llm-large-files 0.3.5 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/dist/cache.d.ts +40 -0
  3. package/dist/cache.d.ts.map +1 -0
  4. package/dist/cache.js +81 -0
  5. package/dist/cache.js.map +1 -0
  6. package/dist/extract.d.ts +1 -1
  7. package/dist/extract.d.ts.map +1 -1
  8. package/dist/extract.js +204 -22
  9. package/dist/extract.js.map +1 -1
  10. package/dist/index.d.ts +1 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +1 -1
  13. package/dist/index.js.map +1 -1
  14. package/dist/library.d.ts +28 -1
  15. package/dist/library.d.ts.map +1 -1
  16. package/dist/library.js +155 -47
  17. package/dist/library.js.map +1 -1
  18. package/dist/limiter.d.ts +20 -0
  19. package/dist/limiter.d.ts.map +1 -0
  20. package/dist/limiter.js +55 -0
  21. package/dist/limiter.js.map +1 -0
  22. package/dist/map-reduce.d.ts +8 -4
  23. package/dist/map-reduce.d.ts.map +1 -1
  24. package/dist/map-reduce.js +65 -24
  25. package/dist/map-reduce.js.map +1 -1
  26. package/dist/node/handlers.d.ts +9 -0
  27. package/dist/node/handlers.d.ts.map +1 -1
  28. package/dist/node/handlers.js +56 -13
  29. package/dist/node/handlers.js.map +1 -1
  30. package/dist/pdf-pictures.d.ts.map +1 -1
  31. package/dist/pdf-pictures.js +52 -9
  32. package/dist/pdf-pictures.js.map +1 -1
  33. package/dist/plan.d.ts +7 -5
  34. package/dist/plan.d.ts.map +1 -1
  35. package/dist/plan.js +9 -8
  36. package/dist/plan.js.map +1 -1
  37. package/dist/ranged.d.ts +102 -0
  38. package/dist/ranged.d.ts.map +1 -0
  39. package/dist/ranged.js +314 -0
  40. package/dist/ranged.js.map +1 -0
  41. package/dist/search.d.ts +79 -15
  42. package/dist/search.d.ts.map +1 -1
  43. package/dist/search.js +388 -130
  44. package/dist/search.js.map +1 -1
  45. package/dist/stores.d.ts +22 -2
  46. package/dist/stores.d.ts.map +1 -1
  47. package/dist/stores.js +132 -15
  48. package/dist/stores.js.map +1 -1
  49. package/dist/text-index.d.ts +64 -0
  50. package/dist/text-index.d.ts.map +1 -0
  51. package/dist/text-index.js +211 -0
  52. package/dist/text-index.js.map +1 -0
  53. package/dist/text.d.ts +2 -1
  54. package/dist/text.d.ts.map +1 -1
  55. package/dist/text.js +13 -4
  56. package/dist/text.js.map +1 -1
  57. package/dist/tools.d.ts +2 -2
  58. package/dist/tools.d.ts.map +1 -1
  59. package/dist/tools.js +20 -14
  60. package/dist/tools.js.map +1 -1
  61. package/dist/types.d.ts +15 -0
  62. package/dist/types.d.ts.map +1 -1
  63. package/docs/api.md +21 -5
  64. package/docs/configuration.md +50 -4
  65. package/docs/getting-started.md +3 -1
  66. package/docs/how-it-works.md +3 -1
  67. package/docs/security.md +8 -0
  68. package/package.json +7 -3
  69. package/src/cache.ts +83 -0
  70. package/src/extract.ts +198 -19
  71. package/src/index.ts +1 -1
  72. package/src/library.ts +176 -44
  73. package/src/limiter.ts +51 -0
  74. package/src/map-reduce.ts +70 -25
  75. package/src/node/handlers.ts +61 -9
  76. package/src/pdf-pictures.ts +60 -10
  77. package/src/plan.ts +10 -9
  78. package/src/ranged.ts +348 -0
  79. package/src/search.ts +432 -120
  80. package/src/stores.ts +136 -17
  81. package/src/text-index.ts +228 -0
  82. package/src/text.ts +13 -4
  83. package/src/tools.ts +22 -16
  84. package/src/types.ts +15 -0
package/docs/api.md CHANGED
@@ -19,7 +19,11 @@ Three entry points:
19
19
  | `ttlMs` | `number` | 72 hours |
20
20
  | `maxUploadBytes` | `number` | 100 MB |
21
21
  | `extractors` | `Partial<Record<DocumentFormat, Extractor>>` | built-ins |
22
- | `cacheSize` | `number` | 6 parsed documents in memory |
22
+ | `cacheBytes` | `number` | 256 MB: memory that documents kept ready between tool calls may take. Each use checks the store first. 0 keeps none |
23
+ | `cacheSize` | `number` | no limit: also caps the number of documents kept |
24
+ | `wholeDocumentBytes` | `number` | 2 MB: larger documents are read by range when the store can ([details](configuration.md#large-files-many-users-several-servers)). `Infinity` loads all whole |
25
+ | `scanChunkBytes` | `number` | 1 MB: text read and searched at a time, reading by range |
26
+ | `maxConcurrentScans` | `number` | 4: searches of a document read by range that run at once; the others wait |
23
27
  | `keepOriginals` | `DocumentFormat[]` | `[]`: only text is kept. `["pdf"]` keeps uploaded PDFs, which `view_pages` needs ([details](configuration.md#keeping-the-uploaded-file)) |
24
28
  | `scannedPdfPages` | `number` | 30: the longest PDF without any text that is accepted when its original is kept. 0 refuses them all |
25
29
 
@@ -77,10 +81,13 @@ carry page numbers: `page` on each matching line, `pages` on a passage and on a
77
81
  ### Stores
78
82
 
79
83
  - `new MemoryDocumentStore({ now? })`: in-process, for tests and single-instance demos.
80
- - `new FileDocumentStore(directory, { now? })`: `<id>.txt` and `<id>.json` per document, and
81
- `<id>.bin` for a kept original.
82
- - Implement `DocumentStore` (`put`, `get`, `getMeta`, `delete`, `sweep?`, and `putOriginal?` with
83
- `getOriginal?` to keep originals) for anything else.
84
+ - `new FileDocumentStore(directory, { now?, orphanAgeMs? })`: `<id>.txt`, `<id>.json` and the line
85
+ index `<id>.idx` per document, and `<id>.bin` for a kept original. Safe for several servers on one
86
+ volume: files are written whole, large documents are read by range, and `sweep` leaves files
87
+ younger than `orphanAgeMs` (1 hour) that belong to no document yet.
88
+ - Implement `DocumentStore` (`put`, `get`, `getMeta`, `delete`, `sweep?`, `putOriginal?` with
89
+ `getOriginal?` to keep originals, and `readTextRange?` with `putIndex?` and `getIndex?` to read
90
+ large documents by range) for anything else.
84
91
 
85
92
  ### Helpers
86
93
 
@@ -203,3 +210,12 @@ Returns `{ upload(req, res), get(req, res, id), remove(req, res, id) }`.
203
210
  (`express.raw()`), that buffer is used.
204
211
  - **get**: 200 with a `DocumentSummary`, or 404.
205
212
  - **remove**: `{ deleted: boolean }`.
213
+
214
+ Each handler answers its errors itself and never rejects, so it needs no `catch`. 422 is a file
215
+ that cannot be read. 500 is the server's trouble, such as a store that fails: the message says
216
+ what failed and gives a system error's code (`Upload failed (ENOSPC).`), never a path or a host.
217
+
218
+ `getOwner` runs before the upload is read. To refuse a request, throw an error with a `status`
219
+ (or `statusCode`) between 400 and 599, as the `http-errors` package makes:
220
+ `throw Object.assign(new Error("Sign in first."), { status: 401 })`. The handler answers with that
221
+ status and message. Any other error from `getOwner` is a 500 that does not repeat its message.
@@ -191,15 +191,57 @@ interface DocumentStore {
191
191
  put(document: { meta: DocumentMeta; text: string }): Promise<void>;
192
192
  get(id: string): Promise<{ meta: DocumentMeta; text: string } | undefined>; // undefined if expired
193
193
  getMeta(id: string): Promise<DocumentMeta | undefined>;
194
- delete(id: string): Promise<boolean>; // the original file too
194
+ delete(id: string): Promise<boolean>; // the original file and the index too
195
195
  sweep?(now?: Date): Promise<number>;
196
196
  putOriginal?(id: string, bytes: Uint8Array): Promise<void>; // optional: see below
197
197
  getOriginal?(id: string): Promise<Uint8Array | undefined>; // undefined if not kept, or expired
198
+ // Optional: read large documents by range instead of loading them whole (see below).
199
+ readTextRange?(id: string, start: number, end: number): Promise<Uint8Array | undefined>; // UTF-8 bytes
200
+ putIndex?(id: string, index: Uint8Array): Promise<void>;
201
+ getIndex?(id: string): Promise<Uint8Array | undefined>;
198
202
  }
199
203
  ```
200
204
 
201
- Keep `getMeta` cheap (store the metadata separately from the text). Parsed documents are cached
202
- in memory (`cacheSize`, default 6), so repeated tool calls don't reload the text.
205
+ Keep `getMeta` cheap (store the metadata separately from the text): it is called on every tool
206
+ call. A document ready to search is kept in memory between tool calls, within `cacheBytes`
207
+ (default 256 MB, the least recently used dropped first; `cacheSize` caps their number too). Every
208
+ use of a kept document asks the store first, so a document deleted or expired anywhere is gone
209
+ everywhere at once.
210
+
211
+ ### Large files, many users, several servers
212
+
213
+ With a store that has `readTextRange`, as `FileDocumentStore` does, a document whose text is larger
214
+ than `wholeDocumentBytes` (default 2 MB) is never loaded whole:
215
+
216
+ - At ingest, a line index is written next to the text (`<id>.idx`, four bytes a line: 3 MB for a
217
+ file of 730,000 lines). `read_document`, the card and the overview read only the lines they show.
218
+ - A search reads the text 1 MB at a time (`scanChunkBytes`), reading the next piece while it searches
219
+ the current one, so a search holds a few MB whatever the size of the file. At most
220
+ `maxConcurrentScans` searches (default 4) run at once in a process; the others wait their turn,
221
+ and those waiting for the same file share one pass over it: it is read, decoded and lowercased
222
+ once for all of them. Results are the same as from the whole text: the tests compare them call by call.
223
+ - Decoded pieces of a file are kept in the same `cacheBytes` budget, so the next search of a file in
224
+ use reads nothing. A file whose decoded text would take more than a quarter of the budget is never
225
+ kept: it would push out everything else. A larger `cacheBytes` spends memory to save CPU.
226
+ - A document from an older version, without an index, gets one the first time it is used: it is
227
+ built from the text in one pass and saved for the other servers. A damaged index, or one that
228
+ does not match its document, is noticed and built again.
229
+
230
+ Smaller documents are loaded whole and kept in the cache: for them that is faster, and they are small.
231
+ `wholeDocumentBytes: Infinity` loads every document whole, as before 0.4; `0` reads every one by range.
232
+
233
+ `FileDocumentStore` on a volume that several servers share:
234
+
235
+ - Every file is written under a temporary name and then renamed, so no server reads half a file.
236
+ - `sweep` removes files of no document (an upload that failed, a server that stopped while writing)
237
+ and temporary files once they are an hour old (`orphanAgeMs`), never younger ones: they may be an
238
+ upload in progress on another server. Run `sweep` from one place, such as a scheduled job.
239
+ - Servers of an older version on the same volume (during a rolling update) read the same files and
240
+ ignore the index. An index left behind when one of them deletes a document is swept an hour later.
241
+
242
+ A store of your own can do the same over S3 (`Range` requests), Redis (`GETRANGE`) or a database:
243
+ add `readTextRange`, and `putIndex` with `getIndex` to keep the index. Without `putIndex` the index
244
+ is built in memory each time the document is opened.
203
245
 
204
246
  ### Keeping the uploaded file
205
247
 
@@ -230,7 +272,7 @@ createLargeFiles({ store: new FileDocumentStore(dir), keepOriginals: ["pdf"] });
230
272
  | `json` | `.json`, `.jsonl`, `.ndjson` | Minified JSON is wrapped into addressable lines |
231
273
  | `csv` | `.csv`, `.tsv` | |
232
274
  | `pdf` | `.pdf` | Needs `unpdf`. Pages are marked `--- Page N ---`, tables are rebuilt (below), and a page without text says so. With `@cantoo/pdf-lib`, a page that shows a picture says so too, and the model can be shown the page itself ([Pictures in PDFs](#pictures-in-pdfs)). A scanned PDF (no text layer at all) is rejected, unless its original is kept and it has at most 30 pages. |
233
- | `docx`, `pptx` | extension or MIME type | Needs `jszip`. Slides are marked `## Slide N`. |
275
+ | `docx`, `pptx` | extension or MIME type | Needs `jszip`. Slides are marked `## Slide N`. A text box is read once, after the paragraph it is anchored in. A file that unpacks to more than 100 times its size (past the first 16 MB), or to more than 128 MB of XML, is rejected as a possible zip bomb. |
234
276
  | `text` | anything else that decodes as text | UTF-8 or UTF-16 (with or without BOM); binary is rejected |
235
277
 
236
278
  Lines longer than 2,000 characters are split, so every line can be read by number.
@@ -329,6 +371,10 @@ What counts:
329
371
  - **A drawing:** shapes filled in three or more colours, outside the tables. Greys, rules, dots
330
372
  and page backgrounds do not count, and neither does the shading of a table's cells.
331
373
  - A page whose drawing instructions are larger than 2 MB: that is a map or a technical drawing.
374
+ So is a page that paints more than 20,000 images, or whose instructions come to more than 16 MB
375
+ once each form (a drawing kept apart and painted by name) is counted every time it is painted.
376
+ Reading such a page stops there, so a few kilobytes of forms painted inside forms cannot hold
377
+ the server.
332
378
 
333
379
  What it gets wrong:
334
380
 
@@ -61,7 +61,9 @@ The response is a `DocumentSummary`:
61
61
  ```
62
62
 
63
63
  Errors are JSON `{ "error": "…" }`: 400 when there's no file name, 413 when the file is too large,
64
- and 422 for an unreadable file (binary, empty, or a scanned PDF that cannot be shown page by page).
64
+ 422 for an unreadable file (binary, empty, a zip bomb, or a scanned PDF that cannot be shown page by
65
+ page), and 500 when the server fails, as when the store's disk is full. `getOwner` can refuse a
66
+ request by throwing an error with a `status`, such as 401 (see the [API reference](api.md)).
65
67
 
66
68
  **Other servers.** The handlers take Node's `IncomingMessage` / `ServerResponse`, so they work with
67
69
  `node:http`, Express, Koa (`ctx.req`, `ctx.res`), Fastify (`request.raw`, `reply.raw`), and Next.js
@@ -28,7 +28,9 @@ chat turn ─► prepare(ids, size of the rest of the request)
28
28
  by *shape*. Numbers, IDs, IPs, hex, and quoted values are replaced with placeholders, so 800
29
29
  timeouts to different hosts become one entry: `[ERROR ×812, L1203] timeout after <n>ms to <ip>`.
30
30
  4. **Store** the text and metadata, and the uploaded file when its format is in `keepOriginals`.
31
- Nothing else is indexed up front.
31
+ With a store that can read by range (`FileDocumentStore`), also a line index: where each line
32
+ starts, a few bytes a line, so a tool call on a large file reads only the lines it needs
33
+ ([details](configuration.md#large-files-many-users-several-servers)). Nothing else is indexed up front.
32
34
 
33
35
  ## The card
34
36
 
package/docs/security.md CHANGED
@@ -38,6 +38,9 @@ treat the model's output as untrusted.
38
38
 
39
39
  - Files expire after `ttlMs` (default 72 h); expired files are never returned. `sweep()` deletes
40
40
  them from disk. Set the TTL to match your data policy.
41
+ - A delete takes effect on every server that shares the store, from the next tool call on: a
42
+ document kept in memory is used only after the store confirms that it is still there. (Before
43
+ 0.4, another server could keep answering from its memory until the document expired.)
41
44
  - `FileDocumentStore` writes plain text to disk. Use an encrypted volume, or implement
42
45
  `DocumentStore` over storage with encryption at rest.
43
46
  - Only IDs matching `doc_` plus 32 hex characters ever reach the file system, so there's no path
@@ -82,6 +85,11 @@ process, on a file a user uploaded.
82
85
  - `maxUploadBytes` (default 100 MB) is enforced while reading, before the body is buffered fully.
83
86
  - The handlers buffer the upload in memory before extraction. Under heavy concurrent uploads, put a
84
87
  limit in front (a reverse proxy or a rate limiter).
88
+ - A DOCX or PPTX is unpacked a piece at a time, and refused as it grows past 100 times its size
89
+ (after the first 16 MB) or past 128 MB of XML: a zip bomb of 160 KB that unpacks to 50 MB is
90
+ stopped at 16 MB. Its XML is read in one pass, so its shape cannot make reading slower.
91
+ - A terminal escape sequence (`ESC ]` …) is removed only up to its end on the same line: one
92
+ without an end loses its two escape characters, not the lines after it.
85
93
  - Binary files are rejected, including compressed ones (`.gz`, `.zip`), which get a message
86
94
  telling the user to decompress first. PDF parsing runs `unpdf` (pdf.js), and with it installed
87
95
  `@cantoo/pdf-lib`, on untrusted input in your process. Keep them updated, or move extraction to a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "llm-large-files",
3
- "version": "0.3.5",
3
+ "version": "0.4.0",
4
4
  "description": "Let an LLM answer questions about books, logs, and other files larger than its request limit or context window: upload, plan, search and read tools, map-reduce, and a look at the pages of a PDF. Gemini and Vertex AI helpers included.",
5
5
  "keywords": [
6
6
  "llm",
@@ -51,8 +51,12 @@
51
51
  },
52
52
  "typesVersions": {
53
53
  "*": {
54
- "gemini": ["./dist/gemini/index.d.ts"],
55
- "node": ["./dist/node/index.d.ts"]
54
+ "gemini": [
55
+ "./dist/gemini/index.d.ts"
56
+ ],
57
+ "node": [
58
+ "./dist/node/index.d.ts"
59
+ ]
56
60
  }
57
61
  },
58
62
  "files": [
package/src/cache.ts ADDED
@@ -0,0 +1,83 @@
1
+ import type { DocumentMeta } from "./types.js";
2
+
3
+ /** Something the cache can hold: it says how much memory it takes. */
4
+ export type Sized = { readonly memoryBytes: number };
5
+
6
+ /**
7
+ * What identifies the contents of a document. A document ID is never reused, but a store can be
8
+ * restored from a backup or written by another program: a cached copy is used only while the
9
+ * store still describes the same text.
10
+ */
11
+ export function documentVersion(meta: DocumentMeta): string {
12
+ return `${meta.createdAt}|${meta.textBytes}|${meta.characters}|${meta.lines}`;
13
+ }
14
+
15
+ /**
16
+ * Documents ready to read and search, kept between tool calls, the least recently used dropped
17
+ * first. Bounded by the memory the documents take, not by their number: six small files and
18
+ * six 50 MB files are not the same load.
19
+ *
20
+ * The cache never decides whether a document still exists. The caller asks the store first,
21
+ * every time (see `createLargeFiles`), so a document deleted or expired on another server is
22
+ * not served from here.
23
+ */
24
+ export class DocumentCache<T extends Sized> {
25
+ private readonly entries = new Map<string, { version: string; value: T; bytes: number }>();
26
+ private total = 0;
27
+
28
+ constructor(
29
+ private readonly maxBytes: number,
30
+ /** An optional cap on the number of documents too (the `cacheSize` of 0.3.x). */
31
+ private readonly maxEntries = Number.POSITIVE_INFINITY,
32
+ ) {}
33
+
34
+ /** Memory taken by the cached documents, by their own estimate. */
35
+ get bytes(): number {
36
+ return this.total;
37
+ }
38
+
39
+ get size(): number {
40
+ return this.entries.size;
41
+ }
42
+
43
+ get(id: string, version: string): T | undefined {
44
+ const entry = this.entries.get(id);
45
+ if (!entry) return undefined;
46
+ if (entry.version !== version) {
47
+ this.delete(id);
48
+ return undefined;
49
+ }
50
+ // Most recently used last.
51
+ this.entries.delete(id);
52
+ this.entries.set(id, entry);
53
+ return entry.value;
54
+ }
55
+
56
+ /** Keeps a document. One larger than the whole cache is not kept: it is used for this call only. */
57
+ set(id: string, version: string, value: T): void {
58
+ const existing = this.entries.get(id);
59
+ if (existing?.value === value && existing.version === version) return;
60
+ this.delete(id);
61
+ const bytes = Math.max(0, value.memoryBytes);
62
+ if (bytes > this.maxBytes || this.maxEntries < 1) return;
63
+ this.entries.set(id, { version, value, bytes });
64
+ this.total += bytes;
65
+ for (const [oldest, entry] of this.entries) {
66
+ if (this.total <= this.maxBytes && this.entries.size <= this.maxEntries) break;
67
+ this.entries.delete(oldest);
68
+ this.total -= entry.bytes;
69
+ }
70
+ }
71
+
72
+ delete(id: string): void {
73
+ const entry = this.entries.get(id);
74
+ if (!entry) return;
75
+ this.entries.delete(id);
76
+ this.total -= entry.bytes;
77
+ }
78
+
79
+ /** Drops every entry whose key starts with `prefix`: all the pieces of one document. */
80
+ deletePrefix(prefix: string): void {
81
+ for (const key of [...this.entries.keys()]) if (key.startsWith(prefix)) this.delete(key);
82
+ }
83
+ }
package/src/extract.ts CHANGED
@@ -82,24 +82,205 @@ function decodeXmlEntities(value: string): string {
82
82
  });
83
83
  }
84
84
 
85
- /** Text of each `<prefix:p>` paragraph in Office XML. Regex keeps this free of an XML parser dependency. */
86
- export function officeXmlParagraphs(xml: string, prefix: "w" | "a"): string[] {
87
- const paragraphs = xml.match(new RegExp(`<${prefix}:p[\\s>][\\s\\S]*?</${prefix}:p>`, "g")) ?? [];
88
- const textPattern = new RegExp(`<${prefix}:t(?:\\s[^>]*)?>([\\s\\S]*?)</${prefix}:t>|<${prefix}:(tab|br)\\b[^>]*/>`, "g");
89
- return paragraphs.map((paragraph) => {
90
- let text = "";
91
- for (const match of paragraph.matchAll(textPattern)) {
92
- if (match[2] === "tab") text += "\t";
93
- else if (match[2] === "br") text += "\n";
94
- else text += decodeXmlEntities(match[1] ?? "");
85
+ /** A tag name is read up to this many characters: the names that matter here are short. */
86
+ const MAX_TAG_NAME = 64;
87
+
88
+ /**
89
+ * Collects the text of each paragraph of Office XML (`<w:p>` in Word, `<a:p>` in PowerPoint) in one
90
+ * pass, with no XML parser. The XML can come in pieces, as it is unpacked: a tag cut between two
91
+ * pieces is read whole. Every character is looked at once, so the time follows the length of the
92
+ * XML whatever its shape: a file of unclosed tags costs what a file of closed ones does.
93
+ *
94
+ * - A paragraph inside another one (the text box of a shape anchored in a paragraph) is a paragraph
95
+ * of its own, after the one it is anchored in, which keeps its text before and after the box.
96
+ * - `mc:Fallback` repeats `mc:Choice` for older programs, so it is skipped: a text box is read once.
97
+ * - Paragraph properties hold no text. Their tab stops are not tabs.
98
+ */
99
+ class OfficeText {
100
+ private readonly paragraphTag: string;
101
+ private readonly paragraphEnd: string;
102
+ private readonly textTag: string;
103
+ private readonly textEnd: string;
104
+ private readonly propertiesTag: string;
105
+ private readonly propertiesEnd: string;
106
+ private readonly tabTag: string;
107
+ private readonly breakTags: ReadonlySet<string>;
108
+ /** The pieces of text of each paragraph, in the order the paragraphs start. */
109
+ private readonly paragraphs: string[][] = [];
110
+ /** The paragraphs that are open, the innermost last. */
111
+ private readonly open: string[][] = [];
112
+ private inText = false;
113
+ private inProperties = 0;
114
+ private inFallback = 0;
115
+ /** The tag being read, from its "<": its name so far, the quote of a value it is in, its last character. */
116
+ private tag: { name: string; named: boolean; quote: number; last: number } | undefined;
117
+
118
+ constructor(prefix: "w" | "a") {
119
+ this.paragraphTag = `${prefix}:p`;
120
+ this.paragraphEnd = `/${prefix}:p`;
121
+ this.textTag = `${prefix}:t`;
122
+ this.textEnd = `/${prefix}:t`;
123
+ this.propertiesTag = `${prefix}:pPr`;
124
+ this.propertiesEnd = `/${prefix}:pPr`;
125
+ this.tabTag = `${prefix}:tab`;
126
+ this.breakTags = new Set([`${prefix}:br`, `${prefix}:cr`]);
127
+ }
128
+
129
+ write(xml: string): void {
130
+ const length = xml.length;
131
+ let at = 0;
132
+ while (at < length) {
133
+ const tag = this.tag;
134
+ if (!tag) {
135
+ const start = xml.indexOf("<", at);
136
+ const end = start === -1 ? length : start;
137
+ if (end > at && this.inText && this.inProperties === 0 && this.inFallback === 0) this.open.at(-1)?.push(xml.slice(at, end));
138
+ if (start === -1) return;
139
+ this.tag = { name: "", named: false, quote: 0, last: 0 };
140
+ at = start + 1;
141
+ continue;
142
+ }
143
+ for (; at < length; at++) {
144
+ const code = xml.charCodeAt(at);
145
+ if (tag.quote !== 0) {
146
+ if (code === tag.quote) tag.quote = 0;
147
+ continue;
148
+ }
149
+ if (!tag.named) {
150
+ // A name ends at white space, at ">", or at the "/" of "<w:br/>". "</w:p>" starts with one.
151
+ if (code === 62 || code === 32 || code === 9 || code === 10 || code === 13 || (code === 47 && tag.name !== "")) tag.named = true;
152
+ else {
153
+ if (tag.name.length < MAX_TAG_NAME) tag.name += xml[at];
154
+ continue;
155
+ }
156
+ }
157
+ if (code === 62) break;
158
+ if (code === 34 || code === 39) tag.quote = code;
159
+ else if (code !== 32 && code !== 9 && code !== 10 && code !== 13) tag.last = code;
160
+ }
161
+ if (at === length) return; // The tag goes on in the next piece.
162
+ this.tag = undefined;
163
+ this.read(tag.name, tag.last === 47);
164
+ at++;
165
+ }
166
+ }
167
+
168
+ /** The text of each paragraph that has some, in the order the paragraphs start. */
169
+ texts(): string[] {
170
+ return this.paragraphs.map((pieces) => decodeXmlEntities(pieces.join(""))).filter((text) => text.trim());
171
+ }
172
+
173
+ /** Acts on a tag that has been read. `empty` is a tag that closes itself, as `<w:br/>`. */
174
+ private read(name: string, empty: boolean): void {
175
+ if (name === "mc:Fallback") {
176
+ if (!empty) this.inFallback++;
177
+ return;
178
+ }
179
+ if (name === "/mc:Fallback") {
180
+ if (this.inFallback > 0) this.inFallback--;
181
+ return;
182
+ }
183
+ if (this.inFallback > 0) return;
184
+ if (name === this.paragraphTag) {
185
+ if (!empty) {
186
+ const pieces: string[] = [];
187
+ this.paragraphs.push(pieces);
188
+ this.open.push(pieces);
189
+ }
190
+ } else if (name === this.paragraphEnd) {
191
+ this.open.pop();
192
+ this.inText = false;
193
+ this.inProperties = 0;
194
+ } else if (name === this.textTag) {
195
+ this.inText = !empty;
196
+ } else if (name === this.textEnd) {
197
+ this.inText = false;
198
+ } else if (name === this.propertiesTag) {
199
+ if (!empty) this.inProperties++;
200
+ } else if (name === this.propertiesEnd) {
201
+ if (this.inProperties > 0) this.inProperties--;
202
+ } else if (this.inProperties === 0) {
203
+ if (name === this.tabTag) this.open.at(-1)?.push("\t");
204
+ else if (this.breakTags.has(name)) this.open.at(-1)?.push("\n");
95
205
  }
96
- return text;
97
- }).filter((text) => text.trim());
206
+ }
98
207
  }
99
208
 
100
- type ZipFile = { async(type: "string"): Promise<string> };
209
+ /** Text of each paragraph of Office XML, in the order the paragraphs start. See `OfficeText`. */
210
+ export function officeXmlParagraphs(xml: string, prefix: "w" | "a"): string[] {
211
+ const text = new OfficeText(prefix);
212
+ text.write(xml);
213
+ return text.texts();
214
+ }
215
+
216
+ /** The part of JSZip's stream of one file that is used here. */
217
+ type ZipStream = {
218
+ on(event: "data", listener: (chunk: string) => void): ZipStream;
219
+ on(event: "error", listener: (error: unknown) => void): ZipStream;
220
+ on(event: "end", listener: () => void): ZipStream;
221
+ resume(): ZipStream;
222
+ pause(): ZipStream;
223
+ };
224
+ /** `internalStream` hands out a file of the archive in pieces, as it is unpacked. */
225
+ type ZipFile = { internalStream(type: "string"): ZipStream };
101
226
  type ZipArchive = { files: Record<string, unknown>; file(name: string): ZipFile | null };
102
227
 
228
+ /** The most XML read from one DOCX or PPTX, whatever its size: a document of thousands of pages. */
229
+ const MAX_OFFICE_XML = 128 * 1024 * 1024;
230
+ /**
231
+ * The parts read from an Office file unpack to less than its size: pictures, fonts and styles stay
232
+ * packed. A generated report that repeats one paragraph 50,000 times unpacks to 90 times its size.
233
+ * A file that unpacks to more than this many times its size, past the first 16 MB, is taken for a
234
+ * zip bomb, as Apache POI does.
235
+ */
236
+ const MAX_OFFICE_EXPANSION = 100;
237
+ const OFFICE_ALLOWANCE = 16 * 1024 * 1024;
238
+
239
+ const megabytes = (size: number) => `${Math.round(size / 1024 / 1024)} MB`;
240
+
241
+ /**
242
+ * Reads the paragraphs of the parts of one DOCX or PPTX, each a piece at a time as it is unpacked,
243
+ * counting what is unpacked: a file that grows far past its size is refused as it grows, before
244
+ * that much is in memory. Unpacking yields to other work between pieces.
245
+ */
246
+ function officeReader(archive: ZipArchive, kind: "DOCX" | "PPTX", size: number) {
247
+ const limit = Math.min(MAX_OFFICE_XML, Math.max(OFFICE_ALLOWANCE, size * MAX_OFFICE_EXPANSION));
248
+ const refusal = limit === MAX_OFFICE_XML
249
+ ? `This ${kind} unpacks to more than ${megabytes(limit)} of XML, more than is read from one file. Save it as text or PDF, and attach that.`
250
+ : `This ${kind} unpacks to more than ${megabytes(limit)}, over ${MAX_OFFICE_EXPANSION} times its size. A file that grows that much is not read: it may be a zip bomb. Save it as text or PDF, and attach that.`;
251
+ let unpacked = 0;
252
+ return (name: string, prefix: "w" | "a") => new Promise<string[]>((resolve, reject) => {
253
+ const file = archive.file(name);
254
+ if (!file) {
255
+ resolve([]);
256
+ return;
257
+ }
258
+ const text = new OfficeText(prefix);
259
+ let stopped = false;
260
+ const stream = file.internalStream("string");
261
+ stream
262
+ .on("data", (chunk) => {
263
+ if (stopped) return;
264
+ unpacked += chunk.length;
265
+ if (unpacked > limit) {
266
+ stopped = true;
267
+ stream.pause();
268
+ reject(new Error(refusal));
269
+ return;
270
+ }
271
+ text.write(chunk);
272
+ })
273
+ .on("error", (error) => {
274
+ stopped = true;
275
+ reject(error);
276
+ })
277
+ .on("end", () => {
278
+ if (!stopped) resolve(text.texts());
279
+ })
280
+ .resume();
281
+ });
282
+ }
283
+
103
284
  async function loadZip(bytes: Uint8Array): Promise<ZipArchive> {
104
285
  let JSZip: { loadAsync(data: Uint8Array): Promise<ZipArchive> };
105
286
  try {
@@ -116,11 +297,9 @@ const docx: Extractor = async (bytes) => {
116
297
  .filter((name) => /^word\/(document|header\d+|footer\d+|footnotes|endnotes)\.xml$/i.test(name))
117
298
  .sort((left, right) => left === "word/document.xml" ? -1 : right === "word/document.xml" ? 1 : left.localeCompare(right));
118
299
  if (!names.includes("word/document.xml")) throw new Error("This DOCX does not contain word/document.xml.");
300
+ const read = officeReader(archive, "DOCX", bytes.byteLength);
119
301
  const sections: string[] = [];
120
- for (const name of names) {
121
- const xml = await archive.file(name)?.async("string");
122
- if (xml) sections.push(officeXmlParagraphs(xml, "w").join("\n"));
123
- }
302
+ for (const name of names) sections.push((await read(name, "w")).join("\n"));
124
303
  return { text: sections.filter(Boolean).join("\n\n") };
125
304
  };
126
305
 
@@ -131,10 +310,10 @@ const pptx: Extractor = async (bytes) => {
131
310
  .filter((name) => /^ppt\/slides\/slide\d+\.xml$/i.test(name))
132
311
  .sort((left, right) => slideNumber(left) - slideNumber(right));
133
312
  if (names.length === 0) throw new Error("This PPTX does not contain any slides.");
313
+ const read = officeReader(archive, "PPTX", bytes.byteLength);
134
314
  const slides: string[] = [];
135
315
  for (const name of names) {
136
- const xml = await archive.file(name)?.async("string");
137
- const text = xml ? officeXmlParagraphs(xml, "a").join("\n") : "";
316
+ const text = (await read(name, "a")).join("\n");
138
317
  slides.push(`## Slide ${slideNumber(name)}\n${text || "[No text on this slide]"}`);
139
318
  }
140
319
  return { text: slides.join("\n\n"), pages: names.length };
package/src/index.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // Core: provider-neutral. Gemini helpers live in "llm-large-files/gemini",
2
2
  // Node HTTP handlers in "llm-large-files/node".
3
- export { createLargeFiles, DEFAULT_BUDGET, isDocumentId, toDocumentSummary } from "./library.js";
3
+ export { createLargeFiles, DEFAULT_BUDGET, DEFAULT_CACHE_BYTES, DEFAULT_WHOLE_DOCUMENT_BYTES, isDocumentId, toDocumentSummary } from "./library.js";
4
4
  export type { AccessOptions, IngestInput, LargeFiles, LargeFilesOptions, PrepareOptions, ToolOptions } from "./library.js";
5
5
  export { FileDocumentStore, MemoryDocumentStore, DOCUMENT_ID_PATTERN } from "./stores.js";
6
6
  export { createPdfExtractor, defaultExtractors, detectFormat } from "./extract.js";