@urban-toolkit/autk-grammar 4.4.1 → 5.0.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.
- package/README.md +275 -5
- package/build/autk-grammar-schema.json +945 -425
- package/dist/autk-grammar.js +752 -426
- package/dist/autk-grammar.js.map +1 -1
- package/dist/autk-grammar.umd.cjs +2 -2
- package/dist/autk-grammar.umd.cjs.map +1 -1
- package/dist/data/autk-grammar-data.cjs +2 -0
- package/dist/data/autk-grammar-data.cjs.map +1 -0
- package/dist/data/autk-grammar-data.d.ts +349 -0
- package/dist/data/autk-grammar-data.js +165 -0
- package/dist/data/autk-grammar-data.js.map +1 -0
- package/dist/index.d.ts +555 -75
- package/package.json +7 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("@urban-toolkit/autk-db");async function w(o,t){const a=t??h.DEFAULT_WORKSPACE_NAME;o.getCurrentWorkspace()!==a&&await o.setWorkspace(a)}function g(o,t){return o===void 0||o===h.DEFAULT_WORKSPACE_NAME?t:`${o}/${t}`}function A(o){const t=new Set;for(const c of o)c?.id!=null&&t.add(JSON.stringify(c.id));const a=new Set;return o.map((c,s)=>{if(c?.id!=null)return c.id;let e=`autk-feature-${s}`;for(;t.has(JSON.stringify(e))||a.has(JSON.stringify(e));)e=`${e}-generated`;return a.add(JSON.stringify(e)),e})}const $={type:"GeometryCollection",geometries:[]};function E(o){const t=o.features??[],a=A(t);let c=!1;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=t.findIndex(u=>u?.geometry!=null);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}function L(o){const{queryArea:t}=o;if(t.bbox===void 0)return{geocodeArea:t.geocodeArea,areas:t.areas};const a=l=>new Error(`OSM source "${o.outputTableName}": ${l}`);if(t.geocodeArea!==void 0||t.areas!==void 0)throw a("queryArea takes either bbox or geocodeArea with areas, not both.");const c=t.bbox;if(!Array.isArray(c)||c.length!==4||!c.every(l=>typeof l=="number"&&Number.isFinite(l)))throw a("queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.");const[s,e,u,r]=t.bbox;if(Math.abs(s)>180||Math.abs(u)>180)throw a("queryArea.bbox west and east must be longitudes from -180 to 180.");if(Math.abs(e)>90||Math.abs(r)>90)throw a("queryArea.bbox south and north must be latitudes from -90 to 90.");if(s>=u)throw a(`queryArea.bbox west (${s}) must be less than east (${u}); a box across the antimeridian is not supported.`);if(e>=r)throw a(`queryArea.bbox south (${e}) must be less than north (${r}).`);return{bbox:[s,e,u,r]}}function N(o){const{autoLoadLayers:t,...a}=o;return{...a,queryArea:L(o),autoLoadLayers:{layers:t?.layers??[]}}}function p(o){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.`}function S(o){let t=1/0,a=1/0,c=-1/0,s=-1/0;const e=r=>{if(Array.isArray(r)){if(typeof r[0]=="number"){const[l,d]=r;l<t&&(t=l),l>c&&(c=l),d<a&&(a=d),d>s&&(s=d);return}for(const l of r)e(l)}},u=r=>{r&&(r.type==="GeometryCollection"?r.geometries.forEach(u):e(r.coordinates))};for(const r of o.features??[])u(r?.geometry);return t<=c?[t,a,c,s]:void 0}function T(o,t){function a(c,s){if(!s||!s.db)return;const e=document.getElementById(s.db);if(e){const u=c.getTablesMetadata();e.innerHTML+="<ul>";for(const r of u)e.innerHTML+=`<li>${r.name}: (${r.source}, ${r.type}) </li>`;e.innerHTML+="</ul>",e.innerHTML+=`<p>Number of tables: ${u.length}</p>`}}return{async resolveSource(c,s){let e=c;e||(e=new h.AutkDb,await e.init());const{workspace:u}=s;await w(e,u);let{type:r,workspace:l,...d}=s;switch(r){case"osm":return await e.loadOsm(N(d)),a(e,o),e;case"csv":return await e.loadCsv(d),a(e,o),e;case"json":return await e.loadJson(d),a(e,o),e;case"geojson":{const n=d;let f;n.geojsonFileUrl?f=await(await fetch(n.geojsonFileUrl)).json():f=n.geojsonObject,t&&f&&t.set(g(u,n.outputTableName),f);const b=f?(()=>{const i={...n,geojsonObject:E(f)};return delete i.geojsonFileUrl,i})():n,x=/^EPSG:4326$/i.test(b.coordinateFormat??"EPSG:4326"),m=f&&x?S(f):void 0;if(m&&(m[1]<-90||m[3]>90))throw new Error(`GeoJSON layer "${b.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${m.join(", ")}]), so they cannot be EPSG:4326 degrees. ${p(b.coordinateFormat)}`);try{await e.loadGeojson(b)}catch(i){throw new Error(`Failed to load GeoJSON layer "${b.outputTableName}": ${i instanceof Error?i.message:String(i)}`)}try{const i=await e.getBoundingBoxFromLayer(b.outputTableName),y=25e6;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)throw new Error(`Geometry bounding box after transform is invalid for layer "${b.outputTableName}" (bbox: [${i.minLon}, ${i.minLat}, ${i.maxLon}, ${i.maxLat}]). ${p(b.coordinateFormat)} The workspace uses ${h.DEFAULT_WORKSPACE_COORDINATE_FORMAT}; input is expected in EPSG:4326 by default.`)}catch(i){if(i instanceof Error&&i.message.includes("bounding box after transform"))throw i}return a(e,o),e}case"geotiff":return await e.loadGeoTiff(d),a(e,o),e;case"heatmap":{const n=d;if(n.groupBy?.some(f=>f.aggregateFn==="collect"))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.`);return await e.buildHeatmap({tableJoinName:n.joinDataRef,near:n.near,outputTableName:n.outputTableName,grid:n.grid,...n.groupBy&&{groupBy:n.groupBy}}),a(e,o),e}case"join":{const n=d;if(await e.spatialQuery({tableRootName:n.dataRef,tableJoinName:n.joinDataRef,...n.near&&{near:n.near},...n.groupBy&&{groupBy:n.groupBy}}),t){const f=await e.getLayer(n.dataRef);t.set(g(u,n.dataRef),f)}return a(e,o),e}default:return}}}}exports.createDataAdapter=T;exports.enterWorkspace=w;exports.tableKey=g;
|
|
2
|
+
//# sourceMappingURL=autk-grammar-data.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"autk-grammar-data.cjs","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":"0HAUA,eAAsBA,EAAeC,EAAYC,EAAmC,CAChF,MAAMC,EAAOD,GAAaE,EAAAA,uBACtBH,EAAG,wBAA0BE,GAAM,MAAMF,EAAG,aAAaE,CAAI,CACrE,CAOO,SAASE,EAASH,EAA+BC,EAAsB,CAC1E,OAAOD,IAAc,QAAaA,IAAcE,EAAAA,uBAAyBD,EAAO,GAAGD,CAAS,IAAIC,CAAI,EACxG,CCPO,SAASG,EAAWC,EAA2E,CAClG,MAAMC,MAAU,IAChB,UAAWC,KAAWF,EACdE,GAAS,IAAM,MAAMD,EAAI,IAAI,KAAK,UAAUC,EAAQ,EAAE,CAAC,EAE/D,MAAMC,MAAY,IAClB,OAAOH,EAAS,IAAI,CAACE,EAASE,IAAU,CACpC,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EAAI+C,CAAO,EACV/C,CACX,CACA,QACI,MAAA,CAEZ,CAAA,CAER"}
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
import { AutkDb } from '@urban-toolkit/autk-db';
|
|
2
|
+
import { BBox } from 'geojson';
|
|
3
|
+
import { FeatureCollection } from 'geojson';
|
|
4
|
+
import { GeoJsonProperties } from 'geojson';
|
|
5
|
+
import { Geometry } from 'geojson';
|
|
6
|
+
|
|
7
|
+
/** How joined rows are combined per feature. */
|
|
8
|
+
declare type AggregateFunction = 'sum' | 'avg' | 'count' | 'min' | 'max' | 'weighted' | 'collect';
|
|
9
|
+
|
|
10
|
+
declare interface BoundingBox {
|
|
11
|
+
minLon: number;
|
|
12
|
+
minLat: number;
|
|
13
|
+
maxLon: number;
|
|
14
|
+
maxLat: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The data adapter `AutkGrammar` runs. Its `resolveSource(db, source)` loads one entry of a spec's `data` into the
|
|
19
|
+
* autk-db database `db` (a new one when `db` is undefined), in the entry's workspace, which it leaves current, and
|
|
20
|
+
* returns the database.
|
|
21
|
+
*
|
|
22
|
+
* A host calls it to load a spec's tables exactly as the grammar does, for example on a server without a map: the
|
|
23
|
+
* `./data` entry exports it with autk-db as its only import. `targets.db` names an element that lists the tables
|
|
24
|
+
* after each load. `cache`, when given, receives each GeoJSON table and each table a join wrote, under
|
|
25
|
+
* {@link tableKey}.
|
|
26
|
+
*/
|
|
27
|
+
export declare function createDataAdapter(targets?: Targets, cache?: GeoJsonCache): DataAdapter;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Loads a CSV table from exactly one of `csvFileUrl` or `csvObject`.
|
|
31
|
+
* @if { "required": ["csvFileUrl"] }
|
|
32
|
+
* @then { "not": { "required": ["csvObject"] } }
|
|
33
|
+
* @else { "required": ["csvObject"] }
|
|
34
|
+
*/
|
|
35
|
+
export declare interface CsvDataSourceSpec extends TableSourceBase {
|
|
36
|
+
type: 'csv';
|
|
37
|
+
csvFileUrl?: string;
|
|
38
|
+
/** Rows as arrays; the first row holds the column names. */
|
|
39
|
+
csvObject?: unknown[][];
|
|
40
|
+
delimiter?: string;
|
|
41
|
+
geometryColumns?: GeometryColumns;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Loads a GeoJSON FeatureCollection from `geojsonFileUrl` or `geojsonObject`. When both are given, the Autark adapter reads the URL.
|
|
46
|
+
* @if { "not": { "required": ["geojsonFileUrl"] } }
|
|
47
|
+
* @then { "required": ["geojsonObject"] }
|
|
48
|
+
*/
|
|
49
|
+
export declare interface CustomDataSourceSpec extends TableSourceBase {
|
|
50
|
+
type: 'geojson';
|
|
51
|
+
geojsonFileUrl?: string;
|
|
52
|
+
/**
|
|
53
|
+
* GeoJSON FeatureCollection to load directly.
|
|
54
|
+
*
|
|
55
|
+
* Per RFC 7946, GeoJSON coordinates MUST be in WGS84 (EPSG:4326) longitude/latitude.
|
|
56
|
+
* This is the default assumption when `coordinateFormat` is omitted.
|
|
57
|
+
*
|
|
58
|
+
* If your FeatureCollection is in a different CRS (e.g. a projected system such as
|
|
59
|
+
* EPSG:3395), you MUST set `coordinateFormat` explicitly to match the actual CRS
|
|
60
|
+
* of the input data. Omitting `coordinateFormat` when the data is not in EPSG:4326
|
|
61
|
+
* will cause the spatial transform to produce invalid geometry.
|
|
62
|
+
*/
|
|
63
|
+
geojsonObject?: InlineFeatureCollection;
|
|
64
|
+
/**
|
|
65
|
+
* Source coordinate reference system of the input data, expressed as an EPSG string
|
|
66
|
+
* (e.g. `'EPSG:4326'`, `'EPSG:3395'`).
|
|
67
|
+
*
|
|
68
|
+
* Defaults to `'EPSG:4326'` (WGS84) when omitted, which is the correct value for
|
|
69
|
+
* standards-compliant GeoJSON. Only set this when the source data deviates from
|
|
70
|
+
* RFC 7946.
|
|
71
|
+
*/
|
|
72
|
+
coordinateFormat?: string;
|
|
73
|
+
boundingBox?: BoundingBox;
|
|
74
|
+
/**
|
|
75
|
+
* How the map draws the layer. When omitted, autk-db reads it from the first feature's geometry. Set it to draw
|
|
76
|
+
* lines as `polylines` or polygons as a `buildings` layer, for example. Read by the Autark adapter only.
|
|
77
|
+
*/
|
|
78
|
+
layerType?: LayerType;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export declare interface DataAdapter {
|
|
82
|
+
resolveSource(context: unknown, spec: DataSourceSpec): Promise<unknown>;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* One entry of `data`. The `type` field selects which fields apply.
|
|
87
|
+
* @discriminator type
|
|
88
|
+
*/
|
|
89
|
+
export declare type DataSourceSpec = OsmDataSourceSpec | CsvDataSourceSpec | JsonDataSourceSpec | CustomDataSourceSpec | GeoTiffDataSourceSpec | HeatmapSourceSpec | JoinSourceSpec;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Makes `workspace` (the default one without a name) the workspace `db` works in; autk-db creates it on first use.
|
|
93
|
+
* It calls autk-db's `setWorkspace` only when `getCurrentWorkspace()` names another one.
|
|
94
|
+
*
|
|
95
|
+
* Every adapter calls it before it reads or writes a table of a spec entry, with the entry's `workspace`. A host that
|
|
96
|
+
* reads a spec's tables itself calls it the same way, since autk-db finds a table by its name in the current
|
|
97
|
+
* workspace only.
|
|
98
|
+
*/
|
|
99
|
+
export declare function enterWorkspace(db: AutkDb, workspace?: string): Promise<void>;
|
|
100
|
+
|
|
101
|
+
export declare type GeoJsonCache = Map<string, FeatureCollection>;
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* How rows become features: `true` reads the `Latitude` and `Longitude` columns, or name the columns.
|
|
105
|
+
*/
|
|
106
|
+
declare type GeometryColumns = true | LatLongGeometryColumns | WktGeometryColumns;
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Loads a GeoTIFF raster from `geotiffFileUrl` as a raster table: one feature, with one band per value. Read by the
|
|
110
|
+
* Autark adapter only.
|
|
111
|
+
*/
|
|
112
|
+
export declare interface GeoTiffDataSourceSpec extends TableSourceBase {
|
|
113
|
+
type: 'geotiff';
|
|
114
|
+
/**
|
|
115
|
+
* URL of the GeoTIFF file, relative to the page or absolute, which autk-db fetches. The file's first image is
|
|
116
|
+
* read: each of its bands becomes a band of the table (`band_1`, `band_2`, ...), where the file's no-data value
|
|
117
|
+
* reads as no value. A rotated or sheared grid is refused.
|
|
118
|
+
*/
|
|
119
|
+
geotiffFileUrl: string;
|
|
120
|
+
/** CRS of the file, as an EPSG string. Defaults to `'EPSG:4326'`. */
|
|
121
|
+
coordinateFormat?: string;
|
|
122
|
+
/** Most cells to decode; a larger raster is downsampled to fit. Defaults to 1 000 000. */
|
|
123
|
+
maxRasterCells?: number;
|
|
124
|
+
/** How a larger raster is downsampled. Defaults to `'bilinear'`. */
|
|
125
|
+
resampleMethod?: 'nearest' | 'bilinear';
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* How the rows near a heatmap cell are combined into its value: any aggregate function but `collect`, which lists the
|
|
130
|
+
* rows, while a cell holds one value.
|
|
131
|
+
*/
|
|
132
|
+
declare type HeatmapAggregateFunction = Exclude<AggregateFunction, 'collect'>;
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Aggregates a table onto a regular grid, producing a raster heatmap table.
|
|
136
|
+
*/
|
|
137
|
+
export declare interface HeatmapSourceSpec extends TableSourceBase {
|
|
138
|
+
type: 'heatmap';
|
|
139
|
+
/** Table whose rows are aggregated onto the grid. */
|
|
140
|
+
joinDataRef: string;
|
|
141
|
+
/** Which rows count toward a grid cell: those within `distance` of the cell's center. */
|
|
142
|
+
near: {
|
|
143
|
+
/** Radius around each cell's center, in workspace units. */
|
|
144
|
+
distance: number;
|
|
145
|
+
/**
|
|
146
|
+
* Measure from the cell's center to each row's centroid, the default. With `false`, measure to the nearest
|
|
147
|
+
* point of the row's geometry, so a long road counts in every cell within `distance` of any part of it.
|
|
148
|
+
*/
|
|
149
|
+
useCentroid?: boolean;
|
|
150
|
+
};
|
|
151
|
+
/** Aggregate the rows near each cell, one raster band per entry. */
|
|
152
|
+
groupBy?: Array<{
|
|
153
|
+
column: string;
|
|
154
|
+
/** How the rows combine into the cell's value: any aggregate but `collect`, which lists rows, while a cell holds one value. */
|
|
155
|
+
aggregateFn?: HeatmapAggregateFunction;
|
|
156
|
+
}>;
|
|
157
|
+
/** Grid resolution. */
|
|
158
|
+
grid: {
|
|
159
|
+
rows: number;
|
|
160
|
+
columns: number;
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* A GeoJSON feature as the loader accepts it: `geometry` may be null and `properties` may be omitted.
|
|
166
|
+
*/
|
|
167
|
+
declare type InlineFeature = {
|
|
168
|
+
type: 'Feature';
|
|
169
|
+
geometry: Geometry | null;
|
|
170
|
+
properties?: GeoJsonProperties;
|
|
171
|
+
id?: string | number;
|
|
172
|
+
bbox?: BBox;
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* A GeoJSON FeatureCollection with at least one feature.
|
|
177
|
+
*/
|
|
178
|
+
declare type InlineFeatureCollection = {
|
|
179
|
+
type: 'FeatureCollection';
|
|
180
|
+
/** @minItems 1 */
|
|
181
|
+
features: InlineFeature[];
|
|
182
|
+
bbox?: BBox;
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Spatially joins one table onto another. The result replaces the root table.
|
|
187
|
+
*/
|
|
188
|
+
export declare interface JoinSourceSpec {
|
|
189
|
+
type: 'join';
|
|
190
|
+
/** Workspace of the two tables. */
|
|
191
|
+
workspace?: WorkspaceName;
|
|
192
|
+
/** Table that receives the joined columns. */
|
|
193
|
+
dataRef: string;
|
|
194
|
+
/** Table whose rows are joined onto the root table. */
|
|
195
|
+
joinDataRef: string;
|
|
196
|
+
/** Join the rows within `distance` of each root feature instead of the rows that intersect it. */
|
|
197
|
+
near?: {
|
|
198
|
+
/** Greatest distance from a root feature to a row it receives, in workspace units. */
|
|
199
|
+
distance: number;
|
|
200
|
+
/**
|
|
201
|
+
* Measure from the root feature's centroid to the row's centroid, the default. With `false`, measure between
|
|
202
|
+
* the geometries themselves, from their nearest points, so features that touch are 0 apart.
|
|
203
|
+
*/
|
|
204
|
+
useCentroid?: boolean;
|
|
205
|
+
};
|
|
206
|
+
/** Aggregate the joined rows per root feature. */
|
|
207
|
+
groupBy?: Array<{
|
|
208
|
+
column: string;
|
|
209
|
+
aggregateFn?: AggregateFunction;
|
|
210
|
+
normalize?: boolean;
|
|
211
|
+
}>;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Loads a JSON table from exactly one of `jsonFileUrl` or `jsonObject`.
|
|
216
|
+
* @if { "required": ["jsonFileUrl"] }
|
|
217
|
+
* @then { "not": { "required": ["jsonObject"] } }
|
|
218
|
+
* @else { "required": ["jsonObject"] }
|
|
219
|
+
*/
|
|
220
|
+
export declare interface JsonDataSourceSpec extends TableSourceBase {
|
|
221
|
+
type: 'json';
|
|
222
|
+
jsonFileUrl?: string;
|
|
223
|
+
jsonObject?: unknown[];
|
|
224
|
+
geometryColumns?: GeometryColumns;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* A latitude in degrees (WGS84).
|
|
229
|
+
* @minimum -90
|
|
230
|
+
* @maximum 90
|
|
231
|
+
*/
|
|
232
|
+
declare type Latitude = number;
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Point geometry from two columns holding latitude and longitude.
|
|
236
|
+
*/
|
|
237
|
+
declare type LatLongGeometryColumns = {
|
|
238
|
+
latColumnName: string;
|
|
239
|
+
longColumnName: string;
|
|
240
|
+
/** CRS of the coordinates, as an EPSG string. Defaults to `'EPSG:4326'`. */
|
|
241
|
+
coordinateFormat?: string;
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
/** OSM layer a data source can split out, or a generic geometry layer. */
|
|
245
|
+
declare type LayerType = 'surface' | 'water' | 'parks' | 'roads' | 'buildings' | 'points' | 'polygons' | 'polylines' | 'raster';
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* A longitude in degrees (WGS84).
|
|
249
|
+
* @minimum -180
|
|
250
|
+
* @maximum 180
|
|
251
|
+
*/
|
|
252
|
+
declare type Longitude = number;
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* An area given as a box instead of boundary names. The box is the whole area: no boundary is read.
|
|
256
|
+
*/
|
|
257
|
+
declare interface OsmBoundingBoxArea {
|
|
258
|
+
/**
|
|
259
|
+
* The box as `[west, south, east, north]` in degrees (WGS84), with west less than east and south less than
|
|
260
|
+
* north. A box across the antimeridian is not supported. The Autark adapter cuts each layer to the box, but
|
|
261
|
+
* keeps or drops each building whole.
|
|
262
|
+
*/
|
|
263
|
+
bbox: [west: Longitude, south: Latitude, east: Longitude, north: Latitude];
|
|
264
|
+
/** Not with `bbox`. */
|
|
265
|
+
geocodeArea?: undefined;
|
|
266
|
+
/** Not with `bbox`. */
|
|
267
|
+
areas?: undefined;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Loads OpenStreetMap data for a named area or a box, from Overpass or from a PBF extract.
|
|
272
|
+
*/
|
|
273
|
+
export declare interface OsmDataSourceSpec extends TableSourceBase {
|
|
274
|
+
type: 'osm';
|
|
275
|
+
/** URL of a local or remote `.osm.pbf` extract to read instead of querying Overpass. */
|
|
276
|
+
pbfFileUrl?: string;
|
|
277
|
+
/** Split the raw OSM table into one table per layer, named `<outputTableName>_<layer>`. */
|
|
278
|
+
autoLoadLayers?: {
|
|
279
|
+
/** Currently ignored by both adapters. */
|
|
280
|
+
dropOsmTable?: boolean;
|
|
281
|
+
layers: Array<LayerType>;
|
|
282
|
+
};
|
|
283
|
+
/** Area to load: sub-areas inside a geocoded region (`geocodeArea` with `areas`), or a box (`bbox`), not both. */
|
|
284
|
+
queryArea: OsmNamedArea | OsmBoundingBoxArea;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* An area named by OpenStreetMap boundaries: sub-areas inside a geocoded region.
|
|
289
|
+
*/
|
|
290
|
+
declare interface OsmNamedArea {
|
|
291
|
+
/** Region to geocode, for example a city name. */
|
|
292
|
+
geocodeArea: string;
|
|
293
|
+
/** Sub-areas inside the region, for example neighborhood names. */
|
|
294
|
+
areas: string[];
|
|
295
|
+
/** Not with `geocodeArea` and `areas`. */
|
|
296
|
+
bbox?: undefined;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* The key a table has in the grammar's caches: its name in the default workspace, `<workspace>/<name>` in another, so
|
|
301
|
+
* two workspaces can hold tables of the same name. A host reads the caches it passes to `createDataAdapter` and
|
|
302
|
+
* `createComputeAdapter` with it.
|
|
303
|
+
*/
|
|
304
|
+
export declare function tableKey(workspace: string | undefined, name: string): string;
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Fields every table-producing data source shares.
|
|
308
|
+
*/
|
|
309
|
+
declare interface TableSourceBase {
|
|
310
|
+
/** Name of the table this source creates. Later sources, compute passes, maps and plots refer to it by this name. */
|
|
311
|
+
outputTableName: string;
|
|
312
|
+
/** Workspace the table is created in. */
|
|
313
|
+
workspace?: WorkspaceName;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** The elements of the page `AutkGrammar` draws in, by id. */
|
|
317
|
+
export declare type Targets = {
|
|
318
|
+
/** Not read by the adapter. */
|
|
319
|
+
compute?: string;
|
|
320
|
+
/** Id of an element that lists the loaded tables after each data source. */
|
|
321
|
+
db?: string;
|
|
322
|
+
/** Id of the canvas a map draws on, or a list of ids, one canvas per entry of `map`, in order. */
|
|
323
|
+
map?: string[] | string;
|
|
324
|
+
/**
|
|
325
|
+
* Id of the element the plots draw in, or a list of ids, one element per entry of `plot`, in order. With one id,
|
|
326
|
+
* every plot draws in that element.
|
|
327
|
+
*/
|
|
328
|
+
plot?: string[] | string;
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Geometry from one column holding WKT text such as `POLYGON((...))`. Read by the Autark adapter only.
|
|
333
|
+
*/
|
|
334
|
+
declare type WktGeometryColumns = {
|
|
335
|
+
wktColumnName: string;
|
|
336
|
+
/** CRS of the geometry, as an EPSG string. Defaults to `'EPSG:4326'`. */
|
|
337
|
+
coordinateFormat?: string;
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Name of a workspace: an isolated set of tables with its own extent. The first source loaded into a workspace sets its
|
|
342
|
+
* extent and later sources are cut to it, so two areas that must not clip each other go in two workspaces. A table is
|
|
343
|
+
* found by its name inside its workspace, so two workspaces may hold tables of the same name. Entries without a
|
|
344
|
+
* workspace use the default one. Read by the Autark adapter only.
|
|
345
|
+
* @minLength 1
|
|
346
|
+
*/
|
|
347
|
+
export declare type WorkspaceName = string;
|
|
348
|
+
|
|
349
|
+
export { }
|
|
@@ -0,0 +1,165 @@
|
|
|
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);
|
|
5
|
+
}
|
|
6
|
+
function h(o, t) {
|
|
7
|
+
return o === void 0 || o === p ? t : `${o}/${t}`;
|
|
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));
|
|
13
|
+
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;
|
|
19
|
+
});
|
|
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;
|
|
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] };
|
|
47
|
+
}
|
|
48
|
+
function S(o) {
|
|
49
|
+
const { autoLoadLayers: t, ...a } = o;
|
|
50
|
+
return { ...a, queryArea: T(o), autoLoadLayers: { layers: t?.layers ?? [] } };
|
|
51
|
+
}
|
|
52
|
+
function g(o) {
|
|
53
|
+
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
|
+
}
|
|
55
|
+
function F(o) {
|
|
56
|
+
let t = 1 / 0, a = 1 / 0, c = -1 / 0, s = -1 / 0;
|
|
57
|
+
const e = (r) => {
|
|
58
|
+
if (Array.isArray(r)) {
|
|
59
|
+
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);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
for (const l of r) e(l);
|
|
65
|
+
}
|
|
66
|
+
}, u = (r) => {
|
|
67
|
+
r && (r.type === "GeometryCollection" ? r.geometries.forEach(u) : e(r.coordinates));
|
|
68
|
+
};
|
|
69
|
+
for (const r of o.features ?? []) u(r?.geometry);
|
|
70
|
+
return t <= c ? [t, a, c, s] : void 0;
|
|
71
|
+
}
|
|
72
|
+
function j(o, t) {
|
|
73
|
+
function a(c, s) {
|
|
74
|
+
if (!s || !s.db)
|
|
75
|
+
return;
|
|
76
|
+
const e = document.getElementById(s.db);
|
|
77
|
+
if (e) {
|
|
78
|
+
const u = c.getTablesMetadata();
|
|
79
|
+
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>`;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
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) {
|
|
93
|
+
case "osm":
|
|
94
|
+
return await e.loadOsm(S(f)), a(e, o), e;
|
|
95
|
+
case "csv":
|
|
96
|
+
return await e.loadCsv(f), a(e, o), e;
|
|
97
|
+
case "json":
|
|
98
|
+
return await e.loadJson(f), a(e, o), e;
|
|
99
|
+
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))
|
|
108
|
+
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)}`
|
|
110
|
+
);
|
|
111
|
+
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)}`);
|
|
115
|
+
}
|
|
116
|
+
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)
|
|
119
|
+
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.`
|
|
121
|
+
);
|
|
122
|
+
} catch (i) {
|
|
123
|
+
if (i instanceof Error && i.message.includes("bounding box after transform")) throw i;
|
|
124
|
+
}
|
|
125
|
+
return a(e, o), e;
|
|
126
|
+
}
|
|
127
|
+
case "geotiff":
|
|
128
|
+
return await e.loadGeoTiff(f), a(e, o), e;
|
|
129
|
+
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.`);
|
|
133
|
+
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;
|
|
140
|
+
}
|
|
141
|
+
case "join": {
|
|
142
|
+
const n = f;
|
|
143
|
+
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);
|
|
151
|
+
}
|
|
152
|
+
return a(e, o), e;
|
|
153
|
+
}
|
|
154
|
+
default:
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
export {
|
|
161
|
+
j as createDataAdapter,
|
|
162
|
+
A as enterWorkspace,
|
|
163
|
+
h as tableKey
|
|
164
|
+
};
|
|
165
|
+
//# sourceMappingURL=autk-grammar-data.js.map
|
|
@@ -0,0 +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,KAAK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