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("only lets a list starting at 1 open a fence inside prose", () => {
261 const splitSegments = (body: string) => splitPullRequestBody(body, () => []);
262 const body = "Intro\n2. ~~~\n https://example.com/demo.mp4";
263 const segments = splitSegments(body);
264 expect(segments.map((segment) => segment.kind)).toEqual(["markdown", "attachment"]);
265 expect(segments[1]).toMatchObject({ url: "https://example.com/demo.mp4", media: "video" });
266 for (const code of [
267 body.replace("2.", "1."),
268 body.replace("Intro\n", "Intro\n\n"),
269 body.replace("Intro", "# Intro"),
270 body.replace("Intro", "1. Item\ncontinuation"),
271 body.replace("Intro", "| Header |\n| --- |\n| Value |"),
272 ]) {
273 expect(splitSegments(code)).toEqual([
274 { id: "markdown:0", kind: "markdown", text: code, sourceOffset: 0 },
275 ]);
276 }
277 });
278
279 it("does not let a different fence marker close an open fence", () => {
280 const body = "```\n~~~\nhttps://example.com/demo.mp4\n```";
281 expect(split(body)).toEqual([
282 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
283 ]);
284 });
285
286 it("does not close a fence opened at the margin on a tab-indented marker", () => {
287 const code = "```\n\t```\nhttps://example.com/sample.mp4\n```";
288 expect(split(`${code}\n\nhttps://example.com/demo.mp4`)).toEqual([
289 { id: "markdown:0", kind: "markdown", text: code, sourceOffset: 0 },
290 {
291 id: "attachment:1",
292 kind: "attachment",
293 url: "https://example.com/demo.mp4",
294 media: "video",
295 },
296 ]);
297 const listCode = "- List\n\n\t```md\n https://example.com/sample.mp4\n\t```";
298 expect(split(`${listCode}\n\nhttps://example.com/demo.mp4`)).toEqual([
299 { id: "markdown:0", kind: "markdown", text: listCode, sourceOffset: 0 },
300 {
301 id: "attachment:1",
302 kind: "attachment",
303 url: "https://example.com/demo.mp4",
304 media: "video",
305 },
306 ]);
307 });
308
309 it("keeps a video tag that shares its line with prose as markdown", () => {
310 const body = 'Before <video src="https://example.com/a.mp4"></video> after';
311 expect(split(body)).toEqual([
312 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
313 ]);
314 const captioned = '<video src="https://example.com/a.mp4"></video> Before the fix\n\nIt opens.';
315 expect(split(`${captioned}\n\n<video src="https://example.com/b.mp4"></video>`)).toEqual([
316 { id: "markdown:0", kind: "markdown", text: captioned, sourceOffset: 0 },
317 { id: "attachment:1", kind: "attachment", url: "https://example.com/b.mp4", media: "video" },
318 ]);
319 });
320
321 it("treats an info-string fence as a nested opener, not a close", () => {
322 const body = "```\n```javascript\nhttps://example.com/demo.mp4\n```";
323 expect(split(body)).toEqual([
324 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
325 ]);
326 });
327
328 it("does not open a fence on a line of inline triple-backtick code", () => {
329 const code = "```\nhttps://example.com/b.png\n```";
330 expect(
331 split(`\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`),
332 ).toEqual([
333 { id: "markdown:0", kind: "markdown", text: "```npm test``` passes.", sourceOffset: 0 },
334 {
335 id: "attachment:1",
336 kind: "attachment",
337 url: "https://example.com/demo.mp4",
338 media: "video",
339 },
340 { id: "markdown:2", kind: "markdown", text: code, sourceOffset: 54 },
341 ]);
342 const multilineSpan = "```foo`\nhttps://example.com/demo.mp4\nbar```";
343 expect(split(multilineSpan)).toEqual([
344 { id: "markdown:0", kind: "markdown", text: multilineSpan, sourceOffset: 0 },
345 ]);
346 });
347
348 it("leaves an indented code line alone even when it is only a video link", () => {
349 const body = " https://example.com/demo.mp4";
350 expect(split(body)).toEqual([
351 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
352 ]);
353 });
354
355 it("never lifts media out of an HTML comment, while lifting media after it", () => {
356 const visible = {
357 id: "attachment:1",
358 kind: "attachment",
359 url: "https://example.org/visible.mp4",
360 media: "video",
361 };
362 // A fence inside a comment is hidden too, so it must not open a code block.
363 const comment = [
364 "<!--",
365 "https://example.org/hidden.mp4",
366 '<video src="https://example.org/hidden-tag.mp4"></video>',
367 "```",
368 "-->",
369 ].join("\n");
370 for (const hidden of [comment, "<!-- template hint -->"]) {
371 expect(split(`${hidden}\n\nhttps://example.org/visible.mp4`)).toEqual([
372 { id: "markdown:0", kind: "markdown", text: hidden, sourceOffset: 0 },
373 visible,
374 ]);
375 }
376 });
377
378 it("leaves an unclosed video tag as prose without eating the rest of the body", () => {
379 const body = ['<video src="https://example.com/a.mp4">', "still prose", "more prose"].join(
380 "\n",
381 );
382 expect(split(body)).toEqual([
383 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
384 ]);
385 });
386
387 it.each([
388 ["a whitespace run inside a line", `a${" ".repeat(1_000_000)}b`],
389 ["a run of unclosed video tags", `${"<video ".repeat(150_000)}</video>`],
390 ["a run of backticks before a line separator", `${"`".repeat(100_000)}\u2028x`],
391 ])("splits %s in one pass", (_case, body) => {
392 expect(split(body)).toEqual([
393 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
394 ]);
395 });
396
397 it("refuses a non-http source rather than making a link out of it", () => {
398 const body = '<video src="javascript:alert(1)"></video>';
399 expect(split(body)).toEqual([
400 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
401 ]);
402 });
403});
404
405describe("extensionless pull request media", () => {
406 it.effect.each([
407 [206, "image/png", "image"],
408 [206, "video/mp4", "video"],
409 [200, "text/html", null],
410 [404, "image/png", null],
411 ] as const)("classifies HTTP %i with Content-Type %s", ([status, contentType, kind]) =>
412 Effect.gen(function* () {
413 const cancel = vi.fn();
414 const fetchMedia = vi.fn(
415 async () =>
416 new Response(new ReadableStream({ cancel }), {
417 status,
418 headers: { "content-type": contentType },
419 }),
420 );
421 const url = "https://environment.test/api/assets/signed/upload";
422 const registry = AtomRegistry.make();
423 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
424 const atom = makePullRequestMediaKindAtom(fetchMedia)(url);
425 expect(yield* AtomRegistry.getResult(registry, atom)).toBe(kind);
426 expect(fetchMedia).toHaveBeenCalledWith(
427 url,
428 expect.objectContaining({
429 headers: { Range: "bytes=0-0" },
430 }),
431 );
432 expect(cancel).toHaveBeenCalledOnce();
433 }),
434 );
435});
436
437describe("reference links around lifted media", () => {
438 const recording =
439 "https://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456";
440 const parser = unified().use(remarkParse).use(remarkGfm);
441 const prose = (segments: ReadonlyArray<PullRequestBodySegment>): string[] =>
442 segments.flatMap((segment) =>
443 segment.kind === "markdown"
444 ? [segment.text]
445 : segment.kind === "table"
446 ? segment.rows.flat().flatMap((cell) => prose(cell.segments))
447 : [],
448 );
449 // Each segment renders as its own document; the first definition of a label wins, as in mdast-util-to-hast.
450 const referenceLinks = (body: string) =>
451 prose(split(body)).flatMap((text) => {
452 const definitions = new Map<string, string>();
453 const references: Array<{ identifier: string; text: string }> = [];
454 const visit = (node: Root | RootContent) => {
455 if (node.type === "definition" && !definitions.has(node.identifier)) {
456 definitions.set(node.identifier, node.url);
457 }
458 if (node.type === "linkReference") {
459 references.push({
460 identifier: node.identifier,
461 text: node.children.map((child) => ("value" in child ? child.value : "")).join(""),
462 });
463 }
464 if ("children" in node) node.children.forEach(visit);
465 };
466 visit(parser.parse(text));
467 return references.map((reference) => [reference.text, definitions.get(reference.identifier)]);
468 });
469
470 it.each([
471 [
472 "use, then media, then definition",
473 `See [the docs][guide].\n\n${recording}\n\n[guide]: https://example.com/docs`,
474 ],
475 [
476 "definition, then media, then use",
477 `[guide]: https://example.com/docs\n\n${recording}\n\nSee [the docs][guide].`,
478 ],
479 ...["\n", "\r\n", "\r"].map((lineEnding) => [
480 `a definition wrapped over quoted lines with ${JSON.stringify(lineEnding)}`,
481 `> [guide]:${lineEnding}> https://example.com/docs${lineEnding}> "The guide"\n\n${recording}\n\nSee [the docs][guide].`,
482 ]),
483 [
484 "a use inside a media table cell",
485 `<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`,
486 ],
487 ])("resolves a reference defined across a video: %s", (_case, body) => {
488 expect(referenceLinks(body)).toEqual([["the docs", "https://example.com/docs"]]);
489 });
490
491 it("keeps the body's first definition of a label, wherever the media falls", () => {
492 expect(
493 referenceLinks(
494 `[guide]: https://example.com/first\n\n${recording}\n\nSee [the docs][guide].\n\n[GUIDE]: https://example.com/second`,
495 ),
496 ).toEqual([["the docs", "https://example.com/first"]]);
497 });
498
499 it("renders the body whole when its definitions would be repeated past the budget", () => {
500 const definitions = Array.from(
501 { length: 400 },
502 (_, index) => `[d${index}]: https://example.com/${"x".repeat(60)}${index}`,
503 ).join("\n");
504 const uses = Array.from({ length: 1200 }, () => `[use][d1]\n${recording}`).join("\n");
505 const body = `\n${definitions}\n\n${uses}\n`;
506 expect(split(body)).toEqual([
507 { id: "markdown:0", kind: "markdown", text: body.trim(), sourceOffset: 1 },
508 ]);
509 });
510
511 it("leaves a definition shown in code as code", () => {
512 expect(
513 referenceLinks(
514 `\`\`\`md\n[guide]: https://example.com/docs\n\`\`\`\n\n${recording}\n\nSee [the docs][guide].`,
515 ),
516 ).toEqual([]);
517 });
518
519 it("still writes a task tick back to its place in the body", () => {
520 const body = `[guide]: https://example.com/docs\n\n${recording}\n\n- [ ] Read [the docs][guide]`;
521 const segment = split(body).at(-1)!;
522 if (segment.kind !== "markdown") throw new Error("expected prose last");
523 const marker = segment.text.indexOf("[ ]");
524 expect(body.slice(segment.sourceOffset + marker)).toBe("[ ] Read [the docs][guide]");
525 });
526
527 it.each([
528 ["\uFEFF", "", 0],
529 ["intro\n\n\uFEFF", "intro\n\n\uFEFF", 0],
530 [`${recording}\n\n\uFEFF`, "\uFEFF", 1],
531 ])("preserves BOM meaning and task offsets after prefix %j", (prefix, kept, pick) => {
532 const definition = "[guide]: https://example.com/docs";
533 const task = "- [ ] Read [guide]";
534 const body = `${prefix}${task}\n\n${recording}\n\n${definition}`;
535 const segment = splitPullRequestBody(body, () => [definition])[pick]!;
536 if (segment.kind !== "markdown") throw new Error("expected prose");
537 expect(segment.text).toBe(`${definition}\n\n${kept}${task}`);
538 expect(segment.sourceOffset + segment.text.indexOf("[ ]")).toBe(body.indexOf("[ ]"));
539 });
540});
541
542describe("media on custom hosts", () => {
543 it.each([
544 [
545 "https://drop.example.com/capture.PNG?token=abc#preview",
546 "https://drop.example.com/capture.PNG?token=abc#preview",
547 "image",
548 undefined,
549 ],
550 [
551 "[Recording](https://drop.example.com/recording.mov)",
552 "https://drop.example.com/recording.mov",
553 "video",
554 "Recording",
555 ],
556 ["[Demo](https://example.com/demo(1).mp4)", "https://example.com/demo(1).mp4", "video", "Demo"],
557 [
558 "[Demo [v2]](https://example.com/demo.mp4)",
559 "https://example.com/demo.mp4",
560 "video",
561 "Demo [v2]",
562 ],
563 ["[`[`](https://example.com/demo.mp4)", "https://example.com/demo.mp4", "video", "`[`"],
564 [
565 "[Demo](https://example.com/demo\\(1\\).mp4)",
566 "https://example.com/demo(1).mp4",
567 "video",
568 "Demo",
569 ],
570 [
571 "[Demo](https://example.com/demo(1).mp4?a=1\\&b=2)",
572 "https://example.com/demo(1).mp4?a=1&b=2",
573 "video",
574 "Demo",
575 ],
576 [
577 "[Screenshot](https://drop.example.com/shot.webp)",
578 "https://drop.example.com/shot.webp",
579 "image",
580 "Screenshot",
581 ],
582 [
583 "<https://drop.example.com/shot.webp>",
584 "https://drop.example.com/shot.webp",
585 "image",
586 undefined,
587 ],
588 ])("recognizes %s without a request and preserves its label", (body, url, media, label) => {
589 const segments = split(body);
590 expect(segments).toEqual([expect.objectContaining({ kind: "attachment", url, media })]);
591 const [segment] = segments;
592 expect(segment?.kind === "attachment" ? segment.label : null).toBe(label);
593 });
594
595 it.each([
596 "[Open report](https://example.com/report?file=demo.mp4)",
597 "https://example.com/report#demo.png",
598 "[Demo](https://example.com/demo(1).mp4) trailing",
599 "[Demo](https://example.com/demo(1.mp4)",
600 "[Demo](https://example.com/demo(1).mp4?a=1&b=2)",
601 ])("keeps %s a link when not a standalone media link", (body) => {
602 expect(split(body)).toEqual([
603 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
604 ]);
605 });
606
607 it("keeps inline links and media examples in code as prose", () => {
608 const body =
609 "See [recording](https://drop.example.com/a.mp4) for context.\n\n```md\nhttps://drop.example.com/a.png\n```";
610 expect(split(body)).toEqual([
611 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
612 ]);
613 });
614});
615
616describe("media tables", () => {
617 const before = "https://github.com/user-attachments/assets/c69c7c1c-ef2f-47dd-97e8-fe42e40712eb";
618 const after = "https://github.com/user-attachments/assets/1867b6ec-4f88-4248-b2df-6b0f9808105b";
619 const video = "https://example.com/a.mp4";
620
621 it("keeps GitHub's before/after video table together, splitting each cell on its own", () => {
622 const segments = split(
623 `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`,
624 );
625 expect(segments.map((segment) => segment.kind)).toEqual(["markdown", "table", "markdown"]);
626 expect(segments[0]).toMatchObject({ text: "Intro" });
627 expect(segments[2]).toMatchObject({ text: "Outro" });
628 const table = segments[1]!;
629 if (table.kind !== "table") throw new Error("expected a table segment");
630 expect(
631 table.rows.map((row) =>
632 row.map((cell) =>
633 cell.segments.map((segment) =>
634 segment.kind === "attachment" ? `attachment:${segment.url}` : segment,
635 ),
636 ),
637 ),
638 ).toEqual([
639 [
640 [{ id: "markdown:0", kind: "markdown", text: "Before", sourceOffset: 23 }],
641 [{ id: "markdown:0", kind: "markdown", text: "After", sourceOffset: 38 }],
642 ],
643 [[`attachment:${before}`], [`attachment:${after}`]],
644 ]);
645 });
646
647 it("keeps a quoted `>` inside a cell's attributes out of its text", () => {
648 const [table] = split(
649 `<table>\n<tr><td title="Before > after">Caption</td><td>\n\n${video}\n\n</td></tr>\n</table>`,
650 );
651 expect(table).toMatchObject({
652 kind: "table",
653 rows: [[{ segments: [{ kind: "markdown", text: "Caption" }] }, {}]],
654 });
655 });
656
657 it("leaves a table without media links as markdown", () => {
658 const body = "<table>\n<tr><td>a</td><td>b</td></tr>\n</table>";
659 expect(split(body)).toEqual([
660 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
661 ]);
662 });
663
664 it.each([
665 ["a caption", "<table>\n<caption>Before upgrading</caption>\n<tr><td>", "</td></tr>\n</table>"],
666 ["text outside cells", "<table>\nBefore upgrading\n<tr><td>", "</td></tr>\n</table>"],
667 [
668 "text inside a row but outside cells",
669 "<table>\n<tr>Before upgrading<td>",
670 "</td></tr>\n</table>",
671 ],
672 [
673 "a table nested in another",
674 "<table>\n<tr><td>\n<table>\n<tr><td>",
675 "</td></tr>\n</table>\n</td></tr>\n</table>",
676 ],
677 ["an unclosed table", "<table>\n<tr><td>", ""],
678 ["a spanning cell", '<table>\n<tr><td colspan="2">', "</td></tr>\n</table>"],
679 [
680 "an indented cell",
681 "<table>\n <tr>\n <th>\n Before\n </th>\n </tr>\n <tr><td>",
682 "</td></tr>\n</table>",
683 ],
684 [
685 "a cell indented by a space and a tab",
686 "<table>\n<tr><td>\n \tBefore\n</td><td>",
687 "</td></tr>\n</table>",
688 ],
689 ])("splits a media table with %s line by line, as before", (_name, open, close) => {
690 const body = `${open}\n\n${video}\n\n${close}`;
691 expect(split(body)).toEqual([
692 { id: "markdown:0", kind: "markdown", text: open, sourceOffset: 0 },
693 { id: "attachment:1", kind: "attachment", url: video, media: "video" },
694 ...(close
695 ? [
696 {
697 id: "markdown:2",
698 kind: "markdown",
699 text: close,
700 sourceOffset: body.length - close.length,
701 },
702 ]
703 : []),
704 ]);
705 });
706});
707
708describe("change request reference autolinks", () => {
709 const urls = (provider: string, url: string, text: string) =>
710 changeRequestReferenceAutolinker({ provider, url })?.(text).map((link) => link.url) ?? null;
711
712 it("links references against the change request's own repository", () => {
713 expect(urls("github", "https://ghe.example.com/acme/web/pull/7", "Fixes #5")).toEqual([
714 "https://ghe.example.com/acme/web/issues/5",
715 ]);
716 });
717
718 // regression: the mobile review guide linked every host's `#5` with GitHub's grammar
719 it("links nothing on a host whose grammar is not applied", () => {
720 expect(urls("forgejo", "https://codeberg.org/acme/web/pulls/7", "#5")).toBeNull();
721 });
722});
723
724describe("change request media urls", () => {
725 // regression: GitCafe's `/api/attachments/<id>` uploads rendered as missing local files
726 it.each([
727 ["/api/attachments/attach_1", "https://git.cafe/api/attachments/attach_1"],
728 ["//cdn.example.com/a.png", "//cdn.example.com/a.png"],
729 ["/\\evil.example.com/a.png", "/\\evil.example.com/a.png"],
730 ["https://example.com/a.png", "https://example.com/a.png"],
731 ["docs/a.png", "docs/a.png"],
732 ])("resolves %s against the forge", (url, expected) => {
733 expect(resolveChangeRequestMediaUrl(url, "https://git.cafe/pingdotgg/t3code/pulls/31251")).toBe(
734 expected,
735 );
736 });
737});