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";
47import { previewErrorText, previewFailureText } from "./previewFailureMessages";
48
49it.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
77it.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
102it("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
122it.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
166it.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
252it("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
281it("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 behind: { x: 0, y: 0 },
290 panes: { width: 0, height: 0 },
291 list: { width: 400, height: 80, commands: [] },
292 tiles: [
293 {
294 x: 0,
295 y: 0,
296 clipX: 0,
297 clipY: 0,
298 list: {
299 width: 208,
300 height: 80,
301 commands: [
302 {
303 op: "text",
304 x: 2,
305 y: 40,
306 text: "MMMMMMMMMMMMMMMMMMMMMMMM",
307 fontSize: 20,
308 color: "#000",
309 clip: { x: 0, y: 0, w: 400, h: 80 },
310 },
311 ],
312 },
313 },
314 { x: 192, y: 0, clipX: 200, clipY: 0, list: { width: 208, height: 80, commands: [] } },
315 ],
316 },
317 { ratio: 1, origin: { x: 0, y: 0 } },
318 );
319 const pixels = context.getImageData(240, 15, 100, 35).data;
320 expect(pixels.some((value, index) => index % 4 === 3 && value > 0)).toBe(true);
321});
322
323it.each([
324 "paragraphs",
325 "runs",
326 "tables",
327 "auxiliary XML",
328 "XML bytes",
329 "renamed XML",
330 "section after prefix",
331 "oversized section",
332])("bounds excessive Word %s before rendering DOM", async (scenario) => {
333 const { default: JSZip } = await import("jszip");
334 const archive = new JSZip();
335 const body = ["paragraphs", "section after prefix", "oversized section"].includes(scenario)
336 ? "<w:p><w:r><w:t>x</w:t></w:r></w:p>".repeat(200_000)
337 : scenario === "runs"
338 ? `<w:p>${"<w:r><w:t>x</w:t></w:r>".repeat(50_001)}</w:p>`
339 : scenario === "tables"
340 ? "<w:tbl/>".repeat(2 * WORD_LIMITS.bodyElements)
341 : scenario === "XML bytes"
342 ? `<w:p><w:r><w:t>${"x".repeat(2 * 1024 * 1024)}</w:t></w:r></w:p>`
343 : "<w:p/>";
344 const section =
345 '<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>';
346 archive.file(
347 "word/document.xml",
348 `<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>`,
349 );
350 if (scenario === "auxiliary XML" || scenario === "renamed XML")
351 archive.file(
352 scenario === "renamed XML" ? "word/footnotes.dat" : "word/footnotes.xml",
353 `<w:footnotes>${"<w:p/>".repeat(WORD_LIMITS.auxiliaryMarkup + 1)}</w:footnotes>`,
354 );
355 const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
356 const src = URL.createObjectURL(file);
357 try {
358 const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
359 type: "module",
360 });
361 try {
362 const result = await new Promise<OfficeWorkerResult>((resolve) => {
363 worker.addEventListener(
364 "message",
365 (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
366 { once: true },
367 );
368 void file
369 .arrayBuffer()
370 .then((bytes) => worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]));
371 });
372 if (
373 scenario === "auxiliary XML" ||
374 scenario === "renamed XML" ||
375 scenario === "oversized section"
376 ) {
377 expect(result).toMatchObject({
378 type: "error",
379 code: expect.stringMatching(/^word-limited-/),
380 });
381 } else {
382 expect(result.type).toBe("docx");
383 if (result.type !== "docx") throw new Error("Expected a Word prefix");
384 expect(result.truncated).toBe(true);
385 const bounded = await JSZip.loadAsync(result.bytes);
386 const markup = await bounded.file("word/document.xml")!.async("string");
387 {
388 const xml = markup;
389 const document = new DOMParser().parseFromString(xml, "application/xml");
390 expect(document.querySelector("parsererror")).toBeNull();
391 const bodies = document.getElementsByTagNameNS("*", "body");
392 expect(bodies).toHaveLength(1);
393 const section = bodies[0]!.lastElementChild!;
394 expect(section.localName).toBe("sectPr");
395 const size = section.getElementsByTagNameNS("*", "pgSz")[0]!;
396 expect(size.getAttributeNS(section.namespaceURI, "w")).toBe(
397 scenario === "section after prefix" ? "11906" : "16838",
398 );
399 expect(size.getAttributeNS(section.namespaceURI, "orient")).toBe(
400 scenario === "section after prefix" ? null : "landscape",
401 );
402 }
403 expect(markup.length).toBeLessThan(body.length);
404 expect(markup.length).toBeLessThanOrEqual(WORD_LIMITS.bodyBytes);
405 expect(markup.match(/<(?![!?/])/g)!.length).toBeLessThanOrEqual(WORD_LIMITS.bodyTags);
406 }
407 } finally {
408 worker.terminate();
409 }
410 } finally {
411 URL.revokeObjectURL(src);
412 }
413});
414
415it.each([
416 "relationship markup",
417 "relationship bytes",
418 "content type",
419 "metadata type",
420 "deep XML",
421 "query path",
422])("bounds XML hidden in media by %s", async (scenario) => {
423 const { default: JSZip } = await import("jszip");
424 const archive = new JSZip();
425 const path = `word/media/payload.png${scenario === "query path" ? "?xml" : ""}`;
426 archive.file(
427 "word/document.xml",
428 '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p/></w:body></w:document>',
429 );
430 archive.file(
431 "[Content_Types].xml",
432 `<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>`,
433 );
434 archive.file(
435 "word/_rels/document.xml.rels",
436 `<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>`,
437 );
438 archive.file(
439 path,
440 scenario === "relationship bytes"
441 ? `<styles>${"x".repeat(WORD_LIMITS.auxiliaryPartBytes)}</styles>`
442 : scenario === "deep XML"
443 ? `${"<styles>".repeat(65)}${"</styles>".repeat(65)}`
444 : `<styles>${"<style/>".repeat(WORD_LIMITS.auxiliaryMarkup + 1)}</styles>`,
445 );
446 const bytes = await archive.generateAsync({ type: "arraybuffer", compression: "DEFLATE" });
447 const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
448 type: "module",
449 });
450 try {
451 const result = await new Promise<OfficeWorkerResult>((resolve) => {
452 worker.addEventListener(
453 "message",
454 (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
455 { once: true },
456 );
457 worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]);
458 });
459 expect(result).toMatchObject({
460 type: "error",
461 code: expect.stringMatching(/^word-limited-/),
462 });
463 } finally {
464 worker.terminate();
465 }
466});
467
468const EXPANDED_WORD_ROLES = [
469 "footnotes",
470 "note roots",
471 "endnotes",
472 "header",
473 "footer",
474 "comments",
475 "styles",
476 "style chain",
477 "style count",
478 "style visits",
479 "numbering",
480 "picture numbering",
481] as const;
482
483async function expandedWordFixture(role: (typeof EXPANDED_WORD_ROLES)[number]) {
484 const archive = new JSZip();
485 const ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
486 const type = role.startsWith("style")
487 ? "styles"
488 : role === "picture numbering"
489 ? "numbering"
490 : role === "note roots"
491 ? "footnotes"
492 : role;
493 archive.file(
494 "_rels/.rels",
495 '<Relationships><Relationship Id="doc" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>',
496 );
497 const text = (value: string) => `<w:p><w:r><w:t>${value}</w:t></w:r></w:p>`;
498 // Each copy of the 2,000-paragraph payload costs 6,000 markup units, so enough
499 // references (or pages) exceed the expansion budget.
500 const copies = Math.ceil(WORD_LIMITS.expandedMarkup / 6_000) + 1;
501 archive.file(
502 "word/document.xml",
503 `<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>`,
504 );
505 archive.file(
506 "word/_rels/document.xml.rels",
507 `<Relationships><Relationship Id="aux" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/${type}" Target="media/aux.xml"/></Relationships>`,
508 );
509 const xml =
510 role === "style chain" || role === "style count" || role === "style visits"
511 ? `<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>`
512 : role === "styles"
513 ? `<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>`
514 : role.includes("numbering")
515 ? `<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>`
516 : role === "header" || role === "footer"
517 ? `<w:${role === "header" ? "hdr" : "ftr"} xmlns:w="${ns}">${text("omitted payload").repeat(2_000)}</w:${role === "header" ? "hdr" : "ftr"}>`
518 : `<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}>`;
519 archive.file("word/media/aux.xml", xml);
520 if (role === "note roots") {
521 // Each note's XML repeats the 32 KB root, which the expansion budget charges twice.
522 const notes = Math.ceil(WORD_LIMITS.expandedBytes / 64_000) + 1;
523 archive.file(
524 "word/document.xml",
525 `<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>`,
526 );
527 archive.file(
528 "word/media/aux.xml",
529 `<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>`,
530 );
531 }
532 return archive.generateAsync({ type: "blob", compression: "DEFLATE" });
533}
534
535// Rendering starts a Word engine worker per case, which compiles about 30 MB of WebAssembly and
536// took 10-17 s per test on loaded CI runners. Omission and retention are prepareOffice decisions,
537// so they are checked there.
538it.each(EXPANDED_WORD_ROLES)(
539 "keeps the body and omits expanded %s from the prepared document",
540 async (role) => {
541 const file = await expandedWordFixture(role);
542 const { SaxesParser } = await import("saxes");
543 const { prepareOffice } = await import("./officeArchive");
544 const parse = vi.spyOn(SaxesParser.prototype, "write");
545 try {
546 const prepared = await prepareOffice(await file.arrayBuffer(), "docx");
547 expect(prepared.truncated).toBe(true);
548 if (role === "note roots")
549 expect(
550 parse.mock.calls.reduce(
551 (sum, [chunk]) => sum + (typeof chunk === "string" ? chunk.length : 0),
552 0,
553 ),
554 ).toBeLessThan(WORD_LIMITS.expandedBytes + 4 * 1024 * 1024);
555 const bounded = await JSZip.loadAsync(prepared.bytes);
556 const markup = await bounded.file("word/document.xml")!.async("string");
557 expect(markup).toContain("body retained");
558 expect(bounded.file("word/media/aux.xml")).toBeNull();
559 // A dangling header or footer reference makes the engine reject the whole body.
560 expect(markup).not.toMatch(/<w:(header|footer)Reference/);
561 for (const entry of Object.values(bounded.files))
562 if (!entry.dir) expect(await entry.async("string")).not.toContain("omitted payload");
563 } finally {
564 parse.mockRestore();
565 }
566 },
567);
568
569it.each([
570 "ordinary parts",
571 "unused parts",
572 "independent styles",
573 "inherited styles",
574 "python-docx package",
575 "default template styles",
576 "binary package properties",
577])("retains Word %s without a limit warning", async (scenario) => {
578 const { default: JSZip } = await import("jszip");
579 const archive = new JSZip();
580 const ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
581 const r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
582 const text = (value: string) => `<w:p><w:r><w:t>${value}</w:t></w:r></w:p>`;
583 archive.file(
584 "_rels/.rels",
585 `<Relationships><Relationship Id="doc" Type="${r}/officeDocument" Target="word/document.xml"/></Relationships>`,
586 );
587 if (scenario === "python-docx package" || scenario === "binary package properties") {
588 const packageRelationships = "http://schemas.openxmlformats.org/package/2006/relationships";
589 archive.file(
590 "_rels/.rels",
591 `<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>`,
592 );
593 archive.file(
594 "[Content_Types].xml",
595 '<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>',
596 );
597 archive.file(
598 "docProps/thumbnail.jpeg",
599 new Uint8Array([255, 216, 255, 224, 0, 16, 74, 70, 73, 70]),
600 );
601 archive.file("_xmlsignatures/origin.sigs", new Uint8Array());
602 for (const part of ["core", "app", "custom"])
603 archive.file(`docProps/${part}.xml`, '<properties xmlns="urn:properties"/>');
604 if (scenario === "binary package properties") {
605 const roles = [
606 `${packageRelationships}/metadata/core-properties`,
607 `${r}/extended-properties`,
608 `${packageRelationships}/metadata/custom-properties`,
609 `${packageRelationships}/digital-signature/signature`,
610 ];
611 archive.file(
612 "_rels/.rels",
613 `<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>`,
614 );
615 for (const i of roles.keys())
616 archive.file(`docProps/metadata${i}.dat`, new Uint8Array([255, 216, 255, 0]));
617 }
618 }
619 const ordinary = scenario === "ordinary parts";
620 archive.file(
621 "word/document.xml",
622 `<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>`,
623 );
624 archive.file(
625 "word/_rels/document.xml.rels",
626 `<Relationships>${["header", "footer", "footnotes", "endnotes", "comments", "fontTable", "styles"].map((role) => `<Relationship Id="${role}" Type="${r}/${role}" Target="${role}.xml"/>`).join("")}</Relationships>`,
627 );
628 for (const [role, root] of [
629 ["header", "hdr"],
630 ["footer", "ftr"],
631 ])
632 archive.file(
633 `word/${role}.xml`,
634 `<w:${root} xmlns:w="${ns}">${text(`${role} retained`)}</w:${root}>`,
635 );
636 for (const role of ["footnotes", "endnotes", "comments"])
637 archive.file(
638 `word/${role}.xml`,
639 `<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}>`,
640 );
641 archive.file(
642 "word/fontTable.xml",
643 `<w:fonts xmlns:w="${ns}"><w:font w:name="unused"/></w:fonts>`,
644 );
645 archive.file(
646 "word/styles.xml",
647 `<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>`,
648 );
649 if (scenario === "default template styles") {
650 const heading =
651 '<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>';
652 const conditions = [
653 "wholeTable",
654 "firstRow",
655 "lastRow",
656 "firstCol",
657 "lastCol",
658 "band1Horz",
659 "band2Horz",
660 "band1Vert",
661 "band2Vert",
662 ];
663 archive.file(
664 "word/styles.xml",
665 `<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>`,
666 );
667 archive.file(
668 "word/_rels/document.xml.rels",
669 (await archive.file("word/_rels/document.xml.rels")!.async("string")).replace(
670 "</Relationships>",
671 `<Relationship Id="numbering" Type="${r}/numbering" Target="numbering.xml"/></Relationships>`,
672 ),
673 );
674 archive.file(
675 "word/numbering.xml",
676 `<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>`,
677 );
678 const document = await archive.file("word/document.xml")!.async("string");
679 archive.file(
680 "word/document.xml",
681 document.replace(
682 "<w:sectPr>",
683 '<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>',
684 ),
685 );
686 }
687 const { prepareOffice } = await import("./officeArchive");
688 const prepared = await prepareOffice(
689 await archive.generateAsync({ type: "arraybuffer", compression: "DEFLATE" }),
690 "docx",
691 );
692 expect(prepared.truncated).toBe(false);
693 const bounded = await JSZip.loadAsync(prepared.bytes);
694 const markup = await bounded.file("word/document.xml")!.async("string");
695 expect(markup).toContain("ordinary body");
696 expect(markup).toContain("styled body");
697 expect(bounded.file("word/styles.xml")).not.toBeNull();
698 if (scenario === "default template styles") {
699 expect(markup).toContain("styled cell");
700 expect(await bounded.file("word/styles.xml")!.async("string")).toContain('w:styleId="Table99"');
701 }
702 if (ordinary) {
703 expect(markup).toMatch(/<w:headerReference/);
704 expect(markup).toMatch(/<w:footerReference/);
705 for (const role of ["header", "footer", "footnotes", "endnotes", "comments"])
706 expect(await bounded.file(`word/${role}.xml`)!.async("string")).toContain(`${role} retained`);
707 }
708});
709
710it.each([false, true])(
711 "bounds shared-string text including CDATA %s per cell and across sheets in the worker",
712 async (cdata) => {
713 const { default: JSZip } = await import("jszip");
714 const archive = new JSZip();
715 archive.file(
716 "xl/workbook.xml",
717 '<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>',
718 );
719 archive.file(
720 "xl/_rels/workbook.xml.rels",
721 '<Relationships><Relationship Id="s" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',
722 );
723 const sharedPath = cdata ? "customStrings.xml" : "sharedStrings.xml";
724 archive.file(
725 "xl/_rels/workbook.xml.rels",
726 (await archive.file("xl/_rels/workbook.xml.rels")!.async("string")).replace(
727 "</Relationships>",
728 `<Relationship Id="strings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="${sharedPath}"/></Relationships>`,
729 ),
730 );
731 const content = "x".repeat(32_767);
732 archive.file(
733 `xl/${sharedPath}`,
734 `<sst><si><t>${cdata ? `<![CDATA[${content}]]>` : content}</t></si></sst>`,
735 );
736 archive.file(
737 "xl/worksheets/sheet1.xml",
738 `<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(
739 '<c r="A1" t="s"><v><![CDATA[0]]></v></c>',
740 `<c r="A1" t="inlineStr"><is><t><![CDATA[${content}]]></t></is></c>`,
741 ),
742 );
743 const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
744 const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
745 type: "module",
746 });
747 try {
748 const result = await new Promise<OfficeWorkerResult>((resolve) => {
749 worker.addEventListener(
750 "message",
751 (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
752 { once: true },
753 );
754 void file
755 .arrayBuffer()
756 .then((bytes) => worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]));
757 });
758 expect(result.type).toBe("xlsx");
759 if (result.type !== "xlsx") throw new Error("Expected bounded workbook");
760 const bounded = await JSZip.loadAsync(result.bytes);
761 const sheet = new DOMParser().parseFromString(
762 await bounded.file("xl/worksheets/sheet1.xml")!.async("string"),
763 "application/xml",
764 );
765 const cells = [...sheet.getElementsByTagName("t")].map((cell) => cell.textContent ?? "");
766 expect(cells.reduce((total, cell) => total + cell.length, 0)).toBe(1024 * 1024);
767 expect(Math.max(...cells.map((cell) => cell.length))).toBe(4096);
768 expect(result.truncated).toBe(true);
769 } finally {
770 worker.terminate();
771 }
772 },
773);
774
775// A body just over the read limit once each paragraph repeats its text this often.
776it.each([1, Math.ceil(WORD_LIMITS.bodyBytes / 5_000 / 4)])(
777 "counts shared Word settings once with %s text repetitions",
778 async (repetitions) => {
779 const { default: JSZip } = await import("jszip");
780 const archive = new JSZip();
781 const ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
782 archive.file(
783 "word/document.xml",
784 `<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>`,
785 );
786 archive.file(
787 "word/_rels/document.xml.rels",
788 '<Relationships><Relationship Id="settings" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings" Target="settings.xml"/></Relationships>',
789 );
790 const settings = `<w:settings xmlns:w="${ns}"><w:unused>${"s".repeat(120_000)}</w:unused></w:settings>`;
791 archive.file("word/settings.xml", settings);
792 const bytes = await archive.generateAsync({ type: "arraybuffer" });
793 const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
794 type: "module",
795 });
796 try {
797 const result = await new Promise<OfficeWorkerResult>((resolve) => {
798 worker.addEventListener(
799 "message",
800 (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
801 { once: true },
802 );
803 worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]);
804 });
805 expect(result.type).toBe("docx");
806 if (result.type !== "docx") throw new Error("Expected a Word prefix");
807 expect(result.truncated).toBe(repetitions > 1);
808 const bounded = await JSZip.loadAsync(result.bytes);
809 const document = await bounded.file("word/document.xml")!.async("string");
810 const retainedSettings = await bounded.file("word/settings.xml")!.async("string");
811 expect(document.match(/<w:p>/g)!.length).toBeGreaterThan(100);
812 expect(document.length).toBeLessThanOrEqual(WORD_LIMITS.bodyBytes);
813 expect(retainedSettings).toBe(settings);
814 } finally {
815 worker.terminate();
816 }
817 },
818);
819
820it.each(["repeated binary", "XML relationship alias", "duplicate relationship ID"])(
821 "bounds Word image expansion for %s",
822 async (scenario) => {
823 const { default: JSZip } = await import("jszip");
824 const archive = new JSZip();
825 archive.file(
826 "[Content_Types].xml",
827 '<Types><Default Extension="png" ContentType="image/png"/></Types>',
828 );
829 archive.file(
830 "word/_rels/document.xml.rels",
831 `<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>`,
832 );
833 archive.file(
834 "word/media/payload.png",
835 scenario === "XML relationship alias" ? "<styles/>" : new Uint8Array(8 * 1024 * 1024),
836 );
837 if (scenario === "duplicate relationship ID")
838 archive.file("word/media/tiny.png", new Uint8Array(1));
839 archive.file(
840 "word/document.xml",
841 `<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>`,
842 );
843 const bytes = await archive.generateAsync({ type: "arraybuffer", compression: "DEFLATE" });
844 const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
845 type: "module",
846 });
847 try {
848 const result = await new Promise<OfficeWorkerResult>((resolve) => {
849 worker.addEventListener(
850 "message",
851 (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
852 { once: true },
853 );
854 worker.postMessage({ type: "open", kind: "docx", bytes }, [bytes]);
855 });
856 expect(result.type === "error" ? previewFailureText(result) : result.type).toContain(
857 "expanded markup",
858 );
859 } finally {
860 worker.terminate();
861 }
862 },
863);
864
865it.each(["XFD200", "XFD300", "XFD1048576", "AX500", "AZ9999999"])(
866 "bounds spreadsheet cells at %s before padding",
867 async (ref) => {
868 const { default: JSZip } = await import("jszip");
869 const archive = new JSZip();
870 archive.file(
871 "xl/workbook.xml",
872 '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet" sheetId="1" r:id="rId1"/></sheets></workbook>',
873 );
874 // A nonstandard relationship target must get the same bounds.
875 archive.file(
876 "xl/_rels/workbook.xml.rels",
877 '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="custom.xml"/></Relationships>',
878 );
879 archive.file(
880 "xl/custom.xml",
881 `<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>`,
882 );
883 const bytes = await archive.generateAsync({ type: "arraybuffer" });
884 const worker = new Worker(new URL("./officePreview.worker.ts", import.meta.url), {
885 type: "module",
886 });
887 try {
888 const result = await new Promise<OfficeWorkerResult>((resolve) => {
889 worker.addEventListener(
890 "message",
891 (event: MessageEvent<OfficeWorkerResult>) => resolve(event.data),
892 { once: true },
893 );
894 worker.postMessage({ type: "open", kind: "xlsx", bytes }, [bytes]);
895 });
896 if (ref === "AZ9999999" || ref === "XFD1048576") {
897 expect(result.type === "error" ? previewFailureText(result) : result.type).toContain(
898 ref === "AZ9999999" ? "invalid" : "preview limit",
899 );
900 } else {
901 expect(result.type).toBe("xlsx");
902 if (result.type !== "xlsx") throw new Error("Expected workbook values");
903 const bounded = await JSZip.loadAsync(result.bytes);
904 const sheet = new DOMParser().parseFromString(
905 await bounded.file("xl/custom.xml")!.async("string"),
906 "application/xml",
907 );
908 expect(sheet.querySelector('c[r="A1"] v')?.textContent).toBe("7");
909 expect(sheet.querySelectorAll("row").length).toBeLessThanOrEqual(500);
910 expect(result.truncated).toBe(ref === "XFD200" || ref === "XFD300");
911 if (ref === "AX500") expect(sheet.querySelector('c[r="AX500"] v')?.textContent).toBe("9");
912 else expect(sheet.querySelector('c[r="' + ref + '"]')).toBeNull();
913 }
914 } finally {
915 worker.terminate();
916 }
917 },
918);
919
920it.each(['<u val="double"/>', '<u val="double"></u>'])(
921 "shows workbook formats and underline %s",
922 async (underline) => {
923 const { default: JSZip } = await import("jszip");
924 const archive = new JSZip();
925 archive.file(
926 "xl/workbook.xml",
927 '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Styles" sheetId="1" r:id="rId1"/></sheets></workbook>',
928 );
929 archive.file(
930 "xl/_rels/workbook.xml.rels",
931 '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',
932 );
933 archive.file(
934 "xl/styles.xml",
935 `<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>`,
936 );
937 archive.file(
938 "xl/worksheets/sheet1.xml",
939 '<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>',
940 );
941 const { prepareOffice } = await import("./officeArchive");
942 const prepared = await prepareOffice(
943 await archive.generateAsync({ type: "arraybuffer" }),
944 "xlsx",
945 );
946 const styles = await (
947 await JSZip.loadAsync(prepared.bytes)
948 )
949 .file("xl/styles.xml")!
950 .async("string");
951 expect(styles).toContain("<font><u/>");
952 const worker = new Worker(new URL("./office/spreadsheet.worker.ts", import.meta.url), {
953 type: "module",
954 });
955 try {
956 const { createWorkerClient } = await import("./office/worker-rpc");
957 const client = createWorkerClient<import("./office/sheet-protocol").SheetMethods>(worker);
958 const bytes = prepared.bytes;
959 await client.call("open", { bytes, view: prepared.view! }, { transfer: [bytes] });
960 const cells = await client.call("cells", {
961 sheet: 0,
962 range: { top: 0, bottom: 0, left: 0, right: 1 },
963 });
964 // Ids under 164 that a workbook defines keep its formats, not Excel's built-in ones.
965 expect(cells[0]).toEqual(["¥100.00", "01-Mar-2023"]);
966 } finally {
967 worker.terminate();
968 }
969 archive.file("xl/styles.xml", "<styleSheet><numFmts/><numFmts/></styleSheet>");
970 await expect(
971 prepareOffice(await archive.generateAsync({ type: "arraybuffer" }), "xlsx").catch(
972 (cause: unknown) => previewErrorText(cause, ""),
973 ),
974 ).resolves.toContain("duplicate stylesheet blocks");
975 },
976);
977
978it("keeps spreadsheet dates on their calendar day west of UTC", async () => {
979 const { default: JSZip } = await import("jszip");
980 const archive = new JSZip();
981 archive.file(
982 "xl/workbook.xml",
983 '<workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Dates" sheetId="1" r:id="rId1"/></sheets></workbook>',
984 );
985 archive.file(
986 "xl/_rels/workbook.xml.rels",
987 '<Relationships><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>',
988 );
989 archive.file(
990 "xl/styles.xml",
991 '<styleSheet><cellXfs><xf numFmtId="0"/><xf numFmtId="14"/></cellXfs></styleSheet>',
992 );
993 archive.file(
994 "xl/worksheets/sheet1.xml",
995 '<worksheet><sheetData><row r="1"><c r="A1" s="1"><v>46023</v></c></row></sheetData></worksheet>',
996 );
997 const bytes = await archive.generateAsync({ type: "arraybuffer" });
998 const workerModule = new URL(
999 "./office/spreadsheet.worker.ts?worker_file&type=module",
1000 import.meta.url,
1001 ).href;
1002 // Give the worker a west-of-UTC default while preserving explicit format options.
1003 const bootstrap = URL.createObjectURL(
1004 new Blob(
1005 [
1006 `
1007 const NativeURL = URL;
1008 globalThis.URL = class extends NativeURL {
1009 constructor(input, base) { super(input, base?.startsWith("blob:") ? ${JSON.stringify(location.href)} : base); }
1010 };
1011 const format = Date.prototype.toLocaleDateString;
1012 Date.prototype.toLocaleDateString = function(locale, options) {
1013 return format.call(this, "en-US", { timeZone: "America/Los_Angeles", ...options });
1014 };
1015 await import(${JSON.stringify(workerModule)});
1016 postMessage({ type: "ready" });
1017 `,
1018 ],
1019 { type: "text/javascript" },
1020 ),
1021 );
1022 const worker = new Worker(bootstrap, { type: "module" });
1023 try {
1024 await new Promise<void>((resolve, reject) => {
1025 worker.addEventListener(
1026 "message",
1027 (event) => {
1028 if (event.data.type === "ready") resolve();
1029 },
1030 { once: true },
1031 );
1032 worker.addEventListener("error", (event) => reject(new Error(event.message)), { once: true });
1033 });
1034 const { createWorkerClient } = await import("./office/worker-rpc");
1035 const client = createWorkerClient<import("./office/sheet-protocol").SheetMethods>(worker);
1036 await client.call(
1037 "open",
1038 {
1039 bytes,
1040 view: { hiddenGridlines: [], themeFonts: { major: "Calibri Light", minor: "Calibri" } },
1041 },
1042 { transfer: [bytes] },
1043 );
1044 const cells = await client.call("cells", {
1045 sheet: 0,
1046 range: { top: 0, bottom: 0, left: 0, right: 0 },
1047 });
1048 expect(cells[0]![0]).toMatch(/^1\/1\/(26|2026)$/);
1049 } finally {
1050 worker.terminate();
1051 URL.revokeObjectURL(bootstrap);
1052 }
1053});
1054
1055it.each([60, 100])("prepares all %i pages of a table-heavy Word report", async (pages) => {
1056 const { default: JSZip } = await import("jszip");
1057 const archive = new JSZip();
1058 const paragraph = (text: string) =>
1059 `<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>`;
1060 archive.file(
1061 "word/document.xml",
1062 `<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>`,
1063 );
1064 archive.file(
1065 "_rels/.rels",
1066 '<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>',
1067 );
1068 archive.file(
1069 "[Content_Types].xml",
1070 '<Types><Default Extension="png" ContentType="image/png"/></Types>',
1071 );
1072 // Binary media must not consume the document's markup budget.
1073 archive.file("word/media/image.png", new Uint8Array(2_500_000));
1074 const file = await archive.generateAsync({ type: "blob", compression: "DEFLATE" });
1075 await using screen = await render(
1076 <AttachmentFilePreview
1077 name="report.docx"
1078 mimeType="application/octet-stream"
1079 file={file}
1080 sizeBytes={file.size}
1081 />,
1082 );
1083 // The first Office preview in the file loads the lazy viewer chain and the preparation worker.
1084 await vi.waitFor(() => expect(screen.container.textContent).toContain("page " + pages), {
1085 timeout: 10_000,
1086 });
1087 expect(screen.container.textContent).not.toContain("Preview limited");
1088 expect(screen.container.querySelector('[role="alert"]')).toBeNull();
1089});