Open History to see the last commit
1import JSZip from "jszip";
2import { openRtf, openNotebook, openDocument, openEpub } from "./extendedDocumentPreview";
3import type { ScopedThreadRef } from "@t3tools/contracts";
4import { ProjectReadFileError } from "@t3tools/contracts";
5import * as Schema from "effect/Schema";
6import { describe, expect, it, vi } from "vite-plus/test";
7
8import { remapFileCommentAnnotations } from "./fileCommentAnnotations";
9import {
10 filePreviewReadErrorMessage,
11 isMarkdownPreviewFile,
12 resolveFilePreviewPath,
13 setMarkdownTaskChecked,
14 shouldShowFileExplorer,
15 workspaceAssetResource,
16} from "./filePreviewMode";
17
18const decodeReadError = Schema.decodeSync(ProjectReadFileError);
19
20describe("file preview read errors", () => {
21 // regression: #15628 read errors from servers without attempted paths keep their own message
22 it("preserves the public message from older servers", () => {
23 const error = decodeReadError({
24 _tag: "ProjectReadFileError",
25 message: "Legacy file read failure.",
26 });
27 expect(filePreviewReadErrorMessage(error)).toBe("Legacy file read failure.");
28 });
29});
30
31describe("file comment annotations", () => {
32 it("keeps an annotation range attached when Pierre remaps its anchor line", () => {
33 expect(
34 remapFileCommentAnnotations([
35 {
36 lineNumber: 20,
37 metadata: {
38 entries: [
39 {
40 id: "comment-1",
41 kind: "comment",
42 startLine: 7,
43 endLine: 16,
44 text: "Keep this guarded.",
45 },
46 ],
47 },
48 },
49 ]),
50 ).toEqual([
51 {
52 lineNumber: 20,
53 metadata: {
54 entries: [
55 {
56 id: "comment-1",
57 kind: "comment",
58 startLine: 11,
59 endLine: 20,
60 text: "Keep this guarded.",
61 },
62 ],
63 },
64 },
65 ]);
66 });
67});
68
69describe("isMarkdownPreviewFile", () => {
70 it("recognizes markdown and MDX files case-insensitively", () => {
71 expect(isMarkdownPreviewFile("README.md")).toBe(true);
72 expect(isMarkdownPreviewFile("docs/guide.MDX")).toBe(true);
73 expect(isMarkdownPreviewFile("docs/guide.MARKDOWN")).toBe(true);
74 expect(isMarkdownPreviewFile("docs/guide.mdown")).toBe(true);
75 expect(isMarkdownPreviewFile("docs/guide.mkd")).toBe(true);
76 });
77});
78
79describe("setMarkdownTaskChecked", () => {
80 const markdown = "- [ ] First\n- [x] Second\n";
81
82 it("checks and unchecks the task marker at the supplied offset", () => {
83 expect(setMarkdownTaskChecked(markdown, 2, true)).toBe("- [x] First\n- [x] Second\n");
84 expect(setMarkdownTaskChecked(markdown, 14, false)).toBe("- [ ] First\n- [ ] Second\n");
85 expect(setMarkdownTaskChecked("1. [X] Ordered\n", 3, false)).toBe("1. [ ] Ordered\n");
86 });
87
88 it("leaves the document unchanged for a stale or invalid marker offset", () => {
89 expect(setMarkdownTaskChecked(markdown, 0, true)).toBe(markdown);
90 expect(setMarkdownTaskChecked(markdown, 200, true)).toBe(markdown);
91 });
92});
93
94describe("resolveFilePreviewPath", () => {
95 it.each([
96 ["/repo/project", null],
97 ["/repo/project/", null],
98 [".", null],
99 [null, null],
100 ["/repo/project/src", "/repo/project/src"],
101 ["/repo/project/src/main.ts", "/repo/project/src/main.ts"],
102 ["src/main.ts", "src/main.ts"],
103 ["/repo/project-other", "/repo/project-other"],
104 ])("opens %s in the appropriate workspace surface", (path, expected) => {
105 const relativePath = resolveFilePreviewPath(path, "/repo/project");
106 expect(relativePath).toBe(expected);
107 if (expected === null) {
108 expect(
109 shouldShowFileExplorer({ relativePath, explorerOpen: false, attachmentOpen: false }),
110 ).toBe(true);
111 }
112 });
113});
114
115describe("workspaceAssetResource", () => {
116 const input = {
117 kind: "workspace-file" as const,
118 threadRef: {
119 environmentId: "env" as ScopedThreadRef["environmentId"],
120 threadId: "thread-1" as ScopedThreadRef["threadId"],
121 },
122 workspaceRoot: "/repo",
123 absolutePath: "/repo/docs/index.html",
124 };
125
126 // regression: #21067 images outside the workspace load through the host media resource
127 it("serves a file outside the workspace as host media and keeps workspace files on workspace access", () => {
128 expect(
129 workspaceAssetResource({ ...input, absolutePath: "/tmp/screenshots/shot.png", draft: false }),
130 ).toEqual({ _tag: "media-file", threadId: "thread-1", path: "/tmp/screenshots/shot.png" });
131 expect(workspaceAssetResource({ ...input, draft: false })).toEqual({
132 _tag: "workspace-file",
133 threadId: "thread-1",
134 path: "/repo/docs/index.html",
135 });
136 });
137
138 it("names the workspace root for a draft, which the server cannot resolve from a thread", () => {
139 expect(workspaceAssetResource({ ...input, draft: true })).toEqual({
140 _tag: "draft-workspace-file",
141 cwd: "/repo",
142 path: "/repo/docs/index.html",
143 });
144 expect(
145 workspaceAssetResource({ ...input, absolutePath: "/tmp/screenshots/shot.png", draft: true }),
146 ).toEqual({ _tag: "draft-workspace-file", cwd: "/repo", path: "/tmp/screenshots/shot.png" });
147 });
148});
149
150describe("document preview contents", () => {
151 const bytes = (text: string) => new TextEncoder().encode(text).buffer;
152
153 it.each(["?", String.raw`\'3f`, String.raw`\\`])(
154 "consumes skipped rich text Unicode fallback %s",
155 (fallback) => {
156 const result = openRtf(bytes(String.raw`{\rtf1{\*\unknown\u945` + fallback + "}Hello}"));
157 if (result.type !== "document") throw new Error("Expected document");
158 expect(result.pages[0]!.html).toBe("<p>Hello</p>");
159 },
160 );
161
162 it("bounds EPUB markup made entirely of empty allowed elements", async () => {
163 const archive = new JSZip()
164 .file(
165 "META-INF/container.xml",
166 '<container><rootfiles><rootfile full-path="book.opf"/></rootfiles></container>',
167 )
168 .file(
169 "book.opf",
170 '<package><manifest><item id="a" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine>' +
171 '<itemref idref="a"/>'.repeat(30) +
172 "</spine></package>",
173 )
174 .file("chapter.xhtml", "<html><body>" + "<figcaption/>".repeat(30_000) + "</body></html>");
175 await expect(openEpub(archive)).rejects.toThrow("too large");
176 });
177
178 it("decodes rich text formatting and Unicode without showing hidden destinations", () => {
179 const result = openRtf(
180 bytes(
181 String.raw`{\rtf1\ansi{\fonttbl{\f0 Hidden font;}}Hello \b bold\b0\par Unicode: \u945?{\*\unknown hidden}{\field{\*\fldinst HYPERLINK "https://example.com"}{\fldrslt visible}}}`,
182 ),
183 );
184 expect(result.type).toBe("document");
185 if (result.type !== "document") throw new Error("Expected document");
186 const html = result.pages[0]!.html;
187 expect(html.replaceAll(/<[^>]*>/g, "")).toBe("Hello boldUnicode: αvisible");
188 expect(html).toContain("<strong>");
189 expect(html).not.toContain("https:");
190 });
191
192 it("preserves rich text page breaks and formatting without splitting hidden destinations", () => {
193 const result = openRtf(
194 bytes(String.raw`{\rtf1\b First\page Second\b0{\*\unknown \page hidden}\page Third\page}`),
195 );
196 if (result.type !== "document") throw new Error("Expected document");
197 expect(result.navigation).toBe("page");
198 expect(result.pages.map((page) => page.html)).toEqual([
199 "<p><strong>First</strong></p>",
200 "<p><strong>Second</strong></p>",
201 "<p>Third</p>",
202 ]);
203 expect(() => openRtf(bytes(String.raw`{\rtf1 ` + String.raw`\page`.repeat(501) + "}"))).toThrow(
204 "500 pages",
205 );
206 });
207
208 it("decodes declared rich text code pages for raw bytes and escaped byte runs", () => {
209 const input = new TextEncoder().encode(
210 String.raw`{\rtf1\ansi\ansicpg1251 A \'c0\par\ansicpg932\'82\'a0}`,
211 );
212 input[input.indexOf(65)] = 0xc0;
213 const result = openRtf(input.buffer);
214 if (result.type !== "document") throw new Error("Expected document");
215 expect(result.pages[0]!.html).toBe("<p>А А<br>あ</p>");
216 expect(() => openRtf(bytes(String.raw`{\rtf1\ansicpg99999 text}`))).toThrow("code page");
217 });
218
219 it("resolves scoped ODF namespaces and explicit spreadsheet whitespace", async () => {
220 const archive = new JSZip().file(
221 "content.xml",
222 '<o:document-content xmlns:o="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:t="urn:oasis:names:tc:opendocument:xmlns:table:1.0"><o:body><o:spreadsheet><t:table t:name="Accounts & names"><t:table-row><t:table-cell><p xmlns="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:x="urn:oasis:names:tc:opendocument:xmlns:text:1.0">Account<s/>Name<s x:c="3"/>A<tab/>B<line-break/>C</p></t:table-cell></t:table-row></t:table></o:spreadsheet></o:body></o:document-content>',
223 );
224 const result = await openDocument(archive, "ods");
225 if (result.type !== "ods") throw new Error("Expected workbook");
226 expect(result.sheets[0]!.name).toBe("Accounts & names");
227 expect(result.sheets[0]!.rows[0]).toEqual(["Account Name A\tB\nC"]);
228 });
229
230 it("stops repeated slide images before encoding beyond the output budget", async () => {
231 const pixels = new Uint8Array(4 * 1024 * 1024);
232 pixels.set(
233 Buffer.from(
234 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",
235 "base64",
236 ),
237 );
238 const archive = new JSZip()
239 .file(
240 "content.xml",
241 '<o:document-content xmlns:o="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:d="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:l="http://www.w3.org/1999/xlink"><o:body>' +
242 '<d:page><d:image l:href="picture.png"/></d:page>'.repeat(500) +
243 "</o:body></o:document-content>",
244 )
245 .file("picture.png", pixels);
246 const image = archive.file("picture.png")!;
247 const read = vi.spyOn(image, "async");
248 await expect(openDocument(archive, "odp")).rejects.toThrow("too large");
249 expect(read.mock.calls.filter(([type]) => type === "base64")).toHaveLength(2);
250 expect(read).toHaveBeenCalledTimes(5);
251 });
252
253 it("reads saved notebook cells and preferred outputs without executing code", () => {
254 const result = openNotebook(
255 bytes(
256 JSON.stringify({
257 nbformat: 4,
258 metadata: { language_info: { name: "python" } },
259 cells: [
260 { cell_type: "markdown", source: ["# Results"] },
261 {
262 cell_type: "code",
263 source: ["print(42)"],
264 outputs: [
265 { output_type: "stream", text: ["\n "] },
266 { output_type: "display_data", data: {} },
267 { data: { "text/html": [""] } },
268 { data: { "text/html": [], "text/plain": "array fallback" } },
269 { data: { "text/html": "", "text/plain": "string fallback" } },
270 { data: { "text/html": " ", "text/plain": "space fallback" } },
271 { output_type: "stream", text: ["42\n"] },
272 { data: { "text/html": ["<b>Results</b>"], "text/plain": ["Results"] } },
273 ],
274 },
275 ],
276 }),
277 ),
278 );
279 expect(result).toEqual({
280 type: "notebook",
281 language: "python",
282 cells: [
283 { kind: "markdown", source: "# Results", outputs: [] },
284 {
285 kind: "code",
286 source: "print(42)",
287 outputs: [
288 { kind: "text", text: "array fallback" },
289 { kind: "text", text: "string fallback" },
290 { kind: "text", text: "space fallback" },
291 { kind: "text", text: "42\n" },
292 { kind: "html", text: "<b>Results</b>" },
293 ],
294 },
295 ],
296 });
297 expect(() => openNotebook(bytes('{"nbformat":3,"cells":[]}'))).toThrow("version 4");
298 expect(() =>
299 openNotebook(
300 bytes(JSON.stringify({ nbformat: 4, cells: Array.from({ length: 501 }, () => ({})) })),
301 ),
302 ).toThrow("500 cells");
303 });
304
305 it("bounds repeated OpenDocument spreadsheet cells and keeps sheet names and values", async () => {
306 const archive = new JSZip().file(
307 "content.xml",
308 '<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"><office:body><office:spreadsheet><table:table table:name="Budget"><table:table-row table:number-rows-repeated="999999999"><table:table-cell table:number-columns-repeated="999999999"><text:p>Research & design</text:p></table:table-cell></table:table-row></table:table></office:spreadsheet></office:body></office:document-content>',
309 );
310 const result = await openDocument(archive, "ods");
311 expect(result.type).toBe("ods");
312 if (result.type !== "ods") throw new Error("Expected workbook");
313 expect(result.sheets[0]!.name).toBe("Budget");
314 expect(result.sheets[0]!.truncated).toBe(true);
315 expect(result.sheets[0]!.rows).toHaveLength(500);
316 expect(result.sheets[0]!.rows[0]).toHaveLength(50);
317 expect(result.sheets[0]!.rows[0]![0]).toBe("Research & design");
318 });
319
320 it.each([1, 500])("ignores styled ODS filler after %s populated rows", async (count) => {
321 const archive = new JSZip().file(
322 "content.xml",
323 `<office:document><table:table><table:table-row table:number-rows-repeated="${count}"><table:table-cell><text:p>North</text:p></table:table-cell><table:table-cell table:number-columns-repeated="1024"/></table:table-row><table:table-row table:number-rows-repeated="1048570"><table:table-cell table:number-columns-repeated="1024"/></table:table-row></table:table></office:document>`,
324 );
325 const result = await openDocument(archive, "ods");
326 if (result.type !== "ods") throw new Error("Expected workbook");
327 expect(result.sheets[0]).toMatchObject({ rowCount: count, columns: 1, truncated: false });
328 expect(result.sheets[0]!.rows).toEqual(Array.from({ length: count }, () => ["North"]));
329 });
330
331 it.each([2, 999999])(
332 "preserves internal ODS gaps of %s rows and reports real overflow",
333 async (gap) => {
334 const archive = new JSZip().file(
335 "content.xml",
336 `<office:document><table:table><table:table-row><table:table-cell><text:p>First</text:p></table:table-cell></table:table-row><table:table-row table:number-rows-repeated="${gap}"><table:table-cell/></table:table-row><table:table-row><table:table-cell table:number-columns-repeated="2"/><table:table-cell><text:p>Last</text:p></table:table-cell></table:table-row></table:table></office:document>`,
337 );
338 const result = await openDocument(archive, "ods");
339 if (result.type !== "ods") throw new Error("Expected workbook");
340 expect(result.sheets[0]).toMatchObject({
341 rowCount: Math.min(gap + 2, 500),
342 columns: gap === 2 ? 3 : 1,
343 truncated: gap !== 2,
344 });
345 expect(result.sheets[0]!.rows[1]).toEqual([]);
346 if (gap === 2) expect(result.sheets[0]!.rows[3]).toEqual(["", "", "Last"]);
347 },
348 );
349
350 it.each(["odt", "odp"] as const)("reads %s text and rejects XML entities", async (kind) => {
351 const archive = new JSZip().file(
352 "content.xml",
353 `<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"><office:body>${kind === "odt" ? "<office:text><text:p>Field notes</text:p></office:text>" : '<draw:page draw:name="Overview"><text:h>Launch plan</text:h></draw:page>'}</office:body></office:document-content>`,
354 );
355 const result = await openDocument(archive, kind);
356 expect(result.type).toBe("document");
357 if (result.type !== "document") throw new Error("Expected document");
358 expect(result.pages[0]!.html).toContain(kind === "odt" ? "Field notes" : "Launch plan");
359 archive.file(
360 "content.xml",
361 '<!DOCTYPE x [<!ENTITY external SYSTEM "file:///etc/passwd">]><x>&external;</x>',
362 );
363 await expect(openDocument(archive, kind)).rejects.toThrow("unsupported XML");
364 });
365
366 it("reads EPUB chapters in spine order and removes active and remote content", async () => {
367 const archive = new JSZip()
368 .file(
369 "META-INF/container.xml",
370 '<container><rootfiles><rootfile full-path="Book/book.opf"/></rootfiles></container>',
371 )
372 .file(
373 "Book/book.opf",
374 '<package><manifest><item id="a" href="one.xhtml" media-type="application/xhtml+xml"/><item id="b" href="two&&&.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="b"/><itemref idref="a"/></spine></package>',
375 )
376 .file(
377 "Book/one.xhtml",
378 '<html><head><title>First</title></head><body><h1>First chapter</h1><img src="cover.png" alt="Cover"/><img src="https://example.com/tracker.png"/><script>alert(1)</script><style>@import "https://example.com/style.css";</style></body></html>',
379 )
380 .file(
381 "Book/two&&&.xhtml",
382 '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html><head><title>Second</title></head><body><h1>Second chapter</h1><p>A B © — ≂̸ &lt;</p><img src="cover.png" alt="© ≂̸"/></body></html>',
383 )
384 .file(
385 "Book/cover.png",
386 Buffer.from(
387 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",
388 "base64",
389 ),
390 );
391 const result = await openEpub(archive);
392 expect(result.type).toBe("document");
393 if (result.type !== "document") throw new Error("Expected document");
394 expect(result.pages.map((page) => page.title)).toEqual(["Second", "First"]);
395 expect(result.pages[0]!.html).toContain("A\u00a0B © — ≂̸ &lt;");
396 expect(result.pages[0]!.html).toContain('alt="© ≂̸"');
397 expect(result.pages[1]!.html).toContain('src="data:image/png;base64,');
398 expect(result.pages[1]!.html).not.toMatch(/https:|script|alert/);
399 });
400});