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

markdownChunks.test.ts

797 lines28.7 KB

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