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 * as Semaphore from "effect/Semaphore";
10import {
11 NonNegativeInt,
12 settingsSecretLiteral,
13 SourceControlProviderKind,
14 TrimmedNonEmptyString,
15 type SourceControlProviderAuth,
16 type SourceControlProviderInfo,
17 type SourceControlRepositoryCloneUrls,
18 type SourceControlRepositoryVisibility,
19} from "@t3tools/contracts";
20import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
21import { sanitizeBranchFragment } from "@t3tools/shared/git";
22import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
23import { recognizeRemoteWith } from "@t3tools/source-control-core/shared/definition";
24import { definition } from "../shared/definition.ts";
25
26import {
27 BitbucketPullRequestListSchema,
28 BitbucketPullRequestSchema,
29 normalizeBitbucketPullRequestRecord,
30 type NormalizedBitbucketPullRequestRecord,
31} from "./bitbucketPullRequests.ts";
32import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
33import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
34import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
35import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition";
36
37import * as BitbucketClient from "../shared/definition.ts";
38import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
39
40const DEFAULT_API_BASE_URL = "https://api.bitbucket.org/2.0";
41const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
42const MAX_REDIRECTS = 3;
43const BITBUCKET_API_REQUEST_TIMEOUT = "30 seconds";
44/** A sweep over many branches would otherwise reach Bitbucket as one burst of lookups. */
45const CONCURRENCY = 4;
46
47const BitbucketApiEnvConfig = Config.all({
48 baseUrl: Config.String("T3CODE_BITBUCKET_API_BASE_URL").pipe(
49 Config.withDefault(DEFAULT_API_BASE_URL),
50 ),
51 accessToken: Config.String("T3CODE_BITBUCKET_ACCESS_TOKEN").pipe(Config.option),
52 email: Config.String("T3CODE_BITBUCKET_EMAIL").pipe(Config.option),
53 apiToken: Config.String("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
54});
55
56// Server and Data Center use a different API; a custom Cloud endpoint must be explicit.
57export const BitbucketServesHost = Config.String("T3CODE_BITBUCKET_API_BASE_URL").pipe(
58 Config.option,
59 Config.map(
60 (baseUrl) => (host: string) =>
61 Option.isSome(baseUrl) || host === "bitbucket.org" || host.endsWith(".bitbucket.org"),
62 ),
63);
64
65const BitbucketApiOperation = Schema.Literals([
66 "resolveRepository",
67 "getRepository",
68 "getBranchingModel",
69 "getPullRequest",
70 "listPullRequests",
71 "createRepository",
72 "createPullRequest",
73 "probeAuth",
74 "checkoutPullRequest",
75 "request",
76]);
77type BitbucketApiOperation = typeof BitbucketApiOperation.Type;
78
79export class BitbucketRepositoryLocatorError extends Schema.TaggedError<BitbucketRepositoryLocatorError>()(
80 "BitbucketRepositoryLocatorError",
81 {
82 repository: Schema.String,
83 },
84) {
85 static readonly detail = "Bitbucket repositories must be specified as workspace/repository.";
86
87 get detail(): string {
88 return BitbucketRepositoryLocatorError.detail;
89 }
90
91 get userFacingDetail(): string {
92 return BitbucketRepositoryLocatorError.detail;
93 }
94
95 override get message(): string {
96 return `Bitbucket API failed: ${this.detail}`;
97 }
98}
99
100export class BitbucketRequestError extends Schema.TaggedError<BitbucketRequestError>()(
101 "BitbucketRequestError",
102 {
103 operation: BitbucketApiOperation,
104 cause: Schema.Defect(),
105 },
106) {
107 get detail(): string {
108 return "Failed to send the Bitbucket request.";
109 }
110
111 override get message(): string {
112 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
113 }
114}
115
116export class BitbucketResponseError extends Schema.TaggedError<BitbucketResponseError>()(
117 "BitbucketResponseError",
118 {
119 operation: BitbucketApiOperation,
120 status: Schema.Int,
121 responseBodyLength: NonNegativeInt,
122 retryAt: Schema.optional(Schema.Number),
123 },
124) {
125 get detail(): string {
126 return `Bitbucket returned HTTP ${this.status}.`;
127 }
128
129 override get message(): string {
130 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
131 }
132}
133
134export class BitbucketResponseBodyReadError extends Schema.TaggedError<BitbucketResponseBodyReadError>()(
135 "BitbucketResponseBodyReadError",
136 {
137 operation: BitbucketApiOperation,
138 status: Schema.Int,
139 retryAt: Schema.optional(Schema.Number),
140 cause: Schema.Defect(),
141 },
142) {
143 get detail(): string {
144 return `Bitbucket returned HTTP ${this.status}.`;
145 }
146
147 override get message(): string {
148 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
149 }
150}
151
152export class BitbucketResponseDecodeError extends Schema.TaggedError<BitbucketResponseDecodeError>()(
153 "BitbucketResponseDecodeError",
154 {
155 operation: BitbucketApiOperation,
156 status: Schema.Int,
157 cause: Schema.Defect(),
158 },
159) {
160 get detail(): string {
161 return "Bitbucket returned invalid JSON for the requested resource.";
162 }
163
164 override get message(): string {
165 return `Bitbucket API failed in ${this.operation}: ${this.detail}`;
166 }
167}
168
169export class BitbucketRepositoryVcsResolveError extends Schema.TaggedError<BitbucketRepositoryVcsResolveError>()(
170 "BitbucketRepositoryVcsResolveError",
171 {
172 cwd: Schema.String,
173 cause: Schema.Defect(),
174 },
175) {
176 get detail(): string {
177 return `Failed to resolve VCS repository for ${this.cwd}.`;
178 }
179
180 override get message(): string {
181 return `Bitbucket API failed in resolveRepository: ${this.detail}`;
182 }
183}
184
185export class BitbucketRepositoryRemotesListError extends Schema.TaggedError<BitbucketRepositoryRemotesListError>()(
186 "BitbucketRepositoryRemotesListError",
187 {
188 cwd: Schema.String,
189 cause: Schema.Defect(),
190 },
191) {
192 get detail(): string {
193 return `Failed to list remotes for ${this.cwd}.`;
194 }
195
196 override get message(): string {
197 return `Bitbucket API failed in resolveRepository: ${this.detail}`;
198 }
199}
200
201export class BitbucketRepositoryRemoteNotFoundError extends Schema.TaggedError<BitbucketRepositoryRemoteNotFoundError>()(
202 "BitbucketRepositoryRemoteNotFoundError",
203 {
204 cwd: Schema.String,
205 },
206) {
207 get detail(): string {
208 return `No Bitbucket repository remote was detected for ${this.cwd}.`;
209 }
210
211 override get message(): string {
212 return `Bitbucket API failed in resolveRepository: ${this.detail}`;
213 }
214}
215
216export class BitbucketPullRequestBodyReadError extends Schema.TaggedError<BitbucketPullRequestBodyReadError>()(
217 "BitbucketPullRequestBodyReadError",
218 {
219 cwd: Schema.String,
220 bodyFile: Schema.String,
221 cause: Schema.Defect(),
222 },
223) {
224 get detail(): string {
225 return `Failed to read pull request body file ${this.bodyFile}.`;
226 }
227
228 override get message(): string {
229 return `Bitbucket API failed in createPullRequest: ${this.detail}`;
230 }
231}
232
233export class BitbucketCheckoutError extends Schema.TaggedError<BitbucketCheckoutError>()(
234 "BitbucketCheckoutError",
235 {
236 cwd: Schema.String,
237 reference: Schema.String,
238 cause: Schema.Defect(),
239 },
240) {
241 get detail(): string {
242 return "Failed to check out the Bitbucket pull request.";
243 }
244
245 override get message(): string {
246 return `Bitbucket API failed in checkoutPullRequest: ${this.detail}`;
247 }
248}
249
250/** Reject response-supplied URLs that could leak credentials. */
251export class BitbucketUntrustedUrlError extends Schema.TaggedError<BitbucketUntrustedUrlError>()(
252 "BitbucketUntrustedUrlError",
253 {
254 /** Host only; signed URL queries can contain credentials. */
255 host: Schema.String,
256 },
257) {
258 get detail(): string {
259 return `The response pointed at ${this.host}, outside the configured Bitbucket.`;
260 }
261
262 override get message(): string {
263 return `Bitbucket API failed in request: ${this.detail}`;
264 }
265}
266
267export const BitbucketApiError = Schema.Union([
268 BitbucketUntrustedUrlError,
269 BitbucketRepositoryLocatorError,
270 BitbucketRequestError,
271 BitbucketResponseError,
272 BitbucketResponseBodyReadError,
273 BitbucketResponseDecodeError,
274 BitbucketRepositoryVcsResolveError,
275 BitbucketRepositoryRemotesListError,
276 BitbucketRepositoryRemoteNotFoundError,
277 BitbucketPullRequestBodyReadError,
278 BitbucketCheckoutError,
279 SourceControlRateLimit.SourceControlRateLimitPausedError,
280]);
281export type BitbucketApiError = typeof BitbucketApiError.Type;
282const isBitbucketApiError = Schema.is(BitbucketApiError);
283
284const RawBitbucketRepositorySchema = Schema.Struct({
285 full_name: TrimmedNonEmptyString,
286 links: Schema.Struct({
287 html: Schema.optional(
288 Schema.Struct({
289 href: TrimmedNonEmptyString,
290 }),
291 ),
292 clone: Schema.optional(
293 Schema.Array(
294 Schema.Struct({
295 name: TrimmedNonEmptyString,
296 href: TrimmedNonEmptyString,
297 }),
298 ),
299 ),
300 }),
301 mainbranch: Schema.optional(
302 Schema.NullOr(
303 Schema.Struct({
304 name: TrimmedNonEmptyString,
305 }),
306 ),
307 ),
308});
309
310const RawBitbucketBranchingModelSchema = Schema.Struct({
311 development: Schema.optional(
312 Schema.Struct({
313 branch: Schema.optional(
314 Schema.NullOr(
315 Schema.Struct({
316 name: Schema.optional(TrimmedNonEmptyString),
317 }),
318 ),
319 ),
320 is_valid: Schema.optional(Schema.Boolean),
321 name: Schema.optional(Schema.NullOr(Schema.String)),
322 use_mainbranch: Schema.optional(Schema.Boolean),
323 }),
324 ),
325});
326
327const BitbucketUserSchema = Schema.Struct({
328 username: Schema.optional(TrimmedNonEmptyString),
329 display_name: Schema.optional(TrimmedNonEmptyString),
330 account_id: Schema.optional(TrimmedNonEmptyString),
331});
332
333export interface BitbucketRepositoryLocator {
334 readonly workspace: string;
335 readonly repoSlug: string;
336}
337
338export class BitbucketApi extends Context.Service<
339 BitbucketApi,
340 {
341 readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;
342
343 readonly request: (input: {
344 readonly method: "GET" | "POST" | "PUT" | "DELETE";
345 readonly url: string;
346 readonly body?: string;
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>()("@t3tools/source-control-bitbucket/server/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/** Invalid header values can throw errors containing credentials; treat them as unset. */
550const HEADER_SAFE = /^[\x21-\x7e]+$/u;
551
552function credentialFrom(input: {
553 readonly accessToken: string;
554 readonly email: string;
555 readonly apiToken: string;
556}): BitbucketCredential | null {
557 if (HEADER_SAFE.test(input.accessToken)) {
558 return { kind: "access-token", accessToken: input.accessToken };
559 }
560 if (HEADER_SAFE.test(input.email) && HEADER_SAFE.test(input.apiToken)) {
561 return { kind: "api-token", email: input.email, apiToken: input.apiToken };
562 }
563 return null;
564}
565
566function resolveCredential(
567 settings: BitbucketClient.BitbucketSettings,
568 env: Config.Success<typeof BitbucketApiEnvConfig>,
569): BitbucketCredential | null {
570 return (
571 credentialFrom({
572 accessToken: settingsSecretLiteral(settings.accessToken),
573 email: settings.email,
574 apiToken: settingsSecretLiteral(settings.apiToken),
575 }) ??
576 credentialFrom({
577 accessToken: Option.getOrElse(env.accessToken, () => ""),
578 email: Option.getOrElse(env.email, () => ""),
579 apiToken: Option.getOrElse(env.apiToken, () => ""),
580 })
581 );
582}
583
584function authFromCredential(credential: BitbucketCredential | null): SourceControlProviderAuth {
585 if (credential?.kind === "access-token") {
586 return {
587 status: "unknown",
588 account: Option.none(),
589 host: Option.some("bitbucket.org"),
590 detail: Option.some("An access token is configured."),
591 };
592 }
593
594 if (credential?.kind === "api-token") {
595 return {
596 status: "unknown",
597 account: Option.some(credential.email),
598 host: Option.some("bitbucket.org"),
599 detail: Option.some("An API token is configured."),
600 };
601 }
602
603 return {
604 status: "unauthenticated",
605 account: Option.none(),
606 host: Option.some("bitbucket.org"),
607 detail: Option.some(
608 "Add a Bitbucket token in Settings → Source Control, or set the T3CODE_BITBUCKET_* environment variables on the server.",
609 ),
610 };
611}
612
613function originOf(value: string): string | null {
614 try {
615 return new URL(value).origin;
616 } catch {
617 return null;
618 }
619}
620
621const responseError = Effect.fn("BitbucketApi.responseError")(function* (
622 operation: BitbucketApiOperation,
623 response: HttpClientResponse.HttpClientResponse,
624): Effect.fn.Return<never, BitbucketApiError> {
625 const now = yield* Clock.currentTimeMillis;
626 const retryAt = SourceControlRateLimit.retryAtFromHeader(response.headers["retry-after"], now);
627 const collected = yield* collectUint8StreamText({
628 stream: response.stream,
629 maxBytes: DEFAULT_MAX_RESPONSE_BYTES,
630 }).pipe(
631 Effect.mapError(
632 (cause) =>
633 new BitbucketResponseBodyReadError({
634 operation,
635 status: response.status,
636 retryAt,
637 cause,
638 }),
639 ),
640 );
641 return yield* new BitbucketResponseError({
642 operation,
643 status: response.status,
644 responseBodyLength: collected.text.length,
645 retryAt,
646 });
647});
648
649/** @public */
650export const make = Effect.gen(function* () {
651 const config = yield* BitbucketApiEnvConfig;
652 const host = yield* SourceControlHost.SourceControlHost;
653 const git = host.git;
654 const httpClient = yield* HttpClient.HttpClient;
655 const fileSystem = yield* FileSystem.FileSystem;
656 const limits = yield* SourceControlRateLimit.SourceControlRateLimit;
657 const slots = yield* Semaphore.make(CONCURRENCY);
658 // The repository host PullRequestService keys its own backoff under, so both share one pause.
659 const rateLimitKey = {
660 provider: SourceControlProviderKind.make("bitbucket"),
661 host: "bitbucket.org",
662 };
663
664 const servesHost = yield* BitbucketServesHost;
665
666 const servesProvider = (provider: SourceControlProviderInfo | null) =>
667 provider?.kind === "bitbucket" && servesHost(URL.parse(provider.baseUrl)?.hostname ?? "");
668
669 const apiUrl = (path: string) => `${config.baseUrl.replace(/\/+$/u, "")}${path}`;
670
671 const currentCredential = host.settings.getWithSecrets(BitbucketClient.definition.kind).pipe(
672 Effect.map((settings) =>
673 resolveCredential(
674 readSourceControlHostSettings(
675 BitbucketClient.settings,
676 settings.sourceControlHosts[BitbucketClient.definition.kind],
677 ),
678 config,
679 ),
680 ),
681 Effect.catch((error) =>
682 // No cause: a settings decode error can quote a hand-edited token.
683 Effect.logWarning("failed to read Bitbucket credentials from settings", {
684 operation: error.operation,
685 }).pipe(
686 Effect.as(
687 resolveCredential(readSourceControlHostSettings(BitbucketClient.settings, {}), config),
688 ),
689 ),
690 ),
691 );
692
693 const withAuth = (request: HttpClientRequest.HttpClientRequest) =>
694 currentCredential.pipe(
695 Effect.map((credential) =>
696 credential === null
697 ? request
698 : credential.kind === "access-token"
699 ? request.pipe(HttpClientRequest.bearerToken(credential.accessToken))
700 : request.pipe(HttpClientRequest.basicAuth(credential.email, credential.apiToken)),
701 ),
702 );
703
704 /**
705 * Every request waits for one of the shared slots, then honors the pause a 429 starts for the
706 * whole host. Each queued lookup would otherwise spend its own 429 and keep the quota exhausted.
707 * Background reads fail at once while paused; a write or an interactive read has a user waiting
708 * on it, so it still goes out.
709 */
710 const throttled = Effect.fn("BitbucketApi.throttled")(
711 function* <A, R>(method: string, effect: Effect.Effect<A, BitbucketApiError, R>) {
712 const interactive = yield* SourceControlRateLimit.Interactive;
713 const lease = yield* limits.check(
714 rateLimitKey,
715 interactive || method !== "GET" ? { allowPaused: true } : undefined,
716 );
717 return yield* effect.pipe(
718 Effect.tap(() => limits.recordSuccess({ ...rateLimitKey, lease })),
719 Effect.tapError((error) =>
720 (error._tag === "BitbucketResponseError" ||
721 error._tag === "BitbucketResponseBodyReadError") &&
722 error.status === 429
723 ? limits.recordRateLimit({ ...rateLimitKey, lease, retryAt: error.retryAt })
724 : Effect.void,
725 ),
726 );
727 },
728 (effect) => slots.withPermit(effect),
729 );
730
731 const decodeResponse = <S extends Schema.Top>(
732 operation: BitbucketApiOperation,
733 schema: S,
734 response: HttpClientResponse.HttpClientResponse,
735 ): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
736 HttpClientResponse.matchStatus({
737 "2xx": (success) =>
738 HttpClientResponse.schemaBodyJson(schema)(success).pipe(
739 Effect.mapError(
740 (cause) =>
741 new BitbucketResponseDecodeError({
742 operation,
743 status: success.status,
744 cause,
745 }),
746 ),
747 ),
748 orElse: (failed) => responseError(operation, failed),
749 })(response);
750
751 const executeJson = <S extends Schema.Top>(
752 operation: BitbucketApiOperation,
753 request: HttpClientRequest.HttpClientRequest,
754 schema: S,
755 ): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
756 throttled(
757 request.method,
758 withAuth(request.pipe(HttpClientRequest.acceptJson)).pipe(
759 Effect.flatMap(httpClient.execute),
760 Effect.mapError(
761 (cause) =>
762 new BitbucketRequestError({
763 operation,
764 cause,
765 }),
766 ),
767 Effect.flatMap((response) => decodeResponse(operation, schema, response)),
768 Effect.timeout(BITBUCKET_API_REQUEST_TIMEOUT),
769 Effect.catchTags({
770 TimeoutError: (cause) => Effect.fail(new BitbucketRequestError({ operation, cause })),
771 }),
772 ),
773 );
774
775 const resolveRepository = Effect.fn("BitbucketApi.resolveRepository")(function* (input: {
776 readonly cwd: string;
777 readonly reference?: string;
778 readonly context?: SourceControlProvider.SourceControlProviderContext;
779 readonly repository?: string;
780 }) {
781 if (input.context?.provider.kind === "bitbucket" && !servesProvider(input.context.provider)) {
782 // Falling back to another remote could act on a different repository.
783 return yield* new BitbucketRepositoryRemoteNotFoundError({ cwd: input.cwd });
784 }
785 if (input.repository !== undefined) {
786 return yield* requireRepositoryLocator(input.repository);
787 }
788
789 const url = input.reference ? URL.parse(input.reference) : null;
790 const link = url ? definition.parseChangeRequestUrl(url) : null;
791 if (link) return yield* requireRepositoryLocator(link.repository);
792
793 const fromContext =
794 input.context?.provider.kind === "bitbucket"
795 ? parseBitbucketRemoteUrl(input.context.remoteUrl)
796 : null;
797 if (fromContext) return fromContext;
798
799 const listRemotes = yield* git.remotes(input.cwd).pipe(
800 Effect.mapError(
801 (cause) =>
802 new BitbucketRepositoryVcsResolveError({
803 cwd: input.cwd,
804 cause,
805 }),
806 ),
807 );
808 const remotes = yield* listRemotes.pipe(
809 Effect.mapError(
810 (cause) =>
811 new BitbucketRepositoryRemotesListError({
812 cwd: input.cwd,
813 cause,
814 }),
815 ),
816 );
817
818 for (const remote of remotes.remotes) {
819 if (!servesProvider(recognizeRemoteWith(definition, remote.url))) continue;
820 const parsed = parseBitbucketRemoteUrl(remote.url);
821 if (parsed) return parsed;
822 }
823
824 return yield* new BitbucketRepositoryRemoteNotFoundError({
825 cwd: input.cwd,
826 });
827 });
828
829 const getRepositoryFromLocator = (repository: BitbucketRepositoryLocator) =>
830 executeJson(
831 "getRepository",
832 HttpClientRequest.get(
833 apiUrl(
834 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
835 ),
836 ),
837 RawBitbucketRepositorySchema,
838 );
839
840 const getRepository = (input: {
841 readonly cwd: string;
842 readonly context?: SourceControlProvider.SourceControlProviderContext;
843 readonly repository?: string;
844 }) => resolveRepository(input).pipe(Effect.flatMap(getRepositoryFromLocator));
845
846 const getBranchingModelFromLocator = (repository: BitbucketRepositoryLocator) =>
847 executeJson(
848 "getBranchingModel",
849 HttpClientRequest.get(
850 apiUrl(
851 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/branching-model`,
852 ),
853 ),
854 RawBitbucketBranchingModelSchema,
855 );
856
857 const getRawPullRequestFromRepository = (
858 repository: BitbucketRepositoryLocator,
859 reference: string,
860 ) =>
861 executeJson(
862 "getPullRequest",
863 HttpClientRequest.get(
864 apiUrl(
865 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests/${encodeURIComponent(normalizeChangeRequestId(reference))}`,
866 ),
867 ),
868 BitbucketPullRequestSchema,
869 );
870
871 const getRawPullRequest = (input: {
872 readonly cwd: string;
873 readonly context?: SourceControlProvider.SourceControlProviderContext;
874 readonly reference: string;
875 }) =>
876 resolveRepository(input).pipe(
877 Effect.flatMap((repository) => getRawPullRequestFromRepository(repository, input.reference)),
878 );
879
880 const readConfigValueNullable = (cwd: string, key: string) =>
881 git.readConfigValue(cwd, key).pipe(Effect.orElseSucceed(() => null));
882
883 const resolveCheckoutRemote = Effect.fn("BitbucketApi.resolveCheckoutRemote")(function* (input: {
884 readonly cwd: string;
885 readonly context?: SourceControlProvider.SourceControlProviderContext;
886 readonly destinationRepository: BitbucketRepositoryLocator;
887 readonly sourceRepositoryName: string;
888 readonly isCrossRepository: boolean;
889 }) {
890 if (!input.isCrossRepository) {
891 const context = input.context?.provider.kind === "bitbucket" ? input.context : undefined;
892 const remoteName =
893 context?.remoteName ??
894 (yield* git.resolvePrimaryRemoteName(input.cwd).pipe(Effect.orElseSucceed(() => null)));
895 if (remoteName) {
896 const remoteUrl =
897 context?.remoteUrl ??
898 (yield* readConfigValueNullable(input.cwd, `remote.${remoteName}.url`));
899 const repository =
900 remoteUrl && (context || recognizeRemoteWith(definition, remoteUrl))
901 ? parseBitbucketRemoteUrl(remoteUrl)
902 : null;
903 if (
904 repository &&
905 `${repository.workspace}/${repository.repoSlug}`.toLowerCase() ===
906 input.sourceRepositoryName.toLowerCase()
907 ) {
908 return remoteName;
909 }
910 }
911 }
912
913 const cloneUrls = yield* getRepository({
914 cwd: input.cwd,
915 repository: input.sourceRepositoryName,
916 ...(input.context ? { context: input.context } : {}),
917 }).pipe(Effect.map(normalizeRepositoryCloneUrls));
918 const originRemoteUrl = yield* readConfigValueNullable(input.cwd, "remote.origin.url");
919 return yield* git.ensureRemote({
920 cwd: input.cwd,
921 preferredName: input.isCrossRepository
922 ? repositoryOwnerName(input.sourceRepositoryName)
923 : input.destinationRepository.workspace,
924 url: selectCloneUrl({ cloneUrls, originRemoteUrl }),
925 });
926 });
927
928 const apiOrigin = originOf(config.baseUrl);
929
930 const trustedUrl = (value: string): string | null => {
931 if (!/^https?:\/\//u.test(value)) return apiUrl(value);
932 const origin = originOf(value);
933 return origin !== null && origin === apiOrigin ? value : null;
934 };
935
936 /** Redirects forward auth headers; restrict them to the configured Bitbucket. */
937 const send = (input: {
938 readonly method: "GET" | "POST" | "PUT" | "DELETE";
939 readonly url: string;
940 readonly body?: string;
941 readonly redirects: number;
942 }): Effect.Effect<HttpClientResponse.HttpClientResponse, BitbucketApiError> => {
943 const url = trustedUrl(input.url);
944 if (url === null) {
945 return Effect.fail(
946 new BitbucketUntrustedUrlError({ host: originOf(input.url) ?? "an unreadable url" }),
947 );
948 }
949 const base =
950 input.method === "GET"
951 ? HttpClientRequest.get(url)
952 : input.method === "POST"
953 ? HttpClientRequest.post(url)
954 : input.method === "DELETE"
955 ? HttpClientRequest.make("DELETE")(url)
956 : HttpClientRequest.put(url);
957 // Diff endpoints return patches, not JSON.
958 const withBody =
959 input.body === undefined
960 ? base
961 : base.pipe(HttpClientRequest.bodyText(input.body, "application/json"));
962 return withAuth(withBody).pipe(
963 Effect.flatMap(httpClient.execute),
964 Effect.mapError(
965 (cause): BitbucketApiError => new BitbucketRequestError({ operation: "request", cause }),
966 ),
967 Effect.flatMap((response) => {
968 const location = response.headers.location;
969 if (
970 response.status >= 300 &&
971 response.status < 400 &&
972 location !== undefined &&
973 input.redirects < MAX_REDIRECTS
974 ) {
975 return send({
976 ...input,
977 url: new URL(location, url).toString(),
978 redirects: input.redirects + 1,
979 });
980 }
981 return Effect.succeed(response);
982 }),
983 );
984 };
985
986 const request: BitbucketApi["Service"]["request"] = (input) =>
987 throttled(
988 input.method,
989 send({ ...input, redirects: 0 }).pipe(
990 Effect.flatMap((response) =>
991 HttpClientResponse.matchStatus({
992 // Read through the body stream rather than `text`, so an oversized diff is stopped as
993 // it arrives instead of being materialized whole and then cut.
994 "2xx": (success) =>
995 collectUint8StreamText({
996 stream: success.stream,
997 maxBytes: input.maxBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
998 }).pipe(
999 Effect.mapError(
1000 (cause) =>
1001 new BitbucketResponseBodyReadError({
1002 operation: "request",
1003 status: success.status,
1004 cause,
1005 }),
1006 ),
1007 Effect.map((collected) => ({
1008 body: collected.text,
1009 truncated: collected.truncated,
1010 })),
1011 ),
1012 orElse: (failed) => responseError("request", failed),
1013 })(response),
1014 ),
1015 // This also caps redirect hops: no request can finish headers then stall its body forever.
1016 Effect.timeout(BITBUCKET_API_REQUEST_TIMEOUT),
1017 Effect.catchTags({
1018 TimeoutError: (cause) =>
1019 Effect.fail(new BitbucketRequestError({ operation: "request", cause })),
1020 }),
1021 ),
1022 );
1023
1024 return BitbucketApi.of({
1025 request,
1026 // Bitbucket answers anonymous /user with 401, so without a credential there is nothing to ask.
1027 probeAuth: currentCredential.pipe(
1028 Effect.flatMap((credential) =>
1029 credential === null
1030 ? Effect.succeed(authFromCredential(null))
1031 : executeJson(
1032 "probeAuth",
1033 HttpClientRequest.get(apiUrl("/user")),
1034 BitbucketUserSchema,
1035 ).pipe(
1036 Effect.map((user) => ({
1037 status: "authenticated" as const,
1038 account: nonEmpty(user.username ?? user.display_name ?? user.account_id),
1039 host: Option.some("bitbucket.org"),
1040 detail: Option.none<string>(),
1041 })),
1042 Effect.catch(() => currentCredential.pipe(Effect.map(authFromCredential))),
1043 ),
1044 ),
1045 ),
1046 listPullRequests: Effect.fn("BitbucketApi.listPullRequests")(function (input) {
1047 return resolveRepository(input).pipe(
1048 Effect.flatMap((repository) => {
1049 const states = toBitbucketStates(input.state);
1050 const query: Record<string, string | ReadonlyArray<string>> = {
1051 pagelen: String(Math.max(1, Math.min(input.limit ?? 20, 50))),
1052 sort: "-updated_on",
1053 q: bitbucketQueryString([
1054 `source.branch.name = "${SourceControlProvider.sourceBranch(input).replaceAll('"', '\\"')}"`,
1055 bitbucketStateFilter(states),
1056 ]),
1057 state: states,
1058 };
1059
1060 return executeJson(
1061 "listPullRequests",
1062 HttpClientRequest.get(
1063 apiUrl(
1064 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
1065 ),
1066 { urlParams: query },
1067 ),
1068 BitbucketPullRequestListSchema,
1069 );
1070 }),
1071 Effect.map((list) => list.values.map(normalizeBitbucketPullRequestRecord)),
1072 );
1073 }),
1074 getPullRequest: Effect.fn("BitbucketApi.getPullRequest")(function (input) {
1075 return getRawPullRequest(input).pipe(Effect.map(normalizeBitbucketPullRequestRecord));
1076 }),
1077 getRepositoryCloneUrls: Effect.fn("BitbucketApi.getRepositoryCloneUrls")(function (input) {
1078 return getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls));
1079 }),
1080 createRepository: Effect.fn("BitbucketApi.createRepository")(function (input) {
1081 return requireRepositoryLocator(input.repository).pipe(
1082 Effect.flatMap((repository) =>
1083 executeJson(
1084 "createRepository",
1085 HttpClientRequest.post(
1086 apiUrl(
1087 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
1088 ),
1089 ).pipe(
1090 HttpClientRequest.bodyJsonUnsafe({
1091 scm: "git",
1092 is_private: input.visibility === "private",
1093 }),
1094 ),
1095 RawBitbucketRepositorySchema,
1096 ),
1097 ),
1098 Effect.map(normalizeRepositoryCloneUrls),
1099 );
1100 }),
1101 createPullRequest: Effect.fn("BitbucketApi.createPullRequest")(function* (input) {
1102 const repository = yield* resolveRepository(input);
1103 const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
1104 Effect.mapError(
1105 (cause) =>
1106 new BitbucketPullRequestBodyReadError({
1107 cwd: input.cwd,
1108 bodyFile: input.bodyFile,
1109 cause,
1110 }),
1111 ),
1112 );
1113 const sourceOwner = sourceWorkspace(input);
1114 const body = {
1115 title: input.title,
1116 description,
1117 source: {
1118 branch: {
1119 name: SourceControlProvider.sourceBranch(input),
1120 },
1121 ...(sourceOwner
1122 ? {
1123 repository: {
1124 full_name: `${sourceOwner}/${input.source?.repository ?? repository.repoSlug}`,
1125 },
1126 }
1127 : {}),
1128 },
1129 destination: {
1130 branch: {
1131 name: input.target?.refName ?? input.baseBranch,
1132 },
1133 },
1134 };
1135
1136 yield* executeJson(
1137 "createPullRequest",
1138 HttpClientRequest.post(
1139 apiUrl(
1140 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
1141 ),
1142 ).pipe(HttpClientRequest.bodyJsonUnsafe(body)),
1143 BitbucketPullRequestSchema,
1144 );
1145 }),
1146 getDefaultBranch: Effect.fn("BitbucketApi.getDefaultBranch")(function (input) {
1147 return resolveRepository(input).pipe(
1148 Effect.flatMap((locator) =>
1149 Effect.all(
1150 {
1151 repository: getRepositoryFromLocator(locator),
1152 branchingModel: getBranchingModelFromLocator(locator).pipe(
1153 Effect.orElseSucceed(
1154 (): typeof RawBitbucketBranchingModelSchema.Type | null => null,
1155 ),
1156 ),
1157 },
1158 { concurrency: "unbounded" },
1159 ),
1160 ),
1161 Effect.map(defaultChangeRequestTargetBranch),
1162 );
1163 }),
1164 checkoutPullRequest: Effect.fn("BitbucketApi.checkoutPullRequest")(
1165 function* (input) {
1166 const destinationRepository = yield* resolveRepository(input);
1167 const pullRequest = yield* getRawPullRequestFromRepository(
1168 destinationRepository,
1169 input.reference,
1170 );
1171 const destinationRepositoryName =
1172 repositoryNameWithOwner(pullRequest.destination.repository) ??
1173 `${destinationRepository.workspace}/${destinationRepository.repoSlug}`;
1174 const sourceRepositoryName =
1175 repositoryNameWithOwner(pullRequest.source.repository) ?? destinationRepositoryName;
1176 const isCrossRepository = sourceRepositoryName !== destinationRepositoryName;
1177 const remoteName = yield* resolveCheckoutRemote({
1178 cwd: input.cwd,
1179 destinationRepository,
1180 sourceRepositoryName,
1181 isCrossRepository,
1182 ...(input.context ? { context: input.context } : {}),
1183 });
1184 const remoteBranch = pullRequest.source.branch.name;
1185 const localBranch = checkoutBranchName({
1186 pullRequestId: pullRequest.id,
1187 headBranch: remoteBranch,
1188 isCrossRepository,
1189 });
1190 const localBranchNames = yield* git.listLocalBranchNames(input.cwd);
1191 const localBranchExists = localBranchNames.includes(localBranch);
1192
1193 if (input.force === true || !localBranchExists) {
1194 yield* git.fetchRemoteBranch({
1195 cwd: input.cwd,
1196 remoteName,
1197 remoteBranch,
1198 localBranch,
1199 });
1200 } else {
1201 yield* git.fetchRemoteTrackingBranch({
1202 cwd: input.cwd,
1203 remoteName,
1204 remoteBranch,
1205 });
1206 }
1207
1208 yield* git.setBranchUpstream({
1209 cwd: input.cwd,
1210 branch: localBranch,
1211 remoteName,
1212 remoteBranch,
1213 });
1214 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
1215 },
1216 (effect, input) =>
1217 effect.pipe(
1218 Effect.mapError((cause) =>
1219 isBitbucketApiError(cause)
1220 ? cause
1221 : new BitbucketCheckoutError({
1222 cwd: input.cwd,
1223 reference: input.reference,
1224 cause,
1225 }),
1226 ),
1227 ),
1228 ),
1229 });
1230});
1231
1232export const layer = Layer.effect(BitbucketApi, make);