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.
Files changed (285) hide show
  1. package/CHANGELOG.md +1719 -466
  2. package/README.md +190 -60
  3. package/dist/analyze.d.ts +8 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +198 -54
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +194 -40
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +63 -7
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1131 -214
  14. package/dist/ask.js.map +1 -1
  15. package/dist/decode.d.ts +19 -0
  16. package/dist/decode.d.ts.map +1 -0
  17. package/dist/decode.js +97 -0
  18. package/dist/decode.js.map +1 -0
  19. package/dist/encoding.d.ts +17 -0
  20. package/dist/encoding.d.ts.map +1 -0
  21. package/dist/encoding.js +852 -0
  22. package/dist/encoding.js.map +1 -0
  23. package/dist/errors.d.ts +59 -0
  24. package/dist/errors.d.ts.map +1 -1
  25. package/dist/errors.js +80 -0
  26. package/dist/errors.js.map +1 -1
  27. package/dist/events.d.ts +339 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +163 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/evidence.d.ts +2 -0
  32. package/dist/evidence.d.ts.map +1 -1
  33. package/dist/evidence.js +9 -2
  34. package/dist/evidence.js.map +1 -1
  35. package/dist/extract.d.ts +26 -7
  36. package/dist/extract.d.ts.map +1 -1
  37. package/dist/extract.js +180 -314
  38. package/dist/extract.js.map +1 -1
  39. package/dist/gemini/adapter.d.ts +17 -8
  40. package/dist/gemini/adapter.d.ts.map +1 -1
  41. package/dist/gemini/adapter.js +117 -66
  42. package/dist/gemini/adapter.js.map +1 -1
  43. package/dist/gemini/chat.d.ts +23 -3
  44. package/dist/gemini/chat.d.ts.map +1 -1
  45. package/dist/gemini/chat.js +6 -2
  46. package/dist/gemini/chat.js.map +1 -1
  47. package/dist/gemini/endpoints.d.ts +5 -1
  48. package/dist/gemini/endpoints.d.ts.map +1 -1
  49. package/dist/gemini/endpoints.js +11 -2
  50. package/dist/gemini/endpoints.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +9 -4
  52. package/dist/gemini/errors.d.ts.map +1 -1
  53. package/dist/gemini/errors.js +32 -0
  54. package/dist/gemini/errors.js.map +1 -1
  55. package/dist/gemini/generate.d.ts +10 -2
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +33 -10
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +3 -3
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +2 -2
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -1
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -1
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/groups.d.ts +54 -0
  68. package/dist/groups.d.ts.map +1 -0
  69. package/dist/groups.js +136 -0
  70. package/dist/groups.js.map +1 -0
  71. package/dist/html.d.ts +11 -0
  72. package/dist/html.d.ts.map +1 -0
  73. package/dist/html.js +1112 -0
  74. package/dist/html.js.map +1 -0
  75. package/dist/http.d.ts +116 -0
  76. package/dist/http.d.ts.map +1 -1
  77. package/dist/http.js +347 -1
  78. package/dist/http.js.map +1 -1
  79. package/dist/index.d.ts +13 -7
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +7 -5
  82. package/dist/index.js.map +1 -1
  83. package/dist/library.d.ts +67 -5
  84. package/dist/library.d.ts.map +1 -1
  85. package/dist/library.js +449 -93
  86. package/dist/library.js.map +1 -1
  87. package/dist/limiter.d.ts +2 -1
  88. package/dist/limiter.d.ts.map +1 -1
  89. package/dist/limiter.js +3 -2
  90. package/dist/limiter.js.map +1 -1
  91. package/dist/map-reduce.d.ts +28 -1
  92. package/dist/map-reduce.d.ts.map +1 -1
  93. package/dist/map-reduce.js +240 -52
  94. package/dist/map-reduce.js.map +1 -1
  95. package/dist/model.d.ts +84 -2
  96. package/dist/model.d.ts.map +1 -1
  97. package/dist/model.js +190 -2
  98. package/dist/model.js.map +1 -1
  99. package/dist/node/handlers.d.ts +20 -4
  100. package/dist/node/handlers.d.ts.map +1 -1
  101. package/dist/node/handlers.js +184 -28
  102. package/dist/node/handlers.js.map +1 -1
  103. package/dist/node/index.d.ts +4 -0
  104. package/dist/node/index.d.ts.map +1 -1
  105. package/dist/node/index.js +2 -0
  106. package/dist/node/index.js.map +1 -1
  107. package/dist/node/ingest-child.d.ts +38 -0
  108. package/dist/node/ingest-child.d.ts.map +1 -0
  109. package/dist/node/ingest-child.js +42 -0
  110. package/dist/node/ingest-child.js.map +1 -0
  111. package/dist/node/isolated.d.ts +88 -0
  112. package/dist/node/isolated.d.ts.map +1 -0
  113. package/dist/node/isolated.js +381 -0
  114. package/dist/node/isolated.js.map +1 -0
  115. package/dist/node/sse.d.ts +59 -0
  116. package/dist/node/sse.d.ts.map +1 -0
  117. package/dist/node/sse.js +174 -0
  118. package/dist/node/sse.js.map +1 -0
  119. package/dist/office.d.ts +105 -0
  120. package/dist/office.d.ts.map +1 -0
  121. package/dist/office.js +1092 -0
  122. package/dist/office.js.map +1 -0
  123. package/dist/openai/adapter.d.ts +29 -5
  124. package/dist/openai/adapter.d.ts.map +1 -1
  125. package/dist/openai/adapter.js +325 -37
  126. package/dist/openai/adapter.js.map +1 -1
  127. package/dist/output-limit.d.ts +14 -2
  128. package/dist/output-limit.d.ts.map +1 -1
  129. package/dist/output-limit.js +39 -10
  130. package/dist/output-limit.js.map +1 -1
  131. package/dist/pause.d.ts +24 -0
  132. package/dist/pause.d.ts.map +1 -0
  133. package/dist/pause.js +38 -0
  134. package/dist/pause.js.map +1 -0
  135. package/dist/pdf-pages.d.ts +32 -2
  136. package/dist/pdf-pages.d.ts.map +1 -1
  137. package/dist/pdf-pages.js +277 -20
  138. package/dist/pdf-pages.js.map +1 -1
  139. package/dist/pdf-pictures.d.ts +30 -3
  140. package/dist/pdf-pictures.d.ts.map +1 -1
  141. package/dist/pdf-pictures.js +50 -8
  142. package/dist/pdf-pictures.js.map +1 -1
  143. package/dist/pdf-work.d.ts +40 -0
  144. package/dist/pdf-work.d.ts.map +1 -0
  145. package/dist/pdf-work.js +734 -0
  146. package/dist/pdf-work.js.map +1 -0
  147. package/dist/peers.d.ts +8 -0
  148. package/dist/peers.d.ts.map +1 -0
  149. package/dist/peers.js +32 -0
  150. package/dist/peers.js.map +1 -0
  151. package/dist/plan.d.ts +22 -4
  152. package/dist/plan.d.ts.map +1 -1
  153. package/dist/plan.js +61 -12
  154. package/dist/plan.js.map +1 -1
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +4 -2
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +23 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +33 -3
  161. package/dist/retry.js.map +1 -1
  162. package/dist/search.d.ts +107 -24
  163. package/dist/search.d.ts.map +1 -1
  164. package/dist/search.js +803 -149
  165. package/dist/search.js.map +1 -1
  166. package/dist/sse.d.ts +35 -2
  167. package/dist/sse.d.ts.map +1 -1
  168. package/dist/sse.js +145 -31
  169. package/dist/sse.js.map +1 -1
  170. package/dist/stores.d.ts.map +1 -1
  171. package/dist/stores.js +5 -2
  172. package/dist/stores.js.map +1 -1
  173. package/dist/text-index.d.ts +9 -1
  174. package/dist/text-index.d.ts.map +1 -1
  175. package/dist/text-index.js +28 -9
  176. package/dist/text-index.js.map +1 -1
  177. package/dist/text.d.ts +87 -3
  178. package/dist/text.d.ts.map +1 -1
  179. package/dist/text.js +526 -24
  180. package/dist/text.js.map +1 -1
  181. package/dist/tools.d.ts +61 -1
  182. package/dist/tools.d.ts.map +1 -1
  183. package/dist/tools.js +461 -46
  184. package/dist/tools.js.map +1 -1
  185. package/dist/types.d.ts +103 -4
  186. package/dist/types.d.ts.map +1 -1
  187. package/dist/word-styles.d.ts +102 -0
  188. package/dist/word-styles.d.ts.map +1 -0
  189. package/dist/word-styles.js +419 -0
  190. package/dist/word-styles.js.map +1 -0
  191. package/dist/xlsx.d.ts +23 -0
  192. package/dist/xlsx.d.ts.map +1 -0
  193. package/dist/xlsx.js +511 -0
  194. package/dist/xlsx.js.map +1 -0
  195. package/dist/xml-stream.d.ts +55 -0
  196. package/dist/xml-stream.d.ts.map +1 -0
  197. package/dist/xml-stream.js +235 -0
  198. package/dist/xml-stream.js.map +1 -0
  199. package/dist/zip-directory.d.ts +43 -0
  200. package/dist/zip-directory.d.ts.map +1 -0
  201. package/dist/zip-directory.js +130 -0
  202. package/dist/zip-directory.js.map +1 -0
  203. package/docs/README.md +288 -0
  204. package/docs/api.md +37 -381
  205. package/docs/configuration.md +28 -558
  206. package/docs/getting-started.md +407 -223
  207. package/docs/guides/anthropic.md +590 -0
  208. package/docs/guides/conversations.md +629 -0
  209. package/docs/guides/costs-and-limits.md +728 -0
  210. package/docs/guides/deployment.md +720 -0
  211. package/docs/guides/errors-and-reliability.md +748 -0
  212. package/docs/guides/explorer-model.md +399 -0
  213. package/docs/guides/openai-compatible.md +602 -0
  214. package/docs/guides/own-adapter-and-loop.md +1169 -0
  215. package/docs/guides/pdfs.md +1024 -0
  216. package/docs/guides/storage.md +731 -0
  217. package/docs/guides/testing.md +1203 -0
  218. package/docs/guides/vertex-and-gemini.md +717 -0
  219. package/docs/guides/web-app.md +1590 -0
  220. package/docs/how-it-works.md +1035 -164
  221. package/docs/measurements.md +881 -0
  222. package/docs/publishing.md +274 -46
  223. package/docs/reference/anthropic.md +427 -0
  224. package/docs/reference/ask.md +910 -0
  225. package/docs/reference/errors-and-retries.md +760 -0
  226. package/docs/reference/events.md +1001 -0
  227. package/docs/reference/gemini.md +827 -0
  228. package/docs/reference/library.md +1598 -0
  229. package/docs/reference/node.md +706 -0
  230. package/docs/reference/openai.md +385 -0
  231. package/docs/reference/tools.md +1031 -0
  232. package/docs/security.md +940 -101
  233. package/docs/troubleshooting.md +1410 -0
  234. package/package.json +7 -3
  235. package/src/analyze.ts +204 -49
  236. package/src/anthropic/adapter.ts +200 -40
  237. package/src/ask.ts +1151 -210
  238. package/src/decode.ts +89 -0
  239. package/src/encoding.ts +850 -0
  240. package/src/errors.ts +125 -0
  241. package/src/events.ts +451 -0
  242. package/src/evidence.ts +11 -2
  243. package/src/extract.ts +191 -308
  244. package/src/gemini/adapter.ts +127 -70
  245. package/src/gemini/chat.ts +28 -4
  246. package/src/gemini/endpoints.ts +12 -2
  247. package/src/gemini/errors.ts +34 -1
  248. package/src/gemini/generate.ts +42 -13
  249. package/src/gemini/index.ts +3 -3
  250. package/src/gemini/sse.ts +1 -1
  251. package/src/groups.ts +162 -0
  252. package/src/html.ts +1071 -0
  253. package/src/http.ts +376 -1
  254. package/src/index.ts +29 -6
  255. package/src/library.ts +498 -93
  256. package/src/limiter.ts +6 -1
  257. package/src/map-reduce.ts +252 -51
  258. package/src/model.ts +244 -4
  259. package/src/node/handlers.ts +196 -31
  260. package/src/node/index.ts +4 -0
  261. package/src/node/ingest-child.ts +61 -0
  262. package/src/node/isolated.ts +464 -0
  263. package/src/node/sse.ts +198 -0
  264. package/src/office.ts +1047 -0
  265. package/src/openai/adapter.ts +319 -38
  266. package/src/output-limit.ts +44 -8
  267. package/src/pause.ts +41 -0
  268. package/src/pdf-pages.ts +270 -20
  269. package/src/pdf-pictures.ts +56 -9
  270. package/src/pdf-work.ts +722 -0
  271. package/src/peers.ts +29 -0
  272. package/src/plan.ts +70 -12
  273. package/src/ranged.ts +4 -2
  274. package/src/retry.ts +49 -5
  275. package/src/search.ts +800 -155
  276. package/src/sse.ts +153 -28
  277. package/src/stores.ts +5 -2
  278. package/src/text-index.ts +30 -9
  279. package/src/text.ts +524 -23
  280. package/src/tools.ts +445 -46
  281. package/src/types.ts +108 -5
  282. package/src/word-styles.ts +420 -0
  283. package/src/xlsx.ts +478 -0
  284. package/src/xml-stream.ts +224 -0
  285. package/src/zip-directory.ts +136 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "llm-large-files",
3
- "version": "0.5.0",
3
+ "version": "0.8.0",
4
4
  "description": "Let an LLM answer questions about books, logs, and other files larger than its request limit or context window: upload, plan, search and read tools, map-reduce, a look at the pages of a PDF, and one tool loop for any model. Adapters for Gemini and Vertex AI, OpenAI-compatible endpoints, and Claude.",
5
5
  "keywords": [
6
6
  "llm",
@@ -59,6 +59,7 @@
59
59
  "types": "./dist/node/index.d.ts",
60
60
  "default": "./dist/node/index.js"
61
61
  },
62
+ "./node/ingest-child.js": "./dist/node/ingest-child.js",
62
63
  "./package.json": "./package.json"
63
64
  },
64
65
  "typesVersions": {
@@ -94,7 +95,7 @@
94
95
  "peerDependencies": {
95
96
  "@cantoo/pdf-lib": "^2.11.1",
96
97
  "jszip": "^3.10.0",
97
- "unpdf": "^1.4.0"
98
+ "unpdf": "^1.4.0 || ^2.0.0"
98
99
  },
99
100
  "peerDependenciesMeta": {
100
101
  "@cantoo/pdf-lib": {
@@ -113,6 +114,9 @@
113
114
  "jszip": "3.10.1",
114
115
  "typescript": "5.9.3",
115
116
  "unpdf": "1.4.0",
116
- "vitest": "3.2.7"
117
+ "vitest": "4.1.12"
118
+ },
119
+ "overrides": {
120
+ "vite": "7.3.7"
117
121
  }
118
122
  }
package/src/analyze.ts CHANGED
@@ -1,55 +1,190 @@
1
+ import type { TimeSlicer } from "./pause.js";
2
+ import { sliceWhole } from "./text.js";
1
3
  import type { DocumentFormat, LogIssue, LogProfile, OutlineEntry } from "./types.js";
2
4
 
3
5
  const MAX_OUTLINE_ENTRIES = 400;
4
6
  const MAX_TEMPLATES = 50_000;
5
- const TIMESTAMP = /\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:[.,]\d+)?(?:Z|[+-]\d{2}:?\d{2})?/;
6
- const LINE_START_TIMESTAMP = /^\[?(?:\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}|\d{2}\/\d{2}\/\d{4}|\w{3} {1,2}\d{1,2} \d{2}:\d{2}:\d{2}|\d{2}:\d{2}:\d{2})/;
7
+ /**
8
+ * Timestamps of logs: ISO 8601 (2026-11-10T14:03:17.120Z), nginx's error log (2026/11/10
9
+ * 14:03:17), the access logs of Apache and nginx (10/Nov/2026:14:03:17 +0000), and syslog (Nov 10
10
+ * 14:03:17).
11
+ */
12
+ const TIMESTAMP = /\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:[.,]\d+)?(?:Z|[+-]\d{2}:?\d{2})?|\b\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}:\d{2}|\b\d{2}\/[A-Z][a-z]{2}\/\d{4}:\d{2}:\d{2}:\d{2}(?: [+-]\d{4})?|\b[A-Z][a-z]{2} {1,2}\d{1,2} \d{2}:\d{2}:\d{2}/;
13
+ const LINE_START_TIMESTAMP = /^\[?(?:\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}|\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}|\d{2}\/\d{2}\/\d{4}|\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}|\w{3} {1,2}\d{1,2} \d{2}:\d{2}:\d{2}|\d{2}:\d{2}:\d{2})/;
14
+ /** Other shapes of log lines: an access log, a JSON log, klog, logfmt. */
15
+ const LOG_LINE = /^(?:\d{1,3}(?:\.\d{1,3}){3} \S+ \S+ \[\d{2}\/\w{3}\/\d{4}:|\{.*"(?:level|severity|time|timestamp|ts|@timestamp)"\s*:|[IWEF]\d{4} \d{2}:\d{2}:\d{2}|(?:time|ts|level|lvl)=)/;
16
+ /** A level word in upper case, anywhere on the line. */
7
17
  const LEVEL = /\b(FATAL|CRITICAL|ERROR|ERR|WARN|WARNING|INFO|DEBUG|TRACE)\b/;
8
- const LEVEL_NAMES: Record<string, string> = { ERR: "ERROR", WARNING: "WARN", CRITICAL: "FATAL" };
18
+ /**
19
+ * A level in lower or mixed case, where logs put one: in brackets as nginx and Apache do
20
+ * ("[error]"), after `level=` as logfmt, zap and logrus do, or in a JSON field ("level":"warn").
21
+ */
22
+ const MARKED_LEVEL = /(?:\[|\b(?:level|lvl|severity)=\s*"?|"(?:level|severity)"\s*:\s*")(fatal|critical|crit|emerg|alert|error|err|warning|warn|notice|info|debug|trace)\b/i;
23
+ /** pino and bunyan write the level as a number. */
24
+ const NUMBER_LEVEL = /"level"\s*:\s*(10|20|30|40|50|60)\b/;
25
+ const NUMBER_LEVELS: Record<string, string> = { 10: "TRACE", 20: "DEBUG", 30: "INFO", 40: "WARN", 50: "ERROR", 60: "FATAL" };
26
+ /** klog and glog start a line with the level's letter, then the month and day. */
27
+ const LETTER_LEVEL = /^([IWEF])\d{4} \d{2}:\d{2}:\d{2}/;
28
+ const LETTER_LEVELS: Record<string, string> = { I: "INFO", W: "WARN", E: "ERROR", F: "FATAL" };
29
+ const LEVEL_NAMES: Record<string, string> = { ERR: "ERROR", WARNING: "WARN", CRITICAL: "FATAL", CRIT: "FATAL", EMERG: "FATAL", ALERT: "FATAL", NOTICE: "INFO" };
9
30
 
10
- /** Treats text as a log when most early lines start with a timestamp or a level. */
31
+ /** The level of a log line, in upper case ("ERROR", "WARN"), or undefined. */
32
+ export function levelOf(line: string): string | undefined {
33
+ const raw = LEVEL.exec(line)?.[1]
34
+ ?? MARKED_LEVEL.exec(line)?.[1]?.toUpperCase()
35
+ ?? NUMBER_LEVELS[NUMBER_LEVEL.exec(line)?.[1] ?? ""]
36
+ ?? LETTER_LEVELS[LETTER_LEVEL.exec(line)?.[1] ?? ""];
37
+ return raw === undefined ? undefined : LEVEL_NAMES[raw] ?? raw;
38
+ }
39
+
40
+ /** Treats text as a log when most early lines start with a timestamp or a level, or have the shape of a log line. */
11
41
  export function looksLikeLog(lines: string[]): boolean {
12
- const sample = lines.filter((line) => line.trim()).slice(0, 200);
42
+ const sample: string[] = [];
43
+ for (let index = 0; index < lines.length && sample.length < 200; index++) if (lines[index]!.trim()) sample.push(lines[index]!);
13
44
  if (sample.length < 5) return false;
14
- const hits = sample.filter((line) => LINE_START_TIMESTAMP.test(line.trim()) || /^\[?(FATAL|ERROR|WARN|WARNING|INFO|DEBUG|TRACE)\b/.test(line.trim())).length;
45
+ const hits = sample.filter((line) => {
46
+ const trimmed = line.trim();
47
+ return LINE_START_TIMESTAMP.test(trimmed) || LOG_LINE.test(trimmed) || /^\[?(FATAL|ERROR|WARN|WARNING|INFO|DEBUG|TRACE)\b/i.test(trimmed);
48
+ }).length;
15
49
  return hits / sample.length >= 0.4;
16
50
  }
17
51
 
52
+ /** A line that opens or closes a fenced code block of Markdown: ``` or ~~~. */
53
+ const FENCE = /^\s{0,3}(`{3,}|~{3,})/;
54
+
55
+ /**
56
+ * Follows fenced code blocks line by line: a "# comment" in a block of shell or Python is not a
57
+ * heading. A fence closes with the same character, at least as long.
58
+ */
59
+ class Fences {
60
+ private open: string | undefined;
61
+
62
+ /** Whether line `line` is inside a block, its fences included. */
63
+ inside(line: string): boolean {
64
+ const fence = FENCE.exec(line)?.[1];
65
+ if (this.open !== undefined) {
66
+ if (fence && fence[0] === this.open[0] && fence.length >= this.open.length && line.trim() === fence) this.open = undefined;
67
+ return true;
68
+ }
69
+ if (fence) {
70
+ this.open = fence;
71
+ return true;
72
+ }
73
+ return false;
74
+ }
75
+ }
76
+
18
77
  /** Headings with line numbers: Markdown, slide/page markers, and common book and report patterns. */
19
78
  export function buildOutline(lines: string[], format: DocumentFormat): OutlineEntry[] {
20
79
  if (format === "log" || format === "json" || format === "csv") return [];
21
80
  const entries: OutlineEntry[] = [];
81
+ const fences = new Fences();
82
+ const hashes = hashHeadings(lines, format);
22
83
  for (let index = 0; index < lines.length; index++) {
23
- const line = (lines[index] ?? "").trim();
24
- if (!line || line.length > 120) continue;
25
- const previousBlank = index === 0 || !(lines[index - 1] ?? "").trim();
26
- let entry: OutlineEntry | undefined;
27
- const markdown = /^(#{1,6})\s+(.+)$/.exec(line);
28
- if (markdown) 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
- } else if (/^\d+(\.\d+){0,2}\s+\S/.test(line) && previousBlank && line.length <= 80 && !/[.:;,]$/.test(line)) {
33
- entry = { line: index + 1, level: (line.split(" ")[0]!.match(/\./g)?.length ?? 0) + 2, title: line };
34
- } else if (previousBlank && line.length >= 4 && line.length <= 60 && /\p{Lu}/u.test(line) && line === line.toUpperCase() && /\p{L}{3}/u.test(line)) {
35
- entry = { line: index + 1, level: 2, title: line };
36
- }
84
+ if (fences.inside(lines[index] ?? "")) continue;
85
+ const entry = outlineEntry(lines, index, hashes);
37
86
  if (entry) entries.push(entry);
38
87
  }
88
+ return pickOutline(entries);
89
+ }
90
+
91
+ /** `buildOutline`, the same result, with pauses for other requests while a large file is read. */
92
+ export async function buildOutlineInSlices(lines: string[], format: DocumentFormat, slicer: TimeSlicer): Promise<OutlineEntry[]> {
93
+ if (format === "log" || format === "json" || format === "csv") return [];
94
+ const entries: OutlineEntry[] = [];
95
+ const fences = new Fences();
96
+ const hashes = hashHeadings(lines, format);
97
+ for (let index = 0; index < lines.length; index++) {
98
+ if ((index & 4095) === 4095) await slicer.maybePause();
99
+ if (fences.inside(lines[index] ?? "")) continue;
100
+ const entry = outlineEntry(lines, index, hashes);
101
+ if (entry) entries.push(entry);
102
+ }
103
+ return pickOutline(entries);
104
+ }
105
+
106
+ /** Whether a line is a "# " line: a Markdown heading, or a comment of a script or a configuration file. */
107
+ const hashLine = (line: string | undefined) => /^\s*#{1,6}\s/.test(line ?? "");
108
+
109
+ /**
110
+ * A line only code has: a shebang, an include, an import, a definition. One is enough. No two
111
+ * repeats in a row can match the same characters: `function\s*\w*\s*\(` split a run of spaces
112
+ * after "function" between its two `\s*` in as many ways as it is long, and a line of "function",
113
+ * 2,000 spaces and "x" took 20 ms; 300 of them held the server 8 seconds.
114
+ */
115
+ const CODE_LINE = /^(?:#!\/|#include\b|import\s+[\w{*"']|from\s+[\w.]+\s+import\b|def\s+\w+\s*\(|class\s+\w+[\s:({]|function\s*(?:\w+\s*)?\(|package\s+[\w.]+;?\s*$|using\s+[\w.]+;\s*$)/;
116
+ /** A line common in code and configuration files, and rarer in prose: three are needed. */
117
+ const CODE_LIKE_LINE = /^(?:(?:const|let|var|export|public|private|return)\s|(?:if|for|while)\s*\(|echo\s|set\s+-\w|[A-Za-z_][\w.-]*\s*=\s*\S|[}\])];?$)/;
118
+
119
+ /**
120
+ * Whether a plain text file is a script, source code or a configuration file, where "# " starts
121
+ * a comment, not a heading: one of its first lines only code has, or three that code often has.
122
+ */
123
+ function looksLikeCode(lines: string[]): boolean {
124
+ let likely = 0;
125
+ for (let index = 0; index < lines.length && index < 300; index++) {
126
+ // Trimmed first, and the end looked at apart: a regex over the leading spaces backtracked by their square.
127
+ const line = (lines[index] ?? "").trim();
128
+ if (CODE_LINE.test(line)) return true;
129
+ if ((CODE_LIKE_LINE.test(line) || line.endsWith("{") || line.endsWith(";")) && ++likely >= 3) return true;
130
+ }
131
+ return false;
132
+ }
133
+
134
+ /**
135
+ * Which "# " lines are headings: all of them in Markdown and the other formats; in a plain text
136
+ * file, none when it reads as code ("strict" is false then), and otherwise only one after a blank
137
+ * line that is not followed by another "# " line, as comments come in blocks.
138
+ */
139
+ type HashHeadings = "all" | "strict" | "none";
140
+
141
+ function hashHeadings(lines: string[], format: DocumentFormat): HashHeadings {
142
+ if (format !== "text") return "all";
143
+ return looksLikeCode(lines) ? "none" : "strict";
144
+ }
145
+
146
+ /** The heading on line `index` (0-based), if it is one. */
147
+ function outlineEntry(lines: string[], index: number, hashes: HashHeadings = "all"): OutlineEntry | undefined {
148
+ const line = (lines[index] ?? "").trim();
149
+ if (!line || line.length > 120) return undefined;
150
+ const previousBlank = index === 0 || !(lines[index - 1] ?? "").trim();
151
+ const markdown = /^(#{1,6})\s+(.+)$/.exec(line);
152
+ if (markdown) {
153
+ if (hashes === "none" || (hashes === "strict" && (!previousBlank || hashLine(lines[index + 1])))) return undefined;
154
+ return { line: index + 1, level: markdown[1]!.length, title: markdown[2]!.trim() };
155
+ }
156
+ // A lookahead, not \b: JavaScript's \b does not treat Hebrew letters as word characters.
157
+ if (/^(chapter|part|book|section|appendix|פרק|חלק|נספח)(?=[\s:.\d]|$)/iu.test(line) && previousBlank) {
158
+ return { line: index + 1, level: /^(part|book|חלק)(?=[\s:.\d]|$)/iu.test(line) ? 1 : 2, title: line };
159
+ }
160
+ if (/^\d+(\.\d+){0,2}\s+\S/.test(line) && previousBlank && line.length <= 80 && !/[.:;,]$/.test(line)) {
161
+ return { line: index + 1, level: (line.split(" ")[0]!.match(/\./g)?.length ?? 0) + 2, title: line };
162
+ }
163
+ if (previousBlank && line.length >= 4 && line.length <= 60 && /\p{Lu}/u.test(line) && line === line.toUpperCase() && /\p{L}{3}/u.test(line)) {
164
+ return { line: index + 1, level: 2, title: line };
165
+ }
166
+ return undefined;
167
+ }
168
+
169
+ /** The outline kept from all the headings found: at most 400 of them. */
170
+ function pickOutline(entries: OutlineEntry[]): OutlineEntry[] {
39
171
  if (entries.length <= MAX_OUTLINE_ENTRIES) return entries;
40
- // Keep the top levels first, then sample evenly so the outline still spans the document.
172
+ // Keep the top-level headings when there are at least 20 of them. A pool that fits is kept whole;
173
+ // a larger one is sampled evenly, so the outline still spans the document.
41
174
  // A loop, not Math.min(...levels): spreading a few hundred thousand values overflows the stack.
42
175
  let minLevel = Number.POSITIVE_INFINITY;
43
176
  for (const entry of entries) if (entry.level < minLevel) minLevel = entry.level;
44
177
  const top = entries.filter((entry) => entry.level === minLevel);
45
178
  const pool = top.length >= 20 ? top : entries;
179
+ if (pool.length <= MAX_OUTLINE_ENTRIES) return pool;
180
+ // The step is above 1 here, so each sampled index is greater than the one before it.
46
181
  const step = pool.length / MAX_OUTLINE_ENTRIES;
47
- return Array.from({ length: Math.min(pool.length, MAX_OUTLINE_ENTRIES) }, (_, index) => pool[Math.floor(index * step)]!);
182
+ return Array.from({ length: MAX_OUTLINE_ENTRIES }, (_, index) => pool[Math.floor(index * step)]!);
48
183
  }
49
184
 
50
185
  /** Replaces the variable parts of a log message so repeated failures group together. */
51
186
  export function logTemplate(line: string): string {
52
- return line
187
+ const template = line
53
188
  .replace(TIMESTAMP, "")
54
189
  .replace(/^\W*\d{2}:\d{2}:\d{2}(?:[.,]\d+)?/, "")
55
190
  .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>")
@@ -58,40 +193,60 @@ export function logTemplate(line: string): string {
58
193
  .replace(/"[^"]{0,200}"|'[^']{0,200}'/g, "<s>")
59
194
  .replace(/\d+(?:\.\d+)?/g, "<n>")
60
195
  .replace(/\s+/g, " ")
61
- .trim()
62
- .slice(0, 180);
196
+ .trim();
197
+ return sliceWhole(template, 180);
63
198
  }
64
199
 
65
200
  export function buildLogProfile(lines: string[]): LogProfile {
66
- const levels: Record<string, number> = {};
67
- const templates = new Map<string, LogIssue>();
68
- let firstTimestamp: string | undefined;
69
- let lastTimestamp: string | undefined;
201
+ const profile = new LogProfiler();
202
+ for (let index = 0; index < lines.length; index++) profile.add(lines[index] ?? "", index);
203
+ return profile.result();
204
+ }
205
+
206
+ /** `buildLogProfile`, the same result, with pauses for other requests while a large log is read. */
207
+ export async function buildLogProfileInSlices(lines: string[], slicer: TimeSlicer): Promise<LogProfile> {
208
+ const profile = new LogProfiler();
70
209
  for (let index = 0; index < lines.length; index++) {
71
- const line = lines[index] ?? "";
210
+ profile.add(lines[index] ?? "", index);
211
+ if ((index & 4095) === 4095) await slicer.maybePause();
212
+ }
213
+ return profile.result();
214
+ }
215
+
216
+ /** Builds a log profile one line at a time. */
217
+ class LogProfiler {
218
+ private readonly levels: Record<string, number> = {};
219
+ private readonly templates = new Map<string, LogIssue>();
220
+ private firstTimestamp: string | undefined;
221
+ private lastTimestamp: string | undefined;
222
+
223
+ /** Adds line `index` (0-based). */
224
+ add(line: string, index: number): void {
72
225
  const stamp = TIMESTAMP.exec(line)?.[0];
73
226
  if (stamp) {
74
- firstTimestamp ??= stamp;
75
- lastTimestamp = stamp;
227
+ this.firstTimestamp ??= stamp;
228
+ this.lastTimestamp = stamp;
76
229
  }
77
- const raw = LEVEL.exec(line)?.[1];
78
- if (!raw) continue;
79
- const level = LEVEL_NAMES[raw] ?? raw;
80
- levels[level] = (levels[level] ?? 0) + 1;
81
- if (level !== "ERROR" && level !== "FATAL" && level !== "WARN") continue;
230
+ const level = levelOf(line);
231
+ if (!level) return;
232
+ this.levels[level] = (this.levels[level] ?? 0) + 1;
233
+ if (level !== "ERROR" && level !== "FATAL" && level !== "WARN") return;
82
234
  const template = logTemplate(line);
83
- const existing = templates.get(template);
235
+ const existing = this.templates.get(template);
84
236
  if (existing) existing.count++;
85
- else if (templates.size < MAX_TEMPLATES) templates.set(template, { template, level, count: 1, firstLine: index + 1 });
237
+ else if (this.templates.size < MAX_TEMPLATES) this.templates.set(template, { template, level, count: 1, firstLine: index + 1 });
238
+ }
239
+
240
+ result(): LogProfile {
241
+ const severity = (issue: LogIssue) => (issue.level === "FATAL" ? 2 : issue.level === "ERROR" ? 1 : 0);
242
+ const topIssues = [...this.templates.values()]
243
+ .sort((left, right) => severity(right) - severity(left) || right.count - left.count)
244
+ .slice(0, 15);
245
+ return {
246
+ levels: this.levels,
247
+ ...(this.firstTimestamp ? { firstTimestamp: this.firstTimestamp } : {}),
248
+ ...(this.lastTimestamp ? { lastTimestamp: this.lastTimestamp } : {}),
249
+ topIssues,
250
+ };
86
251
  }
87
- const severity = (issue: LogIssue) => (issue.level === "FATAL" ? 2 : issue.level === "ERROR" ? 1 : 0);
88
- const topIssues = [...templates.values()]
89
- .sort((left, right) => severity(right) - severity(left) || right.count - left.count)
90
- .slice(0, 15);
91
- return {
92
- levels,
93
- ...(firstTimestamp ? { firstTimestamp } : {}),
94
- ...(lastTimestamp ? { lastTimestamp } : {}),
95
- topIssues,
96
- };
97
252
  }