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

officeArchive.ts

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