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

BitbucketApi.ts

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