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