Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

officeArchive.ts

1,426 lines56.5 KB

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;
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]);
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"');
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("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;");
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 };
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 };
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("&", "&amp;")
346 .replaceAll('"', "&quot;")
347 .replaceAll("<", "&lt;");
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 const kept = shown.slice(0, Math.min(4096, budget.remaining));
415 budget.remaining -= kept.length;
416 if (kept.length < shown.length) {
417 truncated = true;
418 const escape = (s: string) =>
419 s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
420 cells.set(
421 column,
422 cell.opening
423 .replace(/\s+t\s*=\s*(?:"[^"]*"|'[^']*')/, "")
424 .replace(/>$/, ' t="inlineStr">') +
425 `<${cell.prefix}is><${cell.prefix}t>` +
426 escape(kept) +
427 `</${cell.prefix}t></${cell.prefix}is></${cell.name}>`,
428 );
429 } else cells.set(column, raw);
430 cell = null;
431 } else if (depth === 3 && tag.local === "row" && row <= OFFICE_PREVIEW_MAX_ROWS) {
432 rows.set(row, cells);
433 rowTags.set(row, rowTag);
434 }
435 if (depth === 2 && tag.local === "sheetData")
436 dataEnd = emptyData ? parser.position : xml.lastIndexOf("<", parser.position - 1);
437 if (cell?.reading === tag.local) cell.reading = "";
438 depth--;
439 });
440 parser.write(xml).close();
441 if (!dataStart) throw new PreviewError({ code: "workbook-no-data" });
442 const boundRange = (ref: string) => {
443 const [a, b = a] = ref.split(":");
444 const first = coordinate(a!);
445 const last = coordinate(b!);
446 if (first.col > OFFICE_PREVIEW_MAX_COLUMNS || first.line > OFFICE_PREVIEW_MAX_ROWS) return "";
447 let letters = "";
448 for (
449 let col = Math.min(OFFICE_PREVIEW_MAX_COLUMNS, last.col);
450 col > 0;
451 col = Math.floor((col - 1) / 26)
452 )
453 letters = String.fromCharCode(65 + ((col - 1) % 26)) + letters;
454 return a + ":" + letters + Math.min(OFFICE_PREVIEW_MAX_ROWS, last.line);
455 };
456 const metadata = (part: string) =>
457 part.replace(
458 /(<((?:\w+:)?(?:dimension|mergeCell|col))\b(?:[^"'<>]|"[^"]*"|'[^']*')*>)(?:\s*<\/\2\s*>)?/g,
459 (tag: string, opening: string) => {
460 const attributes = metadataAttributes.get(opening);
461 if (!attributes) return tag;
462 const replace = (name: string, value: string) => {
463 const pattern = new RegExp(`\\s${name}\\s*=\\s*(?:"[^"]*"|'[^']*')`);
464 tag = pattern.test(tag)
465 ? tag.replace(pattern, ` ${name}="${value}"`)
466 : tag.replace(/\/?>/, (end) => ` ${name}="${value}"${end}`);
467 };
468 if (attributes.ref !== undefined) {
469 const bounded = boundRange(attributes.ref);
470 if (!bounded) return "";
471 replace("ref", bounded);
472 }
473 if (/<(?:\w+:)?col\b/.test(opening)) {
474 const min = Math.max(1, Number(attributes.min ?? 1));
475 // Hidden columns keep their full span, or the columns past the limit would show again.
476 const hidden = attributes.hidden === "1" || attributes.hidden === "true";
477 const max = Math.min(
478 hidden ? 16384 : OFFICE_PREVIEW_MAX_COLUMNS,
479 Number(attributes.max ?? 16384),
480 );
481 if (!Number.isInteger(min) || !Number.isInteger(max) || min > max) return "";
482 replace("min", String(min));
483 replace("max", String(max));
484 }
485 return tag;
486 },
487 );
488 // The engine sizes columns without a width at Excel's 8.43 characters and ignores `defaultColWidth`, so the
489 // columns it covers get that width spelled out. A second `<cols>` is valid: the schema allows any number.
490 let defaultColumns = "";
491 if (defaultWidth !== undefined) {
492 let next = 1;
493 for (const span of sizedColumns.toSorted((a, b) => a.min - b.min)) {
494 if (span.min > next)
495 defaultColumns += `<${dataPrefix}col min="${next}" max="${Math.min(span.min - 1, OFFICE_PREVIEW_MAX_COLUMNS)}" width="${defaultWidth}"/>`;
496 next = Math.max(next, span.max + 1);
497 if (next > OFFICE_PREVIEW_MAX_COLUMNS) break;
498 }
499 if (next <= OFFICE_PREVIEW_MAX_COLUMNS)
500 defaultColumns += `<${dataPrefix}col min="${next}" max="${OFFICE_PREVIEW_MAX_COLUMNS}" width="${defaultWidth}"/>`;
501 if (defaultColumns)
502 defaultColumns = `<${dataPrefix}cols xmlns${dataPrefix ? `:${dataPrefix.slice(0, -1)}` : ""}="${dataNamespace}">${defaultColumns}</${dataPrefix}cols>`;
503 }
504 const head = (part: string) =>
505 metadata(part.slice(0, dataTag) + defaultColumns + part.slice(dataTag));
506 return {
507 xml: emptyData
508 ? head(xml)
509 : `${head(xml.slice(0, dataStart))}${[...rows]
510 .sort(([a], [b]) => a - b)
511 .map(
512 ([line, values]) =>
513 `${rowTags.get(line) ?? `<row r="${line}">`}${[...values]
514 .sort(([a], [b]) => a - b)
515 .map(([, value]) => value)
516 .join("")}</${/^<([^\s>]+)/.exec(rowTags.get(line) ?? "<row>")![1]}>`,
517 )
518 .join("")}${metadata(xml.slice(dataEnd))}`,
519 truncated,
520 gridlines: gridlines ?? true,
521 };
523​
524/**
525 * A stylesheet as Excel reads it, in the terms the engine understands. The engine takes a number format id under 164 as
526 * Excel's built-in one, though workbooks define their own there (Excel writes its locale formats 5 to 8 that way), so
527 * those move to free ids. It also reads `<u val="…">` as a boolean, which loses every named underline but the bare one.
528 */
529function engineStyles(xml: string) {
530 const name = (local: string) => `<((?:[\\w.-]+:)?)${local}\\b`;
531 const blocks = new Map<string, { start: number; end: number }>();
532 const parser = xmlParser();
533 let depth = 0;
534 parser.on("opentag", (tag) => {
535 if (++depth > 64) throw new PreviewError({ code: "workbook-xml-nesting" });
536 if (depth !== 2 || !["numFmts", "cellStyleXfs", "cellXfs"].includes(tag.local)) return;
537 if (blocks.has(tag.local)) throw new PreviewError({ code: "workbook-duplicate-styles" });
538 blocks.set(tag.local, {
539 start: xml.lastIndexOf("<", parser.position - 1),
540 end: parser.position,
541 });
542 });
543 parser.on("closetag", (tag) => {
544 if (depth === 2) {
545 const block = blocks.get(tag.local);
546 if (block) block.end = parser.position;
547 }
548 depth--;
549 });
550 parser.write(xml).close();
551 const id = /(numFmtId\s*=\s*)(["'])(\d+)\2/g;
552 const moved = new Map<number, number>();
553 const formatBlock = blocks.get("numFmts");
554 const formats = formatBlock ? xml.slice(formatBlock.start, formatBlock.end) : "";
555 const used = new Set([...formats.matchAll(id)].map((match) => Number(match[3])));
556 let next = 164;
557 const renumber = (part: string, assign: boolean) =>
558 part.replace(id, (attribute: string, key: string, quote: string, value: string) => {
559 const number = Number(value);
560 if (assign && number < 164 && !moved.has(number)) {
561 while (used.has(next)) next++;
562 if (next > 65535) throw new PreviewError({ code: "workbook-number-formats" });
563 moved.set(number, next++);
564 }
565 const to = moved.get(number);
566 return to === undefined ? attribute : `${key}${quote}${to}${quote}`;
567 });
568 const numberedFormats = renumber(formats, true);
569 const parts: string[] = [];
570 let offset = 0;
571 for (const [local, block] of blocks) {
572 parts.push(
573 xml.slice(offset, block.start),
574 local === "numFmts" ? numberedFormats : renumber(xml.slice(block.start, block.end), false),
575 );
576 offset = block.end;
577 }
578 parts.push(xml.slice(offset));
579 return parts
580 .join("")
581 .replace(
582 new RegExp(
583 `${name("u")}\\s+val\\s*=\\s*(["'])(?:single|double|singleAccounting|doubleAccounting)\\2\\s*(?:/>|>\\s*</\\1u\\s*>)`,
584 "g",
585 ),
586 "<$1u/>",
587 );
589​
590async function boundWorkbook(archive: JSZip) {
591 const paths = new Map<string, string>();
592 // Chart sheets and other non-grid sheets hold no cells to bound.
593 const otherSheets = new Set<string>();
594 let sharedPath = "xl/sharedStrings.xml";
595 let stylesPath = "xl/styles.xml";
596 let themePath = "xl/theme/theme1.xml";
597 const relationships = xmlParser();
598 relationships.on("opentag", (tag) => {
599 if (tag.local !== "Relationship") return;
600 const type = tag.attributes.Type?.value;
601 const target = tag.attributes.Target?.value ?? "";
602 // Resolve as the engine does: literal ZIP names split on `/`, never URL syntax or escapes.
603 const segments = target.startsWith("/") ? [] : ["xl"];
604 for (const segment of target.split("/")) {
605 if (segment === "..") segments.pop();
606 else if (segment && segment !== ".") segments.push(segment);
607 }
608 const external = tag.attributes.TargetMode?.value.toLowerCase() === "external";
609 // The engine reads an external worksheet from its default part, so leave it unresolved to refuse it.
610 const path = external && type?.endsWith("/worksheet") ? "" : segments.join("/");
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 PreviewError({ code: "workbook-sheet-count" });
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 PreviewError({ code: "workbook-missing-sheet" });
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 };
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 if (!external) {
765 const folder = path === "_rels/.rels" ? "" : path.replace(/_rels\/[^/]+\.rels$/, "");
766 // Preserve archive URL resolution, including literal query/fragment
767 // characters in ZIP names rather than silently classifying another file.
768 const target = new URL(attr("Target"), `https://docx.invalid/${folder}`)
769 .toString()
770 .slice("https://docx.invalid/".length);
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 PreviewError({ code: "word-limited-aliased-part" });
788 if (type === WORD_RELATIONSHIP + "officeDocument" && target !== "word/document.xml")
789 throw new PreviewError({ code: "word-limited-relationship" });
790 }
791 if (
792 (external && !(role === "hyperlink" && externalUrl(attr("Target")))) ||
793 WORD_DISABLED_PARTS.has(role)
794 ) {
795 start = xml.lastIndexOf("<", parser.position - 1);
796 }
797 });
798 parser.on("closetag", (tag) => {
799 if (tag.local === "Relationship" && start >= 0) {
800 removed.push({ start, end: parser.position });
801 start = -1;
802 }
803 });
804 parser.write(xml).close();
805 for (const range of removed.toReversed())
806 xml = xml.slice(0, range.start) + xml.slice(range.end);
807 return xml;
808 },
809 };
811​
812// Bound inherited style and numbering expansion before the engine loads it.
813// Picture bullets can duplicate embedded images, so `pictures` locates those definitions to omit.
814function wordXmlCost(xml: string, roles: Set<string> | undefined) {
815 const parser = xmlParser();
816 let depth = 0;
817 let markup = 0;
818 const limit = Symbol("Word style budget");
819 const exceeded = {
820 bytes: Infinity,
821 markup: Infinity,
822 pictures: [] as { start: number; end: number }[],
823 };
824 let styleCount = 0;
825 let ownUnits = 0;
826 const styles = new Map<
827 string,
828 { properties: Map<string, number>; base: string; linked: string }
829 >();
830 let style: { id: string; base: string; linked: string; properties: Map<string, number> } | null =
831 null;
832 const names: string[] = [];
833 const definitions = new Map<string, { bytes: number; markup: number }>();
834 const references: { id: string; selector: number }[] = [];
835 let definition: { id: string; start: number; markup: number } | null = null;
836 let reference: { id: string; selector: number } | null = null;
837 const pictures: { start: number; end: number }[] = [];
838 let picture: { start: number; depth: number } | null = null;
839 parser.on("opentag", (tag) => {
840 if (++depth > 64) throw new PreviewError({ code: "word-limited-xml-nesting" });
841 markup++;
842 const attr = (name: string) =>
843 Object.values(tag.attributes).find((a) => a.local === name)?.value ?? "";
844 names.push(tag.local === "tblStylePr" ? `${tag.local}:${attr("type")}` : tag.local);
845 if (roles?.has("styles") && (tag.local === "style" || tag.local === "docDefaults")) {
846 if (++styleCount > WORD_LIMITS.styles || attr("styleId").length > 256) throw limit;
847 style = { id: attr("styleId"), properties: new Map(), base: "", linked: "" };
848 }
849 if (style) {
850 if (tag.local === "basedOn") style.base = attr("val");
851 else if (tag.local === "link") style.linked = attr("val");
852 else if (names.length > 2 && tag.local !== "name") {
853 const key = names.slice(2).join("/");
854 const size = new TextEncoder().encode(
855 xml.slice(xml.lastIndexOf("<", parser.position - 1), parser.position),
856 ).length;
857 if (++ownUnits > WORD_LIMITS.styleUnits) throw limit;
858 style.properties.set(key, size);
859 }
860 }
861 if (roles?.has("numbering")) {
862 if (tag.local === "abstractNum")
863 definition = {
864 id: attr("abstractNumId"),
865 start: xml.lastIndexOf("<", parser.position - 1),
866 markup: markup - 1,
867 };
868 if (tag.local === "num") {
869 if (references.length >= WORD_LIMITS.numberingReferences) throw limit;
870 reference = { id: "", selector: attr("numId").length + 32 };
871 references.push(reference);
872 }
873 if (tag.local === "abstractNumId" && reference) reference.id = attr("val");
874 }
875 if (!picture && (tag.local === "numPicBullet" || tag.local === "lvlPicBulletId"))
876 picture = { start: xml.lastIndexOf("<", parser.position - 1), depth };
877 });
878 parser.on("closetag", (tag) => {
879 if (picture?.depth === depth) {
880 pictures.push({ start: picture.start, end: parser.position });
881 picture = null;
882 }
883 if (definition && tag.local === "abstractNum") {
884 const previous = definitions.get(definition.id);
885 definitions.set(definition.id, {
886 bytes:
887 (previous?.bytes ?? 0) +
888 new TextEncoder().encode(xml.slice(definition.start, parser.position)).length,
889 markup: (previous?.markup ?? 0) + markup - definition.markup,
890 });
891 definition = null;
892 }
893 if (tag.local === "num") reference = null;
894 if (style && (tag.local === "style" || tag.local === "docDefaults")) {
895 styles.set(style.id, style);
896 style = null;
897 }
898 names.pop();
899 depth--;
900 });
901 try {
902 parser.write(xml).close();
903 } catch (cause) {
904 if (cause !== limit) throw cause;
905 return exceeded;
906 }
907 const rawBytes = new TextEncoder().encode(xml).length;
908 if (roles?.has("styles")) {
909 // Immutable parent pointers match processStyles' ordered merges (including
910 // forward links and cycles) without copying an expanding property map.
911 type Resolved = {
912 properties: Map<string, number>;
913 parent?: Resolved | undefined;
914 depth: number;
915 };
916 const resolved = new Map<string, Resolved>();
917 for (const [id, style] of styles) resolved.set(id, { properties: style.properties, depth: 1 });
918 for (const [id, style] of styles) {
919 const parent = style.base ? resolved.get(style.base) : undefined;
920 if (parent && parent.depth >= 32) return exceeded;
921 resolved.set(id, { properties: style.properties, parent, depth: (parent?.depth ?? 0) + 1 });
922 }
923 let bytes = 0;
924 let expandedMarkup = 0;
925 let visited = 0;
926 let propertyVisits = 0;
927 for (const [id, style] of styles) {
928 for (const root of [
929 resolved.get(id),
930 style.linked ? resolved.get(style.linked) : undefined,
931 ]) {
932 const seen = new Set<string>();
933 for (let node = root; node; node = node.parent) {
934 if (++visited > WORD_LIMITS.styleVisits) return exceeded;
935 for (const [key, size] of node.properties) {
936 if (++propertyVisits > WORD_LIMITS.stylePropertyVisits) return exceeded;
937 if (seen.has(key)) continue;
938 // Latent styles never enter properties. Charge each own property
939 // once per resolved style, including linked and default selectors.
940 const copies = id ? 1 : 2;
941 bytes += (size * 2 + id.length + 32) * copies;
942 expandedMarkup += copies;
943 if (bytes > WORD_LIMITS.styleBytes || expandedMarkup > WORD_LIMITS.styleUnits)
944 return exceeded;
945 seen.add(key);
946 }
947 }
948 }
949 }
950 return { bytes, markup: expandedMarkup, pictures };
951 }
952 let bytes = rawBytes;
953 if (roles?.has("numbering")) {
954 for (const ref of references) {
955 const cost = definitions.get(ref.id);
956 if (!cost) continue;
957 bytes += cost.bytes * 2 + cost.markup * ref.selector;
958 markup += cost.markup;
959 if (bytes > WORD_LIMITS.numberingBytes || markup > WORD_LIMITS.numberingMarkup)
960 return exceeded;
961 }
962 }
963 return { bytes, markup, pictures };
965​
966// Layout can repeat notes at references and headers/footers across pages.
967// Charge those copies, not just the XML that defines them.
968async function wordExpansion(
969 archive: JSZip,
970 parts: ReturnType<typeof wordPartTypes>,
971 mediaSizes: Map<string, number>,
972 auxiliaryCosts: Map<string, { bytes: number; markup: number }>,
973 documents: string[],
974) {
975 type Cost = { bytes: number; markup: number; media: number; images: Set<string> };
976 const empty = (): Cost => ({ bytes: 0, markup: 0, media: 0, images: new Set() });
977 const nodes = new Map<string, { xml: string; path: string }>();
978 const optional = new Set<string>();
979 const noteParts = new Map<string, string>();
980 for (const [path, roles] of parts.roles) {
981 if (![...roles].some((role) => WORD_EXPANDED_PARTS.has(role))) continue;
982 const xml = await archive.file(path)?.async("string");
983 if (!xml) continue;
984 optional.add(path);
985 if (roles.has("header") || roles.has("footer")) nodes.set(path, { xml, path });
986 for (const role of ["footnotes", "endnotes", "comments"]) {
987 if (!roles.has(role)) continue;
988 noteParts.set(role.slice(0, -1), path);
989 const parser = xmlParser();
990 let start = 0;
991 let id = "";
992 let depth = 0;
993 let prefix = "";
994 let suffix = "";
995 parser.on("opentag", (tag) => {
996 if (++depth === 1) {
997 prefix = xml.slice(0, parser.position);
998 suffix = `</${tag.name}>`;
999 }
1000 if (tag.local !== role.slice(0, -1)) return;
1001 start = xml.lastIndexOf("<", parser.position - 1);
1002 id = Object.values(tag.attributes).find((attr) => attr.local === "id")?.value ?? "";
1003 });
1004 parser.on("closetag", (tag) => {
1005 if (tag.local === role.slice(0, -1))
1006 nodes.set(`${path}#${id}`, {
1007 xml: prefix + xml.slice(start, parser.position) + suffix,
1008 path,
1009 });
1010 depth--;
1011 });
1012 parser.write(xml).close();
1015 const used = new Set<string>();
1016 const memo = new Map<string, Cost>();
1017 let expandedXmlBytes = 0;
1018 const scan = (xml: string, path: string, chain: Set<string>, pages = 1, expand = true): Cost => {
1019 const cost = empty();
1020 const refs = new Map<string, number>();
1021 const headers = new Set<string>();
1022 const parser = xmlParser();
1023 const add = (key: string) => refs.set(key, (refs.get(key) ?? 0) + 1);
1024 parser.on("opentag", (tag) => {
1025 const attr = (name: string) =>
1026 Object.values(tag.attributes).find((a) => a.local === name)?.value ?? "";
1027 const note = /^(footnote|endnote|comment)Reference$/.exec(tag.local)?.[1];
1028 if (note && noteParts.has(note)) add(`${noteParts.get(note)}#${attr("id")}`);
1029 if (tag.local === "headerReference" || tag.local === "footerReference") {
1030 const target = parts.relationships.get(path)?.get(attr("id"));
1031 if (target) headers.add(target);
1033 if (tag.local === "altChunk") cost.bytes = Infinity;
1034 if (tag.local !== "blip" && tag.local !== "imagedata") return;
1035 const target = parts.relationships.get(path)?.get(attr("embed") || attr("id"));
1036 if (target) {
1037 cost.media += mediaSizes.get(target) ?? OFFICE_PREVIEW_MAX_BYTES + 1;
1038 cost.images.add(target);
1040 });
1041 parser.write(xml).close();
1042 for (const header of headers) refs.set(header, pages);
1043 if (!expand) return cost;
1044 for (const [key, copies] of refs) {
1045 const node = nodes.get(key);
1046 if (!node) continue;
1047 used.add(node.path);
1048 if (chain.has(key) || chain.size >= 64) {
1049 cost.bytes = Infinity;
1050 break;
1052 let expanded = memo.get(key);
1053 if (!expanded) {
1054 expandedXmlBytes += node.xml.length * 2;
1055 if (expandedXmlBytes > WORD_LIMITS.expandedBytes) {
1056 cost.bytes = Infinity;
1057 break;
1059 const own = wordXmlCost(node.xml, undefined);
1060 expanded = scan(node.xml, node.path, new Set([...chain, key]));
1061 expanded.bytes += own.bytes;
1062 expanded.markup += own.markup;
1063 memo.set(key, expanded);
1065 cost.bytes += expanded.bytes * copies;
1066 cost.markup += expanded.markup * copies;
1067 cost.media += expanded.media * copies;
1068 for (const image of expanded.images) cost.images.add(image);
1070 return cost;
1071 };
1072 const costs = new Map<string, Cost>();
1073 let bytes = 0;
1074 let markup = 0;
1075 let media = 0;
1076 // Styles may introduce a page break before each styled paragraph. The page
1077 // bound also includes explicit breaks and section transitions in each batch.
1078 let stylePageBreaks = false;
1079 for (const [path, roles] of parts.roles)
1080 if (
1081 roles.has("styles") &&
1082 /<(?:\w+:)?pageBreakBefore\b/.test((await archive.file(path)?.async("string")) ?? "")
1084 stylePageBreaks = true;
1085 for (const document of documents) {
1086 const pages = Math.max(
1087 1,
1088 document.match(
1089 stylePageBreaks ? /<(?:\w+:)?p\b/g : /<(?:\w+:)?(?:br|pageBreakBefore|sectPr)\b/g,
1090 )?.length ?? 0,
1091 );
1092 const expanded = scan(document, "word/document.xml", new Set(), pages);
1093 const body = wordXmlCost(document, undefined);
1094 bytes += body.bytes + expanded.bytes;
1095 markup += body.markup + expanded.markup;
1096 media += expanded.media;
1097 costs.set(document, expanded);
1099 for (const [path, cost] of auxiliaryCosts) {
1100 if (optional.has(path) && !used.has(path)) continue;
1101 bytes += cost.bytes;
1102 markup += cost.markup;
1104 const overBudget =
1105 bytes > WORD_LIMITS.expandedBytes ||
1106 markup > WORD_LIMITS.expandedMarkup ||
1107 media > OFFICE_PREVIEW_MAX_BYTES;
1108 const truncated = (used.size > 0 && overBudget) || bytes === Infinity;
1109 const omitted = new Set([...optional].filter((path) => truncated || !used.has(path)));
1110 for (const path of omitted) archive.remove(path);
1111 if (truncated)
1112 for (const document of documents)
1113 costs.set(document, scan(document, "word/document.xml", new Set(), 1, false));
1114 // Remove relationships too: related XML is parsed even when not rendered.
1115 for (const [owner, refs] of parts.relationships) {
1116 const ids = new Set([...refs].filter(([, path]) => omitted.has(path)).map(([id]) => id));
1117 if (ids.size === 0) continue;
1118 const relPath = owner ? owner.replace(/([^/]+)$/, "_rels/$1.rels") : "_rels/.rels";
1119 let xml = await archive.file(relPath)?.async("string");
1120 if (!xml) continue;
1121 const removed: { start: number; end: number }[] = [];
1122 const parser = xmlParser();
1123 let start = -1;
1124 parser.on("opentag", (tag) => {
1125 if (tag.local === "Relationship" && ids.has(tag.attributes.Id?.value ?? ""))
1126 start = xml!.lastIndexOf("<", parser.position - 1);
1127 });
1128 parser.on("closetag", (tag) => {
1129 if (tag.local === "Relationship" && start >= 0) {
1130 removed.push({ start, end: parser.position });
1131 start = -1;
1133 });
1134 parser.write(xml).close();
1135 for (const range of removed.toReversed())
1136 xml = xml.slice(0, range.start) + xml.slice(range.end);
1137 archive.file(relPath, xml);
1139 return { costs, truncated, omitted };
1141​
1142// Stream each entry before handing it to an engine. A tiny compressed archive
1143// must not turn into an unbounded allocation on the UI thread.
1144export async function boundedArchive(input: Extract<OfficeWorkerRequest, { type: "open" }>) {
1145 const { bytes } = input;
1146 const spreadsheet = input.kind === "xlsx";
1147 if (bytes.byteLength > OFFICE_PREVIEW_MAX_BYTES)
1148 throw new PreviewError({ code: "file-too-large" });
1149 checkZipDirectory(bytes);
1150 const source = await JSZip.loadAsync(bytes).catch(() => {
1151 throw new PreviewError({ code: "office-invalid" });
1152 });
1153 const allEntries = Object.values(source.files);
1154 if (allEntries.length > 2048) throw new PreviewError({ code: "office-too-many-entries" });
1155 const entries = allEntries.filter((entry) => !entry.dir);
1156 if (
1157 input.kind === "docx" &&
1158 entries.some((entry) => entry.name.includes("\\") || entry.name.startsWith("/"))
1160 throw new PreviewError({ code: "word-limited-archive-paths" });
1161 const archive = new JSZip();
1162 const partTypes = wordPartTypes();
1163 // Metadata must be bounded and classified before any payload gets a media exemption.
1164 if (input.kind === "docx")
1165 entries.sort(
1166 (a, b) =>
1167 Number(b.name === "[Content_Types].xml" || b.name.endsWith(".rels")) -
1168 Number(a.name === "[Content_Types].xml" || a.name.endsWith(".rels")),
1169 );
1170 const costs = new Map<string, { bytes: number; markup: number }>();
1171 const mediaSizes = new Map<string, number>();
1172 let total = 0;
1173 let wordAuxiliaryMarkup = 0;
1174 let wordInputTruncated = false;
1175 let word: ReturnType<typeof wordDocuments> | null = null;
1176 for (const entry of entries) {
1177 const document = input.kind === "docx" && entry.name === "word/document.xml";
1178 const media = input.kind === "docx" && partTypes.binary(entry.name);
1179 const chunks: Uint8Array[] = [];
1180 const sections = document ? wordSections() : null;
1181 let decoder: TextDecoder | undefined;
1182 let length = 0;
1183 await new Promise<void>((resolve, reject) => {
1184 // JSZip exposes this streaming API at runtime but omits it from its types.
1185 const stream = (
1186 entry as JSZip.JSZipObject & {
1187 internalStream(type: "uint8array"): JSZip.JSZipStreamHelper<Uint8Array>;
1189 ).internalStream("uint8array");
1190 stream
1191 .on("data", (chunk: Uint8Array) => {
1192 total += chunk.length;
1193 length += chunk.length;
1194 if (total > (spreadsheet ? 128 * 1024 * 1024 : OFFICE_PREVIEW_MAX_BYTES)) {
1195 stream.pause();
1196 reject(new PreviewError({ code: "office-too-large-expanded" }));
1197 return;
1199 try {
1200 if (sections) {
1201 decoder ??= officeXmlDecoder(chunk);
1202 sections.write(decoder.decode(chunk, { stream: true }));
1204 } catch (cause) {
1205 stream.pause();
1206 reject(cause);
1207 return;
1209 if (document && length > 4 * 1024 * 1024) {
1210 const kept = Math.max(0, chunk.length - (length - 4 * 1024 * 1024));
1211 if (kept) chunks.push(chunk.subarray(0, kept));
1212 wordInputTruncated = true;
1213 return;
1215 // Media is bounded independently. Even renamed auxiliary XML must
1216 // stay small before the engine parses it.
1217 if (input.kind === "docx" && !document && !media) {
1218 for (const byte of chunk) if (byte === 0x3c) wordAuxiliaryMarkup++;
1219 if (
1220 length > WORD_LIMITS.auxiliaryPartBytes ||
1221 wordAuxiliaryMarkup > WORD_LIMITS.auxiliaryMarkup
1222 ) {
1223 stream.pause();
1224 reject(new PreviewError({ code: "word-limited-auxiliary-markup" }));
1225 return;
1228 if (
1229 total > (spreadsheet ? 128 * 1024 * 1024 : OFFICE_PREVIEW_MAX_BYTES) ||
1230 (spreadsheet && total > Math.max(bytes.byteLength * 200, 8 * 1024 * 1024)) ||
1231 (!document &&
1232 (spreadsheet || media || entry.name.endsWith(".xml")) &&
1233 length > (spreadsheet ? 64 * 1024 * 1024 : 8 * 1024 * 1024))
1234 ) {
1235 stream.pause();
1236 reject(new PreviewError({ code: "office-too-large-expanded" }));
1237 } else chunks.push(chunk);
1238 })
1239 .on("error", reject)
1240 .on("end", resolve)
1241 .resume();
1242 });
1243 const content = new Uint8Array(document ? Math.min(length, 4 * 1024 * 1024) : length);
1244 let offset = 0;
1245 for (const chunk of chunks) {
1246 content.set(chunk, offset);
1247 offset += chunk.length;
1249 if (document) {
1250 sections!.write(decoder?.decode() ?? "");
1251 word = wordDocuments(officeXml(content), wordInputTruncated, sections!.finish());
1252 archive.file(entry.name, word.documents[0]!);
1253 } else if (input.kind === "docx" && !media) {
1254 let xml = officeXml(content);
1255 if (entry.name === "[Content_Types].xml" || entry.name.endsWith(".rels"))
1256 xml = partTypes.metadata(entry.name, xml);
1257 const roles = partTypes.roles.get(entry.name);
1258 let cost = wordXmlCost(xml, roles);
1259 // The renderer parses related parts even when their render option is off.
1260 if (roles && [...roles].every((role) => WORD_DISABLED_PARTS.has(role))) continue;
1261 // Picture bullets come out, and their list levels keep the text bullets Word falls back to.
1262 if (roles?.has("numbering") && cost.pictures.length > 0) {
1263 for (const range of cost.pictures.toReversed())
1264 xml = xml.slice(0, range.start) + xml.slice(range.end);
1265 cost = wordXmlCost(xml, roles);
1266 wordInputTruncated = true;
1268 if (
1269 (roles?.has("styles") &&
1270 (cost.bytes > WORD_LIMITS.styleBytes || cost.markup > WORD_LIMITS.styleUnits)) ||
1271 (roles?.has("numbering") &&
1272 (cost.bytes > WORD_LIMITS.numberingBytes || cost.markup > WORD_LIMITS.numberingMarkup))
1273 ) {
1274 wordInputTruncated = true;
1275 continue;
1277 costs.set(entry.name, cost);
1278 archive.file(entry.name, xml);
1279 } else {
1280 if (input.kind === "docx" && partTypes.roles.get(entry.name)?.has("font")) {
1281 continue;
1283 if (media) mediaSizes.set(entry.name, Math.ceil((content.length * 4) / 3));
1284 archive.file(entry.name, /\.(?:xml|rels)$/i.test(entry.name) ? officeXml(content) : content);
1287 if (word) {
1288 const expansion = await wordExpansion(archive, partTypes, mediaSizes, costs, word.documents);
1289 wordInputTruncated ||= expansion.truncated;
1290 for (const path of expansion.omitted) {
1291 archive.remove(path);
1292 costs.delete(path);
1294 let mediaBytes = 0;
1295 const usedImages = new Set<string>();
1296 const auxiliary = [...costs.values()].reduce(
1297 (sum, cost) => ({ bytes: sum.bytes + cost.bytes, markup: sum.markup + cost.markup }),
1298 { bytes: 0, markup: 0 },
1299 );
1300 // The worker engine parses shared parts once, rather than once per legacy render batch.
1301 let bytes = auxiliary.bytes;
1302 let markup = auxiliary.markup;
1303 const documents: string[] = [];
1304 for (const document of word.documents) {
1305 const rawCost = wordXmlCost(document, undefined);
1306 const extra = expansion.costs.get(document)!;
1307 const cost = { bytes: rawCost.bytes + extra.bytes, markup: rawCost.markup + extra.markup };
1308 const images = extra.media;
1309 const batchImages = new Set(extra.images);
1310 if (
1311 bytes + cost.bytes > WORD_LIMITS.expandedBytes ||
1312 markup + cost.markup > WORD_LIMITS.expandedMarkup ||
1313 mediaBytes + images > OFFICE_PREVIEW_MAX_BYTES
1315 break;
1316 bytes += cost.bytes;
1317 markup += cost.markup;
1318 mediaBytes += images;
1319 for (const path of batchImages) usedImages.add(path);
1320 documents.push(document);
1322 if (documents.length === 0) throw new PreviewError({ code: "word-limited-expanded-markup" });
1323 word.truncated ||= wordInputTruncated || documents.length < word.documents.length;
1324 word.documents = documents;
1325 for (const path of mediaSizes.keys()) if (!usedImages.has(path)) archive.remove(path);
1326 archive.file("word/document.xml", documents[0]!);
1328 const workbook = input.kind === "xlsx" ? await boundWorkbook(archive) : undefined;
1329 return { archive, word, workbook };
1331​
1332export async function prepareOffice(
1333 bytes: ArrayBuffer,
1334 kind: Extract<OfficeWorkerRequest, { type: "open" }>["kind"],
1335) {
1336 const result = await boundedArchive({ type: "open", kind, bytes });
1337 const root =
1338 kind === "docx"
1339 ? "word/document.xml"
1340 : kind === "xlsx"
1341 ? "xl/workbook.xml"
1342 : "ppt/presentation.xml";
1343 if (!result.archive.file(root)) throw new PreviewError({ code: "office-not-open-xml" });
1344 if (result.word) {
1345 const references = new Map<string, string>();
1346 const relationships = xmlParser();
1347 relationships.on("opentag", (tag) => {
1348 if (tag.local !== "Relationship") return;
1349 const type = tag.attributes.Type?.value ?? "";
1350 const target = tag.attributes.Target?.value ?? "";
1351 const path = new URL(target, "https://docx.invalid/word/").pathname.slice(1);
1352 if (result.archive.file(path))
1353 references.set(tag.attributes.Id?.value ?? "", type.slice(type.lastIndexOf("/") + 1));
1354 });
1355 const relationshipXml = await result.archive
1356 .file("word/_rels/document.xml.rels")
1357 ?.async("string");
1358 if (relationshipXml) relationships.write(relationshipXml).close();
1359 let xml = joinWordBatches(result.word.documents);
1360 const removed: { start: number; end: number }[] = [];
1361 const parser = xmlParser();
1362 let start = -1;
1363 // Bounded parts can be omitted; dangling story references otherwise reject the entire body in the engine.
1364 parser.on("opentag", (tag) => {
1365 if (tag.local !== "headerReference" && tag.local !== "footerReference") return;
1366 const id = Object.values(tag.attributes).find((attr) => attr.local === "id")?.value ?? "";
1367 if (references.get(id) !== tag.local.replace("Reference", ""))
1368 start = xml.lastIndexOf("<", parser.position - 1);
1369 });
1370 parser.on("closetag", (tag) => {
1371 if (start >= 0 && (tag.local === "headerReference" || tag.local === "footerReference")) {
1372 removed.push({ start, end: parser.position });
1373 start = -1;
1375 });
1376 parser.write(xml).close();
1377 for (const range of removed.toReversed())
1378 xml = xml.slice(0, range.start) + xml.slice(range.end);
1379 result.archive.file(root, xml);
1381 return {
1382 bytes: await result.archive.generateAsync({ type: "arraybuffer", compression: "STORE" }),
1383 truncated:
1384 result.word?.truncated || result.workbook?.sheets.some((sheet) => sheet.truncated) || false,
1385 view: result.workbook && {
1386 hiddenGridlines: result.workbook.sheets.flatMap((sheet, index) =>
1387 sheet.gridlines ? [] : [index],
1388 ),
1389 themeFonts: result.workbook.themeFonts,
1390 },
1391 };
1393​
1394function joinWordBatches(documents: string[]) {
1395 let prefix = "";
1396 let suffix = "";
1397 let section = "";
1398 const bodies: string[] = [];
1399 for (const xml of documents) {
1400 const parser = xmlParser();
1401 let depth = 0;
1402 let start = 0;
1403 let end = 0;
1404 let sectionStart = 0;
1405 parser.on("opentag", (tag) => {
1406 depth++;
1407 if (depth === 2 && tag.local === "body") {
1408 start = parser.position;
1409 if (!prefix) prefix = xml.slice(0, start);
1411 if (depth === 3 && tag.local === "sectPr")
1412 sectionStart = xml.lastIndexOf("<", parser.position - 1);
1413 });
1414 parser.on("closetag", (tag) => {
1415 if (depth === 2 && tag.local === "body") {
1416 end = xml.lastIndexOf("<", parser.position - 1);
1417 suffix = xml.slice(end);
1419 depth--;
1420 });
1421 parser.write(xml).close();
1422 bodies.push(xml.slice(start, sectionStart || end));
1423 section = sectionStart ? xml.slice(sectionStart, end) : "";
1425 return prefix + bodies.join("") + section + suffix;