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/src/sse.ts CHANGED
@@ -1,34 +1,159 @@
1
- /** Parses a `text/event-stream` body into JSON objects, one per `data:` event. */
2
- export async function* parseSseJson<T>(stream: ReadableStream<Uint8Array>): AsyncGenerator<T> {
3
- const reader = stream.getReader();
1
+ import { bodyPieces } from "./http.js";
2
+
3
+ /** What a stream reader can be told of as the stream goes: see `parseSseJson`. */
4
+ export type SseHooks = {
5
+ /** Bytes arrived: an event, part of one, or a keep-alive comment. */
6
+ onData?: () => void;
7
+ /** The stream said it is done (`data: [DONE]`), as OpenAI-compatible servers do at the end. */
8
+ onDone?: () => void;
9
+ /** When it aborts, the next piece is not waited for: the stream ends with its reason. */
10
+ signal?: AbortSignal | undefined;
11
+ /**
12
+ * The most characters one event may hold: what its data lines hold after `data:` and the spaces
13
+ * after it, and the line feeds that join them. A line of another field (a comment, `event:`)
14
+ * counts in full with the event, as it is held until its end. A longer event ends the stream with
15
+ * an error named `SseEventTooLongError`, rather than fill the memory of the server, however the
16
+ * stream is cut into pieces. Defaults to 64,000,000. `Infinity` sets no limit; a value that is not
17
+ * a positive number counts as not set.
18
+ */
19
+ maxEventLength?: number;
20
+ };
21
+
22
+ /** The most characters one event holds, by default: see `SseHooks.maxEventLength`. */
23
+ const DEFAULT_MAX_EVENT_LENGTH = 64_000_000;
24
+ /** The data lines of an event are joined this many at a time as they come (see `parseSseJson`). */
25
+ const JOIN_LINES = 1_024;
26
+
27
+ /** An event of a stream held more characters than `SseHooks.maxEventLength`, and was not read. */
28
+ export class SseEventTooLongError extends Error {
29
+ constructor(readonly limit: number) {
30
+ super(`An event of the stream held more than ${limit.toLocaleString("en-US")} characters.`);
31
+ this.name = "SseEventTooLongError";
32
+ }
33
+ }
34
+
35
+ /**
36
+ * The message of a reply whose stream had an event too long to read. It is not sent again: the same
37
+ * event would most likely come back. `who` is "Gemini's", "Claude's"…
38
+ */
39
+ export function eventTooLongMessage(who: string, error: SseEventTooLongError): string {
40
+ return `${who} reply could not be read: an event of its stream held more than ${error.limit.toLocaleString("en-US")} characters.`;
41
+ }
42
+
43
+ /**
44
+ * Parses a `text/event-stream` body into JSON objects, one per `data:` event. The body is a web
45
+ * stream (the global `fetch`), or a Node stream (node-fetch and the like). Lines end with LF, CRLF
46
+ * or CR alone, as the format allows. Each piece of the body is read once, however long the event
47
+ * it belongs to: a line that has not ended waits for the next piece.
48
+ */
49
+ export async function* parseSseJson<T>(stream: ReadableStream<Uint8Array> | AsyncIterable<Uint8Array | string>, hooks: SseHooks = {}): AsyncGenerator<T> {
4
50
  const decoder = new TextDecoder();
5
- let buffer = "";
6
- const parse = (block: string): T | undefined => {
7
- const data = block
8
- .split("\n")
9
- .filter((line) => line.startsWith("data:"))
10
- .map((line) => line.slice(5).trimStart())
11
- .join("\n");
12
- return data && data !== "[DONE]" ? JSON.parse(data) as T : undefined;
51
+ const most = typeof hooks.maxEventLength === "number" && hooks.maxEventLength > 0 ? hooks.maxEventLength : DEFAULT_MAX_EVENT_LENGTH;
52
+ /** The data lines of the event being read, since the last ones were joined into `joined`. */
53
+ let data: string[] = [];
54
+ /**
55
+ * Earlier data lines of the event, joined `JOIN_LINES` at a time: an event of millions of empty
56
+ * data lines would otherwise hold a slot for each, far more memory than the characters counted.
57
+ */
58
+ let joined: string[] = [];
59
+ /** The characters of the event those lines make. */
60
+ let held = 0;
61
+ /** The start of a line whose end has not arrived. */
62
+ let partial = "";
63
+ /**
64
+ * Whether that line is a data line, and if so whether its value has begun after `data:` and the
65
+ * spaces after it. Undefined while what has come of it may still be the start of `data:`.
66
+ */
67
+ let partialKind: "field" | "value" | "other" | undefined;
68
+ /** The characters of the event that line holds, as `held` counts them. */
69
+ let partialHeld = 0;
70
+ /** The last piece ended with CR: a LF that starts the next one belongs to that line end. */
71
+ let afterCr = false;
72
+ const lineEnd = /\r\n?|\n/g;
73
+ /** The event of the data lines read so far, which a blank line ends. */
74
+ const event = (): T | undefined => {
75
+ if (data.length > 0) joined.push(data.join("\n"));
76
+ const text = joined.join("\n");
77
+ data = [];
78
+ joined = [];
79
+ held = 0;
80
+ if (text === "[DONE]") hooks.onDone?.();
81
+ return text && text !== "[DONE]" ? JSON.parse(text) as T : undefined;
82
+ };
83
+ const take = (line: string): T | undefined => {
84
+ if (!line) return event();
85
+ if (line.startsWith("data:")) {
86
+ const value = line.slice(5).trimStart();
87
+ // The line feed that joins it to the line before counts too: empty data lines add up.
88
+ held += value.length + (data.length > 0 || joined.length > 0 ? 1 : 0);
89
+ if (held > most) throw new SseEventTooLongError(most);
90
+ data.push(value);
91
+ if (data.length >= JOIN_LINES) {
92
+ joined.push(data.join("\n"));
93
+ data = [];
94
+ }
95
+ } else if (held + line.length > most) {
96
+ // Another line is not kept, but it was held until its end: it counts as it did then.
97
+ throw new SseEventTooLongError(most);
98
+ }
99
+ return undefined;
13
100
  };
14
- try {
15
- while (true) {
16
- const { done, value } = await reader.read();
17
- buffer += decoder.decode(value, { stream: !done });
18
- buffer = buffer.replace(/\r\n/g, "\n");
19
- let boundary = buffer.indexOf("\n\n");
20
- while (boundary >= 0) {
21
- const event = parse(buffer.slice(0, boundary));
22
- buffer = buffer.slice(boundary + 2);
23
- if (event !== undefined) yield event;
24
- boundary = buffer.indexOf("\n\n");
101
+ /**
102
+ * Adds the rest of a piece to the line whose end has not arrived, and counts it as `take` will
103
+ * count the whole line. Only the rest is looked at, not what came of the line before.
104
+ */
105
+ const hold = (rest: string): void => {
106
+ let at = 0;
107
+ if (partialKind === undefined) {
108
+ const start = partial + rest.slice(0, 5 - partial.length);
109
+ at = start.length - partial.length;
110
+ if (start === "data:") {
111
+ partialKind = "field";
112
+ partialHeld = data.length > 0 || joined.length > 0 ? 1 : 0;
113
+ } else if (!"data:".startsWith(start)) {
114
+ partialKind = "other";
115
+ partialHeld = partial.length;
116
+ at = 0;
25
117
  }
26
- if (done) break;
27
118
  }
28
- const last = buffer.trim() ? parse(buffer.trim()) : undefined;
29
- if (last !== undefined) yield last;
30
- } finally {
31
- await reader.cancel().catch(() => undefined);
32
- reader.releaseLock();
119
+ if (partialKind === "field") {
120
+ const value = rest.slice(at).search(/\S/);
121
+ if (value >= 0) partialKind = "value";
122
+ at = value >= 0 ? at + value : rest.length;
123
+ }
124
+ // What counts starts at `at`: at the end of the rest while the line may still be a data line,
125
+ // or while the value of one has not begun.
126
+ partialHeld += rest.length - at;
127
+ partial += rest;
128
+ if (held + partialHeld > most) throw new SseEventTooLongError(most);
129
+ };
130
+ // The events that end in this text, one at a time: a line that does not end in it waits for more.
131
+ function* lines(text: string): Generator<T> {
132
+ if (!text) return;
133
+ let from = afterCr && text.startsWith("\n") ? 1 : 0;
134
+ afterCr = false;
135
+ lineEnd.lastIndex = from;
136
+ for (let found = lineEnd.exec(text); found; found = lineEnd.exec(text)) {
137
+ const line = partial + text.slice(from, found.index);
138
+ partial = "";
139
+ partialKind = undefined;
140
+ partialHeld = 0;
141
+ from = lineEnd.lastIndex;
142
+ if (found[0] === "\r" && from === text.length) afterCr = true;
143
+ const parsed = take(line);
144
+ if (parsed !== undefined) yield parsed;
145
+ lineEnd.lastIndex = from;
146
+ }
147
+ hold(text.slice(from));
148
+ }
149
+ for await (const value of bodyPieces(stream, hooks.signal)) {
150
+ if (value.length > 0) hooks.onData?.();
151
+ yield* lines(decoder.decode(value, { stream: true }));
33
152
  }
153
+ yield* lines(decoder.decode());
154
+ // A last line, and a last event, that the stream ended without a line end or a blank line after.
155
+ if (partial.trim()) take(partial.trim());
156
+ partial = "";
157
+ const last = event();
158
+ if (last !== undefined) yield last;
34
159
  }
package/src/stores.ts CHANGED
@@ -19,8 +19,11 @@ export class MemoryDocumentStore implements DocumentStore {
19
19
  this.now = options.now ?? (() => new Date());
20
20
  }
21
21
 
22
+ // The metadata is copied on the way in and on the way out, as a store that writes it somewhere
23
+ // does: an app that changes the metadata it was handed (deletes its owner before sending it to a
24
+ // browser) must not change the document's owner or expiry.
22
25
  async put(document: StoredDocument): Promise<void> {
23
- this.documents.set(document.meta.id, document);
26
+ this.documents.set(document.meta.id, { meta: structuredClone(document.meta), text: document.text });
24
27
  }
25
28
 
26
29
  async get(id: string): Promise<StoredDocument | undefined> {
@@ -29,7 +32,7 @@ export class MemoryDocumentStore implements DocumentStore {
29
32
  await this.delete(id);
30
33
  return undefined;
31
34
  }
32
- return document;
35
+ return document && { meta: structuredClone(document.meta), text: document.text };
33
36
  }
34
37
 
35
38
  async getMeta(id: string): Promise<DocumentMeta | undefined> {
package/src/text-index.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  * It is built from the bytes of the text, in one pass, at ingest (and written next to the text
7
7
  * with `putIndex`), or the first time an older document without one is used.
8
8
  */
9
+ import type { TimeSlicer } from "./pause.js";
9
10
  import type { DocumentMeta } from "./types.js";
10
11
 
11
12
  /** A passage, for keyword search, is a run of lines of about this many characters... */
@@ -126,18 +127,36 @@ export class TextIndexBuilder {
126
127
  /** The index of a text held as a string, built from its UTF-8 bytes a slice at a time. */
127
128
  export function buildTextIndex(text: string): TextIndex {
128
129
  const builder = new TextIndexBuilder();
129
- const slice = 1 << 20;
130
+ for (let at = 0; at < text.length;) at = pushSlice(builder, text, at);
131
+ return builder.finish();
132
+ }
133
+
134
+ /**
135
+ * `buildTextIndex`, the same index, with pauses for other requests while a large text is indexed.
136
+ * `onProgress` is told the characters indexed so far, after each slice.
137
+ */
138
+ export async function buildTextIndexInSlices(text: string, slicer: TimeSlicer, onProgress?: (done: number, total: number) => void): Promise<TextIndex> {
139
+ const builder = new TextIndexBuilder();
130
140
  for (let at = 0; at < text.length;) {
131
- let end = Math.min(text.length, at + slice);
132
- // Never cut between the two halves of a surrogate pair: each half alone encodes as U+FFFD.
133
- const last = text.charCodeAt(end - 1);
134
- if (end < text.length && last >= 0xd800 && last <= 0xdbff) end++;
135
- builder.push(Buffer.from(text.slice(at, end), "utf8"));
136
- at = end;
141
+ at = pushSlice(builder, text, at);
142
+ onProgress?.(at, text.length);
143
+ await slicer.maybePause();
137
144
  }
138
145
  return builder.finish();
139
146
  }
140
147
 
148
+ /** Pushes the next slice of `text`, from `at`, as UTF-8; returns where the slice ended. */
149
+ function pushSlice(builder: TextIndexBuilder, text: string, at: number): number {
150
+ let end = Math.min(text.length, at + (1 << 18));
151
+ // Never cut between the two halves of a surrogate pair: each half alone encodes as U+FFFD. Only
152
+ // a real pair is kept whole: a first half followed by anything else is one U+FFFD either way.
153
+ const last = text.charCodeAt(end - 1);
154
+ const next = text.charCodeAt(end);
155
+ if (end < text.length && last >= 0xd800 && last <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) end++;
156
+ builder.push(Buffer.from(text.slice(at, end), "utf8"));
157
+ return end;
158
+ }
159
+
141
160
  // The file: a 40-byte header, then the lists of 32-bit numbers (line starts in bytes, line starts
142
161
  // in characters, passage starts, page starts), all little-endian.
143
162
  // 0 "LLFI" 4 version 8 lineCount 12 passages 16 pages 20 unused
@@ -192,7 +211,7 @@ const ascending = (list: Uint32Array, first: number, last: number): boolean => {
192
211
  * another version, or does not describe the text of `meta`: the caller then builds it again from
193
212
  * the text. An index is only a faster way to the same text, so a doubtful one is never used.
194
213
  */
195
- export function parseTextIndex(bytes: Uint8Array, meta?: Pick<DocumentMeta, "lines" | "characters">): TextIndex | undefined {
214
+ export function parseTextIndex(bytes: Uint8Array, meta?: Pick<DocumentMeta, "lines" | "characters"> & { textBytes?: number }): TextIndex | undefined {
196
215
  if (bytes.length < HEADER || MAGIC.some((byte, at) => bytes[at] !== byte)) return undefined;
197
216
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
198
217
  if (view.getUint32(4, true) !== VERSION) return undefined;
@@ -203,7 +222,9 @@ export function parseTextIndex(bytes: Uint8Array, meta?: Pick<DocumentMeta, "lin
203
222
  const characters = view.getFloat64(32, true);
204
223
  if (bytes.length !== HEADER + 4 * (2 * lineCount + passageCount + pageCount)) return undefined;
205
224
  if (!Number.isSafeInteger(textBytes) || !Number.isSafeInteger(characters) || lineCount < 1 || passageCount < 1) return undefined;
206
- if (meta && (meta.lines !== lineCount || meta.characters !== characters)) return undefined;
225
+ // The size of the text too: with a smaller one, the last line would be read cut short; with a
226
+ // larger one, a store would be asked for that many bytes before the mismatch was seen.
227
+ if (meta && (meta.lines !== lineCount || meta.characters !== characters || (typeof meta.textBytes === "number" && meta.textBytes !== textBytes))) return undefined;
207
228
  const lineStarts = readList(bytes, HEADER, lineCount);
208
229
  const characterStarts = readList(bytes, HEADER + 4 * lineCount, lineCount);
209
230
  const passageStarts = readList(bytes, HEADER + 8 * lineCount, passageCount);