Open History to see the last commit
1import * as Clock from "effect/Clock";
2import * as Config from "effect/Config";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Schema from "effect/Schema";
9import {
10 NonNegativeInt,
11 TrimmedNonEmptyString,
12 type SourceControlProviderAuth,
13 type SourceControlRepositoryCloneUrls,
14 type SourceControlRepositoryVisibility,
15} from "@t3tools/contracts";
16import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
17import { sanitizeBranchFragment } from "@t3tools/shared/git";
18import {
19 detectSourceControlProviderFromRemoteUrl,
20 isSshRemoteUrl,
21} from "@t3tools/shared/sourceControl";
22
23import {
24 BitbucketPullRequestListSchema,
25 BitbucketPullRequestSchema,
26 normalizeBitbucketPullRequestRecord,
27 type NormalizedBitbucketPullRequestRecord,
28} from "./bitbucketPullRequests.ts";
29import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
30import * as SourceControlProvider from "./SourceControlProvider.ts";
31import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
32import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
33import { retryAtFromHeader } from "./SourceControlRateLimit.ts";
34
35const DEFAULT_API_BASE_URL = "https://api.bitbucket.org/2.0";
36/** A response body past this is cut short, so one huge diff cannot exhaust the server. */
37const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
38/** Bitbucket redirects a diff once; this leaves room without following a chain forever. */
39const MAX_REDIRECTS = 3;
40
41const BitbucketApiEnvConfig = Config.all({
42 baseUrl: Config.String("T3CODE_BITBUCKET_API_BASE_URL").pipe(
43 Config.withDefault(DEFAULT_API_BASE_URL),
44 ),
45 accessToken: Config.String("T3CODE_BITBUCKET_ACCESS_TOKEN").pipe(Config.option),
46 email: Config.String("T3CODE_BITBUCKET_EMAIL").pipe(Config.option),
47 apiToken: Config.String("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
48});
49
50const BitbucketApiOperation = Schema.Literals([
51 "resolveRepository",
52 "getRepository",
53 "getBranchingModel",
54 "getPullRequest",
55 "listPullRequests",
56 "createRepository",
57 "createPullRequest",
58 "probeAuth",
59 "checkoutPullRequest",
60 // The raw escape hatch. Callers name their own operation in their own error, the way the
61 // pull request wrappers do on top of `gh` and `glab`.
62 "request",
63]);
64type BitbucketApiOperation = typeof BitbucketApiOperation.Type;
65
66export class BitbucketRepositoryLocatorError extends Schema.TaggedError<BitbucketRepositoryLocatorError>()(
67 "BitbucketRepositoryLocatorError",
68 {
69 repository: Schema.String,
70 },
71) {
72 get detail(): string {
73 return "Bitbucket repositories must be specified as workspace/repository.";
74 }
75
76 override get message(): string {
77 return `Bitbucket API failed in createRepository: ${this.detail}`;
78 }
79}
80
81export class BitbucketRequestError extends Schema.TaggedError<BitbucketRequestError>()(
82 "BitbucketRequestError",
83 {
84 operation: BitbucketApiOperation,
85 cause: Schema.Defect(),
86 },
87) {
88 get detail(): string {
89 return "Failed to send the Bitbucket request.";
90 }
91
92 override get message(): string {
93 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
94 }
95}
96
97export class BitbucketResponseError extends Schema.TaggedError<BitbucketResponseError>()(
98 "BitbucketResponseError",
99 {
100 operation: BitbucketApiOperation,
101 status: Schema.Int,
102 responseBodyLength: NonNegativeInt,
103 retryAt: Schema.optional(Schema.Number),
104 },
105) {
106 get detail(): string {
107 return `Bitbucket returned HTTP ${this.status}.`;
108 }
109
110 override get message(): string {
111 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
112 }
113}
114
115export class BitbucketResponseBodyReadError extends Schema.TaggedError<BitbucketResponseBodyReadError>()(
116 "BitbucketResponseBodyReadError",
117 {
118 operation: BitbucketApiOperation,
119 status: Schema.Int,
120 retryAt: Schema.optional(Schema.Number),
121 cause: Schema.Defect(),
122 },
123) {
124 get detail(): string {
125 return `Bitbucket returned HTTP ${this.status}.`;
126 }
127
128 override get message(): string {
129 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
130 }
131}
132
133export class BitbucketResponseDecodeError extends Schema.TaggedError<BitbucketResponseDecodeError>()(
134 "BitbucketResponseDecodeError",
135 {
136 operation: BitbucketApiOperation,
137 status: Schema.Int,
138 cause: Schema.Defect(),
139 },
140) {
141 get detail(): string {
142 return "Bitbucket returned invalid JSON for the requested resource.";
143 }
144
145 override get message(): string {
146 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
147 }
148}
149
150export class BitbucketRepositoryVcsResolveError extends Schema.TaggedError<BitbucketRepositoryVcsResolveError>()(
151 "BitbucketRepositoryVcsResolveError",
152 {
153 cwd: Schema.String,
154 cause: Schema.Defect(),
155 },
156) {
157 get detail(): string {
158 return `Failed to resolve VCS repository for ${this.cwd}.`;
159 }
160
161 override get message(): string {
162 return `Bitbucket API failed in resolveRepository: ${this.detail}`;
163 }
164}
165
166export class BitbucketRepositoryRemotesListError extends Schema.TaggedError<BitbucketRepositoryRemotesListError>()(
167 "BitbucketRepositoryRemotesListError",
168 {
169 cwd: Schema.String,
170 cause: Schema.Defect(),
171 },
172) {
173 get detail(): string {
174 return `Failed to list remotes for ${this.cwd}.`;
175 }
176
177 override get message(): string {
178 return `Bitbucket API failed in resolveRepository: ${this.detail}`;
179 }
180}
181
182export class BitbucketRepositoryRemoteNotFoundError extends Schema.TaggedError<BitbucketRepositoryRemoteNotFoundError>()(
183 "BitbucketRepositoryRemoteNotFoundError",
184 {
185 cwd: Schema.String,
186 },
187) {
188 get detail(): string {
189 return `No Bitbucket repository remote was detected for ${this.cwd}.`;
190 }
191
192 override get message(): string {
193 return `Bitbucket API failed in resolveRepository: ${this.detail}`;
194 }
195}
196
197export class BitbucketPullRequestBodyReadError extends Schema.TaggedError<BitbucketPullRequestBodyReadError>()(
198 "BitbucketPullRequestBodyReadError",
199 {
200 cwd: Schema.String,
201 bodyFile: Schema.String,
202 cause: Schema.Defect(),
203 },
204) {
205 get detail(): string {
206 return `Failed to read pull request body file ${this.bodyFile}.`;
207 }
208
209 override get message(): string {
210 return `Bitbucket API failed in createPullRequest: ${this.detail}`;
211 }
212}
213
214export class BitbucketCheckoutError extends Schema.TaggedError<BitbucketCheckoutError>()(
215 "BitbucketCheckoutError",
216 {
217 cwd: Schema.String,
218 reference: Schema.String,
219 cause: Schema.Defect(),
220 },
221) {
222 get detail(): string {
223 return "Failed to check out the Bitbucket pull request.";
224 }
225
226 override get message(): string {
227 return `Bitbucket API failed in checkoutPullRequest: ${this.detail}`;
228 }
229}
230
231/**
232 * A url that does not belong to the configured Bitbucket. Refused rather than followed, because
233 * the request carries the account's credentials and a url that came back in a response — a
234 * pagination cursor, or the target of a redirect — is not this server's to trust.
235 */
236export class BitbucketUntrustedUrlError extends Schema.TaggedError<BitbucketUntrustedUrlError>()(
237 "BitbucketUntrustedUrlError",
238 {
239 /** The host only. A rejected hop is often a signed url, whose query carries a credential. */
240 host: Schema.String,
241 },
242) {
243 get detail(): string {
244 return `The response pointed at ${this.host}, outside the configured Bitbucket.`;
245 }
246
247 override get message(): string {
248 return `Bitbucket API failed in request: ${this.detail}`;
249 }
250}
251
252export const BitbucketApiError = Schema.Union([
253 BitbucketUntrustedUrlError,
254 BitbucketRepositoryLocatorError,
255 BitbucketRequestError,
256 BitbucketResponseError,
257 BitbucketResponseBodyReadError,
258 BitbucketResponseDecodeError,
259 BitbucketRepositoryVcsResolveError,
260 BitbucketRepositoryRemotesListError,
261 BitbucketRepositoryRemoteNotFoundError,
262 BitbucketPullRequestBodyReadError,
263 BitbucketCheckoutError,
264]);
265export type BitbucketApiError = typeof BitbucketApiError.Type;
266const isBitbucketApiError = Schema.is(BitbucketApiError);
267
268const RawBitbucketRepositorySchema = Schema.Struct({
269 full_name: TrimmedNonEmptyString,
270 links: Schema.Struct({
271 html: Schema.optional(
272 Schema.Struct({
273 href: TrimmedNonEmptyString,
274 }),
275 ),
276 clone: Schema.optional(
277 Schema.Array(
278 Schema.Struct({
279 name: TrimmedNonEmptyString,
280 href: TrimmedNonEmptyString,
281 }),
282 ),
283 ),
284 }),
285 mainbranch: Schema.optional(
286 Schema.NullOr(
287 Schema.Struct({
288 name: TrimmedNonEmptyString,
289 }),
290 ),
291 ),
292});
293
294const RawBitbucketBranchingModelSchema = Schema.Struct({
295 development: Schema.optional(
296 Schema.Struct({
297 branch: Schema.optional(
298 Schema.NullOr(
299 Schema.Struct({
300 name: Schema.optional(TrimmedNonEmptyString),
301 }),
302 ),
303 ),
304 is_valid: Schema.optional(Schema.Boolean),
305 name: Schema.optional(Schema.NullOr(Schema.String)),
306 use_mainbranch: Schema.optional(Schema.Boolean),
307 }),
308 ),
309});
310
311const BitbucketUserSchema = Schema.Struct({
312 username: Schema.optional(TrimmedNonEmptyString),
313 display_name: Schema.optional(TrimmedNonEmptyString),
314 account_id: Schema.optional(TrimmedNonEmptyString),
315});
316
317export interface BitbucketRepositoryLocator {
318 readonly workspace: string;
319 readonly repoSlug: string;
320}
321
322export class BitbucketApi extends Context.Service<
323 BitbucketApi,
324 {
325 readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;
326
327 /**
328 * One authenticated request, returning the body verbatim. Bitbucket answers most endpoints
329 * with JSON and a few — a pull request diff, for one — with plain text, so the body is
330 * handed back undecoded for the caller to read as it sees fit.
331 */
332 readonly request: (input: {
333 readonly method: "GET" | "POST" | "PUT" | "DELETE";
334 /**
335 * A path below the API base, or a whole URL as a paged response reports its next page.
336 * A whole URL is refused unless it belongs to the configured Bitbucket.
337 */
338 readonly url: string;
339 /** A JSON document, for the endpoints that take one. */
340 readonly body?: string;
341 /** Response bytes to keep; past this the body comes back cut short and marked. */
342 readonly maxBytes?: number;
343 }) => Effect.Effect<{ readonly body: string; readonly truncated: boolean }, BitbucketApiError>;
344 readonly listPullRequests: (input: {
345 readonly cwd: string;
346 readonly context?: SourceControlProvider.SourceControlProviderContext;
347 readonly headSelector: string;
348 readonly source?: SourceControlProvider.SourceControlRefSelector;
349 readonly state: "open" | "closed" | "merged" | "all";
350 readonly limit?: number;
351 }) => Effect.Effect<ReadonlyArray<NormalizedBitbucketPullRequestRecord>, BitbucketApiError>;
352 readonly getPullRequest: (input: {
353 readonly cwd: string;
354 readonly context?: SourceControlProvider.SourceControlProviderContext;
355 readonly reference: string;
356 }) => Effect.Effect<NormalizedBitbucketPullRequestRecord, BitbucketApiError>;
357 readonly getRepositoryCloneUrls: (input: {
358 readonly cwd: string;
359 readonly context?: SourceControlProvider.SourceControlProviderContext;
360 readonly repository: string;
361 }) => Effect.Effect<SourceControlRepositoryCloneUrls, BitbucketApiError>;
362 readonly createRepository: (input: {
363 readonly cwd: string;
364 readonly repository: string;
365 readonly visibility: SourceControlRepositoryVisibility;
366 }) => Effect.Effect<SourceControlRepositoryCloneUrls, BitbucketApiError>;
367 readonly createPullRequest: (input: {
368 readonly cwd: string;
369 readonly context?: SourceControlProvider.SourceControlProviderContext;
370 readonly baseBranch: string;
371 readonly headSelector: string;
372 readonly source?: SourceControlProvider.SourceControlRefSelector;
373 readonly target?: SourceControlProvider.SourceControlRefSelector;
374 readonly title: string;
375 readonly bodyFile: string;
376 }) => Effect.Effect<void, BitbucketApiError>;
377 readonly getDefaultBranch: (input: {
378 readonly cwd: string;
379 readonly context?: SourceControlProvider.SourceControlProviderContext;
380 }) => Effect.Effect<string | null, BitbucketApiError>;
381 readonly checkoutPullRequest: (input: {
382 readonly cwd: string;
383 readonly context?: SourceControlProvider.SourceControlProviderContext;
384 readonly reference: string;
385 readonly force?: boolean;
386 }) => Effect.Effect<void, BitbucketApiError>;
387 }
388>()("t3/sourceControl/BitbucketApi") {}
389
390function nonEmpty(value: string | undefined): Option.Option<string> {
391 const trimmed = value?.trim();
392 return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);
393}
394
395function normalizeChangeRequestId(reference: string): string {
396 const trimmed = reference.trim().replace(/^#/, "");
397 const urlMatch = /(?:pull-requests|pullrequests|pull-request|pull|pr)\/(\d+)(?:\D.*)?$/i.exec(
398 trimmed,
399 );
400 return urlMatch?.[1] ?? trimmed;
401}
402
403function sourceWorkspace(input: {
404 readonly headSelector: string;
405 readonly source?: SourceControlProvider.SourceControlRefSelector;
406}): string | undefined {
407 if (input.source?.owner) return input.source.owner;
408 return SourceControlProvider.parseSourceControlOwnerRef(input.headSelector)?.owner;
409}
410
411function toBitbucketStates(state: "open" | "closed" | "merged" | "all"): ReadonlyArray<string> {
412 switch (state) {
413 case "open":
414 return ["OPEN"];
415 case "closed":
416 return ["DECLINED", "SUPERSEDED"];
417 case "merged":
418 return ["MERGED"];
419 case "all":
420 return ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"];
421 }
422}
423
424function bitbucketQueryString(filters: ReadonlyArray<string>): string {
425 return filters.join(" AND ");
426}
427
428function bitbucketStateFilter(states: ReadonlyArray<string>): string {
429 return states.length === 1
430 ? `state = "${states[0]}"`
431 : `(${states.map((state) => `state = "${state}"`).join(" OR ")})`;
432}
433
434function parseBitbucketRepositorySlug(value: string): BitbucketRepositoryLocator | null {
435 const normalized = value.trim().replace(/\.git$/u, "");
436 const parts = normalized.split("/").filter((part) => part.length > 0);
437 if (parts.length < 2) return null;
438 const workspace = parts.at(-2);
439 const repoSlug = parts.at(-1);
440 return workspace && repoSlug ? { workspace, repoSlug } : null;
441}
442
443function requireRepositoryLocator(
444 repository: string,
445): Effect.Effect<BitbucketRepositoryLocator, BitbucketApiError> {
446 const locator = parseBitbucketRepositorySlug(repository);
447 return locator
448 ? Effect.succeed(locator)
449 : Effect.fail(
450 new BitbucketRepositoryLocatorError({
451 repository,
452 }),
453 );
454}
455
456function parseBitbucketRemoteUrl(remoteUrl: string): BitbucketRepositoryLocator | null {
457 const trimmed = remoteUrl.trim();
458 const scpMatch = /^[a-zA-Z0-9._-]+@[^:/]+:(.+)$/.exec(trimmed);
459 if (scpMatch?.[1]) {
460 return parseBitbucketRepositorySlug(scpMatch[1]);
461 }
462
463 try {
464 return parseBitbucketRepositorySlug(new URL(trimmed).pathname);
465 } catch {
466 return null;
467 }
468}
469
470function normalizeRepositoryCloneUrls(
471 raw: typeof RawBitbucketRepositorySchema.Type,
472): SourceControlRepositoryCloneUrls {
473 const httpClone =
474 raw.links.clone?.find((entry) => entry.name.toLowerCase() === "https")?.href ??
475 raw.links.html?.href;
476 const sshClone = raw.links.clone?.find((entry) => entry.name.toLowerCase() === "ssh")?.href;
477
478 return {
479 nameWithOwner: raw.full_name,
480 url: httpClone ?? raw.links.html?.href ?? raw.full_name,
481 sshUrl: sshClone ?? httpClone ?? raw.full_name,
482 };
483}
484
485function defaultChangeRequestTargetBranch(input: {
486 readonly repository: typeof RawBitbucketRepositorySchema.Type;
487 readonly branchingModel: typeof RawBitbucketBranchingModelSchema.Type | null;
488}): string | null {
489 const repositoryMainBranch = input.repository.mainbranch?.name ?? null;
490 const development = input.branchingModel?.development;
491 if (!development || development.use_mainbranch === true || development.is_valid === false) {
492 return repositoryMainBranch;
493 }
494
495 const developmentBranch = development.branch?.name?.trim() ?? development.name?.trim() ?? "";
496 if (developmentBranch.length === 0 || developmentBranch === "null") {
497 return repositoryMainBranch;
498 }
499
500 return developmentBranch;
501}
502
503function shouldPreferSshRemote(originRemoteUrl: string | null): boolean {
504 if (!originRemoteUrl) return false;
505 return isSshRemoteUrl(originRemoteUrl);
506}
507
508function selectCloneUrl(input: {
509 readonly cloneUrls: SourceControlRepositoryCloneUrls;
510 readonly originRemoteUrl: string | null;
511}): string {
512 return shouldPreferSshRemote(input.originRemoteUrl)
513 ? input.cloneUrls.sshUrl
514 : input.cloneUrls.url;
515}
516
517function checkoutBranchName(input: {
518 readonly pullRequestId: number;
519 readonly headBranch: string;
520 readonly isCrossRepository: boolean;
521}): string {
522 if (!input.isCrossRepository) {
523 return input.headBranch;
524 }
525
526 return `t3code/pr-${input.pullRequestId}/${sanitizeBranchFragment(input.headBranch)}`;
527}
528
529function repositoryNameWithOwner(
530 repository: Schema.Schema.Type<typeof BitbucketPullRequestSchema>["source"]["repository"],
531): string | null {
532 const fullName = repository?.full_name?.trim() ?? "";
533 return fullName.length > 0 ? fullName : null;
534}
535
536function repositoryOwnerName(repositoryName: string): string {
537 return repositoryName.split("/")[0]?.trim() || "bitbucket";
538}
539
540function authFromConfig(
541 config: Config.Success<typeof BitbucketApiEnvConfig>,
542): SourceControlProviderAuth {
543 if (Option.isSome(config.accessToken)) {
544 return {
545 status: "unknown",
546 account: Option.none(),
547 host: Option.some("bitbucket.org"),
548 detail: Option.some("Bitbucket access token is configured."),
549 };
550 }
551
552 if (Option.isSome(config.email) && Option.isSome(config.apiToken)) {
553 return {
554 status: "unknown",
555 account: config.email,
556 host: Option.some("bitbucket.org"),
557 detail: Option.some("Bitbucket API token is configured."),
558 };
559 }
560
561 return {
562 status: "unauthenticated",
563 account: Option.none(),
564 host: Option.some("bitbucket.org"),
565 detail: Option.some(
566 "Set T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN, or T3CODE_BITBUCKET_ACCESS_TOKEN.",
567 ),
568 };
569}
570
571/** Null for anything that is not a url at all, which is never the configured Bitbucket. */
572function originOf(value: string): string | null {
573 try {
574 return new URL(value).origin;
575 } catch {
576 return null;
577 }
578}
579
580function responseError(
581 operation: BitbucketApiOperation,
582 response: HttpClientResponse.HttpClientResponse,
583): Effect.Effect<never, BitbucketApiError> {
584 // Bounded like any other body: an error response is no smaller than a successful one, and
585 // only its length is reported anyway.
586 return Effect.gen(function* () {
587 const now = yield* Clock.currentTimeMillis;
588 const retryAt = retryAtFromHeader(response.headers["retry-after"], now);
589 const collected = yield* collectUint8StreamText({
590 stream: response.stream,
591 maxBytes: DEFAULT_MAX_RESPONSE_BYTES,
592 }).pipe(
593 Effect.mapError(
594 (cause) =>
595 new BitbucketResponseBodyReadError({
596 operation,
597 status: response.status,
598 retryAt,
599 cause,
600 }),
601 ),
602 );
603 return yield* new BitbucketResponseError({
604 operation,
605 status: response.status,
606 responseBodyLength: collected.text.length,
607 retryAt,
608 });
609 });
610}
611
612/** @public Service construction is part of the canonical Effect module API. */
613export const make = Effect.gen(function* () {
614 const config = yield* BitbucketApiEnvConfig;
615 const httpClient = yield* HttpClient.HttpClient;
616 const fileSystem = yield* FileSystem.FileSystem;
617 const git = yield* GitVcsDriver.GitVcsDriver;
618 const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
619
620 const apiUrl = (path: string) => `${config.baseUrl.replace(/\/+$/u, "")}${path}`;
621
622 const withAuth = (request: HttpClientRequest.HttpClientRequest) => {
623 if (Option.isSome(config.accessToken)) {
624 return request.pipe(HttpClientRequest.bearerToken(config.accessToken.value));
625 }
626 if (Option.isSome(config.email) && Option.isSome(config.apiToken)) {
627 return request.pipe(HttpClientRequest.basicAuth(config.email.value, config.apiToken.value));
628 }
629 return request;
630 };
631
632 const decodeResponse = <S extends Schema.Top>(
633 operation: BitbucketApiOperation,
634 schema: S,
635 response: HttpClientResponse.HttpClientResponse,
636 ): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
637 HttpClientResponse.matchStatus({
638 "2xx": (success) =>
639 HttpClientResponse.schemaBodyJson(schema)(success).pipe(
640 Effect.mapError(
641 (cause) =>
642 new BitbucketResponseDecodeError({
643 operation,
644 status: success.status,
645 cause,
646 }),
647 ),
648 ),
649 orElse: (failed) => responseError(operation, failed),
650 })(response);
651
652 const executeJson = <S extends Schema.Top>(
653 operation: BitbucketApiOperation,
654 request: HttpClientRequest.HttpClientRequest,
655 schema: S,
656 ): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
657 httpClient.execute(withAuth(request.pipe(HttpClientRequest.acceptJson))).pipe(
658 Effect.mapError(
659 (cause) =>
660 new BitbucketRequestError({
661 operation,
662 cause,
663 }),
664 ),
665 Effect.flatMap((response) => decodeResponse(operation, schema, response)),
666 );
667
668 const resolveRepository = Effect.fn("BitbucketApi.resolveRepository")(function* (input: {
669 readonly cwd: string;
670 readonly context?: SourceControlProvider.SourceControlProviderContext;
671 readonly repository?: string;
672 }) {
673 const fromRepository =
674 input.repository !== undefined ? parseBitbucketRepositorySlug(input.repository) : null;
675 if (fromRepository) return fromRepository;
676
677 const fromContext =
678 input.context?.provider.kind === "bitbucket"
679 ? parseBitbucketRemoteUrl(input.context.remoteUrl)
680 : null;
681 if (fromContext) return fromContext;
682
683 const handle = yield* vcsRegistry.resolve({ cwd: input.cwd }).pipe(
684 Effect.mapError(
685 (cause) =>
686 new BitbucketRepositoryVcsResolveError({
687 cwd: input.cwd,
688 cause,
689 }),
690 ),
691 );
692 const remotes = yield* handle.driver.listRemotes(input.cwd).pipe(
693 Effect.mapError(
694 (cause) =>
695 new BitbucketRepositoryRemotesListError({
696 cwd: input.cwd,
697 cause,
698 }),
699 ),
700 );
701
702 for (const remote of remotes.remotes) {
703 if (detectSourceControlProviderFromRemoteUrl(remote.url)?.kind !== "bitbucket") continue;
704 const parsed = parseBitbucketRemoteUrl(remote.url);
705 if (parsed) return parsed;
706 }
707
708 return yield* new BitbucketRepositoryRemoteNotFoundError({
709 cwd: input.cwd,
710 });
711 });
712
713 const getRepositoryFromLocator = (repository: BitbucketRepositoryLocator) =>
714 executeJson(
715 "getRepository",
716 HttpClientRequest.get(
717 apiUrl(
718 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
719 ),
720 ),
721 RawBitbucketRepositorySchema,
722 );
723
724 const getRepository = (input: {
725 readonly cwd: string;
726 readonly context?: SourceControlProvider.SourceControlProviderContext;
727 readonly repository?: string;
728 }) => resolveRepository(input).pipe(Effect.flatMap(getRepositoryFromLocator));
729
730 const getBranchingModelFromLocator = (repository: BitbucketRepositoryLocator) =>
731 executeJson(
732 "getBranchingModel",
733 HttpClientRequest.get(
734 apiUrl(
735 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/branching-model`,
736 ),
737 ),
738 RawBitbucketBranchingModelSchema,
739 );
740
741 const getRawPullRequestFromRepository = (
742 repository: BitbucketRepositoryLocator,
743 reference: string,
744 ) =>
745 executeJson(
746 "getPullRequest",
747 HttpClientRequest.get(
748 apiUrl(
749 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests/${encodeURIComponent(normalizeChangeRequestId(reference))}`,
750 ),
751 ),
752 BitbucketPullRequestSchema,
753 );
754
755 const getRawPullRequest = (input: {
756 readonly cwd: string;
757 readonly context?: SourceControlProvider.SourceControlProviderContext;
758 readonly reference: string;
759 }) =>
760 resolveRepository(input).pipe(
761 Effect.flatMap((repository) => getRawPullRequestFromRepository(repository, input.reference)),
762 );
763
764 const readConfigValueNullable = (cwd: string, key: string) =>
765 git.readConfigValue(cwd, key).pipe(Effect.orElseSucceed(() => null));
766
767 const resolveCheckoutRemote = Effect.fn("BitbucketApi.resolveCheckoutRemote")(function* (input: {
768 readonly cwd: string;
769 readonly context?: SourceControlProvider.SourceControlProviderContext;
770 readonly destinationRepository: BitbucketRepositoryLocator;
771 readonly sourceRepositoryName: string;
772 readonly isCrossRepository: boolean;
773 }) {
774 if (
775 input.context?.provider.kind === "bitbucket" &&
776 !input.isCrossRepository &&
777 parseBitbucketRemoteUrl(input.context.remoteUrl) !== null
778 ) {
779 return input.context.remoteName;
780 }
781
782 if (!input.isCrossRepository) {
783 const remoteName = yield* git
784 .resolvePrimaryRemoteName(input.cwd)
785 .pipe(Effect.orElseSucceed(() => null));
786 if (remoteName) return remoteName;
787 }
788
789 const cloneUrls = yield* getRepository({
790 cwd: input.cwd,
791 repository: input.sourceRepositoryName,
792 ...(input.context ? { context: input.context } : {}),
793 }).pipe(Effect.map(normalizeRepositoryCloneUrls));
794 const originRemoteUrl = yield* readConfigValueNullable(input.cwd, "remote.origin.url");
795 return yield* git.ensureRemote({
796 cwd: input.cwd,
797 preferredName: input.isCrossRepository
798 ? repositoryOwnerName(input.sourceRepositoryName)
799 : input.destinationRepository.workspace,
800 url: selectCloneUrl({ cloneUrls, originRemoteUrl }),
801 });
802 });
803
804 // A pull request's diff, diffstat and conflicts are served as redirects to a commit-range
805 // URL, and the client does not follow redirects unless asked. The hop stays on the same host,
806 // so the credentials travel with it.
807 /**
808 * The one host these credentials may be sent to. A url that came back inside a response — a
809 * pagination cursor, or the target of a redirect — is data, not instruction, so it is checked
810 * against this before the account's token travels with it.
811 */
812 const apiOrigin = originOf(config.baseUrl);
813
814 const trustedUrl = (value: string): string | null => {
815 if (!/^https?:\/\//u.test(value)) return apiUrl(value);
816 const origin = originOf(value);
817 return origin !== null && origin === apiOrigin ? value : null;
818 };
819
820 /**
821 * Redirects are followed here rather than by the client, which forwards every header to
822 * whatever host it is sent to. A pull request diff, diffstat and conflicts are all served as
823 * redirects, so they have to be followed — but only back to the same Bitbucket.
824 */
825 const send = (input: {
826 readonly method: "GET" | "POST" | "PUT" | "DELETE";
827 readonly url: string;
828 readonly body?: string;
829 readonly redirects: number;
830 }): Effect.Effect<HttpClientResponse.HttpClientResponse, BitbucketApiError> => {
831 const url = trustedUrl(input.url);
832 if (url === null) {
833 return Effect.fail(
834 new BitbucketUntrustedUrlError({ host: originOf(input.url) ?? "an unreadable url" }),
835 );
836 }
837 const base =
838 input.method === "GET"
839 ? HttpClientRequest.get(url)
840 : input.method === "POST"
841 ? HttpClientRequest.post(url)
842 : input.method === "DELETE"
843 ? HttpClientRequest.make("DELETE")(url)
844 : HttpClientRequest.put(url);
845 // No `Accept: application/json`: the diff endpoints answer with a patch, not JSON.
846 const withBody =
847 input.body === undefined
848 ? base
849 : base.pipe(HttpClientRequest.bodyText(input.body, "application/json"));
850 return httpClient.execute(withAuth(withBody)).pipe(
851 Effect.mapError(
852 (cause): BitbucketApiError => new BitbucketRequestError({ operation: "request", cause }),
853 ),
854 Effect.flatMap((response) => {
855 const location = response.headers.location;
856 if (
857 response.status >= 300 &&
858 response.status < 400 &&
859 location !== undefined &&
860 input.redirects < MAX_REDIRECTS
861 ) {
862 return send({
863 ...input,
864 url: new URL(location, url).toString(),
865 redirects: input.redirects + 1,
866 });
867 }
868 return Effect.succeed(response);
869 }),
870 );
871 };
872
873 const request: BitbucketApi["Service"]["request"] = (input) =>
874 send({ ...input, redirects: 0 }).pipe(
875 Effect.flatMap((response) =>
876 HttpClientResponse.matchStatus({
877 // Read through the body stream rather than `text`, so an oversized diff is stopped
878 // as it arrives instead of being materialized whole and then cut. The same collector
879 // the process runner bounds command output with.
880 "2xx": (success) =>
881 collectUint8StreamText({
882 stream: success.stream,
883 maxBytes: input.maxBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
884 }).pipe(
885 Effect.mapError(
886 (cause) =>
887 new BitbucketResponseBodyReadError({
888 operation: "request",
889 status: success.status,
890 cause,
891 }),
892 ),
893 Effect.map((collected) => ({
894 body: collected.text,
895 truncated: collected.truncated,
896 })),
897 ),
898 orElse: (failed) => responseError("request", failed),
899 })(response),
900 ),
901 );
902
903 return BitbucketApi.of({
904 request,
905 probeAuth: executeJson(
906 "probeAuth",
907 HttpClientRequest.get(apiUrl("/user")),
908 BitbucketUserSchema,
909 ).pipe(
910 Effect.map((user) => ({
911 status: "authenticated" as const,
912 account: nonEmpty(user.username ?? user.display_name ?? user.account_id),
913 host: Option.some("bitbucket.org"),
914 detail: Option.none<string>(),
915 })),
916 Effect.orElseSucceed(() => authFromConfig(config)),
917 ),
918 listPullRequests: (input) =>
919 resolveRepository(input).pipe(
920 Effect.flatMap((repository) => {
921 const states = toBitbucketStates(input.state);
922 const query: Record<string, string | ReadonlyArray<string>> = {
923 pagelen: String(Math.max(1, Math.min(input.limit ?? 20, 50))),
924 sort: "-updated_on",
925 q: bitbucketQueryString([
926 `source.branch.name = "${SourceControlProvider.sourceBranch(input).replaceAll('"', '\\"')}"`,
927 bitbucketStateFilter(states),
928 ]),
929 state: states,
930 };
931
932 return executeJson(
933 "listPullRequests",
934 HttpClientRequest.get(
935 apiUrl(
936 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
937 ),
938 { urlParams: query },
939 ),
940 BitbucketPullRequestListSchema,
941 );
942 }),
943 Effect.map((list) => list.values.map(normalizeBitbucketPullRequestRecord)),
944 ),
945 getPullRequest: (input) =>
946 getRawPullRequest(input).pipe(Effect.map(normalizeBitbucketPullRequestRecord)),
947 getRepositoryCloneUrls: (input) =>
948 getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls)),
949 createRepository: (input) =>
950 requireRepositoryLocator(input.repository).pipe(
951 Effect.flatMap((repository) =>
952 executeJson(
953 "createRepository",
954 HttpClientRequest.post(
955 apiUrl(
956 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
957 ),
958 ).pipe(
959 HttpClientRequest.bodyJsonUnsafe({
960 scm: "git",
961 is_private: input.visibility === "private",
962 }),
963 ),
964 RawBitbucketRepositorySchema,
965 ),
966 ),
967 Effect.map(normalizeRepositoryCloneUrls),
968 ),
969 createPullRequest: (input) =>
970 Effect.gen(function* () {
971 const repository = yield* resolveRepository(input);
972 const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
973 Effect.mapError(
974 (cause) =>
975 new BitbucketPullRequestBodyReadError({
976 cwd: input.cwd,
977 bodyFile: input.bodyFile,
978 cause,
979 }),
980 ),
981 );
982 const sourceOwner = sourceWorkspace(input);
983 const body = {
984 title: input.title,
985 description,
986 source: {
987 branch: {
988 name: SourceControlProvider.sourceBranch(input),
989 },
990 ...(sourceOwner
991 ? {
992 repository: {
993 full_name: `${sourceOwner}/${input.source?.repository ?? repository.repoSlug}`,
994 },
995 }
996 : {}),
997 },
998 destination: {
999 branch: {
1000 name: input.target?.refName ?? input.baseBranch,
1001 },
1002 },
1003 };
1004
1005 yield* executeJson(
1006 "createPullRequest",
1007 HttpClientRequest.post(
1008 apiUrl(
1009 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
1010 ),
1011 ).pipe(HttpClientRequest.bodyJsonUnsafe(body)),
1012 BitbucketPullRequestSchema,
1013 );
1014 }),
1015 getDefaultBranch: (input) =>
1016 resolveRepository(input).pipe(
1017 Effect.flatMap((locator) =>
1018 Effect.all(
1019 {
1020 repository: getRepositoryFromLocator(locator),
1021 branchingModel: getBranchingModelFromLocator(locator).pipe(
1022 Effect.orElseSucceed(
1023 (): typeof RawBitbucketBranchingModelSchema.Type | null => null,
1024 ),
1025 ),
1026 },
1027 { concurrency: "unbounded" },
1028 ),
1029 ),
1030 Effect.map(defaultChangeRequestTargetBranch),
1031 ),
1032 // Bitbucket Cloud pull requests are Git-backed and Bitbucket does not provide
1033 // an official checkout CLI. This provider-local path uses GitVcsDriver as a
1034 // narrow escape hatch to materialize Bitbucket PR refs. Do not generalize this
1035 // as the source-control provider model: if we support non-Git-compatible
1036 // hosting providers or native JJ/Sapling checkout flows, move this into a
1037 // VCS-specific change-request checkout capability.
1038 checkoutPullRequest: (input) =>
1039 Effect.gen(function* () {
1040 const destinationRepository = yield* resolveRepository(input);
1041 const pullRequest = yield* getRawPullRequestFromRepository(
1042 destinationRepository,
1043 input.reference,
1044 );
1045 const destinationRepositoryName =
1046 repositoryNameWithOwner(pullRequest.destination.repository) ??
1047 `${destinationRepository.workspace}/${destinationRepository.repoSlug}`;
1048 const sourceRepositoryName =
1049 repositoryNameWithOwner(pullRequest.source.repository) ?? destinationRepositoryName;
1050 const isCrossRepository = sourceRepositoryName !== destinationRepositoryName;
1051 const remoteName = yield* resolveCheckoutRemote({
1052 cwd: input.cwd,
1053 destinationRepository,
1054 sourceRepositoryName,
1055 isCrossRepository,
1056 ...(input.context ? { context: input.context } : {}),
1057 });
1058 const remoteBranch = pullRequest.source.branch.name;
1059 const localBranch = checkoutBranchName({
1060 pullRequestId: pullRequest.id,
1061 headBranch: remoteBranch,
1062 isCrossRepository,
1063 });
1064 const localBranchNames = yield* git.listLocalBranchNames(input.cwd);
1065 const localBranchExists = localBranchNames.includes(localBranch);
1066
1067 if (input.force === true || !localBranchExists) {
1068 yield* git.fetchRemoteBranch({
1069 cwd: input.cwd,
1070 remoteName,
1071 remoteBranch,
1072 localBranch,
1073 });
1074 } else {
1075 yield* git.fetchRemoteTrackingBranch({
1076 cwd: input.cwd,
1077 remoteName,
1078 remoteBranch,
1079 });
1080 }
1081
1082 yield* git.setBranchUpstream({
1083 cwd: input.cwd,
1084 branch: localBranch,
1085 remoteName,
1086 remoteBranch,
1087 });
1088 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
1089 }).pipe(
1090 Effect.mapError((cause) =>
1091 isBitbucketApiError(cause)
1092 ? cause
1093 : new BitbucketCheckoutError({
1094 cwd: input.cwd,
1095 reference: input.reference,
1096 cause,
1097 }),
1098 ),
1099 ),
1100 });
1101});
1102
1103export const layer = Layer.effect(BitbucketApi, make);