tinyfix-tr 0.0.0-stage → 0.1.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 (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +138 -2
  3. package/dist/pkg/src/context.d.ts +13 -0
  4. package/dist/pkg/src/context.js +80 -0
  5. package/dist/pkg/src/data.d.ts +50 -0
  6. package/dist/pkg/src/data.js +495 -0
  7. package/dist/pkg/src/engine.d.ts +39 -0
  8. package/dist/pkg/src/engine.js +357 -0
  9. package/dist/pkg/src/index.d.ts +30 -0
  10. package/dist/pkg/src/index.js +85 -0
  11. package/dist/pkg/src/protocol.d.ts +64 -0
  12. package/dist/pkg/src/protocol.js +1 -0
  13. package/dist/pkg/src/types.d.ts +184 -0
  14. package/dist/pkg/src/types.js +16 -0
  15. package/dist/pkg/src/worker.d.ts +11 -0
  16. package/dist/pkg/src/worker.js +111 -0
  17. package/dist/pkg/src/workerClient.d.ts +3 -0
  18. package/dist/pkg/src/workerClient.js +202 -0
  19. package/dist/src/context-vocab.d.ts +1 -0
  20. package/dist/src/context-vocab.js +2 -0
  21. package/dist/src/context.d.ts +92 -0
  22. package/dist/src/context.js +390 -0
  23. package/dist/src/corrector.d.ts +338 -0
  24. package/dist/src/corrector.js +2684 -0
  25. package/dist/src/known.d.ts +88 -0
  26. package/dist/src/known.js +286 -0
  27. package/dist/src/lexicon-binary.d.ts +85 -0
  28. package/dist/src/lexicon-binary.js +805 -0
  29. package/dist/src/lexicon.d.ts +24 -0
  30. package/dist/src/lexicon.js +79 -0
  31. package/dist/src/morphology/analyzer.d.ts +30 -0
  32. package/dist/src/morphology/analyzer.js +311 -0
  33. package/dist/src/morphology/binary.d.ts +22 -0
  34. package/dist/src/morphology/binary.js +372 -0
  35. package/dist/src/morphology/dictionary.d.ts +21 -0
  36. package/dist/src/morphology/dictionary.js +559 -0
  37. package/dist/src/morphology/fuzzy.d.ts +44 -0
  38. package/dist/src/morphology/fuzzy.js +599 -0
  39. package/dist/src/morphology/index.d.ts +40 -0
  40. package/dist/src/morphology/index.js +81 -0
  41. package/dist/src/morphology/morphotactics.d.ts +148 -0
  42. package/dist/src/morphology/morphotactics.js +1871 -0
  43. package/dist/src/morphology/phonetics.d.ts +71 -0
  44. package/dist/src/morphology/phonetics.js +309 -0
  45. package/dist/src/morphology/prior.d.ts +61 -0
  46. package/dist/src/morphology/prior.js +457 -0
  47. package/dist/src/morphology/types.d.ts +110 -0
  48. package/dist/src/morphology/types.js +32 -0
  49. package/dist/src/rules/proper-names.d.ts +145 -0
  50. package/dist/src/rules/proper-names.js +1217 -0
  51. package/dist/src/rules/turkish-rules.d.ts +126 -0
  52. package/dist/src/rules/turkish-rules.js +365 -0
  53. package/dist/src/sentence.d.ts +83 -0
  54. package/dist/src/sentence.js +2408 -0
  55. package/dist/src/turkish.d.ts +20 -0
  56. package/dist/src/turkish.js +94 -0
  57. package/package.json +60 -4
@@ -0,0 +1,805 @@
1
+ /**
2
+ * Compact binary format (`ALX1`) for Turkish unigram + bigram lexicons.
3
+ *
4
+ * Design goals:
5
+ * - Zero external dependencies, browser-safe (TypedArrays + DataView + TextEncoder/TextDecoder).
6
+ * - Columnar 1-byte alphabet front-coding for fast direct binary search (~1 ms index init, ~27 µs/word, ~6 MB RAM).
7
+ * - Exact small counts + 1-byte logarithmic quantization for larger counts (zero accuracy loss).
8
+ * - Disjoint Split-CSR bigram tables keyed by unigram IDs (bySecond for frequent trailing particles, byFirst for rest).
9
+ * - Optional Bloom filter tiers for rare protection-only forms (`count = 2, 3, ...`) so clean rare words stay protected
10
+ * without paying full string storage.
11
+ */
12
+ const MAGIC_0 = 0x41; // 'A'
13
+ const MAGIC_1 = 0x4c; // 'L'
14
+ const MAGIC_2 = 0x58; // 'X'
15
+ const MAGIC_3 = 0x31; // '1'
16
+ const FORMAT_VERSION = 1;
17
+ const MAX_WORD_LEN = 128;
18
+ function buildQuantTable(exactMax, buckets, maxVal) {
19
+ const table = new Uint32Array(buckets);
20
+ for (let i = 0; i < exactMax && i < buckets; i++) {
21
+ table[i] = i;
22
+ }
23
+ const logBuckets = buckets - exactMax;
24
+ if (logBuckets > 1 && exactMax > 0 && maxVal > exactMax) {
25
+ const step = Math.log(maxVal / exactMax) / (logBuckets - 1);
26
+ for (let i = 0; i < logBuckets; i++) {
27
+ table[exactMax + i] = Math.round(exactMax * Math.exp(i * step));
28
+ }
29
+ }
30
+ else if (logBuckets === 1) {
31
+ table[exactMax] = exactMax;
32
+ }
33
+ return table;
34
+ }
35
+ function quantizeCount(count, exactMax, buckets, maxVal) {
36
+ if (count <= 0)
37
+ return 0;
38
+ if (count < exactMax)
39
+ return count;
40
+ const logBuckets = buckets - exactMax;
41
+ if (logBuckets <= 1 || exactMax <= 0 || maxVal <= exactMax)
42
+ return Math.min(buckets - 1, exactMax);
43
+ const step = Math.log(maxVal / exactMax) / (logBuckets - 1);
44
+ return Math.min(buckets - 1, exactMax + Math.round(Math.log(count / exactMax) / step));
45
+ }
46
+ function writeVarint(out, value) {
47
+ let v = value >>> 0;
48
+ while (v >= 0x80) {
49
+ out.push((v & 0x7f) | 0x80);
50
+ v >>>= 7;
51
+ }
52
+ out.push(v);
53
+ }
54
+ /** Deterministic dual 32-bit FNV/Murmur-mixed hash over UTF-16 code units (zero allocations). */
55
+ function hashWord2(word) {
56
+ let h1 = 0x811c9dc5 | 0;
57
+ let h2 = 0x9e3779b9 | 0;
58
+ for (let i = 0; i < word.length; i++) {
59
+ const c = word.charCodeAt(i);
60
+ h1 = Math.imul(h1 ^ c, 0x01000193);
61
+ h2 = Math.imul(h2 ^ (c + i), 0x85ebca6b);
62
+ }
63
+ h1 ^= h1 >>> 16;
64
+ h1 = Math.imul(h1, 0x85ebca6b);
65
+ h1 ^= h1 >>> 13;
66
+ h2 ^= h2 >>> 16;
67
+ h2 = Math.imul(h2, 0xc2b2ae35);
68
+ h2 ^= h2 >>> 16;
69
+ return [h1 >>> 0, h2 >>> 0];
70
+ }
71
+ function bloomAdd(bits, nBits, kHashes, word) {
72
+ const [h1, h2] = hashWord2(word);
73
+ for (let i = 0; i < kHashes; i++) {
74
+ const idx = ((h1 + Math.imul(i, h2)) >>> 0) % nBits;
75
+ bits[idx >>> 3] = bits[idx >>> 3] | (1 << (idx & 7));
76
+ }
77
+ }
78
+ function bloomHas(bits, nBits, kHashes, word) {
79
+ const [h1, h2] = hashWord2(word);
80
+ for (let i = 0; i < kHashes; i++) {
81
+ const idx = ((h1 + Math.imul(i, h2)) >>> 0) % nBits;
82
+ if ((bits[idx >>> 3] & (1 << (idx & 7))) === 0)
83
+ return false;
84
+ }
85
+ return true;
86
+ }
87
+ function encodeCsrPartition(groups) {
88
+ const keys = [...groups.keys()].sort((a, b) => a - b);
89
+ const meta = [];
90
+ const inner = [];
91
+ const counts = [];
92
+ let prevKey = 0;
93
+ for (let i = 0; i < keys.length; i++) {
94
+ const key = keys[i];
95
+ writeVarint(meta, key - prevKey);
96
+ prevKey = key;
97
+ const list = groups.get(key);
98
+ list.sort((a, b) => a[0] - b[0]);
99
+ // Deduplicate identical inner IDs (keeping max count) just in case.
100
+ let uniqueLen = 0;
101
+ for (let j = 0; j < list.length; j++) {
102
+ const entry = list[j];
103
+ if (uniqueLen > 0 && list[uniqueLen - 1][0] === entry[0]) {
104
+ if (entry[1] > list[uniqueLen - 1][1])
105
+ list[uniqueLen - 1][1] = entry[1];
106
+ }
107
+ else {
108
+ list[uniqueLen++] = entry;
109
+ }
110
+ }
111
+ writeVarint(meta, uniqueLen);
112
+ let prevVal = 0;
113
+ for (let j = 0; j < uniqueLen; j++) {
114
+ const [val, qc] = list[j];
115
+ writeVarint(inner, val - prevVal);
116
+ prevVal = val;
117
+ counts.push(qc);
118
+ }
119
+ }
120
+ return {
121
+ groupCount: keys.length,
122
+ pairCount: counts.length,
123
+ meta: new Uint8Array(meta),
124
+ inner: new Uint8Array(inner),
125
+ counts: new Uint8Array(counts),
126
+ };
127
+ }
128
+ function decodeCsrPartition(bytes, startOffset, groupCount, pairCount, metaLen, innerLen) {
129
+ const keys = new Uint32Array(groupCount);
130
+ const offsets = new Uint32Array(groupCount + 1);
131
+ const values = new Uint32Array(pairCount);
132
+ let mOff = startOffset;
133
+ const metaEnd = startOffset + metaLen;
134
+ let iOff = metaEnd;
135
+ const innerEnd = metaEnd + innerLen;
136
+ const counts = bytes.subarray(innerEnd, innerEnd + pairCount);
137
+ let curKey = 0;
138
+ let curPair = 0;
139
+ for (let g = 0; g < groupCount; g++) {
140
+ // Read delta key
141
+ let dk = 0;
142
+ let shift = 0;
143
+ for (;;) {
144
+ const b = bytes[mOff++];
145
+ dk |= (b & 0x7f) << shift;
146
+ if ((b & 0x80) === 0)
147
+ break;
148
+ shift += 7;
149
+ }
150
+ curKey += dk >>> 0;
151
+ keys[g] = curKey;
152
+ offsets[g] = curPair;
153
+ // Read degree
154
+ let deg = 0;
155
+ shift = 0;
156
+ for (;;) {
157
+ const b = bytes[mOff++];
158
+ deg |= (b & 0x7f) << shift;
159
+ if ((b & 0x80) === 0)
160
+ break;
161
+ shift += 7;
162
+ }
163
+ deg >>>= 0;
164
+ let curVal = 0;
165
+ for (let j = 0; j < deg; j++) {
166
+ let dv = 0;
167
+ shift = 0;
168
+ for (;;) {
169
+ const b = bytes[iOff++];
170
+ dv |= (b & 0x7f) << shift;
171
+ if ((b & 0x80) === 0)
172
+ break;
173
+ shift += 7;
174
+ }
175
+ curVal += dv >>> 0;
176
+ values[curPair++] = curVal;
177
+ }
178
+ }
179
+ offsets[groupCount] = curPair;
180
+ return {
181
+ table: { keys, offsets, values, counts },
182
+ nextOffset: innerEnd + pairCount,
183
+ };
184
+ }
185
+ function lookupCsr(table, outerId, innerId) {
186
+ const keys = table.keys;
187
+ let lo = 0;
188
+ let hi = keys.length - 1;
189
+ let group = -1;
190
+ while (lo <= hi) {
191
+ const mid = (lo + hi) >>> 1;
192
+ const k = keys[mid];
193
+ if (k === outerId) {
194
+ group = mid;
195
+ break;
196
+ }
197
+ if (k < outerId)
198
+ lo = mid + 1;
199
+ else
200
+ hi = mid - 1;
201
+ }
202
+ if (group === -1)
203
+ return 0;
204
+ let pLo = table.offsets[group];
205
+ let pHi = table.offsets[group + 1] - 1;
206
+ const values = table.values;
207
+ while (pLo <= pHi) {
208
+ const mid = (pLo + pHi) >>> 1;
209
+ const v = values[mid];
210
+ if (v === innerId)
211
+ return table.counts[mid];
212
+ if (v < innerId)
213
+ pLo = mid + 1;
214
+ else
215
+ pHi = mid - 1;
216
+ }
217
+ return 0;
218
+ }
219
+ /**
220
+ * Encodes unigrams, bigrams, and optional Bloom tail filters into an `ALX1` binary payload.
221
+ */
222
+ export function encodeBinaryLexicon(options) {
223
+ const blockSize = options.blockSize ?? 64;
224
+ const exactCountMax = options.exactCountMax ?? 80;
225
+ const countBuckets = options.countBuckets ?? 256;
226
+ const countMaxVal = options.countMaxVal ?? 3_000_000;
227
+ const capMax = options.capMax ?? 50; // 51 levels (0..50 -> step 0.02, exact on 0.45..0.75!)
228
+ // Collect exact alphabet from unigrams (sorted by UTF-16 code unit for deterministic encoding).
229
+ const charSet = new Set();
230
+ for (let i = 0; i < options.unigrams.length; i++) {
231
+ const form = options.unigrams[i].form;
232
+ for (let j = 0; j < form.length; j++) {
233
+ charSet.add(form[j]);
234
+ }
235
+ }
236
+ const alphabet = [...charSet].sort().join("");
237
+ if (alphabet.length > 254) {
238
+ throw new Error(`lexicon binary: alphabet too large (${alphabet.length} > 254)`);
239
+ }
240
+ const charToByte = new Map();
241
+ for (let i = 0; i < alphabet.length; i++) {
242
+ charToByte.set(alphabet[i], i + 1);
243
+ }
244
+ // Encode & sort unigrams by 1-byte alphabet code order so binary search matches code order directly.
245
+ const encoded = options.unigrams.map((u) => {
246
+ const b = new Uint8Array(u.form.length);
247
+ for (let i = 0; i < u.form.length; i++) {
248
+ b[i] = charToByte.get(u.form[i]);
249
+ }
250
+ return { form: u.form, bytes: b, count: u.count, capitalized: u.capitalized };
251
+ });
252
+ encoded.sort((a, b) => {
253
+ const m = Math.min(a.bytes.length, b.bytes.length);
254
+ for (let i = 0; i < m; i++) {
255
+ const diff = a.bytes[i] - b.bytes[i];
256
+ if (diff !== 0)
257
+ return diff;
258
+ }
259
+ return a.bytes.length - b.bytes.length;
260
+ });
261
+ const wordCount = encoded.length;
262
+ const idOf = new Map();
263
+ const prefixLens = new Uint8Array(wordCount);
264
+ const suffixLens = new Uint8Array(wordCount);
265
+ const counts = new Uint8Array(wordCount);
266
+ const caps = new Uint8Array(wordCount);
267
+ let totalChars = 0;
268
+ for (let i = 0; i < wordCount; i++) {
269
+ const cur = encoded[i];
270
+ idOf.set(cur.form, i);
271
+ let prefix = 0;
272
+ if (i % blockSize !== 0) {
273
+ const prev = encoded[i - 1].bytes;
274
+ const maxP = Math.min(prev.length, cur.bytes.length, 255);
275
+ while (prefix < maxP && prev[prefix] === cur.bytes[prefix]) {
276
+ prefix++;
277
+ }
278
+ }
279
+ const suffix = cur.bytes.length - prefix;
280
+ if (suffix > 255) {
281
+ throw new Error(`lexicon binary: word suffix exceeds 255 chars ("${cur.form}")`);
282
+ }
283
+ prefixLens[i] = prefix;
284
+ suffixLens[i] = suffix;
285
+ totalChars += suffix;
286
+ counts[i] = quantizeCount(cur.count, exactCountMax, countBuckets, countMaxVal);
287
+ caps[i] =
288
+ cur.capitalized <= 0 || cur.count <= 0
289
+ ? 0
290
+ : Math.min(capMax, Math.max(1, Math.round((capMax * cur.capitalized) / cur.count)));
291
+ }
292
+ const chars = new Uint8Array(totalChars);
293
+ let charOff = 0;
294
+ for (let i = 0; i < wordCount; i++) {
295
+ const b = encoded[i].bytes;
296
+ const p = prefixLens[i];
297
+ for (let j = p; j < b.length; j++) {
298
+ chars[charOff++] = b[j];
299
+ }
300
+ }
301
+ // Partition bigrams into byFirst and bySecond CSR tables.
302
+ const byFirstGroups = new Map();
303
+ const bySecondGroups = new Map();
304
+ for (let i = 0; i < options.bigrams.length; i++) {
305
+ const bg = options.bigrams[i];
306
+ const id1 = idOf.get(bg.first);
307
+ const id2 = idOf.get(bg.second);
308
+ if (id1 === undefined || id2 === undefined)
309
+ continue;
310
+ const qc = quantizeCount(bg.count, exactCountMax, countBuckets, countMaxVal);
311
+ if (bg.groupBySecond) {
312
+ let list = bySecondGroups.get(id2);
313
+ if (!list) {
314
+ list = [];
315
+ bySecondGroups.set(id2, list);
316
+ }
317
+ list.push([id1, qc]);
318
+ }
319
+ else {
320
+ let list = byFirstGroups.get(id1);
321
+ if (!list) {
322
+ list = [];
323
+ byFirstGroups.set(id1, list);
324
+ }
325
+ list.push([id2, qc]);
326
+ }
327
+ }
328
+ const csr1 = encodeCsrPartition(byFirstGroups);
329
+ const csr2 = encodeCsrPartition(bySecondGroups);
330
+ // Build Bloom filter tiers (ordered by descending returnCount so highest count matches first).
331
+ const sortedTiers = [...(options.bloomTiers ?? [])]
332
+ .filter((t) => t.words.length > 0)
333
+ .sort((a, b) => b.returnCount - a.returnCount);
334
+ const builtBlooms = sortedTiers.map((tier) => {
335
+ const byteLen = Math.max(8, Math.ceil((tier.words.length * tier.bitsPerItem) / 8));
336
+ const nBits = byteLen * 8;
337
+ const kHashes = Math.max(4, Math.min(20, Math.round(tier.bitsPerItem * Math.LN2)));
338
+ const bits = new Uint8Array(byteLen);
339
+ for (let i = 0; i < tier.words.length; i++) {
340
+ bloomAdd(bits, nBits, kHashes, tier.words[i]);
341
+ }
342
+ return {
343
+ returnCount: tier.returnCount,
344
+ kHashes,
345
+ wordCount: tier.words.length,
346
+ nBits,
347
+ bits,
348
+ };
349
+ });
350
+ const alphabetBytes = new TextEncoder().encode(alphabet);
351
+ // Header layout:
352
+ // 4 magic + 1 ver + 1 blockSize + 1 exactCountMax + 2 countBuckets + 4 countMaxVal + 1 capMax
353
+ // + 2 alphabetByteLen + alphabetBytes
354
+ // + 4 wordCount + 4 charsByteLen
355
+ // + 4*4 csr1 (groups, pairs, metaLen, innerLen)
356
+ // + 4*4 csr2 (groups, pairs, metaLen, innerLen)
357
+ // + 1 bloomCount + bloomCount * (1 returnCount + 1 kHashes + 4 wordCount + 4 byteLen)
358
+ const headerLen = 16 + alphabetBytes.byteLength + 8 + 16 + 16 + 1 + builtBlooms.length * 10;
359
+ const bodyParts = [
360
+ prefixLens,
361
+ suffixLens,
362
+ chars,
363
+ counts,
364
+ caps,
365
+ csr1.meta,
366
+ csr1.inner,
367
+ csr1.counts,
368
+ csr2.meta,
369
+ csr2.inner,
370
+ csr2.counts,
371
+ ...builtBlooms.map((b) => b.bits),
372
+ ];
373
+ const bodyLen = bodyParts.reduce((sum, part) => sum + part.byteLength, 0);
374
+ const out = new Uint8Array(headerLen + bodyLen);
375
+ const view = new DataView(out.buffer);
376
+ let off = 0;
377
+ out[off++] = MAGIC_0;
378
+ out[off++] = MAGIC_1;
379
+ out[off++] = MAGIC_2;
380
+ out[off++] = MAGIC_3;
381
+ out[off++] = FORMAT_VERSION;
382
+ out[off++] = blockSize;
383
+ out[off++] = exactCountMax;
384
+ view.setUint16(off, countBuckets, true);
385
+ off += 2;
386
+ view.setUint32(off, countMaxVal, true);
387
+ off += 4;
388
+ out[off++] = capMax;
389
+ view.setUint16(off, alphabetBytes.byteLength, true);
390
+ off += 2;
391
+ out.set(alphabetBytes, off);
392
+ off += alphabetBytes.byteLength;
393
+ view.setUint32(off, wordCount, true);
394
+ off += 4;
395
+ view.setUint32(off, chars.byteLength, true);
396
+ off += 4;
397
+ view.setUint32(off, csr1.groupCount, true);
398
+ off += 4;
399
+ view.setUint32(off, csr1.pairCount, true);
400
+ off += 4;
401
+ view.setUint32(off, csr1.meta.byteLength, true);
402
+ off += 4;
403
+ view.setUint32(off, csr1.inner.byteLength, true);
404
+ off += 4;
405
+ view.setUint32(off, csr2.groupCount, true);
406
+ off += 4;
407
+ view.setUint32(off, csr2.pairCount, true);
408
+ off += 4;
409
+ view.setUint32(off, csr2.meta.byteLength, true);
410
+ off += 4;
411
+ view.setUint32(off, csr2.inner.byteLength, true);
412
+ off += 4;
413
+ out[off++] = builtBlooms.length;
414
+ for (let i = 0; i < builtBlooms.length; i++) {
415
+ const b = builtBlooms[i];
416
+ out[off++] = b.returnCount;
417
+ out[off++] = b.kHashes;
418
+ view.setUint32(off, b.wordCount, true);
419
+ off += 4;
420
+ view.setUint32(off, b.bits.byteLength, true);
421
+ off += 4;
422
+ }
423
+ for (let i = 0; i < bodyParts.length; i++) {
424
+ const part = bodyParts[i];
425
+ out.set(part, off);
426
+ off += part.byteLength;
427
+ }
428
+ return out;
429
+ }
430
+ /**
431
+ * Memory-compact, zero-string-allocation runtime lexicon backed directly by `ALX1` typed arrays.
432
+ */
433
+ export class BinaryLexicon {
434
+ blockSize;
435
+ wordCount;
436
+ totalFormCount;
437
+ totalPairCount;
438
+ capMax;
439
+ quantTable;
440
+ alphabetSize;
441
+ charToByte;
442
+ byteToChar;
443
+ prefixLens;
444
+ suffixLens;
445
+ chars;
446
+ counts;
447
+ caps;
448
+ blkCharOff;
449
+ bktLo;
450
+ bktHi;
451
+ byFirst;
452
+ bySecond;
453
+ blooms;
454
+ queryBuf = new Uint8Array(MAX_WORD_LEN);
455
+ lastForm = "";
456
+ lastId = -2;
457
+ constructor(bytes) {
458
+ if (bytes.byteLength < 57 ||
459
+ bytes[0] !== MAGIC_0 ||
460
+ bytes[1] !== MAGIC_1 ||
461
+ bytes[2] !== MAGIC_2 ||
462
+ bytes[3] !== MAGIC_3) {
463
+ throw new Error("autr: Geçersiz sözlük ikili başlığı (ALX1 bekleniyordu).");
464
+ }
465
+ const version = bytes[4];
466
+ if (version !== FORMAT_VERSION) {
467
+ throw new Error(`autr: Desteklenmeyen sözlük biçim sürümü: ${version}.`);
468
+ }
469
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
470
+ let off = 5;
471
+ this.blockSize = bytes[off++];
472
+ const exactCountMax = bytes[off++];
473
+ const countBuckets = view.getUint16(off, true);
474
+ off += 2;
475
+ const countMaxVal = view.getUint32(off, true);
476
+ off += 4;
477
+ this.capMax = bytes[off++];
478
+ this.quantTable = buildQuantTable(exactCountMax, countBuckets, countMaxVal);
479
+ const alphabetByteLen = view.getUint16(off, true);
480
+ off += 2;
481
+ const alphabet = new TextDecoder("utf-8").decode(bytes.subarray(off, off + alphabetByteLen));
482
+ off += alphabetByteLen;
483
+ this.alphabetSize = alphabet.length + 1;
484
+ this.charToByte = new Uint8Array(65536);
485
+ this.byteToChar = new Array(this.alphabetSize).fill("");
486
+ for (let i = 0; i < alphabet.length; i++) {
487
+ const ch = alphabet[i];
488
+ this.charToByte[ch.charCodeAt(0)] = i + 1;
489
+ this.byteToChar[i + 1] = ch;
490
+ }
491
+ this.wordCount = view.getUint32(off, true);
492
+ off += 4;
493
+ const charsByteLen = view.getUint32(off, true);
494
+ off += 4;
495
+ const csr1Groups = view.getUint32(off, true);
496
+ off += 4;
497
+ const csr1Pairs = view.getUint32(off, true);
498
+ off += 4;
499
+ const csr1MetaLen = view.getUint32(off, true);
500
+ off += 4;
501
+ const csr1InnerLen = view.getUint32(off, true);
502
+ off += 4;
503
+ const csr2Groups = view.getUint32(off, true);
504
+ off += 4;
505
+ const csr2Pairs = view.getUint32(off, true);
506
+ off += 4;
507
+ const csr2MetaLen = view.getUint32(off, true);
508
+ off += 4;
509
+ const csr2InnerLen = view.getUint32(off, true);
510
+ off += 4;
511
+ const bloomCount = bytes[off++];
512
+ const bloomMeta = [];
513
+ for (let i = 0; i < bloomCount; i++) {
514
+ const returnCount = bytes[off++];
515
+ const kHashes = bytes[off++];
516
+ const bloomWords = view.getUint32(off, true);
517
+ off += 4;
518
+ const byteLen = view.getUint32(off, true);
519
+ off += 4;
520
+ bloomMeta.push({ returnCount, kHashes, wordCount: bloomWords, byteLen });
521
+ }
522
+ const n = this.wordCount;
523
+ this.prefixLens = bytes.subarray(off, off + n);
524
+ off += n;
525
+ this.suffixLens = bytes.subarray(off, off + n);
526
+ off += n;
527
+ this.chars = bytes.subarray(off, off + charsByteLen);
528
+ off += charsByteLen;
529
+ this.counts = bytes.subarray(off, off + n);
530
+ off += n;
531
+ this.caps = bytes.subarray(off, off + n);
532
+ off += n;
533
+ const d1 = decodeCsrPartition(bytes, off, csr1Groups, csr1Pairs, csr1MetaLen, csr1InnerLen);
534
+ this.byFirst = d1.table;
535
+ off = d1.nextOffset;
536
+ const d2 = decodeCsrPartition(bytes, off, csr2Groups, csr2Pairs, csr2MetaLen, csr2InnerLen);
537
+ this.bySecond = d2.table;
538
+ off = d2.nextOffset;
539
+ const blooms = [];
540
+ let bloomWordTotal = 0;
541
+ for (let i = 0; i < bloomMeta.length; i++) {
542
+ const m = bloomMeta[i];
543
+ const bits = bytes.subarray(off, off + m.byteLen);
544
+ off += m.byteLen;
545
+ blooms.push({
546
+ returnCount: m.returnCount,
547
+ kHashes: m.kHashes,
548
+ wordCount: m.wordCount,
549
+ nBits: m.byteLen * 8,
550
+ bits,
551
+ });
552
+ bloomWordTotal += m.wordCount;
553
+ }
554
+ this.blooms = blooms;
555
+ this.totalFormCount = n + bloomWordTotal;
556
+ this.totalPairCount = csr1Pairs + csr2Pairs;
557
+ // Build block offsets & 2-byte prefix bucket table in a single fast pass (~0.7 ms).
558
+ const blkSize = this.blockSize;
559
+ const nBlocks = n === 0 ? 0 : Math.ceil(n / blkSize);
560
+ this.blkCharOff = new Uint32Array(nBlocks);
561
+ const cSize = this.alphabetSize;
562
+ const totalBuckets = cSize * cSize;
563
+ const bucketStart = new Int32Array(totalBuckets).fill(-1);
564
+ const bucketEnd = new Int32Array(totalBuckets).fill(-1);
565
+ let charPos = 0;
566
+ const sArr = this.suffixLens;
567
+ const cArr = this.chars;
568
+ for (let blk = 0; blk < nBlocks; blk++) {
569
+ this.blkCharOff[blk] = charPos;
570
+ const base = blk * blkSize;
571
+ const end = base + blkSize < n ? base + blkSize : n;
572
+ const len0 = sArr[base];
573
+ const b0 = len0 > 0 ? cArr[charPos] : 0;
574
+ const b1 = len0 > 1 ? cArr[charPos + 1] : 0;
575
+ const bkt = b0 * cSize + b1;
576
+ if (bucketStart[bkt] === -1)
577
+ bucketStart[bkt] = blk;
578
+ bucketEnd[bkt] = blk + 1;
579
+ for (let i = base; i < end; i++) {
580
+ charPos += sArr[i];
581
+ }
582
+ }
583
+ this.bktLo = new Int32Array(totalBuckets);
584
+ this.bktHi = new Int32Array(totalBuckets);
585
+ let lastSeen = 0;
586
+ for (let bkt = 0; bkt < totalBuckets; bkt++) {
587
+ if (bucketStart[bkt] !== -1) {
588
+ this.bktLo[bkt] = bucketStart[bkt] > 0 ? bucketStart[bkt] - 1 : 0;
589
+ this.bktHi[bkt] = bucketEnd[bkt];
590
+ lastSeen = bucketEnd[bkt] - 1;
591
+ }
592
+ else {
593
+ this.bktLo[bkt] = lastSeen;
594
+ this.bktHi[bkt] = lastSeen + 1 < nBlocks ? lastSeen + 1 : nBlocks;
595
+ }
596
+ }
597
+ }
598
+ get size() {
599
+ return this.totalFormCount;
600
+ }
601
+ get exactSize() {
602
+ return this.wordCount;
603
+ }
604
+ get pairCount() {
605
+ return this.totalPairCount;
606
+ }
607
+ findExactId(form) {
608
+ if (form === this.lastForm && this.lastId !== -2)
609
+ return this.lastId;
610
+ const qLen = form.length;
611
+ if (qLen === 0 || qLen > MAX_WORD_LEN || this.wordCount === 0) {
612
+ this.lastForm = form;
613
+ this.lastId = -1;
614
+ return -1;
615
+ }
616
+ const qBuf = this.queryBuf;
617
+ const charMap = this.charToByte;
618
+ for (let i = 0; i < qLen; i++) {
619
+ const code = charMap[form.charCodeAt(i)];
620
+ if (code === 0) {
621
+ this.lastForm = form;
622
+ this.lastId = -1;
623
+ return -1;
624
+ }
625
+ qBuf[i] = code;
626
+ }
627
+ const b0 = qBuf[0];
628
+ const b1 = qLen > 1 ? qBuf[1] : 0;
629
+ const bkt = b0 * this.alphabetSize + b1;
630
+ let lo = this.bktLo[bkt];
631
+ let hi = this.bktHi[bkt] - 1;
632
+ const blkSize = this.blockSize;
633
+ const blkOff = this.blkCharOff;
634
+ const sArr = this.suffixLens;
635
+ const cArr = this.chars;
636
+ let blk = lo;
637
+ while (lo <= hi) {
638
+ const mid = (lo + hi) >>> 1;
639
+ const idx = mid * blkSize;
640
+ const cOff = blkOff[mid];
641
+ const hLen = sArr[idx];
642
+ const m = hLen < qLen ? hLen : qLen;
643
+ let cmp = 0;
644
+ for (let j = 0; j < m; j++) {
645
+ const diff = cArr[cOff + j] - qBuf[j];
646
+ if (diff !== 0) {
647
+ cmp = diff;
648
+ break;
649
+ }
650
+ }
651
+ if (cmp === 0)
652
+ cmp = hLen - qLen;
653
+ if (cmp === 0) {
654
+ this.lastForm = form;
655
+ this.lastId = idx;
656
+ return idx;
657
+ }
658
+ if (cmp < 0) {
659
+ blk = mid;
660
+ lo = mid + 1;
661
+ }
662
+ else {
663
+ hi = mid - 1;
664
+ }
665
+ }
666
+ const base = blk * blkSize;
667
+ const end = base + blkSize < this.wordCount ? base + blkSize : this.wordCount;
668
+ let pos = blkOff[blk];
669
+ const len0 = sArr[base];
670
+ let matched = 0;
671
+ {
672
+ const m = len0 < qLen ? len0 : qLen;
673
+ while (matched < m && cArr[pos + matched] === qBuf[matched])
674
+ matched++;
675
+ if (matched === len0 && len0 === qLen) {
676
+ this.lastForm = form;
677
+ this.lastId = base;
678
+ return base;
679
+ }
680
+ // If entry 0 is already > query, query cannot exist in this block.
681
+ if (matched < m) {
682
+ if (cArr[pos + matched] > qBuf[matched]) {
683
+ this.lastForm = form;
684
+ this.lastId = -1;
685
+ return -1;
686
+ }
687
+ }
688
+ else if (len0 > qLen) {
689
+ this.lastForm = form;
690
+ this.lastId = -1;
691
+ return -1;
692
+ }
693
+ }
694
+ pos += len0;
695
+ const pArr = this.prefixLens;
696
+ for (let i = base + 1; i < end; i++) {
697
+ const p = pArr[i];
698
+ const s = sArr[i];
699
+ if (p < matched)
700
+ break;
701
+ if (p === matched) {
702
+ let j = 0;
703
+ const rem = qLen - p;
704
+ const m = s < rem ? s : rem;
705
+ while (j < m && cArr[pos + j] === qBuf[p + j])
706
+ j++;
707
+ matched = p + j;
708
+ if (j === m) {
709
+ if (s === rem) {
710
+ this.lastForm = form;
711
+ this.lastId = i;
712
+ return i;
713
+ }
714
+ if (s > rem)
715
+ break;
716
+ }
717
+ else if (cArr[pos + j] > qBuf[p + j]) {
718
+ break;
719
+ }
720
+ }
721
+ pos += s;
722
+ }
723
+ this.lastForm = form;
724
+ this.lastId = -1;
725
+ return -1;
726
+ }
727
+ count(form) {
728
+ const id = this.findExactId(form);
729
+ if (id !== -1)
730
+ return this.quantTable[this.counts[id]];
731
+ // Apostrophe forms are never stored in Bloom tail filters; skip probing them to prevent phantom matches.
732
+ if (form.includes("'"))
733
+ return 0;
734
+ const blooms = this.blooms;
735
+ for (let i = 0; i < blooms.length; i++) {
736
+ const b = blooms[i];
737
+ if (bloomHas(b.bits, b.nBits, b.kHashes, form))
738
+ return b.returnCount;
739
+ }
740
+ return 0;
741
+ }
742
+ /** Returns the exact-table count only (skipping protection-only Bloom filters). */
743
+ exactCount(form) {
744
+ const id = this.findExactId(form);
745
+ return id !== -1 ? this.quantTable[this.counts[id]] : 0;
746
+ }
747
+ capitalShare(form) {
748
+ const id = this.findExactId(form);
749
+ if (id === -1 || this.capMax === 0)
750
+ return 0;
751
+ return this.caps[id] / this.capMax;
752
+ }
753
+ pair(first, second) {
754
+ const id2 = this.findExactId(second);
755
+ if (id2 === -1)
756
+ return 0;
757
+ const id1 = this.findExactId(first);
758
+ if (id1 === -1)
759
+ return 0;
760
+ const q2 = lookupCsr(this.bySecond, id2, id1);
761
+ if (q2 !== 0)
762
+ return this.quantTable[q2];
763
+ const q1 = lookupCsr(this.byFirst, id1, id2);
764
+ return q1 !== 0 ? this.quantTable[q1] : 0;
765
+ }
766
+ /** Reconstructs the exact-table entries as TSV (for debugging/diagnostics). */
767
+ toTsv() {
768
+ const words = new Array(this.wordCount);
769
+ const cur = new Uint8Array(MAX_WORD_LEN);
770
+ let charPos = 0;
771
+ const uLines = [];
772
+ for (let i = 0; i < this.wordCount; i++) {
773
+ const p = this.prefixLens[i];
774
+ const s = this.suffixLens[i];
775
+ for (let j = 0; j < s; j++)
776
+ cur[p + j] = this.chars[charPos++];
777
+ const len = p + s;
778
+ let w = "";
779
+ for (let j = 0; j < len; j++)
780
+ w += this.byteToChar[cur[j]];
781
+ words[i] = w;
782
+ const c = this.quantTable[this.counts[i]];
783
+ const cp = this.capMax === 0 ? 0 : Math.round((c * this.caps[i]) / this.capMax);
784
+ uLines.push(`${w}\t${c}\t${cp}`);
785
+ }
786
+ const bLines = [];
787
+ for (let g = 0; g < this.byFirst.keys.length; g++) {
788
+ const w1 = words[this.byFirst.keys[g]];
789
+ const start = this.byFirst.offsets[g];
790
+ const end = this.byFirst.offsets[g + 1];
791
+ for (let p = start; p < end; p++) {
792
+ bLines.push(`${w1} ${words[this.byFirst.values[p]]}\t${this.quantTable[this.byFirst.counts[p]]}`);
793
+ }
794
+ }
795
+ for (let g = 0; g < this.bySecond.keys.length; g++) {
796
+ const w2 = words[this.bySecond.keys[g]];
797
+ const start = this.bySecond.offsets[g];
798
+ const end = this.bySecond.offsets[g + 1];
799
+ for (let p = start; p < end; p++) {
800
+ bLines.push(`${words[this.bySecond.values[p]]} ${w2}\t${this.quantTable[this.bySecond.counts[p]]}`);
801
+ }
802
+ }
803
+ return { unigrams: uLines.join("\n"), bigrams: bLines.join("\n") };
804
+ }
805
+ }