import*as e from"@arcgis/core/arcade/arcade";import*as r from"@arcgis/core/support/arcadeUtils";import{checkArg as a}from"./checkArg.js";const t=new Map;export function isArcadeScriptAsync(a,t){const s=i(a,t);return["$datastore","$map","$layer"].some((e=>r.hasVariable(s,e)))||e.scriptIsAsync({...s,isAsync:void 0,usesFeatureSet:void 0,usesGeometry:void 0},void 0)}export function arcadeScriptUsesGeometry(e,r){return!!i(e,r).usesGeometry}export async function enableGeometrySupportIfNeeded(r){const{spatialReference:a}=r.geometry,t=r.source?.layer?.elevationInfo?.featureExpressionInfo?.expression;t&&arcadeScriptUsesGeometry(t,a)&&await e.enableGeometrySupport()}export function runArcadeExpression(t,s){const{map:o,layer:n,vars:c,feature:p,spatialReference:f,emitErrorOnMissingVariables:u=!0}=s;a("$map and $layer parameters are not supported in synchronous arcade",s).satisfies((()=>!o&&!n));const l=r.getViewInfo({spatialReference:f}),m=r.createExecContext(p?.toGraphic(),l);if(c)for(const e of Object.keys(c))m.vars[e]=c[e];const y=i(t,f);if(r.hasVariable(y,"$feature"))if(u)a("params.feature",p).isNotMissing();else if(!p)return;return e.executeScript(y,m)}export async function runAsyncArcadeExpression(t,s){const{map:o,layer:n,vars:c,feature:p,spatialReference:f,emitErrorOnMissingVariables:u=!0}=s,l={...i(t,f)},m=["$datastore","$map","$layer"].filter((e=>r.hasVariable(l,e)));await r.loadScriptDependencies(l,!0,m);const y=r.getViewInfo({spatialReference:f}),d=r.createExecContext(p?.toGraphic(),y);if(l.isAsync=!0,l.usesFeatureSet=!0,await Promise.all([e.enableAsyncSupport(),(async()=>{await import("@arcgis/core/arcade/functions/featuresetbase.js"),await e.enableFeatureSetSupport()})(),l.usesGeometry&&e.enableGeometrySupport()]),r.hasVariable(l,"$feature"))if(u)a("params.feature",p).isNotMissing();else if(!p)return;if(m.includes("$map")){if(u)a("params.map",o).isNotMissing();else if(!o)return;d.vars.$map=r.convertMapToFeatureSetCollection({map:o,spatialReference:f})}if(m.includes("$layer")){if(u)a("params.layer",n).isNotMissing();else if(!n)return;d.vars.$layer=r.convertFeatureLayerToFeatureSet({layer:n,spatialReference:f})}if(m.includes("$datastore")){if(u)a("params.layer",n).isNotMissing();else if(!n)return;d.vars.$datastore=r.convertServiceUrlToWorkspace({url:n.url,spatialReference:f})}if(c)for(const e of Object.keys(c))d.vars[e]=c[e];return r.createFunction(l,d)(d)}const s=["__proto__"];function i(r,a){const i=`${r}-${a?.wkid}`;if(t.has(i))return t.get(i);const o=s.filter((e=>r.includes(e)));if(0!==o.length)throw new Error(`Invalid Arcade expression tokens: ${o.join()}`);const n=e.parseScript(r,a);return t.set(i,n),n}