llm-large-files 0.5.0 → 0.7.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 (221) hide show
  1. package/CHANGELOG.md +1402 -467
  2. package/README.md +188 -60
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +190 -39
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +60 -4
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1068 -206
  14. package/dist/ask.js.map +1 -1
  15. package/dist/encoding.d.ts +17 -0
  16. package/dist/encoding.d.ts.map +1 -0
  17. package/dist/encoding.js +852 -0
  18. package/dist/encoding.js.map +1 -0
  19. package/dist/errors.d.ts +4 -0
  20. package/dist/errors.d.ts.map +1 -1
  21. package/dist/errors.js +15 -0
  22. package/dist/errors.js.map +1 -1
  23. package/dist/events.d.ts +333 -0
  24. package/dist/events.d.ts.map +1 -0
  25. package/dist/events.js +159 -0
  26. package/dist/events.js.map +1 -0
  27. package/dist/evidence.d.ts +2 -0
  28. package/dist/evidence.d.ts.map +1 -1
  29. package/dist/evidence.js +3 -2
  30. package/dist/evidence.js.map +1 -1
  31. package/dist/extract.d.ts +35 -3
  32. package/dist/extract.d.ts.map +1 -1
  33. package/dist/extract.js +626 -58
  34. package/dist/extract.js.map +1 -1
  35. package/dist/gemini/adapter.d.ts +17 -8
  36. package/dist/gemini/adapter.d.ts.map +1 -1
  37. package/dist/gemini/adapter.js +108 -61
  38. package/dist/gemini/adapter.js.map +1 -1
  39. package/dist/gemini/chat.d.ts +23 -3
  40. package/dist/gemini/chat.d.ts.map +1 -1
  41. package/dist/gemini/chat.js +6 -2
  42. package/dist/gemini/chat.js.map +1 -1
  43. package/dist/gemini/errors.d.ts +9 -4
  44. package/dist/gemini/errors.d.ts.map +1 -1
  45. package/dist/gemini/errors.js +32 -0
  46. package/dist/gemini/errors.js.map +1 -1
  47. package/dist/gemini/generate.d.ts +10 -2
  48. package/dist/gemini/generate.d.ts.map +1 -1
  49. package/dist/gemini/generate.js +13 -7
  50. package/dist/gemini/generate.js.map +1 -1
  51. package/dist/gemini/index.d.ts +3 -3
  52. package/dist/gemini/index.d.ts.map +1 -1
  53. package/dist/gemini/index.js +2 -2
  54. package/dist/gemini/index.js.map +1 -1
  55. package/dist/gemini/sse.d.ts +1 -1
  56. package/dist/gemini/sse.d.ts.map +1 -1
  57. package/dist/gemini/sse.js +1 -1
  58. package/dist/gemini/sse.js.map +1 -1
  59. package/dist/http.d.ts +116 -0
  60. package/dist/http.d.ts.map +1 -1
  61. package/dist/http.js +347 -1
  62. package/dist/http.js.map +1 -1
  63. package/dist/index.d.ts +11 -6
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +6 -4
  66. package/dist/index.js.map +1 -1
  67. package/dist/library.d.ts +67 -5
  68. package/dist/library.d.ts.map +1 -1
  69. package/dist/library.js +405 -85
  70. package/dist/library.js.map +1 -1
  71. package/dist/map-reduce.d.ts +28 -1
  72. package/dist/map-reduce.d.ts.map +1 -1
  73. package/dist/map-reduce.js +240 -52
  74. package/dist/map-reduce.js.map +1 -1
  75. package/dist/model.d.ts +84 -2
  76. package/dist/model.d.ts.map +1 -1
  77. package/dist/model.js +182 -1
  78. package/dist/model.js.map +1 -1
  79. package/dist/node/handlers.d.ts +20 -4
  80. package/dist/node/handlers.d.ts.map +1 -1
  81. package/dist/node/handlers.js +122 -20
  82. package/dist/node/handlers.js.map +1 -1
  83. package/dist/node/index.d.ts +2 -0
  84. package/dist/node/index.d.ts.map +1 -1
  85. package/dist/node/index.js +1 -0
  86. package/dist/node/index.js.map +1 -1
  87. package/dist/node/sse.d.ts +59 -0
  88. package/dist/node/sse.d.ts.map +1 -0
  89. package/dist/node/sse.js +174 -0
  90. package/dist/node/sse.js.map +1 -0
  91. package/dist/openai/adapter.d.ts +29 -5
  92. package/dist/openai/adapter.d.ts.map +1 -1
  93. package/dist/openai/adapter.js +311 -37
  94. package/dist/openai/adapter.js.map +1 -1
  95. package/dist/output-limit.d.ts +14 -2
  96. package/dist/output-limit.d.ts.map +1 -1
  97. package/dist/output-limit.js +39 -10
  98. package/dist/output-limit.js.map +1 -1
  99. package/dist/pause.d.ts +24 -0
  100. package/dist/pause.d.ts.map +1 -0
  101. package/dist/pause.js +38 -0
  102. package/dist/pause.js.map +1 -0
  103. package/dist/pdf-pages.d.ts +32 -2
  104. package/dist/pdf-pages.d.ts.map +1 -1
  105. package/dist/pdf-pages.js +275 -14
  106. package/dist/pdf-pages.js.map +1 -1
  107. package/dist/pdf-pictures.d.ts +30 -3
  108. package/dist/pdf-pictures.d.ts.map +1 -1
  109. package/dist/pdf-pictures.js +50 -8
  110. package/dist/pdf-pictures.js.map +1 -1
  111. package/dist/pdf-work.d.ts +40 -0
  112. package/dist/pdf-work.d.ts.map +1 -0
  113. package/dist/pdf-work.js +734 -0
  114. package/dist/pdf-work.js.map +1 -0
  115. package/dist/plan.d.ts +22 -4
  116. package/dist/plan.d.ts.map +1 -1
  117. package/dist/plan.js +61 -12
  118. package/dist/plan.js.map +1 -1
  119. package/dist/retry.d.ts +23 -1
  120. package/dist/retry.d.ts.map +1 -1
  121. package/dist/retry.js +33 -3
  122. package/dist/retry.js.map +1 -1
  123. package/dist/search.d.ts +8 -2
  124. package/dist/search.d.ts.map +1 -1
  125. package/dist/search.js +60 -10
  126. package/dist/search.js.map +1 -1
  127. package/dist/sse.d.ts +35 -2
  128. package/dist/sse.d.ts.map +1 -1
  129. package/dist/sse.js +145 -31
  130. package/dist/sse.js.map +1 -1
  131. package/dist/stores.d.ts.map +1 -1
  132. package/dist/stores.js +5 -2
  133. package/dist/stores.js.map +1 -1
  134. package/dist/text-index.d.ts +6 -0
  135. package/dist/text-index.d.ts.map +1 -1
  136. package/dist/text-index.js +25 -8
  137. package/dist/text-index.js.map +1 -1
  138. package/dist/text.d.ts +62 -2
  139. package/dist/text.d.ts.map +1 -1
  140. package/dist/text.js +314 -14
  141. package/dist/text.js.map +1 -1
  142. package/dist/tools.d.ts +61 -1
  143. package/dist/tools.d.ts.map +1 -1
  144. package/dist/tools.js +269 -42
  145. package/dist/tools.js.map +1 -1
  146. package/dist/types.d.ts +102 -3
  147. package/dist/types.d.ts.map +1 -1
  148. package/dist/zip-directory.d.ts +43 -0
  149. package/dist/zip-directory.d.ts.map +1 -0
  150. package/dist/zip-directory.js +130 -0
  151. package/dist/zip-directory.js.map +1 -0
  152. package/docs/README.md +288 -0
  153. package/docs/api.md +37 -381
  154. package/docs/configuration.md +28 -558
  155. package/docs/getting-started.md +407 -223
  156. package/docs/guides/anthropic.md +590 -0
  157. package/docs/guides/conversations.md +629 -0
  158. package/docs/guides/costs-and-limits.md +726 -0
  159. package/docs/guides/deployment.md +654 -0
  160. package/docs/guides/errors-and-reliability.md +735 -0
  161. package/docs/guides/explorer-model.md +399 -0
  162. package/docs/guides/openai-compatible.md +602 -0
  163. package/docs/guides/own-adapter-and-loop.md +1169 -0
  164. package/docs/guides/pdfs.md +971 -0
  165. package/docs/guides/storage.md +731 -0
  166. package/docs/guides/testing.md +1199 -0
  167. package/docs/guides/vertex-and-gemini.md +717 -0
  168. package/docs/guides/web-app.md +1589 -0
  169. package/docs/how-it-works.md +1012 -164
  170. package/docs/measurements.md +881 -0
  171. package/docs/publishing.md +274 -46
  172. package/docs/reference/anthropic.md +427 -0
  173. package/docs/reference/ask.md +892 -0
  174. package/docs/reference/errors-and-retries.md +758 -0
  175. package/docs/reference/events.md +993 -0
  176. package/docs/reference/gemini.md +823 -0
  177. package/docs/reference/library.md +1467 -0
  178. package/docs/reference/node.md +528 -0
  179. package/docs/reference/openai.md +385 -0
  180. package/docs/reference/tools.md +883 -0
  181. package/docs/security.md +897 -103
  182. package/docs/troubleshooting.md +1390 -0
  183. package/package.json +2 -2
  184. package/src/analyze.ts +93 -42
  185. package/src/anthropic/adapter.ts +196 -39
  186. package/src/ask.ts +1087 -202
  187. package/src/encoding.ts +850 -0
  188. package/src/errors.ts +17 -0
  189. package/src/events.ts +442 -0
  190. package/src/evidence.ts +5 -2
  191. package/src/extract.ts +602 -62
  192. package/src/gemini/adapter.ts +118 -65
  193. package/src/gemini/chat.ts +28 -4
  194. package/src/gemini/errors.ts +34 -1
  195. package/src/gemini/generate.ts +23 -10
  196. package/src/gemini/index.ts +3 -3
  197. package/src/gemini/sse.ts +1 -1
  198. package/src/http.ts +376 -1
  199. package/src/index.ts +27 -5
  200. package/src/library.ts +459 -85
  201. package/src/map-reduce.ts +252 -51
  202. package/src/model.ts +236 -3
  203. package/src/node/handlers.ts +137 -22
  204. package/src/node/index.ts +2 -0
  205. package/src/node/sse.ts +198 -0
  206. package/src/openai/adapter.ts +306 -38
  207. package/src/output-limit.ts +44 -8
  208. package/src/pause.ts +41 -0
  209. package/src/pdf-pages.ts +268 -15
  210. package/src/pdf-pictures.ts +56 -9
  211. package/src/pdf-work.ts +722 -0
  212. package/src/plan.ts +68 -12
  213. package/src/retry.ts +49 -5
  214. package/src/search.ts +63 -10
  215. package/src/sse.ts +153 -28
  216. package/src/stores.ts +5 -2
  217. package/src/text-index.ts +26 -7
  218. package/src/text.ts +323 -13
  219. package/src/tools.ts +261 -42
  220. package/src/types.ts +107 -4
  221. package/src/zip-directory.ts +136 -0
package/src/extract.ts CHANGED
@@ -1,6 +1,12 @@
1
+ import { decodeNotUtf8, type DecodedText } from "./encoding.js";
2
+ import { TimeSlicer } from "./pause.js";
1
3
  import { layoutPage, plainPageText, type LayoutBox, type PdfTextItem } from "./pdf-layout.js";
2
- import { findPicturePages, type PageGeometry } from "./pdf-pictures.js";
3
- import type { DocumentFormat, ExtractedText, ExtractInput, Extractor } from "./types.js";
4
+ import { findPicturePages, parsePdf, type PageGeometry } from "./pdf-pictures.js";
5
+ import { checkPageWork, HeavyPage } from "./pdf-work.js";
6
+ import { formatBytes } from "./plan.js";
7
+ import { MAX_LINE_CHARACTERS, plural, sliceWhole, utf8Bytes } from "./text.js";
8
+ import type { DocumentFormat, ExtractedText, ExtractInput, ExtractProgress, Extractor } from "./types.js";
9
+ import { readZipDirectory } from "./zip-directory.js";
4
10
 
5
11
  const EXTENSION_FORMATS: Record<string, DocumentFormat> = {
6
12
  log: "log", out: "log", err: "log",
@@ -29,11 +35,21 @@ const NOT_TEXT = "This file looks binary, not text. Attach a text, log, PDF, DOC
29
35
 
30
36
  /**
31
37
  * Decodes text bytes, honoring UTF-8 and UTF-16 byte-order marks (common for Windows logs).
32
- * Throws a readable error for compressed and other binary files.
38
+ * A file that is not UTF-8 is read in the older encoding it was saved in, or as UTF-8 with its
39
+ * characters that are not valid as U+FFFD (see encoding.ts). Throws a readable error for
40
+ * compressed and other binary files.
33
41
  */
34
42
  export function decodeText(bytes: Uint8Array): string {
35
- if (bytes[0] === 0xff && bytes[1] === 0xfe) return new TextDecoder("utf-16le").decode(bytes.subarray(2));
36
- if (bytes[0] === 0xfe && bytes[1] === 0xff) return new TextDecoder("utf-16be").decode(bytes.subarray(2));
43
+ const steps = decodeSteps(bytes);
44
+ let step = steps.next();
45
+ while (!step.done) step = steps.next();
46
+ return step.value.text;
47
+ }
48
+
49
+ /** `decodeText` in steps: it yields between the steps of a file that is not valid UTF-8. */
50
+ function* decodeSteps(bytes: Uint8Array): Generator<void, DecodedText> {
51
+ if (bytes[0] === 0xff && bytes[1] === 0xfe) return { text: new TextDecoder("utf-16le").decode(bytes.subarray(2)) };
52
+ if (bytes[0] === 0xfe && bytes[1] === 0xff) return { text: new TextDecoder("utf-16be").decode(bytes.subarray(2)) };
37
53
  // Rotated logs often arrive as app.log.gz. Compressed bytes have few zeros, so name them here.
38
54
  if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
39
55
  throw new Error("This file is gzip-compressed. Decompress it, then attach the text file inside.");
@@ -53,7 +69,7 @@ export function decodeText(bytes: Uint8Array): string {
53
69
  if (index % 2 === 0 && sample[index] !== 0) evenText++;
54
70
  }
55
71
  const half = sample.length / 2;
56
- if (oddZeros / half > 0.6 && evenText / half > 0.6) return new TextDecoder("utf-16le").decode(bytes);
72
+ if (oddZeros / half > 0.6 && evenText / half > 0.6) return { text: new TextDecoder("utf-16le").decode(bytes) };
57
73
  }
58
74
  if (sample.length > 0 && zeros / sample.length > 0.01) throw new Error(NOT_TEXT);
59
75
  // Compressed, encrypted, and media files spread control bytes evenly: about 1 byte in 10.
@@ -64,10 +80,33 @@ export function decodeText(bytes: Uint8Array): string {
64
80
  if (byte < 0x09 || (byte > 0x0d && byte < 0x20 && byte !== 0x1b) || byte === 0x7f) controls++;
65
81
  }
66
82
  if (sample.length >= 64 && controls / sample.length > 0.03) throw new Error(NOT_TEXT);
67
- return new TextDecoder("utf-8").decode(bytes);
83
+ try {
84
+ return { text: new TextDecoder("utf-8", { fatal: true }).decode(bytes) };
85
+ } catch (error) {
86
+ if (!(error instanceof TypeError)) throw error;
87
+ }
88
+ // Not valid UTF-8: decoded as it is, the text would be replacement characters.
89
+ return yield* decodeNotUtf8(bytes);
68
90
  }
69
91
 
70
- const plainText: Extractor = async (bytes) => ({ text: decodeText(bytes) });
92
+ /**
93
+ * Text files. One that is not UTF-8 is read in the older encoding it was saved in, when that can
94
+ * be recognized, and other requests get a turn while it is read.
95
+ */
96
+ const plainText: Extractor = async (bytes, input) => {
97
+ const slicer = new TimeSlicer(input?.signal);
98
+ const steps = decodeSteps(bytes);
99
+ let step = steps.next();
100
+ // Only a file that is not UTF-8 takes steps: its decoding is told as one piece of progress, at the end.
101
+ const stepped = !step.done;
102
+ while (!step.done) {
103
+ await slicer.maybePause();
104
+ step = steps.next();
105
+ }
106
+ if (stepped) input?.onProgress?.({ stage: "decode", done: bytes.byteLength, total: bytes.byteLength, unit: "bytes" });
107
+ const { text, encoding, replacedCharacters } = step.value;
108
+ return { text, ...(encoding ? { encoding } : {}), ...(replacedCharacters ? { replacedCharacters } : {}) };
109
+ };
71
110
 
72
111
  function decodeXmlEntities(value: string): string {
73
112
  return value.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (match, entity: string) => {
@@ -84,6 +123,120 @@ function decodeXmlEntities(value: string): string {
84
123
 
85
124
  /** A tag name is read up to this many characters: the names that matter here are short. */
86
125
  const MAX_TAG_NAME = 64;
126
+ /** Paragraphs inside paragraphs, at most. Real files nest two or three: a text box in a paragraph. */
127
+ const MAX_PARAGRAPH_DEPTH = 32;
128
+ /** Paragraphs with text read from one Office file, at most: a document of 10,000 pages has about 300,000. */
129
+ const MAX_OFFICE_PARAGRAPHS = 1_000_000;
130
+ /** Characters of text kept from one Office file, at most, whatever `maxTextBytes` allows: about 10,000 dense pages. */
131
+ const MAX_OFFICE_CHARACTERS = 32_000_000;
132
+ /**
133
+ * The text of an open paragraph is counted as written in the XML, where `&quot;` is six characters
134
+ * for one: past this many times the limit, it is refused before the paragraph closes.
135
+ */
136
+ const MAX_ENTITY_GROWTH = 6;
137
+ /** Below this length V8 copies a slice of a string; from it on, a slice keeps the whole string it was cut from. */
138
+ const SLICE_COPIED_BELOW = 13;
139
+
140
+ /**
141
+ * Written before each line of the text that Word hides (a run marked `<w:vanish/>`), after the text
142
+ * of its paragraph that shows: a person reading the document does not see it. Each line is marked,
143
+ * so hidden text cannot end the mark and pass for text that shows.
144
+ */
145
+ export const HIDDEN_TEXT = "[Hidden text, not shown in the document]";
146
+ /** Added to the heading of a slide that the slide show skips (`<p:sld show="0">`). */
147
+ export const HIDDEN_SLIDE = "(hidden, not shown in the slide show)";
148
+ /**
149
+ * The one attribute read of `w:vanish` and of `p:sld`, and the values that count:
150
+ * `<w:vanish w:val="0"/>` turns hiding off (`<w:vanish/>` and any other value turn it on), and a
151
+ * slide with `show="0"` is hidden. Letter case counts in the value of `show`, and not in that of
152
+ * `w:val`. It counts in names, as in XML: `W:VAL` is another attribute.
153
+ */
154
+ const VANISH_OFF = { name: "w:val", values: ["0", "false", "off"], anyCase: true };
155
+ const SLIDE_NOT_SHOWN = { name: "show", values: ["0", "false"], anyCase: false };
156
+ type WantedAttribute = typeof VANISH_OFF;
157
+ /** Characters kept of an attribute's name and of the value wanted: more than the longest of those above. */
158
+ const MAX_ATTRIBUTE_PART = 6;
159
+ /**
160
+ * A line of hidden text longer than this is cut into pieces, each marked. A mark and its piece then
161
+ * fit on one line, which ingest does not cut: past `MAX_LINE_CHARACTERS` it would put the rest of
162
+ * the hidden line on a line of its own, without the mark.
163
+ */
164
+ const HIDDEN_PIECE = MAX_LINE_CHARACTERS - HIDDEN_TEXT.length - 1;
165
+ /**
166
+ * What ends a line of hidden text: a line break, a carriage return (ingest makes it one), a U+0085
167
+ * (ingest makes it one in a text with no other line break), or a line or paragraph separator
168
+ * (U+2028, U+2029), which a model may take for one. A new marked line where ingest removes the
169
+ * U+0085 instead does no harm.
170
+ */
171
+ const HIDDEN_LINE_END = /[\r\n\x85\u2028\u2029]/g;
172
+ /** Where a line of hidden text starts: at a character that is not white space, nor a U+0085. */
173
+ const NOT_SPACE = /[^\s\x85]/g;
174
+
175
+ /**
176
+ * Reads one attribute of a tag as the tag goes past, a character at a time, in whatever pieces the
177
+ * XML comes: whether its value is one of those wanted. It keeps a few characters, whatever the
178
+ * length of the tag, and looks at names and values apart, so a value that holds `w:val="0"` is not
179
+ * read as the attribute.
180
+ */
181
+ class AttributeReader {
182
+ /** The name being read, or the last one read, cut after `MAX_ATTRIBUTE_PART` characters. */
183
+ private name = "";
184
+ /** Whether the next character of a name starts a new one. */
185
+ private ended = true;
186
+ /** Whether "=" came after the name wanted, so the next value is its value. */
187
+ private assigned = false;
188
+ /** The value of the attribute wanted, while it is read. */
189
+ private value: string | undefined;
190
+ /** Whether the attribute wanted has one of the values wanted. */
191
+ found = false;
192
+
193
+ constructor(private readonly wanted: WantedAttribute) {}
194
+
195
+ /** A character of the tag after its name, outside a value. A quote that opens a value is not one. */
196
+ outside(code: number): void {
197
+ if (code === 32 || code === 9 || code === 10 || code === 13) {
198
+ this.ended = true;
199
+ } else if (code === 61) {
200
+ this.assigned = this.name === this.wanted.name;
201
+ this.name = "";
202
+ this.ended = true;
203
+ } else {
204
+ if (this.ended) {
205
+ this.name = "";
206
+ this.ended = false;
207
+ this.assigned = false;
208
+ }
209
+ if (this.name.length < MAX_ATTRIBUTE_PART) this.name += String.fromCharCode(code);
210
+ }
211
+ }
212
+
213
+ /** A quote opens a value. */
214
+ open(): void {
215
+ if (this.assigned) this.value = "";
216
+ this.assigned = false;
217
+ }
218
+
219
+ /** A character of a value. */
220
+ inValue(code: number): void {
221
+ if (this.value !== undefined && this.value.length < MAX_ATTRIBUTE_PART) this.value += String.fromCharCode(code);
222
+ }
223
+
224
+ /** The quote that closes a value. */
225
+ close(): void {
226
+ if (this.value !== undefined) {
227
+ this.found = this.wanted.values.includes(this.wanted.anyCase ? this.value.toLowerCase() : this.value);
228
+ this.value = undefined;
229
+ }
230
+ this.name = "";
231
+ this.ended = true;
232
+ }
233
+ }
234
+
235
+ /** What an Office file may hold before it is refused, and what to call it in the refusal. */
236
+ type OfficeLimits = { kind: string; maxCharacters: number; byTextLimit: boolean };
237
+ const NO_OFFICE_LIMITS: OfficeLimits = { kind: "file", maxCharacters: MAX_OFFICE_CHARACTERS, byTextLimit: false };
238
+ /** The text and the paragraphs read from all the parts of one Office file so far. */
239
+ type OfficeCount = { characters: number; paragraphs: number };
87
240
 
88
241
  /**
89
242
  * Collects the text of each paragraph of Office XML (`<w:p>` in Word, `<a:p>` in PowerPoint) in one
@@ -95,6 +248,13 @@ const MAX_TAG_NAME = 64;
95
248
  * of its own, after the one it is anchored in, which keeps its text before and after the box.
96
249
  * - `mc:Fallback` repeats `mc:Choice` for older programs, so it is skipped: a text box is read once.
97
250
  * - Paragraph properties hold no text. Their tab stops are not tabs.
251
+ * - In Word, the text of a hidden run (`<w:vanish/>` in the run's own properties) comes after the
252
+ * text of its paragraph that shows, each line marked with `HIDDEN_TEXT`. Text hidden by a style
253
+ * is not told apart. In PowerPoint, `hiddenSlide` says whether the slide show skips the slide.
254
+ *
255
+ * What it keeps in memory is bounded by the text, not by the XML: a paragraph becomes one string
256
+ * when it closes, an empty one is dropped, and a file that nests paragraphs past
257
+ * `MAX_PARAGRAPH_DEPTH`, or has more text or paragraphs than one document holds, is refused.
98
258
  */
99
259
  class OfficeText {
100
260
  private readonly paragraphTag: string;
@@ -105,17 +265,36 @@ class OfficeText {
105
265
  private readonly propertiesEnd: string;
106
266
  private readonly tabTag: string;
107
267
  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[][] = [];
268
+ /** Word marks hidden runs; PowerPoint hides whole slides. */
269
+ private readonly word: boolean;
270
+ /** The one tag whose attributes are read: `w:vanish` in Word, the slide's `p:sld` in PowerPoint. */
271
+ private readonly attributesTag: string;
272
+ /** The attribute read of `attributesTag`, and the values that count. */
273
+ private readonly attribute: WantedAttribute;
274
+ /** The text of each paragraph, in the order the paragraphs start: null while it is open, "" when empty. */
275
+ private readonly paragraphs: Array<string | null> = [];
276
+ /**
277
+ * The paragraphs that are open, the innermost last: where each goes in `paragraphs`, its text so
278
+ * far (that which shows, and that which Word hides), and its length. In Word, also how many runs
279
+ * are open (a ruby's runs are inside a run), how deep the outermost hidden one is (0: none is
280
+ * hidden), and how deep in run properties the reading is.
281
+ */
282
+ private readonly open: Array<{ slot: number; pieces: string[]; hidden: string[] | undefined; length: number; runs: number; hiddenFrom: number; runProperties: number }> = [];
283
+ /** Characters held in the paragraphs that are open, as written in the XML. */
284
+ private pending = 0;
112
285
  private inText = false;
113
286
  private inProperties = 0;
114
287
  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;
288
+ /**
289
+ * The tag being read, from its "<": its name so far, the quote of a value it is in, its last
290
+ * character, and for `attributesTag` the reader of its attribute.
291
+ */
292
+ private tag: { name: string; named: boolean; quote: number; last: number; attributes: AttributeReader | undefined } | undefined;
293
+ /** A PowerPoint slide that the slide show skips (`<p:sld show="0">`). */
294
+ hiddenSlide = false;
117
295
 
118
- constructor(prefix: "w" | "a") {
296
+ /** `count`: what the other parts of the same file held, shared with them. */
297
+ constructor(prefix: "w" | "a", private readonly limits: OfficeLimits = NO_OFFICE_LIMITS, private readonly count: OfficeCount = { characters: 0, paragraphs: 0 }) {
119
298
  this.paragraphTag = `${prefix}:p`;
120
299
  this.paragraphEnd = `/${prefix}:p`;
121
300
  this.textTag = `${prefix}:t`;
@@ -124,6 +303,9 @@ class OfficeText {
124
303
  this.propertiesEnd = `/${prefix}:pPr`;
125
304
  this.tabTag = `${prefix}:tab`;
126
305
  this.breakTags = new Set([`${prefix}:br`, `${prefix}:cr`]);
306
+ this.word = prefix === "w";
307
+ this.attributesTag = this.word ? "w:vanish" : "p:sld";
308
+ this.attribute = this.word ? VANISH_OFF : SLIDE_NOT_SHOWN;
127
309
  }
128
310
 
129
311
  write(xml: string): void {
@@ -134,44 +316,144 @@ class OfficeText {
134
316
  if (!tag) {
135
317
  const start = xml.indexOf("<", at);
136
318
  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));
319
+ if (end > at && this.inText && this.inProperties === 0 && this.inFallback === 0) this.add(xml.slice(at, end));
138
320
  if (start === -1) return;
139
- this.tag = { name: "", named: false, quote: 0, last: 0 };
321
+ this.tag = { name: "", named: false, quote: 0, last: 0, attributes: undefined };
140
322
  at = start + 1;
141
323
  continue;
142
324
  }
143
325
  for (; at < length; at++) {
144
326
  const code = xml.charCodeAt(at);
145
327
  if (tag.quote !== 0) {
146
- if (code === tag.quote) tag.quote = 0;
328
+ if (code === tag.quote) {
329
+ tag.quote = 0;
330
+ tag.attributes?.close();
331
+ } else {
332
+ tag.attributes?.inValue(code);
333
+ }
147
334
  continue;
148
335
  }
149
336
  if (!tag.named) {
150
337
  // 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 {
338
+ if (code === 62 || code === 32 || code === 9 || code === 10 || code === 13 || (code === 47 && tag.name !== "")) {
339
+ tag.named = true;
340
+ if (tag.name === this.attributesTag) tag.attributes = new AttributeReader(this.attribute);
341
+ } else {
153
342
  if (tag.name.length < MAX_TAG_NAME) tag.name += xml[at];
154
343
  continue;
155
344
  }
156
345
  }
157
346
  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;
347
+ if (code === 34 || code === 39) {
348
+ tag.quote = code;
349
+ tag.attributes?.open();
350
+ } else {
351
+ tag.attributes?.outside(code);
352
+ if (code !== 32 && code !== 9 && code !== 10 && code !== 13) tag.last = code;
353
+ }
160
354
  }
161
355
  if (at === length) return; // The tag goes on in the next piece.
162
356
  this.tag = undefined;
163
- this.read(tag.name, tag.last === 47);
357
+ this.read(tag.name, tag.last === 47, tag.attributes?.found ?? false);
164
358
  at++;
165
359
  }
166
360
  }
167
361
 
168
362
  /** The text of each paragraph that has some, in the order the paragraphs start. */
169
363
  texts(): string[] {
170
- return this.paragraphs.map((pieces) => decodeXmlEntities(pieces.join(""))).filter((text) => text.trim());
364
+ // A paragraph never closed keeps the text it has, as when the file ends inside it.
365
+ while (this.open.length > 0) this.close();
366
+ return this.paragraphs.filter((text): text is string => !!text);
367
+ }
368
+
369
+ /** Adds text to the innermost open paragraph. */
370
+ private add(piece: string): void {
371
+ const paragraph = this.open.at(-1);
372
+ if (!paragraph) return;
373
+ this.pending += piece.length;
374
+ paragraph.length += piece.length;
375
+ // The decoded text is counted when its paragraph closes. Until then, what is held is bounded too.
376
+ if (this.pending > this.limits.maxCharacters * MAX_ENTITY_GROWTH) throw this.tooMuchText();
377
+ if (paragraph.hiddenFrom !== 0) (paragraph.hidden ??= []).push(piece);
378
+ else paragraph.pieces.push(piece);
171
379
  }
172
380
 
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 {
381
+ private tooMuchText(): Error {
382
+ const { kind, maxCharacters, byTextLimit } = this.limits;
383
+ return new Error(byTextLimit
384
+ ? `This ${kind} holds more than ${formatBytes(maxCharacters)} of text, more than is kept from one file. Split it, and attach the part you need.`
385
+ : `This ${kind} holds more than ${Math.round(maxCharacters / 1_000_000)} million characters of text, more than is read from one file. Split it, and attach the part you need.`);
386
+ }
387
+
388
+ /** Closes the innermost open paragraph: its text becomes one string, or it is dropped when empty. */
389
+ private close(): void {
390
+ const paragraph = this.open.pop();
391
+ if (!paragraph) return;
392
+ this.pending -= paragraph.length;
393
+ const shown = decodeXmlEntities(paragraph.pieces.join(""));
394
+ const text = paragraph.hidden ? this.withHiddenText(shown, decodeXmlEntities(paragraph.hidden.join(""))) : shown;
395
+ if (text.trim()) {
396
+ this.count.characters += text.length;
397
+ if (this.count.characters > this.limits.maxCharacters) throw this.tooMuchText();
398
+ if (++this.count.paragraphs > MAX_OFFICE_PARAGRAPHS) {
399
+ throw new Error(`This ${this.limits.kind} has more than ${MAX_OFFICE_PARAGRAPHS.toLocaleString("en-US")} paragraphs, more than a document holds. It may be built to exhaust the server, so it is not read.`);
400
+ }
401
+ // A copy, not a slice of the piece of XML it came from: a slice would keep all that XML in memory.
402
+ this.paragraphs[paragraph.slot] = text.length < SLICE_COPIED_BELOW ? text : (" " + text).slice(1);
403
+ } else if (paragraph.slot === this.paragraphs.length - 1) {
404
+ this.paragraphs.pop();
405
+ } else {
406
+ this.paragraphs[paragraph.slot] = "";
407
+ }
408
+ }
409
+
410
+ /**
411
+ * A paragraph's text that shows, then each line of its hidden text, marked with `HIDDEN_TEXT`. A
412
+ * long hidden line is cut into pieces of `HIDDEN_PIECE` characters at most, each marked. The marks
413
+ * make the text longer than the XML it came from, so it is refused as soon as it holds more than
414
+ * the room left under the limit, not once it is built.
415
+ */
416
+ private withHiddenText(shown: string, hidden: string): string {
417
+ const room = this.limits.maxCharacters - this.count.characters;
418
+ const lines = shown.trim() ? [shown] : [];
419
+ // The length of the lines joined with line breaks.
420
+ let length = lines.length > 0 ? shown.length : -1;
421
+ let marked = 0;
422
+ // Where the line being marked ends, found once a line: each of its pieces starts before it, as
423
+ // `NOT_SPACE` never stops at a line end. Searched again from each piece, it took seconds.
424
+ let lineEnd = -1;
425
+ // Line by line, without splitting the text first: a run can hold millions of empty lines.
426
+ for (let at = 0; ;) {
427
+ NOT_SPACE.lastIndex = at;
428
+ const first = NOT_SPACE.exec(hidden);
429
+ if (!first) break;
430
+ const start = first.index;
431
+ if (start >= lineEnd) {
432
+ HIDDEN_LINE_END.lastIndex = start;
433
+ lineEnd = HIDDEN_LINE_END.exec(hidden)?.index ?? hidden.length;
434
+ }
435
+ let end = lineEnd;
436
+ if (end - start > HIDDEN_PIECE) {
437
+ // Cut after a space near the end of the piece, and never between the two halves of an emoji.
438
+ const window = sliceWhole(hidden.slice(start, lineEnd), HIDDEN_PIECE);
439
+ const space = window.lastIndexOf(" ");
440
+ end = start + (space > HIDDEN_PIECE * 0.8 ? space + 1 : window.length);
441
+ }
442
+ const line = `${HIDDEN_TEXT} ${hidden.slice(start, end)}`;
443
+ length += 1 + line.length;
444
+ if (length > room) throw this.tooMuchText();
445
+ lines.push(line);
446
+ marked++;
447
+ at = end;
448
+ }
449
+ return marked === 0 ? shown : lines.join("\n");
450
+ }
451
+
452
+ /**
453
+ * Acts on a tag that has been read. `empty` is a tag that closes itself, as `<w:br/>`.
454
+ * `found`: whether the tag is `attributesTag`, and its attribute has one of the values wanted.
455
+ */
456
+ private read(name: string, empty: boolean, found: boolean): void {
175
457
  if (name === "mc:Fallback") {
176
458
  if (!empty) this.inFallback++;
177
459
  return;
@@ -183,12 +465,14 @@ class OfficeText {
183
465
  if (this.inFallback > 0) return;
184
466
  if (name === this.paragraphTag) {
185
467
  if (!empty) {
186
- const pieces: string[] = [];
187
- this.paragraphs.push(pieces);
188
- this.open.push(pieces);
468
+ if (this.open.length >= MAX_PARAGRAPH_DEPTH) {
469
+ throw new Error(`This ${this.limits.kind} nests paragraphs more than ${MAX_PARAGRAPH_DEPTH} deep, which no document does. It may be built to exhaust the server, so it is not read.`);
470
+ }
471
+ this.open.push({ slot: this.paragraphs.length, pieces: [], hidden: undefined, length: 0, runs: 0, hiddenFrom: 0, runProperties: 0 });
472
+ this.paragraphs.push(null);
189
473
  }
190
474
  } else if (name === this.paragraphEnd) {
191
- this.open.pop();
475
+ this.close();
192
476
  this.inText = false;
193
477
  this.inProperties = 0;
194
478
  } else if (name === this.textTag) {
@@ -200,16 +484,53 @@ class OfficeText {
200
484
  } else if (name === this.propertiesEnd) {
201
485
  if (this.inProperties > 0) this.inProperties--;
202
486
  } 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");
487
+ if (name === this.tabTag) this.add("\t");
488
+ else if (this.breakTags.has(name)) this.add("\n");
489
+ else if (this.word) this.readRun(name, empty, found);
490
+ else if (name === "p:sld" && found) this.hiddenSlide = true;
491
+ }
492
+ }
493
+
494
+ /**
495
+ * Follows the runs of a Word paragraph, to tell the text of a hidden run: `<w:vanish/>` in the
496
+ * run's own properties, not in those of a change it records (`w:rPrChange`), one level deeper.
497
+ * A run inside a hidden run (the text of a ruby) is hidden too, and the run around it stays
498
+ * hidden after it. `off`: the `w:vanish` turns hiding off.
499
+ */
500
+ private readRun(name: string, empty: boolean, off: boolean): void {
501
+ const paragraph = this.open.at(-1);
502
+ if (!paragraph) return;
503
+ if (name === "w:r") {
504
+ if (empty) return;
505
+ paragraph.runs++;
506
+ paragraph.runProperties = 0;
507
+ } else if (name === "/w:r") {
508
+ if (paragraph.runs > 0) {
509
+ if (paragraph.hiddenFrom === paragraph.runs) paragraph.hiddenFrom = 0;
510
+ paragraph.runs--;
511
+ }
512
+ paragraph.runProperties = 0;
513
+ } else if (name === "w:rPr") {
514
+ if (!empty && paragraph.runs > 0) paragraph.runProperties++;
515
+ } else if (name === "/w:rPr") {
516
+ if (paragraph.runProperties > 0) paragraph.runProperties--;
517
+ } else if (name === "w:vanish" && paragraph.runProperties === 1) {
518
+ if (!off) {
519
+ if (paragraph.hiddenFrom === 0) paragraph.hiddenFrom = paragraph.runs;
520
+ } else if (paragraph.hiddenFrom === paragraph.runs) {
521
+ paragraph.hiddenFrom = 0;
522
+ }
205
523
  }
206
524
  }
207
525
  }
208
526
 
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[] {
527
+ /**
528
+ * Text of each paragraph of Office XML, in the order the paragraphs start. See `OfficeText`. The
529
+ * XML may be given in pieces, as it is unpacked.
530
+ */
531
+ export function officeXmlParagraphs(xml: string | string[], prefix: "w" | "a"): string[] {
211
532
  const text = new OfficeText(prefix);
212
- text.write(xml);
533
+ for (const piece of typeof xml === "string" ? [xml] : xml) text.write(piece);
213
534
  return text.texts();
214
535
  }
215
536
 
@@ -241,80 +562,166 @@ const megabytes = (size: number) => `${Math.round(size / 1024 / 1024)} MB`;
241
562
  /**
242
563
  * Reads the paragraphs of the parts of one DOCX or PPTX, each a piece at a time as it is unpacked,
243
564
  * 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.
565
+ * that much is in memory. JSZip can unpack megabytes of XML in one turn of the event loop, so the
566
+ * stream is paused every few milliseconds of reading, and other requests get a turn.
245
567
  */
246
- function officeReader(archive: ZipArchive, kind: "DOCX" | "PPTX", size: number) {
568
+ function officeReader(archive: ZipArchive, kind: "DOCX" | "PPTX", size: number, input: ExtractInput | undefined) {
247
569
  const limit = Math.min(MAX_OFFICE_XML, Math.max(OFFICE_ALLOWANCE, size * MAX_OFFICE_EXPANSION));
248
570
  const refusal = limit === MAX_OFFICE_XML
249
571
  ? `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
572
  : `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.`;
573
+ const maxTextBytes = input?.maxTextBytes ?? Number.POSITIVE_INFINITY;
574
+ // A character is at least one byte: a text with more characters than the limit is past it.
575
+ const limits: OfficeLimits = {
576
+ kind,
577
+ maxCharacters: Math.min(MAX_OFFICE_CHARACTERS, maxTextBytes),
578
+ byTextLimit: maxTextBytes < MAX_OFFICE_CHARACTERS,
579
+ };
580
+ // One count for the whole file, across its parts.
581
+ const count: OfficeCount = { characters: 0, paragraphs: 0 };
582
+ const slicer = new TimeSlicer(input?.signal);
251
583
  let unpacked = 0;
252
- return (name: string, prefix: "w" | "a") => new Promise<string[]>((resolve, reject) => {
584
+ return (name: string, prefix: "w" | "a") => new Promise<{ paragraphs: string[]; hiddenSlide: boolean }>((resolve, reject) => {
253
585
  const file = archive.file(name);
254
586
  if (!file) {
255
- resolve([]);
587
+ resolve({ paragraphs: [], hiddenSlide: false });
256
588
  return;
257
589
  }
258
- const text = new OfficeText(prefix);
590
+ const text = new OfficeText(prefix, limits, count);
259
591
  let stopped = false;
592
+ let pausing = false;
593
+ let ended = false;
260
594
  const stream = file.internalStream("string");
595
+ const stop = (error: unknown) => {
596
+ if (stopped) return;
597
+ stopped = true;
598
+ stream.pause();
599
+ reject(error);
600
+ };
601
+ const finish = () => {
602
+ try {
603
+ resolve({ paragraphs: text.texts(), hiddenSlide: text.hiddenSlide });
604
+ } catch (error) {
605
+ stop(error);
606
+ }
607
+ };
261
608
  stream
262
609
  .on("data", (chunk) => {
263
610
  if (stopped) return;
611
+ if (input?.signal?.aborted) {
612
+ stop(input.signal.reason);
613
+ return;
614
+ }
264
615
  unpacked += chunk.length;
265
616
  if (unpacked > limit) {
266
- stopped = true;
267
- stream.pause();
268
- reject(new Error(refusal));
617
+ stop(new Error(refusal));
269
618
  return;
270
619
  }
271
- text.write(chunk);
272
- })
273
- .on("error", (error) => {
274
- stopped = true;
275
- reject(error);
620
+ try {
621
+ text.write(chunk);
622
+ } catch (error) {
623
+ stop(error);
624
+ return;
625
+ }
626
+ if (!pausing && slicer.due) {
627
+ pausing = true;
628
+ stream.pause();
629
+ slicer.pauseNow().then(() => {
630
+ pausing = false;
631
+ if (stopped) return;
632
+ if (ended) finish();
633
+ else stream.resume();
634
+ }, stop);
635
+ }
276
636
  })
637
+ .on("error", stop)
277
638
  .on("end", () => {
278
- if (!stopped) resolve(text.texts());
639
+ ended = true;
640
+ if (!stopped && !pausing) finish();
279
641
  })
280
642
  .resume();
281
643
  });
282
644
  }
283
645
 
284
- async function loadZip(bytes: Uint8Array): Promise<ZipArchive> {
646
+ /**
647
+ * The parts an Office file may have, at most. A deck of 2,000 slides with notes and pictures has
648
+ * about 12,000. JSZip reads the header of every part into memory before any part is unpacked:
649
+ * about 2 KB each, and 300,000 empty parts took over 500 MB.
650
+ */
651
+ const MAX_ZIP_ENTRIES = 20_000;
652
+ /**
653
+ * The extra fields the parts of an Office file may have, together. Office writes none, other ZIP
654
+ * programs one to three for each part. JSZip keeps about 250 bytes for each field of 4 bytes: a
655
+ * file of 4 MB made only of them took 250 MB.
656
+ */
657
+ const MAX_ZIP_EXTRA_FIELDS = 4 * MAX_ZIP_ENTRIES;
658
+ /**
659
+ * The bytes JSZip may turn into text, or go through one by one, from the directory of an Office
660
+ * file: names, comments, and the data of three kinds of extra field (see ZipDirectory). The Office
661
+ * files we tried had at most 68 KB. A name can be decoded from the same bytes for many parts, and
662
+ * the data of a field can run over the records after it, so the size of the file does not bound
663
+ * them: 2,000 parts of a 0.17 MB file took JSZip over 256 MB. A file just under this limit and the
664
+ * two above took JSZip under 0.5 s and 140 MB.
665
+ */
666
+ const MAX_ZIP_TEXT_BYTES = 8 * 1024 * 1024;
667
+
668
+ async function loadZip(bytes: Uint8Array, kind: "DOCX" | "PPTX"): Promise<ZipArchive> {
285
669
  let JSZip: { loadAsync(data: Uint8Array): Promise<ZipArchive> };
286
670
  try {
287
671
  JSZip = (await import("jszip")).default as unknown as typeof JSZip;
288
672
  } catch {
289
673
  throw new Error("Reading DOCX and PPTX files needs the optional dependency \"jszip\".");
290
674
  }
675
+ // The directory is read first, as JSZip will read it: the count of parts it gives may say
676
+ // anything.
677
+ const directory = readZipDirectory(bytes, { parts: MAX_ZIP_ENTRIES, extraFields: MAX_ZIP_EXTRA_FIELDS, textBytes: MAX_ZIP_TEXT_BYTES });
678
+ if (directory?.endless) {
679
+ throw new Error(`This ${kind} ends with a ZIP64 record that cannot be read, and reading it could hold the server without end. It may be built to exhaust the server, so it is not read.`);
680
+ }
681
+ if (directory && directory.parts > MAX_ZIP_ENTRIES) {
682
+ throw new Error(`This ${kind} has more than ${MAX_ZIP_ENTRIES.toLocaleString("en-US")} parts, more than an Office document has. It may be built to exhaust the server, so it is not read.`);
683
+ }
684
+ // A mass of extra fields, or of names, comments and field data: no Office program writes either.
685
+ if (directory && (directory.extraFields > MAX_ZIP_EXTRA_FIELDS || directory.textBytes > MAX_ZIP_TEXT_BYTES)) {
686
+ throw new Error(`This ${kind} lists its parts in a way that no Office program does: reading the list would take far more memory or time than an Office document needs. It may be built to exhaust the server, so it is not read.`);
687
+ }
291
688
  return JSZip.loadAsync(bytes);
292
689
  }
293
690
 
294
- const docx: Extractor = async (bytes) => {
295
- const archive = await loadZip(bytes);
691
+ const docx: Extractor = async (bytes, input) => {
692
+ input?.signal?.throwIfAborted();
693
+ const archive = await loadZip(bytes, "DOCX");
694
+ input?.signal?.throwIfAborted();
296
695
  const names = Object.keys(archive.files)
297
696
  .filter((name) => /^word\/(document|header\d+|footer\d+|footnotes|endnotes)\.xml$/i.test(name))
298
697
  .sort((left, right) => left === "word/document.xml" ? -1 : right === "word/document.xml" ? 1 : left.localeCompare(right));
299
698
  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);
699
+ const read = officeReader(archive, "DOCX", bytes.byteLength, input);
301
700
  const sections: string[] = [];
302
- for (const name of names) sections.push((await read(name, "w")).join("\n"));
701
+ for (const [index, name] of names.entries()) {
702
+ sections.push((await read(name, "w")).paragraphs.join("\n"));
703
+ input?.onProgress?.({ done: index + 1, total: names.length, unit: "parts" });
704
+ }
303
705
  return { text: sections.filter(Boolean).join("\n\n") };
304
706
  };
305
707
 
306
- const pptx: Extractor = async (bytes) => {
307
- const archive = await loadZip(bytes);
708
+ const pptx: Extractor = async (bytes, input) => {
709
+ input?.signal?.throwIfAborted();
710
+ const archive = await loadZip(bytes, "PPTX");
711
+ input?.signal?.throwIfAborted();
308
712
  const slideNumber = (name: string) => Number(/slide(\d+)\.xml$/i.exec(name)?.[1] ?? Number.MAX_SAFE_INTEGER);
309
713
  const names = Object.keys(archive.files)
310
714
  .filter((name) => /^ppt\/slides\/slide\d+\.xml$/i.test(name))
311
715
  .sort((left, right) => slideNumber(left) - slideNumber(right));
312
716
  if (names.length === 0) throw new Error("This PPTX does not contain any slides.");
313
- const read = officeReader(archive, "PPTX", bytes.byteLength);
717
+ const read = officeReader(archive, "PPTX", bytes.byteLength, input);
314
718
  const slides: string[] = [];
315
- for (const name of names) {
316
- const text = (await read(name, "a")).join("\n");
317
- slides.push(`## Slide ${slideNumber(name)}\n${text || "[No text on this slide]"}`);
719
+ for (const [index, name] of names.entries()) {
720
+ const { paragraphs, hiddenSlide } = await read(name, "a");
721
+ const text = paragraphs.join("\n");
722
+ // A hidden slide keeps its text, and says that the slide show skips it.
723
+ slides.push(`## Slide ${slideNumber(name)}${hiddenSlide ? ` ${HIDDEN_SLIDE}` : ""}\n${text || "[No text on this slide]"}`);
724
+ input?.onProgress?.({ done: index + 1, total: names.length, unit: "parts" });
318
725
  }
319
726
  return { text: slides.join("\n\n"), pages: names.length };
320
727
  };
@@ -332,8 +739,37 @@ export type PdfExtractorOptions = {
332
739
  * optional dependency `@cantoo/pdf-lib`; without it, and with false, the text is that of 0.2.0.
333
740
  */
334
741
  pictures?: boolean;
742
+ /**
743
+ * Before pdf.js reads any page, add up what each page would make it run, and refuse a file with
744
+ * a page that would hold the server for a long time: pdf.js reads a page in one block that no
745
+ * time limit can cut short. Defaults to true. It needs the optional dependency
746
+ * `@cantoo/pdf-lib`. With false, and `pictures: false`, the file is not read with it at ingest.
747
+ */
748
+ checkPages?: boolean;
335
749
  };
336
750
 
751
+ /**
752
+ * A page tree that lists one page more than once makes the text of that page come back each time:
753
+ * a 3 KB file built that way held 107 MB of text. PDF writers do not do this.
754
+ */
755
+ const REPEATED_PAGE = "This PDF lists the same page more than once. A file built that way can hold far more text than its size, so it is not read. Print it to a new PDF, and attach that.";
756
+ /**
757
+ * pdf.js reads the text of a page in one go, and nothing can stop it. A page that paints forms
758
+ * inside forms, or whose content is packed hundreds of times, held the server for 6 s to 2 minutes
759
+ * from files of 2 to 650 KB. Such a page is found before pdf.js reads it (see pdf-work.ts).
760
+ */
761
+ const HEAVY_PAGE = (page: number) => `Page ${page} of this PDF draws far more than its file holds, and reading it would hold the server for a long time. A file built that way is not read: it may be built to exhaust the server. Print it to a new PDF, and attach that.`;
762
+ const HEAVY_FILE = "This PDF draws far more than its file holds, and reading it would hold the server for a long time. A file built that way is not read: it may be built to exhaust the server. Print it to a new PDF, and attach that.";
763
+ const UNREADABLE_PAGE = (page: number) => `Page ${page} of this PDF stores its content in a way that cannot be checked before it is read, so it is not read. Print it to a new PDF, and attach that.`;
764
+ /**
765
+ * The text of a PDF is smaller than the file: fonts and pictures take room, and text is
766
+ * compressed. A page that paints one form inside another, many times over, draws the text of the
767
+ * innermost form each time: a file of a few kilobytes can draw megabytes. Past the first 16 MB,
768
+ * text over this many times the size of the file is refused as it is read.
769
+ */
770
+ const MAX_PDF_EXPANSION = 100;
771
+ const PDF_ALLOWANCE = 16 * 1024 * 1024;
772
+
337
773
  /** Written in place of a page that has no text at all, so the model can say so instead of guessing. */
338
774
  const PAGE_WITHOUT_TEXT = "[No text on this page. It may be a scan, a photo, or a chart.]";
339
775
  /**
@@ -342,6 +778,59 @@ const PAGE_WITHOUT_TEXT = "[No text on this page. It may be a scan, a photo, or
342
778
  */
343
779
  export const PICTURE_ON_PAGE = "[Picture on this page. This text cannot show it.]";
344
780
 
781
+ /**
782
+ * The progress of the pages of one stage of reading a PDF, for `ExtractInput.onProgress`. The page
783
+ * check and the picture marks give up quietly on an error of their own: an error of the listener is
784
+ * kept, and `rethrow` throws it once they are done, as it would anywhere else.
785
+ */
786
+ function pageProgress(input: ExtractInput | undefined, stage: ExtractProgress["stage"]): { report?: (done: number, total: number) => void; rethrow(): void } {
787
+ const listener = input?.onProgress;
788
+ if (!listener) return { rethrow() {} };
789
+ let failed: { error: unknown } | undefined;
790
+ return {
791
+ report(done, total) {
792
+ try {
793
+ listener({ stage, done, total, unit: "pages" });
794
+ } catch (error) {
795
+ failed ??= { error };
796
+ throw error;
797
+ }
798
+ },
799
+ rethrow() {
800
+ if (failed) throw failed.error;
801
+ },
802
+ };
803
+ }
804
+
805
+ /**
806
+ * Loads pdf.js through `unpdf`, and refuses a version of unpdf that cannot read PDFs on this
807
+ * version of Node (`node`, as in `process.versions.node`), with a message that says what to install:
808
+ * - unpdf 1.9 and later load a pdf.js that needs Node 22: on Node 20, every PDF fails.
809
+ * - pdf.js calls `Promise.try`, which Node 20 and 22 do not have (Node 24 does). unpdf adds it
810
+ * where it is missing, but 1.5.0 to 1.6.0 do not: there, the first PDF throws where nothing can
811
+ * catch it, and the whole process stops.
812
+ * The messages give the major version of Node only: an upload can be answered with them.
813
+ */
814
+ export async function checkUnpdf(unpdf: { getResolvedPDFJS?: unknown }, node: string = process.versions.node): Promise<void> {
815
+ if (typeof unpdf.getResolvedPDFJS !== "function") return;
816
+ const major = Number.parseInt(node, 10);
817
+ try {
818
+ await (unpdf.getResolvedPDFJS as () => Promise<unknown>)();
819
+ } catch (error) {
820
+ if (major >= 22) throw error;
821
+ const reason = error instanceof Error ? error.message : String(error);
822
+ throw new Error(`The unpdf installed cannot read PDF files on Node ${major} (${reason}). Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 22 or later.`);
823
+ }
824
+ if (typeof (Promise as { try?: unknown }).try !== "function") {
825
+ const advice = major < 22
826
+ ? "Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 24 or later."
827
+ : major < 24
828
+ ? "Install unpdf 1.6.1 or later, or run Node 24 or later."
829
+ : "Install unpdf 1.6.1 or later.";
830
+ throw new Error(`The unpdf installed would stop the whole server at the first PDF file on Node ${major}, so PDF files are not read. ${advice}`);
831
+ }
832
+ }
833
+
345
834
  /**
346
835
  * The built-in PDF extractor (needs `unpdf`). Use it to change an option:
347
836
  * `createLargeFiles({ extractors: { pdf: createPdfExtractor({ tables: false }) } })`.
@@ -349,6 +838,7 @@ export const PICTURE_ON_PAGE = "[Picture on this page. This text cannot show it.
349
838
  export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor {
350
839
  const tables = options.tables ?? true;
351
840
  const pictures = options.pictures ?? true;
841
+ const checkPages = options.checkPages ?? true;
352
842
  return async (bytes, input) => {
353
843
  let unpdf: typeof import("unpdf");
354
844
  try {
@@ -356,13 +846,55 @@ export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor
356
846
  } catch {
357
847
  throw new Error("Reading PDF files needs the optional dependency \"unpdf\".");
358
848
  }
849
+ await checkUnpdf(unpdf);
850
+ const signal = input?.signal;
851
+ signal?.throwIfAborted();
359
852
  // pdf.js may detach the buffer it reads, so give it a copy.
360
853
  const document = await unpdf.getDocumentProxy(new Uint8Array(bytes));
854
+ const maxPages = input?.maxPages;
855
+ if (maxPages !== undefined && document.numPages > maxPages) {
856
+ throw new Error(`This PDF has ${document.numPages.toLocaleString("en-US")} pages, more than the ${maxPages.toLocaleString("en-US")} read from one file. Split it, and attach the part you need.`);
857
+ }
858
+ // Read once with @cantoo/pdf-lib, when it is installed: to refuse a page that would hold the
859
+ // server before pdf.js reads it, and to mark the pages that show a picture.
860
+ let parsed = checkPages || pictures ? await parsePdf(bytes, signal) : undefined;
861
+ signal?.throwIfAborted();
862
+ if (parsed && checkPages) {
863
+ const checked = pageProgress(input, "check");
864
+ try {
865
+ await checkPageWork(parsed.library, parsed.document, bytes.byteLength, signal, checked.report);
866
+ } catch (error) {
867
+ if (error instanceof HeavyPage) throw new Error(error.reason === "unreadable" ? UNREADABLE_PAGE(error.page) : error.reason === "file" ? HEAVY_FILE : HEAVY_PAGE(error.page));
868
+ signal?.throwIfAborted();
869
+ checked.rethrow();
870
+ // Anything else unusual in the file: the check is given up, and the text is read as before.
871
+ }
872
+ }
873
+ if (!pictures) parsed = undefined;
874
+ const maxTextBytes = input?.maxTextBytes ?? Number.POSITIVE_INFINITY;
875
+ const mostDrawn = Math.max(PDF_ALLOWANCE, bytes.byteLength * MAX_PDF_EXPANSION);
876
+ const tooMuchText = () => new Error(maxTextBytes <= mostDrawn
877
+ ? `This PDF holds more than ${formatBytes(maxTextBytes)} of text, more than is kept from one file. Split it, and attach the part you need.`
878
+ : `This PDF draws more than ${formatBytes(mostDrawn)} of text, over ${MAX_PDF_EXPANSION} times its size. A file that grows that much is not read: it may be built to exhaust the server.`);
879
+ const textLimit = Math.min(maxTextBytes, mostDrawn);
361
880
  const texts: string[] = [];
362
881
  const geometry: PageGeometry[] = [];
882
+ /** The page objects read so far: a page tree that lists one page twice is refused. */
883
+ const seen = new Set<string>();
884
+ // pdf.js reads a page through promises that never let a timer or another request run: other
885
+ // requests get a turn every few milliseconds, or a 2,000-page file holds the server for seconds.
886
+ const slicer = new TimeSlicer(signal);
887
+ let textBytes = 0;
363
888
  let hasText = false;
364
889
  for (let number = 1; number <= document.numPages; number++) {
890
+ signal?.throwIfAborted();
365
891
  const page = await document.getPage(number);
892
+ const ref = page.ref;
893
+ if (ref) {
894
+ const key = `${ref.num} ${ref.gen}`;
895
+ if (seen.has(key)) throw new Error(REPEATED_PAGE);
896
+ seen.add(key);
897
+ }
366
898
  const content = await page.getTextContent();
367
899
  const items = (content.items as unknown[]).filter((item): item is PdfTextItem => typeof (item as PdfTextItem).str === "string");
368
900
  const transform = page.getViewport({ scale: 1 }).transform as number[];
@@ -380,9 +912,14 @@ export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor
380
912
  }
381
913
  text = text.trim();
382
914
  if (text) hasText = true;
915
+ // Counted as it is read: a small file can draw far more text than its own size.
916
+ textBytes += utf8Bytes(text);
917
+ if (textBytes > textLimit) throw tooMuchText();
383
918
  texts.push(text);
384
919
  geometry.push({ view: page.view, transform, tables: found });
385
920
  page.cleanup();
921
+ input?.onProgress?.({ done: number, total: document.numPages, unit: "pages" });
922
+ await slicer.maybePause();
386
923
  }
387
924
  if (!hasText) {
388
925
  // A scan has nothing to search, but a short one can be read by looking at its pages, when the
@@ -390,11 +927,14 @@ export function createPdfExtractor(options: PdfExtractorOptions = {}): Extractor
390
927
  const most = input?.scannedPages ?? 0;
391
928
  if (most <= 0) throw new Error("This PDF has no text layer (it may be scanned). It needs OCR before it can be searched.");
392
929
  if (document.numPages > most) {
393
- throw new Error(`This PDF has no text layer (it may be scanned) and ${document.numPages} pages. Without text it can only be read by looking at its pages, which works for up to ${most} pages. It needs OCR first.`);
930
+ throw new Error(`This PDF has no text layer (it may be scanned) and ${document.numPages} pages. Without text it can only be read by looking at its pages, which works for up to ${most} ${plural(most, "page")}. It needs OCR first.`);
394
931
  }
395
932
  }
396
933
  // Which pages show a picture. Undefined when that could not be found out: then none is marked.
397
- const pictured = pictures ? await findPicturePages(bytes, geometry) : undefined;
934
+ const looked = pageProgress(input, "pictures");
935
+ const pictured = pictures ? await findPicturePages(parsed, geometry, signal, looked.report) : undefined;
936
+ signal?.throwIfAborted();
937
+ looked.rethrow();
398
938
  const pages = texts.map((text, index) => `--- Page ${index + 1} ---\n${pictured?.[index] ? `${PICTURE_ON_PAGE}\n` : ""}${text || PAGE_WITHOUT_TEXT}`);
399
939
  return { text: pages.join("\n\n"), pages: document.numPages };
400
940
  };