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