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

officeArchive.ts

1,384 lines54.4 KB

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