@mailwoman/nominatim 9.1.0 → 9.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +35 -1
  2. package/{app.ts → lib/app.ts} +28 -7
  3. package/{cli.ts → lib/cli.ts} +46 -78
  4. package/{dev-tools → lib/dev-tools}/capture-search-golden.run.ts +8 -9
  5. package/lib/engine.ts +200 -0
  6. package/{format.ts → lib/format.ts} +14 -6
  7. package/lib/forward-address.ts +67 -0
  8. package/{index.ts → lib/index.ts} +5 -5
  9. package/{routes.ts → lib/routes.ts} +26 -20
  10. package/{schema.ts → lib/schema.ts} +37 -5
  11. package/out/app.d.ts +8 -1
  12. package/out/app.d.ts.map +1 -1
  13. package/out/app.js +15 -6
  14. package/out/app.js.map +1 -1
  15. package/out/cli.d.ts.map +1 -1
  16. package/out/cli.js +40 -69
  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 +8 -8
  20. package/out/dev-tools/capture-search-golden.run.js.map +1 -1
  21. package/out/engine.d.ts +74 -16
  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 +9 -3
  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 +16 -16
  40. package/out/routes.js.map +1 -1
  41. package/out/schema.d.ts +73 -9
  42. package/out/schema.d.ts.map +1 -1
  43. package/out/schema.js +36 -5
  44. package/out/schema.js.map +1 -1
  45. package/package.json +52 -20
  46. package/engine.ts +0 -130
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @mailwoman/nominatim
2
2
 
3
- A **Nominatim-compatible HTTP geocoding API** over the [Mailwoman](https://mailwoman.sister.software) engine. Point an existing Nominatim client at it and forward + reverse geocoding work — no PostgreSQL, no `osm2pgsql` import.
3
+ A **Nominatim-compatible HTTP geocoding API** over the [Mailwoman](https://mailwoman.ai) engine. Point an existing Nominatim client at it and forward + reverse geocoding work — no PostgreSQL, no `osm2pgsql` import.
4
4
 
5
5
  ```bash
6
6
  # One-time data fetch (worldwide candidate gazetteer, population-first ranking, ~1.65 GB):
@@ -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,12 +8,22 @@
8
8
  */
9
9
 
10
10
  import { OpenAPIHono } from "@hono/zod-openapi"
11
- import { attachOpenAPIDocs, type OpenAPIDocInfo } from "@mailwoman/api-kit"
12
- import packageJson from "@mailwoman/nominatim/package.json" with { type: "json" }
11
+ import { attachOpenAPIDocs, engineHeaders, type OpenAPIDocInfo } from "@mailwoman/api-kit"
12
+ import { readLocalJSONFile } from "@mailwoman/core/fs/readers"
13
+ import type { EngineStamp } from "@mailwoman/core/license"
14
+ import { resolvePackagePath } from "@mailwoman/core/module/resolvers"
13
15
  import { cors } from "hono/cors"
14
16
 
15
- import type { NominatimEngine } from "./engine.ts"
16
- import { registerNominatimRoutes } from "./routes.ts"
17
+ import type { NominatimEngine } from "#engine"
18
+ import { registerNominatimRoutes } from "#routes"
19
+
20
+ /**
21
+ * This package's own manifest, read at load rather than imported as a module: a JSON import makes `tsc` copy the file
22
+ * into `out/`, where it becomes the package scope for the compiled tree and breaks every `#` import in it.
23
+ */
24
+ const packageJson = await readLocalJSONFile<{ name: string; version: string; description: string }>(
25
+ resolvePackagePath("@mailwoman/nominatim", "package.json")
26
+ )
17
27
 
18
28
  /**
19
29
  * Options for {@link createNominatimApp}.
@@ -25,6 +35,13 @@ export interface NominatimAppOptions {
25
35
  * (#1017). Set `false` when a reverse proxy already owns the CORS headers.
26
36
  */
27
37
  cors?: boolean
38
+
39
+ /**
40
+ * The engine stamp to carry on every response: `engine` on each jsonv2 result and geojson collection, and the
41
+ * `Server` + `Link: rel="license"` headers everywhere. Absent when an embedding application builds the app without
42
+ * the `mailwoman` package; the `nominatim` bin always passes one.
43
+ */
44
+ engine?: EngineStamp
28
45
  }
29
46
 
30
47
  /**
@@ -37,10 +54,10 @@ export const NOMINATIM_DOC_INFO: OpenAPIDocInfo = {
37
54
  version: packageJson.version,
38
55
  description: packageJson.description,
39
56
  license: { name: "AGPL-3.0-only OR LicenseRef-Commercial", identifier: "AGPL-3.0-only" },
40
- contact: { name: "Sister Software", url: "https://mailwoman.sister.software" },
57
+ contact: { name: "Sister Software", url: "https://mailwoman.ai" },
41
58
  externalDocs: {
42
59
  description: "What Mailwoman is",
43
- url: "https://mailwoman.sister.software/docs/developers/get-started/what-mailwoman-is",
60
+ url: "https://mailwoman.ai/docs/developers/get-started/what-mailwoman-is",
44
61
  },
45
62
  servers: [
46
63
  {
@@ -67,11 +84,15 @@ export function createNominatimApp(engine: NominatimEngine, options: NominatimAp
67
84
  app.use(cors({ origin: "*", allowMethods: ["GET", "OPTIONS"], allowHeaders: ["*"], maxAge: 86_400 }))
68
85
  }
69
86
 
87
+ if (options.engine) {
88
+ app.use(engineHeaders(options.engine))
89
+ }
90
+
70
91
  // Safety net: a malformed query or an engine fault must never crash the process into a stack-trace 500 — the
71
92
  // clean legacy JSON error instead (`{error}` — NOT photon's FeatureCollection+message envelope).
72
93
  app.onError((_error, c) => c.json({ error: "internal error" }, 500))
73
94
 
74
- registerNominatimRoutes(app, engine)
95
+ registerNominatimRoutes(app, engine, options.engine)
75
96
  attachOpenAPIDocs(app, NOMINATIM_DOC_INFO)
76
97
 
77
98
  return app
@@ -14,36 +14,40 @@
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"
23
22
  import { makeNUTSAnnotator, NUTSLookup } from "@mailwoman/nuts-lookup"
24
23
  import { createWOFResolver } from "@mailwoman/resolver"
25
24
  import { coordinateFormatAnnotator } from "@mailwoman/spatial"
26
25
  import { makeTimezoneAnnotator, TimezoneLookup } from "@mailwoman/timezone-lookup"
27
- import { makeUnLocodeAnnotator, UnLocodeLookup } from "@mailwoman/un-locode-lookup"
26
+ import { makeUNLocodeAnnotator, UNLocodeLookup } from "@mailwoman/un-locode-lookup"
28
27
  import {
29
28
  corsBannerLine,
30
29
  gazetteerBannerLines,
30
+ gazetteerFreshness,
31
31
  loadClassifierOrExit,
32
- parseOpenAPIFlags,
32
+ openAPICommand,
33
33
  resolveGazetteerOrExit,
34
34
  runDropInCLI,
35
35
  } from "mailwoman/cli-kit/dropin"
36
- import { geocodeAddress, type GeocodeResult, ShardProvider } from "mailwoman/geocode-core"
36
+ import type { ResolvedEngineStamp } from "mailwoman/cli-kit/engine-stamp"
37
+ import { geocodeAddress, RegionDatabaseProvider } from "mailwoman/geocode"
37
38
  import { createResolverBackend, dataRootPath, mailwomanDataRoot } from "mailwoman/resolver-backend"
39
+ import { resolvePath } from "path-ts"
38
40
 
41
+ import { forwardToResolved } from "#forward-address"
39
42
  import {
40
43
  createNominatimApp,
41
44
  type NominatimAddressDetails,
42
45
  type NominatimEngine,
46
+ nominatimStatus,
43
47
  NOMINATIM_DOC_INFO,
44
48
  type ResolvedAddress,
45
49
  toNominatimResult,
46
- } from "./index.ts"
50
+ } from "#index"
47
51
 
48
52
  /**
49
53
  * WOF placetype → Nominatim address key.
@@ -70,43 +74,11 @@ const MAX_QUERY_LEN = 512
70
74
  const BINARY_NAME = "mailwoman-nominatim"
71
75
 
72
76
  function joinNonEmpty(...parts: Array<string | undefined>): string {
73
- return parts.filter(Boolean).join(", ")
77
+ return parts.filter((part) => part !== undefined && part.length > 0).join(", ")
74
78
  }
75
79
 
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({
80
+ async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
81
+ const { values } = parseArguments({
110
82
  options: {
111
83
  port: { type: "string", default: "8080" },
112
84
  host: { type: "string", default: "0.0.0.0" },
@@ -123,17 +95,17 @@ async function serve(): Promise<void> {
123
95
  const host = values.host ?? "0.0.0.0"
124
96
 
125
97
  const resolverMod = await import("@mailwoman/resolver-wof-sqlite")
126
- const gazetteer = resolveGazetteerOrExit(values["candidate-db"])
127
- const { adminDBPath, candidateDb, wofPaths } = gazetteer
98
+ const gazetteer = await resolveGazetteerOrExit(values["candidate-db"])
99
+ const { adminDBPath, candidateDB, wofPaths } = gazetteer
128
100
  const classifier = await loadClassifierOrExit()
129
101
 
130
- const backend = createResolverBackend(resolverMod, { wofPaths, candidateDb })
102
+ const backend = await createResolverBackend(resolverMod, { wofPaths, candidateDB })
131
103
  const resolver = createWOFResolver(backend)
132
- const shards = new ShardProvider(resolverMod, mailwomanDataRoot())
104
+ const extracts = await RegionDatabaseProvider.create(resolverMod, mailwomanDataRoot())
133
105
  // 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())
106
+ // when the extract isn't on disk (conditioned on existsSync inside the provider), so the endpoint degrades cleanly.
107
+ const { BANRegionDatabaseProvider } = await import("@mailwoman/ban/sdk")
108
+ const banExtracts = await BANRegionDatabaseProvider.create(mailwomanDataRoot())
137
109
  // NOT a geocode country constraint. The default-on #244 placer already routes the query's country
138
110
  // (Berlin→DE, Boston→US) and `defaultCountry` is a HARD override that beats it (geocode-core.ts:102),
139
111
  // so forcing "US" resolved every non-US query to its US namesake (Berlin→Berlin NH). We let the
@@ -141,29 +113,34 @@ async function serve(): Promise<void> {
141
113
  // when the resolved hierarchy omits the country tag — which on US-centric data (no candidate DB)
142
114
  // happens for US results, where "US" is the right guess. Non-US results carry the country tag, so
143
115
  // the fallback never mislabels them.
144
- const annotationCountryFallback = candidateDb ? undefined : "US"
116
+ const annotationCountryFallback = candidateDB ? undefined : "US"
145
117
  const reverseGeo = adminDBPath ? new resolverMod.WOFReverseGeocoder({ adminDBPath }) : undefined
146
118
  const annotators = [coordinateFormatAnnotator, countryReferenceAnnotator]
147
119
  const tzDBPath = dataRootPath("timezone", "timezone.db")
148
120
 
149
- if (existsSync(tzDBPath)) {
150
- annotators.push(makeTimezoneAnnotator(new TimezoneLookup({ databasePath: tzDBPath })))
121
+ if (await pathExists(tzDBPath)) {
122
+ annotators.push(makeTimezoneAnnotator(new TimezoneLookup({ databasePath: resolvePath(tzDBPath) })))
151
123
  }
152
124
 
153
125
  const ulDBPath = dataRootPath("un-locode", "un-locode.db")
154
126
 
155
- if (existsSync(ulDBPath)) {
156
- annotators.push(makeUnLocodeAnnotator(new UnLocodeLookup({ databasePath: ulDBPath })))
127
+ if (await pathExists(ulDBPath)) {
128
+ annotators.push(makeUNLocodeAnnotator(new UNLocodeLookup({ databasePath: resolvePath(ulDBPath) })))
157
129
  }
158
130
 
159
131
  const nutsDBPath = dataRootPath("nuts", "nuts.db")
160
132
 
161
- if (existsSync(nutsDBPath)) {
162
- annotators.push(makeNUTSAnnotator(new NUTSLookup({ databasePath: nutsDBPath })))
133
+ if (await pathExists(nutsDBPath)) {
134
+ annotators.push(makeNUTSAnnotator(new NUTSLookup({ databasePath: resolvePath(nutsDBPath) })))
163
135
  }
164
136
 
165
137
  const annotate = composeAnnotators(annotators)
166
138
 
139
+ // Read once, at boot, from the artifacts THEMSELVES (#997). The handles above are held for the life of
140
+ // the process, so this describes what the endpoint is serving from for as long as it serves — and every
141
+ // artifact appears, including one carrying no manifest, which says so rather than being left out.
142
+ const status = nominatimStatus(await gazetteerFreshness(gazetteer))
143
+
167
144
  const engine: NominatimEngine = {
168
145
  async search(params) {
169
146
  const query = (
@@ -181,8 +158,8 @@ async function serve(): Promise<void> {
181
158
  const result = await geocodeAddress(query, {
182
159
  classifier,
183
160
  resolver,
184
- shards: shards.for,
185
- nationalShards: banShards.for,
161
+ databases: extracts.for,
162
+ nationalDatabases: banExtracts.for,
186
163
  defaultCountry: userCountry,
187
164
  })
188
165
 
@@ -193,7 +170,11 @@ async function serve(): Promise<void> {
193
170
  // result `class: place` / `type: house` (upstream Nominatim's own class/type for a house), so a client that
194
171
  // keys on `class`/`type`/`addresstype` treats it as a building, not an untyped admin hit. The admin tier
195
172
  // (a locality centroid) carries no class/type here, as before.
196
- if (result.resolution_tier === "address_point" || result.resolution_tier === "interpolated") {
173
+ if (
174
+ result.resolution_tier === "address_point" ||
175
+ result.resolution_tier === "interpolated" ||
176
+ result.resolution_tier === "plus_code"
177
+ ) {
197
178
  resolved.category = "place"
198
179
  resolved.type = "house"
199
180
  }
@@ -213,7 +194,7 @@ async function serve(): Promise<void> {
213
194
  const country = matchCountry(countryName)
214
195
 
215
196
  if (country) {
216
- if (!resolved.address.country) {
197
+ if (!resolved.address.country && country.canonical) {
217
198
  resolved.address.country = country.canonical
218
199
  }
219
200
 
@@ -293,13 +274,13 @@ async function serve(): Promise<void> {
293
274
  },
294
275
 
295
276
  async status() {
296
- return { status: 0, message: "OK" }
277
+ return status
297
278
  },
298
279
  }
299
280
 
300
- const app = createNominatimApp(engine, { cors: values.cors })
281
+ const app = createNominatimApp(engine, { cors: values.cors, engine: engineStamp.stamp })
301
282
 
302
- serveNode({
283
+ await serveNode({
303
284
  fetch: app.fetch,
304
285
  port,
305
286
  hostname: host,
@@ -316,22 +297,9 @@ async function serve(): Promise<void> {
316
297
  })
317
298
  }
318
299
 
319
- /**
320
- * `openapi` — print (or `--out`-write) the emitted OpenAPI document for this surface. Builds the app around an
321
- * all-optional stub {@link NominatimEngine} (`{}` — every route answers 501 under this stub, but the document itself
322
- * only reflects the ROUTE TABLE, not handler behavior) so this NEVER boots the neural classifier or opens a gazetteer
323
- * DB: pure route-table introspection, fast regardless of data-root state. `--flavor 3.0` prints the 3.0.3 diet instead
324
- * of the default 3.1.0.
325
- */
326
- function openapi(): void {
327
- const app = createNominatimApp({})
328
-
329
- printOpenAPIDocument(app, NOMINATIM_DOC_INFO, parseOpenAPIFlags(BINARY_NAME))
330
- }
331
-
332
300
  await runDropInCLI({
333
301
  binaryName: BINARY_NAME,
334
- openapi,
302
+ openapi: openAPICommand(BINARY_NAME, createNominatimApp, NOMINATIM_DOC_INFO, {}),
335
303
  serve,
336
304
  usage: [
337
305
  " serve [--port 8080] [--host 0.0.0.0] [--candidate-db <path>] [--no-cors]",
@@ -10,16 +10,15 @@
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 = "mailwoman/test-fixtures/legacy-golden/parity-inputs.jsonl"
21
- const SYNTHETIC_PATH = "mailwoman/test-fixtures/legacy-golden/synthetic-inputs.txt"
22
- const OUT_PATH = "nominatim/test-fixtures/search-golden.jsonl"
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"
21
+ const OUT_PATH = "packages/nominatim/test-fixtures/search-golden.jsonl"
23
22
 
24
23
  interface ParityRow {
25
24
  input: string
@@ -37,11 +36,11 @@ const withHouseNumber = parity
37
36
 
38
37
  const syntheticInputs = (await Array.fromAsync(TextSpliterator.fromAsync(SYNTHETIC_PATH)))
39
38
  .map((line) => line.trim())
40
- .filter(Boolean)
39
+ .filter((line) => line.length > 0)
41
40
 
42
41
  const queries = [...new Set([...withHouseNumber.slice(0, 172), ...syntheticInputs])]
43
42
 
44
- const child = spawn("node", ["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,11 +104,16 @@ 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 {
108
- const displayName = r.displayName ?? Object.values(r.address).filter(Boolean).join(", ")
111
+ const displayName =
112
+ r.displayName ??
113
+ Object.values(r.address)
114
+ .filter((value) => typeof value === "string" && value.length > 0)
115
+ .join(", ")
116
+
109
117
  const lat = r.lat != null ? String(r.lat) : ""
110
118
  const lon = r.lon != null ? String(r.lon) : ""
111
119