Files
2024-02-28 17:06:42 +05:00

14 lines
92 KiB
JavaScript

import{_ as Be,s as _e,cy as te,$ as Ce,z as ne,Y as k,kX as wt,aj as it,eP as de,L as at,h0 as Ft,i9 as nt,fR as Re,ky as he,eg as le,e8 as ot,dT as Tt,gv as ce,kY as Ct,aV as kt,kZ as Mt,kw as ke,aC as B,v as ye,ar as qt,A,C as me,ij as At,gU as ht,au as Rt,B as O,bk as Ee,ex as Et,hC as $t,f as K,be as ut,k_ as W,aI as dt,ab as lt,b3 as ct,gx as Ut,D as ge,aS as Ot,w as oe,d as Lt,q as Pt,c3 as Qt,k$ as Gt}from"./index-b5c8f851.js";import{s as $e,I as Bt,i as Dt,a as gt,t as jt,h as Me,M as pt,g as ft,K as Ue,L as zt,y as _t}from"./featureConversionUtils-6aca8295.js";import{W as De}from"./QueryEngine-f2d30caa.js";import{r as Nt,a as yt,I as mt,u as Vt}from"./FeatureStore2D-db06c1ba.js";import{m as It}from"./quantizationUtils-50e37a76.js";import{v as je}from"./ogcFeatureUtils-b8016c72.js";import{d as Ht,c as ze}from"./query-cd419ad0.js";import{S as Ne,h as G,r as Yt,k as Xt}from"./ComputedAttributeStorage-07f34ef9.js";import{r as Zt}from"./pbf-eb90fa42.js";import{a as Oe,t as Q,e as Jt}from"./OptimizedGeometry-d94e541f.js";import{b as Wt,h as Kt}from"./pbfQueryUtils-e46c5add.js";import{t as pe}from"./CircularArray-ef508845.js";import{createConnection as es}from"./createConnection-d5b32134.js";import{X as ts,b as fe,Y as ue}from"./geohashUtils-77d8429b.js";import{j as ae,x as vt}from"./projectionSupport-d15822a5.js";import{s as ss,g as Ve}from"./visualVariablesUtils-f4ae79f2.js";import{c as D}from"./definitions-1467ba4a.js";import"./OptimizedFeatureSet-1d1ac4b9.js";import"./WhereClause-08dab84b.js";import"./TimeOnly-99f1af45.js";import"./timeSupport-b4d06407.js";import"./QueryEngineCapabilities-85c4f1d0.js";import"./utils-10149227.js";import"./utils-b84c61ef.js";import"./generateRendererUtils-d29abb94.js";import"./RenderState-1d6218ee.js";import"./geojson-17044e7b.js";import"./date-294ce3fb.js";import"./clientSideDefaults-6e7fdab0.js";import"./color-0916c686.js";import"./enums-f1a6a48a.js";import"./enums-bdecffa2.js";import"./VertexElementDescriptor-2925c6af.js";import"./json-48e3ea08.js";function rs(a){return a==="heatmap"?Be(()=>import("./HeatmapProcessor-c1136256.js"),["assets/HeatmapProcessor-c1136256.js","assets/index-b5c8f851.js","assets/index-86716609.css","assets/definitions-1467ba4a.js","assets/BaseProcessor-749c8451.js","assets/tileUtils-c2f19f52.js"]):Be(()=>import("./SymbolProcessor-d308a82e.js"),["assets/SymbolProcessor-d308a82e.js","assets/index-b5c8f851.js","assets/index-86716609.css","assets/ExpandedCIM-0020ab0e.js","assets/BidiEngine-9a40f2f4.js","assets/visualVariablesUtils-f4ae79f2.js","assets/OptimizedGeometry-d94e541f.js","assets/color-0916c686.js","assets/enums-f1a6a48a.js","assets/enums-bdecffa2.js","assets/VertexElementDescriptor-2925c6af.js","assets/definitions-1467ba4a.js","assets/GeometryUtils-984e8446.js","assets/utils-ebbcf3da.js","assets/GeometryUtils-7a7937c3.js","assets/Rect-ea14f53a.js","assets/quantizationUtils-50e37a76.js","assets/floatRGBA-ba8d5dad.js","assets/Matcher-dd0694f8.js","assets/tileUtils-c2f19f52.js","assets/TurboLine-f7b8bf8b.js","assets/earcut-d423749e.js","assets/BaseProcessor-749c8451.js"])}const ve=268435455;let is=class{constructor(){this.hasFeatures=!1,this.exceededTransferLimit=!1,this.fieldCount=0,this.featureCount=0,this.objectIdFieldIndex=0,this.vertexCount=0,this.offsets={attributes:new Array,geometry:new Array},this.centroid=new Array}};function as(a,e,t=!1){var M;const h=a.asUnsafe(),l=h.pos(),d=new is;let c=0,g=0;const _=1,p=2,f=4,v=3;let m=null,x=null,y=null,I=!1;const b=[];for(;h.next();)switch(h.tag()){case 1:m=h.getString();break;case 3:x=h.getString();break;case 12:y=h.processMessage(Kt);break;case 9:if(d.exceededTransferLimit=h.getBool(),d.exceededTransferLimit){d.offsets.geometry=t?new Float64Array(8e3):new Int32Array(8e3),d.centroid=t?new Float64Array(16e3):new Int32Array(16e3);for(let F=0;F<d.centroid.length;F++)d.centroid[F]=ve}break;case 13:{const F=h.processMessage(Wt);F.index=c++,b.push(F);break}case 15:{const F=h.getLength(),w=h.pos()+F;if(!d.exceededTransferLimit){const T=d.offsets.geometry,q=d.centroid;T.push(0),q.push(ve),q.push(ve)}!I&&d.exceededTransferLimit&&(I=!0,d.offsets.attributes=t?new Float64Array(8e3*c):new Uint32Array(8e3*c));let C=g*c;for(;h.pos()<w&&h.next();)switch(h.tag()){case _:{I?d.offsets.attributes[C++]=h.pos():d.offsets.attributes.push(h.pos());const T=h.getLength();h.skipLen(T);break}case p:if(e){const T=h.getLength(),q=h.pos()+T;for(;h.pos()<q&&h.next();)switch(h.tag()){case v:{h.getUInt32();const R=h.getSInt64(),U=h.getSInt64();d.centroid[2*g]=R,d.centroid[2*g+1]=U;break}default:h.skip()}}else{d.offsets.geometry[g]=h.pos();const T=h.getLength();d.vertexCount+=T,h.skipLen(T)}break;case f:{const T=h.getLength(),q=h.pos()+T;for(;h.pos()<q&&h.next();)switch(h.tag()){case v:{h.getUInt32();const R=h.getSInt64(),U=h.getSInt64();d.centroid[2*g]=R,d.centroid[2*g+1]=U;break}default:h.skip()}break}default:h.skip()}g++,d.hasFeatures=!0;break}default:h.skip()}const S=m||x;if(!S)throw new _e("FeatureSet has no objectId or globalId field name");return d.fields=new te(b),d.featureCount=g,d.fieldCount=c,d.objectIdFieldIndex=(M=d.fields.get(S))==null?void 0:M.index,d.transform=y,d.displayIds=new Uint32Array(d.featureCount),d.groupIds=new Uint16Array(d.featureCount),h.move(l),d}const ns=!0,be=268435455,He=128,Ye=128e3,se={small:{delta:new Int32Array(He),decoded:new Int32Array(He)},large:{delta:new Int32Array(Ye),decoded:new Int32Array(Ye)}};function Xe(a){return a<=se.small.delta.length?se.small:(a<=se.large.delta.length||(se.large.delta=new Int32Array(Math.round(1.25*a)),se.large.decoded=new Int32Array(Math.round(1.25*a))),se.large)}function os(a){try{const t=new Zt(new Uint8Array(a),new DataView(a));for(;t.next();){if(t.tag()===2)return hs(t.getMessage());t.skip()}}catch(e){const t=new _e("query:parsing-pbf","Error while parsing FeatureSet PBF payload",{error:e});ne.getLogger("esri.view.2d.layers.features.support.FeatureSetReaderPBF").error(t)}return null}function hs(a){for(;a.next();){if(a.tag()===1)return a.getMessage();a.skip()}return null}function us(a){const l=a.getLength(),d=a.pos()+l;for(;a.pos()<d&&a.next();)switch(a.tag()){case 1:return a.getString();case 2:return a.getFloat();case 3:return a.getDouble();case 4:return a.getSInt32();case 5:return a.getUInt32();case 6:return a.getInt64();case 7:return a.getUInt64();case 8:return a.getSInt64();case 9:return a.getBool();default:return a.skip(),null}return null}function ds(a,e,t,s,r,i){return .5*Math.abs(a*s+t*i+r*e-a*i-t*e-r*s)}function xe(a,e,t,s){return a*s-t*e===0&&a*t+e*s>0}let ls=class qe extends Ne{static fromBuffer(e,t,s=!1){const r=t.geometryType,i=os(e),n=as(i,r==="esriGeometryPoint",s),o=Ne.createInstance();return new qe(o,i,n,t)}constructor(e,t,s,r){super(e,r),this._hasNext=!1,this._isPoints=!1,this._featureIndex=-1,this._featureOffset=0,this._cache={area:0,unquantGeometry:void 0,geometry:void 0,centroid:void 0,legacyFeature:void 0,optFeature:void 0},this._geometryType=r.geometryType,this._reader=t,this._header=s,this._hasNext=s.hasFeatures,this._isPoints=r.geometryType==="esriGeometryPoint"}get fields(){return this._header.fields}get geometryType(){return this._geometryType}get _size(){return this._header.featureCount}get hasZ(){return!1}get hasM(){return!1}get stride(){return 2+(this.hasZ?1:0)+(this.hasM?1:0)}get hasFeatures(){return this._header.hasFeatures}get hasNext(){return this._hasNext}get exceededTransferLimit(){return this._header.exceededTransferLimit}getSize(){return this._size}getQuantizationTransform(){return this._header.transform}getCursor(){return this.copy()}getIndex(){return this._featureIndex}setIndex(e){this._cache.area=0,this._cache.unquantGeometry=void 0,this._cache.geometry=void 0,this._cache.centroid=void 0,this._cache.legacyFeature=void 0,this._cache.optFeature=void 0,this._featureIndex=e}getAttributeHash(){let e="";for(const t of this._header.fields.fields)e+=this._readAttributeAtIndex(t.index)+".";return e}getObjectId(){return this._readAttributeAtIndex(this._header.objectIdFieldIndex)}getDisplayId(){return this._header.displayIds[this._featureIndex]}setDisplayId(e){this._header.displayIds[this._featureIndex]=e}getGroupId(){return this._header.groupIds[this._featureIndex]}setGroupId(e){this._header.groupIds[this._featureIndex]=e}readLegacyFeature(){if(this._cache.legacyFeature===void 0){const e=this.readCentroid(),t={attributes:this.readAttributes(),geometry:this._isPoints?this.readLegacyPointGeometry():this.readLegacyGeometry(),centroid:(e&&{x:e.coords[0],y:e.coords[1]})??null};return this._cache.legacyFeature=t,t}return this._cache.legacyFeature}readOptimizedFeature(){if(this._cache.optFeature===void 0){const e=new Oe(this.readGeometry(),this.readAttributes(),this.readCentroid());return e.objectId=this.getObjectId(),e.displayId=this.getDisplayId(),this._cache.optFeature=e,e}return this._cache.optFeature}getXHydrated(){const e=this._header.centroid[2*this._featureIndex],t=this.getQuantizationTransform();return t==null?e:e*t.scale[0]+t.translate[0]}getYHydrated(){const e=this._header.centroid[2*this._featureIndex+1],t=this.getQuantizationTransform();return t==null?e:t.translate[1]-e*t.scale[1]}getX(){return this._header.centroid[2*this._featureIndex]*this._sx+this._tx}getY(){return this._header.centroid[2*this._featureIndex+1]*this._sy+this._ty}readLegacyPointGeometry(){return{x:this.getX(),y:this.getY()}}readLegacyGeometry(e){const t=this.readUnquantizedGeometry(e);return $e(t,this.geometryType,!1,!1)}readLegacyCentroid(){const e=this.readCentroid();if(!e)return null;const[t,s]=e.coords;return{x:t,y:s}}readGeometryArea(){return this._cache.area||this.readGeometry(!0),this._cache.area}readUnquantizedGeometry(e=!1){if(this._cache.unquantGeometry===void 0){const t=this.readGeometry(e);if(!t)return this._cache.unquantGeometry=void 0,null;const s=Xe(t.coords.length).decoded,r=t.clone(s),i=r.coords;let n=0;for(const o of r.lengths){for(let u=1;u<o;u++){const h=2*(n+u),l=2*(n+u-1);i[h]+=i[l],i[h+1]+=i[l+1]}n+=o}return this._cache.unquantGeometry=r,r}return this._cache.unquantGeometry}readHydratedGeometry(){if(this._isPoints){if(this._header.centroid[2*this._featureIndex]===be)return null;const r=this.getXHydrated(),i=this.getYHydrated();return new Q([],[r,i])}const e=this.readGeometry();if(!e)return null;const t=e.clone(),s=this.getQuantizationTransform();return s!=null&&Bt(t,t,this.hasZ,this.hasM,s),t}readGeometry(e=!1){if(this._cache.geometry===void 0){let t=null;if(this._isPoints){if(this._header.centroid[2*this._featureIndex]===be)return null;const s=this.getX(),r=this.getY();t=new Q([],[s,r])}else{const s=this._header.offsets.geometry[this._featureIndex],r=this._reader;if(s===0){const i=this._readServerCentroid();if(!i)return null;const[n,o]=i.coords;return this.createQuantizedExtrudedGeometry(n,o)}r.move(s);try{if(t=e?this._parseGeometryForDisplay(r):this._parseGeometry(r),!t){const i=this._readServerCentroid();if(!i)return null;const[n,o]=i.coords;return this.createQuantizedExtrudedGeometry(n,o)}}catch(i){return console.error("Failed to parse geometry!",i),null}}return this._cache.geometry=t,t}return this._cache.geometry}readCentroid(){if(this._cache.centroid===void 0){let e;return e=this._computeCentroid(),e||(e=this._readServerCentroid()),this._cache.centroid=e??void 0,e??null}return this._cache.centroid}copy(){const e=this._reader.clone(),t=new qe(this.instance,e,this._header,this.fullSchema());return this.copyInto(t),t}next(){for(this._cache.area=0,this._cache.unquantGeometry=void 0,this._cache.geometry=void 0,this._cache.centroid=void 0,this._cache.legacyFeature=void 0,this._cache.optFeature=void 0;++this._featureIndex<this._size&&!this._getExists(););return this._featureIndex<this._size}_readAttribute(e,t){var n;const s=this._header.fields.get(e);if(s==null)return;let r=this._readAttributeAtIndex(s.index);((n=this.fields.get(e))==null?void 0:n.type)==="esriFieldTypeTimestampOffset"&&(r=this.parseTimestampOffset(r));const i=this._header.fields.isDateField(s.name);return t?r==null?r:i?new Date(r):r:r}_readAttributes(){const e={};for(const t of this._header.fields.fields)e[t.name]=this._readAttributeAtIndex(t.index);return e}copyInto(e){super.copyInto(e),e._featureIndex=this._featureIndex,e._featureOffset=this._featureOffset,e._hasNext=this._hasNext}_readAttributeAtIndex(e){const t=this._header.offsets.attributes[this._featureIndex*this._header.fieldCount+e],s=this._reader;return s.move(t),us(s)}_readServerCentroid(){const e=this._header.centroid[2*this._featureIndex]+this._tx,t=this._header.centroid[2*this._featureIndex+1]+this._ty;return e===be?null:new Q([],[e,t])}_parseGeometry(e){const r=e.asUnsafe(),i=r.getLength(),n=r.pos()+i,o=[],u=[];for(;r.pos()<n&&r.next();)switch(r.tag()){case 2:{const h=r.getUInt32(),l=r.pos()+h;for(;r.pos()<l;)u.push(r.getUInt32());break}case 3:{const h=r.getUInt32(),l=r.pos()+h;for(o.push(r.getSInt32()+this._tx),o.push(r.getSInt32()+this._ty),this.hasZ&&r.getSInt32(),this.hasM&&r.getSInt32();r.pos()<l;)o.push(r.getSInt32()),o.push(r.getSInt32()),this.hasZ&&r.getSInt32(),this.hasM&&r.getSInt32();break}default:r.skip()}return o.length?new Q(u,o):null}_parseGeometryForDisplay(e){const r=e.asUnsafe(),i=r.getLength(),n=r.pos()+i,o=[],u=[];let h=0,l=0,d=null,c=0;const g=this.geometryType==="esriGeometryPolygon";for(;r.pos()<n&&r.next();)switch(r.tag()){case 2:{const _=r.getUInt32(),p=r.pos()+_;for(;r.pos()<p;){const f=r.getUInt32();o.push(f),h+=f}d=Xe(2*h).delta;break}case 3:{r.getUInt32();const _=2+(this.hasZ?1:0)+(this.hasM?1:0);Ce(d);for(const p of o)if(l+_*p>d.length)for(let f=0;f<p;f++)r.getSInt32(),r.getSInt32(),this.hasZ&&r.getSInt32(),this.hasM&&r.getSInt32();else if(g&&ns){const f=this.getAreaSimplificationThreshold(p,this._header.vertexCount);let v=2,m=1;const x=!1;let y=r.getSInt32(),I=r.getSInt32();d[l++]=y,d[l++]=I,this.hasZ&&r.getSInt32(),this.hasM&&r.getSInt32();let b=r.getSInt32(),S=r.getSInt32();for(this.hasZ&&r.getSInt32(),this.hasM&&r.getSInt32();v<p;){let M=r.getSInt32(),F=r.getSInt32();this.hasZ&&r.getSInt32(),this.hasM&&r.getSInt32();const w=y+b,C=I+S;ds(y,I,w,C,w+M,C+F)>=f?(c+=-.5*(w-y)*(C+I),m>1&&xe(d[l-2],d[l-1],b,S)?(d[l-2]+=b,d[l-1]+=S):(d[l++]=b,d[l++]=S,m++),y=w,I=C):(M+=b,F+=S),b=M,S=F,v++}m<3||x?l-=2*m:(c+=-.5*(y+b-y)*(I+S+I),xe(d[l-2],d[l-1],b,S)?(d[l-2]+=b,d[l-1]+=S,u.push(m)):(d[l++]=b,d[l++]=S,u.push(++m)))}else{let f=0,v=r.getSInt32(),m=r.getSInt32();this.hasZ&&r.getSInt32(),this.hasM&&r.getSInt32(),d[l++]=v,d[l++]=m,f+=1;for(let x=1;x<p;x++){const y=r.getSInt32(),I=r.getSInt32(),b=v+y,S=m+I;c+=-.5*(b-v)*(S+m),this.hasZ&&r.getSInt32(),this.hasM&&r.getSInt32(),x>2&&xe(d[l-2],d[l-1],y,I)?(d[l-2]+=y,d[l-1]+=I):(d[l++]=y,d[l++]=I,f+=1),v=b,m=S}u.push(f)}break}default:r.skip()}if(this._cache.area=c,!u.length)return null;if(this._tx||this._ty){let _=0;Ce(d);for(const p of u)d[2*_]+=this._tx,d[2*_+1]+=this._ty,_+=p}return new Q(u,d)}},Ie=class{constructor(e){this.service=e,this._arcadeLayerSchema={...e,fieldsIndex:te.fromJSON(e.fieldsIndex)}}destroy(){}};function cs(a){return Array.isArray(a.source)}function gs(a){return(a==null?void 0:a.type)==="ogc-source"}function ps(a){const{capabilities:e}=a;return gs(a.source)?new Is(a):cs(a)?new _s(a):e.query.supportsFormatPBF&&k("featurelayer-pbf")?new ys(a):new ms(a)}async function fs(a){const e=new wt;return await e.open(a,{}),e}let _s=class extends Ie{constructor(e){super(e),this._portsOpen=fs(e.source).then(t=>this.client=t)}destroy(){this.client.close(),this.client=null}async executeQuery(e,t){await this._portsOpen;const s=await this.client.invoke("queryFeatures",e.toJSON(),t);return G.fromFeatureSet(s,this._arcadeLayerSchema)}},ys=class extends Ie{async executeQuery(e,t){const{data:s}=await Ht(this.service.source,e,t),r=!e.quantizationParameters;return ls.fromBuffer(s,this._arcadeLayerSchema,r)}},ms=class extends Ie{async executeQuery(e,t){var h;const{source:s,capabilities:r,spatialReference:i,objectIdField:n,geometryType:o}=this.service;if(e.quantizationParameters!=null&&!r.query.supportsQuantization){const l=e.clone(),d=It(l.quantizationParameters);l.quantizationParameters=null;const{data:c}=await ze(s,l,i,t),g=Dt(c,n);return gt(d,g),G.fromOptimizedFeatureSet(g,this._arcadeLayerSchema)}const{data:u}=await ze(s,e,this.service.spatialReference,t);return o==="esriGeometryPoint"&&(u.features=(h=u.features)==null?void 0:h.filter(l=>{if(l.geometry!=null){const d=l.geometry;return Number.isFinite(d.x)&&Number.isFinite(d.y)}return!0})),G.fromFeatureSet(u,this._arcadeLayerSchema)}},Is=class extends Ie{async executeQuery(e,t){const{capabilities:s}=this.service;if(e.quantizationParameters&&!s.query.supportsQuantization){const i=e.clone(),n=It(i.quantizationParameters);i.quantizationParameters=null;const o=await je(this.service.source,e,t);return gt(n,o),G.fromOptimizedFeatureSet(o,this._arcadeLayerSchema)}const r=await je(this.service.source,e,t);return G.fromOptimizedFeatureSet(r,this._arcadeLayerSchema)}};class E{constructor(){this.version=0,this.source=!1,this.targets={feature:!1,aggregate:!1},this.storage={filters:!1,data:!1},this.mesh=!1,this.queryFilter=!1,this.why={mesh:[],source:[]}}static create(e){const t=new E;let s;for(s in e){const r=e[s];if(typeof r=="object")for(const i in r){const n=i,o=r[n];t[s][n]=o}t[s]=r}return t}static empty(){return E.create({})}static all(){return E.create({source:!0,targets:{feature:!0,aggregate:!0},storage:{filters:!0,data:!0},mesh:!0})}unset(e){this.version=e.version,e.source&&(this.source=!1),e.targets.feature&&(this.targets.feature=!1),e.targets.aggregate&&(this.targets.aggregate=!1),e.storage.filters&&(this.storage.filters=!1),e.storage.data&&(this.storage.data=!1),e.mesh&&(this.mesh=!1),e.queryFilter&&(this.queryFilter=!1)}any(){return this.source||this.mesh||this.storage.filters||this.storage.data||this.targets.feature||this.targets.aggregate||this.queryFilter}describe(){let e=0,t="";if(this.mesh){e+=20,t+=`-> (20) Mesh needs update
`;for(const r of this.why.mesh)t+=` + ${r}
`}if(this.source){e+=10,t+=`-> (10) The source needs update
`;for(const r of this.why.source)t+=` + ${r}
`}this.targets.feature&&(e+=5,t+=`-> (5) Feature target parameters changed
`),this.storage.filters&&(e+=5,t+=`-> (5) Feature filter parameters changed
`),this.targets.aggregate&&(e+=4,t+=`-> (4) Aggregate target parameters changed
`),this.storage.data&&(e+=1,t+="-> (1) Texture storage parameters changed");const s=e<5?"Fastest":e<10?"Fast":e<15?"Moderate":e<20?"Slow":"Very Slow";console.debug(`Applying ${s} update of cost ${e}/45 `),console.debug(t)}toJSON(){return{queryFilter:this.queryFilter,source:this.source,targets:this.targets,storage:this.storage,mesh:this.mesh}}}let vs=class{constructor(e,t){this.requests={done:new Array,stream:new pe(10)},this._edits=null,this._abortController=new AbortController,this._version=0,this._isDone=!1,this.didSend=!1,this.tile=e,this._version=t,this._resolver=it(),this._resolver.promise.catch(s=>de(s))}get signal(){return this._abortController.signal}get options(){return{signal:this._abortController.signal}}get empty(){return!this.requests.done.length&&this.edits==null}get edits(){return this._edits}get done(){return this._resolver.promise}get isDone(){return this._isDone}resolve(){this._isDone=!0,this._resolver.resolve()}clear(){this.requests.done=[]}applyUpdate(e){this.requests.done.forEach(t=>t.message.status.unset(e)),this._version=e.version,this._edits!=null&&this._edits.status.unset(e)}add(e){e.message.status=e.message.status??E.empty(),e.message.status.version=this._version,k("esri-2d-update-debug")&&console.debug(this.tile.id,"DataTileSubscription:add",this._version),e.message.end&&(this.requests.done.forEach(t=>{t.message!=null&&t.message.end&&(t.message.end=!1)}),this._resolver.resolve(),this._isDone=!0),this.requests.done.push(e)}edit(e,t){const s=e.getQuantizationTransform(),r=e.fullSchema(),i=Array.from(e.features()).filter(at),n=[...t,...i.map(o=>o.objectId)];if(this.removeIds(n),this._invalidate(),this._edits==null)return void(this._edits={type:"append",addOrUpdate:G.fromOptimizedFeatures(i,r,s),id:this.tile.id,status:E.empty(),end:!0});this.requests.done.forEach(o=>o.message.end=!1),this._edits.addOrUpdate.append(e.features())}*readers(){var e;for(const{message:t}of this.requests.done)t.addOrUpdate!=null&&(yield t.addOrUpdate);((e=this._edits)==null?void 0:e.addOrUpdate)!=null&&(yield this._edits.addOrUpdate)}_invalidate(){for(const e of this.requests.done)e.message.status=E.empty();this._edits!=null&&(this._edits.status=E.empty())}removeIds(e){var t;this._invalidate();for(const{message:s}of this.requests.done){const r=s.addOrUpdate;r!=null&&(r.removeIds(e),r.isEmpty&&(k("esri-2d-update-debug")&&console.debug("Removing FeatureSetReader"),s.addOrUpdate=null))}((t=this._edits)==null?void 0:t.addOrUpdate)!=null&&this._edits.addOrUpdate.removeIds(e),this.requests.done=this.requests.done.filter(s=>s.message.addOrUpdate||s.message.end)}abort(){this._abortController.abort(),this._resolver.reject(Ft())}};function bs(a,e){const t=new Set;return a&&a.forEach(s=>t.add(s)),e&&e.forEach(s=>t.add(s)),t.has("*")?["*"]:Array.from(t)}let bt=class{constructor(e){this.updatingHandles=new nt,this.events=new Re,this._resolver=it(),this._didEdit=!1,this._subscriptions=new Map,this._outSR=e.outSR,this._serviceInfo=e.serviceInfo,this._onTileUpdateMessage=e.onMessage,this._arcadeLayerSchema=e.arcadeLayerSchema}destroy(){for(const e of this._subscriptions.values())e.abort();this.updatingHandles.destroy()}get subscriptions(){return this._subscriptions.values()}async _onMessage(e){const t=this._subscriptions.get(e.id);if(!t)return;const s={...e,remove:e.remove??[],status:e.status??E.empty()};return he(this._onTileUpdateMessage(s,t.options))}update(e,t){var h;const s=t.fields.length;t.outFields=bs((h=this._schema)==null?void 0:h.outFields,t.outFields),t.outFields=t.outFields.length>=.75*s?["*"]:t.outFields,t.outFields.sort();const r=le(this._schema,t);if(!r)return;k("esri-2d-update-debug")&&console.debug("Applying Update - Source:",r);const i="orderByFields"in this._serviceInfo&&this._serviceInfo.orderByFields?this._serviceInfo.orderByFields:this._serviceInfo.objectIdField+" ASC",n=this._serviceInfo.source,o={returnCentroid:!(n!==null&&typeof n=="object"&&"path"in n&&ot(n.path))&&this._serviceInfo.geometryType==="esriGeometryPolygon",returnGeometry:!0,timeReferenceUnknownClient:this._serviceInfo.type!=="stream"&&this._serviceInfo.timeReferenceUnknownClient,outFields:t.outFields,outSpatialReference:this._outSR,orderByFields:[i],where:t.definitionExpression||"1=1",gdbVersion:t.gdbVersion,historicMoment:t.historicMoment,timeExtent:t.timeExtent?Tt.fromJSON(t.timeExtent):null},u=this._schema&&ce(r,"outFields");this._schema&&Ct(r,["timeExtent","definitionExpression","gdbVersion","historicMoment","customParameters"])&&(e.why.mesh.push("Layer filter and/or custom parameters changed"),e.why.source.push("Layer filter and/or custom parameters changed"),e.mesh=!0,e.source=!0,e.queryFilter=!0),u&&(e.why.source.push("Layer required fields changed"),e.source=!0),le(o,this._queryInfo)&&(this._queryInfo=o),this._schema=t,this._resolver.resolve()}whenInitialized(){return this._resolver.promise}async applyUpdate(e){if(e.queryFilter||e.source&&this._didEdit)return this.refresh(e.version),void(this._didEdit=!1);this._subscriptions.forEach(t=>t.applyUpdate(e)),await this.resend()}refresh(e,t){for(const s of this._tiles())this.unsubscribe(s),this.subscribe(s,e)}subscribe(e,t){const s=new vs(e,t);return this._subscriptions.set(e.id,s),s}unsubscribe(e){const t=this.getSubscription(e.id);t!=null&&t.abort(),this._subscriptions.delete(e.id)}createQuery(e={}){const t=this._queryInfo.historicMoment?new Date(this._queryInfo.historicMoment):null;return new kt({...this._queryInfo,historicMoment:t,...e})}getSubscription(e){return this._subscriptions.has(e)?this._subscriptions.get(e):null}async queryLastEditDate(){throw new Error("Service does not support query type")}async query(e,t){throw new Error("Service does not support query")}*_tiles(){const e=Array.from(this._subscriptions.values());for(const t of e)yield t.tile}async edit(e,t){return this.updatingHandles.addPromise(this._edit(e,t))}async _edit(e,t){const s=Array.from(this._subscriptions.values()),r=s.map(({tile:i})=>i);for(const i of s)i.removeIds(t);if(e.length){const i=r.map(o=>{const u=this.createTileQuery(o);return u.objectIds=e,{tile:o,query:u}}).map(async({tile:o,query:u})=>({tile:o,result:await this.query(u,{query:{tile:k("esri-tiles-debug")?o.id.replaceAll("/","."):void 0}}),query:u})),n=(await Mt(i)).map(async({tile:o,result:u})=>{if(!u.hasFeatures&&!t.length&&!e.length)return;const h=this._subscriptions.get(o.key.id);h&&h.edit(u,e)});await Promise.allSettled(n)}this._didEdit=!0}};const xs=4;let Le=class extends bt{constructor(e){super(e),this.type="feature",this.mode="on-demand",this._adapter=ps(e.serviceInfo),this._queue=new ke({concurrency:8,process:async t=>{var s,r;if(B(t),t.tile!=null){const i=t.tile.key.id,{signal:n}=t,o=k("esri-tiles-debug")?{tile:i.replaceAll("/","."),depth:t.depth}:void 0,u=await this._adapter.executeQuery(t.query,{signal:n,query:{...o,...(s=this._schema)==null?void 0:s.customParameters}});return u.level=t.tile.key.level,u}return this._adapter.executeQuery(t.query,{...t,query:(r=this._schema)==null?void 0:r.customParameters})}}),this._patchQueue=new ke({concurrency:8,process:async t=>{var s,r;if(B(t),t.tile!=null){const i=t.tile.key.id,{signal:n}=t,o=k("esri-tiles-debug")?{tile:i.replaceAll("/","."),depth:t.depth}:void 0,u=await this._adapter.executeQuery(t.query,{signal:n,query:{...o,...(s=this._schema)==null?void 0:s.customParameters}});return u.level=t.tile.key.level,u}return this._adapter.executeQuery(t.query,{...t,query:(r=this._schema)==null?void 0:r.customParameters})}})}destroy(){super.destroy(),this._adapter.destroy(),this._queue.destroy(),this._patchQueue.destroy()}enqueueQuery(e,t){return this.updatingHandles.addPromise(this._queue.push(e,t))}enqueuePatchQuery(e,t){return this.updatingHandles.addPromise(this._patchQueue.push(e,t))}get maxRecordCountFactor(){const{query:e}=this._serviceInfo.capabilities;return e.supportsMaxRecordCountFactor?xs:null}get maxPageSize(){const{query:e}=this._serviceInfo.capabilities;return(e.maxRecordCount??8e3)*(this.maxRecordCountFactor??1)}get pageSize(){return Math.min(8e3,this.maxPageSize)}enableEvent(e,t){}subscribe(e,t){const s=super.subscribe(e,t);return this._fetchDataTile(e).catch(r=>{ye(r)||ne.getLogger("esri.views.2d.layers.features.sources.BaseFeatureSource").error(new _e("mapview-query-error","Encountered error when fetching tile",{tile:e,error:r}))}),s}unsubscribe(e){super.unsubscribe(e)}readers(e){return this._subscriptions.get(e).readers()}async query(e,t={}){var r;const s=t.query??{};return this._adapter.executeQuery(e,{...t,query:{...s,...(r=this._schema)==null?void 0:r.customParameters}})}async queryLastEditDate(){const e=this._serviceInfo.source,t={...e.query,f:"json"};return(await qt(e.path,{query:t,responseType:"json"})).data.editingInfo.lastEditDate}createTileQuery(e,t={}){const s=this._serviceInfo.geometryType,r=this.createQuery(t);r.quantizationParameters=t.quantizationParameters??e.getQuantizationParameters(),r.resultType="tile",r.geometry=e.extent,this._serviceInfo.capabilities.query.supportsQuantization?s==="esriGeometryPolyline"&&(r.maxAllowableOffset=e.resolution*k("feature-polyline-generalization-factor")):s!=="esriGeometryPolyline"&&s!=="esriGeometryPolygon"||(r.maxAllowableOffset=e.resolution,s==="esriGeometryPolyline"&&(r.maxAllowableOffset*=k("feature-polyline-generalization-factor")));const i=this._serviceInfo.capabilities.query;return r.defaultSpatialReferenceEnabled=i.supportsDefaultSpatialReference,r.compactGeometryEnabled=i.supportsCompactGeometry,r}async _executePatchQuery(e,t,s,r){const i=t.clone();i.outFields=[this._serviceInfo.objectIdField,...s],i.returnCentroid=!1,i.returnGeometry=!1;const n=i.start!=null?i.start/8e3:0,o=r.signal;return await this.enqueuePatchQuery({tile:e,query:i,signal:o,depth:n})}async _resend(e,t){const{query:s,message:r}=e,i=s.outFields!=null?s.outFields:[],n=this._queryInfo.outFields,o=n.filter(u=>!i.includes(u));if(r.addOrUpdate!=null)if(o.length)try{const u=this._subscriptions.get(r.id).tile,h=await this._executePatchQuery(u,s,o,t);B(t),s.outFields=n,r.addOrUpdate.joinAttributes(h),this._onMessage({...r,end:r.end,type:"append"})}catch{}else this._onMessage({...r,type:"append"});else this._onMessage({...r,type:"append"})}async _resendSubscription(e){if(k("esri-2d-update-debug")&&console.debug(e.tile.id,"Resend Subscription"),e.empty)return this._onMessage({id:e.tile.id,addOrUpdate:null,end:!1,type:"append"});const t=e.signal;for(const s of e.requests.done)await this._resend(s,{signal:t});return e.edits!=null?this._onMessage(e.edits):void 0}async resend(){const e=Array.from(this._subscriptions.values());await Promise.all(e.map(t=>this._resendSubscription(t)))}};const Ze=k("esri-mobile"),Je={maxDrillLevel:Ze?1:4,maxRecordCountFactor:Ze?1:3};class Ss extends Le{constructor(e){super(e)}async _fetchDataTile(e){const t=this._serviceInfo.capabilities.query.supportsMaxRecordCountFactor,s=this._subscriptions.get(e.key.id),r=s.signal,i=e.getQuantizationParameters();let n=0;const o=async(u,h)=>{const l=this._queryInfo,d=this.createTileQuery(u,{maxRecordCountFactor:t?Je.maxRecordCountFactor:void 0,returnExceededLimitFeatures:!1,quantizationParameters:i});n++;try{const c=await this.enqueueQuery({tile:e,query:d,signal:r,depth:h});if(n--,B(r),!c)return;if(l!==this._queryInfo)return void o(u,h);if(c.exceededTransferLimit&&h<Je.maxDrillLevel){for(const _ of u.createChildTiles())o(_,h+1);return}const g={id:e.id,addOrUpdate:c,end:n===0,type:"append"};s.add({query:d,message:g}),this._onMessage(g)}catch(c){if(!ye(c)){const g={id:e.id,addOrUpdate:null,end:!0,type:"append"};s.add({query:d,message:g}),this._onMessage(g)}}};o(e,0)}}let ws=class extends Le{constructor(e){super(e)}async _fetchDataTile(e){const r=this._subscriptions.get(e.key.id);let i=!1,n=0,o=0;const u=(d,c)=>{o--,B(r);const g=e.id,_=d.reader,p=d.query;if(!_.exceededTransferLimit){if(i=!0,c!==0&&!_.hasFeatures){const m={id:g,addOrUpdate:_,end:o===0,type:"append"};return r.add({message:m,query:p}),void this._onMessage(m)}const v={id:g,addOrUpdate:_,end:o===0,type:"append"};return r.add({message:v,query:p}),void this._onMessage(v)}const f={id:g,addOrUpdate:_,end:i&&o===0,type:"append"};r.add({message:f,query:p}),this._onMessage(f)};let h=0,l=0;for(;!i&&l++<20;){let d;for(let c=0;c<h+1;c++){const g=n++;o++,d=this._fetchDataTilePage(e,g,r).then(_=>_&&u(_,g)).catch(_=>{if(i=!0,!ye(_)){ne.getLogger("esri.views.2d.layers.features.sources.PagedFeatureSource").error(new _e("mapview-query-error","Encountered error when fetching tile",{tile:e,error:_}));const p={id:e.id,addOrUpdate:null,end:i,type:"append"},f={start:this.pageSize*n,num:this.pageSize,returnExceededLimitFeatures:!0,quantizationParameters:e.getQuantizationParameters()};this.maxRecordCountFactor!=null&&(f.maxRecordCountFactor=this.maxRecordCountFactor);const v=this.createTileQuery(e,f);r.add({message:p,query:v}),this._onMessage(p)}})}await d,B(r),h=Math.min(h+2,6)}}async _fetchDataTilePage(e,t,s){B(s);const r=this._queryInfo,i={start:this.pageSize*t,num:this.pageSize,returnExceededLimitFeatures:!0,quantizationParameters:e.getQuantizationParameters()};this.maxRecordCountFactor!=null&&(i.maxRecordCountFactor=this.maxRecordCountFactor);const n=this.createTileQuery(e,i);try{const o=s.signal,u=await this.enqueueQuery({tile:e,query:n,signal:o,depth:t});return B(s),u?r!==this._queryInfo?this._fetchDataTilePage(e,t,s):{reader:u,query:n}:null}catch(o){return de(o),null}}};function Fs(a,e,t){const s=a.getXHydrated(),r=a.getYHydrated(),i=e.getColumnForX(s),n=Math.floor(e.normalizeCol(i));return`${t}/${Math.floor(e.getRowForY(r))}/${n}`}function Se(a,e){if(a==null)return null;const t=e.transform,s=a.getQuantizationTransform();if(s==null){const[f,v]=t.scale,[m,x]=t.translate,y=-m/f,I=1/f,b=x/v,S=1/-v;return a.transform(y,b,I,S)}const[r,i]=s.scale,[n,o]=s.translate,[u,h]=t.scale,[l,d]=t.translate,c=r/u,g=(n-l)/u,_=i/h,p=(-o+d)/h;return a.transform(g,p,c,_)}let Ae=class extends Le{constructor(e){super(e),this.mode="snapshot",this._loading=!0,this._controller=new AbortController,this._downloadPromise=null,this._didSendEnd=!1,this._queries=new Array,this._invalidated=!1,this._hasAggregates=!1,this._random=new At(1e3),this._store=e.store,this._markedIdsBufId=this._store.storage.createBitset()}destroy(){super.destroy(),this._controller.abort()}get loading(){return this._loading}get _signal(){return this._controller.signal}update(e,t){var s;super.update(e,t),this._featureCount??(this._featureCount=t.initialFeatureCount),t.changedFeatureCount!=null&&(this._featureCount=t.changedFeatureCount),this._hasAggregates=!!((s=e.targets)!=null&&s.aggregate)}async resend(e=!1){if(await this._downloadPromise,this._invalidated||e){const s=this._featureCount;return Ce(s,"Expected featureCount to be defined"),this._invalidated=!1,this._subscriptions.forEach(r=>r.clear()),this._downloadPromise=this._download(s),void await this._downloadPromise}const t=this._queries.map(({query:s,reader:r})=>this._sendPatchQuery(s,r));await Promise.all(t),this._subscriptions.forEach(s=>{s.requests.done.forEach(r=>this._onMessage(r.message))})}async refresh(e,t){t&&(this._featureCount=t.featureCount),await this.resend(!0)}async _sendPatchQuery(e,t){const s=e.outFields!=null?e.outFields:[],r=this._queryInfo.outFields,i=r.filter(h=>!s.includes(h));if(!i.length)return;const n=e.clone(),o=this._signal;n.returnGeometry=!1,n.returnCentroid=!1,n.outFields=i,e.outFields=r;const u=await this.enqueueQuery({query:n,depth:0,signal:o});B({signal:o}),t.joinAttributes(u)}async _fetchDataTile(e){this._downloadPromise??(this._downloadPromise=this._download(this._featureCount));const t=this._store.search(e),s=this._subscriptions.get(e.key.id),r=t.length-1;for(let u=0;u<r;u++){const h=Se(t[u],e),l={type:"append",id:e.id,addOrUpdate:h,end:!1,status:E.empty()};s.add({query:null,message:l}),this._hasAggregates||await ht(1),this._onMessage(l)}const i=Se(r>=0?t[r]:null,e),n=this._didSendEnd,o={type:"append",id:e.id,addOrUpdate:i,end:n,status:E.empty()};s.add({query:null,message:o}),this._onMessage(o)}async _download(e){try{await this.whenInitialized();const t=this._store.storage.getBitset(this._markedIdsBufId),s=new Set;t.clear();const r=Math.ceil(e/this.pageSize),i=Array.from({length:r},(n,o)=>o).sort((n,o)=>this._random.getInt()-this._random.getInt()).map(n=>this._downloadPage(n,t,s));await Promise.all(i),this._store.sweepFeatures(t,this._store.storage),this._store.sweepFeatureSets(s)}catch(t){ne.getLogger("esri.views.2d.layers.features.sources.SnapshotFeatureSource").error("mapview-snapshot-source","Encountered and error when downloading feature snapshot",t)}this._sendEnd(),this._loading=!1}async _downloadPage(e,t,s){const r=this.pageSize,i={start:e*r,num:r,cacheHint:!0};this.maxRecordCountFactor!=null&&(i.maxRecordCountFactor=this.maxRecordCountFactor);const n=this.createQuery(i),o=this._signal,u=await this.enqueueQuery({query:n,depth:e,signal:o});B({signal:o}),this._queries.push({query:n,reader:u}),this._store.insert(u),s.add(u.instance);const h=u.getCursor();for(;h.next();)t.set(h.getDisplayId());this._send(u)}_send(e){if(!this._subscriptions.size)return;let t=null;const s=new Map,r=new Set,i=new Map;this._subscriptions.forEach(n=>{const o=n.tile;s.set(o.key.id,null),t=o.tileInfoView,r.add(o.level);const{row:u,col:h}=o.key,l=`${o.level}/${u}/${h}`,d=i.get(l)??[];d.push(n),i.set(l,d)});for(const n of r){const o=t.getLODInfoAt(n),u=e.getCursor();for(;u.next();){const h=Fs(u,o,n),l=u.getIndex();if(i.has(h))for(const d of i.get(h)){const c=d.tile.id;let g=s.get(c);g==null&&(g=[],s.set(c,g)),g.push(l)}}}s.forEach((n,o)=>{if(n!=null){const u=this._subscriptions.get(o),h={type:"append",id:o,addOrUpdate:Se(Nt.from(e,n),u.tile),end:!1,status:E.empty()};u.add({query:null,message:h}),this._onMessage(h)}})}_sendEnd(){this._subscriptions.forEach(e=>{const t={type:"append",id:e.tile.id,addOrUpdate:null,end:!0,status:E.empty()};e.add({query:null,message:t}),this._onMessage(t)}),this._didSendEnd=!0}};Ae=A([me("esri.view.2d.layers.features.sources.SnapshotFeatureSource")],Ae);const Ts="__esri_stream_id__",We="__esri_timestamp__",Ke=1e3;class Cs{constructor(e,t,s,r,i=128){this._trackIdToObservations=new Map,this._idCounter=0,this._lastPurge=performance.now(),this._addOrUpdated=new Map,this._removed=[],this._maxAge=0,this._timeInfo=s,this._purgeOptions=r,this.store=e,this.objectIdField=t,this.purgeInterval=i,this._useGeneratedIds=this.objectIdField===Ts}removeById(e){this._removed.push(e)}removeByTrackId(e){const t=this._trackIdToObservations.get(e);if(t)for(const s of t.entries)this._removed.push(s)}add(e){var n;if(this._useGeneratedIds){const o=this._nextId();e.attributes[this.objectIdField]=o,e.objectId=o}else e.objectId=e.attributes[this.objectIdField];const t=e.objectId;if(this._addOrUpdated.set(t,e),this._maxAge=Math.max(this._maxAge,e.attributes[this._timeInfo.startTimeField]),!this._timeInfo.trackIdField)return this._trackIdLessObservations==null&&(this._trackIdLessObservations=new pe(1e5)),void this._trackIdLessObservations.enqueue(t);const s=e.attributes[this._timeInfo.trackIdField];if(!this._trackIdToObservations.has(s)){const o=((n=this._purgeOptions)==null?void 0:n.maxObservations)!=null?this._purgeOptions.maxObservations:Ke,u=Rt(o,0,Ke);this._trackIdToObservations.set(s,new pe(u))}const r=this._trackIdToObservations.get(s),i=r==null?void 0:r.enqueue(t);i!=null&&(this._addOrUpdated.has(i)?this._addOrUpdated.delete(i):this._removed.push(i))}checkForUpdates(){const e=this._getToAdd(),t=this._getToRemove(),s=performance.now();s-this._lastPurge>=this.purgeInterval&&(this._purge(s),this._lastPurge=s);const r=[];if(t!=null)for(const n of t){const o=this.store.removeById(n);o!=null&&r.push(o)}const i=[];if(e!=null){const n=new Set(t??[]);for(const o of e)n.has(o.objectId)||(o.attributes[We]=s,this.store.add(o),i.push(o))}(i.length||r!=null&&r.length)&&this.store.update(i,r)}_getToAdd(){if(!this._addOrUpdated.size)return null;const e=new Array(this._addOrUpdated.size);let t=0;return this._addOrUpdated.forEach(s=>e[t++]=s),this._addOrUpdated.clear(),e}_getToRemove(){const e=this._removed;return this._removed.length?(this._removed=[],e):null}_nextId(){const e=this._idCounter;return this._idCounter=(this._idCounter+1)%4294967294+1,e}_purge(e){const t=this._purgeOptions;t!=null&&(this._purgeSomeByDisplayCount(t),this._purgeByAge(t),this._purgeByAgeReceived(e,t),this._purgeTracks())}_purgeSomeByDisplayCount(e){if(!e.displayCount)return;let t=this.store.size;if(t>e.displayCount){if(this._timeInfo.trackIdField){for(const s of this._trackIdToObservations.values())if(t>e.displayCount&&s.size){const r=s.dequeue();this._removed.push(r),t--}}if(this._trackIdLessObservations!=null){let s=t-e.displayCount;for(;s-- >0;){const r=this._trackIdLessObservations.dequeue();r!=null&&this._removed.push(r)}}}}_purgeByAge(e){var i;const t=(i=this._timeInfo)==null?void 0:i.startTimeField;if(!e.age||!t)return;const s=60*e.age*1e3,r=this._maxAge-s;this.store.forEach(n=>{n.attributes[t]<r&&this._removed.push(n.objectId)})}_purgeByAgeReceived(e,t){if(!t.ageReceived)return;const s=e-60*t.ageReceived*1e3;this.store.forEach(r=>{r.attributes[We]<s&&this._removed.push(r.objectId)})}_purgeTracks(){this._trackIdToObservations.forEach((e,t)=>{e.size===0&&this._trackIdToObservations.delete(t)})}}let ie=class extends Ee{constructor(e){super(e)}get connectionStatus(){var e;return(e=this.connection)==null?void 0:e.connectionStatus}get errorString(){var e;return(e=this.connection)==null?void 0:e.errorString}};A([O()],ie.prototype,"connection",void 0),A([O()],ie.prototype,"connectionStatus",null),A([O()],ie.prototype,"errorString",null),ie=A([me("esri.views.2d.layers.features.sources.StreamConnectionState")],ie);const ks=2500;function Ms(a,e){const t=a.weakClone();if(a.geometry!=null){const s=pt(e,a.geometry.coords[0]),r=ft(e,a.geometry.coords[1]);t.geometry=new Q([],[s,r])}return t}function qs(a){return a==="esriGeometryPoint"?Ms:(e,t)=>{const s=e.weakClone(),r=new Q,i=!1,n=!1,o=Me(r,e.geometry,i,n,a,t,!1,!1);return s.geometry=o,s}}function As(a){return a==="esriGeometryPoint"?e=>e.geometry!=null?{minX:e.geometry.coords[0],minY:e.geometry.coords[1],maxX:e.geometry.coords[0],maxY:e.geometry.coords[1]}:{minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}:e=>{let t=1/0,s=1/0,r=-1/0,i=-1/0;return e.geometry!=null&&e.geometry.forEachVertex((n,o)=>{t=Math.min(t,n),s=Math.min(s,o),r=Math.max(r,n),i=Math.max(i,o)}),{minX:t,minY:s,maxX:r,maxY:i}}}function Rs(a,e){const t=$t(9,As(e));return t.load(a),t}function Es(a,e){return a.search({minX:e.bounds[0],minY:e.bounds[1],maxX:e.bounds[2],maxY:e.bounds[3]})}class $s{constructor(e,t){this.onUpdate=e,this._geometryType=t,this._objectIdToFeature=new Map,this._index=null}get _features(){const e=[];return this._objectIdToFeature.forEach(t=>e.push(t)),e}add(e){this._objectIdToFeature.set(e.objectId,e),this._index=null}get(e){return this._objectIdToFeature.has(e)?this._objectIdToFeature.get(e):null}forEach(e){this._objectIdToFeature.forEach(e)}search(e){return this._index||(this._index=Rs(this._features,this._geometryType)),Es(this._index,e)}clear(){this._index=null,this._objectIdToFeature.clear()}removeById(e){const t=this._objectIdToFeature.get(e);return t?(this._objectIdToFeature.delete(e),this._index=null,t):null}update(e,t){this.onUpdate(e,t)}get size(){return this._objectIdToFeature.size}}class Us extends bt{constructor(e){super(e),this.type="stream",this._updateIntervalId=0,this._level=0,this._isPaused=!1,this._updateInfo={websocket:0,client:0},this._inUpdate=!1;const{outSR:t}=e,{geometryType:s,objectIdField:r,timeInfo:i,purgeOptions:n,source:o,spatialReference:u,serviceFilter:h,maxReconnectionAttempts:l,maxReconnectionInterval:d,updateInterval:c,customParameters:g,enabledEventTypes:_}=e.serviceInfo,p=new $s(this._onUpdate.bind(this),s),f=new Cs(p,r,i,n),v=es(o,u,t,s,h,l,d,g??{});this._connectionState=new ie({connection:v}),this._store=p,this._manager=f,this._connection=v,this._quantize=qs(s),this._enabledEventTypes=new Set(_),this._handlesGroup=Et([this._connection.on("data-received",m=>this._onFeature(m)),this._connection.on("message-received",m=>this._onWebSocketMessage(m))]),this._initUpdateInterval=()=>{let m=performance.now();this._updateIntervalId=setInterval(()=>{const x=performance.now(),y=x-m;if(y>ks){m=x;const I=Math.round(this._updateInfo.client/(y/1e3)),b=Math.round(this._updateInfo.websocket/(y/1e3));this._updateInfo.client=0,this._updateInfo.websocket=0,this.events.emit("updateRate",{client:I,websocket:b})}e.canAcceptRequest()&&!this._inUpdate&&this._manager.checkForUpdates()},c)},this._isPaused=e.serviceInfo.isPaused,this._isPaused||this._initUpdateInterval()}destroy(){var e;super.destroy(),this._clearUpdateInterval(),this._connection.destroy(),(e=this._handlesGroup)==null||e.remove()}_fetchDataTile(){}get connectionStatus(){return this._connectionState.connectionStatus}get errorString(){return this._connectionState.errorString}updateCustomParameters(e){this._connection.updateCustomParameters(e)}pauseStream(){this._isPaused||(this._isPaused=!0,this._clearUpdateInterval())}resumeStream(){this._isPaused&&(this._isPaused=!1,this._initUpdateInterval())}sendMessageToSocket(e){this._connection.sendMessageToSocket(e)}sendMessageToClient(e){this._isPaused&&"type"in e&&e.type==="clear"?(this._store.clear(),this._subscriptions.forEach((t,s)=>{t.didSend&&t.tile.level===this._level&&this._onMessage({type:"append",id:s,addOrUpdate:null,clear:!0,end:!0})})):this._connection.sendMessageToClient(e)}enableEvent(e,t){t?this._enabledEventTypes.add(e):this._enabledEventTypes.delete(e)}subscribe(e,t){const s=super.subscribe(e,t);this._level=e.level;const r=this._getTileFeatures(e);return this._onMessage({type:"append",id:e.key.id,addOrUpdate:r,end:!0}),s.didSend=!0,s}unsubscribe(e){super.unsubscribe(e)}*readers(e){const t=this._subscriptions.get(e),{tile:s}=t;yield this._getTileFeatures(s)}createTileQuery(e){throw new Error("Service does not support tile queries")}async resend(){this._subscriptions.forEach(e=>{const{tile:t}=e,s={type:"append",id:t.id,addOrUpdate:this._getTileFeatures(t),end:!0};this._onMessage(s)})}_getTileFeatures(e){const t=this._store.search(e).map(s=>this._quantize(s,e.transform));return G.fromOptimizedFeatures(t,this._arcadeLayerSchema,e.transform)}_onWebSocketMessage(e){if(this._enabledEventTypes.has("message-received")&&this.events.emit("message-received",e),"type"in e)switch(e.type){case"delete":if(e.objectIds)for(const t of e.objectIds)this._manager.removeById(t);if(e.trackIds)for(const t of e.trackIds)this._manager.removeByTrackId(t);break;case"clear":this._store.forEach(t=>this._manager.removeById(t.objectId))}}_onFeature(e){this._updateInfo.websocket++;try{this._enabledEventTypes.has("data-received")&&this.events.emit("data-received",e);const t=jt(e,this._serviceInfo.geometryType,!1,!1,this._serviceInfo.objectIdField);this._manager.add(t)}catch{}}_clearUpdateInterval(){clearInterval(this._updateIntervalId),this._updateIntervalId=0}async _onUpdate(e,t){this._inUpdate=!0;try{e!=null&&(this._updateInfo.client+=e.length),this._subscriptions.forEach((r,i)=>{r.didSend&&r.tile.level===this._level&&this._onMessage({type:"append",id:i,addOrUpdate:null,clear:!0,end:!1})});const s=[];this._subscriptions.forEach((r,i)=>{if(!r.didSend||r.tile.level!==this._level)return;const n=r.tile,o={type:"append",id:i,addOrUpdate:this._getTileFeatures(n),remove:[],end:!1,status:E.empty()};r.requests.stream.enqueue(o),s.push(this._onMessage(o))}),await Promise.all(s),this._subscriptions.forEach((r,i)=>{r.didSend&&r.tile.level===this._level&&this._onMessage({type:"append",id:i,addOrUpdate:null,end:!0})})}catch{}this._inUpdate=!1}}function Os(a,e,t,s,r,i,n){const o=Ls(a,e,t,s,r,i,n);switch(o.type){case"feature":switch(o.origin){case"hosted":case"local":return new ws(o);case"snapshot":return new Ae(o);default:return new Ss(o)}case"stream":return new Us(o)}}function Ls(a,e,t,s,r,i,n){switch(a.type){case"snapshot":return{type:"feature",origin:"snapshot",featureCount:a.featureCount??0,serviceInfo:a,onMessage:r,outSR:t,tileInfoView:s,canAcceptRequest:i,store:n,arcadeLayerSchema:e};case"stream":return{type:"stream",serviceInfo:a,onMessage:r,outSR:t,canAcceptRequest:i,arcadeLayerSchema:e};case"memory":case"on-demand":return{type:"feature",serviceInfo:a,onMessage:r,outSR:t,origin:o(a.source),tileInfoView:s,canAcceptRequest:i,arcadeLayerSchema:e}}function o(u){return Array.isArray(u)?"local":"path"in u&&ot(u.path)?"hosted":"unknown"}}class xt{constructor(e=[],t,s=8096){this.onRelease=r=>{},this._nodes=0,this._root=new we(this,0,0,0),this._statisticFields=e,this._pool=s?new pe(8096):null,this._serviceInfo=t}destroy(){this.clear()}_acquire(e,t,s){this._nodes++;let r=null;return this._pool!=null&&(r=this._pool.dequeue()),r!=null?r.realloc(e,t,s):r=new we(this,e,t,s),r}_release(e){this.onRelease(e),this._nodes--,this._pool!=null&&this._pool.enqueue(e)}get count(){return this._root.count}get size(){return this._nodes}get poolSize(){var e;return((e=this._pool)==null?void 0:e.size)??0}get depth(){let e=0;return this.forEach(t=>e=Math.max(e,t.depth)),e}dropLevels(e){this.forEach(t=>{if(t.depth>=e)for(let s=0;s<t.children.length;s++){const r=t.children[s];r&&this._release(r)}}),this.forEach(t=>{if(t.depth>=e)for(let s=0;s<t.children.length;s++)t.children[s]=null})}clear(){this.forEach(e=>this._release(e)),this._root=new we(this,0,0,0)}insert(e,t,s=0){const r=G.fromOptimizedFeatures([e],this._serviceInfo).getCursor();r.next();const i=r.readGeometry();if(!i)return;const[n,o]=i.coords,u=e.geohashX,h=e.geohashY;this.insertCursor(r,e.displayId,n,o,u,h,t,s)}insertCursor(e,t,s,r,i,n,o,u=0){let h=this._root,l=0,d=0,c=0;for(;h!==null;){if(h.depth>=u&&(h.count+=1,h.xTotal+=s,h.yTotal+=r,h.xGeohashTotal+=i,h.yGeohashTotal+=n,h.referenceId=t,this._updateStatisticsCursor(e,h,1)),l>=o)return void h.add(t);const g=Math.ceil((l+1)/2),_=Math.floor((l+1)/2),p=1-l%2,f=30-(3*g+2*_),v=30-(2*g+3*_),m=(i&7*p+3*(1-p)<<f)>>f,x=(n&3*p+7*(1-p)<<v)>>v,y=m+x*(8*p+4*(1-p));d=d<<3*p+2*(1-p)|m,c=c<<2*p+3*(1-p)|x,h.children[y]==null&&(h.children[y]=this._acquire(d,c,l+1)),l+=1,h=h.children[y]}}remove(e,t){const s=G.fromOptimizedFeatures([e],this._serviceInfo).getCursor();s.next();const r=s.readGeometry();if(!r)return;const[i,n]=r.coords,o=e.geohashX,u=e.geohashY;this.removeCursor(s,i,n,o,u,t)}removeCursor(e,t,s,r,i,n){let o=this._root,u=0;for(;o!==null;){if(o.count-=1,o.xTotal-=t,o.yTotal-=s,o.xGeohashTotal-=r,o.yGeohashTotal-=i,this._updateStatisticsCursor(e,o,-1),u>=n)return void o.remove(e.getDisplayId());const h=Math.ceil((u+1)/2),l=Math.floor((u+1)/2),d=1-u%2,c=30-(3*h+2*l),g=30-(2*h+3*l),_=((r&7*d+3*(1-d)<<c)>>c)+((i&3*d+7*(1-d)<<g)>>g)*(8*d+4*(1-d)),p=o.children[_];(p==null?void 0:p.count)===1&&(this._release(p),o.children[_]=null),u+=1,o=p}}forEach(e){let t=this._root;for(;t!==null;){const s=this._linkChildren(t)||t.next;e(t),t=s}}find(e,t,s){return this._root.find(e,t,s,0,0,0)}findIf(e){let t=null;return this.forEach(s=>{e(s)&&(t=s)}),t}findAllIf(e){const t=[];return this.forEach(s=>{e(s)&&t.push(s)}),t}findSingleOccupancyNode(e,t,s,r,i){let n=this._root;for(;n!==null;){const o=n.depth,u=n.xNode,h=n.yNode,l=1-o%2,d=n.xGeohashTotal/n.count,c=n.yGeohashTotal/n.count;if(n.count===1&&e<d&&d<=s&&t<c&&c<=r)return n;if(o>=i){n=n.next;continue}const g=Math.ceil((o+1)/2),_=Math.floor((o+1)/2),p=30-(3*g+2*_),f=30-(2*g+3*_),v=~((1<<p)-1),m=~((1<<f)-1),x=(e&v)>>p,y=(t&m)>>f,I=(s&v)>>p,b=(r&m)>>f,S=u<<3*l+2*(1-l),M=h<<2*l+3*(1-l),F=S+8*l+4*(1-l),w=M+4*l+8*(1-l),C=Math.max(S,x),T=Math.max(M,y),q=Math.min(F,I),R=Math.min(w,b);let U=null,V=null;for(let $=T;$<=R;$++)for(let N=C;N<=q;N++){const z=N-S+($-M)*(8*l+4*(1-l)),L=n.children[z];L&&(U||(U=L,U.next=n.next),V&&(V.next=L),V=L,L.next=n.next)}n=U||n.next}return null}getRegionDisplayIds(e){let t=this._root;const{bounds:s,geohashBounds:r,level:i}=e,[n,o,u,h]=s,l=[];for(;t!==null;){const d=t.depth,c=t.xNode,g=t.yNode;if(d>=i){const z=t.xTotal/t.count,L=t.yTotal/t.count;z>=n&&z<=u&&L>=o&&L<=h&&t.displayIds.forEach(Y=>l.push(Y)),t=t.next;continue}const _=Math.ceil((d+1)/2),p=Math.floor((d+1)/2),f=1-d%2,v=30-(3*_+2*p),m=30-(2*_+3*p),x=~((1<<v)-1),y=~((1<<m)-1),I=(r.xLL&x)>>v,b=(r.yLL&y)>>m,S=(r.xTR&x)>>v,M=(r.yTR&y)>>m,F=c<<3*f+2*(1-f),w=g<<2*f+3*(1-f),C=F+8*f+4*(1-f),T=w+4*f+8*(1-f),q=Math.max(F,I),R=Math.max(w,b),U=Math.min(C,S),V=Math.min(T,M);let $=null,N=null;for(let z=R;z<=V;z++)for(let L=q;L<=U;L++){const Y=L-F+(z-w)*(8*f+4*(1-f)),H=t.children[Y];H&&($||($=H,$.next=t.next),N&&(N.next=H),N=H,H.next=t.next)}t=$||t.next}return l}getRegionStatistics(e){let t=this._root,s=0,r=0,i=0;const n={},{bounds:o,geohashBounds:u,level:h}=e,[l,d,c,g]=o;let _=0;for(;t!==null;){const p=t.depth,f=t.xNode,v=t.yNode;if(p>=h){const X=t.xTotal/t.count,Z=t.yTotal/t.count;X>l&&X<=c&&Z>d&&Z<=g&&(s+=t.count,r+=t.xTotal,i+=t.yTotal,t.count===1&&(_=t.referenceId),this._aggregateStatistics(n,t.statistics)),t=t.next;continue}const m=Math.ceil((p+1)/2),x=Math.floor((p+1)/2),y=1-p%2,I=30-(3*m+2*x),b=30-(2*m+3*x),S=~((1<<I)-1),M=~((1<<b)-1),F=(u.xLL&S)>>I,w=(u.yLL&M)>>b,C=(u.xTR&S)>>I,T=(u.yTR&M)>>b,q=f<<3*y+2*(1-y),R=v<<2*y+3*(1-y),U=q+8*y+4*(1-y),V=R+4*y+8*(1-y),$=Math.max(q,F),N=Math.max(R,w),z=Math.min(U,C),L=Math.min(V,T);let Y=null,H=null;for(let X=N;X<=L;X++)for(let Z=$;Z<=z;Z++){const St=Z-q+(X-R)*(8*y+4*(1-y)),P=t.children[St];if(P){if(X!==N&&X!==L&&Z!==$&&Z!==z){const Qe=P.xTotal/P.count,Ge=P.yTotal/P.count;Qe>l&&Qe<=c&&Ge>d&&Ge<=g&&(s+=P.count,r+=P.xTotal,i+=P.yTotal,P.count===1&&(_=P.referenceId),this._aggregateStatistics(n,P.statistics));continue}Y||(Y=P,Y.next=t.next),H&&(H.next=P),H=P,P.next=t.next}}t=Y||t.next}return{count:s,attributes:this.normalizeStatistics(n,s),xTotal:r,yTotal:i,referenceId:_}}getBins(e){const t=[],{geohashBounds:s,level:r}=e;let i=this._root;for(;i!==null;){const n=i.depth,o=i.xNode,u=i.yNode;if(n>=r){t.push(i),i=i.next;continue}const h=Math.ceil((n+1)/2),l=Math.floor((n+1)/2),d=1-n%2,c=30-(3*h+2*l),g=30-(2*h+3*l),_=~((1<<c)-1),p=~((1<<g)-1),f=(s.xLL&_)>>c,v=(s.yLL&p)>>g,m=(s.xTR&_)>>c,x=(s.yTR&p)>>g,y=o<<3*d+2*(1-d),I=u<<2*d+3*(1-d),b=y+8*d+4*(1-d),S=I+4*d+8*(1-d),M=Math.max(y,f),F=Math.max(I,v),w=Math.min(b,m),C=Math.min(S,x);let T=null,q=null;for(let R=F;R<=C;R++)for(let U=M;U<=w;U++){const V=U-y+(R-I)*(8*d+4*(1-d)),$=i.children[V];$&&(T||(T=$,T.next=i.next),q&&(q.next=$),q=$,$.next=i.next)}i=T||i.next}return t}_linkChildren(e){let t=null,s=null;for(let r=0;r<=e.children.length;r++){const i=e.children[r];i&&(t||(t=i,t.next=e.next),s&&(s.next=i),s=i,i.next=e.next)}return t}_updateStatisticsCursor(e,t,s){for(const r of this._statisticFields){const i=r.name,n=r.inField?e.readAttribute(r.inField):e.getComputedNumericAtIndex(r.inFieldIndex);switch(r.statisticType){case"min":{if(isNaN(n))break;if(!t.statistics[i]){t.statistics[i]={value:n};break}const o=t.statistics[i].value;t.statistics[i].value=Math.min(o,n);break}case"max":{if(isNaN(n))break;if(!t.statistics[i]){t.statistics[i]={value:n};break}const o=t.statistics[i].value;t.statistics[i].value=Math.max(o,n);break}case"count":break;case"sum":case"avg":{t.statistics[i]||(t.statistics[i]={value:0,nanCount:0});const o=t.statistics[i].value,u=t.statistics[i].nanCount??0;n==null||isNaN(n)?t.statistics[i].nanCount=u+s:t.statistics[i].value=o+s*n;break}case"avg_angle":{t.statistics[i]||(t.statistics[i]={x:0,y:0,nanCount:0});const o=t.statistics[i].x,u=t.statistics[i].y,h=t.statistics[i].nanCount??0,l=Math.PI/180;n==null||isNaN(n)?t.statistics[i].nanCount=h+s:(t.statistics[i].x=o+s*Math.cos(n*l),t.statistics[i].y=u+s*Math.sin(n*l));break}case"mode":{t.statistics[i]||(t.statistics[i]={});const o=t.statistics[i][n]||0;t.statistics[i][n]=o+s;break}}}}_aggregateStatistics(e,t){for(const s of this._statisticFields){const r=s.name;switch(s.statisticType){case"min":{if(!e[r]){e[r]={value:t[r].value};break}const i=e[r].value;e[r].value=Math.min(i,t[r].value);break}case"max":{if(!e[r]){e[r]={value:t[r].value};break}const i=e[r].value;e[r].value=Math.max(i,t[r].value);break}case"count":break;case"sum":case"avg":case"avg_angle":case"mode":e[r]||(e[r]={});for(const i in t[r]){const n=e[r][i]||0;e[r][i]=n+t[r][i]}}}}normalizeStatistics(e,t){const s={};for(const r of this._statisticFields){const i=r.name;switch(r.statisticType){case"min":case"max":{const n=e[i];if(!t||!n)break;s[i]=n.value;break}case"count":if(!t)break;s[i]=t;break;case"sum":{if(!t)break;const{value:n,nanCount:o}=e[i];if(!(t-o))break;s[i]=n;break}case"avg":{if(!t)break;const{value:n,nanCount:o}=e[i];if(!(t-o))break;s[i]=n/(t-o);break}case"avg_angle":{if(!t)break;const{x:n,y:o,nanCount:u}=e[i];if(!(t-u))break;const h=n/(t-u),l=o/(t-u),d=180/Math.PI,c=Math.atan2(l,h)*d;s[i]=c;break}case"mode":{const n=e[i];let o=0,u=0,h=null;for(const l in n){const d=n[l];d===o?u+=1:d>o&&(o=d,u=1,h=l)}s[i]=h==="null"||u>1?null:h;break}}}return s}}class we{constructor(e,t,s,r){this.count=0,this.xTotal=0,this.yTotal=0,this.statistics={},this.displayId=0,this.referenceId=0,this.displayIds=new Set,this.next=null,this.depth=0,this.xNode=0,this.yNode=0,this.xGeohashTotal=0,this.yGeohashTotal=0,this._tree=e,this.children=new Array(32);for(let i=0;i<this.children.length;i++)this.children[i]=null;this.xNode=t,this.yNode=s,this.depth=r}realloc(e,t,s){for(let r=0;r<this.children.length;r++)this.children[r]=null;return this.xNode=e,this.yNode=t,this.depth=s,this.next=null,this.xGeohashTotal=0,this.yGeohashTotal=0,this.displayId=0,this.referenceId=0,this.xTotal=0,this.yTotal=0,this.count=0,this.statistics={},this.displayIds.clear(),this}get id(){return`${this.xNode}.${this.yNode}`}add(e){this.displayIds.add(e)}remove(e){this.displayIds.delete(e)}getAttributes(){const e=this._tree.normalizeStatistics(this.statistics,this.count);return e.referenceId=null,e.aggregateId=this.id,e.aggregateCount=this.count,e}getGeometry(e,t){const s=this.getLngLatBounds(),[r,i,n,o]=s,u=ae({rings:[[[r,i],[r,o],[n,o],[n,i],[r,i]]]},K.WGS84,e),h=Ue(new Q,u,!1,!1);return t!=null?Me(new Q,h,!1,!1,"esriGeometryPolygon",t,!1,!1):h}getGeometryCentroid(e,t){const s=this.getLngLatBounds(),[r,i,n,o]=s,u=ae({x:(r+n)/2,y:(i+o)/2},K.WGS84,e),h=zt(new Q,u);return t!=null?Me(new Q,h,!1,!1,"esriGeometryPoint",t,!1,!1):h}getLngLatBounds(){const e=this.depth,t=Math.ceil(e/2),s=Math.floor(e/2),r=30-(3*t+2*s),i=30-(2*t+3*s),n=this.xNode<<r,o=this.yNode<<i;return ts({geohashX:n,geohashY:o},this.depth)}find(e,t,s,r,i,n){if(r>=s)return this;const o=1-r%2,u=3*o+2*(1-o),h=2*o+3*(1-o),l=30-i-u,d=30-n-h,c=((e&7*o+3*(1-o)<<l)>>l)+((t&3*o+7*(1-o)<<d)>>d)*(8*o+4*(1-o)),g=this.children[c];return g==null?null:g.find(e,t,s,r+1,i+u,n+h)}}const Fe=ne.getLogger("esri.view.2d.layers.features.support.BinStore"),et=12,Ps=64,Qs=ut(),Gs=5;function tt(a){return 57.29577951308232*a}let Bs=class extends yt{constructor(e,t,s,r){super(e,s),this.type="bin",this.events=new Re,this.objectIdField="aggregateId",this.featureAdapter=mt,this._geohashLevel=Gs,this._geohashBuf=[],this._serviceInfo=r,this.geometryInfo=e.geometryInfo,this._spatialReference=t,this._projectionSupportCheck=vt(t,K.WGS84),this._bitsets.geohash=s.getBitset(s.createBitset()),this._bitsets.inserted=s.getBitset(s.createBitset())}destroy(){this._tree&&this._tree.destroy()}get featureSpatialReference(){return this._spatialReference}get fields(){return this._fields}async updateSchema(e,t){const s=this._schema;try{await super.updateSchema(e,t),await this._projectionSupportCheck}catch{}this._fields=this._schema.params.fields,this._fieldsIndex=new te(this._fields);const r=le(s,t);t&&(r!=null||e.source||e.storage.filters)?((ce(r,"params.fields")||ce(r,"params")||!this._tree||e.source)&&(this._tree&&this._tree.destroy(),this._tree=new xt(this._statisticFields,this._serviceInfo),this._tree.onRelease=i=>i.displayId&&this._storage.releaseDisplayId(i.displayId),this._geohashLevel=this._schema.params.fixedBinLevel,this._rebuildTree(),k("esri-2d-update-debug")&&Fe.info("Aggregate mesh needs update due to tree changing")),k("esri-2d-update-debug")&&Fe.info("Aggregate mesh needs update due to tree changing"),e.targets[t.name]=!0,e.mesh=!1):s&&(e.mesh=!0)}clear(){this._rebuildTree()}sweepFeatures(e,t){this._bitsets.inserted.forEachSet(s=>{if(!e.has(s)){const r=t.lookupByDisplayIdUnsafe(s);this._remove(r)}})}sweepAggregates(e,t,s){}onTileData(e,t,s,r,i,n=!0){if(!this._schema||t.addOrUpdate==null)return t;this.events.emit("changed");const o=this._getTransforms(e,this._spatialReference);{const h=t.addOrUpdate.getCursor();for(;h.next();)this._update(h,r)}if(t.status.mesh||!n)return t;const u=new Array;this._getBinsForTile(u,e,o,s),t.addOrUpdate=G.fromOptimizedFeatures(u,{fields:this.fields,fieldsIndex:this._fieldsIndex,geometryType:"esriGeometryPolygon",objectIdField:this.objectIdField}),t.addOrUpdate.attachStorage(s),t.end=!0,t.isRepush||(t.clear=!0);{const h=t.addOrUpdate.getCursor();for(;h.next();){const l=h.getDisplayId();this._bitsets.computed.unset(l),this.setComputedAttributes(s,h,l,e.scale,i)}}return t}forEachBin(e){this._tree.forEach(e)}forEach(e){this._tree.forEach(t=>{if(t.depth!==this._geohashLevel)return;const s=this._toFeatureJSON(t),r=G.fromFeatures([s],{objectIdField:this.objectIdField,globalIdField:null,geometryType:this.geometryInfo.geometryType,fields:this.fields,fieldsIndex:this._fieldsIndex}).getCursor();r.next(),e(r)})}forEachInBounds(e,t){}forEachBounds(e,t){const{hasM:s,hasZ:r}=this.geometryInfo;for(const i of e){const n=_t(Qs,i.readGeometry(),r,s);n!=null&&t(n)}}onTileUpdate(e){}getAggregate(e){const t=ss(e,!0),s=this._tree.findIf(r=>r.displayId===t);return s?this._toFeatureJSON(s):null}getAggregates(){return this._tree.findAllIf(e=>e.depth===this._geohashLevel).map(this._toFeatureJSON.bind(this))}getDisplayId(e){var t;return(t=this._tree.findIf(s=>s.id===e))==null?void 0:t.displayId}getFeatureDisplayIdsForAggregate(e){const t=this._tree.findIf(s=>s.id===e);return t!=null?Array.from(t.displayIds):[]}getDisplayIdForReferenceId(e){var t;return(t=this._tree.findIf(s=>s.displayIds.size===1&&s.displayIds.has(e)))==null?void 0:t.displayId}_toFeatureJSON(e){const t=this._spatialReference;return{displayId:e.displayId,attributes:e.getAttributes(),geometry:$e(e.getGeometry(t),"esriGeometryPolygon",!1,!1),centroid:null}}_rebuildTree(){this._bitsets.computed.clear(),this._bitsets.inserted.clear(),this._tree&&this._tree.clear()}_remove(e){const t=e.getDisplayId(),s=e.getXHydrated(),r=e.getYHydrated(),i=this._geohashBuf[2*t],n=this._geohashBuf[2*t+1];this._bitsets.inserted.has(t)&&(this._bitsets.inserted.unset(t),this._tree.removeCursor(e,s,r,i,n,this._geohashLevel))}_update(e,t){const s=e.getDisplayId(),r=this._bitsets.inserted,i=t.isVisible(s);if(i===r.has(s))return;if(!i)return void this._remove(e);const n=e.getXHydrated(),o=e.getYHydrated();if(!this._setGeohash(s,n,o))return;const u=this._geohashBuf[2*s],h=this._geohashBuf[2*s+1];this._tree.insertCursor(e,s,n,o,u,h,this._geohashLevel),r.set(s)}_setGeohash(e,t,s){if(this._bitsets.geohash.has(e))return!0;const r=this._geohashBuf;if(this._spatialReference.isWebMercator){const i=tt(t/W.radius),n=i-360*Math.floor((i+180)/360),o=tt(Math.PI/2-2*Math.atan(Math.exp(-s/W.radius)));fe(r,e,o,n,et)}else{const i=ae({x:t,y:s},this._spatialReference,K.WGS84);if(!i)return!1;fe(r,e,i.y,i.x,et)}return this._bitsets.geohash.set(e),!0}_getBinsForTile(e,t,s,r){try{const i=this._getGeohashBounds(t),n=this._tree.getBins(i);for(const o of n){o.displayId||(o.displayId=r.createDisplayId(!0));let u=null;const h=o.getGeometry(this._spatialReference,s.tile);h||(u=o.getGeometryCentroid(this._spatialReference,s.tile));const l=new Oe(h,o.getAttributes(),u);l.objectId=o.id,l.displayId=o.displayId,e.push(l)}}catch{return void Fe.error("Unable to get bins for tile",t.key.id)}}_getGeohash(e,t,s){const r={geohashX:0,geohashY:0};return ue(r,t,e,s),r}_getGeohashBounds(e){const t=this._getGeohashLevel(e.key.level),s=[e.extent.xmin,e.extent.ymin,e.extent.xmax,e.extent.ymax],r=dt.fromExtent(lt.fromBounds(s,this._spatialReference)),i=ae(r,this._spatialReference,K.WGS84,{densificationStep:e.resolution*Ps}),n=Ue(new Q,i,!1,!1),o=n.coords.filter((p,f)=>!(f%2)),u=n.coords.filter((p,f)=>f%2),h=Math.min(...o),l=Math.min(...u),d=Math.max(...o),c=Math.max(...u),g=this._getGeohash(h,l,t),_=this._getGeohash(d,c,t);return{bounds:s,geohashBounds:{xLL:g.geohashX,yLL:g.geohashY,xTR:_.geohashX,yTR:_.geohashY},level:t}}_getGeohashLevel(e){return this._schema.params.fixedBinLevel}_getTransforms(e,t){const s={originPosition:"upperLeft",scale:[e.resolution,e.resolution],translate:[e.bounds[0],e.bounds[3]]},r=ct(t);if(!r)return{tile:s,left:null,right:null};const[i,n]=r.valid;return{tile:s,left:{...s,translate:[n,e.bounds[3]]},right:{...s,translate:[i-n+e.bounds[0],e.bounds[3]]}}}};const Te=12,Ds=64,st=1,js=ut();class Pe extends Jt{constructor(e,t,s,r,i){super(new Q([],[t,s]),r,null,e),this.geohashBoundsInfo=i}get count(){return this.attributes.cluster_count}static create(e,t,s,r,i,n,o,u){const h=new Pe(t,s,r,n,o);return h.displayId=e.createDisplayId(!0),h.referenceId=u,h.tileLevel=i,h}update(e,t,s,r,i,n){return this.geometry.coords[0]=e,this.geometry.coords[1]=t,this.tileLevel=s,this.attributes=r,this.geohashBoundsInfo=i,this.referenceId=null,this.referenceId=n,this}toJSON(){return{attributes:{...this.attributes,aggregateId:this.objectId,referenceId:this.attributes.cluster_count===1?this.referenceId:null},geometry:{x:this.geometry.coords[0],y:this.geometry.coords[1]}}}}function re(a){return 57.29577951308232*a}class zs extends yt{constructor(e,t,s,r){super(e,s),this.type="cluster",this.events=new Re,this.objectIdField="aggregateId",this.featureAdapter=mt,this._geohashLevel=0,this._tileLevel=0,this._aggregateValueRanges={},this._aggregateValueRangesChanged=!1,this._geohashBuf=[],this._clusters=new Map,this._tiles=new Map,this._serviceInfo=r,this.geometryInfo=e.geometryInfo,this._spatialReference=t,this._projectionSupportCheck=vt(t,K.WGS84),this._bitsets.geohash=s.getBitset(s.createBitset()),this._bitsets.inserted=s.getBitset(s.createBitset())}destroy(){this._tree.destroy()}get featureSpatialReference(){return this._spatialReference}get fields(){return this._fields}async updateSchema(e,t){const s=this._schema;try{await super.updateSchema(e,t),await this._projectionSupportCheck}catch{}this._fields=[...this._schema.params.fields,{name:"referenceId",alias:"referenceId",type:"esriFieldTypeInteger"}],this._fields.some(i=>i.name==="cluster_count")||this._fields.push({name:"cluster_count",alias:"cluster_count",type:"esriFieldTypeInteger"}),this._fieldsIndex=new te(this._fields);const r=le(s,t);t&&(r!=null||e.source||e.storage.filters)?((ce(r,"params.fields")||!this._tree||e.source)&&(this._tree&&this._tree.destroy(),this._tree=new xt(this._statisticFields,this._serviceInfo),this._rebuildTree(),k("esri-2d-update-debug")&&console.debug("Aggregate mesh needs update due to tree changing")),k("esri-2d-update-debug")&&console.debug("Applying Update - ClusterStore:",r),e.targets[t.name]=!0,e.mesh=!1,this._aggregateValueRanges={}):s&&(e.mesh=!0)}clear(){this._rebuildTree()}sweepFeatures(e,t){this._bitsets.inserted.forEachSet(s=>{if(!e.has(s)){const r=t.lookupByDisplayIdUnsafe(s);this._remove(r)}})}sweepAggregates(e,t,s){this._clusters.forEach((r,i)=>{r&&r.tileLevel!==s&&(e.releaseDisplayId(r.displayId),t.unsetAttributeData(r.displayId),this._clusters.delete(i))})}onTileData(e,t,s,r,i,n=!0){if(!this._schema||t.addOrUpdate==null)return t;this.events.emit("changed");const o=this._getTransforms(e,this._spatialReference);{const l=t.addOrUpdate.getCursor();for(;l.next();)this._update(l,r)}if(t.status.mesh||!n)return t;const u=new Array,h=this._schema.params.clusterRadius;this._getClustersForTile(u,e,h,s,o),t.addOrUpdate=G.fromOptimizedFeatures(u,{fields:this.fields,fieldsIndex:this._fieldsIndex,geometryType:"esriGeometryPoint",objectIdField:this.objectIdField}),t.addOrUpdate.attachStorage(s),t.clear=!0,t.end=!0;{const l=t.addOrUpdate.getCursor();for(;l.next();){const d=l.getDisplayId();this._bitsets.computed.unset(d),this.setComputedAttributes(s,l,d,e.scale,i)}}return this._aggregateValueRangesChanged&&t.end&&(this.events.emit("valueRangesChanged",{valueRanges:this._aggregateValueRanges}),this._aggregateValueRangesChanged=!1),t}onTileUpdate({added:e,removed:t}){if(e.length){const r=e[0].level;this._tileLevel=r,this._setGeohashLevel(r)}if(!this._schema)return;const s=this._schema.params.clusterRadius;t.forEach(r=>{this._tiles.delete(r.key.id),this._markTileClustersForDeletion(r,s)})}getAggregate(e){for(const t of this._clusters.values())if(((t==null?void 0:t.displayId)&Ve)==(e&Ve))return t.toJSON();return null}getAggregates(){const e=[];for(const t of this._clusters.values())(t==null?void 0:t.tileLevel)===this._tileLevel&&e.push(t.toJSON());return e}getDisplayId(e){const t=this._clusters.get(e);return t?t.displayId:null}getFeatureDisplayIdsForAggregate(e){const t=this._clusters.get(e);return t?this._tree.getRegionDisplayIds(t.geohashBoundsInfo):[]}getDisplayIdForReferenceId(e){for(const t of this._clusters.values())if((t==null?void 0:t.referenceId)===e)return t.displayId;return null}getAggregateValueRanges(){return this._aggregateValueRanges}forEach(e){this._clusters.forEach(t=>{if(!t)return;const s=t.toJSON(),r=G.fromFeatures([s],{objectIdField:this.objectIdField,globalIdField:null,geometryType:this.geometryInfo.geometryType,fields:this.fields,fieldsIndex:this._fieldsIndex}).getCursor();r.next(),e(r)})}forEachInBounds(e,t){}forEachBounds(e,t){const{hasM:s,hasZ:r}=this.geometryInfo;for(const i of e){const n=_t(js,i.readGeometry(),r,s);n!=null&&t(n)}}size(){let e=0;return this.forEach(t=>e++),e}_rebuildTree(){this._bitsets.computed.clear(),this._bitsets.inserted.clear(),this._tree&&this._tree.clear()}_remove(e){const t=e.getDisplayId(),s=e.getXHydrated(),r=e.getYHydrated(),i=this._geohashBuf[2*t],n=this._geohashBuf[2*t+1];this._bitsets.inserted.has(t)&&(this._bitsets.inserted.unset(t),this._tree.removeCursor(e,s,r,i,n,this._geohashLevel))}_update(e,t){const s=e.getDisplayId(),r=this._bitsets.inserted,i=t.isVisible(s);if(i===r.has(s))return;if(!i)return void this._remove(e);const n=e.getXHydrated(),o=e.getYHydrated();if(!this._setGeohash(s,n,o))return;const u=this._geohashBuf[2*s],h=this._geohashBuf[2*s+1];this._tree.insertCursor(e,s,n,o,u,h,this._geohashLevel),r.set(s)}_setGeohash(e,t,s){if(this._bitsets.geohash.has(e))return!0;const r=this._geohashBuf;if(this._spatialReference.isWebMercator){const i=re(t/W.radius),n=i-360*Math.floor((i+180)/360),o=re(Math.PI/2-2*Math.atan(Math.exp(-s/W.radius)));fe(r,e,o,n,Te)}else{const i=ae({x:t,y:s},this._spatialReference,K.WGS84);if(!i)return!1;fe(r,e,i.y,i.x,Te)}return this._bitsets.geohash.set(e),!0}_getClustersForTile(e,t,s,r,i,n=!0){const o=this._schema.params.clusterPixelBuffer,u=2*s,h=Math.ceil(2**t.key.level*D/u)+1,l=Math.ceil(o/u)+0,d=Math.ceil(D/u),{row:c,col:g}=t.key,_=g*D,p=c*D,f=Math.floor(_/u)-l,v=Math.floor(p/u)-l,m=f+d+2*l,x=v+d+2*l,y=t.tileInfoView.getLODInfoAt(t.key.level);for(let I=f;I<=m;I++)for(let b=v;b<=x;b++){let S=I;y.wrap&&(S=I<0?I+h:I%h);const M=y.wrap&&I<0,F=y.wrap&&I%h!==I,w=this._lookupCluster(r,y,t.key.level,S,b,t);if(w!=null){let C=null;if(i&&(C=M?i.left:F?i.right:i.tile),n&&C==null||!w.count)continue;if(C!=null&&n){const T=w.geometry.clone();let q=w.attributes;T.coords[0]=pt(C,T.coords[0]),T.coords[1]=ft(C,T.coords[1]),w.count===1&&w.referenceId!=null&&(q={...w.attributes,referenceId:w.referenceId});const R=new Oe(T,q);R.displayId=w.displayId,e.push(R)}}}}_getGeohashLevel(e){return Math.min(Math.ceil(e/2+2),Te)}_setGeohashLevel(e){const t=this._getGeohashLevel(e),s=(Math.floor(t/st)+1)*st-1;if(this._geohashLevel!==s)return this._geohashLevel=s,this._rebuildTree(),void this._bitsets.geohash.clear()}_getTransforms(e,t){const s={originPosition:"upperLeft",scale:[e.resolution,e.resolution],translate:[e.bounds[0],e.bounds[3]]},r=ct(t);if(!r)return{tile:s,left:null,right:null};const[i,n]=r.valid;return{tile:s,left:{...s,translate:[n,e.bounds[3]]},right:{...s,translate:[i-n+e.bounds[0],e.bounds[3]]}}}_getClusterId(e,t,s){return(15&e)<<28|(16383&t)<<14|16383&s}_markForDeletion(e,t,s){const r=this._getClusterId(e,t,s);this._clusters.delete(r)}_getClusterBounds(e,t,s){const r=this._schema.params.clusterRadius,i=2*r;let n=s%2?t*i:t*i-r;const o=s*i;let u=n+i;const h=o-i,l=2**e.level*D;e.wrap&&n<0&&(n=0),e.wrap&&u>l&&(u=l);const d=n/D,c=o/D,g=u/D,_=h/D;return[e.getXForColumn(d),e.getYForRow(c),e.getXForColumn(g),e.getYForRow(_)]}_getGeohash(e,t,s){const r={geohashX:0,geohashY:0};return ue(r,t,e,s),r}_getGeohashBounds(e,t){const s=this._getGeohashLevel(e.key.level);if(this._spatialReference.isWebMercator){const[p,f,v,m]=t,x={x:p,y:f},y={x:v,y:m};let I=0,b=0,S=0,M=0;{const C=re(x.x/W.radius);I=C-360*Math.floor((C+180)/360),b=re(Math.PI/2-2*Math.atan(Math.exp(-x.y/W.radius)))}{const C=re(y.x/W.radius);S=C-360*Math.floor((C+180)/360),M=re(Math.PI/2-2*Math.atan(Math.exp(-y.y/W.radius)))}const F={geohashX:0,geohashY:0},w={geohashX:0,geohashY:0};return ue(F,b,I,s),ue(w,M,S,s),{bounds:[p,f,v,m],geohashBounds:{xLL:F.geohashX,yLL:F.geohashY,xTR:w.geohashX,yTR:w.geohashY},level:s}}const r=dt.fromExtent(lt.fromBounds(t,this._spatialReference)),i=ae(r,this._spatialReference,K.WGS84,{densificationStep:e.resolution*Ds});if(!i)return null;const n=Ue(new Q,i,!1,!1),o=n.coords.filter((p,f)=>!(f%2)),u=n.coords.filter((p,f)=>f%2),h=Math.min(...o),l=Math.min(...u),d=Math.max(...o),c=Math.max(...u),g=this._getGeohash(h,l,s),_=this._getGeohash(d,c,s);return{bounds:t,geohashBounds:{xLL:g.geohashX,yLL:g.geohashY,xTR:_.geohashX,yTR:_.geohashY},level:s}}_lookupCluster(e,t,s,r,i,n){const o=this._getClusterId(s,r,i),u=this._clusters.get(o),h=this._getClusterBounds(t,r,i),l=this._getGeohashBounds(n,h);if(l==null)return null;const d=this._tree.getRegionStatistics(l),{count:c,xTotal:g,yTotal:_,referenceId:p}=d,f=c?g/c:0,v=c?_/c:0;if(c===0)return this._clusters.set(o,null),null;const m={cluster_count:c,...d.attributes},x=u!=null?u.update(f,v,s,m,l,p):Pe.create(e,o,f,v,s,m,l,p);if(c===0){const[y,I,b,S]=h;x.geometry.coords[0]=(y+b)/2,x.geometry.coords[1]=(I+S)/2}return this._clusters.set(o,x),this._updateAggregateValueRangeForCluster(x,x.tileLevel),x}_updateAggregateValueRangeForCluster(e,t){const s=this._aggregateValueRanges[t]||{minValue:1/0,maxValue:0},r=s.minValue,i=s.maxValue;s.minValue=Math.min(r,e.count),s.maxValue=Math.max(i,e.count),this._aggregateValueRanges[t]=s,r===s.minValue&&i===s.maxValue||(this._aggregateValueRangesChanged=!0)}_markTileClustersForDeletion(e,t){const s=2*t,r=Math.ceil(D/s),{row:i,col:n}=e.key,o=n*D,u=i*D,h=Math.floor(o/s),l=Math.floor(u/s);for(let d=h;d<h+r;d++)for(let c=l;c<l+r;c++)this._markForDeletion(e.key.level,d,c)}}const Ns=5e3,Vs="tileRenderer.featuresView.attributeView.initialize",Hs="tileRenderer.featuresView.attributeView.requestUpdate",Ys="tileRenderer.featuresView.requestRender";function Xs(a){return a.name==="worker:port-closed"}function J(a){if(!ye(a)&&!Xs(a))throw a}function rt(a){return a.type==="feature"&&a.mode==="snapshot"}let j=class extends Ee{constructor(){super(...arguments),this._storage=new Yt,this._markedIdsBufId=this._storage.createBitset(),this._lastCleanup=performance.now(),this._cleanupNeeded=!1,this._invalidated=!1,this._tileToResolver=new Map,this._didEdit=!1,this._updateVersion=1,this._updatingHandles=new nt,this.tileStore=null,this.config=null,this.processor=null,this.remoteClient=null,this.service=null}initialize(){this._initStores(),this._initSource(),this._updateQueue=new ke({concurrency:this._source.type==="stream"?1:4,process:(a,e)=>this._onTileMessage(a,{signal:e})}),this.addHandles([this.tileStore.on("update",this.onTileUpdate.bind(this)),Ut(()=>!this.updating,()=>this.onIdle())])}_initSource(){const a=this.tileStore.tileScheme,e=()=>this._updateQueue&&this._updateQueue.length<50,t=(s,r)=>(this._invalidated=!0,this._patchTile(s,r));this._source=Os(this.service,{...this.service,fieldsIndex:this.fieldsIndex},this.spatialReference,a,t,e,this.featureStore),this._proxyEvents()}_setStreamClientProperty(a,e){this.remoteClient.invoke("setProperty",{propertyName:a,value:e}).catch(J)}_proxyEvents(){if(this._source.type==="stream"){const a=this._source.events,e=this._source;this.addHandles([ge(()=>e.connectionStatus,t=>this._setStreamClientProperty("pipelineConnectionStatus",t),{initial:!0}),ge(()=>e.errorString,t=>this._setStreamClientProperty("pipelineErrorString",t),{initial:!0}),a.on("data-received",t=>this.remoteClient.invoke("emitEvent",{name:"data-received",event:{attributes:t.attributes,centroid:t.centroid,geometry:t.geometry}}).catch(J)),a.on("message-received",t=>this.remoteClient.invoke("emitEvent",{name:"message-received",event:t}).catch(J)),a.on("updateRate",t=>this.remoteClient.invoke("emitEvent",{name:"update-rate",event:{...t}}).catch(J))])}}_initAttributeStore(a){this.attributeStore||(this.attributeStore=new Xt({type:"remote",initialize:(e,t)=>he(this.remoteClient.invoke(Vs,e,{signal:t}).catch(J)),update:(e,t)=>he(this.remoteClient.invoke(Hs,e,{signal:t}).catch(J)),render:e=>he(this.remoteClient.invoke(Ys,void 0,{signal:e}).catch(J))},a))}_initStores(){const a=this.service.type==="snapshot"?"snapshot":"on-demand",e={geometryInfo:{geometryType:this.service.geometryType,hasM:!1,hasZ:!1},spatialReference:this.spatialReference,fieldsIndex:this.fieldsIndex};this.featureStore=new Vt(e,this._storage,a)}_initQueryEngine(a){var t;const e=this;(t=this.featureQueryEngine)==null||t.destroy(),this.featureQueryEngine=new De({availableFields:a.availableFields,definitionExpression:a.schema.source.definitionExpression??void 0,fieldsIndex:te.fromJSON(this.service.fieldsIndex),geometryType:this.service.geometryType,objectIdField:this.service.objectIdField,hasM:!1,hasZ:!1,spatialReference:this.spatialReference.toJSON(),cacheSpatialQueries:!0,featureStore:this.featureStore,aggregateAdapter:{getFeatureObjectIds(s){return e.aggregateStore==null?[]:e.aggregateStore.getFeatureDisplayIdsForAggregate(s).map(r=>e.getObjectId(r))}},timeInfo:this.service.timeInfo})}_initAggregateQueryEngine(a,e){var s;if((s=this.aggregateQueryEngine)==null||s.destroy(),a==null)return;const t=e.targets.aggregate.params.fields.slice();this.aggregateQueryEngine=new De({definitionExpression:void 0,fieldsIndex:te.fromLayerJSON({fields:t,dateFieldsTimeReference:{timeZoneIANA:Ot}}),geometryType:a.geometryInfo.geometryType,objectIdField:a.objectIdField,hasM:a.geometryInfo.hasM,hasZ:a.geometryInfo.hasZ,spatialReference:this.spatialReference.toJSON(),cacheSpatialQueries:!1,featureStore:a,aggregateAdapter:{getFeatureObjectIds:r=>[]}})}destroy(){var a,e,t;this._updateQueue.destroy(),this._source.destroy(),(a=this.featureQueryEngine)==null||a.destroy(),(e=this.aggregateQueryEngine)==null||e.destroy(),(t=this.attributeStore)==null||t.destroy();for(const s of this.tileStore.tiles)this._source.unsubscribe(s);clearInterval(this._checkUpdating),this._updatingHandles.destroy()}get fieldsIndex(){return te.fromJSON(this.service.fieldsIndex)}get spatialReference(){return this.tileStore.tileScheme.spatialReference}get dataUpdating(){return this._source.updatingHandles.updating}get updating(){return this.isUpdating()}isUpdating(){const a=this._source.updatingHandles.updating,e=!this.attributeStore||this.attributeStore.updatingHandles.updating,t=a||e||this._updatingHandles.updating;if(k("esri-2d-log-updating")){let s=`Updating FeatureController2D: ${t}
`;s+=` -> updatingSource ${a}
`;for(const r of this._source.subscriptions)s+=` ${r.tile.id} ${r.isDone}
`;s+=` -> updatingAttributeStore ${e}
`,s+=` -> updatingHandles ${this._updatingHandles.updating} (queue: ${this._updateQueue.length})
`,console.log(s)}return t}updateCustomParameters(a){this._source.type==="stream"&&this._source.updateCustomParameters(a)}enableEvent(a){this._source.enableEvent(a.name,a.value)}pause(){this._updateQueue.pause(),this._updateQueue.clear()}resume(){this._updateQueue.resume()}pauseStream(){this._source.type==="stream"&&this._source.pauseStream()}resumeStream(){this._source.type==="stream"&&this._source.resumeStream()}sendMessageToSocket(a){this._source.type==="stream"&&this._source.sendMessageToSocket(a)}sendMessageToClient(a){this._source.type==="stream"&&this._source.sendMessageToClient(a)}_initAggregateStore(a){var t,s,r,i,n;const e=((s=(t=a.schema.targets)==null?void 0:t.aggregate)==null?void 0:s.type)??null;if((((n=(i=(r=this.config)==null?void 0:r.schema.targets)==null?void 0:i.aggregate)==null?void 0:n.type)??null)!==e&&(this.aggregateStore!=null&&(this.removeHandles("valueRangesChanged"),this.aggregateStore.destroy(),this.aggregateStore=null),e)){switch(e){case"cluster":{const o={geometryInfo:{geometryType:"esriGeometryPoint",hasM:!1,hasZ:!1},spatialReference:this.spatialReference,fieldsIndex:this.fieldsIndex,fields:this.service.fields};this.aggregateStore=new zs(o,this.spatialReference,this._storage,{...this.service,fieldsIndex:this.fieldsIndex}),this.addHandles(this.aggregateStore.events.on("valueRangesChanged",u=>{this.remoteClient.invoke("emitEvent",{name:"valueRangesChanged",event:{valueRanges:u.valueRanges}}).catch(J)}),"valueRangesChanged");break}case"bin":{const o={geometryInfo:{geometryType:"esriGeometryPolygon",hasM:!1,hasZ:!1},spatialReference:this.spatialReference,fieldsIndex:this.fieldsIndex,fields:this.service.fields};this.aggregateStore=new Bs(o,this.spatialReference,this._storage,{...this.service,fieldsIndex:this.fieldsIndex});break}}this.aggregateStore.onTileUpdate({added:this.tileStore.tiles,removed:[]})}}async update(a,e){var t;this._updateVersion++,k("esri-2d-update-debug")&&console.debug(`FeatureController2D::update: Token version ${this._updateVersion}`),this._initQueryEngine(e),this._initAttributeStore(e),this.pause(),((t=this.config)==null?void 0:t.timeZone)!==e.timeZone&&(a.mesh=!0,a.storage.data=!0,a.storage.filters=!0,a.targets.aggregate=!0,a.targets.feature=!0,this.featureStore.invalidate()),await Promise.all([this._source.update(a,e.schema.source),this.featureStore.updateSchema(a,e.schema.targets.feature),this.attributeStore.update(a,e),this.attributeStore.updateFilters(a,e,this)]),this._initAggregateStore(e),this.aggregateStore!=null&&await this.aggregateStore.updateSchema(a,e.schema.targets.aggregate),this._initAggregateQueryEngine(this.aggregateStore,e.schema),k("esri-2d-update-debug")&&a.describe(),this._set("config",e)}async applyUpdate(a){a.version=this._updateVersion,k("esri-2d-update-debug")&&console.debug(`FeatureController2D::applyUpdate: Token version ${a.version}`),a.mesh&&this.clearTiles(),this._updateQueue.resume(),await this._source.applyUpdate(a),k("esri-2d-update-debug")&&console.debug("FeatureController2D::applyUpdate Waiting for source update to finish"),this.notifyChange("updating"),await oe(()=>!this.updating),k("esri-2d-update-debug")&&console.debug("FeatureController2D::applyUpdate Source update finsihed"),this.aggregateStore!=null&&(await ht(10),k("esri-2d-update-debug")&&console.debug("FeatureController2D::applyUpdate Waiting for aggregate idle call"),await oe(()=>!this.updating),k("esri-2d-update-debug")&&console.debug("FeatureController2D::applyUpdate Aggregate idle called")),k("esri-2d-update-debug")&&console.debug("FeatureController2D::applyUpdate Update finished")}async onEdits({edits:a}){k("esri-2d-update-debug")&&console.debug("Applying Edit:",a),this._didEdit=!0;try{const e=a.removed.map(s=>s.objectId&&s.objectId!==-1?s.objectId:this._lookupObjectIdByGlobalId(s.globalId)),t=a.addOrModified.map(({objectId:s})=>s);this.featureStore.invalidate(),await this._source.edit(t,e),this.clearTiles(),this.notifyChange("updating"),this.aggregateStore!=null&&this.aggregateStore.clear(),await this._source.resend(),await oe(()=>!this.updating)}catch{}}async refresh(a){if(!a.dataChanged){const e=E.empty();return e.storage.filters=!0,this.applyUpdate(e)}this.featureStore.invalidate(),this.clearTiles(),this._source.refresh(this._updateVersion,a),this._cleanupNeeded=!0,this.notifyChange("updating"),await oe(()=>!this.updating)}clearTiles(){for(const a of this.tileStore.tiles)this.processor.onTileClear(a,!1)}onTileUpdate(a){this.aggregateStore!=null&&this.aggregateStore.onTileUpdate(a);for(const e of a.added){const t=this._source.subscribe(e,this._updateVersion);this._source.type!=="stream"&&this._updatingHandles.addPromise(t.done),this._level=e.level}for(const e of a.removed)this._source.unsubscribe(e),this._cleanupNeeded=!0,this._tileToResolver.has(e.id)&&(this._tileToResolver.get(e.id).resolve(),this._tileToResolver.delete(e.id));this.notifyChange("updating")}async onIdle(){this._invalidated&&(this._invalidated=!1,this.aggregateStore==null&&this.processor.type!=="heatmap"||await this._repushCurrentLevelTiles()),this._markAndSweep()}async querySummaryStatistics({query:a,params:e}){return this.featureQueryEngine.executeQueryForSummaryStatistics(a,e)}async queryAggregateSummaryStatistics({query:a,params:e}){return this.aggregateQueryEngine.executeQueryForSummaryStatistics(this._normalizeAggregateQuery(a),e)}async queryUniqueValues({query:a,params:e}){return this.featureQueryEngine.executeQueryForUniqueValues(a,e)}async queryAggregateUniqueValues({query:a,params:e}){return this.aggregateQueryEngine.executeQueryForUniqueValues(this._normalizeAggregateQuery(a),e)}async queryClassBreaks({query:a,params:e}){return this.featureQueryEngine.executeQueryForClassBreaks(a,e)}async queryAggregateClassBreaks({query:a,params:e}){return this.aggregateQueryEngine.executeQueryForClassBreaks(this._normalizeAggregateQuery(a),e)}async queryHistogram({query:a,params:e}){return this.featureQueryEngine.executeQueryForHistogram(a,e)}async queryAggregateHistogram({query:a,params:e}){return this.aggregateQueryEngine.executeQueryForHistogram(this._normalizeAggregateQuery(a),e)}queryExtent(a){return this.featureQueryEngine.executeQueryForExtent(a)}queryAggregates(a){return this.aggregateQueryEngine.executeQuery(this._normalizeAggregateQuery(a))}queryAggregateCount(a){return this.aggregateQueryEngine.executeQueryForCount(this._normalizeAggregateQuery(a))}queryAggregateIds(a){return this.aggregateQueryEngine.executeQueryForIds(this._normalizeAggregateQuery(a))}queryFeatures(a){return this.featureQueryEngine.executeQuery(a)}async queryVisibleFeatures(a){const e=await this.featureQueryEngine.executeQuery(a),t=e.objectIdFieldName;return e.features=e.features.filter(s=>{const r=s.attributes[t],i=this.getDisplayId(r);return i!=null&&this.attributeStore.isVisible(i)}),e}queryFeatureCount(a){return this.featureQueryEngine.executeQueryForCount(a)}queryLatestObservations(a){return this.featureQueryEngine.executeQueryForLatestObservations(a)}queryObjectIds(a){return this.featureQueryEngine.executeQueryForIds(a)}async queryStatistics(){return this.featureStore.storeStatistics}getObjectId(a){return this.featureStore.lookupObjectId(a,this._storage)}getDisplayId(a){if(this.aggregateStore!=null){const e=this.aggregateStore.getDisplayId(a);if(e==null){const t=this.featureStore.lookupDisplayId(a);return this.aggregateStore.getDisplayIdForReferenceId(t)}return e}return this.featureStore.lookupDisplayId(a)}getFeatures(a){const e=[],t=[];for(const s of a){const r=this.aggregateStore!=null?this.getAggregate(s):null;if(r!=null)if(r.attributes.referenceId!=null){const i=this.getFeature(r.attributes.referenceId);i!=null&&e.push(i)}else t.push(r);else{const i=this.getFeature(s);i!=null&&e.push(i)}}return{features:e,aggregates:t}}getFeature(a){const e=this.featureStore.lookupFeatureByDisplayId(a,this._storage);if(e==null)return null;const t=e.readHydratedGeometry(),s=$e(t,e.geometryType,e.hasZ,e.hasM);return{attributes:e.readAttributes(),geometry:s}}getAggregate(a){return this.aggregateStore==null?null:this.aggregateStore.getAggregate(a)}getAggregates(){return this.aggregateStore==null?[]:this.aggregateStore.getAggregates()}async setHighlight(a){const e=a.map(t=>this.getDisplayId(t)).filter(at);return this.attributeStore.setHighlight(a,e)}_normalizeAggregateQuery(a){const e=a.objectIds??[];for(const t of a.aggregateIds??[])e.push(t);return a.objectIds=e,a.aggregateIds=[],a}_lookupObjectIdByGlobalId(a){const e=this.service.globalIdField;if(e==null)throw new Error("Expected globalIdField to be defined");let t=null;if(this.featureStore.forEach(s=>{a===s.readAttribute(e)&&(t=s.getObjectId())}),t==null)throw new Error(`Expected to find a feature with globalId ${a}`);return t}async _repushCurrentLevelTiles(){const a=this.tileStore.tiles.filter(t=>t.level===this._level);a.map(async t=>this._patchTile({type:"append",id:t.key.id,clear:!0,addOrUpdate:null,end:!1}));const e=a.map(async t=>this._patchTile({type:"append",id:t.key.id,addOrUpdate:G.fromOptimizedFeatures([],{...this.service,fieldsIndex:this.fieldsIndex}),remove:[],end:!0,isRepush:!0,status:E.empty()}));await Promise.all(e)}_maybeForceCleanup(){performance.now()-this._lastCleanup>Ns&&this._markAndSweep()}_patchTile(a,e){const t=this._updateQueue.push(a,e).catch(s=>{});return this._updatingHandles.addPromise(t)}async _onTileMessage(a,e){var i,n,o;if(B(e),k("esri-2d-update-debug")){const u=(i=a.addOrUpdate)==null?void 0:i.hasFeatures;console.debug(a.id,`FeatureController:onTileMessage: [clear:${a.clear}, end:${a.end}, features: ${u}]`)}const t=this.tileStore.get(a.id);if(!t)return;if(a.clear)return this.processor.onTileClear(t,a.end);const s=a.status;this._cleanupNeeded=!0;const r=[];for(const u of a.remove??[]){const h=this.featureStore.lookupDisplayId(u);h&&r.push(h)}a.remove=r;try{if(a.addOrUpdate==null)return void this.processor.onTileMessage(t,{...a,addOrUpdate:null},this.aggregateStore!=null,e).catch(de);if(a.addOrUpdate.setArcadeSpatialReference(this.spatialReference),this.featureStore.hasInstance(a.addOrUpdate.instance)&&s.targets.feature||(s.targets.feature=!0,this.featureStore.onTileData(t,a,(n=this.config)==null?void 0:n.timeZone)),(!s.storage.data||!s.storage.filters)&&(s.storage.data=!0,s.storage.filters=!0,this.attributeStore.onTileData(t,a),this._source.type==="stream"||this._didEdit?(await this.attributeStore.sendUpdates(),B(e)):this.attributeStore.sendUpdates()),this.aggregateStore!=null&&!s.targets.aggregate){s.targets.aggregate=!0;const u=rt(this._source)&&this._source.loading,h=!rt(this._source)||u||a.end;if(this.aggregateStore.onTileData(t,a,this._storage,this.attributeStore,(o=this.config)==null?void 0:o.timeZone,h),!h)return;s.mesh||(this.attributeStore.onTileData(t,a),await this.attributeStore.sendUpdates())}if(!s.mesh){s.mesh=!0;const u=this.aggregateStore!=null&&this.aggregateStore.type==="cluster";await this.processor.onTileMessage(t,a,u,e),B(e)}this._maybeForceCleanup()}catch(u){de(u)}}_mark(a,e,t){const s=(4294901760&this._storage.getInstanceId(a))>>>16;a&&(e.add(s),t.set(a))}_markAndSweep(){if(this._lastCleanup=performance.now(),!(!(this._source.type==="feature"&&this._source.mode==="snapshot")&&(this._source.type==="stream"||this._cleanupNeeded)))return;this._cleanupNeeded=!1;const a=this._storage.getBitset(this._markedIdsBufId),e=new Set;a.clear();for(const t of this.tileStore.tiles)for(const s of this._source.readers(t.id)){const r=s.getCursor();for(;r.next();){let i=r.getDisplayId();if(!i){const n=r.getObjectId();i=this.featureStore.lookupDisplayId(n)}this._mark(i,e,a)}}this.processor.type==="symbol"&&this.processor.forEachBufferId(t=>{this._mark(t,e,a)}),this._updateQueue.forEach(t=>{for(const s of t.remove??[]){const r=this.featureStore.lookupDisplayId(s);this._mark(r,e,a)}}),this.aggregateStore!=null&&(this.aggregateStore.sweepFeatures(a,this.featureStore),"sweepAggregates"in this.aggregateStore&&this.aggregateStore.sweepAggregates(this._storage,this.attributeStore,this._level)),this.featureStore.sweepFeatures(a,this._storage,this.attributeStore),this.featureStore.sweepFeatureSets(e)}};A([O({constructOnly:!0})],j.prototype,"tileStore",void 0),A([O()],j.prototype,"config",void 0),A([O({readOnly:!0})],j.prototype,"fieldsIndex",null),A([O()],j.prototype,"processor",void 0),A([O({constructOnly:!0})],j.prototype,"remoteClient",void 0),A([O({constructOnly:!0})],j.prototype,"service",void 0),A([O()],j.prototype,"spatialReference",null),A([O()],j.prototype,"dataUpdating",null),A([O()],j.prototype,"updating",null),j=A([me("esri.views.2d.layers.features.controllers.FeatureController2D")],j);const Zs=j;let ee=class extends Ee{constructor(){super(...arguments),this.controller=null,this.processor=null,this.remoteClient=null,this.tileStore=null,this.service=null,this.viewState=null,this._paused=!1,this._pendingTileUpdates=[]}initialize(){this.addHandles([ge(()=>this.updating,a=>{this.remoteClient.invoke("setUpdating",a).catch(e=>{})})])}destroy(){var a,e;this.stop(),(a=this.controller)==null||a.destroy(),(e=this.processor)==null||e.destroy(),this.controller=this.processor=this.tileStore=this.remoteClient=null}get updating(){return!this.controller||this.controller.updating}stop(){var a,e,t;this._paused=!0,Array.isArray((a=this.service)==null?void 0:a.source)&&(this.service.source.forEach(s=>s.close()),this.service.source.length=0),(e=this.tileStore)==null||e.updateTiles({added:[],removed:this.tileStore.tiles.map(s=>s.id)}),(t=this.tileStore)==null||t.destroy(),this.tileStore=null,this._pendingTileUpdates.length=0}async startup({service:a,config:e,tileInfo:t,tiles:s}){var r,i,n;if(this._paused=!0,Array.isArray((r=this.service)==null?void 0:r.source)&&(this.service.source.forEach(o=>o.close()),this.service.source.length=0),this.service=a,!this.tileStore||!Lt(this.tileStore.tileScheme.spatialReference,t.spatialReference)){const o=new Pt(Qt.fromJSON(t));s.added.length=s.removed.length=0,(i=this.tileStore)==null||i.updateTiles({added:[],removed:this.tileStore.tiles.map(u=>u.id)}),(n=this.tileStore)==null||n.destroy(),this.tileStore=new Gt(o),this._pendingTileUpdates.length=0}for(await this._createProcessorAndController(e),await this.update({config:e}),this.controller.resume(),this.tileStore.clear(),this.tileStore.updateTiles(s),this._paused=!1;this._pendingTileUpdates.length;)this.tileStore.updateTiles(this._pendingTileUpdates.pop())}async updateTiles(a){var e;this._paused?this._pendingTileUpdates.push(a):(e=this.tileStore)==null||e.updateTiles(a)}async update({config:a}){const e=E.empty();return await Promise.all([this.processor.update(e,a),this.controller.update(e,a)]),e.toJSON()}async applyUpdate(a){return this.controller.applyUpdate(E.create(a))}async _createProcessorAndController(a){await Promise.all([this._handleControllerConfig(a),this._handleProcessorConfig(a)]),this.controller.processor=this.processor}async _handleControllerConfig(a){return this._createController(this.service,a)}async _handleProcessorConfig(a){return this._createProcessor(this.service,a)}async _createController(a,e){this.controller&&(this.controller.destroy(),this.removeHandles("controller"));const{tileStore:t,remoteClient:s}=this,r=new Zs({service:a,tileStore:t,remoteClient:s}),i=ge(()=>r.dataUpdating,n=>{this.remoteClient.invoke("setDataUpdating",n).catch(o=>{})});return this.addHandles(i,"controller"),this.controller=r,r}async _createProcessor(a,e){const t=e.schema.processors[0].type,s=(await rs(t)).default,{remoteClient:r,tileStore:i}=this,n=new s({service:a,config:e,tileStore:i,remoteClient:r});return this.processor&&this.processor.destroy(),this.processor=n,n}};A([O()],ee.prototype,"controller",void 0),A([O()],ee.prototype,"processor",void 0),A([O()],ee.prototype,"updating",null),A([O()],ee.prototype,"viewState",void 0),ee=A([me("esri.views.2d.layers.features.Pipeline")],ee);const zr=ee;export{zr as default};