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 {
27 buildReviewThreads,
28 decodeCommentsJson,
29 decodeCommitsJson,
30 decodeConflictsJson,
31 decodeDiffstatJson,
32 decodePullRequestJson,
33 decodePullRequestPageJson,
34 decodeRepositoryPermissionJson,
35 decodeStatusesJson,
36 decodeViewerJson,
37 decodeWorkspaceMembersJson,
38 type BitbucketDiffStat,
39 type BitbucketPullRequest,
40 type BitbucketRawComment,
41} from "./bitbucketPullRequestJson.ts";
42import type { ProviderListCursor } from "@t3tools/source-control-core/server/PullRequestProvider";
43
44export class BitbucketPullRequestReadError extends Schema.TaggedError<BitbucketPullRequestReadError>()(
45 "BitbucketPullRequestReadError",
46 {
47 operation: Schema.String,
48 cause: Schema.Defect(),
49 },
50) {
51 get detail(): string {
52 return `Bitbucket returned an unreadable ${this.operation} response.`;
53 }
54
55 override get message(): string {
56 return `Bitbucket failed in ${this.operation}: ${this.detail}`;
57 }
58}
59
60export class BitbucketViewerUnavailableError extends Schema.TaggedError<BitbucketViewerUnavailableError>()(
61 "BitbucketViewerUnavailableError",
62 {},
63) {
64 get detail(): string {
65 return "Bitbucket returned no account name for the configured credentials.";
66 }
67
68 override get message(): string {
69 return `Bitbucket failed in getViewer: ${this.detail}`;
70 }
71}
72
73export class BitbucketRepositoryUnsupportedError extends Schema.TaggedError<BitbucketRepositoryUnsupportedError>()(
74 "BitbucketRepositoryUnsupportedError",
75 {
76 repository: Schema.String,
77 },
78) {
79 get detail(): string {
80 return "A Bitbucket repository is addressed as workspace/repository.";
81 }
82
83 override get message(): string {
84 return `Bitbucket failed in resolveRepository: ${this.detail}`;
85 }
86}
87
88export class BitbucketDiffCommitError extends Schema.TaggedError<BitbucketDiffCommitError>()(
89 "BitbucketDiffCommitError",
90 {},
91) {
92 get detail(): string {
93 return "The named commit was not a commit sha.";
94 }
95
96 override get message(): string {
97 return `Bitbucket failed in getPullRequestDiff: ${this.detail}`;
98 }
99}
100
101export type BitbucketPullRequestApiError =
102 | BitbucketApi.BitbucketApiError
103 | BitbucketPullRequestReadError
104 | BitbucketViewerUnavailableError
105 | BitbucketRepositoryUnsupportedError
106 | BitbucketDiffCommitError;
107
108function isRepositoryPermissionUnavailableError(
109 error: BitbucketPullRequestApiError,
110): error is BitbucketApi.BitbucketResponseError {
111 return (
112 error._tag === "BitbucketResponseError" &&
113 (error.status === 403 || error.status === 404 || error.status === 410)
114 );
115}
116
117/**
118 * Asking for more does not fail — it answers with an empty page and no error at
119 * all, so this is a number to respect rather than to push against.
120 */
121const MAX_PAGE_SIZE = 50;
122const MAX_LIST_PAGES = 10;
123const CONVERSATION_PAGE_SIZE = 50;
124const CONVERSATION_PAGES = 10;
125const DIFF_MAX_BYTES = 8 * 1024 * 1024;
126/**
127 * Deliberately far shorter than the window the caller holds versions for: a refresh drops what the
128 * caller holds precisely so the next read reaches Bitbucket, and this must not be what answers it
129 * instead.
130 */
131const REVISION_PATCH_TTL = Duration.seconds(5);
132const REVISION_PATCH_CAPACITY = 16;
133export interface BitbucketPullRequestBatch {
134 readonly items: ReadonlyArray<BitbucketPullRequest>;
135 readonly truncated: boolean;
136}
137
138export class BitbucketPullRequestApi extends Context.Service<
139 BitbucketPullRequestApi,
140 {
141 readonly getViewer: () => Effect.Effect<string, BitbucketPullRequestApiError>;
142
143 readonly listPullRequests: (input: {
144 readonly repository: string;
145 readonly state: PullRequestListState;
146 readonly limit: number;
147 readonly query?: string | undefined;
148 readonly cursor?: ProviderListCursor | 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 /**
175 * Answers with every file the patch carries rather than only the paths asked about, since
176 * reading one file's version here means parsing all of them. `complete` is false for a patch
177 * cut short, which cannot speak for what came after the cut.
178 */
179 readonly getFileRevisions: (input: {
180 readonly repository: string;
181 readonly number: number;
182 readonly paths: ReadonlyArray<string>;
183 }) => Effect.Effect<
184 { readonly revisions: ReadonlyMap<string, string>; readonly complete: boolean },
185 BitbucketPullRequestApiError
186 >;
187
188 readonly getMergeability: (input: {
189 readonly repository: string;
190 readonly number: number;
191 }) => Effect.Effect<PullRequestMergeability, BitbucketPullRequestApiError>;
192
193 readonly listComments: (input: {
194 readonly repository: string;
195 readonly number: number;
196 }) => Effect.Effect<
197 {
198 readonly comments: ReadonlyArray<PullRequestComment>;
199 readonly threads: ReadonlyArray<PullRequestReviewThread>;
200 readonly truncated: boolean;
201 },
202 BitbucketPullRequestApiError
203 >;
204
205 readonly listCommits: (input: {
206 readonly repository: string;
207 readonly number: number;
208 }) => Effect.Effect<ReadonlyArray<PullRequestCommit>, BitbucketPullRequestApiError>;
209
210 readonly listChecks: (input: {
211 readonly repository: string;
212 readonly number: number;
213 }) => Effect.Effect<ReadonlyArray<PullRequestCheck>, BitbucketPullRequestApiError>;
214
215 readonly listReviewerCandidates: (input: {
216 readonly repository: string;
217 readonly number: number;
218 }) => Effect.Effect<PullRequestReviewerCandidateList, BitbucketPullRequestApiError>;
219
220 readonly setReviewerRequest: (input: {
221 readonly repository: string;
222 readonly number: number;
223 readonly reviewers: ReadonlyArray<{ readonly id: string }>;
224 readonly requested: boolean;
225 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
226
227 readonly runAction: (input: {
228 readonly repository: string;
229 readonly number: number;
230 readonly action: PullRequestAction;
231 readonly mergeMethod?: PullRequestMergeMethod;
232 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
233
234 readonly updateChangeRequest: (input: {
235 readonly repository: string;
236 readonly number: number;
237 readonly title?: string | undefined;
238 readonly body?: string | undefined;
239 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
240
241 readonly comment: (input: {
242 readonly repository: string;
243 readonly number: number;
244 readonly body: string;
245 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
246
247 readonly updateComment: (input: {
248 readonly repository: string;
249 readonly number: number;
250 readonly commentId: string;
251 readonly body: string;
252 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
253
254 readonly submitReview: (input: {
255 readonly repository: string;
256 readonly number: number;
257 readonly verdict: PullRequestReviewVerdict;
258 readonly body: string;
259 readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>;
260 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
261
262 readonly replyToComment: (input: {
263 readonly repository: string;
264 readonly number: number;
265 readonly commentId: string;
266 readonly body: string;
267 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
268
269 readonly setCommentResolution: (input: {
270 readonly repository: string;
271 readonly number: number;
272 readonly commentId: string;
273 readonly resolved: boolean;
274 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
275 }
276>()("@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi") {}
277
278function repositorySegments(
279 repository: string,
280): Result.Result<
281 { readonly workspace: string; readonly slug: string },
282 BitbucketRepositoryUnsupportedError
283> {
284 const segments = repository
285 .split("/")
286 .map((segment) => segment.trim())
287 .filter((segment) => segment.length > 0);
288 const [workspace, slug] = segments;
289 if (segments.length !== 2 || workspace === undefined || slug === undefined) {
290 return Result.fail(new BitbucketRepositoryUnsupportedError({ repository }));
291 }
292 return Result.succeed({ workspace, slug });
293}
294
295function repositoryPathOf(segments: { readonly workspace: string; readonly slug: string }): string {
296 return `/repositories/${encodeURIComponent(segments.workspace)}/${encodeURIComponent(
297 segments.slug,
298 )}`;
299}
300
301function isCommitSha(value: string): boolean {
302 return /^[0-9a-f]{7,64}$/i.test(value);
303}
304
305/**
306 * Bitbucket unions repeated `state` parameters, so a tab that spans several of its states asks
307 * for each.
308 */
309function stateParams(state: PullRequestListState): ReadonlyArray<string> {
310 switch (state) {
311 case "open":
312 return ["OPEN"];
313 case "merged":
314 return ["MERGED"];
315 case "closed":
316 return ["DECLINED", "SUPERSEDED"];
317 case "all":
318 return ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"];
319 }
320}
321
322/**
323 * The parentheses matter, because the expression is ANDed with the state filter beside it and
324 * an unbracketed `OR` would swallow it.
325 */
326function searchFilter(query: string): string {
327 const literal = filterLiteral(query);
328 return `(title ~ "${literal}" OR description ~ "${literal}")`;
329}
330
331/**
332 * The backslash is escaped first, or escaping the quote would only produce a literal
333 * backslash followed by a live quote.
334 */
335function filterLiteral(value: string): string {
336 return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
337}
338
339function mergeStrategy(method: PullRequestMergeMethod | undefined): string {
340 switch (method) {
341 case "squash":
342 return "squash";
343 case "rebase":
344 return "rebase_fast_forward";
345 default:
346 return "merge_commit";
347 }
348}
349
350function bitbucketReviewPosition(
351 position: PullRequestReviewPosition,
352): { readonly from: number } | { readonly to: number } {
353 switch (position.kind) {
354 case "added":
355 return { to: position.newLine };
356 case "deleted":
357 return { from: position.oldLine };
358 case "context":
359 return position.side === "left" ? { from: position.oldLine } : { to: position.newLine };
360 }
361}
362
363/** @public Service construction is part of the canonical Effect module API. */
364export const make = Effect.gen(function* () {
365 const bitbucket = yield* BitbucketApi.BitbucketApi;
366
367 const withRepository = <A>(
368 repository: string,
369 use: (
370 path: string,
371 workspace: string,
372 slug: string,
373 ) => Effect.Effect<A, BitbucketPullRequestApiError>,
374 ): Effect.Effect<A, BitbucketPullRequestApiError> => {
375 const segments = repositorySegments(repository);
376 return Result.isSuccess(segments)
377 ? use(repositoryPathOf(segments.success), segments.success.workspace, segments.success.slug)
378 : Effect.fail(segments.failure);
379 };
380
381 const listPage = (input: {
382 readonly url: string;
383 readonly limit: number;
384 readonly page: number;
385 readonly collected: ReadonlyArray<BitbucketPullRequest>;
386 }): Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError> =>
387 bitbucket.request({ method: "GET", url: input.url }).pipe(
388 Effect.flatMap((response) => {
389 const decoded = decodePullRequestPageJson(response.body);
390 if (!Result.isSuccess(decoded)) {
391 return Effect.fail(
392 new BitbucketPullRequestReadError({
393 operation: "listPullRequests",
394 cause: decoded.failure,
395 }),
396 );
397 }
398 const collected = [...input.collected, ...decoded.success.items];
399 const next = decoded.success.next;
400 if (next === null || collected.length >= input.limit || input.page >= MAX_LIST_PAGES) {
401 return Effect.succeed({
402 items: collected.slice(0, input.limit),
403 truncated: next !== null || collected.length > input.limit,
404 });
405 }
406 return listPage({ ...input, url: next, page: input.page + 1, collected });
407 }),
408 );
409
410 const readPage = <A>(input: {
411 readonly operation: string;
412 readonly url: string;
413 readonly decode: (body: string) => Result.Result<A, unknown>;
414 }): Effect.Effect<A, BitbucketPullRequestApiError> =>
415 bitbucket.request({ method: "GET", url: input.url }).pipe(
416 Effect.flatMap((response) => {
417 const decoded = input.decode(response.body);
418 return Result.isSuccess(decoded)
419 ? Effect.succeed(decoded.success)
420 : Effect.fail(
421 new BitbucketPullRequestReadError({
422 operation: input.operation,
423 cause: decoded.failure,
424 }),
425 );
426 }),
427 );
428
429 /**
430 * Threads are assembled once at the end rather than per page, because a reply and the remark
431 * it answers can land either side of a page boundary.
432 */
433 const commentsPage = (input: {
434 readonly url: string;
435 readonly page: number;
436 readonly comments: ReadonlyArray<PullRequestComment>;
437 readonly entries: ReadonlyArray<BitbucketRawComment>;
438 }): Effect.Effect<
439 {
440 readonly comments: ReadonlyArray<PullRequestComment>;
441 readonly threads: ReadonlyArray<PullRequestReviewThread>;
442 readonly truncated: boolean;
443 },
444 BitbucketPullRequestApiError
445 > =>
446 readPage({ operation: "listComments", url: input.url, decode: decodeCommentsJson }).pipe(
447 Effect.flatMap((page) => {
448 const comments = [...input.comments, ...page.comments];
449 const entries = [...input.entries, ...page.entries];
450 if (page.next !== null && input.page < CONVERSATION_PAGES) {
451 return commentsPage({ url: page.next, page: input.page + 1, comments, entries });
452 }
453 return Effect.succeed({
454 comments,
455 threads: buildReviewThreads(entries),
456 truncated: page.next !== null,
457 });
458 }),
459 );
460
461 const itemPages = <A>(input: {
462 readonly operation: string;
463 readonly url: string;
464 readonly decode: (
465 body: string,
466 ) => Result.Result<{ readonly items: ReadonlyArray<A>; readonly next: string | null }, unknown>;
467 readonly items: ReadonlyArray<A>;
468 /** Commit pages are individually oldest-first, so older pages are prepended. */
469 readonly prepend: boolean;
470 }): Effect.Effect<ReadonlyArray<A>, BitbucketPullRequestApiError> =>
471 readPage({ operation: input.operation, url: input.url, decode: input.decode }).pipe(
472 Effect.flatMap((page) => {
473 const items = input.prepend
474 ? [...page.items, ...input.items]
475 : [...input.items, ...page.items];
476 return page.next === null
477 ? Effect.succeed(items)
478 : itemPages({ ...input, url: page.next, items });
479 }),
480 );
481
482 const diffStatPages = (input: {
483 readonly url: string;
484 readonly totals: BitbucketDiffStat;
485 }): Effect.Effect<BitbucketDiffStat, BitbucketPullRequestApiError> =>
486 readPage({ operation: "getDiffStat", url: input.url, decode: decodeDiffstatJson }).pipe(
487 Effect.flatMap((page) => {
488 const totals = {
489 additions: input.totals.additions + page.additions,
490 deletions: input.totals.deletions + page.deletions,
491 changedFiles: input.totals.changedFiles + page.changedFiles,
492 };
493 return page.next === null
494 ? Effect.succeed(totals)
495 : diffStatPages({ url: page.next, totals });
496 }),
497 );
498
499 const pullRequestDiff = (input: {
500 readonly repository: string;
501 readonly number: number;
502 readonly commit?: string | undefined;
503 }): Effect.Effect<
504 { readonly patch: string; readonly truncated: boolean },
505 BitbucketPullRequestApiError
506 > =>
507 input.commit !== undefined && !isCommitSha(input.commit)
508 ? Effect.fail(new BitbucketDiffCommitError())
509 : withRepository(input.repository, (path) =>
510 bitbucket
511 .request({
512 method: "GET",
513 url:
514 input.commit === undefined
515 ? `${path}/pullrequests/${input.number}/diff`
516 : `${path}/diff/${input.commit}`,
517 maxBytes: DIFF_MAX_BYTES,
518 })
519 .pipe(
520 Effect.map((response) => ({ patch: response.body, truncated: response.truncated })),
521 ),
522 );
523
524 /**
525 * The parsed answer rather than the patch, which at this capacity would hold sixteen bodies
526 * of up to the byte ceiling each resident, and saves walking a patch of a hundred thousand
527 * lines again on every tick.
528 */
529 const revisionPatches = yield* Cache.makeWith(
530 (key: string) => {
531 const [repository, number] = JSON.parse(key) as [string, number];
532 return pullRequestDiff({ repository, number }).pipe(
533 Effect.map((diff) => ({
534 revisions: parseDiffFileRevisions(diff.patch),
535 truncated: diff.truncated,
536 })),
537 );
538 },
539 {
540 capacity: REVISION_PATCH_CAPACITY,
541 timeToLive: (exit) => (Exit.isSuccess(exit) ? REVISION_PATCH_TTL : Duration.zero),
542 },
543 );
544
545 return BitbucketPullRequestApi.of({
546 getViewer: () =>
547 bitbucket.request({ method: "GET", url: "/user" }).pipe(
548 Effect.flatMap((response): Effect.Effect<string, BitbucketPullRequestApiError> => {
549 const decoded = decodeViewerJson(response.body);
550 if (!Result.isSuccess(decoded)) {
551 return Effect.fail(
552 new BitbucketPullRequestReadError({ operation: "getViewer", cause: decoded.failure }),
553 );
554 }
555 return decoded.success === null
556 ? Effect.fail(new BitbucketViewerUnavailableError())
557 : Effect.succeed(decoded.success);
558 }),
559 ),
560
561 listPullRequests: (input) =>
562 withRepository(input.repository, (path) => {
563 const search = input.query?.trim() ?? "";
564 // The boundary instant is read inclusively — the rows already sent at it come back and
565 // the caller drops them, which is what keeps their neighbours at the same instant from
566 // being skipped.
567 const predicates = [
568 ...(search.length === 0 ? [] : [searchFilter(search)]),
569 ...(input.cursor === undefined ? [] : [`updated_on <= ${input.cursor.updatedBefore}`]),
570 ];
571 return listPage({
572 // Reviewers are not on a listing by default, and `viewerReviewRequested` needs them.
573 url: `${path}/pullrequests?${stateParams(input.state)
574 .map((state) => `state=${state}`)
575 .join("&")}&pagelen=${MAX_PAGE_SIZE}&sort=-updated_on&fields=%2Bvalues.reviewers${
576 predicates.length === 0 ? "" : `&q=${encodeURIComponent(predicates.join(" AND "))}`
577 }`,
578 limit: input.limit,
579 page: 1,
580 collected: [],
581 });
582 }),
583
584 getPullRequest: (input) =>
585 withRepository(input.repository, (path) =>
586 readPage({
587 operation: "getPullRequest",
588 // `closed_on` is left out of the default representation. It is the only merge or
589 // decline time Bitbucket states on the pull request itself, and settlement needs it.
590 url: `${path}/pullrequests/${input.number}?fields=%2Bclosed_on`,
591 decode: decodePullRequestJson,
592 }),
593 ),
594
595 // Bitbucket has retired permission endpoints before (CHANGE-2770), and some credentials may
596 // not reach `/user` endpoints at all. A 403, 404 or 410 here is read as a permission that
597 // could not be learned, the same as an empty page: it grants, and the write itself says why
598 // if the account may not do it. Other failures (a bad token, a network fault) still fail.
599 getRepositoryPermission: (input) =>
600 withRepository(input.repository, (_path, workspace, slug) =>
601 readPage({
602 operation: "getRepositoryPermission",
603 url: `/user/workspaces/${encodeURIComponent(workspace)}/permissions/repositories?q=${encodeURIComponent(
604 `repository.full_name="${filterLiteral(`${workspace}/${slug}`)}"`,
605 )}`,
606 decode: decodeRepositoryPermissionJson,
607 }),
608 ).pipe(Effect.catchIf(isRepositoryPermissionUnavailableError, () => Effect.succeed(true))),
609
610 getPullRequestDiff: pullRequestDiff,
611
612 getFileRevisions: (input) =>
613 input.paths.length === 0
614 ? Effect.succeed({ revisions: new Map(), complete: false })
615 : Cache.get(revisionPatches, JSON.stringify([input.repository, input.number])).pipe(
616 Effect.map((diff) => {
617 const revisions = new Map(diff.revisions);
618 // A patch cut short at the byte ceiling says nothing about the files past the cut,
619 // so those paths are left out rather than reported as removed.
620 if (!diff.truncated) {
621 for (const path of input.paths) {
622 if (!revisions.has(path)) revisions.set(path, "");
623 }
624 }
625 return { revisions, complete: !diff.truncated };
626 }),
627 ),
628
629 getDiffStat: (input) =>
630 withRepository(input.repository, (path) =>
631 diffStatPages({
632 url: `${path}/pullrequests/${input.number}/diffstat?pagelen=${MAX_PAGE_SIZE}`,
633 totals: { additions: 0, deletions: 0, changedFiles: 0 },
634 }),
635 ),
636
637 getMergeability: (input) =>
638 withRepository(input.repository, (path) =>
639 readPage({
640 operation: "getMergeability",
641 url: `${path}/pullrequests/${input.number}/conflicts`,
642 decode: decodeConflictsJson,
643 }),
644 ),
645
646 listComments: (input) =>
647 withRepository(input.repository, (path) =>
648 commentsPage({
649 url: `${path}/pullrequests/${input.number}/comments?pagelen=${CONVERSATION_PAGE_SIZE}`,
650 page: 1,
651 comments: [],
652 entries: [],
653 }),
654 ),
655
656 listCommits: (input) =>
657 withRepository(input.repository, (path) =>
658 itemPages({
659 operation: "listCommits",
660 url: `${path}/pullrequests/${input.number}/commits?pagelen=${CONVERSATION_PAGE_SIZE}`,
661 decode: decodeCommitsJson,
662 items: [],
663 prepend: true,
664 }),
665 ),
666
667 listChecks: (input) =>
668 withRepository(input.repository, (path) =>
669 itemPages({
670 operation: "listChecks",
671 url: `${path}/pullrequests/${input.number}/statuses?pagelen=${CONVERSATION_PAGE_SIZE}`,
672 decode: decodeStatusesJson,
673 items: [],
674 prepend: false,
675 }),
676 ),
677
678 listReviewerCandidates: (input) =>
679 withRepository(input.repository, (path, workspace) =>
680 Effect.all(
681 [
682 readPage({
683 operation: "getPullRequest",
684 url: `${path}/pullrequests/${input.number}`,
685 decode: decodePullRequestJson,
686 }),
687 readPage({
688 operation: "listReviewerCandidates",
689 url: `/workspaces/${encodeURIComponent(workspace)}/members?pagelen=${MAX_PAGE_SIZE}`,
690 decode: decodeWorkspaceMembersJson,
691 }),
692 ],
693 { concurrency: 2 },
694 ).pipe(
695 Effect.map(([pullRequest, members]) => {
696 const requested = new Set(pullRequest.reviewerIds);
697 const author = pullRequest.author?.login;
698 return {
699 // The author is dropped rather than shown unusable: Bitbucket refuses to make the
700 // person who opened a pull request its reviewer.
701 candidates: members.items.flatMap((candidate) =>
702 candidate.login === author
703 ? []
704 : [{ ...candidate, isRequested: requested.has(candidate.id) }],
705 ),
706 truncated: members.next !== null,
707 };
708 }),
709 ),
710 ),
711
712 setReviewerRequest: (input) =>
713 withRepository(input.repository, (path) => {
714 const pullRequest = `${path}/pullrequests/${input.number}`;
715 return readPage({
716 operation: "getPullRequest",
717 url: pullRequest,
718 decode: decodePullRequestJson,
719 }).pipe(
720 Effect.flatMap((current) => {
721 // Bitbucket has no endpoint that adds or removes one reviewer: the pull request's
722 // `reviewers` is written whole, so the set that is already there is read first and
723 // the change applied to it.
724 const uuids = new Set(current.reviewerIds);
725 for (const reviewer of input.reviewers) {
726 if (input.requested) uuids.add(reviewer.id);
727 else uuids.delete(reviewer.id);
728 }
729 return bitbucket.request({
730 method: "PUT",
731 url: pullRequest,
732 body: JSON.stringify({ reviewers: [...uuids].map((uuid) => ({ uuid })) }),
733 });
734 }),
735 Effect.asVoid,
736 );
737 }),
738
739 runAction: (input) =>
740 withRepository(input.repository, (path) => {
741 const pullRequest = `${path}/pullrequests/${input.number}`;
742 if (input.action === "merge") {
743 return bitbucket
744 .request({
745 method: "POST",
746 url: `${pullRequest}/merge`,
747 body: JSON.stringify({ merge_strategy: mergeStrategy(input.mergeMethod) }),
748 })
749 .pipe(Effect.asVoid);
750 }
751 return bitbucket
752 .request({ method: "POST", url: `${pullRequest}/decline` })
753 .pipe(Effect.asVoid);
754 }),
755
756 updateChangeRequest: (input) =>
757 withRepository(input.repository, (path) =>
758 // Only the words this call rewrites travel in the body: as `setReviewerRequest` above
759 // relies on, Bitbucket's PUT is a partial update, so any field left out is left as it
760 // was — sending `reviewers` back here would overwrite a change another user made to it
761 // between this call being issued and the request landing.
762 bitbucket
763 .request({
764 method: "PUT",
765 url: `${path}/pullrequests/${input.number}`,
766 body: JSON.stringify({
767 ...(input.title === undefined ? {} : { title: input.title }),
768 ...(input.body === undefined ? {} : { description: input.body }),
769 }),
770 })
771 .pipe(Effect.asVoid),
772 ),
773
774 comment: (input) =>
775 withRepository(input.repository, (path) =>
776 bitbucket
777 .request({
778 method: "POST",
779 url: `${path}/pullrequests/${input.number}/comments`,
780 body: JSON.stringify({ content: { raw: input.body } }),
781 })
782 .pipe(Effect.asVoid),
783 ),
784
785 updateComment: (input) =>
786 withRepository(input.repository, (path) =>
787 bitbucket
788 .request({
789 method: "PUT",
790 url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
791 input.commentId,
792 )}`,
793 body: JSON.stringify({ content: { raw: input.body } }),
794 })
795 .pipe(Effect.asVoid),
796 ),
797
798 submitReview: (input) =>
799 withRepository(input.repository, (path) =>
800 Effect.gen(function* () {
801 const pullRequest = `${path}/pullrequests/${input.number}`;
802 // Bitbucket has no pending review, so a review is replayed as the requests it is
803 // made of: the line comments, then the summary, then the verdict. The verdict goes
804 // last so a review that fails part-way is never left standing as an approval.
805 yield* Effect.forEach(
806 input.comments,
807 (comment) =>
808 bitbucket.request({
809 method: "POST",
810 url: `${pullRequest}/comments`,
811 body: JSON.stringify({
812 content: { raw: comment.body },
813 inline: {
814 path: comment.path,
815 ...bitbucketReviewPosition(comment.position),
816 },
817 }),
818 }),
819 { discard: true },
820 );
821 if (input.body.trim().length > 0) {
822 yield* bitbucket.request({
823 method: "POST",
824 url: `${pullRequest}/comments`,
825 // @effect-diagnostics-next-line preferSchemaOverJson:off
826 body: JSON.stringify({ content: { raw: input.body } }),
827 });
828 }
829 if (input.verdict === "approve") {
830 yield* bitbucket.request({ method: "POST", url: `${pullRequest}/approve` });
831 }
832 if (input.verdict === "request-changes") {
833 yield* bitbucket.request({ method: "POST", url: `${pullRequest}/request-changes` });
834 }
835 }),
836 ),
837
838 replyToComment: (input) =>
839 withRepository(input.repository, (path) =>
840 bitbucket
841 .request({
842 method: "POST",
843 url: `${path}/pullrequests/${input.number}/comments`,
844 body: JSON.stringify({
845 content: { raw: input.body },
846 parent: { id: Number(input.commentId) },
847 }),
848 })
849 .pipe(Effect.asVoid),
850 ),
851
852 setCommentResolution: (input) =>
853 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
866export const layer = Layer.effect(BitbucketPullRequestApi, make);