Open History to see the last commit
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 Harbor ≂̸ ∳ & <tag> "quoted"</p><p><![CDATA[Literal ]]></p><table><tr><td> </td></tr><tr><td>Kept cell</td></tr></table></html>',
512 },
513 expected: [
514 "## Chapter 2",
515 'North\u00a0Harbor ≂̸ ∳ & <tag> "quoted"',
516 "Literal ",
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"><w:body><w:p><w:pPr><w:pStyle w:val="Heading2"/></w:pPr><w:r><w:t>Report & 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>',
563 },
564 expected: ["## Report & totals", "North\t12 34", "Before Inner After\tNeighbor"],
565 },
566 {
567 ext: "docx",
568 bounded: true,
569 parts: {
570 "word/document.xml":
571 '<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>',
572 },
573 expected: ["First\nSecond\nThird"],
574 },
575 {
576 ext: "docx",
577 bounded: true,
578 parts: {
579 "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>`,
580 },
581 expected: ["A".repeat(32), "[Extracted text truncated at document extraction limits.]"],
582 },
583 {
584 ext: "xlsx",
585 bounded: true,
586 parts: {
587 "xl/workbook.xml": '<workbook><sheet name="Formulas" r:id="a"/></workbook>',
588 "xl/_rels/workbook.xml.rels":
589 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
590 "xl/styles.xml": '<styleSheet><cellXfs><xf numFmtId="9"/></cellXfs></styleSheet>',
591 "xl/worksheets/a.xml":
592 "<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>",
593 },
594 expected: [
595 "SUM(11,22)\nSUM(33,44)\nSUM(55,66)",
596 "33 [Excel numFmtId=9; date system 1900]\t0 [Excel numFmtId=9; date system 1900]",
597 ],
598 absent: ["SUM(0,0)", "[Extracted text truncated"],
599 },
600 {
601 ext: "xlsx",
602 parts: {
603 "xl/workbook.xml":
604 '<workbook><sheets><sheet name="Inventory" r:id="a"/><sheet name="Budget" r:id="b"/></sheets></workbook>',
605 "xl/_rels/workbook.xml.rels":
606 '<Relationships><Relationship Id="a" Target="worksheets/second.xml"/><Relationship Id="b" Target="worksheets/first.xml"/></Relationships>',
607 "xl/sharedStrings.xml": "<sst><si><t>Lantern</t></si></sst>",
608 "xl/styles.xml":
609 '<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>',
610 "xl/worksheets/second.xml":
611 '<worksheet><sheetData><row><c r="A1" t="s"><v>0</v></c><c r="C1"><v>37</v></c></row></sheetData></worksheet>',
612 "xl/worksheets/first.xml":
613 '<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>',
614 },
615 expected: [
616 "## Sheet: Inventory",
617 "Lantern\t\t37",
618 "## Sheet: Budget",
619 "Ferry\t628",
620 "45292 [Excel numFmtId=14; date system 1900]",
621 "0.25 [Excel numFmtId=9; date system 1900]",
622 "45293 [Excel numFmtId=164; format=yyyy-mm-dd; date system 1900]",
623 ],
624 },
625 {
626 ext: "xlsx",
627 bounded: true,
628 parts: {
629 "xl/workbook.xml": '<workbook><sheet name="Phonetics" r:id="a"/></workbook>',
630 "xl/_rels/workbook.xml.rels":
631 '<Relationships><Relationship Id="a" Target="worksheets/a.xml"/></Relationships>',
632 "xl/sharedStrings.xml":
633 '<sst><si><t>東京</t><rPh sb="0" eb="2"><t>とうきょう</t></rPh></si></sst>',
634 "xl/worksheets/a.xml":
635 '<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>',
636 },
637 expected: ["## Sheet: Phonetics", "東京\t東京"],
638 absent: ["とうきょう"],
639 },
640 {
641 ext: "xlsx",
642 bounded: true,
643 parts: {
644 "xl/workbook.xml":
645 '<workbook><workbookPr date1904="true"/><sheets><sheet name="Dates" r:id="a"/></sheets></workbook>',
646 "xl/_rels/workbook.xml.rels":
647 '<Relationships><Relationship Id="a" Target="worksheets/dates.xml"/></Relationships>',
648 "xl/styles.xml": '<styleSheet><cellXfs><xf numFmtId="14"/></cellXfs></styleSheet>',
649 "xl/worksheets/dates.xml":
650 "<worksheet><sheetData><row><c><v>1</v></c></row></sheetData></worksheet>",
651 },
652 expected: ["## Sheet: Dates", "1 [Excel numFmtId=14; date system 1904]"],
653 },
654 {
655 ext: "xlsx",
656 bounded: true,
657 parts: {
658 "xl/workbook.xml":
659 '<workbook><sheets><sheet name="Repeated" r:id="a"/><sheet name="Unneeded" r:id="missing"/></sheets></workbook>',
660 "xl/_rels/workbook.xml.rels":
661 '<Relationships><Relationship Id="a" Target="worksheets/repeated.xml"/></Relationships>',
662 "xl/sharedStrings.xml": `<sst><si><t>${"A".repeat(1_000_000 - "## Sheet: Repeated\n".length)}</t></si></sst>`,
663 "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>`,
664 },
665 expected: [
666 "## Sheet: Repeated",
667 "A".repeat(32),
668 "[Extracted text truncated at document extraction limits.]",
669 ],
670 },
671 {
672 ext: "pptx",
673 bounded: true,
674 parts: {
675 "ppt/presentation.xml":
676 '<p:presentation><p:sldIdLst><p:sldId id="1" r:id="b"/><p:sldId id="2" r:id="a"/></p:sldIdLst></p:presentation>',
677 "ppt/_rels/presentation.xml.rels":
678 '<Relationships><Relationship Id="a" Target="slides/slide1.xml"/><Relationship Id="b" Target="slides/slide2.xml"/></Relationships>',
679 "ppt/slides/slide1.xml": "<p:sld><a:p><a:r><a:t>Departure</a:t></a:r></a:p></p:sld>",
680 "ppt/slides/slide2.xml": "<p:sld><a:p><a:r><a:t>Juniper Pier</a:t></a:r></a:p></p:sld>",
681 "ppt/slides/_rels/slide2.xml.rels":
682 '<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>',
683 "ppt/slides/_rels/slide1.xml.rels":
684 '<Relationships><Relationship Type="http://purl.oclc.org/ooxml/officeDocument/relationships/notesSlide" Target="/ppt/notesSlides/notes3.xml"/></Relationships>',
685 "ppt/notesSlides/notes7.xml":
686 "<p:notes><a:p><a:r><a:t>evacuation code ORCHID-81</a:t></a:r></a:p></p:notes>",
687 "ppt/notesSlides/notes3.xml":
688 "<p:notes><a:p><a:r><a:t>Board at gate 4</a:t></a:r></a:p></p:notes>",
689 "ppt/notesSlides/ignored.xml": "<p:notes><a:p>Unrelated notes</a:p></p:notes>",
690 },
691 expected: [
692 "## Slide 1",
693 "Juniper Pier\nNotes:\nevacuation code ORCHID-81",
694 "## Slide 2",
695 "Departure\nNotes:\nBoard at gate 4",
696 ],
697 absent: ["Unrelated notes", "[Skipped document part", "[Extracted text truncated"],
698 },
699 ...[false, true].map((missing) => ({
700 ext: "pptx",
701 bounded: true,
702 parts: {
703 "ppt/presentation.xml": '<presentation><sldId r:id="a"/></presentation>',
704 "ppt/_rels/presentation.xml.rels":
705 '<Relationships><Relationship Id="a" Target="slides/a.xml"/></Relationships>',
706 "ppt/slides/a.xml": "<slide><p>Slide text</p></slide>",
707 "ppt/slides/_rels/a.xml.rels": `<Relationships><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/${missing ? "missing" : "bad"}.xml"/></Relationships>`,
708 "ppt/notesSlides/bad.xml": "<notes><p>Discard broken notes</notes>",
709 },
710 expected: [
711 "Slide text",
712 `[Skipped document part: ppt/notesSlides/${missing ? "missing" : "bad"}.xml (missing or invalid XML).]`,
713 ],
714 absent: ["Discard broken notes", "[Extracted text truncated"],
715 })),
716 {
717 ext: "pptx",
718 bounded: true,
719 parts: {
720 "ppt/presentation.xml":
721 '<presentation><sldId r:id="a"/><sldId r:id="b"/></presentation>',
722 "ppt/_rels/presentation.xml.rels":
723 '<Relationships><Relationship Id="a" Target="slides/a.xml"/><Relationship Id="b" Target="slides/b.xml"/></Relationships>',
724 "ppt/slides/a.xml": `<slide><p>${"A".repeat(600_000)}</p></slide>`,
725 "ppt/slides/b.xml": "<slide><p>Unneeded slide</p></slide>",
726 "ppt/slides/_rels/a.xml.rels":
727 '<Relationships><Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="../notesSlides/a.xml"/></Relationships>',
728 "ppt/notesSlides/a.xml": `<notes><p>evacuation code ORCHID-81 ${"B".repeat(600_000)} Unneeded notes</p></notes>`,
729 },
730 expected: [
731 "## Slide 1",
732 "A".repeat(32),
733 "Notes:\nevacuation code ORCHID-81",
734 "B".repeat(32),
735 "[Extracted text truncated at document extraction limits.]",
736 ],
737 absent: ["Unneeded notes", "Unneeded slide", "## Slide 2"],
738 },
739 {
740 ext: "odt",
741 parts: {
742 "content.xml":
743 '<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>',
744 },
745 expected: ["## Orchard", "19 violet crates"],
746 },
747 {
748 ext: "ods",
749 parts: {
750 "content.xml":
751 '<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>',
752 },
753 expected: ["## Sheet: Cargo", "Violet\t19\t27"],
754 },
755 {
756 ext: "ods",
757 bounded: true,
758 parts: {
759 "content.xml":
760 '<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>',
761 },
762 expected: ["## Sheet: Padded rows", "Left\t\t\tRight"],
763 absent: ["[Extracted text truncated"],
764 },
765 {
766 ext: "ods",
767 bounded: true,
768 parts: {
769 "content.xml":
770 '<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>',
771 },
772 expected: ["## Sheet: Padded", "Populated"],
773 absent: ["[Extracted text truncated", "\t"],
774 },
775 {
776 ext: "ods",
777 bounded: true,
778 parts: {
779 "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>`,
780 },
781 expected: [
782 "## Sheet: Repeated",
783 "Lead ",
784 " Tail\tLead ",
785 "[Extracted text truncated at document extraction limits.]",
786 ],
787 },
788 {
789 ext: "odp",
790 parts: {
791 "content.xml":
792 "<office:document><draw:page><text:p>First</text:p></draw:page><draw:page><text:p>Second</text:p></draw:page></office:document>",
793 },
794 expected: ["## Slide 1", "First", "## Slide 2", "Second"],
795 },
796 {
797 ext: "ods",
798 bounded: true,
799 parts: {
800 "content.xml": `<office:document>${Array.from(
801 { length: 256 },
802 (_, index) =>
803 `<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>`,
804 ).join("")}</office:document>`,
805 },
806 expected: [
807 "## Sheet: Shared",
808 "B".repeat(32),
809 "[Extracted text truncated at document extraction limits.]",
810 ],
811 absent: ["## Sheet: Unneeded"],
812 },
813 {
814 ext: "odt",
815 bounded: true,
816 parts: {
817 "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>`,
818 },
819 expected: ["Before whitespace", "Unneeded"],
820 absent: ["[Extracted text truncated"],
821 },
822 ...["odt", "odp", "ods"].flatMap((ext) =>
823 [false, true].map((rows) => ({
824 ext,
825 bounded: true,
826 parts: {
827 "content.xml": `<office:document><draw:page>${Array.from(
828 { length: 256 },
829 () =>
830 `<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>`,
831 ).join(
832 "",
833 )}</draw:page><draw:page><text:p>Unneeded</text:p></draw:page></office:document>`,
834 },
835 expected: ["Budget ", "[Extracted text truncated at document extraction limits.]"],
836 absent: ["Unneeded"],
837 })),
838 ),
839 {
840 ext: "docx",
841 bounded: true,
842 parts: {
843 "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>`,
844 },
845 expected: ["A".repeat(32), "[Extracted text truncated at document extraction limits.]"],
846 absent: ["Unneeded"],
847 },
848 {
849 ext: "pptx",
850 bounded: true,
851 parts: {
852 "ppt/presentation.xml":
853 '<p:presentation><p:sldId r:id="a"/><p:sldId r:id="missing"/></p:presentation>',
854 "ppt/_rels/presentation.xml.rels":
855 '<Relationships><Relationship Id="a" Target="slides/slide.xml"/></Relationships>',
856 "ppt/slides/slide.xml": `<p:sld><a:p><a:t>${"A".repeat(1_000_100)}</a:t></a:p></p:sld>`,
857 },
858 expected: [
859 "## Slide 1",
860 "A".repeat(32),
861 "[Extracted text truncated at document extraction limits.]",
862 ],
863 absent: ["## Slide 2"],
864 },
865 {
866 ext: "epub",
867 bounded: true,
868 parts: {
869 "META-INF/container.xml": '<container><rootfile full-path="book.opf"/></container>',
870 "book.opf":
871 '<package><item id="a" href="a.xhtml"/><itemref idref="a"/><itemref idref="missing"/></package>',
872 "a.xhtml": `<html><body><p>${"A".repeat(1_000_100)}</p></body></html>`,
873 },
874 expected: [
875 "## Chapter 1",
876 "A".repeat(32),
877 "[Extracted text truncated at document extraction limits.]",
878 ],
879 absent: ["## Chapter 2"],
880 },
881 {
882 ext: "epub",
883 parts: {
884 "META-INF/container.xml":
885 '<container><rootfile full-path="OEBPS/book.opf"/></container>',
886 "OEBPS/book.opf":
887 '<package><manifest><item id="a" href="a.xhtml"/><item id="b" href="b.xhtml"/></manifest><spine><itemref idref="b"/><itemref idref="a"/></spine></package>',
888 "OEBPS/a.xhtml":
889 '<!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>',
890 "OEBPS/b.xhtml":
891 "<!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>",
892 },
893 expected: [
894 "## Chapter 1",
895 "# First chapter",
896 "Larkspur",
897 "Direct div",
898 "Direct section",
899 "Direct item emphasis trailing",
900 "Account: A\nBalance: 731\nCurrency: USD",
901 "Heading\tTotal",
902 "Important value\t731",
903 "Before Inner After\tNeighbor",
904 "## Chapter 2",
905 "Last chapter",
906 "Price 10 8",
907 ],
908 },
909 ];
910 for (const [caseIndex, item] of cases.entries()) {
911 const local: Buffer[] = [];
912 const central: Buffer[] = [];
913 let offset = 0;
914 for (const [name, content] of Object.entries(item.parts)) {
915 const data = Buffer.from(content!);
916 const compressed = /\.(bmp|bin)$/.test(name) ? NodeZlib.deflateRawSync(data) : data;
917 const filename = Buffer.from(name);
918 const header = Buffer.alloc(30);
919 header.writeUInt32LE(0x04034b50);
920 header.writeUInt16LE(20, 4);
921 header.writeUInt16LE(compressed === data ? 0 : 8, 8);
922 header.writeUInt32LE(NodeZlib.crc32(data), 14);
923 header.writeUInt32LE(compressed.length, 18);
924 header.writeUInt32LE(data.length, 22);
925 header.writeUInt16LE(filename.length, 26);
926 const directory = Buffer.alloc(46);
927 directory.writeUInt32LE(0x02014b50);
928 directory.writeUInt16LE(20, 4);
929 directory.writeUInt16LE(20, 6);
930 directory.writeUInt16LE(compressed === data ? 0 : 8, 10);
931 directory.writeUInt32LE(NodeZlib.crc32(data), 16);
932 directory.writeUInt32LE(compressed.length, 20);
933 directory.writeUInt32LE(data.length, 24);
934 directory.writeUInt16LE(filename.length, 28);
935 directory.writeUInt32LE(offset, 42);
936 local.push(header, filename, compressed);
937 central.push(directory, filename);
938 offset += header.length + filename.length + compressed.length;
939 }
940 const end = Buffer.alloc(22);
941 end.writeUInt32LE(0x06054b50);
942 end.writeUInt16LE(central.length / 2, 8);
943 end.writeUInt16LE(central.length / 2, 10);
944 end.writeUInt32LE(Buffer.concat(central).length, 12);
945 end.writeUInt32LE(offset, 16);
946 const path = NodePath.join(config.attachmentsDir, `structure-${caseIndex}.${item.ext}`);
947 NodeFS.writeFileSync(path, Buffer.concat([...local, ...central, end]));
948 const extracted = yield* Effect.promise(() => extractDocumentText(path, `.${item.ext}`));
949 let previous = -1;
950 for (const expected of item.expected) {
951 const index = extracted.indexOf(expected);
952 expect(index, `${item.ext}: ${expected} in ${extracted.slice(0, 500)}`).toBeGreaterThan(
953 previous,
954 );
955 previous = index;
956 }
957 if ("occurrences" in item)
958 expect(extracted.split(item.occurrences.text).length - 1).toBe(item.occurrences.count);
959 if ("absent" in item)
960 for (const absent of item.absent) expect(extracted).not.toContain(absent);
961 if (("bounded" in item && item.bounded) || item.ext === "epub") {
962 expect(extracted.length).toBeLessThan(1_000_100);
963 expect(extracted.match(/\[Extracted text truncated/g)?.length ?? 0).toBeLessThanOrEqual(
964 1,
965 );
966 const documents = yield* DocumentText.DocumentText;
967 expect(yield* documents.ensure(path)).toBe(path + ".txt");
968 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe(extracted);
969 }
970 if (item.ext === "docx") {
971 end.writeUInt16LE(2049, 8);
972 end.writeUInt16LE(2049, 10);
973 NodeFS.writeFileSync(path, Buffer.concat([...local, ...central, end]));
974 yield* Effect.promise(async () => {
975 expect(await extractDocumentText(path, ".docx")).toContain("[Extracted text truncated");
976 });
977 end.writeUInt16LE(central.length / 2, 8);
978 end.writeUInt16LE(central.length / 2, 10);
979 central[0]!.writeUInt16LE(8, 10);
980 central[0]!.writeUInt32LE(33 * 1024 * 1024, 24);
981 NodeFS.writeFileSync(path, Buffer.concat([...local, ...central, end]));
982 yield* Effect.promise(async () => {
983 expect(await extractDocumentText(path, ".docx")).toContain("[Extracted text truncated");
984 });
985 }
986 }
987 const path = NodePath.join(config.attachmentsDir, "unicode.rtf");
988 NodeFS.writeFileSync(
989 path,
990 String.raw`{\rtf1\ansi{\fonttbl hidden}Hello\tab world\par Unicode \u945?{\*\secret hidden}}`,
991 );
992 const extracted = yield* Effect.promise(() => extractDocumentText(path, ".rtf"));
993 expect(extracted).toContain("Hello\tworld\nUnicode α");
994 expect(extracted).not.toContain("hidden");
995
996 for (const [name, content, expected] of [
997 [
998 "cyrillic-escaped",
999 String.raw`{\rtf1\ansi\ansicpg1251 \'cf\'f0\'e8\'e2\'e5\'f2 {\ansicpg1252 \'e9} \'cc\'ee\'f1\'ea\'e2\'e0}`,
1000 "Привет é Москва",
1001 ],
1002 [
1003 "cyrillic-raw",
1004 Buffer.concat([
1005 Buffer.from(String.raw`{\rtf1\ansi\ansicpg1251 `),
1006 Buffer.from([0xcf, 0xf0, 0xe8, 0xe2, 0xe5, 0xf2]),
1007 Buffer.from("}"),
1008 ]),
1009 "Привет",
1010 ],
1011 ] as const) {
1012 const encodedPath = NodePath.join(config.attachmentsDir, `${name}.rtf`);
1013 NodeFS.writeFileSync(encodedPath, content);
1014 expect(yield* Effect.promise(() => extractDocumentText(encodedPath, ".rtf"))).toBe(
1015 expected,
1016 );
1017 const documents = yield* DocumentText.DocumentText;
1018 expect(yield* documents.ensure(encodedPath)).toBe(encodedPath + ".txt");
1019 expect(NodeFS.readFileSync(encodedPath + ".txt", "utf8")).toBe(expected);
1020 }
1021 const notebookPath = NodePath.join(config.attachmentsDir, "limited.ipynb");
1022 NodeFS.writeFileSync(
1023 notebookPath,
1024 JSON.stringify({ cells: Array.from({ length: 10_001 }, () => ({ source: "Kept" })) }),
1025 );
1026 const notebookLimited = yield* Effect.promise(() =>
1027 extractDocumentText(notebookPath, ".ipynb"),
1028 );
1029 expect(notebookLimited).toContain("## Cell 10000");
1030 expect(notebookLimited).not.toContain("## Cell 10001");
1031 expect(notebookLimited.match(/\[Extracted text truncated/g)).toHaveLength(1);
1032 expect(yield* (yield* DocumentText.DocumentText).ensure(notebookPath)).toBe(
1033 notebookPath + ".txt",
1034 );
1035 expect(NodeFS.readFileSync(notebookPath + ".txt", "utf8")).toBe(notebookLimited);
1036 const errorPath = NodePath.join(config.attachmentsDir, "limited-error.ipynb");
1037 NodeFS.writeFileSync(
1038 errorPath,
1039 JSON.stringify({
1040 cells: [
1041 {
1042 cell_type: "code",
1043 source: "1 / 0",
1044 outputs: [
1045 {
1046 output_type: "error",
1047 ename: "ZeroDivisionError",
1048 evalue: "division by zero",
1049 traceback: ["\u001b[31m" + "trace".repeat(250_000) + "\u001b[0m", "After limit"],
1050 },
1051 ],
1052 },
1053 ],
1054 }),
1055 );
1056 const errorLimited = yield* Effect.promise(() => extractDocumentText(errorPath, ".ipynb"));
1057 expect(errorLimited).toContain("ZeroDivisionError: division by zero\ntrace");
1058 expect(errorLimited.length).toBeLessThan(1_000_100);
1059 expect(errorLimited.match(/\[Extracted text truncated/g)).toHaveLength(1);
1060 expect(errorLimited).not.toContain("After limit");
1061 expect(errorLimited).not.toContain("\u001b");
1062 const deepPath = NodePath.join(config.attachmentsDir, "deep.rtf");
1063 NodeFS.writeFileSync(
1064 deepPath,
1065 String.raw`{\rtf1 Kept` + "{".repeat(128) + "Lost" + "}".repeat(129),
1066 );
1067 const deepLimited = yield* Effect.promise(() => extractDocumentText(deepPath, ".rtf"));
1068 expect(deepLimited).toBe("Kept\n\n[Extracted text truncated at document extraction limits.]");
1069 const unsupportedPath = NodePath.join(config.attachmentsDir, "unsupported-codepage.rtf");
1070 NodeFS.writeFileSync(unsupportedPath, String.raw`{\rtf1\ansi\ansicpg932 \'82\'a0}`);
1071 yield* Effect.promise(async () => {
1072 await expect(extractDocumentText(unsupportedPath, ".rtf")).rejects.toThrow(
1073 "Unsupported RTF code page",
1074 );
1075 });
1076 expect(yield* (yield* DocumentText.DocumentText).ensure(unsupportedPath)).toBeUndefined();
1077 expect(NodeFS.existsSync(unsupportedPath + ".txt")).toBe(false);
1078 NodeFS.writeFileSync(path, String.raw`{\rtf1 ` + "x".repeat(1_000_100) + "}");
1079 expect(yield* Effect.promise(() => extractDocumentText(path, ".rtf"))).toContain(
1080 "[Extracted text truncated",
1081 );
1082 NodeFS.writeFileSync(path, String.raw`{\rtf1 First` + " ".repeat(1_000_100) + "Last}");
1083 const whitespaceTruncated = yield* Effect.promise(() => extractDocumentText(path, ".rtf"));
1084 expect(whitespaceTruncated).toBe(
1085 "First\n\n[Extracted text truncated at document extraction limits.]",
1086 );
1087 const documents = yield* DocumentText.DocumentText;
1088 expect(yield* documents.ensure(path)).toBe(path + ".txt");
1089 expect(NodeFS.readFileSync(path + ".txt", "utf8")).toBe(whitespaceTruncated);
1090 NodeFS.truncateSync(path, 17 * 1024 * 1024);
1091 yield* Effect.promise(async () => {
1092 expect(await extractDocumentText(path, ".rtf")).toContain("[Extracted text truncated");
1093 });
1094 }).pipe(Effect.provide(layer)),
1095 );
1096 it.effect("keeps selected values intact and appends an actual readable server path", () =>
1097 Effect.gen(function* () {
1098 const config = yield* ServerConfig.ServerConfig;
1099 const path = NodePath.join(config.attachmentsDir, `${attachment.id}.txt`);
1100 NodeFS.writeFileSync(path, "spec");
1101 const original = { q: ["First", "Second"], other: "No file" };
1102 const answers = yield* appendUserInputAttachmentPaths({
1103 answers: original,
1104 attachmentsDir: config.attachmentsDir,
1105 attachmentsByQuestionId: { q: [attachment] },
1106 });
1107 expect(answers.q).toEqual([
1108 "First",
1109 "Second",
1110 `Attached file "spec \\"final\\".txt": "${path}"`,
1111 ]);
1112 expect(answers.other).toBe("No file");
1113 expect(original.q).toEqual(["First", "Second"]);
1114 expect(NodeFS.readFileSync(path, "utf8")).toBe("spec");
1115 const specialKey = yield* appendUserInputAttachmentPaths({
1116 answers: {},
1117 attachmentsDir: config.attachmentsDir,
1118 attachmentsByQuestionId: { ["__proto__"]: [attachment] },
1119 });
1120 expect(Object.keys(specialKey)).toEqual(["__proto__"]);
1121 expect(specialKey["__proto__"]).toContain(path);
1122 }).pipe(Effect.provide(layer)),
1123 );
1124 it.effect("does not send an unavailable attachment path", () =>
1125 Effect.gen(function* () {
1126 const config = yield* ServerConfig.ServerConfig;
1127 const result = yield* appendUserInputAttachmentPaths({
1128 answers: { q: "" },
1129 attachmentsDir: config.attachmentsDir,
1130 attachmentsByQuestionId: { q: [attachment] },
1131 }).pipe(Effect.result);
1132 expect(result._tag).toBe("Failure");
1133 }).pipe(Effect.provide(layer)),
1134 );
1135});