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

markdownHtml.test.ts

332 lines13.9 KB

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&amp;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("[![Review](<https://example.com/banner.svg>)](<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="&amp;lt;" src="https://example.com/shot.png?label=&amp;lt;&amp;sig=a%26b">';
34 expect(markdownWithHtml(markdown)).toBe(
35 "![\\&lt;](<https://example.com/shot.png?label=\\&lt;\\&sig=a%26b>)",
36 );
37 expect(markdownImageSources(markdown)).toEqual([
38 "https://example.com/shot.png?label=&lt;&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: "&lt;" });
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 "![Screenshot](<https://example.com/shot.png>)",
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![Two](two.png)\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("links HTML anchors in a table cell without breaking the row at <br>", () => {
79 const document = parseMarkdownDocument(
80 "| Status | Preview URL |\n| - | - |\n| Done | <a href='https://commit.example.com'>Commit</a><br><a href='https://branch.example.com'>Branch</a> |",
81 );
82 const table = document.children[0];
83 expect(table?.type).toBe("table");
84 if (table?.type !== "table") return;
85 expect(table.children).toHaveLength(2);
86 expect(table.children[1]?.children[1]?.children).toMatchObject([
87 { type: "link", url: "https://commit.example.com", children: [{ value: "Commit" }] },
88 { type: "text", value: " " },
89 { type: "link", url: "https://branch.example.com", children: [{ value: "Branch" }] },
90 ]);
91 });
92​
93 it("keeps a table row intact when an anchor href contains a pipe", () => {
94 const document = parseMarkdownDocument(
95 "| Preview | Logs |\n| - | - |\n| <a href='https://example.com/?a=1&#124;2'>Open</a> | done |",
96 );
97 const table = document.children[0];
98 expect(table?.type).toBe("table");
99 if (table?.type !== "table") return;
100 expect(table.children[1]?.children).toMatchObject([
101 { children: [{ type: "link", url: "https://example.com/?a=1%7C2" }] },
102 { children: [{ value: "done" }] },
103 ]);
104 });
105​
106 it("keeps anchor text unlinked for unsafe hrefs", () => {
107 expect(markdownWithHtml('Run <a href="javascript:alert(1)">this</a> now')).toBe("Run this now");
108 });
109});
110​
111describe("file embeds in native thread and file Markdown", () => {
112 const input = {
113 environmentId: EnvironmentId.make("environment-1"),
114 threadId: ThreadId.make("thread-1"),
115 workspaceRoot: "/repo",
116 };
117 const assets = (markdown: string) => {
118 const result: MarkdownNode[] = [];
119 const visit = (node: MarkdownNode) => {
120 if (node.type === "link" || node.type === "image") result.push(node);
121 if ("children" in node) node.children.forEach(visit);
122 };
123 visit(parseMarkdownDocument(markdown));
124 return result;
125 };
126​
127 it.each([
128 [
129 "[![sheet](./report.csv)](https://example.com/download)",
130 "report.csv",
131 "https://example.com/download",
132 ],
133 ["[![report](./report.pdf)](./report.pdf)", "report.pdf", "./report.pdf"],
134 [
135 "[![sheet][f]][download]\n\n[f]: ./report.csv\n[download]: https://example.com/download",
136 "report.csv",
137 "https://example.com/download",
138 ],
139 ])("keeps the enclosing link for %s", async (source, filename, target) => {
140 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
141 markdownFileEmbedLabel(href, input, standalone),
142 );
143 expect((await parseMarkdown(converted.markdown)).children).toMatchObject([
144 {
145 type: "Paragraph",
146 children: [
147 {
148 type: "Link",
149 attributes: { url: target },
150 children: [{ type: "Text", content: filename }],
151 },
152 ],
153 },
154 ]);
155 });
156​
157 it.each(["f", "F", "File Label", "file label"])(
158 "uses the first reference definition for %s",
159 async (identifier) => {
160 const source = `![sheet][${identifier}]\n\n[${identifier.toLowerCase()}]: ./report.csv\n[${identifier.toUpperCase()}]: ./report.xlsx`;
161 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
162 markdownFileEmbedLabel(href, input, standalone),
163 );
164 expect(converted.fileHrefs).toEqual(new Set(["./report.csv"]));
165 expect((await parseMarkdown(converted.markdown)).children).toMatchObject([
166 {
167 type: "Paragraph",
168 children: [
169 {
170 type: "Link",
171 attributes: { url: "./report.csv" },
172 children: [{ type: "Text", content: "report.csv" }],
173 },
174 ],
175 },
176 ]);
177 expect((await parseMarkdown(source)).children).toMatchObject([
178 { type: "Paragraph", children: [{ type: "Image", attributes: { url: "./report.csv" } }] },
179 ]);
180 },
181 );
182​
183 it.each([
184 "report.csv",
185 "report.tsv",
186 "report.pdf",
187 "report.docx",
188 "report.xlsx",
189 "report.pptx",
190 "report.unknown",
191 "main.tf",
192 "schema.prisma",
193 "index.astro",
194 "main.zig",
195 "Containerfile",
196 "sound.mp3",
197 "clip.mp4",
198 ])("uses filename links throughout prose, lists, and tables for %s", (name) => {
199 for (const href of [
200 `./${name}`,
201 `/tmp/${name}`,
202 `file:///tmp/${name}`,
203 `https://cdn.example.com/${name}?signature=a%2fb`,
204 ]) {
205 if (name === "Containerfile" && href.startsWith("https:")) continue;
206 for (const source of [
207 `download: ![sheet](<${href}>)`,
208 `- ![sheet](<${href}>)`,
209 `| file |\n| --- |\n| ![sheet](<${href}>) |`,
210 `download: ![sheet][file]\n\n[file]: <${href}>`,
211 `download: <img src="${href}" alt="sheet">`,
212 ]) {
213 const converted = markdownWithFileEmbeds(markdownWithHtml(source), (url, standalone) =>
214 markdownFileEmbedLabel(url, input, standalone),
215 );
216 const image = href.startsWith("https:") && /\.(unknown|tf|prisma|astro|zig)$/.test(name);
217 if (image) expect(converted.markdown).toBe(markdownWithHtml(source));
218 else
219 expect(assets(converted.markdown)).toMatchObject([
220 { type: "link", url: href, children: [{ type: "text", value: name }] },
221 ]);
222 expect(converted.fileHrefs.has(href)).toBe(!image);
223 const preview = resolveMarkdownMediaPreview(href, { ...input, imageEmbed: true });
224 if (
225 !href.startsWith("https:") &&
226 !name.endsWith(".pdf") &&
227 !name.endsWith(".mp3") &&
228 !name.endsWith(".mp4")
229 ) {
230 expect(preview?.kind).toBe("file");
231 expect(resolveMarkdownLinkPresentation(href)).toMatchObject({ kind: "file" });
232 }
233 }
234 }
235 });
236​
237 it("retains standalone audio players and image/video embeds in threads", () => {
238 const source =
239 "![sound](./sound.mp3)\n\n![image](./image.png)\n\n![clip](./clip.mp4)\n\ninline ![photo](./photo.png)";
240 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
241 markdownFileEmbedLabel(href, input, standalone),
242 );
243 expect(converted.markdown).toBe(source);
244 expect(converted.fileHrefs.size).toBe(0);
245 expect(resolveMarkdownMediaPreview("./sound.mp3", input)?.kind).toBe("audio");
246 });
247​
248 it("uses audio filenames in file previews and draft workspaces", () => {
249 const draft = { ...input, threadId: undefined, workspaceRoot: "/repo/docs" };
250 const converted = markdownWithFileEmbeds("![sound](./sound.mp3)", (href) =>
251 markdownFileEmbedLabel(href, draft, false),
252 );
253 expect(assets(converted.markdown)).toMatchObject([
254 { type: "link", url: "./sound.mp3", children: [{ value: "sound.mp3" }] },
255 ]);
256 expect(resolveMarkdownMediaPreview("./sound.mp3", draft)?.source).toMatchObject({
257 resource: { _tag: "draft-workspace-file", cwd: "/repo/docs", path: "/repo/docs/./sound.mp3" },
258 });
259 });
260​
261 it("keeps captured images on the image path and documents on filename links", () => {
262 const captured = { ...input, captured: true };
263 const converted = markdownWithFileEmbeds(
264 "![photo](./photo.png)\n\n![clip](./clip.mp4)\n\n![sheet](./report.csv)",
265 (href, standalone) => markdownFileEmbedLabel(href, captured, standalone),
266 );
267 expect(assets(converted.markdown)).toMatchObject([
268 { type: "image", url: "./photo.png" },
269 { type: "image", url: "./clip.mp4" },
270 { type: "link", url: "./report.csv", children: [{ value: "report.csv" }] },
271 ]);
272 expect(resolveMarkdownMediaPreview("./report.csv", captured)).toBeNull();
273 });
274​
275 it("preserves table structure and filename punctuation", () => {
276 const source = "| file |\n| --- |\n| ![sheet](./report%5B1%5D%26%7C.csv) |";
277 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
278 markdownFileEmbedLabel(href, input, standalone),
279 );
280 expect(parseMarkdownDocument(converted.markdown).children[0]?.type).toBe("table");
281 expect(assets(converted.markdown)).toMatchObject([
282 { type: "link", url: "./report%5B1%5D%26%7C.csv", children: [{ value: "report[1]&|.csv" }] },
283 ]);
284 });
285​
286 it("keeps authored positions, signed URLs, and code examples literal", () => {
287 const href = "https://cdn.example.com/report%23one%2520.csv?name=&lt;&signature=a%2fb";
288 const source = `![report](<${href.replaceAll("&", "\\&")}>)\n\n![source](./main.tf#L42C3)\n\n\`![sheet](./literal.csv)\`\n\n\`\`\`md\n![sheet](./fenced.csv)\n\`\`\``;
289 const converted = markdownWithFileEmbeds(source, (url, standalone) =>
290 markdownFileEmbedLabel(url, input, standalone),
291 );
292 expect(assets(converted.markdown)).toMatchObject([
293 { type: "link", url: href, children: [{ value: "report#one%20.csv" }] },
294 { type: "link", url: "./main.tf#L42C3", children: [{ value: "main.tf · L42:C3" }] },
295 ]);
296 expect(converted.markdown).toContain("`![sheet](./literal.csv)`");
297 expect(converted.markdown).toContain("```md\n![sheet](./fenced.csv)\n```");
298 expect(converted.fileHrefs.has(href)).toBe(true);
299 });
300});
301​
302describe("Windows paths in native Markdown", () => {
303 // regression: #23722 Markdown escapes ate the separator before `.t3` and `_build`
304 it("keeps backslashes in Windows image and link destinations", async () => {
305 const image = String.raw`C:\work\.t3\_build\shot.png`;
306 const link = String.raw`\\server\share\.t3\notes.md`;
307 const markdown = [
308 `![shot](${image} "Shot")`,
309 String.raw`![paren](C:\a\)b.png)`,
310 `[notes](<${link}>)`,
311 `<img src="${image}">`,
312 String.raw`![amp](C:\R&D\.t3\a&amp;b.png)`,
313 String.raw`<img src="C:\R&amp;D\.t3\b.png">`,
314 "> ![quoted](\n> " + image + ")",
315 ].join("\n\n");
316​
317 const native = await parseMarkdown(
318 markdownForNativeRendering(markdown, ENRICHED_INLINE_FILE_LINK_REGEX),
319 );
320 const urls: string[] = [];
321 const collect = (node: { attributes?: { url?: string }; children?: unknown[] }) => {
322 if (node.attributes?.url) urls.push(node.attributes.url);
323 node.children?.forEach((child) => collect(child as typeof node));
324 };
325 collect(native);
326 const paren = String.raw`C:\a\)b.png`;
327 const amp = String.raw`C:\R&D\.t3\a&b.png`;
328 const htmlAmp = String.raw`C:\R&D\.t3\b.png`;
329 expect(urls).toEqual([image, paren, link, image, amp, htmlAmp, image]);
330 expect(markdownImageSources(markdown)).toEqual([image, paren, amp, htmlAmp]);
331 });
332});