@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
@@ -35,6 +35,7 @@ import { PathBuilder, type PathBuilderLike } from "path-ts"
35
35
  import { TextSpliterator } from "spliterator"
36
36
  import { Globerator } from "spliterator/node/fs"
37
37
 
38
+ import { buildFSTDel1Sidecar, type BuildFSTDel1SidecarOpts, type BuiltFSTDel1Sidecar } from "#fst/del1-sidecar"
38
39
  import type { FSTNode } from "#fst/matcher"
39
40
  import { FSTMatcher, normalizeTokens } from "#fst/matcher"
40
41
  import type { FSTProvenance, PlaceEntry } from "#fst/types"
@@ -94,6 +95,12 @@ export interface BuildStreetMorphologyFSTOpts {
94
95
  * Canadian province abbreviations
95
96
  */
96
97
  excludedVariants?: ReadonlySet<string>
98
+ /**
99
+ * When set, builds a companion `FD1\0` 1-delete fuzzy token sidecar over the morphology FST.
100
+ *
101
+ * Pass `true` for defaults or an options object to override thresholds.
102
+ */
103
+ buildDel1Sidecar?: boolean | BuildFSTDel1SidecarOpts
97
104
  /**
98
105
  * Optional progress callback.
99
106
  */
@@ -107,6 +114,7 @@ export interface BuildStreetMorphologyFSTResult {
107
114
  variantCount: number
108
115
  insertCount: number
109
116
  locales: string[]
117
+ del1Sidecar?: BuiltFSTDel1Sidecar
110
118
  }
111
119
 
112
120
  /**
@@ -294,6 +302,10 @@ export async function buildStreetMorphologyFST(
294
302
  excludedInsertions: null,
295
303
  }
296
304
 
305
+ const del1Sidecar = opts.buildDel1Sidecar
306
+ ? buildFSTDel1Sidecar(matcher, opts.buildDel1Sidecar === true ? {} : opts.buildDel1Sidecar)
307
+ : undefined
308
+
297
309
  return {
298
310
  matcher,
299
311
  provenance,
@@ -301,5 +313,6 @@ export async function buildStreetMorphologyFST(
301
313
  variantCount,
302
314
  insertCount,
303
315
  locales,
316
+ ...(del1Sidecar ? { del1Sidecar } : {}),
304
317
  }
305
318
  }
@@ -26,6 +26,7 @@ import { pathExists } from "@mailwoman/core/fs/readers/stat"
26
26
  import { resourceDictionaryPath } from "@mailwoman/dictionaries/paths"
27
27
  import type { PathBuilder, PathBuilderLike } from "path-ts"
28
28
 
29
+ import { BinaryFSTDel1Lookup, del1SidecarPathFor } from "#fst/del1-sidecar"
29
30
  import type { FSTMatcher } from "#fst/matcher"
30
31
  import { deserializeFST, readFSTProvenance } from "#fst/serialize"
31
32
  import type { FSTProvenance } from "#fst/types"
@@ -59,6 +60,12 @@ export interface LoadStreetMorphologyFSTOpts {
59
60
  * @defaultValue the libpostal dictionaries `@mailwoman/dictionaries` ships.
60
61
  */
61
62
  dictionariesDir?: PathBuilderLike
63
+ /**
64
+ * When true, builds an in-memory `FD1\0` sidecar on the dictionary-build fallback path.
65
+ *
66
+ * @defaultValue `false`
67
+ */
68
+ buildDel1Sidecar?: boolean
62
69
  /**
63
70
  * Unreadable-artifact diagnostics.
64
71
  *
@@ -69,6 +76,11 @@ export interface LoadStreetMorphologyFSTOpts {
69
76
 
70
77
  export interface LoadedStreetMorphologyFST {
71
78
  matcher: FSTMatcher
79
+ /**
80
+ * Companion `FD1\0` 1-delete sidecar loaded from `<artifact>.del1.bin`
81
+ * or built on fallback, or `null` when absent.
82
+ */
83
+ del1Sidecar: BinaryFSTDel1Lookup | null
72
84
  /**
73
85
  * Which rung produced the matcher: a sealed-artifact deserialize, or the per-process dictionary build.
74
86
  */
@@ -98,8 +110,22 @@ export async function loadStreetMorphologyFST(
98
110
  const buf = await readLocalBuffer(artifactPath)
99
111
  const matcher = deserializeFST(buf)
100
112
  const provenance = readFSTProvenance(buf)
113
+ let del1Sidecar: BinaryFSTDel1Lookup | null = null
114
+ const sidecarPath = del1SidecarPathFor(artifactPath)
115
+
116
+ if (await pathExists(sidecarPath)) {
117
+ try {
118
+ const sidecarBuf = await readLocalBuffer(sidecarPath)
119
+ del1Sidecar = new BinaryFSTDel1Lookup(sidecarBuf)
120
+ matcher.del1Sidecar = del1Sidecar
121
+ } catch (sidecarError) {
122
+ warn(
123
+ `street-morphology del1 sidecar at ${sidecarPath} unreadable (${(sidecarError as Error).message}) — continuing without fuzzy sidecar`
124
+ )
125
+ }
126
+ }
101
127
 
102
- return { matcher, source: "artifact", path: artifactPath, provenance }
128
+ return { matcher, del1Sidecar, source: "artifact", path: artifactPath, provenance }
103
129
  } catch (error) {
104
130
  warn(
105
131
  `street-morphology artifact at ${artifactPath} unreadable (${(error as Error).message}) — falling back to the dictionary build`
@@ -109,7 +135,11 @@ export async function loadStreetMorphologyFST(
109
135
 
110
136
  const built = await buildStreetMorphologyFST({
111
137
  dictionariesDir: (opts.dictionariesDir ?? resourceDictionaryPath("libpostal")).toString(),
138
+ ...(opts.buildDel1Sidecar ? { buildDel1Sidecar: true } : {}),
112
139
  })
113
140
 
114
- return { matcher: built.matcher, source: "built", path: null, provenance: built.provenance }
141
+ const del1Sidecar = built.del1Sidecar ? new BinaryFSTDel1Lookup(built.del1Sidecar.bytes) : null
142
+ built.matcher.del1Sidecar = del1Sidecar
143
+
144
+ return { matcher: built.matcher, del1Sidecar, source: "built", path: null, provenance: built.provenance }
115
145
  }
@@ -5,6 +5,8 @@ import { HOUSE_NUMBER_REPETITION_INDEXES } from "@mailwoman/codex/labels/house-n
5
5
  import { AbbreviationToDirectional, US_STREET_SUFFIX_LOOKUP } from "@mailwoman/codex/us"
6
6
  import type { Tagged } from "type-fest"
7
7
 
8
+ import { addressPostcodeKey } from "#address/keys/postcode"
9
+
8
10
  /**
9
11
  * A place name folded by {@link normalizeLocalityForKey}, minted only by calling the fold.
10
12
  */
@@ -271,6 +273,14 @@ export interface StreetKeyRules {
271
273
  * Builds the key a house number is stored and probed under.
272
274
  */
273
275
  houseNumberKey: (number: string) => string
276
+ /**
277
+ * Builds the normalized scope key a postcode is indexed and compared under.
278
+ */
279
+ postcodeKey: (postcode: string | null | undefined) => string | null
280
+ /**
281
+ * Street-type morphology used by `canonicalStreetKey` when classifying thoroughfare types.
282
+ */
283
+ canonicalMorphology: "leading" | "trailing-english" | "germanic-fused" | "han"
274
284
  /**
275
285
  * Matches a house number written as a base number with joined sub-numbers, and captures the base.
276
286
  * A reader probes the base after the written number misses.
@@ -359,6 +369,8 @@ const SHARED_KEY_RULES: StreetKeyRules = {
359
369
  arrondissementAtBaseCity: false,
360
370
  localityFromRegionAndSubregion: false,
361
371
  houseNumberKey: (number) => number.trim().toLowerCase(),
372
+ postcodeKey: (postcode) => addressPostcodeKey("", postcode),
373
+ canonicalMorphology: "leading",
362
374
  houseNumberBase: null,
363
375
  houseNumberRepetition: null,
364
376
  }
@@ -377,13 +389,21 @@ const SHARED_KEY_RULES: StreetKeyRules = {
377
389
  * - `und` has the shared rules only, for a country whose official languages select no one row.
378
390
  */
379
391
  const STREET_KEY_RULES: Readonly<Record<string, StreetKeyRules>> = {
380
- us: { ...SHARED_KEY_RULES, streetKey: normalizeStreetForKey, englishRespellings: true, localityKeys: "abbreviated" },
392
+ us: {
393
+ ...SHARED_KEY_RULES,
394
+ streetKey: normalizeStreetForKey,
395
+ englishRespellings: true,
396
+ localityKeys: "abbreviated",
397
+ postcodeKey: (postcode) => addressPostcodeKey("US", postcode),
398
+ canonicalMorphology: "trailing-english",
399
+ },
381
400
  en: {
382
401
  ...SHARED_KEY_RULES,
383
402
  streetKey: normalizeStreetForKey,
384
403
  // The route reads the surface and never the province, so a bilingual Canadian extract keys each street one way.
385
404
  surfaceRoute: { pattern: FRENCH_LEAD_TYPE, locale: "fr" },
386
405
  englishRespellings: true,
406
+ canonicalMorphology: "trailing-english",
387
407
  },
388
408
  es: { ...SHARED_KEY_RULES, streetKey: (street) => wordStreetKey(street, expandLeadingWord(ES_STREET_TYPE_ABBREV)) },
389
409
  fr: {
@@ -393,9 +413,17 @@ const STREET_KEY_RULES: Readonly<Record<string, StreetKeyRules>> = {
393
413
  // BAN writes `3 bis` across most of France and `3 b` in Paris, and a query may write either joined.
394
414
  houseNumberRepetition: HOUSE_NUMBER_REPETITION_INDEXES,
395
415
  },
396
- de: { ...SHARED_KEY_RULES, streetKey: (street) => wordStreetKey(street, expandStreetSuffix("strasse")) },
416
+ de: {
417
+ ...SHARED_KEY_RULES,
418
+ streetKey: (street) => wordStreetKey(street, expandStreetSuffix("strasse")),
419
+ canonicalMorphology: "germanic-fused",
420
+ },
397
421
  it: { ...SHARED_KEY_RULES, streetKey: (street) => wordStreetKey(street, expandLeadingWord(IT_STREET_TYPE_ABBREV)) },
398
- nl: { ...SHARED_KEY_RULES, streetKey: (street) => wordStreetKey(street, expandStreetSuffix("straat")) },
422
+ nl: {
423
+ ...SHARED_KEY_RULES,
424
+ streetKey: (street) => wordStreetKey(street, expandStreetSuffix("straat")),
425
+ canonicalMorphology: "germanic-fused",
426
+ },
399
427
  pl: {
400
428
  ...SHARED_KEY_RULES,
401
429
  streetKey: (street) =>
@@ -425,6 +453,7 @@ const STREET_KEY_RULES: Readonly<Record<string, StreetKeyRules>> = {
425
453
  streetKey: (street) => foldHan(street) as StreetKey,
426
454
  localityKey: (locality) => foldHan(locality) as NameKey,
427
455
  localityFromRegionAndSubregion: true,
456
+ canonicalMorphology: "han",
428
457
  // A Taiwanese house number ends in 號 and may be written in full-width digits.
429
458
  houseNumberKey: (number) =>
430
459
  foldHan(number)
@@ -504,7 +533,7 @@ export function withoutApostropheLikeMarks(key: NameKey): NameKey {
504
533
  * The tatweel (U+0640), the short-vowel and shadda marks (U+064B–U+065F) and the superscript
505
534
  * alef (U+0670), with the hamza and madda that NFKD splits off `أ`, `إ`, `آ`, `ؤ` and `ئ`.
506
535
  */
507
- const ARABIC_MARKS = /[ـً-ٰٟ]/gu
536
+ const ARABIC_MARKS = /\u0640|[\u064B-\u065F\u0670]/gu
508
537
 
509
538
  /**
510
539
  * The key with the Arabic letters that writers interchange folded together, so `الاسماعيليه`
@@ -665,6 +694,7 @@ export function directionalRelaxedKeys(key: StreetKey): StreetKey[] {
665
694
  if (words.length < 2) return []
666
695
 
667
696
  const base = words.join(" ")
697
+
668
698
  const forms = [
669
699
  base,
670
700
  ...KEY_DIRECTIONALS.flatMap((directional) => [`${directional} ${base}`, `${base} ${directional}`]),
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
2
  // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
3
 
4
+ export * from "#labels/street/canonical"
4
5
  export * from "#labels/street/centroid"
5
6
  export * from "#labels/street/centroid/schema"
6
7
  export * from "#labels/street/morphology/fst/builder"
package/lib/landmark.ts CHANGED
@@ -8,14 +8,18 @@
8
8
  */
9
9
 
10
10
  import type { LandmarkHit, LandmarkLookup } from "@mailwoman/core/resolver"
11
+ import { OutcomeLayer, type OutcomeQuery, refuseMissingOutcomeTables } from "@mailwoman/core/resolver/outcome"
12
+ import { allRows } from "@mailwoman/core/utils"
11
13
  import { DatabaseClient } from "@mailwoman/sqlite/client"
12
14
  import { sql, type Kysely } from "kysely"
13
15
  import type { PathBuilderLike } from "path-ts"
14
16
 
15
17
  import { LANDMARK_BY_NAME_SQL, landmarkHitsFromRows, landmarkNameKey, type LandmarkNameTable } from "#landmark/rows"
18
+ import { missingOutcomeTablesIn, OutcomeMembershipReader, outcomeAdmitPredicate } from "#outcome/memberships"
19
+ import type { LandmarkOutcomeDatabase } from "#outcome/schema"
16
20
  import { prepareAll, type PreparedAll } from "#sqlite-utils"
17
21
 
18
- export interface LandmarkDatabase {
22
+ export interface LandmarkDatabase extends LandmarkOutcomeDatabase {
19
23
  landmark_name: LandmarkNameTable
20
24
  }
21
25
 
@@ -78,14 +82,57 @@ export class LandmarkSqliteLookup implements LandmarkLookup, Disposable {
78
82
 
79
83
  readonly #byName: PreparedAll<[nameKey: string], LandmarkNameTable>
80
84
 
81
- constructor(path: PathBuilderLike) {
85
+ readonly #layer: string
86
+ readonly #missingOutcomeTables: readonly string[]
87
+ readonly #outcomes: OutcomeMembershipReader | null
88
+
89
+ /**
90
+ * `layer` names the database in each outcome member's source and in a refusal:
91
+ * `landmarks` for the Wikidata layer, `openstreetmap` for the OpenStreetMap place layer.
92
+ */
93
+ constructor(path: PathBuilderLike, layer: string = OutcomeLayer.Landmarks) {
82
94
  this.#db = new DatabaseClient<LandmarkDatabase>(path, { readOnly: true })
83
95
 
84
96
  this.#byName = prepareAll(this.#db, LANDMARK_BY_NAME_SQL)
97
+ this.#layer = layer
98
+ this.#missingOutcomeTables = missingOutcomeTablesIn(this.#db)
99
+ this.#outcomes = OutcomeMembershipReader.open(this.#db, { recordColumn: "qid", layer })
100
+ }
101
+
102
+ /**
103
+ * With `outcome`, each hit holds its outcome set, and `admit` is a predicate of the read.
104
+ *
105
+ * @throws {OutcomeRequestError} For an outcome query against a database without the outcome tables.
106
+ */
107
+ find(name: string, outcome?: OutcomeQuery): LandmarkHit[] {
108
+ const key = landmarkNameKey(name)
109
+
110
+ if (!outcome) return landmarkHitsFromRows(this.#byName(key), name)
111
+
112
+ refuseMissingOutcomeTables(`the ${this.#layer} database`, this.#missingOutcomeTables)
113
+
114
+ const rows = outcome.admit ? this.#admittedRows(key, outcome.admit) : this.#byName(key)
115
+
116
+ // A landmark row's defaults are keyed by its `kind`, as a candidate row's are by its placetype.
117
+ return landmarkHitsFromRows(rows, name).map((hit) => ({
118
+ ...hit,
119
+ outcomes: this.#outcomes!.read(hit.qid, hit.kind, outcome),
120
+ }))
85
121
  }
86
122
 
87
- find(name: string): LandmarkHit[] {
88
- return landmarkHitsFromRows(this.#byName(landmarkNameKey(name)), name)
123
+ missingOutcomeTables(): readonly string[] {
124
+ return this.#missingOutcomeTables
125
+ }
126
+
127
+ #admittedRows(key: string, admit: readonly number[]): LandmarkNameTable[] {
128
+ const predicate = outcomeAdmitPredicate(admit, "qid", "landmark_name.qid", "landmark_name.kind")
129
+ const [select, order] = LANDMARK_BY_NAME_SQL.split(" ORDER BY ")
130
+
131
+ return allRows<LandmarkNameTable>(
132
+ this.#db.prepare(`${select} AND ${predicate.sql} ORDER BY ${order}`),
133
+ key,
134
+ ...predicate.params
135
+ )
89
136
  }
90
137
 
91
138
  [Symbol.dispose](): void {
@@ -7,6 +7,7 @@
7
7
  */
8
8
 
9
9
  import type { ScoreUnmeasuredReason } from "@mailwoman/core/resolver"
10
+ import type { OutcomeMembership, OutcomeQuery } from "@mailwoman/core/resolver/outcome"
10
11
  import type { LatLon, LatLonBounds } from "@mailwoman/spatial"
11
12
 
12
13
  /**
@@ -125,6 +126,22 @@ export interface PlaceCandidate {
125
126
  * Set when the input matched an alias of this place, by the candidate-table backend only.
126
127
  */
127
128
  matchedAlias?: true | null
129
+
130
+ /**
131
+ * The matched row's `name_role` (`"abbr"`, `"variant"`, `"foreign-script"`, `"gloss"`),
132
+ * or `null` when unstamped or primary, by the candidate-table backend only.
133
+ */
134
+ nameRole?: string | null
135
+
136
+ /**
137
+ * The place's effective outcome set, read only for a query with `outcome`.
138
+ */
139
+ outcomes?: readonly OutcomeMembership[] | null
140
+
141
+ /**
142
+ * The place's `wd:id` concordance, read only for a query with `outcome`, when the artifact records one.
143
+ */
144
+ wikidata?: string | null
128
145
  }
129
146
 
130
147
  /**
@@ -183,12 +200,6 @@ export interface FindPlaceQuery {
183
200
  */
184
201
  postcode?: string
185
202
 
186
- /**
187
- * Whether a locality query with `postcode` moves candidates near the postcode's centroid
188
- * to the front, sorted by distance, with the rest keeping their order.
189
- */
190
- postcodeContainmentCoherence?: boolean
191
-
192
203
  /**
193
204
  * The parsed region qualifier for a locality lookup.
194
205
  *
@@ -220,6 +231,14 @@ export interface FindPlaceQuery {
220
231
  */
221
232
  bbox?: LatLonBounds
222
233
 
234
+ /**
235
+ * Reads each candidate's outcome set, and with `admit` keeps only the rows that
236
+ * hold an admitted id, as a predicate of the fetch.
237
+ *
238
+ * A backend whose artifact lacks the outcome tables throws an `OutcomeRequestError`.
239
+ */
240
+ outcome?: OutcomeQuery
241
+
223
242
  /**
224
243
  * The maximum number of candidates to return, defaulting to 10.
225
244
  */
@@ -0,0 +1,131 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * The reads of a compiled database's outcome tables, shared by the candidate table
6
+ * and the landmark layers.
7
+ *
8
+ * A record's effective set is the join of `outcome_default`, one row per placetype
9
+ * default, and `record_outcome`, one row per explicit assertion.
10
+ * The candidate table keys `record_outcome` by `spr_id` and its defaults by the row's placetype.
11
+ *
12
+ * A landmark layer keys `record_outcome` by `qid` and its defaults by the row's `kind`.
13
+ */
14
+
15
+ import {
16
+ OUTCOME_TABLES,
17
+ type OutcomeMembership,
18
+ type OutcomeQuery,
19
+ unionOutcomes,
20
+ } from "@mailwoman/core/resolver/outcome"
21
+ import type { DatabaseClient } from "@mailwoman/sqlite/client"
22
+
23
+ import { hasTable, prepareAll, type PreparedAll } from "#sqlite-utils"
24
+
25
+ /**
26
+ * How one database keys its outcome rows.
27
+ */
28
+ export interface OutcomeKeying {
29
+ /**
30
+ * The `record_outcome` column that holds the record's key: `spr_id` or `qid`.
31
+ */
32
+ recordColumn: "spr_id" | "qid"
33
+ /**
34
+ * The data layer's name, the prefix of each member's source.
35
+ */
36
+ layer: string
37
+ }
38
+
39
+ /**
40
+ * The outcome tables `db` lacks.
41
+ */
42
+ export function missingOutcomeTablesIn<DB>(db: DatabaseClient<DB>): string[] {
43
+ return OUTCOME_TABLES.filter((table) => !hasTable(db, table))
44
+ }
45
+
46
+ /**
47
+ * The SQL predicate that keeps a row holding one of `ids`, by default or by assertion.
48
+ *
49
+ * `recordExpression` and `defaultKeyExpression` are SQL over the probed row: its record key
50
+ * and the value `outcome_default.placetype` is compared with.
51
+ */
52
+ export function outcomeAdmitPredicate(
53
+ ids: readonly number[],
54
+ recordColumn: OutcomeKeying["recordColumn"],
55
+ recordExpression: string,
56
+ defaultKeyExpression: string
57
+ ): { sql: string; params: number[] } {
58
+ // An empty admit list admits zero rows, and `IN ()` isn't valid SQL.
59
+ if (!ids.length) return { sql: "0", params: [] }
60
+
61
+ const list = ids.map(() => "?").join(",")
62
+
63
+ return {
64
+ sql:
65
+ `(EXISTS (SELECT 1 FROM outcome_default od WHERE od.placetype = ${defaultKeyExpression} AND od.outcome_id IN (${list}))` +
66
+ ` OR EXISTS (SELECT 1 FROM record_outcome ro WHERE ro.${recordColumn} = ${recordExpression} AND ro.outcome_id IN (${list})))`,
67
+ params: [...ids, ...ids],
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Reads effective outcome sets from one database, caching each placetype's defaults.
73
+ */
74
+ export class OutcomeMembershipReader {
75
+ readonly #keying: OutcomeKeying
76
+ readonly #defaults: PreparedAll<[key: string], { outcome_id: number }>
77
+ readonly #asserted: PreparedAll<[record: string | number], { outcome_id: number; contested: number }>
78
+ readonly #defaultCache = new Map<string, number[]>()
79
+
80
+ private constructor(
81
+ keying: OutcomeKeying,
82
+ defaults: PreparedAll<[key: string], { outcome_id: number }>,
83
+ asserted: PreparedAll<[record: string | number], { outcome_id: number; contested: number }>
84
+ ) {
85
+ this.#keying = keying
86
+ this.#defaults = defaults
87
+ this.#asserted = asserted
88
+ }
89
+
90
+ /**
91
+ * A reader, or null when `db` lacks an outcome table.
92
+ */
93
+ static open<DB>(db: DatabaseClient<DB>, keying: OutcomeKeying): OutcomeMembershipReader | null {
94
+ if (missingOutcomeTablesIn(db).length) return null
95
+
96
+ return new OutcomeMembershipReader(
97
+ keying,
98
+ prepareAll(db, "SELECT outcome_id FROM outcome_default WHERE placetype = ?"),
99
+ prepareAll(db, `SELECT outcome_id, contested FROM record_outcome WHERE ${keying.recordColumn} = ?`)
100
+ )
101
+ }
102
+
103
+ /**
104
+ * The effective set of one record: its placetype defaults and its explicit assertions.
105
+ *
106
+ * An id the vocabulary doesn't hold is left out, because the database may pin a
107
+ * newer revision than the vocabulary the request was checked against.
108
+ */
109
+ read(record: string | number, defaultKey: string, query: OutcomeQuery): OutcomeMembership[] {
110
+ const names = new Map(query.vocabulary.map((m) => [m.id, m.name]))
111
+
112
+ let defaults = this.#defaultCache.get(defaultKey)
113
+
114
+ if (!defaults) {
115
+ defaults = this.#defaults(defaultKey).map((row) => Number(row.outcome_id))
116
+ this.#defaultCache.set(defaultKey, defaults)
117
+ }
118
+
119
+ const fromDefaults: OutcomeMembership[] = defaults
120
+ .map((id) => names.get(id))
121
+ .filter((name): name is string => typeof name === "string")
122
+ .map((outcome) => ({ outcome, contested: false, sources: [`${this.#keying.layer}:default`] }))
123
+
124
+ const fromAssertions: OutcomeMembership[] = this.#asserted(record)
125
+ .map((row) => ({ name: names.get(Number(row.outcome_id)), contested: Number(row.contested) === 1 }))
126
+ .filter((row): row is { name: string; contested: boolean } => typeof row.name === "string")
127
+ .map((row) => ({ outcome: row.name, contested: row.contested, sources: [`${this.#keying.layer}:asserted`] }))
128
+
129
+ return unionOutcomes(fromDefaults, fromAssertions)
130
+ }
131
+ }
@@ -0,0 +1,147 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * The outcome tables of `docs/engineering/reference/outcome-kinds.mdx`,
6
+ * compiled into a database from one pinned revision of the definitions.
7
+ *
8
+ * A record's set is the join of the two: the defaults of its placetype, and its explicit assertions.
9
+ * `outcome_manifest` is the database's `outcomes` block, the revision and spec hash both were built from.
10
+ *
11
+ * `landmarks.db` keys its records by Wikidata item, so its `record_outcome` holds a `qid` column.
12
+ */
13
+
14
+ import { createOutcomeEvidenceTable } from "@mailwoman/gazetteer/whosonfirst/outcomes/evidence"
15
+ import type { CompiledOutcomeSpec, OutcomeSpecPin } from "@mailwoman/gazetteer/whosonfirst/outcomes/spec"
16
+ import type { DatabaseClient } from "@mailwoman/sqlite/client"
17
+ import type { Kysely } from "kysely"
18
+
19
+ import { hasTable } from "#sqlite-utils"
20
+
21
+ /**
22
+ * One placetype default.
23
+ */
24
+ export interface OutcomeDefaultTable {
25
+ placetype: string
26
+ outcome_id: number
27
+ }
28
+
29
+ /**
30
+ * One explicit assertion on one record.
31
+ */
32
+ export interface RecordOutcomeTable {
33
+ spr_id: number
34
+ outcome_id: number
35
+ /**
36
+ * 1 when a source denies the member while the record holds it, else 0.
37
+ */
38
+ contested: number
39
+ }
40
+
41
+ /**
42
+ * One explicit assertion on one `landmarks.db` place.
43
+ */
44
+ export interface LandmarkOutcomeTable {
45
+ qid: string
46
+ outcome_id: number
47
+ contested: number
48
+ }
49
+
50
+ /**
51
+ * The single row naming the definitions revision the tables were compiled from.
52
+ */
53
+ export type OutcomeManifestTable = OutcomeSpecPin
54
+
55
+ export interface OutcomeDatabase {
56
+ outcome_default: OutcomeDefaultTable
57
+ record_outcome: RecordOutcomeTable
58
+ outcome_manifest: OutcomeManifestTable
59
+ }
60
+
61
+ export interface LandmarkOutcomeDatabase {
62
+ outcome_default: OutcomeDefaultTable
63
+ record_outcome: LandmarkOutcomeTable
64
+ outcome_manifest: OutcomeManifestTable
65
+ }
66
+
67
+ /**
68
+ * The placetype every `poi.db` row holds, so the join with `outcome_default` gives each row `venue`.
69
+ */
70
+ export const POI_ROW_PLACETYPE = "venue"
71
+
72
+ /**
73
+ * The two tables every outcome-aware database shares, whichever key its assertions use.
74
+ */
75
+ interface OutcomeSharedDatabase {
76
+ outcome_default: OutcomeDefaultTable
77
+ outcome_manifest: OutcomeManifestTable
78
+ }
79
+
80
+ /**
81
+ * The members of a handle {@link writeOutcomeDefaults} uses, so a handle over any
82
+ * schema that holds the shared tables passes without a cast.
83
+ */
84
+ type OutcomeSharedHandle = Pick<Kysely<OutcomeSharedDatabase>, "insertInto" | "schema">
85
+
86
+ /**
87
+ * Create the outcome tables, write the pinned revision and every placetype default of
88
+ * the spec, and create the assertion table the database keys its records by.
89
+ *
90
+ * @returns The count of `outcome_default` rows.
91
+ */
92
+ export async function writeOutcomeDefaults(
93
+ db: OutcomeSharedHandle,
94
+ spec: CompiledOutcomeSpec,
95
+ pin: OutcomeSpecPin,
96
+ recordKey: "spr_id" | "qid" = "spr_id"
97
+ ): Promise<number> {
98
+ const table = createOutcomeEvidenceTable(spec)
99
+
100
+ await db.schema
101
+ .createTable("outcome_default")
102
+ .addColumn("placetype", "text", (c) => c.notNull())
103
+ .addColumn("outcome_id", "integer", (c) => c.notNull())
104
+ .addPrimaryKeyConstraint("outcome_default_pk", ["placetype", "outcome_id"])
105
+ .execute()
106
+
107
+ await db.schema
108
+ .createTable("outcome_manifest")
109
+ .addColumn("revision", "text", (c) => c.notNull())
110
+ .addColumn("sha256", "text", (c) => c.notNull())
111
+ .execute()
112
+
113
+ await db.schema
114
+ .createTable("record_outcome")
115
+ .addColumn(recordKey, recordKey === "qid" ? "text" : "integer", (c) => c.notNull())
116
+ .addColumn("outcome_id", "integer", (c) => c.notNull())
117
+ .addColumn("contested", "integer", (c) => c.notNull())
118
+ .addPrimaryKeyConstraint("outcome_assertion_pk", [recordKey, "outcome_id"])
119
+ .execute()
120
+
121
+ await db.insertInto("outcome_manifest").values(pin).execute()
122
+
123
+ const defaults = Object.entries(spec.defaults).flatMap(([placetype, members]) =>
124
+ members.map((member) => ({ placetype, outcome_id: table.idOf(member) }))
125
+ )
126
+
127
+ await db.insertInto("outcome_default").values(defaults).execute()
128
+
129
+ return defaults.length
130
+ }
131
+
132
+ /**
133
+ * The `outcomes` block a database was compiled against, or `null` when it predates the tables.
134
+ *
135
+ * @public
136
+ */
137
+ export function readOutcomeManifest<DB>(db: DatabaseClient<DB>): OutcomeSpecPin | null {
138
+ if (!hasTable(db, "outcome_manifest")) return null
139
+
140
+ const row = db.prepare("SELECT revision, sha256 FROM outcome_manifest").get()
141
+
142
+ if (!row) {
143
+ throw new Error("outcome_manifest holds zero rows; the database's outcome tables have no pinned revision.")
144
+ }
145
+
146
+ return { revision: String(row.revision), sha256: String(row.sha256) }
147
+ }
package/lib/poi/lookup.ts CHANGED
@@ -108,6 +108,10 @@ export interface POISearchHit {
108
108
  */
109
109
  gersID: string | null
110
110
  distanceM: number | null
111
+ /**
112
+ * Stored street name when the POI layer includes a street column.
113
+ */
114
+ street?: string | null
111
115
  }
112
116
 
113
117
  /**
package/lib/poi/schema.ts CHANGED
@@ -23,6 +23,7 @@ import type { DatabaseClient } from "@mailwoman/sqlite/client"
23
23
  import { sql, type Kysely } from "kysely"
24
24
 
25
25
  import type { NameKey } from "#labels/street/normalize"
26
+ import type { OutcomeDatabase } from "#outcome/schema"
26
27
 
27
28
  /**
28
29
  * One POI row.
@@ -104,7 +105,7 @@ export interface POICategoryCodeTable {
104
105
  category: string
105
106
  }
106
107
 
107
- export interface POIDatabase extends layerschemadatabase {
108
+ export interface POIDatabase extends layerschemadatabase, OutcomeDatabase {
108
109
  poi: POITable
109
110
  poi_stage: POIStageTable
110
111
  poi_category_codes: POICategoryCodeTable