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