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