@mailwoman/resolver-wof-sqlite 7.2.0 → 7.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/address-point-interpolation.ts +207 -0
  2. package/address-point-schema.ts +107 -0
  3. package/address-point.ts +122 -0
  4. package/ancestry-backfill.ts +205 -0
  5. package/ancestry.ts +70 -0
  6. package/build-candidate.ts +351 -0
  7. package/build-slim.ts +394 -0
  8. package/candidate-fts.ts +43 -0
  9. package/candidate-lookup.ts +382 -0
  10. package/candidate-schema.ts +166 -0
  11. package/coincident-roles.ts +240 -0
  12. package/convention.ts +152 -0
  13. package/fst-autocomplete.ts +187 -0
  14. package/fst-builder.ts +291 -0
  15. package/fst-deserialize-web.ts +164 -0
  16. package/fst-matcher.ts +150 -0
  17. package/fst-serialize.ts +311 -0
  18. package/fst-types.ts +78 -0
  19. package/fts.ts +318 -0
  20. package/geo.ts +140 -0
  21. package/geonames-aliases.ts +317 -0
  22. package/geonames-postal.ts +150 -0
  23. package/index.ts +117 -0
  24. package/interpolation.ts +232 -0
  25. package/lookup.ts +1498 -0
  26. package/package.json +168 -82
  27. package/poi-lookup.ts +319 -0
  28. package/poi-schema.ts +147 -0
  29. package/postal-city-alias-lookup.ts +89 -0
  30. package/postal-city-alias-schema.ts +75 -0
  31. package/postal-city-candidate-schema.ts +81 -0
  32. package/postcode-point-lookup.ts +64 -0
  33. package/reverse.ts +429 -0
  34. package/schema.ts +176 -0
  35. package/sharding.ts +235 -0
  36. package/sqlite-convention-source.ts +61 -0
  37. package/sqlite-utils.ts +25 -0
  38. package/street-centroid-schema.ts +124 -0
  39. package/street-centroid.ts +124 -0
  40. package/street-morphology-fst-builder.ts +230 -0
  41. package/street-name-lookup.ts +101 -0
  42. package/street-normalize.ts +302 -0
  43. package/street-segment-schema.ts +104 -0
  44. package/types.ts +164 -0
  45. package/unified-schema.ts +171 -0
package/lookup.ts ADDED
@@ -0,0 +1,1498 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * `WOFSqlitePlaceLookup` — the resolver implementation backed by `node:sqlite` + a Kysely-typed
7
+ * query layer where the queries are non-trivial, and raw SQL where they aren't (FTS5 MATCH, the
8
+ * FTS index build).
9
+ *
10
+ * See `docs/plan/phases/PHASE_4_2_wof_sqlite.md` for the design rationale.
11
+ */
12
+
13
+ import { DatabaseSync, type SQLInputValue } from "node:sqlite"
14
+
15
+ import { SqliteDialect } from "@mailwoman/core/kysley/dialect"
16
+ import { expandPlacetypeFilter, type Ancestor, type CoincidentLocality } from "@mailwoman/resolver"
17
+ import { Kysely } from "kysely"
18
+
19
+ import { ancestorLineage } from "./ancestry.ts"
20
+ import { COINCIDENT_ROLES_TABLE, coincidentRolesExists } from "./coincident-roles.ts"
21
+ import {
22
+ ADDRESS_CONVENTION_TABLE,
23
+ resolveConvention,
24
+ SeedConventionSource,
25
+ type Convention,
26
+ type ConventionSource,
27
+ type ResolvedConvention,
28
+ type Strategy,
29
+ } from "./convention.ts"
30
+ import {
31
+ aliasBagExactMatch,
32
+ buildPlaceSearchFTS,
33
+ PLACE_BBOX_TABLE,
34
+ PLACE_POPULATION_TABLE,
35
+ placeBboxExists,
36
+ placePopulationExists,
37
+ placeSearchFTSExists,
38
+ } from "./fts.ts"
39
+ import { bboxAround, haversineKm } from "./geo.ts"
40
+ import type { WOFPostalCityAliasLookup } from "./postal-city-alias-lookup.ts"
41
+ import type { WOFDatabase } from "./schema.ts"
42
+ import {
43
+ pickShardForPlacetype,
44
+ pickShardsForPlacetype,
45
+ resolveShards,
46
+ type ResolvedShard,
47
+ type ShardConfig,
48
+ } from "./sharding.ts"
49
+ import { SqliteConventionSource } from "./sqlite-convention-source.ts"
50
+ import type { FindPlaceQuery, PlaceCandidate, PlaceLookup, WOFPlacetype } from "./types.ts"
51
+
52
+ export interface WOFSqlitePlaceLookupOpts {
53
+ /**
54
+ * Path to the WOF SQLite distribution on disk. Mutually exclusive with `database`.
55
+ *
56
+ * **Single string** — opens that one DB as the main shard.
57
+ *
58
+ * **Array** — opens the first entry as main, then ATTACHes each subsequent entry as a separate SQLite schema. Schema
59
+ * names are derived from the filename (`whosonfirst-data-postalcode- us-latest.db` → `postalcode_us`); override with
60
+ * `ShardConfig.schemaName` when the filename doesn't follow WOF convention. See `sharding.ts` for the derivation
61
+ * rules.
62
+ *
63
+ * Routing: queries with a `placetype` matching a shard's name (or explicit `placetypes` hint) are sent to that shard;
64
+ * everything else hits main. Cross-shard UNION is NOT done — BM25 isn't comparable across separately-indexed
65
+ * corpora.
66
+ */
67
+ databasePath?: string | ReadonlyArray<string | ShardConfig>
68
+ /**
69
+ * Pre-opened DatabaseSync — primarily for tests against an inline fixture DB. Mutually exclusive with `databasePath`.
70
+ * Multi-shard requires `databasePath` (so the lookup owns the ATTACH).
71
+ */
72
+ database?: DatabaseSync
73
+ /**
74
+ * If true, build the FTS5 `place_search` virtual table on construction if it doesn't already exist. The upstream WOF
75
+ * distribution does NOT ship FTS5, so callers either set this once on first open or pre-build it via the
76
+ * operator-side CLI documented in the README. Default false — the resolver assumes the index already exists and
77
+ * errors loudly if it doesn't.
78
+ *
79
+ * With multi-shard, `buildFTS: true` builds the index on the **main** shard only. Other shards must be pre-built via
80
+ * `mailwoman gazetteer build fts` — operator script for predictable cost.
81
+ */
82
+ buildFTS?: boolean
83
+ /**
84
+ * Geographic Rule Engine convention source (Direction E, #289). Per-WOF-polygon resolution profiles, either as a
85
+ * ready `ConventionSource` or a plain `{ wofID: Convention }` seed map. Default empty — every query rides
86
+ * `WORLD_DEFAULT` (the EU coordinate-first behavior). JP/KR/TW add rows; #290 wires a build-from-source sqlite-backed
87
+ * source here.
88
+ */
89
+ conventions?: ConventionSource | Record<number, Convention>
90
+ /**
91
+ * Opt-in postal-city alias reader (#475). When supplied, the coordinate-first locality scorer treats an observed
92
+ * `postal_city` ("Antioch", postcode 37013) as a name-match alias for the geographic locality the postcode sits in
93
+ * ("Nashville"), recovering the chronic postal-vs- geographic-city mismatch. Absent (the default), the resolver is
94
+ * byte-identical — every alias code path is gated on this being non-null, so an unprovided reader changes no score.
95
+ */
96
+ postalCityAliases?: WOFPostalCityAliasLookup
97
+ }
98
+
99
+ /**
100
+ * Ranking weights for `findPlace`. Tweakable per-instance but defaults match the values declared in the Phase 4.2 plan
101
+ * doc.
102
+ */
103
+ export interface RankingWeights {
104
+ /** Boost when the candidate's placetype matches an explicit `placetype` filter. */
105
+ placetypeMatchBoost: number
106
+ /** Boost when the candidate is a locality and no explicit placetype was requested. */
107
+ localityImplicitBoost: number
108
+ /** Boost when the candidate's country matches an explicit `country` filter. */
109
+ countryMatchBoost: number
110
+ /** Boost when the candidate is a direct child of the requested `parentID`. */
111
+ directChildBoost: number
112
+ /** Boost when the candidate is a transitive descendant of the requested `parentID`. */
113
+ descendantBoost: number
114
+ /** Multiplier on the length-penalty term (penalizes much-longer-than-query names). */
115
+ lengthPenaltyWeight: number
116
+ /**
117
+ * Magnitude of the proximity boost when the query carries `near`. The contribution is `proximityBoost / (1 +
118
+ * distanceKm / proximityScaleKm)` — at distance 0 the boost is full magnitude, at `proximityScaleKm` it's half,
119
+ * decaying further with distance. Default tuned so proximity can overcome a typical FTS rank tie but not dominate a
120
+ * strong text match.
121
+ */
122
+ proximityBoost: number
123
+ /**
124
+ * Magnitude of the bias-hint term inside the exact-tier PROMINENCE sort (the `bias`/viewport path). Deliberately
125
+ * population-scale (default = populationBoost) so a candidate near the map view / the user beats a distant-but-bigger
126
+ * namesake — "the map view wins" is the feature; same-region ties (all candidates far from every hint) still fall to
127
+ * population.
128
+ */
129
+ biasBoost: number
130
+ /** Distance (km) at which the proximity boost halves. Tune to the typical query radius. */
131
+ proximityScaleKm: number
132
+ /**
133
+ * Magnitude of the population boost when the candidate has a known `wof:population`. The contribution is
134
+ * `populationBoost * log10(1 + population) / populationScaleLog10`, capped at `populationBoost`. WOF only carries
135
+ * population for ~15% of localities (mostly larger ones); places without it get +0 (never a penalty). Default tuned
136
+ * so the famous Springfield, IL (pop ~112k) gets ~0.42 boost — enough to nudge past tiny same-name peers.
137
+ */
138
+ populationBoost: number
139
+ /**
140
+ * Population (in log10) at which the boost reaches its full magnitude. Default 6 — i.e. a population of 1,000,000
141
+ * gives `populationBoost` exactly. Larger populations cap at the same value (no compounding effect for megacities).
142
+ */
143
+ populationScaleLog10: number
144
+ /**
145
+ * Tier candidates with an EXACT name/alias match above candidates that only match partially, BEFORE the weighted-sum
146
+ * score is consulted. Default true.
147
+ *
148
+ * Why this is needed (and why it ALIGNS with — rather than overrides — the population/importance signal): the
149
+ * weighted sum adds population as a large additive boost (`populationBoost`, up to +4) so that famous places surface
150
+ * for unambiguous full-name queries. But population is a _prominence prior_ — its job is to break ties among
151
+ * candidates that match the query EQUALLY WELL (e.g. "Springfield" → Springfield IL over Springfield MA, both exact
152
+ * name matches). It was never meant to promote a place that matches the query WORSE. For a 2-letter region
153
+ * abbreviation that backfires: querying "ME" returns Maine (which has the exact alias `ME`) AND Missouri/
154
+ * Michigan/etc. (which do not), and Missouri's larger population (+4) overcomes Maine's bm25 edge — so "Portland, ME"
155
+ * resolves its region to Missouri and the locality then cascades to the wrong state. Tiering restores the intended
156
+ * ordering: **match quality is the primary key, prominence (population) the secondary key WITHIN a tier.**
157
+ * Springfield-IL-over-MA still works (both exact → same tier → population decides); ME→Maine now works (only Maine is
158
+ * exact → higher tier → population never gets to override it). See
159
+ * docs/articles/evals/resolver-geo/2026-05-30-resolver-exact-match.md.
160
+ *
161
+ * Note: tiering re-ranks within the over-fetched candidate window (`limit * 4`); a pathological exact match that
162
+ * falls outside that window is not rescued. For the region-abbrev case the window is comfortably sufficient (a
163
+ * handful of states match a 2-letter query).
164
+ */
165
+ exactMatchTiering: boolean
166
+ /**
167
+ * #936 option 3 — official-language names ARE names. When true, a candidate holding the query as an OFFICIAL name
168
+ * (`names.official = 1`: a preferred-form name in an official language of its country, stamped at ingest) joins the
169
+ * NAME-exact sub-tier rather than the alias-exact one, provided its population clears {@link officialNameExactFloor}.
170
+ * Fixes unscoped "Åbo" → Turku (its official Swedish name) over a hamlet literally named Åbo; population still orders
171
+ * within the sub-tier, so Paris → Paris FR is untouched.
172
+ *
173
+ * Default true (operator-promoted 2026-07-03 after the pre-registered gate battery: four intended exonym flips —
174
+ * Berne→Bern, Bruges→Brugge, Roma→Rome, Åbo→Turku — with the namesake/abbreviation rows and the US/FI panels
175
+ * byte-identical). Requires a gazetteer carrying the #940 ingest bit — on older DBs without the `official` column the
176
+ * probe fails soft and behavior is identical to the flag being off.
177
+ */
178
+ officialNameExact: boolean
179
+ /**
180
+ * Minimum population for a candidate's official names to join the name-exact sub-tier. The #936 review's no-floor
181
+ * census measured the boundary: ≥100k holders are the famous-exonym class (757 flips, intent-correct; 7 collisions,
182
+ * none harmful) while 10k–100k holders are junk-dominated (3,481 flips led by short-form mis-tags — Villeneuve-Loubet
183
+ * carrying "villeneuve" would bury five real villages of that name). Rank-time knob: tunable without re-ingest;
184
+ * below-floor official names simply stay alias-tier (today's behavior).
185
+ */
186
+ officialNameExactFloor: number
187
+ }
188
+
189
+ const DEFAULT_WEIGHTS: RankingWeights = {
190
+ placetypeMatchBoost: 0.5,
191
+ localityImplicitBoost: 0.2,
192
+ countryMatchBoost: 0.3,
193
+ directChildBoost: 0.5,
194
+ descendantBoost: 0.2,
195
+ lengthPenaltyWeight: 0.1,
196
+ proximityBoost: 0.8,
197
+ proximityScaleKm: 100,
198
+ biasBoost: 4.0,
199
+ // populationBoost is intentionally large — empirical tuning against real WOF showed BM25 gaps
200
+ // of 1.5-3.0 between famous places and tiny same-name peers (because the famous ones have
201
+ // hundreds of alt-name entries that hurt their FTS document score). To consistently surface
202
+ // "the famous one" for unambiguous queries like "New York" or "Chicago", the population signal
203
+ // needs to dominate. Callers wanting a more conservative balance can drop this in the
204
+ // RankingWeights override.
205
+ //
206
+ // Note: this resolver uses `place_population` directly. The separate `place_importance` table
207
+ // (Wikipedia-derived) is consumed by the FST layer, not here. See
208
+ // docs/articles/concepts/importance-vs-population.md for the two-signal contract.
209
+ populationBoost: 4.0,
210
+ populationScaleLog10: 6,
211
+ // Exact name/alias match outranks partial match before the weighted sum (incl. population) is
212
+ // consulted — keeps population as an intra-tier prominence tiebreaker, not a cross-tier promoter.
213
+ // Fixes the 2-letter-region-abbrev bug ("ME" → Maine, not the more-populous Missouri).
214
+ exactMatchTiering: true,
215
+ // #936 option 3 — promoted default-ON 2026-07-03 (gate battery PASS; see the RankingWeights docstring).
216
+ officialNameExact: true,
217
+ officialNameExactFloor: 100_000,
218
+ }
219
+
220
+ /**
221
+ * Over-fetch floor for SHORT (≤3-char) queries — region abbreviations like "NY"/"VT". An exact-abbrev holder's BM25 is
222
+ * poor (long multilingual alt-name document), so the normal `limit * 4` window can drop it before `exactMatchTiering`
223
+ * promotes it. 200 comfortably covers every same-abbrev region across the 12-country gazetteer (a 2-letter token
224
+ * matches a few dozen regions at most) while staying a cheap region-placetype fetch. See the `#fuzzyNameMatch`
225
+ * over-fetch comment.
226
+ */
227
+ const SHORT_QUERY_OVERFETCH = 200
228
+
229
+ /**
230
+ * How many rows the population-ordered companion fetch (#905) adds to the candidate pool. Small on purpose: its only
231
+ * job is to guarantee the FAMOUS holders of a name enter the pool at all — for "Paris"-class floods the bm25 window is
232
+ * saturated by thousands of tiny same-name rows and no boost inside the bm25-based ORDER BY can rescue a candidate
233
+ * whose bm25 is length-poisoned by ~15 points (see the fetch-site comment).
234
+ */
235
+ const POPULATION_FETCH_LIMIT = 15
236
+
237
+ interface RawSearchRow {
238
+ id: number
239
+ name: string
240
+ placetype: string
241
+ country: string | null
242
+ parent_id: number | null
243
+ rank: number // BM25 (lower = better in SQLite); we negate to get higher-is-better
244
+ lat: number | null
245
+ lon: number | null
246
+ min_latitude: number | null
247
+ max_latitude: number | null
248
+ min_longitude: number | null
249
+ max_longitude: number | null
250
+ population: number | null // from the place_population aux table; null when missing
251
+ }
252
+
253
+ /**
254
+ * The coordinate-first candidate table (scripts/build-postcode-locality.ts): postcode → containing
255
+ *
256
+ * - Nearby localities with WOF alt-name aliases.
257
+ */
258
+ const POSTCODE_LOCALITY_TABLE = "postcode_locality"
259
+
260
+ /**
261
+ * Tunables for the coordinate-first locality soft-score `Score = pc·S_pc + name·S_name + pop·S_pop` (each S in [0,1]).
262
+ * The pc/name/pop WEIGHTS now come from the resolved convention's `scoringWeights` (`WORLD_DEFAULT` = 0.6/0.3/0.1 — the
263
+ * EU values), so a locale can retune them as data. PC_DECAY_KM sets how fast S_pc falls with distance.
264
+ */
265
+ const CF_PC_DECAY_KM = 8
266
+ /**
267
+ * The chosen locality must be within this distance of the postcode's containing locality, else the postcode and the
268
+ * parsed city name are judged to disagree (a transposed / wrong-for-the-city postcode) and the `mismatch` flag fires.
269
+ * Generous enough that a city-state Ortsteil (~15km from the city centroid) and an abutting town (~few km) are NOT
270
+ * flagged, tight enough to catch a wrong city (hundreds of km).
271
+ */
272
+ const CF_MISMATCH_KM = 50
273
+ const CF_MISMATCH_DELTA = 0.5
274
+
275
+ /** Case-fold + strip diacritics + collapse punctuation — for the coord-first soft name match. */
276
+ function cfNormalize(s: string): string {
277
+ return s
278
+ .toLowerCase()
279
+ .normalize("NFD")
280
+ .replace(/[\u0300-\u036f]/g, "") // combining diacritical marks
281
+ .replace(/[^a-z0-9]+/g, " ")
282
+ .trim()
283
+ }
284
+
285
+ /** Padded character-trigram set (a leading/trailing space pads short tokens). */
286
+ export function trigrams(s: string): Set<string> {
287
+ const t = ` ${s} `
288
+ const out = new Set<string>()
289
+
290
+ for (let i = 0; i + 3 <= t.length; i++) {
291
+ out.add(t.slice(i, i + 3))
292
+ }
293
+
294
+ return out
295
+ }
296
+
297
+ /**
298
+ * Character-trigram Jaccard ∈ [0,1] — tolerant of the swallowed-leading-char fragments ("auen" vs "plauen") and minor
299
+ * misspellings without a heavyweight edit-distance pass. Shared with the candidate backend's FTS5-trigram fuzzy
300
+ * fallback so both lookups rank typos identically.
301
+ */
302
+ export function trigramJaccard(a: string, b: string): number {
303
+ const A = trigrams(a)
304
+ const B = trigrams(b)
305
+
306
+ if (A.size === 0 || B.size === 0) return 0
307
+ let inter = 0
308
+
309
+ for (const x of A)
310
+ if (B.has(x)) {
311
+ inter++
312
+ }
313
+
314
+ return inter / (A.size + B.size - inter)
315
+ }
316
+
317
+ /** Soft name-match score ∈ [0,1]: exact (normalized) name/alias → 1, else best trigram-Jaccard. */
318
+ function softNameScore(text: string, name: string, aliases: readonly string[]): number {
319
+ const q = cfNormalize(text)
320
+
321
+ if (!q) return 0
322
+ let best = 0
323
+
324
+ for (const raw of [name, ...aliases]) {
325
+ const n = cfNormalize(raw)
326
+
327
+ if (!n) continue
328
+
329
+ if (n === q) return 1
330
+ best = Math.max(best, trigramJaccard(q, n))
331
+ }
332
+
333
+ return best
334
+ }
335
+
336
+ export class WOFSqlitePlaceLookup implements PlaceLookup, Disposable {
337
+ readonly #db: DatabaseSync
338
+ readonly #ownsDB: boolean
339
+ readonly #kysely: Kysely<WOFDatabase>
340
+ readonly #weights: RankingWeights
341
+ /**
342
+ * Cached at construction so we don't `sqlite_master` query on every findPlace call. Bbox + near- with-radius queries
343
+ * fall back to no-filter when this is false, preserving compatibility with DBs that were FTS-built before the R*Tree
344
+ * shipped.
345
+ *
346
+ * Per-shard: a shard is only considered to have the bbox index if its own R*Tree table exists.
347
+ */
348
+ readonly #hasBboxIndex: Map<string, boolean>
349
+ /**
350
+ * Per-shard probe for the `place_population` aux table. When false, the LEFT JOIN is omitted from the SELECT and
351
+ * population boost is 0 for every row — preserves compatibility with DBs built before this feature shipped.
352
+ */
353
+ readonly #hasPopulationIndex: Map<string, boolean>
354
+ /**
355
+ * Per-shard probe for the `postcode_locality` table (the coordinate-first candidate table, built by
356
+ * scripts/build-postcode-locality.ts). Cached at construction; null'd out when absent so the coord-first path
357
+ * silently no-ops on a deployment that didn't ship the table.
358
+ */
359
+ readonly #postcodeLocalityShard: string | null
360
+ /**
361
+ * Resolved shard list. Always at least one entry; first is `main`. Multi-shard adds extras with their own derived (or
362
+ * override) schema names.
363
+ */
364
+ readonly #shards: ResolvedShard[]
365
+ /** #920: per-schema probed country sets for country-aware shard routing (non-main shards only). */
366
+ readonly #shardCountries: Map<string, ReadonlySet<string>>
367
+ /**
368
+ * The Geographic Rule Engine (Direction E, #289). `#conventionSource` supplies per-WOF-polygon resolution profiles;
369
+ * `#strategies` is the named-primitive registry the merged convention dispatches. Empty source → every query resolves
370
+ * to `WORLD_DEFAULT` → byte-identical to the pre-engine coordinate-first path. `#countryWOFIdCache` memoizes the
371
+ * country-code → country-WOF-id lookup that seeds the convention ancestor chain (one query per country, then
372
+ * cached).
373
+ */
374
+ readonly #conventionSource: ConventionSource
375
+ readonly #strategies: Map<string, Strategy>
376
+ readonly #countryWOFIdCache = new Map<string, number | null>()
377
+ /** Strategy names already warned about — so an unknown name surfaces once, not once per query. */
378
+ readonly #warnedUnknownStrategies = new Set<string>()
379
+ /**
380
+ * Lazily-built `admin_id → coincident localities` map from the #403 relation (null until first use).
381
+ */
382
+ #coincidentRolesCache: Map<number, CoincidentLocality[]> | null = null
383
+ /** Per-id memoized ancestor lineages (#404) — a hot chain is queried once. */
384
+ readonly #ancestorsCache = new Map<number, Ancestor[]>()
385
+ /**
386
+ * Opt-in postal-city alias reader (#475). `null` unless `opts.postalCityAliases` was supplied — every alias code path
387
+ * is gated on this, so the default resolver is byte-identical.
388
+ */
389
+ readonly #postalCityAliases: WOFPostalCityAliasLookup | null
390
+
391
+ constructor(opts: WOFSqlitePlaceLookupOpts, weights?: Partial<RankingWeights>) {
392
+ if (opts.database && opts.databasePath) {
393
+ throw new Error("WOFSqlitePlaceLookup: pass either `database` or `databasePath`, not both")
394
+ }
395
+
396
+ if (!opts.database && !opts.databasePath) {
397
+ throw new Error("WOFSqlitePlaceLookup: one of `database` or `databasePath` is required")
398
+ }
399
+
400
+ if (opts.database) {
401
+ this.#db = opts.database
402
+ this.#ownsDB = false
403
+ this.#shards = [{ path: ":memory:", schemaName: "main", placetypes: [] }]
404
+ } else {
405
+ const shards = resolveShards(opts.databasePath!)
406
+ this.#shards = shards
407
+ this.#db = new DatabaseSync(shards[0]!.path, { readOnly: false })
408
+ this.#ownsDB = true
409
+
410
+ // ATTACH each non-main shard. Schema names were validated by resolveShards, so safe to
411
+ // interpolate directly (SQLite ATTACH doesn't accept parameters for the schema name).
412
+ for (const s of shards.slice(1)) {
413
+ this.#db.exec(`ATTACH DATABASE '${s.path.replace(/'/g, "''")}' AS ${s.schemaName}`)
414
+ }
415
+ }
416
+
417
+ // node:sqlite has no .pragma() helper; pragmas are executed as plain SQL.
418
+ this.#db.exec("PRAGMA busy_timeout = 5000")
419
+
420
+ if (opts.buildFTS) {
421
+ this.#ensureFTS()
422
+ } else {
423
+ this.#assertFTSExists()
424
+ }
425
+
426
+ this.#kysely = new Kysely<WOFDatabase>({
427
+ dialect: new SqliteDialect({ database: this.#db }),
428
+ })
429
+ this.#weights = { ...DEFAULT_WEIGHTS, ...weights }
430
+
431
+ // Probe each shard's aux-table presence — driven by per-shard table existence in
432
+ // sqlite_master. Cached at construction so findPlace doesn't query sqlite_master per call.
433
+ this.#hasBboxIndex = new Map()
434
+ this.#hasPopulationIndex = new Map()
435
+
436
+ for (const s of this.#shards) {
437
+ this.#hasBboxIndex.set(s.schemaName, this.#shardHasTable(s.schemaName, PLACE_BBOX_TABLE))
438
+ this.#hasPopulationIndex.set(s.schemaName, this.#shardHasTable(s.schemaName, PLACE_POPULATION_TABLE))
439
+ }
440
+ // #920 country-aware shard routing: probe each NON-MAIN shard's country set once at
441
+ // construction (they're small, purpose-built shards — postcode/locality slices; main is the
442
+ // multi-GB admin DB and is the fallback anyway, so it is deliberately NOT scanned). Feeds
443
+ // pickShardForPlacetype so two postcode shards (postalcode-us + postalcode-geonames-tail)
444
+ // route by the query's country instead of first-match starving the second shard.
445
+ this.#shardCountries = new Map()
446
+
447
+ for (const sh of this.#shards) {
448
+ if (sh.schemaName === "main") continue
449
+
450
+ try {
451
+ const rows = this.#db
452
+ .prepare(`SELECT DISTINCT country FROM ${sh.schemaName}.spr WHERE country != ''`)
453
+ .all() as Array<{ country: string }>
454
+ this.#shardCountries.set(sh.schemaName, new Set(rows.map((r) => r.country)))
455
+ } catch {
456
+ // A shard without spr (or an attach oddity) just doesn't participate in country routing.
457
+ }
458
+ }
459
+
460
+ // The postcode_locality table can live on any attached shard (typically its own
461
+ // `postcode-locality-<cc>.db`). Find the first shard that has it; null = coord-first disabled.
462
+ this.#postcodeLocalityShard =
463
+ this.#shards.find((s) => this.#shardHasTable(s.schemaName, POSTCODE_LOCALITY_TABLE))?.schemaName ?? null
464
+
465
+ // Opt-in postal-city alias reader (#475). Construction-time present-or-not is the gate: null
466
+ // keeps the coordinate-first scorer byte-identical to pre-#475.
467
+ this.#postalCityAliases = opts.postalCityAliases ?? null
468
+
469
+ // The Geographic Rule Engine convention source. Precedence: an explicit `opts.conventions`
470
+ // (a ready source or a seed map) wins; else the build-from-source convention asset if one is
471
+ // attached (auto-detected, like the postcode_locality shard — adding conventions.db to
472
+ // databasePath enables it; queried on demand, not paged into memory); else empty, so EU rides
473
+ // WORLD_DEFAULT. The registry binds strategy NAMES to the SQL-bound primitives — adding a
474
+ // strategy is registering it here.
475
+ const conventionShard =
476
+ this.#shards.find((s) => this.#shardHasTable(s.schemaName, ADDRESS_CONVENTION_TABLE))?.schemaName ?? null
477
+ this.#conventionSource = opts.conventions
478
+ ? "get" in opts.conventions && typeof opts.conventions.get === "function"
479
+ ? opts.conventions
480
+ : new SeedConventionSource(opts.conventions as Record<number, Convention>)
481
+ : conventionShard
482
+ ? new SqliteConventionSource(this.#db, conventionShard)
483
+ : new SeedConventionSource()
484
+ this.#strategies = new Map<string, Strategy>([
485
+ ["postcode_area_resolution", (q, c) => this.#postcodeAreaResolution(q, c)],
486
+ ["fallback_fuzzy_name_match", (q) => this.#fuzzyNameMatch(q)],
487
+ ])
488
+ }
489
+
490
+ #shardHasTable(schemaName: string, tableName: string): boolean {
491
+ // For main, the existing helpers work directly. For attached shards we have to ask via the
492
+ // schema-qualified `sqlite_master` view.
493
+ if (schemaName === "main") {
494
+ if (tableName === PLACE_BBOX_TABLE) return placeBboxExists(this.#db)
495
+
496
+ if (tableName === PLACE_POPULATION_TABLE) return placePopulationExists(this.#db)
497
+ }
498
+ const row = this.#db
499
+ .prepare(`SELECT name FROM ${schemaName}.sqlite_master WHERE type = 'table' AND name = ?`)
500
+ .get(tableName) as { name: string } | undefined
501
+
502
+ return Boolean(row)
503
+ }
504
+
505
+ async findPlace(query: FindPlaceQuery): Promise<PlaceCandidate[]> {
506
+ // Geographic Rule Engine dispatch (#289). Resolve the effective convention for this query
507
+ // (WORLD_DEFAULT for the EU locales — the seed source is empty) and run its candidate strategies
508
+ // in order; the first to return a non-null result wins. The default list,
509
+ // [postcode_area_resolution, fallback_fuzzy_name_match], reproduces the pre-engine coordinate-
510
+ // first → FTS fall-through exactly. Unknown strategy names are skipped, so a convention may name
511
+ // a primitive a future phase will register.
512
+ const convention = this.#conventionFor(query)
513
+
514
+ let outcome: PlaceCandidate[] = []
515
+
516
+ for (const name of convention.candidateStrategies) {
517
+ const strategy = this.#strategies.get(name)
518
+
519
+ if (!strategy) {
520
+ this.#warnUnknownStrategy(name)
521
+ continue
522
+ }
523
+ const result = await strategy(query, convention)
524
+
525
+ if (result !== null) {
526
+ outcome = result
527
+ break
528
+ }
529
+ }
530
+
531
+ if (outcome.length > 0) return outcome
532
+
533
+ // #924: NL postcode retry ladder. The WOF NL postalcode repo stores full codes UNSPACED
534
+ // ('1012LG') plus 4-digit stems ('1012'), while Dutch addresses carry the spaced form
535
+ // ('1012 LG') — two FTS tokens that can never match the one-token doc (the #920 name law,
536
+ // resurfacing in a WOF-built shard). On a postcode-typed NL-shape miss, retry ONCE with the
537
+ // whitespace-joined form (block-level precision when the full-code row exists), then the
538
+ // 4-digit stem (area-level). Country-gated to NL — the same digits+letters shape elsewhere
539
+ // must not silently coarsen to a different system's code. Each retry only fires when its
540
+ // text differs from the current one, so the ladder terminates by construction.
541
+ if (
542
+ query.country?.toUpperCase() === "NL" &&
543
+ (normalizePlacetypes(query.placetype)?.includes("postalcode") ?? false) &&
544
+ /^\d{4}\s?[A-Za-z]{2}$/.test(query.text.trim())
545
+ ) {
546
+ const trimmed = query.text.trim()
547
+ const joined = trimmed.replace(/\s+/g, "")
548
+
549
+ if (joined !== trimmed) {
550
+ const full = await this.findPlace({ ...query, text: joined })
551
+
552
+ if (full.length > 0) return full
553
+ }
554
+ const stem = trimmed.slice(0, 4)
555
+
556
+ if (stem !== trimmed) return this.findPlace({ ...query, text: stem })
557
+ }
558
+
559
+ return outcome
560
+ }
561
+
562
+ /**
563
+ * Dual-role localities coincident with an admin id, from the precomputed `coincident_roles` relation (#403). Backs
564
+ * {@link ResolveOpts.hierarchyCompletion} (#405): O(1) once the relation is loaded. Returns `[]` when the relation
565
+ * table is absent (older DB) or the admin isn't a dual-role place, so completion degrades gracefully. The relation +
566
+ * `spr` join is loaded once and memoized.
567
+ */
568
+ coincidentLocalitiesFor(adminID: number | string): CoincidentLocality[] {
569
+ const id = typeof adminID === "number" ? adminID : Number(adminID)
570
+
571
+ if (!Number.isFinite(id)) return []
572
+
573
+ if (!this.#coincidentRolesCache) {
574
+ const map = new Map<number, CoincidentLocality[]>()
575
+
576
+ if (coincidentRolesExists(this.#db)) {
577
+ const rows = this.#db
578
+ .prepare(
579
+ `SELECT cr.admin_id AS adminID, s.id AS id, s.name AS name, s.country AS country,
580
+ s.latitude AS lat, s.longitude AS lon,
581
+ cr.relationship_type AS relationshipType, cr.locality_population AS population,
582
+ cr.distance_km AS distanceKm
583
+ FROM ${COINCIDENT_ROLES_TABLE} cr JOIN spr s ON s.id = cr.locality_id`
584
+ )
585
+ .all() as unknown as Array<{
586
+ adminID: number
587
+ id: number
588
+ name: string
589
+ country: string
590
+ lat: number
591
+ lon: number
592
+ relationshipType: string
593
+ population: number
594
+ distanceKm: number
595
+ }>
596
+
597
+ for (const r of rows) {
598
+ const candidate: CoincidentLocality = {
599
+ id: r.id,
600
+ name: r.name,
601
+ placetype: "locality",
602
+ country: r.country,
603
+ lat: r.lat,
604
+ lon: r.lon,
605
+ score: 0,
606
+ relationshipType: r.relationshipType,
607
+ population: r.population,
608
+ distanceKm: r.distanceKm,
609
+ }
610
+ const list = map.get(r.adminID)
611
+
612
+ if (list) {
613
+ list.push(candidate)
614
+ } else {
615
+ map.set(r.adminID, [candidate])
616
+ }
617
+ }
618
+ }
619
+ this.#coincidentRolesCache = map
620
+ }
621
+
622
+ return this.#coincidentRolesCache.get(id) ?? []
623
+ }
624
+
625
+ /**
626
+ * The ancestor lineage of a place — its containment chain joined with `spr` for canonical names, ordered
627
+ * NEAREST-FIRST (localadmin → county → region → … → country). Backs {@link ResolveOpts.includeAncestors} (#404). Self
628
+ * is excluded; memoized per id. Returns `[]` when the place has no recorded ancestry.
629
+ *
630
+ * The walk itself lives in `ancestry.ts` (shared with the reverse geocoder, #484); the ordering is its
631
+ * `PLACETYPE_DEPTH` table — same ranking as the previous inline SQL CASE, extended below `localadmin` so
632
+ * locality/neighbourhood ancestors order correctly instead of sorting last.
633
+ */
634
+ ancestors(id: number | string): Ancestor[] {
635
+ const pid = typeof id === "number" ? id : Number(id)
636
+
637
+ if (!Number.isFinite(pid)) return []
638
+ const cached = this.#ancestorsCache.get(pid)
639
+
640
+ if (cached) return cached
641
+ const lineage: Ancestor[] = ancestorLineage(this.#db, pid).map((r) => ({
642
+ id: r.id,
643
+ placetype: r.placetype,
644
+ name: r.name,
645
+ }))
646
+ this.#ancestorsCache.set(pid, lineage)
647
+
648
+ return lineage
649
+ }
650
+
651
+ /**
652
+ * Surface an unknown strategy name LOUDLY (once per name) rather than swallowing it silently — an invisible no-op is
653
+ * exactly the hidden-dependency failure mode we avoid (see the provenance-first design value). We warn rather than
654
+ * throw so a convention asset built against a newer code revision (one that adds a strategy) degrades gracefully on
655
+ * an older build instead of taking down resolution.
656
+ */
657
+ #warnUnknownStrategy(name: string): void {
658
+ if (this.#warnedUnknownStrategies.has(name)) return
659
+ this.#warnedUnknownStrategies.add(name)
660
+ console.warn(
661
+ `WOFSqlitePlaceLookup: a convention names strategy "${name}", which this build does not register ` +
662
+ `(known: ${[...this.#strategies.keys()].join(", ")}). Skipping it. If the convention asset was built ` +
663
+ `against a newer code revision, rebuild the asset for this one.`
664
+ )
665
+ }
666
+
667
+ /**
668
+ * Strategy `postcode_area_resolution` — the coordinate-first locality path, strictly gated (a sibling postcode AND a
669
+ * postcode_locality table AND a locality query). Returns `null` — so the dispatcher falls through to the next
670
+ * strategy — when the gate is unmet or the postcode isn't in the table; otherwise the soft-scored postcode∪name
671
+ * candidate set.
672
+ */
673
+ #postcodeAreaResolution(query: FindPlaceQuery, convention: ResolvedConvention): Promise<PlaceCandidate[] | null> {
674
+ if (!(query.postcode && this.#postcodeLocalityShard && this.#isLocalityQuery(query))) {
675
+ return Promise.resolve(null)
676
+ }
677
+
678
+ return this.#findLocalityCoordFirst(query, this.#postcodeLocalityShard, convention)
679
+ }
680
+
681
+ /**
682
+ * Strategy `fallback_fuzzy_name_match` — the BM25 FTS name-match over the gazetteer, the universal fallback. Always
683
+ * returns an array (never null), so it terminates the dispatch chain.
684
+ */
685
+ async #fuzzyNameMatch(query: FindPlaceQuery, forceShard?: ResolvedShard): Promise<PlaceCandidate[]> {
686
+ const limit = query.limit ?? 10
687
+ // Over-fetch so post-scoring + exact-match tiering have room to re-rank. SHORT queries (a 2–3-char
688
+ // region abbreviation like "NY"/"VT") are the danger case the `exactMatchTiering` docstring flags:
689
+ // the exact-abbrev holder's BM25 is poor (its long multilingual alt-name document tanks the score),
690
+ // so under the normal `limit * 4` window it drops OUT of the candidate pool BEFORE tiering can
691
+ // promote it — "NY" then resolves to a token-matching foreign region (Highland, GB) instead of New
692
+ // York. Widen the window for short queries so the exact match is always present to be tiered.
693
+ // (Cross-country abbrev collisions — "VT" is BOTH Vermont and Viterbo — still need a country/
694
+ // postcode signal to disambiguate; this only rescues the window-drop class, not genuine ambiguity.
695
+ // With a `country` hint every abbrev resolves; bare + no-context lifts 7→10/15 US states.)
696
+ const ftsLimit = query.text.trim().length <= 3 ? Math.max(limit * 4, SHORT_QUERY_OVERFETCH) : limit * 4
697
+
698
+ // Expand the placetype filter through the shared equivalence table (core/resolver): a
699
+ // `locality` query must also reach `borough` / `localadmin` rows — Brooklyn-the-borough
700
+ // (pop 2.5M) is a borough, not a locality, and a strict filter made it unreachable so the
701
+ // fuzzy "Brooklyn Park, MN" won instead. Order-preserving: the FIRST entry stays the
702
+ // requested placetype, which is what shard routing keys off below.
703
+ const placetypes = expandPlacetypeFilter(normalizePlacetypes(query.placetype)) as WOFPlacetype[] | null
704
+ // Postcode-typed queries keep the #920 fused name-law shape; everything else splits on
705
+ // intra-token punctuation so hyphenated names reach the FTS as their real terms (#945).
706
+ const ftsQuery = sanitizeFTSQuery(query.text, { fuseTokens: placetypes?.includes("postalcode") ?? false })
707
+
708
+ if (!ftsQuery) return []
709
+
710
+ // Pick the shard for this query. Multi-shard routing is placetype-driven; a query without
711
+ // `placetype` always goes to main. (Mixed-placetype queries with multiple shards aren't
712
+ // supported in v1 — caller can issue two findPlace calls and merge in TS if needed.)
713
+ const firstPlacetype = placetypes?.[0]
714
+
715
+ // Bias fan-out (#58/proximity-bias): a country-less query WITH proximity hints must see the
716
+ // cross-shard ambiguity the hints exist to resolve — "48026" lives in postalcode-us AND
717
+ // postalcode-intl, and single-shard routing would hide one side. Query every matching shard
718
+ // (self-recursion with a shard pin), merge by id, and re-sort by the same (exact, prominence)
719
+ // keys the per-shard tier sort used. Bounded: hints + no country + >1 matching shard only.
720
+ const hasBiasHints = !!query.near || (query.bias?.length ?? 0) > 0
721
+
722
+ if (!forceShard && hasBiasHints && !query.country) {
723
+ const matching = pickShardsForPlacetype(this.#shards, firstPlacetype)
724
+
725
+ if (matching.length > 1) {
726
+ const pools: PlaceCandidate[][] = []
727
+
728
+ for (const sh of matching) {
729
+ pools.push(await this.#fuzzyNameMatch(query, sh))
730
+ }
731
+ const byID = new Map<PlaceCandidate["id"], PlaceCandidate>()
732
+
733
+ for (const c of pools.flat()) {
734
+ if (!byID.has(c.id)) {
735
+ byID.set(c.id, c)
736
+ }
737
+ }
738
+ const merged = [...byID.values()]
739
+ merged.sort(
740
+ (a, b) =>
741
+ Number(b.exactMatch ?? false) - Number(a.exactMatch ?? false) ||
742
+ (b.prominence ?? 0) - (a.prominence ?? 0) ||
743
+ b.score - a.score
744
+ )
745
+
746
+ return merged.slice(0, limit)
747
+ }
748
+ }
749
+ const shard =
750
+ forceShard ??
751
+ pickShardForPlacetype(this.#shards, firstPlacetype, {
752
+ country: query.country,
753
+ countriesBySchema: this.#shardCountries,
754
+ })
755
+ const sch = shard.schemaName // bare schema name; safe to interpolate (validated at construction)
756
+
757
+ // Filter out historical / superseded / deprecated places by default — they live in the same
758
+ // spr table but should never win a contemporary lookup. `is_current = 0` is the only WOF
759
+ // value that means "not current"; both `-1` (modern) and `1` (legacy) mean current. See #91.
760
+ // Note: with schema-qualified FROM the bare `place_search` reference in MATCH resolves to
761
+ // the FROM table — required by FTS5 parser, see sharding.ts header comment.
762
+ const where: string[] = ["place_search MATCH ?", "spr.is_current != 0", "spr.is_deprecated = 0"]
763
+ const params: SQLInputValue[] = [ftsQuery]
764
+
765
+ if (placetypes && placetypes.length > 0) {
766
+ where.push(`spr.placetype IN (${placetypes.map(() => "?").join(", ")})`)
767
+ params.push(...placetypes)
768
+ }
769
+
770
+ if (query.country) {
771
+ where.push("spr.country = ?")
772
+ params.push(query.country)
773
+ }
774
+
775
+ if (query.parentID !== undefined) {
776
+ where.push(`(spr.parent_id = ? OR spr.id IN (SELECT id FROM ${sch}.ancestors WHERE ancestor_id = ?))`)
777
+ params.push(query.parentID, query.parentID)
778
+ }
779
+
780
+ // Bbox + near-with-radius are SQL-level filters via the R*Tree. We only emit the JOIN when
781
+ // the active shard has the R*Tree; missing-but-requested is silently treated as no-bbox-
782
+ // filter so legacy DBs / shards-without-bbox don't crash.
783
+ const shardHasBbox = this.#hasBboxIndex.get(sch) === true
784
+ const useBboxJoin = (query.bbox || query.near?.maxDistanceKm !== undefined) && shardHasBbox
785
+ let joinClause = `JOIN ${sch}.spr ON spr.id = place_search.wof_id`
786
+
787
+ if (useBboxJoin) {
788
+ joinClause += ` JOIN ${sch}.${PLACE_BBOX_TABLE} bbox ON bbox.id = spr.id`
789
+ // AABB intersection — both bbox sides must overlap. R*Tree handles this in O(log n).
790
+ const filterBox = query.bbox
791
+ ? query.bbox
792
+ : bboxAround(query.near!.lat, query.near!.lon, query.near!.maxDistanceKm!)
793
+ where.push("bbox.min_lat <= ? AND bbox.max_lat >= ?", "bbox.min_lon <= ? AND bbox.max_lon >= ?")
794
+ params.push(filterBox.maxLat, filterBox.minLat, filterBox.maxLon, filterBox.minLon)
795
+ }
796
+
797
+ // LEFT JOIN the population aux table when present. Missing-on-this-shard means the SELECT
798
+ // just doesn't include the population column; the post-scoring loop treats it as 0.
799
+ const shardHasPopulation = this.#hasPopulationIndex.get(sch) === true
800
+ const populationSelect = shardHasPopulation
801
+ ? `${PLACE_POPULATION_TABLE}.population AS population`
802
+ : `NULL AS population`
803
+ const populationJoin = shardHasPopulation
804
+ ? `LEFT JOIN ${sch}.${PLACE_POPULATION_TABLE} ON ${PLACE_POPULATION_TABLE}.id = spr.id`
805
+ : ""
806
+
807
+ // Push the population boost into the ORDER BY when the index is available, so famous places
808
+ // (whose long alt-name lists hurt BM25) actually make it into the over-fetch window. The TS
809
+ // post-scoring will still compute the same boost for the final score; this just ensures the
810
+ // candidate set is right.
811
+ //
812
+ // Formula: rank_adjusted = bm25 - populationBoost * min(1.0, log10(1 + pop) / scaleLog10)
813
+ // Lower rank_adjusted = better (matches SQLite's bm25 convention of "more negative = better").
814
+ //
815
+ // #905 — do NOT reach for bm25 column weights here. Measured falsification (2026-07-02): FTS5's
816
+ // bm25 length normalization is polluted by the row's TOTAL document size, so identical 1-token
817
+ // `name` docs read −16.0 (empty alt_names) vs −0.43 (2.7 KB alt_names) EVEN with the alt_names
818
+ // column weighted to zero — no weighting isolates name relevance in this schema. The famous-
819
+ // holder guarantee lives in the population-ordered companion fetch below instead, and the
820
+ // exact tier breaks ties by population in the post-scoring sort.
821
+ const orderByExpr = shardHasPopulation
822
+ ? `(bm25(place_search) - ? * MIN(1.0, COALESCE(log10(1.0 + ${PLACE_POPULATION_TABLE}.population), 0) / ?))`
823
+ : "bm25(place_search)"
824
+
825
+ // Schema-qualified FROM with bare-name MATCH — required syntax for FTS5 on attached schemas.
826
+ // See sharding.ts header for the gotcha that drove this design.
827
+ const stmt = this.#db.prepare(`
828
+ SELECT
829
+ spr.id AS id,
830
+ spr.name,
831
+ spr.placetype,
832
+ spr.country,
833
+ spr.parent_id,
834
+ bm25(place_search) AS rank,
835
+ spr.latitude AS lat,
836
+ spr.longitude AS lon,
837
+ spr.min_latitude, spr.max_latitude, spr.min_longitude, spr.max_longitude,
838
+ ${populationSelect}
839
+ FROM ${sch}.place_search
840
+ ${joinClause}
841
+ ${populationJoin}
842
+ WHERE ${where.join(" AND ")}
843
+ ORDER BY ${orderByExpr} ASC
844
+ LIMIT ?
845
+ `)
846
+
847
+ if (shardHasPopulation) {
848
+ params.push(this.#weights.populationBoost, this.#weights.populationScaleLog10)
849
+ }
850
+ params.push(ftsLimit)
851
+
852
+ const rawRows = stmt.all(...params) as unknown as RawSearchRow[]
853
+
854
+ // #905 companion fetch: the same MATCH, ordered by population alone. For name floods
855
+ // ("Paris" matches thousands of gap-fill villages) the bm25-based window above cannot admit
856
+ // the famous holder — its bm25 is length-poisoned by the row's alias bulk (measured ~15 pts,
857
+ // vs a +4.0 boost cap), so FR Paris never even reaches post-scoring. This fetch makes the
858
+ // prominent holders of a name pool-complete BY CONSTRUCTION; the exact-tier sort below
859
+ // decides whether they win. Skipped without a population index (nothing to order by).
860
+ if (shardHasPopulation) {
861
+ const popStmt = this.#db.prepare(`
862
+ SELECT
863
+ spr.id AS id,
864
+ spr.name,
865
+ spr.placetype,
866
+ spr.country,
867
+ spr.parent_id,
868
+ bm25(place_search) AS rank,
869
+ spr.latitude AS lat,
870
+ spr.longitude AS lon,
871
+ spr.min_latitude, spr.max_latitude, spr.min_longitude, spr.max_longitude,
872
+ ${populationSelect}
873
+ FROM ${sch}.place_search
874
+ ${joinClause}
875
+ ${populationJoin}
876
+ WHERE ${where.join(" AND ")}
877
+ ORDER BY COALESCE(${PLACE_POPULATION_TABLE}.population, 0) DESC
878
+ LIMIT ?
879
+ `)
880
+ const popParams = params.slice(0, params.length - 3) // drop the two boost params + ftsLimit
881
+ const seen = new Set(rawRows.map((r) => r.id))
882
+
883
+ for (const row of popStmt.all(...popParams, POPULATION_FETCH_LIMIT) as unknown as RawSearchRow[]) {
884
+ if (!seen.has(row.id)) {
885
+ rawRows.push(row)
886
+ }
887
+ }
888
+ }
889
+
890
+ const queryLen = query.text.length
891
+ const candidates = rawRows.map((row): PlaceCandidate => {
892
+ // SQLite's bm25() returns a lower-is-better score (negative for matches). Negate so we
893
+ // start from a higher-is-better baseline.
894
+ let score = -row.rank
895
+
896
+ if (placetypes && placetypes.length > 0 && placetypes.includes(row.placetype as WOFPlacetype)) {
897
+ score += this.#weights.placetypeMatchBoost
898
+ }
899
+
900
+ if (!placetypes && row.placetype === "locality") {
901
+ score += this.#weights.localityImplicitBoost
902
+ }
903
+
904
+ if (query.country && row.country === query.country) {
905
+ score += this.#weights.countryMatchBoost
906
+ }
907
+
908
+ if (query.parentID !== undefined) {
909
+ if (row.parent_id === query.parentID) {
910
+ score += this.#weights.directChildBoost
911
+ } else {
912
+ score += this.#weights.descendantBoost
913
+ }
914
+ }
915
+ const extraLen = Math.max(0, row.name.length - queryLen - 3)
916
+ score -= (this.#weights.lengthPenaltyWeight * extraLen) / 10
917
+
918
+ // Proximity boost: only applied when the query carries `near` AND the candidate has real
919
+ // coordinates. The formula decays smoothly with distance so close-but-not-exact hits
920
+ // still benefit; tunable via proximityBoost + proximityScaleKm.
921
+ let distanceKm: number | undefined
922
+ // The best decayed-distance term over `near` + every `bias` point (each point's term is
923
+ // scaled by its weight; the MAX wins — a candidate near ANY hint is "nearby"). Carried
924
+ // into the exact-tier prominence sort below when hints are present.
925
+ let proximityTerm = 0
926
+
927
+ if (row.lat !== null && row.lon !== null && !(row.lat === 0 && row.lon === 0)) {
928
+ const hints: Array<{ lat: number; lon: number; weight: number }> = []
929
+
930
+ if (query.near) {
931
+ hints.push({ lat: query.near.lat, lon: query.near.lon, weight: 1 })
932
+ }
933
+
934
+ for (const b of query.bias ?? []) {
935
+ hints.push({ lat: b.lat, lon: b.lon, weight: b.weight ?? 1 })
936
+ }
937
+
938
+ let scoreTerm = 0
939
+
940
+ for (const h of hints) {
941
+ const d = haversineKm(h.lat, h.lon, row.lat, row.lon)
942
+ const decay = h.weight / (1 + d / this.#weights.proximityScaleKm)
943
+ const prom = decay * this.#weights.biasBoost
944
+
945
+ if (prom > proximityTerm) {
946
+ proximityTerm = prom
947
+ distanceKm = d
948
+ scoreTerm = decay * this.#weights.proximityBoost
949
+ }
950
+ }
951
+ score += scoreTerm
952
+ }
953
+
954
+ // Population boost: capped at `populationBoost` magnitude at `10^populationScaleLog10`
955
+ // people. Missing population → no contribution. Never penalizes.
956
+ let popTerm = 0
957
+
958
+ if (row.population !== null && row.population > 0 && this.#weights.populationScaleLog10 > 0) {
959
+ const popLog = Math.log10(1 + row.population)
960
+ const popFraction = Math.min(1, popLog / this.#weights.populationScaleLog10)
961
+ popTerm = this.#weights.populationBoost * popFraction
962
+ score += popTerm
963
+ }
964
+ // Combined prominence for the exact-tier sort when proximity hints are present: population
965
+ // and nearness in the SAME additive units, so the map view / the user's location can win a
966
+ // cross-country postcode tie without a hard filter.
967
+ const prominence = popTerm + proximityTerm
968
+
969
+ const candidate: PlaceCandidate = {
970
+ id: row.id,
971
+ prominence,
972
+ name: row.name,
973
+ placetype: row.placetype as WOFPlacetype,
974
+ country: row.country ?? "",
975
+ lat: row.lat ?? 0,
976
+ lon: row.lon ?? 0,
977
+ parent_id: row.parent_id ?? undefined,
978
+ score,
979
+ }
980
+
981
+ if (distanceKm !== undefined) {
982
+ candidate.distanceKm = distanceKm
983
+ }
984
+
985
+ if (row.population !== null && row.population > 0) {
986
+ candidate.population = row.population
987
+ }
988
+
989
+ // Candidate bbox — parity with the WASM lookup (resolver-wof-wasm/lookup.ts), whose
990
+ // consumers (the demo cascade's region constraint) read it. Without this the Node
991
+ // backend's region→bbox constraint is dead and disambiguation falls to population
992
+ // ranking (the Springfield-IL→MO failure the #524 smoke eval caught).
993
+ if (
994
+ row.min_latitude != null &&
995
+ row.max_latitude != null &&
996
+ row.min_longitude != null &&
997
+ row.max_longitude != null
998
+ ) {
999
+ candidate.bbox = {
1000
+ minLat: row.min_latitude,
1001
+ maxLat: row.max_latitude,
1002
+ minLon: row.min_longitude,
1003
+ maxLon: row.max_longitude,
1004
+ }
1005
+ }
1006
+
1007
+ return candidate
1008
+ })
1009
+
1010
+ // Exact-match tiering: a candidate whose name OR any alias equals the query text (case-folded)
1011
+ // ranks above any partial match, with the weighted-sum score (incl. population) breaking ties
1012
+ // WITHIN a tier. See the RankingWeights.exactMatchTiering docstring for why this aligns the
1013
+ // population prior rather than overriding it. One cheap indexed lookup over the candidate ids.
1014
+ // Runs even for a SINGLE candidate so `exactMatch` is stamped consistently (parity with the
1015
+ // WASM lookup) — a sole alias hit ("New York City" → New York) must still carry the flag the
1016
+ // demo cascade / #369 re-rank read.
1017
+ if (this.#weights.exactMatchTiering && candidates.length > 0) {
1018
+ const exactIds = this.#exactMatchIds(
1019
+ sch,
1020
+ candidates.map((c) => c.id as number),
1021
+ query.text
1022
+ )
1023
+
1024
+ // Stamp the tier onto every candidate (not just when the tiering sort fires) so a downstream
1025
+ // re-rank — #369's postcode-anchor country pin in `resolveTree` — can keep the country pin from
1026
+ // crossing the exact/partial boundary ("ME" → Maine, not the more-populous Missouri).
1027
+ for (const c of candidates) {
1028
+ c.exactMatch = exactIds.has(c.id as number)
1029
+ }
1030
+
1031
+ if (exactIds.size > 0) {
1032
+ // #905: WITHIN the exact tier, population is the PRIMARY key and the weighted score
1033
+ // only breaks population ties. Exactness saturates text relevance, and the bm25
1034
+ // residue inside `score` is length-noise (see the fetch-site comment), so letting it
1035
+ // order the tier is what sent unscoped "Paris" to an Ohio township. The partial tier
1036
+ // keeps score order — text relevance still means something there. This makes the
1037
+ // exactMatchTiering docstring literal: match quality primary, prominence within.
1038
+ //
1039
+ // #912 sub-tier: a NAME-exact candidate (spr.name equals the query) outranks an
1040
+ // ALIAS-exact one ('Paris' the place beats 'Paris Township' held via alias 'Paris').
1041
+ // The place's own name is a stronger identity claim than an alias — aliases exist to
1042
+ // widen recall, not to tie primaries. ME→Maine is untouched: 'ME' name-exact-matches
1043
+ // nothing, so the alias sub-tier still decides there. Population orders within each
1044
+ // sub-tier as before.
1045
+ const norm = (v: string): string => v.toLowerCase().trim().replace(/\s+/g, " ")
1046
+ const needle = norm(query.text)
1047
+ // #936 option 3: an OFFICIAL name (preferred form in an official language of the place's
1048
+ // country, `names.official = 1`) counts as the place's own name for the sub-tier — "Åbo" is
1049
+ // Turku's name, not merely its alias. Floor-gated on the holder's population (see the
1050
+ // RankingWeights docstring for the measured 100k boundary). officialIds ⊆ exactIds by
1051
+ // construction (official rows are names rows), so only the sub-tier KIND changes.
1052
+ const officialIds = this.#weights.officialNameExact
1053
+ ? this.#officialNameIds(
1054
+ sch,
1055
+ candidates
1056
+ .filter(
1057
+ (c) => exactIds.has(c.id as number) && (c.population ?? 0) >= this.#weights.officialNameExactFloor
1058
+ )
1059
+ .map((c) => c.id as number),
1060
+ query.text
1061
+ )
1062
+ : undefined
1063
+ const kind = (c: PlaceCandidate): number => {
1064
+ if (!exactIds.has(c.id as number)) return 0
1065
+
1066
+ if (norm(String(c.name ?? "")) === needle) return 2
1067
+
1068
+ return officialIds?.has(c.id as number) ? 2 : 1
1069
+ }
1070
+ // With proximity hints (near/bias), prominence (population + nearness, same units)
1071
+ // replaces raw population as the within-tier key — the 48026 rule: the map view or
1072
+ // the user's location breaks a cross-country postcode tie. Without hints, population
1073
+ // ordering is byte-identical to before.
1074
+ const hasHints = !!query.near || (query.bias?.length ?? 0) > 0
1075
+ candidates.sort((a, b) => {
1076
+ const ax = kind(a)
1077
+ const bx = kind(b)
1078
+
1079
+ if (bx !== ax) return bx - ax
1080
+
1081
+ if (ax >= 1) {
1082
+ if (hasHints) return (b.prominence ?? 0) - (a.prominence ?? 0) || b.score - a.score
1083
+
1084
+ return (b.population ?? 0) - (a.population ?? 0) || b.score - a.score
1085
+ }
1086
+
1087
+ return b.score - a.score
1088
+ })
1089
+
1090
+ return Promise.resolve(candidates.slice(0, limit))
1091
+ }
1092
+ }
1093
+
1094
+ candidates.sort((a, b) => b.score - a.score)
1095
+
1096
+ return Promise.resolve(candidates.slice(0, limit))
1097
+ }
1098
+
1099
+ #isLocalityQuery(query: FindPlaceQuery): boolean {
1100
+ const pts = normalizePlacetypes(query.placetype)
1101
+
1102
+ return !pts || pts.includes("locality")
1103
+ }
1104
+
1105
+ /**
1106
+ * Resolve the effective convention for a query (the Geographic Rule Engine entry point). The ancestor chain is keyed
1107
+ * by WOF polygon id; for #289 it carries just the country level — resolved from `query.country` via the cached
1108
+ * code→WOF-id lookup — so the EU locales, which have no override rows, resolve to `WORLD_DEFAULT` and dispatch is
1109
+ * byte-identical to the pre-engine path. E4 (JP) extends the chain with the resolved locality's `ancestors` row, so a
1110
+ * region/locality-level convention (e.g. Sapporo's grid) deep-merges over the country one.
1111
+ */
1112
+ #conventionFor(query: FindPlaceQuery): ResolvedConvention {
1113
+ const chain: number[] = []
1114
+
1115
+ if (query.country) {
1116
+ const cid = this.#countryWOFId(query.country)
1117
+
1118
+ if (cid !== null) {
1119
+ chain.push(cid)
1120
+ }
1121
+ }
1122
+
1123
+ return resolveConvention(this.#conventionSource, chain)
1124
+ }
1125
+
1126
+ /**
1127
+ * Country ISO code → its WOF polygon id (the coarsest convention key). Cached — one indexed `spr` query per distinct
1128
+ * country, then memoized (including a not-found `null`) so findPlace never pays for it twice.
1129
+ */
1130
+ #countryWOFId(code: string): number | null {
1131
+ const cached = this.#countryWOFIdCache.get(code)
1132
+
1133
+ if (cached !== undefined) return cached
1134
+ let id: number | null = null
1135
+
1136
+ try {
1137
+ const row = this.#db
1138
+ .prepare(`SELECT id FROM main.spr WHERE placetype = 'country' AND country = ? AND is_current != 0 LIMIT 1`)
1139
+ .get(code) as { id: number } | undefined
1140
+ id = row?.id ?? null
1141
+ } catch {
1142
+ id = null
1143
+ }
1144
+ this.#countryWOFIdCache.set(code, id)
1145
+
1146
+ return id
1147
+ }
1148
+
1149
+ /**
1150
+ * Coordinate-first locality resolution. The postcode_locality table maps the sibling postcode to the locality whose
1151
+ * polygon contains the postcode centroid (+ a few nearby ones for the abutting- postcode case). We union those
1152
+ * COORDINATE candidates with the FTS NAME candidates and soft-score the union `0.6·S_pc + 0.3·S_name + 0.1·S_pop` —
1153
+ * so a small town the name-match never finds is recovered by the postcode, while an unambiguous name (Berlin) still
1154
+ * wins on name + population. Returns null when the postcode isn't in the table (→ caller falls back to the FTS
1155
+ * path).
1156
+ */
1157
+ async #findLocalityCoordFirst(
1158
+ query: FindPlaceQuery,
1159
+ sch: string,
1160
+ convention: ResolvedConvention
1161
+ ): Promise<PlaceCandidate[] | null> {
1162
+ const w = convention.scoringWeights
1163
+ const pc = query.postcode!.trim()
1164
+ const pcWhere = query.country ? "postcode = ? AND country = ?" : "postcode = ?"
1165
+ const pcParams: SQLInputValue[] = query.country ? [pc, query.country] : [pc]
1166
+ const pcRows = this.#db
1167
+ .prepare(
1168
+ `SELECT locality_id AS id, aliases, distance_km AS dist, is_containing AS containing
1169
+ FROM ${sch}.${POSTCODE_LOCALITY_TABLE} WHERE ${pcWhere}`
1170
+ )
1171
+ .all(...pcParams) as unknown as Array<{ id: number; aliases: string | null; dist: number; containing: number }>
1172
+
1173
+ if (pcRows.length === 0) return null
1174
+
1175
+ const limit = query.limit ?? 10
1176
+ // Name-match candidates via the normal FTS path (postcode cleared → no recursion).
1177
+ const ftsCands = await this.findPlace({ ...query, postcode: undefined, limit: Math.max(limit, 10) })
1178
+
1179
+ const pcInfo = new Map<number, { dist: number; containing: boolean; aliases: string[] }>()
1180
+
1181
+ for (const r of pcRows) {
1182
+ pcInfo.set(r.id, { dist: r.dist, containing: r.containing === 1, aliases: r.aliases ? r.aliases.split("|") : [] })
1183
+ }
1184
+
1185
+ // #475 (opt-in): observed postal-city aliases for this postcode, keyed by the geographic
1186
+ // locality name they map to. A user-typed postal city ("Antioch", 37013) becomes a name-match
1187
+ // alias for the geographic locality the postcode sits in ("Nashville"). Empty when the reader
1188
+ // isn't supplied → the scoring loop below is byte-identical to pre-#475.
1189
+ const postalAliasByGeo = new Map<string, string[]>()
1190
+
1191
+ if (this.#postalCityAliases) {
1192
+ for (const a of await this.#postalCityAliases.getDivergentAliases(pc)) {
1193
+ const key = cfNormalize(a.geoLocality)
1194
+
1195
+ if (!key) continue
1196
+ const bag = postalAliasByGeo.get(key)
1197
+
1198
+ if (bag) {
1199
+ bag.push(a.postalCity)
1200
+ } else {
1201
+ postalAliasByGeo.set(key, [a.postalCity])
1202
+ }
1203
+ }
1204
+ }
1205
+
1206
+ const merged = new Map<number, PlaceCandidate>()
1207
+
1208
+ for (const c of ftsCands) {
1209
+ merged.set(c.id as number, c)
1210
+ }
1211
+ const missing = [...pcInfo.keys()].filter((id) => !merged.has(id))
1212
+
1213
+ for (const row of this.#fetchLocalitiesByID(missing)) {
1214
+ merged.set(row.id, row)
1215
+ }
1216
+
1217
+ const scored: Array<PlaceCandidate & { exact: boolean }> = []
1218
+
1219
+ for (const cand of merged.values()) {
1220
+ const info = pcInfo.get(cand.id as number)
1221
+ const sPc = info ? (info.containing ? 1 : Math.exp(-info.dist / CF_PC_DECAY_KM)) : 0
1222
+ // Fold any postal-city aliases for this candidate's geographic name into the soft name match
1223
+ // (#475). `postalAliasByGeo` is empty unless the opt-in reader was supplied, so when off this
1224
+ // reduces to the original `info?.aliases ?? []` and the score is unchanged.
1225
+ const wofAliases = info?.aliases ?? []
1226
+ const aliases =
1227
+ postalAliasByGeo.size > 0
1228
+ ? [...wofAliases, ...(postalAliasByGeo.get(cfNormalize(cand.name)) ?? [])]
1229
+ : wofAliases
1230
+ const sName = softNameScore(query.text, cand.name, aliases)
1231
+ const sPop = cand.population && cand.population > 0 ? Math.min(1, Math.log10(1 + cand.population) / 6) : 0
1232
+ scored.push({ ...cand, score: w.pc * sPc + w.name * sName + w.pop * sPop, exact: sName >= 1 })
1233
+ }
1234
+ // Exact-name tiering (same philosophy as the FTS path): an EXACT name/alias match tiers above
1235
+ // coordinate-only candidates, with the soft-score breaking ties WITHIN a tier. This keeps an
1236
+ // unambiguous city ("Berlin", exact + huge population) ahead of the fine-grained Ortsteil its
1237
+ // postcode centroid lands in, while a small town the name-match never finds (no exact tier) is
1238
+ // still recovered by its postcode's containing locality.
1239
+ scored.sort((a, b) => Number(b.exact) - Number(a.exact) || b.score - a.score)
1240
+
1241
+ // Conflict flag: if the chosen locality is NOT the postcode's containing locality and sits far
1242
+ // from it, the postcode and the city name disagree (a transposed / wrong-for-the-city postcode).
1243
+ // We keep the name-chosen locality but flag it — the falsehood signal a BM25 geocoder can't give.
1244
+ const top = scored[0]
1245
+
1246
+ if (top) {
1247
+ // The postcode's geographic anchor: among the postcode's candidate localities that actually
1248
+ // resolved (some — e.g. unnamed Ortsteile — are in the postcode table but not the admin DB),
1249
+ // prefer the containing one, else the nearest. Postcodes whose centroid falls just outside
1250
+ // every locality polygon still anchor to the closest town.
1251
+ const anchorRow = pcRows
1252
+ .filter((r) => merged.has(r.id))
1253
+ .sort((a, b) => b.containing - a.containing || a.dist - b.dist)[0]
1254
+ const anchor = anchorRow ? merged.get(anchorRow.id) : undefined
1255
+
1256
+ if (anchor && (top.id as number) !== anchorRow!.id) {
1257
+ if (haversineKm(top.lat, top.lon, anchor.lat, anchor.lon) > CF_MISMATCH_KM) {
1258
+ top.mismatch = true
1259
+ }
1260
+ }
1261
+ }
1262
+
1263
+ return scored.slice(0, limit).map(({ exact, ...c }) => {
1264
+ void exact
1265
+
1266
+ return c
1267
+ })
1268
+ }
1269
+
1270
+ /** Fetch locality spr rows (from main) for the postcode-injected candidate ids the FTS set missed. */
1271
+ #fetchLocalitiesByID(ids: number[]): PlaceCandidate[] {
1272
+ if (ids.length === 0) return []
1273
+ const hasPop = this.#hasPopulationIndex.get("main") === true
1274
+ const popSelect = hasPop ? `pp.population AS population` : `NULL AS population`
1275
+ const popJoin = hasPop ? `LEFT JOIN main.${PLACE_POPULATION_TABLE} pp ON pp.id = s.id` : ""
1276
+ const ph = ids.map(() => "?").join(", ")
1277
+ const rows = this.#db
1278
+ .prepare(
1279
+ `SELECT s.id AS id, s.name AS name, s.country AS country, s.parent_id AS parent_id,
1280
+ s.latitude AS lat, s.longitude AS lon, s.placetype AS placetype, ${popSelect}
1281
+ FROM main.spr s ${popJoin}
1282
+ WHERE s.id IN (${ph}) AND s.is_current != 0`
1283
+ )
1284
+ .all(...ids) as unknown as Array<RawSearchRow>
1285
+
1286
+ return rows.map((row) => {
1287
+ const c: PlaceCandidate = {
1288
+ id: row.id,
1289
+ name: row.name,
1290
+ placetype: row.placetype as WOFPlacetype,
1291
+ country: row.country ?? "",
1292
+ lat: row.lat ?? 0,
1293
+ lon: row.lon ?? 0,
1294
+ parent_id: row.parent_id ?? undefined,
1295
+ score: 0,
1296
+ }
1297
+
1298
+ if (row.population !== null && row.population > 0) {
1299
+ c.population = row.population
1300
+ }
1301
+
1302
+ return c
1303
+ })
1304
+ }
1305
+
1306
+ /**
1307
+ * Among `ids`, return the subset whose name OR any alias equals `text` case-insensitively — the exact-match tier for
1308
+ * ranking. One indexed query over `<schema>.names`. When the shard has no `names` table (a slim DB built with
1309
+ * `dropNames`, or a postcode-only shard), fall back to the self-contained `place_search` FTS content: its `alt_names`
1310
+ * column is the same alias set joined on the boundary-preserving `ALIAS_SEPARATOR` (#523), so `aliasBagExactMatch`
1311
+ * recovers the exact alias tier ("New York City" → New York) that the dropped `names` table used to provide.
1312
+ */
1313
+ #exactMatchIds(schemaName: string, ids: number[], text: string): Set<number> {
1314
+ const out = new Set<number>()
1315
+ const trimmed = text.trim()
1316
+
1317
+ if (ids.length === 0 || !trimmed) return out
1318
+ const placeholders = ids.map(() => "?").join(", ")
1319
+
1320
+ try {
1321
+ const rows = this.#db
1322
+ .prepare(
1323
+ `SELECT DISTINCT id FROM ${schemaName}.names WHERE id IN (${placeholders}) AND name = ? COLLATE NOCASE`
1324
+ )
1325
+ .all(...ids, trimmed) as Array<{ id: number }>
1326
+
1327
+ for (const r of rows) {
1328
+ out.add(r.id)
1329
+ }
1330
+
1331
+ return out
1332
+ } catch {
1333
+ // No `names` table on this shard — fall through to the place_search alias bag.
1334
+ }
1335
+
1336
+ try {
1337
+ const rows = this.#db
1338
+ .prepare(
1339
+ `SELECT wof_id AS id, name, alt_names FROM ${schemaName}.place_search WHERE wof_id IN (${placeholders})`
1340
+ )
1341
+ .all(...ids) as Array<{ id: number; name: string | null; alt_names: string | null }>
1342
+ const norm = (s: string): string => s.toLowerCase().trim().replace(/\s+/g, " ")
1343
+ const needle = norm(trimmed)
1344
+
1345
+ for (const r of rows) {
1346
+ if (r.name !== null && norm(r.name) === needle) {
1347
+ out.add(r.id)
1348
+ }
1349
+ }
1350
+ // Alias pass via the shared bag parser (#523). Separated bags (built since #523) get a true
1351
+ // per-alias equality check, ungated — matching the `names`-table branch above, where an
1352
+ // alias match counts as exact regardless of other candidates. Legacy bags (no separator)
1353
+ // fall back to padded containment, gated on "no canonical exact in the pool" because their
1354
+ // lost boundaries would otherwise false-promote interior fragments ("York" inside the alias
1355
+ // "New York City") or cross-alias fragments ("York New" across "…York" + "New City…").
1356
+ const anyCanonicalExact = out.size > 0
1357
+
1358
+ for (const r of rows) {
1359
+ if (aliasBagExactMatch(r.alt_names, needle, anyCanonicalExact)) {
1360
+ out.add(r.id)
1361
+ }
1362
+ }
1363
+ } catch {
1364
+ // Shard without place_search either → no exact-match tier. Falls back to weighted-sum order.
1365
+ }
1366
+
1367
+ return out
1368
+ }
1369
+
1370
+ /**
1371
+ * Among `ids` (already known exact matches), the subset holding `text` as an OFFICIAL name (`names.official = 1`, the
1372
+ * #940 ingest bit). Same COLLATE NOCASE semantics as {@link WOFSqlitePlaceLookup.#exactMatchIds} so the two probes
1373
+ * agree on what "equals the query" means. Fails soft on gazetteers built before #940 (no `official` column) — the
1374
+ * sub-tier then behaves exactly as if `officialNameExact` were off.
1375
+ */
1376
+ #officialNameIds(schemaName: string, ids: number[], text: string): Set<number> {
1377
+ const out = new Set<number>()
1378
+ const trimmed = text.trim()
1379
+
1380
+ if (ids.length === 0 || !trimmed) return out
1381
+ const placeholders = ids.map(() => "?").join(", ")
1382
+
1383
+ try {
1384
+ const rows = this.#db
1385
+ .prepare(
1386
+ `SELECT DISTINCT id FROM ${schemaName}.names WHERE id IN (${placeholders}) AND official = 1 AND name = ? COLLATE NOCASE`
1387
+ )
1388
+ .all(...ids, trimmed) as Array<{ id: number }>
1389
+
1390
+ for (const r of rows) {
1391
+ out.add(r.id)
1392
+ }
1393
+ } catch {
1394
+ // Pre-#940 gazetteer (no `official` column) or a names-less slim shard — feature inert.
1395
+ }
1396
+
1397
+ return out
1398
+ }
1399
+
1400
+ close(): void {
1401
+ // Destroying the Kysely instance closes the underlying connection IF we own it. If the caller
1402
+ // passed in a pre-opened DatabaseSync (test fixture), respect their ownership.
1403
+ void this.#kysely.destroy()
1404
+
1405
+ if (this.#ownsDB) {
1406
+ this.#db.close()
1407
+ }
1408
+ }
1409
+
1410
+ [Symbol.dispose](): void {
1411
+ this.close()
1412
+ }
1413
+
1414
+ /** Build the FTS5 virtual table from the `names` + `places` tables. */
1415
+ #ensureFTS(): void {
1416
+ buildPlaceSearchFTS(this.#db)
1417
+ }
1418
+
1419
+ #assertFTSExists(): void {
1420
+ if (!placeSearchFTSExists(this.#db)) {
1421
+ throw new Error(
1422
+ "WOFSqlitePlaceLookup: `place_search` FTS5 table is missing. Pass `buildFTS: true` to build it on open, or run `mailwoman gazetteer build fts <path-to-wof.db>` ahead of time (see resolver-wof-sqlite/README.md)."
1423
+ )
1424
+ }
1425
+ }
1426
+ }
1427
+
1428
+ function normalizePlacetypes(p: FindPlaceQuery["placetype"]): WOFPlacetype[] | null {
1429
+ if (!p) return null
1430
+
1431
+ return Array.isArray(p) ? p : [p]
1432
+ }
1433
+
1434
+ /**
1435
+ * Make an arbitrary user-typed string safe for FTS5 MATCH.
1436
+ *
1437
+ * FTS5 has its own query syntax (`"phrase"`, `term1 OR term2`, `prefix*`, NEAR/N, etc.). Letting raw user input through
1438
+ * means a user typing `Paris's` or `St. (Petersburg)` causes a syntax error.
1439
+ *
1440
+ * Per-token rules:
1441
+ *
1442
+ * - Strip all punctuation except trailing `*` from each whitespace-separated token.
1443
+ * - **Trailing `*`** is preserved as FTS5 **prefix syntax** — `627*` becomes the literal `627*` (unquoted). The caller
1444
+ * signaled they want a prefix; respect that.
1445
+ * - All other tokens are wrapped in `"..."` as a single-word phrase. Conservative — handles apostrophes, parens, accented
1446
+ * input, etc. safely.
1447
+ * - Multiple tokens join with implicit AND.
1448
+ *
1449
+ * Examples:
1450
+ *
1451
+ * - `"Paris"` → `"Paris"` (phrase)
1452
+ * - `"627*"` → `627*` (prefix)
1453
+ * - `"St. (Petersburg)"` → `"St" "Petersburg"` (two phrases, AND-joined)
1454
+ * - `"Thiron-Gardais"` → `"Thiron" "Gardais"` (intra-token punctuation SPLITS — #945; fusing to `ThironGardais` matched
1455
+ * nothing because the FTS doc tokenizes the hyphenated name as two terms)
1456
+ * - `"110 00"` with `fuseTokens` (postcode-typed) → `"110" "00"` per-token fused — the #920 name law
1457
+ * - `"Pari* TX"` → `Pari* "TX"` (mixed prefix + phrase)
1458
+ * - `"*"` alone → `""` (no body → drop)
1459
+ */
1460
+ function sanitizeFTSQuery(text: string, opts?: { fuseTokens?: boolean }): string {
1461
+ const out: string[] = []
1462
+
1463
+ for (const rawToken of text.normalize("NFKC").split(/\s+/u)) {
1464
+ const trimmed = rawToken.trim()
1465
+
1466
+ if (!trimmed) continue
1467
+ const hasPrefixStar = trimmed.endsWith("*")
1468
+
1469
+ // #920 name law (postcode-typed queries ONLY): delete intra-token punctuation and FUSE the
1470
+ // remainder — postal names are stored in this collapsed shape ("SW1A" stays one term).
1471
+ if (opts?.fuseTokens) {
1472
+ const body = trimmed.replace(/[^\p{L}\p{N}]/gu, "")
1473
+
1474
+ if (!body) continue
1475
+ out.push(hasPrefixStar ? `${body}*` : `"${body.replace(/"/g, '""')}"`)
1476
+ continue
1477
+ }
1478
+
1479
+ // Everything else SPLITS on intra-token punctuation — the behavior the docstring always
1480
+ // promised ("St. (Petersburg)" → two phrases). The old code DELETED punctuation instead,
1481
+ // fusing "Thiron-Gardais" into the unmatchable single term `ThironGardais` while the FTS
1482
+ // doc holds two terms (#945 — the entire hyphenated-name class missed at the raw lookup;
1483
+ // masked for years because pre-splice tokenizers never emitted hyphen-preserved values).
1484
+ const parts = trimmed.split(/[^\p{L}\p{N}]+/u).filter(Boolean)
1485
+
1486
+ if (parts.length === 0) continue
1487
+
1488
+ for (let i = 0; i < parts.length; i++) {
1489
+ const body = parts[i]!.replace(/\*/g, "")
1490
+
1491
+ if (!body) continue
1492
+ // The caller's trailing `*` applies to the FINAL part ("Thiron-Gard*" → "Thiron" Gard*).
1493
+ out.push(hasPrefixStar && i === parts.length - 1 ? `${body}*` : `"${body.replace(/"/g, '""')}"`)
1494
+ }
1495
+ }
1496
+
1497
+ return out.join(" ")
1498
+ }