@arcgis/core 6.0.0-next.54 → 6.0.0-next.55

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 (300) hide show
  1. package/WebScene.js +2 -2
  2. package/applications/Components/OrientedImageryViewer/shared/constants.js +1 -1
  3. package/applications/SceneViewer/sceneViewerUtils.js +1 -1
  4. package/arcade/arcadeAsyncRuntime.js +1 -1
  5. package/arcade/arcadeCompiler.js +1 -1
  6. package/arcade/arcadeRuntime.js +1 -1
  7. package/arcade/featureset/support/sqlUtils.js +1 -1
  8. package/arcade/validation/arcadeValidator.js +1 -1
  9. package/assets/esri/core/workers/RemoteClient.js +1 -1
  10. package/assets/esri/core/workers/chunks/0329fa3aa3403f1c243b.js +1 -0
  11. package/assets/esri/core/workers/chunks/{6602310c3fcd91fb6a2f.js → 07c8ac092e4b9e8d5b3c.js} +1 -1
  12. package/assets/esri/core/workers/chunks/0a97b1974367382cfdf5.js +1 -0
  13. package/assets/esri/core/workers/chunks/{db0a7671ab5cbe8afd72.js → 123661019bb69c53f2d3.js} +1 -1
  14. package/assets/esri/core/workers/chunks/{d14732a57c8e63948c60.js → 14259910f44c08fd5bbd.js} +1 -1
  15. package/assets/esri/core/workers/chunks/{1b41ba050cde068d2860.js → 193a73a2c7f4f8482c21.js} +1 -1
  16. package/assets/esri/core/workers/chunks/20acb6f3ed5140b6c6c6.js +1 -0
  17. package/assets/esri/core/workers/chunks/{e507dfc4788295d9c244.js → 249a687ce1b6d0815242.js} +1 -1
  18. package/assets/esri/core/workers/chunks/{afb4dfb89fbc8a342cc5.js → 3354f1fa90f8ce4c8fde.js} +1 -1
  19. package/assets/esri/core/workers/chunks/{9b458b0d1627f22fdd93.js → 3b11e4d2e69b7aea1d65.js} +1 -1
  20. package/assets/esri/core/workers/chunks/41694ee8990e799da225.js +1 -0
  21. package/assets/esri/core/workers/chunks/{e592f2483db71230e8e5.js → 4401b3f8ebb658abe789.js} +1 -1
  22. package/assets/esri/core/workers/chunks/{12add2003631fa314f25.js → 5060be52a380fc4920f8.js} +1 -1
  23. package/assets/esri/core/workers/chunks/{2aa6be0b047a1b25a520.js → 53bbb9aa6e4e4a0a8121.js} +1 -1
  24. package/assets/esri/core/workers/chunks/{4707aedcc1b3bdf5e987.js → 5c34d49a6c9cc34b7626.js} +1 -1
  25. package/assets/esri/core/workers/chunks/69a09c6acb5ae03c67f6.js +1 -0
  26. package/assets/esri/core/workers/chunks/7b156905d168bf973518.js +1 -0
  27. package/assets/esri/core/workers/chunks/{e83806797979138fd22a.js → 844c593754b2692257f4.js} +1 -1
  28. package/assets/esri/core/workers/chunks/{2d3e977f3b75474d7ebc.js → 846248697c398468d8e6.js} +1 -1
  29. package/assets/esri/core/workers/chunks/{f7e33d37dd11fb08f3f8.js → 97107e64407fa6825620.js} +1 -1
  30. package/assets/esri/core/workers/chunks/{032733b863426c5bde00.js → 9e508f930086d2ef5f22.js} +3 -3
  31. package/assets/esri/core/workers/chunks/{5118c7269b706089c88e.js → a05a2c2aaf0c288f9681.js} +1 -1
  32. package/assets/esri/core/workers/chunks/{817bf487df056da1e6ec.js → a116dd204921e7464944.js} +1 -1
  33. package/assets/esri/core/workers/chunks/{944f17e9c9f681b971fb.js → a12e2a345005189c64be.js} +1 -1
  34. package/assets/esri/core/workers/chunks/{15b3386ad92a0b4149b8.js → a24dc5350af001db417a.js} +1 -1
  35. package/assets/esri/core/workers/chunks/{10967a36c77c5188690d.js → a66d6298236d59a615db.js} +1 -1
  36. package/assets/esri/core/workers/chunks/{255f5b45c4d32f97f86c.js → ac0861014b3d2f1a1de2.js} +1 -1
  37. package/assets/esri/core/workers/chunks/ace210d313ce53f3ae10.js +1 -0
  38. package/assets/esri/core/workers/chunks/ae48ee283cfa5b3c14b0.js +1 -0
  39. package/assets/esri/core/workers/chunks/bbd8fcb0bbba7bde3d9b.js +1 -0
  40. package/assets/esri/core/workers/chunks/{ac8d38016e4bee37a77c.js → be0b8bb4f09aae6ff5de.js} +1 -1
  41. package/assets/esri/core/workers/chunks/d0659f1b0495734be4b3.js +1 -0
  42. package/assets/esri/core/workers/chunks/{b9a2b05ede02c305e865.js → d8ffb1502def5c85740b.js} +1 -1
  43. package/assets/esri/core/workers/chunks/{7dfe1e78d2e66de6be22.js → d9ef244019954d5a8a27.js} +1 -1
  44. package/assets/esri/core/workers/chunks/{95403bb27a4ea0a4b7b1.js → ddbfa664e69612295785.js} +1 -1
  45. package/assets/esri/core/workers/chunks/{c6d82397044e403a1f61.js → e61082f56c08abe54b3a.js} +1 -1
  46. package/assets/esri/core/workers/chunks/{55d28d3f5b8ced061e39.js → eaf73ce60f39a48ddd2a.js} +1 -1
  47. package/assets/esri/core/workers/chunks/ed2f2a5da830d058e339.js +1 -0
  48. package/assets/esri/core/workers/chunks/{944cb751c85d3a127f49.js → f52d081bbde5c95265cf.js} +1 -1
  49. package/assets/esri/core/workers/chunks/{1de9be7b65109c207bd5.js → fbd5f3b81cd9f061824d.js} +1 -1
  50. package/assets/esri/layers/raster/formats/blosc-wasm.wasm +0 -0
  51. package/assets/esri/libs/librust-parquet/pkg/parquet_bg.wasm +0 -0
  52. package/basemapGallery/support/basemapCompatibilityUtils.js +1 -1
  53. package/chunks/CypherParser.js +1 -1
  54. package/chunks/GeodeticDistanceCalculator-zRp89-dW.js +1 -1
  55. package/chunks/MultiPathImpl.js +1 -1
  56. package/chunks/OperatorGeodesicBuffer.js +1 -1
  57. package/chunks/UnitFactory.js +1 -1
  58. package/chunks/blosc-wasm.js +2 -0
  59. package/chunks/cameraUtilsSpherical.js +1 -1
  60. package/chunks/parquet.js +1 -1
  61. package/chunks/text.js +1 -1
  62. package/config.js +1 -1
  63. package/core/sql/SqlInterval.js +1 -1
  64. package/core/urlUtils.js +1 -1
  65. package/geometry/geometryEngine.js +1 -1
  66. package/geometry/operators/gx/operatorOffset.js +1 -1
  67. package/geometry/support/Ellipsoid.js +1 -1
  68. package/geometry/support/curves/ellipticArc7Utils.js +1 -1
  69. package/geometry/support/geodesicConstants.js +1 -1
  70. package/geometry/support/meshUtils/primitives.js +1 -1
  71. package/kernel.js +1 -1
  72. package/layers/Lyr3DWasmPerSceneView.js +1 -1
  73. package/layers/VoxelWasmPerSceneView.js +1 -1
  74. package/layers/effects/parser.js +1 -1
  75. package/layers/geospatialPDF/GeospatialPDFLayerWorker.js +1 -1
  76. package/layers/graphics/controllers/I3SOnDemandController.js +1 -1
  77. package/layers/graphics/data/QueryEngineResult.js +1 -1
  78. package/layers/graphics/sources/support/ParquetSourceWorker.js +1 -1
  79. package/layers/parquet.js +1 -1
  80. package/layers/raster/datasets/ZarrRaster.js +1 -1
  81. package/layers/raster/datasets/wcsCoverageParser.js +1 -1
  82. package/layers/raster/formats/RasterCodec.js +1 -1
  83. package/layers/raster/formats/blosc.js +2 -0
  84. package/layers/support/BuildingFilter.js +1 -1
  85. package/layers/support/IntegratedMeshSemantics.js +1 -1
  86. package/layers/support/fieldUtils.d.ts +23 -87
  87. package/layers/support/fieldUtils.js +1 -1
  88. package/layers/support/layersMapping.js +1 -1
  89. package/layers/video/VideoController.js +1 -1
  90. package/legend/ActiveLayerInfo.js +1 -1
  91. package/libs/ajv/ajv.bundle-wrapper.js +1 -1
  92. package/package.json +4 -4
  93. package/renderers/types.d.ts +1 -1
  94. package/rest/knowledgeGraphService.js +1 -1
  95. package/rest/query/operations/pbfFeatureServiceParser.js +1 -1
  96. package/smartMapping/statistics/support/attributeDensity.js +1 -1
  97. package/smartMapping/support/adapters/support/utils.js +1 -1
  98. package/support/tests/serviceMockDependencies.js +1 -1
  99. package/symbols/cim/CIMEffects.js +1 -1
  100. package/symbols/cim/CIMSymbolDrawHelper.js +1 -1
  101. package/symbols/cim/effects/EffectControlMeasureLine.js +1 -1
  102. package/symbols/cim/placements/PlacementInsidePolygon.js +1 -1
  103. package/symbols/cim/rasterizingUtils.js +1 -1
  104. package/views/2d/PaddedViewState.js +1 -1
  105. package/views/2d/engine/vectorTiles/buckets/FillBucket.js +1 -1
  106. package/views/2d/engine/vectorTiles/constants.js +1 -1
  107. package/views/2d/engine/vectorTiles/style/geoJSONVectorTileUtils.js +1 -1
  108. package/views/2d/engine/webgl/effects/HighlightEffect.js +1 -1
  109. package/views/2d/engine/webgl/mesh/templates/segmentUtils.js +1 -1
  110. package/views/2d/engine/webgl/mesh/templates/shapingUtils.js +1 -1
  111. package/views/2d/engine/webgl/shaderGraph/techniques/shaders/constants.js +1 -1
  112. package/views/2d/engine/webgl/shaderGraph/techniques/text/TextShader.js +1 -1
  113. package/views/2d/interactive/editingTools/ControlPointsTransformTool.js +1 -1
  114. package/views/2d/interactive/editingTools/TransformTool.js +1 -1
  115. package/views/2d/layers/FeatureLikeLayerView2D.js +1 -1
  116. package/views/2d/layers/ParquetLayerView2D.js +1 -1
  117. package/views/2d/layers/features/Processor.js +1 -1
  118. package/views/2d/layers/features/aggregation/GridSpatialIndex.js +1 -1
  119. package/views/2d/layers/features/support/AttributeStore.js +1 -1
  120. package/views/2d/layers/features/support/FeatureSetReaderPBF.js +1 -1
  121. package/views/2d/layers/graphics/GraphicsView2D.js +1 -1
  122. package/views/3d/analysis/AreaMeasurement/support/AreaMeasurementPathHelper.js +1 -1
  123. package/views/3d/analysis/Dimension/DimensionTool.js +1 -1
  124. package/views/3d/analysis/Dimension/LengthDimensionSubTool.js +1 -1
  125. package/views/3d/analysis/ElevationProfile/ElevationProfileLineSceneComputation.js +1 -1
  126. package/views/3d/analysis/LineOfSight/LineOfSightController.js +1 -1
  127. package/views/3d/analysis/LineOfSight/LineOfSightItemManipulatedObject3D.js +1 -1
  128. package/views/3d/analysis/LineOfSight/LineOfSightRayIntersector.js +1 -1
  129. package/views/3d/analysis/ShadowCastAnalysisView3D.js +1 -1
  130. package/views/3d/analysis/Slice/SliceTool.js +1 -1
  131. package/views/3d/analysis/Viewshed/ViewshedObserverManipulatedObject3D.js +1 -1
  132. package/views/3d/analysis/Viewshed/ViewshedSnappingController.js +1 -1
  133. package/views/3d/analysis/Viewshed/ViewshedTool.js +1 -1
  134. package/views/3d/analysis/ViewshedAnalysisView3D.js +1 -1
  135. package/views/3d/analysis/VolumeMeasurement/VolumeMeasurementCutFillComputation.js +1 -1
  136. package/views/3d/analysis/VolumeMeasurement/VolumeMeasurementVisualization.js +1 -1
  137. package/views/3d/animation/pointToPoint/Camera.js +1 -1
  138. package/views/3d/camera/constraintUtils.js +1 -1
  139. package/views/3d/camera/intersectionUtils.js +1 -1
  140. package/views/3d/environment/EnvironmentView.js +1 -1
  141. package/views/3d/focusAreaUtils.js +1 -1
  142. package/views/3d/interactive/editingTools/ManipulatedObject3DGraphic.js +1 -1
  143. package/views/3d/interactive/editingTools/dragEventPipeline3D.js +1 -1
  144. package/views/3d/interactive/editingTools/manipulations/config.js +1 -1
  145. package/views/3d/interactive/editingTools/media/MediaElementControllerControlPoints.js +1 -1
  146. package/views/3d/interactive/editingTools/media/MediaElementControllerShape.js +1 -1
  147. package/views/3d/interactive/editingTools/move/MoveTool3D.js +1 -1
  148. package/views/3d/interactive/editingTools/transform/ScaleRotateMeshAdapter.js +1 -1
  149. package/views/3d/interactive/editingTools/transform/TransformTool3D.js +1 -1
  150. package/views/3d/interactive/measurementTools/areaMeasurement3D/AreaMeasurement3DTool.js +1 -1
  151. package/views/3d/interactive/measurementTools/areaMeasurement3D/AreaMeasurement3DView.js +1 -1
  152. package/views/3d/interactive/measurementTools/directLineMeasurement3D/DirectLineMeasurement3DTool.js +1 -1
  153. package/views/3d/layers/I3SMeshView3D.js +1 -1
  154. package/views/3d/layers/SceneLayerGraphicsView3D.js +1 -1
  155. package/views/3d/layers/TiledLayerView3D.js +1 -1
  156. package/views/3d/layers/graphics/Graphics3DExtrudeSymbolLayer.js +1 -1
  157. package/views/3d/layers/graphics/Graphics3DIconSymbolLayer.js +1 -1
  158. package/views/3d/layers/graphics/Graphics3DLineSymbolLayer.js +1 -1
  159. package/views/3d/layers/graphics/Graphics3DMeshFillSymbolLayer.js +1 -1
  160. package/views/3d/layers/graphics/Graphics3DObjectSymbolLayer.js +1 -1
  161. package/views/3d/layers/graphics/Graphics3DPathSymbolLayer.js +1 -1
  162. package/views/3d/layers/graphics/Graphics3DPolygonFillSymbolLayer.js +1 -1
  163. package/views/3d/layers/graphics/Graphics3DSymbolFactory.js +1 -1
  164. package/views/3d/layers/graphics/LabelInfo.js +1 -1
  165. package/views/3d/layers/i3s/I3SClientNodeLoader.js +1 -1
  166. package/views/3d/layers/i3s/I3SIndex.js +1 -1
  167. package/views/3d/layers/i3s/I3SIntersectionHandler.js +1 -1
  168. package/views/3d/layers/i3s/I3SMeshViewFilter.js +1 -1
  169. package/views/3d/layers/i3s/I3SNode.js +1 -1
  170. package/views/3d/layers/i3s/I3SOverrides.js +1 -1
  171. package/views/3d/layers/i3s/I3SViewportQueries.js +1 -1
  172. package/views/3d/layers/i3s/LayerElevationProvider.js +1 -1
  173. package/views/3d/layers/support/FeatureTileFetcher3D.js +1 -1
  174. package/views/3d/layers/support/FeatureTileFetcher3DContext.js +1 -1
  175. package/views/3d/layers/support/FeatureTileMeasurements3D.js +1 -1
  176. package/views/3d/layers/support/FeatureTileVisibility3D.js +1 -1
  177. package/views/3d/layers/support/StageLayerElevationProvider.js +1 -1
  178. package/views/3d/layers/support/Tiles3DLayerViewRegistration.js +1 -1
  179. package/views/3d/layers/support/selectTiles3DSpatialReference.js +1 -1
  180. package/views/3d/layers/support/uvUtils.js +1 -1
  181. package/views/3d/state/Constraints.js +1 -1
  182. package/views/3d/state/ConstraintsManager.js +1 -1
  183. package/views/3d/state/NearFarHeuristic.js +1 -1
  184. package/views/3d/state/ViewState.js +1 -1
  185. package/views/3d/state/ViewStateManager.js +1 -1
  186. package/views/3d/state/controllers/PinchAndPanControllerGlobal.js +1 -1
  187. package/views/3d/state/controllers/PinchAndPanControllerLocal.js +1 -1
  188. package/views/3d/state/controllers/PointToPointAnimationController.js +1 -1
  189. package/views/3d/state/controllers/ZoomStepControllerGlobal.js +1 -1
  190. package/views/3d/state/controllers/ZoomStepControllerLocal.js +1 -1
  191. package/views/3d/state/helpers/SceneIntersectionHelper.js +1 -1
  192. package/views/3d/state/utils/OffsetCorrectionController.js +1 -1
  193. package/views/3d/state/utils/groundNavigationUtils.js +1 -1
  194. package/views/3d/state/utils/navigationUtils.js +1 -1
  195. package/views/3d/support/FrustumExtentIntersection.js +1 -1
  196. package/views/3d/support/RenderCoordsHelper.js +1 -1
  197. package/views/3d/support/SweptSphereVolume.js +1 -1
  198. package/views/3d/support/cameraUtils.js +1 -1
  199. package/views/3d/support/elevationUpdateExtentUtils.js +1 -1
  200. package/views/3d/support/engineContent/line.js +1 -1
  201. package/views/3d/support/engineContent/marker.js +1 -1
  202. package/views/3d/support/hitTest.js +1 -1
  203. package/views/3d/support/orientedBoundingBox.js +1 -1
  204. package/views/3d/support/pointsOfInterest/CameraOnSurface.js +1 -1
  205. package/views/3d/support/pointsOfInterest/PointsOfInterest.js +1 -1
  206. package/views/3d/support/pointsOfInterest/SurfaceGeometryUpdates.js +1 -1
  207. package/views/3d/support/sunUtils.js +1 -1
  208. package/views/3d/terrain/ExtentHelper.js +1 -1
  209. package/views/3d/terrain/OverlayManager.js +1 -1
  210. package/views/3d/terrain/OverlayRenderer.js +1 -1
  211. package/views/3d/terrain/PatchGeometryFactory.js +1 -1
  212. package/views/3d/terrain/TerrainRenderer.js +1 -1
  213. package/views/3d/terrain/TerrainSurface.js +1 -1
  214. package/views/3d/terrain/Tile.js +1 -1
  215. package/views/3d/terrain/TilingSchemeLogic.js +1 -1
  216. package/views/3d/terrain/terrainUtils.js +1 -1
  217. package/views/3d/webgl/RenderCamera.js +1 -1
  218. package/views/3d/webgl-engine/Stage.js +1 -1
  219. package/views/3d/webgl-engine/collections/Component/ComponentObject.js +1 -1
  220. package/views/3d/webgl-engine/collections/Component/ComponentObjectCollection.js +1 -1
  221. package/views/3d/webgl-engine/collections/Component/ComponentObjectElevationAgnosticBVH.js +1 -1
  222. package/views/3d/webgl-engine/collections/Component/ComponentObjectElevationAgnosticComponentGeometryBVH.js +1 -1
  223. package/views/3d/webgl-engine/collections/Component/ElevationAgnosticBVH.js +1 -1
  224. package/views/3d/webgl-engine/collections/Component/IntersectionGeometry.js +1 -1
  225. package/views/3d/webgl-engine/collections/Component/Material/ComponentMaterial.js +1 -1
  226. package/views/3d/webgl-engine/collections/Component/Material/ComponentMaterialRepository.js +1 -1
  227. package/views/3d/webgl-engine/collections/Component/Material/ComponentTechniqueConfiguration.js +1 -1
  228. package/views/3d/webgl-engine/core/shaderLibrary/terrain/Overlay.glsl.js +1 -1
  229. package/views/3d/webgl-engine/effects/atmosphere/MarsAtmosphere.js +1 -1
  230. package/views/3d/webgl-engine/effects/debug/RenderNodeVisualizerNode.js +1 -1
  231. package/views/3d/webgl-engine/effects/highlight/ShadowHighlight.js +1 -1
  232. package/views/3d/webgl-engine/effects/laserlines/LaserlinePathData.js +1 -1
  233. package/views/3d/webgl-engine/effects/shadowAccumulation/ShadowAccumulator.js +1 -1
  234. package/views/3d/webgl-engine/lib/Intersector.js +1 -1
  235. package/views/3d/webgl-engine/lib/Renderer.js +1 -1
  236. package/views/3d/webgl-engine/lib/ShadowMap.js +1 -1
  237. package/views/3d/webgl-engine/lib/TextRenderParameters.js +1 -1
  238. package/views/3d/webgl-engine/lib/TextRenderer.js +1 -1
  239. package/views/3d/webgl-engine/lib/TriangleIntersectionData.js +1 -1
  240. package/views/3d/webgl-engine/lib/edgeRendering/EdgeView.js +1 -1
  241. package/views/3d/webgl-engine/lib/edgeRendering/strokes.js +1 -1
  242. package/views/3d/webgl-engine/lib/verticalOffsetUtils.js +1 -1
  243. package/views/3d/webgl-engine/materials/DefaultMaterial.js +1 -1
  244. package/views/3d/webgl-engine/materials/PolygonOffset.js +1 -1
  245. package/views/3d/webgl-engine/materials/RibbonLineMaterial.js +1 -1
  246. package/views/3d/webgl-engine/parts/RenderView.js +1 -1
  247. package/views/MapView.d.ts +1 -0
  248. package/views/SceneView.js +1 -1
  249. package/views/View2D.js +1 -1
  250. package/views/ViewingMode.js +1 -1
  251. package/views/analysis/ElevationProfile/elevationProfileChartBoundsUtils.js +1 -1
  252. package/views/analysis/ElevationProfile/elevationProfileGeometryUtils.js +1 -1
  253. package/views/draw/DrawAction.js +1 -1
  254. package/views/draw/DrawOperation.js +1 -1
  255. package/views/draw/DrawTool.js +1 -1
  256. package/views/draw/SegmentDrawAction.js +1 -1
  257. package/views/draw/support/Reshape.js +1 -1
  258. package/views/draw/support/helpMessageUtils.js +1 -1
  259. package/views/draw/support/managers/EditSessionManager.js +1 -1
  260. package/views/interactive/dragEventPipeline.js +1 -1
  261. package/views/interactive/editGeometry/EditGeometry.js +1 -1
  262. package/views/interactive/editGeometry/EditGeometryOperations.js +1 -1
  263. package/views/interactive/editGeometry/operations/AddOrUpdatePart.js +1 -1
  264. package/views/layers/support/editableLayerViews.js +1 -1
  265. package/views/overlay/TextOverlayItem.js +1 -1
  266. package/views/support/DefaultsFromMap.js +1 -1
  267. package/views/support/Scheduler.js +1 -1
  268. package/views/support/spatialReferenceSupport.js +1 -1
  269. package/views/webgl/ShaderTranspiler.js +2 -2
  270. package/widgets/AreaMeasurement2D/AreaMeasurement2DTool.js +1 -1
  271. package/widgets/BasemapGallery/support/basemapCompatibilityUtils.js +1 -1
  272. package/widgets/BatchAttributeForm.js +1 -1
  273. package/widgets/DistanceMeasurement2D/DistanceMeasurement2DTool.js +1 -1
  274. package/widgets/Editor/workflowUtils.js +1 -1
  275. package/widgets/ElevationProfile/ElevationProfileLineView.js +1 -1
  276. package/widgets/ElevationProfile/support/chartUtils.js +1 -1
  277. package/widgets/ElevationProfile/support/geometryUtils.js +1 -1
  278. package/widgets/FeatureForm.js +1 -1
  279. package/widgets/Legend/styles/card/ColorRamp.js +1 -1
  280. package/widgets/Legend/support/ActiveLayerInfo.js +1 -1
  281. package/widgets/Measurement.js +1 -1
  282. package/widgets/OrientedImageryViewer/components/ImageLocationWidget.js +1 -1
  283. package/widgets/OrientedImageryViewer/components/ImageMeasurementWidget.js +1 -1
  284. package/widgets/Search/support/layerSearchUtils.js +1 -1
  285. package/widgets/ShadowCast/ShadowCastViewModel.js +1 -1
  286. package/widgets/UtilityNetworkAssociations/UtilityNetworkAssociationsViewModel.js +1 -1
  287. package/widgets/UtilityNetworkAssociations.js +1 -1
  288. package/widgets/Weather/WeatherViewModel.js +1 -1
  289. package/widgets/Weather/css.js +1 -1
  290. package/widgets/Weather.js +1 -1
  291. package/assets/esri/core/workers/chunks/021bd07b9a3e70598840.js +0 -1
  292. package/assets/esri/core/workers/chunks/170e68624b71ac96de4a.js +0 -1
  293. package/assets/esri/core/workers/chunks/8a820e303941b351de81.js +0 -1
  294. package/assets/esri/core/workers/chunks/90d567e920b6982b402d.js +0 -1
  295. package/assets/esri/core/workers/chunks/97cdcedfe853280f6258.js +0 -1
  296. package/assets/esri/core/workers/chunks/9ebc6026934400fc1e1f.js +0 -1
  297. package/assets/esri/core/workers/chunks/b4a325dcf50e276751d7.js +0 -1
  298. package/assets/esri/core/workers/chunks/be5857b0d1b00faf430b.js +0 -1
  299. package/assets/esri/core/workers/chunks/cd9100a7c8309dfa7569.js +0 -1
  300. package/assets/esri/core/workers/chunks/e58f51618251f74aaafd.js +0 -1
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import t from"../../../core/Accessor.js";import{property as n,subclass as r}from"../../../core/accessorSupport/decorators.js";import{runUntracked as i}from"../../../core/accessorSupport/tracking.js";import has from"../../../core/has.js";import{exactEquals as a}from"../../../core/libs/gl-matrix-2/math/vec3.js";import o from"../../../core/Logger.js";import{destroyMaybe as s}from"../../../core/maybe.js";import c from"../../../core/PooledArray.js";import{EsriPromiseMixin as l}from"../../../core/Promise.js";import{isAbortError as u}from"../../../core/promiseUtils.js";import{watch as d,sync as f,initial as p}from"../../../core/reactiveUtils.js";import{UpdatingHandles as m}from"../../../core/support/UpdatingHandles.js";import{create as h,fromValues as g}from"../../../geometry/support/aaBoundingRect.js";import{I3SClientNodeLoader as _}from"../../../views/3d/layers/i3s/I3SClientNodeLoader.js";import{I3SDataRequester as v}from"../../../views/3d/layers/i3s/I3SDataRequester.js";import{addCallback as y}from"../../../views/3d/layers/i3s/I3SFrameTask.js";import{I3SIndex as b}from"../../../views/3d/layers/i3s/I3SIndex.js";import x from"../../../views/3d/layers/i3s/I3SLodHandling.js";import S from"../../../views/3d/layers/i3s/I3SNodeLoader.js";import{getVertexCrs as C,getIndexCrs as w,findIntersectingNodes as T}from"../../../views/3d/layers/i3s/I3SUtil.js";import E from"../../../views/3d/layers/i3s/I3SViewportQueries.js";import{groundNavigationConstants as D}from"../../../views/3d/state/utils/groundNavigationUtils.js";import{projectElevationUpdateExtent as O}from"../../../views/3d/support/elevationUpdateExtentUtils.js";import{toBoundingRect as k}from"../../../views/3d/support/extentUtils.js";import{minQuality as A}from"../../../views/3d/support/MemoryController.js";import{PromiseQueue as j}from"../../../views/support/PromiseQueue.js";import{noBudget as M}from"../../../views/support/Scheduler.js";import{viewingModeFromString as N}from"../../../views/ViewingMode.js";const P=1e4,F=1e-4;let I=class extends l(t){get isMeshPyramid(){return this.layer.profile===`mesh-pyramids`||this.layer.store?.lodType===`MeshPyramid`}get isGraphics3D(){return this.layer.profile===`points`}get useMaximumNumberOfFeatures(){return!this.isMeshPyramid&&(this.layer.priority==null||this.layer.priority===`High`)}get indexRequester(){return new v(this.layer.customParameters,this.layer.apiKey)}get dataRequester(){return new v(this.layer.customParameters,this.layer.apiKey)}get crsVertex(){return C(this.layer)}get crsIndex(){return w(this.layer)}get layer(){return this.layerView.layer}get updating(){return this.running||this._updatingHandles.updating}get rootNodeVisible(){return i(()=>{if(this._index){let e=this._index.rootNode;if(e)return this._updateViewData(),this._index.isNodeVisible(e.index)}return!0})}get index(){return this._index}get requiredAttributes(){return this._requiredAttributes}constructor(e){super(e),this.featureTarget=5e4,this.fixedFeatureTarget=!1,this._updatingHandles=new m,this.running=!0,this.updatingProgress=1,this.leavesReached=!1,this.worker=null,this._featureLOD=1,this._stableFeatureLOD=!1,this._isIdle=!1,this._cameraDirty=!0,this._invisibleDirty=!1,this._newLoadingNodes=new c({deallocator:null}),this._modificationsNodeFilteringArray=new c,this._downloadingCount=0,this._loadingNodes=new Map,this._updatingNodes=new Map,this._progressMaxNumNodes=1,this._requiredAttributes=[],this._requiredAttributesDirty=!0,this._updatesDisabled=!1,this.disableIDBCache=!1,this._disableMemCache=!1,this._restartNodeLoading=!1,this._fields=null,this._attributeStorageInfo=null,this._idleQueue=new j,this._elevationUpdateNodes=new c({deallocator:null}),this._errorCount=0}initialize(){let{layerView:e,layer:t}=this;this._disableMemCache=!e.loadCachedGPUData||!e.addCachedGPUData,this._lodHandling=new x(e),this._defaultGeometrySchema=t.store.defaultGeometrySchema,this.disableIDBCache=!!has(`disable-feature:idb-cache`),`fields`in t&&(this._fields=t.fields,this._attributeStorageInfo=t.attributeStorageInfo),this.addResolvingPromise(Promise.all([t.indexInfo,t.when(),e.when()]).then(([n])=>{if(this.destroyed||!e||e.destroyed||!n)return;let{view:r,clientGeometry:i}=e;if(this._setClippingArea(r.clippingArea),this.addHandles([this._updatingHandles.add(()=>r?.pointsOfInterest?.focus?.renderLocation,e=>this._pointOfInterestChanged(e),{initial:!0,equals:a}),d(()=>r.quality,()=>this._setCameraDirty(),f),this._updatingHandles.add(()=>r.state.mode===2,t=>{this._updateIdleState(t),t&&(this._index?.resetFailedNodes(),e.contentVisible||this._updateViewData())},p),this._updatingHandles.add(()=>e.contentVisible,e=>{e&&this._index?.invalidateAllElevationRanges(),this.restartNodeLoading()},p),y(e.view.resourceController.scheduler,this),this._updatingHandles.add(()=>[this.featureTarget,this.fixedFeatureTarget],()=>{this._setCameraDirty(),this._stableFeatureLOD=!1}),this._updatingHandles.add(()=>r.state?.contentCamera,()=>this._setCameraDirty()),this._updatingHandles.add(()=>r.navigation.mode?.type,e=>{this._setCameraDirty(),this._index&&(this._index.isGroundNavigationMode=e===`ground`)}),this._updatingHandles.add(()=>t.elevationInfo,e=>this._elevationInfoChanged(e),f),this._updatingHandles.add(()=>e.lodFactor,()=>this._setCameraDirty()),this._updatingHandles.add(()=>e.availableFields,()=>this._requiredFieldsChange()),this._updatingHandles.add(()=>e.holeFilling,e=>this._index!=null&&(this._index.holeFilling=e))]),this._viewportQueries=new E(this.crsIndex,r.renderCoordsHelper,r.state.contentCamera,!r.state.fixedContentCamera||this.isGraphics3D,this._clippingArea,this.isMeshPyramid?r.groundView:r.elevationProvider,N(r.viewingMode),this.layer.elevationInfo,{progressiveLoadFactor:this._getProgressiveLoadFactor(),screenspaceErrorBias:this._lod,angleDependentLoD:this._lod<.5}),this._clientNodeLoader=new _(this.layer.uid,{indexSR:this.crsIndex,vertexSR:this.crsVertex,renderSR:r.renderCoordsHelper.spatialReference},r.resourceController.memoryController,this.worker),this._index=new b(N(r.viewingMode),t,r.navigation.mode.type===`ground`,D.i3sNodeDownwardCheckDistanceInMeters/r.renderCoordsHelper.unitInMeters,n,this.indexRequester,this._clientNodeLoader,this._viewportQueries,o.getLogger(this),e.holeFilling,t=>e.isNodeLoaded(t),t=>e.isNodeReloading(t),e=>this._shouldLoadNode(e),e=>this._enableFromGPUCache(e,1),e=>this._needsUpdate(e),t=>e.computeVisibilityObb?.(t)??null,e?.computeNodeFiltering?t=>e.computeNodeFiltering(t):void 0),this._index.updateElevationInfo(this.layer.elevationInfo,this.isMeshPyramid||this.isGraphics3D),this._index.imModificationsChanged(!!e.hasModifications),this._index.layerFilterChanged(!!e.hasGeometryFilter),i!=null){for(let e of i)this._addMesh(e.mesh,e.oid);this.addHandles(i.on(`change`,e=>{for(let t of e.removed)this._removeMesh(t.oid);for(let t of e.added)this._addMesh(t.mesh,t.oid)}))}this._startNodeLoading()}))}updateNodeModificationStatus(e){let t=this._index,n=this.layerView;t!=null&&n?.updateNodeModificationStatus&&(this._modificationsNodeFilteringArray.clear(),e.forAll(e=>{let n=t.getNode(e);n!=null&&this._modificationsNodeFilteringArray.push(n)}),n.updateNodeModificationStatus(this._modificationsNodeFilteringArray),this._invisibleDirty=!0)}destroy(){this.cancelNodeLoading(),this._updatingHandles.destroy(),this._nodeLoader=null,L.prune(),this._newLoadingNodes.prune(),this._modificationsNodeFilteringArray.prune(),this._elevationUpdateNodes.prune(),R!=null&&(R.hide(),R=null),this._index=null,this._lodHandling=s(this._lodHandling),this._nodeLoader=null,this._clientNodeLoader=null,this._viewportQueries=null,this._set(`worker`,null)}get viewportQueries(){return this._viewportQueries}_getRequiredAttributes(){if(this._attributeStorageInfo==null||!this._fields||!this.layerView.availableFields)return[];let e=this._attributeStorageInfo,t=this._fields,n=this.layer.objectIdField;return this.layerView.availableFields.map(n=>{let r=B(e,n),i=B(t,n);return r>=0&&i>=0?{index:r,name:t[i].name,field:t[i],attributeStorageInfo:e[r]}:null}).filter(e=>e!=null&&e.name!==n)}_requiredFieldsChange(){let e=this._getRequiredAttributes();z(this._requiredAttributes,e)||(this._requiredAttributes=e,this._requiredAttributesDirty=!1,this.restartNodeLoading())}requestUpdate(){this._requiredAttributesDirty=!0,this.restartNodeLoading()}_setClippingArea(e){let t=h();this._clippingArea=k(e,t,this.layerView.view.renderSpatialReference)?t:null}_pointOfInterestChanged(e){this._viewportQueries!=null&&(this._viewportQueries.setPointOfInterest(e),this._index!=null&&this._index.requestUpdate())}updateClippingArea(e){this._setClippingArea(e),this._viewportQueries!=null&&this._index!=null&&(this._viewportQueries.updateClippingArea(this._clippingArea),this._index.invalidateVisibilityCache()),this._setCameraDirty()}_setCameraDirty(){this._cameraDirty=!0,this._lodHandling.setLodGlobalDirty(),this._evaluateRunning()}_addMesh(e,t){if(this._index==null)return;let n=this._clientNodeLoader.createMeshNodeInfo(e,t),r=this._index.addClientNodeToIndex(n.id,n.mbs);this._clientNodeLoader.addMeshNode(r,n),this._evaluateRunning(),this.notifyChange(`rootNodeVisible`)}_removeMesh(e){let t=this._clientNodeLoader.getMeshNodeIndex(e);if(t!=null){if(this._index!=null)this._index.removeClientNodeFromIndex(t,(e,t)=>{this.layerView.removeNode(t),this._clientNodeLoader.removeNode(e),this.layerView.deleteCachedNodeData&&e!=null&&this.layerView.deleteCachedNodeData(e),this.layerView.deleteCachedGPUData?.(this.layerView.loadCachedGPUData?.(t))},(e,t,n)=>{this._clientNodeLoader.updateNodeIndex(e,t,n),this.layerView.updateNodeIndex&&this.layerView.updateNodeIndex(t,n)}),this.notifyChange(`rootNodeVisible`);else throw Error(`delayed removal of client side i3s node geometry not supported yet.`)}}updateElevationChanged(e,t){let n=this._index,r=this._viewportQueries;if(n?.rootNode==null||t==null||r==null)return null;let i=r.elevationIntersectionSpatialReference;i.equals(t)||(O(e,t,V,i)||g(-1/0,-1/0,1/0,1/0,V),e=V);let a=this._elevationUpdateNodes;return a.clear(),T(e,n.rootNode,n,e=>a.push(e.index),r),a.length&&(a.forAll(e=>n.updateElevationChanged(e)),this._setCameraDirty()),a}removeAllGeometryObbs(){this._index!=null&&this._index.removeAllGeometryObbs()}getRenderMbs(e){return this._viewportQueries==null?null:this._viewportQueries.calculateServiceMbsInRenderSRElevationAdjusted(e)}_elevationInfoChanged(e){this._index!=null&&(this._index.updateElevationInfo(e,this.isMeshPyramid||this.isGraphics3D),this._setCameraDirty())}restartNodeLoading(){this._restartNodeLoading=!0,this.cancelNodeLoading(),this._evaluateRunning()}schedule(e,t){let n=this._idleQueue.push(e,t);return this._evaluateRunning(),n}reschedule(e,t){let n=this._idleQueue.unshift(e,t);return this._evaluateRunning(),n}get _isIntegratedMesh(){return this.layer.type===`integrated-mesh`}get unloadedMemoryEstimate(){return this._index==null||!this.layerView.contentVisible?0:this._index.unloadedMemoryEstimate*this._lodDropFactor}async _loadNodeData(e,t){return e.index<0?this._clientNodeLoader.loadNodeData(e.id,t):this._nodeLoader.loadNodeData(e,t)}async _loadAttributes(e,t,n){return(e.index<0?this._clientNodeLoader:this._nodeLoader).loadAttributes(e,t,n)}get indexDepth(){return this._index==null?0:this._index.maxLevel}set disableMemCache(e){this._disableMemCache=!this.layerView.loadCachedGPUData||!this.layerView.addCachedGPUData||e}runTask(e,t){return this.layerView.contentVisible?!this.layerView.visible||this._index==null?-1/0:(this._processWithErrorLogging(e,t),this._index.maxPriority):(this._updateViewData(),this._evaluateRunning(),-1/0)}_processWithErrorLogging(e,t){try{this._process(e,t)}catch(e){this._errorCount<50?o.getLogger(this).error(`Error during processing: ${e} at ${e.stack}`):this._errorCount===50&&o.getLogger(this).error(`Too many errors for this layer. Further errors will not be displayed.`),this._errorCount++}}_process(e,t){this._restartNodeLoading&&this._startNodeLoading(),this._nodeLoader!=null&&this._index!=null&&(this._updateViewData(),this._invisibleDirty&&this._removeInvisibleNodes(e)&&(this._invisibleDirty=!1),this._isIntegratedMesh&&(e.enabled=!1),e.run(()=>this._processIndex(e)),this._updateFeatureLOD(),e.run(()=>this._processCache(e)),this._isIntegratedMesh&&(e.enabled=!0),e.run(()=>this._processNodes(e,t)),this._idleQueue.runTask(e),e.run(()=>this._prefetchIndex()),t.numIndexLoading+=this._index.indexLoading,t.numNodesLoading+=this._downloadingCount,e.run(()=>this._lodHandling.lodGlobalHandling(e)),this._evaluateRunning())}_processIndex(e){if(this._index==null)return!1;if(this._index.dirty){this._newLoadingNodes.clear(),this._index.update(Array.from(this._loadingNodes.keys()),e,e=>this.updateNodeModificationStatus(e)),this._disableMemCache||(this._newLoadingNodes.pushArray(this._index.updates.add.data,this._index.updates.add.length),this._newLoadingNodes.pushAll(this._index.updates.missing));let t=this._index.featureEstimate.leavesReached;!this._index.isLoading&&t!==this._get(`leavesReached`)&&this._set(`leavesReached`,t)}return this._index.load()}_prefetchIndex(){return this._index==null||this._loadingNodes.size>0||this._index.updates.add.length>0?!1:this._index.prefetch()}_updateFeatureLOD(){if(!this.useMaximumNumberOfFeatures||this._index==null||this._viewportQueries==null)return;let e=!this._index.isLoading,t=this.featureTarget*this._baseLOD,n=this._index.featureEstimate;if(n.estimate=n.estimate||t/2,this._index.indexMissing>500){if(this._featureLOD<=F)return;this._featureLOD/=1.5,this._stableFeatureLOD=!1}else if(e&&n.estimate<t){if(n.leavesReached||this._featureLOD>=P||this._stableFeatureLOD)return;let e=Math.min(10,Math.max(t/n.estimate,1.001));this._featureLOD*=e;let r=this._lod,i=this._index.checkFeatureTarget(t,r);i!==r&&(this._featureLOD=i/this._baseLOD,this._stableFeatureLOD=!0)}else if(n.estimate>t*1.2||e&&n.estimate>t){if(this._featureLOD<=F)return;this._featureLOD/=1+(n.estimate/t-1)*.25,this._stableFeatureLOD=!1}else return;this._featureLOD=Math.min(P,Math.max(F,this._featureLOD)),this._viewportQueries.updateScreenSpaceErrorBias(this._lod),this._index.requestUpdate()}_processCache(e){let t=this._index;if(t==null)return!1;for(;this._newLoadingNodes.length>0&&!e.done;){let n=this._newLoadingNodes.pop();for(let r=t.getParent(n);r!=null&&!this.layerView.isNodeLoaded(r.index);r=t.getParent(r.index)){if(!this._disableMemCache&&!t.useNodeAsHole(r.index)){e.enabled&&e.madeProgress();break}if(this._enableFromGPUCache(r,0)){e.madeProgress();break}}}return e.hasProgressed}_processNodes(e,t){if(this._index==null)return!1;let n=(this._isIdle?100:2)-this._loadingNodes.size,r=this._index.updates;for(r.cancel.forEach(this._cancelNode,this),r.cancel=[];r.remove.length>0&&!e.done;)this.layerView.removeNode(r.remove.pop()),e.madeProgress();for(;r.update.length>0&&!e.done;){let t=this._index.getNode(r.update.pop());t!=null&&(this._updateLoadedNode(t),e.madeProgress())}for(;r.add.length>0&&!e.done&&n>0;){--n;let i=this._index.getNode(r.add.back());if(i==null||i.cacheState!==2&&!this._hasNodeLoadToken(t))break;r.add.pop(),this._loadNode(i),e.madeProgress()}return e.hasProgressed}_cancelAllNodes(){this._loadingNodes.forEach(e=>e.abort()),this._loadingNodes.clear(),this._updatingNodes.forEach(e=>e.abort()),this._updatingNodes.clear()}_cancelNode(e){let t=this._loadingNodes.get(e);t&&(t.abort(),this._loadingNodes.delete(e))}_hasNodeLoadToken(e){return!this._isIdle&&e.numNodesLoading+this._loadingNodes.size>=2?!1:this.index==null||!this.dataRequester.isFull(this._index.urlPrefix)}_evaluateRunning(){let e=!1,t=0;if(this.layerView){if(!this.layerView.contentVisible)e=this._cameraDirty,t=+!e;else{let n=(this._index?.indexMissing??0)+(this._index?.updates.add.length??0)*3+this._loadingNodes.size*2;e=!!(n>0||this._updatingNodes.size>0||this._restartNodeLoading||this._cameraDirty||this._idleQueue.updating||this._lodHandling&&this._lodHandling.requiresLODGlobalHandling||this._index!=null&&this._index.isPrefetching),n===0&&(this._progressMaxNumNodes=1),this._progressMaxNumNodes=Math.max(n,this._progressMaxNumNodes),t=1-n/this._progressMaxNumNodes}this.running=e,this.updatingProgress=t}}_updateViewData(){if(!this._cameraDirty||this._index==null||this._viewportQueries==null)return;let e=this.layerView.view,{contentCamera:t,fixedContentCamera:n}=e.state;this._viewportQueries.updateCamera(t,!n||this.isGraphics3D),this._viewportQueries.setPointOfInterest(e.pointsOfInterest.focus.renderLocation),this._viewportQueries.updateScreenSpaceErrorBias(this._lod),this._index.invalidateVisibilityCache(),this._index.requestUpdate(),this._stableFeatureLOD=!1,this._invisibleDirty=!0,this._cameraDirty=!1,this.notifyChange(`rootNodeVisible`)}_getProgressiveLoadFactor(){return this.layerView.view.quality<1?1:this.layerView.progressiveLoadFactor}get _lod(){return this._featureLOD*this._baseLOD}get _baseLOD(){let e=this.layerView.lodFactor;return this.fixedFeatureTarget?1:(e>0?e:1)*this.layerView.view.quality}get _lodDropFactor(){return this.fixedFeatureTarget?1:(Math.min(this.layerView.view.quality,.5)-A)/(.5-A)}isGeometryVisible(e){return!!this._index?.isGeometryVisible(e.index)}updateVisibility(e){this._index?.invalidateNodeVisibilityCache(e)}invalidateGeometryVisibility(e){this._index?.invalidateGeometryVisibility(e)}invalidateVisibilityObbs(){this._index?.invalidateVisibilityObbs()}modificationsChanged(){this._index?.imModificationsChanged(!!this.layerView.hasModifications),this._invisibleDirty=!0}_shouldLoadNode(e){return!(!this._lodHandling.shouldLoadNode(e)||this._shouldDropNode(e)||this._index==null||!this._index.isGeometryVisible(e.index))}_shouldDropNode(e){if(this._viewportQueries==null)return!1;let t=this._lodDropFactor;return t>=1||!this._lodHandling.hasNoVisibleChildren(e)?!1:Math.abs(this._viewportQueries.calcCameraDistanceToCenterAndUpdateMinmax(e))-this._viewportQueries.minCenterDistance>(this._viewportQueries.maxCenterDistance-this._viewportQueries.minCenterDistance)*t}_startNodeLoading(){this._restartNodeLoading=!1;let e=this._index;if(this._updatesDisabled||e==null||this._viewportQueries==null)return;this._updateViewData(),this._requiredAttributesDirty&&=(this._requiredAttributes=this._getRequiredAttributes(),!1);let t={textureEncodings:this.layerView.supportedTextureEncodings,textureUsageMask:this.layerView.rendererTextureUsage,loadFeatureData:this.useMaximumNumberOfFeatures};this._nodeLoader=new S(this.layer,this.dataRequester,o.getLogger(this),this._defaultGeometrySchema,this._requiredAttributes,t),e.requestUpdate(),this._lodHandling.startNodeLoading((e,t)=>this._removeNodes(e,t,1),e,{maxLodLevel:this._viewportQueries.maxLodLevel}),this._evaluateRunning()}isNodeLoading(){return this._nodeLoader!=null&&this._index!=null}cancelNodeLoading(){this.isNodeLoading()&&(this.indexRequester.cancelAll(),this.dataRequester.cancelAll(),this._idleQueue.cancelAll(),this._cancelAllNodes(),this._nodeLoader=null,this._evaluateRunning())}_removeInvisibleNodes(e){let t=this._index;if(t==null||this._viewportQueries==null)return!1;L.clear(),this.layerView.getLoadedNodeIndices(L);let n=this._viewportQueries.maxCenterDistance===0,r=n?()=>!1:e=>this._shouldDropNode(e);return L.filterInPlace(e=>{let n=t.getNode(e);return n==null||!t.isGeometryVisible(e)||r(n)}),L.length>0&&this._lodHandling.setLodGlobalDirty(),this._removeNodes(L,e,0),n&&this._lodDropFactor<1?!1:L.length===0||(L.clear(),!1)}markNodeToRemove(e){L.push(e)}removeMarkedNodes(){this._removeNodes(L,M,0)}_removeNodes(e,t,n){if(!(e.length===0||t.done))for(this._index!=null&&this._index.requestUpdate();e.length>0&&!t.done;){let r=e.pop(),i=this._index;n===1&&this.layerView.nodeFadeoutEnabled&&i!=null&&i.isGeometryVisible(r)?this.layerView.fadeNode(r,1,!0):this.layerView.removeNode(r),t.madeProgress()}}_needsUpdate(e){if(e.resources.isEmpty||this._updatingNodes.has(e.index))return!1;let t=this.layerView.getLoadedAttributes(e.index);return t!=null&&t!==this._requiredAttributes}async _updateLoadedNode(e){let t=new AbortController;this._updatingNodes.set(e.index,t),this._evaluateRunning();try{let n=z(this.layerView.getLoadedAttributes(e.index),this._requiredAttributes)?this.layerView.getAttributeData(e.index):await this._loadAttributes(e,this._requiredAttributes,t.signal);await this.schedule(()=>this.layerView.updateAttributes(e.index,{loadedAttributes:this._requiredAttributes,attributeData:n},t.signal),t.signal)}catch(n){if(!u(n))return this.layerView.updateAttributes(e.index,{loadedAttributes:this._requiredAttributes,attributeData:{}},t.signal)}this._updatingNodes.delete(e.index),this._evaluateRunning()}_loadNode(e){if(this._loadingNodes.has(e.index)){o.getLogger(this).error(`already loading node `+e.index);return}let t=new AbortController;this._loadingNodes.set(e.index,t),this._evaluateRunning(),this._loadAndAddNode(e,t.signal).then(n=>{n&&this._index!=null&&this._loadingNodes.get(e.index)===t&&(this._loadingNodes.delete(e.index),this._index.requestUpdate())}).catch(()=>{}).finally(()=>{this._loadingNodes.get(e.index)===t&&this._loadingNodes.delete(e.index),this._evaluateRunning()})}_loadAndAddNode(e,t){return e.cacheState===1?this._loadUncached(e,t).then(()=>!1):this._loadCached(e,t).then(t=>!t&&(e.cacheState=1,!0)).catch(t=>!u(t)&&(e.cacheState=1,!0))}_enableFromGPUCache(e,t){if(this._disableMemCache||this._index==null)return!1;let n=this._loadCachedGPUData(e);return n?(this.layerView.addCachedGPUData(e,n,t),this._nodeAdded(),!0):!1}_loadCachedGPUData(e){let t=this.layerView.loadCachedGPUData(e.index);return t?.attributeInfo!=null&&z(t.attributeInfo.loadedAttributes,this._requiredAttributes)?t:(this.layerView.deleteCachedGPUData(t),null)}_nodeAdded(){this._index!=null&&this._index.requestUpdate(),this._lodHandling.setLodGlobalDirty(),this._evaluateRunning()}updateLoadStatus(e,t){this._index?.updateChildrenLoaded(e,t?1:-1)}async _loadCached(e,t){if(this._enableFromGPUCache(e,1))return!0;let n=this.layerView;if(this.disableIDBCache||!n.loadCachedNodeData||!n.addCachedNodeData)return!1;let r=e.index>=0?(t,n)=>this._nodeLoader.loadTextures(e,t,n):t=>this._clientNodeLoader.loadTextures(e,t),i=await this.schedule(()=>n.loadCachedNodeData(e,t,r),t);if(i==null)return!1;let a=this._requiredAttributes,o=await this.reschedule(()=>this._loadAttributes(e,a,t),t);return await this.reschedule(()=>n.addCachedNodeData(e,i,{loadedAttributes:a,attributeData:o},t),t),this._nodeAdded(),!0}_loadUncached(e,t){return this._downloadingCount++,this._loadNodeData(e,t).then(n=>this.schedule(()=>this.layerView.addNode(e,n,t),t)).finally(()=>this._downloadingCount--).then(()=>{this._nodeAdded(),e.cacheState=2}).catch(t=>{if(!u(t))throw o.getLogger(this).error(`#loadNodeData()`,this.layer,`Failed to load node '${e.id}'`,t),e.failed=!0,this._index?.requestUpdate(),t})}_updateIdleState(e){e!==this._isIdle&&(this._isIdle=e,this._evaluateRunning())}get test(){}notifyLODUpdate(){this._lodHandling.setLodGlobalDirty(),this._evaluateRunning(),this._index!=null&&this._index.requestUpdate()}geometryFilterChanged(e){this._index?.layerFilterChanged(e),this._setCameraDirty()}};e([n({readOnly:!0})],I.prototype,`isMeshPyramid`,null),e([n({readOnly:!0})],I.prototype,`isGraphics3D`,null),e([n({readOnly:!0})],I.prototype,`useMaximumNumberOfFeatures`,null),e([n({readOnly:!0})],I.prototype,`indexRequester`,null),e([n({readOnly:!0})],I.prototype,`dataRequester`,null),e([n({readOnly:!0})],I.prototype,`crsVertex`,null),e([n({readOnly:!0})],I.prototype,`crsIndex`,null),e([n()],I.prototype,`featureTarget`,void 0),e([n()],I.prototype,`fixedFeatureTarget`,void 0),e([n()],I.prototype,`layerView`,void 0),e([n()],I.prototype,`layer`,null),e([n()],I.prototype,`_updatingHandles`,void 0),e([n()],I.prototype,`updating`,null),e([n()],I.prototype,`running`,void 0),e([n()],I.prototype,`updatingProgress`,void 0),e([n({readOnly:!0})],I.prototype,`leavesReached`,void 0),e([n({constructOnly:!0})],I.prototype,`worker`,void 0),e([n({readOnly:!0})],I.prototype,`rootNodeVisible`,null),I=e([r(`esri.layers.graphics.controllers.I3SOnDemandController`)],I);const L=new c({deallocator:null});let R;function z(e,t){return e!=null&&e.length===t.length&&e.every(e=>B(t,e.name)>=0)}function B(e,t){let n=t.toLowerCase();for(let t=0;t<e.length;t++)if(e[t].name.toLowerCase()===n)return t;return-1}const V=h(),H=I;export{H as default};
2
+ import{__decorate as e}from"tslib";import t from"../../../core/Accessor.js";import{property as n,subclass as r}from"../../../core/accessorSupport/decorators.js";import{runUntracked as i}from"../../../core/accessorSupport/tracking.js";import has from"../../../core/has.js";import{exactEquals as a}from"../../../core/libs/gl-matrix-2/math/vec3.js";import o from"../../../core/Logger.js";import{destroyMaybe as s}from"../../../core/maybe.js";import c from"../../../core/PooledArray.js";import{EsriPromiseMixin as l}from"../../../core/Promise.js";import{isAbortError as u}from"../../../core/promiseUtils.js";import{watch as d,sync as f,initial as p}from"../../../core/reactiveUtils.js";import{UpdatingHandles as m}from"../../../core/support/UpdatingHandles.js";import{create as h,fromValues as g}from"../../../geometry/support/aaBoundingRect.js";import{I3SClientNodeLoader as _}from"../../../views/3d/layers/i3s/I3SClientNodeLoader.js";import{I3SDataRequester as v}from"../../../views/3d/layers/i3s/I3SDataRequester.js";import{addCallback as y}from"../../../views/3d/layers/i3s/I3SFrameTask.js";import{I3SIndex as b}from"../../../views/3d/layers/i3s/I3SIndex.js";import x from"../../../views/3d/layers/i3s/I3SLodHandling.js";import S from"../../../views/3d/layers/i3s/I3SNodeLoader.js";import{getVertexCrs as C,getIndexCrs as w,findIntersectingNodes as T}from"../../../views/3d/layers/i3s/I3SUtil.js";import E from"../../../views/3d/layers/i3s/I3SViewportQueries.js";import{groundNavigationConstants as D}from"../../../views/3d/state/utils/groundNavigationUtils.js";import{projectElevationUpdateExtent as O}from"../../../views/3d/support/elevationUpdateExtentUtils.js";import{toBoundingRect as k}from"../../../views/3d/support/extentUtils.js";import{minQuality as A}from"../../../views/3d/support/MemoryController.js";import{PromiseQueue as j}from"../../../views/support/PromiseQueue.js";import{noBudget as M}from"../../../views/support/Scheduler.js";const N=1e4,P=1e-4;let F=class extends l(t){get isMeshPyramid(){return this.layer.profile===`mesh-pyramids`||this.layer.store?.lodType===`MeshPyramid`}get isGraphics3D(){return this.layer.profile===`points`}get useMaximumNumberOfFeatures(){return!this.isMeshPyramid&&(this.layer.priority==null||this.layer.priority===`High`)}get indexRequester(){return new v(this.layer.customParameters,this.layer.apiKey)}get dataRequester(){return new v(this.layer.customParameters,this.layer.apiKey)}get crsVertex(){return C(this.layer)}get crsIndex(){return w(this.layer)}get layer(){return this.layerView.layer}get updating(){return this.running||this._updatingHandles.updating}get rootNodeVisible(){return i(()=>{if(this._index){let e=this._index.rootNode;if(e)return this._updateViewData(),this._index.isNodeVisible(e.index)}return!0})}get index(){return this._index}get requiredAttributes(){return this._requiredAttributes}constructor(e){super(e),this.featureTarget=5e4,this.fixedFeatureTarget=!1,this._updatingHandles=new m,this.running=!0,this.updatingProgress=1,this.leavesReached=!1,this.worker=null,this._featureLOD=1,this._stableFeatureLOD=!1,this._isIdle=!1,this._cameraDirty=!0,this._invisibleDirty=!1,this._newLoadingNodes=new c({deallocator:null}),this._modificationsNodeFilteringArray=new c,this._downloadingCount=0,this._loadingNodes=new Map,this._updatingNodes=new Map,this._progressMaxNumNodes=1,this._requiredAttributes=[],this._requiredAttributesDirty=!0,this._updatesDisabled=!1,this.disableIDBCache=!1,this._disableMemCache=!1,this._restartNodeLoading=!1,this._fields=null,this._attributeStorageInfo=null,this._idleQueue=new j,this._elevationUpdateNodes=new c({deallocator:null}),this._errorCount=0}initialize(){let{layerView:e,layer:t}=this;this._disableMemCache=!e.loadCachedGPUData||!e.addCachedGPUData,this._lodHandling=new x(e),this._defaultGeometrySchema=t.store.defaultGeometrySchema,this.disableIDBCache=!!has(`disable-feature:idb-cache`),`fields`in t&&(this._fields=t.fields,this._attributeStorageInfo=t.attributeStorageInfo),this.addResolvingPromise(Promise.all([t.indexInfo,t.when(),e.when()]).then(([n])=>{if(this.destroyed||!e||e.destroyed||!n)return;let{view:r,clientGeometry:i}=e;if(this._setClippingArea(r.clippingArea),this.addHandles([this._updatingHandles.add(()=>r?.pointsOfInterest?.focus?.renderLocation,e=>this._pointOfInterestChanged(e),{initial:!0,equals:a}),d(()=>r.quality,()=>this._setCameraDirty(),f),this._updatingHandles.add(()=>r.state.mode===2,t=>{this._updateIdleState(t),t&&(this._index?.resetFailedNodes(),e.contentVisible||this._updateViewData())},p),this._updatingHandles.add(()=>e.contentVisible,e=>{e&&this._index?.invalidateAllElevationRanges(),this.restartNodeLoading()},p),y(e.view.resourceController.scheduler,this),this._updatingHandles.add(()=>[this.featureTarget,this.fixedFeatureTarget],()=>{this._setCameraDirty(),this._stableFeatureLOD=!1}),this._updatingHandles.add(()=>r.state?.contentCamera,()=>this._setCameraDirty()),this._updatingHandles.add(()=>r.navigation.mode?.type,e=>{this._setCameraDirty(),this._index&&(this._index.isGroundNavigationMode=e===`ground`)}),this._updatingHandles.add(()=>t.elevationInfo,e=>this._elevationInfoChanged(e),f),this._updatingHandles.add(()=>e.lodFactor,()=>this._setCameraDirty()),this._updatingHandles.add(()=>e.availableFields,()=>this._requiredFieldsChange()),this._updatingHandles.add(()=>e.holeFilling,e=>this._index!=null&&(this._index.holeFilling=e))]),this._viewportQueries=new E(this.crsIndex,r.renderCoordsHelper,r.state.contentCamera,!r.state.fixedContentCamera||this.isGraphics3D,this._clippingArea,this.isMeshPyramid?r.groundView:r.elevationProvider,r.state.isGlobal,this.layer.elevationInfo,{progressiveLoadFactor:this._getProgressiveLoadFactor(),screenspaceErrorBias:this._lod,angleDependentLoD:this._lod<.5}),this._clientNodeLoader=new _(this.layer.uid,{indexSR:this.crsIndex,vertexSR:this.crsVertex,renderSR:r.renderCoordsHelper.spatialReference},r.resourceController.memoryController,this.worker),this._index=new b(t,r.navigation.mode.type===`ground`,D.i3sNodeDownwardCheckDistanceInMeters/r.renderCoordsHelper.unitInMeters,n,this.indexRequester,this._clientNodeLoader,this._viewportQueries,o.getLogger(this),e.holeFilling,t=>e.isNodeLoaded(t),t=>e.isNodeReloading(t),e=>this._shouldLoadNode(e),e=>this._enableFromGPUCache(e,1),e=>this._needsUpdate(e),t=>e.computeVisibilityObb?.(t)??null,e?.computeNodeFiltering?t=>e.computeNodeFiltering(t):void 0),this._index.updateElevationInfo(this.layer.elevationInfo,this.isMeshPyramid||this.isGraphics3D),this._index.imModificationsChanged(!!e.hasModifications),this._index.layerFilterChanged(!!e.hasGeometryFilter),i!=null){for(let e of i)this._addMesh(e.mesh,e.oid);this.addHandles(i.on(`change`,e=>{for(let t of e.removed)this._removeMesh(t.oid);for(let t of e.added)this._addMesh(t.mesh,t.oid)}))}this._startNodeLoading()}))}updateNodeModificationStatus(e){let t=this._index,n=this.layerView;t!=null&&n?.updateNodeModificationStatus&&(this._modificationsNodeFilteringArray.clear(),e.forAll(e=>{let n=t.getNode(e);n!=null&&this._modificationsNodeFilteringArray.push(n)}),n.updateNodeModificationStatus(this._modificationsNodeFilteringArray),this._invisibleDirty=!0)}destroy(){this.cancelNodeLoading(),this._updatingHandles.destroy(),this._nodeLoader=null,I.prune(),this._newLoadingNodes.prune(),this._modificationsNodeFilteringArray.prune(),this._elevationUpdateNodes.prune(),L!=null&&(L.hide(),L=null),this._index=null,this._lodHandling=s(this._lodHandling),this._nodeLoader=null,this._clientNodeLoader=null,this._viewportQueries=null,this._set(`worker`,null)}get viewportQueries(){return this._viewportQueries}_getRequiredAttributes(){if(this._attributeStorageInfo==null||!this._fields||!this.layerView.availableFields)return[];let e=this._attributeStorageInfo,t=this._fields,n=this.layer.objectIdField;return this.layerView.availableFields.map(n=>{let r=z(e,n),i=z(t,n);return r>=0&&i>=0?{index:r,name:t[i].name,field:t[i],attributeStorageInfo:e[r]}:null}).filter(e=>e!=null&&e.name!==n)}_requiredFieldsChange(){let e=this._getRequiredAttributes();R(this._requiredAttributes,e)||(this._requiredAttributes=e,this._requiredAttributesDirty=!1,this.restartNodeLoading())}requestUpdate(){this._requiredAttributesDirty=!0,this.restartNodeLoading()}_setClippingArea(e){let t=h();this._clippingArea=k(e,t,this.layerView.view.renderSpatialReference)?t:null}_pointOfInterestChanged(e){this._viewportQueries!=null&&(this._viewportQueries.setPointOfInterest(e),this._index!=null&&this._index.requestUpdate())}updateClippingArea(e){this._setClippingArea(e),this._viewportQueries!=null&&this._index!=null&&(this._viewportQueries.updateClippingArea(this._clippingArea),this._index.invalidateVisibilityCache()),this._setCameraDirty()}_setCameraDirty(){this._cameraDirty=!0,this._lodHandling.setLodGlobalDirty(),this._evaluateRunning()}_addMesh(e,t){if(this._index==null)return;let n=this._clientNodeLoader.createMeshNodeInfo(e,t),r=this._index.addClientNodeToIndex(n.id,n.mbs);this._clientNodeLoader.addMeshNode(r,n),this._evaluateRunning(),this.notifyChange(`rootNodeVisible`)}_removeMesh(e){let t=this._clientNodeLoader.getMeshNodeIndex(e);if(t!=null){if(this._index!=null)this._index.removeClientNodeFromIndex(t,(e,t)=>{this.layerView.removeNode(t),this._clientNodeLoader.removeNode(e),this.layerView.deleteCachedNodeData&&e!=null&&this.layerView.deleteCachedNodeData(e),this.layerView.deleteCachedGPUData?.(this.layerView.loadCachedGPUData?.(t))},(e,t,n)=>{this._clientNodeLoader.updateNodeIndex(e,t,n),this.layerView.updateNodeIndex&&this.layerView.updateNodeIndex(t,n)}),this.notifyChange(`rootNodeVisible`);else throw Error(`delayed removal of client side i3s node geometry not supported yet.`)}}updateElevationChanged(e,t){let n=this._index,r=this._viewportQueries;if(n?.rootNode==null||t==null||r==null)return null;let i=r.elevationIntersectionSpatialReference;i.equals(t)||(O(e,t,B,i)||g(-1/0,-1/0,1/0,1/0,B),e=B);let a=this._elevationUpdateNodes;return a.clear(),T(e,n.rootNode,n,e=>a.push(e.index),r),a.length&&(a.forAll(e=>n.updateElevationChanged(e)),this._setCameraDirty()),a}removeAllGeometryObbs(){this._index!=null&&this._index.removeAllGeometryObbs()}getRenderMbs(e){return this._viewportQueries==null?null:this._viewportQueries.calculateServiceMbsInRenderSRElevationAdjusted(e)}_elevationInfoChanged(e){this._index!=null&&(this._index.updateElevationInfo(e,this.isMeshPyramid||this.isGraphics3D),this._setCameraDirty())}restartNodeLoading(){this._restartNodeLoading=!0,this.cancelNodeLoading(),this._evaluateRunning()}schedule(e,t){let n=this._idleQueue.push(e,t);return this._evaluateRunning(),n}reschedule(e,t){let n=this._idleQueue.unshift(e,t);return this._evaluateRunning(),n}get _isIntegratedMesh(){return this.layer.type===`integrated-mesh`}get unloadedMemoryEstimate(){return this._index==null||!this.layerView.contentVisible?0:this._index.unloadedMemoryEstimate*this._lodDropFactor}async _loadNodeData(e,t){return e.index<0?this._clientNodeLoader.loadNodeData(e.id,t):this._nodeLoader.loadNodeData(e,t)}async _loadAttributes(e,t,n){return(e.index<0?this._clientNodeLoader:this._nodeLoader).loadAttributes(e,t,n)}get indexDepth(){return this._index==null?0:this._index.maxLevel}set disableMemCache(e){this._disableMemCache=!this.layerView.loadCachedGPUData||!this.layerView.addCachedGPUData||e}runTask(e,t){return this.layerView.contentVisible?!this.layerView.visible||this._index==null?-1/0:(this._processWithErrorLogging(e,t),this._index.maxPriority):(this._updateViewData(),this._evaluateRunning(),-1/0)}_processWithErrorLogging(e,t){try{this._process(e,t)}catch(e){this._errorCount<50?o.getLogger(this).error(`Error during processing: ${e} at ${e.stack}`):this._errorCount===50&&o.getLogger(this).error(`Too many errors for this layer. Further errors will not be displayed.`),this._errorCount++}}_process(e,t){this._restartNodeLoading&&this._startNodeLoading(),this._nodeLoader!=null&&this._index!=null&&(this._updateViewData(),this._invisibleDirty&&this._removeInvisibleNodes(e)&&(this._invisibleDirty=!1),this._isIntegratedMesh&&(e.enabled=!1),e.run(()=>this._processIndex(e)),this._updateFeatureLOD(),e.run(()=>this._processCache(e)),this._isIntegratedMesh&&(e.enabled=!0),e.run(()=>this._processNodes(e,t)),this._idleQueue.runTask(e),e.run(()=>this._prefetchIndex()),t.numIndexLoading+=this._index.indexLoading,t.numNodesLoading+=this._downloadingCount,e.run(()=>this._lodHandling.lodGlobalHandling(e)),this._evaluateRunning())}_processIndex(e){if(this._index==null)return!1;if(this._index.dirty){this._newLoadingNodes.clear(),this._index.update(Array.from(this._loadingNodes.keys()),e,e=>this.updateNodeModificationStatus(e)),this._disableMemCache||(this._newLoadingNodes.pushArray(this._index.updates.add.data,this._index.updates.add.length),this._newLoadingNodes.pushAll(this._index.updates.missing));let t=this._index.featureEstimate.leavesReached;!this._index.isLoading&&t!==this._get(`leavesReached`)&&this._set(`leavesReached`,t)}return this._index.load()}_prefetchIndex(){return this._index==null||this._loadingNodes.size>0||this._index.updates.add.length>0?!1:this._index.prefetch()}_updateFeatureLOD(){if(!this.useMaximumNumberOfFeatures||this._index==null||this._viewportQueries==null)return;let e=!this._index.isLoading,t=this.featureTarget*this._baseLOD,n=this._index.featureEstimate;if(n.estimate=n.estimate||t/2,this._index.indexMissing>500){if(this._featureLOD<=P)return;this._featureLOD/=1.5,this._stableFeatureLOD=!1}else if(e&&n.estimate<t){if(n.leavesReached||this._featureLOD>=N||this._stableFeatureLOD)return;let e=Math.min(10,Math.max(t/n.estimate,1.001));this._featureLOD*=e;let r=this._lod,i=this._index.checkFeatureTarget(t,r);i!==r&&(this._featureLOD=i/this._baseLOD,this._stableFeatureLOD=!0)}else if(n.estimate>t*1.2||e&&n.estimate>t){if(this._featureLOD<=P)return;this._featureLOD/=1+(n.estimate/t-1)*.25,this._stableFeatureLOD=!1}else return;this._featureLOD=Math.min(N,Math.max(P,this._featureLOD)),this._viewportQueries.updateScreenSpaceErrorBias(this._lod),this._index.requestUpdate()}_processCache(e){let t=this._index;if(t==null)return!1;for(;this._newLoadingNodes.length>0&&!e.done;){let n=this._newLoadingNodes.pop();for(let r=t.getParent(n);r!=null&&!this.layerView.isNodeLoaded(r.index);r=t.getParent(r.index)){if(!this._disableMemCache&&!t.useNodeAsHole(r.index)){e.enabled&&e.madeProgress();break}if(this._enableFromGPUCache(r,0)){e.madeProgress();break}}}return e.hasProgressed}_processNodes(e,t){if(this._index==null)return!1;let n=(this._isIdle?100:2)-this._loadingNodes.size,r=this._index.updates;for(r.cancel.forEach(this._cancelNode,this),r.cancel=[];r.remove.length>0&&!e.done;)this.layerView.removeNode(r.remove.pop()),e.madeProgress();for(;r.update.length>0&&!e.done;){let t=this._index.getNode(r.update.pop());t!=null&&(this._updateLoadedNode(t),e.madeProgress())}for(;r.add.length>0&&!e.done&&n>0;){--n;let i=this._index.getNode(r.add.back());if(i==null||i.cacheState!==2&&!this._hasNodeLoadToken(t))break;r.add.pop(),this._loadNode(i),e.madeProgress()}return e.hasProgressed}_cancelAllNodes(){this._loadingNodes.forEach(e=>e.abort()),this._loadingNodes.clear(),this._updatingNodes.forEach(e=>e.abort()),this._updatingNodes.clear()}_cancelNode(e){let t=this._loadingNodes.get(e);t&&(t.abort(),this._loadingNodes.delete(e))}_hasNodeLoadToken(e){return!this._isIdle&&e.numNodesLoading+this._loadingNodes.size>=2?!1:this.index==null||!this.dataRequester.isFull(this._index.urlPrefix)}_evaluateRunning(){let e=!1,t=0;if(this.layerView){if(!this.layerView.contentVisible)e=this._cameraDirty,t=+!e;else{let n=(this._index?.indexMissing??0)+(this._index?.updates.add.length??0)*3+this._loadingNodes.size*2;e=!!(n>0||this._updatingNodes.size>0||this._restartNodeLoading||this._cameraDirty||this._idleQueue.updating||this._lodHandling&&this._lodHandling.requiresLODGlobalHandling||this._index!=null&&this._index.isPrefetching),n===0&&(this._progressMaxNumNodes=1),this._progressMaxNumNodes=Math.max(n,this._progressMaxNumNodes),t=1-n/this._progressMaxNumNodes}this.running=e,this.updatingProgress=t}}_updateViewData(){if(!this._cameraDirty||this._index==null||this._viewportQueries==null)return;let e=this.layerView.view,{contentCamera:t,fixedContentCamera:n}=e.state;this._viewportQueries.updateCamera(t,!n||this.isGraphics3D),this._viewportQueries.setPointOfInterest(e.pointsOfInterest.focus.renderLocation),this._viewportQueries.updateScreenSpaceErrorBias(this._lod),this._index.invalidateVisibilityCache(),this._index.requestUpdate(),this._stableFeatureLOD=!1,this._invisibleDirty=!0,this._cameraDirty=!1,this.notifyChange(`rootNodeVisible`)}_getProgressiveLoadFactor(){return this.layerView.view.quality<1?1:this.layerView.progressiveLoadFactor}get _lod(){return this._featureLOD*this._baseLOD}get _baseLOD(){let e=this.layerView.lodFactor;return this.fixedFeatureTarget?1:(e>0?e:1)*this.layerView.view.quality}get _lodDropFactor(){return this.fixedFeatureTarget?1:(Math.min(this.layerView.view.quality,.5)-A)/(.5-A)}isGeometryVisible(e){return!!this._index?.isGeometryVisible(e.index)}updateVisibility(e){this._index?.invalidateNodeVisibilityCache(e)}invalidateGeometryVisibility(e){this._index?.invalidateGeometryVisibility(e)}invalidateVisibilityObbs(){this._index?.invalidateVisibilityObbs()}modificationsChanged(){this._index?.imModificationsChanged(!!this.layerView.hasModifications),this._invisibleDirty=!0}_shouldLoadNode(e){return!(!this._lodHandling.shouldLoadNode(e)||this._shouldDropNode(e)||this._index==null||!this._index.isGeometryVisible(e.index))}_shouldDropNode(e){if(this._viewportQueries==null)return!1;let t=this._lodDropFactor;return t>=1||!this._lodHandling.hasNoVisibleChildren(e)?!1:Math.abs(this._viewportQueries.calcCameraDistanceToCenterAndUpdateMinmax(e))-this._viewportQueries.minCenterDistance>(this._viewportQueries.maxCenterDistance-this._viewportQueries.minCenterDistance)*t}_startNodeLoading(){this._restartNodeLoading=!1;let e=this._index;if(this._updatesDisabled||e==null||this._viewportQueries==null)return;this._updateViewData(),this._requiredAttributesDirty&&=(this._requiredAttributes=this._getRequiredAttributes(),!1);let t={textureEncodings:this.layerView.supportedTextureEncodings,textureUsageMask:this.layerView.rendererTextureUsage,loadFeatureData:this.useMaximumNumberOfFeatures};this._nodeLoader=new S(this.layer,this.dataRequester,o.getLogger(this),this._defaultGeometrySchema,this._requiredAttributes,t),e.requestUpdate(),this._lodHandling.startNodeLoading((e,t)=>this._removeNodes(e,t,1),e,{maxLodLevel:this._viewportQueries.maxLodLevel}),this._evaluateRunning()}isNodeLoading(){return this._nodeLoader!=null&&this._index!=null}cancelNodeLoading(){this.isNodeLoading()&&(this.indexRequester.cancelAll(),this.dataRequester.cancelAll(),this._idleQueue.cancelAll(),this._cancelAllNodes(),this._nodeLoader=null,this._evaluateRunning())}_removeInvisibleNodes(e){let t=this._index;if(t==null||this._viewportQueries==null)return!1;I.clear(),this.layerView.getLoadedNodeIndices(I);let n=this._viewportQueries.maxCenterDistance===0,r=n?()=>!1:e=>this._shouldDropNode(e);return I.filterInPlace(e=>{let n=t.getNode(e);return n==null||!t.isGeometryVisible(e)||r(n)}),I.length>0&&this._lodHandling.setLodGlobalDirty(),this._removeNodes(I,e,0),n&&this._lodDropFactor<1?!1:I.length===0||(I.clear(),!1)}markNodeToRemove(e){I.push(e)}removeMarkedNodes(){this._removeNodes(I,M,0)}_removeNodes(e,t,n){if(!(e.length===0||t.done))for(this._index!=null&&this._index.requestUpdate();e.length>0&&!t.done;){let r=e.pop(),i=this._index;n===1&&this.layerView.nodeFadeoutEnabled&&i!=null&&i.isGeometryVisible(r)?this.layerView.fadeNode(r,1,!0):this.layerView.removeNode(r),t.madeProgress()}}_needsUpdate(e){if(e.resources.isEmpty||this._updatingNodes.has(e.index))return!1;let t=this.layerView.getLoadedAttributes(e.index);return t!=null&&t!==this._requiredAttributes}async _updateLoadedNode(e){let t=new AbortController,n=this._requiredAttributes;this._updatingNodes.set(e.index,t),this._evaluateRunning();try{let r=R(this.layerView.getLoadedAttributes(e.index),n)?this.layerView.getAttributeData(e.index):await this._loadAttributes(e,n,t.signal);await this.schedule(()=>this.layerView.updateAttributes(e.index,{loadedAttributes:n,attributeData:r},t.signal),t.signal)}catch(r){if(!u(r)&&!t.signal.aborted)try{await this.layerView.updateAttributes(e.index,{loadedAttributes:n,attributeData:{}},t.signal)}catch(e){u(e)||o.getLogger(this).error(`#updateLoadedNode()`,this.layer,e)}}finally{this._updatingNodes.get(e.index)===t&&(this._updatingNodes.delete(e.index),this._evaluateRunning())}}_loadNode(e){if(this._loadingNodes.has(e.index)){o.getLogger(this).error(`already loading node `+e.index);return}let t=new AbortController;this._loadingNodes.set(e.index,t),this._evaluateRunning(),this._loadAndAddNode(e,t.signal).then(n=>{n&&this._index!=null&&this._loadingNodes.get(e.index)===t&&(this._loadingNodes.delete(e.index),this._index.requestUpdate())}).catch(()=>{}).finally(()=>{this._loadingNodes.get(e.index)===t&&this._loadingNodes.delete(e.index),this._evaluateRunning()})}_loadAndAddNode(e,t){return e.cacheState===1?this._loadUncached(e,t).then(()=>!1):this._loadCached(e,t).then(t=>!t&&(e.cacheState=1,!0)).catch(t=>!u(t)&&(e.cacheState=1,!0))}_enableFromGPUCache(e,t){if(this._disableMemCache||this._index==null)return!1;let n=this._loadCachedGPUData(e);return n?(this.layerView.addCachedGPUData(e,n,t),this._nodeAdded(),!0):!1}_loadCachedGPUData(e){let t=this.layerView.loadCachedGPUData(e.index);return t?.attributeInfo!=null&&R(t.attributeInfo.loadedAttributes,this._requiredAttributes)?t:(this.layerView.deleteCachedGPUData(t),null)}_nodeAdded(){this._index!=null&&this._index.requestUpdate(),this._lodHandling.setLodGlobalDirty(),this._evaluateRunning()}updateLoadStatus(e,t){this._index?.updateChildrenLoaded(e,t?1:-1)}async _loadCached(e,t){if(this._enableFromGPUCache(e,1))return!0;let n=this.layerView;if(this.disableIDBCache||!n.loadCachedNodeData||!n.addCachedNodeData)return!1;let r=e.index>=0?(t,n)=>this._nodeLoader.loadTextures(e,t,n):t=>this._clientNodeLoader.loadTextures(e,t),i=await this.schedule(()=>n.loadCachedNodeData(e,t,r),t);if(i==null)return!1;let a=this._requiredAttributes,o=await this.reschedule(()=>this._loadAttributes(e,a,t),t);return await this.reschedule(()=>n.addCachedNodeData(e,i,{loadedAttributes:a,attributeData:o},t),t),this._nodeAdded(),!0}_loadUncached(e,t){return this._downloadingCount++,this._loadNodeData(e,t).then(n=>this.schedule(()=>this.layerView.addNode(e,n,t),t)).finally(()=>this._downloadingCount--).then(()=>{this._nodeAdded(),e.cacheState=2}).catch(t=>{if(!u(t))throw o.getLogger(this).error(`#loadNodeData()`,this.layer,`Failed to load node '${e.id}'`,t),e.failed=!0,this._index?.requestUpdate(),t})}_updateIdleState(e){e!==this._isIdle&&(this._isIdle=e,this._evaluateRunning())}get test(){}notifyLODUpdate(){this._lodHandling.setLodGlobalDirty(),this._evaluateRunning(),this._index!=null&&this._index.requestUpdate()}geometryFilterChanged(e){this._index?.layerFilterChanged(e),this._setCameraDirty()}};e([n({readOnly:!0})],F.prototype,`isMeshPyramid`,null),e([n({readOnly:!0})],F.prototype,`isGraphics3D`,null),e([n({readOnly:!0})],F.prototype,`useMaximumNumberOfFeatures`,null),e([n({readOnly:!0})],F.prototype,`indexRequester`,null),e([n({readOnly:!0})],F.prototype,`dataRequester`,null),e([n({readOnly:!0})],F.prototype,`crsVertex`,null),e([n({readOnly:!0})],F.prototype,`crsIndex`,null),e([n()],F.prototype,`featureTarget`,void 0),e([n()],F.prototype,`fixedFeatureTarget`,void 0),e([n()],F.prototype,`layerView`,void 0),e([n()],F.prototype,`layer`,null),e([n()],F.prototype,`_updatingHandles`,void 0),e([n()],F.prototype,`updating`,null),e([n()],F.prototype,`running`,void 0),e([n()],F.prototype,`updatingProgress`,void 0),e([n({readOnly:!0})],F.prototype,`leavesReached`,void 0),e([n({constructOnly:!0})],F.prototype,`worker`,void 0),e([n({readOnly:!0})],F.prototype,`rootNodeVisible`,null),F=e([r(`esri.layers.graphics.controllers.I3SOnDemandController`)],F);const I=new c({deallocator:null});let L;function R(e,t){return e!=null&&e.length===t.length&&e.every(e=>z(t,e.name)>=0)}function z(e,t){let n=t.toLowerCase();for(let t=0;t<e.length;t++)if(e[t].name.toLowerCase()===n)return t;return-1}const B=h(),V=F;export{V as default};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
- import{DateTime as e}from"luxon";import{insertSortedStableTopN as t}from"../../../core/arrayUtils.js";import{importLazily as n}from"../../../core/importUtils.js";import{clone as r}from"../../../core/lang.js";import i from"../../../geometry/SpatialReference.js";import{polygonCentroid as a,extentCentroid as o}from"../../../geometry/support/centroid.js";import{closestPointOnCurve as s}from"../../../geometry/support/curves/closestPointOnCurve.js";import{getEndpoint as c,isCoordinate as l,cloneCurve as u}from"../../../geometry/support/curves/curveUtils.js";import{getPolygonExtent as d,getGeometryExtent as f,expandExtent as p}from"../../../geometry/support/extentUtils.js";import{toQuantizationTransform as m}from"../../../geometry/support/quantizationUtils.js";import{isValid as h,equals as g}from"../../../geometry/support/spatialReferenceUtils.js";import _ from"../../../rest/support/AutoIntervalBinParameters.js";import v from"../../../rest/support/DateBinParameters.js";import{unitsDict as y}from"../../../rest/support/DateBinUtils.js";import b from"../../../rest/support/FixedBoundariesBinParameters.js";import x from"../../../rest/support/FixedIntervalBinParameters.js";import{isNullCountSupported as S,calculateStringStatistics as C,calculateStatistics as w,processSummaryStatisticsResult as T,calculateUniqueValuesCount as E,createUVResult as D,calculateClassBreaks as O,resolveCBResult as k,calculateHistogram as A,calculatePercentile as j,binIndex as M,getBinParams as N,getAttributeComparator as P}from"../../../statistics/utils.js";import{utc as F}from"../../../time/constants.js";import{isDateField as I,isDateOnlyField as L,isTimestampOffsetField as R,isStringField as z,isTimeOnlyField as B}from"../../support/fieldUtils.js";import V from"./AttributesBuilder.js";import{getGeometry as H,transformCentroid as U}from"./geometryUtils.js";import{project as W}from"./projectionSupport.js";import{getDateInNumber as G}from"./queryUtils.js";import{SnappingCandidateEdge as K,SnappingCandidateVertex as q}from"./SnappingCandidate.js";const J=n(()=>import(`../../../geometry/operators/json/convexHullOperator.js`));class Y{constructor(e,t,n){this.items=e,this.query=t,this.geometryType=n.geometryType,this.hasZ=!!t.returnZ&&n.hasZ,this.hasM=!!t.returnM&&n.hasM,this.fieldsIndex=n.fieldsIndex,this.spatialReference=n.spatialReference,this.featureAdapter=n.featureAdapter,this.featureIdInfo=n.featureIdInfo}get size(){return this.items.length}createQueryResponseForCount(){let e=new V(this.query,this.featureAdapter,this.fieldsIndex);if(!this.query.outStatistics)return e.countDistinctValues(this.items);let{groupByFieldsForStatistics:t,having:n,outStatistics:r}=this.query;if(!t?.length)return 1;let i=new Map,a=new Map,o=new Set;for(let s of r){let{statisticType:r}=s,c=r===`exceedslimit`?void 0:s.onStatisticField;if(!a.has(c)){let n=[];for(let r of t){let t=this._getAttributeValues(e,r,this.items,i);n.push(t)}a.set(c,this._calculateUniqueValues(n,this.items,e.returnDistinctValues))}let l=a.get(c);for(let t in l){let{data:r,items:i}=l[t],a=r.join(`,`);(!n||e.validateItems(i,n))&&o.add(a)}}return o.size}async createQueryResponse(){let e;if(e=this.query.outStatistics?this.query.outStatistics.some(e=>e.statisticType===`exceedslimit`)?this._createExceedsLimitQueryResponse():await this._createStatisticsQueryResponse(this.query,this.items):this._createFeatureQueryResponse(this.query),this.query.returnQueryGeometry){let t=this.query.geometry;e.queryGeometry={spatialReference:this.query.outSR,...h(this.query.outSR)&&!g(t.spatialReference,this.query.outSR)?W(t,t.spatialReference,this.query.outSR):t}}return e}createSnappingResponse(e,t,n){let r=this.featureAdapter,{point:i}=e,a=typeof e.distance==`number`?e.distance:e.distance.x,o=typeof e.distance==`number`?e.distance:e.distance.y;function d(e,t){let n=(e-i.x)/a,r=(t-i.y)/o;return n*n+r*r}let f={candidates:[]},p=this.geometryType===`esriGeometryPolygon`,m=this.geometryType===`esriGeometryPolyline`||this.geometryType===`esriGeometryPoint`,h=this._getPointCreator(t,this.spatialReference,n),g=new Q(null,0),_=new Q(null,0),v={x:0,y:0,z:0};for(let e of this.items){let t=r.getObjectId(e),n=r.getGeometryWithCurves?.(e);if(n!=null){b(n,t);continue}let i=r.getGeometry(e);i!=null&&y(i,t)}return f.candidates.sort((e,t)=>e.distance-t.distance),f;function y(t,n){let{coords:r,stride:a}=t,o=t.isPoint?ee:t.lengths;if(g.coords=r,_.coords=r,e.returnEdge){let e=0;for(let t=0;t<o.length;t++){let r=o[t],s=e;for(let t=0;t<r;t++,e+=a){if(!p&&t===r-1||(g.coordsIndex=e,_.coordsIndex=t===r-1?s:e+a,!Z(v,i,g,_)))continue;let o=d(v.x,v.y);o<=1&&f.candidates.push(new K(n,h(v),Math.sqrt(o),h(g),h(_)))}}}if(e.vertexMode===`all`){let e=0;for(let t=0;t<o.length;t++){let r=o[t],i=e,s=_;s.coordsIndex=i;for(let t=0;t<r;t++,e+=a){if(g.coordsIndex=e,p&&t===r-1&&g.x===s.x&&g.y===s.y)continue;let i=d(g.x,g.y);i<=1&&f.candidates.push(new q(n,h(g),Math.sqrt(i)))}}}else if(m&&e.vertexMode===`ends`){let e=0,t=[];for(let n=0;n<o.length;n++){t.push(e);let r=o[n];e+=r*a,r>1&&t.push(e-a)}for(let e of t){g.coordsIndex=e;let t=d(g.x,g.y);t<=1&&f.candidates.push(new q(n,h(g),Math.sqrt(t)))}}}function b(t,n){let{candidates:r}=f,a={x:0,y:0,z:0};if(e.returnEdge){let e=[i.x,i.y],o=new Q(e,0),f=new Q(e,0);for(let{segments:i}of t.parts)for(let{start:t,curve:p}of i){let{curvePoint:i}=s(t,p,e),m=d(...i);if(m>1)continue;[a.x,a.y]=i,o.coords=t,f.coords=c(p);let g=l(p)?null:u(p);r.push(new K(n,h(a),Math.sqrt(m),h(o),h(f),!1,g))}}function o(e){a.x=t.vertexXY[e*2],a.y=t.vertexXY[e*2+1];let i=d(a.x,a.y);i>1||(a.z=t.vertexZ?.[e]??0,r.push(new q(n,h(a),Math.sqrt(i))))}if(e.vertexMode===`all`){let{vertexCount:e}=t;for(let t=0;t<e;++t)o(t)}else if(e.vertexMode===`ends`)switch(t.type){case`point`:o(0);break;case`polyline`:for(let e=0;e<t.partCount;++e){let n=t.partOffsets[e],r=t.partOffsets[e+1]-1;o(n),r!==n&&o(r)}}}}_getPointCreator(e,t,n){let r=n!=null&&!g(t,n)?e=>W(e,t,n):e=>e,{hasZ:i}=this;return i&&e?({x:e,y:t,z:n})=>r({x:e,y:t,z:n}):({x:e,y:t})=>r({x:e,y:t,z:0})}async createSummaryStatisticsResponse(e){let{field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,minValue:o,maxValue:s,scale:c,timeZone:l,outStatisticTypes:u}=e,d=this.fieldsIndex.get(t),f=I(d)||L(d)||R(d),p=await this._getDataValues({field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,scale:c,timeZone:l},this.items),m=S({normalizationType:i,normalizationField:r,minValue:o,maxValue:s}),h={value:.5,fieldType:d?.type},g=z(d)?C({values:p,supportsNullCount:m,percentileParams:h,outStatisticTypes:u}):w({values:p,minValue:o,maxValue:s,useSampleStdDev:!i,supportsNullCount:m,percentileParams:h,outStatisticTypes:u});return T(g,u,f)}async createUniqueValuesResponse(e){let{field:t,valueExpression:n,domains:r,returnAllCodedValues:i,scale:a,timeZone:o}=e,s=await this._getDataValues({field:t,field2:e.field2,field3:e.field3,fieldDelimiter:e.fieldDelimiter,valueExpression:n,scale:a,timeZone:o},this.items,!1),c=E(s);return D(c,r,i,e.fieldDelimiter)}async createClassBreaksResponse(e){let{field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,classificationMethod:o,standardDeviationInterval:s,minValue:c,maxValue:l,numClasses:u,scale:d,timeZone:f}=e,p=await this._getDataValues({field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,scale:d,timeZone:f},this.items),m=O(p,{field:t,normalizationField:r,normalizationType:i,normalizationTotal:a,classificationMethod:o,standardDeviationInterval:s,minValue:c,maxValue:l,numClasses:u});return k(m,o)}async createHistogramResponse(e){let{field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,classificationMethod:o,standardDeviationInterval:s,minValue:c,maxValue:l,numBins:u,scale:d,timeZone:f}=e,p=await this._getDataValues({field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,scale:d,timeZone:f},this.items);return A(p,{field:t,normalizationField:r,normalizationType:i,normalizationTotal:a,classificationMethod:o,standardDeviationInterval:s,minValue:c,maxValue:l,numBins:u})}_sortFeatures(e,t,n){if(e.length>1&&t?.length)for(let r of t.slice().reverse()){let{compare:t,fieldOrExpression:i,fieldInfo:a}=$(r,this.fieldsIndex);e.sort((e,r)=>t(n(e,i,a),n(r,i,a)))}}_topNFeatures(e,n,r,i){if(e.length>1&&n?.length){let a=n.map(e=>{let{compare:t,fieldOrExpression:n,fieldInfo:r}=$(e,this.fieldsIndex);return(e,a)=>t(i(e,n,r),i(a,n,r))}).reduceRight((e,t)=>(n,r)=>{let i=t(n,r);return i!==0&&!Number.isNaN(i)?i:e(n,r)}),o=[];for(let n of e)t(o,n,r,a);return o}return e.slice(0,r)}_createFeatureQueryResponse(e){let{items:t,geometryType:n,hasM:r,hasZ:i,featureIdInfo:a,spatialReference:o}=this,{outFields:s,outSR:c,quantizationParameters:l,resultRecordCount:u,resultOffset:d,returnZ:f,returnM:p}=e,h=u!=null&&t.length>(d||0)+u,g=s&&(s.includes(`*`)?[...this.fieldsIndex.fields]:s.map(e=>this.fieldsIndex.get(e)));return{exceededTransferLimit:h,features:this._createFeatures(e,t),fields:g,geometryType:n,hasM:r&&p,hasZ:i&&f,objectIdFieldName:a.type===`object-id`?a.fieldName:null,spatialReference:c||o,transform:l&&m(l)||null}}_createFeatures(e,t){let n=new V(e,this.featureAdapter,this.fieldsIndex),{hasM:r,hasZ:i}=this,{orderByFields:a,quantizationParameters:o,returnGeometry:s,returnCentroid:c,maxAllowableOffset:l,resultOffset:u,resultRecordCount:d,returnZ:f=!1,returnM:p=!1}=e,h=i&&f,g=r&&p,_,v=u||0,y=d==null?null:v+d;y!=null&&y<=5e3&&y<t.length?_=this._topNFeatures(t,a,y,(e,t,r)=>n.getFieldValue(e,t,r)):(_=[...t],this._sortFeatures(_,a,(e,t,r)=>n.getFieldValue(e,t,r))),(v>0||y!=null)&&(_=_.slice(v,y??void 0));let b=[],x=0;if(!this.geometryType||!s&&!c)for(let e of _){let t=n.getAttributes(e);t&&(b[x++]=this._addFeatureJSONMetadata(e,{attributes:t}))}else{let e=m(o)??void 0,t=this.geometryType===`esriGeometryPolygon`||this.geometryType===`esriGeometryPolyline`;if(s&&!c)for(let r of _){let i=this.featureAdapter.getGeometry(r),a=this._addFeatureJSONMetadata(r,{attributes:n.getAttributes(r),geometry:H(this.geometryType,i,l,e,h,g)});t&&i&&!a.geometry&&(a.centroid=U(this,this.featureAdapter.getCentroid(r,this),e)),b[x++]=a}else if(!s&&c)for(let t of _)b[x++]=this._addFeatureJSONMetadata(t,{attributes:n.getAttributes(t),centroid:U(this,this.featureAdapter.getCentroid(t,this),e)});else for(let t of _)b[x++]=this._addFeatureJSONMetadata(t,{attributes:n.getAttributes(t),centroid:U(this,this.featureAdapter.getCentroid(t,this),e),geometry:H(this.geometryType,this.featureAdapter.getGeometry(t),l,e,h,g)})}return b}_addFeatureJSONMetadata(e,t){let n=this.featureAdapter.getMetadata?.(e);return n!==void 0&&(t.metadata=n),t}_createExceedsLimitQueryResponse(){let e=!1,t=1/0,n=1/0,r=1/0;for(let e of this.query.outStatistics??[])if(e.statisticType===`exceedslimit`){t=e.maxPointCount==null?1/0:e.maxPointCount,n=e.maxRecordCount==null?1/0:e.maxRecordCount,r=e.maxVertexCount==null?1/0:e.maxVertexCount;break}return e=this.geometryType===`esriGeometryPoint`?this.items.length>t:this.items.length>n||this.items.reduce((e,t)=>e+(this.featureAdapter.getGeometry(t)?.size??0),0)>r,{fields:[{name:`exceedslimit`,type:`esriFieldTypeInteger`,alias:`exceedslimit`,sqlType:`sqlTypeInteger`,domain:null,defaultValue:null}],features:[{attributes:{exceedslimit:Number(e)}}]}}async _createStatisticsQueryResponse(e,t,n={attributes:{}}){let r=[],i=new Map,a=new Map,o=new Map,s=new Map,c=new V(e,this.featureAdapter,this.fieldsIndex),l=e.outStatistics,{groupByFieldsForStatistics:u,having:d,orderByFields:f,resultRecordCount:p}=e,m=u?.length,h=!!m,g=h?u[0]:null,_=h&&!this.fieldsIndex.get(g);for(let f of l??[]){let{outStatisticFieldName:l,statisticType:p}=f,v=f,y=p===`exceedslimit`?void 0:f.onStatisticField,b=p===`percentile_disc`||p===`percentile_cont`,x=p===`EnvelopeAggregate`||p===`CentroidAggregate`||p===`ConvexHullAggregate`,S=h&&m===1&&(y===g||_)&&p===`count`;if(h){if(!o.has(y)){let e=[];for(let n of u){let r=this._getAttributeValues(c,n,t,i);e.push(r)}o.set(y,this._calculateUniqueValues(e,t,!x&&c.returnDistinctValues))}let n=o.get(y);if(!n)continue;let r=Object.keys(n);for(let a of r){let{count:r,data:o,items:f,itemPositions:p}=n[a],m=o.join(`,`);if(!d||c.validateItems(f,d)){let n=s.get(m)||{attributes:{}};if(e.returnAggIds&&(n.aggregateIds=f.map(e=>this.featureAdapter.getObjectId(e)).filter(e=>e!=null)),x){n.aggregateGeometries||={};let{aggregateGeometries:e,outStatisticFieldName:t}=await this._getAggregateGeometry(v,f);n.aggregateGeometries[t]=e}else{let e=null;if(S)e=r;else{let n=this._getAttributeValues(c,y,t,i),r=p.map(e=>n[e]);e=b&&`statisticParameters`in v?this._getPercentileValue(v,r):this._getStatisticValue(v,r,null,c.returnDistinctValues)}n.attributes[l]=e}let a=0;u.forEach((e,t)=>n.attributes[this.fieldsIndex.get(e)?e:`EXPR_${++a}`]=o[t]),s.set(m,n)}}}else if(x){n.aggregateGeometries||={};let{aggregateGeometries:e,outStatisticFieldName:r}=await this._getAggregateGeometry(v,t);n.aggregateGeometries[r]=e}else{let e=this._getAttributeValues(c,y,t,i);n.attributes[l]=b&&`statisticParameters`in v?this._getPercentileValue(v,e):this._getStatisticValue(v,e,a,c.returnDistinctValues)}let C=(p===`min`||p===`max`)&&(z(this.fieldsIndex.get(y))||this._isAnyDateField(y))?this.fieldsIndex.get(y)?.type:null;r.push({name:l,alias:l,type:C||`esriFieldTypeDouble`})}let v=h?Array.from(s.values()):[n];return this._sortFeatures(v,f,(e,t)=>e.attributes[t]),p&&(v.length=Math.min(p,v.length)),{fields:r,features:v}}_isAnyDateField(e){let t=this.fieldsIndex.get(e);return I(t)||L(t)||R(t)||B(t)}async _getAggregateGeometry(e,t){let{statisticType:n,outStatisticFieldName:r}=e,{featureAdapter:i,spatialReference:s,geometryType:c}=this,l=t.map(e=>H(c,i.getGeometry(e))),u={aggregateGeometries:null,outStatisticFieldName:null},{convexHullExecuteMany:f}=await J.getImportPromise(),[p]=f(l,{merge:!0});if(p&&p.rings[0].length<=3&&(p=null),n===`EnvelopeAggregate`)u.aggregateGeometries={...p?d(p):X(l),spatialReference:s},u.outStatisticFieldName=r||`extent`;else if(n===`CentroidAggregate`){let[e,t]=p?a(p):o(X(l));u.aggregateGeometries={x:e,y:t,spatialReference:s},u.outStatisticFieldName=r||`centroid`}else n===`ConvexHullAggregate`&&(u.aggregateGeometries=p&&{...p,spatialReference:s},u.outStatisticFieldName=r||`convexHull`);return u}_getStatisticValue(e,t,n,r){let{onStatisticField:i,statisticType:a}=e,o=null;return o=n?.has(i)?n.get(i):z(this.fieldsIndex.get(i))||this._isAnyDateField(i)?C({values:t,returnDistinct:r}):w({values:r?[...new Set(t)]:t,minValue:null,maxValue:null,useSampleStdDev:!0}),n&&n.set(i,o),o[a===`var`?`variance`:a]}_getPercentileValue(e,t){let{onStatisticField:n,statisticParameters:r,statisticType:i}=e,{value:a,orderBy:o}=r,s={value:a,orderBy:o,fieldType:this.fieldsIndex.get(n)?.type,isDiscrete:i===`percentile_disc`};return j(t,s)}_getAttributeValues(e,t,n,r){if(r.has(t))return r.get(t);let i=this.fieldsIndex.get(t),a=n.map(n=>e.getFieldValue(n,t,i));return r.set(t,a),a}_calculateUniqueValues(e,t,n){let r={},i=t.length;for(let a=0;a<i;a++){let i=t[a],o=Array.from(e,e=>e[a]),s=o.join(`,`);r[s]==null?r[s]={count:1,data:o,items:[i],itemPositions:[a]}:(n||r[s].count++,r[s].items.push(i),r[s].itemPositions.push(a))}return r}async _getDataValues(e,t,n=!0){let a=new V(this.query,this.featureAdapter,this.fieldsIndex),{valueExpression:o,scale:s,timeZone:c}=e,l=i.fromJSON(this.query.outSR||this.spatialReference);return o?a.getExpressionValues(t,o,{viewingMode:`map`,scale:s,spatialReference:l},{geometryType:this.geometryType,hasZ:this.hasZ,hasM:this.hasM},c):a.getDataValues(t,r(e),n)}_calculateHistogramBins(e,t,n){if(t.min==null&&t.max==null)return[];let r=t.intervals,i=t.min??0,a=t.max??0,o=r.map(([e,t])=>({minValue:e,maxValue:t,count:0,items:[]}));for(let t=0;t<e.length;t++){let s=e[t],c=n[t];if(s!=null&&s>=i&&s<=a){let e=M(r,s);e>-1&&(o[e].count++,o[e].items.push(c))}}return o}async createQueryBinsResponse(e){let t=e.bin?.splitBy;if(!t)return this._createBinsResponse(e);let{value:n,outAlias:r,valueType:i}=t,a=[],o=[{name:r??n,alias:r??n,type:i??`esriFieldTypeString`},{name:`bin`,alias:`bin`,type:`esriFieldTypeInteger`}],s=new V(e,this.featureAdapter,this.fieldsIndex),c=new Map,l=[...this.items];this._sortFeatures(l,[n],(e,t,n)=>s.getFieldValue(e,t,n));let u=this._getAttributeValues(s,n,l,c),d=this._calculateUniqueValues([u],l,s.returnDistinctValues);for(let t in d){let{items:i}=d[t],s=await this._createBinsResponse(e,i);if(a.push(...s.features.map(e=>({...e,attributes:{...e.attributes,[r??n]:t}}))),s.fields)for(let e of s.fields)o.some(t=>t.name===e.name)||o.push(e)}return{fields:o,features:a}}async _createBinsResponse(e,t){let n=e.bin;switch(t??=this.items,n.type){case`autoIntervalBin`:return this._createAutoIntervalBinsResponse(_.fromJSON(n),e,t);case`dateBin`:return this._createDateBinsResponse(v.fromJSON(n),e,t);case`fixedBoundariesBin`:return this._createFixedBoundariesBinsResponse(b.fromJSON(n),e,t);case`fixedIntervalBin`:return this._createFixedIntervalBinsResponse(x.fromJSON(n),e,t)}}async _createAutoIntervalBinsResponse(e,t,n){let{field:r,normalizationField:i,numBins:a,normalizationType:o,normalizationTotal:s,start:c,end:l}=e,u=await this._getDataValues({field:e.field||e.expression,normalizationField:e.normalizationField,normalizationType:e.normalizationType,normalizationTotal:e.normalizationTotal,timeZone:t.outTimeReference?.ianaTimeZone},n),d=N(u,{field:r,normalizationField:i,normalizationType:o,normalizationTotal:s,numBins:a,minValue:G(o?e.normalizationMinValue:c,!1),maxValue:G(o?e.normalizationMaxValue:l,!1)}),f=this._calculateHistogramBins(u,d,n);return this._createFeaturesFromHistogramBins(f,t)}async _createDateBinsResponse(t,n,r){let{field:i,interval:a,start:o,end:s,snapToData:c,returnFullIntervalBin:l,offset:u,firstDayOfWeek:d}=t,f=a.unit,p=await this._getDataValues({field:i||t.expression,timeZone:n.outTimeReference?.ianaTimeZone},r),m=B(this.fieldsIndex.get(i)),h=y.toJSON(f),g=p.filter(Boolean).sort((e,t)=>e-t),_=o==null?g[0]:G(o,m),v=s==null?g[g.length-1]:G(s,m),b=[];if(_!=null&&v!=null){let t={zone:n.outTimeReference?.ianaTimeZone??F},r={[u?.unit?y.toJSON(u.unit):`milliseconds`]:u?.value||0},i=e.fromMillis(_,t).minus(r),o=e.fromMillis(v,t).minus(r),s=typeof d==`number`&&d>=1&&d<=7?d:7,f=(e,t)=>{let n=(e.weekday-t+7)%7;return e.minus({days:n}).startOf(`day`)},p=(e,t)=>f(e,t).plus({days:7});if(c===`last`){let e=h===`week`?p(o,s):o;for(;e>i;){let t=e.minus({[h]:a.value});if(t<i){b.unshift([l?t.plus(r).toMillis():i.plus(r).toMillis(),e.plus(r).toMillis()]);break}b.unshift([t.plus(r).toMillis(),e.plus(r).toMillis()]),e=t}}else{let e=c===`first`?i:h===`week`?f(i,s):i.startOf(h);for(;e<=o;){let t=e.plus({[h]:a.value});if(t>o){b.push([e.plus(r).toMillis(),l?t.plus(r).toMillis():o.plus(r).toMillis()]);break}b.push([e.plus(r).toMillis(),t.plus(r).toMillis()]),e=t}}}let x=this._calculateHistogramBins(p,{intervals:b,min:_,max:v},r);return this._createFeaturesFromHistogramBins(x,n)}async _createFixedBoundariesBinsResponse(e,t,n){let{field:r}=e,i=await this._getDataValues({field:r||e.expression,timeZone:t.outTimeReference?.ianaTimeZone},n),a=B(this.fieldsIndex.get(r)),o=e.boundaries.map(e=>G(e,a)).sort((e,t)=>e-t),s=[];for(let e=0;e<o.length-1;e++)s.push([o[e],o[e+1]]);let c={intervals:s,min:o.at(0),max:o.at(-1)},l=this._calculateHistogramBins(i,c,n);return this._createFeaturesFromHistogramBins(l,t)}async _createFixedIntervalBinsResponse(e,t,n){let{field:r,interval:i,normalizationType:a,start:o,end:s}=e,c=await this._getDataValues({field:r||e.expression,normalizationField:e.normalizationField,normalizationType:a,normalizationTotal:e.normalizationTotal,timeZone:t.outTimeReference?.ianaTimeZone},n),l=B(this.fieldsIndex.get(r)),u=N(c,{field:r,classificationMethod:`defined-interval`,definedInterval:i,minValue:G(a?e.normalizationMinValue:o,l),maxValue:G(a?e.normalizationMaxValue:s,l)},!0),d=this._calculateHistogramBins(c,u,n);return this._createFeaturesFromHistogramBins(d,t)}async _createFeaturesFromHistogramBins(t,n){let{upperBoundaryAlias:r,lowerBoundaryAlias:i}=n,a=i||`lowerBoundary`,o=r||`upperBoundary`,s=[],c=[{name:a,alias:a,type:`esriFieldTypeDouble`},{name:o,alias:o,type:`esriFieldTypeDouble`}],l=n.bin?.stackBy?.value,u=n.bin?.stackBy?.outAlias;l&&c.push({name:`bin`,alias:`bin`,type:`esriFieldTypeInteger`},{name:u??l,alias:u??l,type:`esriFieldTypeString`});let d=0,f=n.bin.type===`dateBin`,p=n.outTimeReference?.ianaTimeZone;for(let r of t){let{minValue:t,maxValue:i,items:m}=r,h={attributes:{}};h.attributes[a]=f&&p&&t!=null?e.fromMillis(t,{zone:p}).toISO():t,n.bin.hideUpperBound||(h.attributes[o]=f&&p&&i!=null?e.fromMillis(i,{zone:p}).toISO():i),n.returnAggIds&&(h.aggregateIds=m.map(e=>this.featureAdapter.getObjectId(e)).filter(e=>e!=null));let g;if(l?(g=await this._createStatisticsQueryResponse({...n,groupByFieldsForStatistics:[l],orderByFields:[l]},m),h.attributes.bin=++d,n.bin.jsonStyle===`flat`?s.push(...g.features.map(({attributes:{EXPR_1:e,...t},...n})=>({...n,attributes:u??e?{...t,[u??e]:e,...h.attributes}:{...t,...h.attributes}}))):(h.stackedAttributes=g.features.map(({attributes:{EXPR_1:e,...t}})=>u??e?{...t,[u??e]:e}:t),s.push(h))):(n.bin?.splitBy&&(h.attributes.bin=++d),g=await this._createStatisticsQueryResponse(n,m,h),s.push(h)),g.fields)for(let e of g.fields)c.some(t=>t.name===e.name)||c.push(e)}return n.binOrder===`desc`&&s.reverse(),{fields:c,features:s}}}function X(e){let t=f(e[0]);for(let n of e.slice(1))p(t,f(n));return t}function Z(e,t,n,r){let i=r.x-n.x,a=r.y-n.y,o=t.x-n.x,s=t.y-n.y,c=i*i+a*a;if(c===0)return!1;let l=o*i+s*a,u=Math.min(1,Math.max(0,l/c));return e.x=n.x+i*u,e.y=n.y+a*u,!0}class Q{constructor(e,t){this.coords=e,this.coordsIndex=t}get x(){return this.coords[this.coordsIndex]}get y(){return this.coords[this.coordsIndex+1]}get z(){return this.coords[this.coordsIndex+2]}}const ee=[1];function $(e,t){let n=e.split(` `),r=n[0],i=t.get(r),a=n[1]?n[1].toLowerCase()===`desc`:!1;return{compare:P(i?.type,a,`case-insensitive`),fieldOrExpression:r,fieldInfo:i}}export{Y as QueryEngineResult};
2
+ import{DateTime as e}from"luxon";import{insertSortedStableTopN as t}from"../../../core/arrayUtils.js";import{importLazily as n}from"../../../core/importUtils.js";import{clone as r}from"../../../core/lang.js";import i from"../../../geometry/SpatialReference.js";import{polygonCentroid as a,extentCentroid as o}from"../../../geometry/support/centroid.js";import{closestPointOnCurve as s}from"../../../geometry/support/curves/closestPointOnCurve.js";import{getEndpoint as c,isCoordinate as l,cloneCurve as u}from"../../../geometry/support/curves/curveUtils.js";import{getPolygonExtent as d,getGeometryExtent as f,expandExtent as p}from"../../../geometry/support/extentUtils.js";import{toQuantizationTransform as m}from"../../../geometry/support/quantizationUtils.js";import{isValid as h,equals as g}from"../../../geometry/support/spatialReferenceUtils.js";import _ from"../../../rest/support/AutoIntervalBinParameters.js";import v from"../../../rest/support/DateBinParameters.js";import{unitsDict as y}from"../../../rest/support/DateBinUtils.js";import b from"../../../rest/support/FixedBoundariesBinParameters.js";import x from"../../../rest/support/FixedIntervalBinParameters.js";import{isNullCountSupported as S,calculateStringStatistics as C,calculateStatistics as w,processSummaryStatisticsResult as T,calculateUniqueValuesCount as E,createUVResult as D,calculateClassBreaks as O,resolveCBResult as k,calculateHistogram as A,calculatePercentile as j,binIndex as M,getBinParams as N,getAttributeComparator as P}from"../../../statistics/utils.js";import{utc as F}from"../../../time/constants.js";import{isDateField as I,isDateOnlyField as L,isTimestampOffsetField as R,isStringField as z,isTimeOnlyField as B}from"../../support/fieldUtils.js";import V from"./AttributesBuilder.js";import{getGeometry as H,transformCentroid as U}from"./geometryUtils.js";import{project as W}from"./projectionSupport.js";import{getDateInNumber as G}from"./queryUtils.js";import{SnappingCandidateEdge as K,SnappingCandidateVertex as q}from"./SnappingCandidate.js";const J=n(()=>import(`../../../geometry/operators/json/convexHullOperator.js`));class Y{constructor(e,t,n){this.items=e,this.query=t,this.geometryType=n.geometryType,this.hasZ=!!t.returnZ&&n.hasZ,this.hasM=!!t.returnM&&n.hasM,this.fieldsIndex=n.fieldsIndex,this.spatialReference=n.spatialReference,this.featureAdapter=n.featureAdapter,this.featureIdInfo=n.featureIdInfo}get size(){return this.items.length}createQueryResponseForCount(){let e=new V(this.query,this.featureAdapter,this.fieldsIndex);if(!this.query.outStatistics)return e.countDistinctValues(this.items);let{groupByFieldsForStatistics:t,having:n,outStatistics:r}=this.query;if(!t?.length)return 1;let i=new Map,a=new Map,o=new Set;for(let s of r){let{statisticType:r}=s,c=r===`exceedslimit`?void 0:s.onStatisticField;if(!a.has(c)){let n=[];for(let r of t){let t=this._getAttributeValues(e,r,this.items,i);n.push(t)}a.set(c,this._calculateUniqueValues(n,this.items,e.returnDistinctValues))}let l=a.get(c);for(let t in l){let{data:r,items:i}=l[t],a=r.join(`,`);(!n||e.validateItems(i,n))&&o.add(a)}}return o.size}async createQueryResponse(){let e;if(e=this.query.outStatistics?this.query.outStatistics.some(e=>e.statisticType===`exceedslimit`)?this._createExceedsLimitQueryResponse():await this._createStatisticsQueryResponse(this.query,this.items):this._createFeatureQueryResponse(this.query),this.query.returnQueryGeometry){let t=this.query.geometry;e.queryGeometry={spatialReference:this.query.outSR,...h(this.query.outSR)&&!g(t.spatialReference,this.query.outSR)?W(t,t.spatialReference,this.query.outSR):t}}return e}createSnappingResponse(e,t,n){let r=this.featureAdapter,{point:i}=e,a=typeof e.distance==`number`?e.distance:e.distance.x,o=typeof e.distance==`number`?e.distance:e.distance.y;function d(e,t){let n=(e-i.x)/a,r=(t-i.y)/o;return n*n+r*r}let f={candidates:[]},p=this.geometryType===`esriGeometryPolygon`,m=this.geometryType===`esriGeometryPolyline`||this.geometryType===`esriGeometryPoint`,h=this._getPointCreator(t,this.spatialReference,n),g=new Q(null,0),_=new Q(null,0),v={x:0,y:0,z:0};for(let e of this.items){let t=r.getObjectId(e),n=r.getGeometryWithCurves?.(e);if(n!=null){b(n,t);continue}let i=r.getGeometry(e);i!=null&&y(i,t)}return f.candidates.sort((e,t)=>e.distance-t.distance),f;function y(t,n){let{coords:r,stride:a}=t,o=t.isPoint?ee:t.lengths;if(g.coords=r,_.coords=r,e.returnEdge){let e=0;for(let t=0;t<o.length;t++){let r=o[t],s=e;for(let t=0;t<r;t++,e+=a){if(!p&&t===r-1||(g.coordsIndex=e,_.coordsIndex=t===r-1?s:e+a,!Z(v,i,g,_)))continue;let o=d(v.x,v.y);o<=1&&f.candidates.push(new K(n,h(v),Math.sqrt(o),h(g),h(_)))}}}if(e.vertexMode===`all`){let e=0;for(let t=0;t<o.length;t++){let r=o[t],i=e,s=_;s.coordsIndex=i;for(let t=0;t<r;t++,e+=a){if(g.coordsIndex=e,p&&t===r-1&&g.x===s.x&&g.y===s.y)continue;let i=d(g.x,g.y);i<=1&&f.candidates.push(new q(n,h(g),Math.sqrt(i)))}}}else if(m&&e.vertexMode===`ends`){let e=0,t=[];for(let n=0;n<o.length;n++){t.push(e);let r=o[n];e+=r*a,r>1&&t.push(e-a)}for(let e of t){g.coordsIndex=e;let t=d(g.x,g.y);t<=1&&f.candidates.push(new q(n,h(g),Math.sqrt(t)))}}}function b(t,n){let{candidates:r}=f,a={x:0,y:0,z:0};if(e.returnEdge){let e=[i.x,i.y],o=new Q(e,0),f=new Q(e,0);for(let{segments:i}of t.parts)for(let{start:t,curve:p}of i){let{curvePoint:i}=s(t,p,e),m=d(...i);if(m>1)continue;[a.x,a.y]=i,o.coords=t,f.coords=c(p);let g=l(p)?null:u(p);r.push(new K(n,h(a),Math.sqrt(m),h(o),h(f),!1,g))}}function o(e){a.x=t.vertexXY[e*2],a.y=t.vertexXY[e*2+1];let i=d(a.x,a.y);i>1||(a.z=t.vertexZ?.[e]??0,r.push(new q(n,h(a),Math.sqrt(i))))}if(e.vertexMode===`all`){let{vertexCount:e}=t;for(let t=0;t<e;++t)o(t)}else if(e.vertexMode===`ends`)switch(t.type){case`point`:o(0);break;case`polyline`:for(let e=0;e<t.partCount;++e){let n=t.partOffsets[e],r=t.partOffsets[e+1]-1;o(n),r!==n&&o(r)}}}}_getPointCreator(e,t,n){let r=n!=null&&!g(t,n)?e=>W(e,t,n):e=>e,{hasZ:i}=this;return i&&e?({x:e,y:t,z:n})=>r({x:e,y:t,z:n}):({x:e,y:t})=>r({x:e,y:t,z:0})}async createSummaryStatisticsResponse(e){let{field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,minValue:o,maxValue:s,scale:c,timeZone:l,outStatisticTypes:u}=e,d=this.fieldsIndex.get(t),f=I(d)||L(d)||R(d),p=await this._getDataValues({field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,scale:c,timeZone:l},this.items),m=S({normalizationType:i,normalizationField:r,minValue:o,maxValue:s}),h={value:.5,fieldType:d?.type},g=z(d)?C({values:p,supportsNullCount:m,percentileParams:h,outStatisticTypes:u}):w({values:p,minValue:o,maxValue:s,useSampleStdDev:!i,supportsNullCount:m,percentileParams:h,outStatisticTypes:u});return T(g,u,f)}async createUniqueValuesResponse(e){let{field:t,valueExpression:n,domains:r,returnAllCodedValues:i,scale:a,timeZone:o}=e,s=await this._getDataValues({field:t,field2:e.field2,field3:e.field3,fieldDelimiter:e.fieldDelimiter,valueExpression:n,scale:a,timeZone:o},this.items,!1),c=E(s);return D(c,r,i,e.fieldDelimiter)}async createClassBreaksResponse(e){let{field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,classificationMethod:o,standardDeviationInterval:s,minValue:c,maxValue:l,numClasses:u,scale:d,timeZone:f}=e,p=await this._getDataValues({field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,scale:d,timeZone:f},this.items),m=O(p,{field:t,normalizationField:r,normalizationType:i,normalizationTotal:a,classificationMethod:o,standardDeviationInterval:s,minValue:c,maxValue:l,numClasses:u});return k(m,o)}async createHistogramResponse(e){let{field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,classificationMethod:o,standardDeviationInterval:s,minValue:c,maxValue:l,numBins:u,scale:d,timeZone:f}=e,p=await this._getDataValues({field:t,valueExpression:n,normalizationField:r,normalizationType:i,normalizationTotal:a,scale:d,timeZone:f},this.items);return A(p,{field:t,normalizationField:r,normalizationType:i,normalizationTotal:a,classificationMethod:o,standardDeviationInterval:s,minValue:c,maxValue:l,numBins:u})}_sortFeatures(e,t,n){if(e.length>1&&t?.length)for(let r of t.slice().reverse()){let{compare:t,fieldOrExpression:i,fieldInfo:a}=$(r,this.fieldsIndex);e.sort((e,r)=>t(n(e,i,a),n(r,i,a)))}}_topNFeatures(e,n,r,i){if(e.length>1&&n?.length){let a=n.map(e=>{let{compare:t,fieldOrExpression:n,fieldInfo:r}=$(e,this.fieldsIndex);return(e,a)=>t(i(e,n,r),i(a,n,r))}).reduceRight((e,t)=>(n,r)=>{let i=t(n,r);return i!==0&&!Number.isNaN(i)?i:e(n,r)}),o=[];for(let n of e)t(o,n,r,a);return o}return e.slice(0,r)}_createFeatureQueryResponse(e){let{items:t,geometryType:n,hasM:r,hasZ:i,featureIdInfo:a,spatialReference:o}=this,{outFields:s,outSR:c,quantizationParameters:l,resultRecordCount:u,resultOffset:d,returnZ:f,returnM:p}=e,h=u!=null&&t.length>(d||0)+u,g=s&&(s.includes(`*`)?[...this.fieldsIndex.fields]:s.map(e=>this.fieldsIndex.get(e)));return{exceededTransferLimit:h,features:this._createFeatures(e,t),fields:g,geometryType:n,hasM:r&&p,hasZ:i&&f,objectIdFieldName:a.type===`object-id`?a.fieldName:null,spatialReference:c||o,transform:l&&m(l)||null}}_createFeatures(e,t){let n=new V(e,this.featureAdapter,this.fieldsIndex),{hasM:r,hasZ:i}=this,{orderByFields:a,quantizationParameters:o,returnGeometry:s,returnCentroid:c,maxAllowableOffset:l,resultOffset:u,resultRecordCount:d,returnZ:f=!1,returnM:p=!1}=e,h=i&&f,g=r&&p,_,v=u||0,y=d==null?null:v+d;y!=null&&y<=5e3&&y<t.length?_=this._topNFeatures(t,a,y,(e,t,r)=>n.getFieldValue(e,t,r)):(_=[...t],this._sortFeatures(_,a,(e,t,r)=>n.getFieldValue(e,t,r))),(v>0||y!=null)&&(_=_.slice(v,y??void 0));let b=[],x=0;if(!this.geometryType||!s&&!c)for(let e of _){let t=n.getAttributes(e);t&&(b[x++]=this._addFeatureJSONMetadata(e,{attributes:t}))}else{let e=m(o)??void 0,t=this.geometryType===`esriGeometryPolygon`||this.geometryType===`esriGeometryPolyline`;if(s&&!c)for(let r of _){let i=this.featureAdapter.getGeometry(r),a=this._addFeatureJSONMetadata(r,{attributes:n.getAttributes(r),geometry:H(this.geometryType,i,l,e,h,g)});t&&i&&!a.geometry&&(a.centroid=U(this,this.featureAdapter.getCentroid(r,this),e)),b[x++]=a}else if(!s&&c)for(let t of _)b[x++]=this._addFeatureJSONMetadata(t,{attributes:n.getAttributes(t),centroid:U(this,this.featureAdapter.getCentroid(t,this),e)});else for(let t of _)b[x++]=this._addFeatureJSONMetadata(t,{attributes:n.getAttributes(t),centroid:U(this,this.featureAdapter.getCentroid(t,this),e),geometry:H(this.geometryType,this.featureAdapter.getGeometry(t),l,e,h,g)})}return b}_addFeatureJSONMetadata(e,t){let n=this.featureAdapter.getMetadata?.(e);return n!==void 0&&(t.metadata=n),t}_createExceedsLimitQueryResponse(){let e=!1,t=1/0,n=1/0,r=1/0;for(let e of this.query.outStatistics??[])if(e.statisticType===`exceedslimit`){t=e.maxPointCount==null?1/0:e.maxPointCount,n=e.maxRecordCount==null?1/0:e.maxRecordCount,r=e.maxVertexCount==null?1/0:e.maxVertexCount;break}return e=this.geometryType===`esriGeometryPoint`?this.items.length>t:this.items.length>n||this.items.reduce((e,t)=>e+(this.featureAdapter.getGeometry(t)?.size??0),0)>r,{fields:[{name:`exceedslimit`,type:`esriFieldTypeInteger`,alias:`exceedslimit`,sqlType:`sqlTypeInteger`,domain:null,defaultValue:null}],features:[{attributes:{exceedslimit:Number(e)}}]}}async _createStatisticsQueryResponse(e,t,n={attributes:{}}){let r=[],i=new Map,a=new Map,o=new Map,s=new Map,c=new V(e,this.featureAdapter,this.fieldsIndex),l=e.outStatistics,{groupByFieldsForStatistics:u,having:d,orderByFields:f,resultRecordCount:p}=e,m=u?.length,h=!!m,g=h?u[0]:null,_=h&&!this.fieldsIndex.get(g);for(let f of l??[]){let{outStatisticFieldName:l,statisticType:p}=f,v=f,y=p===`exceedslimit`?void 0:f.onStatisticField,b=p===`percentile_disc`||p===`percentile_cont`,x=p===`EnvelopeAggregate`||p===`CentroidAggregate`||p===`ConvexHullAggregate`,S=h&&m===1&&(y===g||_)&&p===`count`;if(h){if(!o.has(y)){let e=[];for(let n of u){let r=this._getAttributeValues(c,n,t,i);e.push(r)}o.set(y,this._calculateUniqueValues(e,t,!x&&c.returnDistinctValues))}let n=o.get(y);if(!n)continue;let r=Object.keys(n);for(let a of r){let{count:r,data:o,items:f,itemPositions:p}=n[a],m=o.join(`,`);if(!d||c.validateItems(f,d)){let n=s.get(m)||{attributes:{}};if(e.returnAggIds&&(n.aggregateIds=f.map(e=>this.featureAdapter.getObjectId(e)).filter(e=>e!=null)),x){n.aggregateGeometries||={};let{aggregateGeometries:e,outStatisticFieldName:t}=await this._getAggregateGeometry(v,f);n.aggregateGeometries[t]=e}else{let e=null;if(S)e=r;else{let n=this._getAttributeValues(c,y,t,i),r=p.map(e=>n[e]);e=b&&`statisticParameters`in v?this._getPercentileValue(v,r):this._getStatisticValue(v,r,null,c.returnDistinctValues)}n.attributes[l]=e}let a=0;u.forEach((e,t)=>n.attributes[this.fieldsIndex.get(e)?e:`EXPR_${++a}`]=o[t]),s.set(m,n)}}}else if(x){n.aggregateGeometries||={};let{aggregateGeometries:e,outStatisticFieldName:r}=await this._getAggregateGeometry(v,t);n.aggregateGeometries[r]=e}else{let e=this._getAttributeValues(c,y,t,i);n.attributes[l]=b&&`statisticParameters`in v?this._getPercentileValue(v,e):this._getStatisticValue(v,e,a,c.returnDistinctValues)}let C=(p===`min`||p===`max`)&&(z(this.fieldsIndex.get(y))||this._isAnyDateField(y))?this.fieldsIndex.get(y)?.type:null;r.push({name:l,alias:l,type:C||`esriFieldTypeDouble`})}let v=h?Array.from(s.values()):[n];return this._sortFeatures(v,f,(e,t)=>e.attributes[t]),p&&(v.length=Math.min(p,v.length)),{fields:r,features:v}}_isAnyDateField(e){let t=this.fieldsIndex.get(e);return I(t)||L(t)||R(t)||B(t)}async _getAggregateGeometry(e,t){let{statisticType:n,outStatisticFieldName:r}=e,{featureAdapter:i,spatialReference:s,geometryType:c}=this,l=t.map(e=>H(c,i.getGeometry(e))),u={aggregateGeometries:null,outStatisticFieldName:null},{convexHullExecuteMany:f}=await J.getImportPromise(),[p]=f(l,{merge:!0});if(p&&p.rings[0].length<=3&&(p=null),n===`EnvelopeAggregate`)u.aggregateGeometries={...p?d(p):X(l),spatialReference:s},u.outStatisticFieldName=r||`extent`;else if(n===`CentroidAggregate`){let[e,t]=p?a(p):o(X(l));u.aggregateGeometries={x:e,y:t,spatialReference:s},u.outStatisticFieldName=r||`centroid`}else n===`ConvexHullAggregate`&&(u.aggregateGeometries=p&&{...p,spatialReference:s},u.outStatisticFieldName=r||`convexHull`);return u}_getStatisticValue(e,t,n,r){let{onStatisticField:i,statisticType:a}=e,o=null;return o=n?.has(i)?n.get(i):z(this.fieldsIndex.get(i))||this._isAnyDateField(i)?C({values:t,returnDistinct:r}):w({values:r?[...new Set(t)]:t,minValue:null,maxValue:null,useSampleStdDev:!0}),n&&n.set(i,o),o[a===`var`?`variance`:a]}_getPercentileValue(e,t){let{onStatisticField:n,statisticParameters:r,statisticType:i}=e,{value:a,orderBy:o}=r,s={value:a,orderBy:o,fieldType:this.fieldsIndex.get(n)?.type,isDiscrete:i===`percentile_disc`};return j(t,s)}_getAttributeValues(e,t,n,r){if(r.has(t))return r.get(t);let i=this.fieldsIndex.get(t),a=n.map(n=>e.getFieldValue(n,t,i));return r.set(t,a),a}_calculateUniqueValues(e,t,n){let r={},i=t.length;for(let a=0;a<i;a++){let i=t[a],o=Array.from(e,e=>e[a]),s=o.join(`,`);r[s]==null?r[s]={count:1,data:o,items:[i],itemPositions:[a]}:(n||r[s].count++,r[s].items.push(i),r[s].itemPositions.push(a))}return r}async _getDataValues(e,t,n=!0){let a=new V(this.query,this.featureAdapter,this.fieldsIndex),{valueExpression:o,scale:s,timeZone:c}=e,l=i.fromJSON(this.query.outSR||this.spatialReference);return o?a.getExpressionValues(t,o,{viewingMode:`local`,scale:s,spatialReference:l},{geometryType:this.geometryType,hasZ:this.hasZ,hasM:this.hasM},c):a.getDataValues(t,r(e),n)}_calculateHistogramBins(e,t,n){if(t.min==null&&t.max==null)return[];let r=t.intervals,i=t.min??0,a=t.max??0,o=r.map(([e,t])=>({minValue:e,maxValue:t,count:0,items:[]}));for(let t=0;t<e.length;t++){let s=e[t],c=n[t];if(s!=null&&s>=i&&s<=a){let e=M(r,s);e>-1&&(o[e].count++,o[e].items.push(c))}}return o}async createQueryBinsResponse(e){let t=e.bin?.splitBy;if(!t)return this._createBinsResponse(e);let{value:n,outAlias:r,valueType:i}=t,a=[],o=[{name:r??n,alias:r??n,type:i??`esriFieldTypeString`},{name:`bin`,alias:`bin`,type:`esriFieldTypeInteger`}],s=new V(e,this.featureAdapter,this.fieldsIndex),c=new Map,l=[...this.items];this._sortFeatures(l,[n],(e,t,n)=>s.getFieldValue(e,t,n));let u=this._getAttributeValues(s,n,l,c),d=this._calculateUniqueValues([u],l,s.returnDistinctValues);for(let t in d){let{items:i}=d[t],s=await this._createBinsResponse(e,i);if(a.push(...s.features.map(e=>({...e,attributes:{...e.attributes,[r??n]:t}}))),s.fields)for(let e of s.fields)o.some(t=>t.name===e.name)||o.push(e)}return{fields:o,features:a}}async _createBinsResponse(e,t){let n=e.bin;switch(t??=this.items,n.type){case`autoIntervalBin`:return this._createAutoIntervalBinsResponse(_.fromJSON(n),e,t);case`dateBin`:return this._createDateBinsResponse(v.fromJSON(n),e,t);case`fixedBoundariesBin`:return this._createFixedBoundariesBinsResponse(b.fromJSON(n),e,t);case`fixedIntervalBin`:return this._createFixedIntervalBinsResponse(x.fromJSON(n),e,t)}}async _createAutoIntervalBinsResponse(e,t,n){let{field:r,normalizationField:i,numBins:a,normalizationType:o,normalizationTotal:s,start:c,end:l}=e,u=await this._getDataValues({field:e.field||e.expression,normalizationField:e.normalizationField,normalizationType:e.normalizationType,normalizationTotal:e.normalizationTotal,timeZone:t.outTimeReference?.ianaTimeZone},n),d=N(u,{field:r,normalizationField:i,normalizationType:o,normalizationTotal:s,numBins:a,minValue:G(o?e.normalizationMinValue:c,!1),maxValue:G(o?e.normalizationMaxValue:l,!1)}),f=this._calculateHistogramBins(u,d,n);return this._createFeaturesFromHistogramBins(f,t)}async _createDateBinsResponse(t,n,r){let{field:i,interval:a,start:o,end:s,snapToData:c,returnFullIntervalBin:l,offset:u,firstDayOfWeek:d}=t,f=a.unit,p=await this._getDataValues({field:i||t.expression,timeZone:n.outTimeReference?.ianaTimeZone},r),m=B(this.fieldsIndex.get(i)),h=y.toJSON(f),g=p.filter(Boolean).sort((e,t)=>e-t),_=o==null?g[0]:G(o,m),v=s==null?g[g.length-1]:G(s,m),b=[];if(_!=null&&v!=null){let t={zone:n.outTimeReference?.ianaTimeZone??F},r={[u?.unit?y.toJSON(u.unit):`milliseconds`]:u?.value||0},i=e.fromMillis(_,t).minus(r),o=e.fromMillis(v,t).minus(r),s=typeof d==`number`&&d>=1&&d<=7?d:7,f=(e,t)=>{let n=(e.weekday-t+7)%7;return e.minus({days:n}).startOf(`day`)},p=(e,t)=>f(e,t).plus({days:7});if(c===`last`){let e=h===`week`?p(o,s):o;for(;e>i;){let t=e.minus({[h]:a.value});if(t<i){b.unshift([l?t.plus(r).toMillis():i.plus(r).toMillis(),e.plus(r).toMillis()]);break}b.unshift([t.plus(r).toMillis(),e.plus(r).toMillis()]),e=t}}else{let e=c===`first`?i:h===`week`?f(i,s):i.startOf(h);for(;e<=o;){let t=e.plus({[h]:a.value});if(t>o){b.push([e.plus(r).toMillis(),l?t.plus(r).toMillis():o.plus(r).toMillis()]);break}b.push([e.plus(r).toMillis(),t.plus(r).toMillis()]),e=t}}}let x=this._calculateHistogramBins(p,{intervals:b,min:_,max:v},r);return this._createFeaturesFromHistogramBins(x,n)}async _createFixedBoundariesBinsResponse(e,t,n){let{field:r}=e,i=await this._getDataValues({field:r||e.expression,timeZone:t.outTimeReference?.ianaTimeZone},n),a=B(this.fieldsIndex.get(r)),o=e.boundaries.map(e=>G(e,a)).sort((e,t)=>e-t),s=[];for(let e=0;e<o.length-1;e++)s.push([o[e],o[e+1]]);let c={intervals:s,min:o.at(0),max:o.at(-1)},l=this._calculateHistogramBins(i,c,n);return this._createFeaturesFromHistogramBins(l,t)}async _createFixedIntervalBinsResponse(e,t,n){let{field:r,interval:i,normalizationType:a,start:o,end:s}=e,c=await this._getDataValues({field:r||e.expression,normalizationField:e.normalizationField,normalizationType:a,normalizationTotal:e.normalizationTotal,timeZone:t.outTimeReference?.ianaTimeZone},n),l=B(this.fieldsIndex.get(r)),u=N(c,{field:r,classificationMethod:`defined-interval`,definedInterval:i,minValue:G(a?e.normalizationMinValue:o,l),maxValue:G(a?e.normalizationMaxValue:s,l)},!0),d=this._calculateHistogramBins(c,u,n);return this._createFeaturesFromHistogramBins(d,t)}async _createFeaturesFromHistogramBins(t,n){let{upperBoundaryAlias:r,lowerBoundaryAlias:i}=n,a=i||`lowerBoundary`,o=r||`upperBoundary`,s=[],c=[{name:a,alias:a,type:`esriFieldTypeDouble`},{name:o,alias:o,type:`esriFieldTypeDouble`}],l=n.bin?.stackBy?.value,u=n.bin?.stackBy?.outAlias;l&&c.push({name:`bin`,alias:`bin`,type:`esriFieldTypeInteger`},{name:u??l,alias:u??l,type:`esriFieldTypeString`});let d=0,f=n.bin.type===`dateBin`,p=n.outTimeReference?.ianaTimeZone;for(let r of t){let{minValue:t,maxValue:i,items:m}=r,h={attributes:{}};h.attributes[a]=f&&p&&t!=null?e.fromMillis(t,{zone:p}).toISO():t,n.bin.hideUpperBound||(h.attributes[o]=f&&p&&i!=null?e.fromMillis(i,{zone:p}).toISO():i),n.returnAggIds&&(h.aggregateIds=m.map(e=>this.featureAdapter.getObjectId(e)).filter(e=>e!=null));let g;if(l?(g=await this._createStatisticsQueryResponse({...n,groupByFieldsForStatistics:[l],orderByFields:[l]},m),h.attributes.bin=++d,n.bin.jsonStyle===`flat`?s.push(...g.features.map(({attributes:{EXPR_1:e,...t},...n})=>({...n,attributes:u??e?{...t,[u??e]:e,...h.attributes}:{...t,...h.attributes}}))):(h.stackedAttributes=g.features.map(({attributes:{EXPR_1:e,...t}})=>u??e?{...t,[u??e]:e}:t),s.push(h))):(n.bin?.splitBy&&(h.attributes.bin=++d),g=await this._createStatisticsQueryResponse(n,m,h),s.push(h)),g.fields)for(let e of g.fields)c.some(t=>t.name===e.name)||c.push(e)}return n.binOrder===`desc`&&s.reverse(),{fields:c,features:s}}}function X(e){let t=f(e[0]);for(let n of e.slice(1))p(t,f(n));return t}function Z(e,t,n,r){let i=r.x-n.x,a=r.y-n.y,o=t.x-n.x,s=t.y-n.y,c=i*i+a*a;if(c===0)return!1;let l=o*i+s*a,u=Math.min(1,Math.max(0,l/c));return e.x=n.x+i*u,e.y=n.y+a*u,!0}class Q{constructor(e,t){this.coords=e,this.coordsIndex=t}get x(){return this.coords[this.coordsIndex]}get y(){return this.coords[this.coordsIndex+1]}get z(){return this.coords[this.coordsIndex+2]}}const ee=[1];function $(e,t){let n=e.split(` `),r=n[0],i=t.get(r),a=n[1]?n[1].toLowerCase()===`desc`:!1;return{compare:P(i?.type,a,`case-insensitive`),fieldOrExpression:r,fieldInfo:i}}export{Y as QueryEngineResult};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
- import{__addDisposableResource as e,__disposeResources as t}from"tslib";import n from"../../../../core/Error.js";import r from"../../../../core/Handles.js";import has from"../../../../core/has.js";import i from"../../../../core/Logger.js";import{onAbortOrThrow as a,throwIfAborted as o}from"../../../../core/promiseUtils.js";import{QueueProcessor as s}from"../../../../core/QueueProcessor.js";import{parseWhereClause as c}from"../../../../core/sql.js";import{getMetersPerUnitForSR as l}from"../../../../core/units.js";import{initializeProjection as u}from"../../../../geometry/projectionUtils.js";import d from"../../../../geometry/SpatialReference.js";import{set as f,create as p,expandWithAABB as m,expandWithRect as h,negativeInfinity as g}from"../../../../geometry/support/aaBoundingBox.js";import{copy as _,create as v,expandWithRect as ee,negativeInfinity as te}from"../../../../geometry/support/aaBoundingRect.js";import{isWebMercator as y,isWGS84 as b}from"../../../../geometry/support/spatialReferenceUtils.js";import{loadParquetModule as x}from"../../../../libs/librust-parquet/loadParquetModule.js";import{utc as ne}from"../../../../time/constants.js";import{FeatureStoreQueryAdapter as S}from"../../../../views/2d/layers/features/FeatureStoreQueryAdapter.js";import{FeatureSnapshotSourceChunk as C}from"../../../../views/2d/layers/features/sources/strategies/chunks/FeatureSnapshotSourceChunk.js";import{FeatureSourceChunkStore as w}from"../../../../views/2d/layers/features/sources/strategies/chunks/SourceChunkStore.js";import{FeatureMetadata as re}from"../../../../views/2d/layers/features/support/FeatureMetadata.js";import{FeatureSetReaderParquet as T}from"../../../../views/2d/layers/features/support/FeatureSetReaderParquet.js";import{normalizeColumnPath as E,readParquetFileAttribute as D}from"../../../parquet.js";import O from"../../../support/Field.js";import ie from"../../../support/FieldsIndex.js";import{isNumericField as ae}from"../../../support/fieldUtils.js";import{fromParquetGeometryEncodingJSON as oe}from"../../../support/parquetEncodingUtils.js";import{completeParquetLayerInfo as se,fromParquetJSONGeometryType as ce,toParquetJSONGeometryType as k}from"../../../support/parquetUtils.js";import{getFieldNamesFromStatistics as A}from"../../data/attributeSupport.js";import{project as j}from"../../data/projectionSupport.js";import{getQueryResultExtent as M,getQueryBoundingRects as N,QueryEngine as P}from"../../data/QueryEngine.js";import{queryCapabilities as F}from"../../data/QueryEngineCapabilities.js";import{QueryEngineResult as I}from"../../data/QueryEngineResult.js";import{normalizeQueryLike as L}from"../../data/queryUtils.js";import{convertToGeometry as R}from"../../featureConversionUtils.js";import{createFileProvider as z}from"../parquet/createFileProvider.js";import{readFieldStatistic as B}from"../parquet/ParquetFileStatistics.js";import{createDrawingInfo as V}from"./clientSideDefaults.js";import{getParquetFileId as H,getParquetRowId as U,getParquetObjectId as W}from"./parquetIdUtils.js";const G=new S,K=`__OBJECTID`,q=8e3;class le{constructor(e,t){this._files=e,this._createFileStream=t,this._fileIndex=0,this._streamIndex=0,this._streams=[],this._pending=new Set,this._resolvedCount=0}async next(e){for(await this._fill(e);this._pending.size>0;){o(e),await this._fill(e);let t=await ue(this._pending);if(this._pending.delete(t.read),this._resolvedCount++,t.chunk!=null)return t.chunk}return null}async _fill(e){for(this._removeDone();this._pending.size<8;){let t=this._getOrCreateNextStream(e);if(t==null)return;this._pending.add(t.read(e))}}_getOrCreateNextStream(e){let t=this._resolvedCount>=8?8:2;if(this._fileIndex<this._files.length&&this._streams.length<t){let t=this._files[this._fileIndex++],n=new de(t.id,this._createFileStream(t,e));return this._streams.push(n),n}return this._getNextStream()}_getNextStream(){let e=this._streams.length;for(let t=0;t<e;t++){let n=(this._streamIndex+t)%e,r=this._streams[n];if(r.canRead)return this._streamIndex=(n+1)%e,r}return null}_removeDone(){let e=this._streamIndex;for(let t=this._streams.length-1;t>=0;t--)this._streams[t].done&&(this._streams.splice(t,1),t<e&&e--);this._streamIndex=this._streams.length>0?e%this._streams.length:0}}function ue(e){return Promise.race(Array.from(e,async e=>({read:e,chunk:await e})))}class de{constructor(e,t){this._fileId=e,this._stream=t,this._readCount=0,this._reachedEnd=!1}get canRead(){return!this._reachedEnd}get done(){return this._reachedEnd&&this._readCount===0}async read(e){this._readCount++;try{let t=await(await this._stream).next(e);return t==null?(this._reachedEnd=!0,null):{fileId:this._fileId,chunk:t}}finally{this._readCount--}}}class fe{constructor(){this._hasZ=!1,this._hasM=!1,this._queue=new s({concurrency:4,process:(e,t)=>this._executeQuery(e,t)}),this._streams=new Map,this._streamIdCounter=0,this._indexMap={},this._handles=new r}async load(e){let t=e.spatialReference?d.fromJSON(e.spatialReference):void 0;if(t&&!t.isWGS84&&!t.isWebMercator)throw new n(`parquet:unsupported-projection`,`Only WGS84 and Web Mercator are supported`);this._customParameters=e.customParameters,this._loadParameters=e,await this._updateProvider(z(e.provider,null,()=>this._customParameters));let r=await this._provider.getMetadata(),a=await se(r,{fields:e.fields?.map(e=>O.fromJSON(e)),geometryEncoding:e.geometryEncoding?oe(e.geometryEncoding):null,geometryType:e.geometryType?ce(e.geometryType):null,displayOptimization:e.displayOptimization,spatialReference:t});if(this._hasZ=!!r?.hasZ,this._hasM=!!r?.hasM,!a.fields)throw new n(`parquet:unsupported`,`Fields must be defined`);let o;if(a.spatialReference&&a.geometryType){if(!a.spatialReference)throw new n(`parquet:unsupported`,`SpatialReference must be defined`);if(!a.spatialReference.isGeographic&&!a.spatialReference.isWebMercator)throw new n(`parquet:unsupported-projection`,`Only WGS84 and Web Mercator are supported`);a.spatialReference.isGeographic&&!a.spatialReference.isWGS84&&(i.getLogger(`parquet:unsupported-projection`).warn(`Found a geographic projection that is not WGS84. Handling as WGS84.`,{spatialReference:a.spatialReference}),a.spatialReference=d.WGS84),o={geometry:a.geometryEncoding?{geometryType:k(a.geometryType),spatialReference:a.spatialReference.toJSON(),encoding:a.geometryEncoding.toJSON()}:null,displayOptimization:a.displayOptimization}}this.setCustomParameters(e.customParameters),this._displayOptimization=a.displayOptimization,await this._provider.updateGeometryInfo(o),this._capabilities=$(await this._getFileStatistics(),this._hasZ,this._hasM);let s=await this._provider.getFiles();if(!s.length)return{layerDefinition:{},capabilities:$(null,this._hasZ,this._hasM)};let c=await s[0].file;a.file=c;let{fields:l}=a;if(l==null)throw new n(`parquet-layer:missing-metadata`,`Unable to create parquet source: cannot infer fields`,l);l.push(new O({name:K,type:`oid`,alias:K}));for(let e of l){let t=c.getColumnId(e.name);t!=null&&(this._indexMap[e.name]=t)}let u=ie.fromLayerJSON({fields:l.map(e=>e.toJSON()),dateFieldsTimeReference:{timeZoneIANA:`UTC`}});this._fieldsIndex=u;let f=k(a.geometryType??`point`);return this._metadata=re.createFeature({fieldsIndex:u.toJSON(),geometryType:f,hasZ:this._hasZ,hasM:this._hasM,featureIdInfo:{type:`object-id`,fieldName:K},subtypes:null,subtypeField:null,types:null,typeIdField:null,globalIdField:null,spatialReference:a.spatialReference,outSpatialReference:null,attributeSpatialReference:null,timeInfo:null,timeReferenceUnknownClient:null,dateFieldsTimeZone:ne}),this._queryEngineParams={fieldsIndex:this._metadata.fieldsIndex,geometryType:f,featureIdInfo:{type:`object-id`,fieldName:K},hasM:this._hasM,hasZ:this._hasZ,spatialReference:a.spatialReference?.toJSON()??{wkid:4326},aggregateAdapter:null,timeInfo:null,definitionExpression:null},this._fullExtent=r?.extent?r.extent:await this._tryDeriveParquetFullExtent(a),{capabilities:this._capabilities,layerDefinition:{fields:a.fields?.map(e=>e.toJSON()),drawingInfo:V(f),extent:this._fullExtent??void 0,geometryType:f,hasZ:this._hasZ,hasM:this._hasM,geometryEncoding:a.geometryEncoding?.toJSON(),displayOptimization:a.displayOptimization}}}destroy(){this._provider.destroy(),this._queue.destroy();for(let{handle:e}of this._streams.values())e.remove();this._streams.clear(),this._indexMap={},this._handles.removeAll()}async reload(e){this.destroy(),await this.load(e)}set remoteClient(e){this._source=e.createInvokeProxy(``)}setCustomParameters(e){this._customParameters=e}getIndexMap(){return this._indexMap}async updateFileProvider(e){this._loadParameters={...this._loadParameters,provider:e};let t=z(e,this._provider.getGeometryInfo(),()=>this._customParameters);await this._updateProvider(t)}async getDiagnosticsSnapshot(){let e=await this._provider.getFiles();return{files:await Promise.all(e.map(e=>e.getDiagnosticsSnapshot()))}}async getColumnIndex(e){return(await this._getFileInfoById(e.fileId)).getColumnIndex(e.rowGroupIndex,e.columnIndex)}async getOffsetIndex(e){return(await this._getFileInfoById(e.fileId)).getOffsetIndex(e.rowGroupIndex,e.columnIndex)}async queryFeatures(e,t){let n=await L(e,null,this._queryEngineParams.spatialReference);return this._validateQuery(n),Te(n)||(n.resultRecordCount=n.resultRecordCount?Math.min(n.resultRecordCount,q):q,n.resultOffset=n.resultOffset??0),n.outStatistics?this._queryStatistics(n,t):(n.returnDistinctValues&&(n.returnGeometry=void 0),(await this._enqueueQuery(n,t)).createQueryResponse())}async queryFeatureCount(e,t){let n=await L(e,null,this._queryEngineParams.spatialReference);return this._validateQuery(n),!J(n)&&!n.returnDistinctValues&&!n.groupByFieldsForStatistics?.length&&!n.outStatistics?.length?this._getFeatureCount():(n.returnDistinctValues||(n.outFields=void 0),n.returnGeometry=void 0,(await this._enqueueQuery(n,t)).createQueryResponseForCount())}async queryObjectIds(e,t){let n=await L(e,null,this._queryEngineParams.spatialReference);return this._validateQuery(n),J(n)?(n.resultRecordCount=n.resultRecordCount?Math.min(n.resultRecordCount,8e3):8e3,n.resultOffset=n.resultOffset??0,n.returnGeometry=void 0,n.outFields=void 0,n.returnDistinctValues=void 0,(await this._enqueueQuery(n,t)).items.map(e=>e.getObjectId())):Array.from({length:await this._getFeatureCount()},(e,t)=>t)}async queryAttributeBins(e,t={}){throw new n(`parquet:unsupported`,`queryAttributeBins not supported.`)}async queryExtent(e,t){let n=await L(e,null,this._queryEngineParams.spatialReference);this._validateQuery(n);let r=n.outSR??this._queryEngineParams.spatialReference;if(this._fullExtent&&!J(n)){let e=this._fullExtent;return await u(e.spatialReference,n.outSR),{count:await this._getFeatureCount(),extent:n.outSR?j(e,n.outSR):e}}n.returnGeometry=!0,n.outFields=void 0;let i=f(p(),g),a=p(),o=await this._enqueueQuery(n,t),s=0;for(let e of o.items)e.getBounds(a)&&(m(i,a),s+=1);let c=M(i,r,r,r,!1);return{count:s,extent:c}}async queryStream(e,t){if(!t.signal)throw Error(`InternalError: AbortSignal must be passed`);let n=await this._getCandidateFiles(e),r=new le(n,async(t,n)=>{let r=await t.file,i=await this._createParquetDisplayQuery(r,t.id,e);return r.executeQuery(i,q,n)}),i=this._streamIdCounter++,o=a(t.signal,e=>{let t=this._streams.get(i);t!=null&&(t.handle.remove(),this._streams.delete(i))});return this._streams.set(i,{stream:r,handle:o}),i}async getStreamNext(e,t){if(!t.signal)throw Error(`InternalError: AbortSignal must be passed`);let n=this._streams.get(e);if(!n)return{result:null};let r=await n.stream.next(t.signal);if(r==null)return n.handle.remove(),this._streams.delete(e),{result:null};let i=r.chunk.serialize().buffer,a={fileId:r.fileId,buffer:i};return i instanceof ArrayBuffer?{result:a,transferList:[i]}:{result:a}}async getStreamNextFeatures(e,t){let{result:n}=await this.getStreamNext(e,t);if(n==null)return null;let r=(await x()).ParquetChunk.deserialize(new Uint8Array(n.buffer)),i=new T(this._metadata,this._indexMap,r,n.fileId),a=[];for(;i.next();){let e=R(i.readGeometryWorldSpace(),i.geometryType,i.hasZ,i.hasM),t=i.readAttributes();a.push({attributes:t,geometry:e})}return{features:a}}async createPatch(e,t,n,r,i){if(!i.signal)throw Error(`InternalError: AbortSignal must be passed`);return(await(await(await this._getFileInfoById(e)).file).createChunkPatch(t,n,r,i.signal)).serialize().buffer}async _updateProvider(e){let t=this._provider;this._handles.removeAll(),this._provider=e,this._handles.add([e.events.on(`rangeRead`,e=>{this._source.onRangeRead(e)}),e.events.on(`sourceChanged`,async()=>{await this.reload(this._loadParameters),await this._source.onSourceChange()})]),await t?.destroy()}async _getCandidateFiles(e){let t=await this._provider.getFiles(),n=await this._getSpatialFilePruning(e);if(n==null)return t;let r=t.filter(e=>this._mayIncludeFileForSpatialPruning(e,n));return n.type===`xz`?we(r,n):r}async _queryStatistics(e,t){let n=await L({...e},null,this._queryEngineParams.spatialReference);if(n.returnGeometry=void 0,ve(n,this._fieldsIndex)){let e=await this._getStatisticsFromFiles(n);if(e)return e}return(await this._enqueueQuery(n,t)).createQueryResponse()}async _getStatisticsFromFiles(e){let t=await this._provider.getFiles(),n={},r=[];for(let i of e.outStatistics??[]){let e=xe(i,t);if(!e.available)return null;n[i.outStatisticFieldName]=e.value,r.push(be(i,this._fieldsIndex))}return{fields:r,features:[{attributes:n}]}}async _getSpatialFilePruning(e){if(e.type!==`tile`&&(e.type!==`arcade`||e.extent==null))return null;let t=this._displayOptimization?.index;if(t==null)return null;let n=e.outSpatialReference.wkid;if(t.wkid==null||n==null)return null;let r=t.wkid,i=await x();switch(t.type){case`xz`:return{type:`xz`,fieldName:E(t.code),intersects:(a,o)=>i.queryIntersectsXZStatistics(t.fullExtent,e.extent,n,r,t.maxLevel,a,o)};case`z`:return{type:`xy`,xFieldName:E(t.xColumn),yFieldName:E(t.yColumn),intersects:(t,a,o,s)=>i.queryIntersectsXYStatistics(e.extent,n,r,t,a,o,s)}}}_mayIncludeFileForSpatialPruning(e,t){switch(t.type){case`xz`:{let n=Z(e,t);return n?.type===`null-only`?!1:n?.type!==`bounds`||t.intersects(n.minValue,n.maxValue)}case`xy`:{let n=e.statistics.statistics.get(t.xFieldName),r=e.statistics.statistics.get(t.yFieldName);return n?.type===`null-only`||r?.type===`null-only`?!1:n?.type!==`bounds`||r?.type!==`bounds`||t.intersects(n.minValue,n.maxValue,r.minValue,r.maxValue)}}}async _tryDeriveParquetFullExtent(n){if(!n.spatialReference)return null;if(this._fullExtent==null&&n.geometryEncoding?.type===`location`){let r=await this._provider.getFiles(),{xField:i,yField:a}=n.geometryEncoding,o=f(p(),g),s=!1;for(let n of r){let r=await n.file;for(let n of r.rowGroups()){let r={stack:[],error:void 0,hasError:!1};try{let t=e(r,n.columnDescriptorForAttribute(i),!1),c=e(r,n.columnDescriptorForAttribute(a),!1),l=B(t),u=B(c);if(l?.type===`bounds`&&u?.type===`bounds`){let e=[l.minValue,u.minValue,l.maxValue,u.maxValue];h(o,e),s=!0}n.free()}catch(e){r.error=e,r.hasError=!0}finally{t(r)}}}return s?{xmin:o[0],ymin:o[1],xmax:o[3],ymax:o[4],spatialReference:n.spatialReference?.toJSON()}:null}return null}async _getFileInfoById(e){let t=await this._provider.getFiles();for(let n of t)if(n.id===e)return n;throw Error(`InternalError: File ${e} does not exist`)}async _getFileStatistics(){return{featureCount:await this._getFeatureCount(),byteLength:await this._getByteLength()}}async _getFile(e){return(await this._getFileInfoById(e)).file}async _createParquetQuery(e,t,n,r,i){let a=(await x()).Query.new();n!=null&&a.setPreFilterStart(n),r!=null&&a.setPreFilterCount(r),i!=null&&a.setPostFilterCount(i);let o=await this._getRequiredFields(e);a.setOutFields(o),(e.geometry||e.returnGeometry)&&a.setReturnGeometry(!0),a.setReturnZ(!!e.returnZ),a.setReturnM(!!e.returnM);let s=this._tryGetGeneralizedGeometryResolution(e);s!=null&&a.setSourceResolution(s);let c=e.geometry?.spatialReference??this._queryEngineParams.spatialReference,l=c.wkid;if(e.geometry&&(y(c)||b(c))){let t=_(v(),te);for(let n of N(e.geometry))ee(t,n);a.setOutSpatialReference(l),a.setExtent({xmin:t[0],ymin:t[1],xmax:t[2],ymax:t[3]})}if(e.where){let{id:n,file:r}=t;await this._setWhereClause(a,await r,n,e.where)}return a}async _createParquetDisplayQuery(e,t,n){let r=(await x()).Query.new();if(n.type===`tile`){r.setExtent(n.extent),r.setQuantizationTransform(n.transform);let e=this._sourceResolution(n.resolution,n.outSpatialReference);e!=null&&r.setSourceResolution(e)}else n.type===`arcade`&&n.extent!=null&&r.setExtent(n.extent);return r.setOutFields(n.outFields.filter(e=>this._indexMap[e]!=null)),r.setOutSpatialReference(n.outSpatialReference.wkid),r.setReturnGeometry(n.returnGeometry),r.setReturnZ(n.returnZ),r.setReturnM(n.returnM),n.where&&await this._setWhereClause(r,e,t,n.where),r}async _getFeatureCount(){return(await this._provider.getFiles()).map(e=>e.statistics.rowCount).reduce((e,t)=>e+t,0)}async _getByteLength(){return(await this._provider.getFiles()).map(e=>e.statistics.byteSize).reduce((e,t)=>e+t,0)}_validateQuery(e){if(!this._capabilities.query.supportsStatistics&&e.outStatistics)throw new n(`parquet:unsupported`,`Statistics queries are not supported`,{query:e});if(!this._capabilities.query.supportsOrderBy&&e.orderByFields?.length)throw new n(`parquet:unsupported`,`Queries using orderBy are not supported`,{query:e});if(!this._capabilities.query.supportsDistinct&&e.returnDistinctValues)throw new n(`parquet:unsupported`,`Queries using returnDistinctValues are not supported`,{query:e})}async _setWhereClause(e,t,r,i){let a=this._indexMap,o=this._fieldsIndex,s={getAttribute(e,n){let i=a[n];if(i==null){if(o.get(n)?.name===`__OBJECTID`){let t=e.row+e.rowGroupStart;return W(r,t)}return null}let s=o.get(n);return D(t,e.rowGroup,e.row,i,s.type)}},l=await c(i,this._fieldsIndex);if(!l.isStandardized)throw new n(`sql-parse-error`,`expression is not standardized`);let u=(e,t,n)=>l.testFeatureCompiled({rowGroup:e,row:t,rowGroupStart:n},s,null),d=l.fieldNames.map(e=>o.get(e)).filter(e=>e&&this._indexMap[e?.name]!=null);e.setWhere(i),e.setWhereEvaluator(u),e.setWhereFields(d.map(e=>e.name))}async*_streamFeatures(e,t,n,r,i){let a=await this._provider.getFiles(),o=0;for(let s of a){let a=o,c=o+s.statistics.rowCount;if(o+=s.statistics.rowCount,t!=null&&t>=c)continue;let l=t==null?null:Math.max(t-a,0),u=n;if(n!=null){let e=t??0,r=e+n;u=Math.max(Math.min(r,c)-Math.max(e,a),0)}if(u===0)continue;let d=await this._createParquetQuery(e,s,l,u,r),f=await(await s.file).executeQuery(d,q),p=async()=>{let e=await f.next(i);if(!e)return null;let t=new T(this._metadata,this._indexMap,e,s.id);return X([new C(t,null,0,!1)],this._queryEngineParams)},m=await p();for(;m!=null;)yield m,m=await p()}}async _queryFeaturesWithQueryEnginePagination(e,t){let n=[],r=this._streamFeatures(e,null,null,null,t),i=await r.next();for(;!i.done;){let a=await i.value.executeQueryForOpaqueFeatures({...e,where:void 0},t);for(let e of a)n.push(e);i=await r.next()}return n}async _queryFeaturesWithUpfrontPagination(e,t){let n=e.resultOffset??0,r=e.resultRecordCount??q,i,a,o;ge(e)?_e(e)||(o=n+r):(n&&=(i=n,0),a=e.resultRecordCount);let s=[],c=this._streamFeatures(e,i,a,o,t),l=await c.next();for(;!l.done&&r>0;){let i=await l.value.executeQueryForOpaqueFeatures({...e,where:void 0},t);for(let e of i)if(n>0)n--;else if(s.push(e),--r<=0)return s;l=await c.next()}return s}_enqueueQuery(e,t){return this._queue.push(e,t)}async _executeQuery(e,t){if(e.objectIds?.length){let n=new Map;for(let t of e.objectIds){let e=H(t),r=U(t),i=n.get(e);i||(i=[],n.set(e,i)),i.push(r)}let r=[];for(let[i,a]of n.entries()){let n=await this._executeFileIdQuery(e,i,a,t);for(let e of n)r.push(e)}return new I(r,e,{fieldsIndex:this._fieldsIndex,geometryType:this._metadata.geometryType,spatialReference:this._queryEngineParams.spatialReference,hasM:this._hasM,hasZ:this._hasZ,featureAdapter:G,featureIdInfo:this._queryEngineParams.featureIdInfo})}if(e.where===`1=1`&&(e.where=null),e.resultOffset??=0,e.resultRecordCount??=await this._getFeatureCount(),e.resultRecordCount>2e7&&!(this._displayOptimization&&e.geometry))throw new n(`parquet:cannot-execute-query`,`Unable to execute query, dataset is too large.`);let r=!!e.orderByFields?.length||!!e.outStatistics?.length||!!e.returnDistinctValues,i=r?await this._queryFeaturesWithQueryEnginePagination(e,t):await this._queryFeaturesWithUpfrontPagination(e,t);return r||(e.resultOffset=0),new I(i,e,{fieldsIndex:this._fieldsIndex,geometryType:this._metadata.geometryType,spatialReference:this._queryEngineParams.spatialReference,hasM:this._hasM,hasZ:this._hasZ,featureAdapter:G,featureIdInfo:this._queryEngineParams.featureIdInfo})}async _executeFileIdQuery(e,t,n,r){let i=new Set(await this._getRequiredFields(e));if(e.where){let t=await c(e.where,this._fieldsIndex);for(let e of t.fieldNames){let t=this._fieldsIndex.get(e);t&&this._indexMap[t.name]!=null&&i.add(t.name)}}let a=(await x()).Query.new();a.setOutFields(Array.from(i)),a.setReturnGeometry(!!e.returnGeometry),a.setReturnZ(!!e.returnZ),a.setReturnM(!!e.returnM),a.setIds(new Uint32Array(n));let o=await(await this._getFile(t)).executeQuery(a,q,r),s=await o.next(r),l=0,u=[];for(;s!=null;){let e=new T(this._metadata,this._indexMap,s,t),n=new C(e,null,l++,!1);u.push(n),s=await o.next(r)}return X(u,this._queryEngineParams).executeQueryForOpaqueFeatures(e,r)}async _getRequiredFields(e){let t=new Set;if(e.outStatistics)for(let n of A(this._fieldsIndex,e.outStatistics,e.groupByFieldsForStatistics))t.add(n);else if(e.outFields)for(let n of e.outFields)t.add(n);return(t.has(`*`)?this._fieldsIndex.fields.map(e=>e.name):Array.from(t)).filter(e=>this._indexMap[e]!=null)}_tryGetGeneralizedGeometryResolution(e){if(!this._displayOptimization)return null;let t=e.outSR??this._queryEngineParams.spatialReference;if(!y(t)&&!b(t))return null;let n=e.quantizationParameters?.tolerance??e.maxAllowableOffset;return n?this._sourceResolution(n,t):null}_sourceResolution(e,t){let n=this._queryEngineParams.spatialReference,r=l(t)/l(n)*e;return!Number.isFinite(r)||r<=0?null:r}}function pe(e){switch(e){case`fullText`:case`having`:case`timeExtent`:case`historicMoment`:case`aggregateIds`:case`uniqueIds`:case`gdbVersion`:case`objectIds`:case`where`:case`geometry`:case`resultOffset`:case`resultRecordCount`:return!0;default:return!1}}function me(e){switch(e){case`fullText`:case`having`:case`timeExtent`:case`historicMoment`:case`aggregateIds`:case`uniqueIds`:case`gdbVersion`:case`objectIds`:case`where`:case`geometry`:return!0;default:return!1}}function he(e){switch(e){case`fullText`:case`having`:case`timeExtent`:return!0;case`historicMoment`:case`aggregateIds`:case`uniqueIds`:case`gdbVersion`:case`objectIds`:case`where`:case`resultOffset`:case`geometry`:case`resultRecordCount`:return!1}return!1}function J(e){for(let t in e){let n=t;if(pe(n)&&e[n]!==null)return!0}return!1}function ge(e){for(let t in e){let n=t;if(me(n)&&e[n]!==null)return!0}return!1}function _e(e){for(let t in e){let n=t;if(he(n)&&e[n]!==null)return!0}return!1}function ve(e,t){return!!e.outStatistics?.length&&!J(e)&&!e.groupByFieldsForStatistics?.length&&!e.orderByFields?.length&&!e.returnDistinctValues&&!e.returnAggIds&&e.outStatistics.every(e=>ye(e,t))}function ye(e,t){switch(e.statisticType){case`count`:return e.onStatisticField===`1`||t.get(e.onStatisticField)!=null;case`min`:case`max`:{let n=t.get(e.onStatisticField);return n!=null&&ae(n)}default:return!1}}function be(e,t){let n=e.statisticType===`exceedslimit`?null:t.get(e.onStatisticField),r=(e.statisticType===`min`||e.statisticType===`max`)&&n?.type===`esriFieldTypeDate`?n.type:`esriFieldTypeDouble`;return{name:e.outStatisticFieldName,alias:e.outStatisticFieldName,type:r}}function xe(e,t){switch(e.statisticType){case`count`:return Se(e,t);case`min`:return Y(e,t,Math.min);case`max`:return Y(e,t,Math.max);default:return{available:!1,value:null}}}function Se(e,t){if(e.statisticType!==`count`)return{available:!1,value:null};if(e.onStatisticField===`1`)return{available:!0,value:t.reduce((e,t)=>e+t.statistics.rowCount,0)};let n=0;for(let r of t){let t=r.statistics.statistics.get(e.onStatisticField);if(t==null||t.nullCount==null)return{available:!1,value:null};n+=r.statistics.rowCount-t.nullCount}return{available:!0,value:n}}function Y(e,t,n){if(e.statisticType!==`min`&&e.statisticType!==`max`)return{available:!1,value:null};let r=null,i=e.statisticType===`min`?`minValue`:`maxValue`;for(let a of t){let t=a.statistics.statistics.get(e.onStatisticField);if(t==null)return{available:!1,value:null};switch(t.type){case`null-only`:continue;case`unknown`:return{available:!1,value:null};case`bounds`:{let e=Ce(t[i]);if(e==null)return{available:!1,value:null};r=r==null?e:n(r,e);break}}}return{available:!0,value:r}}function Ce(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function X(e,t){let n=new w;for(let t of e)n.insert(t);return new P({...t,featureStore:n})}function Z(e,t){return e.statistics.statistics.get(t.fieldName)??null}function we(e,t){return e.slice().sort((e,n)=>{let r=Q(e,t),i=Q(n,t);return r===i?0:r<i?-1:1})}function Q(e,t){let n=Z(e,t);return n?.type===`bounds`?n.maxValue-n.minValue:1/0}function $(e,t,n){let r=e?.featureCount,i=!1;return r!=null&&r<has(`parquetlayer-full-query-feature-count`)&&(i=!0),{analytics:{supportsCacheHint:!1},attachment:null,data:{isVersioned:!1,isBranchVersioned:!1,supportedCurveTypes:[],supportsAttachment:!1,supportsM:n,supportsTrueCurve:!1,supportsZ:t},metadata:{supportsAdvancedFieldProperties:!1},operations:{supportsCalculate:!1,supportsTruncate:!1,supportsValidateSql:!1,supportsAdd:!1,supportsDelete:!1,supportsEditing:!1,supportsChangeTracking:!1,supportsQuery:!0,supportsQueryBins:!1,supportsQueryPivot:!1,supportsQueryAnalytics:!1,supportsQueryAttachments:!1,supportsQueryTopFeatures:!1,supportsResizeAttachments:!1,supportsSync:!1,supportsUpdate:!1,supportsExceedsLimitStatistics:!1,supportsAsyncConvert3D:!1},query:{...F,maxRecordCount:q,supportsOrderBy:i,supportsDistinct:!0,supportsStatistics:!0,supportsSpatialAggregationStatistics:!1,supportedSpatialAggregationStatistics:{envelope:!1,centroid:!1,convexHull:!1}},queryAttributeBins:{supportsDate:!1,supportsFixedInterval:!1,supportsAutoInterval:!1,supportsFixedBoundaries:!1,supportsStackBy:!1,supportsSplitBy:!1,supportsSnapToData:!1,supportsReturnFullIntervalBin:!1,supportsFirstDayOfWeek:!1,supportsNormalization:!1},queryRelated:{supportsCount:!1,supportsOrderBy:!1,supportsPagination:!1,supportsCacheHint:!1},queryTopFeatures:{supportsCacheHint:!1},editing:{supportsDeleteByAnonymous:!1,supportsDeleteByOthers:!1,supportsGeometryUpdate:!1,supportsGlobalId:!1,supportsTrueCurveUpdate:!1,supportsTrueCurveUpdateByTrueCurveClientsOnly:!0,supportsReturnServiceEditsInSourceSpatialReference:!1,supportsRollbackOnFailure:!1,supportsUpdateByAnonymous:!1,supportsUpdateByOthers:!1,supportsUploadWithItemId:!1,supportsUpdateWithoutM:!1,supportsAsyncApplyEdits:!1,zDefault:void 0}}}function Te(e){return!!e.objectIds?.length||!!e.outStatistics||!!e.orderByFields?.length||!!e.returnDistinctValues}export{fe as default};
2
+ import{__addDisposableResource as e,__disposeResources as t}from"tslib";import n from"../../../../core/Error.js";import r from"../../../../core/Handles.js";import has from"../../../../core/has.js";import i from"../../../../core/Logger.js";import{onAbortOrThrow as a,throwIfAborted as o}from"../../../../core/promiseUtils.js";import{QueueProcessor as s}from"../../../../core/QueueProcessor.js";import{parseWhereClause as c}from"../../../../core/sql.js";import{getMetersPerUnitForSR as l}from"../../../../core/units.js";import{initializeProjection as u}from"../../../../geometry/projectionUtils.js";import d from"../../../../geometry/SpatialReference.js";import{set as f,create as p,expandWithAABB as m,expandWithRect as ee,negativeInfinity as h}from"../../../../geometry/support/aaBoundingBox.js";import{copy as g,create as te,expandWithRect as ne,negativeInfinity as re}from"../../../../geometry/support/aaBoundingRect.js";import{equals as ie}from"../../../../geometry/support/spatialReferenceUtils.js";import{loadParquetModule as _}from"../../../../libs/librust-parquet/loadParquetModule.js";import{utc as v}from"../../../../time/constants.js";import{FeatureStoreQueryAdapter as y}from"../../../../views/2d/layers/features/FeatureStoreQueryAdapter.js";import{FeatureSnapshotSourceChunk as b}from"../../../../views/2d/layers/features/sources/strategies/chunks/FeatureSnapshotSourceChunk.js";import{FeatureSourceChunkStore as x}from"../../../../views/2d/layers/features/sources/strategies/chunks/SourceChunkStore.js";import{FeatureMetadata as S}from"../../../../views/2d/layers/features/support/FeatureMetadata.js";import{FeatureSetReaderParquet as C}from"../../../../views/2d/layers/features/support/FeatureSetReaderParquet.js";import{canProjectParquetSpatialReference as w,normalizeParquetSpatialReferenceWkid as T,normalizeColumnPath as E,readParquetFileAttribute as ae}from"../../../parquet.js";import D from"../../../support/Field.js";import oe from"../../../support/FieldsIndex.js";import{isNumericField as se}from"../../../support/fieldUtils.js";import{fromParquetGeometryEncodingJSON as ce}from"../../../support/parquetEncodingUtils.js";import{completeParquetLayerInfo as le,fromParquetJSONGeometryType as ue,toParquetJSONGeometryType as O}from"../../../support/parquetUtils.js";import{getFieldNamesFromStatistics as k}from"../../data/attributeSupport.js";import{project as A}from"../../data/projectionSupport.js";import{getQueryResultExtent as j,getQueryBoundingRects as M,QueryEngine as N}from"../../data/QueryEngine.js";import{queryCapabilities as P}from"../../data/QueryEngineCapabilities.js";import{QueryEngineResult as F}from"../../data/QueryEngineResult.js";import{normalizeQueryLike as I}from"../../data/queryUtils.js";import{convertToGeometry as L}from"../../featureConversionUtils.js";import{createFileProvider as R}from"../parquet/createFileProvider.js";import{readFieldStatistic as z}from"../parquet/ParquetFileStatistics.js";import{createDrawingInfo as B}from"./clientSideDefaults.js";import{getParquetFileId as V,getParquetRowId as H,getParquetObjectId as U}from"./parquetIdUtils.js";const W=new y,G=`__OBJECTID`,K=8e3;class de{constructor(e,t){this._files=e,this._createFileStream=t,this._fileIndex=0,this._streamIndex=0,this._streams=[],this._pending=new Set,this._resolvedCount=0}async next(e){for(await this._fill(e);this._pending.size>0;){o(e),await this._fill(e);let t=await fe(this._pending);if(this._pending.delete(t.read),this._resolvedCount++,t.chunk!=null)return t.chunk}return null}async _fill(e){for(this._removeDone();this._pending.size<8;){let t=this._getOrCreateNextStream(e);if(t==null)return;this._pending.add(t.read(e))}}_getOrCreateNextStream(e){let t=this._resolvedCount>=8?8:2;if(this._fileIndex<this._files.length&&this._streams.length<t){let t=this._files[this._fileIndex++],n=new pe(t.id,this._createFileStream(t,e));return this._streams.push(n),n}return this._getNextStream()}_getNextStream(){let e=this._streams.length;for(let t=0;t<e;t++){let n=(this._streamIndex+t)%e,r=this._streams[n];if(r.canRead)return this._streamIndex=(n+1)%e,r}return null}_removeDone(){let e=this._streamIndex;for(let t=this._streams.length-1;t>=0;t--)this._streams[t].done&&(this._streams.splice(t,1),t<e&&e--);this._streamIndex=this._streams.length>0?e%this._streams.length:0}}function fe(e){return Promise.race(Array.from(e,async e=>({read:e,chunk:await e})))}class pe{constructor(e,t){this._fileId=e,this._stream=t,this._readCount=0,this._reachedEnd=!1}get canRead(){return!this._reachedEnd}get done(){return this._reachedEnd&&this._readCount===0}async read(e){this._readCount++;try{let t=await(await this._stream).next(e);return t==null?(this._reachedEnd=!0,null):{fileId:this._fileId,chunk:t}}finally{this._readCount--}}}class me{constructor(){this._hasZ=!1,this._hasM=!1,this._queue=new s({concurrency:4,process:(e,t)=>this._executeQuery(e,t)}),this._streams=new Map,this._streamIdCounter=0,this._indexMap={},this._handles=new r}async load(e){let t=e.spatialReference?d.fromJSON(e.spatialReference):void 0;this._customParameters=e.customParameters,this._loadParameters=e,await this._updateProvider(R(e.provider,null,()=>this._customParameters));let r=await this._provider.getMetadata(),a=await le(r,{fields:e.fields?.map(e=>D.fromJSON(e)),geometryEncoding:e.geometryEncoding?ce(e.geometryEncoding):null,geometryType:e.geometryType?ue(e.geometryType):null,displayOptimization:e.displayOptimization,spatialReference:t});if(this._hasZ=!!r?.hasZ,this._hasM=!!r?.hasM,!a.fields)throw new n(`parquet:unsupported`,`Fields must be defined`);let o;if(a.spatialReference&&a.geometryType){if(!a.spatialReference)throw new n(`parquet:unsupported`,`SpatialReference must be defined`);a.spatialReference.isGeographic&&!a.spatialReference.isWGS84&&(i.getLogger(`parquet:unsupported-projection`).warn(`Found a geographic projection that is not WGS84. Handling as WGS84.`,{spatialReference:a.spatialReference}),a.spatialReference=d.WGS84),o={geometry:a.geometryEncoding?{geometryType:O(a.geometryType),spatialReference:a.spatialReference.toJSON(),encoding:a.geometryEncoding.toJSON()}:null,displayOptimization:a.displayOptimization}}this.setCustomParameters(e.customParameters),this._displayOptimization=a.displayOptimization,await this._provider.updateGeometryInfo(o),this._capabilities=$(await this._getFileStatistics(),this._hasZ,this._hasM);let s=await this._provider.getFiles();if(!s.length)return{layerDefinition:{},capabilities:$(null,this._hasZ,this._hasM)};let c=await s[0].file;a.file=c;let{fields:l}=a;if(l==null)throw new n(`parquet-layer:missing-metadata`,`Unable to create parquet source: cannot infer fields`,l);l.push(new D({name:G,type:`oid`,alias:G}));for(let e of l){let t=c.getColumnId(e.name);t!=null&&(this._indexMap[e.name]=t)}let u=oe.fromLayerJSON({fields:l.map(e=>e.toJSON()),dateFieldsTimeReference:{timeZoneIANA:`UTC`}});this._fieldsIndex=u;let f=O(a.geometryType??`point`);return this._metadata=S.createFeature({fieldsIndex:u.toJSON(),geometryType:f,hasZ:this._hasZ,hasM:this._hasM,featureIdInfo:{type:`object-id`,fieldName:G},subtypes:null,subtypeField:null,types:null,typeIdField:null,globalIdField:null,spatialReference:a.spatialReference,outSpatialReference:null,attributeSpatialReference:null,timeInfo:null,timeReferenceUnknownClient:null,dateFieldsTimeZone:v}),this._queryEngineParams={fieldsIndex:this._metadata.fieldsIndex,geometryType:f,featureIdInfo:{type:`object-id`,fieldName:G},hasM:this._hasM,hasZ:this._hasZ,spatialReference:a.spatialReference?.toJSON()??{wkid:4326},aggregateAdapter:null,timeInfo:null,definitionExpression:null},this._fullExtent=r?.extent?r.extent:await this._tryDeriveParquetFullExtent(a),{capabilities:this._capabilities,layerDefinition:{fields:a.fields?.map(e=>e.toJSON()),drawingInfo:B(f),extent:this._fullExtent??void 0,geometryType:f,hasZ:this._hasZ,hasM:this._hasM,geometryEncoding:a.geometryEncoding?.toJSON(),displayOptimization:a.displayOptimization}}}destroy(){this._provider.destroy(),this._queue.destroy();for(let{handle:e}of this._streams.values())e.remove();this._streams.clear(),this._indexMap={},this._handles.removeAll()}async reload(e){this.destroy(),await this.load(e)}set remoteClient(e){this._source=e.createInvokeProxy(``)}setCustomParameters(e){this._customParameters=e}getIndexMap(){return this._indexMap}async updateFileProvider(e){this._loadParameters={...this._loadParameters,provider:e};let t=R(e,this._provider.getGeometryInfo(),()=>this._customParameters);await this._updateProvider(t)}async getDiagnosticsSnapshot(){let e=await this._provider.getFiles();return{files:await Promise.all(e.map(e=>e.getDiagnosticsSnapshot()))}}async getColumnIndex(e){return(await this._getFileInfoById(e.fileId)).getColumnIndex(e.rowGroupIndex,e.columnIndex)}async getOffsetIndex(e){return(await this._getFileInfoById(e.fileId)).getOffsetIndex(e.rowGroupIndex,e.columnIndex)}async queryFeatures(e,t){let n=await I(e,null,this._queryEngineParams.spatialReference);return this._validateQuery(n),Ee(n)||(n.resultRecordCount=n.resultRecordCount?Math.min(n.resultRecordCount,K):K,n.resultOffset=n.resultOffset??0),n.outStatistics?this._queryStatistics(n,t):(n.returnDistinctValues&&(n.returnGeometry=void 0),(await this._enqueueQuery(n,t)).createQueryResponse())}async queryFeatureCount(e,t){let n=await I(e,null,this._queryEngineParams.spatialReference);return this._validateQuery(n),!q(n)&&!n.returnDistinctValues&&!n.groupByFieldsForStatistics?.length&&!n.outStatistics?.length?this._getFeatureCount():(n.returnDistinctValues||(n.outFields=void 0),n.returnGeometry=void 0,(await this._enqueueQuery(n,t)).createQueryResponseForCount())}async queryObjectIds(e,t){let n=await I(e,null,this._queryEngineParams.spatialReference);return this._validateQuery(n),q(n)?(n.resultRecordCount=n.resultRecordCount?Math.min(n.resultRecordCount,8e3):8e3,n.resultOffset=n.resultOffset??0,n.returnGeometry=void 0,n.outFields=void 0,n.returnDistinctValues=void 0,(await this._enqueueQuery(n,t)).items.map(e=>e.getObjectId())):Array.from({length:await this._getFeatureCount()},(e,t)=>t)}async queryAttributeBins(e,t={}){throw new n(`parquet:unsupported`,`queryAttributeBins not supported.`)}async queryExtent(e,t){let n=await I(e,null,this._queryEngineParams.spatialReference);this._validateQuery(n);let r=n.outSR??this._queryEngineParams.spatialReference;if(this._fullExtent&&!q(n)){let e=this._fullExtent;return await u(e.spatialReference,n.outSR),{count:await this._getFeatureCount(),extent:n.outSR?A(e,n.outSR):e}}n.returnGeometry=!0,n.outFields=void 0;let i=f(p(),h),a=p(),o=await this._enqueueQuery(n,t),s=0;for(let e of o.items)e.getBounds(a)&&(m(i,a),s+=1);let c=j(i,r,r,r,!1);return{count:s,extent:c}}async queryStream(e,t){if(!t.signal)throw Error(`InternalError: AbortSignal must be passed`);let n=await this._getCandidateFiles(e),r=new de(n,async(t,n)=>{let r=await t.file,i=await this._createParquetDisplayQuery(r,t.id,e);return r.executeQuery(i,K,n)}),i=this._streamIdCounter++,o=a(t.signal,e=>{let t=this._streams.get(i);t!=null&&(t.handle.remove(),this._streams.delete(i))});return this._streams.set(i,{stream:r,handle:o}),i}async getStreamNext(e,t){if(!t.signal)throw Error(`InternalError: AbortSignal must be passed`);let n=this._streams.get(e);if(!n)return{result:null};let r=await n.stream.next(t.signal);if(r==null)return n.handle.remove(),this._streams.delete(e),{result:null};let i=r.chunk.serialize().buffer,a={fileId:r.fileId,buffer:i};return i instanceof ArrayBuffer?{result:a,transferList:[i]}:{result:a}}async getStreamNextFeatures(e,t){let{result:n}=await this.getStreamNext(e,t);if(n==null)return null;let r=(await _()).ParquetChunk.deserialize(new Uint8Array(n.buffer)),i=new C(this._metadata,this._indexMap,r,n.fileId),a=[];for(;i.next();){let e=L(i.readGeometryWorldSpace(),i.geometryType,i.hasZ,i.hasM),t=i.readAttributes();a.push({attributes:t,geometry:e})}return{features:a}}async createPatch(e,t,n,r,i){if(!i.signal)throw Error(`InternalError: AbortSignal must be passed`);return(await(await(await this._getFileInfoById(e)).file).createChunkPatch(t,n,r,i.signal)).serialize().buffer}async _updateProvider(e){let t=this._provider;this._handles.removeAll(),this._provider=e,this._handles.add([e.events.on(`rangeRead`,e=>{this._source.onRangeRead(e)}),e.events.on(`sourceChanged`,async()=>{await this.reload(this._loadParameters),await this._source.onSourceChange()})]),await t?.destroy()}async _getCandidateFiles(e){let t=await this._provider.getFiles(),n=await this._getSpatialFilePruning(e);if(n==null)return t;let r=t.filter(e=>this._mayIncludeFileForSpatialPruning(e,n));return n.type===`xz`?Te(r,n):r}async _queryStatistics(e,t){let n=await I({...e},null,this._queryEngineParams.spatialReference);if(n.returnGeometry=void 0,be(n,this._fieldsIndex)){let e=await this._getStatisticsFromFiles(n);if(e)return e}return(await this._enqueueQuery(n,t)).createQueryResponse()}async _getStatisticsFromFiles(e){let t=await this._provider.getFiles(),n={},r=[];for(let i of e.outStatistics??[]){let e=Ce(i,t);if(!e.available)return null;n[i.outStatisticFieldName]=e.value,r.push(Se(i,this._fieldsIndex))}return{fields:r,features:[{attributes:n}]}}async _getSpatialFilePruning(e){if(e.type!==`tile`&&(e.type!==`arcade`||e.extent==null))return null;let t=this._displayOptimization?.index;if(t==null)return null;let n={wkid:t.wkid};if(!w(n,e.outSpatialReference))return null;let r=T(n),i=T(e.outSpatialReference),a=await _();switch(t.type){case`xz`:return{type:`xz`,fieldName:E(t.code),intersects:(n,o)=>a.queryIntersectsXZStatistics(t.fullExtent,e.extent,i,r,t.maxLevel,n,o)};case`z`:return{type:`xy`,xFieldName:E(t.xColumn),yFieldName:E(t.yColumn),intersects:(t,n,o,s)=>a.queryIntersectsXYStatistics(e.extent,i,r,t,n,o,s)}}}_mayIncludeFileForSpatialPruning(e,t){switch(t.type){case`xz`:{let n=Z(e,t);return n?.type===`null-only`?!1:n?.type!==`bounds`||t.intersects(n.minValue,n.maxValue)}case`xy`:{let n=e.statistics.statistics.get(t.xFieldName),r=e.statistics.statistics.get(t.yFieldName);return n?.type===`null-only`||r?.type===`null-only`?!1:n?.type!==`bounds`||r?.type!==`bounds`||t.intersects(n.minValue,n.maxValue,r.minValue,r.maxValue)}}}async _tryDeriveParquetFullExtent(n){if(!n.spatialReference)return null;if(this._fullExtent==null&&n.geometryEncoding?.type===`location`){let r=await this._provider.getFiles(),{xField:i,yField:a}=n.geometryEncoding,o=f(p(),h),s=!1;for(let n of r){let r=await n.file;for(let n of r.rowGroups()){let r={stack:[],error:void 0,hasError:!1};try{let t=e(r,n.columnDescriptorForAttribute(i),!1),c=e(r,n.columnDescriptorForAttribute(a),!1),l=z(t),u=z(c);if(l?.type===`bounds`&&u?.type===`bounds`){let e=[l.minValue,u.minValue,l.maxValue,u.maxValue];ee(o,e),s=!0}n.free()}catch(e){r.error=e,r.hasError=!0}finally{t(r)}}}return s?{xmin:o[0],ymin:o[1],xmax:o[3],ymax:o[4],spatialReference:n.spatialReference?.toJSON()}:null}return null}async _getFileInfoById(e){let t=await this._provider.getFiles();for(let n of t)if(n.id===e)return n;throw Error(`InternalError: File ${e} does not exist`)}async _getFileStatistics(){return{featureCount:await this._getFeatureCount(),byteLength:await this._getByteLength()}}async _getFile(e){return(await this._getFileInfoById(e)).file}async _createParquetQuery(e,t,n,r,i){let a=(await _()).Query.new();n!=null&&a.setPreFilterStart(n),r!=null&&a.setPreFilterCount(r),i!=null&&a.setPostFilterCount(i);let o=await this._getRequiredFields(e);a.setOutFields(o),(e.geometry||e.returnGeometry)&&a.setReturnGeometry(!0),a.setReturnZ(!!e.returnZ),a.setReturnM(!!e.returnM);let s=this._tryGetGeneralizedGeometryResolution(e);s!=null&&a.setSourceResolution(s);let c=e.geometry?.spatialReference??this._queryEngineParams.spatialReference;if(e.geometry&&w(this._queryEngineParams.spatialReference,c)){let t=T(c),n=g(te(),re);for(let t of M(e.geometry))ne(n,t);a.setOutSpatialReference(t),a.setExtent({xmin:n[0],ymin:n[1],xmax:n[2],ymax:n[3]})}if(e.where){let{id:n,file:r}=t;await this._setWhereClause(a,await r,n,e.where)}return a}async _createParquetDisplayQuery(e,t,n){let r=(await _()).Query.new();if(n.type===`tile`){r.setExtent(n.extent),r.setQuantizationTransform(n.transform);let e=this._sourceResolution(n.resolution,n.outSpatialReference);e!=null&&r.setSourceResolution(e)}else n.type===`arcade`&&n.extent!=null&&r.setExtent(n.extent);r.setOutFields(n.outFields.filter(e=>this._indexMap[e]!=null));let i=T(n.outSpatialReference);return r.setOutSpatialReference(i),r.setReturnGeometry(n.returnGeometry),r.setReturnZ(n.returnZ),r.setReturnM(n.returnM),n.where&&await this._setWhereClause(r,e,t,n.where),r}async _getFeatureCount(){return(await this._provider.getFiles()).map(e=>e.statistics.rowCount).reduce((e,t)=>e+t,0)}async _getByteLength(){return(await this._provider.getFiles()).map(e=>e.statistics.byteSize).reduce((e,t)=>e+t,0)}_validateQuery(e){if(!this._capabilities.query.supportsStatistics&&e.outStatistics)throw new n(`parquet:unsupported`,`Statistics queries are not supported`,{query:e});if(!this._capabilities.query.supportsOrderBy&&e.orderByFields?.length)throw new n(`parquet:unsupported`,`Queries using orderBy are not supported`,{query:e});if(!this._capabilities.query.supportsDistinct&&e.returnDistinctValues)throw new n(`parquet:unsupported`,`Queries using returnDistinctValues are not supported`,{query:e})}async _setWhereClause(e,t,r,i){let a=this._indexMap,o=this._fieldsIndex,s={getAttribute(e,n){let i=a[n];if(i==null){if(o.get(n)?.name===`__OBJECTID`){let t=e.row+e.rowGroupStart;return U(r,t)}return null}let s=o.get(n);return ae(t,e.rowGroup,e.row,i,s.type)}},l=await c(i,this._fieldsIndex);if(!l.isStandardized)throw new n(`sql-parse-error`,`expression is not standardized`);let u=(e,t,n)=>l.testFeatureCompiled({rowGroup:e,row:t,rowGroupStart:n},s,null),d=l.fieldNames.map(e=>o.get(e)).filter(e=>e&&this._indexMap[e?.name]!=null);e.setWhere(i),e.setWhereEvaluator(u),e.setWhereFields(d.map(e=>e.name))}async*_streamFeatures(e,t,n,r,i){let a=await this._provider.getFiles(),o=0;for(let s of a){let a=o,c=o+s.statistics.rowCount;if(o+=s.statistics.rowCount,t!=null&&t>=c)continue;let l=t==null?null:Math.max(t-a,0),u=n;if(n!=null){let e=t??0,r=e+n;u=Math.max(Math.min(r,c)-Math.max(e,a),0)}if(u===0)continue;let d=await this._createParquetQuery(e,s,l,u,r),f=await(await s.file).executeQuery(d,K),p=async()=>{let e=await f.next(i);if(!e)return null;let t=new C(this._metadata,this._indexMap,e,s.id);return X([new b(t,null,0,!1)],this._queryEngineParams)},m=await p();for(;m!=null;)yield m,m=await p()}}async _queryFeaturesWithQueryEnginePagination(e,t){let n=[],r=this._streamFeatures(e,null,null,null,t),i=await r.next();for(;!i.done;){let a=await i.value.executeQueryForOpaqueFeatures({...e,where:void 0},t);for(let e of a)n.push(e);i=await r.next()}return n}async _queryFeaturesWithUpfrontPagination(e,t){let n=e.resultOffset??0,r=e.resultRecordCount??K,i,a,o;ve(e)?ye(e)||(o=n+r):(n&&=(i=n,0),a=e.resultRecordCount);let s=[],c=this._streamFeatures(e,i,a,o,t),l=await c.next();for(;!l.done&&r>0;){let i=await l.value.executeQueryForOpaqueFeatures({...e,where:void 0},t);for(let e of i)if(n>0)n--;else if(s.push(e),--r<=0)return s;l=await c.next()}return s}_enqueueQuery(e,t){return this._queue.push(e,t)}async _executeQuery(e,t){if(e.objectIds?.length){let n=new Map;for(let t of e.objectIds){let e=V(t),r=H(t),i=n.get(e);i||(i=[],n.set(e,i)),i.push(r)}let r=[];for(let[i,a]of n.entries()){let n=await this._executeFileIdQuery(e,i,a,t);for(let e of n)r.push(e)}return new F(r,e,{fieldsIndex:this._fieldsIndex,geometryType:this._metadata.geometryType,spatialReference:this._queryEngineParams.spatialReference,hasM:this._hasM,hasZ:this._hasZ,featureAdapter:W,featureIdInfo:this._queryEngineParams.featureIdInfo})}if(e.where===`1=1`&&(e.where=null),e.resultOffset??=0,e.resultRecordCount??=await this._getFeatureCount(),e.resultRecordCount>2e7&&!(this._displayOptimization&&e.geometry))throw new n(`parquet:cannot-execute-query`,`Unable to execute query, dataset is too large.`);let r=!!e.orderByFields?.length||!!e.outStatistics?.length||!!e.returnDistinctValues,i=r?await this._queryFeaturesWithQueryEnginePagination(e,t):await this._queryFeaturesWithUpfrontPagination(e,t);return r||(e.resultOffset=0),new F(i,e,{fieldsIndex:this._fieldsIndex,geometryType:this._metadata.geometryType,spatialReference:this._queryEngineParams.spatialReference,hasM:this._hasM,hasZ:this._hasZ,featureAdapter:W,featureIdInfo:this._queryEngineParams.featureIdInfo})}async _executeFileIdQuery(e,t,n,r){let i=new Set(await this._getRequiredFields(e));if(e.where){let t=await c(e.where,this._fieldsIndex);for(let e of t.fieldNames){let t=this._fieldsIndex.get(e);t&&this._indexMap[t.name]!=null&&i.add(t.name)}}let a=(await _()).Query.new();a.setOutFields(Array.from(i)),a.setReturnGeometry(!!e.returnGeometry),a.setReturnZ(!!e.returnZ),a.setReturnM(!!e.returnM),a.setIds(new Uint32Array(n));let o=await(await this._getFile(t)).executeQuery(a,K,r),s=await o.next(r),l=0,u=[];for(;s!=null;){let e=new C(this._metadata,this._indexMap,s,t),n=new b(e,null,l++,!1);u.push(n),s=await o.next(r)}return X(u,this._queryEngineParams).executeQueryForOpaqueFeatures(e,r)}async _getRequiredFields(e){let t=new Set;if(e.outStatistics)for(let n of k(this._fieldsIndex,e.outStatistics,e.groupByFieldsForStatistics))t.add(n);else if(e.outFields)for(let n of e.outFields)t.add(n);return(t.has(`*`)?this._fieldsIndex.fields.map(e=>e.name):Array.from(t)).filter(e=>this._indexMap[e]!=null)}_tryGetGeneralizedGeometryResolution(e){if(!this._displayOptimization)return null;let t=e.outSR??this._queryEngineParams.spatialReference;if(!w(this._queryEngineParams.spatialReference,t))return null;let n=e.quantizationParameters?.tolerance??e.maxAllowableOffset;return n?this._sourceResolution(n,t):null}_sourceResolution(e,t){let n=this._queryEngineParams.spatialReference;if(ie(n,t))return e;let r=l(t)/l(n)*e;return!Number.isFinite(r)||r<=0?null:r}}function he(e){switch(e){case`fullText`:case`having`:case`timeExtent`:case`historicMoment`:case`aggregateIds`:case`uniqueIds`:case`gdbVersion`:case`objectIds`:case`where`:case`geometry`:case`resultOffset`:case`resultRecordCount`:return!0;default:return!1}}function ge(e){switch(e){case`fullText`:case`having`:case`timeExtent`:case`historicMoment`:case`aggregateIds`:case`uniqueIds`:case`gdbVersion`:case`objectIds`:case`where`:case`geometry`:return!0;default:return!1}}function _e(e){switch(e){case`fullText`:case`having`:case`timeExtent`:return!0;case`historicMoment`:case`aggregateIds`:case`uniqueIds`:case`gdbVersion`:case`objectIds`:case`where`:case`resultOffset`:case`geometry`:case`resultRecordCount`:return!1}return!1}function q(e){for(let t in e){let n=t;if(he(n)&&e[n]!==null)return!0}return!1}function ve(e){for(let t in e){let n=t;if(ge(n)&&e[n]!==null)return!0}return!1}function ye(e){for(let t in e){let n=t;if(_e(n)&&e[n]!==null)return!0}return!1}function be(e,t){return!!e.outStatistics?.length&&!q(e)&&!e.groupByFieldsForStatistics?.length&&!e.orderByFields?.length&&!e.returnDistinctValues&&!e.returnAggIds&&e.outStatistics.every(e=>xe(e,t))}function xe(e,t){switch(e.statisticType){case`count`:return e.onStatisticField===`1`||t.get(e.onStatisticField)!=null;case`min`:case`max`:{let n=t.get(e.onStatisticField);return n!=null&&se(n)}default:return!1}}function Se(e,t){let n=e.statisticType===`exceedslimit`?null:t.get(e.onStatisticField),r=(e.statisticType===`min`||e.statisticType===`max`)&&n?.type===`esriFieldTypeDate`?n.type:`esriFieldTypeDouble`;return{name:e.outStatisticFieldName,alias:e.outStatisticFieldName,type:r}}function Ce(e,t){switch(e.statisticType){case`count`:return we(e,t);case`min`:return J(e,t,Math.min);case`max`:return J(e,t,Math.max);default:return{available:!1,value:null}}}function we(e,t){if(e.statisticType!==`count`)return{available:!1,value:null};if(e.onStatisticField===`1`)return{available:!0,value:t.reduce((e,t)=>e+t.statistics.rowCount,0)};let n=0;for(let r of t){let t=r.statistics.statistics.get(e.onStatisticField);if(t==null||t.nullCount==null)return{available:!1,value:null};n+=r.statistics.rowCount-t.nullCount}return{available:!0,value:n}}function J(e,t,n){if(e.statisticType!==`min`&&e.statisticType!==`max`)return{available:!1,value:null};let r=null,i=e.statisticType===`min`?`minValue`:`maxValue`;for(let a of t){let t=a.statistics.statistics.get(e.onStatisticField);if(t==null)return{available:!1,value:null};switch(t.type){case`null-only`:continue;case`unknown`:return{available:!1,value:null};case`bounds`:{let e=Y(t[i]);if(e==null)return{available:!1,value:null};r=r==null?e:n(r,e);break}}}return{available:!0,value:r}}function Y(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function X(e,t){let n=new x;for(let t of e)n.insert(t);return new N({...t,featureStore:n})}function Z(e,t){return e.statistics.statistics.get(t.fieldName)??null}function Te(e,t){return e.slice().sort((e,n)=>{let r=Q(e,t),i=Q(n,t);return r===i?0:r<i?-1:1})}function Q(e,t){let n=Z(e,t);return n?.type===`bounds`?n.maxValue-n.minValue:1/0}function $(e,t,n){let r=e?.featureCount,i=!1;return r!=null&&r<has(`parquetlayer-full-query-feature-count`)&&(i=!0),{analytics:{supportsCacheHint:!1},attachment:null,data:{isVersioned:!1,isBranchVersioned:!1,supportedCurveTypes:[],supportsAttachment:!1,supportsM:n,supportsTrueCurve:!1,supportsZ:t},metadata:{supportsAdvancedFieldProperties:!1},operations:{supportsCalculate:!1,supportsTruncate:!1,supportsValidateSql:!1,supportsAdd:!1,supportsDelete:!1,supportsEditing:!1,supportsChangeTracking:!1,supportsQuery:!0,supportsQueryBins:!1,supportsQueryPivot:!1,supportsQueryAnalytics:!1,supportsQueryAttachments:!1,supportsQueryTopFeatures:!1,supportsResizeAttachments:!1,supportsSync:!1,supportsUpdate:!1,supportsExceedsLimitStatistics:!1,supportsAsyncConvert3D:!1},query:{...P,maxRecordCount:K,supportsOrderBy:i,supportsDistinct:!0,supportsStatistics:!0,supportsSpatialAggregationStatistics:!1,supportedSpatialAggregationStatistics:{envelope:!1,centroid:!1,convexHull:!1}},queryAttributeBins:{supportsDate:!1,supportsFixedInterval:!1,supportsAutoInterval:!1,supportsFixedBoundaries:!1,supportsStackBy:!1,supportsSplitBy:!1,supportsSnapToData:!1,supportsReturnFullIntervalBin:!1,supportsFirstDayOfWeek:!1,supportsNormalization:!1},queryRelated:{supportsCount:!1,supportsOrderBy:!1,supportsPagination:!1,supportsCacheHint:!1},queryTopFeatures:{supportsCacheHint:!1},editing:{supportsDeleteByAnonymous:!1,supportsDeleteByOthers:!1,supportsGeometryUpdate:!1,supportsGlobalId:!1,supportsTrueCurveUpdate:!1,supportsTrueCurveUpdateByTrueCurveClientsOnly:!0,supportsReturnServiceEditsInSourceSpatialReference:!1,supportsRollbackOnFailure:!1,supportsUpdateByAnonymous:!1,supportsUpdateByOthers:!1,supportsUploadWithItemId:!1,supportsUpdateWithoutM:!1,supportsAsyncApplyEdits:!1,zDefault:void 0}}}function Ee(e){return!!e.objectIds?.length||!!e.outStatistics||!!e.orderByFields?.length||!!e.returnDistinctValues}export{me as default};
package/layers/parquet.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
- import e from"../core/Error.js";import t from"../core/Logger.js";import{loadParquetModule as n}from"../libs/librust-parquet/loadParquetModule.js";import{latitudeFieldNames as r,longitudeFieldNames as i}from"./support/locationUtils.js";const a=()=>t.getLogger(`esri.layers.ParquetLayer`),o=new Set([`uncompressed`,`snappy`,`gzip`]),s=new TextDecoder,c=new Set([`esriFieldTypeSmallInteger`,`esriFieldTypeInteger`,`esriFieldTypeBigInteger`,`esriFieldTypeSingle`,`esriFieldTypeDouble`,`esriFieldTypeLong`]);function l(t,n){switch(n){case`esriGeometryPoint`:return t.GeometryType.Point;case`esriGeometryPolygon`:case`polygon`:return t.GeometryType.Polygon;case`esriGeometryPolyline`:case`polyline`:return t.GeometryType.Polyline;case`esriGeometryMultipoint`:case`multipoint`:return t.GeometryType.Multipoint;default:throw new e(`parquet`,`Found unexpected GeometryType: ${n}`)}}function u(e,t){let n=t.encoding,r=l(e,t.geometryType),i=t.spatialReference.wkid;if(i==null)throw Error(`InternalError: Wkid must be defined.`);switch(n.type){case`wkb`:return e.GeometryField.fromWkb(n.field,i,r);case`location`:{let{yField:t,xField:a}=n;return e.GeometryField.fromLocation(t,a,i,r)}}}function d(e,t){let n=e.GeometryInfo.new();t.geometry&&n.setGeometry(u(e,t.geometry));let r=t.displayOptimization;if(r){let{index:t}=r;if(t.type===`z`){let r=e.DisplayOptimizationZBuilder.new();r.setCodeField(g(t.code)),r.setXColumn(g(t.xColumn)),r.setYColumn(g(t.yColumn)),t.zColumn!=null&&r.setZColumn(g(t.zColumn)),t.mColumn!=null&&r.setMColumn(g(t.mColumn)),r.setCooordinatePrecision(t.coordinatePrecision),r.setFullExtent(t.fullExtent),r.setSpatialReference(t.wkid,t.wkid==null?t.wkt:void 0),r.setHasZ(!!t.zColumn),r.setHasM(!!t.mColumn),t.zColumn&&r.setZColumn(g(t.zColumn)),t.mColumn&&r.setMColumn(g(t.mColumn)),n.setOptmizationZ(r)}if(t.type===`xz`){let r=l(e,t.geometryType),i=e.DisplayOptimizationXZBuilder.new();i.setCodeField(g(t.code)),i.setEncoding(t.encoding),i.setFullExtent(t.fullExtent),i.setGeometryType(r),i.setSpatialReference(t.wkid,t.wkid==null?t.wkt:void 0),i.setMaxLevel(t.maxLevel),i.setHasZ(t.hasZ??!1),i.setHasM(t.hasM??!1);for(let n of t.levels??[]){let t=new Float64Array(n.transform.translate),r=new Float64Array(n.transform.scale),a=g(n.column);i.addLevel(e.MultiscaleGeometryField.new(n.level,n.resolution,a,t,r))}n.setOptmizationXZ(i)}}return n}async function f(t,r){let i=await n(),a=r.geometryInfo?d(i,r.geometryInfo):null,o=r.provider.fetchRange.bind(r.provider),s=r.provider.fetchLength.bind(r.provider);try{return await i.ParquetFile.fromUrl(t,o,s,a)}catch(t){throw new e(`parquet`,`Failed to parse file`,{error:t})}}function p(e){let t=e.keyValueMetadata(`geo`);return t==null?null:JSON.parse(t)}function m(t){if(t.keyValueMetadata(`esri`))throw new e(`parquet:unsupported`,`File was created using an unsupported experimental display index. Please regenerate the file.`);let n=t.keyValueMetadata(`geodisplay`);if(n!=null)return{present:!0,optimization:h({index:JSON.parse(n)})};let r=t.keyValueMetadata(`org.apache.spark.sql.parquet.row.metadata`);if(r!=null){let e=JSON.parse(r);for(let t of e.fields)if(t.metadata!=null&&x(t.metadata)){if(!S(t.metadata))return a().warn(`parquet:protocol-violation`,`Ignoring display optimization, found invalid column path`,{index:t.metadata}),{present:!0,optimization:null};let e=y(t.metadata,t.name);return e==null?(a().warn(`parquet:protocol-violation`,`Ignoring display optimization, Spark display column paths must be non-empty strings`,{index:t.metadata}),{present:!0,optimization:null}):{present:!0,optimization:h({index:e})}}}return{present:!1,optimization:null}}function h(e){if(!S(e.index))return a().warn(`parquet:protocol-violation`,`Ignoring display optimization, found invalid column path`,{index:e.index}),null;if(e.index.type===`xz`&&(e.index.geometryType=G(e.index.geometryType),e.index.encoding===`esri-pbf`&&(e.index.encoding=`esriPBF`),e.index.encoding!==`esriPBF`))return a().warn(`parquet:unsupported`,`Encoding for display index must be of type esriPBF, but found ${e.index.encoding}`),null;let{xmin:t,ymin:n,xmax:r,ymax:i}=e.index.fullExtent;return!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)?(a().warn(`parquet:protocol-violation`,`Ignoring display optimization, found bad extent`,{index:e.index}),null):e}function g(e){return Array.isArray(e)?e.join(`.`):e}function _(e,t,n,r,i){let a=I(e.readAttribute(t,n),r);return!i||a==null?a:r===`esriFieldTypeDate`?new Date(a):a}function v(e,t,n,r,i){return I(e.readAttribute(t,n,r),i)}function y(e,t){if(e.type===`z`){let n=b(e.code,t),r=b(e.xColumn,t),i=b(e.yColumn,t),a=e.zColumn==null?e.zColumn:b(e.zColumn,t),o=e.mColumn==null?e.mColumn:b(e.mColumn,t);return n==null||r==null||i==null||a===null||o===null?null:{...e,code:n,xColumn:r,yColumn:i,...a==null?{}:{zColumn:a},...o==null?{}:{mColumn:o}}}let n=b(e.code,t),r=[];for(let n of e.levels){let e=b(n.column,t);if(e==null)return null;r.push({...n,column:e})}return n==null?null:{...e,code:n,levels:r}}function b(e,t){return typeof e==`string`&&e.length>0?[t,e]:null}function x(e){return typeof e==`object`&&!!e&&`type`in e&&(e.type===`z`||e.type===`xz`)}function S(e){return e.type===`z`?C(e.code)&&C(e.xColumn)&&C(e.yColumn)&&(e.zColumn==null||C(e.zColumn))&&(e.mColumn==null||C(e.mColumn)):C(e.code)&&Array.isArray(e.levels)&&e.levels.every(e=>typeof e==`object`&&!!e&&`column`in e&&C(e.column))}function C(e){return typeof e==`string`&&e.length>0||Array.isArray(e)&&e.length===2&&e.every(e=>typeof e==`string`&&e.length>0)}function w(e){if(e==null)return null;let t=e.ordering,n=e.lod;if(t==null&&n==null)return null;if(t?.type!==`xz`||n==null||t.geometry_column!==e.primary_column||n.geometry_column!==e.primary_column||t.geometry_column!==n.geometry_column||t.max_level!==20||!M(t.extent)||n.encoding!==`pbf`)return T(e,`ordering and lod must form a valid primary-column XZ pair`);let r=e.columns[e.primary_column],i=E(r);if(i==null||!D(n.orientation,i.geometryType))return T(e,`geometry type, dimensions, or LOD orientation is invalid`);let a=O(n.levels),o=K(r)?.wkid;if(a==null||o==null)return T(e,`LOD levels or spatial reference is invalid`);let[s,c,l,u]=t.extent;return{index:{type:`xz`,code:`geokey`,wkid:o,wkt:null,encoding:`esriPBF`,fullExtent:{xmin:s,ymin:c,xmax:l,ymax:u},geometryType:i.geometryType,maxLevel:t.max_level,hasZ:i.hasZ,hasM:i.hasM,levels:a}}}function T(e,t){return a().warn(`parquet:protocol-violation`,`Ignoring GeoParquet ordering and LOD extensions: ${t}`,{lod:e.lod,ordering:e.ordering}),null}function E(e){if(e==null||e.geometry_types.length===0)return null;let t,n;for(let r of e.geometry_types){let e=/^(LineString|MultiLineString|Polygon|MultiPolygon)(?: (Z|M|ZM))?$/.exec(r);if(e==null)return null;let i=e[1]===`LineString`||e[1]===`MultiLineString`?`polyline`:`polygon`;if(t!=null&&t!==i||n!=null&&n!==(e[2]??``))return null;t=i,n=e[2]??``}return t==null||n==null?null:{geometryType:t,hasZ:n===`Z`||n===`ZM`,hasM:n===`M`||n===`ZM`}}function D(e,t){return t===`polygon`?e===`clockwise`:e==null}function O(e){if(!Array.isArray(e)||e.length===0)return null;let t=new Set,n=e.slice().sort((e,t)=>t.resolution-e.resolution),r=[];for(let[e,i]of n.entries()){if(!k(i.column)||!Number.isFinite(i.resolution)||i.resolution<=0||t.has(i.resolution)||!A(i.transform))return null;t.add(i.resolution),r.push({column:i.column,level:e,resolution:i.resolution,transform:i.transform})}return r}function k(e){return Array.isArray(e)&&e.length===2&&e[0]===`geolod`&&typeof e[1]==`string`&&e[1].length>0}function A(e){return j(e?.scale,!0)&&j(e?.translate,!1)}function j(e,t){return Array.isArray(e)&&e.length===4&&e.every(e=>typeof e==`number`&&Number.isFinite(e)&&(!t||e>0))}function M(e){return j(e,!1)&&e[0]<e[2]&&e[1]<e[3]}function N(e){P(e);let t=F(e),n=p(e),r=m(e),i=r.present?r.optimization:w(n),a=z(n,t),{hasZ:o,hasM:s}=U(n,i),c,l;if(a)switch(a.type){case`location`:l={wkid:4326},c=`esriGeometryPoint`;break;case`wkb`:if(n){let e=n.primary_column,t=n.columns[e];c=V(t),l=K(t)}}if(i){let e=i.index;!l&&e.wkid&&(l={wkid:e.wkid}),c||=e.type===`z`?`esriGeometryPoint`:W(e.geometryType)}let u=q(n,i,l);return{geoMetadata:n,displayOptimization:i,hasZ:o,hasM:s,geometryEncoding:a,geometryInfo:l&&c?{geometry:a?{geometryType:c,spatialReference:l,encoding:a}:null,displayOptimization:i}:null,geometryType:c,spatialReference:l,extent:u,fields:t}}function P(t){for(let n of t.compressionCodecs())if(!o.has(n))throw new e(`parquet:unsupported`,`Compression codec ${n} is unsupported. Must be of type ${Array.from(o).join(`,`)}`)}function F(e){return Array.from(e.fields(!1),e=>({name:e.name,alias:e.name,type:e.type}))}function I(e,t){return e==null?e:t===`esriFieldTypeDateOnly`?L(e):t===`esriFieldTypeTimeOnly`?R(e):t===`esriFieldTypeString`||t===`esriFieldTypeTimestampOffset`?s.decode(e):e}function L(e){return new Date(e*864e5).toISOString().slice(0,10)}function R(e){let t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=e%60;return`${t.toString().padStart(2,`0`)}:${n.toString().padStart(2,`0`)}:${r.toString().padStart(2,`0`)}`}function z(e,t){if(e!=null){let t=e.primary_column;return{type:`wkb`,field:t,orientation:e.columns[t].orientation===`counterclockwise`?`counter-clockwise`:null}}let n=B(t.filter(e=>c.has(e.type)).map(e=>e.name));return n.latitudeFieldName&&n.longitudeFieldName?{type:`location`,xField:n.longitudeFieldName,yField:n.latitudeFieldName}:null}function B(e){let t=e.map(e=>e.toLowerCase());return{longitudeFieldName:e[t.indexOf(i.find(e=>t.includes(e)))],latitudeFieldName:e[t.indexOf(r.find(e=>t.includes(e)))]}}function V(t){let{geometry_types:n}=t,r=new Set;for(let e of n){let t=H(e);t&&r.add(t)}if(r.size>1)throw new e(`parquet:unsupported`,`Parquet mixed geometry types are not supported`,{geometryTypes:r});return r.size===1?r.values().next().value:void 0}function H(e){switch(e.replace(/ (?:Z|M|ZM)$/u,``)){case`Point`:return`esriGeometryPoint`;case`Polygon`:case`MultiPolygon`:return`esriGeometryPolygon`;case`LineString`:case`MultiLineString`:return`esriGeometryPolyline`;case`MultiPoint`:return`esriGeometryMultipoint`;default:return null}}function U(e,t){let n=t?.index;if(n?.type===`z`)return{hasZ:n.zColumn!=null,hasM:n.mColumn!=null};if(n?.type===`xz`)return{hasZ:n.hasZ===!0,hasM:n.hasM===!0};let r=e?.columns[e.primary_column]?.geometry_types??[];return{hasZ:r.some(e=>/ (?:Z|ZM)$/u.test(e)),hasM:r.some(e=>/ (?:M|ZM)$/u.test(e))}}function W(e){switch(e){case`polygon`:return`esriGeometryPolygon`;case`polyline`:return`esriGeometryPolyline`;case`multipoint`:return`esriGeometryMultipoint`}}function G(t){switch(t.toLowerCase()){case`polygon`:return`polygon`;case`polyline`:return`polyline`;case`multipoint`:return`multipoint`;default:throw new e(`parquet:unsupported`,`Geometry type ${t} is unsupported`)}}function K(e){let t=e.crs?.id?.code;return typeof t==`number`?{wkid:t}:e.crs?.id?.authority===`OGC`&&t===`CRS84`?{wkid:4326}:void 0}function q(e,t,n){if(!n)return null;let r=(e?e.columns[e.primary_column]:null)?.bbox;if(r?.every(e=>Number.isFinite(e)))switch(r.length){case 4:return{xmin:r[0],ymin:r[1],xmax:r[2],ymax:r[3],spatialReference:n};case 6:return{xmin:r[0],ymin:r[1],xmax:r[3],ymax:r[4],spatialReference:n};default:a().warn(`parquet:protocol-violation`,`Invalid Geoparquet file. BoundingBox size must be 4 or 6.`,{geoMetadata:e})}let i=t?.index.fullExtent;return i?{...i,spatialReference:n}:null}export{f as createParquetFile,g as normalizeColumnPath,p as readGeoMetadata,N as readMetadata,_ as readParquetChunkAttribute,v as readParquetFileAttribute};
2
+ import e from"../core/Error.js";import t from"../core/Logger.js";import{isWebMercator as n,isGeographic as r}from"../geometry/support/spatialReferenceUtils.js";import{loadParquetModule as i}from"../libs/librust-parquet/loadParquetModule.js";import{latitudeFieldNames as a,longitudeFieldNames as o}from"./support/locationUtils.js";const s=()=>t.getLogger(`esri.layers.ParquetLayer`),c=new Set([`uncompressed`,`snappy`,`gzip`]),l=new TextDecoder,u=new Set([`esriFieldTypeSmallInteger`,`esriFieldTypeInteger`,`esriFieldTypeBigInteger`,`esriFieldTypeSingle`,`esriFieldTypeDouble`,`esriFieldTypeLong`]);function d(t,n){switch(n){case`esriGeometryPoint`:return t.GeometryType.Point;case`esriGeometryPolygon`:case`polygon`:return t.GeometryType.Polygon;case`esriGeometryPolyline`:case`polyline`:return t.GeometryType.Polyline;case`esriGeometryMultipoint`:case`multipoint`:return t.GeometryType.Multipoint;default:throw new e(`parquet`,`Found unexpected GeometryType: ${n}`)}}function f(e){let t=e.latestWkid??e.wkid;if(t==null)throw Error(`A spatial reference WKID is required.`);return n(e)?3857:r(e)?4326:t}function p(e,t){if((e.latestWkid??e.wkid)==null||(t.latestWkid??t.wkid)==null)return!1;let n=f(e),r=f(t);return n===r||(n===4326||n===3857)&&(r===4326||r===3857)}function m(e,t){let n=t.encoding,r=d(e,t.geometryType),i=f(t.spatialReference);switch(n.type){case`wkb`:return e.GeometryField.fromWkb(n.field,i,r);case`location`:{let{yField:t,xField:a}=n;return e.GeometryField.fromLocation(t,a,i,r)}}}function h(e,t){let n=e.GeometryInfo.new();t.geometry&&n.setGeometry(m(e,t.geometry));let r=t.displayOptimization;if(r){let{index:t}=r;if(t.type===`z`){let r=e.DisplayOptimizationZBuilder.new();r.setCodeField(b(t.code)),r.setXColumn(b(t.xColumn)),r.setYColumn(b(t.yColumn)),t.zColumn!=null&&r.setZColumn(b(t.zColumn)),t.mColumn!=null&&r.setMColumn(b(t.mColumn)),r.setCooordinatePrecision(t.coordinatePrecision),r.setFullExtent(t.fullExtent),r.setSpatialReference(t.wkid==null?void 0:f({wkid:t.wkid}),t.wkid==null?t.wkt:void 0),r.setHasZ(!!t.zColumn),r.setHasM(!!t.mColumn),t.zColumn&&r.setZColumn(b(t.zColumn)),t.mColumn&&r.setMColumn(b(t.mColumn)),n.setOptmizationZ(r)}if(t.type===`xz`){let r=d(e,t.geometryType),i=e.DisplayOptimizationXZBuilder.new();i.setCodeField(b(t.code)),i.setEncoding(t.encoding),i.setFullExtent(t.fullExtent),i.setGeometryType(r),i.setSpatialReference(t.wkid==null?void 0:f({wkid:t.wkid}),t.wkid==null?t.wkt:void 0),i.setMaxLevel(t.maxLevel),i.setHasZ(t.hasZ??!1),i.setHasM(t.hasM??!1);for(let n of t.levels??[]){let t=new Float64Array(n.transform.translate),r=new Float64Array(n.transform.scale),a=b(n.column);i.addLevel(e.MultiscaleGeometryField.new(n.level,n.resolution,a,t,r))}n.setOptmizationXZ(i)}}return n}async function g(t,n){let r=await i(),a=n.geometryInfo?h(r,n.geometryInfo):null,o=n.provider.fetchRange.bind(n.provider),s=n.provider.fetchLength.bind(n.provider);try{return await r.ParquetFile.fromUrl(t,o,s,a)}catch(t){throw new e(`parquet`,`Failed to parse file`,{error:t})}}function _(e){let t=e.keyValueMetadata(`geo`);return t==null?null:JSON.parse(t)}function v(t){if(t.keyValueMetadata(`esri`))throw new e(`parquet:unsupported`,`File was created using an unsupported experimental display index. Please regenerate the file.`);let n=t.keyValueMetadata(`geodisplay`);if(n!=null)return{present:!0,optimization:y({index:JSON.parse(n)})};let r=t.keyValueMetadata(`org.apache.spark.sql.parquet.row.metadata`);if(r!=null){let e=JSON.parse(r);for(let t of e.fields)if(t.metadata!=null&&T(t.metadata)){if(!E(t.metadata))return s().warn(`parquet:protocol-violation`,`Ignoring display optimization, found invalid column path`,{index:t.metadata}),{present:!0,optimization:null};let e=C(t.metadata,t.name);return e==null?(s().warn(`parquet:protocol-violation`,`Ignoring display optimization, Spark display column paths must be non-empty strings`,{index:t.metadata}),{present:!0,optimization:null}):{present:!0,optimization:y({index:e})}}}return{present:!1,optimization:null}}function y(e){if(!E(e.index))return s().warn(`parquet:protocol-violation`,`Ignoring display optimization, found invalid column path`,{index:e.index}),null;if(e.index.type===`xz`&&(e.index.geometryType=Y(e.index.geometryType),e.index.encoding===`esri-pbf`&&(e.index.encoding=`esriPBF`),e.index.encoding!==`esriPBF`))return s().warn(`parquet:unsupported`,`Encoding for display index must be of type esriPBF, but found ${e.index.encoding}`),null;let{xmin:t,ymin:n,xmax:r,ymax:i}=e.index.fullExtent;return!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)?(s().warn(`parquet:protocol-violation`,`Ignoring display optimization, found bad extent`,{index:e.index}),null):e}function b(e){return Array.isArray(e)?e.join(`.`):e}function x(e,t,n,r,i){let a=B(e.readAttribute(t,n),r);return!i||a==null?a:r===`esriFieldTypeDate`?new Date(a):a}function S(e,t,n,r,i){return B(e.readAttribute(t,n,r),i)}function C(e,t){if(e.type===`z`){let n=w(e.code,t),r=w(e.xColumn,t),i=w(e.yColumn,t),a=e.zColumn==null?e.zColumn:w(e.zColumn,t),o=e.mColumn==null?e.mColumn:w(e.mColumn,t);return n==null||r==null||i==null||a===null||o===null?null:{...e,code:n,xColumn:r,yColumn:i,...a==null?{}:{zColumn:a},...o==null?{}:{mColumn:o}}}let n=w(e.code,t),r=[];for(let n of e.levels){let e=w(n.column,t);if(e==null)return null;r.push({...n,column:e})}return n==null?null:{...e,code:n,levels:r}}function w(e,t){return typeof e==`string`&&e.length>0?[t,e]:null}function T(e){return typeof e==`object`&&!!e&&`type`in e&&(e.type===`z`||e.type===`xz`)}function E(e){return e.type===`z`?D(e.code)&&D(e.xColumn)&&D(e.yColumn)&&(e.zColumn==null||D(e.zColumn))&&(e.mColumn==null||D(e.mColumn)):D(e.code)&&Array.isArray(e.levels)&&e.levels.every(e=>typeof e==`object`&&!!e&&`column`in e&&D(e.column))}function D(e){return typeof e==`string`&&e.length>0||Array.isArray(e)&&e.length===2&&e.every(e=>typeof e==`string`&&e.length>0)}function O(e){if(e==null)return null;let t=e.ordering,n=e.lod;if(t==null&&n==null)return null;if(t?.type!==`xz`||n==null||t.geometry_column!==e.primary_column||n.geometry_column!==e.primary_column||t.geometry_column!==n.geometry_column||t.max_level!==20||!I(t.extent)||n.encoding!==`pbf`)return k(e,`ordering and lod must form a valid primary-column XZ pair`);let r=e.columns[e.primary_column],i=A(r);if(i==null||!j(n.orientation,i.geometryType))return k(e,`geometry type, dimensions, or LOD orientation is invalid`);let a=M(n.levels),o=X(r)?.wkid;if(a==null||o==null)return k(e,`LOD levels or spatial reference is invalid`);let[s,c,l,u]=t.extent;return{index:{type:`xz`,code:`geokey`,wkid:o,wkt:null,encoding:`esriPBF`,fullExtent:{xmin:s,ymin:c,xmax:l,ymax:u},geometryType:i.geometryType,maxLevel:t.max_level,hasZ:i.hasZ,hasM:i.hasM,levels:a}}}function k(e,t){return s().warn(`parquet:protocol-violation`,`Ignoring GeoParquet ordering and LOD extensions: ${t}`,{lod:e.lod,ordering:e.ordering}),null}function A(e){if(e==null||e.geometry_types.length===0)return null;let t,n;for(let r of e.geometry_types){let e=/^(LineString|MultiLineString|Polygon|MultiPolygon)(?: (Z|M|ZM))?$/.exec(r);if(e==null)return null;let i=e[1]===`LineString`||e[1]===`MultiLineString`?`polyline`:`polygon`;if(t!=null&&t!==i||n!=null&&n!==(e[2]??``))return null;t=i,n=e[2]??``}return t==null||n==null?null:{geometryType:t,hasZ:n===`Z`||n===`ZM`,hasM:n===`M`||n===`ZM`}}function j(e,t){return t===`polygon`?e===`clockwise`:e==null}function M(e){if(!Array.isArray(e)||e.length===0)return null;let t=new Set,n=e.slice().sort((e,t)=>t.resolution-e.resolution),r=[];for(let[e,i]of n.entries()){if(!N(i.column)||!Number.isFinite(i.resolution)||i.resolution<=0||t.has(i.resolution)||!P(i.transform))return null;t.add(i.resolution),r.push({column:i.column,level:e,resolution:i.resolution,transform:i.transform})}return r}function N(e){return Array.isArray(e)&&e.length===2&&e[0]===`geolod`&&typeof e[1]==`string`&&e[1].length>0}function P(e){return F(e?.scale,!0)&&F(e?.translate,!1)}function F(e,t){return Array.isArray(e)&&e.length===4&&e.every(e=>typeof e==`number`&&Number.isFinite(e)&&(!t||e>0))}function I(e){return F(e,!1)&&e[0]<e[2]&&e[1]<e[3]}function L(e){R(e);let t=z(e),n=_(e),r=v(e),i=r.present?r.optimization:O(n),a=U(n,t),{hasZ:o,hasM:s}=q(n,i),c,l;if(a)switch(a.type){case`location`:l={wkid:4326},c=`esriGeometryPoint`;break;case`wkb`:if(n){let e=n.primary_column,t=n.columns[e];c=G(t),l=X(t)}}if(i){let e=i.index;!l&&e.wkid&&(l={wkid:e.wkid}),c||=e.type===`z`?`esriGeometryPoint`:J(e.geometryType)}let u=Z(n,i,l);return{geoMetadata:n,displayOptimization:i,hasZ:o,hasM:s,geometryEncoding:a,geometryInfo:l&&c?{geometry:a?{geometryType:c,spatialReference:l,encoding:a}:null,displayOptimization:i}:null,geometryType:c,spatialReference:l,extent:u,fields:t}}function R(t){for(let n of t.compressionCodecs())if(!c.has(n))throw new e(`parquet:unsupported`,`Compression codec ${n} is unsupported. Must be of type ${Array.from(c).join(`,`)}`)}function z(e){return Array.from(e.fields(!1),e=>({name:e.name,alias:e.name,type:e.type}))}function B(e,t){return e==null?e:t===`esriFieldTypeDateOnly`?V(e):t===`esriFieldTypeTimeOnly`?H(e):t===`esriFieldTypeString`||t===`esriFieldTypeTimestampOffset`?l.decode(e):e}function V(e){return new Date(e*864e5).toISOString().slice(0,10)}function H(e){let t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=e%60;return`${t.toString().padStart(2,`0`)}:${n.toString().padStart(2,`0`)}:${r.toString().padStart(2,`0`)}`}function U(e,t){if(e!=null){let t=e.primary_column;return{type:`wkb`,field:t,orientation:e.columns[t].orientation===`counterclockwise`?`counter-clockwise`:null}}let n=W(t.filter(e=>u.has(e.type)).map(e=>e.name));return n.latitudeFieldName&&n.longitudeFieldName?{type:`location`,xField:n.longitudeFieldName,yField:n.latitudeFieldName}:null}function W(e){let t=e.map(e=>e.toLowerCase());return{longitudeFieldName:e[t.indexOf(o.find(e=>t.includes(e)))],latitudeFieldName:e[t.indexOf(a.find(e=>t.includes(e)))]}}function G(t){let{geometry_types:n}=t,r=new Set;for(let e of n){let t=K(e);t&&r.add(t)}if(r.size>1)throw new e(`parquet:unsupported`,`Parquet mixed geometry types are not supported`,{geometryTypes:r});return r.size===1?r.values().next().value:void 0}function K(e){switch(e.replace(/ (?:Z|M|ZM)$/u,``)){case`Point`:return`esriGeometryPoint`;case`Polygon`:case`MultiPolygon`:return`esriGeometryPolygon`;case`LineString`:case`MultiLineString`:return`esriGeometryPolyline`;case`MultiPoint`:return`esriGeometryMultipoint`;default:return null}}function q(e,t){let n=t?.index;if(n?.type===`z`)return{hasZ:n.zColumn!=null,hasM:n.mColumn!=null};if(n?.type===`xz`)return{hasZ:n.hasZ===!0,hasM:n.hasM===!0};let r=e?.columns[e.primary_column]?.geometry_types??[];return{hasZ:r.some(e=>/ (?:Z|ZM)$/u.test(e)),hasM:r.some(e=>/ (?:M|ZM)$/u.test(e))}}function J(e){switch(e){case`polygon`:return`esriGeometryPolygon`;case`polyline`:return`esriGeometryPolyline`;case`multipoint`:return`esriGeometryMultipoint`}}function Y(t){switch(t.toLowerCase()){case`polygon`:return`polygon`;case`polyline`:return`polyline`;case`multipoint`:return`multipoint`;default:throw new e(`parquet:unsupported`,`Geometry type ${t} is unsupported`)}}function X(e){let t=e.crs?.id?.code;return typeof t==`number`?{wkid:t}:e.crs?.id?.authority===`OGC`&&t===`CRS84`?{wkid:4326}:void 0}function Z(e,t,n){if(!n)return null;let r=(e?e.columns[e.primary_column]:null)?.bbox;if(r?.every(e=>Number.isFinite(e)))switch(r.length){case 4:return{xmin:r[0],ymin:r[1],xmax:r[2],ymax:r[3],spatialReference:n};case 6:return{xmin:r[0],ymin:r[1],xmax:r[3],ymax:r[4],spatialReference:n};default:s().warn(`parquet:protocol-violation`,`Invalid Geoparquet file. BoundingBox size must be 4 or 6.`,{geoMetadata:e})}let i=t?.index.fullExtent;return i?{...i,spatialReference:n}:null}export{p as canProjectParquetSpatialReference,g as createParquetFile,b as normalizeColumnPath,f as normalizeParquetSpatialReferenceWkid,_ as readGeoMetadata,L as readMetadata,x as readParquetChunkAttribute,S as readParquetFileAttribute};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import{property as t,subclass as n}from"../../../core/accessorSupport/decorators.js";import r from"../../../core/Error.js";import{isAbortError as i}from"../../../core/promiseUtils.js";import a from"./BaseRaster.js";import{convertOleDateTimeToEpoch as o}from"./multidimensionalUtils.js";import{parseConsolidatedMetadata as s,parseRasterInfo as c}from"./zarrParser.js";import{getChunkInfo as l,getZarrObjectUrl as u,extractPixelBlock as d,unpackUncompressedChunk as f}from"./zarrUtils.js";const p=`zarr-raster:open`,m=new Set([`none`]);let h=class extends a{constructor(){super(...arguments),this.datasetFormat=`ZARR`}get _baseUrl(){let{url:e}=this;return e.endsWith(`/.zmetadata`)||e.endsWith(`/.zgroup`)?e.slice(0,e.lastIndexOf(`/`)):e}async fetchRawTile(e,t,n,i={}){let{multidimensionalDefinition:a}=i;if(!a?.length)return null;let o=a[0].variableName,s=this._metadata.dataVariables.find(e=>e.name===o);if(!s)return null;let{storageInfo:c}=s,f=Object.fromEntries(a.map(e=>[e.dimensionName,e.values[0]])),p=this._getDimensionIndices(s,t,n,f);if(!p)return null;let m=s.attributes._ARRAY_DIMENSIONS,{xDimension:h,yDimension:g}=this._metadata,_=l(c,p,m.indexOf(h),m.indexOf(g));if(!_)return null;let v=u(this._baseUrl,`${o}/${_.chunkPath}`),{data:y}=await this.request(v,{responseType:`array-buffer`,signal:i.signal}),{actualSize:b,elementCount:x}=_,S=this._decodeChunk(y,c),C=b.reduce((e,t)=>e*t,1),w=S.length;if(w!==x&&w!==C)throw new r(`zarr-raster:decode`,`Invalid chunk length ${w} for "${v}"; expected ${x} or ${C} values`);return d(S,_)}async _open(e){let t=this.url.slice(this.url.lastIndexOf(`/`)+1);if(t.endsWith(`.zattrs`)||t.endsWith(`.zarray`))throw new r(p,`Unsupported Zarr URL: "${this.url}". Expect a v2 root url or consolidated metadata url`);let n=this._baseUrl;this.datasetName=n.slice(n.lastIndexOf(`/`)+1).replace(`.zarr`,``);let i=e?.signal??void 0,{data:a}=await this.request(`${n}/.zmetadata`,{signal:i}),o=s(a);this._metadata=o;let l=[...o.dataDimensions,...o.dataVariables].find(({storageInfo:{compression:e}})=>!m.has(e));if(l)throw new r(p,`Unsupported Zarr compression "${l.storageInfo.compression}" for array "${l.name}"`);let u={};await Promise.all(o.dataDimensions.map(e=>this._readDimensionValues(e,u,i)));let d=c(o,u);this._dimensionValues=u,this._set(`rasterInfo`,d)}_getDimensionIndices(e,t,n,r){let i=e.attributes._ARRAY_DIMENSIONS,{xDimension:a,yDimension:o}=this._metadata,{chunkSize:s}=e.storageInfo;if(!this.rasterInfo.multidimensionalInfo?.variables.find(t=>t.name===e.name)?.dimensions?.length)return null;let c=[];for(let e=0;e<i.length;e++){let l=i[e];if(l===a)c[e]=n*s[e];else if(l===o)c[e]=t*s[e];else{let t=this._dimensionValues[l],n=r[l],i=t?.indexOf(n)??-1;if(i<0)return null;c[e]=i}}return c}async _readDimensionValues(e,t,n){let{name:a,storageInfo:s}=e,c=s.chunkSize[0],l=s.shape[0];if(c<=0||l<=0)throw new r(p,`Invalid dimension array "${a}" with chunkSize ${c} and totalElements ${l}`);let d=Math.ceil(l/c),f=this._baseUrl,m=[];for(let e=0;e<d;e++){let t=u(f,`${a}/${e}`),o=e===d-1?l-e*c:c;m.push(this.request(t,{responseType:`array-buffer`,signal:n}).then(e=>{let t=this._decodeChunk(e.data,s);if(t.length!==c&&t.length!==o)throw new r(p,`Invalid dimension chunk length for "${a}"`);return t.slice(0,o)}).catch(e=>{throw i(e)?e:new r(p,`Unable to fetch dimension data for "${a}"`)}))}let h=(await Promise.all(m)).flatMap(e=>Array.from(e)),{scaleFactor:g,addOffset:_}=s;if(g!==1||_!==0)for(let e=0;e<h.length;e++)h[e]=h[e]*g+_;t[a]=e.attributes.units===`days since 1899-12-30 00:00:00 UTC`?h.map(o):h}_decodeChunk(e,t){let{compression:n}=t;if(!m.has(n))throw new r(`zarr-raster:decode`,`Unsupported Zarr compression "${n}"`);return f(e,t)}};e([t()],h.prototype,`_baseUrl`,null),e([t({json:{write:!0}})],h.prototype,`_dimensionValues`,void 0),e([t({json:{write:!0}})],h.prototype,`_metadata`,void 0),e([t({type:String,json:{write:!0}})],h.prototype,`datasetFormat`,void 0),h=e([n(`esri.layers.raster.datasets.ZarrRaster`)],h);const g=h;export{g as default};
2
+ import{__decorate as e}from"tslib";import{property as t,subclass as n}from"../../../core/accessorSupport/decorators.js";import r from"../../../core/Error.js";import{isAbortError as i}from"../../../core/promiseUtils.js";import a from"./BaseRaster.js";import{convertOleDateTimeToEpoch as o}from"./multidimensionalUtils.js";import{parseConsolidatedMetadata as s,parseRasterInfo as c}from"./zarrParser.js";import{getChunkInfo as l,getZarrObjectUrl as u,extractPixelBlock as d,unpackUncompressedChunk as f}from"./zarrUtils.js";import{getByteCount as p}from"../formats/pixelRangeUtils.js";const m=`zarr-raster:open`,h=new Set([`none`,`blosc`]);let g=class extends a{constructor(){super(...arguments),this.datasetFormat=`ZARR`}get _baseUrl(){let{url:e}=this;return e.endsWith(`/.zmetadata`)||e.endsWith(`/.zgroup`)?e.slice(0,e.lastIndexOf(`/`)):e}async fetchRawTile(e,t,n,i={}){let{multidimensionalDefinition:a}=i;if(!a?.length)return null;let o=a[0].variableName,s=this._metadata.dataVariables.find(e=>e.name===o);if(!s)return null;let{storageInfo:c}=s,f=Object.fromEntries(a.map(e=>[e.dimensionName,e.values[0]])),p=this._getDimensionIndices(s,t,n,f);if(!p)return null;let m=s.attributes._ARRAY_DIMENSIONS,{xDimension:h,yDimension:g}=this._metadata,_=l(c,p,m.indexOf(h),m.indexOf(g));if(!_)return null;let v=u(this._baseUrl,`${o}/${_.chunkPath}`),{data:y}=await this.request(v,{responseType:`array-buffer`,signal:i.signal}),{actualSize:b,elementCount:x}=_,S=await this._decodeChunk(y,c,i),C=b.reduce((e,t)=>e*t,1),w=S.length;if(w!==x&&w!==C)throw new r(`zarr-raster:decode`,`Invalid chunk length ${w} for "${v}"; expected ${x} or ${C} values`);return d(S,_)}async _open(e){let t=this.url.slice(this.url.lastIndexOf(`/`)+1);if(t.endsWith(`.zattrs`)||t.endsWith(`.zarray`))throw new r(m,`Unsupported Zarr URL: "${this.url}". Expect a v2 root url or consolidated metadata url`);let n=this._baseUrl;this.datasetName=n.slice(n.lastIndexOf(`/`)+1).replace(`.zarr`,``);let i=e?.signal??void 0,{data:a}=await this.request(`${n}/.zmetadata`,{signal:i}),o=s(a);this._metadata=o;let l=[...o.dataDimensions,...o.dataVariables].find(({storageInfo:{compression:e}})=>!h.has(e));if(l)throw new r(m,`Unsupported Zarr compression "${l.storageInfo.compression}" for array "${l.name}"`);let u={};await Promise.all(o.dataDimensions.map(e=>this._readDimensionValues(e,u,i)));let d=c(o,u);this._dimensionValues=u,this._set(`rasterInfo`,d)}_getDimensionIndices(e,t,n,r){let i=e.attributes._ARRAY_DIMENSIONS,{xDimension:a,yDimension:o}=this._metadata,{chunkSize:s}=e.storageInfo;if(!this.rasterInfo.multidimensionalInfo?.variables.find(t=>t.name===e.name)?.dimensions?.length)return null;let c=[];for(let e=0;e<i.length;e++){let l=i[e];if(l===a)c[e]=n*s[e];else if(l===o)c[e]=t*s[e];else{let t=this._dimensionValues[l],n=r[l],i=t?.indexOf(n)??-1;if(i<0)return null;c[e]=i}}return c}async _readDimensionValues(e,t,n){let{name:a,storageInfo:s}=e,c=s.chunkSize[0],l=s.shape[0];if(c<=0||l<=0)throw new r(m,`Invalid dimension array "${a}" with chunkSize ${c} and totalElements ${l}`);let d=Math.ceil(l/c),f=this._baseUrl,p=[];for(let e=0;e<d;e++){let t=u(f,`${a}/${e}`),o=e===d-1?l-e*c:c;p.push(this.request(t,{responseType:`array-buffer`,signal:n}).then(async e=>{let t=await this._decodeChunk(e.data,s,{signal:n});if(t.length!==c&&t.length!==o)throw new r(m,`Invalid dimension chunk length for "${a}"`);return t.slice(0,o)}).catch(e=>{throw i(e)?e:new r(m,`Unable to fetch dimension data for "${a}"`)}))}let h=(await Promise.all(p)).flatMap(e=>Array.from(e)),{scaleFactor:g,addOffset:_}=s;if(g!==1||_!==0)for(let e=0;e<h.length;e++)h[e]=h[e]*g+_;t[a]=e.attributes.units===`days since 1899-12-30 00:00:00 UTC`?h.map(o):h}async _decodeChunk(e,t,n){let{compression:i}=t;if(!h.has(i))throw new r(`zarr-raster:decode`,`Unsupported Zarr compression "${i}"`);if(i===`blosc`){let i=t.originalPixelType===`f2`?2:p(t.pixelType),a=t.chunkSize.reduce((e,t)=>e*t,i),o=await this.decodePixelBlock(e,{format:`blosc`,pixelType:`u8`,skipStatistics:!0,maxUncompressedSize:a},n);if(!o)throw new r(`zarr-raster:decode`,`Unable to decode Blosc chunk`);e=o.pixels[0].buffer}return f(e,t)}};e([t()],g.prototype,`_baseUrl`,null),e([t({json:{write:!0}})],g.prototype,`_dimensionValues`,void 0),e([t({json:{write:!0}})],g.prototype,`_metadata`,void 0),e([t({type:String,json:{write:!0}})],g.prototype,`datasetFormat`,void 0),g=e([n(`esri.layers.raster.datasets.ZarrRaster`)],g);const _=g;export{_ as default};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
- import e from"../../../geometry/Extent.js";import t from"../../../geometry/Polygon.js";import{isAxesOrderReversedForWkid as n}from"../../ogc/crsUtils.js";import r from"../../support/RasterInfo.js";import{convertOleDateTimeToEpoch as i,getDimensionValues as a}from"./multidimensionalUtils.js";import{getElements as o,isSameTagIgnoreNS as s,getElementValue as c,getElementValues as l,getNodeNameIgnoreNS as u,getElement as d,getSpaceDelimitedNumericValues as f}from"./xmlUtilities.js";function p(e){e.variables.forEach(e=>e.dimensions.forEach(e=>e.values??=a(e)))}function m(e){return{requestResponseCRSs:l(e,`requestResponseCRSs`).map(e=>e.split(`:`,2)[1]),nativeCRSs:l(e,`nativeCRSs`).map(e=>e.split(`:`,2)[1])}}function h(e,t){let n=l(e,t===`1.0.0`?`interpolationMethod`:`InterpolationMethod`),r=t===`1.0.0`?e.getAttribute(`default`):c(e,`InterpolationMethods/Default`);return r==null?n:[r].concat(n.filter(e=>e.toLowerCase()!==r.toLowerCase()))}function g(e){return e==null?[`nearest`]:e.map(e=>{let t=e.toLowerCase();return t.includes(`nearest`)?`nearest`:t.includes(`linear`)?`bilinear`:t.includes(`cubic`)?`cubic`:null}).filter(e=>!!e)}function _(t){let n=o(t,`pos`),r=f(n[0]),i=f(n[1]);return new e({xmin:r[0],ymin:r[1],xmax:i[0],ymax:i[1],spatialReference:{wkid:4326}})}function v(e,t){let n=l(e,t);return n?.length&&n[0]!==``&&!isNaN(Number(n[0]))?n.map(e=>Number(e)):null}function y(e){let t=f(e,`MinimumValue`),n=f(e,`MaximumValue`);return t.length&&n.length?t.map((e,t)=>({min:e,max:n[t],avg:-1,stddev:-1})):null}function b(e){return e==null?null:e.every(t=>t===e[0])?e[0]:e}function x(e){let t=[],n=o(e,`RangeSet`),r=[];for(let e=0;e<n.length;e++){let i=c(n[e],`name`),a=c(n[e],`label`),s=[],u=v(n[e],`nullValues/singleValue`),d=o(n[e],`AxisDescription`);for(let e=0;e<d.length;e++){let t=c(d[e],`name`),n=c(d[e],`label`),i=l(d[e],`singleValue`);if(i.length===0){let t=c(d[e],`min`),n=c(d[e],`max`),r=Number(c(d[e],`res`))||1;if(t!==null&&n!==null)for(let e=parseInt(t,10);e<=parseInt(n,10);e+=r)i.push(e.toString())}t.toLowerCase()===`band`&&(r=i),s.push({name:t,label:n,values:i})}t.push({name:i,label:a,nullValues:u,axis:s})}return{rangeSet:t,bandNames:r}}function S(e=null){if(!e)return{resolution:null,units:null};let t=e.toUpperCase(),n=[`Y`,`M`,`D`],r=[`H`,`M`,`S`],i=[`Years`,`Months`,`Days`,`Hours`,`Minutes`,`Seconds`],a,o,s;return t.includes(`PT`)?(t=t.slice(2),s=r.findIndex(e=>t.includes(e)),a=i[3+s],o=parseFloat(t.slice(0,-1))):(t=t.slice(1),s=n.findIndex(e=>t.includes(e)),s>-1&&(a=i[s]),o=parseFloat(t.slice(0,-1))),{resolution:o,units:a}}function C(e){let t=o(e,`timeposition`);if(t.length>0){let e=[];for(let n=0;n<t.length;n++)e.push(new Date(c(t[n])));return{begin:e[0],end:e[e.length-1],values:e}}let n=d(e,`timePeriod`)||d(e,`TimePeriod`);return n?{begin:new Date(c(n,`beginPosition`)||c(n,`BeginPosition`)),end:new Date(c(n,`endPosition`)||c(n,`EndPosition`)),...S(c(n,`timeResolution`)||c(n,`TimeResolution`))}:null}function w(t){let n=d(t,`spatialDomain`),r=d(n,`Envelope`)||d(n,`EnvelopeWithTimePeriod`),i=r.getAttribute(`srsName`).split(`:`),a=i[i.length-1],s=o(r,`pos`),l=f(s[0]),u=f(s[1]),p=parseInt(a,10),m=isNaN(p)?null:{wkid:p},h=new e({xmin:l[0],ymin:l[1],xmax:u[0],ymax:u[1],spatialReference:m}),g=d(n,`RectifiedGrid`),_=c(g,`low`).split(` `),v=c(g,`high`).split(` `),y=parseInt(v[0],10)-parseInt(_[0],10)+1,b=parseInt(v[1],10)-parseInt(_[1],10)+1,x=f(n,`origin/pos`),S=o(n,`offsetVector`),w={envelope:h,columns:y,rows:b,offset:{x:parseFloat(c(S[0]).split(` `,1)[0]),y:parseFloat(c(S[1]).split(` `,2)[1])},origin:{x:x[0],y:x[1]}},T=d(t,`temporalDomain`)||d(t,`TemporalDomain`);return{spatialDomain:w,temporalDomain:T?C(T):null}}function T(e){let t={version:`1.0`},n=[],i;for(let r=0;r<e.childNodes.length;r++){let a=e.childNodes[r];if(a.nodeType===1){if(s(a,`description`))t.description=c(a);else if(s(a,`name`))t.name=c(a);else if(s(a,`label`))t.label=c(a);else if(s(a,`supportedFormats`))t.supportedFormats=l(a,`formats`);else if(s(a,`supportedCRSs`))t.supportedCRSs=m(a);else if(s(a,`supportedInterpolations`))t.supportedInterpolations=h(a,`1.0.0`);else if(s(a,`lonLatEnvelope`))t.lonLatEnvelope=_(a);else if(s(a,`rangeSet`)){let e=x(a);t.rangeSet=e.rangeSet,n=e.bandNames;let r=e.rangeSet[0].nullValues;r?.length&&(i=b(r))}else s(a,`domainSet`)&&(t.domainSet=w(a))}}let a=g(t.supportedInterpolations),{name:o,description:u,label:d,lonLatEnvelope:f,supportedFormats:p}=t,{spatialDomain:v}=t.domainSet,y={x:Math.abs(v.offset.x),y:Math.abs(v.offset.y)},S=E(t.domainSet),C=new r({width:v.columns,height:v.rows,pixelSize:y,pixelType:`unknown`,extent:v.envelope,spatialReference:v.envelope.spatialReference,bandCount:n.length||1,noDataValue:i,multidimensionalInfo:S});return{id:o,title:t.name,description:u||d,lonLatEnvelope:f,rasterInfo:C,bandNames:n,supportedFormats:p,supportedInterpolations:a,coverageDescription:t,version:`1.0.0`,useEPSGAxis:!1}}function E(e){if(!e.temporalDomain)return null;let{begin:t,end:n,values:r,units:i,resolution:a}=e.temporalDomain,o={variables:[{name:`default`,description:``,dimensions:[{name:`StdTime`,description:``,unit:`ISO8601`,values:r?.map(e=>e.getTime()),hasRegularIntervals:!r,interval:a,intervalUnit:i,extent:[t.getTime(),n.getTime()]}]}]};return p(o),o}function D(e,t){let n=[],r=o(e,`Field`),i=[],a;for(let e=0;e<r.length;e++){let s=c(r[e],`Identifier`),u=c(r[e],`Description`),f=c(r[e],`Definition`),p=c(r[e],`Abstract`),m=c(r[e],`Title`),g=v(r[e],`NullValue`),_=d(r[e],`AllowedValues`),b=_?y(_):null,x=h(r[e],`1.1.0`),S=[],C=o(r[e],`Axis`);for(let e=0;e<C.length;e++){let n=C[e].getAttribute(`identifier`),r=c(C[e],`UOM`),o=c(C[e],`DataType`),s=l(C[e],`Key`);(!t||n.toLowerCase().includes(`band`))&&(i=s,a=g),S.push({identifier:n,uom:r,dataType:o,values:s,bandNoDataValues:a})}n.push({identifier:s,description:u,definition:f,abstract:p,title:m,supportedInterpolations:x,axis:S,nullValues:g,statistics:b})}let s=n[0].statistics;return{rangeSet:n,bandNames:i,bandNoDataValues:a,statistics:s}}function O(e,t){if(!t.temporalDomain)return null;let n=e.filter(e=>!e.identifier.toLowerCase().includes(`field_1`)&&!e.axis.some(e=>e.identifier.includes(`band`))),r=[];if(n.length&&n.forEach(e=>{let t=e.axis.map(e=>{let t=e.values.map(t=>e.uom===`ISO8601`?(t=t.trim(),t.toLowerCase().includes(`z`)?new Date(t).getTime():new Date(t+`Z`).getTime()):parseFloat(t.trim())),n=[Math.min.apply(null,t),Math.max.apply(null,t)];return{name:e.identifier.trim(),description:``,field:e.identifier.trim(),unit:e.uom?e.uom.trim():``,hasRegularIntervals:!1,values:t,extent:n}});r.push({name:e.identifier.trim(),description:e.description?.trim()??``,unit:``,dimensions:t,statistics:e.statistics})}),t.temporalDomain){let{begin:e,end:n,values:i,units:a,resolution:o}=t.temporalDomain;r.some(e=>e.dimensions.some(e=>e.name.toLowerCase()===`stdtime`))||r.forEach(t=>{t.dimensions.push({name:`StdTime`,description:``,unit:`ISO8601`,values:i?.map(e=>e.getTime()),hasRegularIntervals:!i,interval:o,intervalUnit:a,extent:[e.getTime(),n.getTime()]})})}if(r.length){let e={variables:r};return p(e),e}return null}function k(t){let r=d(t,`SpatialDomain`),i=d(r,`GridCRS`),a=c(i,`GridBaseCRS`),s=c(i,`GridOrigin`)?.split(` `).map(e=>parseFloat(e))??[0,0],l=f(i,`GridOffsets`),u=o(r,`BoundingBox`),p,m,h,g;for(let t=0;t<u.length;t++){let n=u[t].getAttribute(`crs`)?.toLowerCase();if(n!=null){if(n.includes(`imagecrs`)){let e=f(u[t],`LowerCorner`),n=f(u[t],`UpperCorner`);p=n[0]-e[0]+1,m=n[1]-e[1]+1}else if(n.indexOf(`epsg`)>0){let r=n.split(`:`);h=parseInt(r[r.length-1],10);let i=f(u[t],`LowerCorner`),a=f(u[t],`UpperCorner`);g=new e({xmin:i[0],ymin:i[1],xmax:a[0],ymax:a[1],spatialReference:{wkid:h}})}}}let _=p>m,v=g.xmax-g.xmin>g.ymax-g.ymin,y=!1;n(h)&&(_===v?y=!1:(y=!0,g=new e({xmin:g.ymin,ymin:g.xmin,xmax:g.ymax,ymax:g.xmax,spatialReference:{wkid:h}})));let b={columns:p,rows:m,origin:{x:s[0],y:s[1]},offset:{x:l[0],y:l[l.length-1]},gridBaseCRS:a,envelope:g,useEPSGAxis:y},x=d(t,`temporalDomain`)||d(t,`TemporalDomain`);return{spatialDomain:b,temporalDomain:x?C(x):null}}function A(e,t){let n=[],i=[],a={supportedFormats:n,supportedCRSs:i,version:`1.1`},o=[],s,l;for(let t=0;t<e.childNodes.length;t++){let r=e.childNodes[t];if(r.nodeType!==1)continue;let d=u(r).toLowerCase();switch(d){case`title`:case`abstract`:case`identifier`:a[d]=c(r);break;case`supportedformat`:{let e=c(r);n.includes(e)||n.push(e)}break;case`supportedcrs`:{let e=c(r);i.includes(e)||i.push(e)}break;case`range`:{let e=D(r,!!a.domain?.temporalDomain);a.range=e.rangeSet,o=e.bandNames;let{bandNoDataValues:t}=e;t?.length&&(s=b(t)),l=e.statistics}break;case`domain`:a.domain=k(r)}}let d=g(a.range[0].supportedInterpolations),{identifier:f,abstract:p,title:m,domain:h,range:_}=a,v={x:Math.abs(h.spatialDomain.offset.x),y:Math.abs(h.spatialDomain.offset.y)},y=O(_,h);y&&(s=_[0].nullValues,s?.length===1&&(s=s[0]));let x=new r({width:h.spatialDomain.columns,height:h.spatialDomain.rows,pixelSize:v,pixelType:`unknown`,extent:h.spatialDomain.envelope,spatialReference:h.spatialDomain.envelope.spatialReference,bandCount:o.length||1,noDataValue:s,statistics:l,multidimensionalInfo:y});return{id:f,title:a.title,description:p||m,bandNames:o,rasterInfo:x,supportedFormats:n,supportedInterpolations:d,coverageDescription:a,version:t,useEPSGAxis:h.spatialDomain.useEPSGAxis}}function j(t){let n=d(t,`Envelope`)||d(t,`EnvelopeWithTimePeriod`),r=n.getAttribute(`srsName`),i=r.slice(r.lastIndexOf(`/`)+1),a=n.getAttribute(`axisLabels`).split(` `).map(e=>e.trim()).filter(e=>e.trim()!==``),o=f(n,`lowerCorner`),l=f(n,`upperCorner`),u=![`y`,`lat`,`latitude`,`north`,`nor`,`n`,`b`].includes(a[0].toLowerCase()),p,m=parseInt(i,10),h=isNaN(m)?null:{wkid:m};p=u?new e({xmin:o[0],ymin:o[1],xmax:l[0],ymax:l[1],spatialReference:h}):new e({xmin:o[1],ymin:o[0],xmax:l[1],ymax:l[0],spatialReference:h});let g={mins:o,maxs:l},_=n.getAttribute(`uomLabels`).trim().split(` `),v,y;if(s(n,`EnvelopeWithTimePeriod`)){v=new Date(c(t,`beginPosition`)||c(t,`BeginPosition`)),y=new Date(c(t,`endPosition`)||c(t,`EndPosition`));let e=_?.findIndex(e=>e?.toLowerCase()===`oledatetime`);e>-1&&(_[e]=`ISO8601`)}return{envelope:p,axisLabels:a,uomLabels:_.length?_:null,envelopeAllDims:g,beginPosition:v,endPosition:y,isEastFirst:u}}function M(e,t){let n=[],r=o(e,`DataRecord`),i=[],a=[],s;for(let e=0;e<r.length;e++){let l=o(r[e],`field`),u=[];for(let e=0;e<l.length;e++){let n=l[e].getAttribute(`name`),r=c(l[e],`description`)||``,o=d(l[e],`uom`)?.getAttribute(`code`)||``,p=f(l[e],`interval`),m=v(l[e],`nilValue`)?.[0];(!t||n.toLowerCase().includes(`band`))&&(i.push(n),p?.length&&(s||=[],s.push({min:p[0],max:p[1],avg:-1,stddev:-1})),a.push(m)),u.push({name:n,description:r,uom:o,allowedValues:p,nilValue:m})}n.push(u)}return a.some(e=>e!=null)||(a=null),{rangeType:n,bandNames:i,bandStats:s,bandNoDataValues:a}}function N(e){let t=1,n=``,r=.01;return Math.abs(e-1/24)<1/24*r?n=`Hours`:Math.abs(e-1)<1*r?n=`Days`:e<1?(t=Math.round(e*24),n=`Hours`):e>27.99&&e<31.01||Math.round(e/30)<12?n=`Months`:e>364.99&&e<366.01&&(n=`Years`),{interval:t,intervalUnit:n}}function P(e,t,n){if(n.axisLabels.length<=2)return null;let r=[];for(let t=0;t<e.length;t++){let n=e[t];for(let e=0;e<n.length;e++)n[e].name.toLowerCase().includes(`band`)||r.push(n[e])}let a=[];if(r.length){let e=[];for(let r=2;r<n.axisLabels.length;r++){let a=t.uomLabels?.[r]?.trim()??``,o=n.axisLabels[r].toLowerCase().includes(`time`)||a.toLowerCase()===`iso8601`||a.toLowerCase()===`oledatetime`,s,c;if(o){let e=N(n.offset[r]);s=e.interval,c=e.intervalUnit}else s=n.offset[r],c=a;let l=[];o?(l.push(i(t.envelopeAllDims.mins[r])),l.push(i(t.envelopeAllDims.maxs[r]))):(l.push(t.envelopeAllDims.mins[r]),l.push(t.envelopeAllDims.maxs[r])),e.push({name:n.axisLabels[r].trim(),description:n.axisLabels[r].trim(),unit:o?`ISO8601`:a,hasRegularIntervals:!0,extent:l,interval:s,intervalUnit:c})}if(r.forEach(t=>{let{allowedValues:n}=t,r=n?.length===2?[{min:n[0],max:n[1],avg:-1,stddev:-1}]:null;a.push({name:t.name.trim(),description:t.description?.trim()??``,unit:t.uom.trim(),statistics:r,dimensions:[...e]})}),a.length){let e={variables:a};return p(e),e}}return null}function F(e,t){let n=d(e,`RectifiedGrid`),r=f(n,`low`),i=f(n,`high`),a=[];for(let e=0;e<r.length;e++)a.push(i[e]-r[e]+1);let s=c(n,`axisLabels`).split(` `),l=f(n,`origin/pos`),u=o(n,`offsetVector`),p=[];for(let e=0;e<u.length;e++){let t=f(u[e]),n=t.findIndex(e=>e!==0);p[n]=t[n]}let m=[`y`,`lat`,`latitude`,`north`,`nor`,`n`,`b`],h=!1;t?.length&&s?.length&&(h=[...t].sort((e,t)=>e<t?-1:1).join(`,`)===[...s].sort((e,t)=>e<t?-1:1).join(`,`));let g=h?s:t,_,v,y;return m.includes(g[0].toLowerCase())?(_=a[1],v=a[0],y={y:Math.abs(p[0]),x:Math.abs(p[1])}):(_=a[0],v=a[1],y={x:Math.abs(p[0]),y:Math.abs(p[1])}),{columns:_,rows:v,origin:l,offset:p,resolution:y,gridSamples:a,axisLabels:s,hasSameAxisLabelsAsBoundedBy:h}}function I(e){let n=d(e,`EarthObservation`);if(!n)return null;let r=d(n,`phenomenonTime`),i=r?C(r):null,a=d(n,`phenomenonTime`),o=a?C(a):null,s=c(n,`featureOfInterest/Footprint/multiExtentOf/MultiSurface/surfaceMembers/Polygon/exterior/LinearRing/posList`),l=null;if(s){let e=s.split(` `).map(e=>e.trim()).filter(e=>e!=null&&e!==``).map(Number);if(e.length){let n=[];for(let t=0;t<e.length/2;t+=2)n.push(e[t],e[t+1]);l=new t({rings:[[n]]})}}let u=c(e,`metaDataProperty/EarthObservationMetaData/identifier`),f=c(e,`metaDataProperty/EarthObservationMetaData/acquisitionType`),p=c(e,`metaDataProperty/EarthObservationMetaData/status`);return{observation:{phenomenonTime:i,resultTime:o,footprint:l,identifier:u,acquisitionType:f,status:p}}}function L(e){let t={version:`2.0`},n=[],i,a;for(let r=0;r<e.childNodes.length;r++){let o=e.childNodes[r];if(o.nodeType===1){if(s(o,`coverageId`))t.coverageId=c(o);else if(s(o,`ServiceParameters`))t.serviceParameters={supportedFormats:l(o,`nativeFormat`)};else if(s(o,`boundedBy`))t.boundedBy=j(o);else if(s(o,`rangeType`)){let e=M(o,t.boundedBy?.axisLabels.length>2||t.domainSet?.axisLabels.length>2);t.rangeType=e.rangeType,n=e.bandNames,i=e.bandStats;let{bandNoDataValues:r}=e;r?.length&&(a=b(r))}else if(s(o,`domainSet`))t.domainSet=F(o,t.boundedBy?.axisLabels);else if(s(o,`metadata`)){let e=d(o,`EOMetadata`);t.eoMetadata=e?I(e):null}}}let{coverageId:o,boundedBy:u,domainSet:f,rangeType:p,serviceParameters:m}=t,h=P(p,u,f);!i&&h&&(i=h?.variables[0].statistics),h!=null&&(a=p[0][0].nilValue);let g=new r({width:f.columns,height:f.rows,pixelSize:f.resolution,pixelType:`unknown`,extent:u.envelope,spatialReference:u.envelope.spatialReference,bandCount:n.length||1,statistics:i,noDataValue:a,multidimensionalInfo:h});return{id:o,title:o,description:o,bandNames:n,rasterInfo:g,supportedFormats:m.supportedFormats,coverageDescription:t,version:`2.0.1`,useEPSGAxis:!1}}function R(e,t){let n=null;if(n=typeof e==`string`?new DOMParser().parseFromString(e,`text/xml`):e,t===`1.0.0`)return o(n,`CoverageOffering`).map(e=>T(e));let r=o(n,`CoverageDescription`);return t===`1.1.0`||t===`1.1.1`||t===`1.1.2`?r.map(e=>A(e,t)):r.map(e=>L(e))}export{R as parseCoverages,g as standardizeInterpolations};
2
+ import e from"../../../geometry/Extent.js";import t from"../../../geometry/Polygon.js";import{isAxesOrderReversedForWkid as n}from"../../ogc/crsUtils.js";import r from"../../support/RasterInfo.js";import{convertOleDateTimeToEpoch as i,getDimensionValues as a}from"./multidimensionalUtils.js";import{getElements as o,isSameTagIgnoreNS as s,getElementValue as c,getElementValues as l,getNodeNameIgnoreNS as u,getElement as d,getSpaceDelimitedNumericValues as f}from"./xmlUtilities.js";function p(e){e.variables.forEach(e=>e.dimensions.forEach(e=>e.values??=a(e)))}function m(e){return{requestResponseCRSs:l(e,`requestResponseCRSs`).map(e=>e.split(`:`,2)[1]),nativeCRSs:l(e,`nativeCRSs`).map(e=>e.split(`:`,2)[1])}}function h(e,t){let n=l(e,t===`1.0.0`?`interpolationMethod`:`InterpolationMethod`),r=t===`1.0.0`?e.getAttribute(`default`):c(e,`InterpolationMethods/Default`);return r==null?n:[r].concat(n.filter(e=>e.toLowerCase()!==r.toLowerCase()))}function g(e){return e==null?[`nearest`]:e.map(e=>{let t=e.toLowerCase();return t.includes(`nearest`)?`nearest`:t.includes(`linear`)?`bilinear`:t.includes(`cubic`)?`cubic`:null}).filter(e=>!!e)}function _(t){let n=o(t,`pos`),r=f(n[0]),i=f(n[1]);return new e({xmin:r[0],ymin:r[1],xmax:i[0],ymax:i[1],spatialReference:{wkid:4326}})}function v(e,t){let n=l(e,t);return n?.length&&n[0]!==``&&!isNaN(Number(n[0]))?n.map(e=>Number(e)):null}function y(e){let t=f(e,`MinimumValue`),n=f(e,`MaximumValue`);return t.length&&n.length?t.map((e,t)=>({min:e,max:n[t],avg:-1,stddev:-1})):null}function b(e){return e==null?null:e.every(t=>t===e[0])?e[0]:e}function x(e){let t=[],n=o(e,`RangeSet`),r=[];for(let e=0;e<n.length;e++){let i=c(n[e],`name`),a=c(n[e],`label`),s=[],u=v(n[e],`nullValues/singleValue`),d=o(n[e],`AxisDescription`);for(let e=0;e<d.length;e++){let t=c(d[e],`name`),n=c(d[e],`label`),i=l(d[e],`singleValue`);if(i.length===0){let t=c(d[e],`min`),n=c(d[e],`max`),r=Number(c(d[e],`res`))||1;if(t!==null&&n!==null)for(let e=parseInt(t,10);e<=parseInt(n,10);e+=r)i.push(e.toString())}t.toLowerCase()===`band`&&(r=i),s.push({name:t,label:n,values:i})}t.push({name:i,label:a,nullValues:u,axis:s})}return{rangeSet:t,bandNames:r}}function S(e=null){if(!e)return{resolution:null,units:null};let t=e.toUpperCase(),n=[`Y`,`M`,`D`],r=[`H`,`M`,`S`],i=[`Years`,`Months`,`Days`,`Hours`,`Minutes`,`Seconds`],a,o,s;return t.includes(`PT`)?(t=t.slice(2),s=r.findIndex(e=>t.includes(e)),a=i[3+s],o=parseFloat(t.slice(0,-1))):(t=t.slice(1),s=n.findIndex(e=>t.includes(e)),s>-1&&(a=i[s]),o=parseFloat(t.slice(0,-1))),{resolution:o,units:a}}function C(e){let t=o(e,`timeposition`);if(t.length>0){let e=[];for(let n=0;n<t.length;n++)e.push(new Date(c(t[n])));return{begin:e[0],end:e[e.length-1],values:e}}let n=d(e,`timePeriod`)||d(e,`TimePeriod`);return n?{begin:new Date(c(n,`beginPosition`)||c(n,`BeginPosition`)),end:new Date(c(n,`endPosition`)||c(n,`EndPosition`)),...S(c(n,`timeResolution`)||c(n,`TimeResolution`))}:null}function w(t){let n=d(t,`spatialDomain`),r=d(n,`Envelope`)||d(n,`EnvelopeWithTimePeriod`),i=r.getAttribute(`srsName`).split(`:`),a=i[i.length-1],s=o(r,`pos`),l=f(s[0]),u=f(s[1]),p=parseInt(a,10),m=isNaN(p)?null:{wkid:p},h=new e({xmin:l[0],ymin:l[1],xmax:u[0],ymax:u[1],spatialReference:m}),g=d(n,`RectifiedGrid`),_=c(g,`low`).split(` `),v=c(g,`high`).split(` `),y=parseInt(v[0],10)-parseInt(_[0],10)+1,b=parseInt(v[1],10)-parseInt(_[1],10)+1,x=f(n,`origin/pos`),S=o(n,`offsetVector`),w={envelope:h,columns:y,rows:b,offset:{x:parseFloat(c(S[0]).split(` `,1)[0]),y:parseFloat(c(S[1]).split(` `,2)[1])},origin:{x:x[0],y:x[1]}},T=d(t,`temporalDomain`)||d(t,`TemporalDomain`);return{spatialDomain:w,temporalDomain:T?C(T):null}}function T(e){let t={version:`1.0`},n=[],i;for(let r=0;r<e.childNodes.length;r++){let a=e.childNodes[r];if(a.nodeType===1){if(s(a,`description`))t.description=c(a);else if(s(a,`name`))t.name=c(a);else if(s(a,`label`))t.label=c(a);else if(s(a,`supportedFormats`))t.supportedFormats=l(a,`formats`);else if(s(a,`supportedCRSs`))t.supportedCRSs=m(a);else if(s(a,`supportedInterpolations`))t.supportedInterpolations=h(a,`1.0.0`);else if(s(a,`lonLatEnvelope`))t.lonLatEnvelope=_(a);else if(s(a,`rangeSet`)){let e=x(a);t.rangeSet=e.rangeSet,n=e.bandNames;let r=e.rangeSet[0].nullValues;r?.length&&(i=b(r))}else s(a,`domainSet`)&&(t.domainSet=w(a))}}let a=g(t.supportedInterpolations),{name:o,description:u,label:d,lonLatEnvelope:f,supportedFormats:p}=t,{spatialDomain:v}=t.domainSet,y={x:Math.abs(v.offset.x),y:Math.abs(v.offset.y)},S=E(t.domainSet),C=new r({width:v.columns,height:v.rows,pixelSize:y,pixelType:`unknown`,extent:v.envelope,spatialReference:v.envelope.spatialReference,bandCount:n.length||1,noDataValue:i,multidimensionalInfo:S});return{id:o,title:t.name,description:u||d,lonLatEnvelope:f,rasterInfo:C,bandNames:n,supportedFormats:p,supportedInterpolations:a,coverageDescription:t,version:`1.0.0`,useEPSGAxis:!1}}function E(e){if(!e.temporalDomain)return null;let{begin:t,end:n,values:r,units:i,resolution:a}=e.temporalDomain,o={variables:[{name:`default`,description:``,dimensions:[{name:`StdTime`,description:``,unit:`ISO8601`,values:r?.map(e=>e.getTime()),hasRegularIntervals:!r,interval:a,intervalUnit:i,extent:[t.getTime(),n.getTime()]}]}]};return p(o),o}function D(e,t){let n=[],r=o(e,`Field`),i=[],a;for(let e=0;e<r.length;e++){let s=c(r[e],`Identifier`),u=c(r[e],`Description`),f=c(r[e],`Definition`),p=c(r[e],`Abstract`),m=c(r[e],`Title`),g=v(r[e],`NullValue`),_=d(r[e],`AllowedValues`),b=_?y(_):null,x=h(r[e],`1.1.0`),S=[],C=o(r[e],`Axis`);for(let e=0;e<C.length;e++){let n=C[e].getAttribute(`identifier`),r=c(C[e],`UOM`),o=c(C[e],`DataType`),s=l(C[e],`Key`);(!t||n.toLowerCase().includes(`band`))&&(i=s,a=g),S.push({identifier:n,uom:r,dataType:o,values:s,bandNoDataValues:a})}n.push({identifier:s,description:u,definition:f,abstract:p,title:m,supportedInterpolations:x,axis:S,nullValues:g,statistics:b})}let s=n[0].statistics;return{rangeSet:n,bandNames:i,bandNoDataValues:a,statistics:s}}function O(e,t){if(!t.temporalDomain)return null;let n=e.filter(e=>!e.identifier.toLowerCase().includes(`field_1`)&&!e.axis.some(e=>e.identifier.includes(`band`))),r=[];if(n.length&&n.forEach(e=>{let t=e.axis.map(e=>{let t=e.values.map(t=>e.uom===`ISO8601`?(t=t.trim(),t.toLowerCase().includes(`z`)?new Date(t).getTime():new Date(t+`Z`).getTime()):parseFloat(t.trim())),n=[Math.min.apply(null,t),Math.max.apply(null,t)];return{name:e.identifier.trim(),description:``,field:e.identifier.trim(),unit:e.uom?e.uom.trim():``,hasRegularIntervals:!1,values:t,extent:n}});r.push({name:e.identifier.trim(),description:e.description?.trim()??``,unit:``,dimensions:t,statistics:e.statistics})}),t.temporalDomain){let{begin:e,end:n,values:i,units:a,resolution:o}=t.temporalDomain;r.some(e=>e.dimensions.some(e=>e.name.toLowerCase()===`stdtime`))||r.forEach(t=>{t.dimensions.push({name:`StdTime`,description:``,unit:`ISO8601`,values:i?.map(e=>e.getTime()),hasRegularIntervals:!i,interval:o,intervalUnit:a,extent:[e.getTime(),n.getTime()]})})}if(r.length){let e={variables:r};return p(e),e}return null}function k(t){let r=d(t,`SpatialDomain`),i=d(r,`GridCRS`),a=c(i,`GridBaseCRS`),s=c(i,`GridOrigin`)?.split(` `).map(e=>parseFloat(e))??[0,0],l=f(i,`GridOffsets`),u=o(r,`BoundingBox`),p,m,h,g;for(let t=0;t<u.length;t++){let n=u[t].getAttribute(`crs`)?.toLowerCase();if(n!=null){if(n.includes(`imagecrs`)){let e=f(u[t],`LowerCorner`),n=f(u[t],`UpperCorner`);p=n[0]-e[0]+1,m=n[1]-e[1]+1}else if(n.indexOf(`epsg`)>0){let r=n.split(`:`);h=parseInt(r[r.length-1],10);let i=f(u[t],`LowerCorner`),a=f(u[t],`UpperCorner`);g=new e({xmin:i[0],ymin:i[1],xmax:a[0],ymax:a[1],spatialReference:{wkid:h}})}}}let _=p>m,v=g.xmax-g.xmin>g.ymax-g.ymin,y=!1;n(h)&&(_===v?y=!1:(y=!0,g=new e({xmin:g.ymin,ymin:g.xmin,xmax:g.ymax,ymax:g.xmax,spatialReference:{wkid:h}})));let b={columns:p,rows:m,origin:{x:s[0],y:s[1]},offset:{x:l[0],y:l[l.length-1]},gridBaseCRS:a,envelope:g,useEPSGAxis:y},x=d(t,`temporalDomain`)||d(t,`TemporalDomain`);return{spatialDomain:b,temporalDomain:x?C(x):null}}function A(e,t){let n=[],i=[],a={supportedFormats:n,supportedCRSs:i,version:`1.1`},o=[],s,l;for(let t=0;t<e.childNodes.length;t++){let r=e.childNodes[t];if(r.nodeType!==1)continue;let d=u(r).toLowerCase();switch(d){case`title`:case`abstract`:case`identifier`:a[d]=c(r);break;case`supportedformat`:{let e=c(r);n.includes(e)||n.push(e)}break;case`supportedcrs`:{let e=c(r);i.includes(e)||i.push(e)}break;case`range`:{let e=D(r,!!a.domain?.temporalDomain);a.range=e.rangeSet,o=e.bandNames;let{bandNoDataValues:t}=e;t?.length&&(s=b(t)),l=e.statistics}break;case`domain`:a.domain=k(r)}}let d=g(a.range[0].supportedInterpolations),{identifier:f,abstract:p,title:m,domain:h,range:_}=a,v={x:Math.abs(h.spatialDomain.offset.x),y:Math.abs(h.spatialDomain.offset.y)},y=O(_,h);y&&(s=_[0].nullValues,s?.length===1&&(s=s[0]));let x=new r({width:h.spatialDomain.columns,height:h.spatialDomain.rows,pixelSize:v,pixelType:`unknown`,extent:h.spatialDomain.envelope,spatialReference:h.spatialDomain.envelope.spatialReference,bandCount:o.length||1,noDataValue:s,statistics:l,multidimensionalInfo:y});return{id:f,title:a.title,description:p||m,bandNames:o,rasterInfo:x,supportedFormats:n,supportedInterpolations:d,coverageDescription:a,version:t,useEPSGAxis:h.spatialDomain.useEPSGAxis}}function j(t){let n=d(t,`Envelope`)||d(t,`EnvelopeWithTimePeriod`),r=n.getAttribute(`srsName`),i=r.slice(r.lastIndexOf(`/`)+1),a=n.getAttribute(`axisLabels`).split(` `).map(e=>e.trim()).filter(e=>e.trim()!==``),o=f(n,`lowerCorner`),l=f(n,`upperCorner`),u=![`y`,`lat`,`latitude`,`north`,`nor`,`n`,`b`].includes(a[0].toLowerCase()),p,m=parseInt(i,10),h=isNaN(m)?null:{wkid:m};p=u?new e({xmin:o[0],ymin:o[1],xmax:l[0],ymax:l[1],spatialReference:h}):new e({xmin:o[1],ymin:o[0],xmax:l[1],ymax:l[0],spatialReference:h});let g={mins:o,maxs:l},_=n.getAttribute(`uomLabels`).trim().split(` `),v,y;if(s(n,`EnvelopeWithTimePeriod`)){v=new Date(c(t,`beginPosition`)||c(t,`BeginPosition`)),y=new Date(c(t,`endPosition`)||c(t,`EndPosition`));let e=_?.findIndex(e=>e?.toLowerCase()===`oledatetime`);e>-1&&(_[e]=`ISO8601`)}return{envelope:p,axisLabels:a,uomLabels:_.length?_:null,envelopeAllDims:g,beginPosition:v,endPosition:y,isEastFirst:u}}function M(e,t){let n=[],r=o(e,`DataRecord`),i=[],a=[],s;for(let e=0;e<r.length;e++){let l=o(r[e],`field`),u=[];for(let e=0;e<l.length;e++){let n=l[e].getAttribute(`name`),r=c(l[e],`description`)||``,o=d(l[e],`uom`)?.getAttribute(`code`)||``,p=f(l[e],`interval`),m=v(l[e],`nilValue`)?.[0];(!t||n.toLowerCase().includes(`band`))&&(i.push(n),p?.length&&(s||=[],s.push({min:p[0],max:p[1],avg:-1,stddev:-1})),a.push(m)),u.push({name:n,description:r,uom:o,allowedValues:p,nilValue:m})}n.push(u)}return a.some(e=>e!=null)||(a=null),{rangeType:n,bandNames:i,bandStats:s,bandNoDataValues:a}}function N(e){let t=1,n=``,r=.01;return Math.abs(e-1/24)<1/24*r?n=`Hours`:Math.abs(e-1)<r?n=`Days`:e<1?(t=Math.round(e*24),n=`Hours`):e>27.99&&e<31.01||Math.round(e/30)<12?n=`Months`:e>364.99&&e<366.01&&(n=`Years`),{interval:t,intervalUnit:n}}function P(e,t,n){if(n.axisLabels.length<=2)return null;let r=[];for(let t=0;t<e.length;t++){let n=e[t];for(let e=0;e<n.length;e++)n[e].name.toLowerCase().includes(`band`)||r.push(n[e])}let a=[];if(r.length){let e=[];for(let r=2;r<n.axisLabels.length;r++){let a=t.uomLabels?.[r]?.trim()??``,o=n.axisLabels[r].toLowerCase().includes(`time`)||a.toLowerCase()===`iso8601`||a.toLowerCase()===`oledatetime`,s,c;if(o){let e=N(n.offset[r]);s=e.interval,c=e.intervalUnit}else s=n.offset[r],c=a;let l=[];o?(l.push(i(t.envelopeAllDims.mins[r])),l.push(i(t.envelopeAllDims.maxs[r]))):(l.push(t.envelopeAllDims.mins[r]),l.push(t.envelopeAllDims.maxs[r])),e.push({name:n.axisLabels[r].trim(),description:n.axisLabels[r].trim(),unit:o?`ISO8601`:a,hasRegularIntervals:!0,extent:l,interval:s,intervalUnit:c})}if(r.forEach(t=>{let{allowedValues:n}=t,r=n?.length===2?[{min:n[0],max:n[1],avg:-1,stddev:-1}]:null;a.push({name:t.name.trim(),description:t.description?.trim()??``,unit:t.uom.trim(),statistics:r,dimensions:[...e]})}),a.length){let e={variables:a};return p(e),e}}return null}function F(e,t){let n=d(e,`RectifiedGrid`),r=f(n,`low`),i=f(n,`high`),a=[];for(let e=0;e<r.length;e++)a.push(i[e]-r[e]+1);let s=c(n,`axisLabels`).split(` `),l=f(n,`origin/pos`),u=o(n,`offsetVector`),p=[];for(let e=0;e<u.length;e++){let t=f(u[e]),n=t.findIndex(e=>e!==0);p[n]=t[n]}let m=[`y`,`lat`,`latitude`,`north`,`nor`,`n`,`b`],h=!1;t?.length&&s?.length&&(h=[...t].sort((e,t)=>e<t?-1:1).join(`,`)===[...s].sort((e,t)=>e<t?-1:1).join(`,`));let g=h?s:t,_,v,y;return m.includes(g[0].toLowerCase())?(_=a[1],v=a[0],y={y:Math.abs(p[0]),x:Math.abs(p[1])}):(_=a[0],v=a[1],y={x:Math.abs(p[0]),y:Math.abs(p[1])}),{columns:_,rows:v,origin:l,offset:p,resolution:y,gridSamples:a,axisLabels:s,hasSameAxisLabelsAsBoundedBy:h}}function I(e){let n=d(e,`EarthObservation`);if(!n)return null;let r=d(n,`phenomenonTime`),i=r?C(r):null,a=d(n,`phenomenonTime`),o=a?C(a):null,s=c(n,`featureOfInterest/Footprint/multiExtentOf/MultiSurface/surfaceMembers/Polygon/exterior/LinearRing/posList`),l=null;if(s){let e=s.split(` `).map(e=>e.trim()).filter(e=>e!=null&&e!==``).map(Number);if(e.length){let n=[];for(let t=0;t<e.length/2;t+=2)n.push(e[t],e[t+1]);l=new t({rings:[[n]]})}}let u=c(e,`metaDataProperty/EarthObservationMetaData/identifier`),f=c(e,`metaDataProperty/EarthObservationMetaData/acquisitionType`),p=c(e,`metaDataProperty/EarthObservationMetaData/status`);return{observation:{phenomenonTime:i,resultTime:o,footprint:l,identifier:u,acquisitionType:f,status:p}}}function L(e){let t={version:`2.0`},n=[],i,a;for(let r=0;r<e.childNodes.length;r++){let o=e.childNodes[r];if(o.nodeType===1){if(s(o,`coverageId`))t.coverageId=c(o);else if(s(o,`ServiceParameters`))t.serviceParameters={supportedFormats:l(o,`nativeFormat`)};else if(s(o,`boundedBy`))t.boundedBy=j(o);else if(s(o,`rangeType`)){let e=M(o,t.boundedBy?.axisLabels.length>2||t.domainSet?.axisLabels.length>2);t.rangeType=e.rangeType,n=e.bandNames,i=e.bandStats;let{bandNoDataValues:r}=e;r?.length&&(a=b(r))}else if(s(o,`domainSet`))t.domainSet=F(o,t.boundedBy?.axisLabels);else if(s(o,`metadata`)){let e=d(o,`EOMetadata`);t.eoMetadata=e?I(e):null}}}let{coverageId:o,boundedBy:u,domainSet:f,rangeType:p,serviceParameters:m}=t,h=P(p,u,f);!i&&h&&(i=h?.variables[0].statistics),h!=null&&(a=p[0][0].nilValue);let g=new r({width:f.columns,height:f.rows,pixelSize:f.resolution,pixelType:`unknown`,extent:u.envelope,spatialReference:u.envelope.spatialReference,bandCount:n.length||1,statistics:i,noDataValue:a,multidimensionalInfo:h});return{id:o,title:o,description:o,bandNames:n,rasterInfo:g,supportedFormats:m.supportedFormats,coverageDescription:t,version:`2.0.1`,useEPSGAxis:!1}}function R(e,t){let n=null;if(n=typeof e==`string`?new DOMParser().parseFromString(e,`text/xml`):e,t===`1.0.0`)return o(n,`CoverageOffering`).map(e=>T(e));let r=o(n,`CoverageDescription`);return t===`1.1.0`||t===`1.1.1`||t===`1.1.2`?r.map(e=>A(e,t)):r.map(e=>L(e))}export{R as parseCoverages,g as standardizeInterpolations};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
- import e from"../../../core/Error.js";import{assertIsSome as t}from"../../../core/maybe.js";import{throwIfAborted as n,isAbortError as r}from"../../../core/promiseUtils.js";import i from"../../support/PixelBlock.js";import a from"../../support/SimpleBandStatistics.js";import{decode as o}from"./ImageCanvasDecoder.js";import{decode as s}from"./JpgPlus.js";import{load as c,decode as l}from"./Lerc.js";import{decode as u}from"./Lzw.js";import{convertNoDataToMask as d}from"./pixelRangeUtils.js";import{load as f,decode as p}from"./Qb3.js";import{decode as m}from"./Raw.js";import{decodeTileOrStrip as h,decode as g}from"./TiffDecoder.js";import{isPlatformLittleEndian as _}from"./utils.js";import{inflate as v}from"./Zlib.js";async function y(t,n){if(!_)throw new e(`rasterCoded:decode`,`lerc decoder is not supported on big endian platform`);await c();let{width:r,height:o,pixelType:s,statistics:u,depthCount:d,noDataValues:f,bandMasks:p,pixels:m,mask:h,validPixelCount:g}=l(t,{inputOffset:n.offset,returnInterleaved:n.returnInterleaved});return new i({width:r,height:o,pixelType:s.toLowerCase(),pixels:m,mask:h,validPixelCount:g,statistics:u.map(({minValue:e,maxValue:t})=>new a(e,t)),bandMasks:p,depthCount:d,noDataValues:f})}async function b(t,n){await f();let r=p(t);if(!r)throw new e(`rasterCodec:decode`,`failed to decode the input data.`);let{width:a,height:o,pixels:s,pixelType:c}=r;return new i({width:a,height:o,pixelType:c,pixels:s})}async function x(e,n,r){let a=await g(e,{...n,noDataValue:n.tiffNoDataValue,matchAllNoData:n.matchAllNoData},r);return t(a),new i({width:a.width,height:a.height,pixels:a.pixels,pixelType:a.pixelType.toLowerCase(),mask:a.mask,bandMasks:a.bandMasks})}async function S(e,t,n){let r=await h(e,t.customOptions,n),a=new i({width:r.width,height:r.height,pixels:r.pixels,pixelType:r.pixelType.toLowerCase(),mask:r.mask});return t.skipStatistics||a.updateStatistics(),a}function C(e,t){let n=t.pixelType||`u8`,r=i.getPixelArrayConstructor(n),a=n===`u8`?e:new r(e.buffer),o=[],s=t.planes||1;if(s===1)o.push(a);else for(let n=0;n<s;n++){let i=(t.width||1)*(t.height||e.length),c=new r(i);for(let e=0;e<i;e++)c[e]=a[e*s+n];o.push(c)}return new i({width:t.width||1,height:t.height||e.length,pixels:o,pixelType:n})}async function w(e,t,n){return C(await v(new Uint8Array(e),void 0,n),t)}function T(e,t){return C(u(e,t.offset,t.eof,!t.isInputBigEndian),t)}function E(e,t){let n=t.format,{pixelTypeCtor:r}=j(t.pixelType),a=m(e,{width:t.width,height:t.height,pixelType:r,format:n});return new i({width:t.width,height:t.height,pixels:a.pixels,pixelType:t.pixelType,mask:a.mask})}async function D(e,t){let n=await s(e,t);return new i({width:n.width,height:n.height,pixels:n.pixels,pixelType:`u8`,mask:n.mask})}async function O(e,t,n){let r=await o(e,t,n);return new i(r)}async function k(t,n,i){let a=n.format||N(t),o={...n,format:a},{canvasUsage:s}=n;if(s!==`no-canvas`||a===`png`)try{return await O(t,o,i)}catch(t){if(r(t))throw t;if(s===`canvas-only`)throw new e(`rasterCodec:decode`,`failed to decode the input data with canvas for format ${a}`)}return await D(t,o)}function A(t){let n=null;switch(t){case`lerc`:n=y;break;case`jpg`:case`png`:n=k;break;case`bmp`:case`gif`:n=O;break;case`bsq`:case`bip`:n=E;break;case`tiff`:n=x;break;case`deflate`:n=w;break;case`lzw`:n=T;break;case`qb3`:n=b;break;default:n=()=>{throw new e(`rasterCodec:decode`,`unsupported raster format ${t}`)}}return n}function j(e){let t=e?e.toLowerCase():`f32`,n=null,r=null;switch(t){case`u1`:case`u2`:case`u4`:case`u8`:r=255,n=Uint8Array;break;case`u16`:r||=2**16-1,n=Uint16Array;break;case`u32`:r||=2**32-1,n=Uint32Array;break;case`s8`:r||=-128,n=Int8Array;break;case`s16`:r||=0-2**15,n=Int16Array;break;case`s32`:r||=0-2**31,n=Int32Array;break;default:n=Float32Array}return{pixelTypeCtor:n,noDataValue:r}}function M(e,t=`bilinear`){if(!e)return;let{pixels:n,width:r,height:a,mask:o}=e;if(!n||n.length===0)return;let s=r-1,c=a-1,l=[],u=null,d=i.getPixelArrayConstructor(e.pixelType);if(t===`nearest`){for(let e of n){let t=new d(s*c);for(let n=0;n<c;n++){let i=n*r;for(let r=0;r<s;r++)t[n*s+r]=e[i+r]}l.push(t)}if(o!=null){u=new Uint8Array(s*c);for(let e=0;e<c;e++){let t=e*r;for(let n=0;n<s;n++)u[e*s+n]=o[t+n]}}}else{for(let e of n){let t=new d(s*c);for(let n=0;n<c;n++){let i=n*r;for(let a=0;a<s;a++)t[n*s+a]=(e[i+a]+e[i+a+1]+e[i+r+a]+e[i+r+a+1])/4}l.push(t)}if(o){u=new Uint8Array(s*c);for(let e=0;e<c;e++){let t=e*r;for(let n=0;n<s;n++)u[e*s+n]=Math.min.apply(null,[o[t+n],o[t+n+1],o[t+r+n],o[t+r+n+1]])}}}e.width=s,e.height=c,e.mask=u,e.pixels=l}function N(e){if(!e)return;let t=new Uint8Array(e,0,10),n;return t[0]===255&&t[1]===216?n=`jpg`:t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?n=`png`:t[0]===67&&t[1]===110&&t[2]===116&&t[3]===90&&t[4]===73&&t[5]===109&&t[6]===97&&t[7]===103&&t[8]===101&&t[9]===32||t[0]===76&&t[1]===101&&t[2]===114&&t[3]===99&&t[4]===50&&t[5]===32?n=`lerc`:t[0]===73&&t[1]===73&&t[2]===42&&t[3]===0||t[0]===77&&t[1]===77&&t[2]===0&&t[3]===42||t[0]===73&&t[1]===73&&t[2]===43&&t[3]===0||t[0]===77&&t[1]===77&&t[2]===0&&t[3]===43?n=`tiff`:t[0]===71&&t[1]===73&&t[2]===70?n=`gif`:t[0]===66&&t[1]===77?n=`bmp`:t[0]===81&&t[1]===66&&t[2]===51&&(n=`qb3`),n}async function P(t,r={},a){if(t==null)throw new e(`rasterCodec:decode`,`missing encodeddata parameter.`);let o=r.format?.toLowerCase();if((o===`bsq`||o===`bip`)&&(r.width==null||r.height==null))throw new e(`rasterCodec:decode`,`requires width and height in options parameter.`);if(o===`tiff`&&r.customOptions)return S(t,r,a);if(!o||o!==`bsq`&&o!==`bip`&&o!==`deflate`&&o!==`lzw`){if(o=N(t),!o)throw String.fromCharCode.apply(null,[...new Uint8Array(t,0,10)]).toLowerCase().includes(`error`)?new e(`rasterCodec:decode`,`input data contains error`):new e(`rasterCodec:decode`,`unsupported raster format`);r={...r,format:o}}let s=A(o);r.isPoint&&(r={...r},r.width!=null&&r.width++,r.height!=null&&r.height++);let c,{offsets:l}=r;if(l&&l.length>1){let e=l.map((e,n)=>s(t.slice(e,l[n+1]),r,a)),n=await Promise.all(e);c=n[0],c.pixels=n.map(e=>e.pixels[0]);let o=n.map(e=>e.mask);o.some(e=>e!=null)&&(o.forEach((e,t)=>{o[t]??=new Uint8Array(c.width*c.height).fill(255)}),c.bandMasks=o,c.mask=i.combineBandMasks(o))}else c=await s(t,{...r,offset:l?.[0]??r.offset},a);return n(a),o!==`jpg`&&r.noDataValue!=null&&c.depthCount===1&&d(c,r.noDataValue,{customFloatTolerance:r.tolerance}),r.isPoint&&M(c),!c.statistics?.length&&!r.skipStatistics&&c.updateStatistics(),c}export{P as decode,N as getFormat};
2
+ import e from"../../../core/Error.js";import{assertIsSome as t}from"../../../core/maybe.js";import{throwIfAborted as n,isAbortError as r}from"../../../core/promiseUtils.js";import i from"../../support/PixelBlock.js";import a from"../../support/SimpleBandStatistics.js";import{load as o,decodeZstd as s,decodeBlosc as c}from"./blosc.js";import{decode as l}from"./ImageCanvasDecoder.js";import{decode as u}from"./JpgPlus.js";import{load as d,decode as f}from"./Lerc.js";import{decode as p}from"./Lzw.js";import{convertNoDataToMask as m,getByteCount as h}from"./pixelRangeUtils.js";import{load as g,decode as _}from"./Qb3.js";import{decode as v}from"./Raw.js";import{decodeTileOrStrip as y,decode as b}from"./TiffDecoder.js";import{isPlatformLittleEndian as x}from"./utils.js";import{inflate as S}from"./Zlib.js";const C=new Set([`bsq`,`bip`,`deflate`,`lzw`,`blosc`,`zstd`]);async function w(t,n){if(!x)throw new e(`rasterCoded:decode`,`lerc decoder is not supported on big endian platform`);await d();let{width:r,height:o,pixelType:s,statistics:c,depthCount:l,noDataValues:u,bandMasks:p,pixels:m,mask:h,validPixelCount:g}=f(t,{inputOffset:n.offset,returnInterleaved:n.returnInterleaved});return new i({width:r,height:o,pixelType:s.toLowerCase(),pixels:m,mask:h,validPixelCount:g,statistics:c.map(({minValue:e,maxValue:t})=>new a(e,t)),bandMasks:p,depthCount:l,noDataValues:u})}async function T(t,n){await g();let r=_(t);if(!r)throw new e(`rasterCodec:decode`,`failed to decode the input data.`);let{width:a,height:o,pixels:s,pixelType:c}=r;return new i({width:a,height:o,pixelType:c,pixels:s})}async function E(e,n,r){let a=await b(e,{...n,noDataValue:n.tiffNoDataValue,matchAllNoData:n.matchAllNoData},r);return t(a),new i({width:a.width,height:a.height,pixels:a.pixels,pixelType:a.pixelType.toLowerCase(),mask:a.mask,bandMasks:a.bandMasks})}async function D(e,t,n){let r=await y(e,t.customOptions,n),a=new i({width:r.width,height:r.height,pixels:r.pixels,pixelType:r.pixelType.toLowerCase(),mask:r.mask});return t.skipStatistics||a.updateStatistics(),a}function O(e,t){let n=t.pixelType||`u8`,r=i.getPixelArrayConstructor(n),a=n===`u8`?e:new r(e.buffer),o=[],s=t.planes||1;if(s===1)o.push(a);else for(let n=0;n<s;n++){let i=(t.width||1)*(t.height||e.length),c=new r(i);for(let e=0;e<i;e++)c[e]=a[e*s+n];o.push(c)}return new i({width:t.width||1,height:t.height||e.length,pixels:o,pixelType:n})}async function k(e,t,n){return O(await S(new Uint8Array(e),void 0,n),t)}function A(e,t){return O(p(e,t.offset,t.eof,!t.isInputBigEndian),t)}async function j(e,t,r){return await o(),n(r),O(c(e,t.maxUncompressedSize),t)}async function M(t,r,i){let{width:a,height:c}=r;if(a==null||c==null)throw new e(`rasterCodec:decode`,`width and height parameters are required for zstd.`);await o(),n(i);let l=h(r.pixelType??`u8`),u=r.planes||1,d=a*c*u*l;return O(s(t,d),r)}function N(e,t){let n=t.format,{pixelTypeCtor:r}=R(t.pixelType),a=v(e,{width:t.width,height:t.height,pixelType:r,format:n});return new i({width:t.width,height:t.height,pixels:a.pixels,pixelType:t.pixelType,mask:a.mask})}async function P(e,t){let n=await u(e,t);return new i({width:n.width,height:n.height,pixels:n.pixels,pixelType:`u8`,mask:n.mask})}async function F(e,t,n){let r=await l(e,t,n);return new i(r)}async function I(t,n,i){let a=n.format||B(t),o={...n,format:a},{canvasUsage:s}=n;if(s!==`no-canvas`||a===`png`)try{return await F(t,o,i)}catch(t){if(r(t))throw t;if(s===`canvas-only`)throw new e(`rasterCodec:decode`,`failed to decode the input data with canvas for format ${a}`)}return await P(t,o)}function L(t){let n=null;switch(t){case`lerc`:n=w;break;case`jpg`:case`png`:n=I;break;case`bmp`:case`gif`:n=F;break;case`bsq`:case`bip`:n=N;break;case`tiff`:n=E;break;case`deflate`:n=k;break;case`blosc`:n=j;break;case`zstd`:n=M;break;case`lzw`:n=A;break;case`qb3`:n=T;break;default:n=()=>{throw new e(`rasterCodec:decode`,`unsupported raster format ${t}`)}}return n}function R(e){let t=e?e.toLowerCase():`f32`,n=null,r=null;switch(t){case`u1`:case`u2`:case`u4`:case`u8`:r=255,n=Uint8Array;break;case`u16`:r||=2**16-1,n=Uint16Array;break;case`u32`:r||=2**32-1,n=Uint32Array;break;case`s8`:r||=-128,n=Int8Array;break;case`s16`:r||=0-2**15,n=Int16Array;break;case`s32`:r||=0-2**31,n=Int32Array;break;default:n=Float32Array}return{pixelTypeCtor:n,noDataValue:r}}function z(e,t=`bilinear`){if(!e)return;let{pixels:n,width:r,height:a,mask:o}=e;if(!n||n.length===0)return;let s=r-1,c=a-1,l=[],u=null,d=i.getPixelArrayConstructor(e.pixelType);if(t===`nearest`){for(let e of n){let t=new d(s*c);for(let n=0;n<c;n++){let i=n*r;for(let r=0;r<s;r++)t[n*s+r]=e[i+r]}l.push(t)}if(o!=null){u=new Uint8Array(s*c);for(let e=0;e<c;e++){let t=e*r;for(let n=0;n<s;n++)u[e*s+n]=o[t+n]}}}else{for(let e of n){let t=new d(s*c);for(let n=0;n<c;n++){let i=n*r;for(let a=0;a<s;a++)t[n*s+a]=(e[i+a]+e[i+a+1]+e[i+r+a]+e[i+r+a+1])/4}l.push(t)}if(o){u=new Uint8Array(s*c);for(let e=0;e<c;e++){let t=e*r;for(let n=0;n<s;n++)u[e*s+n]=Math.min.apply(null,[o[t+n],o[t+n+1],o[t+r+n],o[t+r+n+1]])}}}e.width=s,e.height=c,e.mask=u,e.pixels=l}function B(e){if(!e)return;let t=new Uint8Array(e,0,Math.min(e.byteLength,10)),n;return t[0]===255&&t[1]===216?n=`jpg`:t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?n=`png`:t[0]===67&&t[1]===110&&t[2]===116&&t[3]===90&&t[4]===73&&t[5]===109&&t[6]===97&&t[7]===103&&t[8]===101&&t[9]===32||t[0]===76&&t[1]===101&&t[2]===114&&t[3]===99&&t[4]===50&&t[5]===32?n=`lerc`:t[0]===73&&t[1]===73&&t[2]===42&&t[3]===0||t[0]===77&&t[1]===77&&t[2]===0&&t[3]===42||t[0]===73&&t[1]===73&&t[2]===43&&t[3]===0||t[0]===77&&t[1]===77&&t[2]===0&&t[3]===43?n=`tiff`:t[0]===71&&t[1]===73&&t[2]===70?n=`gif`:t[0]===66&&t[1]===77?n=`bmp`:t[0]===81&&t[1]===66&&t[2]===51?n=`qb3`:t[0]===40&&t[1]===181&&t[2]===47&&t[3]===253&&(n=`zstd`),n}async function V(t,r={},a){if(t==null)throw new e(`rasterCodec:decode`,`missing encodeddata parameter.`);let o=r.format?.toLowerCase();if((o===`bsq`||o===`bip`)&&(r.width==null||r.height==null))throw new e(`rasterCodec:decode`,`requires width and height in options parameter.`);if(o===`tiff`&&r.customOptions)return D(t,r,a);if(!o||!C.has(o)){if(o=B(t),!o)throw String.fromCharCode.apply(null,[...new Uint8Array(t,0,10)]).toLowerCase().includes(`error`)?new e(`rasterCodec:decode`,`input data contains error`):new e(`rasterCodec:decode`,`unsupported raster format`);r={...r,format:o}}let s=L(o);r.isPoint&&(r={...r},r.width!=null&&r.width++,r.height!=null&&r.height++);let c,{offsets:l}=r;if(l&&l.length>1){let e=l.map((e,n)=>s(t.slice(e,l[n+1]),r,a)),n=await Promise.all(e);c=n[0],c.pixels=n.map(e=>e.pixels[0]);let o=n.map(e=>e.mask);o.some(e=>e!=null)&&(o.forEach((e,t)=>{o[t]??=new Uint8Array(c.width*c.height).fill(255)}),c.bandMasks=o,c.mask=i.combineBandMasks(o))}else c=await s(t,{...r,offset:l?.[0]??r.offset},a);return n(a),o!==`jpg`&&r.noDataValue!=null&&c.depthCount===1&&m(c,r.noDataValue,{customFloatTolerance:r.tolerance}),r.isPoint&&z(c),!c.statistics?.length&&!r.skipStatistics&&c.updateStatistics(),c}export{V as decode,B as getFormat};
@@ -0,0 +1,2 @@
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/6.0/LICENSE.txt */
2
+ import{getAssetUrl as e}from"../../../assets.js";let t,n;function r(){return t??=import(`../../../chunks/blosc-wasm.js`).then(({default:t})=>t({locateFile:t=>e(`esri/layers/raster/formats/${t}`)})).then(e=>{n=e}),t}function i(e){let t=n._malloc(e);if(!t)throw Error(`Failed to allocate memory when decoding blosc blob.`);return t}function a(e,t,r){let{_free:a}=n,o=i(e.byteLength),s=0;try{s=i(t),n.HEAPU8.set(new Uint8Array(e),o);let a=(r===`blosc`?n._decode_blosc:n._decode_zstd)(o,e.byteLength,s,t);if(a<=0)throw Error(`${r} decoding failed: ${a}`);if(a!==t)throw Error(`decoded byte length ${a} does not match expected ${t}`);return n.HEAPU8.slice(s,s+t)}finally{a(o),s&&a(s)}}function o(e,t=2**30){if(e.byteLength<16)throw Error(`Invalid Blosc header`);let n=new DataView(e),r=n.getUint32(4,!0),i=n.getUint32(12,!0);if(!r||r>t||i!==e.byteLength)throw Error(`Invalid Blosc header`);return a(e,r,`blosc`)}function s(e,t){if(e.byteLength<9)throw Error(`Invalid Zstandard header`);return a(e,t,`zstd`)}export{o as decodeBlosc,s as decodeZstd,r as load};