@mailwoman/resolver 9.1.0 → 9.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +89 -0
- package/lib/admin/coherence-passes.ts +435 -0
- package/lib/admin/containment.ts +92 -0
- package/lib/admin/index.ts +10 -0
- package/lib/admin/jp-municipality.ts +97 -0
- package/lib/admin/winner.ts +189 -0
- package/lib/backend-capabilities.ts +88 -0
- package/lib/bare-toponym-race.ts +129 -0
- package/lib/decorate-node.ts +127 -0
- package/lib/fold-name.ts +36 -0
- package/{index.ts → lib/index.ts} +27 -18
- package/{plausibility.ts → lib/plausibility.ts} +5 -4
- package/{postcode-country-coherence.ts → lib/postcode/country-coherence.ts} +173 -86
- package/lib/postcode/index.ts +9 -0
- package/{postcode-prefix.ts → lib/postcode/prefix.ts} +7 -6
- package/{postcode-shape-coherence.ts → lib/postcode/shape-coherence.ts} +10 -24
- package/{remote-resolver.ts → lib/remote-resolver.ts} +13 -4
- package/{rerank.ts → lib/rerank.ts} +2 -2
- package/lib/resolve/index.ts +982 -0
- package/lib/resolve/passes.ts +544 -0
- package/{span-rescore.ts → lib/span-rescore.ts} +114 -99
- package/{street-evidence.ts → lib/street/evidence.ts} +40 -7
- package/lib/street/index.ts +8 -0
- package/{street-tier.ts → lib/street/tier.ts} +138 -99
- package/{toponym-prior.ts → lib/toponym-prior.ts} +97 -8
- package/out/admin/coherence-passes.d.ts +70 -0
- package/out/admin/coherence-passes.d.ts.map +1 -0
- package/out/admin/coherence-passes.js +327 -0
- package/out/admin/coherence-passes.js.map +1 -0
- package/out/admin/containment.d.ts +48 -0
- package/out/admin/containment.d.ts.map +1 -0
- package/out/admin/containment.js +76 -0
- package/out/admin/containment.js.map +1 -0
- package/out/admin/index.d.ts +10 -0
- package/out/admin/index.d.ts.map +1 -0
- package/out/admin/index.js +10 -0
- package/out/admin/index.js.map +1 -0
- package/out/admin/jp-municipality.d.ts +50 -0
- package/out/admin/jp-municipality.d.ts.map +1 -0
- package/out/admin/jp-municipality.js +54 -0
- package/out/admin/jp-municipality.js.map +1 -0
- package/out/admin/winner.d.ts +114 -0
- package/out/admin/winner.d.ts.map +1 -0
- package/out/admin/winner.js +130 -0
- package/out/admin/winner.js.map +1 -0
- package/out/backend-capabilities.d.ts +37 -0
- package/out/backend-capabilities.d.ts.map +1 -0
- package/out/backend-capabilities.js +75 -0
- package/out/backend-capabilities.js.map +1 -0
- package/out/bare-toponym-race.d.ts +55 -0
- package/out/bare-toponym-race.d.ts.map +1 -0
- package/out/bare-toponym-race.js +110 -0
- package/out/bare-toponym-race.js.map +1 -0
- package/out/decorate-node.d.ts +24 -0
- package/out/decorate-node.d.ts.map +1 -0
- package/out/decorate-node.js +103 -0
- package/out/decorate-node.js.map +1 -0
- package/out/fold-name.d.ts +18 -3
- package/out/fold-name.d.ts.map +1 -1
- package/out/fold-name.js +19 -3
- package/out/fold-name.js.map +1 -1
- package/out/index.d.ts +15 -12
- package/out/index.d.ts.map +1 -1
- package/out/index.js +9 -7
- package/out/index.js.map +1 -1
- package/out/plausibility.d.ts +5 -4
- package/out/plausibility.d.ts.map +1 -1
- package/out/plausibility.js +5 -4
- package/out/plausibility.js.map +1 -1
- package/out/{postcode-country-coherence.d.ts → postcode/country-coherence.d.ts} +46 -25
- package/out/postcode/country-coherence.d.ts.map +1 -0
- package/out/{postcode-country-coherence.js → postcode/country-coherence.js} +157 -77
- package/out/postcode/country-coherence.js.map +1 -0
- package/out/postcode/index.d.ts +9 -0
- package/out/postcode/index.d.ts.map +1 -0
- package/out/postcode/index.js +9 -0
- package/out/postcode/index.js.map +1 -0
- package/out/{postcode-prefix.d.ts → postcode/prefix.d.ts} +4 -4
- package/out/postcode/prefix.d.ts.map +1 -0
- package/out/{postcode-prefix.js → postcode/prefix.js} +7 -6
- package/out/postcode/prefix.js.map +1 -0
- package/out/{postcode-shape-coherence.d.ts → postcode/shape-coherence.d.ts} +3 -3
- package/out/postcode/shape-coherence.d.ts.map +1 -0
- package/out/{postcode-shape-coherence.js → postcode/shape-coherence.js} +11 -20
- package/out/postcode/shape-coherence.js.map +1 -0
- package/out/remote-resolver.d.ts +18 -3
- package/out/remote-resolver.d.ts.map +1 -1
- package/out/remote-resolver.js +2 -2
- package/out/remote-resolver.js.map +1 -1
- package/out/rerank.d.ts +1 -1
- package/out/rerank.d.ts.map +1 -1
- package/out/rerank.js +2 -2
- package/out/rerank.js.map +1 -1
- package/out/{resolve.d.ts → resolve/index.d.ts} +2 -2
- package/out/resolve/index.d.ts.map +1 -0
- package/out/resolve/index.js +795 -0
- package/out/resolve/index.js.map +1 -0
- package/out/resolve/passes.d.ts +218 -0
- package/out/resolve/passes.d.ts.map +1 -0
- package/out/resolve/passes.js +333 -0
- package/out/resolve/passes.js.map +1 -0
- package/out/span-rescore.d.ts +16 -16
- package/out/span-rescore.d.ts.map +1 -1
- package/out/span-rescore.js +87 -71
- package/out/span-rescore.js.map +1 -1
- package/out/{street-evidence.d.ts → street/evidence.d.ts} +18 -3
- package/out/street/evidence.d.ts.map +1 -0
- package/out/{street-evidence.js → street/evidence.js} +23 -7
- package/out/street/evidence.js.map +1 -0
- package/out/street/index.d.ts +8 -0
- package/out/street/index.d.ts.map +1 -0
- package/out/street/index.js +8 -0
- package/out/street/index.js.map +1 -0
- package/out/{street-tier.d.ts → street/tier.d.ts} +14 -3
- package/out/street/tier.d.ts.map +1 -0
- package/out/{street-tier.js → street/tier.js} +127 -90
- package/out/street/tier.js.map +1 -0
- package/out/toponym-prior.d.ts +43 -19
- package/out/toponym-prior.d.ts.map +1 -1
- package/out/toponym-prior.js +76 -8
- package/out/toponym-prior.js.map +1 -1
- package/package.json +167 -19
- package/vitest.config.ts +5 -6
- package/fold-name.ts +0 -20
- package/out/postcode-country-coherence.d.ts.map +0 -1
- package/out/postcode-country-coherence.js.map +0 -1
- package/out/postcode-prefix.d.ts.map +0 -1
- package/out/postcode-prefix.js.map +0 -1
- package/out/postcode-shape-coherence.d.ts.map +0 -1
- package/out/postcode-shape-coherence.js.map +0 -1
- package/out/resolve.d.ts.map +0 -1
- package/out/resolve.js +0 -1049
- package/out/resolve.js.map +0 -1
- package/out/street-evidence.d.ts.map +0 -1
- package/out/street-evidence.js.map +0 -1
- package/out/street-tier.d.ts.map +0 -1
- package/out/street-tier.js.map +0 -1
- package/out/vitest.config.d.ts +0 -16
- package/out/vitest.config.d.ts.map +0 -1
- package/out/vitest.config.js +0 -36
- package/out/vitest.config.js.map +0 -1
- package/resolve.ts +0 -1369
|
@@ -0,0 +1,544 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
* @file The resolver walk's per-node machinery: the trace recorder and its diagnostic bands, the walk's
|
|
6
|
+
* `ResolutionState`, and the span-rescore / postcode-recovery / postcode-consistency passes the walk applies.
|
|
7
|
+
* Split from `resolve.ts`, which owns `WOFResolver` — the walk itself over what this module provides.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { walkNodes, type AddressNode } from "@mailwoman/core/decoder"
|
|
11
|
+
import {
|
|
12
|
+
type CoincidentLocality,
|
|
13
|
+
compareReferential,
|
|
14
|
+
type ResolveCandidateTrace,
|
|
15
|
+
type ResolveNodeTrace,
|
|
16
|
+
type PlacetypeMap,
|
|
17
|
+
type PostcodePrefixIndexLike,
|
|
18
|
+
referentialFromPopulation,
|
|
19
|
+
type ResolvedPlace,
|
|
20
|
+
type ResolveOpts,
|
|
21
|
+
type ResolverBackend,
|
|
22
|
+
} from "@mailwoman/core/resolver"
|
|
23
|
+
import { PLACETYPE_SPECIFICITY } from "@mailwoman/core/resources/whosonfirst/specificity"
|
|
24
|
+
import { haversineKm } from "@mailwoman/spatial"
|
|
25
|
+
|
|
26
|
+
import { decorateNode, isResolvedWithCoord } from "#decorate-node"
|
|
27
|
+
import type { CoordinateOptionalPlace } from "#postcode/prefix"
|
|
28
|
+
import { isShapeExcludedPostcode } from "#postcode/shape-coherence"
|
|
29
|
+
import { findRescoreCandidate, hasResolvedPlace, postcodeCodeSubset } from "#span-rescore"
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Cap on candidates recorded per {@link ResolveNodeTrace} — the trace is a record, not a dump. The count past the cap is
|
|
33
|
+
* reported in `candidatesTruncated`, so absence of a row is never silent.
|
|
34
|
+
*/
|
|
35
|
+
const TRACE_CANDIDATE_CAP = 10
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The fine end of the probe window: `microhood` and no finer.
|
|
39
|
+
*
|
|
40
|
+
* Everything above it — `postalcode`, `venue`, `campus`, `building`, `address` — is excluded because a mislabeled ADMIN
|
|
41
|
+
* span lands on another admin band, and probing every venue in a country per miss buys a long tail of coincidental name
|
|
42
|
+
* matches for a diagnostic that is meant to be read.
|
|
43
|
+
*/
|
|
44
|
+
const FINEST_DIAGNOSTIC_BAND = PLACETYPE_SPECIFICITY["microhood"]!
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The coarse end of the probe window. `country` and no coarser: a name matching at `continent` or `planet` says nothing
|
|
48
|
+
* about a mislabeled admin span, and the walk resolves the country from its own node anyway.
|
|
49
|
+
*/
|
|
50
|
+
const COARSEST_DIAGNOSTIC_BAND = PLACETYPE_SPECIFICITY["country"]!
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The admin bands `ResolveOpts.diagnoseUnreachable` re-probes, coarse to fine.
|
|
54
|
+
*
|
|
55
|
+
* Derived from `PLACETYPE_SPECIFICITY` rather than typed out, so a placetype added there is probed here without anyone
|
|
56
|
+
* remembering to.
|
|
57
|
+
*/
|
|
58
|
+
export const DIAGNOSTIC_BANDS: readonly string[] = Object.entries(PLACETYPE_SPECIFICITY)
|
|
59
|
+
.filter(([, rank]) => rank !== undefined && rank <= FINEST_DIAGNOSTIC_BAND && rank >= COARSEST_DIAGNOSTIC_BAND)
|
|
60
|
+
.toSorted((a, b) => (a[1] as number) - (b[1] as number))
|
|
61
|
+
.map(([placetype]) => placetype)
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Per-lookup trace bookkeeping (#1721). `#lookupAndPick` talks to ONE of these unconditionally — a real recorder when
|
|
65
|
+
* `ResolveOpts.traceSink` is set, the frozen {@link NOOP_TRACE_RECORDER} otherwise — so the hot path carries no
|
|
66
|
+
* per-event branches and the no-sink walk costs a handful of empty calls per node.
|
|
67
|
+
*/
|
|
68
|
+
export interface NodeTraceRecorder {
|
|
69
|
+
bind(
|
|
70
|
+
node: AddressNode,
|
|
71
|
+
placetype: string,
|
|
72
|
+
query: {
|
|
73
|
+
country?: string
|
|
74
|
+
parentID?: string | number
|
|
75
|
+
postcode?: string
|
|
76
|
+
regionQualifier?: string
|
|
77
|
+
limit?: number
|
|
78
|
+
},
|
|
79
|
+
defaultLimit: number
|
|
80
|
+
): void
|
|
81
|
+
check(name: string): void
|
|
82
|
+
stage(name: string, order: readonly ResolvedPlace[]): void
|
|
83
|
+
reachable(bands: NonNullable<ResolveNodeTrace["reachableIn"]>): void
|
|
84
|
+
emit(picked: NonNullable<ResolveNodeTrace["picked"]> | null): void
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* A recorder that records nothing — the walk's default when no trace was requested.
|
|
89
|
+
*/
|
|
90
|
+
export const NOOP_TRACE_RECORDER: NodeTraceRecorder = Object.freeze({
|
|
91
|
+
bind() {},
|
|
92
|
+
check() {},
|
|
93
|
+
stage() {},
|
|
94
|
+
reachable() {},
|
|
95
|
+
emit() {},
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
export function createNodeTraceRecorder(sink: (record: ResolveNodeTrace) => void): NodeTraceRecorder {
|
|
99
|
+
const checks: string[] = []
|
|
100
|
+
const stageOrders: Array<[string, readonly ResolvedPlace[]]> = []
|
|
101
|
+
|
|
102
|
+
let reachableIn: ResolveNodeTrace["reachableIn"]
|
|
103
|
+
|
|
104
|
+
let ctx: {
|
|
105
|
+
node: AddressNode
|
|
106
|
+
placetype: string
|
|
107
|
+
query: Parameters<NodeTraceRecorder["bind"]>[2]
|
|
108
|
+
defaultLimit: number
|
|
109
|
+
} | null = null
|
|
110
|
+
|
|
111
|
+
return {
|
|
112
|
+
bind(node, placetype, query, defaultLimit) {
|
|
113
|
+
ctx = { node, placetype, query, defaultLimit }
|
|
114
|
+
},
|
|
115
|
+
check(name) {
|
|
116
|
+
checks.push(name)
|
|
117
|
+
},
|
|
118
|
+
stage(name, order) {
|
|
119
|
+
stageOrders.push([name, order])
|
|
120
|
+
},
|
|
121
|
+
reachable(bands) {
|
|
122
|
+
reachableIn = bands
|
|
123
|
+
},
|
|
124
|
+
emit(picked) {
|
|
125
|
+
if (!ctx) return
|
|
126
|
+
|
|
127
|
+
const rankMap = new Map<ResolvedPlace, Record<string, number>>()
|
|
128
|
+
|
|
129
|
+
for (const [stage, order] of stageOrders) {
|
|
130
|
+
order.forEach((candidate, index) => {
|
|
131
|
+
let ranks = rankMap.get(candidate)
|
|
132
|
+
|
|
133
|
+
if (!ranks) {
|
|
134
|
+
ranks = {}
|
|
135
|
+
rankMap.set(candidate, ranks)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
ranks[stage] = index + 1
|
|
139
|
+
})
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const finalOrder = stageOrders.at(-1)?.[1] ?? []
|
|
143
|
+
|
|
144
|
+
const rows: ResolveCandidateTrace[] = finalOrder.slice(0, TRACE_CANDIDATE_CAP).map((c) => ({
|
|
145
|
+
id: c.id,
|
|
146
|
+
name: c.name,
|
|
147
|
+
country: c.country,
|
|
148
|
+
placetype: c.placetype,
|
|
149
|
+
score: c.score,
|
|
150
|
+
...(c.prominence !== undefined ? { prominence: c.prominence } : {}),
|
|
151
|
+
...(c.importance !== undefined ? { importance: c.importance } : {}),
|
|
152
|
+
...(c.population !== undefined ? { population: c.population } : {}),
|
|
153
|
+
...(c.exactMatch !== undefined ? { exactMatch: c.exactMatch } : {}),
|
|
154
|
+
...(c.containedByQualifier !== undefined ? { containedByQualifier: c.containedByQualifier } : {}),
|
|
155
|
+
ranks: rankMap.get(c) ?? {},
|
|
156
|
+
}))
|
|
157
|
+
|
|
158
|
+
sink({
|
|
159
|
+
tag: ctx.node.tag,
|
|
160
|
+
value: ctx.node.value,
|
|
161
|
+
placetype: ctx.placetype,
|
|
162
|
+
query: {
|
|
163
|
+
...(ctx.query.country ? { country: ctx.query.country } : {}),
|
|
164
|
+
...(ctx.query.parentID !== undefined ? { parentID: ctx.query.parentID } : {}),
|
|
165
|
+
...(ctx.query.postcode ? { postcode: ctx.query.postcode } : {}),
|
|
166
|
+
...(ctx.query.regionQualifier ? { regionQualifier: ctx.query.regionQualifier } : {}),
|
|
167
|
+
limit: ctx.query.limit ?? ctx.defaultLimit,
|
|
168
|
+
},
|
|
169
|
+
checks,
|
|
170
|
+
...(reachableIn ? { reachableIn } : {}),
|
|
171
|
+
candidates: rows,
|
|
172
|
+
candidatesTruncated: Math.max(0, finalOrder.length - TRACE_CANDIDATE_CAP),
|
|
173
|
+
picked,
|
|
174
|
+
})
|
|
175
|
+
},
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export interface ResolutionState {
|
|
180
|
+
lookupsRemaining: number
|
|
181
|
+
placetypeMap: PlacetypeMap
|
|
182
|
+
minWinningScore: number
|
|
183
|
+
candidatesPerLookup: number
|
|
184
|
+
defaultCountry?: string
|
|
185
|
+
/**
|
|
186
|
+
* Whether {@link defaultCountry} came from the locale rather than the caller. Consulted only by `country`-placetype
|
|
187
|
+
* lookups, which skip an inferred scope — see `ResolveOpts.defaultCountryIsInferred`.
|
|
188
|
+
*/
|
|
189
|
+
defaultCountryIsInferred: boolean
|
|
190
|
+
/**
|
|
191
|
+
* The tree's single value-bearing node when it is locality-tagged (the bare-toponym shape), else null. Checks the
|
|
192
|
+
* country-placetype sibling race in `#lookupAndPick` — a bare name can be a country the parser tagged `locality`
|
|
193
|
+
* ("Japan", "China"), and the locality placetype filter makes the country row unreachable no matter how it ranks.
|
|
194
|
+
*/
|
|
195
|
+
bareLocalityNode: AddressNode | null
|
|
196
|
+
parentFallback: boolean
|
|
197
|
+
/**
|
|
198
|
+
* The address's postcode string, extracted once up front, passed to locality lookups so a coordinate-first backend
|
|
199
|
+
* can inject postcode-proximal locality candidates.
|
|
200
|
+
*/
|
|
201
|
+
postcode?: string
|
|
202
|
+
/**
|
|
203
|
+
* Postcode-containment coherence (#31, Mechanism 2) — forwarded to locality lookups so a coordinate-first backend can
|
|
204
|
+
* re-rank name candidates by proximity to the postcode's own centroid. Opt-in; OFF by default.
|
|
205
|
+
*/
|
|
206
|
+
postcodeContainmentCoherence: boolean
|
|
207
|
+
/**
|
|
208
|
+
* Postcode-prefix prior (#31, Mechanism 3) — on a `postalcode` miss, derive the code's prefix and probe
|
|
209
|
+
* `postcodePrefixIndex`. Opt-in; OFF by default.
|
|
210
|
+
*/
|
|
211
|
+
postcodePrefixPrior: boolean
|
|
212
|
+
/**
|
|
213
|
+
* #1589 — the countries the parsed postcode's FORMAT implies (the #928 singles plus the shared `NNN NN` family). When
|
|
214
|
+
* set AND no country constraint survives, the `postalcode` lookup probes exactly these countries and abstains if all
|
|
215
|
+
* miss — never falling through to an unconstrained probe, whose space-stripped fold collides across systems (`100 00`
|
|
216
|
+
* folded to `10000` answers Troyes FR while Prague sits in the artifact under both keyings).
|
|
217
|
+
*/
|
|
218
|
+
postcodeFormatCountries?: readonly string[]
|
|
219
|
+
/**
|
|
220
|
+
* #1585 — the locale hint's country, forwarded to the backend as `fuzzyCountry` on every primary lookup. Scopes the
|
|
221
|
+
* typo-fuzzy tier only; exact matches stay worldwide. See `ResolveOpts.fuzzyCountryScope`.
|
|
222
|
+
*/
|
|
223
|
+
fuzzyCountryScope?: string
|
|
224
|
+
/**
|
|
225
|
+
* The injected PFX1 index (structural — `PostcodePrefixIndexLike`, core/resolver/types.ts). Absent = the prior cannot
|
|
226
|
+
* fire.
|
|
227
|
+
*/
|
|
228
|
+
postcodePrefixIndex?: PostcodePrefixIndexLike
|
|
229
|
+
/**
|
|
230
|
+
* Proximity-bias points (viewport, user location) — forwarded to every primary lookup.
|
|
231
|
+
*/
|
|
232
|
+
bias?: Array<{ lat: number; lon: number; weight?: number }>
|
|
233
|
+
/**
|
|
234
|
+
* Postcode-anchor country posterior (#369). Undefined = no re-rank (byte-stable default).
|
|
235
|
+
*/
|
|
236
|
+
anchorPosterior?: Record<string, number>
|
|
237
|
+
/**
|
|
238
|
+
* Weight on the posterior in the locality re-rank. Only used when `anchorPosterior` is set.
|
|
239
|
+
*/
|
|
240
|
+
anchorWeight: number
|
|
241
|
+
/**
|
|
242
|
+
* #1721 resolver-interior trace sink. Undefined (the default) = zero bookkeeping, byte-identical walk.
|
|
243
|
+
*/
|
|
244
|
+
traceSink?: (record: ResolveNodeTrace) => void
|
|
245
|
+
/**
|
|
246
|
+
* Re-probe a resolved-nothing lookup across the other admin bands and record which hold it. Diagnostic only — never
|
|
247
|
+
* reaches the pick. See `ResolveOpts.diagnoseUnreachable`.
|
|
248
|
+
*/
|
|
249
|
+
diagnoseUnreachable?: boolean
|
|
250
|
+
/**
|
|
251
|
+
* #27 locale-country SOFT prior for the bare-toponym admin walk. Undefined = no prior (the shipped default) →
|
|
252
|
+
* byte-stable. See `ResolveOpts.localeCountryPrior` for the calibration and why it ships opt-in.
|
|
253
|
+
*/
|
|
254
|
+
localeCountryPrior?: string
|
|
255
|
+
/**
|
|
256
|
+
* Weight of that prior in log10-population units. Only consulted when `localeCountryPrior` is set.
|
|
257
|
+
*/
|
|
258
|
+
localeCountryPriorWeight: number
|
|
259
|
+
/**
|
|
260
|
+
* #1880 capital status per candidate, from `ResolveOpts.capitalLevel`. Undefined → no promotion, byte-stable.
|
|
261
|
+
*/
|
|
262
|
+
capitalLevel?: (place: { name: string; country?: string; lat: number; lon: number }) => number
|
|
263
|
+
/**
|
|
264
|
+
* #743/#194 confident-placer country as a HARD filter (empty→unresolved, no global retry). Off = undefined.
|
|
265
|
+
*/
|
|
266
|
+
hardCountry?: string
|
|
267
|
+
/**
|
|
268
|
+
* Dual-role hierarchy completion (#405). Off by default → byte-stable.
|
|
269
|
+
*/
|
|
270
|
+
hierarchyCompletion: boolean
|
|
271
|
+
/**
|
|
272
|
+
* Attach ancestor lineage to each resolved node (#404). Off by default → byte-stable.
|
|
273
|
+
*/
|
|
274
|
+
includeAncestors: boolean
|
|
275
|
+
/**
|
|
276
|
+
* Admin-containment re-rank (#1717 stage 2). Off by default → byte-stable. See `ResolveOpts.adminContainmentRerank`.
|
|
277
|
+
*/
|
|
278
|
+
adminContainmentRerank: boolean
|
|
279
|
+
/**
|
|
280
|
+
* The tree's first parsed region-tagged span, extracted once up front (the `postcode` pattern above — region and
|
|
281
|
+
* locality are siblings, so the top-down walk wouldn't otherwise let the locality lookup see it). Only consulted when
|
|
282
|
+
* {@link adminContainmentRerank} is on.
|
|
283
|
+
*/
|
|
284
|
+
regionQualifier?: string
|
|
285
|
+
/**
|
|
286
|
+
* Set while resolving when ANY tree node maps to the `locality` placetype (resolved or not) — the completion only
|
|
287
|
+
* fires when the parser emitted no locality at all, never to override one.
|
|
288
|
+
*/
|
|
289
|
+
localityNodePresent: boolean
|
|
290
|
+
/**
|
|
291
|
+
* The first region that resolved (its place — for the coincident-roles lookup).
|
|
292
|
+
*/
|
|
293
|
+
resolvedRegion: CoordinateOptionalPlace | null
|
|
294
|
+
/**
|
|
295
|
+
* The decorated region NODE that produced {@link resolvedRegion} — completion pushes the locality interpretation onto
|
|
296
|
+
* it in place (no synthesized sibling).
|
|
297
|
+
*/
|
|
298
|
+
resolvedRegionNode: AddressNode | null
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Pick the completion locality when an admin maps to several coincident same-name candidates (#405). REFERENTIAL
|
|
303
|
+
* likelihood is the PRIMARY signal — the principal city is the populous one, and it can sit FARTHER from the admin
|
|
304
|
+
* centroid than a tiny same-name hamlet (the Niigata case from #403). Nearest centroid breaks a referential tie; a
|
|
305
|
+
* genuine tie (same population AND distance) ABSTAINS rather than guess.
|
|
306
|
+
*
|
|
307
|
+
* ROAD_TO_V9 §2: `compareReferential` is referential DESC with raw population as its own tiebreak, which is the SAME
|
|
308
|
+
* ORDER as the plain `b.population - a.population` it replaced — referential is strictly increasing in population below
|
|
309
|
+
* saturation and constant above it. The abstention check below still reads raw population, deliberately: two megacities
|
|
310
|
+
* that saturate to the same referential score are not tied, and abstaining there would be a new behavior.
|
|
311
|
+
*/
|
|
312
|
+
export function pickCompletion(candidates: readonly CoincidentLocality[]): CoincidentLocality | null {
|
|
313
|
+
if (!candidates.length) return null
|
|
314
|
+
|
|
315
|
+
if (candidates.length === 1) return candidates[0]!
|
|
316
|
+
|
|
317
|
+
const ranked = [...candidates]
|
|
318
|
+
.map((c) => ({ c, referential: referentialFromPopulation(c.population), population: c.population }))
|
|
319
|
+
// oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
|
|
320
|
+
.sort((a, b) => compareReferential(a, b) || a.c.distanceKm - b.c.distanceKm)
|
|
321
|
+
.map((x) => x.c)
|
|
322
|
+
|
|
323
|
+
const [first, second] = ranked
|
|
324
|
+
|
|
325
|
+
if (first!.population === second!.population && first!.distanceKm === second!.distanceKm) return null
|
|
326
|
+
|
|
327
|
+
return first!
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Find the first postcode value anywhere in the tree (a one-shot pre-scan; postcode and locality are siblings, so the
|
|
332
|
+
* top-down walk wouldn't otherwise let the locality lookup see it).
|
|
333
|
+
*/
|
|
334
|
+
export function firstPostcodeValue(roots: readonly AddressNode[]): string | undefined {
|
|
335
|
+
for (const n of walkNodes(roots)) {
|
|
336
|
+
// #31 Mechanism 1: a shape-excluded span keeps its tag but contributes nothing — its code
|
|
337
|
+
// must never become the address's postcode (it would poison the country-scope pass's anchor).
|
|
338
|
+
if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && n.value.trim().length) return n.value.trim()
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
return undefined
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Span-rescore tier (#370): opt-in last-resort locality recovery. Runs ONLY when the tree resolved NOTHING (the #685
|
|
346
|
+
* brake — never disturb a working coordinate). Enumerates raw-token spans, exact- matches the same-country gazetteer
|
|
347
|
+
* (longest-wins + postcode-consistency check; see `span-rescore.ts`), and on a hit INJECTS a resolved `locality` node
|
|
348
|
+
* decorated exactly like a normally-resolved one. Default-ON (#370, promoted 2026-06-25); byte-stable opt-out via
|
|
349
|
+
* `opts.spanRescore: false`. Async (it queries the backend), so it's awaited.
|
|
350
|
+
*/
|
|
351
|
+
export async function applySpanRescore(
|
|
352
|
+
roots: AddressNode[],
|
|
353
|
+
raw: string,
|
|
354
|
+
backend: ResolverBackend,
|
|
355
|
+
opts: ResolveOpts
|
|
356
|
+
): Promise<void> {
|
|
357
|
+
if (hasResolvedPlace(roots)) return // already resolved — never second-guess a working coordinate
|
|
358
|
+
// Default-ON since 2026-06-25, so this runs on every unresolved tree — a backend hiccup here must
|
|
359
|
+
// degrade to no-rescore, never crash the resolve (the same fall-through the main walk gives).
|
|
360
|
+
let hit
|
|
361
|
+
|
|
362
|
+
try {
|
|
363
|
+
hit = await findRescoreCandidate(raw, roots, backend, {
|
|
364
|
+
country: opts.defaultCountry,
|
|
365
|
+
postcode: firstPostcodeValue(roots),
|
|
366
|
+
thresholdKm: opts.spanRescoreThresholdKm,
|
|
367
|
+
// Default-ON (promoted 2026-07-03); explicit `false` opts out — the spanRescore idiom.
|
|
368
|
+
postalCompoundRecovery: opts.postalCompoundRecovery !== false,
|
|
369
|
+
})
|
|
370
|
+
} catch {
|
|
371
|
+
return
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// #942 postal-compound recovery, part 2: when NO city span matched, decorate the FAILED postcode
|
|
375
|
+
// node from its code-shaped token subset ("1382 Kožljek" → the bare "1382" row) — a postcode-tier
|
|
376
|
+
// coordinate FLOOR, strictly subordinate to a recovered locality. Only-on-miss matters: a GeoNames
|
|
377
|
+
// medoid postcode centroid is COARSER than the exact village centroid, and consumers that rank
|
|
378
|
+
// postcode above locality (the eval harness does) would otherwise trade a 0.2 km village pin for a
|
|
379
|
+
// 5 km area centroid. Same unresolved tree, so the #685 brake semantics hold.
|
|
380
|
+
if (!hit && opts.postalCompoundRecovery !== false) {
|
|
381
|
+
try {
|
|
382
|
+
await recoverPostcodeNode(roots, backend, opts.defaultCountry, opts.traceSink)
|
|
383
|
+
} catch {
|
|
384
|
+
// degrade to no-recovery, never crash the resolve
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
if (!hit) return
|
|
389
|
+
|
|
390
|
+
const node: AddressNode = {
|
|
391
|
+
tag: "locality",
|
|
392
|
+
value: hit.text,
|
|
393
|
+
start: hit.start,
|
|
394
|
+
end: hit.end,
|
|
395
|
+
// No model confidence for a post-hoc recovery; a mid-tier value marks it as recovered, not asserted.
|
|
396
|
+
confidence: 0.5,
|
|
397
|
+
children: [],
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// #1537: the same-span namesake runner-ups, not an empty list. A name the model reads as a `street`
|
|
401
|
+
// ("Springfield", "Berlin", "Moscow") never reaches the admin walk, so this tier is the ONLY thing that
|
|
402
|
+
// resolves it — and decorating with `[]` meant the geocode path's `candidates` held one entry and the
|
|
403
|
+
// dominance margin `declared_ambiguity` reads was uncomputable for exactly the famous-homonym class.
|
|
404
|
+
// The winner is unchanged (see findRescoreCandidate); this is additive.
|
|
405
|
+
decorateNode(node, hit.place, hit.alternatives)
|
|
406
|
+
// `rescore_postcode_verified` carries the check's precision signal as an EXPLICIT handle — NOT folded into the
|
|
407
|
+
// calibrated `confidence`, which would break the isotonic guarantee (a true calibrated 0.83 must not
|
|
408
|
+
// be confused with a rescore plug-in estimate; DeepSeek 2026-06-23). true = postcode check fired
|
|
409
|
+
// (high-precision); false = unrestricted (no postcode→point coverage for this country, ~83%-precision).
|
|
410
|
+
node.metadata = { ...node.metadata, span_rescore: true, rescore_postcode_verified: hit.postcodeVerified }
|
|
411
|
+
roots.push(node)
|
|
412
|
+
|
|
413
|
+
// #1721 follow-up: this tier answers OFF the walk, and it used to answer off the record too — the famous-name
|
|
414
|
+
// class ("Frankfurt") returned a coordinate beside an empty resolver trace, blinding every retrieval account.
|
|
415
|
+
// One record per rescue keeps the trace's promise: no resolved coordinate without a lookup record.
|
|
416
|
+
if (opts.traceSink) {
|
|
417
|
+
const rec = createNodeTraceRecorder(opts.traceSink)
|
|
418
|
+
|
|
419
|
+
rec.bind(node, "locality", opts.defaultCountry ? { country: opts.defaultCountry } : {}, 1)
|
|
420
|
+
rec.check("span_rescore")
|
|
421
|
+
rec.check(hit.postcodeVerified ? "rescore_postcode_verified" : "rescore_postcode_unverified")
|
|
422
|
+
rec.stage("rescore", [hit.place, ...hit.alternatives])
|
|
423
|
+
rec.emit({ id: hit.place.id, name: hit.place.name, source: "span_rescore" })
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* #942: find the first confident-but-UNRESOLVED postcode node whose value is a polluted compound ("1382 Kožljek"),
|
|
429
|
+
* resolve its code-shaped token subset as a `postalcode`, and decorate the node from that hit
|
|
430
|
+
* (`postal_compound_recovered` metadata marks the provenance). No-op when every postcode node resolved, the value has
|
|
431
|
+
* no digit-bearing tokens, or the subset equals the full value (then the walk already tried it).
|
|
432
|
+
*/
|
|
433
|
+
async function recoverPostcodeNode(
|
|
434
|
+
roots: AddressNode[],
|
|
435
|
+
backend: ResolverBackend,
|
|
436
|
+
country: string | undefined,
|
|
437
|
+
traceSink?: (record: ResolveNodeTrace) => void
|
|
438
|
+
): Promise<void> {
|
|
439
|
+
for (const n of walkNodes(roots)) {
|
|
440
|
+
if (n.tag === "postcode" && !n.placeID && n.value.trim()) {
|
|
441
|
+
const code = postcodeCodeSubset(n.value)
|
|
442
|
+
|
|
443
|
+
if (!code || code === n.value.trim()) continue
|
|
444
|
+
const hits = await backend.findPlace({ text: code, placetype: "postalcode", country, limit: 1 })
|
|
445
|
+
const top = hits.find((h) => h.lat !== 0 || h.lon !== 0)
|
|
446
|
+
|
|
447
|
+
if (top) {
|
|
448
|
+
decorateNode(n, top, [])
|
|
449
|
+
n.metadata = { ...n.metadata, postal_compound_recovered: true }
|
|
450
|
+
|
|
451
|
+
// The same off-the-record hole the span-rescore record closes (#1721 follow-up).
|
|
452
|
+
if (traceSink) {
|
|
453
|
+
const rec = createNodeTraceRecorder(traceSink)
|
|
454
|
+
|
|
455
|
+
rec.bind(n, "postalcode", { ...(country ? { country } : {}), limit: 1 }, 1)
|
|
456
|
+
rec.check("postal_compound_recovery")
|
|
457
|
+
rec.stage("recovery", hits)
|
|
458
|
+
rec.emit({ id: top.id, name: top.name, source: "postal_compound_recovery" })
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
return // first postcode node only — one recovery per tree
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* Postcode-disambiguated locality selection (#370 "Change A"). The single biggest miss on the EU/AU panel is a
|
|
469
|
+
* same-named town resolved to the WRONG instance — "06260 Saint-Pierre" lands 617 km off — while the postcode that
|
|
470
|
+
* would disambiguate it (06260 → Alpes-Maritimes) sits resolved in the same tree, discarded because the
|
|
471
|
+
* coordinate-picker prefers the (wrong) locality node and never cross- checks it. This post-walk pass closes that loop,
|
|
472
|
+
* backend-agnostically and with no extra query:
|
|
473
|
+
*
|
|
474
|
+
* 1. Find the resolved postcode's coordinate (the trustworthy anchor — a postcode is unambiguous within a country in a way
|
|
475
|
+
* a town name is not).
|
|
476
|
+
* 2. For each resolved locality node farther than `thresholdKm` from it: re-pick the same-named candidate from the node's
|
|
477
|
+
* already-captured `alternatives` that is NEAREST the postcode and within the radius. This keeps locality
|
|
478
|
+
* granularity at the CORRECT instance.
|
|
479
|
+
* 3. If no alternative reconciles, the locality instance is unreliable — fall its coordinate back to the postcode point
|
|
480
|
+
* (right area, the safe answer) and flag `postcode_city_mismatch`.
|
|
481
|
+
*
|
|
482
|
+
* Only fires where the postcode resolved to a point, so it composes with postcode coverage (#193) — add a country's
|
|
483
|
+
* postcodes and this immediately disambiguates its same-named towns. **Default-ON** since the #370 operator promotion
|
|
484
|
+
* (2026-07-04, commit `0010bb8c`) — `opts.postcodeConsistency: false` opts out, and the pass is byte-stable on every
|
|
485
|
+
* tree with no resolved postcode point (the `!anchor` early return below).
|
|
486
|
+
*/
|
|
487
|
+
export function applyPostcodeConsistency(roots: readonly AddressNode[], thresholdKm: number): void {
|
|
488
|
+
// The resolved postcode anchor (first one with a real coordinate).
|
|
489
|
+
let anchor: { lat: number; lon: number } | null = null
|
|
490
|
+
|
|
491
|
+
for (const n of walkNodes(roots)) {
|
|
492
|
+
// #31 Mechanism 1: a shape-excluded span never anchors the consistency re-pick either.
|
|
493
|
+
if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && isResolvedWithCoord(n)) {
|
|
494
|
+
anchor = { lat: n.lat!, lon: n.lon! }
|
|
495
|
+
|
|
496
|
+
break
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// No postcode→point — nothing to disambiguate against (the check cannot fire).
|
|
501
|
+
if (!anchor) return
|
|
502
|
+
|
|
503
|
+
for (const node of walkNodes(roots)) {
|
|
504
|
+
if ((node.tag !== "locality" && node.tag !== "dependent_locality") || !isResolvedWithCoord(node)) continue
|
|
505
|
+
|
|
506
|
+
if (haversineKm(anchor.lat, anchor.lon, node.lat!, node.lon!) <= thresholdKm) continue // already consistent
|
|
507
|
+
|
|
508
|
+
// Re-pick: the same-named candidate nearest the postcode, within the radius. `alternatives` is
|
|
509
|
+
// typed `unknown[]` on the node (decoder/types.ts can't import resolver types) — they ARE the
|
|
510
|
+
// `ResolvedPlace` runner-ups decorateNode attached, so the cast is sound.
|
|
511
|
+
const alts = (node.alternatives as ResolvedPlace[] | undefined) ?? []
|
|
512
|
+
|
|
513
|
+
const reconciling = alts
|
|
514
|
+
.filter((a) => a.lat !== 0 || a.lon !== 0)
|
|
515
|
+
.map((a) => ({ a, d: haversineKm(anchor!.lat, anchor!.lon, a.lat, a.lon) }))
|
|
516
|
+
.filter((x) => x.d <= thresholdKm)
|
|
517
|
+
// oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
|
|
518
|
+
.sort((x, y) => x.d - y.d)[0]
|
|
519
|
+
|
|
520
|
+
if (reconciling) {
|
|
521
|
+
// Swap to the consistent instance; the displaced winner becomes an alternative.
|
|
522
|
+
const displaced: ResolvedPlace = {
|
|
523
|
+
id: 0,
|
|
524
|
+
name: String(node.metadata?.["resolver_name"] ?? node.value),
|
|
525
|
+
placetype: "locality",
|
|
526
|
+
country: reconciling.a.country,
|
|
527
|
+
lat: node.lat!,
|
|
528
|
+
lon: node.lon!,
|
|
529
|
+
score: 0,
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
const rest = alts.filter((a) => a !== reconciling.a)
|
|
533
|
+
decorateNode(node, reconciling.a, [displaced, ...rest])
|
|
534
|
+
node.metadata = { ...node.metadata, postcode_repicked: true }
|
|
535
|
+
|
|
536
|
+
continue
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// No same-named instance near the postcode → the town is unreliable; trust the postcode's area.
|
|
540
|
+
node.lat = anchor.lat
|
|
541
|
+
node.lon = anchor.lon
|
|
542
|
+
node.metadata = { ...node.metadata, postcode_city_mismatch: true, coordinate_source: "postcode_fallback" }
|
|
543
|
+
}
|
|
544
|
+
}
|