@mailwoman/core 11.4.0 → 12.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/lib/decoder/build-tree.ts +57 -3
  2. package/lib/decoder/types.ts +32 -0
  3. package/lib/geocode/result.ts +42 -0
  4. package/lib/pipeline/types.ts +22 -0
  5. package/lib/resolver/outcome.ts +255 -0
  6. package/lib/resolver/synthetic-id-ranges.ts +39 -1
  7. package/lib/resolver/types.ts +59 -2
  8. package/lib/scripting/arguments.ts +1 -1
  9. package/out/decoder/build-tree.d.ts +8 -1
  10. package/out/decoder/build-tree.d.ts.map +1 -1
  11. package/out/decoder/build-tree.js +35 -2
  12. package/out/decoder/build-tree.js.map +1 -1
  13. package/out/decoder/types.d.ts +33 -0
  14. package/out/decoder/types.d.ts.map +1 -1
  15. package/out/decoder/types.js +7 -0
  16. package/out/decoder/types.js.map +1 -1
  17. package/out/geocode/result.d.ts +31 -0
  18. package/out/geocode/result.d.ts.map +1 -1
  19. package/out/geocode/result.js +39 -0
  20. package/out/geocode/result.js.map +1 -1
  21. package/out/pipeline/types.d.ts +42 -0
  22. package/out/pipeline/types.d.ts.map +1 -1
  23. package/out/pipeline/types.js +10 -0
  24. package/out/pipeline/types.js.map +1 -1
  25. package/out/resolver/outcome.d.ts +166 -0
  26. package/out/resolver/outcome.d.ts.map +1 -0
  27. package/out/resolver/outcome.js +122 -0
  28. package/out/resolver/outcome.js.map +1 -0
  29. package/out/resolver/synthetic-id-ranges.d.ts +26 -0
  30. package/out/resolver/synthetic-id-ranges.d.ts.map +1 -1
  31. package/out/resolver/synthetic-id-ranges.js +23 -1
  32. package/out/resolver/synthetic-id-ranges.js.map +1 -1
  33. package/out/resolver/types.d.ts +58 -1
  34. package/out/resolver/types.d.ts.map +1 -1
  35. package/out/resolver/types.js +1 -1
  36. package/out/resolver/types.js.map +1 -1
  37. package/out/scripting/arguments.js +1 -1
  38. package/out/scripting/arguments.js.map +1 -1
  39. package/package.json +24 -14
@@ -28,7 +28,13 @@ import type { BIOLabel, ComponentTag } from "@mailwoman/codex/component"
28
28
 
29
29
  import type { Calibrator } from "#decoder/calibration"
30
30
  import { containmentFor } from "#decoder/containment"
31
- import type { AddressNode, AddressSystem, AddressTree, DecoderToken } from "#decoder/types"
31
+ import {
32
+ type AddressNode,
33
+ type AddressSystem,
34
+ type AddressTree,
35
+ type DecoderToken,
36
+ INTERPRETATION_MARGIN,
37
+ } from "#decoder/types"
32
38
 
33
39
  /**
34
40
  * Optional caller-supplied attribution stamped on every emitted node.
@@ -64,6 +70,13 @@ export interface BuildTreeOpts {
64
70
  * Build one via `createCalibrator` (`./calibration.ts`).
65
71
  */
66
72
  calibrate?: Calibrator
73
+ /**
74
+ * When true, a span whose closest other tag scores within `INTERPRETATION_MARGIN`
75
+ * of its own stores that tag in its node's `interpretations`.
76
+ *
77
+ * Off by default, because the serializers emit each interpretation as a role of the span.
78
+ */
79
+ runnerUpInterpretations?: boolean
67
80
  }
68
81
 
69
82
  interface OpenSpan {
@@ -71,6 +84,24 @@ interface OpenSpan {
71
84
  start: number
72
85
  end: number
73
86
  confidences: number[]
87
+ /**
88
+ * The span's closest runner-up of another tag, over every piece the span holds.
89
+ */
90
+ runnerUp: { tag: ComponentTag; margin: number } | null
91
+ }
92
+
93
+ /**
94
+ * Folds one piece's runner-up into a span's, keeping the smallest lead to another tag.
95
+ */
96
+ function foldRunnerUp(open: OpenSpan, tok: DecoderToken): void {
97
+ if (!tok.runnerUp) return
98
+ const { tag } = bioParts(tok.runnerUp.label)
99
+
100
+ if (!tag || tag === open.tag) return
101
+
102
+ if (!open.runnerUp || tok.runnerUp.margin < open.runnerUp.margin) {
103
+ open.runnerUp = { tag, margin: tok.runnerUp.margin }
104
+ }
74
105
  }
75
106
 
76
107
  function bioParts(label: BIOLabel): { prefix: "B" | "I" | "O"; tag: ComponentTag | null } {
@@ -165,6 +196,12 @@ function flush(open: OpenSpan | null, raw: string, out: AddressNode[], attributi
165
196
  const confidence = attribution.calibrate ? attribution.calibrate(rawConfidence) : rawConfidence
166
197
  const node: AddressNode = { tag: open.tag, start, end, value, confidence, children: [] }
167
198
 
199
+ // A span whose closest other tag is within the margin has two readings,
200
+ // and the resolver's outcome ordering reads the second from here.
201
+ if (attribution.runnerUpInterpretations && open.runnerUp && open.runnerUp.margin <= INTERPRETATION_MARGIN) {
202
+ node.interpretations = [{ tag: open.runnerUp.tag }]
203
+ }
204
+
168
205
  if (attribution.source) {
169
206
  node.source = attribution.source
170
207
  }
@@ -212,18 +249,21 @@ function emitSpans(raw: string, tokens: DecoderToken[], attribution: BuildTreeOp
212
249
  if (prefix === "B" && open && open.tag === tag && /^\s*$/.test(raw.slice(open.end, tok.start))) {
213
250
  open.end = tok.end
214
251
  open.confidences.push(tok.confidence)
252
+ foldRunnerUp(open, tok)
215
253
 
216
254
  continue
217
255
  }
218
256
 
219
257
  flush(open, raw, out, attribution)
220
- open = { tag: tag!, start: tok.start, end: tok.end, confidences: [tok.confidence] }
258
+ open = { tag: tag!, start: tok.start, end: tok.end, confidences: [tok.confidence], runnerUp: null }
259
+ foldRunnerUp(open, tok)
221
260
 
222
261
  continue
223
262
  }
224
263
 
225
264
  open.end = tok.end
226
265
  open.confidences.push(tok.confidence)
266
+ foldRunnerUp(open, tok)
227
267
  }
228
268
 
229
269
  flush(open, raw, out, attribution)
@@ -286,10 +326,24 @@ export function buildAddressTree(raw: string, tokens: DecoderToken[], opts: Buil
286
326
  const roots: AddressNode[] = []
287
327
  const parentOf = containmentFor(opts.system, opts.country)
288
328
 
329
+ const parentBySpan = new Map<AddressNode, AddressNode>()
330
+
331
+ const wouldCycle = (child: AddressNode, candidate: AddressNode): boolean => {
332
+ let cur: AddressNode | undefined = candidate
333
+
334
+ while (cur) {
335
+ if (cur === child) return true
336
+ cur = parentBySpan.get(cur)
337
+ }
338
+
339
+ return false
340
+ }
341
+
289
342
  for (const span of spans) {
290
343
  const parent = findParent(span, spans, parentOf)
291
344
 
292
- if (parent) {
345
+ if (parent && !wouldCycle(span, parent)) {
346
+ parentBySpan.set(span, parent)
293
347
  parent.children.push(span)
294
348
  } else {
295
349
  roots.push(span)
@@ -34,8 +34,23 @@ export interface DecoderToken {
34
34
  * The softmax confidence of the label, in `[0, 1]`.
35
35
  */
36
36
  confidence: number
37
+ /**
38
+ * The highest-scoring label of another component tag in this piece's emission row,
39
+ * and the decoded label's lead over it in the row's log space.
40
+ *
41
+ * Absent when the decoder doesn't report it, or when every other tag in the row is unreachable.
42
+ */
43
+ runnerUp?: { label: BIOLabel; margin: number }
37
44
  }
38
45
 
46
+ /**
47
+ * The largest emission lead at which a span's runner-up tag becomes an `interpretations` entry.
48
+ *
49
+ * Emissions are in log space, so a lead of `ln 2` means the runner-up's probability
50
+ * is at least half the decoded label's.
51
+ */
52
+ export const INTERPRETATION_MARGIN = Math.LN2
53
+
39
54
  /**
40
55
  * An address component span and the components it contains.
41
56
  */
@@ -185,6 +200,23 @@ export interface AddressTree {
185
200
  * The country predicted by the parse-time locale classifier, when it was confident.
186
201
  */
187
202
  localeCountry?: { country: string; confidence: number }
203
+ /**
204
+ * The outcome head's distribution over the readings the caller wants returned, in the model
205
+ * card's `outcomes.head_classes` order (`docs/engineering/reference/outcome-kinds.mdx`).
206
+ *
207
+ * `null` when the graph has no outcome head.
208
+ * A tree built by another parser omits the field.
209
+ */
210
+ outcomeDistribution?: readonly OutcomeProbability[] | null
211
+ }
212
+
213
+ /**
214
+ * One reading of the outcome head's distribution: an identity top level of the
215
+ * outcome vocabulary and its probability.
216
+ */
217
+ export interface OutcomeProbability {
218
+ outcome: string
219
+ probability: number
188
220
  }
189
221
 
190
222
  /**
@@ -58,6 +58,34 @@ export const ScoreUnmeasuredReasonSchema = z
58
58
  .enum(Object.values(ScoreUnmeasuredReason))
59
59
  .meta({ id: "ScoreUnmeasuredReason", description: "Why a candidate's score is null." })
60
60
 
61
+ /**
62
+ * One member of a place's outcome set.
63
+ */
64
+ export const OutcomeMembershipSchema = z
65
+ .object({
66
+ /**
67
+ * The outcome kind, such as `natural.mountain`.
68
+ */
69
+ outcome: z.string(),
70
+ /**
71
+ * True when one source asserts the member and another denies it.
72
+ * The member stays in the set.
73
+ */
74
+ contested: z.boolean(),
75
+ /**
76
+ * Where the member came from: the data layer and `default` or `asserted`, as in `landmarks:asserted`.
77
+ */
78
+ sources: z.array(z.string()),
79
+ })
80
+ .meta({ id: "OutcomeMembership", description: "One member of a place's outcome set." })
81
+
82
+ /**
83
+ * Whether the loaded model reads the outcome hint and has an outcome head.
84
+ */
85
+ export const OutcomeHintModelSchema = z
86
+ .enum(["applied", "unsupported"])
87
+ .meta({ id: "OutcomeHintModel", description: "Whether the loaded model reads the outcome hint." })
88
+
61
89
  /**
62
90
  * One place the resolver weighed for a parsed span: the winner first, then the places it passed over.
63
91
  */
@@ -111,6 +139,12 @@ export const GeocodeCandidateSchema = z
111
139
  * The field is absent for a place inside the scope.
112
140
  */
113
141
  outsideScope: z.literal(true).optional(),
142
+ /**
143
+ * The place's outcome set, each member with its `contested` flag and its sources.
144
+ *
145
+ * The field is present when the request set `outcomeHint` or `outcomeFilter`.
146
+ */
147
+ outcomes: z.array(OutcomeMembershipSchema).optional(),
114
148
  })
115
149
  .meta({ id: "GeocodeCandidate", description: "A place the resolver weighed for one parsed span." })
116
150
 
@@ -443,6 +477,14 @@ export const GeocodeResultSchema = z
443
477
  * Every value inside comes from the provider, including `refused` and `transport_error`.
444
478
  */
445
479
  authoritative: AuthoritativeAssertionSchema.nullable(),
480
+
481
+ /**
482
+ * `unsupported` when the loaded model has no outcome head, so only the resolver read
483
+ * the request's outcome fields, and `applied` when the model read them too.
484
+ *
485
+ * The field is present when the request set `outcomeHint` or `outcomeFilter`.
486
+ */
487
+ outcome_hint_model: OutcomeHintModelSchema.optional(),
446
488
  })
447
489
  .meta({ id: "GeocodeResult", description: "One geocoded input: its coordinate, tier, components and evidence." })
448
490
 
@@ -424,6 +424,16 @@ export const QueryIntentCode = {
424
424
  * The evidence lists the unused components and both tiers.
425
425
  */
426
426
  DeclaredCoarserAnswer: "declared_coarser_answer",
427
+ /**
428
+ * The answer doesn't satisfy the request's `outcomeHint`.
429
+ *
430
+ * The text's evidence decided the answer, and the hint only ordered its candidates.
431
+ */
432
+ OutcomeHintUnsatisfied: "outcome_hint_unsatisfied",
433
+ /**
434
+ * The request's `outcomeFilter` admitted zero candidates, and the result lists zero places.
435
+ */
436
+ OutcomeFilterEmpty: "outcome_filter_empty",
427
437
  } as const
428
438
 
429
439
  /**
@@ -848,6 +858,18 @@ export interface ClassifierOpts {
848
858
  * and other classifiers ignore it.
849
859
  */
850
860
  localeHint?: string
861
+ /**
862
+ * The outcome kind the caller expects (e.g. `natural.mountain`).
863
+ *
864
+ * A model with an `outcome_hint` input reads it as evidence it can overrule,
865
+ * and other classifiers ignore it.
866
+ */
867
+ outcomeHint?: string
868
+ /**
869
+ * When true, a span whose closest other tag scores within `INTERPRETATION_MARGIN`
870
+ * records that runner-up tag in `node.interpretations` for outcome head ordering.
871
+ */
872
+ runnerUpInterpretations?: boolean
851
873
  fst?: FSTMatcherLike | null
852
874
  fstBiasScale?: number
853
875
  /**
@@ -0,0 +1,255 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * The request side of outcome kinds: the two request fields, their refusals,
6
+ * and the satisfaction rule the resolver and the data layers share.
7
+ *
8
+ * `docs/engineering/reference/outcome-kinds.mdx` is the design.
9
+ * An outcome id is a top-level name or a top-level name and one second-level name joined by a dot.
10
+ *
11
+ * A record satisfies an id when one of its members equals it or begins with it and a dot.
12
+ */
13
+
14
+ /**
15
+ * One member of the outcome vocabulary, as the compiled definitions state it.
16
+ *
17
+ * `OUTCOME_VOCABULARY` in `@mailwoman/gazetteer/whosonfirst/outcomes/vocabulary` is the
18
+ * vocabulary's home, and this shape is the part of each row the resolver reads.
19
+ */
20
+ export interface OutcomeVocabularyLike {
21
+ /**
22
+ * The `mw:id` a compiled database stores in its `outcome_id` columns.
23
+ */
24
+ readonly id: number
25
+ /**
26
+ * The `mw:name`, such as `natural.mountain`.
27
+ */
28
+ readonly name: string
29
+ /**
30
+ * The `mw:facet`: `identity` states what a record is, `role` how people use it.
31
+ */
32
+ readonly facet: "identity" | "role"
33
+ }
34
+
35
+ /**
36
+ * The two outcome fields of a geocode request.
37
+ */
38
+ export interface OutcomeOptions {
39
+ /**
40
+ * The reading the caller expects.
41
+ *
42
+ * The resolver orders candidates that satisfy it first, inside each conformance class, and removes none.
43
+ */
44
+ outcomeHint?: string
45
+ /**
46
+ * The readings the caller admits.
47
+ *
48
+ * A record is admissible when it satisfies one id in the list.
49
+ * Each data layer applies it inside its own query, before its row limit.
50
+ */
51
+ outcomeFilter?: readonly string[]
52
+ }
53
+
54
+ /**
55
+ * One member of a resolved place's outcome set.
56
+ */
57
+ export interface OutcomeMembership {
58
+ outcome: string
59
+ /**
60
+ * True when one source asserts the member and another denies it.
61
+ * The member stays in the set.
62
+ */
63
+ contested: boolean
64
+ /**
65
+ * Where the member came from, one entry per data layer and kind of evidence,
66
+ * such as `candidate:default` or `landmarks:asserted`.
67
+ */
68
+ sources: readonly string[]
69
+ }
70
+
71
+ /**
72
+ * What a data layer's query reads of the outcome request.
73
+ */
74
+ export interface OutcomeQuery {
75
+ readonly vocabulary: readonly OutcomeVocabularyLike[]
76
+ /**
77
+ * The `mw:id`s a row must hold one of to be read, or `null` to read every row.
78
+ *
79
+ * The resolver expands a request id to itself and every member it is a prefix of.
80
+ */
81
+ readonly admit: readonly number[] | null
82
+ }
83
+
84
+ /**
85
+ * The data layers a span's outcome-ordered candidate list reads, in the order their
86
+ * candidates follow when cross-layer prominence is missing.
87
+ */
88
+ export const OutcomeLayer = {
89
+ Candidate: "candidate",
90
+ Landmarks: "landmarks",
91
+ OpenStreetMap: "openstreetmap",
92
+ } as const
93
+
94
+ export type OutcomeLayer = (typeof OutcomeLayer)[keyof typeof OutcomeLayer]
95
+
96
+ /**
97
+ * The outcome request a resolve reads, checked against the vocabulary.
98
+ */
99
+ export interface ResolveOutcome {
100
+ readonly vocabulary: readonly OutcomeVocabularyLike[]
101
+ readonly hint: string | null
102
+ readonly filter: readonly string[] | null
103
+ /**
104
+ * The outcome head's identity top levels, most probable first, when the head's
105
+ * ordering is on and the query is eligible for it, and `null` otherwise.
106
+ */
107
+ readonly headOrder: readonly string[] | null
108
+ }
109
+
110
+ /**
111
+ * The outcome tables a compiled database holds.
112
+ */
113
+ export const OUTCOME_TABLES = ["outcome_default", "record_outcome"] as const
114
+
115
+ /**
116
+ * Why an outcome request was refused.
117
+ */
118
+ export const OutcomeRefusal = {
119
+ /**
120
+ * An id that isn't a member of the vocabulary.
121
+ */
122
+ UnknownOutcome: "unknown_outcome",
123
+ /**
124
+ * A hint that zero filter ids admit.
125
+ */
126
+ HintOutsideFilter: "hint_outside_filter",
127
+ /**
128
+ * A database built before the outcome tables.
129
+ */
130
+ MissingOutcomeTables: "missing_outcome_tables",
131
+ /**
132
+ * A geocoder loaded without the outcome vocabulary.
133
+ */
134
+ VocabularyUnavailable: "outcome_vocabulary_unavailable",
135
+ } as const
136
+
137
+ export type OutcomeRefusal = (typeof OutcomeRefusal)[keyof typeof OutcomeRefusal]
138
+
139
+ /**
140
+ * A refused outcome request.
141
+ * An HTTP surface answers it with status 400.
142
+ */
143
+ export class OutcomeRequestError extends Error {
144
+ readonly code: OutcomeRefusal
145
+
146
+ constructor(code: OutcomeRefusal, message: string) {
147
+ super(message)
148
+ this.name = "OutcomeRequestError"
149
+ this.code = code
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Whether a member satisfies a requested id: the member equals the id or begins with it and a dot.
155
+ */
156
+ export function outcomeSatisfies(requested: string, member: string): boolean {
157
+ return member === requested || member.startsWith(`${requested}.`)
158
+ }
159
+
160
+ /**
161
+ * Whether a set of members satisfies one id of `requested`.
162
+ */
163
+ export function outcomesSatisfy(
164
+ requested: readonly string[],
165
+ members: readonly Pick<OutcomeMembership, "outcome">[]
166
+ ): boolean {
167
+ return members.some((m) => requested.some((id) => outcomeSatisfies(id, m.outcome)))
168
+ }
169
+
170
+ /**
171
+ * The `mw:id`s of every vocabulary member that satisfies one of `requested`.
172
+ */
173
+ export function admittedOutcomeIDs(
174
+ requested: readonly string[],
175
+ vocabulary: readonly OutcomeVocabularyLike[]
176
+ ): number[] {
177
+ return vocabulary.filter((member) => requested.some((id) => outcomeSatisfies(id, member.name))).map((m) => m.id)
178
+ }
179
+
180
+ /**
181
+ * Whether the request sets either outcome field.
182
+ */
183
+ export function hasOutcomeOptions(options: OutcomeOptions | null | undefined): boolean {
184
+ return !!options && (typeof options.outcomeHint === "string" || Array.isArray(options.outcomeFilter))
185
+ }
186
+
187
+ /**
188
+ * Refuses an id outside the vocabulary and a hint that zero filter ids admit.
189
+ *
190
+ * @throws {OutcomeRequestError} With the refused id in the message.
191
+ */
192
+ export function checkOutcomeOptions(options: OutcomeOptions, vocabulary: readonly OutcomeVocabularyLike[]): void {
193
+ const known = new Set(vocabulary.map((m) => m.name))
194
+ const ids = [...(options.outcomeFilter ?? []), ...(options.outcomeHint != null ? [options.outcomeHint] : [])]
195
+
196
+ for (const id of ids) {
197
+ if (!known.has(id)) {
198
+ throw new OutcomeRequestError(
199
+ OutcomeRefusal.UnknownOutcome,
200
+ `"${id}" isn't an outcome kind. The vocabulary holds ${[...known].toSorted().join(", ")}.`
201
+ )
202
+ }
203
+ }
204
+
205
+ if (options.outcomeHint != null && options.outcomeFilter) {
206
+ const hint = options.outcomeHint
207
+ const admitted = options.outcomeFilter.some((id) => outcomeSatisfies(id, hint))
208
+
209
+ if (!admitted) {
210
+ throw new OutcomeRequestError(
211
+ OutcomeRefusal.HintOutsideFilter,
212
+ `The hint "${hint}" is outside the filter [${options.outcomeFilter.join(", ")}], so it can't be satisfied.`
213
+ )
214
+ }
215
+ }
216
+ }
217
+
218
+ /**
219
+ * Refuses a database that lacks an outcome table.
220
+ *
221
+ * @throws {OutcomeRequestError} Naming the database and every missing table.
222
+ */
223
+ export function refuseMissingOutcomeTables(database: string, missing: readonly string[]): void {
224
+ if (!missing.length) return
225
+
226
+ throw new OutcomeRequestError(
227
+ OutcomeRefusal.MissingOutcomeTables,
228
+ `${database} predates outcome kinds: it lacks ${missing.join(" and ")}, so it can't answer outcomeHint or outcomeFilter.`
229
+ )
230
+ }
231
+
232
+ /**
233
+ * Merges two outcome sets, keeping each member once with the union of its sources.
234
+ * A member is contested when either side marks it so.
235
+ */
236
+ export function unionOutcomes(a: readonly OutcomeMembership[], b: readonly OutcomeMembership[]): OutcomeMembership[] {
237
+ const merged = new Map<string, OutcomeMembership>()
238
+
239
+ for (const member of [...a, ...b]) {
240
+ const held = merged.get(member.outcome)
241
+
242
+ merged.set(
243
+ member.outcome,
244
+ held
245
+ ? {
246
+ outcome: member.outcome,
247
+ contested: held.contested || member.contested,
248
+ sources: [...new Set([...held.sources, ...member.sources])],
249
+ }
250
+ : { ...member, sources: [...member.sources] }
251
+ )
252
+ }
253
+
254
+ return [...merged.values()].toSorted((x, y) => x.outcome.localeCompare(y.outcome))
255
+ }
@@ -37,9 +37,43 @@ export function isMailwomanWOFID(id: number): boolean {
37
37
  return Number.isInteger(id) && id >= MAILWOMAN_WOF_ID_BASE && id < MAILWOMAN_WOF_ID_END
38
38
  }
39
39
 
40
+ /**
41
+ * What an id of the `mailwoman` WOF range identifies when no fork record holds it.
42
+ */
43
+ export interface ReservedWOFID {
44
+ /**
45
+ * The `mailwoman` fork whose definition file states the id.
46
+ */
47
+ repository: "whosonfirst-properties" | "whosonfirst-sources"
48
+ /**
49
+ * The definition the id identifies: a property such as `ovtr:id`, or a source's prefix.
50
+ */
51
+ definition: string
52
+ }
53
+
54
+ /**
55
+ * Each id of the `mailwoman` WOF range that identifies a property or source
56
+ * definition, with what it identifies.
57
+ *
58
+ * A fork holds no record under one of these ids, so {@link nextMailwomanWOFID}
59
+ * can't learn it from the forks and passes over it here.
60
+ * Each id was drawn at random from the range, above the largest record id the forks held at the time.
61
+ *
62
+ * To reserve another, draw one the same way and add its entry in the change that adds the definition file.
63
+ */
64
+ export const MAILWOMAN_RESERVED_WOF_IDS: ReadonlyMap<number, ReservedWOFID> = new Map([
65
+ [9_895_173_981, { repository: "whosonfirst-properties", definition: "gn:admin2_code" }],
66
+ [9_895_257_979, { repository: "whosonfirst-properties", definition: "mailwoman:sources" }],
67
+ [9_895_370_366, { repository: "whosonfirst-properties", definition: "uscensus:cbsafp" }],
68
+ [9_895_383_830, { repository: "whosonfirst-properties", definition: "ovtr:id" }],
69
+ [9_895_877_104, { repository: "whosonfirst-sources", definition: "ovtr" }],
70
+ ])
71
+
40
72
  /**
41
73
  * The next free id in the `mailwoman` WOF range: one past the largest id already
42
74
  * minted there, or the range's first id when none is.
75
+ *
76
+ * An id of {@link MAILWOMAN_RESERVED_WOF_IDS} is passed over.
43
77
  * Ids outside the range are ignored.
44
78
  *
45
79
  * @throws When the range is exhausted.
@@ -53,7 +87,11 @@ export function nextMailwomanWOFID(minted: Iterable<number>): number {
53
87
  }
54
88
  }
55
89
 
56
- const next = largest + 1
90
+ let next = largest + 1
91
+
92
+ while (MAILWOMAN_RESERVED_WOF_IDS.has(next)) {
93
+ next++
94
+ }
57
95
 
58
96
  if (next >= MAILWOMAN_WOF_ID_END) throw new Error(`the mailwoman WOF id range ends at ${MAILWOMAN_WOF_ID_END - 1}`)
59
97
 
@@ -11,6 +11,7 @@ import type {
11
11
  PostcodePrefixIndexLike,
12
12
  StreetCentroidLookup,
13
13
  } from "#resolver/lookup-types"
14
+ import type { OutcomeLayer, OutcomeMembership, OutcomeQuery, ResolveOutcome } from "#resolver/outcome"
14
15
 
15
16
  /**
16
17
  * Why a place's ranking score is a rank without a measurement behind it.
@@ -134,6 +135,11 @@ export interface ResolvedPlace {
134
135
  * True when the input matched an alias of this place and differs from its primary name.
135
136
  */
136
137
  matchedAlias?: true | null
138
+ /**
139
+ * The matched alias's `name_role` from the candidate table
140
+ * (`"abbr"`, `"variant"`, `"foreign-script"`, `"gloss"`), or `null` when primary or unstamped.
141
+ */
142
+ nameRole?: string | null
137
143
  /**
138
144
  * True when a hard scope excluded this place: it lies outside the default country
139
145
  * or the caller's parent place.
@@ -146,6 +152,29 @@ export interface ResolvedPlace {
146
152
  * A point-only row stores its coordinate as both corners.
147
153
  */
148
154
  bbox?: { minLat: number; maxLat: number; minLon: number; maxLon: number } | null
155
+ /**
156
+ * The place's outcome set, read only when the request set an outcome field.
157
+ */
158
+ outcomes?: readonly OutcomeMembership[] | null
159
+ /**
160
+ * The place's Wikidata item, such as `Q160409`, when its data layer records one.
161
+ */
162
+ wikidata?: string | null
163
+ /**
164
+ * The data layer the place came from, set on an outcome-ordered candidate list.
165
+ */
166
+ layer?: OutcomeLayer | null
167
+ /**
168
+ * The comparable prominence `log10(sitelinks + 1)` of the place's Wikidata item, when known.
169
+ */
170
+ sitelinkProminence?: number | null
171
+ /**
172
+ * Whether the stated country and locality admit a landmark or OpenStreetMap candidate.
173
+ *
174
+ * Absent on a candidate-table row.
175
+ * The candidate table's query applied the row's scope.
176
+ */
177
+ contextAdmits?: boolean | null
149
178
  }
150
179
 
151
180
  /**
@@ -203,8 +232,17 @@ export interface ResolverBackend {
203
232
  * Parsed region qualifier, if any.
204
233
  */
205
234
  regionQualifier?: string
235
+ /**
236
+ * Reads each place's outcome set, and with `admit` keeps only the rows that hold an admitted id.
237
+ */
238
+ outcome?: OutcomeQuery
206
239
  limit?: number
207
240
  }): Promise<ResolvedPlace[]>
241
+ /**
242
+ * The outcome tables the backend's database lacks, empty when it holds them all.
243
+ * A backend without the method reads no outcome sets.
244
+ */
245
+ missingOutcomeTables?(): readonly string[]
208
246
  /**
209
247
  * Optional ancestor lineage lookup.
210
248
  */
@@ -264,6 +302,10 @@ export interface LandmarkHit {
264
302
  * The importance Photon's index holds for an OpenStreetMap place, in place of a sitelink count.
265
303
  */
266
304
  importance?: number | null
305
+ /**
306
+ * The place's outcome set, read only when the lookup was given an outcome query.
307
+ */
308
+ outcomes?: readonly OutcomeMembership[] | null
267
309
  }
268
310
 
269
311
  /**
@@ -298,7 +340,16 @@ export function landmarkPlaceID(id: string | number): string {
298
340
  * Finds the places a name belongs to, primary names first, then most sitelinks first.
299
341
  */
300
342
  export interface LandmarkLookup {
301
- find(name: string): LandmarkHit[] | Promise<LandmarkHit[]>
343
+ /**
344
+ * With `outcome`, each hit holds its outcome set, and `admit` keeps only the
345
+ * rows that hold an admitted id, inside the query.
346
+ */
347
+ find(name: string, outcome?: OutcomeQuery): LandmarkHit[] | Promise<LandmarkHit[]>
348
+ /**
349
+ * The outcome tables the layer's database lacks, empty when it holds them all.
350
+ * A lookup without the method reads no outcome sets.
351
+ */
352
+ missingOutcomeTables?(): readonly string[]
302
353
  }
303
354
 
304
355
  /**
@@ -455,7 +506,7 @@ export const RESOLVE_SWITCH_DEFAULTS: Readonly<ResolveSwitches> = {
455
506
  countyDesignatorFallback: false,
456
507
  formerDivisions: false,
457
508
  scopeCountryRetrieval: false,
458
- siblingLocalityContainment: false,
509
+ siblingLocalityContainment: true,
459
510
  diagnoseUnreachable: false,
460
511
  }
461
512
 
@@ -735,6 +786,12 @@ export interface ResolveOpts {
735
786
  * @defaultValue {@linkcode RESOLVE_SWITCH_DEFAULTS}
736
787
  */
737
788
  siblingLocalityContainment?: boolean
789
+ /**
790
+ * The request's outcome hint, filter and head order.
791
+ *
792
+ * Absent, every lookup runs today's sequence.
793
+ */
794
+ outcome?: ResolveOutcome | null
738
795
  /**
739
796
  * Optional sink for resolver-internal trace records.
740
797
  */
@@ -80,7 +80,7 @@ export function requiredArgument(scope: string, name: string, value: string | nu
80
80
  export function integerArgument(name: string, value: string): number {
81
81
  const parsed = Number(value)
82
82
 
83
- if (!Number.isSafeInteger(parsed)) throw new Error(`--${name} must be an integer, got ${value}`)
83
+ if (!Number.isSafeInteger(parsed)) throw new TypeError(`--${name} must be an integer, got ${value}`)
84
84
 
85
85
  return parsed
86
86
  }