Open History to see the last commit
1import { describe, expect, it, vi } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import { AtomRegistry } from "effect/reactivity";
4import type { Root, RootContent } from "mdast";
5import remarkGfm from "remark-gfm";
6import remarkParse from "remark-parse";
7import { unified } from "unified";
8
9import {
10 makePullRequestMediaKindAtom,
11 splitPullRequestBody,
12 type PullRequestBodySegment,
13} from "./pullRequestMarkdown.ts";
14import {
15 changeRequestReferenceAutolinker,
16 resolveChangeRequestMediaUrl,
17} from "./pullRequestReferences.ts";
18
19const definitionParser = unified().use(remarkParse).use(remarkGfm);
20
21// The finder a client passes: each first definition, joined onto one line out of its quote.
22const split = (body: string) =>
23 splitPullRequestBody(body, (markdown) => {
24 const definitions = new Map<string, string>();
25 const visit = (node: Root | RootContent, quotes: number) => {
26 if (node.type === "definition" && !definitions.has(node.identifier)) {
27 const wrap = new RegExp(`(?:\\r\\n|\\r|\\n)(?:[ \\t]*>){0,${quotes}}[ \\t]*`, "gu");
28 const source = markdown.slice(node.position?.start.offset, node.position?.end.offset);
29 definitions.set(node.identifier, source.replace(wrap, " "));
30 }
31 if ("children" in node) {
32 for (const child of node.children)
33 visit(child, quotes + (node.type === "blockquote" ? 1 : 0));
34 }
35 };
36 visit(definitionParser.parse(markdown), 0);
37 return [...definitions.values()];
38 });
39
40describe("pull request body segmentation", () => {
41 it("lifts a GitHub upload without guessing its type and keeps the prose around it", () => {
42 expect(
43 split(
44 "Before\n\nhttps://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456\n\nAfter",
45 ),
46 ).toEqual([
47 { id: "markdown:0", kind: "markdown", text: "Before", sourceOffset: 0 },
48 {
49 id: "attachment:1",
50 kind: "attachment",
51 url: "https://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456",
52 media: "unknown",
53 },
54 { id: "markdown:2", kind: "markdown", text: "After", sourceOffset: 89 },
55 ]);
56 });
57
58 it("leaves the type of a linked GitHub upload unresolved", () => {
59 const upload =
60 "https://github.com/user-attachments/assets/f619ea9d-112c-400b-b1db-8c8d5d2357cc";
61 expect(split(`[Native iPhone caption playback](${upload})`)).toEqual([
62 {
63 id: "attachment:0",
64 kind: "attachment",
65 url: upload,
66 media: "unknown",
67 label: "Native iPhone caption playback",
68 },
69 ]);
70 });
71
72 it("places each prose run at its offset in the body, including inside a media table", () => {
73 const body =
74 '\n\n- [ ] Before\r\n\nhttps://example.com/shot.png\n\n\n<video controls>\n <source src="https://example.com/a.mp4">\n</video>\n - [ ] code\n- [x] After\n\r\n<table>\r\n<tr><td>\r\n\r\n- [ ] In a cell\r\n\r\n</td><td>\r\n\r\nhttps://example.com/b.mp4\r\n\r\n</td></tr>\r\n</table>\r\n- [ ] Last\n';
75 type Prose = Extract<PullRequestBodySegment, { kind: "markdown" }>;
76 const prose = (segments: ReadonlyArray<PullRequestBodySegment>): Prose[] =>
77 segments.flatMap((segment) =>
78 segment.kind === "markdown"
79 ? [segment]
80 : segment.kind === "table"
81 ? segment.rows.flat().flatMap((cell) => prose(cell.segments))
82 : [],
83 );
84 const runs = prose(split(body));
85 expect(runs.map((segment) => segment.text)).toEqual([
86 "- [ ] Before",
87 " - [ ] code\n- [x] After",
88 "- [ ] In a cell",
89 "- [ ] Last",
90 ]);
91 for (const segment of runs) {
92 expect(body.slice(segment.sourceOffset, segment.sourceOffset + segment.text.length)).toBe(
93 segment.text,
94 );
95 }
96 });
97
98 it("reads the source out of a video tag, including a multi-line one", () => {
99 expect(
100 split('<video controls>\n <source src="https://example.com/a.webm">\n</video>'),
101 ).toEqual([
102 {
103 id: "attachment:0",
104 kind: "attachment",
105 url: "https://example.com/a.webm",
106 media: "video",
107 },
108 ]);
109 for (const body of [
110 '<video src="https://example.org/right.mp4" data-src="https://example.org/wrong.mp4"></video>',
111 '<video data-src="https://example.org/wrong.mp4" src="https://example.org/right.mp4"></video>',
112 ]) {
113 expect(split(body)).toEqual([
114 {
115 id: "attachment:0",
116 kind: "attachment",
117 url: "https://example.org/right.mp4",
118 media: "video",
119 },
120 ]);
121 }
122 expect(split("<video src=https://example.org/demo.mp4?token=abc></video>")).toEqual([
123 {
124 id: "attachment:0",
125 kind: "attachment",
126 url: "https://example.org/demo.mp4?token=abc",
127 media: "video",
128 },
129 ]);
130 for (const [body, url] of [
131 [
132 '<video src="https://example.org/a.mp4?x=1&y=2"></video>',
133 "https://example.org/a.mp4?x=1&y=2",
134 ],
135 [
136 '<video><source src="https://example.org/a.mp4?x=1&y=2&z=3"></video>',
137 "https://example.org/a.mp4?x=1&y=2&z=3",
138 ],
139 [
140 '<video src="https://example.org/a.mp4?x=1&amp;y=2"></video>',
141 "https://example.org/a.mp4?x=1&y=2",
142 ],
143 ] as const) {
144 expect(split(body)).toEqual([
145 {
146 id: "attachment:0",
147 kind: "attachment",
148 url,
149 media: "video",
150 },
151 ]);
152 }
153 const dataSrcOnly = '<video data-src="https://example.org/wrong.mp4"></video>';
154 expect(split(dataSrcOnly)).toEqual([
155 { id: "markdown:0", kind: "markdown", text: dataSrcOnly, sourceOffset: 0 },
156 ]);
157 });
158
159 it("leaves the img tag GitHub writes for a dropped image as markdown", () => {
160 const body =
161 '<img width="1414" alt="image" src="https://github.com/user-attachments/assets/7195f963-51a9-4331-be74-3e06be760422" />';
162 expect(split(body)).toEqual([
163 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
164 ]);
165 });
166
167 it("leaves an ordinary link alone, whether it is bare or written as markdown", () => {
168 const body = "https://example.com/page\n\n[the docs](https://example.com/docs)";
169 expect(split(body)).toEqual([
170 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
171 ]);
172 });
173
174 it("never lifts a link inside fenced code out of it", () => {
175 const body = "```\nhttps://example.com/demo.mp4\n```";
176 expect(split(body)).toEqual([
177 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
178 ]);
179 });
180
181 // GitHub keeps CRLF in a body written in its web editor.
182 it("recognizes fences in a body with CRLF line endings", () => {
183 const body = "```\r\nhttps://example.com/demo.mp4\r\n```";
184 expect(split(body)).toEqual([
185 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
186 ]);
187 });
188
189 it("closes a CRLF fence, so a video after it still lifts out", () => {
190 const code = '```html\r\n<video src="https://example.com/example.mp4"></video>\r\n```';
191 expect(split(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([
192 { id: "markdown:0", kind: "markdown", text: code, sourceOffset: 0 },
193 {
194 id: "attachment:1",
195 kind: "attachment",
196 url: "https://example.com/demo.mp4",
197 media: "video",
198 },
199 ]);
200 });
201
202 it("splits a lone-CR body into lines, so a video after its fence still lifts out", () => {
203 const crLines = ["```text", "https://example.com/sample.mp4", "```"];
204 const crBody = [...crLines, "", "https://example.com/actual.mp4", "", "- [ ] Done"].join("\r");
205 expect(split(crBody)).toEqual([
206 { id: "markdown:0", kind: "markdown", text: crLines.join("\n"), sourceOffset: 0 },
207 {
208 id: "attachment:1",
209 kind: "attachment",
210 url: "https://example.com/actual.mp4",
211 media: "video",
212 },
213 {
214 id: "markdown:2",
215 kind: "markdown",
216 text: "- [ ] Done",
217 sourceOffset: crBody.indexOf("- [ ] Done"),
218 },
219 ]);
220 });
221
222 it("keeps a fence opened on a list marker in the list, closing it on its close or dedent", () => {
223 const actual = {
224 id: "attachment:1",
225 kind: "attachment",
226 url: "https://example.com/actual.mp4",
227 media: "video",
228 };
229 const listCode = "- ```text\n https://example.com/sample.mp4\n ```";
230 expect(split(`${listCode}\n\nhttps://example.com/actual.mp4`)).toEqual([
231 { id: "markdown:0", kind: "markdown", text: listCode, sourceOffset: 0 },
232 actual,
233 ]);
234 const unclosed = "1. ```text\n https://example.com/sample.mp4";
235 expect(split(`${unclosed}\nhttps://example.com/actual.mp4`)).toEqual([
236 { id: "markdown:0", kind: "markdown", text: unclosed, sourceOffset: 0 },
237 actual,
238 ]);
239 const tabbed = "- ```text\n\tcode()\n https://example.com/sample.mp4\n ```";
240 expect(split(`${tabbed}\n\nhttps://example.com/actual.mp4`)).toEqual([
241 { id: "markdown:0", kind: "markdown", text: tabbed, sourceOffset: 0 },
242 actual,
243 ]);
244 const deepCloser = "- ```text\n\t\t```\n https://example.com/sample.mp4\n ```";
245 expect(split(`${deepCloser}\n\nhttps://example.com/actual.mp4`)).toEqual([
246 { id: "markdown:0", kind: "markdown", text: deepCloser, sourceOffset: 0 },
247 actual,
248 ]);
249 expect(split("- ```js`x\n\n https://example.com/actual.mp4")).toEqual([
250 { id: "markdown:0", kind: "markdown", text: "- ```js`x", sourceOffset: 0 },
251 actual,
252 ]);
253 const shown = "```markdown\n- ```\nhttps://example.com/sample.mp4\n```";
254 expect(split(`${shown}\n\nhttps://example.com/actual.mp4`)).toEqual([
255 { id: "markdown:0", kind: "markdown", text: shown, sourceOffset: 0 },
256 actual,
257 ]);
258 });
259
260 it("does not let a different fence marker close an open fence", () => {
261 const body = "```\n~~~\nhttps://example.com/demo.mp4\n```";
262 expect(split(body)).toEqual([
263 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
264 ]);
265 });
266
267 it("does not close a fence opened at the margin on a tab-indented marker", () => {
268 const code = "```\n\t```\nhttps://example.com/sample.mp4\n```";
269 expect(split(`${code}\n\nhttps://example.com/demo.mp4`)).toEqual([
270 { id: "markdown:0", kind: "markdown", text: code, sourceOffset: 0 },
271 {
272 id: "attachment:1",
273 kind: "attachment",
274 url: "https://example.com/demo.mp4",
275 media: "video",
276 },
277 ]);
278 const listCode = "- List\n\n\t```md\n https://example.com/sample.mp4\n\t```";
279 expect(split(`${listCode}\n\nhttps://example.com/demo.mp4`)).toEqual([
280 { id: "markdown:0", kind: "markdown", text: listCode, sourceOffset: 0 },
281 {
282 id: "attachment:1",
283 kind: "attachment",
284 url: "https://example.com/demo.mp4",
285 media: "video",
286 },
287 ]);
288 });
289
290 it("keeps a video tag that shares its line with prose as markdown", () => {
291 const body = 'Before <video src="https://example.com/a.mp4"></video> after';
292 expect(split(body)).toEqual([
293 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
294 ]);
295 const captioned = '<video src="https://example.com/a.mp4"></video> Before the fix\n\nIt opens.';
296 expect(split(`${captioned}\n\n<video src="https://example.com/b.mp4"></video>`)).toEqual([
297 { id: "markdown:0", kind: "markdown", text: captioned, sourceOffset: 0 },
298 { id: "attachment:1", kind: "attachment", url: "https://example.com/b.mp4", media: "video" },
299 ]);
300 });
301
302 it("treats an info-string fence as a nested opener, not a close", () => {
303 const body = "```\n```javascript\nhttps://example.com/demo.mp4\n```";
304 expect(split(body)).toEqual([
305 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
306 ]);
307 });
308
309 it("does not open a fence on a line of inline triple-backtick code", () => {
310 const code = "```\nhttps://example.com/b.png\n```";
311 expect(
312 split(`\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`),
313 ).toEqual([
314 { id: "markdown:0", kind: "markdown", text: "```npm test``` passes.", sourceOffset: 0 },
315 {
316 id: "attachment:1",
317 kind: "attachment",
318 url: "https://example.com/demo.mp4",
319 media: "video",
320 },
321 { id: "markdown:2", kind: "markdown", text: code, sourceOffset: 54 },
322 ]);
323 const multilineSpan = "```foo`\nhttps://example.com/demo.mp4\nbar```";
324 expect(split(multilineSpan)).toEqual([
325 { id: "markdown:0", kind: "markdown", text: multilineSpan, sourceOffset: 0 },
326 ]);
327 });
328
329 it("leaves an indented code line alone even when it is only a video link", () => {
330 const body = " https://example.com/demo.mp4";
331 expect(split(body)).toEqual([
332 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
333 ]);
334 });
335
336 it("never lifts media out of an HTML comment, while lifting media after it", () => {
337 const visible = {
338 id: "attachment:1",
339 kind: "attachment",
340 url: "https://example.org/visible.mp4",
341 media: "video",
342 };
343 // A fence inside a comment is hidden too, so it must not open a code block.
344 const comment = [
345 "<!--",
346 "https://example.org/hidden.mp4",
347 '<video src="https://example.org/hidden-tag.mp4"></video>',
348 "```",
349 "-->",
350 ].join("\n");
351 for (const hidden of [comment, "<!-- template hint -->"]) {
352 expect(split(`${hidden}\n\nhttps://example.org/visible.mp4`)).toEqual([
353 { id: "markdown:0", kind: "markdown", text: hidden, sourceOffset: 0 },
354 visible,
355 ]);
356 }
357 });
358
359 it("leaves an unclosed video tag as prose without eating the rest of the body", () => {
360 const body = ['<video src="https://example.com/a.mp4">', "still prose", "more prose"].join(
361 "\n",
362 );
363 expect(split(body)).toEqual([
364 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
365 ]);
366 });
367
368 it.each([
369 ["a whitespace run inside a line", `a${" ".repeat(1_000_000)}b`],
370 ["a run of unclosed video tags", `${"<video ".repeat(150_000)}</video>`],
371 ["a run of backticks before a line separator", `${"`".repeat(100_000)}\u2028x`],
372 ])("splits %s in one pass", (_case, body) => {
373 expect(split(body)).toEqual([
374 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
375 ]);
376 });
377
378 it("refuses a non-http source rather than making a link out of it", () => {
379 const body = '<video src="javascript:alert(1)"></video>';
380 expect(split(body)).toEqual([
381 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
382 ]);
383 });
384});
385
386describe("extensionless pull request media", () => {
387 it.effect.each([
388 [206, "image/png", "image"],
389 [206, "video/mp4", "video"],
390 [200, "text/html", null],
391 [404, "image/png", null],
392 ] as const)("classifies HTTP %i with Content-Type %s", ([status, contentType, kind]) =>
393 Effect.gen(function* () {
394 const cancel = vi.fn();
395 const fetchMedia = vi.fn(
396 async () =>
397 new Response(new ReadableStream({ cancel }), {
398 status,
399 headers: { "content-type": contentType },
400 }),
401 );
402 const url = "https://environment.test/api/assets/signed/upload";
403 const registry = AtomRegistry.make();
404 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
405 const atom = makePullRequestMediaKindAtom(fetchMedia)(url);
406 expect(yield* AtomRegistry.getResult(registry, atom)).toBe(kind);
407 expect(fetchMedia).toHaveBeenCalledWith(
408 url,
409 expect.objectContaining({
410 headers: { Range: "bytes=0-0" },
411 }),
412 );
413 expect(cancel).toHaveBeenCalledOnce();
414 }),
415 );
416});
417
418describe("reference links around lifted media", () => {
419 const recording =
420 "https://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456";
421 const parser = unified().use(remarkParse).use(remarkGfm);
422 const prose = (segments: ReadonlyArray<PullRequestBodySegment>): string[] =>
423 segments.flatMap((segment) =>
424 segment.kind === "markdown"
425 ? [segment.text]
426 : segment.kind === "table"
427 ? segment.rows.flat().flatMap((cell) => prose(cell.segments))
428 : [],
429 );
430 // Each segment renders as its own document; the first definition of a label wins, as in mdast-util-to-hast.
431 const referenceLinks = (body: string) =>
432 prose(split(body)).flatMap((text) => {
433 const definitions = new Map<string, string>();
434 const references: Array<{ identifier: string; text: string }> = [];
435 const visit = (node: Root | RootContent) => {
436 if (node.type === "definition" && !definitions.has(node.identifier)) {
437 definitions.set(node.identifier, node.url);
438 }
439 if (node.type === "linkReference") {
440 references.push({
441 identifier: node.identifier,
442 text: node.children.map((child) => ("value" in child ? child.value : "")).join(""),
443 });
444 }
445 if ("children" in node) node.children.forEach(visit);
446 };
447 visit(parser.parse(text));
448 return references.map((reference) => [reference.text, definitions.get(reference.identifier)]);
449 });
450
451 it.each([
452 [
453 "use, then media, then definition",
454 `See [the docs][guide].\n\n${recording}\n\n[guide]: https://example.com/docs`,
455 ],
456 [
457 "definition, then media, then use",
458 `[guide]: https://example.com/docs\n\n${recording}\n\nSee [the docs][guide].`,
459 ],
460 ...["\n", "\r\n", "\r"].map((lineEnding) => [
461 `a definition wrapped over quoted lines with ${JSON.stringify(lineEnding)}`,
462 `> [guide]:${lineEnding}> https://example.com/docs${lineEnding}> "The guide"\n\n${recording}\n\nSee [the docs][guide].`,
463 ]),
464 [
465 "a use inside a media table cell",
466 `<table><tr><td>\n\nSee [the docs][guide].\n\n</td><td>\n\n${recording}\n\n</td></tr></table>\n\n[guide]: https://example.com/docs`,
467 ],
468 ])("resolves a reference defined across a video: %s", (_case, body) => {
469 expect(referenceLinks(body)).toEqual([["the docs", "https://example.com/docs"]]);
470 });
471
472 it("keeps the body's first definition of a label, wherever the media falls", () => {
473 expect(
474 referenceLinks(
475 `[guide]: https://example.com/first\n\n${recording}\n\nSee [the docs][guide].\n\n[GUIDE]: https://example.com/second`,
476 ),
477 ).toEqual([["the docs", "https://example.com/first"]]);
478 });
479
480 it("renders the body whole when its definitions would be repeated past the budget", () => {
481 const definitions = Array.from(
482 { length: 400 },
483 (_, index) => `[d${index}]: https://example.com/${"x".repeat(60)}${index}`,
484 ).join("\n");
485 const uses = Array.from({ length: 1200 }, () => `[use][d1]\n${recording}`).join("\n");
486 const body = `\n${definitions}\n\n${uses}\n`;
487 expect(split(body)).toEqual([
488 { id: "markdown:0", kind: "markdown", text: body.trim(), sourceOffset: 1 },
489 ]);
490 });
491
492 it("leaves a definition shown in code as code", () => {
493 expect(
494 referenceLinks(
495 `\`\`\`md\n[guide]: https://example.com/docs\n\`\`\`\n\n${recording}\n\nSee [the docs][guide].`,
496 ),
497 ).toEqual([]);
498 });
499
500 it("still writes a task tick back to its place in the body", () => {
501 const body = `[guide]: https://example.com/docs\n\n${recording}\n\n- [ ] Read [the docs][guide]`;
502 const segment = split(body).at(-1)!;
503 if (segment.kind !== "markdown") throw new Error("expected prose last");
504 const marker = segment.text.indexOf("[ ]");
505 expect(body.slice(segment.sourceOffset + marker)).toBe("[ ] Read [the docs][guide]");
506 });
507
508 it.each([
509 ["\uFEFF", "", 0],
510 ["intro\n\n\uFEFF", "intro\n\n\uFEFF", 0],
511 [`${recording}\n\n\uFEFF`, "\uFEFF", 1],
512 ])("preserves BOM meaning and task offsets after prefix %j", (prefix, kept, pick) => {
513 const definition = "[guide]: https://example.com/docs";
514 const task = "- [ ] Read [guide]";
515 const body = `${prefix}${task}\n\n${recording}\n\n${definition}`;
516 const segment = splitPullRequestBody(body, () => [definition])[pick]!;
517 if (segment.kind !== "markdown") throw new Error("expected prose");
518 expect(segment.text).toBe(`${definition}\n\n${kept}${task}`);
519 expect(segment.sourceOffset + segment.text.indexOf("[ ]")).toBe(body.indexOf("[ ]"));
520 });
521});
522
523describe("media on custom hosts", () => {
524 it.each([
525 [
526 "https://drop.example.com/capture.PNG?token=abc#preview",
527 "https://drop.example.com/capture.PNG?token=abc#preview",
528 "image",
529 undefined,
530 ],
531 [
532 "[Recording](https://drop.example.com/recording.mov)",
533 "https://drop.example.com/recording.mov",
534 "video",
535 "Recording",
536 ],
537 ["[Demo](https://example.com/demo(1).mp4)", "https://example.com/demo(1).mp4", "video", "Demo"],
538 [
539 "[Demo [v2]](https://example.com/demo.mp4)",
540 "https://example.com/demo.mp4",
541 "video",
542 "Demo [v2]",
543 ],
544 ["[`[`](https://example.com/demo.mp4)", "https://example.com/demo.mp4", "video", "`[`"],
545 [
546 "[Demo](https://example.com/demo\\(1\\).mp4)",
547 "https://example.com/demo(1).mp4",
548 "video",
549 "Demo",
550 ],
551 [
552 "[Demo](https://example.com/demo(1).mp4?a=1\\&b=2)",
553 "https://example.com/demo(1).mp4?a=1&b=2",
554 "video",
555 "Demo",
556 ],
557 [
558 "[Screenshot](https://drop.example.com/shot.webp)",
559 "https://drop.example.com/shot.webp",
560 "image",
561 "Screenshot",
562 ],
563 [
564 "<https://drop.example.com/shot.webp>",
565 "https://drop.example.com/shot.webp",
566 "image",
567 undefined,
568 ],
569 ])("recognizes %s without a request and preserves its label", (body, url, media, label) => {
570 const segments = split(body);
571 expect(segments).toEqual([expect.objectContaining({ kind: "attachment", url, media })]);
572 const [segment] = segments;
573 expect(segment?.kind === "attachment" ? segment.label : null).toBe(label);
574 });
575
576 it.each([
577 "[Open report](https://example.com/report?file=demo.mp4)",
578 "https://example.com/report#demo.png",
579 "[Demo](https://example.com/demo(1).mp4) trailing",
580 "[Demo](https://example.com/demo(1.mp4)",
581 "[Demo](https://example.com/demo(1).mp4?a=1&b=2)",
582 ])("keeps %s a link when not a standalone media link", (body) => {
583 expect(split(body)).toEqual([
584 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
585 ]);
586 });
587
588 it("keeps inline links and media examples in code as prose", () => {
589 const body =
590 "See [recording](https://drop.example.com/a.mp4) for context.\n\n```md\nhttps://drop.example.com/a.png\n```";
591 expect(split(body)).toEqual([
592 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
593 ]);
594 });
595});
596
597describe("media tables", () => {
598 const before = "https://github.com/user-attachments/assets/c69c7c1c-ef2f-47dd-97e8-fe42e40712eb";
599 const after = "https://github.com/user-attachments/assets/1867b6ec-4f88-4248-b2df-6b0f9808105b";
600 const video = "https://example.com/a.mp4";
601
602 it("keeps GitHub's before/after video table together, splitting each cell on its own", () => {
603 const segments = split(
604 `Intro\n\n<table>\n<tr><th>Before</th><th>After</th></tr>\n<tr>\n<td>\n\n${before}\n\n</td>\n<td>\n\n${after}\n\n</td>\n</tr>\n</table>\n\nOutro`,
605 );
606 expect(segments.map((segment) => segment.kind)).toEqual(["markdown", "table", "markdown"]);
607 expect(segments[0]).toMatchObject({ text: "Intro" });
608 expect(segments[2]).toMatchObject({ text: "Outro" });
609 const table = segments[1]!;
610 if (table.kind !== "table") throw new Error("expected a table segment");
611 expect(
612 table.rows.map((row) =>
613 row.map((cell) =>
614 cell.segments.map((segment) =>
615 segment.kind === "attachment" ? `attachment:${segment.url}` : segment,
616 ),
617 ),
618 ),
619 ).toEqual([
620 [
621 [{ id: "markdown:0", kind: "markdown", text: "Before", sourceOffset: 23 }],
622 [{ id: "markdown:0", kind: "markdown", text: "After", sourceOffset: 38 }],
623 ],
624 [[`attachment:${before}`], [`attachment:${after}`]],
625 ]);
626 });
627
628 it("keeps a quoted `>` inside a cell's attributes out of its text", () => {
629 const [table] = split(
630 `<table>\n<tr><td title="Before > after">Caption</td><td>\n\n${video}\n\n</td></tr>\n</table>`,
631 );
632 expect(table).toMatchObject({
633 kind: "table",
634 rows: [[{ segments: [{ kind: "markdown", text: "Caption" }] }, {}]],
635 });
636 });
637
638 it("leaves a table without media links as markdown", () => {
639 const body = "<table>\n<tr><td>a</td><td>b</td></tr>\n</table>";
640 expect(split(body)).toEqual([
641 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
642 ]);
643 });
644
645 it.each([
646 ["a caption", "<table>\n<caption>Before upgrading</caption>\n<tr><td>", "</td></tr>\n</table>"],
647 ["text outside cells", "<table>\nBefore upgrading\n<tr><td>", "</td></tr>\n</table>"],
648 [
649 "text inside a row but outside cells",
650 "<table>\n<tr>Before upgrading<td>",
651 "</td></tr>\n</table>",
652 ],
653 [
654 "a table nested in another",
655 "<table>\n<tr><td>\n<table>\n<tr><td>",
656 "</td></tr>\n</table>\n</td></tr>\n</table>",
657 ],
658 ["an unclosed table", "<table>\n<tr><td>", ""],
659 ["a spanning cell", '<table>\n<tr><td colspan="2">', "</td></tr>\n</table>"],
660 [
661 "an indented cell",
662 "<table>\n <tr>\n <th>\n Before\n </th>\n </tr>\n <tr><td>",
663 "</td></tr>\n</table>",
664 ],
665 [
666 "a cell indented by a space and a tab",
667 "<table>\n<tr><td>\n \tBefore\n</td><td>",
668 "</td></tr>\n</table>",
669 ],
670 ])("splits a media table with %s line by line, as before", (_name, open, close) => {
671 const body = `${open}\n\n${video}\n\n${close}`;
672 expect(split(body)).toEqual([
673 { id: "markdown:0", kind: "markdown", text: open, sourceOffset: 0 },
674 { id: "attachment:1", kind: "attachment", url: video, media: "video" },
675 ...(close
676 ? [
677 {
678 id: "markdown:2",
679 kind: "markdown",
680 text: close,
681 sourceOffset: body.length - close.length,
682 },
683 ]
684 : []),
685 ]);
686 });
687});
688
689describe("change request reference autolinks", () => {
690 const urls = (provider: string, url: string, text: string) =>
691 changeRequestReferenceAutolinker({ provider, url })?.(text).map((link) => link.url) ?? null;
692
693 it("links references against the change request's own repository", () => {
694 expect(urls("github", "https://ghe.example.com/acme/web/pull/7", "Fixes #5")).toEqual([
695 "https://ghe.example.com/acme/web/issues/5",
696 ]);
697 });
698
699 // regression: the mobile review guide linked every host's `#5` with GitHub's grammar
700 it("links nothing on a host whose grammar is not applied", () => {
701 expect(urls("forgejo", "https://codeberg.org/acme/web/pulls/7", "#5")).toBeNull();
702 });
703});
704
705describe("change request media urls", () => {
706 // regression: GitCafe's `/api/attachments/<id>` uploads rendered as missing local files
707 it.each([
708 ["/api/attachments/attach_1", "https://git.cafe/api/attachments/attach_1"],
709 ["//cdn.example.com/a.png", "//cdn.example.com/a.png"],
710 ["/\\evil.example.com/a.png", "/\\evil.example.com/a.png"],
711 ["https://example.com/a.png", "https://example.com/a.png"],
712 ["docs/a.png", "docs/a.png"],
713 ])("resolves %s against the forge", (url, expected) => {
714 expect(resolveChangeRequestMediaUrl(url, "https://git.cafe/pingdotgg/t3code/pulls/31251")).toBe(
715 expected,
716 );
717 });
718});