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