@mailwoman/resolver-wof-sqlite 12.0.0 → 12.2.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 (173) hide show
  1. package/lib/address/keys/build.ts +35 -0
  2. package/lib/address/keys/lookup.ts +318 -6
  3. package/lib/address/keys/open.ts +1 -0
  4. package/lib/address/keys/point-lookup.ts +61 -2
  5. package/lib/address/keys/schema.ts +37 -0
  6. package/lib/address/number-forms.ts +32 -13
  7. package/lib/address/point/interpolation.ts +23 -6
  8. package/lib/address/point/schema.ts +198 -2
  9. package/lib/address/point/scope-search.ts +179 -0
  10. package/lib/address/point.ts +365 -32
  11. package/lib/build/candidate.ts +36 -9
  12. package/lib/candidate/ancestors/sidecar.ts +73 -4
  13. package/lib/candidate/del1.ts +218 -0
  14. package/lib/candidate/lookup.ts +159 -100
  15. package/lib/candidate/schema.ts +14 -2
  16. package/lib/fst/binary-matcher.ts +9 -1
  17. package/lib/fst/builder.ts +7 -0
  18. package/lib/fst/del1-sidecar.ts +782 -0
  19. package/lib/fst/deserialize-web.ts +14 -2
  20. package/lib/fst/matcher.ts +7 -1
  21. package/lib/fst/types.ts +8 -0
  22. package/lib/fst.ts +1 -0
  23. package/lib/index.ts +22 -2
  24. package/lib/labels/street/canonical.ts +333 -0
  25. package/lib/labels/street/centroid/schema.ts +23 -1
  26. package/lib/labels/street/interpolation.ts +32 -6
  27. package/lib/labels/street/morphology/fst/builder.ts +13 -0
  28. package/lib/labels/street/morphology/fst/loader.ts +32 -2
  29. package/lib/labels/street/normalize.ts +153 -4
  30. package/lib/labels/street.ts +1 -0
  31. package/lib/landmark.ts +43 -2
  32. package/lib/lookup/types.ts +0 -6
  33. package/lib/poi/lookup.ts +148 -52
  34. package/lib/poi/schema.ts +9 -1
  35. package/lib/schema/overture-match.ts +2 -1
  36. package/lib/weights/overlay-linker.ts +6 -2
  37. package/out/address/keys/build.d.ts.map +1 -1
  38. package/out/address/keys/build.js +28 -1
  39. package/out/address/keys/build.js.map +1 -1
  40. package/out/address/keys/lookup.d.ts +42 -0
  41. package/out/address/keys/lookup.d.ts.map +1 -1
  42. package/out/address/keys/lookup.js +182 -6
  43. package/out/address/keys/lookup.js.map +1 -1
  44. package/out/address/keys/open.d.ts.map +1 -1
  45. package/out/address/keys/open.js +1 -0
  46. package/out/address/keys/open.js.map +1 -1
  47. package/out/address/keys/point-lookup.d.ts +6 -1
  48. package/out/address/keys/point-lookup.d.ts.map +1 -1
  49. package/out/address/keys/point-lookup.js +43 -1
  50. package/out/address/keys/point-lookup.js.map +1 -1
  51. package/out/address/keys/schema.d.ts +21 -0
  52. package/out/address/keys/schema.d.ts.map +1 -1
  53. package/out/address/keys/schema.js +18 -0
  54. package/out/address/keys/schema.js.map +1 -1
  55. package/out/address/number-forms.d.ts +10 -1
  56. package/out/address/number-forms.d.ts.map +1 -1
  57. package/out/address/number-forms.js +20 -11
  58. package/out/address/number-forms.js.map +1 -1
  59. package/out/address/point/interpolation.d.ts.map +1 -1
  60. package/out/address/point/interpolation.js +15 -5
  61. package/out/address/point/interpolation.js.map +1 -1
  62. package/out/address/point/schema.d.ts +45 -2
  63. package/out/address/point/schema.d.ts.map +1 -1
  64. package/out/address/point/schema.js +129 -0
  65. package/out/address/point/schema.js.map +1 -1
  66. package/out/address/point/scope-search.d.ts +77 -0
  67. package/out/address/point/scope-search.d.ts.map +1 -0
  68. package/out/address/point/scope-search.js +107 -0
  69. package/out/address/point/scope-search.js.map +1 -0
  70. package/out/address/point.d.ts +24 -1
  71. package/out/address/point.d.ts.map +1 -1
  72. package/out/address/point.js +231 -30
  73. package/out/address/point.js.map +1 -1
  74. package/out/build/candidate.d.ts +8 -0
  75. package/out/build/candidate.d.ts.map +1 -1
  76. package/out/build/candidate.js +17 -7
  77. package/out/build/candidate.js.map +1 -1
  78. package/out/candidate/ancestors/sidecar.d.ts +7 -3
  79. package/out/candidate/ancestors/sidecar.d.ts.map +1 -1
  80. package/out/candidate/ancestors/sidecar.js +56 -4
  81. package/out/candidate/ancestors/sidecar.js.map +1 -1
  82. package/out/candidate/del1.d.ts +61 -0
  83. package/out/candidate/del1.d.ts.map +1 -0
  84. package/out/candidate/del1.js +158 -0
  85. package/out/candidate/del1.js.map +1 -0
  86. package/out/candidate/lookup.d.ts +2 -14
  87. package/out/candidate/lookup.d.ts.map +1 -1
  88. package/out/candidate/lookup.js +122 -84
  89. package/out/candidate/lookup.js.map +1 -1
  90. package/out/candidate/schema.d.ts +8 -2
  91. package/out/candidate/schema.d.ts.map +1 -1
  92. package/out/candidate/schema.js +8 -2
  93. package/out/candidate/schema.js.map +1 -1
  94. package/out/fst/binary-matcher.d.ts +7 -1
  95. package/out/fst/binary-matcher.d.ts.map +1 -1
  96. package/out/fst/binary-matcher.js +7 -1
  97. package/out/fst/binary-matcher.js.map +1 -1
  98. package/out/fst/builder.d.ts +2 -0
  99. package/out/fst/builder.d.ts.map +1 -1
  100. package/out/fst/builder.js +5 -0
  101. package/out/fst/builder.js.map +1 -1
  102. package/out/fst/del1-sidecar.d.ts +158 -0
  103. package/out/fst/del1-sidecar.d.ts.map +1 -0
  104. package/out/fst/del1-sidecar.js +581 -0
  105. package/out/fst/del1-sidecar.js.map +1 -0
  106. package/out/fst/deserialize-web.d.ts +3 -1
  107. package/out/fst/deserialize-web.d.ts.map +1 -1
  108. package/out/fst/deserialize-web.js +9 -2
  109. package/out/fst/deserialize-web.js.map +1 -1
  110. package/out/fst/matcher.d.ts +6 -1
  111. package/out/fst/matcher.d.ts.map +1 -1
  112. package/out/fst/matcher.js +6 -1
  113. package/out/fst/matcher.js.map +1 -1
  114. package/out/fst/types.d.ts +7 -0
  115. package/out/fst/types.d.ts.map +1 -1
  116. package/out/fst.d.ts +1 -0
  117. package/out/fst.d.ts.map +1 -1
  118. package/out/fst.js +1 -0
  119. package/out/fst.js.map +1 -1
  120. package/out/index.d.ts +4 -3
  121. package/out/index.d.ts.map +1 -1
  122. package/out/index.js +3 -2
  123. package/out/index.js.map +1 -1
  124. package/out/labels/street/canonical.d.ts +68 -0
  125. package/out/labels/street/canonical.d.ts.map +1 -0
  126. package/out/labels/street/canonical.js +234 -0
  127. package/out/labels/street/canonical.js.map +1 -0
  128. package/out/labels/street/centroid/schema.d.ts +10 -1
  129. package/out/labels/street/centroid/schema.d.ts.map +1 -1
  130. package/out/labels/street/centroid/schema.js +12 -0
  131. package/out/labels/street/centroid/schema.js.map +1 -1
  132. package/out/labels/street/interpolation.d.ts +9 -1
  133. package/out/labels/street/interpolation.d.ts.map +1 -1
  134. package/out/labels/street/interpolation.js +8 -5
  135. package/out/labels/street/interpolation.js.map +1 -1
  136. package/out/labels/street/morphology/fst/builder.d.ts +8 -0
  137. package/out/labels/street/morphology/fst/builder.d.ts.map +1 -1
  138. package/out/labels/street/morphology/fst/builder.js +5 -0
  139. package/out/labels/street/morphology/fst/builder.js.map +1 -1
  140. package/out/labels/street/morphology/fst/loader.d.ts +12 -0
  141. package/out/labels/street/morphology/fst/loader.d.ts.map +1 -1
  142. package/out/labels/street/morphology/fst/loader.js +18 -2
  143. package/out/labels/street/morphology/fst/loader.js.map +1 -1
  144. package/out/labels/street/normalize.d.ts +8 -0
  145. package/out/labels/street/normalize.d.ts.map +1 -1
  146. package/out/labels/street/normalize.js +138 -4
  147. package/out/labels/street/normalize.js.map +1 -1
  148. package/out/labels/street.d.ts +1 -0
  149. package/out/labels/street.d.ts.map +1 -1
  150. package/out/labels/street.js +1 -0
  151. package/out/labels/street.js.map +1 -1
  152. package/out/landmark.d.ts +8 -0
  153. package/out/landmark.d.ts.map +1 -1
  154. package/out/landmark.js +25 -2
  155. package/out/landmark.js.map +1 -1
  156. package/out/lookup/types.d.ts +0 -5
  157. package/out/lookup/types.d.ts.map +1 -1
  158. package/out/poi/lookup.d.ts +9 -1
  159. package/out/poi/lookup.d.ts.map +1 -1
  160. package/out/poi/lookup.js +111 -53
  161. package/out/poi/lookup.js.map +1 -1
  162. package/out/poi/schema.d.ts +7 -2
  163. package/out/poi/schema.d.ts.map +1 -1
  164. package/out/poi/schema.js +3 -0
  165. package/out/poi/schema.js.map +1 -1
  166. package/out/schema/overture-match.d.ts +2 -1
  167. package/out/schema/overture-match.d.ts.map +1 -1
  168. package/out/schema/overture-match.js.map +1 -1
  169. package/out/weights/overlay-linker.d.ts +1 -1
  170. package/out/weights/overlay-linker.d.ts.map +1 -1
  171. package/out/weights/overlay-linker.js +5 -1
  172. package/out/weights/overlay-linker.js.map +1 -1
  173. package/package.json +12 -12
@@ -0,0 +1,782 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * Compact binary 1-delete token sidecar (`FD1\0` v1) for decode-time FST fuzzy lookup.
6
+ *
7
+ * `FST\0` v6 hashes whole normalized tokens, so a character edit-distance walk
8
+ * doesn't run against the trie directly.
9
+ * This sidecar indexes distinct normalized non-numeric tokens from high-referential
10
+ * FST entries into a sorted table of 32-bit FNV-1a 1-deletion hash buckets.
11
+ *
12
+ * Because every candidate token retrieved from a bucket is verified with exact code-point
13
+ * Damerau-Levenshtein distance `<= 1`, a rare hash collision never produces a false
14
+ * positive, and omitting delete-key strings from disk keeps the sidecar around 0.6
15
+ * MiB for `fst-en-us.bin` and under 100 KiB for `fst-street-morphology.bin`.
16
+ *
17
+ * Binary layout (little-endian, platform-free):
18
+ * - Header (32 bytes): magic `FD1\0`, version u16 (1), flags u16 (bit 0 = u16 postings),
19
+ * tokenCount u32, tokenStringBytes u32, bucketCount u32, postingCount u32,
20
+ * minTokenLength u16, maxTokenLength u16, maxBucketSize u16, reserved u16.
21
+ * - Token string table: `(tokenCount + 1)` u32 offsets (final sentinel) followed by UTF-8 bytes.
22
+ * - Delete-bucket hashes: `bucketCount` u32 FNV-1a hashes sorted strictly ascending.
23
+ * - Delete-bucket counts: `bucketCount` u8 posting counts (`1..maxBucketSize`).
24
+ * - Postings: `postingCount` u16 token IDs when flag bit 0 is set, else u32 token IDs.
25
+ */
26
+
27
+ import { hashFNV1a } from "@mailwoman/core/coarse-placer/fnv-hash"
28
+
29
+ import { FSTMatcher } from "#fst/matcher"
30
+ import type { FSTContinuation, PlaceEntry } from "#fst/types"
31
+
32
+ /**
33
+ * File magic `"FD1\0"` as bytes.
34
+ *
35
+ * @public
36
+ */
37
+ export const DEL1_MAGIC_BYTES: readonly number[] = [0x46, 0x44, 0x31, 0x00]
38
+
39
+ /**
40
+ * Binary format version written and accepted by this module.
41
+ *
42
+ * @public
43
+ */
44
+ export const DEL1_FORMAT_VERSION = 1
45
+
46
+ /**
47
+ * Fixed binary header size in bytes.
48
+ *
49
+ * @public
50
+ */
51
+ export const DEL1_HEADER_SIZE = 32
52
+
53
+ /**
54
+ * Header flag bit 0: postings store u16 token IDs because `tokenCount <= 65,535`.
55
+ */
56
+ const DEL1_FLAG_U16_POSTINGS = 1
57
+
58
+ const MAX_U16_TOKEN_COUNT = 0xff_ff
59
+ const MAX_U8_BUCKET_SIZE = 0xff
60
+ const EMPTY_SLOT = -1
61
+
62
+ /**
63
+ * Default minimum referential score for indexing an FST token.
64
+ *
65
+ * @public
66
+ */
67
+ export const DEFAULT_DEL1_MIN_REFERENTIAL = 0.2
68
+
69
+ /**
70
+ * Default minimum token length (in Unicode code points) for indexing.
71
+ *
72
+ * @public
73
+ */
74
+ export const DEFAULT_DEL1_MIN_TOKEN_LENGTH = 5
75
+
76
+ /**
77
+ * Default maximum token length (in Unicode code points) for indexing.
78
+ *
79
+ * @public
80
+ */
81
+ export const DEFAULT_DEL1_MAX_TOKEN_LENGTH = 40
82
+
83
+ /**
84
+ * Default maximum number of canonical token IDs retained per 1-delete hash bucket.
85
+ *
86
+ * @public
87
+ */
88
+ export const DEFAULT_DEL1_MAX_BUCKET_SIZE = 16
89
+
90
+ const LETTER_RE = /\p{L}/u
91
+ const DIGIT_RE = /\p{N}/u
92
+
93
+ /**
94
+ * Structural FST graph surface accepted by {@link buildFSTDel1Sidecar}.
95
+ *
96
+ * Satisfied by both {@link FSTMatcher} and {@link BinaryFSTMatcher}.
97
+ *
98
+ * @public
99
+ */
100
+ export interface FSTGraphSource {
101
+ readonly stateCount: number
102
+ continuations(stateID: number): FSTContinuation[]
103
+ accepting(stateID: number): PlaceEntry[]
104
+ }
105
+
106
+ /**
107
+ * Options controlling which FST tokens enter a 1-delete sidecar.
108
+ *
109
+ * @public
110
+ */
111
+ export interface BuildFSTDel1SidecarOpts {
112
+ /**
113
+ * Minimum subtree referential score required for a token to be indexed.
114
+ *
115
+ * @defaultValue `0.2`
116
+ */
117
+ minReferential?: number
118
+ /**
119
+ * Minimum code-point length of an indexed token.
120
+ *
121
+ * @defaultValue `5`
122
+ */
123
+ minTokenLength?: number
124
+ /**
125
+ * Maximum code-point length of an indexed token.
126
+ *
127
+ * @defaultValue `40`
128
+ */
129
+ maxTokenLength?: number
130
+ /**
131
+ * Maximum number of canonical token IDs stored per 1-delete hash bucket (clamped to `1..255`).
132
+ *
133
+ * Higher-referential tokens are retained first when a bucket reaches the cap.
134
+ *
135
+ * @defaultValue `16`
136
+ */
137
+ maxBucketSize?: number
138
+ }
139
+
140
+ /**
141
+ * Summary counts for a built 1-delete token sidecar.
142
+ *
143
+ * @public
144
+ */
145
+ export interface FSTDel1SidecarStats {
146
+ tokenCount: number
147
+ bucketCount: number
148
+ postingCount: number
149
+ byteLength: number
150
+ minTokenLength: number
151
+ maxTokenLength: number
152
+ maxBucketSize: number
153
+ }
154
+
155
+ /**
156
+ * Result of {@link buildFSTDel1Sidecar}.
157
+ *
158
+ * @public
159
+ */
160
+ export interface BuiltFSTDel1Sidecar {
161
+ bytes: Uint8Array
162
+ stats: FSTDel1SidecarStats
163
+ }
164
+
165
+ /**
166
+ * Returns the conventional sibling sidecar path for an FST artifact:
167
+ * `fst-en-us.bin` maps to `fst-en-us.del1.bin`.
168
+ *
169
+ * Uses pure string manipulation so this module stays browser-safe with zero `node:path` imports.
170
+ *
171
+ * @public
172
+ */
173
+ export function del1SidecarPathFor(fstPath: string | { toString(): string }): string {
174
+ const raw = typeof fstPath === "string" ? fstPath : fstPath.toString()
175
+
176
+ return raw.endsWith(".bin") ? `${raw.slice(0, -4)}.del1.bin` : `${raw}.del1.bin`
177
+ }
178
+
179
+ function isEligibleToken(token: string, minLength: number, maxLength: number): boolean {
180
+ if (!token || DIGIT_RE.test(token) || !LETTER_RE.test(token)) return false
181
+ const cpLength = [...token].length
182
+
183
+ return cpLength >= minLength && cpLength <= maxLength
184
+ }
185
+
186
+ function tableCapacity(count: number): number {
187
+ let capacity = 16
188
+
189
+ while (capacity < count * 2) {
190
+ capacity *= 2
191
+ }
192
+
193
+ return capacity
194
+ }
195
+
196
+ /**
197
+ * Checks whether two code-point arrays have Damerau-Levenshtein distance `<= 1`
198
+ * (identity, 1 deletion, 1 insertion, 1 substitution, or 1 adjacent transposition).
199
+ */
200
+ function isWithinOneEditCodePoints(a: readonly string[], b: readonly string[]): boolean {
201
+ const la = a.length
202
+ const lb = b.length
203
+
204
+ if (Math.abs(la - lb) > 1) return false
205
+
206
+ const minLen = Math.min(la, lb)
207
+ let i = 0
208
+
209
+ while (i < minLen && a[i] === b[i]) {
210
+ i++
211
+ }
212
+
213
+ if (i === minLen) return true
214
+
215
+ if (la === lb) {
216
+ // Single substitution at position `i`.
217
+ let subMatches = true
218
+
219
+ for (let j = i + 1; j < la; j++) {
220
+ if (a[j] !== b[j]) {
221
+ subMatches = false
222
+
223
+ break
224
+ }
225
+ }
226
+
227
+ if (subMatches) return true
228
+
229
+ // Single adjacent transposition at `(i, i + 1)`.
230
+ if (i + 1 < la && a[i] === b[i + 1] && a[i + 1] === b[i]) {
231
+ for (let j = i + 2; j < la; j++) {
232
+ if (a[j] !== b[j]) return false
233
+ }
234
+
235
+ return true
236
+ }
237
+
238
+ return false
239
+ }
240
+
241
+ if (la > lb) {
242
+ for (let j = i; j < lb; j++) {
243
+ if (a[j + 1] !== b[j]) return false
244
+ }
245
+
246
+ return true
247
+ }
248
+
249
+ for (let j = i; j < la; j++) {
250
+ if (a[j] !== b[j + 1]) return false
251
+ }
252
+
253
+ return true
254
+ }
255
+
256
+ /**
257
+ * Computes the maximum referential score reachable from each state in `source`
258
+ * and collects distinct eligible tokens with their highest reachable referential score.
259
+ */
260
+ function collectEligibleTokens(
261
+ source: FSTGraphSource,
262
+ minReferential: number,
263
+ minTokenLength: number,
264
+ maxTokenLength: number
265
+ ): Map<string, number> {
266
+ const stateCount = source.stateCount
267
+
268
+ if (stateCount === 0) return new Map()
269
+
270
+ const nodes = source instanceof FSTMatcher ? source.toNodes() : null
271
+ const maxRef = new Float32Array(stateCount).fill(-1)
272
+ const visited = new Uint8Array(stateCount)
273
+ const order: number[] = []
274
+ const stack: number[] = [0]
275
+ visited[0] = 1
276
+
277
+ const edgesCache: FSTContinuation[][] | null = nodes ? null : new Array(stateCount)
278
+
279
+ while (stack.length) {
280
+ const u = stack.pop()!
281
+ order.push(u)
282
+
283
+ if (nodes) {
284
+ for (const target of nodes[u]!.edges.values()) {
285
+ if (target < stateCount && !visited[target]) {
286
+ visited[target] = 1
287
+ stack.push(target)
288
+ }
289
+ }
290
+ } else {
291
+ const conts = source.continuations(u)
292
+ edgesCache![u] = conts
293
+
294
+ for (const cont of conts) {
295
+ if (cont.targetState < stateCount && !visited[cont.targetState]) {
296
+ visited[cont.targetState] = 1
297
+ stack.push(cont.targetState)
298
+ }
299
+ }
300
+ }
301
+ }
302
+
303
+ for (let i = order.length - 1; i >= 0; i--) {
304
+ const u = order[i]!
305
+ let best = -1
306
+ const places = nodes ? nodes[u]!.places : source.accepting(u)
307
+
308
+ for (const place of places) {
309
+ if (place.referential > best) {
310
+ best = place.referential
311
+ }
312
+ }
313
+
314
+ if (nodes) {
315
+ for (const target of nodes[u]!.edges.values()) {
316
+ const childBest = maxRef[target]!
317
+
318
+ if (childBest > best) {
319
+ best = childBest
320
+ }
321
+ }
322
+ } else {
323
+ for (const cont of edgesCache![u]!) {
324
+ const childBest = maxRef[cont.targetState]!
325
+
326
+ if (childBest > best) {
327
+ best = childBest
328
+ }
329
+ }
330
+ }
331
+
332
+ maxRef[u] = best
333
+ }
334
+
335
+ const tokens = new Map<string, number>()
336
+
337
+ for (const u of order) {
338
+ if (nodes) {
339
+ for (const [token, target] of nodes[u]!.edges) {
340
+ const score = maxRef[target]!
341
+
342
+ if (score < minReferential || !isEligibleToken(token, minTokenLength, maxTokenLength)) continue
343
+
344
+ const prev = tokens.get(token)
345
+
346
+ if (prev == null || score > prev) {
347
+ tokens.set(token, score)
348
+ }
349
+ }
350
+ } else {
351
+ for (const cont of edgesCache![u]!) {
352
+ const score = maxRef[cont.targetState]!
353
+
354
+ if (score < minReferential || !isEligibleToken(cont.token, minTokenLength, maxTokenLength)) continue
355
+
356
+ const prev = tokens.get(cont.token)
357
+
358
+ if (prev == null || score > prev) {
359
+ tokens.set(cont.token, score)
360
+ }
361
+ }
362
+ }
363
+ }
364
+
365
+ return tokens
366
+ }
367
+
368
+ /**
369
+ * Builds and serializes a compact `FD1\0` v1 1-delete token sidecar from an FST matcher.
370
+ *
371
+ * @public
372
+ */
373
+ export function buildFSTDel1Sidecar(source: FSTGraphSource, opts: BuildFSTDel1SidecarOpts = {}): BuiltFSTDel1Sidecar {
374
+ const minReferential = opts.minReferential ?? DEFAULT_DEL1_MIN_REFERENTIAL
375
+ const minTokenLength = Math.max(2, Math.floor(opts.minTokenLength ?? DEFAULT_DEL1_MIN_TOKEN_LENGTH))
376
+ const maxTokenLength = Math.max(minTokenLength, Math.floor(opts.maxTokenLength ?? DEFAULT_DEL1_MAX_TOKEN_LENGTH))
377
+
378
+ const maxBucketSize = Math.min(
379
+ MAX_U8_BUCKET_SIZE,
380
+ Math.max(1, Math.floor(opts.maxBucketSize ?? DEFAULT_DEL1_MAX_BUCKET_SIZE))
381
+ )
382
+
383
+ const tokenScores = collectEligibleTokens(source, minReferential, minTokenLength, maxTokenLength)
384
+
385
+ // Sort tokens by descending referential score (tie-break lexicographically) so lower token IDs
386
+ // represent higher-referential places and bucket caps retain the most prominent tokens first.
387
+ const sortedTokens = [...tokenScores.entries()]
388
+ .toSorted(([tokA, refA], [tokB, refB]) => {
389
+ if (refB !== refA) return refB - refA
390
+
391
+ return tokA < tokB ? -1 : tokA > tokB ? 1 : 0
392
+ })
393
+ .map(([token]) => token)
394
+
395
+ const bucketsByHash = new Map<number, number[]>()
396
+
397
+ for (let tokenID = 0; tokenID < sortedTokens.length; tokenID++) {
398
+ const cps = [...sortedTokens[tokenID]!]
399
+
400
+ for (let i = 0; i < cps.length; i++) {
401
+ // Adjacent identical code points produce the same deletion key.
402
+ if (i > 0 && cps[i] === cps[i - 1]) continue
403
+
404
+ const delKey = cps.slice(0, i).join("") + cps.slice(i + 1).join("")
405
+ const hash = hashFNV1a(delKey) >>> 0
406
+ let bucket = bucketsByHash.get(hash)
407
+
408
+ if (!bucket) {
409
+ bucket = [tokenID]
410
+ bucketsByHash.set(hash, bucket)
411
+ } else if (bucket.at(-1) !== tokenID && bucket.length < maxBucketSize) {
412
+ bucket.push(tokenID)
413
+ }
414
+ }
415
+ }
416
+
417
+ const sortedHashes = [...bucketsByHash.keys()].toSorted((a, b) => a - b)
418
+ const encoder = new TextEncoder()
419
+ const encodedTokens = sortedTokens.map((token) => encoder.encode(token))
420
+
421
+ let tokenStringBytes = 0
422
+
423
+ for (const encoded of encodedTokens) {
424
+ tokenStringBytes += encoded.byteLength
425
+ }
426
+
427
+ let postingCount = 0
428
+
429
+ for (const hash of sortedHashes) {
430
+ postingCount += bucketsByHash.get(hash)!.length
431
+ }
432
+
433
+ const tokenCount = sortedTokens.length
434
+ const bucketCount = sortedHashes.length
435
+ const usesU16Postings = tokenCount <= MAX_U16_TOKEN_COUNT
436
+ const postingEntrySize = usesU16Postings ? 2 : 4
437
+
438
+ const tokenOffsetsBytes = (tokenCount + 1) * 4
439
+ const bucketHashesBytes = bucketCount * 4
440
+ const bucketCountsBytes = bucketCount
441
+ const postingsBytes = postingCount * postingEntrySize
442
+
443
+ const totalBytes =
444
+ DEL1_HEADER_SIZE + tokenOffsetsBytes + tokenStringBytes + bucketHashesBytes + bucketCountsBytes + postingsBytes
445
+
446
+ const bytes = new Uint8Array(totalBytes)
447
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
448
+
449
+ for (let i = 0; i < DEL1_MAGIC_BYTES.length; i++) {
450
+ bytes[i] = DEL1_MAGIC_BYTES[i]!
451
+ }
452
+
453
+ view.setUint16(4, DEL1_FORMAT_VERSION, true)
454
+ view.setUint16(6, usesU16Postings ? DEL1_FLAG_U16_POSTINGS : 0, true)
455
+ view.setUint32(8, tokenCount, true)
456
+ view.setUint32(12, tokenStringBytes, true)
457
+ view.setUint32(16, bucketCount, true)
458
+ view.setUint32(20, postingCount, true)
459
+ view.setUint16(24, minTokenLength, true)
460
+ view.setUint16(26, maxTokenLength, true)
461
+ view.setUint16(28, maxBucketSize, true)
462
+ view.setUint16(30, 0, true)
463
+
464
+ let pos = DEL1_HEADER_SIZE
465
+ let strOffset = 0
466
+
467
+ for (const encoded of encodedTokens) {
468
+ view.setUint32(pos, strOffset, true)
469
+ pos += 4
470
+ strOffset += encoded.byteLength
471
+ }
472
+
473
+ view.setUint32(pos, strOffset, true)
474
+ pos += 4
475
+
476
+ for (const encoded of encodedTokens) {
477
+ bytes.set(encoded, pos)
478
+ pos += encoded.byteLength
479
+ }
480
+
481
+ for (const hash of sortedHashes) {
482
+ view.setUint32(pos, hash, true)
483
+ pos += 4
484
+ }
485
+
486
+ for (const hash of sortedHashes) {
487
+ bytes[pos] = bucketsByHash.get(hash)!.length
488
+ pos += 1
489
+ }
490
+
491
+ for (const hash of sortedHashes) {
492
+ for (const tokenID of bucketsByHash.get(hash)!) {
493
+ if (usesU16Postings) {
494
+ view.setUint16(pos, tokenID, true)
495
+ pos += 2
496
+ } else {
497
+ view.setUint32(pos, tokenID, true)
498
+ pos += 4
499
+ }
500
+ }
501
+ }
502
+
503
+ return {
504
+ bytes,
505
+ stats: {
506
+ tokenCount,
507
+ bucketCount,
508
+ postingCount,
509
+ byteLength: bytes.byteLength,
510
+ minTokenLength,
511
+ maxTokenLength,
512
+ maxBucketSize,
513
+ },
514
+ }
515
+ }
516
+
517
+ /**
518
+ * Reads an `FD1\0` v1 1-delete sidecar binary in place using typed arrays and `DataView`,
519
+ * returning canonical indexed tokens within Damerau-Levenshtein distance `<= 1` in microseconds.
520
+ *
521
+ * @public
522
+ */
523
+ export class BinaryFSTDel1Lookup {
524
+ readonly tokenCount: number
525
+ readonly bucketCount: number
526
+ readonly postingCount: number
527
+ readonly minTokenLength: number
528
+ readonly maxTokenLength: number
529
+ readonly maxBucketSize: number
530
+ readonly byteLength: number
531
+
532
+ readonly #bytes: Uint8Array
533
+ readonly #view: DataView
534
+ readonly #decoder = new TextDecoder("utf-8")
535
+ readonly #usesU16Postings: boolean
536
+ readonly #tokenStringsStart: number
537
+ readonly #postingsStart: number
538
+ readonly #tokenOffsets: Uint32Array
539
+ readonly #bucketHashes: Uint32Array
540
+ readonly #postingOffsets: Uint32Array
541
+ readonly #exactTokenSlots: Int32Array
542
+
543
+ constructor(input: ArrayBuffer | Uint8Array) {
544
+ const bytes = input instanceof ArrayBuffer ? new Uint8Array(input) : input
545
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
546
+
547
+ if (bytes.byteLength < DEL1_HEADER_SIZE) {
548
+ throw new Error("FST del1 sidecar buffer too small for header")
549
+ }
550
+
551
+ if (DEL1_MAGIC_BYTES.some((byte, index) => bytes[index] !== byte)) {
552
+ throw new Error("FST del1 sidecar magic mismatch")
553
+ }
554
+
555
+ const version = view.getUint16(4, true)
556
+
557
+ if (version !== DEL1_FORMAT_VERSION) {
558
+ throw new Error(`FST del1 sidecar version ${version} unsupported (expected ${DEL1_FORMAT_VERSION})`)
559
+ }
560
+
561
+ const flags = view.getUint16(6, true)
562
+ const usesU16Postings = (flags & DEL1_FLAG_U16_POSTINGS) === DEL1_FLAG_U16_POSTINGS
563
+ const tokenCount = view.getUint32(8, true)
564
+ const tokenStringBytes = view.getUint32(12, true)
565
+ const bucketCount = view.getUint32(16, true)
566
+ const postingCount = view.getUint32(20, true)
567
+ const minTokenLength = view.getUint16(24, true)
568
+ const maxTokenLength = view.getUint16(26, true)
569
+ const maxBucketSize = view.getUint16(28, true)
570
+
571
+ const tokenOffsetsStart = DEL1_HEADER_SIZE
572
+ const tokenStringsStart = tokenOffsetsStart + (tokenCount + 1) * 4
573
+ const bucketHashesStart = tokenStringsStart + tokenStringBytes
574
+ const bucketCountsStart = bucketHashesStart + bucketCount * 4
575
+ const postingsStart = bucketCountsStart + bucketCount
576
+ const postingEntrySize = usesU16Postings ? 2 : 4
577
+ const expectedBytes = postingsStart + postingCount * postingEntrySize
578
+
579
+ if (bytes.byteLength < expectedBytes) {
580
+ throw new Error(`FST del1 sidecar truncated: expected ${expectedBytes} bytes, got ${bytes.byteLength}`)
581
+ }
582
+
583
+ const tokenOffsets = new Uint32Array(tokenCount + 1)
584
+
585
+ for (let i = 0; i <= tokenCount; i++) {
586
+ tokenOffsets[i] = view.getUint32(tokenOffsetsStart + i * 4, true)
587
+ }
588
+
589
+ if (tokenOffsets[tokenCount] !== tokenStringBytes) {
590
+ throw new Error(
591
+ `FST del1 sidecar string table sentinel mismatch: ${tokenOffsets[tokenCount]} !== ${tokenStringBytes}`
592
+ )
593
+ }
594
+
595
+ const bucketHashes = new Uint32Array(bucketCount)
596
+
597
+ for (let i = 0; i < bucketCount; i++) {
598
+ bucketHashes[i] = view.getUint32(bucketHashesStart + i * 4, true)
599
+ }
600
+
601
+ const postingOffsets = new Uint32Array(bucketCount + 1)
602
+ let running = 0
603
+
604
+ for (let i = 0; i < bucketCount; i++) {
605
+ postingOffsets[i] = running
606
+ running += bytes[bucketCountsStart + i]!
607
+ }
608
+
609
+ postingOffsets[bucketCount] = running
610
+
611
+ if (running !== postingCount) {
612
+ throw new Error(`FST del1 sidecar posting count mismatch: sum ${running} !== header ${postingCount}`)
613
+ }
614
+
615
+ this.tokenCount = tokenCount
616
+ this.bucketCount = bucketCount
617
+ this.postingCount = postingCount
618
+ this.minTokenLength = minTokenLength
619
+ this.maxTokenLength = maxTokenLength
620
+ this.maxBucketSize = maxBucketSize
621
+ this.byteLength = bytes.byteLength
622
+
623
+ this.#bytes = bytes
624
+ this.#view = view
625
+ this.#usesU16Postings = usesU16Postings
626
+ this.#tokenStringsStart = tokenStringsStart
627
+ this.#postingsStart = postingsStart
628
+ this.#tokenOffsets = tokenOffsets
629
+ this.#bucketHashes = bucketHashes
630
+ this.#postingOffsets = postingOffsets
631
+ this.#exactTokenSlots = new Int32Array(tableCapacity(tokenCount)).fill(EMPTY_SLOT)
632
+
633
+ const mask = this.#exactTokenSlots.length - 1
634
+
635
+ for (let tokenID = 0; tokenID < tokenCount; tokenID++) {
636
+ const token = this.#tokenAt(tokenID)
637
+ let slot = hashFNV1a(token) & mask
638
+
639
+ while (this.#exactTokenSlots[slot] !== EMPTY_SLOT) {
640
+ slot = (slot + 1) & mask
641
+ }
642
+
643
+ this.#exactTokenSlots[slot] = tokenID
644
+ }
645
+ }
646
+
647
+ /**
648
+ * Reports whether `token` is stored directly in this sidecar's canonical token table.
649
+ */
650
+ hasToken(token: string): boolean {
651
+ return this.#findExactToken(token) !== EMPTY_SLOT
652
+ }
653
+
654
+ /**
655
+ * Returns all indexed canonical tokens within Damerau-Levenshtein distance `<= 1` of `query`,
656
+ * ordered by descending build-time referential priority (exact match first when present).
657
+ *
658
+ * Numeric or non-letter queries and queries outside `[minTokenLength - 1, maxTokenLength + 1]`
659
+ * code points immediately return `[]`.
660
+ */
661
+ lookupFuzzyToken(query: string): string[] {
662
+ if (this.tokenCount === 0 || !query || DIGIT_RE.test(query) || !LETTER_RE.test(query)) {
663
+ return []
664
+ }
665
+
666
+ const cps = [...query]
667
+
668
+ if (cps.length < this.minTokenLength - 1 || cps.length > this.maxTokenLength + 1) {
669
+ return []
670
+ }
671
+
672
+ const matched = new Set<number>()
673
+
674
+ const checkCandidate = (tokenID: number): void => {
675
+ if (matched.has(tokenID)) return
676
+
677
+ if (isWithinOneEditCodePoints(cps, [...this.#tokenAt(tokenID)])) {
678
+ matched.add(tokenID)
679
+ }
680
+ }
681
+
682
+ // Exact token hit (distance 0) and 1-deletion query hit (`query` equals a 1-deletion of canonical).
683
+ const exactID = this.#findExactToken(query)
684
+
685
+ if (exactID !== EMPTY_SLOT) {
686
+ matched.add(exactID)
687
+ }
688
+
689
+ this.#visitBucket(hashFNV1a(query) >>> 0, checkCandidate)
690
+
691
+ // Probe every unique 1-deletion of `query` against:
692
+ // 1. Exact canonical tokens (recovers 1-insertion queries such as `aucklland` -> `auckland`).
693
+ // 2. Delete-key buckets (recovers 1-substitution and adjacent transposition
694
+ // such as `aucklnad` -> `auckland`).
695
+ for (let i = 0; i < cps.length; i++) {
696
+ if (i > 0 && cps[i] === cps[i - 1]) continue
697
+
698
+ const delKey = cps.slice(0, i).join("") + cps.slice(i + 1).join("")
699
+ const delExactID = this.#findExactToken(delKey)
700
+
701
+ if (delExactID !== EMPTY_SLOT) {
702
+ matched.add(delExactID)
703
+ }
704
+
705
+ this.#visitBucket(hashFNV1a(delKey) >>> 0, checkCandidate)
706
+ }
707
+
708
+ if (!matched.size) return []
709
+
710
+ const sortedIDs = [...matched].toSorted((a, b) => {
711
+ if (a === exactID) return -1
712
+
713
+ if (b === exactID) return 1
714
+
715
+ return a - b
716
+ })
717
+
718
+ return sortedIDs.map((id) => this.#tokenAt(id))
719
+ }
720
+
721
+ #tokenAt(tokenID: number): string {
722
+ const start = this.#tokenStringsStart + this.#tokenOffsets[tokenID]!
723
+ const end = this.#tokenStringsStart + this.#tokenOffsets[tokenID + 1]!
724
+
725
+ return this.#decoder.decode(this.#bytes.subarray(start, end))
726
+ }
727
+
728
+ #findExactToken(token: string): number {
729
+ if (this.tokenCount === 0) return EMPTY_SLOT
730
+
731
+ const mask = this.#exactTokenSlots.length - 1
732
+ let slot = hashFNV1a(token) & mask
733
+
734
+ for (;;) {
735
+ const tokenID = this.#exactTokenSlots[slot]!
736
+
737
+ if (tokenID === EMPTY_SLOT) return EMPTY_SLOT
738
+
739
+ if (this.#tokenAt(tokenID) === token) return tokenID
740
+ slot = (slot + 1) & mask
741
+ }
742
+ }
743
+
744
+ #visitBucket(hash: number, visitor: (tokenID: number) => void): void {
745
+ const bucketIdx = this.#findBucket(hash)
746
+
747
+ if (bucketIdx < 0) return
748
+
749
+ const start = this.#postingOffsets[bucketIdx]!
750
+ const end = this.#postingOffsets[bucketIdx + 1]!
751
+
752
+ if (this.#usesU16Postings) {
753
+ for (let i = start; i < end; i++) {
754
+ visitor(this.#view.getUint16(this.#postingsStart + i * 2, true))
755
+ }
756
+ } else {
757
+ for (let i = start; i < end; i++) {
758
+ visitor(this.#view.getUint32(this.#postingsStart + i * 4, true))
759
+ }
760
+ }
761
+ }
762
+
763
+ #findBucket(targetHash: number): number {
764
+ let lo = 0
765
+ let hi = this.bucketCount - 1
766
+
767
+ while (lo <= hi) {
768
+ const mid = (lo + hi) >>> 1
769
+ const hash = this.#bucketHashes[mid]!
770
+
771
+ if (hash === targetHash) return mid
772
+
773
+ if (hash < targetHash) {
774
+ lo = mid + 1
775
+ } else {
776
+ hi = mid - 1
777
+ }
778
+ }
779
+
780
+ return -1
781
+ }
782
+ }