@mailwoman/resolver-wof-sqlite 11.5.0 → 12.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 (196) hide show
  1. package/lib/address/keys/build.ts +35 -0
  2. package/lib/address/keys/lookup.ts +204 -6
  3. package/lib/address/keys/point-lookup.ts +4 -0
  4. package/lib/address/keys/schema.ts +37 -0
  5. package/lib/address/number-forms.ts +32 -13
  6. package/lib/address/point/interpolation.ts +23 -6
  7. package/lib/address/point/schema.ts +120 -2
  8. package/lib/address/point/scope-search.ts +179 -0
  9. package/lib/address/point.ts +225 -28
  10. package/lib/build/candidate.ts +222 -9
  11. package/lib/build/population-corrections.ts +11 -2
  12. package/lib/candidate/ancestors/sidecar.ts +73 -4
  13. package/lib/candidate/del1.ts +218 -0
  14. package/lib/candidate/lookup.ts +316 -113
  15. package/lib/candidate/name-roles.ts +112 -6
  16. package/lib/candidate/outcomes.ts +191 -0
  17. package/lib/candidate/schema.ts +79 -3
  18. package/lib/fst/binary-matcher.ts +9 -1
  19. package/lib/fst/builder.ts +7 -0
  20. package/lib/fst/del1-sidecar.ts +782 -0
  21. package/lib/fst/deserialize-web.ts +14 -2
  22. package/lib/fst/matcher.ts +7 -1
  23. package/lib/fst/types.ts +8 -0
  24. package/lib/fst.ts +1 -0
  25. package/lib/geonames/aliases.ts +39 -1
  26. package/lib/index.ts +22 -2
  27. package/lib/labels/street/canonical.ts +333 -0
  28. package/lib/labels/street/centroid/schema.ts +23 -1
  29. package/lib/labels/street/interpolation.ts +32 -6
  30. package/lib/labels/street/morphology/fst/builder.ts +13 -0
  31. package/lib/labels/street/morphology/fst/loader.ts +32 -2
  32. package/lib/labels/street/normalize.ts +34 -4
  33. package/lib/labels/street.ts +1 -0
  34. package/lib/landmark.ts +51 -4
  35. package/lib/lookup/types.ts +25 -6
  36. package/lib/outcome/memberships.ts +131 -0
  37. package/lib/outcome/schema.ts +147 -0
  38. package/lib/poi/lookup.ts +4 -0
  39. package/lib/poi/schema.ts +2 -1
  40. package/lib/ranking/primary-preference.ts +14 -6
  41. package/lib/schema/overture-match.ts +2 -1
  42. package/out/address/keys/build.d.ts.map +1 -1
  43. package/out/address/keys/build.js +28 -1
  44. package/out/address/keys/build.js.map +1 -1
  45. package/out/address/keys/lookup.d.ts +17 -0
  46. package/out/address/keys/lookup.d.ts.map +1 -1
  47. package/out/address/keys/lookup.js +119 -6
  48. package/out/address/keys/lookup.js.map +1 -1
  49. package/out/address/keys/point-lookup.d.ts.map +1 -1
  50. package/out/address/keys/point-lookup.js +4 -0
  51. package/out/address/keys/point-lookup.js.map +1 -1
  52. package/out/address/keys/schema.d.ts +21 -0
  53. package/out/address/keys/schema.d.ts.map +1 -1
  54. package/out/address/keys/schema.js +18 -0
  55. package/out/address/keys/schema.js.map +1 -1
  56. package/out/address/number-forms.d.ts +10 -1
  57. package/out/address/number-forms.d.ts.map +1 -1
  58. package/out/address/number-forms.js +20 -11
  59. package/out/address/number-forms.js.map +1 -1
  60. package/out/address/point/interpolation.d.ts.map +1 -1
  61. package/out/address/point/interpolation.js +15 -5
  62. package/out/address/point/interpolation.js.map +1 -1
  63. package/out/address/point/schema.d.ts +43 -2
  64. package/out/address/point/schema.d.ts.map +1 -1
  65. package/out/address/point/schema.js +73 -0
  66. package/out/address/point/schema.js.map +1 -1
  67. package/out/address/point/scope-search.d.ts +77 -0
  68. package/out/address/point/scope-search.d.ts.map +1 -0
  69. package/out/address/point/scope-search.js +107 -0
  70. package/out/address/point/scope-search.js.map +1 -0
  71. package/out/address/point.d.ts +12 -0
  72. package/out/address/point.d.ts.map +1 -1
  73. package/out/address/point.js +143 -26
  74. package/out/address/point.js.map +1 -1
  75. package/out/build/candidate.d.ts +49 -0
  76. package/out/build/candidate.d.ts.map +1 -1
  77. package/out/build/candidate.js +101 -8
  78. package/out/build/candidate.js.map +1 -1
  79. package/out/build/population-corrections.d.ts +2 -2
  80. package/out/build/population-corrections.d.ts.map +1 -1
  81. package/out/build/population-corrections.js +10 -2
  82. package/out/build/population-corrections.js.map +1 -1
  83. package/out/candidate/ancestors/sidecar.d.ts +7 -3
  84. package/out/candidate/ancestors/sidecar.d.ts.map +1 -1
  85. package/out/candidate/ancestors/sidecar.js +56 -4
  86. package/out/candidate/ancestors/sidecar.js.map +1 -1
  87. package/out/candidate/del1.d.ts +61 -0
  88. package/out/candidate/del1.d.ts.map +1 -0
  89. package/out/candidate/del1.js +158 -0
  90. package/out/candidate/del1.js.map +1 -0
  91. package/out/candidate/lookup.d.ts +16 -17
  92. package/out/candidate/lookup.d.ts.map +1 -1
  93. package/out/candidate/lookup.js +222 -92
  94. package/out/candidate/lookup.js.map +1 -1
  95. package/out/candidate/name-roles.d.ts +3 -2
  96. package/out/candidate/name-roles.d.ts.map +1 -1
  97. package/out/candidate/name-roles.js +75 -5
  98. package/out/candidate/name-roles.js.map +1 -1
  99. package/out/candidate/outcomes.d.ts +57 -0
  100. package/out/candidate/outcomes.d.ts.map +1 -0
  101. package/out/candidate/outcomes.js +109 -0
  102. package/out/candidate/outcomes.js.map +1 -0
  103. package/out/candidate/schema.d.ts +51 -3
  104. package/out/candidate/schema.d.ts.map +1 -1
  105. package/out/candidate/schema.js +40 -0
  106. package/out/candidate/schema.js.map +1 -1
  107. package/out/fst/binary-matcher.d.ts +7 -1
  108. package/out/fst/binary-matcher.d.ts.map +1 -1
  109. package/out/fst/binary-matcher.js +7 -1
  110. package/out/fst/binary-matcher.js.map +1 -1
  111. package/out/fst/builder.d.ts +2 -0
  112. package/out/fst/builder.d.ts.map +1 -1
  113. package/out/fst/builder.js +5 -0
  114. package/out/fst/builder.js.map +1 -1
  115. package/out/fst/del1-sidecar.d.ts +158 -0
  116. package/out/fst/del1-sidecar.d.ts.map +1 -0
  117. package/out/fst/del1-sidecar.js +581 -0
  118. package/out/fst/del1-sidecar.js.map +1 -0
  119. package/out/fst/deserialize-web.d.ts +3 -1
  120. package/out/fst/deserialize-web.d.ts.map +1 -1
  121. package/out/fst/deserialize-web.js +9 -2
  122. package/out/fst/deserialize-web.js.map +1 -1
  123. package/out/fst/matcher.d.ts +6 -1
  124. package/out/fst/matcher.d.ts.map +1 -1
  125. package/out/fst/matcher.js +6 -1
  126. package/out/fst/matcher.js.map +1 -1
  127. package/out/fst/types.d.ts +7 -0
  128. package/out/fst/types.d.ts.map +1 -1
  129. package/out/fst.d.ts +1 -0
  130. package/out/fst.d.ts.map +1 -1
  131. package/out/fst.js +1 -0
  132. package/out/fst.js.map +1 -1
  133. package/out/geonames/aliases.d.ts +10 -0
  134. package/out/geonames/aliases.d.ts.map +1 -1
  135. package/out/geonames/aliases.js +33 -1
  136. package/out/geonames/aliases.js.map +1 -1
  137. package/out/index.d.ts +4 -3
  138. package/out/index.d.ts.map +1 -1
  139. package/out/index.js +3 -2
  140. package/out/index.js.map +1 -1
  141. package/out/labels/street/canonical.d.ts +68 -0
  142. package/out/labels/street/canonical.d.ts.map +1 -0
  143. package/out/labels/street/canonical.js +234 -0
  144. package/out/labels/street/canonical.js.map +1 -0
  145. package/out/labels/street/centroid/schema.d.ts +10 -1
  146. package/out/labels/street/centroid/schema.d.ts.map +1 -1
  147. package/out/labels/street/centroid/schema.js +12 -0
  148. package/out/labels/street/centroid/schema.js.map +1 -1
  149. package/out/labels/street/interpolation.d.ts +9 -1
  150. package/out/labels/street/interpolation.d.ts.map +1 -1
  151. package/out/labels/street/interpolation.js +8 -5
  152. package/out/labels/street/interpolation.js.map +1 -1
  153. package/out/labels/street/morphology/fst/builder.d.ts +8 -0
  154. package/out/labels/street/morphology/fst/builder.d.ts.map +1 -1
  155. package/out/labels/street/morphology/fst/builder.js +5 -0
  156. package/out/labels/street/morphology/fst/builder.js.map +1 -1
  157. package/out/labels/street/morphology/fst/loader.d.ts +12 -0
  158. package/out/labels/street/morphology/fst/loader.d.ts.map +1 -1
  159. package/out/labels/street/morphology/fst/loader.js +18 -2
  160. package/out/labels/street/morphology/fst/loader.js.map +1 -1
  161. package/out/labels/street/normalize.d.ts +8 -0
  162. package/out/labels/street/normalize.d.ts.map +1 -1
  163. package/out/labels/street/normalize.js +24 -4
  164. package/out/labels/street/normalize.js.map +1 -1
  165. package/out/labels/street.d.ts +1 -0
  166. package/out/labels/street.d.ts.map +1 -1
  167. package/out/labels/street.js +1 -0
  168. package/out/labels/street.js.map +1 -1
  169. package/out/landmark.d.ts +15 -3
  170. package/out/landmark.d.ts.map +1 -1
  171. package/out/landmark.js +38 -3
  172. package/out/landmark.js.map +1 -1
  173. package/out/lookup/types.d.ts +21 -5
  174. package/out/lookup/types.d.ts.map +1 -1
  175. package/out/outcome/memberships.d.ts +58 -0
  176. package/out/outcome/memberships.d.ts.map +1 -0
  177. package/out/outcome/memberships.js +83 -0
  178. package/out/outcome/memberships.js.map +1 -0
  179. package/out/outcome/schema.d.ts +74 -0
  180. package/out/outcome/schema.d.ts.map +1 -0
  181. package/out/outcome/schema.js +63 -0
  182. package/out/outcome/schema.js.map +1 -0
  183. package/out/poi/lookup.d.ts +4 -0
  184. package/out/poi/lookup.d.ts.map +1 -1
  185. package/out/poi/lookup.js.map +1 -1
  186. package/out/poi/schema.d.ts +2 -1
  187. package/out/poi/schema.d.ts.map +1 -1
  188. package/out/poi/schema.js.map +1 -1
  189. package/out/ranking/primary-preference.d.ts +9 -5
  190. package/out/ranking/primary-preference.d.ts.map +1 -1
  191. package/out/ranking/primary-preference.js +11 -3
  192. package/out/ranking/primary-preference.js.map +1 -1
  193. package/out/schema/overture-match.d.ts +2 -1
  194. package/out/schema/overture-match.d.ts.map +1 -1
  195. package/out/schema/overture-match.js.map +1 -1
  196. package/package.json +15 -15
@@ -33,6 +33,7 @@ import {
33
33
  import { addressPostcodeKey } from "#address/keys/postcode"
34
34
  import {
35
35
  ADDRESS_SCOPED_KEY_TABLES,
36
+ ADDRESS_STREET_ALIAS_TABLES,
36
37
  ADDRESS_STREET_TABLES,
37
38
  type AddressDetailDatabase,
38
39
  type AddressLookupDatabase,
@@ -41,10 +42,13 @@ import {
41
42
  createAddressRegionKeyTable,
42
43
  createAddressScopedKeyTable,
43
44
  createAddressSourceTable,
45
+ createAddressStreetAliasTable,
44
46
  createAddressStreetTable,
45
47
  } from "#address/keys/schema"
46
48
  import type { AddressRecord } from "#address/record"
47
49
  import { addressPointStacksSQL } from "#address/stack"
50
+ import { canonicalStreetKey } from "#labels/street/canonical"
51
+ import { streetLocaleForCountry } from "#labels/street/locale"
48
52
 
49
53
  /**
50
54
  * The SQLite page size of both files.
@@ -646,10 +650,22 @@ async function writeLookup(
646
650
  for (const table of ADDRESS_STREET_TABLES) {
647
651
  await createAddressStreetTable(db, table)
648
652
  }
653
+
654
+ for (const table of ADDRESS_STREET_ALIAS_TABLES) {
655
+ await createAddressStreetAliasTable(db, table)
656
+ }
649
657
  },
650
658
  ingest: async (db) => {
651
659
  db.exec(`ATTACH DATABASE '${stagingPath.replaceAll("'", "''")}' AS staged`)
652
660
 
661
+ db.function("canonical_street_key", { deterministic: true }, (streetRaw: unknown, country: unknown): string => {
662
+ if (typeof streetRaw !== "string" || !streetRaw) return ""
663
+
664
+ const locale = streetLocaleForCountry(typeof country === "string" ? country : "")
665
+
666
+ return canonicalStreetKey(streetRaw, locale).key
667
+ })
668
+
653
669
  const insertSource = db.prepare("INSERT INTO source VALUES (?, ?, ?, ?, ?)")
654
670
 
655
671
  const ids = db.prepare("SELECT name, source_id FROM staged.source_ids ORDER BY source_id").all() as Array<{
@@ -687,6 +703,25 @@ async function writeLookup(
687
703
  )
688
704
  }
689
705
 
706
+ for (const [table, level] of [
707
+ ["street_alias_postcode", "key_postcode"],
708
+ ["street_alias_locality", "key_locality"],
709
+ ] as const) {
710
+ db.exec(
711
+ `INSERT OR IGNORE INTO ${table} (scope, street_canon, street)
712
+ SELECT scope, street_canon, street FROM (
713
+ SELECT scope, canonical_street_key(street_raw, country) AS street_canon, street
714
+ FROM (
715
+ SELECT DISTINCT s.scope, s.street, a.street_raw, a.country
716
+ FROM staged.stage s JOIN staged.address a USING (address_id)
717
+ WHERE s.level = '${level}'
718
+ )
719
+ )
720
+ WHERE street_canon != ''
721
+ ORDER BY scope, street_canon, street`
722
+ )
723
+ }
724
+
690
725
  db.exec("DETACH DATABASE staged")
691
726
 
692
727
  return true
@@ -10,8 +10,18 @@
10
10
  * so the three runtimes share one read order.
11
11
  */
12
12
 
13
+ import { memoizeResettable } from "@mailwoman/core/async/memoize"
14
+ import type { NumberMatchKind, StreetMatchKind } from "@mailwoman/core/resolver"
15
+
13
16
  import { addressPostcodeKey } from "#address/keys/postcode"
14
17
  import { houseNumberForms } from "#address/number-forms"
18
+ import {
19
+ canonicalStreetKey,
20
+ findFuzzyEdit1Streets,
21
+ FUZZY_SCOPE_ROW_LIMIT,
22
+ MIN_FUZZY_CORE_LENGTH,
23
+ type ScopedStreetAliasRow,
24
+ } from "#labels/street/canonical"
15
25
  import { streetLocaleForCountry } from "#labels/street/locale"
16
26
  import {
17
27
  normalizeHouseNumberForKey,
@@ -75,6 +85,22 @@ export interface AddressKeyQuery {
75
85
  export interface AddressKeyAnswer {
76
86
  level: AddressKeyLevel
77
87
  hits: AddressKeyHit[]
88
+ /**
89
+ * The stored house-number key that answered.
90
+ */
91
+ matchedNumber: string
92
+ /**
93
+ * How {@link matchedNumber} relates to the query's normalized house number.
94
+ */
95
+ numberMatch: NumberMatchKind
96
+ /**
97
+ * The stored street key that answered.
98
+ */
99
+ matchedStreet: string
100
+ /**
101
+ * How {@link matchedStreet} relates to the query's primary normalized street key.
102
+ */
103
+ streetMatch: StreetMatchKind
78
104
  }
79
105
 
80
106
  export interface AddressKeyLookupOptions {
@@ -115,6 +141,20 @@ export class AddressKeyLookup {
115
141
  readonly #locale: StreetLocale
116
142
  readonly #cap: number
117
143
 
144
+ /**
145
+ * Checks once (lazily, on the first exact miss) which alias and street-aggregate
146
+ * tables exist in `lookup.db`, so legacy files built without `street_alias_*` keep
147
+ * answering without throwing and exact Step 1 hits issue zero extra queries.
148
+ */
149
+ readonly #optionalTables = memoizeResettable(async (): Promise<ReadonlySet<string>> => {
150
+ const rows = await this.#runner.query<{ name: string }>(
151
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('street_alias_postcode', 'street_alias_locality', 'street_postcode', 'street_locality')",
152
+ []
153
+ )
154
+
155
+ return new Set(rows.map((row) => String(row.name)))
156
+ })
157
+
118
158
  constructor(runner: AddressStatementRunner, options: AddressKeyLookupOptions) {
119
159
  this.#runner = runner
120
160
  this.#country = options.country.toUpperCase()
@@ -130,22 +170,180 @@ export class AddressKeyLookup {
130
170
 
131
171
  if (!number) return null
132
172
 
133
- // Every street variant runs every number form, and every form runs the level ladder,
134
- // so the literal street and written number answer first.
135
- for (const street of streetKeyVariants(query.street, streetLocaleForSurface(query.street, this.#locale))) {
173
+ const surfaceLocale = streetLocaleForSurface(query.street, this.#locale)
174
+ const variants = streetKeyVariants(query.street, surfaceLocale)
175
+
176
+ // Step 1: exact / existing streetKeyVariants (zero extra queries on exact hits).
177
+ for (let i = 0; i < variants.length; i++) {
178
+ const street = variants[i]!
179
+
136
180
  if (!street) continue
137
181
 
138
182
  for (const form of houseNumberForms(number, this.#locale)) {
139
- const answer = await this.#ladder(query, street, form)
183
+ const answer = await this.#ladder(query, street, form.number)
184
+
185
+ if (answer) {
186
+ return {
187
+ ...answer,
188
+ matchedNumber: form.number,
189
+ numberMatch: form.match,
190
+ matchedStreet: street,
191
+ streetMatch: i === 0 ? "written" : "respelled",
192
+ }
193
+ }
194
+ }
195
+ }
196
+
197
+ const canon = canonicalStreetKey(query.street, surfaceLocale)
198
+
199
+ if (!canon.key) return null
200
+
201
+ const scopes = this.#aliasScopes(query)
202
+
203
+ if (!scopes.length) return null
204
+
205
+ const tables = await this.#optionalTables()
206
+ const tried = new Set<string>(variants)
207
+
208
+ // Step 2: canonical-alias via one B-tree seek on `street_alias_postcode` / `street_alias_locality`.
209
+ for (const scope of scopes) {
210
+ if (!tables.has(scope.aliasTable)) continue
211
+
212
+ const aliasRows = await this.#runner.query<{ street: string }>(
213
+ `SELECT street FROM ${scope.aliasTable} WHERE scope = ? AND street_canon = ?`,
214
+ [scope.value, canon.key]
215
+ )
216
+
217
+ for (const { street } of aliasRows) {
218
+ if (tried.has(street)) continue
219
+
220
+ const hit = await this.#probeScopedNumberForms(scope.keyTable, scope.level, scope.value, street, number)
221
+
222
+ if (hit) {
223
+ return { ...hit, matchedStreet: street, streetMatch: "canonical-alias" }
224
+ }
225
+ }
226
+ }
227
+
228
+ // Step 3: scoped 1-edit fuzzy recovery, unique confirmed street only.
229
+ if (canon.core.length < MIN_FUZZY_CORE_LENGTH) return null
230
+
231
+ for (const scope of scopes) {
232
+ let scopeRows: ScopedStreetAliasRow[]
233
+
234
+ if (tables.has(scope.aliasTable)) {
235
+ scopeRows = await this.#runner.query<ScopedStreetAliasRow>(
236
+ `SELECT street_canon, street AS street_norm FROM ${scope.aliasTable} WHERE scope = ? LIMIT ${FUZZY_SCOPE_ROW_LIMIT + 1}`,
237
+ [scope.value]
238
+ )
239
+ } else if (tables.has(scope.streetTable)) {
240
+ const rawRows = await this.#runner.query<{ street: string }>(
241
+ `SELECT street FROM ${scope.streetTable} WHERE scope = ? LIMIT ${FUZZY_SCOPE_ROW_LIMIT + 1}`,
242
+ [scope.value]
243
+ )
244
+
245
+ scopeRows = rawRows.map((row) => ({
246
+ street_canon: canonicalStreetKey(row.street, surfaceLocale).key,
247
+ street_norm: row.street,
248
+ }))
249
+ } else {
250
+ continue
251
+ }
252
+
253
+ const candidates = findFuzzyEdit1Streets(canon, scopeRows)
254
+
255
+ if (!candidates.length) continue
140
256
 
141
- if (answer) return answer
257
+ let unique: (Omit<AddressKeyAnswer, "matchedStreet" | "streetMatch"> & { matchedStreet: string }) | null = null
258
+ let confirmedCount = 0
259
+
260
+ for (const candidate of candidates) {
261
+ const hit = await this.#probeScopedNumberForms(scope.keyTable, scope.level, scope.value, candidate, number)
262
+
263
+ if (!hit) continue
264
+
265
+ confirmedCount++
266
+
267
+ if (confirmedCount > 1) return null
268
+
269
+ unique = { ...hit, matchedStreet: candidate }
270
+ }
271
+
272
+ if (confirmedCount === 1 && unique) {
273
+ return { ...unique, streetMatch: "fuzzy-edit1" }
142
274
  }
143
275
  }
144
276
 
145
277
  return null
146
278
  }
147
279
 
148
- async #ladder(query: AddressKeyQuery, street: string, number: string): Promise<AddressKeyAnswer | null> {
280
+ #aliasScopes(query: AddressKeyQuery): Array<{
281
+ level: AddressKeyLevel
282
+ keyTable: "key_postcode" | "key_locality"
283
+ aliasTable: "street_alias_postcode" | "street_alias_locality"
284
+ streetTable: "street_postcode" | "street_locality"
285
+ value: string
286
+ }> {
287
+ const scopes: Array<{
288
+ level: AddressKeyLevel
289
+ keyTable: "key_postcode" | "key_locality"
290
+ aliasTable: "street_alias_postcode" | "street_alias_locality"
291
+ streetTable: "street_postcode" | "street_locality"
292
+ value: string
293
+ }> = []
294
+
295
+ const postcode = addressPostcodeKey(this.#country, query.postcode)
296
+
297
+ if (postcode) {
298
+ scopes.push({
299
+ level: AddressKeyLevel.Postcode,
300
+ keyTable: "key_postcode",
301
+ aliasTable: "street_alias_postcode",
302
+ streetTable: "street_postcode",
303
+ value: postcode,
304
+ })
305
+ }
306
+
307
+ for (const locality of query.localities ?? []) {
308
+ const key = normalizeLocalityForKey(locality)
309
+
310
+ if (!key) continue
311
+
312
+ scopes.push({
313
+ level: AddressKeyLevel.Locality,
314
+ keyTable: "key_locality",
315
+ aliasTable: "street_alias_locality",
316
+ streetTable: "street_locality",
317
+ value: key,
318
+ })
319
+ }
320
+
321
+ return scopes
322
+ }
323
+
324
+ async #probeScopedNumberForms(
325
+ table: "key_postcode" | "key_locality",
326
+ level: AddressKeyLevel,
327
+ scope: string,
328
+ street: string,
329
+ number: string
330
+ ): Promise<Omit<AddressKeyAnswer, "matchedStreet" | "streetMatch"> | null> {
331
+ for (const form of houseNumberForms(number, this.#locale)) {
332
+ const hits = await this.#scoped(table, level, scope, street, form.number)
333
+
334
+ if (hits.length) {
335
+ return { level, hits, matchedNumber: form.number, numberMatch: form.match }
336
+ }
337
+ }
338
+
339
+ return null
340
+ }
341
+
342
+ async #ladder(
343
+ query: AddressKeyQuery,
344
+ street: string,
345
+ number: string
346
+ ): Promise<{ level: AddressKeyLevel; hits: AddressKeyHit[] } | null> {
149
347
  const postcode = addressPostcodeKey(this.#country, query.postcode)
150
348
 
151
349
  if (postcode) {
@@ -125,6 +125,10 @@ export class AddressKeyPointLookup implements AddressPointLookup {
125
125
  release,
126
126
  localityNorm: null,
127
127
  postcode: answer.level === AddressKeyLevel.Postcode ? (query.postcode?.trim() ?? null) : null,
128
+ matchedNumber: answer.matchedNumber,
129
+ numberMatch: answer.numberMatch,
130
+ matchedStreet: answer.matchedStreet,
131
+ streetMatch: answer.streetMatch,
128
132
  }
129
133
  }
130
134
  }
@@ -82,6 +82,16 @@ export interface AddressStreetTable {
82
82
  points: number
83
83
  }
84
84
 
85
+ /**
86
+ * One canonical street alias under one scope, mapping a build-time `street_canon` key
87
+ * to the stored normalized `street` key in `key_postcode` or `key_locality`.
88
+ */
89
+ export interface AddressStreetAliasTable {
90
+ scope: string
91
+ street_canon: string
92
+ street: string
93
+ }
94
+
85
95
  /**
86
96
  * The `lookup.db` schema, for `new DatabaseClient<AddressLookupDatabase>(...)`,
87
97
  * with the layer interface's `layer_manifest` and `layer_coverage` tables.
@@ -95,6 +105,8 @@ export interface AddressLookupDatabase extends layerschemadatabase {
95
105
  key_region: AddressRegionKeyTable
96
106
  street_postcode: AddressStreetTable
97
107
  street_locality: AddressStreetTable
108
+ street_alias_postcode: AddressStreetAliasTable
109
+ street_alias_locality: AddressStreetAliasTable
98
110
  }
99
111
 
100
112
  /**
@@ -111,6 +123,14 @@ export const ADDRESS_STREET_TABLES = ["street_postcode", "street_locality"] as c
111
123
 
112
124
  export type AddressStreetTableName = (typeof ADDRESS_STREET_TABLES)[number]
113
125
 
126
+ /**
127
+ * The canonical street alias tables, one per scoped level used for `canonical-alias`
128
+ * and scoped `fuzzy-edit1` lookup.
129
+ */
130
+ export const ADDRESS_STREET_ALIAS_TABLES = ["street_alias_postcode", "street_alias_locality"] as const
131
+
132
+ export type AddressStreetAliasTableName = (typeof ADDRESS_STREET_ALIAS_TABLES)[number]
133
+
114
134
  /**
115
135
  * One address point's full record, kept apart from the lookup file.
116
136
  */
@@ -238,6 +258,23 @@ export async function createAddressStreetTable(
238
258
  .execute()
239
259
  }
240
260
 
261
+ /**
262
+ * Creates one canonical street alias table, clustered on `(scope, street_canon, street)`.
263
+ */
264
+ export async function createAddressStreetAliasTable(
265
+ db: Kysely<AddressLookupDatabase>,
266
+ table: AddressStreetAliasTableName
267
+ ): Promise<void> {
268
+ await db.schema
269
+ .createTable(table)
270
+ .addColumn("scope", "text", (c) => c.notNull())
271
+ .addColumn("street_canon", "text", (c) => c.notNull())
272
+ .addColumn("street", "text", (c) => c.notNull())
273
+ .addPrimaryKeyConstraint(`${table}_pk`, ["scope", "street_canon", "street"])
274
+ .modifyEnd(sql`without rowid`)
275
+ .execute()
276
+ }
277
+
241
278
  /**
242
279
  * Creates the `address` detail table, keyed by `address_id`.
243
280
  *
@@ -1,10 +1,20 @@
1
1
  // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
2
  // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
3
 
4
+ import type { NumberMatchKind } from "@mailwoman/core/resolver"
4
5
  import { isJoinedHouseNumber } from "@mailwoman/match/address-point"
5
6
 
6
7
  import { streetKeyRulesOf, type StreetLocale } from "#labels/street/normalize"
7
8
 
9
+ /**
10
+ * One house-number form yielded by {@link houseNumberForms}, paired with how it
11
+ * relates to the query's normalized number.
12
+ */
13
+ export interface HouseNumberForm {
14
+ number: string
15
+ match: NumberMatchKind
16
+ }
17
+
8
18
  /**
9
19
  * The forms a normalized house number is probed under, the written form first,
10
20
  * each later form tried only after every earlier one missed.
@@ -26,15 +36,15 @@ import { streetKeyRulesOf, type StreetLocale } from "#labels/street/normalize"
26
36
  *
27
37
  * Both address readers call this, so they try one number in one order.
28
38
  */
29
- export function* houseNumberForms(number: string, locale: StreetLocale): Generator<string> {
30
- yield number
39
+ export function* houseNumberForms(number: string, locale: StreetLocale): Generator<HouseNumberForm> {
40
+ yield { number, match: "written" }
31
41
 
32
42
  const indexes = streetKeyRulesOf(locale).houseNumberRepetition
33
43
  const repetition = indexes ? repetitionForms(number, indexes) : null
34
44
 
35
45
  if (repetition) {
36
46
  for (const form of repetition) {
37
- if (form !== number) {
47
+ if (form.number !== number) {
38
48
  yield form
39
49
  }
40
50
  }
@@ -43,36 +53,39 @@ export function* houseNumberForms(number: string, locale: StreetLocale): Generat
43
53
  }
44
54
 
45
55
  if (isJoinedHouseNumber(number)) {
46
- yield number.replace("-", "")
56
+ yield { number: number.replace("-", ""), match: "respelled" }
47
57
  }
48
58
 
49
59
  const grid = /^([nesw])(?:\s+)?(\d+)$/.exec(number)
50
60
 
51
61
  if (grid) {
52
- yield number.includes(" ") ? `${grid[1]}${grid[2]}` : `${grid[1]} ${grid[2]}`
62
+ yield {
63
+ number: number.includes(" ") ? `${grid[1]}${grid[2]}` : `${grid[1]} ${grid[2]}`,
64
+ match: "respelled",
65
+ }
53
66
  }
54
67
 
55
68
  const low = /^(\d+[a-z]?)-\d+[a-z]?$/.exec(number)?.[1]
56
69
 
57
70
  if (low) {
58
- yield low
71
+ yield { number: low, match: "base" }
59
72
  }
60
73
 
61
74
  const joined = /^(\d+)\s+([a-z])$/.exec(number)
62
75
  const spaced = /^(\d+)([a-z])$/.exec(number)
63
76
 
64
77
  if (joined) {
65
- yield `${joined[1]}${joined[2]}`
66
- yield joined[1]!
78
+ yield { number: `${joined[1]}${joined[2]}`, match: "respelled" }
79
+ yield { number: joined[1]!, match: "base" }
67
80
  } else if (spaced) {
68
- yield `${spaced[1]} ${spaced[2]}`
69
- yield spaced[1]!
81
+ yield { number: `${spaced[1]} ${spaced[2]}`, match: "respelled" }
82
+ yield { number: spaced[1]!, match: "base" }
70
83
  }
71
84
 
72
85
  const base = streetKeyRulesOf(locale).houseNumberBase?.exec(number)?.[1]
73
86
 
74
87
  if (base) {
75
- yield base
88
+ yield { number: base, match: "base" }
76
89
  }
77
90
  }
78
91
 
@@ -82,7 +95,7 @@ export function* houseNumberForms(number: string, locale: StreetLocale): Generat
82
95
  *
83
96
  * An index is written as its word or its first letter, spaced or joined.
84
97
  */
85
- function repetitionForms(number: string, indexes: readonly string[]): string[] | null {
98
+ function repetitionForms(number: string, indexes: readonly string[]): HouseNumberForm[] | null {
86
99
  const match = /^(\d+)\s*([a-z]+)$/.exec(number)
87
100
  const digits = match?.[1]
88
101
  const suffix = match?.[2]
@@ -93,5 +106,11 @@ function repetitionForms(number: string, indexes: readonly string[]): string[] |
93
106
 
94
107
  if (!word) return null
95
108
 
96
- return [`${digits} ${word}`, `${digits}${word}`, `${digits} ${word[0]}`, `${digits}${word[0]}`, digits]
109
+ return [
110
+ { number: `${digits} ${word}`, match: "respelled" },
111
+ { number: `${digits}${word}`, match: "respelled" },
112
+ { number: `${digits} ${word[0]}`, match: "respelled" },
113
+ { number: `${digits}${word[0]}`, match: "respelled" },
114
+ { number: digits, match: "base" },
115
+ ]
97
116
  }
@@ -34,7 +34,7 @@
34
34
  * Standalone like the segment tier, wired through the ordered `spatialTiers` list.
35
35
  */
36
36
 
37
- import type { InterpolationLookup } from "@mailwoman/core/resolver"
37
+ import type { InterpolationLookup, StreetMatchKind } from "@mailwoman/core/resolver"
38
38
  import { haversine } from "@mailwoman/spatial/geometries/point/distance"
39
39
  import { DatabaseClient } from "@mailwoman/sqlite/client"
40
40
 
@@ -131,17 +131,25 @@ export class AddressPointInterpolator<
131
131
  if (!this.#byPostcode || !query.postcode) return this.#fallback?.find(query) ?? null
132
132
 
133
133
  // Key-variant ladder (see `streetKeyVariants`), the same probe order as the exact-point reader.
134
+ const variants = streetKeyVariants(query.street, EXTRACT_STREET_LOCALE)
134
135
  let rows: PointRow[] = []
136
+ let matchedStreet: RouteKey | null = null
137
+ let streetMatch: StreetMatchKind = "written"
135
138
 
136
- for (const variant of streetKeyVariants(query.street, EXTRACT_STREET_LOCALE)) {
137
- const streetKey = canonicalizeRouteKey(variant)
139
+ for (let i = 0; i < variants.length; i++) {
140
+ const streetKey = canonicalizeRouteKey(variants[i]!)
138
141
 
139
142
  rows = this.#byPostcode(query.postcode.trim(), streetKey, n)
140
143
 
141
- if (rows.length) break
144
+ if (rows.length) {
145
+ matchedStreet = streetKey
146
+ streetMatch = i === 0 ? "written" : "respelled"
147
+
148
+ break
149
+ }
142
150
  }
143
151
 
144
- const hit = rows.length >= 2 ? interpolateFromNeighbors(rows, n) : null
152
+ const hit = rows.length >= 2 && matchedStreet ? interpolateFromNeighbors(rows, n, matchedStreet, streetMatch) : null
145
153
 
146
154
  return hit ?? this.#fallback?.find(query) ?? null
147
155
  }
@@ -178,7 +186,12 @@ function anchorsByNumber(rows: readonly PointRow[]): NumberAnchor[] {
178
186
  .toSorted((a, b) => a.n - b.n)
179
187
  }
180
188
 
181
- function interpolateFromNeighbors(rows: readonly PointRow[], n: number): InterpolatedHit | null {
189
+ function interpolateFromNeighbors(
190
+ rows: readonly PointRow[],
191
+ n: number,
192
+ matchedStreet: string,
193
+ streetMatch: StreetMatchKind
194
+ ): InterpolatedHit | null {
182
195
  const anchors = anchorsByNumber(rows)
183
196
 
184
197
  // Nearest known number below and above the query.
@@ -210,6 +223,8 @@ function interpolateFromNeighbors(rows: readonly PointRow[], n: number): Interpo
210
223
  uncertaintyM: Math.round(spanM / 2),
211
224
  source: below.source,
212
225
  release: below.release,
226
+ matchedStreet,
227
+ streetMatch,
213
228
  }
214
229
  }
215
230
 
@@ -239,5 +254,7 @@ function interpolateFromNeighbors(rows: readonly PointRow[], n: number): Interpo
239
254
  uncertaintyM: Math.round(pairM + overshootM),
240
255
  source: near.source,
241
256
  release: near.release,
257
+ matchedStreet,
258
+ streetMatch,
242
259
  }
243
260
  }