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 decodeMergeRequestDetailJson,
9 decodeMergeRequestDiffsJson,
10 decodeMergeRequestListJson,
11 decodeNotesJson,
12 decodeOwnAwardIdJson,
13} from "./gitLabMergeRequestJson.ts";
14
15function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
16 return JSON.stringify(
17 entries.map((entry) => ({
18 iid: 1,
19 title: "Add the merge requests page",
20 web_url: "https://gitlab.com/acme/web/-/merge_requests/1",
21 source_branch: "feat/page",
22 target_branch: "main",
23 created_at: "2026-07-01T00:00:00Z",
24 updated_at: "2026-07-02T00:00:00Z",
25 ...entry,
26 })),
27 );
28}
29
30function detailJson(entry: Record<string, unknown>): string {
31 return JSON.stringify({
32 iid: 1,
33 title: "Add the merge requests page",
34 web_url: "https://gitlab.com/acme/web/-/merge_requests/1",
35 source_branch: "feat/page",
36 target_branch: "main",
37 created_at: "2026-07-01T00:00:00Z",
38 updated_at: "2026-07-02T00:00:00Z",
39 ...entry,
40 });
41}
42
43function expectSuccess<A>(result: Result.Result<A, unknown>): A {
44 expect(Result.isSuccess(result)).toBe(true);
45 if (!Result.isSuccess(result)) throw new Error("expected a successful decode");
46 return result.success;
47}
48
49describe("decodeMergeRequestListJson", () => {
50 it("reads a merge request as a change request", () => {
51 const batch = expectSuccess(
52 decodeMergeRequestListJson(
53 listJson([
54 {
55 iid: 42,
56 author: { username: "bilal", name: "Bilal" },
57 state: "opened",
58 merge_status: "can_be_merged",
59 draft: false,
60 reviewers: [{ username: "julius" }],
61 labels: ["backend", " "],
62 },
63 ]),
64 ),
65 );
66
67 expect(batch.items).toHaveLength(1);
68 expect(batch.items[0]).toMatchObject({
69 number: 42,
70 author: { login: "bilal", name: "Bilal" },
71 headBranch: "feat/page",
72 baseBranch: "main",
73 state: "open",
74 isDraft: false,
75 mergeability: "mergeable",
76 reviewRequestLogins: ["julius"],
77 labels: [{ name: "backend", color: null }],
78 });
79 });
80
81 it("treats a merged timestamp as merged whatever the state says", () => {
82 const batch = expectSuccess(
83 decodeMergeRequestListJson(
84 listJson([{ state: "opened", merged_at: "2026-07-03T00:00:00Z" }]),
85 ),
86 );
87
88 expect(batch.items[0]?.state).toBe("merged");
89 });
90
91 it("keeps a locked merge request open", () => {
92 const batch = expectSuccess(decodeMergeRequestListJson(listJson([{ state: "locked" }])));
93
94 expect(batch.items[0]?.state).toBe("open");
95 });
96
97 it("reads the legacy draft flag", () => {
98 const batch = expectSuccess(decodeMergeRequestListJson(listJson([{ work_in_progress: true }])));
99
100 expect(batch.items[0]?.isDraft).toBe(true);
101 });
102
103 it("calls a conflicted merge request conflicting even while the merge check is pending", () => {
104 const batch = expectSuccess(
105 decodeMergeRequestListJson(listJson([{ merge_status: "checking", has_conflicts: true }])),
106 );
107
108 expect(batch.items[0]?.mergeability).toBe("conflicting");
109 });
110
111 it("leaves an unfinished merge check unknown", () => {
112 const batch = expectSuccess(
113 decodeMergeRequestListJson(listJson([{ merge_status: "checking" }])),
114 );
115
116 expect(batch.items[0]?.mergeability).toBe("unknown");
117 });
118
119 it("skips a malformed row but still counts it, so paging does not stop early", () => {
120 const batch = expectSuccess(
121 decodeMergeRequestListJson(
122 JSON.stringify([{ iid: "not a number" }, ...JSON.parse(listJson([{}]))]),
123 ),
124 );
125
126 expect(batch.items).toHaveLength(1);
127 expect(batch.rawIndexes).toEqual([1]);
128 expect(batch.rawCount).toBe(2);
129 });
130});
131
132describe("decodeMergeRequestDetailJson", () => {
133 it("reads the description, file count and pipeline", () => {
134 const detail = expectSuccess(
135 decodeMergeRequestDetailJson(
136 detailJson({
137 description: "Ships the page.",
138 changes_count: "3",
139 reviewers: [{ username: "julius", name: "Julius" }],
140 head_pipeline: {
141 status: "success",
142 web_url: "https://gitlab.com/acme/web/-/pipelines/9",
143 source: "merge_request_event",
144 },
145 }),
146 ),
147 );
148
149 expect(detail.body).toBe("Ships the page.");
150 expect(detail.changedFiles).toBe(3);
151 expect(detail.reviewers).toEqual([{ login: "julius", name: "Julius", avatarUrl: null }]);
152 expect(detail.checks).toEqual([
153 {
154 name: "Pipeline",
155 status: "success",
156 description: "merge_request_event",
157 url: "https://gitlab.com/acme/web/-/pipelines/9",
158 },
159 ]);
160 });
161
162 it("reads an uncounted change set as its floor", () => {
163 const detail = expectSuccess(
164 decodeMergeRequestDetailJson(detailJson({ changes_count: "1000+" })),
165 );
166
167 expect(detail.changedFiles).toBe(1000);
168 });
169
170 it("reads the head commit, and says nothing where GitLab omitted it", () => {
171 const headSha = (entry: Record<string, unknown>) =>
172 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).headSha;
173 const sha = "afce4da4d5fe7d2fd0647b5b864526ea0a2827cb";
174
175 expect(headSha({ sha })).toBe(sha);
176 // A new merge request can report its head before GitLab has computed `diff_refs`.
177 expect(headSha({ sha, diff_refs: null })).toBe(sha);
178 expect(headSha({ sha, merge_commit_sha: "0".repeat(40) })).toBe(sha);
179 expect(headSha({})).toBeUndefined();
180 expect(headSha({ sha: null })).toBeUndefined();
181 expect(headSha({ sha: " " })).toBeUndefined();
182 });
183
184 it("reads either auto-merge field, and says nothing where GitLab named neither", () => {
185 const armed = (entry: Record<string, unknown>) =>
186 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).autoMergeEnabled;
187
188 expect(armed({ merge_when_pipeline_succeeds: true })).toBe(true);
189 expect(armed({ auto_merge_enabled: true })).toBe(true);
190 expect(armed({ merge_when_pipeline_succeeds: false })).toBe(false);
191 expect(armed({})).toBeUndefined();
192 });
193
194 it("keeps the squash choice stored with auto-merge", () => {
195 expect(
196 expectSuccess(
197 decodeMergeRequestDetailJson(
198 detailJson({ auto_merge_enabled: true, squash_on_merge: true }),
199 ),
200 ),
201 ).toMatchObject({ autoMergeEnabled: true, autoMergeMethod: "squash" });
202
203 expect(
204 expectSuccess(
205 decodeMergeRequestDetailJson(
206 detailJson({
207 auto_merge_enabled: true,
208 squash: true,
209 squash_on_merge: false,
210 }),
211 ),
212 ).autoMergeMethod,
213 ).toBeUndefined();
214 });
215
216 it("keeps a divergence GitLab did not count apart from a divergence of none", () => {
217 const behind = (entry: Record<string, unknown>) =>
218 expectSuccess(decodeMergeRequestDetailJson(detailJson(entry))).divergedCommits;
219
220 expect(behind({ diverged_commits_count: 3 })).toBe(3);
221 expect(behind({ diverged_commits_count: 0 })).toBe(0);
222 expect(behind({})).toBeUndefined();
223 expect(behind({ diverged_commits_count: null })).toBeUndefined();
224 });
225
226 it("maps a pipeline waiting on a person to neutral, not failure", () => {
227 const detail = expectSuccess(
228 decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status: "manual" } })),
229 );
230
231 expect(detail.checks[0]?.status).toBe("neutral");
232 });
233});
234
235describe("decodeNotesJson", () => {
236 it("keeps comments and drops GitLab's own activity notes", () => {
237 const notes = expectSuccess(
238 decodeNotesJson(
239 JSON.stringify([
240 {
241 id: 1,
242 body: "assigned to @bilal",
243 system: true,
244 created_at: "2026-07-01T00:00:00Z",
245 },
246 {
247 id: 2,
248 body: "Looks good.",
249 author: { username: "julius" },
250 created_at: "2026-07-02T00:00:00Z",
251 },
252 { id: 3, body: " ", created_at: "2026-07-03T00:00:00Z" },
253 ]),
254 ),
255 );
256
257 expect(notes.comments).toHaveLength(1);
258 expect(notes.comments[0]).toMatchObject({
259 id: "2",
260 kind: "issue-comment",
261 body: "Looks good.",
262 });
263 expect(notes.rawCount).toBe(3);
264 });
265
266 it("reads a line note as a review comment on its file", () => {
267 const notes = expectSuccess(
268 decodeNotesJson(
269 JSON.stringify([
270 {
271 id: 7,
272 type: "DiffNote",
273 body: "Rename this.",
274 created_at: "2026-07-02T00:00:00Z",
275 position: { new_path: "src/app.ts", old_path: "src/old.ts" },
276 },
277 ]),
278 ),
279 );
280
281 expect(notes.comments[0]).toMatchObject({ kind: "review-comment", path: "src/app.ts" });
282 });
283
284 it("falls back to the old path for a note on a deleted line", () => {
285 const notes = expectSuccess(
286 decodeNotesJson(
287 JSON.stringify([
288 {
289 id: 8,
290 type: "DiffNote",
291 body: "Gone.",
292 created_at: "2026-07-02T00:00:00Z",
293 position: { new_path: null, old_path: "src/old.ts" },
294 },
295 ]),
296 ),
297 );
298
299 expect(notes.comments[0]?.path).toBe("src/old.ts");
300 });
301});
302
303describe("decodeCommitsJson", () => {
304 it("falls back to the creation timestamp when there is no commit date", () => {
305 const commits = expectSuccess(
306 decodeCommitsJson(
307 JSON.stringify([
308 {
309 id: "aaa",
310 created_at: "2026-07-01T00:00:00+08:00",
311 author_name: "Ada Lovelace",
312 author_email: "ada@example.com",
313 },
314 ]),
315 ),
316 );
317
318 expect(commits[0]).toMatchObject({
319 oid: "aaa",
320 committedDate: "2026-07-01T00:00:00+08:00",
321 authors: [{ login: "Ada Lovelace", name: "Ada Lovelace", avatarUrl: null }],
322 });
323 });
324});
325
326describe("decodeMergeRequestDiffsJson", () => {
327 it("quotes literal backslashes without interpreting them as escapes", () => {
328 const result = expectSuccess(
329 decodeMergeRequestDiffsJson(
330 JSON.stringify([
331 {
332 old_path: String.raw`src\notes.ts`,
333 new_path: String.raw`src\notes.ts`,
334 diff: "@@ -1 +1 @@\n-old\n+new",
335 },
336 ]),
337 ),
338 );
339
340 expect(result.patch).toBe(
341 [
342 String.raw`diff --git "a/src\\notes.ts" "b/src\\notes.ts"`,
343 String.raw`--- "a/src\\notes.ts"`,
344 String.raw`+++ "b/src\\notes.ts"`,
345 "@@ -1 +1 @@",
346 "-old",
347 "+new",
348 "",
349 ].join("\n"),
350 );
351 });
352
353 it("preserves spaces and literal backslashes in both rename paths", () => {
354 const result = expectSuccess(
355 decodeMergeRequestDiffsJson(
356 JSON.stringify([
357 {
358 old_path: String.raw` old\name.ts `,
359 new_path: String.raw` new\name.ts `,
360 renamed_file: true,
361 diff: "",
362 },
363 ]),
364 ),
365 );
366
367 expect(result.patch).toBe(
368 [
369 String.raw`diff --git "a/ old\\name.ts " "b/ new\\name.ts "`,
370 String.raw`rename from " old\\name.ts "`,
371 String.raw`rename to " new\\name.ts "`,
372 String.raw`--- "a/ old\\name.ts "`,
373 String.raw`+++ "b/ new\\name.ts "`,
374 ].join("\n"),
375 );
376 });
377
378 it("assembles a unified patch GitLab does not return", () => {
379 const result = expectSuccess(
380 decodeMergeRequestDiffsJson(
381 JSON.stringify([
382 {
383 old_path: "src/app.ts",
384 new_path: "src/app.ts",
385 diff: "@@ -1 +1 @@\n-old\n+new\n",
386 },
387 ]),
388 ),
389 );
390
391 expect(result.patch).toBe(
392 [
393 "diff --git a/src/app.ts b/src/app.ts",
394 "--- a/src/app.ts",
395 "+++ b/src/app.ts",
396 "@@ -1 +1 @@",
397 "-old",
398 "+new",
399 "",
400 ].join("\n"),
401 );
402 expect(result.truncated).toBe(false);
403 });
404
405 it("points a new file at /dev/null on the left and a deleted file on the right", () => {
406 const result = expectSuccess(
407 decodeMergeRequestDiffsJson(
408 JSON.stringify([
409 {
410 old_path: "src/new.ts",
411 new_path: "src/new.ts",
412 new_file: true,
413 b_mode: "100755",
414 diff: "@@ -0,0 +1 @@\n+hello\n",
415 },
416 {
417 old_path: "src/gone.ts",
418 new_path: "src/gone.ts",
419 deleted_file: true,
420 diff: "@@ -1 +0,0 @@\n-bye\n",
421 },
422 ]),
423 ),
424 );
425
426 expect(result.patch).toContain("new file mode 100755");
427 expect(result.patch).toContain("--- /dev/null");
428 expect(result.patch).toContain("deleted file mode 100644");
429 expect(result.patch).toContain("+++ /dev/null");
430 });
431
432 it("reports truncation for a file GitLab refused to inline", () => {
433 const result = expectSuccess(
434 decodeMergeRequestDiffsJson(
435 JSON.stringify([{ old_path: "big.bin", new_path: "big.bin", diff: "", too_large: true }]),
436 ),
437 );
438
439 expect(result.truncated).toBe(true);
440 expect(result.patch).toContain("diff --git a/big.bin b/big.bin");
441 });
442
443 it("reports how many files GitLab returned, so the caller can page", () => {
444 const result = expectSuccess(
445 decodeMergeRequestDiffsJson(
446 JSON.stringify(
447 Array.from({ length: 3 }, (_, index) => ({
448 old_path: `src/${index}.ts`,
449 new_path: `src/${index}.ts`,
450 diff: "@@ -1 +1 @@\n-a\n+b\n",
451 })),
452 ),
453 ),
454 );
455
456 expect(result.rawCount).toBe(3);
457 expect(result.truncated).toBe(false);
458 expect(result.patch).toContain("src/2.ts");
459 });
460});
461
462describe("merge request viewer fields", () => {
463 it("carries GitLab's own answer for whether this viewer can merge", () => {
464 expect(
465 expectSuccess(decodeMergeRequestDetailJson(detailJson({ user: { can_merge: false } })))
466 .viewerCanMerge,
467 ).toBe(false);
468 expect(
469 expectSuccess(decodeMergeRequestDetailJson(detailJson({ user: { can_merge: true } })))
470 .viewerCanMerge,
471 ).toBe(true);
472 });
473
474 it("leaves merging permitted where GitLab answered without the field", () => {
475 expect(expectSuccess(decodeMergeRequestDetailJson(detailJson({}))).viewerCanMerge).toBe(true);
476 expect(
477 expectSuccess(decodeMergeRequestDetailJson(detailJson({ user: null }))).viewerCanMerge,
478 ).toBe(true);
479 });
480});
481
482describe("decodeAwardEmojiJson", () => {
483 it("reads MR-level awards, keys per-note awards by the REST id inside their gid, and ignores an award outside the eight", () => {
484 const result = expectSuccess(
485 decodeAwardEmojiJson(
486 JSON.stringify({
487 data: {
488 currentUser: { username: "bilal" },
489 project: {
490 mergeRequest: {
491 awardEmoji: {
492 nodes: [
493 { name: "thumbsup", user: { username: "bilal" } },
494 { name: "thumbsup", user: { username: "julius" } },
495 ],
496 },
497 notes: {
498 pageInfo: { hasNextPage: false, endCursor: null },
499 nodes: [
500 {
501 id: "gid://gitlab/DiffNote/42",
502 awardEmoji: { nodes: [{ name: "heart", user: { username: "julius" } }] },
503 },
504 {
505 id: "gid://gitlab/Note/7",
506 awardEmoji: {
507 nodes: [{ name: "partyparrot", user: { username: "bilal" } }],
508 },
509 },
510 ],
511 },
512 },
513 },
514 },
515 }),
516 ),
517 );
518
519 expect(result.reactions).toEqual([
520 { content: "thumbs-up", count: 2, actors: ["julius"], viewerHasReacted: true },
521 ]);
522 expect([...result.reactionsByNoteId]).toEqual([
523 ["42", [{ content: "heart", count: 1, actors: ["julius"], viewerHasReacted: false }]],
524 ]);
525 expect(result.nextCursor).toBeNull();
526 });
527
528 it("hands back a cursor when GitLab has more notes to page", () => {
529 const result = expectSuccess(
530 decodeAwardEmojiJson(
531 JSON.stringify({
532 data: {
533 currentUser: null,
534 project: {
535 mergeRequest: {
536 awardEmoji: { nodes: [] },
537 notes: { pageInfo: { hasNextPage: true, endCursor: "Y3Vyc29yOjE" }, nodes: [] },
538 },
539 },
540 },
541 }),
542 ),
543 );
544
545 expect(result.nextCursor).toBe("Y3Vyc29yOjE");
546 });
547
548 it("matches the viewer's username case-insensitively, since GitLab is not consistent about case", () => {
549 const result = expectSuccess(
550 decodeAwardEmojiJson(
551 JSON.stringify({
552 data: {
553 currentUser: { username: "Bilal" },
554 project: {
555 mergeRequest: {
556 awardEmoji: {
557 nodes: [
558 { name: "heart", user: { username: "bilal" } },
559 { name: "heart", user: { username: "julius" } },
560 ],
561 },
562 notes: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] },
563 },
564 },
565 },
566 }),
567 ),
568 );
569
570 expect(result.reactions).toEqual([
571 { content: "heart", count: 2, actors: ["julius"], viewerHasReacted: true },
572 ]);
573 });
574});
575
576describe("decodeOwnAwardIdJson", () => {
577 const awards = JSON.stringify([
578 { id: 101, name: "thumbsup", user: { username: "julius" } },
579 { id: 102, name: "thumbsup", user: { username: "bilal" } },
580 ]);
581
582 it("finds the reader's own award of that name, which is the one a removal deletes", () => {
583 expect(
584 expectSuccess(decodeOwnAwardIdJson(awards, { content: "thumbs-up", viewer: "bilal" })),
585 ).toBe(102);
586 });
587
588 it("returns nothing where the reader has no award of that name", () => {
589 expect(
590 expectSuccess(decodeOwnAwardIdJson(awards, { content: "heart", viewer: "bilal" })),
591 ).toBeNull();
592 });
593});
594
595describe("decodeRepositoryBlobsJson", () => {
596 function expectBlobs(result: Result.Result<ReadonlyMap<string, string> | null, unknown>) {
597 const blobs = expectSuccess(result);
598 expect(blobs).not.toBe(null);
599 if (blobs === null) throw new Error("expected an answered blobs query");
600 return blobs;
601 }
602
603 it("leaves out a node missing either half, which names no version", () => {
604 const blobs = expectBlobs(
605 decodeRepositoryBlobsJson(
606 JSON.stringify({
607 data: {
608 project: {
609 repository: {
610 blobs: {
611 nodes: [
612 { path: "src/a.ts", oid: null },
613 { path: null, oid: "bbb222" },
614 null,
615 { path: "src/c.ts", oid: "ccc333" },
616 ],
617 },
618 },
619 },
620 },
621 }),
622 ),
623 );
624
625 expect([...blobs]).toEqual([["src/c.ts", "ccc333"]]);
626 });
627
628 it("keys a blob by the path the host spelled, spaces and all", () => {
629 const blobs = expectBlobs(
630 decodeRepositoryBlobsJson(
631 JSON.stringify({
632 data: {
633 project: {
634 repository: {
635 blobs: {
636 nodes: [
637 { path: " leading.ts", oid: "aaa111" },
638 { path: "trailing.ts ", oid: "bbb222" },
639 { path: " ", oid: "ccc333" },
640 { path: "", oid: "ddd444" },
641 ],
642 },
643 },
644 },
645 },
646 }),
647 ),
648 );
649
650 expect([...blobs]).toEqual([
651 [" leading.ts", "aaa111"],
652 ["trailing.ts ", "bbb222"],
653 [" ", "ccc333"],
654 ]);
655 });
656
657 it("tells a project the reader cannot see from a revision with none of the files", () => {
658 expect(
659 expectSuccess(decodeRepositoryBlobsJson(JSON.stringify({ data: { project: null } }))),
660 ).toBe(null);
661 expect(
662 expectSuccess(
663 decodeRepositoryBlobsJson(JSON.stringify({ data: { project: { repository: null } } })),
664 ),
665 ).toBe(null);
666 expect(
667 expectSuccess(
668 decodeRepositoryBlobsJson(
669 JSON.stringify({ data: { project: { repository: { blobs: { nodes: [] } } } } }),
670 ),
671 ),
672 ).toEqual(new Map());
673 });
674});