@arcgis/core 4.27.0-rc.1 → 4.27.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +2 -2
  2. package/assets/esri/core/workers/RemoteClient.js +1 -1
  3. package/assets/esri/core/workers/chunks/{92e7f224a80195e606d6.js → 1f69fb9687de9ebfcf90.js} +1 -1
  4. package/assets/esri/core/workers/chunks/{0a02ac5628d1739372c6.js → 2b55295590b4a0503749.js} +1 -1
  5. package/assets/esri/core/workers/chunks/471f6eba213412b82840.js +1 -0
  6. package/assets/esri/core/workers/chunks/{f339db2b599fa9585283.js → 5e6471dd2a08e66b47d0.js} +79 -81
  7. package/assets/esri/core/workers/chunks/{474d9b334812533bab36.js → 6cd248d065f6d1616294.js} +1 -1
  8. package/assets/esri/core/workers/chunks/{d8bd3f498b3fa8153404.js → 6f510f28526c73ab453c.js} +1 -1
  9. package/assets/esri/core/workers/chunks/83e3d104886b48f00397.js +1 -0
  10. package/assets/esri/core/workers/chunks/{3c5a64a545272f148e93.js → 9621b7d8d951aa881686.js} +1 -1
  11. package/assets/esri/core/workers/chunks/{b6e173eddaad4244cb5f.js → b31974524932e638df8c.js} +1 -1
  12. package/assets/esri/core/workers/chunks/da57eba2fe25495ea217.js +1 -0
  13. package/assets/esri/core/workers/chunks/dabd889e064c4e7807fa.js +1 -0
  14. package/assets/esri/core/workers/chunks/f35895e03c036d67b3ed.js +1 -0
  15. package/assets/esri/core/workers/chunks/{c6efe2e04ea6a55bb6e3.js → f6e68befe2812b90b40d.js} +1 -1
  16. package/assets/esri/themes/base/widgets/_Feature.scss +4 -0
  17. package/assets/esri/themes/base/widgets/_FeatureContent.scss +9 -2
  18. package/assets/esri/themes/base/widgets/_ScaleRangeSlider.scss +1 -0
  19. package/assets/esri/themes/dark/main.css +1 -1
  20. package/assets/esri/themes/light/main.css +1 -1
  21. package/assets/esri/themes/light/view.css +1 -1
  22. package/chunks/DefaultMaterial.glsl.js +3 -2
  23. package/chunks/ShadowCastAccumulate.glsl.js +1 -1
  24. package/core/timeUtils.js +1 -1
  25. package/geometry/Mesh.js +1 -1
  26. package/geometry/support/meshVertexSpaceUtils.js +5 -0
  27. package/interfaces.d.ts +179 -31
  28. package/kernel.js +1 -1
  29. package/layers/VideoLayer.js +1 -1
  30. package/layers/graphics/controllers/StreamController.js +1 -1
  31. package/layers/graphics/data/QueryEngine.js +1 -1
  32. package/layers/graphics/data/attributeSupport.js +1 -1
  33. package/layers/graphics/editingSupport.js +1 -1
  34. package/layers/graphics/sources/FeatureLayerSource.js +1 -1
  35. package/layers/video/VideoController.js +1 -1
  36. package/layers/video/videoUtils.js +5 -0
  37. package/package.json +1 -1
  38. package/rest/support/meshFeatureSet.js +1 -1
  39. package/smartMapping/symbology/flow.js +1 -1
  40. package/statistics/utils.js +1 -1
  41. package/support/revision.js +1 -1
  42. package/symbols/cim/CIMSymbolHelper.js +1 -1
  43. package/views/2d/layers/StreamLayerView2D.js +1 -1
  44. package/views/2d/layers/features/sources/StreamSource.js +1 -1
  45. package/views/3d/environment/ChapmanAtmosphereTechnique.js +1 -1
  46. package/views/3d/interactive/visualElements/OutlineVisualElement.js +1 -1
  47. package/views/3d/layers/BuildingComponentSublayerView3D.js +1 -1
  48. package/views/3d/layers/I3SMeshView3D.js +1 -1
  49. package/views/3d/layers/II3SMeshView3D.js +1 -1
  50. package/views/3d/layers/SceneLayerView3D.js +1 -1
  51. package/views/3d/layers/graphics/Graphics3DMeshFillSymbolLayer.js +1 -1
  52. package/views/3d/layers/graphics/Graphics3DObjectSymbolLayer.js +1 -1
  53. package/views/3d/layers/graphics/objectResourceUtils.js +1 -1
  54. package/views/3d/layers/i3s/I3SClientNodeLoader.js +1 -1
  55. package/views/3d/layers/i3s/I3SMaterialUtil.js +1 -1
  56. package/views/3d/layers/i3s/I3SOverrides.js +1 -1
  57. package/views/3d/webgl-engine/collections/Component/Material/ComponentMaterial.js +1 -1
  58. package/views/3d/webgl-engine/core/renderPasses/AllRenderPasses.js +1 -1
  59. package/views/3d/webgl-engine/core/shaderLibrary/Transform.glsl.js +3 -9
  60. package/views/3d/webgl-engine/core/shaderLibrary/default/DefaultMaterialAuxiliaryPasses.glsl.js +12 -9
  61. package/views/3d/webgl-engine/core/shaderLibrary/shading/PhysicallyBasedRenderingParameters.glsl.js +10 -10
  62. package/views/3d/webgl-engine/core/shaderLibrary/shading/ReadShadowMap.glsl.js +2 -2
  63. package/views/3d/webgl-engine/core/shaderLibrary/shading/WaterDistortion.glsl.js +2 -2
  64. package/views/3d/webgl-engine/core/shaderLibrary/terrain/TerrainTexture.glsl.js +8 -8
  65. package/views/3d/webgl-engine/core/shaderModules/Matrix4sDrawUniform.js +1 -1
  66. package/views/3d/webgl-engine/lib/ShadowHighlight.js +1 -1
  67. package/views/3d/webgl-engine/lib/ShadowMap.js +1 -1
  68. package/views/3d/webgl-engine/materials/PathTechnique.js +1 -1
  69. package/views/3d/webgl-engine/materials/WaterMaterial.js +1 -1
  70. package/views/3d/webgl-engine/materials/pbrUtils.js +1 -1
  71. package/views/3d/webgl-engine/shaders/AtmosphereCompositingTechnique.js +1 -1
  72. package/views/3d/webgl-engine/shaders/DefaultMaterialTechnique.js +1 -1
  73. package/views/3d/webgl-engine/shaders/ShadowHighlightTechnique.js +1 -1
  74. package/views/draw/DrawGraphicTool.js +1 -1
  75. package/views/layers/GroupLayerView.js +1 -1
  76. package/widgets/Daylight/DaylightViewModel.js +1 -1
  77. package/widgets/Editor/EditorViewModel.js +1 -1
  78. package/widgets/Editor/UpdateWorkflow.js +1 -1
  79. package/widgets/Editor/Workflow.js +1 -1
  80. package/widgets/Editor/workflowUtils.js +1 -1
  81. package/widgets/Editor.js +1 -1
  82. package/widgets/Feature/FeatureRelationship/FeatureRelationshipViewModel.js +1 -1
  83. package/widgets/Feature/FeatureRelationship.js +1 -1
  84. package/widgets/FeatureForm/EditableInput.d.ts +2 -2
  85. package/widgets/FeatureTable/FieldColumn.js +1 -1
  86. package/widgets/UtilityNetworkTrace/UtilityNetworkTraceViewModel.js +1 -1
  87. package/widgets/UtilityNetworkTrace/support/GeometryHandler.js +1 -1
  88. package/widgets/UtilityNetworkTrace/support/ResultAreaHandler.js +1 -1
  89. package/widgets/UtilityNetworkTrace.js +1 -1
  90. package/widgets/UtilityNetworkValidateTopology/UtilityNetworkValidateTopologyViewModel.js +1 -1
  91. package/widgets/UtilityNetworkValidateTopology.js +1 -1
  92. package/widgets/ValuePicker/ValuePickerBaseComponent.js +1 -1
  93. package/widgets/ValuePicker.js +1 -1
  94. package/assets/esri/core/workers/chunks/07651ef8348f702d59ac.js +0 -1
  95. package/assets/esri/core/workers/chunks/39714837f9d3708e3806.js +0 -1
  96. package/assets/esri/core/workers/chunks/785a6c925f29bc962992.js +0 -1
  97. package/assets/esri/core/workers/chunks/90da1ed112b82712d0ef.js +0 -1
  98. package/assets/esri/core/workers/chunks/b5fc6f2044ed047c5afd.js +0 -1
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.27/esri/copyright.txt for details.
4
4
  */
5
- import{PositionHint as e,indexOf as t}from"../../../core/arrayUtils.js";import i from"../../../core/Error.js";import{clone as s}from"../../../core/lang.js";import{removeMaybe as r,destroyMaybe as a}from"../../../core/maybe.js";import{MemCacheStorage as n,MemCache as u}from"../../../core/MemCache.js";import{throwIfAborted as o}from"../../../core/promiseUtils.js";import{getMetersPerUnitForSR as l}from"../../../core/unitUtils.js";import{set as c,NEGATIVE_INFINITY as h,create as p,expandWithAABB as m}from"../../../geometry/support/aaBoundingBox.js";import{fromValues as f,create as d}from"../../../geometry/support/aaBoundingRect.js";import{getBoundsXY as y}from"../../../geometry/support/boundsUtils.js";import{fromJSON as g,isExtent as _,isPolygon as x}from"../../../geometry/support/jsonUtils.js";import{normalizeCentralMeridian as w}from"../../../geometry/support/normalizeUtils.js";import{equals as S,isValid as F}from"../../../geometry/support/spatialReferenceUtils.js";import{convertFromGeometry as R}from"../featureConversionUtils.js";import{getWhereClause as Q,validateFields as I,validateFieldTypes as j,validateWhere as E,validateHaving as A,validNumericTypesKebabDict as b,validDateTypesKebabDict as q,hasInvalidFieldType as C}from"./attributeSupport.js";import{checkProjectionSupport as P,project as T,projectMany as B}from"./projectionSupport.js";import{queryCapabilities as k}from"./QueryEngineCapabilities.js";import{QueryEngineResult as v}from"./QueryEngineResult.js";import{getSpatialQueryOperator as z,canQueryWithRBush as O,checkSpatialQuerySupport as G}from"./spatialQuerySupport.js";import{getTimeExtent as M,getTimeOperator as U}from"./timeSupport.js";import{QUERY_ENGINE_EMPTY_RESULT as N,cleanFromGeometryEngine as Z,normalizeQuery as V,getGeometry as H}from"./utils.js";import L from"../../support/FieldsIndex.js";import{loadArcade as D}from"../../../support/arcadeOnDemand.js";import{noBudget as J}from"../../../views/support/Scheduler.js";function W(e){return null!=e&&e.every((e=>"exceedslimit"!==e.statisticType))}const $="feature-store:unsupported-query";class K{constructor(e,t=null,i,s,r){this.attributes=e,this.geometry=i,this.centroid=s,this.filterFlags=r,this.groupId=-1,this.displayId=t}}const X=new n(2e6);let Y=0;class ee{constructor(e){this._geometryQueryCache=null,this._changeHandle=null,this.capabilities={query:k},this.geometryType=e.geometryType,this.hasM=!!e.hasM,this.hasZ=!!e.hasZ,this.objectIdField=e.objectIdField,this.spatialReference=e.spatialReference,this.definitionExpression=e.definitionExpression,this.featureStore=e.featureStore,this.aggregateAdapter=e.aggregateAdapter,this._changeHandle=this.featureStore.events.on("changed",(()=>this.clearCache())),this.timeInfo=e.timeInfo,e.cacheSpatialQueries&&(this._geometryQueryCache=new u(Y+++"$$",X)),this.fieldsIndex=new L(e.fields),e.scheduler&&e.priority&&(this._frameTask=e.scheduler.registerTask(e.priority))}destroy(){this._frameTask=r(this._frameTask),this.clearCache(),a(this._geometryQueryCache),this._changeHandle=r(this._changeHandle),a(this.fieldsIndex)}get featureAdapter(){return this.featureStore.featureAdapter}clearCache(){this._geometryQueryCache?.clear(),this._allFeaturesPromise=null,this._timeExtentPromise=null}async executeQuery(e,t){try{return(await this._executeQuery(e,{},t)).createQueryResponse()}catch(i){if(i!==N)throw i;return new v([],e,this).createQueryResponse()}}async executeQueryForCount(e={},t){try{return(await this._executeQuery(e,{returnGeometry:!1,returnCentroid:!1,outSR:null},t)).createQueryResponseForCount()}catch(i){if(i!==N)throw i;return 0}}async executeQueryForExtent(e,t){const i=e.outSR;try{const s=await this._executeQuery(e,{returnGeometry:!0,returnCentroid:!1,outSR:null},t),r=s.size;if(!r)return{count:0,extent:null};return{count:r,extent:await this._getBounds(s.items,s.spatialReference,i||this.spatialReference)}}catch(s){if(s===N)return{count:0,extent:null};throw s}}async executeQueryForIds(e,t){return this.executeQueryForIdSet(e,t).then((e=>Array.from(e)))}async executeQueryForIdSet(e,t){try{const i=await this._executeQuery(e,{returnGeometry:!0,returnCentroid:!1,outSR:null},t),s=i.items,r=new Set;return await this._reschedule((()=>{for(const e of s)r.add(i.featureAdapter.getObjectId(e))}),t),r}catch(i){if(i===N)return new Set;throw i}}async executeQueryForSnapping(e,t){const{point:i,distance:s,returnEdge:r,returnVertex:a}=e;if(!r&&!a)return{candidates:[]};const n=await this._reschedule((()=>this._checkQuerySupport(e.query)),t),u=!S(i.spatialReference,this.spatialReference);u&&await P(i.spatialReference,this.spatialReference);const o="number"==typeof s?s:s.x,l="number"==typeof s?s:s.y,c={xmin:i.x-o,xmax:i.x+o,ymin:i.y-l,ymax:i.y+l,spatialReference:i.spatialReference},h=u?T(c,this.spatialReference):c;if(!h)return{candidates:[]};const p=(await w(g(i),null,{signal:t}))[0],m=(await w(g(h),null,{signal:t}))[0];if(null==p||null==m)return{candidates:[]};const f=new v(await this._reschedule((()=>this._searchFeatures(this._getQueryBBoxes(m.toJSON()))),t),n,this);await this._reschedule((()=>this._executeObjectIdsQuery(f)),t),await this._reschedule((()=>this._executeTimeQuery(f)),t),await this._reschedule((()=>this._executeAttributesQuery(f)),t);const d=p.toJSON(),y=u?T(d,this.spatialReference):d,_=u?Math.max(h.xmax-h.xmin,h.ymax-h.ymin)/2:s;return f.createSnappingResponse({...e,point:y,distance:_},i.spatialReference)}async executeQueryForLatestObservations(e,t){if(!this.timeInfo||!this.timeInfo.trackIdField)throw new i($,"Missing timeInfo or timeInfo.trackIdField",{query:e,timeInfo:this.timeInfo});try{const i=await this._executeQuery(e,{},t);return await this._reschedule((()=>this._filterLatest(i)),t),i.createQueryResponse()}catch(s){if(s!==N)throw s;return new v([],e,this).createQueryResponse()}}async executeQueryForSummaryStatistics(e={},t,i){const{field:s,normalizationField:r,valueExpression:a}=t;return(await this._getQueryEngineResultForStats(e,{field:s,normalizationField:r,valueExpression:a},i)).createSummaryStatisticsResponse(t)}async executeQueryForUniqueValues(e={},t,i){const{field:s,field2:r,field3:a,valueExpression:n}=t;return(await this._getQueryEngineResultForStats(e,{field:s,field2:r,field3:a,valueExpression:n},i)).createUniqueValuesResponse(t)}async executeQueryForClassBreaks(e={},t,i){const{field:s,normalizationField:r,valueExpression:a}=t;return(await this._getQueryEngineResultForStats(e,{field:s,normalizationField:r,valueExpression:a},i)).createClassBreaksResponse(t)}async executeQueryForHistogram(e={},t,i){const{field:s,normalizationField:r,valueExpression:a}=t;return(await this._getQueryEngineResultForStats(e,{field:s,normalizationField:r,valueExpression:a},i)).createHistogramResponse(t)}async fetchRecomputedExtents(e){const[t,i]=await Promise.all(["getFullExtent"in this.featureStore&&this.featureStore.getFullExtent?Promise.resolve(this.featureStore.getFullExtent(this.spatialReference)):this._getBounds(await this._getAllFeatures(),this.spatialReference,this.spatialReference),null!=this._timeExtentPromise?this._timeExtentPromise:this._timeExtentPromise=M(this.timeInfo,this.featureStore)]);return o(e),{fullExtent:t,timeExtent:i}}async _getBounds(e,t,i){const s=c(p(),h);await this.featureStore.forEachBounds(e,(e=>m(s,e)));const r={xmin:s[0],ymin:s[1],xmax:s[3],ymax:s[4],spatialReference:Z(this.spatialReference)};this.hasZ&&isFinite(s[2])&&isFinite(s[5])&&(r.zmin=s[2],r.zmax=s[5]);const a=T(r,t,i);if(a.spatialReference=Z(i),a.xmax-a.xmin==0){const e=l(a.spatialReference);a.xmin-=e,a.xmax+=e}if(a.ymax-a.ymin==0){const e=l(a.spatialReference);a.ymin-=e,a.ymax+=e}if(this.hasZ&&null!=a.zmin&&null!=a.zmax&&a.zmax-a.zmin==0){const e=l(a.spatialReference);a.zmin-=e,a.zmax+=e}return a}async _schedule(e,t){return null!=this._frameTask?this._frameTask.schedule(e,t):e(J)}async _reschedule(e,t){return null!=this._frameTask?this._frameTask.reschedule(e,t):e(J)}async _getAllFeaturesQueryEngineResult(e){return new v(await this._getAllFeatures(),e,this)}async _getAllFeatures(){if(null==this._allFeaturesPromise){const e=[];this._allFeaturesPromise=(async()=>{await this.featureStore.forEach((t=>e.push(t)))})().then((()=>e))}const e=this._allFeaturesPromise,t=await e;return e===this._allFeaturesPromise?t.slice():this._getAllFeatures()}async _executeQuery(e,t,i){e=s(e),e=await this._schedule((()=>V(e,this.definitionExpression,this.spatialReference)),i),e=await this._reschedule((()=>this._checkQuerySupport(e)),i),e={...e,...t};const r=await this._reschedule((()=>this._executeSceneFilterQuery(e,i)),i),a=await this._reschedule((()=>this._executeGeometryQuery(e,r,i)),i);return await this._reschedule((()=>this._executeAggregateIdsQuery(a)),i),await this._reschedule((()=>this._executeObjectIdsQuery(a)),i),await this._reschedule((()=>this._executeTimeQuery(a)),i),await this._reschedule((()=>this._executeAttributesQuery(a)),i),a}async _executeSceneFilterQuery(e,t){if(null==e.sceneFilter)return null;const{outSR:i,returnGeometry:s,returnCentroid:r}=e,a=this.featureStore.featureSpatialReference,n=e.sceneFilter.geometry,u=null==a||S(a,n.spatialReference)?n:T(n,a);if(!u)return null;const o=s||r,l=F(i)&&!S(this.spatialReference,i)&&o?async e=>this._project(e,i):e=>e,c=this.featureAdapter,h=await this._reschedule((()=>this._searchFeatures(this._getQueryBBoxes(u))),t);if("disjoint"===e.sceneFilter.spatialRelationship){if(!h.length)return null;const i=new Set;for(const e of h)i.add(c.getObjectId(e));const s=await this._reschedule((()=>this._getAllFeatures()),t),r=await this._reschedule((async()=>{const r=await z("esriSpatialRelDisjoint",u,this.geometryType,this.hasZ,this.hasM),a=e=>!i.has(c.getObjectId(e))||r(c.getGeometry(e)),n=await this._runSpatialFilter(s,a,t);return new v(n,e,this)}),t);return l(r)}if(!h.length)return new v([],e,this);if(this._canExecuteSinglePass(u,e))return l(new v(h,e,this));const p=await z("esriSpatialRelContains",u,this.geometryType,this.hasZ,this.hasM),m=await this._runSpatialFilter(h,(e=>p(c.getGeometry(e))),t);return l(new v(m,e,this))}async _executeGeometryQuery(i,s,r){if(null!=s&&0===s.items.length)return s;i=null!=s?s.query:i;const{geometry:a,outSR:n,spatialRel:u,returnGeometry:o,returnCentroid:l}=i,c=this.featureStore.featureSpatialReference,h=!a||null==c||S(c,a.spatialReference)?a:T(a,c),p=o||l,m=F(n)&&!S(this.spatialReference,n),f=this._geometryQueryCache&&null==s?m&&p?JSON.stringify({originalFilterGeometry:a,spatialRelationship:u,outSpatialReference:n}):JSON.stringify({originalFilterGeometry:a,spatialRelationship:u}):null,d=f?this._geometryQueryCache.get(f):null;if(null!=d)return new v(d,i,this);const y=async e=>(m&&p&&await this._project(e,n),f&&this._geometryQueryCache.put(f,e.items,e.items.length+1),e);if(!h)return y(null!=s?s:await this._getAllFeaturesQueryEngineResult(i));const g=this.featureAdapter;let _=await this._reschedule((()=>this._searchFeatures(this._getQueryBBoxes(a))),r);if("esriSpatialRelDisjoint"===u){if(!_.length)return y(null!=s?s:await this._getAllFeaturesQueryEngineResult(i));const e=new Set;for(const i of _)e.add(g.getObjectId(i));const t=null!=s?s.items:await this._reschedule((()=>this._getAllFeatures()),r),a=await this._reschedule((async()=>{const s=await z(u,h,this.geometryType,this.hasZ,this.hasM),a=t=>!e.has(g.getObjectId(t))||s(g.getGeometry(t)),n=await this._runSpatialFilter(t,a,r);return new v(n,i,this)}),r);return y(a)}if(null!=s){const i=new e;_=_.filter((e=>t(s.items,e,s.items.length,i)>=0))}if(!_.length){const e=new v([],i,this);return f&&this._geometryQueryCache.put(f,e.items,1),e}if(this._canExecuteSinglePass(h,i))return y(new v(_,i,this));const x=await z(u,h,this.geometryType,this.hasZ,this.hasM),w=await this._runSpatialFilter(_,(e=>x(g.getGeometry(e))),r);return y(new v(w,i,this))}_executeAggregateIdsQuery(e){if(0===e.items.length||!e.query.aggregateIds||!e.query.aggregateIds.length||null==this.aggregateAdapter)return;const t=new Set;for(const s of e.query.aggregateIds){this.aggregateAdapter.getFeatureObjectIds(s).forEach((e=>t.add(e)))}const i=this.featureAdapter.getObjectId;e.items=e.items.filter((e=>t.has(i(e))))}_executeObjectIdsQuery(e){if(0===e.items.length||!e.query.objectIds||!e.query.objectIds.length)return;const t=new Set(e.query.objectIds),i=this.featureAdapter.getObjectId;e.items=e.items.filter((e=>t.has(i(e))))}_executeTimeQuery(e){if(0===e.items.length)return;const t=U(this.timeInfo,e.query.timeExtent,this.featureAdapter);null!=t&&(e.items=e.items.filter(t))}_executeAttributesQuery(e){if(0===e.items.length)return;const t=Q(e.query.where,this.fieldsIndex);if(t){if(!t.isStandardized)throw new TypeError("Where clause is not standardized");e.items=e.items.filter((e=>t.testFeature(e,this.featureAdapter)))}}async _runSpatialFilter(e,t,i){if(!t)return e;if(null==this._frameTask)return e.filter((e=>t(e)));let s=0;const r=new Array,a=async n=>{for(;s<e.length;){const u=e[s++];t(u)&&(r.push(u),n.madeProgress()),n.done&&await this._reschedule((e=>a(e)),i)}};return this._reschedule((e=>a(e)),i).then((()=>r))}_filterLatest(e){const{trackIdField:t,startTimeField:i,endTimeField:s}=this.timeInfo,r=s||i,a=new Map,n=this.featureAdapter.getAttribute;for(const u of e.items){const e=n(u,t),i=n(u,r),s=a.get(e);(!s||i>n(s,r))&&a.set(e,u)}e.items=Array.from(a.values())}_canExecuteSinglePass(e,t){const{spatialRel:i}=t;return O(e)&&("esriSpatialRelEnvelopeIntersects"===i||"esriGeometryPoint"===this.geometryType&&("esriSpatialRelIntersects"===i||"esriSpatialRelContains"===i||"esriSpatialRelWithin"===i))}async _project(e,t){if(!t||S(this.spatialReference,t))return e;const i=this.featureAdapter,s=await B(e.items.map((e=>H(this.geometryType,this.hasZ,this.hasM,i.getGeometry(e)))),this.spatialReference,t);return e.items=s.map(((t,s)=>i.cloneWithGeometry(e.items[s],R(t,this.hasZ,this.hasM)))),e}_getQueryBBoxes(e){if(O(e)){if(_(e))return[f(e.xmin,e.ymin,e.xmax,e.ymax)];if(x(e))return e.rings.map((e=>f(Math.min(e[0][0],e[2][0]),Math.min(e[0][1],e[2][1]),Math.max(e[0][0],e[2][0]),Math.max(e[0][1],e[2][1]))))}return[y(d(),e)]}async _searchFeatures(e){const t=new Set;await Promise.all(e.map((e=>this.featureStore.forEachInBounds(e,(e=>t.add(e))))));const i=Array.from(t.values());return t.clear(),i}async _checkStatisticsSupport(e,t){if((e.distance??0)<0||null!=e.geometryPrecision||e.multipatchOption||e.pixelSize||e.relationParam||e.text||e.outStatistics||e.groupByFieldsForStatistics||e.having||e.orderByFields)throw new i($,"Unsupported query options",{query:e});return this._checkAttributesQuerySupport(e),Promise.all([this._checkStatisticsParamsSupport(t,e),G(e,this.geometryType,this.spatialReference),P(this.spatialReference,e.outSR)]).then((()=>e))}async _checkStatisticsParamsSupport(e,t){let s=[];if(e.valueExpression){const{arcadeUtils:t}=await D();s=t.extractFieldNames(e.valueExpression)}if(e.field&&s.push(e.field),e.field2&&s.push(e.field2),e.field3&&s.push(e.field3),e.normalizationField&&s.push(e.normalizationField),!s.length&&!e.valueExpression)throw new i($,"field or valueExpression is required",{params:e});I(this.fieldsIndex,s,{errorMessage:"Cannot calculate statistics for missing fields",query:t}),j(this.fieldsIndex,s,{expressionName:"statistics",query:t})}async _checkQuerySupport(e){if((e.distance??0)<0||null!=e.geometryPrecision||e.multipatchOption||e.pixelSize||e.relationParam||e.text)throw new i($,"Unsupported query options",{query:e});return this._checkAttributesQuerySupport(e),this._checkStatisticsQuerySupport(e),Promise.all([G(e,this.geometryType,this.spatialReference),P(this.spatialReference,e.outSR)]).then((()=>e))}_checkAttributesQuerySupport(e){const{outFields:t,orderByFields:s,returnDistinctValues:r,outStatistics:a}=e,n=a?a.map((e=>e.outStatisticFieldName&&e.outStatisticFieldName.toLowerCase())).filter(Boolean):[];if(s&&s.length>0){const t=" asc",i=" desc",r=s.map((e=>{const s=e.toLowerCase();return s.includes(t)?s.split(t)[0]:s.includes(i)?s.split(i)[0]:e})).filter((e=>!n.includes(e)));I(this.fieldsIndex,r,{expressionName:"orderByFields",query:e})}if(t&&t.length>0)I(this.fieldsIndex,t,{expressionName:"outFields",query:e});else if(r)throw new i($,"outFields should be specified for returnDistinctValues",{query:e});E(this.fieldsIndex,e.where,e)}_checkStatisticsQuerySupport(e){const{outStatistics:t,groupByFieldsForStatistics:s,having:r}=e,a=s&&s.length,n=t&&t.length;if(r){if(!a||!n)throw new i($,"outStatistics and groupByFieldsForStatistics should be specified with having",{query:e});A(this.fieldsIndex,r,t,e)}if(n){if(!W(t))return;const r=t.map((e=>e.onStatisticField)).filter(Boolean);I(this.fieldsIndex,r,{expressionName:"onStatisticFields",query:e}),a&&I(this.fieldsIndex,s,{expressionName:"groupByFieldsForStatistics",query:e});const n=new Set([...b.jsonValues,...q.jsonValues]),u=new Intl.ListFormat("en-US",{type:"conjunction"}).format([...b.apiValues,...q.apiValues]);for(const s of t){const{onStatisticField:t,statisticType:r}=s;if(("percentile_disc"===r||"percentile_cont"===r)&&"statisticParameters"in s){const{statisticParameters:t}=s;if(!t)throw new i($,"statisticParamters should be set for percentile type",{definition:s,query:e})}else if("count"!==r&&t&&C(t,this.fieldsIndex,n))throw new i($,`outStatistics only supports ${u} field types`,{definition:s,query:e})}}}async _getQueryEngineResultForStats(e,t,i){e=s(e);try{e=await this._schedule((()=>V(e,this.definitionExpression,this.spatialReference)),i),e=await this._reschedule((()=>this._checkStatisticsSupport(e,t)),i);const s=await this._reschedule((()=>this._executeSceneFilterQuery(e,i)),i),r=await this._reschedule((()=>this._executeGeometryQuery(e,s,i)),i);return await this._reschedule((()=>this._executeAggregateIdsQuery(r)),i),await this._reschedule((()=>this._executeObjectIdsQuery(r)),i),await this._reschedule((()=>this._executeTimeQuery(r)),i),await this._reschedule((()=>this._executeAttributesQuery(r)),i),r}catch(r){if(r!==N)throw r;return new v([],e,this)}}}export{K as Feature,ee as QueryEngine};
5
+ import{PositionHint as e,indexOf as t}from"../../../core/arrayUtils.js";import i from"../../../core/Error.js";import{clone as s}from"../../../core/lang.js";import{removeMaybe as r,destroyMaybe as a}from"../../../core/maybe.js";import{MemCacheStorage as n,MemCache as u}from"../../../core/MemCache.js";import{throwIfAborted as o}from"../../../core/promiseUtils.js";import{getMetersPerUnitForSR as l}from"../../../core/unitUtils.js";import{set as c,NEGATIVE_INFINITY as h,create as p,expandWithAABB as m}from"../../../geometry/support/aaBoundingBox.js";import{fromValues as f,create as d}from"../../../geometry/support/aaBoundingRect.js";import{getBoundsXY as y}from"../../../geometry/support/boundsUtils.js";import{fromJSON as g,isExtent as _,isPolygon as x}from"../../../geometry/support/jsonUtils.js";import{normalizeCentralMeridian as w}from"../../../geometry/support/normalizeUtils.js";import{equals as S,isValid as F}from"../../../geometry/support/spatialReferenceUtils.js";import{convertFromGeometry as R}from"../featureConversionUtils.js";import{getWhereClause as Q,validateFields as I,validateFieldTypes as j,validateWhere as E,validateHaving as A,validNumericTypesKebabDict as b,validDateTypesKebabDict as q,hasInvalidFieldType as C}from"./attributeSupport.js";import{checkProjectionSupport as P,project as T,projectMany as B}from"./projectionSupport.js";import{queryCapabilities as k}from"./QueryEngineCapabilities.js";import{QueryEngineResult as v}from"./QueryEngineResult.js";import{getSpatialQueryOperator as z,canQueryWithRBush as O,checkSpatialQuerySupport as G}from"./spatialQuerySupport.js";import{getTimeExtent as M,getTimeOperator as U}from"./timeSupport.js";import{QUERY_ENGINE_EMPTY_RESULT as N,cleanFromGeometryEngine as Z,normalizeQuery as V,getGeometry as H}from"./utils.js";import L from"../../support/FieldsIndex.js";import{loadArcade as D}from"../../../support/arcadeOnDemand.js";import{noBudget as J}from"../../../views/support/Scheduler.js";function $(e){return null!=e&&e.every((e=>"exceedslimit"!==e.statisticType))}const W="feature-store:unsupported-query";class K{constructor(e,t=null,i,s,r){this.attributes=e,this.geometry=i,this.centroid=s,this.filterFlags=r,this.groupId=-1,this.displayId=t}}const X=new n(2e6);let Y=0;class ee{constructor(e){this._geometryQueryCache=null,this._changeHandle=null,this.capabilities={query:k},this.geometryType=e.geometryType,this.hasM=!!e.hasM,this.hasZ=!!e.hasZ,this.objectIdField=e.objectIdField,this.spatialReference=e.spatialReference,this.definitionExpression=e.definitionExpression,this.featureStore=e.featureStore,this.aggregateAdapter=e.aggregateAdapter,this._changeHandle=this.featureStore.events.on("changed",(()=>this.clearCache())),this.timeInfo=e.timeInfo,e.cacheSpatialQueries&&(this._geometryQueryCache=new u(Y+++"$$",X)),this.fieldsIndex=new L(e.fields),e.scheduler&&e.priority&&(this._frameTask=e.scheduler.registerTask(e.priority))}destroy(){this._frameTask=r(this._frameTask),this.clearCache(),a(this._geometryQueryCache),this._changeHandle=r(this._changeHandle),a(this.fieldsIndex)}get featureAdapter(){return this.featureStore.featureAdapter}clearCache(){this._geometryQueryCache?.clear(),this._allFeaturesPromise=null,this._timeExtentPromise=null}async executeQuery(e,t){try{return(await this._executeQuery(e,{},t)).createQueryResponse()}catch(i){if(i!==N)throw i;return new v([],e,this).createQueryResponse()}}async executeQueryForCount(e={},t){try{return(await this._executeQuery(e,{returnGeometry:!1,returnCentroid:!1,outSR:null},t)).createQueryResponseForCount()}catch(i){if(i!==N)throw i;return 0}}async executeQueryForExtent(e,t){const i=e.outSR;try{const s=await this._executeQuery(e,{returnGeometry:!0,returnCentroid:!1,outSR:null},t),r=s.size;if(!r)return{count:0,extent:null};return{count:r,extent:await this._getBounds(s.items,s.spatialReference,i||this.spatialReference)}}catch(s){if(s===N)return{count:0,extent:null};throw s}}async executeQueryForIds(e,t){return this.executeQueryForIdSet(e,t).then((e=>Array.from(e)))}async executeQueryForIdSet(e,t){try{const i=await this._executeQuery(e,{returnGeometry:!0,returnCentroid:!1,outSR:null},t),s=i.items,r=new Set;return await this._reschedule((()=>{for(const e of s)r.add(i.featureAdapter.getObjectId(e))}),t),r}catch(i){if(i===N)return new Set;throw i}}async executeQueryForSnapping(e,t){const{point:i,distance:s,returnEdge:r,returnVertex:a}=e;if(!r&&!a)return{candidates:[]};const n=await this._reschedule((()=>this._checkQuerySupport(e.query)),t),u=!S(i.spatialReference,this.spatialReference);u&&await P(i.spatialReference,this.spatialReference);const o="number"==typeof s?s:s.x,l="number"==typeof s?s:s.y,c={xmin:i.x-o,xmax:i.x+o,ymin:i.y-l,ymax:i.y+l,spatialReference:i.spatialReference},h=u?T(c,this.spatialReference):c;if(!h)return{candidates:[]};const p=(await w(g(i),null,{signal:t}))[0],m=(await w(g(h),null,{signal:t}))[0];if(null==p||null==m)return{candidates:[]};const f=new v(await this._reschedule((()=>this._searchFeatures(this._getQueryBBoxes(m.toJSON()))),t),n,this);await this._reschedule((()=>this._executeObjectIdsQuery(f)),t),await this._reschedule((()=>this._executeTimeQuery(f)),t),await this._reschedule((()=>this._executeAttributesQuery(f)),t);const d=p.toJSON(),y=u?T(d,this.spatialReference):d,_=u?Math.max(h.xmax-h.xmin,h.ymax-h.ymin)/2:s;return f.createSnappingResponse({...e,point:y,distance:_},i.spatialReference)}async executeQueryForLatestObservations(e,t){if(!this.timeInfo||!this.timeInfo.trackIdField)throw new i(W,"Missing timeInfo or timeInfo.trackIdField",{query:e,timeInfo:this.timeInfo});try{const i=await this._executeQuery(e,{},t);return await this._reschedule((()=>this._filterLatest(i)),t),i.createQueryResponse()}catch(s){if(s!==N)throw s;return new v([],e,this).createQueryResponse()}}async executeQueryForSummaryStatistics(e={},t,i){const{field:s,normalizationField:r,valueExpression:a}=t;return(await this._getQueryEngineResultForStats(e,{field:s,normalizationField:r,valueExpression:a},i)).createSummaryStatisticsResponse(t)}async executeQueryForUniqueValues(e={},t,i){const{field:s,field2:r,field3:a,valueExpression:n}=t;return(await this._getQueryEngineResultForStats(e,{field:s,field2:r,field3:a,valueExpression:n},i)).createUniqueValuesResponse(t)}async executeQueryForClassBreaks(e={},t,i){const{field:s,normalizationField:r,valueExpression:a}=t;return(await this._getQueryEngineResultForStats(e,{field:s,normalizationField:r,valueExpression:a},i)).createClassBreaksResponse(t)}async executeQueryForHistogram(e={},t,i){const{field:s,normalizationField:r,valueExpression:a}=t;return(await this._getQueryEngineResultForStats(e,{field:s,normalizationField:r,valueExpression:a},i)).createHistogramResponse(t)}async fetchRecomputedExtents(e){const[t,i]=await Promise.all(["getFullExtent"in this.featureStore&&this.featureStore.getFullExtent?Promise.resolve(this.featureStore.getFullExtent(this.spatialReference)):this._getBounds(await this._getAllFeatures(),this.spatialReference,this.spatialReference),null!=this._timeExtentPromise?this._timeExtentPromise:this._timeExtentPromise=M(this.timeInfo,this.featureStore)]);return o(e),{fullExtent:t,timeExtent:i}}async _getBounds(e,t,i){const s=c(p(),h);await this.featureStore.forEachBounds(e,(e=>m(s,e)));const r={xmin:s[0],ymin:s[1],xmax:s[3],ymax:s[4],spatialReference:Z(this.spatialReference)};this.hasZ&&isFinite(s[2])&&isFinite(s[5])&&(r.zmin=s[2],r.zmax=s[5]);const a=T(r,t,i);if(a.spatialReference=Z(i),a.xmax-a.xmin==0){const e=l(a.spatialReference);a.xmin-=e,a.xmax+=e}if(a.ymax-a.ymin==0){const e=l(a.spatialReference);a.ymin-=e,a.ymax+=e}if(this.hasZ&&null!=a.zmin&&null!=a.zmax&&a.zmax-a.zmin==0){const e=l(a.spatialReference);a.zmin-=e,a.zmax+=e}return a}async _schedule(e,t){return null!=this._frameTask?this._frameTask.schedule(e,t):e(J)}async _reschedule(e,t){return null!=this._frameTask?this._frameTask.reschedule(e,t):e(J)}async _getAllFeaturesQueryEngineResult(e){return new v(await this._getAllFeatures(),e,this)}async _getAllFeatures(){if(null==this._allFeaturesPromise){const e=[];this._allFeaturesPromise=(async()=>{await this.featureStore.forEach((t=>e.push(t)))})().then((()=>e))}const e=this._allFeaturesPromise,t=await e;return e===this._allFeaturesPromise?t.slice():this._getAllFeatures()}async _executeQuery(e,t,i){e=s(e),e=await this._schedule((()=>V(e,this.definitionExpression,this.spatialReference)),i),e=await this._reschedule((()=>this._checkQuerySupport(e)),i),e={...e,...t};const r=await this._reschedule((()=>this._executeSceneFilterQuery(e,i)),i),a=await this._reschedule((()=>this._executeGeometryQuery(e,r,i)),i);return await this._reschedule((()=>this._executeAggregateIdsQuery(a)),i),await this._reschedule((()=>this._executeObjectIdsQuery(a)),i),await this._reschedule((()=>this._executeTimeQuery(a)),i),await this._reschedule((()=>this._executeAttributesQuery(a)),i),a}async _executeSceneFilterQuery(e,t){if(null==e.sceneFilter)return null;const{outSR:i,returnGeometry:s,returnCentroid:r}=e,a=this.featureStore.featureSpatialReference,n=e.sceneFilter.geometry,u=null==a||S(a,n.spatialReference)?n:T(n,a);if(!u)return null;const o=s||r,l=F(i)&&!S(this.spatialReference,i)&&o?async e=>this._project(e,i):e=>e,c=this.featureAdapter,h=await this._reschedule((()=>this._searchFeatures(this._getQueryBBoxes(u))),t);if("disjoint"===e.sceneFilter.spatialRelationship){if(!h.length)return null;const i=new Set;for(const e of h)i.add(c.getObjectId(e));const s=await this._reschedule((()=>this._getAllFeatures()),t),r=await this._reschedule((async()=>{const r=await z("esriSpatialRelDisjoint",u,this.geometryType,this.hasZ,this.hasM),a=e=>!i.has(c.getObjectId(e))||r(c.getGeometry(e)),n=await this._runSpatialFilter(s,a,t);return new v(n,e,this)}),t);return l(r)}if(!h.length)return new v([],e,this);if(this._canExecuteSinglePass(u,e))return l(new v(h,e,this));const p=await z("esriSpatialRelContains",u,this.geometryType,this.hasZ,this.hasM),m=await this._runSpatialFilter(h,(e=>p(c.getGeometry(e))),t);return l(new v(m,e,this))}async _executeGeometryQuery(i,s,r){if(null!=s&&0===s.items.length)return s;i=null!=s?s.query:i;const{geometry:a,outSR:n,spatialRel:u,returnGeometry:o,returnCentroid:l}=i,c=this.featureStore.featureSpatialReference,h=!a||null==c||S(c,a.spatialReference)?a:T(a,c),p=o||l,m=F(n)&&!S(this.spatialReference,n),f=this._geometryQueryCache&&null==s?m&&p?JSON.stringify({originalFilterGeometry:a,spatialRelationship:u,outSpatialReference:n}):JSON.stringify({originalFilterGeometry:a,spatialRelationship:u}):null,d=f?this._geometryQueryCache.get(f):null;if(null!=d)return new v(d,i,this);const y=async e=>(m&&p&&await this._project(e,n),f&&this._geometryQueryCache.put(f,e.items,e.items.length+1),e);if(!h)return y(null!=s?s:await this._getAllFeaturesQueryEngineResult(i));const g=this.featureAdapter;let _=await this._reschedule((()=>this._searchFeatures(this._getQueryBBoxes(a))),r);if("esriSpatialRelDisjoint"===u){if(!_.length)return y(null!=s?s:await this._getAllFeaturesQueryEngineResult(i));const e=new Set;for(const i of _)e.add(g.getObjectId(i));const t=null!=s?s.items:await this._reschedule((()=>this._getAllFeatures()),r),a=await this._reschedule((async()=>{const s=await z(u,h,this.geometryType,this.hasZ,this.hasM),a=t=>!e.has(g.getObjectId(t))||s(g.getGeometry(t)),n=await this._runSpatialFilter(t,a,r);return new v(n,i,this)}),r);return y(a)}if(null!=s){const i=new e;_=_.filter((e=>t(s.items,e,s.items.length,i)>=0))}if(!_.length){const e=new v([],i,this);return f&&this._geometryQueryCache.put(f,e.items,1),e}if(this._canExecuteSinglePass(h,i))return y(new v(_,i,this));const x=await z(u,h,this.geometryType,this.hasZ,this.hasM),w=await this._runSpatialFilter(_,(e=>x(g.getGeometry(e))),r);return y(new v(w,i,this))}_executeAggregateIdsQuery(e){if(0===e.items.length||!e.query.aggregateIds||!e.query.aggregateIds.length||null==this.aggregateAdapter)return;const t=new Set;for(const s of e.query.aggregateIds){this.aggregateAdapter.getFeatureObjectIds(s).forEach((e=>t.add(e)))}const i=this.featureAdapter.getObjectId;e.items=e.items.filter((e=>t.has(i(e))))}_executeObjectIdsQuery(e){if(0===e.items.length||!e.query.objectIds||!e.query.objectIds.length)return;const t=new Set(e.query.objectIds),i=this.featureAdapter.getObjectId;e.items=e.items.filter((e=>t.has(i(e))))}_executeTimeQuery(e){if(0===e.items.length)return;const t=U(this.timeInfo,e.query.timeExtent,this.featureAdapter);null!=t&&(e.items=e.items.filter(t))}_executeAttributesQuery(e){if(0===e.items.length)return;const t=Q(e.query.where,this.fieldsIndex);if(t){if(!t.isStandardized)throw new TypeError("Where clause is not standardized");e.items=e.items.filter((e=>t.testFeature(e,this.featureAdapter)))}}async _runSpatialFilter(e,t,i){if(!t)return e;if(null==this._frameTask)return e.filter((e=>t(e)));let s=0;const r=new Array,a=async n=>{for(;s<e.length;){const u=e[s++];t(u)&&(r.push(u),n.madeProgress()),n.done&&await this._reschedule((e=>a(e)),i)}};return this._reschedule((e=>a(e)),i).then((()=>r))}_filterLatest(e){const{trackIdField:t,startTimeField:i,endTimeField:s}=this.timeInfo,r=s||i,a=new Map,n=this.featureAdapter.getAttribute;for(const u of e.items){const e=n(u,t),i=n(u,r),s=a.get(e);(!s||i>n(s,r))&&a.set(e,u)}e.items=Array.from(a.values())}_canExecuteSinglePass(e,t){const{spatialRel:i}=t;return O(e)&&("esriSpatialRelEnvelopeIntersects"===i||"esriGeometryPoint"===this.geometryType&&("esriSpatialRelIntersects"===i||"esriSpatialRelContains"===i||"esriSpatialRelWithin"===i))}async _project(e,t){if(!t||S(this.spatialReference,t))return e;const i=this.featureAdapter,s=await B(e.items.map((e=>H(this.geometryType,this.hasZ,this.hasM,i.getGeometry(e)))),this.spatialReference,t);return e.items=s.map(((t,s)=>i.cloneWithGeometry(e.items[s],R(t,this.hasZ,this.hasM)))),e}_getQueryBBoxes(e){if(O(e)){if(_(e))return[f(e.xmin,e.ymin,e.xmax,e.ymax)];if(x(e))return e.rings.map((e=>f(Math.min(e[0][0],e[2][0]),Math.min(e[0][1],e[2][1]),Math.max(e[0][0],e[2][0]),Math.max(e[0][1],e[2][1]))))}return[y(d(),e)]}async _searchFeatures(e){const t=new Set;await Promise.all(e.map((e=>this.featureStore.forEachInBounds(e,(e=>t.add(e))))));const i=Array.from(t.values());return t.clear(),i}async _checkStatisticsSupport(e,t){if((e.distance??0)<0||null!=e.geometryPrecision||e.multipatchOption||e.pixelSize||e.relationParam||e.text||e.outStatistics||e.groupByFieldsForStatistics||e.having||e.orderByFields)throw new i(W,"Unsupported query options",{query:e});return this._checkAttributesQuerySupport(e),Promise.all([this._checkStatisticsParamsSupport(t,e),G(e,this.geometryType,this.spatialReference),P(this.spatialReference,e.outSR)]).then((()=>e))}async _checkStatisticsParamsSupport(e,t){let s=[];if(e.valueExpression){const{arcadeUtils:t}=await D();s=t.extractFieldNames(e.valueExpression)}if(e.field&&s.push(e.field),e.field2&&s.push(e.field2),e.field3&&s.push(e.field3),e.normalizationField&&s.push(e.normalizationField),!s.length&&!e.valueExpression)throw new i(W,"field or valueExpression is required",{params:e});I(this.fieldsIndex,s,{errorMessage:"Cannot calculate statistics for missing fields",query:t}),j(this.fieldsIndex,s,{expressionName:"statistics",query:t})}async _checkQuerySupport(e){if((e.distance??0)<0||null!=e.geometryPrecision||e.multipatchOption||e.pixelSize||e.relationParam||e.text)throw new i(W,"Unsupported query options",{query:e});return this._checkAttributesQuerySupport(e),this._checkStatisticsQuerySupport(e),Promise.all([G(e,this.geometryType,this.spatialReference),P(this.spatialReference,e.outSR)]).then((()=>e))}_checkAttributesQuerySupport(e){const{outFields:t,orderByFields:s,returnDistinctValues:r,outStatistics:a}=e,n=a?a.map((e=>e.outStatisticFieldName&&e.outStatisticFieldName.toLowerCase())).filter(Boolean):[];if(s&&s.length>0){const t=" asc",i=" desc",r=s.map((e=>{const s=e.toLowerCase();return s.includes(t)?s.split(t)[0]:s.includes(i)?s.split(i)[0]:e})).filter((e=>!n.includes(e)));I(this.fieldsIndex,r,{expressionName:"orderByFields",query:e})}if(t&&t.length>0)I(this.fieldsIndex,t,{expressionName:"outFields",query:e});else if(r)throw new i(W,"outFields should be specified for returnDistinctValues",{query:e});E(this.fieldsIndex,e.where,e)}_checkStatisticsQuerySupport(e){const{outStatistics:t,groupByFieldsForStatistics:s,having:r}=e,a=s&&s.length,n=t&&t.length;if(r){if(!a||!n)throw new i(W,"outStatistics and groupByFieldsForStatistics should be specified with having",{query:e});A(this.fieldsIndex,r,t,e)}if(n){if(!$(t))return;const r=t.map((e=>e.onStatisticField)).filter(Boolean);I(this.fieldsIndex,r,{expressionName:"onStatisticFields",query:e}),a&&I(this.fieldsIndex,s,{expressionName:"groupByFieldsForStatistics",query:e});const n=new Set([...b.jsonValues,...q.jsonValues]),u=new Intl.ListFormat("en-US",{type:"conjunction"}).format([...b.apiValues,...q.apiValues]);for(const s of t){const{onStatisticField:t,statisticType:r}=s;if(("percentile_disc"===r||"percentile_cont"===r)&&"statisticParameters"in s){const{statisticParameters:t}=s;if(!t)throw new i(W,"statisticParameters should be set for percentile type",{definition:s,query:e})}else if("count"!==r&&"min"!==r&&"max"!==r&&t&&C(t,this.fieldsIndex,n))throw new i(W,`outStatistics with '${r}' statistic type, only supports ${u} field types`,{definition:s,query:e})}}}async _getQueryEngineResultForStats(e,t,i){e=s(e);try{e=await this._schedule((()=>V(e,this.definitionExpression,this.spatialReference)),i),e=await this._reschedule((()=>this._checkStatisticsSupport(e,t)),i);const s=await this._reschedule((()=>this._executeSceneFilterQuery(e,i)),i),r=await this._reschedule((()=>this._executeGeometryQuery(e,s,i)),i);return await this._reschedule((()=>this._executeAggregateIdsQuery(r)),i),await this._reschedule((()=>this._executeObjectIdsQuery(r)),i),await this._reschedule((()=>this._executeTimeQuery(r)),i),await this._reschedule((()=>this._executeAttributesQuery(r)),i),r}catch(r){if(r!==N)throw r;return new v([],e,this)}}}export{K as Feature,ee as QueryEngine};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.27/esri/copyright.txt for details.
4
4
  */
5
- import e from"../../../core/Error.js";import{JSONMap as s}from"../../../core/jsonMap.js";import{WhereClauseCache as i}from"../../../core/sql/WhereClauseCache.js";const n=new i(50,500),r="feature-store:unsupported-query",t=" as ",o=new s({esriFieldTypeString:"string"}),a=new s({esriFieldTypeOID:"oid",esriFieldTypeSmallInteger:"small-integer",esriFieldTypeInteger:"integer",esriFieldTypeSingle:"single",esriFieldTypeDouble:"double",esriFieldTypeLong:"long"}),l=new s({esriFieldTypeDate:"date"}),d=new s({esriFieldTypeGUID:"guid",esriFieldTypeGlobalId:"global-id"}),p=new Set([...a.jsonValues,...l.jsonValues,...o.jsonValues,...d.jsonValues]),u=new Intl.ListFormat("en-US",{type:"conjunction"}).format([...a.apiValues,...l.apiValues,...o.apiValues,...d.apiValues]);function g(s,i,n={}){const t=y(s,i);if(!t)throw new e(r,"invalid SQL expression",{expression:s});const o=n.expressionName||"expression";if(n.validateStandardized&&!t.isStandardized)throw new e(r,`${o} is not standard`,{expression:s});if(n.validateAggregate&&!t.isAggregate)throw new e(r,`${o} does not contain a valid aggregate function`,{expression:s});return t.fieldNames}function c(e,s,i){if(!s)return!0;const n="where clause",r=g(s,e,{validateStandardized:!0,expressionName:n});return m(e,r,{expressionName:n,query:i}),x(e,r,{expressionName:n,query:i}),!0}function f(s,i,t,o){if(!i)return!0;const a="having",l=g(i,s,{validateAggregate:!0,expressionName:a});m(s,l,{expressionName:a,query:o}),x(s,l,{expressionName:a,query:o});const d=n.get(i,s),p=d?.getExpressions().every((e=>{const{aggregateType:i,field:n}=e,r=s.get(n)?.name;return t.some((e=>{const{onStatisticField:n,statisticType:t}=e,o=s.get(n)?.name;return o===r&&t.toLowerCase().trim()===i}))}));if(!p)throw new e(r,"expressions in having should also exist in outStatistics",{having:i});return!0}function y(e,s){return e?n.get(e,s):null}function m(e,s,i={}){i.errorMessage||(i.errorMessage=i.expressionName?`${i.expressionName} contains invalid fields`:"Fields are invalid"),h(e,s,((e,s)=>s.has(e)),i)}function x(e,s,i={}){i.errorMessage||(i.errorMessage=i.expressionName?`${i.expressionName} only supports ${u} field types`:`Only ${u} field types are supported`),h(e,s,((e,s)=>!F(e,s)),i)}function h(s,i,n,t={}){const o=t.verifyExpression??!0,a=[];for(const e of i){const i=n(e,s);if("*"!==e&&!i)if(o){const i=w(e);try{h(s,g(i,s,{validateStandardized:!0}),n,t)}catch(l){const s=l?.details;if(s?.expression)throw l;s?.invalidFields?a.push(...s.invalidFields):a.push(e)}}else a.push(e)}if(a.length)throw new e(r,t.errorMessage,{invalidFields:a,query:t.query})}function w(e){return e.split(t)[0]}function v(e){return e.split(t)[1]}function F(e,s,i=p){const n=s.get(e);return!!n&&!i.has(n.type)}export{v as getAliasFromFieldName,w as getExpressionFromFieldName,y as getWhereClause,F as hasInvalidFieldType,l as validDateTypesKebabDict,d as validGuidTypesKebabDict,a as validNumericTypesKebabDict,x as validateFieldTypes,m as validateFields,f as validateHaving,c as validateWhere};
5
+ import e from"../../../core/Error.js";import{JSONMap as s}from"../../../core/jsonMap.js";import{WhereClauseCache as i}from"../../../core/sql/WhereClauseCache.js";const n=new i(50,500),r="feature-store:unsupported-query",t=" as ",o=new s({esriFieldTypeString:"string"}),a=new s({esriFieldTypeOID:"oid",esriFieldTypeSmallInteger:"small-integer",esriFieldTypeInteger:"integer",esriFieldTypeSingle:"single",esriFieldTypeDouble:"double",esriFieldTypeLong:"long"}),l=new s({esriFieldTypeDate:"date"}),d=new s({esriFieldTypeGUID:"guid",esriFieldTypeGlobalId:"global-id"}),p=new Set([...a.jsonValues,...l.jsonValues,...o.jsonValues,...d.jsonValues]),u=new Intl.ListFormat("en-US",{type:"conjunction"}).format([...a.apiValues,...l.apiValues,...o.apiValues,...d.apiValues]);function g(s,i,n={}){const t=y(s,i);if(!t)throw new e(r,"invalid SQL expression",{expression:s});const o=n.expressionName||"expression";if(n.validateStandardized&&!t.isStandardized)throw new e(r,`${o} is not standard`,{expression:s});if(n.validateAggregate&&!t.isAggregate)throw new e(r,`${o} does not contain a valid aggregate function`,{expression:s});return t.fieldNames}function c(e,s,i){if(!s)return!0;const n="where clause",r=g(s,e,{validateStandardized:!0,expressionName:n});return m(e,r,{expressionName:n,query:i}),x(e,r,{expressionName:n,query:i}),!0}function f(s,i,t,o){if(!i)return!0;const a="having",l=g(i,s,{validateAggregate:!0,expressionName:a});m(s,l,{expressionName:a,query:o}),x(s,l,{expressionName:a,query:o});const d=n.get(i,s),p=d?.getExpressions().every((e=>{const{aggregateType:i,field:n}=e,r=s.get(n)?.name;return t.some((e=>{const{onStatisticField:n,statisticType:t}=e,o=s.get(n)?.name;return o===r&&t.toLowerCase().trim()===i}))}));if(!p)throw new e(r,"expressions in having should also exist in outStatistics",{having:i});return!0}function y(e,s){return e?n.get(e,s):null}function m(e,s,i={}){i.errorMessage||(i.errorMessage=i.expressionName?`${i.expressionName} contains invalid fields`:"Fields are invalid"),h(e,s,((e,s)=>s.has(e)),i)}function x(e,s,i={}){i.errorMessage||(i.errorMessage=i.expressionName?`${i.expressionName} only supports ${u} field types`:`Only ${u} field types are supported`),h(e,s,((e,s)=>!F(e,s)),i)}function h(s,i,n,t={}){const o=t.verifyExpression??!0,a=[];for(const e of i){const i=n(e,s);if("*"!==e&&!i)if(o){const i=w(e);try{h(s,g(i,s,{validateStandardized:!0}),n,t)}catch(l){const s=l?.details;if(s?.expression)throw l;s?.invalidFields?a.push(...s.invalidFields):a.push(e)}}else a.push(e)}if(a.length)throw new e(r,t.errorMessage,{invalidFields:a,query:t.query})}function w(e){return e.split(t)[0]}function v(e){return e.split(t)[1]}function F(e,s,i=p){const n=s.get(e);return!!n&&!i.has(n.type)}export{v as getAliasFromFieldName,w as getExpressionFromFieldName,y as getWhereClause,F as hasInvalidFieldType,l as validDateTypesKebabDict,d as validGuidTypesKebabDict,a as validNumericTypesKebabDict,o as validStringTypesKebabDict,x as validateFieldTypes,m as validateFields,f as validateHaving,c as validateWhere};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.27/esri/copyright.txt for details.
4
4
  */
5
- import e from"../../Graphic.js";import t from"../../core/Collection.js";import a from"../../core/Error.js";import{clone as r}from"../../core/lang.js";import{createResolver as s}from"../../core/promiseUtils.js";import{dataComponents as i}from"../../core/urlUtils.js";import{normalizeCentralMeridian as o}from"../../geometry/support/normalizeUtils.js";import{isEditBusLayer as n,emitApplyEditsEvent as d}from"../mixins/EditBusLayer.js";import{getMimeTypeFormatId as l,getFilenameFormatId as u}from"../support/infoFor3D.js";import{getEffectiveEditingEnabled as p,getEffectiveLayerCapabilities as c}from"../support/layerUtils.js";function h(e){return e&&null!=e.applyEdits}function m(e){return"object"==typeof e&&null!=e&&"objectId"in e&&!!e.objectId}function y(e){return e.every(m)}function f(e){return"object"==typeof e&&null!=e&&"globalId"in e&&!!e.globalId}function g(e){return e.every(f)}async function b(e,t,a,i={}){let o;if(n(e)&&e.url)o=d(e.url,e.layerId,"original-and-current-features"===i.returnServiceEditsOption);else{o=s(),o.promise.then((t=>{(t.addedFeatures.length||t.updatedFeatures.length||t.deletedFeatures.length||t.addedAttachments.length||t.updatedAttachments.length||t.deletedAttachments.length)&&e.emit("edits",t)}));const t={result:o.promise};e.emit("apply-edits",t)}try{const{results:s,edits:n}=await F(e,t,a,i),d=e=>e.filter((e=>!e.error)).map(r),l={edits:n,addedFeatures:d(s.addFeatureResults),updatedFeatures:d(s.updateFeatureResults),deletedFeatures:d(s.deleteFeatureResults),addedAttachments:d(s.addAttachmentResults),updatedAttachments:d(s.updateAttachmentResults),deletedAttachments:d(s.deleteAttachmentResults),exceededTransferLimit:!1};return s.editedFeatureResults?.length&&(l.editedFeatures=s.editedFeatureResults),o.resolve(l),s}catch(l){throw o.reject(l),l}}async function F(e,t,r,s){if(await e.load(),!h(t))throw new a(`${e.type}-layer:no-editing-support`,"Layer source does not support applyEdits capability",{layer:e});if(!p(e))throw new a(`${e.type}-layer:editing-disabled`,"Editing is disabled for layer",{layer:e});const{edits:i,options:o}=await w(e,r,s);return i.addFeatures?.length||i.updateFeatures?.length||i.deleteFeatures?.length||i.addAttachments?.length||i.updateAttachments?.length||i.deleteAttachments?.length?{edits:i,results:await t.applyEdits(i,o)}:{edits:i,results:{addFeatureResults:[],updateFeatureResults:[],deleteFeatureResults:[],addAttachmentResults:[],updateAttachmentResults:[],deleteAttachmentResults:[]}}}async function w(e,r,s){const i=r&&(r.addFeatures||r.updateFeatures||r.deleteFeatures),o=r&&(r.addAttachments||r.updateAttachments||r.deleteAttachments),n=null!=e.infoFor3D;if(!r||!i&&!o)throw new a(`${e.type}-layer:missing-parameters`,"'addFeatures', 'updateFeatures', 'deleteFeatures', 'addAttachments', 'updateAttachments' or 'deleteAttachments' parameter is required");const d=c(e);if(!d.data.isVersioned&&s?.gdbVersion)throw new a(`${e.type}-layer:invalid-parameter`,"'gdbVersion' is applicable only if the layer supports versioned data. See: 'capabilities.data.isVersioned'");if(!d.editing.supportsRollbackOnFailure&&s?.rollbackOnFailureEnabled)throw new a(`${e.type}-layer:invalid-parameter`,"This layer does not support 'rollbackOnFailureEnabled' parameter. See: 'capabilities.editing.supportsRollbackOnFailure'");if(!d.editing.supportsGlobalId&&s?.globalIdUsed)throw new a(`${e.type}-layer:invalid-parameter`,"This layer does not support 'globalIdUsed' parameter. See: 'capabilities.editing.supportsGlobalId'");if(!d.editing.supportsGlobalId&&o)throw new a(`${e.type}-layer:invalid-parameter`,"'addAttachments', 'updateAttachments' and 'deleteAttachments' are applicable only if the layer supports global ids. See: 'capabilities.editing.supportsGlobalId'");if(!s?.globalIdUsed&&o)throw new a(`${e.type}-layer:invalid-parameter`,"When 'addAttachments', 'updateAttachments' or 'deleteAttachments' is specified, globalIdUsed should be set to true");const l={...s};if(null!=l.rollbackOnFailureEnabled||d.editing.supportsRollbackOnFailure||(l.rollbackOnFailureEnabled=!0),!1===l.rollbackOnFailureEnabled&&"original-and-current-features"===l.returnServiceEditsOption)throw new a(`${e.type}-layer:invalid-parameter`,"'original-and-current-features' is valid for 'returnServiceEditsOption' only when 'rollBackOnFailure' is true.");if(!d.editing.supportsReturnServiceEditsInSourceSpatialReference&&l.returnServiceEditsInSourceSR)throw new a(`${e.type}-layer:invalid-parameter`,"This layer does not support 'returnServiceEditsInSourceSR' parameter. See: 'capabilities.editing.supportsReturnServiceEditsInSourceSpatialReference'");if(l.returnServiceEditsInSourceSR&&"original-and-current-features"!==l.returnServiceEditsOption)throw new a(`${e.type}-layer:invalid-parameter`,"'returnServiceEditsInSourceSR' is valid only when 'returnServiceEditsOption' is set to 'original-and-current-features'");const u={...r};if(u.addFeatures=r&&t.isCollection(r.addFeatures)?r.addFeatures.toArray():u.addFeatures||[],u.updateFeatures=r&&t.isCollection(r.updateFeatures)?r.updateFeatures.toArray():u.updateFeatures||[],u.deleteFeatures=r&&t.isCollection(r.deleteFeatures)?r.deleteFeatures.toArray():u.deleteFeatures||[],u.addFeatures.length&&!d.operations.supportsAdd)throw new a(`${e.type}-layer:unsupported-operation`,"Layer does not support adding features.");if(u.updateFeatures.length&&!d.operations.supportsUpdate)throw new a(`${e.type}-layer:unsupported-operation`,"Layer does not support updating features.");if(u.deleteFeatures.length&&!d.operations.supportsDelete)throw new a(`${e.type}-layer:unsupported-operation`,"Layer does not support deleting features.");u.addAttachments=u.addAttachments||[],u.updateAttachments=u.updateAttachments||[],u.deleteAttachments=u.deleteAttachments||[],u.addFeatures=u.addFeatures.map(R),u.updateFeatures=u.updateFeatures.map(R),u.addAssetFeatures=[];const p=s?.globalIdUsed||n;u.addFeatures.forEach((t=>v(t,e,p))),u.updateFeatures.forEach((t=>E(t,e,p))),u.deleteFeatures.forEach((t=>I(t,e,p))),u.addAttachments.forEach((t=>S(t,e))),u.updateAttachments.forEach((t=>S(t,e))),n&&await j(u,e);return{edits:await $(u),options:l}}function A(e,t,r){if(r){if("attributes"in e&&!e.attributes[t.globalIdField])throw new a(`${t.type}-layer:invalid-parameter`,"Feature should have 'globalId' when 'globalIdUsed' is true");if(!("attributes"in e)&&!e.globalId)throw new a(`${t.type}-layer:invalid-parameter`,"'globalId' of the feature should be passed when 'globalIdUsed' is true")}if("geometry"in e&&null!=e.geometry){if(e.geometry.hasZ&&!1===t.capabilities?.data.supportsZ)throw new a(`${t.type}-layer:z-unsupported`,"Layer does not support z values while feature has z values.");if(e.geometry.hasM&&!1===t.capabilities?.data.supportsM)throw new a(`${t.type}-layer:m-unsupported`,"Layer does not support m values while feature has m values.")}}function v(e,t,a){A(e,t,a)}function I(e,t,a){A(e,t,a)}function E(e,t,r){A(e,t,r);const s=c(t);if("geometry"in e&&null!=e.geometry&&!s?.editing.supportsGeometryUpdate)throw new a(`${t.type}-layer:unsupported-operation`,"Layer does not support geometry updates.")}function S(e,t){const{feature:r,attachment:s}=e;if(!r||"attributes"in r&&!r.attributes[t.globalIdField])throw new a(`${t.type}-layer:invalid-parameter`,"Attachment should have reference to a feature with 'globalId'");if(!("attributes"in r)&&!r.globalId)throw new a(`${t.type}-layer:invalid-parameter`,"Attachment should have reference to 'globalId' of the parent feature");if(!s.globalId)throw new a(`${t.type}-layer:invalid-parameter`,"Attachment should have 'globalId'");if(!s.data&&!s.uploadId)throw new a(`${t.type}-layer:invalid-parameter`,"Attachment should have 'data' or 'uploadId'");if(!(s.data instanceof File&&!!s.data.name)&&!s.name)throw new a(`${t.type}-layer:invalid-parameter`,"'name' is required when attachment is specified as Base64 encoded string using 'data'");if(!t.capabilities?.editing.supportsUploadWithItemId&&s.uploadId)throw new a(`${t.type}-layer:invalid-parameter`,"This layer does not support 'uploadId' parameter. See: 'capabilities.editing.supportsUploadWithItemId'");if("string"==typeof s.data){const e=i(s.data);if(e&&!e.isBase64)throw new a(`${t.type}-layer:invalid-parameter`,"Attachment 'data' should be a Blob, File or Base64 encoded string")}}async function $(e){const t=e.addFeatures??[],a=e.updateFeatures??[],r=t.concat(a).map((e=>e.geometry)),s=await o(r),i=t.length,n=a.length;return s.slice(0,i).forEach(((e,a)=>t[a].geometry=e)),s.slice(i,i+n).forEach(((e,t)=>a[t].geometry=e)),e}function R(t){const a=new e;return t.attributes||(t.attributes={}),a.geometry=t.geometry,a.attributes=t.attributes,a}async function j(e,t){if(null==t.infoFor3D)return;const{infoFor3D:r}=t,s=l("model/gltf-binary",r.supportedFormats)??u("glb",r.supportedFormats);if(!(!!s&&r.editFormats.includes(s)))throw new a(`${t.type}-layer:binary-gltf-asset-not-supported`,"3DObjectFeatureLayer requires binary glTF (.glb) support for updating mesh geometry.");e.addAssetFeatures??=[];const{addAssetFeatures:i}=e;for(const a of e.addFeatures??[])O(a)&&i.push(a);for(const a of e.updateFeatures??[])O(a)&&i.push(a)}function O(e){return"mesh"===e?.geometry?.type}function U(e,t,r,s){if(!h(t))throw new a(`${e.type}-layer:no-editing-support`,"Layer source does not support applyEdits capability",{layer:e});if(!t.uploadAssets)throw new a(`${e.type}-layer:no-asset-upload-support`,"Layer source does not support uploadAssets capability",{layer:e});return t.uploadAssets(r,s)}export{b as applyEdits,g as isFeatureIdentifierArrayWithGlobalId,y as isFeatureIdentifierArrayWithObjectId,f as isFeatureIdentifierWithGlobalId,m as isFeatureIdentifierWithObjectId,U as uploadAssets};
5
+ import e from"../../Graphic.js";import t from"../../core/Collection.js";import a from"../../core/Error.js";import{clone as r}from"../../core/lang.js";import s from"../../core/Logger.js";import{createResolver as i}from"../../core/promiseUtils.js";import{dataComponents as o}from"../../core/urlUtils.js";import{normalizeCentralMeridian as n}from"../../geometry/support/normalizeUtils.js";import{isEditBusLayer as d,emitApplyEditsEvent as l}from"../mixins/EditBusLayer.js";import{getMimeTypeFormatId as u,getFilenameFormatId as p}from"../support/infoFor3D.js";import{getEffectiveEditingEnabled as c,getEffectiveLayerCapabilities as h}from"../support/layerUtils.js";function m(e){return e&&null!=e.applyEdits}function y(e){return"object"==typeof e&&null!=e&&"objectId"in e&&!!e.objectId}function f(e){return e.every(y)}function g(e){return"object"==typeof e&&null!=e&&"globalId"in e&&!!e.globalId}function b(e){return e.every(g)}async function F(e,t,a,s={}){let o;if(d(e)&&e.url)o=l(e.url,e.layerId,"original-and-current-features"===s.returnServiceEditsOption);else{o=i(),o.promise.then((t=>{(t.addedFeatures.length||t.updatedFeatures.length||t.deletedFeatures.length||t.addedAttachments.length||t.updatedAttachments.length||t.deletedAttachments.length)&&e.emit("edits",t)}));const t={result:o.promise};e.emit("apply-edits",t)}try{const{results:i,edits:n}=await w(e,t,a,s),d=e=>e.filter((e=>!e.error)).map(r),l={edits:n,addedFeatures:d(i.addFeatureResults),updatedFeatures:d(i.updateFeatureResults),deletedFeatures:d(i.deleteFeatureResults),addedAttachments:d(i.addAttachmentResults),updatedAttachments:d(i.updateAttachmentResults),deletedAttachments:d(i.deleteAttachmentResults),exceededTransferLimit:!1};return i.editedFeatureResults?.length&&(l.editedFeatures=i.editedFeatureResults),o.resolve(l),i}catch(n){throw o.reject(n),n}}async function w(e,t,r,s){if(await e.load(),!m(t))throw new a(`${e.type}-layer:no-editing-support`,"Layer source does not support applyEdits capability",{layer:e});if(!c(e))throw new a(`${e.type}-layer:editing-disabled`,"Editing is disabled for layer",{layer:e});const{edits:i,options:o}=await A(e,r,s);return i.addFeatures?.length||i.updateFeatures?.length||i.deleteFeatures?.length||i.addAttachments?.length||i.updateAttachments?.length||i.deleteAttachments?.length?{edits:i,results:await t.applyEdits(i,o)}:{edits:i,results:{addFeatureResults:[],updateFeatureResults:[],deleteFeatureResults:[],addAttachmentResults:[],updateAttachmentResults:[],deleteAttachmentResults:[]}}}async function A(e,r,i){const o=r&&(r.addFeatures||r.updateFeatures||r.deleteFeatures),n=r&&(r.addAttachments||r.updateAttachments||r.deleteAttachments),d=null!=e.infoFor3D;if(!r||!o&&!n)throw new a(`${e.type}-layer:missing-parameters`,"'addFeatures', 'updateFeatures', 'deleteFeatures', 'addAttachments', 'updateAttachments' or 'deleteAttachments' parameter is required");const l=h(e);if(!l.data.isVersioned&&i?.gdbVersion)throw new a(`${e.type}-layer:invalid-parameter`,"'gdbVersion' is applicable only if the layer supports versioned data. See: 'capabilities.data.isVersioned'");if(!l.editing.supportsRollbackOnFailure&&i?.rollbackOnFailureEnabled)throw new a(`${e.type}-layer:invalid-parameter`,"This layer does not support 'rollbackOnFailureEnabled' parameter. See: 'capabilities.editing.supportsRollbackOnFailure'");if(!l.editing.supportsGlobalId&&i?.globalIdUsed)throw new a(`${e.type}-layer:invalid-parameter`,"This layer does not support 'globalIdUsed' parameter. See: 'capabilities.editing.supportsGlobalId'");if(!l.editing.supportsGlobalId&&n)throw new a(`${e.type}-layer:invalid-parameter`,"'addAttachments', 'updateAttachments' and 'deleteAttachments' are applicable only if the layer supports global ids. See: 'capabilities.editing.supportsGlobalId'");if(!i?.globalIdUsed&&n)throw new a(`${e.type}-layer:invalid-parameter`,"When 'addAttachments', 'updateAttachments' or 'deleteAttachments' is specified, globalIdUsed should be set to true");const u={...i};if(null!=u.rollbackOnFailureEnabled||l.editing.supportsRollbackOnFailure||(u.rollbackOnFailureEnabled=!0),u.rollbackOnFailureEnabled||"original-and-current-features"!==u.returnServiceEditsOption||(!1===u.rollbackOnFailureEnabled&&s.getLogger("esri.layers.graphics.editingSupport").warn(`${e.type}-layer:invalid-parameter`,"'original-and-current-features' is valid for 'returnServiceEditsOption' only when 'rollBackOnFailure' is true, but 'rollBackOnFailure' was set to false. 'rollBackOnFailure' has been overwrritten and set to true."),u.rollbackOnFailureEnabled=!0),!l.editing.supportsReturnServiceEditsInSourceSpatialReference&&u.returnServiceEditsInSourceSR)throw new a(`${e.type}-layer:invalid-parameter`,"This layer does not support 'returnServiceEditsInSourceSR' parameter. See: 'capabilities.editing.supportsReturnServiceEditsInSourceSpatialReference'");if(u.returnServiceEditsInSourceSR&&"original-and-current-features"!==u.returnServiceEditsOption)throw new a(`${e.type}-layer:invalid-parameter`,"'returnServiceEditsInSourceSR' is valid only when 'returnServiceEditsOption' is set to 'original-and-current-features'");const p={...r};if(p.addFeatures=r&&t.isCollection(r.addFeatures)?r.addFeatures.toArray():p.addFeatures||[],p.updateFeatures=r&&t.isCollection(r.updateFeatures)?r.updateFeatures.toArray():p.updateFeatures||[],p.deleteFeatures=r&&t.isCollection(r.deleteFeatures)?r.deleteFeatures.toArray():p.deleteFeatures||[],p.addFeatures.length&&!l.operations.supportsAdd)throw new a(`${e.type}-layer:unsupported-operation`,"Layer does not support adding features.");if(p.updateFeatures.length&&!l.operations.supportsUpdate)throw new a(`${e.type}-layer:unsupported-operation`,"Layer does not support updating features.");if(p.deleteFeatures.length&&!l.operations.supportsDelete)throw new a(`${e.type}-layer:unsupported-operation`,"Layer does not support deleting features.");p.addAttachments=p.addAttachments||[],p.updateAttachments=p.updateAttachments||[],p.deleteAttachments=p.deleteAttachments||[],p.addFeatures=p.addFeatures.map(O),p.updateFeatures=p.updateFeatures.map(O),p.addAssetFeatures=[];const c=i?.globalIdUsed||d;p.addFeatures.forEach((t=>I(t,e,c))),p.updateFeatures.forEach((t=>S(t,e,c))),p.deleteFeatures.forEach((t=>E(t,e,c))),p.addAttachments.forEach((t=>$(t,e))),p.updateAttachments.forEach((t=>$(t,e))),d&&await j(p,e);return{edits:await R(p),options:u}}function v(e,t,r){if(r){if("attributes"in e&&!e.attributes[t.globalIdField])throw new a(`${t.type}-layer:invalid-parameter`,"Feature should have 'globalId' when 'globalIdUsed' is true");if(!("attributes"in e)&&!e.globalId)throw new a(`${t.type}-layer:invalid-parameter`,"'globalId' of the feature should be passed when 'globalIdUsed' is true")}if("geometry"in e&&null!=e.geometry){if(e.geometry.hasZ&&!1===t.capabilities?.data.supportsZ)throw new a(`${t.type}-layer:z-unsupported`,"Layer does not support z values while feature has z values.");if(e.geometry.hasM&&!1===t.capabilities?.data.supportsM)throw new a(`${t.type}-layer:m-unsupported`,"Layer does not support m values while feature has m values.")}}function I(e,t,a){v(e,t,a)}function E(e,t,a){v(e,t,a)}function S(e,t,r){v(e,t,r);const s=h(t);if("geometry"in e&&null!=e.geometry&&!s?.editing.supportsGeometryUpdate)throw new a(`${t.type}-layer:unsupported-operation`,"Layer does not support geometry updates.")}function $(e,t){const{feature:r,attachment:s}=e;if(!r||"attributes"in r&&!r.attributes[t.globalIdField])throw new a(`${t.type}-layer:invalid-parameter`,"Attachment should have reference to a feature with 'globalId'");if(!("attributes"in r)&&!r.globalId)throw new a(`${t.type}-layer:invalid-parameter`,"Attachment should have reference to 'globalId' of the parent feature");if(!s.globalId)throw new a(`${t.type}-layer:invalid-parameter`,"Attachment should have 'globalId'");if(!s.data&&!s.uploadId)throw new a(`${t.type}-layer:invalid-parameter`,"Attachment should have 'data' or 'uploadId'");if(!(s.data instanceof File&&!!s.data.name)&&!s.name)throw new a(`${t.type}-layer:invalid-parameter`,"'name' is required when attachment is specified as Base64 encoded string using 'data'");if(!t.capabilities?.editing.supportsUploadWithItemId&&s.uploadId)throw new a(`${t.type}-layer:invalid-parameter`,"This layer does not support 'uploadId' parameter. See: 'capabilities.editing.supportsUploadWithItemId'");if("string"==typeof s.data){const e=o(s.data);if(e&&!e.isBase64)throw new a(`${t.type}-layer:invalid-parameter`,"Attachment 'data' should be a Blob, File or Base64 encoded string")}}async function R(e){const t=e.addFeatures??[],a=e.updateFeatures??[],r=t.concat(a).map((e=>e.geometry)),s=await n(r),i=t.length,o=a.length;return s.slice(0,i).forEach(((e,a)=>t[a].geometry=e)),s.slice(i,i+o).forEach(((e,t)=>a[t].geometry=e)),e}function O(t){const a=new e;return t.attributes||(t.attributes={}),a.geometry=t.geometry,a.attributes=t.attributes,a}async function j(e,t){if(null==t.infoFor3D)return;const{infoFor3D:r}=t,s=u("model/gltf-binary",r.supportedFormats)??p("glb",r.supportedFormats);if(!(!!s&&r.editFormats.includes(s)))throw new a(`${t.type}-layer:binary-gltf-asset-not-supported`,"3DObjectFeatureLayer requires binary glTF (.glb) support for updating mesh geometry.");e.addAssetFeatures??=[];const{addAssetFeatures:i}=e;for(const a of e.addFeatures??[])U(a)&&i.push(a);for(const a of e.updateFeatures??[])U(a)&&i.push(a)}function U(e){return"mesh"===e?.geometry?.type}function L(e,t,r,s){if(!m(t))throw new a(`${e.type}-layer:no-editing-support`,"Layer source does not support applyEdits capability",{layer:e});if(!t.uploadAssets)throw new a(`${e.type}-layer:no-asset-upload-support`,"Layer source does not support uploadAssets capability",{layer:e});return t.uploadAssets(r,s)}export{F as applyEdits,b as isFeatureIdentifierArrayWithGlobalId,f as isFeatureIdentifierArrayWithObjectId,g as isFeatureIdentifierWithGlobalId,y as isFeatureIdentifierWithObjectId,L as uploadAssets};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.27/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../../chunks/tslib.es6.js";import"../../../geometry.js";import t from"../../../Graphic.js";import{id as s}from"../../../kernel.js";import r from"../../../request.js";import a from"../../../TimeExtent.js";import{isSome as i}from"../../../core/arrayUtils.js";import o from"../../../core/Error.js";import has from"../../../core/has.js";import{JSONMap as n}from"../../../core/jsonMap.js";import u from"../../../core/Loadable.js";import l from"../../../core/Logger.js";import{setDeepValue as d}from"../../../core/object.js";import{debounce as c,after as p}from"../../../core/promiseUtils.js";import{getMetersPerCartesianUnitForSR as h}from"../../../core/unitUtils.js";import{join as y,parseData as m}from"../../../core/urlUtils.js";import{generateBracedUUID as g}from"../../../core/uuid.js";import{property as f}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/accessorSupport/ensureType.js";import{subclass as R}from"../../../core/accessorSupport/decorators/subclass.js";import b from"../../../geometry/Extent.js";import{initializeProjection as S,project as F}from"../../../geometry/projection.js";import{fromJSON as E}from"../../../geometry/support/jsonUtils.js";import{isOriginalExternal as q}from"../../../geometry/support/meshUtils/External.js";import{isFeatureIdentifierArrayWithGlobalId as w,isFeatureIdentifierArrayWithObjectId as _}from"../editingSupport.js";import{createDrawingInfo as O}from"./support/clientSideDefaults.js";import A from"./support/QueryTask.js";import{isHostedAgolService as I}from"../../support/arcgisLayerUrl.js";import{getAssetMapTable as j}from"../../support/infoFor3D.js";import{executeQueryJSON as x}from"../../../rest/query/executeQueryJSON.js";import{unapplyEditsZUnitScaling as T}from"../../../rest/query/operations/editsZScale.js";import N from"../../../rest/support/Query.js";import J from"../../../geometry/SpatialReference.js";const v=new n({originalAndCurrentFeatures:"original-and-current-features",none:"none"}),k=new Set(["Feature Layer","Table"]),M=new n({Started:"published",Publishing:"publishing",Stopped:"unavailable"});let U=class extends u{constructor(){super(...arguments),this.type="feature-layer",this.refresh=c((async()=>{await this.load();const e=this.sourceJSON.editingInfo?.lastEditDate;if(null==e)return{dataChanged:!0,updates:{}};try{await this._fetchService(null)}catch{return{dataChanged:!0,updates:{}}}const t=e!==this.sourceJSON.editingInfo?.lastEditDate;return{dataChanged:t,updates:t?{editingInfo:this.sourceJSON.editingInfo,extent:this.sourceJSON.extent}:null}})),this._ongoingAssetUploads=new Map}load(e){const t=null!=e?e.signal:null,s=this.layer.sourceJSON;return this.addResolvingPromise(this._fetchService(s,t)),Promise.resolve(this)}get queryTask(){const{capabilities:e,parsedUrl:t,dynamicDataSource:s,infoFor3D:r,gdbVersion:a,spatialReference:i,fieldsIndex:o}=this.layer,n=has("featurelayer-pbf")&&e?.query.supportsFormatPBF&&null==r,u=e?.operations?.supportsQueryAttachments??!1;return new A({url:t.path,pbfSupported:n,fieldsIndex:o,infoFor3D:r,dynamicDataSource:s,gdbVersion:a,sourceSpatialReference:i,queryAttachmentsSupported:u})}async addAttachment(e,t){await this.load();const s=e.attributes[this.layer.objectIdField],a=this.layer.parsedUrl.path+"/"+s+"/addAttachment",i=this._getLayerRequestOptions(),o=this._getFormDataForAttachment(t,i.query);try{const e=await r(a,{body:o});return this._createFeatureEditResult(e.data.addAttachmentResult)}catch(n){throw this._createAttachmentErrorResult(s,n)}}async updateAttachment(e,t,s){await this.load();const a=e.attributes[this.layer.objectIdField],i=this.layer.parsedUrl.path+"/"+a+"/updateAttachment",o=this._getLayerRequestOptions({query:{attachmentId:t}}),n=this._getFormDataForAttachment(s,o.query);try{const e=await r(i,{body:n});return this._createFeatureEditResult(e.data.updateAttachmentResult)}catch(u){throw this._createAttachmentErrorResult(a,u)}}async applyEdits(e,t){await this.load();const{layer:a}=this,o=a.infoFor3D,n=null!=o,u=n||(t?.globalIdUsed??!1),l=e.addFeatures?.map((e=>this._getFeatureJSON(e,o)))??[],d=(await Promise.all(l)).filter(i),c=e.updateFeatures?.map((e=>this._getFeatureJSON(e,o)))??[],p=(await Promise.all(c)).filter(i),h=this._getFeatureIds(e.deleteFeatures,u);T(d,p,a.spatialReference);const y=await this._getAttachmentEditsJSON(e),m=n?await this._uploadMeshesAndGetAssetMapEditsJSON(e):null,g=a.capabilities.editing.supportsAsyncApplyEdits&&null!=m&&(0!==m.adds.length||0!==m.updates.length),f={gdbVersion:t?.gdbVersion||a.gdbVersion,rollbackOnFailure:t?.rollbackOnFailureEnabled,useGlobalIds:u,returnEditMoment:t?.returnEditMoment,usePreviousEditMoment:t?.usePreviousEditMoment,sessionId:t?.sessionId,async:g};t?.returnServiceEditsOption?(f.edits=JSON.stringify([{id:a.layerId,adds:d,updates:p,deletes:h,attachments:y,assetMaps:m}]),f.returnServiceEditsOption=v.toJSON(t?.returnServiceEditsOption),f.returnServiceEditsInSourceSR=t?.returnServiceEditsInSourceSR):(f.adds=d.length?JSON.stringify(d):null,f.updates=p.length?JSON.stringify(p):null,f.deletes=h.length?u?JSON.stringify(h):h.join(","):null,f.attachments=y&&JSON.stringify(y),f.assetMaps=null!=m?JSON.stringify(m):void 0);const R=this._getLayerRequestOptions({method:"post",query:f}),b=t?.returnServiceEditsOption?a.url:a.parsedUrl.path,S=g?await this._asyncApplyEdits(b+"/applyEdits",R):await r(b+"/applyEdits",R);if(!a.capabilities.operations?.supportsEditing&&a.effectiveCapabilities?.operations?.supportsEditing){const e=s?.findCredential(a.url);await(e?.refreshToken())}return this._createEditsResult(S)}async deleteAttachments(e,t){await this.load();const s=e.attributes[this.layer.objectIdField],a=this.layer.parsedUrl.path+"/"+s+"/deleteAttachments";try{return(await r(a,this._getLayerRequestOptions({query:{attachmentIds:t.join(",")},method:"post"}))).data.deleteAttachmentResults.map(this._createFeatureEditResult)}catch(i){throw this._createAttachmentErrorResult(s,i)}}fetchRecomputedExtents(e={}){const t=e.signal;return this.load({signal:t}).then((async()=>{const t=this._getLayerRequestOptions({...e,query:{returnUpdates:!0}}),{layerId:s,url:i}=this.layer,{data:o}=await r(`${i}/${s}`,t),{id:n,extent:u,fullExtent:l,timeExtent:d}=o,c=u||l;return{id:n,fullExtent:c&&b.fromJSON(c),timeExtent:d&&a.fromJSON({start:d[0],end:d[1]})}}))}async queryAttachments(e,t={}){await this.load();const s=this._getLayerRequestOptions(t);return this.queryTask.executeAttachmentQuery(e,s)}async queryFeatures(e,t){return await this.load(),this.queryTask.execute(e,{...t,query:this._createRequestQueryOptions(t)})}async queryFeaturesJSON(e,t){return await this.load(),this.queryTask.executeJSON(e,{...t,query:this._createRequestQueryOptions(t)})}async queryObjectIds(e,t){return await this.load(),this.queryTask.executeForIds(e,{...t,query:this._createRequestQueryOptions(t)})}async queryFeatureCount(e,t){return await this.load(),this.queryTask.executeForCount(e,{...t,query:this._createRequestQueryOptions(t)})}async queryExtent(e,t){return await this.load(),this.queryTask.executeForExtent(e,{...t,query:this._createRequestQueryOptions(t)})}async queryRelatedFeatures(e,t){return await this.load(),this.queryTask.executeRelationshipQuery(e,{...t,query:this._createRequestQueryOptions(t)})}async queryRelatedFeaturesCount(e,t){return await this.load(),this.queryTask.executeRelationshipQueryForCount(e,{...t,query:this._createRequestQueryOptions(t)})}async queryTopFeatures(e,t){return await this.load(),this.queryTask.executeTopFeaturesQuery(e,{...t,query:this._createRequestQueryOptions(t)})}async queryTopObjectIds(e,t){return await this.load(),this.queryTask.executeForTopIds(e,{...t,query:this._createRequestQueryOptions(t)})}async queryTopExtents(e,t){return await this.load(),this.queryTask.executeForTopExtents(e,{...t,query:this._createRequestQueryOptions(t)})}async queryTopCount(e,t){return await this.load(),this.queryTask.executeForTopCount(e,{...t,query:this._createRequestQueryOptions(t)})}async fetchPublishingStatus(){if(!I(this.layer.url))return"unavailable";const e=y(this.layer.url,"status"),t=await r(e,{query:{f:"json"}});return M.fromJSON(t.data.status)}async uploadAssets(e,t){const{uploadAssets:s}=await import("./support/uploadAssets.js");return s(e,{layer:this.layer,ongoingUploads:this._ongoingAssetUploads},t)}async _asyncApplyEdits(e,t){const s=(await r(e,t)).data.statusUrl;for(;;){const e=(await r(s,{query:{f:"json"},responseType:"json"})).data;switch(e.status){case"Completed":return r(e.resultUrl,{query:{f:"json"},responseType:"json"});case"CompletedWithErrors":throw new o("async-applyEdits-failed","asynchronous applyEdits call failed.");case"Failed ImportChanges":case"InProgress":case"Pending":case"ExportAttachments":case"ExportChanges":case"ExportingData":case"ExportingSnapshot":case"ImportAttachments":case"ProvisioningReplica":case"UnRegisteringReplica":break;default:throw new o("async-applyEdits-failed","asynchronous applyEdits call failed (undefined response status)")}await p(Q)}}_createRequestQueryOptions(e){const t={...this.layer.customParameters,token:this.layer.apiKey,...e?.query};return this.layer.datesInUnknownTimezone&&(t.timeReferenceUnknownClient=!0),t}async _fetchService(e,t){if(!e){const{data:s}=await r(this.layer.parsedUrl.path,this._getLayerRequestOptions({query:has("featurelayer-advanced-symbols")?{returnAdvancedSymbols:!0}:{},signal:t}));e=s}this.sourceJSON=this._patchServiceJSON(e);const s=e.type;if(!k.has(s))throw new o("feature-layer-source:unsupported-type",`Source type "${s}" is not supported`)}_patchServiceJSON(e){if("Table"!==e.type&&e.geometryType&&!e?.drawingInfo?.renderer&&!e.defaultSymbol){const t=O(e.geometryType).renderer;d("drawingInfo.renderer",t,e)}return"esriGeometryMultiPatch"===e.geometryType&&e.infoFor3D&&(e.geometryType="mesh"),e}async _getFeatureJSON(e,t){const{geometry:s}=e,r={...e.attributes};if(null!=t&&"mesh"===s?.type){const{transformFieldRoles:e}=t,{origin:a,spatialReference:i,transform:o}=s,n=this.layer.spatialReference;await S(i,n);const u=F(a,n);if(r[e.originX]=u.x,r[e.originY]=u.y,r[e.originZ]=u.z??0,null!=o){const{translation:t,scale:a,rotation:u}=o,{vertexSpace:l}=s,d=l.isGeoreferenced?1:h(i)/h(n);r[e.translationX]=t[0]*d,r[e.translationY]=-t[2]*d,r[e.translationZ]=t[1]*d,r[e.scaleX]=a[0],r[e.scaleY]=a[2],r[e.scaleZ]=a[1],r[e.rotationX]=u[0],r[e.rotationY]=u[2],r[e.rotationZ]=u[1],r[e.rotationDeg]=u[3]}return{geometry:null,attributes:r}}return null==s?{attributes:r}:"mesh"===s.type||"extent"===s.type?null:{geometry:s.toJSON(),attributes:r}}async _getAttachmentEditsJSON(e){const t=await Promise.all((e.addAttachments??[]).map((e=>this._getAttachmentEditJSON(e)))),s=await Promise.all((e.updateAttachments??[]).map((e=>this._getAttachmentEditJSON(e)))),r=e.deleteAttachments??[];return t.length||s.length||r.length?{adds:t,updates:s,deletes:[...r]}:null}async _getAttachmentEditJSON(e){const{feature:t,attachment:s}=e,{globalId:r,name:a,contentType:i,data:o,uploadId:n}=s,u={globalId:r,parentGlobalId:null,contentType:null,name:null,uploadId:null,data:null};if(t&&(u.parentGlobalId="attributes"in t?t.attributes&&t.attributes[this.layer.globalIdField]:t.globalId),n)u.uploadId=n;else if(o){const e=await m(o);e&&(u.contentType=e.mediaType,u.data=e.data),o instanceof File&&(u.name=o.name)}return a&&(u.name=a),i&&(u.contentType=i),u}async _uploadMeshesAndGetAssetMapEditsJSON(e){const{addAssetFeatures:t}=e;if(!t?.length)return null;const s=await this._filterRedundantAssetMaps(t);if(!t?.length)return null;const r=s.map((e=>e.geometry));return await this.uploadAssets(r),{adds:this._getAssetMapEditsJSON(s),updates:[],deletes:[]}}_getAssetMapEditsJSON(e){const t=new Array,s=this.layer.globalIdField,r=this.layer.parsedUrl;for(const a of e){const e=a.geometry,{metadata:i}=e,o=i.getExternalSourcesOnService(r),n=a.getAttribute(s);if(0===o.length){l.getLogger(this).error(`Skipping feature ${n}. The mesh it is associated with has not been uploaded to the service and cannot be mapped to it.`);continue}const{source:u}=o.find(q)??o[0],{vertexSpace:d}=e,c=d.isGeoreferenced?["PROJECT_VERTICES"]:[];for(const s of u)1===s.parts.length?t.push({globalId:g(),parentGlobalId:n,assetName:s.assetName,assetHash:s.parts[0].partHash,flags:c}):l.getLogger(this).error(`Skipping asset ${s.assetName}. It does not have exactly one part, so we cannot map it to a feature.`)}return t}_getFeatureIds(e,t){if(!e||0===e.length)return[];if(t&&w(e))return e.map((e=>e.globalId));if(_(e))return e.map((e=>e.objectId));const{layer:s}=this,r=t?s.globalIdField:s.objectIdField;return r?e.map((e=>e.getAttribute(r))):[]}_createEditsResult(e){const t=e.data,{layerId:s}=this.layer,r=[];let a=null;if(Array.isArray(t))for(const u of t)r.push({id:u.id,editedFeatures:u.editedFeatures}),u.id===s&&(a={addResults:u.addResults??[],updateResults:u.updateResults??[],deleteResults:u.deleteResults??[],attachments:u.attachments,editMoment:u.editMoment});else a=t;const i=a?.assetMaps;if(i){for(const e of i.addResults)e.success||l.getLogger(this).error(`Failed to map asset to feature with globalId ${e.globalId}.`);for(const e of i.updateResults)e.success||l.getLogger(this).error(`Failed to map asset to feature with globalId ${e.globalId}.`)}const o=a?.attachments,n={addFeatureResults:a?.addResults?.map(this._createFeatureEditResult,this)??[],updateFeatureResults:a?.updateResults?.map(this._createFeatureEditResult,this)??[],deleteFeatureResults:a?.deleteResults?.map(this._createFeatureEditResult,this)??[],addAttachmentResults:o&&o.addResults?o.addResults.map(this._createFeatureEditResult,this):[],updateAttachmentResults:o&&o.updateResults?o.updateResults.map(this._createFeatureEditResult,this):[],deleteAttachmentResults:o&&o.deleteResults?o.deleteResults.map(this._createFeatureEditResult,this):[]};if(a?.editMoment&&(n.editMoment=a.editMoment),r.length>0){n.editedFeatureResults=[];for(const e of r){const{editedFeatures:t}=e,s=t?.spatialReference?new J(t.spatialReference):null;n.editedFeatureResults.push({layerId:e.id,editedFeatures:{adds:t?.adds?.map((e=>this._createEditedFeature(e,s)))||[],updates:t?.updates?.map((e=>({original:this._createEditedFeature(e[0],s),current:this._createEditedFeature(e[1],s)})))||[],deletes:t?.deletes?.map((e=>this._createEditedFeature(e,s)))||[],spatialReference:s}})}}return n}_createEditedFeature(e,s){return new t({attributes:e.attributes,geometry:E({...e.geometry,spatialReference:s})})}_createFeatureEditResult(e){const t=!0===e.success?null:e.error||{code:void 0,description:void 0};return{objectId:e.objectId,globalId:e.globalId,error:t?new o("feature-layer-source:edit-failure",t.description,{code:t.code}):null}}_createAttachmentErrorResult(e,t){const s=t.details.messages&&t.details.messages[0]||t.message,r=t.details.httpStatus||t.details.messageCode;return{objectId:e,globalId:null,error:new o("feature-layer-source:attachment-failure",s,{code:r})}}_getFormDataForAttachment(e,t){const s=e instanceof FormData?e:e&&e.elements?new FormData(e):null;if(s)for(const r in t){const e=t[r];null!=e&&(s.set?s.set(r,e):s.append(r,e))}return s}_getLayerRequestOptions(e={}){const{parsedUrl:t,gdbVersion:s,dynamicDataSource:r}=this.layer;return{...e,query:{gdbVersion:s,layer:r?JSON.stringify({source:r}):void 0,...t.query,f:"json",...this._createRequestQueryOptions(e)},responseType:"json"}}async _filterRedundantAssetMaps(e){const{layer:t}=this,{globalIdField:s,infoFor3D:r,parsedUrl:a}=t;if(null==r||null==s)return e;const o=j(r);if(null==o)return e;const n=y(a.path,`../${o.id}`),u=new Array,l=new Array;for(const i of e)i.geometry.metadata.getExternalSourcesOnService(a).length>0?l.push(i):u.push(i);const d=l.map((e=>e.getAttribute(s))).filter(i);if(0===d.length)return e;const{assetMapFieldRoles:{parentGlobalId:c,assetHash:p}}=r,h=new N;h.where=`${c} IN (${d.map((e=>`'${e}'`))})`,h.outFields=[p,c],h.returnGeometry=!1;const m=await x(n,h),{features:g}=m;return 0===g.length?e:[...u,...l.filter((e=>{const t=e.getAttribute(s);if(!t)return!0;const{metadata:r}=e.geometry,i=g.filter((e=>e.getAttribute(c)===t));if(0===i.length)return!0;const o=i.map((e=>e.getAttribute(p)));return r.getExternalSourcesOnService(a).flatMap((({source:e})=>e.flatMap((e=>e.parts.map((e=>e.partHash)))))).some((e=>o.every((t=>e!==t))))}))]}};e([f()],U.prototype,"type",void 0),e([f({constructOnly:!0})],U.prototype,"layer",void 0),e([f({readOnly:!0})],U.prototype,"queryTask",null),U=e([R("esri.layers.graphics.sources.FeatureLayerSource")],U);const Q=1e3,C=U;export{C as default};
5
+ import{_ as e}from"../../../chunks/tslib.es6.js";import"../../../geometry.js";import t from"../../../Graphic.js";import{id as s}from"../../../kernel.js";import r from"../../../request.js";import a from"../../../TimeExtent.js";import{isSome as i}from"../../../core/arrayUtils.js";import o from"../../../core/Error.js";import has from"../../../core/has.js";import{JSONMap as n}from"../../../core/jsonMap.js";import u from"../../../core/Loadable.js";import l from"../../../core/Logger.js";import{setDeepValue as d}from"../../../core/object.js";import{debounce as c,after as p}from"../../../core/promiseUtils.js";import{getMetersPerCartesianUnitForSR as h}from"../../../core/unitUtils.js";import{join as y,parseData as m}from"../../../core/urlUtils.js";import{generateBracedUUID as f}from"../../../core/uuid.js";import{property as g}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/accessorSupport/ensureType.js";import{subclass as R}from"../../../core/accessorSupport/decorators/subclass.js";import S from"../../../geometry/Extent.js";import{initializeProjection as b,project as F}from"../../../geometry/projection.js";import{fromJSON as E}from"../../../geometry/support/jsonUtils.js";import{toRelativeVertexSpace as w}from"../../../geometry/support/meshVertexSpaceUtils.js";import{isOriginalExternal as q}from"../../../geometry/support/meshUtils/External.js";import{isFeatureIdentifierArrayWithGlobalId as _,isFeatureIdentifierArrayWithObjectId as O}from"../editingSupport.js";import{createDrawingInfo as A}from"./support/clientSideDefaults.js";import I from"./support/QueryTask.js";import{isHostedAgolService as j}from"../../support/arcgisLayerUrl.js";import{getAssetMapTable as x}from"../../support/infoFor3D.js";import{executeQueryJSON as T}from"../../../rest/query/executeQueryJSON.js";import{unapplyEditsZUnitScaling as N}from"../../../rest/query/operations/editsZScale.js";import v from"../../../rest/support/Query.js";import J from"../../../geometry/SpatialReference.js";const M=new n({originalAndCurrentFeatures:"original-and-current-features",none:"none"}),U=new Set(["Feature Layer","Table"]),k=new n({Started:"published",Publishing:"publishing",Stopped:"unavailable"});let Q=class extends u{constructor(){super(...arguments),this.type="feature-layer",this.refresh=c((async()=>{await this.load();const e=this.sourceJSON.editingInfo?.lastEditDate;if(null==e)return{dataChanged:!0,updates:{}};try{await this._fetchService(null)}catch{return{dataChanged:!0,updates:{}}}const t=e!==this.sourceJSON.editingInfo?.lastEditDate;return{dataChanged:t,updates:t?{editingInfo:this.sourceJSON.editingInfo,extent:this.sourceJSON.extent}:null}})),this._ongoingAssetUploads=new Map}load(e){const t=null!=e?e.signal:null,s=this.layer.sourceJSON;return this.addResolvingPromise(this._fetchService(s,t)),Promise.resolve(this)}get queryTask(){const{capabilities:e,parsedUrl:t,dynamicDataSource:s,infoFor3D:r,gdbVersion:a,spatialReference:i,fieldsIndex:o}=this.layer,n=has("featurelayer-pbf")&&e?.query.supportsFormatPBF&&null==r,u=e?.operations?.supportsQueryAttachments??!1;return new I({url:t.path,pbfSupported:n,fieldsIndex:o,infoFor3D:r,dynamicDataSource:s,gdbVersion:a,sourceSpatialReference:i,queryAttachmentsSupported:u})}async addAttachment(e,t){await this.load();const s=e.attributes[this.layer.objectIdField],a=this.layer.parsedUrl.path+"/"+s+"/addAttachment",i=this._getLayerRequestOptions(),o=this._getFormDataForAttachment(t,i.query);try{const e=await r(a,{body:o});return this._createFeatureEditResult(e.data.addAttachmentResult)}catch(n){throw this._createAttachmentErrorResult(s,n)}}async updateAttachment(e,t,s){await this.load();const a=e.attributes[this.layer.objectIdField],i=this.layer.parsedUrl.path+"/"+a+"/updateAttachment",o=this._getLayerRequestOptions({query:{attachmentId:t}}),n=this._getFormDataForAttachment(s,o.query);try{const e=await r(i,{body:n});return this._createFeatureEditResult(e.data.updateAttachmentResult)}catch(u){throw this._createAttachmentErrorResult(a,u)}}async applyEdits(e,t){await this.load();const{layer:a}=this,o=a.infoFor3D,n=null!=o,u=n||(t?.globalIdUsed??!1),l=n?await this._uploadMeshesAndGetAssetMapEditsJSON(e):null,d=e.addFeatures?.map((e=>this._getFeatureJSON(e,o)))??[],c=(await Promise.all(d)).filter(i),p=e.updateFeatures?.map((e=>this._getFeatureJSON(e,o)))??[],h=(await Promise.all(p)).filter(i),y=this._getFeatureIds(e.deleteFeatures,u);N(c,h,a.spatialReference);const m=await this._getAttachmentEditsJSON(e),f=a.capabilities.editing.supportsAsyncApplyEdits&&n,g={gdbVersion:t?.gdbVersion||a.gdbVersion,rollbackOnFailure:t?.rollbackOnFailureEnabled,useGlobalIds:u,returnEditMoment:t?.returnEditMoment,usePreviousEditMoment:t?.usePreviousEditMoment,sessionId:t?.sessionId,async:f};t?.returnServiceEditsOption?(g.edits=JSON.stringify([{id:a.layerId,adds:c,updates:h,deletes:y,attachments:m,assetMaps:l}]),g.returnServiceEditsOption=M.toJSON(t?.returnServiceEditsOption),g.returnServiceEditsInSourceSR=t?.returnServiceEditsInSourceSR):(g.adds=c.length?JSON.stringify(c):null,g.updates=h.length?JSON.stringify(h):null,g.deletes=y.length?u?JSON.stringify(y):y.join(","):null,g.attachments=m&&JSON.stringify(m),g.assetMaps=null!=l?JSON.stringify(l):void 0);const R=this._getLayerRequestOptions({method:"post",query:g}),S=t?.returnServiceEditsOption?a.url:a.parsedUrl.path,b=f?await this._asyncApplyEdits(S+"/applyEdits",R):await r(S+"/applyEdits",R);if(!a.capabilities.operations?.supportsEditing&&a.effectiveCapabilities?.operations?.supportsEditing){const e=s?.findCredential(a.url);await(e?.refreshToken())}return this._createEditsResult(b)}async deleteAttachments(e,t){await this.load();const s=e.attributes[this.layer.objectIdField],a=this.layer.parsedUrl.path+"/"+s+"/deleteAttachments";try{return(await r(a,this._getLayerRequestOptions({query:{attachmentIds:t.join(",")},method:"post"}))).data.deleteAttachmentResults.map(this._createFeatureEditResult)}catch(i){throw this._createAttachmentErrorResult(s,i)}}fetchRecomputedExtents(e={}){const t=e.signal;return this.load({signal:t}).then((async()=>{const t=this._getLayerRequestOptions({...e,query:{returnUpdates:!0}}),{layerId:s,url:i}=this.layer,{data:o}=await r(`${i}/${s}`,t),{id:n,extent:u,fullExtent:l,timeExtent:d}=o,c=u||l;return{id:n,fullExtent:c&&S.fromJSON(c),timeExtent:d&&a.fromJSON({start:d[0],end:d[1]})}}))}async queryAttachments(e,t={}){await this.load();const s=this._getLayerRequestOptions(t);return this.queryTask.executeAttachmentQuery(e,s)}async queryFeatures(e,t){return await this.load(),this.queryTask.execute(e,{...t,query:this._createRequestQueryOptions(t)})}async queryFeaturesJSON(e,t){return await this.load(),this.queryTask.executeJSON(e,{...t,query:this._createRequestQueryOptions(t)})}async queryObjectIds(e,t){return await this.load(),this.queryTask.executeForIds(e,{...t,query:this._createRequestQueryOptions(t)})}async queryFeatureCount(e,t){return await this.load(),this.queryTask.executeForCount(e,{...t,query:this._createRequestQueryOptions(t)})}async queryExtent(e,t){return await this.load(),this.queryTask.executeForExtent(e,{...t,query:this._createRequestQueryOptions(t)})}async queryRelatedFeatures(e,t){return await this.load(),this.queryTask.executeRelationshipQuery(e,{...t,query:this._createRequestQueryOptions(t)})}async queryRelatedFeaturesCount(e,t){return await this.load(),this.queryTask.executeRelationshipQueryForCount(e,{...t,query:this._createRequestQueryOptions(t)})}async queryTopFeatures(e,t){return await this.load(),this.queryTask.executeTopFeaturesQuery(e,{...t,query:this._createRequestQueryOptions(t)})}async queryTopObjectIds(e,t){return await this.load(),this.queryTask.executeForTopIds(e,{...t,query:this._createRequestQueryOptions(t)})}async queryTopExtents(e,t){return await this.load(),this.queryTask.executeForTopExtents(e,{...t,query:this._createRequestQueryOptions(t)})}async queryTopCount(e,t){return await this.load(),this.queryTask.executeForTopCount(e,{...t,query:this._createRequestQueryOptions(t)})}async fetchPublishingStatus(){if(!j(this.layer.url))return"unavailable";const e=y(this.layer.url,"status"),t=await r(e,{query:{f:"json"}});return k.fromJSON(t.data.status)}async uploadAssets(e,t){const{uploadAssets:s}=await import("./support/uploadAssets.js");return s(e,{layer:this.layer,ongoingUploads:this._ongoingAssetUploads},t)}async _asyncApplyEdits(e,t){const s=(await r(e,t)).data.statusUrl;for(;;){const e=(await r(s,{query:{f:"json"},responseType:"json"})).data;switch(e.status){case"Completed":return r(e.resultUrl,{query:{f:"json"},responseType:"json"});case"CompletedWithErrors":throw new o("async-applyEdits-failed","asynchronous applyEdits call failed.");case"Failed ImportChanges":case"InProgress":case"Pending":case"ExportAttachments":case"ExportChanges":case"ExportingData":case"ExportingSnapshot":case"ImportAttachments":case"ProvisioningReplica":case"UnRegisteringReplica":break;default:throw new o("async-applyEdits-failed","asynchronous applyEdits call failed (undefined response status)")}await p(C)}}_createRequestQueryOptions(e){const t={...this.layer.customParameters,token:this.layer.apiKey,...e?.query};return this.layer.datesInUnknownTimezone&&(t.timeReferenceUnknownClient=!0),t}async _fetchService(e,t){if(!e){const{data:s}=await r(this.layer.parsedUrl.path,this._getLayerRequestOptions({query:has("featurelayer-advanced-symbols")?{returnAdvancedSymbols:!0}:{},signal:t}));e=s}this.sourceJSON=this._patchServiceJSON(e);const s=e.type;if(!U.has(s))throw new o("feature-layer-source:unsupported-type",`Source type "${s}" is not supported`)}_patchServiceJSON(e){if("Table"!==e.type&&e.geometryType&&!e?.drawingInfo?.renderer&&!e.defaultSymbol){const t=A(e.geometryType).renderer;d("drawingInfo.renderer",t,e)}return"esriGeometryMultiPatch"===e.geometryType&&e.infoFor3D&&(e.geometryType="mesh"),e}async _getFeatureJSON(e,t){const{geometry:s}=e,r={...e.attributes};if(null!=t&&"mesh"===s?.type){const{transformFieldRoles:e}=t,{origin:a,spatialReference:i,transform:o}=s,n=this.layer.spatialReference;await b(i,n);const u=F(a,n);if(r[e.originX]=u.x,r[e.originY]=u.y,r[e.originZ]=u.z??0,null!=o){const{translation:t,scale:a,rotation:u}=o,{vertexSpace:l}=s,d=l.isGeoreferenced?1:h(i)/h(n);r[e.translationX]=t[0]*d,r[e.translationY]=-t[2]*d,r[e.translationZ]=t[1]*d,r[e.scaleX]=a[0],r[e.scaleY]=a[2],r[e.scaleZ]=a[1],r[e.rotationX]=u[0],r[e.rotationY]=u[2],r[e.rotationZ]=u[1],r[e.rotationDeg]=u[3]}return{geometry:null,attributes:r}}return null==s?{attributes:r}:"mesh"===s.type||"extent"===s.type?null:{geometry:s.toJSON(),attributes:r}}async _getAttachmentEditsJSON(e){const t=await Promise.all((e.addAttachments??[]).map((e=>this._getAttachmentEditJSON(e)))),s=await Promise.all((e.updateAttachments??[]).map((e=>this._getAttachmentEditJSON(e)))),r=e.deleteAttachments??[];return t.length||s.length||r.length?{adds:t,updates:s,deletes:[...r]}:null}async _getAttachmentEditJSON(e){const{feature:t,attachment:s}=e,{globalId:r,name:a,contentType:i,data:o,uploadId:n}=s,u={globalId:r,parentGlobalId:null,contentType:null,name:null,uploadId:null,data:null};if(t&&(u.parentGlobalId="attributes"in t?t.attributes&&t.attributes[this.layer.globalIdField]:t.globalId),n)u.uploadId=n;else if(o){const e=await m(o);e&&(u.contentType=e.mediaType,u.data=e.data),o instanceof File&&(u.name=o.name)}return a&&(u.name=a),i&&(u.contentType=i),u}async _uploadMeshesAndGetAssetMapEditsJSON(e){const{addAssetFeatures:t}=e;if(!t?.length)return null;const s=await this._filterRedundantAssetMaps(t);if(!t?.length)return null;const r=new Array,a=new Map;for(const i of s){const{geometry:e}=i,{vertexSpace:t}=e;if(t.isRelative)r.push(e);else{const t=w(e);a.set(t,e),i.geometry=t,r.push(t)}}await this.uploadAssets(r);for(const[i,o]of a)o.addExternalSources(i.metadata.externalSources.items);return{adds:this._getAssetMapEditsJSON(s),updates:[],deletes:[]}}_getAssetMapEditsJSON(e){const t=new Array,s=this.layer.globalIdField,r=this.layer.parsedUrl;for(const a of e){const e=a.geometry,{metadata:i}=e,o=i.getExternalSourcesOnService(r),n=a.getAttribute(s);if(0===o.length){l.getLogger(this).error(`Skipping feature ${n}. The mesh it is associated with has not been uploaded to the service and cannot be mapped to it.`);continue}const{source:u}=o.find(q)??o[0],{vertexSpace:d}=e,c=d.isGeoreferenced?["PROJECT_VERTICES"]:[];for(const s of u)1===s.parts.length?t.push({globalId:f(),parentGlobalId:n,assetName:s.assetName,assetHash:s.parts[0].partHash,flags:c}):l.getLogger(this).error(`Skipping asset ${s.assetName}. It does not have exactly one part, so we cannot map it to a feature.`)}return t}_getFeatureIds(e,t){if(!e||0===e.length)return[];if(t&&_(e))return e.map((e=>e.globalId));if(O(e))return e.map((e=>e.objectId));const{layer:s}=this,r=t?s.globalIdField:s.objectIdField;return r?e.map((e=>e.getAttribute(r))):[]}_createEditsResult(e){const t=e.data,{layerId:s}=this.layer,r=[];let a=null;if(Array.isArray(t))for(const u of t)r.push({id:u.id,editedFeatures:u.editedFeatures}),u.id===s&&(a={addResults:u.addResults??[],updateResults:u.updateResults??[],deleteResults:u.deleteResults??[],attachments:u.attachments,editMoment:u.editMoment});else a=t;const i=a?.assetMaps;if(i){for(const e of i.addResults)e.success||l.getLogger(this).error(`Failed to map asset to feature with globalId ${e.globalId}.`);for(const e of i.updateResults)e.success||l.getLogger(this).error(`Failed to map asset to feature with globalId ${e.globalId}.`)}const o=a?.attachments,n={addFeatureResults:a?.addResults?.map(this._createFeatureEditResult,this)??[],updateFeatureResults:a?.updateResults?.map(this._createFeatureEditResult,this)??[],deleteFeatureResults:a?.deleteResults?.map(this._createFeatureEditResult,this)??[],addAttachmentResults:o&&o.addResults?o.addResults.map(this._createFeatureEditResult,this):[],updateAttachmentResults:o&&o.updateResults?o.updateResults.map(this._createFeatureEditResult,this):[],deleteAttachmentResults:o&&o.deleteResults?o.deleteResults.map(this._createFeatureEditResult,this):[]};if(a?.editMoment&&(n.editMoment=a.editMoment),r.length>0){n.editedFeatureResults=[];for(const e of r){const{editedFeatures:t}=e,s=t?.spatialReference?new J(t.spatialReference):null;n.editedFeatureResults.push({layerId:e.id,editedFeatures:{adds:t?.adds?.map((e=>this._createEditedFeature(e,s)))||[],updates:t?.updates?.map((e=>({original:this._createEditedFeature(e[0],s),current:this._createEditedFeature(e[1],s)})))||[],deletes:t?.deletes?.map((e=>this._createEditedFeature(e,s)))||[],spatialReference:s}})}}return n}_createEditedFeature(e,s){return new t({attributes:e.attributes,geometry:E({...e.geometry,spatialReference:s})})}_createFeatureEditResult(e){const t=!0===e.success?null:e.error||{code:void 0,description:void 0};return{objectId:e.objectId,globalId:e.globalId,error:t?new o("feature-layer-source:edit-failure",t.description,{code:t.code}):null}}_createAttachmentErrorResult(e,t){const s=t.details.messages&&t.details.messages[0]||t.message,r=t.details.httpStatus||t.details.messageCode;return{objectId:e,globalId:null,error:new o("feature-layer-source:attachment-failure",s,{code:r})}}_getFormDataForAttachment(e,t){const s=e instanceof FormData?e:e&&e.elements?new FormData(e):null;if(s)for(const r in t){const e=t[r];null!=e&&(s.set?s.set(r,e):s.append(r,e))}return s}_getLayerRequestOptions(e={}){const{parsedUrl:t,gdbVersion:s,dynamicDataSource:r}=this.layer;return{...e,query:{gdbVersion:s,layer:r?JSON.stringify({source:r}):void 0,...t.query,f:"json",...this._createRequestQueryOptions(e)},responseType:"json"}}async _filterRedundantAssetMaps(e){const{layer:t}=this,{globalIdField:s,infoFor3D:r,parsedUrl:a}=t;if(null==r||null==s)return e;const o=x(r);if(null==o)return e;const n=y(a.path,`../${o.id}`),u=new Array,l=new Array;for(const i of e)i.geometry.metadata.getExternalSourcesOnService(a).length>0?l.push(i):u.push(i);const d=l.map((e=>e.getAttribute(s))).filter(i);if(0===d.length)return e;const{assetMapFieldRoles:{parentGlobalId:c,assetHash:p}}=r,h=new v;h.where=`${c} IN (${d.map((e=>`'${e}'`))})`,h.outFields=[p,c],h.returnGeometry=!1;const m=await T(n,h),{features:f}=m;return 0===f.length?e:[...u,...l.filter((e=>{const t=e.getAttribute(s);if(!t)return!0;const{metadata:r}=e.geometry,i=f.filter((e=>e.getAttribute(c)===t));if(0===i.length)return!0;const o=i.map((e=>e.getAttribute(p)));return r.getExternalSourcesOnService(a).flatMap((({source:e})=>e.flatMap((e=>e.parts.map((e=>e.partHash)))))).some((e=>o.every((t=>e!==t))))}))]}};e([g()],Q.prototype,"type",void 0),e([g({constructOnly:!0})],Q.prototype,"layer",void 0),e([g({readOnly:!0})],Q.prototype,"queryTask",null),Q=e([R("esri.layers.graphics.sources.FeatureLayerSource")],Q);const C=1e3,D=Q;export{D as default};