Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

pullRequestMarkdown.test.ts

441 lines17.4 KB

1import type { Root, RootContent } from "mdast";
2import remarkGfm from "remark-gfm";
3import remarkParse from "remark-parse";
4import { unified } from "unified";
5import { describe, expect, it } from "vite-plus/test";
6​
7import { splitPullRequestBody, type PullRequestBodySegment } from "./pullRequestMarkdown.ts";
8import {
9 changeRequestReferenceAutolinker,
10 resolveChangeRequestMediaUrl,
11} from "./pullRequestReferences.ts";
12​
13const definitionParser = unified().use(remarkParse).use(remarkGfm);
14​
15// The finder a client passes: each first definition, joined onto one line out of its quote.
16const split = (body: string) =>
17 splitPullRequestBody(body, (markdown) => {
18 const definitions = new Map<string, string>();
19 const visit = (node: Root | RootContent, quotes: number) => {
20 if (node.type === "definition" && !definitions.has(node.identifier)) {
21 const wrap = new RegExp(`(?:\\r\\n|\\r|\\n)(?:[ \\t]*>){0,${quotes}}[ \\t]*`, "gu");
22 const source = markdown.slice(node.position?.start.offset, node.position?.end.offset);
23 definitions.set(node.identifier, source.replace(wrap, " "));
24 }
25 if ("children" in node) {
26 for (const child of node.children)
27 visit(child, quotes + (node.type === "blockquote" ? 1 : 0));
28 }
29 };
30 visit(definitionParser.parse(markdown), 0);
31 return [...definitions.values()];
32 });
33​
34describe("pull request body segmentation", () => {
35 // GitHub writes a dropped image into the body as an `<img>` tag, so a bare attachment link on
36 // its own line is the shape it uses for a video — every one sampled in the wild was one.
37 it("lifts a dropped video out and keeps the prose around it", () => {
38 expect(
39 split(
40 "Before\n\nhttps://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456\n\nAfter",
41 ),
42 ).toEqual([
43 { id: "markdown:0", kind: "markdown", text: "Before", sourceOffset: 0 },
44 {
45 id: "attachment:1",
46 kind: "attachment",
47 url: "https://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456",
48 media: "video",
49 },
50 { id: "markdown:2", kind: "markdown", text: "After", sourceOffset: 89 },
51 ]);
52 });
53​
54 it("places each prose run at its offset in the body, including inside a media table", () => {
55 const body =
56 '\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';
57 type Prose = Extract<PullRequestBodySegment, { kind: "markdown" }>;
58 const prose = (segments: ReadonlyArray<PullRequestBodySegment>): Prose[] =>
59 segments.flatMap((segment) =>
60 segment.kind === "markdown"
61 ? [segment]
62 : segment.kind === "table"
63 ? segment.rows.flat().flatMap((cell) => prose(cell.segments))
64 : [],
65 );
66 const runs = prose(split(body));
67 expect(runs.map((segment) => segment.text)).toEqual([
68 "- [ ] Before",
69 " - [ ] code\n- [x] After",
70 "- [ ] In a cell",
71 "- [ ] Last",
72 ]);
73 for (const segment of runs) {
74 expect(body.slice(segment.sourceOffset, segment.sourceOffset + segment.text.length)).toBe(
75 segment.text,
76 );
77 }
78 });
79​
80 it("reads the source out of a video tag, including a multi-line one", () => {
81 expect(
82 split('<video controls>\n <source src="https://example.com/a.webm">\n</video>'),
83 ).toEqual([
84 {
85 id: "attachment:0",
86 kind: "attachment",
87 url: "https://example.com/a.webm",
88 media: "video",
89 },
90 ]);
91 });
92​
93 it("leaves the img tag GitHub writes for a dropped image as markdown", () => {
94 const body =
95 '<img width="1414" alt="image" src="https://github.com/user-attachments/assets/7195f963-51a9-4331-be74-3e06be760422" />';
96 expect(split(body)).toEqual([
97 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
98 ]);
99 });
100​
101 it("leaves an ordinary link alone, whether it is bare or written as markdown", () => {
102 const body = "https://example.com/page\n\n[the docs](https://example.com/docs)";
103 expect(split(body)).toEqual([
104 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
105 ]);
106 });
107​
108 it("never lifts a link inside fenced code out of it", () => {
109 const body = "```\nhttps://example.com/demo.mp4\n```";
110 expect(split(body)).toEqual([
111 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
112 ]);
113 });
114​
115 // GitHub keeps CRLF in a body written in its web editor.
116 it("recognizes fences in a body with CRLF line endings", () => {
117 const body = "```\r\nhttps://example.com/demo.mp4\r\n```";
118 expect(split(body)).toEqual([
119 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
120 ]);
121 });
122​
123 it("closes a CRLF fence, so a video after it still lifts out", () => {
124 const code = '```html\r\n<video src="https://example.com/example.mp4"></video>\r\n```';
125 expect(split(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([
126 { id: "markdown:0", kind: "markdown", text: code, sourceOffset: 0 },
127 {
128 id: "attachment:1",
129 kind: "attachment",
130 url: "https://example.com/demo.mp4",
131 media: "video",
132 },
133 ]);
134 });
135​
136 it("does not let a different fence marker close an open fence", () => {
137 const body = "```\n~~~\nhttps://example.com/demo.mp4\n```";
138 expect(split(body)).toEqual([
139 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
140 ]);
141 });
142​
143 it("keeps a video tag that shares its line with prose as markdown", () => {
144 const body = 'Before <video src="https://example.com/a.mp4"></video> after';
145 expect(split(body)).toEqual([
146 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
147 ]);
148 });
149​
150 it("treats an info-string fence as a nested opener, not a close", () => {
151 const body = "```\n```javascript\nhttps://example.com/demo.mp4\n```";
152 expect(split(body)).toEqual([
153 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
154 ]);
155 });
156​
157 it("does not open a fence on a line of inline triple-backtick code", () => {
158 const code = "```\nhttps://example.com/b.png\n```";
159 expect(
160 split(`\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`),
161 ).toEqual([
162 { id: "markdown:0", kind: "markdown", text: "```npm test``` passes.", sourceOffset: 0 },
163 {
164 id: "attachment:1",
165 kind: "attachment",
166 url: "https://example.com/demo.mp4",
167 media: "video",
168 },
169 { id: "markdown:2", kind: "markdown", text: code, sourceOffset: 54 },
170 ]);
171 const multilineSpan = "```foo`\nhttps://example.com/demo.mp4\nbar```";
172 expect(split(multilineSpan)).toEqual([
173 { id: "markdown:0", kind: "markdown", text: multilineSpan, sourceOffset: 0 },
174 ]);
175 });
176​
177 it("leaves an indented code line alone even when it is only a video link", () => {
178 const body = " https://example.com/demo.mp4";
179 expect(split(body)).toEqual([
180 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
181 ]);
182 });
183​
184 it("leaves an unclosed video tag as prose without eating the rest of the body", () => {
185 const body = ['<video src="https://example.com/a.mp4">', "still prose", "more prose"].join(
186 "\n",
187 );
188 expect(split(body)).toEqual([
189 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
190 ]);
191 });
192​
193 it.each([
194 ["a whitespace run inside a line", `a${" ".repeat(1_000_000)}b`],
195 ["a run of unclosed video tags", `${"<video ".repeat(150_000)}</video>`],
196 ["a run of backticks before a line separator", `${"`".repeat(100_000)}\u2028x`],
197 ])("splits %s in one pass", (_case, body) => {
198 expect(split(body)).toEqual([
199 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
200 ]);
201 });
202​
203 it("refuses a non-http source rather than making a link out of it", () => {
204 const body = '<video src="javascript:alert(1)"></video>';
205 expect(split(body)).toEqual([
206 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
207 ]);
208 });
209});
210​
211describe("reference links around lifted media", () => {
212 const recording =
213 "https://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456";
214 const parser = unified().use(remarkParse).use(remarkGfm);
215 const prose = (segments: ReadonlyArray<PullRequestBodySegment>): string[] =>
216 segments.flatMap((segment) =>
217 segment.kind === "markdown"
218 ? [segment.text]
219 : segment.kind === "table"
220 ? segment.rows.flat().flatMap((cell) => prose(cell.segments))
221 : [],
222 );
223 // Each segment renders as its own document; the first definition of a label wins, as in mdast-util-to-hast.
224 const referenceLinks = (body: string) =>
225 prose(split(body)).flatMap((text) => {
226 const definitions = new Map<string, string>();
227 const references: Array<{ identifier: string; text: string }> = [];
228 const visit = (node: Root | RootContent) => {
229 if (node.type === "definition" && !definitions.has(node.identifier)) {
230 definitions.set(node.identifier, node.url);
231 }
232 if (node.type === "linkReference") {
233 references.push({
234 identifier: node.identifier,
235 text: node.children.map((child) => ("value" in child ? child.value : "")).join(""),
236 });
237 }
238 if ("children" in node) node.children.forEach(visit);
239 };
240 visit(parser.parse(text));
241 return references.map((reference) => [reference.text, definitions.get(reference.identifier)]);
242 });
243​
244 it.each([
245 [
246 "use, then media, then definition",
247 `See [the docs][guide].\n\n${recording}\n\n[guide]: https://example.com/docs`,
248 ],
249 [
250 "definition, then media, then use",
251 `[guide]: https://example.com/docs\n\n${recording}\n\nSee [the docs][guide].`,
252 ],
253 ...["\n", "\r\n", "\r"].map((lineEnding) => [
254 `a definition wrapped over quoted lines with ${JSON.stringify(lineEnding)}`,
255 `> [guide]:${lineEnding}> https://example.com/docs${lineEnding}> "The guide"\n\n${recording}\n\nSee [the docs][guide].`,
256 ]),
257 [
258 "a use inside a media table cell",
259 `<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`,
260 ],
261 ])("resolves a reference defined across a video: %s", (_case, body) => {
262 expect(referenceLinks(body)).toEqual([["the docs", "https://example.com/docs"]]);
263 });
264​
265 it("keeps the body's first definition of a label, wherever the media falls", () => {
266 expect(
267 referenceLinks(
268 `[guide]: https://example.com/first\n\n${recording}\n\nSee [the docs][guide].\n\n[GUIDE]: https://example.com/second`,
269 ),
270 ).toEqual([["the docs", "https://example.com/first"]]);
271 });
272​
273 it("renders the body whole when its definitions would be repeated past the budget", () => {
274 const definitions = Array.from(
275 { length: 400 },
276 (_, index) => `[d${index}]: https://example.com/${"x".repeat(60)}${index}`,
277 ).join("\n");
278 const uses = Array.from({ length: 1200 }, () => `[use][d1]\n${recording}`).join("\n");
279 const body = `\n${definitions}\n\n${uses}\n`;
280 expect(split(body)).toEqual([
281 { id: "markdown:0", kind: "markdown", text: body.trim(), sourceOffset: 1 },
282 ]);
283 });
284​
285 it("leaves a definition shown in code as code", () => {
286 expect(
287 referenceLinks(
288 `\`\`\`md\n[guide]: https://example.com/docs\n\`\`\`\n\n${recording}\n\nSee [the docs][guide].`,
289 ),
290 ).toEqual([]);
291 });
292​
293 it("still writes a task tick back to its place in the body", () => {
294 const body = `[guide]: https://example.com/docs\n\n${recording}\n\n- [ ] Read [the docs][guide]`;
295 const segment = split(body).at(-1)!;
296 if (segment.kind !== "markdown") throw new Error("expected prose last");
297 const marker = segment.text.indexOf("[ ]");
298 expect(body.slice(segment.sourceOffset + marker)).toBe("[ ] Read [the docs][guide]");
299 });
300});
301​
302describe("media on custom hosts", () => {
303 it.each([
304 ["https://drop.example.com/capture.PNG?token=abc#preview", "image"],
305 ["[Recording](https://drop.example.com/recording.mov)", "video"],
306 ["<https://drop.example.com/shot.webp>", "image"],
307 ])("recognizes %s without a request", (body, media) => {
308 expect(split(body)).toEqual([expect.objectContaining({ kind: "attachment", media })]);
309 });
310​
311 it("keeps inline links and media examples in code as prose", () => {
312 const body =
313 "See [recording](https://drop.example.com/a.mp4) for context.\n\n```md\nhttps://drop.example.com/a.png\n```";
314 expect(split(body)).toEqual([
315 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
316 ]);
317 });
318});
319​
320describe("media tables", () => {
321 const before = "https://github.com/user-attachments/assets/c69c7c1c-ef2f-47dd-97e8-fe42e40712eb";
322 const after = "https://github.com/user-attachments/assets/1867b6ec-4f88-4248-b2df-6b0f9808105b";
323 const video = "https://example.com/a.mp4";
324​
325 it("keeps GitHub's before/after video table together, splitting each cell on its own", () => {
326 const segments = split(
327 `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`,
328 );
329 expect(segments.map((segment) => segment.kind)).toEqual(["markdown", "table", "markdown"]);
330 expect(segments[0]).toMatchObject({ text: "Intro" });
331 expect(segments[2]).toMatchObject({ text: "Outro" });
332 const table = segments[1]!;
333 if (table.kind !== "table") throw new Error("expected a table segment");
334 expect(
335 table.rows.map((row) =>
336 row.map((cell) =>
337 cell.segments.map((segment) =>
338 segment.kind === "attachment" ? `attachment:${segment.url}` : segment,
339 ),
340 ),
341 ),
342 ).toEqual([
343 [
344 [{ id: "markdown:0", kind: "markdown", text: "Before", sourceOffset: 23 }],
345 [{ id: "markdown:0", kind: "markdown", text: "After", sourceOffset: 38 }],
346 ],
347 [[`attachment:${before}`], [`attachment:${after}`]],
348 ]);
349 });
350​
351 it("keeps a quoted `>` inside a cell's attributes out of its text", () => {
352 const [table] = split(
353 `<table>\n<tr><td title="Before > after">Caption</td><td>\n\n${video}\n\n</td></tr>\n</table>`,
354 );
355 expect(table).toMatchObject({
356 kind: "table",
357 rows: [[{ segments: [{ kind: "markdown", text: "Caption" }] }, {}]],
358 });
359 });
360​
361 it("leaves a table without media links as markdown", () => {
362 const body = "<table>\n<tr><td>a</td><td>b</td></tr>\n</table>";
363 expect(split(body)).toEqual([
364 { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 },
365 ]);
366 });
367​
368 it.each([
369 ["a caption", "<table>\n<caption>Before upgrading</caption>\n<tr><td>", "</td></tr>\n</table>"],
370 ["text outside cells", "<table>\nBefore upgrading\n<tr><td>", "</td></tr>\n</table>"],
371 [
372 "text inside a row but outside cells",
373 "<table>\n<tr>Before upgrading<td>",
374 "</td></tr>\n</table>",
375 ],
376 [
377 "a table nested in another",
378 "<table>\n<tr><td>\n<table>\n<tr><td>",
379 "</td></tr>\n</table>\n</td></tr>\n</table>",
380 ],
381 ["an unclosed table", "<table>\n<tr><td>", ""],
382 ["a spanning cell", '<table>\n<tr><td colspan="2">', "</td></tr>\n</table>"],
383 [
384 "an indented cell",
385 "<table>\n <tr>\n <th>\n Before\n </th>\n </tr>\n <tr><td>",
386 "</td></tr>\n</table>",
387 ],
388 [
389 "a cell indented by a space and a tab",
390 "<table>\n<tr><td>\n \tBefore\n</td><td>",
391 "</td></tr>\n</table>",
392 ],
393 ])("splits a media table with %s line by line, as before", (_name, open, close) => {
394 const body = `${open}\n\n${video}\n\n${close}`;
395 expect(split(body)).toEqual([
396 { id: "markdown:0", kind: "markdown", text: open, sourceOffset: 0 },
397 { id: "attachment:1", kind: "attachment", url: video, media: "video" },
398 ...(close
399 ? [
400 {
401 id: "markdown:2",
402 kind: "markdown",
403 text: close,
404 sourceOffset: body.length - close.length,
405 },
406 ]
407 : []),
408 ]);
409 });
410});
411​
412describe("change request reference autolinks", () => {
413 const urls = (provider: string, url: string, text: string) =>
414 changeRequestReferenceAutolinker({ provider, url })?.(text).map((link) => link.url) ?? null;
415​
416 it("links references against the change request's own repository", () => {
417 expect(urls("github", "https://ghe.example.com/acme/web/pull/7", "Fixes #5")).toEqual([
418 "https://ghe.example.com/acme/web/issues/5",
419 ]);
420 });
421​
422 // regression: the mobile review guide linked every host's `#5` with GitHub's grammar
423 it("links nothing on a host whose grammar is not applied", () => {
424 expect(urls("forgejo", "https://codeberg.org/acme/web/pulls/7", "#5")).toBeNull();
425 });
426});
427​
428describe("change request media urls", () => {
429 // regression: GitCafe's `/api/attachments/<id>` uploads rendered as missing local files
430 it.each([
431 ["/api/attachments/attach_1", "https://git.cafe/api/attachments/attach_1"],
432 ["//cdn.example.com/a.png", "//cdn.example.com/a.png"],
433 ["/\\evil.example.com/a.png", "/\\evil.example.com/a.png"],
434 ["https://example.com/a.png", "https://example.com/a.png"],
435 ["docs/a.png", "docs/a.png"],
436 ])("resolves %s against the forge", (url, expected) => {
437 expect(resolveChangeRequestMediaUrl(url, "https://git.cafe/pingdotgg/t3code/pulls/31251")).toBe(
438 expected,
439 );
440 });
441});