@mailwoman/resolver-wof-sqlite 9.1.0 → 9.3.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 (501) hide show
  1. package/README.md +36 -20
  2. package/lib/address/index.ts +9 -0
  3. package/{address-point-interpolation.ts → lib/address/point-interpolation.ts} +40 -28
  4. package/{address-point-schema.ts → lib/address/point-schema.ts} +34 -8
  5. package/lib/address/point.ts +280 -0
  6. package/{ancestry-backfill.ts → lib/ancestry/backfill.ts} +14 -19
  7. package/{ancestry.ts → lib/ancestry/index.ts} +13 -8
  8. package/{build-candidate.ts → lib/build-candidate.ts} +243 -199
  9. package/{build-slim.ts → lib/build-slim.ts} +153 -168
  10. package/lib/candidate/alias-bags.ts +56 -0
  11. package/lib/candidate/ancestors-sidecar.ts +204 -0
  12. package/lib/candidate/country-display-names.ts +79 -0
  13. package/lib/candidate/extract-fold.ts +138 -0
  14. package/lib/candidate/name-roles.ts +238 -0
  15. package/lib/candidate/own-name.ts +146 -0
  16. package/lib/candidate/place-attrs.ts +44 -0
  17. package/lib/candidate-ancestors-schema.ts +195 -0
  18. package/{candidate-fts.ts → lib/candidate-fts.ts} +7 -5
  19. package/{candidate-importance.ts → lib/candidate-importance.ts} +54 -57
  20. package/lib/candidate-lookup.ts +976 -0
  21. package/{candidate-schema.ts → lib/candidate-schema.ts} +34 -6
  22. package/lib/candidate-scoring.ts +261 -0
  23. package/lib/capital-schema.ts +89 -0
  24. package/lib/capitals.ts +148 -0
  25. package/{coincident-roles.ts → lib/coincident-roles.ts} +75 -19
  26. package/{convention.ts → lib/convention/index.ts} +5 -5
  27. package/lib/convention/schema.ts +72 -0
  28. package/{coverage-manifest-schema.ts → lib/coverage-manifest-schema.ts} +15 -16
  29. package/lib/currency-backfill.ts +334 -0
  30. package/lib/env.ts +50 -0
  31. package/lib/exact-match.ts +113 -0
  32. package/{sharding.ts → lib/extracts.ts} +63 -60
  33. package/lib/fst/autocomplete.ts +176 -0
  34. package/{fst-builder.ts → lib/fst/builder.ts} +30 -27
  35. package/{fst-deserialize-web.ts → lib/fst/deserialize-web.ts} +27 -87
  36. package/lib/fst/format.ts +106 -0
  37. package/{fst-freshness.ts → lib/fst/freshness.ts} +42 -75
  38. package/lib/fst/index.ts +14 -0
  39. package/{fst-matcher.ts → lib/fst/matcher.ts} +1 -1
  40. package/{fst-serialize.ts → lib/fst/serialize.ts} +37 -115
  41. package/{fst-types.ts → lib/fst/types.ts} +4 -2
  42. package/{fts.ts → lib/fts/index.ts} +28 -23
  43. package/{fts-query.ts → lib/fts/query.ts} +2 -2
  44. package/{geonames-aliases.ts → lib/geonames/aliases.ts} +13 -13
  45. package/lib/geonames/index.ts +8 -0
  46. package/{geonames-postal.ts → lib/geonames/postal.ts} +16 -15
  47. package/{index.ts → lib/index.ts} +52 -48
  48. package/{interpolation.ts → lib/interpolation.ts} +137 -41
  49. package/lib/lookup.ts +861 -0
  50. package/{name-score.ts → lib/name-score.ts} +6 -4
  51. package/lib/nsul/index.ts +8 -0
  52. package/lib/nsul/lookup.ts +144 -0
  53. package/lib/nsul/schema.ts +130 -0
  54. package/{place-importance-schema.ts → lib/place-importance-schema.ts} +70 -22
  55. package/lib/poi/index.ts +8 -0
  56. package/{poi-lookup.ts → lib/poi/lookup.ts} +32 -39
  57. package/{poi-schema.ts → lib/poi/schema.ts} +10 -6
  58. package/lib/polygon-schema.ts +47 -0
  59. package/{postal-city-alias-lookup.ts → lib/postal/city-alias-lookup.ts} +15 -21
  60. package/{postal-city-candidate-schema.ts → lib/postal/city-candidate-schema.ts} +4 -2
  61. package/lib/postal/index.ts +9 -0
  62. package/{postcode-point-lookup.ts → lib/postcode-point-lookup.ts} +17 -15
  63. package/lib/primary-preference.ts +226 -0
  64. package/lib/proximity-rerank.ts +120 -0
  65. package/{ranking-weights.ts → lib/ranking-weights.ts} +30 -4
  66. package/lib/region-keys.ts +144 -0
  67. package/{reverse.ts → lib/reverse.ts} +45 -56
  68. package/{schema.ts → lib/schema.ts} +11 -1
  69. package/lib/search-fetch.ts +257 -0
  70. package/{sqlite-convention-source.ts → lib/sqlite-convention-source.ts} +9 -10
  71. package/lib/sqlite-utils.ts +83 -0
  72. package/{street-centroid-schema.ts → lib/street/centroid-schema.ts} +12 -6
  73. package/{street-centroid.ts → lib/street/centroid.ts} +26 -28
  74. package/lib/street/index.ts +13 -0
  75. package/{street-morphology-fst-builder.ts → lib/street/morphology-fst-builder.ts} +24 -14
  76. package/{street-morphology-fst-loader.ts → lib/street/morphology-fst-loader.ts} +14 -12
  77. package/{street-name-lookup.ts → lib/street/name-lookup.ts} +14 -30
  78. package/lib/street/normalize.ts +572 -0
  79. package/{street-segment-schema.ts → lib/street/segment-schema.ts} +13 -8
  80. package/{types.ts → lib/types.ts} +49 -9
  81. package/{unified-schema.ts → lib/unified-schema.ts} +21 -25
  82. package/lib/uprn/existence.ts +84 -0
  83. package/lib/uprn/index.ts +9 -0
  84. package/lib/uprn/lookup.ts +206 -0
  85. package/lib/uprn/schema.ts +124 -0
  86. package/lib/weights-overlay-linker.ts +878 -0
  87. package/out/address/index.d.ts +9 -0
  88. package/out/address/index.d.ts.map +1 -0
  89. package/out/address/index.js +9 -0
  90. package/out/address/index.js.map +1 -0
  91. package/out/{address-point-interpolation.d.ts → address/point-interpolation.d.ts} +11 -10
  92. package/out/address/point-interpolation.d.ts.map +1 -0
  93. package/out/{address-point-interpolation.js → address/point-interpolation.js} +29 -23
  94. package/out/address/point-interpolation.js.map +1 -0
  95. package/out/{address-point-schema.d.ts → address/point-schema.d.ts} +30 -10
  96. package/out/address/point-schema.d.ts.map +1 -0
  97. package/out/{address-point-schema.js → address/point-schema.js} +7 -3
  98. package/out/address/point-schema.js.map +1 -0
  99. package/out/{address-point.d.ts → address/point.d.ts} +16 -8
  100. package/out/address/point.d.ts.map +1 -0
  101. package/out/address/point.js +191 -0
  102. package/out/address/point.js.map +1 -0
  103. package/out/{ancestry-backfill.d.ts → ancestry/backfill.d.ts} +7 -5
  104. package/out/ancestry/backfill.d.ts.map +1 -0
  105. package/out/{ancestry-backfill.js → ancestry/backfill.js} +12 -16
  106. package/out/ancestry/backfill.js.map +1 -0
  107. package/out/{ancestry.d.ts → ancestry/index.d.ts} +6 -5
  108. package/out/ancestry/index.d.ts.map +1 -0
  109. package/out/{ancestry.js → ancestry/index.js} +7 -7
  110. package/out/ancestry/index.js.map +1 -0
  111. package/out/build-candidate.d.ts +88 -7
  112. package/out/build-candidate.d.ts.map +1 -1
  113. package/out/build-candidate.js +145 -149
  114. package/out/build-candidate.js.map +1 -1
  115. package/out/build-slim.d.ts +5 -5
  116. package/out/build-slim.d.ts.map +1 -1
  117. package/out/build-slim.js +127 -142
  118. package/out/build-slim.js.map +1 -1
  119. package/out/candidate/alias-bags.d.ts +19 -0
  120. package/out/candidate/alias-bags.d.ts.map +1 -0
  121. package/out/candidate/alias-bags.js +39 -0
  122. package/out/candidate/alias-bags.js.map +1 -0
  123. package/out/candidate/ancestors-sidecar.d.ts +32 -0
  124. package/out/candidate/ancestors-sidecar.d.ts.map +1 -0
  125. package/out/candidate/ancestors-sidecar.js +140 -0
  126. package/out/candidate/ancestors-sidecar.js.map +1 -0
  127. package/out/candidate/country-display-names.d.ts +35 -0
  128. package/out/candidate/country-display-names.d.ts.map +1 -0
  129. package/out/candidate/country-display-names.js +59 -0
  130. package/out/candidate/country-display-names.js.map +1 -0
  131. package/out/candidate/extract-fold.d.ts +32 -0
  132. package/out/candidate/extract-fold.d.ts.map +1 -0
  133. package/out/candidate/extract-fold.js +104 -0
  134. package/out/candidate/extract-fold.js.map +1 -0
  135. package/out/candidate/name-roles.d.ts +57 -0
  136. package/out/candidate/name-roles.d.ts.map +1 -0
  137. package/out/candidate/name-roles.js +166 -0
  138. package/out/candidate/name-roles.js.map +1 -0
  139. package/out/candidate/own-name.d.ts +50 -0
  140. package/out/candidate/own-name.d.ts.map +1 -0
  141. package/out/candidate/own-name.js +132 -0
  142. package/out/candidate/own-name.js.map +1 -0
  143. package/out/candidate/place-attrs.d.ts +43 -0
  144. package/out/candidate/place-attrs.d.ts.map +1 -0
  145. package/out/candidate/place-attrs.js +15 -0
  146. package/out/candidate/place-attrs.js.map +1 -0
  147. package/out/candidate-ancestors-schema.d.ts +150 -0
  148. package/out/candidate-ancestors-schema.d.ts.map +1 -0
  149. package/out/candidate-ancestors-schema.js +123 -0
  150. package/out/candidate-ancestors-schema.js.map +1 -0
  151. package/out/candidate-fts.d.ts +7 -5
  152. package/out/candidate-fts.d.ts.map +1 -1
  153. package/out/candidate-fts.js +5 -3
  154. package/out/candidate-fts.js.map +1 -1
  155. package/out/candidate-importance.d.ts +16 -16
  156. package/out/candidate-importance.d.ts.map +1 -1
  157. package/out/candidate-importance.js +47 -52
  158. package/out/candidate-importance.js.map +1 -1
  159. package/out/candidate-lookup.d.ts +31 -52
  160. package/out/candidate-lookup.d.ts.map +1 -1
  161. package/out/candidate-lookup.js +380 -172
  162. package/out/candidate-lookup.js.map +1 -1
  163. package/out/candidate-schema.d.ts +31 -7
  164. package/out/candidate-schema.d.ts.map +1 -1
  165. package/out/candidate-schema.js +3 -0
  166. package/out/candidate-schema.js.map +1 -1
  167. package/out/candidate-scoring.d.ts +34 -0
  168. package/out/candidate-scoring.d.ts.map +1 -0
  169. package/out/candidate-scoring.js +196 -0
  170. package/out/candidate-scoring.js.map +1 -0
  171. package/out/capital-schema.d.ts +51 -0
  172. package/out/capital-schema.d.ts.map +1 -0
  173. package/out/capital-schema.js +63 -0
  174. package/out/capital-schema.js.map +1 -0
  175. package/out/capitals.d.ts +69 -0
  176. package/out/capitals.d.ts.map +1 -0
  177. package/out/capitals.js +98 -0
  178. package/out/capitals.js.map +1 -0
  179. package/out/coincident-roles.d.ts +12 -4
  180. package/out/coincident-roles.d.ts.map +1 -1
  181. package/out/coincident-roles.js +43 -11
  182. package/out/coincident-roles.js.map +1 -1
  183. package/out/{convention.d.ts → convention/index.d.ts} +5 -5
  184. package/out/convention/index.d.ts.map +1 -0
  185. package/out/{convention.js → convention/index.js} +4 -4
  186. package/out/convention/index.js.map +1 -0
  187. package/out/convention/schema.d.ts +51 -0
  188. package/out/convention/schema.d.ts.map +1 -0
  189. package/out/convention/schema.js +34 -0
  190. package/out/convention/schema.js.map +1 -0
  191. package/out/coverage-manifest-schema.d.ts +8 -8
  192. package/out/coverage-manifest-schema.d.ts.map +1 -1
  193. package/out/coverage-manifest-schema.js +6 -10
  194. package/out/coverage-manifest-schema.js.map +1 -1
  195. package/out/currency-backfill.d.ts +90 -0
  196. package/out/currency-backfill.d.ts.map +1 -0
  197. package/out/currency-backfill.js +196 -0
  198. package/out/currency-backfill.js.map +1 -0
  199. package/out/env.d.ts +43 -0
  200. package/out/env.d.ts.map +1 -0
  201. package/out/env.js +48 -0
  202. package/out/env.js.map +1 -0
  203. package/out/exact-match.d.ts +25 -0
  204. package/out/exact-match.d.ts.map +1 -0
  205. package/out/exact-match.js +88 -0
  206. package/out/exact-match.js.map +1 -0
  207. package/out/extracts.d.ts +114 -0
  208. package/out/extracts.d.ts.map +1 -0
  209. package/out/{sharding.js → extracts.js} +38 -38
  210. package/out/extracts.js.map +1 -0
  211. package/out/{fst-autocomplete.d.ts → fst/autocomplete.d.ts} +13 -13
  212. package/out/fst/autocomplete.d.ts.map +1 -0
  213. package/out/fst/autocomplete.js +113 -0
  214. package/out/fst/autocomplete.js.map +1 -0
  215. package/out/{fst-builder.d.ts → fst/builder.d.ts} +5 -5
  216. package/out/fst/builder.d.ts.map +1 -0
  217. package/out/{fst-builder.js → fst/builder.js} +24 -24
  218. package/out/fst/builder.js.map +1 -0
  219. package/out/{fst-deserialize-web.d.ts → fst/deserialize-web.d.ts} +3 -3
  220. package/out/fst/deserialize-web.d.ts.map +1 -0
  221. package/out/{fst-deserialize-web.js → fst/deserialize-web.js} +10 -74
  222. package/out/fst/deserialize-web.js.map +1 -0
  223. package/out/fst/format.d.ts +80 -0
  224. package/out/fst/format.d.ts.map +1 -0
  225. package/out/fst/format.js +91 -0
  226. package/out/fst/format.js.map +1 -0
  227. package/out/{fst-freshness.d.ts → fst/freshness.d.ts} +11 -14
  228. package/out/fst/freshness.d.ts.map +1 -0
  229. package/out/{fst-freshness.js → fst/freshness.js} +42 -74
  230. package/out/fst/freshness.js.map +1 -0
  231. package/out/fst/index.d.ts +14 -0
  232. package/out/fst/index.d.ts.map +1 -0
  233. package/out/fst/index.js +14 -0
  234. package/out/fst/index.js.map +1 -0
  235. package/out/{fst-matcher.d.ts → fst/matcher.d.ts} +2 -2
  236. package/out/fst/matcher.d.ts.map +1 -0
  237. package/out/{fst-matcher.js → fst/matcher.js} +1 -1
  238. package/out/fst/matcher.js.map +1 -0
  239. package/out/{fst-serialize.d.ts → fst/serialize.d.ts} +5 -10
  240. package/out/fst/serialize.d.ts.map +1 -0
  241. package/out/{fst-serialize.js → fst/serialize.js} +18 -98
  242. package/out/fst/serialize.js.map +1 -0
  243. package/out/{fst-types.d.ts → fst/types.d.ts} +4 -3
  244. package/out/fst/types.d.ts.map +1 -0
  245. package/out/{fst-types.js → fst/types.js} +1 -1
  246. package/out/fst/types.js.map +1 -0
  247. package/out/{fts.d.ts → fts/index.d.ts} +20 -13
  248. package/out/fts/index.d.ts.map +1 -0
  249. package/out/{fts.js → fts/index.js} +20 -15
  250. package/out/fts/index.js.map +1 -0
  251. package/out/{fts-query.d.ts → fts/query.d.ts} +2 -2
  252. package/out/fts/query.d.ts.map +1 -0
  253. package/out/{fts-query.js → fts/query.js} +2 -2
  254. package/out/fts/query.js.map +1 -0
  255. package/out/{geonames-aliases.d.ts → geonames/aliases.d.ts} +8 -6
  256. package/out/geonames/aliases.d.ts.map +1 -0
  257. package/out/{geonames-aliases.js → geonames/aliases.js} +7 -7
  258. package/out/geonames/aliases.js.map +1 -0
  259. package/out/geonames/index.d.ts +8 -0
  260. package/out/geonames/index.d.ts.map +1 -0
  261. package/out/geonames/index.js +8 -0
  262. package/out/geonames/index.js.map +1 -0
  263. package/out/{geonames-postal.d.ts → geonames/postal.d.ts} +12 -10
  264. package/out/geonames/postal.d.ts.map +1 -0
  265. package/out/{geonames-postal.js → geonames/postal.js} +11 -11
  266. package/out/geonames/postal.js.map +1 -0
  267. package/out/index.d.ts +32 -31
  268. package/out/index.d.ts.map +1 -1
  269. package/out/index.js +24 -24
  270. package/out/index.js.map +1 -1
  271. package/out/interpolation.d.ts +18 -9
  272. package/out/interpolation.d.ts.map +1 -1
  273. package/out/interpolation.js +108 -36
  274. package/out/interpolation.js.map +1 -1
  275. package/out/lookup.d.ts +25 -25
  276. package/out/lookup.d.ts.map +1 -1
  277. package/out/lookup.js +174 -558
  278. package/out/lookup.js.map +1 -1
  279. package/out/name-score.d.ts +0 -10
  280. package/out/name-score.d.ts.map +1 -1
  281. package/out/name-score.js +6 -4
  282. package/out/name-score.js.map +1 -1
  283. package/out/nsul/index.d.ts +8 -0
  284. package/out/nsul/index.d.ts.map +1 -0
  285. package/out/nsul/index.js +8 -0
  286. package/out/nsul/index.js.map +1 -0
  287. package/out/nsul/lookup.d.ts +83 -0
  288. package/out/nsul/lookup.d.ts.map +1 -0
  289. package/out/nsul/lookup.js +80 -0
  290. package/out/nsul/lookup.js.map +1 -0
  291. package/out/nsul/schema.d.ts +100 -0
  292. package/out/nsul/schema.d.ts.map +1 -0
  293. package/out/nsul/schema.js +78 -0
  294. package/out/nsul/schema.js.map +1 -0
  295. package/out/place-importance-schema.d.ts +47 -10
  296. package/out/place-importance-schema.d.ts.map +1 -1
  297. package/out/place-importance-schema.js +56 -10
  298. package/out/place-importance-schema.js.map +1 -1
  299. package/out/poi/index.d.ts +8 -0
  300. package/out/poi/index.d.ts.map +1 -0
  301. package/out/poi/index.js +8 -0
  302. package/out/poi/index.js.map +1 -0
  303. package/out/{poi-lookup.d.ts → poi/lookup.d.ts} +8 -10
  304. package/out/poi/lookup.d.ts.map +1 -0
  305. package/out/{poi-lookup.js → poi/lookup.js} +24 -29
  306. package/out/poi/lookup.js.map +1 -0
  307. package/out/{poi-schema.d.ts → poi/schema.d.ts} +10 -6
  308. package/out/poi/schema.d.ts.map +1 -0
  309. package/out/{poi-schema.js → poi/schema.js} +1 -1
  310. package/out/poi/schema.js.map +1 -0
  311. package/out/polygon-schema.d.ts +37 -0
  312. package/out/polygon-schema.d.ts.map +1 -0
  313. package/out/polygon-schema.js +23 -0
  314. package/out/polygon-schema.js.map +1 -0
  315. package/out/{postal-city-alias-lookup.d.ts → postal/city-alias-lookup.d.ts} +7 -6
  316. package/out/postal/city-alias-lookup.d.ts.map +1 -0
  317. package/out/{postal-city-alias-lookup.js → postal/city-alias-lookup.js} +12 -16
  318. package/out/postal/city-alias-lookup.js.map +1 -0
  319. package/out/{postal-city-alias-schema.d.ts → postal/city-alias-schema.d.ts} +1 -1
  320. package/out/{postal-city-alias-schema.d.ts.map → postal/city-alias-schema.d.ts.map} +1 -1
  321. package/out/{postal-city-alias-schema.js → postal/city-alias-schema.js} +1 -1
  322. package/out/{postal-city-alias-schema.js.map → postal/city-alias-schema.js.map} +1 -1
  323. package/out/{postal-city-candidate-schema.d.ts → postal/city-candidate-schema.d.ts} +4 -3
  324. package/out/postal/city-candidate-schema.d.ts.map +1 -0
  325. package/out/{postal-city-candidate-schema.js → postal/city-candidate-schema.js} +2 -2
  326. package/out/{postal-city-candidate-schema.js.map → postal/city-candidate-schema.js.map} +1 -1
  327. package/out/postal/index.d.ts +9 -0
  328. package/out/postal/index.d.ts.map +1 -0
  329. package/out/postal/index.js +9 -0
  330. package/out/postal/index.js.map +1 -0
  331. package/out/postcode-point-lookup.d.ts +10 -10
  332. package/out/postcode-point-lookup.d.ts.map +1 -1
  333. package/out/postcode-point-lookup.js +13 -13
  334. package/out/postcode-point-lookup.js.map +1 -1
  335. package/out/primary-preference.d.ts +133 -0
  336. package/out/primary-preference.d.ts.map +1 -0
  337. package/out/primary-preference.js +146 -0
  338. package/out/primary-preference.js.map +1 -0
  339. package/out/proximity-rerank.d.ts +77 -0
  340. package/out/proximity-rerank.d.ts.map +1 -0
  341. package/out/proximity-rerank.js +86 -0
  342. package/out/proximity-rerank.js.map +1 -0
  343. package/out/ranking-weights.d.ts +15 -3
  344. package/out/ranking-weights.d.ts.map +1 -1
  345. package/out/ranking-weights.js +21 -3
  346. package/out/ranking-weights.js.map +1 -1
  347. package/out/region-keys.d.ts +47 -0
  348. package/out/region-keys.d.ts.map +1 -0
  349. package/out/region-keys.js +121 -0
  350. package/out/region-keys.js.map +1 -0
  351. package/out/reverse.d.ts +6 -6
  352. package/out/reverse.d.ts.map +1 -1
  353. package/out/reverse.js +23 -35
  354. package/out/reverse.js.map +1 -1
  355. package/out/schema.d.ts +10 -1
  356. package/out/schema.d.ts.map +1 -1
  357. package/out/schema.js.map +1 -1
  358. package/out/search-fetch.d.ts +59 -0
  359. package/out/search-fetch.d.ts.map +1 -0
  360. package/out/search-fetch.js +184 -0
  361. package/out/search-fetch.js.map +1 -0
  362. package/out/sqlite-convention-source.d.ts +7 -7
  363. package/out/sqlite-convention-source.d.ts.map +1 -1
  364. package/out/sqlite-convention-source.js +5 -5
  365. package/out/sqlite-convention-source.js.map +1 -1
  366. package/out/sqlite-utils.d.ts +24 -6
  367. package/out/sqlite-utils.d.ts.map +1 -1
  368. package/out/sqlite-utils.js +24 -7
  369. package/out/sqlite-utils.js.map +1 -1
  370. package/out/{street-centroid-schema.d.ts → street/centroid-schema.d.ts} +12 -7
  371. package/out/street/centroid-schema.d.ts.map +1 -0
  372. package/out/{street-centroid-schema.js → street/centroid-schema.js} +5 -5
  373. package/out/{street-centroid-schema.js.map → street/centroid-schema.js.map} +1 -1
  374. package/out/{street-centroid.d.ts → street/centroid.d.ts} +6 -6
  375. package/out/street/centroid.d.ts.map +1 -0
  376. package/out/{street-centroid.js → street/centroid.js} +18 -24
  377. package/out/street/centroid.js.map +1 -0
  378. package/out/street/index.d.ts +13 -0
  379. package/out/street/index.d.ts.map +1 -0
  380. package/out/street/index.js +13 -0
  381. package/out/street/index.js.map +1 -0
  382. package/out/{street-morphology-fst-builder.d.ts → street/morphology-fst-builder.d.ts} +4 -4
  383. package/out/street/morphology-fst-builder.d.ts.map +1 -0
  384. package/out/{street-morphology-fst-builder.js → street/morphology-fst-builder.js} +18 -13
  385. package/out/street/morphology-fst-builder.js.map +1 -0
  386. package/out/{street-morphology-fst-loader.d.ts → street/morphology-fst-loader.d.ts} +5 -5
  387. package/out/street/morphology-fst-loader.d.ts.map +1 -0
  388. package/out/{street-morphology-fst-loader.js → street/morphology-fst-loader.js} +11 -10
  389. package/out/street/morphology-fst-loader.js.map +1 -0
  390. package/out/{street-name-lookup.d.ts → street/name-lookup.d.ts} +4 -7
  391. package/out/street/name-lookup.d.ts.map +1 -0
  392. package/out/{street-name-lookup.js → street/name-lookup.js} +9 -23
  393. package/out/street/name-lookup.js.map +1 -0
  394. package/out/street/normalize.d.ts +179 -0
  395. package/out/street/normalize.d.ts.map +1 -0
  396. package/out/street/normalize.js +457 -0
  397. package/out/street/normalize.js.map +1 -0
  398. package/out/{street-segment-schema.d.ts → street/segment-schema.d.ts} +13 -9
  399. package/out/street/segment-schema.d.ts.map +1 -0
  400. package/out/{street-segment-schema.js → street/segment-schema.js} +4 -4
  401. package/out/{street-segment-schema.js.map → street/segment-schema.js.map} +1 -1
  402. package/out/types.d.ts +49 -9
  403. package/out/types.d.ts.map +1 -1
  404. package/out/types.js.map +1 -1
  405. package/out/unified-schema.d.ts +6 -5
  406. package/out/unified-schema.d.ts.map +1 -1
  407. package/out/unified-schema.js +16 -19
  408. package/out/unified-schema.js.map +1 -1
  409. package/out/uprn/existence.d.ts +53 -0
  410. package/out/uprn/existence.d.ts.map +1 -0
  411. package/out/uprn/existence.js +61 -0
  412. package/out/uprn/existence.js.map +1 -0
  413. package/out/uprn/index.d.ts +9 -0
  414. package/out/uprn/index.d.ts.map +1 -0
  415. package/out/uprn/index.js +9 -0
  416. package/out/uprn/index.js.map +1 -0
  417. package/out/uprn/lookup.d.ts +85 -0
  418. package/out/uprn/lookup.d.ts.map +1 -0
  419. package/out/uprn/lookup.js +149 -0
  420. package/out/uprn/lookup.js.map +1 -0
  421. package/out/uprn/schema.d.ts +93 -0
  422. package/out/uprn/schema.d.ts.map +1 -0
  423. package/out/uprn/schema.js +78 -0
  424. package/out/uprn/schema.js.map +1 -0
  425. package/out/weights-overlay-linker.d.ts +299 -0
  426. package/out/weights-overlay-linker.d.ts.map +1 -0
  427. package/out/weights-overlay-linker.js +511 -0
  428. package/out/weights-overlay-linker.js.map +1 -0
  429. package/package.json +622 -154
  430. package/address-point.ts +0 -125
  431. package/candidate-lookup.ts +0 -720
  432. package/fst-autocomplete.ts +0 -204
  433. package/geo.ts +0 -121
  434. package/lookup.ts +0 -1354
  435. package/out/address-point-interpolation.d.ts.map +0 -1
  436. package/out/address-point-interpolation.js.map +0 -1
  437. package/out/address-point-schema.d.ts.map +0 -1
  438. package/out/address-point-schema.js.map +0 -1
  439. package/out/address-point.d.ts.map +0 -1
  440. package/out/address-point.js +0 -84
  441. package/out/address-point.js.map +0 -1
  442. package/out/ancestry-backfill.d.ts.map +0 -1
  443. package/out/ancestry-backfill.js.map +0 -1
  444. package/out/ancestry.d.ts.map +0 -1
  445. package/out/ancestry.js.map +0 -1
  446. package/out/convention.d.ts.map +0 -1
  447. package/out/convention.js.map +0 -1
  448. package/out/fst-autocomplete.d.ts.map +0 -1
  449. package/out/fst-autocomplete.js +0 -130
  450. package/out/fst-autocomplete.js.map +0 -1
  451. package/out/fst-builder.d.ts.map +0 -1
  452. package/out/fst-builder.js.map +0 -1
  453. package/out/fst-deserialize-web.d.ts.map +0 -1
  454. package/out/fst-deserialize-web.js.map +0 -1
  455. package/out/fst-freshness.d.ts.map +0 -1
  456. package/out/fst-freshness.js.map +0 -1
  457. package/out/fst-matcher.d.ts.map +0 -1
  458. package/out/fst-matcher.js.map +0 -1
  459. package/out/fst-serialize.d.ts.map +0 -1
  460. package/out/fst-serialize.js.map +0 -1
  461. package/out/fst-types.d.ts.map +0 -1
  462. package/out/fst-types.js.map +0 -1
  463. package/out/fts-query.d.ts.map +0 -1
  464. package/out/fts-query.js.map +0 -1
  465. package/out/fts.d.ts.map +0 -1
  466. package/out/fts.js.map +0 -1
  467. package/out/geo.d.ts +0 -74
  468. package/out/geo.d.ts.map +0 -1
  469. package/out/geo.js +0 -71
  470. package/out/geo.js.map +0 -1
  471. package/out/geonames-aliases.d.ts.map +0 -1
  472. package/out/geonames-aliases.js.map +0 -1
  473. package/out/geonames-postal.d.ts.map +0 -1
  474. package/out/geonames-postal.js.map +0 -1
  475. package/out/poi-lookup.d.ts.map +0 -1
  476. package/out/poi-lookup.js.map +0 -1
  477. package/out/poi-schema.d.ts.map +0 -1
  478. package/out/poi-schema.js.map +0 -1
  479. package/out/postal-city-alias-lookup.d.ts.map +0 -1
  480. package/out/postal-city-alias-lookup.js.map +0 -1
  481. package/out/postal-city-candidate-schema.d.ts.map +0 -1
  482. package/out/sharding.d.ts +0 -114
  483. package/out/sharding.d.ts.map +0 -1
  484. package/out/sharding.js.map +0 -1
  485. package/out/street-centroid-schema.d.ts.map +0 -1
  486. package/out/street-centroid.d.ts.map +0 -1
  487. package/out/street-centroid.js.map +0 -1
  488. package/out/street-morphology-fst-builder.d.ts.map +0 -1
  489. package/out/street-morphology-fst-builder.js.map +0 -1
  490. package/out/street-morphology-fst-loader.d.ts.map +0 -1
  491. package/out/street-morphology-fst-loader.js.map +0 -1
  492. package/out/street-name-lookup.d.ts.map +0 -1
  493. package/out/street-name-lookup.js.map +0 -1
  494. package/out/street-normalize.d.ts +0 -95
  495. package/out/street-normalize.d.ts.map +0 -1
  496. package/out/street-normalize.js +0 -272
  497. package/out/street-normalize.js.map +0 -1
  498. package/out/street-segment-schema.d.ts.map +0 -1
  499. package/sqlite-utils.ts +0 -46
  500. package/street-normalize.ts +0 -318
  501. /package/{postal-city-alias-schema.ts → lib/postal/city-alias-schema.ts} +0 -0
@@ -0,0 +1,976 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Node-side {@link PlaceLookup} over the byte-range CANDIDATE table (`build-candidate.ts`) — the
7
+ * SAME gazetteer the browser demo resolves against ({@link WOFCandidateTableLookup} in
8
+ * `docs/src/shared/httpvfs-resolver.ts`), but reading a LOCAL `candidate.db` via `node:sqlite`
9
+ * instead of sql.js-httpvfs. This is what makes the server/CLI resolver match the demo: one
10
+ * lookup surface, one artifact, one ranking.
11
+ *
12
+ * The query is a single contiguous probe on the `WITHOUT ROWID` B-tree keyed `(name_key,
13
+ * country_id, region_id, placetype_id, neg_rank, spr_id)`. `name_key` is the SHARED
14
+ * {@link normalizeLocalityForKey} (build- and query-consistent), each row is denormalized (display
15
+ * `name`, centroid, bbox), and population rank is precomputed into `neg_rank` — so the result is
16
+ * POPULATION-FIRST and COUNTRY-AGNOSTIC (when no `country` filter is given), exactly like the
17
+ * demo. That's the deliberate divergence from {@link WOFSQLitePlaceLookup}'s FTS/bm25 ranking: a
18
+ * bare "Moscow" resolves to the 10.4 M-pop Russian city, not whichever same-name US township bm25
19
+ * floats to the top.
20
+ *
21
+ * Disambiguation rides the same mechanism the cascade already uses: a parsed region resolves to its
22
+ * stored bbox and the locality query is point-in-bbox-filtered on the candidate centroid (the
23
+ * `bbox` field on {@link FindPlaceQuery}).
24
+ */
25
+
26
+ import { jaroWinkler, levenshteinSimilarity } from "@mailwoman/match/comparators"
27
+ import {
28
+ expandPlacetypeFilter,
29
+ partitionByContainment,
30
+ type Ancestor,
31
+ type GazetteerArtifactCoverage,
32
+ } from "@mailwoman/resolver"
33
+ import { haversineKm } from "@mailwoman/spatial"
34
+ import { DatabaseClient } from "@mailwoman/sqlite/client"
35
+ import type { PathBuilderLike } from "path-ts"
36
+
37
+ import {
38
+ CANDIDATE_ANCESTOR_TABLE,
39
+ CANDIDATE_INTERVAL_TABLE,
40
+ intervalContains,
41
+ type CandidateAncestorTable,
42
+ type IntervalLabel,
43
+ } from "#candidate-ancestors-schema"
44
+ import { CANDIDATE_FTS_TABLE } from "#candidate-fts"
45
+ import type { CandidateDatabase, CandidateTable, CountryCodeTable, PlacetypeCodeTable } from "#candidate-schema"
46
+ import { readGazetteerCoverageManifest } from "#coverage-manifest-schema"
47
+ import { referentialFromPopulation } from "#place-importance-schema"
48
+ import { POSTAL_CITY_CANDIDATE_TABLE, type PostalCityCandidateTable } from "#postal/city-candidate-schema"
49
+ import { rankByPrimaryPreference, type RankedRow, RERANK_FETCH } from "#primary-preference"
50
+ import { applyProximityRerank } from "#proximity-rerank"
51
+ import { REGION_CLASS_PLACETYPES, regionQualifierProbeKeys } from "#region-keys"
52
+ import { allRows, hasColumn, hasTable } from "#sqlite-utils"
53
+ import { type NameKey, normalizeLocalityForKey, stripLocalityQualifier } from "#street/normalize"
54
+ import type { FindPlaceQuery, PlaceCandidate, PlaceLookup, WOFPlacetype } from "#types"
55
+
56
+ export { rankByPrimaryPreference } from "#primary-preference"
57
+ export type { RankedRow } from "#primary-preference"
58
+
59
+ export interface WOFCandidateTableLookupOpts {
60
+ /**
61
+ * Path to a `candidate.db` built by `build-candidate.ts`. Opened read-only.
62
+ */
63
+ databasePath?: PathBuilderLike
64
+ /**
65
+ * Pre-opened handle (tests / shared connections). Mutually exclusive with `databasePath`.
66
+ */
67
+ database?: DatabaseClient<CandidateDatabase>
68
+ /**
69
+ * #1882 opt-in: exempt `name_role = 'variant'` aliases — the holder's own primary name in another orthography,
70
+ * stamped by the build's own-name detector — from the cross-country primary-preference penalty. No-ops on an artifact
71
+ * without the role column. Default OFF (D-rule).
72
+ */
73
+ variantAliasExemption?: boolean
74
+ }
75
+
76
+ /**
77
+ * The candidate columns this lookup probes — a typed projection of the SHARED {@link CandidateTable}, so a column rename
78
+ * in `build-candidate` (the writer) is a compile error here (the reader).
79
+ */
80
+ type CandidateRow = Pick<
81
+ CandidateTable,
82
+ | "spr_id"
83
+ | "name"
84
+ | "country_id"
85
+ | "placetype_id"
86
+ | "latitude"
87
+ | "longitude"
88
+ | "min_lat"
89
+ | "min_lon"
90
+ | "max_lat"
91
+ | "max_lon"
92
+ | "neg_rank"
93
+ | "is_primary"
94
+ | "population"
95
+ > &
96
+ // `importance` is OPTIONAL on the row rather than `number | null`, because whether the SELECT names it
97
+ // depends on the artifact: a candidate.db built before #28 has no such column and the probe leaves it
98
+ // out (see `#importanceSelect`). `undefined` therefore means "this build cannot tell you", which is the
99
+ // same answer as `null`'s "the score source had no measurement" — both are UNMEASURED, and the emit
100
+ // below collapses them into the one thing the consumer understands: no `importance` field at all.
101
+ Partial<Pick<CandidateTable, "importance">>
102
+
103
+ /**
104
+ * FTS5-trigram over-fetch before the WORD-LEVEL re-rank. The trigram index stays the candidate GENERATOR (it is what
105
+ * the artifact carries); the scoring moved off trigram-Jaccard on 2026-08-12 (#1614), which the aucklnad receipts
106
+ * falsified as a typo measure: it scored the true transposition correction 'auckland' at 0.333 — below its own 0.34 bar
107
+ * — while 'auckley' scored 0.375 and the 'gore bay' scrape 0.455, because shared generic suffixes count as trigram
108
+ * evidence and transpositions count against it.
109
+ */
110
+ const FUZZY_FETCH = 40
111
+
112
+ /**
113
+ * Minimum WORD-LEVEL similarity (max of Jaro-Winkler and normalized edit similarity — the `match/comparators`
114
+ * primitives, deliberately WITHOUT `nameSimilarity`'s token-subset floor, which is a person-name rule that would hand
115
+ * 'stanmore bay' to a place named 'Bay') for a fuzzy correction to count. Measured on the #1614 receipts:
116
+ * 'aucklnad'→'auckland' 0.975 (in), →'auckley' 0.868 (in, but outranked), 'stanmore bay'→'gore bay' ~0.70 (out),
117
+ * 'sacremento'→'sacramento' ~0.97 (in).
118
+ */
119
+ const WORD_FUZZY_MIN = 0.85
120
+
121
+ /**
122
+ * The word-level correction similarity — see {@link WORD_FUZZY_MIN}.
123
+ */
124
+ function wordFuzzySimilarity(a: string, b: string): number {
125
+ return Math.max(jaroWinkler(a, b), levenshteinSimilarity(a, b))
126
+ }
127
+
128
+ /**
129
+ * Postcode-containment re-rank check radius (km) — the SAME value the resolver's country pass measures at
130
+ * (`POSTCODE_COUNTRY_COHERENCE_THRESHOLD_KM`, resolver/postcode-country-coherence.ts): a locality within this distance
131
+ * of the postcode's own centroid counts as "containing" it. One number, two passes — a divergence here would make the
132
+ * two mechanisms disagree about what is proximal.
133
+ */
134
+ const POSTCODE_CONTAINMENT_THRESHOLD_KM = 25
135
+
136
+ /**
137
+ * Unpadded character-trigrams of `s`, OR'd into an FTS5 trigram MATCH query (each quoted so FTS treats it as a literal
138
+ * term). Returns "" when `s` is shorter than a trigram or yields no clean grams — the caller then skips the fuzzy
139
+ * probe.
140
+ */
141
+ function ftsTrigramQuery(s: string): string {
142
+ const grams = new Set<string>()
143
+
144
+ for (let i = 0; i + 3 <= s.length; i++) {
145
+ const g = s.slice(i, i + 3)
146
+
147
+ if (/^[\p{L}\p{N} ]{3}$/u.test(g)) {
148
+ grams.add(g)
149
+ }
150
+ }
151
+
152
+ return [...grams].map((g) => `"${g}"`).join(" OR ")
153
+ }
154
+
155
+ /**
156
+ * Node {@link PlaceLookup} over `candidate.db`. Drop-in for {@link WOFSQLitePlaceLookup} in `createWOFResolver(backend)`
157
+ * — same `findPlace` contract, population-first ranking.
158
+ */
159
+ export class WOFCandidateTableLookup implements PlaceLookup, Disposable {
160
+ #db: DatabaseClient<CandidateDatabase>
161
+ /**
162
+ * Resources this instance opened. A connection handed in by a caller is NOT in here, so disposal cannot reach it —
163
+ * ownership is membership rather than a flag a later branch has to check.
164
+ */
165
+ readonly #resources = new DisposableStack()
166
+ readonly #countryToID = new Map<string, number>()
167
+ readonly #idToCountry = new Map<number, string>()
168
+ readonly #placetypeToID = new Map<string, number>()
169
+ readonly #idToPlacetype = new Map<number, string>()
170
+ /**
171
+ * Prepared `(name_key, postcode)` probe for the #741 postal-city side-index — `undefined` when the
172
+ * `postal_city_candidate` table isn't present, so a candidate.db built without it is byte-stable.
173
+ */
174
+ readonly #postalCityProbe: ReturnType<DatabaseClient["prepare"]> | undefined
175
+ /**
176
+ * Prepared FTS5-trigram MATCH probe for the typo-tolerant fallback — `undefined` when the `candidate_fts` index isn't
177
+ * present, so a candidate.db built without it is byte-stable (the fuzzy path is skipped, exactly like today).
178
+ */
179
+ readonly #ftsProbe: ReturnType<DatabaseClient["prepare"]> | undefined
180
+ /**
181
+ * Prepared UNFILTERED existence probe (`name_key` present anywhere, ignoring country/placetype/bbox). Checks the
182
+ * fuzzy fallback: fuzzy is a TYPO corrector, so it engages only when the name doesn't exist in the gazetteer at all.
183
+ * A name that DOES exist but missed under the active filter is a filter miss (e.g. a placer misroute "Vienna,
184
+ * Austria"→IT), not a spelling miss — fuzzing it would scrape an unrelated same-country place and defeat the
185
+ * cascade's country-agnostic retry. Prepared only alongside `#ftsProbe`.
186
+ */
187
+ readonly #nameKeyExistsProbe: ReturnType<DatabaseClient["prepare"]> | undefined
188
+ /**
189
+ * Facts this candidate DB declares about itself — the coverage manifest (`country_coverage` + `country_bbox`) the
190
+ * gazetteer build emits, read once at open. `undefined` when the artifact predates the manifest, so every consumer
191
+ * (the hard-country coverage check, guard-B plausibility) falls back to its code constants byte-identically.
192
+ */
193
+ readonly artifactCoverage: GazetteerArtifactCoverage | undefined
194
+ /**
195
+ * `", importance"` when this artifact carries the #28 fame column, `""` when it does not — spliced into the probe's
196
+ * SELECT list. Existence-restricted exactly like `#ftsProbe` and `#postalCityProbe` above, and for the same reason: a
197
+ * candidate.db built before the column is a valid artifact, and naming a column it lacks would turn a stale gazetteer
198
+ * into `no such column` on the first keystroke rather than into "no fame signal", which is what it is.
199
+ */
200
+ readonly #importanceSelect: string
201
+ /**
202
+ * Whether the artifact carries the #1730 `name_role` column — absent on pre-role builds, where the `excludeNameRoles`
203
+ * filter degrades to a no-op rather than erroring on a missing column.
204
+ */
205
+ readonly #hasNameRole: boolean
206
+ readonly #variantAliasExemption: boolean
207
+ /**
208
+ * `", name_role"` when the artifact carries the column — the probe SELECT rides it so the #1882 exemption can read
209
+ * the stamp off the row; empty on a pre-role build.
210
+ */
211
+ readonly #roleSelect: string
212
+ /**
213
+ * Prepared chain probe over the `candidate_ancestor` sidecar — `undefined` when the artifact predates it.
214
+ */
215
+ readonly #ancestorsProbe: ReturnType<DatabaseClient["prepare"]> | undefined
216
+ readonly #ancestorsCache = new Map<number, Ancestor[]>()
217
+ /**
218
+ * Prepared interval-label probe over `candidate_interval` — `undefined` when the artifact predates the sidecar, which
219
+ * is what makes the admin-containment re-rank (#1717 stage 2) capability-restricted: without it,
220
+ * `FindPlaceQuery.regionQualifier` is ignored, no candidate carries a `containedByQualifier` stamp, and the resolver
221
+ * walk reports the change `unavailable` instead of silently dead.
222
+ */
223
+ readonly #intervalProbe: ReturnType<DatabaseClient["prepare"]> | undefined
224
+ readonly #intervalCache = new Map<number, IntervalLabel | null>()
225
+ /**
226
+ * Prepared qualifier probe: the region-band rows (plus `country` — the region SLOT can hold a mislabeled country
227
+ * name, "Moscow, Russia" parses region="Russia") for one folded qualifier key. `undefined` when the artifact lacks
228
+ * the sidecar or the placetype dictionary lacks the band entirely.
229
+ */
230
+ readonly #qualifierProbe: ReturnType<DatabaseClient["prepare"]> | undefined
231
+ /**
232
+ * The ancestor lineage of a resolved place — nearest-first (locality-tier → county → region → … → country), the same
233
+ * order the FTS backend's `ancestorLineage` serves, read from the `candidate_ancestor` sidecar in one clustered
234
+ * probe. Backs `ResolveOpts.includeAncestors` (#404) on this backend, which is what puts region-class ancestry in
235
+ * front of the admin-coherence check (#1717).
236
+ *
237
+ * A PROPERTY, not a method, and assigned only when the artifact carries the sidecar: capability probes (`typeof
238
+ * backend.ancestors === "function"` — the resolver's gap report) then read the ARTIFACT truthfully. A candidate.db
239
+ * built before the sidecar reports the capability absent instead of presenting a method that answers `[]` for every
240
+ * place, which would be an absence dressed as a negative answer.
241
+ */
242
+ readonly ancestors: ((id: number | string) => Ancestor[]) | undefined
243
+
244
+ constructor(opts: WOFCandidateTableLookupOpts) {
245
+ if (opts.database) {
246
+ this.#db = opts.database
247
+ } else if (opts.databasePath) {
248
+ this.#db = this.#resources.use(new DatabaseClient<CandidateDatabase>(opts.databasePath, { readOnly: true }))
249
+ } else {
250
+ throw new Error("WOFCandidateTableLookup needs `databasePath` or `database`")
251
+ }
252
+
253
+ // The code tables are tiny (country/placetype dictionaries) — load them once at construction so
254
+ // `findPlace` is a single B-tree probe with no dictionary round-trip.
255
+ for (const r of allRows<CountryCodeTable>(this.#db.prepare("SELECT id, code FROM country_codes"))) {
256
+ const code = String(r.code).toUpperCase()
257
+ this.#countryToID.set(code, Number(r.id))
258
+ this.#idToCountry.set(Number(r.id), code)
259
+ }
260
+
261
+ for (const r of allRows<PlacetypeCodeTable>(this.#db.prepare("SELECT id, placetype FROM placetype_codes"))) {
262
+ this.#placetypeToID.set(String(r.placetype), Number(r.id))
263
+ this.#idToPlacetype.set(Number(r.id), String(r.placetype))
264
+ }
265
+
266
+ // #741 postal-city side-index: prepare the exact probe only if the table is present. Absent →
267
+ // `#postalCityProbe` stays undefined → findPlace skips the postal-city path → byte-stable.
268
+ if (hasTable(this.#db, POSTAL_CITY_CANDIDATE_TABLE)) {
269
+ this.#postalCityProbe = this.#db.prepare(
270
+ `SELECT spr_id, name, latitude, longitude FROM ${POSTAL_CITY_CANDIDATE_TABLE} WHERE name_key = ? AND postcode = ? LIMIT 1`
271
+ )
272
+ }
273
+
274
+ // FTS5-trigram fuzzy fallback: prepare the MATCH probe only if the index is present (the unified
275
+ // gazetteer carries it; an older candidate.db doesn't → the fuzzy path is skipped, byte-stable).
276
+ if (hasTable(this.#db, CANDIDATE_FTS_TABLE)) {
277
+ this.#ftsProbe = this.#db.prepare(
278
+ `SELECT name_key FROM ${CANDIDATE_FTS_TABLE} WHERE ${CANDIDATE_FTS_TABLE} MATCH ? ORDER BY bm25(${CANDIDATE_FTS_TABLE}) LIMIT ?`
279
+ )
280
+
281
+ this.#nameKeyExistsProbe = this.#db.prepare("SELECT 1 FROM candidate WHERE name_key = ? LIMIT 1")
282
+ }
283
+
284
+ // #28 fame column: probed ONCE here (it runs a PRAGMA, and `findPlace` is per-keystroke hot).
285
+ this.#importanceSelect = hasColumn(this.#db, "candidate", "importance") ? ", importance" : ""
286
+ this.#hasNameRole = hasColumn(this.#db, "candidate", "name_role")
287
+ this.#variantAliasExemption = opts.variantAliasExemption === true
288
+ this.#roleSelect = this.#hasNameRole ? ", name_role" : ""
289
+
290
+ // Ancestors sidecar (#1717): existence-restricted like the probes above, and the CAPABILITY checks with
291
+ // it — see the `ancestors` property doc for why an older artifact must read as "no ancestors()"
292
+ // rather than as a method that answers [] everywhere.
293
+ if (hasTable(this.#db, CANDIDATE_ANCESTOR_TABLE)) {
294
+ this.#ancestorsProbe = this.#db.prepare(
295
+ `SELECT parent_spr_id, parent_placetype_id, parent_name FROM ${CANDIDATE_ANCESTOR_TABLE}` +
296
+ " WHERE spr_id = ? ORDER BY depth ASC"
297
+ )
298
+
299
+ this.ancestors = (id) => this.#ancestorLineage(id)
300
+ }
301
+
302
+ // Admin-containment re-rank (#1717 stage 2): conditioned on the interval half of the sidecar (built in
303
+ // the same pass as the closure rows; probed separately so a hand-degraded artifact degrades
304
+ // truthfully) AND on the placetype dictionary carrying the qualifier band at all.
305
+ if (this.#ancestorsProbe && hasTable(this.#db, CANDIDATE_INTERVAL_TABLE)) {
306
+ this.#intervalProbe = this.#db.prepare(`SELECT pre, post FROM ${CANDIDATE_INTERVAL_TABLE} WHERE spr_id = ?`)
307
+
308
+ const bandIDs = [...REGION_CLASS_PLACETYPES, "country"]
309
+ .map((placetype) => this.#placetypeToID.get(placetype))
310
+ .filter((id): id is number => id !== undefined)
311
+
312
+ if (bandIDs.length) {
313
+ this.#qualifierProbe = this.#db.prepare(
314
+ `SELECT DISTINCT spr_id FROM candidate WHERE name_key = ? AND placetype_id IN (${bandIDs.join(",")}) LIMIT 8`
315
+ )
316
+ }
317
+ }
318
+
319
+ // Coverage manifest (survey candidate #2): the artifact's own coverage facts, existence-restricted like
320
+ // the probes above — a candidate.db built before the manifest reads `undefined` and consumers keep
321
+ // their code-constant fallbacks byte-identically.
322
+ this.artifactCoverage = readGazetteerCoverageManifest(this.#db)
323
+ }
324
+
325
+ /**
326
+ * The memoized chain read behind {@link ancestors}. Sync raw `.prepare()` on purpose — the backend contract's
327
+ * `ancestors()` is synchronous (the sync-by-interface resolver-reader rule), and the sidecar row already carries the
328
+ * parent's name and placetype, so this is one clustered probe with no join.
329
+ */
330
+ #ancestorLineage(id: number | string): Ancestor[] {
331
+ const pid = typeof id === "number" ? id : Number(id)
332
+
333
+ if (!Number.isFinite(pid) || !this.#ancestorsProbe) return []
334
+
335
+ const cached = this.#ancestorsCache.get(pid)
336
+
337
+ if (cached) return cached
338
+
339
+ const rows = allRows<Pick<CandidateAncestorTable, "parent_spr_id" | "parent_placetype_id" | "parent_name">>(
340
+ this.#ancestorsProbe,
341
+ pid
342
+ )
343
+
344
+ const lineage: Ancestor[] = rows.map((r) => ({
345
+ id: Number(r.parent_spr_id),
346
+ placetype: this.#idToPlacetype.get(Number(r.parent_placetype_id)) ?? "",
347
+ name: String(r.parent_name ?? ""),
348
+ }))
349
+
350
+ this.#ancestorsCache.set(pid, lineage)
351
+
352
+ return lineage
353
+ }
354
+
355
+ /**
356
+ * The interval label for one place, memoized. `null` is a real answer — the place has no recorded ancestry in the
357
+ * source (absence semantics: UNVERIFIABLE, never a containment verdict) — and is cached as such.
358
+ */
359
+ #intervalLabel(sprID: number): IntervalLabel | null {
360
+ if (!this.#intervalProbe) return null
361
+
362
+ const cached = this.#intervalCache.get(sprID)
363
+
364
+ if (cached !== undefined) return cached
365
+
366
+ const row = this.#intervalProbe.get(sprID) as { pre: number; post: number } | undefined
367
+ const label = row ? { pre: Number(row.pre), post: Number(row.post) } : null
368
+
369
+ this.#intervalCache.set(sprID, label)
370
+
371
+ return label
372
+ }
373
+
374
+ /**
375
+ * The qualifier's own rows in the candidate table: every region-band (+ country) place whose `name_key` matches one
376
+ * of the qualifier's {@link regionQualifierProbeKeys} expansions. Alias keys participate — `Thüringen` finds the row
377
+ * stored as `Thuringia` through the artifact's own alias keying, which is precisely the variant-form bridge the
378
+ * admin-coherence verdicts' fold-equality bound cannot offer (its stated v1 bound). Empty = the qualifier names
379
+ * nothing the artifact knows; the caller then stamps `false` everywhere and reorders nothing.
380
+ */
381
+ #qualifierRegionIDs(qualifier: string, country: string | undefined): Set<number> {
382
+ const ids = new Set<number>()
383
+
384
+ if (!this.#qualifierProbe) return ids
385
+
386
+ for (const key of regionQualifierProbeKeys(qualifier, country)) {
387
+ if (!key) continue
388
+
389
+ for (const row of allRows<{ spr_id: number }>(this.#qualifierProbe, key)) {
390
+ ids.add(Number(row.spr_id))
391
+ }
392
+ }
393
+
394
+ return ids
395
+ }
396
+
397
+ /**
398
+ * Is `sprID` contained by ANY of the qualifier's rows? Interval first — {@link intervalContains}, O(1), reflexive —
399
+ * then the closure rows where intervals abstain: the interval forest encodes only the CANONICAL parent per place, so
400
+ * a `false` there means "not contained along the canonical hierarchy", and the chain probe (one clustered read of
401
+ * ≤{@link MAX_ANCESTOR_DEPTH} rows) is the complete record that determines the result.
402
+ */
403
+ #containedByQualifier(sprID: number, qualifierIDs: ReadonlySet<number>, qualifierLabels: IntervalLabel[]): boolean {
404
+ if (qualifierIDs.has(sprID)) return true
405
+
406
+ const label = this.#intervalLabel(sprID)
407
+
408
+ if (label && qualifierLabels.some((outer) => intervalContains(outer, label))) return true
409
+
410
+ return this.#ancestorLineage(sprID).some((ancestor) => qualifierIDs.has(Number(ancestor.id)))
411
+ }
412
+
413
+ /**
414
+ * The #1717 stage-2 re-rank over one lookup's final row set. Three steps, each additive:
415
+ *
416
+ * 1. Resolve the qualifier to its region-band rows ({@link #qualifierRegionIDs}) and stamp every existing row's
417
+ * `containedByQualifier` — the stamp is the trace surface, written even when nothing reorders.
418
+ * 2. INJECT contained same-key candidates the country scope hid: the deciding-site measurement (2026-08-18, the #1729
419
+ * lesson re-confirmed) showed `Weimar, Thüringen` under the en-US locale probes `country_id = US`, so the DE row
420
+ * is not IN the list and no reorder of the list can reach it. The injection probe runs the same exact fold (and,
421
+ * on a contained-miss, the qualifier-strip variant restricted to primary keys — the #1626 alias-scrape guard)
422
+ * under the SHAPE conds only, appends contained rows not already present, and never removes anything — recall can
423
+ * only widen. The typo-fuzzy tier is deliberately not probed: a qualifier cannot vouch for a name the gazetteer
424
+ * does not carry.
425
+ * 3. Partition contained-first — the SHARED {@link partitionByContainment} (tier-safe, stable; the resolver walk runs
426
+ * the same function after its fame re-rank, one function at both deciding sites per the #861 rule) — then
427
+ * re-window to `limit`.
428
+ *
429
+ * A qualifier that matches nothing stamps `false` everywhere and reorders nothing — byte-identical answers, and the
430
+ * walk's verdict reads `no_contained_candidate` rather than `unavailable` (the question WAS asked).
431
+ */
432
+ #applyAdminContainment(
433
+ rows: Array<RankedRow<CandidateRow>>,
434
+ qualifier: string,
435
+ country: string | undefined,
436
+ opts: {
437
+ nameKey: NameKey
438
+ strippedKey: NameKey
439
+ shapeFilters: string[]
440
+ shapeParams: Array<string | number>
441
+ limit: number
442
+ }
443
+ ): Array<RankedRow<CandidateRow>> {
444
+ const qualifierIDs = this.#qualifierRegionIDs(qualifier, country)
445
+
446
+ if (!qualifierIDs.size) {
447
+ for (const row of rows) {
448
+ row.containedByQualifier = false
449
+ }
450
+
451
+ return rows
452
+ }
453
+
454
+ const qualifierLabels = [...qualifierIDs]
455
+ .map((id) => this.#intervalLabel(id))
456
+ .filter((label): label is IntervalLabel => label !== null)
457
+
458
+ const contained = (sprID: number): boolean => this.#containedByQualifier(sprID, qualifierIDs, qualifierLabels)
459
+
460
+ for (const row of rows) {
461
+ row.containedByQualifier = contained(Number(row.spr_id))
462
+ }
463
+
464
+ const present = new Set(rows.map((row) => Number(row.spr_id)))
465
+ const injected: Array<RankedRow<CandidateRow>> = []
466
+
467
+ const injectSQL = (primaryOnly: boolean): string =>
468
+ "SELECT spr_id, name, country_id, placetype_id, latitude, longitude, min_lat, min_lon, max_lat, max_lon, neg_rank, is_primary, population" +
469
+ `${this.#importanceSelect} FROM candidate WHERE ${["name_key = ?", ...opts.shapeFilters, ...(primaryOnly ? ["is_primary = 1"] : [])].join(" AND ")} ` +
470
+ "ORDER BY neg_rank ASC LIMIT ?"
471
+
472
+ const injectFrom = (key: string, primaryOnly: boolean): void => {
473
+ const fetched = allRows<CandidateRow>(
474
+ this.#db.prepare(injectSQL(primaryOnly)),
475
+ key,
476
+ ...opts.shapeParams,
477
+ RERANK_FETCH
478
+ )
479
+
480
+ for (const row of fetched) {
481
+ const sprID = Number(row.spr_id)
482
+
483
+ if (present.has(sprID) || !contained(sprID)) continue
484
+ present.add(sprID)
485
+
486
+ injected.push({ ...row, effectiveNegRank: row.neg_rank, demoted: false, containedByQualifier: true })
487
+ }
488
+ }
489
+
490
+ injectFrom(opts.nameKey, false)
491
+
492
+ // #1731: the dependent-locality band. A locality query's filter group (locality/borough/localadmin)
493
+ // cannot reach a neighbourhood-tier namesake, so a CONTAINED one is structurally invisible no matter
494
+ // how the list reorders — the Astoria class: Queens' Astoria is a WOF neighbourhood, and the walk
495
+ // answered the Oregon locality under `qualifier="NY"` because nothing in the pool sat under NY. The
496
+ // widening is injection-only and triple-conditioned: the band is explicit (neighbourhood/macrohood/microhood
497
+ // — never region or country tiers), admission still requires the sidecar's containment proof, and only
498
+ // primary-keyed rows enter (an alias-keyed neighbourhood is the #1626 scrape class). Recall can only
499
+ // widen, and only toward rows the qualifier vouches for. `opts.shapeFilters`' bbox clause is
500
+ // deliberately not carried: containment is the stronger constraint, and the two co-occurring is not a
501
+ // measured shape.
502
+ const bandIDs = ["neighbourhood", "macrohood", "microhood"]
503
+ .map((placetype) => this.#placetypeToID.get(placetype))
504
+ .filter((id): id is number => id !== undefined)
505
+
506
+ if (bandIDs.length) {
507
+ const bandSQL =
508
+ "SELECT spr_id, name, country_id, placetype_id, latitude, longitude, min_lat, min_lon, max_lat, max_lon, neg_rank, is_primary, population" +
509
+ `${this.#importanceSelect} FROM candidate WHERE name_key = ? AND placetype_id IN (${bandIDs.map(() => "?").join(",")}) AND is_primary = 1 ` +
510
+ "ORDER BY neg_rank ASC LIMIT ?"
511
+
512
+ const fetched = allRows<CandidateRow>(this.#db.prepare(bandSQL), opts.nameKey, ...bandIDs, RERANK_FETCH)
513
+
514
+ for (const row of fetched) {
515
+ const sprID = Number(row.spr_id)
516
+
517
+ if (present.has(sprID) || !contained(sprID)) continue
518
+ present.add(sprID)
519
+
520
+ injected.push({ ...row, effectiveNegRank: row.neg_rank, demoted: false, containedByQualifier: true })
521
+ }
522
+ }
523
+
524
+ // The strip variant mirrors the cascade's discipline: tried only when the exact fold vouched for
525
+ // nothing, and primary-keyed only (a stripped surface never named an alias — #1626).
526
+ if (
527
+ !injected.length &&
528
+ !rows.some((row) => row.containedByQualifier) &&
529
+ opts.strippedKey &&
530
+ opts.strippedKey !== opts.nameKey
531
+ ) {
532
+ injectFrom(opts.strippedKey, true)
533
+ }
534
+
535
+ if (!injected.length && !rows.some((row) => row.containedByQualifier)) return rows
536
+
537
+ return partitionByContainment(
538
+ [...rows, ...injected],
539
+ (row) => row.containedByQualifier === true,
540
+ (row) => !row.demoted && !row.fuzzy
541
+ ).slice(0, opts.limit)
542
+ }
543
+
544
+ /**
545
+ * Does this query want a locality-tier place? Postal-city aliases (#741) are all localities.
546
+ */
547
+ #wantsLocality(placetype: FindPlaceQuery["placetype"]): boolean {
548
+ if (!placetype) return true
549
+ const want = Array.isArray(placetype) ? placetype : [placetype]
550
+
551
+ return expandPlacetypeFilter(want as readonly string[]).includes("locality")
552
+ }
553
+
554
+ /**
555
+ * The postcode-containment anchor: the postcode's own centroid row in the candidate table, keyed whitespace-stripped
556
+ * (#920 — the same fold the build applies to postcode rows), country-scoped when the query is, first
557
+ * coordinate-bearing row wins. null when the candidate table carries no such postcode — the re-rank then abstains,
558
+ * because a recall gap is not evidence for the name match. Meaning-of-zero: a 0,0 row is the build's unlocated
559
+ * sentinel, never a real centroid.
560
+ */
561
+ #postcodeAnchor(postcode: string, country?: string): { lat: number; lon: number } | null {
562
+ const placetypeID = this.#placetypeToID.get("postalcode")
563
+
564
+ if (placetypeID === undefined) return null
565
+
566
+ const conds = ["name_key = ?", "placetype_id = ?"]
567
+ const params: Array<string | number> = [postcode.replaceAll(/\s+/g, ""), placetypeID]
568
+
569
+ if (country) {
570
+ const countryID = this.#countryToID.get(country.toUpperCase())
571
+
572
+ if (countryID === undefined) return null // a country the candidate table doesn't carry
573
+ conds.push("country_id = ?")
574
+ params.push(countryID)
575
+ }
576
+
577
+ const row = this.#db
578
+ .prepare(`SELECT latitude, longitude FROM candidate WHERE ${conds.join(" AND ")} ORDER BY neg_rank ASC LIMIT 1`)
579
+ .get(...params) as { latitude: number; longitude: number } | undefined
580
+
581
+ if (!row || (Number(row.latitude) === 0 && Number(row.longitude) === 0)) return null
582
+
583
+ return { lat: Number(row.latitude), lon: Number(row.longitude) }
584
+ }
585
+
586
+ async findPlace(query: FindPlaceQuery): Promise<PlaceCandidate[]> {
587
+ let text = (query.text ?? "").trim()
588
+
589
+ if (!text) return []
590
+
591
+ // #920 name law, candidate-key edition: postcode rows are keyed by their whitespace-stripped
592
+ // form at build (the GeoNames fold normalizes '624 66' → '62466'), so a postcode-typed query
593
+ // strips internal whitespace before keying. Postcode-only — locality names keep their spaces.
594
+ const wantsPostcode = [query.placetype].flat().includes("postalcode")
595
+
596
+ if (wantsPostcode) {
597
+ text = text.replaceAll(/\s+/g, "")
598
+ }
599
+
600
+ const nameKey = normalizeLocalityForKey(text)
601
+
602
+ if (!nameKey) return []
603
+
604
+ // #741: postcode-keyed postal-city alias. An exact `(name_key, postcode)` hit resolves a
605
+ // user-typed POSTAL city ("Antioch", 37013) to the geographic locality the postcode sits in
606
+ // ("Nashville"), bypassing the population/region ranking that can't see the postcode. Conditioned on
607
+ // the side-index being present, a postcode in the query, and a locality-tier request — so the
608
+ // common (no-postcode / non-locality) path is untouched. A hit short-circuits: the postcode is
609
+ // an exact, high-confidence disambiguator, so we return the single geographic locality.
610
+ if (query.postcode && this.#postalCityProbe && this.#wantsLocality(query.placetype)) {
611
+ const hit = this.#postalCityProbe.get(nameKey, query.postcode.trim()) as
612
+ | Pick<PostalCityCandidateTable, "spr_id" | "name" | "latitude" | "longitude">
613
+ | undefined
614
+
615
+ if (hit) {
616
+ return [
617
+ {
618
+ id: Number(hit.spr_id),
619
+ name: String(hit.name ?? ""),
620
+ placetype: "locality" as WOFPlacetype,
621
+ country: query.country?.toUpperCase() ?? "",
622
+ lat: Number(hit.latitude),
623
+ lon: Number(hit.longitude),
624
+ score: 1,
625
+ exactMatch: true,
626
+ },
627
+ ]
628
+ }
629
+ }
630
+
631
+ const limit = Math.max(1, query.limit ?? 10)
632
+
633
+ // Filter conds shared by the exact-key + strip-fallback probes (everything but name_key). The
634
+ // SHAPE subset (placetype/bbox/primary — everything but the country scope) is kept separately
635
+ // because the admin-containment injection probe (#1717 stage 2) runs under the shape conds
636
+ // WITHOUT the country: bypassing a locale-inferred country scope for a qualifier-vouched
637
+ // candidate is the change's whole point and the one filter injection may cross.
638
+ const filters: string[] = []
639
+ const filterParams: Array<string | number> = []
640
+ const shapeFilters: string[] = []
641
+ const shapeParams: Array<string | number> = []
642
+
643
+ if (query.country) {
644
+ const cid = this.#countryToID.get(query.country.toUpperCase())
645
+
646
+ if (cid === undefined) return [] // a country the candidate table doesn't carry
647
+ filters.push("country_id = ?")
648
+ filterParams.push(cid)
649
+ }
650
+
651
+ if (query.placetype) {
652
+ // Shared placetype-equivalence expansion (a `locality` query must also reach borough /
653
+ // localadmin). `postalcode` maps to no admin placetype here → empty → no rows.
654
+ const want = Array.isArray(query.placetype) ? query.placetype : [query.placetype]
655
+
656
+ const ids = expandPlacetypeFilter(want as readonly string[])
657
+ .map((t) => this.#placetypeToID.get(t))
658
+ .filter((v): v is number => v !== undefined)
659
+
660
+ if (!ids.length) return []
661
+ shapeFilters.push(`placetype_id IN (${ids.map(() => "?").join(",")})`)
662
+ shapeParams.push(...ids)
663
+ }
664
+
665
+ if (query.bbox) {
666
+ const b = query.bbox
667
+ shapeFilters.push("latitude BETWEEN ? AND ? AND longitude BETWEEN ? AND ?")
668
+ shapeParams.push(b.minLat, b.maxLat, b.minLon, b.maxLon)
669
+ }
670
+
671
+ // The re-reading guard (#1632, the #1626 rationale generalized to the caller): a probe whose surface
672
+ // is a token taken out of a longer classified span never NAMED an alias, so alias-keyed rows must not
673
+ // answer it — 'Savile Row''s token 'Row' resolved Rhu, Scotland (585 km) through the village's
674
+ // historical-name alias key. Whole-input bare probes never set this, keeping the exonym recall the
675
+ // #1546 note protects (Москва's alias rows answer 'Moscow').
676
+ if (query.primaryOnly) {
677
+ shapeFilters.push("is_primary = 1")
678
+ }
679
+
680
+ // The role guard (#1730): a probe may refuse abbreviation/gloss alias rows while keeping the
681
+ // role-NULL exonym tier open — the distinction `primaryOnly` cannot express. Degrades to a no-op
682
+ // on an artifact without the column.
683
+ if (query.excludeNameRoles?.length && this.#hasNameRole) {
684
+ shapeFilters.push(`(name_role IS NULL OR name_role NOT IN (${query.excludeNameRoles.map(() => "?").join(",")}))`)
685
+ shapeParams.push(...query.excludeNameRoles)
686
+ }
687
+
688
+ // The main-probe conds are country-then-shape, exactly the order they have always been.
689
+ filters.push(...shapeFilters)
690
+ filterParams.push(...shapeParams)
691
+
692
+ // Region scope: when the cascade resolves a region and passes it down as `parentID` (the walk sets
693
+ // `query.parentID = parentResolved.id`), the candidate build stamps each place's region-tier ancestor
694
+ // id into `region_id` (build-candidate.ts `regionOf`), and that id equals the resolved region's WOF id
695
+ // — so `region_id = parentID` scopes the probe to in-region rows. Without it a bare same-name probe is
696
+ // population-first and "Springfield, IL" (parentID = Illinois) drops to the larger Springfield, MO.
697
+ // Kept OUT of the shared `filters` so a region MISS falls back to the unscoped cascade below: a
698
+ // country/non-region parent (no `region_id` match), a `region_id=0` row (place with no region
699
+ // ancestor), or a wrong parent degrades to today's behavior — never worse, recall-safe by construction.
700
+ const regionParentID = query.parentID || undefined
701
+
702
+ const probe = (nk: string, regionID: number | undefined, countryID?: number): Array<RankedRow<CandidateRow>> => {
703
+ const conds = ["name_key = ?", ...filters]
704
+ const params: Array<string | number> = [nk, ...filterParams]
705
+
706
+ if (regionID !== undefined) {
707
+ conds.push("region_id = ?")
708
+ params.push(regionID)
709
+ }
710
+
711
+ // #1585: the fuzzy tier's country scope — only the corrected-key probes pass this.
712
+ if (typeof countryID === "number") {
713
+ conds.push("country_id = ?")
714
+ params.push(countryID)
715
+ }
716
+
717
+ // Fetch population-ordered (the clustered-key order — a cheap ordered scan), over-fetching to
718
+ // RERANK_FETCH so the bounded cross-country primary-preference re-rank (below) can promote the
719
+ // intended primary even when a cluster of more-populous foreign aliases sits ahead of it. `is_primary`
720
+ // + `country_id` feed that re-rank. A single-country probe (a country filter, or all rows same
721
+ // country) re-ranks to the identical population order, so the common path is untouched.
722
+ // `population` rides along for the REFERENTIAL score on the result (ROAD_TO_V9 §2) — one more
723
+ // column off a clustered row the probe already reads, and it is NOT what the probe orders by:
724
+ // `neg_rank` remains the sort key, so this changes no ordering, only what the result reports.
725
+ // `importance` (#28) rides along on the same terms, and there is deliberately NO `ORDER BY` on it:
726
+ // the fame prior is applied by the RESOLVER (`resolver/toponym-prior.ts`), which alone knows
727
+ // whether the query was bare enough to deserve it. A backend that pre-sorted by fame would apply
728
+ // it to every lookup, including the qualified addresses the D-rule guard exists to protect.
729
+ const sql =
730
+ "SELECT spr_id, name, country_id, placetype_id, latitude, longitude, min_lat, min_lon, max_lat, max_lon, neg_rank, is_primary, population" +
731
+ `${this.#importanceSelect}${this.#roleSelect} FROM candidate WHERE ${conds.join(" AND ")} ORDER BY neg_rank ASC LIMIT ?`
732
+
733
+ const fetched = allRows<CandidateRow>(this.#db.prepare(sql), ...params, Math.max(limit, RERANK_FETCH))
734
+
735
+ return rankByPrimaryPreference(fetched, limit, undefined, this.#idToPlacetype, this.#variantAliasExemption)
736
+ }
737
+
738
+ // The exact → qualifier-strip → typo-fuzzy probe cascade, run at a fixed region scope. Region scoping
739
+ // only tightens an already-population-first pick, so a region MISS re-runs the whole cascade unscoped
740
+ // (below) rather than dropping a place that has no in-region row.
741
+ const cascade = (regionID: number | undefined): Array<RankedRow<CandidateRow>> => {
742
+ let rows = probe(nameKey, regionID)
743
+
744
+ if (!rows.length) {
745
+ // Query-side qualifier-strip fallback: an OA locality with a qualifier the gazetteer's
746
+ // canonical name omits ("Lenk im Simmental" → "Lenk", "Roche VD"). Tried ONLY on an exact
747
+ // miss; the cascade's region bbox disambiguates any base-name ambiguity.
748
+ const strippedKey = normalizeLocalityForKey(stripLocalityQualifier(text))
749
+
750
+ if (strippedKey && strippedKey !== nameKey) {
751
+ // #1626: a stripped probe may answer only through a NON-PRIMARY alias key, which is a
752
+ // scrape, not a qualifier match — 'Savile Row' stripped to 'row' resolved Rhu, Scotland
753
+ // (585 km) through the village's historical-name alias. The legitimate qualifier class
754
+ // matches the place's own primary key ('Lenk im Simmental' → the Lenk row keyed 'lenk',
755
+ // is_primary=1), so refusing alias-keyed rows keeps every intended case and kills the
756
+ // scrape. The alias tier remains fully available to EXACT queries — only the stripped
757
+ // RETRY loses it, because the query's own surface never named the alias.
758
+ rows = probe(strippedKey, regionID).filter((r) => r.is_primary === 1)
759
+ }
760
+ }
761
+
762
+ // Typo-tolerant fallback (the unified gazetteer's fuzzy mode): an exact + strip miss may be a
763
+ // misspelling the normalized key can't reach. FTS5-trigram fetches a loose set; we re-rank by
764
+ // trigram-Jaccard (the admin backend's measure) and probe the best name_keys, so a typo resolves
765
+ // the same on either backend. The country/placetype/bbox/region filters still apply via `probe`.
766
+ // Skipped when the index is absent (byte-stable for an older candidate.db).
767
+ //
768
+ // Condition: only when the name doesn't exist in the gazetteer AT ALL (unfiltered). A name that exists
769
+ // but missed under the active country/placetype/bbox filter is a FILTER miss, not a spelling miss
770
+ // — fuzzing it scrapes an unrelated same-filter place ("Vienna, Austria" misrouted to IT would
771
+ // pull a tiny Italian name_key near Siena) and masks the cascade's country-agnostic retry that
772
+ // correctly lands population-first Vienna AT. The exact/strip probes already covered the real name.
773
+ //
774
+ // NEVER for postcodes: fuzzy is a typo corrector for place NAMES, and a "corrected" postcode is a
775
+ // DIFFERENT postcode. The 2026-08-05 Code-Point swap exposed the trap at scale: Northern Ireland's
776
+ // `BT3 9QQ` (absent — no permissive NI source) trigram-matched Sheffield's `S3 9QQ` (Jaccard 0.4
777
+ // on {39q, 9qq}) and resolved 200+ km wrong with full confidence. An unknown postcode must abstain.
778
+ // #1585: a locale HINT scopes the typo tier to its country. Only when no hard `country`
779
+ // filter is active (that is already narrower); a scope naming a country the table doesn't
780
+ // carry is a SCOPED-EMPTY — the fuzzy tier abstains rather than falling through worldwide.
781
+ const fuzzyCountryID =
782
+ !query.country && query.fuzzyCountry ? this.#countryToID.get(query.fuzzyCountry.toUpperCase()) : undefined
783
+
784
+ const fuzzyScopedOut = !query.country && !!query.fuzzyCountry && typeof fuzzyCountryID !== "number"
785
+
786
+ if (
787
+ !rows.length &&
788
+ !wantsPostcode &&
789
+ !fuzzyScopedOut &&
790
+ this.#ftsProbe &&
791
+ this.#nameKeyExistsProbe &&
792
+ !this.#nameKeyExistsProbe.get(nameKey)
793
+ ) {
794
+ const match = ftsTrigramQuery(nameKey)
795
+
796
+ if (match) {
797
+ const hits = allRows<{ name_key: string }>(this.#ftsProbe, match, FUZZY_FETCH)
798
+
799
+ const ranked = hits
800
+ .map((h) => ({ nk: String(h.name_key), s: wordFuzzySimilarity(nameKey, String(h.name_key)) }))
801
+ .filter((h) => h.s >= WORD_FUZZY_MIN)
802
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
803
+ .sort((a, b) => b.s - a.s)
804
+
805
+ const seen = new Set<string>()
806
+
807
+ for (const h of ranked) {
808
+ if (seen.has(h.nk)) continue
809
+ seen.add(h.nk)
810
+ // #17: stamp the tier. These rows answer a name the gazetteer does not carry, so they are
811
+ // fuzzy matches and `exactMatch` below must say so — see `RankedRow.fuzzy`.
812
+ rows.push(...probe(h.nk, regionID, fuzzyCountryID).map((r) => ({ ...r, fuzzy: true })))
813
+
814
+ if (rows.length >= limit) break
815
+ }
816
+
817
+ rows = rows.slice(0, limit)
818
+ }
819
+ }
820
+
821
+ return rows
822
+ }
823
+
824
+ let rows = cascade(regionParentID)
825
+ // #1731: whether the rows the caller receives came from the UNSCOPED fallback below — the backend's
826
+ // interior check the resolver-side trace (#1721) cannot otherwise see. Stamped onto every returned
827
+ // place, because the re-admission path is exactly where a wrong-instance namesake enters.
828
+ let regionScopeMiss = false
829
+
830
+ // Region-scope fallback: if scoping to the parent region found nothing across the whole cascade, retry
831
+ // unscoped so a place with no in-region row (missing ancestry, or a country/non-region parent) still
832
+ // resolves exactly as it does today. Only when a region scope was actually applied.
833
+ if (!rows.length && regionParentID !== undefined) {
834
+ rows = cascade(undefined)
835
+ regionScopeMiss = rows.length > 0
836
+ }
837
+
838
+ // Postcode-containment coherence (#31, Mechanism 2): re-rank the rows by proximity to the postcode's
839
+ // own centroid, so the locality that CONTAINS the postcode wins the name-match tie (the "Paris" that
840
+ // holds 75001, not the one that holds a 75001-free namesake). The resolver sends this flag on locality
841
+ // lookups when `ResolveOpts.postcodeContainmentCoherence` is on. Strictly beneath the #741 postal-city
842
+ // short-circuit above — an exact (name, postcode) hit IS the answer and outranks any re-rank — and after
843
+ // the region-scope fallback, so it sees the final row set. Rows within the radius sort by distance first;
844
+ // the out-of-radius tail keeps its original population-first order. No in-radius row, or no postcode row in
845
+ // the candidate table → unchanged (byte-identical to the flag-off path).
846
+ if (
847
+ query.postcode &&
848
+ query.postcodeContainmentCoherence === true &&
849
+ this.#wantsLocality(query.placetype) &&
850
+ rows.length > 1
851
+ ) {
852
+ const anchor = this.#postcodeAnchor(query.postcode, query.country)
853
+
854
+ if (anchor) {
855
+ const insideThreshold: Array<{ row: RankedRow<CandidateRow>; distanceKm: number }> = []
856
+ const outsideThreshold: RankedRow<CandidateRow>[] = []
857
+
858
+ for (const row of rows) {
859
+ const distanceKm = haversineKm(anchor.lat, anchor.lon, Number(row.latitude), Number(row.longitude))
860
+
861
+ if (distanceKm <= POSTCODE_CONTAINMENT_THRESHOLD_KM) {
862
+ insideThreshold.push({ row, distanceKm })
863
+ } else {
864
+ outsideThreshold.push(row)
865
+ }
866
+ }
867
+
868
+ if (insideThreshold.length) {
869
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
870
+ insideThreshold.sort((a, b) => a.distanceKm - b.distanceKm)
871
+ rows = [...insideThreshold.map(({ row }) => row), ...outsideThreshold]
872
+ }
873
+ }
874
+ }
875
+
876
+ // Admin-containment re-rank (#1717 stage 2): LAST, on the final row set — the qualifier is the
877
+ // address's outermost explicit statement, so its partition outranks the postcode-proximity order
878
+ // above (contained rows keep that order among themselves). Capability-conditioned on the sidecar
879
+ // (`#qualifierProbe`); when the artifact predates it, `regionQualifier` is ignored, no stamp is
880
+ // written, and the resolver walk reports the change `unavailable`.
881
+ if (query.regionQualifier?.trim() && this.#qualifierProbe && this.#wantsLocality(query.placetype)) {
882
+ rows = this.#applyAdminContainment(rows, query.regionQualifier.trim(), query.country, {
883
+ nameKey,
884
+ strippedKey: normalizeLocalityForKey(stripLocalityQualifier(text)),
885
+ shapeFilters,
886
+ shapeParams,
887
+ limit,
888
+ })
889
+ }
890
+
891
+ const candidates = rows.map((row): PlaceCandidate => {
892
+ const hasBbox = row.min_lat != null && row.max_lat != null && row.min_lon != null && row.max_lon != null
893
+
894
+ return {
895
+ id: Number(row.spr_id),
896
+ name: String(row.name ?? ""),
897
+ placetype: (this.#idToPlacetype.get(Number(row.placetype_id)) ?? "") as WOFPlacetype,
898
+ // Surfaced so the cascade can country-restrict a postcode by the resolved locality (an ambiguous
899
+ // international postcode like 10115 = Berlin DE AND New York US must not out-resolve the city).
900
+ country: this.#idToCountry.get(Number(row.country_id)) ?? "",
901
+ lat: Number(row.latitude),
902
+ lon: Number(row.longitude),
903
+ // `score` stays the RAW population rank (`-neg_rank`) — it feeds the resolver walk's absolute
904
+ // `minWinningScore` floor (`resolve.ts`), which must see real prominence, never a penalized value.
905
+ score: -Number(row.neg_rank),
906
+ // `prominence` carries the bounded cross-country primary preference (the effective, penalty-adjusted
907
+ // rank). The walk ORDERS candidates by `prominence ?? score` (`resolve.ts`), so this is what makes the
908
+ // re-rank actually stick through resolution — without it the walk re-sorts by raw `score` and a
909
+ // more-populous foreign alias (Changchun for "Cancun") wins back the node. Equals `score` for every
910
+ // un-penalized row (primaries + same-country aliases), so the common ordering is unchanged.
911
+ prominence: -Number(row.effectiveNegRank),
912
+ // Every candidate row IS an exact normalized-name (or alias/abbrev) match — the cascade's exact tier
913
+ // accepts alias-exact hits ("New York City" → New York) the same as canonical — EXCEPT a cross-country
914
+ // alias that lost the bounded contest to a same-key primary (`demoted`): it drops to the partial tier so
915
+ // the walk's country posterior can't cross back over the primary (see `RankedRow.demoted`) — and
916
+ // EXCEPT a row the typo-corrector produced (`fuzzy`), which by definition answers a name the
917
+ // gazetteer does not carry (see `RankedRow.fuzzy`).
918
+ exactMatch: !row.demoted && !row.fuzzy,
919
+ // #1731: emitted ONLY when a region scope was applied, missed, and the unscoped fallback
920
+ // produced this row — the re-admission path. Absence means the question never arose.
921
+ ...(regionScopeMiss ? { regionScopeMiss: true } : {}),
922
+ // #1717 stage 2 — the containment stamp, tri-state: emitted ONLY when the question was
923
+ // asked (a `regionQualifier` query over a sidecar-bearing artifact); its absence is what
924
+ // the resolver walk reports as `unavailable` (meaning-of-zero).
925
+ ...(row.containedByQualifier === undefined ? {} : { containedByQualifier: row.containedByQualifier }),
926
+ // #1893 — the exemption's firing mark, carried only when the ranker actually spared this row
927
+ // the cross-country penalty (see RankedRow.variantExempted).
928
+ ...(row.variantExempted ? { variantAliasExempted: true as const } : {}),
929
+ // The two-score split's carry (ROAD_TO_V9 §2). `referential` names the prominence this
930
+ // backend has always ordered by — `neg_rank` IS `-log10(population + 1)`, so the score and
931
+ // the sort key are two readings of the same number.
932
+ ...(row.population === null || row.population <= 0
933
+ ? {}
934
+ : { population: row.population, referential: referentialFromPopulation(row.population) }),
935
+ // #28: the fame prior, from the `importance` column the candidate build joins in. Emitted ONLY
936
+ // when the artifact measured this place — an absent field is what `rankByImportance` reads as
937
+ // "does not participate", and a 0 would be a claim nobody made (meaning-of-zero).
938
+ //
939
+ // The field name matches the column because they hold the same thing: the score source's
940
+ // BLENDED prior — the concordance's encyclopedia-derived channel where a concordance matched, a
941
+ // population-derived proxy everywhere else. It is NOT the strict `encyclopedic` channel
942
+ // `place-importance-schema.ts` defines, and it deliberately does not land in that field: the
943
+ // strict channel was measured on 2026-08-10 and covers eleven countries, none of them CA/AU/RU,
944
+ // which makes it inert on three of the four homonym contests the prior exists to settle.
945
+ // `PlaceCandidate.encyclopedic` stays reserved for a strict-channel source (the FTS backend's
946
+ // clauses are strict and today emit NULL for everything — no shipped admin DB has the split
947
+ // table at all). See `candidate-schema.ts` → {@link CandidateTable.importance}.
948
+ ...(typeof row.importance === "number" && Number.isFinite(row.importance)
949
+ ? { importance: row.importance }
950
+ : {}),
951
+ ...(hasBbox
952
+ ? {
953
+ bbox: {
954
+ minLat: Number(row.min_lat),
955
+ maxLat: Number(row.max_lat),
956
+ minLon: Number(row.min_lon),
957
+ maxLon: Number(row.max_lon),
958
+ },
959
+ }
960
+ : {}),
961
+ }
962
+ })
963
+
964
+ // Proximity re-rank (#938) — the shared implementation, so the browser byte-range twin runs the same
965
+ // code rather than the same constants. See proximity-rerank.ts for why that distinction mattered.
966
+ if (query.bias && query.bias.length) {
967
+ applyProximityRerank(candidates, query.bias)
968
+ }
969
+
970
+ return candidates
971
+ }
972
+
973
+ [Symbol.dispose](): void {
974
+ this.#resources[Symbol.dispose]()
975
+ }
976
+ }