Open History to see the last commit
1import { describe, expect, it } from "vite-plus/test";
2import { unified } from "unified";
3import remarkParse from "remark-parse";
4import remarkGfm from "remark-gfm";
5import type { Root, RootContent } from "mdast";
6import { ENRICHED_INLINE_FILE_LINK_REGEX } from "./enrichedLinkPresentation";
7import {
8 markdownForNativeRendering,
9 markdownWithInlineFileLinks,
10 parseMarkdownDocument,
11 markdownWithHtml,
12} from "./markdownDocument";
13
14const rewrite = (markdown: string) =>
15 markdownWithInlineFileLinks(markdown, ENRICHED_INLINE_FILE_LINK_REGEX);
16
17describe("inline code that names a file", () => {
18 it.each([
19 [
20 "file links",
21 "See `src/math.ts:2`, `C:\\repo\\a.ts`, `./src/a©.ts`, and [`./README.md`](readme).",
22 ],
23 [
24 "tables",
25 "Intro `src/math.ts:2`\n| `./README.md` | Fit |\n|---|---|\n| `./a.ts` | A |\n\nMore\n| a |\n|---|\n| b |",
26 ],
27 ["escaped pipe in file header", "Intro text\n| `./a\\|b.ts` | c |\n|---|---|\n| a | b |"],
28 ["escaped pipe in file body", "Intro text\n| a | c |\n|---|---|\n| `./a\\|b.ts` | b |"],
29 [
30 "escaped pipe after a normal file span",
31 "Intro `./normal.ts`\n| `./a\\|b.ts` | c |\n|---|---|\n| a | b |",
32 ],
33 [
34 "unmatched delimiter before escaped pipe in header",
35 "Intro `./normal.ts`\n| `x``./a\\|b.ts`` | c |\n|---|---|\n|a|b|",
36 ],
37 [
38 "unmatched delimiter before escaped pipe in body",
39 "Intro `./normal.ts`\n| a | c |\n|---|---|\n| `x``./a\\|b.ts`` | b |",
40 ],
41 ["tabbed quote header", ">\tIntro `./a.ts`\n>\t| `./b.ts` | c |\n>\t|---|---|\n>\t| a | b |"],
42 ["lazy quote header", "> Intro\n`./README.md` | file\n> | - | - |\n> | ok | yes |"],
43 ["lazy list header", "- Intro\n`./README.md` | file\n | - | - |\n | ok | yes |"],
44 [
45 "HTML",
46 '<details>\n<summary>Files</summary>\n\nSee `src/math.ts:2`\n| `./README.md` |\n|---|\n| ok |\n<img alt="A & B" src="https://example.com/a.png?a=1&b=2">\n</details>',
47 ],
48 [
49 "nested fences",
50 '> - Example\n> ````md\n> ```ts\n> `src/math.ts:2`\n> <img src="literal.png">\n> | a |\n> |---|\n> ```\n> ````\n\nSee `./README.md`.',
51 ],
52 [
53 "HTML fences",
54 '<details>\n<summary>Example</summary>\n\n````md\n```html\n<img src="literal.png">\n```\n`src/math.ts`\n````\n\nSee `./README.md`\n</details>',
55 ],
56 ])("preserves the two-pass output for every streamed prefix: %s", (_name, fixture) => {
57 for (const ending of ["\n", "\r\n", "\r"]) {
58 const document = fixture.replaceAll("\n", ending);
59 for (let length = 0; length <= document.length; length++) {
60 const prefix = document.slice(0, length);
61 const expected = previousTableBreaks(
62 previousFileLinks(markdownWithHtml(prefix), ENRICHED_INLINE_FILE_LINK_REGEX),
63 );
64 expect(
65 markdownForNativeRendering(prefix, ENRICHED_INLINE_FILE_LINK_REGEX),
66 JSON.stringify(prefix),
67 ).toBe(expected);
68 }
69 }
70 });
71
72 it("becomes a link to the same path", () => {
73 expect(rewrite("See `src/math.ts:2` and `./README.md`.")).toBe(
74 "See [src/math.ts:2](<src/math.ts:2>) and [./README.md](<./README.md>).",
75 );
76 });
77
78 it("keeps commands, identifiers and URLs as code", () => {
79 const markdown = "Run `vp test run`, call `useMemo`, open `https://example.com/a.ts`.";
80 expect(rewrite(markdown)).toBe(markdown);
81 });
82
83 it("leaves fenced code blocks and code already inside a link alone", () => {
84 const markdown = "```\nsrc/math.ts:2\n```\n\n[`src/math.ts`](src/math.ts)";
85 expect(rewrite(markdown)).toBe(markdown);
86 });
87
88 it("links to the exact path when it holds backslashes or ampersands", () => {
89 for (const path of ["C:\\repo\\_private\\file.ts", "./src/a©.ts", "./src/[id].ts"]) {
90 const paragraph = parseMarkdownDocument(rewrite(`\`${path}\``)).children[0];
91 const link = paragraph?.type === "paragraph" ? paragraph.children[0] : undefined;
92 expect(link?.type === "link" && link.url).toBe(path);
93 expect(
94 link?.type === "link" && link.children[0]?.type === "text" && link.children[0].value,
95 ).toBe(path);
96 }
97 });
98});
99
100// Freeze the pre-optimization passes so shared transform regressions cannot change the oracle.
101const parser = unified().use(remarkParse).use(remarkGfm);
102type MarkdownNode = Root | RootContent;
103const INLINE_CODE_SPAN = /`+([^`\r\n]+)`+/g;
104
105function previousFileLinks(markdown: string, fileLink: RegExp): string {
106 if (![...markdown.matchAll(INLINE_CODE_SPAN)].some(([, code]) => fileLink.test(code!.trim())))
107 return markdown;
108 const edits: Array<{ start: number; end: number; content: string }> = [];
109 const visit = (node: MarkdownNode) => {
110 if (node.type === "inlineCode") {
111 const start = node.position?.start.offset;
112 const end = node.position?.end.offset;
113 const escaped = node.value.replace(/[\\[\]&]/g, "\\$&");
114 if (
115 start !== undefined &&
116 end !== undefined &&
117 fileLink.test(node.value) &&
118 !/[<>]/.test(node.value)
119 )
120 edits.push({
121 start,
122 end,
123 content: `[${escaped}](<${escaped}>)`,
124 });
125 } else if (node.type !== "link" && node.type !== "linkReference" && "children" in node)
126 node.children.forEach(visit);
127 };
128 visit(parser.parse(markdown));
129 for (const edit of edits.toReversed())
130 markdown = markdown.slice(0, edit.start) + edit.content + markdown.slice(edit.end);
131 return markdown;
132}
133
134// A delimiter row such as `|---|:--:|`, possibly inside a blockquote or list item.
135function isTableDelimiterRow(line: string): boolean {
136 if (!line.includes("-")) return false;
137 const row = line.replace(/^[ \t>]+/, "").trim();
138 return row
139 .replace(/^\||\|$/g, "")
140 .split("|")
141 .every((cell) => /^:?-+:?$/.test(cell.trim()));
142}
143
144// Cheap pre-check for a delimiter row two lines below text, so most messages skip the parse.
145function mayHaveTableUnderText(markdown: string): boolean {
146 if (!markdown.includes("|")) return false;
147 const lines = markdown.split(/\r\n|\r|\n/);
148 for (let index = 2; index < lines.length; index += 1) {
149 if (isTableDelimiterRow(lines[index]!) && /[^\s>]/.test(lines[index - 2]!)) return true;
150 }
151 return false;
152}
153
154/**
155 * GFM lets a table interrupt a paragraph, but the native parser (md4c) only starts a table
156 * on a paragraph's first line, so a table right under a line of text renders as one
157 * run-on paragraph. Insert the blank line md4c needs before each such table.
158 */
159function previousTableBreaks(markdown: string): string {
160 if (!mayHaveTableUnderText(markdown)) return markdown;
161 const lineStarts: number[] = [];
162 const visit = (node: MarkdownNode) => {
163 if (!("children" in node)) return;
164 node.children.forEach((child, index) => {
165 const previous = node.children[index - 1];
166 const start = child.position?.start;
167 if (
168 child.type === "table" &&
169 previous?.type === "paragraph" &&
170 start?.offset !== undefined &&
171 previous.position?.end.line === start.line - 1
172 )
173 lineStarts.push(
174 Math.max(
175 markdown.lastIndexOf("\n", start.offset - 1),
176 markdown.lastIndexOf("\r", start.offset - 1),
177 ) + 1,
178 );
179 visit(child);
180 });
181 };
182 visit(parser.parse(markdown));
183 for (const lineStart of lineStarts.toReversed()) {
184 // The header row may be a lazy line without its container markers (`>` or list indent),
185 // so copy the delimiter row's markers onto the blank line and the header row.
186 const [, header = "", cells = "", ending = "\n", markers = ""] =
187 /^([ \t>]*)([^\r\n]*)(\r\n|\r|\n)([ \t>]*)/.exec(markdown.slice(lineStart)) ?? [];
188 markdown =
189 markdown.slice(0, lineStart) +
190 `${markers.trimEnd()}${ending}${markers}${cells}` +
191 markdown.slice(lineStart + header.length + cells.length);
192 }
193 return markdown;
194}