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