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/dist/text.js CHANGED
@@ -6,47 +6,442 @@ export const MAX_LINE_CHARACTERS = 2_000;
6
6
  * ("ESC 7", "ESC c"). Coloured logs are full of them. An "ESC ]" whose end is not on its line is
7
7
  * not a sequence: only those two characters go. Otherwise one stray "ESC ]", a cut-off window title
8
8
  * or two bytes in a logged user agent, would take every line after it.
9
+ * U+009B, the one-character form of "ESC [", starts a sequence only with a parameter ("\x9b31m"),
10
+ * and not right after U+0080-U+00FF: there it is the end of a letter of UTF-8 read as Latin-1
11
+ * ("ś" is C5 9B, so "Coś? Tak" holds "\xc5\x9b? Tak"), and what follows it is text. `INVISIBLE`
12
+ * removes the U+009B alone then.
9
13
  */
10
14
  // eslint-disable-next-line no-control-regex
11
- const ANSI_ESCAPE = /\x1b(?:\[[0-?]*[ -\/]*[@-~]|\][^\x07\x1b\n]*(?:\x07|\x1b\\)|[ -\/]+[0-~]|[0-~])/g;
15
+ const ANSI_ESCAPE = /\x1b(?:\[[0-?]*[ -\/]*[@-~]|\][^\x07\x1b\n]*(?:\x07|\x1b\\)|[ -\/]+[0-~]|[0-~])|(?<![\x80-\xff])\x9b[0-?]+[ -\/]*[@-~]/g;
12
16
  /**
13
- * Strips a BOM, unifies line endings, and removes terminal escape sequences and control characters
14
- * other than tab and newline.
17
+ * Characters that show nothing, that no script needs, and that can hide text from a person who
18
+ * reads the file while a model reads it:
19
+ * - control characters other than tab and line breaks: C0 (U+0000-U+001F, U+007F) and C1
20
+ * (U+0080-U+009F);
21
+ * - Unicode tag characters (U+E0000-U+E007F). Each spells out one ASCII character, which a model
22
+ * reads and a person does not see. The three flags written with them (England, Scotland,
23
+ * Wales) are kept;
24
+ * - the text-direction controls that change the order a person sees: embeddings and overrides
25
+ * (U+202A-U+202E) and isolates (U+2066-U+2069). The marks that right-to-left text needs
26
+ * (U+200E, U+200F, U+061C) are kept;
27
+ * - the zero-width space (U+200B), the word joiner and invisible operators (U+2060-U+2064), the
28
+ * deprecated format characters (U+206A-U+206F), a byte order mark inside the text (U+FEFF), and
29
+ * the soft hyphen (U+00AD), but not one before a line break: there it shows, as a hyphen.
30
+ * Zero-width joiners and non-joiners (U+200C, U+200D) are kept: emoji and some scripts need them.
31
+ * Tab, "\n" and "\r" are not among them, so removing them moves no line. U+0085 goes with the other
32
+ * C1 characters, except where it ends lines (see `NEXT_LINE`).
33
+ */
34
+ // eslint-disable-next-line no-control-regex
35
+ const INVISIBLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\u200B\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF]+|\xAD(?!\n)|\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|(?:\uDB40[\uDC00-\uDC7F])+/g;
36
+ /** A flag written with tag characters starts with U+1F3F4, whose first half is this. */
37
+ const FLAG_START = 0xd83c;
38
+ /**
39
+ * U+0085 (next line) ends each record of a mainframe file converted to UTF-8, which has no other
40
+ * line break: in such a text it becomes a line break (see `breaksAtNextLine`). Not one right after
41
+ * U+0080-U+00FF: there it is the last byte of a UTF-8 letter read as Latin-1 ("ą" is C4 85), and a
42
+ * line break would split the word. `INVISIBLE` removes that one, and those of other texts.
43
+ */
44
+ const NEXT_LINE = /(?<![\x80-\xFF])\x85/g;
45
+ /** A run of U+0085, to go past it in one step. */
46
+ const NEXT_LINE_RUN = /\x85+/y;
47
+ /** `text` without the characters of `INVISIBLE`. */
48
+ export function removeInvisible(text) {
49
+ return text.replace(INVISIBLE, (found) => (found.charCodeAt(0) === FLAG_START ? found : ""));
50
+ }
51
+ /** A word for a count: "line" for 1, "lines" for any other. */
52
+ export const plural = (count, word) => (count === 1 ? word : `${word}s`);
53
+ /**
54
+ * Whether the U+0085 of `text` end lines: only when it has no other line break, one at its very end
55
+ * aside. A mainframe file converted to UTF-8 has none. In a text that has them, a U+0085 is more
56
+ * often in a JSON string or a CSV field, or a windows-1252 "…" read as Latin-1, and a line break
57
+ * there would split a record and move every line after it.
58
+ */
59
+ export function breaksAtNextLine(text) {
60
+ let end = text.length;
61
+ if (text.charCodeAt(end - 1) === 10)
62
+ end--;
63
+ if (text.charCodeAt(end - 1) === 13)
64
+ end--;
65
+ const lineFeed = text.indexOf("\n");
66
+ if (lineFeed !== -1 && lineFeed < end)
67
+ return false;
68
+ const carriageReturn = text.indexOf("\r");
69
+ return carriageReturn === -1 || carriageReturn >= end;
70
+ }
71
+ /** `removeInvisible`, after each U+0085 that ends a line is made a line break, when `nextLines`; then `composed`. */
72
+ function cleanLines(text, nextLines) {
73
+ return composed(removeInvisible(nextLines && text.includes("\x85") ? text.replace(NEXT_LINE, "\n") : text));
74
+ }
75
+ /** A character that Unicode normalization (NFC) may change: nothing below U+0300 does. */
76
+ const MAY_COMPOSE = /[^\x00-\u02ff]/;
77
+ /**
78
+ * `text` in Unicode's composed form (NFC): "e" followed by a combining acute accent becomes one
79
+ * "é", as a model writes it in a query. Text exported from macOS, from some PDF and Word files, and
80
+ * Vietnamese, often comes decomposed, and a search for the composed word found nothing in it. Text
81
+ * with no character from U+0300 on is returned as it is, without the cost of normalizing it.
82
+ * Hebrew and Arabic points are not composed by NFC: they stay as they are.
83
+ */
84
+ export function composed(text) {
85
+ const first = text.search(MAY_COMPOSE);
86
+ if (first === -1)
87
+ return text;
88
+ return streamSafe(text, first).text.normalize("NFC");
89
+ }
90
+ /**
91
+ * More marks in a row than any script writes on one letter. NFC orders the marks of a run by
92
+ * their class, in time that grows with the square of the run: 600 KB of marks of two classes in
93
+ * turn held the server 80 seconds. Unicode's stream-safe form (UAX #15) bounds the run instead.
94
+ */
95
+ const MAX_MARKS = 30;
96
+ /** A mark (\p{M}): a character that NFC may order with the marks next to it. */
97
+ const MARK = /\p{M}/u;
98
+ const MARK_RUNS = /\p{M}+/gu;
99
+ /** The combining grapheme joiner: a mark that is a starter, so NFC orders no marks across it. */
100
+ const GRAPHEME_JOINER = 0x034f;
101
+ /** Code points below this are looked up in `marks`; the few marks above it, with `MARK`. */
102
+ const TABLE_END = 0x20000;
103
+ /** Which code points below `TABLE_END` are marks, filled in a block of 4,096 the first time a character of the block is looked up. */
104
+ const marks = new Uint8Array(TABLE_END);
105
+ const markBlocks = new Uint8Array(TABLE_END >> 12);
106
+ /** Whether code point `point` is a mark. A look at a table: far quicker than a regex test. */
107
+ function isMark(point) {
108
+ if (point >= TABLE_END)
109
+ return MARK.test(String.fromCodePoint(point));
110
+ const block = point >> 12;
111
+ if (markBlocks[block] === 0) {
112
+ markBlocks[block] = 1;
113
+ const points = [];
114
+ for (let at = block << 12; at < (block + 1) << 12; at++)
115
+ if (at < 0xd800 || at > 0xdfff)
116
+ points.push(at);
117
+ for (const [run] of String.fromCodePoint(...points).matchAll(MARK_RUNS))
118
+ for (const character of run)
119
+ marks[character.codePointAt(0)] = 1;
120
+ }
121
+ return marks[point] === 1;
122
+ }
123
+ /**
124
+ * `text` in the stream-safe form: a combining grapheme joiner (U+034F, which shows nothing and is
125
+ * a starter) after every 30 marks of a run, so no run NFC orders is longer than that. `first` is
126
+ * where the first character from U+0300 on is: nothing before it is a mark. `carried`: the marks
127
+ * that end the text before this one, for a text worked on in pieces; `run` is those that end this
128
+ * one. One pass, a look at a table for each character: a regex for long runs tried a match at each
129
+ * mark of a run, and took 1.3 microseconds a mark on runs of 30, more than NFC itself; on a run of
130
+ * millions of marks its greedy repeat ran out of stack, and the upload was refused with the
131
+ * engine's "Maximum call stack size exceeded".
132
+ */
133
+ function streamSafe(text, first, carried = 0) {
134
+ let pieces;
135
+ let copied = 0;
136
+ let run = first === 0 ? carried : 0;
137
+ const length = text.length;
138
+ for (let at = first; at < length; at++) {
139
+ const code = text.charCodeAt(at);
140
+ if (code < 0x0300) {
141
+ run = 0;
142
+ continue;
143
+ }
144
+ // A pair of surrogates is one character, outside the basic plane.
145
+ const low = code >= 0xd800 && code <= 0xdbff ? text.charCodeAt(at + 1) : 0;
146
+ const pair = low >= 0xdc00 && low <= 0xdfff;
147
+ if (pair ? !isMark(((code - 0xd800) << 10) + (low - 0xdc00) + 0x10000) : code === GRAPHEME_JOINER || !isMark(code)) {
148
+ run = 0;
149
+ if (pair)
150
+ at++;
151
+ continue;
152
+ }
153
+ // These four become two marks each under NFC (UAX #15 counts the marks of the decomposition):
154
+ // counted as one, a run of 30 grew past 30 once composed, and composing it again changed it.
155
+ const weight = code === 0x0344 || code === 0x0f73 || code === 0x0f75 || code === 0x0f81 ? 2 : 1;
156
+ if (run + weight > MAX_MARKS) {
157
+ (pieces ??= []).push(text.slice(copied, at), "\u034f");
158
+ copied = at;
159
+ run = 0;
160
+ }
161
+ run += weight;
162
+ if (pair)
163
+ at++;
164
+ }
165
+ if (!pieces)
166
+ return { text, run };
167
+ pieces.push(text.slice(copied));
168
+ return { text: pieces.join(""), run };
169
+ }
170
+ /**
171
+ * Strips a BOM, unifies line endings, and removes terminal escape sequences, control characters
172
+ * other than tab and newline, and the invisible characters of `INVISIBLE`. In a text with no other
173
+ * line break, a U+0085 becomes one (see `NEXT_LINE`).
15
174
  */
16
175
  export function normalizeText(raw) {
17
- let text = raw.replace(/^/, "").replace(/\r\n?/g, "\n");
176
+ const text = raw.replace(/^/, "");
177
+ return normalizeLines(text, breaksAtNextLine(text));
178
+ }
179
+ /**
180
+ * `normalizeText` without the BOM: the same on a whole text as on pieces of it cut after line
181
+ * breaks, given `breaksAtNextLine` of the whole text as `nextLines`.
182
+ */
183
+ function normalizeLines(raw, nextLines) {
184
+ return cleanLines(withoutEscapes(raw.replace(/\r\n?/g, "\n")), nextLines);
185
+ }
186
+ /** `text` without terminal escape sequences. */
187
+ function withoutEscapes(text) {
18
188
  // Remove whole sequences first. Dropping only the ESC byte would leave "[31mERROR[0m" behind.
19
- if (text.includes("\x1b"))
20
- text = text.replace(ANSI_ESCAPE, "");
21
- // eslint-disable-next-line no-control-regex
22
- return text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "");
189
+ // U+009B is the one-character form of "ESC [".
190
+ return text.includes("\x1b") || text.includes("\x9b") ? text.replace(ANSI_ESCAPE, "") : text;
191
+ }
192
+ /**
193
+ * `withoutEscapes`, with a pause after each `piece` characters or so. The sequences are found one
194
+ * after the other, as `replace` finds them, so the result is the same.
195
+ */
196
+ async function withoutEscapesInPieces(text, slicer, piece) {
197
+ if (!text.includes("\x1b") && !text.includes("\x9b"))
198
+ return text;
199
+ // A copy of its own: during a pause, another ingest may use `ANSI_ESCAPE`, which moves its lastIndex.
200
+ const escape = new RegExp(ANSI_ESCAPE.source, "g");
201
+ const done = [];
202
+ let parts = [];
203
+ // Where the text after the last sequence starts, and where the last pause was.
204
+ let kept = 0;
205
+ let paused = 0;
206
+ for (let found = escape.exec(text); found !== null; found = escape.exec(text)) {
207
+ parts.push(text.slice(kept, found.index));
208
+ kept = escape.lastIndex;
209
+ if (kept - paused >= piece) {
210
+ done.push(parts.join(""));
211
+ parts = [];
212
+ paused = kept;
213
+ await slicer.maybePause();
214
+ }
215
+ }
216
+ parts.push(text.slice(kept));
217
+ done.push(parts.join(""));
218
+ return done.length === 1 ? done[0] : done.join("");
219
+ }
220
+ /**
221
+ * `normalizeLines`, a piece of about `piece` characters at a time, with a pause between pieces. A
222
+ * line with no break for megabytes can hold millions of characters or escape sequences to remove,
223
+ * which take seconds in one go. The steps of `cleanLines` are taken on each piece in turn, so the
224
+ * result is the same as in one go: the escape sequences are found in order; the invisible
225
+ * characters are removed from pieces that end where `removesCleanly` says; the stream-safe form
226
+ * counts the marks of a run across pieces; and the text is composed up to the last place where
227
+ * NFC joins nothing across (`composesCleanly`), the rest with the next piece. A run of millions of
228
+ * marks has such a place after every 30 marks, where the stream-safe form puts a grapheme joiner:
229
+ * composed in one go, it held the server for seconds.
230
+ */
231
+ export async function normalizeInPieces(raw, slicer, nextLines, piece = SLICE_CHARACTERS) {
232
+ const text = await withoutEscapesInPieces(raw.replace(/\r\n?/g, "\n"), slicer, piece);
233
+ const parts = [];
234
+ // The marks in a row that end the text cleaned so far, and the end of that text, not yet composed.
235
+ let run = 0;
236
+ let tail = "";
237
+ for (let from = 0; from < text.length;) {
238
+ let to = Math.min(text.length, from + piece);
239
+ // Where the next piece starts.
240
+ let next = to;
241
+ while (to < text.length && !removesCleanly(text, to)) {
242
+ if (text.charCodeAt(to) === 0x85) {
243
+ // A run of U+0085 after U+0080-U+00FF, which no place may cut. `cleanLines` removes all of
244
+ // it, and gives the same on the text before it and after it alone: the run is left out.
245
+ NEXT_LINE_RUN.lastIndex = to;
246
+ NEXT_LINE_RUN.test(text);
247
+ next = NEXT_LINE_RUN.lastIndex;
248
+ break;
249
+ }
250
+ next = ++to;
251
+ }
252
+ const slice = text.slice(from, to);
253
+ const safe = streamSafe(removeInvisible(nextLines && slice.includes("\x85") ? slice.replace(NEXT_LINE, "\n") : slice), 0, run);
254
+ run = safe.run;
255
+ const cleaned = tail + safe.text;
256
+ // The last piece is composed whole; another, up to a place where what follows joins nothing
257
+ // before it. Its very end is not one: the next piece may start with a mark.
258
+ let cut = cleaned.length;
259
+ if (next < text.length) {
260
+ cut = Math.max(0, cut - 1);
261
+ while (cut > 0 && !composesCleanly(cleaned, cut))
262
+ cut--;
263
+ }
264
+ const done = cleaned.slice(0, cut);
265
+ parts.push(MAY_COMPOSE.test(done) ? done.normalize("NFC") : done);
266
+ tail = cleaned.slice(cut);
267
+ from = next;
268
+ await slicer.maybePause();
269
+ }
270
+ return parts.length === 1 ? parts[0] : parts.join("");
271
+ }
272
+ /**
273
+ * Whether `removeInvisible`, after U+0085 is made a line break where it ends a line, gives the same
274
+ * result on `text` cut before `at` as on it whole. It does unless the cut is between the two halves
275
+ * of a character outside the basic plane, inside a flag, between a soft hyphen and a line break,
276
+ * or before a U+0085 right after U+0080-U+00FF. Only these places are kept whole: a rule that
277
+ * never cut after a soft hyphen or half of a pair would never cut a line of soft hyphens, or of
278
+ * tag characters and emoji in turn, and such a line would be cleaned in one go again.
279
+ */
280
+ function removesCleanly(text, at) {
281
+ const before = text.charCodeAt(at - 1);
282
+ const after = text.charCodeAt(at);
283
+ if (isHighSurrogate(before) && isLowSurrogate(after))
284
+ return false;
285
+ if (before === 0xad && after === 0x0a)
286
+ return false;
287
+ if (after === 0x85 && before >= 0x80 && before <= 0xff)
288
+ return false;
289
+ // A flag is 14 units: U+1F3F4, then tag characters, each a pair that starts with U+DB40.
290
+ if (after === 0xdb40 && text.slice(Math.max(0, at - 12), at).includes("\uD83C\uDFF4"))
291
+ return false;
292
+ return true;
293
+ }
294
+ /**
295
+ * Whether NFC gives the same result on a text in the stream-safe form cut before `at` as on it
296
+ * whole: the cut is not inside a character, and NFC joins nothing across it. It joins a mark to the
297
+ * letter before it, and orders the marks of a run, but neither across a grapheme joiner, which is
298
+ * a starter and joins with nothing. It joins a Hangul vowel to an initial consonant, and a final
299
+ * consonant to a syllable of the two, or to a vowel that will join the consonant before it.
300
+ */
301
+ function composesCleanly(text, at) {
302
+ const before = text.charCodeAt(at - 1);
303
+ const after = text.charCodeAt(at);
304
+ if (isHighSurrogate(before) && isLowSurrogate(after))
305
+ return false;
306
+ if (after < 0x0300 || before === GRAPHEME_JOINER)
307
+ return true;
308
+ if (after >= 0x1161 && after <= 0x1175)
309
+ return !(before >= 0x1100 && before <= 0x1112);
310
+ if (after >= 0x11a8 && after <= 0x11c2)
311
+ return !((before >= 0x1161 && before <= 0x1175) || (before >= 0xac00 && before <= 0xd7a3 && (before - 0xac00) % 28 === 0));
312
+ const low = isHighSurrogate(after) ? text.charCodeAt(at + 1) : 0;
313
+ return !isMark(isLowSurrogate(low) ? ((after - 0xd800) << 10) + (low - 0xdc00) + 0x10000 : after);
23
314
  }
315
+ /**
316
+ * Characters that are written several ways for one meaning, each folded to the plain one for a
317
+ * search that ignores case: curly quotes and primes to `'` and `"`, Hebrew geresh (׳) and gershayim
318
+ * (״) too, which keyboards replace by them ("צה״ל", "צה\"ל"); hyphens, dashes, the minus sign and the
319
+ * Hebrew maqaf (־) to "-"; no-break, thin and other fixed-width spaces to a space; and the
320
+ * full-width forms of ASCII (A, 1) to ASCII. Each is one UTF-16 unit for one, so offsets keep.
321
+ */
322
+ const SEARCH_FOLDS = {
323
+ "\u2018": "'", "\u2019": "'", "\u201a": "'", "\u201b": "'", "\u2032": "'", "\u05f3": "'", "\u02bc": "'",
324
+ "\u201c": "\"", "\u201d": "\"", "\u201e": "\"", "\u201f": "\"", "\u2033": "\"", "\u05f4": "\"",
325
+ "\u2010": "-", "\u2011": "-", "\u2012": "-", "\u2013": "-", "\u2014": "-", "\u2015": "-", "\u2212": "-", "\u05be": "-",
326
+ "\u00a0": " ", "\u2007": " ", "\u2009": " ", "\u200a": " ", "\u202f": " ", "\u2002": " ", "\u2003": " ",
327
+ "\u03c2": "\u03c3",
328
+ };
329
+ const SEARCH_FOLD = /[\u2018\u2019\u201a\u201b\u2032\u05f3\u02bc\u201c\u201d\u201e\u201f\u2033\u05f4\u2010-\u2015\u2212\u05be\u00a0\u2007\u2009\u200a\u202f\u2002\u2003\u03c2\uff01-\uff5e]/g;
24
330
  /**
25
331
  * Lowercases for case-insensitive search without changing the string's length, so an offset in the
26
332
  * result points at the same character in the original. "İ" (U+0130) is the one character whose
27
- * lowercase form is longer; it is folded to "i".
333
+ * lowercase form is longer; it is folded to "i". Greek final sigma (ς) is folded to σ, as an upper
334
+ * case Σ is lowered to either depending on where it stands. Then the characters of `SEARCH_FOLDS`
335
+ * are folded, and the full-width forms of ASCII: a search for "don't" finds "don’t".
28
336
  */
29
337
  export function foldCase(text) {
30
- const lower = (text.includes("\u0130") ? text.replaceAll("\u0130", "i") : text).toLowerCase();
31
- if (lower.length === text.length)
338
+ let lower = (text.includes("\u0130") ? text.replaceAll("\u0130", "i") : text).toLowerCase();
339
+ if (lower.length !== text.length) {
340
+ // Not expected with today's Unicode data. Fold unit by unit and keep any unit that would grow.
341
+ let out = "";
342
+ for (let index = 0; index < text.length; index++) {
343
+ const unit = text[index];
344
+ const folded = unit.toLowerCase();
345
+ out += folded.length === 1 ? folded : unit;
346
+ }
347
+ lower = out;
348
+ }
349
+ SEARCH_FOLD.lastIndex = 0;
350
+ if (!SEARCH_FOLD.test(lower))
32
351
  return lower;
33
- // Not expected with today's Unicode data. Fold unit by unit and keep any unit that would grow.
34
- let out = "";
35
- for (let index = 0; index < text.length; index++) {
36
- const unit = text[index];
37
- const folded = unit.toLowerCase();
38
- out += folded.length === 1 ? folded : unit;
352
+ // One pass over the character codes, with a table: a replace with a callback for each character
353
+ // took seconds on a text full of curly quotes and dashes, which counted against a search's time.
354
+ const codes = new Uint16Array(lower.length);
355
+ for (let index = 0; index < lower.length; index++) {
356
+ const code = lower.charCodeAt(index);
357
+ codes[index] = FOLDED[code] || code;
39
358
  }
40
- return out;
359
+ // From the codes a block at a time: a decoder would make a lone half of a surrogate pair U+FFFD.
360
+ const parts = [];
361
+ for (let at = 0; at < codes.length; at += 8_192)
362
+ parts.push(String.fromCharCode(...codes.subarray(at, at + 8_192)));
363
+ return parts.join("");
41
364
  }
365
+ /** For each UTF-16 unit, the unit `foldCase` makes of it, or 0 when it keeps it. */
366
+ const FOLDED = (() => {
367
+ const table = new Uint16Array(0x10000);
368
+ for (const [from, to] of Object.entries(SEARCH_FOLDS))
369
+ table[from.charCodeAt(0)] = to.charCodeAt(0);
370
+ for (let code = 0xff01; code <= 0xff5e; code++)
371
+ table[code] = code - 0xfee0;
372
+ return table;
373
+ })();
42
374
  /** The first and the second half of a character outside the basic plane, as JavaScript holds it. */
43
375
  const isHighSurrogate = (code) => code >= 0xd800 && code <= 0xdbff;
44
376
  const isLowSurrogate = (code) => code >= 0xdc00 && code <= 0xdfff;
377
+ /**
378
+ * The first `end` UTF-16 units of `text`, one fewer when the last of them would be the first half
379
+ * of a character outside the basic plane (an emoji). Half of one is not text: JSON writes it as
380
+ * `\ud83d`, and an API that checks its input (Claude's) refuses the request.
381
+ */
382
+ export function sliceWhole(text, end) {
383
+ const at = Math.max(0, Math.min(text.length, Math.trunc(end)));
384
+ return at > 0 && at < text.length && isHighSurrogate(text.charCodeAt(at - 1)) ? text.slice(0, at - 1) : text.slice(0, at);
385
+ }
386
+ /** Half of a character outside the basic plane, on its own. */
387
+ const LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
388
+ /**
389
+ * `text` with each half of a character that is on its own (an emoji cut in two) made a replacement
390
+ * character, as `String.prototype.toWellFormed` does. 0.5.0 cut some strings that way, and kept them:
391
+ * log templates in the metadata, and search windows in tool rounds. Claude's API refuses a request
392
+ * that holds one. Text that is whole comes back as it is.
393
+ */
394
+ export function wellFormed(text) {
395
+ return /[\ud800-\udfff]/.test(text) ? text.replace(LONE_SURROGATE, "\ufffd") : text;
396
+ }
397
+ /**
398
+ * A JSON value with `wellFormed` applied to every string in it, keys included. The same value, not
399
+ * a copy, when nothing in it needed that.
400
+ */
401
+ export function wellFormedJson(value) {
402
+ if (typeof value === "string")
403
+ return wellFormed(value);
404
+ if (Array.isArray(value)) {
405
+ let changed = false;
406
+ const items = value.map((item) => {
407
+ const fixed = wellFormedJson(item);
408
+ if (fixed !== item)
409
+ changed = true;
410
+ return fixed;
411
+ });
412
+ return (changed ? items : value);
413
+ }
414
+ if (value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
415
+ let changed = false;
416
+ const entries = Object.entries(value).map(([key, item]) => {
417
+ const fixedKey = wellFormed(key);
418
+ const fixed = wellFormedJson(item);
419
+ if (fixedKey !== key || fixed !== item)
420
+ changed = true;
421
+ return [fixedKey, fixed];
422
+ });
423
+ return (changed ? Object.fromEntries(entries) : value);
424
+ }
425
+ return value;
426
+ }
45
427
  /**
46
428
  * Splits lines longer than `limit`, preferring a break after whitespace or punctuation near the
47
429
  * end of each piece. Minified JSON or a PDF paragraph becomes many addressable lines.
48
430
  */
49
431
  export function wrapLongLines(text, limit = MAX_LINE_CHARACTERS) {
432
+ // Most files have no long line: then the text is used as it is, without splitting and joining it.
433
+ let longest = 0;
434
+ let start = 0;
435
+ for (let end = text.indexOf("\n");; end = text.indexOf("\n", start)) {
436
+ const stop = end === -1 ? text.length : end;
437
+ if (stop - start > longest)
438
+ longest = stop - start;
439
+ if (end === -1 || longest > limit)
440
+ break;
441
+ start = end + 1;
442
+ }
443
+ if (longest <= limit)
444
+ return { text, wrapped: 0 };
50
445
  let wrapped = 0;
51
446
  const lines = text.split("\n");
52
447
  const out = [];
@@ -87,6 +482,7 @@ const PUNCTUATION = 0.85; // The first of a run of ASCII punctuation; the rest o
87
482
  const NEWLINE = 2.2;
88
483
  const TAB = 1;
89
484
  const LOOSE_SPACE = 0.2; // A space before anything but a letter. A space before a word is free.
485
+ const SPACE_RUN = 16; // A run of spaces costs a token for each this many after its first.
90
486
  const LATIN_EXTENDED = 0.6; // é, ü, ß
91
487
  const GREEK = 0.4;
92
488
  const CYRILLIC = 0.3;
@@ -109,14 +505,23 @@ const SYMBOL = 1; // Dashes, quotes, arrows, box drawing, and anything unclassif
109
505
  * of random letters in a single case with no digits (about 70% of the real count).
110
506
  */
111
507
  export function estimateTokens(text) {
112
- let tokens = 0;
508
+ return Math.ceil(tokensIn(text, 0, text.length, 0));
509
+ }
510
+ /**
511
+ * The tokens of `text` from `from` to `to`, added to `tokens`. Every count starts again after a line
512
+ * break, so a text cut after line breaks gives, piece by piece, the sum it gives whole.
513
+ */
514
+ function tokensIn(text, from, to, tokens) {
113
515
  // The current run of ASCII letters: its length since the last case change, and its casing.
114
516
  let piece = 0;
115
517
  let capitalsInARow = 0;
116
518
  let previousWasLower = false;
117
519
  let previous = 0; // 1 = space, 2 = ASCII punctuation, 0 = anything else
118
- for (let index = 0; index < text.length; index++) {
520
+ let spaces = 0; // the length of the current run of spaces
521
+ for (let index = from; index < to; index++) {
119
522
  const code = text.charCodeAt(index);
523
+ if (code !== 32)
524
+ spaces = 0;
120
525
  if ((code >= 97 && code <= 122) || (code >= 65 && code <= 90)) {
121
526
  const capital = code <= 90;
122
527
  if (piece === 0)
@@ -139,6 +544,11 @@ export function estimateTokens(text) {
139
544
  capitalsInARow = 0;
140
545
  previousWasLower = false;
141
546
  if (code === 32) {
547
+ // Tokenizers have tokens for runs of spaces up to a length: a long run costs about one token
548
+ // for every SPACE_RUN spaces after the first. Fixed-width reports and padded tables were
549
+ // planned at almost nothing, then refused by the provider.
550
+ if (++spaces > 1 && (spaces - 1) % SPACE_RUN === 0)
551
+ tokens += 1;
142
552
  previous = 1;
143
553
  continue;
144
554
  }
@@ -198,7 +608,7 @@ export function estimateTokens(text) {
198
608
  else
199
609
  tokens += KANA;
200
610
  }
201
- return Math.ceil(tokens);
611
+ return tokens;
202
612
  }
203
613
  /**
204
614
  * The size of a text in one pass: its UTF-8 bytes, and the bytes it takes as a string in a JSON
@@ -208,9 +618,14 @@ export function estimateTokens(text) {
208
618
  * quarter or more, a novel by a hundredth.
209
619
  */
210
620
  export function textSizes(text) {
621
+ const { utf8, escapes } = sizesIn(text, 0, text.length);
622
+ return { utf8, json: utf8 + escapes + 2 };
623
+ }
624
+ /** UTF-8 bytes and JSON escapes of `text` from `from` to `to`, which must not split a surrogate pair. */
625
+ function sizesIn(text, from, to) {
211
626
  let utf8 = 0;
212
627
  let escapes = 0;
213
- for (let index = 0; index < text.length; index++) {
628
+ for (let index = from; index < to; index++) {
214
629
  const code = text.charCodeAt(index);
215
630
  if (code < 0x80) {
216
631
  utf8 += 1;
@@ -222,7 +637,7 @@ export function textSizes(text) {
222
637
  else if (code < 0x800) {
223
638
  utf8 += 2;
224
639
  }
225
- else if (isHighSurrogate(code) && isLowSurrogate(text.charCodeAt(index + 1))) {
640
+ else if (isHighSurrogate(code) && index + 1 < to && isLowSurrogate(text.charCodeAt(index + 1))) {
226
641
  utf8 += 4;
227
642
  index++;
228
643
  }
@@ -233,7 +648,80 @@ export function textSizes(text) {
233
648
  escapes += 3;
234
649
  }
235
650
  }
236
- return { utf8, json: utf8 + escapes + 2 };
651
+ return { utf8, escapes };
652
+ }
653
+ /** Characters worked on between two looks at the clock while ingesting. */
654
+ const SLICE_CHARACTERS = 1 << 18;
655
+ /**
656
+ * The text cut into slices of about 256K characters, each ending after a line break (the last
657
+ * one at the end of the text), as `[from, to)` offsets.
658
+ */
659
+ function* lineSlices(text) {
660
+ for (let from = 0; from < text.length;) {
661
+ let to = Math.min(text.length, from + SLICE_CHARACTERS);
662
+ if (to < text.length) {
663
+ const newline = text.indexOf("\n", to - 1);
664
+ to = newline === -1 ? text.length : newline + 1;
665
+ }
666
+ yield [from, to];
667
+ from = to;
668
+ }
669
+ }
670
+ /**
671
+ * `estimateTokens` and `textSizes` of a text, the same numbers, worked out a slice at a time so
672
+ * that other requests get a turn while a large upload is measured. Slices end after a line break.
673
+ */
674
+ export async function measureText(text, slicer) {
675
+ let tokens = 0;
676
+ let utf8 = 0;
677
+ let escapes = 0;
678
+ for (const [from, to] of lineSlices(text)) {
679
+ tokens = tokensIn(text, from, to, tokens);
680
+ const sizes = sizesIn(text, from, to);
681
+ utf8 += sizes.utf8;
682
+ escapes += sizes.escapes;
683
+ await slicer.maybePause();
684
+ }
685
+ return { tokens: Math.ceil(tokens), utf8, json: utf8 + escapes + 2 };
686
+ }
687
+ /**
688
+ * What ingest makes of extracted text, a slice at a time: `normalizeText`, then `wrapLongLines`,
689
+ * then the lines (a line break at the very end does not start another line). The same results as
690
+ * doing each in one go: no step of `normalizeText` reaches across a line break, and whether a U+0085
691
+ * ends lines is decided once, for the whole text. A slice that runs far past its size holds a long
692
+ * line: it is cleaned in pieces too. `onProgress` is told the characters of `raw` cleaned so far,
693
+ * after each slice; splitting the lines after that is quick, and is not counted.
694
+ */
695
+ export async function prepareText(raw, slicer, onProgress) {
696
+ const start = raw.charCodeAt(0) === 0xfeff ? 1 : 0;
697
+ const body = start === 1 ? raw.slice(1) : raw;
698
+ const nextLines = breaksAtNextLine(body);
699
+ const parts = [];
700
+ // A clean text (most logs) comes back as it is: joining its slices would copy all of it.
701
+ let changed = false;
702
+ for (const [from, to] of lineSlices(body)) {
703
+ const slice = body.slice(from, to);
704
+ const normalized = slice.length > 2 * SLICE_CHARACTERS ? await normalizeInPieces(slice, slicer, nextLines) : normalizeLines(slice, nextLines);
705
+ if (normalized !== slice)
706
+ changed = true;
707
+ parts.push(normalized);
708
+ onProgress?.(start + to, raw.length);
709
+ await slicer.maybePause();
710
+ }
711
+ const { text, wrapped } = wrapLongLines(!changed ? body : parts.length === 1 ? parts[0] : parts.join(""));
712
+ parts.length = 0;
713
+ await slicer.maybePause();
714
+ const lines = [];
715
+ for (const [from, to] of lineSlices(text)) {
716
+ const piece = text.slice(from, to).split("\n");
717
+ // A slice that ends with a line break splits into one empty string too many.
718
+ if (text.charCodeAt(to - 1) === 10)
719
+ piece.pop();
720
+ for (const line of piece)
721
+ lines.push(line);
722
+ await slicer.maybePause();
723
+ }
724
+ return { text, wrapped, lines };
237
725
  }
238
726
  /** UTF-8 byte length without allocating an encoded copy. */
239
727
  export function utf8Bytes(text) {
@@ -297,6 +785,20 @@ export class LineIndex {
297
785
  return "";
298
786
  return this.text.slice(this.startOf(line), this.endOf(line));
299
787
  }
788
+ /**
789
+ * Lines `first` to `last`, which must exist, as a text of their own with its index: their text,
790
+ * with the line break after the last one when there is one, as a document read by range gives
791
+ * a piece of itself. Offsets in it are counted from `startOf(first)`.
792
+ */
793
+ piece(first, last) {
794
+ const start = this.startOf(first);
795
+ const end = last < this.lineCount ? this.starts[last] : this.text.length;
796
+ const starts = new Uint32Array(last - first + 1);
797
+ for (let line = 0; line < starts.length; line++)
798
+ starts[line] = this.starts[first - 1 + line] - start;
799
+ const text = this.text.slice(start, end);
800
+ return { text, lines: new LineIndex(text, starts) };
801
+ }
300
802
  /** Lines `from`..`to` inclusive, each prefixed with its number. */
301
803
  numbered(from, to) {
302
804
  const out = [];