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

BitbucketPullRequestApi.ts

863 lines32.4 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Result from "effect/Result";
5import * as Schema from "effect/Schema";
6import type {
7 PullRequestAction,
8 PullRequestCheck,
9 PullRequestComment,
10 PullRequestCommit,
11 PullRequestListState,
12 PullRequestMergeMethod,
13 PullRequestMergeability,
14 PullRequestReviewCommentDraft,
15 PullRequestReviewPosition,
16 PullRequestReviewThread,
17 PullRequestReviewVerdict,
18 PullRequestReviewerCandidateList,
19} from "@t3tools/contracts";
20​
21import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";
22import {
23 buildReviewThreads,
24 decodeCommentsJson,
25 decodeCommitsJson,
26 decodeConflictsJson,
27 decodeDiffstatJson,
28 decodePullRequestJson,
29 decodePullRequestPageJson,
30 decodeRepositoryPermissionJson,
31 decodeStatusesJson,
32 decodeViewerJson,
33 decodeWorkspaceMembersJson,
34 type BitbucketDiffStat,
35 type BitbucketPullRequest,
36 type BitbucketRawComment,
37} from "./bitbucketPullRequestJson.ts";
38import type { ProviderListCursor } from "./PullRequestProvider.ts";
39​
40/**
41 * Names the read that produced unusable output, so a failure reports the call it came from
42 * rather than borrowing another operation's message.
43 */
44export class BitbucketPullRequestReadError extends Schema.TaggedErrorClass<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 }
59​
60/** Not a decode failure: Bitbucket answered, the account it answered for just has no handle. */
61export class BitbucketViewerUnavailableError extends Schema.TaggedErrorClass<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 }
73​
74/** A repository that is not `workspace/slug`, which is the only form Bitbucket addresses. */
75export class BitbucketRepositoryUnsupportedError extends Schema.TaggedErrorClass<BitbucketRepositoryUnsupportedError>()(
76 "BitbucketRepositoryUnsupportedError",
77 {
78 repository: Schema.String,
79 },
80) {
81 get detail(): string {
82 return "A Bitbucket repository is addressed as workspace/repository.";
83 }
84​
85 override get message(): string {
86 return `Bitbucket failed in resolveRepository: ${this.detail}`;
87 }
89​
90/** Not a decode failure: the reader named a commit that is not a sha this repository could hold. */
91export class BitbucketDiffCommitError extends Schema.TaggedErrorClass<BitbucketDiffCommitError>()(
92 "BitbucketDiffCommitError",
93 {},
94) {
95 get detail(): string {
96 return "The named commit was not a commit sha.";
97 }
98​
99 override get message(): string {
100 return `Bitbucket failed in getPullRequestDiff: ${this.detail}`;
101 }
103​
104export type BitbucketPullRequestApiError =
105 | BitbucketApi.BitbucketApiError
106 | BitbucketPullRequestReadError
107 | BitbucketViewerUnavailableError
108 | BitbucketRepositoryUnsupportedError
109 | BitbucketDiffCommitError;
110​
111/**
112 * `/user/permissions/repositories` answering CHANGE-2770's removal notice rather than a
113 * permission — Bitbucket sends this for every account now, not only ones it would have refused.
114 */
115function isRepositoryPermissionRemovedError(
116 error: BitbucketPullRequestApiError,
117): error is BitbucketApi.BitbucketResponseError {
118 return error._tag === "BitbucketResponseError" && error.status === 410;
120​
121/**
122 * Bitbucket's own ceiling. Asking for more does not fail — it answers with an empty page and no
123 * error at all, so this is a number to respect rather than to push against.
124 */
125const MAX_PAGE_SIZE = 50;
126/** Pages to walk before a listing is reported as truncated. */
127const MAX_LIST_PAGES = 10;
128/** The page size for pull request conversations, commits, and checks. */
129const CONVERSATION_PAGE_SIZE = 50;
130/**
131 * Pages of the conversation to follow before it is reported as truncated. Bitbucket serves
132 * fifty comments a page, so this is five hundred — beyond any pull request a person is reading,
133 * and an end to a walk whose only other stop is Bitbucket running out.
134 */
135const CONVERSATION_PAGES = 10;
136/** The same ceiling the gh and glab diff reads use. */
137const DIFF_MAX_BYTES = 8 * 1024 * 1024;
138​
139export interface BitbucketPullRequestBatch {
140 readonly items: ReadonlyArray<BitbucketPullRequest>;
141 readonly truncated: boolean;
143​
144export class BitbucketPullRequestApi extends Context.Service<
145 BitbucketPullRequestApi,
146 {
147 /** A function rather than a value, so the request is built per call and not at layer time. */
148 readonly getViewer: () => Effect.Effect<string, BitbucketPullRequestApiError>;
149​
150 readonly listPullRequests: (input: {
151 readonly repository: string;
152 readonly state: PullRequestListState;
153 readonly limit: number;
154 /** Free text, matched against a pull request's title and description. */
155 readonly query?: string | undefined;
156 /** Where to carry on from, as a predicate on `updated_on` beside any other. */
157 readonly cursor?: ProviderListCursor | undefined;
158 }) => Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError>;
159​
160 readonly getPullRequest: (input: {
161 readonly repository: string;
162 readonly number: number;
163 }) => Effect.Effect<BitbucketPullRequest, BitbucketPullRequestApiError>;
164​
165 /** True where the credentials can write to the repository, which is what merging needs. */
166 readonly getRepositoryPermission: (input: {
167 readonly repository: string;
168 }) => Effect.Effect<boolean, BitbucketPullRequestApiError>;
169​
170 readonly getPullRequestDiff: (input: {
171 readonly repository: string;
172 readonly number: number;
173 /** One commit's own changes, rather than everything the pull request carries. */
174 readonly commit?: string | undefined;
175 }) => Effect.Effect<
176 { readonly patch: string; readonly truncated: boolean },
177 BitbucketPullRequestApiError
178 >;
179​
180 readonly getDiffStat: (input: {
181 readonly repository: string;
182 readonly number: number;
183 }) => Effect.Effect<BitbucketDiffStat, BitbucketPullRequestApiError>;
184​
185 readonly getMergeability: (input: {
186 readonly repository: string;
187 readonly number: number;
188 }) => Effect.Effect<PullRequestMergeability, BitbucketPullRequestApiError>;
189​
190 readonly listComments: (input: {
191 readonly repository: string;
192 readonly number: number;
193 }) => Effect.Effect<
194 {
195 readonly comments: ReadonlyArray<PullRequestComment>;
196 readonly threads: ReadonlyArray<PullRequestReviewThread>;
197 readonly truncated: boolean;
198 },
199 BitbucketPullRequestApiError
200 >;
201​
202 readonly listCommits: (input: {
203 readonly repository: string;
204 readonly number: number;
205 }) => Effect.Effect<ReadonlyArray<PullRequestCommit>, BitbucketPullRequestApiError>;
206​
207 readonly listChecks: (input: {
208 readonly repository: string;
209 readonly number: number;
210 }) => Effect.Effect<ReadonlyArray<PullRequestCheck>, BitbucketPullRequestApiError>;
211​
212 /**
213 * Who this pull request may be sent to, and who it has already been sent to. Two reads at
214 * once, because Bitbucket keeps the people on the workspace and the reviewers on the pull
215 * request, and neither answers for the other.
216 */
217 readonly listReviewerCandidates: (input: {
218 readonly repository: string;
219 readonly number: number;
220 }) => Effect.Effect<PullRequestReviewerCandidateList, BitbucketPullRequestApiError>;
221​
222 readonly setReviewerRequest: (input: {
223 readonly repository: string;
224 readonly number: number;
225 readonly reviewers: ReadonlyArray<{ readonly id: string }>;
226 readonly requested: boolean;
227 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
228​
229 readonly runAction: (input: {
230 readonly repository: string;
231 readonly number: number;
232 readonly action: PullRequestAction;
233 readonly mergeMethod?: PullRequestMergeMethod;
234 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
235​
236 readonly updateChangeRequest: (input: {
237 readonly repository: string;
238 readonly number: number;
239 readonly title?: string | undefined;
240 readonly body?: string | undefined;
241 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
242​
243 readonly comment: (input: {
244 readonly repository: string;
245 readonly number: number;
246 readonly body: string;
247 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
248​
249 readonly updateComment: (input: {
250 readonly repository: string;
251 readonly number: number;
252 readonly commentId: string;
253 readonly body: string;
254 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
255​
256 readonly submitReview: (input: {
257 readonly repository: string;
258 readonly number: number;
259 readonly verdict: PullRequestReviewVerdict;
260 readonly body: string;
261 readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>;
262 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
263​
264 readonly replyToComment: (input: {
265 readonly repository: string;
266 readonly number: number;
267 readonly commentId: string;
268 readonly body: string;
269 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
270​
271 readonly setCommentResolution: (input: {
272 readonly repository: string;
273 readonly number: number;
274 readonly commentId: string;
275 readonly resolved: boolean;
276 }) => Effect.Effect<void, BitbucketPullRequestApiError>;
277 }
278>()("t3/pullRequest/BitbucketPullRequestApi") {}
279​
280/** `workspace/slug`; Bitbucket has no deeper nesting to address. */
281function repositorySegments(
282 repository: string,
283): Result.Result<
284 { readonly workspace: string; readonly slug: string },
285 BitbucketRepositoryUnsupportedError
286> {
287 const segments = repository
288 .split("/")
289 .map((segment) => segment.trim())
290 .filter((segment) => segment.length > 0);
291 const [workspace, slug] = segments;
292 if (segments.length !== 2 || workspace === undefined || slug === undefined) {
293 return Result.fail(new BitbucketRepositoryUnsupportedError({ repository }));
294 }
295 return Result.succeed({ workspace, slug });
297​
298function repositoryPathOf(segments: { readonly workspace: string; readonly slug: string }): string {
299 return `/repositories/${encodeURIComponent(segments.workspace)}/${encodeURIComponent(
300 segments.slug,
301 )}`;
303​
304/**
305 * A commit sha arrives from the reader and goes straight into a request path, so it is checked
306 * rather than trusted: hexadecimal only, from the shortest abbreviation a host prints up to a
307 * whole sha.
308 */
309function isCommitSha(value: string): boolean {
310 return /^[0-9a-f]{7,64}$/i.test(value);
312​
313/**
314 * Bitbucket unions repeated `state` parameters, so a tab that spans several of its states asks
315 * for each. It separates a declined pull request from one superseded by another, and both read
316 * as closed here.
317 */
318function stateParams(state: PullRequestListState): ReadonlyArray<string> {
319 switch (state) {
320 case "open":
321 return ["OPEN"];
322 case "merged":
323 return ["MERGED"];
324 case "closed":
325 return ["DECLINED", "SUPERSEDED"];
326 case "all":
327 return ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"];
328 }
330​
331/**
332 * Bitbucket has no search term, only a filter expression, so free text becomes one: a
333 * case-insensitive contains against the two fields a pull request carries words in. The
334 * parentheses matter, because the expression is ANDed with the state filter beside it and an
335 * unbracketed `OR` would swallow it.
336 *
337 * A string literal in that grammar is delimited by double quotes, so the reader's text is
338 * escaped before it goes inside one — a quote would otherwise end the literal and leave the
339 * rest of the text standing as filter syntax. The whole expression is then URL-encoded, so
340 * nothing in it reaches the query string as a parameter of its own.
341 */
342function searchFilter(query: string): string {
343 const literal = filterLiteral(query);
344 return `(title ~ "${literal}" OR description ~ "${literal}")`;
346​
347/**
348 * Text as a string literal of Bitbucket's filter grammar. The backslash is escaped first, or
349 * escaping the quote would only produce a literal backslash followed by a live quote.
350 */
351function filterLiteral(value: string): string {
352 return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
354​
355/** Bitbucket's merge strategies, named differently from the three the contract carries. */
356function mergeStrategy(method: PullRequestMergeMethod | undefined): string {
357 switch (method) {
358 case "squash":
359 return "squash";
360 case "rebase":
361 // The linear history GitHub calls "rebase and merge".
362 return "rebase_fast_forward";
363 default:
364 return "merge_commit";
365 }
367​
368function bitbucketReviewPosition(
369 position: PullRequestReviewPosition,
370): { readonly from: number } | { readonly to: number } {
371 switch (position.kind) {
372 case "added":
373 return { to: position.newLine };
374 case "deleted":
375 return { from: position.oldLine };
376 case "context":
377 return position.side === "left" ? { from: position.oldLine } : { to: position.newLine };
378 }
380​
381export const make = Effect.gen(function* () {
382 const bitbucket = yield* BitbucketApi.BitbucketApi;
383​
384 /**
385 * The repository's own path, and the workspace above it — which the people who may review are
386 * kept on rather than on the repository, so both are handed over at once.
387 */
388 const withRepository = <A>(
389 repository: string,
390 use: (path: string, workspace: string) => Effect.Effect<A, BitbucketPullRequestApiError>,
391 ): Effect.Effect<A, BitbucketPullRequestApiError> => {
392 const segments = repositorySegments(repository);
393 return Result.isSuccess(segments)
394 ? use(repositoryPathOf(segments.success), segments.success.workspace)
395 : Effect.fail(segments.failure);
396 };
397​
398 /**
399 * Bitbucket pages with a cursor rather than an offset, so the walk follows the `next` URL it
400 * sends. It stops once the caller's page is filled, when Bitbucket reports no next page, or at
401 * the page cap — and anything but running out of pages means there is more to be had.
402 */
403 const listPage = (input: {
404 readonly url: string;
405 readonly limit: number;
406 readonly page: number;
407 readonly collected: ReadonlyArray<BitbucketPullRequest>;
408 }): Effect.Effect<BitbucketPullRequestBatch, BitbucketPullRequestApiError> =>
409 bitbucket.request({ method: "GET", url: input.url }).pipe(
410 Effect.flatMap((response) => {
411 const decoded = decodePullRequestPageJson(response.body);
412 if (!Result.isSuccess(decoded)) {
413 return Effect.fail(
414 new BitbucketPullRequestReadError({
415 operation: "listPullRequests",
416 cause: decoded.failure,
417 }),
418 );
419 }
420 const collected = [...input.collected, ...decoded.success.items];
421 const next = decoded.success.next;
422 if (next === null || collected.length >= input.limit || input.page >= MAX_LIST_PAGES) {
423 return Effect.succeed({
424 items: collected.slice(0, input.limit),
425 // Bitbucket pages in fifties whatever was asked for, so a walk that stopped on the
426 // count rather than on the last page is holding rows it is about to drop. Those are
427 // more results just as surely as another page would be.
428 truncated: next !== null || collected.length > input.limit,
429 });
430 }
431 return listPage({ ...input, url: next, page: input.page + 1, collected });
432 }),
433 );
434​
435 const readPage = <A>(input: {
436 readonly operation: string;
437 readonly url: string;
438 readonly decode: (body: string) => Result.Result<A, unknown>;
439 }): Effect.Effect<A, BitbucketPullRequestApiError> =>
440 bitbucket.request({ method: "GET", url: input.url }).pipe(
441 Effect.flatMap((response) => {
442 const decoded = input.decode(response.body);
443 return Result.isSuccess(decoded)
444 ? Effect.succeed(decoded.success)
445 : Effect.fail(
446 new BitbucketPullRequestReadError({
447 operation: input.operation,
448 cause: decoded.failure,
449 }),
450 );
451 }),
452 );
453​
454 /**
455 * The conversation, following the `next` Bitbucket sends until it sends none. Threads are
456 * assembled once at the end rather than per page, because a reply and the remark it answers
457 * can land either side of a page boundary.
458 */
459 const commentsPage = (input: {
460 readonly url: string;
461 readonly page: number;
462 readonly comments: ReadonlyArray<PullRequestComment>;
463 readonly entries: ReadonlyArray<BitbucketRawComment>;
464 }): Effect.Effect<
465 {
466 readonly comments: ReadonlyArray<PullRequestComment>;
467 readonly threads: ReadonlyArray<PullRequestReviewThread>;
468 readonly truncated: boolean;
469 },
470 BitbucketPullRequestApiError
471 > =>
472 readPage({ operation: "listComments", url: input.url, decode: decodeCommentsJson }).pipe(
473 Effect.flatMap((page) => {
474 const comments = [...input.comments, ...page.comments];
475 const entries = [...input.entries, ...page.entries];
476 if (page.next !== null && input.page < CONVERSATION_PAGES) {
477 return commentsPage({ url: page.next, page: input.page + 1, comments, entries });
478 }
479 return Effect.succeed({
480 comments,
481 threads: buildReviewThreads(entries),
482 truncated: page.next !== null,
483 });
484 }),
485 );
486​
487 /** Walks a Bitbucket cursor to its end and combines every decoded item. */
488 const itemPages = <A>(input: {
489 readonly operation: string;
490 readonly url: string;
491 readonly decode: (
492 body: string,
493 ) => Result.Result<{ readonly items: ReadonlyArray<A>; readonly next: string | null }, unknown>;
494 readonly items: ReadonlyArray<A>;
495 /** Commit pages are individually oldest-first, so older pages are prepended. */
496 readonly prepend: boolean;
497 }): Effect.Effect<ReadonlyArray<A>, BitbucketPullRequestApiError> =>
498 readPage({ operation: input.operation, url: input.url, decode: input.decode }).pipe(
499 Effect.flatMap((page) => {
500 const items = input.prepend
501 ? [...page.items, ...input.items]
502 : [...input.items, ...page.items];
503 return page.next === null
504 ? Effect.succeed(items)
505 : itemPages({ ...input, url: page.next, items });
506 }),
507 );
508​
509 /** Diffstat has one aggregate per page, so its totals are folded while following `next`. */
510 const diffStatPages = (input: {
511 readonly url: string;
512 readonly totals: BitbucketDiffStat;
513 }): Effect.Effect<BitbucketDiffStat, BitbucketPullRequestApiError> =>
514 readPage({ operation: "getDiffStat", url: input.url, decode: decodeDiffstatJson }).pipe(
515 Effect.flatMap((page) => {
516 const totals = {
517 additions: input.totals.additions + page.additions,
518 deletions: input.totals.deletions + page.deletions,
519 changedFiles: input.totals.changedFiles + page.changedFiles,
520 };
521 return page.next === null
522 ? Effect.succeed(totals)
523 : diffStatPages({ url: page.next, totals });
524 }),
525 );
526​
527 return BitbucketPullRequestApi.of({
528 getViewer: () =>
529 bitbucket.request({ method: "GET", url: "/user" }).pipe(
530 Effect.flatMap((response): Effect.Effect<string, BitbucketPullRequestApiError> => {
531 const decoded = decodeViewerJson(response.body);
532 if (!Result.isSuccess(decoded)) {
533 return Effect.fail(
534 new BitbucketPullRequestReadError({ operation: "getViewer", cause: decoded.failure }),
535 );
536 }
537 return decoded.success === null
538 ? Effect.fail(new BitbucketViewerUnavailableError())
539 : Effect.succeed(decoded.success);
540 }),
541 ),
542​
543 listPullRequests: (input) =>
544 withRepository(input.repository, (path) => {
545 const search = input.query?.trim() ?? "";
546 // Both narrowings share the one `q` Bitbucket takes, so they are ANDed rather than one
547 // replacing the other. The boundary instant is read inclusively — the rows already sent
548 // at it come back and the caller drops them, which is what keeps their neighbours at the
549 // same instant from being skipped. A date is a bare literal in this grammar, and this one
550 // was checked against a timestamp's shape before it got here.
551 const predicates = [
552 ...(search.length === 0 ? [] : [searchFilter(search)]),
553 ...(input.cursor === undefined ? [] : [`updated_on <= ${input.cursor.updatedBefore}`]),
554 ];
555 return listPage({
556 // Reviewers are not on a listing by default, and `viewerReviewRequested` needs them.
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 url: `${path}/pullrequests/${input.number}`,
573 decode: decodePullRequestJson,
574 }),
575 ),
576​
577 // Nothing on the repository, the pull request or the workspace states what the credentials
578 // may do, so this endpoint is the one request Bitbucket makes unavoidable. It is asked
579 // alongside the reads the detail was already making, so it costs no round trip of its own.
580 //
581 // Bitbucket permanently removed this endpoint (CHANGE-2770): every account now gets HTTP 410
582 // in place of an answer, whatever it may do. That is the deprecated-endpoint signal, not a
583 // permission being refused, so it is read the same way an unreachable read already is
584 // elsewhere — as a permission that could not be learned, which grants rather than blocks, and
585 // leaves the actual merge or write to say why if the account may not do it. Any other failure
586 // (a bad token, a network fault, an unreadable body) still fails as it did before.
587 getRepositoryPermission: (input) =>
588 withRepository(input.repository, () =>
589 readPage({
590 operation: "getRepositoryPermission",
591 url: `/user/permissions/repositories?q=${encodeURIComponent(
592 `repository.full_name="${filterLiteral(input.repository.trim())}"`,
593 )}`,
594 decode: decodeRepositoryPermissionJson,
595 }),
596 ).pipe(Effect.catchIf(isRepositoryPermissionRemovedError, () => Effect.succeed(true))),
597​
598 getPullRequestDiff: (input) =>
599 input.commit !== undefined && !isCommitSha(input.commit)
600 ? Effect.fail(new BitbucketDiffCommitError())
601 : withRepository(input.repository, (path) =>
602 // Already a unified patch, so it needs no decoding at all — only a bound, which a
603 // diff of any size would otherwise ignore. A commit's own patch sits beside the pull
604 // request's at `/diff/{sha}` and reads the same way.
605 bitbucket
606 .request({
607 method: "GET",
608 url:
609 input.commit === undefined
610 ? `${path}/pullrequests/${input.number}/diff`
611 : `${path}/diff/${input.commit}`,
612 maxBytes: DIFF_MAX_BYTES,
613 })
614 .pipe(
615 Effect.map((response) => ({ patch: response.body, truncated: response.truncated })),
616 ),
617 ),
618​
619 getDiffStat: (input) =>
620 withRepository(input.repository, (path) =>
621 diffStatPages({
622 url: `${path}/pullrequests/${input.number}/diffstat?pagelen=${MAX_PAGE_SIZE}`,
623 totals: { additions: 0, deletions: 0, changedFiles: 0 },
624 }),
625 ),
626​
627 getMergeability: (input) =>
628 withRepository(input.repository, (path) =>
629 readPage({
630 operation: "getMergeability",
631 url: `${path}/pullrequests/${input.number}/conflicts`,
632 decode: decodeConflictsJson,
633 }),
634 ),
635​
636 listComments: (input) =>
637 withRepository(input.repository, (path) =>
638 commentsPage({
639 url: `${path}/pullrequests/${input.number}/comments?pagelen=${CONVERSATION_PAGE_SIZE}`,
640 page: 1,
641 comments: [],
642 entries: [],
643 }),
644 ),
645​
646 listCommits: (input) =>
647 withRepository(input.repository, (path) =>
648 itemPages({
649 operation: "listCommits",
650 url: `${path}/pullrequests/${input.number}/commits?pagelen=${CONVERSATION_PAGE_SIZE}`,
651 decode: decodeCommitsJson,
652 items: [],
653 prepend: true,
654 }),
655 ),
656​
657 listChecks: (input) =>
658 withRepository(input.repository, (path) =>
659 itemPages({
660 operation: "listChecks",
661 url: `${path}/pullrequests/${input.number}/statuses?pagelen=${CONVERSATION_PAGE_SIZE}`,
662 decode: decodeStatusesJson,
663 items: [],
664 prepend: false,
665 }),
666 ),
667​
668 listReviewerCandidates: (input) =>
669 withRepository(input.repository, (path, workspace) =>
670 Effect.all(
671 [
672 readPage({
673 operation: "getPullRequest",
674 url: `${path}/pullrequests/${input.number}`,
675 decode: decodePullRequestJson,
676 }),
677 readPage({
678 operation: "listReviewerCandidates",
679 url: `/workspaces/${encodeURIComponent(workspace)}/members?pagelen=${MAX_PAGE_SIZE}`,
680 decode: decodeWorkspaceMembersJson,
681 }),
682 ],
683 { concurrency: 2 },
684 ).pipe(
685 Effect.map(([pullRequest, members]) => {
686 const requested = new Set(pullRequest.reviewerIds);
687 const author = pullRequest.author?.login;
688 return {
689 // The author is dropped rather than shown unusable: Bitbucket refuses to make the
690 // person who opened a pull request its reviewer.
691 candidates: members.items.flatMap((candidate) =>
692 candidate.login === author
693 ? []
694 : [{ ...candidate, isRequested: requested.has(candidate.id) }],
695 ),
696 truncated: members.next !== null,
697 };
698 }),
699 ),
700 ),
701​
702 setReviewerRequest: (input) =>
703 withRepository(input.repository, (path) => {
704 const pullRequest = `${path}/pullrequests/${input.number}`;
705 return readPage({
706 operation: "getPullRequest",
707 url: pullRequest,
708 decode: decodePullRequestJson,
709 }).pipe(
710 Effect.flatMap((current) => {
711 // Bitbucket has no endpoint that adds or removes one reviewer: the pull request's
712 // `reviewers` is written whole, so the set that is already there is read first and
713 // the change applied to it. Everything else about the pull request is left out of
714 // the body, which leaves it as it was.
715 const uuids = new Set(current.reviewerIds);
716 for (const reviewer of input.reviewers) {
717 if (input.requested) uuids.add(reviewer.id);
718 else uuids.delete(reviewer.id);
719 }
720 return bitbucket.request({
721 method: "PUT",
722 url: pullRequest,
723 body: JSON.stringify({ reviewers: [...uuids].map((uuid) => ({ uuid })) }),
724 });
725 }),
726 Effect.asVoid,
727 );
728 }),
729​
730 runAction: (input) =>
731 withRepository(input.repository, (path) => {
732 const pullRequest = `${path}/pullrequests/${input.number}`;
733 // Only merge and close reach here: the provider declares the others unsupported, so the
734 // surface never offers them.
735 if (input.action === "merge") {
736 return bitbucket
737 .request({
738 method: "POST",
739 url: `${pullRequest}/merge`,
740 body: JSON.stringify({ merge_strategy: mergeStrategy(input.mergeMethod) }),
741 })
742 .pipe(Effect.asVoid);
743 }
744 return bitbucket
745 .request({ method: "POST", url: `${pullRequest}/decline` })
746 .pipe(Effect.asVoid);
747 }),
748​
749 updateChangeRequest: (input) =>
750 withRepository(input.repository, (path) =>
751 // Only the words this call rewrites travel in the body: as `setReviewerRequest` above
752 // relies on, Bitbucket's PUT is a partial update, so any field left out is left as it
753 // was — sending `reviewers` back here would overwrite a change another user made to it
754 // between this call being issued and the request landing.
755 bitbucket
756 .request({
757 method: "PUT",
758 url: `${path}/pullrequests/${input.number}`,
759 body: JSON.stringify({
760 ...(input.title === undefined ? {} : { title: input.title }),
761 ...(input.body === undefined ? {} : { description: input.body }),
762 }),
763 })
764 .pipe(Effect.asVoid),
765 ),
766​
767 comment: (input) =>
768 withRepository(input.repository, (path) =>
769 bitbucket
770 .request({
771 method: "POST",
772 url: `${path}/pullrequests/${input.number}/comments`,
773 // A JSON document rather than a form field, so the body stays text whatever it says.
774 body: JSON.stringify({ content: { raw: input.body } }),
775 })
776 .pipe(Effect.asVoid),
777 ),
778​
779 updateComment: (input) =>
780 withRepository(input.repository, (path) =>
781 bitbucket
782 .request({
783 // Bitbucket keeps a pull request's remarks and its line comments in the one
784 // collection, so this endpoint rewrites either kind.
785 method: "PUT",
786 url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
787 input.commentId,
788 )}`,
789 body: JSON.stringify({ content: { raw: input.body } }),
790 })
791 .pipe(Effect.asVoid),
792 ),
793​
794 submitReview: (input) =>
795 withRepository(input.repository, (path) =>
796 Effect.gen(function* () {
797 const pullRequest = `${path}/pullrequests/${input.number}`;
798 // Bitbucket has no pending review, so a review is replayed as the requests it is
799 // made of: the line comments, then the summary, then the verdict. The verdict goes
800 // last so a review that fails part-way is never left standing as an approval.
801 yield* Effect.forEach(
802 input.comments,
803 (comment) =>
804 bitbucket.request({
805 method: "POST",
806 url: `${pullRequest}/comments`,
807 body: JSON.stringify({
808 content: { raw: comment.body },
809 inline: {
810 path: comment.path,
811 ...bitbucketReviewPosition(comment.position),
812 },
813 }),
814 }),
815 { discard: true },
816 );
817 if (input.body.trim().length > 0) {
818 yield* bitbucket.request({
819 method: "POST",
820 url: `${pullRequest}/comments`,
821 // @effect-diagnostics-next-line preferSchemaOverJson:off
822 body: JSON.stringify({ content: { raw: input.body } }),
823 });
824 }
825 if (input.verdict === "approve") {
826 yield* bitbucket.request({ method: "POST", url: `${pullRequest}/approve` });
827 }
828 if (input.verdict === "request-changes") {
829 yield* bitbucket.request({ method: "POST", url: `${pullRequest}/request-changes` });
830 }
831 }),
832 ),
833​
834 replyToComment: (input) =>
835 withRepository(input.repository, (path) =>
836 bitbucket
837 .request({
838 method: "POST",
839 url: `${path}/pullrequests/${input.number}/comments`,
840 body: JSON.stringify({
841 content: { raw: input.body },
842 parent: { id: Number(input.commentId) },
843 }),
844 })
845 .pipe(Effect.asVoid),
846 ),
847​
848 setCommentResolution: (input) =>
849 withRepository(input.repository, (path) =>
850 bitbucket
851 .request({
852 // Resolving is a sub-resource that is created and deleted, rather than a field.
853 method: input.resolved ? "POST" : "DELETE",
854 url: `${path}/pullrequests/${input.number}/comments/${encodeURIComponent(
855 input.commentId,
856 )}/resolve`,
857 })
858 .pipe(Effect.asVoid),
859 ),
860 });
861});
862​
863export const layer = Layer.effect(BitbucketPullRequestApi, make);