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