llm-large-files 0.7.0 → 0.8.1

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 (196) hide show
  1. package/CHANGELOG.md +370 -1
  2. package/README.md +12 -8
  3. package/dist/aggregate.d.ts +103 -0
  4. package/dist/aggregate.d.ts.map +1 -0
  5. package/dist/aggregate.js +651 -0
  6. package/dist/aggregate.js.map +1 -0
  7. package/dist/analyze.d.ts +3 -1
  8. package/dist/analyze.d.ts.map +1 -1
  9. package/dist/analyze.js +109 -14
  10. package/dist/analyze.js.map +1 -1
  11. package/dist/anthropic/adapter.d.ts.map +1 -1
  12. package/dist/anthropic/adapter.js +4 -1
  13. package/dist/anthropic/adapter.js.map +1 -1
  14. package/dist/ask.d.ts +3 -3
  15. package/dist/ask.d.ts.map +1 -1
  16. package/dist/ask.js +72 -17
  17. package/dist/ask.js.map +1 -1
  18. package/dist/decode.d.ts +19 -0
  19. package/dist/decode.d.ts.map +1 -0
  20. package/dist/decode.js +97 -0
  21. package/dist/decode.js.map +1 -0
  22. package/dist/errors.d.ts +55 -0
  23. package/dist/errors.d.ts.map +1 -1
  24. package/dist/errors.js +65 -0
  25. package/dist/errors.js.map +1 -1
  26. package/dist/events.d.ts +6 -0
  27. package/dist/events.d.ts.map +1 -1
  28. package/dist/events.js +5 -1
  29. package/dist/events.js.map +1 -1
  30. package/dist/evidence.d.ts.map +1 -1
  31. package/dist/evidence.js +23 -0
  32. package/dist/evidence.js.map +1 -1
  33. package/dist/extract.d.ts +12 -18
  34. package/dist/extract.d.ts.map +1 -1
  35. package/dist/extract.js +82 -746
  36. package/dist/extract.js.map +1 -1
  37. package/dist/gemini/adapter.d.ts.map +1 -1
  38. package/dist/gemini/adapter.js +9 -5
  39. package/dist/gemini/adapter.js.map +1 -1
  40. package/dist/gemini/endpoints.d.ts +5 -1
  41. package/dist/gemini/endpoints.d.ts.map +1 -1
  42. package/dist/gemini/endpoints.js +11 -2
  43. package/dist/gemini/endpoints.js.map +1 -1
  44. package/dist/gemini/generate.d.ts.map +1 -1
  45. package/dist/gemini/generate.js +20 -3
  46. package/dist/gemini/generate.js.map +1 -1
  47. package/dist/groups.d.ts +54 -0
  48. package/dist/groups.d.ts.map +1 -0
  49. package/dist/groups.js +136 -0
  50. package/dist/groups.js.map +1 -0
  51. package/dist/html.d.ts +11 -0
  52. package/dist/html.d.ts.map +1 -0
  53. package/dist/html.js +1112 -0
  54. package/dist/html.js.map +1 -0
  55. package/dist/index.d.ts +2 -1
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +1 -1
  58. package/dist/index.js.map +1 -1
  59. package/dist/library.d.ts.map +1 -1
  60. package/dist/library.js +57 -14
  61. package/dist/library.js.map +1 -1
  62. package/dist/limiter.d.ts +2 -1
  63. package/dist/limiter.d.ts.map +1 -1
  64. package/dist/limiter.js +3 -2
  65. package/dist/limiter.js.map +1 -1
  66. package/dist/model.d.ts.map +1 -1
  67. package/dist/model.js +8 -1
  68. package/dist/model.js.map +1 -1
  69. package/dist/node/handlers.d.ts.map +1 -1
  70. package/dist/node/handlers.js +69 -15
  71. package/dist/node/handlers.js.map +1 -1
  72. package/dist/node/index.d.ts +2 -0
  73. package/dist/node/index.d.ts.map +1 -1
  74. package/dist/node/index.js +1 -0
  75. package/dist/node/index.js.map +1 -1
  76. package/dist/node/ingest-child.d.ts +38 -0
  77. package/dist/node/ingest-child.d.ts.map +1 -0
  78. package/dist/node/ingest-child.js +42 -0
  79. package/dist/node/ingest-child.js.map +1 -0
  80. package/dist/node/isolated.d.ts +88 -0
  81. package/dist/node/isolated.d.ts.map +1 -0
  82. package/dist/node/isolated.js +381 -0
  83. package/dist/node/isolated.js.map +1 -0
  84. package/dist/office.d.ts +105 -0
  85. package/dist/office.d.ts.map +1 -0
  86. package/dist/office.js +1092 -0
  87. package/dist/office.js.map +1 -0
  88. package/dist/openai/adapter.d.ts.map +1 -1
  89. package/dist/openai/adapter.js +15 -1
  90. package/dist/openai/adapter.js.map +1 -1
  91. package/dist/pdf-pages.d.ts.map +1 -1
  92. package/dist/pdf-pages.js +2 -6
  93. package/dist/pdf-pages.js.map +1 -1
  94. package/dist/peers.d.ts +8 -0
  95. package/dist/peers.d.ts.map +1 -0
  96. package/dist/peers.js +32 -0
  97. package/dist/peers.js.map +1 -0
  98. package/dist/plan.d.ts +3 -1
  99. package/dist/plan.d.ts.map +1 -1
  100. package/dist/plan.js +17 -1
  101. package/dist/plan.js.map +1 -1
  102. package/dist/quality.d.ts +16 -0
  103. package/dist/quality.d.ts.map +1 -0
  104. package/dist/quality.js +157 -0
  105. package/dist/quality.js.map +1 -0
  106. package/dist/ranged.d.ts.map +1 -1
  107. package/dist/ranged.js +4 -2
  108. package/dist/ranged.js.map +1 -1
  109. package/dist/search.d.ts +99 -22
  110. package/dist/search.d.ts.map +1 -1
  111. package/dist/search.js +744 -140
  112. package/dist/search.js.map +1 -1
  113. package/dist/text-index.d.ts +3 -1
  114. package/dist/text-index.d.ts.map +1 -1
  115. package/dist/text-index.js +3 -1
  116. package/dist/text-index.js.map +1 -1
  117. package/dist/text.d.ts +27 -3
  118. package/dist/text.d.ts.map +1 -1
  119. package/dist/text.js +225 -23
  120. package/dist/text.js.map +1 -1
  121. package/dist/tools.d.ts +9 -0
  122. package/dist/tools.d.ts.map +1 -1
  123. package/dist/tools.js +457 -16
  124. package/dist/tools.js.map +1 -1
  125. package/dist/types.d.ts +23 -3
  126. package/dist/types.d.ts.map +1 -1
  127. package/dist/word-styles.d.ts +102 -0
  128. package/dist/word-styles.d.ts.map +1 -0
  129. package/dist/word-styles.js +419 -0
  130. package/dist/word-styles.js.map +1 -0
  131. package/dist/xlsx.d.ts +23 -0
  132. package/dist/xlsx.d.ts.map +1 -0
  133. package/dist/xlsx.js +511 -0
  134. package/dist/xlsx.js.map +1 -0
  135. package/dist/xml-stream.d.ts +55 -0
  136. package/dist/xml-stream.d.ts.map +1 -0
  137. package/dist/xml-stream.js +235 -0
  138. package/dist/xml-stream.js.map +1 -0
  139. package/docs/README.md +8 -8
  140. package/docs/getting-started.md +1 -1
  141. package/docs/guides/costs-and-limits.md +7 -5
  142. package/docs/guides/deployment.md +95 -29
  143. package/docs/guides/errors-and-reliability.md +23 -10
  144. package/docs/guides/pdfs.md +127 -74
  145. package/docs/guides/storage.md +1 -1
  146. package/docs/guides/testing.md +5 -1
  147. package/docs/guides/web-app.md +10 -9
  148. package/docs/how-it-works.md +80 -50
  149. package/docs/reference/ask.md +26 -8
  150. package/docs/reference/errors-and-retries.md +5 -3
  151. package/docs/reference/events.md +14 -6
  152. package/docs/reference/gemini.md +6 -2
  153. package/docs/reference/library.md +221 -79
  154. package/docs/reference/node.md +201 -23
  155. package/docs/reference/openai.md +1 -1
  156. package/docs/reference/tools.md +269 -23
  157. package/docs/security.md +114 -69
  158. package/docs/troubleshooting.md +40 -20
  159. package/package.json +6 -2
  160. package/src/aggregate.ts +674 -0
  161. package/src/analyze.ts +117 -13
  162. package/src/anthropic/adapter.ts +4 -1
  163. package/src/ask.ts +73 -17
  164. package/src/decode.ts +89 -0
  165. package/src/errors.ts +108 -0
  166. package/src/events.ts +10 -1
  167. package/src/evidence.ts +23 -0
  168. package/src/extract.ts +79 -701
  169. package/src/gemini/adapter.ts +9 -5
  170. package/src/gemini/endpoints.ts +12 -2
  171. package/src/gemini/generate.ts +19 -3
  172. package/src/groups.ts +162 -0
  173. package/src/html.ts +1071 -0
  174. package/src/index.ts +2 -1
  175. package/src/library.ts +52 -14
  176. package/src/limiter.ts +6 -1
  177. package/src/model.ts +8 -1
  178. package/src/node/handlers.ts +66 -16
  179. package/src/node/index.ts +2 -0
  180. package/src/node/ingest-child.ts +61 -0
  181. package/src/node/isolated.ts +464 -0
  182. package/src/office.ts +1047 -0
  183. package/src/openai/adapter.ts +14 -1
  184. package/src/pdf-pages.ts +2 -5
  185. package/src/peers.ts +29 -0
  186. package/src/plan.ts +19 -1
  187. package/src/quality.ts +146 -0
  188. package/src/ranged.ts +4 -2
  189. package/src/search.ts +738 -146
  190. package/src/text-index.ts +4 -2
  191. package/src/text.ts +214 -23
  192. package/src/tools.ts +440 -16
  193. package/src/types.ts +20 -3
  194. package/src/word-styles.ts +420 -0
  195. package/src/xlsx.ts +478 -0
  196. package/src/xml-stream.ts +224 -0
package/src/text-index.ts CHANGED
@@ -211,7 +211,7 @@ const ascending = (list: Uint32Array, first: number, last: number): boolean => {
211
211
  * another version, or does not describe the text of `meta`: the caller then builds it again from
212
212
  * the text. An index is only a faster way to the same text, so a doubtful one is never used.
213
213
  */
214
- 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 {
215
215
  if (bytes.length < HEADER || MAGIC.some((byte, at) => bytes[at] !== byte)) return undefined;
216
216
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
217
217
  if (view.getUint32(4, true) !== VERSION) return undefined;
@@ -222,7 +222,9 @@ export function parseTextIndex(bytes: Uint8Array, meta?: Pick<DocumentMeta, "lin
222
222
  const characters = view.getFloat64(32, true);
223
223
  if (bytes.length !== HEADER + 4 * (2 * lineCount + passageCount + pageCount)) return undefined;
224
224
  if (!Number.isSafeInteger(textBytes) || !Number.isSafeInteger(characters) || lineCount < 1 || passageCount < 1) return undefined;
225
- 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;
226
228
  const lineStarts = readList(bytes, HEADER, lineCount);
227
229
  const characterStarts = readList(bytes, HEADER + 4 * lineCount, lineCount);
228
230
  const passageStarts = readList(bytes, HEADER + 8 * lineCount, passageCount);
package/src/text.ts CHANGED
@@ -73,9 +73,100 @@ export function breaksAtNextLine(text: string): boolean {
73
73
  return carriageReturn === -1 || carriageReturn >= end;
74
74
  }
75
75
 
76
- /** `removeInvisible`, after each U+0085 that ends a line is made a line break, when `nextLines`. */
76
+ /** `removeInvisible`, after each U+0085 that ends a line is made a line break, when `nextLines`; then `composed`. */
77
77
  function cleanLines(text: string, nextLines: boolean): string {
78
- return removeInvisible(nextLines && text.includes("\x85") ? text.replace(NEXT_LINE, "\n") : text);
78
+ return composed(removeInvisible(nextLines && text.includes("\x85") ? text.replace(NEXT_LINE, "\n") : text));
79
+ }
80
+
81
+ /** A character that Unicode normalization (NFC) may change: nothing below U+0300 does. */
82
+ const MAY_COMPOSE = /[^\x00-\u02ff]/;
83
+
84
+ /**
85
+ * `text` in Unicode's composed form (NFC): "e" followed by a combining acute accent becomes one
86
+ * "é", as a model writes it in a query. Text exported from macOS, from some PDF and Word files, and
87
+ * Vietnamese, often comes decomposed, and a search for the composed word found nothing in it. Text
88
+ * with no character from U+0300 on is returned as it is, without the cost of normalizing it.
89
+ * Hebrew and Arabic points are not composed by NFC: they stay as they are.
90
+ */
91
+ export function composed(text: string): string {
92
+ const first = text.search(MAY_COMPOSE);
93
+ if (first === -1) return text;
94
+ return streamSafe(text, first).text.normalize("NFC");
95
+ }
96
+
97
+ /**
98
+ * More marks in a row than any script writes on one letter. NFC orders the marks of a run by
99
+ * their class, in time that grows with the square of the run: 600 KB of marks of two classes in
100
+ * turn held the server 80 seconds. Unicode's stream-safe form (UAX #15) bounds the run instead.
101
+ */
102
+ const MAX_MARKS = 30;
103
+ /** A mark (\p{M}): a character that NFC may order with the marks next to it. */
104
+ const MARK = /\p{M}/u;
105
+ const MARK_RUNS = /\p{M}+/gu;
106
+ /** The combining grapheme joiner: a mark that is a starter, so NFC orders no marks across it. */
107
+ const GRAPHEME_JOINER = 0x034f;
108
+ /** Code points below this are looked up in `marks`; the few marks above it, with `MARK`. */
109
+ const TABLE_END = 0x20000;
110
+ /** 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. */
111
+ const marks = new Uint8Array(TABLE_END);
112
+ const markBlocks = new Uint8Array(TABLE_END >> 12);
113
+
114
+ /** Whether code point `point` is a mark. A look at a table: far quicker than a regex test. */
115
+ function isMark(point: number): boolean {
116
+ if (point >= TABLE_END) return MARK.test(String.fromCodePoint(point));
117
+ const block = point >> 12;
118
+ if (markBlocks[block] === 0) {
119
+ markBlocks[block] = 1;
120
+ const points: number[] = [];
121
+ for (let at = block << 12; at < (block + 1) << 12; at++) if (at < 0xd800 || at > 0xdfff) points.push(at);
122
+ for (const [run] of String.fromCodePoint(...points).matchAll(MARK_RUNS)) for (const character of run) marks[character.codePointAt(0)!] = 1;
123
+ }
124
+ return marks[point] === 1;
125
+ }
126
+
127
+ /**
128
+ * `text` in the stream-safe form: a combining grapheme joiner (U+034F, which shows nothing and is
129
+ * a starter) after every 30 marks of a run, so no run NFC orders is longer than that. `first` is
130
+ * where the first character from U+0300 on is: nothing before it is a mark. `carried`: the marks
131
+ * that end the text before this one, for a text worked on in pieces; `run` is those that end this
132
+ * one. One pass, a look at a table for each character: a regex for long runs tried a match at each
133
+ * mark of a run, and took 1.3 microseconds a mark on runs of 30, more than NFC itself; on a run of
134
+ * millions of marks its greedy repeat ran out of stack, and the upload was refused with the
135
+ * engine's "Maximum call stack size exceeded".
136
+ */
137
+ function streamSafe(text: string, first: number, carried = 0): { text: string; run: number } {
138
+ let pieces: string[] | undefined;
139
+ let copied = 0;
140
+ let run = first === 0 ? carried : 0;
141
+ const length = text.length;
142
+ for (let at = first; at < length; at++) {
143
+ const code = text.charCodeAt(at);
144
+ if (code < 0x0300) {
145
+ run = 0;
146
+ continue;
147
+ }
148
+ // A pair of surrogates is one character, outside the basic plane.
149
+ const low = code >= 0xd800 && code <= 0xdbff ? text.charCodeAt(at + 1) : 0;
150
+ const pair = low >= 0xdc00 && low <= 0xdfff;
151
+ if (pair ? !isMark(((code - 0xd800) << 10) + (low - 0xdc00) + 0x10000) : code === GRAPHEME_JOINER || !isMark(code)) {
152
+ run = 0;
153
+ if (pair) at++;
154
+ continue;
155
+ }
156
+ // These four become two marks each under NFC (UAX #15 counts the marks of the decomposition):
157
+ // counted as one, a run of 30 grew past 30 once composed, and composing it again changed it.
158
+ const weight = code === 0x0344 || code === 0x0f73 || code === 0x0f75 || code === 0x0f81 ? 2 : 1;
159
+ if (run + weight > MAX_MARKS) {
160
+ (pieces ??= []).push(text.slice(copied, at), "\u034f");
161
+ copied = at;
162
+ run = 0;
163
+ }
164
+ run += weight;
165
+ if (pair) at++;
166
+ }
167
+ if (!pieces) return { text, run };
168
+ pieces.push(text.slice(copied));
169
+ return { text: pieces.join(""), run };
79
170
  }
80
171
 
81
172
  /**
@@ -134,17 +225,25 @@ async function withoutEscapesInPieces(text: string, slicer: TimeSlicer, piece: n
134
225
  /**
135
226
  * `normalizeLines`, a piece of about `piece` characters at a time, with a pause between pieces. A
136
227
  * line with no break for megabytes can hold millions of characters or escape sequences to remove,
137
- * which take seconds in one go. The escape sequences are found in order, as in one go, and the
138
- * pieces of the last step (`cleanLines`) end where `cutsCleanly` says, so the result is the same.
228
+ * which take seconds in one go. The steps of `cleanLines` are taken on each piece in turn, so the
229
+ * result is the same as in one go: the escape sequences are found in order; the invisible
230
+ * characters are removed from pieces that end where `removesCleanly` says; the stream-safe form
231
+ * counts the marks of a run across pieces; and the text is composed up to the last place where
232
+ * NFC joins nothing across (`composesCleanly`), the rest with the next piece. A run of millions of
233
+ * marks has such a place after every 30 marks, where the stream-safe form puts a grapheme joiner:
234
+ * composed in one go, it held the server for seconds.
139
235
  */
140
236
  export async function normalizeInPieces(raw: string, slicer: TimeSlicer, nextLines: boolean, piece = SLICE_CHARACTERS): Promise<string> {
141
237
  const text = await withoutEscapesInPieces(raw.replace(/\r\n?/g, "\n"), slicer, piece);
142
238
  const parts: string[] = [];
239
+ // The marks in a row that end the text cleaned so far, and the end of that text, not yet composed.
240
+ let run = 0;
241
+ let tail = "";
143
242
  for (let from = 0; from < text.length;) {
144
243
  let to = Math.min(text.length, from + piece);
145
244
  // Where the next piece starts.
146
245
  let next = to;
147
- while (to < text.length && !cutsCleanly(text, to)) {
246
+ while (to < text.length && !removesCleanly(text, to)) {
148
247
  if (text.charCodeAt(to) === 0x85) {
149
248
  // A run of U+0085 after U+0080-U+00FF, which no place may cut. `cleanLines` removes all of
150
249
  // it, and gives the same on the text before it and after it alone: the run is left out.
@@ -155,7 +254,20 @@ export async function normalizeInPieces(raw: string, slicer: TimeSlicer, nextLin
155
254
  }
156
255
  next = ++to;
157
256
  }
158
- parts.push(cleanLines(text.slice(from, to), nextLines));
257
+ const slice = text.slice(from, to);
258
+ const safe = streamSafe(removeInvisible(nextLines && slice.includes("\x85") ? slice.replace(NEXT_LINE, "\n") : slice), 0, run);
259
+ run = safe.run;
260
+ const cleaned = tail + safe.text;
261
+ // The last piece is composed whole; another, up to a place where what follows joins nothing
262
+ // before it. Its very end is not one: the next piece may start with a mark.
263
+ let cut = cleaned.length;
264
+ if (next < text.length) {
265
+ cut = Math.max(0, cut - 1);
266
+ while (cut > 0 && !composesCleanly(cleaned, cut)) cut--;
267
+ }
268
+ const done = cleaned.slice(0, cut);
269
+ parts.push(MAY_COMPOSE.test(done) ? done.normalize("NFC") : done);
270
+ tail = cleaned.slice(cut);
159
271
  from = next;
160
272
  await slicer.maybePause();
161
273
  }
@@ -163,14 +275,14 @@ export async function normalizeInPieces(raw: string, slicer: TimeSlicer, nextLin
163
275
  }
164
276
 
165
277
  /**
166
- * Whether `cleanLines` gives the same result on `text` cut before `at` as on it whole. It does
167
- * unless the cut is between the two halves of a character outside the basic plane, inside a flag,
168
- * between a soft hyphen and a line break, or before a U+0085 right after U+0080-U+00FF. Only
169
- * these places are kept whole: a rule that never cut after a soft hyphen or half of a pair would
170
- * never cut a line of soft hyphens, or of tag characters and emoji in turn, and such a line
171
- * would be cleaned in one go again.
278
+ * Whether `removeInvisible`, after U+0085 is made a line break where it ends a line, gives the same
279
+ * result on `text` cut before `at` as on it whole. It does unless the cut is between the two halves
280
+ * of a character outside the basic plane, inside a flag, between a soft hyphen and a line break,
281
+ * or before a U+0085 right after U+0080-U+00FF. Only these places are kept whole: a rule that
282
+ * never cut after a soft hyphen or half of a pair would never cut a line of soft hyphens, or of
283
+ * tag characters and emoji in turn, and such a line would be cleaned in one go again.
172
284
  */
173
- function cutsCleanly(text: string, at: number): boolean {
285
+ function removesCleanly(text: string, at: number): boolean {
174
286
  const before = text.charCodeAt(at - 1);
175
287
  const after = text.charCodeAt(at);
176
288
  if (isHighSurrogate(before) && isLowSurrogate(after)) return false;
@@ -181,24 +293,82 @@ function cutsCleanly(text: string, at: number): boolean {
181
293
  return true;
182
294
  }
183
295
 
296
+ /**
297
+ * Whether NFC gives the same result on a text in the stream-safe form cut before `at` as on it
298
+ * whole: the cut is not inside a character, and NFC joins nothing across it. It joins a mark to the
299
+ * letter before it, and orders the marks of a run, but neither across a grapheme joiner, which is
300
+ * a starter and joins with nothing. It joins a Hangul vowel to an initial consonant, and a final
301
+ * consonant to a syllable of the two, or to a vowel that will join the consonant before it.
302
+ */
303
+ function composesCleanly(text: string, at: number): boolean {
304
+ const before = text.charCodeAt(at - 1);
305
+ const after = text.charCodeAt(at);
306
+ if (isHighSurrogate(before) && isLowSurrogate(after)) return false;
307
+ if (after < 0x0300 || before === GRAPHEME_JOINER) return true;
308
+ if (after >= 0x1161 && after <= 0x1175) return !(before >= 0x1100 && before <= 0x1112);
309
+ if (after >= 0x11a8 && after <= 0x11c2) return !((before >= 0x1161 && before <= 0x1175) || (before >= 0xac00 && before <= 0xd7a3 && (before - 0xac00) % 28 === 0));
310
+ const low = isHighSurrogate(after) ? text.charCodeAt(at + 1) : 0;
311
+ return !isMark(isLowSurrogate(low) ? ((after - 0xd800) << 10) + (low - 0xdc00) + 0x10000 : after);
312
+ }
313
+
314
+ /**
315
+ * Characters that are written several ways for one meaning, each folded to the plain one for a
316
+ * search that ignores case: curly quotes and primes to `'` and `"`, Hebrew geresh (׳) and gershayim
317
+ * (״) too, which keyboards replace by them ("צה״ל", "צה\"ל"); hyphens, dashes, the minus sign and the
318
+ * Hebrew maqaf (־) to "-"; no-break, thin and other fixed-width spaces to a space; and the
319
+ * full-width forms of ASCII (A, 1) to ASCII. Each is one UTF-16 unit for one, so offsets keep.
320
+ */
321
+ const SEARCH_FOLDS: Record<string, string> = {
322
+ "\u2018": "'", "\u2019": "'", "\u201a": "'", "\u201b": "'", "\u2032": "'", "\u05f3": "'", "\u02bc": "'",
323
+ "\u201c": "\"", "\u201d": "\"", "\u201e": "\"", "\u201f": "\"", "\u2033": "\"", "\u05f4": "\"",
324
+ "\u2010": "-", "\u2011": "-", "\u2012": "-", "\u2013": "-", "\u2014": "-", "\u2015": "-", "\u2212": "-", "\u05be": "-",
325
+ "\u00a0": " ", "\u2007": " ", "\u2009": " ", "\u200a": " ", "\u202f": " ", "\u2002": " ", "\u2003": " ",
326
+ "\u03c2": "\u03c3",
327
+ };
328
+ 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;
329
+
184
330
  /**
185
331
  * Lowercases for case-insensitive search without changing the string's length, so an offset in the
186
332
  * result points at the same character in the original. "İ" (U+0130) is the one character whose
187
- * 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".
188
336
  */
189
337
  export function foldCase(text: string): string {
190
- const lower = (text.includes("\u0130") ? text.replaceAll("\u0130", "i") : text).toLowerCase();
191
- if (lower.length === text.length) return lower;
192
- // Not expected with today's Unicode data. Fold unit by unit and keep any unit that would grow.
193
- let out = "";
194
- for (let index = 0; index < text.length; index++) {
195
- const unit = text[index]!;
196
- const folded = unit.toLowerCase();
197
- out += folded.length === 1 ? folded : unit;
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)) return lower;
351
+ // One pass over the character codes, with a table: a replace with a callback for each character
352
+ // took seconds on a text full of curly quotes and dashes, which counted against a search's time.
353
+ const codes = new Uint16Array(lower.length);
354
+ for (let index = 0; index < lower.length; index++) {
355
+ const code = lower.charCodeAt(index);
356
+ codes[index] = FOLDED[code] || code;
198
357
  }
199
- return out;
358
+ // From the codes a block at a time: a decoder would make a lone half of a surrogate pair U+FFFD.
359
+ const parts: string[] = [];
360
+ for (let at = 0; at < codes.length; at += 8_192) parts.push(String.fromCharCode(...codes.subarray(at, at + 8_192)));
361
+ return parts.join("");
200
362
  }
201
363
 
364
+ /** For each UTF-16 unit, the unit `foldCase` makes of it, or 0 when it keeps it. */
365
+ const FOLDED = (() => {
366
+ const table = new Uint16Array(0x10000);
367
+ for (const [from, to] of Object.entries(SEARCH_FOLDS)) table[from.charCodeAt(0)] = to.charCodeAt(0);
368
+ for (let code = 0xff01; code <= 0xff5e; code++) table[code] = code - 0xfee0;
369
+ return table;
370
+ })();
371
+
202
372
  /** The first and the second half of a character outside the basic plane, as JavaScript holds it. */
203
373
  const isHighSurrogate = (code: number) => code >= 0xd800 && code <= 0xdbff;
204
374
  const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff;
@@ -309,6 +479,7 @@ const PUNCTUATION = 0.85; // The first of a run of ASCII punctuation; the rest o
309
479
  const NEWLINE = 2.2;
310
480
  const TAB = 1;
311
481
  const LOOSE_SPACE = 0.2; // A space before anything but a letter. A space before a word is free.
482
+ const SPACE_RUN = 16; // A run of spaces costs a token for each this many after its first.
312
483
  const LATIN_EXTENDED = 0.6; // é, ü, ß
313
484
  const GREEK = 0.4;
314
485
  const CYRILLIC = 0.3;
@@ -345,8 +516,10 @@ function tokensIn(text: string, from: number, to: number, tokens: number): numbe
345
516
  let capitalsInARow = 0;
346
517
  let previousWasLower = false;
347
518
  let previous = 0; // 1 = space, 2 = ASCII punctuation, 0 = anything else
519
+ let spaces = 0; // the length of the current run of spaces
348
520
  for (let index = from; index < to; index++) {
349
521
  const code = text.charCodeAt(index);
522
+ if (code !== 32) spaces = 0;
350
523
  if ((code >= 97 && code <= 122) || (code >= 65 && code <= 90)) {
351
524
  const capital = code <= 90;
352
525
  if (piece === 0) tokens += WORD;
@@ -366,6 +539,10 @@ function tokensIn(text: string, from: number, to: number, tokens: number): numbe
366
539
  capitalsInARow = 0;
367
540
  previousWasLower = false;
368
541
  if (code === 32) {
542
+ // Tokenizers have tokens for runs of spaces up to a length: a long run costs about one token
543
+ // for every SPACE_RUN spaces after the first. Fixed-width reports and padded tables were
544
+ // planned at almost nothing, then refused by the provider.
545
+ if (++spaces > 1 && (spaces - 1) % SPACE_RUN === 0) tokens += 1;
369
546
  previous = 1;
370
547
  continue;
371
548
  }
@@ -581,6 +758,20 @@ export class LineIndex {
581
758
  return this.text.slice(this.startOf(line), this.endOf(line));
582
759
  }
583
760
 
761
+ /**
762
+ * Lines `first` to `last`, which must exist, as a text of their own with its index: their text,
763
+ * with the line break after the last one when there is one, as a document read by range gives
764
+ * a piece of itself. Offsets in it are counted from `startOf(first)`.
765
+ */
766
+ piece(first: number, last: number): { text: string; lines: LineIndex } {
767
+ const start = this.startOf(first);
768
+ const end = last < this.lineCount ? this.starts[last]! : this.text.length;
769
+ const starts = new Uint32Array(last - first + 1);
770
+ for (let line = 0; line < starts.length; line++) starts[line] = this.starts[first - 1 + line]! - start;
771
+ const text = this.text.slice(start, end);
772
+ return { text, lines: new LineIndex(text, starts) };
773
+ }
774
+
584
775
  /** Lines `from`..`to` inclusive, each prefixed with its number. */
585
776
  numbered(from: number, to: number): string {
586
777
  const out: string[] = [];