@urban-toolkit/autk-grammar 5.1.0 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"autk-grammar-data.js","sources":["../../src/workspace.ts","../../src/rows.ts","../../src/adapters/data.ts"],"sourcesContent":["import { AutkDb, DEFAULT_WORKSPACE_NAME } from '@urban-toolkit/autk-db';\n\n/**\n * Makes `workspace` (the default one without a name) the workspace `db` works in; autk-db creates it on first use.\n * It calls autk-db's `setWorkspace` only when `getCurrentWorkspace()` names another one.\n *\n * Every adapter calls it before it reads or writes a table of a spec entry, with the entry's `workspace`. A host that\n * reads a spec's tables itself calls it the same way, since autk-db finds a table by its name in the current\n * workspace only.\n */\nexport async function enterWorkspace(db: AutkDb, workspace?: string): Promise<void> {\n const name = workspace ?? DEFAULT_WORKSPACE_NAME;\n if (db.getCurrentWorkspace() !== name) await db.setWorkspace(name);\n}\n\n/**\n * The key a table has in the grammar's caches: its name in the default workspace, `<workspace>/<name>` in another, so\n * two workspaces can hold tables of the same name. A host reads the caches it passes to `createDataAdapter` and\n * `createComputeAdapter` with it.\n */\nexport function tableKey(workspace: string | undefined, name: string): string {\n return workspace === undefined || workspace === DEFAULT_WORKSPACE_NAME ? name : `${workspace}/${name}`;\n}\n","import type { Feature } from 'geojson';\n\n/**\n * A selection passes between a plot and a map layer by the rows each drew, not by positions. A plot draws its table's\n * rows in the order the host handed them, while a map layer draws autk-db's export of the table, which can keep the\n * rows in an order of its own and leaves out those without a geometry, so one position can be another row in each\n * view. Each row is known in both by its feature id, which autk-db keeps in its export. Nothing here needs a GPU or a\n * database, so the unit tests run it in Node.\n */\n\n/**\n * The id autk-db gives each feature of a GeoJSON source: its own `id`, else `autk-feature-<index>`, with `-generated`\n * added while another feature has that id. The data adapter hands autk-db features that carry these ids, so autk-db\n * keeps them in its export whatever rule it would use itself.\n */\nexport function featureIds(features: readonly (Feature | null | undefined)[]): Array<string | number> {\n const own = new Set<string>();\n for (const feature of features) {\n if (feature?.id != null) own.add(JSON.stringify(feature.id));\n }\n const given = new Set<string>();\n return features.map((feature, index) => {\n if (feature?.id != null) return feature.id;\n let id = `autk-feature-${index}`;\n while (own.has(JSON.stringify(id)) || given.has(JSON.stringify(id))) id = `${id}-generated`;\n given.add(JSON.stringify(id));\n return id;\n });\n}\n\n/**\n * The key of each row of a collection, which names the row in every view of its table: its id as {@link featureIds}\n * gives it, written as JSON so that `3` and `\"3\"` stay apart, and the times that id came before when it repeats.\n */\nexport function rowKeys(features: readonly (Feature | null | undefined)[]): string[] {\n const seen = new Map<string, number>();\n return featureIds(features).map((id) => {\n const json = JSON.stringify(id);\n const before = seen.get(json) ?? 0;\n seen.set(json, before + 1);\n return before === 0 ? json : `${json} ${before}`;\n });\n}\n\n/** Each key's positions, built once for each list of keys. */\nconst positionsByKey = new WeakMap<readonly string[], Map<string, number[]>>();\n\nfunction positionsOf(keys: readonly string[]): Map<string, number[]> {\n let positions = positionsByKey.get(keys);\n if (positions) return positions;\n positions = new Map();\n keys.forEach((key, position) => {\n const list = positions!.get(key);\n if (list) list.push(position);\n else positions!.set(key, [position]);\n });\n positionsByKey.set(keys, positions);\n return positions;\n}\n\n/**\n * The positions in one view of the rows at the positions `ids` in another, each view given by the key of the row at\n * each of its positions. A row the other view does not draw has no position there, and a row it draws at several\n * positions has each of them.\n */\nexport function translateIds(ids: readonly number[], from: readonly string[], to: readonly string[]): number[] {\n const positions = positionsOf(to);\n const translated = new Set<number>();\n for (const id of ids) {\n const key = from[id];\n if (key === undefined) continue;\n for (const position of positions.get(key) ?? []) translated.add(position);\n }\n return [...translated];\n}\n","import { CsvDataSourceSpec, CustomDataSourceSpec, DataAdapter, DataSourceSpec, DropSourceSpec, GeoTiffDataSourceSpec, HeatmapSourceSpec, JoinSourceSpec, JsonDataSourceSpec, OsmDataSourceSpec, SqlSourceSpec, UpdateSourceSpec, WorkspaceSpec } from '@urban-toolkit/the-urban-grammar';\nimport { AutkDb, DEFAULT_WORKSPACE_NAME, isRenderableTable, isVectorTable } from '@urban-toolkit/autk-db';\nimport type { LoadGeojsonParams, Table } from '@urban-toolkit/autk-db';\nimport type { FeatureCollection, Geometry } from 'geojson';\nimport { Targets, GeoJsonCache } from '../types';\nimport { enterWorkspace, tableKey } from '../workspace';\nimport { featureIds } from '../rows';\n\n/** An empty geometry: a GeometryCollection with none in it, which a map draws as nothing. */\nconst NO_GEOMETRY: Geometry = { type: 'GeometryCollection', geometries: [] };\n\n/**\n * A GeoJSON source's collection as autk-db loads it, row for row.\n *\n * - Each feature carries the id autk-db gives it (see `featureIds`), from its place in the source. autk-db keeps the\n * id in its export, so a row a map draws from the export is found among the source's own rows, which a plot draws.\n * - autk-db refuses a feature whose geometry is null, which GeoJSON allows, so such a feature gets an empty one: a map\n * draws nothing for it, and a plot still counts it.\n * - autk-db reads the layer's type off the first feature, so a first feature without a geometry trades places with the\n * first that has one. Each keeps its id, so the rows are still found by it.\n */\nfunction loadableCollection(collection: FeatureCollection): FeatureCollection {\n const features = collection.features ?? [];\n const ids = featureIds(features);\n let changed = false;\n const loadable = features.map((feature, index) => {\n if (feature == null || (feature.id != null && feature.geometry != null)) return feature;\n changed = true;\n return { ...feature, id: ids[index], geometry: feature.geometry ?? NO_GEOMETRY };\n });\n const first = features.findIndex((feature) => feature?.geometry != null);\n if (first > 0 && features[0] != null && features[0].geometry == null) {\n [loadable[0], loadable[first]] = [loadable[first], loadable[0]];\n changed = true;\n }\n return changed ? { ...collection, features: loadable } : collection;\n}\n\n/**\n * The query area autk-db reads: `{ bbox }` or `{ geocodeArea, areas }`. autk-db takes any area with a\n * `bbox` key as a box, so a box that also names areas, or that is not [west, south, east, north] in\n * degrees with west less than east and south less than north, is refused here.\n */\nfunction queryAreaOf(spec: OsmDataSourceSpec): OsmDataSourceSpec['queryArea'] {\n const { queryArea } = spec;\n if (queryArea.bbox === undefined) return { geocodeArea: queryArea.geocodeArea, areas: queryArea.areas };\n\n const refuse = (message: string) => new Error(`OSM source \"${spec.outputTableName}\": ${message}`);\n if (queryArea.geocodeArea !== undefined || queryArea.areas !== undefined)\n throw refuse('queryArea takes either bbox or geocodeArea with areas, not both.');\n const box: unknown = queryArea.bbox;\n if (!Array.isArray(box) || box.length !== 4 || !box.every((value) => typeof value === 'number' && Number.isFinite(value)))\n throw refuse('queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.');\n const [west, south, east, north] = queryArea.bbox;\n if (Math.abs(west) > 180 || Math.abs(east) > 180)\n throw refuse('queryArea.bbox west and east must be longitudes from -180 to 180.');\n if (Math.abs(south) > 90 || Math.abs(north) > 90)\n throw refuse('queryArea.bbox south and north must be latitudes from -90 to 90.');\n if (west >= east)\n throw refuse(`queryArea.bbox west (${west}) must be less than east (${east}); a box across the antimeridian is not supported.`);\n if (south >= north)\n throw refuse(`queryArea.bbox south (${south}) must be less than north (${north}).`);\n return { bbox: [west, south, east, north] };\n}\n\n/**\n * Maps an OSM source onto autk-db's parameters, which always expect `autoLoadLayers`, with the CRS of the source's\n * coordinates when it gives one, and no longer take `dropOsmTable`. autk-db reads `tagSets` from the Overpass API only,\n * so a source that also names a PBF extract is refused here, by its name.\n */\nfunction toLoadOsmParams(spec: OsmDataSourceSpec) {\n const { autoLoadLayers, ...rest } = spec;\n if (spec.pbfFileUrl !== undefined && (spec.tagSets?.length ?? 0) > 0)\n throw new Error(`OSM source \"${spec.outputTableName}\": tagSets are read from the Overpass API only, so a source with pbfFileUrl cannot take them.`);\n return {\n ...rest,\n queryArea: queryAreaOf(spec),\n autoLoadLayers: {\n layers: autoLoadLayers?.layers ?? [],\n ...(autoLoadLayers?.coordinateFormat !== undefined && { coordinateFormat: autoLoadLayers.coordinateFormat }),\n },\n };\n}\n\n/**\n * The CRS advice. Only a bounding-box check gives it, when the box shows that a layer's coordinates\n * are not in the CRS it was loaded as; any other load error is autk-db's own message.\n */\nfunction crsAdvice(coordinateFormat: string | undefined): string {\n const assumed = coordinateFormat\n ? `coordinateFormat is set to \"${coordinateFormat}\"`\n : 'no coordinateFormat was specified, so it defaults to EPSG:4326 (WGS84 per RFC 7946)';\n return `${assumed}. Verify that coordinateFormat matches the actual CRS of the input data.`;\n}\n\n/** How a message names a workspace: the default one, or another by its name. */\nfunction workspaceLabel(name: string | undefined): string {\n return name === undefined || name === DEFAULT_WORKSPACE_NAME ? 'the default workspace' : `the workspace \"${name}\"`;\n}\n\n/** A feature property's value as SQL's `->>` reads it: a string as it is, any other value as its JSON. */\nfunction propertyText(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n return typeof value === 'string' ? value : JSON.stringify(value);\n}\n\n/**\n * The rows of an update of a layer keyed by a feature property, `properties.<name>`, keyed instead by the feature ids of\n * the table's rows they match. autk-db 4.1.1 matches such a key with `table.properties->>'name' =\n * staging.properties->>'name'`, which DuckDB reads so that the comparison is NULL: no row matches, and nothing is\n * updated. It matches a plain column as written. So each given feature goes to every row whose property has its value,\n * compared as text, as `->>` reads it, under that row's id in autk-db's export: its `geojson_id`, else its `id`.\n */\nasync function updateByFeatureId(db: AutkDb, table: Table, rows: FeatureCollection, property: string): Promise<{ data: FeatureCollection, idColumn: string }> {\n const ids = new Map<string, Array<string | number>>();\n for (const row of (await db.getLayer(table.name)).features) {\n const key = propertyText((row.properties as Record<string, unknown> | null)?.[property]);\n if (key === undefined) continue;\n if (row.id === undefined || row.id === null)\n throw new Error('its rows have no feature id to update them by.');\n ids.set(key, [...(ids.get(key) ?? []), row.id]);\n }\n const features = rows.features.flatMap((feature) => {\n const key = propertyText((feature.properties as Record<string, unknown> | null)?.[property]);\n return key === undefined ? [] : (ids.get(key) ?? []).map((id) => ({ ...feature, id }));\n });\n const idColumn = table.columns.some((column) => column.name === 'geojson_id') ? 'geojson_id' : 'id';\n return { data: { ...rows, features }, idColumn };\n}\n\n/** The database a source loads into: `context`, else a new one. */\nasync function database(context: AutkDb | undefined): Promise<AutkDb> {\n if (context) return context;\n const db = new AutkDb();\n await db.init();\n return db;\n}\n\n/** The [minX, minY, maxX, maxY] of every position in a collection, or undefined when it has none. */\nexport function extentOf(collection: FeatureCollection): [number, number, number, number] | undefined {\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n const visitPositions = (value: unknown): void => {\n if (!Array.isArray(value)) return;\n if (typeof value[0] === 'number') {\n const [x, y] = value as number[];\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n return;\n }\n for (const inner of value) visitPositions(inner);\n };\n const visitGeometry = (geometry: Geometry | null | undefined): void => {\n if (!geometry) return;\n if (geometry.type === 'GeometryCollection') geometry.geometries.forEach(visitGeometry);\n else visitPositions(geometry.coordinates);\n };\n for (const feature of collection.features ?? []) visitGeometry(feature?.geometry);\n return minX <= maxX ? [minX, minY, maxX, maxY] : undefined;\n}\n\n/**\n * The data adapter `AutkGrammar` runs. Its `resolveSource(db, source)` loads one entry of a spec's `data` into the\n * autk-db database `db` (a new one when `db` is undefined), in the entry's workspace, which it leaves current, and\n * returns the database. Its `resolveWorkspaces(db, workspaces)` sets each workspace a spec's `workspaces` lists to its\n * CRS and precision grid, before the first source loads, leaves the default workspace current and returns the database.\n *\n * A host calls it to load a spec's tables exactly as the grammar does, for example on a server without a map: the\n * `./data` entry exports it with autk-db as its only import. `targets.db` names an element that lists the tables\n * after each load. `cache`, when given, receives each GeoJSON table and each table a join or an update wrote, under\n * {@link tableKey}, and loses each table a `sql` source replaces or a `drop` source drops.\n */\nexport function createDataAdapter(targets?: Targets, cache?: GeoJsonCache): Required<DataAdapter> {\n\n function print(db: AutkDb, targets?: Targets): void {\n if(!targets || !targets.db)\n return\n\n const div = document.getElementById(targets.db);\n if (div) {\n const tables = db.getTablesMetadata();\n\n div.innerHTML += `<ul>`;\n for (const table of tables) {\n div.innerHTML += `<li>${table.name}: (${table.source}, ${table.type}) </li>`;\n }\n div.innerHTML += `</ul>`;\n\n div.innerHTML += `<p>Number of tables: ${tables.length}</p>`;\n }\n }\n\n /**\n * Puts a table a source changed in `cache` as autk-db now exports it, as a join's, or takes it out when autk-db does\n * not export it as a layer: the plots read a table from the cache before autk-db.\n */\n async function recache(db: AutkDb, workspace: string | undefined, name: string): Promise<void> {\n if (!cache) return;\n const key = tableKey(workspace, name);\n const table = db.getTablesMetadata().find((candidate) => candidate.name === name);\n if (table && isRenderableTable(table)) cache.set(key, await db.getLayer(name));\n else cache.delete(key);\n }\n\n return {\n async resolveWorkspaces(context: AutkDb | undefined, workspaces: WorkspaceSpec[]): Promise<AutkDb> {\n const db = await database(context);\n const named = new Set<string>();\n for (const { name, coordinateFormat, precisionGrid } of workspaces) {\n const workspace = name ?? DEFAULT_WORKSPACE_NAME;\n if (named.has(workspace))\n throw new Error(`workspaces sets ${workspaceLabel(name)} twice; give each workspace one entry.`);\n named.add(workspace);\n // autk-db creates the workspace with this configuration, or sets it on the one that exists while it\n // holds no table, the default workspace among them.\n try {\n await db.setWorkspace(workspace, { coordinateFormat, precisionGrid });\n } catch (err) {\n throw new Error(`workspaces, ${workspaceLabel(name)}: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n // Each source, compute pass, map and plot enters its own workspace.\n await enterWorkspace(db);\n return db;\n },\n\n async resolveSource(context: AutkDb | undefined, spec: DataSourceSpec): Promise<AutkDb> {\n\n const db = await database(context);\n\n const { workspace } = spec as { workspace?: string };\n await enterWorkspace(db, workspace);\n\n let {type, workspace: _workspace, ...rest_spec} = spec as DataSourceSpec & { workspace?: string };\n\n switch (type) {\n case 'osm':\n await db.loadOsm(toLoadOsmParams(rest_spec as OsmDataSourceSpec));\n print(db, targets);\n return db;\n case 'csv':\n await db.loadCsv(rest_spec as CsvDataSourceSpec);\n print(db, targets);\n return db;\n case 'json':\n await db.loadJson(rest_spec as JsonDataSourceSpec);\n print(db, targets);\n return db;\n case 'geojson': {\n const geojsonSpec = rest_spec as CustomDataSourceSpec;\n let geojsonData: FeatureCollection | undefined;\n\n if (geojsonSpec.geojsonFileUrl) {\n const response = await fetch(geojsonSpec.geojsonFileUrl);\n geojsonData = await response.json() as FeatureCollection;\n } else {\n // The inline type allows a feature whose geometry is null, which autk-db refuses: loadableCollection\n // gives such a feature an empty geometry before autk-db loads it.\n geojsonData = geojsonSpec.geojsonObject as FeatureCollection | undefined;\n }\n\n if (cache && geojsonData) cache.set(tableKey(workspace, geojsonSpec.outputTableName), geojsonData);\n\n // Pass the fetched object directly so autk-db doesn't need to re-fetch, as autk-db loads it (see\n // loadableCollection). The cache keeps the source's own rows, in their order, for its plots.\n const loadSpec = (geojsonData\n ? (() => { const s = { ...geojsonSpec, geojsonObject: loadableCollection(geojsonData) }; delete s.geojsonFileUrl; return s; })()\n : geojsonSpec) as LoadGeojsonParams;\n\n // Degrees put every y within -90 to 90, so a y outside it shows a layer in another CRS. The\n // transform makes such a y infinite, and autk-db would refuse the layer with a grid error.\n // A longitude past 180 is not checked: the transform wraps it.\n const readAsDegrees = /^EPSG:4326$/i.test(loadSpec.coordinateFormat ?? 'EPSG:4326');\n const extent = geojsonData && readAsDegrees ? extentOf(geojsonData) : undefined;\n if (extent && (extent[1] < -90 || extent[3] > 90)) {\n throw new Error(\n `GeoJSON layer \"${loadSpec.outputTableName}\" has y coordinates outside -90 to 90 ` +\n `(bbox: [${extent.join(', ')}]), so they cannot be EPSG:4326 degrees. ${crsAdvice(loadSpec.coordinateFormat)}`\n );\n }\n\n try {\n await db.loadGeojson(loadSpec);\n } catch (err) {\n throw new Error(`Failed to load GeoJSON layer \"${loadSpec.outputTableName}\": ${err instanceof Error ? err.message : String(err)}`);\n }\n\n // Validate that the loaded geometry is within the workspace CRS extent.\n // A bounding box outside the valid world extent indicates a CRS mismatch.\n try {\n const bbox = await db.getBoundingBoxFromLayer(loadSpec.outputTableName);\n const WORLD_EXTENT = 25_000_000; // generous bound for World Mercator (EPSG:3395), autk-db's default CRS\n if (\n !isFinite(bbox.minLon) || !isFinite(bbox.minLat) ||\n !isFinite(bbox.maxLon) || !isFinite(bbox.maxLat) ||\n Math.abs(bbox.minLon) > WORLD_EXTENT || Math.abs(bbox.maxLon) > WORLD_EXTENT ||\n Math.abs(bbox.minLat) > WORLD_EXTENT || Math.abs(bbox.maxLat) > WORLD_EXTENT\n ) {\n throw new Error(\n `Geometry bounding box after transform is invalid for layer \"${loadSpec.outputTableName}\" ` +\n `(bbox: [${bbox.minLon}, ${bbox.minLat}, ${bbox.maxLon}, ${bbox.maxLat}]). ` +\n `${crsAdvice(loadSpec.coordinateFormat)} ` +\n `The workspace uses ${db.getWorkspaceConfiguration().coordinateFormat}; input is expected in EPSG:4326 by default.`\n );\n }\n } catch (bboxErr) {\n if (bboxErr instanceof Error && bboxErr.message.includes('bounding box after transform')) throw bboxErr;\n // getBoundingBoxFromLayer failed (empty table, unsupported layer type, etc.): skip validation\n }\n print(db, targets);\n return db;\n }\n case 'geotiff':\n await db.loadGeoTiff(rest_spec as GeoTiffDataSourceSpec);\n print(db, targets);\n return db;\n case 'heatmap': {\n const hm = rest_spec as HeatmapSourceSpec;\n // The schema refuses collect in a heatmap, but a spec that was not checked against it reaches here.\n if (hm.groupBy?.some((group) => (group.aggregateFn as string | undefined) === 'collect'))\n throw new Error(`Heatmap \"${hm.outputTableName}\": aggregateFn \"collect\" lists the rows near a cell, and a cell holds one value; use sum, avg, count, min, max or weighted.`);\n await db.buildHeatmap({\n tableJoinName: hm.joinDataRef,\n near: hm.near,\n outputTableName: hm.outputTableName,\n grid: hm.grid,\n ...(hm.groupBy && { groupBy: hm.groupBy }),\n });\n print(db, targets);\n return db;\n }\n case 'join': {\n const jn = rest_spec as JoinSourceSpec;\n await db.spatialQuery({\n tableRootName: jn.dataRef,\n tableJoinName: jn.joinDataRef,\n ...(jn.near && { near: jn.near }),\n ...(jn.groupBy && { groupBy: jn.groupBy }),\n });\n if (cache) {\n const updated = await db.getLayer(jn.dataRef);\n cache.set(tableKey(workspace, jn.dataRef), updated);\n }\n print(db, targets);\n return db;\n }\n case 'sql': {\n const sql = rest_spec as SqlSourceSpec;\n try {\n await db.rawQuery({\n query: sql.query,\n output: {\n type: 'CREATE_TABLE',\n tableName: sql.outputTableName,\n source: 'user',\n ...(sql.layerType !== undefined && { tableType: sql.layerType }),\n },\n });\n } catch (err) {\n throw new Error(`SQL source \"${sql.outputTableName}\": ${err instanceof Error ? err.message : String(err)}`);\n }\n // A query saved under the name of a GeoJSON table replaces it, so the plots no longer read its rows.\n cache?.delete(tableKey(workspace, sql.outputTableName));\n print(db, targets);\n return db;\n }\n case 'update': {\n const update = rest_spec as UpdateSourceSpec;\n const refuse = (message: string) => new Error(`Update of \"${update.dataRef}\": ${message}`);\n // The schema refuses these shapes too, but a spec that was not checked against it reaches here.\n if ((update.geojsonObject === undefined) === (update.jsonObject === undefined))\n throw refuse('give its rows in geojsonObject or in jsonObject, one of the two.');\n if (update.strategy === 'update' && !update.idColumn)\n throw refuse(\"the update strategy needs an idColumn, the column that matches a given row to the table's rows.\");\n let data = (update.geojsonObject ?? update.jsonObject) as FeatureCollection | Record<string, unknown>[];\n let idColumn = update.idColumn;\n try {\n // A layer keyed by a feature property is matched here, then updated by its rows' feature ids.\n const table = db.getTablesMetadata().find((candidate) => candidate.name === update.dataRef);\n if (update.strategy === 'update' && update.geojsonObject && idColumn?.startsWith('properties.') && table && isVectorTable(table)) {\n ({ data, idColumn } = await updateByFeatureId(db, table, update.geojsonObject as FeatureCollection, idColumn.slice('properties.'.length)));\n // No row has a given key, so the table stays as it is, as autk-db leaves it.\n if ((data as FeatureCollection).features.length === 0) {\n print(db, targets);\n return db;\n }\n }\n await db.updateTable({\n tableName: update.dataRef,\n data,\n strategy: update.strategy,\n ...(idColumn !== undefined && { idColumn }),\n });\n } catch (err) {\n throw refuse(err instanceof Error ? err.message : String(err));\n }\n await recache(db, workspace, update.dataRef);\n print(db, targets);\n return db;\n }\n case 'drop': {\n const drop = rest_spec as DropSourceSpec;\n // autk-db drops a table it does not hold without a word, so a name that names none is refused here.\n if (!db.getTablesMetadata().some((table) => table.name === drop.dataRef))\n throw new Error(`Drop of \"${drop.dataRef}\": ${workspaceLabel(workspace)} holds no table of that name.`);\n await db.removeLayer(drop.dataRef);\n cache?.delete(tableKey(workspace, drop.dataRef));\n print(db, targets);\n return db;\n }\n default:\n // The schema refuses any other type, but a spec that was not checked against it reaches here. Handing\n // the engine no database would make the next source start a new one, without the tables before it.\n throw new Error(`Unknown data source type \"${String(type)}\".`);\n }\n }\n }\n}\n"],"names":["enterWorkspace","db","workspace","name","DEFAULT_WORKSPACE_NAME","tableKey","featureIds","features","own","feature","given","index","id","NO_GEOMETRY","loadableCollection","collection","ids","changed","loadable","first","queryAreaOf","spec","queryArea","refuse","message","box","value","west","south","east","north","toLoadOsmParams","autoLoadLayers","rest","crsAdvice","coordinateFormat","workspaceLabel","propertyText","updateByFeatureId","table","rows","property","row","key","idColumn","column","database","context","AutkDb","extentOf","minX","minY","maxX","maxY","visitPositions","x","inner","visitGeometry","geometry","createDataAdapter","targets","cache","print","div","tables","recache","candidate","isRenderableTable","workspaces","named","precisionGrid","err","type","_workspace","rest_spec","geojsonSpec","geojsonData","loadSpec","s","readAsDegrees","extent","bbox","WORLD_EXTENT","bboxErr","hm","group","jn","updated","sql","update","data","isVectorTable","drop"],"mappings":";AAUA,eAAsBA,EAAeC,GAAYC,GAAmC;AAChF,QAAMC,IAAOD,KAAaE;AAC1B,EAAIH,EAAG,0BAA0BE,KAAM,MAAMF,EAAG,aAAaE,CAAI;AACrE;AAOO,SAASE,EAASH,GAA+BC,GAAsB;AAC1E,SAAOD,MAAc,UAAaA,MAAcE,IAAyBD,IAAO,GAAGD,CAAS,IAAIC,CAAI;AACxG;ACPO,SAASG,EAAWC,GAA2E;AAClG,QAAMC,wBAAU,IAAA;AAChB,aAAWC,KAAWF;AAClB,IAAIE,GAAS,MAAM,QAAMD,EAAI,IAAI,KAAK,UAAUC,EAAQ,EAAE,CAAC;AAE/D,QAAMC,wBAAY,IAAA;AAClB,SAAOH,EAAS,IAAI,CAACE,GAASE,MAAU;AACpC,QAAI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ows.ts","../../src/adapters/data.ts"],"sourcesContent":["import { AutkDb, DEFAULT_WORKSPACE_NAME } from '@urban-toolkit/autk-db';\nimport type { FeatureCollection } from 'geojson';\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\n/**\n * The CRS of the coordinates of each collection a GeoJSON source put in a cache: the source's own. The package's two\n * entries, the main one and `./data`, are built apart, each with a copy of this module, so the notes live in one map\n * that both copies find on the page under one global key: a compute adapter from one entry reads the notes of a data\n * adapter from the other.\n */\nconst SOURCE_CRS = Symbol.for('@urban-toolkit/autk-grammar:source-crs');\nconst pageWide = globalThis as unknown as Record<symbol, WeakMap<FeatureCollection, string> | undefined>;\nconst sourceCrs = (pageWide[SOURCE_CRS] ??= new WeakMap<FeatureCollection, string>());\n\n/**\n * Notes that a GeoJSON source put `collection` in a cache as it gave it, with its coordinates in `crs`, its\n * `coordinateFormat`, which autk-db transforms to its workspace's CRS as it loads the source.\n */\nexport function noteSourceCrs(collection: FeatureCollection, crs: string): void {\n sourceCrs.set(collection, crs);\n}\n\n/**\n * `collection` when a GeoJSON source put it in a cache with its coordinates in `workspaceCrs`, the CRS autk-db keeps its\n * workspace in, else `undefined`: a compute pass compares a `fromFeature` table's coordinates with its own table's,\n * which autk-db keeps in the workspace's CRS.\n */\nexport function inWorkspaceCrs(collection: FeatureCollection | undefined, workspaceCrs: string): FeatureCollection | undefined {\n const crs = collection && sourceCrs.get(collection);\n return crs !== undefined && crs.toUpperCase() === workspaceCrs.toUpperCase() ? collection : undefined;\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, noteSourceCrs, 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) {\n cache.set(tableKey(workspace, geojsonSpec.outputTableName), geojsonData);\n // autk-db reads a GeoJSON source in EPSG:4326 unless it names another CRS.\n noteSourceCrs(geojsonData, geojsonSpec.coordinateFormat ?? 'EPSG:4326');\n }\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","SOURCE_CRS","pageWide","sourceCrs","noteSourceCrs","collection","crs","featureIds","features","own","feature","given","index","id","NO_GEOMETRY","loadableCollection","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":";AAWA,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;AAQA,MAAMG,IAAa,uBAAO,IAAI,wCAAwC,GAChEC,IAAW,YACXC,IAAaD,EAASD,CAAU,0BAAU,QAAA;AAMzC,SAASG,EAAcC,GAA+BC,GAAmB;AAC5E,EAAAH,EAAU,IAAIE,GAAYC,CAAG;AACjC;AC1BO,SAASC,EAAWC,GAA2E;AAClG,QAAMC,wBAAU,IAAA;AAChB,aAAWC,KAAWF;AAClB,IAAIE,GAAS,MAAM,QAAMD,EAAI,IAAI,KAAK,UAAUC,EAAQ,EAAE,CAAC;AAE/D,QAAMC,wBAAY,IAAA;AAClB,SAAOH,EAAS,IAAI,CAACE,GAASE,MAAU;AACpC,QAAIF,GAAS,MAAM,KAAM,QAAOA,EAAQ;AACxC,QAAIG,IAAK,gBAAgBD,CAAK;AAC9B,WAAOH,EAAI,IAAI,KAAK,UAAUI,CAAE,CAAC,KAAKF,EAAM,IAAI,KAAK,UAAUE,CAAE,CAAC,IAAG,CAAAA,IAAK,GAAGA,CAAE;AAC/E,WAAAF,EAAM,IAAI,KAAK,UAAUE,CAAE,CAAC,GACrBA;AAAA,EACX,CAAC;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C,EAAS,MAAM,EAAoB,CAAC,GAEnI8C,EAA2B,SAAS,WAAW;AAChD,qBAAA5B,EAAMlE,GAAIgE,CAAO,GACVhE;AAGf,kBAAMA,EAAG,YAAY;AAAA,cACjB,WAAW6F,EAAO;AAAA,cAClB,MAAAC;AAAA,cACA,UAAUD,EAAO;AAAA,cACjB,GAAI7C,MAAa,UAAa,EAAE,UAAAA,EAAA;AAAA,YAAS,CAC5C;AAAA,UACL,SAAS2B,GAAK;AACV,kBAAMhD,EAAOgD,aAAe,QAAQA,EAAI,UAAU,OAAOA,CAAG,CAAC;AAAA,UACjE;AACA,uBAAMN,EAAQrE,GAAIC,GAAW4F,EAAO,OAAO,GAC3C3B,EAAMlE,GAAIgE,CAAO,GACVhE;AAAA,QACX;AAAA,QACA,KAAK,QAAQ;AACT,gBAAMgG,IAAOlB;AAEb,cAAI,CAAC9E,EAAG,kBAAA,EAAoB,KAAK,CAAC2C,MAAUA,EAAM,SAASqD,EAAK,OAAO;AACnE,kBAAM,IAAI,MAAM,YAAYA,EAAK,OAAO,MAAMxD,EAAevC,CAAS,CAAC,+BAA+B;AAC1G,uBAAMD,EAAG,YAAYgG,EAAK,OAAO,GACjC/B,GAAO,OAAO7D,EAASH,GAAW+F,EAAK,OAAO,CAAC,GAC/C9B,EAAMlE,GAAIgE,CAAO,GACVhE;AAAA,QACX;AAAA,QACA;AAGI,gBAAM,IAAI,MAAM,6BAA6B,OAAO4E,CAAI,CAAC,IAAI;AAAA,MAAA;AAAA,IAEzE;AAAA,EAAA;AAER;"}
package/dist/index.d.ts CHANGED
@@ -164,6 +164,20 @@ export declare class AutkGrammar {
164
164
  private _selectInLinkedPlots;
165
165
  /** Wires each entry of `links` between a plot and a layer of a map, both now drawn. */
166
166
  private _wireLinks;
167
+ /**
168
+ * Draws each layer's `pickedComps` as picked once the maps, the plots and their links exist, as `highlightOnMap` does
169
+ * for that one layer: the layer highlights the features, and the plots linked to it select the same rows. autk-map
170
+ * draws picked features only on the layer of a map that picks, and lets one layer of a map pick, so a layer that no
171
+ * longer picks, since a link or a plot's `mapRef` made another layer of its map pick, is refused. So is one linked to a
172
+ * plot that sets `selection`, which sets what both show too.
173
+ */
174
+ private _pickFromTheStart;
175
+ /**
176
+ * Applies each plot's `selection` once the plots and their links exist, as `setPlotSelection` does: the plot selects
177
+ * the rows, and the layers it is linked to, by `mapRef` or `links`, highlight them. autk-plot's `setSelection` emits
178
+ * no event, so no `plot:selection` reports it.
179
+ */
180
+ private _selectFromTheStart;
167
181
  private _rewireInteractions;
168
182
  }
169
183
 
@@ -224,6 +238,9 @@ export declare type CameraSpec = {
224
238
  bearing?: number;
225
239
  };
226
240
 
241
+ /** A categorical color scheme: a `scheme*` name, one color for each category. */
242
+ export declare type CategoricalColorMapInterpolator = ColorMapInterpolator.CAT_ACCENT | ColorMapInterpolator.CAT_DARK2 | ColorMapInterpolator.CAT_CATEGORY10 | ColorMapInterpolator.CAT_OBSERVABLE10 | ColorMapInterpolator.CAT_PAIRED | ColorMapInterpolator.CAT_PASTEL1 | ColorMapInterpolator.CAT_PASTEL2 | ColorMapInterpolator.CAT_SET1 | ColorMapInterpolator.CAT_SET2 | ColorMapInterpolator.CAT_SET3 | ColorMapInterpolator.CAT_TABLEAU10;
243
+
227
244
  /** Color scheme for a colored map layer: `scheme*` names are categorical, `interpolate*` names are sequential or diverging. */
228
245
  export declare enum ColorMapInterpolator {
229
246
  CAT_ACCENT = "schemeAccent",
@@ -310,6 +327,9 @@ export declare type ComputeRunner = (params: GpgpuPipelineParams) => Promise<Fea
310
327
  /** One entry of `compute`. A pass with `type: 'render'` is a {@link RenderComputeSpec}, any other a {@link GpgpuComputeSpec}. */
311
328
  export declare type ComputeSpec = GpgpuComputeSpec | RenderComputeSpec;
312
329
 
330
+ /** A sequential or diverging color scheme: an `interpolate*` name, a color for each number of a scale. */
331
+ export declare type ContinuousColorMapInterpolator = ColorMapInterpolator.SEQ_REDS | ColorMapInterpolator.SEQ_BLUES | ColorMapInterpolator.SEQ_GREENS | ColorMapInterpolator.SEQ_GREYS | ColorMapInterpolator.SEQ_ORANGES | ColorMapInterpolator.SEQ_PURPLES | ColorMapInterpolator.SEQ_TURBO | ColorMapInterpolator.SEQ_VIRIDIS | ColorMapInterpolator.SEQ_INFERNO | ColorMapInterpolator.SEQ_MAGMA | ColorMapInterpolator.SEQ_PLASMA | ColorMapInterpolator.SEQ_CIVIDIS | ColorMapInterpolator.SEQ_WARM | ColorMapInterpolator.SEQ_COOL | ColorMapInterpolator.SEQ_CUBEHELIX_DEFAULT | ColorMapInterpolator.SEQ_BU_GN | ColorMapInterpolator.SEQ_BU_PU | ColorMapInterpolator.SEQ_GN_BU | ColorMapInterpolator.SEQ_OR_RD | ColorMapInterpolator.SEQ_PU_BU_GN | ColorMapInterpolator.SEQ_PU_BU | ColorMapInterpolator.SEQ_PU_RD | ColorMapInterpolator.SEQ_RD_PU | ColorMapInterpolator.SEQ_YL_GN_BU | ColorMapInterpolator.SEQ_YL_GN | ColorMapInterpolator.SEQ_YL_OR_BR | ColorMapInterpolator.SEQ_YL_OR_RD | ColorMapInterpolator.DIV_BR_BG | ColorMapInterpolator.DIV_PR_GN | ColorMapInterpolator.DIV_PI_YG | ColorMapInterpolator.DIV_PU_OR | ColorMapInterpolator.DIV_RED_BLUE | ColorMapInterpolator.DIV_RED_GREY | ColorMapInterpolator.DIV_RED_YELLOW_BLUE | ColorMapInterpolator.DIV_RED_YELLOW_GREEN | ColorMapInterpolator.DIV_SPECTRAL;
332
+
313
333
  /**
314
334
  * The compute adapter `AutkGrammar` runs. Its `resolveCompute(db, pass)` runs one entry of a spec's `compute`, a
315
335
  * GPGPU pass or a render pass, on autk-compute, in the pass's workspace, which it leaves current. It does nothing
@@ -318,9 +338,11 @@ export declare type ComputeSpec = GpgpuComputeSpec | RenderComputeSpec;
318
338
  * A host calls it to run compute passes exactly as the grammar does. The passes need WebGPU, and their results are
319
339
  * kept only in the caches: `cache` receives each pass's result under {@link tableKey} of its `outputTableName`, or of
320
340
  * the table it computed over, and a later pass reads a table from it first. `types` receives the layer type of each
321
- * table a pass wrote under its own `outputTableName`, which a map needs to draw it.
341
+ * table a pass wrote under its own `outputTableName`, which a map needs to draw it. `sources` is the cache the data
342
+ * adapter fills: a pass reads a `fromFeature` table from it next, as its plots read theirs, when a GeoJSON source put
343
+ * the table there with its coordinates in the workspace's CRS.
322
344
  */
323
- export declare function createComputeAdapter(cache?: ComputeCache, types?: ComputeLayerTypes): ComputeAdapter;
345
+ export declare function createComputeAdapter(cache?: ComputeCache, types?: ComputeLayerTypes, sources?: GeoJsonCache): ComputeAdapter;
324
346
 
325
347
  /**
326
348
  * The data adapter `AutkGrammar` runs. Its `resolveSource(db, source)` loads one entry of a spec's `data` into the
@@ -453,7 +475,11 @@ export declare function findIterateSource(block: GpgpuComputeSpec): {
453
475
  */
454
476
  export declare type FromFeatureDirective = {
455
477
  fromFeature: {
456
- /** Table to read from. */
478
+ /**
479
+ * Table to read from. The Autark adapter reads it as an earlier compute pass wrote it; else, when a GeoJSON source
480
+ * loaded it with its coordinates in its workspace's CRS, as the source gave its features, each building part with
481
+ * its own outline; else as autk-db keeps it, a buildings table's geometry inside a GeometryCollection.
482
+ */
457
483
  layer: string;
458
484
  /** Dot path from the feature root, for example `properties.height` or `geometry.coordinates.0`. */
459
485
  path: string;
@@ -809,8 +835,8 @@ export declare type MapId = string | number;
809
835
 
810
836
  /**
811
837
  * One layer drawn by a map.
812
- * @if { "required": ["colorMapRange"] }
813
- * @then { "not": { "required": ["colorMapDomain"] } }
838
+ * @if { "type": "object" }
839
+ * @then { "allOf": [{ "if": { "required": ["colorMapRange"] }, "then": { "not": { "required": ["colorMapDomain"] } } }, { "if": { "required": ["pickedComps"] }, "then": { "required": ["isPick"], "not": { "properties": { "isPick": { "const": false } } } } }, { "if": { "required": ["widthBy"] }, "then": { "not": { "required": ["width"] } } }] }
814
840
  */
815
841
  export declare type MapLayerSpec = {
816
842
  /** Name of the table to draw, as produced by a data source or a compute pass. */
@@ -837,10 +863,20 @@ export declare type MapLayerSpec = {
837
863
  stroke?: HexColor | false;
838
864
  /**
839
865
  * Width of the lines of a polylines or roads layer, in the map's planar units (about meters). It replaces
840
- * the widths a roads layer gives each kind of road. Read by the Autark adapter; the deck.gl adapter ignores it.
866
+ * the widths a roads layer gives each kind of road. Not with `widthBy`. Read by the Autark adapter; the deck.gl
867
+ * adapter ignores it.
841
868
  * @exclusiveMinimum 0
842
869
  */
843
870
  width?: number;
871
+ /**
872
+ * Dot path to the width of each line of a roads layer, relative to `feature.properties`, in the map's planar units
873
+ * (about meters), as `width` gives every line one: autk-map's widths by feature. A line without a positive number there
874
+ * keeps the width of its kind of road. autk-map draws every line of a polylines layer at one width, so a table of lines
875
+ * takes it drawn as roads, with `layerType: 'roads'`. Not with `width`. Read by the Autark adapter; the deck.gl adapter
876
+ * ignores it.
877
+ * @minLength 1
878
+ */
879
+ widthBy?: string;
844
880
  /**
845
881
  * Radius of each point of a points layer, in meters on the ground. The Autark adapter converts it to the
846
882
  * workspace's planar units at the middle of the layer's extent, where World Mercator, the default, stretches a
@@ -851,6 +887,13 @@ export declare type MapLayerSpec = {
851
887
  pointSize?: number;
852
888
  /** Color the layer by the value read with `getFnv`. */
853
889
  isColorMap?: boolean;
890
+ /**
891
+ * Show this layer's color scale in the map's legend, which otherwise shows the last layer whose colors autk-map set,
892
+ * about the last layer colored by value. One layer of a map at most; a layer colored by value, or a raster, whose
893
+ * legend it shows; and a map that shows its controls. The layers pick as their `isPick` says. Read by the Autark
894
+ * adapter; the deck.gl adapter ignores it.
895
+ */
896
+ legend?: boolean;
854
897
  /** Color scheme used when `isColorMap` is set. */
855
898
  colorMapInterpolator?: ColorMapInterpolator;
856
899
  /**
@@ -882,19 +925,50 @@ export declare type MapLayerSpec = {
882
925
  * raster layers; other layers and the deck.gl adapter ignore it.
883
926
  */
884
927
  transferFunction?: RasterTransferFunction;
885
- /** Legend labels. Read by the deck.gl adapter; the Autark adapter ignores it. */
928
+ /** Legend labels. Neither adapter reads it. */
886
929
  colorMapLabels?: string[];
887
- /** Feature ids drawn as picked. Read by the deck.gl adapter; the Autark adapter ignores it. */
888
- pickedComps?: number[];
930
+ /**
931
+ * Features drawn as picked from the start, in the map's highlight color, as if the user had picked them: their
932
+ * positions among the features the layer draws, as `map:picking` events give them. autk-map draws picked features
933
+ * only on the layer of a map that picks, so the layer sets `isPick: true`, and no later layer of its map sets it, nor
934
+ * does a link or a plot's `mapRef` make another layer of its map pick. The plots linked to the layer select the same
935
+ * rows. Read by the Autark adapter; the deck.gl adapter ignores it.
936
+ */
937
+ pickedComps?: RowPosition[];
938
+ /**
939
+ * Features the layer hides, by their positions among the features it draws, as `map:picking` events give them. A
940
+ * hidden feature of a polygons or buildings layer can still be picked with autk-map 4.1.1. Read by the Autark adapter;
941
+ * the deck.gl adapter ignores it.
942
+ */
943
+ skippedComps?: RowPosition[];
889
944
  /** How values are rescaled before coloring. */
890
945
  normalization?: {
891
946
  mode: NormalizationMode;
892
947
  lowerPercentile?: number;
893
948
  upperPercentile?: number;
894
949
  };
950
+ /**
951
+ * How the map draws the layer's table, in place of the table's own type, among the types of its kind of geometry: a
952
+ * table of polygons as `polygons`, `surface`, `parks`, `water` or `buildings` (raised by its heights), a table of lines
953
+ * as `polylines` or `roads`, a table of points as `points`, and a raster as `raster`. autk-map draws surface, parks,
954
+ * water and roads layers below the others, in that order, whatever the order of `layerRefs`. Read by the Autark
955
+ * adapter; the deck.gl adapter ignores it.
956
+ */
957
+ layerType?: LayerType;
958
+ /**
959
+ * Draw the parts of a buildings layer that have no height, each with a random height of 3 to 7 floors of 3.4 m (10.2
960
+ * to 23.8 m), rather than leave them out: autk-map's `buildingsZeroHeight`. A part has no height when it has none of
961
+ * `height`, `building:height`, `levels` and `building:levels`; a part with one of them whose height is not above its
962
+ * minimum, such as `0`, is still left out. The heights change at each run. Read by the Autark adapter for buildings
963
+ * layers; other layers and the deck.gl adapter ignore it.
964
+ */
965
+ buildingsZeroHeight?: boolean;
895
966
  /** Load the layer without drawing it. */
896
967
  isSkip?: boolean;
897
- /** Allow picking features on this layer. */
968
+ /**
969
+ * Allow picking features on this layer. autk-map lets one layer of a map pick: the last layer that sets it, unless a
970
+ * link or a plot's `mapRef` makes another layer of the map pick.
971
+ */
898
972
  isPick?: boolean;
899
973
  /**
900
974
  * Columns whose values name the rows a pick on this layer selects, so an app can link
@@ -910,7 +984,11 @@ export declare type MapLayerSpec = {
910
984
  * update changed are drawn row by row, as without it. Read by the Autark adapter only.
911
985
  */
912
986
  osmElements?: boolean;
913
- /** Dot path to the thematic value, relative to `feature.properties` (for example `tags.highway` or `compute.result`). */
987
+ /**
988
+ * Dot path to the thematic value, relative to `feature.properties` (for example `tags.highway` or `compute.result`).
989
+ * On a raster layer, the band to draw, by its id (`band_1`, ...) or its label (`count.noise` for a heatmap band labeled
990
+ * `count_noise`), the first band without it; on a raster of several bands, one that names none of them is refused.
991
+ */
914
992
  getFnv?: string;
915
993
  /** `categorical` reads the value as a string for discrete palettes; `quantitative` reads it as a number for continuous scales. Read by the deck.gl adapter; the Autark adapter ignores it. */
916
994
  getFnvType?: 'categorical' | 'quantitative';
@@ -932,14 +1010,68 @@ export declare type MapSpec = {
932
1010
  id?: string;
933
1011
  /** Workspace the map reads its layers' tables from. */
934
1012
  workspace?: WorkspaceName;
935
- /** Map style. */
936
- style?: string;
1013
+ /**
1014
+ * Map style: the name of one of autk-map's styles, such as `apple`, its default, or `light` (a name autk-map does not
1015
+ * know draws in `apple`), or the colors of a style of the spec's own. A layer with a `color` is drawn in it instead,
1016
+ * and a layer colored by value in its scheme. Read by the Autark adapter; the deck.gl adapter ignores it.
1017
+ */
1018
+ style?: string | MapStyleColors;
1019
+ /**
1020
+ * The color of the features the map draws as picked, by the user, a layer's `pickedComps`, a link or a call such as
1021
+ * `highlightOnMap`, `#rrggbb`. Each map has its own; autk-map's is `#5dade2`. Read by the Autark adapter; the deck.gl
1022
+ * adapter ignores it.
1023
+ */
1024
+ highlightColor?: HexColor;
1025
+ /**
1026
+ * The color of the features of a layer colored by value whose value autk-map cannot color: one without a value, or
1027
+ * with one that is not on the layer's scale, `#rrggbb`. Each map has its own; autk-map's is `#ffffff`. Read by the
1028
+ * Autark adapter; the deck.gl adapter ignores it.
1029
+ */
1030
+ invalidValueColor?: HexColor;
1031
+ /**
1032
+ * Whether autk-map shows its floating controls on the map: the menu of its layers and the legend. `false` hides them,
1033
+ * and the "made with autark" credit stays. Defaults to `true`. Read by the Autark adapter; the deck.gl adapter ignores
1034
+ * it.
1035
+ */
1036
+ showUi?: boolean;
937
1037
  /** Where the map looks from. */
938
1038
  camera?: CameraSpec;
1039
+ /**
1040
+ * A 3D ground from an elevation raster: autk-map raises the ground the raster covers to its heights, drapes the map's
1041
+ * flat layers over it, stands its buildings on it, and fits the view to it, from which `camera` moves. Read by the
1042
+ * Autark adapter; the deck.gl adapter ignores it.
1043
+ */
1044
+ terrain?: TerrainSpec;
939
1045
  /** Layers to draw, bottom first. Each names a table with `dataRef`. */
940
1046
  layerRefs: MapLayerSpec[];
941
1047
  };
942
1048
 
1049
+ /**
1050
+ * The colors of a map style of the spec's own, each `#rrggbb`: the background, and the color of each kind of layer
1051
+ * drawn in one color. autk-map takes a style only whole, so each of the nine is given. Read by the Autark adapter; the
1052
+ * deck.gl adapter ignores it.
1053
+ */
1054
+ export declare type MapStyleColors = {
1055
+ /** The map's background, where no layer is drawn. */
1056
+ background: HexColor;
1057
+ /** Surface layers: the ground of an area. */
1058
+ surface: HexColor;
1059
+ /** Parks layers. */
1060
+ parks: HexColor;
1061
+ /** Water layers. */
1062
+ water: HexColor;
1063
+ /** Roads layers. */
1064
+ roads: HexColor;
1065
+ /** Buildings layers. */
1066
+ buildings: HexColor;
1067
+ /** Points layers. */
1068
+ points: HexColor;
1069
+ /** Polylines layers. */
1070
+ polylines: HexColor;
1071
+ /** Polygons layers. */
1072
+ polygons: HexColor;
1073
+ };
1074
+
943
1075
  declare type MatrixEntry = {
944
1076
  data: number[][];
945
1077
  cols: number;
@@ -1101,7 +1233,79 @@ export declare interface PlotBase {
1101
1233
  * @minItems 1
1102
1234
  */
1103
1235
  axis: string[];
1236
+ /**
1237
+ * Column whose values color the marks: a scatter plot's points, a bar chart's bars, and the lines of parallel
1238
+ * coordinates, which a click on an axis's title colors by that axis instead. When every value is a number, or a
1239
+ * string that reads as one, the marks take `colorMapInterpolator`'s scheme; otherwise the values are categories,
1240
+ * and take `categoricalColorMapInterpolator`'s. A heat matrix colors its cells by their values, which `@transform`
1241
+ * names. Line charts and tables color no mark by value.
1242
+ */
1104
1243
  color?: string;
1244
+ /**
1245
+ * Color scheme of marks colored by numbers: a sequential or diverging `interpolate*` scheme, `interpolateReds` by
1246
+ * default. The scale's low end takes the scheme's first color and its high end its last: the lowest and highest
1247
+ * values, unless `colorMapRange` or `normalization` sets them. A categorical `scheme*` name is refused, since
1248
+ * categories take `categoricalColorMapInterpolator`. Read by the Autark adapter; the deck.gl adapter ignores it.
1249
+ */
1250
+ colorMapInterpolator?: ContinuousColorMapInterpolator;
1251
+ /**
1252
+ * Color scheme of marks colored by categories: a categorical `scheme*` scheme, `schemeObservable10` by default.
1253
+ * The categories take the scheme's colors in the order they first appear, or in `colorMapDomain`'s order, and those
1254
+ * past the scheme's last color take that one. A sequential or diverging `interpolate*` name is refused. Read by the
1255
+ * Autark adapter; the deck.gl adapter ignores it.
1256
+ */
1257
+ categoricalColorMapInterpolator?: CategoricalColorMapInterpolator;
1258
+ /**
1259
+ * How the ends of the color scale of numbers are found: `minMax`, the default, takes the lowest and highest
1260
+ * values; `percentile` takes the values at the `lowerPercentile` and `upperPercentile` percentiles, 2 and 98 when
1261
+ * it gives neither, else 0 and 100 for the one it leaves out. Categories ignore it. A map layer's `normalization`
1262
+ * reads the same way. Read by the Autark adapter; the deck.gl adapter ignores it.
1263
+ */
1264
+ normalization?: MapLayerSpec['normalization'];
1265
+ /**
1266
+ * Ends of the color scale of numbers, as `[low, high]` with low less than high. The plot is colored over this range
1267
+ * instead of its lowest and highest values, so plots and map layers that set the same range color the same value
1268
+ * alike. Values that are categories ignore it, as a layer with a categorical scheme does, and it cannot be set with
1269
+ * `colorMapDomain`. Read by the Autark adapter; the deck.gl adapter ignores it.
1270
+ * @uniqueItems true
1271
+ */
1272
+ colorMapRange?: [low: number, high: number];
1273
+ /**
1274
+ * Categories the plot is colored over, in order: the first takes the categorical scheme's first color, and so on.
1275
+ * The values are read as categories, numbers too, and a mark whose value is not among them is drawn in the mark
1276
+ * color. It cannot be set with `colorMapRange`. Read by the Autark adapter; the deck.gl adapter ignores it.
1277
+ */
1278
+ colorMapDomain?: string[];
1279
+ /**
1280
+ * Color of the marks that are neither colored by value nor selected, as `#rrggbb`: `#bfbfbf` by default. autk-plot
1281
+ * keeps one mark color for the page, so every plot it draws there takes it: a run refuses two plots that set
1282
+ * different ones, and a run whose plots set none gives back autk-plot's. Read by the Autark adapter; the deck.gl
1283
+ * adapter ignores it.
1284
+ */
1285
+ markColor?: HexColor;
1286
+ /**
1287
+ * Color of the selected marks, and of a table's selected rows, as `#rrggbb`: `#5dade2` by default. autk-plot keeps
1288
+ * one highlight color for the page, so every plot it draws there takes it: a run refuses two plots that set
1289
+ * different ones, and a run whose plots set none gives back autk-plot's. Read by the Autark adapter; the deck.gl
1290
+ * adapter ignores it.
1291
+ */
1292
+ highlightColor?: HexColor;
1293
+ /**
1294
+ * d3-format specifiers of the tick labels of the plot's axes, `[x, y]`: a scatter plot's x and y axes; a bar or line
1295
+ * chart's x axis, for labels that read as numbers, and its y axis; and every axis of numbers of parallel coordinates,
1296
+ * which read only the first. Heat matrices and tables ignore it. Without it, `['~s', '~s']`. Read by the Autark
1297
+ * adapter; the deck.gl adapter ignores it.
1298
+ */
1299
+ tickFormats?: [x: TickFormat, y: TickFormat];
1300
+ /**
1301
+ * Titles of the plot's axes, in the order of `axis`, in place of the column names: the x and y axes' titles of a
1302
+ * scatter plot, a bar chart, a line chart and a heat matrix, each axis's title of parallel coordinates, and a table's
1303
+ * column headers. An axis without a title keeps its column's name, and an axis that holds a transform's output,
1304
+ * `@transform`, is titled `value`. A run refuses more titles than `axis` has columns, and two titles alike, since a
1305
+ * table finds the column to sort by its header. Read by the Autark adapter; the deck.gl adapter ignores it.
1306
+ * @uniqueItems true
1307
+ */
1308
+ axisLabels?: string[];
1105
1309
  title?: string;
1106
1310
  /** Interactions the plot emits. */
1107
1311
  events?: PlotEvent[];
@@ -1122,6 +1326,14 @@ export declare interface PlotBase {
1122
1326
  };
1123
1327
  /** `dataRef` of the map layer this plot links its selection to. A shorthand for a link in `links`. */
1124
1328
  mapRef?: string;
1329
+ /**
1330
+ * Rows selected when the plot is drawn, by their positions among the rows it draws, as `plot:selection` events and
1331
+ * `setPlotSelection` name them. The plot draws them in its highlight color (a binned plot, the bins that hold them),
1332
+ * and the map layers it is linked to, by `mapRef` or `links`, highlight the same rows, as after `setPlotSelection`.
1333
+ * No `plot:selection` event reports it. A run refuses a position past the plot's last row. Read by the Autark
1334
+ * adapter; the deck.gl adapter ignores it.
1335
+ */
1336
+ selection?: RowPosition[];
1125
1337
  /**
1126
1338
  * Plot an OpenStreetMap layer table as one row per OSM element it was built from, each with the element's tags,
1127
1339
  * `osm_type` and `osm_id` (and `building_id` in a buildings table), rather than one row per table row. A table that
@@ -1142,6 +1354,8 @@ export declare type PlotRegistry = Map<string, AutkPlot>;
1142
1354
  /**
1143
1355
  * A plot view. The `mark` field selects which transforms apply.
1144
1356
  * @discriminator mark
1357
+ * @if { "required": ["colorMapRange"] }
1358
+ * @then { "not": { "required": ["colorMapDomain"] } }
1145
1359
  */
1146
1360
  export declare type PlotSpec = ScatterPlotSpec | BarPlotSpec | LinePlotSpec | ParallelCoordinatesPlotSpec | TablePlotSpec | HeatmatrixPlotSpec;
1147
1361
 
@@ -1314,6 +1528,13 @@ export declare function resolveUniformMatrices(matrices: Record<string, MatrixEn
1314
1528
  */
1315
1529
  export declare function resolveUniforms(uniforms: Record<string, UniformEntry> | undefined, layers: ComputeLayers, iterateIndex?: number): Record<string, number> | undefined;
1316
1530
 
1531
+ /**
1532
+ * A row of a table as a view draws it: its position among the rows the view draws, from 0.
1533
+ * @minimum 0
1534
+ * @multipleOf 1
1535
+ */
1536
+ declare type RowPosition = number;
1537
+
1317
1538
  /**
1318
1539
  * Runs a compute pass. Without iteration, or with `batched`, that is one dispatch. With `all` it is
1319
1540
  * one dispatch per feature of the iterated layer, and each output column holds the sum over them.
@@ -1406,6 +1627,33 @@ export declare type Targets = {
1406
1627
  plot?: string[] | string;
1407
1628
  };
1408
1629
 
1630
+ /**
1631
+ * The ground of a map in 3D, raised to the heights a raster band gives. Read by the Autark adapter; the deck.gl adapter
1632
+ * ignores it.
1633
+ */
1634
+ export declare type TerrainSpec = {
1635
+ /**
1636
+ * Name of the raster table whose band gives the ground's height in each of its cells, in the workspace's units, such
1637
+ * as a `geotiff` source of an elevation model in meters. It is a table of the map's workspace. A cell without a value
1638
+ * lies at height 0.
1639
+ * @minLength 1
1640
+ */
1641
+ dataRef: string;
1642
+ /**
1643
+ * The band of heights, by its id (`band_1`, ...) or its label, as a raster layer's `getFnv` names one. Defaults to the
1644
+ * first band. On a raster of several bands, a band that names none of them is refused.
1645
+ * @minLength 1
1646
+ */
1647
+ band?: string;
1648
+ };
1649
+
1650
+ /**
1651
+ * A d3-format specifier, such as `~s`, `,d`, `.2f` or `.0%`: d3-format's
1652
+ * `[[fill]align][sign][symbol][0][width][,][.precision][~][type]`.
1653
+ * @pattern ^(?:.?[<>=^])?[-+( ]?[$#]?0?\d*,?(?:\.\d+)?~?[a-zA-Z%]?$
1654
+ */
1655
+ declare type TickFormat = string;
1656
+
1409
1657
  declare type UniformEntry = number | FromFeatureDirective;
1410
1658
 
1411
1659
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@urban-toolkit/autk-grammar",
3
- "version": "5.1.0",
3
+ "version": "5.3.0",
4
4
  "description": "A declarative grammar for urban visual analytics, built on Autark",
5
5
  "license": "MIT",
6
6
  "author": "Gustavo Moreira",