Open History to see the last commit
1import * as Result from "effect/Result";
2import { describe, expect, it } from "vite-plus/test";
3
4import {
5 decodeAwardEmojiJson,
6 decodeRepositoryBlobsJson,
7 decodeCommitsJson,
8 decodeGraphqlListSupportJson,
9 decodeMergeRequestGraphqlListJson,
10 decodeMergeMessagesJson,
11 decodeMergeRequestDetailJson,
12 decodeMergeRequestDiffsJson,
13 decodeMergeRequestListJson,
14 decodeMergeRequestFileStatsJson,
15 decodeMergeRequestStatsJson,
16 decodeMergeRequestWatchFingerprintJson,
17 decodeReferenceCandidatesJson,
18 decodeNotesJson,
19 decodeOwnAwardIdJson,
20 decodeListStatesJson,
21 decodeTriggerJobChecksJson,
22 decodePipelineStageChecksJson,
23} from "./gitLabMergeRequestJson.ts";
24
25function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
26 return JSON.stringify(
27 entries.map((entry) => ({
28 iid: 1,
29 title: "Add the merge requests page",
30 web_url: "https://gitlab.com/acme/web/-/merge_requests/1",
31 source_branch: "feat/page",
32 target_branch: "main",
33 created_at: "2026-07-01T00:00:00Z",
34 updated_at: "2026-07-02T00:00:00Z",
35 ...entry,
36 })),
37 );
38}
39
40function detailJson(entry: Record<string, unknown>): string {
41 return JSON.stringify({
42 iid: 1,
43 title: "Add the merge requests page",
44 web_url: "https://gitlab.com/acme/web/-/merge_requests/1",
45 source_branch: "feat/page",
46 target_branch: "main",
47 created_at: "2026-07-01T00:00:00Z",
48 updated_at: "2026-07-02T00:00:00Z",
49 ...entry,
50 });
51}
52
53function expectSuccess<A>(result: Result.Result<A, unknown>): A {
54 expect(Result.isSuccess(result)).toBe(true);
55 if (!Result.isSuccess(result)) throw new Error("expected a successful decode");
56 return result.success;
57}
58
59describe("decodeMergeRequestListJson", () => {
60 it("reads a merge request as a change request", () => {
61 const batch = expectSuccess(
62 decodeMergeRequestListJson(
63 listJson([
64 {
65 iid: 42,
66 author: { username: "bilal", name: "Bilal" },
67 state: "opened",
68 merge_status: "can_be_merged",
69 draft: false,
70 reviewers: [{ username: "julius" }],
71 labels: ["backend", " "],
72 },
73 ]),
74 ),
75 );
76
77 expect(batch.items).toHaveLength(1);
78 expect(batch.items[0]).toMatchObject({
79 number: 42,
80 author: { login: "bilal", name: "Bilal" },
81 headBranch: "feat/page",
82 baseBranch: "main",
83 state: "open",
84 isDraft: false,
85 mergeability: "mergeable",
86 reviewRequestLogins: ["julius"],
87 labels: [{ name: "backend", color: null }],
88 });
89 });
90
91 it("treats a merged timestamp as merged whatever the state says", () => {
92 const batch = expectSuccess(
93 decodeMergeRequestListJson(
94 listJson([{ state: "opened", merged_at: "2026-07-03T00:00:00Z" }]),
95 ),
96 );
97
98 expect(batch.items[0]?.state).toBe("merged");
99 });
100
101 it("reads the legacy draft flag", () => {
102 const batch = expectSuccess(decodeMergeRequestListJson(listJson([{ work_in_progress: true }])));
103
104 expect(batch.items[0]?.isDraft).toBe(true);
105 });
106
107 it("calls a conflicted merge request conflicting even while the merge check is pending", () => {
108 const batch = expectSuccess(
109 decodeMergeRequestListJson(listJson([{ merge_status: "checking", has_conflicts: true }])),
110 );
111
112 expect(batch.items[0]?.mergeability).toBe("conflicting");
113 });
114
115 it("skips a malformed row but still counts it, so paging does not stop early", () => {
116 const batch = expectSuccess(
117 decodeMergeRequestListJson(
118 JSON.stringify([{ iid: "not a number" }, ...JSON.parse(listJson([{}]))]),
119 ),
120 );
121
122 expect(batch.items).toHaveLength(1);
123 expect(batch.rawIndexes).toEqual([1]);
124 expect(batch.rawCount).toBe(2);
125 });
126});
127
128describe("decodeMergeRequestDetailJson", () => {
129 it("preserves a required rebase while CI is running or successful", () => {
130 for (const status of ["running", "success"]) {
131 const detail = expectSuccess(
132 decodeMergeRequestDetailJson(
133 detailJson({
134 merge_status: "can_be_merged",
135 detailed_merge_status: "need_rebase",
136 has_conflicts: false,
137 head_pipeline: { status },
138 }),
139 ),
140 );
141 expect(detail.rebaseRequired).toBe(true);
142 expect(detail.mergeability).toBe("mergeable");
143 }
144 });
145
146 it("distinguishes a cleared rebase blocker from an inconclusive merge check", () => {
147 expect(
148 expectSuccess(
149 decodeMergeRequestDetailJson(detailJson({ detailed_merge_status: "mergeable" })),
150 ).rebaseRequired,
151 ).toBe(false);
152 for (const detailed_merge_status of [undefined, "checking", "ci_still_running"]) {
153 expect(
154 expectSuccess(decodeMergeRequestDetailJson(detailJson({ detailed_merge_status })))
155 .rebaseRequired,
156 ).toBeUndefined();
157 }
158 });
159
160 it("reads the description, file count and pipeline", () => {
161 const detail = expectSuccess(
162 decodeMergeRequestDetailJson(
163 detailJson({
164 description: "Ships the page.",
165 changes_count: "3",
166 reviewers: [{ username: "julius", name: "Julius" }],
167 head_pipeline: {
168 status: "success",
169 web_url: "https://gitlab.com/acme/web/-/pipelines/9",
170 source: "merge_request_event",
171 },
172 }),
173 ),
174 );
175
176 expect(detail.body).toBe("Ships the page.");
177 expect(detail.changedFiles).toBe(3);
178 expect(detail.reviewers).toEqual([{ login: "julius", name: "Julius", avatarUrl: null }]);
179 expect(detail.checks).toEqual([
180 {
181 name: "Pipeline",
182 status: "success",
183 description: "merge_request_event",
184 url: "https://gitlab.com/acme/web/-/pipelines/9",
185 },
186 ]);
187 });
188
189 it.each(["canceled", "canceling"])("maps a %s pipeline to cancelled", (status) => {
190 const detail = expectSuccess(
191 decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status } })),
192 );
193
194 expect(detail.checks[0]?.status).toBe("cancelled");
195 });
196
197 it("reads an uncounted change set as its floor", () => {
198 const detail = expectSuccess(
199 decodeMergeRequestDetailJson(detailJson({ changes_count: "1000+" })),
200 );
201
202 expect(detail.changedFiles).toBe(1000);
203 });
204
205 it("reads the head commit, and says nothing where GitLab omitted it", () => {
206 const headSha = (entry: Record<string, unknown>) =>
207 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).headSha;
208 const sha = "afce4da4d5fe7d2fd0647b5b864526ea0a2827cb";
209
210 expect(headSha({ sha })).toBe(sha);
211 expect(headSha({ sha, diff_refs: null })).toBe(sha);
212 expect(headSha({ sha, merge_commit_sha: "0".repeat(40) })).toBe(sha);
213 expect(headSha({})).toBeUndefined();
214 expect(headSha({ sha: null })).toBeUndefined();
215 expect(headSha({ sha: " " })).toBeUndefined();
216 });
217
218 it("reads the diff refs threads are placed against", () => {
219 const diffRefs = (entry: Record<string, unknown>) =>
220 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).diffRefs;
221
222 expect(diffRefs({ diff_refs: { base_sha: "b", start_sha: "s", head_sha: "h" } })).toEqual({
223 baseSha: "b",
224 startSha: "s",
225 headSha: "h",
226 });
227 expect(diffRefs({ diff_refs: null })).toBeUndefined();
228 expect(
229 diffRefs({ diff_refs: { base_sha: null, start_sha: "s", head_sha: "h" } }),
230 ).toBeUndefined();
231 });
232
233 it("reads either auto-merge field, and says nothing where GitLab named neither", () => {
234 const armed = (entry: Record<string, unknown>) =>
235 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).autoMergeEnabled;
236
237 expect(armed({ merge_when_pipeline_succeeds: true })).toBe(true);
238 expect(armed({ auto_merge_enabled: true })).toBe(true);
239 expect(armed({ merge_when_pipeline_succeeds: false })).toBe(false);
240 expect(armed({})).toBeUndefined();
241 });
242
243 it("keeps the squash choice stored with auto-merge", () => {
244 expect(
245 expectSuccess(
246 decodeMergeRequestDetailJson(
247 detailJson({ auto_merge_enabled: true, squash_on_merge: true }),
248 ),
249 ),
250 ).toMatchObject({ autoMergeEnabled: true, autoMergeMethod: "squash" });
251
252 expect(
253 expectSuccess(
254 decodeMergeRequestDetailJson(
255 detailJson({
256 auto_merge_enabled: true,
257 squash: true,
258 squash_on_merge: false,
259 }),
260 ),
261 ).autoMergeMethod,
262 ).toBeUndefined();
263 });
264
265 it("keeps a divergence GitLab did not count apart from a divergence of none", () => {
266 const behind = (entry: Record<string, unknown>) =>
267 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).divergedCommits;
268
269 expect(behind({ diverged_commits_count: 3 })).toBe(3);
270 expect(behind({ diverged_commits_count: 0 })).toBe(0);
271 expect(behind({})).toBeUndefined();
272 expect(behind({ diverged_commits_count: null })).toBeUndefined();
273 });
274
275 it.each(["scheduled", " SCHEDULED "])("keeps a delayed pipeline pending: %s", (status) => {
276 const detail = expectSuccess(
277 decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status } })),
278 );
279
280 expect(detail.checks[0]?.status).toBe("pending");
281 });
282
283 it("maps a pipeline waiting on a person to neutral, not failure", () => {
284 const detail = expectSuccess(
285 decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status: "manual" } })),
286 );
287
288 expect(detail.checks[0]?.status).toBe("neutral");
289 });
290});
291
292describe("decodePipelineStageChecksJson", () => {
293 function stagesJson(
294 stages: ReadonlyArray<Record<string, unknown> | null> | null,
295 hasNextPage = false,
296 ): string {
297 return JSON.stringify({
298 data: {
299 project: {
300 mergeRequest: {
301 headPipeline:
302 stages === null
303 ? null
304 : {
305 path: "/fork/web/-/pipelines/9",
306 stages: { nodes: stages, pageInfo: { hasNextPage } },
307 },
308 },
309 },
310 },
311 });
312 }
313
314 it("shows every job under its stage", () => {
315 const checks = expectSuccess(
316 decodePipelineStageChecksJson(
317 stagesJson([
318 {
319 name: "build",
320 status: "success",
321 jobs: {
322 nodes: [
323 { name: "compile", status: "FAILED", retried: true, webPath: "/acme/web/-/jobs/1" },
324 {
325 name: "compile",
326 status: "SUCCESS",
327 detailedStatus: { label: "passed" },
328 webPath: "/acme/web/-/jobs/2",
329 },
330 ],
331 },
332 },
333 {
334 name: "test",
335 status: "failed",
336 jobs: {
337 nodes: [
338 {
339 name: "unit",
340 status: "FAILED",
341 allowFailure: false,
342 webPath: "/acme/web/-/jobs/3",
343 },
344 {
345 name: "lint",
346 status: "FAILED",
347 allowFailure: true,
348 webPath: "/acme/web/-/jobs/4",
349 },
350 { name: "slow", status: "CANCELED", webPath: "/acme/web/-/jobs/5" },
351 { name: "e2e", status: "RUNNING", webPath: "/acme/web/-/jobs/6" },
352 ],
353 },
354 },
355 {
356 name: "deploy",
357 status: "manual",
358 jobs: { nodes: [{ name: "release", status: "MANUAL", webPath: "/acme/web/-/jobs/7" }] },
359 },
360 ]),
361 "https://gitlab.example.com",
362 ),
363 );
364
365 expect(checks?.map((check) => [check.name, check.status, check.url])).toEqual([
366 ["build / compile", "success", "https://gitlab.example.com/acme/web/-/jobs/2"],
367 ["test / unit", "failure", "https://gitlab.example.com/acme/web/-/jobs/3"],
368 ["test / lint", "neutral", "https://gitlab.example.com/acme/web/-/jobs/4"],
369 ["test / slow", "cancelled", "https://gitlab.example.com/acme/web/-/jobs/5"],
370 ["test / e2e", "pending", "https://gitlab.example.com/acme/web/-/jobs/6"],
371 ["deploy / release", "neutral", "https://gitlab.example.com/acme/web/-/jobs/7"],
372 ]);
373 expect(checks?.[0]?.description).toBe("passed");
374 });
375
376 it.each([
377 ["no jobs", undefined],
378 ["an empty job list", { nodes: [] }],
379 [
380 "more jobs than one page",
381 { nodes: [{ name: "unit", status: "FAILED" }], pageInfo: { hasNextPage: true } },
382 ],
383 ["a job GitLab could not resolve", { nodes: [{ name: "unit", status: "FAILED" }, null] }],
384 [
385 "a job without a name",
386 {
387 nodes: [
388 { name: "unit", status: "FAILED" },
389 { name: null, status: "FAILED" },
390 ],
391 },
392 ],
393 ])("keeps a stage whole where its jobs come back with %s", (_, jobs) => {
394 expect(
395 expectSuccess(
396 decodePipelineStageChecksJson(
397 stagesJson([
398 {
399 name: "test",
400 status: "failed",
401 detailedStatus: { label: "failed", detailsPath: "/fork/web/-/pipelines/9#test" },
402 ...(jobs === undefined ? {} : { jobs }),
403 },
404 ]),
405 "https://gitlab.com",
406 ),
407 ),
408 ).toEqual([
409 {
410 name: "test",
411 status: "failure",
412 description: "failed",
413 url: "https://gitlab.com/fork/web/-/pipelines/9#test",
414 },
415 ]);
416 });
417
418 it("answers nothing where there are no stages to show", () => {
419 expect(
420 expectSuccess(decodePipelineStageChecksJson(stagesJson(null), "https://gitlab.com")),
421 ).toBe(null);
422 expect(expectSuccess(decodePipelineStageChecksJson(stagesJson([]), "https://gitlab.com"))).toBe(
423 null,
424 );
425 // A stage past the first page could be the failed one.
426 expect(
427 expectSuccess(
428 decodePipelineStageChecksJson(
429 stagesJson([{ name: "build", status: "success" }], true),
430 "https://gitlab.com",
431 ),
432 ),
433 ).toBe(null);
434 // A stage GitLab failed to resolve comes back null beside an error, and could be the failed one.
435 expect(
436 expectSuccess(
437 decodePipelineStageChecksJson(
438 stagesJson([{ name: "build", status: "success" }, null]),
439 "https://gitlab.com",
440 ),
441 ),
442 ).toBe(null);
443 expect(
444 expectSuccess(
445 decodePipelineStageChecksJson(
446 stagesJson([
447 { name: "build", status: "success" },
448 { name: null, status: "failed" },
449 ]),
450 "https://gitlab.com",
451 ),
452 ),
453 ).toBe(null);
454 expect(
455 expectSuccess(
456 decodePipelineStageChecksJson(
457 JSON.stringify({
458 ...JSON.parse(stagesJson([{ name: "build", status: "success" }])),
459 errors: [{ message: "boom" }],
460 }),
461 "https://gitlab.com",
462 ),
463 ),
464 ).toBe(null);
465 // GitLab answers an error it hit with no data at all.
466 expect(
467 expectSuccess(
468 decodePipelineStageChecksJson(
469 JSON.stringify({ errors: [{ message: "boom" }] }),
470 "https://gitlab.com",
471 ),
472 ),
473 ).toBe(null);
474 });
475});
476
477describe("decodeNotesJson", () => {
478 it("keeps comments and drops GitLab's own activity notes", () => {
479 const notes = expectSuccess(
480 decodeNotesJson(
481 JSON.stringify([
482 {
483 id: 1,
484 body: "assigned to @bilal",
485 system: true,
486 created_at: "2026-07-01T00:00:00Z",
487 },
488 {
489 id: 2,
490 body: "Looks good.",
491 author: { username: "julius" },
492 created_at: "2026-07-02T00:00:00Z",
493 },
494 { id: 3, body: " ", created_at: "2026-07-03T00:00:00Z" },
495 ]),
496 ),
497 );
498
499 expect(notes.comments).toHaveLength(1);
500 expect(notes.comments[0]).toMatchObject({
501 id: "2",
502 kind: "issue-comment",
503 body: "Looks good.",
504 });
505 expect(notes.rawCount).toBe(3);
506 });
507
508 it("reads a line note as a review comment on its file", () => {
509 const notes = expectSuccess(
510 decodeNotesJson(
511 JSON.stringify([
512 {
513 id: 7,
514 type: "DiffNote",
515 body: "Rename this.",
516 created_at: "2026-07-02T00:00:00Z",
517 position: { new_path: "src/app.ts", old_path: "src/old.ts" },
518 },
519 ]),
520 ),
521 );
522
523 expect(notes.comments[0]).toMatchObject({ kind: "review-comment", path: "src/app.ts" });
524 });
525
526 it("falls back to the old path for a note on a deleted line", () => {
527 const notes = expectSuccess(
528 decodeNotesJson(
529 JSON.stringify([
530 {
531 id: 8,
532 type: "DiffNote",
533 body: "Gone.",
534 created_at: "2026-07-02T00:00:00Z",
535 position: { new_path: null, old_path: "src/old.ts" },
536 },
537 ]),
538 ),
539 );
540
541 expect(notes.comments[0]?.path).toBe("src/old.ts");
542 });
543});
544
545describe("decodeCommitsJson", () => {
546 it("falls back to the creation timestamp when there is no commit date", () => {
547 const commits = expectSuccess(
548 decodeCommitsJson(
549 JSON.stringify([
550 {
551 id: "aaa",
552 created_at: "2026-07-01T00:00:00+08:00",
553 author_name: "Ada Lovelace",
554 author_email: "ada@example.com",
555 },
556 ]),
557 ),
558 );
559
560 expect(commits[0]).toMatchObject({
561 oid: "aaa",
562 committedDate: "2026-07-01T00:00:00+08:00",
563 authors: [{ login: "Ada Lovelace", name: "Ada Lovelace", avatarUrl: null }],
564 });
565 });
566});
567
568describe("decodeMergeRequestDiffsJson", () => {
569 it("quotes literal backslashes without interpreting them as escapes", () => {
570 const result = expectSuccess(
571 decodeMergeRequestDiffsJson(
572 JSON.stringify([
573 {
574 old_path: String.raw`src\notes.ts`,
575 new_path: String.raw`src\notes.ts`,
576 diff: "@@ -1 +1 @@\n-old\n+new",
577 },
578 ]),
579 ),
580 );
581
582 expect(result.patch).toBe(
583 [
584 String.raw`diff --git "a/src\\notes.ts" "b/src\\notes.ts"`,
585 String.raw`--- "a/src\\notes.ts"`,
586 String.raw`+++ "b/src\\notes.ts"`,
587 "@@ -1 +1 @@",
588 "-old",
589 "+new",
590 "",
591 ].join("\n"),
592 );
593 });
594
595 it("preserves spaces and literal backslashes in both rename paths", () => {
596 const result = expectSuccess(
597 decodeMergeRequestDiffsJson(
598 JSON.stringify([
599 {
600 old_path: String.raw` old\name.ts `,
601 new_path: String.raw` new\name.ts `,
602 renamed_file: true,
603 diff: "",
604 },
605 ]),
606 ),
607 );
608
609 expect(result.patch).toBe(
610 [
611 String.raw`diff --git "a/ old\\name.ts " "b/ new\\name.ts "`,
612 "similarity index 100%",
613 String.raw`rename from " old\\name.ts "`,
614 String.raw`rename to " new\\name.ts "`,
615 String.raw`--- "a/ old\\name.ts "`,
616 String.raw`+++ "b/ new\\name.ts "`,
617 ].join("\n"),
618 );
619 });
620
621 it("assembles a unified patch GitLab does not return", () => {
622 const result = expectSuccess(
623 decodeMergeRequestDiffsJson(
624 JSON.stringify([
625 {
626 old_path: "src/app.ts",
627 new_path: "src/app.ts",
628 diff: "@@ -1 +1 @@\n-old\n+new\n",
629 },
630 ]),
631 ),
632 );
633
634 expect(result.patch).toBe(
635 [
636 "diff --git a/src/app.ts b/src/app.ts",
637 "--- a/src/app.ts",
638 "+++ b/src/app.ts",
639 "@@ -1 +1 @@",
640 "-old",
641 "+new",
642 "",
643 ].join("\n"),
644 );
645 expect(result.truncated).toBe(false);
646 });
647
648 it("points a new file at /dev/null on the left and a deleted file on the right", () => {
649 const result = expectSuccess(
650 decodeMergeRequestDiffsJson(
651 JSON.stringify([
652 {
653 old_path: "src/new.ts",
654 new_path: "src/new.ts",
655 new_file: true,
656 b_mode: "100755",
657 diff: "@@ -0,0 +1 @@\n+hello\n",
658 },
659 {
660 old_path: "src/gone.ts",
661 new_path: "src/gone.ts",
662 deleted_file: true,
663 diff: "@@ -1 +0,0 @@\n-bye\n",
664 },
665 ]),
666 ),
667 );
668
669 expect(result.patch).toContain("new file mode 100755");
670 expect(result.patch).toContain("--- /dev/null");
671 expect(result.patch).toContain("deleted file mode 100644");
672 expect(result.patch).toContain("+++ /dev/null");
673 });
674
675 it("reports truncation for a file GitLab refused to inline", () => {
676 const result = expectSuccess(
677 decodeMergeRequestDiffsJson(
678 JSON.stringify([{ old_path: "big.bin", new_path: "big.bin", diff: "", too_large: true }]),
679 ),
680 );
681
682 expect(result.truncated).toBe(true);
683 expect(result.patch).toContain("diff --git a/big.bin b/big.bin");
684 expect(result.withheldPaths).toEqual(["big.bin"]);
685 });
686
687 it("reports how many files GitLab returned, so the caller can page", () => {
688 const result = expectSuccess(
689 decodeMergeRequestDiffsJson(
690 JSON.stringify(
691 Array.from({ length: 3 }, (_, index) => ({
692 old_path: `src/${index}.ts`,
693 new_path: `src/${index}.ts`,
694 diff: "@@ -1 +1 @@\n-a\n+b\n",
695 })),
696 ),
697 ),
698 );
699
700 expect(result.rawCount).toBe(3);
701 expect(result.truncated).toBe(false);
702 expect(result.patch).toContain("src/2.ts");
703 });
704});
705
706describe("decodeTriggerJobChecksJson", () => {
707 it("reads a downstream failure GitLab was told to allow as neutral, not failure", () => {
708 const result = expectSuccess(
709 decodeTriggerJobChecksJson(
710 JSON.stringify([
711 { name: "e2e", allow_failure: true, downstream_pipeline: { status: "failed" } },
712 { name: "deploy", allow_failure: false, downstream_pipeline: { status: "running" } },
713 { name: 7 },
714 ]),
715 ),
716 );
717
718 expect(result.checks.map((check) => [check.name, check.status])).toEqual([
719 ["e2e", "neutral"],
720 ["deploy", "pending"],
721 ]);
722 expect(result.rawCount).toBe(3);
723 });
724});
725
726describe("merge request viewer fields", () => {
727 it("leaves merging permitted where GitLab answered without the field", () => {
728 expect(expectSuccess(decodeMergeRequestDetailJson(detailJson({}))).viewerCanMerge).toBe(true);
729 expect(
730 expectSuccess(decodeMergeRequestDetailJson(detailJson({ user: null }))).viewerCanMerge,
731 ).toBe(true);
732 });
733});
734
735describe("decodeAwardEmojiJson", () => {
736 it("reads MR-level awards, keys per-note awards by the REST id inside their gid, ignores an award outside the eight, and collects bot note authors", () => {
737 const result = expectSuccess(
738 decodeAwardEmojiJson(
739 JSON.stringify({
740 data: {
741 currentUser: { username: "bilal" },
742 project: {
743 mergeRequest: {
744 awardEmoji: {
745 nodes: [
746 { name: "thumbsup", user: { username: "bilal" } },
747 { name: "thumbsup", user: { username: "julius" } },
748 ],
749 },
750 notes: {
751 pageInfo: { hasNextPage: false, endCursor: null },
752 nodes: [
753 {
754 id: "gid://gitlab/DiffNote/42",
755 author: { username: "julius", bot: false },
756 awardEmoji: { nodes: [{ name: "heart", user: { username: "julius" } }] },
757 },
758 {
759 id: "gid://gitlab/Note/7",
760 author: { username: "project_278964_bot_89f97e2c", bot: true },
761 awardEmoji: {
762 nodes: [{ name: "partyparrot", user: { username: "bilal" } }],
763 },
764 },
765 ],
766 },
767 },
768 },
769 },
770 }),
771 ),
772 );
773
774 expect(result.reactions).toEqual([
775 { content: "thumbs-up", count: 2, actors: ["julius"], viewerHasReacted: true },
776 ]);
777 expect([...result.reactionsByNoteId]).toEqual([
778 ["42", [{ content: "heart", count: 1, actors: ["julius"], viewerHasReacted: false }]],
779 ]);
780 expect([...result.botLogins]).toEqual(["project_278964_bot_89f97e2c"]);
781 expect(result.nextCursor).toBeNull();
782 });
783
784 it("dates a note's edit only when someone edited its text, not when its thread was resolved", () => {
785 const result = expectSuccess(
786 decodeAwardEmojiJson(
787 JSON.stringify({
788 data: {
789 currentUser: { username: "bilal" },
790 project: {
791 mergeRequest: {
792 awardEmoji: { nodes: [] },
793 notes: {
794 pageInfo: { hasNextPage: false, endCursor: null },
795 nodes: [
796 {
797 id: "gid://gitlab/Note/1",
798 lastEditedAt: "2026-07-02T00:00:00Z",
799 lastEditedBy: { username: "julius" },
800 resolved: false,
801 },
802 {
803 id: "gid://gitlab/Note/2",
804 lastEditedAt: "2026-07-01T00:00:00Z",
805 lastEditedBy: null,
806 resolved: false,
807 },
808 {
809 id: "gid://gitlab/DiscussionNote/3",
810 lastEditedAt: "2026-07-03T00:00:00Z",
811 lastEditedBy: { username: "julius" },
812 resolved: true,
813 },
814 ],
815 },
816 },
817 },
818 },
819 }),
820 ),
821 );
822
823 expect([...result.editedAtByNoteId]).toEqual([["1", "2026-07-02T00:00:00Z"]]);
824 });
825
826 it("matches the viewer's username case-insensitively, since GitLab is not consistent about case", () => {
827 const result = expectSuccess(
828 decodeAwardEmojiJson(
829 JSON.stringify({
830 data: {
831 currentUser: { username: "Bilal" },
832 project: {
833 mergeRequest: {
834 awardEmoji: {
835 nodes: [
836 { name: "heart", user: { username: "bilal" } },
837 { name: "heart", user: { username: "julius" } },
838 ],
839 },
840 notes: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] },
841 },
842 },
843 },
844 }),
845 ),
846 );
847
848 expect(result.reactions).toEqual([
849 { content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
850 ]);
851 });
852});
853
854describe("decodeOwnAwardIdJson", () => {
855 const awards = JSON.stringify([
856 { id: 101, name: "thumbsup", user: { username: "julius" } },
857 { id: 102, name: "thumbsup", user: { username: "bilal" } },
858 ]);
859
860 it("finds the reader's own award of that name, which is the one a removal deletes", () => {
861 expect(
862 expectSuccess(decodeOwnAwardIdJson(awards, { content: "thumbs-up", viewer: "bilal" })),
863 ).toEqual({ id: 102, empty: false });
864 });
865});
866
867describe("decodeRepositoryBlobsJson", () => {
868 function expectBlobs(result: Result.Result<ReadonlyMap<string, string> | null, unknown>) {
869 const blobs = expectSuccess(result);
870 expect(blobs).not.toBe(null);
871 if (blobs === null) throw new Error("expected an answered blobs query");
872 return blobs;
873 }
874
875 it("leaves out a node missing either half, which names no version", () => {
876 const blobs = expectBlobs(
877 decodeRepositoryBlobsJson(
878 JSON.stringify({
879 data: {
880 project: {
881 repository: {
882 blobs: {
883 nodes: [
884 { path: "src/a.ts", oid: null },
885 { path: null, oid: "bbb222" },
886 null,
887 { path: "src/c.ts", oid: "ccc333" },
888 ],
889 },
890 },
891 },
892 },
893 }),
894 ),
895 );
896
897 expect([...blobs]).toEqual([["src/c.ts", "ccc333"]]);
898 });
899
900 it("keys a blob by the path the host spelled, spaces and all", () => {
901 const blobs = expectBlobs(
902 decodeRepositoryBlobsJson(
903 JSON.stringify({
904 data: {
905 project: {
906 repository: {
907 blobs: {
908 nodes: [
909 { path: " leading.ts", oid: "aaa111" },
910 { path: "trailing.ts ", oid: "bbb222" },
911 { path: " ", oid: "ccc333" },
912 { path: "", oid: "ddd444" },
913 ],
914 },
915 },
916 },
917 },
918 }),
919 ),
920 );
921
922 expect([...blobs]).toEqual([
923 [" leading.ts", "aaa111"],
924 ["trailing.ts ", "bbb222"],
925 [" ", "ccc333"],
926 ]);
927 });
928
929 it("tells a project the reader cannot see from a revision with none of the files", () => {
930 expect(
931 expectSuccess(decodeRepositoryBlobsJson(JSON.stringify({ data: { project: null } }))),
932 ).toBe(null);
933 expect(
934 expectSuccess(
935 decodeRepositoryBlobsJson(JSON.stringify({ data: { project: { repository: null } } })),
936 ),
937 ).toBe(null);
938 expect(
939 expectSuccess(
940 decodeRepositoryBlobsJson(
941 JSON.stringify({ data: { project: { repository: { blobs: { nodes: [] } } } } }),
942 ),
943 ),
944 ).toEqual(new Map());
945 });
946});
947
948describe("decodeListStatesJson", () => {
949 const statesOf = (enterprise: boolean | null, nodes: ReadonlyArray<unknown>) =>
950 expectSuccess(
951 decodeListStatesJson(
952 JSON.stringify({
953 data: {
954 metadata: enterprise === null ? null : { enterprise },
955 project: { mergeRequests: { nodes } },
956 },
957 }),
958 ),
959 );
960 const approvedBy = (...usernames: ReadonlyArray<string>) => ({
961 nodes: usernames.map((username) => ({ username })),
962 });
963 const reviewers = (...reviewStates: ReadonlyArray<string>) => ({
964 nodes: reviewStates.map((reviewState) => ({ mergeRequestInteraction: { reviewState } })),
965 });
966
967 it.each([
968 {
969 reading: "an approval short of Enterprise approval rules",
970 enterprise: true,
971 approval: { approved: false, approvedBy: approvedBy("GitLabDuo") },
972 decision: "review-required",
973 },
974 {
975 reading: "Enterprise approval rules no one has approved against",
976 enterprise: true,
977 approval: { approved: false, approvedBy: approvedBy() },
978 decision: "review-required",
979 },
980 {
981 reading: "Enterprise approval rules met",
982 enterprise: true,
983 approval: { approved: true, approvedBy: approvedBy("julius") },
984 decision: "approved",
985 },
986 {
987 reading: "Enterprise without approval rules or approvals",
988 enterprise: true,
989 approval: { approved: true, approvedBy: approvedBy() },
990 decision: null,
991 },
992 {
993 reading: "Community Edition with an approval",
994 enterprise: false,
995 approval: { approved: true, approvedBy: approvedBy("julius") },
996 decision: "approved",
997 },
998 {
999 reading: "Community Edition without approvals",
1000 enterprise: false,
1001 approval: { approved: false, approvedBy: approvedBy() },
1002 decision: null,
1003 },
1004 {
1005 reading: "a reviewer requesting changes after another approved",
1006 enterprise: true,
1007 approval: {
1008 approved: true,
1009 approvedBy: approvedBy("julius"),
1010 reviewers: reviewers("APPROVED", "REQUESTED_CHANGES"),
1011 },
1012 decision: "changes-requested",
1013 },
1014 {
1015 reading: "a Community Edition reviewer requesting changes",
1016 enterprise: false,
1017 approval: {
1018 approved: false,
1019 approvedBy: approvedBy(),
1020 reviewers: reviewers("REQUESTED_CHANGES"),
1021 },
1022 decision: "changes-requested",
1023 },
1024 {
1025 reading: "reviewers who have not asked for changes",
1026 enterprise: false,
1027 approval: {
1028 approved: true,
1029 approvedBy: approvedBy("julius"),
1030 reviewers: reviewers("UNREVIEWED", "REVIEWED"),
1031 },
1032 decision: "approved",
1033 },
1034 ])("reads $reading as $decision", ({ enterprise, approval, decision }) => {
1035 expect([...statesOf(enterprise, [{ iid: "7", ...approval }])]).toEqual([
1036 [7, { reviewDecision: decision, checksState: null }],
1037 ]);
1038 });
1039
1040 it.each([
1041 { pipeline: { status: "SUCCESS" }, checksState: "passing" },
1042 { pipeline: { status: "FAILED" }, checksState: "failing" },
1043 { pipeline: { status: "CANCELED" }, checksState: "failing" },
1044 { pipeline: { status: "RUNNING" }, checksState: "pending" },
1045 { pipeline: { status: "WAITING_FOR_RESOURCE" }, checksState: "pending" },
1046 { pipeline: { status: "MANUAL" }, checksState: null },
1047 { pipeline: { status: "SKIPPED" }, checksState: null },
1048 { pipeline: null, checksState: null },
1049 ])(
1050 "reads a $pipeline.status head pipeline as $checksState checks",
1051 ({ pipeline, checksState }) => {
1052 expect([
1053 ...statesOf(false, [
1054 { iid: "7", approved: false, approvedBy: approvedBy(), headPipeline: pipeline },
1055 ]),
1056 ]).toEqual([[7, { reviewDecision: null, checksState }]]);
1057 },
1058 );
1059
1060 it("leaves out a merge request it cannot key, and a project the reader cannot see", () => {
1061 expect([...statesOf(true, [null, { iid: "x", approved: true }])]).toEqual([]);
1062 expect(
1063 expectSuccess(decodeListStatesJson(JSON.stringify({ data: { project: null } }))),
1064 ).toEqual(new Map());
1065 });
1066
1067 it("keeps the checks of a merge request whose approval it cannot judge", () => {
1068 expect([
1069 ...statesOf(null, [
1070 {
1071 iid: "7",
1072 approved: false,
1073 approvedBy: approvedBy(),
1074 headPipeline: { status: "FAILED" },
1075 },
1076 ]),
1077 ...statesOf(true, [
1078 { iid: "8", approved: null, approvedBy: approvedBy("julius") },
1079 { iid: "9", approved: true, approvedBy: null },
1080 ]),
1081 ]).toEqual([
1082 [7, { checksState: "failing" }],
1083 [8, { checksState: null }],
1084 [9, { checksState: null }],
1085 ]);
1086 });
1087});
1088
1089describe("decodeReferenceCandidatesJson", () => {
1090 it("prefixes merge requests with ! and skips malformed entries", () => {
1091 const raw = JSON.stringify([
1092 { iid: 5, title: "Ship it", state: "merged" },
1093 { iid: 6, title: "Draft", state: "opened" },
1094 { iid: 7, title: "Locked", state: "locked" },
1095 { title: "No iid", state: "opened" },
1096 ]);
1097 const decoded = decodeReferenceCandidatesJson(raw, "change-request");
1098 expect(Result.isSuccess(decoded) && decoded.success).toEqual({
1099 items: [
1100 { reference: "!5", kind: "change-request", number: 5, title: "Ship it", state: "merged" },
1101 { reference: "!6", kind: "change-request", number: 6, title: "Draft", state: "open" },
1102 { reference: "!7", kind: "change-request", number: 7, title: "Locked", state: "closed" },
1103 ],
1104 rawCount: 4,
1105 });
1106 const issues = decodeReferenceCandidatesJson(raw, "issue");
1107 expect(Result.isSuccess(issues) && issues.success.items[0]?.reference).toBe("#5");
1108 });
1109});
1110
1111describe("decodeMergeRequestStatsJson", () => {
1112 it("keys the counts by merge request number", () => {
1113 const stats = expectSuccess(
1114 decodeMergeRequestStatsJson(
1115 JSON.stringify({
1116 data: {
1117 project: {
1118 mergeRequests: {
1119 nodes: [
1120 { iid: "7", diffStatsSummary: { additions: 12, deletions: 3 } },
1121 { iid: "8", diffStatsSummary: null },
1122 ],
1123 },
1124 },
1125 },
1126 }),
1127 ),
1128 );
1129
1130 // A merge request without a summary is left out rather than shown as zero lines changed.
1131 expect([...stats]).toEqual([[7, { additions: 12, deletions: 3 }]]);
1132 });
1133
1134 it("answers nothing for a project the token cannot see", () => {
1135 const stats = expectSuccess(
1136 decodeMergeRequestStatsJson(JSON.stringify({ data: { project: null } })),
1137 );
1138
1139 expect(stats.size).toBe(0);
1140 });
1141
1142 it("reports a file list shorter than the summary as truncated", () => {
1143 const read = (fileCount: number) =>
1144 expectSuccess(
1145 decodeMergeRequestFileStatsJson(
1146 JSON.stringify({
1147 data: {
1148 project: {
1149 mergeRequest: {
1150 diffStatsSummary: { fileCount },
1151 diffStats: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
1152 },
1153 },
1154 },
1155 }),
1156 ),
1157 );
1158
1159 expect(read(1)).toEqual({
1160 files: [{ path: "src/a.ts", additions: 2, deletions: 1 }],
1161 truncated: false,
1162 });
1163 expect(read(2).truncated).toBe(true);
1164 });
1165});
1166
1167describe("decodeMergeRequestGraphqlListJson", () => {
1168 it("reads a row and its review state in one page, counting rows it cannot read", () => {
1169 const page = expectSuccess(
1170 decodeMergeRequestGraphqlListJson(
1171 JSON.stringify({
1172 data: {
1173 metadata: { enterprise: false },
1174 project: {
1175 mergeRequests: {
1176 pageInfo: { hasNextPage: true, endCursor: "eyJpZCI6IjcifQ" },
1177 nodes: [
1178 {
1179 iid: "7",
1180 title: "Add the merge requests page",
1181 webUrl: "https://gitlab.com/acme/web/-/merge_requests/7",
1182 state: "opened",
1183 draft: true,
1184 createdAt: "2026-07-01T00:00:00Z",
1185 updatedAt: "2026-07-02T00:00:00Z",
1186 sourceBranch: "feat/page",
1187 targetBranch: "main",
1188 conflicts: true,
1189 mergeStatusEnum: "CHECKING",
1190 author: { username: "bilal", name: "Bilal", avatarUrl: null },
1191 labels: { nodes: [{ title: "bug" }] },
1192 approved: false,
1193 approvedBy: { nodes: [] },
1194 reviewers: {
1195 nodes: [
1196 {
1197 username: "julius",
1198 mergeRequestInteraction: { reviewState: "REQUESTED_CHANGES" },
1199 },
1200 ],
1201 },
1202 headPipeline: { status: "FAILED" },
1203 },
1204 { iid: "8" },
1205 ],
1206 },
1207 },
1208 },
1209 }),
1210 ),
1211 );
1212
1213 expect(page.items).toEqual([
1214 expect.objectContaining({
1215 number: 7,
1216 state: "open",
1217 isDraft: true,
1218 mergeability: "conflicting",
1219 reviewRequestLogins: ["julius"],
1220 labels: [expect.objectContaining({ name: "bug" })],
1221 }),
1222 ]);
1223 expect([...page.states]).toEqual([
1224 [7, { reviewDecision: "changes-requested", checksState: "failing" }],
1225 ]);
1226 expect(page).toMatchObject({ rawCount: 2, hasNextPage: true, endCursor: "eyJpZCI6IjcifQ" });
1227 });
1228 it("fails on a project the reader cannot see, rather than reading it as empty", () => {
1229 expect(
1230 Result.isFailure(
1231 decodeMergeRequestGraphqlListJson(
1232 JSON.stringify({ data: { metadata: { enterprise: true }, project: null } }),
1233 ),
1234 ),
1235 ).toBe(true);
1236 });
1237});
1238
1239describe("decodeGraphqlListSupportJson", () => {
1240 it.each([
1241 { version: "17.8.4", supported: false },
1242 { version: "17.9.0", supported: true },
1243 { version: "19.6.0-pre", supported: true },
1244 { version: null, supported: false },
1245 ])("reads GitLab $version as supported: $supported", ({ version, supported }) => {
1246 expect(
1247 expectSuccess(
1248 decodeGraphqlListSupportJson(JSON.stringify({ data: { metadata: { version } } })),
1249 ),
1250 ).toBe(supported);
1251 });
1252});
1253
1254describe("decodeMergeMessagesJson", () => {
1255 it("fails a partial response instead of reading errored fields as absent templates", () => {
1256 const decoded = decodeMergeMessagesJson(
1257 JSON.stringify({
1258 errors: [{ message: "Internal server error", path: ["project", "mergeRequest"] }],
1259 data: {
1260 project: { mergeRequest: { title: "Add thing", defaultMergeCommitMessage: null } },
1261 },
1262 }),
1263 );
1264
1265 expect(Result.isFailure(decoded)).toBe(true);
1266 });
1267});
1268
1269describe("decodeMergeRequestWatchFingerprintJson", () => {
1270 const pipeline = (status: string, downstream: string, failed = 0, moreBridges = false) => ({
1271 id: "gid://gitlab/Ci::Pipeline/9",
1272 status,
1273 succeeded: { count: 3 },
1274 failed: { count: failed },
1275 stopped: { count: 0 },
1276 jobs: {
1277 pageInfo: { hasNextPage: moreBridges },
1278 nodes: [
1279 {
1280 name: "deploy",
1281 status,
1282 downstreamPipeline: { id: "gid://gitlab/Ci::Pipeline/10", status: downstream },
1283 },
1284 ],
1285 },
1286 });
1287 const edit = (at: string, resolved = false) => ({
1288 lastEditedAt: at,
1289 lastEditedBy: { username: "reviewer" },
1290 resolved,
1291 });
1292 const read = (overrides: Record<string, unknown>) =>
1293 expectSuccess(
1294 decodeMergeRequestWatchFingerprintJson(
1295 JSON.stringify({
1296 data: {
1297 project: {
1298 mergeRequest: {
1299 state: "opened",
1300 mergeStatusEnum: "CAN_BE_MERGED",
1301 detailedMergeStatus: "MERGEABLE",
1302 conflicts: false,
1303 diffHeadSha: "a".repeat(40),
1304 userPermissions: { updateMergeRequest: true },
1305 headPipeline: pipeline("RUNNING", "RUNNING"),
1306 userNotesCount: 2,
1307 notes: {
1308 nodes: [
1309 edit("2026-07-02T00:00:00Z"),
1310 { lastEditedAt: null, lastEditedBy: null, resolved: null },
1311 edit("2026-07-01T00:00:00Z"),
1312 ],
1313 },
1314 ...overrides,
1315 },
1316 },
1317 },
1318 }),
1319 ),
1320 );
1321
1322 // A remarks change makes the watch reread every comment, so pipeline progress must not touch it.
1323 it("moves pipeline progress into status and comment edits into remarks", () => {
1324 const base = read({});
1325 const passed = read({ headPipeline: pipeline("SUCCESS", "RUNNING") });
1326 const downstreamPassed = read({ headPipeline: pipeline("SUCCESS", "SUCCESS") });
1327 const jobFailed = read({ headPipeline: pipeline("RUNNING", "RUNNING", 1) });
1328 const edited = read({ notes: { nodes: [edit("2026-07-03T00:00:00Z")] } });
1329 // Resolving a thread restamps its notes without an edit, so it must not reread comments.
1330 const resolved = read({
1331 notes: { nodes: [edit("2026-07-02T00:00:00Z"), edit("2026-07-03T00:00:00Z", true)] },
1332 });
1333
1334 expect(base?.remarks).toBe("2 2026-07-02T00:00:00Z");
1335 expect(passed?.status).not.toBe(base?.status);
1336 expect(downstreamPassed?.status).not.toBe(passed?.status);
1337 expect(jobFailed?.status).not.toBe(base?.status);
1338 expect(passed?.remarks).toBe(base?.remarks);
1339 expect(edited?.status).toBe(base?.status);
1340 expect(edited?.remarks).not.toBe(base?.remarks);
1341 expect(resolved?.remarks).toBe(base?.remarks);
1342 expect(read({ userNotesCount: 3 })?.remarks).not.toBe(base?.remarks);
1343 // A target branch moving on leaves merge_status at can_be_merged on fast-forward projects.
1344 expect(read({ detailedMergeStatus: "NEED_REBASE" })?.status).not.toBe(base?.status);
1345 });
1346
1347 // Only the REST read asks GitLab to recheck mergeability, and only for viewers who can update.
1348 it("covers the detail read once merge status has settled or no read could settle it", () => {
1349 expect(read({})?.coversDetail).toBe(true);
1350 // A capped job count or a second bridge page can hide a job settling.
1351 expect(read({ headPipeline: pipeline("RUNNING", "RUNNING", 1001) })?.coversDetail).toBe(false);
1352 expect(read({ headPipeline: pipeline("RUNNING", "RUNNING", 0, true) })?.coversDetail).toBe(
1353 false,
1354 );
1355 expect(read({ mergeStatusEnum: "UNCHECKED" })?.coversDetail).toBe(false);
1356 expect(read({ mergeStatusEnum: "CHECKING", conflicts: true })?.coversDetail).toBe(true);
1357 expect(
1358 read({ mergeStatusEnum: "UNCHECKED", userPermissions: { updateMergeRequest: false } })
1359 ?.coversDetail,
1360 ).toBe(true);
1361 });
1362
1363 it("answers null when GitLab returned no merge request", () => {
1364 expect(
1365 expectSuccess(
1366 decodeMergeRequestWatchFingerprintJson(
1367 JSON.stringify({ data: { project: { mergeRequest: null } } }),
1368 ),
1369 ),
1370 ).toBeNull();
1371 });
1372});