Open History to see the last commit
1import * as Cache from "effect/Cache";
2import * as Context from "effect/Context";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Layer from "effect/Layer";
7import * as Result from "effect/Result";
8import * as Schema from "effect/Schema";
9import type {
10 PullRequestAction,
11 PullRequestCheck,
12 PullRequestComment,
13 PullRequestCommit,
14 PullRequestListState,
15 PullRequestMergeMethod,
16 PullRequestMergeability,
17 PullRequestReviewCommentDraft,
18 PullRequestReviewPosition,
19 PullRequestReviewThread,
20 PullRequestReviewVerdict,
21 PullRequestReviewerCandidateList,
22} from "@t3tools/contracts";
23
24import * as BitbucketApi from "./BitbucketApi.ts";
25import { parseDiffFileRevisions } from "@t3tools/source-control-core/server/diffFileRevisions";
26import { sortChecks } from "@t3tools/source-control-core/server/pullRequestChecks";
27import {
28 buildReviewThreads,
29 decodeCommentsJson,
30 decodeCommitsJson,
31 decodeConflictsJson,
32 decodeDiffstatJson,
33 decodePullRequestJson,
34 decodePullRequestPageJson,
35 decodeRepositoryPermissionJson,
36 decodeStatusesJson,
37 decodeViewerJson,
38 decodeWorkspaceMembersJson,
39 type BitbucketDiffStat,
40 type BitbucketPullRequest,
41 type BitbucketRawComment,
42} from "./bitbucketPullRequestJson.ts";
43import type { ProviderListCursor } from "@t3tools/source-control-core/server/PullRequestProvider";
44
45export class BitbucketPullRequestReadError extends Schema.TaggedError<BitbucketPullRequestReadError>()(
46 "BitbucketPullRequestReadError",
47 {
48 operation: Schema.String,
49 cause: Schema.Defect(),
50 },
51) {
52 get detail(): string {
53 return `Bitbucket returned an unreadable ${this.operation} response.`;
54 }
55
56 override get message(): string {
57 return `Bitbucket failed in ${this.operation}: ${this.detail}`;
58 }
59}
60
61export class BitbucketViewerUnavailableError extends Schema.TaggedError<BitbucketViewerUnavailableError>()(
62 "BitbucketViewerUnavailableError",
63 {},
64) {
65 get detail(): string {
66 return "Bitbucket returned no account name for the configured credentials.";
67 }
68
69 override get message(): string {
70 return `Bitbucket failed in getViewer: ${this.detail}`;
71 }
72}
73
74export class BitbucketRepositoryUnsupportedError extends Schema.TaggedError<BitbucketRepositoryUnsupportedError>()(
75 "BitbucketRepositoryUnsupportedError",
76 {
77 repository: Schema.String,
78 },
79) {
80 get detail(): string {
81 return "A Bitbucket repository is addressed as workspace/repository.";
82 }
83
84 override get message(): string {
85 return `Bitbucket failed in resolveRepository: ${this.detail}`;
86 }
87}
88
89export class BitbucketDiffCommitError extends Schema.TaggedError<BitbucketDiffCommitError>()(
90 "BitbucketDiffCommitError",
91 {},
92) {
93 get detail(): string {
94 return "The named commit was not a commit sha.";
95 }
96
97 override get message(): string {
98 return `Bitbucket failed in getPullRequestDiff: ${this.detail}`;
99 }
100}
101
102export type BitbucketPullRequestApiError =
103 | BitbucketApi.BitbucketApiError
104 | BitbucketPullRequestReadError
105 | BitbucketViewerUnavailableError
106 | BitbucketRepositoryUnsupportedError
107 | BitbucketDiffCommitError;
108
109function isRepositoryPermissionUnavailableError(
110 error: BitbucketPullRequestApiError,
111): error is BitbucketApi.BitbucketResponseError {
112 return (
113 error._tag === "BitbucketResponseError" &&
114 (error.status === 403 || error.status === 404 || error.status === 410)
115 );
116}
117
118/** Requests above this size return an empty page without an error. */
119const MAX_PAGE_SIZE = 50;
120const MAX_LIST_PAGES = 10;
121const CONVERSATION_PAGE_SIZE = 50;
122const CONVERSATION_PAGES = 10;
123const DIFF_MAX_BYTES = 8 * 1024 * 1024;
124/** Must expire before the caller's version cache so refreshes reach Bitbucket. */
125const REVISION_PATCH_TTL = Duration.seconds(5);
126const REVISION_PATCH_CAPACITY = 16;
127const encodeRevisionKey = Schema.encodeSync(
128 Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.Number])),
129);
130export interface BitbucketPullRequestBatch {
131 readonly items: ReadonlyArray<BitbucketPullRequest>;
132 readonly truncated: boolean;
133}
134
135export class BitbucketPullRequestApi extends Context.Service<
136 BitbucketPullRequestApi,
137 {
138 readonly getViewer: () => Effect.Effect<string, BitbucketPullRequestApiError>;
139
140 readonly listPullRequests: (input: {
141 readonly repository: string;
142 readonly state: PullRequestListState;
143 readonly limit: number;
144 readonly query?: string | undefined;
145 readonly cursor?: ProviderListCursor | undefined;
146 /** Matched against the login a row shows, which is the nickname or else the display name. */
147 readonly author?: string | undefined;
148 readonly draft?: boolean | undefined;
149 }) => Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError>;
150
151 readonly getPullRequest: (input: {
152 readonly repository: string;
153 readonly number: number;
154 }) => Effect.Effect<BitbucketPullRequest, BitbucketPullRequestApiError>;
155
156 readonly getRepositoryPermission: (input: {
157 readonly repository: string;
158 }) => Effect.Effect<boolean, BitbucketPullRequestApiError>;
159
160 readonly getPullRequestDiff: (input: {
161 readonly repository: string;
162 readonly number: number;
163 readonly commit?: string | undefined;
164 }) => Effect.Effect<
165 { readonly patch: string; readonly truncated: boolean },
166 BitbucketPullRequestApiError
167 >;
168
169 readonly getDiffStat: (input: {
170 readonly repository: string;
171 readonly number: number;
172 }) => Effect.Effect<BitbucketDiffStat, BitbucketPullRequestApiError>;
173
174 /** Truncated patches cannot identify absent paths as deleted. */
175 readonly getFileRevisions: (input: {
176 readonly repository: string;
177 readonly number: number;
178 readonly paths: ReadonlyArray<string>;
179 }) => Effect.Effect<
180 { readonly revisions: ReadonlyMap<string, string>; readonly complete: boolean },
181 BitbucketPullRequestApiError
182 >;
183
184 readonly getMergeability: (input: {
185 readonly repository: string;
186 readonly number: number;
187 }) => Effect.Effect<PullRequestMergeability, BitbucketPullRequestApiError>;
188
189 readonly listComments: (input: {
190 readonly repository: string;
191 readonly number: number;
192 }) => Effect.Effect<
193 {
194 readonly comments: ReadonlyArray<PullRequestComment>;
195 readonly threads: ReadonlyArray<PullRequestReviewThread>;
196 readonly truncated: boolean;
197 },
198 BitbucketPullRequestApiError
199 >;
200
201 readonly listCommits: (input: {
202 readonly repository: string;
203 readonly number: number;
204 }) => Effect.Effect<ReadonlyArray<PullRequestCommit>, BitbucketPullRequestApiError>;
205
206 readonly listChecks: (input: {
207 readonly repository: string;
208 readonly number: number;
209 }) => Effect.Effect<ReadonlyArray<PullRequestCheck>, BitbucketPullRequestApiError>;
210
211 readonly listReviewerCandidates: (input: {
212 readonly repository: string;
213 readonly number: number;
214 }) => Effect.Effect<PullRequestReviewerCandidateList, BitbucketPullRequestApiError>;
215
216 readonly setReviewerRequest: (input: {
217 readonly repository: string;
218 readonly number: number;
219 readonly reviewers: ReadonlyArray<{ readonly id: string }>;
220 readonly requested: boolean;
221 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
222
223 readonly runAction: (input: {
224 readonly repository: string;
225 readonly number: number;
226 readonly action: PullRequestAction;
227 readonly mergeMethod?: PullRequestMergeMethod;
228 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
229
230 readonly updateChangeRequest: (input: {
231 readonly repository: string;
232 readonly number: number;
233 readonly title?: string | undefined;
234 readonly body?: string | undefined;
235 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
236
237 readonly comment: (input: {
238 readonly repository: string;
239 readonly number: number;
240 readonly body: string;
241 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
242
243 readonly updateComment: (input: {
244 readonly repository: string;
245 readonly number: number;
246 readonly commentId: string;
247 readonly body: string;
248 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
249
250 readonly submitReview: (input: {
251 readonly repository: string;
252 readonly number: number;
253 readonly verdict: PullRequestReviewVerdict;
254 readonly body: string;
255 readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>;
256 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
257
258 readonly replyToComment: (input: {
259 readonly repository: string;
260 readonly number: number;
261 readonly commentId: string;
262 readonly body: string;
263 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
264
265 readonly setCommentResolution: (input: {
266 readonly repository: string;
267 readonly number: number;
268 readonly commentId: string;
269 readonly resolved: boolean;
270 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
271 }
272>()("@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi") {}
273
274function repositorySegments(
275 repository: string,
276): Result.Result<
277 { readonly workspace: string; readonly slug: string },
278 BitbucketRepositoryUnsupportedError
279> {
280 const segments = repository
281 .split("/")
282 .map((segment) => segment.trim())
283 .filter((segment) => segment.length > 0);
284 const [workspace, slug] = segments;
285 if (segments.length !== 2 || workspace === undefined || slug === undefined) {
286 return Result.fail(new BitbucketRepositoryUnsupportedError({ repository }));
287 }
288 return Result.succeed({ workspace, slug });
289}
290
291function repositoryPathOf(segments: { readonly workspace: string; readonly slug: string }): string {
292 return `/repositories/${encodeURIComponent(segments.workspace)}/${encodeURIComponent(
293 segments.slug,
294 )}`;
295}
296
297function isCommitSha(value: string): boolean {
298 return /^[0-9a-f]{7,64}$/i.test(value);
299}
300
301function stateParams(state: PullRequestListState): ReadonlyArray<string> {
302 switch (state) {
303 case "open":
304 return ["OPEN"];
305 case "merged":
306 return ["MERGED"];
307 case "closed":
308 return ["DECLINED", "SUPERSEDED"];
309 case "all":
310 return ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"];
311 }
312}
313
314function searchFilter(query: string): string {
315 const literal = filterLiteral(query);
316 return `(title ~ "${literal}" OR description ~ "${literal}")`;
317}
318
319function authorFilter(login: string): string {
320 const literal = filterLiteral(login);
321 return `(author.nickname = "${literal}" OR author.display_name = "${literal}")`;
322}
323
324/**
325 * The backslash is escaped first, or escaping the quote would only produce a literal
326 * backslash followed by a live quote.
327 */
328function filterLiteral(value: string): string {
329 return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
330}
331
332function mergeStrategy(method: PullRequestMergeMethod | undefined): string {
333 switch (method) {
334 case "squash":
335 return "squash";
336 case "rebase":
337 return "rebase_fast_forward";
338 default:
339 return "merge_commit";
340 }
341}
342
343function bitbucketReviewPosition(
344 position: PullRequestReviewPosition,
345): { readonly from: number } | { readonly to: number } {
346 switch (position.kind) {
347 case "added":
348 return { to: position.newLine };
349 case "deleted":
350 return { from: position.oldLine };
351 case "context":
352 return position.side === "left" ? { from: position.oldLine } : { to: position.newLine };
353 }
354}
355
356/** @public */
357export const make = Effect.gen(function* () {
358 const bitbucket = yield* BitbucketApi.BitbucketApi;
359
360 const withRepository = <A>(
361 repository: string,
362 use: (
363 path: string,
364 workspace: string,
365 slug: string,
366 ) => Effect.Effect<A, BitbucketPullRequestApiError>,
367 ): Effect.Effect<A, BitbucketPullRequestApiError> => {
368 const segments = repositorySegments(repository);
369 return Result.isSuccess(segments)
370 ? use(repositoryPathOf(segments.success), segments.success.workspace, segments.success.slug)
371 : Effect.fail(segments.failure);
372 };
373
374 const listPage = (input: {
375 readonly url: string;
376 readonly limit: number;
377 readonly page: number;
378 readonly collected: ReadonlyArray<BitbucketPullRequest>;
379 }): Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError> =>
380 bitbucket.request({ method: "GET", url: input.url }).pipe(
381 Effect.flatMap((response) => {
382 const decoded = decodePullRequestPageJson(response.body);
383 if (!Result.isSuccess(decoded)) {
384 return Effect.fail(
385 new BitbucketPullRequestReadError({
386 operation: "listPullRequests",
387 cause: decoded.failure,
388 }),
389 );
390 }
391 const collected = [...input.collected, ...decoded.success.items];
392 const next = decoded.success.next;
393 if (next === null || collected.length >= input.limit || input.page >= MAX_LIST_PAGES) {
394 return Effect.succeed({
395 items: collected.slice(0, input.limit),
396 truncated: next !== null || collected.length > input.limit,
397 });
398 }
399 return listPage({ ...input, url: next, page: input.page + 1, collected });
400 }),
401 );
402
403 const readPage = <A>(input: {
404 readonly operation: string;
405 readonly url: string;
406 readonly decode: (body: string) => Result.Result<A, unknown>;
407 }): Effect.Effect<A, BitbucketPullRequestApiError> =>
408 bitbucket.request({ method: "GET", url: input.url }).pipe(
409 Effect.flatMap((response) => {
410 const decoded = input.decode(response.body);
411 return Result.isSuccess(decoded)
412 ? Effect.succeed(decoded.success)
413 : Effect.fail(
414 new BitbucketPullRequestReadError({
415 operation: input.operation,
416 cause: decoded.failure,
417 }),
418 );
419 }),
420 );
421
422 /** Replies and parents can span pages; assemble threads after pagination. */
423 const commentsPage = (input: {
424 readonly url: string;
425 readonly page: number;
426 readonly comments: ReadonlyArray<PullRequestComment>;
427 readonly entries: ReadonlyArray<BitbucketRawComment>;
428 }): Effect.Effect<
429 {
430 readonly comments: ReadonlyArray<PullRequestComment>;
431 readonly threads: ReadonlyArray<PullRequestReviewThread>;
432 readonly truncated: boolean;
433 },
434 BitbucketPullRequestApiError
435 > =>
436 readPage({ operation: "listComments", url: input.url, decode: decodeCommentsJson }).pipe(
437 Effect.flatMap((page) => {
438 const comments = [...input.comments, ...page.comments];
439 const entries = [...input.entries, ...page.entries];
440 if (page.next !== null && input.page < CONVERSATION_PAGES) {
441 return commentsPage({ url: page.next, page: input.page + 1, comments, entries });
442 }
443 return Effect.succeed({
444 comments,
445 threads: buildReviewThreads(entries),
446 truncated: page.next !== null,
447 });
448 }),
449 );
450
451 const itemPages = <A>(input: {
452 readonly operation: string;
453 readonly url: string;
454 readonly decode: (
455 body: string,
456 ) => Result.Result<{ readonly items: ReadonlyArray<A>; readonly next: string | null }, unknown>;
457 readonly items: ReadonlyArray<A>;
458 /** Each commit page is oldest-first. */
459 readonly prepend: boolean;
460 }): Effect.Effect<ReadonlyArray<A>, BitbucketPullRequestApiError> =>
461 readPage({ operation: input.operation, url: input.url, decode: input.decode }).pipe(
462 Effect.flatMap((page) => {
463 const items = input.prepend
464 ? [...page.items, ...input.items]
465 : [...input.items, ...page.items];
466 return page.next === null
467 ? Effect.succeed(items)
468 : itemPages({ ...input, url: page.next, items });
469 }),
470 );
471
472 const diffStatPages = (input: {
473 readonly url: string;
474 readonly totals: BitbucketDiffStat;
475 }): Effect.Effect<BitbucketDiffStat, BitbucketPullRequestApiError> =>
476 readPage({ operation: "getDiffStat", url: input.url, decode: decodeDiffstatJson }).pipe(
477 Effect.flatMap((page) => {
478 const totals = {
479 additions: input.totals.additions + page.additions,
480 deletions: input.totals.deletions + page.deletions,
481 changedFiles: input.totals.changedFiles + page.changedFiles,
482 };
483 return page.next === null
484 ? Effect.succeed(totals)
485 : diffStatPages({ url: page.next, totals });
486 }),
487 );
488
489 const pullRequestDiff = (input: {
490 readonly repository: string;
491 readonly number: number;
492 readonly commit?: string | undefined;
493 }): Effect.Effect<
494 { readonly patch: string; readonly truncated: boolean },
495 BitbucketPullRequestApiError
496 > =>
497 input.commit !== undefined && !isCommitSha(input.commit)
498 ? Effect.fail(new BitbucketDiffCommitError())
499 : withRepository(input.repository, (path) =>
500 bitbucket
501 .request({
502 method: "GET",
503 url:
504 input.commit === undefined
505 ? `${path}/pullrequests/${input.number}/diff`
506 : `${path}/diff/${input.commit}`,
507 maxBytes: DIFF_MAX_BYTES,
508 })
509 .pipe(
510 Effect.map((response) => ({ patch: response.body, truncated: response.truncated })),
511 ),
512 );
513
514 // Cache revisions, not large patch bodies that need reparsing.
515 const revisionPatches = yield* Cache.makeWith(
516 (key: string) => {
517 const [repository, number] = JSON.parse(key) as [string, number];
518 return pullRequestDiff({ repository, number }).pipe(
519 Effect.map((diff) => ({
520 revisions: parseDiffFileRevisions(diff.patch),
521 truncated: diff.truncated,
522 })),
523 );
524 },
525 {
526 capacity: REVISION_PATCH_CAPACITY,
527 timeToLive: (exit) => (Exit.isSuccess(exit) ? REVISION_PATCH_TTL : Duration.zero),
528 },
529 );
530
531 return BitbucketPullRequestApi.of({
532 getViewer: Effect.fn("BitbucketPullRequestApi.getViewer")(function () {
533 return bitbucket.request({ method: "GET", url: "/user" }).pipe(
534 Effect.flatMap((response): Effect.Effect<string, BitbucketPullRequestApiError> => {
535 const decoded = decodeViewerJson(response.body);
536 if (!Result.isSuccess(decoded)) {
537 return Effect.fail(
538 new BitbucketPullRequestReadError({ operation: "getViewer", cause: decoded.failure }),
539 );
540 }
541 return decoded.success === null
542 ? Effect.fail(new BitbucketViewerUnavailableError())
543 : Effect.succeed(decoded.success);
544 }),
545 );
546 }),
547
548 listPullRequests: Effect.fn("BitbucketPullRequestApi.listPullRequests")(function (input) {
549 return withRepository(input.repository, (path) => {
550 const search = input.query?.trim() ?? "";
551 // Exclude already-sent IDs at the inclusive timestamp before applying the page limit.
552 const predicates = [
553 ...(search.length === 0 ? [] : [searchFilter(search)]),
554 ...(input.author === undefined ? [] : [authorFilter(input.author)]),
555 ...(input.draft === undefined ? [] : [`draft = ${input.draft}`]),
556 ...(input.cursor === undefined ? [] : [`updated_on <= ${input.cursor.updatedBefore}`]),
557 ...(input.cursor?.seenAt ?? []).map((number) => `id != ${number}`),
558 ];
559 return listPage({
560 // Listings omit reviewers needed by `viewerReviewRequested`.
561 url: `${path}/pullrequests?${stateParams(input.state)
562 .map((state) => `state=${state}`)
563 .join("&")}&pagelen=${MAX_PAGE_SIZE}&sort=-updated_on&fields=%2Bvalues.reviewers${
564 predicates.length === 0 ? "" : `&q=${encodeURIComponent(predicates.join(" AND "))}`
565 }`,
566 limit: input.limit,
567 page: 1,
568 collected: [],
569 });
570 });
571 }),
572
573 getPullRequest: Effect.fn("BitbucketPullRequestApi.getPullRequest")(function (input) {
574 return withRepository(input.repository, (path) =>
575 readPage({
576 operation: "getPullRequest",
577 // Settlement needs `closed_on`, omitted by default.
578 url: `${path}/pullrequests/${input.number}?fields=%2Bclosed_on`,
579 decode: decodePullRequestJson,
580 }),
581 );
582 }),
583
584 // Permission endpoints may return 403/404/410 (CHANGE-2770); let writes enforce access.
585 getRepositoryPermission: Effect.fn("BitbucketPullRequestApi.getRepositoryPermission")(
586 function (input) {
587 return withRepository(input.repository, (_path, workspace, slug) =>
588 readPage({
589 operation: "getRepositoryPermission",
590 url: `/user/workspaces/${encodeURIComponent(workspace)}/permissions/repositories?q=${encodeURIComponent(
591 `repository.full_name="${filterLiteral(`${workspace}/${slug}`)}"`,
592 )}`,
593 decode: decodeRepositoryPermissionJson,
594 }),
595 ).pipe(Effect.catchIf(isRepositoryPermissionUnavailableError, () => Effect.succeed(true)));
596 },
597 ),
598
599 getPullRequestDiff: pullRequestDiff,
600
601 getFileRevisions: Effect.fn("BitbucketPullRequestApi.getFileRevisions")(function* (input) {
602 if (input.paths.length === 0)
603 return { revisions: new Map<string, string>(), complete: false };
604 return yield* Cache.get(
605 revisionPatches,
606 encodeRevisionKey([input.repository, input.number]),
607 ).pipe(
608 Effect.map((diff) => {
609 const revisions = new Map(diff.revisions);
610 // A truncated patch cannot identify absent paths as deleted.
611 if (!diff.truncated) {
612 for (const path of input.paths) {
613 if (!revisions.has(path)) revisions.set(path, "");
614 }
615 }
616 return { revisions, complete: !diff.truncated };
617 }),
618 );
619 }),
620
621 getDiffStat: Effect.fn("BitbucketPullRequestApi.getDiffStat")(function (input) {
622 return withRepository(input.repository, (path) =>
623 diffStatPages({
624 url: `${path}/pullrequests/${input.number}/diffstat?pagelen=${MAX_PAGE_SIZE}`,
625 totals: { additions: 0, deletions: 0, changedFiles: 0 },
626 }),
627 );
628 }),
629
630 getMergeability: Effect.fn("BitbucketPullRequestApi.getMergeability")(function (input) {
631 return withRepository(input.repository, (path) =>
632 readPage({
633 operation: "getMergeability",
634 url: `${path}/pullrequests/${input.number}/conflicts`,
635 decode: decodeConflictsJson,
636 }),
637 );
638 }),
639
640 listComments: Effect.fn("BitbucketPullRequestApi.listComments")(function (input) {
641 return withRepository(input.repository, (path) =>
642 commentsPage({
643 url: `${path}/pullrequests/${input.number}/comments?pagelen=${CONVERSATION_PAGE_SIZE}`,
644 page: 1,
645 comments: [],
646 entries: [],
647 }),
648 );
649 }),
650
651 listCommits: Effect.fn("BitbucketPullRequestApi.listCommits")(function (input) {
652 return withRepository(input.repository, (path) =>
653 itemPages({
654 operation: "listCommits",
655 url: `${path}/pullrequests/${input.number}/commits?pagelen=${CONVERSATION_PAGE_SIZE}`,
656 decode: decodeCommitsJson,
657 items: [],
658 prepend: true,
659 }),
660 );
661 }),
662
663 listChecks: Effect.fn("BitbucketPullRequestApi.listChecks")(function (input) {
664 return withRepository(input.repository, (path) =>
665 itemPages({
666 operation: "listChecks",
667 url: `${path}/pullrequests/${input.number}/statuses?pagelen=${CONVERSATION_PAGE_SIZE}`,
668 decode: decodeStatusesJson,
669 items: [],
670 prepend: false,
671 }).pipe(Effect.map(sortChecks)),
672 );
673 }),
674
675 listReviewerCandidates: Effect.fn("BitbucketPullRequestApi.listReviewerCandidates")(
676 function (input) {
677 return withRepository(input.repository, (path, workspace) =>
678 Effect.all(
679 [
680 readPage({
681 operation: "getPullRequest",
682 url: `${path}/pullrequests/${input.number}`,
683 decode: decodePullRequestJson,
684 }),
685 readPage({
686 operation: "listReviewerCandidates",
687 url: `/workspaces/${encodeURIComponent(workspace)}/members?pagelen=${MAX_PAGE_SIZE}`,
688 decode: decodeWorkspaceMembersJson,
689 }),
690 ],
691 { concurrency: 2 },
692 ).pipe(
693 Effect.map(([pullRequest, members]) => {
694 const requested = new Set(pullRequest.reviewerIds);
695 const author = pullRequest.author?.login;
696 return {
697 // Bitbucket forbids requesting a review from the PR author.
698 candidates: members.items.flatMap((candidate) =>
699 candidate.login === author
700 ? []
701 : [{ ...candidate, isRequested: requested.has(candidate.id) }],
702 ),
703 truncated: members.next !== null,
704 };
705 }),
706 ),
707 );
708 },
709 ),
710
711 setReviewerRequest: Effect.fn("BitbucketPullRequestApi.setReviewerRequest")(function (input) {
712 return withRepository(input.repository, (path) => {
713 const pullRequest = `${path}/pullrequests/${input.number}`;
714 return readPage({
715 operation: "getPullRequest",
716 url: pullRequest,
717 decode: decodePullRequestJson,
718 }).pipe(
719 Effect.flatMap((current) => {
720 // Bitbucket replaces the entire reviewer list.
721 const uuids = new Set(current.reviewerIds);
722 for (const reviewer of input.reviewers) {
723 if (input.requested) uuids.add(reviewer.id);
724 else uuids.delete(reviewer.id);
725 }
726 return bitbucket.request({
727 method: "PUT",
728 url: pullRequest,
729 body: JSON.stringify({ reviewers: [...uuids].map((uuid) => ({ uuid })) }),
730 });
731 }),
732 Effect.asVoid,
733 );
734 });
735 }),
736
737 runAction: Effect.fn("BitbucketPullRequestApi.runAction")(function (input) {
738 return withRepository(input.repository, (path) => {
739 const pullRequest = `${path}/pullrequests/${input.number}`;
740 if (input.action === "merge") {
741 return bitbucket
742 .request({
743 method: "POST",
744 url: `${pullRequest}/merge`,
745 body: JSON.stringify({ merge_strategy: mergeStrategy(input.mergeMethod) }),
746 })
747 .pipe(Effect.asVoid);
748 }
749 return bitbucket
750 .request({ method: "POST", url: `${pullRequest}/decline` })
751 .pipe(Effect.asVoid);
752 });
753 }),
754
755 updateChangeRequest: Effect.fn("BitbucketPullRequestApi.updateChangeRequest")(function (input) {
756 return withRepository(input.repository, (path) =>
757 // Partial PUTs preserve concurrent edits to unchanged fields.
758 bitbucket
759 .request({
760 method: "PUT",
761 url: `${path}/pullrequests/${input.number}`,
762 body: JSON.stringify({
763 ...(input.title === undefined ? {} : { title: input.title }),
764 ...(input.body === undefined ? {} : { description: input.body }),
765 }),
766 })
767 .pipe(Effect.asVoid),
768 );
769 }),
770
771 comment: Effect.fn("BitbucketPullRequestApi.comment")(function (input) {
772 return withRepository(input.repository, (path) =>
773 bitbucket
774 .request({
775 method: "POST",
776 url: `${path}/pullrequests/${input.number}/comments`,
777 body: JSON.stringify({ content: { raw: input.body } }),
778 })
779 .pipe(Effect.asVoid),
780 );
781 }),
782
783 updateComment: Effect.fn("BitbucketPullRequestApi.updateComment")(function (input) {
784 return withRepository(input.repository, (path) =>
785 bitbucket
786 .request({
787 method: "PUT",
788 url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
789 input.commentId,
790 )}`,
791 body: JSON.stringify({ content: { raw: input.body } }),
792 })
793 .pipe(Effect.asVoid),
794 );
795 }),
796
797 submitReview: Effect.fn("BitbucketPullRequestApi.submitReview")(function (input) {
798 return withRepository(input.repository, (path) =>
799 Effect.gen(function* () {
800 const pullRequest = `${path}/pullrequests/${input.number}`;
801 // A partially failed review must not leave an approval.
802 yield* Effect.forEach(
803 input.comments,
804 (comment) =>
805 bitbucket.request({
806 method: "POST",
807 url: `${pullRequest}/comments`,
808 body: JSON.stringify({
809 content: { raw: comment.body },
810 inline: {
811 path: comment.path,
812 ...bitbucketReviewPosition(comment.position),
813 },
814 }),
815 }),
816 { discard: true },
817 );
818 if (input.body.trim().length > 0) {
819 yield* bitbucket.request({
820 method: "POST",
821 url: `${pullRequest}/comments`,
822 // @effect-diagnostics-next-line preferSchemaOverJson:off
823 body: JSON.stringify({ content: { raw: input.body } }),
824 });
825 }
826 if (input.verdict === "approve") {
827 yield* bitbucket.request({ method: "POST", url: `${pullRequest}/approve` });
828 }
829 if (input.verdict === "request-changes") {
830 yield* bitbucket.request({ method: "POST", url: `${pullRequest}/request-changes` });
831 }
832 }),
833 );
834 }),
835
836 replyToComment: Effect.fn("BitbucketPullRequestApi.replyToComment")(function (input) {
837 return withRepository(input.repository, (path) =>
838 bitbucket
839 .request({
840 method: "POST",
841 url: `${path}/pullrequests/${input.number}/comments`,
842 body: JSON.stringify({
843 content: { raw: input.body },
844 parent: { id: Number(input.commentId) },
845 }),
846 })
847 .pipe(Effect.asVoid),
848 );
849 }),
850
851 setCommentResolution: Effect.fn("BitbucketPullRequestApi.setCommentResolution")(
852 function (input) {
853 return withRepository(input.repository, (path) =>
854 bitbucket
855 .request({
856 method: input.resolved ? "POST" : "DELETE",
857 url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
858 input.commentId,
859 )}/resolve`,
860 })
861 .pipe(Effect.asVoid),
862 );
863 },
864 ),
865 });
866});
867
868export const layer = Layer.effect(BitbucketPullRequestApi, make);