Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

BitbucketApi.ts

1,274 lines42.9 KB

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