@mailwoman/resolver-wof-sqlite 11.5.0 → 12.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/lib/address/keys/build.ts +35 -0
  2. package/lib/address/keys/lookup.ts +204 -6
  3. package/lib/address/keys/point-lookup.ts +4 -0
  4. package/lib/address/keys/schema.ts +37 -0
  5. package/lib/address/number-forms.ts +32 -13
  6. package/lib/address/point/interpolation.ts +23 -6
  7. package/lib/address/point/schema.ts +120 -2
  8. package/lib/address/point/scope-search.ts +179 -0
  9. package/lib/address/point.ts +225 -28
  10. package/lib/build/candidate.ts +222 -9
  11. package/lib/build/population-corrections.ts +11 -2
  12. package/lib/candidate/ancestors/sidecar.ts +73 -4
  13. package/lib/candidate/del1.ts +218 -0
  14. package/lib/candidate/lookup.ts +316 -113
  15. package/lib/candidate/name-roles.ts +112 -6
  16. package/lib/candidate/outcomes.ts +191 -0
  17. package/lib/candidate/schema.ts +79 -3
  18. package/lib/fst/binary-matcher.ts +9 -1
  19. package/lib/fst/builder.ts +7 -0
  20. package/lib/fst/del1-sidecar.ts +782 -0
  21. package/lib/fst/deserialize-web.ts +14 -2
  22. package/lib/fst/matcher.ts +7 -1
  23. package/lib/fst/types.ts +8 -0
  24. package/lib/fst.ts +1 -0
  25. package/lib/geonames/aliases.ts +39 -1
  26. package/lib/index.ts +22 -2
  27. package/lib/labels/street/canonical.ts +333 -0
  28. package/lib/labels/street/centroid/schema.ts +23 -1
  29. package/lib/labels/street/interpolation.ts +32 -6
  30. package/lib/labels/street/morphology/fst/builder.ts +13 -0
  31. package/lib/labels/street/morphology/fst/loader.ts +32 -2
  32. package/lib/labels/street/normalize.ts +34 -4
  33. package/lib/labels/street.ts +1 -0
  34. package/lib/landmark.ts +51 -4
  35. package/lib/lookup/types.ts +25 -6
  36. package/lib/outcome/memberships.ts +131 -0
  37. package/lib/outcome/schema.ts +147 -0
  38. package/lib/poi/lookup.ts +4 -0
  39. package/lib/poi/schema.ts +2 -1
  40. package/lib/ranking/primary-preference.ts +14 -6
  41. package/lib/schema/overture-match.ts +2 -1
  42. package/out/address/keys/build.d.ts.map +1 -1
  43. package/out/address/keys/build.js +28 -1
  44. package/out/address/keys/build.js.map +1 -1
  45. package/out/address/keys/lookup.d.ts +17 -0
  46. package/out/address/keys/lookup.d.ts.map +1 -1
  47. package/out/address/keys/lookup.js +119 -6
  48. package/out/address/keys/lookup.js.map +1 -1
  49. package/out/address/keys/point-lookup.d.ts.map +1 -1
  50. package/out/address/keys/point-lookup.js +4 -0
  51. package/out/address/keys/point-lookup.js.map +1 -1
  52. package/out/address/keys/schema.d.ts +21 -0
  53. package/out/address/keys/schema.d.ts.map +1 -1
  54. package/out/address/keys/schema.js +18 -0
  55. package/out/address/keys/schema.js.map +1 -1
  56. package/out/address/number-forms.d.ts +10 -1
  57. package/out/address/number-forms.d.ts.map +1 -1
  58. package/out/address/number-forms.js +20 -11
  59. package/out/address/number-forms.js.map +1 -1
  60. package/out/address/point/interpolation.d.ts.map +1 -1
  61. package/out/address/point/interpolation.js +15 -5
  62. package/out/address/point/interpolation.js.map +1 -1
  63. package/out/address/point/schema.d.ts +43 -2
  64. package/out/address/point/schema.d.ts.map +1 -1
  65. package/out/address/point/schema.js +73 -0
  66. package/out/address/point/schema.js.map +1 -1
  67. package/out/address/point/scope-search.d.ts +77 -0
  68. package/out/address/point/scope-search.d.ts.map +1 -0
  69. package/out/address/point/scope-search.js +107 -0
  70. package/out/address/point/scope-search.js.map +1 -0
  71. package/out/address/point.d.ts +12 -0
  72. package/out/address/point.d.ts.map +1 -1
  73. package/out/address/point.js +143 -26
  74. package/out/address/point.js.map +1 -1
  75. package/out/build/candidate.d.ts +49 -0
  76. package/out/build/candidate.d.ts.map +1 -1
  77. package/out/build/candidate.js +101 -8
  78. package/out/build/candidate.js.map +1 -1
  79. package/out/build/population-corrections.d.ts +2 -2
  80. package/out/build/population-corrections.d.ts.map +1 -1
  81. package/out/build/population-corrections.js +10 -2
  82. package/out/build/population-corrections.js.map +1 -1
  83. package/out/candidate/ancestors/sidecar.d.ts +7 -3
  84. package/out/candidate/ancestors/sidecar.d.ts.map +1 -1
  85. package/out/candidate/ancestors/sidecar.js +56 -4
  86. package/out/candidate/ancestors/sidecar.js.map +1 -1
  87. package/out/candidate/del1.d.ts +61 -0
  88. package/out/candidate/del1.d.ts.map +1 -0
  89. package/out/candidate/del1.js +158 -0
  90. package/out/candidate/del1.js.map +1 -0
  91. package/out/candidate/lookup.d.ts +16 -17
  92. package/out/candidate/lookup.d.ts.map +1 -1
  93. package/out/candidate/lookup.js +222 -92
  94. package/out/candidate/lookup.js.map +1 -1
  95. package/out/candidate/name-roles.d.ts +3 -2
  96. package/out/candidate/name-roles.d.ts.map +1 -1
  97. package/out/candidate/name-roles.js +75 -5
  98. package/out/candidate/name-roles.js.map +1 -1
  99. package/out/candidate/outcomes.d.ts +57 -0
  100. package/out/candidate/outcomes.d.ts.map +1 -0
  101. package/out/candidate/outcomes.js +109 -0
  102. package/out/candidate/outcomes.js.map +1 -0
  103. package/out/candidate/schema.d.ts +51 -3
  104. package/out/candidate/schema.d.ts.map +1 -1
  105. package/out/candidate/schema.js +40 -0
  106. package/out/candidate/schema.js.map +1 -1
  107. package/out/fst/binary-matcher.d.ts +7 -1
  108. package/out/fst/binary-matcher.d.ts.map +1 -1
  109. package/out/fst/binary-matcher.js +7 -1
  110. package/out/fst/binary-matcher.js.map +1 -1
  111. package/out/fst/builder.d.ts +2 -0
  112. package/out/fst/builder.d.ts.map +1 -1
  113. package/out/fst/builder.js +5 -0
  114. package/out/fst/builder.js.map +1 -1
  115. package/out/fst/del1-sidecar.d.ts +158 -0
  116. package/out/fst/del1-sidecar.d.ts.map +1 -0
  117. package/out/fst/del1-sidecar.js +581 -0
  118. package/out/fst/del1-sidecar.js.map +1 -0
  119. package/out/fst/deserialize-web.d.ts +3 -1
  120. package/out/fst/deserialize-web.d.ts.map +1 -1
  121. package/out/fst/deserialize-web.js +9 -2
  122. package/out/fst/deserialize-web.js.map +1 -1
  123. package/out/fst/matcher.d.ts +6 -1
  124. package/out/fst/matcher.d.ts.map +1 -1
  125. package/out/fst/matcher.js +6 -1
  126. package/out/fst/matcher.js.map +1 -1
  127. package/out/fst/types.d.ts +7 -0
  128. package/out/fst/types.d.ts.map +1 -1
  129. package/out/fst.d.ts +1 -0
  130. package/out/fst.d.ts.map +1 -1
  131. package/out/fst.js +1 -0
  132. package/out/fst.js.map +1 -1
  133. package/out/geonames/aliases.d.ts +10 -0
  134. package/out/geonames/aliases.d.ts.map +1 -1
  135. package/out/geonames/aliases.js +33 -1
  136. package/out/geonames/aliases.js.map +1 -1
  137. package/out/index.d.ts +4 -3
  138. package/out/index.d.ts.map +1 -1
  139. package/out/index.js +3 -2
  140. package/out/index.js.map +1 -1
  141. package/out/labels/street/canonical.d.ts +68 -0
  142. package/out/labels/street/canonical.d.ts.map +1 -0
  143. package/out/labels/street/canonical.js +234 -0
  144. package/out/labels/street/canonical.js.map +1 -0
  145. package/out/labels/street/centroid/schema.d.ts +10 -1
  146. package/out/labels/street/centroid/schema.d.ts.map +1 -1
  147. package/out/labels/street/centroid/schema.js +12 -0
  148. package/out/labels/street/centroid/schema.js.map +1 -1
  149. package/out/labels/street/interpolation.d.ts +9 -1
  150. package/out/labels/street/interpolation.d.ts.map +1 -1
  151. package/out/labels/street/interpolation.js +8 -5
  152. package/out/labels/street/interpolation.js.map +1 -1
  153. package/out/labels/street/morphology/fst/builder.d.ts +8 -0
  154. package/out/labels/street/morphology/fst/builder.d.ts.map +1 -1
  155. package/out/labels/street/morphology/fst/builder.js +5 -0
  156. package/out/labels/street/morphology/fst/builder.js.map +1 -1
  157. package/out/labels/street/morphology/fst/loader.d.ts +12 -0
  158. package/out/labels/street/morphology/fst/loader.d.ts.map +1 -1
  159. package/out/labels/street/morphology/fst/loader.js +18 -2
  160. package/out/labels/street/morphology/fst/loader.js.map +1 -1
  161. package/out/labels/street/normalize.d.ts +8 -0
  162. package/out/labels/street/normalize.d.ts.map +1 -1
  163. package/out/labels/street/normalize.js +24 -4
  164. package/out/labels/street/normalize.js.map +1 -1
  165. package/out/labels/street.d.ts +1 -0
  166. package/out/labels/street.d.ts.map +1 -1
  167. package/out/labels/street.js +1 -0
  168. package/out/labels/street.js.map +1 -1
  169. package/out/landmark.d.ts +15 -3
  170. package/out/landmark.d.ts.map +1 -1
  171. package/out/landmark.js +38 -3
  172. package/out/landmark.js.map +1 -1
  173. package/out/lookup/types.d.ts +21 -5
  174. package/out/lookup/types.d.ts.map +1 -1
  175. package/out/outcome/memberships.d.ts +58 -0
  176. package/out/outcome/memberships.d.ts.map +1 -0
  177. package/out/outcome/memberships.js +83 -0
  178. package/out/outcome/memberships.js.map +1 -0
  179. package/out/outcome/schema.d.ts +74 -0
  180. package/out/outcome/schema.d.ts.map +1 -0
  181. package/out/outcome/schema.js +63 -0
  182. package/out/outcome/schema.js.map +1 -0
  183. package/out/poi/lookup.d.ts +4 -0
  184. package/out/poi/lookup.d.ts.map +1 -1
  185. package/out/poi/lookup.js.map +1 -1
  186. package/out/poi/schema.d.ts +2 -1
  187. package/out/poi/schema.d.ts.map +1 -1
  188. package/out/poi/schema.js.map +1 -1
  189. package/out/ranking/primary-preference.d.ts +9 -5
  190. package/out/ranking/primary-preference.d.ts.map +1 -1
  191. package/out/ranking/primary-preference.js +11 -3
  192. package/out/ranking/primary-preference.js.map +1 -1
  193. package/out/schema/overture-match.d.ts +2 -1
  194. package/out/schema/overture-match.d.ts.map +1 -1
  195. package/out/schema/overture-match.js.map +1 -1
  196. package/package.json +15 -15
@@ -2,17 +2,16 @@
2
2
  // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
3
 
4
4
  import { expandPlacetypeFilter } from "@mailwoman/codex/labels/placetype-map"
5
- import type { VariantAliasExemption } from "@mailwoman/core/geocode"
6
5
  import {
7
6
  type Ancestor,
8
7
  type GazetteerArtifactCoverage,
9
8
  populationScoreUnmeasured,
10
9
  referentialFromPopulation,
11
10
  } from "@mailwoman/core/resolver"
11
+ import { refuseMissingOutcomeTables } from "@mailwoman/core/resolver/outcome"
12
12
  import { allRows } from "@mailwoman/core/utils"
13
13
  import { jaroWinkler, levenshteinSimilarity } from "@mailwoman/match/comparators"
14
14
  import { partitionByContainment } from "@mailwoman/resolver"
15
- import { haversine } from "@mailwoman/spatial/geometries/point/distance"
16
15
  import type { DatabaseClient } from "@mailwoman/sqlite/client"
17
16
  import { SQLiteLookup, type SQLiteLookupOptions } from "@mailwoman/sqlite/lookup"
18
17
 
@@ -24,9 +23,22 @@ import {
24
23
  type IntervalLabel,
25
24
  } from "#candidate/ancestors/schema"
26
25
  import { readGazetteerCoverageManifest } from "#candidate/coverage-manifest"
26
+ import {
27
+ CANDIDATE_DEL1_MAX_LENGTH,
28
+ CANDIDATE_DEL1_TABLE,
29
+ del1Keys,
30
+ firstCodePoint,
31
+ isWithinOneEdit,
32
+ } from "#candidate/del1"
27
33
  import { CANDIDATE_FTS_TABLE } from "#candidate/fts"
28
34
  import { candidateQueryKeyFold } from "#candidate/key-fold"
29
- import type { CandidateDatabase, CandidateTable, CountryCodeTable, PlacetypeCodeTable } from "#candidate/schema"
35
+ import {
36
+ CANDIDATE_SITELINKS_TABLE,
37
+ type CandidateDatabase,
38
+ type CandidateTable,
39
+ type CountryCodeTable,
40
+ type PlacetypeCodeTable,
41
+ } from "#candidate/schema"
30
42
  import {
31
43
  POSTAL_CITY_CANDIDATE_TABLE,
32
44
  type PostalCityCandidateTable,
@@ -34,25 +46,15 @@ import {
34
46
  import { REGION_CLASS_PLACETYPES, regionQualifierProbeKeys } from "#labels/region"
35
47
  import { type NameKey, normalizeLocalityForKey, stripLocalityQualifier } from "#labels/street/normalize"
36
48
  import type { FindPlaceQuery, PlaceCandidate, PlaceLookup, WOFPlacetype } from "#lookup/types"
49
+ import { missingOutcomeTablesIn, OutcomeMembershipReader, outcomeAdmitPredicate } from "#outcome/memberships"
37
50
  import { rankByPrimaryPreference, type RankedRow, regionAliasMargin, RERANK_FETCH } from "#ranking/primary-preference"
38
51
  import { applyProximityRerank } from "#ranking/proximity-rerank"
39
52
  import { hasColumn, hasTable } from "#sqlite-utils"
40
53
 
41
54
  /**
42
- * Where a {@link WOFCandidateTableLookup} reads from
43
- * (a read-only `candidate.db` or a caller-held connection) and how it ranks.
55
+ * Database path or caller-held connection for {@link WOFCandidateTableLookup}.
44
56
  */
45
- export interface WOFCandidateTableLookupOpts extends SQLiteLookupOptions<CandidateDatabase> {
46
- /**
47
- * Exempt `name_role = 'variant'` aliases from the cross-country primary-preference penalty.
48
- *
49
- * - No-ops without the role column.
50
- * - `"not_applied"` penalizes variant aliases like any other.
51
- *
52
- * @defaultValue `"applied"`.
53
- */
54
- variantAliasExemption?: VariantAliasExemption
55
- }
57
+ export type WOFCandidateTableLookupOpts = SQLiteLookupOptions<CandidateDatabase>
56
58
 
57
59
  type CandidateRow = Pick<
58
60
  CandidateTable,
@@ -70,8 +72,8 @@ type CandidateRow = Pick<
70
72
  | "is_primary"
71
73
  | "population"
72
74
  > &
73
- // Optional because older artifacts may not include `importance`.
74
- Partial<Pick<CandidateTable, "importance">>
75
+ // Optional because older artifacts may not include `importance` or `name_role`.
76
+ Partial<Pick<CandidateTable, "importance" | "name_role">>
75
77
 
76
78
  /**
77
79
  * What a containment re-rank needs beside the rows: the keys to inject contained
@@ -83,17 +85,30 @@ interface ContainmentOptions {
83
85
  shapeFilters: string[]
84
86
  shapeParams: Array<string | number>
85
87
  limit: number
88
+ /**
89
+ * The outcome filter's predicate, also among `shapeFilters`, for the injections
90
+ * that skip the shape filters.
91
+ */
92
+ outcomeFilter: { sql: string; params: number[] } | null
86
93
  }
87
94
 
88
95
  const FUZZY_FETCH = 40
89
96
 
97
+ const DEL1_MAX_MATCHED_KEYS = 128
98
+
90
99
  const WORD_FUZZY_MIN = 0.85
91
100
 
92
101
  function wordFuzzySimilarity(a: string, b: string): number {
93
102
  return Math.max(jaroWinkler(a, b), levenshteinSimilarity(a, b))
94
103
  }
95
104
 
96
- const POSTCODE_CONTAINMENT_THRESHOLD_KM = 25
105
+ /**
106
+ * The number of words in a folded name key.
107
+ * A folded key separates its words with single spaces.
108
+ */
109
+ function wordCount(key: string): number {
110
+ return key ? key.split(" ").length : 0
111
+ }
97
112
 
98
113
  function ftsTrigramQuery(s: string): string {
99
114
  const grams = new Set<string>()
@@ -109,6 +124,14 @@ function ftsTrigramQuery(s: string): string {
109
124
  return [...grams].map((g) => `"${g}"`).join(" OR ")
110
125
  }
111
126
 
127
+ /**
128
+ * A {@link PlaceCandidate} extended with cross-layer sitelink prominence
129
+ * when the artifact includes `candidate_sitelinks`.
130
+ */
131
+ export type CandidatePlace = PlaceCandidate & {
132
+ sitelinkProminence?: number | null
133
+ }
134
+
112
135
  /**
113
136
  * Node {@link PlaceLookup} over `candidate.db`.
114
137
  */
@@ -120,6 +143,8 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
120
143
 
121
144
  readonly #postalCityProbe: ReturnType<DatabaseClient["prepare"]> | undefined
122
145
 
146
+ readonly #hasDel1Table: boolean
147
+ readonly #del1Probes = new Map<number, ReturnType<DatabaseClient["prepare"]>>()
123
148
  readonly #ftsProbe: ReturnType<DatabaseClient["prepare"]> | undefined
124
149
  /**
125
150
  * Prepared unfiltered `name_key` existence probe, so fuzzy fallback runs only for true name misses.
@@ -131,7 +156,6 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
131
156
  readonly #importanceSelect: string
132
157
 
133
158
  readonly #hasNameRole: boolean
134
- readonly #variantAliasExemption: boolean
135
159
 
136
160
  readonly #roleSelect: string
137
161
 
@@ -144,6 +168,11 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
144
168
  readonly #qualifierProbe: ReturnType<DatabaseClient["prepare"]> | undefined
145
169
 
146
170
  #placeProbe: ReturnType<DatabaseClient["prepare"]> | undefined
171
+
172
+ readonly #missingOutcomeTables: readonly string[]
173
+ readonly #outcomes: OutcomeMembershipReader | null
174
+ readonly #wikidataProbe: ReturnType<DatabaseClient["prepare"]> | undefined
175
+ readonly #sitelinkProbe: ReturnType<DatabaseClient["prepare"]> | undefined
147
176
  /**
148
177
  * The folds the artifact recorded for its `name_key` column, applied to every query key.
149
178
  */
@@ -175,18 +204,21 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
175
204
  )
176
205
  }
177
206
 
207
+ this.#hasDel1Table = hasTable(this.database, CANDIDATE_DEL1_TABLE)
208
+
178
209
  if (hasTable(this.database, CANDIDATE_FTS_TABLE)) {
179
210
  this.#ftsProbe = this.database.prepare(
180
211
  `SELECT name_key FROM ${CANDIDATE_FTS_TABLE} WHERE ${CANDIDATE_FTS_TABLE} MATCH ? ORDER BY bm25(${CANDIDATE_FTS_TABLE}) LIMIT ?`
181
212
  )
213
+ }
182
214
 
215
+ if (this.#hasDel1Table || this.#ftsProbe) {
183
216
  this.#nameKeyExistsProbe = this.database.prepare("SELECT 1 FROM candidate WHERE name_key = ? LIMIT 1")
184
217
  }
185
218
 
186
219
  // Optional columns are detected once here for hot-path reads.
187
220
  this.#importanceSelect = hasColumn(this.database, "candidate", "importance") ? ", importance" : ""
188
221
  this.#hasNameRole = hasColumn(this.database, "candidate", "name_role")
189
- this.#variantAliasExemption = (opts.variantAliasExemption ?? "applied") === "applied"
190
222
  this.#roleSelect = this.#hasNameRole ? ", name_role" : ""
191
223
 
192
224
  if (hasTable(this.database, CANDIDATE_ANCESTOR_TABLE)) {
@@ -213,6 +245,69 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
213
245
  }
214
246
 
215
247
  this.artifactCoverage = readGazetteerCoverageManifest(this.database)
248
+
249
+ this.#missingOutcomeTables = missingOutcomeTablesIn(this.database)
250
+ this.#outcomes = OutcomeMembershipReader.open(this.database, { recordColumn: "spr_id", layer: "candidate" })
251
+
252
+ // The unified build's `concordances` table holds each record's `wd:id`.
253
+ if (hasTable(this.database, "concordances")) {
254
+ this.#wikidataProbe = this.database.prepare(
255
+ "SELECT other_id FROM concordances WHERE id = ? AND other_source = 'wd:id' LIMIT 1"
256
+ )
257
+ }
258
+
259
+ if (hasTable(this.database, CANDIDATE_SITELINKS_TABLE)) {
260
+ this.#sitelinkProbe = this.database.prepare(
261
+ `SELECT sitelinks FROM ${CANDIDATE_SITELINKS_TABLE} WHERE spr_id = ? LIMIT 1`
262
+ )
263
+ }
264
+ }
265
+
266
+ /**
267
+ * The outcome tables the artifact lacks, empty when it holds them all.
268
+ */
269
+ missingOutcomeTables(): readonly string[] {
270
+ return this.#missingOutcomeTables
271
+ }
272
+
273
+ /**
274
+ * The fetch predicate of a query's outcome filter, or null when the query sets none.
275
+ *
276
+ * @throws {OutcomeRequestError} When the artifact predates the outcome tables.
277
+ */
278
+ #outcomeFilter(query: FindPlaceQuery): { sql: string; params: number[] } | null {
279
+ if (!query.outcome) return null
280
+
281
+ refuseMissingOutcomeTables("candidate.db", this.#missingOutcomeTables)
282
+
283
+ if (!query.outcome.admit) return null
284
+
285
+ return outcomeAdmitPredicate(
286
+ query.outcome.admit,
287
+ "spr_id",
288
+ "candidate.spr_id",
289
+ "(SELECT pc.placetype FROM placetype_codes pc WHERE pc.id = candidate.placetype_id)"
290
+ )
291
+ }
292
+
293
+ /**
294
+ * The record's Wikidata item, or null when the artifact records none.
295
+ */
296
+ #wikidataOf(sprID: number): string | null {
297
+ const row = this.#wikidataProbe?.get(sprID) as { other_id: string } | undefined
298
+
299
+ return row ? String(row.other_id) : null
300
+ }
301
+
302
+ /**
303
+ * Cross-layer prominence `log10(sitelinks + 1)` from `candidate_sitelinks`, or null when unrecorded.
304
+ */
305
+ #sitelinkProminenceOf(sprID: number): number | null {
306
+ const row = this.#sitelinkProbe?.get(sprID) as { sitelinks: number } | undefined
307
+
308
+ return row && typeof row.sitelinks === "number" && Number.isFinite(row.sitelinks)
309
+ ? Math.log10(row.sitelinks + 1)
310
+ : null
216
311
  }
217
312
 
218
313
  #ancestorLineage(id: number | string): Ancestor[] {
@@ -326,6 +421,13 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
326
421
 
327
422
  for (const row of rows) {
328
423
  row.containedByQualifier = contained(Number(row.spr_id))
424
+
425
+ // A foreign-script namesake contained by the query's stated qualifier
426
+ // (`Москва, Айдахо`, `בית לחם, פנסילבניה`) re-enters the exact tier
427
+ // so `partitionByContainment` places it ahead of uncontained home-script candidates.
428
+ if (row.containedByQualifier && row.name_role === "foreign-script" && row.demoted) {
429
+ row.demoted = false
430
+ }
329
431
  }
330
432
 
331
433
  const present = new Set(rows.map((row) => Number(row.spr_id)))
@@ -333,7 +435,7 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
333
435
 
334
436
  const injectSQL = (primaryOnly: boolean): string =>
335
437
  "SELECT spr_id, name, country_id, placetype_id, latitude, longitude, min_lat, min_lon, max_lat, max_lon, neg_rank, is_primary, population" +
336
- `${this.#importanceSelect} FROM candidate WHERE ${["name_key = ?", ...opts.shapeFilters, ...(primaryOnly ? ["is_primary = 1"] : [])].join(" AND ")} ` +
438
+ `${this.#importanceSelect}${this.#roleSelect} FROM candidate WHERE ${["name_key = ?", ...opts.shapeFilters, ...(primaryOnly ? ["is_primary = 1"] : [])].join(" AND ")} ` +
337
439
  "ORDER BY neg_rank ASC LIMIT ?"
338
440
 
339
441
  const injectFrom = (key: string, primaryOnly: boolean): void => {
@@ -356,23 +458,39 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
356
458
 
357
459
  injectFrom(opts.nameKey, false)
358
460
 
359
- // Also inject contained neighborhood-band namesakes (primary-keyed only).
461
+ // Also inject contained neighborhood-band namesakes keyed by the primary name
462
+ // or by an `abbr` alias whose word count equals the primary name's.
463
+ // Such an alias respells the name, as `Mount Tabor` does `Mt. Tabor`.
464
+ // An alias with fewer words drops one, as `Camden` does `Camden Town`, and is the
465
+ // exact name of a larger place, the borough of Camden, so it stays out.
360
466
  const bandIDs = ["neighbourhood", "macrohood", "microhood"]
361
467
  .map((placetype) => this.#placetypeToID.get(placetype))
362
468
  .filter((id) => typeof id === "number")
363
469
 
364
470
  if (bandIDs.length) {
471
+ const bandNames = this.#hasNameRole ? "(is_primary = 1 OR name_role = 'abbr')" : "is_primary = 1"
472
+
365
473
  const bandSQL =
366
474
  "SELECT spr_id, name, country_id, placetype_id, latitude, longitude, min_lat, min_lon, max_lat, max_lon, neg_rank, is_primary, population" +
367
- `${this.#importanceSelect} FROM candidate WHERE name_key = ? AND placetype_id IN (${bandIDs.map(() => "?").join(",")}) AND is_primary = 1 ` +
368
- "ORDER BY neg_rank ASC LIMIT ?"
475
+ `${this.#importanceSelect}${this.#roleSelect} FROM candidate WHERE name_key = ? AND placetype_id IN (${bandIDs.map(() => "?").join(",")}) AND ${bandNames} ` +
476
+ `${opts.outcomeFilter ? `AND ${opts.outcomeFilter.sql} ` : ""}ORDER BY neg_rank ASC LIMIT ?`
369
477
 
370
- const fetched = allRows<CandidateRow>(this.database.prepare(bandSQL), opts.nameKey, ...bandIDs, RERANK_FETCH)
478
+ const fetched = allRows<CandidateRow>(
479
+ this.database.prepare(bandSQL),
480
+ opts.nameKey,
481
+ ...bandIDs,
482
+ ...(opts.outcomeFilter?.params ?? []),
483
+ RERANK_FETCH
484
+ )
485
+
486
+ const queryWords = wordCount(opts.nameKey)
371
487
 
372
488
  for (const row of fetched) {
373
489
  const sprID = Number(row.spr_id)
374
490
 
375
491
  if (present.has(sprID) || !contained(sprID)) continue
492
+
493
+ if (!row.is_primary && (!row.name || wordCount(normalizeLocalityForKey(row.name)) !== queryWords)) continue
376
494
  present.add(sprID)
377
495
 
378
496
  injected.push({ ...row, effectiveNegRank: row.neg_rank, demoted: false, containedByQualifier: true })
@@ -405,32 +523,56 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
405
523
  return expandPlacetypeFilter(want as readonly string[]).includes("locality")
406
524
  }
407
525
 
408
- #postcodeAnchor(postcode: string, country?: string): { lat: number; lon: number } | null {
409
- const placetypeID = this.#placetypeToID.get("postalcode")
526
+ #del1MatchedNameKeys(nameKey: NameKey, hasCountryEvidence: boolean): string[] {
527
+ if (!this.#hasDel1Table) return []
528
+
529
+ const queryDelKeys = del1Keys(nameKey, CANDIDATE_DEL1_MAX_LENGTH + 1)
530
+
531
+ if (!queryDelKeys.length) return []
532
+
533
+ let stmt = this.#del1Probes.get(queryDelKeys.length)
534
+
535
+ if (!stmt) {
536
+ const placeholders = queryDelKeys.map(() => "?").join(",")
537
+
538
+ stmt = this.database.prepare(
539
+ `SELECT DISTINCT name_key FROM ${CANDIDATE_DEL1_TABLE} WHERE del_key IN (${placeholders})`
540
+ )
541
+
542
+ this.#del1Probes.set(queryDelKeys.length, stmt)
543
+ }
544
+
545
+ const hits = allRows<{ name_key: string }>(stmt, ...queryDelKeys)
546
+ const queryFirst = firstCodePoint(nameKey)
547
+ const matched = new Set<string>()
410
548
 
411
- if (typeof placetypeID !== "number") return null
549
+ for (const hit of hits) {
550
+ const nk = this.#queryKeyFold(String(hit.name_key) as NameKey)
412
551
 
413
- const conds = ["name_key = ?", "placetype_id = ?"]
414
- const params: Array<string | number> = [postcode.replaceAll(/\s+/g, ""), placetypeID]
552
+ if (nk === nameKey || matched.has(nk)) continue
415
553
 
416
- if (country) {
417
- const countryID = this.#countryToID.get(country.toUpperCase())
554
+ if (!isWithinOneEdit(nameKey, nk)) continue
418
555
 
419
- if (typeof countryID !== "number") return null // Unknown country in this artifact.
420
- conds.push("country_id = ?")
421
- params.push(countryID)
556
+ if (!hasCountryEvidence && firstCodePoint(nk) !== queryFirst) continue
557
+
558
+ matched.add(nk)
422
559
  }
423
560
 
424
- const row = this.database
425
- .prepare(`SELECT latitude, longitude FROM candidate WHERE ${conds.join(" AND ")} ORDER BY neg_rank ASC LIMIT 1`)
426
- .get(...params) as { latitude: number; longitude: number } | undefined
561
+ const keys = [...matched]
427
562
 
428
- if (!row || (Number(row.latitude) === 0 && Number(row.longitude) === 0)) return null
563
+ if (keys.length <= DEL1_MAX_MATCHED_KEYS) return keys
429
564
 
430
- return { lat: Number(row.latitude), lon: Number(row.longitude) }
565
+ return (
566
+ keys
567
+ .map((nk) => ({ nk, s: wordFuzzySimilarity(nameKey, nk) }))
568
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array on a hot path
569
+ .sort((a, b) => b.s - a.s)
570
+ .slice(0, DEL1_MAX_MATCHED_KEYS)
571
+ .map((h) => h.nk)
572
+ )
431
573
  }
432
574
 
433
- async findPlace(query: FindPlaceQuery): Promise<PlaceCandidate[]> {
575
+ async findPlace(query: FindPlaceQuery): Promise<CandidatePlace[]> {
434
576
  let text = (query.text ?? "").trim()
435
577
 
436
578
  if (!text) return []
@@ -447,7 +589,8 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
447
589
 
448
590
  if (!nameKey) return []
449
591
 
450
- if (query.postcode && this.#postalCityProbe && this.#wantsLocality(query.placetype)) {
592
+ // The postal-city probe reads no outcome tables, so an outcome query skips it.
593
+ if (query.postcode && !query.outcome && this.#postalCityProbe && this.#wantsLocality(query.placetype)) {
451
594
  const hit = this.#postalCityProbe.get(nameKey, query.postcode.trim()) as
452
595
  | Pick<PostalCityCandidateTable, "spr_id" | "name" | "latitude" | "longitude">
453
596
  | undefined
@@ -526,6 +669,14 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
526
669
  shapeParams.push(...query.excludeNameRoles)
527
670
  }
528
671
 
672
+ // The outcome filter is a predicate of the fetch, so a matching row is never lost to the row limit.
673
+ const outcomeFilter = this.#outcomeFilter(query)
674
+
675
+ if (outcomeFilter) {
676
+ shapeFilters.push(outcomeFilter.sql)
677
+ shapeParams.push(...outcomeFilter.params)
678
+ }
679
+
529
680
  filters.push(...shapeFilters)
530
681
  filterParams.push(...shapeParams)
531
682
 
@@ -556,10 +707,58 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
556
707
  // Inside a stated region, an alias yields to a different place whose primary name equals
557
708
  // the query, including an own-name variant the exemption spares from the worldwide penalty.
558
709
  return regionID === null
559
- ? rankByPrimaryPreference(fetched, limit, undefined, this.#idToPlacetype, this.#variantAliasExemption)
710
+ ? rankByPrimaryPreference(fetched, limit, undefined, this.#idToPlacetype, true)
560
711
  : rankByPrimaryPreference(fetched, limit, regionAliasMargin, this.#idToPlacetype)
561
712
  }
562
713
 
714
+ const probeKeys = (
715
+ keys: readonly string[],
716
+ regionID: number | null,
717
+ countryID?: number
718
+ ): Array<RankedRow<CandidateRow>> => {
719
+ if (!keys.length) return []
720
+
721
+ if (keys.length === 1) return probe(keys[0]!, regionID, countryID)
722
+
723
+ const conds = [`name_key IN (${keys.map(() => "?").join(",")})`, ...filters]
724
+ const params: Array<string | number> = [...keys, ...filterParams]
725
+
726
+ if (regionID !== null) {
727
+ conds.push("region_id = ?")
728
+ params.push(regionID)
729
+ }
730
+
731
+ if (typeof countryID === "number") {
732
+ conds.push("country_id = ?")
733
+ params.push(countryID)
734
+ }
735
+
736
+ const sql =
737
+ "SELECT spr_id, name, country_id, placetype_id, latitude, longitude, min_lat, min_lon, max_lat, max_lon, neg_rank, is_primary, population" +
738
+ `${this.#importanceSelect}${this.#roleSelect} FROM candidate WHERE ${conds.join(" AND ")} ORDER BY neg_rank ASC LIMIT ?`
739
+
740
+ const fetched = allRows<CandidateRow>(this.database.prepare(sql), ...params, Math.max(limit, RERANK_FETCH))
741
+
742
+ // A place can appear under multiple 1-edit keys (such as primary and alias).
743
+ // Keep its best row per spr_id.
744
+ const bySPR = new Map<number, CandidateRow>()
745
+
746
+ for (const row of fetched) {
747
+ const sprID = Number(row.spr_id)
748
+ const prev = bySPR.get(sprID)
749
+
750
+ if (!prev || (prev.is_primary !== 1 && row.is_primary === 1)) {
751
+ bySPR.set(sprID, row)
752
+ }
753
+ }
754
+
755
+ const deduped = [...bySPR.values()]
756
+
757
+ return regionID === null
758
+ ? rankByPrimaryPreference(deduped, limit, undefined, this.#idToPlacetype, true)
759
+ : rankByPrimaryPreference(deduped, limit, regionAliasMargin, this.#idToPlacetype)
760
+ }
761
+
563
762
  const cascade = (regionID: number | null): Array<RankedRow<CandidateRow>> => {
564
763
  let rows = probe(nameKey, regionID)
565
764
 
@@ -581,35 +780,45 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
581
780
  !rows.length &&
582
781
  !wantsPostcode &&
583
782
  !(query.fuzzyCountry && !query.country && typeof fuzzyCountryID !== "number") &&
584
- this.#ftsProbe &&
585
- this.#nameKeyExistsProbe &&
783
+ (this.#hasDel1Table || this.#ftsProbe != null) &&
784
+ this.#nameKeyExistsProbe != null &&
586
785
  !this.#nameKeyExistsProbe.get(nameKey)
587
786
  ) {
588
- const match = ftsTrigramQuery(nameKey)
787
+ if (this.#hasDel1Table) {
788
+ const matchedKeys = this.#del1MatchedNameKeys(nameKey, hasCountryEvidence)
789
+
790
+ if (matchedKeys.length) {
791
+ rows = probeKeys(matchedKeys, regionID, fuzzyCountryID).map((r) => ({ ...r, fuzzy: true }))
792
+ }
793
+ }
589
794
 
590
- if (match) {
591
- const hits = allRows<{ name_key: string }>(this.#ftsProbe, match, FUZZY_FETCH)
795
+ if (!rows.length && this.#ftsProbe) {
796
+ const match = ftsTrigramQuery(nameKey)
592
797
 
593
- const ranked = hits
594
- // An index built before the artifact's key folds holds unfolded keys, so each hit is folded too.
595
- .map((h) => this.#queryKeyFold(String(h.name_key) as NameKey))
596
- .map((nk) => ({ nk, s: wordFuzzySimilarity(nameKey, nk) }))
597
- .filter((h) => h.s >= WORD_FUZZY_MIN && (hasCountryEvidence || h.nk[0] === nameKey[0]))
598
- // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
599
- .sort((a, b) => b.s - a.s)
798
+ if (match) {
799
+ const hits = allRows<{ name_key: string }>(this.#ftsProbe, match, FUZZY_FETCH)
600
800
 
601
- const seen = new Set<string>()
801
+ const ranked = hits
802
+ // An index built before the artifact's key folds holds unfolded keys, so each hit is folded too.
803
+ .map((h) => this.#queryKeyFold(String(h.name_key) as NameKey))
804
+ .map((nk) => ({ nk, s: wordFuzzySimilarity(nameKey, nk) }))
805
+ .filter((h) => h.s >= WORD_FUZZY_MIN && (hasCountryEvidence || h.nk[0] === nameKey[0]))
806
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
807
+ .sort((a, b) => b.s - a.s)
602
808
 
603
- for (const h of ranked) {
604
- if (seen.has(h.nk)) continue
605
- seen.add(h.nk)
809
+ const seen = new Set<string>()
606
810
 
607
- rows.push(...probe(h.nk, regionID, fuzzyCountryID).map((r) => ({ ...r, fuzzy: true })))
811
+ for (const h of ranked) {
812
+ if (seen.has(h.nk)) continue
813
+ seen.add(h.nk)
608
814
 
609
- if (rows.length >= limit) break
610
- }
815
+ rows.push(...probe(h.nk, regionID, fuzzyCountryID).map((r) => ({ ...r, fuzzy: true })))
816
+
817
+ if (rows.length >= limit) break
818
+ }
611
819
 
612
- rows = rows.slice(0, limit)
820
+ rows = rows.slice(0, limit)
821
+ }
613
822
  }
614
823
  }
615
824
 
@@ -625,58 +834,45 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
625
834
  regionScopeMiss = rows.length > 0
626
835
  }
627
836
 
628
- if (
629
- query.postcode &&
630
- query.postcodeContainmentCoherence === true &&
631
- this.#wantsLocality(query.placetype) &&
632
- rows.length > 1
633
- ) {
634
- const anchor = this.#postcodeAnchor(query.postcode, query.country)
635
-
636
- if (anchor) {
637
- const insideThreshold: Array<{ row: RankedRow<CandidateRow>; distanceKm: number }> = []
638
- const outsideThreshold: RankedRow<CandidateRow>[] = []
639
-
640
- for (const row of rows) {
641
- const distanceKm = haversine(anchor.lat, anchor.lon, Number(row.latitude), Number(row.longitude))
837
+ // Admin-containment re-rank runs last.
838
+ // Test the more specific resolved parent id before falling back to the region qualifier's name.
839
+ if (this.#wantsLocality(query.placetype)) {
840
+ const containmentOptions: ContainmentOptions = {
841
+ nameKey,
842
+ strippedKey: strippedNameKey,
843
+ shapeFilters,
844
+ shapeParams,
845
+ limit,
846
+ outcomeFilter,
847
+ }
642
848
 
643
- if (distanceKm <= POSTCODE_CONTAINMENT_THRESHOLD_KM) {
644
- insideThreshold.push({ row, distanceKm })
645
- } else {
646
- outsideThreshold.push(row)
647
- }
648
- }
849
+ let parentMatched = false
649
850
 
650
- if (insideThreshold.length) {
651
- // oxlint-disable-next-line unicorn/no-array-sort -- hot-path in-place sort
652
- insideThreshold.sort((a, b) => a.distanceKm - b.distanceKm)
653
- rows = [...insideThreshold.map(({ row }) => row), ...outsideThreshold]
654
- }
851
+ if (typeof query.parentQualifierID === "number" && this.#ancestorsProbe) {
852
+ // A resolved parent qualifies by id, so no name probe runs.
853
+ rows = this.#applyContainment(rows, new Set([query.parentQualifierID]), containmentOptions)
854
+ parentMatched = rows.some((row) => row.containedByQualifier === true)
655
855
  }
656
- }
657
856
 
658
- // Admin-containment re-rank runs last.
659
- const containmentOptions: ContainmentOptions = {
660
- nameKey,
661
- strippedKey: strippedNameKey,
662
- shapeFilters,
663
- shapeParams,
664
- limit,
665
- }
666
-
667
- if (query.regionQualifier?.trim() && this.#qualifierProbe && this.#wantsLocality(query.placetype)) {
668
- rows = this.#applyAdminContainment(rows, query.regionQualifier.trim(), query.country ?? null, containmentOptions)
669
- } else if (
670
- typeof query.parentQualifierID === "number" &&
671
- this.#ancestorsProbe &&
672
- this.#wantsLocality(query.placetype)
673
- ) {
674
- // A resolved parent qualifies by id, so no name probe runs (#2804).
675
- rows = this.#applyContainment(rows, new Set([query.parentQualifierID]), containmentOptions)
857
+ if (!parentMatched && query.regionQualifier?.trim() && this.#qualifierProbe) {
858
+ rows = this.#applyAdminContainment(
859
+ rows,
860
+ query.regionQualifier.trim(),
861
+ query.country ?? null,
862
+ containmentOptions
863
+ )
864
+ }
676
865
  }
677
866
 
678
867
  const candidates = rows.map((row) => this.#toCandidate(row, regionScopeMiss))
679
868
 
869
+ if (query.outcome) {
870
+ for (const candidate of candidates) {
871
+ candidate.outcomes = this.#outcomes!.read(candidate.id, candidate.placetype, query.outcome)
872
+ candidate.wikidata = this.#wikidataOf(candidate.id)
873
+ }
874
+ }
875
+
680
876
  if (query.bias && query.bias.length) {
681
877
  applyProximityRerank(candidates, query.bias)
682
878
  }
@@ -687,12 +883,12 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
687
883
  /**
688
884
  * One place by its `spr_id`, read from its primary-name row, or null when the table holds no row for it.
689
885
  */
690
- place(id: number): PlaceCandidate | null {
886
+ place(id: number): CandidatePlace | null {
691
887
  if (!Number.isInteger(id)) return null
692
888
 
693
889
  this.#placeProbe ??= this.database.prepare(
694
890
  "SELECT spr_id, name, country_id, placetype_id, latitude, longitude, min_lat, min_lon, max_lat, max_lon, neg_rank, is_primary, population" +
695
- `${this.#importanceSelect} FROM candidate WHERE spr_id = ? ORDER BY is_primary DESC LIMIT 1`
891
+ `${this.#importanceSelect}${this.#roleSelect} FROM candidate WHERE spr_id = ? ORDER BY is_primary DESC LIMIT 1`
696
892
  )
697
893
 
698
894
  const row = this.#placeProbe.get(id) as CandidateRow | undefined
@@ -700,13 +896,16 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
700
896
  return row ? this.#toCandidate({ ...row, effectiveNegRank: row.neg_rank, demoted: false }, false) : null
701
897
  }
702
898
 
703
- #toCandidate(row: RankedRow<CandidateRow>, regionScopeMiss: boolean): PlaceCandidate {
899
+ #toCandidate(row: RankedRow<CandidateRow>, regionScopeMiss: boolean): CandidatePlace {
900
+ const sprID = Number(row.spr_id)
704
901
  const hasBbox = row.min_lat != null && row.max_lat != null && row.min_lon != null && row.max_lon != null
705
- const parent = this.#ancestorLineage(Number(row.spr_id))[0]
902
+ const parent = this.#ancestorLineage(sprID)[0]
706
903
  const hasPopulation = row.population !== null && row.population > 0
904
+ const wikidata = this.#wikidataProbe ? this.#wikidataOf(sprID) : null
905
+ const sitelinkProminence = this.#sitelinkProbe ? this.#sitelinkProminenceOf(sprID) : null
707
906
 
708
907
  return {
709
- id: Number(row.spr_id),
908
+ id: sprID,
710
909
  name: String(row.name ?? ""),
711
910
  placetype: (this.#idToPlacetype.get(Number(row.placetype_id)) ?? "") as WOFPlacetype,
712
911
 
@@ -734,6 +933,8 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
734
933
 
735
934
  matchedAlias: row.is_primary === 0 ? true : null,
736
935
 
936
+ nameRole: typeof row.name_role === "string" ? row.name_role : null,
937
+
737
938
  population: hasPopulation ? row.population : null,
738
939
  referential: hasPopulation ? referentialFromPopulation(row.population) : null,
739
940
  encyclopedic: null,
@@ -748,6 +949,8 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
748
949
  }
749
950
  : null,
750
951
  mismatch: null,
952
+ ...(wikidata ? { wikidata } : {}),
953
+ ...(sitelinkProminence != null ? { sitelinkProminence } : {}),
751
954
  }
752
955
  }
753
956
  }