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