@urban-toolkit/autk-grammar 4.3.0 → 4.4.1

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.js","sources":["../../../grammar/dist/the-urban-grammar.js","../src/adapters/data.ts","../src/adapters/map.ts","../src/adapters/plot.ts","../src/compute-params.ts","../src/adapters/compute.ts","../src/types.ts","../src/main.ts"],"sourcesContent":["function P(e) {\n const { spec: _, adapters: S } = e;\n let t;\n async function s() {\n let E;\n if (_.data)\n for (const i of _.data)\n E = await S.db.resolveSource(E, i);\n if (_.compute)\n for (const i of _.compute)\n E = await S.compute.resolveCompute(E, i);\n if (_.map)\n if (Array.isArray(_.map))\n for (let i = 0; i < _.map.length; i++) {\n let u = _.map[i];\n await S.map.resolveMap(E, u, i);\n }\n else\n await S.map.resolveMap(E, _.map);\n if (_.plot)\n if (Array.isArray(_.plot))\n for (const i of _.plot)\n await S.plot.resolvePlot(E, i);\n else\n await S.plot.resolvePlot(E, _.plot);\n t = E;\n }\n function R(E) {\n return console.log(\"Spec to update\", E), new Promise((i) => {\n i();\n });\n }\n function c() {\n console.log(\"Function not implemented yet\");\n }\n return { run: s, updatedSpec: R, destroy: c, get context() {\n return t;\n } };\n}\nvar n = /* @__PURE__ */ ((e) => (e.CAT_ACCENT = \"schemeAccent\", e.CAT_DARK2 = \"schemeDark2\", e.CAT_CATEGORY10 = \"schemeCategory10\", e.CAT_OBSERVABLE10 = \"schemeObservable10\", e.CAT_PAIRED = \"schemePaired\", e.CAT_PASTEL1 = \"schemePastel1\", e.CAT_PASTEL2 = \"schemePastel2\", e.CAT_SET1 = \"schemeSet1\", e.CAT_SET2 = \"schemeSet2\", e.CAT_SET3 = \"schemeSet3\", e.CAT_TABLEAU10 = \"schemeTableau10\", e.SEQ_REDS = \"interpolateReds\", e.SEQ_BLUES = \"interpolateBlues\", e.SEQ_GREENS = \"interpolateGreens\", e.SEQ_GREYS = \"interpolateGreys\", e.SEQ_ORANGES = \"interpolateOranges\", e.SEQ_PURPLES = \"interpolatePurples\", e.SEQ_TURBO = \"interpolateTurbo\", e.SEQ_VIRIDIS = \"interpolateViridis\", e.SEQ_INFERNO = \"interpolateInferno\", e.SEQ_MAGMA = \"interpolateMagma\", e.SEQ_PLASMA = \"interpolatePlasma\", e.SEQ_CIVIDIS = \"interpolateCividis\", e.SEQ_WARM = \"interpolateWarm\", e.SEQ_COOL = \"interpolateCool\", e.SEQ_CUBEHELIX_DEFAULT = \"interpolateCubehelixDefault\", e.SEQ_BU_GN = \"interpolateBuGn\", e.SEQ_BU_PU = \"interpolateBuPu\", e.SEQ_GN_BU = \"interpolateGnBu\", e.SEQ_OR_RD = \"interpolateOrRd\", e.SEQ_PU_BU_GN = \"interpolatePuBuGn\", e.SEQ_PU_BU = \"interpolatePuBu\", e.SEQ_PU_RD = \"interpolatePuRd\", e.SEQ_RD_PU = \"interpolateRdPu\", e.SEQ_YL_GN_BU = \"interpolateYlGnBu\", e.SEQ_YL_GN = \"interpolateYlGn\", e.SEQ_YL_OR_BR = \"interpolateYlOrBr\", e.SEQ_YL_OR_RD = \"interpolateYlOrRd\", e.DIV_BR_BG = \"interpolateBrBG\", e.DIV_PR_GN = \"interpolatePRGn\", e.DIV_PI_YG = \"interpolatePiYG\", e.DIV_PU_OR = \"interpolatePuOr\", e.DIV_RED_BLUE = \"interpolateRdBu\", e.DIV_RED_GREY = \"interpolateRdGy\", e.DIV_RED_YELLOW_BLUE = \"interpolateRdYlBu\", e.DIV_RED_YELLOW_GREEN = \"interpolateRdYlGn\", e.DIV_SPECTRAL = \"interpolateSpectral\", e))(n || {}), A = /* @__PURE__ */ ((e) => (e.MIN_MAX = \"minMax\", e.PERCENTILE = \"percentile\", e))(A || {});\nexport {\n n as ColorMapInterpolator,\n A as NormalizationMode,\n P as createEngine\n};\n//# sourceMappingURL=the-urban-grammar.js.map\n","import { CsvDataSourceSpec, CustomDataSourceSpec, DataAdapter, DataSourceSpec, HeatmapSourceSpec, JoinSourceSpec, JsonDataSourceSpec, OsmDataSourceSpec } from '@urban-toolkit/the-urban-grammar';\nimport { AutkDb, DEFAULT_WORKSPACE_COORDINATE_FORMAT } from '@urban-toolkit/autk-db';\nimport type { LoadGeojsonParams } from '@urban-toolkit/autk-db';\nimport type { FeatureCollection } from 'geojson';\nimport { Targets, GeoJsonCache } from '../types';\n\n/**\n * The query area autk-db reads: `{ bbox }` or `{ geocodeArea, areas }`. autk-db takes any area with a\n * `bbox` key as a box, so a box that also names areas, or that is not [west, south, east, north] in\n * degrees with west less than east and south less than north, is refused here.\n */\nfunction queryAreaOf(spec: OsmDataSourceSpec): OsmDataSourceSpec['queryArea'] {\n const { queryArea } = spec;\n if (queryArea.bbox === undefined) return { geocodeArea: queryArea.geocodeArea, areas: queryArea.areas };\n\n const refuse = (message: string) => new Error(`OSM source \"${spec.outputTableName}\": ${message}`);\n if (queryArea.geocodeArea !== undefined || queryArea.areas !== undefined)\n throw refuse('queryArea takes either bbox or geocodeArea with areas, not both.');\n const box: unknown = queryArea.bbox;\n if (!Array.isArray(box) || box.length !== 4 || !box.every((value) => typeof value === 'number' && Number.isFinite(value)))\n throw refuse('queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.');\n const [west, south, east, north] = queryArea.bbox;\n if (Math.abs(west) > 180 || Math.abs(east) > 180)\n throw refuse('queryArea.bbox west and east must be longitudes from -180 to 180.');\n if (Math.abs(south) > 90 || Math.abs(north) > 90)\n throw refuse('queryArea.bbox south and north must be latitudes from -90 to 90.');\n if (west >= east)\n throw refuse(`queryArea.bbox west (${west}) must be less than east (${east}); a box across the antimeridian is not supported.`);\n if (south >= north)\n throw refuse(`queryArea.bbox south (${south}) must be less than north (${north}).`);\n return { bbox: [west, south, east, north] };\n}\n\n/**\n * Maps an OSM source onto autk-db's parameters, which always expect\n * `autoLoadLayers` and no longer take `dropOsmTable`.\n */\nfunction toLoadOsmParams(spec: OsmDataSourceSpec) {\n const { autoLoadLayers, ...rest } = spec;\n return { ...rest, queryArea: queryAreaOf(spec), autoLoadLayers: { layers: autoLoadLayers?.layers ?? [] } };\n}\n\nexport function createDataAdapter(targets?: Targets, cache?: GeoJsonCache): DataAdapter {\n\n function print(db: AutkDb, targets?: Targets): void {\n if(!targets || !targets.db)\n return\n\n const div = document.getElementById(targets.db);\n if (div) {\n const tables = db.getTablesMetadata();\n\n div.innerHTML += `<ul>`;\n for (const table of tables) {\n div.innerHTML += `<li>${table.name}: (${table.source}, ${table.type}) </li>`;\n }\n div.innerHTML += `</ul>`;\n\n div.innerHTML += `<p>Number of tables: ${tables.length}</p>`;\n }\n }\n\n return {\n async resolveSource(context: AutkDb | undefined, spec: DataSourceSpec): Promise<AutkDb | undefined> {\n\n let db = context;\n\n if(!db){\n db = new AutkDb();\n await db.init();\n }\n\n let {type, ...rest_spec} = spec;\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 loader tolerates null geometry and missing properties, which the inline type allows.\n geojsonData = geojsonSpec.geojsonObject as FeatureCollection | undefined;\n }\n\n if (cache && geojsonData) cache.set(geojsonSpec.outputTableName, geojsonData);\n\n // Pass the fetched object directly so autk-db doesn't need to re-fetch\n const loadSpec = (geojsonData\n ? (() => { const s = { ...geojsonSpec, geojsonObject: geojsonData }; delete s.geojsonFileUrl; return s; })()\n : geojsonSpec) as LoadGeojsonParams;\n\n try {\n await db.loadGeojson(loadSpec);\n } catch (err) {\n const crsHint = loadSpec.coordinateFormat\n ? `coordinateFormat is set to \"${loadSpec.coordinateFormat}\"`\n : `no coordinateFormat was specified — defaulting to EPSG:4326 (WGS84 per RFC 7946)`;\n throw new Error(\n `Failed to load GeoJSON layer \"${loadSpec.outputTableName}\": ${err instanceof Error ? err.message : String(err)}. ` +\n `${crsHint}. Verify that coordinateFormat matches the actual CRS of the input data.`\n );\n }\n\n // Validate that the loaded geometry is within the workspace CRS extent.\n // A bounding box outside the valid world extent indicates a CRS mismatch.\n try {\n const bbox = await db.getBoundingBoxFromLayer(loadSpec.outputTableName);\n const WORLD_EXTENT = 25_000_000; // generous bound for DEFAULT_WORKSPACE_COORDINATE_FORMAT (EPSG:3395)\n if (\n !isFinite(bbox.minLon) || !isFinite(bbox.minLat) ||\n !isFinite(bbox.maxLon) || !isFinite(bbox.maxLat) ||\n Math.abs(bbox.minLon) > WORLD_EXTENT || Math.abs(bbox.maxLon) > WORLD_EXTENT ||\n Math.abs(bbox.minLat) > WORLD_EXTENT || Math.abs(bbox.maxLat) > WORLD_EXTENT\n ) {\n throw new Error(\n `Geometry bounding box after transform is invalid for layer \"${loadSpec.outputTableName}\" ` +\n `(bbox: [${bbox.minLon}, ${bbox.minLat}, ${bbox.maxLon}, ${bbox.maxLat}]). ` +\n `Verify that coordinateFormat matches the actual CRS of the input data. ` +\n `The workspace uses ${DEFAULT_WORKSPACE_COORDINATE_FORMAT}; input is expected in EPSG:4326 by default.`\n );\n }\n } catch (bboxErr) {\n if (bboxErr instanceof Error && bboxErr.message.includes('bounding box after transform')) throw bboxErr;\n // getBoundingBoxFromLayer failed (empty table, unsupported layer type, etc.) — skip validation\n }\n print(db, targets);\n return db;\n }\n case 'heatmap': {\n const hm = rest_spec as HeatmapSourceSpec;\n await db.buildHeatmap({\n tableJoinName: hm.tableJoinName,\n near: { distance: hm.near.distance },\n outputTableName: hm.outputTableName,\n grid: hm.grid,\n ...(hm.groupBy && { groupBy: hm.groupBy as any }),\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.tableRootName,\n tableJoinName: jn.tableJoinName,\n ...(jn.near && { near: jn.near }),\n ...(jn.groupBy && { groupBy: jn.groupBy }),\n });\n if (cache) {\n const updated = await db.getLayer(jn.tableRootName);\n cache.set(jn.tableRootName, updated);\n }\n print(db, targets);\n return db;\n }\n default:\n return\n }\n }\n }\n}\n","import { MapAdapter, MapLayerSpec, MapSpec, NormalizationMode } from '@urban-toolkit/the-urban-grammar';\nimport { Targets, MapRegistry, MapLayerIds, ComputeCache } from '../types';\nimport { AutkMap } from '@urban-toolkit/autk-map';\nimport type { LayerRenderInfo } from '@urban-toolkit/autk-map';\nimport { ColorMap, ColorMapDomainStrategy, ColorMapInterpolator } from '@urban-toolkit/autk-core';\nimport type { ColorHEX, ColorMapConfig, ColorMapDomainSpec, ColorRGB, LayerType, TransferFunction } from '@urban-toolkit/autk-core';\nimport { AutkDb } from '@urban-toolkit/autk-db';\n\n/** The id a layer has in its map: its `title`, else its `dataRef`. */\nexport function layerIdOf(layerRef: MapLayerSpec): string {\n return typeof layerRef.title === 'string' && layerRef.title !== '' ? layerRef.title : layerRef.dataRef;\n}\n\n/** Refuses a map whose layers would share an id. */\nfunction checkLayerIds(spec: MapSpec, index: number): void {\n const ids = new Set<string>();\n for (const layerRef of spec.layerRefs) {\n const id = layerIdOf(layerRef);\n if (ids.has(id))\n throw new Error(`Map ${index} draws two layers with the id \"${id}\". A layer's id is its title, else its dataRef: give each layer of a map its own title.`);\n ids.add(id);\n }\n}\n\nconst HEX_COLOR = /^#[0-9a-fA-F]{6}$/;\n\nfunction hexColor(value: string, key: string, layerId: string): ColorRGB {\n if (!HEX_COLOR.test(value))\n throw new Error(`Layer \"${layerId}\": ${key} must be a color written #rrggbb, not \"${value}\".`);\n return ColorMap.hexToRgb(value as ColorHEX);\n}\n\n/** What `color`, `stroke` and `width` set on the layer's autk-map render info. */\nfunction styleRenderInfo(layerRef: MapLayerSpec, layerId: string): Partial<LayerRenderInfo> {\n const renderInfo: Partial<LayerRenderInfo> = {};\n if (layerRef.color != null)\n renderInfo.color = hexColor(layerRef.color, 'color', layerId);\n if (layerRef.stroke === false)\n renderInfo.showBorders = false;\n else if (layerRef.stroke != null)\n renderInfo.strokeColor = hexColor(layerRef.stroke, 'stroke', layerId);\n if (layerRef.width != null)\n renderInfo.polylinesWidth = layerRef.width;\n return renderInfo;\n}\n\n/**\n * Whether the layer is colored by value. An explicit `isColorMap` decides. A raster layer is colored by value\n * either way, and this only shows or hides its legend. Otherwise a layer with a `color` is drawn in it, and a\n * layer with a scheme or a `getFnv` value is colored by value.\n */\nfunction colorsByValue(layerRef: MapLayerSpec, type: LayerType): boolean {\n if (layerRef.isColorMap != null) return layerRef.isColorMap;\n if (type === 'raster')\n return layerRef.colorMapInterpolator != null || layerRef.colorMapCenter != null || layerRef.colorMapReverse === true;\n if (layerRef.color != null) return false;\n return layerRef.colorMapInterpolator != null || layerRef.getFnv != null;\n}\n\n/** A raster band's values, as autk-map reads them. */\nfunction bandValues(collection: { features?: { properties?: unknown }[] }, band: string): Float32Array | null {\n const values = (collection.features?.[0]?.properties as Record<string, unknown> | undefined)?.[band];\n if (values instanceof Float32Array) return values;\n if ((ArrayBuffer.isView(values) && !(values instanceof DataView)) || Array.isArray(values))\n return Float32Array.from(values as ArrayLike<number>, (v) => (Number.isFinite(Number(v)) ? Number(v) : NaN));\n return null;\n}\n\n/**\n * The domain of a raster's centered or reversed color scale, or `undefined` when the layer asks for neither, the\n * scheme is categorical, or the band has no value. Centered on `center`, it runs from the center less the farthest\n * value's distance to it, to the center plus that distance; when every value is the center, it is not centered.\n * Otherwise it is the domain autk-map resolves from `config`. `reverse` turns it around.\n */\nexport function rasterScaleDomain(values: Float32Array, config: ColorMapConfig, center?: number, reverse?: boolean): number[] | undefined {\n if (ColorMap.isCategorical(config.interpolator)) return undefined;\n let reach = 0;\n let finite = 0;\n for (let i = 0; i < values.length; i++) {\n const value = values[i];\n if (!Number.isFinite(value)) continue;\n finite++;\n if (center != null) reach = Math.max(reach, Math.abs(value - center));\n }\n const centered = center != null && reach > 0;\n if (finite === 0 || (!centered && reverse !== true)) return undefined;\n const domain = centered && center != null\n ? [center - reach, center, center + reach]\n : ColorMap.resolveDomainFromData(values, config) as number[];\n return reverse === true ? [...domain].reverse() : domain;\n}\n\nfunction buildDomainSpec(\n normalization: MapSpec['layerRefs'][number]['normalization'],\n colorMapDomain?: string[],\n): ColorMapDomainSpec {\n if (colorMapDomain && colorMapDomain.length > 0)\n return { type: ColorMapDomainStrategy.USER, params: colorMapDomain };\n if (normalization?.mode === NormalizationMode.PERCENTILE) {\n const hasExplicitBounds =\n normalization.lowerPercentile !== undefined || normalization.upperPercentile !== undefined;\n if (hasExplicitBounds)\n return {\n type: ColorMapDomainStrategy.PERCENTILE,\n params: [normalization.lowerPercentile ?? 0, normalization.upperPercentile ?? 100],\n };\n return { type: ColorMapDomainStrategy.PERCENTILE };\n }\n return { type: ColorMapDomainStrategy.MIN_MAX };\n}\n\nfunction valueAtPath(obj: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>((acc, key) => {\n if (acc == null || typeof acc !== 'object') return undefined;\n return (acc as Record<string, unknown>)[key];\n }, obj);\n}\n\nfunction setValueAtPath(obj: Record<string, unknown>, path: string, value: unknown): Record<string, unknown> {\n const keys = path.split('.');\n const result = { ...obj };\n let current = result as Record<string, unknown>;\n for (let i = 0; i < keys.length - 1; i++) {\n current[keys[i]] = { ...(current[keys[i]] as Record<string, unknown> ?? {}) };\n current = current[keys[i]] as Record<string, unknown>;\n }\n current[keys[keys.length - 1]] = value;\n return result;\n}\n\n/**\n * Resolves a grammar value path such as `count.noise` to the raster band that holds it.\n * autk-db stores heatmap values in bands (`band_1`, ...) labelled `<aggregateFn>_<table>`.\n */\nfunction rasterBand(collection: { features?: { properties?: unknown }[] }, getFnv?: string): string {\n const props = collection.features?.[0]?.properties as { bands?: { id: string; label?: string }[] } | undefined;\n const bands = props?.bands ?? [];\n const band = bands.find((b) => b.id === getFnv || b.label === getFnv?.replace(/\\./g, '_'));\n return band?.id ?? bands[0]?.id ?? getFnv ?? '';\n}\n\nexport function createMapAdapter(targets?: Targets, registry?: MapRegistry, computeCache?: ComputeCache, maps?: AutkMap[], layerIds?: MapLayerIds): MapAdapter {\n\n async function loadLayers(map: AutkMap, context: AutkDb, spec: MapSpec): Promise<void> {\n let tableToTypeMap: {[tableName: string]: string} = {};\n for(const table of context.getTablesMetadata()) {\n if(table.type !== undefined) tableToTypeMap[table.name] = table.type;\n }\n\n for(const layerRef of spec.layerRefs){\n const name = layerRef.dataRef;\n const layerId = layerIdOf(layerRef);\n const type = tableToTypeMap[name] as LayerType;\n const getFnv = layerRef.getFnv;\n\n const rawData = computeCache?.get(name) ?? await context.getLayer(name);\n // Raster tables (e.g. heatmaps) are a single feature with no geometry, so keep them as-is.\n const data = type === 'raster' ? rawData : {\n ...rawData,\n features: (rawData.features ?? []).filter((f: any) => f.geometry != null),\n };\n const band = type === 'raster' ? rasterBand(data, getFnv) : '';\n\n if(type === 'raster') {\n map.loadCollection(layerId, { collection: data, type: 'raster', property: band });\n } else {\n map.loadCollection(layerId, { collection: data, type });\n }\n\n if(layerRef.opacity != null)\n map.updateRenderInfo(layerId, { opacity: layerRef.opacity });\n\n const style = styleRenderInfo(layerRef, layerId);\n if(Object.keys(style).length > 0)\n map.updateRenderInfo(layerId, style);\n\n // Thematic (getFnv) vector layers are colored by value out of the box: autk-map\n // attaches a default colour ramp to every layer, so this works even when the\n // spec omits colorMapInterpolator (see colorsByValue).\n if(colorsByValue(layerRef, type))\n map.updateRenderInfo(layerId, { isColorMap: true });\n\n if(layerRef.isPick)\n map.updateRenderInfo(layerId, { isPick: true });\n\n if(layerRef.isSkip)\n map.updateRenderInfo(layerId, { isSkip: true });\n\n // When catchAllCategory is set, remap features whose property value is not\n // in colorMapDomain to the catch-all label, and extend the domain to include it.\n const { catchAllCategory, colorMapDomain } = layerRef;\n let thematicData = data;\n let effectiveDomain = colorMapDomain;\n\n if(getFnv && catchAllCategory && colorMapDomain?.length) {\n const allowed = new Set(colorMapDomain);\n thematicData = {\n ...data,\n features: data.features.map((f: any) => {\n const props = f.properties as Record<string, unknown>;\n const val = valueAtPath(props, getFnv);\n if(val === undefined || val === null || !allowed.has(String(val))) {\n return { ...f, properties: setValueAtPath(props, getFnv, catchAllCategory) };\n }\n return f;\n }),\n };\n effectiveDomain = allowed.has(catchAllCategory)\n ? colorMapDomain\n : [...colorMapDomain, catchAllCategory];\n }\n\n // A raster's transfer function is only stored by setTransferFunction; the\n // updateColorMap below colors the cells again with it.\n const rasterTransfer = type === 'raster' && layerRef.transferFunction != null;\n if(rasterTransfer) {\n const layer = map.layerManager.searchByLayerId(layerId) as unknown as\n { setTransferFunction?: (transferFunction: TransferFunction) => void } | null;\n layer?.setTransferFunction?.(layerRef.transferFunction as TransferFunction);\n }\n\n // The scheme and its domain go through updateColorMap, which colors a raster's\n // cells again and gives the legend its labels.\n const rasterScale = type === 'raster' && (layerRef.colorMapCenter != null || layerRef.colorMapReverse === true);\n if(layerRef.colorMapInterpolator || rasterScale) {\n const colormapConfig: ColorMapConfig = {\n // urban-grammar ColorMapInterpolator values are string-compatible\n // with autk-core ColorMapInterpolator at runtime\n interpolator: (layerRef.colorMapInterpolator as unknown as ColorMapConfig['interpolator'] | undefined)\n ?? map.layerManager.searchByLayerId(layerId)?.layerRenderInfo.colormap.config.interpolator\n ?? ColorMapInterpolator.SEQ_REDS,\n domainSpec: buildDomainSpec(layerRef.normalization, effectiveDomain),\n };\n const values = rasterScale ? bandValues(data, band) : null;\n const domain = values\n ? rasterScaleDomain(values, colormapConfig, layerRef.colorMapCenter, layerRef.colorMapReverse)\n : undefined;\n if(domain)\n colormapConfig.domainSpec = { type: ColorMapDomainStrategy.USER, params: domain };\n map.updateColorMap(layerId, { colorMap: colormapConfig });\n } else if(rasterTransfer) {\n map.updateColorMap(layerId, { colorMap: {} });\n }\n\n if(getFnv && type !== 'raster') {\n const property = getFnv.startsWith('properties.') ? getFnv : `properties.${getFnv}`;\n map.updateThematic(layerId, { collection: thematicData, property });\n }\n }\n }\n\n return {\n async resolveMap(context: AutkDb | undefined, spec: MapSpec, index: number = 0): Promise<void> {\n if(targets && targets.map && context){\n\n checkLayerIds(spec, index);\n\n let canvas;\n\n if(Array.isArray(targets.map)){\n canvas = document.getElementById(targets.map[index]);\n }else{\n canvas = document.getElementById(targets.map);\n }\n\n if(!canvas)\n throw new Error(\"Could not find rendering target for map: \"+targets.map);\n\n if(!(canvas instanceof HTMLCanvasElement))\n throw new Error(\"Target for map is not a canvas: \"+targets.map);\n\n const map = new AutkMap(canvas);\n\n if(spec.style)\n map.style.setPredefinedStyle(spec.style)\n\n await map.init();\n await loadLayers(map, context, spec);\n\n for(const layerRef of spec.layerRefs) {\n registry?.set(layerRef.dataRef, map);\n layerIds?.set(layerRef.dataRef, layerIdOf(layerRef));\n }\n\n if(maps)\n maps[index] = map;\n\n map.draw();\n }\n }\n }\n}\n","import { PlotAdapter, PlotSpec, PlotMark } from '@urban-toolkit/the-urban-grammar';\nimport { Targets, MapRegistry, MapLayerIds, PlotRegistry, PlotMapLinks, GeoJsonCache } from '../types';\nimport { AutkDb } from '@urban-toolkit/autk-db';\nimport { AutkPlot, PlotEvent as AutkPlotEvent } from '@urban-toolkit/autk-plot';\nimport type { PlotEventData, PlotType, PlotTransformConfig } from '@urban-toolkit/autk-plot';\nimport { AutkMap, MapEvent } from '@urban-toolkit/autk-map';\nimport type { MapEventData } from '@urban-toolkit/autk-map';\nimport { FeatureCollection } from 'geojson';\n\nfunction grammarMarkToPlotType(mark: PlotMark): PlotType {\n const mapping: Record<PlotMark, PlotType> = {\n 'scatter': 'scatterplot',\n 'bar': 'barchart',\n 'line': 'linechart',\n 'linechart': 'linechart',\n 'parallel-coordinates': 'parallel-coordinates',\n 'table': 'table',\n 'heatmatrix': 'heatmatrix',\n };\n return mapping[mark];\n}\n\nexport function createPlotAdapter(targets?: Targets, registry?: MapRegistry, plotRegistry?: PlotRegistry, plotMapLinks?: PlotMapLinks, cache?: GeoJsonCache, layerIds?: MapLayerIds): PlotAdapter {\n\n return {\n async resolvePlot(context: unknown, spec: PlotSpec): Promise<void> {\n if(!targets || !targets.plot) return;\n\n const div = document.getElementById(targets.plot);\n if(!div) throw new Error(`Could not find plot target: ${targets.plot}`);\n\n const db = context as AutkDb | undefined;\n if(!db) throw new Error('No data context available for plot.');\n\n const geojson: FeatureCollection = cache?.get(spec.dataRef) ?? await db.getLayer(spec.dataRef);\n\n const events = (spec.events ?? []) as unknown as AutkPlotEvent[];\n\n const plot = new AutkPlot(div, {\n type: grammarMarkToPlotType(spec.mark),\n collection: geojson,\n attributes: { axis: spec.axis, ...(spec.color && { color: spec.color }) },\n labels: { axis: spec.axis, title: spec.title },\n events,\n ...(spec.width && { width: spec.width }),\n ...(spec.height && { height: spec.height }),\n ...(spec.margins && { margins: spec.margins }),\n ...(spec.transform && { transform: spec.transform as PlotTransformConfig }),\n });\n\n plotRegistry?.set(spec.dataRef, plot);\n if (spec.mapRef) plotMapLinks?.set(spec.dataRef, spec.mapRef);\n\n // Wire map ↔ plot events if a mapRef is specified. mapRef names the layer's\n // table; the layer's id in its map is its title, else that name.\n if(spec.mapRef && registry) {\n const map: AutkMap | undefined = registry.get(spec.mapRef);\n const layerId = layerIds?.get(spec.mapRef) ?? spec.mapRef;\n\n if(map) {\n map.updateRenderInfo(layerId, { isPick: true });\n\n map.events.on(MapEvent.PICKING, ({ selection }: MapEventData) => {\n plot.setSelection(selection);\n });\n\n for(const event of events) {\n plot.events.on(event, ({ selection }: PlotEventData) => {\n map.setHighlightedIds(layerId, selection);\n });\n }\n }\n }\n }\n }\n}\n","import type { ComputeSpec, FromFeatureDirective } from '@urban-toolkit/the-urban-grammar';\nimport type { GpgpuPipelineParams } from '@urban-toolkit/autk-compute';\nimport type { Feature, FeatureCollection } from 'geojson';\n\n/** Tables a compute pass can read, keyed by table name. */\nexport type ComputeLayers = Record<string, FeatureCollection | undefined> | Map<string, FeatureCollection>;\n\n/** Runs one GPU dispatch, for example `params => new AutkComputeEngine().gpgpuPipeline(params)`. */\nexport type ComputeRunner = (params: GpgpuPipelineParams) => Promise<FeatureCollection>;\n\n/**\n * The storage buffer binding every WebGPU device supports: the default\n * `maxStorageBufferBindingSize`, 128 MiB. autk-compute 4 reads each array a `batched` directive\n * packs from a read-only storage buffer of its own, so every packed array must fit one binding.\n * autk-compute 3 bound them as uniform buffers, which hold 64 KiB (2048 bounding boxes).\n */\nexport const STORAGE_BUFFER_BINDING_SIZE = 134_217_728;\n\n/** Bytes a feature adds to a packed array: one f32 for a scalar entry, a bounding box of eight for a matrix entry. */\nconst SCALAR_BYTES = 4;\nconst BOX_BYTES = 8 * 4;\n\ntype UniformEntry = number | FromFeatureDirective;\ntype MatrixEntry = { data: number[][]; cols: number } | FromFeatureDirective;\n\n/** Joins a `wglsFunction` written as an array of lines. Any other separator would let a `//` comment swallow the lines after it. */\nexport function joinWgsl(body: string | string[]): string {\n return Array.isArray(body) ? body.join('\\n') : body;\n}\n\n/** True when a uniform entry reads its value from a feature. */\nexport function isFromFeature(value: unknown): value is FromFeatureDirective {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n && typeof (value as FromFeatureDirective).fromFeature === 'object'\n && (value as FromFeatureDirective).fromFeature !== null;\n}\n\nfunction lookup(layers: ComputeLayers, name: string): FeatureCollection | undefined {\n return layers instanceof Map ? layers.get(name) : layers[name];\n}\n\nfunction valueAtPath(item: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>((acc, key) => {\n if (acc == null || typeof acc !== 'object') return undefined;\n return (acc as Record<string, unknown>)[key];\n }, item);\n}\n\nfunction directives(block: ComputeSpec): FromFeatureDirective[] {\n const out: FromFeatureDirective[] = [];\n for (const cfg of [block.uniforms, block.uniformMatrices]) {\n for (const value of Object.values(cfg ?? {})) {\n if (isFromFeature(value)) out.push(value);\n }\n }\n return out;\n}\n\n/** Every table a compute pass reads: its `dataRef` plus each `fromFeature` layer. */\nexport function computeLayerNames(block: ComputeSpec): string[] {\n return [...new Set([block.dataRef, ...directives(block).map(d => d.fromFeature.layer)])];\n}\n\n/**\n * The iteration a compute pass asks for, or `null`. Every iterating directive must read the same\n * layer; the first one found decides the mode and the layer.\n */\nexport function findIterateSource(block: ComputeSpec): { mode: 'all' | 'batched'; layer: string } | null {\n for (const d of directives(block)) {\n const { iterate, layer } = d.fromFeature;\n if (iterate === 'all' || iterate === 'batched') return { mode: iterate, layer };\n }\n return null;\n}\n\nfunction resolveDirective(d: FromFeatureDirective, layers: ComputeLayers, iterateIndex?: number): unknown {\n const ff = d.fromFeature;\n const index = iterateIndex !== undefined && ff.iterate === 'all' ? iterateIndex : (ff.index ?? 0);\n const feature = lookup(layers, ff.layer)?.features?.[index];\n return feature ? valueAtPath(feature, ff.path) : undefined;\n}\n\n/**\n * Resolves the `fromFeature` entries of `uniforms` to numbers. An entry that does not resolve to a\n * finite number takes its `default`, or is dropped when it has none.\n */\nexport function resolveUniforms(\n uniforms: Record<string, UniformEntry> | undefined,\n layers: ComputeLayers,\n iterateIndex?: number,\n): Record<string, number> | undefined {\n if (!uniforms) return undefined;\n const out: Record<string, number> = {};\n for (const [key, value] of Object.entries(uniforms)) {\n if (!isFromFeature(value)) {\n out[key] = value;\n continue;\n }\n const num = Number(resolveDirective(value, layers, iterateIndex) ?? NaN);\n if (Number.isFinite(num)) out[key] = num;\n else if (typeof value.default === 'number') out[key] = value.default;\n }\n return out;\n}\n\n/**\n * Resolves the `fromFeature` entries of `uniformMatrices` to `{ data, cols }`. An entry that does\n * not resolve to an array takes its `default`, or is dropped when it has none.\n */\nexport function resolveUniformMatrices(\n matrices: Record<string, MatrixEntry> | undefined,\n layers: ComputeLayers,\n iterateIndex?: number,\n): Record<string, { data: number[][]; cols: number }> | undefined {\n if (!matrices) return undefined;\n const out: Record<string, { data: number[][]; cols: number }> = {};\n for (const [key, value] of Object.entries(matrices)) {\n if (!isFromFeature(value)) {\n out[key] = value;\n continue;\n }\n const resolved = resolveDirective(value, layers, iterateIndex);\n const data = Array.isArray(resolved) ? (resolved as number[][])\n : Array.isArray(value.default) ? value.default : undefined;\n if (!data) continue;\n const cols = value.cols ?? (Array.isArray(data[0]) ? data[0].length : 0);\n if (cols > 0) out[key] = { data, cols };\n else console.warn(`[autk-grammar] uniform matrix \"${key}\" has no column count; entry dropped`);\n }\n return out;\n}\n\nfunction isFiniteValue(v: unknown): boolean {\n return v !== undefined && v !== null && !(typeof v === 'number' && !Number.isFinite(v));\n}\n\nfunction isBatched(value: unknown): boolean {\n return isFromFeature(value) && value.fromFeature.iterate === 'batched';\n}\n\n/** Bytes one feature adds to the largest array a batched pass packs, or 0 when it packs none. */\nfunction batchedBytesPerFeature(\n uniforms: Record<string, UniformEntry> | undefined,\n matrices: Record<string, MatrixEntry> | undefined,\n): number {\n if (Object.values(matrices ?? {}).some(isBatched)) return BOX_BYTES;\n if (Object.values(uniforms ?? {}).some(isBatched)) return SCALAR_BYTES;\n return 0;\n}\n\n/**\n * Most features a batched pass packs: as many as its largest array holds in one storage buffer\n * binding of `bindingSize` bytes. With {@link STORAGE_BUFFER_BINDING_SIZE} that is 4,194,304\n * features for a pass with a matrix entry, and 33,554,432 for one with scalar entries only.\n */\nexport function maxBatchedFeatures(\n uniforms: Record<string, UniformEntry> | undefined,\n matrices: Record<string, MatrixEntry> | undefined,\n bindingSize: number = STORAGE_BUFFER_BINDING_SIZE,\n): number {\n const bytes = batchedBytesPerFeature(uniforms, matrices);\n return bytes > 0 ? Math.floor(bindingSize / bytes) : Number.POSITIVE_INFINITY;\n}\n\n/**\n * Packs every feature of a `batched` layer into uniform arrays:\n * - a scalar entry becomes an array of one value per feature, under the entry's name;\n * - a matrix entry becomes each feature's axis-aligned bounding box as four corners\n * `[xmin,ymin, xmax,ymin, xmax,ymax, xmin,ymax]`, eight values per feature;\n * - `num_features` holds the feature count.\n * Features missing a `required` path are dropped first, and at most {@link maxBatchedFeatures}\n * are packed: as many as the largest array holds in one storage buffer binding of `bindingSize`\n * bytes. Plain numbers pass through; other entries that do not iterate are left to\n * {@link resolveComputeParams}.\n */\nexport function buildBatchedUniforms(\n uniforms: Record<string, UniformEntry> | undefined,\n matrices: Record<string, MatrixEntry> | undefined,\n sources: Feature[],\n bindingSize: number = STORAGE_BUFFER_BINDING_SIZE,\n): { uniforms: Record<string, number>; uniformArrays: Record<string, number[]> } {\n const outUniforms: Record<string, number> = {};\n const outArrays: Record<string, number[]> = {};\n\n const required: string[] = [];\n for (const cfg of [uniforms, matrices]) {\n for (const value of Object.values(cfg ?? {})) {\n if (isFromFeature(value) && value.fromFeature.iterate === 'batched' && value.fromFeature.required) {\n required.push(value.fromFeature.path);\n }\n }\n }\n if (required.length > 0) {\n const before = sources.length;\n sources = sources.filter(f => required.every(p => isFiniteValue(valueAtPath(f, p))));\n if (sources.length < before) {\n console.info(`[autk-grammar] batched compute dropped ${before - sources.length} feature(s) missing ${required.join(', ')}`);\n }\n }\n const limit = maxBatchedFeatures(uniforms, matrices, bindingSize);\n if (sources.length > limit) {\n console.warn(\n `[autk-grammar] batched compute capped at ${limit} features (got ${sources.length}): `\n + `its largest packed array takes ${batchedBytesPerFeature(uniforms, matrices)} B per feature, `\n + `and a storage buffer binding holds ${bindingSize} B`,\n );\n sources = sources.slice(0, limit);\n }\n\n for (const [key, value] of Object.entries(uniforms ?? {})) {\n if (isFromFeature(value) && value.fromFeature.iterate === 'batched') {\n const fallback = typeof value.default === 'number' ? value.default : undefined;\n outArrays[key] = sources.map(f => {\n const num = Number(valueAtPath(f, value.fromFeature.path) ?? fallback);\n return Number.isFinite(num) ? num : 0;\n });\n } else if (typeof value === 'number') {\n outUniforms[key] = value;\n }\n }\n\n for (const [key, value] of Object.entries(matrices ?? {})) {\n if (!isFromFeature(value) || value.fromFeature.iterate !== 'batched') continue;\n const data: number[] = [];\n for (const f of sources) {\n const ring = valueAtPath(f, value.fromFeature.path);\n let xmin = Infinity, ymin = Infinity, xmax = -Infinity, ymax = -Infinity;\n if (Array.isArray(ring)) {\n for (const coord of ring) {\n if (!Array.isArray(coord) || coord.length < 2) continue;\n const x = Number(coord[0]);\n const y = Number(coord[1]);\n if (!Number.isFinite(x) || !Number.isFinite(y)) continue;\n xmin = Math.min(xmin, x); ymin = Math.min(ymin, y);\n xmax = Math.max(xmax, x); ymax = Math.max(ymax, y);\n }\n }\n // A degenerate feature gets a zero-area box, so the shader's loop runs but adds nothing.\n if (!Number.isFinite(xmin)) { xmin = 0; ymin = 0; xmax = 0; ymax = 0; }\n data.push(xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax);\n }\n outArrays[key] = data;\n }\n\n outUniforms.num_features = sources.length;\n return { uniforms: outUniforms, uniformArrays: outArrays };\n}\n\n/**\n * Turns a compute pass into the parameters of one GPU dispatch. Pure: it reads `layers` and runs\n * nothing. With `iterate: 'all'`, pass the feature index as `iterateIndex` for each dispatch (see\n * {@link runCompute}). Throws when the pass's `dataRef` is not in `layers`.\n */\nexport function resolveComputeParams(block: ComputeSpec, layers: ComputeLayers, iterateIndex?: number): GpgpuPipelineParams {\n const collection = lookup(layers, block.dataRef);\n if (!collection) throw new Error(`compute: table \"${block.dataRef}\" is not loaded`);\n\n const params: GpgpuPipelineParams = {\n collection,\n variableMapping: block.attributes,\n wgslBody: joinWgsl(block.wglsFunction),\n };\n if (block.attributeArrays) params.attributeArrays = block.attributeArrays;\n if (block.attributeMatrices) params.attributeMatrices = block.attributeMatrices;\n if (block.uniformArrays) params.uniformArrays = block.uniformArrays;\n if (block.outputColumnName) params.resultField = block.outputColumnName;\n if (block.outputColumns) params.outputColumns = block.outputColumns;\n\n const iterate = findIterateSource(block);\n if (iterate?.mode === 'batched') {\n const sources = lookup(layers, iterate.layer)?.features ?? [];\n const packed = buildBatchedUniforms(block.uniforms, block.uniformMatrices, sources);\n // Entries that do not iterate resolve as they would without iteration.\n const single = resolveUniforms(notBatched(block.uniforms), layers) ?? {};\n const matrices = resolveUniformMatrices(notBatched(block.uniformMatrices), layers);\n params.uniforms = { ...single, ...packed.uniforms };\n params.uniformArrays = { ...(params.uniformArrays ?? {}), ...packed.uniformArrays };\n if (matrices && Object.keys(matrices).length > 0) params.uniformMatrices = matrices;\n return params;\n }\n\n const index = iterate?.mode === 'all' ? iterateIndex : undefined;\n const uniforms = resolveUniforms(block.uniforms, layers, index);\n const matrices = resolveUniformMatrices(block.uniformMatrices, layers, index);\n if (uniforms) params.uniforms = uniforms;\n if (matrices) params.uniformMatrices = matrices;\n return params;\n}\n\nfunction notBatched<T>(entries: Record<string, T> | undefined): Record<string, T> | undefined {\n if (!entries) return undefined;\n return Object.fromEntries(Object.entries(entries).filter(([, v]) => !(isFromFeature(v) && v.fromFeature.iterate === 'batched')));\n}\n\nfunction outputColumns(block: ComputeSpec): string[] {\n return block.outputColumns ?? (block.outputColumnName ? [block.outputColumnName] : []);\n}\n\n/**\n * Runs a compute pass. Without iteration, or with `batched`, that is one dispatch. With `all` it is\n * one dispatch per feature of the iterated layer, and each output column holds the sum over them.\n */\nexport async function runCompute(block: ComputeSpec, layers: ComputeLayers, run: ComputeRunner): Promise<FeatureCollection> {\n const iterate = findIterateSource(block);\n if (iterate?.mode !== 'all') return run(resolveComputeParams(block, layers));\n\n const target = lookup(layers, block.dataRef);\n if (!target) throw new Error(`compute: table \"${block.dataRef}\" is not loaded`);\n const columns = outputColumns(block);\n const summed: FeatureCollection = structuredClone(target);\n for (const f of summed.features) {\n const props = (f.properties ??= {}) as Record<string, unknown>;\n const compute = (props.compute ??= {}) as Record<string, number>;\n for (const col of columns) compute[col] = 0;\n }\n\n const count = lookup(layers, iterate.layer)?.features?.length ?? 0;\n for (let i = 0; i < count; i++) {\n const step = await run({ ...resolveComputeParams(block, layers, i), collection: summed });\n summed.features.forEach((f, j) => {\n const dst = (f.properties as Record<string, unknown> | null)?.compute as Record<string, number> | undefined;\n const src = (step.features[j]?.properties as Record<string, unknown> | null)?.compute as Record<string, unknown> | undefined;\n if (!dst || !src) return;\n for (const col of columns) {\n const inc = Number(src[col]);\n if (Number.isFinite(inc)) dst[col] += inc;\n }\n });\n }\n return summed;\n}\n","import { ComputeAdapter, ComputeSpec } from '@urban-toolkit/the-urban-grammar';\nimport { AutkDb } from '@urban-toolkit/autk-db';\nimport { AutkComputeEngine } from '@urban-toolkit/autk-compute';\nimport { FeatureCollection } from 'geojson';\nimport { ComputeCache } from '../types';\nimport { computeLayerNames, runCompute } from '../compute-params';\n\nexport function createComputeAdapter(cache?: ComputeCache): ComputeAdapter {\n\n return {\n async resolveCompute(context: AutkDb | undefined, spec: ComputeSpec): Promise<AutkDb | undefined> {\n if(context){\n // A table an earlier compute pass wrote is read from the cache, so passes chain.\n // Only the pass's own table must load; a `fromFeature` table that cannot\n // falls back to the directive's `default`.\n const layers: Record<string, FeatureCollection | undefined> = {};\n for (const name of computeLayerNames(spec)) {\n const cached = cache?.get(name);\n if (cached) layers[name] = cached;\n else if (name === spec.dataRef) layers[name] = await context.getLayer(name);\n else {\n try { layers[name] = await context.getLayer(name); }\n catch { layers[name] = undefined; }\n }\n }\n\n const engine = new AutkComputeEngine();\n const result = await runCompute(spec, layers, params => engine.gpgpuPipeline(params));\n\n if (cache) cache.set(spec.dataRef, result);\n\n return context;\n }\n }\n }\n}\n","import type { UrbanSpec } from '@urban-toolkit/the-urban-grammar';\nimport type { AutkMap } from '@urban-toolkit/autk-map';\nimport type { AutkPlot } from '@urban-toolkit/autk-plot';\nimport type { FeatureCollection } from 'geojson';\n\nexport type Targets = {\n compute?: string,\n db?: string,\n map?: string[] | string,\n plot?: string\n}\n\nexport type MapRegistry = Map<string, AutkMap>;\nexport type MapLayerIds = Map<string, string>; // dataRef → id of the layer that draws it in the map the MapRegistry holds for it\nexport type PlotRegistry = Map<string, AutkPlot>;\nexport type PlotMapLinks = Map<string, string>; // plotId (dataRef) → mapRef (dataRef of a map layer)\n\n/** A layer a map of the last run draws, as `AutkGrammar.mapLayer` finds it by its table's name. */\nexport interface GrammarMapLayer {\n /** The map that draws the layer. */\n map: AutkMap;\n /** The layer's id in that map: its `title`, else its `dataRef`. */\n layerId: string;\n}\nexport type GeoJsonCache = Map<string, FeatureCollection>;\nexport type ComputeCache = Map<string, FeatureCollection>;\n\nexport type AutkGrammarSpec = UrbanSpec;\n\n// Grammar-level interaction payloads — no autk internals leak through the public API\nexport interface GrammarPickingEvent {\n layerId: string;\n selection: number[];\n}\n\nexport interface GrammarPlotSelectionEvent {\n plotId: string;\n event: 'click' | 'brush' | 'brushX' | 'brushY';\n selection: number[];\n}\n\nexport type GrammarEventRecord = {\n 'map:picking': GrammarPickingEvent;\n 'plot:selection': GrammarPlotSelectionEvent;\n};\n\n// Self-contained typed emitter — does not import from autk packages\nexport class GrammarEventEmitter {\n private _listeners: Map<string, Set<(p: unknown) => void>> = new Map();\n\n on<K extends keyof GrammarEventRecord>(\n event: K,\n listener: (payload: GrammarEventRecord[K]) => void\n ): () => void {\n if (!this._listeners.has(event)) this._listeners.set(event, new Set());\n const bucket = this._listeners.get(event)!;\n bucket.add(listener as (p: unknown) => void);\n return () => bucket.delete(listener as (p: unknown) => void);\n }\n\n /** @internal */\n emit<K extends keyof GrammarEventRecord>(event: K, payload: GrammarEventRecord[K]): void {\n this._listeners.get(event)?.forEach(l => l(payload));\n }\n}\n\n","import { DataAdapter, MapAdapter, PlotAdapter, ComputeAdapter, IEngine, UrbanSpec, createEngine } from \"@urban-toolkit/the-urban-grammar\";\nimport { AutkDb, DEFAULT_WORKSPACE_COORDINATE_FORMAT } from \"@urban-toolkit/autk-db\";\nimport { MapEvent } from \"@urban-toolkit/autk-map\";\nimport type { AutkMap } from \"@urban-toolkit/autk-map\";\nimport type { MapEventData } from \"@urban-toolkit/autk-map\";\nimport { PlotEvent } from \"@urban-toolkit/autk-plot\";\nimport type { PlotEventData } from \"@urban-toolkit/autk-plot\";\nimport { FeatureCollection } from \"geojson\";\nimport { createDataAdapter } from \"./adapters/data\";\nimport { createMapAdapter } from \"./adapters/map\";\nimport { createPlotAdapter } from \"./adapters/plot\";\nimport { createComputeAdapter } from \"./adapters/compute\";\nimport { Targets, MapRegistry, MapLayerIds, PlotRegistry, PlotMapLinks, GeoJsonCache, ComputeCache, GrammarEventEmitter } from \"./types\";\nimport type { GrammarMapLayer, GrammarPlotSelectionEvent } from \"./types\";\n\nexport class AutkGrammar {\n private dataAdapter?: DataAdapter;\n private mapAdapter?: MapAdapter;\n private plotAdapter?: PlotAdapter;\n private computeAdapter?: ComputeAdapter;\n private grammarEngine?: IEngine;\n private _computeCache: ComputeCache = new Map();\n private _data: Record<string, Promise<FeatureCollection>> = {};\n private _mapRegistry: MapRegistry = new Map();\n private _mapLayerIds: MapLayerIds = new Map();\n private _maps: AutkMap[] = [];\n private _plotRegistry: PlotRegistry = new Map();\n private _fwdCleanups: Array<() => void> = [];\n private _plotMapLinks: PlotMapLinks = new Map();\n\n readonly interactions = new GrammarEventEmitter();\n\n constructor(targets?: Targets) {\n const cache: GeoJsonCache = new Map();\n this.dataAdapter = createDataAdapter(targets, cache);\n this.mapAdapter = createMapAdapter(targets, this._mapRegistry, this._computeCache, this._maps, this._mapLayerIds);\n this.plotAdapter = createPlotAdapter(targets, this._mapRegistry, this._plotRegistry, this._plotMapLinks, cache, this._mapLayerIds);\n this.computeAdapter = createComputeAdapter(this._computeCache);\n }\n\n /**\n * The coordinate reference system used internally by the autk workspace.\n *\n * Input data is expected in EPSG:4326 (WGS84) by default and is transformed\n * to this CRS on load. Consumers that prepare data for injection (e.g. by\n * serialising a GeoDataFrame) can read this value and reproject accordingly\n * instead of hard-coding a CRS string.\n */\n get workspaceCrs(): string {\n return DEFAULT_WORKSPACE_COORDINATE_FORMAT;\n }\n\n get data(): Record<string, Promise<FeatureCollection>> {\n return this._data;\n }\n\n /**\n * The maps the last {@link run} drew, one per `map` entry of the spec, in order.\n *\n * Each map draws on demand: one frame once its layers are loaded, then one each\n * time it changes. Between frames a map canvas can read back empty, so to read a\n * map's pixels (for example with `canvas.toDataURL()`), call its `requestRender()`\n * and read in a `requestAnimationFrame` callback registered after that call.\n */\n get maps(): readonly AutkMap[] {\n return this._maps;\n }\n\n /**\n * The layer a map of the last {@link run} draws for a table, found by the table's name (a layer's `dataRef`):\n * the map that draws it, and the layer's id in that map, which is its `title`, else its `dataRef`.\n * `undefined` when no map draws the table. When several layers draw it, the last one.\n *\n * @example\n * const layer = grammar.mapLayer('buildings');\n * layer?.map.updateRenderInfo(layer.layerId, { opacity: 0.5 });\n */\n mapLayer(dataRef: string): GrammarMapLayer | undefined {\n const map = this._mapRegistry.get(dataRef);\n return map ? { map, layerId: this._mapLayerIds.get(dataRef) ?? dataRef } : undefined;\n }\n\n async run(spec: UrbanSpec) {\n if(!this.dataAdapter)\n throw new Error('Database adapter not initialized. Please call the constructor first.');\n\n if(!this.mapAdapter)\n throw new Error('Map engine not initialized. Please call the constructor first.');\n\n if(!this.plotAdapter)\n throw new Error('Plot adapter not initialized. Please call the constructor first.');\n\n if(!this.computeAdapter)\n throw new Error('Compute adapter not initialized. Please call the constructor first.');\n\n this._mapRegistry.clear();\n this._mapLayerIds.clear();\n this._maps.length = 0;\n this._plotRegistry.clear();\n this._plotMapLinks.clear();\n this._computeCache.clear();\n\n this.grammarEngine = createEngine({\n spec,\n adapters: {\n db: this.dataAdapter,\n map: this.mapAdapter,\n plot: this.plotAdapter,\n compute: this.computeAdapter\n }\n });\n\n await this.grammarEngine.run();\n this._rewireInteractions();\n\n const db = this.grammarEngine.context as AutkDb | undefined;\n if (!db) {\n console.warn('Grammar engine produced no data context.');\n this._data = {};\n return;\n }\n\n const dataObj: Record<string, Promise<FeatureCollection>> = {};\n for (const table of db.getLayersMetadata()) {\n Object.defineProperty(dataObj, table.name, {\n get: () => {\n const computed = this._computeCache.get(table.name);\n return computed ? Promise.resolve(computed) : db.getLayer(table.name);\n },\n enumerable: true,\n configurable: true,\n });\n }\n this._data = dataObj;\n }\n\n /**\n * Highlights features on the map layer that draws the table `dataRef` (see {@link mapLayer}).\n * If that layer is linked to a plot via `mapRef`, the plot selection is updated too.\n */\n highlightOnMap(dataRef: string, featureIds: number[]): void {\n const layer = this.mapLayer(dataRef);\n layer?.map.setHighlightedIds(layer.layerId, featureIds);\n for (const [plotId, mapRef] of this._plotMapLinks) {\n if (mapRef === dataRef) this._plotRegistry.get(plotId)?.setSelection(featureIds);\n }\n }\n\n /**\n * Clears highlighted features on the map layer that draws the table `dataRef` (see {@link mapLayer}).\n * If that layer is linked to a plot via `mapRef`, the plot selection is cleared too.\n */\n clearHighlightOnMap(dataRef: string): void {\n const layer = this.mapLayer(dataRef);\n layer?.map.clearHighlightedIds(layer.layerId);\n for (const [plotId, mapRef] of this._plotMapLinks) {\n if (mapRef === dataRef) this._plotRegistry.get(plotId)?.setSelection([]);\n }\n }\n\n /**\n * Clears the selection on the plot identified by `plotId` (its dataRef).\n * If that plot is linked to a map via `mapRef`, the map highlight is cleared too.\n */\n clearHighlightOnPlot(plotId: string): void {\n this._plotRegistry.get(plotId)?.setSelection([]);\n const mapRef = this._plotMapLinks.get(plotId);\n const layer = mapRef ? this.mapLayer(mapRef) : undefined;\n layer?.map.clearHighlightedIds(layer.layerId);\n }\n\n /**\n * Applies a selection to the plot identified by `plotId` (its dataRef).\n * If that plot is linked to a map via `mapRef`, the map highlight is updated too.\n */\n setPlotSelection(plotId: string, featureIds: number[]): void {\n this._plotRegistry.get(plotId)?.setSelection(featureIds);\n const mapRef = this._plotMapLinks.get(plotId);\n const layer = mapRef ? this.mapLayer(mapRef) : undefined;\n layer?.map.setHighlightedIds(layer.layerId, featureIds);\n }\n\n private _rewireInteractions(): void {\n for (const cleanup of this._fwdCleanups) cleanup();\n this._fwdCleanups = [];\n\n // Wire each unique map → grammar bus\n // Multiple layerRefs can share one AutkMap instance; deduplicate to avoid double-subscription\n const seenMaps = new Set<AutkMap>();\n for (const [layerId, map] of this._mapRegistry) {\n if (seenMaps.has(map)) continue;\n seenMaps.add(map);\n const handler = ({ selection }: MapEventData) => {\n this.interactions.emit('map:picking', { layerId, selection });\n };\n map.events.on(MapEvent.PICKING, handler);\n this._fwdCleanups.push(() => map.events.off(MapEvent.PICKING, handler));\n }\n\n // Wire each plot → grammar bus (all four event types)\n for (const [plotId, plot] of this._plotRegistry) {\n for (const ev of [PlotEvent.CLICK, PlotEvent.BRUSH, PlotEvent.BRUSH_X, PlotEvent.BRUSH_Y] as const) {\n const handler = ({ selection }: PlotEventData) => {\n this.interactions.emit('plot:selection', {\n plotId,\n event: ev as GrammarPlotSelectionEvent['event'],\n selection,\n });\n };\n plot.events.on(ev, handler);\n this._fwdCleanups.push(() => plot.events.off(ev, handler));\n }\n }\n }\n}\n"],"names":["P","e","_","S","t","s","E","i","u","R","c","n","A","queryAreaOf","spec","queryArea","refuse","message","box","value","west","south","east","north","toLoadOsmParams","autoLoadLayers","rest","createDataAdapter","targets","cache","print","db","div","tables","table","context","AutkDb","type","rest_spec","geojsonSpec","geojsonData","loadSpec","err","crsHint","bbox","WORLD_EXTENT","DEFAULT_WORKSPACE_COORDINATE_FORMAT","bboxErr","hm","jn","updated","layerIdOf","layerRef","checkLayerIds","index","ids","id","HEX_COLOR","hexColor","key","layerId","ColorMap","styleRenderInfo","renderInfo","colorsByValue","bandValues","collection","band","values","v","rasterScaleDomain","config","center","reverse","reach","finite","centered","domain","buildDomainSpec","normalization","colorMapDomain","ColorMapDomainStrategy","NormalizationMode","valueAtPath","obj","path","acc","setValueAtPath","keys","result","current","rasterBand","getFnv","bands","b","createMapAdapter","registry","computeCache","maps","layerIds","loadLayers","map","tableToTypeMap","name","rawData","data","f","style","catchAllCategory","thematicData","effectiveDomain","allowed","props","val","rasterTransfer","rasterScale","colormapConfig","ColorMapInterpolator","property","canvas","AutkMap","grammarMarkToPlotType","mark","createPlotAdapter","plotRegistry","plotMapLinks","geojson","events","plot","AutkPlot","MapEvent","selection","event","STORAGE_BUFFER_BINDING_SIZE","SCALAR_BYTES","BOX_BYTES","joinWgsl","body","isFromFeature","lookup","layers","item","directives","block","out","cfg","computeLayerNames","d","findIterateSource","iterate","layer","resolveDirective","iterateIndex","ff","feature","resolveUniforms","uniforms","num","resolveUniformMatrices","matrices","resolved","cols","isFiniteValue","isBatched","batchedBytesPerFeature","maxBatchedFeatures","bindingSize","bytes","buildBatchedUniforms","sources","outUniforms","outArrays","required","before","p","limit","fallback","ring","xmin","ymin","xmax","ymax","coord","x","y","resolveComputeParams","params","packed","single","notBatched","entries","outputColumns","runCompute","run","target","columns","summed","compute","col","count","step","j","dst","src","inc","createComputeAdapter","cached","engine","AutkComputeEngine","GrammarEventEmitter","listener","bucket","payload","l","AutkGrammar","dataRef","createEngine","dataObj","computed","featureIds","plotId","mapRef","cleanup","seenMaps","handler","ev","PlotEvent"],"mappings":";;;;;AAAA,SAASA,GAAEC,GAAG;AACZ,QAAM,EAAE,MAAMC,GAAG,UAAUC,EAAC,IAAKF;AACjC,MAAIG;AACJ,iBAAeC,IAAI;AACjB,QAAIC;AACJ,QAAIJ,EAAE;AACJ,iBAAWK,KAAKL,EAAE;AAChB,QAAAI,IAAI,MAAMH,EAAE,GAAG,cAAcG,GAAGC,CAAC;AACrC,QAAIL,EAAE;AACJ,iBAAWK,KAAKL,EAAE;AAChB,QAAAI,IAAI,MAAMH,EAAE,QAAQ,eAAeG,GAAGC,CAAC;AAC3C,QAAIL,EAAE;AACJ,UAAI,MAAM,QAAQA,EAAE,GAAG;AACrB,iBAASK,IAAI,GAAGA,IAAIL,EAAE,IAAI,QAAQK,KAAK;AACrC,cAAIC,IAAIN,EAAE,IAAIK,CAAC;AACf,gBAAMJ,EAAE,IAAI,WAAWG,GAAGE,GAAGD,CAAC;AAAA,QAChC;AAAA;AAEA,cAAMJ,EAAE,IAAI,WAAWG,GAAGJ,EAAE,GAAG;AACnC,QAAIA,EAAE;AACJ,UAAI,MAAM,QAAQA,EAAE,IAAI;AACtB,mBAAWK,KAAKL,EAAE;AAChB,gBAAMC,EAAE,KAAK,YAAYG,GAAGC,CAAC;AAAA;AAE/B,cAAMJ,EAAE,KAAK,YAAYG,GA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AA,QACL;AACA,QAAAH,EAAK,OAAO,GAAGiG,GAAID,CAAO,GAC1B,KAAK,aAAa,KAAK,MAAMhG,EAAK,OAAO,IAAIiG,GAAID,CAAO,CAAC;AAAA,MAC7D;AAAA,EAER;AACJ;"}
1
+ {"version":3,"file":"autk-grammar.js","sources":["../../../grammar/dist/the-urban-grammar.js","../src/adapters/data.ts","../src/adapters/map.ts","../src/adapters/plot.ts","../src/compute-params.ts","../src/adapters/compute.ts","../src/types.ts","../src/main.ts"],"sourcesContent":["function P(e) {\n const { spec: _, adapters: S } = e;\n let t;\n async function s() {\n let E;\n if (_.data)\n for (const i of _.data)\n E = await S.db.resolveSource(E, i);\n if (_.compute)\n for (const i of _.compute)\n E = await S.compute.resolveCompute(E, i);\n if (_.map)\n if (Array.isArray(_.map))\n for (let i = 0; i < _.map.length; i++) {\n let u = _.map[i];\n await S.map.resolveMap(E, u, i);\n }\n else\n await S.map.resolveMap(E, _.map);\n if (_.plot)\n if (Array.isArray(_.plot))\n for (const i of _.plot)\n await S.plot.resolvePlot(E, i);\n else\n await S.plot.resolvePlot(E, _.plot);\n t = E;\n }\n function R(E) {\n return console.log(\"Spec to update\", E), new Promise((i) => {\n i();\n });\n }\n function c() {\n console.log(\"Function not implemented yet\");\n }\n return { run: s, updatedSpec: R, destroy: c, get context() {\n return t;\n } };\n}\nvar n = /* @__PURE__ */ ((e) => (e.CAT_ACCENT = \"schemeAccent\", e.CAT_DARK2 = \"schemeDark2\", e.CAT_CATEGORY10 = \"schemeCategory10\", e.CAT_OBSERVABLE10 = \"schemeObservable10\", e.CAT_PAIRED = \"schemePaired\", e.CAT_PASTEL1 = \"schemePastel1\", e.CAT_PASTEL2 = \"schemePastel2\", e.CAT_SET1 = \"schemeSet1\", e.CAT_SET2 = \"schemeSet2\", e.CAT_SET3 = \"schemeSet3\", e.CAT_TABLEAU10 = \"schemeTableau10\", e.SEQ_REDS = \"interpolateReds\", e.SEQ_BLUES = \"interpolateBlues\", e.SEQ_GREENS = \"interpolateGreens\", e.SEQ_GREYS = \"interpolateGreys\", e.SEQ_ORANGES = \"interpolateOranges\", e.SEQ_PURPLES = \"interpolatePurples\", e.SEQ_TURBO = \"interpolateTurbo\", e.SEQ_VIRIDIS = \"interpolateViridis\", e.SEQ_INFERNO = \"interpolateInferno\", e.SEQ_MAGMA = \"interpolateMagma\", e.SEQ_PLASMA = \"interpolatePlasma\", e.SEQ_CIVIDIS = \"interpolateCividis\", e.SEQ_WARM = \"interpolateWarm\", e.SEQ_COOL = \"interpolateCool\", e.SEQ_CUBEHELIX_DEFAULT = \"interpolateCubehelixDefault\", e.SEQ_BU_GN = \"interpolateBuGn\", e.SEQ_BU_PU = \"interpolateBuPu\", e.SEQ_GN_BU = \"interpolateGnBu\", e.SEQ_OR_RD = \"interpolateOrRd\", e.SEQ_PU_BU_GN = \"interpolatePuBuGn\", e.SEQ_PU_BU = \"interpolatePuBu\", e.SEQ_PU_RD = \"interpolatePuRd\", e.SEQ_RD_PU = \"interpolateRdPu\", e.SEQ_YL_GN_BU = \"interpolateYlGnBu\", e.SEQ_YL_GN = \"interpolateYlGn\", e.SEQ_YL_OR_BR = \"interpolateYlOrBr\", e.SEQ_YL_OR_RD = \"interpolateYlOrRd\", e.DIV_BR_BG = \"interpolateBrBG\", e.DIV_PR_GN = \"interpolatePRGn\", e.DIV_PI_YG = \"interpolatePiYG\", e.DIV_PU_OR = \"interpolatePuOr\", e.DIV_RED_BLUE = \"interpolateRdBu\", e.DIV_RED_GREY = \"interpolateRdGy\", e.DIV_RED_YELLOW_BLUE = \"interpolateRdYlBu\", e.DIV_RED_YELLOW_GREEN = \"interpolateRdYlGn\", e.DIV_SPECTRAL = \"interpolateSpectral\", e))(n || {}), A = /* @__PURE__ */ ((e) => (e.MIN_MAX = \"minMax\", e.PERCENTILE = \"percentile\", e))(A || {});\nexport {\n n as ColorMapInterpolator,\n A as NormalizationMode,\n P as createEngine\n};\n//# sourceMappingURL=the-urban-grammar.js.map\n","import { CsvDataSourceSpec, CustomDataSourceSpec, DataAdapter, DataSourceSpec, HeatmapSourceSpec, JoinSourceSpec, JsonDataSourceSpec, OsmDataSourceSpec } from '@urban-toolkit/the-urban-grammar';\nimport { AutkDb, DEFAULT_WORKSPACE_COORDINATE_FORMAT } from '@urban-toolkit/autk-db';\nimport type { LoadGeojsonParams } from '@urban-toolkit/autk-db';\nimport type { FeatureCollection, Geometry } from 'geojson';\nimport { Targets, GeoJsonCache } from '../types';\n\n/**\n * The query area autk-db reads: `{ bbox }` or `{ geocodeArea, areas }`. autk-db takes any area with a\n * `bbox` key as a box, so a box that also names areas, or that is not [west, south, east, north] in\n * degrees with west less than east and south less than north, is refused here.\n */\nfunction queryAreaOf(spec: OsmDataSourceSpec): OsmDataSourceSpec['queryArea'] {\n const { queryArea } = spec;\n if (queryArea.bbox === undefined) return { geocodeArea: queryArea.geocodeArea, areas: queryArea.areas };\n\n const refuse = (message: string) => new Error(`OSM source \"${spec.outputTableName}\": ${message}`);\n if (queryArea.geocodeArea !== undefined || queryArea.areas !== undefined)\n throw refuse('queryArea takes either bbox or geocodeArea with areas, not both.');\n const box: unknown = queryArea.bbox;\n if (!Array.isArray(box) || box.length !== 4 || !box.every((value) => typeof value === 'number' && Number.isFinite(value)))\n throw refuse('queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.');\n const [west, south, east, north] = queryArea.bbox;\n if (Math.abs(west) > 180 || Math.abs(east) > 180)\n throw refuse('queryArea.bbox west and east must be longitudes from -180 to 180.');\n if (Math.abs(south) > 90 || Math.abs(north) > 90)\n throw refuse('queryArea.bbox south and north must be latitudes from -90 to 90.');\n if (west >= east)\n throw refuse(`queryArea.bbox west (${west}) must be less than east (${east}); a box across the antimeridian is not supported.`);\n if (south >= north)\n throw refuse(`queryArea.bbox south (${south}) must be less than north (${north}).`);\n return { bbox: [west, south, east, north] };\n}\n\n/**\n * Maps an OSM source onto autk-db's parameters, which always expect\n * `autoLoadLayers` and no longer take `dropOsmTable`.\n */\nfunction toLoadOsmParams(spec: OsmDataSourceSpec) {\n const { autoLoadLayers, ...rest } = spec;\n return { ...rest, queryArea: queryAreaOf(spec), autoLoadLayers: { layers: autoLoadLayers?.layers ?? [] } };\n}\n\n/**\n * The CRS advice. Only a bounding-box check gives it, when the box shows that a layer's coordinates\n * are not in the CRS it was loaded as; any other load error is autk-db's own message.\n */\nfunction crsAdvice(coordinateFormat: string | undefined): string {\n const assumed = coordinateFormat\n ? `coordinateFormat is set to \"${coordinateFormat}\"`\n : 'no coordinateFormat was specified, so it defaults to EPSG:4326 (WGS84 per RFC 7946)';\n return `${assumed}. Verify that coordinateFormat matches the actual CRS of the input data.`;\n}\n\n/** The [minX, minY, maxX, maxY] of every position in a collection, or undefined when it has none. */\nfunction 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\nexport function createDataAdapter(targets?: Targets, cache?: GeoJsonCache): DataAdapter {\n\n function print(db: AutkDb, targets?: Targets): void {\n if(!targets || !targets.db)\n return\n\n const div = document.getElementById(targets.db);\n if (div) {\n const tables = db.getTablesMetadata();\n\n div.innerHTML += `<ul>`;\n for (const table of tables) {\n div.innerHTML += `<li>${table.name}: (${table.source}, ${table.type}) </li>`;\n }\n div.innerHTML += `</ul>`;\n\n div.innerHTML += `<p>Number of tables: ${tables.length}</p>`;\n }\n }\n\n return {\n async resolveSource(context: AutkDb | undefined, spec: DataSourceSpec): Promise<AutkDb | undefined> {\n\n let db = context;\n\n if(!db){\n db = new AutkDb();\n await db.init();\n }\n\n let {type, ...rest_spec} = spec;\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 loader tolerates null geometry and missing properties, which the inline type allows.\n geojsonData = geojsonSpec.geojsonObject as FeatureCollection | undefined;\n }\n\n if (cache && geojsonData) cache.set(geojsonSpec.outputTableName, geojsonData);\n\n // Pass the fetched object directly so autk-db doesn't need to re-fetch\n const loadSpec = (geojsonData\n ? (() => { const s = { ...geojsonSpec, geojsonObject: geojsonData }; delete s.geojsonFileUrl; return s; })()\n : geojsonSpec) as LoadGeojsonParams;\n\n // Degrees put every y within -90 to 90, so a y outside it shows a layer in another CRS. The\n // transform makes such a y infinite, and autk-db would refuse the layer with a grid error.\n // A longitude past 180 is not checked: the transform wraps it.\n const readAsDegrees = /^EPSG:4326$/i.test(loadSpec.coordinateFormat ?? 'EPSG:4326');\n const extent = geojsonData && readAsDegrees ? extentOf(geojsonData) : undefined;\n if (extent && (extent[1] < -90 || extent[3] > 90)) {\n throw new Error(\n `GeoJSON layer \"${loadSpec.outputTableName}\" has y coordinates outside -90 to 90 ` +\n `(bbox: [${extent.join(', ')}]), so they cannot be EPSG:4326 degrees. ${crsAdvice(loadSpec.coordinateFormat)}`\n );\n }\n\n try {\n await db.loadGeojson(loadSpec);\n } catch (err) {\n throw new Error(`Failed to load GeoJSON layer \"${loadSpec.outputTableName}\": ${err instanceof Error ? err.message : String(err)}`);\n }\n\n // Validate that the loaded geometry is within the workspace CRS extent.\n // A bounding box outside the valid world extent indicates a CRS mismatch.\n try {\n const bbox = await db.getBoundingBoxFromLayer(loadSpec.outputTableName);\n const WORLD_EXTENT = 25_000_000; // generous bound for DEFAULT_WORKSPACE_COORDINATE_FORMAT (EPSG:3395)\n if (\n !isFinite(bbox.minLon) || !isFinite(bbox.minLat) ||\n !isFinite(bbox.maxLon) || !isFinite(bbox.maxLat) ||\n Math.abs(bbox.minLon) > WORLD_EXTENT || Math.abs(bbox.maxLon) > WORLD_EXTENT ||\n Math.abs(bbox.minLat) > WORLD_EXTENT || Math.abs(bbox.maxLat) > WORLD_EXTENT\n ) {\n throw new Error(\n `Geometry bounding box after transform is invalid for layer \"${loadSpec.outputTableName}\" ` +\n `(bbox: [${bbox.minLon}, ${bbox.minLat}, ${bbox.maxLon}, ${bbox.maxLat}]). ` +\n `${crsAdvice(loadSpec.coordinateFormat)} ` +\n `The workspace uses ${DEFAULT_WORKSPACE_COORDINATE_FORMAT}; input is expected in EPSG:4326 by default.`\n );\n }\n } catch (bboxErr) {\n if (bboxErr instanceof Error && bboxErr.message.includes('bounding box after transform')) throw bboxErr;\n // getBoundingBoxFromLayer failed (empty table, unsupported layer type, etc.) — skip validation\n }\n print(db, targets);\n return db;\n }\n case 'heatmap': {\n const hm = rest_spec as HeatmapSourceSpec;\n await db.buildHeatmap({\n tableJoinName: hm.tableJoinName,\n near: { distance: hm.near.distance },\n outputTableName: hm.outputTableName,\n grid: hm.grid,\n ...(hm.groupBy && { groupBy: hm.groupBy as any }),\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.tableRootName,\n tableJoinName: jn.tableJoinName,\n ...(jn.near && { near: jn.near }),\n ...(jn.groupBy && { groupBy: jn.groupBy }),\n });\n if (cache) {\n const updated = await db.getLayer(jn.tableRootName);\n cache.set(jn.tableRootName, updated);\n }\n print(db, targets);\n return db;\n }\n default:\n return\n }\n }\n }\n}\n","import { MapAdapter, MapLayerSpec, MapSpec, NormalizationMode } from '@urban-toolkit/the-urban-grammar';\nimport { Targets, MapRegistry, MapLayerIds, ComputeCache } from '../types';\nimport { AutkMap } from '@urban-toolkit/autk-map';\nimport type { LayerRenderInfo } from '@urban-toolkit/autk-map';\nimport { ColorMap, ColorMapDomainStrategy, ColorMapInterpolator } from '@urban-toolkit/autk-core';\nimport type { ColorHEX, ColorMapConfig, ColorMapDomainSpec, ColorRGB, LayerType, TransferFunction } from '@urban-toolkit/autk-core';\nimport { AutkDb } from '@urban-toolkit/autk-db';\n\n/** The id a layer has in its map: its `title`, else its `dataRef`. */\nexport function layerIdOf(layerRef: MapLayerSpec): string {\n return typeof layerRef.title === 'string' && layerRef.title !== '' ? layerRef.title : layerRef.dataRef;\n}\n\n/** Refuses a map whose layers would share an id. */\nfunction checkLayerIds(spec: MapSpec, index: number): void {\n const ids = new Set<string>();\n for (const layerRef of spec.layerRefs) {\n const id = layerIdOf(layerRef);\n if (ids.has(id))\n throw new Error(`Map ${index} draws two layers with the id \"${id}\". A layer's id is its title, else its dataRef: give each layer of a map its own title.`);\n ids.add(id);\n }\n}\n\nconst HEX_COLOR = /^#[0-9a-fA-F]{6}$/;\n\nfunction hexColor(value: string, key: string, layerId: string): ColorRGB {\n if (!HEX_COLOR.test(value))\n throw new Error(`Layer \"${layerId}\": ${key} must be a color written #rrggbb, not \"${value}\".`);\n return ColorMap.hexToRgb(value as ColorHEX);\n}\n\n/** What `color`, `stroke` and `width` set on the layer's autk-map render info. */\nfunction styleRenderInfo(layerRef: MapLayerSpec, layerId: string): Partial<LayerRenderInfo> {\n const renderInfo: Partial<LayerRenderInfo> = {};\n if (layerRef.color != null)\n renderInfo.color = hexColor(layerRef.color, 'color', layerId);\n if (layerRef.stroke === false)\n renderInfo.showBorders = false;\n else if (layerRef.stroke != null)\n renderInfo.strokeColor = hexColor(layerRef.stroke, 'stroke', layerId);\n if (layerRef.width != null)\n renderInfo.polylinesWidth = layerRef.width;\n return renderInfo;\n}\n\n/**\n * Whether the layer is colored by value. An explicit `isColorMap` decides. A raster layer is colored by value\n * either way, and this only shows or hides its legend. Otherwise a layer with a `color` is drawn in it, and a\n * layer with a scheme or a `getFnv` value is colored by value.\n */\nfunction colorsByValue(layerRef: MapLayerSpec, type: LayerType): boolean {\n if (layerRef.isColorMap != null) return layerRef.isColorMap;\n if (type === 'raster')\n return layerRef.colorMapInterpolator != null || layerRef.colorMapRange != null || layerRef.colorMapCenter != null\n || layerRef.colorMapReverse === true;\n if (layerRef.color != null) return false;\n return layerRef.colorMapInterpolator != null || layerRef.getFnv != null;\n}\n\n/** A raster band's values, as autk-map reads them. */\nfunction bandValues(collection: { features?: { properties?: unknown }[] }, band: string): Float32Array | null {\n const values = (collection.features?.[0]?.properties as Record<string, unknown> | undefined)?.[band];\n if (values instanceof Float32Array) return values;\n if ((ArrayBuffer.isView(values) && !(values instanceof DataView)) || Array.isArray(values))\n return Float32Array.from(values as ArrayLike<number>, (v) => (Number.isFinite(Number(v)) ? Number(v) : NaN));\n return null;\n}\n\n/**\n * The domain of a raster's color scale when the layer sets a range, a center or reverse, or `undefined` when it\n * sets none of them, the scheme is categorical, or, without a range, the band has no value. A range is the domain:\n * `[low, high]`, or `[low, center, high]` with a center. Without one, a scale centered on `center` runs from the\n * center less the farthest value's distance to it, to the center plus that distance; when every value is the\n * center, it is not centered. Otherwise it is the domain autk-map resolves from `config`. `reverse` turns it around.\n */\nexport function rasterScaleDomain(\n values: Float32Array | null, config: ColorMapConfig, center?: number, reverse?: boolean, range?: [number, number],\n): number[] | undefined {\n if (ColorMap.isCategorical(config.interpolator)) return undefined;\n if (range != null) {\n const domain = center != null ? [range[0], center, range[1]] : [range[0], range[1]];\n return reverse === true ? domain.reverse() : domain;\n }\n if (!values) return undefined;\n let reach = 0;\n let finite = 0;\n for (let i = 0; i < values.length; i++) {\n const value = values[i];\n if (!Number.isFinite(value)) continue;\n finite++;\n if (center != null) reach = Math.max(reach, Math.abs(value - center));\n }\n const centered = center != null && reach > 0;\n if (finite === 0 || (!centered && reverse !== true)) return undefined;\n const domain = centered && center != null\n ? [center - reach, center, center + reach]\n : ColorMap.resolveDomainFromData(values, config) as number[];\n return reverse === true ? [...domain].reverse() : domain;\n}\n\n/**\n * The domain of a vector layer's color scale: its range, unless the scheme is categorical. autk-map colors a vector\n * layer on the GPU from its domain's first value to its last, which must be the higher, so the domain is neither\n * centered nor reversed.\n */\nfunction vectorScaleDomain(config: ColorMapConfig, range?: [number, number]): number[] | undefined {\n if (range == null || ColorMap.isCategorical(config.interpolator)) return undefined;\n return [range[0], range[1]];\n}\n\n/**\n * Refuses a `colorMapRange` that is not two numbers with low less than high, one set with `colorMapDomain`, and\n * one whose layer's `colorMapCenter` lies outside it. The schema refuses the same shapes and the pairing with\n * `colorMapDomain`, but JSON Schema cannot compare two values: a low above its high and a center outside the range\n * are refused only here.\n */\nfunction checkColorMapRange(layerRef: MapLayerSpec): void {\n const range: unknown = layerRef.colorMapRange;\n if (range === undefined) return;\n const refuse = (message: string) => new Error(`Layer \"${layerIdOf(layerRef)}\": ${message}`);\n if (!Array.isArray(range) || range.length !== 2 || !range.every((value) => typeof value === 'number' && Number.isFinite(value)))\n throw refuse('colorMapRange must hold two numbers, [low, high].');\n const [low, high] = range as [number, number];\n if (low >= high)\n throw refuse(`colorMapRange low (${low}) must be less than high (${high}).`);\n if (layerRef.colorMapDomain !== undefined)\n throw refuse('set colorMapRange or colorMapDomain, not both.');\n const center = layerRef.colorMapCenter;\n if (center != null && (center < low || center > high))\n throw refuse(`colorMapCenter (${center}) must lie within colorMapRange [${low}, ${high}].`);\n}\n\nfunction buildDomainSpec(\n normalization: MapSpec['layerRefs'][number]['normalization'],\n colorMapDomain?: string[],\n): ColorMapDomainSpec {\n if (colorMapDomain && colorMapDomain.length > 0)\n return { type: ColorMapDomainStrategy.USER, params: colorMapDomain };\n if (normalization?.mode === NormalizationMode.PERCENTILE) {\n const hasExplicitBounds =\n normalization.lowerPercentile !== undefined || normalization.upperPercentile !== undefined;\n if (hasExplicitBounds)\n return {\n type: ColorMapDomainStrategy.PERCENTILE,\n params: [normalization.lowerPercentile ?? 0, normalization.upperPercentile ?? 100],\n };\n return { type: ColorMapDomainStrategy.PERCENTILE };\n }\n return { type: ColorMapDomainStrategy.MIN_MAX };\n}\n\nfunction valueAtPath(obj: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>((acc, key) => {\n if (acc == null || typeof acc !== 'object') return undefined;\n return (acc as Record<string, unknown>)[key];\n }, obj);\n}\n\nfunction setValueAtPath(obj: Record<string, unknown>, path: string, value: unknown): Record<string, unknown> {\n const keys = path.split('.');\n const result = { ...obj };\n let current = result as Record<string, unknown>;\n for (let i = 0; i < keys.length - 1; i++) {\n current[keys[i]] = { ...(current[keys[i]] as Record<string, unknown> ?? {}) };\n current = current[keys[i]] as Record<string, unknown>;\n }\n current[keys[keys.length - 1]] = value;\n return result;\n}\n\n/**\n * Resolves a grammar value path such as `count.noise` to the raster band that holds it.\n * autk-db stores heatmap values in bands (`band_1`, ...) labelled `<aggregateFn>_<table>`.\n */\nfunction rasterBand(collection: { features?: { properties?: unknown }[] }, getFnv?: string): string {\n const props = collection.features?.[0]?.properties as { bands?: { id: string; label?: string }[] } | undefined;\n const bands = props?.bands ?? [];\n const band = bands.find((b) => b.id === getFnv || b.label === getFnv?.replace(/\\./g, '_'));\n return band?.id ?? bands[0]?.id ?? getFnv ?? '';\n}\n\nexport function createMapAdapter(targets?: Targets, registry?: MapRegistry, computeCache?: ComputeCache, maps?: AutkMap[], layerIds?: MapLayerIds): MapAdapter {\n\n async function loadLayers(map: AutkMap, context: AutkDb, spec: MapSpec): Promise<void> {\n let tableToTypeMap: {[tableName: string]: string} = {};\n for(const table of context.getTablesMetadata()) {\n if(table.type !== undefined) tableToTypeMap[table.name] = table.type;\n }\n\n for(const layerRef of spec.layerRefs){\n const name = layerRef.dataRef;\n const layerId = layerIdOf(layerRef);\n const type = tableToTypeMap[name] as LayerType;\n const getFnv = layerRef.getFnv;\n\n const rawData = computeCache?.get(name) ?? await context.getLayer(name);\n // Raster tables (e.g. heatmaps) are a single feature with no geometry, so keep them as-is.\n const data = type === 'raster' ? rawData : {\n ...rawData,\n features: (rawData.features ?? []).filter((f: any) => f.geometry != null),\n };\n const band = type === 'raster' ? rasterBand(data, getFnv) : '';\n\n if(type === 'raster') {\n map.loadCollection(layerId, { collection: data, type: 'raster', property: band });\n } else {\n map.loadCollection(layerId, { collection: data, type });\n }\n\n if(layerRef.opacity != null)\n map.updateRenderInfo(layerId, { opacity: layerRef.opacity });\n\n const style = styleRenderInfo(layerRef, layerId);\n if(Object.keys(style).length > 0)\n map.updateRenderInfo(layerId, style);\n\n // Thematic (getFnv) vector layers are colored by value out of the box: autk-map\n // attaches a default colour ramp to every layer, so this works even when the\n // spec omits colorMapInterpolator (see colorsByValue).\n if(colorsByValue(layerRef, type))\n map.updateRenderInfo(layerId, { isColorMap: true });\n\n if(layerRef.isPick)\n map.updateRenderInfo(layerId, { isPick: true });\n\n if(layerRef.isSkip)\n map.updateRenderInfo(layerId, { isSkip: true });\n\n // When catchAllCategory is set, remap features whose property value is not\n // in colorMapDomain to the catch-all label, and extend the domain to include it.\n const { catchAllCategory, colorMapDomain } = layerRef;\n let thematicData = data;\n let effectiveDomain = colorMapDomain;\n\n if(getFnv && catchAllCategory && colorMapDomain?.length) {\n const allowed = new Set(colorMapDomain);\n thematicData = {\n ...data,\n features: data.features.map((f: any) => {\n const props = f.properties as Record<string, unknown>;\n const val = valueAtPath(props, getFnv);\n if(val === undefined || val === null || !allowed.has(String(val))) {\n return { ...f, properties: setValueAtPath(props, getFnv, catchAllCategory) };\n }\n return f;\n }),\n };\n effectiveDomain = allowed.has(catchAllCategory)\n ? colorMapDomain\n : [...colorMapDomain, catchAllCategory];\n }\n\n // A raster's transfer function is only stored by setTransferFunction; the\n // updateColorMap below colors the cells again with it.\n const rasterTransfer = type === 'raster' && layerRef.transferFunction != null;\n if(rasterTransfer) {\n const layer = map.layerManager.searchByLayerId(layerId) as unknown as\n { setTransferFunction?: (transferFunction: TransferFunction) => void } | null;\n layer?.setTransferFunction?.(layerRef.transferFunction as TransferFunction);\n }\n\n // The scheme and its domain go through updateColorMap, which colors a raster's\n // cells again and gives the legend its labels. A vector layer keeps the domain\n // in its config, where the updateThematic below reads it.\n const range = layerRef.colorMapRange;\n const rasterScale = type === 'raster' && (range != null || layerRef.colorMapCenter != null || layerRef.colorMapReverse === true);\n if(layerRef.colorMapInterpolator || rasterScale || range) {\n const colormapConfig: ColorMapConfig = {\n // urban-grammar ColorMapInterpolator values are string-compatible\n // with autk-core ColorMapInterpolator at runtime\n interpolator: (layerRef.colorMapInterpolator as unknown as ColorMapConfig['interpolator'] | undefined)\n ?? map.layerManager.searchByLayerId(layerId)?.layerRenderInfo.colormap.config.interpolator\n ?? ColorMapInterpolator.SEQ_REDS,\n domainSpec: buildDomainSpec(layerRef.normalization, effectiveDomain),\n };\n let domain: number[] | undefined;\n if(rasterScale)\n domain = rasterScaleDomain(bandValues(data, band), colormapConfig, layerRef.colorMapCenter, layerRef.colorMapReverse, range);\n else if(type !== 'raster')\n domain = vectorScaleDomain(colormapConfig, range);\n if(domain)\n colormapConfig.domainSpec = { type: ColorMapDomainStrategy.USER, params: domain };\n map.updateColorMap(layerId, { colorMap: colormapConfig });\n } else if(rasterTransfer) {\n map.updateColorMap(layerId, { colorMap: {} });\n }\n\n if(getFnv && type !== 'raster') {\n const property = getFnv.startsWith('properties.') ? getFnv : `properties.${getFnv}`;\n map.updateThematic(layerId, { collection: thematicData, property });\n }\n }\n }\n\n return {\n async resolveMap(context: AutkDb | undefined, spec: MapSpec, index: number = 0): Promise<void> {\n if(targets && targets.map && context){\n\n checkLayerIds(spec, index);\n for(const layerRef of spec.layerRefs)\n checkColorMapRange(layerRef);\n\n let canvas;\n\n if(Array.isArray(targets.map)){\n canvas = document.getElementById(targets.map[index]);\n }else{\n canvas = document.getElementById(targets.map);\n }\n\n if(!canvas)\n throw new Error(\"Could not find rendering target for map: \"+targets.map);\n\n if(!(canvas instanceof HTMLCanvasElement))\n throw new Error(\"Target for map is not a canvas: \"+targets.map);\n\n const map = new AutkMap(canvas);\n\n if(spec.style)\n map.style.setPredefinedStyle(spec.style)\n\n await map.init();\n await loadLayers(map, context, spec);\n\n for(const layerRef of spec.layerRefs) {\n registry?.set(layerRef.dataRef, map);\n layerIds?.set(layerRef.dataRef, layerIdOf(layerRef));\n }\n\n if(maps)\n maps[index] = map;\n\n map.draw();\n }\n }\n }\n}\n","import { PlotAdapter, PlotSpec, PlotMark } from '@urban-toolkit/the-urban-grammar';\nimport { Targets, MapRegistry, MapLayerIds, PlotRegistry, PlotMapLinks, GeoJsonCache } from '../types';\nimport { AutkDb } from '@urban-toolkit/autk-db';\nimport { AutkPlot, PlotEvent as AutkPlotEvent } from '@urban-toolkit/autk-plot';\nimport type { PlotEventData, PlotType, PlotTransformConfig } from '@urban-toolkit/autk-plot';\nimport { AutkMap, MapEvent } from '@urban-toolkit/autk-map';\nimport type { MapEventData } from '@urban-toolkit/autk-map';\nimport { FeatureCollection } from 'geojson';\n\nfunction grammarMarkToPlotType(mark: PlotMark): PlotType {\n const mapping: Record<PlotMark, PlotType> = {\n 'scatter': 'scatterplot',\n 'bar': 'barchart',\n 'line': 'linechart',\n 'linechart': 'linechart',\n 'parallel-coordinates': 'parallel-coordinates',\n 'table': 'table',\n 'heatmatrix': 'heatmatrix',\n };\n return mapping[mark];\n}\n\nexport function createPlotAdapter(targets?: Targets, registry?: MapRegistry, plotRegistry?: PlotRegistry, plotMapLinks?: PlotMapLinks, cache?: GeoJsonCache, layerIds?: MapLayerIds): PlotAdapter {\n\n return {\n async resolvePlot(context: unknown, spec: PlotSpec): Promise<void> {\n if(!targets || !targets.plot) return;\n\n const div = document.getElementById(targets.plot);\n if(!div) throw new Error(`Could not find plot target: ${targets.plot}`);\n\n const db = context as AutkDb | undefined;\n if(!db) throw new Error('No data context available for plot.');\n\n const geojson: FeatureCollection = cache?.get(spec.dataRef) ?? await db.getLayer(spec.dataRef);\n\n const events = (spec.events ?? []) as unknown as AutkPlotEvent[];\n\n const plot = new AutkPlot(div, {\n type: grammarMarkToPlotType(spec.mark),\n collection: geojson,\n attributes: { axis: spec.axis, ...(spec.color && { color: spec.color }) },\n labels: { axis: spec.axis, title: spec.title },\n events,\n ...(spec.width && { width: spec.width }),\n ...(spec.height && { height: spec.height }),\n ...(spec.margins && { margins: spec.margins }),\n ...(spec.transform && { transform: spec.transform as PlotTransformConfig }),\n });\n\n plotRegistry?.set(spec.dataRef, plot);\n if (spec.mapRef) plotMapLinks?.set(spec.dataRef, spec.mapRef);\n\n // Wire map ↔ plot events if a mapRef is specified. mapRef names the layer's\n // table; the layer's id in its map is its title, else that name.\n if(spec.mapRef && registry) {\n const map: AutkMap | undefined = registry.get(spec.mapRef);\n const layerId = layerIds?.get(spec.mapRef) ?? spec.mapRef;\n\n if(map) {\n map.updateRenderInfo(layerId, { isPick: true });\n\n map.events.on(MapEvent.PICKING, ({ selection }: MapEventData) => {\n plot.setSelection(selection);\n });\n\n for(const event of events) {\n plot.events.on(event, ({ selection }: PlotEventData) => {\n map.setHighlightedIds(layerId, selection);\n });\n }\n }\n }\n }\n }\n}\n","import type { ComputeSpec, FromFeatureDirective } from '@urban-toolkit/the-urban-grammar';\nimport type { GpgpuPipelineParams } from '@urban-toolkit/autk-compute';\nimport type { Feature, FeatureCollection } from 'geojson';\n\n/** Tables a compute pass can read, keyed by table name. */\nexport type ComputeLayers = Record<string, FeatureCollection | undefined> | Map<string, FeatureCollection>;\n\n/** Runs one GPU dispatch, for example `params => new AutkComputeEngine().gpgpuPipeline(params)`. */\nexport type ComputeRunner = (params: GpgpuPipelineParams) => Promise<FeatureCollection>;\n\n/**\n * The storage buffer binding every WebGPU device supports: the default\n * `maxStorageBufferBindingSize`, 128 MiB. autk-compute 4 reads each array a `batched` directive\n * packs from a read-only storage buffer of its own, so every packed array must fit one binding.\n * autk-compute 3 bound them as uniform buffers, which hold 64 KiB (2048 bounding boxes).\n */\nexport const STORAGE_BUFFER_BINDING_SIZE = 134_217_728;\n\n/** Bytes a feature adds to a packed array: one f32 for a scalar entry, a bounding box of eight for a matrix entry. */\nconst SCALAR_BYTES = 4;\nconst BOX_BYTES = 8 * 4;\n\ntype UniformEntry = number | FromFeatureDirective;\ntype MatrixEntry = { data: number[][]; cols: number } | FromFeatureDirective;\n\n/** Joins a `wglsFunction` written as an array of lines. Any other separator would let a `//` comment swallow the lines after it. */\nexport function joinWgsl(body: string | string[]): string {\n return Array.isArray(body) ? body.join('\\n') : body;\n}\n\n/** True when a uniform entry reads its value from a feature. */\nexport function isFromFeature(value: unknown): value is FromFeatureDirective {\n return !!value && typeof value === 'object' && !Array.isArray(value)\n && typeof (value as FromFeatureDirective).fromFeature === 'object'\n && (value as FromFeatureDirective).fromFeature !== null;\n}\n\nfunction lookup(layers: ComputeLayers, name: string): FeatureCollection | undefined {\n return layers instanceof Map ? layers.get(name) : layers[name];\n}\n\nfunction valueAtPath(item: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>((acc, key) => {\n if (acc == null || typeof acc !== 'object') return undefined;\n return (acc as Record<string, unknown>)[key];\n }, item);\n}\n\nfunction directives(block: ComputeSpec): FromFeatureDirective[] {\n const out: FromFeatureDirective[] = [];\n for (const cfg of [block.uniforms, block.uniformMatrices]) {\n for (const value of Object.values(cfg ?? {})) {\n if (isFromFeature(value)) out.push(value);\n }\n }\n return out;\n}\n\n/** Every table a compute pass reads: its `dataRef` plus each `fromFeature` layer. */\nexport function computeLayerNames(block: ComputeSpec): string[] {\n return [...new Set([block.dataRef, ...directives(block).map(d => d.fromFeature.layer)])];\n}\n\n/**\n * The iteration a compute pass asks for, or `null`. Every iterating directive must read the same\n * layer; the first one found decides the mode and the layer.\n */\nexport function findIterateSource(block: ComputeSpec): { mode: 'all' | 'batched'; layer: string } | null {\n for (const d of directives(block)) {\n const { iterate, layer } = d.fromFeature;\n if (iterate === 'all' || iterate === 'batched') return { mode: iterate, layer };\n }\n return null;\n}\n\nfunction resolveDirective(d: FromFeatureDirective, layers: ComputeLayers, iterateIndex?: number): unknown {\n const ff = d.fromFeature;\n const index = iterateIndex !== undefined && ff.iterate === 'all' ? iterateIndex : (ff.index ?? 0);\n const feature = lookup(layers, ff.layer)?.features?.[index];\n return feature ? valueAtPath(feature, ff.path) : undefined;\n}\n\n/**\n * Resolves the `fromFeature` entries of `uniforms` to numbers. An entry that does not resolve to a\n * finite number takes its `default`, or is dropped when it has none.\n */\nexport function resolveUniforms(\n uniforms: Record<string, UniformEntry> | undefined,\n layers: ComputeLayers,\n iterateIndex?: number,\n): Record<string, number> | undefined {\n if (!uniforms) return undefined;\n const out: Record<string, number> = {};\n for (const [key, value] of Object.entries(uniforms)) {\n if (!isFromFeature(value)) {\n out[key] = value;\n continue;\n }\n const num = Number(resolveDirective(value, layers, iterateIndex) ?? NaN);\n if (Number.isFinite(num)) out[key] = num;\n else if (typeof value.default === 'number') out[key] = value.default;\n }\n return out;\n}\n\n/**\n * Resolves the `fromFeature` entries of `uniformMatrices` to `{ data, cols }`. An entry that does\n * not resolve to an array takes its `default`, or is dropped when it has none.\n */\nexport function resolveUniformMatrices(\n matrices: Record<string, MatrixEntry> | undefined,\n layers: ComputeLayers,\n iterateIndex?: number,\n): Record<string, { data: number[][]; cols: number }> | undefined {\n if (!matrices) return undefined;\n const out: Record<string, { data: number[][]; cols: number }> = {};\n for (const [key, value] of Object.entries(matrices)) {\n if (!isFromFeature(value)) {\n out[key] = value;\n continue;\n }\n const resolved = resolveDirective(value, layers, iterateIndex);\n const data = Array.isArray(resolved) ? (resolved as number[][])\n : Array.isArray(value.default) ? value.default : undefined;\n if (!data) continue;\n const cols = value.cols ?? (Array.isArray(data[0]) ? data[0].length : 0);\n if (cols > 0) out[key] = { data, cols };\n else console.warn(`[autk-grammar] uniform matrix \"${key}\" has no column count; entry dropped`);\n }\n return out;\n}\n\nfunction isFiniteValue(v: unknown): boolean {\n return v !== undefined && v !== null && !(typeof v === 'number' && !Number.isFinite(v));\n}\n\nfunction isBatched(value: unknown): boolean {\n return isFromFeature(value) && value.fromFeature.iterate === 'batched';\n}\n\n/** Bytes one feature adds to the largest array a batched pass packs, or 0 when it packs none. */\nfunction batchedBytesPerFeature(\n uniforms: Record<string, UniformEntry> | undefined,\n matrices: Record<string, MatrixEntry> | undefined,\n): number {\n if (Object.values(matrices ?? {}).some(isBatched)) return BOX_BYTES;\n if (Object.values(uniforms ?? {}).some(isBatched)) return SCALAR_BYTES;\n return 0;\n}\n\n/**\n * Most features a batched pass packs: as many as its largest array holds in one storage buffer\n * binding of `bindingSize` bytes. With {@link STORAGE_BUFFER_BINDING_SIZE} that is 4,194,304\n * features for a pass with a matrix entry, and 33,554,432 for one with scalar entries only.\n */\nexport function maxBatchedFeatures(\n uniforms: Record<string, UniformEntry> | undefined,\n matrices: Record<string, MatrixEntry> | undefined,\n bindingSize: number = STORAGE_BUFFER_BINDING_SIZE,\n): number {\n const bytes = batchedBytesPerFeature(uniforms, matrices);\n return bytes > 0 ? Math.floor(bindingSize / bytes) : Number.POSITIVE_INFINITY;\n}\n\n/**\n * Packs every feature of a `batched` layer into uniform arrays:\n * - a scalar entry becomes an array of one value per feature, under the entry's name;\n * - a matrix entry becomes each feature's axis-aligned bounding box as four corners\n * `[xmin,ymin, xmax,ymin, xmax,ymax, xmin,ymax]`, eight values per feature;\n * - `num_features` holds the feature count.\n * Features missing a `required` path are dropped first, and at most {@link maxBatchedFeatures}\n * are packed: as many as the largest array holds in one storage buffer binding of `bindingSize`\n * bytes. Plain numbers pass through; other entries that do not iterate are left to\n * {@link resolveComputeParams}.\n */\nexport function buildBatchedUniforms(\n uniforms: Record<string, UniformEntry> | undefined,\n matrices: Record<string, MatrixEntry> | undefined,\n sources: Feature[],\n bindingSize: number = STORAGE_BUFFER_BINDING_SIZE,\n): { uniforms: Record<string, number>; uniformArrays: Record<string, number[]> } {\n const outUniforms: Record<string, number> = {};\n const outArrays: Record<string, number[]> = {};\n\n const required: string[] = [];\n for (const cfg of [uniforms, matrices]) {\n for (const value of Object.values(cfg ?? {})) {\n if (isFromFeature(value) && value.fromFeature.iterate === 'batched' && value.fromFeature.required) {\n required.push(value.fromFeature.path);\n }\n }\n }\n if (required.length > 0) {\n const before = sources.length;\n sources = sources.filter(f => required.every(p => isFiniteValue(valueAtPath(f, p))));\n if (sources.length < before) {\n console.info(`[autk-grammar] batched compute dropped ${before - sources.length} feature(s) missing ${required.join(', ')}`);\n }\n }\n const limit = maxBatchedFeatures(uniforms, matrices, bindingSize);\n if (sources.length > limit) {\n console.warn(\n `[autk-grammar] batched compute capped at ${limit} features (got ${sources.length}): `\n + `its largest packed array takes ${batchedBytesPerFeature(uniforms, matrices)} B per feature, `\n + `and a storage buffer binding holds ${bindingSize} B`,\n );\n sources = sources.slice(0, limit);\n }\n\n for (const [key, value] of Object.entries(uniforms ?? {})) {\n if (isFromFeature(value) && value.fromFeature.iterate === 'batched') {\n const fallback = typeof value.default === 'number' ? value.default : undefined;\n outArrays[key] = sources.map(f => {\n const num = Number(valueAtPath(f, value.fromFeature.path) ?? fallback);\n return Number.isFinite(num) ? num : 0;\n });\n } else if (typeof value === 'number') {\n outUniforms[key] = value;\n }\n }\n\n for (const [key, value] of Object.entries(matrices ?? {})) {\n if (!isFromFeature(value) || value.fromFeature.iterate !== 'batched') continue;\n const data: number[] = [];\n for (const f of sources) {\n const ring = valueAtPath(f, value.fromFeature.path);\n let xmin = Infinity, ymin = Infinity, xmax = -Infinity, ymax = -Infinity;\n if (Array.isArray(ring)) {\n for (const coord of ring) {\n if (!Array.isArray(coord) || coord.length < 2) continue;\n const x = Number(coord[0]);\n const y = Number(coord[1]);\n if (!Number.isFinite(x) || !Number.isFinite(y)) continue;\n xmin = Math.min(xmin, x); ymin = Math.min(ymin, y);\n xmax = Math.max(xmax, x); ymax = Math.max(ymax, y);\n }\n }\n // A degenerate feature gets a zero-area box, so the shader's loop runs but adds nothing.\n if (!Number.isFinite(xmin)) { xmin = 0; ymin = 0; xmax = 0; ymax = 0; }\n data.push(xmin, ymin, xmax, ymin, xmax, ymax, xmin, ymax);\n }\n outArrays[key] = data;\n }\n\n outUniforms.num_features = sources.length;\n return { uniforms: outUniforms, uniformArrays: outArrays };\n}\n\n/**\n * Turns a compute pass into the parameters of one GPU dispatch. Pure: it reads `layers` and runs\n * nothing. With `iterate: 'all'`, pass the feature index as `iterateIndex` for each dispatch (see\n * {@link runCompute}). Throws when the pass's `dataRef` is not in `layers`.\n */\nexport function resolveComputeParams(block: ComputeSpec, layers: ComputeLayers, iterateIndex?: number): GpgpuPipelineParams {\n const collection = lookup(layers, block.dataRef);\n if (!collection) throw new Error(`compute: table \"${block.dataRef}\" is not loaded`);\n\n const params: GpgpuPipelineParams = {\n collection,\n variableMapping: block.attributes,\n wgslBody: joinWgsl(block.wglsFunction),\n };\n if (block.attributeArrays) params.attributeArrays = block.attributeArrays;\n if (block.attributeMatrices) params.attributeMatrices = block.attributeMatrices;\n if (block.uniformArrays) params.uniformArrays = block.uniformArrays;\n if (block.outputColumnName) params.resultField = block.outputColumnName;\n if (block.outputColumns) params.outputColumns = block.outputColumns;\n\n const iterate = findIterateSource(block);\n if (iterate?.mode === 'batched') {\n const sources = lookup(layers, iterate.layer)?.features ?? [];\n const packed = buildBatchedUniforms(block.uniforms, block.uniformMatrices, sources);\n // Entries that do not iterate resolve as they would without iteration.\n const single = resolveUniforms(notBatched(block.uniforms), layers) ?? {};\n const matrices = resolveUniformMatrices(notBatched(block.uniformMatrices), layers);\n params.uniforms = { ...single, ...packed.uniforms };\n params.uniformArrays = { ...(params.uniformArrays ?? {}), ...packed.uniformArrays };\n if (matrices && Object.keys(matrices).length > 0) params.uniformMatrices = matrices;\n return params;\n }\n\n const index = iterate?.mode === 'all' ? iterateIndex : undefined;\n const uniforms = resolveUniforms(block.uniforms, layers, index);\n const matrices = resolveUniformMatrices(block.uniformMatrices, layers, index);\n if (uniforms) params.uniforms = uniforms;\n if (matrices) params.uniformMatrices = matrices;\n return params;\n}\n\nfunction notBatched<T>(entries: Record<string, T> | undefined): Record<string, T> | undefined {\n if (!entries) return undefined;\n return Object.fromEntries(Object.entries(entries).filter(([, v]) => !(isFromFeature(v) && v.fromFeature.iterate === 'batched')));\n}\n\nfunction outputColumns(block: ComputeSpec): string[] {\n return block.outputColumns ?? (block.outputColumnName ? [block.outputColumnName] : []);\n}\n\n/**\n * Runs a compute pass. Without iteration, or with `batched`, that is one dispatch. With `all` it is\n * one dispatch per feature of the iterated layer, and each output column holds the sum over them.\n */\nexport async function runCompute(block: ComputeSpec, layers: ComputeLayers, run: ComputeRunner): Promise<FeatureCollection> {\n const iterate = findIterateSource(block);\n if (iterate?.mode !== 'all') return run(resolveComputeParams(block, layers));\n\n const target = lookup(layers, block.dataRef);\n if (!target) throw new Error(`compute: table \"${block.dataRef}\" is not loaded`);\n const columns = outputColumns(block);\n const summed: FeatureCollection = structuredClone(target);\n for (const f of summed.features) {\n const props = (f.properties ??= {}) as Record<string, unknown>;\n const compute = (props.compute ??= {}) as Record<string, number>;\n for (const col of columns) compute[col] = 0;\n }\n\n const count = lookup(layers, iterate.layer)?.features?.length ?? 0;\n for (let i = 0; i < count; i++) {\n const step = await run({ ...resolveComputeParams(block, layers, i), collection: summed });\n summed.features.forEach((f, j) => {\n const dst = (f.properties as Record<string, unknown> | null)?.compute as Record<string, number> | undefined;\n const src = (step.features[j]?.properties as Record<string, unknown> | null)?.compute as Record<string, unknown> | undefined;\n if (!dst || !src) return;\n for (const col of columns) {\n const inc = Number(src[col]);\n if (Number.isFinite(inc)) dst[col] += inc;\n }\n });\n }\n return summed;\n}\n","import { ComputeAdapter, ComputeSpec } from '@urban-toolkit/the-urban-grammar';\nimport { AutkDb } from '@urban-toolkit/autk-db';\nimport { AutkComputeEngine } from '@urban-toolkit/autk-compute';\nimport { FeatureCollection } from 'geojson';\nimport { ComputeCache } from '../types';\nimport { computeLayerNames, runCompute } from '../compute-params';\n\nexport function createComputeAdapter(cache?: ComputeCache): ComputeAdapter {\n\n return {\n async resolveCompute(context: AutkDb | undefined, spec: ComputeSpec): Promise<AutkDb | undefined> {\n if(context){\n // A table an earlier compute pass wrote is read from the cache, so passes chain.\n // Only the pass's own table must load; a `fromFeature` table that cannot\n // falls back to the directive's `default`.\n const layers: Record<string, FeatureCollection | undefined> = {};\n for (const name of computeLayerNames(spec)) {\n const cached = cache?.get(name);\n if (cached) layers[name] = cached;\n else if (name === spec.dataRef) layers[name] = await context.getLayer(name);\n else {\n try { layers[name] = await context.getLayer(name); }\n catch { layers[name] = undefined; }\n }\n }\n\n const engine = new AutkComputeEngine();\n const result = await runCompute(spec, layers, params => engine.gpgpuPipeline(params));\n\n if (cache) cache.set(spec.dataRef, result);\n\n return context;\n }\n }\n }\n}\n","import type { UrbanSpec } from '@urban-toolkit/the-urban-grammar';\nimport type { AutkMap } from '@urban-toolkit/autk-map';\nimport type { AutkPlot } from '@urban-toolkit/autk-plot';\nimport type { FeatureCollection } from 'geojson';\n\nexport type Targets = {\n compute?: string,\n db?: string,\n map?: string[] | string,\n plot?: string\n}\n\nexport type MapRegistry = Map<string, AutkMap>;\nexport type MapLayerIds = Map<string, string>; // dataRef → id of the layer that draws it in the map the MapRegistry holds for it\nexport type PlotRegistry = Map<string, AutkPlot>;\nexport type PlotMapLinks = Map<string, string>; // plotId (dataRef) → mapRef (dataRef of a map layer)\n\n/** A layer a map of the last run draws, as `AutkGrammar.mapLayer` finds it by its table's name. */\nexport interface GrammarMapLayer {\n /** The map that draws the layer. */\n map: AutkMap;\n /** The layer's id in that map: its `title`, else its `dataRef`. */\n layerId: string;\n}\nexport type GeoJsonCache = Map<string, FeatureCollection>;\nexport type ComputeCache = Map<string, FeatureCollection>;\n\nexport type AutkGrammarSpec = UrbanSpec;\n\n// Grammar-level interaction payloads — no autk internals leak through the public API\nexport interface GrammarPickingEvent {\n layerId: string;\n selection: number[];\n}\n\nexport interface GrammarPlotSelectionEvent {\n plotId: string;\n event: 'click' | 'brush' | 'brushX' | 'brushY';\n selection: number[];\n}\n\nexport type GrammarEventRecord = {\n 'map:picking': GrammarPickingEvent;\n 'plot:selection': GrammarPlotSelectionEvent;\n};\n\n// Self-contained typed emitter — does not import from autk packages\nexport class GrammarEventEmitter {\n private _listeners: Map<string, Set<(p: unknown) => void>> = new Map();\n\n on<K extends keyof GrammarEventRecord>(\n event: K,\n listener: (payload: GrammarEventRecord[K]) => void\n ): () => void {\n if (!this._listeners.has(event)) this._listeners.set(event, new Set());\n const bucket = this._listeners.get(event)!;\n bucket.add(listener as (p: unknown) => void);\n return () => bucket.delete(listener as (p: unknown) => void);\n }\n\n /** @internal */\n emit<K extends keyof GrammarEventRecord>(event: K, payload: GrammarEventRecord[K]): void {\n this._listeners.get(event)?.forEach(l => l(payload));\n }\n}\n\n","import { DataAdapter, MapAdapter, PlotAdapter, ComputeAdapter, IEngine, UrbanSpec, createEngine } from \"@urban-toolkit/the-urban-grammar\";\nimport { AutkDb, DEFAULT_WORKSPACE_COORDINATE_FORMAT } from \"@urban-toolkit/autk-db\";\nimport { MapEvent } from \"@urban-toolkit/autk-map\";\nimport type { AutkMap } from \"@urban-toolkit/autk-map\";\nimport type { MapEventData } from \"@urban-toolkit/autk-map\";\nimport { PlotEvent } from \"@urban-toolkit/autk-plot\";\nimport type { PlotEventData } from \"@urban-toolkit/autk-plot\";\nimport { FeatureCollection } from \"geojson\";\nimport { createDataAdapter } from \"./adapters/data\";\nimport { createMapAdapter } from \"./adapters/map\";\nimport { createPlotAdapter } from \"./adapters/plot\";\nimport { createComputeAdapter } from \"./adapters/compute\";\nimport { Targets, MapRegistry, MapLayerIds, PlotRegistry, PlotMapLinks, GeoJsonCache, ComputeCache, GrammarEventEmitter } from \"./types\";\nimport type { GrammarMapLayer, GrammarPlotSelectionEvent } from \"./types\";\n\nexport class AutkGrammar {\n private dataAdapter?: DataAdapter;\n private mapAdapter?: MapAdapter;\n private plotAdapter?: PlotAdapter;\n private computeAdapter?: ComputeAdapter;\n private grammarEngine?: IEngine;\n private _computeCache: ComputeCache = new Map();\n private _data: Record<string, Promise<FeatureCollection>> = {};\n private _mapRegistry: MapRegistry = new Map();\n private _mapLayerIds: MapLayerIds = new Map();\n private _maps: AutkMap[] = [];\n private _plotRegistry: PlotRegistry = new Map();\n private _fwdCleanups: Array<() => void> = [];\n private _plotMapLinks: PlotMapLinks = new Map();\n\n readonly interactions = new GrammarEventEmitter();\n\n constructor(targets?: Targets) {\n const cache: GeoJsonCache = new Map();\n this.dataAdapter = createDataAdapter(targets, cache);\n this.mapAdapter = createMapAdapter(targets, this._mapRegistry, this._computeCache, this._maps, this._mapLayerIds);\n this.plotAdapter = createPlotAdapter(targets, this._mapRegistry, this._plotRegistry, this._plotMapLinks, cache, this._mapLayerIds);\n this.computeAdapter = createComputeAdapter(this._computeCache);\n }\n\n /**\n * The coordinate reference system used internally by the autk workspace.\n *\n * Input data is expected in EPSG:4326 (WGS84) by default and is transformed\n * to this CRS on load. Consumers that prepare data for injection (e.g. by\n * serialising a GeoDataFrame) can read this value and reproject accordingly\n * instead of hard-coding a CRS string.\n */\n get workspaceCrs(): string {\n return DEFAULT_WORKSPACE_COORDINATE_FORMAT;\n }\n\n get data(): Record<string, Promise<FeatureCollection>> {\n return this._data;\n }\n\n /**\n * The maps the last {@link run} drew, one per `map` entry of the spec, in order.\n *\n * Each map draws on demand: one frame once its layers are loaded, then one each\n * time it changes. Between frames a map canvas can read back empty, so to read a\n * map's pixels (for example with `canvas.toDataURL()`), call its `requestRender()`\n * and read in a `requestAnimationFrame` callback registered after that call.\n */\n get maps(): readonly AutkMap[] {\n return this._maps;\n }\n\n /**\n * The layer a map of the last {@link run} draws for a table, found by the table's name (a layer's `dataRef`):\n * the map that draws it, and the layer's id in that map, which is its `title`, else its `dataRef`.\n * `undefined` when no map draws the table. When several layers draw it, the last one.\n *\n * @example\n * const layer = grammar.mapLayer('buildings');\n * layer?.map.updateRenderInfo(layer.layerId, { opacity: 0.5 });\n */\n mapLayer(dataRef: string): GrammarMapLayer | undefined {\n const map = this._mapRegistry.get(dataRef);\n return map ? { map, layerId: this._mapLayerIds.get(dataRef) ?? dataRef } : undefined;\n }\n\n async run(spec: UrbanSpec) {\n if(!this.dataAdapter)\n throw new Error('Database adapter not initialized. Please call the constructor first.');\n\n if(!this.mapAdapter)\n throw new Error('Map engine not initialized. Please call the constructor first.');\n\n if(!this.plotAdapter)\n throw new Error('Plot adapter not initialized. Please call the constructor first.');\n\n if(!this.computeAdapter)\n throw new Error('Compute adapter not initialized. Please call the constructor first.');\n\n this._mapRegistry.clear();\n this._mapLayerIds.clear();\n this._maps.length = 0;\n this._plotRegistry.clear();\n this._plotMapLinks.clear();\n this._computeCache.clear();\n\n this.grammarEngine = createEngine({\n spec,\n adapters: {\n db: this.dataAdapter,\n map: this.mapAdapter,\n plot: this.plotAdapter,\n compute: this.computeAdapter\n }\n });\n\n await this.grammarEngine.run();\n this._rewireInteractions();\n\n const db = this.grammarEngine.context as AutkDb | undefined;\n if (!db) {\n console.warn('Grammar engine produced no data context.');\n this._data = {};\n return;\n }\n\n const dataObj: Record<string, Promise<FeatureCollection>> = {};\n for (const table of db.getLayersMetadata()) {\n Object.defineProperty(dataObj, table.name, {\n get: () => {\n const computed = this._computeCache.get(table.name);\n return computed ? Promise.resolve(computed) : db.getLayer(table.name);\n },\n enumerable: true,\n configurable: true,\n });\n }\n this._data = dataObj;\n }\n\n /**\n * Highlights features on the map layer that draws the table `dataRef` (see {@link mapLayer}).\n * If that layer is linked to a plot via `mapRef`, the plot selection is updated too.\n */\n highlightOnMap(dataRef: string, featureIds: number[]): void {\n const layer = this.mapLayer(dataRef);\n layer?.map.setHighlightedIds(layer.layerId, featureIds);\n for (const [plotId, mapRef] of this._plotMapLinks) {\n if (mapRef === dataRef) this._plotRegistry.get(plotId)?.setSelection(featureIds);\n }\n }\n\n /**\n * Clears highlighted features on the map layer that draws the table `dataRef` (see {@link mapLayer}).\n * If that layer is linked to a plot via `mapRef`, the plot selection is cleared too.\n */\n clearHighlightOnMap(dataRef: string): void {\n const layer = this.mapLayer(dataRef);\n layer?.map.clearHighlightedIds(layer.layerId);\n for (const [plotId, mapRef] of this._plotMapLinks) {\n if (mapRef === dataRef) this._plotRegistry.get(plotId)?.setSelection([]);\n }\n }\n\n /**\n * Clears the selection on the plot identified by `plotId` (its dataRef).\n * If that plot is linked to a map via `mapRef`, the map highlight is cleared too.\n */\n clearHighlightOnPlot(plotId: string): void {\n this._plotRegistry.get(plotId)?.setSelection([]);\n const mapRef = this._plotMapLinks.get(plotId);\n const layer = mapRef ? this.mapLayer(mapRef) : undefined;\n layer?.map.clearHighlightedIds(layer.layerId);\n }\n\n /**\n * Applies a selection to the plot identified by `plotId` (its dataRef).\n * If that plot is linked to a map via `mapRef`, the map highlight is updated too.\n */\n setPlotSelection(plotId: string, featureIds: number[]): void {\n this._plotRegistry.get(plotId)?.setSelection(featureIds);\n const mapRef = this._plotMapLinks.get(plotId);\n const layer = mapRef ? this.mapLayer(mapRef) : undefined;\n layer?.map.setHighlightedIds(layer.layerId, featureIds);\n }\n\n private _rewireInteractions(): void {\n for (const cleanup of this._fwdCleanups) cleanup();\n this._fwdCleanups = [];\n\n // Wire each unique map → grammar bus\n // Multiple layerRefs can share one AutkMap instance; deduplicate to avoid double-subscription\n const seenMaps = new Set<AutkMap>();\n for (const [layerId, map] of this._mapRegistry) {\n if (seenMaps.has(map)) continue;\n seenMaps.add(map);\n const handler = ({ selection }: MapEventData) => {\n this.interactions.emit('map:picking', { layerId, selection });\n };\n map.events.on(MapEvent.PICKING, handler);\n this._fwdCleanups.push(() => map.events.off(MapEvent.PICKING, handler));\n }\n\n // Wire each plot → grammar bus (all four event types)\n for (const [plotId, plot] of this._plotRegistry) {\n for (const ev of [PlotEvent.CLICK, PlotEvent.BRUSH, PlotEvent.BRUSH_X, PlotEvent.BRUSH_Y] as const) {\n const handler = ({ selection }: PlotEventData) => {\n this.interactions.emit('plot:selection', {\n plotId,\n event: ev as GrammarPlotSelectionEvent['event'],\n selection,\n });\n };\n plot.events.on(ev, handler);\n this._fwdCleanups.push(() => plot.events.off(ev, handler));\n }\n }\n }\n}\n"],"names":["P","e","_","S","t","s","E","i","R","c","n","A","queryAreaOf","spec","queryArea","refuse","message","box","value","west","south","east","north","toLoadOsmParams","autoLoadLayers","rest","crsAdvice","coordinateFormat","extentOf","collection","minX","minY","maxX","maxY","visitPositions","x","y","inner","visitGeometry","geometry","feature","createDataAdapter","targets","cache","print","db","div","tables","table","context","AutkDb","type","rest_spec","geojsonSpec","geojsonData","loadSpec","readAsDegrees","extent","err","bbox","WORLD_EXTENT","DEFAULT_WORKSPACE_COORDINATE_FORMAT","bboxErr","hm","jn","updated","layerIdOf","layerRef","checkLayerIds","index","ids","id","HEX_COLOR","hexColor","key","layerId","ColorMap","styleRenderInfo","renderInfo","colorsByValue","bandValues","band","values","v","rasterScaleDomain","config","center","reverse","range","domain","reach","finite","centered","vectorScaleDomain","checkColorMapRange","low","high","buildDomainSpec","normalization","colorMapDomain","ColorMapDomainStrategy","NormalizationMode","valueAtPath","obj","path","acc","setValueAtPath","keys","result","current","rasterBand","getFnv","bands","b","createMapAdapter","registry","computeCache","maps","layerIds","loadLayers","map","tableToTypeMap","name","rawData","data","f","style","catchAllCategory","thematicData","effectiveDomain","allowed","props","val","rasterTransfer","rasterScale","colormapConfig","ColorMapInterpolator","property","canvas","AutkMap","grammarMarkToPlotType","mark","createPlotAdapter","plotRegistry","plotMapLinks","geojson","events","plot","AutkPlot","MapEvent","selection","event","STORAGE_BUFFER_BINDING_SIZE","SCALAR_BYTES","BOX_BYTES","joinWgsl","body","isFromFeature","lookup","layers","item","directives","block","out","cfg","computeLayerNames","d","findIterateSource","iterate","layer","resolveDirective","iterateIndex","ff","resolveUniforms","uniforms","num","resolveUniformMatrices","matrices","resolved","cols","isFiniteValue","isBatched","batchedBytesPerFeature","maxBatchedFeatures","bindingSize","bytes","buildBatchedUniforms","sources","outUniforms","outArrays","required","before","p","limit","fallback","ring","xmin","ymin","xmax","ymax","coord","resolveComputeParams","params","packed","single","notBatched","entries","outputColumns","runCompute","run","target","columns","summed","compute","col","count","step","j","dst","src","inc","createComputeAdapter","cached","engine","AutkComputeEngine","GrammarEventEmitter","listener","bucket","payload","l","AutkGrammar","dataRef","createEngine","dataObj","computed","featureIds","plotId","mapRef","cleanup","seenMaps","handler","ev","PlotEvent"],"mappings":";;;;;AAAA,SAASA,GAAEC,GAAG;AACZ,QAAM,EAAE,MAAMC,GAAG,UAAUC,EAAC,IAAKF;AACjC,MAAIG;AACJ,iBAAeC,IAAI;AACjB,QAAIC;AACJ,QAAIJ,EAAE;AACJ,iBAAWK,KAAKL,EAAE;AAChB,QAAAI,IAAI,MAAMH,EAAE,GAAG,cAAcG,GAAGC,CAAC;AACrC,QAAIL,EAAE;AACJ,iBAAWK,KAAKL,EAAE;AAChB,QAAAI,IAAI,MAAMH,EAAE,QAAQ,eAAeG,GAAGC,CAAC;AAC3C,QAAIL,EAAE;AACJ,UAAI,MAAM,QAAQA,EAAE,GAAG;AACrB,iBAASK,IAAI,GAAGA,IAAIL,EAAE,IAAI,QAAQK,KAAK;AACrC,cAAI,IAAIL,EAAE,IAAIK,CAAC;AACf,gBAAMJ,EAAE,IAAI,WAAWG,GAAG,GAAGC,CAAC;AAAA,QAChC;AAAA;AAEA,cAAMJ,EAAE,IAAI,WAAWG,GAAGJ,EAAE,GAAG;AACnC,QAAIA,EAAE;AACJ,UAAI,MAAM,QAAQA,EAAE,IAAI;AACtB,mBAAWK,KAAKL,EAAE;AAChB,gBAAMC,EAAE,KAAK,YAAYG,GAAGC,CAAC;AAAA;AAE/B,cAAMJ,EAAE,KAAK,YAAYG,GAAGJ,EAAE,IAAI;AACtC,IAAAE,IAAIE;AAAA,EACN;AACA,WAASE,EAAEF,GAAG;AACZ,WAAO,QAAQ,IAAI,kBAAkBA,CAA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eof module<"u"?w(exports,require("@urban-toolkit/autk-db"),require("@urban-toolkit/autk-map"),require("@urban-toolkit/autk-plot"),require("@urban-toolkit/autk-core"),require("@urban-toolkit/autk-compute")):typeof define=="function"&&define.amd?define(["exports","@urban-toolkit/autk-db","@urban-toolkit/autk-map","@urban-toolkit/autk-plot","@urban-toolkit/autk-core","@urban-toolkit/autk-compute"],w):(m=typeof globalThis<"u"?globalThis:m||self,w(m["autk-grammar"]={},m.autkDb,m.autkMap,m.autkPlot,m.autkCore,m.autkCompute))})(this,(function(m,w,N,C,_,at){"use strict";function $(t){const{spec:e,adapters:r}=t;let o;async function i(){let n;if(e.data)for(const s of e.data)n=await r.db.resolveSource(n,s);if(e.compute)for(const s of e.compute)n=await r.compute.resolveCompute(n,s);if(e.map)if(Array.isArray(e.map))for(let s=0;s<e.map.length;s++){let c=e.map[s];await r.map.resolveMap(n,c,s)}else await r.map.resolveMap(n,e.map);if(e.plot)if(Array.isArray(e.plot))for(const s of e.plot)await r.plot.resolvePlot(n,s);else await r.plot.resolvePlot(n,e.plot);o=n}function a(n){return console.log("Spec to update",n),new Promise(s=>{s()})}function l(){console.log("Function not implemented yet")}return{run:i,updatedSpec:a,destroy:l,get context(){return o}}}var x=(t=>(t.CAT_ACCENT="schemeAccent",t.CAT_DARK2="schemeDark2",t.CAT_CATEGORY10="schemeCategory10",t.CAT_OBSERVABLE10="schemeObservable10",t.CAT_PAIRED="schemePaired",t.CAT_PASTEL1="schemePastel1",t.CAT_PASTEL2="schemePastel2",t.CAT_SET1="schemeSet1",t.CAT_SET2="schemeSet2",t.CAT_SET3="schemeSet3",t.CAT_TABLEAU10="schemeTableau10",t.SEQ_REDS="interpolateReds",t.SEQ_BLUES="interpolateBlues",t.SEQ_GREENS="interpolateGreens",t.SEQ_GREYS="interpolateGreys",t.SEQ_ORANGES="interpolateOranges",t.SEQ_PURPLES="interpolatePurples",t.SEQ_TURBO="interpolateTurbo",t.SEQ_VIRIDIS="interpolateViridis",t.SEQ_INFERNO="interpolateInferno",t.SEQ_MAGMA="interpolateMagma",t.SEQ_PLASMA="interpolatePlasma",t.SEQ_CIVIDIS="interpolateCividis",t.SEQ_WARM="interpolateWarm",t.SEQ_COOL="interpolateCool",t.SEQ_CUBEHELIX_DEFAULT="interpolateCubehelixDefault",t.SEQ_BU_GN="interpolateBuGn",t.SEQ_BU_PU="interpolateBuPu",t.SEQ_GN_BU="interpolateGnBu",t.SEQ_OR_RD="interpolateOrRd",t.SEQ_PU_BU_GN="interpolatePuBuGn",t.SEQ_PU_BU="interpolatePuBu",t.SEQ_PU_RD="interpolatePuRd",t.SEQ_RD_PU="interpolateRdPu",t.SEQ_YL_GN_BU="interpolateYlGnBu",t.SEQ_YL_GN="interpolateYlGn",t.SEQ_YL_OR_BR="interpolateYlOrBr",t.SEQ_YL_OR_RD="interpolateYlOrRd",t.DIV_BR_BG="interpolateBrBG",t.DIV_PR_GN="interpolatePRGn",t.DIV_PI_YG="interpolatePiYG",t.DIV_PU_OR="interpolatePuOr",t.DIV_RED_BLUE="interpolateRdBu",t.DIV_RED_GREY="interpolateRdGy",t.DIV_RED_YELLOW_BLUE="interpolateRdYlBu",t.DIV_RED_YELLOW_GREEN="interpolateRdYlGn",t.DIV_SPECTRAL="interpolateSpectral",t))(x||{}),F=(t=>(t.MIN_MAX="minMax",t.PERCENTILE="percentile",t))(F||{});function nt(t){const{queryArea:e}=t;if(e.bbox===void 0)return{geocodeArea:e.geocodeArea,areas:e.areas};const r=s=>new Error(`OSM source "${t.outputTableName}": ${s}`);if(e.geocodeArea!==void 0||e.areas!==void 0)throw r("queryArea takes either bbox or geocodeArea with areas, not both.");const o=e.bbox;if(!Array.isArray(o)||o.length!==4||!o.every(s=>typeof s=="number"&&Number.isFinite(s)))throw r("queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.");const[i,a,l,n]=e.bbox;if(Math.abs(i)>180||Math.abs(l)>180)throw r("queryArea.bbox west and east must be longitudes from -180 to 180.");if(Math.abs(a)>90||Math.abs(n)>90)throw r("queryArea.bbox south and north must be latitudes from -90 to 90.");if(i>=l)throw r(`queryArea.bbox west (${i}) must be less than east (${l}); a box across the antimeridian is not supported.`);if(a>=n)throw r(`queryArea.bbox south (${a}) must be less than north (${n}).`);return{bbox:[i,a,l,n]}}function it(t){const{autoLoadLayers:e,...r}=t;return{...r,queryArea:nt(t),autoLoadLayers:{layers:e?.layers??[]}}}function st(t,e){function r(o,i){if(!i||!i.db)return;const a=document.getElementById(i.db);if(a){const l=o.getTablesMetadata();a.innerHTML+="<ul>";for(const n of l)a.innerHTML+=`<li>${n.name}: (${n.source}, ${n.type}) </li>`;a.innerHTML+="</ul>",a.innerHTML+=`<p>Number of tables: ${l.length}</p>`}}return{async resolveSource(o,i){let a=o;a||(a=new w.AutkDb,await a.init());let{type:l,...n}=i;switch(l){case"osm":return await a.loadOsm(it(n)),r(a,t),a;case"csv":return await a.loadCsv(n),r(a,t),a;case"json":return await a.loadJson(n),r(a,t),a;case"geojson":{const s=n;let c;s.geojsonFileUrl?c=await(await fetch(s.geojsonFileUrl)).json():c=s.geojsonObject,e&&c&&e.set(s.outputTableName,c);const u=c?(()=>{const f={...s,geojsonObject:c};return delete f.geojsonFileUrl,f})():s;try{await a.loadGeojson(u)}catch(f){const p=u.coordinateFormat?`coordinateFormat is set to "${u.coordinateFormat}"`:"no coordinateFormat was specified — defaulting to EPSG:4326 (WGS84 per RFC 7946)";throw new Error(`Failed to load GeoJSON layer "${u.outputTableName}": ${f instanceof Error?f.message:String(f)}. ${p}. Verify that coordinateFormat matches the actual CRS of the input data.`)}try{const f=await a.getBoundingBoxFromLayer(u.outputTableName),p=25e6;if(!isFinite(f.minLon)||!isFinite(f.minLat)||!isFinite(f.maxLon)||!isFinite(f.maxLat)||Math.abs(f.minLon)>p||Math.abs(f.maxLon)>p||Math.abs(f.minLat)>p||Math.abs(f.maxLat)>p)throw new Error(`Geometry bounding box after transform is invalid for layer "${u.outputTableName}" (bbox: [${f.minLon}, ${f.minLat}, ${f.maxLon}, ${f.maxLat}]). Verify that coordinateFormat matches the actual CRS of the input data. The workspace uses ${w.DEFAULT_WORKSPACE_COORDINATE_FORMAT}; input is expected in EPSG:4326 by default.`)}catch(f){if(f instanceof Error&&f.message.includes("bounding box after transform"))throw f}return r(a,t),a}case"heatmap":{const s=n;return await a.buildHeatmap({tableJoinName:s.tableJoinName,near:{distance:s.near.distance},outputTableName:s.outputTableName,grid:s.grid,...s.groupBy&&{groupBy:s.groupBy}}),r(a,t),a}case"join":{const s=n;if(await a.spatialQuery({tableRootName:s.tableRootName,tableJoinName:s.tableJoinName,...s.near&&{near:s.near},...s.groupBy&&{groupBy:s.groupBy}}),e){const c=await a.getLayer(s.tableRootName);e.set(s.tableRootName,c)}return r(a,t),a}default:return}}}}function B(t){return typeof t.title=="string"&&t.title!==""?t.title:t.dataRef}function lt(t,e){const r=new Set;for(const o of t.layerRefs){const i=B(o);if(r.has(i))throw new Error(`Map ${e} draws two layers with the id "${i}". A layer's id is its title, else its dataRef: give each layer of a map its own title.`);r.add(i)}}const ut=/^#[0-9a-fA-F]{6}$/;function Q(t,e,r){if(!ut.test(t))throw new Error(`Layer "${r}": ${e} must be a color written #rrggbb, not "${t}".`);return _.ColorMap.hexToRgb(t)}function ct(t,e){const r={};return t.color!=null&&(r.color=Q(t.color,"color",e)),t.stroke===!1?r.showBorders=!1:t.stroke!=null&&(r.strokeColor=Q(t.stroke,"stroke",e)),t.width!=null&&(r.polylinesWidth=t.width),r}function ft(t,e){return t.isColorMap!=null?t.isColorMap:e==="raster"?t.colorMapInterpolator!=null||t.colorMapCenter!=null||t.colorMapReverse===!0:t.color!=null?!1:t.colorMapInterpolator!=null||t.getFnv!=null}function pt(t,e){const r=t.features?.[0]?.properties?.[e];return r instanceof Float32Array?r:ArrayBuffer.isView(r)&&!(r instanceof DataView)||Array.isArray(r)?Float32Array.from(r,o=>Number.isFinite(Number(o))?Number(o):NaN):null}function mt(t,e,r,o){if(_.ColorMap.isCategorical(e.interpolator))return;let i=0,a=0;for(let s=0;s<t.length;s++){const c=t[s];Number.isFinite(c)&&(a++,r!=null&&(i=Math.max(i,Math.abs(c-r))))}const l=r!=null&&i>0;if(a===0||!l&&o!==!0)return;const n=l&&r!=null?[r-i,r,r+i]:_.ColorMap.resolveDomainFromData(t,e);return o===!0?[...n].reverse():n}function dt(t,e){return e&&e.length>0?{type:_.ColorMapDomainStrategy.USER,params:e}:t?.mode===F.PERCENTILE?t.lowerPercentile!==void 0||t.upperPercentile!==void 0?{type:_.ColorMapDomainStrategy.PERCENTILE,params:[t.lowerPercentile??0,t.upperPercentile??100]}:{type:_.ColorMapDomainStrategy.PERCENTILE}:{type:_.ColorMapDomainStrategy.MIN_MAX}}function ht(t,e){return e.split(".").reduce((r,o)=>{if(!(r==null||typeof r!="object"))return r[o]},t)}function yt(t,e,r){const o=e.split("."),i={...t};let a=i;for(let l=0;l<o.length-1;l++)a[o[l]]={...a[o[l]]??{}},a=a[o[l]];return a[o[o.length-1]]=r,i}function gt(t,e){const o=t.features?.[0]?.properties?.bands??[];return o.find(a=>a.id===e||a.label===e?.replace(/\./g,"_"))?.id??o[0]?.id??e??""}function bt(t,e,r,o,i){async function a(l,n,s){let c={};for(const u of n.getTablesMetadata())u.type!==void 0&&(c[u.name]=u.type);for(const u of s.layerRefs){const f=u.dataRef,p=B(u),d=c[f],h=u.getFnv,y=r?.get(f)??await n.getLayer(f),g=d==="raster"?y:{...y,features:(y.features??[]).filter(b=>b.geometry!=null)},R=d==="raster"?gt(g,h):"";d==="raster"?l.loadCollection(p,{collection:g,type:"raster",property:R}):l.loadCollection(p,{collection:g,type:d}),u.opacity!=null&&l.updateRenderInfo(p,{opacity:u.opacity});const S=ct(u,p);Object.keys(S).length>0&&l.updateRenderInfo(p,S),ft(u,d)&&l.updateRenderInfo(p,{isColorMap:!0}),u.isPick&&l.updateRenderInfo(p,{isPick:!0}),u.isSkip&&l.updateRenderInfo(p,{isSkip:!0});const{catchAllCategory:A,colorMapDomain:v}=u;let tt=g,et=v;if(h&&A&&v?.length){const b=new Set(v);tt={...g,features:g.features.map(M=>{const L=M.properties,U=ht(L,h);return U==null||!b.has(String(U))?{...M,properties:yt(L,h,A)}:M})},et=b.has(A)?v:[...v,A]}const rt=d==="raster"&&u.transferFunction!=null;rt&&l.layerManager.searchByLayerId(p)?.setTransferFunction?.(u.transferFunction);const ot=d==="raster"&&(u.colorMapCenter!=null||u.colorMapReverse===!0);if(u.colorMapInterpolator||ot){const b={interpolator:u.colorMapInterpolator??l.layerManager.searchByLayerId(p)?.layerRenderInfo.colormap.config.interpolator??_.ColorMapInterpolator.SEQ_REDS,domainSpec:dt(u.normalization,et)},M=ot?pt(g,R):null,L=M?mt(M,b,u.colorMapCenter,u.colorMapReverse):void 0;L&&(b.domainSpec={type:_.ColorMapDomainStrategy.USER,params:L}),l.updateColorMap(p,{colorMap:b})}else rt&&l.updateColorMap(p,{colorMap:{}});if(h&&d!=="raster"){const b=h.startsWith("properties.")?h:`properties.${h}`;l.updateThematic(p,{collection:tt,property:b})}}}return{async resolveMap(l,n,s=0){if(t&&t.map&&l){lt(n,s);let c;if(Array.isArray(t.map)?c=document.getElementById(t.map[s]):c=document.getElementById(t.map),!c)throw new Error("Could not find rendering target for map: "+t.map);if(!(c instanceof HTMLCanvasElement))throw new Error("Target for map is not a canvas: "+t.map);const u=new N.AutkMap(c);n.style&&u.style.setPredefinedStyle(n.style),await u.init(),await a(u,l,n);for(const f of n.layerRefs)e?.set(f.dataRef,u),i?.set(f.dataRef,B(f));o&&(o[s]=u),u.draw()}}}}function _t(t){return{scatter:"scatterplot",bar:"barchart",line:"linechart",linechart:"linechart","parallel-coordinates":"parallel-coordinates",table:"table",heatmatrix:"heatmatrix"}[t]}function Et(t,e,r,o,i,a){return{async resolvePlot(l,n){if(!t||!t.plot)return;const s=document.getElementById(t.plot);if(!s)throw new Error(`Could not find plot target: ${t.plot}`);const c=l;if(!c)throw new Error("No data context available for plot.");const u=i?.get(n.dataRef)??await c.getLayer(n.dataRef),f=n.events??[],p=new C.AutkPlot(s,{type:_t(n.mark),collection:u,attributes:{axis:n.axis,...n.color&&{color:n.color}},labels:{axis:n.axis,title:n.title},events:f,...n.width&&{width:n.width},...n.height&&{height:n.height},...n.margins&&{margins:n.margins},...n.transform&&{transform:n.transform}});if(r?.set(n.dataRef,p),n.mapRef&&o?.set(n.dataRef,n.mapRef),n.mapRef&&e){const d=e.get(n.mapRef),h=a?.get(n.mapRef)??n.mapRef;if(d){d.updateRenderInfo(h,{isPick:!0}),d.events.on(N.MapEvent.PICKING,({selection:y})=>{p.setSelection(y)});for(const y of f)p.events.on(y,({selection:g})=>{d.setHighlightedIds(h,g)})}}}}}const T=134217728,At=4,wt=32;function k(t){return Array.isArray(t)?t.join(`
2
- `):t}function E(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.fromFeature=="object"&&t.fromFeature!==null}function I(t,e){return t instanceof Map?t.get(e):t[e]}function P(t,e){return e.split(".").reduce((r,o)=>{if(!(r==null||typeof r!="object"))return r[o]},t)}function V(t){const e=[];for(const r of[t.uniforms,t.uniformMatrices])for(const o of Object.values(r??{}))E(o)&&e.push(o);return e}function Y(t){return[...new Set([t.dataRef,...V(t).map(e=>e.fromFeature.layer)])]}function O(t){for(const e of V(t)){const{iterate:r,layer:o}=e.fromFeature;if(r==="all"||r==="batched")return{mode:r,layer:o}}return null}function H(t,e,r){const o=t.fromFeature,i=r!==void 0&&o.iterate==="all"?r:o.index??0,a=I(e,o.layer)?.features?.[i];return a?P(a,o.path):void 0}function D(t,e,r){if(!t)return;const o={};for(const[i,a]of Object.entries(t)){if(!E(a)){o[i]=a;continue}const l=Number(H(a,e,r)??NaN);Number.isFinite(l)?o[i]=l:typeof a.default=="number"&&(o[i]=a.default)}return o}function G(t,e,r){if(!t)return;const o={};for(const[i,a]of Object.entries(t)){if(!E(a)){o[i]=a;continue}const l=H(a,e,r),n=Array.isArray(l)?l:Array.isArray(a.default)?a.default:void 0;if(!n)continue;const s=a.cols??(Array.isArray(n[0])?n[0].length:0);s>0?o[i]={data:n,cols:s}:console.warn(`[autk-grammar] uniform matrix "${i}" has no column count; entry dropped`)}return o}function Rt(t){return t!=null&&!(typeof t=="number"&&!Number.isFinite(t))}function q(t){return E(t)&&t.fromFeature.iterate==="batched"}function W(t,e){return Object.values(e??{}).some(q)?wt:Object.values(t??{}).some(q)?At:0}function K(t,e,r=T){const o=W(t,e);return o>0?Math.floor(r/o):Number.POSITIVE_INFINITY}function X(t,e,r,o=T){const i={},a={},l=[];for(const s of[t,e])for(const c of Object.values(s??{}))E(c)&&c.fromFeature.iterate==="batched"&&c.fromFeature.required&&l.push(c.fromFeature.path);if(l.length>0){const s=r.length;r=r.filter(c=>l.every(u=>Rt(P(c,u)))),r.length<s&&console.info(`[autk-grammar] batched compute dropped ${s-r.length} feature(s) missing ${l.join(", ")}`)}const n=K(t,e,o);r.length>n&&(console.warn(`[autk-grammar] batched compute capped at ${n} features (got ${r.length}): its largest packed array takes ${W(t,e)} B per feature, and a storage buffer binding holds ${o} B`),r=r.slice(0,n));for(const[s,c]of Object.entries(t??{}))if(E(c)&&c.fromFeature.iterate==="batched"){const u=typeof c.default=="number"?c.default:void 0;a[s]=r.map(f=>{const p=Number(P(f,c.fromFeature.path)??u);return Number.isFinite(p)?p:0})}else typeof c=="number"&&(i[s]=c);for(const[s,c]of Object.entries(e??{})){if(!E(c)||c.fromFeature.iterate!=="batched")continue;const u=[];for(const f of r){const p=P(f,c.fromFeature.path);let d=1/0,h=1/0,y=-1/0,g=-1/0;if(Array.isArray(p))for(const R of p){if(!Array.isArray(R)||R.length<2)continue;const S=Number(R[0]),A=Number(R[1]);!Number.isFinite(S)||!Number.isFinite(A)||(d=Math.min(d,S),h=Math.min(h,A),y=Math.max(y,S),g=Math.max(g,A))}Number.isFinite(d)||(d=0,h=0,y=0,g=0),u.push(d,h,y,h,y,g,d,g)}a[s]=u}return i.num_features=r.length,{uniforms:i,uniformArrays:a}}function j(t,e,r){const o=I(e,t.dataRef);if(!o)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const i={collection:o,variableMapping:t.attributes,wgslBody:k(t.wglsFunction)};t.attributeArrays&&(i.attributeArrays=t.attributeArrays),t.attributeMatrices&&(i.attributeMatrices=t.attributeMatrices),t.uniformArrays&&(i.uniformArrays=t.uniformArrays),t.outputColumnName&&(i.resultField=t.outputColumnName),t.outputColumns&&(i.outputColumns=t.outputColumns);const a=O(t);if(a?.mode==="batched"){const c=I(e,a.layer)?.features??[],u=X(t.uniforms,t.uniformMatrices,c),f=D(J(t.uniforms),e)??{},p=G(J(t.uniformMatrices),e);return i.uniforms={...f,...u.uniforms},i.uniformArrays={...i.uniformArrays??{},...u.uniformArrays},p&&Object.keys(p).length>0&&(i.uniformMatrices=p),i}const l=a?.mode==="all"?r:void 0,n=D(t.uniforms,e,l),s=G(t.uniformMatrices,e,l);return n&&(i.uniforms=n),s&&(i.uniformMatrices=s),i}function J(t){if(t)return Object.fromEntries(Object.entries(t).filter(([,e])=>!(E(e)&&e.fromFeature.iterate==="batched")))}function St(t){return t.outputColumns??(t.outputColumnName?[t.outputColumnName]:[])}async function Z(t,e,r){const o=O(t);if(o?.mode!=="all")return r(j(t,e));const i=I(e,t.dataRef);if(!i)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const a=St(t),l=structuredClone(i);for(const s of l.features){const c=s.properties??={},u=c.compute??={};for(const f of a)u[f]=0}const n=I(e,o.layer)?.features?.length??0;for(let s=0;s<n;s++){const c=await r({...j(t,e,s),collection:l});l.features.forEach((u,f)=>{const p=u.properties?.compute,d=c.features[f]?.properties?.compute;if(!(!p||!d))for(const h of a){const y=Number(d[h]);Number.isFinite(y)&&(p[h]+=y)}})}return l}function Mt(t){return{async resolveCompute(e,r){if(e){const o={};for(const l of Y(r)){const n=t?.get(l);if(n)o[l]=n;else if(l===r.dataRef)o[l]=await e.getLayer(l);else try{o[l]=await e.getLayer(l)}catch{o[l]=void 0}}const i=new at.AutkComputeEngine,a=await Z(r,o,l=>i.gpgpuPipeline(l));return t&&t.set(r.dataRef,a),e}}}}class z{_listeners=new Map;on(e,r){this._listeners.has(e)||this._listeners.set(e,new Set);const o=this._listeners.get(e);return o.add(r),()=>o.delete(r)}emit(e,r){this._listeners.get(e)?.forEach(o=>o(r))}}class Ct{dataAdapter;mapAdapter;plotAdapter;computeAdapter;grammarEngine;_computeCache=new Map;_data={};_mapRegistry=new Map;_mapLayerIds=new Map;_maps=[];_plotRegistry=new Map;_fwdCleanups=[];_plotMapLinks=new Map;interactions=new z;constructor(e){const r=new Map;this.dataAdapter=st(e,r),this.mapAdapter=bt(e,this._mapRegistry,this._computeCache,this._maps,this._mapLayerIds),this.plotAdapter=Et(e,this._mapRegistry,this._plotRegistry,this._plotMapLinks,r,this._mapLayerIds),this.computeAdapter=Mt(this._computeCache)}get workspaceCrs(){return w.DEFAULT_WORKSPACE_COORDINATE_FORMAT}get data(){return this._data}get maps(){return this._maps}mapLayer(e){const r=this._mapRegistry.get(e);return r?{map:r,layerId:this._mapLayerIds.get(e)??e}:void 0}async run(e){if(!this.dataAdapter)throw new Error("Database adapter not initialized. Please call the constructor first.");if(!this.mapAdapter)throw new Error("Map engine not initialized. Please call the constructor first.");if(!this.plotAdapter)throw new Error("Plot adapter not initialized. Please call the constructor first.");if(!this.computeAdapter)throw new Error("Compute adapter not initialized. Please call the constructor first.");this._mapRegistry.clear(),this._mapLayerIds.clear(),this._maps.length=0,this._plotRegistry.clear(),this._plotMapLinks.clear(),this._computeCache.clear(),this.grammarEngine=$({spec:e,adapters:{db:this.dataAdapter,map:this.mapAdapter,plot:this.plotAdapter,compute:this.computeAdapter}}),await this.grammarEngine.run(),this._rewireInteractions();const r=this.grammarEngine.context;if(!r){console.warn("Grammar engine produced no data context."),this._data={};return}const o={};for(const i of r.getLayersMetadata())Object.defineProperty(o,i.name,{get:()=>{const a=this._computeCache.get(i.name);return a?Promise.resolve(a):r.getLayer(i.name)},enumerable:!0,configurable:!0});this._data=o}highlightOnMap(e,r){const o=this.mapLayer(e);o?.map.setHighlightedIds(o.layerId,r);for(const[i,a]of this._plotMapLinks)a===e&&this._plotRegistry.get(i)?.setSelection(r)}clearHighlightOnMap(e){const r=this.mapLayer(e);r?.map.clearHighlightedIds(r.layerId);for(const[o,i]of this._plotMapLinks)i===e&&this._plotRegistry.get(o)?.setSelection([])}clearHighlightOnPlot(e){this._plotRegistry.get(e)?.setSelection([]);const r=this._plotMapLinks.get(e),o=r?this.mapLayer(r):void 0;o?.map.clearHighlightedIds(o.layerId)}setPlotSelection(e,r){this._plotRegistry.get(e)?.setSelection(r);const o=this._plotMapLinks.get(e),i=o?this.mapLayer(o):void 0;i?.map.setHighlightedIds(i.layerId,r)}_rewireInteractions(){for(const r of this._fwdCleanups)r();this._fwdCleanups=[];const e=new Set;for(const[r,o]of this._mapRegistry){if(e.has(o))continue;e.add(o);const i=({selection:a})=>{this.interactions.emit("map:picking",{layerId:r,selection:a})};o.events.on(N.MapEvent.PICKING,i),this._fwdCleanups.push(()=>o.events.off(N.MapEvent.PICKING,i))}for(const[r,o]of this._plotRegistry)for(const i of[C.PlotEvent.CLICK,C.PlotEvent.BRUSH,C.PlotEvent.BRUSH_X,C.PlotEvent.BRUSH_Y]){const a=({selection:l})=>{this.interactions.emit("plot:selection",{plotId:r,event:i,selection:l})};o.events.on(i,a),this._fwdCleanups.push(()=>o.events.off(i,a))}}}m.AutkGrammar=Ct,m.ColorMapInterpolator=x,m.GrammarEventEmitter=z,m.NormalizationMode=F,m.STORAGE_BUFFER_BINDING_SIZE=T,m.buildBatchedUniforms=X,m.computeLayerNames=Y,m.createEngine=$,m.findIterateSource=O,m.isFromFeature=E,m.joinWgsl=k,m.maxBatchedFeatures=K,m.resolveComputeParams=j,m.resolveUniformMatrices=G,m.resolveUniforms=D,m.runCompute=Z,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(m,M){typeof exports=="object"&&typeof module<"u"?M(exports,require("@urban-toolkit/autk-db"),require("@urban-toolkit/autk-map"),require("@urban-toolkit/autk-plot"),require("@urban-toolkit/autk-core"),require("@urban-toolkit/autk-compute")):typeof define=="function"&&define.amd?define(["exports","@urban-toolkit/autk-db","@urban-toolkit/autk-map","@urban-toolkit/autk-plot","@urban-toolkit/autk-core","@urban-toolkit/autk-compute"],M):(m=typeof globalThis<"u"?globalThis:m||self,M(m["autk-grammar"]={},m.autkDb,m.autkMap,m.autkPlot,m.autkCore,m.autkCompute))})(this,(function(m,M,L,C,_,it){"use strict";function x(t){const{spec:e,adapters:r}=t;let o;async function i(){let a;if(e.data)for(const s of e.data)a=await r.db.resolveSource(a,s);if(e.compute)for(const s of e.compute)a=await r.compute.resolveCompute(a,s);if(e.map)if(Array.isArray(e.map))for(let s=0;s<e.map.length;s++){let u=e.map[s];await r.map.resolveMap(a,u,s)}else await r.map.resolveMap(a,e.map);if(e.plot)if(Array.isArray(e.plot))for(const s of e.plot)await r.plot.resolvePlot(a,s);else await r.plot.resolvePlot(a,e.plot);o=a}function n(a){return console.log("Spec to update",a),new Promise(s=>{s()})}function l(){console.log("Function not implemented yet")}return{run:i,updatedSpec:n,destroy:l,get context(){return o}}}var U=(t=>(t.CAT_ACCENT="schemeAccent",t.CAT_DARK2="schemeDark2",t.CAT_CATEGORY10="schemeCategory10",t.CAT_OBSERVABLE10="schemeObservable10",t.CAT_PAIRED="schemePaired",t.CAT_PASTEL1="schemePastel1",t.CAT_PASTEL2="schemePastel2",t.CAT_SET1="schemeSet1",t.CAT_SET2="schemeSet2",t.CAT_SET3="schemeSet3",t.CAT_TABLEAU10="schemeTableau10",t.SEQ_REDS="interpolateReds",t.SEQ_BLUES="interpolateBlues",t.SEQ_GREENS="interpolateGreens",t.SEQ_GREYS="interpolateGreys",t.SEQ_ORANGES="interpolateOranges",t.SEQ_PURPLES="interpolatePurples",t.SEQ_TURBO="interpolateTurbo",t.SEQ_VIRIDIS="interpolateViridis",t.SEQ_INFERNO="interpolateInferno",t.SEQ_MAGMA="interpolateMagma",t.SEQ_PLASMA="interpolatePlasma",t.SEQ_CIVIDIS="interpolateCividis",t.SEQ_WARM="interpolateWarm",t.SEQ_COOL="interpolateCool",t.SEQ_CUBEHELIX_DEFAULT="interpolateCubehelixDefault",t.SEQ_BU_GN="interpolateBuGn",t.SEQ_BU_PU="interpolateBuPu",t.SEQ_GN_BU="interpolateGnBu",t.SEQ_OR_RD="interpolateOrRd",t.SEQ_PU_BU_GN="interpolatePuBuGn",t.SEQ_PU_BU="interpolatePuBu",t.SEQ_PU_RD="interpolatePuRd",t.SEQ_RD_PU="interpolateRdPu",t.SEQ_YL_GN_BU="interpolateYlGnBu",t.SEQ_YL_GN="interpolateYlGn",t.SEQ_YL_OR_BR="interpolateYlOrBr",t.SEQ_YL_OR_RD="interpolateYlOrRd",t.DIV_BR_BG="interpolateBrBG",t.DIV_PR_GN="interpolatePRGn",t.DIV_PI_YG="interpolatePiYG",t.DIV_PU_OR="interpolatePuOr",t.DIV_RED_BLUE="interpolateRdBu",t.DIV_RED_GREY="interpolateRdGy",t.DIV_RED_YELLOW_BLUE="interpolateRdYlBu",t.DIV_RED_YELLOW_GREEN="interpolateRdYlGn",t.DIV_SPECTRAL="interpolateSpectral",t))(U||{}),T=(t=>(t.MIN_MAX="minMax",t.PERCENTILE="percentile",t))(T||{});function st(t){const{queryArea:e}=t;if(e.bbox===void 0)return{geocodeArea:e.geocodeArea,areas:e.areas};const r=s=>new Error(`OSM source "${t.outputTableName}": ${s}`);if(e.geocodeArea!==void 0||e.areas!==void 0)throw r("queryArea takes either bbox or geocodeArea with areas, not both.");const o=e.bbox;if(!Array.isArray(o)||o.length!==4||!o.every(s=>typeof s=="number"&&Number.isFinite(s)))throw r("queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.");const[i,n,l,a]=e.bbox;if(Math.abs(i)>180||Math.abs(l)>180)throw r("queryArea.bbox west and east must be longitudes from -180 to 180.");if(Math.abs(n)>90||Math.abs(a)>90)throw r("queryArea.bbox south and north must be latitudes from -90 to 90.");if(i>=l)throw r(`queryArea.bbox west (${i}) must be less than east (${l}); a box across the antimeridian is not supported.`);if(n>=a)throw r(`queryArea.bbox south (${n}) must be less than north (${a}).`);return{bbox:[i,n,l,a]}}function lt(t){const{autoLoadLayers:e,...r}=t;return{...r,queryArea:st(t),autoLoadLayers:{layers:e?.layers??[]}}}function Q(t){return`${t?`coordinateFormat is set to "${t}"`:"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 ut(t){let e=1/0,r=1/0,o=-1/0,i=-1/0;const n=a=>{if(Array.isArray(a)){if(typeof a[0]=="number"){const[s,u]=a;s<e&&(e=s),s>o&&(o=s),u<r&&(r=u),u>i&&(i=u);return}for(const s of a)n(s)}},l=a=>{a&&(a.type==="GeometryCollection"?a.geometries.forEach(l):n(a.coordinates))};for(const a of t.features??[])l(a?.geometry);return e<=o?[e,r,o,i]:void 0}function ct(t,e){function r(o,i){if(!i||!i.db)return;const n=document.getElementById(i.db);if(n){const l=o.getTablesMetadata();n.innerHTML+="<ul>";for(const a of l)n.innerHTML+=`<li>${a.name}: (${a.source}, ${a.type}) </li>`;n.innerHTML+="</ul>",n.innerHTML+=`<p>Number of tables: ${l.length}</p>`}}return{async resolveSource(o,i){let n=o;n||(n=new M.AutkDb,await n.init());let{type:l,...a}=i;switch(l){case"osm":return await n.loadOsm(lt(a)),r(n,t),n;case"csv":return await n.loadCsv(a),r(n,t),n;case"json":return await n.loadJson(a),r(n,t),n;case"geojson":{const s=a;let u;s.geojsonFileUrl?u=await(await fetch(s.geojsonFileUrl)).json():u=s.geojsonObject,e&&u&&e.set(s.outputTableName,u);const c=u?(()=>{const f={...s,geojsonObject:u};return delete f.geojsonFileUrl,f})():s,h=/^EPSG:4326$/i.test(c.coordinateFormat??"EPSG:4326"),p=u&&h?ut(u):void 0;if(p&&(p[1]<-90||p[3]>90))throw new Error(`GeoJSON layer "${c.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${p.join(", ")}]), so they cannot be EPSG:4326 degrees. ${Q(c.coordinateFormat)}`);try{await n.loadGeojson(c)}catch(f){throw new Error(`Failed to load GeoJSON layer "${c.outputTableName}": ${f instanceof Error?f.message:String(f)}`)}try{const f=await n.getBoundingBoxFromLayer(c.outputTableName),d=25e6;if(!isFinite(f.minLon)||!isFinite(f.minLat)||!isFinite(f.maxLon)||!isFinite(f.maxLat)||Math.abs(f.minLon)>d||Math.abs(f.maxLon)>d||Math.abs(f.minLat)>d||Math.abs(f.maxLat)>d)throw new Error(`Geometry bounding box after transform is invalid for layer "${c.outputTableName}" (bbox: [${f.minLon}, ${f.minLat}, ${f.maxLon}, ${f.maxLat}]). ${Q(c.coordinateFormat)} The workspace uses ${M.DEFAULT_WORKSPACE_COORDINATE_FORMAT}; input is expected in EPSG:4326 by default.`)}catch(f){if(f instanceof Error&&f.message.includes("bounding box after transform"))throw f}return r(n,t),n}case"heatmap":{const s=a;return await n.buildHeatmap({tableJoinName:s.tableJoinName,near:{distance:s.near.distance},outputTableName:s.outputTableName,grid:s.grid,...s.groupBy&&{groupBy:s.groupBy}}),r(n,t),n}case"join":{const s=a;if(await n.spatialQuery({tableRootName:s.tableRootName,tableJoinName:s.tableJoinName,...s.near&&{near:s.near},...s.groupBy&&{groupBy:s.groupBy}}),e){const u=await n.getLayer(s.tableRootName);e.set(s.tableRootName,u)}return r(n,t),n}default:return}}}}function N(t){return typeof t.title=="string"&&t.title!==""?t.title:t.dataRef}function ft(t,e){const r=new Set;for(const o of t.layerRefs){const i=N(o);if(r.has(i))throw new Error(`Map ${e} draws two layers with the id "${i}". A layer's id is its title, else its dataRef: give each layer of a map its own title.`);r.add(i)}}const pt=/^#[0-9a-fA-F]{6}$/;function k(t,e,r){if(!pt.test(t))throw new Error(`Layer "${r}": ${e} must be a color written #rrggbb, not "${t}".`);return _.ColorMap.hexToRgb(t)}function mt(t,e){const r={};return t.color!=null&&(r.color=k(t.color,"color",e)),t.stroke===!1?r.showBorders=!1:t.stroke!=null&&(r.strokeColor=k(t.stroke,"stroke",e)),t.width!=null&&(r.polylinesWidth=t.width),r}function dt(t,e){return t.isColorMap!=null?t.isColorMap:e==="raster"?t.colorMapInterpolator!=null||t.colorMapRange!=null||t.colorMapCenter!=null||t.colorMapReverse===!0:t.color!=null?!1:t.colorMapInterpolator!=null||t.getFnv!=null}function ht(t,e){const r=t.features?.[0]?.properties?.[e];return r instanceof Float32Array?r:ArrayBuffer.isView(r)&&!(r instanceof DataView)||Array.isArray(r)?Float32Array.from(r,o=>Number.isFinite(Number(o))?Number(o):NaN):null}function yt(t,e,r,o,i){if(_.ColorMap.isCategorical(e.interpolator))return;if(i!=null){const u=r!=null?[i[0],r,i[1]]:[i[0],i[1]];return o===!0?u.reverse():u}if(!t)return;let n=0,l=0;for(let u=0;u<t.length;u++){const c=t[u];Number.isFinite(c)&&(l++,r!=null&&(n=Math.max(n,Math.abs(c-r))))}const a=r!=null&&n>0;if(l===0||!a&&o!==!0)return;const s=a&&r!=null?[r-n,r,r+n]:_.ColorMap.resolveDomainFromData(t,e);return o===!0?[...s].reverse():s}function gt(t,e){if(!(e==null||_.ColorMap.isCategorical(t.interpolator)))return[e[0],e[1]]}function bt(t){const e=t.colorMapRange;if(e===void 0)return;const r=l=>new Error(`Layer "${N(t)}": ${l}`);if(!Array.isArray(e)||e.length!==2||!e.every(l=>typeof l=="number"&&Number.isFinite(l)))throw r("colorMapRange must hold two numbers, [low, high].");const[o,i]=e;if(o>=i)throw r(`colorMapRange low (${o}) must be less than high (${i}).`);if(t.colorMapDomain!==void 0)throw r("set colorMapRange or colorMapDomain, not both.");const n=t.colorMapCenter;if(n!=null&&(n<o||n>i))throw r(`colorMapCenter (${n}) must lie within colorMapRange [${o}, ${i}].`)}function _t(t,e){return e&&e.length>0?{type:_.ColorMapDomainStrategy.USER,params:e}:t?.mode===T.PERCENTILE?t.lowerPercentile!==void 0||t.upperPercentile!==void 0?{type:_.ColorMapDomainStrategy.PERCENTILE,params:[t.lowerPercentile??0,t.upperPercentile??100]}:{type:_.ColorMapDomainStrategy.PERCENTILE}:{type:_.ColorMapDomainStrategy.MIN_MAX}}function Et(t,e){return e.split(".").reduce((r,o)=>{if(!(r==null||typeof r!="object"))return r[o]},t)}function At(t,e,r){const o=e.split("."),i={...t};let n=i;for(let l=0;l<o.length-1;l++)n[o[l]]={...n[o[l]]??{}},n=n[o[l]];return n[o[o.length-1]]=r,i}function wt(t,e){const o=t.features?.[0]?.properties?.bands??[];return o.find(n=>n.id===e||n.label===e?.replace(/\./g,"_"))?.id??o[0]?.id??e??""}function Mt(t,e,r,o,i){async function n(l,a,s){let u={};for(const c of a.getTablesMetadata())c.type!==void 0&&(u[c.name]=c.type);for(const c of s.layerRefs){const h=c.dataRef,p=N(c),f=u[h],d=c.getFnv,y=r?.get(h)??await a.getLayer(h),g=f==="raster"?y:{...y,features:(y.features??[]).filter(b=>b.geometry!=null)},R=f==="raster"?wt(g,d):"";f==="raster"?l.loadCollection(p,{collection:g,type:"raster",property:R}):l.loadCollection(p,{collection:g,type:f}),c.opacity!=null&&l.updateRenderInfo(p,{opacity:c.opacity});const S=mt(c,p);Object.keys(S).length>0&&l.updateRenderInfo(p,S),dt(c,f)&&l.updateRenderInfo(p,{isColorMap:!0}),c.isPick&&l.updateRenderInfo(p,{isPick:!0}),c.isSkip&&l.updateRenderInfo(p,{isSkip:!0});const{catchAllCategory:A,colorMapDomain:v}=c;let et=g,rt=v;if(d&&A&&v?.length){const b=new Set(v);et={...g,features:g.features.map(w=>{const at=w.properties,j=Et(at,d);return j==null||!b.has(String(j))?{...w,properties:At(at,d,A)}:w})},rt=b.has(A)?v:[...v,A]}const ot=f==="raster"&&c.transferFunction!=null;ot&&l.layerManager.searchByLayerId(p)?.setTransferFunction?.(c.transferFunction);const F=c.colorMapRange,nt=f==="raster"&&(F!=null||c.colorMapCenter!=null||c.colorMapReverse===!0);if(c.colorMapInterpolator||nt||F){const b={interpolator:c.colorMapInterpolator??l.layerManager.searchByLayerId(p)?.layerRenderInfo.colormap.config.interpolator??_.ColorMapInterpolator.SEQ_REDS,domainSpec:_t(c.normalization,rt)};let w;nt?w=yt(ht(g,R),b,c.colorMapCenter,c.colorMapReverse,F):f!=="raster"&&(w=gt(b,F)),w&&(b.domainSpec={type:_.ColorMapDomainStrategy.USER,params:w}),l.updateColorMap(p,{colorMap:b})}else ot&&l.updateColorMap(p,{colorMap:{}});if(d&&f!=="raster"){const b=d.startsWith("properties.")?d:`properties.${d}`;l.updateThematic(p,{collection:et,property:b})}}}return{async resolveMap(l,a,s=0){if(t&&t.map&&l){ft(a,s);for(const h of a.layerRefs)bt(h);let u;if(Array.isArray(t.map)?u=document.getElementById(t.map[s]):u=document.getElementById(t.map),!u)throw new Error("Could not find rendering target for map: "+t.map);if(!(u instanceof HTMLCanvasElement))throw new Error("Target for map is not a canvas: "+t.map);const c=new L.AutkMap(u);a.style&&c.style.setPredefinedStyle(a.style),await c.init(),await n(c,l,a);for(const h of a.layerRefs)e?.set(h.dataRef,c),i?.set(h.dataRef,N(h));o&&(o[s]=c),c.draw()}}}}function Rt(t){return{scatter:"scatterplot",bar:"barchart",line:"linechart",linechart:"linechart","parallel-coordinates":"parallel-coordinates",table:"table",heatmatrix:"heatmatrix"}[t]}function St(t,e,r,o,i,n){return{async resolvePlot(l,a){if(!t||!t.plot)return;const s=document.getElementById(t.plot);if(!s)throw new Error(`Could not find plot target: ${t.plot}`);const u=l;if(!u)throw new Error("No data context available for plot.");const c=i?.get(a.dataRef)??await u.getLayer(a.dataRef),h=a.events??[],p=new C.AutkPlot(s,{type:Rt(a.mark),collection:c,attributes:{axis:a.axis,...a.color&&{color:a.color}},labels:{axis:a.axis,title:a.title},events:h,...a.width&&{width:a.width},...a.height&&{height:a.height},...a.margins&&{margins:a.margins},...a.transform&&{transform:a.transform}});if(r?.set(a.dataRef,p),a.mapRef&&o?.set(a.dataRef,a.mapRef),a.mapRef&&e){const f=e.get(a.mapRef),d=n?.get(a.mapRef)??a.mapRef;if(f){f.updateRenderInfo(d,{isPick:!0}),f.events.on(L.MapEvent.PICKING,({selection:y})=>{p.setSelection(y)});for(const y of h)p.events.on(y,({selection:g})=>{f.setHighlightedIds(d,g)})}}}}}const B=134217728,Ct=4,It=32;function Y(t){return Array.isArray(t)?t.join(`
2
+ `):t}function E(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.fromFeature=="object"&&t.fromFeature!==null}function I(t,e){return t instanceof Map?t.get(e):t[e]}function P(t,e){return e.split(".").reduce((r,o)=>{if(!(r==null||typeof r!="object"))return r[o]},t)}function V(t){const e=[];for(const r of[t.uniforms,t.uniformMatrices])for(const o of Object.values(r??{}))E(o)&&e.push(o);return e}function H(t){return[...new Set([t.dataRef,...V(t).map(e=>e.fromFeature.layer)])]}function O(t){for(const e of V(t)){const{iterate:r,layer:o}=e.fromFeature;if(r==="all"||r==="batched")return{mode:r,layer:o}}return null}function q(t,e,r){const o=t.fromFeature,i=r!==void 0&&o.iterate==="all"?r:o.index??0,n=I(e,o.layer)?.features?.[i];return n?P(n,o.path):void 0}function D(t,e,r){if(!t)return;const o={};for(const[i,n]of Object.entries(t)){if(!E(n)){o[i]=n;continue}const l=Number(q(n,e,r)??NaN);Number.isFinite(l)?o[i]=l:typeof n.default=="number"&&(o[i]=n.default)}return o}function G(t,e,r){if(!t)return;const o={};for(const[i,n]of Object.entries(t)){if(!E(n)){o[i]=n;continue}const l=q(n,e,r),a=Array.isArray(l)?l:Array.isArray(n.default)?n.default:void 0;if(!a)continue;const s=n.cols??(Array.isArray(a[0])?a[0].length:0);s>0?o[i]={data:a,cols:s}:console.warn(`[autk-grammar] uniform matrix "${i}" has no column count; entry dropped`)}return o}function vt(t){return t!=null&&!(typeof t=="number"&&!Number.isFinite(t))}function W(t){return E(t)&&t.fromFeature.iterate==="batched"}function X(t,e){return Object.values(e??{}).some(W)?It:Object.values(t??{}).some(W)?Ct:0}function J(t,e,r=B){const o=X(t,e);return o>0?Math.floor(r/o):Number.POSITIVE_INFINITY}function K(t,e,r,o=B){const i={},n={},l=[];for(const s of[t,e])for(const u of Object.values(s??{}))E(u)&&u.fromFeature.iterate==="batched"&&u.fromFeature.required&&l.push(u.fromFeature.path);if(l.length>0){const s=r.length;r=r.filter(u=>l.every(c=>vt(P(u,c)))),r.length<s&&console.info(`[autk-grammar] batched compute dropped ${s-r.length} feature(s) missing ${l.join(", ")}`)}const a=J(t,e,o);r.length>a&&(console.warn(`[autk-grammar] batched compute capped at ${a} features (got ${r.length}): its largest packed array takes ${X(t,e)} B per feature, and a storage buffer binding holds ${o} B`),r=r.slice(0,a));for(const[s,u]of Object.entries(t??{}))if(E(u)&&u.fromFeature.iterate==="batched"){const c=typeof u.default=="number"?u.default:void 0;n[s]=r.map(h=>{const p=Number(P(h,u.fromFeature.path)??c);return Number.isFinite(p)?p:0})}else typeof u=="number"&&(i[s]=u);for(const[s,u]of Object.entries(e??{})){if(!E(u)||u.fromFeature.iterate!=="batched")continue;const c=[];for(const h of r){const p=P(h,u.fromFeature.path);let f=1/0,d=1/0,y=-1/0,g=-1/0;if(Array.isArray(p))for(const R of p){if(!Array.isArray(R)||R.length<2)continue;const S=Number(R[0]),A=Number(R[1]);!Number.isFinite(S)||!Number.isFinite(A)||(f=Math.min(f,S),d=Math.min(d,A),y=Math.max(y,S),g=Math.max(g,A))}Number.isFinite(f)||(f=0,d=0,y=0,g=0),c.push(f,d,y,d,y,g,f,g)}n[s]=c}return i.num_features=r.length,{uniforms:i,uniformArrays:n}}function $(t,e,r){const o=I(e,t.dataRef);if(!o)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const i={collection:o,variableMapping:t.attributes,wgslBody:Y(t.wglsFunction)};t.attributeArrays&&(i.attributeArrays=t.attributeArrays),t.attributeMatrices&&(i.attributeMatrices=t.attributeMatrices),t.uniformArrays&&(i.uniformArrays=t.uniformArrays),t.outputColumnName&&(i.resultField=t.outputColumnName),t.outputColumns&&(i.outputColumns=t.outputColumns);const n=O(t);if(n?.mode==="batched"){const u=I(e,n.layer)?.features??[],c=K(t.uniforms,t.uniformMatrices,u),h=D(Z(t.uniforms),e)??{},p=G(Z(t.uniformMatrices),e);return i.uniforms={...h,...c.uniforms},i.uniformArrays={...i.uniformArrays??{},...c.uniformArrays},p&&Object.keys(p).length>0&&(i.uniformMatrices=p),i}const l=n?.mode==="all"?r:void 0,a=D(t.uniforms,e,l),s=G(t.uniformMatrices,e,l);return a&&(i.uniforms=a),s&&(i.uniformMatrices=s),i}function Z(t){if(t)return Object.fromEntries(Object.entries(t).filter(([,e])=>!(E(e)&&e.fromFeature.iterate==="batched")))}function Lt(t){return t.outputColumns??(t.outputColumnName?[t.outputColumnName]:[])}async function z(t,e,r){const o=O(t);if(o?.mode!=="all")return r($(t,e));const i=I(e,t.dataRef);if(!i)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const n=Lt(t),l=structuredClone(i);for(const s of l.features){const u=s.properties??={},c=u.compute??={};for(const h of n)c[h]=0}const a=I(e,o.layer)?.features?.length??0;for(let s=0;s<a;s++){const u=await r({...$(t,e,s),collection:l});l.features.forEach((c,h)=>{const p=c.properties?.compute,f=u.features[h]?.properties?.compute;if(!(!p||!f))for(const d of n){const y=Number(f[d]);Number.isFinite(y)&&(p[d]+=y)}})}return l}function Nt(t){return{async resolveCompute(e,r){if(e){const o={};for(const l of H(r)){const a=t?.get(l);if(a)o[l]=a;else if(l===r.dataRef)o[l]=await e.getLayer(l);else try{o[l]=await e.getLayer(l)}catch{o[l]=void 0}}const i=new it.AutkComputeEngine,n=await z(r,o,l=>i.gpgpuPipeline(l));return t&&t.set(r.dataRef,n),e}}}}class tt{_listeners=new Map;on(e,r){this._listeners.has(e)||this._listeners.set(e,new Set);const o=this._listeners.get(e);return o.add(r),()=>o.delete(r)}emit(e,r){this._listeners.get(e)?.forEach(o=>o(r))}}class Pt{dataAdapter;mapAdapter;plotAdapter;computeAdapter;grammarEngine;_computeCache=new Map;_data={};_mapRegistry=new Map;_mapLayerIds=new Map;_maps=[];_plotRegistry=new Map;_fwdCleanups=[];_plotMapLinks=new Map;interactions=new tt;constructor(e){const r=new Map;this.dataAdapter=ct(e,r),this.mapAdapter=Mt(e,this._mapRegistry,this._computeCache,this._maps,this._mapLayerIds),this.plotAdapter=St(e,this._mapRegistry,this._plotRegistry,this._plotMapLinks,r,this._mapLayerIds),this.computeAdapter=Nt(this._computeCache)}get workspaceCrs(){return M.DEFAULT_WORKSPACE_COORDINATE_FORMAT}get data(){return this._data}get maps(){return this._maps}mapLayer(e){const r=this._mapRegistry.get(e);return r?{map:r,layerId:this._mapLayerIds.get(e)??e}:void 0}async run(e){if(!this.dataAdapter)throw new Error("Database adapter not initialized. Please call the constructor first.");if(!this.mapAdapter)throw new Error("Map engine not initialized. Please call the constructor first.");if(!this.plotAdapter)throw new Error("Plot adapter not initialized. Please call the constructor first.");if(!this.computeAdapter)throw new Error("Compute adapter not initialized. Please call the constructor first.");this._mapRegistry.clear(),this._mapLayerIds.clear(),this._maps.length=0,this._plotRegistry.clear(),this._plotMapLinks.clear(),this._computeCache.clear(),this.grammarEngine=x({spec:e,adapters:{db:this.dataAdapter,map:this.mapAdapter,plot:this.plotAdapter,compute:this.computeAdapter}}),await this.grammarEngine.run(),this._rewireInteractions();const r=this.grammarEngine.context;if(!r){console.warn("Grammar engine produced no data context."),this._data={};return}const o={};for(const i of r.getLayersMetadata())Object.defineProperty(o,i.name,{get:()=>{const n=this._computeCache.get(i.name);return n?Promise.resolve(n):r.getLayer(i.name)},enumerable:!0,configurable:!0});this._data=o}highlightOnMap(e,r){const o=this.mapLayer(e);o?.map.setHighlightedIds(o.layerId,r);for(const[i,n]of this._plotMapLinks)n===e&&this._plotRegistry.get(i)?.setSelection(r)}clearHighlightOnMap(e){const r=this.mapLayer(e);r?.map.clearHighlightedIds(r.layerId);for(const[o,i]of this._plotMapLinks)i===e&&this._plotRegistry.get(o)?.setSelection([])}clearHighlightOnPlot(e){this._plotRegistry.get(e)?.setSelection([]);const r=this._plotMapLinks.get(e),o=r?this.mapLayer(r):void 0;o?.map.clearHighlightedIds(o.layerId)}setPlotSelection(e,r){this._plotRegistry.get(e)?.setSelection(r);const o=this._plotMapLinks.get(e),i=o?this.mapLayer(o):void 0;i?.map.setHighlightedIds(i.layerId,r)}_rewireInteractions(){for(const r of this._fwdCleanups)r();this._fwdCleanups=[];const e=new Set;for(const[r,o]of this._mapRegistry){if(e.has(o))continue;e.add(o);const i=({selection:n})=>{this.interactions.emit("map:picking",{layerId:r,selection:n})};o.events.on(L.MapEvent.PICKING,i),this._fwdCleanups.push(()=>o.events.off(L.MapEvent.PICKING,i))}for(const[r,o]of this._plotRegistry)for(const i of[C.PlotEvent.CLICK,C.PlotEvent.BRUSH,C.PlotEvent.BRUSH_X,C.PlotEvent.BRUSH_Y]){const n=({selection:l})=>{this.interactions.emit("plot:selection",{plotId:r,event:i,selection:l})};o.events.on(i,n),this._fwdCleanups.push(()=>o.events.off(i,n))}}}m.AutkGrammar=Pt,m.ColorMapInterpolator=U,m.GrammarEventEmitter=tt,m.NormalizationMode=T,m.STORAGE_BUFFER_BINDING_SIZE=B,m.buildBatchedUniforms=K,m.computeLayerNames=H,m.createEngine=x,m.findIterateSource=O,m.isFromFeature=E,m.joinWgsl=Y,m.maxBatchedFeatures=J,m.resolveComputeParams=$,m.resolveUniformMatrices=G,m.resolveUniforms=D,m.runCompute=z,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
3
3
  //# sourceMappingURL=autk-grammar.umd.cjs.map