llm-large-files 0.4.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/CHANGELOG.md +1400 -338
  2. package/README.md +217 -49
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +117 -0
  8. package/dist/anthropic/adapter.d.ts.map +1 -0
  9. package/dist/anthropic/adapter.js +542 -0
  10. package/dist/anthropic/adapter.js.map +1 -0
  11. package/dist/anthropic/index.d.ts +3 -0
  12. package/dist/anthropic/index.d.ts.map +1 -0
  13. package/dist/anthropic/index.js +2 -0
  14. package/dist/anthropic/index.js.map +1 -0
  15. package/dist/ask.d.ts +200 -0
  16. package/dist/ask.d.ts.map +1 -0
  17. package/dist/ask.js +1402 -0
  18. package/dist/ask.js.map +1 -0
  19. package/dist/budget.d.ts +23 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +64 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/encoding.d.ts +17 -0
  24. package/dist/encoding.d.ts.map +1 -0
  25. package/dist/encoding.js +852 -0
  26. package/dist/encoding.js.map +1 -0
  27. package/dist/errors.d.ts +4 -0
  28. package/dist/errors.d.ts.map +1 -1
  29. package/dist/errors.js +15 -0
  30. package/dist/errors.js.map +1 -1
  31. package/dist/events.d.ts +333 -0
  32. package/dist/events.d.ts.map +1 -0
  33. package/dist/events.js +159 -0
  34. package/dist/events.js.map +1 -0
  35. package/dist/evidence.d.ts +42 -0
  36. package/dist/evidence.d.ts.map +1 -0
  37. package/dist/evidence.js +138 -0
  38. package/dist/evidence.js.map +1 -0
  39. package/dist/extract.d.ts +35 -3
  40. package/dist/extract.d.ts.map +1 -1
  41. package/dist/extract.js +626 -58
  42. package/dist/extract.js.map +1 -1
  43. package/dist/gemini/adapter.d.ts +59 -0
  44. package/dist/gemini/adapter.d.ts.map +1 -0
  45. package/dist/gemini/adapter.js +226 -0
  46. package/dist/gemini/adapter.js.map +1 -0
  47. package/dist/gemini/chat.d.ts +53 -77
  48. package/dist/gemini/chat.d.ts.map +1 -1
  49. package/dist/gemini/chat.js +42 -300
  50. package/dist/gemini/chat.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +16 -0
  52. package/dist/gemini/errors.d.ts.map +1 -0
  53. package/dist/gemini/errors.js +46 -0
  54. package/dist/gemini/errors.js.map +1 -0
  55. package/dist/gemini/generate.d.ts +18 -21
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +49 -92
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +6 -4
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +4 -3
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -2
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -38
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/http.d.ts +136 -0
  68. package/dist/http.d.ts.map +1 -0
  69. package/dist/http.js +401 -0
  70. package/dist/http.js.map +1 -0
  71. package/dist/index.d.ts +18 -2
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +13 -4
  74. package/dist/index.js.map +1 -1
  75. package/dist/library.d.ts +96 -8
  76. package/dist/library.d.ts.map +1 -1
  77. package/dist/library.js +414 -96
  78. package/dist/library.js.map +1 -1
  79. package/dist/map-reduce.d.ts +37 -1
  80. package/dist/map-reduce.d.ts.map +1 -1
  81. package/dist/map-reduce.js +255 -61
  82. package/dist/map-reduce.js.map +1 -1
  83. package/dist/model.d.ts +278 -0
  84. package/dist/model.d.ts.map +1 -0
  85. package/dist/model.js +222 -0
  86. package/dist/model.js.map +1 -0
  87. package/dist/node/handlers.d.ts +20 -4
  88. package/dist/node/handlers.d.ts.map +1 -1
  89. package/dist/node/handlers.js +122 -20
  90. package/dist/node/handlers.js.map +1 -1
  91. package/dist/node/index.d.ts +2 -0
  92. package/dist/node/index.d.ts.map +1 -1
  93. package/dist/node/index.js +1 -0
  94. package/dist/node/index.js.map +1 -1
  95. package/dist/node/sse.d.ts +59 -0
  96. package/dist/node/sse.d.ts.map +1 -0
  97. package/dist/node/sse.js +174 -0
  98. package/dist/node/sse.js.map +1 -0
  99. package/dist/openai/adapter.d.ts +109 -0
  100. package/dist/openai/adapter.d.ts.map +1 -0
  101. package/dist/openai/adapter.js +567 -0
  102. package/dist/openai/adapter.js.map +1 -0
  103. package/dist/openai/index.d.ts +3 -0
  104. package/dist/openai/index.d.ts.map +1 -0
  105. package/dist/openai/index.js +2 -0
  106. package/dist/openai/index.js.map +1 -0
  107. package/dist/output-limit.d.ts +42 -0
  108. package/dist/output-limit.d.ts.map +1 -0
  109. package/dist/output-limit.js +121 -0
  110. package/dist/output-limit.js.map +1 -0
  111. package/dist/pause.d.ts +24 -0
  112. package/dist/pause.d.ts.map +1 -0
  113. package/dist/pause.js +38 -0
  114. package/dist/pause.js.map +1 -0
  115. package/dist/pdf-pages.d.ts +32 -2
  116. package/dist/pdf-pages.d.ts.map +1 -1
  117. package/dist/pdf-pages.js +275 -14
  118. package/dist/pdf-pages.js.map +1 -1
  119. package/dist/pdf-pictures.d.ts +30 -3
  120. package/dist/pdf-pictures.d.ts.map +1 -1
  121. package/dist/pdf-pictures.js +50 -8
  122. package/dist/pdf-pictures.js.map +1 -1
  123. package/dist/pdf-work.d.ts +40 -0
  124. package/dist/pdf-work.d.ts.map +1 -0
  125. package/dist/pdf-work.js +734 -0
  126. package/dist/pdf-work.js.map +1 -0
  127. package/dist/plan.d.ts +22 -4
  128. package/dist/plan.d.ts.map +1 -1
  129. package/dist/plan.js +61 -12
  130. package/dist/plan.js.map +1 -1
  131. package/dist/retry.d.ts +76 -0
  132. package/dist/retry.d.ts.map +1 -0
  133. package/dist/retry.js +141 -0
  134. package/dist/retry.js.map +1 -0
  135. package/dist/search.d.ts +8 -2
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +60 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/sse.d.ts +36 -0
  140. package/dist/sse.d.ts.map +1 -0
  141. package/dist/sse.js +153 -0
  142. package/dist/sse.js.map +1 -0
  143. package/dist/stores.d.ts.map +1 -1
  144. package/dist/stores.js +5 -2
  145. package/dist/stores.js.map +1 -1
  146. package/dist/text-index.d.ts +6 -0
  147. package/dist/text-index.d.ts.map +1 -1
  148. package/dist/text-index.js +25 -8
  149. package/dist/text-index.js.map +1 -1
  150. package/dist/text.d.ts +62 -2
  151. package/dist/text.d.ts.map +1 -1
  152. package/dist/text.js +314 -14
  153. package/dist/text.js.map +1 -1
  154. package/dist/tools.d.ts +72 -1
  155. package/dist/tools.d.ts.map +1 -1
  156. package/dist/tools.js +341 -60
  157. package/dist/tools.js.map +1 -1
  158. package/dist/types.d.ts +128 -4
  159. package/dist/types.d.ts.map +1 -1
  160. package/dist/zip-directory.d.ts +43 -0
  161. package/dist/zip-directory.d.ts.map +1 -0
  162. package/dist/zip-directory.js +130 -0
  163. package/dist/zip-directory.js.map +1 -0
  164. package/docs/README.md +288 -0
  165. package/docs/api.md +58 -184
  166. package/docs/configuration.md +34 -490
  167. package/docs/getting-started.md +412 -177
  168. package/docs/guides/anthropic.md +590 -0
  169. package/docs/guides/conversations.md +629 -0
  170. package/docs/guides/costs-and-limits.md +726 -0
  171. package/docs/guides/deployment.md +654 -0
  172. package/docs/guides/errors-and-reliability.md +735 -0
  173. package/docs/guides/explorer-model.md +399 -0
  174. package/docs/guides/openai-compatible.md +602 -0
  175. package/docs/guides/own-adapter-and-loop.md +1169 -0
  176. package/docs/guides/pdfs.md +971 -0
  177. package/docs/guides/storage.md +731 -0
  178. package/docs/guides/testing.md +1199 -0
  179. package/docs/guides/vertex-and-gemini.md +717 -0
  180. package/docs/guides/web-app.md +1589 -0
  181. package/docs/how-it-works.md +1022 -138
  182. package/docs/measurements.md +881 -0
  183. package/docs/publishing.md +274 -46
  184. package/docs/reference/anthropic.md +427 -0
  185. package/docs/reference/ask.md +892 -0
  186. package/docs/reference/errors-and-retries.md +758 -0
  187. package/docs/reference/events.md +993 -0
  188. package/docs/reference/gemini.md +823 -0
  189. package/docs/reference/library.md +1467 -0
  190. package/docs/reference/node.md +528 -0
  191. package/docs/reference/openai.md +385 -0
  192. package/docs/reference/tools.md +883 -0
  193. package/docs/security.md +902 -90
  194. package/docs/troubleshooting.md +1390 -0
  195. package/package.json +22 -4
  196. package/src/analyze.ts +93 -42
  197. package/src/anthropic/adapter.ts +611 -0
  198. package/src/anthropic/index.ts +2 -0
  199. package/src/ask.ts +1560 -0
  200. package/src/budget.ts +71 -0
  201. package/src/encoding.ts +850 -0
  202. package/src/errors.ts +17 -0
  203. package/src/events.ts +442 -0
  204. package/src/evidence.ts +165 -0
  205. package/src/extract.ts +602 -62
  206. package/src/gemini/adapter.ts +271 -0
  207. package/src/gemini/chat.ts +87 -355
  208. package/src/gemini/errors.ts +48 -0
  209. package/src/gemini/generate.ts +67 -94
  210. package/src/gemini/index.ts +6 -4
  211. package/src/gemini/sse.ts +1 -34
  212. package/src/http.ts +434 -0
  213. package/src/index.ts +55 -4
  214. package/src/library.ts +497 -97
  215. package/src/map-reduce.ts +266 -59
  216. package/src/model.ts +433 -0
  217. package/src/node/handlers.ts +137 -22
  218. package/src/node/index.ts +2 -0
  219. package/src/node/sse.ts +198 -0
  220. package/src/openai/adapter.ts +613 -0
  221. package/src/openai/index.ts +2 -0
  222. package/src/output-limit.ts +135 -0
  223. package/src/pause.ts +41 -0
  224. package/src/pdf-pages.ts +268 -15
  225. package/src/pdf-pictures.ts +56 -9
  226. package/src/pdf-work.ts +722 -0
  227. package/src/plan.ts +68 -12
  228. package/src/retry.ts +176 -0
  229. package/src/search.ts +63 -10
  230. package/src/sse.ts +159 -0
  231. package/src/stores.ts +5 -2
  232. package/src/text-index.ts +26 -7
  233. package/src/text.ts +323 -13
  234. package/src/tools.ts +338 -62
  235. package/src/types.ts +129 -5
  236. package/src/zip-directory.ts +136 -0
package/README.md CHANGED
@@ -12,70 +12,190 @@ and 1M tokens of context. This package bridges the gap:
12
12
  - **Pictures in a PDF** are not in its text. The model can **look at the real pages** when it
13
13
  needs to: a chart, a photo, a scan.
14
14
 
15
- It's a small library, not a framework: no model SDK, no server, and no UI are required. A drop-in
16
- Gemini / Vertex AI helper and Node HTTP handlers are included for the common case.
15
+ It's a small library, not a framework: no model SDK, no server, and no UI are required. One tool
16
+ loop, `askWithFiles`, works with any model through an adapter. Adapters for **Gemini and Vertex
17
+ AI**, **any OpenAI-compatible endpoint** and **Claude** are included, and so are Node HTTP handlers.
17
18
 
18
19
  ```bash
19
20
  npm install llm-large-files
20
21
  ```
21
22
 
22
- ## Quickstart (Gemini, 10 lines)
23
+ ## Quickstart
24
+
25
+ With Gemini on Vertex AI, and an access token from Application Default Credentials
26
+ (`npm install google-auth-library`; on your own machine, `gcloud auth application-default login`):
23
27
 
24
28
  ```ts
29
+ import { readFile } from "node:fs/promises";
30
+ import { GoogleAuth } from "google-auth-library";
25
31
  import { createLargeFiles, FileDocumentStore } from "llm-large-files";
26
- import { askGemini, geminiApi } from "llm-large-files/gemini";
32
+ import { askGemini, vertexAi } from "llm-large-files/gemini";
27
33
 
28
34
  const files = createLargeFiles({ store: new FileDocumentStore("./data/large-files") });
29
35
 
30
36
  // When a user uploads a file:
31
- const doc = await files.ingest({ name: "app.log", bytes: fileBytes });
37
+ const doc = await files.ingest({ name: "app.log", bytes: await readFile("./app.log") });
32
38
 
33
39
  // When they ask about it:
34
- const { text, steps } = await askGemini({
40
+ const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
41
+ const endpoint = vertexAi({
42
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
43
+ model: "gemini-3.8-flash",
44
+ accessToken: async () => (await auth.getAccessToken())!, // asked for on each request
45
+ });
46
+ const result = await askGemini({
35
47
  files,
36
- endpoint: geminiApi({ apiKey: process.env.GEMINI_API_KEY!, model: "gemini-3.8-flash" }),
48
+ endpoint,
37
49
  documentIds: [doc.id],
38
50
  messages: [{ role: "user", text: "What caused the outage, and when? Cite lines." }],
39
- onText: (delta) => process.stdout.write(delta), // optional streaming
51
+ onText: (delta) => process.stdout.write(delta), // optional: the answer as it streams
40
52
  });
41
53
  ```
42
54
 
43
- `steps` lists what the model did, for example
44
- `Search app.log (exact) for “failover” — 1 matching lines`. Show it under the answer so users can
45
- see where the answer came from.
55
+ `result.steps` lists the tool calls in order, such as
56
+ `Search app.log (exact) for “failover” — 12 matching lines`, with the loop's own notices among
57
+ them (`Older tool results were shortened to make room in the request`). Show it under the answer so
58
+ users can see where the answer came from, as plain text: the steps quote what the model sent.
59
+
60
+ Using the **Gemini API** with a key, or an **enterprise gateway**? Swap the endpoint:
61
+
62
+ ```ts
63
+ import { geminiApi, type GeminiEndpoint } from "llm-large-files/gemini";
64
+
65
+ const withKey = geminiApi({ apiKey: process.env.GEMINI_API_KEY!, model: "gemini-3.8-flash" });
66
+
67
+ // Your own proxy of Generate Content. Its headers are sent exactly as given.
68
+ const viaGateway: GeminiEndpoint = {
69
+ url: "https://llm-gateway.example.com/v1/gemini:generateContent",
70
+ streamUrl: "https://llm-gateway.example.com/v1/gemini:streamGenerateContent?alt=sse", // without it, no streaming
71
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.GATEWAY_KEY}` },
72
+ };
73
+ ```
74
+
75
+ ## Any model
46
76
 
47
- Using **Vertex AI** or an **enterprise gateway**? Swap the endpoint:
77
+ `askGemini` is `askWithFiles` with a Gemini model. With another provider, name the model yourself:
48
78
 
49
79
  ```ts
50
- import { vertexAi } from "llm-large-files/gemini";
51
- const endpoint = vertexAi({ project: "my-project", model: "gemini-3.8-flash", accessToken: getToken });
52
- // or your own proxy:
53
- const endpoint = { url: "https://llm-gw.corp/v1/gemini:generateContent", headers: { Authorization: `Bearer ${key}` } };
80
+ import { askWithFiles } from "llm-large-files";
81
+ import { openAiCompatible } from "llm-large-files/openai";
82
+ import { anthropic } from "llm-large-files/anthropic";
83
+
84
+ // OpenAI, Azure OpenAI, DeepSeek, LiteLLM, vLLM, Ollama, OpenRouter: anything that speaks Chat Completions.
85
+ const deepseek = openAiCompatible({ baseUrl: "https://api.deepseek.com/v1", apiKey: process.env.DEEPSEEK_API_KEY!, model: "deepseek-v4-pro" });
86
+ // Claude. `fallbacks` lets another model answer when a safety classifier declines the request.
87
+ const claude = anthropic({ apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-opus-5-5", fallbacks: "default" });
88
+
89
+ const withClaude = await askWithFiles({
90
+ files, // `files` and `doc` are those of the quickstart
91
+ model: claude, // writes the answer
92
+ explorer: deepseek, // optional: a second model, of any provider, that searches and reads
93
+ documentIds: [doc.id],
94
+ messages: [{ role: "user", text: "What caused the outage, and when? Cite lines." }],
95
+ onText: (delta) => process.stdout.write(delta),
96
+ });
97
+
98
+ withClaude.answered; // false when the last reply had no text (a blocked prompt, a reply cut off before any text, a tool call that could not be read): show your own message
99
+ withClaude.usage; // { requests: 5, inputTokens: 32662, cachedInputTokens: 6086, outputTokens: 750, thoughtTokens: 0, byModel: { … } }
100
+ withClaude.evidence; // [{ tool: "read_document", documentId, document: "app.log", lines: [[34100, 34110]] }, …]
101
+ withClaude.toolTurns; // pass these back in `messages`, between this question and its answer: a follow-up then needs no new search
54
102
  ```
55
103
 
104
+ How to keep a chat's history, tool turns included, across requests and servers:
105
+ [Conversations](docs/guides/conversations.md).
106
+
107
+ Every model gets the same loop. A failed request is sent again when another try can help (a lost
108
+ connection, HTTP 408, 409, 429 or 5xx), never for a quota that ran out or once text was shown. With
109
+ the built-in adapters, a model silent for 10 minutes before its reply (`firstByteTimeoutMs`) or 5
110
+ minutes inside it (`idleTimeoutMs`) is cut off and asked once more. A request the provider refuses
111
+ as too large is made smaller, or the files are planned again for a window a little smaller than the
112
+ one it names. An empty first reply, an unreadable tool call, or an answer that comes back without
113
+ text is asked for again, a repeated call gets a pointer to the result already shown, and by default
114
+ each file is read whole at most once a question.
115
+
116
+ A question that fails throws `DocumentsNotFoundError` for a file that expired, was deleted, or
117
+ belongs to another `owner`, `DocumentStoreError` when the store cannot be read, or a
118
+ `ModelRequestError` whose `kind` (`"rate_limit"`, `"quota"`, `"timeout"`, `"context_overflow"`, …)
119
+ tells you what to show the user. `partialResultOf(error)` gives what it found and paid for:
120
+ [Errors and reliability](docs/guides/errors-and-reliability.md).
121
+
122
+ A model that has no adapter needs one object with an `id`, its `capabilities` (at least `toolFiles`
123
+ and `pageTokens`) and a `send` method, plus `generateText` to read whole files in parts:
124
+ [your own adapter](docs/guides/own-adapter-and-loop.md).
125
+
56
126
  ## Add it to a web app
57
127
 
58
128
  ```ts
59
129
  import express from "express";
60
130
  import { createDocumentHandlers } from "llm-large-files/node";
61
131
 
62
- const documents = createDocumentHandlers(files, { getOwner: (req) => req.user?.id });
63
- app.post("/api/documents", documents.upload); // mount before express.json()
132
+ const app = express();
133
+ // `files` is the quickstart's. getOwner names the signed-in user (here, set on req.user by your
134
+ // auth middleware): each upload is then theirs alone.
135
+ const documents = createDocumentHandlers(files, {
136
+ getOwner: (req) => (req as typeof req & { user?: { id: string } }).user?.id,
137
+ });
138
+ app.post("/api/documents", documents.upload); // mount before express.json(): the body is the raw file
139
+ app.get("/api/documents/:id", (req, res) => documents.get(req, res, req.params.id));
64
140
  app.delete("/api/documents/:id", (req, res) => documents.remove(req, res, req.params.id));
65
141
  ```
66
142
 
67
- The browser uploads the raw file:
143
+ The browser uploads the raw file (`file` comes from an `<input type="file">`):
68
144
 
69
145
  ```ts
70
- await fetch("/api/documents", {
146
+ const response = await fetch("/api/documents", {
71
147
  method: "POST",
72
148
  headers: { "Content-Type": "application/octet-stream", "X-File-Name": encodeURIComponent(file.name) },
73
149
  body: file,
74
- }); // → { id, name, format, lines, estimatedTokens, expiresAt, ... }
150
+ });
151
+ const summary = await response.json(); // 201: { id, name, format, lines, estimatedTokens, expiresAt, … }; otherwise { error }
75
152
  ```
76
153
 
77
- The full walkthrough, with streaming to the browser, is in the [integration guide](docs/getting-started.md).
78
- There's also a [one-file demo server](examples/server.ts).
154
+ When the user asks, stream the question to the page with `askStream` (new in 0.7.0): typed events
155
+ in order, from `run.start` through each tool call, its progress and the text as it is written, to
156
+ `run.finish` or `run.error`. Errors in events are told in words for users, and no text of the
157
+ documents is in them:
158
+
159
+ ```ts
160
+ import { askStream } from "llm-large-files";
161
+ import { writeSseEvents } from "llm-large-files/node";
162
+
163
+ app.post("/api/chat", express.json(), async (req, res) => {
164
+ const stream = askStream({
165
+ files, model: claude, // `claude` is the adapter of "Any model"
166
+ owner: (req as typeof req & { user?: { id: string } }).user?.id,
167
+ documentIds: [String(req.body.documentId)],
168
+ messages: [{ role: "user", text: String(req.body.question) }],
169
+ });
170
+ await writeSseEvents(res, stream); // one SSE message per event; stops the question if the page leaves
171
+ });
172
+ ```
173
+
174
+ Pass the upload's `id` in `documentIds` and the same user as `owner`: a document
175
+ that has an owner is missing for anyone else. This `getOwner` returns `undefined` for an anonymous
176
+ upload. Never return an empty string: it would be one owner shared by every caller without a user,
177
+ and the upload is answered 500. Reading the events in the browser, the upload's own progress, and
178
+ cancelling are in the [web app guide](docs/guides/web-app.md); every event is in
179
+ [Events](docs/reference/events.md). There's also a
180
+ [one-file demo server](https://github.com/renanbazinin/llm-large-files/blob/main/examples/server.ts) and a [command-line script](https://github.com/renanbazinin/llm-large-files/blob/main/examples/ask-cli.ts): from a
181
+ clone of this repository, run `npm install` and `npm run build`, then run them with Node 22.18 or a
182
+ later 22.x, or Node 23.6 or later.
183
+
184
+ **Uploads you do not trust.** These handlers read each upload in your server's process. Ingest
185
+ limits the text, the pages and the time of one file, refuses the zip bombs and the PDFs built to
186
+ hold a server that its checks recognize, and pauses for other requests between pages and slices of
187
+ its work. It does not refuse every file built to hurt a server. While a file is read, it takes
188
+ memory from your server's heap. Some steps run in one block, and no other request is answered
189
+ meanwhile. pdf.js reads one page of a PDF in one block: up to about 1.5 s for a page of a small
190
+ file that passes the page check, longer in a large file. `@cantoo/pdf-lib` reads one object of a
191
+ PDF in one block, about 0.1 to 0.35 s for each MB of it. Neither it nor pdf.js checks the memory
192
+ an object takes before building it: a crafted PDF of 732 bytes, whose object stream unpacks to
193
+ 4 MB of empty dictionaries, ran a heap of 512 MB out of memory at ingest. What a stream unpacks to
194
+ is outside the heap: one of 1.6 KB took 1.6 GB of memory with 20 MB of heap. If your users can
195
+ upload files you do not trust, ingest them in a child process with its own heap limit, memory
196
+ limit and timer, as [Deployment](docs/guides/deployment.md#uploads-and-ingest) shows, and do not
197
+ offer `view_pages` on their documents. What is refused, and what still holds the server:
198
+ [Security](docs/security.md#uploads).
79
199
 
80
200
  ## Pictures, charts and scans in PDFs
81
201
 
@@ -83,21 +203,28 @@ A large PDF goes to the model as text, and text cannot show a chart. Keep the up
83
203
  the model gets a tool, `view_pages`, that hands it the pages it asks for as a small PDF:
84
204
 
85
205
  ```bash
86
- npm install @cantoo/pdf-lib
206
+ npm install unpdf @cantoo/pdf-lib # Node 24; for Node 20 and 22, see Requirements
87
207
  ```
88
208
 
89
209
  ```ts
210
+ // In place of the quickstart's files:
90
211
  const files = createLargeFiles({
91
212
  store: new FileDocumentStore("./data/large-files"),
92
- keepOriginals: ["pdf"], // off by default: a kept file takes disk space until it expires
213
+ keepOriginals: ["pdf"], // off by default: a kept file takes disk space until it expires and is swept
93
214
  });
215
+ setInterval(() => files.sweep().catch(console.error), 60 * 60 * 1000).unref(); // removes expired documents and their files
94
216
  // askGemini needs no change. A step then reads: Look at report.pdf pages 12-14
95
217
  ```
96
218
 
219
+ `unpdf` reads the text of a PDF, and `@cantoo/pdf-lib` cuts its pages. With `askWithFiles`,
220
+ `view_pages` is offered only when every model of the question can be sent a file: `gemini()` and
221
+ `anthropic()` can by default, `openAiCompatible()` only with `pdfInput: true`. So the question
222
+ above, with DeepSeek exploring, is not offered `view_pages` at all.
223
+
97
224
  Asked which bar of a chart is tallest, `gemini-3.5-flash-lite` said from the text that it could
98
225
  not see the chart; with `view_pages` it looked at the page and answered correctly. It did not look
99
- at a page for any of ten questions that the text answers. A page costs about 530 tokens.
100
- Details, limits and measurements: [Pictures in PDFs](docs/configuration.md#pictures-in-pdfs).
226
+ at a page for any of ten questions that the text answers. On Gemini a page costs about 530 tokens;
227
+ `anthropic()` counts 3,500 for Claude by default. Scans, tables, limits: [PDFs](docs/guides/pdfs.md).
101
228
 
102
229
  ## One model to explore, another to answer
103
230
 
@@ -106,10 +233,12 @@ default. That model does both halves of the work on a large file. It explores th
106
233
  reads, looks at pages), and then it answers. You can name a second model for the first half:
107
234
 
108
235
  ```ts
109
- const endpoint = geminiApi({
110
- apiKey: process.env.GEMINI_API_KEY!,
236
+ // In place of the quickstart's endpoint:
237
+ const endpoint = vertexAi({
238
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
111
239
  model: "gemini-3.8-flash", // writes the answer
112
240
  explorerModel: process.env.GEMINI_EXPLORER_MODEL, // optional: searches and reads
241
+ accessToken: async () => (await auth.getAccessToken())!, // `auth` is the quickstart's
113
242
  });
114
243
  ```
115
244
 
@@ -117,48 +246,87 @@ Left out or empty, nothing changes: one model does both. With an explorer, the m
117
246
  search through a large file go to that model, which can be a cheaper or faster one, and `model`
118
247
  gets what the tools returned and writes the answer in one request. In eleven live checks with
119
248
  `gemini-3.5-flash-lite` exploring, the other model answered every one correctly from what it found.
120
- What each model gets, and what it costs: [An explorer model](docs/configuration.md#an-explorer-model).
249
+ What each model gets, and what it costs: [An explorer model](docs/guides/explorer-model.md).
121
250
 
122
251
  ## What it handles
123
252
 
124
253
  | | |
125
254
  |---|---|
126
- | **Formats** | Text, Markdown, logs (UTF-8 and UTF-16), JSON/JSONL, CSV/TSV, DOCX, PPTX, PDF (text layer, with tables rebuilt so empty cells stay empty; pages with a picture are marked, and the model can look at the pages themselves; scans of up to 30 pages) |
255
+ | **Formats** | Text, Markdown, logs (UTF-8 and UTF-16, and Hebrew, Arabic, Cyrillic, Japanese and Western European text in its older encoding), JSON/JSONL, CSV/TSV, DOCX, PPTX, PDF (text layer, with tables rebuilt so empty cells stay empty; pages with a picture are marked, and the model can look at the pages themselves; scans of up to 30 pages when PDFs are kept) |
127
256
  | **Logs** | Detected automatically; the card shows level counts, the time range, and the most frequent errors grouped by shape (`timeout after <n>ms to <ip>`) |
128
257
  | **Books and documents** | An outline of headings with line numbers, including Markdown, "Chapter 12", numbered sections, and Hebrew chapter titles |
129
- | **Limits** | One budget covers tokens *and* request bytes, so files fit both your context window and your connector's payload limit |
258
+ | **Limits** | One budget covers tokens *and* request bytes, so files fit both your context window and your connector's payload limit. It assumes 1M tokens and 10 MB: set `budget.contextTokens` for your model's window (an adapter's `contextTokens` can only make it smaller) |
259
+ | **Reliability** | Retries, waits on a silent model, recovery from a request too large, error kinds: see [Errors and reliability](docs/guides/errors-and-reliability.md) |
260
+ | **Models** | Gemini and Vertex AI, any OpenAI-compatible endpoint, Claude, or an adapter of your own. Two models of different providers can share a question |
261
+ | **Cost** | Usage summed over every request of a question, for each model, with ceilings on whole-file reads, requests and input tokens |
130
262
  | **Privacy** | Documents can belong to an `owner`; other users can't plan, read, or delete them |
263
+ | **Hostile uploads** | Limits on the text, pages and time of one file; zip bombs and PDFs built to exhaust a server are refused when the checks recognize them; ingest pauses for other requests between pages and slices. Not every hostile file is refused, parsing shares your server's heap, and some steps hold the server for a while: ingest untrusted uploads in a process of their own ([Security](docs/security.md#uploads)) |
131
264
  | **Storage** | In memory, on disk with expiry, or your own store (Redis, S3, a database) |
132
265
 
133
266
  ## Live results
134
267
 
135
- With `gemini-3.8-flash` on the Gemini API:
136
-
137
- | File | Question | Result |
138
- |---|---|---|
139
- | 5 MB log, about 1.27M tokens (over the 1M limit) | "What caused the outage?" | Correct root cause, citing the right lines, in about 60 s over 11 tool calls |
140
- | 467 KB novel, about 117K tokens | "Where was the ledger hidden?" | Sent whole; correct. Estimated 116,840 tokens; Gemini billed 116,842 |
141
- | Same novel, map-reduce | "Read all of it…" | 4 parts read in parallel; correct, cited answer in 32 s |
142
- | PDF with a chart and photos (`gemini-3.5-flash-lite`) | "Which bar is tallest, and what number is on the sign?" | Looked at 2 pages unasked; all five facts right, in 3 s. From the text alone: "cannot see the chart" |
268
+ With `gemini-3.8-flash` on the Gemini API, a 5 MB log of about 1.27M tokens, over the 1M window,
269
+ got the right root cause of an outage, citing the right lines, in about 60 s over 11 tool calls.
270
+ Every live result with its date, model and setup, and what has not been run live, such as the
271
+ Claude adapter: [Measurements](docs/measurements.md).
143
272
 
144
273
  ## Documentation
145
274
 
146
- - [Integration guide](docs/getting-started.md): Express, plain Node, browser upload, streaming, Vertex AI, gateways, existing chat history
147
- - [API reference](docs/api.md)
148
- - [Configuration](docs/configuration.md): budget, an explorer model, stores, formats, extractors, pictures in PDFs
149
- - [How it works](docs/how-it-works.md): planner, cards, tools, map-reduce, looking at pages, and the Gemini quirks it handles
150
- - [Security](docs/security.md): owners, tool scoping, retention, original files, regex safety
275
+ - [Documentation index](docs/README.md): where to start, which entry point to use, a glossary, and every page in one line.
276
+ - [Getting started](docs/getting-started.md): install, a quickstart that runs, and the integration in short steps.
277
+
278
+ Guides, one task each:
279
+
280
+ - [Gemini and Vertex AI](docs/guides/vertex-and-gemini.md): endpoints, access tokens, thinking, whole-file reads, pages, gateways, Vertex quotas and errors.
281
+ - [OpenAI-compatible endpoints](docs/guides/openai-compatible.md): OpenAI, Azure OpenAI, DeepSeek, OpenRouter, vLLM, Ollama, LiteLLM, llama.cpp.
282
+ - [Claude](docs/guides/anthropic.md): setup, thinking, streaming, conversations that may only grow, gateways.
283
+ - [An explorer model](docs/guides/explorer-model.md): a cheaper model that explores the files while another answers.
284
+ - [Web app](docs/guides/web-app.md): uploads, answers and progress streamed over Server-Sent Events, cancelling.
285
+ - [Conversations](docs/guides/conversations.md): the history you keep, tool turns included, across requests and servers.
286
+ - [Storage](docs/guides/storage.md): the store contract, owners, a layout per user and per chat session, retention.
287
+ - [Deployment](docs/guides/deployment.md): several servers, memory, sweeps, proxies and timeouts for streams, upgrades.
288
+ - [Errors and reliability](docs/guides/errors-and-reliability.md): every error and what to show the user, retries, waits, deadlines.
289
+ - [Costs and limits](docs/guides/costs-and-limits.md): the limits of a question, the budget per model, usage per user or session.
290
+ - [PDFs](docs/guides/pdfs.md): formats and optional packages, tables, pictures, `view_pages`, scans, extractors and OCR.
291
+ - [Your own adapter or loop](docs/guides/own-adapter-and-loop.md): a model without an adapter, or a tool loop of your own.
292
+ - [Testing](docs/guides/testing.md): testing your integration without a real model.
293
+
294
+ Reference, one page per module:
295
+
296
+ - [`llm-large-files`: the library and its documents](docs/reference/library.md): `createLargeFiles`, stores, budget, extractors.
297
+ - [`llm-large-files`: the tool loop](docs/reference/ask.md): `askWithFiles`, its options and result, the adapter contract.
298
+ - [`llm-large-files`: errors, retries, streams](docs/reference/errors-and-retries.md): `ModelRequestError` and its kinds, `withRetry`, `parseSseJson`.
299
+ - [`llm-large-files`: the tools](docs/reference/tools.md): every tool the model sees, its arguments, results and limits.
300
+ - [`llm-large-files`: events](docs/reference/events.md): `askStream`, the events of a question and of an ingest, `eventStream`.
301
+ - [`llm-large-files/gemini`](docs/reference/gemini.md): `askGemini`, `gemini()`, `geminiApi()`, `vertexAi()`.
302
+ - [`llm-large-files/openai`](docs/reference/openai.md): `openAiCompatible()` and its options.
303
+ - [`llm-large-files/anthropic`](docs/reference/anthropic.md): `anthropic()` and its options.
304
+ - [`llm-large-files/node`](docs/reference/node.md): `createDocumentHandlers`, its routes and responses.
305
+
306
+ [Changelog](CHANGELOG.md): what each version changed, and what to change in your code when you upgrade.
307
+
308
+ Also: [How it works](docs/how-it-works.md), [Security](docs/security.md),
309
+ [Troubleshooting](docs/troubleshooting.md) and [Measurements](docs/measurements.md). For
310
+ maintainers: [Contributing](https://github.com/renanbazinin/llm-large-files/blob/main/CONTRIBUTING.md) and [Publishing](docs/publishing.md).
151
311
 
152
312
  ## Requirements
153
313
 
154
- Node.js 20.19 or newer. The package is ESM; CommonJS projects can `require()` it on Node 20.19+ and 22.12+.
155
- For DOCX/PPTX install `jszip`, for PDF install `unpdf`, and to mark and show the pages of a PDF
156
- install `@cantoo/pdf-lib`. All three are optional:
314
+ Node.js 20.19 or newer. The package is ESM; CommonJS code can `require()` it on Node 20.19+ and
315
+ 22.12+. For DOCX/PPTX install `jszip`, for PDF install `unpdf`, and to mark and show the pages of a
316
+ PDF, and refuse a page built to hold the server before it is read, install `@cantoo/pdf-lib`. All
317
+ three are optional:
157
318
 
158
319
  ```bash
159
- npm install jszip unpdf @cantoo/pdf-lib
320
+ npm install jszip unpdf @cantoo/pdf-lib # Node 24 and later
321
+ npm install jszip unpdf@1 @cantoo/pdf-lib # Node 22
322
+ npm install jszip unpdf@1.7.0 @cantoo/pdf-lib # Node 20
160
323
  ```
161
324
 
325
+ On Node 24 and later, `npm install unpdf` installs unpdf 2, which asks for Node 24. On Node 20,
326
+ unpdf 1.9 and later cannot load pdf.js, and on Node 20 and 22 the pdf.js of unpdf 1.5.0 to 1.6.0
327
+ would stop the whole process. Such an unpdf is refused at the first PDF, with a message that says
328
+ what to install.
329
+
162
330
  ## License
163
331
 
164
332
  [MIT](LICENSE)
package/dist/analyze.d.ts CHANGED
@@ -1,9 +1,14 @@
1
+ import type { TimeSlicer } from "./pause.js";
1
2
  import type { DocumentFormat, LogProfile, OutlineEntry } from "./types.js";
2
3
  /** Treats text as a log when most early lines start with a timestamp or a level. */
3
4
  export declare function looksLikeLog(lines: string[]): boolean;
4
5
  /** Headings with line numbers: Markdown, slide/page markers, and common book and report patterns. */
5
6
  export declare function buildOutline(lines: string[], format: DocumentFormat): OutlineEntry[];
7
+ /** `buildOutline`, the same result, with pauses for other requests while a large file is read. */
8
+ export declare function buildOutlineInSlices(lines: string[], format: DocumentFormat, slicer: TimeSlicer): Promise<OutlineEntry[]>;
6
9
  /** Replaces the variable parts of a log message so repeated failures group together. */
7
10
  export declare function logTemplate(line: string): string;
8
11
  export declare function buildLogProfile(lines: string[]): LogProfile;
12
+ /** `buildLogProfile`, the same result, with pauses for other requests while a large log is read. */
13
+ export declare function buildLogProfileInSlices(lines: string[], slicer: TimeSlicer): Promise<LogProfile>;
9
14
  //# sourceMappingURL=analyze.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"analyze.d.ts","sourceRoot":"","sources":["../src/analyze.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAY,UAAU,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AASrF,oFAAoF;AACpF,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAKrD;AAED,qGAAqG;AACrG,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,cAAc,GAAG,YAAY,EAAE,CA6BpF;AAED,wFAAwF;AACxF,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAYhD;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,UAAU,CAgC3D"}
1
+ {"version":3,"file":"analyze.d.ts","sourceRoot":"","sources":["../src/analyze.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C,OAAO,KAAK,EAAE,cAAc,EAAY,UAAU,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AASrF,oFAAoF;AACpF,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAMrD;AAED,qGAAqG;AACrG,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,cAAc,GAAG,YAAY,EAAE,CAQpF;AAED,kGAAkG;AAClG,wBAAsB,oBAAoB,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC,CAS/H;AAsCD,wFAAwF;AACxF,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAYhD;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,UAAU,CAI3D;AAED,oGAAoG;AACpG,wBAAsB,uBAAuB,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAOtG"}
package/dist/analyze.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { sliceWhole } from "./text.js";
1
2
  const MAX_OUTLINE_ENTRIES = 400;
2
3
  const MAX_TEMPLATES = 50_000;
3
4
  const TIMESTAMP = /\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:[.,]\d+)?(?:Z|[+-]\d{2}:?\d{2})?/;
@@ -6,7 +7,10 @@ const LEVEL = /\b(FATAL|CRITICAL|ERROR|ERR|WARN|WARNING|INFO|DEBUG|TRACE)\b/;
6
7
  const LEVEL_NAMES = { ERR: "ERROR", WARNING: "WARN", CRITICAL: "FATAL" };
7
8
  /** Treats text as a log when most early lines start with a timestamp or a level. */
8
9
  export function looksLikeLog(lines) {
9
- const sample = lines.filter((line) => line.trim()).slice(0, 200);
10
+ const sample = [];
11
+ for (let index = 0; index < lines.length && sample.length < 200; index++)
12
+ if (lines[index].trim())
13
+ sample.push(lines[index]);
10
14
  if (sample.length < 5)
11
15
  return false;
12
16
  const hits = sample.filter((line) => LINE_START_TIMESTAMP.test(line.trim()) || /^\[?(FATAL|ERROR|WARN|WARNING|INFO|DEBUG|TRACE)\b/.test(line.trim())).length;
@@ -18,30 +22,53 @@ export function buildOutline(lines, format) {
18
22
  return [];
19
23
  const entries = [];
20
24
  for (let index = 0; index < lines.length; index++) {
21
- const line = (lines[index] ?? "").trim();
22
- if (!line || line.length > 120)
23
- continue;
24
- const previousBlank = index === 0 || !(lines[index - 1] ?? "").trim();
25
- let entry;
26
- const markdown = /^(#{1,6})\s+(.+)$/.exec(line);
27
- if (markdown)
28
- entry = { line: index + 1, level: markdown[1].length, title: markdown[2].trim() };
29
- // A lookahead, not \b: JavaScript's \b does not treat Hebrew letters as word characters.
30
- else if (/^(chapter|part|book|section|appendix|פרק|חלק|נספח)(?=[\s:.\d]|$)/iu.test(line) && previousBlank) {
31
- entry = { line: index + 1, level: /^(part|book|חלק)(?=[\s:.\d]|$)/iu.test(line) ? 1 : 2, title: line };
32
- }
33
- else if (/^\d+(\.\d+){0,2}\s+\S/.test(line) && previousBlank && line.length <= 80 && !/[.:;,]$/.test(line)) {
34
- entry = { line: index + 1, level: (line.split(" ")[0].match(/\./g)?.length ?? 0) + 2, title: line };
35
- }
36
- else if (previousBlank && line.length >= 4 && line.length <= 60 && /\p{Lu}/u.test(line) && line === line.toUpperCase() && /\p{L}{3}/u.test(line)) {
37
- entry = { line: index + 1, level: 2, title: line };
38
- }
25
+ const entry = outlineEntry(lines, index);
26
+ if (entry)
27
+ entries.push(entry);
28
+ }
29
+ return pickOutline(entries);
30
+ }
31
+ /** `buildOutline`, the same result, with pauses for other requests while a large file is read. */
32
+ export async function buildOutlineInSlices(lines, format, slicer) {
33
+ if (format === "log" || format === "json" || format === "csv")
34
+ return [];
35
+ const entries = [];
36
+ for (let index = 0; index < lines.length; index++) {
37
+ const entry = outlineEntry(lines, index);
39
38
  if (entry)
40
39
  entries.push(entry);
40
+ if ((index & 4095) === 4095)
41
+ await slicer.maybePause();
42
+ }
43
+ return pickOutline(entries);
44
+ }
45
+ /** The heading on line `index` (0-based), if it is one. */
46
+ function outlineEntry(lines, index) {
47
+ const line = (lines[index] ?? "").trim();
48
+ if (!line || line.length > 120)
49
+ return undefined;
50
+ const previousBlank = index === 0 || !(lines[index - 1] ?? "").trim();
51
+ const markdown = /^(#{1,6})\s+(.+)$/.exec(line);
52
+ if (markdown)
53
+ return { line: index + 1, level: markdown[1].length, title: markdown[2].trim() };
54
+ // A lookahead, not \b: JavaScript's \b does not treat Hebrew letters as word characters.
55
+ if (/^(chapter|part|book|section|appendix|פרק|חלק|נספח)(?=[\s:.\d]|$)/iu.test(line) && previousBlank) {
56
+ return { line: index + 1, level: /^(part|book|חלק)(?=[\s:.\d]|$)/iu.test(line) ? 1 : 2, title: line };
57
+ }
58
+ if (/^\d+(\.\d+){0,2}\s+\S/.test(line) && previousBlank && line.length <= 80 && !/[.:;,]$/.test(line)) {
59
+ return { line: index + 1, level: (line.split(" ")[0].match(/\./g)?.length ?? 0) + 2, title: line };
60
+ }
61
+ if (previousBlank && line.length >= 4 && line.length <= 60 && /\p{Lu}/u.test(line) && line === line.toUpperCase() && /\p{L}{3}/u.test(line)) {
62
+ return { line: index + 1, level: 2, title: line };
41
63
  }
64
+ return undefined;
65
+ }
66
+ /** The outline kept from all the headings found: at most 400 of them. */
67
+ function pickOutline(entries) {
42
68
  if (entries.length <= MAX_OUTLINE_ENTRIES)
43
69
  return entries;
44
- // Keep the top levels first, then sample evenly so the outline still spans the document.
70
+ // Keep the top-level headings when there are at least 20 of them. A pool that fits is kept whole;
71
+ // a larger one is sampled evenly, so the outline still spans the document.
45
72
  // A loop, not Math.min(...levels): spreading a few hundred thousand values overflows the stack.
46
73
  let minLevel = Number.POSITIVE_INFINITY;
47
74
  for (const entry of entries)
@@ -49,12 +76,15 @@ export function buildOutline(lines, format) {
49
76
  minLevel = entry.level;
50
77
  const top = entries.filter((entry) => entry.level === minLevel);
51
78
  const pool = top.length >= 20 ? top : entries;
79
+ if (pool.length <= MAX_OUTLINE_ENTRIES)
80
+ return pool;
81
+ // The step is above 1 here, so each sampled index is greater than the one before it.
52
82
  const step = pool.length / MAX_OUTLINE_ENTRIES;
53
- return Array.from({ length: Math.min(pool.length, MAX_OUTLINE_ENTRIES) }, (_, index) => pool[Math.floor(index * step)]);
83
+ return Array.from({ length: MAX_OUTLINE_ENTRIES }, (_, index) => pool[Math.floor(index * step)]);
54
84
  }
55
85
  /** Replaces the variable parts of a log message so repeated failures group together. */
56
86
  export function logTemplate(line) {
57
- return line
87
+ const template = line
58
88
  .replace(TIMESTAMP, "")
59
89
  .replace(/^\W*\d{2}:\d{2}:\d{2}(?:[.,]\d+)?/, "")
60
90
  .replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, "<id>")
@@ -63,44 +93,63 @@ export function logTemplate(line) {
63
93
  .replace(/"[^"]{0,200}"|'[^']{0,200}'/g, "<s>")
64
94
  .replace(/\d+(?:\.\d+)?/g, "<n>")
65
95
  .replace(/\s+/g, " ")
66
- .trim()
67
- .slice(0, 180);
96
+ .trim();
97
+ return sliceWhole(template, 180);
68
98
  }
69
99
  export function buildLogProfile(lines) {
70
- const levels = {};
71
- const templates = new Map();
72
- let firstTimestamp;
73
- let lastTimestamp;
100
+ const profile = new LogProfiler();
101
+ for (let index = 0; index < lines.length; index++)
102
+ profile.add(lines[index] ?? "", index);
103
+ return profile.result();
104
+ }
105
+ /** `buildLogProfile`, the same result, with pauses for other requests while a large log is read. */
106
+ export async function buildLogProfileInSlices(lines, slicer) {
107
+ const profile = new LogProfiler();
74
108
  for (let index = 0; index < lines.length; index++) {
75
- const line = lines[index] ?? "";
109
+ profile.add(lines[index] ?? "", index);
110
+ if ((index & 4095) === 4095)
111
+ await slicer.maybePause();
112
+ }
113
+ return profile.result();
114
+ }
115
+ /** Builds a log profile one line at a time. */
116
+ class LogProfiler {
117
+ levels = {};
118
+ templates = new Map();
119
+ firstTimestamp;
120
+ lastTimestamp;
121
+ /** Adds line `index` (0-based). */
122
+ add(line, index) {
76
123
  const stamp = TIMESTAMP.exec(line)?.[0];
77
124
  if (stamp) {
78
- firstTimestamp ??= stamp;
79
- lastTimestamp = stamp;
125
+ this.firstTimestamp ??= stamp;
126
+ this.lastTimestamp = stamp;
80
127
  }
81
128
  const raw = LEVEL.exec(line)?.[1];
82
129
  if (!raw)
83
- continue;
130
+ return;
84
131
  const level = LEVEL_NAMES[raw] ?? raw;
85
- levels[level] = (levels[level] ?? 0) + 1;
132
+ this.levels[level] = (this.levels[level] ?? 0) + 1;
86
133
  if (level !== "ERROR" && level !== "FATAL" && level !== "WARN")
87
- continue;
134
+ return;
88
135
  const template = logTemplate(line);
89
- const existing = templates.get(template);
136
+ const existing = this.templates.get(template);
90
137
  if (existing)
91
138
  existing.count++;
92
- else if (templates.size < MAX_TEMPLATES)
93
- templates.set(template, { template, level, count: 1, firstLine: index + 1 });
139
+ else if (this.templates.size < MAX_TEMPLATES)
140
+ this.templates.set(template, { template, level, count: 1, firstLine: index + 1 });
141
+ }
142
+ result() {
143
+ const severity = (issue) => (issue.level === "FATAL" ? 2 : issue.level === "ERROR" ? 1 : 0);
144
+ const topIssues = [...this.templates.values()]
145
+ .sort((left, right) => severity(right) - severity(left) || right.count - left.count)
146
+ .slice(0, 15);
147
+ return {
148
+ levels: this.levels,
149
+ ...(this.firstTimestamp ? { firstTimestamp: this.firstTimestamp } : {}),
150
+ ...(this.lastTimestamp ? { lastTimestamp: this.lastTimestamp } : {}),
151
+ topIssues,
152
+ };
94
153
  }
95
- const severity = (issue) => (issue.level === "FATAL" ? 2 : issue.level === "ERROR" ? 1 : 0);
96
- const topIssues = [...templates.values()]
97
- .sort((left, right) => severity(right) - severity(left) || right.count - left.count)
98
- .slice(0, 15);
99
- return {
100
- levels,
101
- ...(firstTimestamp ? { firstTimestamp } : {}),
102
- ...(lastTimestamp ? { lastTimestamp } : {}),
103
- topIssues,
104
- };
105
154
  }
106
155
  //# sourceMappingURL=analyze.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"analyze.js","sourceRoot":"","sources":["../src/analyze.ts"],"names":[],"mappings":"AAEA,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,MAAM,aAAa,GAAG,MAAM,CAAC;AAC7B,MAAM,SAAS,GAAG,6EAA6E,CAAC;AAChG,MAAM,oBAAoB,GAAG,qHAAqH,CAAC;AACnJ,MAAM,KAAK,GAAG,8DAA8D,CAAC;AAC7E,MAAM,WAAW,GAA2B,E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