@urban-toolkit/autk-grammar 5.1.0 → 5.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +222 -1
- package/build/autk-grammar-schema.json +844 -24
- package/dist/autk-grammar.js +942 -671
- package/dist/autk-grammar.js.map +1 -1
- package/dist/autk-grammar.umd.cjs +2 -2
- package/dist/autk-grammar.umd.cjs.map +1 -1
- package/dist/data/autk-grammar-data.cjs +1 -1
- package/dist/data/autk-grammar-data.cjs.map +1 -1
- package/dist/data/autk-grammar-data.js +98 -94
- package/dist/data/autk-grammar-data.js.map +1 -1
- package/dist/index.d.ts +261 -13
- package/package.json +1 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(g,E){typeof exports=="object"&&typeof module<"u"?E(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"],E):(g=typeof globalThis<"u"?globalThis:g||self,E(g["autk-grammar"]={},g.autkDb,g.autkMap,g.autkPlot,g.autkCore,g.autkCompute))})(this,(function(g,E,k,P,M,X){"use strict";function z(t){const{spec:e,adapters:r}=t;let o;async function n(){let i;if(e.workspaces?.length&&r.db.resolveWorkspaces&&(i=await r.db.resolveWorkspaces(i,e.workspaces)),e.data)for(const l of e.data)i=await r.db.resolveSource(i,l);if(e.compute)for(const l of e.compute)i=await r.compute.resolveCompute(i,l);if(e.map)if(Array.isArray(e.map))for(let l=0;l<e.map.length;l++){let u=e.map[l];await r.map.resolveMap(i,u,l)}else await r.map.resolveMap(i,e.map);if(e.plot)if(Array.isArray(e.plot))for(let l=0;l<e.plot.length;l++)await r.plot.resolvePlot(i,e.plot[l],l);else await r.plot.resolvePlot(i,e.plot);o=i}function s(i){return console.log("Spec to update",i),new Promise(l=>{l()})}function a(){console.log("Function not implemented yet")}return{run:n,updatedSpec:s,destroy:a,get context(){return o}}}function Z(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function Dt(t){const e=t.layout??{},r=e.type??"vertical";if(r!=="vertical"&&r!=="horizontal"&&r!=="grid")throw new Error(`Layout type must be vertical, horizontal or grid, not ${JSON.stringify(r)}.`);const o=e.gap??0;if(typeof o!="number"||!Number.isFinite(o)||o<0)throw new Error(`Layout gap must be a number of pixels, 0 or more, not ${JSON.stringify(o)}.`);const n=e.columns??2;if(!Number.isInteger(n)||n<1)throw new Error(`Layout columns must be a whole number, 1 or more, not ${JSON.stringify(n)}.`);const s=[...Z(t.map).map((l,u)=>({kind:"map",index:u,id:l.id,key:l.id??u})),...Z(t.plot).map((l,u)=>({kind:"plot",index:u,id:l.id,key:l.id??l.dataRef}))],a=r==="vertical"?1:r==="horizontal"?Math.max(s.length,1):n,i=s.map(({kind:l,index:u,id:d,key:c},f)=>({kind:l,index:u,...d!==void 0&&{id:d},key:c,row:Math.floor(f/a),column:f%a}));return{type:r,rows:Math.ceil(s.length/a),columns:a,gap:o,panes:i}}var tt=(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))(tt||{}),x=(t=>(t.MIN_MAX="minMax",t.PERCENTILE="percentile",t))(x||{});async function I(t,e){const r=e??E.DEFAULT_WORKSPACE_NAME;t.getCurrentWorkspace()!==r&&await t.setWorkspace(r)}function _(t,e){return t===void 0||t===E.DEFAULT_WORKSPACE_NAME?e:`${t}/${e}`}function et(t){const e=new Set;for(const o of t)o?.id!=null&&e.add(JSON.stringify(o.id));const r=new Set;return t.map((o,n)=>{if(o?.id!=null)return o.id;let s=`autk-feature-${n}`;for(;e.has(JSON.stringify(s))||r.has(JSON.stringify(s));)s=`${s}-generated`;return r.add(JSON.stringify(s)),s})}function rt(t){const e=new Map;return et(t).map(r=>{const o=JSON.stringify(r),n=e.get(o)??0;return e.set(o,n+1),n===0?o:`${o} ${n}`})}const ot=new WeakMap;function xt(t){let e=ot.get(t);return e||(e=new Map,t.forEach((r,o)=>{const n=e.get(r);n?n.push(o):e.set(r,[o])}),ot.set(t,e),e)}function B(t,e,r){const o=xt(r),n=new Set;for(const s of t){const a=e[s];if(a!==void 0)for(const i of o.get(a)??[])n.add(i)}return[...n]}const Ut={type:"GeometryCollection",geometries:[]};function Qt(t){const e=t.features??[],r=et(e);let o=!1;const n=e.map((a,i)=>a==null||a.id!=null&&a.geometry!=null?a:(o=!0,{...a,id:r[i],geometry:a.geometry??Ut})),s=e.findIndex(a=>a?.geometry!=null);return s>0&&e[0]!=null&&e[0].geometry==null&&([n[0],n[s]]=[n[s],n[0]],o=!0),o?{...t,features:n}:t}function Wt(t){const{queryArea:e}=t;if(e.bbox===void 0)return{geocodeArea:e.geocodeArea,areas:e.areas};const r=l=>new Error(`OSM source "${t.outputTableName}": ${l}`);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(l=>typeof l=="number"&&Number.isFinite(l)))throw r("queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.");const[n,s,a,i]=e.bbox;if(Math.abs(n)>180||Math.abs(a)>180)throw r("queryArea.bbox west and east must be longitudes from -180 to 180.");if(Math.abs(s)>90||Math.abs(i)>90)throw r("queryArea.bbox south and north must be latitudes from -90 to 90.");if(n>=a)throw r(`queryArea.bbox west (${n}) must be less than east (${a}); a box across the antimeridian is not supported.`);if(s>=i)throw r(`queryArea.bbox south (${s}) must be less than north (${i}).`);return{bbox:[n,s,a,i]}}function Yt(t){const{autoLoadLayers:e,...r}=t;if(t.pbfFileUrl!==void 0&&(t.tagSets?.length??0)>0)throw new Error(`OSM source "${t.outputTableName}": tagSets are read from the Overpass API only, so a source with pbfFileUrl cannot take them.`);return{...r,queryArea:Wt(t),autoLoadLayers:{layers:e?.layers??[],...e?.coordinateFormat!==void 0&&{coordinateFormat:e.coordinateFormat}}}}function nt(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 U(t){return t===void 0||t===E.DEFAULT_WORKSPACE_NAME?"the default workspace":`the workspace "${t}"`}function at(t){if(t!=null)return typeof t=="string"?t:JSON.stringify(t)}async function Vt(t,e,r,o){const n=new Map;for(const i of(await t.getLayer(e.name)).features){const l=at(i.properties?.[o]);if(l!==void 0){if(i.id===void 0||i.id===null)throw new Error("its rows have no feature id to update them by.");n.set(l,[...n.get(l)??[],i.id])}}const s=r.features.flatMap(i=>{const l=at(i.properties?.[o]);return l===void 0?[]:(n.get(l)??[]).map(u=>({...i,id:u}))}),a=e.columns.some(i=>i.name==="geojson_id")?"geojson_id":"id";return{data:{...r,features:s},idColumn:a}}async function it(t){if(t)return t;const e=new E.AutkDb;return await e.init(),e}function st(t){let e=1/0,r=1/0,o=-1/0,n=-1/0;const s=i=>{if(Array.isArray(i)){if(typeof i[0]=="number"){const[l,u]=i;l<e&&(e=l),l>o&&(o=l),u<r&&(r=u),u>n&&(n=u);return}for(const l of i)s(l)}},a=i=>{i&&(i.type==="GeometryCollection"?i.geometries.forEach(a):s(i.coordinates))};for(const i of t.features??[])a(i?.geometry);return e<=o?[e,r,o,n]:void 0}function lt(t,e){function r(n,s){if(!s||!s.db)return;const a=document.getElementById(s.db);if(a){const i=n.getTablesMetadata();a.innerHTML+="<ul>";for(const l of i)a.innerHTML+=`<li>${l.name}: (${l.source}, ${l.type}) </li>`;a.innerHTML+="</ul>",a.innerHTML+=`<p>Number of tables: ${i.length}</p>`}}async function o(n,s,a){if(!e)return;const i=_(s,a),l=n.getTablesMetadata().find(u=>u.name===a);l&&E.isRenderableTable(l)?e.set(i,await n.getLayer(a)):e.delete(i)}return{async resolveWorkspaces(n,s){const a=await it(n),i=new Set;for(const{name:l,coordinateFormat:u,precisionGrid:d}of s){const c=l??E.DEFAULT_WORKSPACE_NAME;if(i.has(c))throw new Error(`workspaces sets ${U(l)} twice; give each workspace one entry.`);i.add(c);try{await a.setWorkspace(c,{coordinateFormat:u,precisionGrid:d})}catch(f){throw new Error(`workspaces, ${U(l)}: ${f instanceof Error?f.message:String(f)}`)}}return await I(a),a},async resolveSource(n,s){const a=await it(n),{workspace:i}=s;await I(a,i);let{type:l,workspace:u,...d}=s;switch(l){case"osm":return await a.loadOsm(Yt(d)),r(a,t),a;case"csv":return await a.loadCsv(d),r(a,t),a;case"json":return await a.loadJson(d),r(a,t),a;case"geojson":{const c=d;let f;c.geojsonFileUrl?f=await(await fetch(c.geojsonFileUrl)).json():f=c.geojsonObject,e&&f&&e.set(_(i,c.outputTableName),f);const y=f?(()=>{const p={...c,geojsonObject:Qt(f)};return delete p.geojsonFileUrl,p})():c,m=/^EPSG:4326$/i.test(y.coordinateFormat??"EPSG:4326"),h=f&&m?st(f):void 0;if(h&&(h[1]<-90||h[3]>90))throw new Error(`GeoJSON layer "${y.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${h.join(", ")}]), so they cannot be EPSG:4326 degrees. ${nt(y.coordinateFormat)}`);try{await a.loadGeojson(y)}catch(p){throw new Error(`Failed to load GeoJSON layer "${y.outputTableName}": ${p instanceof Error?p.message:String(p)}`)}try{const p=await a.getBoundingBoxFromLayer(y.outputTableName),w=25e6;if(!isFinite(p.minLon)||!isFinite(p.minLat)||!isFinite(p.maxLon)||!isFinite(p.maxLat)||Math.abs(p.minLon)>w||Math.abs(p.maxLon)>w||Math.abs(p.minLat)>w||Math.abs(p.maxLat)>w)throw new Error(`Geometry bounding box after transform is invalid for layer "${y.outputTableName}" (bbox: [${p.minLon}, ${p.minLat}, ${p.maxLon}, ${p.maxLat}]). ${nt(y.coordinateFormat)} The workspace uses ${a.getWorkspaceConfiguration().coordinateFormat}; input is expected in EPSG:4326 by default.`)}catch(p){if(p instanceof Error&&p.message.includes("bounding box after transform"))throw p}return r(a,t),a}case"geotiff":return await a.loadGeoTiff(d),r(a,t),a;case"heatmap":{const c=d;if(c.groupBy?.some(f=>f.aggregateFn==="collect"))throw new Error(`Heatmap "${c.outputTableName}": aggregateFn "collect" lists the rows near a cell, and a cell holds one value; use sum, avg, count, min, max or weighted.`);return await a.buildHeatmap({tableJoinName:c.joinDataRef,near:c.near,outputTableName:c.outputTableName,grid:c.grid,...c.groupBy&&{groupBy:c.groupBy}}),r(a,t),a}case"join":{const c=d;if(await a.spatialQuery({tableRootName:c.dataRef,tableJoinName:c.joinDataRef,...c.near&&{near:c.near},...c.groupBy&&{groupBy:c.groupBy}}),e){const f=await a.getLayer(c.dataRef);e.set(_(i,c.dataRef),f)}return r(a,t),a}case"sql":{const c=d;try{await a.rawQuery({query:c.query,output:{type:"CREATE_TABLE",tableName:c.outputTableName,source:"user",...c.layerType!==void 0&&{tableType:c.layerType}}})}catch(f){throw new Error(`SQL source "${c.outputTableName}": ${f instanceof Error?f.message:String(f)}`)}return e?.delete(_(i,c.outputTableName)),r(a,t),a}case"update":{const c=d,f=h=>new Error(`Update of "${c.dataRef}": ${h}`);if(c.geojsonObject===void 0==(c.jsonObject===void 0))throw f("give its rows in geojsonObject or in jsonObject, one of the two.");if(c.strategy==="update"&&!c.idColumn)throw f("the update strategy needs an idColumn, the column that matches a given row to the table's rows.");let y=c.geojsonObject??c.jsonObject,m=c.idColumn;try{const h=a.getTablesMetadata().find(p=>p.name===c.dataRef);if(c.strategy==="update"&&c.geojsonObject&&m?.startsWith("properties.")&&h&&E.isVectorTable(h)&&({data:y,idColumn:m}=await Vt(a,h,c.geojsonObject,m.slice(11)),y.features.length===0))return r(a,t),a;await a.updateTable({tableName:c.dataRef,data:y,strategy:c.strategy,...m!==void 0&&{idColumn:m}})}catch(h){throw f(h instanceof Error?h.message:String(h))}return await o(a,i,c.dataRef),r(a,t),a}case"drop":{const c=d;if(!a.getTablesMetadata().some(f=>f.name===c.dataRef))throw new Error(`Drop of "${c.dataRef}": ${U(i)} holds no table of that name.`);return await a.removeLayer(c.dataRef),e?.delete(_(i,c.dataRef)),r(a,t),a}default:throw new Error(`Unknown data source type "${String(l)}".`)}}}}function ut(t,e){return e===!0?`${t} osm-elements`:t}function ct(t){return t===!0?{osmElements:!0}:void 0}function ft(t,e,r){if(!t)return r();let o=t.get(e);return o||(o=r(),t.set(e,o)),o}function dt(t,e){return t?.id??e}function Q(t,e){return e===void 0?!0:typeof e=="number"?t.mapIndex===e:t.mapId===e}function pt(t,e,r){const o=t?.get(e)??[];o.includes(r)||t?.set(e,[...o,r])}const mt=6378137,W=.0818191908426215;function qt(t,e){if(t===void 0||typeof t=="number"&&Number.isFinite(t)&&t>0)return;const r=typeof t=="number"?String(t):JSON.stringify(t);throw new Error(`Layer "${e}": pointSize must be a number of meters greater than 0, not ${r}.`)}function Ht(t){const e=Math.exp(-t/mt);let r=Math.PI/2-2*Math.atan(e);for(let o=0;o<10;o++){const n=W*Math.sin(r),s=Math.PI/2-2*Math.atan(e*((1-n)/(1+n))**(W/2));if(Math.abs(s-r)<1e-12)return s;r=s}return r}function Jt(t,e){if(/^EPSG:3395$/i.test(t)){const r=Ht(e),o=W*Math.sin(r);return Math.sqrt(1-o*o)/Math.cos(r)}return/^EPSG:3857$/i.test(t)?Math.cosh(e/mt):1}function Kt(t,e,r,o){if(t===void 0||e!=="points")return;const n=o();if(n)return t*Jt(r,(n[1]+n[3])/2)}function L(t){return typeof t.title=="string"&&t.title!==""?t.title:t.dataRef}function Xt(t,e){const r=new Set;for(const o of t.layerRefs){const n=L(o);if(r.has(n))throw new Error(`Map ${e} draws two layers with the id "${n}". A layer's id is its title, else its dataRef: give each layer of a map its own title.`);r.add(n)}}const zt=/^#[0-9a-fA-F]{6}$/;function ht(t,e,r){if(!zt.test(t))throw new Error(`Layer "${r}": ${e} must be a color written #rrggbb, not "${t}".`);return M.ColorMap.hexToRgb(t)}function Zt(t,e){const r={};return t.color!=null&&(r.color=ht(t.color,"color",e)),t.stroke===!1?r.showBorders=!1:t.stroke!=null&&(r.strokeColor=ht(t.stroke,"stroke",e)),t.width!=null&&(r.polylinesWidth=t.width),r}function te(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 ee(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 re(t,e,r,o,n){if(M.ColorMap.isCategorical(e.interpolator))return;if(n!=null){const u=r!=null?[n[0],r,n[1]]:[n[0],n[1]];return o===!0?u.reverse():u}if(!t)return;let s=0,a=0;for(let u=0;u<t.length;u++){const d=t[u];Number.isFinite(d)&&(a++,r!=null&&(s=Math.max(s,Math.abs(d-r))))}const i=r!=null&&s>0;if(a===0||!i&&o!==!0)return;const l=i&&r!=null?[r-s,r,r+s]:M.ColorMap.resolveDomainFromData(t,e);return o===!0?[...l].reverse():l}function oe(t,e){if(!(e==null||M.ColorMap.isCategorical(t.interpolator)))return[e[0],e[1]]}function ne(t){const e=t.colorMapRange;if(e===void 0)return;const r=a=>new Error(`Layer "${L(t)}": ${a}`);if(!Array.isArray(e)||e.length!==2||!e.every(a=>typeof a=="number"&&Number.isFinite(a)))throw r("colorMapRange must hold two numbers, [low, high].");const[o,n]=e;if(o>=n)throw r(`colorMapRange low (${o}) must be less than high (${n}).`);if(t.colorMapDomain!==void 0)throw r("set colorMapRange or colorMapDomain, not both.");const s=t.colorMapCenter;if(s!=null&&(s<o||s>n))throw r(`colorMapCenter (${s}) must lie within colorMapRange [${o}, ${n}].`)}function ae(t,e){return e&&e.length>0?{type:M.ColorMapDomainStrategy.USER,params:e}:t?.mode===x.PERCENTILE?t.lowerPercentile!==void 0||t.upperPercentile!==void 0?{type:M.ColorMapDomainStrategy.PERCENTILE,params:[t.lowerPercentile??0,t.upperPercentile??100]}:{type:M.ColorMapDomainStrategy.PERCENTILE}:{type:M.ColorMapDomainStrategy.MIN_MAX}}function ie(t,e){return e.split(".").reduce((r,o)=>{if(!(r==null||typeof r!="object"))return r[o]},t)}function se(t,e,r){const o=e.split("."),n={...t};let s=n;for(let a=0;a<o.length-1;a++)s[o[a]]={...s[o[a]]??{}},s=s[o[a]];return s[o[o.length-1]]=r,n}function le(t,e){const o=t.features?.[0]?.properties?.bands??[];return o.find(s=>s.id===e||s.label===e?.replace(/\./g,"_"))?.id??o[0]?.id??e??""}function yt(t){const{pitch:e}=t;return e===void 0||typeof e=="number"&&e>=0&&e<90?void 0:`camera.pitch must be at least 0 and less than 90 degrees, not ${typeof e=="number"?String(e):JSON.stringify(e)}: at 90 the eye would sit on the ground, edge-on to the map's flat layers, and the map could not pan.`}function gt(t,e){const r=yt(e);if(r)throw new Error(r);if(e.zoom===void 0&&!e.pitch&&!e.bearing)return;const o=t.camera,[n,s]=o.getLookAt(),a=e.zoom!==void 0?1e4/Math.pow(2,e.zoom-10):Math.abs(o.getEye()[2]),i=(e.pitch??0)*Math.PI/180,l=(e.bearing??0)*Math.PI/180,u=[n-a*Math.sin(i)*Math.sin(l),s-a*Math.sin(i)*Math.cos(l),a*Math.cos(i)],d=[Math.cos(i)*Math.sin(l),Math.cos(i)*Math.cos(l),Math.sin(i)];o.resetCamera(d,[n,s,0],u)}function ue(t,e,r,o){const s=t.layerManager.searchByLayerId(e)?.components;return Array.isArray(s)?s.map((a,i)=>{const l=Number.isInteger(a?.featureIndex)?a.featureIndex:i;return r[o[l]]??""}):o.map(a=>r[a]??"")}function ce(t,e,r,o,n,s){async function a(i,l,u){let d={};for(const f of l.getTablesMetadata())f.type!==void 0&&(d[f.name]=f.type);const c=[];for(const f of u.layerRefs){const y=f.dataRef,m=L(f),h=_(u.workspace,y),p=n?.get(h)??d[y],w=f.getFnv,A=r?.get(h)??(p==="raster"?await l.getRaster(y):await ft(s,ut(h,f.osmElements),()=>l.getLayer(y,ct(f.osmElements)))),v=A.features??[],N=p==="raster"?[]:v.flatMap((b,S)=>b?.geometry!=null?[S]:[]),C=p==="raster"?A:{...A,features:N.map(b=>v[b])},Pt=p==="raster"?le(C,w):"";p==="raster"?i.loadCollection(m,{collection:C,type:"raster",property:Pt}):i.loadCollection(m,{collection:C,type:p}),f.opacity!=null&&i.updateRenderInfo(m,{opacity:f.opacity});const $t=Zt(f,m);Object.keys($t).length>0&&i.updateRenderInfo(m,$t);const _e=l.getWorkspaceConfiguration().coordinateFormat,Ot=Kt(f.pointSize,p,_e,()=>st(C));Ot!==void 0&&i.updateRenderInfo(m,{pointSize:Ot}),te(f,p)&&i.updateRenderInfo(m,{isColorMap:!0}),f.isPick&&i.updateRenderInfo(m,{isPick:!0}),f.isSkip&&i.updateRenderInfo(m,{isSkip:!0});const{catchAllCategory:G,colorMapDomain:F}=f;let Ft=C,kt=F;if(w&&G&&F?.length){const b=new Set(F);Ft={...C,features:C.features.map(S=>{const Gt=S.properties,K=ie(Gt,w);return K==null||!b.has(String(K))?{...S,properties:se(Gt,w,G)}:S})},kt=b.has(G)?F:[...F,G]}const Bt=p==="raster"&&f.transferFunction!=null;Bt&&i.layerManager.searchByLayerId(m)?.setTransferFunction?.(f.transferFunction);const D=f.colorMapRange,jt=p==="raster"&&(D!=null||f.colorMapCenter!=null||f.colorMapReverse===!0);if(f.colorMapInterpolator||jt||D){const b={interpolator:f.colorMapInterpolator??i.layerManager.searchByLayerId(m)?.layerRenderInfo.colormap.config.interpolator??M.ColorMapInterpolator.SEQ_REDS,domainSpec:ae(f.normalization,kt)};let S;jt?S=re(ee(C,Pt),b,f.colorMapCenter,f.colorMapReverse,D):p!=="raster"&&(S=oe(b,D)),S&&(b.domainSpec={type:M.ColorMapDomainStrategy.USER,params:S}),i.updateColorMap(m,{colorMap:b})}else Bt&&i.updateColorMap(m,{colorMap:{}});if(w&&p!=="raster"){const b=w.startsWith("properties.")?w:`properties.${w}`;i.updateThematic(m,{collection:Ft,property:b})}c.push(p==="raster"?[]:ue(i,m,rt(v),N))}return c}return{async resolveMap(i,l,u=0){if(t&&t.map&&i){Xt(l,u);for(const h of l.layerRefs)ne(h),qt(h.pointSize,L(h));const d=l.camera&&yt(l.camera);if(d)throw new Error(`Map ${u}: ${d}`);let c;if(Array.isArray(t.map)?c=document.getElementById(t.map[u]):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 f=new k.AutkMap(c);let y;try{l.style&&f.style.setPredefinedStyle(l.style),await f.init(),await I(i,l.workspace),y=await a(f,i,l)}catch(h){try{f.destroy()}catch{}throw h}const m=dt(l,u);l.layerRefs.forEach((h,p)=>e?.push({map:f,mapIndex:u,mapId:m,layerId:L(h),dataRef:h.dataRef,rows:y[p]})),o&&(o[u]=f),l.camera&>(f,l.camera),f.draw()}}}}function fe(t){return{scatter:"scatterplot",bar:"barchart",line:"linechart",linechart:"linechart","parallel-coordinates":"parallel-coordinates",table:"table",heatmatrix:"heatmatrix"}[t]}function $(t){return t.id??t.dataRef}function wt(t,e,r,o){const{map:n,layerId:s}=o;n.updateRenderInfo(s,{isPick:!0}),n.events.on(k.MapEvent.PICKING,({layerId:a,selection:i})=>{a===s&&t.setSelection(B(i,o.rows,e))});for(const a of r)t.events.on(a,({selection:i})=>{n.setHighlightedIds(s,B(i,e,o.rows))})}async function de(t,e,r,o,n){const s=t.getTablesMetadata().find(a=>a.name===e);return s&&!E.isRenderableTable(s)?{type:"FeatureCollection",features:(await t.getTable(e)).map(i=>({type:"Feature",geometry:null,properties:i}))}:ft(o,ut(r,n),()=>t.getLayer(e,ct(n)))}function pe(t,e,r,o,n,s,a,i){return{async resolvePlot(l,u,d=0){if(!t||!t.plot)return;const c=Array.isArray(t.plot)?t.plot[d]:t.plot;if(c===void 0)throw new Error(`Plot ${d} has no target: the plot targets name ${t.plot.length} elements.`);const f=document.getElementById(c);if(!f)throw new Error(`Could not find plot target: ${c}`);const y=l;if(!y)throw new Error("No data context available for plot.");await I(y,u.workspace);const m=_(u.workspace,u.dataRef),h=u.osmElements===!0?void 0:n?.get(m),p=s?.get(m)??h??await de(y,u.dataRef,m,i,u.osmElements),w=u.events??[],A=new P.AutkPlot(f,{type:fe(u.mark),collection:p,attributes:{axis:u.axis,...u.color&&{color:u.color}},labels:{axis:u.axis,title:u.title},events:w,...u.width&&{width:u.width},...u.height&&{height:u.height},...u.margins&&{margins:u.margins},...u.transform&&{transform:u.transform}});r?.set($(u),A);const v=rt(p.features??[]);a?.set($(u),v);for(const N of e??[])!u.mapRef||N.dataRef!==u.mapRef||(wt(A,v,w,N),pt(o,$(u),N))}}}const Y=134217728,me=4,he=32;function bt(t){return Array.isArray(t)?t.join(`
|
|
2
|
-
`):t}function R(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.fromFeature=="object"&&t.fromFeature!==null}function O(t,e){return t instanceof Map?t.get(e):t[e]}function j(t,e){return e.split(".").reduce((r,o)=>{if(!(r==null||typeof r!="object"))return r[o]},t)}function Et(t){const e=[];for(const r of[t.uniforms,t.uniformMatrices])for(const o of Object.values(r??{}))R(o)&&e.push(o);return e}function _t(t){return[...new Set([t.dataRef,...Et(t).map(e=>e.fromFeature.layer)])]}function V(t){for(const e of Et(t)){const{iterate:r,layer:o}=e.fromFeature;if(r==="all"||r==="batched")return{mode:r,layer:o}}return null}function Mt(t,e,r){const o=t.fromFeature,n=r!==void 0&&o.iterate==="all"?r:o.index??0,s=O(e,o.layer)?.features?.[n];return s?j(s,o.path):void 0}function q(t,e,r){if(!t)return;const o={};for(const[n,s]of Object.entries(t)){if(!R(s)){o[n]=s;continue}const a=Number(Mt(s,e,r)??NaN);Number.isFinite(a)?o[n]=a:typeof s.default=="number"&&(o[n]=s.default)}return o}function H(t,e,r){if(!t)return;const o={};for(const[n,s]of Object.entries(t)){if(!R(s)){o[n]=s;continue}const a=Mt(s,e,r),i=Array.isArray(a)?a:Array.isArray(s.default)?s.default:void 0;if(!i)continue;const l=s.cols??(Array.isArray(i[0])?i[0].length:0);l>0?o[n]={data:i,cols:l}:console.warn(`[autk-grammar] uniform matrix "${n}" has no column count; entry dropped`)}return o}function ye(t){return t!=null&&!(typeof t=="number"&&!Number.isFinite(t))}function At(t){return R(t)&&t.fromFeature.iterate==="batched"}function vt(t,e){return Object.values(e??{}).some(At)?he:Object.values(t??{}).some(At)?me:0}function St(t,e,r=Y){const o=vt(t,e);return o>0?Math.floor(r/o):Number.POSITIVE_INFINITY}function Rt(t,e,r,o=Y){const n={},s={},a=[];for(const l of[t,e])for(const u of Object.values(l??{}))R(u)&&u.fromFeature.iterate==="batched"&&u.fromFeature.required&&a.push(u.fromFeature.path);if(a.length>0){const l=r.length;r=r.filter(u=>a.every(d=>ye(j(u,d)))),r.length<l&&console.info(`[autk-grammar] batched compute dropped ${l-r.length} feature(s) missing ${a.join(", ")}`)}const i=St(t,e,o);r.length>i&&(console.warn(`[autk-grammar] batched compute capped at ${i} features (got ${r.length}): its largest packed array takes ${vt(t,e)} B per feature, and a storage buffer binding holds ${o} B`),r=r.slice(0,i));for(const[l,u]of Object.entries(t??{}))if(R(u)&&u.fromFeature.iterate==="batched"){const d=typeof u.default=="number"?u.default:void 0;s[l]=r.map(c=>{const f=Number(j(c,u.fromFeature.path)??d);return Number.isFinite(f)?f:0})}else typeof u=="number"&&(n[l]=u);for(const[l,u]of Object.entries(e??{})){if(!R(u)||u.fromFeature.iterate!=="batched")continue;const d=[];for(const c of r){const f=j(c,u.fromFeature.path);let y=1/0,m=1/0,h=-1/0,p=-1/0;if(Array.isArray(f))for(const w of f){if(!Array.isArray(w)||w.length<2)continue;const A=Number(w[0]),v=Number(w[1]);!Number.isFinite(A)||!Number.isFinite(v)||(y=Math.min(y,A),m=Math.min(m,v),h=Math.max(h,A),p=Math.max(p,v))}Number.isFinite(y)||(y=0,m=0,h=0,p=0),d.push(y,m,h,m,h,p,y,p)}s[l]=d}return n.num_features=r.length,{uniforms:n,uniformArrays:s}}function J(t,e,r){const o=O(e,t.dataRef);if(!o)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const n={collection:o,variableMapping:t.attributes,wgslBody:bt(t.wgslFunction)};t.attributeArrays&&(n.attributeArrays=t.attributeArrays),t.attributeMatrices&&(n.attributeMatrices=t.attributeMatrices),t.uniformArrays&&(n.uniformArrays=t.uniformArrays),t.outputColumnName&&(n.resultField=t.outputColumnName),t.outputColumns&&(n.outputColumns=t.outputColumns);const s=V(t);if(s?.mode==="batched"){const u=O(e,s.layer)?.features??[],d=Rt(t.uniforms,t.uniformMatrices,u),c=q(Ct(t.uniforms),e)??{},f=H(Ct(t.uniformMatrices),e);return n.uniforms={...c,...d.uniforms},n.uniformArrays={...n.uniformArrays??{},...d.uniformArrays},f&&Object.keys(f).length>0&&(n.uniformMatrices=f),n}const a=s?.mode==="all"?r:void 0,i=q(t.uniforms,e,a),l=H(t.uniformMatrices,e,a);return i&&(n.uniforms=i),l&&(n.uniformMatrices=l),n}function Ct(t){if(t)return Object.fromEntries(Object.entries(t).filter(([,e])=>!(R(e)&&e.fromFeature.iterate==="batched")))}function ge(t){return t.outputColumns??(t.outputColumnName?[t.outputColumnName]:[])}async function It(t,e,r){const o=V(t);if(o?.mode!=="all")return r(J(t,e));const n=O(e,t.dataRef);if(!n)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const s=ge(t),a=structuredClone(n);for(const l of a.features){const u=l.properties??={},d=u.compute??={};for(const c of s)d[c]=0}const i=O(e,o.layer)?.features?.length??0;for(let l=0;l<i;l++){const u=await r({...J(t,e,l),collection:a});a.features.forEach((d,c)=>{const f=d.properties?.compute,y=u.features[c]?.properties?.compute;if(!(!f||!y))for(const m of s){const h=Number(y[m]);Number.isFinite(h)&&(f[m]+=h)}})}return a}const Lt=["surface","parks","water","roads","buildings","polygons","polylines"];function we(t,e,r,o){return o?.get(_(r,e))??t.getTablesMetadata().find(n=>n.name===e)?.type}function Tt(t,e){async function r(a,i,l){return t?.get(_(l,i))??await a.getLayer(i)}function o(a,i,l,u,d){if(!t)return;const c=u.outputTableName??l;t.set(_(u.workspace,c),i);const f=u.layerType??d??we(a,l,u.workspace,e);u.outputTableName&&f&&e?.set(_(u.workspace,c),f)}async function n(a,i){for(const d of i.layers)if(!Lt.includes(d.type))throw new Error(`Render pass "${i.outputTableName}": layer "${d.id}" has the type "${d.type}", which a render pass cannot draw. A layer's type is one of ${Lt.join(", ")}.`);const l=await Promise.all(i.layers.map(async d=>({id:d.id,collection:await r(a,d.dataRef,i.workspace),type:d.type,objectIdProperty:d.objectIdProperty}))),u=await new X.AutkComputeEngine().renderPipeline({layers:l,viewpoints:{collection:await r(a,i.viewpoints.dataRef,i.workspace),strategy:i.viewpoints.strategy,sampling:i.viewpoints.sampling},aggregation:i.aggregation,camera:i.camera,tileSize:i.tileSize});o(a,u,i.viewpoints.dataRef,i,i.viewpoints.strategy?.type==="building-windows"?"points":void 0)}async function s(a,i){const l={};for(const c of _t(i)){const f=t?.get(_(i.workspace,c));if(f)l[c]=f;else if(c===i.dataRef)l[c]=await a.getLayer(c);else try{l[c]=await a.getLayer(c)}catch{l[c]=void 0}}const u=new X.AutkComputeEngine,d=await It(i,l,c=>u.gpgpuPipeline(c));o(a,d,i.dataRef,i)}return{async resolveCompute(a,i){if(a)return await I(a,i.workspace),i.type==="render"?await n(a,i):await s(a,i),a}}}class Nt{_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))}}function T(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function be(t){const e=new Set;for(const o of[...T(t.map),...T(t.plot)])if(o.id!==void 0){if(o.id==="")throw new Error("A map or plot has an empty id.");if(e.has(o.id))throw new Error(`Two maps or plots have the id "${o.id}"; an id names one view.`);e.add(o.id)}const r=new Map;for(const o of T(t.plot)){const n=$(o),s=r.get(n);if(s)throw new Error(s.id===void 0&&o.id===void 0?`Two plots of the table "${n}" have no id; give each plot an id.`:`A plot's id "${n}" is the dataRef of a plot without an id; give each plot an id.`);r.set(n,o)}}class Ee{dataAdapter;mapAdapter;plotAdapter;computeAdapter;grammarEngine;_computeCache=new Map;_computeTypes=new Map;_data={};_layers=[];_maps=[];_plotRegistry=new Map;_fwdCleanups=[];_plotLinks=new Map;_plotRows=new Map;_exports=new Map;_geojsonCache=new Map;interactions=new Nt;constructor(e){this.dataAdapter=lt(e,this._geojsonCache),this.mapAdapter=ce(e,this._layers,this._computeCache,this._maps,this._computeTypes,this._exports),this.plotAdapter=pe(e,this._layers,this._plotRegistry,this._plotLinks,this._geojsonCache,this._computeCache,this._plotRows,this._exports),this.computeAdapter=Tt(this._computeCache,this._computeTypes)}get workspaceCrs(){return E.DEFAULT_WORKSPACE_COORDINATE_FORMAT}get data(){return this._data}get maps(){return this._maps}mapLayers(e,r){return this._layersOf(e,r).map(({map:o,layerId:n})=>({map:o,layerId:n}))}mapLayer(e,r){return this.mapLayers(e,r).pop()}_layersOf(e,r){return this._layers.filter(o=>o.dataRef===e&&Q(o,r))}destroy(){for(const e of this._fwdCleanups)e();this._fwdCleanups=[];for(const e of this._maps)e.destroy();this._maps.length=0,this._layers.length=0,this._plotRegistry.clear(),this._plotLinks.clear(),this._plotRows.clear(),this._exports.clear(),this._geojsonCache.clear(),this._computeCache.clear(),this._computeTypes.clear(),this.grammarEngine=void 0,this._data={}}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.");be(e),this.destroy(),this.grammarEngine=z({spec:e,adapters:{db:this.dataAdapter,map:this.mapAdapter,plot:this.plotAdapter,compute:this.computeAdapter}}),await this.grammarEngine.run();const r=this.grammarEngine.context;if(r&&await I(r),this._wireLinks(e),this._rewireInteractions(e),!r){console.warn("Grammar engine produced no data context."),this._data={};return}const o={};for(const n of r.getLayersMetadata())Object.defineProperty(o,n.name,{get:()=>{const s=this._computeCache.get(n.name);return s?Promise.resolve(s):r.getLayer(n.name)},enumerable:!0,configurable:!0});for(const n of this._computeCache.keys())n in o||Object.defineProperty(o,n,{get:()=>Promise.resolve(this._computeCache.get(n)),enumerable:!0,configurable:!0});this._data=o}highlightOnMap(e,r,o){const n=this._layersOf(e,o);for(const{map:s,layerId:a}of n)s.setHighlightedIds(a,r);this._selectInLinkedPlots(n,r)}clearHighlightOnMap(e,r){const o=this._layersOf(e,r);for(const{map:n,layerId:s}of o)n.clearHighlightedIds(s);this._selectInLinkedPlots(o,[])}clearHighlightOnPlot(e,r){this._plotRegistry.get(e)?.setSelection([]);for(const o of this._plotLinks.get(e)??[])Q(o,r)&&o.map.clearHighlightedIds(o.layerId)}setPlotSelection(e,r,o){this._plotRegistry.get(e)?.setSelection(r);const n=this._plotRows.get(e)??[];for(const s of this._plotLinks.get(e)??[])Q(s,o)&&s.map.setHighlightedIds(s.layerId,B(r,n,s.rows))}_selectInLinkedPlots(e,r){for(const[o,n]of this._plotLinks){const s=n.filter(l=>e.includes(l));if(s.length===0)continue;const a=this._plotRows.get(o)??[],i=new Set(s.flatMap(l=>B(r,l.rows,a)));this._plotRegistry.get(o)?.setSelection([...i])}}_wireLinks(e){const r=T(e.map),o=T(e.plot);for(const n of e.links??[]){const s=o.find(c=>$(c)===n.source),a=this._plotRegistry.get(n.source);if(!s||!a)throw new Error(`Link source "${n.source}" is not the id (or the dataRef) of a plot of this specification.`);const i=r.findIndex(c=>c.id===n.target),l=this._maps[i];if(i<0||!l)throw new Error(`Link target "${n.target}" is not the id of a map of this specification.`);const u=r[i].layerRefs.find(c=>n.layer!==void 0?L(c)===n.layer:c.dataRef===s.dataRef);if(!u)throw new Error(n.layer!==void 0?`Link from "${n.source}": map "${n.target}" has no layer "${n.layer}".`:`Link from "${n.source}": map "${n.target}" draws no layer of the table "${s.dataRef}"; name the layer.`);const d=this._layers.find(c=>c.mapIndex===i&&c.layerId===L(u));d&&(wt(a,this._plotRows.get(n.source)??[],s.events??[],d),pt(this._plotLinks,n.source,d))}}_rewireInteractions(e){for(const o of this._fwdCleanups)o();this._fwdCleanups=[];const r=T(e.map);this._maps.forEach((o,n)=>{const s=dt(r[n],n),a=({layerId:i,selection:l})=>{this.interactions.emit("map:picking",{mapId:s,layerId:i,selection:l})};o.events.on(k.MapEvent.PICKING,a),this._fwdCleanups.push(()=>o.events.off(k.MapEvent.PICKING,a))});for(const[o,n]of this._plotRegistry)for(const s of[P.PlotEvent.CLICK,P.PlotEvent.BRUSH,P.PlotEvent.BRUSH_X,P.PlotEvent.BRUSH_Y]){const a=({selection:i})=>{this.interactions.emit("plot:selection",{plotId:o,event:s,selection:i})};n.events.on(s,a),this._fwdCleanups.push(()=>n.events.off(s,a))}}}g.AutkGrammar=Ee,g.ColorMapInterpolator=tt,g.GrammarEventEmitter=Nt,g.NormalizationMode=x,g.STORAGE_BUFFER_BINDING_SIZE=Y,g.applyCamera=gt,g.arrangeViews=Dt,g.buildBatchedUniforms=Rt,g.computeLayerNames=_t,g.createComputeAdapter=Tt,g.createDataAdapter=lt,g.createEngine=z,g.enterWorkspace=I,g.findIterateSource=V,g.isFromFeature=R,g.joinWgsl=bt,g.maxBatchedFeatures=St,g.resolveComputeParams=J,g.resolveUniformMatrices=H,g.resolveUniforms=q,g.runCompute=It,g.tableKey=_,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})}));
|
|
1
|
+
(function(g,_){typeof exports=="object"&&typeof module<"u"?_(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"],_):(g=typeof globalThis<"u"?globalThis:g||self,_(g["autk-grammar"]={},g.autkDb,g.autkMap,g.autkPlot,g.autkCore,g.autkCompute))})(this,(function(g,_,T,k,E,et){"use strict";function ot(t){const{spec:e,adapters:o}=t;let r;async function n(){let l;if(e.workspaces?.length&&o.db.resolveWorkspaces&&(l=await o.db.resolveWorkspaces(l,e.workspaces)),e.data)for(const s of e.data)l=await o.db.resolveSource(l,s);if(e.compute)for(const s of e.compute)l=await o.compute.resolveCompute(l,s);if(e.map)if(Array.isArray(e.map))for(let s=0;s<e.map.length;s++){let u=e.map[s];await o.map.resolveMap(l,u,s)}else await o.map.resolveMap(l,e.map);if(e.plot)if(Array.isArray(e.plot))for(let s=0;s<e.plot.length;s++)await o.plot.resolvePlot(l,e.plot[s],s);else await o.plot.resolvePlot(l,e.plot);r=l}function i(l){return console.log("Spec to update",l),new Promise(s=>{s()})}function a(){console.log("Function not implemented yet")}return{run:n,updatedSpec:i,destroy:a,get context(){return r}}}function rt(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function Zt(t){const e=t.layout??{},o=e.type??"vertical";if(o!=="vertical"&&o!=="horizontal"&&o!=="grid")throw new Error(`Layout type must be vertical, horizontal or grid, not ${JSON.stringify(o)}.`);const r=e.gap??0;if(typeof r!="number"||!Number.isFinite(r)||r<0)throw new Error(`Layout gap must be a number of pixels, 0 or more, not ${JSON.stringify(r)}.`);const n=e.columns??2;if(!Number.isInteger(n)||n<1)throw new Error(`Layout columns must be a whole number, 1 or more, not ${JSON.stringify(n)}.`);const i=[...rt(t.map).map((s,u)=>({kind:"map",index:u,id:s.id,key:s.id??u})),...rt(t.plot).map((s,u)=>({kind:"plot",index:u,id:s.id,key:s.id??s.dataRef}))],a=o==="vertical"?1:o==="horizontal"?Math.max(i.length,1):n,l=i.map(({kind:s,index:u,id:d,key:c},f)=>({kind:s,index:u,...d!==void 0&&{id:d},key:c,row:Math.floor(f/a),column:f%a}));return{type:o,rows:Math.ceil(i.length/a),columns:a,gap:r,panes:l}}var nt=(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))(nt||{}),W=(t=>(t.MIN_MAX="minMax",t.PERCENTILE="percentile",t))(W||{});async function N(t,e){const o=e??_.DEFAULT_WORKSPACE_NAME;t.getCurrentWorkspace()!==o&&await t.setWorkspace(o)}function C(t,e){return t===void 0||t===_.DEFAULT_WORKSPACE_NAME?e:`${t}/${e}`}const te=Symbol.for("@urban-toolkit/autk-grammar:source-crs"),ee=globalThis,at=ee[te]??=new WeakMap;function oe(t,e){at.set(t,e)}function re(t,e){const o=t&&at.get(t);return o!==void 0&&o.toUpperCase()===e.toUpperCase()?t:void 0}function it(t){const e=new Set;for(const r of t)r?.id!=null&&e.add(JSON.stringify(r.id));const o=new Set;return t.map((r,n)=>{if(r?.id!=null)return r.id;let i=`autk-feature-${n}`;for(;e.has(JSON.stringify(i))||o.has(JSON.stringify(i));)i=`${i}-generated`;return o.add(JSON.stringify(i)),i})}function st(t){const e=new Map;return it(t).map(o=>{const r=JSON.stringify(o),n=e.get(r)??0;return e.set(r,n+1),n===0?r:`${r} ${n}`})}const lt=new WeakMap;function ne(t){let e=lt.get(t);return e||(e=new Map,t.forEach((o,r)=>{const n=e.get(o);n?n.push(r):e.set(o,[r])}),lt.set(t,e),e)}function B(t,e,o){const r=ne(o),n=new Set;for(const i of t){const a=e[i];if(a!==void 0)for(const l of r.get(a)??[])n.add(l)}return[...n]}const ae={type:"GeometryCollection",geometries:[]};function ie(t){const e=t.features??[],o=it(e);let r=!1;const n=e.map((a,l)=>a==null||a.id!=null&&a.geometry!=null?a:(r=!0,{...a,id:o[l],geometry:a.geometry??ae})),i=e.findIndex(a=>a?.geometry!=null);return i>0&&e[0]!=null&&e[0].geometry==null&&([n[0],n[i]]=[n[i],n[0]],r=!0),r?{...t,features:n}:t}function se(t){const{queryArea:e}=t;if(e.bbox===void 0)return{geocodeArea:e.geocodeArea,areas:e.areas};const o=s=>new Error(`OSM source "${t.outputTableName}": ${s}`);if(e.geocodeArea!==void 0||e.areas!==void 0)throw o("queryArea takes either bbox or geocodeArea with areas, not both.");const r=e.bbox;if(!Array.isArray(r)||r.length!==4||!r.every(s=>typeof s=="number"&&Number.isFinite(s)))throw o("queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.");const[n,i,a,l]=e.bbox;if(Math.abs(n)>180||Math.abs(a)>180)throw o("queryArea.bbox west and east must be longitudes from -180 to 180.");if(Math.abs(i)>90||Math.abs(l)>90)throw o("queryArea.bbox south and north must be latitudes from -90 to 90.");if(n>=a)throw o(`queryArea.bbox west (${n}) must be less than east (${a}); a box across the antimeridian is not supported.`);if(i>=l)throw o(`queryArea.bbox south (${i}) must be less than north (${l}).`);return{bbox:[n,i,a,l]}}function le(t){const{autoLoadLayers:e,...o}=t;if(t.pbfFileUrl!==void 0&&(t.tagSets?.length??0)>0)throw new Error(`OSM source "${t.outputTableName}": tagSets are read from the Overpass API only, so a source with pbfFileUrl cannot take them.`);return{...o,queryArea:se(t),autoLoadLayers:{layers:e?.layers??[],...e?.coordinateFormat!==void 0&&{coordinateFormat:e.coordinateFormat}}}}function ut(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 Q(t){return t===void 0||t===_.DEFAULT_WORKSPACE_NAME?"the default workspace":`the workspace "${t}"`}function ct(t){if(t!=null)return typeof t=="string"?t:JSON.stringify(t)}async function ue(t,e,o,r){const n=new Map;for(const l of(await t.getLayer(e.name)).features){const s=ct(l.properties?.[r]);if(s!==void 0){if(l.id===void 0||l.id===null)throw new Error("its rows have no feature id to update them by.");n.set(s,[...n.get(s)??[],l.id])}}const i=o.features.flatMap(l=>{const s=ct(l.properties?.[r]);return s===void 0?[]:(n.get(s)??[]).map(u=>({...l,id:u}))}),a=e.columns.some(l=>l.name==="geojson_id")?"geojson_id":"id";return{data:{...o,features:i},idColumn:a}}async function ft(t){if(t)return t;const e=new _.AutkDb;return await e.init(),e}function dt(t){let e=1/0,o=1/0,r=-1/0,n=-1/0;const i=l=>{if(Array.isArray(l)){if(typeof l[0]=="number"){const[s,u]=l;s<e&&(e=s),s>r&&(r=s),u<o&&(o=u),u>n&&(n=u);return}for(const s of l)i(s)}},a=l=>{l&&(l.type==="GeometryCollection"?l.geometries.forEach(a):i(l.coordinates))};for(const l of t.features??[])a(l?.geometry);return e<=r?[e,o,r,n]:void 0}function pt(t,e){function o(n,i){if(!i||!i.db)return;const a=document.getElementById(i.db);if(a){const l=n.getTablesMetadata();a.innerHTML+="<ul>";for(const s of l)a.innerHTML+=`<li>${s.name}: (${s.source}, ${s.type}) </li>`;a.innerHTML+="</ul>",a.innerHTML+=`<p>Number of tables: ${l.length}</p>`}}async function r(n,i,a){if(!e)return;const l=C(i,a),s=n.getTablesMetadata().find(u=>u.name===a);s&&_.isRenderableTable(s)?e.set(l,await n.getLayer(a)):e.delete(l)}return{async resolveWorkspaces(n,i){const a=await ft(n),l=new Set;for(const{name:s,coordinateFormat:u,precisionGrid:d}of i){const c=s??_.DEFAULT_WORKSPACE_NAME;if(l.has(c))throw new Error(`workspaces sets ${Q(s)} twice; give each workspace one entry.`);l.add(c);try{await a.setWorkspace(c,{coordinateFormat:u,precisionGrid:d})}catch(f){throw new Error(`workspaces, ${Q(s)}: ${f instanceof Error?f.message:String(f)}`)}}return await N(a),a},async resolveSource(n,i){const a=await ft(n),{workspace:l}=i;await N(a,l);let{type:s,workspace:u,...d}=i;switch(s){case"osm":return await a.loadOsm(le(d)),o(a,t),a;case"csv":return await a.loadCsv(d),o(a,t),a;case"json":return await a.loadJson(d),o(a,t),a;case"geojson":{const c=d;let f;c.geojsonFileUrl?f=await(await fetch(c.geojsonFileUrl)).json():f=c.geojsonObject,e&&f&&(e.set(C(l,c.outputTableName),f),oe(f,c.coordinateFormat??"EPSG:4326"));const h=f?(()=>{const p={...c,geojsonObject:ie(f)};return delete p.geojsonFileUrl,p})():c,m=/^EPSG:4326$/i.test(h.coordinateFormat??"EPSG:4326"),y=f&&m?dt(f):void 0;if(y&&(y[1]<-90||y[3]>90))throw new Error(`GeoJSON layer "${h.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${y.join(", ")}]), so they cannot be EPSG:4326 degrees. ${ut(h.coordinateFormat)}`);try{await a.loadGeojson(h)}catch(p){throw new Error(`Failed to load GeoJSON layer "${h.outputTableName}": ${p instanceof Error?p.message:String(p)}`)}try{const p=await a.getBoundingBoxFromLayer(h.outputTableName),w=25e6;if(!isFinite(p.minLon)||!isFinite(p.minLat)||!isFinite(p.maxLon)||!isFinite(p.maxLat)||Math.abs(p.minLon)>w||Math.abs(p.maxLon)>w||Math.abs(p.minLat)>w||Math.abs(p.maxLat)>w)throw new Error(`Geometry bounding box after transform is invalid for layer "${h.outputTableName}" (bbox: [${p.minLon}, ${p.minLat}, ${p.maxLon}, ${p.maxLat}]). ${ut(h.coordinateFormat)} The workspace uses ${a.getWorkspaceConfiguration().coordinateFormat}; input is expected in EPSG:4326 by default.`)}catch(p){if(p instanceof Error&&p.message.includes("bounding box after transform"))throw p}return o(a,t),a}case"geotiff":return await a.loadGeoTiff(d),o(a,t),a;case"heatmap":{const c=d;if(c.groupBy?.some(f=>f.aggregateFn==="collect"))throw new Error(`Heatmap "${c.outputTableName}": aggregateFn "collect" lists the rows near a cell, and a cell holds one value; use sum, avg, count, min, max or weighted.`);return await a.buildHeatmap({tableJoinName:c.joinDataRef,near:c.near,outputTableName:c.outputTableName,grid:c.grid,...c.groupBy&&{groupBy:c.groupBy}}),o(a,t),a}case"join":{const c=d;if(await a.spatialQuery({tableRootName:c.dataRef,tableJoinName:c.joinDataRef,...c.near&&{near:c.near},...c.groupBy&&{groupBy:c.groupBy}}),e){const f=await a.getLayer(c.dataRef);e.set(C(l,c.dataRef),f)}return o(a,t),a}case"sql":{const c=d;try{await a.rawQuery({query:c.query,output:{type:"CREATE_TABLE",tableName:c.outputTableName,source:"user",...c.layerType!==void 0&&{tableType:c.layerType}}})}catch(f){throw new Error(`SQL source "${c.outputTableName}": ${f instanceof Error?f.message:String(f)}`)}return e?.delete(C(l,c.outputTableName)),o(a,t),a}case"update":{const c=d,f=y=>new Error(`Update of "${c.dataRef}": ${y}`);if(c.geojsonObject===void 0==(c.jsonObject===void 0))throw f("give its rows in geojsonObject or in jsonObject, one of the two.");if(c.strategy==="update"&&!c.idColumn)throw f("the update strategy needs an idColumn, the column that matches a given row to the table's rows.");let h=c.geojsonObject??c.jsonObject,m=c.idColumn;try{const y=a.getTablesMetadata().find(p=>p.name===c.dataRef);if(c.strategy==="update"&&c.geojsonObject&&m?.startsWith("properties.")&&y&&_.isVectorTable(y)&&({data:h,idColumn:m}=await ue(a,y,c.geojsonObject,m.slice(11)),h.features.length===0))return o(a,t),a;await a.updateTable({tableName:c.dataRef,data:h,strategy:c.strategy,...m!==void 0&&{idColumn:m}})}catch(y){throw f(y instanceof Error?y.message:String(y))}return await r(a,l,c.dataRef),o(a,t),a}case"drop":{const c=d;if(!a.getTablesMetadata().some(f=>f.name===c.dataRef))throw new Error(`Drop of "${c.dataRef}": ${Q(l)} holds no table of that name.`);return await a.removeLayer(c.dataRef),e?.delete(C(l,c.dataRef)),o(a,t),a}default:throw new Error(`Unknown data source type "${String(s)}".`)}}}}function ht(t,e){return e===!0?`${t} osm-elements`:t}function mt(t){return t===!0?{osmElements:!0}:void 0}function yt(t,e,o){if(!t)return o();let r=t.get(e);return r||(r=o(),t.set(e,r)),r}function gt(t,e){return t?.id??e}function V(t,e){return e===void 0?!0:typeof e=="number"?t.mapIndex===e:t.mapId===e}function wt(t,e,o){const r=t?.get(e)??[];r.includes(o)||t?.set(e,[...r,o])}const bt=6378137,Y=.0818191908426215;function ce(t,e){if(t===void 0||typeof t=="number"&&Number.isFinite(t)&&t>0)return;const o=typeof t=="number"?String(t):JSON.stringify(t);throw new Error(`Layer "${e}": pointSize must be a number of meters greater than 0, not ${o}.`)}function fe(t){const e=Math.exp(-t/bt);let o=Math.PI/2-2*Math.atan(e);for(let r=0;r<10;r++){const n=Y*Math.sin(o),i=Math.PI/2-2*Math.atan(e*((1-n)/(1+n))**(Y/2));if(Math.abs(i-o)<1e-12)return i;o=i}return o}function de(t,e){if(/^EPSG:3395$/i.test(t)){const o=fe(e),r=Y*Math.sin(o);return Math.sqrt(1-r*r)/Math.cos(o)}return/^EPSG:3857$/i.test(t)?Math.cosh(e/bt):1}function pe(t,e,o,r){if(t===void 0||e!=="points")return;const n=r();if(n)return t*de(o,(n[1]+n[3])/2)}const j=/^#[0-9a-fA-F]{6}$/;function Et(t,e){if(t===void 0)return;if(!Array.isArray(t)||t.length!==2||!t.every(n=>typeof n=="number"&&Number.isFinite(n)))return"colorMapRange must hold two numbers, [low, high].";const[o,r]=t;if(o>=r)return`colorMapRange low (${o}) must be less than high (${r}).`;if(e!==void 0)return"set colorMapRange or colorMapDomain, not both."}function vt(t,e){return e&&e.length>0?{type:E.ColorMapDomainStrategy.USER,params:e}:t?.mode===W.PERCENTILE?t.lowerPercentile!==void 0||t.upperPercentile!==void 0?{type:E.ColorMapDomainStrategy.PERCENTILE,params:[t.lowerPercentile??0,t.upperPercentile??100]}:{type:E.ColorMapDomainStrategy.PERCENTILE}:{type:E.ColorMapDomainStrategy.MIN_MAX}}function v(t){return typeof t.title=="string"&&t.title!==""?t.title:t.dataRef}function he(t,e){const o=new Set;for(const r of t.layerRefs){const n=v(r);if(o.has(n))throw new Error(`Map ${e} draws two layers with the id "${n}". A layer's id is its title, else its dataRef: give each layer of a map its own title.`);o.add(n)}}function _t(t,e,o){if(!j.test(t))throw new Error(`Layer "${o}": ${e} must be a color written #rrggbb, not "${t}".`);return E.ColorMap.hexToRgb(t)}function me(t,e){const o={};return t.color!=null&&(o.color=_t(t.color,"color",e)),t.stroke===!1?o.showBorders=!1:t.stroke!=null&&(o.strokeColor=_t(t.stroke,"stroke",e)),t.width!=null&&(o.polylinesWidth=t.width),o}function ye(t,e){return t.isColorMap!=null?t.isColorMap:e==="raster"?t.colorMapInterpolator!=null||t.colorMapRange!=null||t.colorMapCenter!=null||t.colorMapReverse===!0||t.legend===!0:t.color!=null?!1:t.colorMapInterpolator!=null||t.getFnv!=null}function ge(t,e){const o=t.features?.[0]?.properties?.[e];return o instanceof Float32Array?o:ArrayBuffer.isView(o)&&!(o instanceof DataView)||Array.isArray(o)?Float32Array.from(o,r=>Number.isFinite(Number(r))?Number(r):NaN):null}function we(t,e,o,r,n){if(E.ColorMap.isCategorical(e.interpolator))return;if(n!=null){const u=o!=null?[n[0],o,n[1]]:[n[0],n[1]];return r===!0?u.reverse():u}if(!t)return;let i=0,a=0;for(let u=0;u<t.length;u++){const d=t[u];Number.isFinite(d)&&(a++,o!=null&&(i=Math.max(i,Math.abs(d-o))))}const l=o!=null&&i>0;if(a===0||!l&&r!==!0)return;const s=l&&o!=null?[o-i,o,o+i]:E.ColorMap.resolveDomainFromData(t,e);return r===!0?[...s].reverse():s}function be(t,e){if(!(e==null||E.ColorMap.isCategorical(t.interpolator)))return[e[0],e[1]]}function Ee(t){const e=t.colorMapRange;if(e===void 0)return;const o=l=>new Error(`Layer "${v(t)}": ${l}`),r=Et(e,t.colorMapDomain);if(r)throw o(r);const[n,i]=e,a=t.colorMapCenter;if(a!=null&&(a<n||a>i))throw o(`colorMapCenter (${a}) must lie within colorMapRange [${n}, ${i}].`)}const H=["background","surface","parks","water","roads","buildings","points","polylines","polygons"];function ve(t,e){const o=n=>new Error(`Map ${e}: ${n}`),r=t.style;if(r!==void 0&&typeof r!="string"){if(r===null||typeof r!="object"||Array.isArray(r))throw o(`style must be the name of one of autk-map's styles or the colors of a style, not ${JSON.stringify(r)}.`);const n=H.filter(i=>!(i in r));if(n.length>0)throw o(`style gives no color for ${n.join(", ")}: a style of the spec's own gives each of ${H.join(", ")}.`);for(const i of H){const a=r[i];if(typeof a!="string"||!j.test(a))throw o(`style.${i} must be a color written #rrggbb, not ${JSON.stringify(a)}.`)}}for(const n of["highlightColor","invalidValueColor"]){const i=t[n];if(i!==void 0&&(typeof i!="string"||!j.test(i)))throw o(`${n} must be a color written #rrggbb, not ${JSON.stringify(i)}.`)}}function _e(t,e){typeof e.style=="string"?t.style.setPredefinedStyle(e.style):e.style&&t.style.setCustomStyle(e.style),e.highlightColor!==void 0&&t.style.setHighlightColor(e.highlightColor),e.invalidValueColor!==void 0&&t.style.setInvalidValueColor(e.invalidValueColor)}function Ce(t,e){const o=t.widthBy;if(o!==void 0){if(typeof o!="string"||o==="")throw new Error(`Layer "${e}": widthBy must be the dot path to each line's width, not ${JSON.stringify(o)}.`);if(t.width!==void 0)throw new Error(`Layer "${e}": set width or widthBy, not both: width gives every line one width.`)}}function Me(t,e,o,r,n){if(r!=="roads")throw new Error(`Layer "${e}": widthBy sets the width of each line of a roads layer, and the layer is drawn as ${r}: draw a table of lines as roads with layerType: 'roads'.`);const i=t.layerManager.searchByLayerId(e),a=i?.components??[],l=new Float32Array(a.length);l.set(i?.layerRenderInfo.polylinesWidthByComponent?.subarray(0,a.length)??[]);const s=o.startsWith("properties.")?o.slice(11):o;let u=0;if(a.forEach((d,c)=>{const f=n.features[d.featureIndex??c],h=Number(St(f?.properties,s));Number.isFinite(h)&&h>0&&(l[c]=h,u++)}),u===0)throw new Error(`Layer "${e}": widthBy "${o}" gives no line of the layer a width: none has a positive number there.`);t.updateRenderInfo(e,{polylinesWidthByComponent:l})}function Se(t,e){const o=t.layerRefs.filter(r=>r.legend===!0).map(v);if(o.length>1)throw new Error(`Map ${e}: layers ${o.map(r=>`"${r}"`).join(" and ")} each set legend: a map shows one legend.`);if(o.length===1&&t.showUi===!1)throw new Error(`Layer "${o[0]}": legend shows the layer in the map's legend, and the map's showUi is false, which hides the legend.`)}function $e(t,e){const o=e.layerRefs.find(i=>i.legend===!0);if(!o)return;const r=v(o),n=t.layerManager.searchByLayerId(r);if(!n?.layerRenderInfo.isColorMap)throw new Error(`Layer "${r}": legend shows the color scale of a layer colored by value, and the layer is drawn in one color.`);t.ui.activeLayer=n,t.ui.refreshLegend(null)}const Ae=[{types:["points"],drawn:"a table of points is drawn as points"},{types:["polylines","roads"],drawn:"a table of lines is drawn as polylines or roads"},{types:["polygons","surface","parks","water","buildings"],drawn:"a table of polygons is drawn as polygons, surface, parks, water or buildings"},{types:["raster"],drawn:"a raster table is drawn as raster"}];function Re(t,e,o){const r=t.layerType;if(r===void 0||e===void 0)return r??e;const n=Ae.find(i=>i.types.includes(e));if(!n||n.types.includes(r))return r;throw new Error(`Layer "${o}": layerType "${r}" cannot draw the table "${t.dataRef}", a ${e} table: ${n.drawn}.`)}function Ct(t,e,o){if(!Array.isArray(t)||!t.every(r=>Number.isInteger(r)&&r>=0))throw new Error(`Layer "${o}": ${e} must list the positions of features the layer draws, whole numbers from 0, not ${JSON.stringify(t)}.`)}function Mt(t,e,o,r,n){if(r==="raster")throw new Error(`Layer "${o}": ${e} names features, and a raster layer has none.`);const i=t.find(a=>a>=n);if(i!==void 0)throw new Error(`Layer "${o}": ${e} names position ${i}, past the ${n} features the layer draws.`)}function ke(t){t.layerRefs.forEach((e,o)=>{if(e.pickedComps===void 0)return;const r=v(e);if(Ct(e.pickedComps,"pickedComps",r),e.isPick!==!0)throw new Error(`Layer "${r}": pickedComps draws features as picked, which autk-map does only on the layer that picks: set isPick: true.`);const n=t.layerRefs.slice(o+1).find(i=>i.isPick===!0);if(n)throw new Error(`Layer "${r}": pickedComps draws features as picked on the layer that picks, but layer "${v(n)}", after it, picks too: autk-map lets one layer of a map pick, the last.`)})}function St(t,e){return e.split(".").reduce((o,r)=>{if(!(o==null||typeof o!="object"))return o[r]},t)}function Ie(t,e,o){const r=e.split("."),n={...t};let i=n;for(let a=0;a<r.length-1;a++)i[r[a]]={...i[r[a]]??{}},i=i[r[a]];return i[r[r.length-1]]=o,n}function $t(t,e,o){const n=t.features?.[0]?.properties?.bands??[];if(e===void 0)return n[0]?.id??"";const i=n.find(a=>a.id===e||a.label===e.replace(/\./g,"_"));if(i)return i.id;if(n.length>1){const a=n.map(l=>l.label&&l.label!==l.id?`${l.id} (${l.label})`:l.id);throw o(`"${e}" names none of its ${n.length} bands: ${a.join(", ")}.`)}return n[0]?.id??e}function At(t){const{pitch:e}=t;return e===void 0||typeof e=="number"&&e>=0&&e<90?void 0:`camera.pitch must be at least 0 and less than 90 degrees, not ${typeof e=="number"?String(e):JSON.stringify(e)}: at 90 the eye would sit on the ground, edge-on to the map's flat layers, and the map could not pan.`}function Rt(t,e){const o=At(e);if(o)throw new Error(o);if(e.zoom===void 0&&!e.pitch&&!e.bearing)return;const r=t.camera,[n,i]=r.getLookAt(),a=e.zoom!==void 0?1e4/Math.pow(2,e.zoom-10):Math.abs(r.getEye()[2]),l=(e.pitch??0)*Math.PI/180,s=(e.bearing??0)*Math.PI/180,u=[n-a*Math.sin(l)*Math.sin(s),i-a*Math.sin(l)*Math.cos(s),a*Math.cos(l)],d=[Math.cos(l)*Math.sin(s),Math.cos(l)*Math.cos(s),Math.sin(l)];r.resetCamera(d,[n,i,0],u)}async function Le(t,e,o,r){const n=s=>new Error(`Map ${r}: terrain ${s}`),i=e.getTablesMetadata().find(s=>s.name===o.dataRef);if(!i)throw n(`dataRef "${o.dataRef}" names no table of the map's workspace.`);if(i.type!=="raster")throw n(`dataRef "${o.dataRef}" names a ${i.type??"plain"} table, and a terrain takes its heights from a raster table, such as a geotiff source's.`);const a=await e.getRaster(o.dataRef),l=$t(a,o.band,s=>n(`band ${s}`));try{t.enableTerrainMode(a,l)}catch(s){throw n(`"${o.dataRef}": ${s instanceof Error?s.message:String(s)}`)}}function Ne(t,e,o,r){const i=t.layerManager.searchByLayerId(e)?.components;return Array.isArray(i)?i.map((a,l)=>{const s=Number.isInteger(a?.featureIndex)?a.featureIndex:l;return o[r[s]]??""}):r.map(a=>o[a]??"")}function Pe(t,e,o,r,n,i){async function a(l,s,u){let d={};for(const f of s.getTablesMetadata())f.type!==void 0&&(d[f.name]=f.type);const c=[];for(const f of u.layerRefs){const h=f.dataRef,m=v(f),y=C(u.workspace,h),p=Re(f,n?.get(y)??d[h],m),w=f.getFnv,$=o?.get(y)??(p==="raster"?await s.getRaster(h):await yt(i,ht(y,f.osmElements),()=>s.getLayer(h,mt(f.osmElements)))),A=$.features??[],P=p==="raster"?[]:A.flatMap((b,R)=>b?.geometry!=null?[R]:[]),L=p==="raster"?$:{...$,features:P.map(b=>A[b])},Vt=p==="raster"?$t(L,w,b=>new Error(`Layer "${m}": getFnv ${b}`)):"";if(p==="raster")l.loadCollection(m,{collection:L,type:"raster",property:Vt});else{const b=p==="buildings"&&f.buildingsZeroHeight===!0;l.loadCollection(m,{collection:L,type:p,...b?{loadConfig:{buildingsZeroHeight:!0}}:{}})}f.opacity!=null&&l.updateRenderInfo(m,{opacity:f.opacity});const Yt=me(f,m);Object.keys(Yt).length>0&&l.updateRenderInfo(m,Yt),f.widthBy!==void 0&&Me(l,m,f.widthBy,p,L);const ro=s.getWorkspaceConfiguration().coordinateFormat,Ht=pe(f.pointSize,p,ro,()=>dt(L));Ht!==void 0&&l.updateRenderInfo(m,{pointSize:Ht}),ye(f,p)&&l.updateRenderInfo(m,{isColorMap:!0}),f.isPick&&l.updateRenderInfo(m,{isPick:!0}),f.isSkip&&l.updateRenderInfo(m,{isSkip:!0});const{catchAllCategory:x,colorMapDomain:F}=f;let Jt=L,qt=F;if(w&&x&&F?.length){const b=new Set(F);Jt={...L,features:L.features.map(R=>{const Xt=R.properties,tt=St(Xt,w);return tt==null||!b.has(String(tt))?{...R,properties:Ie(Xt,w,x)}:R})},qt=b.has(x)?F:[...F,x]}const Kt=p==="raster"&&f.transferFunction!=null;Kt&&l.layerManager.searchByLayerId(m)?.setTransferFunction?.(f.transferFunction);const U=f.colorMapRange,zt=p==="raster"&&(U!=null||f.colorMapCenter!=null||f.colorMapReverse===!0);if(f.colorMapInterpolator||zt||U){const b={interpolator:f.colorMapInterpolator??l.layerManager.searchByLayerId(m)?.layerRenderInfo.colormap.config.interpolator??E.ColorMapInterpolator.SEQ_REDS,domainSpec:vt(f.normalization,qt)};let R;zt?R=we(ge(L,Vt),b,f.colorMapCenter,f.colorMapReverse,U):p!=="raster"&&(R=be(b,U)),R&&(b.domainSpec={type:E.ColorMapDomainStrategy.USER,params:R}),l.updateColorMap(m,{colorMap:b})}else Kt&&l.updateColorMap(m,{colorMap:{}});if(w&&p!=="raster"){const b=w.startsWith("properties.")?w:`properties.${w}`;l.updateThematic(m,{collection:Jt,property:b})}const Z=p==="raster"?[]:Ne(l,m,st(A),P);f.pickedComps&&Mt(f.pickedComps,"pickedComps",m,p,Z.length),f.skippedComps&&(Mt(f.skippedComps,"skippedComps",m,p,Z.length),l.layerManager.searchByLayerId(m)?.setSkippedIds(f.skippedComps)),c.push(Z)}return c}return{async resolveMap(l,s,u=0){if(t&&t.map&&l){he(s,u);for(const y of s.layerRefs)Ee(y),ce(y.pointSize,v(y)),y.skippedComps!==void 0&&Ct(y.skippedComps,"skippedComps",v(y)),Ce(y,v(y));ke(s),ve(s,u),Se(s,u);const d=s.camera&&At(s.camera);if(d)throw new Error(`Map ${u}: ${d}`);let c;if(Array.isArray(t.map)?c=document.getElementById(t.map[u]):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 f=s.showUi===!1?new T.AutkMap(c,!1):new T.AutkMap(c);let h;try{_e(f,s),await f.init(),await N(l,s.workspace),h=await a(f,l,s),s.terrain&&await Le(f,l,s.terrain,u),$e(f,s)}catch(y){try{f.destroy()}catch{}throw y}const m=gt(s,u);s.layerRefs.forEach((y,p)=>e?.push({map:f,mapIndex:u,mapId:m,layerId:v(y),dataRef:y.dataRef,rows:h[p]})),r&&(r[u]=f),s.camera&&Rt(f,s.camera),f.draw()}}}}function S(t){return t.id??t.dataRef}const Te=new Set(Object.values(E.ColorMapInterpolator));function kt(t,e,o){if(e!==void 0){if(typeof e!="string"||!Te.has(e))return`${t} ${JSON.stringify(e)} is not a color scheme.`;if(E.ColorMap.isCategorical(e)!==o)return o?`${t} "${e}" is not a categorical scheme: categories take a scheme* scheme, such as schemeTableau10.`:`${t} "${e}" is a categorical scheme: numbers take an interpolate* scheme, and categories take categoricalColorMapInterpolator.`}}const Oe=/^(?:.?[<>=^])?[-+( ]?[$#]?0?\d*,?(?:\.\d+)?~?[a-zA-Z%]?$/;function Fe(t){if(t===void 0)return;if(!Array.isArray(t)||t.length!==2)return"tickFormats must hold two d3-format specifiers, [x, y].";const e=t.findIndex(o=>typeof o!="string"||!Oe.test(o));if(e>=0)return`tickFormats[${e}] ${JSON.stringify(t[e])} is not a d3-format specifier, such as "~s", ",d" or ".0%".`}function Be(t,e){if(t===void 0)return;if(!Array.isArray(t)||!t.every(r=>typeof r=="string"))return"axisLabels must be a list of titles, one for each column of axis.";if(t.length>e.length)return`axisLabels has ${t.length} titles for the ${e.length} columns of axis.`;const o=t.find((r,n)=>t.indexOf(r)!==n);if(o!==void 0)return`axisLabels gives two axes the title ${JSON.stringify(o)}.`}function It(t,e){if(!(e===void 0||typeof e=="string"&&j.test(e)))return`${t} must be a color written #rrggbb, not ${JSON.stringify(e)}.`}function je(t){if(t!==void 0&&(!Array.isArray(t)||!t.every(e=>Number.isInteger(e)&&e>=0)))return"selection must list the positions of rows, whole numbers from 0."}function De(t){const e=kt("colorMapInterpolator",t.colorMapInterpolator,!1)??kt("categoricalColorMapInterpolator",t.categoricalColorMapInterpolator,!0)??Et(t.colorMapRange,t.colorMapDomain)??Fe(t.tickFormats)??Be(t.axisLabels,t.axis)??je(t.selection)??It("markColor",t.markColor)??It("highlightColor",t.highlightColor);if(e)throw new Error(`Plot "${S(t)}": ${e}`)}function Ge(t){const e={};for(const[o,r]of[["markColor","mark"],["highlightColor","highlight"]]){let n;for(const i of t){const a=i[o];if(a!==void 0){if(n&&n[o].toLowerCase()!==a.toLowerCase())throw new Error(`Plots "${S(n)}" and "${S(i)}" set different ${o} values, "${n[o]}" and "${a}": autk-plot draws every plot of a page in one ${r} color.`);n??=i}}n&&(e[o]=n[o])}return e}function xe(t,e){const o=t.selection?.find(r=>r>=e);if(o!==void 0)throw new Error(`Plot "${S(t)}": selection names row ${o}, but the plot draws ${e===1?"1 row":`${e} rows`}.`)}function Ue(t,e){return t===void 0||t==="@transform"?!1:e.some(o=>{const r=E.valueAtPath(o?.properties??{},t);return typeof r=="string"&&isNaN(Number(r))})}function We(t,e){const o=t.colorMapRange;if(o!==void 0&&!Ue(t.color,e))return{type:E.ColorMapDomainStrategy.USER,params:[o[0],o[1]]};if(!(t.normalization===void 0&&t.colorMapDomain===void 0))return vt(t.normalization,t.colorMapDomain)}function Qe(t){return t.axis.map((e,o)=>t.axisLabels?.[o]??(e==="@transform"?"value":e))}function Ve(t,e){const o=We(t,e);return{labels:{axis:Qe(t),title:t.title},...t.colorMapInterpolator!==void 0&&{colorMapInterpolator:t.colorMapInterpolator},...t.categoricalColorMapInterpolator!==void 0&&{categoricalColorMapInterpolator:t.categoricalColorMapInterpolator},...o&&{domainSpec:o},...t.tickFormats!==void 0&&{tickFormats:[...t.tickFormats]}}}function Ye(t){return{scatter:"scatterplot",bar:"barchart",line:"linechart",linechart:"linechart","parallel-coordinates":"parallel-coordinates",table:"table",heatmatrix:"heatmatrix"}[t]}let D;function He(t){t.markColor===void 0&&t.highlightColor===void 0&&!D||(D??={markColor:k.PlotStyle.default,highlightColor:k.PlotStyle.highlight},k.PlotStyle.setDefaultColor(t.markColor??D.markColor),k.PlotStyle.setHighlightColor(t.highlightColor??D.highlightColor))}function Lt(t,e,o,r){const{map:n,layerId:i}=r;n.updateRenderInfo(i,{isPick:!0}),n.events.on(T.MapEvent.PICKING,({layerId:a,selection:l})=>{a===i&&t.setSelection(B(l,r.rows,e))});for(const a of o)t.events.on(a,({selection:l})=>{n.setHighlightedIds(i,B(l,e,r.rows))})}async function Je(t,e,o,r,n){const i=t.getTablesMetadata().find(a=>a.name===e);return i&&!_.isRenderableTable(i)?{type:"FeatureCollection",features:(await t.getTable(e)).map(l=>({type:"Feature",geometry:null,properties:l}))}:yt(r,ht(o,n),()=>t.getLayer(e,mt(n)))}function qe(t,e,o,r,n,i,a,l){return{async resolvePlot(s,u,d=0){if(!t||!t.plot)return;const c=Array.isArray(t.plot)?t.plot[d]:t.plot;if(c===void 0)throw new Error(`Plot ${d} has no target: the plot targets name ${t.plot.length} elements.`);const f=document.getElementById(c);if(!f)throw new Error(`Could not find plot target: ${c}`);const h=s;if(!h)throw new Error("No data context available for plot.");await N(h,u.workspace);const m=C(u.workspace,u.dataRef),y=u.osmElements===!0?void 0:n?.get(m),p=i?.get(m)??y??await Je(h,u.dataRef,m,l,u.osmElements);xe(u,p.features?.length??0);const w=u.events??[],$=new k.AutkPlot(f,{type:Ye(u.mark),collection:p,attributes:{axis:u.axis,...u.color&&{color:u.color}},events:w,...Ve(u,p.features??[]),...u.width&&{width:u.width},...u.height&&{height:u.height},...u.margins&&{margins:u.margins},...u.transform&&{transform:u.transform}});u.mark==="scatter"&&u.color!==void 0&&$.setSelection([]),o?.set(S(u),$);const A=st(p.features??[]);a?.set(S(u),A);for(const P of e??[])!u.mapRef||P.dataRef!==u.mapRef||(Lt($,A,w,P),wt(r,S(u),P))}}}const J=134217728,Ke=4,ze=32;function Nt(t){return Array.isArray(t)?t.join(`
|
|
2
|
+
`):t}function I(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.fromFeature=="object"&&t.fromFeature!==null}function O(t,e){return t instanceof Map?t.get(e):t[e]}function G(t,e){return e.split(".").reduce((o,r)=>{if(!(o==null||typeof o!="object"))return o[r]},t)}function Pt(t){const e=[];for(const o of[t.uniforms,t.uniformMatrices])for(const r of Object.values(o??{}))I(r)&&e.push(r);return e}function Tt(t){return[...new Set([t.dataRef,...Pt(t).map(e=>e.fromFeature.layer)])]}function q(t){for(const e of Pt(t)){const{iterate:o,layer:r}=e.fromFeature;if(o==="all"||o==="batched")return{mode:o,layer:r}}return null}function Ot(t,e,o){const r=t.fromFeature,n=o!==void 0&&r.iterate==="all"?o:r.index??0,i=O(e,r.layer)?.features?.[n];return i?G(i,r.path):void 0}function K(t,e,o){if(!t)return;const r={};for(const[n,i]of Object.entries(t)){if(!I(i)){r[n]=i;continue}const a=Number(Ot(i,e,o)??NaN);Number.isFinite(a)?r[n]=a:typeof i.default=="number"&&(r[n]=i.default)}return r}function z(t,e,o){if(!t)return;const r={};for(const[n,i]of Object.entries(t)){if(!I(i)){r[n]=i;continue}const a=Ot(i,e,o),l=Array.isArray(a)?a:Array.isArray(i.default)?i.default:void 0;if(!l)continue;const s=i.cols??(Array.isArray(l[0])?l[0].length:0);s>0?r[n]={data:l,cols:s}:console.warn(`[autk-grammar] uniform matrix "${n}" has no column count; entry dropped`)}return r}function Xe(t){return t!=null&&!(typeof t=="number"&&!Number.isFinite(t))}function Ft(t){return I(t)&&t.fromFeature.iterate==="batched"}function Bt(t,e){return Object.values(e??{}).some(Ft)?ze:Object.values(t??{}).some(Ft)?Ke:0}function jt(t,e,o=J){const r=Bt(t,e);return r>0?Math.floor(o/r):Number.POSITIVE_INFINITY}function Dt(t,e,o,r=J){const n={},i={},a=[];for(const s of[t,e])for(const u of Object.values(s??{}))I(u)&&u.fromFeature.iterate==="batched"&&u.fromFeature.required&&a.push(u.fromFeature.path);if(a.length>0){const s=o.length;o=o.filter(u=>a.every(d=>Xe(G(u,d)))),o.length<s&&console.info(`[autk-grammar] batched compute dropped ${s-o.length} feature(s) missing ${a.join(", ")}`)}const l=jt(t,e,r);o.length>l&&(console.warn(`[autk-grammar] batched compute capped at ${l} features (got ${o.length}): its largest packed array takes ${Bt(t,e)} B per feature, and a storage buffer binding holds ${r} B`),o=o.slice(0,l));for(const[s,u]of Object.entries(t??{}))if(I(u)&&u.fromFeature.iterate==="batched"){const d=typeof u.default=="number"?u.default:void 0;i[s]=o.map(c=>{const f=Number(G(c,u.fromFeature.path)??d);return Number.isFinite(f)?f:0})}else typeof u=="number"&&(n[s]=u);for(const[s,u]of Object.entries(e??{})){if(!I(u)||u.fromFeature.iterate!=="batched")continue;const d=[];for(const c of o){const f=G(c,u.fromFeature.path);let h=1/0,m=1/0,y=-1/0,p=-1/0;if(Array.isArray(f))for(const w of f){if(!Array.isArray(w)||w.length<2)continue;const $=Number(w[0]),A=Number(w[1]);!Number.isFinite($)||!Number.isFinite(A)||(h=Math.min(h,$),m=Math.min(m,A),y=Math.max(y,$),p=Math.max(p,A))}Number.isFinite(h)||(h=0,m=0,y=0,p=0),d.push(h,m,y,m,y,p,h,p)}i[s]=d}return n.num_features=o.length,{uniforms:n,uniformArrays:i}}function X(t,e,o){const r=O(e,t.dataRef);if(!r)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const n={collection:r,variableMapping:t.attributes,wgslBody:Nt(t.wgslFunction)};t.attributeArrays&&(n.attributeArrays=t.attributeArrays),t.attributeMatrices&&(n.attributeMatrices=t.attributeMatrices),t.uniformArrays&&(n.uniformArrays=t.uniformArrays),t.outputColumnName&&(n.resultField=t.outputColumnName),t.outputColumns&&(n.outputColumns=t.outputColumns);const i=q(t);if(i?.mode==="batched"){const u=O(e,i.layer)?.features??[],d=Dt(t.uniforms,t.uniformMatrices,u),c=K(Gt(t.uniforms),e)??{},f=z(Gt(t.uniformMatrices),e);return n.uniforms={...c,...d.uniforms},n.uniformArrays={...n.uniformArrays??{},...d.uniformArrays},f&&Object.keys(f).length>0&&(n.uniformMatrices=f),n}const a=i?.mode==="all"?o:void 0,l=K(t.uniforms,e,a),s=z(t.uniformMatrices,e,a);return l&&(n.uniforms=l),s&&(n.uniformMatrices=s),n}function Gt(t){if(t)return Object.fromEntries(Object.entries(t).filter(([,e])=>!(I(e)&&e.fromFeature.iterate==="batched")))}function Ze(t){return t.outputColumns??(t.outputColumnName?[t.outputColumnName]:[])}async function xt(t,e,o){const r=q(t);if(r?.mode!=="all")return o(X(t,e));const n=O(e,t.dataRef);if(!n)throw new Error(`compute: table "${t.dataRef}" is not loaded`);const i=Ze(t),a=structuredClone(n);for(const s of a.features){const u=s.properties??={},d=u.compute??={};for(const c of i)d[c]=0}const l=O(e,r.layer)?.features?.length??0;for(let s=0;s<l;s++){const u=await o({...X(t,e,s),collection:a});a.features.forEach((d,c)=>{const f=d.properties?.compute,h=u.features[c]?.properties?.compute;if(!(!f||!h))for(const m of i){const y=Number(h[m]);Number.isFinite(y)&&(f[m]+=y)}})}return a}const Ut=["surface","parks","water","roads","buildings","polygons","polylines"];function to(t,e,o,r){return r?.get(C(o,e))??t.getTablesMetadata().find(n=>n.name===e)?.type}function Wt(t,e,o){async function r(l,s,u){return t?.get(C(u,s))??await l.getLayer(s)}function n(l,s,u,d,c){if(!t)return;const f=d.outputTableName??u;t.set(C(d.workspace,f),s);const h=d.layerType??c??to(l,u,d.workspace,e);d.outputTableName&&h&&e?.set(C(d.workspace,f),h)}async function i(l,s){for(const c of s.layers)if(!Ut.includes(c.type))throw new Error(`Render pass "${s.outputTableName}": layer "${c.id}" has the type "${c.type}", which a render pass cannot draw. A layer's type is one of ${Ut.join(", ")}.`);const u=await Promise.all(s.layers.map(async c=>({id:c.id,collection:await r(l,c.dataRef,s.workspace),type:c.type,objectIdProperty:c.objectIdProperty}))),d=await new et.AutkComputeEngine().renderPipeline({layers:u,viewpoints:{collection:await r(l,s.viewpoints.dataRef,s.workspace),strategy:s.viewpoints.strategy,sampling:s.viewpoints.sampling},aggregation:s.aggregation,camera:s.camera,tileSize:s.tileSize});n(l,d,s.viewpoints.dataRef,s,s.viewpoints.strategy?.type==="building-windows"?"points":void 0)}async function a(l,s){const u={},d=l.getWorkspaceConfiguration().coordinateFormat;for(const h of Tt(s)){const m=C(s.workspace,h),y=t?.get(m)??(h===s.dataRef?void 0:re(o?.get(m),d));if(y)u[h]=y;else if(h===s.dataRef)u[h]=await l.getLayer(h);else try{u[h]=await l.getLayer(h)}catch{u[h]=void 0}}const c=new et.AutkComputeEngine,f=await xt(s,u,h=>c.gpgpuPipeline(h));n(l,f,s.dataRef,s)}return{async resolveCompute(l,s){if(l)return await N(l,s.workspace),s.type==="render"?await i(l,s):await a(l,s),l}}}class Qt{_listeners=new Map;on(e,o){this._listeners.has(e)||this._listeners.set(e,new Set);const r=this._listeners.get(e);return r.add(o),()=>r.delete(o)}emit(e,o){this._listeners.get(e)?.forEach(r=>r(o))}}function M(t){return t===void 0?[]:Array.isArray(t)?t:[t]}function eo(t){const e=new Set;for(const r of[...M(t.map),...M(t.plot)])if(r.id!==void 0){if(r.id==="")throw new Error("A map or plot has an empty id.");if(e.has(r.id))throw new Error(`Two maps or plots have the id "${r.id}"; an id names one view.`);e.add(r.id)}const o=new Map;for(const r of M(t.plot)){const n=S(r),i=o.get(n);if(i)throw new Error(i.id===void 0&&r.id===void 0?`Two plots of the table "${n}" have no id; give each plot an id.`:`A plot's id "${n}" is the dataRef of a plot without an id; give each plot an id.`);o.set(n,r)}}class oo{dataAdapter;mapAdapter;plotAdapter;computeAdapter;grammarEngine;_computeCache=new Map;_computeTypes=new Map;_data={};_layers=[];_maps=[];_plotRegistry=new Map;_fwdCleanups=[];_plotLinks=new Map;_plotRows=new Map;_exports=new Map;_geojsonCache=new Map;interactions=new Qt;constructor(e){this.dataAdapter=pt(e,this._geojsonCache),this.mapAdapter=Pe(e,this._layers,this._computeCache,this._maps,this._computeTypes,this._exports),this.plotAdapter=qe(e,this._layers,this._plotRegistry,this._plotLinks,this._geojsonCache,this._computeCache,this._plotRows,this._exports),this.computeAdapter=Wt(this._computeCache,this._computeTypes,this._geojsonCache)}get workspaceCrs(){return _.DEFAULT_WORKSPACE_COORDINATE_FORMAT}get data(){return this._data}get maps(){return this._maps}mapLayers(e,o){return this._layersOf(e,o).map(({map:r,layerId:n})=>({map:r,layerId:n}))}mapLayer(e,o){return this.mapLayers(e,o).pop()}_layersOf(e,o){return this._layers.filter(r=>r.dataRef===e&&V(r,o))}destroy(){for(const e of this._fwdCleanups)e();this._fwdCleanups=[];for(const e of this._maps)e.destroy();this._maps.length=0,this._layers.length=0,this._plotRegistry.clear(),this._plotLinks.clear(),this._plotRows.clear(),this._exports.clear(),this._geojsonCache.clear(),this._computeCache.clear(),this._computeTypes.clear(),this.grammarEngine=void 0,this._data={}}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.");eo(e);for(const i of M(e.plot))De(i);const o=Ge(M(e.plot));this.destroy(),M(e.plot).length>0&&He(o),this.grammarEngine=ot({spec:e,adapters:{db:this.dataAdapter,map:this.mapAdapter,plot:this.plotAdapter,compute:this.computeAdapter}}),await this.grammarEngine.run();const r=this.grammarEngine.context;if(r&&await N(r),this._wireLinks(e),this._pickFromTheStart(e),this._selectFromTheStart(e),this._rewireInteractions(e),!r){console.warn("Grammar engine produced no data context."),this._data={};return}const n={};for(const i of r.getLayersMetadata())Object.defineProperty(n,i.name,{get:()=>{const a=this._computeCache.get(i.name);return a?Promise.resolve(a):r.getLayer(i.name)},enumerable:!0,configurable:!0});for(const i of this._computeCache.keys())i in n||Object.defineProperty(n,i,{get:()=>Promise.resolve(this._computeCache.get(i)),enumerable:!0,configurable:!0});this._data=n}highlightOnMap(e,o,r){const n=this._layersOf(e,r);for(const{map:i,layerId:a}of n)i.setHighlightedIds(a,o);this._selectInLinkedPlots(n,o)}clearHighlightOnMap(e,o){const r=this._layersOf(e,o);for(const{map:n,layerId:i}of r)n.clearHighlightedIds(i);this._selectInLinkedPlots(r,[])}clearHighlightOnPlot(e,o){this._plotRegistry.get(e)?.setSelection([]);for(const r of this._plotLinks.get(e)??[])V(r,o)&&r.map.clearHighlightedIds(r.layerId)}setPlotSelection(e,o,r){this._plotRegistry.get(e)?.setSelection(o);const n=this._plotRows.get(e)??[];for(const i of this._plotLinks.get(e)??[])V(i,r)&&i.map.setHighlightedIds(i.layerId,B(o,n,i.rows))}_selectInLinkedPlots(e,o){for(const[r,n]of this._plotLinks){const i=n.filter(s=>e.includes(s));if(i.length===0)continue;const a=this._plotRows.get(r)??[],l=new Set(i.flatMap(s=>B(o,s.rows,a)));this._plotRegistry.get(r)?.setSelection([...l])}}_wireLinks(e){const o=M(e.map),r=M(e.plot);for(const n of e.links??[]){const i=r.find(c=>S(c)===n.source),a=this._plotRegistry.get(n.source);if(!i||!a)throw new Error(`Link source "${n.source}" is not the id (or the dataRef) of a plot of this specification.`);const l=o.findIndex(c=>c.id===n.target),s=this._maps[l];if(l<0||!s)throw new Error(`Link target "${n.target}" is not the id of a map of this specification.`);const u=o[l].layerRefs.find(c=>n.layer!==void 0?v(c)===n.layer:c.dataRef===i.dataRef);if(!u)throw new Error(n.layer!==void 0?`Link from "${n.source}": map "${n.target}" has no layer "${n.layer}".`:`Link from "${n.source}": map "${n.target}" draws no layer of the table "${i.dataRef}"; name the layer.`);const d=this._layers.find(c=>c.mapIndex===l&&c.layerId===v(u));d&&(Lt(a,this._plotRows.get(n.source)??[],i.events??[],d),wt(this._plotLinks,n.source,d))}}_pickFromTheStart(e){const o=M(e.plot);M(e.map).forEach((r,n)=>{for(const i of r.layerRefs){if(!i.pickedComps)continue;const a=v(i),l=this._layers.find(u=>u.mapIndex===n&&u.layerId===a);if(!l)continue;const s=l.map.activePickingLayer?.layerInfo.id;if(s!==a)throw new Error(`Layer "${a}": pickedComps draws features as picked on the layer that picks, but ${s===void 0?"no layer of its map picks":`a link or a plot's mapRef made layer "${s}" of its map pick`}: autk-map lets one layer of a map pick.`);for(const[u,d]of this._plotLinks){const c=o.find(f=>S(f)===u);if(d.includes(l)&&(c?.selection?.length??0)>0)throw new Error(`Layer "${a}": pickedComps and the selection of plot "${u}", which is linked to it, both set what the two show: set one of them.`)}l.map.setHighlightedIds(a,i.pickedComps),this._selectInLinkedPlots([l],i.pickedComps)}})}_selectFromTheStart(e){for(const o of M(e.plot))o.selection&&o.selection.length>0&&this.setPlotSelection(S(o),o.selection)}_rewireInteractions(e){for(const r of this._fwdCleanups)r();this._fwdCleanups=[];const o=M(e.map);this._maps.forEach((r,n)=>{const i=gt(o[n],n),a=({layerId:l,selection:s})=>{this.interactions.emit("map:picking",{mapId:i,layerId:l,selection:s})};r.events.on(T.MapEvent.PICKING,a),this._fwdCleanups.push(()=>r.events.off(T.MapEvent.PICKING,a))});for(const[r,n]of this._plotRegistry)for(const i of[k.PlotEvent.CLICK,k.PlotEvent.BRUSH,k.PlotEvent.BRUSH_X,k.PlotEvent.BRUSH_Y]){const a=({selection:l})=>{this.interactions.emit("plot:selection",{plotId:r,event:i,selection:l})};n.events.on(i,a),this._fwdCleanups.push(()=>n.events.off(i,a))}}}g.AutkGrammar=oo,g.ColorMapInterpolator=nt,g.GrammarEventEmitter=Qt,g.NormalizationMode=W,g.STORAGE_BUFFER_BINDING_SIZE=J,g.applyCamera=Rt,g.arrangeViews=Zt,g.buildBatchedUniforms=Dt,g.computeLayerNames=Tt,g.createComputeAdapter=Wt,g.createDataAdapter=pt,g.createEngine=ot,g.enterWorkspace=N,g.findIterateSource=q,g.isFromFeature=I,g.joinWgsl=Nt,g.maxBatchedFeatures=jt,g.resolveComputeParams=X,g.resolveUniformMatrices=z,g.resolveUniforms=K,g.runCompute=xt,g.tableKey=C,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})}));
|
|
3
3
|
//# sourceMappingURL=autk-grammar.umd.cjs.map
|