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

documentTextWorker.ts

780 lines29.1 KB

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