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

userInputAttachments.test.ts

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