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​
605const responseError = Effect.fn("BitbucketApi.responseError")(function* (
606 operation: BitbucketApiOperation,
607 response: HttpClientResponse.HttpClientResponse,
608): Effect.fn.Return<never, BitbucketApiError> {
609 const now = yield* Clock.currentTimeMillis;
610 const retryAt = retryAtFromHeader(response.headers["retry-after"], now);
611 const collected = yield* collectUint8StreamText({
612 stream: response.stream,
613 maxBytes: DEFAULT_MAX_RESPONSE_BYTES,
614 }).pipe(
615 Effect.mapError(
616 (cause) =>
617 new BitbucketResponseBodyReadError({
618 operation,
619 status: response.status,
620 retryAt,
621 cause,
622 }),
623 ),
624 );
625 return yield* new BitbucketResponseError({
626 operation,
627 status: response.status,
628 responseBodyLength: collected.text.length,
629 retryAt,
630 });
631});
632​
633/** @public Service construction is part of the canonical Effect module API. */
634export const make = Effect.gen(function* () {
635 const config = yield* BitbucketApiEnvConfig;
636 const host = yield* SourceControlHost.SourceControlHost;
637 const git = host.git;
638 const httpClient = yield* HttpClient.HttpClient;
639 const fileSystem = yield* FileSystem.FileSystem;
640​
641 const apiUrl = (path: string) => `${config.baseUrl.replace(/\/+$/u, "")}${path}`;
642​
643 const currentCredential = host.settings.get.pipe(
644 Effect.map((settings) =>
645 resolveCredential(
646 readSourceControlHostSettings(
647 BitbucketClient.settings,
648 settings.sourceControlHosts[BitbucketClient.definition.kind],
649 ),
650 config,
651 ),
652 ),
653 Effect.catch((error) =>
654 // No cause: a settings decode error can quote a hand-edited token.
655 Effect.logWarning("failed to read Bitbucket credentials from settings", {
656 operation: error.operation,
657 }).pipe(
658 Effect.as(
659 resolveCredential(readSourceControlHostSettings(BitbucketClient.settings, {}), config),
660 ),
661 ),
662 ),
663 );
664​
665 const withAuth = (request: HttpClientRequest.HttpClientRequest) =>
666 currentCredential.pipe(
667 Effect.map((credential) =>
668 credential === null
669 ? request
670 : credential.kind === "access-token"
671 ? request.pipe(HttpClientRequest.bearerToken(credential.accessToken))
672 : request.pipe(HttpClientRequest.basicAuth(credential.email, credential.apiToken)),
673 ),
674 );
675​
676 const decodeResponse = <S extends Schema.Top>(
677 operation: BitbucketApiOperation,
678 schema: S,
679 response: HttpClientResponse.HttpClientResponse,
680 ): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
681 HttpClientResponse.matchStatus({
682 "2xx": (success) =>
683 HttpClientResponse.schemaBodyJson(schema)(success).pipe(
684 Effect.mapError(
685 (cause) =>
686 new BitbucketResponseDecodeError({
687 operation,
688 status: success.status,
689 cause,
690 }),
691 ),
692 ),
693 orElse: (failed) => responseError(operation, failed),
694 })(response);
695​
696 const executeJson = <S extends Schema.Top>(
697 operation: BitbucketApiOperation,
698 request: HttpClientRequest.HttpClientRequest,
699 schema: S,
700 ): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
701 withAuth(request.pipe(HttpClientRequest.acceptJson)).pipe(
702 Effect.flatMap(httpClient.execute),
703 Effect.mapError(
704 (cause) =>
705 new BitbucketRequestError({
706 operation,
707 cause,
708 }),
709 ),
710 Effect.flatMap((response) => decodeResponse(operation, schema, response)),
711 Effect.timeout(BITBUCKET_API_REQUEST_TIMEOUT),
712 Effect.catchTags({
713 TimeoutError: (cause) => Effect.fail(new BitbucketRequestError({ operation, cause })),
714 }),
715 );
716​
717 const resolveRepository = Effect.fn("BitbucketApi.resolveRepository")(function* (input: {
718 readonly cwd: string;
719 readonly context?: SourceControlProvider.SourceControlProviderContext;
720 readonly repository?: string;
721 }) {
722 if (input.repository !== undefined) {
723 return yield* requireRepositoryLocator(input.repository);
724 }
725​
726 const fromContext =
727 input.context?.provider.kind === "bitbucket"
728 ? parseBitbucketRemoteUrl(input.context.remoteUrl)
729 : null;
730 if (fromContext) return fromContext;
731​
732 const listRemotes = yield* git.remotes(input.cwd).pipe(
733 Effect.mapError(
734 (cause) =>
735 new BitbucketRepositoryVcsResolveError({
736 cwd: input.cwd,
737 cause,
738 }),
739 ),
740 );
741 const remotes = yield* listRemotes.pipe(
742 Effect.mapError(
743 (cause) =>
744 new BitbucketRepositoryRemotesListError({
745 cwd: input.cwd,
746 cause,
747 }),
748 ),
749 );
750​
751 for (const remote of remotes.remotes) {
752 if (detectSourceControlProviderFromRemoteUrl(remote.url)?.kind !== "bitbucket") continue;
753 const parsed = parseBitbucketRemoteUrl(remote.url);
754 if (parsed) return parsed;
755 }
756​
757 return yield* new BitbucketRepositoryRemoteNotFoundError({
758 cwd: input.cwd,
759 });
760 });
761​
762 const getRepositoryFromLocator = (repository: BitbucketRepositoryLocator) =>
763 executeJson(
764 "getRepository",
765 HttpClientRequest.get(
766 apiUrl(
767 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
768 ),
769 ),
770 RawBitbucketRepositorySchema,
771 );
772​
773 const getRepository = (input: {
774 readonly cwd: string;
775 readonly context?: SourceControlProvider.SourceControlProviderContext;
776 readonly repository?: string;
777 }) => resolveRepository(input).pipe(Effect.flatMap(getRepositoryFromLocator));
778​
779 const getBranchingModelFromLocator = (repository: BitbucketRepositoryLocator) =>
780 executeJson(
781 "getBranchingModel",
782 HttpClientRequest.get(
783 apiUrl(
784 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/branching-model`,
785 ),
786 ),
787 RawBitbucketBranchingModelSchema,
788 );
789​
790 const getRawPullRequestFromRepository = (
791 repository: BitbucketRepositoryLocator,
792 reference: string,
793 ) =>
794 executeJson(
795 "getPullRequest",
796 HttpClientRequest.get(
797 apiUrl(
798 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests/${encodeURIComponent(normalizeChangeRequestId(reference))}`,
799 ),
800 ),
801 BitbucketPullRequestSchema,
802 );
803​
804 const getRawPullRequest = (input: {
805 readonly cwd: string;
806 readonly context?: SourceControlProvider.SourceControlProviderContext;
807 readonly reference: string;
808 }) =>
809 resolveRepository(input).pipe(
810 Effect.flatMap((repository) => getRawPullRequestFromRepository(repository, input.reference)),
811 );
812​
813 const readConfigValueNullable = (cwd: string, key: string) =>
814 git.readConfigValue(cwd, key).pipe(Effect.orElseSucceed(() => null));
815​
816 const resolveCheckoutRemote = Effect.fn("BitbucketApi.resolveCheckoutRemote")(function* (input: {
817 readonly cwd: string;
818 readonly context?: SourceControlProvider.SourceControlProviderContext;
819 readonly destinationRepository: BitbucketRepositoryLocator;
820 readonly sourceRepositoryName: string;
821 readonly isCrossRepository: boolean;
822 }) {
823 if (
824 input.context?.provider.kind === "bitbucket" &&
825 !input.isCrossRepository &&
826 parseBitbucketRemoteUrl(input.context.remoteUrl) !== null
827 ) {
828 return input.context.remoteName;
829 }
830​
831 if (!input.isCrossRepository) {
832 const remoteName = yield* git
833 .resolvePrimaryRemoteName(input.cwd)
834 .pipe(Effect.orElseSucceed(() => null));
835 if (remoteName) return remoteName;
836 }
837​
838 const cloneUrls = yield* getRepository({
839 cwd: input.cwd,
840 repository: input.sourceRepositoryName,
841 ...(input.context ? { context: input.context } : {}),
842 }).pipe(Effect.map(normalizeRepositoryCloneUrls));
843 const originRemoteUrl = yield* readConfigValueNullable(input.cwd, "remote.origin.url");
844 return yield* git.ensureRemote({
845 cwd: input.cwd,
846 preferredName: input.isCrossRepository
847 ? repositoryOwnerName(input.sourceRepositoryName)
848 : input.destinationRepository.workspace,
849 url: selectCloneUrl({ cloneUrls, originRemoteUrl }),
850 });
851 });
852​
853 const apiOrigin = originOf(config.baseUrl);
854​
855 const trustedUrl = (value: string): string | null => {
856 if (!/^https?:\/\//u.test(value)) return apiUrl(value);
857 const origin = originOf(value);
858 return origin !== null && origin === apiOrigin ? value : null;
859 };
860​
861 /**
862 * Redirects are followed here rather than by the client, which forwards every header to
863 * whatever host it is sent to. A pull request diff, diffstat and conflicts are all served as
864 * redirects, so they have to be followed — but only back to the same Bitbucket.
865 */
866 const send = (input: {
867 readonly method: "GET" | "POST" | "PUT" | "DELETE";
868 readonly url: string;
869 readonly body?: string;
870 readonly redirects: number;
871 }): Effect.Effect<HttpClientResponse.HttpClientResponse, BitbucketApiError> => {
872 const url = trustedUrl(input.url);
873 if (url === null) {
874 return Effect.fail(
875 new BitbucketUntrustedUrlError({ host: originOf(input.url) ?? "an unreadable url" }),
876 );
877 }
878 const base =
879 input.method === "GET"
880 ? HttpClientRequest.get(url)
881 : input.method === "POST"
882 ? HttpClientRequest.post(url)
883 : input.method === "DELETE"
884 ? HttpClientRequest.make("DELETE")(url)
885 : HttpClientRequest.put(url);
886 // No `Accept: application/json`: the diff endpoints answer with a patch, not JSON.
887 const withBody =
888 input.body === undefined
889 ? base
890 : base.pipe(HttpClientRequest.bodyText(input.body, "application/json"));
891 return withAuth(withBody).pipe(
892 Effect.flatMap(httpClient.execute),
893 Effect.mapError(
894 (cause): BitbucketApiError => new BitbucketRequestError({ operation: "request", cause }),
895 ),
896 Effect.flatMap((response) => {
897 const location = response.headers.location;
898 if (
899 response.status >= 300 &&
900 response.status < 400 &&
901 location !== undefined &&
902 input.redirects < MAX_REDIRECTS
903 ) {
904 return send({
905 ...input,
906 url: new URL(location, url).toString(),
907 redirects: input.redirects + 1,
908 });
909 }
910 return Effect.succeed(response);
911 }),
912 );
913 };
914​
915 const request: BitbucketApi["Service"]["request"] = (input) =>
916 send({ ...input, redirects: 0 }).pipe(
917 Effect.flatMap((response) =>
918 HttpClientResponse.matchStatus({
919 // Read through the body stream rather than `text`, so an oversized diff is stopped as
920 // it arrives instead of being materialized whole and then cut.
921 "2xx": (success) =>
922 collectUint8StreamText({
923 stream: success.stream,
924 maxBytes: input.maxBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
925 }).pipe(
926 Effect.mapError(
927 (cause) =>
928 new BitbucketResponseBodyReadError({
929 operation: "request",
930 status: success.status,
931 cause,
932 }),
933 ),
934 Effect.map((collected) => ({
935 body: collected.text,
936 truncated: collected.truncated,
937 })),
938 ),
939 orElse: (failed) => responseError("request", failed),
940 })(response),
941 ),
942 // This also caps redirect hops: no request can finish headers then stall its body forever.
943 Effect.timeout(BITBUCKET_API_REQUEST_TIMEOUT),
944 Effect.catchTags({
945 TimeoutError: (cause) =>
946 Effect.fail(new BitbucketRequestError({ operation: "request", cause })),
947 }),
948 );
949​
950 return BitbucketApi.of({
951 request,
952 probeAuth: executeJson(
953 "probeAuth",
954 HttpClientRequest.get(apiUrl("/user")),
955 BitbucketUserSchema,
956 ).pipe(
957 Effect.map((user) => ({
958 status: "authenticated" as const,
959 account: nonEmpty(user.username ?? user.display_name ?? user.account_id),
960 host: Option.some("bitbucket.org"),
961 detail: Option.none<string>(),
962 })),
963 Effect.catch(() => currentCredential.pipe(Effect.map(authFromCredential))),
964 ),
965 listPullRequests: (input) =>
966 resolveRepository(input).pipe(
967 Effect.flatMap((repository) => {
968 const states = toBitbucketStates(input.state);
969 const query: Record<string, string | ReadonlyArray<string>> = {
970 pagelen: String(Math.max(1, Math.min(input.limit ?? 20, 50))),
971 sort: "-updated_on",
972 q: bitbucketQueryString([
973 `source.branch.name = "${SourceControlProvider.sourceBranch(input).replaceAll('"', '\\"')}"`,
974 bitbucketStateFilter(states),
975 ]),
976 state: states,
977 };
978​
979 return executeJson(
980 "listPullRequests",
981 HttpClientRequest.get(
982 apiUrl(
983 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
984 ),
985 { urlParams: query },
986 ),
987 BitbucketPullRequestListSchema,
988 );
989 }),
990 Effect.map((list) => list.values.map(normalizeBitbucketPullRequestRecord)),
991 ),
992 getPullRequest: (input) =>
993 getRawPullRequest(input).pipe(Effect.map(normalizeBitbucketPullRequestRecord)),
994 getRepositoryCloneUrls: (input) =>
995 getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls)),
996 createRepository: (input) =>
997 requireRepositoryLocator(input.repository).pipe(
998 Effect.flatMap((repository) =>
999 executeJson(
1000 "createRepository",
1001 HttpClientRequest.post(
1002 apiUrl(
1003 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,
1004 ),
1005 ).pipe(
1006 HttpClientRequest.bodyJsonUnsafe({
1007 scm: "git",
1008 is_private: input.visibility === "private",
1009 }),
1010 ),
1011 RawBitbucketRepositorySchema,
1012 ),
1013 ),
1014 Effect.map(normalizeRepositoryCloneUrls),
1015 ),
1016 createPullRequest: Effect.fn("BitbucketApi.createPullRequest")(function* (input) {
1017 const repository = yield* resolveRepository(input);
1018 const description = yield* fileSystem.readFileString(input.bodyFile).pipe(
1019 Effect.mapError(
1020 (cause) =>
1021 new BitbucketPullRequestBodyReadError({
1022 cwd: input.cwd,
1023 bodyFile: input.bodyFile,
1024 cause,
1025 }),
1026 ),
1027 );
1028 const sourceOwner = sourceWorkspace(input);
1029 const body = {
1030 title: input.title,
1031 description,
1032 source: {
1033 branch: {
1034 name: SourceControlProvider.sourceBranch(input),
1035 },
1036 ...(sourceOwner
1037 ? {
1038 repository: {
1039 full_name: `${sourceOwner}/${input.source?.repository ?? repository.repoSlug}`,
1040 },
1042 : {}),
1043 },
1044 destination: {
1045 branch: {
1046 name: input.target?.refName ?? input.baseBranch,
1047 },
1048 },
1049 };
1050​
1051 yield* executeJson(
1052 "createPullRequest",
1053 HttpClientRequest.post(
1054 apiUrl(
1055 `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,
1056 ),
1057 ).pipe(HttpClientRequest.bodyJsonUnsafe(body)),
1058 BitbucketPullRequestSchema,
1059 );
1060 }),
1061 getDefaultBranch: (input) =>
1062 resolveRepository(input).pipe(
1063 Effect.flatMap((locator) =>
1064 Effect.all(
1066 repository: getRepositoryFromLocator(locator),
1067 branchingModel: getBranchingModelFromLocator(locator).pipe(
1068 Effect.orElseSucceed(
1069 (): typeof RawBitbucketBranchingModelSchema.Type | null => null,
1070 ),
1071 ),
1072 },
1073 { concurrency: "unbounded" },
1074 ),
1075 ),
1076 Effect.map(defaultChangeRequestTargetBranch),
1077 ),
1078 checkoutPullRequest: Effect.fn("BitbucketApi.checkoutPullRequest")(
1079 function* (input) {
1080 const destinationRepository = yield* resolveRepository(input);
1081 const pullRequest = yield* getRawPullRequestFromRepository(
1082 destinationRepository,
1083 input.reference,
1084 );
1085 const destinationRepositoryName =
1086 repositoryNameWithOwner(pullRequest.destination.repository) ??
1087 `${destinationRepository.workspace}/${destinationRepository.repoSlug}`;
1088 const sourceRepositoryName =
1089 repositoryNameWithOwner(pullRequest.source.repository) ?? destinationRepositoryName;
1090 const isCrossRepository = sourceRepositoryName !== destinationRepositoryName;
1091 const remoteName = yield* resolveCheckoutRemote({
1092 cwd: input.cwd,
1093 destinationRepository,
1094 sourceRepositoryName,
1095 isCrossRepository,
1096 ...(input.context ? { context: input.context } : {}),
1097 });
1098 const remoteBranch = pullRequest.source.branch.name;
1099 const localBranch = checkoutBranchName({
1100 pullRequestId: pullRequest.id,
1101 headBranch: remoteBranch,
1102 isCrossRepository,
1103 });
1104 const localBranchNames = yield* git.listLocalBranchNames(input.cwd);
1105 const localBranchExists = localBranchNames.includes(localBranch);
1106​
1107 if (input.force === true || !localBranchExists) {
1108 yield* git.fetchRemoteBranch({
1109 cwd: input.cwd,
1110 remoteName,
1111 remoteBranch,
1112 localBranch,
1113 });
1114 } else {
1115 yield* git.fetchRemoteTrackingBranch({
1116 cwd: input.cwd,
1117 remoteName,
1118 remoteBranch,
1119 });
1121​
1122 yield* git.setBranchUpstream({
1123 cwd: input.cwd,
1124 branch: localBranch,
1125 remoteName,
1126 remoteBranch,
1127 });
1128 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
1129 },
1130 (effect, input) =>
1131 effect.pipe(
1132 Effect.mapError((cause) =>
1133 isBitbucketApiError(cause)
1134 ? cause
1135 : new BitbucketCheckoutError({
1136 cwd: input.cwd,
1137 reference: input.reference,
1138 cause,
1139 }),
1140 ),
1141 ),
1142 ),
1143 });
1144});
1145​
1146export const layer = Layer.effect(BitbucketApi, make);