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

BitbucketPullRequestApi.ts

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