@urban-toolkit/autk-grammar 4.4.1 → 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.
- package/README.md +424 -5
- package/build/autk-grammar-schema.json +1367 -505
- package/dist/autk-grammar.js +872 -430
- 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 +516 -0
- package/dist/data/autk-grammar-data.js +265 -0
- package/dist/data/autk-grammar-data.js.map +1 -0
- package/dist/index.d.ts +744 -76
- package/package.json +7 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("@urban-toolkit/autk-db");async function $(o,a){const n=a??w.DEFAULT_WORKSPACE_NAME;o.getCurrentWorkspace()!==n&&await o.setWorkspace(n)}function g(o,a){return o===void 0||o===w.DEFAULT_WORKSPACE_NAME?a:`${o}/${a}`}function S(o){const a=new Set;for(const l of o)l?.id!=null&&a.add(JSON.stringify(l.id));const n=new Set;return o.map((l,u)=>{if(l?.id!=null)return l.id;let i=`autk-feature-${u}`;for(;a.has(JSON.stringify(i))||n.has(JSON.stringify(i));)i=`${i}-generated`;return n.add(JSON.stringify(i)),i})}const L={type:"GeometryCollection",geometries:[]};function x(o){const a=o.features??[],n=S(a);let l=!1;const u=a.map((e,r)=>e==null||e.id!=null&&e.geometry!=null?e:(l=!0,{...e,id:n[r],geometry:e.geometry??L})),i=a.findIndex(e=>e?.geometry!=null);return i>0&&a[0]!=null&&a[0].geometry==null&&([u[0],u[i]]=[u[i],u[0]],l=!0),l?{...o,features:u}:o}function N(o){const{queryArea:a}=o;if(a.bbox===void 0)return{geocodeArea:a.geocodeArea,areas:a.areas};const n=s=>new Error(`OSM source "${o.outputTableName}": ${s}`);if(a.geocodeArea!==void 0||a.areas!==void 0)throw n("queryArea takes either bbox or geocodeArea with areas, not both.");const l=a.bbox;if(!Array.isArray(l)||l.length!==4||!l.every(s=>typeof s=="number"&&Number.isFinite(s)))throw n("queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.");const[u,i,e,r]=a.bbox;if(Math.abs(u)>180||Math.abs(e)>180)throw n("queryArea.bbox west and east must be longitudes from -180 to 180.");if(Math.abs(i)>90||Math.abs(r)>90)throw n("queryArea.bbox south and north must be latitudes from -90 to 90.");if(u>=e)throw n(`queryArea.bbox west (${u}) must be less than east (${e}); a box across the antimeridian is not supported.`);if(i>=r)throw n(`queryArea.bbox south (${i}) must be less than north (${r}).`);return{bbox:[u,i,e,r]}}function O(o){const{autoLoadLayers:a,...n}=o;if(o.pbfFileUrl!==void 0&&(o.tagSets?.length??0)>0)throw new Error(`OSM source "${o.outputTableName}": tagSets are read from the Overpass API only, so a source with pbfFileUrl cannot take them.`);return{...n,queryArea:N(o),autoLoadLayers:{layers:a?.layers??[],...a?.coordinateFormat!==void 0&&{coordinateFormat:a.coordinateFormat}}}}function T(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 E(o){return o===void 0||o===w.DEFAULT_WORKSPACE_NAME?"the default workspace":`the workspace "${o}"`}function j(o){if(o!=null)return typeof o=="string"?o:JSON.stringify(o)}async function v(o,a,n,l){const u=new Map;for(const r of(await o.getLayer(a.name)).features){const s=j(r.properties?.[l]);if(s!==void 0){if(r.id===void 0||r.id===null)throw new Error("its rows have no feature id to update them by.");u.set(s,[...u.get(s)??[],r.id])}}const i=n.features.flatMap(r=>{const s=j(r.properties?.[l]);return s===void 0?[]:(u.get(s)??[]).map(y=>({...r,id:y}))}),e=a.columns.some(r=>r.name==="geojson_id")?"geojson_id":"id";return{data:{...n,features:i},idColumn:e}}async function A(o){if(o)return o;const a=new w.AutkDb;return await a.init(),a}function F(o){let a=1/0,n=1/0,l=-1/0,u=-1/0;const i=r=>{if(Array.isArray(r)){if(typeof r[0]=="number"){const[s,y]=r;s<a&&(a=s),s>l&&(l=s),y<n&&(n=y),y>u&&(u=y);return}for(const s of r)i(s)}},e=r=>{r&&(r.type==="GeometryCollection"?r.geometries.forEach(e):i(r.coordinates))};for(const r of o.features??[])e(r?.geometry);return a<=l?[a,n,l,u]:void 0}function M(o,a){function n(u,i){if(!i||!i.db)return;const e=document.getElementById(i.db);if(e){const r=u.getTablesMetadata();e.innerHTML+="<ul>";for(const s of r)e.innerHTML+=`<li>${s.name}: (${s.source}, ${s.type}) </li>`;e.innerHTML+="</ul>",e.innerHTML+=`<p>Number of tables: ${r.length}</p>`}}async function l(u,i,e){if(!a)return;const r=g(i,e),s=u.getTablesMetadata().find(y=>y.name===e);s&&w.isRenderableTable(s)?a.set(r,await u.getLayer(e)):a.delete(r)}return{async resolveWorkspaces(u,i){const e=await A(u),r=new Set;for(const{name:s,coordinateFormat:y,precisionGrid:b}of i){const t=s??w.DEFAULT_WORKSPACE_NAME;if(r.has(t))throw new Error(`workspaces sets ${E(s)} twice; give each workspace one entry.`);r.add(t);try{await e.setWorkspace(t,{coordinateFormat:y,precisionGrid:b})}catch(c){throw new Error(`workspaces, ${E(s)}: ${c instanceof Error?c.message:String(c)}`)}}return await $(e),e},async resolveSource(u,i){const e=await A(u),{workspace:r}=i;await $(e,r);let{type:s,workspace:y,...b}=i;switch(s){case"osm":return await e.loadOsm(O(b)),n(e,o),e;case"csv":return await e.loadCsv(b),n(e,o),e;case"json":return await e.loadJson(b),n(e,o),e;case"geojson":{const t=b;let c;t.geojsonFileUrl?c=await(await fetch(t.geojsonFileUrl)).json():c=t.geojsonObject,a&&c&&a.set(g(r,t.outputTableName),c);const m=c?(()=>{const d={...t,geojsonObject:x(c)};return delete d.geojsonFileUrl,d})():t,p=/^EPSG:4326$/i.test(m.coordinateFormat??"EPSG:4326"),f=c&&p?F(c):void 0;if(f&&(f[1]<-90||f[3]>90))throw new Error(`GeoJSON layer "${m.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${f.join(", ")}]), so they cannot be EPSG:4326 degrees. ${T(m.coordinateFormat)}`);try{await e.loadGeojson(m)}catch(d){throw new Error(`Failed to load GeoJSON layer "${m.outputTableName}": ${d instanceof Error?d.message:String(d)}`)}try{const d=await e.getBoundingBoxFromLayer(m.outputTableName),h=25e6;if(!isFinite(d.minLon)||!isFinite(d.minLat)||!isFinite(d.maxLon)||!isFinite(d.maxLat)||Math.abs(d.minLon)>h||Math.abs(d.maxLon)>h||Math.abs(d.minLat)>h||Math.abs(d.maxLat)>h)throw new Error(`Geometry bounding box after transform is invalid for layer "${m.outputTableName}" (bbox: [${d.minLon}, ${d.minLat}, ${d.maxLon}, ${d.maxLat}]). ${T(m.coordinateFormat)} The workspace uses ${e.getWorkspaceConfiguration().coordinateFormat}; input is expected in EPSG:4326 by default.`)}catch(d){if(d instanceof Error&&d.message.includes("bounding box after transform"))throw d}return n(e,o),e}case"geotiff":return await e.loadGeoTiff(b),n(e,o),e;case"heatmap":{const t=b;if(t.groupBy?.some(c=>c.aggregateFn==="collect"))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.`);return await e.buildHeatmap({tableJoinName:t.joinDataRef,near:t.near,outputTableName:t.outputTableName,grid:t.grid,...t.groupBy&&{groupBy:t.groupBy}}),n(e,o),e}case"join":{const t=b;if(await e.spatialQuery({tableRootName:t.dataRef,tableJoinName:t.joinDataRef,...t.near&&{near:t.near},...t.groupBy&&{groupBy:t.groupBy}}),a){const c=await e.getLayer(t.dataRef);a.set(g(r,t.dataRef),c)}return n(e,o),e}case"sql":{const t=b;try{await e.rawQuery({query:t.query,output:{type:"CREATE_TABLE",tableName:t.outputTableName,source:"user",...t.layerType!==void 0&&{tableType:t.layerType}}})}catch(c){throw new Error(`SQL source "${t.outputTableName}": ${c instanceof Error?c.message:String(c)}`)}return a?.delete(g(r,t.outputTableName)),n(e,o),e}case"update":{const t=b,c=f=>new Error(`Update of "${t.dataRef}": ${f}`);if(t.geojsonObject===void 0==(t.jsonObject===void 0))throw c("give its rows in geojsonObject or in jsonObject, one of the two.");if(t.strategy==="update"&&!t.idColumn)throw c("the update strategy needs an idColumn, the column that matches a given row to the table's rows.");let m=t.geojsonObject??t.jsonObject,p=t.idColumn;try{const f=e.getTablesMetadata().find(d=>d.name===t.dataRef);if(t.strategy==="update"&&t.geojsonObject&&p?.startsWith("properties.")&&f&&w.isVectorTable(f)&&({data:m,idColumn:p}=await v(e,f,t.geojsonObject,p.slice(11)),m.features.length===0))return n(e,o),e;await e.updateTable({tableName:t.dataRef,data:m,strategy:t.strategy,...p!==void 0&&{idColumn:p}})}catch(f){throw c(f instanceof Error?f.message:String(f))}return await l(e,r,t.dataRef),n(e,o),e}case"drop":{const t=b;if(!e.getTablesMetadata().some(c=>c.name===t.dataRef))throw new Error(`Drop of "${t.dataRef}": ${E(r)} holds no table of that name.`);return await e.removeLayer(t.dataRef),a?.delete(g(r,t.dataRef)),n(e,o),e}default:throw new Error(`Unknown data source type "${String(s)}".`)}}}}exports.createDataAdapter=M;exports.enterWorkspace=$;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, 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":"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,GAAIF,GAAS,IAAM,KAAM,OAAOA,EAAQ,GACxC,IAAIG,EAAK,gBAAgBD,CAAK,GAC9B,KAAOH,EAAI,IAAI,KAAK,UAAUI,CAAE,CAAC,GAAKF,EAAM,IAAI,KAAK,UAAUE,CAAE,CAAC,GAAGA,EAAK,GAAGA,CAAE,aAC/E,OAAAF,EAAM,IAAI,KAAK,UAAUE,CAAE,CAAC,EACrBA,CACX,CAAC,CACL,CCnBA,MAAMC,EAAwB,CAAE,KAAM,qBAAsB,WAAY,CAAA,CAAC,EAYzE,SAASC,EAAmBC,EAAkD,CAC1E,MAAMR,EAAWQ,EAAW,UAAY,CAAA,EAClCC,EAAMV,EAAWC,CAAQ,EAC/B,IAAIU,EAAU,GACd,MAAMC,EAAWX,EAAS,IAAI,CAACE,EAASE,IAChCF,GAAW,MAASA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
+
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. Its `resolveWorkspaces(db, workspaces)` sets each workspace a spec's `workspaces` lists to its
|
|
21
|
+
* CRS and precision grid, before the first source loads, leaves the default workspace current and returns the database.
|
|
22
|
+
*
|
|
23
|
+
* A host calls it to load a spec's tables exactly as the grammar does, for example on a server without a map: the
|
|
24
|
+
* `./data` entry exports it with autk-db as its only import. `targets.db` names an element that lists the tables
|
|
25
|
+
* after each load. `cache`, when given, receives each GeoJSON table and each table a join or an update wrote, under
|
|
26
|
+
* {@link tableKey}, and loses each table a `sql` source replaces or a `drop` source drops.
|
|
27
|
+
*/
|
|
28
|
+
export declare function createDataAdapter(targets?: Targets, cache?: GeoJsonCache): Required<DataAdapter>;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Loads a CSV table from exactly one of `csvFileUrl` or `csvObject`.
|
|
32
|
+
* @if { "required": ["csvFileUrl"] }
|
|
33
|
+
* @then { "not": { "required": ["csvObject"] } }
|
|
34
|
+
* @else { "required": ["csvObject"] }
|
|
35
|
+
*/
|
|
36
|
+
export declare interface CsvDataSourceSpec extends TableSourceBase {
|
|
37
|
+
type: 'csv';
|
|
38
|
+
csvFileUrl?: string;
|
|
39
|
+
/** Rows as arrays; the first row holds the column names. */
|
|
40
|
+
csvObject?: unknown[][];
|
|
41
|
+
delimiter?: string;
|
|
42
|
+
geometryColumns?: GeometryColumns;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Loads a GeoJSON FeatureCollection from `geojsonFileUrl` or `geojsonObject`. When both are given, the Autark adapter reads the URL.
|
|
47
|
+
* @if { "not": { "required": ["geojsonFileUrl"] } }
|
|
48
|
+
* @then { "required": ["geojsonObject"] }
|
|
49
|
+
*/
|
|
50
|
+
export declare interface CustomDataSourceSpec extends TableSourceBase {
|
|
51
|
+
type: 'geojson';
|
|
52
|
+
geojsonFileUrl?: string;
|
|
53
|
+
/**
|
|
54
|
+
* GeoJSON FeatureCollection to load directly.
|
|
55
|
+
*
|
|
56
|
+
* Per RFC 7946, GeoJSON coordinates MUST be in WGS84 (EPSG:4326) longitude/latitude.
|
|
57
|
+
* This is the default assumption when `coordinateFormat` is omitted.
|
|
58
|
+
*
|
|
59
|
+
* If your FeatureCollection is in a different CRS (e.g. a projected system such as
|
|
60
|
+
* EPSG:3395), you MUST set `coordinateFormat` explicitly to match the actual CRS
|
|
61
|
+
* of the input data. Omitting `coordinateFormat` when the data is not in EPSG:4326
|
|
62
|
+
* will cause the spatial transform to produce invalid geometry.
|
|
63
|
+
*/
|
|
64
|
+
geojsonObject?: InlineFeatureCollection;
|
|
65
|
+
/**
|
|
66
|
+
* Source coordinate reference system of the input data, expressed as an EPSG string
|
|
67
|
+
* (e.g. `'EPSG:4326'`, `'EPSG:3395'`).
|
|
68
|
+
*
|
|
69
|
+
* Defaults to `'EPSG:4326'` (WGS84) when omitted, which is the correct value for
|
|
70
|
+
* standards-compliant GeoJSON. Only set this when the source data deviates from
|
|
71
|
+
* RFC 7946.
|
|
72
|
+
*/
|
|
73
|
+
coordinateFormat?: string;
|
|
74
|
+
boundingBox?: BoundingBox;
|
|
75
|
+
/**
|
|
76
|
+
* How the map draws the layer. When omitted, autk-db reads it from the first feature's geometry. Set it to draw
|
|
77
|
+
* lines as `polylines` or polygons as a `buildings` layer, for example. Read by the Autark adapter only.
|
|
78
|
+
*/
|
|
79
|
+
layerType?: LayerType;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export declare interface DataAdapter {
|
|
83
|
+
resolveSource(context: unknown, spec: DataSourceSpec): Promise<unknown>;
|
|
84
|
+
/**
|
|
85
|
+
* Sets up the workspaces a spec's `workspaces` lists, before its first source loads, and returns the context. An
|
|
86
|
+
* adapter without workspaces leaves it out, and the engine then skips `workspaces`.
|
|
87
|
+
*/
|
|
88
|
+
resolveWorkspaces?(context: unknown, workspaces: WorkspaceSpec[]): Promise<unknown>;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* One entry of `data`. The `type` field selects which fields apply.
|
|
93
|
+
* @discriminator type
|
|
94
|
+
*/
|
|
95
|
+
export declare type DataSourceSpec = OsmDataSourceSpec | CsvDataSourceSpec | JsonDataSourceSpec | CustomDataSourceSpec | GeoTiffDataSourceSpec | HeatmapSourceSpec | JoinSourceSpec | SqlSourceSpec | UpdateSourceSpec | DropSourceSpec;
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Drops a table, so the sources, compute passes, maps and plots after it no longer find it, and `AutkGrammar.data` no
|
|
99
|
+
* longer lists it. Read by the Autark adapter only.
|
|
100
|
+
*/
|
|
101
|
+
export declare interface DropSourceSpec {
|
|
102
|
+
type: 'drop';
|
|
103
|
+
/** Workspace of the table. */
|
|
104
|
+
workspace?: WorkspaceName;
|
|
105
|
+
/** The table to drop. */
|
|
106
|
+
dataRef: string;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Makes `workspace` (the default one without a name) the workspace `db` works in; autk-db creates it on first use.
|
|
111
|
+
* It calls autk-db's `setWorkspace` only when `getCurrentWorkspace()` names another one.
|
|
112
|
+
*
|
|
113
|
+
* Every adapter calls it before it reads or writes a table of a spec entry, with the entry's `workspace`. A host that
|
|
114
|
+
* reads a spec's tables itself calls it the same way, since autk-db finds a table by its name in the current
|
|
115
|
+
* workspace only.
|
|
116
|
+
*/
|
|
117
|
+
export declare function enterWorkspace(db: AutkDb, workspace?: string): Promise<void>;
|
|
118
|
+
|
|
119
|
+
export declare type GeoJsonCache = Map<string, FeatureCollection>;
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* How rows become features: `true` reads the `Latitude` and `Longitude` columns, or name the columns.
|
|
123
|
+
*/
|
|
124
|
+
declare type GeometryColumns = true | LatLongGeometryColumns | WktGeometryColumns;
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Loads a GeoTIFF raster from `geotiffFileUrl` as a raster table: one feature, with one band per value. Read by the
|
|
128
|
+
* Autark adapter only.
|
|
129
|
+
*/
|
|
130
|
+
export declare interface GeoTiffDataSourceSpec extends TableSourceBase {
|
|
131
|
+
type: 'geotiff';
|
|
132
|
+
/**
|
|
133
|
+
* URL of the GeoTIFF file, relative to the page or absolute, which autk-db fetches. The file's first image is
|
|
134
|
+
* read: each of its bands becomes a band of the table (`band_1`, `band_2`, ...), where the file's no-data value
|
|
135
|
+
* reads as no value. A rotated or sheared grid is refused.
|
|
136
|
+
*/
|
|
137
|
+
geotiffFileUrl: string;
|
|
138
|
+
/** CRS of the file, as an EPSG string. Defaults to `'EPSG:4326'`. */
|
|
139
|
+
coordinateFormat?: string;
|
|
140
|
+
/** Most cells to decode; a larger raster is downsampled to fit. Defaults to 1 000 000. */
|
|
141
|
+
maxRasterCells?: number;
|
|
142
|
+
/** How a larger raster is downsampled. Defaults to `'bilinear'`. */
|
|
143
|
+
resampleMethod?: 'nearest' | 'bilinear';
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* How the rows near a heatmap cell are combined into its value: any aggregate function but `collect`, which lists the
|
|
148
|
+
* rows, while a cell holds one value.
|
|
149
|
+
*/
|
|
150
|
+
declare type HeatmapAggregateFunction = Exclude<AggregateFunction, 'collect'>;
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Aggregates a table onto a regular grid, producing a raster heatmap table.
|
|
154
|
+
*/
|
|
155
|
+
export declare interface HeatmapSourceSpec extends TableSourceBase {
|
|
156
|
+
type: 'heatmap';
|
|
157
|
+
/** Table whose rows are aggregated onto the grid. */
|
|
158
|
+
joinDataRef: string;
|
|
159
|
+
/** Which rows count toward a grid cell: those within `distance` of the cell's center. */
|
|
160
|
+
near: {
|
|
161
|
+
/** Radius around each cell's center, in workspace units. */
|
|
162
|
+
distance: number;
|
|
163
|
+
/**
|
|
164
|
+
* Measure from the cell's center to each row's centroid, the default. With `false`, measure to the nearest
|
|
165
|
+
* point of the row's geometry, so a long road counts in every cell within `distance` of any part of it.
|
|
166
|
+
*/
|
|
167
|
+
useCentroid?: boolean;
|
|
168
|
+
};
|
|
169
|
+
/** Aggregate the rows near each cell, one raster band per entry. */
|
|
170
|
+
groupBy?: Array<{
|
|
171
|
+
column: string;
|
|
172
|
+
/** How the rows combine into the cell's value: any aggregate but `collect`, which lists rows, while a cell holds one value. */
|
|
173
|
+
aggregateFn?: HeatmapAggregateFunction;
|
|
174
|
+
/**
|
|
175
|
+
* Rescale the band's values from 0 to 1 across the grid's cells. It needs an autk-db with
|
|
176
|
+
* urban-toolkit/autark#132, which also adds `_norm` to the band's label; autk-db 4.1.1 builds the band from the
|
|
177
|
+
* values as they are.
|
|
178
|
+
*/
|
|
179
|
+
normalize?: boolean;
|
|
180
|
+
}>;
|
|
181
|
+
/** Grid resolution. */
|
|
182
|
+
grid: {
|
|
183
|
+
rows: number;
|
|
184
|
+
columns: number;
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* A GeoJSON feature as the loader accepts it: `geometry` may be null and `properties` may be omitted.
|
|
190
|
+
*/
|
|
191
|
+
declare type InlineFeature = {
|
|
192
|
+
type: 'Feature';
|
|
193
|
+
geometry: Geometry | null;
|
|
194
|
+
properties?: GeoJsonProperties;
|
|
195
|
+
id?: string | number;
|
|
196
|
+
bbox?: BBox;
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* A GeoJSON FeatureCollection with at least one feature.
|
|
201
|
+
*/
|
|
202
|
+
declare type InlineFeatureCollection = {
|
|
203
|
+
type: 'FeatureCollection';
|
|
204
|
+
/** @minItems 1 */
|
|
205
|
+
features: InlineFeature[];
|
|
206
|
+
bbox?: BBox;
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Spatially joins one table onto another. The result replaces the root table.
|
|
211
|
+
*/
|
|
212
|
+
export declare interface JoinSourceSpec {
|
|
213
|
+
type: 'join';
|
|
214
|
+
/** Workspace of the two tables. */
|
|
215
|
+
workspace?: WorkspaceName;
|
|
216
|
+
/** Table that receives the joined columns. */
|
|
217
|
+
dataRef: string;
|
|
218
|
+
/** Table whose rows are joined onto the root table. */
|
|
219
|
+
joinDataRef: string;
|
|
220
|
+
/** Join the rows within `distance` of each root feature instead of the rows that intersect it. */
|
|
221
|
+
near?: {
|
|
222
|
+
/** Greatest distance from a root feature to a row it receives, in workspace units. */
|
|
223
|
+
distance: number;
|
|
224
|
+
/**
|
|
225
|
+
* Measure from the root feature's centroid to the row's centroid, the default. With `false`, measure between
|
|
226
|
+
* the geometries themselves, from their nearest points, so features that touch are 0 apart.
|
|
227
|
+
*/
|
|
228
|
+
useCentroid?: boolean;
|
|
229
|
+
};
|
|
230
|
+
/** Aggregate the joined rows per root feature. */
|
|
231
|
+
groupBy?: Array<{
|
|
232
|
+
column: string;
|
|
233
|
+
aggregateFn?: AggregateFunction;
|
|
234
|
+
normalize?: boolean;
|
|
235
|
+
}>;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Loads a JSON table from exactly one of `jsonFileUrl` or `jsonObject`.
|
|
240
|
+
* @if { "required": ["jsonFileUrl"] }
|
|
241
|
+
* @then { "not": { "required": ["jsonObject"] } }
|
|
242
|
+
* @else { "required": ["jsonObject"] }
|
|
243
|
+
*/
|
|
244
|
+
export declare interface JsonDataSourceSpec extends TableSourceBase {
|
|
245
|
+
type: 'json';
|
|
246
|
+
jsonFileUrl?: string;
|
|
247
|
+
jsonObject?: unknown[];
|
|
248
|
+
geometryColumns?: GeometryColumns;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* A latitude in degrees (WGS84).
|
|
253
|
+
* @minimum -90
|
|
254
|
+
* @maximum 90
|
|
255
|
+
*/
|
|
256
|
+
declare type Latitude = number;
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Point geometry from two columns holding latitude and longitude.
|
|
260
|
+
*/
|
|
261
|
+
declare type LatLongGeometryColumns = {
|
|
262
|
+
latColumnName: string;
|
|
263
|
+
longColumnName: string;
|
|
264
|
+
/** CRS of the coordinates, as an EPSG string. Defaults to `'EPSG:4326'`. */
|
|
265
|
+
coordinateFormat?: string;
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
/** OSM layer a data source can split out, or a generic geometry layer. */
|
|
269
|
+
declare type LayerType = 'surface' | 'water' | 'parks' | 'roads' | 'buildings' | 'points' | 'polygons' | 'polylines' | 'raster';
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* A longitude in degrees (WGS84).
|
|
273
|
+
* @minimum -180
|
|
274
|
+
* @maximum 180
|
|
275
|
+
*/
|
|
276
|
+
declare type Longitude = number;
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* An area given as a box instead of boundary names. The box is the whole area: no boundary is read.
|
|
280
|
+
*/
|
|
281
|
+
declare interface OsmBoundingBoxArea {
|
|
282
|
+
/**
|
|
283
|
+
* The box as `[west, south, east, north]` in degrees (WGS84), with west less than east and south less than
|
|
284
|
+
* north. A box across the antimeridian is not supported. The Autark adapter cuts each layer to the box, but
|
|
285
|
+
* keeps or drops each building whole.
|
|
286
|
+
*/
|
|
287
|
+
bbox: [west: Longitude, south: Latitude, east: Longitude, north: Latitude];
|
|
288
|
+
/** Not with `bbox`. */
|
|
289
|
+
geocodeArea?: undefined;
|
|
290
|
+
/** Not with `bbox`. */
|
|
291
|
+
areas?: undefined;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Loads OpenStreetMap data for a named area or a box, from Overpass or from a PBF extract.
|
|
296
|
+
* @if { "required": ["pbfFileUrl"] }
|
|
297
|
+
* @then { "not": { "required": ["tagSets"], "properties": { "tagSets": { "minItems": 1 } } } }
|
|
298
|
+
*/
|
|
299
|
+
export declare interface OsmDataSourceSpec extends TableSourceBase {
|
|
300
|
+
type: 'osm';
|
|
301
|
+
/** URL of a local or remote `.osm.pbf` extract to read instead of querying Overpass. */
|
|
302
|
+
pbfFileUrl?: string;
|
|
303
|
+
/**
|
|
304
|
+
* Features chosen by their tags, each set as a table of its own, `<outputTableName>_<name>_<type>`, cut to the
|
|
305
|
+
* area. A set that matches no feature in the area makes no table. Read from the Overpass API only: a source with
|
|
306
|
+
* `pbfFileUrl` cannot take them. Read by the Autark adapter only.
|
|
307
|
+
* @maxItems 8
|
|
308
|
+
*/
|
|
309
|
+
tagSets?: OsmTagSet[];
|
|
310
|
+
/**
|
|
311
|
+
* Query the Overpass API again rather than read the answer the browser cached for this area, its layers and its tag
|
|
312
|
+
* sets, which autk-db keeps for 24 hours. A source with `pbfFileUrl` reads its file each time and ignores it. Read
|
|
313
|
+
* by the Autark adapter only.
|
|
314
|
+
*/
|
|
315
|
+
forceRefresh?: boolean;
|
|
316
|
+
/** Split the raw OSM table into one table per layer, named `<outputTableName>_<layer>`. */
|
|
317
|
+
autoLoadLayers?: {
|
|
318
|
+
/** Currently ignored by both adapters. */
|
|
319
|
+
dropOsmTable?: boolean;
|
|
320
|
+
/**
|
|
321
|
+
* CRS of the OpenStreetMap data's coordinates, as an EPSG string. Defaults to `'EPSG:4326'`, the degrees the
|
|
322
|
+
* Overpass API and OpenStreetMap's extracts give. The layers and the tag sets are read in it. Read by the Autark
|
|
323
|
+
* adapter only.
|
|
324
|
+
*/
|
|
325
|
+
coordinateFormat?: string;
|
|
326
|
+
layers: Array<LayerType>;
|
|
327
|
+
};
|
|
328
|
+
/** Area to load: sub-areas inside a geocoded region (`geocodeArea` with `areas`), or a box (`bbox`), not both. */
|
|
329
|
+
queryArea: OsmNamedArea | OsmBoundingBoxArea;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* An area named by OpenStreetMap boundaries: sub-areas inside a geocoded region.
|
|
334
|
+
*/
|
|
335
|
+
declare interface OsmNamedArea {
|
|
336
|
+
/** Region to geocode, for example a city name. */
|
|
337
|
+
geocodeArea: string;
|
|
338
|
+
/** Sub-areas inside the region, for example neighborhood names. */
|
|
339
|
+
areas: string[];
|
|
340
|
+
/** Not with `geocodeArea` and `areas`. */
|
|
341
|
+
bbox?: undefined;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* An OpenStreetMap tag a tag set matches: the tag `key` with the value `value`, or with any value when `value` is
|
|
346
|
+
* omitted.
|
|
347
|
+
*/
|
|
348
|
+
export declare type OsmTagFilter = {
|
|
349
|
+
/**
|
|
350
|
+
* The tag's key, such as `amenity` or `addr:street`: letters, digits, `_`, `:`, `.` and `-`, starting with a letter
|
|
351
|
+
* or a digit.
|
|
352
|
+
* @pattern ^[A-Za-z0-9][A-Za-z0-9_:.-]{0,254}$
|
|
353
|
+
*/
|
|
354
|
+
key: string;
|
|
355
|
+
/**
|
|
356
|
+
* The tag's value, such as `cafe`. Without it, the key with any value matches.
|
|
357
|
+
* @minLength 1
|
|
358
|
+
* @maxLength 255
|
|
359
|
+
*/
|
|
360
|
+
value?: string;
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* OpenStreetMap features chosen by their tags, as one table of one geometry type.
|
|
365
|
+
*/
|
|
366
|
+
export declare type OsmTagSet = {
|
|
367
|
+
/**
|
|
368
|
+
* Names the set's table, `<outputTableName>_<name>_<type>`: a lowercase letter, then up to 31 lowercase letters,
|
|
369
|
+
* digits or `_`. No two sets of a source share a name.
|
|
370
|
+
* @pattern ^[a-z][a-z0-9_]{0,31}$
|
|
371
|
+
*/
|
|
372
|
+
name: string;
|
|
373
|
+
/**
|
|
374
|
+
* The geometry the table holds: `points`, the tagged nodes; `polylines`, the open ways and the ways tagged as
|
|
375
|
+
* lines (`highway`, `barrier`, `railway`, `waterway`, or `area=no`); `polygons`, the other closed ways and the
|
|
376
|
+
* multipolygon relations.
|
|
377
|
+
*/
|
|
378
|
+
type: 'points' | 'polylines' | 'polygons';
|
|
379
|
+
/**
|
|
380
|
+
* The tags a feature is chosen by: it is in the set when it has any one of them.
|
|
381
|
+
* @minItems 1
|
|
382
|
+
* @maxItems 64
|
|
383
|
+
*/
|
|
384
|
+
tags: OsmTagFilter[];
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Saves the rows of a SQL query over the workspace's tables as a new table. Read by the Autark adapter only.
|
|
389
|
+
*/
|
|
390
|
+
export declare interface SqlSourceSpec extends TableSourceBase {
|
|
391
|
+
type: 'sql';
|
|
392
|
+
/**
|
|
393
|
+
* A `SELECT`, or a `WITH` query that ends in one, in DuckDB's SQL, over the tables of the source's workspace by their
|
|
394
|
+
* names. autk-db refuses any other statement, and any query in which `insert`, `update`, `delete`, `create`,
|
|
395
|
+
* `alter`, `drop`, `truncate` or `replace` appears as a word, even inside a string.
|
|
396
|
+
* @minLength 1
|
|
397
|
+
*/
|
|
398
|
+
query: string;
|
|
399
|
+
/**
|
|
400
|
+
* How a map draws the new table, whose geometry must then be in a column named `geometry`, in the workspace's CRS,
|
|
401
|
+
* as the workspace's tables hold it. Without it, the table has no layer type: a plot draws its rows, while a map
|
|
402
|
+
* does not draw it and `AutkGrammar.data` does not list it.
|
|
403
|
+
*/
|
|
404
|
+
layerType?: LayerType;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* The key a table has in the grammar's caches: its name in the default workspace, `<workspace>/<name>` in another, so
|
|
409
|
+
* two workspaces can hold tables of the same name. A host reads the caches it passes to `createDataAdapter` and
|
|
410
|
+
* `createComputeAdapter` with it.
|
|
411
|
+
*/
|
|
412
|
+
export declare function tableKey(workspace: string | undefined, name: string): string;
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Fields every table-producing data source shares.
|
|
416
|
+
*/
|
|
417
|
+
declare interface TableSourceBase {
|
|
418
|
+
/** Name of the table this source creates. Later sources, compute passes, maps and plots refer to it by this name. */
|
|
419
|
+
outputTableName: string;
|
|
420
|
+
/** Workspace the table is created in. */
|
|
421
|
+
workspace?: WorkspaceName;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** The elements of the page `AutkGrammar` draws in, by id. */
|
|
425
|
+
export declare type Targets = {
|
|
426
|
+
/** Not read by the adapter. */
|
|
427
|
+
compute?: string;
|
|
428
|
+
/** Id of an element that lists the loaded tables after each data source. */
|
|
429
|
+
db?: string;
|
|
430
|
+
/** Id of the canvas a map draws on, or a list of ids, one canvas per entry of `map`, in order. */
|
|
431
|
+
map?: string[] | string;
|
|
432
|
+
/**
|
|
433
|
+
* Id of the element the plots draw in, or a list of ids, one element per entry of `plot`, in order. With one id,
|
|
434
|
+
* every plot draws in that element.
|
|
435
|
+
*/
|
|
436
|
+
plot?: string[] | string;
|
|
437
|
+
};
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Replaces or changes the rows of a table already loaded, with rows given inline: a FeatureCollection for a table with
|
|
441
|
+
* a geometry, an array of objects for a table without one. Read by the Autark adapter only.
|
|
442
|
+
* @if { "required": ["geojsonObject"] }
|
|
443
|
+
* @then { "not": { "required": ["jsonObject"] }, "if": { "required": ["strategy"], "properties": { "strategy": { "const": "update" } } }, "then": { "required": ["idColumn"] } }
|
|
444
|
+
* @else { "required": ["jsonObject"], "if": { "required": ["strategy"], "properties": { "strategy": { "const": "update" } } }, "then": { "required": ["idColumn"] } }
|
|
445
|
+
*/
|
|
446
|
+
export declare interface UpdateSourceSpec {
|
|
447
|
+
type: 'update';
|
|
448
|
+
/** Workspace of the table. */
|
|
449
|
+
workspace?: WorkspaceName;
|
|
450
|
+
/** The table to change. */
|
|
451
|
+
dataRef: string;
|
|
452
|
+
/**
|
|
453
|
+
* `replace` swaps every row of the table for the given rows. `update` changes the rows whose `idColumn` value a
|
|
454
|
+
* given row has: in a table with a geometry, each takes the given row's geometry and properties, and no row is
|
|
455
|
+
* added; in a table without one, the given rows replace them, and those that match no row are added.
|
|
456
|
+
*/
|
|
457
|
+
strategy: 'replace' | 'update';
|
|
458
|
+
/**
|
|
459
|
+
* With `update`, the column that matches a given row to the table's rows: a column such as `month`, or a feature
|
|
460
|
+
* property as `properties.<name>`, such as `properties.parcel_id`.
|
|
461
|
+
* @minLength 1
|
|
462
|
+
*/
|
|
463
|
+
idColumn?: string;
|
|
464
|
+
/**
|
|
465
|
+
* The rows of a table with a geometry. autk-db stores their coordinates as they come, so they are in the
|
|
466
|
+
* workspace's CRS, as `AutkGrammar.data` gives a table's features.
|
|
467
|
+
*/
|
|
468
|
+
geojsonObject?: InlineFeatureCollection;
|
|
469
|
+
/**
|
|
470
|
+
* The rows of a table without a geometry, such as a CSV or JSON table loaded without `geometryColumns`.
|
|
471
|
+
* @minItems 1
|
|
472
|
+
*/
|
|
473
|
+
jsonObject?: Array<Record<string, unknown>>;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* Geometry from one column holding WKT text such as `POLYGON((...))`. Read by the Autark adapter only.
|
|
478
|
+
*/
|
|
479
|
+
declare type WktGeometryColumns = {
|
|
480
|
+
wktColumnName: string;
|
|
481
|
+
/** CRS of the geometry, as an EPSG string. Defaults to `'EPSG:4326'`. */
|
|
482
|
+
coordinateFormat?: string;
|
|
483
|
+
};
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Name of a workspace: an isolated set of tables with its own extent. The first source loaded into a workspace sets its
|
|
487
|
+
* extent and later sources are cut to it, so two areas that must not clip each other go in two workspaces. A table is
|
|
488
|
+
* found by its name inside its workspace, so two workspaces may hold tables of the same name. Entries without a
|
|
489
|
+
* workspace use the default one. Read by the Autark adapter only.
|
|
490
|
+
* @minLength 1
|
|
491
|
+
*/
|
|
492
|
+
export declare type WorkspaceName = string;
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* How a workspace stores its tables: the coordinate system they are kept in, and the grid their coordinates are rounded
|
|
496
|
+
* to. Read by the Autark adapter only.
|
|
497
|
+
*/
|
|
498
|
+
export declare type WorkspaceSpec = {
|
|
499
|
+
/** The workspace, by the name sources, compute passes, maps and plots give as their `workspace`. Without it, the default workspace. */
|
|
500
|
+
name?: WorkspaceName;
|
|
501
|
+
/**
|
|
502
|
+
* CRS the workspace stores its tables in, as an EPSG string such as `'EPSG:3857'`. Each source is transformed to
|
|
503
|
+
* it as it loads, its maps draw in its units, and so are the lengths given in workspace units, such as a join's
|
|
504
|
+
* `near.distance`. autk-db's default is `'EPSG:3395'`, World Mercator, in meters.
|
|
505
|
+
* @minLength 1
|
|
506
|
+
*/
|
|
507
|
+
coordinateFormat: string;
|
|
508
|
+
/**
|
|
509
|
+
* Grid every stored coordinate is rounded to, in the CRS's units. autk-db's default is `0.01`, a centimeter in World
|
|
510
|
+
* Mercator. A geometry the grid collapses is refused as it loads.
|
|
511
|
+
* @exclusiveMinimum 0
|
|
512
|
+
*/
|
|
513
|
+
precisionGrid: number;
|
|
514
|
+
};
|
|
515
|
+
|
|
516
|
+
export { }
|