Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- Builds the zip Azure returns and stands in for az writing it.
2import * as NodeFS from "node:fs";
3import * as NodeZlib from "node:zlib";
4
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import { afterEach, assert, expect, it, vi } from "@effect/vitest";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import { ChildProcessSpawner } from "effect/process";
10
11import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
12import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";
13import * as AzureDevOpsPullRequestProvider from "./AzureDevOpsPullRequestProvider.ts";
14
15const mockedExecute = vi.fn<AzureDevOpsCli.AzureDevOpsCli["Service"]["execute"]>();
16
17const layer = it.layer(
18 AzureDevOpsPullRequestCli.layer.pipe(
19 Layer.provide(
20 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({
21 execute: mockedExecute,
22 }),
23 ),
24 Layer.provide(NodeServices.layer),
25 ),
26);
27
28function output(stdout: string) {
29 return {
30 exitCode: ChildProcessSpawner.ExitCode(0),
31 stdout,
32 stderr: "",
33 stdoutTruncated: false,
34 stderrTruncated: false,
35 };
36}
37
38const VCS_DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
39
40function outputWithin(maxOutputBytes: number | undefined, response: string) {
41 const ceiling = maxOutputBytes ?? VCS_DEFAULT_MAX_OUTPUT_BYTES;
42 return ceiling >= Buffer.byteLength(response)
43 ? output(response)
44 : { ...output(response.slice(0, ceiling)), stdoutTruncated: true };
45}
46
47const json = (value: Record<string, unknown>) => JSON.stringify(value);
48
49const pullRequestRow = {
50 pullRequestId: 42,
51 title: "Add the page",
52 status: "active",
53 sourceRefName: "refs/heads/feat/page",
54 targetRefName: "refs/heads/main",
55 creationDate: "2026-07-01T00:00:00Z",
56 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
57 repository: { name: "web", project: { name: "platform" } },
58};
59
60const oneIteration = {
61 value: [
62 {
63 id: 1,
64 sourceRefCommit: { commitId: "a".repeat(40) },
65 commonRefCommit: { commitId: "b".repeat(40) },
66 },
67 ],
68};
69
70function pullRequestRows(
71 count: number,
72 firstNumber: number,
73): ReadonlyArray<Record<string, unknown>> {
74 return Array.from({ length: count }, (_, index) => ({
75 pullRequestId: firstNumber + index,
76 title: `Pull request ${firstNumber + index}`,
77 status: "active",
78 sourceRefName: "refs/heads/feat/page",
79 targetRefName: "refs/heads/main",
80 creationDate: "2026-07-01T00:00:00Z",
81 repository: { name: "web", project: { name: "platform" } },
82 url: `https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/${firstNumber + index}`,
83 }));
84}
85
86function pullRequests(count: number, firstNumber: number): string {
87 return JSON.stringify(pullRequestRows(count, firstNumber));
88}
89
90/** Entries as Azure streams them: data descriptors, with sizes only in the central directory. */
91function streamedZip(
92 entries: ReadonlyArray<{
93 readonly name: string;
94 readonly data: Uint8Array;
95 readonly stored?: true;
96 }>,
97): Buffer {
98 const parts: Buffer[] = [];
99 const directory: Buffer[] = [];
100 let offset = 0;
101 for (const entry of entries) {
102 const name = Buffer.from(entry.name);
103 const method = entry.stored ? 0 : 8;
104 const body = entry.stored ? Buffer.from(entry.data) : NodeZlib.deflateRawSync(entry.data);
105 const local = Buffer.alloc(30);
106 local.writeUInt32LE(0x04034b50, 0);
107 local.writeUInt16LE(0x0008, 6);
108 local.writeUInt16LE(method, 8);
109 local.writeUInt16LE(name.length, 26);
110 const descriptor = Buffer.alloc(16);
111 descriptor.writeUInt32LE(0x08074b50, 0);
112 descriptor.writeUInt32LE(body.length, 8);
113 descriptor.writeUInt32LE(entry.data.length, 12);
114 const central = Buffer.alloc(46);
115 central.writeUInt32LE(0x02014b50, 0);
116 central.writeUInt16LE(0x0008, 8);
117 central.writeUInt16LE(method, 10);
118 central.writeUInt32LE(body.length, 20);
119 central.writeUInt32LE(entry.data.length, 24);
120 central.writeUInt16LE(name.length, 28);
121 central.writeUInt32LE(offset, 42);
122 parts.push(local, name, body, descriptor);
123 directory.push(central, name);
124 offset += local.length + name.length + body.length + descriptor.length;
125 }
126 const centralDirectory = Buffer.concat(directory);
127 const end = Buffer.alloc(22);
128 end.writeUInt32LE(0x06054b50, 0);
129 end.writeUInt16LE(entries.length, 8);
130 end.writeUInt16LE(entries.length, 10);
131 end.writeUInt32LE(centralDirectory.length, 12);
132 end.writeUInt32LE(offset, 16);
133 return Buffer.concat([...parts, centralDirectory, end]);
134}
135
136function argsOfCall(index: number): ReadonlyArray<string> {
137 const call = mockedExecute.mock.calls[index];
138 assert.isDefined(call);
139 return call[0].args;
140}
141
142function changeEntries(count: number): ReadonlyArray<Record<string, unknown>> {
143 const commit = "c".repeat(40);
144 return Array.from({ length: count }, (_, index) => {
145 const path = `/apps/server/src/generated/module-${index}/persisted-projection-${index}.ts`;
146 return {
147 changeType: "edit",
148 item: {
149 path,
150 objectId: "a".repeat(40),
151 originalObjectId: "b".repeat(40),
152 commitId: commit,
153 gitObjectType: "blob",
154 url: `https://dev.azure.com/acme/platform/_apis/git/repositories/6f9c9b7f-0000-0000-0000-000000000000/items${path}?versionType=Commit&version=${commit}`,
155 },
156 };
157 });
158}
159
160afterEach(() => {
161 mockedExecute.mockReset();
162});
163
164layer("AzureDevOpsPullRequestCli.layer", (it) => {
165 it.effect("reports the latest pushed source commit even while the trial merge is stale", () =>
166 Effect.gen(function* () {
167 const previousHead = "a".repeat(40);
168 const latestHead = "c".repeat(40);
169 mockedExecute
170 .mockReturnValueOnce(
171 Effect.succeed(
172 output(json({ ...pullRequestRow, lastMergeSourceCommit: { commitId: previousHead } })),
173 ),
174 )
175 .mockReturnValueOnce(
176 Effect.succeed(
177 output(
178 json({
179 value: [
180 {
181 id: 2,
182 sourceRefCommit: { commitId: latestHead },
183 commonRefCommit: { commitId: "b".repeat(40) },
184 },
185 ...oneIteration.value,
186 ],
187 }),
188 ),
189 ),
190 )
191 .mockReturnValueOnce(Effect.succeed(output(json({ changeEntries: [] }))))
192 .mockReturnValueOnce(Effect.succeed(output("[]")));
193 const provider = yield* AzureDevOpsPullRequestProvider.make;
194 const detail = yield* provider.getChangeRequest({
195 cwd: "/w",
196 repository: "platform/web",
197 host: "dev.azure.com",
198 number: 42,
199 });
200
201 expect(detail.headSha).toBe(latestHead);
202 expect(argsOfCall(2)).toContain("iterationId=2");
203 expect(mockedExecute).toHaveBeenCalledTimes(4);
204 }),
205 );
206
207 it.effect("reads an Azure pull request page larger than the VCS default output limit", () =>
208 Effect.gen(function* () {
209 const rows = pullRequestRows(100, 1).map((row) => ({
210 ...row,
211 description: "x".repeat(10_000),
212 }));
213 const response = JSON.stringify(rows);
214 expect(Buffer.byteLength(response)).toBeGreaterThan(1_000_000);
215
216 mockedExecute.mockImplementationOnce((input) =>
217 Effect.succeed(outputWithin(input.maxOutputBytes, response)),
218 );
219 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
220
221 const batch = yield* cli.listPullRequests({
222 cwd: "/w",
223 repository: "web",
224 state: "merged",
225 involvement: "all",
226 viewer: "bilal@acme.dev",
227 limit: 99,
228 });
229
230 assert.strictEqual(batch.items.length, 99);
231 assert.isTrue(batch.truncated);
232 }),
233 );
234
235 it.effect("steps over what it has already handed over, which is all Azure can be told", () =>
236 Effect.gen(function* () {
237 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(3, 1))));
238 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
239
240 yield* cli.listPullRequests({
241 cwd: "/w",
242 repository: "web",
243 state: "open",
244 involvement: "all",
245 viewer: "bilal@acme.dev",
246 limit: 10,
247 cursor: { updatedBefore: "2026-07-02T00:00:00Z", delivered: 20 },
248 });
249
250 const args = argsOfCall(0);
251 expect(args).toContain("--skip");
252 assert.strictEqual(args[args.indexOf("--skip") + 1], "20");
253 expect(args).not.toContain("2026-07-02T00:00:00Z");
254 }),
255 );
256
257 it.effect("asks Azure for the author's pull requests by creator", () =>
258 Effect.gen(function* () {
259 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(1, 1))));
260 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
261
262 yield* cli.listPullRequests({
263 cwd: "/w",
264 repository: "web",
265 state: "open",
266 involvement: "reviewing",
267 viewer: "bilal@acme.dev",
268 limit: 10,
269 author: "ana@acme.dev",
270 });
271
272 const args = argsOfCall(0);
273 assert.strictEqual(args[args.indexOf("--creator") + 1], "ana@acme.dev");
274 assert.strictEqual(args[args.indexOf("--reviewer") + 1], "bilal@acme.dev");
275 }),
276 );
277
278 it.effect("advances by malformed raw rows and keeps reading until the page is full", () =>
279 Effect.gen(function* () {
280 mockedExecute
281 .mockReturnValueOnce(
282 Effect.succeed(
283 output(
284 JSON.stringify([
285 { pullRequestId: "malformed" },
286 pullRequestRows(1, 1)[0],
287 { pullRequestId: "also malformed" },
288 ]),
289 ),
290 ),
291 )
292 .mockReturnValueOnce(Effect.succeed(output(pullRequests(2, 2))));
293 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
294
295 const batch = yield* cli.listPullRequests({
296 cwd: "/w",
297 repository: "web",
298 state: "open",
299 involvement: "all",
300 viewer: "bilal@acme.dev",
301 limit: 2,
302 });
303
304 expect(batch.items.map((item) => item.number)).toEqual([1, 2]);
305 assert.isTrue(batch.truncated);
306 assert.strictEqual(batch.cursorAdvance, 4);
307 const secondArgs = argsOfCall(1);
308 assert.strictEqual(secondArgs[secondArgs.indexOf("--skip") + 1], "3");
309 assert.strictEqual(secondArgs[secondArgs.indexOf("--top") + 1], "2");
310 }),
311 );
312
313 it.effect("reads the signed-in account, which az reports as a bare value", () =>
314 Effect.gen(function* () {
315 mockedExecute.mockReturnValueOnce(
316 Effect.succeed(output(JSON.stringify({ name: "bilal@acme.dev", type: "user" }))),
317 );
318 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
319
320 const viewer = yield* cli.getViewer({ cwd: "/w" });
321
322 assert.strictEqual(viewer, "bilal@acme.dev");
323 expect(argsOfCall(0)).toEqual([
324 "account",
325 "show",
326 "--query",
327 "user",
328 "--only-show-errors",
329 "--output",
330 "json",
331 ]);
332 }),
333 );
334
335 it.effect("names a token sign-in by the viewer's own pull request", () =>
336 Effect.gen(function* () {
337 const notLoggedIn = new AzureDevOpsCli.AzureDevOpsCliAuthenticationError({
338 operation: "execute",
339 command: "az",
340 cwd: "/w",
341 argumentCount: 7,
342 cause: new Error("Please run 'az login' to setup account."),
343 });
344 mockedExecute
345 .mockReturnValueOnce(Effect.fail(notLoggedIn))
346 .mockReturnValueOnce(
347 Effect.succeed(
348 output(
349 JSON.stringify([{ ...pullRequestRow, createdBy: { uniqueName: "bilal@acme.dev" } }]),
350 ),
351 ),
352 )
353 .mockReturnValueOnce(Effect.succeed(output("")))
354 .mockReturnValueOnce(Effect.succeed(output("[]")));
355 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
356
357 assert.strictEqual(yield* cli.getViewer({ cwd: "/w" }), "bilal@acme.dev");
358 expect(argsOfCall(1)).toEqual(expect.arrayContaining(["--creator", "me", "--top", "1"]));
359 const error = yield* Effect.flip(cli.getViewer({ cwd: "/w" }));
360 assert.strictEqual(error._tag, "AzureDevOpsViewerUnavailableError");
361 }),
362 );
363
364 it.effect("fails when no sign-in can read pull requests", () =>
365 Effect.gen(function* () {
366 const signedOut = new AzureDevOpsCli.AzureDevOpsCliAuthenticationError({
367 operation: "execute",
368 command: "az",
369 cwd: "/w",
370 argumentCount: 7,
371 cause: new Error("signed out"),
372 });
373 mockedExecute.mockReturnValue(Effect.fail(signedOut));
374 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
375
376 const error = yield* Effect.flip(cli.getViewer({ cwd: "/w" }));
377
378 assert.strictEqual(error._tag, "AzureDevOpsCliAuthenticationError");
379 }),
380 );
381
382 const policyRow = (name: string, status: string) => ({
383 status,
384 configuration: {
385 url: "https://dev.azure.com/acme/platform/_apis/policy/configurations/54",
386 isBlocking: true,
387 type: { id: "0609b952-1397-4640-95ec-e00a01b2c241" },
388 settings: { displayName: name },
389 },
390 });
391
392 it.effect("follows every page of policies and puts failures first", () =>
393 Effect.gen(function* () {
394 const fullPage = Array.from({ length: 100 }, () => policyRow("Lint", "approved"));
395 mockedExecute
396 .mockReturnValueOnce(Effect.succeed(output(JSON.stringify(fullPage))))
397 .mockReturnValueOnce(
398 Effect.succeed(output(JSON.stringify([policyRow("Tests", "rejected")]))),
399 );
400 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
401 const checks = yield* cli.listPolicyChecks({ cwd: "/w", number: 42, isDraft: false });
402 assert.deepStrictEqual(argsOfCall(1).slice(0, 12), [
403 "repos",
404 "pr",
405 "policy",
406 "list",
407 "--detect",
408 "true",
409 "--id",
410 "42",
411 "--top",
412 "100",
413 "--skip",
414 "100",
415 ]);
416 assert.strictEqual(checks.length, 101);
417 assert.strictEqual(checks[0]?.name, "Tests");
418 }),
419 );
420
421 it.effect.each([
422 { name: "cut off", result: { ...output("[]"), stdoutTruncated: true } },
423 { name: "unreadable", result: output(JSON.stringify([{ status: 7 }])) },
424 ])("fails rather than report a $name policy page as complete", ({ result }) =>
425 Effect.gen(function* () {
426 mockedExecute.mockReturnValueOnce(Effect.succeed(result));
427 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
428 const error = yield* Effect.flip(
429 cli.listPolicyChecks({ cwd: "/w", number: 42, isDraft: false }),
430 );
431 assert.strictEqual(error._tag, "AzureDevOpsPullRequestReadError");
432 }),
433 );
434
435 it.effect("sends a description that starts with a dash as one value, not as a flag", () =>
436 Effect.gen(function* () {
437 mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
438 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
439
440 yield* cli.updatePullRequest({
441 cwd: "/w",
442 number: 42,
443 body: "- rewrote the page\n- kept the rest",
444 });
445
446 expect(argsOfCall(0)).toContain("--description=- rewrote the page\n- kept the rest");
447 }),
448 );
449
450 it.effect("names the head's blob as what a cleared file was cleared at", () =>
451 Effect.gen(function* () {
452 mockedExecute
453 .mockReturnValueOnce(
454 Effect.succeed(
455 output(
456 JSON.stringify({
457 pullRequestId: 42,
458 title: "Add the page",
459 status: "active",
460 sourceRefName: "refs/heads/feat/page",
461 targetRefName: "refs/heads/main",
462 creationDate: "2026-07-01T00:00:00Z",
463 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
464 repository: { name: "web", project: { name: "platform" } },
465 }),
466 ),
467 ),
468 )
469 .mockReturnValueOnce(
470 Effect.succeed(
471 output(
472 JSON.stringify({
473 value: [
474 {
475 id: 1,
476 sourceRefCommit: { commitId: "a".repeat(40) },
477 commonRefCommit: { commitId: "b".repeat(40) },
478 },
479 {
480 id: 2,
481 sourceRefCommit: { commitId: "c".repeat(40) },
482 commonRefCommit: { commitId: "b".repeat(40) },
483 },
484 ],
485 }),
486 ),
487 ),
488 )
489 .mockReturnValueOnce(
490 Effect.succeed(
491 output(
492 JSON.stringify({
493 changeEntries: [
494 { changeType: "edit", item: { path: "/README.md", objectId: "8f80" } },
495 { changeType: "add", item: { path: "/DEMO.md", objectId: "0ca4" } },
496 ],
497 }),
498 ),
499 ),
500 );
501 const provider = yield* AzureDevOpsPullRequestProvider.make;
502
503 assert.strictEqual(provider.capabilities.viewedFiles, "environment");
504 assert.isDefined(provider.getFileRevisions);
505 const answer = yield* provider.getFileRevisions({
506 cwd: "/w",
507 repository: "web",
508 host: "dev.azure.com",
509 number: 42,
510 paths: ["README.md"],
511 });
512
513 expect(argsOfCall(2)).toContain("iterationId=2");
514 expect([...answer.revisions]).toEqual([["README.md", "8f80"]]);
515 }),
516 );
517
518 it.effect(
519 "answers for a marked file the pull request no longer changes as the empty version",
520 () =>
521 Effect.gen(function* () {
522 mockedExecute
523 .mockReturnValueOnce(
524 Effect.succeed(
525 output(
526 json({
527 pullRequestId: 42,
528 title: "Add the page",
529 status: "active",
530 sourceRefName: "refs/heads/feat/page",
531 targetRefName: "refs/heads/main",
532 creationDate: "2026-07-01T00:00:00Z",
533 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
534 repository: { name: "web", project: { name: "platform" } },
535 }),
536 ),
537 ),
538 )
539 .mockReturnValueOnce(
540 Effect.succeed(
541 output(
542 json({
543 value: [
544 {
545 id: 1,
546 sourceRefCommit: { commitId: "a".repeat(40) },
547 commonRefCommit: { commitId: "b".repeat(40) },
548 },
549 ],
550 }),
551 ),
552 ),
553 )
554 .mockReturnValueOnce(Effect.succeed(output('{"changeEntries":[]}')));
555 const provider = yield* AzureDevOpsPullRequestProvider.make;
556 assert.isDefined(provider.getFileRevisions);
557
558 const answer = yield* provider.getFileRevisions({
559 cwd: "/w",
560 repository: "web",
561 host: "dev.azure.com",
562 number: 42,
563 paths: ["GONE.md"],
564 });
565
566 expect([...answer.revisions]).toEqual([["GONE.md", ""]]);
567 }),
568 );
569
570 it.effect("says nothing about the files past the end of a change it gave up following", () =>
571 Effect.gen(function* () {
572 const entries = (from: number, count: number) =>
573 Array.from({ length: count }, (_, index) => ({
574 changeType: "edit",
575 item: { path: `/src/f${from + index}.ts`, objectId: `blob-${from + index}` },
576 }));
577 mockedExecute
578 .mockReturnValueOnce(
579 Effect.succeed(
580 output(
581 json({
582 pullRequestId: 42,
583 title: "Add the page",
584 status: "active",
585 sourceRefName: "refs/heads/feat/page",
586 targetRefName: "refs/heads/main",
587 creationDate: "2026-07-01T00:00:00Z",
588 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
589 repository: { name: "web", project: { name: "platform" } },
590 }),
591 ),
592 ),
593 )
594 .mockReturnValueOnce(
595 Effect.succeed(
596 output(
597 json({
598 value: [
599 {
600 id: 1,
601 sourceRefCommit: { commitId: "a".repeat(40) },
602 commonRefCommit: { commitId: "b".repeat(40) },
603 },
604 ],
605 }),
606 ),
607 ),
608 )
609 .mockReturnValueOnce(
610 Effect.succeed(output(json({ changeEntries: entries(0, 5_000), nextSkip: 5_000 }))),
611 )
612 .mockReturnValueOnce(
613 Effect.succeed(output(json({ changeEntries: entries(5_000, 5_000), nextSkip: 10_000 }))),
614 );
615 const provider = yield* AzureDevOpsPullRequestProvider.make;
616 assert.isDefined(provider.getFileRevisions);
617
618 const answer = yield* provider.getFileRevisions({
619 cwd: "/w",
620 repository: "web",
621 host: "dev.azure.com",
622 number: 42,
623 paths: ["src/f1.ts", "src/f5001.ts", "src/past-the-cut.ts"],
624 });
625
626 expect(argsOfCall(3)).toContain("$skip=5000");
627 expect([...answer.revisions]).toEqual([
628 ["src/f1.ts", "blob-1"],
629 ["src/f5001.ts", "blob-5001"],
630 ]);
631 }),
632 );
633
634 it.effect("stops following pages by what Azure counts, not by what survives decoding", () =>
635 Effect.gen(function* () {
636 mockedExecute
637 .mockReturnValueOnce(
638 Effect.succeed(
639 output(
640 json({
641 pullRequestId: 42,
642 title: "Add the page",
643 status: "active",
644 sourceRefName: "refs/heads/feat/page",
645 targetRefName: "refs/heads/main",
646 creationDate: "2026-07-01T00:00:00Z",
647 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
648 repository: { name: "web", project: { name: "platform" } },
649 }),
650 ),
651 ),
652 )
653 .mockReturnValueOnce(
654 Effect.succeed(
655 output(
656 json({
657 value: [
658 {
659 id: 1,
660 sourceRefCommit: { commitId: "a".repeat(40) },
661 commonRefCommit: { commitId: "b".repeat(40) },
662 },
663 ],
664 }),
665 ),
666 ),
667 )
668 .mockImplementation((command) => {
669 const skip = command.args.find((arg) => arg.startsWith("$skip="));
670 const from = Number(skip?.slice("$skip=".length) ?? 0);
671 return Effect.succeed(
672 output(
673 json({
674 changeEntries: [{ changeType: "add", item: { path: "/src", isFolder: true } }],
675 nextSkip: from + 2_000,
676 }),
677 ),
678 );
679 });
680 const provider = yield* AzureDevOpsPullRequestProvider.make;
681 assert.isDefined(provider.getFileRevisions);
682
683 const answer = yield* provider.getFileRevisions({
684 cwd: "/w",
685 repository: "web",
686 host: "dev.azure.com",
687 number: 42,
688 paths: ["src/page.ts"],
689 });
690
691 assert.strictEqual(mockedExecute.mock.calls.length, 7);
692 assert.strictEqual(answer.revisions.size, 0);
693 }),
694 );
695
696 it.effect("leaves one file the host would not hand over listed without its hunks", () =>
697 Effect.gen(function* () {
698 mockedExecute
699 .mockReturnValueOnce(Effect.succeed(output(json(pullRequestRow))))
700 .mockReturnValueOnce(Effect.succeed(output(json(oneIteration))))
701 .mockReturnValueOnce(
702 Effect.succeed(
703 output(
704 json({
705 changeEntries: [
706 { changeType: "add", item: { path: "/huge.bin", objectId: "8f80" } },
707 { changeType: "add", item: { path: "/DEMO.md", objectId: "0ca4" } },
708 ],
709 }),
710 ),
711 ),
712 )
713 .mockReturnValueOnce(
714 Effect.fail(
715 new AzureDevOpsCli.AzureDevOpsCommandFailedError({
716 operation: "execute",
717 command: "az",
718 cwd: "/w",
719 argumentCount: 1,
720 cause: "the blob is past what the route will carry",
721 }),
722 ),
723 )
724 .mockReturnValueOnce(Effect.succeed(output(json({ content: "hello\n" }))));
725 const provider = yield* AzureDevOpsPullRequestProvider.make;
726
727 const slice = yield* provider.getDiff({
728 cwd: "/w",
729 repository: "web",
730 host: "dev.azure.com",
731 number: 42,
732 });
733
734 assert.isTrue(slice.truncated);
735 expect(slice.patch).toContain("diff --git a/huge.bin b/huge.bin");
736 expect(slice.patch).toContain("+hello");
737 }),
738 );
739
740 it.effect("fails the whole read when it is the connection that would not answer", () =>
741 Effect.gen(function* () {
742 mockedExecute
743 .mockReturnValueOnce(Effect.succeed(output(json(pullRequestRow))))
744 .mockReturnValueOnce(Effect.succeed(output(json(oneIteration))))
745 .mockReturnValueOnce(
746 Effect.succeed(
747 output(
748 json({
749 changeEntries: [
750 { changeType: "add", item: { path: "/DEMO.md", objectId: "0ca4" } },
751 ],
752 }),
753 ),
754 ),
755 )
756 .mockReturnValueOnce(
757 Effect.fail(
758 new AzureDevOpsCli.AzureDevOpsCliRateLimitError({
759 operation: "execute",
760 command: "az",
761 cwd: "/w",
762 argumentCount: 1,
763 cause: "429",
764 }),
765 ),
766 );
767 const provider = yield* AzureDevOpsPullRequestProvider.make;
768
769 const error = yield* Effect.flip(
770 provider.getDiff({ cwd: "/w", repository: "web", host: "dev.azure.com", number: 42 }),
771 );
772
773 assert.strictEqual(error.reason, "rate-limited");
774 }),
775 );
776
777 it.effect("takes Azure's own word on a file it will not spell out", () =>
778 Effect.gen(function* () {
779 mockedExecute
780 .mockReturnValueOnce(
781 Effect.succeed(
782 output(
783 json({
784 pullRequestId: 42,
785 title: "Add the page",
786 status: "active",
787 sourceRefName: "refs/heads/feat/page",
788 targetRefName: "refs/heads/main",
789 creationDate: "2026-07-01T00:00:00Z",
790 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
791 repository: { name: "web", project: { name: "platform" } },
792 }),
793 ),
794 ),
795 )
796 .mockReturnValueOnce(
797 Effect.succeed(
798 output(
799 json({
800 value: [
801 {
802 id: 1,
803 sourceRefCommit: { commitId: "a".repeat(40) },
804 commonRefCommit: { commitId: "b".repeat(40) },
805 },
806 ],
807 }),
808 ),
809 ),
810 )
811 .mockReturnValueOnce(
812 Effect.succeed(
813 output(
814 json({
815 changeEntries: [
816 { changeType: "add", item: { path: "/logo.png", objectId: "8f80" } },
817 ],
818 }),
819 ),
820 ),
821 )
822 .mockReturnValueOnce(
823 Effect.succeed(
824 output(json({ content: "iVBORw0KGgo=", contentMetadata: { isBinary: true } })),
825 ),
826 );
827 const provider = yield* AzureDevOpsPullRequestProvider.make;
828
829 const slice = yield* provider.getDiff({
830 cwd: "/w",
831 repository: "web",
832 host: "dev.azure.com",
833 number: 42,
834 });
835
836 expect(argsOfCall(3)).toContain("includeContentMetadata=true");
837 expect(slice.patch).toContain("Binary files a/logo.png and b/logo.png differ");
838 assert.isTrue(slice.truncated);
839 }),
840 );
841
842 it.effect("stops following pages when one of them does not move the cursor on", () =>
843 Effect.gen(function* () {
844 mockedExecute
845 .mockReturnValueOnce(
846 Effect.succeed(
847 output(
848 json({
849 pullRequestId: 42,
850 title: "Add the page",
851 status: "active",
852 sourceRefName: "refs/heads/feat/page",
853 targetRefName: "refs/heads/main",
854 creationDate: "2026-07-01T00:00:00Z",
855 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
856 repository: { name: "web", project: { name: "platform" } },
857 }),
858 ),
859 ),
860 )
861 .mockReturnValueOnce(
862 Effect.succeed(
863 output(
864 json({
865 value: [
866 {
867 id: 1,
868 sourceRefCommit: { commitId: "a".repeat(40) },
869 commonRefCommit: { commitId: "b".repeat(40) },
870 },
871 ],
872 }),
873 ),
874 ),
875 )
876 .mockReturnValueOnce(
877 Effect.succeed(
878 output(
879 json({
880 changeEntries: [{ changeType: "edit", item: { path: "/a.ts", objectId: "8f80" } }],
881 nextSkip: 2_000,
882 }),
883 ),
884 ),
885 )
886 .mockReturnValueOnce(
887 Effect.succeed(
888 output(
889 json({
890 changeEntries: [{ changeType: "edit", item: { path: "/b.ts", objectId: "0ca4" } }],
891 nextSkip: 2_000,
892 }),
893 ),
894 ),
895 );
896 const provider = yield* AzureDevOpsPullRequestProvider.make;
897 assert.isDefined(provider.getFileRevisions);
898
899 const answer = yield* provider.getFileRevisions({
900 cwd: "/w",
901 repository: "web",
902 host: "dev.azure.com",
903 number: 42,
904 paths: ["a.ts", "b.ts", "unlisted.ts"],
905 });
906
907 assert.strictEqual(mockedExecute.mock.calls.length, 4);
908 expect([...answer.revisions]).toEqual([
909 ["a.ts", "8f80"],
910 ["b.ts", "0ca4"],
911 ]);
912 }),
913 );
914
915 it.effect("reads a full page of change entries, which is past the default output limit", () =>
916 Effect.gen(function* () {
917 const response = json({ changeEntries: changeEntries(2_000) });
918 expect(Buffer.byteLength(response)).toBeGreaterThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);
919 mockedExecute.mockImplementationOnce((input) =>
920 Effect.succeed(outputWithin(input.maxOutputBytes, response)),
921 );
922 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
923
924 const page = yield* cli.listIterationChanges({
925 cwd: "/w",
926 location: { project: "platform", repository: "web" },
927 number: 42,
928 iterationId: 1,
929 });
930
931 assert.strictEqual(page.changes.length, 2_000);
932 assert.isFalse(page.truncated);
933 }),
934 );
935
936 it.effect("reads a file whose JSON envelope is past the default output limit", () =>
937 Effect.gen(function* () {
938 const file = "const value = 1;\n".repeat(57_000);
939 const response = json({ content: file });
940 expect(Buffer.byteLength(file)).toBeLessThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);
941 expect(Buffer.byteLength(response)).toBeGreaterThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);
942 mockedExecute.mockImplementationOnce((input) =>
943 Effect.succeed(outputWithin(input.maxOutputBytes, response)),
944 );
945 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
946
947 const item = yield* cli.readItemContent({
948 cwd: "/w",
949 location: { project: "platform", repository: "web" },
950 path: "src/generated/schema.ts",
951 commit: "a".repeat(40),
952 });
953
954 assert.strictEqual(item.contents, file);
955 assert.isFalse(item.isBinary);
956 }),
957 );
958
959 it.effect(
960 "reads a batch of files from one blobs zip, keeping only what Azure's read would say",
961 () =>
962 Effect.gen(function* () {
963 const id = (digit: string) => digit.repeat(40);
964 const utf8 = (text: string) => new TextEncoder().encode(text);
965 let sent = "";
966 mockedExecute.mockImplementationOnce((input) =>
967 Effect.sync(() => {
968 const flag = (name: string) => input.args[input.args.indexOf(name) + 1] ?? "";
969 sent = NodeFS.readFileSync(flag("--in-file"), "utf8");
970 NodeFS.writeFileSync(
971 flag("--out-file"),
972 streamedZip([
973 { name: id("a"), data: utf8("plain text\n") },
974 { name: id("b"), data: utf8("\uFEFFcafé ✓\n") },
975 { name: id("c"), data: Uint8Array.of(0x89, 0x50, 0x00, 0x01) },
976 // Windows-1252 "café" and UTF-16: Azure decodes these itself.
977 { name: id("d"), data: Uint8Array.of(0x63, 0x61, 0x66, 0xe9) },
978 { name: id("e"), data: Uint8Array.of(0xff, 0xfe, 0x68, 0x00) },
979 { name: id("f"), data: utf8("stored\n"), stored: true },
980 { name: id("9"), data: utf8("never asked for\n") },
981 ]),
982 );
983 return output("");
984 }),
985 );
986 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
987
988 const blobs = yield* cli.readBlobs({
989 cwd: "/w",
990 location: { project: "platform", repository: "web" },
991 objectIds: [id("A"), id("b"), id("C"), id("d"), id("e"), id("f"), id("a"), "../etc"],
992 });
993
994 expect(JSON.parse(sent)).toEqual([id("A"), id("b"), id("C"), id("d"), id("e"), id("f")]);
995 expect(argsOfCall(0)).toEqual(
996 expect.arrayContaining(["blobs", "POST", "application/zip", "project=platform"]),
997 );
998 expect(Object.fromEntries(blobs)).toEqual({
999 [id("a")]: { contents: "plain text\n", isBinary: false },
1000 [id("b")]: { contents: "café ✓\n", isBinary: false },
1001 [id("c")]: { contents: "", isBinary: true },
1002 [id("f")]: { contents: "stored\n", isBinary: false },
1003 });
1004 }),
1005 );
1006
1007 it.effect("leaves blobs past the batch's total size to per-file reads", () =>
1008 Effect.gen(function* () {
1009 const ids = ["1", "2", "3", "4", "5", "6"].map((digit) => digit.repeat(40));
1010 // Compresses to a few KiB each, so only the inflated total can bound memory.
1011 const blob = new Uint8Array(3 * 1024 * 1024).fill(0x61);
1012 mockedExecute.mockImplementationOnce((input) =>
1013 Effect.sync(() => {
1014 NodeFS.writeFileSync(
1015 input.args[input.args.indexOf("--out-file") + 1] ?? "",
1016 streamedZip(ids.map((name) => ({ name, data: blob }))),
1017 );
1018 return output("");
1019 }),
1020 );
1021 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1022
1023 const blobs = yield* cli.readBlobs({
1024 cwd: "/w",
1025 location: { project: "platform", repository: "web" },
1026 objectIds: ids,
1027 });
1028
1029 expect([...blobs.keys()]).toEqual(ids.slice(0, 5));
1030 }),
1031 );
1032
1033 it.effect("escapes characters in a file path that would cut the query string", () =>
1034 Effect.gen(function* () {
1035 mockedExecute.mockReturnValueOnce(Effect.succeed(output(json({ content: "x" }))));
1036 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1037
1038 yield* cli.readItemContent({
1039 cwd: "/w",
1040 location: { project: "platform", repository: "web" },
1041 path: "docs/C#/a&b.md",
1042 commit: "a".repeat(40),
1043 });
1044
1045 expect(mockedExecute.mock.calls.at(-1)?.[0].args).toContain("path=%2Fdocs%2FC%23%2Fa%26b.md");
1046 }),
1047 );
1048
1049 it.effect("reports a pull request it cannot place as its own outcome", () =>
1050 Effect.gen(function* () {
1051 mockedExecute.mockReturnValueOnce(
1052 Effect.succeed(
1053 output(
1054 JSON.stringify({
1055 pullRequestId: 42,
1056 title: "Add the page",
1057 sourceRefName: "refs/heads/feat/page",
1058 targetRefName: "refs/heads/main",
1059 creationDate: "2026-07-01T00:00:00Z",
1060 }),
1061 ),
1062 ),
1063 );
1064 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1065
1066 const error = yield* Effect.flip(cli.getPullRequest({ cwd: "/w", number: 42 }));
1067
1068 assert.strictEqual(error._tag, "AzureDevOpsPullRequestIncompleteError");
1069 }),
1070 );
1071
1072 it.effect("refuses a reviewer az would read as a flag, before running anything", () =>
1073 Effect.gen(function* () {
1074 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1075
1076 const error = yield* Effect.flip(
1077 cli.setPullRequestReviewers({
1078 cwd: "/w",
1079 number: 42,
1080 reviewers: ["--query"],
1081 requested: true,
1082 }),
1083 );
1084
1085 assert.strictEqual(error._tag, "AzureDevOpsReviewerNameError");
1086 assert.strictEqual(mockedExecute.mock.calls.length, 0);
1087 }),
1088 );
1089});