@mailwoman/resolver 10.1.0 → 10.2.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/lib/admin/coherence-passes.ts +10 -10
- package/lib/admin/containment.ts +4 -4
- package/lib/admin/jp-municipality.ts +1 -1
- package/lib/admin/winner.ts +7 -7
- package/lib/backend-capabilities.ts +3 -3
- package/lib/decorate-node.ts +8 -8
- package/lib/plausibility.ts +6 -6
- package/lib/postcode/country-coherence.ts +30 -14
- package/lib/postcode/prefix.ts +4 -2
- package/lib/postcode/shape-coherence.ts +4 -4
- package/lib/remote-resolver.ts +6 -4
- package/lib/rerank.ts +9 -6
- package/lib/resolve/passes.ts +47 -33
- package/lib/resolve.ts +56 -38
- package/lib/span-rescore.ts +27 -26
- package/lib/street/tier.ts +20 -21
- package/lib/toponym-prior.ts +1 -1
- package/out/admin/coherence-passes.d.ts +1 -1
- package/out/admin/coherence-passes.d.ts.map +1 -1
- package/out/admin/coherence-passes.js +6 -6
- package/out/admin/coherence-passes.js.map +1 -1
- package/out/admin/containment.d.ts +2 -2
- package/out/admin/containment.d.ts.map +1 -1
- package/out/admin/containment.js +2 -2
- package/out/admin/containment.js.map +1 -1
- package/out/admin/jp-municipality.d.ts +1 -1
- package/out/admin/jp-municipality.d.ts.map +1 -1
- package/out/admin/winner.d.ts +2 -2
- package/out/admin/winner.d.ts.map +1 -1
- package/out/admin/winner.js +5 -5
- package/out/admin/winner.js.map +1 -1
- package/out/backend-capabilities.d.ts +1 -1
- package/out/backend-capabilities.d.ts.map +1 -1
- package/out/backend-capabilities.js +3 -2
- package/out/backend-capabilities.js.map +1 -1
- package/out/decorate-node.js +8 -8
- package/out/decorate-node.js.map +1 -1
- package/out/plausibility.d.ts +3 -3
- package/out/plausibility.d.ts.map +1 -1
- package/out/plausibility.js +3 -3
- package/out/plausibility.js.map +1 -1
- package/out/postcode/country-coherence.d.ts +7 -7
- package/out/postcode/country-coherence.d.ts.map +1 -1
- package/out/postcode/country-coherence.js +23 -7
- package/out/postcode/country-coherence.js.map +1 -1
- package/out/postcode/prefix.d.ts +1 -1
- package/out/postcode/prefix.d.ts.map +1 -1
- package/out/postcode/prefix.js +3 -1
- package/out/postcode/prefix.js.map +1 -1
- package/out/postcode/shape-coherence.d.ts +2 -2
- package/out/postcode/shape-coherence.d.ts.map +1 -1
- package/out/postcode/shape-coherence.js +2 -2
- package/out/postcode/shape-coherence.js.map +1 -1
- package/out/remote-resolver.d.ts +5 -3
- package/out/remote-resolver.d.ts.map +1 -1
- package/out/remote-resolver.js +3 -1
- package/out/remote-resolver.js.map +1 -1
- package/out/rerank.d.ts +6 -3
- package/out/rerank.d.ts.map +1 -1
- package/out/rerank.js +3 -3
- package/out/rerank.js.map +1 -1
- package/out/resolve/passes.d.ts +14 -11
- package/out/resolve/passes.d.ts.map +1 -1
- package/out/resolve/passes.js +27 -21
- package/out/resolve/passes.js.map +1 -1
- package/out/resolve.d.ts.map +1 -1
- package/out/resolve.js +51 -37
- package/out/resolve.js.map +1 -1
- package/out/span-rescore.d.ts +12 -8
- package/out/span-rescore.d.ts.map +1 -1
- package/out/span-rescore.js +10 -10
- package/out/span-rescore.js.map +1 -1
- package/out/street/tier.d.ts +1 -1
- package/out/street/tier.d.ts.map +1 -1
- package/out/street/tier.js +17 -17
- package/out/street/tier.js.map +1 -1
- package/out/toponym-prior.d.ts +1 -1
- package/out/toponym-prior.d.ts.map +1 -1
- package/out/toponym-prior.js.map +1 -1
- package/package.json +7 -7
package/lib/resolve/passes.ts
CHANGED
|
@@ -8,6 +8,8 @@ import type { PlacetypeMap } from "@mailwoman/codex/placetype-map"
|
|
|
8
8
|
import { walkNodes, type AddressNode } from "@mailwoman/core/decoder"
|
|
9
9
|
import {
|
|
10
10
|
type CoincidentLocality,
|
|
11
|
+
type DefaultCountry,
|
|
12
|
+
EMPTY_PLACE_FIELDS,
|
|
11
13
|
compareReferential,
|
|
12
14
|
type ResolveCandidateTrace,
|
|
13
15
|
type ResolveNodeTrace,
|
|
@@ -16,6 +18,7 @@ import {
|
|
|
16
18
|
type ResolvedPlace,
|
|
17
19
|
type ResolveOpts,
|
|
18
20
|
type ResolverBackend,
|
|
21
|
+
type ResolveSwitches,
|
|
19
22
|
} from "@mailwoman/core/resolver"
|
|
20
23
|
import { PLACETYPE_SPECIFICITY } from "@mailwoman/core/resources/whosonfirst/specificity"
|
|
21
24
|
import { haversineKm } from "@mailwoman/spatial"
|
|
@@ -31,6 +34,11 @@ const FINEST_DIAGNOSTIC_BAND = PLACETYPE_SPECIFICITY["microhood"]!
|
|
|
31
34
|
|
|
32
35
|
const COARSEST_DIAGNOSTIC_BAND = PLACETYPE_SPECIFICITY["country"]!
|
|
33
36
|
|
|
37
|
+
/**
|
|
38
|
+
* {@link ResolveOpts} with every {@link ResolveSwitches} key resolved against its default.
|
|
39
|
+
*/
|
|
40
|
+
export type ResolvedOpts = ResolveOpts & ResolveSwitches
|
|
41
|
+
|
|
34
42
|
/**
|
|
35
43
|
* The admin placetypes from country to microhood that `ResolveOpts.diagnoseUnreachable`
|
|
36
44
|
* re-probes, coarse to fine.
|
|
@@ -38,7 +46,7 @@ const COARSEST_DIAGNOSTIC_BAND = PLACETYPE_SPECIFICITY["country"]!
|
|
|
38
46
|
* The list derives from `PLACETYPE_SPECIFICITY`, so a new placetype in that range is probed automatically.
|
|
39
47
|
*/
|
|
40
48
|
export const DIAGNOSTIC_BANDS: readonly string[] = Object.entries(PLACETYPE_SPECIFICITY)
|
|
41
|
-
.filter(([, rank]) => rank
|
|
49
|
+
.filter(([, rank]) => rank != null && rank <= FINEST_DIAGNOSTIC_BAND && rank >= COARSEST_DIAGNOSTIC_BAND)
|
|
42
50
|
.toSorted((a, b) => (a[1] as number) - (b[1] as number))
|
|
43
51
|
.map(([placetype]) => placetype)
|
|
44
52
|
|
|
@@ -54,8 +62,8 @@ export interface NodeTraceRecorder {
|
|
|
54
62
|
query: {
|
|
55
63
|
country?: string
|
|
56
64
|
parentID?: string | number
|
|
57
|
-
postcode?: string
|
|
58
|
-
regionQualifier?: string
|
|
65
|
+
postcode?: string | null
|
|
66
|
+
regionQualifier?: string | null
|
|
59
67
|
limit?: number
|
|
60
68
|
},
|
|
61
69
|
defaultLimit: number
|
|
@@ -85,7 +93,7 @@ export function createNodeTraceRecorder(sink: (record: ResolveNodeTrace) => void
|
|
|
85
93
|
const checks: string[] = []
|
|
86
94
|
const stageOrders: Array<[string, readonly ResolvedPlace[]]> = []
|
|
87
95
|
|
|
88
|
-
let reachableIn: ResolveNodeTrace["reachableIn"]
|
|
96
|
+
let reachableIn: ResolveNodeTrace["reachableIn"] = null
|
|
89
97
|
|
|
90
98
|
let ctx: {
|
|
91
99
|
node: AddressNode
|
|
@@ -133,11 +141,11 @@ export function createNodeTraceRecorder(sink: (record: ResolveNodeTrace) => void
|
|
|
133
141
|
country: c.country,
|
|
134
142
|
placetype: c.placetype,
|
|
135
143
|
score: c.score,
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
144
|
+
prominence: c.prominence ?? null,
|
|
145
|
+
importance: c.importance ?? null,
|
|
146
|
+
population: c.population ?? null,
|
|
147
|
+
exactMatch: c.exactMatch ?? null,
|
|
148
|
+
containedByQualifier: c.containedByQualifier ?? null,
|
|
141
149
|
ranks: rankMap.get(c) ?? {},
|
|
142
150
|
}))
|
|
143
151
|
|
|
@@ -146,14 +154,14 @@ export function createNodeTraceRecorder(sink: (record: ResolveNodeTrace) => void
|
|
|
146
154
|
value: ctx.node.value,
|
|
147
155
|
placetype: ctx.placetype,
|
|
148
156
|
query: {
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
157
|
+
country: ctx.query.country || null,
|
|
158
|
+
parentID: ctx.query.parentID ?? null,
|
|
159
|
+
postcode: ctx.query.postcode || null,
|
|
160
|
+
regionQualifier: ctx.query.regionQualifier || null,
|
|
153
161
|
limit: ctx.query.limit ?? ctx.defaultLimit,
|
|
154
162
|
},
|
|
155
163
|
checks,
|
|
156
|
-
|
|
164
|
+
reachableIn,
|
|
157
165
|
candidates: rows,
|
|
158
166
|
candidatesTruncated: Math.max(0, finalOrder.length - TRACE_CANDIDATE_CAP),
|
|
159
167
|
picked,
|
|
@@ -178,14 +186,12 @@ export interface ResolutionState {
|
|
|
178
186
|
*/
|
|
179
187
|
minScoreRefusals: number
|
|
180
188
|
candidatesPerLookup: number
|
|
181
|
-
defaultCountry?: string
|
|
182
|
-
|
|
183
189
|
/**
|
|
184
|
-
*
|
|
190
|
+
* The default country scope, or null for none.
|
|
185
191
|
*
|
|
186
192
|
* `country` lookups ignore an inferred default.
|
|
187
193
|
*/
|
|
188
|
-
|
|
194
|
+
defaultCountry: DefaultCountry | null
|
|
189
195
|
|
|
190
196
|
/**
|
|
191
197
|
* The tree's only value-bearing node when it maps to `locality`, or null otherwise.
|
|
@@ -202,7 +208,7 @@ export interface ResolutionState {
|
|
|
202
208
|
* Locality lookups send it to the backend.
|
|
203
209
|
* The backend can then favor nearby candidates.
|
|
204
210
|
*/
|
|
205
|
-
postcode?: string
|
|
211
|
+
postcode?: string | null
|
|
206
212
|
|
|
207
213
|
/**
|
|
208
214
|
* Whether locality lookups ask the backend to re-rank candidates by distance to the postcode centroid.
|
|
@@ -281,7 +287,7 @@ export interface ResolutionState {
|
|
|
281
287
|
* Returns a candidate's capital level for bounded capital promotion.
|
|
282
288
|
* Capital promotion is off when it is absent.
|
|
283
289
|
*/
|
|
284
|
-
capitalLevel?: (place: { name: string; country
|
|
290
|
+
capitalLevel?: (place: { name: string; country: string | null; lat: number; lon: number }) => number
|
|
285
291
|
|
|
286
292
|
/**
|
|
287
293
|
* The country scope applied to a lookup when no parent, default country, or node hint supplies one.
|
|
@@ -313,7 +319,7 @@ export interface ResolutionState {
|
|
|
313
319
|
* It applies only with {@link ResolutionState.adminContainmentRerank}
|
|
314
320
|
* and no caller-supplied default country.
|
|
315
321
|
*/
|
|
316
|
-
regionQualifier?: string
|
|
322
|
+
regionQualifier?: string | null
|
|
317
323
|
|
|
318
324
|
/**
|
|
319
325
|
* Whether any node maps to the `locality` placetype.
|
|
@@ -362,12 +368,12 @@ export function pickCompletion(candidates: readonly CoincidentLocality[]): Coinc
|
|
|
362
368
|
* Returns the first postcode value anywhere in the tree, skipping shape-excluded postcodes.
|
|
363
369
|
* a locality lookup uses it because the postcode node is usually a sibling.
|
|
364
370
|
*/
|
|
365
|
-
export function firstPostcodeValue(roots: readonly AddressNode[]): string |
|
|
371
|
+
export function firstPostcodeValue(roots: readonly AddressNode[]): string | null {
|
|
366
372
|
for (const n of walkNodes(roots)) {
|
|
367
|
-
if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && n.value.trim()
|
|
373
|
+
if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && n.value.trim()) return n.value.trim()
|
|
368
374
|
}
|
|
369
375
|
|
|
370
|
-
return
|
|
376
|
+
return null
|
|
371
377
|
}
|
|
372
378
|
|
|
373
379
|
/**
|
|
@@ -380,7 +386,7 @@ export async function applySpanRescore(
|
|
|
380
386
|
roots: AddressNode[],
|
|
381
387
|
raw: string,
|
|
382
388
|
backend: ResolverBackend,
|
|
383
|
-
opts:
|
|
389
|
+
opts: ResolvedOpts
|
|
384
390
|
): Promise<void> {
|
|
385
391
|
if (hasResolvedPlace(roots, opts.spanRescoreWeakResolution ?? false)) return
|
|
386
392
|
|
|
@@ -388,20 +394,20 @@ export async function applySpanRescore(
|
|
|
388
394
|
|
|
389
395
|
try {
|
|
390
396
|
hit = await findRescoreCandidate(raw, roots, backend, {
|
|
391
|
-
country: opts.defaultCountry,
|
|
397
|
+
country: opts.defaultCountry?.country,
|
|
392
398
|
postcode: firstPostcodeValue(roots),
|
|
393
399
|
thresholdKm: opts.spanRescoreThresholdKm,
|
|
394
400
|
|
|
395
|
-
postalCompoundRecovery: opts.postalCompoundRecovery
|
|
401
|
+
postalCompoundRecovery: opts.postalCompoundRecovery,
|
|
396
402
|
spanRescoreRequireContextRemainder: opts.spanRescoreRequireContextRemainder,
|
|
397
403
|
})
|
|
398
404
|
} catch {
|
|
399
405
|
return
|
|
400
406
|
}
|
|
401
407
|
|
|
402
|
-
if (!hit && opts.postalCompoundRecovery
|
|
408
|
+
if (!hit && opts.postalCompoundRecovery) {
|
|
403
409
|
try {
|
|
404
|
-
await recoverPostcodeNode(roots, backend, opts.defaultCountry, opts.traceSink)
|
|
410
|
+
await recoverPostcodeNode(roots, backend, opts.defaultCountry?.country ?? null, opts.traceSink)
|
|
405
411
|
} catch {}
|
|
406
412
|
}
|
|
407
413
|
|
|
@@ -425,7 +431,7 @@ export async function applySpanRescore(
|
|
|
425
431
|
if (opts.traceSink) {
|
|
426
432
|
const rec = createNodeTraceRecorder(opts.traceSink)
|
|
427
433
|
|
|
428
|
-
rec.bind(node, "locality", opts.defaultCountry ? { country: opts.defaultCountry } : {}, 1)
|
|
434
|
+
rec.bind(node, "locality", opts.defaultCountry ? { country: opts.defaultCountry.country } : {}, 1)
|
|
429
435
|
rec.check("span_rescore")
|
|
430
436
|
rec.check(hit.postcodeVerified ? "rescore_postcode_verified" : "rescore_postcode_unverified")
|
|
431
437
|
rec.stage("rescore", [hit.place, ...hit.alternatives])
|
|
@@ -436,7 +442,7 @@ export async function applySpanRescore(
|
|
|
436
442
|
async function recoverPostcodeNode(
|
|
437
443
|
roots: AddressNode[],
|
|
438
444
|
backend: ResolverBackend,
|
|
439
|
-
country: string |
|
|
445
|
+
country: string | null,
|
|
440
446
|
traceSink?: (record: ResolveNodeTrace) => void
|
|
441
447
|
): Promise<void> {
|
|
442
448
|
for (const n of walkNodes(roots)) {
|
|
@@ -444,7 +450,14 @@ async function recoverPostcodeNode(
|
|
|
444
450
|
const code = postcodeCodeSubset(n.value)
|
|
445
451
|
|
|
446
452
|
if (!code || code === n.value.trim()) continue
|
|
447
|
-
|
|
453
|
+
|
|
454
|
+
const hits = await backend.findPlace({
|
|
455
|
+
text: code,
|
|
456
|
+
placetype: "postalcode",
|
|
457
|
+
...(country ? { country } : {}),
|
|
458
|
+
limit: 1,
|
|
459
|
+
})
|
|
460
|
+
|
|
448
461
|
const top = hits.find((h) => h.lat !== 0 || h.lon !== 0)
|
|
449
462
|
|
|
450
463
|
if (top) {
|
|
@@ -501,7 +514,7 @@ export function applyPostcodeConsistency(
|
|
|
501
514
|
|
|
502
515
|
if (gapKm <= thresholdKm) continue
|
|
503
516
|
|
|
504
|
-
const alts = (node.alternatives as ResolvedPlace[] |
|
|
517
|
+
const alts = (node.alternatives as ResolvedPlace[] | null) ?? []
|
|
505
518
|
|
|
506
519
|
const reconciling = alts
|
|
507
520
|
.filter((a) => a.lat !== 0 || a.lon !== 0)
|
|
@@ -512,6 +525,7 @@ export function applyPostcodeConsistency(
|
|
|
512
525
|
|
|
513
526
|
if (reconciling) {
|
|
514
527
|
const displaced: ResolvedPlace = {
|
|
528
|
+
...EMPTY_PLACE_FIELDS,
|
|
515
529
|
id: 0,
|
|
516
530
|
name: String(node.metadata?.["resolver_name"] ?? node.value),
|
|
517
531
|
placetype: "locality",
|
package/lib/resolve.ts
CHANGED
|
@@ -13,12 +13,14 @@ import { DEFAULT_PLACETYPE_MAP, isPlacetypeFallback } from "@mailwoman/codex/pla
|
|
|
13
13
|
import { collectNodes, type AddressNode, type AddressTree, type Interpretation } from "@mailwoman/core/decoder"
|
|
14
14
|
import {
|
|
15
15
|
type BackendCapabilityGap,
|
|
16
|
+
type DefaultCountry,
|
|
16
17
|
type ResolveNodeTrace,
|
|
17
18
|
type ResolvedPlace,
|
|
18
19
|
type ResolveOpts,
|
|
19
20
|
type Resolver,
|
|
20
21
|
type ResolverBackend,
|
|
21
22
|
countriesFromPostcodeFormat,
|
|
23
|
+
resolveSwitches,
|
|
22
24
|
} from "@mailwoman/core/resolver"
|
|
23
25
|
|
|
24
26
|
import {
|
|
@@ -55,6 +57,7 @@ import {
|
|
|
55
57
|
NOOP_TRACE_RECORDER,
|
|
56
58
|
pickCompletion,
|
|
57
59
|
type ResolutionState,
|
|
60
|
+
type ResolvedOpts,
|
|
58
61
|
} from "#resolve/passes"
|
|
59
62
|
import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "#street/tier"
|
|
60
63
|
import {
|
|
@@ -95,6 +98,23 @@ function explicitCountryScope(roots: readonly AddressNode[]): string | null {
|
|
|
95
98
|
return matched.iso2
|
|
96
99
|
}
|
|
97
100
|
|
|
101
|
+
/**
|
|
102
|
+
* The default country a lookup filters by, or undefined when none applies.
|
|
103
|
+
* `country` lookups ignore an inferred scope.
|
|
104
|
+
*/
|
|
105
|
+
function scopedCountryFor(placetype: string, scope: DefaultCountry | null): string | undefined {
|
|
106
|
+
if (!scope || (placetype === "country" && scope.source === "inferred")) return undefined
|
|
107
|
+
|
|
108
|
+
return scope.country
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Reports whether the caller chose the default country scope.
|
|
113
|
+
*/
|
|
114
|
+
function isCallerScope(scope: DefaultCountry | null): boolean {
|
|
115
|
+
return scope?.source === "caller"
|
|
116
|
+
}
|
|
117
|
+
|
|
98
118
|
class WOFResolver implements Resolver {
|
|
99
119
|
readonly #backend: ResolverBackend
|
|
100
120
|
/**
|
|
@@ -108,7 +128,7 @@ class WOFResolver implements Resolver {
|
|
|
108
128
|
|
|
109
129
|
constructor(backend: ResolverBackend) {
|
|
110
130
|
this.#backend = backend
|
|
111
|
-
this.artifactCoverage = backend.artifactCoverage
|
|
131
|
+
this.artifactCoverage = backend.artifactCoverage ?? null
|
|
112
132
|
this.capabilityGaps = describeCapabilityGaps(backend)
|
|
113
133
|
reportCapabilityGaps(this.capabilityGaps)
|
|
114
134
|
}
|
|
@@ -118,10 +138,12 @@ class WOFResolver implements Resolver {
|
|
|
118
138
|
*/
|
|
119
139
|
findPlace: Resolver["findPlace"] = (query) => this.#backend.findPlace(query)
|
|
120
140
|
|
|
121
|
-
async resolveTree(tree: AddressTree,
|
|
141
|
+
async resolveTree(tree: AddressTree, callerOpts: ResolveOpts = {}): Promise<AddressTree> {
|
|
142
|
+
// Every on/off switch resolves against the one defaults table, so the reads below are plain truthiness.
|
|
143
|
+
const opts: ResolvedOpts = { ...callerOpts, ...resolveSwitches(callerOpts) }
|
|
122
144
|
// Optional early postcode-shape pass.
|
|
123
145
|
// Runs sync and can only narrow candidates.
|
|
124
|
-
const shapeVerdict = opts.postcodeShapeCoherence
|
|
146
|
+
const shapeVerdict = opts.postcodeShapeCoherence ? applyPostcodeShapeCoherence(tree.roots) : null
|
|
125
147
|
|
|
126
148
|
const state: ResolutionState = {
|
|
127
149
|
lookupsRemaining: opts.maxLookups ?? 10,
|
|
@@ -130,17 +152,16 @@ class WOFResolver implements Resolver {
|
|
|
130
152
|
minWinningScore: opts.minWinningScore ?? 0,
|
|
131
153
|
minScoreRefusals: 0,
|
|
132
154
|
candidatesPerLookup: opts.candidatesPerLookup ?? 5,
|
|
133
|
-
defaultCountry: opts.defaultCountry,
|
|
134
|
-
defaultCountryIsInferred: opts.defaultCountryIsInferred === true,
|
|
155
|
+
defaultCountry: opts.defaultCountry ?? null,
|
|
135
156
|
bareLocalityNode: loneBareLocalityNode(tree, opts.placetypeMap ?? DEFAULT_PLACETYPE_MAP),
|
|
136
|
-
parentFallback: opts.parentFallback
|
|
157
|
+
parentFallback: opts.parentFallback,
|
|
137
158
|
// Only enable unreachable diagnostics when a trace sink exists.
|
|
138
159
|
...(opts.diagnoseUnreachable && opts.traceSink ? { diagnoseUnreachable: true } : {}),
|
|
139
160
|
postcode: firstPostcodeValue(tree.roots),
|
|
140
161
|
// Optional postcode-containment hint for locality lookups.
|
|
141
|
-
postcodeContainmentCoherence: opts.postcodeContainmentCoherence
|
|
162
|
+
postcodeContainmentCoherence: opts.postcodeContainmentCoherence,
|
|
142
163
|
// Optional postcode-prefix prior and index.
|
|
143
|
-
postcodePrefixPrior: opts.postcodePrefixPrior
|
|
164
|
+
postcodePrefixPrior: opts.postcodePrefixPrior,
|
|
144
165
|
postcodePrefixIndex: opts.postcodePrefixIndex,
|
|
145
166
|
// Derive format-implied countries when not provided.
|
|
146
167
|
postcodeFormatCountries:
|
|
@@ -154,10 +175,10 @@ class WOFResolver implements Resolver {
|
|
|
154
175
|
capitalLevel: opts.capitalLevel,
|
|
155
176
|
hardCountry: opts.hardCountry,
|
|
156
177
|
// Dual-role hierarchy completion (default on, backend-dependent).
|
|
157
|
-
hierarchyCompletion: opts.hierarchyCompletion
|
|
158
|
-
includeAncestors: opts.includeAncestors
|
|
178
|
+
hierarchyCompletion: opts.hierarchyCompletion,
|
|
179
|
+
includeAncestors: opts.includeAncestors,
|
|
159
180
|
// Optional admin containment rerank uses a pre-scanned region qualifier.
|
|
160
|
-
adminContainmentRerank: opts.adminContainmentRerank
|
|
181
|
+
adminContainmentRerank: opts.adminContainmentRerank,
|
|
161
182
|
regionQualifier: firstRegionQualifier(tree.roots),
|
|
162
183
|
...(opts.traceSink ? { traceSink: opts.traceSink } : {}),
|
|
163
184
|
localityNodePresent: false,
|
|
@@ -173,28 +194,28 @@ class WOFResolver implements Resolver {
|
|
|
173
194
|
// Explicit scope outranks inferred default scope.
|
|
174
195
|
let explicitScope: string | null = null
|
|
175
196
|
|
|
176
|
-
if (
|
|
197
|
+
if (state.defaultCountry?.source !== "caller") {
|
|
177
198
|
explicitScope = explicitCountryScope(tree.roots)
|
|
178
199
|
|
|
179
200
|
if (explicitScope) {
|
|
180
|
-
state.defaultCountry = explicitScope
|
|
181
|
-
state.defaultCountryIsInferred = false
|
|
201
|
+
state.defaultCountry = { country: explicitScope, source: "caller" }
|
|
182
202
|
}
|
|
183
203
|
}
|
|
184
204
|
|
|
185
|
-
if (opts.postcodeCountryCoherence
|
|
205
|
+
if (opts.postcodeCountryCoherence && state.postcode) {
|
|
186
206
|
postcodeScope = await findPostcodeCountryScope(tree.roots, this.#backend, {
|
|
187
207
|
postcode: state.postcode,
|
|
188
|
-
defaultCountry: state.defaultCountry,
|
|
189
|
-
...(shapeVerdict?.narrowing
|
|
190
|
-
...(opts.postcodeCountryCoherenceThresholdKm
|
|
208
|
+
defaultCountry: state.defaultCountry?.country ?? null,
|
|
209
|
+
...(shapeVerdict?.narrowing ? { candidateSystems: shapeVerdict.narrowing } : {}),
|
|
210
|
+
...(opts.postcodeCountryCoherenceThresholdKm != null
|
|
191
211
|
? { thresholdKm: opts.postcodeCountryCoherenceThresholdKm }
|
|
192
212
|
: {}),
|
|
193
213
|
})
|
|
194
214
|
|
|
195
215
|
if (postcodeScope) {
|
|
196
216
|
// Override default country for the walk.
|
|
197
|
-
|
|
217
|
+
// The postcode's country replaces the scope but keeps its source.
|
|
218
|
+
state.defaultCountry = { country: postcodeScope.country, source: state.defaultCountry?.source ?? "caller" }
|
|
198
219
|
}
|
|
199
220
|
}
|
|
200
221
|
|
|
@@ -224,18 +245,18 @@ class WOFResolver implements Resolver {
|
|
|
224
245
|
}
|
|
225
246
|
|
|
226
247
|
// Admin coherence passes (default on).
|
|
227
|
-
if (opts.adminCoherence
|
|
248
|
+
if (opts.adminCoherence) {
|
|
228
249
|
// Clear contradictory parent-fallback picks before coherence passes.
|
|
229
250
|
applyParentFallbackContradiction(newRoots)
|
|
230
251
|
await applyAdminCoherence(newRoots, this.#backend)
|
|
231
252
|
// Re-resolve locality when explicit country contradicts it.
|
|
232
253
|
await applyExplicitCountryCoherence(newRoots, this.#backend)
|
|
233
254
|
// Re-resolve foreign region/locality pairs blocked by locale scope.
|
|
234
|
-
await applyRegionCountryCoherence(newRoots, this.#backend, state.defaultCountry)
|
|
255
|
+
await applyRegionCountryCoherence(newRoots, this.#backend, state.defaultCountry?.country ?? null)
|
|
235
256
|
}
|
|
236
257
|
|
|
237
258
|
// Postcode/locality consistency pass (default on).
|
|
238
|
-
if (opts.postcodeConsistency
|
|
259
|
+
if (opts.postcodeConsistency) {
|
|
239
260
|
applyPostcodeConsistency(newRoots, opts.postcodeConsistencyThresholdKm ?? 50, opts.postcodeConsistencyMaxMoveKm)
|
|
240
261
|
}
|
|
241
262
|
|
|
@@ -251,7 +272,7 @@ class WOFResolver implements Resolver {
|
|
|
251
272
|
|
|
252
273
|
// Span-rescore fallback tier (default on).
|
|
253
274
|
// Skip when a min-score refusal already occurred.
|
|
254
|
-
if (opts.spanRescore
|
|
275
|
+
if (opts.spanRescore && state.minScoreRefusals === 0) {
|
|
255
276
|
await applySpanRescore(newRoots, tree.raw, this.#backend, opts)
|
|
256
277
|
}
|
|
257
278
|
|
|
@@ -309,7 +330,7 @@ class WOFResolver implements Resolver {
|
|
|
309
330
|
let resolved: CoordinateOptionalPlace | null = null
|
|
310
331
|
|
|
311
332
|
// Skip lookup for shape-excluded postcode spans.
|
|
312
|
-
if (placetype && state.lookupsRemaining > 0 && node.value.trim()
|
|
333
|
+
if (placetype && state.lookupsRemaining > 0 && node.value.trim() && !isShapeExcludedPostcode(node)) {
|
|
313
334
|
let picked = await this.#lookupAndPick(node, placetype, parentResolved, state)
|
|
314
335
|
|
|
315
336
|
// Compound JP municipality handling with scoped fallback control.
|
|
@@ -428,8 +449,7 @@ class WOFResolver implements Resolver {
|
|
|
428
449
|
const countryHint = node.metadata?.["country_hint"]
|
|
429
450
|
|
|
430
451
|
// Do not apply inferred default-country filtering to country lookups.
|
|
431
|
-
const defaultCountryForLookup =
|
|
432
|
-
placetype === "country" && state.defaultCountryIsInferred ? undefined : state.defaultCountry
|
|
452
|
+
const defaultCountryForLookup = scopedCountryFor(placetype, state.defaultCountry)
|
|
433
453
|
|
|
434
454
|
const country =
|
|
435
455
|
parentResolved?.country ??
|
|
@@ -450,11 +470,11 @@ class WOFResolver implements Resolver {
|
|
|
450
470
|
const containmentEligible =
|
|
451
471
|
state.adminContainmentRerank &&
|
|
452
472
|
placetype === "locality" &&
|
|
453
|
-
state.regionQualifier
|
|
454
|
-
(
|
|
473
|
+
state.regionQualifier != null &&
|
|
474
|
+
!isCallerScope(state.defaultCountry)
|
|
455
475
|
|
|
456
476
|
if (containmentEligible) {
|
|
457
|
-
query.regionQualifier = state.regionQualifier
|
|
477
|
+
query.regionQualifier = state.regionQualifier!
|
|
458
478
|
}
|
|
459
479
|
|
|
460
480
|
// Optional locality postcode hint and containment coherence flag.
|
|
@@ -477,7 +497,7 @@ class WOFResolver implements Resolver {
|
|
|
477
497
|
// For unconstrained postalcodes, probe format-implied countries only.
|
|
478
498
|
if (placetype === "postalcode" && !query.country && state.postcodeFormatCountries?.length) {
|
|
479
499
|
rec.check("postcode_format_probe")
|
|
480
|
-
let best: ResolvedPlace |
|
|
500
|
+
let best: ResolvedPlace | null = null
|
|
481
501
|
|
|
482
502
|
for (const impliedCountry of state.postcodeFormatCountries) {
|
|
483
503
|
try {
|
|
@@ -511,7 +531,7 @@ class WOFResolver implements Resolver {
|
|
|
511
531
|
}
|
|
512
532
|
|
|
513
533
|
// If parent scope misses, retry once without parent scope.
|
|
514
|
-
if (!candidates.length && state.parentFallback && query.parentID
|
|
534
|
+
if (!candidates.length && state.parentFallback && query.parentID != null) {
|
|
515
535
|
delete query.parentID
|
|
516
536
|
rec.check("parent_fallback_retry")
|
|
517
537
|
candidates = await this.#backend.findPlace(query)
|
|
@@ -539,10 +559,8 @@ class WOFResolver implements Resolver {
|
|
|
539
559
|
const metadata: Record<string, unknown> = {
|
|
540
560
|
postcode_prefix: probe.prefix,
|
|
541
561
|
postcode_prefix_ancestors: probe.node.ancestors,
|
|
542
|
-
...(probe.node.radiusP95Km
|
|
543
|
-
...(probe.node.lat
|
|
544
|
-
? { coordinate_source: "postcode_prefix" }
|
|
545
|
-
: {}),
|
|
562
|
+
...(probe.node.radiusP95Km != null ? { postcode_prefix_radius_p95_km: probe.node.radiusP95Km } : {}),
|
|
563
|
+
...(probe.node.lat != null && probe.node.lon != null ? { coordinate_source: "postcode_prefix" } : {}),
|
|
546
564
|
}
|
|
547
565
|
|
|
548
566
|
rec.check("postcode_prefix_prior")
|
|
@@ -604,8 +622,8 @@ class WOFResolver implements Resolver {
|
|
|
604
622
|
|
|
605
623
|
if (tier !== 0) return tier
|
|
606
624
|
// Unknown-country candidates get zero posterior mass.
|
|
607
|
-
const aKey = (a.prominence ?? a.score) + w * (a.country
|
|
608
|
-
const bKey = (b.prominence ?? b.score) + w * (b.country
|
|
625
|
+
const aKey = (a.prominence ?? a.score) + w * (a.country ? (post[a.country] ?? 0) : 0)
|
|
626
|
+
const bKey = (b.prominence ?? b.score) + w * (b.country ? (post[b.country] ?? 0) : 0)
|
|
609
627
|
|
|
610
628
|
return bKey - aKey || b.score - a.score
|
|
611
629
|
})
|
|
@@ -694,7 +712,7 @@ class WOFResolver implements Resolver {
|
|
|
694
712
|
...(containmentEligible ? { admin_containment: adminContainmentVerdict(ranked) } : {}),
|
|
695
713
|
...(top.variantAliasExempted === true ? { variant_alias_exemption: true } : {}),
|
|
696
714
|
// Mark picks admitted outside resolved parent scope.
|
|
697
|
-
...((parentResolved && typeof parentResolved.id === "number" && query.parentID
|
|
715
|
+
...((parentResolved && typeof parentResolved.id === "number" && query.parentID == null) ||
|
|
698
716
|
top.regionScopeMiss === true
|
|
699
717
|
? { parent_fallback: true }
|
|
700
718
|
: {}),
|
package/lib/span-rescore.ts
CHANGED
|
@@ -25,7 +25,7 @@ export interface SpanRescoreOptions {
|
|
|
25
25
|
/**
|
|
26
26
|
* The sibling postcode serves as the backend disambiguation hint and the consistency-check anchor.
|
|
27
27
|
*/
|
|
28
|
-
postcode?: string
|
|
28
|
+
postcode?: string | null
|
|
29
29
|
/**
|
|
30
30
|
* Reject a candidate whose coordinate is farther than this (km) from the postcode anchor.
|
|
31
31
|
*
|
|
@@ -33,19 +33,20 @@ export interface SpanRescoreOptions {
|
|
|
33
33
|
* A backend without postcode coverage receives no penalty.
|
|
34
34
|
*
|
|
35
35
|
* A value of 0 disables the check.
|
|
36
|
-
*
|
|
36
|
+
*
|
|
37
|
+
* @defaultValue `50`
|
|
37
38
|
*/
|
|
38
39
|
thresholdKm?: number
|
|
39
40
|
/**
|
|
40
41
|
* Max contiguous raw tokens to treat as one locality span.
|
|
41
42
|
*
|
|
42
|
-
*
|
|
43
|
+
* @defaultValue `4`
|
|
43
44
|
*/
|
|
44
45
|
maxSpanTokens?: number
|
|
45
46
|
/**
|
|
46
47
|
* Min confidence for a street/house_number/postcode node to count as a span-blocking constituent.
|
|
47
48
|
*
|
|
48
|
-
*
|
|
49
|
+
* @defaultValue `0.7`
|
|
49
50
|
*/
|
|
50
51
|
confidentThreshold?: number
|
|
51
52
|
/**
|
|
@@ -53,26 +54,29 @@ export interface SpanRescoreOptions {
|
|
|
53
54
|
* postcode node blocks only those code tokens, leaving the residual name tokens as span material.
|
|
54
55
|
*
|
|
55
56
|
* Street/affix blocking is untouched.
|
|
56
|
-
*
|
|
57
|
+
*
|
|
58
|
+
* @defaultValue `false`
|
|
57
59
|
*/
|
|
58
60
|
postalCompoundRecovery?: boolean
|
|
59
61
|
/**
|
|
60
62
|
* When the span covers the whole unqualified input, treat {@link country} as an additive prior
|
|
61
63
|
* instead of a hard gazetteer filter; `false` restores the hard filter byte-for-byte.
|
|
62
|
-
*
|
|
64
|
+
*
|
|
65
|
+
* @defaultValue `true`
|
|
63
66
|
*/
|
|
64
67
|
bareToponymSoftCountry?: boolean
|
|
65
68
|
/**
|
|
66
69
|
* Weight of that prior, in log10-population units.
|
|
67
70
|
*
|
|
68
|
-
*
|
|
71
|
+
* @defaultValue {@linkcode DEFAULT_COUNTRY_PRIOR_WEIGHT} (2), and 0 removes the locale's say entirely.
|
|
69
72
|
*/
|
|
70
73
|
bareToponymCountryWeight?: number
|
|
71
74
|
/**
|
|
72
75
|
* Admit a proper sub-span only when every token it leaves behind is a subdivision code or a number.
|
|
73
76
|
*
|
|
74
77
|
* See `remainderIsContext` for the rule.
|
|
75
|
-
*
|
|
78
|
+
*
|
|
79
|
+
* @defaultValue `false`
|
|
76
80
|
*/
|
|
77
81
|
spanRescoreRequireContextRemainder?: boolean
|
|
78
82
|
}
|
|
@@ -122,7 +126,7 @@ function tokenizeRaw(raw: string): RawTok[] {
|
|
|
122
126
|
const re = /[^\s,;/]+/g
|
|
123
127
|
let m: RegExpExecArray | null
|
|
124
128
|
|
|
125
|
-
while ((m = re.exec(raw))
|
|
129
|
+
while ((m = re.exec(raw))) {
|
|
126
130
|
toks.push({ text: m[0], start: m.index, end: m.index + m[0].length })
|
|
127
131
|
}
|
|
128
132
|
|
|
@@ -163,7 +167,7 @@ function hasAdminQualifier(roots: readonly AddressNode[]): boolean {
|
|
|
163
167
|
n.tag === "postcode" ||
|
|
164
168
|
n.tag === "house_number") &&
|
|
165
169
|
n.value.trim().length > 0
|
|
166
|
-
)
|
|
170
|
+
) != null
|
|
167
171
|
)
|
|
168
172
|
}
|
|
169
173
|
|
|
@@ -190,9 +194,7 @@ export function hasResolvedPlace(
|
|
|
190
194
|
roots: readonly AddressNode[],
|
|
191
195
|
weakReading: WeakResolutionReading | false = false
|
|
192
196
|
): boolean {
|
|
193
|
-
return (
|
|
194
|
-
firstNodeWhere(roots, (n) => Boolean(n.placeID) && !(weakReading && resolvedWeakly(n, weakReading))) !== undefined
|
|
195
|
-
)
|
|
197
|
+
return firstNodeWhere(roots, (n) => Boolean(n.placeID) && !(weakReading && resolvedWeakly(n, weakReading))) != null
|
|
196
198
|
}
|
|
197
199
|
|
|
198
200
|
/**
|
|
@@ -384,14 +386,14 @@ export async function findRescoreCandidate(
|
|
|
384
386
|
* The token a sub-span probe leaves behind when it reads as an administrative qualifier: one token
|
|
385
387
|
* of 2 or 3 uppercase ASCII letters, shaped as a subdivision code rather than looked up in a table.
|
|
386
388
|
*/
|
|
387
|
-
const qualifierRemainder = (span: { start: number; end: number }): string |
|
|
389
|
+
const qualifierRemainder = (span: { start: number; end: number }): string | null => {
|
|
388
390
|
const outside = toks.filter((t) => t.end <= span.start || t.start >= span.end)
|
|
389
391
|
|
|
390
|
-
if (outside.length !== 1) return
|
|
392
|
+
if (outside.length !== 1) return null
|
|
391
393
|
|
|
392
394
|
const token = outside[0]!.text
|
|
393
395
|
|
|
394
|
-
return isRegionAbbreviationToken(token, { maxLetters: 3 }) ? token :
|
|
396
|
+
return isRegionAbbreviationToken(token, { maxLetters: 3 }) ? token : null
|
|
395
397
|
}
|
|
396
398
|
|
|
397
399
|
/**
|
|
@@ -432,7 +434,7 @@ export async function findRescoreCandidate(
|
|
|
432
434
|
if (opts.spanRescoreRequireContextRemainder && !wholeSpan && !remainderIsContext(sp)) continue
|
|
433
435
|
|
|
434
436
|
const bare = softCountryEligible && wholeSpan
|
|
435
|
-
const qualifier = wholeSpan ?
|
|
437
|
+
const qualifier = wholeSpan ? null : qualifierRemainder(sp)
|
|
436
438
|
|
|
437
439
|
const hits = bare
|
|
438
440
|
? rankByCountryPrior(
|
|
@@ -453,7 +455,7 @@ export async function findRescoreCandidate(
|
|
|
453
455
|
// The qualifier the sub-span left behind.
|
|
454
456
|
// A backend without the ancestors sidecar ignores this qualifier.
|
|
455
457
|
// That matches a query without one.
|
|
456
|
-
...(qualifier
|
|
458
|
+
...(qualifier ? { regionQualifier: qualifier } : {}),
|
|
457
459
|
})
|
|
458
460
|
|
|
459
461
|
// No primary-name re-check: `exactMatch` is name-or-alias, so re-comparing only
|
|
@@ -465,14 +467,13 @@ export async function findRescoreCandidate(
|
|
|
465
467
|
|
|
466
468
|
// The same partition the walk applies: tier-safe, stable and positive-evidence-only,
|
|
467
469
|
// so a backend that ignored `regionQualifier` is byte-stable.
|
|
468
|
-
const exact =
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
)
|
|
470
|
+
const exact = qualifier
|
|
471
|
+
? partitionByContainment(
|
|
472
|
+
ranked,
|
|
473
|
+
(c) => c.containedByQualifier === true,
|
|
474
|
+
(c) => c.exactMatch === true
|
|
475
|
+
)
|
|
476
|
+
: ranked
|
|
476
477
|
|
|
477
478
|
const withinThreshold = (p: ResolvedPlace): boolean =>
|
|
478
479
|
!anchor || thresholdKm <= 0 || haversineKm(anchor.lat, anchor.lon, p.lat, p.lon) <= thresholdKm
|