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

documentTextWorker.ts

933 lines35.7 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 // 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;
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);
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 (extension === ".docx" &&
119 node.name === "r" &&
120 children(node)
121 .flatMap((child) => (child.name === "rPr" ? children(child) : []))
122 .some(
123 (prop) => prop.name === "vanish" && ["true", "1", "on"].includes(prop.attrs.val ?? "1"),
124 )) ||
125 (odf && node.name === "annotation" && parent.name !== "semantics") ||
126 (extension === ".odp" &&
127 node.name === "page-thumbnail" &&
128 stack.some((ancestor) => ancestor.name === "notes"))
129 ) {
130 parent.children.pop();
131 return;
132 }
133 if (node.name === "Fallback" && !retainCompatibilityFallback(parent, node)) return;
134 if (HIDDEN.has(node.name) || (!node.hasText && node.name !== "noBreakHyphen")) return;
135 parent.hasText = true;
136 if (node.name === "Choice") parent.hasTextChoice = true;
137 });
138 const text = (value: string) => {
139 const node = stack.at(-1)!;
140 node.children.push(value);
141 if (value.trim() !== "") node.hasText = true;
142 };
143 parser.on("text", text);
144 parser.on("cdata", text);
145 parser.write(source).close();
146 return root;
148​
149const children = (node: XmlNode | undefined) =>
150 node?.children.filter((child): child is XmlNode => typeof child !== "string") ?? [];
151​
152function slideRelationshipId(slide: XmlNode, inheritedAttributes: XmlNode["attrs"]) {
153 for (const [name, value] of Object.entries(slide.attrs)) {
154 if (!name.endsWith(":id")) continue;
155 const binding = `xmlns:${name.slice(0, -3)}`;
156 const namespace = slide.attrs[binding] ?? inheritedAttributes[binding];
157 if (
158 namespace === "http://schemas.openxmlformats.org/officeDocument/2006/relationships" ||
159 namespace === "http://purl.oclc.org/ooxml/officeDocument/relationships"
160 )
161 return value;
162 }
163 return slide.attrs["r:id"] ?? slide.attrs.id;
165​
166function retainCompatibilityFallback(parent: XmlNode, fallback: XmlNode): boolean {
167 // Markup-compatibility fallbacks repeat their mc:Choice content, e.g. Word text boxes.
168 // Keep one when no Choice carries text, such as a chart with a VML caption.
169 if (parent.hasTextChoice) {
170 parent.children.pop();
171 return false;
172 }
173 if (fallback.hasText || hasInlineTab(fallback, ["tab", "ptab"])) {
174 parent.children = parent.children.filter(
175 (child) =>
176 typeof child === "string" || child.name !== "Choice" || !hasInlineTab(child, ["ptab"]),
177 );
178 }
179 return true;
181​
182function hasInlineTab(node: XmlNode, names: readonly string[]): boolean {
183 return (
184 !HIDDEN.has(node.name) &&
185 (names.includes(node.name) || children(node).some((child) => hasInlineTab(child, names)))
186 );
188function* all(node: XmlNode, name: string | readonly string[]): Generator<XmlNode, void> {
189 for (const child of children(node)) {
190 if (typeof name === "string" ? child.name === name : name.includes(child.name)) yield child;
191 else yield* all(child, name);
192 }
194function* text(node: XmlNode): Generator<TextPart, void> {
195 if (HIDDEN.has(node.name)) return;
196 // Word text boxes hold their own paragraphs inside the anchoring paragraph.
197 if (node.name === "txbxContent") yield* paragraphs(node);
198 else if (["tab", "ptab", "cell"].includes(node.name)) yield "\t";
199 else if (["br", "line-break", "cr"].includes(node.name)) yield "\n";
200 else if (node.name === "noBreakHyphen") yield "\u2011";
201 else if (node.spaceCount !== undefined) {
202 yield " ".repeat(Math.min(MAX_OUTPUT, node.spaceCount));
203 if (node.spaceCount > MAX_OUTPUT) throw new Truncation("Space repeat limit");
204 } else
205 for (const child of node.children) {
206 if (typeof child === "string") yield child;
207 else yield* text(child);
208 }
210// SpreadsheetML `t` and `v` values are ST_Xstring: `_xHHHH_` is one UTF-16 code unit, and an
211// escaped lead underscore (`_x005F_xHHHH_`) keeps the literal `_xHHHH_`. Decoded in one pass.
212function* xstringText(node: XmlNode): Generator<string, void> {
213 if (HIDDEN.has(node.name)) return;
214 if (node.name !== "t" && node.name !== "v") {
215 for (const child of children(node)) yield* xstringText(child);
216 return;
217 }
218 yield node.children
219 .filter((child) => typeof child === "string")
220 .join("")
221 .replaceAll(
222 /_x005[Ff]_(x[\dA-Fa-f]{4}_)|_x([\dA-Fa-f]{4})_/g,
223 (_, literal?: string, hex?: string) =>
224 literal ? `_${literal}` : String.fromCharCode(Number.parseInt(hex!, 16)),
225 );
227function* paragraphs(node: XmlNode): Generator<TextPart, void> {
228 if (HIDDEN.has(node.name)) return;
229 for (const child of node.children) {
230 if (typeof child === "string") yield child;
231 else if (["br", "line-break", "cr"].includes(child.name)) yield "\n";
232 else if (["tbl", "table"].includes(child.name)) yield* table(child);
233 else if (["p", "h"].includes(child.name) || /^h[1-6]$/.test(child.name)) {
234 const style = all(child, "pStyle").next().value?.attrs.val ?? "";
235 const level =
236 child.name === "h"
237 ? Number(child.attrs["outline-level"]) || 1
238 : /^h[1-6]$/.test(child.name)
239 ? Number(child.name[1])
240 : Number(style.match(/^Heading([1-6])$/i)?.[1]) || 0;
241 if (level) yield `${"#".repeat(Math.min(6, level))} `;
242 yield* text(child);
243 yield "\n";
244 } else {
245 yield* paragraphs(child);
246 if (["li", "div", "section"].includes(child.name)) yield "\n";
247 }
248 }
250// A notes page also holds the slide image, slide number, date, header and footer placeholders.
251const NOTES_PAGE_PLACEHOLDERS = new Set(["sldImg", "sldNum", "dt", "hdr", "ftr"]);
252const isNotesPagePlaceholder = (node: XmlNode) =>
253 node.name === "sp" && NOTES_PAGE_PLACEHOLDERS.has(all(node, "ph").next().value?.attrs.type ?? "");
254function withoutNotesPagePlaceholders(node: XmlNode): XmlNode {
255 return {
256 ...node,
257 children: node.children
258 .filter((child) => typeof child === "string" || !isNotesPagePlaceholder(child))
259 .map((child) => (typeof child === "string" ? child : withoutNotesPagePlaceholders(child))),
260 };
262function* inCell(parts: Iterable<TextPart>): Generator<TextPart, void> {
263 yield CELL_START;
264 yield* parts;
265 yield CELL_END;
267function repeatCount(value: string | undefined): number {
268 if (value === undefined) return 1;
269 if (!/^[0-9]+$/.test(value) || Number(value) < 1) throw new Error("Invalid repeat count");
270 return Number(value);
272function odfValue(cell: XmlNode): string {
273 const type = cell.attrs["office:value-type"] ?? cell.attrs["value-type"];
274 const attr = (name: string) => cell.attrs[`office:${name}`] ?? cell.attrs[name] ?? "";
275 switch (type) {
276 case "void":
277 return "";
278 case "string":
279 return attr("string-value");
280 case "boolean":
281 return attr("boolean-value");
282 case "date":
283 return attr("date-value");
284 case "time":
285 return attr("time-value");
286 case "currency":
287 return attr("value").trim() ? `${attr("value")} ${attr("currency")}`.trim() : "";
288 case "percentage":
289 return attr("value").trim() ? `${attr("value")} [ODF value-type=percentage]` : "";
290 default:
291 return attr("value");
292 }
294function hasCellText(cell: XmlNode): boolean {
295 if (odfValue(cell).trim() || cell.name === "noBreakHyphen") return true;
296 // Space markers can have enormous repeat counts; emptiness never requires expanding them.
297 if (HIDDEN.has(cell.name) || cell.spaceCount !== undefined) return false;
298 return cell.children.some((child) =>
299 typeof child === "string" ? !!child.trim() : hasCellText(child),
300 );
302function* table(node: XmlNode): Generator<TextPart, void> {
303 let rowCount = 0;
304 for (const row of all(node, ["tr", "table-row"])) {
305 // Word nests a cell inside w:sdt when a content control wraps the whole cell.
306 const cells = [...all(row, ["tc", "table-cell", "covered-table-cell", "td", "th"])];
307 // ODS writers pad sheets with repeated empty rows and trailing cells.
308 while (cells.length && !hasCellText(cells.at(-1)!)) cells.pop();
309 if (!cells.length) continue;
310 const repeat = repeatCount(row.attrs["number-rows-repeated"]);
311 for (let index = 0; index < repeat; index++) {
312 if (++rowCount > 10_000) throw new Truncation("Row limit");
313 let column = 0;
314 for (const cell of cells) {
315 const count = repeatCount(cell.attrs["number-columns-repeated"]);
316 for (let i = 0; i < count; i++) {
317 if (column >= 512) throw new Truncation("Column limit");
318 if (column++) yield "\t";
319 yield CELL_START;
320 yield* paragraphs(cell);
321 yield { fallback: odfValue(cell) };
322 yield CELL_END;
323 }
324 }
325 yield "\n";
326 }
327 }
329​
330async function archive(path: string): Promise<Map<string, string>> {
331 const zip = await new Promise<Yauzl.ZipFile>((resolve, reject) =>
332 Yauzl.open(
333 path,
334 { lazyEntries: true, validateEntrySizes: true, strictFileNames: true },
335 (error, result) => (error || !result ? reject(error) : resolve(result)),
336 ),
337 );
338 const files = new Map<string, string>();
339 let expanded = 0;
340 let count = 0;
341 try {
342 await new Promise<void>((resolve, reject) => {
343 zip.on("error", reject);
344 zip.on("end", resolve);
345 zip.on("entry", (entry: Yauzl.Entry) => {
346 if (++count > 2048 || zip.entryCount > 2048) {
347 reject(new Truncation("Archive limit"));
348 return;
349 }
350 if (entry.generalPurposeBitFlag & 1) {
351 reject(new Error("Encrypted archive"));
352 return;
353 }
354 if (!/\.(xml|rels|xhtml|html|htm|opf|svg)$/i.test(entry.fileName)) {
355 zip.readEntry();
356 return;
357 }
358 if (
359 entry.uncompressedSize > MAX_EXPANDED ||
360 entry.uncompressedSize > Math.max(1024, entry.compressedSize * 200)
361 ) {
362 reject(new Truncation("Archive limit"));
363 return;
364 }
365 expanded += entry.uncompressedSize;
366 if (expanded > MAX_EXPANDED) {
367 reject(new Truncation("Expanded byte limit"));
368 return;
369 }
370 zip.openReadStream(entry, (error, stream) => {
371 if (error || !stream) {
372 reject(error);
373 return;
374 }
375 const buffers: Buffer[] = [];
376 let size = 0;
377 stream.on("error", reject);
378 stream.on("data", (chunk: Buffer) => {
379 size += chunk.length;
380 if (size > entry.uncompressedSize || size > MAX_EXPANDED) {
381 stream.destroy(new Truncation("Entry byte limit"));
382 return;
383 }
384 buffers.push(chunk);
385 });
386 stream.on("end", () => {
387 const data = Buffer.concat(buffers);
388 // XML's BOM and initial '<' bytes distinguish both UTF-16 byte orders.
389 const encoding =
390 (data[0] === 0xff && data[1] === 0xfe) || (data[0] === 0x3c && data[1] === 0)
391 ? "utf-16le"
392 : (data[0] === 0xfe && data[1] === 0xff) || (data[0] === 0 && data[1] === 0x3c)
393 ? "utf-16be"
394 : "utf-8";
395 files.set(entry.fileName, new TextDecoder(encoding).decode(data));
396 zip.readEntry();
397 });
398 });
399 });
400 zip.readEntry();
401 });
402 } finally {
403 zip.close();
404 }
405 return files;
407​
408const NOTEBOOK_CELL_TYPES = ["code", "markdown", "raw"];
409​
410function* notebook(source: string): Generator<string, void> {
411 const book: unknown = JSON.parse(source);
412 if (!book || typeof book !== "object" || !("cells" in book) || !Array.isArray(book.cells))
413 throw new Error("Invalid notebook");
414 function* lines(value: unknown): Generator<string, void> {
415 if (typeof value === "string") yield value;
416 else if (Array.isArray(value))
417 for (const line of value) {
418 if (typeof line === "string") yield line;
419 }
420 }
421 function outputText(value: unknown): string {
422 // Notebook fragments can split a terminal escape sequence.
423 return NodeUtil.stripVTControlCharacters([...lines(value)].join(""));
424 }
425 for (const [index, cell] of book.cells.entries()) {
426 if (index >= 10_000) throw new Truncation("Notebook cell limit");
427 if (!cell || typeof cell !== "object") continue;
428 const cellType = "cell_type" in cell ? cell.cell_type : undefined;
429 const kind = NOTEBOOK_CELL_TYPES.find((type) => type === cellType) ?? "markdown";
430 yield `## Cell ${index + 1} (${kind})\n`;
431 if ("source" in cell) yield* lines(cell.source);
432 if ("outputs" in cell && Array.isArray(cell.outputs)) {
433 yield "\nOutput:\n";
434 for (const output of cell.outputs) {
435 if (!output || typeof output !== "object") continue;
436 if ("text" in output) yield outputText(output.text);
437 else if (
438 "data" in output &&
439 output.data &&
440 typeof output.data === "object" &&
441 "text/plain" in output.data
442 )
443 yield outputText(output.data["text/plain"]);
444 else if ("output_type" in output && output.output_type === "error") {
445 if ("ename" in output) yield* lines(output.ename);
446 if ("evalue" in output) {
447 yield ": ";
448 yield* lines(output.evalue);
449 }
450 yield "\n";
451 if ("traceback" in output)
452 for (const line of lines(output.traceback)) {
453 yield NodeUtil.stripVTControlCharacters(line);
454 yield "\n";
455 }
456 }
457 yield "\n";
458 }
459 }
460 yield "\n\n";
461 }
463​
464// Per-byte decoding only supports the single-byte \fcharset values.
465const FONT_CODE_PAGES = new Map([
466 [0, "windows-1252"],
467 [77, "macintosh"],
468 [161, "windows-1253"],
469 [162, "windows-1254"],
470 [163, "windows-1258"],
471 [177, "windows-1255"],
472 [178, "windows-1256"],
473 [186, "windows-1257"],
474 [204, "windows-1251"],
475 [222, "windows-874"],
476 [238, "windows-1250"],
477]);
478​
479// Per-byte decoding only supports single-byte code pages.
480const singleByteCodePage = (value: number) =>
481 value === 0
482 ? "windows-1252"
483 : value === 866
484 ? "ibm866"
485 : value === 10000
486 ? "macintosh"
487 : value === 874 || (value >= 1250 && value <= 1258)
488 ? `windows-${value}`
489 : undefined;
490​
491function* rtf(source: string): Generator<string, void> {
492 if (!source.startsWith("{\\rtf")) throw new Error("Invalid RTF document");
493 let state = {
494 skip: false,
495 deleted: false,
496 hiddenText: false,
497 uc: 1,
498 font: 0,
499 fontTable: false,
500 fontFile: false,
501 decoder: new TextDecoder("windows-1252"),
502 };
503 const stack: Array<typeof state> = [];
504 // A font's \cpg, else its \fcharset, not the document code page, encodes the bytes written in
505 // that font. A \cpg inside \fontfile encodes the font's file name instead.
506 const fonts = new Map<number, typeof state.decoder>();
507 let defaultFont = 0;
508 const decoder = () => fonts.get(state.font) ?? state.decoder;
509 const hidden = () => state.skip || state.deleted || state.hiddenText;
510 const symbols = new Map([
511 ["endash", "–"],
512 ["emdash", characterEntities.mdash],
513 ["enspace", "\u2002"],
514 ["emspace", "\u2003"],
515 ["qmspace", "\u2005"],
516 ["lquote", "‘"],
517 ["rquote", "’"],
518 ["ldblquote", "“"],
519 ["rdblquote", "”"],
520 ["bullet", "•"],
521 ["zwj", "\u200d"],
522 ["zwnj", "\u200c"],
523 ["ltrmark", "\u200e"],
524 ["rtlmark", "\u200f"],
525 ["~", "\u00a0"],
526 ["_", "\u2011"],
527 ["-", ""],
528 ]);
529 let fallback = 0;
530 for (let i = 0; i < source.length; i++) {
531 const char = source[i]!;
532 if (char === "{" || char === "}") fallback = 0;
533 if (char === "{") {
534 stack.push({ ...state });
535 if (stack.length > 128) throw new Truncation("RTF depth limit");
536 } else if (char === "}") state = stack.pop() ?? state;
537 else if (char === "\\") {
538 const rest = source.slice(i + 1, i + 80);
539 const hex = /^'([0-9a-f]{2})/i.exec(rest);
540 const word = /^([a-z]+)(-?\d+)? ?/i.exec(rest);
541 if (hex) {
542 if (fallback) fallback--;
543 else if (!hidden()) yield decoder().decode(Uint8Array.of(Number.parseInt(hex[1]!, 16)));
544 i += 3;
545 } else if (word) {
546 i += word[0].length;
547 const control = word[1]!;
548 const value = Number(word[2]);
549 if (control === "bin") {
550 if (!Number.isSafeInteger(value) || value < 0)
551 throw new Error("Invalid RTF binary length");
552 i += value;
553 }
554 if (fallback) {
555 fallback--;
556 continue;
557 }
558 if (
559 [
560 "fonttbl",
561 "colortbl",
562 "stylesheet",
563 "info",
564 "pict",
565 "object",
566 "fldinst",
567 "header",
568 "headerf",
569 "headerl",
570 "headerr",
571 "footer",
572 "footerf",
573 "footerl",
574 "footerr",
575 ].includes(control)
576 )
577 state.skip = true;
578 if (control === "fonttbl") state.fontTable = true;
579 else if (control === "fontfile") state.fontFile = true;
580 else if (control === "deff") state.font = defaultFont = value;
581 else if (control === "f") {
582 state.font = value;
583 if (state.fontTable) fonts.delete(value);
584 } else if (control === "fcharset" && state.fontTable) {
585 const codePage = FONT_CODE_PAGES.get(value);
586 if (codePage) fonts.set(state.font, new TextDecoder(codePage));
587 } else if (control === "cpg" && state.fontTable && !state.fontFile) {
588 const codePage = singleByteCodePage(value);
589 if (codePage) fonts.set(state.font, new TextDecoder(codePage));
590 }
591 if (control === "deleted") state.deleted = value !== 0;
592 else if (control === "v") state.hiddenText = value !== 0;
593 else if (control === "plain") {
594 state.deleted = false;
595 state.hiddenText = false;
596 state.font = defaultFont;
597 }
598 if (control === "mac" || (control === "ansicpg" && value === 10000))
599 state.decoder = new TextDecoder("macintosh");
600 else if (control === "ansicpg") {
601 const label = singleByteCodePage(value);
602 if (!label) throw new Error("Unsupported RTF code page");
603 state.decoder = new TextDecoder(label, { fatal: true });
604 } else if (control === "uc") {
605 if (!Number.isSafeInteger(value) || value < 0)
606 throw new Error("Invalid RTF fallback count");
607 state.uc = value;
608 } else if (control === "u") {
609 if (!hidden()) yield String.fromCharCode(value < 0 ? value + 65536 : value);
610 fallback = state.uc;
611 } else if (!hidden() && ["par", "line", "sect", "page", "column"].includes(control))
612 yield "\n";
613 else if (!hidden() && control === "tab") yield "\t";
614 // Table structure survives tracked deletions; only the deleted cell text is dropped.
615 else if (!state.skip && control === "row") yield "\n";
616 else if (!state.skip && control === "cell") yield "\t";
617 else if (!hidden() && symbols.has(control)) yield symbols.get(control)!;
618 } else {
619 i++;
620 if (fallback) fallback--;
621 else if (rest[0] === "*") state.skip = true;
622 // A backslash before a line break is \par; TextEdit ends paragraphs this way.
623 else if (!hidden() && (rest[0] === "\n" || rest[0] === "\r")) yield "\n";
624 else if (!hidden() && ["\\", "{", "}"].includes(rest[0]!)) yield rest[0]!;
625 else if (!hidden() && symbols.has(rest[0]!)) yield symbols.get(rest[0]!)!;
626 }
627 } else if (char !== "\n" && char !== "\r") {
628 if (fallback) fallback--;
629 else if (!hidden())
630 yield char.charCodeAt(0) < 128 ? char : decoder().decode(Uint8Array.of(char.charCodeAt(0)));
631 }
632 }
634​
635async function* document(path: string, extension: string): AsyncGenerator<TextPart, void> {
636 if ((await NodeFSP.stat(path)).size > MAX_INPUT) throw new Truncation("Input byte limit");
637 if (extension === ".ipynb") yield* notebook(await NodeFSP.readFile(path, "utf8"));
638 else if (extension === ".rtf") yield* rtf((await NodeFSP.readFile(path)).toString("latin1"));
639 else {
640 const files = await archive(path);
641 // OPC part names compare case-insensitively for ASCII letters; exact names win.
642 const foldAscii = (name: string) => name.replaceAll(/[A-Z]/gu, (char) => char.toLowerCase());
643 const folded = new Map<string, string>();
644 for (const name of files.keys())
645 if (!folded.has(foldAscii(name))) folded.set(foldAscii(name), name);
646 const part = (name: string) => (files.has(name) ? name : (folded.get(foldAscii(name)) ?? name));
647 const has = (name: string) => files.has(part(name));
648 const notes: string[] = [];
649 const skip = (name: string) =>
650 notes.push(`\n[Skipped document part: ${name} (missing or invalid XML).]\n`);
651 const read = (name: string): XmlNode => {
652 try {
653 const data = files.get(part(name));
654 if (!data) throw new Error("Missing document part");
655 return xml(data, extension);
656 } catch (error) {
657 if (error instanceof Truncation) throw error;
658 skip(name);
659 return { name: "root", attrs: {}, children: [] };
660 }
661 };
662 const partRels = (name: string) =>
663 NodePath.posix.join(
664 NodePath.posix.dirname(name),
665 "_rels",
666 `${NodePath.posix.basename(name)}.rels`,
667 );
668 const relations = (name: string) =>
669 new Map(
670 [...all(read(name), "Relationship")]
671 .filter((rel) => rel.attrs.TargetMode !== "External")
672 .map((rel) => [rel.attrs.Id, rel.attrs]),
673 );
674 // The package relationship names the main part; Word for the web saves word/document2.xml.
675 const mainPart = (fallback: string) => {
676 const target = has("_rels/.rels")
677 ? [...all(read("_rels/.rels"), "Relationship")].find(
678 (rel) =>
679 rel.attrs.Type?.endsWith("/officeDocument") && rel.attrs.TargetMode !== "External",
680 )?.attrs.Target
681 : undefined;
682 const main = target && NodePath.posix.normalize(target).replace(/^\//, "");
683 return main && has(main) ? main : fallback;
684 };
685 if (extension === ".docx") {
686 yield* paragraphs(read(mainPart("word/document.xml")));
687 } else if ([".odt", ".ods", ".odp"].includes(extension)) {
688 const content = read("content.xml");
689 if (extension === ".odt") yield* paragraphs(content);
690 else {
691 let index = 0;
692 for (const part of all(content, extension === ".ods" ? "table" : "page")) {
693 yield extension === ".ods"
694 ? `\n\n## Sheet: ${part.attrs.name ?? "Untitled"}\n`
695 : `\n\n## Slide ${++index}\n`;
696 if (extension === ".ods") {
697 yield* table(part);
698 continue;
699 }
700 const notes = children(part).find((child) => child.name === "notes");
701 yield* paragraphs({
702 ...part,
703 children: part.children.filter((child) => child !== notes),
704 });
705 if (notes && hasCellText(notes)) {
706 yield "\nNotes:\n";
707 yield* paragraphs(notes);
708 }
709 }
710 }
711 } else if (extension === ".xlsx") {
712 const workbookPath = mainPart("xl/workbook.xml");
713 const workbookDir = NodePath.posix.dirname(workbookPath);
714 const resolveWorkbookPart = (target: string) =>
715 NodePath.posix.resolve(`/${workbookDir}`, target).slice(1);
716 const workbook = read(workbookPath);
717 const rels = relations(partRels(workbookPath));
718 const workbookRelations = [...rels.values()];
719 const workbookPartPath = (part: string) => {
720 const target = workbookRelations.find((rel) => rel.Type?.endsWith(`/${part}`))?.Target;
721 return resolveWorkbookPart(target || `${part}.xml`);
722 };
723 const dateSystem = ["1", "true"].includes(
724 all(workbook, "workbookPr").next().value?.attrs.date1904 ?? "",
725 )
726 ? "1904"
727 : "1900";
728 const stylesPath = workbookPartPath("styles");
729 const styles = has(stylesPath) ? read(stylesPath) : undefined;
730 const customFormats = new Map(
731 styles
732 ? [...all(styles, "numFmt")].map((node) => [node.attrs.numFmtId, node.attrs.formatCode])
733 : [],
734 );
735 const cellFormats = styles ? all(styles, "cellXfs").next().value : undefined;
736 const formats = cellFormats ? children(cellFormats) : [];
737 const sharedPath = workbookPartPath("sharedStrings");
738 const strings = has(sharedPath) ? [...all(read(sharedPath), "si")] : [];
739 const populatedStrings = strings.map(hasCellText);
740 for (const sheet of all(workbook, "sheet")) {
741 yield `\n## Sheet: ${sheet.attrs.name}\n`;
742 const target = rels.get(sheet.attrs["r:id"] ?? sheet.attrs.id)?.Target;
743 if (!target) {
744 skip(`sheet relationship ${sheet.attrs.name}`);
745 continue;
746 }
747 const name = resolveWorkbookPart(target);
748 const populated = (cell: XmlNode) => {
749 const value = all(cell, "v").next().value;
750 if (cell.attrs.t === "s") {
751 const raw = value?.children.find((child) => typeof child === "string")?.trim();
752 return !!raw && !!populatedStrings[Number(raw)];
753 }
754 if (cell.attrs.t === "inlineStr") return hasCellText(cell);
755 if (value && hasCellText(value)) return true;
756 for (const formula of all(cell, "f")) if (hasCellText(formula)) return true;
757 return false;
758 };
759 let rowCount = 0;
760 for (const row of all(read(name), "row")) {
761 const cells: Array<XmlNode | undefined> = [];
762 let nextColumn = 0;
763 let columnsTruncated = false;
764 for (const cell of children(row).filter((node) => node.name === "c")) {
765 const letters = cell.attrs.r?.match(/^[A-Z]+/)?.[0];
766 const column = letters
767 ? [...letters].reduce((n, char) => n * 26 + char.charCodeAt(0) - 64, 0) - 1
768 : nextColumn;
769 nextColumn = column + 1;
770 if (!populated(cell)) continue;
771 if (column >= 512) {
772 columnsTruncated = true;
773 continue;
774 }
775 cells[column] = cell;
776 }
777 if (!cells.length && !columnsTruncated) continue;
778 if (++rowCount > 10_000) throw new Truncation("Row limit");
779 for (const [column, cell] of cells.entries()) {
780 if (column) yield "\t";
781 if (!cell) continue;
782 const value = all(cell, "v").next().value;
783 const raw = value?.children.find((child) => typeof child === "string") ?? "";
784 if (cell.attrs.t === "s") {
785 const shared = strings[Number(raw)];
786 if (shared) yield* inCell(xstringText(shared));
787 } else if (cell.attrs.t === "inlineStr") yield* inCell(xstringText(cell));
788 else if (cell.attrs.t === "b" && (raw.trim() === "0" || raw.trim() === "1"))
789 yield* inCell([raw.trim() === "1" ? "true" : "false"]);
790 else {
791 if (value && hasCellText(value)) yield* inCell(xstringText(value));
792 else for (const formula of all(cell, "f")) yield* inCell(text(formula));
793 const formatId = formats[Number(cell.attrs.s ?? 0)]?.attrs.numFmtId;
794 const format = formatId ? customFormats.get(formatId) : undefined;
795 if (
796 (cell.attrs.t === undefined || cell.attrs.t === "n") &&
797 raw.trim() &&
798 formatId &&
799 formatId !== "0"
800 )
801 yield ` [Excel numFmtId=${formatId}${format ? `; format=${format}` : ""}; date system ${dateSystem}]`;
802 }
803 }
804 yield "\n";
805 if (columnsTruncated) throw new Truncation("Column limit");
806 }
807 }
808 } else if (extension === ".pptx") {
809 const presentationPath = mainPart("ppt/presentation.xml");
810 const presentationDir = NodePath.posix.dirname(presentationPath);
811 const rels = relations(partRels(presentationPath));
812 const [presentation] = children(read(presentationPath));
813 const slideList = children(presentation).find((node) => node.name === "sldIdLst");
814 const inheritedAttributes = { ...presentation?.attrs, ...slideList?.attrs };
815 let index = 0;
816 for (const slide of children(slideList).filter((node) => node.name === "sldId")) {
817 yield `\n\n## Slide ${++index}\n`;
818 const target = rels.get(slideRelationshipId(slide, inheritedAttributes))?.Target;
819 if (!target) {
820 skip(`slide relationship ${index}`);
821 continue;
822 }
823 const name = NodePath.posix.resolve(`/${presentationDir}`, target).slice(1);
824 yield* paragraphs(read(name));
825 const slideRels = partRels(name);
826 if (!has(slideRels)) continue;
827 for (const rel of all(read(slideRels), "Relationship")) {
828 const target = rel.attrs.Target;
829 if (
830 !rel.attrs.Type?.endsWith("/notesSlide") ||
831 rel.attrs.TargetMode === "External" ||
832 !target
833 )
834 continue;
835 const notesPage = withoutNotesPagePlaceholders(
836 read(
837 target.startsWith("/")
838 ? target.slice(1)
839 : NodePath.posix.join(NodePath.posix.dirname(name), target),
840 ),
841 );
842 if (!hasCellText(notesPage)) continue;
843 yield "Notes:\n";
844 yield* paragraphs(notesPage);
845 }
846 }
847 } else if (extension === ".epub") {
848 let rootfile = all(read("META-INF/container.xml"), "rootfile").next().value?.attrs[
849 "full-path"
850 ];
851 if (!rootfile) {
852 if (!notes.length) skip("EPUB package");
853 yield* notes;
854 return;
855 }
856 try {
857 const decoded = decodeURIComponent(rootfile);
858 if (files.has(decoded)) rootfile = decoded;
859 } catch {}
860 const packageXml = read(rootfile);
861 const items = new Map(
862 [...all(packageXml, "item")].map((item) => [item.attrs.id, item.attrs.href]),
863 );
864 let index = 0;
865 for (const item of all(packageXml, "itemref")) {
866 yield `\n\n## Chapter ${++index}\n`;
867 const href = items.get(item.attrs.idref);
868 if (!href) {
869 skip(`chapter ${index}`);
870 continue;
871 }
872 let decoded: string;
873 try {
874 decoded = decodeURIComponent(href.split(/[?#]/, 1)[0]!);
875 } catch {
876 skip(`chapter ${index}`);
877 continue;
878 }
879 const name = NodePath.posix.normalize(
880 NodePath.posix.join(NodePath.posix.dirname(rootfile), decoded),
881 );
882 yield* paragraphs(read(name));
883 }
884 } else throw new Error("Unsupported document");
885 yield* notes;
886 }
888​
889export async function extractDocumentText(path: string, extension: string): Promise<string> {
890 let result = "";
891 let remaining = MAX_OUTPUT;
892 let cellDepth = 0;
893 let started = false;
894 let space = false;
895 let truncated = false;
896 try {
897 // Charge raw text before normalization so repeated whitespace also exhausts the budget.
898 for await (const part of document(path, extension)) {
899 if (part === CELL_START) {
900 if (cellDepth++ === 0) {
901 started = false;
902 space = false;
903 } else if (started) space = true;
904 continue;
905 }
906 if (part === CELL_END) {
907 cellDepth--;
908 if (cellDepth > 0 && started) space = true;
909 continue;
910 }
911 if (typeof part !== "string" && started) continue;
912 const raw = typeof part === "string" ? part : part.fallback;
913 let value = raw.slice(0, remaining).replaceAll("\0", "");
914 remaining -= Math.min(raw.length, remaining);
915 if (cellDepth) {
916 value = value.replaceAll(/\s+/g, " ");
917 const trimmed = value.trim();
918 if (trimmed) {
919 result += (started && (space || value.startsWith(" ")) ? " " : "") + trimmed;
920 started = true;
921 }
922 space = value.endsWith(" ") || (!value && space);
923 } else result += value;
924 if (remaining === 0) throw new Truncation("Output budget");
925 }
926 } catch (error) {
927 if (!(error instanceof Truncation)) throw error;
928 truncated = true;
929 }
930 result = result.replaceAll(/\n(?:[ \t]*\n){2,}/g, "\n\n").trim();
931 if (!result && !truncated) throw new Error("No text extracted");
932 return truncated ? result.replace(/[\uD800-\uDBFF]$/, "").trimEnd() + TRUNCATED : result;