@urban-toolkit/autk-grammar 5.0.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,165 +1,265 @@
1
- import { DEFAULT_WORKSPACE_NAME as p, AutkDb as x, DEFAULT_WORKSPACE_COORDINATE_FORMAT as $ } from "@urban-toolkit/autk-db";
2
- async function A(o, t) {
3
- const a = t ?? p;
4
- o.getCurrentWorkspace() !== a && await o.setWorkspace(a);
1
+ import { DEFAULT_WORKSPACE_NAME as h, isVectorTable as L, AutkDb as S, isRenderableTable as N } from "@urban-toolkit/autk-db";
2
+ async function j(o, a) {
3
+ const n = a ?? h;
4
+ o.getCurrentWorkspace() !== n && await o.setWorkspace(n);
5
5
  }
6
- function h(o, t) {
7
- return o === void 0 || o === p ? t : `${o}/${t}`;
6
+ function w(o, a) {
7
+ return o === void 0 || o === h ? a : `${o}/${a}`;
8
8
  }
9
- function L(o) {
10
- const t = /* @__PURE__ */ new Set();
11
- for (const c of o)
12
- c?.id != null && t.add(JSON.stringify(c.id));
9
+ function v(o) {
13
10
  const a = /* @__PURE__ */ new Set();
14
- return o.map((c, s) => {
15
- if (c?.id != null) return c.id;
16
- let e = `autk-feature-${s}`;
17
- for (; t.has(JSON.stringify(e)) || a.has(JSON.stringify(e)); ) e = `${e}-generated`;
18
- return a.add(JSON.stringify(e)), e;
11
+ for (const f of o)
12
+ f?.id != null && a.add(JSON.stringify(f.id));
13
+ const n = /* @__PURE__ */ new Set();
14
+ return o.map((f, u) => {
15
+ if (f?.id != null) return f.id;
16
+ let i = `autk-feature-${u}`;
17
+ for (; a.has(JSON.stringify(i)) || n.has(JSON.stringify(i)); ) i = `${i}-generated`;
18
+ return n.add(JSON.stringify(i)), i;
19
19
  });
20
20
  }
21
- const E = { type: "GeometryCollection", geometries: [] };
22
- function N(o) {
23
- const t = o.features ?? [], a = L(t);
24
- let c = !1;
25
- const s = t.map((u, r) => u == null || u.id != null && u.geometry != null ? u : (c = !0, { ...u, id: a[r], geometry: u.geometry ?? E })), e = t.findIndex((u) => u?.geometry != null);
26
- return e > 0 && t[0] != null && t[0].geometry == null && ([s[0], s[e]] = [s[e], s[0]], c = !0), c ? { ...o, features: s } : o;
21
+ const O = { type: "GeometryCollection", geometries: [] };
22
+ function A(o) {
23
+ const a = o.features ?? [], n = v(a);
24
+ let f = !1;
25
+ const u = a.map((e, r) => e == null || e.id != null && e.geometry != null ? e : (f = !0, { ...e, id: n[r], geometry: e.geometry ?? O })), i = a.findIndex((e) => e?.geometry != null);
26
+ return i > 0 && a[0] != null && a[0].geometry == null && ([u[0], u[i]] = [u[i], u[0]], f = !0), f ? { ...o, features: u } : o;
27
27
  }
28
- function T(o) {
29
- const { queryArea: t } = o;
30
- if (t.bbox === void 0) return { geocodeArea: t.geocodeArea, areas: t.areas };
31
- const a = (l) => new Error(`OSM source "${o.outputTableName}": ${l}`);
32
- if (t.geocodeArea !== void 0 || t.areas !== void 0)
33
- throw a("queryArea takes either bbox or geocodeArea with areas, not both.");
34
- const c = t.bbox;
35
- if (!Array.isArray(c) || c.length !== 4 || !c.every((l) => typeof l == "number" && Number.isFinite(l)))
36
- throw a("queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.");
37
- const [s, e, u, r] = t.bbox;
38
- if (Math.abs(s) > 180 || Math.abs(u) > 180)
39
- throw a("queryArea.bbox west and east must be longitudes from -180 to 180.");
40
- if (Math.abs(e) > 90 || Math.abs(r) > 90)
41
- throw a("queryArea.bbox south and north must be latitudes from -90 to 90.");
42
- if (s >= u)
43
- throw a(`queryArea.bbox west (${s}) must be less than east (${u}); a box across the antimeridian is not supported.`);
44
- if (e >= r)
45
- throw a(`queryArea.bbox south (${e}) must be less than north (${r}).`);
46
- return { bbox: [s, e, u, r] };
28
+ function F(o) {
29
+ const { queryArea: a } = o;
30
+ if (a.bbox === void 0) return { geocodeArea: a.geocodeArea, areas: a.areas };
31
+ const n = (s) => new Error(`OSM source "${o.outputTableName}": ${s}`);
32
+ if (a.geocodeArea !== void 0 || a.areas !== void 0)
33
+ throw n("queryArea takes either bbox or geocodeArea with areas, not both.");
34
+ const f = a.bbox;
35
+ if (!Array.isArray(f) || f.length !== 4 || !f.every((s) => typeof s == "number" && Number.isFinite(s)))
36
+ throw n("queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.");
37
+ const [u, i, e, r] = a.bbox;
38
+ if (Math.abs(u) > 180 || Math.abs(e) > 180)
39
+ throw n("queryArea.bbox west and east must be longitudes from -180 to 180.");
40
+ if (Math.abs(i) > 90 || Math.abs(r) > 90)
41
+ throw n("queryArea.bbox south and north must be latitudes from -90 to 90.");
42
+ if (u >= e)
43
+ throw n(`queryArea.bbox west (${u}) must be less than east (${e}); a box across the antimeridian is not supported.`);
44
+ if (i >= r)
45
+ throw n(`queryArea.bbox south (${i}) must be less than north (${r}).`);
46
+ return { bbox: [u, i, e, r] };
47
47
  }
48
- function S(o) {
49
- const { autoLoadLayers: t, ...a } = o;
50
- return { ...a, queryArea: T(o), autoLoadLayers: { layers: t?.layers ?? [] } };
48
+ function k(o) {
49
+ const { autoLoadLayers: a, ...n } = o;
50
+ if (o.pbfFileUrl !== void 0 && (o.tagSets?.length ?? 0) > 0)
51
+ throw new Error(`OSM source "${o.outputTableName}": tagSets are read from the Overpass API only, so a source with pbfFileUrl cannot take them.`);
52
+ return {
53
+ ...n,
54
+ queryArea: F(o),
55
+ autoLoadLayers: {
56
+ layers: a?.layers ?? [],
57
+ ...a?.coordinateFormat !== void 0 && { coordinateFormat: a.coordinateFormat }
58
+ }
59
+ };
51
60
  }
52
- function g(o) {
61
+ function E(o) {
53
62
  return `${o ? `coordinateFormat is set to "${o}"` : "no coordinateFormat was specified, so it defaults to EPSG:4326 (WGS84 per RFC 7946)"}. Verify that coordinateFormat matches the actual CRS of the input data.`;
54
63
  }
55
- function F(o) {
56
- let t = 1 / 0, a = 1 / 0, c = -1 / 0, s = -1 / 0;
57
- const e = (r) => {
64
+ function $(o) {
65
+ return o === void 0 || o === h ? "the default workspace" : `the workspace "${o}"`;
66
+ }
67
+ function T(o) {
68
+ if (o != null)
69
+ return typeof o == "string" ? o : JSON.stringify(o);
70
+ }
71
+ async function M(o, a, n, f) {
72
+ const u = /* @__PURE__ */ new Map();
73
+ for (const r of (await o.getLayer(a.name)).features) {
74
+ const s = T(r.properties?.[f]);
75
+ if (s !== void 0) {
76
+ if (r.id === void 0 || r.id === null)
77
+ throw new Error("its rows have no feature id to update them by.");
78
+ u.set(s, [...u.get(s) ?? [], r.id]);
79
+ }
80
+ }
81
+ const i = n.features.flatMap((r) => {
82
+ const s = T(r.properties?.[f]);
83
+ return s === void 0 ? [] : (u.get(s) ?? []).map((y) => ({ ...r, id: y }));
84
+ }), e = a.columns.some((r) => r.name === "geojson_id") ? "geojson_id" : "id";
85
+ return { data: { ...n, features: i }, idColumn: e };
86
+ }
87
+ async function x(o) {
88
+ if (o) return o;
89
+ const a = new S();
90
+ return await a.init(), a;
91
+ }
92
+ function R(o) {
93
+ let a = 1 / 0, n = 1 / 0, f = -1 / 0, u = -1 / 0;
94
+ const i = (r) => {
58
95
  if (Array.isArray(r)) {
59
96
  if (typeof r[0] == "number") {
60
- const [l, f] = r;
61
- l < t && (t = l), l > c && (c = l), f < a && (a = f), f > s && (s = f);
97
+ const [s, y] = r;
98
+ s < a && (a = s), s > f && (f = s), y < n && (n = y), y > u && (u = y);
62
99
  return;
63
100
  }
64
- for (const l of r) e(l);
101
+ for (const s of r) i(s);
65
102
  }
66
- }, u = (r) => {
67
- r && (r.type === "GeometryCollection" ? r.geometries.forEach(u) : e(r.coordinates));
103
+ }, e = (r) => {
104
+ r && (r.type === "GeometryCollection" ? r.geometries.forEach(e) : i(r.coordinates));
68
105
  };
69
- for (const r of o.features ?? []) u(r?.geometry);
70
- return t <= c ? [t, a, c, s] : void 0;
106
+ for (const r of o.features ?? []) e(r?.geometry);
107
+ return a <= f ? [a, n, f, u] : void 0;
71
108
  }
72
- function j(o, t) {
73
- function a(c, s) {
74
- if (!s || !s.db)
109
+ function C(o, a) {
110
+ function n(u, i) {
111
+ if (!i || !i.db)
75
112
  return;
76
- const e = document.getElementById(s.db);
113
+ const e = document.getElementById(i.db);
77
114
  if (e) {
78
- const u = c.getTablesMetadata();
115
+ const r = u.getTablesMetadata();
79
116
  e.innerHTML += "<ul>";
80
- for (const r of u)
81
- e.innerHTML += `<li>${r.name}: (${r.source}, ${r.type}) </li>`;
82
- e.innerHTML += "</ul>", e.innerHTML += `<p>Number of tables: ${u.length}</p>`;
117
+ for (const s of r)
118
+ e.innerHTML += `<li>${s.name}: (${s.source}, ${s.type}) </li>`;
119
+ e.innerHTML += "</ul>", e.innerHTML += `<p>Number of tables: ${r.length}</p>`;
83
120
  }
84
121
  }
122
+ async function f(u, i, e) {
123
+ if (!a) return;
124
+ const r = w(i, e), s = u.getTablesMetadata().find((y) => y.name === e);
125
+ s && N(s) ? a.set(r, await u.getLayer(e)) : a.delete(r);
126
+ }
85
127
  return {
86
- async resolveSource(c, s) {
87
- let e = c;
88
- e || (e = new x(), await e.init());
89
- const { workspace: u } = s;
90
- await A(e, u);
91
- let { type: r, workspace: l, ...f } = s;
92
- switch (r) {
128
+ async resolveWorkspaces(u, i) {
129
+ const e = await x(u), r = /* @__PURE__ */ new Set();
130
+ for (const { name: s, coordinateFormat: y, precisionGrid: m } of i) {
131
+ const t = s ?? h;
132
+ if (r.has(t))
133
+ throw new Error(`workspaces sets ${$(s)} twice; give each workspace one entry.`);
134
+ r.add(t);
135
+ try {
136
+ await e.setWorkspace(t, { coordinateFormat: y, precisionGrid: m });
137
+ } catch (c) {
138
+ throw new Error(`workspaces, ${$(s)}: ${c instanceof Error ? c.message : String(c)}`);
139
+ }
140
+ }
141
+ return await j(e), e;
142
+ },
143
+ async resolveSource(u, i) {
144
+ const e = await x(u), { workspace: r } = i;
145
+ await j(e, r);
146
+ let { type: s, workspace: y, ...m } = i;
147
+ switch (s) {
93
148
  case "osm":
94
- return await e.loadOsm(S(f)), a(e, o), e;
149
+ return await e.loadOsm(k(m)), n(e, o), e;
95
150
  case "csv":
96
- return await e.loadCsv(f), a(e, o), e;
151
+ return await e.loadCsv(m), n(e, o), e;
97
152
  case "json":
98
- return await e.loadJson(f), a(e, o), e;
153
+ return await e.loadJson(m), n(e, o), e;
99
154
  case "geojson": {
100
- const n = f;
101
- let d;
102
- n.geojsonFileUrl ? d = await (await fetch(n.geojsonFileUrl)).json() : d = n.geojsonObject, t && d && t.set(h(u, n.outputTableName), d);
103
- const m = d ? (() => {
104
- const i = { ...n, geojsonObject: N(d) };
105
- return delete i.geojsonFileUrl, i;
106
- })() : n, w = /^EPSG:4326$/i.test(m.coordinateFormat ?? "EPSG:4326"), b = d && w ? F(d) : void 0;
107
- if (b && (b[1] < -90 || b[3] > 90))
155
+ const t = m;
156
+ let c;
157
+ t.geojsonFileUrl ? c = await (await fetch(t.geojsonFileUrl)).json() : c = t.geojsonObject, a && c && a.set(w(r, t.outputTableName), c);
158
+ const b = c ? (() => {
159
+ const d = { ...t, geojsonObject: A(c) };
160
+ return delete d.geojsonFileUrl, d;
161
+ })() : t, p = /^EPSG:4326$/i.test(b.coordinateFormat ?? "EPSG:4326"), l = c && p ? R(c) : void 0;
162
+ if (l && (l[1] < -90 || l[3] > 90))
108
163
  throw new Error(
109
- `GeoJSON layer "${m.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${b.join(", ")}]), so they cannot be EPSG:4326 degrees. ${g(m.coordinateFormat)}`
164
+ `GeoJSON layer "${b.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${l.join(", ")}]), so they cannot be EPSG:4326 degrees. ${E(b.coordinateFormat)}`
110
165
  );
111
166
  try {
112
- await e.loadGeojson(m);
113
- } catch (i) {
114
- throw new Error(`Failed to load GeoJSON layer "${m.outputTableName}": ${i instanceof Error ? i.message : String(i)}`);
167
+ await e.loadGeojson(b);
168
+ } catch (d) {
169
+ throw new Error(`Failed to load GeoJSON layer "${b.outputTableName}": ${d instanceof Error ? d.message : String(d)}`);
115
170
  }
116
171
  try {
117
- const i = await e.getBoundingBoxFromLayer(m.outputTableName), y = 25e6;
118
- if (!isFinite(i.minLon) || !isFinite(i.minLat) || !isFinite(i.maxLon) || !isFinite(i.maxLat) || Math.abs(i.minLon) > y || Math.abs(i.maxLon) > y || Math.abs(i.minLat) > y || Math.abs(i.maxLat) > y)
172
+ const d = await e.getBoundingBoxFromLayer(b.outputTableName), g = 25e6;
173
+ if (!isFinite(d.minLon) || !isFinite(d.minLat) || !isFinite(d.maxLon) || !isFinite(d.maxLat) || Math.abs(d.minLon) > g || Math.abs(d.maxLon) > g || Math.abs(d.minLat) > g || Math.abs(d.maxLat) > g)
119
174
  throw new Error(
120
- `Geometry bounding box after transform is invalid for layer "${m.outputTableName}" (bbox: [${i.minLon}, ${i.minLat}, ${i.maxLon}, ${i.maxLat}]). ${g(m.coordinateFormat)} The workspace uses ${$}; input is expected in EPSG:4326 by default.`
175
+ `Geometry bounding box after transform is invalid for layer "${b.outputTableName}" (bbox: [${d.minLon}, ${d.minLat}, ${d.maxLon}, ${d.maxLat}]). ${E(b.coordinateFormat)} The workspace uses ${e.getWorkspaceConfiguration().coordinateFormat}; input is expected in EPSG:4326 by default.`
121
176
  );
122
- } catch (i) {
123
- if (i instanceof Error && i.message.includes("bounding box after transform")) throw i;
177
+ } catch (d) {
178
+ if (d instanceof Error && d.message.includes("bounding box after transform")) throw d;
124
179
  }
125
- return a(e, o), e;
180
+ return n(e, o), e;
126
181
  }
127
182
  case "geotiff":
128
- return await e.loadGeoTiff(f), a(e, o), e;
183
+ return await e.loadGeoTiff(m), n(e, o), e;
129
184
  case "heatmap": {
130
- const n = f;
131
- if (n.groupBy?.some((d) => d.aggregateFn === "collect"))
132
- throw new Error(`Heatmap "${n.outputTableName}": aggregateFn "collect" lists the rows near a cell, and a cell holds one value; use sum, avg, count, min, max or weighted.`);
185
+ const t = m;
186
+ if (t.groupBy?.some((c) => c.aggregateFn === "collect"))
187
+ throw new Error(`Heatmap "${t.outputTableName}": aggregateFn "collect" lists the rows near a cell, and a cell holds one value; use sum, avg, count, min, max or weighted.`);
133
188
  return await e.buildHeatmap({
134
- tableJoinName: n.joinDataRef,
135
- near: n.near,
136
- outputTableName: n.outputTableName,
137
- grid: n.grid,
138
- ...n.groupBy && { groupBy: n.groupBy }
139
- }), a(e, o), e;
189
+ tableJoinName: t.joinDataRef,
190
+ near: t.near,
191
+ outputTableName: t.outputTableName,
192
+ grid: t.grid,
193
+ ...t.groupBy && { groupBy: t.groupBy }
194
+ }), n(e, o), e;
140
195
  }
141
196
  case "join": {
142
- const n = f;
197
+ const t = m;
143
198
  if (await e.spatialQuery({
144
- tableRootName: n.dataRef,
145
- tableJoinName: n.joinDataRef,
146
- ...n.near && { near: n.near },
147
- ...n.groupBy && { groupBy: n.groupBy }
148
- }), t) {
149
- const d = await e.getLayer(n.dataRef);
150
- t.set(h(u, n.dataRef), d);
199
+ tableRootName: t.dataRef,
200
+ tableJoinName: t.joinDataRef,
201
+ ...t.near && { near: t.near },
202
+ ...t.groupBy && { groupBy: t.groupBy }
203
+ }), a) {
204
+ const c = await e.getLayer(t.dataRef);
205
+ a.set(w(r, t.dataRef), c);
151
206
  }
152
- return a(e, o), e;
207
+ return n(e, o), e;
208
+ }
209
+ case "sql": {
210
+ const t = m;
211
+ try {
212
+ await e.rawQuery({
213
+ query: t.query,
214
+ output: {
215
+ type: "CREATE_TABLE",
216
+ tableName: t.outputTableName,
217
+ source: "user",
218
+ ...t.layerType !== void 0 && { tableType: t.layerType }
219
+ }
220
+ });
221
+ } catch (c) {
222
+ throw new Error(`SQL source "${t.outputTableName}": ${c instanceof Error ? c.message : String(c)}`);
223
+ }
224
+ return a?.delete(w(r, t.outputTableName)), n(e, o), e;
225
+ }
226
+ case "update": {
227
+ const t = m, c = (l) => new Error(`Update of "${t.dataRef}": ${l}`);
228
+ if (t.geojsonObject === void 0 == (t.jsonObject === void 0))
229
+ throw c("give its rows in geojsonObject or in jsonObject, one of the two.");
230
+ if (t.strategy === "update" && !t.idColumn)
231
+ throw c("the update strategy needs an idColumn, the column that matches a given row to the table's rows.");
232
+ let b = t.geojsonObject ?? t.jsonObject, p = t.idColumn;
233
+ try {
234
+ const l = e.getTablesMetadata().find((d) => d.name === t.dataRef);
235
+ if (t.strategy === "update" && t.geojsonObject && p?.startsWith("properties.") && l && L(l) && ({ data: b, idColumn: p } = await M(e, l, t.geojsonObject, p.slice(11)), b.features.length === 0))
236
+ return n(e, o), e;
237
+ await e.updateTable({
238
+ tableName: t.dataRef,
239
+ data: b,
240
+ strategy: t.strategy,
241
+ ...p !== void 0 && { idColumn: p }
242
+ });
243
+ } catch (l) {
244
+ throw c(l instanceof Error ? l.message : String(l));
245
+ }
246
+ return await f(e, r, t.dataRef), n(e, o), e;
247
+ }
248
+ case "drop": {
249
+ const t = m;
250
+ if (!e.getTablesMetadata().some((c) => c.name === t.dataRef))
251
+ throw new Error(`Drop of "${t.dataRef}": ${$(r)} holds no table of that name.`);
252
+ return await e.removeLayer(t.dataRef), a?.delete(w(r, t.dataRef)), n(e, o), e;
153
253
  }
154
254
  default:
155
- return;
255
+ throw new Error(`Unknown data source type "${String(s)}".`);
156
256
  }
157
257
  }
158
258
  };
159
259
  }
160
260
  export {
161
- j as createDataAdapter,
162
- A as enterWorkspace,
163
- h as tableKey
261
+ C as createDataAdapter,
262
+ j as enterWorkspace,
263
+ w as tableKey
164
264
  };
165
265
  //# sourceMappingURL=autk-grammar-data.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"autk-grammar-data.js","sources":["../../src/workspace.ts","../../src/rows.ts","../../src/adapters/data.ts"],"sourcesContent":["import { AutkDb, DEFAULT_WORKSPACE_NAME } from '@urban-toolkit/autk-db';\n\n/**\n * Makes `workspace` (the default one without a name) the workspace `db` works in; autk-db creates it on first use.\n * It calls autk-db's `setWorkspace` only when `getCurrentWorkspace()` names another one.\n *\n * Every adapter calls it before it reads or writes a table of a spec entry, with the entry's `workspace`. A host that\n * reads a spec's tables itself calls it the same way, since autk-db finds a table by its name in the current\n * workspace only.\n */\nexport async function enterWorkspace(db: AutkDb, workspace?: string): Promise<void> {\n const name = workspace ?? DEFAULT_WORKSPACE_NAME;\n if (db.getCurrentWorkspace() !== name) await db.setWorkspace(name);\n}\n\n/**\n * The key a table has in the grammar's caches: its name in the default workspace, `<workspace>/<name>` in another, so\n * two workspaces can hold tables of the same name. A host reads the caches it passes to `createDataAdapter` and\n * `createComputeAdapter` with it.\n */\nexport function tableKey(workspace: string | undefined, name: string): string {\n return workspace === undefined || workspace === DEFAULT_WORKSPACE_NAME ? name : `${workspace}/${name}`;\n}\n","import type { Feature } from 'geojson';\n\n/**\n * A selection passes between a plot and a map layer by the rows each drew, not by positions. A plot draws its table's\n * rows in the order the host handed them, while a map layer draws autk-db's export of the table, which can keep the\n * rows in an order of its own and leaves out those without a geometry, so one position can be another row in each\n * view. Each row is known in both by its feature id, which autk-db keeps in its export. Nothing here needs a GPU or a\n * database, so the unit tests run it in Node.\n */\n\n/**\n * The id autk-db gives each feature of a GeoJSON source: its own `id`, else `autk-feature-<index>`, with `-generated`\n * added while another feature has that id. The data adapter hands autk-db features that carry these ids, so autk-db\n * keeps them in its export whatever rule it would use itself.\n */\nexport function featureIds(features: readonly (Feature | null | undefined)[]): Array<string | number> {\n const own = new Set<string>();\n for (const feature of features) {\n if (feature?.id != null) own.add(JSON.stringify(feature.id));\n }\n const given = new Set<string>();\n return features.map((feature, index) => {\n if (feature?.id != null) return feature.id;\n let id = `autk-feature-${index}`;\n while (own.has(JSON.stringify(id)) || given.has(JSON.stringify(id))) id = `${id}-generated`;\n given.add(JSON.stringify(id));\n return id;\n });\n}\n\n/**\n * The key of each row of a collection, which names the row in every view of its table: its id as {@link featureIds}\n * gives it, written as JSON so that `3` and `\"3\"` stay apart, and the times that id came before when it repeats.\n */\nexport function rowKeys(features: readonly (Feature | null | undefined)[]): string[] {\n const seen = new Map<string, number>();\n return featureIds(features).map((id) => {\n const json = JSON.stringify(id);\n const before = seen.get(json) ?? 0;\n seen.set(json, before + 1);\n return before === 0 ? json : `${json} ${before}`;\n });\n}\n\n/** Each key's positions, built once for each list of keys. */\nconst positionsByKey = new WeakMap<readonly string[], Map<string, number[]>>();\n\nfunction positionsOf(keys: readonly string[]): Map<string, number[]> {\n let positions = positionsByKey.get(keys);\n if (positions) return positions;\n positions = new Map();\n keys.forEach((key, position) => {\n const list = positions!.get(key);\n if (list) list.push(position);\n else positions!.set(key, [position]);\n });\n positionsByKey.set(keys, positions);\n return positions;\n}\n\n/**\n * The positions in one view of the rows at the positions `ids` in another, each view given by the key of the row at\n * each of its positions. A row the other view does not draw has no position there, and a row it draws at several\n * positions has each of them.\n */\nexport function translateIds(ids: readonly number[], from: readonly string[], to: readonly string[]): number[] {\n const positions = positionsOf(to);\n const translated = new Set<number>();\n for (const id of ids) {\n const key = from[id];\n if (key === undefined) continue;\n for (const position of positions.get(key) ?? []) translated.add(position);\n }\n return [...translated];\n}\n","import { CsvDataSourceSpec, CustomDataSourceSpec, DataAdapter, DataSourceSpec, GeoTiffDataSourceSpec, HeatmapSourceSpec, JoinSourceSpec, JsonDataSourceSpec, OsmDataSourceSpec } from '@urban-toolkit/the-urban-grammar';\nimport { AutkDb, DEFAULT_WORKSPACE_COORDINATE_FORMAT } from '@urban-toolkit/autk-db';\nimport type { LoadGeojsonParams } from '@urban-toolkit/autk-db';\nimport type { FeatureCollection, Geometry } from 'geojson';\nimport { Targets, GeoJsonCache } from '../types';\nimport { enterWorkspace, tableKey } from '../workspace';\nimport { featureIds } from '../rows';\n\n/** An empty geometry: a GeometryCollection with none in it, which a map draws as nothing. */\nconst NO_GEOMETRY: Geometry = { type: 'GeometryCollection', geometries: [] };\n\n/**\n * A GeoJSON source's collection as autk-db loads it, row for row.\n *\n * - Each feature carries the id autk-db gives it (see `featureIds`), from its place in the source. autk-db keeps the\n * id in its export, so a row a map draws from the export is found among the source's own rows, which a plot draws.\n * - autk-db refuses a feature whose geometry is null, which GeoJSON allows, so such a feature gets an empty one: a map\n * draws nothing for it, and a plot still counts it.\n * - autk-db reads the layer's type off the first feature, so a first feature without a geometry trades places with the\n * first that has one. Each keeps its id, so the rows are still found by it.\n */\nfunction loadableCollection(collection: FeatureCollection): FeatureCollection {\n const features = collection.features ?? [];\n const ids = featureIds(features);\n let changed = false;\n const loadable = features.map((feature, index) => {\n if (feature == null || (feature.id != null && feature.geometry != null)) return feature;\n changed = true;\n return { ...feature, id: ids[index], geometry: feature.geometry ?? NO_GEOMETRY };\n });\n const first = features.findIndex((feature) => feature?.geometry != null);\n if (first > 0 && features[0] != null && features[0].geometry == null) {\n [loadable[0], loadable[first]] = [loadable[first], loadable[0]];\n changed = true;\n }\n return changed ? { ...collection, features: loadable } : collection;\n}\n\n/**\n * The query area autk-db reads: `{ bbox }` or `{ geocodeArea, areas }`. autk-db takes any area with a\n * `bbox` key as a box, so a box that also names areas, or that is not [west, south, east, north] in\n * degrees with west less than east and south less than north, is refused here.\n */\nfunction queryAreaOf(spec: OsmDataSourceSpec): OsmDataSourceSpec['queryArea'] {\n const { queryArea } = spec;\n if (queryArea.bbox === undefined) return { geocodeArea: queryArea.geocodeArea, areas: queryArea.areas };\n\n const refuse = (message: string) => new Error(`OSM source \"${spec.outputTableName}\": ${message}`);\n if (queryArea.geocodeArea !== undefined || queryArea.areas !== undefined)\n throw refuse('queryArea takes either bbox or geocodeArea with areas, not both.');\n const box: unknown = queryArea.bbox;\n if (!Array.isArray(box) || box.length !== 4 || !box.every((value) => typeof value === 'number' && Number.isFinite(value)))\n throw refuse('queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.');\n const [west, south, east, north] = queryArea.bbox;\n if (Math.abs(west) > 180 || Math.abs(east) > 180)\n throw refuse('queryArea.bbox west and east must be longitudes from -180 to 180.');\n if (Math.abs(south) > 90 || Math.abs(north) > 90)\n throw refuse('queryArea.bbox south and north must be latitudes from -90 to 90.');\n if (west >= east)\n throw refuse(`queryArea.bbox west (${west}) must be less than east (${east}); a box across the antimeridian is not supported.`);\n if (south >= north)\n throw refuse(`queryArea.bbox south (${south}) must be less than north (${north}).`);\n return { bbox: [west, south, east, north] };\n}\n\n/**\n * Maps an OSM source onto autk-db's parameters, which always expect\n * `autoLoadLayers` and no longer take `dropOsmTable`.\n */\nfunction toLoadOsmParams(spec: OsmDataSourceSpec) {\n const { autoLoadLayers, ...rest } = spec;\n return { ...rest, queryArea: queryAreaOf(spec), autoLoadLayers: { layers: autoLoadLayers?.layers ?? [] } };\n}\n\n/**\n * The CRS advice. Only a bounding-box check gives it, when the box shows that a layer's coordinates\n * are not in the CRS it was loaded as; any other load error is autk-db's own message.\n */\nfunction crsAdvice(coordinateFormat: string | undefined): string {\n const assumed = coordinateFormat\n ? `coordinateFormat is set to \"${coordinateFormat}\"`\n : 'no coordinateFormat was specified, so it defaults to EPSG:4326 (WGS84 per RFC 7946)';\n return `${assumed}. Verify that coordinateFormat matches the actual CRS of the input data.`;\n}\n\n/** The [minX, minY, maxX, maxY] of every position in a collection, or undefined when it has none. */\nexport function extentOf(collection: FeatureCollection): [number, number, number, number] | undefined {\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n const visitPositions = (value: unknown): void => {\n if (!Array.isArray(value)) return;\n if (typeof value[0] === 'number') {\n const [x, y] = value as number[];\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n return;\n }\n for (const inner of value) visitPositions(inner);\n };\n const visitGeometry = (geometry: Geometry | null | undefined): void => {\n if (!geometry) return;\n if (geometry.type === 'GeometryCollection') geometry.geometries.forEach(visitGeometry);\n else visitPositions(geometry.coordinates);\n };\n for (const feature of collection.features ?? []) visitGeometry(feature?.geometry);\n return minX <= maxX ? [minX, minY, maxX, maxY] : undefined;\n}\n\n/**\n * The data adapter `AutkGrammar` runs. Its `resolveSource(db, source)` loads one entry of a spec's `data` into the\n * autk-db database `db` (a new one when `db` is undefined), in the entry's workspace, which it leaves current, and\n * returns the database.\n *\n * A host calls it to load a spec's tables exactly as the grammar does, for example on a server without a map: the\n * `./data` entry exports it with autk-db as its only import. `targets.db` names an element that lists the tables\n * after each load. `cache`, when given, receives each GeoJSON table and each table a join wrote, under\n * {@link tableKey}.\n */\nexport function createDataAdapter(targets?: Targets, cache?: GeoJsonCache): DataAdapter {\n\n function print(db: AutkDb, targets?: Targets): void {\n if(!targets || !targets.db)\n return\n\n const div = document.getElementById(targets.db);\n if (div) {\n const tables = db.getTablesMetadata();\n\n div.innerHTML += `<ul>`;\n for (const table of tables) {\n div.innerHTML += `<li>${table.name}: (${table.source}, ${table.type}) </li>`;\n }\n div.innerHTML += `</ul>`;\n\n div.innerHTML += `<p>Number of tables: ${tables.length}</p>`;\n }\n }\n\n return {\n async resolveSource(context: AutkDb | undefined, spec: DataSourceSpec): Promise<AutkDb | undefined> {\n\n let db = context;\n\n if(!db){\n db = new AutkDb();\n await db.init();\n }\n\n const { workspace } = spec as { workspace?: string };\n await enterWorkspace(db, workspace);\n\n let {type, workspace: _workspace, ...rest_spec} = spec as DataSourceSpec & { workspace?: string };\n\n switch (type) {\n case 'osm':\n await db.loadOsm(toLoadOsmParams(rest_spec as OsmDataSourceSpec));\n print(db, targets);\n return db;\n case 'csv':\n await db.loadCsv(rest_spec as CsvDataSourceSpec);\n print(db, targets);\n return db;\n case 'json':\n await db.loadJson(rest_spec as JsonDataSourceSpec);\n print(db, targets);\n return db;\n case 'geojson': {\n const geojsonSpec = rest_spec as CustomDataSourceSpec;\n let geojsonData: FeatureCollection | undefined;\n\n if (geojsonSpec.geojsonFileUrl) {\n const response = await fetch(geojsonSpec.geojsonFileUrl);\n geojsonData = await response.json() as FeatureCollection;\n } else {\n // The inline type allows a feature whose geometry is null, which autk-db refuses: loadableCollection\n // gives such a feature an empty geometry before autk-db loads it.\n geojsonData = geojsonSpec.geojsonObject as FeatureCollection | undefined;\n }\n\n if (cache && geojsonData) cache.set(tableKey(workspace, geojsonSpec.outputTableName), geojsonData);\n\n // Pass the fetched object directly so autk-db doesn't need to re-fetch, as autk-db loads it (see\n // loadableCollection). The cache keeps the source's own rows, in their order, for its plots.\n const loadSpec = (geojsonData\n ? (() => { const s = { ...geojsonSpec, geojsonObject: loadableCollection(geojsonData) }; delete s.geojsonFileUrl; return s; })()\n : geojsonSpec) as LoadGeojsonParams;\n\n // Degrees put every y within -90 to 90, so a y outside it shows a layer in another CRS. The\n // transform makes such a y infinite, and autk-db would refuse the layer with a grid error.\n // A longitude past 180 is not checked: the transform wraps it.\n const readAsDegrees = /^EPSG:4326$/i.test(loadSpec.coordinateFormat ?? 'EPSG:4326');\n const extent = geojsonData && readAsDegrees ? extentOf(geojsonData) : undefined;\n if (extent && (extent[1] < -90 || extent[3] > 90)) {\n throw new Error(\n `GeoJSON layer \"${loadSpec.outputTableName}\" has y coordinates outside -90 to 90 ` +\n `(bbox: [${extent.join(', ')}]), so they cannot be EPSG:4326 degrees. ${crsAdvice(loadSpec.coordinateFormat)}`\n );\n }\n\n try {\n await db.loadGeojson(loadSpec);\n } catch (err) {\n throw new Error(`Failed to load GeoJSON layer \"${loadSpec.outputTableName}\": ${err instanceof Error ? err.message : String(err)}`);\n }\n\n // Validate that the loaded geometry is within the workspace CRS extent.\n // A bounding box outside the valid world extent indicates a CRS mismatch.\n try {\n const bbox = await db.getBoundingBoxFromLayer(loadSpec.outputTableName);\n const WORLD_EXTENT = 25_000_000; // generous bound for DEFAULT_WORKSPACE_COORDINATE_FORMAT (EPSG:3395)\n if (\n !isFinite(bbox.minLon) || !isFinite(bbox.minLat) ||\n !isFinite(bbox.maxLon) || !isFinite(bbox.maxLat) ||\n Math.abs(bbox.minLon) > WORLD_EXTENT || Math.abs(bbox.maxLon) > WORLD_EXTENT ||\n Math.abs(bbox.minLat) > WORLD_EXTENT || Math.abs(bbox.maxLat) > WORLD_EXTENT\n ) {\n throw new Error(\n `Geometry bounding box after transform is invalid for layer \"${loadSpec.outputTableName}\" ` +\n `(bbox: [${bbox.minLon}, ${bbox.minLat}, ${bbox.maxLon}, ${bbox.maxLat}]). ` +\n `${crsAdvice(loadSpec.coordinateFormat)} ` +\n `The workspace uses ${DEFAULT_WORKSPACE_COORDINATE_FORMAT}; input is expected in EPSG:4326 by default.`\n );\n }\n } catch (bboxErr) {\n if (bboxErr instanceof Error && bboxErr.message.includes('bounding box after transform')) throw bboxErr;\n // getBoundingBoxFromLayer failed (empty table, unsupported layer type, etc.): skip validation\n }\n print(db, targets);\n return db;\n }\n case 'geotiff':\n await db.loadGeoTiff(rest_spec as GeoTiffDataSourceSpec);\n print(db, targets);\n return db;\n case 'heatmap': {\n const hm = rest_spec as HeatmapSourceSpec;\n // The schema refuses collect in a heatmap, but a spec that was not checked against it reaches here.\n if (hm.groupBy?.some((group) => (group.aggregateFn as string | undefined) === 'collect'))\n throw new Error(`Heatmap \"${hm.outputTableName}\": aggregateFn \"collect\" lists the rows near a cell, and a cell holds one value; use sum, avg, count, min, max or weighted.`);\n await db.buildHeatmap({\n tableJoinName: hm.joinDataRef,\n near: hm.near,\n outputTableName: hm.outputTableName,\n grid: hm.grid,\n ...(hm.groupBy && { groupBy: hm.groupBy }),\n });\n print(db, targets);\n return db;\n }\n case 'join': {\n const jn = rest_spec as JoinSourceSpec;\n await db.spatialQuery({\n tableRootName: jn.dataRef,\n tableJoinName: jn.joinDataRef,\n ...(jn.near && { near: jn.near }),\n ...(jn.groupBy && { groupBy: jn.groupBy }),\n });\n if (cache) {\n const updated = await db.getLayer(jn.dataRef);\n cache.set(tableKey(workspace, jn.dataRef), updated);\n }\n print(db, targets);\n return db;\n }\n default:\n return\n }\n }\n }\n}\n"],"names":["enterWorkspace","db","workspace","name","DEFAULT_WORKSPACE_NAME","tableKey","featureIds","features","own","feature","given","index","id","NO_GEOMETRY","loadableCollection","collection","ids","changed","loadable","first","queryAreaOf","spec","queryArea","refuse","message","box","value","west","south","east","north","toLoadOsmParams","autoLoadLayers","rest","crsAdvice","coordinateFormat","extentOf","minX","minY","maxX","maxY","visitPositions","x","y","inner","visitGeometry","geometry","createDataAdapter","targets","cache","print","div","tables","table","context","AutkDb","type","_workspace","rest_spec","geojsonSpec","geojsonData","loadSpec","s","readAsDegrees","extent","err","bbox","WORLD_EXTENT","DEFAULT_WORKSPACE_COORDINATE_FORMAT","bboxErr","hm","group","jn","updated"],"mappings":";AAUA,eAAsBA,EAAeC,GAAYC,GAAmC;AAChF,QAAMC,IAAOD,KAAaE;AAC1B,EAAIH,EAAG,0BAA0BE,KAAM,MAAMF,EAAG,aAAaE,CAAI;AACrE;AAOO,SAASE,EAASH,GAA+BC,GAAsB;AAC1E,SAAOD,MAAc,UAAaA,MAAcE,IAAyBD,IAAO,GAAGD,CAAS,IAAIC,CAAI;AACxG;ACPO,SAASG,EAAWC,GAA2E;AAClG,QAAMC,wBAAU,IAAA;AAChB,aAAWC,KAAWF;AAClB,IAAIE,GAAS,MAAM,QAAMD,EAAI,IAAI,KAAK,UAAUC,EAAQ,EAAE,CAAC;AAE/D,QAAMC,wBAAY,IAAA;AAClB,SAAOH,EAAS,IAAI,CAACE,GAASE,MAAU;AACpC,QAAIF,GAAS,MAAM,KAAM,QAAOA,EAAQ;AACxC,QAAIG,IAAK,gBAAgBD,CAAK;AAC9B,WAAOH,EAAI,IAAI,KAAK,UAAUI,CAAE,CAAC,KAAKF,EAAM,IAAI,KAAK,UAAUE,CAAE,CAAC,IAAG,CAAAA,IAAK,GAAGA,CAAE;AAC/E,WAAAF,EAAM,IAAI,KAAK,UAAUE,CAAE,CAAC,GACrBA;AAAA,EACX,CAAC;AACL;ACnBA,MAAMC,IAAwB,EAAE,MAAM,sBAAsB,YAAY,CAAA,EAAC;AAYzE,SAASC,EAAmBC,GAAkD;AAC1E,QAAMR,IAAWQ,EAAW,YAAY,CAAA,GAClCC,IAAMV,EAAWC,CAAQ;AAC/B,MAAIU,IAAU;AACd,QAAMC,IAAWX,EAAS,IAAI,CAACE,GAASE,MAChCF,KAAW,QAASA,EAAQ,MAAM,QAAQA,EAAQ,YAAY,OAAcA,KAChFQ,I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,UAEpG;AACA,iBAAAnB,EAAMjD,GAAI+C,CAAO,GACV/C;AAAA,QACX;AAAA,QACA,KAAK;AACD,uBAAMA,EAAG,YAAYyD,CAAkC,GACvDR,EAAMjD,GAAI+C,CAAO,GACV/C;AAAA,QACX,KAAK,WAAW;AACZ,gBAAMqE,IAAKZ;AAEX,cAAIY,EAAG,SAAS,KAAK,CAACC,MAAWA,EAAM,gBAAuC,SAAS;AACnF,kBAAM,IAAI,MAAM,YAAYD,EAAG,eAAe,6HAA6H;AAC/K,uBAAMrE,EAAG,aAAa;AAAA,YAClB,eAAeqE,EAAG;AAAA,YAClB,MAAMA,EAAG;AAAA,YACT,iBAAiBA,EAAG;AAAA,YACpB,MAAMA,EAAG;AAAA,YACT,GAAIA,EAAG,WAAW,EAAE,SAASA,EAAG,QAAA;AAAA,UAAQ,CAC3C,GACDpB,EAAMjD,GAAI+C,CAAO,GACV/C;AAAA,QACX;AAAA,QACA,KAAK,QAAQ;AACT,gBAAMuE,IAAKd;AAOX,cANA,MAAMzD,EAAG,aAAa;AAAA,YAClB,eAAeuE,EAAG;AAAA,YAClB,eAAeA,EAAG;AAAA,YAClB,GAAIA,EAAG,QAAQ,EAAE,MAAMA,EAAG,KAAA;AAAA,YAC1B,GAAIA,EAAG,WAAW,EAAE,SAASA,EAAG,QAAA;AAAA,UAAQ,CAC3C,GACGvB,GAAO;AACP,kBAAMwB,IAAU,MAAMxE,EAAG,SAASuE,EAAG,OAAO;AAC5C,YAAAvB,EAAM,IAAI5C,EAASH,GAAWsE,EAAG,OAAO,GAAGC,CAAO;AAAA,UACtD;AACA,iBAAAvB,EAAMjD,GAAI+C,CAAO,GACV/C;AAAA,QACX;AAAA,QACA;AACI;AAAA,MAAA;AAAA,IAEZ;AAAA,EAAA;AAER;"}
1
+ {"version":3,"file":"autk-grammar-data.js","sources":["../../src/workspace.ts","../../src/rows.ts","../../src/adapters/data.ts"],"sourcesContent":["import { AutkDb, DEFAULT_WORKSPACE_NAME } from '@urban-toolkit/autk-db';\n\n/**\n * Makes `workspace` (the default one without a name) the workspace `db` works in; autk-db creates it on first use.\n * It calls autk-db's `setWorkspace` only when `getCurrentWorkspace()` names another one.\n *\n * Every adapter calls it before it reads or writes a table of a spec entry, with the entry's `workspace`. A host that\n * reads a spec's tables itself calls it the same way, since autk-db finds a table by its name in the current\n * workspace only.\n */\nexport async function enterWorkspace(db: AutkDb, workspace?: string): Promise<void> {\n const name = workspace ?? DEFAULT_WORKSPACE_NAME;\n if (db.getCurrentWorkspace() !== name) await db.setWorkspace(name);\n}\n\n/**\n * The key a table has in the grammar's caches: its name in the default workspace, `<workspace>/<name>` in another, so\n * two workspaces can hold tables of the same name. A host reads the caches it passes to `createDataAdapter` and\n * `createComputeAdapter` with it.\n */\nexport function tableKey(workspace: string | undefined, name: string): string {\n return workspace === undefined || workspace === DEFAULT_WORKSPACE_NAME ? name : `${workspace}/${name}`;\n}\n","import type { Feature } from 'geojson';\n\n/**\n * A selection passes between a plot and a map layer by the rows each drew, not by positions. A plot draws its table's\n * rows in the order the host handed them, while a map layer draws autk-db's export of the table, which can keep the\n * rows in an order of its own and leaves out those without a geometry, so one position can be another row in each\n * view. Each row is known in both by its feature id, which autk-db keeps in its export. Nothing here needs a GPU or a\n * database, so the unit tests run it in Node.\n */\n\n/**\n * The id autk-db gives each feature of a GeoJSON source: its own `id`, else `autk-feature-<index>`, with `-generated`\n * added while another feature has that id. The data adapter hands autk-db features that carry these ids, so autk-db\n * keeps them in its export whatever rule it would use itself.\n */\nexport function featureIds(features: readonly (Feature | null | undefined)[]): Array<string | number> {\n const own = new Set<string>();\n for (const feature of features) {\n if (feature?.id != null) own.add(JSON.stringify(feature.id));\n }\n const given = new Set<string>();\n return features.map((feature, index) => {\n if (feature?.id != null) return feature.id;\n let id = `autk-feature-${index}`;\n while (own.has(JSON.stringify(id)) || given.has(JSON.stringify(id))) id = `${id}-generated`;\n given.add(JSON.stringify(id));\n return id;\n });\n}\n\n/**\n * The key of each row of a collection, which names the row in every view of its table: its id as {@link featureIds}\n * gives it, written as JSON so that `3` and `\"3\"` stay apart, and the times that id came before when it repeats.\n */\nexport function rowKeys(features: readonly (Feature | null | undefined)[]): string[] {\n const seen = new Map<string, number>();\n return featureIds(features).map((id) => {\n const json = JSON.stringify(id);\n const before = seen.get(json) ?? 0;\n seen.set(json, before + 1);\n return before === 0 ? json : `${json} ${before}`;\n });\n}\n\n/** Each key's positions, built once for each list of keys. */\nconst positionsByKey = new WeakMap<readonly string[], Map<string, number[]>>();\n\nfunction positionsOf(keys: readonly string[]): Map<string, number[]> {\n let positions = positionsByKey.get(keys);\n if (positions) return positions;\n positions = new Map();\n keys.forEach((key, position) => {\n const list = positions!.get(key);\n if (list) list.push(position);\n else positions!.set(key, [position]);\n });\n positionsByKey.set(keys, positions);\n return positions;\n}\n\n/**\n * The positions in one view of the rows at the positions `ids` in another, each view given by the key of the row at\n * each of its positions. A row the other view does not draw has no position there, and a row it draws at several\n * positions has each of them.\n */\nexport function translateIds(ids: readonly number[], from: readonly string[], to: readonly string[]): number[] {\n const positions = positionsOf(to);\n const translated = new Set<number>();\n for (const id of ids) {\n const key = from[id];\n if (key === undefined) continue;\n for (const position of positions.get(key) ?? []) translated.add(position);\n }\n return [...translated];\n}\n","import { CsvDataSourceSpec, CustomDataSourceSpec, DataAdapter, DataSourceSpec, DropSourceSpec, GeoTiffDataSourceSpec, HeatmapSourceSpec, JoinSourceSpec, JsonDataSourceSpec, OsmDataSourceSpec, SqlSourceSpec, UpdateSourceSpec, WorkspaceSpec } from '@urban-toolkit/the-urban-grammar';\nimport { AutkDb, DEFAULT_WORKSPACE_NAME, isRenderableTable, isVectorTable } from '@urban-toolkit/autk-db';\nimport type { LoadGeojsonParams, Table } from '@urban-toolkit/autk-db';\nimport type { FeatureCollection, Geometry } from 'geojson';\nimport { Targets, GeoJsonCache } from '../types';\nimport { enterWorkspace, tableKey } from '../workspace';\nimport { featureIds } from '../rows';\n\n/** An empty geometry: a GeometryCollection with none in it, which a map draws as nothing. */\nconst NO_GEOMETRY: Geometry = { type: 'GeometryCollection', geometries: [] };\n\n/**\n * A GeoJSON source's collection as autk-db loads it, row for row.\n *\n * - Each feature carries the id autk-db gives it (see `featureIds`), from its place in the source. autk-db keeps the\n * id in its export, so a row a map draws from the export is found among the source's own rows, which a plot draws.\n * - autk-db refuses a feature whose geometry is null, which GeoJSON allows, so such a feature gets an empty one: a map\n * draws nothing for it, and a plot still counts it.\n * - autk-db reads the layer's type off the first feature, so a first feature without a geometry trades places with the\n * first that has one. Each keeps its id, so the rows are still found by it.\n */\nfunction loadableCollection(collection: FeatureCollection): FeatureCollection {\n const features = collection.features ?? [];\n const ids = featureIds(features);\n let changed = false;\n const loadable = features.map((feature, index) => {\n if (feature == null || (feature.id != null && feature.geometry != null)) return feature;\n changed = true;\n return { ...feature, id: ids[index], geometry: feature.geometry ?? NO_GEOMETRY };\n });\n const first = features.findIndex((feature) => feature?.geometry != null);\n if (first > 0 && features[0] != null && features[0].geometry == null) {\n [loadable[0], loadable[first]] = [loadable[first], loadable[0]];\n changed = true;\n }\n return changed ? { ...collection, features: loadable } : collection;\n}\n\n/**\n * The query area autk-db reads: `{ bbox }` or `{ geocodeArea, areas }`. autk-db takes any area with a\n * `bbox` key as a box, so a box that also names areas, or that is not [west, south, east, north] in\n * degrees with west less than east and south less than north, is refused here.\n */\nfunction queryAreaOf(spec: OsmDataSourceSpec): OsmDataSourceSpec['queryArea'] {\n const { queryArea } = spec;\n if (queryArea.bbox === undefined) return { geocodeArea: queryArea.geocodeArea, areas: queryArea.areas };\n\n const refuse = (message: string) => new Error(`OSM source \"${spec.outputTableName}\": ${message}`);\n if (queryArea.geocodeArea !== undefined || queryArea.areas !== undefined)\n throw refuse('queryArea takes either bbox or geocodeArea with areas, not both.');\n const box: unknown = queryArea.bbox;\n if (!Array.isArray(box) || box.length !== 4 || !box.every((value) => typeof value === 'number' && Number.isFinite(value)))\n throw refuse('queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.');\n const [west, south, east, north] = queryArea.bbox;\n if (Math.abs(west) > 180 || Math.abs(east) > 180)\n throw refuse('queryArea.bbox west and east must be longitudes from -180 to 180.');\n if (Math.abs(south) > 90 || Math.abs(north) > 90)\n throw refuse('queryArea.bbox south and north must be latitudes from -90 to 90.');\n if (west >= east)\n throw refuse(`queryArea.bbox west (${west}) must be less than east (${east}); a box across the antimeridian is not supported.`);\n if (south >= north)\n throw refuse(`queryArea.bbox south (${south}) must be less than north (${north}).`);\n return { bbox: [west, south, east, north] };\n}\n\n/**\n * Maps an OSM source onto autk-db's parameters, which always expect `autoLoadLayers`, with the CRS of the source's\n * coordinates when it gives one, and no longer take `dropOsmTable`. autk-db reads `tagSets` from the Overpass API only,\n * so a source that also names a PBF extract is refused here, by its name.\n */\nfunction toLoadOsmParams(spec: OsmDataSourceSpec) {\n const { autoLoadLayers, ...rest } = spec;\n if (spec.pbfFileUrl !== undefined && (spec.tagSets?.length ?? 0) > 0)\n throw new Error(`OSM source \"${spec.outputTableName}\": tagSets are read from the Overpass API only, so a source with pbfFileUrl cannot take them.`);\n return {\n ...rest,\n queryArea: queryAreaOf(spec),\n autoLoadLayers: {\n layers: autoLoadLayers?.layers ?? [],\n ...(autoLoadLayers?.coordinateFormat !== undefined && { coordinateFormat: autoLoadLayers.coordinateFormat }),\n },\n };\n}\n\n/**\n * The CRS advice. Only a bounding-box check gives it, when the box shows that a layer's coordinates\n * are not in the CRS it was loaded as; any other load error is autk-db's own message.\n */\nfunction crsAdvice(coordinateFormat: string | undefined): string {\n const assumed = coordinateFormat\n ? `coordinateFormat is set to \"${coordinateFormat}\"`\n : 'no coordinateFormat was specified, so it defaults to EPSG:4326 (WGS84 per RFC 7946)';\n return `${assumed}. Verify that coordinateFormat matches the actual CRS of the input data.`;\n}\n\n/** How a message names a workspace: the default one, or another by its name. */\nfunction workspaceLabel(name: string | undefined): string {\n return name === undefined || name === DEFAULT_WORKSPACE_NAME ? 'the default workspace' : `the workspace \"${name}\"`;\n}\n\n/** A feature property's value as SQL's `->>` reads it: a string as it is, any other value as its JSON. */\nfunction propertyText(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n return typeof value === 'string' ? value : JSON.stringify(value);\n}\n\n/**\n * The rows of an update of a layer keyed by a feature property, `properties.<name>`, keyed instead by the feature ids of\n * the table's rows they match. autk-db 4.1.1 matches such a key with `table.properties->>'name' =\n * staging.properties->>'name'`, which DuckDB reads so that the comparison is NULL: no row matches, and nothing is\n * updated. It matches a plain column as written. So each given feature goes to every row whose property has its value,\n * compared as text, as `->>` reads it, under that row's id in autk-db's export: its `geojson_id`, else its `id`.\n */\nasync function updateByFeatureId(db: AutkDb, table: Table, rows: FeatureCollection, property: string): Promise<{ data: FeatureCollection, idColumn: string }> {\n const ids = new Map<string, Array<string | number>>();\n for (const row of (await db.getLayer(table.name)).features) {\n const key = propertyText((row.properties as Record<string, unknown> | null)?.[property]);\n if (key === undefined) continue;\n if (row.id === undefined || row.id === null)\n throw new Error('its rows have no feature id to update them by.');\n ids.set(key, [...(ids.get(key) ?? []), row.id]);\n }\n const features = rows.features.flatMap((feature) => {\n const key = propertyText((feature.properties as Record<string, unknown> | null)?.[property]);\n return key === undefined ? [] : (ids.get(key) ?? []).map((id) => ({ ...feature, id }));\n });\n const idColumn = table.columns.some((column) => column.name === 'geojson_id') ? 'geojson_id' : 'id';\n return { data: { ...rows, features }, idColumn };\n}\n\n/** The database a source loads into: `context`, else a new one. */\nasync function database(context: AutkDb | undefined): Promise<AutkDb> {\n if (context) return context;\n const db = new AutkDb();\n await db.init();\n return db;\n}\n\n/** The [minX, minY, maxX, maxY] of every position in a collection, or undefined when it has none. */\nexport function extentOf(collection: FeatureCollection): [number, number, number, number] | undefined {\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n const visitPositions = (value: unknown): void => {\n if (!Array.isArray(value)) return;\n if (typeof value[0] === 'number') {\n const [x, y] = value as number[];\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n return;\n }\n for (const inner of value) visitPositions(inner);\n };\n const visitGeometry = (geometry: Geometry | null | undefined): void => {\n if (!geometry) return;\n if (geometry.type === 'GeometryCollection') geometry.geometries.forEach(visitGeometry);\n else visitPositions(geometry.coordinates);\n };\n for (const feature of collection.features ?? []) visitGeometry(feature?.geometry);\n return minX <= maxX ? [minX, minY, maxX, maxY] : undefined;\n}\n\n/**\n * The data adapter `AutkGrammar` runs. Its `resolveSource(db, source)` loads one entry of a spec's `data` into the\n * autk-db database `db` (a new one when `db` is undefined), in the entry's workspace, which it leaves current, and\n * returns the database. Its `resolveWorkspaces(db, workspaces)` sets each workspace a spec's `workspaces` lists to its\n * CRS and precision grid, before the first source loads, leaves the default workspace current and returns the database.\n *\n * A host calls it to load a spec's tables exactly as the grammar does, for example on a server without a map: the\n * `./data` entry exports it with autk-db as its only import. `targets.db` names an element that lists the tables\n * after each load. `cache`, when given, receives each GeoJSON table and each table a join or an update wrote, under\n * {@link tableKey}, and loses each table a `sql` source replaces or a `drop` source drops.\n */\nexport function createDataAdapter(targets?: Targets, cache?: GeoJsonCache): Required<DataAdapter> {\n\n function print(db: AutkDb, targets?: Targets): void {\n if(!targets || !targets.db)\n return\n\n const div = document.getElementById(targets.db);\n if (div) {\n const tables = db.getTablesMetadata();\n\n div.innerHTML += `<ul>`;\n for (const table of tables) {\n div.innerHTML += `<li>${table.name}: (${table.source}, ${table.type}) </li>`;\n }\n div.innerHTML += `</ul>`;\n\n div.innerHTML += `<p>Number of tables: ${tables.length}</p>`;\n }\n }\n\n /**\n * Puts a table a source changed in `cache` as autk-db now exports it, as a join's, or takes it out when autk-db does\n * not export it as a layer: the plots read a table from the cache before autk-db.\n */\n async function recache(db: AutkDb, workspace: string | undefined, name: string): Promise<void> {\n if (!cache) return;\n const key = tableKey(workspace, name);\n const table = db.getTablesMetadata().find((candidate) => candidate.name === name);\n if (table && isRenderableTable(table)) cache.set(key, await db.getLayer(name));\n else cache.delete(key);\n }\n\n return {\n async resolveWorkspaces(context: AutkDb | undefined, workspaces: WorkspaceSpec[]): Promise<AutkDb> {\n const db = await database(context);\n const named = new Set<string>();\n for (const { name, coordinateFormat, precisionGrid } of workspaces) {\n const workspace = name ?? DEFAULT_WORKSPACE_NAME;\n if (named.has(workspace))\n throw new Error(`workspaces sets ${workspaceLabel(name)} twice; give each workspace one entry.`);\n named.add(workspace);\n // autk-db creates the workspace with this configuration, or sets it on the one that exists while it\n // holds no table, the default workspace among them.\n try {\n await db.setWorkspace(workspace, { coordinateFormat, precisionGrid });\n } catch (err) {\n throw new Error(`workspaces, ${workspaceLabel(name)}: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n // Each source, compute pass, map and plot enters its own workspace.\n await enterWorkspace(db);\n return db;\n },\n\n async resolveSource(context: AutkDb | undefined, spec: DataSourceSpec): Promise<AutkDb> {\n\n const db = await database(context);\n\n const { workspace } = spec as { workspace?: string };\n await enterWorkspace(db, workspace);\n\n let {type, workspace: _workspace, ...rest_spec} = spec as DataSourceSpec & { workspace?: string };\n\n switch (type) {\n case 'osm':\n await db.loadOsm(toLoadOsmParams(rest_spec as OsmDataSourceSpec));\n print(db, targets);\n return db;\n case 'csv':\n await db.loadCsv(rest_spec as CsvDataSourceSpec);\n print(db, targets);\n return db;\n case 'json':\n await db.loadJson(rest_spec as JsonDataSourceSpec);\n print(db, targets);\n return db;\n case 'geojson': {\n const geojsonSpec = rest_spec as CustomDataSourceSpec;\n let geojsonData: FeatureCollection | undefined;\n\n if (geojsonSpec.geojsonFileUrl) {\n const response = await fetch(geojsonSpec.geojsonFileUrl);\n geojsonData = await response.json() as FeatureCollection;\n } else {\n // The inline type allows a feature whose geometry is null, which autk-db refuses: loadableCollection\n // gives such a feature an empty geometry before autk-db loads it.\n geojsonData = geojsonSpec.geojsonObject as FeatureCollection | undefined;\n }\n\n if (cache && geojsonData) cache.set(tableKey(workspace, geojsonSpec.outputTableName), geojsonData);\n\n // Pass the fetched object directly so autk-db doesn't need to re-fetch, as autk-db loads it (see\n // loadableCollection). The cache keeps the source's own rows, in their order, for its plots.\n const loadSpec = (geojsonData\n ? (() => { const s = { ...geojsonSpec, geojsonObject: loadableCollection(geojsonData) }; delete s.geojsonFileUrl; return s; })()\n : geojsonSpec) as LoadGeojsonParams;\n\n // Degrees put every y within -90 to 90, so a y outside it shows a layer in another CRS. The\n // transform makes such a y infinite, and autk-db would refuse the layer with a grid error.\n // A longitude past 180 is not checked: the transform wraps it.\n const readAsDegrees = /^EPSG:4326$/i.test(loadSpec.coordinateFormat ?? 'EPSG:4326');\n const extent = geojsonData && readAsDegrees ? extentOf(geojsonData) : undefined;\n if (extent && (extent[1] < -90 || extent[3] > 90)) {\n throw new Error(\n `GeoJSON layer \"${loadSpec.outputTableName}\" has y coordinates outside -90 to 90 ` +\n `(bbox: [${extent.join(', ')}]), so they cannot be EPSG:4326 degrees. ${crsAdvice(loadSpec.coordinateFormat)}`\n );\n }\n\n try {\n await db.loadGeojson(loadSpec);\n } catch (err) {\n throw new Error(`Failed to load GeoJSON layer \"${loadSpec.outputTableName}\": ${err instanceof Error ? err.message : String(err)}`);\n }\n\n // Validate that the loaded geometry is within the workspace CRS extent.\n // A bounding box outside the valid world extent indicates a CRS mismatch.\n try {\n const bbox = await db.getBoundingBoxFromLayer(loadSpec.outputTableName);\n const WORLD_EXTENT = 25_000_000; // generous bound for World Mercator (EPSG:3395), autk-db's default CRS\n if (\n !isFinite(bbox.minLon) || !isFinite(bbox.minLat) ||\n !isFinite(bbox.maxLon) || !isFinite(bbox.maxLat) ||\n Math.abs(bbox.minLon) > WORLD_EXTENT || Math.abs(bbox.maxLon) > WORLD_EXTENT ||\n Math.abs(bbox.minLat) > WORLD_EXTENT || Math.abs(bbox.maxLat) > WORLD_EXTENT\n ) {\n throw new Error(\n `Geometry bounding box after transform is invalid for layer \"${loadSpec.outputTableName}\" ` +\n `(bbox: [${bbox.minLon}, ${bbox.minLat}, ${bbox.maxLon}, ${bbox.maxLat}]). ` +\n `${crsAdvice(loadSpec.coordinateFormat)} ` +\n `The workspace uses ${db.getWorkspaceConfiguration().coordinateFormat}; input is expected in EPSG:4326 by default.`\n );\n }\n } catch (bboxErr) {\n if (bboxErr instanceof Error && bboxErr.message.includes('bounding box after transform')) throw bboxErr;\n // getBoundingBoxFromLayer failed (empty table, unsupported layer type, etc.): skip validation\n }\n print(db, targets);\n return db;\n }\n case 'geotiff':\n await db.loadGeoTiff(rest_spec as GeoTiffDataSourceSpec);\n print(db, targets);\n return db;\n case 'heatmap': {\n const hm = rest_spec as HeatmapSourceSpec;\n // The schema refuses collect in a heatmap, but a spec that was not checked against it reaches here.\n if (hm.groupBy?.some((group) => (group.aggregateFn as string | undefined) === 'collect'))\n throw new Error(`Heatmap \"${hm.outputTableName}\": aggregateFn \"collect\" lists the rows near a cell, and a cell holds one value; use sum, avg, count, min, max or weighted.`);\n await db.buildHeatmap({\n tableJoinName: hm.joinDataRef,\n near: hm.near,\n outputTableName: hm.outputTableName,\n grid: hm.grid,\n ...(hm.groupBy && { groupBy: hm.groupBy }),\n });\n print(db, targets);\n return db;\n }\n case 'join': {\n const jn = rest_spec as JoinSourceSpec;\n await db.spatialQuery({\n tableRootName: jn.dataRef,\n tableJoinName: jn.joinDataRef,\n ...(jn.near && { near: jn.near }),\n ...(jn.groupBy && { groupBy: jn.groupBy }),\n });\n if (cache) {\n const updated = await db.getLayer(jn.dataRef);\n cache.set(tableKey(workspace, jn.dataRef), updated);\n }\n print(db, targets);\n return db;\n }\n case 'sql': {\n const sql = rest_spec as SqlSourceSpec;\n try {\n await db.rawQuery({\n query: sql.query,\n output: {\n type: 'CREATE_TABLE',\n tableName: sql.outputTableName,\n source: 'user',\n ...(sql.layerType !== undefined && { tableType: sql.layerType }),\n },\n });\n } catch (err) {\n throw new Error(`SQL source \"${sql.outputTableName}\": ${err instanceof Error ? err.message : String(err)}`);\n }\n // A query saved under the name of a GeoJSON table replaces it, so the plots no longer read its rows.\n cache?.delete(tableKey(workspace, sql.outputTableName));\n print(db, targets);\n return db;\n }\n case 'update': {\n const update = rest_spec as UpdateSourceSpec;\n const refuse = (message: string) => new Error(`Update of \"${update.dataRef}\": ${message}`);\n // The schema refuses these shapes too, but a spec that was not checked against it reaches here.\n if ((update.geojsonObject === undefined) === (update.jsonObject === undefined))\n throw refuse('give its rows in geojsonObject or in jsonObject, one of the two.');\n if (update.strategy === 'update' && !update.idColumn)\n throw refuse(\"the update strategy needs an idColumn, the column that matches a given row to the table's rows.\");\n let data = (update.geojsonObject ?? update.jsonObject) as FeatureCollection | Record<string, unknown>[];\n let idColumn = update.idColumn;\n try {\n // A layer keyed by a feature property is matched here, then updated by its rows' feature ids.\n const table = db.getTablesMetadata().find((candidate) => candidate.name === update.dataRef);\n if (update.strategy === 'update' && update.geojsonObject && idColumn?.startsWith('properties.') && table && isVectorTable(table)) {\n ({ data, idColumn } = await updateByFeatureId(db, table, update.geojsonObject as FeatureCollection, idColumn.slice('properties.'.length)));\n // No row has a given key, so the table stays as it is, as autk-db leaves it.\n if ((data as FeatureCollection).features.length === 0) {\n print(db, targets);\n return db;\n }\n }\n await db.updateTable({\n tableName: update.dataRef,\n data,\n strategy: update.strategy,\n ...(idColumn !== undefined && { idColumn }),\n });\n } catch (err) {\n throw refuse(err instanceof Error ? err.message : String(err));\n }\n await recache(db, workspace, update.dataRef);\n print(db, targets);\n return db;\n }\n case 'drop': {\n const drop = rest_spec as DropSourceSpec;\n // autk-db drops a table it does not hold without a word, so a name that names none is refused here.\n if (!db.getTablesMetadata().some((table) => table.name === drop.dataRef))\n throw new Error(`Drop of \"${drop.dataRef}\": ${workspaceLabel(workspace)} holds no table of that name.`);\n await db.removeLayer(drop.dataRef);\n cache?.delete(tableKey(workspace, drop.dataRef));\n print(db, targets);\n return db;\n }\n default:\n // The schema refuses any other type, but a spec that was not checked against it reaches here. Handing\n // the engine no database would make the next source start a new one, without the tables before it.\n throw new Error(`Unknown data source type \"${String(type)}\".`);\n }\n }\n }\n}\n"],"names":["enterWorkspace","db","workspace","name","DEFAULT_WORKSPACE_NAME","tableKey","featureIds","features","own","feature","given","index","id","NO_GEOMETRY","loadableCollection","collection","ids","changed","loadable","first","queryAreaOf","spec","queryArea","refuse","message","box","value","west","south","east","north","toLoadOsmParams","autoLoadLayers","rest","crsAdvice","coordinateFormat","workspaceLabel","propertyText","updateByFeatureId","table","rows","property","row","key","idColumn","column","database","context","AutkDb","extentOf","minX","minY","maxX","maxY","visitPositions","x","inner","visitGeometry","geometry","createDataAdapter","targets","cache","print","div","tables","recache","candidate","isRenderableTable","workspaces","named","precisionGrid","err","type","_workspace","rest_spec","geojsonSpec","geojsonData","loadSpec","s","readAsDegrees","extent","bbox","WORLD_EXTENT","bboxErr","hm","group","jn","updated","sql","update","data","isVectorTable","drop"],"mappings":";AAUA,eAAsBA,EAAeC,GAAYC,GAAmC;AAChF,QAAMC,IAAOD,KAAaE;AAC1B,EAAIH,EAAG,0BAA0BE,KAAM,MAAMF,EAAG,aAAaE,CAAI;AACrE;AAOO,SAASE,EAASH,GAA+BC,GAAsB;AAC1E,SAAOD,MAAc,UAAaA,MAAcE,IAAyBD,IAAO,GAAGD,CAAS,IAAIC,CAAI;AACxG;ACPO,SAASG,EAAWC,GAA2E;AAClG,QAAMC,wBAAU,IAAA;AAChB,aAAWC,KAAWF;AAClB,IAAIE,GAAS,MAAM,QAAMD,EAAI,IAAI,KAAK,UAAUC,EAAQ,EAAE,CAAC;AAE/D,QAAMC,wBAAY,IAAA;AAClB,SAAOH,EAAS,IAAI,CAACE,GAASE,MAAU;AACpC,QAAIF,GAAS,MAAM,KAAM,QAAOA,EAAQ;AACxC,QAAIG,IAAK,gBAAgBD,CAAK;AAC9B,WAAOH,EAAI,IAAI,KAAK,UAAUI,CAAE,CAAC,KAAKF,EAAM,IAAI,KAAK,UAAUE,CAAE,CAAC,IAAG,CAAAA,IAAK,GAAGA,CAAE;AAC/E,WAAAF,EAAM,IAAI,KAAK,UAAUE,CAAE,CAAC,GACrBA;AAAA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