@mailwoman/nominatim 9.4.0 → 10.1.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 (52) hide show
  1. package/README.md +5 -5
  2. package/{lib/cli.ts → cli/main.ts} +53 -44
  3. package/lib/app.ts +11 -16
  4. package/lib/engine.ts +56 -33
  5. package/lib/format.ts +36 -23
  6. package/lib/forward-address.ts +5 -7
  7. package/lib/index.ts +9 -14
  8. package/lib/routes.ts +20 -18
  9. package/lib/schema.ts +38 -42
  10. package/out/app.d.ts +11 -12
  11. package/out/app.d.ts.map +1 -1
  12. package/out/app.js +2 -10
  13. package/out/app.js.map +1 -1
  14. package/out/cli/main.d.ts +16 -0
  15. package/out/cli/main.d.ts.map +1 -0
  16. package/out/{cli.js → cli/main.js} +51 -44
  17. package/out/cli/main.js.map +1 -0
  18. package/out/engine.d.ts +56 -33
  19. package/out/engine.d.ts.map +1 -1
  20. package/out/engine.js +6 -7
  21. package/out/engine.js.map +1 -1
  22. package/out/format.d.ts +30 -18
  23. package/out/format.d.ts.map +1 -1
  24. package/out/format.js +26 -17
  25. package/out/format.js.map +1 -1
  26. package/out/forward-address.d.ts +2 -4
  27. package/out/forward-address.d.ts.map +1 -1
  28. package/out/forward-address.js +5 -7
  29. package/out/forward-address.js.map +1 -1
  30. package/out/index.d.ts +9 -14
  31. package/out/index.d.ts.map +1 -1
  32. package/out/index.js +9 -14
  33. package/out/index.js.map +1 -1
  34. package/out/routes.d.ts +3 -3
  35. package/out/routes.d.ts.map +1 -1
  36. package/out/routes.js +20 -18
  37. package/out/routes.js.map +1 -1
  38. package/out/schema.d.ts +34 -36
  39. package/out/schema.d.ts.map +1 -1
  40. package/out/schema.js +38 -42
  41. package/out/schema.js.map +1 -1
  42. package/out/{dev-tools → tools}/capture-search-golden.run.d.ts +3 -3
  43. package/out/tools/capture-search-golden.run.d.ts.map +1 -0
  44. package/out/{dev-tools → tools}/capture-search-golden.run.js +15 -14
  45. package/out/tools/capture-search-golden.run.js.map +1 -0
  46. package/package.json +74 -37
  47. package/{lib/dev-tools → tools}/capture-search-golden.run.ts +14 -14
  48. package/out/cli.d.ts +0 -17
  49. package/out/cli.d.ts.map +0 -1
  50. package/out/cli.js.map +0 -1
  51. package/out/dev-tools/capture-search-golden.run.d.ts.map +0 -1
  52. package/out/dev-tools/capture-search-golden.run.js.map +0 -1
package/README.md CHANGED
@@ -8,7 +8,7 @@ MAILWOMAN_DATA_ROOT="${MAILWOMAN_DATA_ROOT:-/tmp/mailwoman-data}" npx mailwoman
8
8
 
9
9
  MAILWOMAN_DATA_ROOT="${MAILWOMAN_DATA_ROOT:-/tmp/mailwoman-data}" \
10
10
  npx @mailwoman/nominatim serve --port 8080
11
- # The pulled candidate.db is auto-detected at $MAILWOMAN_DATA_ROOT/wof/candidate.db — no export needed.
11
+ # The pulled candidate.db is auto-detected at $MAILWOMAN_DATA_ROOT/db/wof/candidate.db — no export needed.
12
12
  # Or point at your own: --candidate-db <path> / $MAILWOMAN_CANDIDATE_DB
13
13
  ```
14
14
 
@@ -22,7 +22,7 @@ geo.reverse((38.8977, -77.0365))
22
22
 
23
23
  ## Endpoints
24
24
 
25
- | Endpoint | Nominatim contract | Status |
25
+ | Endpoint | Nominatim interface | Status |
26
26
  | --------------- | ------------------------------------------------------------- | ------- |
27
27
  | `/` | HTML landing page (endpoint index + example queries) | ✓ |
28
28
  | `/search` | free-text `q` + structured forward geocoding | ✓ |
@@ -50,8 +50,8 @@ Browser-embedded geocoder clients call this cross-origin, so the server sends pe
50
50
 
51
51
  ## Annotations
52
52
 
53
- Every result carries an OpenCage-style `annotations` block — coordinate formats (DMS, MGRS, geohash,
54
- Maidenhead, Mercator), qibla bearing, sun times, country flag, calling code, and currency, plus the IANA
53
+ The API returns an OpenCage-style `annotations` block — coordinate formats (DMS, MGRS, geohash,
54
+ Maidenhead, Mercator), qibla direction, sun times, country flag, calling code, and currency, plus the IANA
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
 
@@ -85,7 +85,7 @@ Nominatim-compatible field — the newest build date across the databases this p
85
85
  ```
86
86
 
87
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
88
+ from a file's timestamp or a record kept alongside. An artifact built without a manifest, and
89
89
  says so (`"manifest": "absent"`) rather than being left out; when none of them carries one, `data_updated` is omitted
90
90
  instead of guessed. A Nominatim client ignores the `mailwoman` key.
91
91
 
@@ -4,38 +4,39 @@
4
4
  * @license AGPL-3.0
5
5
  * @author Teffen Ellis, et al.
6
6
  *
7
- * `mailwoman-nominatim` — boot a Nominatim-compatible endpoint via the `serve` command. Usage +
8
- * examples live in the package README.
7
+ * `mailwoman-nominatim`, booting a Nominatim-compatible endpoint through the `serve` command.
8
+ * Usage and examples live in the package readme.
9
9
  *
10
- * Wires the real engine: `/search` over `geocodeAddress` (parse → resolve), `/reverse` over
11
- * `WOFReverseGeocoder` (point-in-polygon over WOF admin polygons), reusing the same
12
- * resolver-backend selector GeocodeRouter uses. Results carry the OpenCage-style `annotations`
13
- * block — coordinate formats, flag, calling code, currency, and (when their DBs are present)
14
- * timezone, UN/LOCODE, NUTS — composed from the `@mailwoman/*` annotators.
10
+ * Wires the real engine: `/search` over `geocodeAddress` and `/reverse` over
11
+ * `WOFReverseGeocoder` (point-in-polygon over WOF admin polygons), reusing the resolver-backend
12
+ * selector `GeocodeRouter` uses. Results include the OpenCage-style `annotations` block composed
13
+ * from the `@mailwoman/*` annotators.
15
14
  */
16
15
 
17
16
  import { composeAnnotators, toOpenCage } from "@mailwoman/annotations"
18
17
  import { serveNode } from "@mailwoman/api-kit"
19
18
  import { countryReferenceAnnotator, matchCountry } from "@mailwoman/codex/country"
19
+ import { dataRootPath } from "@mailwoman/core/data-root"
20
20
  import { pathExists } from "@mailwoman/core/fs/readers"
21
21
  import { parseArguments } from "@mailwoman/core/scripting/arguments"
22
- import { dataRootPath, mailwomanDataRoot } from "@mailwoman/core/utils"
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"
26
+ import { timezoneDatabasePath } from "@mailwoman/timezone-lookup/paths"
27
27
  import { makeUNLocodeAnnotator, UNLocodeLookup } from "@mailwoman/un-locode-lookup"
28
28
  import {
29
29
  corsBannerLine,
30
30
  gazetteerBannerLines,
31
+ rightsBannerLines,
31
32
  gazetteerFreshness,
32
33
  loadClassifierOrExit,
33
34
  openAPICommand,
34
35
  resolveGazetteerOrExit,
35
36
  runDropInCLI,
36
- } from "mailwoman/cli-kit/dropin"
37
- import type { ResolvedEngineStamp } from "mailwoman/cli-kit/engine-stamp"
38
- import { geocodeAddress, RegionDatabaseProvider } from "mailwoman/geocode"
37
+ } from "mailwoman/cli/kit/dropin"
38
+ import type { ResolvedEngineStamp } from "mailwoman/cli/kit/engine-stamp"
39
+ import { geocodeAddress, USStateDatabaseProvider } from "mailwoman/geocode"
39
40
  import { createResolverBackend } from "mailwoman/resolver-backend"
40
41
  import { resolvePath } from "path-ts"
41
42
 
@@ -67,15 +68,17 @@ const PLACETYPE_TO_KEY: Record<string, keyof NominatimAddressDetails> = {
67
68
  }
68
69
 
69
70
  /**
70
- * A real address fits comfortably; anything longer is malformed input (and would exceed the model's input window). Cap
71
- * defensively so a giant query returns no results instead of faulting.
71
+ * A real address fits comfortably and anything longer is malformed input that
72
+ * would exceed the model's input window.
73
+ *
74
+ * Cap defensively so a giant query returns no results instead of faulting.
72
75
  */
73
76
  const MAX_QUERY_LEN = 512
74
77
 
75
78
  const BINARY_NAME = "mailwoman-nominatim"
76
79
 
77
80
  function joinNonEmpty(...parts: Array<string | undefined>): string {
78
- return parts.filter((part) => part !== undefined && part.length > 0).join(", ")
81
+ return parts.filter((part) => part !== undefined && part.length).join(", ")
79
82
  }
80
83
 
81
84
  async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
@@ -84,8 +87,8 @@ async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
84
87
  port: { type: "string", default: "8080" },
85
88
  host: { type: "string", default: "0.0.0.0" },
86
89
  "candidate-db": { type: "string" },
87
- // Permissive CORS is on by default (browser geocoder clients need it). `--no-cors` turns it off for
88
- // deployments where a reverse proxy already sets the headers.
90
+ // Permissive cors is on by default (browser geocoder clients need it).
91
+ // `--no-cors` turns it off for deployments where a reverse proxy already sets the headers.
89
92
  cors: { type: "boolean", default: true },
90
93
  },
91
94
  allowNegative: true,
@@ -102,22 +105,23 @@ async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
102
105
 
103
106
  const backend = await createResolverBackend(resolverMod, { wofPaths, candidateDB })
104
107
  const resolver = createWOFResolver(backend)
105
- const extracts = await RegionDatabaseProvider.create(resolverMod, mailwomanDataRoot())
106
- // National open-register rooftop tier (#1012): BAN-FR ahead of the OSM tier for a non-US parse. A no-op
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())
110
- // NOT a geocode country constraint. The default-on #244 placer already routes the query's country
111
- // (Berlin→DE, Boston→US) and `defaultCountry` is a HARD override that beats it (geocode-core.ts:102),
112
- // so forcing "US" resolved every non-US query to its US namesake (Berlin→Berlin NH). We let the
113
- // placer decide instead. This is the fallback used ONLY to annotate the flag/currency/calling-code
114
- // when the resolved hierarchy omits the country tag — which on US-centric data (no candidate DB)
115
- // happens for US results, where "US" is the right guess. Non-US results carry the country tag, so
116
- // the fallback never mislabels them.
108
+ const extracts = await USStateDatabaseProvider.create(resolverMod, dataRootPath())
109
+ // National open-register rooftop tier: BAN-FR ahead of the OSM tier for a non-US parse.
110
+ // A no-op when the extract is not on disk, so the endpoint degrades cleanly.
111
+ const { BANRegionDatabaseProvider } = await import("@mailwoman/ban/region-database-provider")
112
+ const banExtracts = await BANRegionDatabaseProvider.create(dataRootPath())
113
+ // The annotation fallback adds no country constraint to the geocode.
114
+ // The default-on placer already routes the query's country.
115
+ // `defaultCountry` is a hard override that beats it, so forcing "US" would
116
+ // resolve every non-US query to its US namesake.
117
+ // The fallback only annotates the flag, currency and calling code when the
118
+ // resolved hierarchy omits the country tag.
119
+ // US-centric data without a candidate DB omits it for US results, where "US" is
120
+ // the right guess, while non-US results include the country tag.
117
121
  const annotationCountryFallback = candidateDB ? undefined : "US"
118
122
  const reverseGeo = adminDBPath ? new resolverMod.WOFReverseGeocoder({ adminDBPath }) : undefined
119
123
  const annotators = [coordinateFormatAnnotator, countryReferenceAnnotator]
120
- const tzDBPath = dataRootPath("timezone", "timezone.db")
124
+ const tzDBPath = timezoneDatabasePath("timezone.db")
121
125
 
122
126
  if (await pathExists(tzDBPath)) {
123
127
  annotators.push(makeTimezoneAnnotator(new TimezoneLookup({ databasePath: resolvePath(tzDBPath) })))
@@ -137,9 +141,9 @@ async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
137
141
 
138
142
  const annotate = composeAnnotators(annotators)
139
143
 
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.
144
+ // Read once at boot from the artifacts themselves, so this describes what the
145
+ // endpoint serves from for as long as it serves.
146
+ // Every artifact appears, including one carrying no manifest.
143
147
  const status = nominatimStatus(await gazetteerFreshness(gazetteer))
144
148
 
145
149
  const engine: NominatimEngine = {
@@ -148,12 +152,10 @@ async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
148
152
  params.q ?? joinNonEmpty(params.street, params.city, params.state, params.postalcode, params.country)
149
153
  )?.trim()
150
154
 
151
- // Empty/whitespace → no query; absurdly long → not an address (and would blow the model's input).
152
155
  if (!query || query.length > MAX_QUERY_LEN) return []
153
- // A caller-supplied `countrycodes` is an explicit hard restriction (Nominatim semantics): honor
154
- // it as the country constraint, even to the point of no result. It doubles as the manual override
155
- // for the #822 placer frontier — `countrycodes=au` lands Sydney in Australia. One country is the
156
- // common (geopy) case; for a list we apply the first.
156
+ // A caller-supplied `countrycodes` is an explicit hard restriction in Nominatim semantics,
157
+ // so it is honored as the country constraint even to the point of no result.
158
+ // For a list we apply the first, the common geopy case.
157
159
  const userCountry = params.countrycodes?.[0]?.toUpperCase()
158
160
 
159
161
  const result = await geocodeAddress(query, {
@@ -167,10 +169,10 @@ async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
167
169
  if (result.lat == null || result.lon == null) return []
168
170
  const resolved = forwardToResolved(result)
169
171
 
170
- // #1041: a rooftop (`address_point`) / house-number-estimate (`interpolated`) tier is HOUSE-GRADE — tag the
171
- // result `class: place` / `type: house` (upstream Nominatim's own class/type for a house), so a client that
172
- // keys on `class`/`type`/`addresstype` treats it as a building, not an untyped admin hit. The admin tier
173
- // (a locality centroid) carries no class/type here, as before.
172
+ // A house-grade resolution tier (`address_point`, `interpolated` or `plus_code`) is tagged
173
+ // `class: place` and `type: house`, upstream Nominatim's own class and type for a house,
174
+ // so a client that keys on those fields treats it as a building rather than an untyped admin hit.
175
+ // The admin tier has no class here.
174
176
  if (
175
177
  result.resolution_tier === "address_point" ||
176
178
  result.resolution_tier === "interpolated" ||
@@ -180,7 +182,7 @@ async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
180
182
  resolved.type = "house"
181
183
  }
182
184
 
183
- // The geocode result already carries the parse's street spans (#1041) — no second parse.
185
+ // The geocode result already includes the parse's street spans, so no second parse.
184
186
  if (result.house_number) {
185
187
  resolved.address.house_number = result.house_number
186
188
  }
@@ -189,8 +191,9 @@ async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
189
191
  resolved.address.road = result.street
190
192
  }
191
193
 
192
- // The country tag isn't always in the hierarchy (US admin results omit it); backfill from the
193
- // US-centric-data default so the address, display_name, and flag/currency/calling-code agree.
194
+ // The country tag is not always in the hierarchy, since US admin results omit it.
195
+ // Backfill from the US-centric-data default so the address, display name,
196
+ // flag, currency and calling code agree.
194
197
  const countryName = result.hierarchy.find((h) => h.tag === "country")?.value ?? annotationCountryFallback
195
198
  const country = matchCountry(countryName)
196
199
 
@@ -292,6 +295,12 @@ async function serve(engineStamp: ResolvedEngineStamp): Promise<void> {
292
295
  console.error(line)
293
296
  }
294
297
 
298
+ // The terms come from the same `layer_manifest` rows the `/status` payload includes,
299
+ // so the operator reads them at boot rather than by querying the endpoint they just started.
300
+ for (const line of rightsBannerLines(status.mailwoman ?? { artifacts: [] })) {
301
+ console.error(line)
302
+ }
303
+
295
304
  console.error(corsBannerLine(values.cors))
296
305
  console.error(` endpoints: GET / GET /search GET /reverse GET /lookup GET /status GET /openapi.json`)
297
306
  },
package/lib/app.ts CHANGED
@@ -2,9 +2,6 @@
2
2
  * @copyright Sister Software
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
- *
6
- * The Nominatim-compatible Hono app: CORS + error safety net + routes + the emitted OpenAPI
7
- * document. Engine-agnostic — the CLI wires the real engine; tests inject fixtures.
8
5
  */
9
6
 
10
7
  import { OpenAPIHono } from "@hono/zod-openapi"
@@ -20,24 +17,26 @@ import { registerNominatimRoutes } from "#routes"
20
17
  */
21
18
  export interface NominatimAppOptions {
22
19
  /**
23
- * Emit permissive CORS headers (`Access-Control-Allow-Origin: *`) on every response and answer preflight `OPTIONS`
24
- * with `204`. Default `true` — browser-embedded geocoder clients need it: a cross-origin XHR is blocked without it
25
- * (#1017). Set `false` when a reverse proxy already owns the CORS headers.
20
+ * Whether every response includes `Access-Control-Allow-Origin: *` and preflight requests
21
+ * are answered, defaulting to `true` so browser clients can call cross-origin.
22
+ *
23
+ * Set it to `false` when a reverse proxy already sets the CORS headers.
26
24
  */
27
25
  cors?: boolean
28
26
 
29
27
  /**
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.
28
+ * The engine stamp is added to each JSON result and GeoJSON collection.
29
+ *
30
+ * It also appears in the `Server` and `Link: rel="license"` headers.
31
+ *
32
+ * An embedding application may omit it, but the `nominatim` CLI always passes one.
33
33
  */
34
34
  engine?: EngineStamp
35
35
  }
36
36
 
37
37
  /**
38
- * The document info stamped into the emitted OpenAPI document. Exported (not inlined) so the CLI's `openapi` subcommand
39
- * can call `emitOpenAPIDocuments` with the SAME info the mounted `/openapi.json` route (below, via
40
- * {@link attachOpenAPIDocs}) uses — one source of truth, no risk of the two drifting.
38
+ * Supplies the OpenAPI document info shared by the served `/openapi.json` route
39
+ * and the CLI's `openapi` subcommand, so the two documents cannot drift apart.
41
40
  */
42
41
  export const NOMINATIM_DOC_INFO: OpenAPIDocInfo = {
43
42
  ...(await readServedDocumentInfo(import.meta.url, "@mailwoman/nominatim")),
@@ -66,8 +65,6 @@ export const NOMINATIM_DOC_INFO: OpenAPIDocInfo = {
66
65
  export function createNominatimApp(engine: NominatimEngine, options: NominatimAppOptions = {}): OpenAPIHono {
67
66
  const app = new OpenAPIHono()
68
67
 
69
- // Browser-embedded geocoder clients need CORS or their cross-origin XHR is blocked before completing (#1017).
70
- // GET-only — nominatim has no mutating routes, so unlike libpostal's CORS there is no POST in the methods list.
71
68
  if (options.cors !== false) {
72
69
  app.use(cors({ origin: "*", allowMethods: ["GET", "OPTIONS"], allowHeaders: ["*"], maxAge: 86_400 }))
73
70
  }
@@ -76,8 +73,6 @@ export function createNominatimApp(engine: NominatimEngine, options: NominatimAp
76
73
  app.use(engineHeaders(options.engine))
77
74
  }
78
75
 
79
- // Safety net: a malformed query or an engine fault must never crash the process into a stack-trace 500 — the
80
- // clean legacy JSON error instead (`{error}` — NOT photon's FeatureCollection+message envelope).
81
76
  app.onError((_error, c) => c.json({ error: "internal error" }, 500))
82
77
 
83
78
  registerNominatimRoutes(app, engine, options.engine)
package/lib/engine.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * The Nominatim engine contract + wire types the router delegates to. The RESOLVED-address →
6
+ * The Nominatim engine interface + wire types the router delegates to. The resolved-address →
7
7
  * {@link NominatimResult} formatter (`toNominatimResult`, `toFeatureCollection`,
8
8
  * `nominatimResultToSchemaOrg`) lives in `format.ts`.
9
9
  */
@@ -11,15 +11,18 @@
11
11
  import type { OpenCageAnnotations } from "@mailwoman/annotations"
12
12
 
13
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.
14
+ * Output serialization formats Nominatim supports.
15
+ *
16
+ * `jsonv2` is the modern default and `jsonld` is the Mailwoman extension that emits
17
+ * schema.org `Place` JSON-LD rather than an upstream Nominatim format.
16
18
  */
17
19
  export type NominatimFormat = "jsonv2" | "json" | "geojson" | "jsonld"
18
20
 
19
21
  /**
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).
22
+ * The structured address breakdown returned under `address` when `addressdetails=1`.
23
+ *
24
+ * Keys mirror Nominatim's OSM-derived tag names, populated from Mailwoman's
25
+ * `ComponentTag` and resolved ancestor lineage.
23
26
  */
24
27
  export type NominatimAddressDetails = Record<string, string>
25
28
 
@@ -48,13 +51,13 @@ export interface NominatimResult {
48
51
  */
49
52
  geojson?: unknown
50
53
  /**
51
- * OpenCage-style enrichment block (timezone, coordinate formats, …); attached by the engine.
54
+ * OpenCage-style enrichment block (timezone, coordinate formats, …), attached by the engine.
52
55
  */
53
56
  annotations?: OpenCageAnnotations
54
57
  }
55
58
 
56
59
  /**
57
- * Parsed `/search` parameters (free-text OR structured; never both).
60
+ * Parsed `/search` parameters (free-text or structured. Never both).
58
61
  */
59
62
  export interface NominatimSearchParams {
60
63
  q?: string
@@ -95,17 +98,18 @@ export interface NominatimLookupParams {
95
98
  }
96
99
 
97
100
  /**
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.
101
+ * Whether an artifact could state its own provenance.
102
+ *
103
+ * `unreadable` is kept apart from `absent` because "we could not open it" is a
104
+ * fault to chase rather than a rebuild to schedule.
100
105
  */
101
106
  export type NominatimManifestState = "present" | "absent" | "unreadable"
102
107
 
103
108
  /**
104
- * One database this deployment is serving from, and what it says about itself.
109
+ * One database this deployment serves and its self-reported metadata.
105
110
  *
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.
111
+ * The wire surface owns its own doc-accuracy types, so the CLI assigns the reader's report
112
+ * straight into this shape and a drift is a compile error rather than a different response body.
109
113
  */
110
114
  export interface NominatimStatusArtifact {
111
115
  /**
@@ -119,27 +123,44 @@ export interface NominatimStatusArtifact {
119
123
  */
120
124
  reason?: string
121
125
  /**
122
- * When the artifact was BUILT, as its own manifest records it.
126
+ * When the artifact was built, as its own manifest records it.
123
127
  */
124
128
  built?: string
125
129
  /**
126
- * `<layer name>@<layer version>` — the artifact's identity.
130
+ * `<layer name>@<layer version>`, the artifact's identity.
127
131
  */
128
132
  version?: string
129
133
  /**
130
- * What it was built FROM: the manifest's source, then its source vintage.
134
+ * What it was built from: the manifest's source, then its source vintage.
131
135
  */
132
136
  sources?: string[]
137
+ /**
138
+ * The SPDX expression this artifact's own manifest records, verbatim.
139
+ *
140
+ * Left out when the row holds none.
141
+ * An absent expression states that the build did not record the obligations.
142
+ *
143
+ * The artifact may still contain a manifest, so a client must not read its absence as permissive.
144
+ */
145
+ license?: string
146
+ /**
147
+ * The credit line the publisher's terms ask for, as this artifact's own manifest records it.
148
+ */
149
+ attribution?: string
133
150
  }
134
151
 
135
152
  /**
136
- * The native provenance block. A Nominatim client ignores unknown keys, so this rides alongside the compatible
153
+ * The native provenance block.
154
+ *
155
+ * A Nominatim client ignores unknown keys, so this appears beside the compatible
137
156
  * `data_updated` without breaking one.
138
157
  */
139
158
  export interface NominatimStatusExtension {
140
159
  /**
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.
160
+ * Every artifact this process opened, including those with no manifest.
161
+ *
162
+ * An unstamped artifact reports its own absence rather than being omitted,
163
+ * because an omission cannot be told apart from an unopened artifact.
143
164
  */
144
165
  artifacts: NominatimStatusArtifact[]
145
166
  }
@@ -151,16 +172,18 @@ export interface NominatimStatus {
151
172
  status: number
152
173
  message: string
153
174
  /**
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.
175
+ * The newest build epoch across the artifacts this deployment opened.
176
+ *
177
+ * Left out when none of them has a manifest.
178
+ * A boot time or a file mtime would answer a question the process cannot answer.
156
179
  */
157
180
  data_updated?: string
158
181
  mailwoman?: NominatimStatusExtension
159
182
  }
160
183
 
161
184
  /**
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.
185
+ * A freshness report as this surface consumes it, structurally `mailwoman/freshness`'s `FreshnessReport`
186
+ * and declared here so the wire interface keeps no import from the engine implementation.
164
187
  */
165
188
  export interface NominatimFreshnessReport {
166
189
  dataUpdated?: string
@@ -170,13 +193,12 @@ export interface NominatimFreshnessReport {
170
193
  /**
171
194
  * Compose the `/status` payload from a freshness report.
172
195
  *
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.
196
+ * A function prevents the CLI and response test from holding separate copies of the mapping.
197
+ * The mapped field is omitted under a condition, so both callers need the same logic.
176
198
  *
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.
199
+ * `data_updated` is dropped when no artifact recorded a build date,
200
+ * since Nominatim declares the field optional.
201
+ * A boot time or a file mtime would look measured and answer a question the process cannot.
180
202
  */
181
203
  export function nominatimStatus(freshness: NominatimFreshnessReport): NominatimStatus {
182
204
  return {
@@ -188,9 +210,10 @@ export function nominatimStatus(freshness: NominatimFreshnessReport): NominatimS
188
210
  }
189
211
 
190
212
  /**
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.
213
+ * The geocoding engine the router delegates to.
214
+ *
215
+ * Each method is optional and a route whose method is absent answers `501 Not Implemented`.
216
+ * The real implementation is wired by the CLI.
194
217
  */
195
218
  export interface NominatimEngine {
196
219
  search?(params: NominatimSearchParams): Promise<NominatimResult[]>
package/lib/format.ts CHANGED
@@ -3,10 +3,10 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * The RESOLVED-address → Nominatim-schema formatter: rendering a {@link ResolvedAddress} into a
6
+ * The resolved-address → Nominatim-schema formatter: rendering a {@link ResolvedAddress} into a
7
7
  * {@link NominatimResult} (`toNominatimResult`), the `format=geojson` FeatureCollection envelope
8
8
  * (`toFeatureCollection`), and the `format=jsonld` schema.org projection
9
- * (`nominatimResultToSchemaOrg`). Wire types + the engine contract live in `engine.ts`.
9
+ * (`nominatimResultToSchemaOrg`). Wire types + the engine interface live in `engine.ts`.
10
10
  */
11
11
 
12
12
  import { composeStreetAddress, type SchemaOrgPlace, toSchemaOrg } from "@mailwoman/annotations"
@@ -19,7 +19,7 @@ import type { NominatimAddressDetails, NominatimResult } from "#engine"
19
19
  const BBOX_2D_LENGTH = 4
20
20
 
21
21
  /**
22
- * A GeoJSON `FeatureCollection` — the `format=geojson` envelope.
22
+ * A GeoJSON `FeatureCollection`, the `format=geojson` envelope.
23
23
  */
24
24
  export interface NominatimFeatureCollection {
25
25
  type: "FeatureCollection"
@@ -32,18 +32,22 @@ export interface NominatimFeatureCollection {
32
32
  }
33
33
 
34
34
  /**
35
- * Render results as a GeoJSON `FeatureCollection` (`format=geojson`). Nominatim moves the coordinate into `geometry` (a
36
- * Point, or the place polygon when one is present), `boundingbox` ([south, north, west, east]) into a GeoJSON `bbox`
37
- * ([west, south, east, north]), and the remaining result fields into `properties`. Rows without a coordinate are
38
- * dropped — a Feature needs a geometry.
35
+ * Render results as a GeoJSON `FeatureCollection` (`format=geojson`).
36
+ *
37
+ * Nominatim moves the coordinate into `geometry` (a Point, or the place polygon when one is present),
38
+ * `boundingbox` ([south, north, west, east]) into a GeoJSON `bbox` ([west, south, east, north]),
39
+ * and the remaining result fields into `properties`.
40
+ * Rows without a coordinate are dropped.
41
+ * A Feature needs a geometry.
39
42
  */
40
43
  export function toFeatureCollection(results: readonly NominatimResult[]): NominatimFeatureCollection {
41
44
  const features: NominatimFeatureCollection["features"] = []
42
45
 
43
46
  for (const r of results) {
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
+ // `toNominatimResult` writes "" for a missing coordinate, never null,
48
+ // so emptiness is the condition that matters.
49
+ // A `== null` check by itself lets a coordinate-less row through as Point [0, 0],
50
+ // a real place in the Gulf of Guinea rather than an absence.
47
51
  if (!r.lat || !r.lon) continue
48
52
  const { lat, lon, boundingbox, geojson, ...properties } = r
49
53
 
@@ -54,7 +58,7 @@ export function toFeatureCollection(results: readonly NominatimResult[]): Nomina
54
58
  }
55
59
 
56
60
  if (boundingbox?.length === BBOX_2D_LENGTH) {
57
- // boundingbox is [south, north, west, east]; GeoJSON bbox is [west, south, east, north].
61
+ // boundingbox is [south, north, west, east] and GeoJSON bbox is [west, south, east, north].
58
62
  feature.bbox = [Number(boundingbox[2]), Number(boundingbox[0]), Number(boundingbox[3]), Number(boundingbox[1])]
59
63
  }
60
64
 
@@ -65,16 +69,20 @@ export function toFeatureCollection(results: readonly NominatimResult[]): Nomina
65
69
  }
66
70
 
67
71
  /**
68
- * A resolved address in a neutral shape, the input to {@link toNominatimResult}. The engine maps its native
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.
72
+ * A resolved address in a neutral shape, the input to {@link toNominatimResult}.
73
+ *
74
+ * The engine maps its native geocode or reverse result into this.
75
+ * The formatter renders it as a Nominatim result.
76
+ *
77
+ * It is the mapping boundary and stays dependency-free so it is unit-testable.
71
78
  */
72
79
  export interface ResolvedAddress {
73
80
  lat: number | null
74
81
  lon: number | null
75
82
  address: NominatimAddressDetails
76
83
  /**
77
- * Pre-rendered display name; falls back to the address values joined by ", ".
84
+ * Pre-rendered display name.
85
+ * Falls back to the address values joined by ", ".
78
86
  */
79
87
  displayName?: string
80
88
  category?: string
@@ -83,7 +91,7 @@ export interface ResolvedAddress {
83
91
  placeRank?: number
84
92
  boundingbox?: [string, string, string, string]
85
93
  /**
86
- * A stable id from the resolver (WOF/GERS); a deterministic hash is used when absent.
94
+ * A stable id from the resolver (WOF or gers), with a deterministic hash when absent.
87
95
  */
88
96
  placeID?: string | number
89
97
  }
@@ -104,14 +112,16 @@ function stableID(seed: string): number {
104
112
  }
105
113
 
106
114
  /**
107
- * Render a {@link ResolvedAddress} as a Nominatim result. `addressdetails` selects the `address` block, matching
108
- * Nominatim. The `annotations` block is attached by the caller (empty until the annotations layer lands).
115
+ * Render a {@link ResolvedAddress} as a Nominatim result.
116
+ *
117
+ * `addressdetails` selects the `address` block, matching Nominatim.
118
+ * The caller attaches the `annotations` block.
109
119
  */
110
120
  export function toNominatimResult(r: ResolvedAddress, opts: { addressdetails?: boolean } = {}): NominatimResult {
111
121
  const displayName =
112
122
  r.displayName ??
113
123
  Object.values(r.address)
114
- .filter((value) => typeof value === "string" && value.length > 0)
124
+ .filter((value) => typeof value === "string" && value.length)
115
125
  .join(", ")
116
126
 
117
127
  const lat = r.lat != null ? String(r.lat) : ""
@@ -153,10 +163,13 @@ export function toNominatimResult(r: ResolvedAddress, opts: { addressdetails?: b
153
163
  }
154
164
 
155
165
  /**
156
- * Project a Nominatim result into a schema.org `Place` JSON-LD object (`format=jsonld`, #1052) — the OUTPUT-format
157
- * projection. Reads the result's `address` breakdown (populated because the router forces `addressdetails` for
158
- * `jsonld`) plus the coordinate, re-serializing the SAME resolved place. `streetAddress` is the plain
159
- * house-number-first join (house_number + road); `addressCountry` is ISO-3166 alpha-2 (uppercased).
166
+ * Project a Nominatim result into a schema.org `Place` JSON-LD object for `format=jsonld`.
167
+ *
168
+ * It reads the result's `address` breakdown.
169
+ * The router populates this by forcing `addressdetails` for jsonld.
170
+ *
171
+ * The formatter then re-serializes the same resolved place.
172
+ * `streetAddress` is the house-number-first join and `addressCountry` is ISO-3166 alpha-2 uppercased.
160
173
  */
161
174
  export function nominatimResultToSchemaOrg(r: NominatimResult): SchemaOrgPlace {
162
175
  const a = r.address ?? {}