Open History to see the last commit
1import { afterEach, assert, expect, it, vi } from "@effect/vitest";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as TestClock from "effect/testing/TestClock";
6
7import * as BitbucketApi from "./BitbucketApi.ts";
8import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";
9
10const mockedRequest = vi.fn<BitbucketApi.BitbucketApi["Service"]["request"]>();
11
12const layer = it.layer(
13 BitbucketPullRequestApi.layer.pipe(
14 Layer.provide(
15 Layer.mock(BitbucketApi.BitbucketApi)({
16 request: mockedRequest,
17 }),
18 ),
19 ),
20);
21
22function response(body: string) {
23 return { body, truncated: false };
24}
25
26function page(count: number, firstNumber: number, next?: string): string {
27 return JSON.stringify({
28 pagelen: 50,
29 size: count,
30 values: Array.from({ length: count }, (_, index) => ({
31 id: firstNumber + index,
32 title: `Pull request ${firstNumber + index}`,
33 state: "OPEN",
34 created_on: "2026-06-16T05:04:32+00:00",
35 updated_on: "2026-06-16T05:04:33+00:00",
36 source: { branch: { name: "feat/page" } },
37 destination: { branch: { name: "master" } },
38 links: { html: { href: `https://bitbucket.org/acme/web/pull-requests/${firstNumber}` } },
39 })),
40 ...(next === undefined ? {} : { next }),
41 });
42}
43
44function valuePage(values: ReadonlyArray<unknown>, next?: string): string {
45 return JSON.stringify({ values, ...(next === undefined ? {} : { next }) });
46}
47
48const bilal = { uuid: "{bilal}", nickname: "bilal" };
49const octocat = { uuid: "{octocat}", nickname: "octocat" };
50const hubot = { uuid: "{hubot}", nickname: "hubot" };
51
52function pullRequestJson(overrides: Record<string, unknown>): string {
53 return JSON.stringify({
54 id: 7,
55 title: "Pull request 7",
56 state: "OPEN",
57 author: bilal,
58 created_on: "2026-06-16T05:04:32+00:00",
59 updated_on: "2026-06-16T05:04:33+00:00",
60 source: { branch: { name: "feat/page" } },
61 destination: { branch: { name: "master" } },
62 links: { html: { href: "https://bitbucket.org/acme/web/pull-requests/7" } },
63 ...overrides,
64 });
65}
66
67function callAt(index: number) {
68 const call = mockedRequest.mock.calls[index];
69 assert.isDefined(call);
70 return call[0];
71}
72
73function filterOfCall(index: number): string | null {
74 const url = callAt(index).url;
75 return new URLSearchParams(url.slice(url.indexOf("?") + 1)).get("q");
76}
77
78afterEach(() => {
79 mockedRequest.mockReset();
80});
81
82layer("BitbucketPullRequestApi.layer", (it) => {
83 it.effect("asks for reviewers, newest first, at Bitbucket's page ceiling", () =>
84 Effect.gen(function* () {
85 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(3, 1))));
86 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
87
88 const batch = yield* api.listPullRequests({
89 repository: "acme/web",
90 state: "open",
91 limit: 50,
92 });
93
94 assert.strictEqual(batch.items.length, 3);
95 assert.isFalse(batch.truncated);
96 const url = callAt(0).url;
97 expect(url).toContain("/repositories/acme/web/pullrequests");
98 expect(url).toContain("state=OPEN");
99 // Over 50 Bitbucket answers with an empty page and no error, so it is never exceeded.
100 expect(url).toContain("pagelen=50");
101 expect(url).toContain("sort=-updated_on");
102 expect(url).toContain("fields=%2Bvalues.reviewers");
103 }),
104 );
105
106 it.effect("follows the cursor Bitbucket sends rather than counting offsets", () =>
107 Effect.gen(function* () {
108 const next = "https://api.bitbucket.org/2.0/repositories/acme/web/pullrequests?page=2";
109 mockedRequest
110 .mockReturnValueOnce(Effect.succeed(response(page(50, 1, next))))
111 .mockReturnValueOnce(Effect.succeed(response(page(50, 51))));
112 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
113
114 const batch = yield* api.listPullRequests({
115 repository: "acme/web",
116 state: "open",
117 limit: 100,
118 });
119
120 assert.strictEqual(batch.items.length, 100);
121 assert.isFalse(batch.truncated);
122 assert.strictEqual(callAt(1).url, next);
123 }),
124 );
125
126 it.effect("stops at the caller's page and says more remain", () =>
127 Effect.gen(function* () {
128 const next = "https://api.bitbucket.org/2.0/repositories/acme/web/pullrequests?page=2";
129 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(50, 1, next))));
130 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
131
132 const batch = yield* api.listPullRequests({
133 repository: "acme/web",
134 state: "open",
135 limit: 50,
136 });
137
138 assert.strictEqual(batch.items.length, 50);
139 assert.isTrue(batch.truncated);
140 assert.strictEqual(mockedRequest.mock.calls.length, 1);
141 }),
142 );
143
144 it.effect("counts the rows it walked past as more to come", () =>
145 Effect.gen(function* () {
146 // Bitbucket pages in fifties whatever was asked for, so a request for ninety-nine reads a
147 // hundred and drops one.
148 const next = "https://api.bitbucket.org/2.0/repositories/acme/web/pullrequests?page=2";
149 mockedRequest
150 .mockReturnValueOnce(Effect.succeed(response(page(50, 1, next))))
151 .mockReturnValueOnce(Effect.succeed(response(page(50, 51))));
152 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
153
154 const batch = yield* api.listPullRequests({
155 repository: "acme/web",
156 state: "open",
157 limit: 99,
158 });
159
160 assert.strictEqual(batch.items.length, 99);
161 assert.isTrue(batch.truncated);
162 }),
163 );
164
165 it.effect("searches with a filter expression, which is all Bitbucket offers", () =>
166 Effect.gen(function* () {
167 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
168 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
169
170 yield* api.listPullRequests({
171 repository: "acme/web",
172 state: "open",
173 limit: 50,
174 query: "page",
175 });
176
177 expect(filterOfCall(0)).toBe('(title ~ "page" OR description ~ "page")');
178 expect(callAt(0).url).toContain("state=OPEN");
179 }),
180 );
181
182 it.effect("escapes a quote and a backslash, so a search cannot reshape the filter", () =>
183 Effect.gen(function* () {
184 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
185 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
186
187 yield* api.listPullRequests({
188 repository: "acme/web",
189 state: "open",
190 limit: 50,
191 query: String.raw`a\" OR state = "MERGED"`,
192 });
193
194 const literal = String.raw`a\\\" OR state = \"MERGED\"`;
195 expect(filterOfCall(0)).toBe(`(title ~ "${literal}" OR description ~ "${literal}")`);
196 }),
197 );
198
199 it.effect("asks for no filter at all when the reader typed only spaces", () =>
200 Effect.gen(function* () {
201 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
202 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
203
204 yield* api.listPullRequests({
205 repository: "acme/web",
206 state: "open",
207 limit: 50,
208 query: " ",
209 });
210
211 assert.isNull(filterOfCall(0));
212 }),
213 );
214
215 it.effect("carries on from the instant the last slice ended on", () =>
216 Effect.gen(function* () {
217 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
218 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
219
220 yield* api.listPullRequests({
221 repository: "acme/web",
222 state: "open",
223 limit: 50,
224 cursor: { updatedBefore: "2026-07-02T00:00:00.123456+00:00", delivered: 50 },
225 });
226
227 expect(filterOfCall(0)).toBe("updated_on <= 2026-07-02T00:00:00.123456+00:00");
228 expect(callAt(0).url).toContain("sort=-updated_on");
229 }),
230 );
231
232 it.effect("narrows by the reader's words and by where it left off at once", () =>
233 Effect.gen(function* () {
234 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
235 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
236
237 yield* api.listPullRequests({
238 repository: "acme/web",
239 state: "open",
240 limit: 50,
241 query: "page",
242 cursor: { updatedBefore: "2026-07-02T00:00:00+00:00", delivered: 50 },
243 });
244
245 // Bitbucket takes one `q`, so the two narrowings are joined rather than one replacing the
246 // other — and the search keeps its brackets, which is what keeps the AND out of its OR.
247 expect(filterOfCall(0)).toBe(
248 '(title ~ "page" OR description ~ "page") AND updated_on <= 2026-07-02T00:00:00+00:00',
249 );
250 }),
251 );
252
253 it.effect("asks for declined pull requests on the closed tab", () =>
254 Effect.gen(function* () {
255 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
256 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
257
258 yield* api.listPullRequests({ repository: "acme/web", state: "closed", limit: 50 });
259
260 expect(callAt(0).url).toContain("state=DECLINED");
261 }),
262 );
263
264 it.effect("asks for every state at once on the All tab", () =>
265 Effect.gen(function* () {
266 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
267 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
268
269 yield* api.listPullRequests({ repository: "acme/web", state: "all", limit: 50 });
270
271 // Bitbucket unions repeated state parameters, which is the only way to span them.
272 const url = callAt(0).url;
273 for (const state of ["OPEN", "MERGED", "DECLINED", "SUPERSEDED"]) {
274 expect(url).toContain(`state=${state}`);
275 }
276 }),
277 );
278
279 it.effect("counts a superseded pull request as closed", () =>
280 Effect.gen(function* () {
281 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
282 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
283
284 yield* api.listPullRequests({ repository: "acme/web", state: "closed", limit: 50 });
285
286 expect(callAt(0).url).toContain("state=DECLINED");
287 expect(callAt(0).url).toContain("state=SUPERSEDED");
288 }),
289 );
290
291 it.effect("refuses a repository that is not workspace and slug", () =>
292 Effect.gen(function* () {
293 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
294
295 const error = yield* Effect.flip(
296 api.listPullRequests({ repository: "acme/team/web", state: "open", limit: 50 }),
297 );
298
299 assert.strictEqual(error._tag, "BitbucketRepositoryUnsupportedError");
300 assert.strictEqual(mockedRequest.mock.calls.length, 0);
301 }),
302 );
303
304 it.effect("returns the diff verbatim, because Bitbucket already sends a patch", () =>
305 Effect.gen(function* () {
306 const patch = "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -1 +1 @@\n-a\n+b\n";
307 mockedRequest.mockReturnValueOnce(Effect.succeed(response(patch)));
308 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
309
310 const diff = yield* api.getPullRequestDiff({ repository: "acme/web", number: 7 });
311
312 assert.strictEqual(diff.patch, patch);
313 assert.isFalse(diff.truncated);
314 expect(callAt(0)).toMatchObject({
315 url: "/repositories/acme/web/pullrequests/7/diff",
316 maxBytes: 8 * 1024 * 1024,
317 });
318 }),
319 );
320
321 it.effect("reads a named commit's own patch, which pages no further than the whole of it", () =>
322 Effect.gen(function* () {
323 const patch = "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -1 +1 @@\n-a\n+b\n";
324 mockedRequest.mockReturnValueOnce(Effect.succeed(response(patch)));
325 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
326
327 const diff = yield* api.getPullRequestDiff({
328 repository: "acme/web",
329 number: 7,
330 commit: "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0",
331 });
332
333 assert.strictEqual(diff.patch, patch);
334 expect(callAt(0)).toMatchObject({
335 url: "/repositories/acme/web/diff/a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0",
336 maxBytes: 8 * 1024 * 1024,
337 });
338 }),
339 );
340
341 it.effect("refuses a commit that is not a sha rather than reading it into a URL", () =>
342 Effect.gen(function* () {
343 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
344
345 const error = yield* Effect.flip(
346 api.getPullRequestDiff({
347 repository: "acme/web",
348 number: 7,
349 commit: "../../acme/other/diff/deadbeef",
350 }),
351 );
352
353 assert.strictEqual(error._tag, "BitbucketDiffCommitError");
354 assert.strictEqual(mockedRequest.mock.calls.length, 0);
355 }),
356 );
357
358 it.effect("reads every file version the patch states, not only the paths asked about", () =>
359 Effect.gen(function* () {
360 mockedRequest.mockReturnValueOnce(
361 Effect.succeed(
362 response(
363 [
364 "diff --git a/a.ts b/a.ts",
365 "index 1111111..2222222 100644",
366 "--- a/a.ts",
367 "+++ b/a.ts",
368 "@@ -1 +1 @@",
369 "-a",
370 "+b",
371 "diff --git a/b.ts b/b.ts",
372 "index 3333333..4444444 100644",
373 "--- a/b.ts",
374 "+++ b/b.ts",
375 "@@ -1 +1 @@",
376 "-c",
377 "+d",
378 "",
379 ].join("\n"),
380 ),
381 ),
382 );
383 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
384
385 const revisions = yield* api.getFileRevisions({
386 repository: "acme/web",
387 number: 71,
388 paths: ["a.ts", "missing.ts"],
389 });
390
391 assert.deepStrictEqual(
392 [...revisions.revisions],
393 [
394 ["a.ts", "2222222"],
395 ["b.ts", "4444444"],
396 ["missing.ts", ""],
397 ],
398 );
399 assert.strictEqual(revisions.complete, true);
400 expect(callAt(0)).toMatchObject({ url: "/repositories/acme/web/pullrequests/71/diff" });
401 }),
402 );
403
404 it.effect("says nothing about the files past the end of a patch it could not read whole", () =>
405 Effect.gen(function* () {
406 mockedRequest.mockReturnValueOnce(
407 Effect.succeed({
408 body: "diff --git a/a.ts b/a.ts\nindex 1111111..2222222 100644\n@@ -1 +1 @@\n",
409 truncated: true,
410 }),
411 );
412 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
413
414 const revisions = yield* api.getFileRevisions({
415 repository: "acme/web",
416 number: 72,
417 paths: ["a.ts", "past-the-cut.ts"],
418 });
419
420 assert.deepStrictEqual([...revisions.revisions], [["a.ts", "2222222"]]);
421 assert.strictEqual(revisions.complete, false);
422 }),
423 );
424
425 it.effect("reads the patch once for a run of ticks, not once a tick", () =>
426 Effect.gen(function* () {
427 mockedRequest.mockReturnValue(
428 Effect.succeed(
429 response(
430 [
431 "diff --git a/a.ts b/a.ts",
432 "index 1111111..2222222 100644",
433 "@@ -1 +1 @@",
434 "diff --git a/b.ts b/b.ts",
435 "index 3333333..4444444 100644",
436 "@@ -1 +1 @@",
437 "",
438 ].join("\n"),
439 ),
440 ),
441 );
442 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
443
444 const first = yield* api.getFileRevisions({
445 repository: "acme/web",
446 number: 74,
447 paths: ["a.ts"],
448 });
449 const second = yield* api.getFileRevisions({
450 repository: "acme/web",
451 number: 74,
452 paths: ["b.ts"],
453 });
454
455 const both = [
456 ["a.ts", "2222222"],
457 ["b.ts", "4444444"],
458 ];
459 assert.deepStrictEqual([...first.revisions], both);
460 assert.deepStrictEqual([...second.revisions], both);
461 assert.strictEqual(mockedRequest.mock.calls.length, 1);
462 }),
463 );
464
465 it.effect("reads the patch afresh once the one it held has aged out", () =>
466 Effect.gen(function* () {
467 mockedRequest.mockReturnValue(
468 Effect.succeed(
469 response("diff --git a/a.ts b/a.ts\nindex 1111111..2222222 100644\n@@ -1 +1 @@\n"),
470 ),
471 );
472 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
473 const read = () =>
474 api.getFileRevisions({ repository: "acme/web", number: 75, paths: ["a.ts"] });
475
476 yield* read();
477 yield* read();
478 assert.strictEqual(mockedRequest.mock.calls.length, 1);
479
480 yield* TestClock.adjust(Duration.seconds(30));
481 yield* read();
482 assert.strictEqual(mockedRequest.mock.calls.length, 2);
483 }),
484 );
485
486 it.effect("asks Bitbucket nothing when no file has been ticked off", () =>
487 Effect.gen(function* () {
488 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
489
490 const revisions = yield* api.getFileRevisions({
491 repository: "acme/web",
492 number: 73,
493 paths: [],
494 });
495
496 assert.strictEqual(revisions.revisions.size, 0);
497 assert.strictEqual(mockedRequest.mock.calls.length, 0);
498 }),
499 );
500
501 it.effect("aggregates every diffstat page", () =>
502 Effect.gen(function* () {
503 const next = "https://api.bitbucket.org/2.0/diffstat?page=2";
504 mockedRequest
505 .mockReturnValueOnce(
506 Effect.succeed(
507 response(
508 valuePage(
509 [
510 { lines_added: 9, lines_removed: 2 },
511 { lines_added: 3, lines_removed: 1 },
512 ],
513 next,
514 ),
515 ),
516 ),
517 )
518 .mockReturnValueOnce(
519 Effect.succeed(response(valuePage([{ lines_added: 4, lines_removed: 7 }]))),
520 );
521 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
522
523 const stat = yield* api.getDiffStat({ repository: "acme/web", number: 7 });
524
525 expect(stat).toEqual({ additions: 16, deletions: 10, changedFiles: 3 });
526 expect(callAt(1).url).toBe(next);
527 }),
528 );
529
530 it.effect("returns the complete commit timeline oldest first across pages", () =>
531 Effect.gen(function* () {
532 const next = "https://api.bitbucket.org/2.0/commits?page=2";
533 mockedRequest
534 .mockReturnValueOnce(
535 Effect.succeed(
536 response(
537 valuePage(
538 [
539 { hash: "ddd", message: "fourth", date: "2026-07-04T00:00:00Z" },
540 { hash: "ccc", message: "third", date: "2026-07-03T00:00:00Z" },
541 ],
542 next,
543 ),
544 ),
545 ),
546 )
547 .mockReturnValueOnce(
548 Effect.succeed(
549 response(
550 valuePage([
551 { hash: "bbb", message: "second", date: "2026-07-02T00:00:00Z" },
552 { hash: "aaa", message: "first", date: "2026-07-01T00:00:00Z" },
553 ]),
554 ),
555 ),
556 );
557 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
558
559 const commits = yield* api.listCommits({ repository: "acme/web", number: 7 });
560
561 expect(commits.map((commit) => commit.oid)).toEqual(["aaa", "bbb", "ccc", "ddd"]);
562 expect(callAt(1).url).toBe(next);
563 }),
564 );
565
566 it.effect("returns build statuses from every page", () =>
567 Effect.gen(function* () {
568 const next = "https://api.bitbucket.org/2.0/statuses?page=2";
569 mockedRequest
570 .mockReturnValueOnce(
571 Effect.succeed(response(valuePage([{ name: "Build", state: "SUCCESSFUL" }], next))),
572 )
573 .mockReturnValueOnce(
574 Effect.succeed(response(valuePage([{ name: "Lint", state: "FAILED" }]))),
575 );
576 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
577
578 const checks = yield* api.listChecks({ repository: "acme/web", number: 7 });
579
580 expect(checks.map((check) => [check.name, check.status])).toEqual([
581 ["Build", "success"],
582 ["Lint", "failure"],
583 ]);
584 expect(callAt(1).url).toBe(next);
585 }),
586 );
587
588 it.effect("reads an empty conflict list as mergeable", () =>
589 Effect.gen(function* () {
590 mockedRequest.mockReturnValueOnce(Effect.succeed(response(page(0, 1))));
591 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
592
593 const mergeability = yield* api.getMergeability({ repository: "acme/web", number: 7 });
594
595 assert.strictEqual(mergeability, "mergeable");
596 expect(callAt(0).url).toBe("/repositories/acme/web/pullrequests/7/conflicts");
597 }),
598 );
599
600 it.effect("merges with Bitbucket's own name for the strategy", () =>
601 Effect.gen(function* () {
602 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
603 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
604
605 yield* api.runAction({
606 repository: "acme/web",
607 number: 7,
608 action: "merge",
609 mergeMethod: "rebase",
610 });
611
612 expect(callAt(0)).toMatchObject({
613 method: "POST",
614 url: "/repositories/acme/web/pullrequests/7/merge",
615 body: '{"merge_strategy":"rebase_fast_forward"}',
616 });
617 }),
618 );
619
620 it.effect("closes a pull request by declining it", () =>
621 Effect.gen(function* () {
622 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
623 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
624
625 yield* api.runAction({ repository: "acme/web", number: 7, action: "close" });
626
627 expect(callAt(0)).toMatchObject({
628 method: "POST",
629 url: "/repositories/acme/web/pullrequests/7/decline",
630 });
631 }),
632 );
633
634 it.effect("posts a comment as a JSON document, so the body stays text", () =>
635 Effect.gen(function* () {
636 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
637 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
638
639 yield* api.comment({ repository: "acme/web", number: 7, body: "true" });
640
641 expect(callAt(0)).toMatchObject({
642 method: "POST",
643 url: "/repositories/acme/web/pullrequests/7/comments",
644 body: '{"content":{"raw":"true"}}',
645 });
646 }),
647 );
648
649 it.effect("rewrites a title alone, without touching anything else", () =>
650 Effect.gen(function* () {
651 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
652 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
653
654 yield* api.updateChangeRequest({ repository: "acme/web", number: 7, title: "A new title" });
655
656 const call = callAt(0);
657 expect(call.method).toBe("PUT");
658 expect(call.url).toBe("/repositories/acme/web/pullrequests/7");
659 // Bitbucket's PUT is a partial update, so a field left out of the body is left as it was.
660 expect(JSON.parse(call.body ?? "")).toEqual({ title: "A new title" });
661 }),
662 );
663
664 it.effect("leaves out the half of the pull request it was not asked about", () =>
665 Effect.gen(function* () {
666 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
667 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
668
669 yield* api.updateChangeRequest({ repository: "acme/web", number: 7, body: "New body." });
670
671 expect(JSON.parse(callAt(0).body ?? "")).toEqual({ description: "New body." });
672 }),
673 );
674
675 it.effect("writes both fields when both were rewritten", () =>
676 Effect.gen(function* () {
677 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
678 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
679
680 yield* api.updateChangeRequest({
681 repository: "acme/web",
682 number: 7,
683 title: "A new title",
684 body: "New body.",
685 });
686
687 expect(JSON.parse(callAt(0).body ?? "")).toEqual({
688 title: "A new title",
689 description: "New body.",
690 });
691 }),
692 );
693
694 it.effect("rewrites a comment where it stands, whichever kind it is", () =>
695 Effect.gen(function* () {
696 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
697 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
698
699 yield* api.updateComment({
700 repository: "acme/web",
701 number: 7,
702 commentId: "10",
703 body: "Edited.",
704 });
705
706 expect(callAt(0)).toMatchObject({
707 method: "PUT",
708 url: "/repositories/acme/web/pullrequests/7/comments/10",
709 body: '{"content":{"raw":"Edited."}}',
710 });
711 }),
712 );
713
714 it.effect("fails the read when Bitbucket answers with something unreadable", () =>
715 Effect.gen(function* () {
716 mockedRequest.mockReturnValueOnce(
717 Effect.succeed(response(JSON.stringify({ error: "nope" }))),
718 );
719 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
720
721 const error = yield* Effect.flip(api.getPullRequest({ repository: "acme/web", number: 7 }));
722
723 assert.strictEqual(error._tag, "BitbucketPullRequestReadError");
724 }),
725 );
726
727 it.effect("states a failure once, without stacking one message inside another", () =>
728 Effect.gen(function* () {
729 mockedRequest.mockReturnValueOnce(
730 Effect.fail(
731 new BitbucketApi.BitbucketResponseError({
732 operation: "request",
733 status: 500,
734 responseBodyLength: 0,
735 }),
736 ),
737 );
738 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
739
740 const error = yield* Effect.flip(api.getViewer());
741
742 assert.strictEqual(error.detail, "Bitbucket returned HTTP 500.");
743 }),
744 );
745
746 it.effect("fails when the credentials belong to no named account", () =>
747 Effect.gen(function* () {
748 mockedRequest.mockReturnValueOnce(Effect.succeed(response(JSON.stringify({}))));
749 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
750
751 const error = yield* Effect.flip(api.getViewer());
752
753 assert.strictEqual(error._tag, "BitbucketViewerUnavailableError");
754 }),
755 );
756
757 it.effect("follows Bitbucket's cursor and reassembles a thread that spans two pages", () =>
758 Effect.gen(function* () {
759 mockedRequest.mockReturnValueOnce(
760 Effect.succeed(
761 response(
762 JSON.stringify({
763 next: "https://api.bitbucket.org/2.0/comments?page=2",
764 values: [
765 {
766 id: 10,
767 content: { raw: "rename this" },
768 user: { nickname: "bilal" },
769 created_on: "2026-06-16T05:04:32+00:00",
770 inline: { path: "src/a.ts", to: 12 },
771 },
772 ],
773 }),
774 ),
775 ),
776 );
777 mockedRequest.mockReturnValueOnce(
778 Effect.succeed(
779 response(
780 JSON.stringify({
781 values: [
782 {
783 id: 11,
784 content: { raw: "done" },
785 user: { nickname: "julius" },
786 created_on: "2026-06-16T06:04:32+00:00",
787 parent: { id: 10 },
788 },
789 ],
790 }),
791 ),
792 ),
793 );
794 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
795
796 const { comments, threads, truncated } = yield* api.listComments({
797 repository: "acme/web",
798 number: 7,
799 });
800
801 expect(callAt(1).url).toBe("https://api.bitbucket.org/2.0/comments?page=2");
802 expect(comments.map((comment) => comment.id)).toEqual(["10", "11"]);
803 expect(threads[0]?.comments.map((comment) => comment.id)).toEqual(["10", "11"]);
804 assert.isFalse(truncated);
805 }),
806 );
807
808 it.effect("stops the comment walk at its bound and says the conversation was cut short", () =>
809 Effect.gen(function* () {
810 mockedRequest.mockReturnValue(
811 Effect.succeed(
812 response(
813 JSON.stringify({
814 next: "https://api.bitbucket.org/2.0/comments?page=2",
815 values: [
816 {
817 id: 10,
818 content: { raw: "again" },
819 created_on: "2026-06-16T05:04:32+00:00",
820 },
821 ],
822 }),
823 ),
824 ),
825 );
826 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
827
828 const { truncated } = yield* api.listComments({ repository: "acme/web", number: 7 });
829
830 assert.strictEqual(mockedRequest.mock.calls.length, 10);
831 assert.isTrue(truncated);
832 }),
833 );
834
835 it.effect("reassembles a thread from the flat comment list, replies included", () =>
836 Effect.gen(function* () {
837 mockedRequest.mockReturnValueOnce(
838 Effect.succeed(
839 response(
840 JSON.stringify({
841 values: [
842 {
843 id: 10,
844 content: { raw: "rename this" },
845 user: { nickname: "bilal" },
846 created_on: "2026-06-16T05:04:32+00:00",
847 inline: { path: "src/a.ts", to: 12, from: null },
848 resolution: { type: "pullrequest_comment_resolution" },
849 },
850 {
851 id: 11,
852 content: { raw: "done" },
853 user: { nickname: "julius" },
854 created_on: "2026-06-16T06:04:32+00:00",
855 parent: { id: 10 },
856 },
857 {
858 id: 12,
859 content: { raw: "thanks" },
860 user: { nickname: "bilal" },
861 created_on: "2026-06-16T07:04:32+00:00",
862 parent: { id: 11 },
863 },
864 {
865 id: 13,
866 content: { raw: "ship it" },
867 user: { nickname: "bilal" },
868 created_on: "2026-06-16T08:04:32+00:00",
869 },
870 ],
871 }),
872 ),
873 ),
874 );
875 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
876
877 const { threads } = yield* api.listComments({ repository: "acme/web", number: 7 });
878
879 assert.strictEqual(threads.length, 1);
880 expect(threads[0]).toMatchObject({
881 id: "10",
882 path: "src/a.ts",
883 line: 12,
884 side: "right",
885 isResolved: true,
886 });
887 expect(threads[0]?.comments.map((comment) => comment.id)).toEqual(["10", "11", "12"]);
888 }),
889 );
890
891 it.effect("writes a review's line comments, its summary, then its verdict", () =>
892 Effect.gen(function* () {
893 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
894 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
895
896 yield* api.submitReview({
897 repository: "acme/web",
898 number: 7,
899 verdict: "request-changes",
900 body: "Two things.",
901 comments: [
902 {
903 path: "src/a.ts",
904 position: { kind: "deleted", oldLine: 12 },
905 body: "why remove?",
906 },
907 ],
908 });
909
910 expect(callAt(0).url).toContain("/pullrequests/7/comments");
911 expect(JSON.parse(callAt(0).body ?? "")).toEqual({
912 content: { raw: "why remove?" },
913 inline: { path: "src/a.ts", from: 12 },
914 });
915 expect(callAt(1).url).toContain("/pullrequests/7/comments");
916 expect(callAt(2).url).toContain("/pullrequests/7/request-changes");
917 }),
918 );
919
920 it.effect("resolves by creating the sub-resource and unresolves by deleting it", () =>
921 Effect.gen(function* () {
922 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
923 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
924
925 yield* api.setCommentResolution({
926 repository: "acme/web",
927 number: 7,
928 commentId: "10",
929 resolved: true,
930 });
931 yield* api.setCommentResolution({
932 repository: "acme/web",
933 number: 7,
934 commentId: "10",
935 resolved: false,
936 });
937
938 assert.strictEqual(callAt(0).method, "POST");
939 assert.strictEqual(callAt(1).method, "DELETE");
940 expect(callAt(0).url).toContain("/comments/10/resolve");
941 }),
942 );
943
944 it.effect("replies by naming the comment it answers", () =>
945 Effect.gen(function* () {
946 mockedRequest.mockReturnValue(Effect.succeed(response("{}")));
947 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
948
949 yield* api.replyToComment({
950 repository: "acme/web",
951 number: 7,
952 commentId: "10",
953 body: "Fixed.",
954 });
955
956 expect(JSON.parse(callAt(0).body ?? "")).toEqual({
957 content: { raw: "Fixed." },
958 parent: { id: 10 },
959 });
960 }),
961 );
962
963 it.effect("asks for the credentials' permission on this repository, and nobody else's", () =>
964 Effect.gen(function* () {
965 mockedRequest.mockReturnValue(
966 Effect.succeed(
967 response(
968 JSON.stringify({ values: [{ type: "repository_permission", permission: "read" }] }),
969 ),
970 ),
971 );
972 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
973
974 assert.isFalse(yield* api.getRepositoryPermission({ repository: "acme/web" }));
975
976 expect(new URL(callAt(0).url, "https://api.bitbucket.org").pathname).toBe(
977 "/user/workspaces/acme/permissions/repositories",
978 );
979 assert.strictEqual(filterOfCall(0), 'repository.full_name="acme/web"');
980 }),
981 );
982
983 it.effect("matches repository permissions after normalizing whitespace around segments", () =>
984 Effect.gen(function* () {
985 mockedRequest.mockImplementation((input) => {
986 const url = new URL(input.url, "https://api.bitbucket.org");
987 const matches =
988 url.pathname === "/user/workspaces/acme/permissions/repositories" &&
989 url.searchParams.get("q") === 'repository.full_name="acme/web"';
990 return Effect.succeed(response(valuePage(matches ? [{ permission: "read" }] : [])));
991 });
992 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
993
994 assert.isFalse(yield* api.getRepositoryPermission({ repository: " acme / web " }));
995 }),
996 );
997
998 it.effect("escapes a repository name before it goes inside a filter literal", () =>
999 Effect.gen(function* () {
1000 mockedRequest.mockReturnValue(Effect.succeed(response(JSON.stringify({ values: [] }))));
1001 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
1002
1003 yield* api.getRepositoryPermission({ repository: 'acme/we"b' });
1004
1005 assert.strictEqual(filterOfCall(0), 'repository.full_name="acme/we\\"b"');
1006 }),
1007 );
1008
1009 const permissionFailure = (status: number) =>
1010 Effect.fail(
1011 new BitbucketApi.BitbucketResponseError({
1012 operation: "request",
1013 status,
1014 responseBodyLength: 0,
1015 }),
1016 );
1017
1018 it.effect.each([403, 404, 410])(
1019 "reads HTTP %s from the permissions endpoint as an unknown permission",
1020 (status) =>
1021 Effect.gen(function* () {
1022 mockedRequest.mockReturnValue(permissionFailure(status));
1023 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
1024
1025 assert.isTrue(yield* api.getRepositoryPermission({ repository: "acme/web" }));
1026 }),
1027 );
1028
1029 it.effect.each([401, 500])("still fails the permission read on HTTP %s", (status) =>
1030 Effect.gen(function* () {
1031 mockedRequest.mockReturnValue(permissionFailure(status));
1032 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
1033
1034 const error = yield* Effect.flip(api.getRepositoryPermission({ repository: "acme/web" }));
1035 assert.strictEqual(error._tag, "BitbucketResponseError");
1036 if (error._tag === "BitbucketResponseError") {
1037 assert.strictEqual(error.status, status);
1038 }
1039 }),
1040 );
1041
1042 it.effect("reads the workspace's people and marks whoever is already a reviewer", () =>
1043 Effect.gen(function* () {
1044 mockedRequest
1045 .mockReturnValueOnce(Effect.succeed(response(pullRequestJson({ reviewers: [octocat] }))))
1046 .mockReturnValueOnce(
1047 Effect.succeed(
1048 response(
1049 JSON.stringify({ values: [{ user: bilal }, { user: octocat }, { user: hubot }] }),
1050 ),
1051 ),
1052 );
1053 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
1054
1055 const list = yield* api.listReviewerCandidates({ repository: "acme/web", number: 7 });
1056
1057 expect(callAt(1).url).toBe("/workspaces/acme/members?pagelen=50");
1058 expect(list.candidates.map((candidate) => [candidate.id, candidate.isRequested])).toEqual([
1059 ["{octocat}", true],
1060 ["{hubot}", false],
1061 ]);
1062 assert.isFalse(list.truncated);
1063 }),
1064 );
1065
1066 it.effect("writes the reviewer set back with the one being asked added to it", () =>
1067 Effect.gen(function* () {
1068 mockedRequest
1069 .mockReturnValueOnce(Effect.succeed(response(pullRequestJson({ reviewers: [octocat] }))))
1070 .mockReturnValueOnce(Effect.succeed(response("{}")));
1071 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
1072
1073 yield* api.setReviewerRequest({
1074 repository: "acme/web",
1075 number: 7,
1076 reviewers: [{ id: "{hubot}" }],
1077 requested: true,
1078 });
1079
1080 // Bitbucket writes `reviewers` whole, so the one already on the pull request travels with
1081 // the new one or the request would take them off it.
1082 const call = callAt(1);
1083 expect(call.method).toBe("PUT");
1084 expect(call.url).toBe("/repositories/acme/web/pullrequests/7");
1085 expect(JSON.parse(call.body ?? "")).toEqual({
1086 reviewers: [{ uuid: "{octocat}" }, { uuid: "{hubot}" }],
1087 });
1088 }),
1089 );
1090
1091 it.effect("takes a reviewer out of the set rather than clearing it", () =>
1092 Effect.gen(function* () {
1093 mockedRequest
1094 .mockReturnValueOnce(
1095 Effect.succeed(response(pullRequestJson({ reviewers: [octocat, hubot] }))),
1096 )
1097 .mockReturnValueOnce(Effect.succeed(response("{}")));
1098 const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
1099
1100 yield* api.setReviewerRequest({
1101 repository: "acme/web",
1102 number: 7,
1103 reviewers: [{ id: "{hubot}" }],
1104 requested: false,
1105 });
1106
1107 expect(JSON.parse(callAt(1).body ?? "")).toEqual({ reviewers: [{ uuid: "{octocat}" }] });
1108 }),
1109 );
1110});