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

FilePreviewPanel.test.ts

777 lines38.9 KB

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 { promptFileCommentEntries, remapFileCommentAnnotations } from "./fileCommentAnnotations";
9import {
10 filePreviewReadErrorMessage,
11 isMarkdownPreviewFile,
12 resolveFilePreviewPath,
13 shouldShowFileExplorer,
14 workspaceAssetResource,
15} from "./filePreviewMode";
16​
17const decodeReadError = Schema.decodeSync(ProjectReadFileError);
18​
19describe("file preview read errors", () => {
20 // regression: #15628 read errors from servers without attempted paths keep their own message
21 it("preserves the public message from older servers", () => {
22 const error = decodeReadError({
23 _tag: "ProjectReadFileError",
24 message: "Legacy file read failure.",
25 });
26 expect(filePreviewReadErrorMessage(error)).toBe("Legacy file read failure.");
27 });
28});
29​
30describe("file comment annotations", () => {
31 it("keeps an annotation range attached when Pierre remaps its anchor line", () => {
32 expect(
33 remapFileCommentAnnotations([
34 {
35 lineNumber: 20,
36 metadata: {
37 entries: [
38 {
39 id: "comment-1",
40 kind: "comment",
41 startLine: 7,
42 endLine: 16,
43 text: "Keep this guarded.",
44 },
45 ],
46 },
47 },
48 ]),
49 ).toEqual([
50 {
51 lineNumber: 20,
52 metadata: {
53 entries: [
54 {
55 id: "comment-1",
56 kind: "comment",
57 startLine: 11,
58 endLine: 20,
59 text: "Keep this guarded.",
60 },
61 ],
62 },
63 },
64 ]);
65 });
66​
67 it("shows only drafts and comments still in the prompt", () => {
68 const entry = (id: string, kind: "draft" | "comment") => ({
69 id,
70 kind,
71 startLine: 3,
72 endLine: 3,
73 text: "",
74 });
75 expect(
76 promptFileCommentEntries(
77 [entry("sent", "comment"), entry("new", "draft"), entry("kept", "comment")],
78 new Set(["kept"]),
79 ),
80 ).toEqual([entry("new", "draft"), entry("kept", "comment")]);
81 });
82});
83​
84describe("isMarkdownPreviewFile", () => {
85 it("recognizes markdown and MDX files case-insensitively", () => {
86 expect(isMarkdownPreviewFile("README.md")).toBe(true);
87 expect(isMarkdownPreviewFile("docs/guide.MDX")).toBe(true);
88 expect(isMarkdownPreviewFile("docs/guide.MARKDOWN")).toBe(true);
89 expect(isMarkdownPreviewFile("docs/guide.mdown")).toBe(true);
90 expect(isMarkdownPreviewFile("docs/guide.mkd")).toBe(true);
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([
154 ["control symbols", String.raw`{\rtf1 Jean\_Luc\-X\~Y}`, "Jean\u2011Luc\u00adX\u00a0Y"],
155 [
156 "named spaces, joiners and direction marks",
157 String.raw`{\rtf1 A\tab B\emspace C\enspace D\qmspace E\zwj F\zwnj G\zwbo H\ltrmark I\rtlmark J}`,
158 "A\tB\u2003C\u2002D\u2005E\u200dF\u200cG\u200bH\u200eI\u200fJ",
159 ],
160 ["a Unicode fallback", String.raw`{\rtf1 Jean\u8209\_Luc}`, "Jean\u2011Luc"],
161 [
162 "visible text around hidden character formatting",
163 String.raw`{\rtf1 A{\v hidden{\v0 B}hidden}C\v hidden\v0 D\v hidden\plain E}`,
164 "ABCDE",
165 ],
166 ["a tracked replacement", String.raw`{\rtf1 aaa{\deleted bbb}{\revised BBB}ccc}`, "aaaBBBccc"],
167 [
168 "text after a deletion reset",
169 String.raw`{\rtf1 A\deleted old\deleted0 B\deleted old\plain C}`,
170 "ABC",
171 ],
172 [
173 "text around a deleted Unicode span",
174 String.raw`{\rtf1 A{\deleted\uc1\u945\deleted0 old}B}`,
175 "AB",
176 ],
177 ])("keeps the text of %s", (_name, source, expected) => {
178 const result = openRtf(bytes(source));
179 if (result.type !== "document") throw new Error("Expected document");
180 expect(result.pages[0]!.html.replaceAll(/<[^>]*>/g, "")).toBe(expected);
181 });
182​
183 it.each(["?", String.raw`\'3f`, String.raw`\\`])(
184 "consumes skipped rich text Unicode fallback %s",
185 (fallback) => {
186 const result = openRtf(bytes(String.raw`{\rtf1{\*\unknown\u945` + fallback + "}Hello}"));
187 if (result.type !== "document") throw new Error("Expected document");
188 expect(result.pages[0]!.html).toBe("<p>Hello</p>");
189 },
190 );
191​
192 it("bounds EPUB markup made entirely of empty allowed elements", async () => {
193 const archive = new JSZip()
194 .file(
195 "META-INF/container.xml",
196 '<container><rootfiles><rootfile full-path="book.opf"/></rootfiles></container>',
197 )
198 .file(
199 "book.opf",
200 '<package><manifest><item id="a" href="chapter.xhtml" media-type="application/xhtml+xml"/></manifest><spine>' +
201 '<itemref idref="a"/>'.repeat(30) +
202 "</spine></package>",
203 )
204 .file("chapter.xhtml", "<html><body>" + "<figcaption/>".repeat(30_000) + "</body></html>");
205 await expect(openEpub(archive)).rejects.toMatchObject({ code: "rendered-too-large" });
206 });
207​
208 it("decodes rich text formatting and Unicode without showing hidden destinations", () => {
209 const result = openRtf(
210 bytes(
211 String.raw`{\rtf1\ansi{\fonttbl{\f0 Hidden font;}}Hello \b bold\b0\par Unicode: \u945?{\*\unknown hidden\_\emspace\zwj}{\field{\*\fldinst HYPERLINK "https://example.com"}{\fldrslt visible}}}`,
212 ),
213 );
214 expect(result.type).toBe("document");
215 if (result.type !== "document") throw new Error("Expected document");
216 const html = result.pages[0]!.html;
217 expect(html.replaceAll(/<[^>]*>/g, "")).toBe("Hello boldUnicode: αvisible");
218 expect(html).toContain("<strong>");
219 expect(html).not.toContain("https:");
220 const styled = openRtf(
221 bytes(
222 "{\\rtf1\\ansi\\b \\uc0\\u55357 \\u56960 Launch\\b0 \\i\\uc1\\u-10187?\\u-8904?\\i0}",
223 ),
224 );
225 if (styled.type !== "document") throw new Error("Expected document");
226 expect(styled.pages[0]!.html).toBe("<p><strong>🚀 Launch</strong> <em>𝔸</em></p>");
227 const fallbacks = openRtf(bytes("{\\rtf1\\b\\uc1\\u-10179\\_\\uc0\\u-8576 }"));
228 if (fallbacks.type !== "document") throw new Error("Expected document");
229 expect(fallbacks.pages[0]!.html).toBe("<p><strong>🚀</strong></p>");
230 const escapedBreak = openRtf(bytes("{\\rtf1\\b A\\u66\\\nC\\par D}"));
231 if (escapedBreak.type !== "document") throw new Error("Expected document");
232 expect(escapedBreak.pages[0]!.html).toBe("<p><strong>ABC</strong><br><strong>D</strong></p>");
233 });
234​
235 it("breaks lines at the paragraph and line breaks TextEdit writes", () => {
236 const html = (rtf: string) => {
237 const result = openRtf(bytes(rtf));
238 if (result.type !== "document") throw new Error("Expected document");
239 return result.pages.map((page) => page.html);
240 };
241 const textEdit = String.raw`{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}
242\pard\f0\fs24 \cf0 First\
243Second\
245Third}`;
246 const expected = html(
247 String.raw`{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\pard\f0\fs24 \cf0 First\par Second\par \par Third}`,
248 );
249 expect(html(textEdit)).toEqual(expected);
250 expect(html(textEdit.replaceAll("\n", "\r\n"))).toEqual(expected);
251 const lineBreak = html(String.raw`{\rtf1\ansi First line\line Second line}`);
252 expect(lineBreak).toEqual(["<p>First line<br>Second line</p>"]);
253 expect(html(String.raw`{\rtf1\ansi{\v\line\line\line}First line\line Second line}`)).toEqual(
254 lineBreak,
255 );
256 expect(html(String.raw`{\rtf1\ansi First line\uc0\u8232 Second line}`)).toEqual(lineBreak);
257 expect(html(String.raw`{\rtf1\ansi First line\u8232?Second line{\deleted\u8232?}}`)).toEqual(
258 lineBreak,
259 );
260 });
261​
262 it("preserves rich text page breaks and formatting without splitting hidden destinations", () => {
263 const result = openRtf(
264 bytes(String.raw`{\rtf1\b First\page Second\b0{\*\unknown \page hidden}\page Third\page}`),
265 );
266 if (result.type !== "document") throw new Error("Expected document");
267 expect(result.navigation).toBe("page");
268 expect(result.pages.map((page) => page.html)).toEqual([
269 "<p><strong>First</strong></p>",
270 "<p><strong>Second</strong></p>",
271 "<p>Third</p>",
272 ]);
273 expect(() => openRtf(bytes(String.raw`{\rtf1 ` + String.raw`\page`.repeat(501) + "}"))).toThrow(
274 expect.objectContaining({ code: "rtf-too-many-pages" }),
275 );
276 });
277​
278 it("starts a new line at rich text section and column breaks", () => {
279 const result = openRtf(
280 bytes(
281 String.raw`{\rtf1\ansi\sectd\cols2\pard North quota: 120\column South quota: 240\page East quota: 360\sect\sectd\pard West quota: 480\par}`,
282 ),
283 );
284 if (result.type !== "document") throw new Error("Expected document");
285 expect(result.pages.map((page) => page.html)).toEqual([
286 "<p>North quota: 120<br>South quota: 240</p>",
287 "<p>East quota: 360<br>West quota: 480<br></p>",
288 ]);
289 const written = openRtf(
290 bytes(String.raw`{\rtf1\ansi First\par\sect\sectd Second\par\column Third\page\sect Fourth}`),
291 );
292 if (written.type !== "document") throw new Error("Expected document");
293 expect(written.pages.map((page) => page.html)).toEqual([
294 "<p>First<br>Second<br>Third</p>",
295 "<p>Fourth</p>",
296 ]);
297 });
298​
299 it("decodes declared rich text code pages for raw bytes and escaped byte runs", () => {
300 const input = new TextEncoder().encode(
301 String.raw`{\rtf1\ansi\ansicpg1251 A \'c0\par\ansicpg932\'82\'a0}`,
302 );
303 input[input.indexOf(65)] = 0xc0;
304 const result = openRtf(input.buffer);
305 if (result.type !== "document") throw new Error("Expected document");
306 expect(result.pages[0]!.html).toBe("<p>А А<br>あ</p>");
307 for (const header of [String.raw`\mac`, String.raw`\mac\ansicpg10000`]) {
308 const mac = openRtf(bytes(String.raw`{\rtf1` + header + String.raw` Caf\'8e Cr\'8fme}`));
309 if (mac.type !== "document") throw new Error("Expected document");
310 expect(mac.pages[0]!.html).toBe("<p>Café Crème</p>");
311 }
312 for (const [rtf, expected] of [
313 [String.raw`{\rtf1\ansi\ansicpg0 Caf\'e9}`, "<p>Café</p>"],
314 [String.raw`{\rtf1\ansi\ansicpg866 \'8f\'e0\'a8\'a2\'a5\'e2}`, "<p>Привет</p>"],
315 [
316 String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl\f0\froman\fcharset0 Times-Roman;}\f0 \'805 caf\'e9}`,
317 "<p>€5 café</p>",
318 ],
319 [
320 String.raw`{\rtf1\mac\ansicpg10000{\fonttbl\f0\fnil\fcharset0 LucidaGrande;}\f0 pridr\'9eana}`,
321 "<p>pridržana</p>",
322 ],
323 [
324 String.raw`{\rtf1\ansi\ansicpg1251{\fonttbl{\f0\fnil\fcharset0\cpg1251 Arial;}{\f1\fnil\fcharset204 Arial{\*\fontfile\cpg1252 arial.ttf};}}\f0 \'cf\'f0\'e8\f1\'e2\'e5\'f2}`,
325 "<p>Привет</p>",
326 ],
327 [
328 String.raw`{\rtf1\ansi\ansicpg54936 Quarterly notes: \'d6\'d0\'ce\'c4 \'95\'32\'82\'36 \'82\'35\'8f\'33 \uc2\u20320\'c4\'e3 done\par}`,
329 "<p>Quarterly notes: 中文 𠀀 龦 你 done<br></p>",
330 ],
331 [
332 String.raw`{\rtf1\ansi{\fonttbl{\f0\fnil\fcharset0\cpg54936 SimSun;}}\f0 \'d6\'d0\'ce\'c4}`,
333 "<p>中文</p>",
334 ],
335 ] as const) {
336 const decoded = openRtf(bytes(rtf));
337 if (decoded.type !== "document") throw new Error("Expected document");
338 expect(decoded.pages[0]!.html).toBe(expected);
339 }
340 expect(() => openRtf(bytes(String.raw`{\rtf1\ansicpg99999 text}`))).toThrow(
341 expect.objectContaining({ code: "rtf-code-page" }),
342 );
343 });
344​
345 it("resolves scoped ODF namespaces and explicit spreadsheet whitespace", async () => {
346 const archive = new JSZip().file(
347 "content.xml",
348 '<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 &amp; 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 &amp; <![CDATA[&amp;]]></p></t:table-cell></t:table-row></t:table></o:spreadsheet></o:body></o:document-content>',
349 );
350 const result = await openDocument(archive, "ods");
351 if (result.type !== "ods") throw new Error("Expected workbook");
352 expect(result.sheets[0]!.name).toBe("Accounts & names");
353 expect(result.sheets[0]!.rows[0]).toEqual(["Account Name A\tB\nC & &amp;"]);
354 });
355​
356 it("stops repeated slide images before encoding beyond the output budget", async () => {
357 const pixels = new Uint8Array(4 * 1024 * 1024);
358 pixels.set(
359 Buffer.from(
360 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",
361 "base64",
362 ),
363 );
364 const archive = new JSZip()
365 .file(
366 "content.xml",
367 '<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>' +
368 '<d:page><d:image l:href="picture.png"/></d:page>'.repeat(500) +
369 "</o:body></o:document-content>",
370 )
371 .file("picture.png", pixels);
372 const image = archive.file("picture.png")!;
373 const read = vi.spyOn(image, "async");
374 await expect(openDocument(archive, "odp")).rejects.toMatchObject({
375 code: "rendered-too-large",
376 });
377 expect(read.mock.calls.filter(([type]) => type === "base64")).toHaveLength(2);
378 expect(read).toHaveBeenCalledTimes(5);
379 });
380​
381 it("reads saved notebook cells and preferred outputs without executing code", () => {
382 const result = openNotebook(
383 bytes(
384 JSON.stringify({
385 nbformat: 4,
386 metadata: { language_info: { name: "python" } },
387 cells: [
388 { cell_type: "markdown", source: ["# Results"] },
389 {
390 cell_type: "code",
391 source: ["print(42)"],
392 outputs: [
393 { output_type: "stream", text: ["\n "] },
394 { output_type: "display_data", data: {} },
395 { data: { "text/html": [""] } },
396 { data: { "text/html": [], "text/plain": "array fallback" } },
397 { data: { "text/html": "", "text/plain": "\u001b[1mstring fallback\u001b[0m" } },
398 { data: { "text/html": " ", "text/plain": "space fallback" } },
399 { output_type: "stream", text: ["\u001b[", "32m42\u001b[0m\n"] },
400 {
401 output_type: "stream",
402 name: "stderr",
403 text: ["\r 10%|# |", "\r100%|##########|\n", "done\r\n", "🚀 ready\rX\n"],
404 },
405 { data: { "text/html": ["<b>Results</b>"], "text/plain": ["Results"] } },
406 ],
407 },
408 ],
409 }),
410 ),
411 );
412 expect(result).toEqual({
413 type: "notebook",
414 language: "python",
415 cells: [
416 { kind: "markdown", source: "# Results", outputs: [] },
417 {
418 kind: "code",
419 source: "print(42)",
420 outputs: [
421 { kind: "text", text: "array fallback" },
422 { kind: "text", text: "string fallback" },
423 { kind: "text", text: "space fallback" },
424 { kind: "text", text: "42\n" },
425 { kind: "text", text: "100%|##########|\ndone\nX ready\n" },
426 { kind: "html", text: "<b>Results</b>" },
427 ],
428 },
429 ],
430 });
431 for (const name of ["", "Питон"]) {
432 const blank = { nbformat: 4, metadata: { language_info: { name } }, cells: [] };
433 expect(openNotebook(bytes(JSON.stringify(blank)))).toMatchObject({ language: "text" });
434 }
435 // IPython traceback frames can omit trailing newlines or place ANSI resets after them.
436 const failed = openNotebook(
437 bytes(
438 JSON.stringify({
439 nbformat: 4,
440 cells: [
441 {
442 cell_type: "code",
443 source: "fail()",
444 outputs: [
445 {
446 output_type: "error",
447 traceback: [
448 "-----",
449 "ValueError Traceback (most recent call last)",
450 "Cell In[1], line 4\n----> 4 fail()\n",
451 "Cell In[1], line 2, in fail()\n----> 2 raise ValueError()\n",
452 "ValueError: preview proof",
453 ],
454 },
455 {
456 output_type: "error",
457 traceback: [
458 "Traceback (most recent call last):\n",
459 " Cell In[2], line 5\n fail()\n",
460 "ValueError: preview proof\n",
461 ],
462 },
463 {
464 output_type: "error",
465 traceback: [
466 "\u001b[31mTraceback (most recent call last):\n\u001b[0m",
467 "\u001b[38:2::255:0:0mCell In[3], line 1\n----> 1 fail()\n\u001b[0m\u001b[39m",
468 "\u001b[31mValueError: preview proof\u001b[0m",
469 "final entry",
470 ],
471 },
472 {
473 output_type: "error",
474 ename: "ZeroDivisionError",
475 evalue: "division by zero",
476 traceback: [],
477 },
478 {
479 output_type: "error",
480 evalue: "\u001b[31mbad input\u001b[0m",
481 traceback: [],
482 },
483 {
484 output_type: "error",
485 ename: "RuntimeError",
486 evalue: "kernel reset",
487 traceback: ["\u001b[31m\u001b[0m", " \n"],
488 },
489 ],
490 },
491 ],
492 }),
493 ),
494 );
495 if (failed.type !== "notebook") throw new Error("Expected notebook");
496 expect(failed.cells[0]!.outputs).toEqual([
497 {
498 kind: "text",
499 text: "-----\nValueError Traceback (most recent call last)\nCell In[1], line 4\n----> 4 fail()\nCell In[1], line 2, in fail()\n----> 2 raise ValueError()\nValueError: preview proof",
500 },
501 {
502 kind: "text",
503 text: "Traceback (most recent call last):\n Cell In[2], line 5\n fail()\nValueError: preview proof\n",
504 },
505 {
506 kind: "text",
507 text: "Traceback (most recent call last):\nCell In[3], line 1\n----> 1 fail()\nValueError: preview proof\nfinal entry",
508 },
509 { kind: "text", text: "ZeroDivisionError: division by zero" },
510 { kind: "text", text: "bad input" },
511 { kind: "text", text: "RuntimeError: kernel reset" },
512 ]);
513 expect(() => openNotebook(bytes('{"nbformat":3,"cells":[]}'))).toThrow(
514 expect.objectContaining({ code: "notebook-unsupported" }),
515 );
516 expect(() =>
517 openNotebook(
518 bytes(JSON.stringify({ nbformat: 4, cells: Array.from({ length: 501 }, () => ({})) })),
519 ),
520 ).toThrow(expect.objectContaining({ code: "notebook-unsupported" }));
521 });
522​
523 it("bounds repeated OpenDocument spreadsheet cells and keeps sheet names and values", async () => {
524 const archive = new JSZip().file(
525 "content.xml",
526 '<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 &amp; design</text:p></table:table-cell></table:table-row></table:table></office:spreadsheet></office:body></office:document-content>',
527 );
528 const result = await openDocument(archive, "ods");
529 expect(result.type).toBe("ods");
530 if (result.type !== "ods") throw new Error("Expected workbook");
531 expect(result.sheets[0]!.name).toBe("Budget");
532 expect(result.sheets[0]!.truncated).toBe(true);
533 expect(result.sheets[0]!.rows).toHaveLength(500);
534 expect(result.sheets[0]!.rows[0]).toHaveLength(50);
535 expect(result.sheets[0]!.rows[0]![0]).toBe("Research & design");
536 });
537​
538 it("hides ODS values kept in cells a merge covers", async () => {
539 const archive = new JSZip().file(
540 "content.xml",
541 '<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="Merged">' +
542 '<table:table-row><table:table-cell table:number-columns-spanned="4" table:number-rows-spanned="2"><text:p>Total</text:p></table:table-cell><table:covered-table-cell office:value-type="float" office:value="2"><text:p>2</text:p></table:covered-table-cell><table:covered-table-cell table:number-columns-repeated="2"/><table:table-cell><text:p>Lead</text:p></table:table-cell></table:table-row>' +
543 '<table:table-row><table:covered-table-cell office:value-type="string" office:string-value="Below"/><table:covered-table-cell table:number-columns-repeated="3"/><table:table-cell><text:p>Q2</text:p></table:table-cell></table:table-row>' +
544 "</table:table></office:spreadsheet></office:body></office:document-content>",
545 );
546 const result = await openDocument(archive, "ods");
547 if (result.type !== "ods") throw new Error("Expected workbook");
548 expect(result.sheets[0]!.rows).toEqual([
549 ["Total", "", "", "", "Lead"],
550 ["", "", "", "", "Q2"],
551 ]);
552 });
553​
554 it("reads an ODS time cell that has no display paragraph", async () => {
555 const archive = new JSZip().file(
556 "content.xml",
557 `<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"><office:body><office:spreadsheet><table:table table:name="Values"><table:table-row><table:table-cell office:value-type="time" office:time-value="PT03H30M00S"></table:table-cell></table:table-row></table:table></office:spreadsheet></office:body></office:document-content>`,
558 );
559 const result = await openDocument(archive, "ods");
560 if (result.type !== "ods") throw new Error("Expected workbook");
561 expect(result.sheets[0]!.rows).toEqual([["PT03H30M00S"]]);
562 });
563​
564 it("reports zero columns for an empty ODS sheet", async () => {
565 const archive = new JSZip().file(
566 "content.xml",
567 '<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>' +
568 '<table:table table:name="Empty"><table:table-row table:number-rows-repeated="1048576"><table:table-cell table:number-columns-repeated="1024"/></table:table-row></table:table>' +
569 '<table:table table:name="Data"><table:table-row><table:table-cell><text:p>A</text:p></table:table-cell><table:table-cell><text:p>B</text:p></table:table-cell><table:table-cell><text:p>C</text:p></table:table-cell></table:table-row></table:table>' +
570 '<table:table table:name="Late"><table:table-row table:number-rows-repeated="500"><table:table-cell/></table:table-row><table:table-row><table:table-cell><text:p>Z</text:p></table:table-cell></table:table-row></table:table>' +
571 "</office:spreadsheet></office:body></office:document-content>",
572 );
573 const result = await openDocument(archive, "ods");
574 if (result.type !== "ods") throw new Error("Expected workbook");
575 expect(result.sheets[0]).toMatchObject({ rowCount: 0, columns: 0 });
576 expect(result.sheets[1]).toMatchObject({ rowCount: 1, columns: 3 });
577 expect(result.sheets[2]).toMatchObject({ rowCount: 500, columns: 1, truncated: true });
578 });
579​
580 it.each([1, 500])("ignores styled ODS filler after %s populated rows", async (count) => {
581 const archive = new JSZip().file(
582 "content.xml",
583 `<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>`,
584 );
585 const result = await openDocument(archive, "ods");
586 if (result.type !== "ods") throw new Error("Expected workbook");
587 expect(result.sheets[0]).toMatchObject({ rowCount: count, columns: 1, truncated: false });
588 expect(result.sheets[0]!.rows).toEqual(Array.from({ length: count }, () => ["North"]));
589 });
590​
591 it.each([2, 999999])(
592 "preserves internal ODS gaps of %s rows and reports real overflow",
593 async (gap) => {
594 const archive = new JSZip().file(
595 "content.xml",
596 `<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>`,
597 );
598 const result = await openDocument(archive, "ods");
599 if (result.type !== "ods") throw new Error("Expected workbook");
600 expect(result.sheets[0]).toMatchObject({
601 rowCount: Math.min(gap + 2, 500),
602 columns: gap === 2 ? 3 : 1,
603 truncated: gap !== 2,
604 });
605 expect(result.sheets[0]!.rows[1]).toEqual([]);
606 if (gap === 2) expect(result.sheets[0]!.rows[3]).toEqual(["", "", "Last"]);
607 },
608 );
609​
610 const approved = "<text:p>Approved <text:span>now</text:span></text:p>";
611 const approvedRow = `<tr>${"<td><p>Approved <span>now</span></p></td>".repeat(2)}</tr>`;
612 it.each([
613 [
614 "expands",
615 `<table:table-row>${`<table:table-cell>${approved}</table:table-cell>`.repeat(2)}</table:table-row><table:table-row table:number-rows-repeated="2"><table:table-cell table:number-columns-repeated="2">${approved}</table:table-cell></table:table-row>`,
616 approvedRow.repeat(3),
617 ],
618 [
619 "bounds",
620 '<table:table-row table:number-rows-repeated="999999999"><table:table-cell table:number-columns-repeated="999999999"><text:p>x</text:p></table:table-cell></table:table-row>',
621 `<tr>${"<td><p>x</p></td>".repeat(50)}</tr>`.repeat(500),
622 ],
623 ])("%s repeated ODT table rows and cells", async (_, rows, html) => {
624 const archive = new JSZip().file(
625 "content.xml",
626 `<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:text><table:table><table:table-column table:number-columns-repeated="2"/>${rows}</table:table></office:text></office:body></office:document-content>`,
627 );
628 const result = await openDocument(archive, "odt");
629 if (result.type !== "document") throw new Error("Expected document");
630 expect(result.pages[0]!.html).toBe(`<table>${html}</table>`);
631 });
632​
633 it("preserves ODT table colspan and rowspan on merged cells", async () => {
634 const archive = new JSZip().file(
635 "content.xml",
636 '<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:text><table:table><table:table-column table:number-columns-repeated="3"/>' +
637 '<table:table-row><table:table-cell table:number-columns-spanned="2"><text:p>Quarter</text:p></table:table-cell><table:covered-table-cell/><table:table-cell><text:p>Lead</text:p></table:table-cell></table:table-row>' +
638 '<table:table-row><table:table-cell table:number-rows-spanned="2"><text:p>North</text:p></table:table-cell><table:table-cell><text:p>Q1</text:p></table:table-cell><table:table-cell><text:p>Lead A</text:p></table:table-cell></table:table-row>' +
639 "<table:table-row><table:covered-table-cell><text:p>Hidden</text:p></table:covered-table-cell><table:table-cell><text:p>Q2</text:p></table:table-cell><table:table-cell><text:p>Lead B</text:p></table:table-cell></table:table-row>" +
640 '<table:table-row><table:table-cell table:number-columns-spanned="9999" table:number-rows-spanned="0"><text:p>Total</text:p></table:table-cell><table:table-cell table:number-columns-spanned="Infinity" table:number-rows-spanned="50.5"/></table:table-row>' +
641 '<table:table-row table:number-rows-repeated="2"><table:table-cell table:number-columns-spanned="2" table:number-rows-spanned="2"><table:table><table:table-row><table:table-cell table:number-rows-spanned="2"/></table:table-row></table:table></table:table-cell><table:table-cell table:number-columns-repeated="2" table:number-columns-spanned="2"/></table:table-row>' +
642 "</table:table></office:text></office:body></office:document-content>",
643 );
644 const result = await openDocument(archive, "odt");
645 if (result.type !== "document") throw new Error("Expected document");
646 expect(result.pages[0]!.html).toBe(
647 `<table><tr><td colspan="2"><p>Quarter</p></td><td><p>Lead</p></td></tr><tr><td rowspan="2"><p>North</p></td><td><p>Q1</p></td><td><p>Lead A</p></td></tr><tr><td><p>Q2</p></td><td><p>Lead B</p></td></tr><tr><td colspan="50"><p>Total</p></td><td></td></tr>${'<tr><td colspan="2"><table><tr><td rowspan="2"></td></tr></table></td><td></td><td></td></tr>'.repeat(2)}</table>`,
648 );
649 });
650​
651 // LibreOffice writes every index as the templates it was built from, then the built index.
652 const indexes = [
653 "table-of-content",
654 "illustration-index",
655 "table-index",
656 "object-index",
657 "user-index",
658 "alphabetical-index",
659 "bibliography",
660 ].map(
661 (name) =>
662 `<text:${name}><text:${name}-source><text:index-title-template>Index</text:index-title-template><text:${name}-entry-template><text:index-entry-text/><text:index-entry-span>: </text:index-entry-span><text:index-entry-page-number/></text:${name}-entry-template></text:${name}-source><text:index-body><text:index-title><text:p>Index</text:p></text:index-title><text:p>Field notes: 1</text:p></text:index-body></text:${name}>`,
663 );
664 it.each(["odt", "odp"] as const)("reads %s text and rejects unsupported XML", async (kind) => {
665 const archive = new JSZip().file(
666 "content.xml",
667 `<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" xmlns:presentation="urn:oasis:names:tc:opendocument:xmlns:presentation:1.0"><office:body>${kind === "odt" ? `<office:text><text:p>Field notes</text:p>${indexes.join("")}</office:text>` : '<draw:page draw:name="Overview"><text:h>Launch plan</text:h><presentation:notes><draw:frame><draw:text-box><text:p>Speaker only</text:p></draw:text-box></draw:frame></presentation:notes></draw:page>'}</office:body></office:document-content>`,
668 );
669 const result = await openDocument(archive, kind);
670 expect(result.type).toBe("document");
671 if (result.type !== "document") throw new Error("Expected document");
672 expect(result.pages[0]!.html).toContain(kind === "odt" ? "Field notes" : "Launch plan");
673 expect(result.pages[0]!.html).not.toContain("Speaker only");
674 if (kind === "odt")
675 expect(result.pages[0]!.html).toBe(
676 `<p>Field notes</p>${"<p>Index</p><p>Field notes: 1</p>".repeat(indexes.length)}`,
677 );
678 for (const source of [
679 '<!DOCTYPE x [<!ENTITY external SYSTEM "file:///etc/passwd">]><x>&external;</x>',
680 '<html><body><p title="<!--">x</p><!DOCTYPE x [<!ENTITY e "boom">]><b title="-->">&e;</b></body></html>',
681 '<html><body><p title="<![CDATA[">x</p><!DOCTYPE x [<!ENTITY e "boom">]><b title="]]>">&e;</b></body></html>',
682 '<!DOC<!DOCTYPE a>TYPE x [<!EN<!DOCTYPE a>TITY e "boom">]><x>&e;</x>',
683 '<?test <![CDATA[ ?><!DOCTYPE html [<!ENTITY e "boom">]><html><body><pre><![CDATA[x]]></pre></body></html>',
684 '<?test <!-- ?><!DOCTYPE html [<!ENTITY e "boom">]><html><body><!-- x --></body></html>',
685 "<html><body>" + "<!--".repeat(80_000) + "</body></html>",
686 "<html><body>" + "<![CDATA[".repeat(80_000) + "</body></html>",
687 ]) {
688 archive.file("content.xml", source);
689 await expect(openDocument(archive, kind)).rejects.toMatchObject({ code: "xml-invalid" });
690 }
691 });
692​
693 it("keeps OpenDocument image descriptions in image alt text", async () => {
694 const archive = new JSZip()
695 .file(
696 "content.xml",
697 '<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" xmlns:l="http://www.w3.org/1999/xlink" xmlns:s="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0">' +
698 '<office:body><office:text><text:p><draw:frame><draw:image l:href="picture.png"/><s:title>Logo</s:title><s:desc>Research &amp; &quot;Design&quot;</s:desc></draw:frame>Visible caption</text:p></office:text></office:body></office:document-content>',
699 )
700 .file(
701 "picture.png",
702 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",
703 { base64: true },
704 );
705​
706 const result = await openDocument(archive, "odt");
707 if (result.type !== "document") throw new Error("Expected document");
708 expect(result.pages[0]!.html).toMatch(
709 /^<p><img src="data:image\/png;base64,[^"]+" alt="Logo Research &amp; &quot;Design&quot;">Visible caption<\/p>$/,
710 );
711 });
712​
713 it("reads EPUB chapters in spine order and removes active and remote content", async () => {
714 const archive = new JSZip()
715 .file(
716 "META-INF/container.xml",
717 '<container><rootfiles><rootfile full-path="Book/book.opf"/></rootfiles></container>',
718 )
719 .file(
720 "Book/book.opf",
721 '<package><manifest><item id="a" href="one.xhtml" media-type="application/xhtml+xml"/><item id="b" href="two&amp;&#x26;&#38;.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="b"/><itemref idref="a"/></spine></package>',
722 )
723 .file(
724 "Book/one.xhtml",
725 `<html><head><title>${"a".repeat(119)}🚀</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>`,
726 )
727 .file(
728 "Book/two&&&.xhtml",
729 '<?xml-stylesheet href="a<b.css"?><!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&nbsp;B &copy; &mdash; &NotEqualTilde; &amp;lt;</p><pre><![CDATA[Use &amp; and &lt; literally]]></pre><pre><![CDATA[<!DOCTYPE html><!ENTITY author "Ada">]]></pre><!-- <!ENTITY note "x"> --><img src="cover.png" alt="&lt; &copy; &NotEqualTilde;"/></body></html>',
730 )
731 .file(
732 "Book/cover.png",
733 Buffer.from(
734 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",
735 "base64",
736 ),
737 );
738 const result = await openEpub(archive);
739 expect(result.type).toBe("document");
740 if (result.type !== "document") throw new Error("Expected document");
741 expect(result.pages.map((page) => page.title)).toEqual(["Second", "a".repeat(119)]);
742 expect(result.pages[0]!.html).toContain("A\u00a0B © — ≂̸ &amp;lt;");
743 expect(result.pages[0]!.html).toContain("<pre>Use &amp;amp; and &amp;lt; literally</pre>");
744 expect(result.pages[0]!.html).toContain(
745 "<pre>&lt;!DOCTYPE html&gt;&lt;!ENTITY author &quot;Ada&quot;&gt;</pre>",
746 );
747 expect(result.pages[0]!.html).toContain('alt="&lt; © ≂̸"');
748 expect(result.pages[1]!.html).toContain('src="data:image/png;base64,');
749 expect(result.pages[1]!.html).not.toMatch(/https:|script|alert/);
750 });
751​
752 it.each([
753 ["percent-encoded", "My%20Book/book%201.opf", "My Book/book 1.opf", "My Book/one.xhtml"],
754 ["literal percent", "My%20Book/book.opf", "My%20Book/book.opf", "My%20Book/one.xhtml"],
755 ["malformed percent", "Book%ZZ/book.opf", "Book%ZZ/book.opf", "Book%ZZ/one.xhtml"],
756 ])(
757 "reads EPUB packages with %s rootfile paths",
758 async (_label, fullPath, packagePath, chapterPath) => {
759 const archive = new JSZip()
760 .file(
761 "META-INF/container.xml",
762 `<container><rootfiles><rootfile full-path="${fullPath}"/></rootfiles></container>`,
763 )
764 .file(
765 packagePath,
766 '<package><manifest><item id="a" href="one.xhtml" media-type="application/xhtml+xml"/></manifest><spine><itemref idref="a"/></spine></package>',
767 )
768 .file(
769 chapterPath,
770 "<html><head><title>First</title></head><body><p>Hello</p></body></html>",
771 );
772 const result = await openEpub(archive);
773 if (result.type !== "document") throw new Error("Expected document");
774 expect(result.pages).toEqual([{ title: "First", html: "<p>Hello</p>" }]);
775 },
776 );
777});