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

markdownPipeline.test.ts

714 lines29.7 KB

1import { expect, it } from "vite-plus/test";
2import { type PluggableList, unified } from "unified";
3import rehypeRaw from "rehype-raw";
4import remarkParse from "remark-parse";
5import remarkRehype from "remark-rehype";
6import type { Link, Root, RootContent } from "mdast";
7import {
8 CHAT_MARKDOWN_REHYPE_PLUGINS,
9 CHAT_MARKDOWN_REMARK_PLUGINS,
10 CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
11 remarkAssistantInsights,
12 remarkEnableOrderedListNumbers,
13} from "./markdownPipeline.ts";
14​
15it.each([
16 ["default", CHAT_MARKDOWN_REMARK_PLUGINS],
17 ["with breaks", CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS],
18] as const)("preserves bare URL boundaries (%s)", (_, plugins) => {
19 const processor = unified().use(remarkParse).use(plugins);
20 const shape = (node: Root | RootContent): string => {
21 if (node.type === "text") return node.value;
22 if (node.type === "inlineCode") return `\`${node.value}\``;
23 if (node.type === "code") return `\`\`\`${node.value}\`\`\``;
24 const children = "children" in node ? node.children.map(shape).join("") : "";
25 if (node.type === "link") return `[${children}](${node.url})`;
26 if (node.type === "linkReference") return `[${children}][${node.identifier}]`;
27 if (node.type === "emphasis") return `*${children}*`;
28 if (node.type === "strong") return `**${children}**`;
29 if (node.type === "delete") return `~~${children}~~`;
30 return children;
31 };
32 const link = (url: string) => `[${url}](${/^www\./i.test(url) ? `http://${url}` : url})`;
33 for (const url of [
34 "https://x.com/dimasike_",
35 "http://example.com/name__",
36 "HTTPS://example.com/name_",
37 "https://example.com/a_(b)_",
38 "https://example.com/?name=value_",
39 "https://example.com/#section_",
40 "https://example.com/a_?name=value_#section_",
41 "https://example.com/name~",
42 "https://example.com/name~~",
43 "https://example.com/name_~",
44 "https://example.com/name~_",
45 "https://example.com/name__~~_",
46 "https://example.com/?name=value~",
47 "https://example.com/#section~",
48 "www.example.com/name_",
49 "www.example.com/name~_",
50 "WWW.example.com/name~~",
51 "https://example.com/name-",
52 "https://example.com/name/",
53 "https://example.com/name%5F",
54 "https://example.com/name%7E",
55 ]) {
56 for (const punctuation of ["", ".", ",", "!", "?", ":", ";", ")", "]", '"']) {
57 const markdown = `See ${url}${punctuation} next`;
58 expect(shape(processor.runSync(processor.parse(markdown), markdown) as Root), markdown).toBe(
59 `See ${link(url)}${punctuation} next`,
60 );
61 }
62 }
63 for (const [markdown, expected] of [
64 ["*https://x.com/dimasike_*", `*${link("https://x.com/dimasike_")}*`],
65 ["**https://x.com/dimasike_**", `**${link("https://x.com/dimasike_")}**`],
66 ["_https://x.com/dimasike_", `*${link("https://x.com/dimasike")}*`],
67 ["__https://x.com/dimasike__", `**${link("https://x.com/dimasike")}**`],
68 ["~~https://example.com/name_~~", `~~${link("https://example.com/name_")}~~`],
69 ["~~https://example.com/name~~", `~~${link("https://example.com/name")}~~`],
70 ["~https://example.com/name~", `~~${link("https://example.com/name")}~~`],
71 ["*https://example.com/name~*", `*${link("https://example.com/name~")}*`],
72 ["_https://example.com/name~_", `*${link("https://example.com/name~")}*`],
73 ["[test](https://example.com/name~)", "[test](https://example.com/name~)"],
74 ["[https://x.com/a](https://x.com/a)~_", `${link("https://x.com/a")}~_`],
75 ["<https://x.com/a>~_", `${link("https://x.com/a")}~_`],
76 ["[test][ref]~_\n\n[ref]: https://x.com/a~_", "[test][ref]~_"],
77 ["`https://example.com/name~_`", "`https://example.com/name~_`"],
78 ["```\nhttps://example.com/name~_\n```", "```https://example.com/name~_```"],
79 ["https\\://example.com/name~_", link("https://example.com/name~_")],
80 ["https://example.com/name. _~", `${link("https://example.com/name")}. _~`],
81 ["Mail person@example.com_", "Mail person@example.com_"],
82 ["Mail person@example.com ~_", "Mail [person@example.com](mailto:person@example.com) ~_"],
83 ["[test](https://x.com/dimasike_)", "[test](https://x.com/dimasike_)"],
84 ["[https://x.com/a](https://x.com/a)_", `${link("https://x.com/a")}_`],
85 ["<https://x.com/a>_", `${link("https://x.com/a")}_`],
86 ["[test][ref]_\n\n[ref]: https://x.com/a_", "[test][ref]_"],
87 ["`https://x.com/dimasike_`", "`https://x.com/dimasike_`"],
88 ["```\nhttps://x.com/dimasike_\n```", "```https://x.com/dimasike_```"],
89 ["https://x.com/a. _", `${link("https://x.com/a")}. _`],
90 ["https\\://x.com/dimasike_", link("https://x.com/dimasike_")],
91 ["https://x.com/a\\_", link("https://x.com/a\\_")],
92 ["https://x.com/a&#95;", `${link("https://x.com/a&#95")};`],
93 [
94 "可以看了:**http://localhost:18780**(已重启)。",
95 `可以看了:**${link("http://localhost:18780")}**(已重启)。`,
96 ],
97 ["打开 http://localhost:18780,然后刷新", `打开 ${link("http://localhost:18780")},然后刷新`],
98 ["URL:https://example.com/a。下一句", `URL:${link("https://example.com/a")}。下一句`],
99 ["(预览:http://localhost:18780)", `(预览:${link("http://localhost:18780")})`],
100 [
101 "能打开 http://localhost:3000?见 http://localhost:3001;「www.example.com」",
102 `能打开 ${link("http://localhost:3000")}?见 ${link("http://localhost:3001")};「${link("www.example.com")}」`,
103 ],
104 [
105 "__http://localhost:18780__,*http://localhost:3000*,~~http://localhost:3001~~。",
106 `**${link("http://localhost:18780")}**,*${link("http://localhost:3000")}*,~~${link("http://localhost:3001")}~~。`,
107 ],
108 [
109 "foo**http://localhost:18780**(bar)***http://localhost:3000***。",
110 `foo**${link("http://localhost:18780")}**(bar)***${link("http://localhost:3000")}***。`,
111 ],
112 [
113 "http://a.com。http://b.com,www.c.com、person@example.com。",
114 `${link("http://a.com")}。${link("http://b.com")},${link("www.c.com")}、[person@example.com](mailto:person@example.com)。`,
115 ],
116 [
117 "**http://localhost:18780**(重启)。 https://example.com/a。结束",
118 `**${link("http://localhost:18780")}**(重启)。 ${link("https://example.com/a")}。结束`,
119 ],
120 ["# **http://localhost:3000**,刷新", `**${link("http://localhost:3000")}**,刷新`],
121 [
122 "| a |\n| - |\n| **http://localhost:3000**,刷新 |",
123 `a**${link("http://localhost:3000")}**,刷新`,
124 ],
125 ["www.example.com/preview。下一句", `${link("www.example.com/preview")}。下一句`],
126 ["https://example.com/a_。下一句", `${link("https://example.com/a_")}。下一句`],
127 ["https://example.com/a.,下一句", `${link("https://example.com/a")}.,下一句`],
128 [
129 "https://example.com/search?q=hello,world",
130 `${link("https://example.com/search?q=hello")},world`,
131 ],
132 ["https://example.com/日本語,続き", link("https://example.com/日本語,続き")],
133 [
134 "https://zh.wikipedia.org/wiki/北京(城市)",
135 link("https://zh.wikipedia.org/wiki/北京(城市)"),
136 ],
137 ["https://example.com/a%EF%BC%8Cb", link("https://example.com/a%EF%BC%8Cb")],
138 ["<https://example.com/日本語,続き>", link("https://example.com/日本語,続き")],
139 ["[記事](https://example.com/a,b)", "[記事](https://example.com/a,b)"],
140 ["[http://example.com/a,b](http://example.com/a,b)", link("http://example.com/a,b")],
141 ["`https://example.com/a。次`", "`https://example.com/a。次`"],
142 [
143 "منشور على https://example.com/report، ونسخته",
144 `منشور على ${link("https://example.com/report")}، ونسخته`,
145 ],
146 [
147 "هل يعمل **http://localhost:3000**؟ نعم؛ www.example.com۔",
148 `هل يعمل **${link("http://localhost:3000")}**؟ نعم؛ ${link("www.example.com")}۔`,
149 ],
150 [
151 "https://x.com/a_ https://x.com/b_",
152 `${link("https://x.com/a_")} ${link("https://x.com/b_")}`,
153 ],
154 ] as const) {
155 expect(shape(processor.runSync(processor.parse(markdown), markdown) as Root), markdown).toBe(
156 expected,
157 );
158 }
159 for (const url of ["https://x.com/dimasike_", "www.example.com/name~_"]) {
160 const markdown = `${url}, next`;
161 const boundary = { line: 1, column: url.length + 1, offset: url.length };
162 expect(processor.runSync(processor.parse(markdown), markdown)).toMatchObject({
163 children: [
164 {
165 children: [
166 {
167 type: "link",
168 url: /^www\./i.test(url) ? `http://${url}` : url,
169 position: { end: boundary },
170 children: [{ type: "text", value: url, position: { end: boundary } }],
171 },
172 { type: "text", value: ", next", position: { start: boundary } },
173 ],
174 },
175 ],
176 });
177 }
178});
179​
180it("ends bare URLs at CJK and Arabic punctuation with source positions", () => {
181 const processor = unified().use(remarkParse).use(CHAT_MARKDOWN_REMARK_PLUGINS);
182 const parse = (markdown: string) => processor.runSync(processor.parse(markdown), markdown);
183 const at = (line: number, column: number, offset: number) => ({ line, column, offset });
184 const url = "http://localhost:18780";
185 expect(parse(`第一行\n可以看了:**${url}**(已重启)。`)).toMatchObject({
186 children: [
187 {
188 children: [
189 { type: "text", value: "第一行\n可以看了:", position: { end: at(2, 6, 9) } },
190 {
191 type: "strong",
192 position: { start: at(2, 6, 9), end: at(2, 32, 35) },
193 children: [
194 {
195 type: "link",
196 url,
197 position: { start: at(2, 8, 11), end: at(2, 30, 33) },
198 children: [{ type: "text", value: url, position: { end: at(2, 30, 33) } }],
199 },
200 ],
201 },
202 {
203 type: "text",
204 value: "(已重启)。",
205 position: { start: at(2, 32, 35), end: at(2, 38, 41) },
206 },
207 ],
208 },
209 ],
210 });
211 // Markup the URL swallowed comes back once the URL ends.
212 expect(parse(`打开 ${url},然后运行\`pnpm dev\``)).toMatchObject({
213 children: [
214 {
215 children: [
216 { type: "text", value: "打开 " },
217 { type: "link", url },
218 { type: "text", value: ",然后运行" },
219 { type: "inlineCode", value: "pnpm dev" },
220 ],
221 },
222 ],
223 });
224 // Every URL in one paragraph ends at its mark, with positions on its own line.
225 const lines = Array.from({ length: 300 }, (_, index) => `接口:http://localhost:${index},`);
226 const [paragraph] = (parse(lines.join("\n")) as Root).children;
227 const links =
228 paragraph?.type === "paragraph"
229 ? paragraph.children.filter((node): node is Link => node.type === "link")
230 : [];
231 expect(links.map((node) => node.url)).toEqual(
232 lines.map((_, index) => `http://localhost:${index}`),
233 );
234 const lastLine = lines.slice(0, -1).join("\n").length + 1;
235 expect(links.at(-1)).toMatchObject({
236 position: { start: at(300, 4, lastLine + 3), end: at(300, 24, lastLine + 23) },
237 });
238 // Only a table unescapes `\|` in code, so that cell keeps its parse and the URL is cut.
239 const descendants = (node: Root | RootContent): RootContent[] =>
240 "children" in node
241 ? (node.children as RootContent[]).flatMap((child) => [child, ...descendants(child)])
242 : [];
243 const cell = descendants(parse("| a |\n| - |\n| http://example.com, `a\\|b` |") as Root);
244 expect(cell.flatMap((node) => (node.type === "link" ? [node.url] : []))).toEqual([
245 "http://example.com",
246 ]);
247 expect(cell.flatMap((node) => (node.type === "inlineCode" ? [node.value] : []))).toEqual(["a|b"]);
248 // A task item's checkbox is not part of its paragraph's text.
249 const task = descendants(parse("- [x] http://example.com,刷新") as Root);
250 expect(task.flatMap((node) => (node.type === "text" ? [node.value] : []))).toEqual([
251 "http://example.com",
252 ",刷新",
253 ]);
254 // A list item's indentation stays out of a code span that crosses lines.
255 const code = descendants(parse("- `echo\n hello` http://example.com,结束") as Root);
256 expect(code.flatMap((node) => (node.type === "link" ? [node.url] : []))).toEqual([
257 "http://example.com",
258 ]);
259 expect(code.flatMap((node) => (node.type === "inlineCode" ? [node.value] : []))).toEqual([
260 "echo\nhello",
261 ]);
262 // A list item's continuation line parses the same on its own.
263 expect(parse(`- 第一行\n **${url}**(已重启)`)).toMatchObject({
264 children: [
265 {
266 children: [
267 {
268 children: [
269 {
270 children: [
271 { type: "text", value: "第一行\n" },
272 { type: "strong", children: [{ type: "link", url }] },
273 { type: "text", value: "(已重启)" },
274 ],
275 },
276 ],
277 },
278 ],
279 },
280 ],
281 });
282 // A quote's continuation line does not, so the URL ends and the asterisks stay as text.
283 expect(parse(`> 第一行\n> **${url}**(已重启)`)).toMatchObject({
284 children: [
285 {
286 children: [
287 {
288 children: [
289 { type: "text", value: "第一行\n**" },
290 { type: "link", url, position: { end: at(2, 27, 32) } },
291 { type: "text", value: "**(已重启)", position: { start: at(2, 27, 32) } },
292 ],
293 },
294 ],
295 },
296 ],
297 });
298});
299​
300const insightRule = "─".repeat(20);
301const insightFence = (body: string, wrap = "") =>
302 [`${wrap}★ Insight ${insightRule}${wrap}`, body, `${wrap}${insightRule}${wrap}`].join("\n");
303​
304it.each(["", "`"])("groups %j insight fences while preserving surrounding markdown", (wrap) => {
305 const markdown = [
306 "Before **bold** and [reference][src].",
307 "",
308 insightFence("- Also [reference][src].", wrap),
309 "",
310 "After.",
311 "",
312 '[src]:\n https://example.com\n "Source"',
313 ].join("\n");
314 const processor = unified()
315 .use(remarkParse)
316 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
317 .use(remarkAssistantInsights)
318 .use(remarkRehype)
319 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
320 const tree = processor.runSync(processor.parse(markdown), markdown);
321 expect(
322 tree.children.filter((node) => node.type === "element").map((node) => node.tagName),
323 ).toEqual(["p", "blockquote", "p"]);
324 expect(
325 tree.children.find((node) => node.type === "element" && node.tagName === "blockquote"),
326 ).toMatchObject({ properties: { dataAlert: "insight" } });
327 expect(JSON.stringify(tree).match(/"href":"https:\/\/example.com"/g)).toHaveLength(2);
328 expect(JSON.stringify(tree)).toContain('"tagName":"strong"');
329 expect(JSON.stringify(tree)).not.toContain(insightRule);
330});
331​
332it.each([
333 ["```text", "★ Insight " + insightRule, "literal", insightRule, "```"].join("\n"),
334 ["- ```text", " ★ Insight " + insightRule, " literal", " " + insightRule, " ```"].join("\n"),
335 [" ★ Insight " + insightRule, " literal", " " + insightRule].join("\n"),
336 ["Paragraph.", " ★ Insight " + insightRule, " literal", " " + insightRule].join("\n"),
337 ["`example", "★ Insight " + insightRule, "literal", insightRule, "`"].join("\n"),
338 insightFence("quoted")
339 .split("\n")
340 .map((line) => "> " + line)
341 .join("\n"),
342])("leaves literal and nested insight examples unchanged: %s", (markdown) => {
343 const processor = unified().use(remarkParse).use(remarkAssistantInsights);
344 const tree = processor.parse(markdown);
345 expect(processor.runSync(structuredClone(tree), markdown)).toEqual(tree);
346});
347​
348it("groups streaming bodies and several insights without losing code or headings", () => {
349 const markdown = [
350 "## Setup",
351 "",
352 insightFence("```text\n" + insightRule + "\n```"),
353 "",
354 "## Setup",
355 "",
356 "★ Insight " + insightRule,
357 "Still **streaming**",
358 ].join("\n");
359 const processor = unified().use(remarkParse).use(remarkAssistantInsights);
360 const tree = processor.parse(markdown);
361 processor.runSync(tree, markdown);
362 expect(tree.children.map((node) => node.type)).toEqual([
363 "heading",
364 "blockquote",
365 "heading",
366 "blockquote",
367 ]);
368 expect(tree.children[1]).toMatchObject({ children: [{ type: "code", value: insightRule }] });
369 expect(tree.children[3]).toMatchObject({
370 children: [
371 { type: "paragraph", children: [{ type: "text", value: "Still " }, { type: "strong" }] },
372 ],
373 });
374});
375​
376it("keeps reference definitions out of unfinished streaming code", () => {
377 const markdown = `[src]: https://example.com\n\n★ Insight ${insightRule}\n\`\`\`ts\nconst value = 1`;
378 const processor = unified().use(remarkParse).use(remarkAssistantInsights);
379 const tree = processor.parse(markdown);
380 processor.runSync(tree, markdown);
381 expect(tree.children.find((node) => node.type === "blockquote")).toMatchObject({
382 children: [{ type: "code", value: "const value = 1" }],
383 });
384});
385​
386it("preserves footnotes and original code positions across a callout", () => {
387 const code = "```sh\necho hello\n```";
388 const markdown = ["Before[^n].", "", insightFence(code), "", "[^n]: Footnote."].join("\n");
389 const processor = unified()
390 .use(remarkParse)
391 .use(remarkAssistantInsights)
392 .use(CHAT_MARKDOWN_REMARK_PLUGINS);
393 const tree = processor.parse(markdown);
394 processor.runSync(tree, markdown);
395 expect(tree.children[0]).toMatchObject({
396 children: [
397 { type: "text", value: "Before" },
398 { type: "footnoteReference", identifier: "n" },
399 { type: "text", value: "." },
400 ],
401 });
402 expect(tree.children.at(-1)).toMatchObject({ type: "footnoteDefinition", identifier: "n" });
403 const note = tree.children.find((node) => node.type === "blockquote");
404 const block = note?.children[0];
405 expect(markdown.slice(block?.position?.start.offset, block?.position?.end.offset)).toBe(code);
406});
407​
408it("preserves in-app thread links through the shared Markdown sanitizer", () => {
409 const processor = unified()
410 .use(remarkParse)
411 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
412 .use(remarkRehype, { allowDangerousHtml: true })
413 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
414 const tree = processor.runSync(
415 processor.parse(
416 '[Open thread](t3-thread://v1/thread)\n\n<t3-thread://v2/environment/thread:a%3A1>\n\n<a href="javascript:alert(1)">Unsafe</a>',
417 ),
418 );
419 expect(tree.children[0]).toMatchObject({
420 tagName: "p",
421 children: [
422 {
423 tagName: "a",
424 properties: { href: "t3-thread://v1/thread" },
425 children: [{ type: "text", value: "Open thread" }],
426 },
427 ],
428 });
429 expect(tree.children[2]).toMatchObject({
430 tagName: "p",
431 children: [
432 {
433 tagName: "a",
434 properties: { href: "t3-thread://v2/environment/thread:a%3A1" },
435 children: [{ type: "text", value: "t3-thread://v2/environment/thread:a%3A1" }],
436 },
437 ],
438 });
439 expect(JSON.stringify(tree)).not.toContain("javascript:");
440});
441​
442it("builds the tree rehype-raw builds for markdown without HTML", () => {
443 type Node = {
444 type: string;
445 tagName?: string;
446 value?: string;
447 position?: unknown;
448 data?: unknown;
449 children?: Node[];
450 };
451 // What the round trip changes that renders the same; see `needsHtmlParser`.
452 const comparable = (node: Node): Node => {
453 const { position, children, data, ...rest } = node;
454 const result: Node =
455 node.type === "text" || node.type === "root" ? rest : { ...rest, position, data };
456 if (!children) return result;
457 const merged: Node[] = [];
458 for (const child of children.map(comparable)) {
459 const last = merged.at(-1);
460 if (child.type === "text" && last?.type === "text") last.value += child.value ?? "";
461 else merged.push(child);
462 }
463 // Blank text inside a table moves in front of it; the JSX runtime drops it in tables.
464 const inTable = /^(?:table|thead|tbody|tfoot|tr)$/.test(node.tagName ?? "");
465 result.children = merged.filter(
466 (child, index) =>
467 child.type !== "text" ||
468 child.value?.trim() ||
469 !(inTable || merged[index + 1]?.tagName === "table"),
470 );
471 return result;
472 };
473 const tree = (rehypePlugins: typeof CHAT_MARKDOWN_REHYPE_PLUGINS, markdown: string) => {
474 const processor = unified()
475 .use(remarkParse)
476 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
477 .use(remarkRehype, { allowDangerousHtml: true })
478 .use(rehypePlugins);
479 return comparable(processor.runSync(processor.parse(markdown)) as Node);
480 };
481 const [first, , ...rest] = CHAT_MARKDOWN_REHYPE_PLUGINS;
482 const withRaw = [first!, rehypeRaw, ...rest];
483 for (const markdown of [
484 "- [ ] open\n- [x] done\n\nNote[^1]\n\n[^1]: The note.",
485 "| a | b |\n| :- | -: |\n| `c` | ![d](./d.png) |\n\n```ts title=x\nconst a = 1;\n```",
486 // The HTML parser moves the footnote's link out of the label's link.
487 "[note[^x]](https://example.com)\n\n[^x]: text",
488 "**a** **b**\r\n> - | a |\r\n> | - |\r\n> | b |\r\n\n-\tx\n\n y",
489 ]) {
490 expect(tree(CHAT_MARKDOWN_REHYPE_PLUGINS, markdown)).toEqual(tree(withRaw, markdown));
491 }
492});
493​
494it("keeps local editor file links but not other schemes through the shared Markdown sanitizer", () => {
495 const processor = unified()
496 .use(remarkParse)
497 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
498 .use(remarkRehype, { allowDangerousHtml: true })
499 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
500 const tree = processor.runSync(
501 processor.parse(
502 [
503 "[cursor](cursor://file/Users/me/repo/file.md:3)",
504 "[code](vscode://file/Users/me/repo/file.md:3:7)",
505 "[insiders](vscode-insiders://file/Users/me/repo/file.md)",
506 "[unknown](foo://file/Users/me/repo/file.md)",
507 "[zed](zed://file/Users/me/repo/file.md)",
508 ].join(" "),
509 ),
510 );
511 type Node = { tagName?: string; properties?: { href?: string }; children?: Node[] };
512 const hrefs = ((tree.children[0] as Node).children ?? [])
513 .filter((node) => node.tagName === "a")
514 .map((node) => node.properties?.href);
515 expect(hrefs).toEqual([
516 "cursor://file/Users/me/repo/file.md:3",
517 "vscode://file/Users/me/repo/file.md:3:7",
518 "vscode-insiders://file/Users/me/repo/file.md",
519 undefined,
520 undefined,
521 ]);
522});
523​
524it("keeps mixed-case local editor file links by lowercasing the scheme before sanitizing", () => {
525 const processor = unified()
526 .use(remarkParse)
527 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
528 .use(remarkRehype, { allowDangerousHtml: true })
529 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
530 const tree = processor.runSync(
531 processor.parse(
532 [
533 "[upper](VSCODE://file/Users/me/repo/file.md:3:7)",
534 "[mixed](Cursor://file/Users/me/repo/file.md:3)",
535 "[other](FOO://file/Users/me/repo/file.md)",
536 ].join(" "),
537 ),
538 );
539 type Node = { tagName?: string; properties?: { href?: string }; children?: Node[] };
540 const hrefs = ((tree.children[0] as Node).children ?? [])
541 .filter((node) => node.tagName === "a")
542 .map((node) => node.properties?.href);
543 expect(hrefs).toEqual([
544 "vscode://file/Users/me/repo/file.md:3:7",
545 "cursor://file/Users/me/repo/file.md:3",
546 undefined,
547 ]);
548});
549​
550it("keeps backslashes that CommonMark would read as escapes in prose Windows paths", () => {
551 const processor = unified()
552 .use(remarkParse)
553 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
554 .use(remarkRehype, { allowDangerousHtml: true })
555 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
556 type Node = { type: string; value?: string; tagName?: string; children?: Node[] };
557 const text = (node: Node): string =>
558 node.type === "text"
559 ? (node.value ?? "")
560 : node.tagName === "code"
561 ? `<code>${(node.children ?? []).map(text).join("")}</code>`
562 : (node.children ?? []).map(text).join("");
563 const render = (markdown: string) => text(processor.runSync(processor.parse(markdown)) as Node);
564​
565 expect(
566 render(String.raw`Saved to C:\Users\me\.t3\_build and (C:\.scratch) and C:/work\.config.`),
567 ).toBe(String.raw`Saved to C:\Users\me\.t3\_build and (C:\.scratch) and C:/work\.config.`);
568 expect(render(String.raw`Escaped C:\\Users\\me`)).toBe(String.raw`Escaped C:\\Users\\me`);
569 expect(render(String.raw`See C:\x and \*this\* and Note:\*that\*.`)).toBe(
570 String.raw`See C:\x and *this* and Note:*that*.`,
571 );
572 expect(render(String.raw`${"`"}C:\me\.t3${"`"} and C:\me\.t3`)).toBe(
573 String.raw`<code>C:\me\.t3</code> and C:\me\.t3`,
574 );
575});
576​
577it("keeps an image on its own line under a label but leaves inline images inline", () => {
578 const processor = unified()
579 .use(remarkParse)
580 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
581 .use(remarkRehype, { allowDangerousHtml: true })
582 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
583 type Node = { type: string; value?: string; tagName?: string; children?: Node[] };
584 const shape = (node: Node): string =>
585 node.type === "text"
586 ? (node.value ?? "")
587 : node.tagName === "br" || node.tagName === "img"
588 ? `<${node.tagName}>`
589 : (node.children ?? []).map(shape).join("");
590 const render = (markdown: string) => shape(processor.runSync(processor.parse(markdown)) as Node);
591​
592 expect(
593 render("**Palette**\n![Palette](/tmp/palette.png)\n**Hero** (dark)\n![Hero](/tmp/hero.png)"),
594 ).toBe("Palette<br>\n<img><br>\nHero (dark)<br>\n<img>");
595 expect(render("Built [![CI](/ci.svg)](/ci)\nand wrapped")).toBe("Built <img>\nand wrapped");
596 expect(render("Hard-wrapped\nprose")).toBe("Hard-wrapped\nprose");
597});
598​
599it("keeps the number written on each ordered list item only when enabled", () => {
600 type Node = { tagName?: string; properties?: { value?: unknown }; children?: Node[] };
601 const values = (node: Node): unknown[] => [
602 ...(node.tagName === "li" ? [node.properties?.value] : []),
603 ...(node.children ?? []).flatMap(values),
604 ];
605 const renderer = (plugins: PluggableList) => {
606 const processor = unified()
607 .use(remarkParse)
608 .use(plugins)
609 .use(remarkRehype, { allowDangerousHtml: true });
610 return (markdown: string) =>
611 values(processor.runSync(processor.parse(markdown), markdown) as Node);
612 };
613 const render = renderer([
614 ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
615 remarkEnableOrderedListNumbers,
616 ]);
617​
618 expect(render("3. first\n5. second\n6. third")).toEqual([undefined, "5", undefined]);
619 expect(render("1. one\n1. one again")).toEqual([undefined, "1"]);
620 expect(render("> 1. quoted\n> 4. skipped")).toEqual([undefined, "4"]);
621 expect(render("1. outer\n 1. nested\n 7. jump\n9. back")).toEqual([
622 undefined,
623 undefined,
624 "7",
625 "9",
626 ]);
627 expect(render("1. one\n2. two\n- bullet")).toEqual([undefined, undefined, undefined]);
628 expect(render("- first block\n\n 3. first\n 5. second")).toEqual([
629 undefined,
630 undefined,
631 "5",
632 ]);
633 expect(
634 renderer(CHAT_MARKDOWN_REMARK_PLUGINS)(
635 "3. first\n5. second\n\n- first block\n\n 3. first\n 5. second",
636 ),
637 ).toEqual([undefined, undefined, undefined, undefined, undefined]);
638});
639​
640it("moves a <picture>'s color-scheme sources onto its <img>, which the renderer resolves", () => {
641 const processor = unified()
642 .use(remarkParse)
643 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
644 .use(remarkRehype, { allowDangerousHtml: true })
645 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
646 type Node = { type: string; tagName?: string; properties?: object; children?: Node[] };
647 const tags = (node: Node): string[] => [
648 ...(node.tagName ? [node.tagName] : []),
649 ...(node.children ?? []).flatMap(tags),
650 ];
651 const images = (node: Node): Node[] =>
652 node.tagName === "img" ? [node] : (node.children ?? []).flatMap(images);
653 const tree = processor.runSync(
654 processor.parse(
655 [
656 "<picture>",
657 ' <source media="(prefers-color-scheme: dark)" srcset="docs/dark.webp 1x, docs/dark@2x.webp 2x">',
658 ' <source media="(prefers-color-scheme: dark)" srcset="docs/dark-unused.webp">',
659 ' <source media="(min-width: 600px)" srcset="docs/wide.webp">',
660 ' <img src="docs/light.webp" alt="Studio">',
661 "</picture>",
662 "",
663 '<picture><source media="(prefers-color-scheme: light)" srcset="javascript:alert(1)"><img src="docs/dark.webp"></picture>',
664 "",
665 String.raw`<picture><source media="(prefers-color-scheme: dark)" srcset="C:\shots\dark.png"><img src="C:\shots\light.png"></picture>`,
666 ].join("\n"),
667 ),
668 ) as Node;
669​
670 expect(tags(tree)).toEqual(["picture", "img", "p", "picture", "img", "p", "picture", "img"]);
671 expect(images(tree).map((image) => image.properties)).toEqual([
672 { src: "docs/light.webp", alt: "Studio", dataDarkSrc: "docs/dark.webp" },
673 { src: "docs/dark.webp" },
674 { dataLocalSrc: String.raw`C:\shots\light.png`, dataDarkSrc: "file:///C:/shots/dark.png" },
675 ]);
676});
677​
678it("links complete absolute paths in prose and skips shortened ones", () => {
679 const path =
680 "/tmp/claude-1000/-home-user--t3-worktrees-app-t3-abc123/session/scratchpad/notes.md";
681 const processor = unified().use(remarkParse).use(CHAT_MARKDOWN_REMARK_PLUGINS);
682 const links = (markdown: string) => {
683 const urls: string[] = [];
684 const visit = (node: Root | RootContent) => {
685 if (node.type === "link") urls.push(node.url);
686 if ("children" in node) node.children.forEach(visit);
687 };
688 visit(processor.runSync(processor.parse(markdown), markdown) as Root);
689 return urls;
690 };
691 expect(links(`Saved to ${path} and /tmp/other.txt.`)).toEqual([path, "/tmp/other.txt"]);
692 expect(links(`See (${path}:12).`)).toEqual([`${path}:12`]);
693 expect(links("See /tmp/report(1).txt. and /tmp/app/[id]/page.tsx.")).toEqual([
694 "/tmp/report(1).txt",
695 "/tmp/app/[id]/page.tsx",
696 ]);
697 expect(links("(see /tmp/claude-1000/...). and /tmp/claude-1000/….")).toEqual([]);
698 expect(links("Served at /index.html; GET /api/users.json; see /tmp/x.md:3.")).toEqual([
699 "/tmp/x.md:3",
700 ]);
701 expect(
702 links(
703 '<a title="</a>" href="https://example.com">/tmp/notes.md</a> and **<a href="x">/tmp/a.md</a>**',
704 ),
705 ).toEqual([]);
706 expect(
707 links("Config lives in /Users/me/Library/Application Support/T3 Code/settings.json now."),
708 ).toEqual([]);
709 expect(links(`/chat/settings and https://example.com${path}`)).toEqual([
710 `https://example.com${path}`,
711 ]);
712 expect(links(`[notes](${path}) and \`${path}\``)).toEqual([path]);
713 expect(links(`\`\`\`\n${path}\n\`\`\``)).toEqual([]);
714});