Open History to see the last commit
1import { describe, expect, it } from "vite-plus/test";
2
3import { toHtml } from "hast-util-to-html";
4import remarkGfm from "remark-gfm";
5import remarkParse from "remark-parse";
6import remarkRehype from "remark-rehype";
7import { unified } from "unified";
8
9import {
10 buildMarkdownFootnotesSection,
11 findFootnoteRefChunkIndex,
12 joinMarkdownChunks,
13 LARGE_MARKDOWN_CHUNK_MAX_CHARS,
14 prepareMarkdownChunk,
15 splitMarkdown,
16 withMarkdownDefinitions,
17} from "./markdownChunks.ts";
18import { taskListMarkerOffset } from "./markdownTaskEdits.ts";
19
20const splitLargeMarkdown = (text: string, targetChars?: number) =>
21 splitMarkdown(text, targetChars).chunks;
22
23const starts = (text: string) =>
24 splitLargeMarkdown(text, 1).map((chunk) => chunk.text.split("\n")[0]);
25
26describe("splitMarkdown", () => {
27 it("cuts only where a new top-level block starts, and keeps every byte", () => {
28 const text = [
29 "# Title",
30 "Intro paragraph",
31 "",
32 "- item one",
33 "",
34 " continued item",
35 "- item two",
36 "",
37 "2. ordered",
38 "",
39 "```md",
40 "# not a heading",
41 "",
42 "Not a paragraph",
43 "```",
44 "",
45 "> quote",
46 "",
47 "Closing paragraph",
48 "## Next",
49 "---",
50 "",
51 "| a | b |",
52 ].join("\n");
53 const chunks = splitLargeMarkdown(text, 1);
54 expect(chunks.map((chunk) => chunk.text).join("\n")).toBe(text);
55 expect(chunks.reduce((sum, chunk) => sum + chunk.lines, 0)).toBe(text.split("\n").length);
56 expect(starts(text)).toEqual([
57 "# Title",
58 "```md",
59 "> quote",
60 "Closing paragraph",
61 "## Next",
62 "| a | b |",
63 ]);
64 });
65
66 it("keeps a fence open until a matching closer", () => {
67 const text = ["````", "```", "", "# inside", "````", "", "after"].join("\n");
68 expect(starts(text)).toEqual(["````", "after"]);
69 });
70
71 it("treats nonbreaking spaces as content rather than fence suffixes or blank lines", () => {
72 const fence = ["```md", "x".repeat(4100), "```\u00a0", "# literal", "```"].join("\n");
73 expect(splitLargeMarkdown(fence)).toHaveLength(1);
74
75 const prose = ["*" + "x".repeat(4100), "\u00a0", "more*"].join("\n");
76 expect(splitLargeMarkdown(prose)).toHaveLength(1);
77
78 const htmlBlock = ["<div>", "x".repeat(4100), "\u00a0", "# literal", "</div>"].join("\n");
79 expect(splitLargeMarkdown(htmlBlock)).toHaveLength(1);
80
81 const listFence = "- ~~~md\n\u00a0\n\n [real]: /right\n\n[real]";
82 expect(splitMarkdown(listFence, 1).definitions).toBe("[real]: /right");
83 });
84
85 it("still closes fences and recognizes blank lines with ASCII spaces, tabs, and CRLF", () => {
86 const fence = ["```md", "x".repeat(4100), "``` \t", "# heading"].join("\r\n");
87 expect(splitLargeMarkdown(fence).map((chunk) => chunk.text.split("\r\n")[0])).toEqual([
88 "```md",
89 "# heading",
90 ]);
91
92 const prose = ["a".repeat(4100), " \t", "next paragraph"].join("\r\n");
93 expect(splitLargeMarkdown(prose).map((chunk) => chunk.text.split("\r\n")[0])).toEqual([
94 "a".repeat(4100),
95 "next paragraph",
96 ]);
97
98 const htmlBlock = ["<div>", "x".repeat(4100), " \t", "# heading"].join("\r\n");
99 expect(splitLargeMarkdown(htmlBlock).map((chunk) => chunk.text.split("\r\n")[0])).toEqual([
100 "<div>",
101 "# heading",
102 ]);
103 });
104
105 it("splits CR-only Markdown into bounded chunks like LF and preserves line endings", () => {
106 const cr = `first\r\r# ${"x\r\r# ".repeat(30_000)}end`;
107 const lf = cr.replaceAll("\r", "\n");
108 const crResult = splitMarkdown(cr);
109 const lfResult = splitMarkdown(lf);
110
111 expect(crResult.chunks.length).toBe(lfResult.chunks.length);
112 expect(crResult.chunks.length).toBeGreaterThan(1);
113 expect(
114 crResult.chunks.every((chunk) => chunk.text.length <= LARGE_MARKDOWN_CHUNK_MAX_CHARS),
115 ).toBe(true);
116 expect(crResult.chunks.reduce((sum, chunk) => sum + chunk.lines, 0)).toBe(
117 lfResult.chunks.reduce((sum, chunk) => sum + chunk.lines, 0),
118 );
119 expect(joinMarkdownChunks(crResult.chunks)).toBe(cr);
120 const rendered = unified().use(remarkParse).use(remarkRehype);
121 expect(toHtml(rendered.runSync(rendered.parse(crResult.chunks[1]!.text)))).toContain(
122 "<h1>x</h1>",
123 );
124
125 const mixed = `---\rtitle: cr\r---\r\r[ref]: /cr-link\r\r- \`\`\`md\r\r [fake]: /wrong\r \`\`\`\r\r\`\`\`md\r# inside fence\r\`\`\`\r\r<details>\r\r${"x".repeat(32 * 1024)}\r\r</details>\r\r# After [ref]\r\n\r\n- [ ] task`;
126 const mixedResult = splitMarkdown(mixed);
127 expect(mixedResult.definitions).toBe("[ref]: /cr-link");
128 expect(mixedResult.chunks.map((chunk) => chunk.text.split(/\r\n?|\n/)[0])).toEqual([
129 "---",
130 "# After [ref]",
131 ]);
132 expect(joinMarkdownChunks(mixedResult.chunks)).toBe(mixed);
133 const secondChunk = withMarkdownDefinitions(
134 mixedResult.chunks[1]!.text,
135 mixedResult.definitions,
136 );
137 const list = unified()
138 .use(remarkParse)
139 .use(remarkGfm)
140 .parse(secondChunk)
141 .children.find((node) => node.type === "list");
142 const marker = taskListMarkerOffset(secondChunk, list!.position!.start.offset!);
143 const secondStart = mixedResult.chunks[0]!.text.length + 1;
144 expect(secondStart + marker! - (mixedResult.definitions.length + 2)).toBe(mixed.indexOf("[ ]"));
145 });
146
147 it("keeps HTML blocks and display math open across blank lines", () => {
148 const text = [
149 "<!--",
150 "",
151 "# hidden",
152 "-->",
153 "",
154 "$$",
155 "",
156 "Inside math",
157 "$$",
158 "",
159 "<pre>",
160 "",
161 "Preformatted",
162 "</pre>",
163 "",
164 "<!-- one line -->",
165 "",
166 "<div>",
167 "# literal",
168 "</div>",
169 "",
170 '<p class="lead">text',
171 "# literal",
172 "</p>",
173 "",
174 '<span class="box">',
175 "# literal",
176 "</span>",
177 "",
178 "<details>",
179 "<summary>Answer</summary>",
180 "",
181 "Inside details",
182 "",
183 "</details>",
184 "",
185 "<table><tr><td>",
186 "",
187 "```ts",
188 "inside a cell",
189 "```",
190 "",
191 "</td></tr></table>",
192 "",
193 '<ol start="10">',
194 "",
195 "<li>one</li>",
196 "",
197 "<li>two</li>",
198 "",
199 "</ol>",
200 "",
201 "```html",
202 "<details>",
203 "```",
204 "",
205 "after",
206 ].join("\n");
207 expect(starts(text)).toEqual(["<!--", "```html", "after"]);
208 const multiline = [
209 "<details",
210 ' class="faq"><!-- </details> -->',
211 "",
212 "Inside details",
213 "",
214 "</details>",
215 "",
216 "after",
217 ].join("\n");
218 expect(starts(multiline)).toEqual(["<details", "after"]);
219 const unclosed = ["<details>", "", "x".repeat(32 * 1024), "", "after"].join("\n");
220 expect(starts(unclosed)).toEqual(["<details>", "after"]);
221 const head = ["<details>", "", "a".repeat(8 * 1024), "", ""].join("\n");
222 const longLine = "x".repeat(LARGE_MARKDOWN_CHUNK_MAX_CHARS - head.length);
223 expect(starts(head + longLine)).toEqual(["<details>"]);
224 expect(starts(`${head}${longLine}x`)).toEqual(["<details>", `${longLine}x`]);
225 expect(starts(`${head}\`\`\`json\n${longLine}\n\`\`\`\n\n</details>`)).toEqual([
226 "<details>",
227 "```json",
228 ]);
229 });
230
231 it("treats an autolink or inline HTML line as a paragraph, so a following fence still opens", () => {
232 const text = [
233 "<https://example.com>",
234 "```md",
235 "",
236 "# literal",
237 "```",
238 "",
239 "<b>bold</b> text",
240 "```md",
241 "",
242 "# literal",
243 "```",
244 "",
245 "after",
246 ].join("\n");
247 expect(starts(text)).toEqual(["<https://example.com>", "after"]);
248 });
249
250 it("waits for the target size before cutting", () => {
251 const text = ["# a", "", "b", "", "# c", "", "d"].join("\n");
252 expect(splitLargeMarkdown(text, 6).map((chunk) => chunk.text)).toEqual([
253 "# a\n\nb\n",
254 "# c\n\nd",
255 ]);
256 });
257
258 it("keeps the complete sample fence before a later oversized source chunk", () => {
259 const example = ["```md", "Sample Markdown", "", "# Sample heading", "```"].join("\n");
260 const preview = ["x".repeat(4200), "<span>", example, "More prose", "<span>"].join("\n");
261 const oversized = "# Appendix\n" + "[link](/example) ".repeat(11_000);
262 const { chunks } = splitMarkdown(preview + "\n" + oversized);
263 expect(chunks.map((chunk) => chunk.text)).toEqual([preview, oversized]);
264 });
265
266 it.each(["===", "---", "***"])(
267 "keeps HTML together after a long paragraph and %s",
268 (boundary) => {
269 const text = ["x".repeat(9000), boundary, "<span>", "# literal"].join("\n");
270 expect(splitMarkdown(text).chunks.map((chunk) => chunk.text)).toEqual([text]);
271 },
272 );
273
274 it.each([
275 ["a fence", "```md", "```"],
276 ["an HTML comment", "<!--", "-->"],
277 ["display math", "$$", "$$"],
278 ])("keeps %s intact after an ambiguous standalone tag", (_, open, close) => {
279 const block = [open, "Sample Markdown", "", "# Sample heading", close].join("\n");
280 const preview = ["x".repeat(9000), "<span>", block].join("\n");
281 expect(splitMarkdown(preview).chunks.map((chunk) => chunk.text)).toEqual([preview]);
282 });
283
284 it("preserves an oversized ambiguous region for source display", () => {
285 const oversized = ["x".repeat(LARGE_MARKDOWN_CHUNK_MAX_CHARS), "<span>", "# Heading"].join(
286 "\n",
287 );
288 const next = "# Next";
289 const text = oversized + "\n\n" + next;
290 expect(splitMarkdown(text).chunks.map((chunk) => chunk.text)).toEqual([oversized + "\n", next]);
291 });
292
293 it.each([
294 ["multiline math with backticks", ["$$", "```", "$$", " # Heading"]],
295 ["single-line display math", ["$$x$$"]],
296 ])("keeps standalone HTML intact after %s", (_, math) => {
297 const text = ["x".repeat(4200), "<span>", ...math, "<span>", "# literal"].join("\n");
298 expect(splitMarkdown(text).chunks.map((chunk) => chunk.text)).toEqual([text]);
299 });
300
301 it("can cut at a heading after a tag in a lazy quote continuation", () => {
302 const quote = ["> " + "x".repeat(4200), "continued", "<span>"].join("\n");
303 const heading = "# Next";
304 expect(splitMarkdown(quote + "\n" + heading).chunks.map((chunk) => chunk.text)).toEqual([
305 quote,
306 heading,
307 ]);
308 });
309
310 it("keeps leading frontmatter in the first piece", () => {
311 const text = ["---", "title: x", "", "# not a heading", "---", "", "# Heading"].join("\n");
312 expect(starts(text)).toEqual(["---", "# Heading"]);
313 });
314
315 it("cuts after a leading horizontal rule with no frontmatter closer", () => {
316 const md =
317 "---\n\n" +
318 Array.from({ length: 300 }, (_, i) => `## Part ${i}\n${"a".repeat(450)}`).join("\n\n");
319 const { chunks } = splitMarkdown(md);
320 expect(chunks.length).toBeGreaterThan(1);
321 expect(chunks.every((chunk) => chunk.text.length <= LARGE_MARKDOWN_CHUNK_MAX_CHARS)).toBe(true);
322 expect(chunks.map((chunk) => chunk.text).join("\n")).toBe(md);
323 });
324
325 it.each([
326 ["one space", " # References"],
327 ["two spaces", " ### References"],
328 ["three spaces", " ###### References"],
329 ])("collects definitions after headings indented by %s without cutting there", (_, heading) => {
330 const intro = "[Release notes][release]\n";
331 const definition = "[release]: /releases";
332 const appendix = ["## Appendix", heading, definition].join("\n");
333 const result = splitMarkdown(`${intro}\n${appendix}`, 1);
334
335 expect(result.definitions).toBe(definition);
336 expect(result.chunks.map((chunk) => chunk.text)).toEqual([intro, appendix]);
337 });
338
339 it("collects definitions immediately after equals-sign Setext headings", () => {
340 const text = `Read [guide]. ${"filler ".repeat(600)}\n\nNotes\n===\n[guide]: https://example.com/guide\n`;
341 const result = splitMarkdown(text);
342
343 expect(result.chunks.length).toBeGreaterThan(1);
344 expect(result.definitions).toBe("[guide]: https://example.com/guide");
345 });
346
347 it("resumes Markdown after a standalone HTML block following a long Setext heading", () => {
348 const intro = ["x".repeat(9000), "===", "<span>", "```", ""].join("\n");
349 const appendix = "# Appendix\n[guide]: /guide";
350 const result = splitMarkdown(`${intro}\n${appendix}`);
351
352 expect(result.chunks.map((chunk) => chunk.text)).toEqual([intro, appendix]);
353 expect(result.definitions).toBe("[guide]: /guide");
354 });
355
356 it("collects definitions after Setext underlines only when they end a paragraph", () => {
357 const cases = [
358 "Notes\n=\n[s1]: /single-eq",
359 "Line 1\nLine 2\n === \n[s2]: /multiline-eq",
360 "Subheading\n--\n[s3]: /double-dash",
361 "Heading\n--- | ---\n===\n[s4]: /mismatched-table-header",
362 "- item\n\n Notes\n===\n[s5]: /after-list-blank",
363 "Notes\n===\n===\n[n1]: /second-eq-is-paragraph",
364 "Notes\n ===\n[n2]: /indented-underline",
365 "> quote\nlazy\n===\n[n3]: /in-blockquote",
366 "- item\n===\n[n4]: /in-list",
367 "- item\n\n sub\n===\n[n5]: /in-loose-list",
368 " code\n===\n[n6]: /after-indented-code",
369 "a | b\n--- | ---\n===\n[n7]: /in-table",
370 "<!-- comment -->\n===\n[n8]: /after-html-comment",
371 ].join("\n\n");
372
373 expect(splitMarkdown(cases).definitions).toBe(
374 [
375 "[s1]: /single-eq",
376 "[s2]: /multiline-eq",
377 "[s3]: /double-dash",
378 "[s4]: /mismatched-table-header",
379 "[s5]: /after-list-blank",
380 ].join("\n"),
381 );
382 });
383
384 it.each([
385 ["an ordered item whose content starts farther right", "10. Item\n\n", ""],
386 ["an item padded to the next tab stop", "-\tItem\n\n", ""],
387 ["a blockquote that ends the list", "- Item\n> quote\n", ""],
388 ["an HTML comment that ends the list", "- Item\n<!-- note -->\n", ""],
389 ["an HTML block that ends the list", "- Item\n<div>top level</div>\n\n", ""],
390 ["a math block that ends the list", "- Item\n$$\nx\n$$\n", ""],
391 ["an indented thematic break", " - - -\n", ""],
392 ["an empty list item", "-\n\n", " "],
393 ["an empty list item with trailing spaces", "- \n\n", " "],
394 ["an empty list item followed by dedented prose", "-\nfoo\n", " "],
395 ])("collects definitions after a fence following %s", (_, beforeFence, definitionIndent) => {
396 const definition = "[ref]: /target";
397 const text = beforeFence + " ```sh\n example\n ```\n" + definitionIndent + definition;
398 expect(splitMarkdown(text).definitions).toBe(definition);
399 });
400
401 it("keeps list sample definitions literal and retains outside definitions", () => {
402 for (const listFence of [
403 "- ```md\n\n [fake]: /wrong\n ```",
404 "-\t```md\n\n [fake]: /wrong\n ```",
405 "* ````md\n ```\n\n [fake]: /wrong\n ````",
406 "2. ~~~md\n\n [fake]: /wrong\n ~~~",
407 "1. First\n2. ```md\n\n [fake]: /wrong\n ```",
408 "1.\tFirst\n2. ~~~md\n\n [fake]: /wrong\n ~~~",
409 "1. First\n\n continuation\n2. ~~~md\n\n [fake]: /wrong\n ~~~",
410 "1. First\n - nested\n\n outer continuation\n2. ~~~md\n\n [fake]: /wrong\n ~~~",
411 "1. First\nlazy continuation\n2. ```md\n\n [fake]: /wrong\n ```",
412 "1. --\nlazy continuation\n2. ~~~md\n\n [fake]: /wrong\n ~~~",
413 "+\n2. ~~~md\n\n [fake]: /wrong\n ~~~",
414 "1. First\n2.\n3. ~~~md\n\n [fake]: /wrong\n ~~~",
415 "- ```md\n\tcode\n\n [fake]: /wrong\n ```",
416 ]) {
417 expect(splitMarkdown(`${listFence}\n\n[fake]`).definitions).toBe("");
418 }
419 // "2." cannot interrupt a paragraph, and a less-indented line ends the list item's fence.
420 expect(splitMarkdown("Text\n2. ```md\n\n [real]: /right\n\n[real]").definitions).toBe(
421 "[real]: /right",
422 );
423 expect(splitMarkdown("- item\n 2. ~~~md\n[fake]: /wrong\n\n[fake]").definitions).toBe("");
424 for (const text of [
425 "- item\n<pre></pre>\nparagraph\n2. ~~~md\n\n [real]: /right\n\n[real]",
426 "- item\n<!-- comment -->\nparagraph\n2. ~~~md\n\n [real]: /right\n\n[real]",
427 "- item\n> quote\nparagraph\n2. ~~~md\n\n [real]: /right\n\n[real]",
428 "1. First\n\nparagraph\n2. ~~~md\n\n [real]: /right\n\n[real]",
429 "1. First\n --\nparagraph\n2. ~~~md\n\n [real]: /right\n\n[real]",
430 "paragraph\n+\n2. ~~~md\n\n [real]: /right\n\n[real]",
431 "1. ```md\n x\n ```\nparagraph\n2. ~~~md\n\n [real]: /right\n\n[real]",
432 "123. ~~~\n\t\tcode\n ~~~\n[real]: /right\n\n[real]",
433 "1.\t```md\n\t```\n[real]: /right\n\n[real]",
434 ]) {
435 const result = splitMarkdown(text, 1);
436 expect(result.definitions).toBe("[real]: /right");
437 expect(result.chunks.map((chunk) => chunk.text).join("\n")).toBe(text);
438 }
439 expect(splitMarkdown("- ```md\n\n [fake]: /wrong\n[real]: /right").definitions).toBe(
440 "[real]: /right",
441 );
442 const multilineAfterListFence =
443 "- ```md\n\n [fake]:\n /wrong\n ```\n[real]:\n /right\n\n[fake] [real]";
444 expect(splitMarkdown(multilineAfterListFence, 1).definitions).toBe("[real]:\n /right");
445 });
446
447 it.each([
448 ["nested markers on one line", "- - ```\n code\n ```"],
449 ["a line of many nested markers", "- ".repeat(70_000) + "x"],
450 ["a heading in a list item", "- # Heading\n 2. Item\n ```\n code\n ```"],
451 ["a lazy ordered marker", "- outer\n - inner\n2. lazy\n ```\n ```"],
452 ])("collects a list item definition after %s", (_, list) => {
453 const definition = "[ref]: /target";
454 expect(splitMarkdown(`${list}\n\n ${definition}`).definitions).toBe(definition);
455 });
456
457 it.each([
458 ["after a list fence", ["- Item", " ```", " code", "```", "[ref]: /fake", "```"]],
459 ["after a paragraph", ["Paragraph", "2. continuation", " ```", "[ref]: /fake", " ```"]],
460 [
461 "in a parent item after a nested item",
462 ["- outer", " - inner", " ```", " ```", " [ref]: /fake", " ```"],
463 ],
464 ])("keeps definitions inside a top-level fence %s literal", (_, lines) => {
465 expect(splitMarkdown(lines.join("\n")).definitions).toBe("");
466 });
467
468 it.each(["", " ", " ", " "])(
469 "collects link definitions outside code with fence indent %j",
470 (indent) => {
471 const text = [
472 "[![badge][b]][site]",
473 "",
474 "```md",
475 "[fake]: /not-a-definition",
476 "```",
477 "",
478 "Paragraph",
479 "[inline]: /continues-the-paragraph",
480 "",
481 "[site]: https://example.com",
482 "[b]: https://example.com/badge.svg 'Badge'",
483 "[^note]: a footnote",
484 "",
485 '[x]: /url "title" is paragraph text',
486 "",
487 "# Heading",
488 "[h]: /after-heading",
489 "",
490 "---",
491 "[t]: /after-break",
492 "",
493 "===",
494 "[p]: /paragraph-text",
495 "",
496 `${indent}\`\`\`sh`,
497 "npm install",
498 `${indent}\`\`\``,
499 "[fence]: /after-fence",
500 "~~~",
501 "~~~",
502 "Text after a fence",
503 "[q]: /continues-the-paragraph",
504 "",
505 "$$",
506 "x",
507 "$$ trailing",
508 "[math]: /inside-math",
509 "",
510 "<!-->",
511 "```",
512 "-->",
513 "```",
514 "[comment]: /after-a-closed-comment",
515 "```",
516 "[code]: /inside-a-fence-after-a-comment",
517 "```",
518 "",
519 "<!-- Links",
520 "[hidden]: /inside-a-comment",
521 "-->",
522 "[html]: /after-an-html-block",
523 "",
524 "<pre></pre>",
525 "[pre]: /after-a-one-line-html-block",
526 "",
527 "- ```md",
528 " ~~~",
529 " ~~~",
530 " [list]: /inside-a-list-fence",
531 " ```",
532 ].join("\n");
533 expect(splitMarkdown(text).definitions).toBe(
534 "[site]: https://example.com\n[b]: https://example.com/badge.svg 'Badge'\n[h]: /after-heading\n[t]: /after-break\n[fence]: /after-fence\n[comment]: /after-a-closed-comment\n[html]: /after-an-html-block\n[pre]: /after-a-one-line-html-block",
535 );
536 const frontmatter = ["---", "title: x", "...", "[fm]: /after-frontmatter", "", "# A"];
537 expect(splitMarkdown(frontmatter.join("\n")).definitions).toBe("[fm]: /after-frontmatter");
538 const unclosed = ["---", ...Array<string>(1000).fill("text"), "[u]: /paragraph-text"];
539 expect(splitMarkdown(unclosed.join("\n")).definitions).toBe("");
540 expect(splitMarkdown("---\n[rule]: /after-leading-rule\n\n# A").definitions).toBe(
541 "[rule]: /after-leading-rule",
542 );
543 const unbalanced = [
544 "[x]: /docs/example)",
545 "[after]: /continues-paragraph",
546 "",
547 "[open]: /docs/example(",
548 "",
549 "[bs]: /docs/example\\\\)",
550 "",
551 "[balanced]: /docs/example(a(b))",
552 "[escaped]: /docs/example\\)",
553 "[angle]: </docs/example)>",
554 ];
555 expect(splitMarkdown(unbalanced.join("\n")).definitions).toBe(
556 "[balanced]: /docs/example(a(b))\n[escaped]: /docs/example\\)\n[angle]: </docs/example)>",
557 );
558 },
559 );
560});
561
562describe("withMarkdownDefinitions", () => {
563 const html = (text: string) => {
564 const processor = unified().use(remarkParse).use(remarkRehype);
565 return toHtml(processor.runSync(processor.parse(text)));
566 };
567
568 it("keeps the first document definition ahead of later chunk definitions", () => {
569 const text = "[id]: /first\n\n" + "x".repeat(4100) + "\n\n# Next\n[id]: /later\n\n[id]";
570 const { chunks, definitions } = splitMarkdown(text);
571 expect(html(text)).toContain('href="/first"');
572 expect(chunks).toHaveLength(2);
573 expect(html(withMarkdownDefinitions(chunks[1]!.text, definitions))).toContain('href="/first"');
574 expect(chunks.map((chunk) => chunk.text).join("\n")).toBe(text);
575 });
576
577 it.each([
578 ["a wrapped label with an inline destination", "[release\nnotes]: /first", "/first", ""],
579 ["a wrapped label with a next-line destination", "[release\nnotes]:\n /first", "/first", ""],
580 [
581 "a title on the next line of the preceding definition",
582 '[other]: /other\n "Other"\n[release notes]: /first',
583 "/first",
584 "",
585 ],
586 [
587 "a title starting on the destination line",
588 '[release notes]: /first "First\n release"',
589 "/first",
590 'title="First\nrelease"',
591 ],
592 [
593 "a destination ending in a nonbreaking space",
594 "[release notes]:\n /first\u00a0",
595 "/first%C2%A0",
596 "",
597 ],
598 ])("preserves the first reference with %s", (_, first, href, title) => {
599 const text = `${first}\n\n${"x".repeat(4100)}\n\n# Next\n[release notes]: /later\n\n[Release][release notes]`;
600 const { chunks, definitions } = splitMarkdown(text);
601 expect(chunks).toHaveLength(2);
602 const rendered = html(withMarkdownDefinitions(chunks[1]!.text, definitions));
603 expect(rendered).toContain(`href="${href}"`);
604 if (title) expect(rendered).toContain(title);
605 });
606
607 it("shares a wrapped label at the Markdown length limit with an escaped bracket", () => {
608 const definition = `[${"a".repeat(995)}\\]\nct]: /first`;
609 expect(splitMarkdown(definition).definitions).toBe(definition);
610 });
611
612 it("leaves oversized titles with their source definitions", () => {
613 const title = "t".repeat(16 * 1024);
614 const text = `[id]\n\n[id]:\n /first\n "${title}"\n\n# Next\n[ID]: /later\n\n[id]`;
615 const { chunks, definitions } = splitMarkdown(text);
616 expect(chunks).toHaveLength(2);
617 const first = html(withMarkdownDefinitions(chunks[0]!.text, definitions));
618 expect(first).toContain('href="/first"');
619 expect(first).toContain(`title="${title}"`);
620 });
621
622 it.each(["", '" trailing text', '\\"'])(
623 "shares a complete definition before a long quote-led paragraph ending in %j",
624 (suffix) => {
625 const text = `[id]:\n /first\n "${"x".repeat(16 * 1024)}${suffix}\n\n# Next\n[id]: /later\n\n[id]`;
626 const { chunks, definitions } = splitMarkdown(text);
627 expect(chunks).toHaveLength(2);
628 const rendered = html(withMarkdownDefinitions(chunks[1]!.text, definitions));
629 expect(rendered).toContain('href="/first"');
630 },
631 );
632
633 it.each([
634 ["inline links", "[a](/x)".repeat(2000), "\n\n", 64],
635 ["link-like text separated by thematic breaks", "[note] text\n***", "\n", 2000],
636 ["invalid definitions separated by thematic breaks", "[note]: /invalid)\n***", "\n", 2000],
637 ])("keeps long runs of %s out of shared definitions", (_, block, separator, count) => {
638 const text = Array.from({ length: count }, () => block).join(separator);
639 const { chunks, definitions } = splitMarkdown(text);
640 expect(definitions).toBe("");
641 expect(chunks.map((chunk) => chunk.text).join("\n")).toBe(text);
642 });
643
644 it("keeps a display math opener and its contents out of shared definitions", () => {
645 const text = "[actual]\n\n[unused]:\n$$\n\n[actual]: /wrong\n\n$$\n\n[actual]: /right";
646 const { chunks, definitions } = splitMarkdown(text, 1);
647 expect(html(withMarkdownDefinitions(chunks[0]!.text, definitions))).toContain('href="/right"');
648 expect(definitions).toBe("[actual]: /right");
649 expect(chunks.map((chunk) => chunk.text).join("\n")).toBe(text);
650 });
651
652 it("collects a long run of titled references within the shared definition budget", () => {
653 const references = Array.from({ length: 2000 }, (_, index) => `[r${index}]:\n /url "Title"`);
654 const source = references.join("\n");
655 const { definitions } = splitMarkdown(source);
656 expect(definitions).toBe(source.slice(0, definitions.length));
657 expect(definitions).toContain(references[500]);
658 expect(definitions.length).toBeLessThanOrEqual(16 * 1024);
659 expect(definitions).not.toContain("[r1999]");
660 });
661
662 it("keeps frontmatter hidden and task offsets shifted by exactly the prefix", () => {
663 const text = "\uFEFF---\r\ntitle: hidden\r\n---\r\n\r\n[ref]: /x\r\n\r\n- [ ] task";
664 const { definitions } = splitMarkdown(text);
665 const rendered = withMarkdownDefinitions(text, definitions);
666 expect(html(rendered)).not.toContain("hidden");
667 const list = unified()
668 .use(remarkParse)
669 .use(remarkGfm)
670 .parse(rendered)
671 .children.find((node) => node.type === "list");
672 const marker = taskListMarkerOffset(rendered, list!.position!.start.offset!);
673 expect(marker! - (definitions.length + 2)).toBe(text.indexOf("[ ]"));
674 });
675
676 it("keeps shared definitions out of a trailing unclosed code fence", () => {
677 const text = "[ref]: /dst\n\n```text\nshown";
678 const { definitions } = splitMarkdown(text);
679 expect(html(withMarkdownDefinitions(text, definitions))).toBe(html(text));
680 });
681});
682
683describe("chunked Markdown footnotes", () => {
684 it.each([{ renderedChunkSize: LARGE_MARKDOWN_CHUNK_MAX_CHARS }, { renderedChunkSize: 0 }])(
685 "counts only rendered references with a $renderedChunkSize-character sibling",
686 ({ renderedChunkSize }) => {
687 const ref = "[^note]";
688 const rendered = renderedChunkSize
689 ? `${"a".repeat(renderedChunkSize - ref.length - 1)}${ref}\n\n`
690 : "";
691 const oversized = `${"b".repeat(LARGE_MARKDOWN_CHUNK_MAX_CHARS - ref.length)}${ref}\n\n`;
692 const definition = "[^note]: Shared explanation.";
693 const { definitions, footnotes } = splitMarkdown(
694 `${rendered}${oversized}# Appendix\n\n${definition}`,
695 1,
696 );
697 const section = buildMarkdownFootnotesSection(definitions, footnotes);
698 expect(section?.text ?? null).toBe(renderedChunkSize ? `${ref}\n\n${definition}` : null);
699 },
700 );
701
702 it("keeps footnotes undefined for single-chunk files and unreferenced definitions", () => {
703 const small = "A footnote reference.[^1]\n\n[^1]: The footnote text.\n";
704 expect(splitMarkdown(small).footnotes).toBeUndefined();
705
706 const unreferenced = [
707 "Intro paragraph.",
708 "",
709 ...Array.from({ length: 40 }, (_, i) => `Paragraph ${i}. ${"Lorem ipsum. ".repeat(12)}`),
710 "",
711 "[^unused]: Never referenced.",
712 ].join("\n");
713 const split = splitMarkdown(unreferenced);
714 expect(split.chunks.length).toBeGreaterThan(1);
715 expect(split.footnotes).toBeUndefined();
716 });
717
718 it("collects footnote definitions and per-chunk references across pieces", () => {
719 const paragraphs = Array.from(
720 { length: 60 },
721 (_, i) =>
722 `Paragraph ${i}. ${"Lorem ipsum dolor sit amet, consectetur adipiscing elit. ".repeat(2)}`,
723 );
724 const text = [
725 "A footnote reference.[^1] Escaped \\[^1], code `[^1]`, [link](https://example.com/[^1]).",
726 "",
727 ...paragraphs.slice(0, 35).flatMap((p) => [p, ""]),
728 "Second ref[^note] and repeat[^1].",
729 "",
730 ...paragraphs.slice(35).flatMap((p) => [p, ""]),
731 "```md",
732 "[^fake]: inside code fence",
733 "```",
734 "",
735 "[^1]: The footnote text.",
736 " Second paragraph of footnote 1.",
737 "",
738 "[^note]: First note definition.",
739 "",
740 "[^note]: Duplicate ignored.",
741 ].join("\n");
742
743 const { chunks, definitions, footnotes } = splitMarkdown(text);
744 expect(chunks.length).toBeGreaterThan(1);
745 expect(chunks.map((chunk) => chunk.text).join("\n")).toBe(text);
746 expect(footnotes).toBeDefined();
747 expect(footnotes!.stubs).toBe("[^1]: .\n[^note]: .");
748 expect(footnotes!.definitions).toBe(
749 "[^1]: The footnote text.\n Second paragraph of footnote 1.\n\n[^note]: First note definition.",
750 );
751 expect(footnotes!.chunkRefs.flat()).toEqual(["1", "note", "1"]);
752
753 const firstRefChunk = footnotes!.chunkRefs.findIndex((refs) => refs.length > 0);
754 const secondRefChunk = footnotes!.chunkRefs.findIndex(
755 (refs, index) => index > firstRefChunk && refs.length > 0,
756 );
757 expect(firstRefChunk).toBe(0);
758 expect(secondRefChunk).toBeGreaterThan(0);
759
760 const preparedFirst = prepareMarkdownChunk(
761 chunks[firstRefChunk]!.text,
762 firstRefChunk,
763 definitions,
764 footnotes,
765 );
766 expect(preparedFirst.footnotesMode).toBe("omit");
767
768 const preparedSecond = prepareMarkdownChunk(
769 chunks[secondRefChunk]!.text,
770 secondRefChunk,
771 definitions,
772 footnotes,
773 );
774 expect(preparedSecond.footnotesMode).toBe("omit-seeded");
775 expect(preparedSecond.text).toContain("[^1]\n\n");
776
777 const section = buildMarkdownFootnotesSection(definitions, footnotes)?.text;
778 expect(section).toContain("[^1] [^note] [^1]");
779 expect(section).toContain("Second paragraph of footnote 1.");
780 expect(section).not.toContain("Duplicate ignored.");
781
782 expect(findFootnoteRefChunkIndex(footnotes!, 1, 1)).toBe(firstRefChunk);
783 expect(findFootnoteRefChunkIndex(footnotes!, 2, 1)).toBe(secondRefChunk);
784 expect(findFootnoteRefChunkIndex(footnotes!, 1, 2)).toBe(secondRefChunk);
785 expect(findFootnoteRefChunkIndex(footnotes!, 1, 3)).toBeNull();
786 });
787
788 it("keeps task list offsets exact when footnote seed prefix is prepended", () => {
789 const filler = Array.from({ length: 40 }, (_, i) => `Section ${i} ${"x".repeat(120)}`).join(
790 "\n\n",
791 );
792 const text = [
793 "[site]: https://example.com",
794 "",
795 "Lead[^1] with [site].",
796 "",
797 filler,
798 "",
799 "- [ ] task in chunk with seeded ref[^1]",
800 "",
801 "[^1]: Footnote body.",
802 ].join("\n");
803 const { chunks, definitions, footnotes } = splitMarkdown(text);
804 const taskChunkIndex = chunks.findIndex((chunk) => chunk.text.includes("- [ ] task"));
805 expect(taskChunkIndex).toBeGreaterThan(0);
806 const prepared = prepareMarkdownChunk(
807 chunks[taskChunkIndex]!.text,
808 taskChunkIndex,
809 definitions,
810 footnotes,
811 );
812 const list = unified()
813 .use(remarkParse)
814 .use(remarkGfm)
815 .parse(prepared.text)
816 .children.find((node) => node.type === "list");
817 const marker = taskListMarkerOffset(prepared.text, list!.position!.start.offset!);
818 let chunkStart = 0;
819 for (let i = 0; i < taskChunkIndex; i++) {
820 chunkStart += chunks[i]!.text.length + 1;
821 }
822 expect(chunkStart + marker! - prepared.offsetShift).toBe(text.indexOf("[ ]"));
823 });
824
825 it("counts references followed by ':' or '(', skips inline math, and stays linear", () => {
826 const filler = Array.from(
827 { length: 40 },
828 (_, i) => `Paragraph ${i}. ${"word ".repeat(25)}`,
829 ).join("\n\n");
830 const text = [
831 "As noted[^a]: see this. Quote.[^b](emphasis added) and [^c](https://example.com). Math $x[^a]y$.",
832 "",
833 // Unclosed marks rescanned from each opener took seconds; nested quotes took minutes.
834 `${"> ".repeat(40)}x[^b]: t`,
835 "",
836 `[^c] ${"](( ".repeat(20000)}`,
837 "",
838 `[^a] ${"$x ".repeat(20000)}`,
839 "",
840 `[^c] ${"<!-- ](<".repeat(16_000)}`,
841 "",
842 "Literal ](see[^b]) but [link](x[^a]) is a destination.",
843 "",
844 filler,
845 "",
846 "[^a]: First note.",
847 "[^b]: Second note.",
848 "[^c]: Third note.",
849 ].join("\n");
850
851 const { chunks, footnotes } = splitMarkdown(text);
852 expect(chunks.length).toBeGreaterThan(1);
853 expect(footnotes?.chunkRefs.flat()).toEqual(["a", "b", "c", "b", "c", "a", "c", "b"]);
854 });
855
856 it("falls back when footnote definitions exceed the shared cap", () => {
857 const sections = Array.from(
858 { length: 400 },
859 (_, i) => `Paragraph ${i} referencing [^f${i}].\n\n[^f${i}]: ${"note text ".repeat(20)}`,
860 ).join("\n\n");
861 const split = splitMarkdown(sections);
862 expect(split.chunks.length).toBeGreaterThan(1);
863 expect(split.footnotes).toBeUndefined();
864 });
865
866 it("separates stub footnote definitions from a chunk starting with indented code", () => {
867 const filler = Array.from({ length: 40 }, (_, i) => `Section ${i} ${"x".repeat(120)}`).join(
868 "\n\n",
869 );
870 const text = [
871 " indented()",
872 "",
873 "Ref[^1].",
874 "",
875 filler,
876 "",
877 " code[^a]",
878 "",
879 "- item",
880 "",
881 " item text[^2]",
882 "",
883 "[^1]: Footnote body.",
884 "",
885 "[^a]: Literal in code.",
886 "",
887 "[^2]: In a list item.",
888 ].join("\n");
889
890 const { chunks, definitions, footnotes } = splitMarkdown(text);
891 const prepared = prepareMarkdownChunk(chunks[0]!.text, 0, definitions, footnotes);
892 expect(prepared.footnotesMode).toBe("omit");
893 expect(prepared.text).toContain("<!-- -->\n\n indented()");
894 expect(footnotes?.chunkRefs.flat()).toEqual(["1", "2"]);
895 // The unreferenced `[^a]` definition is dropped when the section renders.
896 const section = buildMarkdownFootnotesSection(definitions, footnotes)!.text;
897 expect(section.startsWith("[^1] [^2]\n\n")).toBe(true);
898 });
899});