@mailwoman/resolver 9.2.0 → 9.4.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 +5 -5
- package/{admin-coherence-passes.ts → lib/admin/coherence-passes.ts} +87 -9
- package/{admin-containment.ts → lib/admin/containment.ts} +5 -14
- package/lib/admin/index.ts +10 -0
- package/lib/admin/jp-municipality.ts +97 -0
- package/{admin-winner.ts → lib/admin/winner.ts} +18 -2
- package/{backend-capabilities.ts → lib/backend-capabilities.ts} +3 -3
- package/{bare-toponym-race.ts → lib/bare-toponym-race.ts} +1 -1
- package/{decorate-node.ts → lib/decorate-node.ts} +2 -2
- package/{fold-name.ts → lib/fold-name.ts} +2 -2
- package/{index.ts → lib/index.ts} +16 -22
- package/{plausibility.ts → lib/plausibility.ts} +5 -4
- package/{postcode-country-coherence.ts → lib/postcode/country-coherence.ts} +27 -32
- package/lib/postcode/index.ts +9 -0
- package/{postcode-prefix.ts → lib/postcode/prefix.ts} +4 -4
- 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/{resolve.ts → lib/resolve/index.ts} +133 -602
- package/lib/resolve/passes.ts +544 -0
- package/{span-rescore.ts → lib/span-rescore.ts} +63 -97
- package/{street-evidence.ts → lib/street/evidence.ts} +39 -6
- package/lib/street/index.ts +8 -0
- package/{street-tier.ts → lib/street/tier.ts} +131 -110
- package/{toponym-prior.ts → lib/toponym-prior.ts} +8 -8
- package/out/{admin-coherence-passes.d.ts → admin/coherence-passes.d.ts} +29 -7
- package/out/admin/coherence-passes.d.ts.map +1 -0
- package/out/{admin-coherence-passes.js → admin/coherence-passes.js} +73 -9
- package/out/admin/coherence-passes.js.map +1 -0
- package/out/{admin-containment.d.ts → admin/containment.d.ts} +5 -5
- package/out/admin/containment.d.ts.map +1 -0
- package/out/{admin-containment.js → admin/containment.js} +6 -12
- 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 → admin/winner.d.ts} +11 -3
- package/out/admin/winner.d.ts.map +1 -0
- package/out/{admin-winner.js → admin/winner.js} +19 -3
- package/out/admin/winner.js.map +1 -0
- package/out/backend-capabilities.d.ts.map +1 -1
- package/out/backend-capabilities.js +3 -3
- package/out/backend-capabilities.js.map +1 -1
- package/out/bare-toponym-race.d.ts.map +1 -1
- package/out/bare-toponym-race.js +1 -1
- package/out/bare-toponym-race.js.map +1 -1
- package/out/decorate-node.d.ts +1 -1
- package/out/decorate-node.d.ts.map +1 -1
- package/out/decorate-node.js +1 -1
- package/out/decorate-node.js.map +1 -1
- package/out/fold-name.d.ts +2 -2
- package/out/fold-name.d.ts.map +1 -1
- package/out/fold-name.js +2 -2
- package/out/fold-name.js.map +1 -1
- package/out/index.d.ts +15 -16
- package/out/index.d.ts.map +1 -1
- package/out/index.js +9 -10
- 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} +16 -16
- package/out/postcode/country-coherence.d.ts.map +1 -0
- package/out/{postcode-country-coherence.js → postcode/country-coherence.js} +24 -25
- 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} +4 -4
- 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} +1 -1
- package/out/resolve/index.d.ts.map +1 -0
- package/out/{resolve.js → resolve/index.js} +100 -387
- 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 +43 -69
- 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} +22 -6
- 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} +121 -99
- package/out/street/tier.js.map +1 -0
- package/out/toponym-prior.d.ts +8 -8
- package/out/toponym-prior.d.ts.map +1 -1
- package/out/toponym-prior.js +8 -8
- package/out/toponym-prior.js.map +1 -1
- package/package.json +116 -59
- package/vitest.config.ts +5 -6
- package/out/admin-coherence-passes.d.ts.map +0 -1
- package/out/admin-coherence-passes.js.map +0 -1
- package/out/admin-containment.d.ts.map +0 -1
- package/out/admin-containment.js.map +0 -1
- package/out/admin-winner.d.ts.map +0 -1
- package/out/admin-winner.js.map +0 -1
- 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.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
|
@@ -13,34 +13,34 @@
|
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import { matchCountry, matchSubdivision } from "@mailwoman/codex/country"
|
|
16
|
-
import
|
|
16
|
+
import {
|
|
17
|
+
collectNodes,
|
|
18
|
+
type AddressNode,
|
|
19
|
+
type AddressTree,
|
|
20
|
+
type ComponentTag,
|
|
21
|
+
type Interpretation,
|
|
22
|
+
} from "@mailwoman/core/decoder"
|
|
17
23
|
import {
|
|
18
24
|
type BackendCapabilityGap,
|
|
19
|
-
type CoincidentLocality,
|
|
20
|
-
compareReferential,
|
|
21
|
-
type ResolveCandidateTrace,
|
|
22
25
|
type ResolveNodeTrace,
|
|
23
26
|
DEFAULT_PLACETYPE_MAP,
|
|
24
27
|
isPlacetypeFallback,
|
|
25
|
-
type PlacetypeMap,
|
|
26
|
-
type PostcodePrefixIndexLike,
|
|
27
|
-
referentialFromPopulation,
|
|
28
28
|
type ResolvedPlace,
|
|
29
29
|
type ResolveOpts,
|
|
30
30
|
type Resolver,
|
|
31
31
|
type ResolverBackend,
|
|
32
32
|
countriesFromPostcodeFormat,
|
|
33
33
|
} from "@mailwoman/core/resolver"
|
|
34
|
-
import { PLACETYPE_SPECIFICITY } from "@mailwoman/core/resources/whosonfirst/specificity"
|
|
35
|
-
import { haversineKm } from "@mailwoman/spatial"
|
|
36
34
|
|
|
37
35
|
import {
|
|
38
36
|
applyAdminCoherence,
|
|
39
37
|
applyExplicitCountryCoherence,
|
|
38
|
+
applyParentFallbackContradiction,
|
|
40
39
|
applyRegionCountryCoherence,
|
|
41
|
-
} from "
|
|
42
|
-
import { adminContainmentVerdict, firstRegionQualifier, partitionByContainment } from "
|
|
43
|
-
import {
|
|
40
|
+
} from "#admin/coherence-passes"
|
|
41
|
+
import { adminContainmentVerdict, firstRegionQualifier, partitionByContainment } from "#admin/containment"
|
|
42
|
+
import { resolveCompoundMunicipality } from "#admin/jp-municipality"
|
|
43
|
+
import { describeCapabilityGaps, reportCapabilityGaps } from "#backend-capabilities"
|
|
44
44
|
import {
|
|
45
45
|
BARE_REGION_DOMINANCE_LOG10,
|
|
46
46
|
bareCountryCandidate,
|
|
@@ -48,18 +48,33 @@ import {
|
|
|
48
48
|
logPopulation,
|
|
49
49
|
loneBareLocalityNode,
|
|
50
50
|
pickLargerAdmin,
|
|
51
|
-
} from "
|
|
52
|
-
import { decorateNode
|
|
51
|
+
} from "#bare-toponym-race"
|
|
52
|
+
import { decorateNode } from "#decorate-node"
|
|
53
53
|
import {
|
|
54
54
|
findPostcodeCountryScope,
|
|
55
55
|
type PostcodeCountryScope,
|
|
56
56
|
stampPostcodeCountryScope,
|
|
57
|
-
} from "
|
|
58
|
-
import { type CoordinateOptionalPlace, postcodePrefixResolvedPlace, probePostcodePrefix } from "
|
|
59
|
-
import { applyPostcodeShapeCoherence, isShapeExcludedPostcode } from "
|
|
60
|
-
import {
|
|
61
|
-
|
|
62
|
-
|
|
57
|
+
} from "#postcode/country-coherence"
|
|
58
|
+
import { type CoordinateOptionalPlace, postcodePrefixResolvedPlace, probePostcodePrefix } from "#postcode/prefix"
|
|
59
|
+
import { applyPostcodeShapeCoherence, isShapeExcludedPostcode } from "#postcode/shape-coherence"
|
|
60
|
+
import {
|
|
61
|
+
applyPostcodeConsistency,
|
|
62
|
+
applySpanRescore,
|
|
63
|
+
createNodeTraceRecorder,
|
|
64
|
+
DIAGNOSTIC_BANDS,
|
|
65
|
+
firstPostcodeValue,
|
|
66
|
+
NOOP_TRACE_RECORDER,
|
|
67
|
+
pickCompletion,
|
|
68
|
+
type ResolutionState,
|
|
69
|
+
} from "#resolve/passes"
|
|
70
|
+
import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "#street/tier"
|
|
71
|
+
import {
|
|
72
|
+
type CapitalLevelFn,
|
|
73
|
+
DEFAULT_COUNTRY_PRIOR_WEIGHT,
|
|
74
|
+
promoteCapitals,
|
|
75
|
+
rankByCountryPrior,
|
|
76
|
+
rankByImportance,
|
|
77
|
+
} from "#toponym-prior"
|
|
63
78
|
|
|
64
79
|
/**
|
|
65
80
|
* Build a `Resolver` backed by a `ResolverBackend`. The backend can be any concrete impl structurally compatible with
|
|
@@ -82,18 +97,7 @@ export function createWOFResolver(backend: ResolverBackend): Resolver {
|
|
|
82
97
|
* existing coherence passes keep handling it). Returns the alpha-2 or null.
|
|
83
98
|
*/
|
|
84
99
|
function explicitCountryScope(roots: readonly AddressNode[]): string | null {
|
|
85
|
-
const countryNodes
|
|
86
|
-
const stack = [...roots]
|
|
87
|
-
|
|
88
|
-
while (stack.length) {
|
|
89
|
-
const node = stack.pop()!
|
|
90
|
-
|
|
91
|
-
if (node.tag === "country" && node.value.trim()) {
|
|
92
|
-
countryNodes.push(node)
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
stack.push(...node.children)
|
|
96
|
-
}
|
|
100
|
+
const countryNodes = collectNodes(roots, (node) => node.tag === "country" && node.value.trim().length > 0)
|
|
97
101
|
|
|
98
102
|
if (countryNodes.length !== 1) return null
|
|
99
103
|
const value = countryNodes[0]!.value.trim()
|
|
@@ -106,540 +110,6 @@ function explicitCountryScope(roots: readonly AddressNode[]): string | null {
|
|
|
106
110
|
return matched.iso2
|
|
107
111
|
}
|
|
108
112
|
|
|
109
|
-
/**
|
|
110
|
-
* Cap on candidates recorded per {@link ResolveNodeTrace} — the trace is a record, not a dump. The count past the cap is
|
|
111
|
-
* reported in `candidatesTruncated`, so absence of a row is never silent.
|
|
112
|
-
*/
|
|
113
|
-
const TRACE_CANDIDATE_CAP = 10
|
|
114
|
-
|
|
115
|
-
/**
|
|
116
|
-
* The fine end of the probe window: `microhood` and no finer.
|
|
117
|
-
*
|
|
118
|
-
* Everything above it — `postalcode`, `venue`, `campus`, `building`, `address` — is excluded because a mislabeled ADMIN
|
|
119
|
-
* span lands on another admin band, and probing every venue in a country per miss buys a long tail of coincidental name
|
|
120
|
-
* matches for a diagnostic that is meant to be read.
|
|
121
|
-
*/
|
|
122
|
-
const FINEST_DIAGNOSTIC_BAND = PLACETYPE_SPECIFICITY["microhood"]!
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* The coarse end of the probe window. `country` and no coarser: a name matching at `continent` or `planet` says nothing
|
|
126
|
-
* about a mislabeled admin span, and the walk resolves the country from its own node anyway.
|
|
127
|
-
*/
|
|
128
|
-
const COARSEST_DIAGNOSTIC_BAND = PLACETYPE_SPECIFICITY["country"]!
|
|
129
|
-
|
|
130
|
-
/**
|
|
131
|
-
* The admin bands `ResolveOpts.diagnoseUnreachable` re-probes, coarse to fine.
|
|
132
|
-
*
|
|
133
|
-
* Derived from `PLACETYPE_SPECIFICITY` rather than typed out, so a placetype added there is probed here without anyone
|
|
134
|
-
* remembering to.
|
|
135
|
-
*/
|
|
136
|
-
const DIAGNOSTIC_BANDS: readonly string[] = Object.entries(PLACETYPE_SPECIFICITY)
|
|
137
|
-
.filter(([, rank]) => rank !== undefined && rank <= FINEST_DIAGNOSTIC_BAND && rank >= COARSEST_DIAGNOSTIC_BAND)
|
|
138
|
-
.toSorted((a, b) => (a[1] as number) - (b[1] as number))
|
|
139
|
-
.map(([placetype]) => placetype)
|
|
140
|
-
|
|
141
|
-
/**
|
|
142
|
-
* Per-lookup trace bookkeeping (#1721). `#lookupAndPick` talks to ONE of these unconditionally — a real recorder when
|
|
143
|
-
* `ResolveOpts.traceSink` is set, the frozen {@link NOOP_TRACE_RECORDER} otherwise — so the hot path carries no
|
|
144
|
-
* per-event branches and the no-sink walk costs a handful of empty calls per node.
|
|
145
|
-
*/
|
|
146
|
-
interface NodeTraceRecorder {
|
|
147
|
-
bind(
|
|
148
|
-
node: AddressNode,
|
|
149
|
-
placetype: string,
|
|
150
|
-
query: {
|
|
151
|
-
country?: string
|
|
152
|
-
parentID?: string | number
|
|
153
|
-
postcode?: string
|
|
154
|
-
regionQualifier?: string
|
|
155
|
-
limit?: number
|
|
156
|
-
},
|
|
157
|
-
defaultLimit: number
|
|
158
|
-
): void
|
|
159
|
-
gate(name: string): void
|
|
160
|
-
stage(name: string, order: readonly ResolvedPlace[]): void
|
|
161
|
-
reachable(bands: NonNullable<ResolveNodeTrace["reachableIn"]>): void
|
|
162
|
-
emit(picked: NonNullable<ResolveNodeTrace["picked"]> | null): void
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
const NOOP_TRACE_RECORDER: NodeTraceRecorder = Object.freeze({
|
|
166
|
-
bind() {},
|
|
167
|
-
gate() {},
|
|
168
|
-
stage() {},
|
|
169
|
-
reachable() {},
|
|
170
|
-
emit() {},
|
|
171
|
-
})
|
|
172
|
-
|
|
173
|
-
function createNodeTraceRecorder(sink: (record: ResolveNodeTrace) => void): NodeTraceRecorder {
|
|
174
|
-
const gates: string[] = []
|
|
175
|
-
const stageOrders: Array<[string, readonly ResolvedPlace[]]> = []
|
|
176
|
-
|
|
177
|
-
let reachableIn: ResolveNodeTrace["reachableIn"]
|
|
178
|
-
|
|
179
|
-
let ctx: {
|
|
180
|
-
node: AddressNode
|
|
181
|
-
placetype: string
|
|
182
|
-
query: Parameters<NodeTraceRecorder["bind"]>[2]
|
|
183
|
-
defaultLimit: number
|
|
184
|
-
} | null = null
|
|
185
|
-
|
|
186
|
-
return {
|
|
187
|
-
bind(node, placetype, query, defaultLimit) {
|
|
188
|
-
ctx = { node, placetype, query, defaultLimit }
|
|
189
|
-
},
|
|
190
|
-
gate(name) {
|
|
191
|
-
gates.push(name)
|
|
192
|
-
},
|
|
193
|
-
stage(name, order) {
|
|
194
|
-
stageOrders.push([name, order])
|
|
195
|
-
},
|
|
196
|
-
reachable(bands) {
|
|
197
|
-
reachableIn = bands
|
|
198
|
-
},
|
|
199
|
-
emit(picked) {
|
|
200
|
-
if (!ctx) return
|
|
201
|
-
|
|
202
|
-
const rankMap = new Map<ResolvedPlace, Record<string, number>>()
|
|
203
|
-
|
|
204
|
-
for (const [stage, order] of stageOrders) {
|
|
205
|
-
order.forEach((candidate, index) => {
|
|
206
|
-
let ranks = rankMap.get(candidate)
|
|
207
|
-
|
|
208
|
-
if (!ranks) {
|
|
209
|
-
ranks = {}
|
|
210
|
-
rankMap.set(candidate, ranks)
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
ranks[stage] = index + 1
|
|
214
|
-
})
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
const finalOrder = stageOrders.at(-1)?.[1] ?? []
|
|
218
|
-
|
|
219
|
-
const rows: ResolveCandidateTrace[] = finalOrder.slice(0, TRACE_CANDIDATE_CAP).map((c) => ({
|
|
220
|
-
id: c.id,
|
|
221
|
-
name: c.name,
|
|
222
|
-
country: c.country,
|
|
223
|
-
placetype: c.placetype,
|
|
224
|
-
score: c.score,
|
|
225
|
-
...(c.prominence !== undefined ? { prominence: c.prominence } : {}),
|
|
226
|
-
...(c.importance !== undefined ? { importance: c.importance } : {}),
|
|
227
|
-
...(c.population !== undefined ? { population: c.population } : {}),
|
|
228
|
-
...(c.exactMatch !== undefined ? { exactMatch: c.exactMatch } : {}),
|
|
229
|
-
...(c.containedByQualifier !== undefined ? { containedByQualifier: c.containedByQualifier } : {}),
|
|
230
|
-
ranks: rankMap.get(c) ?? {},
|
|
231
|
-
}))
|
|
232
|
-
|
|
233
|
-
sink({
|
|
234
|
-
tag: ctx.node.tag,
|
|
235
|
-
value: ctx.node.value,
|
|
236
|
-
placetype: ctx.placetype,
|
|
237
|
-
query: {
|
|
238
|
-
...(ctx.query.country ? { country: ctx.query.country } : {}),
|
|
239
|
-
...(ctx.query.parentID !== undefined ? { parentID: ctx.query.parentID } : {}),
|
|
240
|
-
...(ctx.query.postcode ? { postcode: ctx.query.postcode } : {}),
|
|
241
|
-
...(ctx.query.regionQualifier ? { regionQualifier: ctx.query.regionQualifier } : {}),
|
|
242
|
-
limit: ctx.query.limit ?? ctx.defaultLimit,
|
|
243
|
-
},
|
|
244
|
-
gates,
|
|
245
|
-
...(reachableIn ? { reachableIn } : {}),
|
|
246
|
-
candidates: rows,
|
|
247
|
-
candidatesTruncated: Math.max(0, finalOrder.length - TRACE_CANDIDATE_CAP),
|
|
248
|
-
picked,
|
|
249
|
-
})
|
|
250
|
-
},
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
interface ResolutionState {
|
|
255
|
-
lookupsRemaining: number
|
|
256
|
-
placetypeMap: PlacetypeMap
|
|
257
|
-
minWinningScore: number
|
|
258
|
-
candidatesPerLookup: number
|
|
259
|
-
defaultCountry?: string
|
|
260
|
-
/**
|
|
261
|
-
* Whether {@link defaultCountry} came from the locale rather than the caller. Consulted only by `country`-placetype
|
|
262
|
-
* lookups, which skip an inferred scope — see `ResolveOpts.defaultCountryIsInferred`.
|
|
263
|
-
*/
|
|
264
|
-
defaultCountryIsInferred: boolean
|
|
265
|
-
/**
|
|
266
|
-
* The tree's single value-bearing node when it is locality-tagged (the bare-toponym shape), else null. Gates the
|
|
267
|
-
* country-placetype sibling race in `#lookupAndPick` — a bare name can be a country the parser tagged `locality`
|
|
268
|
-
* ("Japan", "China"), and the locality placetype filter makes the country row unreachable no matter how it ranks.
|
|
269
|
-
*/
|
|
270
|
-
bareLocalityNode: AddressNode | null
|
|
271
|
-
parentFallback: boolean
|
|
272
|
-
/**
|
|
273
|
-
* The address's postcode string, extracted once up front, passed to locality lookups so a coordinate-first backend
|
|
274
|
-
* can inject postcode-proximal locality candidates.
|
|
275
|
-
*/
|
|
276
|
-
postcode?: string
|
|
277
|
-
/**
|
|
278
|
-
* Postcode-containment coherence (#31, Mechanism 2) — forwarded to locality lookups so a coordinate-first backend can
|
|
279
|
-
* re-rank name candidates by proximity to the postcode's own centroid. Opt-in; OFF by default.
|
|
280
|
-
*/
|
|
281
|
-
postcodeContainmentCoherence: boolean
|
|
282
|
-
/**
|
|
283
|
-
* Postcode-prefix prior (#31, Mechanism 3) — on a `postalcode` miss, derive the code's prefix and probe
|
|
284
|
-
* `postcodePrefixIndex`. Opt-in; OFF by default.
|
|
285
|
-
*/
|
|
286
|
-
postcodePrefixPrior: boolean
|
|
287
|
-
/**
|
|
288
|
-
* #1589 — the countries the parsed postcode's FORMAT implies (the #928 singles plus the shared `NNN NN` family). When
|
|
289
|
-
* set AND no country constraint survives, the `postalcode` lookup probes exactly these countries and abstains if all
|
|
290
|
-
* miss — never falling through to an unconstrained probe, whose space-stripped fold collides across systems (`100 00`
|
|
291
|
-
* folded to `10000` answers Troyes FR while Prague sits in the artifact under both keyings).
|
|
292
|
-
*/
|
|
293
|
-
postcodeFormatCountries?: readonly string[]
|
|
294
|
-
/**
|
|
295
|
-
* #1585 — the locale hint's country, forwarded to the backend as `fuzzyCountry` on every primary lookup. Scopes the
|
|
296
|
-
* typo-fuzzy tier only; exact matches stay worldwide. See `ResolveOpts.fuzzyCountryScope`.
|
|
297
|
-
*/
|
|
298
|
-
fuzzyCountryScope?: string
|
|
299
|
-
/**
|
|
300
|
-
* The injected PFX1 index (structural — `PostcodePrefixIndexLike`, core/resolver/types.ts). Absent = the prior cannot
|
|
301
|
-
* fire.
|
|
302
|
-
*/
|
|
303
|
-
postcodePrefixIndex?: PostcodePrefixIndexLike
|
|
304
|
-
/**
|
|
305
|
-
* Proximity-bias points (viewport, user location) — forwarded to every primary lookup.
|
|
306
|
-
*/
|
|
307
|
-
bias?: Array<{ lat: number; lon: number; weight?: number }>
|
|
308
|
-
/**
|
|
309
|
-
* Postcode-anchor country posterior (#369). Undefined = no re-rank (byte-stable default).
|
|
310
|
-
*/
|
|
311
|
-
anchorPosterior?: Record<string, number>
|
|
312
|
-
/**
|
|
313
|
-
* Weight on the posterior in the locality re-rank. Only used when `anchorPosterior` is set.
|
|
314
|
-
*/
|
|
315
|
-
anchorWeight: number
|
|
316
|
-
/**
|
|
317
|
-
* #1721 resolver-interior trace sink. Undefined (the default) = zero bookkeeping, byte-identical walk.
|
|
318
|
-
*/
|
|
319
|
-
traceSink?: (record: ResolveNodeTrace) => void
|
|
320
|
-
/**
|
|
321
|
-
* Re-probe a resolved-nothing lookup across the other admin bands and record which hold it. Diagnostic only — never
|
|
322
|
-
* reaches the pick. See `ResolveOpts.diagnoseUnreachable`.
|
|
323
|
-
*/
|
|
324
|
-
diagnoseUnreachable?: boolean
|
|
325
|
-
/**
|
|
326
|
-
* #27 locale-country SOFT prior for the bare-toponym admin walk. Undefined = no prior (the shipped default) →
|
|
327
|
-
* byte-stable. See `ResolveOpts.localeCountryPrior` for the calibration and why it ships opt-in.
|
|
328
|
-
*/
|
|
329
|
-
localeCountryPrior?: string
|
|
330
|
-
/**
|
|
331
|
-
* Weight of that prior in log10-population units. Only consulted when `localeCountryPrior` is set.
|
|
332
|
-
*/
|
|
333
|
-
localeCountryPriorWeight: number
|
|
334
|
-
/**
|
|
335
|
-
* #1880 capital status per candidate, from `ResolveOpts.capitalLevel`. Undefined → no promotion, byte-stable.
|
|
336
|
-
*/
|
|
337
|
-
capitalLevel?: (place: { name: string; country?: string; lat: number; lon: number }) => number
|
|
338
|
-
/**
|
|
339
|
-
* #743/#194 confident-placer country as a HARD filter (empty→unresolved, no global retry). Off = undefined.
|
|
340
|
-
*/
|
|
341
|
-
hardCountry?: string
|
|
342
|
-
/**
|
|
343
|
-
* Dual-role hierarchy completion (#405). Off by default → byte-stable.
|
|
344
|
-
*/
|
|
345
|
-
hierarchyCompletion: boolean
|
|
346
|
-
/**
|
|
347
|
-
* Attach ancestor lineage to each resolved node (#404). Off by default → byte-stable.
|
|
348
|
-
*/
|
|
349
|
-
includeAncestors: boolean
|
|
350
|
-
/**
|
|
351
|
-
* Admin-containment re-rank (#1717 stage 2). Off by default → byte-stable. See `ResolveOpts.adminContainmentRerank`.
|
|
352
|
-
*/
|
|
353
|
-
adminContainmentRerank: boolean
|
|
354
|
-
/**
|
|
355
|
-
* The tree's first parsed region-tagged span, extracted once up front (the `postcode` pattern above — region and
|
|
356
|
-
* locality are siblings, so the top-down walk wouldn't otherwise let the locality lookup see it). Only consulted when
|
|
357
|
-
* {@link adminContainmentRerank} is on.
|
|
358
|
-
*/
|
|
359
|
-
regionQualifier?: string
|
|
360
|
-
/**
|
|
361
|
-
* Set while resolving when ANY tree node maps to the `locality` placetype (resolved or not) — the completion only
|
|
362
|
-
* fires when the parser emitted no locality at all, never to override one.
|
|
363
|
-
*/
|
|
364
|
-
localityNodePresent: boolean
|
|
365
|
-
/**
|
|
366
|
-
* The first region that resolved (its place — for the coincident-roles lookup).
|
|
367
|
-
*/
|
|
368
|
-
resolvedRegion: CoordinateOptionalPlace | null
|
|
369
|
-
/**
|
|
370
|
-
* The decorated region NODE that produced {@link resolvedRegion} — completion pushes the locality interpretation onto
|
|
371
|
-
* it in place (no synthesized sibling).
|
|
372
|
-
*/
|
|
373
|
-
resolvedRegionNode: AddressNode | null
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
/**
|
|
377
|
-
* Pick the completion locality when an admin maps to several coincident same-name candidates (#405). REFERENTIAL
|
|
378
|
-
* likelihood is the PRIMARY signal — the principal city is the populous one, and it can sit FARTHER from the admin
|
|
379
|
-
* centroid than a tiny same-name hamlet (the Niigata case from #403). Nearest centroid breaks a referential tie; a
|
|
380
|
-
* genuine tie (same population AND distance) ABSTAINS rather than guess.
|
|
381
|
-
*
|
|
382
|
-
* ROAD_TO_V9 §2: `compareReferential` is referential DESC with raw population as its own tiebreak, which is the SAME
|
|
383
|
-
* ORDER as the plain `b.population - a.population` it replaced — referential is strictly increasing in population below
|
|
384
|
-
* saturation and constant above it. The abstention check below still reads raw population, deliberately: two megacities
|
|
385
|
-
* that saturate to the same referential score are not tied, and abstaining there would be a new behavior.
|
|
386
|
-
*/
|
|
387
|
-
function pickCompletion(candidates: readonly CoincidentLocality[]): CoincidentLocality | null {
|
|
388
|
-
if (!candidates.length) return null
|
|
389
|
-
|
|
390
|
-
if (candidates.length === 1) return candidates[0]!
|
|
391
|
-
|
|
392
|
-
const ranked = [...candidates]
|
|
393
|
-
.map((c) => ({ c, referential: referentialFromPopulation(c.population), population: c.population }))
|
|
394
|
-
// oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
|
|
395
|
-
.sort((a, b) => compareReferential(a, b) || a.c.distanceKm - b.c.distanceKm)
|
|
396
|
-
.map((x) => x.c)
|
|
397
|
-
|
|
398
|
-
const [first, second] = ranked
|
|
399
|
-
|
|
400
|
-
if (first!.population === second!.population && first!.distanceKm === second!.distanceKm) return null
|
|
401
|
-
|
|
402
|
-
return first!
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
/**
|
|
406
|
-
* Find the first postcode value anywhere in the tree (a one-shot pre-scan; postcode and locality are siblings, so the
|
|
407
|
-
* top-down walk wouldn't otherwise let the locality lookup see it).
|
|
408
|
-
*/
|
|
409
|
-
function firstPostcodeValue(roots: readonly AddressNode[]): string | undefined {
|
|
410
|
-
const stack = [...roots]
|
|
411
|
-
|
|
412
|
-
while (stack.length) {
|
|
413
|
-
const n = stack.pop()!
|
|
414
|
-
|
|
415
|
-
// #31 Mechanism 1: a shape-excluded span keeps its tag but contributes nothing — its code
|
|
416
|
-
// must never become the address's postcode (it would poison the country-scope pass's anchor).
|
|
417
|
-
if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && n.value.trim().length) return n.value.trim()
|
|
418
|
-
stack.push(...n.children)
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
return undefined
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
/**
|
|
425
|
-
* Span-rescore tier (#370): opt-in last-resort locality recovery. Runs ONLY when the tree resolved NOTHING (the #685
|
|
426
|
-
* brake — never disturb a working coordinate). Enumerates raw-token spans, exact- matches the same-country gazetteer
|
|
427
|
-
* (longest-wins + postcode-consistency gate; see `span-rescore.ts`), and on a hit INJECTS a resolved `locality` node
|
|
428
|
-
* decorated exactly like a normally-resolved one. Default-ON (#370, promoted 2026-06-25); byte-stable opt-out via
|
|
429
|
-
* `opts.spanRescore: false`. Async (it queries the backend), so it's awaited.
|
|
430
|
-
*/
|
|
431
|
-
async function applySpanRescore(
|
|
432
|
-
roots: AddressNode[],
|
|
433
|
-
raw: string,
|
|
434
|
-
backend: ResolverBackend,
|
|
435
|
-
opts: ResolveOpts
|
|
436
|
-
): Promise<void> {
|
|
437
|
-
if (hasResolvedPlace(roots)) return // already resolved — never second-guess a working coordinate
|
|
438
|
-
// Default-ON since 2026-06-25, so this runs on every unresolved tree — a backend hiccup here must
|
|
439
|
-
// degrade to no-rescore, never crash the resolve (the same fall-through the main walk gives).
|
|
440
|
-
let hit
|
|
441
|
-
|
|
442
|
-
try {
|
|
443
|
-
hit = await findRescoreCandidate(raw, roots, backend, {
|
|
444
|
-
country: opts.defaultCountry,
|
|
445
|
-
postcode: firstPostcodeValue(roots),
|
|
446
|
-
gateKm: opts.spanRescoreGateKm,
|
|
447
|
-
// Default-ON (promoted 2026-07-03); explicit `false` opts out — the spanRescore idiom.
|
|
448
|
-
postalCompoundRecovery: opts.postalCompoundRecovery !== false,
|
|
449
|
-
})
|
|
450
|
-
} catch {
|
|
451
|
-
return
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
// #942 postal-compound recovery, part 2: when NO city span matched, decorate the FAILED postcode
|
|
455
|
-
// node from its code-shaped token subset ("1382 Kožljek" → the bare "1382" row) — a postcode-tier
|
|
456
|
-
// coordinate FLOOR, strictly subordinate to a recovered locality. Only-on-miss matters: a GeoNames
|
|
457
|
-
// medoid postcode centroid is COARSER than the exact village centroid, and consumers that rank
|
|
458
|
-
// postcode above locality (the eval harness does) would otherwise trade a 0.2 km village pin for a
|
|
459
|
-
// 5 km area centroid. Same unresolved tree, so the #685 brake semantics hold.
|
|
460
|
-
if (!hit && opts.postalCompoundRecovery !== false) {
|
|
461
|
-
try {
|
|
462
|
-
await recoverPostcodeNode(roots, backend, opts.defaultCountry, opts.traceSink)
|
|
463
|
-
} catch {
|
|
464
|
-
// degrade to no-recovery, never crash the resolve
|
|
465
|
-
}
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
if (!hit) return
|
|
469
|
-
|
|
470
|
-
const node: AddressNode = {
|
|
471
|
-
tag: "locality",
|
|
472
|
-
value: hit.text,
|
|
473
|
-
start: hit.start,
|
|
474
|
-
end: hit.end,
|
|
475
|
-
// No model confidence for a post-hoc recovery; a mid-tier value marks it as recovered, not asserted.
|
|
476
|
-
confidence: 0.5,
|
|
477
|
-
children: [],
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
// #1537: the same-span namesake runner-ups, not an empty list. A name the model reads as a `street`
|
|
481
|
-
// ("Springfield", "Berlin", "Moscow") never reaches the admin walk, so this tier is the ONLY thing that
|
|
482
|
-
// resolves it — and decorating with `[]` meant the geocode path's `candidates` held one entry and the
|
|
483
|
-
// dominance margin `declared_ambiguity` reads was uncomputable for exactly the famous-homonym class.
|
|
484
|
-
// The winner is unchanged (see findRescoreCandidate); this is additive.
|
|
485
|
-
decorateNode(node, hit.place, hit.alternatives)
|
|
486
|
-
// `rescore_gated` carries the gate's precision signal as an EXPLICIT handle — NOT folded into the
|
|
487
|
-
// calibrated `confidence`, which would break the isotonic guarantee (a true calibrated 0.83 must not
|
|
488
|
-
// be confused with a rescore plug-in estimate; DeepSeek 2026-06-23). true = postcode gate fired
|
|
489
|
-
// (high-precision); false = ungated (no postcode→point coverage for this country, ~83%-precision).
|
|
490
|
-
node.metadata = { ...node.metadata, span_rescore: true, rescore_gated: hit.gated }
|
|
491
|
-
roots.push(node)
|
|
492
|
-
|
|
493
|
-
// #1721 follow-up: this tier answers OFF the walk, and it used to answer off the record too — the famous-name
|
|
494
|
-
// class ("Frankfurt") returned a coordinate beside an empty resolver trace, blinding every retrieval account.
|
|
495
|
-
// One record per rescue keeps the trace's promise: no resolved coordinate without a lookup record.
|
|
496
|
-
if (opts.traceSink) {
|
|
497
|
-
const rec = createNodeTraceRecorder(opts.traceSink)
|
|
498
|
-
|
|
499
|
-
rec.bind(node, "locality", opts.defaultCountry ? { country: opts.defaultCountry } : {}, 1)
|
|
500
|
-
rec.gate("span_rescore")
|
|
501
|
-
rec.gate(hit.gated ? "rescore_gated" : "rescore_ungated")
|
|
502
|
-
rec.stage("rescore", [hit.place, ...hit.alternatives])
|
|
503
|
-
rec.emit({ id: hit.place.id, name: hit.place.name, source: "span_rescore" })
|
|
504
|
-
}
|
|
505
|
-
}
|
|
506
|
-
|
|
507
|
-
/**
|
|
508
|
-
* #942: find the first confident-but-UNRESOLVED postcode node whose value is a polluted compound ("1382 Kožljek"),
|
|
509
|
-
* resolve its code-shaped token subset as a `postalcode`, and decorate the node from that hit
|
|
510
|
-
* (`postal_compound_recovered` metadata marks the provenance). No-op when every postcode node resolved, the value has
|
|
511
|
-
* no digit-bearing tokens, or the subset equals the full value (then the walk already tried it).
|
|
512
|
-
*/
|
|
513
|
-
async function recoverPostcodeNode(
|
|
514
|
-
roots: AddressNode[],
|
|
515
|
-
backend: ResolverBackend,
|
|
516
|
-
country: string | undefined,
|
|
517
|
-
traceSink?: (record: ResolveNodeTrace) => void
|
|
518
|
-
): Promise<void> {
|
|
519
|
-
const stack: AddressNode[] = [...roots]
|
|
520
|
-
|
|
521
|
-
while (stack.length) {
|
|
522
|
-
const n = stack.pop()!
|
|
523
|
-
|
|
524
|
-
if (n.tag === "postcode" && !n.placeID && n.value.trim()) {
|
|
525
|
-
const code = postcodeCodeSubset(n.value)
|
|
526
|
-
|
|
527
|
-
if (!code || code === n.value.trim()) continue
|
|
528
|
-
const hits = await backend.findPlace({ text: code, placetype: "postalcode", country, limit: 1 })
|
|
529
|
-
const top = hits.find((h) => h.lat !== 0 || h.lon !== 0)
|
|
530
|
-
|
|
531
|
-
if (top) {
|
|
532
|
-
decorateNode(n, top, [])
|
|
533
|
-
n.metadata = { ...n.metadata, postal_compound_recovered: true }
|
|
534
|
-
|
|
535
|
-
// The same off-the-record hole the span-rescore record closes (#1721 follow-up).
|
|
536
|
-
if (traceSink) {
|
|
537
|
-
const rec = createNodeTraceRecorder(traceSink)
|
|
538
|
-
|
|
539
|
-
rec.bind(n, "postalcode", { ...(country ? { country } : {}), limit: 1 }, 1)
|
|
540
|
-
rec.gate("postal_compound_recovery")
|
|
541
|
-
rec.stage("recovery", hits)
|
|
542
|
-
rec.emit({ id: top.id, name: top.name, source: "postal_compound_recovery" })
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
|
|
546
|
-
return // first postcode node only — one recovery per tree
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
if (n.children?.length) {
|
|
550
|
-
stack.push(...n.children)
|
|
551
|
-
}
|
|
552
|
-
}
|
|
553
|
-
}
|
|
554
|
-
|
|
555
|
-
/**
|
|
556
|
-
* Postcode-disambiguated locality selection (#370 "Lever A"). The single biggest miss on the EU/AU panel is a
|
|
557
|
-
* same-named town resolved to the WRONG instance — "06260 Saint-Pierre" lands 617 km off — while the postcode that
|
|
558
|
-
* would disambiguate it (06260 → Alpes-Maritimes) sits resolved in the same tree, discarded because the
|
|
559
|
-
* coordinate-picker prefers the (wrong) locality node and never cross- checks it. This post-walk pass closes that loop,
|
|
560
|
-
* backend-agnostically and with no extra query:
|
|
561
|
-
*
|
|
562
|
-
* 1. Find the resolved postcode's coordinate (the trustworthy anchor — a postcode is unambiguous within a country in a way
|
|
563
|
-
* a town name is not).
|
|
564
|
-
* 2. For each resolved locality node farther than `gateKm` from it: re-pick the same-named candidate from the node's
|
|
565
|
-
* already-captured `alternatives` that is NEAREST the postcode and within the gate. This keeps locality granularity
|
|
566
|
-
* at the CORRECT instance.
|
|
567
|
-
* 3. If no alternative reconciles, the locality instance is unreliable — fall its coordinate back to the postcode point
|
|
568
|
-
* (right area, the safe answer) and flag `postcode_city_mismatch`.
|
|
569
|
-
*
|
|
570
|
-
* Only fires where the postcode resolved to a point, so it composes with postcode coverage (#193) — add a country's
|
|
571
|
-
* postcodes and this immediately disambiguates its same-named towns. **Default-ON** since the #370 operator promotion
|
|
572
|
-
* (2026-07-04, commit `0010bb8c`) — `opts.postcodeConsistency: false` opts out, and the pass is byte-stable on every
|
|
573
|
-
* tree with no resolved postcode point (the `!anchor` early return below).
|
|
574
|
-
*/
|
|
575
|
-
function applyPostcodeConsistency(roots: readonly AddressNode[], gateKm: number): void {
|
|
576
|
-
// The resolved postcode anchor (first one with a real coordinate).
|
|
577
|
-
let anchor: { lat: number; lon: number } | null = null
|
|
578
|
-
const findAnchor: AddressNode[] = [...roots]
|
|
579
|
-
|
|
580
|
-
while (findAnchor.length) {
|
|
581
|
-
const n = findAnchor.pop()!
|
|
582
|
-
|
|
583
|
-
// #31 Mechanism 1: a shape-excluded span never anchors the consistency re-pick either.
|
|
584
|
-
if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && isResolvedWithCoord(n)) {
|
|
585
|
-
anchor = { lat: n.lat!, lon: n.lon! }
|
|
586
|
-
|
|
587
|
-
break
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
findAnchor.push(...n.children)
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
if (!anchor) return // no postcode→point — nothing to disambiguate against (gate can't fire)
|
|
594
|
-
|
|
595
|
-
const stack: AddressNode[] = [...roots]
|
|
596
|
-
|
|
597
|
-
while (stack.length) {
|
|
598
|
-
const node = stack.pop()!
|
|
599
|
-
stack.push(...node.children)
|
|
600
|
-
|
|
601
|
-
if ((node.tag !== "locality" && node.tag !== "dependent_locality") || !isResolvedWithCoord(node)) continue
|
|
602
|
-
|
|
603
|
-
if (haversineKm(anchor.lat, anchor.lon, node.lat!, node.lon!) <= gateKm) continue // already consistent
|
|
604
|
-
|
|
605
|
-
// Re-pick: the same-named candidate nearest the postcode, within the gate. `alternatives` is
|
|
606
|
-
// typed `unknown[]` on the node (decoder/types.ts can't import resolver types) — they ARE the
|
|
607
|
-
// `ResolvedPlace` runner-ups decorateNode attached, so the cast is sound.
|
|
608
|
-
const alts = (node.alternatives as ResolvedPlace[] | undefined) ?? []
|
|
609
|
-
|
|
610
|
-
const reconciling = alts
|
|
611
|
-
.filter((a) => a.lat !== 0 || a.lon !== 0)
|
|
612
|
-
.map((a) => ({ a, d: haversineKm(anchor!.lat, anchor!.lon, a.lat, a.lon) }))
|
|
613
|
-
.filter((x) => x.d <= gateKm)
|
|
614
|
-
// oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
|
|
615
|
-
.sort((x, y) => x.d - y.d)[0]
|
|
616
|
-
|
|
617
|
-
if (reconciling) {
|
|
618
|
-
// Swap to the consistent instance; the displaced winner becomes an alternative.
|
|
619
|
-
const displaced: ResolvedPlace = {
|
|
620
|
-
id: 0,
|
|
621
|
-
name: String(node.metadata?.["resolver_name"] ?? node.value),
|
|
622
|
-
placetype: "locality",
|
|
623
|
-
country: reconciling.a.country,
|
|
624
|
-
lat: node.lat!,
|
|
625
|
-
lon: node.lon!,
|
|
626
|
-
score: 0,
|
|
627
|
-
}
|
|
628
|
-
|
|
629
|
-
const rest = alts.filter((a) => a !== reconciling.a)
|
|
630
|
-
decorateNode(node, reconciling.a, [displaced, ...rest])
|
|
631
|
-
node.metadata = { ...node.metadata, postcode_repicked: true }
|
|
632
|
-
|
|
633
|
-
continue
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
// No same-named instance near the postcode → the town is unreliable; trust the postcode's area.
|
|
637
|
-
node.lat = anchor.lat
|
|
638
|
-
node.lon = anchor.lon
|
|
639
|
-
node.metadata = { ...node.metadata, postcode_city_mismatch: true, coordinate_source: "postcode_fallback" }
|
|
640
|
-
}
|
|
641
|
-
}
|
|
642
|
-
|
|
643
113
|
class WOFResolver implements Resolver {
|
|
644
114
|
readonly #backend: ResolverBackend
|
|
645
115
|
/**
|
|
@@ -766,7 +236,9 @@ class WOFResolver implements Resolver {
|
|
|
766
236
|
postcode: state.postcode,
|
|
767
237
|
defaultCountry: state.defaultCountry,
|
|
768
238
|
...(shapeVerdict?.narrowing !== undefined ? { candidateSystems: shapeVerdict.narrowing } : {}),
|
|
769
|
-
...(opts.
|
|
239
|
+
...(opts.postcodeCountryCoherenceThresholdKm !== undefined
|
|
240
|
+
? { thresholdKm: opts.postcodeCountryCoherenceThresholdKm }
|
|
241
|
+
: {}),
|
|
770
242
|
})
|
|
771
243
|
|
|
772
244
|
if (postcodeScope) {
|
|
@@ -789,9 +261,9 @@ class WOFResolver implements Resolver {
|
|
|
789
261
|
}
|
|
790
262
|
|
|
791
263
|
// The pre-scope's receipt (#1735): consumers that select country-scoped artifacts AFTER the walk
|
|
792
|
-
// (geocode-core's rooftop-
|
|
264
|
+
// (geocode-core's rooftop-extract second pass) key on a scope stamp. Without this, an address whose
|
|
793
265
|
// country was right FROM THE TREE never writes one — the #42 pass stays silent because the default
|
|
794
|
-
// is already coherent — and the FR rooftop
|
|
266
|
+
// is already coherent — and the FR rooftop extract silently stops loading for "…, France" inputs
|
|
795
267
|
// under a non-FR locale (six board venue rows dropped from rooftop to city centroid; the battery
|
|
796
268
|
// caught it).
|
|
797
269
|
if (explicitScope) {
|
|
@@ -816,6 +288,9 @@ class WOFResolver implements Resolver {
|
|
|
816
288
|
// off the postcode/street, not the admin coordinate this adjusts). Byte-stable when nothing fell
|
|
817
289
|
// through or the backend lacks `ancestors`.
|
|
818
290
|
if (opts.adminCoherence !== false) {
|
|
291
|
+
// First: a parent-fallback pick whose lineage names another region is un-resolved, so the passes below
|
|
292
|
+
// and the admin ladder read it as the fall-through it is, not as a resolved namesake elsewhere.
|
|
293
|
+
applyParentFallbackContradiction(newRoots)
|
|
819
294
|
await applyAdminCoherence(newRoots, this.#backend)
|
|
820
295
|
// #822 — same joint-consistency family, inverse trigger: an explicit country token whose resolved
|
|
821
296
|
// locality landed in the wrong country (the populous US namesake). Runs after the region pass so the
|
|
@@ -825,16 +300,16 @@ class WOFResolver implements Resolver {
|
|
|
825
300
|
// resolve (a foreign subdivision — "Montreal QC" under a US locale). The default filter discarded "QC" and
|
|
826
301
|
// force-matched the locality to the US namesake; this re-resolves the subdivision + its same-named locality
|
|
827
302
|
// under the subdivision's OWN country. Disjoint from the two passes above (unresolved region + resolved
|
|
828
|
-
// locality); evidence-
|
|
303
|
+
// locality); evidence-conditional + byte-stable on the domestic path (a US region resolves under `US`).
|
|
829
304
|
await applyRegionCountryCoherence(newRoots, this.#backend, state.defaultCountry)
|
|
830
305
|
}
|
|
831
306
|
|
|
832
|
-
// Postcode-consistency (#370 "
|
|
307
|
+
// Postcode-consistency (#370 "Change A"): default-ON (promoted 2026-07-04 — the corrected check:
|
|
833
308
|
// FI 231/0, SI 37/6, CZ 47/2, US byte-flat; see the ResolveOpts docstring). After the admin walk
|
|
834
309
|
// (needs both the locality and the postcode resolved) and before the street tiers (which key off
|
|
835
310
|
// the postcode/street, not the locality coordinate this adjusts). `false` opts out, byte-stable.
|
|
836
311
|
if (opts.postcodeConsistency !== false) {
|
|
837
|
-
applyPostcodeConsistency(newRoots, opts.
|
|
312
|
+
applyPostcodeConsistency(newRoots, opts.postcodeConsistencyThresholdKm ?? 50)
|
|
838
313
|
}
|
|
839
314
|
|
|
840
315
|
// Address-point tier (#476): opt-in street-level exact match. After the admin walk so the
|
|
@@ -845,7 +320,7 @@ class WOFResolver implements Resolver {
|
|
|
845
320
|
}
|
|
846
321
|
|
|
847
322
|
// Interpolation tier (#483): strictly AFTER the exact-point block so an estimate can never
|
|
848
|
-
// override a real situs point (applyInterpolation also
|
|
323
|
+
// override a real situs point (applyInterpolation also checks on resolution_tier). Opt-in;
|
|
849
324
|
// byte-stable when opts.interpolation is absent.
|
|
850
325
|
if (opts.interpolation) {
|
|
851
326
|
applyInterpolation(newRoots, opts.interpolation, opts.interpolationRadiusCalibration)
|
|
@@ -871,7 +346,7 @@ class WOFResolver implements Resolver {
|
|
|
871
346
|
// Street-centroid tier (#1042): LAST, after span-rescore, so it can (a) union the span-rescore-recovered
|
|
872
347
|
// country into its FR/national country hints (a placer-misrouted street — "Rue Sainte-Catherine" → IT — leaves
|
|
873
348
|
// admin unresolved, and only span-rescore recovers the FR country signal) and (b) override a coarse recovered
|
|
874
|
-
// locality with the exact street centroid.
|
|
349
|
+
// locality with the exact street centroid. Applies only when there is no house number + no existing street-level tier, so a
|
|
875
350
|
// rooftop query is untouched; byte-stable when opts.streetCentroids absent.
|
|
876
351
|
if (opts.streetCentroids) {
|
|
877
352
|
applyStreetCentroid(newRoots, tree.raw, opts.streetCentroids, opts.streetCountryHints ?? [])
|
|
@@ -930,7 +405,26 @@ class WOFResolver implements Resolver {
|
|
|
930
405
|
// stripped of their resolve contribution — the walk does not look them up. Digit-only excluded
|
|
931
406
|
// spans were retagged to `house_number` and flow through their correct sibling placetype.
|
|
932
407
|
if (placetype && state.lookupsRemaining > 0 && node.value.trim().length && !isShapeExcludedPostcode(node)) {
|
|
933
|
-
|
|
408
|
+
let picked = await this.#lookupAndPick(node, placetype, parentResolved, state)
|
|
409
|
+
|
|
410
|
+
// A compound JP municipality as a scoped pair: the parent fallback is withheld on the tail probe only.
|
|
411
|
+
if (!picked && node.tag === "municipality") {
|
|
412
|
+
picked = await resolveCompoundMunicipality(
|
|
413
|
+
node.value,
|
|
414
|
+
parentResolved,
|
|
415
|
+
() => state.lookupsRemaining > 0,
|
|
416
|
+
async (value, scope, parentFallback) => {
|
|
417
|
+
const prior = state.parentFallback
|
|
418
|
+
state.parentFallback = prior && parentFallback
|
|
419
|
+
|
|
420
|
+
try {
|
|
421
|
+
return await this.#lookupAndPick({ ...node, value }, placetype, scope, state)
|
|
422
|
+
} finally {
|
|
423
|
+
state.parentFallback = prior
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
)
|
|
427
|
+
}
|
|
934
428
|
|
|
935
429
|
if (picked) {
|
|
936
430
|
resolved = picked.top
|
|
@@ -1048,7 +542,7 @@ class WOFResolver implements Resolver {
|
|
|
1048
542
|
}
|
|
1049
543
|
|
|
1050
544
|
// #194: a resolved parent's country wins, then the caller's `defaultCountry`, then the confident
|
|
1051
|
-
// placer `hardCountry`. All three are a HARD candidate filter. The placer's `hardCountry` is
|
|
545
|
+
// placer `hardCountry`. All three are a HARD candidate filter. The placer's `hardCountry` is conditional
|
|
1052
546
|
// upstream on high confidence (so it only fires when the model is sure), and on a miss the node is
|
|
1053
547
|
// left UNRESOLVED rather than re-resolved globally: the off-continent rows are precisely the ones
|
|
1054
548
|
// whose locality isn't in the country's gazetteer slice, so a global retry would just re-admit the
|
|
@@ -1138,7 +632,7 @@ class WOFResolver implements Resolver {
|
|
|
1138
632
|
// set — its index is country-scoped by construction, so it is not the fold this branch
|
|
1139
633
|
// exists to avoid (the B3 tests hold that path).
|
|
1140
634
|
if (placetype === "postalcode" && !query.country && state.postcodeFormatCountries?.length) {
|
|
1141
|
-
rec.
|
|
635
|
+
rec.check("postcode_format_probe")
|
|
1142
636
|
let best: ResolvedPlace | undefined
|
|
1143
637
|
|
|
1144
638
|
for (const impliedCountry of state.postcodeFormatCountries) {
|
|
@@ -1168,13 +662,13 @@ class WOFResolver implements Resolver {
|
|
|
1168
662
|
candidates = await this.#backend.findPlace(query)
|
|
1169
663
|
rec.stage("initial", candidates)
|
|
1170
664
|
|
|
1171
|
-
// #1731: the backend's interior region-scope fallback, surfaced as a
|
|
665
|
+
// #1731: the backend's interior region-scope fallback, surfaced as a check — the resolver
|
|
1172
666
|
// never sees the scoped probe miss, only the stamp the re-admitted rows carry.
|
|
1173
667
|
if (candidates[0]?.regionScopeMiss) {
|
|
1174
|
-
rec.
|
|
668
|
+
rec.check("region_scope_miss")
|
|
1175
669
|
}
|
|
1176
670
|
|
|
1177
|
-
// Parent soft-
|
|
671
|
+
// Parent soft-filtering: `parentID` is a HARD descendant filter in the backend, which wrongly
|
|
1178
672
|
// zeroes the result when the parent resolved wrong OR the gazetteer hierarchy is incomplete
|
|
1179
673
|
// (a real locality whose `ancestors` chain is missing its region). Rather than turn a
|
|
1180
674
|
// resolvable node into an unresolved one, retry once WITHOUT the parent constraint — we
|
|
@@ -1182,7 +676,7 @@ class WOFResolver implements Resolver {
|
|
|
1182
676
|
// this still can't wander to a foreign place. Same logical resolution → no extra budget.
|
|
1183
677
|
if (!candidates.length && state.parentFallback && query.parentID !== undefined) {
|
|
1184
678
|
delete query.parentID
|
|
1185
|
-
rec.
|
|
679
|
+
rec.check("parent_fallback_retry")
|
|
1186
680
|
candidates = await this.#backend.findPlace(query)
|
|
1187
681
|
rec.stage("parent_fallback", candidates)
|
|
1188
682
|
}
|
|
@@ -1199,10 +693,10 @@ class WOFResolver implements Resolver {
|
|
|
1199
693
|
// Defensive: a backend failure should not abort the whole tree walk. Leave the node with
|
|
1200
694
|
// its classifier attribution intact.
|
|
1201
695
|
//
|
|
1202
|
-
// The reason rides the
|
|
696
|
+
// The reason rides the check name. A bare `backend_error` cannot tell a closed database from a
|
|
1203
697
|
// finalized statement from a genuine query fault, which is what made three full-board constraint
|
|
1204
698
|
// runs unreadable — 64 of 591 rows errored and the census could not say why.
|
|
1205
|
-
rec.
|
|
699
|
+
rec.check(`backend_error: ${(error as Error).message}`)
|
|
1206
700
|
rec.emit(null)
|
|
1207
701
|
|
|
1208
702
|
return null
|
|
@@ -1228,7 +722,7 @@ class WOFResolver implements Resolver {
|
|
|
1228
722
|
: {}),
|
|
1229
723
|
}
|
|
1230
724
|
|
|
1231
|
-
rec.
|
|
725
|
+
rec.check("postcode_prefix_prior")
|
|
1232
726
|
const prefixPlace = postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex)
|
|
1233
727
|
|
|
1234
728
|
rec.emit({ id: prefixPlace.id, name: prefixPlace.name, source: "postcode_prefix" })
|
|
@@ -1250,7 +744,7 @@ class WOFResolver implements Resolver {
|
|
|
1250
744
|
const isBareRace = placetype === "locality" && node === state.bareLocalityNode
|
|
1251
745
|
|
|
1252
746
|
if (isBareRace) {
|
|
1253
|
-
rec.
|
|
747
|
+
rec.check("bare_race")
|
|
1254
748
|
}
|
|
1255
749
|
|
|
1256
750
|
const bareCountry = isBareRace ? await bareCountryCandidate(this.#backend, node.value, query.country) : null
|
|
@@ -1262,7 +756,7 @@ class WOFResolver implements Resolver {
|
|
|
1262
756
|
const admin = pickLargerAdmin(bareCountry, bareRegion)
|
|
1263
757
|
|
|
1264
758
|
if (admin) {
|
|
1265
|
-
rec.
|
|
759
|
+
rec.check("empty_admin_pick")
|
|
1266
760
|
rec.emit({ id: admin.id, name: admin.name, source: "empty_admin" })
|
|
1267
761
|
|
|
1268
762
|
return {
|
|
@@ -1320,8 +814,10 @@ class WOFResolver implements Resolver {
|
|
|
1320
814
|
const tier = Number(b.exactMatch ?? false) - Number(a.exactMatch ?? false)
|
|
1321
815
|
|
|
1322
816
|
if (tier !== 0) return tier
|
|
1323
|
-
|
|
1324
|
-
|
|
817
|
+
// A candidate with no country gets no posterior mass rather than an index by `undefined`, which reads
|
|
818
|
+
// every unknown-country row as the same key.
|
|
819
|
+
const aKey = (a.prominence ?? a.score) + w * (a.country === undefined ? 0 : (post[a.country] ?? 0))
|
|
820
|
+
const bKey = (b.prominence ?? b.score) + w * (b.country === undefined ? 0 : (post[b.country] ?? 0))
|
|
1325
821
|
|
|
1326
822
|
return bKey - aKey || b.score - a.score
|
|
1327
823
|
})
|
|
@@ -1329,7 +825,7 @@ class WOFResolver implements Resolver {
|
|
|
1329
825
|
rec.stage("anchor", ranked)
|
|
1330
826
|
}
|
|
1331
827
|
|
|
1332
|
-
// Locale-country soft prior (#27) — the #912
|
|
828
|
+
// Locale-country soft prior (#27) — the #912 change's other half, at the tier that decides a bare
|
|
1333
829
|
// toponym the model tagged `locality`. `--locale en-GB "Whitby"` answers Whitby, Ontario while
|
|
1334
830
|
// `--default-country GB "Whitby"` answers the gold, because the CLI DROPS the locale-inferred
|
|
1335
831
|
// country for this shape rather than choosing between "hard filter" and "nothing". This is the
|
|
@@ -1368,16 +864,16 @@ class WOFResolver implements Resolver {
|
|
|
1368
864
|
// containment partition (the qualifier is the address's own text; evidence outranks a prior).
|
|
1369
865
|
// Same stand-down as fame: an anchor posterior is postcode evidence and silences the prior.
|
|
1370
866
|
if (state.capitalLevel) {
|
|
1371
|
-
ranked =
|
|
867
|
+
ranked = promoteCapitalsWithReceipt(ranked, state.capitalLevel, node)
|
|
1372
868
|
rec.stage("capital", ranked)
|
|
1373
869
|
}
|
|
1374
870
|
}
|
|
1375
871
|
|
|
1376
872
|
// Admin-containment partition (#1717 stage 2): the LAST soft re-rank, after the anchor/fame keys
|
|
1377
873
|
// above, because the qualifier is the address's OWN text — evidence, which outranks a prior. The
|
|
1378
|
-
// backend already put contained rows first; this second partition is
|
|
874
|
+
// backend already put contained rows first; this second partition is required, not belt-and-
|
|
1379
875
|
// braces: `rankByImportance` just re-ordered the exact tier by fame, and Richmond, Virginia
|
|
1380
|
-
// outscores Richmond, North Yorkshire on importance — without this the
|
|
876
|
+
// outscores Richmond, North Yorkshire on importance — without this the change loses exactly where
|
|
1381
877
|
// fame disagrees with the qualifier (the shared-function partition, tier-safe + stable, so it can
|
|
1382
878
|
// never promote a contained partial match over an exact one). No stamps → identity → byte-stable
|
|
1383
879
|
// on any backend that ignored `regionQualifier`.
|
|
@@ -1413,7 +909,7 @@ class WOFResolver implements Resolver {
|
|
|
1413
909
|
const top = ranked[0]!
|
|
1414
910
|
|
|
1415
911
|
if (top.score < state.minWinningScore) {
|
|
1416
|
-
rec.
|
|
912
|
+
rec.check("min_score_reject")
|
|
1417
913
|
rec.emit(null)
|
|
1418
914
|
|
|
1419
915
|
return null
|
|
@@ -1424,18 +920,18 @@ class WOFResolver implements Resolver {
|
|
|
1424
920
|
// DOMINATE the locality winner by {@link BARE_REGION_DOMINANCE_LOG10} in log-population:
|
|
1425
921
|
// prominence saturates at the backend's populationBoost cap, so the margin is measured on the
|
|
1426
922
|
// raw populations, and the margin is what keeps bare "New York" on the city (state 19.6M vs
|
|
1427
|
-
// city 8.8M = 0.35, under the
|
|
923
|
+
// city 8.8M = 0.35, under the threshold) while bare "Georgia" promotes to the 11M state over the
|
|
1428
924
|
// Vermont hamlet (margin 3.4). A bare name with no admin namesake never reaches these lines,
|
|
1429
925
|
// and the displaced locality stays first among the alternatives either way.
|
|
1430
926
|
if (bareCountry && (bareCountry.prominence ?? bareCountry.score) > (top.prominence ?? top.score)) {
|
|
1431
|
-
rec.
|
|
927
|
+
rec.check("bare_country_repick")
|
|
1432
928
|
rec.emit({ id: bareCountry.id, name: bareCountry.name, source: "bare_country" })
|
|
1433
929
|
|
|
1434
930
|
return { top: bareCountry, alternatives: ranked, metadata: { bare_country_repick: true } }
|
|
1435
931
|
}
|
|
1436
932
|
|
|
1437
933
|
if (bareRegion && logPopulation(bareRegion) >= logPopulation(top) + BARE_REGION_DOMINANCE_LOG10) {
|
|
1438
|
-
rec.
|
|
934
|
+
rec.check("bare_region_repick")
|
|
1439
935
|
rec.emit({ id: bareRegion.id, name: bareRegion.name, source: "bare_region" })
|
|
1440
936
|
|
|
1441
937
|
return { top: bareRegion, alternatives: ranked, metadata: { bare_region_repick: true } }
|
|
@@ -1446,19 +942,54 @@ class WOFResolver implements Resolver {
|
|
|
1446
942
|
// identity/coordinate are unchanged; only `metadata.resolution_quality` is stamped downstream.
|
|
1447
943
|
if (isPlacetypeFallback(placetype, top.placetype)) {
|
|
1448
944
|
top.resolutionQuality = "fallback"
|
|
1449
|
-
rec.
|
|
945
|
+
rec.check("placetype_fallback")
|
|
1450
946
|
}
|
|
1451
947
|
|
|
1452
948
|
rec.emit({ id: top.id, name: top.name, source: "ranked" })
|
|
1453
949
|
|
|
1454
|
-
// The
|
|
1455
|
-
//
|
|
1456
|
-
//
|
|
1457
|
-
//
|
|
950
|
+
// The trace stamps (#1717 stage 2 / #1719's rule): an opted-in mechanism that cannot fire — a
|
|
951
|
+
// pre-sidecar artifact, an incapable backend — must say so in the result, not degrade silently.
|
|
952
|
+
// The parse-side census cannot see resolver mechanisms, so these stamps are its census surface.
|
|
953
|
+
// admin_containment asserts a question was asked; variant_alias_exemption (#1893) asserts the
|
|
954
|
+
// winning candidate reached the top BECAUSE the exemption spared it the cross-country penalty —
|
|
955
|
+
// the winner-level firing receipt, same posture as capital_promotion.
|
|
956
|
+
const pickMetadata = {
|
|
957
|
+
...(containmentEligible ? { admin_containment: adminContainmentVerdict(ranked) } : {}),
|
|
958
|
+
...(top.variantAliasExempted === true ? { variant_alias_exemption: true } : {}),
|
|
959
|
+
// The pick was admitted from OUTSIDE the resolved parent's scope, by either widening: the resolver's own retry
|
|
960
|
+
// without the parent (the scope was set — a resolved parent with a numeric id — and the retry is the only
|
|
961
|
+
// thing that deletes it), or the backend's interior region-scope fallback, which keeps the query intact and
|
|
962
|
+
// stamps the rows it re-admitted (#1731). Stamped so `applyParentFallbackContradiction` can tell a namesake
|
|
963
|
+
// under another region from the incomplete chain both widenings exist for.
|
|
964
|
+
...((parentResolved && typeof parentResolved.id === "number" && query.parentID === undefined) ||
|
|
965
|
+
top.regionScopeMiss === true
|
|
966
|
+
? { parent_fallback: true }
|
|
967
|
+
: {}),
|
|
968
|
+
}
|
|
969
|
+
|
|
1458
970
|
return {
|
|
1459
971
|
top,
|
|
1460
972
|
alternatives: ranked.slice(1),
|
|
1461
|
-
...(
|
|
973
|
+
...(Object.keys(pickMetadata).length ? { metadata: pickMetadata } : {}),
|
|
1462
974
|
}
|
|
1463
975
|
}
|
|
1464
976
|
}
|
|
977
|
+
|
|
978
|
+
/**
|
|
979
|
+
* #1880's promotion plus its firing receipt, in one place: when the promotion changes the race's leading candidate, the
|
|
980
|
+
* node is stamped `capital_promotion` with the promoted candidate's country — the same posture as
|
|
981
|
+
* `postcode_country_scope`, a mechanism reporting that it SPOKE apart from whether the outcome moved, so an unchanged
|
|
982
|
+
* verdict downstream can never mean either "harmless" or "never ran". Metadata-only; nothing reads it to rank.
|
|
983
|
+
*/
|
|
984
|
+
function promoteCapitalsWithReceipt<
|
|
985
|
+
T extends Pick<ResolvedPlace, "score" | "name" | "country" | "lat" | "lon"> &
|
|
986
|
+
Partial<Pick<ResolvedPlace, "exactMatch" | "importance" | "prominence">>,
|
|
987
|
+
>(ranked: readonly T[], level: CapitalLevelFn, node: { metadata?: Record<string, unknown> }): T[] {
|
|
988
|
+
const promoted = promoteCapitals(ranked, level)
|
|
989
|
+
|
|
990
|
+
if (promoted[0] !== ranked[0]) {
|
|
991
|
+
node.metadata = { ...node.metadata, capital_promotion: promoted[0]!.country ?? true }
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
return promoted
|
|
995
|
+
}
|