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