Open History to see the last commit
1import JSZip from "jszip";
2import { checkZipDirectory } from "@t3tools/client-runtime/zip/directory";
3import { SaxesParser } from "saxes";
4import { externalUrl } from "./office/links";
5
6import {
7 OFFICE_PREVIEW_MAX_BYTES,
8 OFFICE_PREVIEW_MAX_COLUMNS,
9 OFFICE_PREVIEW_MAX_ROWS,
10 type OfficeWorkerRequest,
11} from "./officePreviewProtocol";
12
13// Word limits, measured against the @betteroffice/docx engine, which lays out in its own worker.
14export const WORD_LIMITS = {
15 /** document.xml read and kept, about 700 pages of prose; the engine opens it in about 1 s. */
16 bodyBytes: 4 * 1024 * 1024,
17 bodyElements: 50_000,
18 bodyTags: 1_000_000,
19 /** A table is laid out in one go: 100,000 tags is a 4,000-row table, about 2 s. */
20 elementTags: 100_000,
21 /** Line breaking grows with the square of a paragraph's text: 40K characters take about 2 s. */
22 paragraphText: 128 * 1024,
23 styles: 8_192,
24 styleBytes: 16 * 1024 * 1024,
25 styleUnits: 400_000,
26 styleVisits: 131_072,
27 stylePropertyVisits: 2_000_000,
28 numberingReferences: 20_000,
29 numberingBytes: 32 * 1024 * 1024,
30 numberingMarkup: 400_000,
31 auxiliaryPartBytes: 8 * 1024 * 1024,
32 auxiliaryMarkup: 1_000_000,
33 /** Body, styles, lists and notes, with headers and footers counted once per page. */
34 expandedBytes: 64 * 1024 * 1024,
35 expandedMarkup: 4_000_000,
36};
37
38function xmlParser() {
39 const parser = new SaxesParser({ xmlns: true });
40 parser.on("doctype", () => {
41 throw new Error("This document contains unsupported XML declarations.");
42 });
43 return parser;
44}
45
46function officeXmlDecoder(bytes: Uint8Array) {
47 if ((bytes[0] === 0xff && bytes[1] === 0xfe) || (bytes[0] === 0x3c && bytes[1] === 0))
48 return new TextDecoder("utf-16le");
49 if ((bytes[0] === 0xfe && bytes[1] === 0xff) || (bytes[0] === 0 && bytes[1] === 0x3c))
50 return new TextDecoder("utf-16be");
51 const declaration = new TextDecoder().decode(bytes.subarray(0, 256));
52 return new TextDecoder(/^<\?xml\s[^?]*\bencoding\s*=\s*["']([^"']+)["']/i.exec(declaration)?.[1]);
53}
54
55function officeXml(bytes: Uint8Array) {
56 // Repacked XML is UTF-8, regardless of the source part's encoding.
57 return officeXmlDecoder(bytes)
58 .decode(bytes)
59 .replace(/^(<\?xml\s[^?]*\bencoding\s*=\s*)["'][^"']+["']/i, '$1"UTF-8"');
60}
61
62// Section properties terminate the section they describe, so the kept prefix
63// may depend on a paragraph or body section beyond the retained input window.
64function wordSections() {
65 const parser = xmlParser();
66 const names: string[] = [];
67 const namespaceScopes: Record<string, string>[] = [];
68 const sections: { end: number; xml: string; body: boolean }[] = [];
69 let window = "";
70 let offset = 0;
71 let capture: {
72 start: number;
73 insert: number;
74 namespaces: string;
75 body: boolean;
76 depth: number;
77 } | null = null;
78 let bytes = 0;
79 let tags = 0;
80 let nextParagraph = false;
81 let paragraphSection = false;
82 const escape = (value: string) =>
83 value.replaceAll("&", "&").replaceAll('"', """).replaceAll("<", "<");
84 parser.on("opentag", (tag) => {
85 names.push(tag.local);
86 namespaceScopes.push(tag.ns);
87 if (names.length > 64) throw new Error("This Word document has excessive XML nesting.");
88 const body = names.length === 3 && names[1] === "body";
89 if (
90 tag.local === "sectPr" &&
91 tag.uri === "http://schemas.openxmlformats.org/wordprocessingml/2006/main" &&
92 (body || (names.length === 5 && names[2] === "p" && names[3] === "pPr" && !nextParagraph))
93 ) {
94 let namespaces = "";
95 const scope = Object.assign({}, ...namespaceScopes) as Record<string, string>;
96 for (const prefix in scope) {
97 const name = prefix ? `xmlns:${prefix}` : "xmlns";
98 if (prefix !== "xml" && !tag.attributes[name])
99 namespaces += ` ${name}="${escape(scope[prefix]!)}"`;
100 }
101 const start = window.lastIndexOf("<", parser.position - offset - 1);
102 if (start < 0) throw new Error("This Word document has too much section markup.");
103 capture = {
104 start: start + offset,
105 insert: parser.position - (tag.isSelfClosing ? 2 : 1),
106 namespaces,
107 body,
108 depth: names.length,
109 };
110 }
111 if (capture && ++tags > 2_000)
112 throw new Error("Preview limited: this Word document has too much section markup.");
113 });
114 parser.on("closetag", (tag) => {
115 if (capture && tag.local === "sectPr" && names.length === capture.depth) {
116 const xml =
117 window.slice(capture.start - offset, capture.insert - offset) +
118 capture.namespaces +
119 window.slice(capture.insert - offset, parser.position - offset);
120 bytes += xml.length;
121 if (bytes > 128 * 1024)
122 throw new Error("Preview limited: this Word document has too much section markup.");
123 sections.push({ end: parser.position, xml, body: capture.body });
124 paragraphSection = !capture.body;
125 if (!capture.body && parser.position > 4 * 1024 * 1024) nextParagraph = true;
126 capture = null;
127 }
128 if (names.length === 3 && tag.local === "p" && paragraphSection) {
129 sections[sections.length - 1]!.end = parser.position;
130 paragraphSection = false;
131 }
132 names.pop();
133 namespaceScopes.pop();
134 });
135 return {
136 write(chunk: string) {
137 window += chunk;
138 parser.write(chunk);
139 if (capture && parser.position - capture.start > 128 * 1024)
140 throw new Error("Preview limited: this Word document has too much section markup.");
141 const keep = capture?.start ?? Math.max(offset, parser.position - 128 * 1024);
142 window = window.slice(keep - offset);
143 offset = keep;
144 },
145 finish() {
146 parser.close();
147 return sections;
148 },
149 };
150}
151
152// Keep whole body elements so every prefix and render batch is valid Word XML.
153// Individual tables/paragraphs are bounded too: one giant element must not
154// bypass the budget between yields on the main thread.
155function wordDocuments(
156 xml: string,
157 incomplete: boolean,
158 sections: ReturnType<ReturnType<typeof wordSections>["finish"]>,
159) {
160 const parser = xmlParser();
161 const names: string[] = [];
162 const batches: { content: string; end: number }[] = [];
163 let prefix = "";
164 let suffix = "";
165 let boundary = 0;
166 let batchStart = 0;
167 let tags = 0;
168 let elementTags = 0;
169 let batchTags = 0;
170 let elements = 0;
171 // The text each open paragraph lays out (its w:t runs); a nested paragraph counts apart.
172 const paragraphText: number[] = [];
173 let inText = false;
174 let truncated = incomplete;
175 const limit = Symbol("Word preview limit");
176 const countText = (text: string) => {
177 if (!inText || paragraphText.length === 0) return;
178 const length = paragraphText.at(-1)! + text.length;
179 if (length > WORD_LIMITS.paragraphText) throw limit;
180 paragraphText[paragraphText.length - 1] = length;
181 };
182 parser.on("text", countText);
183 parser.on("cdata", countText);
184 parser.on("opentag", (tag) => {
185 names.push(tag.name);
186 if (prefix && tag.local === "p") paragraphText.push(0);
187 if (tag.local === "t") inText = true;
188 if (names.length === 2 && tag.local === "body") {
189 prefix = xml.slice(0, parser.position).replace(/\/>$/, ">");
190 suffix = `</${tag.name}></${names[0]}>`;
191 boundary = batchStart = parser.position;
192 } else if (prefix && names.length > 2) {
193 if (names.length === 3 && ++elements > WORD_LIMITS.bodyElements) throw limit;
194 tags++;
195 elementTags++;
196 batchTags++;
197 if (tags > WORD_LIMITS.bodyTags || elementTags > WORD_LIMITS.elementTags) throw limit;
198 }
199 if (names.length > 64) throw limit;
200 });
201 parser.on("closetag", (tag) => {
202 if (prefix && tag.local === "p") paragraphText.pop();
203 if (tag.local === "t") inText = false;
204 if (prefix && names.length === 3 && tag.local !== "sectPr") {
205 if (parser.position - prefix.length > WORD_LIMITS.bodyBytes) throw limit;
206 boundary = parser.position;
207 elementTags = 0;
208 if (batchTags >= 500) {
209 batches.push({ content: xml.slice(batchStart, boundary), end: boundary });
210 batchStart = boundary;
211 batchTags = 0;
212 }
213 }
214 names.pop();
215 });
216 try {
217 for (let offset = 0; offset < xml.length; offset += 16 * 1024) {
218 parser.write(xml.slice(offset, offset + 16 * 1024));
219 }
220 if (!incomplete) parser.close();
221 } catch (cause) {
222 if (cause !== limit) throw cause;
223 truncated = true;
224 }
225 if (!prefix) throw new Error("This Word document has no readable body.");
226 if (boundary > batchStart || batches.length === 0)
227 batches.push({ content: xml.slice(batchStart, boundary), end: boundary });
228 const documents: string[] = [];
229 let length = 0;
230 let markup = 0;
231 for (const batch of batches) {
232 const section = sections.find((section) => section.body || section.end >= batch.end);
233 const document = prefix + batch.content + (section?.xml ?? "") + suffix;
234 length += batch.content.length;
235 markup += batch.content.match(/<(?![!?/])/g)?.length ?? 0;
236 if (length > WORD_LIMITS.bodyBytes || markup > WORD_LIMITS.bodyTags) {
237 truncated = true;
238 break;
239 }
240 documents.push(document);
241 }
242 if (documents.length === 0) throw new Error("This Word document has too much section markup.");
243 return { documents, truncated };
244}
245
246function boundedWorksheet(
247 xml: string,
248 strings: readonly string[],
249 budget: { remaining: number; cells: number },
250) {
251 const parser = xmlParser();
252 const rows = new Map<number, Map<number, string>>();
253 const rowTags = new Map<number, string>();
254 const metadataAttributes = new Map<
255 string,
256 {
257 ref: string | undefined;
258 min: string | undefined;
259 max: string | undefined;
260 hidden: string | undefined;
261 }
262 >();
263 let dataStart = 0;
264 let dataTag = 0;
265 let dataPrefix = "";
266 let dataNamespace = "";
267 let dataEnd = 0;
268 let defaultWidth: number | undefined;
269 let gridlines: boolean | undefined;
270 const sizedColumns: { min: number; max: number }[] = [];
271 let emptyData = false;
272 let depth = 0;
273 let row = 0;
274 let explicitRow = false;
275 let rowTag = "";
276 let column = 0;
277 let maxRow = 0;
278 let maxColumn = 0;
279 let cells = new Map<number, string>();
280 let cell: {
281 start: number;
282 opening: string;
283 name: string;
284 prefix: string;
285 selfClosing: boolean;
286 text: string;
287 value: string;
288 reading: string;
289 shared: boolean;
290 } | null = null;
291 let truncated = false;
292 const coordinate = (ref: string) => {
293 const match = /^([A-Z]{1,3})([1-9]\d{0,6})$/.exec(ref);
294 if (!match) throw new Error("This workbook contains invalid cell coordinates.");
295 let col = 0;
296 for (const letter of match[1]!) col = col * 26 + letter.charCodeAt(0) - 64;
297 const line = Number(match[2]);
298 if (col > 16384 || line > 1048576)
299 throw new Error("This workbook contains invalid worksheet dimensions.");
300 return { col, line };
301 };
302 parser.on("opentag", (tag) => {
303 depth++;
304 if (depth > 64) throw new Error("This workbook contains excessive XML nesting.");
305 if (
306 (tag.local === "row" && depth !== 3) ||
307 (tag.local === "c" && depth !== 4) ||
308 ((tag.local === "dimension" || tag.local === "sheetData") && depth !== 2)
309 )
310 throw new Error("This workbook contains invalid worksheet structure.");
311 const attribute = (name: string) => tag.attributes[name]?.value;
312 if (["dimension", "mergeCell", "col"].includes(tag.local))
313 metadataAttributes.set(
314 xml.slice(xml.lastIndexOf("<", parser.position - 1), parser.position),
315 {
316 ref: attribute("ref"),
317 min: attribute("min"),
318 max: attribute("max"),
319 hidden: attribute("hidden"),
320 },
321 );
322 // The engine draws gridlines on every sheet, so the first view's choice travels beside the bytes.
323 if (depth === 3 && tag.local === "sheetView" && gridlines === undefined) {
324 const shown = attribute("showGridLines");
325 gridlines = shown !== "0" && shown !== "false";
326 }
327 if (depth === 2 && tag.local === "sheetFormatPr") {
328 const width = Number(attribute("defaultColWidth") ?? Number.NaN);
329 if (width >= 0 && width <= 255) defaultWidth = width;
330 }
331 if (depth === 3 && tag.local === "col") {
332 const hidden = attribute("hidden");
333 const min = Number(attribute("min") ?? 1);
334 const max = Number(attribute("max") ?? min);
335 if (
336 (attribute("width") !== undefined || hidden === "1" || hidden === "true") &&
337 Number.isInteger(min) &&
338 Number.isInteger(max)
339 )
340 sizedColumns.push({ min, max });
341 }
342 if (depth === 2 && tag.local === "sheetData") {
343 dataStart = parser.position;
344 dataTag = xml.lastIndexOf("<", parser.position - 1);
345 dataPrefix = tag.prefix ? `${tag.prefix}:` : "";
346 dataNamespace = tag.uri
347 .replaceAll("&", "&")
348 .replaceAll('"', """)
349 .replaceAll("<", "<");
350 emptyData = tag.isSelfClosing;
351 }
352 // A dimension past the limits loses nothing by itself; the cells past them say whether content is lost.
353 if (depth === 2 && tag.local === "dimension") {
354 for (const ref of (attribute("ref") ?? "").split(":")) coordinate(ref);
355 } else if (depth === 3 && tag.local === "row") {
356 explicitRow = attribute("r") !== undefined;
357 row = attribute("r") === undefined ? row + 1 : Number(attribute("r"));
358 if (!Number.isInteger(row) || row < 1 || row > 1048576)
359 throw new Error("This workbook contains invalid row coordinates.");
360 rowTag = xml
361 .slice(xml.lastIndexOf("<", parser.position - 1), parser.position)
362 .replace(/\/>$/, ">");
363 column = 0;
364 cells = rows.get(row) ?? new Map<number, string>();
365 if (row > OFFICE_PREVIEW_MAX_ROWS)
366 throw new Error("This workbook exceeds the preview limit: 250,000 rows.");
367 } else if (depth === 4 && tag.local === "c") {
368 const ref = attribute("r");
369 const position = ref ? coordinate(ref) : { col: column + 1, line: row };
370 if (!explicitRow && column === 0) row = position.line;
371 column = position.col;
372 if (row < 1 || position.line !== row)
373 throw new Error("This workbook contains inconsistent cell rows.");
374 if (row > OFFICE_PREVIEW_MAX_ROWS || column > OFFICE_PREVIEW_MAX_COLUMNS) {
375 truncated = true;
376 return;
377 }
378 maxRow = Math.max(maxRow, row);
379 maxColumn = Math.max(maxColumn, column);
380 if (++budget.cells > 2_000_000 || maxRow * maxColumn > 8_000_000)
381 throw new Error(
382 "This workbook exceeds the preview limit: 2 million cells or 8 million grid positions.",
383 );
384 // Explicit coordinates also bound sheets whose rows/cells omit r.
385 let letters = "";
386 for (let value = column; value > 0; value = Math.floor((value - 1) / 26))
387 letters = String.fromCharCode(65 + ((value - 1) % 26)) + letters;
388 const style = attribute("s");
389 const type = attribute("t");
390 if ((style && !/^\d{1,6}$/.test(style)) || (type && !/^[a-zA-Z]+$/.test(type)))
391 throw new Error("This workbook contains invalid cell metadata.");
392 cell = {
393 start: parser.position,
394 opening: xml
395 .slice(xml.lastIndexOf("<", parser.position - 1), parser.position)
396 .replace(/\/?>$/, `${ref ? "" : ` r="${letters}${row}"`}>`),
397 name: tag.name,
398 prefix: tag.prefix ? `${tag.prefix}:` : "",
399 selfClosing: tag.isSelfClosing,
400 text: "",
401 value: "",
402 reading: "",
403 shared: type === "s",
404 };
405 }
406 if (cell && (tag.local === "t" || tag.local === "v")) cell.reading = tag.local;
407 });
408 const readCellText = (chunk: string) => {
409 if (cell?.reading === "t") cell.text += chunk;
410 if (cell?.reading === "v") cell.value += chunk;
411 };
412 parser.on("text", readCellText);
413 parser.on("cdata", readCellText);
414 parser.on("closetag", (tag) => {
415 if (depth === 4 && tag.local === "c" && cell) {
416 const end = cell.selfClosing ? cell.start : xml.lastIndexOf("<", parser.position - 1);
417 const raw = cell.opening + xml.slice(cell.start, end) + `</${cell.name}>`;
418 const shown = cell.shared ? (strings[Number(cell.value)] ?? "") : cell.text || cell.value;
419 const kept = shown.slice(0, Math.min(4096, budget.remaining));
420 budget.remaining -= kept.length;
421 if (kept.length < shown.length) {
422 truncated = true;
423 const escape = (s: string) =>
424 s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
425 cells.set(
426 column,
427 cell.opening
428 .replace(/\s+t\s*=\s*(?:"[^"]*"|'[^']*')/, "")
429 .replace(/>$/, ' t="inlineStr">') +
430 `<${cell.prefix}is><${cell.prefix}t>` +
431 escape(kept) +
432 `</${cell.prefix}t></${cell.prefix}is></${cell.name}>`,
433 );
434 } else cells.set(column, raw);
435 cell = null;
436 } else if (depth === 3 && tag.local === "row" && row <= OFFICE_PREVIEW_MAX_ROWS) {
437 rows.set(row, cells);
438 rowTags.set(row, rowTag);
439 }
440 if (depth === 2 && tag.local === "sheetData")
441 dataEnd = emptyData ? parser.position : xml.lastIndexOf("<", parser.position - 1);
442 if (cell?.reading === tag.local) cell.reading = "";
443 depth--;
444 });
445 parser.write(xml).close();
446 if (!dataStart) throw new Error("This workbook has no worksheet data.");
447 const boundRange = (ref: string) => {
448 const [a, b = a] = ref.split(":");
449 const first = coordinate(a!);
450 const last = coordinate(b!);
451 if (first.col > OFFICE_PREVIEW_MAX_COLUMNS || first.line > OFFICE_PREVIEW_MAX_ROWS) return "";
452 let letters = "";
453 for (
454 let col = Math.min(OFFICE_PREVIEW_MAX_COLUMNS, last.col);
455 col > 0;
456 col = Math.floor((col - 1) / 26)
457 )
458 letters = String.fromCharCode(65 + ((col - 1) % 26)) + letters;
459 return a + ":" + letters + Math.min(OFFICE_PREVIEW_MAX_ROWS, last.line);
460 };
461 const metadata = (part: string) =>
462 part.replace(
463 /(<((?:\w+:)?(?:dimension|mergeCell|col))\b(?:[^"'<>]|"[^"]*"|'[^']*')*>)(?:\s*<\/\2\s*>)?/g,
464 (tag: string, opening: string) => {
465 const attributes = metadataAttributes.get(opening);
466 if (!attributes) return tag;
467 const replace = (name: string, value: string) => {
468 const pattern = new RegExp(`\\s${name}\\s*=\\s*(?:"[^"]*"|'[^']*')`);
469 tag = pattern.test(tag)
470 ? tag.replace(pattern, ` ${name}="${value}"`)
471 : tag.replace(/\/?>/, (end) => ` ${name}="${value}"${end}`);
472 };
473 if (attributes.ref !== undefined) {
474 const bounded = boundRange(attributes.ref);
475 if (!bounded) return "";
476 replace("ref", bounded);
477 }
478 if (/<(?:\w+:)?col\b/.test(opening)) {
479 const min = Math.max(1, Number(attributes.min ?? 1));
480 // Hidden columns keep their full span, or the columns past the limit would show again.
481 const hidden = attributes.hidden === "1" || attributes.hidden === "true";
482 const max = Math.min(
483 hidden ? 16384 : OFFICE_PREVIEW_MAX_COLUMNS,
484 Number(attributes.max ?? 16384),
485 );
486 if (!Number.isInteger(min) || !Number.isInteger(max) || min > max) return "";
487 replace("min", String(min));
488 replace("max", String(max));
489 }
490 return tag;
491 },
492 );
493 // The engine sizes columns without a width at Excel's 8.43 characters and ignores `defaultColWidth`, so the
494 // columns it covers get that width spelled out. A second `<cols>` is valid: the schema allows any number.
495 let defaultColumns = "";
496 if (defaultWidth !== undefined) {
497 let next = 1;
498 for (const span of sizedColumns.toSorted((a, b) => a.min - b.min)) {
499 if (span.min > next)
500 defaultColumns += `<${dataPrefix}col min="${next}" max="${Math.min(span.min - 1, OFFICE_PREVIEW_MAX_COLUMNS)}" width="${defaultWidth}"/>`;
501 next = Math.max(next, span.max + 1);
502 if (next > OFFICE_PREVIEW_MAX_COLUMNS) break;
503 }
504 if (next <= OFFICE_PREVIEW_MAX_COLUMNS)
505 defaultColumns += `<${dataPrefix}col min="${next}" max="${OFFICE_PREVIEW_MAX_COLUMNS}" width="${defaultWidth}"/>`;
506 if (defaultColumns)
507 defaultColumns = `<${dataPrefix}cols xmlns${dataPrefix ? `:${dataPrefix.slice(0, -1)}` : ""}="${dataNamespace}">${defaultColumns}</${dataPrefix}cols>`;
508 }
509 const head = (part: string) =>
510 metadata(part.slice(0, dataTag) + defaultColumns + part.slice(dataTag));
511 return {
512 xml: emptyData
513 ? head(xml)
514 : `${head(xml.slice(0, dataStart))}${[...rows]
515 .sort(([a], [b]) => a - b)
516 .map(
517 ([line, values]) =>
518 `${rowTags.get(line) ?? `<row r="${line}">`}${[...values]
519 .sort(([a], [b]) => a - b)
520 .map(([, value]) => value)
521 .join("")}</${/^<([^\s>]+)/.exec(rowTags.get(line) ?? "<row>")![1]}>`,
522 )
523 .join("")}${metadata(xml.slice(dataEnd))}`,
524 truncated,
525 gridlines: gridlines ?? true,
526 };
527}
528
529/**
530 * A stylesheet as Excel reads it, in the terms the engine understands. The engine takes a number format id under 164 as
531 * Excel's built-in one, though workbooks define their own there (Excel writes its locale formats 5 to 8 that way), so
532 * those move to free ids. It also reads `<u val="…">` as a boolean, which loses every named underline but the bare one.
533 */
534function engineStyles(xml: string) {
535 const name = (local: string) => `<((?:[\\w.-]+:)?)${local}\\b`;
536 const blocks = new Map<string, { start: number; end: number }>();
537 const parser = xmlParser();
538 let depth = 0;
539 parser.on("opentag", (tag) => {
540 if (++depth > 64) throw new Error("This workbook contains excessive XML nesting.");
541 if (depth !== 2 || !["numFmts", "cellStyleXfs", "cellXfs"].includes(tag.local)) return;
542 if (blocks.has(tag.local))
543 throw new Error("This workbook contains duplicate stylesheet blocks.");
544 blocks.set(tag.local, {
545 start: xml.lastIndexOf("<", parser.position - 1),
546 end: parser.position,
547 });
548 });
549 parser.on("closetag", (tag) => {
550 if (depth === 2) {
551 const block = blocks.get(tag.local);
552 if (block) block.end = parser.position;
553 }
554 depth--;
555 });
556 parser.write(xml).close();
557 const id = /(numFmtId\s*=\s*)(["'])(\d+)\2/g;
558 const moved = new Map<number, number>();
559 const formatBlock = blocks.get("numFmts");
560 const formats = formatBlock ? xml.slice(formatBlock.start, formatBlock.end) : "";
561 const used = new Set([...formats.matchAll(id)].map((match) => Number(match[3])));
562 let next = 164;
563 const renumber = (part: string, assign: boolean) =>
564 part.replace(id, (attribute: string, key: string, quote: string, value: string) => {
565 const number = Number(value);
566 if (assign && number < 164 && !moved.has(number)) {
567 while (used.has(next)) next++;
568 if (next > 65535) throw new Error("This workbook has too many custom number formats.");
569 moved.set(number, next++);
570 }
571 const to = moved.get(number);
572 return to === undefined ? attribute : `${key}${quote}${to}${quote}`;
573 });
574 const numberedFormats = renumber(formats, true);
575 const parts: string[] = [];
576 let offset = 0;
577 for (const [local, block] of blocks) {
578 parts.push(
579 xml.slice(offset, block.start),
580 local === "numFmts" ? numberedFormats : renumber(xml.slice(block.start, block.end), false),
581 );
582 offset = block.end;
583 }
584 parts.push(xml.slice(offset));
585 return parts
586 .join("")
587 .replace(
588 new RegExp(
589 `${name("u")}\\s+val\\s*=\\s*(["'])(?:single|double|singleAccounting|doubleAccounting)\\2\\s*(?:/>|>\\s*</\\1u\\s*>)`,
590 "g",
591 ),
592 "<$1u/>",
593 );
594}
595
596async function boundWorkbook(archive: JSZip) {
597 const paths = new Map<string, string>();
598 // Chart sheets and other non-grid sheets hold no cells to bound.
599 const otherSheets = new Set<string>();
600 let sharedPath = "xl/sharedStrings.xml";
601 let stylesPath = "xl/styles.xml";
602 let themePath = "xl/theme/theme1.xml";
603 const relationships = xmlParser();
604 relationships.on("opentag", (tag) => {
605 if (tag.local !== "Relationship") return;
606 const type = tag.attributes.Type?.value;
607 const path = new URL(
608 tag.attributes.Target?.value ?? "",
609 "https://docx.invalid/xl/workbook.xml",
610 ).pathname.slice(1);
611 if (type?.endsWith("/worksheet")) paths.set(tag.attributes.Id?.value ?? "", path);
612 else if (/\/(?:chartsheet|dialogsheet|xlMacrosheet|xlIntlMacrosheet)$/.test(type ?? ""))
613 otherSheets.add(tag.attributes.Id?.value ?? "");
614 if (type?.endsWith("/sharedStrings")) sharedPath = path;
615 if (type?.endsWith("/styles")) stylesPath = path;
616 if (type?.endsWith("/theme")) themePath = path;
617 });
618 relationships
619 .write((await archive.file("xl/_rels/workbook.xml.rels")?.async("string")) ?? "")
620 .close();
621 const sheetPaths: string[] = [];
622 // Every sheet in workbook order, as the engine indexes them; chart sheets have no worksheet path.
623 const sheetOrder: (string | undefined)[] = [];
624 const workbook = xmlParser();
625 workbook.on("opentag", (tag) => {
626 if (tag.local !== "sheet") return;
627 const id = Object.values(tag.attributes).find((attribute) => attribute.local === "id")?.value;
628 if (otherSheets.has(id ?? "")) {
629 sheetOrder.push(undefined);
630 return;
631 }
632 const path = paths.get(id ?? "");
633 if (!path || sheetPaths.length === 100)
634 throw new Error("This workbook has invalid or too many sheets.");
635 sheetPaths.push(path);
636 sheetOrder.push(path);
637 });
638 workbook.write((await archive.file("xl/workbook.xml")?.async("string")) ?? "").close();
639 const theme = (await archive.file(themePath)?.async("string")) ?? "";
640 const typeface = (font: string, fallback: string) =>
641 new RegExp(
642 `<(?:[\\w.-]+:)?${font}\\b[^>]*>\\s*<(?:[\\w.-]+:)?latin\\b[^>]*\\btypeface\\s*=\\s*["']([^"']+)["']`,
643 ).exec(theme)?.[1] ?? fallback;
644 const themeFonts = {
645 major: typeface("majorFont", "Calibri Light"),
646 minor: typeface("minorFont", "Calibri"),
647 };
648 const styles = await archive.file(stylesPath)?.async("string");
649 if (styles) archive.file(stylesPath, engineStyles(styles));
650 const strings: string[] = [];
651 const shared = await archive.file(sharedPath)?.async("string");
652 if (shared) {
653 const parser = xmlParser();
654 let text = "";
655 let reading = false;
656 parser.on("opentag", (tag) => {
657 if (tag.local === "si") text = "";
658 if (tag.local === "t") reading = true;
659 });
660 const readSharedText = (chunk: string) => {
661 if (reading) text += chunk;
662 };
663 parser.on("text", readSharedText);
664 parser.on("cdata", readSharedText);
665 parser.on("closetag", (tag) => {
666 if (tag.local === "t") reading = false;
667 if (tag.local === "si") strings.push(text);
668 });
669 parser.write(shared).close();
670 }
671 const budget = { remaining: 1024 * 1024, cells: 0 };
672 const bounded = new Map<string, { truncated: boolean; gridlines: boolean }>();
673 for (const path of new Set(sheetPaths)) {
674 const file = archive.file(path);
675 if (!file) throw new Error("This workbook has a missing worksheet.");
676 const sheet = boundedWorksheet(await file.async("string"), strings, budget);
677 archive.file(path, sheet.xml);
678 bounded.set(path, sheet);
679 }
680 return {
681 sheets: sheetOrder.map(
682 (path) => (path && bounded.get(path)) || { truncated: false, gridlines: true },
683 ),
684 themeFonts,
685 };
686}
687
688const WORD_RELATIONSHIP = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/";
689const WORD_EXPANDED_PARTS = new Set(["footnotes", "endnotes", "comments", "header", "footer"]);
690const WORD_DISABLED_PARTS = new Set(["commentsExtended", "fontTable", "aFChunk"]);
691const WORD_BINARY_PARTS = new Set([
692 "image",
693 "font",
694 "thumbnail",
695 "audio",
696 "video",
697 "oleObject",
698 "package",
699 "printerSettings",
700 "vbaProject",
701 "origin",
702 "certificate",
703 // Package metadata can point to binary payloads; explicit XML still wins below.
704 "core-properties",
705 "extended-properties",
706 "custom-properties",
707 "signature",
708]);
709
710function wordPartTypes() {
711 const defaults = new Map<string, string>();
712 const overrides = new Map<string, string>();
713 const xmlParts = new Set([
714 "word/document.xml",
715 "docProps/app.xml",
716 "docProps/core.xml",
717 "docProps/custom.xml",
718 ]);
719 const roles = new Map<string, Set<string>>();
720 const relationships = new Map<string, Map<string, string>>();
721 return {
722 roles,
723 relationships,
724 binary(path: string) {
725 const extension = path.split(".").at(-1)?.toLowerCase() ?? "";
726 const type = overrides.get(path) ?? defaults.get(extension) ?? "";
727 // An XML relationship always wins over a misleading media content type.
728 if (
729 path === "[Content_Types].xml" ||
730 extension === "rels" ||
731 extension === "xml" ||
732 xmlParts.has(path) ||
733 /(?:\+xml|\/xml)$/i.test(type)
734 )
735 return false;
736 return (
737 [...(roles.get(path) ?? [])].some((role) => WORD_BINARY_PARTS.has(role)) ||
738 /^(?:image|audio|video|font)\//i.test(type) ||
739 /^(?:png|jpe?g|gif|webp|bmp|tiff?|ico|bin|sigs|cer|ttf|otf|odttf|woff2?)$/.test(
740 extension,
741 ) ||
742 type === "application/octet-stream" ||
743 type === "application/vnd.openxmlformats-package.digital-signature-origin"
744 );
745 },
746 metadata(path: string, xml: string) {
747 const parser = xmlParser();
748 const removed: { start: number; end: number }[] = [];
749 let start = -1;
750 parser.on("opentag", (tag) => {
751 const attr = (name: string) => tag.attributes[name]?.value ?? "";
752 if (path === "[Content_Types].xml") {
753 if (tag.local === "Default")
754 defaults.set(attr("Extension").toLowerCase(), attr("ContentType"));
755 if (tag.local === "Override")
756 overrides.set(attr("PartName").replace(/^\//, ""), attr("ContentType"));
757 }
758 if (tag.local !== "Relationship" || !path.endsWith(".rels")) return;
759 const type = attr("Type");
760 const role = type.slice(type.lastIndexOf("/") + 1);
761 const external =
762 attr("TargetMode").toLowerCase() === "external" ||
763 /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(attr("Target"));
764 const folder = path === "_rels/.rels" ? "" : path.replace(/_rels\/[^/]+\.rels$/, "");
765 // Preserve archive URL resolution, including literal query/fragment
766 // characters in ZIP names rather than silently classifying another file.
767 const target = new URL(attr("Target"), `https://docx.invalid/${folder}`)
768 .toString()
769 .slice("https://docx.invalid/".length);
770 if (!external) {
771 if (
772 !WORD_BINARY_PARTS.has(role) &&
773 role !== "hyperlink" &&
774 (type.startsWith(WORD_RELATIONSHIP) ||
775 role === "core-properties" ||
776 role === "signature")
777 )
778 xmlParts.add(target);
779 const types = roles.get(target) ?? new Set<string>();
780 types.add(role);
781 roles.set(target, types);
782 const owner = path === "_rels/.rels" ? "" : path.replace(/_rels\/([^/]+)\.rels$/, "$1");
783 const refs = relationships.get(owner) ?? new Map<string, string>();
784 if (!refs.has(attr("Id"))) refs.set(attr("Id"), target);
785 relationships.set(owner, refs);
786 if (target === "word/document.xml" && role !== "officeDocument")
787 throw new Error("Preview limited: this Word document has an aliased document part.");
788 if (type === WORD_RELATIONSHIP + "officeDocument" && target !== "word/document.xml")
789 throw new Error(
790 "Preview limited: this Word document has an unsupported document relationship.",
791 );
792 }
793 if (
794 (external && !(role === "hyperlink" && externalUrl(attr("Target")))) ||
795 WORD_DISABLED_PARTS.has(role)
796 ) {
797 start = xml.lastIndexOf("<", parser.position - 1);
798 }
799 });
800 parser.on("closetag", (tag) => {
801 if (tag.local === "Relationship" && start >= 0) {
802 removed.push({ start, end: parser.position });
803 start = -1;
804 }
805 });
806 parser.write(xml).close();
807 for (const range of removed.toReversed())
808 xml = xml.slice(0, range.start) + xml.slice(range.end);
809 return xml;
810 },
811 };
812}
813
814// Bound inherited style and numbering expansion before the engine loads it.
815// Picture bullets can duplicate embedded images, so `pictures` locates those definitions to omit.
816function wordXmlCost(xml: string, roles: Set<string> | undefined) {
817 const parser = xmlParser();
818 let depth = 0;
819 let markup = 0;
820 const limit = Symbol("Word style budget");
821 const exceeded = {
822 bytes: Infinity,
823 markup: Infinity,
824 pictures: [] as { start: number; end: number }[],
825 };
826 let styleCount = 0;
827 let ownUnits = 0;
828 const styles = new Map<
829 string,
830 { properties: Map<string, number>; base: string; linked: string }
831 >();
832 let style: { id: string; base: string; linked: string; properties: Map<string, number> } | null =
833 null;
834 const names: string[] = [];
835 const definitions = new Map<string, { bytes: number; markup: number }>();
836 const references: { id: string; selector: number }[] = [];
837 let definition: { id: string; start: number; markup: number } | null = null;
838 let reference: { id: string; selector: number } | null = null;
839 const pictures: { start: number; end: number }[] = [];
840 let picture: { start: number; depth: number } | null = null;
841 parser.on("opentag", (tag) => {
842 if (++depth > 64)
843 throw new Error("Preview limited: this Word document has excessive XML nesting.");
844 markup++;
845 const attr = (name: string) =>
846 Object.values(tag.attributes).find((a) => a.local === name)?.value ?? "";
847 names.push(tag.local === "tblStylePr" ? `${tag.local}:${attr("type")}` : tag.local);
848 if (roles?.has("styles") && (tag.local === "style" || tag.local === "docDefaults")) {
849 if (++styleCount > WORD_LIMITS.styles || attr("styleId").length > 256) throw limit;
850 style = { id: attr("styleId"), properties: new Map(), base: "", linked: "" };
851 }
852 if (style) {
853 if (tag.local === "basedOn") style.base = attr("val");
854 else if (tag.local === "link") style.linked = attr("val");
855 else if (names.length > 2 && tag.local !== "name") {
856 const key = names.slice(2).join("/");
857 const size = new TextEncoder().encode(
858 xml.slice(xml.lastIndexOf("<", parser.position - 1), parser.position),
859 ).length;
860 if (++ownUnits > WORD_LIMITS.styleUnits) throw limit;
861 style.properties.set(key, size);
862 }
863 }
864 if (roles?.has("numbering")) {
865 if (tag.local === "abstractNum")
866 definition = {
867 id: attr("abstractNumId"),
868 start: xml.lastIndexOf("<", parser.position - 1),
869 markup: markup - 1,
870 };
871 if (tag.local === "num") {
872 if (references.length >= WORD_LIMITS.numberingReferences) throw limit;
873 reference = { id: "", selector: attr("numId").length + 32 };
874 references.push(reference);
875 }
876 if (tag.local === "abstractNumId" && reference) reference.id = attr("val");
877 }
878 if (!picture && (tag.local === "numPicBullet" || tag.local === "lvlPicBulletId"))
879 picture = { start: xml.lastIndexOf("<", parser.position - 1), depth };
880 });
881 parser.on("closetag", (tag) => {
882 if (picture?.depth === depth) {
883 pictures.push({ start: picture.start, end: parser.position });
884 picture = null;
885 }
886 if (definition && tag.local === "abstractNum") {
887 const previous = definitions.get(definition.id);
888 definitions.set(definition.id, {
889 bytes:
890 (previous?.bytes ?? 0) +
891 new TextEncoder().encode(xml.slice(definition.start, parser.position)).length,
892 markup: (previous?.markup ?? 0) + markup - definition.markup,
893 });
894 definition = null;
895 }
896 if (tag.local === "num") reference = null;
897 if (style && (tag.local === "style" || tag.local === "docDefaults")) {
898 styles.set(style.id, style);
899 style = null;
900 }
901 names.pop();
902 depth--;
903 });
904 try {
905 parser.write(xml).close();
906 } catch (cause) {
907 if (cause !== limit) throw cause;
908 return exceeded;
909 }
910 const rawBytes = new TextEncoder().encode(xml).length;
911 if (roles?.has("styles")) {
912 // Immutable parent pointers match processStyles' ordered merges (including
913 // forward links and cycles) without copying an expanding property map.
914 type Resolved = {
915 properties: Map<string, number>;
916 parent?: Resolved | undefined;
917 depth: number;
918 };
919 const resolved = new Map<string, Resolved>();
920 for (const [id, style] of styles) resolved.set(id, { properties: style.properties, depth: 1 });
921 for (const [id, style] of styles) {
922 const parent = style.base ? resolved.get(style.base) : undefined;
923 if (parent && parent.depth >= 32) return exceeded;
924 resolved.set(id, { properties: style.properties, parent, depth: (parent?.depth ?? 0) + 1 });
925 }
926 let bytes = 0;
927 let expandedMarkup = 0;
928 let visited = 0;
929 let propertyVisits = 0;
930 for (const [id, style] of styles) {
931 for (const root of [
932 resolved.get(id),
933 style.linked ? resolved.get(style.linked) : undefined,
934 ]) {
935 const seen = new Set<string>();
936 for (let node = root; node; node = node.parent) {
937 if (++visited > WORD_LIMITS.styleVisits) return exceeded;
938 for (const [key, size] of node.properties) {
939 if (++propertyVisits > WORD_LIMITS.stylePropertyVisits) return exceeded;
940 if (seen.has(key)) continue;
941 // Latent styles never enter properties. Charge each own property
942 // once per resolved style, including linked and default selectors.
943 const copies = id ? 1 : 2;
944 bytes += (size * 2 + id.length + 32) * copies;
945 expandedMarkup += copies;
946 if (bytes > WORD_LIMITS.styleBytes || expandedMarkup > WORD_LIMITS.styleUnits)
947 return exceeded;
948 seen.add(key);
949 }
950 }
951 }
952 }
953 return { bytes, markup: expandedMarkup, pictures };
954 }
955 let bytes = rawBytes;
956 if (roles?.has("numbering")) {
957 for (const ref of references) {
958 const cost = definitions.get(ref.id);
959 if (!cost) continue;
960 bytes += cost.bytes * 2 + cost.markup * ref.selector;
961 markup += cost.markup;
962 if (bytes > WORD_LIMITS.numberingBytes || markup > WORD_LIMITS.numberingMarkup)
963 return exceeded;
964 }
965 }
966 return { bytes, markup, pictures };
967}
968
969// Layout can repeat notes at references and headers/footers across pages.
970// Charge those copies, not just the XML that defines them.
971async function wordExpansion(
972 archive: JSZip,
973 parts: ReturnType<typeof wordPartTypes>,
974 mediaSizes: Map<string, number>,
975 auxiliaryCosts: Map<string, { bytes: number; markup: number }>,
976 documents: string[],
977) {
978 type Cost = { bytes: number; markup: number; media: number; images: Set<string> };
979 const empty = (): Cost => ({ bytes: 0, markup: 0, media: 0, images: new Set() });
980 const nodes = new Map<string, { xml: string; path: string }>();
981 const optional = new Set<string>();
982 const noteParts = new Map<string, string>();
983 for (const [path, roles] of parts.roles) {
984 if (![...roles].some((role) => WORD_EXPANDED_PARTS.has(role))) continue;
985 const xml = await archive.file(path)?.async("string");
986 if (!xml) continue;
987 optional.add(path);
988 if (roles.has("header") || roles.has("footer")) nodes.set(path, { xml, path });
989 for (const role of ["footnotes", "endnotes", "comments"]) {
990 if (!roles.has(role)) continue;
991 noteParts.set(role.slice(0, -1), path);
992 const parser = xmlParser();
993 let start = 0;
994 let id = "";
995 let depth = 0;
996 let prefix = "";
997 let suffix = "";
998 parser.on("opentag", (tag) => {
999 if (++depth === 1) {
1000 prefix = xml.slice(0, parser.position);
1001 suffix = `</${tag.name}>`;
1002 }
1003 if (tag.local !== role.slice(0, -1)) return;
1004 start = xml.lastIndexOf("<", parser.position - 1);
1005 id = Object.values(tag.attributes).find((attr) => attr.local === "id")?.value ?? "";
1006 });
1007 parser.on("closetag", (tag) => {
1008 if (tag.local === role.slice(0, -1))
1009 nodes.set(`${path}#${id}`, {
1010 xml: prefix + xml.slice(start, parser.position) + suffix,
1011 path,
1012 });
1013 depth--;
1014 });
1015 parser.write(xml).close();
1016 }
1017 }
1018 const used = new Set<string>();
1019 const memo = new Map<string, Cost>();
1020 let expandedXmlBytes = 0;
1021 const scan = (xml: string, path: string, chain: Set<string>, pages = 1, expand = true): Cost => {
1022 const cost = empty();
1023 const refs = new Map<string, number>();
1024 const headers = new Set<string>();
1025 const parser = xmlParser();
1026 const add = (key: string) => refs.set(key, (refs.get(key) ?? 0) + 1);
1027 parser.on("opentag", (tag) => {
1028 const attr = (name: string) =>
1029 Object.values(tag.attributes).find((a) => a.local === name)?.value ?? "";
1030 const note = /^(footnote|endnote|comment)Reference$/.exec(tag.local)?.[1];
1031 if (note && noteParts.has(note)) add(`${noteParts.get(note)}#${attr("id")}`);
1032 if (tag.local === "headerReference" || tag.local === "footerReference") {
1033 const target = parts.relationships.get(path)?.get(attr("id"));
1034 if (target) headers.add(target);
1035 }
1036 if (tag.local === "altChunk") cost.bytes = Infinity;
1037 if (tag.local !== "blip" && tag.local !== "imagedata") return;
1038 const target = parts.relationships.get(path)?.get(attr("embed") || attr("id"));
1039 if (target) {
1040 cost.media += mediaSizes.get(target) ?? OFFICE_PREVIEW_MAX_BYTES + 1;
1041 cost.images.add(target);
1042 }
1043 });
1044 parser.write(xml).close();
1045 for (const header of headers) refs.set(header, pages);
1046 if (!expand) return cost;
1047 for (const [key, copies] of refs) {
1048 const node = nodes.get(key);
1049 if (!node) continue;
1050 used.add(node.path);
1051 if (chain.has(key) || chain.size >= 64) {
1052 cost.bytes = Infinity;
1053 break;
1054 }
1055 let expanded = memo.get(key);
1056 if (!expanded) {
1057 expandedXmlBytes += node.xml.length * 2;
1058 if (expandedXmlBytes > WORD_LIMITS.expandedBytes) {
1059 cost.bytes = Infinity;
1060 break;
1061 }
1062 const own = wordXmlCost(node.xml, undefined);
1063 expanded = scan(node.xml, node.path, new Set([...chain, key]));
1064 expanded.bytes += own.bytes;
1065 expanded.markup += own.markup;
1066 memo.set(key, expanded);
1067 }
1068 cost.bytes += expanded.bytes * copies;
1069 cost.markup += expanded.markup * copies;
1070 cost.media += expanded.media * copies;
1071 for (const image of expanded.images) cost.images.add(image);
1072 }
1073 return cost;
1074 };
1075 const costs = new Map<string, Cost>();
1076 let bytes = 0;
1077 let markup = 0;
1078 let media = 0;
1079 // Styles may introduce a page break before each styled paragraph. The page
1080 // bound also includes explicit breaks and section transitions in each batch.
1081 let stylePageBreaks = false;
1082 for (const [path, roles] of parts.roles)
1083 if (
1084 roles.has("styles") &&
1085 /<(?:\w+:)?pageBreakBefore\b/.test((await archive.file(path)?.async("string")) ?? "")
1086 )
1087 stylePageBreaks = true;
1088 for (const document of documents) {
1089 const pages = Math.max(
1090 1,
1091 document.match(
1092 stylePageBreaks ? /<(?:\w+:)?p\b/g : /<(?:\w+:)?(?:br|pageBreakBefore|sectPr)\b/g,
1093 )?.length ?? 0,
1094 );
1095 const expanded = scan(document, "word/document.xml", new Set(), pages);
1096 const body = wordXmlCost(document, undefined);
1097 bytes += body.bytes + expanded.bytes;
1098 markup += body.markup + expanded.markup;
1099 media += expanded.media;
1100 costs.set(document, expanded);
1101 }
1102 for (const [path, cost] of auxiliaryCosts) {
1103 if (optional.has(path) && !used.has(path)) continue;
1104 bytes += cost.bytes;
1105 markup += cost.markup;
1106 }
1107 const overBudget =
1108 bytes > WORD_LIMITS.expandedBytes ||
1109 markup > WORD_LIMITS.expandedMarkup ||
1110 media > OFFICE_PREVIEW_MAX_BYTES;
1111 const truncated = (used.size > 0 && overBudget) || bytes === Infinity;
1112 const omitted = new Set([...optional].filter((path) => truncated || !used.has(path)));
1113 for (const path of omitted) archive.remove(path);
1114 if (truncated)
1115 for (const document of documents)
1116 costs.set(document, scan(document, "word/document.xml", new Set(), 1, false));
1117 // Remove relationships too: related XML is parsed even when not rendered.
1118 for (const [owner, refs] of parts.relationships) {
1119 const ids = new Set([...refs].filter(([, path]) => omitted.has(path)).map(([id]) => id));
1120 if (ids.size === 0) continue;
1121 const relPath = owner ? owner.replace(/([^/]+)$/, "_rels/$1.rels") : "_rels/.rels";
1122 let xml = await archive.file(relPath)?.async("string");
1123 if (!xml) continue;
1124 const removed: { start: number; end: number }[] = [];
1125 const parser = xmlParser();
1126 let start = -1;
1127 parser.on("opentag", (tag) => {
1128 if (tag.local === "Relationship" && ids.has(tag.attributes.Id?.value ?? ""))
1129 start = xml!.lastIndexOf("<", parser.position - 1);
1130 });
1131 parser.on("closetag", (tag) => {
1132 if (tag.local === "Relationship" && start >= 0) {
1133 removed.push({ start, end: parser.position });
1134 start = -1;
1135 }
1136 });
1137 parser.write(xml).close();
1138 for (const range of removed.toReversed())
1139 xml = xml.slice(0, range.start) + xml.slice(range.end);
1140 archive.file(relPath, xml);
1141 }
1142 return { costs, truncated, omitted };
1143}
1144
1145// Stream each entry before handing it to an engine. A tiny compressed archive
1146// must not turn into an unbounded allocation on the UI thread.
1147export async function boundedArchive(input: Extract<OfficeWorkerRequest, { type: "open" }>) {
1148 const { bytes } = input;
1149 const spreadsheet = input.kind === "xlsx";
1150 if (bytes.byteLength > OFFICE_PREVIEW_MAX_BYTES)
1151 throw new Error("Preview limited to files under 50 MB.");
1152 checkZipDirectory(bytes);
1153 const source = await JSZip.loadAsync(bytes).catch(() => {
1154 throw new Error("This file is damaged, encrypted, or not a valid Office document.");
1155 });
1156 const allEntries = Object.values(source.files);
1157 if (allEntries.length > 2048)
1158 throw new Error("This file contains too many archive entries to preview.");
1159 const entries = allEntries.filter((entry) => !entry.dir);
1160 if (
1161 input.kind === "docx" &&
1162 entries.some((entry) => entry.name.includes("\\") || entry.name.startsWith("/"))
1163 )
1164 throw new Error("Preview limited: this Word document has unsupported archive paths.");
1165 const archive = new JSZip();
1166 const partTypes = wordPartTypes();
1167 // Metadata must be bounded and classified before any payload gets a media exemption.
1168 if (input.kind === "docx")
1169 entries.sort(
1170 (a, b) =>
1171 Number(b.name === "[Content_Types].xml" || b.name.endsWith(".rels")) -
1172 Number(a.name === "[Content_Types].xml" || a.name.endsWith(".rels")),
1173 );
1174 const costs = new Map<string, { bytes: number; markup: number }>();
1175 const mediaSizes = new Map<string, number>();
1176 let total = 0;
1177 let wordAuxiliaryMarkup = 0;
1178 let wordInputTruncated = false;
1179 let word: ReturnType<typeof wordDocuments> | null = null;
1180 for (const entry of entries) {
1181 const document = input.kind === "docx" && entry.name === "word/document.xml";
1182 const media = input.kind === "docx" && partTypes.binary(entry.name);
1183 const chunks: Uint8Array[] = [];
1184 const sections = document ? wordSections() : null;
1185 let decoder: TextDecoder | undefined;
1186 let length = 0;
1187 await new Promise<void>((resolve, reject) => {
1188 // JSZip exposes this streaming API at runtime but omits it from its types.
1189 const stream = (
1190 entry as JSZip.JSZipObject & {
1191 internalStream(type: "uint8array"): JSZip.JSZipStreamHelper<Uint8Array>;
1192 }
1193 ).internalStream("uint8array");
1194 stream
1195 .on("data", (chunk: Uint8Array) => {
1196 total += chunk.length;
1197 length += chunk.length;
1198 if (total > (spreadsheet ? 128 * 1024 * 1024 : OFFICE_PREVIEW_MAX_BYTES)) {
1199 stream.pause();
1200 reject(new Error("The expanded document is too large to preview safely."));
1201 return;
1202 }
1203 try {
1204 if (sections) {
1205 decoder ??= officeXmlDecoder(chunk);
1206 sections.write(decoder.decode(chunk, { stream: true }));
1207 }
1208 } catch (cause) {
1209 stream.pause();
1210 reject(cause);
1211 return;
1212 }
1213 if (document && length > 4 * 1024 * 1024) {
1214 const kept = Math.max(0, chunk.length - (length - 4 * 1024 * 1024));
1215 if (kept) chunks.push(chunk.subarray(0, kept));
1216 wordInputTruncated = true;
1217 return;
1218 }
1219 // Media is bounded independently. Even renamed auxiliary XML must
1220 // stay small before the engine parses it.
1221 if (input.kind === "docx" && !document && !media) {
1222 for (const byte of chunk) if (byte === 0x3c) wordAuxiliaryMarkup++;
1223 if (
1224 length > WORD_LIMITS.auxiliaryPartBytes ||
1225 wordAuxiliaryMarkup > WORD_LIMITS.auxiliaryMarkup
1226 ) {
1227 stream.pause();
1228 reject(
1229 new Error("Preview limited: this Word document has too much auxiliary markup."),
1230 );
1231 return;
1232 }
1233 }
1234 if (
1235 total > (spreadsheet ? 128 * 1024 * 1024 : OFFICE_PREVIEW_MAX_BYTES) ||
1236 (spreadsheet && total > Math.max(bytes.byteLength * 200, 8 * 1024 * 1024)) ||
1237 (!document &&
1238 (spreadsheet || media || entry.name.endsWith(".xml")) &&
1239 length > (spreadsheet ? 64 * 1024 * 1024 : 8 * 1024 * 1024))
1240 ) {
1241 stream.pause();
1242 reject(new Error("The expanded document is too large to preview safely."));
1243 } else chunks.push(chunk);
1244 })
1245 .on("error", reject)
1246 .on("end", resolve)
1247 .resume();
1248 });
1249 const content = new Uint8Array(document ? Math.min(length, 4 * 1024 * 1024) : length);
1250 let offset = 0;
1251 for (const chunk of chunks) {
1252 content.set(chunk, offset);
1253 offset += chunk.length;
1254 }
1255 if (document) {
1256 sections!.write(decoder?.decode() ?? "");
1257 word = wordDocuments(officeXml(content), wordInputTruncated, sections!.finish());
1258 archive.file(entry.name, word.documents[0]!);
1259 } else if (input.kind === "docx" && !media) {
1260 let xml = officeXml(content);
1261 if (entry.name === "[Content_Types].xml" || entry.name.endsWith(".rels"))
1262 xml = partTypes.metadata(entry.name, xml);
1263 const roles = partTypes.roles.get(entry.name);
1264 let cost = wordXmlCost(xml, roles);
1265 // The renderer parses related parts even when their render option is off.
1266 if (roles && [...roles].every((role) => WORD_DISABLED_PARTS.has(role))) continue;
1267 // Picture bullets come out, and their list levels keep the text bullets Word falls back to.
1268 if (roles?.has("numbering") && cost.pictures.length > 0) {
1269 for (const range of cost.pictures.toReversed())
1270 xml = xml.slice(0, range.start) + xml.slice(range.end);
1271 cost = wordXmlCost(xml, roles);
1272 wordInputTruncated = true;
1273 }
1274 if (
1275 (roles?.has("styles") &&
1276 (cost.bytes > WORD_LIMITS.styleBytes || cost.markup > WORD_LIMITS.styleUnits)) ||
1277 (roles?.has("numbering") &&
1278 (cost.bytes > WORD_LIMITS.numberingBytes || cost.markup > WORD_LIMITS.numberingMarkup))
1279 ) {
1280 wordInputTruncated = true;
1281 continue;
1282 }
1283 costs.set(entry.name, cost);
1284 archive.file(entry.name, xml);
1285 } else {
1286 if (input.kind === "docx" && partTypes.roles.get(entry.name)?.has("font")) {
1287 continue;
1288 }
1289 if (media) mediaSizes.set(entry.name, Math.ceil((content.length * 4) / 3));
1290 archive.file(entry.name, /\.(?:xml|rels)$/i.test(entry.name) ? officeXml(content) : content);
1291 }
1292 }
1293 if (word) {
1294 const expansion = await wordExpansion(archive, partTypes, mediaSizes, costs, word.documents);
1295 wordInputTruncated ||= expansion.truncated;
1296 for (const path of expansion.omitted) {
1297 archive.remove(path);
1298 costs.delete(path);
1299 }
1300 let mediaBytes = 0;
1301 const usedImages = new Set<string>();
1302 const auxiliary = [...costs.values()].reduce(
1303 (sum, cost) => ({ bytes: sum.bytes + cost.bytes, markup: sum.markup + cost.markup }),
1304 { bytes: 0, markup: 0 },
1305 );
1306 // The worker engine parses shared parts once, rather than once per legacy render batch.
1307 let bytes = auxiliary.bytes;
1308 let markup = auxiliary.markup;
1309 const documents: string[] = [];
1310 for (const document of word.documents) {
1311 const rawCost = wordXmlCost(document, undefined);
1312 const extra = expansion.costs.get(document)!;
1313 const cost = { bytes: rawCost.bytes + extra.bytes, markup: rawCost.markup + extra.markup };
1314 const images = extra.media;
1315 const batchImages = new Set(extra.images);
1316 if (
1317 bytes + cost.bytes > WORD_LIMITS.expandedBytes ||
1318 markup + cost.markup > WORD_LIMITS.expandedMarkup ||
1319 mediaBytes + images > OFFICE_PREVIEW_MAX_BYTES
1320 )
1321 break;
1322 bytes += cost.bytes;
1323 markup += cost.markup;
1324 mediaBytes += images;
1325 for (const path of batchImages) usedImages.add(path);
1326 documents.push(document);
1327 }
1328 if (documents.length === 0)
1329 throw new Error("Preview limited: this Word document has too much expanded markup.");
1330 word.truncated ||= wordInputTruncated || documents.length < word.documents.length;
1331 word.documents = documents;
1332 for (const path of mediaSizes.keys()) if (!usedImages.has(path)) archive.remove(path);
1333 archive.file("word/document.xml", documents[0]!);
1334 }
1335 const workbook = input.kind === "xlsx" ? await boundWorkbook(archive) : undefined;
1336 return { archive, word, workbook };
1337}
1338
1339export async function prepareOffice(
1340 bytes: ArrayBuffer,
1341 kind: Extract<OfficeWorkerRequest, { type: "open" }>["kind"],
1342) {
1343 const result = await boundedArchive({ type: "open", kind, bytes });
1344 const root =
1345 kind === "docx"
1346 ? "word/document.xml"
1347 : kind === "xlsx"
1348 ? "xl/workbook.xml"
1349 : "ppt/presentation.xml";
1350 if (!result.archive.file(root))
1351 throw new Error("This is not a valid Office Open XML file. Encrypted files are not supported.");
1352 if (result.word) {
1353 const references = new Map<string, string>();
1354 const relationships = xmlParser();
1355 relationships.on("opentag", (tag) => {
1356 if (tag.local !== "Relationship") return;
1357 const type = tag.attributes.Type?.value ?? "";
1358 const target = tag.attributes.Target?.value ?? "";
1359 const path = new URL(target, "https://docx.invalid/word/").pathname.slice(1);
1360 if (result.archive.file(path))
1361 references.set(tag.attributes.Id?.value ?? "", type.slice(type.lastIndexOf("/") + 1));
1362 });
1363 const relationshipXml = await result.archive
1364 .file("word/_rels/document.xml.rels")
1365 ?.async("string");
1366 if (relationshipXml) relationships.write(relationshipXml).close();
1367 let xml = joinWordBatches(result.word.documents);
1368 const removed: { start: number; end: number }[] = [];
1369 const parser = xmlParser();
1370 let start = -1;
1371 // Bounded parts can be omitted; dangling story references otherwise reject the entire body in the engine.
1372 parser.on("opentag", (tag) => {
1373 if (tag.local !== "headerReference" && tag.local !== "footerReference") return;
1374 const id = Object.values(tag.attributes).find((attr) => attr.local === "id")?.value ?? "";
1375 if (references.get(id) !== tag.local.replace("Reference", ""))
1376 start = xml.lastIndexOf("<", parser.position - 1);
1377 });
1378 parser.on("closetag", (tag) => {
1379 if (start >= 0 && (tag.local === "headerReference" || tag.local === "footerReference")) {
1380 removed.push({ start, end: parser.position });
1381 start = -1;
1382 }
1383 });
1384 parser.write(xml).close();
1385 for (const range of removed.toReversed())
1386 xml = xml.slice(0, range.start) + xml.slice(range.end);
1387 result.archive.file(root, xml);
1388 }
1389 return {
1390 bytes: await result.archive.generateAsync({ type: "arraybuffer", compression: "STORE" }),
1391 truncated:
1392 result.word?.truncated || result.workbook?.sheets.some((sheet) => sheet.truncated) || false,
1393 view: result.workbook && {
1394 hiddenGridlines: result.workbook.sheets.flatMap((sheet, index) =>
1395 sheet.gridlines ? [] : [index],
1396 ),
1397 themeFonts: result.workbook.themeFonts,
1398 },
1399 };
1400}
1401
1402function joinWordBatches(documents: string[]) {
1403 let prefix = "";
1404 let suffix = "";
1405 let section = "";
1406 const bodies: string[] = [];
1407 for (const xml of documents) {
1408 const parser = xmlParser();
1409 let depth = 0;
1410 let start = 0;
1411 let end = 0;
1412 let sectionStart = 0;
1413 parser.on("opentag", (tag) => {
1414 depth++;
1415 if (depth === 2 && tag.local === "body") {
1416 start = parser.position;
1417 if (!prefix) prefix = xml.slice(0, start);
1418 }
1419 if (depth === 3 && tag.local === "sectPr")
1420 sectionStart = xml.lastIndexOf("<", parser.position - 1);
1421 });
1422 parser.on("closetag", (tag) => {
1423 if (depth === 2 && tag.local === "body") {
1424 end = xml.lastIndexOf("<", parser.position - 1);
1425 suffix = xml.slice(end);
1426 }
1427 depth--;
1428 });
1429 parser.write(xml).close();
1430 bodies.push(xml.slice(start, sectionStart || end));
1431 section = sectionStart ? xml.slice(sectionStart, end) : "";
1432 }
1433 return prefix + bodies.join("") + section + suffix;
1434}