@mailwoman/resolver 10.8.0 → 11.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 (142) hide show
  1. package/README.md +4 -8
  2. package/lib/admin/coherence-passes.ts +14 -20
  3. package/lib/admin/containment.ts +6 -5
  4. package/lib/admin/jp-municipality.ts +3 -3
  5. package/lib/admin/winner.ts +5 -5
  6. package/lib/admin.ts +2 -5
  7. package/lib/bare-toponym-race.ts +12 -10
  8. package/lib/decorate-node.ts +62 -9
  9. package/lib/fold-name.ts +8 -8
  10. package/lib/index.ts +11 -8
  11. package/lib/plausibility.ts +2 -5
  12. package/lib/postcode/country-coherence.ts +4 -7
  13. package/lib/postcode/prefix.ts +4 -7
  14. package/lib/postcode/shape-coherence.ts +3 -6
  15. package/lib/postcode.ts +2 -5
  16. package/lib/remote-resolver.ts +3 -7
  17. package/lib/rerank.ts +7 -8
  18. package/lib/resolve/country-code.ts +106 -0
  19. package/lib/resolve/landmark.ts +234 -0
  20. package/lib/resolve/passes.ts +14 -61
  21. package/lib/resolve/region-city.ts +255 -0
  22. package/lib/resolve/whole-input.ts +49 -0
  23. package/lib/resolve.ts +62 -65
  24. package/lib/span-rescore.ts +90 -26
  25. package/lib/street/evidence.ts +2 -5
  26. package/lib/street/tier.ts +28 -13
  27. package/lib/street.ts +2 -5
  28. package/lib/toponym-prior.ts +4 -7
  29. package/out/admin/coherence-passes.d.ts +2 -7
  30. package/out/admin/coherence-passes.d.ts.map +1 -1
  31. package/out/admin/coherence-passes.js +14 -20
  32. package/out/admin/coherence-passes.js.map +1 -1
  33. package/out/admin/containment.d.ts +3 -5
  34. package/out/admin/containment.d.ts.map +1 -1
  35. package/out/admin/containment.js +5 -5
  36. package/out/admin/containment.js.map +1 -1
  37. package/out/admin/jp-municipality.d.ts +0 -3
  38. package/out/admin/jp-municipality.d.ts.map +1 -1
  39. package/out/admin/jp-municipality.js +2 -15
  40. package/out/admin/jp-municipality.js.map +1 -1
  41. package/out/admin/winner.d.ts +2 -5
  42. package/out/admin/winner.d.ts.map +1 -1
  43. package/out/admin/winner.js +2 -9
  44. package/out/admin/winner.js.map +1 -1
  45. package/out/admin.d.ts +0 -5
  46. package/out/admin.d.ts.map +1 -1
  47. package/out/admin.js +2 -5
  48. package/out/admin.js.map +1 -1
  49. package/out/bare-toponym-race.d.ts +0 -11
  50. package/out/bare-toponym-race.d.ts.map +1 -1
  51. package/out/bare-toponym-race.js +3 -12
  52. package/out/bare-toponym-race.js.map +1 -1
  53. package/out/decorate-node.d.ts +14 -6
  54. package/out/decorate-node.d.ts.map +1 -1
  55. package/out/decorate-node.js +53 -9
  56. package/out/decorate-node.js.map +1 -1
  57. package/out/fold-name.d.ts +5 -8
  58. package/out/fold-name.d.ts.map +1 -1
  59. package/out/fold-name.js +7 -8
  60. package/out/fold-name.js.map +1 -1
  61. package/out/index.d.ts +8 -8
  62. package/out/index.d.ts.map +1 -1
  63. package/out/index.js +10 -8
  64. package/out/index.js.map +1 -1
  65. package/out/plausibility.d.ts +0 -5
  66. package/out/plausibility.d.ts.map +1 -1
  67. package/out/plausibility.js +2 -5
  68. package/out/plausibility.js.map +1 -1
  69. package/out/postcode/country-coherence.d.ts +2 -7
  70. package/out/postcode/country-coherence.d.ts.map +1 -1
  71. package/out/postcode/country-coherence.js +3 -6
  72. package/out/postcode/country-coherence.js.map +1 -1
  73. package/out/postcode/prefix.d.ts +2 -7
  74. package/out/postcode/prefix.d.ts.map +1 -1
  75. package/out/postcode/prefix.js +3 -6
  76. package/out/postcode/prefix.js.map +1 -1
  77. package/out/postcode/shape-coherence.d.ts +1 -6
  78. package/out/postcode/shape-coherence.d.ts.map +1 -1
  79. package/out/postcode/shape-coherence.js +2 -5
  80. package/out/postcode/shape-coherence.js.map +1 -1
  81. package/out/postcode.d.ts +0 -5
  82. package/out/postcode.d.ts.map +1 -1
  83. package/out/postcode.js +2 -5
  84. package/out/postcode.js.map +1 -1
  85. package/out/remote-resolver.d.ts +1 -7
  86. package/out/remote-resolver.d.ts.map +1 -1
  87. package/out/remote-resolver.js +2 -6
  88. package/out/remote-resolver.js.map +1 -1
  89. package/out/rerank.d.ts +3 -7
  90. package/out/rerank.d.ts.map +1 -1
  91. package/out/rerank.js +3 -10
  92. package/out/rerank.js.map +1 -1
  93. package/out/resolve/country-code.d.ts +28 -0
  94. package/out/resolve/country-code.d.ts.map +1 -0
  95. package/out/resolve/country-code.js +91 -0
  96. package/out/resolve/country-code.js.map +1 -0
  97. package/out/resolve/landmark.d.ts +25 -0
  98. package/out/resolve/landmark.d.ts.map +1 -0
  99. package/out/resolve/landmark.js +187 -0
  100. package/out/resolve/landmark.js.map +1 -0
  101. package/out/resolve/passes.d.ts +3 -36
  102. package/out/resolve/passes.d.ts.map +1 -1
  103. package/out/resolve/passes.js +13 -30
  104. package/out/resolve/passes.js.map +1 -1
  105. package/out/resolve/region-city.d.ts +56 -0
  106. package/out/resolve/region-city.d.ts.map +1 -0
  107. package/out/resolve/region-city.js +209 -0
  108. package/out/resolve/region-city.js.map +1 -0
  109. package/out/resolve/whole-input.d.ts +14 -0
  110. package/out/resolve/whole-input.d.ts.map +1 -0
  111. package/out/resolve/whole-input.js +37 -0
  112. package/out/resolve/whole-input.js.map +1 -0
  113. package/out/resolve.d.ts +0 -8
  114. package/out/resolve.d.ts.map +1 -1
  115. package/out/resolve.js +42 -59
  116. package/out/resolve.js.map +1 -1
  117. package/out/span-rescore.d.ts +16 -15
  118. package/out/span-rescore.d.ts.map +1 -1
  119. package/out/span-rescore.js +68 -18
  120. package/out/span-rescore.js.map +1 -1
  121. package/out/street/evidence.d.ts +0 -5
  122. package/out/street/evidence.d.ts.map +1 -1
  123. package/out/street/evidence.js +2 -5
  124. package/out/street/evidence.js.map +1 -1
  125. package/out/street/tier.d.ts +3 -8
  126. package/out/street/tier.d.ts.map +1 -1
  127. package/out/street/tier.js +24 -11
  128. package/out/street/tier.js.map +1 -1
  129. package/out/street.d.ts +0 -5
  130. package/out/street.d.ts.map +1 -1
  131. package/out/street.js +2 -5
  132. package/out/street.js.map +1 -1
  133. package/out/toponym-prior.d.ts +2 -7
  134. package/out/toponym-prior.d.ts.map +1 -1
  135. package/out/toponym-prior.js +4 -7
  136. package/out/toponym-prior.js.map +1 -1
  137. package/package.json +9 -8
  138. package/lib/backend-capabilities.ts +0 -89
  139. package/out/backend-capabilities.d.ts +0 -36
  140. package/out/backend-capabilities.d.ts.map +0 -1
  141. package/out/backend-capabilities.js +0 -77
  142. package/out/backend-capabilities.js.map +0 -1
@@ -0,0 +1,234 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * Answers a query that's a place's name, with no street or postcode, from the landmark layer.
6
+ *
7
+ * The place of that name with the most Wikipedia language editions answers,
8
+ * and the others stay as alternatives.
9
+ * A prominence of log10(sitelinks) puts the lead on the scale the admin tier's `declared_ambiguity`
10
+ * margin reads, so a close call is declared by the same rule that declares one between two towns.
11
+ *
12
+ * A code written in capitals reads by one rule.
13
+ * A code a country is written as answers the country, and the airport holding the same
14
+ * IATA code is listed as an alternative: `AUS` is Australia, then Austin–Bergstrom.
15
+ *
16
+ * Every other code answers the place holding it: `SFO`, `LHR` and `DTW` are airports.
17
+ * `writtenCountryCode` states which codes a country claims.
18
+ */
19
+
20
+ import { walkNodes, type AddressNode } from "@mailwoman/core/decoder"
21
+ import {
22
+ EMPTY_PLACE_FIELDS,
23
+ landmarkPlaceID,
24
+ OSM_LANDMARK_PREFIX,
25
+ type LandmarkHit,
26
+ type LandmarkLookup,
27
+ type ResolvedPlace,
28
+ } from "@mailwoman/core/resolver"
29
+ import { isCountryAirportCollision } from "@mailwoman/registry/overlap/country-airport"
30
+ import { isLatLonBounds, latLonBoundsContain } from "@mailwoman/spatial/bbox"
31
+ import { haversine } from "@mailwoman/spatial/geometries/point/distance"
32
+
33
+ import { decorateNode } from "#decorate-node"
34
+ import { foldName } from "#fold-name"
35
+ import { writtenCountryCode } from "#resolve/country-code"
36
+
37
+ /**
38
+ * The tags that make an input an address.
39
+ * A landmark name cannot answer an address.
40
+ */
41
+ const ADDRESS_TAGS: ReadonlySet<string> = new Set(["house_number", "postcode", "unit", "po_box"])
42
+
43
+ /**
44
+ * The namesakes a landmark answer lists: OpenStreetMap can hold hundreds of parks under one name.
45
+ */
46
+ const LISTED_ALTERNATIVES = 8
47
+
48
+ /**
49
+ * The farthest a landmark may lie from a locality the input states, matching span rescore's postcode radius.
50
+ */
51
+ const STATED_LOCALITY_RADIUS_KM = 50
52
+
53
+ /**
54
+ * Keeps the hits an input's stated context permits: its country, and the surroundings of its locality.
55
+ */
56
+ function hitsInContext(hits: readonly LandmarkHit[], context: readonly AddressNode[]): LandmarkHit[] {
57
+ const nodes = [...walkNodes(context)]
58
+
59
+ const country = nodes
60
+ .map((node) => node.metadata?.["resolver_country"])
61
+ .find((code): code is string => typeof code === "string")
62
+
63
+ const locality = nodes.find((node) => node.tag === "locality" && node.lat != null && node.lon != null)
64
+ const extent = locality?.metadata?.["resolver_bbox"]
65
+
66
+ const distance = (hit: LandmarkHit) => (locality ? haversine(locality.lat!, locality.lon!, hit.lat, hit.lon) : 0)
67
+
68
+ // OpenStreetMap holds a St Mary's in every village, so a stated town's own extent
69
+ // bounds its places where the gazetteer holds one.
70
+ // Wikipedia editions separate famous namesakes, so a Wikidata place keeps the wider radius.
71
+ const inLocality = (hit: LandmarkHit) =>
72
+ hit.qid.startsWith(OSM_LANDMARK_PREFIX) && isLatLonBounds(extent)
73
+ ? latLonBoundsContain(extent, hit.lat, hit.lon)
74
+ : distance(hit) <= STATED_LOCALITY_RADIUS_KM
75
+
76
+ const kept = hits.filter((hit) => hit.country === country && inLocality(hit))
77
+
78
+ return kept.every((hit) => hit.qid.startsWith(OSM_LANDMARK_PREFIX))
79
+ ? kept.toSorted((a, b) => distance(a) - distance(b))
80
+ : kept
81
+ }
82
+
83
+ function placeOf(hit: LandmarkHit): ResolvedPlace {
84
+ const prominence = hit.importance ?? Math.log10(hit.sitelinks + 1)
85
+
86
+ return {
87
+ ...EMPTY_PLACE_FIELDS,
88
+ id: hit.qid,
89
+ name: hit.name,
90
+ placetype: "venue",
91
+ country: hit.country,
92
+ lat: hit.lat,
93
+ lon: hit.lon,
94
+ parent_id: null,
95
+ score: prominence,
96
+ prominence,
97
+ exactMatch: true,
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Lists every landmark that holds the written code on the resolved country node, as its alternatives.
103
+ *
104
+ * `AUS` answers Australia, and Austin–Bergstrom International Airport is the
105
+ * reading a caller can pick instead.
106
+ * A word spelled like the code, such as the town of Usa under `USA`,
107
+ * isn't a holder of the code and stays out.
108
+ *
109
+ * The list sits on a resolved country node, so a country the gazetteer left unresolved keeps its parse.
110
+ *
111
+ * The node also records `code_collision`, the identifier registry's verdict on whether the written
112
+ * code is both an officially assigned ISO 3166-1 alpha-3 code and an IATA airport code in its profile.
113
+ * The registry and the landmark layer read different sources, so the flag
114
+ * and the listed holders can disagree, and both are kept.
115
+ */
116
+ function listCodeHoldersOnCountry(roots: AddressNode[], code: string, hits: readonly LandmarkHit[]): void {
117
+ const country = roots.find((root) => root.tag === "country" && typeof root.placeID === "string")
118
+
119
+ if (!country) return
120
+
121
+ country.metadata = { ...country.metadata, code_collision: isCountryAirportCollision(code) }
122
+
123
+ const holders = hits.filter((hit) => hit.code && hit.kind === "venue")
124
+
125
+ if (!holders.length) return
126
+
127
+ const listed = (country.alternatives as ResolvedPlace[] | undefined) ?? []
128
+
129
+ country.alternatives = [...listed, ...holders.map(placeOf)]
130
+ }
131
+
132
+ /**
133
+ * Replaces the parse's reading of a landmark name with a venue node that holds the answer.
134
+ *
135
+ * The first comma-separated part is the name, and any other part is context that has to have resolved.
136
+ * A settlement that leads the name stays with the admin ladder, because the ladder ranks settlements.
137
+ */
138
+ export async function applyLandmark(roots: AddressNode[], raw: string, landmarks: LandmarkLookup): Promise<void> {
139
+ const nodes = [...walkNodes(roots)]
140
+
141
+ if (nodes.some((node) => ADDRESS_TAGS.has(node.tag))) return
142
+
143
+ const name = raw.split(",", 1)[0]!.trim()
144
+
145
+ if (!name) return
146
+
147
+ const hits = await landmarks.find(name)
148
+ const hasContext = raw.trim().length > name.length
149
+
150
+ // A bare country code answers the country, and the airport holding the same code is listed beside it.
151
+ // The registry's collision verdict is stamped whether or not the landmark layer holds the code.
152
+ // With context, `FRA, Germany` can still reach the airport.
153
+ if (!hasContext && writtenCountryCode(name)) {
154
+ listCodeHoldersOnCountry(roots, name, hits)
155
+
156
+ return
157
+ }
158
+
159
+ if (!hits.length) return
160
+
161
+ const nameEnd = raw.indexOf(name) + name.length
162
+ const context = roots.filter((node) => node.start >= nameEnd && typeof node.placeID === "string")
163
+
164
+ if (hasContext && !context.length) return
165
+
166
+ const candidates = hasContext ? hitsInContext(hits, context) : hits
167
+ const leader = candidates[0]
168
+
169
+ if (!leader || leader.kind !== "venue") return
170
+
171
+ // A translation or alias is the weakest claim on a name, so it answers only where the
172
+ // gazetteer holds none: `Hamburg` is an alias of Hamburg Airport and the name of a city.
173
+ const resolved = roots.filter((root) => typeof root.placeID === "string")
174
+ const fromOSM = leader.qid.startsWith(OSM_LANDMARK_PREFIX)
175
+
176
+ // The parser reads `Wall Street` and `Times Square` as streets, and `Central Park` as a venue.
177
+ // It also reads some parks as a street with the suffix `Park`, and those stay places.
178
+ const inName = (node: AddressNode) => node.start < nameEnd
179
+
180
+ const readsAsPark = nodes.some(
181
+ (node) => node.tag === "street_suffix" && inName(node) && foldName(node.value) === "park"
182
+ )
183
+
184
+ const readsAsStreet = !readsAsPark && nodes.some((node) => node.tag === "street" && inName(node))
185
+
186
+ if (fromOSM) {
187
+ // OpenStreetMap holds a place spelled like a street in some other town: `Wall Street` also answers in Utah.
188
+ if (readsAsStreet) return
189
+
190
+ // A bare name that several OpenStreetMap places hold names none of them: `bus stop`
191
+ // is held in India and Kiribati, and `The Big Apple` in South Carolina and Australia.
192
+ // With no context to choose, the layer abstains.
193
+ if (!hasContext && candidates.length > 1) return
194
+
195
+ // A school or a park in OpenStreetMap can share its town's name,
196
+ // so a place holding the whole name keeps it.
197
+ // A park reading beats a row with no measured population, as `Piedmont Park`
198
+ // in South Carolina yields to the park in Atlanta.
199
+ const holdsName = (node: AddressNode) =>
200
+ typeof node.placeID === "string" &&
201
+ foldName(node.value) === foldName(name) &&
202
+ (!readsAsPark || Number(node.metadata?.["resolver_score"] ?? 0) > 0)
203
+
204
+ if (nodes.some(holdsName)) return
205
+ } else {
206
+ const nameResolved = resolved.some(
207
+ (root) => root.start < nameEnd || root.value.toLowerCase() === name.toLowerCase()
208
+ )
209
+
210
+ // `Baker Street` is an alias of the tube station, and the street keeps its name.
211
+ if (!leader.primary && !leader.code && (nameResolved || readsAsStreet)) return
212
+ }
213
+
214
+ const node: AddressNode = {
215
+ // A famous street answers from Wikidata and stays a street: `Downing Street` holds a coordinate and a street.
216
+ tag: readsAsStreet ? "street" : "venue",
217
+ value: name.normalize("NFC").replaceAll(/\s+/gu, " "),
218
+ start: raw.indexOf(name),
219
+ end: nameEnd,
220
+ confidence: 1,
221
+ children: [],
222
+ }
223
+
224
+ decorateNode(node, placeOf(leader), candidates.slice(1, LISTED_ALTERNATIVES + 1).map(placeOf))
225
+ node.placeID = landmarkPlaceID(leader.qid)
226
+
227
+ node.metadata = {
228
+ ...node.metadata,
229
+ landmark_sitelinks: leader.sitelinks,
230
+ ...(fromOSM ? { landmark_source: "openstreetmap:planet" } : {}),
231
+ }
232
+
233
+ roots.splice(0, roots.length, node, ...context)
234
+ }
@@ -1,20 +1,14 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- */
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
6
3
 
7
4
  import type { PlacetypeMap } from "@mailwoman/codex/placetype-map"
8
5
  import { isShapeExcludedPostcode, walkNodes, type AddressNode } from "@mailwoman/core/decoder"
9
6
  import {
10
- type CoincidentLocality,
11
7
  type DefaultCountry,
12
8
  EMPTY_PLACE_FIELDS,
13
- compareReferential,
14
9
  type ResolveCandidateTrace,
15
10
  type ResolveNodeTrace,
16
11
  type PostcodePrefixIndexLike,
17
- referentialFromPopulation,
18
12
  type ResolvedPlace,
19
13
  type ResolveOpts,
20
14
  type ResolverBackend,
@@ -24,7 +18,6 @@ import { PLACETYPE_SPECIFICITY } from "@mailwoman/gazetteer/whosonfirst/placetyp
24
18
  import { haversine } from "@mailwoman/spatial/geometries/point/distance"
25
19
 
26
20
  import { decorateNode, isResolvedWithCoord } from "#decorate-node"
27
- import type { CoordinateOptionalPlace } from "#postcode/prefix"
28
21
  import { findRescoreCandidate, hasResolvedPlace, postcodeCodeSubset } from "#span-rescore"
29
22
 
30
23
  const TRACE_CANDIDATE_CAP = 10
@@ -295,12 +288,6 @@ export interface ResolutionState {
295
288
  */
296
289
  hardCountry?: string
297
290
 
298
- /**
299
- * Whether a resolved region gains its coincident locality of the same name as an
300
- * interpretation when the tree has no locality node.
301
- */
302
- hierarchyCompletion: boolean
303
-
304
291
  /**
305
292
  * Whether each resolved node gets its ancestor lineage in metadata, when the backend supports it.
306
293
  */
@@ -321,54 +308,12 @@ export interface ResolutionState {
321
308
  /**
322
309
  * The tree's first region value.
323
310
  *
324
- * The region and locality nodes are siblings, so the walk would not otherwise
311
+ * The region and locality nodes are siblings, so the walk wouldn't otherwise
325
312
  * pass the region to the locality lookup.
326
313
  * It applies only with {@link ResolutionState.adminContainmentRerank}
327
314
  * and no caller-supplied default country.
328
315
  */
329
316
  regionQualifier?: string | null
330
-
331
- /**
332
- * Whether any node maps to the `locality` placetype.
333
- * Hierarchy completion runs only when this is false.
334
- */
335
- localityNodePresent: boolean
336
-
337
- /**
338
- * The first resolved region place, used to look up its coincident locality.
339
- */
340
- resolvedRegion: CoordinateOptionalPlace | null
341
-
342
- /**
343
- * The decorated node for {@link ResolutionState.resolvedRegion}.
344
- *
345
- * Hierarchy completion adds the locality interpretation to it in place.
346
- */
347
- resolvedRegionNode: AddressNode | null
348
- }
349
-
350
- /**
351
- * Picks the completion locality among coincident candidates of the same name.
352
- *
353
- * It prefers the most populous candidate, then the nearest candidate.
354
- * It returns `null` on an exact tie.
355
- */
356
- export function pickCompletion(candidates: readonly CoincidentLocality[]): CoincidentLocality | null {
357
- if (!candidates.length) return null
358
-
359
- if (candidates.length === 1) return candidates[0]!
360
-
361
- const ranked = [...candidates]
362
- .map((c) => ({ c, referential: referentialFromPopulation(c.population), population: c.population }))
363
- // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
364
- .sort((a, b) => compareReferential(a, b) || a.c.distanceKm - b.c.distanceKm)
365
- .map((x) => x.c)
366
-
367
- const [first, second] = ranked
368
-
369
- if (first!.population === second!.population && first!.distanceKm === second!.distanceKm) return null
370
-
371
- return first!
372
317
  }
373
318
 
374
319
  /**
@@ -407,7 +352,7 @@ export async function applySpanRescore(
407
352
  thresholdKm: opts.spanRescoreThresholdKm,
408
353
 
409
354
  postalCompoundRecovery: opts.postalCompoundRecovery,
410
- spanRescoreRequireContextRemainder: opts.spanRescoreRequireContextRemainder,
355
+ ...(opts.isVenueCategoryWord ? { isVenueCategoryWord: opts.isVenueCategoryWord } : {}),
411
356
  })
412
357
  } catch {
413
358
  return
@@ -433,7 +378,15 @@ export async function applySpanRescore(
433
378
 
434
379
  decorateNode(node, hit.place, hit.alternatives)
435
380
 
436
- node.metadata = { ...node.metadata, span_rescore: true, rescore_postcode_verified: hit.postcodeVerified }
381
+ // `rescore_drops_name` tells the geocode that this locality may scope a venue lookup.
382
+ // It answers only when a venue answers near it.
383
+ node.metadata = {
384
+ ...node.metadata,
385
+ span_rescore: true,
386
+ rescore_postcode_verified: hit.postcodeVerified,
387
+ rescore_drops_name: hit.dropsName,
388
+ }
389
+
437
390
  roots.push(node)
438
391
 
439
392
  if (opts.traceSink) {
@@ -570,7 +523,7 @@ const ROOFTOP_NAMESAKE_LIMIT = 25
570
523
  *
571
524
  * A rooftop row is an observed point, so an unreconciled locality is never moved onto it.
572
525
  * The node records the distance as `rooftop_outside_locality_km`, and the result
573
- * reports the locality as a component the answer did not follow.
526
+ * reports the locality as a component the answer didn't follow.
574
527
  */
575
528
  export async function applyRooftopConsistency(
576
529
  roots: readonly AddressNode[],
@@ -0,0 +1,255 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ import { walkNodes, type AddressNode } from "@mailwoman/core/decoder"
5
+ import type { ResolverBackend } from "@mailwoman/core/resolver"
6
+ import { haversine } from "@mailwoman/spatial/geometries/point/distance"
7
+
8
+ import { decorateNode } from "#decorate-node"
9
+ import { streetNumberPairs } from "#street/tier"
10
+
11
+ /**
12
+ * Reads a street address's region as the city of the same name when the
13
+ * gazetteer holds one inside that region.
14
+ *
15
+ * `34 Lê Duẩn, Sài Gòn, Hồ Chí Minh, Vietnam` parses with a region and no locality.
16
+ * The region's point can lie far from the street, and the address-point lookup
17
+ * has no locality to search around.
18
+ *
19
+ * A place held at both levels occurs wherever a city is its own province, so the test reads the hierarchy.
20
+ *
21
+ * `Altona, Hamburg` and `Triana, Sevilla` state a resolved district, and a district also sits inside a city.
22
+ *
23
+ * A bare region stays a region, because only a street and number or a district
24
+ * say the input means somewhere inside a city.
25
+ *
26
+ * A locality the gazetteer didn't resolve leaves the region as the only place,
27
+ * and Bristol's region point lies in the Bristol Channel, so the city answers there too.
28
+ */
29
+ export async function applyRegionCity(roots: AddressNode[], backend: ResolverBackend): Promise<void> {
30
+ const nodes = [...walkNodes(roots)]
31
+
32
+ // A street with a number, or a resolved district, places the input inside a city.
33
+ const insideACity =
34
+ streetNumberPairs(roots).length > 0 || nodes.some((node) => node.tag === "dependent_locality" && node.placeID)
35
+
36
+ if (nodes.some((node) => node.tag === "locality" && node.placeID) || !insideACity) return
37
+
38
+ const region = nodes.find((node) => node.tag === "region" && node.placeID?.startsWith("wof:"))
39
+
40
+ if (!region) return
41
+
42
+ const [city, ...others] = await backend.findPlace({
43
+ text: region.value,
44
+ placetype: "locality",
45
+ parentID: Number(region.placeID!.slice("wof:".length)),
46
+ })
47
+
48
+ // A lookup that finds the name only outside the parent answers with that place and marks the miss.
49
+ if (!city?.exactMatch || city.regionScopeMiss) return
50
+
51
+ region.tag = "locality"
52
+ decorateNode(region, city, others)
53
+ region.metadata = { ...region.metadata, region_city: true }
54
+
55
+ // A district inside the city's box answers ahead of the city, as the walk's containment stamp lets it.
56
+ for (const district of nodes) {
57
+ if (district.tag !== "dependent_locality" || !district.placeID || district.lat == null || district.lon == null)
58
+ continue
59
+
60
+ const box = city.bbox
61
+
62
+ if (
63
+ box &&
64
+ district.lat >= box.minLat &&
65
+ district.lat <= box.maxLat &&
66
+ district.lon >= box.minLon &&
67
+ district.lon <= box.maxLon
68
+ ) {
69
+ district.metadata = { ...district.metadata, contained_by_parent: true }
70
+ }
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Reads a locality the gazetteer holds only as a region, inside a country the input states.
76
+ *
77
+ * `Likiep Atoll, RMI` parses the atoll as a locality, and the Marshall Islands hold it as a region.
78
+ * This runs after the locality band missed, so a place with a locality row keeps it.
79
+ */
80
+ export async function applyLocalityAsRegion(
81
+ roots: AddressNode[],
82
+ backend: ResolverBackend,
83
+ country: string
84
+ ): Promise<void> {
85
+ const nodes = [...walkNodes(roots)]
86
+ const locality = nodes.find((node) => node.tag === "locality" && !node.placeID && node.value.trim())
87
+
88
+ if (!locality || nodes.some((node) => node.tag === "region" && node.placeID)) return
89
+
90
+ const [region, ...others] = await backend.findPlace({ text: locality.value, placetype: "region", country })
91
+
92
+ if (!region?.exactMatch || region.country !== country) return
93
+
94
+ locality.tag = "region"
95
+ decorateNode(locality, region, others)
96
+ }
97
+
98
+ /**
99
+ * Reads a country as the region of the same name when only that region holds the stated town.
100
+ *
101
+ * `Savannah, Georgia` parses `Georgia` as the country, and the country holds no Savannah.
102
+ * `Tbilisi, Georgia` keeps the country, because the country holds Tbilisi.
103
+ *
104
+ * A caller's US scope leaves the country of Georgia unresolved, so that node has no country to test against.
105
+ */
106
+ export async function applyCountryAsRegion(roots: AddressNode[], backend: ResolverBackend): Promise<void> {
107
+ const nodes = [...walkNodes(roots)]
108
+ const country = nodes.find((node) => node.tag === "country" && node.value.trim())
109
+ const locality = nodes.find((node) => node.tag === "locality" && node.value.trim())
110
+
111
+ if (!country || !locality || nodes.some((node) => node.tag === "region")) return
112
+
113
+ const stated = country.metadata?.["resolver_country"]
114
+
115
+ if (typeof stated === "string") {
116
+ const [local] = await backend.findPlace({ text: locality.value, placetype: "locality", country: stated })
117
+
118
+ if (local?.exactMatch) return
119
+ }
120
+
121
+ for (const region of await backend.findPlace({ text: country.value, placetype: "region" })) {
122
+ if (!region.exactMatch) continue
123
+
124
+ const [city, ...others] = await backend.findPlace({
125
+ text: locality.value,
126
+ placetype: "locality",
127
+ parentID: region.id,
128
+ })
129
+
130
+ if (!city?.exactMatch || city.regionScopeMiss) continue
131
+
132
+ country.tag = "region"
133
+ decorateNode(country, region, [])
134
+ decorateNode(locality, city, others)
135
+
136
+ return
137
+ }
138
+ }
139
+
140
+ /**
141
+ * The tags whose spans together write a street's name.
142
+ */
143
+ const STREET_PART_TAGS: ReadonlySet<string> = new Set([
144
+ "street_prefix",
145
+ "street_prefix_particle",
146
+ "street",
147
+ "street_suffix",
148
+ ])
149
+
150
+ /**
151
+ * How far a town may sit from the stated postcode's point and still be the place the postcode serves.
152
+ */
153
+ const TOWN_POSTCODE_REACH_KM = 15
154
+
155
+ /**
156
+ * Removes the given nodes wherever they sit in the tree.
157
+ */
158
+ function removeNodes(list: AddressNode[], drop: ReadonlySet<AddressNode>): void {
159
+ for (let index = list.length - 1; index >= 0; index--) {
160
+ const node = list[index]!
161
+
162
+ if (drop.has(node)) {
163
+ list.splice(index, 1)
164
+ } else if (node.children?.length) {
165
+ removeNodes(node.children, drop)
166
+ }
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Reads an unnumbered street as the town of that name when the town holds the stated postcode.
172
+ *
173
+ * `Alameda, CA 94501` and `Crocketts Bluff, AR 72038` parse the town as a street,
174
+ * because a name before a region and postcode is where a street sits in a full address.
175
+ * A street name and a town name agree this close to the postcode's point only when they
176
+ * name one place, so a real street such as `Main Street, CA 94501` keeps its tag.
177
+ */
178
+ export async function applyStreetAsTown(roots: AddressNode[], backend: ResolverBackend): Promise<void> {
179
+ const nodes = [...walkNodes(roots)]
180
+ const parts = nodes.filter((node) => STREET_PART_TAGS.has(node.tag)).toSorted((a, b) => a.start - b.start)
181
+ const postcode = nodes.find((node) => node.tag === "postcode" && node.lat != null && node.lon != null)
182
+
183
+ if (!parts.some((node) => node.tag === "street") || !postcode) return
184
+
185
+ if (nodes.some((node) => node.tag === "house_number" || node.tag === "locality" || node.tag === "venue")) return
186
+
187
+ const region = nodes.find((node) => node.tag === "region" && node.placeID?.startsWith("wof:"))
188
+ const country = postcode.metadata?.["resolver_country"]
189
+
190
+ if (!region && typeof country !== "string") return
191
+
192
+ const name = parts.map((node) => node.value.trim()).join(" ")
193
+
194
+ const [town, ...others] = await backend.findPlace({
195
+ text: name,
196
+ placetype: "locality",
197
+ ...(region ? { parentID: Number(region.placeID!.slice("wof:".length)) } : { country: country as string }),
198
+ })
199
+
200
+ if (!town?.exactMatch || town.regionScopeMiss || town.lat == null || town.lon == null) return
201
+
202
+ if (haversine(postcode.lat!, postcode.lon!, town.lat, town.lon, "km") > TOWN_POSTCODE_REACH_KM) return
203
+
204
+ const [first, ...rest] = parts
205
+
206
+ first!.tag = "locality"
207
+ first!.value = name
208
+ first!.end = parts.at(-1)!.end
209
+ removeNodes(roots, new Set(rest))
210
+ decorateNode(first!, town, others)
211
+ first!.metadata = { ...first!.metadata, street_as_town: true }
212
+ }
213
+
214
+ /**
215
+ * Reads a venue as a town when the input states only a country beside it
216
+ * and the country holds a town of that name.
217
+ *
218
+ * `Road Town, British Virgin Islands` parses the town as a venue.
219
+ * This runs ahead of the landmark layer, so an airport alias under `Biggin Hill`
220
+ * yields to the town that holds the name.
221
+ */
222
+ export async function applyVenueAsTown(roots: AddressNode[], backend: ResolverBackend): Promise<void> {
223
+ const nodes = [...walkNodes(roots)]
224
+ const venue = nodes.find((node) => node.tag === "venue" && !node.placeID && node.value.trim())
225
+
226
+ const country = nodes.find(
227
+ (node) => node.tag === "country" && typeof node.metadata?.["resolver_country"] === "string"
228
+ )
229
+
230
+ if (!venue || !country || nodes.some((node) => node !== venue && node !== country)) return
231
+
232
+ // A name written in two forms, `Derry/Londonderry` or `Biel/Bienne`, is read whole and then as each form.
233
+ const forms = [venue.value, ...venue.value.split("/").map((form) => form.trim())].filter(
234
+ (form, index, all) => form && all.indexOf(form) === index
235
+ )
236
+
237
+ let found: Awaited<ReturnType<ResolverBackend["findPlace"]>> = []
238
+
239
+ for (const form of forms) {
240
+ found = await backend.findPlace({
241
+ text: form,
242
+ placetype: "locality",
243
+ country: country.metadata!["resolver_country"] as string,
244
+ })
245
+
246
+ if (found[0]?.exactMatch) break
247
+ }
248
+
249
+ const [town, ...others] = found
250
+
251
+ if (!town?.exactMatch) return
252
+
253
+ venue.tag = "locality"
254
+ decorateNode(venue, town, others)
255
+ }
@@ -0,0 +1,49 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ import { walkNodes, type AddressNode } from "@mailwoman/core/decoder"
5
+ import type { ResolverBackend } from "@mailwoman/core/resolver"
6
+
7
+ import { decorateNode } from "#decorate-node"
8
+
9
+ /**
10
+ * A character that separates the parts of an address in some script.
11
+ */
12
+ const SEPARATOR = /[\s,,、;;/|·・]/u
13
+
14
+ /**
15
+ * Reads an input as one place when its whole text names that place and the parse resolved none of its parts.
16
+ *
17
+ * `ミュンヘン` and `裕廊东` hold no separator.
18
+ * The en-US parser reads them as a venue, or splits them into fragments the
19
+ * gazetteer doesn't key, while it keys both whole names.
20
+ *
21
+ * An unspaced address whose parts resolve, or whose whole text identifies no place, keeps its parse.
22
+ * This runs after the landmark layer, so a venue the landmark layer knows keeps that answer.
23
+ */
24
+ export async function applyWholeInputPlace(
25
+ roots: AddressNode[],
26
+ written: string,
27
+ backend: ResolverBackend,
28
+ country: string | null
29
+ ): Promise<void> {
30
+ const text = written.trim()
31
+ const nodes = [...walkNodes(roots)]
32
+
33
+ if (!text || SEPARATOR.test(text) || nodes.some((node) => node.placeID)) return
34
+
35
+ // A lone admin span already looked up its whole text, under the placetype and scope the walk applies.
36
+ // Fragments and a venue span didn't.
37
+ if (nodes.length < 2 && nodes[0]?.tag !== "venue") return
38
+
39
+ const found = await backend.findPlace({ text, ...(country ? { country } : {}) }).catch(() => [])
40
+ const [place, ...others] = found
41
+
42
+ if (!place?.exactMatch) return
43
+
44
+ const whole = { tag: "locality", value: text, start: 0, end: text.length, confidence: 1, children: [] } as AddressNode
45
+
46
+ decorateNode(whole, place, others)
47
+ whole.metadata = { ...whole.metadata, whole_input_place: true }
48
+ roots.splice(0, roots.length, whole)
49
+ }