llm-large-files 0.5.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.
- package/CHANGELOG.md +1719 -466
- package/README.md +190 -60
- package/dist/analyze.d.ts +8 -1
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +198 -54
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts +14 -3
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +194 -40
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +63 -7
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +1131 -214
- package/dist/ask.js.map +1 -1
- package/dist/decode.d.ts +19 -0
- package/dist/decode.d.ts.map +1 -0
- package/dist/decode.js +97 -0
- package/dist/decode.js.map +1 -0
- package/dist/encoding.d.ts +17 -0
- package/dist/encoding.d.ts.map +1 -0
- package/dist/encoding.js +852 -0
- package/dist/encoding.js.map +1 -0
- package/dist/errors.d.ts +59 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +80 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +339 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +163 -0
- package/dist/events.js.map +1 -0
- package/dist/evidence.d.ts +2 -0
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +9 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +26 -7
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +180 -314
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +17 -8
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +117 -66
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +23 -3
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +6 -2
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +5 -1
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +11 -2
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/errors.d.ts +9 -4
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +32 -0
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +10 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +33 -10
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -1
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -1
- package/dist/gemini/sse.js.map +1 -1
- package/dist/groups.d.ts +54 -0
- package/dist/groups.d.ts.map +1 -0
- package/dist/groups.js +136 -0
- package/dist/groups.js.map +1 -0
- package/dist/html.d.ts +11 -0
- package/dist/html.d.ts.map +1 -0
- package/dist/html.js +1112 -0
- package/dist/html.js.map +1 -0
- package/dist/http.d.ts +116 -0
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +347 -1
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +13 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -5
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +67 -5
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +449 -93
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -1
- package/dist/limiter.d.ts.map +1 -1
- package/dist/limiter.js +3 -2
- package/dist/limiter.js.map +1 -1
- package/dist/map-reduce.d.ts +28 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +240 -52
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +84 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +190 -2
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +184 -28
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +4 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +38 -0
- package/dist/node/ingest-child.d.ts.map +1 -0
- package/dist/node/ingest-child.js +42 -0
- package/dist/node/ingest-child.js.map +1 -0
- package/dist/node/isolated.d.ts +88 -0
- package/dist/node/isolated.d.ts.map +1 -0
- package/dist/node/isolated.js +381 -0
- package/dist/node/isolated.js.map +1 -0
- package/dist/node/sse.d.ts +59 -0
- package/dist/node/sse.d.ts.map +1 -0
- package/dist/node/sse.js +174 -0
- package/dist/node/sse.js.map +1 -0
- package/dist/office.d.ts +105 -0
- package/dist/office.d.ts.map +1 -0
- package/dist/office.js +1092 -0
- package/dist/office.js.map +1 -0
- package/dist/openai/adapter.d.ts +29 -5
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +325 -37
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +14 -2
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +39 -10
- package/dist/output-limit.js.map +1 -1
- package/dist/pause.d.ts +24 -0
- package/dist/pause.d.ts.map +1 -0
- package/dist/pause.js +38 -0
- package/dist/pause.js.map +1 -0
- package/dist/pdf-pages.d.ts +32 -2
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +277 -20
- package/dist/pdf-pages.js.map +1 -1
- package/dist/pdf-pictures.d.ts +30 -3
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +50 -8
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/pdf-work.d.ts +40 -0
- package/dist/pdf-work.d.ts.map +1 -0
- package/dist/pdf-work.js +734 -0
- package/dist/pdf-work.js.map +1 -0
- package/dist/peers.d.ts +8 -0
- package/dist/peers.d.ts.map +1 -0
- package/dist/peers.js +32 -0
- package/dist/peers.js.map +1 -0
- package/dist/plan.d.ts +22 -4
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +61 -12
- package/dist/plan.js.map +1 -1
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +4 -2
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +23 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +33 -3
- package/dist/retry.js.map +1 -1
- package/dist/search.d.ts +107 -24
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +803 -149
- package/dist/search.js.map +1 -1
- package/dist/sse.d.ts +35 -2
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +145 -31
- package/dist/sse.js.map +1 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +5 -2
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +9 -1
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +28 -9
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +87 -3
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +526 -24
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +61 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +461 -46
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +103 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/word-styles.d.ts +102 -0
- package/dist/word-styles.d.ts.map +1 -0
- package/dist/word-styles.js +419 -0
- package/dist/word-styles.js.map +1 -0
- package/dist/xlsx.d.ts +23 -0
- package/dist/xlsx.d.ts.map +1 -0
- package/dist/xlsx.js +511 -0
- package/dist/xlsx.js.map +1 -0
- package/dist/xml-stream.d.ts +55 -0
- package/dist/xml-stream.d.ts.map +1 -0
- package/dist/xml-stream.js +235 -0
- package/dist/xml-stream.js.map +1 -0
- package/dist/zip-directory.d.ts +43 -0
- package/dist/zip-directory.d.ts.map +1 -0
- package/dist/zip-directory.js +130 -0
- package/dist/zip-directory.js.map +1 -0
- package/docs/README.md +288 -0
- package/docs/api.md +37 -381
- package/docs/configuration.md +28 -558
- package/docs/getting-started.md +407 -223
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +728 -0
- package/docs/guides/deployment.md +720 -0
- package/docs/guides/errors-and-reliability.md +748 -0
- package/docs/guides/explorer-model.md +399 -0
- package/docs/guides/openai-compatible.md +602 -0
- package/docs/guides/own-adapter-and-loop.md +1169 -0
- package/docs/guides/pdfs.md +1024 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1203 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1590 -0
- package/docs/how-it-works.md +1035 -164
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +910 -0
- package/docs/reference/errors-and-retries.md +760 -0
- package/docs/reference/events.md +1001 -0
- package/docs/reference/gemini.md +827 -0
- package/docs/reference/library.md +1598 -0
- package/docs/reference/node.md +706 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +1031 -0
- package/docs/security.md +940 -101
- package/docs/troubleshooting.md +1410 -0
- package/package.json +7 -3
- package/src/analyze.ts +204 -49
- package/src/anthropic/adapter.ts +200 -40
- package/src/ask.ts +1151 -210
- package/src/decode.ts +89 -0
- package/src/encoding.ts +850 -0
- package/src/errors.ts +125 -0
- package/src/events.ts +451 -0
- package/src/evidence.ts +11 -2
- package/src/extract.ts +191 -308
- package/src/gemini/adapter.ts +127 -70
- package/src/gemini/chat.ts +28 -4
- package/src/gemini/endpoints.ts +12 -2
- package/src/gemini/errors.ts +34 -1
- package/src/gemini/generate.ts +42 -13
- package/src/gemini/index.ts +3 -3
- package/src/gemini/sse.ts +1 -1
- package/src/groups.ts +162 -0
- package/src/html.ts +1071 -0
- package/src/http.ts +376 -1
- package/src/index.ts +29 -6
- package/src/library.ts +498 -93
- package/src/limiter.ts +6 -1
- package/src/map-reduce.ts +252 -51
- package/src/model.ts +244 -4
- package/src/node/handlers.ts +196 -31
- package/src/node/index.ts +4 -0
- package/src/node/ingest-child.ts +61 -0
- package/src/node/isolated.ts +464 -0
- package/src/node/sse.ts +198 -0
- package/src/office.ts +1047 -0
- package/src/openai/adapter.ts +319 -38
- package/src/output-limit.ts +44 -8
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +270 -20
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/peers.ts +29 -0
- package/src/plan.ts +70 -12
- package/src/ranged.ts +4 -2
- package/src/retry.ts +49 -5
- package/src/search.ts +800 -155
- package/src/sse.ts +153 -28
- package/src/stores.ts +5 -2
- package/src/text-index.ts +30 -9
- package/src/text.ts +524 -23
- package/src/tools.ts +445 -46
- package/src/types.ts +108 -5
- package/src/word-styles.ts +420 -0
- package/src/xlsx.ts +478 -0
- package/src/xml-stream.ts +224 -0
- package/src/zip-directory.ts +136 -0
|
@@ -0,0 +1,706 @@
|
|
|
1
|
+
# `llm-large-files/node`
|
|
2
|
+
|
|
3
|
+
This page lists every export of `llm-large-files/node`: `createDocumentHandlers`, its options, and
|
|
4
|
+
the three HTTP handlers it returns, with the request each one expects and every status and body it
|
|
5
|
+
can answer; `createIsolatedExtractors`, which reads PDF and Office files in child processes with a
|
|
6
|
+
memory limit and a kill timer; and `writeSseEvents` and `sseMessageOf`, which send the events of a
|
|
7
|
+
question or an ingest to a browser as Server-Sent Events. It is for you if your server runs on Node
|
|
8
|
+
and you want uploads, look-ups and deletes of documents without writing the routes yourself, files
|
|
9
|
+
from users read apart from your server, or a streamed answer without writing the stream yourself.
|
|
10
|
+
How to mount them, what the browser sends, and how to read the stream in the browser are in the
|
|
11
|
+
guide [web app](../guides/web-app.md).
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { createDocumentHandlers, createIsolatedExtractors, sseMessageOf, writeSseEvents } from "llm-large-files/node";
|
|
15
|
+
import type {
|
|
16
|
+
DocumentHandlerOptions, DocumentHandlers, IsolatedExtractorOptions, IsolatedExtractors, SseMessage, SseWriteOptions,
|
|
17
|
+
} from "llm-large-files/node";
|
|
18
|
+
// What the signatures below use:
|
|
19
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
20
|
+
import type { DocumentFormat, Extractor, LargeFiles, PdfExtractorOptions } from "llm-large-files";
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Contents
|
|
24
|
+
|
|
25
|
+
- [`createDocumentHandlers()`](#createdocumenthandlersfiles-options)
|
|
26
|
+
- [`DocumentHandlerOptions`](#documenthandleroptions)
|
|
27
|
+
- [`DocumentHandlers`](#documenthandlers): [`upload()`](#uploadrequest-response) and
|
|
28
|
+
[its progress as events](#upload-with-progress-accept-textevent-stream),
|
|
29
|
+
[`get()`](#getrequest-response-id), [`remove()`](#removerequest-response-id)
|
|
30
|
+
- [How errors are answered](#how-errors-are-answered)
|
|
31
|
+
- [Isolated ingest](#isolated-ingest): [`createIsolatedExtractors()`](#createisolatedextractorsoptions),
|
|
32
|
+
[`IsolatedExtractorOptions`](#isolatedextractoroptions), [`IsolatedExtractors`](#isolatedextractors)
|
|
33
|
+
- [Server-Sent Events](#server-sent-events): [`writeSseEvents()`](#writesseeventsresponse-events-options),
|
|
34
|
+
[`sseMessageOf()`](#ssemessageofevent), [`SseMessage`](#ssemessage),
|
|
35
|
+
[`SseWriteOptions`](#ssewriteoptions)
|
|
36
|
+
|
|
37
|
+
### createDocumentHandlers(files, options?)
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
declare function createDocumentHandlers(files: LargeFiles, options?: DocumentHandlerOptions): DocumentHandlers;
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Upload, look-up and delete handlers for any Node HTTP server: `node:http` and Express; Fastify
|
|
44
|
+
through `request.raw` and `reply.raw`, with a pass-through parser for `application/octet-stream`
|
|
45
|
+
and `reply.hijack()`; Next.js API routes on the Node runtime, with `bodyParser: false`. The last two
|
|
46
|
+
are not tested in this repository: see [web app](../guides/web-app.md#mount-them-in-plain-nodehttp).
|
|
47
|
+
Each takes Node's `IncomingMessage` and `ServerResponse`, answers with JSON itself, errors
|
|
48
|
+
included, and never rejects, so it can be called without a `catch`.
|
|
49
|
+
|
|
50
|
+
| Parameter | Type | Default | What it does |
|
|
51
|
+
|---|---|---|---|
|
|
52
|
+
| `files` | [`LargeFiles`](./library.md#largefiles) | required | The library that uploads are ingested into and documents are looked up in. Its `maxUploadBytes` ([`LargeFilesOptions`](./library.md#largefilesoptions), 100 MB by default) is the upload limit. |
|
|
53
|
+
| `options` | [`DocumentHandlerOptions`](#documenthandleroptions) | `{}` | Who owns a request. |
|
|
54
|
+
|
|
55
|
+
**Returns** the three [`DocumentHandlers`](#documenthandlers). It makes no request, reads no
|
|
56
|
+
store and throws nothing.
|
|
57
|
+
|
|
58
|
+
The handlers do not check the method or the path of a request: route each request to the one you
|
|
59
|
+
mean. Every response they write has the header `Content-Type: application/json; charset=utf-8`
|
|
60
|
+
and a JSON body, except an upload that asks for its progress as events
|
|
61
|
+
([below](#upload-with-progress-accept-textevent-stream)). When the response has already started
|
|
62
|
+
(`response.headersSent`), they write nothing.
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
import { createServer } from "node:http";
|
|
66
|
+
import { createLargeFiles, MemoryDocumentStore } from "llm-large-files";
|
|
67
|
+
import { createDocumentHandlers } from "llm-large-files/node";
|
|
68
|
+
|
|
69
|
+
const files = createLargeFiles({ store: new MemoryDocumentStore() });
|
|
70
|
+
|
|
71
|
+
const documents = createDocumentHandlers(files, {
|
|
72
|
+
getOwner: async (request) => {
|
|
73
|
+
const userId = await signedInUser(request); // your sign-in: the user's ID, or undefined
|
|
74
|
+
if (!userId) throw Object.assign(new Error("Sign in to attach files."), { status: 401 });
|
|
75
|
+
return userId;
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
createServer((request, response) => {
|
|
80
|
+
const { pathname } = new URL(request.url ?? "/", "http://localhost");
|
|
81
|
+
const id = /^\/api\/documents\/([^/]+)$/.exec(pathname)?.[1];
|
|
82
|
+
if (pathname === "/api/documents" && request.method === "POST") return void documents.upload(request, response);
|
|
83
|
+
if (id !== undefined && request.method === "GET") return void documents.get(request, response, id);
|
|
84
|
+
if (id !== undefined && request.method === "DELETE") return void documents.remove(request, response, id);
|
|
85
|
+
response.writeHead(404).end();
|
|
86
|
+
}).listen(3000);
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Guide: [web app](../guides/web-app.md), with the Express routes, the browser's `fetch`, and an
|
|
90
|
+
upload route of your own for multipart forms or the Fetch API's `Request`.
|
|
91
|
+
|
|
92
|
+
### `DocumentHandlerOptions`
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
type DocumentHandlerOptions = {
|
|
96
|
+
getOwner?: (request: IncomingMessage) => string | undefined | Promise<string | undefined>;
|
|
97
|
+
};
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
The options of [`createDocumentHandlers()`](#createdocumenthandlersfiles-options).
|
|
101
|
+
|
|
102
|
+
| Option | Type | Default | What it does |
|
|
103
|
+
|---|---|---|---|
|
|
104
|
+
| `getOwner` | `(request: IncomingMessage) => string \| undefined \| Promise<string \| undefined>` | none: every request is anonymous | The owner of this request, usually the signed-in user's ID. Called at most once per request. In `upload` it runs after the name is read and before the body: an upload without a name is answered `400` without calling it, and a refused upload is never buffered. An empty owner (`""`, or spaces only) is the server's mistake: the upload is answered `500` `{ "error": "Upload failed (empty owner)." }`, before its body is read. So is an owner from JavaScript that is neither a string nor a finite number (`req.user` in place of `req.user.id`, say): `{ "error": "Upload failed (owner is not a string)." }`. |
|
|
105
|
+
|
|
106
|
+
What `getOwner` returns decides what each handler does:
|
|
107
|
+
|
|
108
|
+
| `getOwner` | `upload` | `get` and `remove` |
|
|
109
|
+
|---|---|---|
|
|
110
|
+
| Returns a string that is not empty or only spaces | The document is ingested with that `owner`. | They pass `{ owner }`: they find the documents of that owner, and those that have no owner. A document of another owner answers as one that does not exist. |
|
|
111
|
+
| Returns `undefined`, or there is no `getOwner` | The document has no owner: anyone who has its ID can read it, delete it and ask about it. | They pass no owner: they find only documents that have no owner. |
|
|
112
|
+
| Returns `""`, spaces only, or `null` from JavaScript | Answered `500` `{ "error": "Upload failed (empty owner)." }`, before the body is read, and nothing is logged. Such an owner would be one owner shared by every caller without a user: `user?.id ?? ""` gives it for a user who is not signed in. New in 0.6.0: 0.5.0 stored the document with that owner. | As before: they pass it as `owner`, so documents that 0.5.0 stored with the owner `""` stay readable until they expire. |
|
|
113
|
+
| Returns, from JavaScript, something that is neither a string nor a finite number: an object such as `req.user`, `true`, `NaN`, an array | Answered `500` `{ "error": "Upload failed (owner is not a string)." }`, before the body is read, and nothing is logged. New in 0.6.0. A finite number is taken as the owner, as before. | They pass it as `owner`, as before. |
|
|
114
|
+
| Throws an `Error` whose `status` (or `statusCode`) is a whole number from 400 to 599, as the `http-errors` package makes them | Answered with that status and `{ "error": <the error's message> }`. | The same. |
|
|
115
|
+
| Throws anything else | Answered `500` without the error's message, which may name your hosts: `{ "error": "Upload failed." }` (with the code of a Node system error: "Upload failed (ECONNREFUSED)."). | `500`: "The file could not be looked up." or "The file could not be deleted.", the same way. |
|
|
116
|
+
|
|
117
|
+
The owner is one opaque string, compared as it is. Pass the same string as `owner` to
|
|
118
|
+
`askWithFiles` or `askGemini`, and to `files.getMeta`, `files.getOriginal` and `files.delete`. An
|
|
119
|
+
owner per chat session (`${userId}/${sessionId}`) works the same way:
|
|
120
|
+
[storage](../guides/storage.md). What ownership protects and what it does not:
|
|
121
|
+
[security](../security.md).
|
|
122
|
+
|
|
123
|
+
### `DocumentHandlers`
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
type DocumentHandlers = {
|
|
127
|
+
upload(request: IncomingMessage, response: ServerResponse): Promise<void>;
|
|
128
|
+
get(request: IncomingMessage, response: ServerResponse, id: string): Promise<void>;
|
|
129
|
+
remove(request: IncomingMessage, response: ServerResponse, id: string): Promise<void>;
|
|
130
|
+
};
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
What [`createDocumentHandlers()`](#createdocumenthandlersfiles-options) returns. Each handler's
|
|
134
|
+
promise resolves once the response is written; none rejects.
|
|
135
|
+
|
|
136
|
+
| Handler | Route it for | What it does |
|
|
137
|
+
|---|---|---|
|
|
138
|
+
| [`upload(request, response)`](#uploadrequest-response) | `POST`, such as `/api/documents` | Reads the raw body and ingests it as a document of the request's owner. `201` with its summary, or, with `Accept: text/event-stream`, `200` and the ingest's events ending with the summary. |
|
|
139
|
+
| [`get(request, response, id)`](#getrequest-response-id) | `GET`, such as `/api/documents/:id` | `200` with the document's summary, or `404`. |
|
|
140
|
+
| [`remove(request, response, id)`](#removerequest-response-id) | `DELETE`, such as `/api/documents/:id` | Deletes the document. `200` with `{ "deleted": true }` or `{ "deleted": false }`. |
|
|
141
|
+
|
|
142
|
+
The summary is a [`DocumentSummary`](./library.md#documentsummary), the fields of a document that
|
|
143
|
+
are safe to send to a browser: `id`, `name`, `mimeType`, `format`, `bytes`, `lines`,
|
|
144
|
+
`estimatedTokens`, `pages` (for a PDF, a PPTX or an XLSX), `encoding` and `replacedCharacters` (for a text
|
|
145
|
+
file that was not valid UTF-8, since 0.6.0) and `expiresAt`. It holds no `owner`.
|
|
146
|
+
|
|
147
|
+
#### upload(request, response)
|
|
148
|
+
|
|
149
|
+
The request:
|
|
150
|
+
|
|
151
|
+
| Part | What it must be |
|
|
152
|
+
|---|---|
|
|
153
|
+
| Method and path | Any: the handler does not check them. Route `POST` to it. |
|
|
154
|
+
| Body | The file itself, as raw bytes. Not a multipart form: the handler does not parse one. |
|
|
155
|
+
| `X-File-Name` header | The file name, URI-encoded with `encodeURIComponent` so that any name survives a header. It is decoded with `decodeURIComponent` (a value that does not decode is used as it is) and trimmed. |
|
|
156
|
+
| `?name=` query parameter | The file name, when there is no `X-File-Name`. One of the two is required. |
|
|
157
|
+
| `X-File-Type` header | Optional: the MIME type, URI-decoded. |
|
|
158
|
+
| `Content-Type` header | The MIME type when there is no `X-File-Type`, unless it starts with `application/octet-stream`. The value is kept whole, parameters included: a `fetch` with a string body sends `text/plain;charset=UTF-8`, and that is the document's `mimeType`. A type with parameters does not set the format, so name the file with its extension. With neither header, the document's `mimeType` is `application/octet-stream`. Send `application/octet-stream`, which JSON and form parsers leave alone. |
|
|
159
|
+
| `Content-Length` header | Optional. When it is larger than `maxUploadBytes`, the handler answers `413` before it reads anything. |
|
|
160
|
+
| `Accept` header | Optional. When it names `text/event-stream`, the ingest is answered with its progress as Server-Sent Events: see [upload with progress](#upload-with-progress-accept-textevent-stream). New in 0.7.0. |
|
|
161
|
+
|
|
162
|
+
`files.ingest` then keeps the last path segment of the name, without control characters and
|
|
163
|
+
characters that show nothing, up to 255 characters and never cut in the middle of a character, and takes the format
|
|
164
|
+
from the name's extension first, then from the MIME type
|
|
165
|
+
([`detectFormat`](./library.md#detectformatname-mimetype)).
|
|
166
|
+
|
|
167
|
+
What it does, in order:
|
|
168
|
+
|
|
169
|
+
1. Reads the name. Without one, it answers `400`.
|
|
170
|
+
2. Calls `getOwner`, and checks what it returned: `""`, spaces only or `null`, or from JavaScript
|
|
171
|
+
a value that is neither a string nor a finite number, is answered `500` (see
|
|
172
|
+
[`DocumentHandlerOptions`](#documenthandleroptions)).
|
|
173
|
+
3. Reads the body, up to `files.maxUploadBytes`:
|
|
174
|
+
- a `Uint8Array` or `Buffer` that a framework left in `request.body` (`express.raw()`) is used
|
|
175
|
+
as the file, with the same limit;
|
|
176
|
+
- an object with fields in `request.body` (`express.json()` on a JSON request) is answered
|
|
177
|
+
`400`;
|
|
178
|
+
- otherwise it reads the request stream. Past the limit it stops keeping the bytes, and
|
|
179
|
+
answers `413` at once. The rest of the body is then read and dropped, up to 8 MB, and the
|
|
180
|
+
answer ends when the body does: a client that is still sending reads the `413`, and can send
|
|
181
|
+
its next request on the same keep-alive connection. A body that goes on more than 8 MB past
|
|
182
|
+
that is cut off: the connection is closed, and a client still sending may then get a reset
|
|
183
|
+
(`ECONNRESET`) instead of the answer. Closing the connection at once was not chosen: some
|
|
184
|
+
systems (Windows) reset a connection closed while data is still arriving, and the client
|
|
185
|
+
never reads the answer. The same holds for every answer sent before the body was read to its
|
|
186
|
+
end (no name, or a `Content-Length` over the limit, whose body Node would otherwise read
|
|
187
|
+
whole). Before 0.7.1 the rest was left unread, and the connection stayed open with the
|
|
188
|
+
client stuck sending into it. The answer to such a body has no `Content-Length`. A stream
|
|
189
|
+
that another middleware has already read gives no bytes, and the upload is answered `422` as
|
|
190
|
+
an empty file.
|
|
191
|
+
4. Ingests it: `files.ingest({ name, bytes, mimeType, owner, signal })`, `mimeType` and `owner`
|
|
192
|
+
only when there are any. The `signal` aborts when the client closes the connection before the
|
|
193
|
+
answer is sent: the ingest stops between two pages or pieces, and nothing is stored. The
|
|
194
|
+
answer then goes to no one.
|
|
195
|
+
5. Answers `201` with the document's summary. With `Accept: text/event-stream`, steps 4 and 5 are
|
|
196
|
+
a stream of events instead ([below](#upload-with-progress-accept-textevent-stream)).
|
|
197
|
+
|
|
198
|
+
The responses:
|
|
199
|
+
|
|
200
|
+
| Status | Body | When |
|
|
201
|
+
|---|---|---|
|
|
202
|
+
| `201` | The [`DocumentSummary`](./library.md#documentsummary) of the new document | It was ingested. |
|
|
203
|
+
| `400` | `{ "error": "Name the file with an X-File-Name header or a ?name= query parameter." }` | No name. |
|
|
204
|
+
| `400` | `{ "error": "The upload body was already parsed by another middleware. Mount the upload route before body parsers, or send Content-Type: application/octet-stream." }` | `request.body` is an object with fields. |
|
|
205
|
+
| `413` | `{ "error": "The file is larger than the 100 MB upload limit." }`, with your `maxUploadBytes` in its place (`512 KB`, `1000 B`) | `Content-Length`, the bytes read, or the `Buffer` in `request.body` are over `maxUploadBytes`. |
|
|
206
|
+
| `422` | `{ "error": <the message of files.ingest> }` | The file cannot be read: `files.ingest` threw an [`IngestError`](./library.md#ingesterror), whose `status` is 422. The message says why and is meant for the user: "app.log is empty.", "app.log did not contain any text.", "This file looks binary, not text. Attach a text, log, PDF, Word, PowerPoint, Excel or HTML file.", "This file is gzip-compressed. Decompress it, then attach the text file inside.", "This file is a ZIP archive. Extract it, then attach the text file you need.", an Office file of before 2007 or with a password, a PDF with a password or with no text layer, and a PDF, DOCX, PPTX or XLSX while the optional dependency that reads it is missing ("Reading PDF files needs the optional dependency "unpdf".") or, for a PDF, cannot run on this Node ("The unpdf installed cannot read PDF files on Node 20 (…). Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 22 or later.", see [defaultExtractors](./library.md#defaultextractors)). A text file is never refused for its encoding. A file past the limits of `createLargeFiles`: more text than `maxTextBytes`, more pages than `maxPdfPages`, longer to read than `ingestTimeoutMs` ("report.pdf took too long to read (more than 2 min). Split it, or save it as plain text, and attach that."), or built to exhaust the server ([every message](../guides/pdfs.md#what-is-refused)). With [`createIsolatedExtractors`](#createisolatedextractorsoptions), also a file whose reader ran out of memory or time. An extractor of your own that throws an `Error` gives its message here too. |
|
|
207
|
+
| `503` | `{ "error": "The server is reading other files right now. Try again in a moment." }`, with `Retry-After: 5` | The isolated readers of [`createIsolatedExtractors`](#createisolatedextractorsoptions) are all busy and their queue is full: an `IngestError` of code `"busy"`. The header is its `retryAfterMs` in seconds, rounded up, at least 1. While they shut down (`close()`): "The server is shutting down. Try again in a moment." New in 0.8.0. |
|
|
208
|
+
| 400 to 599 | `{ "error": <the error's message> }` | `getOwner`, an extractor or the store threw an error with that `status` or `statusCode`. |
|
|
209
|
+
| `500` | `{ "error": "Upload failed (empty owner)." }` | `getOwner` returned `""`, spaces only or `null`. The body is not read. New in 0.6.0. |
|
|
210
|
+
| `500` | `{ "error": "Upload failed (owner is not a string)." }` | `getOwner` returned, from JavaScript, something that is neither a string nor a finite number: an object such as `req.user`, `true`, `NaN`, an array. The body is not read. New in 0.6.0. |
|
|
211
|
+
| `500` | `{ "error": "Upload failed (ENOSPC)." }` | The store failed with a Node system error, one with a `code` and a `syscall`. Only the code is passed on. |
|
|
212
|
+
| `500` | `{ "error": "Upload failed." }` | `getOwner` threw an error without a status, or the request body could not be read: the client went away, or a proxy cut the upload. Node's error for a client that went away has a `code` (`ECONNRESET`) but no `syscall`, so no code is added. An error of either kind that has a `code` and a `syscall` is answered as in the row above, with its code. |
|
|
213
|
+
| `500` | `{ "error": "Upload failed." }` | The store failed while it wrote the document, with an error that has no `status` or `statusCode` from 400 to 599 and is not a Node system error (a database driver's error, say). Or `files.ingest` threw a value that is not an `Error` (an extractor of your own that throws a string, say). Such a value with a `code` and a `syscall` gets its code, as in the `ENOSPC` row. The error's own message is not sent. See below. |
|
|
214
|
+
|
|
215
|
+
A store that fails while it writes is answered `500` "Upload failed." when its error has neither a
|
|
216
|
+
`status` (or `statusCode`) from 400 to 599 nor a Node system error's `code` and `syscall`. Its
|
|
217
|
+
message may name a host, so it is not sent, and the handlers log nothing. `files.ingest` throws
|
|
218
|
+
that error unchanged, and the handler knows it by a mark that `ingest` keeps. The package does not
|
|
219
|
+
export the mark, so two paths answer such an error `422` with the store's message, as a file that
|
|
220
|
+
cannot be read:
|
|
221
|
+
|
|
222
|
+
- an `ingest` of your own that throws a new error in place of the store's, such as `ingestInProcess`
|
|
223
|
+
in [deployment](../guides/deployment.md#uploads-and-ingest);
|
|
224
|
+
- a route of your own around `files.ingest`, such as the one in
|
|
225
|
+
[web app](../guides/web-app.md#filesingest-and-its-errors) with its `ingestFailure` helper.
|
|
226
|
+
|
|
227
|
+
In a store of your own, log the failure and throw an error with a `status` (a `503`, say) and a
|
|
228
|
+
message without hosts: every path keeps that status. An `ingest` of your own must copy the
|
|
229
|
+
`status`, and a system error's `code` and `syscall`, onto the error it throws.
|
|
230
|
+
[Storage](../guides/storage.md) has the rules for a store's errors.
|
|
231
|
+
|
|
232
|
+
#### Upload with progress: `Accept: text/event-stream`
|
|
233
|
+
|
|
234
|
+
New in 0.7.0. An upload whose `Accept` header names `text/event-stream` is answered with the
|
|
235
|
+
ingest's events as Server-Sent Events, so that the page can show how far the server has read the
|
|
236
|
+
file: the pages of a PDF, the parts of a DOCX, the writes to the store. Without that header,
|
|
237
|
+
nothing changes: `201` and JSON, as above.
|
|
238
|
+
|
|
239
|
+
The handler reads the `Accept` header this way:
|
|
240
|
+
|
|
241
|
+
- The header is split at commas into media ranges. One of them must be `text/event-stream`
|
|
242
|
+
itself, in any case, with spaces allowed around it and its parameters
|
|
243
|
+
(`TEXT/Event-Stream ; q=0.5` counts).
|
|
244
|
+
- Its `q`, when there is one, must be a number above 0. `q=0` and `q=0.0` keep the JSON answer, and
|
|
245
|
+
so does a `q` that is not a number.
|
|
246
|
+
- A wildcard keeps the JSON answer: `*/*` and `text/*` do not ask for events. So does any other
|
|
247
|
+
type, such as `application/json`.
|
|
248
|
+
- Other parameters, such as `charset=utf-8`, change nothing.
|
|
249
|
+
|
|
250
|
+
What stays JSON: every check that runs before the ingest answers as it always did, with its status
|
|
251
|
+
and `{ "error": "…" }`, because the stream has not started yet. That is a missing name (`400`), a
|
|
252
|
+
refusal or a bad owner from `getOwner` (its status, or `500`), a body another middleware parsed
|
|
253
|
+
(`400`), and a file over `maxUploadBytes` (`413`). Only a file that passes them is answered `200`
|
|
254
|
+
with the event-stream headers of [`writeSseEvents()`](#writesseeventsresponse-events-options) and
|
|
255
|
+
a `: keep-alive` comment every 15 seconds.
|
|
256
|
+
|
|
257
|
+
Each message is `id: <seq>`, `event: <type>` and `data: <the event as JSON>`. The events are those
|
|
258
|
+
of [`IngestEvent`](./events.md#ingestevent), stamped with `seq` (1, 2, 3… with no gaps), `runId`
|
|
259
|
+
("ing_" and 16 hex digits) and `time` (milliseconds since 1970):
|
|
260
|
+
|
|
261
|
+
| Event | `data` besides `type`, `seq`, `runId` and `time` | When |
|
|
262
|
+
|---|---|---|
|
|
263
|
+
| `ingest.start` | `name` (cleaned), `format` (what the name and the type say: a text file can still become a log), `bytes` | First. |
|
|
264
|
+
| `ingest.progress` | `stage` (`"decode"`, `"extract"`, `"check"`, `"pictures"`, `"prepare"`, `"index"` or `"store"`), `done`, `total` (absent when not known), `unit` (`"pages"`, `"parts"`, `"bytes"` or `"characters"`) | At most about every 12 ms for a stage, and once more when the stage ends. A stage with nothing to report may send none ([stages and units](./events.md#stages-and-units)). |
|
|
265
|
+
| `ingest.finish` | `document`: the [`DocumentSummary`](./library.md#documentsummary), the same fields as the body of a `201` | Last, when the document is stored. |
|
|
266
|
+
| `ingest.error` | `error`: `{ "message": …, "status": … }`, the message and status the JSON answer would have, and for a file that could not be read `"code"`, the [`IngestError`](./library.md#ingesterror) code (new in 0.8.0) | Last, when the ingest fails. |
|
|
267
|
+
|
|
268
|
+
```text
|
|
269
|
+
id: 4
|
|
270
|
+
event: ingest.finish
|
|
271
|
+
data: {"type":"ingest.finish","document":{"id":"doc_f6502d2f94694d709c7db2ec634c8397","name":"b.log","mimeType":"text/plain","format":"log","bytes":81000,"lines":3000,"estimatedTokens":74940,"expiresAt":"2026-11-25T19:09:01.650Z"},"seq":4,"runId":"ing_d19490eacdcd4546","time":1795374541651}
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
- **The stream always ends with one `ingest.finish` or one `ingest.error`.** A file the ingest
|
|
275
|
+
refuses at once (an empty file) still gets `ingest.start`, then `ingest.error`. When an `ingest`
|
|
276
|
+
of your own sends no events at all, the handler adds the last one: then that one event is the
|
|
277
|
+
whole stream, with `seq` 1.
|
|
278
|
+
- **`ingest.error` holds what the JSON answer would.** A file that cannot be read gives
|
|
279
|
+
`{ "message": "This file looks binary, not text. …", "status": 422, "code": "not_text" }`, and
|
|
280
|
+
isolated readers that are all busy `{ "message": "The server is reading other files right now. Try
|
|
281
|
+
again in a moment.", "status": 503, "code": "busy" }`, with no `Retry-After` (the headers are
|
|
282
|
+
sent). A store that failed is `{ "message": "Upload failed.", "status": 500 }`, never the store's
|
|
283
|
+
own message, which may name a host. An error with a status keeps it. The error has no `kind` or
|
|
284
|
+
`name` here, unlike the `EventError` of `files.ingest`'s own events; `code` is new in 0.8.0, so
|
|
285
|
+
that a page can say why in its own words.
|
|
286
|
+
- **The status is `200` whatever happens next.** Once the stream has started, a failure can only be
|
|
287
|
+
an `ingest.error` event.
|
|
288
|
+
- **A client that goes away stops the ingest**, as in step 4: nothing is stored, and nothing more
|
|
289
|
+
is written.
|
|
290
|
+
- **The handler still never rejects.**
|
|
291
|
+
|
|
292
|
+
How to read the stream in the browser: [web app](../guides/web-app.md#upload-with-progress).
|
|
293
|
+
|
|
294
|
+
#### get(request, response, id)
|
|
295
|
+
|
|
296
|
+
The request: route `GET` to it; the handler does not check the method. `id` is the document ID,
|
|
297
|
+
taken from your route. Nothing else is read but what `getOwner` reads.
|
|
298
|
+
|
|
299
|
+
| Status | Body | When |
|
|
300
|
+
|---|---|---|
|
|
301
|
+
| `200` | The [`DocumentSummary`](./library.md#documentsummary) | The document is there, has not expired, and has no owner or the owner `getOwner` returned. |
|
|
302
|
+
| `404` | `{ "error": "This file is no longer available." }` | `id` is not a document ID, was never uploaded, has expired or been deleted, or belongs to another owner. |
|
|
303
|
+
| 400 to 599 | `{ "error": <the error's message> }` | `getOwner` threw an error with that `status` or `statusCode`. |
|
|
304
|
+
| `500` | `{ "error": "The file could not be looked up (EIO)." }` | The store could not be read ([`DocumentStoreError`](./library.md#documentstoreerror)), with the code of the system error behind it, when there is one. |
|
|
305
|
+
| `500` | `{ "error": "The file could not be looked up." }` | The store could not be read and gave no system error code, or `getOwner` threw an error without a status. |
|
|
306
|
+
|
|
307
|
+
#### remove(request, response, id)
|
|
308
|
+
|
|
309
|
+
The request: route `DELETE` to it; the handler does not check the method. `id` is the document
|
|
310
|
+
ID, taken from your route. It deletes the document through `files.delete`, which removes it from
|
|
311
|
+
the store: its text, its index and any kept original, as far as your store's `delete` does.
|
|
312
|
+
|
|
313
|
+
| Status | Body | When |
|
|
314
|
+
|---|---|---|
|
|
315
|
+
| `200` | `{ "deleted": true }` | The document was deleted. |
|
|
316
|
+
| `200` | `{ "deleted": false }` | This owner has no such document: `id` is not a document ID, was never uploaded, has expired or been deleted, or belongs to another owner. Also when the store's `delete` returned `false`. It never answers `404`. |
|
|
317
|
+
| 400 to 599 | `{ "error": <the error's message> }` | `getOwner`, or the store's `delete`, threw an error with that `status` or `statusCode`. |
|
|
318
|
+
| `500` | `{ "error": "The file could not be deleted (EIO)." }` | The store could not be read, or its `delete` failed with a Node system error, with that error's code. |
|
|
319
|
+
| `500` | `{ "error": "The file could not be deleted." }` | The same with no system error code, or `getOwner` threw an error without a status. |
|
|
320
|
+
|
|
321
|
+
## How errors are answered
|
|
322
|
+
|
|
323
|
+
The three handlers answer an error by one rule:
|
|
324
|
+
|
|
325
|
+
- **An error with a status.** An `Error` whose `status`, or else `statusCode`, is a whole number
|
|
326
|
+
from 400 to 599 is answered with that status and `{ "error": <its message> }`. With an empty
|
|
327
|
+
message, the body says what failed instead ("Upload failed.", "The file could not be looked
|
|
328
|
+
up.", "The file could not be deleted."). A `413` is always answered with the size message of
|
|
329
|
+
`upload`. An [`IngestError`](./library.md#ingesterror) carries its `status` (422, 413 or 503),
|
|
330
|
+
and a `503` whose error has a `retryAfterMs` also gets a `Retry-After` header, in seconds.
|
|
331
|
+
- **Any other error** is the server's trouble: `500`, with what failed and, for a Node system error
|
|
332
|
+
(one with a `code` and a `syscall`), its code: "Upload failed (ENOSPC).". The error's own message
|
|
333
|
+
is never sent, since it can name paths and hosts of your server.
|
|
334
|
+
- **The one exception** is in `upload`: an `Error` from `files.ingest` that has neither a status nor
|
|
335
|
+
a system error's `code` and `syscall` is a file that cannot be read, `422` with its message,
|
|
336
|
+
unless `files.ingest` marked it as an error the store threw while it wrote the document. That
|
|
337
|
+
one, and a thrown value that is not an `Error`, are answered as any other error. An `ingest` of
|
|
338
|
+
your own that throws a new error in its place loses the mark ([upload](#uploadrequest-response)).
|
|
339
|
+
|
|
340
|
+
Guide: [errors and reliability](../guides/errors-and-reliability.md), for the errors of a question
|
|
341
|
+
itself; [web app](../guides/web-app.md), for what to show in the browser.
|
|
342
|
+
|
|
343
|
+
## Isolated ingest
|
|
344
|
+
|
|
345
|
+
New in 0.8.0. The built-in extractors read a file in your server's process, in its heap: a file
|
|
346
|
+
built to exhaust a server (a zip bomb, a PDF whose objects take gigabytes) can run that heap out of
|
|
347
|
+
memory and stop every answer streaming on the server. `createIsolatedExtractors` reads PDF, DOCX,
|
|
348
|
+
PPTX and XLSX files in child processes instead, each with a heap limit and a kill timer, so that
|
|
349
|
+
such a file is refused and the server goes on. A worker thread does not reliably contain running
|
|
350
|
+
out of memory; a process does ([Security](../security.md#reading-pdfs-for-pages-and-pictures)).
|
|
351
|
+
|
|
352
|
+
### createIsolatedExtractors(options?)
|
|
353
|
+
|
|
354
|
+
```ts
|
|
355
|
+
declare function createIsolatedExtractors(options?: IsolatedExtractorOptions): IsolatedExtractors;
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
Starts nothing yet: a child process starts with the first file it is given. Pass its `extractors`
|
|
359
|
+
to `createLargeFiles`. Everything else stays as it is: `files.ingest`, the upload handler, events
|
|
360
|
+
and progress.
|
|
361
|
+
|
|
362
|
+
```ts
|
|
363
|
+
import { createServer } from "node:http";
|
|
364
|
+
import { createLargeFiles, FileDocumentStore } from "llm-large-files";
|
|
365
|
+
import { createDocumentHandlers, createIsolatedExtractors } from "llm-large-files/node";
|
|
366
|
+
|
|
367
|
+
const isolated = createIsolatedExtractors({ maxHeapMb: 512, concurrency: 2 });
|
|
368
|
+
const files = createLargeFiles({ store: new FileDocumentStore("./data"), extractors: isolated.extractors });
|
|
369
|
+
const documents = createDocumentHandlers(files);
|
|
370
|
+
const server = createServer(/* your routes, with documents.upload */).listen(3000);
|
|
371
|
+
|
|
372
|
+
// A SIGTERM listener replaces Node's own exit: stop the server there too, or it goes on serving.
|
|
373
|
+
// (On Windows no SIGTERM arrives: a kill ends the process.)
|
|
374
|
+
process.once("SIGTERM", () => {
|
|
375
|
+
server.close(); // no new connections; requests under way go on
|
|
376
|
+
void isolated.close(); // kills the children: the files they read are refused as "busy"
|
|
377
|
+
});
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
With nothing else open (a database pool, a timer of your own), the process then exits once the
|
|
381
|
+
requests under way end. To let the uploads under way finish before the children are killed, call
|
|
382
|
+
`close()` later, when the grace period of your platform runs out, as in
|
|
383
|
+
[Stopping a server](../guides/deployment.md#stopping-a-server).
|
|
384
|
+
|
|
385
|
+
What happens to a file of one of its formats:
|
|
386
|
+
|
|
387
|
+
1. `files.ingest` calls the isolated extractor, as it would the built-in one. When `concurrency`
|
|
388
|
+
files are being read, the file waits, up to `maxQueue` files; past that it is refused at once
|
|
389
|
+
as `"busy"`.
|
|
390
|
+
2. Its bytes are copied to a child process, with its name, MIME type, format and the limits of
|
|
391
|
+
`createLargeFiles` (`maxTextBytes`, `maxPdfPages`, `scannedPdfPages`). The child reads it with the
|
|
392
|
+
built-in extractor of its format, and sends its progress and then its text back.
|
|
393
|
+
3. The rest of the ingest runs in your server, as without it: the text is normalized, profiled,
|
|
394
|
+
indexed and stored. A file costs its bytes copied to the child and its text copied back.
|
|
395
|
+
4. A child reads one file at a time. It is replaced by a new one after `maxFilesPerChild` files,
|
|
396
|
+
since some parsers keep memory for the life of their process (`@cantoo/pdf-lib` keeps every name
|
|
397
|
+
it reads), and stopped after `idleMs` with nothing to read. An idle child does not keep your
|
|
398
|
+
process alive.
|
|
399
|
+
|
|
400
|
+
When the ingest's signal aborts (`ingestTimeoutMs`, or a client that went away), the child that
|
|
401
|
+
reads the file is killed, and a file that waits leaves the queue. The children load the same
|
|
402
|
+
optional dependencies (`unpdf`, `jszip`, `@cantoo/pdf-lib`) the server would, so install them on
|
|
403
|
+
the server. Text formats, HTML included, are read in the server, in slices, by default.
|
|
404
|
+
|
|
405
|
+
The refusals of the children. Each is an [`IngestError`](./library.md#ingesterror), with your
|
|
406
|
+
numbers in its message:
|
|
407
|
+
|
|
408
|
+
| `code` | Message | When |
|
|
409
|
+
|---|---|---|
|
|
410
|
+
| `"out_of_memory"` | `report.pdf needed more memory than is allowed for reading one file (512 MB). It may be built to exhaust the server, so it is not read. Split it, or save it as plain text, and attach that.` | The child ran out of its heap, `maxHeapMb`: its standard error says so, or it ended with `SIGABRT` or exit code 134. |
|
|
411
|
+
| `"timeout"` | `report.pdf took too long to read (more than 2 min). Split it, or save it as plain text, and attach that.` | The file took longer than `timeoutMs`. The child is killed, even in the middle of a PDF page that pdf.js reads in one block, which `ingestTimeoutMs` cannot cut short. |
|
|
412
|
+
| `"busy"` | `The server is reading other files right now. Try again in a moment.` | `concurrency` files are being read and `maxQueue` wait. `retryAfterMs` is 5,000: the upload handler answers `503` with `Retry-After: 5` ([upload](#uploadrequest-response)). |
|
|
413
|
+
| `"busy"` | `The server is shutting down. Try again in a moment.` | `close()` was called while the file waited or was read, or before it was sent. |
|
|
414
|
+
| `"unreadable"` | `report.pdf could not be read: its reader stopped (SIGSEGV).`, or `(exit code 1)` | The child ended another way. |
|
|
415
|
+
| `"unreadable"` | `report.pdf could not be read: its reader could not be reached.` | The file could not be sent to the child. |
|
|
416
|
+
|
|
417
|
+
A child that stops before it is ready to read, so before it was sent the file, is the server's
|
|
418
|
+
trouble, not the file's: a `childScript` that is not there, an `execArgv` that Node does not know.
|
|
419
|
+
Such a file is refused with an `Error` that is not an `IngestError`, with `status` 500:
|
|
420
|
+
`The server could not start a reader for report.pdf (exit code 1).` The upload handler answers it
|
|
421
|
+
`500` with that message. The end of the child's standard error, which names paths of the server, is
|
|
422
|
+
its `cause` only. The upload handler answers the error itself, so to log the cause there, wrap the
|
|
423
|
+
extractors before you hand them to `createLargeFiles`:
|
|
424
|
+
|
|
425
|
+
```ts
|
|
426
|
+
const isolated = createIsolatedExtractors();
|
|
427
|
+
const extractors = Object.fromEntries(Object.entries(isolated.extractors).map(([format, extract]) => [
|
|
428
|
+
format,
|
|
429
|
+
(bytes: Uint8Array, input: ExtractInput) => extract!(bytes, input).catch((error: unknown) => {
|
|
430
|
+
if ((error as { status?: unknown }).status === 500) console.error("reader did not start", (error as Error).cause);
|
|
431
|
+
throw error;
|
|
432
|
+
}),
|
|
433
|
+
]));
|
|
434
|
+
const files = createLargeFiles({ store, extractors });
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
A file the built-in extractor refuses in the child is refused with the same message as in the
|
|
438
|
+
server, and the code of its words: a zip bomb or a PDF that would hold the server is `"hostile"`, a
|
|
439
|
+
PDF without text `"no_text"`, and so on ([`IngestError`](./library.md#ingesterror)).
|
|
440
|
+
|
|
441
|
+
**The heap limit.** Each child runs with `--max-old-space-size` set to `maxHeapMb`, and Node adds
|
|
442
|
+
its young generation above it: with 512, a heap limit of 560 MB on Node 20 and 22, 704 MB on Node
|
|
443
|
+
24 and 608 MB on Node 26 ([Deployment](../guides/deployment.md#memory-on-each-server)). The
|
|
444
|
+
server's own `NODE_OPTIONS` are not passed to the children: a `--max-old-space-size` there would
|
|
445
|
+
replace this one. The rest of its environment is. The limit bounds the heap only: what a parser
|
|
446
|
+
unpacks outside it, such as a stream of a PDF, is not bounded by it. For uploads you do not trust,
|
|
447
|
+
give the server a memory limit of its own too, such as that of its container
|
|
448
|
+
([Security](../security.md#uploads)).
|
|
449
|
+
|
|
450
|
+
### `IsolatedExtractorOptions`
|
|
451
|
+
|
|
452
|
+
```ts
|
|
453
|
+
type IsolatedExtractorOptions = {
|
|
454
|
+
maxHeapMb?: number;
|
|
455
|
+
timeoutMs?: number;
|
|
456
|
+
concurrency?: number;
|
|
457
|
+
maxQueue?: number;
|
|
458
|
+
formats?: DocumentFormat[];
|
|
459
|
+
pdf?: PdfExtractorOptions;
|
|
460
|
+
maxFilesPerChild?: number;
|
|
461
|
+
idleMs?: number;
|
|
462
|
+
execArgv?: string[];
|
|
463
|
+
childScript?: string | URL;
|
|
464
|
+
};
|
|
465
|
+
```
|
|
466
|
+
|
|
467
|
+
| Option | Type | Default | What it does |
|
|
468
|
+
|---|---|---|---|
|
|
469
|
+
| `maxHeapMb` | `number` | 512 | The heap of each child process, in MB, given as `--max-old-space-size`. A file that needs more is refused (`"out_of_memory"`), and the server goes on. From 1 to 1,048,576, and finite; a fraction is cut to a whole number. Node reads `--max-old-space-size=0` as its default heap, so a value below 1 is refused rather than cut to 0. |
|
|
470
|
+
| `timeoutMs` | `number` | 120,000 | The most time one file may take, in milliseconds. Past it, its child is killed and the file refused (`"timeout"`). 0 sets none, and so does a value past what a timer can wait (2,147,483,647 ms, 24.8 days), `Infinity` included, as for `ingestTimeoutMs`. With both at their defaults, the `ingestTimeoutMs` of `createLargeFiles` usually ends the ingest first, and its signal kills the child too. |
|
|
471
|
+
| `concurrency` | `number` | 2 | How many files are read at once, each in a child process of its own. At least 1. |
|
|
472
|
+
| `maxQueue` | `number` | 8 | How many files may wait for a child. Past it, a file is refused at once as `"busy"`. 0: none waits. |
|
|
473
|
+
| `formats` | `DocumentFormat[]` | `["pdf", "docx", "pptx", "xlsx"]` | The formats read in child processes: by default those whose parsers a hostile file can exhaust. `extractors` has an entry for each. |
|
|
474
|
+
| `pdf` | [`PdfExtractorOptions`](./library.md#pdfextractoroptions) | `{}` | Options of the built-in PDF extractor in the children, as for [`createPdfExtractor`](./library.md#createpdfextractoroptions). |
|
|
475
|
+
| `maxFilesPerChild` | `number` | 50 | How many files one child reads before it is replaced by a new one. At least 1. |
|
|
476
|
+
| `idleMs` | `number` | 30,000 | A child with nothing to read is stopped after this many milliseconds. 0, or a value past what a timer can wait (`Infinity` included), keeps the children until `close()`. Either way an idle child does not keep your process alive. |
|
|
477
|
+
| `execArgv` | `string[]` | `[]` | Further Node options for the children, after the heap limit. |
|
|
478
|
+
| `childScript` | `string \| URL` | The `ingest-child.js` shipped next to the module | The script the children run: a path, a `file:` URL, or a string of one. For a bundler that moves files: `import.meta.resolve("llm-large-files/node/ingest-child.js")` gives the one in the installed package ([Bundlers](../guides/deployment.md#nodejs-esm-and-require)). |
|
|
479
|
+
|
|
480
|
+
A number option that is not a number, NaN, below 0, or 0 where it must be above 0, throws a
|
|
481
|
+
`RangeError` when `createIsolatedExtractors` is called: "maxHeapMb must be a number above 0, and is
|
|
482
|
+
NaN.", or "timeoutMs must be a number above or equal to 0, and is -1.". So does a `maxHeapMb` below
|
|
483
|
+
1, above 1,048,576 (1 TB, past which Node reads the flag wrong) or not finite: "maxHeapMb must be a
|
|
484
|
+
number from 1 to 1,048,576 (1 TB), and is 0.5.". A heap below about 32 MB cannot start a reader
|
|
485
|
+
that reads ordinary files: every file is then refused.
|
|
486
|
+
|
|
487
|
+
### `IsolatedExtractors`
|
|
488
|
+
|
|
489
|
+
```ts
|
|
490
|
+
type IsolatedExtractors = {
|
|
491
|
+
extractors: Partial<Record<DocumentFormat, Extractor>>;
|
|
492
|
+
stats(): { running: number; queued: number; children: number };
|
|
493
|
+
close(): Promise<void>;
|
|
494
|
+
};
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
| Member | What it is |
|
|
498
|
+
|---|---|
|
|
499
|
+
| `extractors` | One extractor for each of `formats`, to pass to `createLargeFiles({ extractors })`. To add one of your own for another format: `{ ...isolated.extractors, text: myText }`. |
|
|
500
|
+
| `stats()` | The files being read (`running`), the files waiting (`queued`) and the child processes alive (`children`): for a health check or a metric. |
|
|
501
|
+
| `close()` | Kills every child process, and refuses the files waiting, those being read and those sent while it runs as `"busy"` ("The server is shutting down. Try again in a moment."). Resolves once the children have exited, also when nothing else keeps your process open, so code after `await isolated.close()` runs. Files sent after that start new children. Call it when the server stops, next to the server's own `close()`: a SIGTERM listener replaces Node's own exit ([above](#createisolatedextractorsoptions)). |
|
|
502
|
+
|
|
503
|
+
## Server-Sent Events
|
|
504
|
+
|
|
505
|
+
New in 0.7.0. Two functions send the events of a question (`askStream`, or
|
|
506
|
+
[`eventStream`](./events.md#eventstreamrun-options) over `askGemini`) or of an ingest to a browser,
|
|
507
|
+
one Server-Sent Events message per event. The events themselves are in the
|
|
508
|
+
[events reference](./events.md). The guide [web app](../guides/web-app.md#the-event-stream) has a
|
|
509
|
+
whole route and the browser code that reads it.
|
|
510
|
+
|
|
511
|
+
### writeSseEvents(response, events, options?)
|
|
512
|
+
|
|
513
|
+
```ts
|
|
514
|
+
declare function writeSseEvents<E extends { type: string; seq: number }>(
|
|
515
|
+
response: ServerResponse,
|
|
516
|
+
events: AsyncIterable<E>,
|
|
517
|
+
options?: SseWriteOptions<E>,
|
|
518
|
+
): Promise<void>;
|
|
519
|
+
```
|
|
520
|
+
|
|
521
|
+
Sends `events` on `response` as Server-Sent Events, and ends the response after the last one. Any
|
|
522
|
+
iterable of objects with a `type` and a `seq` works: an `askStream`, an `eventStream`, or an async
|
|
523
|
+
generator of your own.
|
|
524
|
+
|
|
525
|
+
| Parameter | Type | Default | What it does |
|
|
526
|
+
|---|---|---|---|
|
|
527
|
+
| `response` | `ServerResponse` | required | The response to write on. Express's `res` is one. |
|
|
528
|
+
| `events` | `AsyncIterable<E>` | required | The events. Pass an `askStream` or an `eventStream` itself, not a generator around it: see [when the client goes away](#when-the-client-goes-away). |
|
|
529
|
+
| `options` | [`SseWriteOptions<E>`](#ssewriteoptions) | `{}` | The keep-alive, extra headers, what to send for each event, and whether to end the response. |
|
|
530
|
+
|
|
531
|
+
**What it writes.** When no headers are sent yet, it sets these and writes a `200` at once
|
|
532
|
+
(`flushHeaders()`), so the browser's `fetch` resolves before the first event:
|
|
533
|
+
|
|
534
|
+
| Header | Value |
|
|
535
|
+
|---|---|
|
|
536
|
+
| `Content-Type` | `text/event-stream; charset=utf-8` |
|
|
537
|
+
| `Cache-Control` | `no-cache, no-transform` |
|
|
538
|
+
| `Connection` | `keep-alive` |
|
|
539
|
+
| `X-Accel-Buffering` | `no` |
|
|
540
|
+
|
|
541
|
+
Then `headers` from the options are set on top: a name replaces the header above whatever its case
|
|
542
|
+
(`cache-control` replaces `Cache-Control`). A header you set on the response before the call
|
|
543
|
+
(`res.setHeader`, a CORS middleware) is kept, unless it has one of these names. The status is
|
|
544
|
+
always `200`. When the headers are already sent (you called `writeHead` yourself), it writes none
|
|
545
|
+
and leaves yours as they are.
|
|
546
|
+
|
|
547
|
+
Each event then becomes one message:
|
|
548
|
+
|
|
549
|
+
```text
|
|
550
|
+
id: 7
|
|
551
|
+
event: tool.start
|
|
552
|
+
data: {"type":"tool.start","callId":"call_1","tool":"search_document","args":{"document_id":"doc_3f9c…","query":"timeout","mode":"exact"},"label":"Search app.log (exact) for “timeout”","documentId":"doc_3f9c…","round":1,"seq":7,"runId":"run_8d2c41f07a9e3b65","time":1795374541651}
|
|
553
|
+
```
|
|
554
|
+
|
|
555
|
+
- `id` is the message's `id`, or else the event's `seq`.
|
|
556
|
+
- `event` is the message's `event`, or else the event's `type`.
|
|
557
|
+
- `data` is the message's `data` as JSON, always on one line. U+2028 and U+2029, which JSON leaves as
|
|
558
|
+
they are, are written `\u2028` and `\u2029`: the same JSON, which a client that splits the stream
|
|
559
|
+
on every Unicode line break still reads whole. `undefined` is sent as `null`.
|
|
560
|
+
- A line break in an `id` or an `event` becomes a space, so that it cannot end the field early.
|
|
561
|
+
|
|
562
|
+
What is sent for an event comes from `map`, [`sseMessageOf()`](#ssemessageofevent) by default. A
|
|
563
|
+
`: keep-alive` comment goes out every `heartbeatMs` (15 seconds by default) while the stream is
|
|
564
|
+
open; browsers and readers skip comments, and proxies see traffic. None is written while it waits
|
|
565
|
+
for the client.
|
|
566
|
+
|
|
567
|
+
**When the client reads slowly.** When `response.write()` returns false, it waits for `drain`
|
|
568
|
+
before it takes the next event. The question or the ingest does not wait: its events wait in
|
|
569
|
+
memory, in the `eventStream`, until they are read.
|
|
570
|
+
|
|
571
|
+
**When it resolves, and when it rejects.**
|
|
572
|
+
|
|
573
|
+
| What happens | What it does |
|
|
574
|
+
|---|---|
|
|
575
|
+
| The events end | Ends the response (unless `end: false`) and resolves. |
|
|
576
|
+
| The client goes away, or someone else ends the response | Stops reading, calls the iterator's `return()` and resolves. Nothing more is written. |
|
|
577
|
+
| The response is already ended or destroyed when it is called | Writes nothing, calls `return()` and resolves. |
|
|
578
|
+
| `map` throws | Calls `return()`, ends the response (unless `end: false`), and rejects with that error. |
|
|
579
|
+
| The iterable throws | Ends the response (unless `end: false`) and rejects with that error. It does not call `return()` of an iterator that failed. An `askStream` or an `eventStream` never throws: a run that fails ends with its `run.error` or `ingest.error` event, and the promise resolves. |
|
|
580
|
+
| A header cannot be set (an invalid name or value in `headers`) | Calls `return()`, destroys the response without a status line, and rejects with that error. |
|
|
581
|
+
|
|
582
|
+
#### When the client goes away
|
|
583
|
+
|
|
584
|
+
When the response closes before the end (the user pressed Stop, closed the tab or lost the
|
|
585
|
+
connection) or `finish`es because something else ended it, `writeSseEvents` stops reading at once,
|
|
586
|
+
even while it waits for the next event, and calls `return()` on the iterator it was reading:
|
|
587
|
+
|
|
588
|
+
- **An `askStream` or an `eventStream` passed in directly** stops its run at once: its signal
|
|
589
|
+
aborts with an `AbortError` ("The events stopped being read."), the request under way stops, and
|
|
590
|
+
no tool call starts. The stream's `result` rejects with that error, and
|
|
591
|
+
[`partialResultOf(error)`](./ask.md#partialresultoferror) gives what the question found. The
|
|
592
|
+
`run.error` event is not sent: nobody reads.
|
|
593
|
+
- **An async generator that wraps one** (to rename events or skip some) is only stopped when it
|
|
594
|
+
next yields. A question that waits on a long model request goes on, and costs, until then. To
|
|
595
|
+
change what is sent, use `map` and pass the stream itself; return `undefined` from `map` to skip
|
|
596
|
+
an event. If you wrap it anyway, stop the run yourself:
|
|
597
|
+
|
|
598
|
+
```ts
|
|
599
|
+
import type { ServerResponse } from "node:http";
|
|
600
|
+
import { askStream, type AskEvent, type AskOptions } from "llm-large-files";
|
|
601
|
+
import { writeSseEvents } from "llm-large-files/node";
|
|
602
|
+
|
|
603
|
+
export async function sendWithoutRequests(res: ServerResponse, options: AskOptions): Promise<void> {
|
|
604
|
+
const stream = askStream(options);
|
|
605
|
+
// The generator only notices the client left when it next yields: stop the question yourself.
|
|
606
|
+
res.once("close", () => stream.abort());
|
|
607
|
+
async function* withoutRequests(): AsyncGenerator<AskEvent> {
|
|
608
|
+
for await (const event of stream) if (!event.type.startsWith("request.")) yield event;
|
|
609
|
+
}
|
|
610
|
+
await writeSseEvents(res, withoutRequests());
|
|
611
|
+
}
|
|
612
|
+
```
|
|
613
|
+
|
|
614
|
+
The same with `map`, which needs no listener of its own:
|
|
615
|
+
|
|
616
|
+
```ts
|
|
617
|
+
import type { ServerResponse } from "node:http";
|
|
618
|
+
import { askStream, type AskOptions } from "llm-large-files";
|
|
619
|
+
import { sseMessageOf, writeSseEvents } from "llm-large-files/node";
|
|
620
|
+
|
|
621
|
+
export async function sendWithoutRequests(res: ServerResponse, options: AskOptions): Promise<void> {
|
|
622
|
+
await writeSseEvents(res, askStream(options), {
|
|
623
|
+
map: (event) => (event.type.startsWith("request.") ? undefined : sseMessageOf(event)),
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
```
|
|
627
|
+
|
|
628
|
+
### sseMessageOf(event)
|
|
629
|
+
|
|
630
|
+
```ts
|
|
631
|
+
declare function sseMessageOf<E extends { type: string; seq: number }>(event: E): SseMessage;
|
|
632
|
+
```
|
|
633
|
+
|
|
634
|
+
The default `map` of [`writeSseEvents()`](#writesseeventsresponse-events-options): what is sent for
|
|
635
|
+
an event. Call it from a `map` of your own to change one event and send the others as they are.
|
|
636
|
+
|
|
637
|
+
It returns `{ event: <type>, id: <seq>, data }`. The `data` is the event itself, `type`, `seq`,
|
|
638
|
+
`runId` and `time` included, for every event but two, which it sends smaller:
|
|
639
|
+
|
|
640
|
+
| Event | `data` |
|
|
641
|
+
|---|---|
|
|
642
|
+
| `run.finish` | `{ type, seq, runId, time, result }`, where `result` holds only `answered`, `text`, `finishReason`, `blockReason`, `steps`, `evidence`, `turns` and `usage`. Not `toolTurns`, `plan`, `budget` or `lastUsage`. |
|
|
643
|
+
| `run.error` | `{ type, seq, runId, time, error, partial }`, where `error` is the event's [`EventError`](./events.md#errors-eventerror) and `partial` holds only `steps`, `evidence` and `usage` of the partial result. Without a partial result, `partial` is left out of the JSON. |
|
|
644
|
+
| Any other event, ingest events included | The event as it is. |
|
|
645
|
+
|
|
646
|
+
A field that is `undefined`, such as `finishReason` or `blockReason`, is left out of the JSON.
|
|
647
|
+
|
|
648
|
+
`toolTurns` are left out even when the question ran with `eventResults: true`: keep them on the
|
|
649
|
+
server, from the stream's `result` or from `partialResultOf(error)`
|
|
650
|
+
([conversations](../guides/conversations.md)). `eventResults: true` does put each tool result in
|
|
651
|
+
its `tool.end` event (`result`), and `sseMessageOf` sends that event as it is: leave
|
|
652
|
+
`eventResults` off for a stream to a browser, or drop `result` in a `map` of your own.
|
|
653
|
+
|
|
654
|
+
```ts
|
|
655
|
+
import type { AskEvent } from "llm-large-files";
|
|
656
|
+
import { sseMessageOf, type SseMessage } from "llm-large-files/node";
|
|
657
|
+
|
|
658
|
+
/** run.error in the app's own words; every other event as sseMessageOf sends it. */
|
|
659
|
+
export function mapForPage(event: AskEvent): SseMessage {
|
|
660
|
+
if (event.type !== "run.error") return sseMessageOf(event);
|
|
661
|
+
const message = event.error.kind === "rate_limit" ? "The assistant is busy. Try again in a minute." : event.error.message;
|
|
662
|
+
return sseMessageOf({ ...event, error: { ...event.error, message } });
|
|
663
|
+
}
|
|
664
|
+
```
|
|
665
|
+
|
|
666
|
+
### `SseMessage`
|
|
667
|
+
|
|
668
|
+
```ts
|
|
669
|
+
type SseMessage = {
|
|
670
|
+
event?: string;
|
|
671
|
+
data: unknown;
|
|
672
|
+
id?: string | number;
|
|
673
|
+
};
|
|
674
|
+
```
|
|
675
|
+
|
|
676
|
+
One message, as a `map` returns it.
|
|
677
|
+
|
|
678
|
+
| Field | Type | Default | What it does |
|
|
679
|
+
|---|---|---|---|
|
|
680
|
+
| `event` | `string` | the event's `type` | The `event:` field: the name a browser's `EventSource` dispatches on. |
|
|
681
|
+
| `data` | `unknown` | required | Any JSON value, sent as JSON on one `data:` line. |
|
|
682
|
+
| `id` | `string \| number` | the event's `seq` | The `id:` field. |
|
|
683
|
+
|
|
684
|
+
### `SseWriteOptions`
|
|
685
|
+
|
|
686
|
+
```ts
|
|
687
|
+
type SseWriteOptions<E> = {
|
|
688
|
+
heartbeatMs?: number;
|
|
689
|
+
headers?: Record<string, string | number | string[]>;
|
|
690
|
+
map?: (event: E) => SseMessage | undefined;
|
|
691
|
+
end?: boolean;
|
|
692
|
+
};
|
|
693
|
+
```
|
|
694
|
+
|
|
695
|
+
The options of [`writeSseEvents()`](#writesseeventsresponse-events-options).
|
|
696
|
+
|
|
697
|
+
| Option | Type | Default | What it does |
|
|
698
|
+
|---|---|---|---|
|
|
699
|
+
| `heartbeatMs` | `number` | `15000` | Milliseconds between two `: keep-alive` comments, which keep proxies and load balancers from closing a quiet stream. 0 sends none. The timer does not keep the process alive. |
|
|
700
|
+
| `headers` | `Record<string, string \| number \| string[]>` | none | Headers to send besides the event-stream ones, or in their place: a name replaces one of them whatever its case. Used only when no headers are sent yet. |
|
|
701
|
+
| `map` | `(event: E) => SseMessage \| undefined` | [`sseMessageOf`](#ssemessageofevent) | What to send for an event. Return `undefined` to skip it. A throw stops the run and rejects. |
|
|
702
|
+
| `end` | `boolean` | `true` | False keeps the response open after the last event, for something you write after it, or to end it yourself once the question is saved. You must then end it: `if (!res.writableEnded && !res.destroyed) res.end()`. |
|
|
703
|
+
|
|
704
|
+
Guide: [web app](../guides/web-app.md), with the route, the browser code that reads the events,
|
|
705
|
+
keep-alive comments and proxies; [deployment](../guides/deployment.md#streamed-answers-behind-proxies),
|
|
706
|
+
for timeouts and buffering on the way to the browser.
|