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

userInputAttachments.test.ts

1,174 lines57.4 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodePath from "node:path";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import { describe, expect, it } from "@effect/vitest";
7import * as Effect from "effect/Effect";
8import * as Deferred from "effect/Deferred";
9import * as Fiber from "effect/Fiber";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as TestClock from "effect/testing/TestClock";
13import { vi } from "vite-plus/test";
14import * as HostProcess from "@t3tools/shared/HostProcess";
15import * as ServerConfig from "../config.ts";
16import * as DocumentText from "./DocumentText.ts";
17import { extractDocumentText } from "./documentTextWorker.ts";
18import * as Cleanup from "../orchestration-v2/ResourceCleanupService.ts";
19import * as TerminalManager from "../terminal/Manager.ts";
20import * as PreviewManager from "../preview/Manager.ts";
21import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
22import * as NodeZlib from "node:zlib";
23import { appendUserInputAttachmentPaths } from "./userInputAttachments.ts";
24​
25vi.mock("node:child_process", { spy: true });
26​
27const layer = Layer.merge(
28 ServerConfig.layerTest(process.cwd(), { prefix: "t3-answer-paths-" }),
29 DocumentText.layer,
30).pipe(Layer.provideMerge(NodeServices.layer));
31const attachment = {
32 type: "file" as const,
33 id: "thread-1-00000000-0000-4000-8000-0000000000aa-txt",
34 name: 'spec "final".txt',
35 mimeType: "text/plain",
36 sizeBytes: 4,
37};
38describe("question answer paths", () => {
39 it.effect.each([false, true])(
40 "keeps unrelated files available during extraction (failure: %s)",
41 (failure) =>
42 Effect.gen(function* () {
43 const config = yield* ServerConfig.ServerConfig;
44 const fs = yield* FileSystem.FileSystem;
45 const path = NodePath.join(config.attachmentsDir, "blocked.rtf");
46 const cached = NodePath.join(config.attachmentsDir, "cached.rtf");
47 NodeFS.writeFileSync(path, failure ? "invalid document" : String.raw`{\rtf1 Available}`);
48 NodeFS.writeFileSync(cached + ".txt", "Cached text");
49 const started = yield* Deferred.make<void>();
50 const release = yield* Deferred.make<void>();
51 let reads = 0;
52 yield* Effect.gen(function* () {
53 const documents = yield* DocumentText.DocumentText;
54 const extraction = yield* documents.ensure(path).pipe(Effect.forkChild);
55 yield* Deferred.await(started);
56 const duplicate = yield* documents.ensure(path).pipe(Effect.forkChild);
57 expect(yield* documents.ensure(path + ".png")).toBeUndefined();
58 expect(yield* documents.ensure(path + ".pdf")).toBeUndefined();
59 expect(yield* documents.ensure(cached)).toBe(cached + ".txt");
60 expect(NodeFS.readFileSync(cached + ".txt", "utf8")).toBe("Cached text");
61 yield* Deferred.succeed(release, undefined);
62 const expected = failure ? undefined : path + ".txt";
63 expect(yield* Fiber.join(extraction)).toBe(expected);
64 expect(yield* Fiber.join(duplicate)).toBe(expected);
65 expect(yield* documents.ensure(path)).toBe(expected);
66 expect(reads).toBe(1);
67 if (failure) {
68 NodeFS.writeFileSync(path + ".txt", "Recovered text");
69 expect(yield* documents.ensure(path)).toBe(path + ".txt");
70 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe("Recovered text");
71 } else expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe("Available");
72 }).pipe(
73 Effect.provide(Layer.fresh(DocumentText.layer)),
74 Effect.provideService(FileSystem.FileSystem, {
75 ...fs,
76 stat: (file) =>
77 file === path
78 ? Effect.gen(function* () {
79 reads++;
80 yield* Deferred.succeed(started, undefined);
81 yield* Deferred.await(release);
82 return yield* fs.stat(file);
83 })
84 : fs.stat(file),
85 }),
86 );
87 }).pipe(Effect.provide(layer)),
88 );
89​
90 it.effect.each(["spawn", "read"])("retries after a transient %s failure expires", (failure) =>
91 Effect.acquireUseRelease(
92 Effect.promise(async () => {
93 const { execFile } = await vi.importActual<typeof NodeChildProcess>("node:child_process");
94 const worker = vi.spyOn(NodeChildProcess, "execFile");
95 worker.mockImplementationOnce(((
96 file: string,
97 args: readonly string[],
98 options: NodeChildProcess.ExecFileOptionsWithStringEncoding,
99 callback: (
100 error: NodeChildProcess.ExecFileException | null,
101 stdout: string,
102 stderr: string,
103 ) => void,
104 ) => {
105 if (failure === "spawn") {
106 throw Object.assign(new Error("spawn EAGAIN"), { code: "EAGAIN" });
107 }
108 const preload = `import fs from 'node:fs/promises';
109 import { syncBuiltinESMExports } from 'node:module';
110 fs.readFile = async () => { throw Object.assign(new Error('read EAGAIN'), { code: 'EAGAIN' }); };
111 syncBuiltinESMExports();`;
112 return execFile(
113 file,
114 ["--import", `data:text/javascript,${encodeURIComponent(preload)}`, ...args],
115 options,
116 callback,
117 );
118 }) as typeof NodeChildProcess.execFile);
119 return worker;
120 }),
121 (worker) =>
122 Effect.gen(function* () {
123 const config = yield* ServerConfig.ServerConfig;
124 const path = NodePath.join(config.attachmentsDir, "retry.rtf");
125 NodeFS.writeFileSync(path, String.raw`{\rtf1 Available}`);
126 const documents = yield* DocumentText.DocumentText;
127 expect(yield* documents.ensure(path)).toBeUndefined();
128 expect(yield* documents.ensure(path)).toBeUndefined();
129 expect(worker).toHaveBeenCalledTimes(1);
130 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
131 yield* TestClock.adjust("1 second");
132 expect(yield* documents.ensure(path)).toBe(path + ".txt");
133 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe("Available");
134 expect(worker).toHaveBeenCalledTimes(2);
135 expect(yield* documents.ensure(path)).toBe(path + ".txt");
136 expect(worker).toHaveBeenCalledTimes(2);
137 }).pipe(Effect.provide(layer)),
138 (worker) => Effect.sync(() => worker.mockRestore()),
139 ),
140 );
141​
142 it.effect.each([
143 ["ipynb", "{"],
144 ["rtf", "invalid document"],
145 ["rtf", String.raw`{\rtf1}`],
146 ["rtf", String.raw`{\rtf1\ansi\ansicpg99999 Unsupported}`],
147 ] as const)("caches unchanged document rejections: %s %s", ([extension, source]) =>
148 Effect.acquireUseRelease(
149 Effect.sync(() => vi.spyOn(NodeChildProcess, "execFile")),
150 (worker) =>
151 Effect.gen(function* () {
152 const config = yield* ServerConfig.ServerConfig;
153 const path = NodePath.join(config.attachmentsDir, `invalid.${extension}`);
154 NodeFS.writeFileSync(path, source);
155 const documents = yield* DocumentText.DocumentText;
156 for (const seconds of [0, 1, 60]) {
157 yield* TestClock.adjust(`${seconds} seconds`);
158 expect(yield* documents.ensure(path)).toBeUndefined();
159 expect(worker).toHaveBeenCalledTimes(1);
160 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
161 }
162 }).pipe(Effect.provide(layer)),
163 (worker) => Effect.sync(() => worker.mockRestore()),
164 ),
165 );
166​
167 it.effect.each([
168 [
169 "text symbols",
170 String.raw`{\rtf1\ansi Pages 1\endash 5\emdash\lquote left\rquote\ldblquote right\rdblquote\bullet\b End\b0\unknown{\*\secret\bullet hidden}}`,
171 "Pages 1–5—‘left’“right”•End",
172 ],
173 [
174 "space and hyphen symbols",
175 String.raw`{\rtf1\ansi A\enspace B\emspace C\qmspace D\~E\_F\-G}`,
176 "A\u2002B\u2003C\u2005D\u00a0E\u2011FG",
177 ],
178 [
179 "text symbol fallback",
180 String.raw`{\rtf1\ansi\uc10\u945\endash\emdash\enspace\emspace\qmspace\lquote\rquote\ldblquote\rdblquote\bullet Z}`,
181 "αZ",
182 ],
183 ["hyphen symbol fallback", String.raw`{\rtf1\ansi\uc3\u945\~\_\-Z}`, "αZ"],
184 ["control word", String.raw`{\rtf1\ansi A\u9\tab X}`, "A\tX"],
185 ["group close", String.raw`{\rtf1\ansi{\u945}Z}`, "αZ"],
186 ["group open", String.raw`{\rtf1\ansi\u945{Z}}`, "αZ"],
187 ["hex byte", String.raw`{\rtf1\ansi\u945\'3fZ}`, "αZ"],
188 ["escaped symbol", String.raw`{\rtf1\ansi\u945\{Z}`, "αZ"],
189 ["destination symbol", String.raw`{\rtf1\ansi\u945\*Z}`, "αZ"],
190 ["multiple units", String.raw`{\rtf1\ansi\uc4\u945?\tab\'3f\~Z}`, "αZ"],
191 ["binary unit", String.raw`{\rtf1\ansi\u945\bin3 abcZ}`, "αZ"],
192 ["large fallback", String.raw`{\rtf1\ansi\uc20\u945????????????????????Z}`, "αZ"],
193 ["no fallback", String.raw`{\rtf1\ansi\uc0\u945Z}`, "αZ"],
194 ["scoped count", String.raw`{\rtf1\ansi{\uc2\u945??}\u946?Z}`, "αβZ"],
195 ] as const)("extracts RTF symbols and Unicode fallbacks: %s", ([name, source, expected]) =>
196 Effect.gen(function* () {
197 const config = yield* ServerConfig.ServerConfig;
198 const path = NodePath.join(config.attachmentsDir, `${name}.rtf`);
199 NodeFS.writeFileSync(path, source);
200 expect(yield* Effect.promise(() => extractDocumentText(path, ".rtf"))).toBe(expected);
201 expect(yield* (yield* DocumentText.DocumentText).ensure(path)).toBe(path + ".txt");
202 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe(expected);
203 }).pipe(Effect.provide(layer)),
204 );
205​
206 it.effect.each([false, true])("limits the child heap for standalone=%s", (standalone) =>
207 Effect.acquireUseRelease(
208 Effect.promise(async () => {
209 const { execFile } = await vi.importActual<typeof NodeChildProcess>("node:child_process");
210 const probe = vi.spyOn(NodeChildProcess, "execFile");
211 probe.mockImplementation(((
212 file: string,
213 _args: readonly string[],
214 options: NodeChildProcess.ExecFileOptionsWithStringEncoding,
215 callback: (
216 error: NodeChildProcess.ExecFileException | null,
217 stdout: string,
218 stderr: string,
219 ) => void,
220 ) =>
221 execFile(
222 file,
223 [
224 "-e",
225 'process.stdout.write(String(require("node:v8").getHeapStatistics().heap_size_limit))',
226 ],
227 options,
228 callback,
229 )) as typeof NodeChildProcess.execFile);
230 return probe;
231 }),
232 () =>
233 Effect.gen(function* () {
234 const config = yield* ServerConfig.ServerConfig;
235 const path = NodePath.join(config.attachmentsDir, "heap.rtf");
236 NodeFS.writeFileSync(path, String.raw`{\rtf1 hello}`);
237 const extracted = yield* Effect.gen(function* () {
238 return yield* (yield* DocumentText.DocumentText).ensure(path);
239 }).pipe(
240 Effect.provide(Layer.fresh(DocumentText.layer)),
241 Effect.provideService(HostProcess.IsExecutable, standalone),
242 Effect.provideService(HostProcess.Environment, {
243 ...process.env,
244 NODE_OPTIONS: "--max-old-space-size=1024",
245 }),
246 );
247 expect(extracted).toBe(path + ".txt");
248 const heapLimit = Number(NodeFS.readFileSync(path + ".txt", "utf8"));
249 expect(heapLimit).toBeGreaterThan(192 * 1024 * 1024);
250 // Newer V8 versions reserve up to 192 MiB for the young generation as well.
251 expect(heapLimit).toBeLessThanOrEqual(384 * 1024 * 1024);
252 }).pipe(Effect.provide(layer)),
253 (probe) => Effect.sync(() => probe.mockRestore()),
254 ),
255 );
256​
257 it.effect("extracts notebook cells and outputs once and keeps both readable paths", () =>
258 Effect.gen(function* () {
259 const config = yield* ServerConfig.ServerConfig;
260 const file = {
261 ...attachment,
262 id: attachment.id.replace(/txt$/, "ipynb"),
263 name: "survey.ipynb",
264 mimeType: "application/x-ipynb+json",
265 };
266 const path = NodePath.join(config.attachmentsDir, `${file.id}.ipynb`);
267 const notebook = JSON.stringify({
268 cells: [
269 { cell_type: "markdown", source: ["# Survey\n", "Vessel: Larkspur"] },
270 {
271 cell_type: "code",
272 source: ["print(43 * 7)"],
273 outputs: [
274 { text: ["301\n"] },
275 { data: { "text/plain": ["42"] } },
276 {
277 output_type: "error",
278 ename: "ZeroDivisionError",
279 evalue: "division by zero",
280 traceback: [
281 "\u001b[32mCell In[1], line 1\u001b[0m",
282 "\u001b[31m----> 1 1 / 0\u001b[0m",
283 "ZeroDivisionError: division by zero",
284 ],
285 },
286 ],
287 },
288 ],
289 });
290 NodeFS.writeFileSync(path, notebook);
291 const answers = yield* appendUserInputAttachmentPaths({
292 answers: { q: "Read this" },
293 attachmentsDir: config.attachmentsDir,
294 attachmentsByQuestionId: { q: [file] },
295 });
296 expect(answers.q).toContain(`text extracted to: "${path}.txt"`);
297 expect(NodeFS.readFileSync(`${path}.txt`, "utf8")).toContain("Vessel: Larkspur");
298 expect(NodeFS.readFileSync(`${path}.txt`, "utf8")).toContain("301");
299 expect(NodeFS.readFileSync(`${path}.txt`, "utf8")).toContain("42");
300 const extracted = NodeFS.readFileSync(`${path}.txt`, "utf8");
301 expect(extracted).toContain(
302 "ZeroDivisionError: division by zero\nCell In[1], line 1\n----> 1 1 / 0\nZeroDivisionError: division by zero",
303 );
304 expect(extracted).not.toContain("\u001b");
305 expect(NodeFS.readFileSync(path, "utf8")).toBe(notebook);
306 const before = NodeFS.statSync(path + ".txt").mtimeMs;
307 // A changed binary would fail parsing if the cached extraction were not reused.
308 NodeFS.writeFileSync(path, "invalid notebook");
309 const documents = yield* DocumentText.DocumentText;
310 const results = yield* Effect.all([documents.ensure(path), documents.ensure(path)], {
311 concurrency: "unbounded",
312 });
313 expect(results).toEqual([path + ".txt", path + ".txt"]);
314 expect(NodeFS.statSync(path + ".txt").mtimeMs).toBe(before);
315 yield* Effect.gen(function* () {
316 const cleanup = yield* Cleanup.ResourceCleanupService;
317 yield* cleanup.cleanupAttachments([file.id]);
318 expect(NodeFS.existsSync(path)).toBe(false);
319 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
320 NodeFS.writeFileSync(path + ".txt", "orphaned extraction");
321 yield* cleanup.cleanupAttachments([file.id]);
322 expect(NodeFS.existsSync(path + ".txt")).toBe(false);
323 }).pipe(
324 Effect.provide(
325 Cleanup.layer.pipe(
326 Layer.provide(
327 Layer.mergeAll(
328 Layer.mock(TerminalManager.TerminalManager)({}),
329 Layer.mock(PreviewManager.PreviewManager)({}),
330 Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
331 ),
332 ),
333 ),
334 ),
335 );
336 }).pipe(Effect.provide(layer)),
337 );
338​
339 it.effect(
340 "preserves corrupt documents, PDFs and unknown binaries without an extracted path",
341 () =>
342 Effect.gen(function* () {
343 const config = yield* ServerConfig.ServerConfig;
344 for (const extension of ["docx", "ipynb", "zip", "pdf"]) {
345 const file = {
346 ...attachment,
347 id: attachment.id.replace(/txt$/, extension),
348 name: `broken.${extension}`,
349 };
350 const path = NodePath.join(config.attachmentsDir, `${file.id}.${extension}`);
351 NodeFS.writeFileSync(path, "invalid document");
352 const answers = yield* appendUserInputAttachmentPaths({
353 answers: {},
354 attachmentsDir: config.attachmentsDir,
355 attachmentsByQuestionId: { q: [file] },
356 });
357 expect(answers.q).toContain(path);
358 expect(answers.q).not.toContain("text extracted");
359 expect(NodeFS.existsSync(`${path}.txt`)).toBe(false);
360 expect(NodeFS.readFileSync(path, "utf8")).toBe("invalid document");
361 }
362 }).pipe(Effect.provide(layer)),
363 );
364​
365 it.effect("preserves office structure and EPUB reading order with bounded archives", () =>
366 Effect.gen(function* () {
367 const config = yield* ServerConfig.ServerConfig;
368 const cases = [
369 {
370 ext: "docx",
371 bounded: true,
372 parts: {
373 "word/document.xml": "<document><p>Readable despite embedded media</p></document>",
374 "word/media/black.bmp": "\0".repeat(64 * 1024),
375 "word/embeddings/unused.bin": "\0".repeat(33 * 1024 * 1024),
376 },
377 expected: ["Readable despite embedded media"],
378 absent: ["[Extracted text truncated"],
379 },
380 ...[false, true].map((deep) => ({
381 ext: "docx",
382 bounded: true,
383 parts: {
384 "word/document.xml": `<document>${deep ? "<div>".repeat(129) + "Lost" + "</div>".repeat(129) : "<p/>".repeat(200_001)}</document>`,
385 },
386 expected: ["[Extracted text truncated at document extraction limits.]"],
387 absent: ["Lost"],
388 })),
389 ...["ods", "odt", "odp", "docx"].flatMap((ext) =>
390 [false, true].map((rows) => ({
391 ext,
392 bounded: true,
393 parts: {
394 [ext === "docx" ? "word/document.xml" : "content.xml"]:
395 `<document><page><table><table-row${rows ? ' number-rows-repeated="10001"' : ""}><table-cell${rows ? "" : ' number-columns-repeated="513"'}><p>Repeated value</p></table-cell></table-row></table></page></document>`,
396 },
397 expected: [
398 "Repeated value",
399 "[Extracted text truncated at document extraction limits.]",
400 ],
401 occurrences: { text: "Repeated value", count: rows ? 10_000 : 512 },
402 })),
403 ),
404 ...["ods", "odt", "odp", "docx"].map((ext) => ({
405 ext,
406 bounded: true,
407 parts: {
408 [ext === "docx" ? "word/document.xml" : "content.xml"]:
409 `<document><page><table><table-row><table-cell><p>Kept</p></table-cell><table-cell number-columns-repeated="16383"> \n <p> \t </p> <s c="1048575"/> </table-cell></table-row><table-row number-rows-repeated="1048575"><table-cell> \n <p> \t </p> </table-cell></table-row></table></page></document>`,
410 },
411 expected: ["Kept"],
412 absent: ["[Extracted text truncated", "\t"],
413 })),
414 ...["ods", "odt", "odp"].map((ext) => ({
415 ext,
416 bounded: true,
417 parts: {
418 "content.xml": `<document><page><table><table-row>
419 <table-cell office:value-type="string" office:string-value="Harbor"/>
420 <table-cell office:value-type="boolean" office:boolean-value="false"/>
421 <table-cell office:value-type="date" office:date-value="2026-10-20"/>
422 <table-cell office:value-type="time" office:time-value="PT2H30M"/>
423 <table-cell office:value-type="currency" office:value="125.50" office:currency="USD"/>
424 <table-cell office:value-type="percentage" office:value="0.25"/>
425 <table-cell office:value-type="float" office:value="0"/>
426 <table-cell office:value-type="string" office:string-value="Fallback"><p> \n </p></table-cell>
427 <table-cell office:value-type="string" office:string-value="Unshown"><p>Displayed</p></table-cell>
428 <table-cell office:value-type="void" office:value="Unshown"/>
429 <table-cell office:value-type="currency" office:value=" " office:currency="Unshown"/>
430 <table-cell office:value-type="percentage" office:value=" "/>
431 </table-row></table></page></document>`,
432 },
433 expected: [
434 "Harbor\tfalse\t2026-10-20\tPT2H30M\t125.50 USD\t0.25 [ODF value-type=percentage]\t0\tFallback\tDisplayed",
435 ],
436 absent: ["Unshown", "[Extracted text truncated"],
437 })),
438 ...[false, true].map((rows) => ({
439 ext: "xlsx",
440 bounded: true,
441 parts: {
442 "xl/workbook.xml": '<workbook><sheet name="Limited" r:id="a"/></workbook>',
443 "xl/_rels/workbook.xml.rels":
444 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
445 "xl/worksheets/a.xml": `<worksheet>${rows ? "<row><c><v>7</v></c></row>".repeat(10_001) : '<row><c r="A1"><v>7</v></c><c r="SS1"><v>Beyond</v></c></row>'}</worksheet>`,
446 },
447 expected: ["7", "[Extracted text truncated at document extraction limits.]"],
448 absent: ["Beyond"],
449 })),
450 {
451 ext: "xlsx",
452 bounded: true,
453 parts: {
454 "xl/workbook.xml": '<workbook><sheet name="Padding" r:id="a"/></workbook>',
455 "xl/_rels/workbook.xml.rels":
456 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
457 "xl/sharedStrings.xml": "<sst><si><t> \n </t></si><si><t>Present</t></si></sst>",
458 "xl/worksheets/a.xml": `<worksheet>${'<row><c t="s"><v>0</v></c><c r="XFD1" t="inlineStr"><is><t> \t </t></is></c></row>'.repeat(10_001)}<row><c t="s"><v>0</v></c><c t="s"><v>1</v></c><c r="XFD2"><v> \n </v></c></row></worksheet>`,
459 },
460 expected: ["Present"],
461 absent: ["[Extracted text truncated"],
462 },
463 {
464 ext: "epub",
465 parts: {
466 "META-INF/container.xml": '<container><rootfile full-path="book.opf"/></container>',
467 "book.opf":
468 '<package><item id="bad" href="ch%ZZ.xhtml"/><item id="good" href="good.svg"/><itemref idref="bad"/><itemref idref="good"/></package>',
469 "good.svg":
470 '<svg xmlns="http://www.w3.org/2000/svg"><text>Readable SVG chapter</text></svg>',
471 },
472 expected: [
473 "Readable SVG chapter",
474 "[Skipped document part: chapter 1 (missing or invalid XML).]",
475 ],
476 absent: ["[Extracted text truncated"],
477 },
478 ...[false, true].flatMap((bom) =>
479 [false, true].map((bigEndian) => {
480 const encode = (source: string) => {
481 const data = Buffer.from(`${bom ? "\ufeff" : ""}${source}`, "utf16le");
482 return bigEndian ? data.swap16() : data;
483 };
484 return {
485 ext: "epub",
486 parts: {
487 "META-INF/container.xml": encode(
488 '<?xml version="1.0" encoding="UTF-16"?><container><rootfile full-path="book.opf"/></container>',
489 ),
490 "book.opf": encode(
491 '<?xml version="1.0" encoding="UTF-16"?><package><item id="a" href="a.xhtml"/><itemref idref="a"/></package>',
492 ),
493 "a.xhtml": encode(
494 '<?xml version="1.0" encoding="UTF-16"?><html><p>UTF-16 chapter: café 日本語</p></html>',
495 ),
496 },
497 expected: ["UTF-16 chapter: café 日本語"],
498 absent: ["[Skipped document part", "[Extracted text truncated"],
499 };
500 }),
501 ),
502 {
503 ext: "epub",
504 bounded: true,
505 parts: {
506 "META-INF/container.xml": '<container><rootfile full-path="book.opf"/></container>',
507 "book.opf":
508 '<package><item id="bad" href="bad.xhtml"/><item id="good" href="good.xhtml"/><itemref idref="bad"/><itemref idref="good"/></package>',
509 "bad.xhtml": "<html><p>Discard this broken chapter</html>",
510 "good.xhtml":
511 '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html><p>North&nbsp;Harbor &NotEqualTilde; &CounterClockwiseContourIntegral; &amp; &lt;tag&gt; &quot;quoted&quot;</p><p><![CDATA[Literal &nbsp;]]></p><table><tr><td>&nbsp; </td></tr><tr><td>Kept&nbsp;cell</td></tr></table></html>',
512 },
513 expected: [
514 "## Chapter 2",
515 'North\u00a0Harbor ≂̸ ∳ & <tag> "quoted"',
516 "Literal &nbsp;",
517 "Kept cell",
518 "[Skipped document part: bad.xhtml (missing or invalid XML).]",
519 ],
520 absent: ["Discard this broken chapter", "[Extracted text truncated"],
521 },
522 ...["pptx", "xlsx"].map((ext) => ({
523 ext,
524 bounded: true,
525 parts:
526 ext === "pptx"
527 ? {
528 "ppt/presentation.xml":
529 '<presentation><sldId r:id="bad"/><sldId r:id="good"/></presentation>',
530 "ppt/_rels/presentation.xml.rels":
531 '<Relationships><Relationship Id="bad" Target="bad.xml"/><Relationship Id="good" Target="good.xml"/></Relationships>',
532 "ppt/bad.xml": "<slide><p>Discard</slide>",
533 "ppt/good.xml": "<slide><p>Healthy part</p></slide>",
534 }
535 : {
536 "xl/workbook.xml":
537 '<workbook><sheet name="Bad" r:id="bad"/><sheet name="Good" r:id="good"/></workbook>',
538 "xl/_rels/workbook.xml.rels":
539 '<Relationships><Relationship Id="bad" Target="bad.xml"/><Relationship Id="good" Target="good.xml"/></Relationships>',
540 "xl/bad.xml": "<worksheet><row>Discard</worksheet>",
541 "xl/good.xml":
542 '<worksheet><row><c t="inlineStr"><is><t>Healthy part</t></is></c></row></worksheet>',
543 },
544 expected: [
545 "Healthy part",
546 `[Skipped document part: ${ext === "pptx" ? "ppt" : "xl"}/bad.xml (missing or invalid XML).]`,
547 ],
548 absent: ["Discard", "[Extracted text truncated"],
549 })),
550 {
551 ext: "odt",
552 bounded: true,
553 parts: { "content.xml": '<document><p>Start<s c="1000001"/>Unneeded</p></document>' },
554 expected: ["Start", "[Extracted text truncated at document extraction limits.]"],
555 absent: ["Unneeded"],
556 },
557 {
558 ext: "docx",
559 bounded: true,
560 parts: {
561 "word/document.xml":
562 '<w:document xmlns:w="urn:w" xmlns:mc="urn:mc"><w:body><w:p><w:r><w:t>Body</w:t></w:r></w:p><w:p><w:r><mc:AlternateContent><mc:Choice Requires="wps"><w:drawing><wps:wsp><wps:txbx><w:txbxContent><w:p><w:r><w:t>Callout box</w:t></w:r></w:p></w:txbxContent></wps:txbx></wps:wsp></w:drawing></mc:Choice><mc:Fallback><w:pict><v:shape><v:textbox><w:txbxContent><w:p><w:r><w:t>Callout box</w:t></w:r></w:p></w:txbxContent></v:textbox></v:shape></w:pict></mc:Fallback></mc:AlternateContent></w:r></w:p></w:body></w:document>',
563 },
564 expected: ["Body\nCallout box"],
565 occurrences: { text: "Callout box", count: 1 },
566 },
567 {
568 ext: "docx",
569 bounded: true,
570 parts: {
571 "word/document.xml":
572 '<w:document xmlns:w="urn:w" xmlns:mc="urn:mc"><w:body><w:p><w:r><mc:AlternateContent><mc:Choice Requires="cx"><w:drawing><cx:chart/></w:drawing></mc:Choice><mc:Fallback><w:pict><v:shape><v:textbox><w:txbxContent><w:p><w:r><w:t>Chart caption</w:t></w:r></w:p></w:txbxContent></v:textbox></v:shape></w:pict></mc:Fallback></mc:AlternateContent></w:r></w:p></w:body></w:document>',
573 },
574 expected: ["Chart caption"],
575 },
576 {
577 ext: "docx",
578 bounded: true,
579 parts: {
580 "word/document.xml":
581 '<w:document xmlns:w="urn:w"><w:body><w:p><w:pPr><w:pStyle w:val="Heading2"/></w:pPr><w:r><w:t>Report &amp; totals</w:t></w:r></w:p><w:tbl><w:tr><w:tc><w:p><w:r><w:t>North</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>12</w:t></w:r></w:p><w:p><w:r><w:t>34</w:t></w:r></w:p></w:tc></w:tr><w:tr><w:tc><w:p><w:r><w:t>Before</w:t></w:r></w:p><w:tbl><w:tr><w:tc><w:p><w:r><w:t>Inner</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p><w:r><w:t>After</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>Neighbor</w:t></w:r></w:p></w:tc></w:tr></w:tbl></w:body></w:document>',
582 },
583 expected: ["## Report & totals", "North\t12 34", "Before Inner After\tNeighbor"],
584 },
585 {
586 ext: "docx",
587 bounded: true,
588 parts: {
589 "word/document.xml":
590 '<w:document xmlns:w="urn:w"><w:body><w:p><w:r><w:t>First</w:t><w:cr/><w:t>Second</w:t><w:br/><w:t>Third</w:t></w:r></w:p></w:body></w:document>',
591 },
592 expected: ["First\nSecond\nThird"],
593 },
594 {
595 ext: "docx",
596 bounded: true,
597 parts: {
598 "word/document.xml":
599 '<w:document xmlns:w="urn:w"><w:body><w:p><w:r><w:t>Intro</w:t></w:r><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText> PAGEREF _Toc1 \\h </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t> 3</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p><w:p><w:pPr><w:tabs><w:tab w:val="right" w:pos="9350"/></w:tabs></w:pPr><w:r><w:t xml:space="preserve">Fee </w:t></w:r><w:del><w:r><w:delText>$500</w:delText></w:r></w:del><w:ins><w:r><w:t>$700</w:t></w:r></w:ins><w:moveFrom><w:r><w:t>Moved</w:t></w:r></w:moveFrom><w:r><w:tab/><w:t>due</w:t></w:r></w:p></w:body></w:document>',
600 },
601 expected: ["Intro 3\nFee $700\tdue"],
602 absent: ["PAGEREF", "$500", "Moved"],
603 },
604 {
605 ext: "odt",
606 bounded: true,
607 parts: {
608 "content.xml":
609 "<document><text><tracked-changes><changed-region><deletion><change-info><creator>Reviewer</creator></change-info><p>$500</p></deletion></changed-region></tracked-changes><p>Fee <change/>$700</p></text></document>",
610 },
611 expected: ["Fee $700"],
612 absent: ["Reviewer", "$500"],
613 },
614 {
615 ext: "docx",
616 bounded: true,
617 parts: {
618 "word/document.xml": `<w:document><w:body><w:tbl><w:tr><w:tc><w:p><w:r><w:t>${"A".repeat(1_000_000)}</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>Later cell</w:t></w:r></w:p></w:tc></w:tr></w:tbl></w:body></w:document>`,
619 },
620 expected: ["A".repeat(32), "[Extracted text truncated at document extraction limits.]"],
621 },
622 {
623 ext: "xlsx",
624 bounded: true,
625 parts: {
626 "xl/workbook.xml": '<workbook><sheet name="Formulas" r:id="a"/></workbook>',
627 "xl/_rels/workbook.xml.rels":
628 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
629 "xl/styles.xml": '<styleSheet><cellXfs><xf numFmtId="9"/></cellXfs></styleSheet>',
630 "xl/worksheets/a.xml":
631 "<worksheet><row><c><f>SUM(11,22)</f><v/></c></row><row><c><f>SUM(33,44)</f><v> \n </v></c></row><row><c><f>SUM(55,66)</f></c></row><row><c><f>SUM(11,22)</f><v>33</v></c><c><f>SUM(0,0)</f><v>0</v></c></row></worksheet>",
632 },
633 expected: [
634 "SUM(11,22)\nSUM(33,44)\nSUM(55,66)",
635 "33 [Excel numFmtId=9; date system 1900]\t0 [Excel numFmtId=9; date system 1900]",
636 ],
637 absent: ["SUM(0,0)", "[Extracted text truncated"],
638 },
639 {
640 ext: "xlsx",
641 parts: {
642 "xl/workbook.xml":
643 '<workbook><sheets><sheet name="Inventory" r:id="a"/><sheet name="Budget" r:id="b"/></sheets></workbook>',
644 "xl/_rels/workbook.xml.rels":
645 '<Relationships><Relationship Id="a" Target="worksheets/second.xml"/><Relationship Id="b" Target="worksheets/first.xml"/></Relationships>',
646 "xl/sharedStrings.xml": "<sst><si><t>Lantern</t></si></sst>",
647 "xl/styles.xml":
648 '<styleSheet><numFmts><numFmt numFmtId="164" formatCode="yyyy-mm-dd"/></numFmts><cellXfs><xf numFmtId="0"/><xf numFmtId="14"/><xf numFmtId="9"/><xf numFmtId="164"/></cellXfs></styleSheet>',
649 "xl/worksheets/second.xml":
650 '<worksheet><sheetData><row><c r="A1" t="s"><v>0</v></c><c r="C1"><v>37</v></c></row></sheetData></worksheet>',
651 "xl/worksheets/first.xml":
652 '<worksheet><sheetData><row><c t="inlineStr"><is><t>Ferry</t></is></c><c><v>628</v></c><c s="1"><v>45292</v></c><c s="2"><v>0.25</v></c><c s="3"><v>45293</v></c></row></sheetData></worksheet>',
653 },
654 expected: [
655 "## Sheet: Inventory",
656 "Lantern\t\t37",
657 "## Sheet: Budget",
658 "Ferry\t628",
659 "45292 [Excel numFmtId=14; date system 1900]",
660 "0.25 [Excel numFmtId=9; date system 1900]",
661 "45293 [Excel numFmtId=164; format=yyyy-mm-dd; date system 1900]",
662 ],
663 },
664 {
665 ext: "xlsx",
666 bounded: true,
667 parts: {
668 "xl/workbook.xml": '<workbook><sheet name="Phonetics" r:id="a"/></workbook>',
669 "xl/_rels/workbook.xml.rels":
670 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
671 "xl/sharedStrings.xml":
672 '<sst><si><t>東京</t><rPh sb="0" eb="2"><t>とうきょう</t></rPh></si></sst>',
673 "xl/worksheets/a.xml":
674 '<worksheet><row><c t="s"><v>0</v></c><c t="inlineStr"><is><t>東京</t><rPh sb="0" eb="2"><t>とうきょう</t></rPh></is></c></row></worksheet>',
675 },
676 expected: ["## Sheet: Phonetics", "東京\t東京"],
677 absent: ["とうきょう"],
678 },
679 {
680 ext: "xlsx",
681 bounded: true,
682 parts: {
683 "xl/workbook.xml":
684 '<workbook><workbookPr date1904="true"/><sheets><sheet name="Dates" r:id="a"/></sheets></workbook>',
685 "xl/_rels/workbook.xml.rels":
686 '<Relationships><Relationship Id="a" Target="worksheets/dates.xml"/></Relationships>',
687 "xl/styles.xml": '<styleSheet><cellXfs><xf numFmtId="14"/></cellXfs></styleSheet>',
688 "xl/worksheets/dates.xml":
689 "<worksheet><sheetData><row><c><v>1</v></c></row></sheetData></worksheet>",
690 },
691 expected: ["## Sheet: Dates", "1 [Excel numFmtId=14; date system 1904]"],
692 },
693 {
694 ext: "xlsx",
695 bounded: true,
696 parts: {
697 "xl/workbook.xml":
698 '<workbook><sheets><sheet name="Repeated" r:id="a"/><sheet name="Unneeded" r:id="missing"/></sheets></workbook>',
699 "xl/_rels/workbook.xml.rels":
700 '<Relationships><Relationship Id="a" Target="worksheets/repeated.xml"/></Relationships>',
701 "xl/sharedStrings.xml": `<sst><si><t>${"A".repeat(1_000_000 - "## Sheet: Repeated\n".length)}</t></si></sst>`,
702 "xl/worksheets/repeated.xml": `<worksheet><sheetData>${'<row><c t="s"><v>0</v></c><c t="s"><v>0</v></c></row>'.repeat(1_500)}</sheetData></worksheet>`,
703 },
704 expected: [
705 "## Sheet: Repeated",
706 "A".repeat(32),
707 "[Extracted text truncated at document extraction limits.]",
708 ],
709 },
710 {
711 ext: "pptx",
712 bounded: true,
713 parts: {
714 "ppt/presentation.xml":
715 '<p:presentation><p:sldIdLst><p:sldId id="1" r:id="b"/><p:sldId id="2" r:id="a"/></p:sldIdLst></p:presentation>',
716 "ppt/_rels/presentation.xml.rels":
717 '<Relationships><Relationship Id="a" Target="slides/slide1.xml"/><Relationship Id="b" Target="slides/slide2.xml"/></Relationships>',
718 "ppt/slides/slide1.xml": "<p:sld><a:p><a:r><a:t>Departure</a:t></a:r></a:p></p:sld>",
719 "ppt/slides/slide2.xml": "<p:sld><a:p><a:r><a:t>Juniper Pier</a:t></a:r></a:p></p:sld>",
720 "ppt/slides/_rels/slide2.xml.rels":
721 '<Relationships><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../notesSlides/ignored.xml"/><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" TargetMode="External" Target="https://example.com/notes.xml"/><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/notes7.xml"/></Relationships>',
722 "ppt/slides/_rels/slide1.xml.rels":
723 '<Relationships><Relationship Type="http://purl.oclc.org/ooxml/officeDocument/relationships/notesSlide" Target="/ppt/notesSlides/notes3.xml"/></Relationships>',
724 "ppt/notesSlides/notes7.xml":
725 "<p:notes><a:p><a:r><a:t>evacuation code ORCHID-81</a:t></a:r></a:p></p:notes>",
726 "ppt/notesSlides/notes3.xml":
727 "<p:notes><a:p><a:r><a:t>Board at gate 4</a:t></a:r></a:p></p:notes>",
728 "ppt/notesSlides/ignored.xml": "<p:notes><a:p>Unrelated notes</a:p></p:notes>",
729 },
730 expected: [
731 "## Slide 1",
732 "Juniper Pier\nNotes:\nevacuation code ORCHID-81",
733 "## Slide 2",
734 "Departure\nNotes:\nBoard at gate 4",
735 ],
736 absent: ["Unrelated notes", "[Skipped document part", "[Extracted text truncated"],
737 },
738 ...[false, true].map((missing) => ({
739 ext: "pptx",
740 bounded: true,
741 parts: {
742 "ppt/presentation.xml": '<presentation><sldId r:id="a"/></presentation>',
743 "ppt/_rels/presentation.xml.rels":
744 '<Relationships><Relationship Id="a" Target="slides/a.xml"/></Relationships>',
745 "ppt/slides/a.xml": "<slide><p>Slide text</p></slide>",
746 "ppt/slides/_rels/a.xml.rels": `<Relationships><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/${missing ? "missing" : "bad"}.xml"/></Relationships>`,
747 "ppt/notesSlides/bad.xml": "<notes><p>Discard broken notes</notes>",
748 },
749 expected: [
750 "Slide text",
751 `[Skipped document part: ppt/notesSlides/${missing ? "missing" : "bad"}.xml (missing or invalid XML).]`,
752 ],
753 absent: ["Discard broken notes", "[Extracted text truncated"],
754 })),
755 {
756 ext: "pptx",
757 bounded: true,
758 parts: {
759 "ppt/presentation.xml":
760 '<presentation><sldId r:id="a"/><sldId r:id="b"/></presentation>',
761 "ppt/_rels/presentation.xml.rels":
762 '<Relationships><Relationship Id="a" Target="slides/a.xml"/><Relationship Id="b" Target="slides/b.xml"/></Relationships>',
763 "ppt/slides/a.xml": `<slide><p>${"A".repeat(600_000)}</p></slide>`,
764 "ppt/slides/b.xml": "<slide><p>Unneeded slide</p></slide>",
765 "ppt/slides/_rels/a.xml.rels":
766 '<Relationships><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/a.xml"/></Relationships>',
767 "ppt/notesSlides/a.xml": `<notes><p>evacuation code ORCHID-81 ${"B".repeat(600_000)} Unneeded notes</p></notes>`,
768 },
769 expected: [
770 "## Slide 1",
771 "A".repeat(32),
772 "Notes:\nevacuation code ORCHID-81",
773 "B".repeat(32),
774 "[Extracted text truncated at document extraction limits.]",
775 ],
776 absent: ["Unneeded notes", "Unneeded slide", "## Slide 2"],
777 },
778 {
779 ext: "odt",
780 parts: {
781 "content.xml":
782 '<office:document><text:h text:outline-level="2">Orchard</text:h><text:p>19<text:s text:c="3"/>violet<text:s/>crates</text:p></office:document>',
783 },
784 expected: ["## Orchard", "19 violet crates"],
785 },
786 {
787 ext: "ods",
788 parts: {
789 "content.xml":
790 '<office:document><table:table table:name="Cargo"><table:table-row><table:table-cell><text:p>Violet</text:p></table:table-cell><table:table-cell office:value="19"/><table:table-cell office:value="27"><text:p/></table:table-cell></table:table-row></table:table></office:document>',
791 },
792 expected: ["## Sheet: Cargo", "Violet\t19\t27"],
793 },
794 {
795 ext: "ods",
796 bounded: true,
797 parts: {
798 "content.xml":
799 '<office:document><table:table table:name="Padded rows"><table:table-row><table:table-cell><text:p>Left</text:p></table:table-cell><table:table-cell table:number-columns-repeated="2"/><table:table-cell><text:p>Right</text:p></table:table-cell></table:table-row><table:table-row table:number-rows-repeated="1048575"><table:table-cell/></table:table-row></table:table></office:document>',
800 },
801 expected: ["## Sheet: Padded rows", "Left\t\t\tRight"],
802 absent: ["[Extracted text truncated"],
803 },
804 {
805 ext: "ods",
806 bounded: true,
807 parts: {
808 "content.xml":
809 '<office:document><table:table table:name="Padded"><table:table-row><table:table-cell><text:p>Populated</text:p></table:table-cell><table:table-cell table:number-columns-repeated="16383"/></table:table-row><table:table-row table:number-rows-repeated="1048575"><table:table-cell table:number-columns-repeated="16384"><text:p/></table:table-cell></table:table-row></table:table></office:document>',
810 },
811 expected: ["## Sheet: Padded", "Populated"],
812 absent: ["[Extracted text truncated", "\t"],
813 },
814 {
815 ext: "ods",
816 bounded: true,
817 parts: {
818 "content.xml": `<office:document><table:table table:name="Repeated"><table:table-row><table:table-cell table:number-columns-repeated="512"><text:p>Lead ${"a".repeat(600_000)} Tail</text:p></table:table-cell></table:table-row></table:table></office:document>`,
819 },
820 expected: [
821 "## Sheet: Repeated",
822 "Lead ",
823 " Tail\tLead ",
824 "[Extracted text truncated at document extraction limits.]",
825 ],
826 },
827 {
828 ext: "odp",
829 parts: {
830 "content.xml":
831 "<office:document><draw:page><text:p>First</text:p></draw:page><draw:page><text:p>Second</text:p></draw:page></office:document>",
832 },
833 expected: ["## Slide 1", "First", "## Slide 2", "Second"],
834 },
835 {
836 ext: "ods",
837 bounded: true,
838 parts: {
839 "content.xml": `<office:document>${Array.from(
840 { length: 256 },
841 (_, index) =>
842 `<table:table table:name="${index === 0 ? "Shared" : "Unneeded"}"><table:table-row><table:table-cell table:number-columns-repeated="512"><text:p>${"B".repeat(4096)}</text:p></table:table-cell></table:table-row></table:table>`,
843 ).join("")}</office:document>`,
844 },
845 expected: [
846 "## Sheet: Shared",
847 "B".repeat(32),
848 "[Extracted text truncated at document extraction limits.]",
849 ],
850 absent: ["## Sheet: Unneeded"],
851 },
852 {
853 ext: "odt",
854 bounded: true,
855 parts: {
856 "content.xml": `<office:document><text:p>Before whitespace</text:p><table:table><table:table-row table:number-rows-repeated="10000"><table:table-cell table:number-columns-repeated="512"><text:p>${" ".repeat(10_000)}</text:p></table:table-cell></table:table-row></table:table><text:p>Unneeded</text:p></office:document>`,
857 },
858 expected: ["Before whitespace", "Unneeded"],
859 absent: ["[Extracted text truncated"],
860 },
861 ...["odt", "odp", "ods"].flatMap((ext) =>
862 [false, true].map((rows) => ({
863 ext,
864 bounded: true,
865 parts: {
866 "content.xml": `<office:document><draw:page>${Array.from(
867 { length: 256 },
868 () =>
869 `<table:table><table:table-row${rows ? ' table:number-rows-repeated="10000"' : ""}><table:table-cell table:number-columns-repeated="512"><text:p>${"Budget ".repeat(rows ? 160 : 585)}</text:p></table:table-cell></table:table-row></table:table>`,
870 ).join(
871 "",
872 )}</draw:page><draw:page><text:p>Unneeded</text:p></draw:page></office:document>`,
873 },
874 expected: ["Budget ", "[Extracted text truncated at document extraction limits.]"],
875 absent: ["Unneeded"],
876 })),
877 ),
878 {
879 ext: "docx",
880 bounded: true,
881 parts: {
882 "word/document.xml": `<w:document><w:p><w:t>${"A".repeat(1_000_100)}</w:t></w:p><w:p><w:t>Unneeded</w:t></w:p></w:document>`,
883 },
884 expected: ["A".repeat(32), "[Extracted text truncated at document extraction limits.]"],
885 absent: ["Unneeded"],
886 },
887 {
888 ext: "pptx",
889 bounded: true,
890 parts: {
891 "ppt/presentation.xml":
892 '<p:presentation><p:sldId r:id="a"/><p:sldId r:id="missing"/></p:presentation>',
893 "ppt/_rels/presentation.xml.rels":
894 '<Relationships><Relationship Id="a" Target="slides/slide.xml"/></Relationships>',
895 "ppt/slides/slide.xml": `<p:sld><a:p><a:t>${"A".repeat(1_000_100)}</a:t></a:p></p:sld>`,
896 },
897 expected: [
898 "## Slide 1",
899 "A".repeat(32),
900 "[Extracted text truncated at document extraction limits.]",
901 ],
902 absent: ["## Slide 2"],
903 },
904 {
905 ext: "epub",
906 bounded: true,
907 parts: {
908 "META-INF/container.xml": '<container><rootfile full-path="book.opf"/></container>',
909 "book.opf":
910 '<package><item id="a" href="a.xhtml"/><itemref idref="a"/><itemref idref="missing"/></package>',
911 "a.xhtml": `<html><body><p>${"A".repeat(1_000_100)}</p></body></html>`,
912 },
913 expected: [
914 "## Chapter 1",
915 "A".repeat(32),
916 "[Extracted text truncated at document extraction limits.]",
917 ],
918 absent: ["## Chapter 2"],
919 },
920 {
921 ext: "epub",
922 parts: {
923 "META-INF/container.xml":
924 '<container><rootfile full-path="OEBPS/book.opf"/></container>',
925 "OEBPS/book.opf":
926 '<package><manifest><item id="a" href="a.xhtml"/><item id="b" href="b.xhtml"/></manifest><spine><itemref idref="b"/><itemref idref="a"/></spine></package>',
927 "OEBPS/a.xhtml":
928 '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html><body><p>Last chapter</p><p>Price <s>10</s> 8</p></body></html>',
929 "OEBPS/b.xhtml":
930 "<!DOCTYPE html><html><body><h1>First chapter</h1><p>Larkspur</p><div>Direct div<section>Direct section<li>Direct item <em>emphasis</em> trailing</li></section></div><div>Account: A<br/>Balance: 731<line-break/>Currency: USD</div><table><thead><tr><th>Heading</th><th>Total</th></tr></thead><tbody><tr><td>Important value</td><td>731</td></tr><tr><td>Before<table><tr><td>Inner</td></tr></table>After</td><td>Neighbor</td></tr></tbody></table></body></html>",
931 },
932 expected: [
933 "## Chapter 1",
934 "# First chapter",
935 "Larkspur",
936 "Direct div",
937 "Direct section",
938 "Direct item emphasis trailing",
939 "Account: A\nBalance: 731\nCurrency: USD",
940 "Heading\tTotal",
941 "Important value\t731",
942 "Before Inner After\tNeighbor",
943 "## Chapter 2",
944 "Last chapter",
945 "Price 10 8",
946 ],
947 },
948 ];
949 for (const [caseIndex, item] of cases.entries()) {
950 const local: Buffer[] = [];
951 const central: Buffer[] = [];
952 let offset = 0;
953 for (const [name, content] of Object.entries(item.parts)) {
954 const data = Buffer.from(content!);
955 const compressed = /\.(bmp|bin)$/.test(name) ? NodeZlib.deflateRawSync(data) : data;
956 const filename = Buffer.from(name);
957 const header = Buffer.alloc(30);
958 header.writeUInt32LE(0x04034b50);
959 header.writeUInt16LE(20, 4);
960 header.writeUInt16LE(compressed === data ? 0 : 8, 8);
961 header.writeUInt32LE(NodeZlib.crc32(data), 14);
962 header.writeUInt32LE(compressed.length, 18);
963 header.writeUInt32LE(data.length, 22);
964 header.writeUInt16LE(filename.length, 26);
965 const directory = Buffer.alloc(46);
966 directory.writeUInt32LE(0x02014b50);
967 directory.writeUInt16LE(20, 4);
968 directory.writeUInt16LE(20, 6);
969 directory.writeUInt16LE(compressed === data ? 0 : 8, 10);
970 directory.writeUInt32LE(NodeZlib.crc32(data), 16);
971 directory.writeUInt32LE(compressed.length, 20);
972 directory.writeUInt32LE(data.length, 24);
973 directory.writeUInt16LE(filename.length, 28);
974 directory.writeUInt32LE(offset, 42);
975 local.push(header, filename, compressed);
976 central.push(directory, filename);
977 offset += header.length + filename.length + compressed.length;
978 }
979 const end = Buffer.alloc(22);
980 end.writeUInt32LE(0x06054b50);
981 end.writeUInt16LE(central.length / 2, 8);
982 end.writeUInt16LE(central.length / 2, 10);
983 end.writeUInt32LE(Buffer.concat(central).length, 12);
984 end.writeUInt32LE(offset, 16);
985 const path = NodePath.join(config.attachmentsDir, `structure-${caseIndex}.${item.ext}`);
986 NodeFS.writeFileSync(path, Buffer.concat([...local, ...central, end]));
987 const extracted = yield* Effect.promise(() => extractDocumentText(path, `.${item.ext}`));
988 let previous = -1;
989 for (const expected of item.expected) {
990 const index = extracted.indexOf(expected);
991 expect(index, `${item.ext}: ${expected} in ${extracted.slice(0, 500)}`).toBeGreaterThan(
992 previous,
993 );
994 previous = index;
995 }
996 if ("occurrences" in item)
997 expect(extracted.split(item.occurrences.text).length - 1).toBe(item.occurrences.count);
998 if ("absent" in item)
999 for (const absent of item.absent) expect(extracted).not.toContain(absent);
1000 if (("bounded" in item && item.bounded) || item.ext === "epub") {
1001 expect(extracted.length).toBeLessThan(1_000_100);
1002 expect(extracted.match(/\[Extracted text truncated/g)?.length ?? 0).toBeLessThanOrEqual(
1003 1,
1004 );
1005 const documents = yield* DocumentText.DocumentText;
1006 expect(yield* documents.ensure(path)).toBe(path + ".txt");
1007 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe(extracted);
1009 if (item.ext === "docx") {
1010 end.writeUInt16LE(2049, 8);
1011 end.writeUInt16LE(2049, 10);
1012 NodeFS.writeFileSync(path, Buffer.concat([...local, ...central, end]));
1013 yield* Effect.promise(async () => {
1014 expect(await extractDocumentText(path, ".docx")).toContain("[Extracted text truncated");
1015 });
1016 end.writeUInt16LE(central.length / 2, 8);
1017 end.writeUInt16LE(central.length / 2, 10);
1018 central[0]!.writeUInt16LE(8, 10);
1019 central[0]!.writeUInt32LE(33 * 1024 * 1024, 24);
1020 NodeFS.writeFileSync(path, Buffer.concat([...local, ...central, end]));
1021 yield* Effect.promise(async () => {
1022 expect(await extractDocumentText(path, ".docx")).toContain("[Extracted text truncated");
1023 });
1026 const path = NodePath.join(config.attachmentsDir, "unicode.rtf");
1027 NodeFS.writeFileSync(
1028 path,
1029 String.raw`{\rtf1\ansi{\fonttbl hidden}Hello\tab world\par Unicode \u945?{\*\secret hidden}}`,
1030 );
1031 const extracted = yield* Effect.promise(() => extractDocumentText(path, ".rtf"));
1032 expect(extracted).toContain("Hello\tworld\nUnicode α");
1033 expect(extracted).not.toContain("hidden");
1034​
1035 for (const [name, content, expected] of [
1037 "cyrillic-escaped",
1038 String.raw`{\rtf1\ansi\ansicpg1251 \'cf\'f0\'e8\'e2\'e5\'f2 {\ansicpg1252 \'e9} \'cc\'ee\'f1\'ea\'e2\'e0}`,
1039 "Привет é Москва",
1040 ],
1042 "cyrillic-raw",
1043 Buffer.concat([
1044 Buffer.from(String.raw`{\rtf1\ansi\ansicpg1251 `),
1045 Buffer.from([0xcf, 0xf0, 0xe8, 0xe2, 0xe5, 0xf2]),
1046 Buffer.from("}"),
1047 ]),
1048 "Привет",
1049 ],
1050 ] as const) {
1051 const encodedPath = NodePath.join(config.attachmentsDir, `${name}.rtf`);
1052 NodeFS.writeFileSync(encodedPath, content);
1053 expect(yield* Effect.promise(() => extractDocumentText(encodedPath, ".rtf"))).toBe(
1054 expected,
1055 );
1056 const documents = yield* DocumentText.DocumentText;
1057 expect(yield* documents.ensure(encodedPath)).toBe(encodedPath + ".txt");
1058 expect(NodeFS.readFileSync(encodedPath + ".txt", "utf8")).toBe(expected);
1060 const notebookPath = NodePath.join(config.attachmentsDir, "limited.ipynb");
1061 NodeFS.writeFileSync(
1062 notebookPath,
1063 JSON.stringify({ cells: Array.from({ length: 10_001 }, () => ({ source: "Kept" })) }),
1064 );
1065 const notebookLimited = yield* Effect.promise(() =>
1066 extractDocumentText(notebookPath, ".ipynb"),
1067 );
1068 expect(notebookLimited).toContain("## Cell 10000");
1069 expect(notebookLimited).not.toContain("## Cell 10001");
1070 expect(notebookLimited.match(/\[Extracted text truncated/g)).toHaveLength(1);
1071 expect(yield* (yield* DocumentText.DocumentText).ensure(notebookPath)).toBe(
1072 notebookPath + ".txt",
1073 );
1074 expect(NodeFS.readFileSync(notebookPath + ".txt", "utf8")).toBe(notebookLimited);
1075 const errorPath = NodePath.join(config.attachmentsDir, "limited-error.ipynb");
1076 NodeFS.writeFileSync(
1077 errorPath,
1078 JSON.stringify({
1079 cells: [
1081 cell_type: "code",
1082 source: "1 / 0",
1083 outputs: [
1085 output_type: "error",
1086 ename: "ZeroDivisionError",
1087 evalue: "division by zero",
1088 traceback: ["\u001b[31m" + "trace".repeat(250_000) + "\u001b[0m", "After limit"],
1089 },
1090 ],
1091 },
1092 ],
1093 }),
1094 );
1095 const errorLimited = yield* Effect.promise(() => extractDocumentText(errorPath, ".ipynb"));
1096 expect(errorLimited).toContain("ZeroDivisionError: division by zero\ntrace");
1097 expect(errorLimited.length).toBeLessThan(1_000_100);
1098 expect(errorLimited.match(/\[Extracted text truncated/g)).toHaveLength(1);
1099 expect(errorLimited).not.toContain("After limit");
1100 expect(errorLimited).not.toContain("\u001b");
1101 const deepPath = NodePath.join(config.attachmentsDir, "deep.rtf");
1102 NodeFS.writeFileSync(
1103 deepPath,
1104 String.raw`{\rtf1 Kept` + "{".repeat(128) + "Lost" + "}".repeat(129),
1105 );
1106 const deepLimited = yield* Effect.promise(() => extractDocumentText(deepPath, ".rtf"));
1107 expect(deepLimited).toBe("Kept\n\n[Extracted text truncated at document extraction limits.]");
1108 const unsupportedPath = NodePath.join(config.attachmentsDir, "unsupported-codepage.rtf");
1109 NodeFS.writeFileSync(unsupportedPath, String.raw`{\rtf1\ansi\ansicpg932 \'82\'a0}`);
1110 yield* Effect.promise(async () => {
1111 await expect(extractDocumentText(unsupportedPath, ".rtf")).rejects.toThrow(
1112 "Unsupported RTF code page",
1113 );
1114 });
1115 expect(yield* (yield* DocumentText.DocumentText).ensure(unsupportedPath)).toBeUndefined();
1116 expect(NodeFS.existsSync(unsupportedPath + ".txt")).toBe(false);
1117 NodeFS.writeFileSync(path, String.raw`{\rtf1 ` + "x".repeat(1_000_100) + "}");
1118 expect(yield* Effect.promise(() => extractDocumentText(path, ".rtf"))).toContain(
1119 "[Extracted text truncated",
1120 );
1121 NodeFS.writeFileSync(path, String.raw`{\rtf1 First` + " ".repeat(1_000_100) + "Last}");
1122 const whitespaceTruncated = yield* Effect.promise(() => extractDocumentText(path, ".rtf"));
1123 expect(whitespaceTruncated).toBe(
1124 "First\n\n[Extracted text truncated at document extraction limits.]",
1125 );
1126 const documents = yield* DocumentText.DocumentText;
1127 expect(yield* documents.ensure(path)).toBe(path + ".txt");
1128 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe(whitespaceTruncated);
1129 NodeFS.truncateSync(path, 17 * 1024 * 1024);
1130 yield* Effect.promise(async () => {
1131 expect(await extractDocumentText(path, ".rtf")).toContain("[Extracted text truncated");
1132 });
1133 }).pipe(Effect.provide(layer)),
1134 );
1135 it.effect("keeps selected values intact and appends an actual readable server path", () =>
1136 Effect.gen(function* () {
1137 const config = yield* ServerConfig.ServerConfig;
1138 const path = NodePath.join(config.attachmentsDir, `${attachment.id}.txt`);
1139 NodeFS.writeFileSync(path, "spec");
1140 const original = { q: ["First", "Second"], other: "No file" };
1141 const answers = yield* appendUserInputAttachmentPaths({
1142 answers: original,
1143 attachmentsDir: config.attachmentsDir,
1144 attachmentsByQuestionId: { q: [attachment] },
1145 });
1146 expect(answers.q).toEqual([
1147 "First",
1148 "Second",
1149 `Attached file "spec \\"final\\".txt": "${path}"`,
1150 ]);
1151 expect(answers.other).toBe("No file");
1152 expect(original.q).toEqual(["First", "Second"]);
1153 expect(NodeFS.readFileSync(path, "utf8")).toBe("spec");
1154 const specialKey = yield* appendUserInputAttachmentPaths({
1155 answers: {},
1156 attachmentsDir: config.attachmentsDir,
1157 attachmentsByQuestionId: { ["__proto__"]: [attachment] },
1158 });
1159 expect(Object.keys(specialKey)).toEqual(["__proto__"]);
1160 expect(specialKey["__proto__"]).toContain(path);
1161 }).pipe(Effect.provide(layer)),
1162 );
1163 it.effect("does not send an unavailable attachment path", () =>
1164 Effect.gen(function* () {
1165 const config = yield* ServerConfig.ServerConfig;
1166 const result = yield* appendUserInputAttachmentPaths({
1167 answers: { q: "" },
1168 attachmentsDir: config.attachmentsDir,
1169 attachmentsByQuestionId: { q: [attachment] },
1170 }).pipe(Effect.result);
1171 expect(result._tag).toBe("Failure");
1172 }).pipe(Effect.provide(layer)),
1173 );
1174});