Open History to see the last commit
1import { describe, expect, it } from "vite-plus/test";
2import {
3 markdownForNativeRendering,
4 markdownHtmlContent,
5 markdownWithHtml,
6 markdownWithFileEmbeds,
7 parseMarkdownDocument,
8 type MarkdownNode,
9} from "./markdownDocument";
10import { markdownImageSources } from "./markdownImageSources";
11import { markdownFileEmbedLabel, resolveMarkdownMediaPreview } from "./markdownMedia";
12import { resolveMarkdownLinkPresentation } from "./markdownLinks";
13import { ENRICHED_INLINE_FILE_LINK_REGEX } from "./enrichedLinkPresentation";
14import { EnvironmentId, ThreadId } from "@t3tools/contracts";
15import { parseMarkdown } from "react-native-enriched-markdown/src/web/parseMarkdown";
16
17describe("HTML in native Markdown", () => {
18 it("preserves screenshot URLs and captions from GitHub HTML image embeds", () => {
19 expect(
20 markdownHtmlContent(
21 '<img width="900" alt="Before > after [settings]" src="https://example.com/before.png?a=1&b=2" />',
22 ),
23 ).toBe("![Before > after \\[settings\\]](<https://example.com/before.png?a=1\\&b=2>)");
24 expect(
25 markdownHtmlContent(
26 "<a href='https://example.com'><img src='https://example.com/banner.svg' alt='Review' /></a>",
27 ),
28 ).toBe("[](<https://example.com>)");
29 });
30
31 it("decodes HTML attributes once and preserves entity-shaped query values through Markdown", () => {
32 const markdown =
33 '<img alt="&lt;" src="https://example.com/shot.png?label=&lt;&sig=a%26b">';
34 expect(markdownWithHtml(markdown)).toBe(
35 "",
36 );
37 expect(markdownImageSources(markdown)).toEqual([
38 "https://example.com/shot.png?label=<&sig=a%26b",
39 ]);
40 const paragraph = parseMarkdownDocument(markdown).children[0];
41 expect(paragraph?.type).toBe("paragraph");
42 if (paragraph?.type === "paragraph")
43 expect(paragraph.children[0]).toMatchObject({ type: "image", alt: "<" });
44 });
45
46 it("ignores code delimiters in HTML attributes and comments when collecting screenshots", () => {
47 const markdown =
48 '<details data-example="`">\n<summary>Proof</summary>\n<img src="https://example.com/shot.png" alt="Screenshot">\n<!-- ` -->\n</details>';
49 expect(markdownHtmlContent(markdown)).toContain(
50 "",
51 );
52 expect(markdownImageSources(markdown)).toEqual(["https://example.com/shot.png"]);
53 expect(markdownWithHtml(markdown)).not.toContain("<img");
54 });
55
56 it("removes bot metadata and details wrappers while keeping the content", () => {
57 const markdown =
58 "<!-- generated bot metadata -->\n<details>\n<summary>Walkthrough</summary>\n\n## Changes\n\nText\n\n</details>";
59 const result = markdownWithHtml(markdown);
60 expect(result).not.toContain("<!--");
61 expect(result).not.toContain("<details>");
62 expect(result).toContain("**Walkthrough**");
63 expect(result).toContain("## Changes");
64 expect(parseMarkdownDocument(markdown).children.some((node) => node.type === "html")).toBe(
65 false,
66 );
67 });
68
69 it("collects HTML and Markdown screenshots while leaving inline and fenced code literal", () => {
70 const markdown =
71 '```html\n<img src="literal.png">\n```\n\nUse `<img src="inline.png">` here.\n\n<img src="one.png">\n\n\n\n<img src="one.png">';
72 expect(markdownImageSources(markdown)).toEqual(["one.png", "two.png"]);
73 const result = markdownWithHtml(markdown);
74 expect(result).toContain('```html\n<img src="literal.png">\n```');
75 expect(result).toContain('`<img src="inline.png">`');
76 });
77
78 it("treats an unclosed fence in an HTML block as code through the end", () => {
79 // Sized so the quadratic rescan cannot finish within the test timeout.
80 const fences = Array.from({ length: 40_000 }, () => "```x y").join("\n");
81 const markdown = `<details>\n<img src="before.png">\n${fences}\n<img src="after.png">\n</details>`;
82 const result = markdownHtmlContent(markdown);
83 expect(result).toContain("");
84 expect(result).not.toContain("<details>");
85 expect(result).toContain('<img src="after.png">\n</details>');
86 });
87
88 it("links HTML anchors in a table cell without breaking the row at <br>", () => {
89 const document = parseMarkdownDocument(
90 "| Status | Preview URL |\n| - | - |\n| Done | <a href='https://commit.example.com'>Commit</a><br><a href='https://branch.example.com'>Branch</a> |",
91 );
92 const table = document.children[0];
93 expect(table?.type).toBe("table");
94 if (table?.type !== "table") return;
95 expect(table.children).toHaveLength(2);
96 expect(table.children[1]?.children[1]?.children).toMatchObject([
97 { type: "link", url: "https://commit.example.com", children: [{ value: "Commit" }] },
98 { type: "text", value: " " },
99 { type: "link", url: "https://branch.example.com", children: [{ value: "Branch" }] },
100 ]);
101 });
102
103 it("keeps a table row intact when an anchor href contains a pipe", () => {
104 const document = parseMarkdownDocument(
105 "| Preview | Logs |\n| - | - |\n| <a href='https://example.com/?a=1|2'>Open</a> | done |",
106 );
107 const table = document.children[0];
108 expect(table?.type).toBe("table");
109 if (table?.type !== "table") return;
110 expect(table.children[1]?.children).toMatchObject([
111 { children: [{ type: "link", url: "https://example.com/?a=1%7C2" }] },
112 { children: [{ value: "done" }] },
113 ]);
114 });
115
116 it("keeps anchor text unlinked for unsafe hrefs", () => {
117 expect(markdownWithHtml('Run <a href="javascript:alert(1)">this</a> now')).toBe("Run this now");
118 });
119
120 it("keeps anchor labels and escaped bangs intact across nested formatting and table cells", () => {
121 const markdown =
122 '> **!<a href="https://x.test">[one]</a>** and <span>tail</span>\n\n| A |\n| - |\n| !<a href="https://x.test">x[y]</a><br><img src="x.png"> |';
123 expect(markdownWithHtml(markdown)).toBe(
124 "> **\\![\\[one\\]](<https://x.test>)** and tail\n\n| A |\n| - |\n| \\![x\\[y\\]](<https://x.test>)  |",
125 );
126 expect(
127 markdownWithHtml(
128 String.raw`Before \!<a href="https://x.test">escaped</a> \\!<a href="mailto:a@b">even</a>`,
129 ),
130 ).toBe(String.raw`Before \ \\\`);
131 });
132
133 it("converts separated HTML without changing code examples or an unfinished tag", () => {
134 const literal = '`<br>`\n\n```html\n<img src="literal.png">\n```\n\n<broken';
135 expect(markdownWithHtml(literal)).toBe(literal);
136 const rows = Array.from(
137 { length: 100 },
138 (_, index) => `row ${index} <span>text</span><br>!<a href="https://x.test/${index}">go</a>`,
139 );
140 const expected = Array.from(
141 { length: 100 },
142 (_, index) => `row ${index} text \n\\`,
143 );
144 expect(markdownWithHtml(rows.join("\n\n") + "\n\n" + literal)).toBe(
145 expected.join("\n\n") + "\n\n" + literal,
146 );
147 });
148});
149
150describe("file embeds in native thread and file Markdown", () => {
151 const input = {
152 environmentId: EnvironmentId.make("environment-1"),
153 threadId: ThreadId.make("thread-1"),
154 workspaceRoot: "/repo",
155 };
156 const assets = (markdown: string) => {
157 const result: MarkdownNode[] = [];
158 const visit = (node: MarkdownNode) => {
159 if (node.type === "link" || node.type === "image") result.push(node);
160 if ("children" in node) node.children.forEach(visit);
161 };
162 visit(parseMarkdownDocument(markdown));
163 return result;
164 };
165
166 it.each([
167 [
168 "[](https://example.com/download)",
169 "report.csv",
170 "https://example.com/download",
171 ],
172 ["[](./report.pdf)", "report.pdf", "./report.pdf"],
173 [
174 "[![sheet][f]][download]\n\n[f]: ./report.csv\n[download]: https://example.com/download",
175 "report.csv",
176 "https://example.com/download",
177 ],
178 ])("keeps the enclosing link for %s", async (source, filename, target) => {
179 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
180 markdownFileEmbedLabel(href, input, standalone),
181 );
182 expect((await parseMarkdown(converted.markdown)).children).toMatchObject([
183 {
184 type: "Paragraph",
185 children: [
186 {
187 type: "Link",
188 attributes: { url: target },
189 children: [{ type: "Text", content: filename }],
190 },
191 ],
192 },
193 ]);
194 });
195
196 it.each(["f", "F", "File Label", "file label"])(
197 "uses the first reference definition for %s",
198 async (identifier) => {
199 const source = `![sheet][${identifier}]\n\n[${identifier.toLowerCase()}]: ./report.csv\n[${identifier.toUpperCase()}]: ./report.xlsx`;
200 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
201 markdownFileEmbedLabel(href, input, standalone),
202 );
203 expect(converted.fileHrefs).toEqual(new Set(["./report.csv"]));
204 expect((await parseMarkdown(converted.markdown)).children).toMatchObject([
205 {
206 type: "Paragraph",
207 children: [
208 {
209 type: "Link",
210 attributes: { url: "./report.csv" },
211 children: [{ type: "Text", content: "report.csv" }],
212 },
213 ],
214 },
215 ]);
216 expect((await parseMarkdown(source)).children).toMatchObject([
217 { type: "Paragraph", children: [{ type: "Image", attributes: { url: "./report.csv" } }] },
218 ]);
219 },
220 );
221
222 it.each([
223 "report.csv",
224 "report.tsv",
225 "report.pdf",
226 "report.docx",
227 "report.xlsx",
228 "report.pptx",
229 "report.unknown",
230 "main.tf",
231 "schema.prisma",
232 "index.astro",
233 "main.zig",
234 "Containerfile",
235 "sound.mp3",
236 "clip.mp4",
237 ])("uses filename links throughout prose, lists, and tables for %s", (name) => {
238 for (const href of [
239 `./${name}`,
240 `/tmp/${name}`,
241 `file:///tmp/${name}`,
242 `https://cdn.example.com/${name}?signature=a%2fb`,
243 ]) {
244 if (name === "Containerfile" && href.startsWith("https:")) continue;
245 for (const source of [
246 `download: `,
247 `- `,
248 `| file |\n| --- |\n|  |`,
249 `download: ![sheet][file]\n\n[file]: <${href}>`,
250 `download: <img src="${href}" alt="sheet">`,
251 ]) {
252 const converted = markdownWithFileEmbeds(markdownWithHtml(source), (url, standalone) =>
253 markdownFileEmbedLabel(url, input, standalone),
254 );
255 const image = href.startsWith("https:") && /\.(unknown|tf|prisma|astro|zig)$/.test(name);
256 if (image) expect(converted.markdown).toBe(markdownWithHtml(source));
257 else
258 expect(assets(converted.markdown)).toMatchObject([
259 { type: "link", url: href, children: [{ type: "text", value: name }] },
260 ]);
261 expect(converted.fileHrefs.has(href)).toBe(!image);
262 const preview = resolveMarkdownMediaPreview(href, { ...input, imageEmbed: true });
263 if (
264 !href.startsWith("https:") &&
265 !name.endsWith(".pdf") &&
266 !name.endsWith(".mp3") &&
267 !name.endsWith(".mp4")
268 ) {
269 expect(preview?.kind).toBe("file");
270 expect(resolveMarkdownLinkPresentation(href)).toMatchObject({ kind: "file" });
271 }
272 }
273 }
274 });
275
276 it("retains standalone audio players and image/video embeds in threads", () => {
277 const source =
278 "\n\n\n\n\n\ninline ";
279 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
280 markdownFileEmbedLabel(href, input, standalone),
281 );
282 expect(converted.markdown).toBe(source);
283 expect(converted.fileHrefs.size).toBe(0);
284 expect(resolveMarkdownMediaPreview("./sound.mp3", input)?.kind).toBe("audio");
285 });
286
287 it("uses audio filenames in file previews and draft workspaces", () => {
288 const draft = { ...input, threadId: undefined, workspaceRoot: "/repo/docs" };
289 const converted = markdownWithFileEmbeds("", (href) =>
290 markdownFileEmbedLabel(href, draft, false),
291 );
292 expect(assets(converted.markdown)).toMatchObject([
293 { type: "link", url: "./sound.mp3", children: [{ value: "sound.mp3" }] },
294 ]);
295 expect(resolveMarkdownMediaPreview("./sound.mp3", draft)?.source).toMatchObject({
296 resource: { _tag: "draft-workspace-file", cwd: "/repo/docs", path: "/repo/docs/./sound.mp3" },
297 });
298 });
299
300 it("keeps captured images on the image path and documents on filename links", () => {
301 const captured = { ...input, captured: true };
302 const converted = markdownWithFileEmbeds(
303 "\n\n\n\n",
304 (href, standalone) => markdownFileEmbedLabel(href, captured, standalone),
305 );
306 expect(assets(converted.markdown)).toMatchObject([
307 { type: "image", url: "./photo.png" },
308 { type: "image", url: "./clip.mp4" },
309 { type: "link", url: "./report.csv", children: [{ value: "report.csv" }] },
310 ]);
311 expect(resolveMarkdownMediaPreview("./report.csv", captured)).toBeNull();
312 });
313
314 it("preserves table structure and filename punctuation", () => {
315 const source = "| file |\n| --- |\n|  |";
316 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
317 markdownFileEmbedLabel(href, input, standalone),
318 );
319 expect(parseMarkdownDocument(converted.markdown).children[0]?.type).toBe("table");
320 expect(assets(converted.markdown)).toMatchObject([
321 { type: "link", url: "./report%5B1%5D%26%7C.csv", children: [{ value: "report[1]&|.csv" }] },
322 ]);
323 });
324
325 it("keeps authored positions, signed URLs, and code examples literal", () => {
326 const href = "https://cdn.example.com/report%23one%2520.csv?name=<&signature=a%2fb";
327 const source = `}>)\n\n\n\n\`\`\n\n\`\`\`md\n\n\`\`\``;
328 const converted = markdownWithFileEmbeds(source, (url, standalone) =>
329 markdownFileEmbedLabel(url, input, standalone),
330 );
331 expect(assets(converted.markdown)).toMatchObject([
332 { type: "link", url: href, children: [{ value: "report#one%20.csv" }] },
333 { type: "link", url: "./main.tf#L42C3", children: [{ value: "main.tf · L42:C3" }] },
334 ]);
335 expect(converted.markdown).toContain("``");
336 expect(converted.markdown).toContain("```md\n\n```");
337 expect(converted.fileHrefs.has(href)).toBe(true);
338 });
339});
340
341describe("Windows paths in native Markdown", () => {
342 // regression: #23722 Markdown escapes ate the separator before `.t3` and `_build`
343 it("keeps backslashes in Windows image and link destinations", async () => {
344 const image = String.raw`C:\work\.t3\_build\shot.png`;
345 const link = String.raw`\\server\share\.t3\notes.md`;
346 const markdown = [
347 ``,
348 String.raw`b.png)`,
349 `[notes](<${link}>)`,
350 `<img src="${image}">`,
351 String.raw``,
352 String.raw`<img src="C:\R&D\.t3\b.png">`,
353 "> ",
354 ].join("\n\n");
355
356 const native = await parseMarkdown(
357 markdownForNativeRendering(markdown, ENRICHED_INLINE_FILE_LINK_REGEX),
358 );
359 const urls: string[] = [];
360 const collect = (node: { attributes?: { url?: string }; children?: unknown[] }) => {
361 if (node.attributes?.url) urls.push(node.attributes.url);
362 node.children?.forEach((child) => collect(child as typeof node));
363 };
364 collect(native);
365 const paren = String.raw`C:\a\)b.png`;
366 const amp = String.raw`C:\R&D\.t3\a&b.png`;
367 const htmlAmp = String.raw`C:\R&D\.t3\b.png`;
368 expect(urls).toEqual([image, paren, link, image, amp, htmlAmp, image]);
369 expect(markdownImageSources(markdown)).toEqual([image, paren, amp, htmlAmp]);
370 });
371});
372
373it("keeps backslashes in drive paths in mobile Markdown prose", () => {
374 const path = String.raw`Saved to C:\Users\me\.t3\_build\shot.png and C:/work\.config.`;
375
376 expect(parseMarkdownDocument(String.raw`${path} Then \*this\*.`).children).toMatchObject([
377 { type: "paragraph", children: [{ type: "text", value: `${path} Then *this*.` }] },
378 ]);
379});