@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 1,087 lines 51.9 KB
Raw
1 import { act, render } from "../../../test/render";
2 import { expect, it, vi } from "vite-plus/test";
3 import "~/index.css";
4
5 const { refresh, assetUrlState } = vi.hoisted(() => ({
6 refresh: vi.fn<() => Promise<string | null>>(),
7 assetUrlState: vi.fn<() => import("~/assets/assetUrls").AssetUrlState>(),
8 }));
9
10 vi.mock(import("~/assets/assetUrls"), async (original) => ({
11 ...(await original()),
12 useAssetUrlRefresh: () => refresh,
13 useAssetUrlState: assetUrlState,
14 }));
15 // The real source view highlights through a worker pool; the text it receives is what matters here.
16 // Never load the original: its highlighter graph can outlast waitFor on a cold CI browser.
17 vi.mock(import("./ReadOnlySourcePreview"), () => ({
18 default: ({ text, wordWrap }: { text: string; wordWrap?: boolean }) => (
19 <pre data-word-wrap={String(wordWrap)}>{text}</pre>
20 ),
21 }));
22
23 // The Word engine compiles about 30 MB of WebAssembly in a fresh worker per document, which took
24 // 10-17 s per test on loaded CI runners. These tests cover fetching, preparation and remounts, so
25 // the stand-in shows the prepared body's text instead of laying it out.
26 vi.mock(import("./office/WordDocument"), async () => {
27 const { use } = await import("react");
28 const { default: Zip } = await import("jszip");
29 const texts = new WeakMap<ArrayBuffer, Promise<string>>();
30 const read = (bytes: ArrayBuffer) =>
31 Zip.loadAsync(bytes)
32 .then((zip) => zip.file("word/document.xml")!.async("string"))
33 .then((xml) => xml.replace(/<[^>]+>/g, " "));
34 return {
35 default: ({ bytes }: { bytes: ArrayBuffer }) => {
36 let text = texts.get(bytes);
37 if (!text) texts.set(bytes, (text = read(bytes)));
38 return <pre>{use(text)}</pre>;
39 },
40 };
41 });
42
43 import { AttachmentFilePreview } from "./AttachmentFilePreview";
44 import JSZip from "jszip";
45 import { OFFICE_PREVIEW_MAX_COLUMNS, type OfficeWorkerResult } from "./officePreviewProtocol";
46 import { WORD_LIMITS } from "./officeArchive";
47 import { previewErrorText, previewFailureText } from "./previewFailureMessages";
48
49 it.each(["<w:body/>", "<w:body></w:body>"])(
50 "opens an empty Word document with %s",
51 async (body) => {
52 const { default: JSZip } = await import("jszip");
53 const { prepareOffice } = await import("./officeArchive");
54 const archive = new JSZip().file(
55 "word/document.xml",
56 `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">${body}</w:document>`,
57 );
58 const prepared = await prepareOffice(
59 await archive.generateAsync({ type: "arraybuffer" }),
60 "docx",
61 );
62 const result = await JSZip.loadAsync(prepared.bytes);
63 const xml = new DOMParser().parseFromString(
64 await result.file("word/document.xml")!.async("string"),
65 "application/xml",
66 );
67 expect(xml.querySelector("parsererror")).toBeNull();
68 expect(
69 xml.getElementsByTagNameNS(
70 "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
71 "body",
72 ),
73 ).toHaveLength(1);
74 },
75 );
76
77 it.each([false, true])(
78 "rejects excessive archive entries before JSZip (directories: %s)",
79 async (directories) => {
80 const { default: JSZip } = await import("jszip");
81 const { prepareOffice } = await import("./officeArchive");
82 const archive = new JSZip();
83 for (let i = 0; i < 4096; i++)
84 archive.file(`entry-${i}${directories ? "/" : ".txt"}`, "", { dir: directories });
85 const bytes = await archive.generateAsync({ type: "arraybuffer" });
86 const load = vi.spyOn(JSZip, "loadAsync");
87 try {
88 await expect(prepareOffice(bytes, "docx")).rejects.toThrow("2,048 entries");
89 expect(load).not.toHaveBeenCalled();
90 // The actual central-directory records must also be bounded if EOCD lies.
91 const view = new DataView(bytes);
92 view.setUint16(bytes.byteLength - 22 + 8, 1, true);
93 view.setUint16(bytes.byteLength - 22 + 10, 1, true);
94 await expect(prepareOffice(bytes, "docx")).rejects.toThrow("2,048 entries");
95 expect(load).not.toHaveBeenCalled();
96 } finally {
97 load.mockRestore();
98 }
99 },
100 );
101
102 it("rejects oversized embedded images before decoding pixels and retains ordinary images", async () => {
103 const { officeImageBitmap } = await import("./office/image-bitmap");
104 const canvas = new OffscreenCanvas(2, 3);
105 canvas.getContext("2d");
106 const blob = await canvas.convertToBlob({ type: "image/png" });
107 const bytes = await blob.arrayBuffer();
108 new DataView(bytes).setUint32(16, 12000);
109 new DataView(bytes).setUint32(20, 12000);
110 const decode = vi.spyOn(globalThis, "createImageBitmap");
111 try {
112 await expect(officeImageBitmap(new Blob([bytes]))).rejects.toThrow("pixel limit");
113 expect(decode).not.toHaveBeenCalled();
114 const bitmap = await officeImageBitmap(blob);
115 expect([bitmap.width, bitmap.height]).toEqual([2, 3]);
116 bitmap.close();
117 } finally {
118 decode.mockRestore();
119 }
120 });
121
122 it.each(["utf-16le", "utf-16be", "windows-1252"])(
123 "preserves %s Office XML and safe hyperlink targets",
124 async (encoding) => {
125 const { default: JSZip } = await import("jszip");
126 const { prepareOffice } = await import("./officeArchive");
127 const archive = new JSZip();
128 const encode = (text: string) => {
129 const xml = `<?xml version="1.0" encoding="${encoding}"?>${text}`;
130 if (encoding === "windows-1252") return Uint8Array.from(xml, (char) => char.charCodeAt(0));
131 const bytes = new Uint8Array(2 + xml.length * 2);
132 const view = new DataView(bytes.buffer);
133 const little = encoding === "utf-16le";
134 view.setUint16(0, 0xfeff, little);
135 for (let i = 0; i < xml.length; i++) view.setUint16(2 + i * 2, xml.charCodeAt(i), little);
136 return bytes;
137 };
138 archive.file(
139 "word/document.xml",
140 encode(
141 '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:t>café</w:t></w:r></w:p></w:body></w:document>',
142 ),
143 );
144 archive.file(
145 "word/_rels/document.xml.rels",
146 encode(
147 `<Relationships>${["https://example.com/page", "http://example.com", "mailto:maria@example.com", "javascript:alert(1)", "file:///tmp/private"].map((target, i) => `<Relationship Id="r${i}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" TargetMode="External" Target="${target}"/>`).join("")}</Relationships>`,
148 ),
149 );
150 const prepared = await prepareOffice(
151 await archive.generateAsync({ type: "arraybuffer" }),
152 "docx",
153 );
154 const result = await JSZip.loadAsync(prepared.bytes);
155 expect(await result.file("word/document.xml")!.async("string")).toContain("café");
156 const links = await result.file("word/_rels/document.xml.rels")!.async("string");
157 expect(links).toContain('encoding="UTF-8"');
158 expect(links).toContain("https://example.com/page");
159 expect(links).toContain("http://example.com");
160 expect(links).toContain("mailto:maria@example.com");
161 expect(links).not.toContain("javascript:");
162 expect(links).not.toContain("file:");
163 },
164 );
165
166 it.each([
167 ["", "worksheets/./sheet1.xml", false, false],
168 ["x:", "../xl/worksheets/sheet1.xml", false, false],
169 ["", "/xl/worksheets/sheet1.xml", true, false],
170 ["", "worksheets/sheet1.xml", false, true],
171 ["", "worksheets/sheet1.xml", true, true],
172 ])(
173 "preserves %sworksheet metadata with relationship target %s",
174 async (prefix, target, empty, localPrefix) => {
175 const { default: JSZip } = await import("jszip");
176 const archive = new JSZip();
177 const ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
178 archive.file(
179 "xl/workbook.xml",
180 '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Chart" sheetId="2" r:id="c"/><sheet name="Sheet" sheetId="1" r:id="s"/></sheets></workbook>',
181 );
182 archive.file(
183 "xl/_rels/workbook.xml.rels",
184 `<Relationships><Relationship Id="s" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="${target}"/><Relationship Id="c" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet" Target="chartsheets/sheet1.xml"/></Relationships>`,
185 );
186 archive.file(
187 "xl/worksheets/sheet1.xml",
188 `<${prefix}worksheet xmlns${prefix ? ":x" : ""}="${ns}"><${prefix}dimension ref="XFD1048576"/><${prefix}sheetViews><${prefix}sheetView showGridLines="0"/></${prefix}sheetViews><${prefix}sheetFormatPr defaultColWidth="30"/><${prefix}cols><${prefix}col min="${OFFICE_PREVIEW_MAX_COLUMNS - 1}" max="${OFFICE_PREVIEW_MAX_COLUMNS + 10}" width="20"/><${prefix}col min="${OFFICE_PREVIEW_MAX_COLUMNS + 1}" max="${OFFICE_PREVIEW_MAX_COLUMNS + 30}" hidden="1"/></${prefix}cols><${prefix}sheetData><${prefix}row ht="42" customHeight="1" hidden="1"><${prefix}c r="A50" t="inlineStr"><${prefix}is><${prefix}t>${"value".repeat(1000)}</${prefix}t></${prefix}is></${prefix}c></${prefix}row></${prefix}sheetData><${prefix}mergeCells><${prefix}mergeCell ref="XFD1048576"/></${prefix}mergeCells></${prefix}worksheet>`
189 .replace(
190 /<((?:x:)?(?:col|dimension|mergeCell))\b([^>]*)\/>/g,
191 prefix ? "<$1$2></$1>" : "$&",
192 )
193 .replace(/<sheetData>[\s\S]*?<\/sheetData>/, (data) => (empty ? "<sheetData/>" : data))
194 .replace(/<(\/?)sheetData\b/g, (tag, closing: string) =>
195 localPrefix ? `<${closing}x:sheetData${closing ? "" : ` xmlns:x="${ns}"`}` : tag,
196 )
197 .replace(/="([^"]*)"/g, (attribute, value: string) =>
198 prefix || empty
199 ? ` = '${value.replace(/\d/g, (digit) => `&#${digit.charCodeAt(0)};`)}'`
200 : attribute,
201 ),
202 );
203 const bytes = await archive.generateAsync({ type: "arraybuffer" });
204 const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
205 type: "module",
206 });
207 try {
208 const result = await new Promise<OfficeWorkerResult>((resolve) => {
209 worker.addEventListener(
210 "message",
211 (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
212 { once: true },
213 );
214 worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]);
215 });
216 expect(result.type).toBe("xlsx");
217 if (result.type !== "xlsx") throw new Error("Expected bounded workbook");
218 // The engine counts the chart sheet before it.
219 expect(result.view?.hiddenGridlines).toEqual([1]);
220 const bounded = await JSZip.loadAsync(result.bytes);
221 const sheet = new DOMParser().parseFromString(
222 await bounded.file("xl/worksheets/sheet1.xml")!.async("string"),
223 "application/xml",
224 );
225 expect(sheet.querySelector("parsererror")).toBeNull();
226 const row = sheet.getElementsByTagNameNS(ns, "row")[0];
227 if (empty) expect(row).toBeUndefined();
228 else {
229 expect(row!.getAttribute("ht")).toBe("42");
230 expect(row!.getAttribute("hidden")).toBe("1");
231 expect(row!.getElementsByTagNameNS(ns, "c")[0]!.getAttribute("r")).toBe("A50");
232 expect(row!.getElementsByTagNameNS(ns, "t")[0]!.textContent).toHaveLength(4096);
233 }
234 expect(sheet.getElementsByTagNameNS(ns, "dimension")).toHaveLength(0);
235 expect(sheet.getElementsByTagNameNS(ns, "mergeCell")).toHaveLength(0);
236 const columns = [...sheet.getElementsByTagNameNS(ns, "col")].map((column) =>
237 ["min", "max", "width"].map((name) => column.getAttribute(name)),
238 );
239 // The engine ignores `defaultColWidth`, so the columns it sizes are spelled out.
240 expect(columns).toEqual([
241 [String(OFFICE_PREVIEW_MAX_COLUMNS - 1), String(OFFICE_PREVIEW_MAX_COLUMNS), "20"],
242 // Hidden columns keep their span past the limit, so they stay hidden.
243 [String(OFFICE_PREVIEW_MAX_COLUMNS + 1), String(OFFICE_PREVIEW_MAX_COLUMNS + 30), null],
244 ["1", String(OFFICE_PREVIEW_MAX_COLUMNS - 2), "30"],
245 ]);
246 } finally {
247 worker.terminate();
248 }
249 },
250 );
251
252 it("reports the final slide at maximum scroll after page visibility changes", async () => {
253 const { OfficePages } = await import("./office/OfficePages");
254 const changed = vi.fn();
255 const container = document.createElement("div");
256 container.style.cssText = "display:flex;flex-direction:column;width:400px;height:400px";
257 await using screen = await render(
258 <OfficePages
259 pages={Array.from({ length: 6 }, () => ({ width: 400, height: 240 }))}
260 kind="slide"
261 paint={async () => undefined}
262 onPageChange={changed}
263 onError={(error) => {
264 throw error;
265 }}
266 />,
267 { container },
268 );
269 const scroller = screen.container.querySelector<HTMLElement>("[data-office-pages]")!;
270 await vi.waitFor(() => expect(scroller.scrollHeight).toBeGreaterThan(scroller.clientHeight));
271 await act(() => {
272 scroller.scrollTop = scroller.scrollHeight;
273 });
274 await vi.waitFor(() => expect(changed).toHaveBeenLastCalledWith(5));
275 await act(() => {
276 scroller.scrollTop = 10;
277 });
278 await vi.waitFor(() => expect(changed).toHaveBeenLastCalledWith(0));
279 });
280
281 it("preserves merged text across tile clears", async () => {
282 const { paintFrame } = await import("./office/sheet-frame");
283 const canvas = new OffscreenCanvas(400, 80);
284 const context = canvas.getContext("2d")!;
285 paintFrame(
286 context,
287 {
288 viewport: { x: 0, y: 0, width: 400, height: 80 },
289 list: { width: 400, height: 80, commands: [] },
290 tiles: [
291 {
292 x: 0,
293 y: 0,
294 clipX: 0,
295 clipY: 0,
296 list: {
297 width: 208,
298 height: 80,
299 commands: [
300 {
301 op: "text",
302 x: 2,
303 y: 40,
304 text: "MMMMMMMMMMMMMMMMMMMMMMMM",
305 fontSize: 20,
306 color: "#000",
307 clip: { x: 0, y: 0, w: 400, h: 80 },
308 },
309 ],
310 },
311 },
312 { x: 192, y: 0, clipX: 200, clipY: 0, list: { width: 208, height: 80, commands: [] } },
313 ],
314 },
315 { ratio: 1, origin: { x: 0, y: 0 } },
316 );
317 const pixels = context.getImageData(240, 15, 100, 35).data;
318 expect(pixels.some((value, index) => index % 4 === 3 && value > 0)).toBe(true);
319 });
320
321 it.each([
322 "paragraphs",
323 "runs",
324 "tables",
325 "auxiliary XML",
326 "XML bytes",
327 "renamed XML",
328 "section after prefix",
329 "oversized section",
330 ])("bounds excessive Word %s before rendering DOM", async (scenario) => {
331 const { default: JSZip } = await import("jszip");
332 const archive = new JSZip();
333 const body = ["paragraphs", "section after prefix", "oversized section"].includes(scenario)
334 ? "<w:p><w:r><w:t>x</w:t></w:r></w:p>".repeat(200_000)
335 : scenario === "runs"
336 ? `<w:p>${"<w:r><w:t>x</w:t></w:r>".repeat(50_001)}</w:p>`
337 : scenario === "tables"
338 ? "<w:tbl/>".repeat(2 * WORD_LIMITS.bodyElements)
339 : scenario === "XML bytes"
340 ? `<w:p><w:r><w:t>${"x".repeat(2 * 1024 * 1024)}</w:t></w:r></w:p>`
341 : "<w:p/>";
342 const section =
343 '<w:sectPr><w:pgSz w:w="16838" w:h="11906" w:orient="landscape"/><w:pgMar w:top="1440" w:left="1440" w:bottom="1440" w:right="1440"/></w:sectPr>';
344 archive.file(
345 "word/document.xml",
346 `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>${body}${scenario === "section after prefix" ? '<w:p xmlns:s="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:pPr><s:sectPr><s:pgSz s:w="11906" s:h="16838"/></s:sectPr></w:pPr></w:p>' : ""}${scenario === "oversized section" ? `<w:sectPr>${"<w:cols/>".repeat(2_001)}</w:sectPr>` : section}</w:body></w:document>`,
347 );
348 if (scenario === "auxiliary XML" || scenario === "renamed XML")
349 archive.file(
350 scenario === "renamed XML" ? "word/footnotes.dat" : "word/footnotes.xml",
351 `<w:footnotes>${"<w:p/>".repeat(WORD_LIMITS.auxiliaryMarkup + 1)}</w:footnotes>`,
352 );
353 const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
354 const src = URL.createObjectURL(file);
355 try {
356 const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
357 type: "module",
358 });
359 try {
360 const result = await new Promise<OfficeWorkerResult>((resolve) => {
361 worker.addEventListener(
362 "message",
363 (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
364 { once: true },
365 );
366 void file
367 .arrayBuffer()
368 .then((bytes) => worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]));
369 });
370 if (
371 scenario === "auxiliary XML" ||
372 scenario === "renamed XML" ||
373 scenario === "oversized section"
374 ) {
375 expect(result).toMatchObject({
376 type: "error",
377 code: expect.stringMatching(/^word-limited-/),
378 });
379 } else {
380 expect(result.type).toBe("docx");
381 if (result.type !== "docx") throw new Error("Expected a Word prefix");
382 expect(result.truncated).toBe(true);
383 const bounded = await JSZip.loadAsync(result.bytes);
384 const markup = await bounded.file("word/document.xml")!.async("string");
385 {
386 const xml = markup;
387 const document = new DOMParser().parseFromString(xml, "application/xml");
388 expect(document.querySelector("parsererror")).toBeNull();
389 const bodies = document.getElementsByTagNameNS("*", "body");
390 expect(bodies).toHaveLength(1);
391 const section = bodies[0]!.lastElementChild!;
392 expect(section.localName).toBe("sectPr");
393 const size = section.getElementsByTagNameNS("*", "pgSz")[0]!;
394 expect(size.getAttributeNS(section.namespaceURI, "w")).toBe(
395 scenario === "section after prefix" ? "11906" : "16838",
396 );
397 expect(size.getAttributeNS(section.namespaceURI, "orient")).toBe(
398 scenario === "section after prefix" ? null : "landscape",
399 );
400 }
401 expect(markup.length).toBeLessThan(body.length);
402 expect(markup.length).toBeLessThanOrEqual(WORD_LIMITS.bodyBytes);
403 expect(markup.match(/<(?![!?/])/g)!.length).toBeLessThanOrEqual(WORD_LIMITS.bodyTags);
404 }
405 } finally {
406 worker.terminate();
407 }
408 } finally {
409 URL.revokeObjectURL(src);
410 }
411 });
412
413 it.each([
414 "relationship markup",
415 "relationship bytes",
416 "content type",
417 "metadata type",
418 "deep XML",
419 "query path",
420 ])("bounds XML hidden in media by %s", async (scenario) => {
421 const { default: JSZip } = await import("jszip");
422 const archive = new JSZip();
423 const path = `word/media/payload.png${scenario === "query path" ? "?xml" : ""}`;
424 archive.file(
425 "word/document.xml",
426 '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p/></w:body></w:document>',
427 );
428 archive.file(
429 "[Content_Types].xml",
430 `<Types><Override PartName="/${path}" ContentType="${scenario === "content type" ? "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml" : "image/png"}"/>${scenario === "metadata type" ? '<Default Extension="rels" ContentType="image/png"/>' : ""}</Types>`,
431 );
432 archive.file(
433 "word/_rels/document.xml.rels",
434 `<Relationships>${scenario === "content type" ? "" : `<Relationship Id="style" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="${path.slice(5)}"/>`}${scenario === "metadata type" ? "<unused/>".repeat(WORD_LIMITS.auxiliaryMarkup + 1) : ""}</Relationships>`,
435 );
436 archive.file(
437 path,
438 scenario === "relationship bytes"
439 ? `<styles>${"x".repeat(WORD_LIMITS.auxiliaryPartBytes)}</styles>`
440 : scenario === "deep XML"
441 ? `${"<styles>".repeat(65)}${"</styles>".repeat(65)}`
442 : `<styles>${"<style/>".repeat(WORD_LIMITS.auxiliaryMarkup + 1)}</styles>`,
443 );
444 const bytes = await archive.generateAsync({ type: "arraybuffer", compression: "DEFLATE" });
445 const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
446 type: "module",
447 });
448 try {
449 const result = await new Promise<OfficeWorkerResult>((resolve) => {
450 worker.addEventListener(
451 "message",
452 (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
453 { once: true },
454 );
455 worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]);
456 });
457 expect(result).toMatchObject({
458 type: "error",
459 code: expect.stringMatching(/^word-limited-/),
460 });
461 } finally {
462 worker.terminate();
463 }
464 });
465
466 const EXPANDED_WORD_ROLES = [
467 "footnotes",
468 "note roots",
469 "endnotes",
470 "header",
471 "footer",
472 "comments",
473 "styles",
474 "style chain",
475 "style count",
476 "style visits",
477 "numbering",
478 "picture numbering",
479 ] as const;
480
481 async function expandedWordFixture(role: (typeof EXPANDED_WORD_ROLES)[number]) {
482 const archive = new JSZip();
483 const ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
484 const type = role.startsWith("style")
485 ? "styles"
486 : role === "picture numbering"
487 ? "numbering"
488 : role === "note roots"
489 ? "footnotes"
490 : role;
491 archive.file(
492 "_rels/.rels",
493 '<Relationships><Relationship Id="doc" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>',
494 );
495 const text = (value: string) => `<w:p><w:r><w:t>${value}</w:t></w:r></w:p>`;
496 // Each copy of the 2,000-paragraph payload costs 6,000 markup units, so enough
497 // references (or pages) exceed the expansion budget.
498 const copies = Math.ceil(WORD_LIMITS.expandedMarkup / 6_000) + 1;
499 archive.file(
500 "word/document.xml",
501 `<w:document xmlns:w="${ns}" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body>${text("body retained")}${Array.from({ length: copies }, () => `<w:p><w:r><w:footnoteReference w:id="1"/><w:endnoteReference w:id="1"/><w:commentReference w:id="1"/><w:br w:type="page"/></w:r></w:p>`).join("")}<w:sectPr><w:headerReference w:type="default" r:id="aux"/><w:footerReference w:type="default" r:id="aux"/></w:sectPr></w:body></w:document>`,
502 );
503 archive.file(
504 "word/_rels/document.xml.rels",
505 `<Relationships><Relationship Id="aux" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/${type}" Target="media/aux.xml"/></Relationships>`,
506 );
507 const xml =
508 role === "style chain" || role === "style count" || role === "style visits"
509 ? `<w:styles xmlns:w="${ns}">${Array.from({ length: role === "style count" ? WORD_LIMITS.styles + 1 : role === "style visits" ? Math.ceil(WORD_LIMITS.styleVisits / 30) + 1 : 1_000 }, (_, i) => `<w:style w:styleId="s${i}" w:type="paragraph">${i ? `<w:basedOn w:val="s${role === "style visits" && i >= 30 ? 29 : i - 1}"/>` : ""}<w:pPr><w:spacing w:after="120"/></w:pPr></w:style>`).join("")}</w:styles>`
510 : role === "styles"
511 ? `<w:styles xmlns:w="${ns}">${Array.from({ length: 100 }, (_, i) => `<w:style w:styleId="${"s".repeat(2_000)}${i}" w:type="paragraph"><w:basedOn w:val="s0"/><w:pPr><w:spacing w:after="120"/></w:pPr></w:style>`).join("")}</w:styles>`
512 : role.includes("numbering")
513 ? `<w:numbering xmlns:w="${ns}">${role === "picture numbering" ? '<w:numPicBullet w:numPicBulletId="1"/>' : ""}<w:abstractNum w:abstractNumId="1">${Array.from({ length: 9 }, (_, i) => `<w:lvl w:ilvl="${i}"><w:lvlText w:val="%1."/></w:lvl>`).join("")}</w:abstractNum>${Array.from({ length: WORD_LIMITS.numberingReferences + 1 }, (_, i) => `<w:num w:numId="${i}"><w:abstractNumId w:val="1"/></w:num>`).join("")}</w:numbering>`
514 : role === "header" || role === "footer"
515 ? `<w:${role === "header" ? "hdr" : "ftr"} xmlns:w="${ns}">${text("omitted payload").repeat(2_000)}</w:${role === "header" ? "hdr" : "ftr"}>`
516 : `<w:${role} xmlns:w="${ns}"><w:${role.slice(0, -1)} w:id="1">${text("omitted payload").repeat(2_000)}</w:${role.slice(0, -1)}></w:${role}>`;
517 archive.file("word/media/aux.xml", xml);
518 if (role === "note roots") {
519 // Each note's XML repeats the 32 KB root, which the expansion budget charges twice.
520 const notes = Math.ceil(WORD_LIMITS.expandedBytes / 64_000) + 1;
521 archive.file(
522 "word/document.xml",
523 `<w:document xmlns:w="${ns}"><w:body>${text("body retained")}${Array.from({ length: notes }, (_, id) => `<w:p><w:r><w:footnoteReference w:id="${id}"/></w:r></w:p>`).join("")}</w:body></w:document>`,
524 );
525 archive.file(
526 "word/media/aux.xml",
527 `<w:footnotes xmlns:w="${ns}" padding="${"x".repeat(32_000)}">${Array.from({ length: notes }, (_, id) => `<w:footnote w:id="${id}">${text("omitted payload")}</w:footnote>`).join("")}</w:footnotes>`,
528 );
529 }
530 return archive.generateAsync({ type: "blob", compression: "DEFLATE" });
531 }
532
533 // Rendering starts a Word engine worker per case, which compiles about 30 MB of WebAssembly and
534 // took 10-17 s per test on loaded CI runners. Omission and retention are prepareOffice decisions,
535 // so they are checked there.
536 it.each(EXPANDED_WORD_ROLES)(
537 "keeps the body and omits expanded %s from the prepared document",
538 async (role) => {
539 const file = await expandedWordFixture(role);
540 const { SaxesParser } = await import("saxes");
541 const { prepareOffice } = await import("./officeArchive");
542 const parse = vi.spyOn(SaxesParser.prototype, "write");
543 try {
544 const prepared = await prepareOffice(await file.arrayBuffer(), "docx");
545 expect(prepared.truncated).toBe(true);
546 if (role === "note roots")
547 expect(
548 parse.mock.calls.reduce(
549 (sum, [chunk]) => sum + (typeof chunk === "string" ? chunk.length : 0),
550 0,
551 ),
552 ).toBeLessThan(WORD_LIMITS.expandedBytes + 4 * 1024 * 1024);
553 const bounded = await JSZip.loadAsync(prepared.bytes);
554 const markup = await bounded.file("word/document.xml")!.async("string");
555 expect(markup).toContain("body retained");
556 expect(bounded.file("word/media/aux.xml")).toBeNull();
557 // A dangling header or footer reference makes the engine reject the whole body.
558 expect(markup).not.toMatch(/<w:(header|footer)Reference/);
559 for (const entry of Object.values(bounded.files))
560 if (!entry.dir) expect(await entry.async("string")).not.toContain("omitted payload");
561 } finally {
562 parse.mockRestore();
563 }
564 },
565 );
566
567 it.each([
568 "ordinary parts",
569 "unused parts",
570 "independent styles",
571 "inherited styles",
572 "python-docx package",
573 "default template styles",
574 "binary package properties",
575 ])("retains Word %s without a limit warning", async (scenario) => {
576 const { default: JSZip } = await import("jszip");
577 const archive = new JSZip();
578 const ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
579 const r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
580 const text = (value: string) => `<w:p><w:r><w:t>${value}</w:t></w:r></w:p>`;
581 archive.file(
582 "_rels/.rels",
583 `<Relationships><Relationship Id="doc" Type="${r}/officeDocument" Target="word/document.xml"/></Relationships>`,
584 );
585 if (scenario === "python-docx package" || scenario === "binary package properties") {
586 const packageRelationships = "http://schemas.openxmlformats.org/package/2006/relationships";
587 archive.file(
588 "_rels/.rels",
589 `<Relationships xmlns="${packageRelationships}"><Relationship Id="doc" Type="${r}/officeDocument" Target="word/document.xml"/><Relationship Id="thumbnail" Type="${packageRelationships}/metadata/thumbnail" Target="docProps/thumbnail.jpeg"/><Relationship Id="core" Type="${packageRelationships}/metadata/core-properties" Target="docProps/core.xml"/><Relationship Id="app" Type="${r}/extended-properties" Target="docProps/app.xml"/><Relationship Id="custom" Type="${r}/custom-properties" Target="docProps/custom.xml"/><Relationship Id="signature" Type="${packageRelationships}/digital-signature/origin" Target="_xmlsignatures/origin.sigs"/></Relationships>`,
590 );
591 archive.file(
592 "[Content_Types].xml",
593 '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="jpeg" ContentType="image/jpeg"/><Default Extension="xml" ContentType="application/xml"/><Default Extension="sigs" ContentType="application/vnd.openxmlformats-package.digital-signature-origin"/></Types>',
594 );
595 archive.file(
596 "docProps/thumbnail.jpeg",
597 new Uint8Array([255, 216, 255, 224, 0, 16, 74, 70, 73, 70]),
598 );
599 archive.file("_xmlsignatures/origin.sigs", new Uint8Array());
600 for (const part of ["core", "app", "custom"])
601 archive.file(`docProps/${part}.xml`, '<properties xmlns="urn:properties"/>');
602 if (scenario === "binary package properties") {
603 const roles = [
604 `${packageRelationships}/metadata/core-properties`,
605 `${r}/extended-properties`,
606 `${packageRelationships}/metadata/custom-properties`,
607 `${packageRelationships}/digital-signature/signature`,
608 ];
609 archive.file(
610 "_rels/.rels",
611 `<Relationships><Relationship Id="doc" Type="${r}/officeDocument" Target="word/document.xml"/>${roles.map((role, i) => `<Relationship Id="metadata${i}" Type="${role}" Target="docProps/metadata${i}.dat"/>`).join("")}</Relationships>`,
612 );
613 for (const i of roles.keys())
614 archive.file(`docProps/metadata${i}.dat`, new Uint8Array([255, 216, 255, 0]));
615 }
616 }
617 const ordinary = scenario === "ordinary parts";
618 archive.file(
619 "word/document.xml",
620 `<w:document xmlns:w="${ns}" xmlns:r="${r}"><w:body>${text("ordinary body")}<w:p><w:pPr><w:pStyle w:val="s19"/></w:pPr><w:r><w:t>styled body</w:t>${ordinary ? '<w:footnoteReference w:id="1"/><w:footnoteReference w:id="1"/><w:endnoteReference w:id="1"/><w:commentReference w:id="1"/>' : ""}</w:r></w:p><w:sectPr>${ordinary ? '<w:headerReference w:type="default" r:id="header"/><w:footerReference w:type="default" r:id="footer"/>' : ""}</w:sectPr></w:body></w:document>`,
621 );
622 archive.file(
623 "word/_rels/document.xml.rels",
624 `<Relationships>${["header", "footer", "footnotes", "endnotes", "comments", "fontTable", "styles"].map((role) => `<Relationship Id="${role}" Type="${r}/${role}" Target="${role}.xml"/>`).join("")}</Relationships>`,
625 );
626 for (const [role, root] of [
627 ["header", "hdr"],
628 ["footer", "ftr"],
629 ])
630 archive.file(
631 `word/${role}.xml`,
632 `<w:${root} xmlns:w="${ns}">${text(`${role} retained`)}</w:${root}>`,
633 );
634 for (const role of ["footnotes", "endnotes", "comments"])
635 archive.file(
636 `word/${role}.xml`,
637 `<w:${role} xmlns:w="${ns}"><w:${role.slice(0, -1)} w:id="1" w:author="reviewer" w:date="2026-10-01T00:00:00Z">${text(`${role} retained`)}</w:${role.slice(0, -1)}></w:${role}>`,
638 );
639 archive.file(
640 "word/fontTable.xml",
641 `<w:fonts xmlns:w="${ns}"><w:font w:name="unused"/></w:fonts>`,
642 );
643 archive.file(
644 "word/styles.xml",
645 `<w:styles xmlns:w="${ns}"><w:docDefaults/><w:style w:type="paragraph" w:styleId="base"><w:rPr><w:b/></w:rPr></w:style>${Array.from({ length: 20 }, (_, i) => `<w:style w:styleId="s${i}" w:type="paragraph">${scenario === "inherited styles" ? '<w:basedOn w:val="base"/>' : ""}<w:rPr><w:color w:val="123456"/></w:rPr></w:style>`).join("")}</w:styles>`,
646 );
647 if (scenario === "default template styles") {
648 const heading =
649 '<w:style w:type="paragraph" w:styleId="s19"><w:basedOn w:val="Normal"/><w:link w:val="HeadingChar"/><w:pPr><w:spacing w:after="120"/></w:pPr><w:rPr><w:b/><w:sz w:val="32"/><w:color w:val="123456"/></w:rPr></w:style>';
650 const conditions = [
651 "wholeTable",
652 "firstRow",
653 "lastRow",
654 "firstCol",
655 "lastCol",
656 "band1Horz",
657 "band2Horz",
658 "band1Vert",
659 "band2Vert",
660 ];
661 archive.file(
662 "word/styles.xml",
663 `<w:styles xmlns:w="${ns}"><w:docDefaults><w:rPrDefault><w:rPr><w:sz w:val="22"/></w:rPr></w:rPrDefault></w:docDefaults><w:latentStyles>${Array.from({ length: 276 }, (_, i) => `<w:lsdException w:name="latent ${i}" w:semiHidden="0" w:uiPriority="99"/>`).join("")}</w:latentStyles><w:style w:type="paragraph" w:styleId="Normal"/><w:style w:type="character" w:styleId="HeadingChar"><w:rPr><w:b/></w:rPr></w:style>${heading}${Array.from({ length: 61 }, (_, i) => `<w:style w:type="paragraph" w:styleId="p${i}"><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:after="120"/></w:pPr><w:rPr><w:color w:val="123456"/></w:rPr></w:style>`).join("")}${Array.from({ length: 100 }, (_, i) => `<w:style w:type="table" w:styleId="Table${i}">${i ? '<w:basedOn w:val="Table0"/>' : ""}<w:tblPr><w:tblCellMar><w:top w:w="0"/><w:left w:w="108"/><w:bottom w:w="0"/><w:right w:w="108"/></w:tblCellMar></w:tblPr>${conditions.map((type) => `<w:tblStylePr w:type="${type}"><w:pPr><w:spacing w:after="0"/></w:pPr><w:rPr><w:b/><w:color w:val="123456"/></w:rPr><w:tcPr><w:shd w:fill="D9E2F3"/></w:tcPr></w:tblStylePr>`).join("")}</w:style>`).join("")}</w:styles>`,
664 );
665 archive.file(
666 "word/_rels/document.xml.rels",
667 (await archive.file("word/_rels/document.xml.rels")!.async("string")).replace(
668 "</Relationships>",
669 `<Relationship Id="numbering" Type="${r}/numbering" Target="numbering.xml"/></Relationships>`,
670 ),
671 );
672 archive.file(
673 "word/numbering.xml",
674 `<w:numbering xmlns:w="${ns}">${Array.from({ length: 9 }, (_, i) => `<w:abstractNum w:abstractNumId="${i}"><w:multiLevelType w:val="singleLevel"/><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:lvlJc w:val="left"/><w:pPr><w:tabs><w:tab w:val="num" w:pos="720"/></w:tabs><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl></w:abstractNum><w:num w:numId="${i + 1}"><w:abstractNumId w:val="${i}"/></w:num>`).join("")}</w:numbering>`,
675 );
676 const document = await archive.file("word/document.xml")!.async("string");
677 archive.file(
678 "word/document.xml",
679 document.replace(
680 "<w:sectPr>",
681 '<w:tbl><w:tblPr><w:tblStyle w:val="Table99"/></w:tblPr><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:tc><w:p><w:r><w:t>styled cell</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:sectPr>',
682 ),
683 );
684 }
685 const { prepareOffice } = await import("./officeArchive");
686 const prepared = await prepareOffice(
687 await archive.generateAsync({ type: "arraybuffer", compression: "DEFLATE" }),
688 "docx",
689 );
690 expect(prepared.truncated).toBe(false);
691 const bounded = await JSZip.loadAsync(prepared.bytes);
692 const markup = await bounded.file("word/document.xml")!.async("string");
693 expect(markup).toContain("ordinary body");
694 expect(markup).toContain("styled body");
695 expect(bounded.file("word/styles.xml")).not.toBeNull();
696 if (scenario === "default template styles") {
697 expect(markup).toContain("styled cell");
698 expect(await bounded.file("word/styles.xml")!.async("string")).toContain('w:styleId="Table99"');
699 }
700 if (ordinary) {
701 expect(markup).toMatch(/<w:headerReference/);
702 expect(markup).toMatch(/<w:footerReference/);
703 for (const role of ["header", "footer", "footnotes", "endnotes", "comments"])
704 expect(await bounded.file(`word/${role}.xml`)!.async("string")).toContain(`${role} retained`);
705 }
706 });
707
708 it.each([false, true])(
709 "bounds shared-string text including CDATA %s per cell and across sheets in the worker",
710 async (cdata) => {
711 const { default: JSZip } = await import("jszip");
712 const archive = new JSZip();
713 archive.file(
714 "xl/workbook.xml",
715 '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="one" sheetId="1" r:id="s"/><sheet name="two" sheetId="2" r:id="s"/></sheets></workbook>',
716 );
717 archive.file(
718 "xl/_rels/workbook.xml.rels",
719 '<Relationships><Relationship Id="s" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',
720 );
721 const sharedPath = cdata ? "customStrings.xml" : "sharedStrings.xml";
722 archive.file(
723 "xl/_rels/workbook.xml.rels",
724 (await archive.file("xl/_rels/workbook.xml.rels")!.async("string")).replace(
725 "</Relationships>",
726 `<Relationship Id="strings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="${sharedPath}"/></Relationships>`,
727 ),
728 );
729 const content = "x".repeat(32_767);
730 archive.file(
731 `xl/${sharedPath}`,
732 `<sst><si><t>${cdata ? `<![CDATA[${content}]]>` : content}</t></si></sst>`,
733 );
734 archive.file(
735 "xl/worksheets/sheet1.xml",
736 `<worksheet><sheetData>${Array.from({ length: 500 }, (_, i) => `<row r="${i + 1}">${Array.from({ length: 50 }, (_, j) => `<c r="${j < 26 ? String.fromCharCode(65 + j) : "A" + String.fromCharCode(65 + j - 26)}${i + 1}" t="s"><v>${cdata ? "<![CDATA[0]]>" : "0"}</v></c>`).join("")}</row>`).join("")}</sheetData></worksheet>`.replace(
737 '<c r="A1" t="s"><v><![CDATA[0]]></v></c>',
738 `<c r="A1" t="inlineStr"><is><t><![CDATA[${content}]]></t></is></c>`,
739 ),
740 );
741 const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
742 const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
743 type: "module",
744 });
745 try {
746 const result = await new Promise<OfficeWorkerResult>((resolve) => {
747 worker.addEventListener(
748 "message",
749 (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
750 { once: true },
751 );
752 void file
753 .arrayBuffer()
754 .then((bytes) => worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]));
755 });
756 expect(result.type).toBe("xlsx");
757 if (result.type !== "xlsx") throw new Error("Expected bounded workbook");
758 const bounded = await JSZip.loadAsync(result.bytes);
759 const sheet = new DOMParser().parseFromString(
760 await bounded.file("xl/worksheets/sheet1.xml")!.async("string"),
761 "application/xml",
762 );
763 const cells = [...sheet.getElementsByTagName("t")].map((cell) => cell.textContent ?? "");
764 expect(cells.reduce((total, cell) => total + cell.length, 0)).toBe(1024 * 1024);
765 expect(Math.max(...cells.map((cell) => cell.length))).toBe(4096);
766 expect(result.truncated).toBe(true);
767 } finally {
768 worker.terminate();
769 }
770 },
771 );
772
773 // A body just over the read limit once each paragraph repeats its text this often.
774 it.each([1, Math.ceil(WORD_LIMITS.bodyBytes / 5_000 / 4)])(
775 "counts shared Word settings once with %s text repetitions",
776 async (repetitions) => {
777 const { default: JSZip } = await import("jszip");
778 const archive = new JSZip();
779 const ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
780 archive.file(
781 "word/document.xml",
782 `<w:document xmlns:w="${ns}"><w:body>${`<w:p><w:r><w:t>${"body".repeat(repetitions)}</w:t></w:r></w:p>`.repeat(5_000)}</w:body></w:document>`,
783 );
784 archive.file(
785 "word/_rels/document.xml.rels",
786 '<Relationships><Relationship Id="settings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/></Relationships>',
787 );
788 const settings = `<w:settings xmlns:w="${ns}"><w:unused>${"s".repeat(120_000)}</w:unused></w:settings>`;
789 archive.file("word/settings.xml", settings);
790 const bytes = await archive.generateAsync({ type: "arraybuffer" });
791 const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
792 type: "module",
793 });
794 try {
795 const result = await new Promise<OfficeWorkerResult>((resolve) => {
796 worker.addEventListener(
797 "message",
798 (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
799 { once: true },
800 );
801 worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]);
802 });
803 expect(result.type).toBe("docx");
804 if (result.type !== "docx") throw new Error("Expected a Word prefix");
805 expect(result.truncated).toBe(repetitions > 1);
806 const bounded = await JSZip.loadAsync(result.bytes);
807 const document = await bounded.file("word/document.xml")!.async("string");
808 const retainedSettings = await bounded.file("word/settings.xml")!.async("string");
809 expect(document.match(/<w:p>/g)!.length).toBeGreaterThan(100);
810 expect(document.length).toBeLessThanOrEqual(WORD_LIMITS.bodyBytes);
811 expect(retainedSettings).toBe(settings);
812 } finally {
813 worker.terminate();
814 }
815 },
816 );
817
818 it.each(["repeated binary", "XML relationship alias", "duplicate relationship ID"])(
819 "bounds Word image expansion for %s",
820 async (scenario) => {
821 const { default: JSZip } = await import("jszip");
822 const archive = new JSZip();
823 archive.file(
824 "[Content_Types].xml",
825 '<Types><Default Extension="png" ContentType="image/png"/></Types>',
826 );
827 archive.file(
828 "word/_rels/document.xml.rels",
829 `<Relationships><Relationship Id="image" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/${scenario === "XML relationship alias" ? "styles" : "image"}" Target="media/payload.png"/>${scenario === "duplicate relationship ID" ? '<Relationship Id="image" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/tiny.png"/>' : ""}</Relationships>`,
830 );
831 archive.file(
832 "word/media/payload.png",
833 scenario === "XML relationship alias" ? "<styles/>" : new Uint8Array(8 * 1024 * 1024),
834 );
835 if (scenario === "duplicate relationship ID")
836 archive.file("word/media/tiny.png", new Uint8Array(1));
837 archive.file(
838 "word/document.xml",
839 `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body><w:p>${'<w:r><a:blip r:embed="image"/></w:r>'.repeat(7)}</w:p></w:body></w:document>`,
840 );
841 const bytes = await archive.generateAsync({ type: "arraybuffer", compression: "DEFLATE" });
842 const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
843 type: "module",
844 });
845 try {
846 const result = await new Promise<OfficeWorkerResult>((resolve) => {
847 worker.addEventListener(
848 "message",
849 (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
850 { once: true },
851 );
852 worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]);
853 });
854 expect(result.type === "error" ? previewFailureText(result) : result.type).toContain(
855 "expanded markup",
856 );
857 } finally {
858 worker.terminate();
859 }
860 },
861 );
862
863 it.each(["XFD200", "XFD300", "XFD1048576", "AX500", "AZ9999999"])(
864 "bounds spreadsheet cells at %s before padding",
865 async (ref) => {
866 const { default: JSZip } = await import("jszip");
867 const archive = new JSZip();
868 archive.file(
869 "xl/workbook.xml",
870 '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet" sheetId="1" r:id="rId1"/></sheets></workbook>',
871 );
872 // A nonstandard relationship target must get the same bounds.
873 archive.file(
874 "xl/_rels/workbook.xml.rels",
875 '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="custom.xml"/></Relationships>',
876 );
877 archive.file(
878 "xl/custom.xml",
879 `<worksheet><dimension ref="A1:${ref}"/><sheetData><row r="1"><c r="A1"><v>7</v></c></row><row r="${ref.replace(/\D/g, "")}">${ref === "XFD300" ? `<c r="${ref}" s="1"/>` : `<c r="${ref}"><v>9</v></c>`}</row></sheetData></worksheet>`,
880 );
881 const bytes = await archive.generateAsync({ type: "arraybuffer" });
882 const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
883 type: "module",
884 });
885 try {
886 const result = await new Promise<OfficeWorkerResult>((resolve) => {
887 worker.addEventListener(
888 "message",
889 (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
890 { once: true },
891 );
892 worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]);
893 });
894 if (ref === "AZ9999999" || ref === "XFD1048576") {
895 expect(result.type === "error" ? previewFailureText(result) : result.type).toContain(
896 ref === "AZ9999999" ? "invalid" : "preview limit",
897 );
898 } else {
899 expect(result.type).toBe("xlsx");
900 if (result.type !== "xlsx") throw new Error("Expected workbook values");
901 const bounded = await JSZip.loadAsync(result.bytes);
902 const sheet = new DOMParser().parseFromString(
903 await bounded.file("xl/custom.xml")!.async("string"),
904 "application/xml",
905 );
906 expect(sheet.querySelector('c[r="A1"] v')?.textContent).toBe("7");
907 expect(sheet.querySelectorAll("row").length).toBeLessThanOrEqual(500);
908 expect(result.truncated).toBe(ref === "XFD200" || ref === "XFD300");
909 if (ref === "AX500") expect(sheet.querySelector('c[r="AX500"] v')?.textContent).toBe("9");
910 else expect(sheet.querySelector('c[r="' + ref + '"]')).toBeNull();
911 }
912 } finally {
913 worker.terminate();
914 }
915 },
916 );
917
918 it.each(['<u val="double"/>', '<u val="double"></u>'])(
919 "shows workbook formats and underline %s",
920 async (underline) => {
921 const { default: JSZip } = await import("jszip");
922 const archive = new JSZip();
923 archive.file(
924 "xl/workbook.xml",
925 '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Styles" sheetId="1" r:id="rId1"/></sheets></workbook>',
926 );
927 archive.file(
928 "xl/_rels/workbook.xml.rels",
929 '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',
930 );
931 archive.file(
932 "xl/styles.xml",
933 `<styleSheet><numFmts count="4"><numFmt numFmtId="164" formatCode="0.000"/><numFmt numFmtId="65535" formatCode="0.0000"/><numFmt numFmtId="007" formatCode="&quot;¥&quot;#,##0.00"/><numFmt numFmtId="82" formatCode="[$-010409]dd-mmm-yyyy"/></numFmts><fonts count="2"><font><sz val="11"/></font><font>${underline}<sz val="11"/></font></fonts><cellXfs count="4"><xf numFmtId="0" fontId="0"/><xf numFmtId="7" fontId="0"/><xf numFmtId="82" fontId="0"/><xf numFmtId="0" fontId="1"/></cellXfs></styleSheet>`,
934 );
935 archive.file(
936 "xl/worksheets/sheet1.xml",
937 '<worksheet><sheetData><row r="1"><c r="A1" s="1"><v>100</v></c><c r="B1" s="2"><v>44986</v></c><c r="C1" s="3" t="inlineStr"><is><t>Total</t></is></c></row></sheetData></worksheet>',
938 );
939 const { prepareOffice } = await import("./officeArchive");
940 const prepared = await prepareOffice(
941 await archive.generateAsync({ type: "arraybuffer" }),
942 "xlsx",
943 );
944 const styles = await (
945 await JSZip.loadAsync(prepared.bytes)
946 )
947 .file("xl/styles.xml")!
948 .async("string");
949 expect(styles).toContain("<font><u/>");
950 const worker = new Worker(new URL("./office/spreadsheet.worker.ts", import.meta.url), {
951 type: "module",
952 });
953 try {
954 const { createWorkerClient } = await import("./office/worker-rpc");
955 const client = createWorkerClient<import("./office/sheet-protocol").SheetMethods>(worker);
956 const bytes = prepared.bytes;
957 await client.call("open", { bytes, view: prepared.view! }, { transfer: [bytes] });
958 const cells = await client.call("cells", {
959 sheet: 0,
960 range: { top: 0, bottom: 0, left: 0, right: 1 },
961 });
962 // Ids under 164 that a workbook defines keep its formats, not Excel's built-in ones.
963 expect(cells[0]).toEqual(["¥100.00", "01-Mar-2023"]);
964 } finally {
965 worker.terminate();
966 }
967 archive.file("xl/styles.xml", "<styleSheet><numFmts/><numFmts/></styleSheet>");
968 await expect(
969 prepareOffice(await archive.generateAsync({ type: "arraybuffer" }), "xlsx").catch(
970 (cause: unknown) => previewErrorText(cause, ""),
971 ),
972 ).resolves.toContain("duplicate stylesheet blocks");
973 },
974 );
975
976 it("keeps spreadsheet dates on their calendar day west of UTC", async () => {
977 const { default: JSZip } = await import("jszip");
978 const archive = new JSZip();
979 archive.file(
980 "xl/workbook.xml",
981 '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Dates" sheetId="1" r:id="rId1"/></sheets></workbook>',
982 );
983 archive.file(
984 "xl/_rels/workbook.xml.rels",
985 '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',
986 );
987 archive.file(
988 "xl/styles.xml",
989 '<styleSheet><cellXfs><xf numFmtId="0"/><xf numFmtId="14"/></cellXfs></styleSheet>',
990 );
991 archive.file(
992 "xl/worksheets/sheet1.xml",
993 '<worksheet><sheetData><row r="1"><c r="A1" s="1"><v>46023</v></c></row></sheetData></worksheet>',
994 );
995 const bytes = await archive.generateAsync({ type: "arraybuffer" });
996 const workerModule = new URL(
997 "./office/spreadsheet.worker.ts?worker_file&type=module",
998 import.meta.url,
999 ).href;
1000 // Give the worker a west-of-UTC default while preserving explicit format options.
1001 const bootstrap = URL.createObjectURL(
1002 new Blob(
1003 [
1004 `
1005 const NativeURL = URL;
1006 globalThis.URL = class extends NativeURL {
1007 constructor(input, base) { super(input, base?.startsWith("blob:") ? ${JSON.stringify(location.href)} : base); }
1008 };
1009 const format = Date.prototype.toLocaleDateString;
1010 Date.prototype.toLocaleDateString = function(locale, options) {
1011 return format.call(this, "en-US", { timeZone: "America/Los_Angeles", ...options });
1012 };
1013 await import(${JSON.stringify(workerModule)});
1014 postMessage({ type: "ready" });
1015 `,
1016 ],
1017 { type: "text/javascript" },
1018 ),
1019 );
1020 const worker = new Worker(bootstrap, { type: "module" });
1021 try {
1022 await new Promise<void>((resolve, reject) => {
1023 worker.addEventListener(
1024 "message",
1025 (event) => {
1026 if (event.data.type === "ready") resolve();
1027 },
1028 { once: true },
1029 );
1030 worker.addEventListener("error", (event) => reject(new Error(event.message)), { once: true });
1031 });
1032 const { createWorkerClient } = await import("./office/worker-rpc");
1033 const client = createWorkerClient<import("./office/sheet-protocol").SheetMethods>(worker);
1034 await client.call(
1035 "open",
1036 {
1037 bytes,
1038 view: { hiddenGridlines: [], themeFonts: { major: "Calibri Light", minor: "Calibri" } },
1039 },
1040 { transfer: [bytes] },
1041 );
1042 const cells = await client.call("cells", {
1043 sheet: 0,
1044 range: { top: 0, bottom: 0, left: 0, right: 0 },
1045 });
1046 expect(cells[0]![0]).toMatch(/^1\/1\/(26|2026)$/);
1047 } finally {
1048 worker.terminate();
1049 URL.revokeObjectURL(bootstrap);
1050 }
1051 });
1052
1053 it.each([60, 100])("prepares all %i pages of a table-heavy Word report", async (pages) => {
1054 const { default: JSZip } = await import("jszip");
1055 const archive = new JSZip();
1056 const paragraph = (text: string) =>
1057 `<w:p><w:pPr><w:spacing w:after="120"/><w:jc w:val="left"/></w:pPr><w:r><w:rPr><w:rFonts w:ascii="Calibri"/><w:sz w:val="22"/></w:rPr><w:t>${text}</w:t></w:r></w:p>`;
1058 archive.file(
1059 "word/document.xml",
1060 `<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>${Array.from({ length: pages }, (_, page) => paragraph(`page ${page + 1}`) + `<w:tbl>${Array.from({ length: 10 }, () => `<w:tr>${Array.from({ length: 5 }, () => `<w:tc><w:tcPr><w:tcW w:w="1800"/></w:tcPr>${paragraph("report entry")}</w:tc>`).join("")}</w:tr>`).join("")}</w:tbl>`).join("")}</w:body></w:document>`,
1061 );
1062 archive.file(
1063 "_rels/.rels",
1064 '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>',
1065 );
1066 archive.file(
1067 "[Content_Types].xml",
1068 '<Types><Default Extension="png" ContentType="image/png"/></Types>',
1069 );
1070 // Binary media must not consume the document's markup budget.
1071 archive.file("word/media/image.png", new Uint8Array(2_500_000));
1072 const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
1073 await using screen = await render(
1074 <AttachmentFilePreview
1075 name="report.docx"
1076 mimeType="application/octet-stream"
1077 file={file}
1078 sizeBytes={file.size}
1079 />,
1080 );
1081 // The first Office preview in the file loads the lazy viewer chain and the preparation worker.
1082 await vi.waitFor(() => expect(screen.container.textContent).toContain("page " + pages), {
1083 timeout: 10_000,
1084 });
1085 expect(screen.container.textContent).not.toContain("Preview limited");
1086 expect(screen.container.querySelector('[role="alert"]')).toBeNull();
1087 });