@florasync/leaflet-geokit 0.11.1 → 0.12.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 (47) hide show
  1. package/CHANGELOG.md +5 -1
  2. package/README.md +4 -7
  3. package/dist/django/index.js +1044 -955
  4. package/dist/django/index.js.map +1 -1
  5. package/dist/geocoding-control.js +177 -0
  6. package/dist/geocoding-control.js.map +1 -0
  7. package/dist/geocoding.js +241 -0
  8. package/dist/geocoding.js.map +1 -0
  9. package/dist/leaflet-geokit.es.js +1155 -1064
  10. package/dist/leaflet-geokit.es.js.map +1 -1
  11. package/dist/leaflet-geokit.external.es.js +1583 -1492
  12. package/dist/leaflet-geokit.external.es.js.map +1 -1
  13. package/dist/leaflet-geokit.umd.js +23 -23
  14. package/dist/leaflet-geokit.umd.js.map +1 -1
  15. package/dist/preact/{index-CFFA4RWo.js → index-IL53Vgct.js} +745 -657
  16. package/dist/preact/index-IL53Vgct.js.map +1 -0
  17. package/dist/preact/index.js +8 -7
  18. package/dist/preact/index.js.map +1 -1
  19. package/dist/preact-bundled/index.js +2160 -2071
  20. package/dist/preact-bundled/index.js.map +1 -1
  21. package/dist/react/{index-CFFA4RWo.js → index-IL53Vgct.js} +745 -657
  22. package/dist/react/index-IL53Vgct.js.map +1 -0
  23. package/dist/react/index.js +18 -17
  24. package/dist/react/index.js.map +1 -1
  25. package/dist/react-bundled/index.js +2159 -2070
  26. package/dist/react-bundled/index.js.map +1 -1
  27. package/dist/types/components/LeafletDrawMapElement.d.ts +8 -2
  28. package/dist/types/geocoding.d.ts +5 -0
  29. package/dist/types/lib/MapController.d.ts +2 -0
  30. package/dist/types/lib/feature-credits.d.ts +12 -0
  31. package/dist/types/lib/geocoding-control.d.ts +4 -0
  32. package/dist/types/preact/core.d.ts +1 -1
  33. package/dist/types/react/core.d.ts +2 -2
  34. package/dist/types/react/index.d.ts +1 -1
  35. package/dist/types/react-bundled/index.d.ts +1 -1
  36. package/dist/types/types/events.d.ts +4 -0
  37. package/dist/types/types/geocoding.d.ts +36 -0
  38. package/dist/types/types/public.d.ts +4 -0
  39. package/docs/api-reference.md +41 -0
  40. package/docs/grower-geometry.md +1 -3
  41. package/docs/release-verification.md +6 -1
  42. package/docs/shims/django.md +1 -1
  43. package/docs/shims/preact.md +4 -2
  44. package/docs/shims/react.md +3 -1
  45. package/package.json +17 -12
  46. package/dist/preact/index-CFFA4RWo.js.map +0 -1
  47. package/dist/react/index-CFFA4RWo.js.map +0 -1
@@ -0,0 +1,177 @@
1
+ import { normalizeResult as x, createNominatimProvider as A } from "./geocoding.js";
2
+ const L = "geokit:credits", h = {
3
+ Status: "leaflet-geokit:status",
4
+ GeocodingStart: "leaflet-geokit:geocoding-start",
5
+ GeocodingResults: "leaflet-geokit:geocoding-results",
6
+ GeocodingAdded: "leaflet-geokit:geocoding-added",
7
+ GeocodingError: "leaflet-geokit:geocoding-error",
8
+ Diagnostic: "leaflet-geokit:diagnostic",
9
+ ToolCommand: "leaflet-geokit:tool-command",
10
+ ToolCommanded: "leaflet-geokit:tool-commanded",
11
+ ToolStarted: "leaflet-geokit:tool-started",
12
+ ToolCompleted: "leaflet-geokit:tool-completed",
13
+ ToolCancelled: "leaflet-geokit:tool-cancelled",
14
+ ToolFailed: "leaflet-geokit:tool-failed",
15
+ ToolStateChanged: "leaflet-geokit:tool-state-changed",
16
+ ToolCapabilitiesChanged: "leaflet-geokit:tool-capabilities-changed",
17
+ LayersChanged: "leaflet-geokit:layers-changed",
18
+ LayerStyleRequest: "leaflet-geokit:layer-style-request",
19
+ LayerCakeSessionStarted: "tool:layer-cake:session-started",
20
+ LayerCakeSessionChanged: "tool:layer-cake:session-changed",
21
+ LayerCakeSaved: "tool:layer-cake:saved",
22
+ LayerCakeCancelled: "tool:layer-cake:cancelled"
23
+ };
24
+ function G(r) {
25
+ var c;
26
+ if (r.geocodingProvider != null) {
27
+ const n = r.geocodingProvider;
28
+ if (typeof n.search != "function" || typeof n.attribution != "string" || !n.attribution.trim())
29
+ throw new Error("Invalid provider");
30
+ return n;
31
+ }
32
+ if (r.getAttribute("geocoding-provider") !== "nominatim")
33
+ throw new Error("No provider selected");
34
+ return A(
35
+ JSON.parse((c = r.getAttribute("geocoding-options")) != null ? c : "{}")
36
+ );
37
+ }
38
+ function q(r, c) {
39
+ var w;
40
+ const n = document.createElement("section");
41
+ n.className = "geokit-geocoding", n.setAttribute("part", "geocoding"), n.innerHTML = `<style>
42
+ .geokit-geocoding { position:absolute; z-index:1001; top:.5rem; left:50%; transform:translateX(-50%); box-sizing:border-box; width:min(22rem,calc(100% - 6rem)); max-height:calc(100% - 1rem); overflow:auto; padding:.4rem; border-radius:.25rem; background:var(--geokit-geocoding-bg,white); color:var(--geokit-geocoding-color,#222); font: 1rem/1.3 system-ui; }
43
+ .geokit-geocoding form { display:flex; } .geokit-geocoding input { flex:1; min-width:0; font:inherit; }
44
+ .geokit-geocoding ul { margin:0; padding:0; list-style:none; } .geokit-geocoding li button { width:100%; text-align:start; overflow-wrap:anywhere; } .geokit-geocoding small a { color:inherit; }
45
+ </style>
46
+ <form role="search" aria-label="Place search" autocomplete="off">
47
+ <input type="search" aria-label="Search places" required><button type="submit">Search</button>
48
+ </form>
49
+ <div role="status" aria-live="polite"></div><ul aria-label="Search results"></ul><small></small>`;
50
+ const y = n.querySelector("form"), p = n.querySelector("input"), v = n.querySelector("ul"), k = n.querySelector("small"), s = n.querySelector("[role=status]");
51
+ p.placeholder = (w = r.getAttribute("geocoding-placeholder")) != null ? w : "Search places", r.shadowRoot.append(n);
52
+ let g, l;
53
+ const C = () => {
54
+ g == null || g.abort(), v.replaceChildren(), l == null || l.remove(), l = void 0, s.textContent = "";
55
+ };
56
+ c.addEventListener(
57
+ "abort",
58
+ () => {
59
+ C(), n.remove();
60
+ },
61
+ { once: !0 }
62
+ );
63
+ const b = (t, o, i) => {
64
+ s.textContent = o, r.dispatchEvent(
65
+ new CustomEvent(h.GeocodingError, {
66
+ detail: { code: t, query: i }
67
+ })
68
+ );
69
+ };
70
+ let u, f;
71
+ try {
72
+ if (u = G(r), f = { text: u.attribution }, k.textContent = f.text, u.attributionUrl) {
73
+ const t = new URL(u.attributionUrl);
74
+ if (!["https:", "http:"].includes(t.protocol) || t.username || t.password)
75
+ throw new Error("Invalid attribution URL");
76
+ const o = document.createElement("a");
77
+ f.url = t.href, o.href = t.href, o.textContent = u.attribution, k.replaceChildren(o);
78
+ }
79
+ } catch {
80
+ p.disabled = !0, y.querySelector("button").disabled = !0, y.onsubmit = (t) => t.preventDefault(), b(
81
+ "configuration",
82
+ "Configure a search provider and endpoint to search."
83
+ );
84
+ return;
85
+ }
86
+ function E(t, o, i) {
87
+ const d = t.geometry;
88
+ if (!d || r.readOnly || !r.hasAttribute("geocoding-ingest"))
89
+ return;
90
+ const e = document.createElement("button");
91
+ e.type = "button", e.textContent = "Add to map";
92
+ const a = () => !i.aborted && l === e;
93
+ return e.onclick = async () => {
94
+ if (!(!a() || e.disabled)) {
95
+ e.disabled = !0;
96
+ try {
97
+ const m = await r.importGeoJSON(
98
+ {
99
+ type: "FeatureCollection",
100
+ features: [
101
+ {
102
+ type: "Feature",
103
+ properties: {
104
+ name: t.label,
105
+ attribution: f.text,
106
+ [L]: [{ ...f }]
107
+ },
108
+ geometry: structuredClone(d)
109
+ }
110
+ ]
111
+ },
112
+ { behavior: "add", validate: !0 }
113
+ );
114
+ if (!m.length) throw new Error("No features added");
115
+ r.dispatchEvent(
116
+ new CustomEvent(h.GeocodingAdded, {
117
+ detail: { featureIds: m }
118
+ })
119
+ ), a() && (s.textContent = "Added to map.");
120
+ } catch {
121
+ e.disabled = !1, a() && b("add", "Could not add this result.", o);
122
+ }
123
+ }
124
+ }, e;
125
+ }
126
+ function S(t, o, i) {
127
+ const d = document.createElement("li"), e = document.createElement("button");
128
+ e.type = "button", e.textContent = t.label, e.setAttribute("aria-pressed", "false"), d.append(e), v.append(d);
129
+ let a;
130
+ e.addEventListener(
131
+ "click",
132
+ () => {
133
+ var m;
134
+ i.aborted || ((m = v.querySelector("[aria-pressed=true]")) == null || m.setAttribute("aria-pressed", "false"), e.setAttribute("aria-pressed", "true"), l == null || l.remove(), a != null || (a = E(t, o, i)), l = a, a && k.before(a), s.textContent = `Selected: ${t.label}`, r.setView(t.latitude, t.longitude).catch(() => {
135
+ !i.aborted && e.getAttribute("aria-pressed") === "true" && b("center", "Could not center the map.", o);
136
+ }));
137
+ },
138
+ { signal: i }
139
+ );
140
+ }
141
+ p.addEventListener("input", C, { signal: c }), y.addEventListener(
142
+ "submit",
143
+ async (t) => {
144
+ t.preventDefault(), C();
145
+ const o = p.value.trim();
146
+ if (!o) return;
147
+ g = new AbortController();
148
+ const { signal: i } = g;
149
+ if (s.textContent = "Searching…", r.dispatchEvent(
150
+ new CustomEvent(h.GeocodingStart, {
151
+ detail: { query: o }
152
+ })
153
+ ), !i.aborted)
154
+ try {
155
+ const d = await u.search(o, { signal: i });
156
+ if (i.aborted) return;
157
+ const e = d.map(x).filter((a) => a !== null);
158
+ for (const a of e) S(a, o, i);
159
+ s.textContent = e.length ? `${e.length} results.` : "No results.", r.dispatchEvent(
160
+ new CustomEvent(h.GeocodingResults, {
161
+ detail: {
162
+ query: o,
163
+ results: structuredClone(e)
164
+ }
165
+ })
166
+ );
167
+ } catch {
168
+ i.aborted || b("search", "Search failed. You can submit again.", o);
169
+ }
170
+ },
171
+ { signal: c }
172
+ );
173
+ }
174
+ export {
175
+ q as mountGeocoding
176
+ };
177
+ //# sourceMappingURL=geocoding-control.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"geocoding-control.js","sources":["../src/lib/feature-credits.ts","../src/types/events.ts","../src/lib/geocoding-control.ts"],"sourcesContent":["import type { Feature } from \"geojson\";\nimport type { Control, Layer } from \"leaflet\";\n\nexport const CREDIT_KEY = \"geokit:credits\";\ntype Credit = { text: string; url?: string };\n\n/** Imported GeoJSON is untrusted. A bad URL must not suppress the credit text. */\nexport function featureCredits(features: Feature[]): Credit[] {\n const unique = new Map<string, Credit>();\n for (const feature of features) {\n const credits: unknown = feature.properties?.[CREDIT_KEY];\n if (!Array.isArray(credits)) continue;\n for (const row of credits) {\n if (typeof row?.text !== \"string\" || !row.text.trim()) continue;\n const credit: Credit = { text: row.text.trim() };\n if (typeof row.url === \"string\") {\n try {\n const url = new URL(row.url);\n if (\n [\"https:\", \"http:\"].includes(url.protocol) &&\n !url.username &&\n !url.password\n )\n credit.url = url.href;\n } catch {\n /* Invalid link: render the source as text. */\n }\n }\n unique.set(JSON.stringify(credit), credit);\n }\n }\n return [...unique.values()];\n}\n\n/** Leaflet reference-counts credits; bind each source to the actual rendered layer. */\nexport function bindFeatureCredits(\n feature: Feature,\n layer: Layer,\n control?: Control.Attribution,\n) {\n if (!control || !feature.properties?.[CREDIT_KEY]) return;\n for (const { text, url } of featureCredits([feature])) {\n const node = url\n ? document.createElement(\"a\")\n : document.createElement(\"span\");\n if (url) node.setAttribute(\"href\", url);\n node.textContent = text;\n // Leaflet's public attribution API expects HTML. Never interpolate user data.\n const html = node.outerHTML;\n layer.on(\"add\", () => control.addAttribution(html));\n layer.on(\"remove\", () => control.removeAttribution(html));\n }\n}\n","import type { Feature, FeatureCollection } from \"geojson\";\nimport type { GeoJSONExportAdapter } from \"@src/utils/geojson\";\n\nexport type GeoKitStatusState =\n \"uninitialized\" | \"initializing\" | \"ready\" | \"loading\" | \"error\";\n\nexport interface GeoKitDiagnosticSummary {\n code: string;\n message: string;\n recoverable: boolean;\n timestamp: number;\n}\n\n/**\n * Details for the 'leaflet-geokit:status' event and the element `status` getter.\n */\nexport interface StatusEventDetail {\n state: GeoKitStatusState;\n ready: boolean;\n busy: boolean;\n featureCount: number;\n lastEvent?: string;\n lastError?: GeoKitDiagnosticSummary;\n timestamp: number;\n}\n\n/**\n * Details for the 'leaflet-geokit:diagnostic' event.\n */\nexport interface DiagnosticEventDetail extends GeoKitDiagnosticSummary {\n severity: \"info\" | \"warn\" | \"error\";\n state: GeoKitStatusState;\n cause?: unknown;\n}\n\n/**\n * Details for the 'leaflet-draw:ready' event.\n * bounds: optional southwest/northeast LatLng pairs.\n */\nexport interface ReadyEventDetail {\n bounds?: [[number, number], [number, number]];\n}\n\n/**\n * Details for the 'leaflet-draw:created' event.\n * id: the stable feature id assigned by the FeatureStore.\n */\nexport interface CreatedEventDetail {\n id: string;\n layerType: \"polygon\" | \"polyline\" | \"rectangle\" | \"circle\" | \"marker\";\n geoJSON: Feature;\n}\n\n/**\n * Details for the 'leaflet-draw:edited' event.\n * ids: array of feature ids that were edited.\n */\nexport interface EditedEventDetail {\n ids: string[];\n geoJSON: FeatureCollection;\n}\n\n/**\n * Details for the 'leaflet-draw:deleted' event.\n * ids: array of feature ids that were deleted.\n */\nexport interface DeletedEventDetail {\n ids: string[];\n geoJSON: FeatureCollection;\n}\n\n/**\n * Details for error events emitted as 'leaflet-draw:error'.\n */\nexport interface ErrorEventDetail extends GeoKitDiagnosticSummary {\n cause?: unknown;\n}\n\n/**\n * Details for 'leaflet-draw:ingest' event. Fired before data is added to the map.\n * Listeners may mutate detail.fc to transform incoming data (e.g., flatten MultiPolygon).\n */\nexport interface IngestEventDetail {\n fc: FeatureCollection;\n mode: \"load\" | \"add\";\n}\n\n/**\n * Details for 'leaflet-draw:export' event.\n */\nexport interface ExportEventDetail {\n geoJSON: FeatureCollection;\n featureCount: number;\n adapter: GeoJSONExportAdapter;\n}\n\n/**\n * Event name constants for convenience (non-enforced).\n */\nexport const DrawEvent = {\n Ready: \"leaflet-draw:ready\",\n Created: \"leaflet-draw:created\",\n Edited: \"leaflet-draw:edited\",\n Deleted: \"leaflet-draw:deleted\",\n Error: \"leaflet-draw:error\",\n Ingest: \"leaflet-draw:ingest\",\n Export: \"leaflet-draw:export\",\n} as const;\n\nexport const GeoKitEvent = {\n Status: \"leaflet-geokit:status\",\n GeocodingStart: \"leaflet-geokit:geocoding-start\",\n GeocodingResults: \"leaflet-geokit:geocoding-results\",\n GeocodingAdded: \"leaflet-geokit:geocoding-added\",\n GeocodingError: \"leaflet-geokit:geocoding-error\",\n Diagnostic: \"leaflet-geokit:diagnostic\",\n ToolCommand: \"leaflet-geokit:tool-command\",\n ToolCommanded: \"leaflet-geokit:tool-commanded\",\n ToolStarted: \"leaflet-geokit:tool-started\",\n ToolCompleted: \"leaflet-geokit:tool-completed\",\n ToolCancelled: \"leaflet-geokit:tool-cancelled\",\n ToolFailed: \"leaflet-geokit:tool-failed\",\n ToolStateChanged: \"leaflet-geokit:tool-state-changed\",\n ToolCapabilitiesChanged: \"leaflet-geokit:tool-capabilities-changed\",\n LayersChanged: \"leaflet-geokit:layers-changed\",\n LayerStyleRequest: \"leaflet-geokit:layer-style-request\",\n LayerCakeSessionStarted: \"tool:layer-cake:session-started\",\n LayerCakeSessionChanged: \"tool:layer-cake:session-changed\",\n LayerCakeSaved: \"tool:layer-cake:saved\",\n LayerCakeCancelled: \"tool:layer-cake:cancelled\",\n} as const;\n","import type { LeafletDrawMapElementAPI } from \"../types/public\";\nimport type {\n GeocodingAddedDetail,\n GeocodingErrorDetail,\n GeocodingProvider,\n GeocodingResult,\n GeocodingResultsDetail,\n GeocodingStartDetail,\n} from \"../types/geocoding\";\nimport { createNominatimProvider, normalizeResult } from \"../geocoding\";\nimport { CREDIT_KEY } from \"./feature-credits\";\nimport { GeoKitEvent } from \"../types/events\";\n\ntype Host = HTMLElement &\n Pick<\n LeafletDrawMapElementAPI,\n \"importGeoJSON\" | \"setView\" | \"geocodingProvider\" | \"readOnly\"\n >;\nfunction configuredProvider(host: Host): GeocodingProvider {\n if (host.geocodingProvider != null) {\n const p = host.geocodingProvider;\n if (\n typeof p.search !== \"function\" ||\n typeof p.attribution !== \"string\" ||\n !p.attribution.trim()\n )\n throw new Error(\"Invalid provider\");\n return p;\n }\n if (host.getAttribute(\"geocoding-provider\") !== \"nominatim\")\n throw new Error(\"No provider selected\");\n return createNominatimProvider(\n JSON.parse(host.getAttribute(\"geocoding-options\") ?? \"{}\"),\n );\n}\n\nexport function mountGeocoding(host: Host, lifetime: AbortSignal): void {\n const panel = document.createElement(\"section\");\n panel.className = \"geokit-geocoding\";\n panel.setAttribute(\"part\", \"geocoding\");\n // Static template only. All provider, option and query strings use DOM text/attribute setters.\n panel.innerHTML = `<style>\n .geokit-geocoding { position:absolute; z-index:1001; top:.5rem; left:50%; transform:translateX(-50%); box-sizing:border-box; width:min(22rem,calc(100% - 6rem)); max-height:calc(100% - 1rem); overflow:auto; padding:.4rem; border-radius:.25rem; background:var(--geokit-geocoding-bg,white); color:var(--geokit-geocoding-color,#222); font: 1rem/1.3 system-ui; }\n .geokit-geocoding form { display:flex; } .geokit-geocoding input { flex:1; min-width:0; font:inherit; }\n .geokit-geocoding ul { margin:0; padding:0; list-style:none; } .geokit-geocoding li button { width:100%; text-align:start; overflow-wrap:anywhere; } .geokit-geocoding small a { color:inherit; }\n </style>\n <form role=\"search\" aria-label=\"Place search\" autocomplete=\"off\">\n <input type=\"search\" aria-label=\"Search places\" required><button type=\"submit\">Search</button>\n </form>\n <div role=\"status\" aria-live=\"polite\"></div><ul aria-label=\"Search results\"></ul><small></small>`;\n const form = panel.querySelector(\"form\")!,\n input = panel.querySelector(\"input\")!,\n list = panel.querySelector(\"ul\")!,\n credit = panel.querySelector(\"small\")!,\n status = panel.querySelector(\"[role=status]\")!;\n input.placeholder =\n host.getAttribute(\"geocoding-placeholder\") ?? \"Search places\";\n host.shadowRoot!.append(panel);\n let request: AbortController | undefined;\n let add: HTMLButtonElement | undefined;\n const clear = () => {\n request?.abort();\n list.replaceChildren();\n add?.remove();\n add = undefined;\n status.textContent = \"\";\n };\n lifetime.addEventListener(\n \"abort\",\n () => {\n clear();\n panel.remove();\n },\n { once: true },\n );\n const error = (\n code: GeocodingErrorDetail[\"code\"],\n message: string,\n query?: string,\n ) => {\n status.textContent = message;\n host.dispatchEvent(\n new CustomEvent(GeoKitEvent.GeocodingError, {\n detail: { code, query } satisfies GeocodingErrorDetail,\n }),\n );\n };\n let provider: GeocodingProvider;\n let source: { text: string; url?: string };\n try {\n provider = configuredProvider(host);\n source = { text: provider.attribution };\n credit.textContent = source.text;\n if (provider.attributionUrl) {\n const url = new URL(provider.attributionUrl);\n if (\n ![\"https:\", \"http:\"].includes(url.protocol) ||\n url.username ||\n url.password\n )\n throw new Error(\"Invalid attribution URL\");\n const link = document.createElement(\"a\");\n source.url = url.href;\n link.href = url.href;\n link.textContent = provider.attribution;\n credit.replaceChildren(link);\n }\n } catch {\n input.disabled = true;\n form.querySelector(\"button\")!.disabled = true;\n form.onsubmit = (e) => e.preventDefault();\n error(\n \"configuration\",\n \"Configure a search provider and endpoint to search.\",\n );\n return;\n }\n function createAddButton(\n result: GeocodingResult,\n query: string,\n signal: AbortSignal,\n ) {\n const geometry = result.geometry;\n if (!geometry || host.readOnly || !host.hasAttribute(\"geocoding-ingest\"))\n return;\n const action = document.createElement(\"button\");\n action.type = \"button\";\n action.textContent = \"Add to map\";\n const current = () => !signal.aborted && add === action;\n action.onclick = async () => {\n if (!current() || action.disabled) return;\n action.disabled = true;\n try {\n // The ingest hook can replace the whole collection; validate its output before appending.\n const featureIds = await host.importGeoJSON(\n {\n type: \"FeatureCollection\",\n features: [\n {\n type: \"Feature\",\n properties: {\n name: result.label,\n attribution: source.text,\n [CREDIT_KEY]: [{ ...source }],\n },\n geometry: structuredClone(geometry),\n },\n ],\n },\n { behavior: \"add\", validate: true },\n );\n if (!featureIds.length) throw new Error(\"No features added\");\n // A completed write belongs to the host, even if the search panel has changed.\n host.dispatchEvent(\n new CustomEvent(GeoKitEvent.GeocodingAdded, {\n detail: { featureIds } satisfies GeocodingAddedDetail,\n }),\n );\n if (current()) status.textContent = \"Added to map.\";\n } catch {\n action.disabled = false;\n if (current()) error(\"add\", \"Could not add this result.\", query);\n }\n };\n return action;\n }\n\n function renderResult(\n result: GeocodingResult,\n query: string,\n signal: AbortSignal,\n ) {\n const li = document.createElement(\"li\");\n const button = document.createElement(\"button\");\n button.type = \"button\";\n button.textContent = result.label;\n button.setAttribute(\"aria-pressed\", \"false\");\n li.append(button);\n list.append(li);\n let action: HTMLButtonElement | undefined;\n button.addEventListener(\n \"click\",\n () => {\n if (signal.aborted) return;\n list\n .querySelector(\"[aria-pressed=true]\")\n ?.setAttribute(\"aria-pressed\", \"false\");\n button.setAttribute(\"aria-pressed\", \"true\");\n add?.remove();\n action ??= createAddButton(result, query, signal);\n add = action;\n if (action) credit.before(action);\n status.textContent = `Selected: ${result.label}`;\n void host.setView(result.latitude, result.longitude).catch(() => {\n if (!signal.aborted && button.getAttribute(\"aria-pressed\") === \"true\")\n error(\"center\", \"Could not center the map.\", query);\n });\n },\n { signal },\n );\n }\n\n input.addEventListener(\"input\", clear, { signal: lifetime });\n form.addEventListener(\n \"submit\",\n async (e) => {\n e.preventDefault();\n clear();\n const query = input.value.trim();\n if (!query) return;\n request = new AbortController();\n const { signal } = request;\n status.textContent = \"Searching…\";\n host.dispatchEvent(\n new CustomEvent(GeoKitEvent.GeocodingStart, {\n detail: { query } satisfies GeocodingStartDetail,\n }),\n );\n if (signal.aborted) return;\n try {\n const rows = await provider.search(query, { signal });\n if (signal.aborted) return;\n const results = rows\n .map(normalizeResult)\n .filter((r): r is GeocodingResult => r !== null);\n for (const result of results) renderResult(result, query, signal);\n status.textContent = results.length\n ? `${results.length} results.`\n : \"No results.\";\n host.dispatchEvent(\n new CustomEvent(GeoKitEvent.GeocodingResults, {\n detail: {\n query,\n results: structuredClone(results),\n } satisfies GeocodingResultsDetail,\n }),\n );\n } catch {\n if (!signal.aborted)\n error(\"search\", \"Search failed. You can submit again.\", query);\n }\n },\n { signal: lifetime },\n );\n}\n"],"names":["CREDIT_KEY","GeoKitEvent","configuredProvider","host","p","createNominatimProvider","_a","mountGeocoding","lifetime","panel","form","input","list","credit","status","request","add","clear","error","code","message","query","provider","source","url","link","e","createAddButton","result","signal","geometry","action","current","featureIds","renderResult","li","button","rows","results","normalizeResult","r"],"mappings":";AAGO,MAAMA,IAAa,kBC0GbC,IAAc;AAAA,EACzB,QAAQ;A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AAQ,GAAQ;AACpD,cAAIA,EAAO,QAAS;AACpB,gBAAMS,IAAUD,EACb,IAAIE,CAAe,EACnB,OAAO,CAACC,MAA4BA,MAAM,IAAI;AACjD,qBAAWZ,KAAUU,EAAS,CAAAJ,EAAaN,GAAQP,GAAOQ,CAAM;AAChE,UAAAf,EAAO,cAAcwB,EAAQ,SACzB,GAAGA,EAAQ,MAAM,cACjB,eACJnC,EAAK;AAAA,YACH,IAAI,YAAYF,EAAY,kBAAkB;AAAA,cAC5C,QAAQ;AAAA,gBACN,OAAAoB;AAAA,gBACA,SAAS,gBAAgBiB,CAAO;AAAA,cAAA;AAAA,YAClC,CACD;AAAA,UAAA;AAAA,QAEL,QAAQ;AACN,UAAKT,EAAO,WACVX,EAAM,UAAU,wCAAwCG,CAAK;AAAA,QACjE;AAAA,IACF;AAAA,IACA,EAAE,QAAQb,EAAA;AAAA,EAAS;AAEvB;"}
@@ -0,0 +1,241 @@
1
+ const A = (r) => r !== null && typeof r == "object" && !Array.isArray(r);
2
+ function F(r) {
3
+ const s = [];
4
+ let c = 0;
5
+ const d = /* @__PURE__ */ new Set(), i = (e, t, o, n = "error") => {
6
+ s.push({ code: e, path: t, message: o, severity: n });
7
+ }, g = (e, t) => {
8
+ "crs" in e && i(
9
+ "crs-mismatch",
10
+ `${t}.crs`,
11
+ "RFC 7946 uses WGS84 longitude/latitude; legacy CRS is not reprojected.",
12
+ "warning"
13
+ );
14
+ }, l = (e, t) => {
15
+ if (Array.isArray(e) && e.length === 0 && i("empty-geometry", t, "Point has no coordinates."), !Array.isArray(e) || e.length < 2 || !e.every((o) => typeof o == "number" && Number.isFinite(o))) {
16
+ i(
17
+ "invalid-position",
18
+ t,
19
+ "Expected at least two finite ordinates."
20
+ );
21
+ return;
22
+ }
23
+ (Math.abs(e[0]) > 180 || Math.abs(e[1]) > 90) && i(
24
+ "crs-mismatch",
25
+ t,
26
+ "Position outside WGS84 longitude/latitude range.",
27
+ "warning"
28
+ );
29
+ }, a = (e, t, o) => {
30
+ if (!Array.isArray(e) || e.length === 0) {
31
+ i(
32
+ "empty-geometry",
33
+ t,
34
+ "Expected a non-empty coordinate/geometry array."
35
+ );
36
+ return;
37
+ }
38
+ e.forEach((n, f) => o(n, `${t}[${f}]`));
39
+ }, $ = (e, t) => {
40
+ a(e, t, l), Array.isArray(e) && e.length < 2 && i(
41
+ "invalid-line",
42
+ t,
43
+ "LineString requires at least two positions."
44
+ );
45
+ }, h = (e, t) => {
46
+ a(e, t, l);
47
+ const o = Array.isArray(e) ? e[0] : void 0, n = Array.isArray(e) ? e[e.length - 1] : void 0, f = Array.isArray(o) && Array.isArray(n) && o.length === n.length && o.every((p, b) => p === n[b]);
48
+ Array.isArray(e) && (e.length < 4 || !f) && i(
49
+ "invalid-ring",
50
+ t,
51
+ "Linear rings require four positions and exact closure."
52
+ );
53
+ }, y = (e, t) => a(e, t, h), m = (e, t, o) => {
54
+ if (o > 64) {
55
+ i("nesting-limit", t, "Geometry nesting exceeds 64.");
56
+ return;
57
+ }
58
+ if (!A(e)) {
59
+ i("empty-geometry", t, "Missing or null geometry.");
60
+ return;
61
+ }
62
+ g(e, t);
63
+ const n = `${t}.coordinates`;
64
+ switch (e.type) {
65
+ case "Point":
66
+ l(e.coordinates, n);
67
+ break;
68
+ case "LineString":
69
+ $(e.coordinates, n);
70
+ break;
71
+ case "Polygon":
72
+ y(e.coordinates, n);
73
+ break;
74
+ case "MultiPoint":
75
+ a(e.coordinates, n, l);
76
+ break;
77
+ case "MultiLineString":
78
+ a(e.coordinates, n, $);
79
+ break;
80
+ case "MultiPolygon":
81
+ a(e.coordinates, n, y);
82
+ break;
83
+ case "GeometryCollection":
84
+ a(
85
+ e.geometries,
86
+ `${t}.geometries`,
87
+ (f, p) => m(f, p, o + 1)
88
+ );
89
+ break;
90
+ default:
91
+ i(
92
+ "unsupported-geometry",
93
+ t,
94
+ `Unsupported geometry: ${typeof e.type == "string" ? e.type : "missing or non-string type"}.`
95
+ );
96
+ }
97
+ typeof e.type == "string" && (e.type.startsWith("Multi") || e.type === "GeometryCollection") && i(
98
+ "multi-expansion",
99
+ t,
100
+ "Editing adapters expand this geometry into single-geometry features.",
101
+ "info"
102
+ );
103
+ }, x = (e, t) => {
104
+ var f;
105
+ if (c++, !A(e) || e.type !== "Feature") {
106
+ i("invalid-feature", t, "Expected a Feature.");
107
+ return;
108
+ }
109
+ if (g(e, t), e.properties === null || A(e.properties) || i(
110
+ "invalid-properties",
111
+ `${t}.properties`,
112
+ "Expected an object or null."
113
+ ), A(e.properties)) {
114
+ const p = e.properties.id;
115
+ e.id === void 0 && p !== void 0 && !(typeof p == "string" && p.length > 0) && !(typeof p == "number" && Number.isFinite(p)) && i(
116
+ "invalid-id",
117
+ `${t}.properties.id`,
118
+ "Fallback ID must be a non-empty string or finite number."
119
+ );
120
+ const b = e.properties["geokit:source"];
121
+ b !== void 0 && (!Array.isArray(b) || b.length === 0 || b.length > 64 || !b.every(
122
+ (u) => A(u) && typeof u.type == "string" && [
123
+ "MultiPoint",
124
+ "MultiLineString",
125
+ "MultiPolygon",
126
+ "GeometryCollection"
127
+ ].includes(u.type) && (typeof u.id == "string" || typeof u.id == "number") && typeof u.hasPropertyId == "boolean" && typeof u.nullProperties == "boolean"
128
+ )) && i(
129
+ "invalid-provenance",
130
+ `${t}.properties.geokit:source`,
131
+ "Reserved expansion provenance is malformed."
132
+ );
133
+ }
134
+ e.id !== void 0 && !(typeof e.id == "string" && e.id.length > 0) && !(typeof e.id == "number" && Number.isFinite(e.id)) && i(
135
+ "invalid-id",
136
+ `${t}.id`,
137
+ "Feature ID must be a non-empty string or finite number."
138
+ );
139
+ const o = (f = e.id) != null ? f : A(e.properties) ? e.properties.id : void 0, n = typeof o == "string" || typeof o == "number" ? String(o) : void 0;
140
+ n !== void 0 && (d.has(n) && i("duplicate-id", `${t}.id`, `Duplicate feature ID: ${n}.`), d.add(n)), m(e.geometry, `${t}.geometry`, 0);
141
+ }, w = /* @__PURE__ */ new Set();
142
+ let j = !1;
143
+ const E = (e, t, o) => {
144
+ if (o > 128) {
145
+ j = !0, i("nesting-limit", t, "JSON nesting exceeds 128.");
146
+ return;
147
+ }
148
+ if (!(e === null || typeof e == "string" || typeof e == "boolean") && !(typeof e == "number" && Number.isFinite(e))) {
149
+ if (typeof e != "object" || e === null || w.has(e)) {
150
+ typeof e == "object" && e !== null && w.has(e) && (j = !0), i("invalid-json", t, "Expected finite, acyclic JSON values.");
151
+ return;
152
+ }
153
+ if (!Array.isArray(e) && Object.getPrototypeOf(e) !== Object.prototype && Object.getPrototypeOf(e) !== null) {
154
+ i("invalid-json", t, "Expected a plain JSON object.");
155
+ return;
156
+ }
157
+ if (w.add(e), Array.isArray(e))
158
+ for (let n = 0; n < e.length; n++)
159
+ E(e[n], `${t}[${n}]`, o + 1);
160
+ else
161
+ Object.entries(e).forEach(
162
+ ([n, f]) => E(f, `${t}.${n}`, o + 1)
163
+ );
164
+ w.delete(e);
165
+ }
166
+ };
167
+ return E(r, "$", 0), j ? { valid: !1, featureCount: c, diagnostics: s } : (A(r) ? r.type === "FeatureCollection" ? (g(r, "$"), Array.isArray(r.features) ? r.features.forEach((e, t) => x(e, `$.features[${t}]`)) : i("invalid-collection", "$.features", "Expected a features array.")) : r.type === "Feature" ? x(r, "$") : (c = 1, m(r, "$", 0)) : i("invalid-input", "$", "Expected a GeoJSON object."), {
168
+ valid: !s.some((e) => e.severity === "error"),
169
+ featureCount: c,
170
+ diagnostics: s
171
+ });
172
+ }
173
+ const P = (r) => !!r && typeof r == "object" && !Array.isArray(r);
174
+ function M(r) {
175
+ if (!P(r)) return null;
176
+ const { label: s, latitude: c, longitude: d, geometry: i } = r;
177
+ if (typeof s != "string" || !s.trim() || typeof c != "number" || !Number.isFinite(c) || Math.abs(c) > 90 || typeof d != "number" || !Number.isFinite(d) || Math.abs(d) > 180)
178
+ return null;
179
+ const g = { label: s.trim(), latitude: c, longitude: d };
180
+ if (i === void 0) return g;
181
+ const { diagnostics: l } = F({
182
+ type: "Feature",
183
+ properties: null,
184
+ geometry: i
185
+ });
186
+ return l.some((a) => a.severity !== "info") ? null : {
187
+ ...g,
188
+ geometry: structuredClone(i)
189
+ };
190
+ }
191
+ const S = (r) => typeof r == "string" && /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(r) ? Number(r) : r;
192
+ function k(r) {
193
+ var c, d, i;
194
+ if (typeof (r == null ? void 0 : r.endpoint) != "string" || !r.endpoint.trim())
195
+ throw new Error("A search endpoint is required.");
196
+ const s = new URL(r.endpoint, (c = globalThis.location) == null ? void 0 : c.href);
197
+ if (!["http:", "https:"].includes(s.protocol) || s.username || s.password)
198
+ throw new Error("Expected an HTTP(S) search endpoint without credentials.");
199
+ if (r.attribution !== void 0 && (typeof r.attribution != "string" || !r.attribution.trim()))
200
+ throw new Error("Expected a nonempty attribution.");
201
+ return {
202
+ attribution: (d = r.attribution) != null ? d : "© OpenStreetMap contributors",
203
+ attributionUrl: (i = r.attributionUrl) != null ? i : r.attribution ? void 0 : "https://www.openstreetmap.org/copyright",
204
+ async search(g, { signal: l }) {
205
+ const a = new URL(s);
206
+ for (const [y, m] of Object.entries({
207
+ q: g,
208
+ format: "jsonv2",
209
+ limit: "5",
210
+ polygon_geojson: "1"
211
+ }))
212
+ a.searchParams.set(y, m);
213
+ const $ = await fetch(a, {
214
+ signal: l,
215
+ headers: { Accept: "application/json" },
216
+ credentials: "omit",
217
+ redirect: "error"
218
+ });
219
+ if (!$.ok)
220
+ throw new Error(`Search failed (HTTP ${$.status}).`);
221
+ const h = await $.json();
222
+ if (!Array.isArray(h))
223
+ throw new Error("Expected a search result array.");
224
+ return h.flatMap((y) => {
225
+ if (!P(y)) return [];
226
+ const m = M({
227
+ label: y.display_name,
228
+ latitude: S(y.lat),
229
+ longitude: S(y.lon),
230
+ geometry: y.geojson
231
+ });
232
+ return m ? [m] : [];
233
+ });
234
+ }
235
+ };
236
+ }
237
+ export {
238
+ k as createNominatimProvider,
239
+ M as normalizeResult
240
+ };
241
+ //# sourceMappingURL=geocoding.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"geocoding.js","sources":["../src/utils/geojson-pipeline.ts","../src/geocoding.ts"],"sourcesContent":["import type { Feature, FeatureCollection } from \"geojson\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport {\n adaptFeatureCollectionForExport,\n expandMultiGeometries,\n normalizeId,\n type GeoJSONExportOptions,\n} from \"./geojson.js\";\n\nexport interface GeoJSONDiagnostic {\n severity: \"error\" | \"warning\" | \"info\";\n code: string;\n path: string;\n message: string;\n}\nexport interface GeoJSONValidationSummary {\n valid: boolean;\n featureCount: number;\n diagnostics: GeoJSONDiagnostic[];\n}\nexport interface GeoJSONNormalizationOptions {\n /** Opt in to Leaflet.draw-compatible single geometries. */\n expandMulti?: boolean;\n}\nexport interface GeoJSONImportResult extends GeoJSONValidationSummary {\n data: FeatureCollection | null;\n}\nexport interface GeoJSONPatch {\n created: Feature[];\n updated: Feature[];\n deleted: string[];\n}\nexport interface GeoJSONDiff extends GeoJSONPatch {\n createdIds: string[];\n updatedIds: string[];\n deletedIds: string[];\n}\n\nconst record = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\nconst clone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T;\n\n/** Structural RFC 7946 preflight; never mutates its input or a map. */\nexport function validateGeoJSON(input: unknown): GeoJSONValidationSummary {\n const diagnostics: GeoJSONDiagnostic[] = [];\n let featureCount = 0;\n const ids = new Set<string>();\n const report = (\n code: string,\n path: string,\n message: string,\n severity: GeoJSONDiagnostic[\"severity\"] = \"error\",\n ) => {\n diagnostics.push({ code, path, message, severity });\n };\n const crs = (value: Record<string, unknown>, path: string) => {\n if (\"crs\" in value)\n report(\n \"crs-mismatch\",\n `${path}.crs`,\n \"RFC 7946 uses WGS84 longitude/latitude; legacy CRS is not reprojected.\",\n \"warning\",\n );\n };\n const position = (value: unknown, path: string) => {\n if (Array.isArray(value) && value.length === 0)\n report(\"empty-geometry\", path, \"Point has no coordinates.\");\n if (\n !Array.isArray(value) ||\n value.length < 2 ||\n !value.every((n) => typeof n === \"number\" && Number.isFinite(n))\n ) {\n report(\n \"invalid-position\",\n path,\n \"Expected at least two finite ordinates.\",\n );\n return;\n }\n if (Math.abs(value[0]) > 180 || Math.abs(value[1]) > 90)\n report(\n \"crs-mismatch\",\n path,\n \"Position outside WGS84 longitude/latitude range.\",\n \"warning\",\n );\n };\n const array = (\n value: unknown,\n path: string,\n visit: (v: unknown, p: string) => void,\n ) => {\n if (!Array.isArray(value) || value.length === 0) {\n report(\n \"empty-geometry\",\n path,\n \"Expected a non-empty coordinate/geometry array.\",\n );\n return;\n }\n value.forEach((v, i) => visit(v, `${path}[${i}]`));\n };\n const line = (value: unknown, path: string) => {\n array(value, path, position);\n if (Array.isArray(value) && value.length < 2)\n report(\n \"invalid-line\",\n path,\n \"LineString requires at least two positions.\",\n );\n };\n const ring = (value: unknown, path: string) => {\n array(value, path, position);\n const first = Array.isArray(value) ? value[0] : undefined;\n const last = Array.isArray(value) ? value[value.length - 1] : undefined;\n const closed =\n Array.isArray(first) &&\n Array.isArray(last) &&\n first.length === last.length &&\n first.every((n, i) => n === last[i]);\n if (Array.isArray(value) && (value.length < 4 || !closed))\n report(\n \"invalid-ring\",\n path,\n \"Linear rings require four positions and exact closure.\",\n );\n };\n const polygon = (value: unknown, path: string) => array(value, path, ring);\n const geometry = (value: unknown, path: string, depth: number) => {\n if (depth > 64) {\n report(\"nesting-limit\", path, \"Geometry nesting exceeds 64.\");\n return;\n }\n if (!record(value)) {\n report(\"empty-geometry\", path, \"Missing or null geometry.\");\n return;\n }\n crs(value, path);\n const coords = `${path}.coordinates`;\n switch (value.type) {\n case \"Point\":\n position(value.coordinates, coords);\n break;\n case \"LineString\":\n line(value.coordinates, coords);\n break;\n case \"Polygon\":\n polygon(value.coordinates, coords);\n break;\n case \"MultiPoint\":\n array(value.coordinates, coords, position);\n break;\n case \"MultiLineString\":\n array(value.coordinates, coords, line);\n break;\n case \"MultiPolygon\":\n array(value.coordinates, coords, polygon);\n break;\n case \"GeometryCollection\":\n array(value.geometries, `${path}.geometries`, (v, p) =>\n geometry(v, p, depth + 1),\n );\n break;\n default:\n report(\n \"unsupported-geometry\",\n path,\n `Unsupported geometry: ${typeof value.type === \"string\" ? value.type : \"missing or non-string type\"}.`,\n );\n }\n if (\n typeof value.type === \"string\" &&\n (value.type.startsWith(\"Multi\") || value.type === \"GeometryCollection\")\n )\n report(\n \"multi-expansion\",\n path,\n \"Editing adapters expand this geometry into single-geometry features.\",\n \"info\",\n );\n };\n const feature = (value: unknown, path: string) => {\n featureCount++;\n if (!record(value) || value.type !== \"Feature\") {\n report(\"invalid-feature\", path, \"Expected a Feature.\");\n return;\n }\n crs(value, path);\n if (!(value.properties === null || record(value.properties)))\n report(\n \"invalid-properties\",\n `${path}.properties`,\n \"Expected an object or null.\",\n );\n if (record(value.properties)) {\n const fallback = value.properties.id;\n if (\n value.id === undefined &&\n fallback !== undefined &&\n !(typeof fallback === \"string\" && fallback.length > 0) &&\n !(typeof fallback === \"number\" && Number.isFinite(fallback))\n )\n report(\n \"invalid-id\",\n `${path}.properties.id`,\n \"Fallback ID must be a non-empty string or finite number.\",\n );\n const sources = value.properties[\"geokit:source\"];\n if (\n sources !== undefined &&\n (!Array.isArray(sources) ||\n sources.length === 0 ||\n sources.length > 64 ||\n !sources.every(\n (s) =>\n record(s) &&\n typeof s.type === \"string\" &&\n [\n \"MultiPoint\",\n \"MultiLineString\",\n \"MultiPolygon\",\n \"GeometryCollection\",\n ].includes(s.type) &&\n (typeof s.id === \"string\" || typeof s.id === \"number\") &&\n typeof s.hasPropertyId === \"boolean\" &&\n typeof s.nullProperties === \"boolean\",\n ))\n )\n report(\n \"invalid-provenance\",\n `${path}.properties.geokit:source`,\n \"Reserved expansion provenance is malformed.\",\n );\n }\n if (\n value.id !== undefined &&\n !(typeof value.id === \"string\" && value.id.length > 0) &&\n !(typeof value.id === \"number\" && Number.isFinite(value.id))\n )\n report(\n \"invalid-id\",\n `${path}.id`,\n \"Feature ID must be a non-empty string or finite number.\",\n );\n const candidate =\n value.id ?? (record(value.properties) ? value.properties.id : undefined);\n const id =\n typeof candidate === \"string\" || typeof candidate === \"number\"\n ? String(candidate)\n : undefined;\n if (id !== undefined) {\n if (ids.has(id))\n report(\"duplicate-id\", `${path}.id`, `Duplicate feature ID: ${id}.`);\n ids.add(id);\n }\n geometry(value.geometry, `${path}.geometry`, 0);\n };\n // Guard serialization so cyclic/non-JSON metadata cannot fail later, after mutation.\n const active = new Set<object>();\n let unsafeGraph = false;\n const json = (value: unknown, path: string, depth: number): void => {\n if (depth > 128) {\n unsafeGraph = true;\n report(\"nesting-limit\", path, \"JSON nesting exceeds 128.\");\n return;\n }\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"boolean\"\n )\n return;\n if (typeof value === \"number\" && Number.isFinite(value)) return;\n if (typeof value !== \"object\" || value === null || active.has(value)) {\n if (typeof value === \"object\" && value !== null && active.has(value))\n unsafeGraph = true;\n report(\"invalid-json\", path, \"Expected finite, acyclic JSON values.\");\n return;\n }\n if (\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) !== Object.prototype &&\n Object.getPrototypeOf(value) !== null\n ) {\n report(\"invalid-json\", path, \"Expected a plain JSON object.\");\n return;\n }\n active.add(value);\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++)\n json(value[i], `${path}[${i}]`, depth + 1);\n } else\n Object.entries(value).forEach(([k, v]) =>\n json(v, `${path}.${k}`, depth + 1),\n );\n active.delete(value);\n };\n json(input, \"$\", 0);\n // Do not traverse rejected graphs again: branching cycles can otherwise\n // multiply geometry visits exponentially before the depth guard is reached.\n if (unsafeGraph) return { valid: false, featureCount, diagnostics };\n if (!record(input))\n report(\"invalid-input\", \"$\", \"Expected a GeoJSON object.\");\n else if (input.type === \"FeatureCollection\") {\n crs(input, \"$\");\n if (!Array.isArray(input.features))\n report(\"invalid-collection\", \"$.features\", \"Expected a features array.\");\n else input.features.forEach((f, i) => feature(f, `$.features[${i}]`));\n } else if (input.type === \"Feature\") feature(input, \"$\");\n else {\n featureCount = 1;\n geometry(input, \"$\", 0);\n }\n return {\n valid: !diagnostics.some((d) => d.severity === \"error\"),\n featureCount,\n diagnostics,\n };\n}\n\nexport class GeoJSONValidationError extends Error {\n constructor(public readonly summary: GeoJSONValidationSummary) {\n super(\"GeoJSON validation failed\");\n this.name = \"GeoJSONValidationError\";\n }\n}\n\n/** Wrap app shapes, clone metadata, assign missing IDs once, optionally expand. */\nexport function normalizeGeoJSON(\n input: unknown,\n options: GeoJSONNormalizationOptions = {},\n): FeatureCollection {\n const summary = validateGeoJSON(input);\n if (!summary.valid) throw new GeoJSONValidationError(summary);\n const value = clone(input) as\n FeatureCollection | Feature | Feature[\"geometry\"];\n const fc: FeatureCollection =\n value.type === \"FeatureCollection\"\n ? value\n : {\n type: \"FeatureCollection\",\n features: [\n value.type === \"Feature\"\n ? value\n : { type: \"Feature\", properties: {}, geometry: value },\n ],\n };\n for (const f of fc.features) f.id = f.id ?? normalizeId(f) ?? uuidv4();\n const result = options.expandMulti\n ? expandMultiGeometries(fc, { preserveMetadata: true })\n : fc;\n const checked = validateGeoJSON(result);\n if (!checked.valid) throw new GeoJSONValidationError(checked);\n return clone(result);\n}\n\nexport function importGeoJSONData(\n input: unknown,\n options: GeoJSONNormalizationOptions = {},\n): GeoJSONImportResult {\n const summary = validateGeoJSON(input);\n if (!summary.valid) return { ...summary, data: null };\n try {\n return { ...summary, data: normalizeGeoJSON(input, options) };\n } catch (error) {\n if (error instanceof GeoJSONValidationError)\n return { ...error.summary, data: null };\n throw error;\n }\n}\n\nexport function importGeoJSONText(\n text: string,\n options: GeoJSONNormalizationOptions = {},\n): GeoJSONImportResult {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n return {\n valid: false,\n featureCount: 0,\n data: null,\n diagnostics: [\n {\n severity: \"error\",\n code: \"invalid-json\",\n path: \"$\",\n message: \"Unable to parse JSON text.\",\n },\n ],\n };\n }\n return importGeoJSONData(value, options);\n}\n\n/** Validate export too; source mode refuses divergent child properties rather than losing edits. */\nexport function exportGeoJSONData(\n input: FeatureCollection,\n options: GeoJSONExportOptions = {},\n): GeoJSONImportResult {\n const summary = validateGeoJSON(input);\n if (!summary.valid) return { ...summary, data: null };\n if (options.adapter === \"source\") {\n const groups = new Map<string, string>();\n for (const [i, f] of input.features.entries()) {\n const sources = f.properties?.[\"geokit:source\"];\n if (!Array.isArray(sources) || !sources.length) continue;\n const key = String(sources[0]?.id);\n const properties = { ...f.properties };\n delete properties.id;\n delete properties[\"geokit:source\"];\n const serialized = canonical(properties);\n if (groups.has(key) && groups.get(key) !== serialized)\n summary.diagnostics.push({\n severity: \"error\",\n code: \"metadata-conflict\",\n path: `$.features[${i}].properties`,\n message:\n \"Expanded children have divergent properties; export editing data or reconcile before source export.\",\n });\n groups.set(key, serialized);\n }\n }\n summary.valid = !summary.diagnostics.some((d) => d.severity === \"error\");\n if (!summary.valid) return { ...summary, data: null };\n const data = adaptFeatureCollectionForExport(clone(input), {\n ...options,\n provenanceOnly: true,\n });\n const output = validateGeoJSON(data);\n return {\n ...output,\n diagnostics: [...summary.diagnostics, ...output.diagnostics],\n data: output.valid ? data : null,\n };\n}\n\n/** Explicit URL adapter: no implicit fetching of arbitrary strings. Fetch errors reject. */\nexport async function importGeoJSONURL(\n url: string | URL,\n options: GeoJSONNormalizationOptions & {\n signal?: AbortSignal;\n fetcher?: typeof fetch;\n } = {},\n): Promise<GeoJSONImportResult> {\n const response = await (options.fetcher ?? fetch)(url, {\n signal: options.signal,\n });\n if (!response.ok)\n throw new Error(`GeoJSON fetch failed: HTTP ${response.status}`);\n return importGeoJSONText(await response.text(), options);\n}\n\nfunction indexed(input: unknown): Map<string, Feature> {\n const summary = validateGeoJSON(input);\n if (!summary.valid) throw new GeoJSONValidationError(summary);\n const fc = input as FeatureCollection;\n if (fc.type !== \"FeatureCollection\")\n throw new Error(\"Diff/patch requires a FeatureCollection.\");\n return new Map(\n fc.features.map((f) => {\n const id = normalizeId(f);\n if (id === undefined)\n throw new Error(\n \"Diff/patch requires stable feature IDs; normalize once before editing.\",\n );\n return [id, f];\n }),\n );\n}\nfunction canonical(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n if (record(value))\n return `{${Object.keys(value)\n .sort()\n .map((k) => `${JSON.stringify(k)}:${canonical(value[k])}`)\n .join(\",\")}}`;\n return JSON.stringify(value);\n}\n\n/** ID-based, order-insensitive comparison; property and geometry edits both count. */\nexport function diffGeoJSON(\n before: FeatureCollection,\n after: FeatureCollection,\n): GeoJSONDiff {\n const old = indexed(before),\n next = indexed(after);\n const created: Feature[] = [],\n updated: Feature[] = [],\n deleted: string[] = [];\n for (const [id, f] of next) {\n if (!old.has(id)) created.push(clone(f));\n else if (canonical(old.get(id)) !== canonical(f)) updated.push(clone(f));\n }\n for (const id of old.keys()) if (!next.has(id)) deleted.push(id);\n return {\n created,\n updated,\n deleted,\n createdIds: created.map((f) => normalizeId(f)!),\n updatedIds: updated.map((f) => normalizeId(f)!),\n deletedIds: [...deleted],\n };\n}\n\n/** Strict, atomic pure patch: reject missing targets, duplicate operations and creates. */\nexport function applyGeoJSONPatch(\n base: FeatureCollection,\n patch: GeoJSONPatch,\n): FeatureCollection {\n const next = indexed(base);\n if (\n !patch ||\n !Array.isArray(patch.created) ||\n !Array.isArray(patch.updated) ||\n !Array.isArray(patch.deleted)\n )\n throw new Error(\"Malformed GeoJSON patch.\");\n const touched = new Set<string>();\n const touch = (id: string) => {\n if (touched.has(id)) throw new Error(`Conflicting patch operations: ${id}`);\n touched.add(id);\n };\n for (const id of patch.deleted) {\n if (typeof id !== \"string\") throw new Error(\"Deleted IDs must be strings.\");\n touch(id);\n if (!next.delete(id)) throw new Error(`Missing deleted feature: ${id}`);\n }\n for (const [kind, features] of [\n [\"created\", patch.created],\n [\"updated\", patch.updated],\n ] as const) {\n const entries = indexed({ type: \"FeatureCollection\", features });\n for (const [id, f] of entries) {\n touch(id);\n if (kind === \"created\" ? next.has(id) : !next.has(id))\n throw new Error(`Invalid ${kind} target: ${id}`);\n next.set(id, f);\n }\n }\n return clone({ ...base, features: [...next.values()] });\n}\n","import type {\n GeocodingProvider,\n GeocodingResult,\n NominatimOptions,\n} from \"./types/geocoding\";\nimport { validateGeoJSON } from \"./utils/geojson-pipeline\";\nexport type * from \"./types/geocoding\";\n\nconst record = (v: unknown): v is Record<string, unknown> =>\n !!v && typeof v === \"object\" && !Array.isArray(v);\n\n/** @internal Take a detached snapshot of a provider row, not a reference to its data. */\nexport function normalizeResult(row: unknown): GeocodingResult | null {\n if (!record(row)) return null;\n const { label, latitude, longitude, geometry } = row;\n if (\n typeof label !== \"string\" ||\n !label.trim() ||\n typeof latitude !== \"number\" ||\n !Number.isFinite(latitude) ||\n Math.abs(latitude) > 90 ||\n typeof longitude !== \"number\" ||\n !Number.isFinite(longitude) ||\n Math.abs(longitude) > 180\n )\n return null;\n const result = { label: label.trim(), latitude, longitude };\n if (geometry === undefined) return result;\n // Wrapping a Feature rejects FeatureCollections/Features masquerading as geometries.\n const { diagnostics } = validateGeoJSON({\n type: \"Feature\",\n properties: null,\n geometry,\n });\n if (diagnostics.some((d) => d.severity !== \"info\")) return null;\n return {\n ...result,\n geometry: structuredClone(geometry) as GeocodingResult[\"geometry\"],\n };\n}\n\nconst number = (value: unknown) =>\n typeof value === \"string\" &&\n /^[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i.test(value)\n ? Number(value)\n : value;\n\nexport function createNominatimProvider(\n options: NominatimOptions,\n): GeocodingProvider {\n if (typeof options?.endpoint !== \"string\" || !options.endpoint.trim())\n throw new Error(\"A search endpoint is required.\");\n const endpoint = new URL(options.endpoint, globalThis.location?.href);\n if (\n ![\"http:\", \"https:\"].includes(endpoint.protocol) ||\n endpoint.username ||\n endpoint.password\n )\n throw new Error(\"Expected an HTTP(S) search endpoint without credentials.\");\n if (\n options.attribution !== undefined &&\n (typeof options.attribution !== \"string\" || !options.attribution.trim())\n )\n throw new Error(\"Expected a nonempty attribution.\");\n return {\n attribution: options.attribution ?? \"© OpenStreetMap contributors\",\n attributionUrl:\n options.attributionUrl ??\n (options.attribution\n ? undefined\n : \"https://www.openstreetmap.org/copyright\"),\n async search(query, { signal }) {\n const url = new URL(endpoint);\n for (const [key, value] of Object.entries({\n q: query,\n format: \"jsonv2\",\n limit: \"5\",\n polygon_geojson: \"1\",\n }))\n url.searchParams.set(key, value);\n const response = await fetch(url, {\n signal,\n headers: { Accept: \"application/json\" },\n credentials: \"omit\",\n redirect: \"error\",\n });\n if (!response.ok)\n throw new Error(`Search failed (HTTP ${response.status}).`);\n const rows: unknown = await response.json();\n if (!Array.isArray(rows))\n throw new Error(\"Expected a search result array.\");\n return rows.flatMap((row) => {\n if (!record(row)) return [];\n const result = normalizeResult({\n label: row.display_name,\n latitude: number(row.lat),\n longitude: number(row.lon),\n geometry: row.geojson,\n });\n return result ? [result] : [];\n });\n },\n };\n}\n"],"names":["record","value","validateGeoJSON","input","diagnostics","featureCount","ids","report","code","path","message","severity","crs","position","n","array","visit","v","i","line","ring","first","last","closed","polygon","geometry","depth","coords","feature","_a","fallback","sources","s","candidate","id","active","unsafeGraph","json","k","f","d","normalizeResult","row","label","latitude","longitude","result","number","createNominatimProvider","options","_b","_c","endpoint","query","signal","url","key","response","rows"],"mappings":"AAsCA,MAAMA,IAAS,CAACC,MACdA,MAAU,QAAQ,OAAOA,KAAU,YAAY,CAAC,MAAM,QAAQA,CAAK;AAI9D,SAASC,EAAgBC,GAA0C;AACxE,QAAMC,IAAmC,CAAA;AACzC,MAAIC,IAAe;AACnB,QAAMC,wBAAU,IAAA,GACVC,IAAS,CACbC,GACAC,GACAC,GACAC,IAA0C,YACvC;AACH,IAAAP,EAAY,KAAK,EAAE,MAAAI,GAAM,MAAAC,GAAM,SAAAC,GAAS,UAAAC,GAAU;AAAA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