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

documentTextWorker.ts

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