@mailwoman/resolver-wof-sqlite 9.0.0 → 9.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (297) hide show
  1. package/README.md +28 -9
  2. package/address-point-interpolation.ts +18 -8
  3. package/address-point-schema.ts +18 -6
  4. package/address-point.ts +111 -18
  5. package/ancestry.ts +9 -6
  6. package/build-candidate.ts +287 -157
  7. package/build-slim.ts +3 -3
  8. package/candidate/alias-bags.ts +54 -0
  9. package/candidate/ancestors-sidecar.ts +206 -0
  10. package/candidate/country-display-names.ts +79 -0
  11. package/candidate/name-roles.ts +237 -0
  12. package/candidate/own-name.ts +146 -0
  13. package/candidate/place-attrs.ts +44 -0
  14. package/candidate/shard-fold.ts +137 -0
  15. package/candidate-ancestors-schema.ts +195 -0
  16. package/candidate-fts.ts +4 -2
  17. package/candidate-importance.ts +228 -0
  18. package/candidate-lookup.ts +564 -174
  19. package/candidate-schema.ts +60 -3
  20. package/candidate-scoring.ts +268 -0
  21. package/capital-schema.ts +90 -0
  22. package/capitals.ts +148 -0
  23. package/coincident-roles.ts +69 -10
  24. package/convention-schema.ts +72 -0
  25. package/convention.ts +2 -2
  26. package/coverage-manifest-schema.ts +7 -7
  27. package/currency-backfill.ts +249 -0
  28. package/exact-match.ts +104 -0
  29. package/fst-autocomplete.ts +105 -122
  30. package/fst-builder.ts +39 -47
  31. package/fst-deserialize-web.ts +43 -7
  32. package/fst-freshness.ts +2 -2
  33. package/fst-serialize.ts +68 -12
  34. package/fst-types.ts +35 -1
  35. package/fts-query.ts +1 -1
  36. package/fts.ts +16 -4
  37. package/geonames-postal.ts +2 -2
  38. package/index.ts +26 -14
  39. package/interpolation.ts +113 -19
  40. package/lookup.ts +118 -560
  41. package/name-score.ts +6 -4
  42. package/out/address-point-interpolation.d.ts.map +1 -1
  43. package/out/address-point-interpolation.js +13 -7
  44. package/out/address-point-interpolation.js.map +1 -1
  45. package/out/address-point-schema.d.ts +16 -6
  46. package/out/address-point-schema.d.ts.map +1 -1
  47. package/out/address-point-schema.js.map +1 -1
  48. package/out/address-point.d.ts.map +1 -1
  49. package/out/address-point.js +70 -14
  50. package/out/address-point.js.map +1 -1
  51. package/out/ancestry.d.ts +2 -2
  52. package/out/ancestry.d.ts.map +1 -1
  53. package/out/ancestry.js +5 -6
  54. package/out/ancestry.js.map +1 -1
  55. package/out/build-candidate.d.ts +108 -0
  56. package/out/build-candidate.d.ts.map +1 -1
  57. package/out/build-candidate.js +151 -120
  58. package/out/build-candidate.js.map +1 -1
  59. package/out/build-slim.d.ts +1 -1
  60. package/out/build-slim.js +3 -3
  61. package/out/build-slim.js.map +1 -1
  62. package/out/candidate/alias-bags.d.ts +17 -0
  63. package/out/candidate/alias-bags.d.ts.map +1 -0
  64. package/out/candidate/alias-bags.js +39 -0
  65. package/out/candidate/alias-bags.js.map +1 -0
  66. package/out/candidate/ancestors-sidecar.d.ts +33 -0
  67. package/out/candidate/ancestors-sidecar.d.ts.map +1 -0
  68. package/out/candidate/ancestors-sidecar.js +140 -0
  69. package/out/candidate/ancestors-sidecar.js.map +1 -0
  70. package/out/candidate/country-display-names.d.ts +35 -0
  71. package/out/candidate/country-display-names.d.ts.map +1 -0
  72. package/out/candidate/country-display-names.js +59 -0
  73. package/out/candidate/country-display-names.js.map +1 -0
  74. package/out/candidate/name-roles.d.ts +55 -0
  75. package/out/candidate/name-roles.d.ts.map +1 -0
  76. package/out/candidate/name-roles.js +165 -0
  77. package/out/candidate/name-roles.js.map +1 -0
  78. package/out/candidate/own-name.d.ts +50 -0
  79. package/out/candidate/own-name.d.ts.map +1 -0
  80. package/out/candidate/own-name.js +132 -0
  81. package/out/candidate/own-name.js.map +1 -0
  82. package/out/candidate/place-attrs.d.ts +43 -0
  83. package/out/candidate/place-attrs.d.ts.map +1 -0
  84. package/out/candidate/place-attrs.js +15 -0
  85. package/out/candidate/place-attrs.js.map +1 -0
  86. package/out/candidate/shard-fold.d.ts +31 -0
  87. package/out/candidate/shard-fold.d.ts.map +1 -0
  88. package/out/candidate/shard-fold.js +104 -0
  89. package/out/candidate/shard-fold.js.map +1 -0
  90. package/out/candidate-ancestors-schema.d.ts +150 -0
  91. package/out/candidate-ancestors-schema.d.ts.map +1 -0
  92. package/out/candidate-ancestors-schema.js +123 -0
  93. package/out/candidate-ancestors-schema.js.map +1 -0
  94. package/out/candidate-fts.d.ts +4 -2
  95. package/out/candidate-fts.d.ts.map +1 -1
  96. package/out/candidate-fts.js +4 -2
  97. package/out/candidate-fts.js.map +1 -1
  98. package/out/candidate-importance.d.ts +132 -0
  99. package/out/candidate-importance.d.ts.map +1 -0
  100. package/out/candidate-importance.js +174 -0
  101. package/out/candidate-importance.js.map +1 -0
  102. package/out/candidate-lookup.d.ts +22 -37
  103. package/out/candidate-lookup.d.ts.map +1 -1
  104. package/out/candidate-lookup.js +446 -132
  105. package/out/candidate-lookup.js.map +1 -1
  106. package/out/candidate-schema.d.ts +52 -4
  107. package/out/candidate-schema.d.ts.map +1 -1
  108. package/out/candidate-schema.js +8 -0
  109. package/out/candidate-schema.js.map +1 -1
  110. package/out/candidate-scoring.d.ts +34 -0
  111. package/out/candidate-scoring.d.ts.map +1 -0
  112. package/out/candidate-scoring.js +200 -0
  113. package/out/candidate-scoring.js.map +1 -0
  114. package/out/capital-schema.d.ts +51 -0
  115. package/out/capital-schema.d.ts.map +1 -0
  116. package/out/capital-schema.js +63 -0
  117. package/out/capital-schema.js.map +1 -0
  118. package/out/capitals.d.ts +69 -0
  119. package/out/capitals.d.ts.map +1 -0
  120. package/out/capitals.js +98 -0
  121. package/out/capitals.js.map +1 -0
  122. package/out/coincident-roles.d.ts +7 -0
  123. package/out/coincident-roles.d.ts.map +1 -1
  124. package/out/coincident-roles.js +42 -8
  125. package/out/coincident-roles.js.map +1 -1
  126. package/out/convention-schema.d.ts +51 -0
  127. package/out/convention-schema.d.ts.map +1 -0
  128. package/out/convention-schema.js +34 -0
  129. package/out/convention-schema.js.map +1 -0
  130. package/out/convention.d.ts +1 -1
  131. package/out/convention.js +2 -2
  132. package/out/coverage-manifest-schema.js +3 -7
  133. package/out/coverage-manifest-schema.js.map +1 -1
  134. package/out/currency-backfill.d.ts +46 -0
  135. package/out/currency-backfill.d.ts.map +1 -0
  136. package/out/currency-backfill.js +180 -0
  137. package/out/currency-backfill.js.map +1 -0
  138. package/out/exact-match.d.ts +25 -0
  139. package/out/exact-match.d.ts.map +1 -0
  140. package/out/exact-match.js +89 -0
  141. package/out/exact-match.js.map +1 -0
  142. package/out/fst-autocomplete.d.ts +24 -14
  143. package/out/fst-autocomplete.d.ts.map +1 -1
  144. package/out/fst-autocomplete.js +84 -100
  145. package/out/fst-autocomplete.js.map +1 -1
  146. package/out/fst-builder.d.ts.map +1 -1
  147. package/out/fst-builder.js +32 -40
  148. package/out/fst-builder.js.map +1 -1
  149. package/out/fst-deserialize-web.d.ts.map +1 -1
  150. package/out/fst-deserialize-web.js +36 -7
  151. package/out/fst-deserialize-web.js.map +1 -1
  152. package/out/fst-freshness.d.ts +2 -2
  153. package/out/fst-freshness.js +2 -2
  154. package/out/fst-serialize.d.ts +14 -4
  155. package/out/fst-serialize.d.ts.map +1 -1
  156. package/out/fst-serialize.js +60 -12
  157. package/out/fst-serialize.js.map +1 -1
  158. package/out/fst-types.d.ts +35 -1
  159. package/out/fst-types.d.ts.map +1 -1
  160. package/out/fts-query.js +1 -1
  161. package/out/fts-query.js.map +1 -1
  162. package/out/fts.d.ts +15 -4
  163. package/out/fts.d.ts.map +1 -1
  164. package/out/fts.js +15 -4
  165. package/out/fts.js.map +1 -1
  166. package/out/geonames-postal.d.ts +2 -2
  167. package/out/geonames-postal.js +2 -2
  168. package/out/index.d.ts +4 -2
  169. package/out/index.d.ts.map +1 -1
  170. package/out/index.js +3 -2
  171. package/out/index.js.map +1 -1
  172. package/out/interpolation.d.ts +8 -0
  173. package/out/interpolation.d.ts.map +1 -1
  174. package/out/interpolation.js +91 -19
  175. package/out/interpolation.js.map +1 -1
  176. package/out/lookup.d.ts +4 -5
  177. package/out/lookup.d.ts.map +1 -1
  178. package/out/lookup.js +102 -444
  179. package/out/lookup.js.map +1 -1
  180. package/out/name-score.d.ts +0 -10
  181. package/out/name-score.d.ts.map +1 -1
  182. package/out/name-score.js +6 -4
  183. package/out/name-score.js.map +1 -1
  184. package/out/place-importance-schema.d.ts +226 -0
  185. package/out/place-importance-schema.d.ts.map +1 -0
  186. package/out/place-importance-schema.js +288 -0
  187. package/out/place-importance-schema.js.map +1 -0
  188. package/out/poi-lookup.d.ts +1 -1
  189. package/out/poi-lookup.d.ts.map +1 -1
  190. package/out/poi-lookup.js +12 -13
  191. package/out/poi-lookup.js.map +1 -1
  192. package/out/poi-schema.d.ts +7 -3
  193. package/out/poi-schema.d.ts.map +1 -1
  194. package/out/poi-schema.js.map +1 -1
  195. package/out/polygon-schema.d.ts +37 -0
  196. package/out/polygon-schema.d.ts.map +1 -0
  197. package/out/polygon-schema.js +23 -0
  198. package/out/polygon-schema.js.map +1 -0
  199. package/out/postal-city-alias-lookup.d.ts +1 -1
  200. package/out/postal-city-alias-lookup.js +1 -1
  201. package/out/postal-city-candidate-schema.d.ts +2 -1
  202. package/out/postal-city-candidate-schema.d.ts.map +1 -1
  203. package/out/postal-city-candidate-schema.js.map +1 -1
  204. package/out/postcode-point-lookup.d.ts +1 -1
  205. package/out/postcode-point-lookup.js +1 -1
  206. package/out/primary-preference.d.ts +125 -0
  207. package/out/primary-preference.d.ts.map +1 -0
  208. package/out/primary-preference.js +138 -0
  209. package/out/primary-preference.js.map +1 -0
  210. package/out/proximity-rerank.d.ts +77 -0
  211. package/out/proximity-rerank.d.ts.map +1 -0
  212. package/out/proximity-rerank.js +86 -0
  213. package/out/proximity-rerank.js.map +1 -0
  214. package/out/region-keys.d.ts +47 -0
  215. package/out/region-keys.d.ts.map +1 -0
  216. package/out/region-keys.js +121 -0
  217. package/out/region-keys.js.map +1 -0
  218. package/out/reverse.d.ts.map +1 -1
  219. package/out/reverse.js +6 -9
  220. package/out/reverse.js.map +1 -1
  221. package/out/schema.d.ts +1 -1
  222. package/out/search-fetch.d.ts +57 -0
  223. package/out/search-fetch.d.ts.map +1 -0
  224. package/out/search-fetch.js +183 -0
  225. package/out/search-fetch.js.map +1 -0
  226. package/out/sharding.d.ts +3 -3
  227. package/out/sharding.js +1 -1
  228. package/out/sqlite-convention-source.d.ts +1 -1
  229. package/out/sqlite-convention-source.js +1 -1
  230. package/out/sqlite-utils.d.ts +31 -1
  231. package/out/sqlite-utils.d.ts.map +1 -1
  232. package/out/sqlite-utils.js +38 -0
  233. package/out/sqlite-utils.js.map +1 -1
  234. package/out/street-centroid-schema.d.ts +7 -2
  235. package/out/street-centroid-schema.d.ts.map +1 -1
  236. package/out/street-centroid-schema.js.map +1 -1
  237. package/out/street-centroid.d.ts.map +1 -1
  238. package/out/street-centroid.js +7 -7
  239. package/out/street-centroid.js.map +1 -1
  240. package/out/street-morphology-fst-builder.d.ts.map +1 -1
  241. package/out/street-morphology-fst-builder.js +5 -4
  242. package/out/street-morphology-fst-builder.js.map +1 -1
  243. package/out/street-normalize.d.ts +83 -9
  244. package/out/street-normalize.d.ts.map +1 -1
  245. package/out/street-normalize.js +177 -10
  246. package/out/street-normalize.js.map +1 -1
  247. package/out/street-segment-schema.d.ts +6 -2
  248. package/out/street-segment-schema.d.ts.map +1 -1
  249. package/out/street-segment-schema.js.map +1 -1
  250. package/out/types.d.ts +74 -1
  251. package/out/types.d.ts.map +1 -1
  252. package/out/unified-schema.d.ts +1 -1
  253. package/out/unified-schema.js +1 -1
  254. package/out/uprn-lookup.d.ts +85 -0
  255. package/out/uprn-lookup.d.ts.map +1 -0
  256. package/out/uprn-lookup.js +152 -0
  257. package/out/uprn-lookup.js.map +1 -0
  258. package/out/uprn-schema.d.ts +93 -0
  259. package/out/uprn-schema.d.ts.map +1 -0
  260. package/out/uprn-schema.js +78 -0
  261. package/out/uprn-schema.js.map +1 -0
  262. package/out/weights-overlay-linker.d.ts +141 -0
  263. package/out/weights-overlay-linker.d.ts.map +1 -0
  264. package/out/weights-overlay-linker.js +259 -0
  265. package/out/weights-overlay-linker.js.map +1 -0
  266. package/package.json +296 -16
  267. package/place-importance-schema.ts +402 -0
  268. package/poi-lookup.ts +12 -13
  269. package/poi-schema.ts +8 -3
  270. package/polygon-schema.ts +47 -0
  271. package/postal-city-alias-lookup.ts +1 -1
  272. package/postal-city-candidate-schema.ts +3 -1
  273. package/postcode-point-lookup.ts +1 -1
  274. package/primary-preference.ts +207 -0
  275. package/proximity-rerank.ts +120 -0
  276. package/region-keys.ts +144 -0
  277. package/reverse.ts +17 -16
  278. package/schema.ts +1 -1
  279. package/search-fetch.ts +256 -0
  280. package/sharding.ts +3 -3
  281. package/sqlite-convention-source.ts +1 -1
  282. package/sqlite-utils.ts +63 -1
  283. package/street-centroid-schema.ts +8 -2
  284. package/street-centroid.ts +13 -8
  285. package/street-morphology-fst-builder.ts +5 -4
  286. package/street-normalize.ts +254 -24
  287. package/street-segment-schema.ts +7 -2
  288. package/types.ts +74 -1
  289. package/unified-schema.ts +1 -1
  290. package/uprn-lookup.ts +210 -0
  291. package/uprn-schema.ts +124 -0
  292. package/weights-overlay-linker.ts +377 -0
  293. package/geo.ts +0 -121
  294. package/out/geo.d.ts +0 -74
  295. package/out/geo.d.ts.map +0 -1
  296. package/out/geo.js +0 -71
  297. package/out/geo.js.map +0 -1
package/out/lookup.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * `WOFSqlitePlaceLookup` — the resolver implementation backed by `node:sqlite` + a Kysely-typed
6
+ * `WOFSQLitePlaceLookup` — the resolver implementation backed by `node:sqlite` + a Kysely-typed
7
7
  * query layer where the queries are non-trivial, and raw SQL where they aren't (FTS5 MATCH, the
8
8
  * FTS index build).
9
9
  *
@@ -12,43 +12,39 @@
12
12
  import { DatabaseSync } from "node:sqlite";
13
13
  import { SqliteDialect } from "@mailwoman/core/kysley/dialect";
14
14
  import { expandPlacetypeFilter } from "@mailwoman/resolver";
15
+ import { haversineKm } from "@mailwoman/spatial";
15
16
  import { Kysely } from "kysely";
16
17
  import { ancestorLineage } from "./ancestry.js";
17
- import { COINCIDENT_ROLES_TABLE, coincidentRolesExists } from "./coincident-roles.js";
18
+ import { candidateFromSearchRow, rankCandidates } from "./candidate-scoring.js";
19
+ import { loadCoincidentLocalities } from "./coincident-roles.js";
18
20
  import { ADDRESS_CONVENTION_TABLE, resolveConvention, SeedConventionSource, } from "./convention.js";
19
21
  import { normalizePlacetypes, sanitizeFTSQuery } from "./fts-query.js";
20
- import { aliasBagExactMatch, buildPlaceSearchFTS, PLACE_BBOX_TABLE, PLACE_POPULATION_TABLE, placeBboxExists, placePopulationExists, placeSearchFTSExists, } from "./fts.js";
21
- import { bboxAround, haversineKm } from "./geo.js";
22
- import { cfNormalize, softNameScore, trigramJaccard } from "./name-score.js";
22
+ import { buildPlaceSearchFTS, PLACE_BBOX_TABLE, PLACE_POPULATION_TABLE, PLACE_SEARCH_TABLE, placeBboxExists, placePopulationExists, placeSearchFTSExists, } from "./fts.js";
23
+ import { cfNormalize, softNameScore } from "./name-score.js";
24
+ import { encyclopedicClauses } from "./place-importance-schema.js";
23
25
  import { DEFAULT_WEIGHTS } from "./ranking-weights.js";
26
+ import { fetchSearchRows } from "./search-fetch.js";
24
27
  import { pickShardForPlacetype, pickShardsForPlacetype, resolveShards, } from "./sharding.js";
25
28
  import { SqliteConventionSource } from "./sqlite-convention-source.js";
26
- /**
27
- * Query length at or below which the FTS window is widened. A two- or three-character query is almost always a region
28
- * abbreviation, where the exact match can otherwise fall outside the window behind higher-bm25 partial hits — "NY"
29
- * losing to "New York".
30
- */
31
- const SHORT_QUERY_MAX_LENGTH = 3;
32
- /**
33
- * Over-fetch floor for SHORT (≤3-char) queries — region abbreviations like "NY"/"VT". An exact-abbrev holder's BM25 is
34
- * poor (long multilingual alt-name document), so the normal `limit * 4` window can drop it before `exactMatchTiering`
35
- * promotes it. 200 comfortably covers every same-abbrev region across the 12-country gazetteer (a 2-letter token
36
- * matches a few dozen regions at most) while staying a cheap region-placetype fetch. See the `#fuzzyNameMatch`
37
- * over-fetch comment.
38
- */
39
- const SHORT_QUERY_OVERFETCH = 200;
40
- /**
41
- * How many rows the population-ordered companion fetch (#905) adds to the candidate pool. Small on purpose: its only
42
- * job is to guarantee the FAMOUS holders of a name enter the pool at all — for "Paris"-class floods the bm25 window is
43
- * saturated by thousands of tiny same-name rows and no boost inside the bm25-based ORDER BY can rescue a candidate
44
- * whose bm25 is length-poisoned by ~15 points (see the fetch-site comment).
45
- */
46
- const POPULATION_FETCH_LIMIT = 15;
29
+ import { allRows } from "./sqlite-utils.js";
47
30
  /**
48
31
  * The coordinate-first candidate table (scripts/build-postcode-locality.ts): postcode → containing
49
32
  *
50
33
  * - Nearby localities with WOF alt-name aliases.
51
34
  */
35
+ /**
36
+ * The placetypes `pickShardsForPlacetype`'s substring rule can route by name. Not every WOF placetype — only the ones a
37
+ * purpose-built shard is ever named for — so the diagnostic below can say "this name routes nowhere" without claiming
38
+ * to enumerate the gazetteer.
39
+ */
40
+ const KNOWN_ROUTED_PLACETYPES = [
41
+ "postalcode",
42
+ "locality",
43
+ "region",
44
+ "county",
45
+ "country",
46
+ "venue",
47
+ ];
52
48
  const POSTCODE_LOCALITY_TABLE = "postcode_locality";
53
49
  /**
54
50
  * Tunables for the coordinate-first locality soft-score `Score = pc·S_pc + name·S_name + pop·S_pop` (each S in [0,1]).
@@ -63,8 +59,7 @@ const CF_PC_DECAY_KM = 8;
63
59
  * flagged, tight enough to catch a wrong city (hundreds of km).
64
60
  */
65
61
  const CF_MISMATCH_KM = 50;
66
- const CF_MISMATCH_DELTA = 0.5;
67
- export class WOFSqlitePlaceLookup {
62
+ export class WOFSQLitePlaceLookup {
68
63
  #db;
69
64
  #ownsDB;
70
65
  #kysely;
@@ -82,6 +77,12 @@ export class WOFSqlitePlaceLookup {
82
77
  * population boost is 0 for every row — preserves compatibility with DBs built before this feature shipped.
83
78
  */
84
79
  #hasPopulationIndex;
80
+ /**
81
+ * Per-shard SELECT term + LEFT JOIN for the two-score split's `encyclopedic` carry (ROAD_TO_V9 §2 R1), probed and
82
+ * built once at construction. Degrades to `NULL AS encyclopedic` with no join on a pre-split shard — every shipped
83
+ * shard today. See {@link encyclopedicClauses} for why the probe is a column and not a table.
84
+ */
85
+ #encyclopedicClauses;
85
86
  /**
86
87
  * Per-shard probe for the `postcode_locality` table (the coordinate-first candidate table, built by
87
88
  * scripts/build-postcode-locality.ts). Cached at construction; null'd out when absent so the coord-first path
@@ -126,10 +127,10 @@ export class WOFSqlitePlaceLookup {
126
127
  #postalCityAliases;
127
128
  constructor(opts, weights) {
128
129
  if (opts.database && opts.databasePath) {
129
- throw new Error("WOFSqlitePlaceLookup: pass either `database` or `databasePath`, not both");
130
+ throw new Error("WOFSQLitePlaceLookup: pass either `database` or `databasePath`, not both");
130
131
  }
131
132
  if (!opts.database && !opts.databasePath) {
132
- throw new Error("WOFSqlitePlaceLookup: one of `database` or `databasePath` is required");
133
+ throw new Error("WOFSQLitePlaceLookup: one of `database` or `databasePath` is required");
133
134
  }
134
135
  if (opts.database) {
135
136
  this.#db = opts.database;
@@ -169,9 +170,47 @@ export class WOFSqlitePlaceLookup {
169
170
  // sqlite_master. Cached at construction so findPlace doesn't query sqlite_master per call.
170
171
  this.#hasBboxIndex = new Map();
171
172
  this.#hasPopulationIndex = new Map();
173
+ this.#encyclopedicClauses = new Map();
172
174
  for (const s of this.#shards) {
173
175
  this.#hasBboxIndex.set(s.schemaName, this.#shardHasTable(s.schemaName, PLACE_BBOX_TABLE));
174
176
  this.#hasPopulationIndex.set(s.schemaName, this.#shardHasTable(s.schemaName, PLACE_POPULATION_TABLE));
177
+ this.#encyclopedicClauses.set(s.schemaName, encyclopedicClauses(this.#db, s.schemaName));
178
+ }
179
+ // Every lookup path here reaches `place_search`, and a shard without it fails in one of two ways
180
+ // that are both hard to read: an unroutable name returns zero hits (indistinguishable from "this
181
+ // country has no places") and a routable one throws mid-query from deep inside a SELECT. The
182
+ // unroutable half is the worse of the two — a shard reaches routing only through the name
183
+ // `deriveSchemaName` derives from its FILENAME, so a file spelled one letter off the placetype it
184
+ // serves answers with nothing while holding every row that was asked for.
185
+ //
186
+ // Two independent things bring a shard under the guard, and it needs both. Carrying `spr` is a
187
+ // CLAIM to be a place shard. Carrying a name that routes is an INVITATION to be queried as one, and
188
+ // it is made by the filename alone — so a database with no tables at all still gets picked, still
189
+ // answers no query, and still dies inside a SELECT. Testing only the claim lets an empty or
190
+ // truncated file past construction; testing only the name would exempt a correctly-named build
191
+ // input. A shard needs to fail neither test to be exempt.
192
+ //
193
+ // Exempt by design: `postcode-locality-<cc>.db` carries a relation table and nothing else, matches
194
+ // no routed placetype, and is part of the documented default shard list.
195
+ for (const s of this.#shards) {
196
+ if (s.schemaName === "main")
197
+ continue;
198
+ const routes = KNOWN_ROUTED_PLACETYPES.some((pt) => s.schemaName === pt || s.schemaName.startsWith(`${pt}_`) || s.schemaName.endsWith(`_${pt}`));
199
+ const claimsPlaceShard = this.#shardHasTable(s.schemaName, "spr");
200
+ if (!routes && !claimsPlaceShard)
201
+ continue;
202
+ if (this.#shardHasTable(s.schemaName, PLACE_SEARCH_TABLE))
203
+ continue;
204
+ throw new Error(`WOFSQLitePlaceLookup: ${s.path} ` +
205
+ (claimsPlaceShard
206
+ ? `carries "spr" but no "${PLACE_SEARCH_TABLE}" table, so it cannot serve a lookup.`
207
+ : `is named for a routed placetype but carries neither "spr" nor "${PLACE_SEARCH_TABLE}", so every ` +
208
+ `query routed to it would die mid-SELECT. An empty or truncated file reads exactly like this.`) +
209
+ ` Build it with the FTS index, or leave it out — it is usable as a BUILD input either way.` +
210
+ (routes
211
+ ? ""
212
+ : ` Its schema name "${s.schemaName}" also matches no routed placetype (${KNOWN_ROUTED_PLACETYPES.join(", ")}), ` +
213
+ `so it would never have been queried even with the table — check the filename's spelling.`));
175
214
  }
176
215
  // #920 country-aware shard routing: probe each NON-MAIN shard's country set once at
177
216
  // construction (they're small, purpose-built shards — postcode/locality slices; main is the
@@ -290,38 +329,7 @@ export class WOFSqlitePlaceLookup {
290
329
  if (!Number.isFinite(id))
291
330
  return [];
292
331
  if (!this.#coincidentRolesCache) {
293
- const map = new Map();
294
- if (coincidentRolesExists(this.#db)) {
295
- const rows = this.#db
296
- .prepare(`SELECT cr.admin_id AS adminID, s.id AS id, s.name AS name, s.country AS country,
297
- s.latitude AS lat, s.longitude AS lon,
298
- cr.relationship_type AS relationshipType, cr.locality_population AS population,
299
- cr.distance_km AS distanceKm
300
- FROM ${COINCIDENT_ROLES_TABLE} cr JOIN spr s ON s.id = cr.locality_id`)
301
- .all();
302
- for (const r of rows) {
303
- const candidate = {
304
- id: r.id,
305
- name: r.name,
306
- placetype: "locality",
307
- country: r.country,
308
- lat: r.lat,
309
- lon: r.lon,
310
- score: 0,
311
- relationshipType: r.relationshipType,
312
- population: r.population,
313
- distanceKm: r.distanceKm,
314
- };
315
- const list = map.get(r.adminID);
316
- if (list) {
317
- list.push(candidate);
318
- }
319
- else {
320
- map.set(r.adminID, [candidate]);
321
- }
322
- }
323
- }
324
- this.#coincidentRolesCache = map;
332
+ this.#coincidentRolesCache = loadCoincidentLocalities(this.#db);
325
333
  }
326
334
  return this.#coincidentRolesCache.get(id) ?? [];
327
335
  }
@@ -359,7 +367,7 @@ export class WOFSqlitePlaceLookup {
359
367
  if (this.#warnedUnknownStrategies.has(name))
360
368
  return;
361
369
  this.#warnedUnknownStrategies.add(name);
362
- console.warn(`WOFSqlitePlaceLookup: a convention names strategy "${name}", which this build does not register ` +
370
+ console.warn(`WOFSQLitePlaceLookup: a convention names strategy "${name}", which this build does not register ` +
363
371
  `(known: ${[...this.#strategies.keys()].join(", ")}). Skipping it. If the convention asset was built ` +
364
372
  `against a newer code revision, rebuild the asset for this one.`);
365
373
  }
@@ -381,16 +389,6 @@ export class WOFSqlitePlaceLookup {
381
389
  */
382
390
  async #fuzzyNameMatch(query, forceShard) {
383
391
  const limit = query.limit ?? 10;
384
- // Over-fetch so post-scoring + exact-match tiering have room to re-rank. SHORT queries (a 2–3-char
385
- // region abbreviation like "NY"/"VT") are the danger case the `exactMatchTiering` docstring flags:
386
- // the exact-abbrev holder's BM25 is poor (its long multilingual alt-name document tanks the score),
387
- // so under the normal `limit * 4` window it drops OUT of the candidate pool BEFORE tiering can
388
- // promote it — "NY" then resolves to a token-matching foreign region (Highland, GB) instead of New
389
- // York. Widen the window for short queries so the exact match is always present to be tiered.
390
- // (Cross-country abbrev collisions — "VT" is BOTH Vermont and Viterbo — still need a country/
391
- // postcode signal to disambiguate; this only rescues the window-drop class, not genuine ambiguity.
392
- // With a `country` hint every abbrev resolves; bare + no-context lifts 7→10/15 US states.)
393
- const ftsLimit = query.text.trim().length <= SHORT_QUERY_MAX_LENGTH ? Math.max(limit * 4, SHORT_QUERY_OVERFETCH) : limit * 4;
394
392
  // Expand the placetype filter through the shared equivalence table (core/resolver): a
395
393
  // `locality` query must also reach `borough` / `localadmin` rows — Brooklyn-the-borough
396
394
  // (pop 2.5M) is a borough, not a locality, and a strict filter made it unreachable so the
@@ -437,289 +435,33 @@ export class WOFSqlitePlaceLookup {
437
435
  country: query.country,
438
436
  countriesBySchema: this.#shardCountries,
439
437
  });
440
- const sch = shard.schemaName; // bare schema name; safe to interpolate (validated at construction)
441
- // Filter out historical / superseded / deprecated places by default — they live in the same
442
- // spr table but should never win a contemporary lookup. `is_current = 0` is the only WOF
443
- // value that means "not current"; both `-1` (modern) and `1` (legacy) mean current. See #91.
444
- // Note: with schema-qualified FROM the bare `place_search` reference in MATCH resolves to
445
- // the FROM table — required by FTS5 parser, see sharding.ts header comment.
446
- const where = ["place_search MATCH ?", "spr.is_current != 0", "spr.is_deprecated = 0"];
447
- const params = [ftsQuery];
448
- if (placetypes && placetypes.length) {
449
- where.push(`spr.placetype IN (${placetypes.map(() => "?").join(", ")})`);
450
- params.push(...placetypes);
451
- }
452
- if (query.country) {
453
- where.push("spr.country = ?");
454
- params.push(query.country);
455
- }
456
- if (query.parentID !== undefined) {
457
- where.push(`(spr.parent_id = ? OR spr.id IN (SELECT id FROM ${sch}.ancestors WHERE ancestor_id = ?))`);
458
- params.push(query.parentID, query.parentID);
459
- }
460
- // Bbox + near-with-radius are SQL-level filters via the R*Tree. We only emit the JOIN when
461
- // the active shard has the R*Tree; missing-but-requested is silently treated as no-bbox-
462
- // filter so legacy DBs / shards-without-bbox don't crash.
463
- const shardHasBbox = this.#hasBboxIndex.get(sch) === true;
464
- const useBboxJoin = (query.bbox || query.near?.maxDistanceKm !== undefined) && shardHasBbox;
465
- let joinClause = `JOIN ${sch}.spr ON spr.id = place_search.wof_id`;
466
- if (useBboxJoin) {
467
- joinClause += ` JOIN ${sch}.${PLACE_BBOX_TABLE} bbox ON bbox.id = spr.id`;
468
- // AABB intersection — both bbox sides must overlap. R*Tree handles this in O(log n).
469
- const filterBox = query.bbox || bboxAround(query.near.lat, query.near.lon, query.near.maxDistanceKm);
470
- where.push("bbox.min_lat <= ? AND bbox.max_lat >= ?", "bbox.min_lon <= ? AND bbox.max_lon >= ?");
471
- params.push(filterBox.maxLat, filterBox.minLat, filterBox.maxLon, filterBox.minLon);
472
- }
473
- // LEFT JOIN the population aux table when present. Missing-on-this-shard means the SELECT
474
- // just doesn't include the population column; the post-scoring loop treats it as 0.
475
- const shardHasPopulation = this.#hasPopulationIndex.get(sch) === true;
476
- const populationSelect = shardHasPopulation
477
- ? `${PLACE_POPULATION_TABLE}.population AS population`
478
- : `NULL AS population`;
479
- const populationJoin = shardHasPopulation
480
- ? `LEFT JOIN ${sch}.${PLACE_POPULATION_TABLE} ON ${PLACE_POPULATION_TABLE}.id = spr.id`
481
- : "";
482
- // Push the population boost into the ORDER BY when the index is available, so famous places
483
- // (whose long alt-name lists hurt BM25) actually make it into the over-fetch window. The TS
484
- // post-scoring will still compute the same boost for the final score; this just ensures the
485
- // candidate set is right.
486
- //
487
- // Formula: rank_adjusted = bm25 - populationBoost * min(1.0, log10(1 + pop) / scaleLog10)
488
- // Lower rank_adjusted = better (matches SQLite's bm25 convention of "more negative = better").
489
- //
490
- // #905 — do NOT reach for bm25 column weights here. Measured falsification (2026-07-02): FTS5's
491
- // bm25 length normalization is polluted by the row's TOTAL document size, so identical 1-token
492
- // `name` docs read −16.0 (empty alt_names) vs −0.43 (2.7 KB alt_names) EVEN with the alt_names
493
- // column weighted to zero — no weighting isolates name relevance in this schema. The famous-
494
- // holder guarantee lives in the population-ordered companion fetch below instead, and the
495
- // exact tier breaks ties by population in the post-scoring sort.
496
- const orderByExpr = shardHasPopulation
497
- ? `(bm25(place_search) - ? * MIN(1.0, COALESCE(log10(1.0 + ${PLACE_POPULATION_TABLE}.population), 0) / ?))`
498
- : "bm25(place_search)";
499
- // Schema-qualified FROM with bare-name MATCH — required syntax for FTS5 on attached schemas.
500
- // See sharding.ts header for the gotcha that drove this design.
501
- const stmt = this.#db.prepare(`
502
- SELECT
503
- spr.id AS id,
504
- spr.name,
505
- spr.placetype,
506
- spr.country,
507
- spr.parent_id,
508
- bm25(place_search) AS rank,
509
- spr.latitude AS lat,
510
- spr.longitude AS lon,
511
- spr.min_latitude, spr.max_latitude, spr.min_longitude, spr.max_longitude,
512
- ${populationSelect}
513
- FROM ${sch}.place_search
514
- ${joinClause}
515
- ${populationJoin}
516
- WHERE ${where.join(" AND ")}
517
- ORDER BY ${orderByExpr} ASC
518
- LIMIT ?
519
- `);
520
- if (shardHasPopulation) {
521
- params.push(this.#weights.populationBoost, this.#weights.populationScaleLog10);
522
- }
523
- params.push(ftsLimit);
524
- const rawRows = stmt.all(...params);
525
- // #905 companion fetch: the same MATCH, ordered by population alone. For name floods
526
- // ("Paris" matches thousands of gap-fill villages) the bm25-based window above cannot admit
527
- // the famous holder — its bm25 is length-poisoned by the row's alias bulk (measured ~15 pts,
528
- // vs a +4.0 boost cap), so FR Paris never even reaches post-scoring. This fetch makes the
529
- // prominent holders of a name pool-complete BY CONSTRUCTION; the exact-tier sort below
530
- // decides whether they win. Skipped without a population index (nothing to order by).
531
- if (shardHasPopulation) {
532
- const popStmt = this.#db.prepare(`
533
- SELECT
534
- spr.id AS id,
535
- spr.name,
536
- spr.placetype,
537
- spr.country,
538
- spr.parent_id,
539
- bm25(place_search) AS rank,
540
- spr.latitude AS lat,
541
- spr.longitude AS lon,
542
- spr.min_latitude, spr.max_latitude, spr.min_longitude, spr.max_longitude,
543
- ${populationSelect}
544
- FROM ${sch}.place_search
545
- ${joinClause}
546
- ${populationJoin}
547
- WHERE ${where.join(" AND ")}
548
- ORDER BY COALESCE(${PLACE_POPULATION_TABLE}.population, 0) DESC
549
- LIMIT ?
550
- `);
551
- const popParams = params.slice(0, -3); // drop the two boost params + ftsLimit
552
- const seen = new Set(rawRows.map((r) => r.id));
553
- for (const row of popStmt.all(...popParams, POPULATION_FETCH_LIMIT)) {
554
- if (!seen.has(row.id)) {
555
- rawRows.push(row);
556
- }
557
- }
558
- }
559
- const queryLen = query.text.length;
560
- const candidates = rawRows.map((row) => {
561
- // SQLite's bm25() returns a lower-is-better score (negative for matches). Negate so we
562
- // start from a higher-is-better baseline.
563
- let score = -row.rank;
564
- if (placetypes && placetypes.length && placetypes.includes(row.placetype)) {
565
- score += this.#weights.placetypeMatchBoost;
566
- }
567
- if (!placetypes && row.placetype === "locality") {
568
- score += this.#weights.localityImplicitBoost;
569
- }
570
- if (query.country && row.country === query.country) {
571
- score += this.#weights.countryMatchBoost;
572
- }
573
- if (query.parentID !== undefined) {
574
- score += row.parent_id === query.parentID ? this.#weights.directChildBoost : this.#weights.descendantBoost;
575
- }
576
- const extraLen = Math.max(0, row.name.length - queryLen - 3);
577
- score -= (this.#weights.lengthPenaltyWeight * extraLen) / 10;
578
- // Proximity boost: only applied when the query carries `near` AND the candidate has real
579
- // coordinates. The formula decays smoothly with distance so close-but-not-exact hits
580
- // still benefit; tunable via proximityBoost + proximityScaleKm.
581
- let distanceKm;
582
- // The best decayed-distance term over `near` + every `bias` point (each point's term is
583
- // scaled by its weight; the MAX wins — a candidate near ANY hint is "nearby"). Carried
584
- // into the exact-tier prominence sort below when hints are present.
585
- let proximityTerm = 0;
586
- if (row.lat !== null && row.lon !== null && !(row.lat === 0 && row.lon === 0)) {
587
- const hints = [];
588
- if (query.near) {
589
- hints.push({ lat: query.near.lat, lon: query.near.lon, weight: 1 });
590
- }
591
- for (const b of query.bias ?? []) {
592
- hints.push({ lat: b.lat, lon: b.lon, weight: b.weight ?? 1 });
593
- }
594
- let scoreTerm = 0;
595
- for (const h of hints) {
596
- const d = haversineKm(h.lat, h.lon, row.lat, row.lon);
597
- const decay = h.weight / (1 + d / this.#weights.proximityScaleKm);
598
- const prom = decay * this.#weights.biasBoost;
599
- if (prom > proximityTerm) {
600
- proximityTerm = prom;
601
- distanceKm = d;
602
- scoreTerm = decay * this.#weights.proximityBoost;
603
- }
604
- }
605
- score += scoreTerm;
606
- }
607
- // Population boost: capped at `populationBoost` magnitude at `10^populationScaleLog10`
608
- // people. Missing population → no contribution. Never penalizes.
609
- let popTerm = 0;
610
- if (row.population !== null && row.population > 0 && this.#weights.populationScaleLog10 > 0) {
611
- const popLog = Math.log10(1 + row.population);
612
- const popFraction = Math.min(1, popLog / this.#weights.populationScaleLog10);
613
- popTerm = this.#weights.populationBoost * popFraction;
614
- score += popTerm;
615
- }
616
- // Combined prominence for the exact-tier sort when proximity hints are present: population
617
- // and nearness in the SAME additive units, so the map view / the user's location can win a
618
- // cross-country postcode tie without a hard filter.
619
- const prominence = popTerm + proximityTerm;
620
- const candidate = {
621
- id: row.id,
622
- prominence,
623
- name: row.name,
624
- placetype: row.placetype,
625
- country: row.country ?? "",
626
- lat: row.lat ?? 0,
627
- lon: row.lon ?? 0,
628
- parent_id: row.parent_id ?? undefined,
629
- score,
630
- };
631
- if (distanceKm !== undefined) {
632
- candidate.distanceKm = distanceKm;
633
- }
634
- if (row.population !== null && row.population > 0) {
635
- candidate.population = row.population;
636
- }
637
- // Candidate bbox — parity with the WASM lookup (resolver-wof-wasm/lookup.ts), whose
638
- // consumers (the demo cascade's region constraint) read it. Without this the Node
639
- // backend's region→bbox constraint is dead and disambiguation falls to population
640
- // ranking (the Springfield-IL→MO failure the #524 smoke eval caught).
641
- if (row.min_latitude != null &&
642
- row.max_latitude != null &&
643
- row.min_longitude != null &&
644
- row.max_longitude != null) {
645
- candidate.bbox = {
646
- minLat: row.min_latitude,
647
- maxLat: row.max_latitude,
648
- minLon: row.min_longitude,
649
- maxLon: row.max_longitude,
650
- };
651
- }
652
- return candidate;
438
+ // bare schema name; safe to interpolate (validated at construction)
439
+ const sch = shard.schemaName;
440
+ const rawRows = fetchSearchRows({
441
+ db: this.#db,
442
+ schemaName: sch,
443
+ query,
444
+ placetypes,
445
+ ftsQuery,
446
+ limit,
447
+ hasBboxIndex: this.#hasBboxIndex,
448
+ hasPopulationIndex: this.#hasPopulationIndex,
449
+ encyclopedicClauses: this.#encyclopedicClauses,
450
+ weights: this.#weights,
451
+ });
452
+ const scoring = {
453
+ query,
454
+ placetypes,
455
+ queryLen: query.text.length,
456
+ weights: this.#weights,
457
+ };
458
+ const candidates = rawRows.map((row) => candidateFromSearchRow(row, scoring));
459
+ rankCandidates(candidates, {
460
+ db: this.#db,
461
+ schemaName: sch,
462
+ query,
463
+ weights: this.#weights,
653
464
  });
654
- // Exact-match tiering: a candidate whose name OR any alias equals the query text (case-folded)
655
- // ranks above any partial match, with the weighted-sum score (incl. population) breaking ties
656
- // WITHIN a tier. See the RankingWeights.exactMatchTiering docstring for why this aligns the
657
- // population prior rather than overriding it. One cheap indexed lookup over the candidate ids.
658
- // Runs even for a SINGLE candidate so `exactMatch` is stamped consistently (parity with the
659
- // WASM lookup) — a sole alias hit ("New York City" → New York) must still carry the flag the
660
- // demo cascade / #369 re-rank read.
661
- if (this.#weights.exactMatchTiering && candidates.length) {
662
- const exactIds = this.#exactMatchIds(sch, candidates.map((c) => c.id), query.text);
663
- // Stamp the tier onto every candidate (not just when the tiering sort fires) so a downstream
664
- // re-rank — #369's postcode-anchor country pin in `resolveTree` — can keep the country pin from
665
- // crossing the exact/partial boundary ("ME" → Maine, not the more-populous Missouri).
666
- for (const c of candidates) {
667
- c.exactMatch = exactIds.has(c.id);
668
- }
669
- if (exactIds.size) {
670
- // #905: WITHIN the exact tier, population is the PRIMARY key and the weighted score
671
- // only breaks population ties. Exactness saturates text relevance, and the bm25
672
- // residue inside `score` is length-noise (see the fetch-site comment), so letting it
673
- // order the tier is what sent unscoped "Paris" to an Ohio township. The partial tier
674
- // keeps score order — text relevance still means something there. This makes the
675
- // exactMatchTiering docstring literal: match quality primary, prominence within.
676
- //
677
- // #912 sub-tier: a NAME-exact candidate (spr.name equals the query) outranks an
678
- // ALIAS-exact one ('Paris' the place beats 'Paris Township' held via alias 'Paris').
679
- // The place's own name is a stronger identity claim than an alias — aliases exist to
680
- // widen recall, not to tie primaries. ME→Maine is untouched: 'ME' name-exact-matches
681
- // nothing, so the alias sub-tier still decides there. Population orders within each
682
- // sub-tier as before.
683
- const norm = (v) => v.toLowerCase().trim().replaceAll(/\s+/g, " ");
684
- const needle = norm(query.text);
685
- // #936 option 3: an OFFICIAL name (preferred form in an official language of the place's
686
- // country, `names.official = 1`) counts as the place's own name for the sub-tier — "Åbo" is
687
- // Turku's name, not merely its alias. Floor-gated on the holder's population (see the
688
- // RankingWeights docstring for the measured 100k boundary). officialIds ⊆ exactIds by
689
- // construction (official rows are names rows), so only the sub-tier KIND changes.
690
- const officialIds = this.#weights.officialNameExact
691
- ? this.#officialNameIds(sch, candidates
692
- .filter((c) => exactIds.has(c.id) && (c.population ?? 0) >= this.#weights.officialNameExactFloor)
693
- .map((c) => c.id), query.text)
694
- : undefined;
695
- const kind = (c) => {
696
- if (!exactIds.has(c.id))
697
- return 0;
698
- if (norm(String(c.name ?? "")) === needle)
699
- return 2;
700
- return officialIds?.has(c.id) ? 2 : 1;
701
- };
702
- // With proximity hints (near/bias), prominence (population + nearness, same units)
703
- // replaces raw population as the within-tier key — the 48026 rule: the map view or
704
- // the user's location breaks a cross-country postcode tie. Without hints, population
705
- // ordering is byte-identical to before.
706
- const hasHints = !!query.near || (query.bias?.length ?? 0) > 0;
707
- candidates.sort((a, b) => {
708
- const ax = kind(a);
709
- const bx = kind(b);
710
- if (bx !== ax)
711
- return bx - ax;
712
- if (ax >= 1) {
713
- if (hasHints)
714
- return (b.prominence ?? 0) - (a.prominence ?? 0) || b.score - a.score;
715
- return (b.population ?? 0) - (a.population ?? 0) || b.score - a.score;
716
- }
717
- return b.score - a.score;
718
- });
719
- return candidates.slice(0, limit);
720
- }
721
- }
722
- candidates.sort((a, b) => b.score - a.score);
723
465
  return candidates.slice(0, limit);
724
466
  }
725
467
  #isLocalityQuery(query) {
@@ -777,10 +519,8 @@ export class WOFSqlitePlaceLookup {
777
519
  const pc = query.postcode.trim();
778
520
  const pcWhere = query.country ? "postcode = ? AND country = ?" : "postcode = ?";
779
521
  const pcParams = query.country ? [pc, query.country] : [pc];
780
- const pcRows = this.#db
781
- .prepare(`SELECT locality_id AS id, aliases, distance_km AS dist, is_containing AS containing
782
- FROM ${sch}.${POSTCODE_LOCALITY_TABLE} WHERE ${pcWhere}`)
783
- .all(...pcParams);
522
+ const pcRows = allRows(this.#db.prepare(`SELECT locality_id AS id, aliases, distance_km AS dist, is_containing AS containing
523
+ FROM ${sch}.${POSTCODE_LOCALITY_TABLE} WHERE ${pcWhere}`), ...pcParams);
784
524
  if (!pcRows.length)
785
525
  return null;
786
526
  const limit = query.limit ?? 10;
@@ -873,12 +613,10 @@ export class WOFSqlitePlaceLookup {
873
613
  const popSelect = hasPop ? `pp.population AS population` : `NULL AS population`;
874
614
  const popJoin = hasPop ? `LEFT JOIN main.${PLACE_POPULATION_TABLE} pp ON pp.id = s.id` : "";
875
615
  const ph = ids.map(() => "?").join(", ");
876
- const rows = this.#db
877
- .prepare(`SELECT s.id AS id, s.name AS name, s.country AS country, s.parent_id AS parent_id,
616
+ const rows = allRows(this.#db.prepare(`SELECT s.id AS id, s.name AS name, s.country AS country, s.parent_id AS parent_id,
878
617
  s.latitude AS lat, s.longitude AS lon, s.placetype AS placetype, ${popSelect}
879
618
  FROM main.spr s ${popJoin}
880
- WHERE s.id IN (${ph}) AND s.is_current != 0`)
881
- .all(...ids);
619
+ WHERE s.id IN (${ph}) AND s.is_current != 0`), ...ids);
882
620
  return rows.map((row) => {
883
621
  const c = {
884
622
  id: row.id,
@@ -896,85 +634,6 @@ export class WOFSqlitePlaceLookup {
896
634
  return c;
897
635
  });
898
636
  }
899
- /**
900
- * Among `ids`, return the subset whose name OR any alias equals `text` case-insensitively — the exact-match tier for
901
- * ranking. One indexed query over `<schema>.names`. When the shard has no `names` table (a slim DB built with
902
- * `dropNames`, or a postcode-only shard), fall back to the self-contained `place_search` FTS content: its `alt_names`
903
- * column is the same alias set joined on the boundary-preserving `ALIAS_SEPARATOR` (#523), so `aliasBagExactMatch`
904
- * recovers the exact alias tier ("New York City" → New York) that the dropped `names` table used to provide.
905
- */
906
- #exactMatchIds(schemaName, ids, text) {
907
- const out = new Set();
908
- const trimmed = text.trim();
909
- if (!ids.length || !trimmed)
910
- return out;
911
- const placeholders = ids.map(() => "?").join(", ");
912
- try {
913
- const rows = this.#db
914
- .prepare(`SELECT DISTINCT id FROM ${schemaName}.names WHERE id IN (${placeholders}) AND name = ? COLLATE NOCASE`)
915
- .all(...ids, trimmed);
916
- for (const r of rows) {
917
- out.add(r.id);
918
- }
919
- return out;
920
- }
921
- catch {
922
- // No `names` table on this shard — fall through to the place_search alias bag.
923
- }
924
- try {
925
- const rows = this.#db
926
- .prepare(`SELECT wof_id AS id, name, alt_names FROM ${schemaName}.place_search WHERE wof_id IN (${placeholders})`)
927
- .all(...ids);
928
- const norm = (s) => s.toLowerCase().trim().replaceAll(/\s+/g, " ");
929
- const needle = norm(trimmed);
930
- for (const r of rows) {
931
- if (r.name !== null && norm(r.name) === needle) {
932
- out.add(r.id);
933
- }
934
- }
935
- // Alias pass via the shared bag parser (#523). Separated bags (built since #523) get a true
936
- // per-alias equality check, ungated — matching the `names`-table branch above, where an
937
- // alias match counts as exact regardless of other candidates. Legacy bags (no separator)
938
- // fall back to padded containment, gated on "no canonical exact in the pool" because their
939
- // lost boundaries would otherwise false-promote interior fragments ("York" inside the alias
940
- // "New York City") or cross-alias fragments ("York New" across "…York" + "New City…").
941
- const anyCanonicalExact = out.size > 0;
942
- for (const r of rows) {
943
- if (aliasBagExactMatch(r.alt_names, needle, anyCanonicalExact)) {
944
- out.add(r.id);
945
- }
946
- }
947
- }
948
- catch {
949
- // Shard without place_search either → no exact-match tier. Falls back to weighted-sum order.
950
- }
951
- return out;
952
- }
953
- /**
954
- * Among `ids` (already known exact matches), the subset holding `text` as an OFFICIAL name (`names.official = 1`, the
955
- * #940 ingest bit). Same COLLATE NOCASE semantics as {@link WOFSqlitePlaceLookup.#exactMatchIds} so the two probes
956
- * agree on what "equals the query" means. Fails soft on gazetteers built before #940 (no `official` column) — the
957
- * sub-tier then behaves exactly as if `officialNameExact` were off.
958
- */
959
- #officialNameIds(schemaName, ids, text) {
960
- const out = new Set();
961
- const trimmed = text.trim();
962
- if (!ids.length || !trimmed)
963
- return out;
964
- const placeholders = ids.map(() => "?").join(", ");
965
- try {
966
- const rows = this.#db
967
- .prepare(`SELECT DISTINCT id FROM ${schemaName}.names WHERE id IN (${placeholders}) AND official = 1 AND name = ? COLLATE NOCASE`)
968
- .all(...ids, trimmed);
969
- for (const r of rows) {
970
- out.add(r.id);
971
- }
972
- }
973
- catch {
974
- // Pre-#940 gazetteer (no `official` column) or a names-less slim shard — feature inert.
975
- }
976
- return out;
977
- }
978
637
  close() {
979
638
  // Destroying the Kysely instance closes the underlying connection IF we own it. If the caller
980
639
  // passed in a pre-opened DatabaseSync (test fixture), respect their ownership.
@@ -994,9 +653,8 @@ export class WOFSqlitePlaceLookup {
994
653
  }
995
654
  #assertFTSExists() {
996
655
  if (!placeSearchFTSExists(this.#db)) {
997
- throw new Error("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).");
656
+ throw new Error("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).");
998
657
  }
999
658
  }
1000
659
  }
1001
- export { trigramJaccard, trigrams } from "./name-score.js";
1002
660
  //# sourceMappingURL=lookup.js.map