@mailwoman/ogc 0.0.0-stage → 11.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +149 -2
  2. package/cli/main.ts +153 -0
  3. package/lib/app.ts +99 -0
  4. package/lib/collections.ts +159 -0
  5. package/lib/engine.ts +71 -0
  6. package/lib/format.ts +46 -0
  7. package/lib/html.ts +236 -0
  8. package/lib/index.ts +20 -0
  9. package/lib/projection.ts +206 -0
  10. package/lib/routes.ts +587 -0
  11. package/lib/schema.ts +296 -0
  12. package/out/app.d.ts +33 -0
  13. package/out/app.d.ts.map +1 -0
  14. package/out/app.js +67 -0
  15. package/out/app.js.map +1 -0
  16. package/out/cli/main.d.ts +3 -0
  17. package/out/cli/main.d.ts.map +1 -0
  18. package/out/cli/main.js +118 -0
  19. package/out/cli/main.js.map +1 -0
  20. package/out/collections.d.ts +72 -0
  21. package/out/collections.d.ts.map +1 -0
  22. package/out/collections.js +103 -0
  23. package/out/collections.js.map +1 -0
  24. package/out/engine.d.ts +65 -0
  25. package/out/engine.d.ts.map +1 -0
  26. package/out/engine.js +4 -0
  27. package/out/engine.js.map +1 -0
  28. package/out/format.d.ts +18 -0
  29. package/out/format.d.ts.map +1 -0
  30. package/out/format.js +31 -0
  31. package/out/format.js.map +1 -0
  32. package/out/html.d.ts +42 -0
  33. package/out/html.d.ts.map +1 -0
  34. package/out/html.js +153 -0
  35. package/out/html.js.map +1 -0
  36. package/out/index.d.ts +17 -0
  37. package/out/index.d.ts.map +1 -0
  38. package/out/index.js +19 -0
  39. package/out/index.js.map +1 -0
  40. package/out/projection.d.ts +26 -0
  41. package/out/projection.d.ts.map +1 -0
  42. package/out/projection.js +168 -0
  43. package/out/projection.js.map +1 -0
  44. package/out/routes.d.ts +93 -0
  45. package/out/routes.d.ts.map +1 -0
  46. package/out/routes.js +429 -0
  47. package/out/routes.js.map +1 -0
  48. package/out/schema.d.ts +267 -0
  49. package/out/schema.d.ts.map +1 -0
  50. package/out/schema.js +241 -0
  51. package/out/schema.js.map +1 -0
  52. package/package.json +98 -3
package/lib/html.ts ADDED
@@ -0,0 +1,236 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * HTML encodings of the OGC API resources.
6
+ *
7
+ * OGC API Common's HTML class asks that an HTML response include everything the
8
+ * JSON response includes and render every link as an `<a>` element.
9
+ * Each page here renders from the same value the JSON route serves, so the two encodings can't disagree.
10
+ */
11
+
12
+ import type { OpenAPIHono } from "@hono/zod-openapi"
13
+ import { escapeHTML } from "@mailwoman/core/strings/escape"
14
+
15
+ import type { OGCServedCollection } from "#engine"
16
+ import {
17
+ collectionVersionParameter,
18
+ type OGCCollection,
19
+ type OGCCollections,
20
+ OGC_COLLECTION_VERSION,
21
+ type OGCConformance,
22
+ type OGCLandingPage,
23
+ type OGCLink,
24
+ type OGCSearchFeature,
25
+ type OGCSearchResponse,
26
+ } from "#schema"
27
+
28
+ /**
29
+ * The OpenAPI 3.0 document the generator emits.
30
+ */
31
+ export type OpenAPI30Document = ReturnType<OpenAPIHono["getOpenAPIDocument"]>
32
+
33
+ const STYLE = `:root { color-scheme: light dark }
34
+ body { font: 16px/1.6 system-ui, -apple-system, sans-serif; max-width: 48rem; margin: 3rem auto; padding: 0 1.25rem }
35
+ h1 { font-size: 1.3rem; margin: 0 0 .5rem }
36
+ h2 { font-size: 1.1rem; margin: 1.5rem 0 .5rem }
37
+ code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace }
38
+ ul { padding-left: 1.2rem }
39
+ li { margin: .3rem 0 }
40
+ a { color: #2563eb }
41
+ .meta { opacity: .75; font-size: .9rem }`
42
+
43
+ function page(title: string, body: string): string {
44
+ return `<!doctype html>
45
+ <html lang="en">
46
+ <head>
47
+ <meta charset="utf-8">
48
+ <meta name="viewport" content="width=device-width, initial-scale=1">
49
+ <title>${escapeHTML(title)}</title>
50
+ <style>
51
+ ${STYLE}
52
+ </style>
53
+ </head>
54
+ <body>
55
+ ${body}
56
+ </body>
57
+ </html>
58
+ `
59
+ }
60
+
61
+ function linkItem(link: OGCLink): string {
62
+ const label = escapeHTML(link.title ?? link.href)
63
+ const meta = [link.rel, link.type].filter((part): part is string => typeof part === "string").map(escapeHTML)
64
+
65
+ return `<li><a href="${escapeHTML(link.href)}" rel="${escapeHTML(link.rel)}">${label}</a> <span class="meta">${meta.join(" &middot; ")}</span></li>`
66
+ }
67
+
68
+ function linkList(links: readonly OGCLink[]): string {
69
+ return `<ul>\n${links.map(linkItem).join("\n")}\n</ul>`
70
+ }
71
+
72
+ /**
73
+ * The landing page as HTML.
74
+ */
75
+ export function landingPageHTML(landing: OGCLandingPage): string {
76
+ return page(
77
+ landing.title,
78
+ `<h1>${escapeHTML(landing.title)}</h1>
79
+ <p>${escapeHTML(landing.description)}</p>
80
+ <h2>Links</h2>
81
+ ${linkList(landing.links)}`
82
+ )
83
+ }
84
+
85
+ /**
86
+ * The conformance declaration as HTML.
87
+ */
88
+ export function conformanceHTML(conformance: OGCConformance, links: readonly OGCLink[]): string {
89
+ const classes = conformance.conformsTo.map(
90
+ (uri) => `<li><a href="${escapeHTML(uri)}"><code>${escapeHTML(uri)}</code></a></li>`
91
+ )
92
+
93
+ return page(
94
+ "Conformance",
95
+ `<h1>Conformance</h1>
96
+ <p>The API conforms to these conformance classes.</p>
97
+ <ul>
98
+ ${classes.join("\n")}
99
+ </ul>
100
+ <h2>Links</h2>
101
+ ${linkList(links)}`
102
+ )
103
+ }
104
+
105
+ function collectionSection(collection: OGCCollection, heading: "h1" | "h2"): string {
106
+ return `<${heading}>${escapeHTML(collection.title)} <code>${escapeHTML(collection.id)}</code></${heading}>
107
+ <p>${escapeHTML(collection.description)}</p>
108
+ <p class="meta">Point features, version ${collection.version}</p>
109
+ ${linkList(collection.links)}`
110
+ }
111
+
112
+ /**
113
+ * The collections list as HTML.
114
+ */
115
+ export function collectionsHTML(body: OGCCollections): string {
116
+ return page(
117
+ "Collections",
118
+ `<h1>Collections</h1>
119
+ ${linkList(body.links)}
120
+ ${body.collections.map((collection) => collectionSection(collection, "h2")).join("\n")}`
121
+ )
122
+ }
123
+
124
+ /**
125
+ * One collection description as HTML.
126
+ */
127
+ export function collectionHTML(collection: OGCCollection): string {
128
+ return page(collection.title, collectionSection(collection, "h1"))
129
+ }
130
+
131
+ function searchFeatureItem(feature: OGCSearchFeature): string {
132
+ const [lon, lat] = feature.geometry.coordinates
133
+ const { display_name, score, score_unmeasured, collection_id, place_id, placetype } = feature.properties
134
+ const scoreText = score == null ? `score null (${score_unmeasured ?? "unmeasured"})` : `score ${score}`
135
+ const identity = [placetype, place_id].filter((part): part is string => typeof part === "string")
136
+
137
+ const meta = [collection_id, ...identity, `${lat}, ${lon}`, scoreText].map(escapeHTML).join(" &middot; ")
138
+
139
+ return `<li>${escapeHTML(display_name)} <span class="meta">${meta}</span></li>`
140
+ }
141
+
142
+ /**
143
+ * The search form, with the results of a search when `body` holds one.
144
+ *
145
+ * @param collections The collections a checkbox can restrict the search to.
146
+ */
147
+ export function searchHTML(
148
+ body: OGCSearchResponse | null,
149
+ links: readonly OGCLink[],
150
+ collections: readonly OGCServedCollection[],
151
+ q = ""
152
+ ): string {
153
+ const boxes = collections.map(
154
+ ({ id }) =>
155
+ `<label><input type="checkbox" name="${escapeHTML(collectionVersionParameter(id))}" value="${OGC_COLLECTION_VERSION}"> ${escapeHTML(id)}</label>`
156
+ )
157
+
158
+ const results = body
159
+ ? `<h2>Results</h2>
160
+ <p class="meta">${body.numberReturned} returned at ${escapeHTML(body.timeStamp)}</p>
161
+ <ol>
162
+ ${body.features.map(searchFeatureItem).join("\n")}
163
+ </ol>`
164
+ : ""
165
+
166
+ return page(
167
+ "Search",
168
+ `<h1>Search</h1>
169
+ <p>Forward geocoding. Leave every collection unchecked to search them all.</p>
170
+ <form method="get" action="search">
171
+ <input type="hidden" name="f" value="html">
172
+ <p><input type="search" name="q" value="${escapeHTML(q)}" required size="48" aria-label="Address or place"> <button type="submit">Search</button></p>
173
+ <p>${boxes.join(" ")}</p>
174
+ </form>
175
+ ${results}
176
+ <h2>Links</h2>
177
+ ${linkList(links)}`
178
+ )
179
+ }
180
+
181
+ interface OperationLike {
182
+ summary?: string
183
+ description?: string
184
+ parameters?: Array<{ name?: string; in?: string; description?: string; required?: boolean }>
185
+ responses?: Record<string, { description?: string; content?: Record<string, unknown> }>
186
+ }
187
+
188
+ function operationHTML(method: string, path: string, operation: OperationLike): string {
189
+ const parameters = (operation.parameters ?? []).map((parameter) => {
190
+ const required = parameter.required ? " (required)" : ""
191
+ const description = parameter.description ? `: ${escapeHTML(parameter.description)}` : ""
192
+
193
+ return `<li><code>${escapeHTML(parameter.name ?? "")}</code> in ${escapeHTML(parameter.in ?? "")}${required}${description}</li>`
194
+ })
195
+
196
+ const responses = Object.entries(operation.responses ?? {}).map(([status, response]) => {
197
+ const mediaTypes = Object.keys(response.content ?? {}).map((type) => `<code>${escapeHTML(type)}</code>`)
198
+
199
+ return `<li><code>${escapeHTML(status)}</code> ${escapeHTML(response.description ?? "")} ${mediaTypes.join(", ")}</li>`
200
+ })
201
+
202
+ return `<h2><code>${escapeHTML(method.toUpperCase())} ${escapeHTML(path)}</code></h2>
203
+ <p>${escapeHTML(operation.summary ?? "")}</p>
204
+ ${operation.description ? `<p>${escapeHTML(operation.description)}</p>` : ""}
205
+ <p>Parameters:</p>
206
+ <ul>
207
+ ${parameters.join("\n")}
208
+ </ul>
209
+ <p>Responses:</p>
210
+ <ul>
211
+ ${responses.join("\n")}
212
+ </ul>`
213
+ }
214
+
215
+ /**
216
+ * The API definition as HTML: each operation with its parameters and responses,
217
+ * read from the OpenAPI 3.0 document the JSON encoding serves.
218
+ */
219
+ export function apiDefinitionHTML(document: OpenAPI30Document, links: readonly OGCLink[]): string {
220
+ const operations: string[] = []
221
+
222
+ for (const [path, item] of Object.entries(document.paths ?? {})) {
223
+ for (const [method, operation] of Object.entries(item as Record<string, OperationLike>)) {
224
+ operations.push(operationHTML(method, path, operation))
225
+ }
226
+ }
227
+
228
+ return page(
229
+ `${document.info.title} API definition`,
230
+ `<h1>${escapeHTML(document.info.title)} API definition</h1>
231
+ <p>${escapeHTML(document.info.description ?? "")}</p>
232
+ <p class="meta">OpenAPI ${escapeHTML(document.openapi)}, version ${escapeHTML(document.info.version)}</p>
233
+ ${linkList(links)}
234
+ ${operations.join("\n")}`
235
+ )
236
+ }
package/lib/index.ts ADDED
@@ -0,0 +1,20 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * `@mailwoman/ogc` serves Mailwoman through the OGC API family of standards.
6
+ *
7
+ * It serves the OGC API Common Part 1 resources an OGC client reads first
8
+ * (the landing page, the conformance declaration and the API definition), the OGC API
9
+ * Common Part 2 collections, and forward geocoding at `/search` in PDOK's form.
10
+ * The conformance declaration names only the classes these routes implement.
11
+ */
12
+
13
+ export * from "#app"
14
+ export * from "#collections"
15
+ export * from "#engine"
16
+ export * from "#format"
17
+ export * from "#html"
18
+ export * from "#projection"
19
+ export * from "#routes"
20
+ export * from "#schema"
@@ -0,0 +1,206 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * The projection from a geocode result to `/search` matches.
6
+ *
7
+ * The result's coordinate is the first match, in the collection its tier names.
8
+ * The places the resolver weighed for the same part of the input follow,
9
+ * each in the collection its placetype names.
10
+ */
11
+
12
+ import { formatAddress } from "@mailwoman/codex/address/format"
13
+ import type { ComponentDict } from "@mailwoman/codex/address/render"
14
+ import { matchCountry } from "@mailwoman/codex/country"
15
+ import type { GeocodeCandidate, GeocodeResult } from "@mailwoman/core/geocode"
16
+ import { type Ancestor, ScoreUnmeasuredReason, wofIDFromPlaceID } from "@mailwoman/core/resolver"
17
+
18
+ import { collectionOfPlacetype, collectionOfTier, OGCCollectionID } from "#collections"
19
+ import type { OGCSearchHit } from "#engine"
20
+
21
+ function hierarchyName(result: GeocodeResult, tag: string): string | null {
22
+ return result.hierarchy.find((entry) => entry.tag === tag)?.name ?? null
23
+ }
24
+
25
+ /**
26
+ * The resolved names, most specific first, with a repeated name dropped
27
+ * and the country appended when the hierarchy doesn't name it.
28
+ */
29
+ function hierarchyLabel(result: GeocodeResult): string {
30
+ const names: string[] = []
31
+
32
+ for (const { name } of result.hierarchy) {
33
+ if (name && !names.includes(name)) {
34
+ names.push(name)
35
+ }
36
+ }
37
+
38
+ const country = matchCountry(result.countryCode)?.canonical
39
+
40
+ if (names.length && country && !names.includes(country)) {
41
+ names.push(country)
42
+ }
43
+
44
+ return names.join(", ")
45
+ }
46
+
47
+ /**
48
+ * The one-line address of a house-grade or street-grade answer, in the country's own order.
49
+ */
50
+ function addressLabel(result: GeocodeResult, withHouseNumber: boolean): string {
51
+ const country = matchCountry(result.countryCode)
52
+
53
+ const postcode = result.postcode ?? result.rooftop?.postcode ?? null
54
+ const locality = hierarchyName(result, "locality") ?? result.locality
55
+ const region = hierarchyName(result, "region") ?? result.region
56
+
57
+ const components: ComponentDict = {
58
+ ...(withHouseNumber && result.house_number ? { house_number: result.house_number } : {}),
59
+ ...(result.street ? { street: result.street } : {}),
60
+ ...(result.unit && withHouseNumber ? { unit: result.unit } : {}),
61
+ ...(postcode ? { postcode } : {}),
62
+ ...(locality ? { locality } : {}),
63
+ ...(region ? { region } : {}),
64
+ ...(country?.canonical ? { country: country.canonical } : {}),
65
+ }
66
+
67
+ const formatted = country ? formatAddress(components, country.iso2, { singleLine: true, withRegion: true }) : ""
68
+
69
+ // A country with no recorded layout renders an empty string, so the parts join in the order they were read.
70
+ return formatted || Object.values(components).join(", ")
71
+ }
72
+
73
+ /**
74
+ * The candidate the answer's coordinate came from, when the coordinate is a gazetteer place's.
75
+ */
76
+ function answeringCandidate(result: GeocodeResult): GeocodeCandidate | null {
77
+ if (result.resolution_tier !== "admin" && result.resolution_tier !== "postcode") return null
78
+
79
+ return result.candidates.find((candidate) => candidate.lat === result.lat && candidate.lon === result.lon) ?? null
80
+ }
81
+
82
+ function scoreOf(candidate: GeocodeCandidate | null): Pick<OGCSearchHit, "score" | "scoreUnmeasured"> {
83
+ if (candidate && typeof candidate.score === "number") return { score: candidate.score }
84
+
85
+ return { score: null, scoreUnmeasured: candidate?.scoreUnmeasured ?? ScoreUnmeasuredReason.Unrecorded }
86
+ }
87
+
88
+ /**
89
+ * Reads a gazetteer place's ancestors by WOF id, nearest first, as `ResolverBackend.ancestors` does.
90
+ */
91
+ export type AncestorsOf = (wofID: number) => readonly Ancestor[]
92
+
93
+ /**
94
+ * A gazetteer place's label: its name, the ancestors the gazetteer records between it
95
+ * and its country, most specific first, and the country.
96
+ *
97
+ * A name repeated by an ancestor appears once.
98
+ * Without a WOF place ID or a recorded ancestry the label is the name and the country.
99
+ */
100
+ function candidateLabel(candidate: GeocodeCandidate, ancestorsOf: AncestorsOf | undefined): string {
101
+ const names = [candidate.name]
102
+ const wofID = wofIDFromPlaceID(candidate.placeID)
103
+
104
+ if (ancestorsOf && wofID != null) {
105
+ for (const ancestor of ancestorsOf(wofID)) {
106
+ if (ancestor.placetype !== "country" && ancestor.name && !names.includes(ancestor.name)) {
107
+ names.push(ancestor.name)
108
+ }
109
+ }
110
+ }
111
+
112
+ const country = matchCountry(candidate.countryCode)?.canonical
113
+
114
+ if (country && !names.includes(country)) {
115
+ names.push(country)
116
+ }
117
+
118
+ return names.join(", ")
119
+ }
120
+
121
+ /**
122
+ * The gazetteer identity of a place match, so two places that share a label stay apart.
123
+ */
124
+ function placeIdentity(candidate: GeocodeCandidate): Pick<OGCSearchHit, "placeID" | "placetype"> {
125
+ return { ...(candidate.placeID ? { placeID: candidate.placeID } : {}), placetype: candidate.placetype }
126
+ }
127
+
128
+ /**
129
+ * The `/search` matches for one geocode result, best first.
130
+ *
131
+ * The answer's own coordinate comes first.
132
+ * Its score is the resolver's score for the gazetteer place it came from.
133
+ *
134
+ * An answer placed by an address point, an interpolation or a street centroid
135
+ * has no measured score, so its score is null.
136
+ *
137
+ * The places the resolver weighed for the same span as its first candidate follow, each with its own score.
138
+ * The result lists at most 10 places for a span, so a call reads at most 10 ancestries.
139
+ *
140
+ * @param ancestorsOf The gazetteer's ancestry reader.
141
+ * The label of each place lists the region and county it returns.
142
+ * Absent, a place's label is its name and its country.
143
+ * @returns An empty array when the result has no coordinate.
144
+ */
145
+ export function geocodeSearchHits(result: GeocodeResult, ancestorsOf?: AncestorsOf): OGCSearchHit[] {
146
+ const hits: OGCSearchHit[] = []
147
+ const answering = answeringCandidate(result)
148
+ const collectionID = collectionOfTier(result.resolution_tier)
149
+
150
+ if (result.lat != null && result.lon != null && collectionID) {
151
+ const houseGrade = collectionID === OGCCollectionID.Addresses
152
+
153
+ if (houseGrade || collectionID === OGCCollectionID.Streets) {
154
+ hits.push({
155
+ collectionID,
156
+ lon: result.lon,
157
+ lat: result.lat,
158
+ displayName: addressLabel(result, houseGrade),
159
+ ...scoreOf(answering),
160
+ })
161
+ } else {
162
+ hits.push({
163
+ collectionID,
164
+ lon: result.lon,
165
+ lat: result.lat,
166
+ displayName: answering ? candidateLabel(answering, ancestorsOf) : hierarchyLabel(result) || result.input.trim(),
167
+ ...scoreOf(answering),
168
+ ...(answering ? placeIdentity(answering) : {}),
169
+ })
170
+ }
171
+ }
172
+
173
+ const [first] = result.candidates
174
+
175
+ if (!first) return hits
176
+
177
+ // A place appears once, so the answer's own place and a place listed twice are skipped.
178
+ // Two places at one coordinate stay two matches, because the place ID tells them apart.
179
+ const seen = new Set<string>()
180
+ const placeKey = (candidate: GeocodeCandidate) => candidate.placeID ?? `${candidate.lon},${candidate.lat}`
181
+
182
+ if (answering) {
183
+ seen.add(placeKey(answering))
184
+ }
185
+
186
+ for (const candidate of result.candidates) {
187
+ if (candidate.tag !== first.tag || candidate.value !== first.value) continue
188
+
189
+ const key = placeKey(candidate)
190
+
191
+ if (seen.has(key)) continue
192
+
193
+ seen.add(key)
194
+
195
+ hits.push({
196
+ collectionID: collectionOfPlacetype(candidate.placetype),
197
+ lon: candidate.lon,
198
+ lat: candidate.lat,
199
+ displayName: candidateLabel(candidate, ancestorsOf),
200
+ ...scoreOf(candidate),
201
+ ...placeIdentity(candidate),
202
+ })
203
+ }
204
+
205
+ return hits
206
+ }