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

BitbucketApi.ts

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