Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off -- isolated CLI worker; no server runtime is loaded here.
2import * as NodeFSP from "node:fs/promises";
3import * as NodePath from "node:path";
4import * as NodeUtil from "node:util";
5import { characterEntities } from "character-entities";
6import { SaxesParser } from "saxes";
7import * as Yauzl from "yauzl";
8
9const MAX_INPUT = 16 * 1024 * 1024;
10const MAX_EXPANDED = 32 * 1024 * 1024;
11const MAX_OUTPUT = 1_000_000;
12const CELL_START = Symbol("cell-start");
13const CELL_END = Symbol("cell-end");
14type TextPart = string | typeof CELL_START | typeof CELL_END | { fallback: string };
15
16const TRUNCATED = "\n\n[Extracted text truncated at document extraction limits.]";
17// Parts the document never displays: the XHTML head, tracked deletions and moves, field codes,
18// phonetic guides, paragraph properties such as tab-stop definitions, drawing anchor layout
19// values and encoded field data.
20const HIDDEN = new Set([
21 "head",
22 "script",
23 "style",
24 "binary-data",
25 "rPh",
26 "delText",
27 "moveFrom",
28 "instrText",
29 "delInstrText",
30 "tracked-changes",
31 "pPr",
32 "positionH",
33 "positionV",
34 "sizeRelH",
35 "sizeRelV",
36 "fldData",
37 // An OpenDocument index keeps its templates beside the generated index; only the latter is content.
38 "table-of-content-source",
39 "illustration-index-source",
40 "table-index-source",
41 "object-index-source",
42 "user-index-source",
43 "alphabetical-index-source",
44 "bibliography-source",
45]);
46
47// @effect-diagnostics-next-line extendsNativeError:off - this worker loads no Effect runtime; Truncation is a local throw sentinel.
48class Truncation extends Error {}
49
50interface XmlNode {
51 name: string;
52 attrs: Record<string, string>;
53 children: Array<XmlNode | string>;
54 spaceCount?: number;
55 hasText?: boolean;
56 hasTextChoice?: boolean;
57}
58
59// ODF 1.3 Part 3 §6.1.2: paragraph character data turns TAB, CR and LF into spaces, collapses
60// space runs and trims the ends; only <text:s>, <text:tab> and <text:line-break> keep literal ones.
61function collapseOdfWhitespace(paragraph: XmlNode) {
62 let afterSpace = true;
63 let tail: { node: XmlNode; index: number; value: string } | undefined;
64 const visit = (node: XmlNode) => {
65 for (const [index, child] of node.children.entries()) {
66 if (typeof child !== "string") {
67 if (HIDDEN.has(child.name)) continue;
68 if (child.spaceCount === undefined && !["tab", "line-break", "p", "h"].includes(child.name))
69 visit(child);
70 else {
71 afterSpace = false;
72 tail = undefined;
73 }
74 continue;
75 }
76 let value = child.replaceAll(/[ \t\r\n]+/g, " ");
77 if (afterSpace && value.startsWith(" ")) value = value.slice(1);
78 if (value) {
79 afterSpace = value.endsWith(" ");
80 tail = { node, index, value };
81 }
82 node.children[index] = value;
83 }
84 };
85 visit(paragraph);
86 if (tail && afterSpace) tail.node.children[tail.index] = tail.value.slice(0, -1);
87}
88
89function xml(source: string, extension: string): XmlNode {
90 const odf = [".odt", ".ods", ".odp"].includes(extension);
91 const root: XmlNode = { name: "root", attrs: {}, children: [] };
92 const stack = [root];
93 let nodes = 0;
94 const parser = new SaxesParser();
95 if (extension === ".epub") Object.assign(parser.ENTITIES, characterEntities);
96 parser.on("opentag", (tag) => {
97 if (++nodes > 200_000 || stack.length > 128) throw new Truncation("XML structure limit");
98 const node: XmlNode = {
99 name: tag.name.split(":").at(-1)!,
100 attrs: Object.fromEntries(
101 Object.entries(tag.attributes).flatMap(([key, value]) => [
102 [key, String(value)],
103 [key.split(":").at(-1)!, String(value)],
104 ]),
105 ),
106 children: [],
107 };
108 if (odf && node.name === "s") node.spaceCount = repeatCount(node.attrs.c);
109 stack.at(-1)!.children.push(node);
110 stack.push(node);
111 });
112 parser.on("closetag", () => {
113 const node = stack.pop()!;
114 const parent = stack.at(-1)!;
115 if (odf && (node.name === "p" || node.name === "h")) collapseOdfWhitespace(node);
116 if (
117 (extension === ".docx" && node.name === "del") ||
118 (odf && node.name === "annotation" && parent.name !== "semantics")
119 ) {
120 parent.children.pop();
121 return;
122 }
123 if (node.name === "Fallback" && !retainCompatibilityFallback(parent, node)) return;
124 if (HIDDEN.has(node.name) || (!node.hasText && node.name !== "noBreakHyphen")) return;
125 parent.hasText = true;
126 if (node.name === "Choice") parent.hasTextChoice = true;
127 });
128 const text = (value: string) => {
129 const node = stack.at(-1)!;
130 node.children.push(value);
131 if (value.trim() !== "") node.hasText = true;
132 };
133 parser.on("text", text);
134 parser.on("cdata", text);
135 parser.write(source).close();
136 return root;
137}
138
139const children = (node: XmlNode | undefined) =>
140 node?.children.filter((child): child is XmlNode => typeof child !== "string") ?? [];
141
142function retainCompatibilityFallback(parent: XmlNode, fallback: XmlNode): boolean {
143 // Markup-compatibility fallbacks repeat their mc:Choice content, e.g. Word text boxes.
144 // Keep one when no Choice carries text, such as a chart with a VML caption.
145 if (parent.hasTextChoice) {
146 parent.children.pop();
147 return false;
148 }
149 if (fallback.hasText || hasInlineTab(fallback, ["tab", "ptab"])) {
150 parent.children = parent.children.filter(
151 (child) =>
152 typeof child === "string" || child.name !== "Choice" || !hasInlineTab(child, ["ptab"]),
153 );
154 }
155 return true;
156}
157
158function hasInlineTab(node: XmlNode, names: readonly string[]): boolean {
159 return (
160 !HIDDEN.has(node.name) &&
161 (names.includes(node.name) || children(node).some((child) => hasInlineTab(child, names)))
162 );
163}
164function* all(node: XmlNode, name: string | readonly string[]): Generator<XmlNode, void> {
165 for (const child of children(node)) {
166 if (typeof name === "string" ? child.name === name : name.includes(child.name)) yield child;
167 else yield* all(child, name);
168 }
169}
170function* text(node: XmlNode): Generator<string, void> {
171 if (HIDDEN.has(node.name)) return;
172 if (["tab", "ptab", "cell"].includes(node.name)) yield "\t";
173 else if (["br", "line-break", "cr"].includes(node.name)) yield "\n";
174 else if (node.name === "noBreakHyphen") yield "\u2011";
175 else if (node.spaceCount !== undefined) {
176 yield " ".repeat(Math.min(MAX_OUTPUT, node.spaceCount));
177 if (node.spaceCount > MAX_OUTPUT) throw new Truncation("Space repeat limit");
178 } else
179 for (const child of node.children) {
180 if (typeof child === "string") yield child;
181 else yield* text(child);
182 }
183}
184// SpreadsheetML `t` and `v` values are ST_Xstring: `_xHHHH_` is one UTF-16 code unit, and an
185// escaped lead underscore (`_x005F_xHHHH_`) keeps the literal `_xHHHH_`. Decoded in one pass.
186function* xstringText(node: XmlNode): Generator<string, void> {
187 if (HIDDEN.has(node.name)) return;
188 if (node.name !== "t" && node.name !== "v") {
189 for (const child of children(node)) yield* xstringText(child);
190 return;
191 }
192 yield node.children
193 .filter((child) => typeof child === "string")
194 .join("")
195 .replaceAll(
196 /_x005[Ff]_(x[\dA-Fa-f]{4}_)|_x([\dA-Fa-f]{4})_/g,
197 (_, literal?: string, hex?: string) =>
198 literal ? `_${literal}` : String.fromCharCode(Number.parseInt(hex!, 16)),
199 );
200}
201function* paragraphs(node: XmlNode): Generator<TextPart, void> {
202 if (HIDDEN.has(node.name)) return;
203 for (const child of node.children) {
204 if (typeof child === "string") yield child;
205 else if (["br", "line-break", "cr"].includes(child.name)) yield "\n";
206 else if (["tbl", "table"].includes(child.name)) yield* table(child);
207 else if (["p", "h"].includes(child.name) || /^h[1-6]$/.test(child.name)) {
208 const style = all(child, "pStyle").next().value?.attrs.val ?? "";
209 const level =
210 child.name === "h"
211 ? Number(child.attrs["outline-level"]) || 1
212 : /^h[1-6]$/.test(child.name)
213 ? Number(child.name[1])
214 : Number(style.match(/^Heading([1-6])$/i)?.[1]) || 0;
215 if (level) yield `${"#".repeat(Math.min(6, level))} `;
216 yield* text(child);
217 yield "\n";
218 } else {
219 yield* paragraphs(child);
220 if (["li", "div", "section"].includes(child.name)) yield "\n";
221 }
222 }
223}
224// A notes page also holds the slide image, slide number, date, header and footer placeholders.
225const NOTES_PAGE_PLACEHOLDERS = new Set(["sldImg", "sldNum", "dt", "hdr", "ftr"]);
226const isNotesPagePlaceholder = (node: XmlNode) =>
227 node.name === "sp" && NOTES_PAGE_PLACEHOLDERS.has(all(node, "ph").next().value?.attrs.type ?? "");
228function withoutNotesPagePlaceholders(node: XmlNode): XmlNode {
229 return {
230 ...node,
231 children: node.children
232 .filter((child) => typeof child === "string" || !isNotesPagePlaceholder(child))
233 .map((child) => (typeof child === "string" ? child : withoutNotesPagePlaceholders(child))),
234 };
235}
236function* inCell(parts: Iterable<TextPart>): Generator<TextPart, void> {
237 yield CELL_START;
238 yield* parts;
239 yield CELL_END;
240}
241function repeatCount(value: string | undefined): number {
242 if (value === undefined) return 1;
243 if (!/^[0-9]+$/.test(value) || Number(value) < 1) throw new Error("Invalid repeat count");
244 return Number(value);
245}
246function odfValue(cell: XmlNode): string {
247 const type = cell.attrs["office:value-type"] ?? cell.attrs["value-type"];
248 const attr = (name: string) => cell.attrs[`office:${name}`] ?? cell.attrs[name] ?? "";
249 switch (type) {
250 case "void":
251 return "";
252 case "string":
253 return attr("string-value");
254 case "boolean":
255 return attr("boolean-value");
256 case "date":
257 return attr("date-value");
258 case "time":
259 return attr("time-value");
260 case "currency":
261 return attr("value").trim() ? `${attr("value")} ${attr("currency")}`.trim() : "";
262 case "percentage":
263 return attr("value").trim() ? `${attr("value")} [ODF value-type=percentage]` : "";
264 default:
265 return attr("value");
266 }
267}
268function hasCellText(cell: XmlNode): boolean {
269 if (odfValue(cell).trim() || cell.name === "noBreakHyphen") return true;
270 // Space markers can have enormous repeat counts; emptiness never requires expanding them.
271 if (HIDDEN.has(cell.name) || cell.spaceCount !== undefined) return false;
272 return cell.children.some((child) =>
273 typeof child === "string" ? !!child.trim() : hasCellText(child),
274 );
275}
276function* table(node: XmlNode): Generator<TextPart, void> {
277 let rowCount = 0;
278 for (const row of all(node, ["tr", "table-row"])) {
279 // Word nests a cell inside w:sdt when a content control wraps the whole cell.
280 const cells = [...all(row, ["tc", "table-cell", "covered-table-cell", "td", "th"])];
281 // ODS writers pad sheets with repeated empty rows and trailing cells.
282 while (cells.length && !hasCellText(cells.at(-1)!)) cells.pop();
283 if (!cells.length) continue;
284 const repeat = repeatCount(row.attrs["number-rows-repeated"]);
285 for (let index = 0; index < repeat; index++) {
286 if (++rowCount > 10_000) throw new Truncation("Row limit");
287 let column = 0;
288 for (const cell of cells) {
289 const count = repeatCount(cell.attrs["number-columns-repeated"]);
290 for (let i = 0; i < count; i++) {
291 if (column >= 512) throw new Truncation("Column limit");
292 if (column++) yield "\t";
293 yield CELL_START;
294 yield* paragraphs(cell);
295 yield { fallback: odfValue(cell) };
296 yield CELL_END;
297 }
298 }
299 yield "\n";
300 }
301 }
302}
303
304async function archive(path: string): Promise<Map<string, string>> {
305 const zip = await new Promise<Yauzl.ZipFile>((resolve, reject) =>
306 Yauzl.open(
307 path,
308 { lazyEntries: true, validateEntrySizes: true, strictFileNames: true },
309 (error, result) => (error || !result ? reject(error) : resolve(result)),
310 ),
311 );
312 const files = new Map<string, string>();
313 let expanded = 0;
314 let count = 0;
315 try {
316 await new Promise<void>((resolve, reject) => {
317 zip.on("error", reject);
318 zip.on("end", resolve);
319 zip.on("entry", (entry: Yauzl.Entry) => {
320 if (++count > 2048 || zip.entryCount > 2048) {
321 reject(new Truncation("Archive limit"));
322 return;
323 }
324 if (entry.generalPurposeBitFlag & 1) {
325 reject(new Error("Encrypted archive"));
326 return;
327 }
328 if (!/\.(xml|rels|xhtml|html|htm|opf|svg)$/i.test(entry.fileName)) {
329 zip.readEntry();
330 return;
331 }
332 if (
333 entry.uncompressedSize > MAX_EXPANDED ||
334 entry.uncompressedSize > Math.max(1024, entry.compressedSize * 200)
335 ) {
336 reject(new Truncation("Archive limit"));
337 return;
338 }
339 expanded += entry.uncompressedSize;
340 if (expanded > MAX_EXPANDED) {
341 reject(new Truncation("Expanded byte limit"));
342 return;
343 }
344 zip.openReadStream(entry, (error, stream) => {
345 if (error || !stream) {
346 reject(error);
347 return;
348 }
349 const buffers: Buffer[] = [];
350 let size = 0;
351 stream.on("error", reject);
352 stream.on("data", (chunk: Buffer) => {
353 size += chunk.length;
354 if (size > entry.uncompressedSize || size > MAX_EXPANDED) {
355 stream.destroy(new Truncation("Entry byte limit"));
356 return;
357 }
358 buffers.push(chunk);
359 });
360 stream.on("end", () => {
361 const data = Buffer.concat(buffers);
362 // XML's BOM and initial '<' bytes distinguish both UTF-16 byte orders.
363 const encoding =
364 (data[0] === 0xff && data[1] === 0xfe) || (data[0] === 0x3c && data[1] === 0)
365 ? "utf-16le"
366 : (data[0] === 0xfe && data[1] === 0xff) || (data[0] === 0 && data[1] === 0x3c)
367 ? "utf-16be"
368 : "utf-8";
369 files.set(entry.fileName, new TextDecoder(encoding).decode(data));
370 zip.readEntry();
371 });
372 });
373 });
374 zip.readEntry();
375 });
376 } finally {
377 zip.close();
378 }
379 return files;
380}
381
382const NOTEBOOK_CELL_TYPES = ["code", "markdown", "raw"];
383
384function* notebook(source: string): Generator<string, void> {
385 const book: unknown = JSON.parse(source);
386 if (!book || typeof book !== "object" || !("cells" in book) || !Array.isArray(book.cells))
387 throw new Error("Invalid notebook");
388 function* lines(value: unknown): Generator<string, void> {
389 if (typeof value === "string") yield value;
390 else if (Array.isArray(value))
391 for (const line of value) {
392 if (typeof line === "string") yield line;
393 }
394 }
395 function outputText(value: unknown): string {
396 // Notebook fragments can split a terminal escape sequence.
397 return NodeUtil.stripVTControlCharacters([...lines(value)].join(""));
398 }
399 for (const [index, cell] of book.cells.entries()) {
400 if (index >= 10_000) throw new Truncation("Notebook cell limit");
401 if (!cell || typeof cell !== "object") continue;
402 const cellType = "cell_type" in cell ? cell.cell_type : undefined;
403 const kind = NOTEBOOK_CELL_TYPES.find((type) => type === cellType) ?? "markdown";
404 yield `## Cell ${index + 1} (${kind})\n`;
405 if ("source" in cell) yield* lines(cell.source);
406 if ("outputs" in cell && Array.isArray(cell.outputs)) {
407 yield "\nOutput:\n";
408 for (const output of cell.outputs) {
409 if (!output || typeof output !== "object") continue;
410 if ("text" in output) yield outputText(output.text);
411 else if (
412 "data" in output &&
413 output.data &&
414 typeof output.data === "object" &&
415 "text/plain" in output.data
416 )
417 yield outputText(output.data["text/plain"]);
418 else if ("output_type" in output && output.output_type === "error") {
419 if ("ename" in output) yield* lines(output.ename);
420 if ("evalue" in output) {
421 yield ": ";
422 yield* lines(output.evalue);
423 }
424 yield "\n";
425 if ("traceback" in output)
426 for (const line of lines(output.traceback)) {
427 yield NodeUtil.stripVTControlCharacters(line);
428 yield "\n";
429 }
430 }
431 yield "\n";
432 }
433 }
434 yield "\n\n";
435 }
436}
437
438// Per-byte decoding only supports the single-byte \fcharset values.
439const FONT_CODE_PAGES = new Map([
440 [77, "macintosh"],
441 [161, "windows-1253"],
442 [162, "windows-1254"],
443 [163, "windows-1258"],
444 [177, "windows-1255"],
445 [178, "windows-1256"],
446 [186, "windows-1257"],
447 [204, "windows-1251"],
448 [222, "windows-874"],
449 [238, "windows-1250"],
450]);
451
452function* rtf(source: string): Generator<string, void> {
453 if (!source.startsWith("{\\rtf")) throw new Error("Invalid RTF document");
454 let state = {
455 skip: false,
456 deleted: false,
457 uc: 1,
458 font: 0,
459 fontTable: false,
460 decoder: new TextDecoder("windows-1252"),
461 };
462 const stack: Array<typeof state> = [];
463 // A font's \fcharset, not the document code page, encodes the bytes written in that font.
464 const fonts = new Map<number, typeof state.decoder>();
465 let defaultFont = 0;
466 const decoder = () => fonts.get(state.font) ?? state.decoder;
467 const hidden = () => state.skip || state.deleted;
468 const symbols = new Map([
469 ["endash", "–"],
470 ["emdash", characterEntities.mdash],
471 ["enspace", "\u2002"],
472 ["emspace", "\u2003"],
473 ["qmspace", "\u2005"],
474 ["lquote", "‘"],
475 ["rquote", "’"],
476 ["ldblquote", "“"],
477 ["rdblquote", "”"],
478 ["bullet", "•"],
479 ["zwj", "\u200d"],
480 ["zwnj", "\u200c"],
481 ["ltrmark", "\u200e"],
482 ["rtlmark", "\u200f"],
483 ["~", "\u00a0"],
484 ["_", "\u2011"],
485 ["-", ""],
486 ]);
487 let fallback = 0;
488 for (let i = 0; i < source.length; i++) {
489 const char = source[i]!;
490 if (char === "{" || char === "}") fallback = 0;
491 if (char === "{") {
492 stack.push({ ...state });
493 if (stack.length > 128) throw new Truncation("RTF depth limit");
494 } else if (char === "}") state = stack.pop() ?? state;
495 else if (char === "\\") {
496 const rest = source.slice(i + 1, i + 80);
497 const hex = /^'([0-9a-f]{2})/i.exec(rest);
498 const word = /^([a-z]+)(-?\d+)? ?/i.exec(rest);
499 if (hex) {
500 if (fallback) fallback--;
501 else if (!hidden()) yield decoder().decode(Uint8Array.of(Number.parseInt(hex[1]!, 16)));
502 i += 3;
503 } else if (word) {
504 i += word[0].length;
505 const control = word[1]!;
506 const value = Number(word[2]);
507 if (control === "bin") {
508 if (!Number.isSafeInteger(value) || value < 0)
509 throw new Error("Invalid RTF binary length");
510 i += value;
511 }
512 if (fallback) {
513 fallback--;
514 continue;
515 }
516 if (
517 [
518 "fonttbl",
519 "colortbl",
520 "stylesheet",
521 "info",
522 "pict",
523 "object",
524 "fldinst",
525 "header",
526 "headerf",
527 "headerl",
528 "headerr",
529 "footer",
530 "footerf",
531 "footerl",
532 "footerr",
533 ].includes(control)
534 )
535 state.skip = true;
536 if (control === "fonttbl") state.fontTable = true;
537 else if (control === "deff") state.font = defaultFont = value;
538 else if (control === "f") {
539 state.font = value;
540 if (state.fontTable) fonts.delete(value);
541 } else if (control === "fcharset" && state.fontTable) {
542 const codePage = FONT_CODE_PAGES.get(value);
543 if (codePage) fonts.set(state.font, new TextDecoder(codePage));
544 }
545 if (control === "deleted") state.deleted = value !== 0;
546 else if (control === "plain") {
547 state.deleted = false;
548 state.font = defaultFont;
549 }
550 if (control === "mac" || (control === "ansicpg" && value === 10000))
551 state.decoder = new TextDecoder("macintosh");
552 else if (control === "ansicpg") {
553 // Per-byte decoding only supports single-byte Windows code pages.
554 if (value !== 874 && (value < 1250 || value > 1258))
555 throw new Error("Unsupported RTF code page");
556 state.decoder = new TextDecoder(`windows-${value}`, { fatal: true });
557 } else if (control === "uc") {
558 if (!Number.isSafeInteger(value) || value < 0)
559 throw new Error("Invalid RTF fallback count");
560 state.uc = value;
561 } else if (control === "u") {
562 if (!hidden()) yield String.fromCharCode(value < 0 ? value + 65536 : value);
563 fallback = state.uc;
564 } else if (!hidden() && ["par", "line", "sect", "page", "column"].includes(control))
565 yield "\n";
566 else if (!hidden() && control === "tab") yield "\t";
567 // Table structure survives tracked deletions; only the deleted cell text is dropped.
568 else if (!state.skip && control === "row") yield "\n";
569 else if (!state.skip && control === "cell") yield "\t";
570 else if (!hidden() && symbols.has(control)) yield symbols.get(control)!;
571 } else {
572 i++;
573 if (fallback) fallback--;
574 else if (rest[0] === "*") state.skip = true;
575 // A backslash before a line break is \par; TextEdit ends paragraphs this way.
576 else if (!hidden() && (rest[0] === "\n" || rest[0] === "\r")) yield "\n";
577 else if (!hidden() && ["\\", "{", "}"].includes(rest[0]!)) yield rest[0]!;
578 else if (!hidden() && symbols.has(rest[0]!)) yield symbols.get(rest[0]!)!;
579 }
580 } else if (char !== "\n" && char !== "\r") {
581 if (fallback) fallback--;
582 else if (!hidden())
583 yield char.charCodeAt(0) < 128 ? char : decoder().decode(Uint8Array.of(char.charCodeAt(0)));
584 }
585 }
586}
587
588async function* document(path: string, extension: string): AsyncGenerator<TextPart, void> {
589 if ((await NodeFSP.stat(path)).size > MAX_INPUT) throw new Truncation("Input byte limit");
590 if (extension === ".ipynb") yield* notebook(await NodeFSP.readFile(path, "utf8"));
591 else if (extension === ".rtf") yield* rtf((await NodeFSP.readFile(path)).toString("latin1"));
592 else {
593 const files = await archive(path);
594 const notes: string[] = [];
595 const skip = (name: string) =>
596 notes.push(`\n[Skipped document part: ${name} (missing or invalid XML).]\n`);
597 const read = (name: string): XmlNode => {
598 try {
599 const data = files.get(name);
600 if (!data) throw new Error("Missing document part");
601 return xml(data, extension);
602 } catch (error) {
603 if (error instanceof Truncation) throw error;
604 skip(name);
605 return { name: "root", attrs: {}, children: [] };
606 }
607 };
608 const relations = (name: string) =>
609 new Map(
610 [...all(read(name), "Relationship")]
611 .filter((rel) => rel.attrs.TargetMode !== "External")
612 .map((rel) => [rel.attrs.Id, rel.attrs.Target]),
613 );
614 if (extension === ".docx") yield* paragraphs(read("word/document.xml"));
615 else if ([".odt", ".ods", ".odp"].includes(extension)) {
616 const content = read("content.xml");
617 if (extension === ".odt") yield* paragraphs(content);
618 else {
619 let index = 0;
620 for (const part of all(content, extension === ".ods" ? "table" : "page")) {
621 yield extension === ".ods"
622 ? `\n\n## Sheet: ${part.attrs.name ?? "Untitled"}\n`
623 : `\n\n## Slide ${++index}\n`;
624 if (extension === ".ods") yield* table(part);
625 else yield* paragraphs(part);
626 }
627 }
628 } else if (extension === ".xlsx") {
629 const workbook = read("xl/workbook.xml");
630 const dateSystem = ["1", "true"].includes(
631 all(workbook, "workbookPr").next().value?.attrs.date1904 ?? "",
632 )
633 ? "1904"
634 : "1900";
635 const styles = files.has("xl/styles.xml") ? read("xl/styles.xml") : undefined;
636 const customFormats = new Map(
637 styles
638 ? [...all(styles, "numFmt")].map((node) => [node.attrs.numFmtId, node.attrs.formatCode])
639 : [],
640 );
641 const cellFormats = styles ? all(styles, "cellXfs").next().value : undefined;
642 const formats = cellFormats ? children(cellFormats) : [];
643 const strings = files.has("xl/sharedStrings.xml")
644 ? [...all(read("xl/sharedStrings.xml"), "si")]
645 : [];
646 const populatedStrings = strings.map(hasCellText);
647 const rels = relations("xl/_rels/workbook.xml.rels");
648 for (const sheet of all(workbook, "sheet")) {
649 yield `\n## Sheet: ${sheet.attrs.name}\n`;
650 const target = rels.get(sheet.attrs["r:id"] ?? sheet.attrs.id);
651 if (!target) {
652 skip(`sheet relationship ${sheet.attrs.name}`);
653 continue;
654 }
655 const name = target.startsWith("/")
656 ? target.slice(1)
657 : NodePath.posix.normalize(`xl/${target}`);
658 const populated = (cell: XmlNode) => {
659 const value = all(cell, "v").next().value;
660 if (cell.attrs.t === "s") {
661 const raw = value?.children.find((child) => typeof child === "string")?.trim();
662 return !!raw && !!populatedStrings[Number(raw)];
663 }
664 if (cell.attrs.t === "inlineStr") return hasCellText(cell);
665 if (value && hasCellText(value)) return true;
666 for (const formula of all(cell, "f")) if (hasCellText(formula)) return true;
667 return false;
668 };
669 let rowCount = 0;
670 for (const row of all(read(name), "row")) {
671 const cells: Array<XmlNode | undefined> = [];
672 let nextColumn = 0;
673 let columnsTruncated = false;
674 for (const cell of children(row).filter((node) => node.name === "c")) {
675 const letters = cell.attrs.r?.match(/^[A-Z]+/)?.[0];
676 const column = letters
677 ? [...letters].reduce((n, char) => n * 26 + char.charCodeAt(0) - 64, 0) - 1
678 : nextColumn;
679 nextColumn = column + 1;
680 if (!populated(cell)) continue;
681 if (column >= 512) {
682 columnsTruncated = true;
683 continue;
684 }
685 cells[column] = cell;
686 }
687 if (!cells.length && !columnsTruncated) continue;
688 if (++rowCount > 10_000) throw new Truncation("Row limit");
689 for (const [column, cell] of cells.entries()) {
690 if (column) yield "\t";
691 if (!cell) continue;
692 const value = all(cell, "v").next().value;
693 const raw = value?.children.find((child) => typeof child === "string") ?? "";
694 if (cell.attrs.t === "s") {
695 const shared = strings[Number(raw)];
696 if (shared) yield* inCell(xstringText(shared));
697 } else if (cell.attrs.t === "inlineStr") yield* inCell(xstringText(cell));
698 else if (cell.attrs.t === "b" && (raw.trim() === "0" || raw.trim() === "1"))
699 yield* inCell([raw.trim() === "1" ? "true" : "false"]);
700 else {
701 if (value && hasCellText(value)) yield* inCell(xstringText(value));
702 else for (const formula of all(cell, "f")) yield* inCell(text(formula));
703 const formatId = formats[Number(cell.attrs.s ?? 0)]?.attrs.numFmtId;
704 const format = formatId ? customFormats.get(formatId) : undefined;
705 if (
706 (cell.attrs.t === undefined || cell.attrs.t === "n") &&
707 raw.trim() &&
708 formatId &&
709 formatId !== "0"
710 )
711 yield ` [Excel numFmtId=${formatId}${format ? `; format=${format}` : ""}; date system ${dateSystem}]`;
712 }
713 }
714 yield "\n";
715 if (columnsTruncated) throw new Truncation("Column limit");
716 }
717 }
718 } else if (extension === ".pptx") {
719 const rels = relations("ppt/_rels/presentation.xml.rels");
720 const [presentation] = children(read("ppt/presentation.xml"));
721 const slideList = children(presentation).find((node) => node.name === "sldIdLst");
722 let index = 0;
723 for (const slide of children(slideList).filter((node) => node.name === "sldId")) {
724 yield `\n\n## Slide ${++index}\n`;
725 const target = rels.get(slide.attrs["r:id"] ?? slide.attrs.id);
726 if (!target) {
727 skip(`slide relationship ${index}`);
728 continue;
729 }
730 const name = target.startsWith("/")
731 ? target.slice(1)
732 : NodePath.posix.normalize(`ppt/${target}`);
733 yield* paragraphs(read(name));
734 const slideRels = NodePath.posix.join(
735 NodePath.posix.dirname(name),
736 "_rels",
737 `${NodePath.posix.basename(name)}.rels`,
738 );
739 if (!files.has(slideRels)) continue;
740 for (const rel of all(read(slideRels), "Relationship")) {
741 const target = rel.attrs.Target;
742 if (
743 !rel.attrs.Type?.endsWith("/notesSlide") ||
744 rel.attrs.TargetMode === "External" ||
745 !target
746 )
747 continue;
748 const notesPage = withoutNotesPagePlaceholders(
749 read(
750 target.startsWith("/")
751 ? target.slice(1)
752 : NodePath.posix.join(NodePath.posix.dirname(name), target),
753 ),
754 );
755 if (!hasCellText(notesPage)) continue;
756 yield "Notes:\n";
757 yield* paragraphs(notesPage);
758 }
759 }
760 } else if (extension === ".epub") {
761 const rootfile = all(read("META-INF/container.xml"), "rootfile").next().value?.attrs[
762 "full-path"
763 ];
764 if (!rootfile) {
765 if (!notes.length) skip("EPUB package");
766 yield* notes;
767 return;
768 }
769 const packageXml = read(rootfile);
770 const items = new Map(
771 [...all(packageXml, "item")].map((item) => [item.attrs.id, item.attrs.href]),
772 );
773 let index = 0;
774 for (const item of all(packageXml, "itemref")) {
775 yield `\n\n## Chapter ${++index}\n`;
776 const href = items.get(item.attrs.idref);
777 if (!href) {
778 skip(`chapter ${index}`);
779 continue;
780 }
781 let decoded: string;
782 try {
783 decoded = decodeURIComponent(href.split("#")[0]!);
784 } catch {
785 skip(`chapter ${index}`);
786 continue;
787 }
788 const name = NodePath.posix.normalize(
789 NodePath.posix.join(NodePath.posix.dirname(rootfile), decoded),
790 );
791 yield* paragraphs(read(name));
792 }
793 } else throw new Error("Unsupported document");
794 yield* notes;
795 }
796}
797
798export async function extractDocumentText(path: string, extension: string): Promise<string> {
799 let result = "";
800 let remaining = MAX_OUTPUT;
801 let cellDepth = 0;
802 let started = false;
803 let space = false;
804 let truncated = false;
805 try {
806 // Charge raw text before normalization so repeated whitespace also exhausts the budget.
807 for await (const part of document(path, extension)) {
808 if (part === CELL_START) {
809 if (cellDepth++ === 0) {
810 started = false;
811 space = false;
812 } else if (started) space = true;
813 continue;
814 }
815 if (part === CELL_END) {
816 cellDepth--;
817 if (cellDepth > 0 && started) space = true;
818 continue;
819 }
820 if (typeof part !== "string" && started) continue;
821 const raw = typeof part === "string" ? part : part.fallback;
822 let value = raw.slice(0, remaining).replaceAll("\0", "");
823 remaining -= Math.min(raw.length, remaining);
824 if (cellDepth) {
825 value = value.replaceAll(/\s+/g, " ");
826 const trimmed = value.trim();
827 if (trimmed) {
828 result += (started && (space || value.startsWith(" ")) ? " " : "") + trimmed;
829 started = true;
830 }
831 space = value.endsWith(" ") || (!value && space);
832 } else result += value;
833 if (remaining === 0) throw new Truncation("Output budget");
834 }
835 } catch (error) {
836 if (!(error instanceof Truncation)) throw error;
837 truncated = true;
838 }
839 result = result.replaceAll(/\n(?:[ \t]*\n){2,}/g, "\n\n").trim();
840 if (!result && !truncated) throw new Error("No text extracted");
841 return truncated ? result.replace(/[\uD800-\uDBFF]$/, "").trimEnd() + TRUNCATED : result;
842}