@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
@@ -14,6 +14,7 @@
14
14
  import { tryParsingJSON } from "@mailwoman/core/values/json"
15
15
 
16
16
  import { BinaryFSTMatcher } from "#fst/binary-matcher"
17
+ import { BinaryFSTDel1Lookup } from "#fst/del1-sidecar"
17
18
  import { HEADER_SIZE, VERSION_WITH_METADATA } from "#fst/format"
18
19
  import type { FSTProvenance } from "#fst/types"
19
20
 
@@ -21,9 +22,20 @@ import type { FSTProvenance } from "#fst/types"
21
22
  * Opens an FST binary for matching, answering queries from the bytes in place.
22
23
  *
23
24
  * The matcher keeps a reference to `input`, so the caller mustn't modify it afterward.
25
+ * An optional `del1Sidecar` (raw `FD1\0` bytes or a loaded lookup) attaches fuzzy 1-edit recovery.
24
26
  */
25
- export function deserializeFSTWeb(input: ArrayBuffer | Uint8Array): BinaryFSTMatcher {
26
- return new BinaryFSTMatcher(input)
27
+ export function deserializeFSTWeb(
28
+ input: ArrayBuffer | Uint8Array,
29
+ del1Sidecar?: ArrayBuffer | Uint8Array | BinaryFSTDel1Lookup | null
30
+ ): BinaryFSTMatcher {
31
+ const lookup =
32
+ del1Sidecar == null
33
+ ? null
34
+ : del1Sidecar instanceof BinaryFSTDel1Lookup
35
+ ? del1Sidecar
36
+ : new BinaryFSTDel1Lookup(del1Sidecar)
37
+
38
+ return new BinaryFSTMatcher(input, lookup)
27
39
  }
28
40
 
29
41
  export function readFSTProvenanceWeb(input: ArrayBuffer | Uint8Array): FSTProvenance | null {
@@ -10,6 +10,7 @@
10
10
 
11
11
  import type { AncestrieMatch } from "@mailwoman/ancestrie"
12
12
 
13
+ import type { BinaryFSTDel1Lookup } from "#fst/del1-sidecar"
13
14
  import type { FSTContinuation, FSTQueryResult, PlaceEntry } from "#fst/types"
14
15
 
15
16
  interface FSTNode {
@@ -19,9 +20,14 @@ interface FSTNode {
19
20
 
20
21
  export class FSTMatcher {
21
22
  private nodes: FSTNode[]
23
+ /**
24
+ * Optional 1-delete fuzzy token sidecar paired with this matcher.
25
+ */
26
+ del1Sidecar: BinaryFSTDel1Lookup | null
22
27
 
23
- constructor(nodes: FSTNode[]) {
28
+ constructor(nodes: FSTNode[], del1Sidecar: BinaryFSTDel1Lookup | null = null) {
24
29
  this.nodes = nodes
30
+ this.del1Sidecar = del1Sidecar
25
31
  }
26
32
 
27
33
  get stateCount(): number {
package/lib/fst/types.ts CHANGED
@@ -7,6 +7,8 @@
7
7
 
8
8
  import type { PathBuilderLike } from "path-ts"
9
9
 
10
+ import type { BuildFSTDel1SidecarOpts } from "#fst/del1-sidecar"
11
+
10
12
  /**
11
13
  * One place that a token sequence in the FST accepts.
12
14
  */
@@ -169,6 +171,12 @@ export interface BuildFSTOpts {
169
171
  * A place reachable under several surfaces records each surface's own count.
170
172
  */
171
173
  surfaceCountryCounts?: ReadonlyMap<string, number>
174
+ /**
175
+ * When set, builds a companion `FD1\0` 1-delete fuzzy token sidecar from the resulting FST.
176
+ *
177
+ * Pass `true` for defaults or an options object to override thresholds.
178
+ */
179
+ buildDel1Sidecar?: boolean | BuildFSTDel1SidecarOpts
172
180
  onProgress?: (phase: string, detail?: string) => void
173
181
  }
174
182
 
package/lib/fst.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  export * from "#fst/autocomplete"
5
5
  export * from "#fst/binary-matcher"
6
6
  export * from "#fst/builder"
7
+ export * from "#fst/del1-sidecar"
7
8
  export * from "#fst/deserialize-web"
8
9
  export * from "#fst/format"
9
10
  export * from "#fst/freshness"
@@ -253,9 +253,20 @@ function addAdminRows(
253
253
  return { countryID, adminMap }
254
254
  }
255
255
 
256
+ /**
257
+ * The GeoNames feature codes of a populated place that no longer exists: abandoned (`PPLQ`),
258
+ * destroyed (`PPLW`), historical (`PPLH`) and a historical capital (`PPLCH`).
259
+ *
260
+ * A row with one of these codes is left out, because every row this step writes is a current locality.
261
+ * WOF marks its own record of such a place as ceased.
262
+ */
263
+ export const FORMER_PLACE_FEATURE_CODES: ReadonlySet<string> = new Set(["PPLQ", "PPLW", "PPLH", "PPLCH"])
264
+
256
265
  /**
257
266
  * Purges the GeoNames alias id range, then adds GeoNames `P`-class places
258
267
  * and their alternate names for `countries` to `db`.
268
+ *
269
+ * A place of {@link FORMER_PLACE_FEATURE_CODES} is left out.
259
270
  * It returns the number of places ingested.
260
271
  *
261
272
  * The caller must then rebuild `place_search` with `buildPlaceSearchFTS(db, { drop: true })`
@@ -310,6 +321,31 @@ export async function ingestGeonamesAliases(
310
321
 
311
322
  const populationInsert = db.prepare(`INSERT OR REPLACE INTO place_population (id, population) VALUES (?, ?)`)
312
323
 
324
+ const recordedPopulation = db.prepare(`SELECT 1 FROM place_population WHERE id = ? AND population > 0`)
325
+
326
+ /**
327
+ * The population this run wrote onto each matched record that had none.
328
+ */
329
+ const populationsAdded = new Map<number, number>()
330
+
331
+ /**
332
+ * Writes a matched place's population onto its record when the record's own sources gave it none.
333
+ *
334
+ * A record with a population of its own keeps it.
335
+ * A record with none takes the largest population among the GeoNames places that matched it,
336
+ * so a suburb read before its city doesn't decide the city record's value.
337
+ */
338
+ const addPopulation = (id: number, population: number): void => {
339
+ const added = populationsAdded.get(id)
340
+
341
+ if (population <= (added ?? 0)) return
342
+
343
+ if (added == null && recordedPopulation.get(id)) return
344
+
345
+ populationInsert.run(id, population)
346
+ populationsAdded.set(id, population)
347
+ }
348
+
313
349
  const ancestorInsert = db.prepare(
314
350
  `INSERT INTO ancestors (id, ancestor_id, ancestor_placetype, lastmodified) VALUES (?, ?, ?, 0)`
315
351
  )
@@ -382,7 +418,7 @@ export async function ingestGeonamesAliases(
382
418
  : { countryID: -1, adminMap: new Map<string, number>() }
383
419
 
384
420
  for await (const f of readUnquotedTSV(file)) {
385
- if (f[6] !== "P") continue
421
+ if (f[6] !== "P" || FORMER_PLACE_FEATURE_CODES.has(f[7] ?? "")) continue
386
422
  const lat = Number(f[4])
387
423
  const lon = Number(f[5])
388
424
 
@@ -408,6 +444,8 @@ export async function ingestGeonamesAliases(
408
444
  if (matched) {
409
445
  claim(matched, name)
410
446
 
447
+ addPopulation(matched.id, Number(f[14]) || 0)
448
+
411
449
  for (const raw of alternates) {
412
450
  const alt = cleanAlias(raw)
413
451
 
package/lib/index.ts CHANGED
@@ -35,6 +35,13 @@ export type {
35
35
  IntervalLabel,
36
36
  } from "#candidate/ancestors/schema"
37
37
 
38
+ export {
39
+ CANDIDATE_DEL1_TABLE,
40
+ createCandidateDel1,
41
+ type CandidateDel1Result,
42
+ type CandidateDel1Table,
43
+ } from "#candidate/del1"
44
+
38
45
  export { CANDIDATE_FTS_TABLE, createCandidateFTS } from "#candidate/fts"
39
46
 
40
47
  export {
@@ -60,8 +67,20 @@ export { SQLiteStreetNameLookup, type SQLiteStreetNameLookupOpts } from "#labels
60
67
 
61
68
  export { type GeonamesIngestProgress, ingestGeonamesAliases, purgeGeonamesAliasRange } from "#geonames/aliases"
62
69
 
63
- export { ADDRESS_POINT_COLUMNS, createAddressPointIndexes, createAddressPointTable } from "#address/point/schema"
64
- export type { AddressPointDatabase, AddressPointTable } from "#address/point/schema"
70
+ export {
71
+ ADDRESS_POINT_COLUMNS,
72
+ createAddressPointIndexes,
73
+ createAddressPointTable,
74
+ createStreetScopeIndex,
75
+ createStreetScopeIndexTable,
76
+ } from "#address/point/schema"
77
+
78
+ export type {
79
+ AddressPointDatabase,
80
+ AddressPointTable,
81
+ StreetScopeIndexHandle,
82
+ StreetScopeIndexTable,
83
+ } from "#address/point/schema"
65
84
 
66
85
  export {
67
86
  WOFPostalCityAliasLookup,
@@ -128,6 +147,7 @@ export { readLatestAddressLayerManifest, readLatestAddressLayerManifests } from
128
147
  export {
129
148
  STREET_CENTROID_COLUMNS,
130
149
  createStreetCentroidIndexes,
150
+ createStreetCentroidScopeIndex,
131
151
  createStreetCentroidTable,
132
152
  } from "#labels/street/centroid/schema"
133
153
 
@@ -0,0 +1,333 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * Build-time canonical street keys and scoped 1-edit candidate filtering.
6
+ *
7
+ * Unlike `normalizeStreetForKeyLocale`, which preserves language-specific street words
8
+ * and drops apostrophes without inserting spaces, `canonicalStreetKey` maps thoroughfare types
9
+ * into semantic classes, spaces apostrophes before stripping post-type Romance connectors,
10
+ * and keeps distinct classes apart (`Calle Mayor` → `way mayor`, `Plaza Mayor` → `square mayor`).
11
+ */
12
+
13
+ import { stripLeadingStreetConnector } from "@mailwoman/codex/labels/street/connectors"
14
+ import {
15
+ isThoroughfareClass,
16
+ type ThoroughfareClass,
17
+ thoroughfareClassOf,
18
+ } from "@mailwoman/codex/labels/street/thoroughfare-classes"
19
+ import { AbbreviationToDirectional } from "@mailwoman/codex/us"
20
+ import { oneEditDistance } from "@mailwoman/match/comparators"
21
+
22
+ import {
23
+ normalizeStreetForKey,
24
+ normalizeStreetForKeyLocale,
25
+ streetKeyRulesOf,
26
+ streetLocaleForSurface,
27
+ type StreetLocale,
28
+ } from "#labels/street/normalize"
29
+
30
+ /**
31
+ * Maximum distinct streets in one postcode or locality scope that scoped 1-edit fuzzy lookup scans.
32
+ *
33
+ * Scopes above this cap abstain so lookups remain sub-millisecond.
34
+ */
35
+ export const FUZZY_SCOPE_ROW_LIMIT = 1500
36
+
37
+ /**
38
+ * Minimum character length of the proper-name core required before 1-edit fuzzy recovery activates.
39
+ *
40
+ * Below 5 characters a single edit collides with unrelated street names.
41
+ */
42
+ export const MIN_FUZZY_CORE_LENGTH = 5
43
+
44
+ /**
45
+ * Structured canonical street key derived from a raw street name and street locale.
46
+ */
47
+ export interface CanonicalStreetKey {
48
+ /**
49
+ * Build-time key stored in `street_canon`: `"<thoroughfareClass> <core>"`
50
+ * when a thoroughfare class was recognized, or `core` otherwise.
51
+ */
52
+ key: string
53
+ /**
54
+ * Semantic thoroughfare equivalence class when recognized, else `null`.
55
+ */
56
+ thoroughfareClass: ThoroughfareClass | null
57
+ /**
58
+ * Proper-name core with leading or trailing thoroughfare type and post-type
59
+ * grammatical connectors stripped.
60
+ */
61
+ core: string
62
+ }
63
+
64
+ /**
65
+ * One candidate row from `street_scope_index` or `street_alias_*` scanned during scoped 1-edit fuzzy lookup.
66
+ */
67
+ export interface ScopedStreetAliasRow {
68
+ street_canon: string
69
+ street_norm: string
70
+ }
71
+
72
+ const DIRECTIONAL_WORDS: ReadonlySet<string> = new Set(
73
+ [...AbbreviationToDirectional.values()].map((name) => name.toLowerCase().replaceAll(" ", ""))
74
+ )
75
+
76
+ /**
77
+ * Fused German and Dutch street-type suffixes, longest first, paired with their thoroughfare class.
78
+ *
79
+ * A fused suffix is split only when at least 3 characters of stem precede it,
80
+ * so standalone type words aren't reduced to empty cores.
81
+ */
82
+ const DE_NL_FUSED_SUFFIXES: ReadonlyArray<readonly [suffix: string, cls: ThoroughfareClass]> = [
83
+ ["strasse", "way"],
84
+ ["straat", "way"],
85
+ ["platz", "square"],
86
+ ["plein", "square"],
87
+ ["gasse", "alley"],
88
+ ["steeg", "alley"],
89
+ ["allee", "avenue"],
90
+ ["laan", "avenue"],
91
+ ["gracht", "promenade"],
92
+ ["singel", "promenade"],
93
+ ["kade", "promenade"],
94
+ ["dreef", "road"],
95
+ ["weg", "road"],
96
+ ["str", "way"],
97
+ ]
98
+
99
+ const MIN_FUSED_STEM_LENGTH = 3
100
+
101
+ /**
102
+ * Minimum token count for an English street name to hold a proper name, a thoroughfare type,
103
+ * and a trailing directional (`Main Street North`).
104
+ */
105
+ const MIN_TOKENS_WITH_TRAILING_DIRECTIONAL = 3
106
+
107
+ /**
108
+ * Minimum token count for a two-word leading thoroughfare type (`Rond-Point` split on its hyphen)
109
+ * followed by at least one proper-name token.
110
+ */
111
+ const MIN_TOKENS_FOR_TWO_WORD_LEAD_TYPE = 3
112
+
113
+ /**
114
+ * Folds a raw Latin street string into space-separated lowercase ASCII tokens, replacing
115
+ * apostrophes, slashes, hyphens, and punctuation with spaces before connector stripping
116
+ * so elisions such as `d'Enric` tokenize as `["d", "enric"]`.
117
+ */
118
+ function canonicalFoldTokens(streetRaw: string): string[] {
119
+ const cleaned = streetRaw
120
+ // Normalize Spanish `P.º` before stripping periods so it stays `po` (`paseo`) rather than `p o`.
121
+ .replaceAll(/([pP])\.º/gu, "$1o")
122
+ .normalize("NFKD")
123
+ .replaceAll(/[\u0300-\u036F]/gu, "")
124
+ .toLowerCase()
125
+ .replaceAll("ß", "ss")
126
+ .replaceAll("ł", "l")
127
+ .replaceAll("đ", "d")
128
+ .replaceAll("ð", "d")
129
+ .replaceAll(/['’‘`ʻʼ/.,-]+/gu, " ")
130
+ .replaceAll(/\s+/gu, " ")
131
+ .trim()
132
+
133
+ return cleaned ? cleaned.split(" ") : []
134
+ }
135
+
136
+ function canonicalFromTrailingEnglish(streetRaw: string, locale: StreetLocale): CanonicalStreetKey {
137
+ const normalized = normalizeStreetForKey(streetRaw)
138
+
139
+ if (!normalized) return { key: "", thoroughfareClass: null, core: "" }
140
+
141
+ const tokens = normalized.split(" ").filter((t) => t.length > 0)
142
+
143
+ if (!tokens.length) return { key: "", thoroughfareClass: null, core: "" }
144
+
145
+ // Check the trailing thoroughfare word (last token, or second-to-last when a directional trails).
146
+ if (tokens.length >= 2) {
147
+ const lastIdx = tokens.length - 1
148
+
149
+ const typeIdx =
150
+ tokens.length >= MIN_TOKENS_WITH_TRAILING_DIRECTIONAL && DIRECTIONAL_WORDS.has(tokens[lastIdx]!)
151
+ ? lastIdx - 1
152
+ : lastIdx
153
+
154
+ const cls = thoroughfareClassOf(tokens[typeIdx]!, locale)
155
+
156
+ if (cls) {
157
+ const remaining = tokens.filter((_, idx) => idx !== typeIdx)
158
+
159
+ if (remaining.length) {
160
+ const core = remaining.join(" ")
161
+
162
+ return { key: `${cls} ${core}`, thoroughfareClass: cls, core }
163
+ }
164
+ }
165
+ }
166
+
167
+ const core = tokens.join(" ")
168
+
169
+ return { key: core, thoroughfareClass: null, core }
170
+ }
171
+
172
+ function canonicalFromGermanic(streetRaw: string, locale: StreetLocale): CanonicalStreetKey {
173
+ const tokens = canonicalFoldTokens(streetRaw)
174
+
175
+ if (!tokens.length) return { key: "", thoroughfareClass: null, core: "" }
176
+
177
+ // Standalone leading type (`Straße des 17. Juni`).
178
+ if (tokens.length >= 2) {
179
+ const leadClass = thoroughfareClassOf(tokens[0]!, locale)
180
+
181
+ if (leadClass) {
182
+ const core = tokens.slice(1).join(" ")
183
+
184
+ return { key: `${leadClass} ${core}`, thoroughfareClass: leadClass, core }
185
+ }
186
+
187
+ // Standalone trailing type (`Teschener Weg`).
188
+ const tailClass = thoroughfareClassOf(tokens.at(-1)!, locale)
189
+
190
+ if (tailClass) {
191
+ const core = tokens.slice(0, -1).join(" ")
192
+
193
+ return { key: `${tailClass} ${core}`, thoroughfareClass: tailClass, core }
194
+ }
195
+ }
196
+
197
+ // Fused compound suffix (`Hauptstraße`, `Krankenhausstr.`, `Kalverstraat`).
198
+ const last = tokens.at(-1)!
199
+
200
+ for (const [suffix, cls] of DE_NL_FUSED_SUFFIXES) {
201
+ if (last.endsWith(suffix) && last.length - suffix.length >= MIN_FUSED_STEM_LENGTH) {
202
+ const stem = last.slice(0, -suffix.length)
203
+ const coreTokens = [...tokens.slice(0, -1), stem]
204
+ const core = coreTokens.join(" ")
205
+
206
+ return { key: `${cls} ${core}`, thoroughfareClass: cls, core }
207
+ }
208
+ }
209
+
210
+ const core = tokens.join(" ")
211
+
212
+ return { key: core, thoroughfareClass: null, core }
213
+ }
214
+
215
+ /**
216
+ * Computes the build-time canonical street key for `streetRaw` under `locale`.
217
+ *
218
+ * The function maps leading thoroughfare types to semantic classes from `@mailwoman/codex`.
219
+ * Post-type grammatical connectors are stripped only immediately after a recognized
220
+ * leading thoroughfare type and only when at least one proper-name token remains.
221
+ *
222
+ * Apostrophes are normalized to spaces before connector stripping so `Calle d'Enric Granados`
223
+ * and `Carrer d'Enric Granados` both canonicalize to `way enric granados`.
224
+ */
225
+ export function canonicalStreetKey(streetRaw: string, locale: StreetLocale): CanonicalStreetKey {
226
+ if (!streetRaw.trim()) return { key: "", thoroughfareClass: null, core: "" }
227
+
228
+ const effectiveLocale = streetLocaleForSurface(streetRaw, locale)
229
+ const { canonicalMorphology } = streetKeyRulesOf(effectiveLocale)
230
+
231
+ if (canonicalMorphology === "han") {
232
+ const folded = String(normalizeStreetForKeyLocale(streetRaw, effectiveLocale))
233
+
234
+ return { key: folded, thoroughfareClass: null, core: folded }
235
+ }
236
+
237
+ if (canonicalMorphology === "trailing-english") {
238
+ return canonicalFromTrailingEnglish(streetRaw, effectiveLocale)
239
+ }
240
+
241
+ if (canonicalMorphology === "germanic-fused") {
242
+ return canonicalFromGermanic(streetRaw, effectiveLocale)
243
+ }
244
+
245
+ const tokens = canonicalFoldTokens(streetRaw)
246
+
247
+ if (!tokens.length) return { key: "", thoroughfareClass: null, core: "" }
248
+
249
+ // Two-token hyphen-split French `Rond-Point` leading type.
250
+ if (tokens.length >= MIN_TOKENS_FOR_TWO_WORD_LEAD_TYPE && tokens[0] === "rond" && tokens[1] === "point") {
251
+ const coreTokens = stripLeadingStreetConnector(tokens.slice(2))
252
+ const core = coreTokens.join(" ")
253
+
254
+ return { key: `roundabout ${core}`, thoroughfareClass: "roundabout", core }
255
+ }
256
+
257
+ if (tokens.length >= 2) {
258
+ const leadClass = thoroughfareClassOf(tokens[0]!, effectiveLocale)
259
+
260
+ if (leadClass) {
261
+ const coreTokens = stripLeadingStreetConnector(tokens.slice(1))
262
+ const core = coreTokens.join(" ")
263
+
264
+ return { key: `${leadClass} ${core}`, thoroughfareClass: leadClass, core }
265
+ }
266
+ }
267
+
268
+ // No recognized leading thoroughfare type: preserve leading particles (`De Gaulle`).
269
+ const core = tokens.join(" ")
270
+
271
+ return { key: core, thoroughfareClass: null, core }
272
+ }
273
+
274
+ /**
275
+ * Parses a stored `street_canon` string back into its thoroughfare class and proper-name core.
276
+ *
277
+ * @public
278
+ */
279
+ export function parseCanonicalStreetKey(streetCanon: string): CanonicalStreetKey {
280
+ const trimmed = streetCanon.trim()
281
+
282
+ if (!trimmed) return { key: "", thoroughfareClass: null, core: "" }
283
+
284
+ const space = trimmed.indexOf(" ")
285
+
286
+ if (space > 0) {
287
+ const head = trimmed.slice(0, space)
288
+ const rest = trimmed.slice(space + 1)
289
+
290
+ if (rest && isThoroughfareClass(head)) {
291
+ return { key: trimmed, thoroughfareClass: head, core: rest }
292
+ }
293
+ }
294
+
295
+ return { key: trimmed, thoroughfareClass: null, core: trimmed }
296
+ }
297
+
298
+ /**
299
+ * Filters a contiguous scope scan of `street_canon` / `street_norm` rows to the
300
+ * distinct `street_norm` candidates whose proper-name core is within 1 restricted
301
+ * Damerau-Levenshtein edit of `queryCanon.core`.
302
+ *
303
+ * Abstains (returns `[]`) when `queryCanon.core.length < MIN_FUZZY_CORE_LENGTH`
304
+ * or when `scopeRows.length > FUZZY_SCOPE_ROW_LIMIT`.
305
+ * When the query stated a thoroughfare class, only candidates in the same class qualify.
306
+ */
307
+ export function findFuzzyEdit1Streets(
308
+ queryCanon: CanonicalStreetKey,
309
+ scopeRows: readonly ScopedStreetAliasRow[]
310
+ ): string[] {
311
+ if (queryCanon.core.length < MIN_FUZZY_CORE_LENGTH) return []
312
+
313
+ if (scopeRows.length > FUZZY_SCOPE_ROW_LIMIT) return []
314
+
315
+ const qCore = queryCanon.core
316
+ const qLen = qCore.length
317
+ const qClass = queryCanon.thoroughfareClass
318
+ const matched = new Set<string>()
319
+
320
+ for (const row of scopeRows) {
321
+ const cand = parseCanonicalStreetKey(row.street_canon)
322
+
323
+ if (qClass !== null && cand.thoroughfareClass !== qClass) continue
324
+
325
+ if (Math.abs(qLen - cand.core.length) > 1) continue
326
+
327
+ if (oneEditDistance(qCore, cand.core) === 1) {
328
+ matched.add(row.street_norm)
329
+ }
330
+ }
331
+
332
+ return [...matched]
333
+ }
@@ -8,7 +8,12 @@
8
8
 
9
9
  import type { Kysely } from "kysely"
10
10
 
11
- import type { NameKey, StreetKey } from "#labels/street/normalize"
11
+ import {
12
+ populateStreetScopeIndex,
13
+ type StreetScopeIndexHandle,
14
+ type StreetScopeIndexTable,
15
+ } from "#address/point/schema"
16
+ import type { NameKey, StreetKey, StreetLocale } from "#labels/street/normalize"
12
17
 
13
18
  /**
14
19
  * One row per street, postcode and commune.
@@ -83,6 +88,7 @@ export interface StreetCentroidTable {
83
88
  */
84
89
  export interface StreetCentroidDatabase {
85
90
  street_centroid: StreetCentroidTable
91
+ street_scope_index?: StreetScopeIndexTable
86
92
  }
87
93
 
88
94
  /**
@@ -147,3 +153,19 @@ export async function createStreetCentroidIndexes(db: Kysely<StreetCentroidDatab
147
153
 
148
154
  await db.schema.createIndex("idx_sc_name").on("street_centroid").columns(["name_key"]).execute()
149
155
  }
156
+
157
+ /**
158
+ * Creates and populates `street_scope_index` from `street_centroid`, keying postcode
159
+ * scopes with `addressPostcodeKey` and locality scopes from `locality_base`.
160
+ */
161
+ export async function createStreetCentroidScopeIndex(
162
+ db: StreetScopeIndexHandle,
163
+ streetLocale: StreetLocale,
164
+ options?: { country?: string }
165
+ ): Promise<void> {
166
+ await populateStreetScopeIndex(db, streetLocale, {
167
+ sourceTable: "street_centroid",
168
+ localityColumn: "locality_base",
169
+ ...options,
170
+ })
171
+ }
@@ -7,7 +7,7 @@
7
7
  * and linear interpolation along the segment polyline.
8
8
  */
9
9
 
10
- import type { InterpolationLookup } from "@mailwoman/core/resolver"
10
+ import type { InterpolationLookup, StreetMatchKind } from "@mailwoman/core/resolver"
11
11
  import { parseJSONStrict, stringifyJSON } from "@mailwoman/core/values/json"
12
12
  import { haversine } from "@mailwoman/spatial/geometries/point/distance"
13
13
  import { clampFraction, pointAlong } from "@mailwoman/spatial/polyline"
@@ -65,6 +65,16 @@ export interface InterpolatedHit {
65
65
  source: string
66
66
 
67
67
  release: string
68
+
69
+ /**
70
+ * The stored street key that answered.
71
+ */
72
+ matchedStreet: string
73
+
74
+ /**
75
+ * How {@link matchedStreet} relates to the query's primary normalized street key.
76
+ */
77
+ streetMatch: StreetMatchKind
68
78
  }
69
79
 
70
80
  export interface InterpolationQuery {
@@ -235,15 +245,15 @@ export class StreetInterpolator<
235
245
  const variants = streetKeyVariants(query.street, SEGMENT_STREET_LOCALE)
236
246
 
237
247
  // A variant advances the ladder when it produces no answer rather than merely no rows.
238
- for (const variant of variants) {
239
- const streetNorm = canonicalizeRouteKey(variant)
248
+ for (let i = 0; i < variants.length; i++) {
249
+ const streetNorm = canonicalizeRouteKey(variants[i]!)
240
250
 
241
251
  // A ZIP that scopes to no candidate is a miss rather than a statewide guess.
242
252
  const rows = query.postcode
243
253
  ? this.#byPostcode(query.postcode.trim(), streetNorm, n, n)
244
254
  : this.#byStreet(streetNorm, n, n)
245
255
 
246
- const hit = this.#answerFromRows(rows, n, query)
256
+ const hit = this.#answerFromRows(rows, n, query, streetNorm, i === 0 ? "written" : "respelled")
247
257
 
248
258
  if (hit) return hit
249
259
  }
@@ -272,13 +282,27 @@ export class StreetInterpolator<
272
282
 
273
283
  if (stored.length !== 1) return null
274
284
 
275
- return this.#answerFromRows(this.#byPostcode(postcode, stored[0]!.street_norm as RouteKey, n, n), n, query)
285
+ const matchedStreet = stored[0]!.street_norm as RouteKey
286
+
287
+ return this.#answerFromRows(
288
+ this.#byPostcode(postcode, matchedStreet, n, n),
289
+ n,
290
+ query,
291
+ matchedStreet,
292
+ "directional-relaxed"
293
+ )
276
294
  }
277
295
 
278
296
  /**
279
297
  * Resolve one key variant's covering rows to an answer, or null when the rows do not support one.
280
298
  */
281
- #answerFromRows(rows: SegmentRow[], n: number, query: InterpolationQuery): InterpolatedHit | null {
299
+ #answerFromRows(
300
+ rows: SegmentRow[],
301
+ n: number,
302
+ query: InterpolationQuery,
303
+ matchedStreet: string,
304
+ streetMatch: StreetMatchKind
305
+ ): InterpolatedHit | null {
282
306
  if (!rows.length) return null
283
307
 
284
308
  // Parity preference: exact side first, then `mixed`, then the opposite side as a flagged fallback.
@@ -325,6 +349,8 @@ export class StreetInterpolator<
325
349
  uncertaintyM: Math.round((lengthKm * 1000) / 2),
326
350
  source: best.source,
327
351
  release: best.release,
352
+ matchedStreet,
353
+ streetMatch,
328
354
  }
329
355
  }
330
356