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