@mailwoman/nominatim 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.
Files changed (46) hide show
  1. package/README.md +34 -0
  2. package/{app.ts → lib/app.ts} +17 -9
  3. package/{cli.ts → lib/cli.ts} +39 -74
  4. package/{dev-tools → lib/dev-tools}/capture-search-golden.run.ts +6 -7
  5. package/lib/engine.ts +200 -0
  6. package/{format.ts → lib/format.ts} +8 -5
  7. package/lib/forward-address.ts +67 -0
  8. package/{index.ts → lib/index.ts} +5 -5
  9. package/{routes.ts → lib/routes.ts} +22 -15
  10. package/{schema.ts → lib/schema.ts} +43 -4
  11. package/out/app.d.ts +8 -1
  12. package/out/app.d.ts.map +1 -1
  13. package/out/app.js +7 -7
  14. package/out/app.js.map +1 -1
  15. package/out/cli.d.ts.map +1 -1
  16. package/out/cli.js +35 -65
  17. package/out/cli.js.map +1 -1
  18. package/out/dev-tools/capture-search-golden.run.d.ts.map +1 -1
  19. package/out/dev-tools/capture-search-golden.run.js +6 -6
  20. package/out/dev-tools/capture-search-golden.run.js.map +1 -1
  21. package/out/engine.d.ts +72 -0
  22. package/out/engine.d.ts.map +1 -1
  23. package/out/engine.js +19 -1
  24. package/out/engine.js.map +1 -1
  25. package/out/format.d.ts +4 -4
  26. package/out/format.d.ts.map +1 -1
  27. package/out/format.js +5 -2
  28. package/out/format.js.map +1 -1
  29. package/out/forward-address.d.ts +20 -0
  30. package/out/forward-address.d.ts.map +1 -0
  31. package/out/forward-address.js +55 -0
  32. package/out/forward-address.js.map +1 -0
  33. package/out/index.d.ts +5 -5
  34. package/out/index.d.ts.map +1 -1
  35. package/out/index.js +5 -5
  36. package/out/index.js.map +1 -1
  37. package/out/routes.d.ts +3 -2
  38. package/out/routes.d.ts.map +1 -1
  39. package/out/routes.js +13 -13
  40. package/out/routes.js.map +1 -1
  41. package/out/schema.d.ts +136 -9
  42. package/out/schema.d.ts.map +1 -1
  43. package/out/schema.js +37 -4
  44. package/out/schema.js.map +1 -1
  45. package/package.json +45 -20
  46. package/engine.ts +0 -116
package/README.md CHANGED
@@ -55,6 +55,40 @@ Maidenhead, Mercator), qibla bearing, sun times, country flag, calling code, and
55
55
  timezone, UN/LOCODE, and EU NUTS codes when their data bundles are present. Plain Nominatim returns none
56
56
  of these.
57
57
 
58
+ ## Data freshness
59
+
60
+ You cannot tell how stale a geocoder's data is from its answers, so `/status` reports it. `data_updated` is the
61
+ Nominatim-compatible field — the newest build date across the databases this process opened — and the native
62
+ `mailwoman` block names each one:
63
+
64
+ ```jsonc
65
+ {
66
+ "status": 0,
67
+ "message": "OK",
68
+ "data_updated": "2026-08-25T17:21:58.254Z",
69
+ "mailwoman": {
70
+ "artifacts": [
71
+ {
72
+ "name": "gazetteer",
73
+ "path": "…/wof/candidate.db",
74
+ "manifest": "present",
75
+ "version": "candidate@2026-08-25",
76
+ "built": "2026-08-25T17:21:58.254Z",
77
+ "sources": [
78
+ "admin-global-priority@2026-08-25",
79
+ "admin=… postcode-extracts=23 locality-extracts=2 importance=yes",
80
+ ],
81
+ },
82
+ ],
83
+ },
84
+ }
85
+ ```
86
+
87
+ Every date comes out of the artifact itself — the `layer_manifest` row its builder wrote before sealing it — never
88
+ from a file's timestamp or a record kept alongside. An artifact built before that contract carries no manifest, and
89
+ says so (`"manifest": "absent"`) rather than being left out; when none of them carries one, `data_updated` is omitted
90
+ instead of guessed. A Nominatim client ignores the `mailwoman` key.
91
+
58
92
  ## Status
59
93
 
60
94
  Shipped. `/search` and `/reverse` resolve over the live engine and return the enriched block; `/lookup`
@@ -8,13 +8,12 @@
8
8
  */
9
9
 
10
10
  import { OpenAPIHono } from "@hono/zod-openapi"
11
- import { attachOpenAPIDocs, type OpenAPIDocInfo } from "@mailwoman/api-kit"
11
+ import { attachOpenAPIDocs, engineHeaders, type OpenAPIDocInfo, readServedDocumentInfo } from "@mailwoman/api-kit"
12
+ import type { EngineStamp } from "@mailwoman/core/license"
12
13
  import { cors } from "hono/cors"
13
14
 
14
- import packageJson from "#package.json" with { type: "json" }
15
-
16
- import type { NominatimEngine } from "./engine.ts"
17
- import { registerNominatimRoutes } from "./routes.ts"
15
+ import type { NominatimEngine } from "#engine"
16
+ import { registerNominatimRoutes } from "#routes"
18
17
 
19
18
  /**
20
19
  * Options for {@link createNominatimApp}.
@@ -26,6 +25,13 @@ export interface NominatimAppOptions {
26
25
  * (#1017). Set `false` when a reverse proxy already owns the CORS headers.
27
26
  */
28
27
  cors?: boolean
28
+
29
+ /**
30
+ * The engine stamp to carry on every response: `engine` on each jsonv2 result and geojson collection, and the
31
+ * `Server` + `Link: rel="license"` headers everywhere. Absent when an embedding application builds the app without
32
+ * the `mailwoman` package; the `nominatim` bin always passes one.
33
+ */
34
+ engine?: EngineStamp
29
35
  }
30
36
 
31
37
  /**
@@ -34,9 +40,7 @@ export interface NominatimAppOptions {
34
40
  * {@link attachOpenAPIDocs}) uses — one source of truth, no risk of the two drifting.
35
41
  */
36
42
  export const NOMINATIM_DOC_INFO: OpenAPIDocInfo = {
37
- title: packageJson.name,
38
- version: packageJson.version,
39
- description: packageJson.description,
43
+ ...(await readServedDocumentInfo(import.meta.url, "@mailwoman/nominatim")),
40
44
  license: { name: "AGPL-3.0-only OR LicenseRef-Commercial", identifier: "AGPL-3.0-only" },
41
45
  contact: { name: "Sister Software", url: "https://mailwoman.ai" },
42
46
  externalDocs: {
@@ -68,11 +72,15 @@ export function createNominatimApp(engine: NominatimEngine, options: NominatimAp
68
72
  app.use(cors({ origin: "*", allowMethods: ["GET", "OPTIONS"], allowHeaders: ["*"], maxAge: 86_400 }))
69
73
  }
70
74
 
75
+ if (options.engine) {
76
+ app.use(engineHeaders(options.engine))
77
+ }
78
+
71
79
  // Safety net: a malformed query or an engine fault must never crash the process into a stack-trace 500 — the
72
80
  // clean legacy JSON error instead (`{error}` — NOT photon's FeatureCollection+message envelope).
73
81
  app.onError((_error, c) => c.json({ error: "internal error" }, 500))
74
82
 
75
- registerNominatimRoutes(app, engine)
83
+ registerNominatimRoutes(app, engine, options.engine)
76
84
  attachOpenAPIDocs(app, NOMINATIM_DOC_INFO)
77
85
 
78
86
  return app
@@ -14,36 +14,41 @@
14
14
  * timezone, UN/LOCODE, NUTS — composed from the `@mailwoman/*` annotators.
15
15
  */
16
16
 
17
- import { existsSync } from "node:fs"
18
- import { parseArgs } from "node:util"
19
-
20
17
  import { composeAnnotators, toOpenCage } from "@mailwoman/annotations"
21
- import { printOpenAPIDocument, serveNode } from "@mailwoman/api-kit"
18
+ import { serveNode } from "@mailwoman/api-kit"
22
19
  import { countryReferenceAnnotator, matchCountry } from "@mailwoman/codex/country"
20
+ import { pathExists } from "@mailwoman/core/fs/readers"
21
+ import { parseArguments } from "@mailwoman/core/scripting/arguments"
22
+ import { dataRootPath, mailwomanDataRoot } from "@mailwoman/core/utils"
23
23
  import { makeNUTSAnnotator, NUTSLookup } from "@mailwoman/nuts-lookup"
24
24
  import { createWOFResolver } from "@mailwoman/resolver"
25
25
  import { coordinateFormatAnnotator } from "@mailwoman/spatial"
26
26
  import { makeTimezoneAnnotator, TimezoneLookup } from "@mailwoman/timezone-lookup"
27
- import { makeUnLocodeAnnotator, UnLocodeLookup } from "@mailwoman/un-locode-lookup"
27
+ import { makeUNLocodeAnnotator, UNLocodeLookup } from "@mailwoman/un-locode-lookup"
28
28
  import {
29
29
  corsBannerLine,
30
30
  gazetteerBannerLines,
31
+ gazetteerFreshness,
31
32
  loadClassifierOrExit,
32
- parseOpenAPIFlags,
33
+ openAPICommand,
33
34
  resolveGazetteerOrExit,
34
35
  runDropInCLI,
35
36
  } from "mailwoman/cli-kit/dropin"
36
- import { geocodeAddress, type GeocodeResult, ShardProvider } from "mailwoman/geocode-core"
37
- import { createResolverBackend, dataRootPath, mailwomanDataRoot } from "mailwoman/resolver-backend"
37
+ import type { ResolvedEngineStamp } from "mailwoman/cli-kit/engine-stamp"
38
+ import { geocodeAddress, RegionDatabaseProvider } from "mailwoman/geocode"
39
+ import { createResolverBackend } from "mailwoman/resolver-backend"
40
+ import { resolvePath } from "path-ts"
38
41
 
42
+ import { forwardToResolved } from "#forward-address"
39
43
  import {
40
44
  createNominatimApp,
41
45
  type NominatimAddressDetails,
42
46
  type NominatimEngine,
47
+ nominatimStatus,
43
48
  NOMINATIM_DOC_INFO,
44
49
  type ResolvedAddress,
45
50
  toNominatimResult,
46
- } from "./index.ts"
51
+ } from "#index"
47
52
 
48
53
  /**
49
54
  * WOF placetype → Nominatim address key.
@@ -73,40 +78,8 @@ function joinNonEmpty(...parts: Array<string | undefined>): string {
73
78
  return parts.filter((part) => part !== undefined && part.length > 0).join(", ")
74
79
  }
75
80
 
76
- /**
77
- * Map a forward geocode result (admin + coordinate) into the formatter's neutral shape.
78
- */
79
- function forwardToResolved(r: GeocodeResult): ResolvedAddress {
80
- const address: NominatimAddressDetails = {}
81
-
82
- if (r.locality) {
83
- address.city = r.locality
84
- }
85
-
86
- if (r.region) {
87
- address.state = r.region
88
- }
89
-
90
- if (r.postcode) {
91
- address.postcode = r.postcode
92
- }
93
-
94
- for (const h of r.hierarchy) {
95
- if (h.tag === "country") {
96
- address.country = h.value
97
- }
98
- }
99
-
100
- return {
101
- lat: r.lat,
102
- lon: r.lon,
103
- address,
104
- displayName: joinNonEmpty(address.city, address.state, address.postcode, address.country) || r.input,
105
- }
106
- }
107
-
108
- async function serve(): Promise<void> {
109
- const { values } = parseArgs({
81
+ async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
82
+ const { values } = parseArguments({
110
83
  options: {
111
84
  port: { type: "string", default: "8080" },
112
85
  host: { type: "string", default: "0.0.0.0" },
@@ -123,17 +96,17 @@ async function serve(): Promise<void> {
123
96
  const host = values.host ?? "0.0.0.0"
124
97
 
125
98
  const resolverMod = await import("@mailwoman/resolver-wof-sqlite")
126
- const gazetteer = resolveGazetteerOrExit(values["candidate-db"])
99
+ const gazetteer = await resolveGazetteerOrExit(values["candidate-db"])
127
100
  const { adminDBPath, candidateDB, wofPaths } = gazetteer
128
101
  const classifier = await loadClassifierOrExit()
129
102
 
130
- const backend = createResolverBackend(resolverMod, { wofPaths, candidateDB })
103
+ const backend = await createResolverBackend(resolverMod, { wofPaths, candidateDB })
131
104
  const resolver = createWOFResolver(backend)
132
- const shards = new ShardProvider(resolverMod, mailwomanDataRoot())
105
+ const extracts = await RegionDatabaseProvider.create(resolverMod, mailwomanDataRoot())
133
106
  // National open-register rooftop tier (#1012): BAN-FR ahead of the OSM tier for a non-US parse. A no-op
134
- // when the shard isn't on disk (existsSync-gated inside the provider), so the endpoint degrades cleanly.
135
- const { BANShardProvider } = await import("@mailwoman/ban/sdk")
136
- const banShards = new BANShardProvider(mailwomanDataRoot())
107
+ // when the extract isn't on disk (conditioned on existsSync inside the provider), so the endpoint degrades cleanly.
108
+ const { BANRegionDatabaseProvider } = await import("@mailwoman/ban/sdk")
109
+ const banExtracts = await BANRegionDatabaseProvider.create(mailwomanDataRoot())
137
110
  // NOT a geocode country constraint. The default-on #244 placer already routes the query's country
138
111
  // (Berlin→DE, Boston→US) and `defaultCountry` is a HARD override that beats it (geocode-core.ts:102),
139
112
  // so forcing "US" resolved every non-US query to its US namesake (Berlin→Berlin NH). We let the
@@ -146,24 +119,29 @@ async function serve(): Promise<void> {
146
119
  const annotators = [coordinateFormatAnnotator, countryReferenceAnnotator]
147
120
  const tzDBPath = dataRootPath("timezone", "timezone.db")
148
121
 
149
- if (existsSync(tzDBPath)) {
150
- annotators.push(makeTimezoneAnnotator(new TimezoneLookup({ databasePath: tzDBPath })))
122
+ if (await pathExists(tzDBPath)) {
123
+ annotators.push(makeTimezoneAnnotator(new TimezoneLookup({ databasePath: resolvePath(tzDBPath) })))
151
124
  }
152
125
 
153
126
  const ulDBPath = dataRootPath("un-locode", "un-locode.db")
154
127
 
155
- if (existsSync(ulDBPath)) {
156
- annotators.push(makeUnLocodeAnnotator(new UnLocodeLookup({ databasePath: ulDBPath })))
128
+ if (await pathExists(ulDBPath)) {
129
+ annotators.push(makeUNLocodeAnnotator(new UNLocodeLookup({ databasePath: resolvePath(ulDBPath) })))
157
130
  }
158
131
 
159
132
  const nutsDBPath = dataRootPath("nuts", "nuts.db")
160
133
 
161
- if (existsSync(nutsDBPath)) {
162
- annotators.push(makeNUTSAnnotator(new NUTSLookup({ databasePath: nutsDBPath })))
134
+ if (await pathExists(nutsDBPath)) {
135
+ annotators.push(makeNUTSAnnotator(new NUTSLookup({ databasePath: resolvePath(nutsDBPath) })))
163
136
  }
164
137
 
165
138
  const annotate = composeAnnotators(annotators)
166
139
 
140
+ // Read once, at boot, from the artifacts THEMSELVES (#997). The handles above are held for the life of
141
+ // the process, so this describes what the endpoint is serving from for as long as it serves — and every
142
+ // artifact appears, including one carrying no manifest, which says so rather than being left out.
143
+ const status = nominatimStatus(await gazetteerFreshness(gazetteer))
144
+
167
145
  const engine: NominatimEngine = {
168
146
  async search(params) {
169
147
  const query = (
@@ -181,8 +159,8 @@ async function serve(): Promise<void> {
181
159
  const result = await geocodeAddress(query, {
182
160
  classifier,
183
161
  resolver,
184
- shards: shards.for,
185
- nationalShards: banShards.for,
162
+ databases: extracts.for,
163
+ nationalDatabases: banExtracts.for,
186
164
  defaultCountry: userCountry,
187
165
  })
188
166
 
@@ -297,13 +275,13 @@ async function serve(): Promise<void> {
297
275
  },
298
276
 
299
277
  async status() {
300
- return { status: 0, message: "OK" }
278
+ return status
301
279
  },
302
280
  }
303
281
 
304
- const app = createNominatimApp(engine, { cors: values.cors })
282
+ const app = createNominatimApp(engine, { cors: values.cors, engine: engineStamp.stamp })
305
283
 
306
- serveNode({
284
+ await serveNode({
307
285
  fetch: app.fetch,
308
286
  port,
309
287
  hostname: host,
@@ -320,22 +298,9 @@ async function serve(): Promise<void> {
320
298
  })
321
299
  }
322
300
 
323
- /**
324
- * `openapi` — print (or `--out`-write) the emitted OpenAPI document for this surface. Builds the app around an
325
- * all-optional stub {@link NominatimEngine} (`{}` — every route answers 501 under this stub, but the document itself
326
- * only reflects the ROUTE TABLE, not handler behavior) so this NEVER boots the neural classifier or opens a gazetteer
327
- * DB: pure route-table introspection, fast regardless of data-root state. `--flavor 3.0` prints the 3.0.3 diet instead
328
- * of the default 3.1.0.
329
- */
330
- function openapi(): void {
331
- const app = createNominatimApp({})
332
-
333
- printOpenAPIDocument(app, NOMINATIM_DOC_INFO, parseOpenAPIFlags(BINARY_NAME))
334
- }
335
-
336
301
  await runDropInCLI({
337
302
  binaryName: BINARY_NAME,
338
- openapi,
303
+ openapi: openAPICommand(BINARY_NAME, createNominatimApp, NOMINATIM_DOC_INFO, {}),
339
304
  serve,
340
305
  usage: [
341
306
  " serve [--port 8080] [--host 0.0.0.0] [--candidate-db <path>] [--no-cors]",
@@ -10,15 +10,14 @@
10
10
  * `node nominatim/dev-tools/capture-search-golden.run.ts`
11
11
  */
12
12
 
13
- import { spawn } from "node:child_process"
14
- import { writeFileSync } from "node:fs"
15
-
13
+ import { writeLocalTextFile } from "@mailwoman/core/fs/writers"
14
+ import { spawnProcess } from "@mailwoman/core/process"
16
15
  import { JSONSpliterator, TextSpliterator } from "spliterator"
17
16
 
18
17
  const PORT = 8199
19
18
  const BASE = `http://127.0.0.1:${PORT}`
20
- const PARITY_PATH = "packages/mailwoman/test-fixtures/legacy-golden/parity-inputs.jsonl"
21
- const SYNTHETIC_PATH = "packages/mailwoman/test-fixtures/legacy-golden/synthetic-inputs.txt"
19
+ const PARITY_PATH = "packages/mailwoman/lib/test-fixtures/legacy-golden/parity-inputs.jsonl"
20
+ const SYNTHETIC_PATH = "packages/mailwoman/lib/test-fixtures/legacy-golden/synthetic-inputs.txt"
22
21
  const OUT_PATH = "packages/nominatim/test-fixtures/search-golden.jsonl"
23
22
 
24
23
  interface ParityRow {
@@ -41,7 +40,7 @@ const syntheticInputs = (await Array.fromAsync(TextSpliterator.fromAsync(SYNTHET
41
40
 
42
41
  const queries = [...new Set([...withHouseNumber.slice(0, 172), ...syntheticInputs])]
43
42
 
44
- const child = spawn("node", ["packages/nominatim/out/cli.js", "serve", "--port", String(PORT)], {
43
+ const child = spawnProcess("node", ["packages/nominatim/out/cli.js", "serve", "--port", String(PORT)], {
45
44
  stdio: ["ignore", "inherit", "inherit"],
46
45
  })
47
46
 
@@ -73,7 +72,7 @@ try {
73
72
  rows.push(JSON.stringify({ query, status: res.status, body: await res.json() }))
74
73
  }
75
74
 
76
- writeFileSync(OUT_PATH, rows.join("\n") + "\n")
75
+ await writeLocalTextFile(rows.join("\n") + "\n", OUT_PATH)
77
76
 
78
77
  console.error(
79
78
  `captured ${rows.length} /search responses (${withHouseNumber.length} house-number parity cases available)`
package/lib/engine.ts ADDED
@@ -0,0 +1,200 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The Nominatim engine contract + wire types the router delegates to. The RESOLVED-address →
7
+ * {@link NominatimResult} formatter (`toNominatimResult`, `toFeatureCollection`,
8
+ * `nominatimResultToSchemaOrg`) lives in `format.ts`.
9
+ */
10
+
11
+ import type { OpenCageAnnotations } from "@mailwoman/annotations"
12
+
13
+ /**
14
+ * Output serialization formats Nominatim supports. `jsonv2` is the modern default. `jsonld` is the Mailwoman extension
15
+ * (#1052) — schema.org `Place` JSON-LD, not part of upstream Nominatim.
16
+ */
17
+ export type NominatimFormat = "jsonv2" | "json" | "geojson" | "jsonld"
18
+
19
+ /**
20
+ * The structured address breakdown returned under `address` when `addressdetails=1`. Keys mirror Nominatim's
21
+ * OSM-derived tag names; populated from Mailwoman's `ComponentTag` / resolved ancestor lineage (mapping owned by
22
+ * #804).
23
+ */
24
+ export type NominatimAddressDetails = Record<string, string>
25
+
26
+ /**
27
+ * A single Nominatim result object (the shape geopy and friends parse).
28
+ */
29
+ export interface NominatimResult {
30
+ place_id: number | string
31
+ licence: string
32
+ osm_type?: string
33
+ osm_id?: number | string
34
+ lat: string
35
+ lon: string
36
+ display_name: string
37
+ /**
38
+ * `[south, north, west, east]` as strings, per Nominatim.
39
+ */
40
+ boundingbox?: [string, string, string, string]
41
+ class?: string
42
+ type?: string
43
+ importance?: number
44
+ place_rank?: number
45
+ address?: NominatimAddressDetails
46
+ /**
47
+ * Present when `format=geojson` or `polygon_geojson=1`.
48
+ */
49
+ geojson?: unknown
50
+ /**
51
+ * OpenCage-style enrichment block (timezone, coordinate formats, …); attached by the engine.
52
+ */
53
+ annotations?: OpenCageAnnotations
54
+ }
55
+
56
+ /**
57
+ * Parsed `/search` parameters (free-text OR structured; never both).
58
+ */
59
+ export interface NominatimSearchParams {
60
+ q?: string
61
+ street?: string
62
+ city?: string
63
+ county?: string
64
+ state?: string
65
+ country?: string
66
+ postalcode?: string
67
+ countrycodes?: string[]
68
+ limit: number
69
+ viewbox?: [number, number, number, number]
70
+ bounded?: boolean
71
+ addressdetails?: boolean
72
+ format: NominatimFormat
73
+ acceptLanguage?: string
74
+ }
75
+
76
+ /**
77
+ * Parsed `/reverse` parameters.
78
+ */
79
+ export interface NominatimReverseParams {
80
+ lat: number
81
+ lon: number
82
+ zoom?: number
83
+ addressdetails?: boolean
84
+ format: NominatimFormat
85
+ acceptLanguage?: string
86
+ }
87
+
88
+ /**
89
+ * Parsed `/lookup` parameters.
90
+ */
91
+ export interface NominatimLookupParams {
92
+ osmIDs: string[]
93
+ addressdetails?: boolean
94
+ format: NominatimFormat
95
+ }
96
+
97
+ /**
98
+ * Whether an artifact could state its own provenance. `unreadable` is kept apart from `absent` because "we could not
99
+ * open it" is a fault to chase, not a rebuild to schedule.
100
+ */
101
+ export type NominatimManifestState = "present" | "absent" | "unreadable"
102
+
103
+ /**
104
+ * One database this deployment is serving from, and what it says about itself.
105
+ *
106
+ * Modeled here rather than imported from `mailwoman/freshness`, matching this package's convention that a wire surface
107
+ * owns its own doc-accuracy types. The CLI assigns the reader's report straight into this shape, so a drift between the
108
+ * two is a compile error at that assignment rather than a silently different response body.
109
+ */
110
+ export interface NominatimStatusArtifact {
111
+ /**
112
+ * The role this artifact plays for the running process (`gazetteer`, `reverse-admin`).
113
+ */
114
+ name: string
115
+ path: string
116
+ manifest: NominatimManifestState
117
+ /**
118
+ * Why the manifest is absent or unreadable.
119
+ */
120
+ reason?: string
121
+ /**
122
+ * When the artifact was BUILT, as its own manifest records it.
123
+ */
124
+ built?: string
125
+ /**
126
+ * `<layer name>@<layer version>` — the artifact's identity.
127
+ */
128
+ version?: string
129
+ /**
130
+ * What it was built FROM: the manifest's source, then its source vintage.
131
+ */
132
+ sources?: string[]
133
+ }
134
+
135
+ /**
136
+ * The native provenance block. A Nominatim client ignores unknown keys, so this rides alongside the compatible
137
+ * `data_updated` without breaking one.
138
+ */
139
+ export interface NominatimStatusExtension {
140
+ /**
141
+ * Every artifact this process opened, INCLUDING the ones that carry no manifest — an unstamped artifact reports its
142
+ * own absence rather than being omitted, because an omission cannot be told apart from an artifact nobody opened.
143
+ */
144
+ artifacts: NominatimStatusArtifact[]
145
+ }
146
+
147
+ /**
148
+ * Nominatim `/status` payload.
149
+ */
150
+ export interface NominatimStatus {
151
+ status: number
152
+ message: string
153
+ /**
154
+ * The newest build epoch across the artifacts this deployment opened. Left OUT when none of them carries a manifest —
155
+ * never filled with a boot time or a file mtime, which would answer a question the process cannot answer.
156
+ */
157
+ data_updated?: string
158
+ mailwoman?: NominatimStatusExtension
159
+ }
160
+
161
+ /**
162
+ * A freshness report as this surface consumes it — structurally `mailwoman/freshness`'s `FreshnessReport`, declared
163
+ * here so the wire contract keeps no import from the engine implementation.
164
+ */
165
+ export interface NominatimFreshnessReport {
166
+ dataUpdated?: string
167
+ artifacts: NominatimStatusArtifact[]
168
+ }
169
+
170
+ /**
171
+ * Compose the `/status` payload from a freshness report.
172
+ *
173
+ * A FUNCTION rather than four lines at the one call site, because the CLI and the test that checks this response would
174
+ * otherwise each hold their own copy of the same mapping — and the field this mapping exists to get right is one that
175
+ * is OMITTED under a condition, which is exactly what two copies stop agreeing about first.
176
+ *
177
+ * `data_updated` is dropped when no artifact carried a build date. Nominatim declares the field optional, so leaving it
178
+ * out is the contract's own way of saying the deployment cannot date its data; filling it with a boot time or a file
179
+ * mtime would answer with something that looks measured and is not.
180
+ */
181
+ export function nominatimStatus(freshness: NominatimFreshnessReport): NominatimStatus {
182
+ return {
183
+ status: 0,
184
+ message: "OK",
185
+ ...(freshness.dataUpdated ? { data_updated: freshness.dataUpdated } : {}),
186
+ mailwoman: { artifacts: freshness.artifacts },
187
+ }
188
+ }
189
+
190
+ /**
191
+ * The geocoding engine the router delegates to. Each method is optional; a route whose method is not provided answers
192
+ * `501 Not Implemented`. The real implementation (Mailwoman parse → resolve, plus `WOFReverseGeocoder`) is wired by the
193
+ * CLI and fleshed out across #802–#805.
194
+ */
195
+ export interface NominatimEngine {
196
+ search?(params: NominatimSearchParams): Promise<NominatimResult[]>
197
+ reverse?(params: NominatimReverseParams): Promise<NominatimResult | null>
198
+ lookup?(params: NominatimLookupParams): Promise<NominatimResult[]>
199
+ status?(): Promise<NominatimStatus>
200
+ }
@@ -11,7 +11,7 @@
11
11
 
12
12
  import { composeStreetAddress, type SchemaOrgPlace, toSchemaOrg } from "@mailwoman/annotations"
13
13
 
14
- import type { NominatimAddressDetails, NominatimResult } from "./engine.ts"
14
+ import type { NominatimAddressDetails, NominatimResult } from "#engine"
15
15
 
16
16
  /**
17
17
  * Arity of a 2D bounding box, as Nominatim reports it.
@@ -41,7 +41,10 @@ export function toFeatureCollection(results: readonly NominatimResult[]): Nomina
41
41
  const features: NominatimFeatureCollection["features"] = []
42
42
 
43
43
  for (const r of results) {
44
- if (r.lat == null || r.lon == null) continue
44
+ // `toNominatimResult` writes "" for a missing coordinate, never null, so EMPTINESS is the condition that
45
+ // matters. A `== null` check alone lets a coordinate-less row through as Point [0, 0] — a real place in the
46
+ // Gulf of Guinea rather than an absence.
47
+ if (!r.lat || !r.lon) continue
45
48
  const { lat, lon, boundingbox, geojson, ...properties } = r
46
49
 
47
50
  const feature: NominatimFeatureCollection["features"][number] = {
@@ -63,8 +66,8 @@ export function toFeatureCollection(results: readonly NominatimResult[]): Nomina
63
66
 
64
67
  /**
65
68
  * A resolved address in a neutral shape, the input to {@link toNominatimResult}. The engine maps its native
66
- * geocode/reverse result into this; the formatter renders it as a Nominatim result. This is the #804 mapping seam, kept
67
- * dependency-free (no `@mailwoman/*` import) so it stays unit-testable.
69
+ * geocode/reverse result into this; the formatter renders it as a Nominatim result. This is the #804 mapping boundary,
70
+ * kept dependency-free (no `@mailwoman/*` import) so it stays unit-testable.
68
71
  */
69
72
  export interface ResolvedAddress {
70
73
  lat: number | null
@@ -101,7 +104,7 @@ function stableID(seed: string): number {
101
104
  }
102
105
 
103
106
  /**
104
- * Render a {@link ResolvedAddress} as a Nominatim result. `addressdetails` gates the `address` block, matching
107
+ * Render a {@link ResolvedAddress} as a Nominatim result. `addressdetails` selects the `address` block, matching
105
108
  * Nominatim. The `annotations` block is attached by the caller (empty until the annotations layer lands).
106
109
  */
107
110
  export function toNominatimResult(r: ResolvedAddress, opts: { addressdetails?: boolean } = {}): NominatimResult {
@@ -0,0 +1,67 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ * @file A forward geocode result as Nominatim's address block: the parse's named slots first, then the resolved
6
+ * ancestry labelled by tag the way Nominatim labels each ancestor by its address rank — a Japanese municipality is
7
+ * `city`, a prefecture `state`, a 大字 / 町名 `suburb`. The native `locality` / `region` slots stay what the parse said;
8
+ * only this compatibility surface reads the JP tiers into the Latin keys.
9
+ */
10
+
11
+ import type { GeocodeResult } from "mailwoman/geocode"
12
+
13
+ import type { NominatimAddressDetails, ResolvedAddress } from "#index"
14
+
15
+ /**
16
+ * Resolved tag → Nominatim address key, for a forward result's `hierarchy`.
17
+ */
18
+ export const TAG_TO_KEY: Record<string, keyof NominatimAddressDetails> = {
19
+ locality: "city",
20
+ municipality: "city",
21
+ dependent_locality: "suburb",
22
+ district: "suburb",
23
+ subregion: "county",
24
+ region: "state",
25
+ prefecture: "state",
26
+ country: "country",
27
+ }
28
+
29
+ function joinNonEmpty(...parts: Array<string | undefined>): string {
30
+ return parts.filter((part) => part !== undefined && part.length > 0).join(", ")
31
+ }
32
+
33
+ /**
34
+ * Map a forward geocode result (admin + coordinate) into the formatter's neutral shape.
35
+ */
36
+ export function forwardToResolved(r: GeocodeResult): ResolvedAddress {
37
+ const address: NominatimAddressDetails = {}
38
+
39
+ if (r.locality) {
40
+ address.city = r.locality
41
+ }
42
+
43
+ if (r.region) {
44
+ address.state = r.region
45
+ }
46
+
47
+ if (r.postcode) {
48
+ address.postcode = r.postcode
49
+ }
50
+
51
+ // The resolved ancestry fills what the slots did not: a JP result carries `municipality` and `prefecture` in
52
+ // `hierarchy` and nothing in `locality` / `region`. Most specific first, so the first name per key wins.
53
+ for (const h of r.hierarchy) {
54
+ const key = TAG_TO_KEY[h.tag]
55
+
56
+ if (key && !address[key]) {
57
+ address[key] = h.name || h.value
58
+ }
59
+ }
60
+
61
+ return {
62
+ lat: r.lat,
63
+ lon: r.lon,
64
+ address,
65
+ displayName: joinNonEmpty(address.city, address.state, address.postcode, address.country) || r.input,
66
+ }
67
+ }
@@ -22,8 +22,8 @@
22
22
  * schemas in `schema.ts`.
23
23
  */
24
24
 
25
- export * from "./app.ts"
26
- export * from "./engine.ts"
27
- export * from "./format.ts"
28
- export * from "./routes.ts"
29
- export * from "./schema.ts"
25
+ export * from "#app"
26
+ export * from "#engine"
27
+ export * from "#format"
28
+ export * from "#routes"
29
+ export * from "#schema"