llm-large-files 0.7.0 → 0.8.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 (184) hide show
  1. package/CHANGELOG.md +319 -1
  2. package/README.md +10 -8
  3. package/dist/analyze.d.ts +3 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +109 -14
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts.map +1 -1
  8. package/dist/anthropic/adapter.js +4 -1
  9. package/dist/anthropic/adapter.js.map +1 -1
  10. package/dist/ask.d.ts +3 -3
  11. package/dist/ask.d.ts.map +1 -1
  12. package/dist/ask.js +72 -17
  13. package/dist/ask.js.map +1 -1
  14. package/dist/decode.d.ts +19 -0
  15. package/dist/decode.d.ts.map +1 -0
  16. package/dist/decode.js +97 -0
  17. package/dist/decode.js.map +1 -0
  18. package/dist/errors.d.ts +55 -0
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/errors.js +65 -0
  21. package/dist/errors.js.map +1 -1
  22. package/dist/events.d.ts +6 -0
  23. package/dist/events.d.ts.map +1 -1
  24. package/dist/events.js +5 -1
  25. package/dist/events.js.map +1 -1
  26. package/dist/evidence.d.ts.map +1 -1
  27. package/dist/evidence.js +6 -0
  28. package/dist/evidence.js.map +1 -1
  29. package/dist/extract.d.ts +7 -20
  30. package/dist/extract.d.ts.map +1 -1
  31. package/dist/extract.js +49 -751
  32. package/dist/extract.js.map +1 -1
  33. package/dist/gemini/adapter.d.ts.map +1 -1
  34. package/dist/gemini/adapter.js +9 -5
  35. package/dist/gemini/adapter.js.map +1 -1
  36. package/dist/gemini/endpoints.d.ts +5 -1
  37. package/dist/gemini/endpoints.d.ts.map +1 -1
  38. package/dist/gemini/endpoints.js +11 -2
  39. package/dist/gemini/endpoints.js.map +1 -1
  40. package/dist/gemini/generate.d.ts.map +1 -1
  41. package/dist/gemini/generate.js +20 -3
  42. package/dist/gemini/generate.js.map +1 -1
  43. package/dist/groups.d.ts +54 -0
  44. package/dist/groups.d.ts.map +1 -0
  45. package/dist/groups.js +136 -0
  46. package/dist/groups.js.map +1 -0
  47. package/dist/html.d.ts +11 -0
  48. package/dist/html.d.ts.map +1 -0
  49. package/dist/html.js +1112 -0
  50. package/dist/html.js.map +1 -0
  51. package/dist/index.d.ts +2 -1
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +1 -1
  54. package/dist/index.js.map +1 -1
  55. package/dist/library.d.ts.map +1 -1
  56. package/dist/library.js +48 -12
  57. package/dist/library.js.map +1 -1
  58. package/dist/limiter.d.ts +2 -1
  59. package/dist/limiter.d.ts.map +1 -1
  60. package/dist/limiter.js +3 -2
  61. package/dist/limiter.js.map +1 -1
  62. package/dist/model.d.ts.map +1 -1
  63. package/dist/model.js +8 -1
  64. package/dist/model.js.map +1 -1
  65. package/dist/node/handlers.d.ts.map +1 -1
  66. package/dist/node/handlers.js +69 -15
  67. package/dist/node/handlers.js.map +1 -1
  68. package/dist/node/index.d.ts +2 -0
  69. package/dist/node/index.d.ts.map +1 -1
  70. package/dist/node/index.js +1 -0
  71. package/dist/node/index.js.map +1 -1
  72. package/dist/node/ingest-child.d.ts +38 -0
  73. package/dist/node/ingest-child.d.ts.map +1 -0
  74. package/dist/node/ingest-child.js +42 -0
  75. package/dist/node/ingest-child.js.map +1 -0
  76. package/dist/node/isolated.d.ts +88 -0
  77. package/dist/node/isolated.d.ts.map +1 -0
  78. package/dist/node/isolated.js +381 -0
  79. package/dist/node/isolated.js.map +1 -0
  80. package/dist/office.d.ts +105 -0
  81. package/dist/office.d.ts.map +1 -0
  82. package/dist/office.js +1092 -0
  83. package/dist/office.js.map +1 -0
  84. package/dist/openai/adapter.d.ts.map +1 -1
  85. package/dist/openai/adapter.js +15 -1
  86. package/dist/openai/adapter.js.map +1 -1
  87. package/dist/pdf-pages.d.ts.map +1 -1
  88. package/dist/pdf-pages.js +2 -6
  89. package/dist/pdf-pages.js.map +1 -1
  90. package/dist/peers.d.ts +8 -0
  91. package/dist/peers.d.ts.map +1 -0
  92. package/dist/peers.js +32 -0
  93. package/dist/peers.js.map +1 -0
  94. package/dist/plan.d.ts.map +1 -1
  95. package/dist/plan.js +1 -1
  96. package/dist/plan.js.map +1 -1
  97. package/dist/ranged.d.ts.map +1 -1
  98. package/dist/ranged.js +4 -2
  99. package/dist/ranged.js.map +1 -1
  100. package/dist/search.d.ts +99 -22
  101. package/dist/search.d.ts.map +1 -1
  102. package/dist/search.js +744 -140
  103. package/dist/search.js.map +1 -1
  104. package/dist/text-index.d.ts +3 -1
  105. package/dist/text-index.d.ts.map +1 -1
  106. package/dist/text-index.js +3 -1
  107. package/dist/text-index.js.map +1 -1
  108. package/dist/text.d.ts +27 -3
  109. package/dist/text.d.ts.map +1 -1
  110. package/dist/text.js +225 -23
  111. package/dist/text.js.map +1 -1
  112. package/dist/tools.d.ts.map +1 -1
  113. package/dist/tools.js +200 -12
  114. package/dist/tools.js.map +1 -1
  115. package/dist/types.d.ts +3 -3
  116. package/dist/types.d.ts.map +1 -1
  117. package/dist/word-styles.d.ts +102 -0
  118. package/dist/word-styles.d.ts.map +1 -0
  119. package/dist/word-styles.js +419 -0
  120. package/dist/word-styles.js.map +1 -0
  121. package/dist/xlsx.d.ts +23 -0
  122. package/dist/xlsx.d.ts.map +1 -0
  123. package/dist/xlsx.js +511 -0
  124. package/dist/xlsx.js.map +1 -0
  125. package/dist/xml-stream.d.ts +55 -0
  126. package/dist/xml-stream.d.ts.map +1 -0
  127. package/dist/xml-stream.js +235 -0
  128. package/dist/xml-stream.js.map +1 -0
  129. package/docs/README.md +8 -8
  130. package/docs/getting-started.md +1 -1
  131. package/docs/guides/costs-and-limits.md +7 -5
  132. package/docs/guides/deployment.md +95 -29
  133. package/docs/guides/errors-and-reliability.md +23 -10
  134. package/docs/guides/pdfs.md +127 -74
  135. package/docs/guides/storage.md +1 -1
  136. package/docs/guides/testing.md +5 -1
  137. package/docs/guides/web-app.md +10 -9
  138. package/docs/how-it-works.md +73 -50
  139. package/docs/reference/ask.md +26 -8
  140. package/docs/reference/errors-and-retries.md +5 -3
  141. package/docs/reference/events.md +14 -6
  142. package/docs/reference/gemini.md +6 -2
  143. package/docs/reference/library.md +205 -74
  144. package/docs/reference/node.md +200 -22
  145. package/docs/reference/openai.md +1 -1
  146. package/docs/reference/tools.md +170 -22
  147. package/docs/security.md +114 -69
  148. package/docs/troubleshooting.md +40 -20
  149. package/package.json +6 -2
  150. package/src/analyze.ts +117 -13
  151. package/src/anthropic/adapter.ts +4 -1
  152. package/src/ask.ts +73 -17
  153. package/src/decode.ts +89 -0
  154. package/src/errors.ts +108 -0
  155. package/src/events.ts +10 -1
  156. package/src/evidence.ts +6 -0
  157. package/src/extract.ts +52 -709
  158. package/src/gemini/adapter.ts +9 -5
  159. package/src/gemini/endpoints.ts +12 -2
  160. package/src/gemini/generate.ts +19 -3
  161. package/src/groups.ts +162 -0
  162. package/src/html.ts +1071 -0
  163. package/src/index.ts +2 -1
  164. package/src/library.ts +43 -12
  165. package/src/limiter.ts +6 -1
  166. package/src/model.ts +8 -1
  167. package/src/node/handlers.ts +66 -16
  168. package/src/node/index.ts +2 -0
  169. package/src/node/ingest-child.ts +61 -0
  170. package/src/node/isolated.ts +464 -0
  171. package/src/office.ts +1047 -0
  172. package/src/openai/adapter.ts +14 -1
  173. package/src/pdf-pages.ts +2 -5
  174. package/src/peers.ts +29 -0
  175. package/src/plan.ts +2 -0
  176. package/src/ranged.ts +4 -2
  177. package/src/search.ts +738 -146
  178. package/src/text-index.ts +4 -2
  179. package/src/text.ts +214 -23
  180. package/src/tools.ts +192 -12
  181. package/src/types.ts +3 -3
  182. package/src/word-styles.ts +420 -0
  183. package/src/xlsx.ts +478 -0
  184. package/src/xml-stream.ts +224 -0
package/src/index.ts CHANGED
@@ -53,7 +53,8 @@ export { parseSseJson, SseEventTooLongError } from "./sse.js";
53
53
  export type { SseHooks } from "./sse.js";
54
54
  export { DEFAULT_FIRST_BYTE_TIMEOUT_MS, DEFAULT_IDLE_TIMEOUT_MS } from "./http.js";
55
55
  export type { IdleWaits } from "./http.js";
56
- export { DocumentStoreError } from "./errors.js";
56
+ export { DocumentStoreError, IngestError, ingestErrorCodeOf } from "./errors.js";
57
+ export type { IngestErrorCode } from "./errors.js";
57
58
  export { FileDocumentStore, MemoryDocumentStore, DOCUMENT_ID_PATTERN } from "./stores.js";
58
59
  export { createPdfExtractor, defaultExtractors, detectFormat } from "./extract.js";
59
60
  export type { PdfExtractorOptions } from "./extract.js";
package/src/library.ts CHANGED
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { buildLogProfileInSlices, buildOutlineInSlices, looksLikeLog } from "./analyze.js";
3
3
  import { givenBudget, resolveBudget, type ModelLimits } from "./budget.js";
4
4
  import { DocumentCache, documentVersion, type Sized } from "./cache.js";
5
- import { DocumentStoreError, noteStoreWriteFailure } from "./errors.js";
5
+ import { DocumentStoreError, isStoreWriteFailure, noteStoreWriteFailure, toIngestError } from "./errors.js";
6
6
  import { EventEmitter, eventErrorOf, newRunId, type IngestEvent, type IngestStage } from "./events.js";
7
7
  import { detectFormat, extractText } from "./extract.js";
8
8
  import { Limiter } from "./limiter.js";
@@ -477,6 +477,19 @@ class IngestProgress {
477
477
  /** Default for `wholeDocumentBytes`. */
478
478
  export const DEFAULT_WHOLE_DOCUMENT_BYTES = 2 * 1024 * 1024;
479
479
 
480
+ /**
481
+ * A number option as it was given, or `fallback` when it was left out. NaN, which
482
+ * `Number(process.env.X)` gives for a variable that is not set, and a value that is not a number
483
+ * are an error: NaN passes every `Math.max` and fails every comparison, so it hung the scans or
484
+ * turned a limit off. `finite` refuses `Infinity` too, for an option that cannot be endless.
485
+ */
486
+ function numberOption(name: string, value: unknown, fallback: number, finite = false): number {
487
+ if (value === undefined) return fallback;
488
+ if (typeof value !== "number") throw new TypeError(`${name} must be a number, and is ${typeof value === "string" ? JSON.stringify(value) : typeof value}.`);
489
+ if (Number.isNaN(value) || (finite && !Number.isFinite(value))) throw new RangeError(`${name} must be a ${finite ? "finite " : ""}number, and is ${value}. Leave it out for the default.`);
490
+ return value;
491
+ }
492
+
480
493
  export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
481
494
  /** The fields the application set. The others follow the context window, whichever it is for a request. */
482
495
  const ownBudget = givenBudget(options.budget);
@@ -484,19 +497,19 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
484
497
  const budgetFor = (overrides?: Partial<Budget>, limits?: ModelLimits): Budget => (
485
498
  overrides || limits ? resolveBudget({ ...ownBudget, ...givenBudget(overrides) }, limits) : budget
486
499
  );
487
- const ttlMs = options.ttlMs ?? 72 * 60 * 60 * 1000;
488
- const maxUploadBytes = options.maxUploadBytes ?? 100 * 1024 * 1024;
500
+ const ttlMs = numberOption("ttlMs", options.ttlMs, 72 * 60 * 60 * 1000);
501
+ const maxUploadBytes = numberOption("maxUploadBytes", options.maxUploadBytes, 100 * 1024 * 1024);
489
502
  const given = (value: number | undefined, fallback: number) => (typeof value === "number" && !Number.isNaN(value) ? value : fallback);
490
503
  const maxTextBytes = Math.max(1, given(options.maxTextBytes, Math.max(maxUploadBytes, DEFAULT_MAX_TEXT_BYTES)));
491
504
  const maxPdfPages = Math.max(1, Math.trunc(given(options.maxPdfPages, DEFAULT_MAX_PDF_PAGES)));
492
505
  const ingestTimeoutMs = given(options.ingestTimeoutMs, DEFAULT_INGEST_TIMEOUT_MS);
493
506
  const now = options.now ?? (() => new Date());
494
507
  const { store } = options;
495
- const cacheBytes = Math.max(0, options.cacheBytes ?? DEFAULT_CACHE_BYTES);
508
+ const cacheBytes = Math.max(0, numberOption("cacheBytes", options.cacheBytes, DEFAULT_CACHE_BYTES));
496
509
  /** Documents ready to search, and decoded pieces of documents read by range, in one memory budget. */
497
510
  const cache = new DocumentCache<Sized>(
498
511
  cacheBytes,
499
- options.cacheSize === undefined ? Number.POSITIVE_INFINITY : Math.max(0, Math.trunc(options.cacheSize)),
512
+ Math.max(0, Math.trunc(numberOption("cacheSize", options.cacheSize, Number.POSITIVE_INFINITY))),
500
513
  );
501
514
  /** Forgets everything kept of a document: the document, and its pieces. */
502
515
  const forget = (id: string) => {
@@ -513,12 +526,12 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
513
526
  } : undefined;
514
527
  /** The uploaded file of a document, when the store keeps such files. */
515
528
  const loadOriginal = store.getOriginal ? (id: string) => reading(() => store.getOriginal!(id)) : undefined;
516
- const wholeDocumentBytes = Math.max(0, options.wholeDocumentBytes ?? DEFAULT_WHOLE_DOCUMENT_BYTES);
529
+ const wholeDocumentBytes = Math.max(0, numberOption("wholeDocumentBytes", options.wholeDocumentBytes, DEFAULT_WHOLE_DOCUMENT_BYTES));
517
530
  /** Documents whose saved index did not match their text: the next opening builds it from the text. */
518
531
  const rebuildIndex = new Set<string>();
519
532
  const scan: ScanSettings = {
520
- chunkBytes: Math.max(1, Math.trunc(options.scanChunkBytes ?? 1024 * 1024)),
521
- limiter: new Limiter(Math.max(1, Math.trunc(options.maxConcurrentScans ?? 4))),
533
+ chunkBytes: Math.max(1, Math.trunc(numberOption("scanChunkBytes", options.scanChunkBytes, 1024 * 1024, true))),
534
+ limiter: new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentScans", options.maxConcurrentScans, 4)))),
522
535
  onBroken: (id) => {
523
536
  rebuildIndex.add(id);
524
537
  forget(id);
@@ -532,7 +545,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
532
545
  },
533
546
  };
534
547
  const keepOriginals = new Set<DocumentFormat>(options.keepOriginals ?? []);
535
- const scannedPdfPages = Math.max(0, Math.trunc(options.scannedPdfPages ?? 30));
548
+ const scannedPdfPages = Math.max(0, Math.trunc(numberOption("scannedPdfPages", options.scannedPdfPages, 30)));
536
549
  /** Whether the uploaded file of a document of this format is kept. */
537
550
  const keeps = (format: DocumentFormat) => keepOriginals.has(format) && typeof options.store.putOriginal === "function";
538
551
 
@@ -717,7 +730,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
717
730
  // Never, for a time to live without end (or one that runs past what a date can hold).
718
731
  expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
719
732
  };
720
- const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters
733
+ const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters && index.textBytes === meta.textBytes
721
734
  ? serializeTextIndex(index)
722
735
  : undefined;
723
736
  // Each write is reported once done. What the listener of the events throws is not the store's failure.
@@ -766,7 +779,17 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
766
779
 
767
780
  async ingest(input) {
768
781
  // The events first, so that every ingest that throws, even on what it was given, ends with ingest.error.
769
- const events = new EventEmitter<IngestEvent>(input?.runId ?? newRunId("ing"), input?.onEvent);
782
+ // What the caller's listener throws is passed on as it is, not told as a file that could not be read.
783
+ let listenerFailure: { error: unknown } | undefined;
784
+ const listener = input?.onEvent;
785
+ const events = new EventEmitter<IngestEvent>(input?.runId ?? newRunId("ing"), listener && ((event: IngestEvent) => {
786
+ try {
787
+ listener(event);
788
+ } catch (error) {
789
+ listenerFailure ??= { error };
790
+ throw error;
791
+ }
792
+ }));
770
793
  let storeFailed = false;
771
794
  try {
772
795
  if (events.active) events.emit({ type: "ingest.start", ...startOf(input) });
@@ -776,7 +799,15 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
776
799
  const format = detectFormat(name, mimeType);
777
800
  // Progress is worked out only for someone who listens.
778
801
  const progress = events.active ? new IngestProgress(events) : undefined;
779
- const meta = await ingestFile(input, name, mimeType, format, progress, () => (storeFailed = true));
802
+ let meta: DocumentMeta;
803
+ try {
804
+ meta = await ingestFile(input, name, mimeType, format, progress, () => (storeFailed = true));
805
+ } catch (error) {
806
+ // A store that failed, and a caller that gave up (its own reason), are passed on as they
807
+ // are; a file that could not be read is told with a code.
808
+ if (storeFailed || (input.signal?.aborted && error === input.signal.reason) || isStoreWriteFailure(error) || (listenerFailure && error === listenerFailure.error)) throw error;
809
+ throw toIngestError(error);
810
+ }
780
811
  try {
781
812
  events.emit({ type: "ingest.finish", document: toDocumentSummary(meta) });
782
813
  } catch (error) {
package/src/limiter.ts CHANGED
@@ -7,7 +7,12 @@ export class Limiter {
7
7
  private active = 0;
8
8
  private readonly waiting: Array<() => void> = [];
9
9
 
10
- constructor(private readonly max: number) {}
10
+ private readonly max: number;
11
+
12
+ /** `max` is at least 1: with NaN or 0 no slot was ever free, and every task waited forever. */
13
+ constructor(max: number) {
14
+ this.max = Number.isNaN(max) ? 1 : Math.max(1, Math.trunc(max));
15
+ }
11
16
 
12
17
  /** Waits for a slot. Call the returned function once to give it back. */
13
18
  async acquire(signal?: AbortSignal): Promise<() => void> {
package/src/model.ts CHANGED
@@ -421,7 +421,14 @@ export class UsageMeter {
421
421
  readonly totals: UsageTotals = { requests: 0, ...EMPTY_USAGE, byModel: {} };
422
422
 
423
423
  add(model: string, usage: Partial<ModelUsage> | undefined): void {
424
- const of = (this.totals.byModel[model] ??= { requests: 0, ...EMPTY_USAGE });
424
+ const { byModel } = this.totals;
425
+ // An own entry only: an id such as "__proto__" or "constructor" found what every object
426
+ // inherits, and "__proto__" then counted the usage into Object.prototype.
427
+ let of = Object.hasOwn(byModel, model) ? byModel[model] : undefined;
428
+ if (!of) {
429
+ of = { requests: 0, ...EMPTY_USAGE };
430
+ Object.defineProperty(byModel, model, { value: of, enumerable: true, writable: true, configurable: true });
431
+ }
425
432
  for (const sum of [this.totals, of]) {
426
433
  sum.requests++;
427
434
  for (const key of Object.keys(EMPTY_USAGE) as Array<keyof ModelUsage>) {
@@ -1,5 +1,5 @@
1
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
- import { isStoreWriteFailure } from "../errors.js";
2
+ import { IngestError, isStoreWriteFailure } from "../errors.js";
3
3
  import { eventStream, newRunId, type EventError, type IngestEvent } from "../events.js";
4
4
  import { checkOwner, toDocumentSummary, type IngestInput, type LargeFiles } from "../library.js";
5
5
  import { formatBytes } from "../plan.js";
@@ -84,10 +84,14 @@ function answerOf(error: unknown, failed: string, tooLarge: string): { status: n
84
84
  return { status: 500, message: code ? `${failed} (${code}).` : `${failed}.` };
85
85
  }
86
86
 
87
- /** Answers a failed request with JSON (see `answerOf`). */
88
- function fail(response: ServerResponse, error: unknown, failed: string, tooLarge: string): void {
87
+ /** Answers a failed request with JSON (see `answerOf`). A refusal that says when to try again (a busy reader) sets `Retry-After`. */
88
+ function fail(response: ServerResponse, error: unknown, failed: string, tooLarge: string, unread?: IncomingMessage): void {
89
89
  const { status, message } = answerOf(error, failed, tooLarge);
90
- send(response, status, { error: message });
90
+ const retryAfterMs = (error as { retryAfterMs?: unknown } | null)?.retryAfterMs;
91
+ if (status === 503 && typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) && !response.headersSent) {
92
+ response.setHeader("Retry-After", String(Math.max(1, Math.ceil(retryAfterMs / 1_000))));
93
+ }
94
+ send(response, status, { error: message }, unread);
91
95
  }
92
96
 
93
97
  /**
@@ -133,7 +137,9 @@ async function streamIngest(files: LargeFiles, input: IngestInput, response: Ser
133
137
  await stream.result;
134
138
  return { message: fallback.message, ...(fallback.status !== undefined ? { status: fallback.status } : {}) };
135
139
  } catch (error) {
136
- return answerOf(ingestFailure(error), "Upload failed", tooLarge);
140
+ const failure = ingestFailure(error);
141
+ // A file that could not be read also says why, for a page that tells it in its own words.
142
+ return { ...answerOf(failure, "Upload failed", tooLarge), ...(failure instanceof IngestError ? { code: failure.code } : {}) };
137
143
  }
138
144
  };
139
145
  async function* events(): AsyncGenerator<IngestEvent> {
@@ -160,11 +166,19 @@ async function streamIngest(files: LargeFiles, input: IngestInput, response: Ser
160
166
  await writeSseEvents(response, events());
161
167
  }
162
168
 
163
- function send(response: ServerResponse, status: number, value: unknown): void {
169
+ /**
170
+ * Answers with `value` as JSON. With `unread`, a request whose body was not read to its end (an
171
+ * upload refused as too large, or before it was read): the answer is written now, so that a client
172
+ * still sending reads it, and ended once the rest of the body is drained (see `drain`).
173
+ */
174
+ function send(response: ServerResponse, status: number, value: unknown, unread?: IncomingMessage): void {
164
175
  if (response.headersSent) return;
165
176
  response.statusCode = status;
166
177
  response.setHeader("Content-Type", "application/json; charset=utf-8");
167
- response.end(JSON.stringify(value));
178
+ const body = JSON.stringify(value);
179
+ if (!unread || unread.complete || unread.destroyed) return void response.end(body);
180
+ response.write(body);
181
+ drain(unread, response);
168
182
  }
169
183
 
170
184
  function header(request: IncomingMessage, name: string): string {
@@ -192,20 +206,54 @@ async function readBody(request: IncomingMessage, limit: number): Promise<Uint8A
192
206
  if (Number.isFinite(declared) && declared > limit) throw new HttpError(413, "");
193
207
  const chunks: Buffer[] = [];
194
208
  let size = 0;
195
- for await (const chunk of request) {
209
+ // Leaving the loop early must not destroy the request: the rest of the body is drained after
210
+ // the answer (see `drain`), which a destroyed request would not do.
211
+ for await (const chunk of request.iterator({ destroyOnReturn: false })) {
196
212
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);
197
213
  size += buffer.byteLength;
198
- if (size > limit) {
199
- // Stop buffering; drain the rest so the client can read the response.
200
- request.resume();
201
- throw new HttpError(413, "");
202
- }
214
+ if (size > limit) throw new HttpError(413, "");
203
215
  chunks.push(buffer);
204
216
  }
205
217
  const body = Buffer.concat(chunks);
206
218
  return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
207
219
  }
208
220
 
221
+ /**
222
+ * The most bytes of an upload's body that are read and dropped after it was answered before the
223
+ * body was read to its end (too large, no name). Past it the connection is closed.
224
+ */
225
+ const DRAIN_BYTES = 8 * 1024 * 1024;
226
+
227
+ /**
228
+ * Reads and drops the rest of a body that was answered before it was read to its end, up to
229
+ * `DRAIN_BYTES`, then ends the answer, which was written but not ended. The client, still
230
+ * sending, reads the answer and can use the connection again. Two things Node does shape this:
231
+ * it stops reading a request once its answer has ended, and its client stops sending once it has
232
+ * a whole answer (so the answer has no Content-Length, and ends only after the drain). Closing the
233
+ * connection at once instead makes some systems (Windows) reset it, and the client then never
234
+ * reads the answer. A body larger than `DRAIN_BYTES` is cut off: the answer ends, and the
235
+ * connection is closed.
236
+ */
237
+ function drain(request: IncomingMessage, response: ServerResponse): void {
238
+ let drained = 0;
239
+ const end = () => {
240
+ request.off("data", count);
241
+ if (!response.writableEnded) response.end();
242
+ };
243
+ const count = (chunk: Buffer | string) => {
244
+ drained += chunk.length;
245
+ if (drained <= DRAIN_BYTES) return;
246
+ end();
247
+ if (response.writableFinished) request.destroy();
248
+ else response.once("finish", () => request.destroy());
249
+ };
250
+ request.on("data", count);
251
+ request.once("end", end);
252
+ request.once("close", end);
253
+ request.on("error", () => {});
254
+ request.resume();
255
+ }
256
+
209
257
  /**
210
258
  * Upload, get, and delete handlers for any Node HTTP server (node:http, Express, Fastify via
211
259
  * `request.raw`/`reply.raw`, Next.js API routes on the Node runtime). Responses are JSON, except an upload that asks for
@@ -260,9 +308,11 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
260
308
  }
261
309
  send(response, 201, toDocumentSummary(meta));
262
310
  } catch (error) {
263
- fail(response, error, "Upload failed", tooLarge);
264
- // An event stream that failed after its headers were sent cannot answer with a status.
265
- if (response.headersSent && !response.writableEnded) response.end();
311
+ // Answered before the body was read to its end (too large, no name): the rest is drained.
312
+ fail(response, error, "Upload failed", tooLarge, request);
313
+ // An event stream that failed after its headers were sent cannot answer with a status. (An
314
+ // answer to a body still being drained is ended by `drain`.)
315
+ if (response.headersSent && !response.writableEnded && request.complete) response.end();
266
316
  }
267
317
  },
268
318
 
package/src/node/index.ts CHANGED
@@ -2,3 +2,5 @@ export { createDocumentHandlers } from "./handlers.js";
2
2
  export type { DocumentHandlerOptions, DocumentHandlers } from "./handlers.js";
3
3
  export { sseMessageOf, writeSseEvents } from "./sse.js";
4
4
  export type { SseMessage, SseWriteOptions } from "./sse.js";
5
+ export { createIsolatedExtractors } from "./isolated.js";
6
+ export type { IsolatedExtractorOptions, IsolatedExtractors } from "./isolated.js";
@@ -0,0 +1,61 @@
1
+ // The child process of `createIsolatedExtractors` (isolated.ts): it reads the files it is sent with
2
+ // the built-in extractors, one at a time, and answers over the IPC channel. It runs with a heap
3
+ // limit of its own: a file that would exhaust the memory kills this process, not the server.
4
+ import { createPdfExtractor, extractText, type PdfExtractorOptions } from "../extract.js";
5
+ import type { DocumentFormat, ExtractedText, ExtractProgress } from "../types.js";
6
+
7
+ /** A file to read. */
8
+ export type ChildJob = {
9
+ type: "extract";
10
+ id: number;
11
+ bytes: Uint8Array;
12
+ input: { name: string; mimeType: string; format: DocumentFormat; scannedPages?: number; maxTextBytes?: number; maxPages?: number; progress: boolean };
13
+ pdf?: PdfExtractorOptions;
14
+ };
15
+
16
+ /** What the child answers. */
17
+ export type ChildMessage =
18
+ | { type: "ready" }
19
+ | { type: "progress"; id: number; progress: ExtractProgress }
20
+ | { type: "done"; id: number; result: ExtractedText }
21
+ | { type: "error"; id: number; message: string; name: string; code?: string; syscall?: string };
22
+
23
+ const send = (message: ChildMessage) => {
24
+ process.send?.(message);
25
+ };
26
+
27
+ process.on("message", (message: ChildJob | { type: "abort"; id: number }) => {
28
+ if (message?.type === "extract") void run(message);
29
+ });
30
+
31
+ // The parent went away: nothing is left to answer.
32
+ process.on("disconnect", () => process.exit(0));
33
+
34
+ let pdfExtractor: { options: string; extract: ReturnType<typeof createPdfExtractor> } | undefined;
35
+
36
+ async function run(job: ChildJob): Promise<void> {
37
+ try {
38
+ const options = JSON.stringify(job.pdf ?? {});
39
+ if (job.input.format === "pdf" && pdfExtractor?.options !== options) pdfExtractor = { options, extract: createPdfExtractor(job.pdf ?? {}) };
40
+ const { progress, ...input } = job.input;
41
+ const result = await extractText(job.bytes, {
42
+ ...input,
43
+ ...(progress ? { onProgress: (report: ExtractProgress) => send({ type: "progress", id: job.id, progress: report }) } : {}),
44
+ }, job.input.format === "pdf" && pdfExtractor ? { pdf: pdfExtractor.extract } : {});
45
+ const { text, pages, encoding, replacedCharacters } = result;
46
+ send({ type: "done", id: job.id, result: { text, ...(pages !== undefined ? { pages } : {}), ...(encoding !== undefined ? { encoding } : {}), ...(replacedCharacters !== undefined ? { replacedCharacters } : {}) } });
47
+ } catch (error) {
48
+ // A system error keeps its code and system call: the server tells it apart from a file that cannot be read.
49
+ const { code, syscall } = (error ?? {}) as { code?: unknown; syscall?: unknown };
50
+ send({
51
+ type: "error",
52
+ id: job.id,
53
+ message: error instanceof Error ? error.message : String(error),
54
+ name: error instanceof Error ? error.name : "Error",
55
+ ...(typeof code === "string" ? { code } : {}),
56
+ ...(typeof syscall === "string" ? { syscall } : {}),
57
+ });
58
+ }
59
+ }
60
+
61
+ send({ type: "ready" });