Open History to see the last commit
1import { describe, expect, it } from "vite-plus/test";
2import {
3 markdownHtmlContent,
4 markdownWithHtml,
5 markdownWithFileEmbeds,
6 parseMarkdownDocument,
7 type MarkdownNode,
8} from "./markdownDocument";
9import { markdownImageSources } from "./markdownImageSources";
10import { markdownFileEmbedLabel, resolveMarkdownMediaPreview } from "./markdownMedia";
11import { resolveMarkdownLinkPresentation } from "./markdownLinks";
12import { EnvironmentId, ThreadId } from "@t3tools/contracts";
13import { parseMarkdown } from "react-native-enriched-markdown/src/web/parseMarkdown";
14
15describe("HTML in native Markdown", () => {
16 it("preserves screenshot URLs and captions from GitHub HTML image embeds", () => {
17 expect(
18 markdownHtmlContent(
19 '<img width="900" alt="Before > after [settings]" src="https://example.com/before.png?a=1&b=2" />',
20 ),
21 ).toBe("![Before > after \\[settings\\]](<https://example.com/before.png?a=1\\&b=2>)");
22 expect(
23 markdownHtmlContent(
24 "<a href='https://example.com'><img src='https://example.com/banner.svg' alt='Review' /></a>",
25 ),
26 ).toBe("[](<https://example.com>)");
27 });
28
29 it("decodes HTML attributes once and preserves entity-shaped query values through Markdown", () => {
30 const markdown =
31 '<img alt="&lt;" src="https://example.com/shot.png?label=&lt;&sig=a%26b">';
32 expect(markdownWithHtml(markdown)).toBe(
33 "",
34 );
35 expect(markdownImageSources(markdown)).toEqual([
36 "https://example.com/shot.png?label=<&sig=a%26b",
37 ]);
38 const paragraph = parseMarkdownDocument(markdown).children[0];
39 expect(paragraph?.type).toBe("paragraph");
40 if (paragraph?.type === "paragraph")
41 expect(paragraph.children[0]).toMatchObject({ type: "image", alt: "<" });
42 });
43
44 it("ignores code delimiters in HTML attributes and comments when collecting screenshots", () => {
45 const markdown =
46 '<details data-example="`">\n<summary>Proof</summary>\n<img src="https://example.com/shot.png" alt="Screenshot">\n<!-- ` -->\n</details>';
47 expect(markdownHtmlContent(markdown)).toContain(
48 "",
49 );
50 expect(markdownImageSources(markdown)).toEqual(["https://example.com/shot.png"]);
51 expect(markdownWithHtml(markdown)).not.toContain("<img");
52 });
53
54 it("removes bot metadata and details wrappers while keeping the content", () => {
55 const markdown =
56 "<!-- generated bot metadata -->\n<details>\n<summary>Walkthrough</summary>\n\n## Changes\n\nText\n\n</details>";
57 const result = markdownWithHtml(markdown);
58 expect(result).not.toContain("<!--");
59 expect(result).not.toContain("<details>");
60 expect(result).toContain("**Walkthrough**");
61 expect(result).toContain("## Changes");
62 expect(parseMarkdownDocument(markdown).children.some((node) => node.type === "html")).toBe(
63 false,
64 );
65 });
66
67 it("collects HTML and Markdown screenshots while leaving inline and fenced code literal", () => {
68 const markdown =
69 '```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">';
70 expect(markdownImageSources(markdown)).toEqual(["one.png", "two.png"]);
71 const result = markdownWithHtml(markdown);
72 expect(result).toContain('```html\n<img src="literal.png">\n```');
73 expect(result).toContain('`<img src="inline.png">`');
74 });
75
76 it("links HTML anchors in a table cell without breaking the row at <br>", () => {
77 const document = parseMarkdownDocument(
78 "| Status | Preview URL |\n| - | - |\n| Done | <a href='https://commit.example.com'>Commit</a><br><a href='https://branch.example.com'>Branch</a> |",
79 );
80 const table = document.children[0];
81 expect(table?.type).toBe("table");
82 if (table?.type !== "table") return;
83 expect(table.children).toHaveLength(2);
84 expect(table.children[1]?.children[1]?.children).toMatchObject([
85 { type: "link", url: "https://commit.example.com", children: [{ value: "Commit" }] },
86 { type: "text", value: " " },
87 { type: "link", url: "https://branch.example.com", children: [{ value: "Branch" }] },
88 ]);
89 });
90
91 it("keeps a table row intact when an anchor href contains a pipe", () => {
92 const document = parseMarkdownDocument(
93 "| Preview | Logs |\n| - | - |\n| <a href='https://example.com/?a=1|2'>Open</a> | done |",
94 );
95 const table = document.children[0];
96 expect(table?.type).toBe("table");
97 if (table?.type !== "table") return;
98 expect(table.children[1]?.children).toMatchObject([
99 { children: [{ type: "link", url: "https://example.com/?a=1%7C2" }] },
100 { children: [{ value: "done" }] },
101 ]);
102 });
103
104 it("keeps anchor text unlinked for unsafe hrefs", () => {
105 expect(markdownWithHtml('Run <a href="javascript:alert(1)">this</a> now')).toBe("Run this now");
106 });
107});
108
109describe("file embeds in native thread and file Markdown", () => {
110 const input = {
111 environmentId: EnvironmentId.make("environment-1"),
112 threadId: ThreadId.make("thread-1"),
113 workspaceRoot: "/repo",
114 };
115 const assets = (markdown: string) => {
116 const result: MarkdownNode[] = [];
117 const visit = (node: MarkdownNode) => {
118 if (node.type === "link" || node.type === "image") result.push(node);
119 if ("children" in node) node.children.forEach(visit);
120 };
121 visit(parseMarkdownDocument(markdown));
122 return result;
123 };
124
125 it.each([
126 [
127 "[](https://example.com/download)",
128 "report.csv",
129 "https://example.com/download",
130 ],
131 ["[](./report.pdf)", "report.pdf", "./report.pdf"],
132 [
133 "[![sheet][f]][download]\n\n[f]: ./report.csv\n[download]: https://example.com/download",
134 "report.csv",
135 "https://example.com/download",
136 ],
137 ])("keeps the enclosing link for %s", async (source, filename, target) => {
138 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
139 markdownFileEmbedLabel(href, input, standalone),
140 );
141 expect((await parseMarkdown(converted.markdown)).children).toMatchObject([
142 {
143 type: "Paragraph",
144 children: [
145 {
146 type: "Link",
147 attributes: { url: target },
148 children: [{ type: "Text", content: filename }],
149 },
150 ],
151 },
152 ]);
153 });
154
155 it.each(["f", "F", "File Label", "file label"])(
156 "uses the first reference definition for %s",
157 async (identifier) => {
158 const source = `![sheet][${identifier}]\n\n[${identifier.toLowerCase()}]: ./report.csv\n[${identifier.toUpperCase()}]: ./report.xlsx`;
159 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
160 markdownFileEmbedLabel(href, input, standalone),
161 );
162 expect(converted.fileHrefs).toEqual(new Set(["./report.csv"]));
163 expect((await parseMarkdown(converted.markdown)).children).toMatchObject([
164 {
165 type: "Paragraph",
166 children: [
167 {
168 type: "Link",
169 attributes: { url: "./report.csv" },
170 children: [{ type: "Text", content: "report.csv" }],
171 },
172 ],
173 },
174 ]);
175 expect((await parseMarkdown(source)).children).toMatchObject([
176 { type: "Paragraph", children: [{ type: "Image", attributes: { url: "./report.csv" } }] },
177 ]);
178 },
179 );
180
181 it.each([
182 "report.csv",
183 "report.tsv",
184 "report.pdf",
185 "report.docx",
186 "report.xlsx",
187 "report.pptx",
188 "report.unknown",
189 "main.tf",
190 "schema.prisma",
191 "index.astro",
192 "main.zig",
193 "Containerfile",
194 "sound.mp3",
195 "clip.mp4",
196 ])("uses filename links throughout prose, lists, and tables for %s", (name) => {
197 for (const href of [
198 `./${name}`,
199 `/tmp/${name}`,
200 `file:///tmp/${name}`,
201 `https://cdn.example.com/${name}?signature=a%2fb`,
202 ]) {
203 if (name === "Containerfile" && href.startsWith("https:")) continue;
204 for (const source of [
205 `download: `,
206 `- `,
207 `| file |\n| --- |\n|  |`,
208 `download: ![sheet][file]\n\n[file]: <${href}>`,
209 `download: <img src="${href}" alt="sheet">`,
210 ]) {
211 const converted = markdownWithFileEmbeds(markdownWithHtml(source), (url, standalone) =>
212 markdownFileEmbedLabel(url, input, standalone),
213 );
214 const image = href.startsWith("https:") && /\.(unknown|tf|prisma|astro|zig)$/.test(name);
215 if (image) expect(converted.markdown).toBe(markdownWithHtml(source));
216 else
217 expect(assets(converted.markdown)).toMatchObject([
218 { type: "link", url: href, children: [{ type: "text", value: name }] },
219 ]);
220 expect(converted.fileHrefs.has(href)).toBe(!image);
221 const preview = resolveMarkdownMediaPreview(href, { ...input, imageEmbed: true });
222 if (
223 !href.startsWith("https:") &&
224 !name.endsWith(".pdf") &&
225 !name.endsWith(".mp3") &&
226 !name.endsWith(".mp4")
227 ) {
228 expect(preview?.kind).toBe("file");
229 expect(resolveMarkdownLinkPresentation(href)).toMatchObject({ kind: "file" });
230 }
231 }
232 }
233 });
234
235 it("retains standalone audio players and image/video embeds in threads", () => {
236 const source =
237 "\n\n\n\n\n\ninline ";
238 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
239 markdownFileEmbedLabel(href, input, standalone),
240 );
241 expect(converted.markdown).toBe(source);
242 expect(converted.fileHrefs.size).toBe(0);
243 expect(resolveMarkdownMediaPreview("./sound.mp3", input)?.kind).toBe("audio");
244 });
245
246 it("uses audio filenames in file previews and draft workspaces", () => {
247 const draft = { ...input, threadId: undefined, workspaceRoot: "/repo/docs" };
248 const converted = markdownWithFileEmbeds("", (href) =>
249 markdownFileEmbedLabel(href, draft, false),
250 );
251 expect(assets(converted.markdown)).toMatchObject([
252 { type: "link", url: "./sound.mp3", children: [{ value: "sound.mp3" }] },
253 ]);
254 expect(resolveMarkdownMediaPreview("./sound.mp3", draft)?.source).toMatchObject({
255 resource: { _tag: "draft-workspace-file", cwd: "/repo/docs", path: "/repo/docs/./sound.mp3" },
256 });
257 });
258
259 it("keeps captured images on the image path and documents on filename links", () => {
260 const captured = { ...input, captured: true };
261 const converted = markdownWithFileEmbeds(
262 "\n\n\n\n",
263 (href, standalone) => markdownFileEmbedLabel(href, captured, standalone),
264 );
265 expect(assets(converted.markdown)).toMatchObject([
266 { type: "image", url: "./photo.png" },
267 { type: "image", url: "./clip.mp4" },
268 { type: "link", url: "./report.csv", children: [{ value: "report.csv" }] },
269 ]);
270 expect(resolveMarkdownMediaPreview("./report.csv", captured)).toBeNull();
271 });
272
273 it("preserves table structure and filename punctuation", () => {
274 const source = "| file |\n| --- |\n|  |";
275 const converted = markdownWithFileEmbeds(source, (href, standalone) =>
276 markdownFileEmbedLabel(href, input, standalone),
277 );
278 expect(parseMarkdownDocument(converted.markdown).children[0]?.type).toBe("table");
279 expect(assets(converted.markdown)).toMatchObject([
280 { type: "link", url: "./report%5B1%5D%26%7C.csv", children: [{ value: "report[1]&|.csv" }] },
281 ]);
282 });
283
284 it("keeps authored positions, signed URLs, and code examples literal", () => {
285 const href = "https://cdn.example.com/report%23one%2520.csv?name=<&signature=a%2fb";
286 const source = `}>)\n\n\n\n\`\`\n\n\`\`\`md\n\n\`\`\``;
287 const converted = markdownWithFileEmbeds(source, (url, standalone) =>
288 markdownFileEmbedLabel(url, input, standalone),
289 );
290 expect(assets(converted.markdown)).toMatchObject([
291 { type: "link", url: href, children: [{ value: "report#one%20.csv" }] },
292 { type: "link", url: "./main.tf#L42C3", children: [{ value: "main.tf · L42:C3" }] },
293 ]);
294 expect(converted.markdown).toContain("``");
295 expect(converted.markdown).toContain("```md\n\n```");
296 expect(converted.fileHrefs.has(href)).toBe(true);
297 });
298});