@mailwoman/ogc 11.2.0 → 11.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 (73) hide show
  1. package/README.md +167 -28
  2. package/cli/geocoder.ts +50 -0
  3. package/cli/main.ts +303 -49
  4. package/lib/app.ts +9 -1
  5. package/lib/bbox.ts +69 -0
  6. package/lib/collections.ts +63 -9
  7. package/lib/engine.ts +72 -0
  8. package/lib/html.ts +64 -2
  9. package/lib/index.ts +4 -0
  10. package/lib/items.ts +169 -0
  11. package/lib/projection.ts +28 -8
  12. package/lib/provenance.ts +86 -0
  13. package/lib/refusal.ts +34 -0
  14. package/lib/routes.ts +326 -61
  15. package/lib/schema.ts +164 -3
  16. package/out/app.d.ts +8 -0
  17. package/out/app.d.ts.map +1 -1
  18. package/out/app.js +1 -1
  19. package/out/app.js.map +1 -1
  20. package/out/bbox.d.ts +23 -0
  21. package/out/bbox.d.ts.map +1 -0
  22. package/out/bbox.js +54 -0
  23. package/out/bbox.js.map +1 -0
  24. package/out/cli/geocoder.d.ts +24 -0
  25. package/out/cli/geocoder.d.ts.map +1 -0
  26. package/out/cli/geocoder.js +28 -0
  27. package/out/cli/geocoder.js.map +1 -0
  28. package/out/cli/main.js +225 -46
  29. package/out/cli/main.js.map +1 -1
  30. package/out/collections.d.ts +31 -4
  31. package/out/collections.d.ts.map +1 -1
  32. package/out/collections.js +32 -3
  33. package/out/collections.js.map +1 -1
  34. package/out/engine.d.ts +68 -0
  35. package/out/engine.d.ts.map +1 -1
  36. package/out/html.d.ts +11 -1
  37. package/out/html.d.ts.map +1 -1
  38. package/out/html.js +49 -2
  39. package/out/html.js.map +1 -1
  40. package/out/index.d.ts +4 -0
  41. package/out/index.d.ts.map +1 -1
  42. package/out/index.js +4 -0
  43. package/out/index.js.map +1 -1
  44. package/out/items.d.ts +38 -0
  45. package/out/items.d.ts.map +1 -0
  46. package/out/items.js +136 -0
  47. package/out/items.js.map +1 -0
  48. package/out/projection.d.ts +15 -1
  49. package/out/projection.d.ts.map +1 -1
  50. package/out/projection.js +21 -8
  51. package/out/projection.js.map +1 -1
  52. package/out/provenance.d.ts +41 -0
  53. package/out/provenance.d.ts.map +1 -0
  54. package/out/provenance.js +60 -0
  55. package/out/provenance.js.map +1 -0
  56. package/out/refusal.d.ts +18 -0
  57. package/out/refusal.d.ts.map +1 -0
  58. package/out/refusal.js +30 -0
  59. package/out/refusal.js.map +1 -0
  60. package/out/routes.d.ts +24 -22
  61. package/out/routes.d.ts.map +1 -1
  62. package/out/routes.js +246 -51
  63. package/out/routes.js.map +1 -1
  64. package/out/schema.d.ts +157 -2
  65. package/out/schema.d.ts.map +1 -1
  66. package/out/schema.js +140 -3
  67. package/out/schema.js.map +1 -1
  68. package/out/tools/ets.run.d.ts +2 -0
  69. package/out/tools/ets.run.d.ts.map +1 -0
  70. package/out/tools/ets.run.js +187 -0
  71. package/out/tools/ets.run.js.map +1 -0
  72. package/package.json +32 -10
  73. package/tools/ets.run.ts +258 -0
package/lib/engine.ts CHANGED
@@ -9,8 +9,62 @@
9
9
  * collections its opened layers serve.
10
10
  */
11
11
 
12
+ import type { LayerTerms } from "@mailwoman/core/layers/provenance"
13
+
14
+ import type { OGCBBox } from "#bbox"
12
15
  import type { OGCCollectionID } from "#collections"
13
16
 
17
+ /**
18
+ * One gazetteer place a collection serves as an item.
19
+ */
20
+ export interface OGCItem {
21
+ /**
22
+ * The place's WOF id, the number in its place ID `wof:<id>`.
23
+ */
24
+ wofID: number
25
+ name: string
26
+ placetype: string
27
+ /**
28
+ * The ISO 3166-1 alpha-2 code the gazetteer records, or null when it records none.
29
+ */
30
+ countryCode: string | null
31
+ lon: number
32
+ lat: number
33
+ /**
34
+ * The label `/search` gives the same place: its name, ancestors and country.
35
+ */
36
+ displayName: string
37
+ }
38
+
39
+ /**
40
+ * One page of a collection's items.
41
+ */
42
+ export interface OGCItemPageRequest {
43
+ /**
44
+ * Keep only places whose point lies inside the box, or every place when null.
45
+ */
46
+ bbox: OGCBBox | null
47
+ /**
48
+ * Start after the place with this WOF id, or at the first place when null.
49
+ */
50
+ after: number | null
51
+ limit: number
52
+ }
53
+
54
+ /**
55
+ * The reader behind a collection's `/items` routes.
56
+ */
57
+ export interface OGCItemSource {
58
+ /**
59
+ * The places the request selects, in ascending WOF id order, at most `limit` of them.
60
+ */
61
+ page(request: OGCItemPageRequest): Promise<OGCItem[]>
62
+ /**
63
+ * The place with this WOF id, or null when the collection holds no such place.
64
+ */
65
+ item(wofID: number): Promise<OGCItem | null>
66
+ }
67
+
14
68
  /**
15
69
  * A collection the engine serves, and the regions its layers cover.
16
70
  */
@@ -22,6 +76,24 @@ export interface OGCServedCollection {
22
76
  * Null when the collection isn't divided by region, as for the worldwide gazetteer.
23
77
  */
24
78
  regions: readonly string[] | null
79
+ /**
80
+ * The reader that serves the collection's items, absent for a collection without `/items`.
81
+ */
82
+ items?: OGCItemSource
83
+ /**
84
+ * The manifests of the layers behind the collection.
85
+ * Its license and source links come from them.
86
+ *
87
+ * An empty array means no layer backs the collection.
88
+ * Absent means the engine read no manifest for it, and the description states that.
89
+ */
90
+ layers?: readonly LayerTerms[]
91
+ /**
92
+ * The regions with a layer database whose `layer_manifest` the engine couldn't read, absent or unreadable.
93
+ *
94
+ * Such a layer contributes no link, and the description states the count.
95
+ */
96
+ unreadRegions?: number
25
97
  }
26
98
 
27
99
  /**
package/lib/html.ts CHANGED
@@ -19,6 +19,8 @@ import {
19
19
  type OGCCollections,
20
20
  OGC_COLLECTION_VERSION,
21
21
  type OGCConformance,
22
+ type OGCItemFeature,
23
+ type OGCItemsResponse,
22
24
  type OGCLandingPage,
23
25
  type OGCLink,
24
26
  type OGCSearchFeature,
@@ -130,13 +132,73 @@ export function collectionHTML(collection: OGCCollection): string {
130
132
 
131
133
  function searchFeatureItem(feature: OGCSearchFeature): string {
132
134
  const [lon, lat] = feature.geometry.coordinates
133
- const { display_name, score, score_unmeasured, collection_id, place_id, placetype } = feature.properties
135
+ const { display_name, score, score_unmeasured, collection_id, place_id, placetype, href } = feature.properties
134
136
  const scoreText = score == null ? `score null (${score_unmeasured ?? "unmeasured"})` : `score ${score}`
135
137
  const identity = [placetype, place_id].filter((part): part is string => typeof part === "string")
136
138
 
137
139
  const meta = [collection_id, ...identity, `${lat}, ${lon}`, scoreText].map(escapeHTML).join(" &middot; ")
140
+ const label = href ? `<a href="${escapeHTML(href)}">${escapeHTML(display_name)}</a>` : escapeHTML(display_name)
138
141
 
139
- return `<li>${escapeHTML(display_name)} <span class="meta">${meta}</span></li>`
142
+ return `<li>${label} <span class="meta">${meta}</span></li>`
143
+ }
144
+
145
+ /**
146
+ * The properties of one item as a definition list, the same members its GeoJSON form holds.
147
+ */
148
+ function itemDetails(feature: OGCItemFeature): string {
149
+ const [lon, lat] = feature.geometry.coordinates
150
+ const { name, placetype, country_code, display_name } = feature.properties
151
+
152
+ const rows: Array<[string, string]> = [
153
+ ["id", feature.id],
154
+ ["name", name],
155
+ ["placetype", placetype],
156
+ ["country_code", country_code ?? "null"],
157
+ ["display_name", display_name],
158
+ ["coordinates", `${lon}, ${lat}`],
159
+ ]
160
+
161
+ return `<dl>\n${rows.map(([term, value]) => `<dt><code>${term}</code></dt><dd>${escapeHTML(value)}</dd>`).join("\n")}\n</dl>`
162
+ }
163
+
164
+ /**
165
+ * One page of a collection's items as HTML: each item linked to its own page, then the page's links.
166
+ *
167
+ * @param collectionID The collection the items belong to, for each item's link.
168
+ */
169
+ export function itemsHTML(body: OGCItemsResponse, title: string, collectionID: string): string {
170
+ const items = body.features.map((feature) => {
171
+ const [lon, lat] = feature.geometry.coordinates
172
+ const href = `${encodeURIComponent(collectionID)}/items/${encodeURIComponent(feature.id)}?f=html`
173
+ const meta = [feature.id, feature.properties.placetype, `${lat}, ${lon}`].map(escapeHTML).join(" &middot; ")
174
+
175
+ return `<li><a href="../${escapeHTML(href)}">${escapeHTML(feature.properties.display_name)}</a> <span class="meta">${meta}</span></li>`
176
+ })
177
+
178
+ return page(
179
+ `${title} items`,
180
+ `<h1>${escapeHTML(title)} items</h1>
181
+ <p class="meta">${body.numberReturned} returned at ${escapeHTML(body.timeStamp)}</p>
182
+ <ol>
183
+ ${items.join("\n")}
184
+ </ol>
185
+ <h2>Links</h2>
186
+ ${linkList(body.links)}`
187
+ )
188
+ }
189
+
190
+ /**
191
+ * One item as HTML.
192
+ */
193
+ export function itemHTML(feature: OGCItemFeature, collectionTitle: string): string {
194
+ return page(
195
+ feature.properties.name,
196
+ `<h1>${escapeHTML(feature.properties.name)}</h1>
197
+ <p class="meta">An item of ${escapeHTML(collectionTitle)}</p>
198
+ ${itemDetails(feature)}
199
+ <h2>Links</h2>
200
+ ${linkList(feature.links ?? [])}`
201
+ )
140
202
  }
141
203
 
142
204
  /**
package/lib/index.ts CHANGED
@@ -11,10 +11,14 @@
11
11
  */
12
12
 
13
13
  export * from "#app"
14
+ export * from "#bbox"
14
15
  export * from "#collections"
15
16
  export * from "#engine"
16
17
  export * from "#format"
17
18
  export * from "#html"
19
+ export * from "#items"
18
20
  export * from "#projection"
21
+ export * from "#provenance"
22
+ export * from "#refusal"
19
23
  export * from "#routes"
20
24
  export * from "#schema"
package/lib/items.ts ADDED
@@ -0,0 +1,169 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * The query parsing and feature encoding of the OGC API Features Part 1 items resources,
6
+ * `/collections/{collectionId}/items` and `/collections/{collectionId}/items/{featureId}`.
7
+ *
8
+ * A page is read in ascending WOF id order and continues after the last id it returned,
9
+ * so a deep page costs what the first page costs and no item repeats or goes missing between pages.
10
+ */
11
+
12
+ import { isRFC3339DateTime } from "@mailwoman/core/utils"
13
+ import type { BrowsedPlace, WOFPlaceBrowser } from "@mailwoman/resolver-wof-sqlite/lookup/browse"
14
+
15
+ import { parseBBox } from "#bbox"
16
+ import type { OGCItem, OGCItemPageRequest, OGCItemSource } from "#engine"
17
+ import { type AncestorsOf, placeLabel } from "#projection"
18
+ import { type OGCItemFeature, OGC_ITEMS_DEFAULT_LIMIT, OGC_ITEMS_MAX_LIMIT } from "#schema"
19
+
20
+ /**
21
+ * The open end of a `datetime` interval: `..`, or an empty string.
22
+ */
23
+ function isOpenEnd(value: string): boolean {
24
+ return value === ".." || value === ""
25
+ }
26
+
27
+ /**
28
+ * Whether `raw` is a `datetime` value as OGC API Features Part 1, Requirement 26 D defines it:
29
+ * an RFC 3339 `date-time`, or an interval of two with at most one open end.
30
+ */
31
+ export function isFeaturesDateTime(raw: string): boolean {
32
+ const parts = raw.split("/")
33
+
34
+ if (parts.length === 1) return isRFC3339DateTime(raw)
35
+
36
+ if (parts.length !== 2) return false
37
+
38
+ const [start, end] = parts as [string, string]
39
+
40
+ if (isOpenEnd(start) && isOpenEnd(end)) return false
41
+
42
+ return (isOpenEnd(start) || isRFC3339DateTime(start)) && (isOpenEnd(end) || isRFC3339DateTime(end))
43
+ }
44
+
45
+ /**
46
+ * Parse the `after` cursor a `next` link sets: a WOF id.
47
+ */
48
+ function parseCursor(raw: string): number | null {
49
+ if (!/^\d{1,16}$/.test(raw)) return null
50
+
51
+ const value = Number(raw)
52
+
53
+ return Number.isSafeInteger(value) ? value : null
54
+ }
55
+
56
+ /**
57
+ * Validate a `/collections/{collectionId}/items` query the schema admitted.
58
+ *
59
+ * A `limit` above {@link OGC_ITEMS_MAX_LIMIT} is served as the maximum, as Requirement 22 C asks.
60
+ * A valid `datetime` selects every place, because no place has a temporal geometry (Requirement 26 C).
61
+ *
62
+ * @returns The page request, or a message that identifies the invalid parameter.
63
+ */
64
+ export function parseItemsQuery(query: Readonly<Record<string, string | undefined>>): OGCItemPageRequest | string {
65
+ let limit = OGC_ITEMS_DEFAULT_LIMIT
66
+ const rawLimit = query["limit"]
67
+
68
+ if (rawLimit != null) {
69
+ limit = /^\d+$/.test(rawLimit) ? Number(rawLimit) : Number.NaN
70
+
71
+ if (!(limit >= 1)) return "limit: a positive integer is required"
72
+
73
+ limit = Math.min(limit, OGC_ITEMS_MAX_LIMIT)
74
+ }
75
+
76
+ let bbox: OGCItemPageRequest["bbox"] = null
77
+ const rawBBox = query["bbox"]
78
+
79
+ if (rawBBox != null) {
80
+ const parsed = parseBBox(rawBBox, { withHeight: true })
81
+
82
+ if (typeof parsed === "string") return parsed
83
+
84
+ bbox = parsed
85
+ }
86
+
87
+ const datetime = query["datetime"]
88
+
89
+ if (datetime != null && !isFeaturesDateTime(datetime)) {
90
+ return "datetime: an RFC 3339 date-time, or an interval of two separated by / with .. for an open end, is required"
91
+ }
92
+
93
+ let after: number | null = null
94
+ const rawAfter = query["after"]
95
+
96
+ if (rawAfter != null) {
97
+ after = parseCursor(rawAfter)
98
+
99
+ if (after == null) return "after: the WOF id a next link carries is required"
100
+ }
101
+
102
+ return { bbox, after, limit }
103
+ }
104
+
105
+ /**
106
+ * The reader {@link placeItemSource} pages through, such as a `WOFPlaceBrowser` over the admin gazetteer.
107
+ */
108
+ export type PlaceBrowser = Pick<WOFPlaceBrowser, "page" | "place">
109
+
110
+ /**
111
+ * The item source of a collection of gazetteer places, read through `browser`.
112
+ *
113
+ * @param ancestorsOf The ancestry reader `/search` labels its places with,
114
+ * so an item's `display_name` matches the label `/search` gives the same place.
115
+ */
116
+ export function placeItemSource(browser: PlaceBrowser, ancestorsOf: AncestorsOf | undefined): OGCItemSource {
117
+ const toItem = (place: BrowsedPlace): OGCItem => {
118
+ const countryCode = place.country || null
119
+ const name = place.name ?? ""
120
+
121
+ return {
122
+ wofID: place.id,
123
+ name,
124
+ placetype: place.placetype ?? "",
125
+ countryCode,
126
+ lon: place.longitude,
127
+ lat: place.latitude,
128
+ displayName: placeLabel({ name, placeID: `wof:${place.id}`, countryCode }, ancestorsOf),
129
+ }
130
+ }
131
+
132
+ return {
133
+ async page({ bbox, after, limit }) {
134
+ const box = bbox ? { minLon: bbox[0], minLat: bbox[1], maxLon: bbox[2], maxLat: bbox[3] } : null
135
+
136
+ return (await browser.page({ box, after, limit })).map(toItem)
137
+ },
138
+ async item(wofID) {
139
+ const place = await browser.place(wofID)
140
+
141
+ return place ? toItem(place) : null
142
+ },
143
+ }
144
+ }
145
+
146
+ /**
147
+ * The gazetteer place ID of an item, the `id` of its feature and the `place_id` `/search` reports.
148
+ */
149
+ export function itemPlaceID(item: Pick<OGCItem, "wofID">): string {
150
+ return `wof:${item.wofID}`
151
+ }
152
+
153
+ /**
154
+ * One item as a GeoJSON feature, with the links the caller supplies.
155
+ */
156
+ export function itemFeature(item: OGCItem, links?: OGCItemFeature["links"]): OGCItemFeature {
157
+ return {
158
+ type: "Feature",
159
+ id: itemPlaceID(item),
160
+ geometry: { type: "Point", coordinates: [item.lon, item.lat] },
161
+ properties: {
162
+ name: item.name,
163
+ placetype: item.placetype,
164
+ country_code: item.countryCode,
165
+ display_name: item.displayName,
166
+ },
167
+ ...(links ? { links } : {}),
168
+ }
169
+ }
package/lib/projection.ts CHANGED
@@ -11,13 +11,26 @@
11
11
 
12
12
  import { formatAddress } from "@mailwoman/codex/address/format"
13
13
  import type { ComponentDict } from "@mailwoman/codex/address/render"
14
- import { matchCountry } from "@mailwoman/codex/country"
14
+ import { ISO2_TO_NAME } from "@mailwoman/codex/country"
15
15
  import type { GeocodeCandidate, GeocodeResult } from "@mailwoman/core/geocode"
16
16
  import { type Ancestor, ScoreUnmeasuredReason, wofIDFromPlaceID } from "@mailwoman/core/resolver"
17
17
 
18
18
  import { collectionOfPlacetype, collectionOfTier, OGCCollectionID } from "#collections"
19
19
  import type { OGCSearchHit } from "#engine"
20
20
 
21
+ /**
22
+ * The country a record's ISO 3166-1 alpha-2 code names, read from the code table.
23
+ *
24
+ * `matchCountry` reads free-form address text and resolves only some two-letter codes,
25
+ * such as `FR` but not `EE`, so a recorded code is looked up directly.
26
+ */
27
+ function countryOfCode(code: string | null): { iso2: string; name: string } | null {
28
+ const iso2 = code?.trim().toUpperCase()
29
+ const name = iso2 ? ISO2_TO_NAME.get(iso2) : undefined
30
+
31
+ return iso2 && name ? { iso2, name } : null
32
+ }
33
+
21
34
  function hierarchyName(result: GeocodeResult, tag: string): string | null {
22
35
  return result.hierarchy.find((entry) => entry.tag === tag)?.name ?? null
23
36
  }
@@ -35,7 +48,7 @@ function hierarchyLabel(result: GeocodeResult): string {
35
48
  }
36
49
  }
37
50
 
38
- const country = matchCountry(result.countryCode)?.canonical
51
+ const country = countryOfCode(result.countryCode)?.name
39
52
 
40
53
  if (names.length && country && !names.includes(country)) {
41
54
  names.push(country)
@@ -48,7 +61,7 @@ function hierarchyLabel(result: GeocodeResult): string {
48
61
  * The one-line address of a house-grade or street-grade answer, in the country's own order.
49
62
  */
50
63
  function addressLabel(result: GeocodeResult, withHouseNumber: boolean): string {
51
- const country = matchCountry(result.countryCode)
64
+ const country = countryOfCode(result.countryCode)
52
65
 
53
66
  const postcode = result.postcode ?? result.rooftop?.postcode ?? null
54
67
  const locality = hierarchyName(result, "locality") ?? result.locality
@@ -61,7 +74,7 @@ function addressLabel(result: GeocodeResult, withHouseNumber: boolean): string {
61
74
  ...(postcode ? { postcode } : {}),
62
75
  ...(locality ? { locality } : {}),
63
76
  ...(region ? { region } : {}),
64
- ...(country?.canonical ? { country: country.canonical } : {}),
77
+ ...(country ? { country: country.name } : {}),
65
78
  }
66
79
 
67
80
  const formatted = country ? formatAddress(components, country.iso2, { singleLine: true, withRegion: true }) : ""
@@ -90,14 +103,21 @@ function scoreOf(candidate: GeocodeCandidate | null): Pick<OGCSearchHit, "score"
90
103
  */
91
104
  export type AncestorsOf = (wofID: number) => readonly Ancestor[]
92
105
 
106
+ /**
107
+ * The fields of a gazetteer place its label reads.
108
+ */
109
+ export type LabeledPlace = Pick<GeocodeCandidate, "name" | "placeID" | "countryCode">
110
+
93
111
  /**
94
112
  * A gazetteer place's label: its name, the ancestors the gazetteer records between it
95
113
  * and its country, most specific first, and the country.
96
114
  *
115
+ * `/search` labels its place matches with it, and `/collections/{collectionId}/items` its features.
97
116
  * A name repeated by an ancestor appears once.
117
+ *
98
118
  * Without a WOF place ID or a recorded ancestry the label is the name and the country.
99
119
  */
100
- function candidateLabel(candidate: GeocodeCandidate, ancestorsOf: AncestorsOf | undefined): string {
120
+ export function placeLabel(candidate: LabeledPlace, ancestorsOf: AncestorsOf | undefined): string {
101
121
  const names = [candidate.name]
102
122
  const wofID = wofIDFromPlaceID(candidate.placeID)
103
123
 
@@ -109,7 +129,7 @@ function candidateLabel(candidate: GeocodeCandidate, ancestorsOf: AncestorsOf |
109
129
  }
110
130
  }
111
131
 
112
- const country = matchCountry(candidate.countryCode)?.canonical
132
+ const country = countryOfCode(candidate.countryCode)?.name
113
133
 
114
134
  if (country && !names.includes(country)) {
115
135
  names.push(country)
@@ -163,7 +183,7 @@ export function geocodeSearchHits(result: GeocodeResult, ancestorsOf?: Ancestors
163
183
  collectionID,
164
184
  lon: result.lon,
165
185
  lat: result.lat,
166
- displayName: answering ? candidateLabel(answering, ancestorsOf) : hierarchyLabel(result) || result.input.trim(),
186
+ displayName: answering ? placeLabel(answering, ancestorsOf) : hierarchyLabel(result) || result.input.trim(),
167
187
  ...scoreOf(answering),
168
188
  ...(answering ? placeIdentity(answering) : {}),
169
189
  })
@@ -196,7 +216,7 @@ export function geocodeSearchHits(result: GeocodeResult, ancestorsOf?: Ancestors
196
216
  collectionID: collectionOfPlacetype(candidate.placetype),
197
217
  lon: candidate.lon,
198
218
  lat: candidate.lat,
199
- displayName: candidateLabel(candidate, ancestorsOf),
219
+ displayName: placeLabel(candidate, ancestorsOf),
200
220
  ...scoreOf(candidate),
201
221
  ...placeIdentity(candidate),
202
222
  })
@@ -0,0 +1,86 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * The license and source links of a collection, read from the manifests of its layers.
6
+ *
7
+ * {@linkcode resolveLayerTerms} reads the manifests.
8
+ * Its license links become `license` links (RFC 4946: "Refers to a license
9
+ * associated with this context"), and its source links become `via` links
10
+ * (the RFC 4287 relation for the source of the information in the link's context).
11
+ *
12
+ * A license that requires credit adds an `attribution`, the member OGC API Common Part
13
+ * 2 gives a collection for "a short attribution for data being visualized".
14
+ *
15
+ * A collection lists each link once, whatever the count of regional layers that record it.
16
+ * A manifest field without a value, and a value without a known URL,
17
+ * adds one sentence to the description rather than a link.
18
+ */
19
+
20
+ import { type LayerTerms, ProvenanceLinkKind, resolveLayerTerms } from "@mailwoman/core/layers/provenance"
21
+ import { gazetteerSourceLocation } from "@mailwoman/resolver-wof-sqlite/build/sources"
22
+
23
+ import type { OGCServedCollection } from "#engine"
24
+ import { OGCLinkRelation, OGCMediaType, type OGCLink } from "#schema"
25
+
26
+ /**
27
+ * The links, attribution and description sentences a collection's layers contribute.
28
+ */
29
+ export interface OGCCollectionTerms {
30
+ links: OGCLink[]
31
+ /**
32
+ * The credit a client shows beside the data, present when a layer's license requires attribution.
33
+ */
34
+ attribution?: string
35
+ /**
36
+ * Sentences for the description, each one stating a manifest field the links couldn't come from.
37
+ */
38
+ notes: string[]
39
+ }
40
+
41
+ function countPhrase(count: number, singular: string, plural: string): string {
42
+ return count === 1 ? `1 ${singular}` : `${count} ${plural}`
43
+ }
44
+
45
+ /**
46
+ * The license and source links of `served`, from its own layers' manifests.
47
+ *
48
+ * A source that neither the layer's provider nor the gazetteer's source table locates is stated in a note.
49
+ *
50
+ * @param knownLayers Every layer the engine opened, so a source that matches a layer resolves to that layer.
51
+ */
52
+ export function collectionTerms(served: OGCServedCollection, knownLayers: readonly LayerTerms[]): OGCCollectionTerms {
53
+ const unread = served.unreadRegions
54
+ ? `${countPhrase(served.unreadRegions, "region has", "regions have")} a layer without a readable layer_manifest, so ${served.unreadRegions === 1 ? "it contributes" : "they contribute"} no link.`
55
+ : null
56
+
57
+ if (!served.layers) {
58
+ return {
59
+ links: [],
60
+ notes: ["The server read no layer manifest for this collection, so it links no license or source."],
61
+ }
62
+ }
63
+
64
+ const provenance = resolveLayerTerms(served.layers, { knownLayers, locate: gazetteerSourceLocation })
65
+
66
+ const links: OGCLink[] = provenance.links.map((link) => ({
67
+ href: link.href,
68
+ rel: link.kind === ProvenanceLinkKind.License ? OGCLinkRelation.License : OGCLinkRelation.Via,
69
+ type: OGCMediaType.HTML,
70
+ title: link.title,
71
+ }))
72
+
73
+ const { withoutLicense, withoutSource, unlinkedLicenses, unlocatedSources, credits } = provenance
74
+
75
+ const notes = [
76
+ ...(unread ? [unread] : []),
77
+ ...(withoutLicense ? [`${countPhrase(withoutLicense, "layer records", "layers record")} no license.`] : []),
78
+ ...(withoutSource ? [`${countPhrase(withoutSource, "layer records", "layers record")} no source.`] : []),
79
+ ...(unlinkedLicenses.length ? [`No published text is linked for the license ${unlinkedLicenses.join(", ")}.`] : []),
80
+ ...(unlocatedSources.length ? [`The server knows no location for the source ${unlocatedSources.join(", ")}.`] : []),
81
+ ]
82
+
83
+ return provenance.attributionRequired && credits.length
84
+ ? { links, notes, attribution: credits.join("; ") }
85
+ : { links, notes }
86
+ }
package/lib/refusal.ts ADDED
@@ -0,0 +1,34 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * Whether the operator's refused obligation classes keep a layer from being served in bulk.
6
+ *
7
+ * The items routes page through a whole gazetteer, so `MAILWOMAN_REFUSE_OBLIGATIONS`
8
+ * applies to them as it applies to attaching an OpenStreetMap layer.
9
+ */
10
+
11
+ import { obligationFindings, ObligationRefusal } from "@mailwoman/license/refusals"
12
+
13
+ /**
14
+ * Why the refused classes keep a layer with this recorded license from serving items,
15
+ * or null when none applies.
16
+ *
17
+ * A refused class among the license's obligations refuses it.
18
+ * A license the manifest doesn't record has unknown obligations, so `unresolved` refuses it too.
19
+ *
20
+ * @param license The SPDX expression the layer's manifest records, or null when it records none.
21
+ */
22
+ export function itemsRefusal(license: string | null, refuse: readonly ObligationRefusal[]): string | null {
23
+ if (!license) {
24
+ return refuse.includes(ObligationRefusal.Unresolved)
25
+ ? "MAILWOMAN_REFUSE_OBLIGATIONS refuses unresolved obligations, and the database records no license"
26
+ : null
27
+ }
28
+
29
+ const findings = obligationFindings(license, refuse)
30
+
31
+ return findings.length
32
+ ? `MAILWOMAN_REFUSE_OBLIGATIONS refuses ${findings.map(({ reason }) => reason).join("; ")}`
33
+ : null
34
+ }