@arcgis/core 5.2.0-next.61 → 5.2.0-next.63

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 (253) hide show
  1. package/WebDocument2D.d.ts +17 -1
  2. package/WebDocument2D.js +1 -1
  3. package/WebLinkChart.js +1 -1
  4. package/WebMap.js +1 -1
  5. package/WebScene.js +1 -1
  6. package/applications/Components/imageryUtils.d.ts +10 -0
  7. package/applications/Components/imageryUtils.js +1 -1
  8. package/arcade/featureset/sources/FeatureLayerDynamic.js +1 -1
  9. package/arcgisGlobal.d.ts +7 -0
  10. package/assets/esri/core/workers/RemoteClient.js +1 -1
  11. package/assets/esri/core/workers/chunks/02dd79beb13eff6be85e.js +1 -0
  12. package/assets/esri/core/workers/chunks/04ffe788d2efc0a076dd.js +1 -0
  13. package/assets/esri/core/workers/chunks/0623acb2bd14a61b65c9.js +29 -0
  14. package/assets/esri/core/workers/chunks/08c2bf9defcece9e049a.js +1 -0
  15. package/assets/esri/core/workers/chunks/0d61c8d348b09179777a.js +1 -0
  16. package/assets/esri/core/workers/chunks/{3abc12d2407e4214963d.js → 13033178de9f637a2356.js} +1 -1
  17. package/assets/esri/core/workers/chunks/14cd8bb1ad4da8d1d2ca.js +1 -0
  18. package/assets/esri/core/workers/chunks/23a3d8f91caf3136b2aa.js +1 -0
  19. package/assets/esri/core/workers/chunks/{3157f85bb319294878ca.js → 2426601b8cae7f06af4d.js} +2 -2
  20. package/assets/esri/core/workers/chunks/2a1c6df073e6ca6a6365.js +1 -0
  21. package/assets/esri/core/workers/chunks/{a615a644086e98a90579.js → 3f775deea48e268411f1.js} +3 -3
  22. package/assets/esri/core/workers/chunks/{e3623e557ab463580fd2.js → 41e821ce229bc56dc1a1.js} +1 -1
  23. package/assets/esri/core/workers/chunks/{17acbf40e7c1cb42d9bd.js → 44b1cdf28269b4fa8a39.js} +1 -1
  24. package/assets/esri/core/workers/chunks/44e8cd4b3dad777ab0c9.js +1 -0
  25. package/assets/esri/core/workers/chunks/456e616f32e7de696d38.js +1 -0
  26. package/assets/esri/core/workers/chunks/{127b111ee53e4b9184f8.js → 4dcd4a052b40047a9230.js} +1 -1
  27. package/assets/esri/core/workers/chunks/54b9667450d066c6f6ce.js +1 -0
  28. package/assets/esri/core/workers/chunks/{aaa66a04b882b0ba2961.js → 5600fc334d20c4f0c83d.js} +1 -1
  29. package/assets/esri/core/workers/chunks/5dbd8ca7e7b8eb9a0bf7.js +1 -0
  30. package/assets/esri/core/workers/chunks/5e3d5347223f0111f40f.js +1 -0
  31. package/assets/esri/core/workers/chunks/62f3ca0719ac6bc76512.js +1 -0
  32. package/assets/esri/core/workers/chunks/{14c066c31fe37b7f6e63.js → 638ed1297efdb24f4711.js} +1 -1
  33. package/assets/esri/core/workers/chunks/63ede7295938f7010808.js +1 -0
  34. package/assets/esri/core/workers/chunks/687cf21e027f49b44d22.js +1 -0
  35. package/assets/esri/core/workers/chunks/6c98a64d92c9bca78203.js +1 -0
  36. package/assets/esri/core/workers/chunks/{e7402dfd683f82878360.js → 752343d92ed48e674351.js} +1 -1
  37. package/assets/esri/core/workers/chunks/7538a0fe0cec3156769e.js +1 -0
  38. package/assets/esri/core/workers/chunks/{42692a4ce3fb364e321e.js → 763cbb6716e398436a6d.js} +1 -1
  39. package/assets/esri/core/workers/chunks/{d6aad815fc0ee8e24bb5.js → 7ce52b850dd785bfa33f.js} +1 -1
  40. package/assets/esri/core/workers/chunks/{64247e439ef3e1f712e9.js → 7fdd6a5fa062778be55d.js} +1 -1
  41. package/assets/esri/core/workers/chunks/8369edafab7bdc59b95a.js +1 -0
  42. package/assets/esri/core/workers/chunks/{94e9cf8e729ec36de5be.js → 8c535c6a39d2be2ed655.js} +1 -1
  43. package/assets/esri/core/workers/chunks/8e1d4867406753c5483c.js +1 -0
  44. package/assets/esri/core/workers/chunks/92696cce2b980373f9ad.js +1 -0
  45. package/assets/esri/core/workers/chunks/{580451761cadfe308919.js → 9954149def644c371894.js} +1 -1
  46. package/assets/esri/core/workers/chunks/9f65cc6d9f7390bb1d5b.js +1 -0
  47. package/assets/esri/core/workers/chunks/a09ce34fc7c8abe64ed5.js +1 -0
  48. package/assets/esri/core/workers/chunks/{81659d121ed732bda907.js → a12803108c3b12808698.js} +2 -2
  49. package/assets/esri/core/workers/chunks/{83991475aa54fd5aa008.js → a965d151515b76dd7566.js} +1 -1
  50. package/assets/esri/core/workers/chunks/{128799741dd3c6fc69b9.js → ac4131121230cfc14f21.js} +1 -1
  51. package/assets/esri/core/workers/chunks/afeeb11b39e140303b5a.js +1 -0
  52. package/assets/esri/core/workers/chunks/b13d2da33ec07e9d41ff.js +1 -0
  53. package/assets/esri/core/workers/chunks/{33bd9785bd0b6ccef21b.js → b2cf1d3f0d48eac23a84.js} +1 -1
  54. package/assets/esri/core/workers/chunks/{498d29e8c8be4a12ba12.js → b958f87f23f984131d09.js} +1 -1
  55. package/assets/esri/core/workers/chunks/c53b2be005721591e29b.js +1 -0
  56. package/assets/esri/core/workers/chunks/{edf87407dd20685c82ab.js → c82ab4f0908290e70ee9.js} +1 -1
  57. package/assets/esri/core/workers/chunks/{4e2f3dd158a5228c87ba.js → c85ba0700eafdc8d6f9e.js} +1 -1
  58. package/assets/esri/core/workers/chunks/d456520e4b119a2816b6.js +1 -0
  59. package/assets/esri/core/workers/chunks/d83ea3e4e9ab45334068.js +1 -0
  60. package/assets/esri/core/workers/chunks/{4f59357f535f30a6b5cc.js → d9b83d7dd7d1f7729a91.js} +1 -1
  61. package/assets/esri/core/workers/chunks/dbcec48c4ba104a6d0b5.js +1 -0
  62. package/assets/esri/core/workers/chunks/e02f02040b63d9c2e654.js +1 -0
  63. package/assets/esri/core/workers/chunks/e08c64e4ae5a68eae2be.js +1 -0
  64. package/assets/esri/core/workers/chunks/e2ddfc96ddba92302e0c.js +1 -0
  65. package/assets/esri/core/workers/chunks/{61d3fcb419d6bf7e355e.js → e65ee26feca0564aeb9b.js} +1 -1
  66. package/assets/esri/core/workers/chunks/{35cbf00f0c37a86517af.js → ed1de8b7406269e217b9.js} +1 -1
  67. package/assets/esri/core/workers/chunks/ed4ac5568dc2815b066d.js +1 -0
  68. package/assets/esri/core/workers/chunks/f029c12f1afee0e9b2a1.js +1 -0
  69. package/assets/esri/core/workers/chunks/{461c2de938bf4c9b1442.js → f6715b8765cd36d81ec8.js} +1 -1
  70. package/assets/esri/core/workers/chunks/{4fb549f11e176fc2f24a.js → f7fa932ade85cb2847b6.js} +1 -1
  71. package/assets/esri/core/workers/chunks/f9a4f4efd63b8189a4eb.js +1 -0
  72. package/assets/esri/core/workers/chunks/{26a2d4b95cda0a41d980.js → fa1c58e5b582d61a03ab.js} +1 -1
  73. package/assets/esri/core/workers/chunks/fa377112ef3b78f6ed18.js +1 -0
  74. package/chunks/VolumeMask.glsl.js +3 -0
  75. package/chunks/persistableUrlUtils.js +1 -1
  76. package/config.js +1 -1
  77. package/core/Collection.d.ts +42 -6
  78. package/core/Collection.js +1 -1
  79. package/core/screenUtils.js +1 -1
  80. package/geometry/SpatialReference.d.ts +1 -4
  81. package/geometry/support/intersectsBase.js +1 -1
  82. package/interfaces.d.ts +14 -0
  83. package/kernel.js +1 -1
  84. package/layers/BaseElevationLayer.js +1 -1
  85. package/layers/ElevationLayer.js +1 -1
  86. package/layers/IntegratedMesh3DTilesLayer.js +1 -1
  87. package/layers/KnowledgeGraphLayer.js +1 -1
  88. package/layers/Lyr3DWasmPerSceneView.js +1 -1
  89. package/layers/StreamLayer.js +1 -1
  90. package/layers/VoxelWasmPerSceneView.js +1 -1
  91. package/layers/graphics/sources/connections/createConnection.js +1 -1
  92. package/layers/graphics/sources/parquet/ParquetFileStatistics.js +1 -1
  93. package/layers/graphics/sources/support/ParquetSourceWorker.js +1 -1
  94. package/layers/graphics/sources/support/QueryTask.js +1 -1
  95. package/layers/mixins/SceneService.js +1 -1
  96. package/layers/raster/datasets/BaseRaster.js +1 -1
  97. package/layers/save/groupLayerUtils.js +1 -1
  98. package/layers/save/mediaLayerUtils.js +1 -1
  99. package/layers/support/ElevationQueryTileCache.js +1 -1
  100. package/layers/video/types.d.ts +17 -1
  101. package/linkChart/LinkChartProperties.js +1 -1
  102. package/package.json +3 -3
  103. package/popup/FeatureContent.d.ts +311 -0
  104. package/popup/FeatureContent.js +2 -0
  105. package/popup/FeatureContentCollection.d.ts +569 -0
  106. package/popup/FeatureContentCollection.js +2 -0
  107. package/portal/support/jsonContext.js +1 -1
  108. package/support/persistableUrlUtils.js +1 -1
  109. package/support/revision.js +1 -1
  110. package/symbols/cim/CIMSymbolDrawHelper.js +1 -1
  111. package/views/2d/layers/BaseLayerView2D.d.ts +2 -2
  112. package/views/2d/layers/BaseLayerViewGL2D.d.ts +2 -2
  113. package/views/2d/layers/features/sources/strategies/AFeatureLoadStrategy.js +1 -1
  114. package/views/2d/layers/features/sources/strategies/FeatureHybridTileLoadStrategy.js +1 -1
  115. package/views/2d/layers/graphics/GraphicStore.js +1 -1
  116. package/views/2d/support/hitTestUtils.js +1 -1
  117. package/views/3d/GroundView3D.js +1 -1
  118. package/views/3d/analysis/VolumeMeasurement/VolumeMeasurementCutFillController.js +1 -1
  119. package/views/3d/layers/FlowSubView3D.js +1 -1
  120. package/views/3d/layers/I3SMeshView3D.js +1 -1
  121. package/views/3d/layers/IntegratedMesh3DTilesLayerView3D.js +1 -1
  122. package/views/3d/layers/MediaLayerView3D.js +1 -1
  123. package/views/3d/layers/PointCloudLayerView3D.js +1 -1
  124. package/views/3d/layers/graphics/Deconflictor.js +1 -1
  125. package/views/3d/layers/graphics/Graphics3DCore.js +1 -1
  126. package/views/3d/layers/i3s/I3SIntersectionHandler.js +1 -1
  127. package/views/3d/layers/i3s/PointCloudRenderer.js +1 -1
  128. package/views/3d/layers/support/FeatureTileFetcher3D.js +1 -1
  129. package/views/3d/layers/support/HeatmapFeatureProcessor.js +1 -1
  130. package/views/3d/layers/support/Tiles3DMeshIntersectionHandler.js +1 -1
  131. package/views/3d/state/controllers/ZoomStepControllerGlobal.js +1 -1
  132. package/views/3d/state/controllers/ZoomStepControllerLocal.js +1 -1
  133. package/views/3d/state/helpers/SceneIntersectionHelper.js +1 -1
  134. package/views/3d/support/buffer/glUtil.js +1 -1
  135. package/views/3d/support/flow/FlowSubViewTiles3D.js +1 -1
  136. package/views/3d/support/gaussianSplatting/GaussianSplatFadeHelper.js +1 -1
  137. package/views/3d/support/gaussianSplatting/GaussianSplatFadeTexture.js +1 -1
  138. package/views/3d/support/gaussianSplatting/GaussianSplatHeaderTexture.js +1 -1
  139. package/views/3d/support/gaussianSplatting/GaussianSplatIntersectionHandler.js +1 -1
  140. package/views/3d/support/gaussianSplatting/GaussianSplatOrderTexture.js +1 -1
  141. package/views/3d/support/hitTest.js +1 -1
  142. package/views/3d/support/pointsOfInterest/CameraOnSurface.js +1 -1
  143. package/views/3d/support/pointsOfInterest/PointsOfInterest.js +1 -1
  144. package/views/3d/support/pointsOfInterest/StableSurfaceCenter.js +1 -1
  145. package/views/3d/terrain/TerrainRenderer.js +1 -1
  146. package/views/3d/terrain/TerrainSurface.js +1 -1
  147. package/views/3d/webgl-engine/collections/Component/ComponentObjectElevationAgnosticBVH.js +1 -1
  148. package/views/3d/webgl-engine/collections/Component/ComponentObjectFixedBVH.js +1 -1
  149. package/views/3d/webgl-engine/collections/Component/IntersectionGeometry.js +1 -1
  150. package/views/3d/webgl-engine/core/FBOCache.js +1 -1
  151. package/views/3d/webgl-engine/core/FBOCacheUsage.js +1 -1
  152. package/views/3d/webgl-engine/core/shaderLibrary/TextureBackedBufferFields.glsl.js +11 -11
  153. package/views/3d/webgl-engine/effects/focusArea/FocusAreaMask.js +1 -1
  154. package/views/3d/webgl-engine/lib/CutFillVisualization.js +1 -1
  155. package/views/3d/webgl-engine/lib/Intersector.js +1 -1
  156. package/views/3d/webgl-engine/lib/IntersectorResult.js +1 -1
  157. package/views/3d/webgl-engine/lib/PathGeometry.js +1 -1
  158. package/views/3d/webgl-engine/lib/RayIntersections.js +1 -1
  159. package/views/3d/webgl-engine/lib/ShadowAccumulator.js +1 -1
  160. package/views/3d/webgl-engine/lib/SortedRenderGeometryRenderer.js +1 -1
  161. package/views/3d/webgl-engine/lib/TextureBackedBuffer/TextureBackedBuffer.js +1 -1
  162. package/views/3d/webgl-engine/lib/TextureBackedBuffer/TextureBackedBufferFieldCreation.js +1 -1
  163. package/views/3d/webgl-engine/lib/ViewshedShadowMap.js +1 -1
  164. package/views/3d/webgl-engine/lib/lodRendering/LodResources.js +1 -1
  165. package/views/3d/webgl-engine/lib/screenPolygonTriangleIntersections.js +1 -1
  166. package/views/3d/webgl-engine/materials/HUDMaterial.js +1 -1
  167. package/views/3d/webgl-engine/materials/HeatmapDensityMaterial.js +1 -1
  168. package/views/3d/webgl-engine/materials/NativeLineMaterial.js +1 -1
  169. package/views/3d/webgl-engine/materials/PathMaterial.js +1 -1
  170. package/views/3d/webgl-engine/materials/RibbonLineMaterial.js +1 -1
  171. package/views/3d/webgl-engine/materials/intersectWithPolygonOffset.js +1 -1
  172. package/views/3d/webgl-engine/shaders/ShadowCastMaskTechnique.js +1 -1
  173. package/views/3d/webgl-engine/shaders/{CutFillMask.glsl.js → VolumeMask.glsl.js} +1 -1
  174. package/views/3d/webgl-engine/shaders/VolumeMaskTechnique.js +2 -0
  175. package/views/View2D.d.ts +2 -2
  176. package/views/interactive/snapping/featureSources/WorkerTileTreeDebugger.js +1 -1
  177. package/views/webgl/FramebufferObject.js +1 -1
  178. package/webdoc/support/resourceUtils.js +1 -1
  179. package/webdoc/support/types.d.ts +2 -0
  180. package/webdoc/support/utils.js +2 -0
  181. package/webdoc/support/webdocLoadUtils.js +1 -1
  182. package/webdoc/support/webdocSaveUtils.js +1 -1
  183. package/widgets/BatchAttributeForm/BatchAttributeFormViewModel.js +1 -1
  184. package/widgets/BatchAttributeForm/batchAttributeFormUtils.js +1 -1
  185. package/widgets/BatchAttributeForm/expressions/ArcadeExecutorProvider.js +1 -1
  186. package/widgets/BatchAttributeForm/expressions/ExpressionsManager.js +1 -1
  187. package/widgets/BatchAttributeForm/expressions/ExpressionsModel.js +1 -1
  188. package/widgets/BatchAttributeForm/inputs/AttachmentElementInput.js +1 -1
  189. package/widgets/BatchAttributeForm/inputs/BatchFormInputs.js +1 -1
  190. package/widgets/BatchAttributeForm/inputs/FieldInput.js +1 -1
  191. package/widgets/BatchAttributeForm/inputs/RelationshipElementInput.js +1 -1
  192. package/widgets/BatchAttributeForm/inputs/support/inputUtils.js +1 -1
  193. package/widgets/BatchAttributeForm/rendered-content/RelationshipDetails.js +1 -1
  194. package/widgets/BatchAttributeForm/templates/support/createBatchFormTemplate.js +1 -1
  195. package/widgets/BatchAttributeForm.js +1 -1
  196. package/widgets/Editor/UpdateWorkflow.js +1 -1
  197. package/widgets/Editor.js +1 -1
  198. package/widgets/FeatureForm.js +1 -1
  199. package/widgets/FeatureTable/Grid/Column.d.ts +6 -0
  200. package/widgets/Legend/support/ActiveLayerInfo.js +1 -1
  201. package/widgets/Legend/support/heatmapRampUtils.js +1 -1
  202. package/widgets/Sketch/SketchViewModel.js +1 -1
  203. package/widgets/support/SelectionList/FeatureItem.d.ts +116 -0
  204. package/widgets/support/SelectionList/GroupLayerItem.d.ts +94 -0
  205. package/widgets/support/SelectionList/ItemBase.d.ts +70 -0
  206. package/widgets/support/SelectionList/LayerItem.d.ts +140 -0
  207. package/widgets/support/SelectionList/LayerItem.js +1 -1
  208. package/widgets/support/SelectionList/SelectionListViewModel.d.ts +265 -0
  209. package/widgets/support/SelectionList/SelectionListViewModel.js +1 -1
  210. package/widgets/support/SelectionList/types.d.ts +42 -0
  211. package/widgets/support/forms/formUtils.js +1 -1
  212. package/assets/esri/core/workers/chunks/003a87b16f8a4b476e14.js +0 -1
  213. package/assets/esri/core/workers/chunks/0a50efb07eee36237e21.js +0 -1
  214. package/assets/esri/core/workers/chunks/129fdd1636e67997337c.js +0 -1
  215. package/assets/esri/core/workers/chunks/12e0c5b7cc5c3f9e6f0f.js +0 -1
  216. package/assets/esri/core/workers/chunks/26f1fd3f2be5102aae1d.js +0 -1
  217. package/assets/esri/core/workers/chunks/34fbeeeeef4bd01672c6.js +0 -1
  218. package/assets/esri/core/workers/chunks/36fe6adf6517d8f80125.js +0 -1
  219. package/assets/esri/core/workers/chunks/403f08e0c1a9203f7fba.js +0 -1
  220. package/assets/esri/core/workers/chunks/4f2170609742b51bd7b8.js +0 -1
  221. package/assets/esri/core/workers/chunks/5133083222588799493f.js +0 -1
  222. package/assets/esri/core/workers/chunks/52993a9dc0c56e9bda19.js +0 -1
  223. package/assets/esri/core/workers/chunks/5527b2da4abe0faa98bb.js +0 -1
  224. package/assets/esri/core/workers/chunks/5e35828216020f33e26b.js +0 -1
  225. package/assets/esri/core/workers/chunks/5f0d6c853873a7f32527.js +0 -1
  226. package/assets/esri/core/workers/chunks/6121cd0264b6841a5bac.js +0 -1
  227. package/assets/esri/core/workers/chunks/6823ba1688dfedba0107.js +0 -1
  228. package/assets/esri/core/workers/chunks/705d6b108fd121cea887.js +0 -1
  229. package/assets/esri/core/workers/chunks/73aa1bfa6e1dc271c9d7.js +0 -1
  230. package/assets/esri/core/workers/chunks/825eb845216762a1ed2f.js +0 -1
  231. package/assets/esri/core/workers/chunks/88df19742edb0cdc3e67.js +0 -1
  232. package/assets/esri/core/workers/chunks/8977c85aecc7e08ab13c.js +0 -1
  233. package/assets/esri/core/workers/chunks/8bdca809dd88eab9e5d8.js +0 -29
  234. package/assets/esri/core/workers/chunks/8c5726c7ce40a92901e6.js +0 -1
  235. package/assets/esri/core/workers/chunks/8c5e65982c3f9295e844.js +0 -1
  236. package/assets/esri/core/workers/chunks/8ce649e55fefc8eca55c.js +0 -1
  237. package/assets/esri/core/workers/chunks/90ae80b797642bff0efa.js +0 -1
  238. package/assets/esri/core/workers/chunks/97c758f736f28c5dab84.js +0 -1
  239. package/assets/esri/core/workers/chunks/a8ade34612e73862de6f.js +0 -1
  240. package/assets/esri/core/workers/chunks/a9d391071803b1e9e8a0.js +0 -1
  241. package/assets/esri/core/workers/chunks/aa3abc07de2921ef6ca1.js +0 -1
  242. package/assets/esri/core/workers/chunks/b03f09ee2224f0cc526a.js +0 -1
  243. package/assets/esri/core/workers/chunks/b3f1a442d6b7826e917f.js +0 -1
  244. package/assets/esri/core/workers/chunks/b819a9187426d0c146df.js +0 -1
  245. package/assets/esri/core/workers/chunks/d205edd949f3e6e24eb9.js +0 -1
  246. package/assets/esri/core/workers/chunks/f0225829f7d941914815.js +0 -1
  247. package/assets/esri/core/workers/chunks/fb34d6d96c8c0d53fcf6.js +0 -1
  248. package/chunks/CutFillMask.glsl.js +0 -3
  249. package/chunks/FocusAreaMask.glsl.js +0 -3
  250. package/views/3d/webgl-engine/effects/focusArea/FocusAreaMask.glsl.js +0 -2
  251. package/views/3d/webgl-engine/effects/focusArea/FocusAreaMaskTechnique.js +0 -2
  252. package/views/3d/webgl-engine/shaders/CutFillMaskTechnique.js +0 -2
  253. /package/assets/esri/core/workers/chunks/{81659d121ed732bda907.js.LICENSE.txt → a12803108c3b12808698.js.LICENSE.txt} +0 -0
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import t from"../PopupTemplate.js";import r from"../request.js";import{ClonableMixin as i}from"../core/Clonable.js";import o from"../core/Error.js";import{handlesGroup as s}from"../core/handleUtils.js";import{clone as n}from"../core/lang.js";import a from"../core/Logger.js";import{MultiOriginJSONSupportMixin as p}from"../core/MultiOriginJSONSupport.js";import{debounce as l,throwIfAbortError as m}from"../core/promiseUtils.js";import{urlToObject as d}from"../core/urlUtils.js";import{property as c,subclass as u}from"../core/accessorSupport/decorators.js";import{Integer as f}from"../core/accessorSupport/ensureType.js";import y from"../geometry/Extent.js";import h from"../geometry/SpatialReference.js";import{featureGeometryTypeKebabDictionary as g}from"../geometry/support/typeUtils.js";import b from"../graphic/StreamGraphicOrigin.js";import v from"./Layer.js";import{ArcGISService as w}from"./mixins/ArcGISService.js";import{BlendLayer as j}from"./mixins/BlendLayer.js";import{CustomParametersMixin as S}from"./mixins/CustomParametersMixin.js";import{DisplayFilteredLayer as I}from"./mixins/DisplayFilteredLayer.js";import{FeatureEffectLayer as x}from"./mixins/FeatureEffectLayer.js";import{FeatureReductionLayer as R}from"./mixins/FeatureReductionLayer.js";import{OperationalLayer as T}from"./mixins/OperationalLayer.js";import{PortalLayer as F}from"./mixins/PortalLayer.js";import{RefreshableLayer as P}from"./mixins/RefreshableLayer.js";import{ScaleRangeLayer as U}from"./mixins/ScaleRangeLayer.js";import{TemporalLayer as O}from"./mixins/TemporalLayer.js";import{TrackableLayer as L}from"./mixins/TrackableLayer.js";import{labelsVisible as k,legendEnabled as E,maxScale as D,minScale as A,popupEnabled as N,screenSizePerspectiveEnabled as C,url as J}from"./support/commonProperties.js";import G from"./support/FabricKustoSource.js";import{createDefaultRenderer as _}from"./support/featureLayerUtils.js";import M from"./support/Field.js";import{defineFieldProperties as V}from"./support/fieldProperties.js";import{fixRendererFields as q,fixTimeInfoFields as z}from"./support/fieldUtils.js";import{completeKustoStreamLayerInfo as K}from"./support/kustoUtils.js";import W from"./support/LabelClass.js";import{reader as Q}from"./support/labelingInfo.js";import B from"./support/PurgeOptions.js";import{defaultStreamIdField as H}from"./support/streamLayerUtils.js";import{read as X}from"../renderers/support/jsonUtils.js";import{loadStyleRenderer as Y}from"../renderers/support/styleUtils.js";import{webSceneRendererTypes as Z,rendererTypes as $}from"../renderers/support/typeUtils.js";import ee from"../rest/support/Query.js";import{createPopupTemplate as te}from"../support/popupUtils.js";import re from"../symbols/support/ElevationInfo.js";import{addLayerUnsupportedError as ie}from"../webdoc/support/unsupportedErrors.js";import{reader as oe}from"../core/accessorSupport/decorators/reader.js";const se=V();let ne=class extends(I(R(x(j(O(L(U(P(w(T(F(p(S(i(v))))))))))))))){constructor(...e){super(...e),this.copyright=null,this.definitionExpression=null,this.displayField=null,this.elevationInfo=null,this.fields=null,this.fieldsIndex=null,this.geometryDefinition=null,this.geometryType=null,this.graphicOrigin=new b(this),this.labelsVisible=!0,this.labelingInfo=null,this.legendEnabled=!0,this.maxReconnectionAttempts=0,this.maxReconnectionInterval=20,this.maxScale=0,this.minScale=0,this.objectIdField=null,this.operationalLayerType="ArcGISStreamLayer",this.outFields=["*"],this.popupEnabled=!0,this.popupTemplate=null,this.purgeOptions=new B,this.refreshInterval=0,this.screenSizePerspectiveEnabled=!0,this.source=null,this.sourceJSON=null,this.spatialReference=h.WGS84,this.type="stream",this.url=null,this.updateInterval=300,this.useViewTime=!0,this.webSocketUrl=null,this._debouncedSaveOperations=l(async(e,t,r)=>{const{save:i,saveAs:o}=await import("./save/streamLayerUtils.js");switch(e){case 0:return i(this,t);case 1:return o(this,r,t)}})}normalizeCtorArgs(e,t){return"string"==typeof e?{url:e,...t}:e}load(e){if(!("WebSocket"in globalThis))return this.addResolvingPromise(Promise.reject(new o("stream-layer:websocket-unsupported","WebSocket is not supported in this browser. StreamLayer will not have real-time connection with the stream service."))),Promise.resolve(this);const t=null!=e?e.signal:null;return this.addResolvingPromise(this.loadFromPortal({supportedTypes:["Stream Service","Feed"]},e).catch(m).then(()=>this._fetchService(t))),Promise.resolve(this)}get defaultPopupTemplate(){return this.createPopupTemplate()}set featureReduction(e){const t=this._normalizeFeatureReduction(e);this._set("featureReduction",t)}set renderer(e){q(e,this.fieldsIndex),this._set("renderer",e)}readRenderer(e,t,r){t=t.layerDefinition||t;const i=t.drawingInfo?.renderer;if(i){const e=X(i,t,r)||void 0;return e||a.getLogger(this).error("Failed to create renderer",{rendererDefinition:t.drawingInfo.renderer,layer:this,context:r}),e}return _(t,r)}async connect(e){const[{createConnection:t}]=await Promise.all([import("./graphics/sources/connections/createConnection.js"),this.load()]),r=e?.spatialReference?.toJSON()??this.spatialReference.toJSON(),i=t(this.getStreamConnectionSource(e),r),o=s([this.on("send-message-to-socket",e=>i.sendMessageToSocket(e)),this.on("send-message-to-client",e=>i.sendMessageToClient(e))]);return i.once("destroy",o.remove),i}getStreamConnectionSource(e){const{customParameters:t=null,definitionExpression:r=null,geometryDefinition:i=null,maxReconnectionAttempts:s=0,maxReconnectionInterval:n=20}=e||this.createConnectionParameters(),a=this.geometryType?g.toJSON(this.geometryType):null,p=this.spatialReference.toJSON();if(this.source){if(!this.timeInfo?.trackIdField)throw new o("stream-layer:missing-metadata","TrackIdField required for Kusto data source.");return{type:"kusto",database:this.database,table:this.source.table,trackIdField:this.timeInfo.trackIdField,geometryEncoding:this.source.geometryEncoding.toJSON(),sourceSpatialReference:p,refreshInterval:this.source.refreshInterval}}return this.webSocketUrl?{type:"custom",url:d(this.webSocketUrl),customParameters:t,definitionExpression:r,geometryDefinition:i,geometryType:a,maxReconnectionAttempts:s,maxReconnectionInterval:n,sourceSpatialReference:p}:this.parsedUrl?{type:"geoevent",url:this.parsedUrl,customParameters:t,definitionExpression:r,geometryDefinition:i,geometryType:a,maxReconnectionAttempts:s,maxReconnectionInterval:n,sourceSpatialReference:p}:{type:"client",geometryType:a,sourceSpatialReference:this.spatialReference.toJSON()}}createConnectionParameters(){return{spatialReference:this.spatialReference,customParameters:this.customParameters,definitionExpression:this.definitionExpression,geometryDefinition:this.geometryDefinition,maxReconnectionAttempts:this.maxReconnectionAttempts,maxReconnectionInterval:this.maxReconnectionInterval}}createPopupTemplate(e){return te(this,e)}createQuery(){const e=new ee;return e.returnGeometry=!0,e.outFields=["*"],e.where=this.definitionExpression||"1=1",e}getFieldDomain(e,t){if(!this.fields)return null;let r=null;return this.fields.some(t=>(t.name===e&&(r=t.domain),!!r)),r}getField(e){return this.fieldsIndex.get(e)}serviceSupportsSpatialReference(e){return!0}sendMessageToSocket(e){this.emit("send-message-to-socket",e)}sendMessageToClient(e){this.emit("send-message-to-client",e)}async save(e){return this._debouncedSaveOperations(0,e)}async saveAs(e,t){return this._debouncedSaveOperations(1,t,e)}write(e,t){return this.webSocketUrl?(ie(t,this,"a custom websocket connection cannot be written to web scenes and web maps"),null):this.source?(ie(t,this,"a custom source cannot be written to web scenes and web maps"),null):this.parsedUrl?super.write(e,t):(ie(t,this,"a client-side only connection without a url cannot be written to web scenes and web maps"),null)}async _fetchService(e){if(this.source){const e=await K(this.source.workspace,this.source.database,this.source.table,{fields:this.fields,source:this.source,database:this.database});if(this.database=e.database,!e.fields)throw new o("stream-layer:missing-metadata","The stream layer fields must be specified.");if(this.fields=e.fields,!e.source)throw new o("stream-layer:missing-metadata","Unable to infer Kusto source.",{layerInfo:e});if(!e.source.geometryEncoding)throw new o("stream-layer:missing-metadata","Unable to infer Kusto geometry encoding.",{layerInfo:e});this.source=e.source}if(this.parsedUrl){if(!this.sourceJSON){const{data:t}=await r(this.parsedUrl.path,{query:{f:"json",...this.customParameters,...this.parsedUrl.query},responseType:"json",signal:e});this.sourceJSON=t}}else{if(!this.timeInfo?.trackIdField)throw new o("stream-layer:missing-metadata","The stream layer trackIdField must be specified.");if(!this.fields)throw new o("stream-layer:missing-metadata","The stream layer fields must be specified.");if(!this.objectIdField){const e=this.fields.find(e=>"oid"===e.type)?.name;e&&(this.objectIdField=e)}if(this.fields.some(e=>e.name===this.objectIdField)||this.fields.push(new M({name:this.objectIdField,alias:this.objectIdField,type:"oid"})),!this.geometryType)throw new o("stream-layer:missing-metadata","The stream layer geometryType must be specified.")}return this.read(this.sourceJSON,{origin:"service",portalItem:this.portalItem,portal:this.portalItem?.portal,url:this.parsedUrl}),q(this.renderer,this.fieldsIndex),z(this.timeInfo,this.fieldsIndex),this.objectIdField||(this.objectIdField=H),Y(this,{origin:"service"})}};e([c({type:String})],ne.prototype,"copyright",void 0),e([c()],ne.prototype,"database",void 0),e([c({readOnly:!0})],ne.prototype,"defaultPopupTemplate",null),e([c({type:String,json:{name:"layerDefinition.definitionExpression",write:{enabled:!0,allowNull:!0}}})],ne.prototype,"definitionExpression",void 0),e([c({type:String})],ne.prototype,"displayField",void 0),e([c({type:re})],ne.prototype,"elevationInfo",void 0),e([c({json:{origins:{"web-map":{read:!1,write:!1},"portal-item":{read:!1,write:!1},"web-scene":{read:!1,write:!1}}}})],ne.prototype,"featureReduction",null),e([c(se.fields)],ne.prototype,"fields",void 0),e([c(se.fieldsIndex)],ne.prototype,"fieldsIndex",void 0),e([c({type:y,json:{name:"layerDefinition.definitionGeometry",write:!0}})],ne.prototype,"geometryDefinition",void 0),e([c({type:g.apiValues,json:{read:{reader:g.read}}})],ne.prototype,"geometryType",void 0),e([c({readOnly:!0,clonable:!1})],ne.prototype,"graphicOrigin",void 0),e([c(k)],ne.prototype,"labelsVisible",void 0),e([c({type:[W],json:{name:"layerDefinition.drawingInfo.labelingInfo",read:{reader:Q},write:!0}})],ne.prototype,"labelingInfo",void 0),e([c(E)],ne.prototype,"legendEnabled",void 0),e([c({type:["show","hide"],json:{origins:{"portal-item":{read:!1,write:!1}}}})],ne.prototype,"listMode",void 0),e([c({type:f})],ne.prototype,"maxReconnectionAttempts",void 0),e([c({type:f})],ne.prototype,"maxReconnectionInterval",void 0),e([c(D)],ne.prototype,"maxScale",void 0),e([c(A)],ne.prototype,"minScale",void 0),e([c({type:String})],ne.prototype,"objectIdField",void 0),e([c({value:"ArcGISStreamLayer",type:["ArcGISStreamLayer"]})],ne.prototype,"operationalLayerType",void 0),e([c({readOnly:!0})],ne.prototype,"outFields",void 0),e([c(N)],ne.prototype,"popupEnabled",void 0),e([c({type:t,json:{name:"popupInfo",write:!0}})],ne.prototype,"popupTemplate",void 0),e([c({type:B})],ne.prototype,"purgeOptions",void 0),e([c({json:{read:!1,write:!1}})],ne.prototype,"refreshInterval",void 0),e([c({types:$,json:{origins:{service:{write:{target:"drawingInfo.renderer",enabled:!1}},"web-scene":{name:"layerDefinition.drawingInfo.renderer",types:Z,write:!0}},write:{target:"layerDefinition.drawingInfo.renderer"}}})],ne.prototype,"renderer",null),e([oe("service","renderer",["drawingInfo.renderer","defaultSymbol"]),oe("renderer",["layerDefinition.drawingInfo.renderer","layerDefinition.defaultSymbol"])],ne.prototype,"readRenderer",null),e([c((()=>{const e=n(C);return e.json.origins["portal-item"]={read:!1,write:!1},e})())],ne.prototype,"screenSizePerspectiveEnabled",void 0),e([c({type:G,json:{write:!1}})],ne.prototype,"source",void 0),e([c()],ne.prototype,"sourceJSON",void 0),e([c({type:h,json:{origins:{service:{read:{source:"spatialReference"}}}}})],ne.prototype,"spatialReference",void 0),e([c({json:{read:!1}})],ne.prototype,"type",void 0),e([c(J)],ne.prototype,"url",void 0),e([c({type:Number})],ne.prototype,"updateInterval",void 0),e([c({json:{read:!1,write:!1}})],ne.prototype,"useViewTime",void 0),e([c({type:String})],ne.prototype,"webSocketUrl",void 0),ne=e([u("esri.layers.StreamLayer")],ne);const ae=ne;export{ae as default};
2
+ import{__decorate as e}from"tslib";import t from"../PopupTemplate.js";import r from"../request.js";import{ClonableMixin as i}from"../core/Clonable.js";import o from"../core/Error.js";import{handlesGroup as s}from"../core/handleUtils.js";import{clone as n}from"../core/lang.js";import a from"../core/Logger.js";import{MultiOriginJSONSupportMixin as p}from"../core/MultiOriginJSONSupport.js";import{debounce as l,throwIfAbortError as m}from"../core/promiseUtils.js";import{urlToObject as d}from"../core/urlUtils.js";import{property as c,subclass as u}from"../core/accessorSupport/decorators.js";import{Integer as f}from"../core/accessorSupport/ensureType.js";import y from"../geometry/Extent.js";import h from"../geometry/SpatialReference.js";import{featureGeometryTypeKebabDictionary as g}from"../geometry/support/typeUtils.js";import b from"../graphic/StreamGraphicOrigin.js";import v from"./Layer.js";import{ArcGISService as w}from"./mixins/ArcGISService.js";import{BlendLayer as j}from"./mixins/BlendLayer.js";import{CustomParametersMixin as S}from"./mixins/CustomParametersMixin.js";import{DisplayFilteredLayer as I}from"./mixins/DisplayFilteredLayer.js";import{FeatureEffectLayer as x}from"./mixins/FeatureEffectLayer.js";import{FeatureReductionLayer as R}from"./mixins/FeatureReductionLayer.js";import{OperationalLayer as T}from"./mixins/OperationalLayer.js";import{PortalLayer as F}from"./mixins/PortalLayer.js";import{RefreshableLayer as P}from"./mixins/RefreshableLayer.js";import{ScaleRangeLayer as U}from"./mixins/ScaleRangeLayer.js";import{TemporalLayer as L}from"./mixins/TemporalLayer.js";import{TrackableLayer as O}from"./mixins/TrackableLayer.js";import{labelsVisible as k,legendEnabled as E,maxScale as D,minScale as A,popupEnabled as C,screenSizePerspectiveEnabled as N,url as J}from"./support/commonProperties.js";import G from"./support/FabricKustoSource.js";import{createDefaultRenderer as _}from"./support/featureLayerUtils.js";import M from"./support/Field.js";import{defineFieldProperties as V}from"./support/fieldProperties.js";import{fixRendererFields as q,fixTimeInfoFields as z}from"./support/fieldUtils.js";import{completeKustoStreamLayerInfo as K}from"./support/kustoUtils.js";import W from"./support/LabelClass.js";import{reader as Q}from"./support/labelingInfo.js";import B from"./support/PurgeOptions.js";import{defaultStreamIdField as H}from"./support/streamLayerUtils.js";import{read as X}from"../renderers/support/jsonUtils.js";import{loadStyleRenderer as Y}from"../renderers/support/styleUtils.js";import{webSceneRendererTypes as Z,rendererTypes as $}from"../renderers/support/typeUtils.js";import ee from"../rest/support/Query.js";import{createPopupTemplate as te}from"../support/popupUtils.js";import re from"../symbols/support/ElevationInfo.js";import{addLayerUnsupportedError as ie}from"../webdoc/support/unsupportedErrors.js";import{reader as oe}from"../core/accessorSupport/decorators/reader.js";const se=V();let ne=class extends(I(R(x(j(L(O(U(P(w(T(F(p(S(i(v))))))))))))))){constructor(...e){super(...e),this.copyright=null,this.definitionExpression=null,this.displayField=null,this.elevationInfo=null,this.fields=null,this.fieldsIndex=null,this.geometryDefinition=null,this.geometryType=null,this.graphicOrigin=new b(this),this.labelsVisible=!0,this.labelingInfo=null,this.legendEnabled=!0,this.maxReconnectionAttempts=0,this.maxReconnectionInterval=20,this.maxScale=0,this.minScale=0,this.objectIdField=null,this.operationalLayerType="ArcGISStreamLayer",this.outFields=["*"],this.popupEnabled=!0,this.popupTemplate=null,this.purgeOptions=new B,this.refreshInterval=0,this.screenSizePerspectiveEnabled=!0,this.source=null,this.sourceJSON=null,this.spatialReference=h.WGS84,this.type="stream",this.url=null,this.updateInterval=300,this.useViewTime=!0,this.webSocketUrl=null,this._debouncedSaveOperations=l(async(e,t,r)=>{const{save:i,saveAs:o}=await import("./save/streamLayerUtils.js");switch(e){case 0:return i(this,t);case 1:return o(this,r,t)}})}normalizeCtorArgs(e,t){return"string"==typeof e?{url:e,...t}:e}load(e){if(!("WebSocket"in globalThis))return this.addResolvingPromise(Promise.reject(new o("stream-layer:websocket-unsupported","WebSocket is not supported in this browser. StreamLayer will not have real-time connection with the stream service."))),Promise.resolve(this);const t=null!=e?e.signal:null;return this.addResolvingPromise(this.loadFromPortal({supportedTypes:["Stream Service","Feed"]},e).catch(m).then(()=>this._fetchService(t))),Promise.resolve(this)}get defaultPopupTemplate(){return this.createPopupTemplate()}set featureReduction(e){const t=this._normalizeFeatureReduction(e);this._set("featureReduction",t)}set renderer(e){q(e,this.fieldsIndex),this._set("renderer",e)}readRenderer(e,t,r){t=t.layerDefinition||t;const i=t.drawingInfo?.renderer;if(i){const e=X(i,t,r)||void 0;return e||a.getLogger(this).error("Failed to create renderer",{rendererDefinition:t.drawingInfo.renderer,layer:this,context:r}),e}return _(t,r)}async connect(e){const[{createConnection:t}]=await Promise.all([import("./graphics/sources/connections/createConnection.js"),this.load()]),r=e?.spatialReference??this.spatialReference,i=t(this.getStreamConnectionSource(e),r),o=s([this.on("send-message-to-socket",e=>i.sendMessageToSocket(e)),this.on("send-message-to-client",e=>i.sendMessageToClient(e))]);return i.once("destroy",o.remove),i}getStreamConnectionSource(e){const{customParameters:t=null,definitionExpression:r=null,geometryDefinition:i=null,maxReconnectionAttempts:s=0,maxReconnectionInterval:n=20}=e||this.createConnectionParameters(),a=this.geometryType?g.toJSON(this.geometryType):null,p=this.spatialReference.toJSON();if(this.source){if(!this.timeInfo?.trackIdField)throw new o("stream-layer:missing-metadata","TrackIdField required for Kusto data source.");return{type:"kusto",database:this.database,table:this.source.table,trackIdField:this.timeInfo.trackIdField,geometryEncoding:this.source.geometryEncoding.toJSON(),sourceSpatialReference:p,refreshInterval:this.source.refreshInterval}}return this.webSocketUrl?{type:"custom",url:d(this.webSocketUrl),customParameters:t,definitionExpression:r,geometryDefinition:i,geometryType:a,maxReconnectionAttempts:s,maxReconnectionInterval:n,sourceSpatialReference:p}:this.parsedUrl?{type:"geoevent",url:this.parsedUrl,customParameters:t,definitionExpression:r,geometryDefinition:i,geometryType:a,maxReconnectionAttempts:s,maxReconnectionInterval:n,sourceSpatialReference:p}:{type:"client",geometryType:a,sourceSpatialReference:this.spatialReference.toJSON()}}createConnectionParameters(){return{spatialReference:this.spatialReference,customParameters:this.customParameters,definitionExpression:this.definitionExpression,geometryDefinition:this.geometryDefinition,maxReconnectionAttempts:this.maxReconnectionAttempts,maxReconnectionInterval:this.maxReconnectionInterval}}createPopupTemplate(e){return te(this,e)}createQuery(){const e=new ee;return e.returnGeometry=!0,e.outFields=["*"],e.where=this.definitionExpression||"1=1",e}getFieldDomain(e,t){if(!this.fields)return null;let r=null;return this.fields.some(t=>(t.name===e&&(r=t.domain),!!r)),r}getField(e){return this.fieldsIndex.get(e)}serviceSupportsSpatialReference(e){return!0}sendMessageToSocket(e){this.emit("send-message-to-socket",e)}sendMessageToClient(e){this.emit("send-message-to-client",e)}async save(e){return this._debouncedSaveOperations(0,e)}async saveAs(e,t){return this._debouncedSaveOperations(1,t,e)}write(e,t){return this.webSocketUrl?(ie(t,this,"a custom websocket connection cannot be written to web scenes and web maps"),null):this.source?(ie(t,this,"a custom source cannot be written to web scenes and web maps"),null):this.parsedUrl?super.write(e,t):(ie(t,this,"a client-side only connection without a url cannot be written to web scenes and web maps"),null)}async _fetchService(e){if(this.source){const e=await K(this.source.workspace,this.source.database,this.source.table,{fields:this.fields,source:this.source,database:this.database});if(this.database=e.database,!e.fields)throw new o("stream-layer:missing-metadata","The stream layer fields must be specified.");if(this.fields=e.fields,!e.source)throw new o("stream-layer:missing-metadata","Unable to infer Kusto source.",{layerInfo:e});if(!e.source.geometryEncoding)throw new o("stream-layer:missing-metadata","Unable to infer Kusto geometry encoding.",{layerInfo:e});this.source=e.source}if(this.parsedUrl){if(!this.sourceJSON){const{data:t}=await r(this.parsedUrl.path,{query:{f:"json",...this.customParameters,...this.parsedUrl.query},responseType:"json",signal:e});this.sourceJSON=t}}else{if(!this.timeInfo?.trackIdField)throw new o("stream-layer:missing-metadata","The stream layer trackIdField must be specified.");if(!this.fields)throw new o("stream-layer:missing-metadata","The stream layer fields must be specified.");if(!this.objectIdField){const e=this.fields.find(e=>"oid"===e.type)?.name;e&&(this.objectIdField=e)}if(this.fields.some(e=>e.name===this.objectIdField)||this.fields.push(new M({name:this.objectIdField,alias:this.objectIdField,type:"oid"})),!this.geometryType)throw new o("stream-layer:missing-metadata","The stream layer geometryType must be specified.")}return this.read(this.sourceJSON,{origin:"service",portalItem:this.portalItem,portal:this.portalItem?.portal,url:this.parsedUrl}),q(this.renderer,this.fieldsIndex),z(this.timeInfo,this.fieldsIndex),this.objectIdField||(this.objectIdField=H),Y(this,{origin:"service"})}};e([c({type:String})],ne.prototype,"copyright",void 0),e([c()],ne.prototype,"database",void 0),e([c({readOnly:!0})],ne.prototype,"defaultPopupTemplate",null),e([c({type:String,json:{name:"layerDefinition.definitionExpression",write:{enabled:!0,allowNull:!0}}})],ne.prototype,"definitionExpression",void 0),e([c({type:String})],ne.prototype,"displayField",void 0),e([c({type:re})],ne.prototype,"elevationInfo",void 0),e([c({json:{origins:{"web-map":{read:!1,write:!1},"portal-item":{read:!1,write:!1},"web-scene":{read:!1,write:!1}}}})],ne.prototype,"featureReduction",null),e([c(se.fields)],ne.prototype,"fields",void 0),e([c(se.fieldsIndex)],ne.prototype,"fieldsIndex",void 0),e([c({type:y,json:{name:"layerDefinition.definitionGeometry",write:!0}})],ne.prototype,"geometryDefinition",void 0),e([c({type:g.apiValues,json:{read:{reader:g.read}}})],ne.prototype,"geometryType",void 0),e([c({readOnly:!0,clonable:!1})],ne.prototype,"graphicOrigin",void 0),e([c(k)],ne.prototype,"labelsVisible",void 0),e([c({type:[W],json:{name:"layerDefinition.drawingInfo.labelingInfo",read:{reader:Q},write:!0}})],ne.prototype,"labelingInfo",void 0),e([c(E)],ne.prototype,"legendEnabled",void 0),e([c({type:["show","hide"],json:{origins:{"portal-item":{read:!1,write:!1}}}})],ne.prototype,"listMode",void 0),e([c({type:f})],ne.prototype,"maxReconnectionAttempts",void 0),e([c({type:f})],ne.prototype,"maxReconnectionInterval",void 0),e([c(D)],ne.prototype,"maxScale",void 0),e([c(A)],ne.prototype,"minScale",void 0),e([c({type:String})],ne.prototype,"objectIdField",void 0),e([c({value:"ArcGISStreamLayer",type:["ArcGISStreamLayer"]})],ne.prototype,"operationalLayerType",void 0),e([c({readOnly:!0})],ne.prototype,"outFields",void 0),e([c(C)],ne.prototype,"popupEnabled",void 0),e([c({type:t,json:{name:"popupInfo",write:!0}})],ne.prototype,"popupTemplate",void 0),e([c({type:B})],ne.prototype,"purgeOptions",void 0),e([c({json:{read:!1,write:!1}})],ne.prototype,"refreshInterval",void 0),e([c({types:$,json:{origins:{service:{write:{target:"drawingInfo.renderer",enabled:!1}},"web-scene":{name:"layerDefinition.drawingInfo.renderer",types:Z,write:!0}},write:{target:"layerDefinition.drawingInfo.renderer"}}})],ne.prototype,"renderer",null),e([oe("service","renderer",["drawingInfo.renderer","defaultSymbol"]),oe("renderer",["layerDefinition.drawingInfo.renderer","layerDefinition.defaultSymbol"])],ne.prototype,"readRenderer",null),e([c((()=>{const e=n(N);return e.json.origins["portal-item"]={read:!1,write:!1},e})())],ne.prototype,"screenSizePerspectiveEnabled",void 0),e([c({type:G,json:{write:!1}})],ne.prototype,"source",void 0),e([c()],ne.prototype,"sourceJSON",void 0),e([c({type:h,json:{origins:{service:{read:{source:"spatialReference"}}}}})],ne.prototype,"spatialReference",void 0),e([c({json:{read:!1}})],ne.prototype,"type",void 0),e([c(J)],ne.prototype,"url",void 0),e([c({type:Number})],ne.prototype,"updateInterval",void 0),e([c({json:{read:!1,write:!1}})],ne.prototype,"useViewTime",void 0),e([c({type:String})],ne.prototype,"webSocketUrl",void 0),ne=e([u("esri.layers.StreamLayer")],ne);const ae=ne;export{ae as default};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import t from"../request.js";import has from"../core/has.js";import s from"../core/Logger.js";import{isAbortError as r}from"../core/promiseUtils.js";import{watch as i,initial as a}from"../core/reactiveUtils.js";import{convertTime as n}from"../core/timeUtils.js";import{property as o,subclass as l}from"../core/accessorSupport/decorators.js";import{distance as h}from"../core/libs/gl-matrix-2/math/vec3.js";import{create as d}from"../core/libs/gl-matrix-2/factories/vec3f64.js";import{renderSRFromViewSR as u}from"../geometry/support/coordinateSystem.js";import{loadVoxelWASM as _}from"../libs/vxl/VxlModule.js";import{InternalRenderCategory as c}from"../views/3d/webgl.js";import{VoxelGraphic as m}from"../views/3d/layers/VoxelGraphic.js";import{VoxelTarget as f}from"../views/3d/layers/i3s/Intersector.js";import{Frustum as p}from"../views/3d/state/Frustum.js";import{RenderCoordsHelper as g}from"../views/3d/support/RenderCoordsHelper.js";import y from"../views/3d/webgl/RenderNode.js";import{IntersectorResultRay as x}from"../views/3d/webgl-engine/lib/IntersectorResult.js";let v=class extends y{constructor(e){super(e),this._havePreparedWithAllLayers=!1,this.consumes={required:[c.VOXEL]},this.produces="disabled",this._vxlPromise=null,this._moreToLoad=!1,this._viewportWidth=-1,this._viewportHeight=-1,this._newLayers=[],this._layers=new Map,this._renderTargetToRestore=null,this._lastFrameWasStationary=!1,this._wasmMemBlockSizes=[512,1024,2048,4096,8192,16384,32768,65536],this._wasmMemBlocks=new Map,this._dbgFlags=new Set,this._captureFrustum=!1,this._frustum=null,this._frustumRenderableId=-1,this._renderCoordsHelper=null,this.type=9,this.slicePlaneEnabled=!0,this.isGround=!1,this.layerViewUid=[]}_dbg(e,t){this._dbgFlags.has(e)&&(4===e?s.getLogger(this).error(t):s.getLogger(this).warn(t))}initialize(){this._dbg(1,"--initialize--");for(const e of this._wasmMemBlockSizes)this._wasmMemBlocks.set(e,0);this.addHandles([i(()=>"local"===this.view.viewingMode,e=>{e?(this._dbg(1,"view switched to local view, enabling rendering"),this.produces=c.VOXEL,this.view.sceneIntersectionHelper.addIntersectionHandler(this)):(this._dbg(1,"view switched to global view, disabling rendering"),this.view.sceneIntersectionHelper.removeIntersectionHandler(this),this.produces="disabled")},a),i(()=>this.view?.qualityProfile,e=>{this._dbg(3,"qualityProfile changed to "+e),this._vxl?.set_quality(this._toWasmQuality(e))},a),i(()=>this.view?.timeExtent,()=>{if(this._vxl){const e=this._getTimeArgs(this.view?.timeExtent);this._dbg(3,"sceneView timeExtent changed to useTime="+e.hasTime+" st="+e.startTime+" et="+e.endTime),this._vxl.set_scene_time_extent(e.startTime,e.endTime,e.hasTime),this.requestRender(1)}},a),i(()=>this.view?.stationary,e=>{this._vxl&&e&&!this._lastFrameWasStationary&&this.requestRender(1)})])}get _rctx(){return this.renderContext?.rctx}get _halfIntTexturesAvailable(){return!!this._rctx?.capabilities.textureNorm16}get _textureFloatLinearAvailable(){return!!this._rctx?.capabilities.textureFloatLinear}_restoreFramebuffer(){if(!this._renderTargetToRestore||!this._rctx)return;const e=this._renderTargetToRestore.fbo;if(!!!this._rctx)return void this._dbg(4,"no context in restoreFramebuffer!");this._rctx.bindFramebuffer(e,!0);const t=this._renderTargetToRestore.viewport;this._rctx.setViewport(t.x,t.y,t.width,t.height)}_bindPreviousDepthToSlot(e,t){if(!this._rctx||!this._renderTargetToRestore)return 0;const s=this._renderTargetToRestore.fbo?.depthStencilTexture;return s?(0===t?this._rctx.bindTexture(null,e,!0):this._rctx.bindTexture(s,e,!0),1):(this._dbg(4,"no depth/stencil texture exists!"),0)}_modifyResourceCount(e,t,s){if(!this._rctx)return void this._dbg(4,"modifyAllocation callback has no rendering context!");const r=e;1===s?this._rctx.instanceCounter.increment(r,t):this._rctx.instanceCounter.decrement(r,t)}_setBlendState(e,t,s,r){this._rctx?(this._rctx.setBlendingEnabled(1===e),this._rctx.setBlendFunction(t,s),this._rctx.setBlendEquation(r)):this._dbg(4,"setBlendState callback has no rendering context!")}_setFrontFace(e){this._rctx?this._rctx.setFrontFace(e):this._dbg(4,"setFrontFace callback has no rendering context!")}_setDepthStencilStateFunction(e,t,s){this._rctx?(this._rctx.setDepthFunction(s),this._rctx.setDepthTestEnabled(1===e),this._rctx.setDepthWriteEnabled(1===t),this._rctx.setStencilTestEnabled(!1),this._rctx.setStencilFunction(519,0,255),this._rctx.setStencilOpSeparate(1028,7680,7682,7680),this._rctx.setStencilOpSeparate(1029,7680,7683,7680)):this._dbg(4,"setDepthStencilStateFunction callback has no rendering context!")}_setRasterizerState(e){if(this._rctx)switch(e){case 1:this._rctx.setFaceCullingEnabled(!1);break;case 3:this._rctx.setCullFace(1029),this._rctx.setFaceCullingEnabled(!0);break;case 2:this._rctx.setCullFace(1028),this._rctx.setFaceCullingEnabled(!0)}else this._dbg(4,"setRasterizerState callback has no rendering context!")}_setViewport(e,t,s,r){this._rctx?this._rctx.setViewport(e,t,s,r):this._dbg(4,"setViewport callback has no rendering context!")}_updateMemoryUsage(){this._layers.forEach((e,t)=>{if(e.needMemoryUsageUpdate){const s=this._vxl?.estimate_memory_usage(t)??0;s>=0&&(e.needMemoryUsageUpdate=!1,e.layerView.setUsedMemory(s))}})}_syncRequestsResponses(){this._vxl&&this._layers.forEach((e,s)=>{const i=[];e.responses.forEach((t,r)=>{i.push(r),this._dbg(2,"responding for requestID:"+r+" size:"+t.size),this._vxl?.respond(s,r,t),0!==t.requestType&&4!==t.requestType||(e.needMemoryUsageUpdate=!0)});const a=e.responses;for(const t of i)a.delete(t);const n=this._vxl.get_new_requests(s),o=e.abortController.signal;for(const l in n){e.outstandingRequestCount+=1,1===e.outstandingRequestCount&&e.layerView.updatingFlagChanged();const s=n[l],i={responseType:"array-buffer",signal:o,query:{...e.layerView.layer.customParameters,token:e.layerView.layer.apiKey}};this._dbg(2,"making requestID:"+l+" url:"+s.url),t(s.url,i).then(t=>{e.outstandingRequestCount-=1,0===e.outstandingRequestCount&&e.layerView.updatingFlagChanged(),this._dbg(2,"have response for requestID:"+l);let r=0;if(t.data.byteLength>0&&this._vxl){r=this._vxl._malloc(t.data.byteLength);const e=new Uint8Array(this._vxl.HEAPU8.buffer,r,t.data.byteLength),s=new Uint8Array(t.data);for(let r=0;r<t.data.byteLength;++r)e[r]=s[r]}a.set(+l,{responseType:s.responseType,ptr:r,size:t.data.byteLength,success:!0,requestType:s.requestType})}).catch(t=>{e.outstandingRequestCount-=1,0===e.outstandingRequestCount&&e.layerView.updatingFlagChanged(),r(t)||(this._dbg(4,`requestID:${l} failed, error=${t.toString()}`),a.set(+l,{responseType:s.responseType,ptr:0,size:0,success:!1,requestType:s.requestType}))})}})}updateWasmCamera(e){this._vxl?.set_projection_matrix.apply(this._vxl,e.projectionMatrix),this._vxl?.set_view_matrix.apply(this._vxl,e.viewMatrix),this._vxl?.set_near_far(e.near,e.far)}isUpdating(e){if(!this._vxl&&this._vxlPromise)return!0;const t=this._layers.get(e);return!!t&&t.outstandingRequestCount>0}getLayerTimes(e){const t=[];return this._vxl?(this._layers.forEach((s,r)=>{if(s.layerView.wasmLayerId===e.wasmLayerId){const s=this._vxl.get_layer_epoch_times(r,e.layer.currentVariableId);for(let e=0;e<s.length;++e)t.push(s[e])}}),t):t}getCurrentLayerTimeIndex(e){let t=0;return this._layers.forEach((s,r)=>{s.layerView.wasmLayerId===e.wasmLayerId&&(t=this._vxl?.get_layer_current_time_id(r)??0)}),t}setEnabled(e,t){this._layers.forEach((s,r)=>{s.layerView.wasmLayerId===e.wasmLayerId&&(this._vxl?.set_enabled(r,t),s.needMemoryUsageUpdate=!0,this.requestRender(1))})}setIsInScaleRange(e,t){const s=this._layers.get(e.wasmLayerId);s&&t!==s.isInScaleRange&&(s.isInScaleRange=t,this._vxl?.set_is_in_scale_range(e.wasmLayerId,t),s.needMemoryUsageUpdate=!t,this.requestRender(1))}setStaticSections(e,t){const s={mask:1,staticSections:t};return this._doMaskedUIUpdate(e,s,!0)}setCurrentVariable(e,t){const s={mask:1024,currentVariable:t};return this._doMaskedUIUpdate(e,s,!0)}setRenderMode(e,t){const s={mask:8192,renderMode:t};return this._doMaskedUIUpdate(e,s,!0)}setVerticalExaggerationAndOffset(e,t,s,r){const i={mask:256,volStyleDesc:{volumeId:t,verticalExaggeration:s,verticalOffset:r}};return this._doMaskedUIUpdate(e,i,!0)}setVariableStyles(e,t){const s={mask:32768,variableStyles:t};return this._doMaskedUIUpdate(e,s,!0)}setVolumeStyles(e,t){const s={mask:65536,volumeStyles:t};return this._doMaskedUIUpdate(e,s,!0)}setEnableDynamicSections(e,t){const s={mask:4096,containerIsVisible:t,container:1};return this._doMaskedUIUpdate(e,s,!0)}setEnableIsosurfaces(e,t){const s={mask:4096,containerIsVisible:t,container:0};return this._doMaskedUIUpdate(e,s,!0)}setEnableSections(e,t){const s={mask:4096,containerIsVisible:t,container:2};return this._doMaskedUIUpdate(e,s,!0)}setAnalysisSlice(e,t,s,r){const i={mask:131072,analysisSlice:{point:s,normal:r,enabled:t}};return this._doMaskedUIUpdate(e,i,!0)}updateLayerTimeProperties(e){if(!this._vxl)return;const t=this._layers.get(e.wasmLayerId);if(t){const s=t.layerView.layer;let r=0;s.timeOffset&&(r=n(s.timeOffset.value,s.timeOffset.unit,"seconds"));const i=this._getTimeArgs(s.timeExtent);this._vxl?.set_layer_time_properties(e.wasmLayerId,i.startTime,i.endTime,i.hasTime,s.useViewTime,r),this.requestRender(1)}}_doMaskedUIUpdate(e,t,s){if(!this._vxl)return!1;let r=!1;return this._layers.forEach((s,i)=>{if(s.layerView.wasmLayerId===e.wasmLayerId){const e={str:JSON.stringify(t),byteCount:0,ptr:0,isReusable:!1};this._allocateBlock(e)&&(r=1===this._vxl?.handle_masked_ui_update(i,e.ptr,e.byteCount),e.isReusable||this._vxl?._free(e.ptr))}}),r&&s&&this.requestRender(1),r}_addTriangleToWasmBuffer(e,t,s,r,i){return e[3*t]=s[0],e[3*t+1]=s[1],e[3*t+2]=s[2],e[3*(t+=1)]=r[0],e[3*t+1]=r[1],e[3*t+2]=r[2],e[3*(t+=1)]=i[0],e[3*t+1]=i[1],e[3*t+2]=i[2],t+=1}_addNormalToWasmBuffer(e,t,s){return e[3*t]=s[0],e[3*t+1]=s[1],e[3*t+2]=s[2],t+=1}_doCaptureFrustum(){if(!this._vxl)return;const e=36,t=e/3,s=this._vxl._malloc(3*e*Float32Array.BYTES_PER_ELEMENT),r=new Float32Array(this._vxl.HEAPF32.buffer,s,3*e),i=this._vxl._malloc(3*t*Float32Array.BYTES_PER_ELEMENT),a=new Float32Array(this._vxl.HEAPF32.buffer,i,e),n=this._frustum.points[0],o=this._frustum.points[1],l=this._frustum.points[2],h=this._frustum.points[3],d=this._frustum.points[4],u=this._frustum.points[5],_=this._frustum.points[6],c=this._frustum.points[7];let m=0,f=0;const p=this._frustum.planes[4];m=this._addTriangleToWasmBuffer(r,m,l,o,n),f=this._addNormalToWasmBuffer(a,f,p),m=this._addTriangleToWasmBuffer(r,m,n,h,l),f=this._addNormalToWasmBuffer(a,f,p);const g=this._frustum.planes[5];m=this._addTriangleToWasmBuffer(r,m,d,u,_),f=this._addNormalToWasmBuffer(a,f,g),m=this._addTriangleToWasmBuffer(r,m,_,c,d),f=this._addNormalToWasmBuffer(a,f,g);const y=this._frustum.planes[3];m=this._addTriangleToWasmBuffer(r,m,_,l,h),f=this._addNormalToWasmBuffer(a,f,y),m=this._addTriangleToWasmBuffer(r,m,h,c,_),f=this._addNormalToWasmBuffer(a,f,y);const x=this._frustum.planes[2];m=this._addTriangleToWasmBuffer(r,m,n,o,u),f=this._addNormalToWasmBuffer(a,f,x),m=this._addTriangleToWasmBuffer(r,m,u,d,n),f=this._addNormalToWasmBuffer(a,f,x);const v=this._frustum.planes[0];m=this._addTriangleToWasmBuffer(r,m,h,n,d),f=this._addNormalToWasmBuffer(a,f,v),m=this._addTriangleToWasmBuffer(r,m,d,c,h),f=this._addNormalToWasmBuffer(a,f,v);const b=this._frustum.planes[1];m=this._addTriangleToWasmBuffer(r,m,l,_,u),f=this._addNormalToWasmBuffer(a,f,b),this._addTriangleToWasmBuffer(r,m,u,o,l),this._addNormalToWasmBuffer(a,f,b),-1!==this._frustumRenderableId&&this._vxl.remove_generic_mesh(this._frustumRenderableId),this._frustumRenderableId=this._vxl.add_generic_mesh(s,3*e,i,e,255,0,0,64),this._vxl._free(s),this._vxl._free(i),this._captureFrustum=!1,this.requestRender(1)}captureFrustum(){null===this._renderCoordsHelper&&(this._renderCoordsHelper=g.create(2,u(!1,this.view.spatialReference))),null===this._frustum&&(this._frustum=new p(this._renderCoordsHelper)),this._captureFrustum=!0,this.requestRender(1)}toggleFullVolumeExtentDraw(e){this._vxl&&this._layers.forEach((t,s)=>{t.layerView.wasmLayerId===e.wasmLayerId&&(this._vxl?.toggle_full_volume_extent_draw(s),this.requestRender(1))})}dropQueryRenderTarget(){this._vxl?.drop_query_rt()}addVoxelLayer(e){if(!this._vxl){const t={layerView:e,resolveCallback:null,rejectCallback:null},s=new Promise((e,s)=>{t.resolveCallback=e,t.rejectCallback=s});return this._newLayers.push(t),s}const t=this._addVoxelLayer(e,this._vxl);return t<0?Promise.reject(-1):Promise.resolve(t)}removeVoxelLayer(e){if(!this._vxl){const t=this._newLayers.findIndex(t=>e.uid===t.layerView.uid);t>=0&&(this._newLayers[t].resolveCallback(-1),this._newLayers.splice(t,1));const s=this._newLayers.length;return 0===s&&(this._dbg(1,"No voxel layers left after removing a layer, destroying render node"),this.destroy()),s}let t=-1;this._layers.forEach((s,r)=>{if(s.layerView.wasmLayerId===e.wasmLayerId){t=r,s.abortController.abort(),this._vxl?.remove_layer(t);const i=this.layerViewUid.indexOf(e.uid);-1!==i&&this.layerViewUid.splice(i,1)}}),t>=0&&this._layers.delete(t);const s=this._layers.size;return 0===s&&(this._dbg(1,"No voxel layers left after removing a layer, destroying render node"),this.destroy()),s}_getBlockSize(e){for(const t of this._wasmMemBlockSizes)if(e<t)return t;return-1}_allocateBlock(e){if(!this._vxl)return!1;e.byteCount=this._vxl.lengthBytesUTF8(e.str)+1;const t=this._getBlockSize(e.byteCount);return t<0?(e.isReusable=!1,e.ptr=this._vxl._malloc(e.byteCount)):(e.isReusable=!0,e.ptr=this._wasmMemBlocks.get(t),0===e.ptr&&(e.ptr=this._vxl._malloc(t),this._wasmMemBlocks.set(t,e.ptr))),0!==e.ptr&&(this._vxl.stringToUTF8(e.str,e.ptr,e.byteCount),!0)}_getTimeArgs(e){let t=-Number.MAX_VALUE,s=Number.MAX_VALUE,r=!1;return null!=e&&(e.isAllTime?r=!0:(null!=e.start&&(r=!0,t=e.start.getTime()/1e3),null!=e.end&&(r=!0,s=e.end.getTime()/1e3))),{startTime:t,endTime:s,hasTime:r}}_addVoxelLayer(e,t){const r=e.layer;let i=-1;const a=r.getConfiguration();if(a.length<1)return-1;const o={str:a,byteCount:0,ptr:0,isReusable:!1};if(!this._allocateBlock(o))return-1;const l=this._getTimeArgs(r.timeExtent),h=this.view.spatialReference.isWGS84&&r.spatialReference.isWGS84?111319.49079327357:1;let d=0;if(r.timeOffset&&(d=n(r.timeOffset.value,r.timeOffset.unit,"seconds")),i=t.add_layer(r.serviceRoot,o.ptr,o.byteCount,h,h,l.startTime,l.endTime,l.hasTime,r.useViewTime,d,this._toWasmQuality(this.view.qualityProfile)),o.isReusable||t._free(o.ptr),i>=0){r.test?.constantUpscaling&&(this._setUpscalingLimits(0,.25,.25),this._setUpscalingLimits(1,.5,.5),this._setUpscalingLimits(2,.75,.75));const t=new AbortController;if(this._layers.set(i,{layerView:e,responses:new Map,outstandingRequestCount:0,abortController:t,needMemoryUsageUpdate:!1,isInScaleRange:!0}),this.layerViewUid.push(e.uid),!this._halfIntTexturesAvailable||has("mac")){const t=[];let r="";for(const s of e.layer.variables)"Int16"!==s.renderingFormat.type&&"UInt16"!==s.renderingFormat.type||(t.push(s.name),s.id===e.layer.currentVariableId&&(r=s.name));""!==r&&s.getLogger(this).error("#addVoxelLayer_error()",e.layer,`The voxel layer '${e.layer.title}' cannot render the current variable '${r}' in this browser`),t.length>0&&s.getLogger(this).warn("#addVoxelLayer_warning()",e.layer,`The voxel layer '${e.layer.title}' cannot render the variables '${t.toString()}' in this browser`)}if(!this._textureFloatLinearAvailable){const t=[];let r="";for(const s of e.layer.variables)"Float32"===s.renderingFormat.type&&(t.push(s.name),s.id===e.layer.currentVariableId&&(r=s.name));""!==r&&s.getLogger(this).error("#addVoxelLayer_error()",e.layer,`The voxel layer '${e.layer.title}' cannot render the current variable '${r}' in this browser`),t.length>0&&s.getLogger(this).warn("#addVoxelLayer_warning()",e.layer,`The voxel layer '${e.layer.title}' cannot render the variables '${t.toString()}' in this browser`)}return has("esri-mobile")&&s.getLogger(this).warnOnce("Mobile support differs across devices. Voxel layer might not display as expected."),i}return-1}_prepareRender(){if(!this._vxl)return void this._initializeWasm();const e=this.bindParameters.camera.viewForward,t=this.bindParameters.camera.eye;this._vxl.update_camera_pos_and_direction(t[0],t[1],t[2],e[0],e[1],e[2]);const s=this._vxl.cull();this._dbg(2,"missingResourceCount="+s),this._moreToLoad=s>0,this._havePreparedWithAllLayers=0===this._newLayers.length,this._updateMemoryUsage()}render(){this._prepareRender();const e=this.bindRenderTarget();if(!this._vxl||!this._rctx)return this.requestRender(1),e;for(const s of this._newLayers){const e=this._addVoxelLayer(s.layerView,this._vxl);-1===e?s.rejectCallback(-1):s.resolveCallback(e)}if(this._newLayers=[],0===this._layers.size)return this._dbg(4,"No voxel layers but RenderNode is being asked to render!"),e;this._lastFrameWasStationary=this.view.stationary,this._syncRequestsResponses(),this._beforeDraw(this._rctx),this._vxl.begin_color_frame(!this.view.stage.renderer.isFeatureEnabled(1),this.bindParameters.lighting.mainLight.direction[0],this.bindParameters.lighting.mainLight.direction[1],this.bindParameters.lighting.mainLight.direction[2]);const t=this._renderTargetToRestore.viewport;return t.width===this._viewportWidth&&t.height===this._viewportHeight||(this._viewportWidth=t.width,this._viewportHeight=t.height,this._vxl.set_viewport(t.width,t.height),this._layers.forEach(e=>e.needMemoryUsageUpdate=!0)),0===t.x&&0===t.y||this._dbg(4,"Unsupported viewport parameters detected!"),this.updateWasmCamera(this.bindParameters.camera),this._captureFrustum&&(this._frustum.update(this.bindParameters.camera),this._doCaptureFrustum()),this._vxl.draw(),this._afterDraw(this._rctx,this._vxl),(this._moreToLoad||!this._havePreparedWithAllLayers&&this._layers.size>0)&&this.requestRender(1),e}destroy(){this._dbg(1,"--destroy--"),this._vxl&&(this._layers.forEach(e=>{e.abortController.abort()}),this._wasmMemBlocks.forEach(e=>{0!==e&&this._vxl?._free(e)}),this._vxl.uninitialize_voxel_wasm(),this._vxl=null)}_initializeWasm(){if(this._vxl||this._vxlPromise||!this._rctx?.gl)return;const e=this._rctx.gl;this._vxlPromise=_(e).then(t=>{if(t.specialHTMLTargets.jsAPI3DRenderingContext=e,this._vxl=t,this._vxlPromise=null,this._newLayers.length<=0)return this._dbg(1," no voxel layers left after WASM downloaded, removing RenderNode and destroying"),void this.destroy();const s=this._getTimeArgs(this.view?.timeExtent),r=this._vxl.addFunction(this._restoreFramebuffer.bind(this),"v"),i=this._vxl.addFunction(this._setBlendState.bind(this),"viiii"),a=this._vxl.addFunction(this._setFrontFace.bind(this),"vi"),n=this._vxl.addFunction(this._setRasterizerState.bind(this),"vi"),o=this._vxl.addFunction(this._setDepthStencilStateFunction.bind(this),"viii"),l=this._vxl.addFunction(this._setViewport.bind(this),"viiii"),h=this._vxl.addFunction(this._bindPreviousDepthToSlot.bind(this),"iii"),d=this._vxl.addFunction(this._modifyResourceCount.bind(this),"viii"),u=this._halfIntTexturesAvailable&&!has("mac"),_=this._textureFloatLinearAvailable;this._vxl.initialize_voxel_wasm(r,i,a,n,o,l,h,d,s.startTime,s.endTime,s.hasTime,u,_),this.requestRender(1)}).catch(()=>{for(const e of this._newLayers)e.rejectCallback(-2);this._dbg(4," WASM failed to download, destroying render node"),this.destroy()})}pickDepth(e,t,s){if(!this._vxl||!this._rctx||0===this._layers.size)return null;const r=s.viewport[3]-t;if(e<0||e>s.viewport[2]||t<0||t>s.viewport[3])return this._dbg(4,`[js] pickDepth: outOfRange, screenXY=[${e.toFixed(0)}, ${r.toFixed(0)}]]`),null;this._beforeDraw(this._rctx);const i=s.viewForward,a=s.eye;this._vxl.update_camera_pos_and_direction(a[0],a[1],a[2],i[0],i[1],i[2]),this.updateWasmCamera(s),this._vxl.begin_frame();const n=this._vxl.pick_depth(e,r);if(this._afterDraw(this._rctx,this._vxl),n.success){return n.distanceToCamera}return null}pickObject(e,t,s,r){if(!this._vxl||!this._rctx||0===this._layers.size)return null;const i=Math.round(e),a=Math.round(t);if(i<0||i>s.viewport[2]||a<0||a>s.viewport[3])return this._dbg(4,`[js] pickObject: outOfRange, screenXY=[${i}, ${a}], vp=[${s.viewport.toString()}]`),null;this._beforeDraw(this._rctx);const n=s.viewForward,o=s.eye;this._vxl.update_camera_pos_and_direction(o[0],o[1],o[2],n[0],n[1],n[2]),this.updateWasmCamera(s),this._vxl.begin_frame();let l=null;if(0===r.length)l=this._vxl.pick_object(i,a,0,0);else{const e={str:JSON.stringify({layerIds:r}),byteCount:0,ptr:0,isReusable:!1};this._allocateBlock(e)&&(l=this._vxl.pick_object(i,a,e.ptr,e.byteCount),e.isReusable||this._vxl._free(e.ptr))}return this._afterDraw(this._rctx,this._vxl),l}async getOtherFieldPopupValues(e,s){if(!this._vxl)return[];for(const r of e){const e=r.gpuResult;if(!e)continue;const i=this._layers.get(e.layerId);if(!i||!i.layerView.layer.url)continue;const a=i.layerView.layer,n={responseType:"array-buffer",signal:i.abortController.signal,query:{...i.layerView.layer.customParameters,token:i.layerView.layer.apiKey}},o=e.voxelSpacePosition,l=[Math.floor(o[0]/32),Math.floor(o[1]/32),Math.floor(o[2]/32)],h=[-4&l[0],-4&l[1],-4&l[2]];let d=0;if(e.epochTime){const t=this._vxl.get_layer_epoch_times(i.layerView.wasmLayerId,a.currentVariableId);for(let s=0;s<t.length;++s)if(t[s]===e.epochTime/1e3){d=s;break}}const u=[],_={varIds:[],ptrs:[],sizes:[]};for(const r of s){const e=a.variables.findIndex(e=>e.name===r);if(-1===e)continue;const s=a.variables.getItemAt(e)?.id;if(null==s)continue;const i=`${a.url}/variables/${s}/${d}/bundles/0/${h[0]}-${h[1]}-${h[2]}`;u.push(t(i,n).then(e=>e.data)),_.varIds.push(s)}const c=await Promise.allSettled(u),m=c.length;for(let t=0;t<m;++t){const e=c[t];if("fulfilled"===e.status){const t=e.value,s=this._vxl._malloc(t.byteLength);new Uint8Array(this._vxl.HEAPU8.buffer,s,t.byteLength).set(new Uint8Array(t)),_.ptrs.push(s),_.sizes.push(t.byteLength)}else _.varIds.splice(t,1)}const f=this._vxl.get_other_field_popup_values(e,_);for(let t=0;t<_.ptrs.length;++t)this._vxl._free(_.ptrs[t]);if(f.continuousValues)for(const t in f.continuousValues)r.attributes[t]=f.continuousValues[t];if(f.uniqueValues)for(const t in f.uniqueValues)r.attributes[t]=f.uniqueValues[t]}return e}_beforeDraw(e){this._renderTargetToRestore={fbo:e.boundFramebuffer,viewport:e.getViewport()},e.setPolygonOffsetFillEnabled(!1),e.setScissorTestEnabled(!1),e.setColorMask(!0,!0,!0,!0)}_afterDraw(e,t){this._renderTargetToRestore.fbo=null,e.externalTextureUnitUpdate(t.get_texture_units_bound_in_frame(),t.get_active_texture_unit()),e.externalVertexArrayObjectUpdate(),e.externalVertexBufferUpdate(),e.externalProgramUpdate()}intersectRay(e,t,s,r,i){if(!this._vxl||!this._rctx||0===this._layers.size||!e.options.selectionMode||e.options.isFiltered||!e.camera)return;if(null==i||i[0]<0||i[0]>e.camera.viewport[2]||i[1]<0||i[1]>e.camera.viewport[3])return this._dbg(4,i?`[js] VoxelWasmPerScene.intersect: outOfRange, screenXY=[${i[0].toFixed(0)}, ${i[1].toFixed(0)}]`:"[js] VoxelWasmPerScene.intersect: outOfRange, screenXY=null"),null;const a=[];this._layers.forEach(t=>{e.options.filteredLayerViewUids.includes(t.layerView.uid)&&a.push(t.layerView.wasmLayerId)});const n=this.pickObject(i[0],i[1],e.camera,a);if(null==n||-1===n.layerId)return;const o=this._layers.get(n.layerId);if(o){const t=o.layerView.layer.uid,i=n.distanceToCamera/h(s,r),a=d();a[0]=n.worldX,a[1]=n.worldY,a[2]=n.worldZ;const l={},u=o.layerView.layer,_=u.variables.findIndex(e=>e.id===u.currentVariableId);if(_>=0){const e=u.variables.getItemAt(_);null!=e&&(null!=n.continuousValue?l[e.name]=n.continuousValue:null!=n.uniqueValueLabel&&null!=n.uniqueValue?l[e.name]=`${n.uniqueValueLabel} (${n.uniqueValue})`:null!=n.uniqueValue&&(l[e.name]=`${n.uniqueValue}`),e.description.length>0?l["Voxel.CurrentVariable"]=e.description:e.name?.length>0&&(l["Voxel.CurrentVariable"]=e.name))}if(l["Voxel.Position"]=`[${n.voxelSpacePosition.toString()}]`,null!=n.epochTime&&null!=n.nativeTime&&null!=n.nativeTimeUnits){const e=new Date(n.epochTime);l["Voxel.LocalTime"]=e,l["Voxel.SourceTime"]=`${n.nativeTime.toLocaleString()} ${n.nativeTimeUnits}`}null!=n.depth&&(l["Voxel.Depth"]=n.depth);const c=n.faceNormal;l["Voxel.WorldPosition"]=`[${a[0]}, ${a[1]}, ${a[2]}]`;const m=e=>{const s=new f(a,t,()=>this._createVoxelGraphic(o.layerView.layer,l,n));e.set(this.type,s,i,c)},p=e.results,g=2===e.options.store;if((null==p.min.distance||i<p.min.distance)&&m(p.min),(null==p.max.distance||i>p.max.distance)&&m(p.max),g){const t=new x(e.ray);m(t),e.results.all.push(t)}}}_createVoxelGraphic(e,t,s){return new m({layer:e,sourceLayer:e,origin:e.graphicOrigin,attributes:t,gpuResult:s})}_toWasmQuality(e){switch(e){case"low":return 0;case"medium":return 1;case"high":return 2}}_setUpscalingLimits(e,t,s){this._vxl&&this._vxl.set_upscaling_limits(e,t,s)}};e([o()],v.prototype,"consumes",void 0),e([o()],v.prototype,"produces",void 0),v=e([l("esri.layers.VoxelWasmPerSceneView")],v);const b=v;export{b as default};
2
+ import{__decorate as e}from"tslib";import t from"../request.js";import has from"../core/has.js";import s from"../core/Logger.js";import{isAbortError as r}from"../core/promiseUtils.js";import{watch as i,initial as a}from"../core/reactiveUtils.js";import{convertTime as n}from"../core/timeUtils.js";import{property as o,subclass as l}from"../core/accessorSupport/decorators.js";import{distance as h}from"../core/libs/gl-matrix-2/math/vec3.js";import{create as d}from"../core/libs/gl-matrix-2/factories/vec3f64.js";import{renderSRFromViewSR as u}from"../geometry/support/coordinateSystem.js";import{loadVoxelWASM as _}from"../libs/vxl/VxlModule.js";import{InternalRenderCategory as c}from"../views/3d/webgl.js";import{VoxelGraphic as m}from"../views/3d/layers/VoxelGraphic.js";import{VoxelTarget as f}from"../views/3d/layers/i3s/Intersector.js";import{Frustum as p}from"../views/3d/state/Frustum.js";import{RenderCoordsHelper as g}from"../views/3d/support/RenderCoordsHelper.js";import y from"../views/3d/webgl/RenderNode.js";import{IntersectorResultRay as x}from"../views/3d/webgl-engine/lib/IntersectorResult.js";let v=class extends y{constructor(e){super(e),this._havePreparedWithAllLayers=!1,this.consumes={required:[c.VOXEL]},this.produces="disabled",this._vxlPromise=null,this._moreToLoad=!1,this._viewportWidth=-1,this._viewportHeight=-1,this._newLayers=[],this._layers=new Map,this._renderTargetToRestore=null,this._lastFrameWasStationary=!1,this._wasmMemBlockSizes=[512,1024,2048,4096,8192,16384,32768,65536],this._wasmMemBlocks=new Map,this._dbgFlags=new Set,this._captureFrustum=!1,this._frustum=null,this._frustumRenderableId=-1,this._renderCoordsHelper=null,this.type=9,this.slicePlaneEnabled=!0,this.isGround=!1,this.layerViewUid=[]}_dbg(e,t){this._dbgFlags.has(e)&&(4===e?s.getLogger(this).error(t):s.getLogger(this).warn(t))}initialize(){this._dbg(1,"--initialize--");for(const e of this._wasmMemBlockSizes)this._wasmMemBlocks.set(e,0);this.addHandles([i(()=>"local"===this.view.viewingMode,e=>{e?(this._dbg(1,"view switched to local view, enabling rendering"),this.produces=c.VOXEL,this.view.sceneIntersectionHelper.addIntersectionHandler(this)):(this._dbg(1,"view switched to global view, disabling rendering"),this.view.sceneIntersectionHelper.removeIntersectionHandler(this),this.produces="disabled")},a),i(()=>this.view?.qualityProfile,e=>{this._dbg(3,"qualityProfile changed to "+e),this._vxl?.set_quality(this._toWasmQuality(e))},a),i(()=>this.view?.timeExtent,()=>{if(this._vxl){const e=this._getTimeArgs(this.view?.timeExtent);this._dbg(3,"sceneView timeExtent changed to useTime="+e.hasTime+" st="+e.startTime+" et="+e.endTime),this._vxl.set_scene_time_extent(e.startTime,e.endTime,e.hasTime),this.requestRender(1)}},a),i(()=>this.view?.stationary,e=>{this._vxl&&e&&!this._lastFrameWasStationary&&this.requestRender(1)})])}get _rctx(){return this.renderContext?.rctx}get _halfIntTexturesAvailable(){return!!this._rctx?.capabilities.textureNorm16}get _textureFloatLinearAvailable(){return!!this._rctx?.capabilities.textureFloatLinear}_restoreFramebuffer(){if(!this._renderTargetToRestore||!this._rctx)return;const e=this._renderTargetToRestore.fbo;if(!!!this._rctx)return void this._dbg(4,"no context in restoreFramebuffer!");this._rctx.bindFramebuffer(e,!0);const t=this._renderTargetToRestore.viewport;this._rctx.setViewport(t.x,t.y,t.width,t.height)}_bindPreviousDepthToSlot(e,t){if(!this._rctx||!this._renderTargetToRestore)return 0;const s=this._renderTargetToRestore.fbo?.depthStencilTexture;return s?(0===t?this._rctx.bindTexture(null,e,!0):this._rctx.bindTexture(s,e,!0),1):(this._dbg(4,"no depth/stencil texture exists!"),0)}_modifyResourceCount(e,t,s){if(!this._rctx)return void this._dbg(4,"modifyAllocation callback has no rendering context!");const r=e;1===s?this._rctx.instanceCounter.increment(r,t):this._rctx.instanceCounter.decrement(r,t)}_setBlendState(e,t,s,r){this._rctx?(this._rctx.setBlendingEnabled(1===e),this._rctx.setBlendFunction(t,s),this._rctx.setBlendEquation(r)):this._dbg(4,"setBlendState callback has no rendering context!")}_setFrontFace(e){this._rctx?this._rctx.setFrontFace(e):this._dbg(4,"setFrontFace callback has no rendering context!")}_setDepthStencilStateFunction(e,t,s){this._rctx?(this._rctx.setDepthFunction(s),this._rctx.setDepthTestEnabled(1===e),this._rctx.setDepthWriteEnabled(1===t),this._rctx.setStencilTestEnabled(!1),this._rctx.setStencilFunction(519,0,255),this._rctx.setStencilOpSeparate(1028,7680,7682,7680),this._rctx.setStencilOpSeparate(1029,7680,7683,7680)):this._dbg(4,"setDepthStencilStateFunction callback has no rendering context!")}_setRasterizerState(e){if(this._rctx)switch(e){case 1:this._rctx.setFaceCullingEnabled(!1);break;case 3:this._rctx.setCullFace(1029),this._rctx.setFaceCullingEnabled(!0);break;case 2:this._rctx.setCullFace(1028),this._rctx.setFaceCullingEnabled(!0)}else this._dbg(4,"setRasterizerState callback has no rendering context!")}_setViewport(e,t,s,r){this._rctx?this._rctx.setViewport(e,t,s,r):this._dbg(4,"setViewport callback has no rendering context!")}_updateMemoryUsage(){this._layers.forEach((e,t)=>{if(e.needMemoryUsageUpdate){const s=this._vxl?.estimate_memory_usage(t)??0;s>=0&&(e.needMemoryUsageUpdate=!1,e.layerView.setUsedMemory(s))}})}_syncRequestsResponses(){this._vxl&&this._layers.forEach((e,s)=>{const i=[];e.responses.forEach((t,r)=>{i.push(r),this._dbg(2,"responding for requestID:"+r+" size:"+t.size),this._vxl?.respond(s,r,t),0!==t.requestType&&4!==t.requestType||(e.needMemoryUsageUpdate=!0)});const a=e.responses;for(const t of i)a.delete(t);const n=this._vxl.get_new_requests(s),o=e.abortController.signal;for(const l in n){e.outstandingRequestCount+=1,1===e.outstandingRequestCount&&e.layerView.updatingFlagChanged();const s=n[l],i={responseType:"array-buffer",signal:o,query:{...e.layerView.layer.customParameters,token:e.layerView.layer.apiKey}};this._dbg(2,"making requestID:"+l+" url:"+s.url),t(s.url,i).then(t=>{e.outstandingRequestCount-=1,0===e.outstandingRequestCount&&e.layerView.updatingFlagChanged(),this._dbg(2,"have response for requestID:"+l);let r=0;if(t.data.byteLength>0&&this._vxl){r=this._vxl._malloc(t.data.byteLength);const e=new Uint8Array(this._vxl.HEAPU8.buffer,r,t.data.byteLength),s=new Uint8Array(t.data);for(let r=0;r<t.data.byteLength;++r)e[r]=s[r]}a.set(+l,{responseType:s.responseType,ptr:r,size:t.data.byteLength,success:!0,requestType:s.requestType})}).catch(t=>{e.outstandingRequestCount-=1,0===e.outstandingRequestCount&&e.layerView.updatingFlagChanged(),r(t)||(this._dbg(4,`requestID:${l} failed, error=${t.toString()}`),a.set(+l,{responseType:s.responseType,ptr:0,size:0,success:!1,requestType:s.requestType}))})}})}updateWasmCamera(e){this._vxl?.set_projection_matrix.apply(this._vxl,e.projectionMatrix),this._vxl?.set_view_matrix.apply(this._vxl,e.viewMatrix),this._vxl?.set_near_far(e.near,e.far)}isUpdating(e){if(!this._vxl&&this._vxlPromise)return!0;const t=this._layers.get(e);return!!t&&t.outstandingRequestCount>0}getLayerTimes(e){const t=[];return this._vxl?(this._layers.forEach((s,r)=>{if(s.layerView.wasmLayerId===e.wasmLayerId){const s=this._vxl.get_layer_epoch_times(r,e.layer.currentVariableId);for(let e=0;e<s.length;++e)t.push(s[e])}}),t):t}getCurrentLayerTimeIndex(e){let t=0;return this._layers.forEach((s,r)=>{s.layerView.wasmLayerId===e.wasmLayerId&&(t=this._vxl?.get_layer_current_time_id(r)??0)}),t}setEnabled(e,t){this._layers.forEach((s,r)=>{s.layerView.wasmLayerId===e.wasmLayerId&&(this._vxl?.set_enabled(r,t),s.needMemoryUsageUpdate=!0,this.requestRender(1))})}setIsInScaleRange(e,t){const s=this._layers.get(e.wasmLayerId);s&&t!==s.isInScaleRange&&(s.isInScaleRange=t,this._vxl?.set_is_in_scale_range(e.wasmLayerId,t),s.needMemoryUsageUpdate=!t,this.requestRender(1))}setStaticSections(e,t){const s={mask:1,staticSections:t};return this._doMaskedUIUpdate(e,s,!0)}setCurrentVariable(e,t){const s={mask:1024,currentVariable:t};return this._doMaskedUIUpdate(e,s,!0)}setRenderMode(e,t){const s={mask:8192,renderMode:t};return this._doMaskedUIUpdate(e,s,!0)}setVerticalExaggerationAndOffset(e,t,s,r){const i={mask:256,volStyleDesc:{volumeId:t,verticalExaggeration:s,verticalOffset:r}};return this._doMaskedUIUpdate(e,i,!0)}setVariableStyles(e,t){const s={mask:32768,variableStyles:t};return this._doMaskedUIUpdate(e,s,!0)}setVolumeStyles(e,t){const s={mask:65536,volumeStyles:t};return this._doMaskedUIUpdate(e,s,!0)}setEnableDynamicSections(e,t){const s={mask:4096,containerIsVisible:t,container:1};return this._doMaskedUIUpdate(e,s,!0)}setEnableIsosurfaces(e,t){const s={mask:4096,containerIsVisible:t,container:0};return this._doMaskedUIUpdate(e,s,!0)}setEnableSections(e,t){const s={mask:4096,containerIsVisible:t,container:2};return this._doMaskedUIUpdate(e,s,!0)}setAnalysisSlice(e,t,s,r){const i={mask:131072,analysisSlice:{point:s,normal:r,enabled:t}};return this._doMaskedUIUpdate(e,i,!0)}updateLayerTimeProperties(e){if(!this._vxl)return;const t=this._layers.get(e.wasmLayerId);if(t){const s=t.layerView.layer;let r=0;s.timeOffset&&(r=n(s.timeOffset.value,s.timeOffset.unit,"seconds"));const i=this._getTimeArgs(s.timeExtent);this._vxl?.set_layer_time_properties(e.wasmLayerId,i.startTime,i.endTime,i.hasTime,s.useViewTime,r),this.requestRender(1)}}_doMaskedUIUpdate(e,t,s){if(!this._vxl)return!1;let r=!1;return this._layers.forEach((s,i)=>{if(s.layerView.wasmLayerId===e.wasmLayerId){const e={str:JSON.stringify(t),byteCount:0,ptr:0,isReusable:!1};this._allocateBlock(e)&&(r=1===this._vxl?.handle_masked_ui_update(i,e.ptr,e.byteCount),e.isReusable||this._vxl?._free(e.ptr))}}),r&&s&&this.requestRender(1),r}_addTriangleToWasmBuffer(e,t,s,r,i){return e[3*t]=s[0],e[3*t+1]=s[1],e[3*t+2]=s[2],e[3*(t+=1)]=r[0],e[3*t+1]=r[1],e[3*t+2]=r[2],e[3*(t+=1)]=i[0],e[3*t+1]=i[1],e[3*t+2]=i[2],t+=1}_addNormalToWasmBuffer(e,t,s){return e[3*t]=s[0],e[3*t+1]=s[1],e[3*t+2]=s[2],t+=1}_doCaptureFrustum(){if(!this._vxl)return;const e=36,t=e/3,s=this._vxl._malloc(3*e*Float32Array.BYTES_PER_ELEMENT),r=new Float32Array(this._vxl.HEAPF32.buffer,s,3*e),i=this._vxl._malloc(3*t*Float32Array.BYTES_PER_ELEMENT),a=new Float32Array(this._vxl.HEAPF32.buffer,i,e),n=this._frustum.points[0],o=this._frustum.points[1],l=this._frustum.points[2],h=this._frustum.points[3],d=this._frustum.points[4],u=this._frustum.points[5],_=this._frustum.points[6],c=this._frustum.points[7];let m=0,f=0;const p=this._frustum.planes[4];m=this._addTriangleToWasmBuffer(r,m,l,o,n),f=this._addNormalToWasmBuffer(a,f,p),m=this._addTriangleToWasmBuffer(r,m,n,h,l),f=this._addNormalToWasmBuffer(a,f,p);const g=this._frustum.planes[5];m=this._addTriangleToWasmBuffer(r,m,d,u,_),f=this._addNormalToWasmBuffer(a,f,g),m=this._addTriangleToWasmBuffer(r,m,_,c,d),f=this._addNormalToWasmBuffer(a,f,g);const y=this._frustum.planes[3];m=this._addTriangleToWasmBuffer(r,m,_,l,h),f=this._addNormalToWasmBuffer(a,f,y),m=this._addTriangleToWasmBuffer(r,m,h,c,_),f=this._addNormalToWasmBuffer(a,f,y);const x=this._frustum.planes[2];m=this._addTriangleToWasmBuffer(r,m,n,o,u),f=this._addNormalToWasmBuffer(a,f,x),m=this._addTriangleToWasmBuffer(r,m,u,d,n),f=this._addNormalToWasmBuffer(a,f,x);const v=this._frustum.planes[0];m=this._addTriangleToWasmBuffer(r,m,h,n,d),f=this._addNormalToWasmBuffer(a,f,v),m=this._addTriangleToWasmBuffer(r,m,d,c,h),f=this._addNormalToWasmBuffer(a,f,v);const b=this._frustum.planes[1];m=this._addTriangleToWasmBuffer(r,m,l,_,u),f=this._addNormalToWasmBuffer(a,f,b),this._addTriangleToWasmBuffer(r,m,u,o,l),this._addNormalToWasmBuffer(a,f,b),-1!==this._frustumRenderableId&&this._vxl.remove_generic_mesh(this._frustumRenderableId),this._frustumRenderableId=this._vxl.add_generic_mesh(s,3*e,i,e,255,0,0,64),this._vxl._free(s),this._vxl._free(i),this._captureFrustum=!1,this.requestRender(1)}captureFrustum(){null===this._renderCoordsHelper&&(this._renderCoordsHelper=g.create(2,u(!1,this.view.spatialReference))),null===this._frustum&&(this._frustum=new p(this._renderCoordsHelper)),this._captureFrustum=!0,this.requestRender(1)}toggleFullVolumeExtentDraw(e){this._vxl&&this._layers.forEach((t,s)=>{t.layerView.wasmLayerId===e.wasmLayerId&&(this._vxl?.toggle_full_volume_extent_draw(s),this.requestRender(1))})}dropQueryRenderTarget(){this._vxl?.drop_query_rt()}addVoxelLayer(e){if(!this._vxl){const t={layerView:e,resolveCallback:null,rejectCallback:null},s=new Promise((e,s)=>{t.resolveCallback=e,t.rejectCallback=s});return this._newLayers.push(t),s}const t=this._addVoxelLayer(e,this._vxl);return t<0?Promise.reject(-1):Promise.resolve(t)}removeVoxelLayer(e){if(!this._vxl){const t=this._newLayers.findIndex(t=>e.uid===t.layerView.uid);t>=0&&(this._newLayers[t].resolveCallback(-1),this._newLayers.splice(t,1));const s=this._newLayers.length;return 0===s&&(this._dbg(1,"No voxel layers left after removing a layer, destroying render node"),this.destroy()),s}let t=-1;this._layers.forEach((s,r)=>{if(s.layerView.wasmLayerId===e.wasmLayerId){t=r,s.abortController.abort(),this._vxl?.remove_layer(t);const i=this.layerViewUid.indexOf(e.uid);-1!==i&&this.layerViewUid.splice(i,1)}}),t>=0&&this._layers.delete(t);const s=this._layers.size;return 0===s&&(this._dbg(1,"No voxel layers left after removing a layer, destroying render node"),this.destroy()),s}_getBlockSize(e){for(const t of this._wasmMemBlockSizes)if(e<t)return t;return-1}_allocateBlock(e){if(!this._vxl)return!1;e.byteCount=this._vxl.lengthBytesUTF8(e.str)+1;const t=this._getBlockSize(e.byteCount);return t<0?(e.isReusable=!1,e.ptr=this._vxl._malloc(e.byteCount)):(e.isReusable=!0,e.ptr=this._wasmMemBlocks.get(t),0===e.ptr&&(e.ptr=this._vxl._malloc(t),this._wasmMemBlocks.set(t,e.ptr))),0!==e.ptr&&(this._vxl.stringToUTF8(e.str,e.ptr,e.byteCount),!0)}_getTimeArgs(e){let t=-Number.MAX_VALUE,s=Number.MAX_VALUE,r=!1;return null!=e&&(e.isAllTime?r=!0:(null!=e.start&&(r=!0,t=e.start.getTime()/1e3),null!=e.end&&(r=!0,s=e.end.getTime()/1e3))),{startTime:t,endTime:s,hasTime:r}}_addVoxelLayer(e,t){const r=e.layer;let i=-1;const a=r.getConfiguration();if(a.length<1)return-1;const o={str:a,byteCount:0,ptr:0,isReusable:!1};if(!this._allocateBlock(o))return-1;const l=this._getTimeArgs(r.timeExtent),h=this.view.spatialReference.isWGS84&&r.spatialReference.isWGS84?111319.49079327357:1;let d=0;if(r.timeOffset&&(d=n(r.timeOffset.value,r.timeOffset.unit,"seconds")),i=t.add_layer(r.serviceRoot,o.ptr,o.byteCount,h,h,l.startTime,l.endTime,l.hasTime,r.useViewTime,d,this._toWasmQuality(this.view.qualityProfile)),o.isReusable||t._free(o.ptr),i>=0){r.test?.constantUpscaling&&(this._setUpscalingLimits(0,.25,.25),this._setUpscalingLimits(1,.5,.5),this._setUpscalingLimits(2,.75,.75));const t=new AbortController;if(this._layers.set(i,{layerView:e,responses:new Map,outstandingRequestCount:0,abortController:t,needMemoryUsageUpdate:!1,isInScaleRange:!0}),this.layerViewUid.push(e.uid),!this._halfIntTexturesAvailable||has("mac")){const t=[];let r="";for(const s of e.layer.variables)"Int16"!==s.renderingFormat.type&&"UInt16"!==s.renderingFormat.type||(t.push(s.name),s.id===e.layer.currentVariableId&&(r=s.name));""!==r&&s.getLogger(this).error("#addVoxelLayer_error()",e.layer,`The voxel layer '${e.layer.title}' cannot render the current variable '${r}' in this browser`),t.length>0&&s.getLogger(this).warn("#addVoxelLayer_warning()",e.layer,`The voxel layer '${e.layer.title}' cannot render the variables '${t.toString()}' in this browser`)}if(!this._textureFloatLinearAvailable){const t=[];let r="";for(const s of e.layer.variables)"Float32"===s.renderingFormat.type&&(t.push(s.name),s.id===e.layer.currentVariableId&&(r=s.name));""!==r&&s.getLogger(this).error("#addVoxelLayer_error()",e.layer,`The voxel layer '${e.layer.title}' cannot render the current variable '${r}' in this browser`),t.length>0&&s.getLogger(this).warn("#addVoxelLayer_warning()",e.layer,`The voxel layer '${e.layer.title}' cannot render the variables '${t.toString()}' in this browser`)}return has("esri-mobile")&&s.getLogger(this).warnOnce("Mobile support differs across devices. Voxel layer might not display as expected."),i}return-1}_prepareRender(){if(!this._vxl)return void this._initializeWasm();const e=this.bindParameters.camera.viewForward,t=this.bindParameters.camera.eye;this._vxl.update_camera_pos_and_direction(t[0],t[1],t[2],e[0],e[1],e[2]);const s=this._vxl.cull();this._dbg(2,"missingResourceCount="+s),this._moreToLoad=s>0,this._havePreparedWithAllLayers=0===this._newLayers.length,this._updateMemoryUsage()}render(){this._prepareRender();const e=this.bindRenderTarget();if(!this._vxl||!this._rctx)return this.requestRender(1),e;for(const s of this._newLayers){const e=this._addVoxelLayer(s.layerView,this._vxl);-1===e?s.rejectCallback(-1):s.resolveCallback(e)}if(this._newLayers=[],0===this._layers.size)return this._dbg(4,"No voxel layers but RenderNode is being asked to render!"),e;this._lastFrameWasStationary=this.view.stationary,this._syncRequestsResponses(),this._beforeDraw(this._rctx),this._vxl.begin_color_frame(!this.view.stage.renderer.isFeatureEnabled(1),this.bindParameters.lighting.mainLight.direction[0],this.bindParameters.lighting.mainLight.direction[1],this.bindParameters.lighting.mainLight.direction[2]);const t=this._renderTargetToRestore.viewport;return t.width===this._viewportWidth&&t.height===this._viewportHeight||(this._viewportWidth=t.width,this._viewportHeight=t.height,this._vxl.set_viewport(t.width,t.height),this._layers.forEach(e=>e.needMemoryUsageUpdate=!0)),0===t.x&&0===t.y||this._dbg(4,"Unsupported viewport parameters detected!"),this.updateWasmCamera(this.bindParameters.camera),this._captureFrustum&&(this._frustum.update(this.bindParameters.camera),this._doCaptureFrustum()),this._vxl.draw(),this._afterDraw(this._rctx,this._vxl),(this._moreToLoad||!this._havePreparedWithAllLayers&&this._layers.size>0)&&this.requestRender(1),e}destroy(){this._dbg(1,"--destroy--"),this._vxl&&(this._layers.forEach(e=>{e.abortController.abort()}),this._wasmMemBlocks.forEach(e=>{0!==e&&this._vxl?._free(e)}),this._vxl.uninitialize_voxel_wasm(),this._vxl=null)}_initializeWasm(){if(this._vxl||this._vxlPromise||!this._rctx?.gl)return;const e=this._rctx.gl;this._vxlPromise=_(e).then(t=>{if(t.specialHTMLTargets.jsAPI3DRenderingContext=e,this._vxl=t,this._vxlPromise=null,this._newLayers.length<=0)return this._dbg(1," no voxel layers left after WASM downloaded, removing RenderNode and destroying"),void this.destroy();const s=this._getTimeArgs(this.view?.timeExtent),r=this._vxl.addFunction(this._restoreFramebuffer.bind(this),"v"),i=this._vxl.addFunction(this._setBlendState.bind(this),"viiii"),a=this._vxl.addFunction(this._setFrontFace.bind(this),"vi"),n=this._vxl.addFunction(this._setRasterizerState.bind(this),"vi"),o=this._vxl.addFunction(this._setDepthStencilStateFunction.bind(this),"viii"),l=this._vxl.addFunction(this._setViewport.bind(this),"viiii"),h=this._vxl.addFunction(this._bindPreviousDepthToSlot.bind(this),"iii"),d=this._vxl.addFunction(this._modifyResourceCount.bind(this),"viii"),u=this._halfIntTexturesAvailable&&!has("mac"),_=this._textureFloatLinearAvailable;this._vxl.initialize_voxel_wasm(r,i,a,n,o,l,h,d,s.startTime,s.endTime,s.hasTime,u,_),this.requestRender(1)}).catch(()=>{for(const e of this._newLayers)e.rejectCallback(-2);this._dbg(4," WASM failed to download, destroying render node"),this.destroy()})}pickDepth(e,t,s){if(!this._vxl||!this._rctx||0===this._layers.size)return null;const r=s.viewport[3]-t;if(e<0||e>s.viewport[2]||t<0||t>s.viewport[3])return this._dbg(4,`[js] pickDepth: outOfRange, screenXY=[${e.toFixed(0)}, ${r.toFixed(0)}]]`),null;this._beforeDraw(this._rctx);const i=s.viewForward,a=s.eye;this._vxl.update_camera_pos_and_direction(a[0],a[1],a[2],i[0],i[1],i[2]),this.updateWasmCamera(s),this._vxl.begin_frame();const n=this._vxl.pick_depth(e,r);if(this._afterDraw(this._rctx,this._vxl),n.success){return n.distanceToCamera}return null}pickObject(e,t,s,r){if(!this._vxl||!this._rctx||0===this._layers.size)return null;const i=Math.round(e),a=Math.round(t);if(i<0||i>s.viewport[2]||a<0||a>s.viewport[3])return this._dbg(4,`[js] pickObject: outOfRange, screenXY=[${i}, ${a}], vp=[${s.viewport.toString()}]`),null;this._beforeDraw(this._rctx);const n=s.viewForward,o=s.eye;this._vxl.update_camera_pos_and_direction(o[0],o[1],o[2],n[0],n[1],n[2]),this.updateWasmCamera(s),this._vxl.begin_frame();let l=null;if(0===r.length)l=this._vxl.pick_object(i,a,0,0);else{const e={str:JSON.stringify({layerIds:r}),byteCount:0,ptr:0,isReusable:!1};this._allocateBlock(e)&&(l=this._vxl.pick_object(i,a,e.ptr,e.byteCount),e.isReusable||this._vxl._free(e.ptr))}return this._afterDraw(this._rctx,this._vxl),l}async getOtherFieldPopupValues(e,s){if(!this._vxl)return[];for(const r of e){const e=r.gpuResult;if(!e)continue;const i=this._layers.get(e.layerId);if(!i||!i.layerView.layer.url)continue;const a=i.layerView.layer,n={responseType:"array-buffer",signal:i.abortController.signal,query:{...i.layerView.layer.customParameters,token:i.layerView.layer.apiKey}},o=e.voxelSpacePosition,l=[Math.floor(o[0]/32),Math.floor(o[1]/32),Math.floor(o[2]/32)],h=[-4&l[0],-4&l[1],-4&l[2]];let d=0;if(e.epochTime){const t=this._vxl.get_layer_epoch_times(i.layerView.wasmLayerId,a.currentVariableId);for(let s=0;s<t.length;++s)if(t[s]===e.epochTime/1e3){d=s;break}}const u=[],_={varIds:[],ptrs:[],sizes:[]};for(const r of s){const e=a.variables.findIndex(e=>e.name===r);if(-1===e)continue;const s=a.variables.getItemAt(e)?.id;if(null==s)continue;const i=`${a.url}/variables/${s}/${d}/bundles/0/${h[0]}-${h[1]}-${h[2]}`;u.push(t(i,n).then(e=>e.data)),_.varIds.push(s)}const c=await Promise.allSettled(u),m=c.length;for(let t=0;t<m;++t){const e=c[t];if("fulfilled"===e.status){const t=e.value,s=this._vxl._malloc(t.byteLength);new Uint8Array(this._vxl.HEAPU8.buffer,s,t.byteLength).set(new Uint8Array(t)),_.ptrs.push(s),_.sizes.push(t.byteLength)}else _.varIds.splice(t,1)}const f=this._vxl.get_other_field_popup_values(e,_);for(let t=0;t<_.ptrs.length;++t)this._vxl._free(_.ptrs[t]);if(f.continuousValues)for(const t in f.continuousValues)r.attributes[t]=f.continuousValues[t];if(f.uniqueValues)for(const t in f.uniqueValues)r.attributes[t]=f.uniqueValues[t]}return e}_beforeDraw(e){this._renderTargetToRestore={fbo:e.boundFramebuffer,viewport:e.getViewport()},e.setPolygonOffsetFillEnabled(!1),e.setScissorTestEnabled(!1),e.setColorMask(!0,!0,!0,!0)}_afterDraw(e,t){this._renderTargetToRestore.fbo=null,e.externalTextureUnitUpdate(t.get_texture_units_bound_in_frame(),t.get_active_texture_unit()),e.externalVertexArrayObjectUpdate(),e.externalVertexBufferUpdate(),e.externalProgramUpdate()}intersectRay(e,t,s,r,i){if(!this._vxl||!this._rctx||0===this._layers.size||!e.options.selectionMode||e.options.isFiltered||!e.camera)return;if(null==i||i[0]<0||i[0]>e.camera.viewport[2]||i[1]<0||i[1]>e.camera.viewport[3])return this._dbg(4,i?`[js] VoxelWasmPerScene.intersect: outOfRange, screenXY=[${i[0].toFixed(0)}, ${i[1].toFixed(0)}]`:"[js] VoxelWasmPerScene.intersect: outOfRange, screenXY=null"),null;const a=[];this._layers.forEach(t=>{e.options.filteredLayerViewUids.includes(t.layerView.uid)&&a.push(t.layerView.wasmLayerId)});const n=this.pickObject(i[0],i[1],e.camera,a);if(null==n||-1===n.layerId)return;const o=this._layers.get(n.layerId);if(o){const t=o.layerView.layer.uid,i=n.distanceToCamera/h(s,r),a=d();a[0]=n.worldX,a[1]=n.worldY,a[2]=n.worldZ;const l={},u=o.layerView.layer,_=u.variables.findIndex(e=>e.id===u.currentVariableId);if(_>=0){const e=u.variables.getItemAt(_);null!=e&&(null!=n.continuousValue?l[e.name]=n.continuousValue:null!=n.uniqueValueLabel&&null!=n.uniqueValue?l[e.name]=`${n.uniqueValueLabel} (${n.uniqueValue})`:null!=n.uniqueValue&&(l[e.name]=`${n.uniqueValue}`),e.description.length>0?l["Voxel.CurrentVariable"]=e.description:e.name?.length>0&&(l["Voxel.CurrentVariable"]=e.name))}if(l["Voxel.Position"]=`[${n.voxelSpacePosition.toString()}]`,null!=n.epochTime&&null!=n.nativeTime&&null!=n.nativeTimeUnits){const e=new Date(n.epochTime);l["Voxel.LocalTime"]=e,l["Voxel.SourceTime"]=`${n.nativeTime.toLocaleString()} ${n.nativeTimeUnits}`}null!=n.depth&&(l["Voxel.Depth"]=n.depth);const c=n.faceNormal;l["Voxel.WorldPosition"]=`[${a[0]}, ${a[1]}, ${a[2]}]`;const m=e=>{const s=new f(a,t,()=>this._createVoxelGraphic(o.layerView.layer,l,n));e.set(this.type,s,i,i,c)},p=e.results,g=2===e.options.store;if((null==p.min.renderDistance||i<p.min.renderDistance)&&m(p.min),(null==p.max.renderDistance||i>p.max.renderDistance)&&m(p.max),g){const t=new x(e.ray);m(t),e.results.all.push(t)}}}_createVoxelGraphic(e,t,s){return new m({layer:e,sourceLayer:e,origin:e.graphicOrigin,attributes:t,gpuResult:s})}_toWasmQuality(e){switch(e){case"low":return 0;case"medium":return 1;case"high":return 2}}_setUpscalingLimits(e,t,s){this._vxl&&this._vxl.set_upscaling_limits(e,t,s)}};e([o()],v.prototype,"consumes",void 0),e([o()],v.prototype,"produces",void 0),v=e([l("esri.layers.VoxelWasmPerSceneView")],v);const b=v;export{b as default};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{FabricKustoConnection as e}from"./FabricKustoConnection.js";import n from"./GeoEventConnection.js";import{WebSocketConnection as o}from"./WebSocketConnection.js";import{ClientSideConnection as t}from"../../../support/ClientSideConnection.js";function r(r,c){switch(r.type){case"client":return new t(r,c);case"custom":return new o(r,c);case"geoevent":return new n(r,c);case"kusto":return new e(r,c)}}export{r as createConnection};
2
+ import{FabricKustoConnection as e}from"./FabricKustoConnection.js";import n from"./GeoEventConnection.js";import{WebSocketConnection as o}from"./WebSocketConnection.js";import{ClientSideConnection as t}from"../../../support/ClientSideConnection.js";function r(r,c){const i=c.toJSON();switch(r.type){case"client":return new t(r,i);case"custom":return new o(r,i);case"geoevent":return new n(r,i);case"kusto":return new e(r,i)}}export{r as createConnection};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- function n(n){const u=new Map;for(const o of n.files){const n=t(o);u.set(o.name,n)}return u}function t(n){const t=new Map;for(const u of n.statistics??[]){const n=u.column.at(-1);null!=n&&t.set(n,{minValue:u.minValue,maxValue:u.maxValue,nullCount:u.nullCount??0,distinctCount:u.distinctCount??null})}return new u(0,0,t)}class u{static fromFile(n){const t=n.numRows(),o=n.byteLength(),l=new Map;for(const u of n.getColumnDescriptors()){const n=u.minValue(),t=u.maxValue(),o=u.distinctCount()??null,s=u.nullCount()??null;null!=n&&null!=t&&l.set(u.name(),{minValue:n,maxValue:t,distinctCount:o,nullCount:s}),u.free()}return new u(t,o,l)}constructor(n,t,u){this.rowCount=n,this.byteSize=t,this.statistics=u}}export{u as FileStatistics,t as parseFileStatistics,n as parseFileStatisticsMap};
2
+ function n(n){const{minValue:t,maxValue:u,numValues:l,nullCount:e,distinctCount:o}=n;return null!=l&&e===l?{type:"null-only",nullCount:e,distinctCount:o}:"number"==typeof t&&Number.isFinite(t)&&"number"==typeof u&&Number.isFinite(u)&&t<=u?{type:"bounds",minValue:t,maxValue:u,nullCount:e,distinctCount:o}:null!=t||null!=u||null!=o||null!=e?{type:"unknown",nullCount:e,distinctCount:o}:null}function t(n){const t=new Map;for(const l of n.files){const n=u(l);t.set(l.name,n)}return t}function u(t){const u=new Map;for(const l of t.statistics??[]){const t=l.column.at(-1);if(null==t)continue;const e=n({minValue:l.minValue,maxValue:l.maxValue,numValues:null,nullCount:l.nullCount??0,distinctCount:l.distinctCount??null});null!=e&&u.set(t,e)}return new e(0,0,u)}function l(t){const u=t.minValue(),l=t.maxValue(),e=t.numValues(),o=t.distinctCount()??null;return n({minValue:u,maxValue:l,numValues:e,nullCount:t.nullCount()??null,distinctCount:o})}class e{static fromFile(n){const t=n.numRows(),u=n.byteLength(),o=new Map;for(const e of n.getColumnDescriptors()){const n=l(e);null!=n&&o.set(e.name(),n),e.free()}return new e(t,u,o)}constructor(n,t,u){this.rowCount=n,this.byteSize=t,this.statistics=u}}export{e as FileStatistics,u as parseFileStatistics,t as parseFileStatisticsMap,l as readFieldStatistic};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{__addDisposableResource as e,__disposeResources as t}from"tslib";import{toConst as s}from"../../../../core/compilerUtils.js";import r from"../../../../core/Error.js";import i from"../../../../core/Handles.js";import has from"../../../../core/has.js";import a from"../../../../core/Logger.js";import{onAbortOrThrow as n,throwIfAborted as u}from"../../../../core/promiseUtils.js";import{QueueProcessor as o}from"../../../../core/QueueProcessor.js";import{parseWhereClause as l}from"../../../../core/sql.js";import c from"../../../../geometry/SpatialReference.js";import{set as p,create as d,expandWithAABB as f,expandWithRect as h,negativeInfinity as m}from"../../../../geometry/support/aaBoundingBox.js";import{copy as y,negativeInfinity as g,create as _,expandWithRect as w}from"../../../../geometry/support/aaBoundingRect.js";import{getScaleForResolution as x}from"../../../../geometry/support/scaleUtils.js";import{isWebMercator as F,isWGS84 as S}from"../../../../geometry/support/spatialReferenceUtils.js";import{convertToGeometry as I}from"../../featureConversionUtils.js";import{getFieldNamesFromStatistics as v}from"../../data/attributeSupport.js";import{getQueryResultExtent as q,getQueryBoundingRects as R,QueryEngine as C}from"../../data/QueryEngine.js";import{queryCapabilities as b}from"../../data/QueryEngineCapabilities.js";import{QueryEngineResult as E}from"../../data/QueryEngineResult.js";import{normalizeQueryLike as O}from"../../data/queryUtils.js";import{createFileProvider as P}from"../parquet/createFileProvider.js";import{createDrawingInfo as M}from"./clientSideDefaults.js";import{getParquetFileId as T,getParquetRowId as j,getParquetObjectId as Q}from"./parquetIdUtils.js";import N from"../../../support/Field.js";import A from"../../../support/FieldsIndex.js";import{isNumericField as B}from"../../../support/fieldUtils.js";import{fromParquetGeometryEncodingJSON as G}from"../../../support/parquetEncodingUtils.js";import{completeParquetLayerInfo as D,fromParquetJSONGeometryType as z,toParquetJSONGeometryType as V}from"../../../support/parquetUtils.js";import{loadParquetModule as W}from"../../../../libs/parquet/loadParquetModule.js";import{FeatureStoreQueryAdapter as U}from"../../../../views/2d/layers/features/FeatureStoreQueryAdapter.js";import{FeatureSnapshotSourceChunk as k}from"../../../../views/2d/layers/features/sources/strategies/chunks/FeatureSnapshotSourceChunk.js";import{FeatureSourceChunkStore as Z}from"../../../../views/2d/layers/features/sources/strategies/chunks/SourceChunkStore.js";import{FeatureMetadata as J}from"../../../../views/2d/layers/features/support/FeatureMetadata.js";import{FeatureSetReaderParquet as L}from"../../../../views/2d/layers/features/support/FeatureSetReaderParquet.js";const H=new U,Y=4,X="__OBJECTID",$=new TextDecoder,K=8e3,ee=2e7,te=8,se=2,re=20;class ie{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;){u(e),await this._fill(e);const t=await ae(this._pending);if(this._pending.delete(t.read),this._resolvedCount++,null!=t.chunk)return t.chunk}return null}async _fill(e){for(this._removeDone();this._pending.size<te;){const t=this._getOrCreateNextStream(e);if(null==t)return;this._pending.add(t.read(e))}}_getOrCreateNextStream(e){const t=this._resolvedCount>=te?te:se;if(this._fileIndex<this._files.length&&this._streams.length<t){const t=this._files[this._fileIndex++],s=new ne(t.id,this._createFileStream(t,e));return this._streams.push(s),s}return this._getNextStream()}_getNextStream(){const e=this._streams.length;for(let t=0;t<e;t++){const s=(this._streamIndex+t)%e,r=this._streams[s];if(r.canRead)return this._streamIndex=(s+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 ae(e){return Promise.race(Array.from(e,async e=>({read:e,chunk:await e})))}class ne{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&&0===this._readCount}async read(e){this._readCount++;try{const t=await this._stream,s=await t.next(e);return null==s?(this._reachedEnd=!0,null):{fileId:this._fileId,chunk:s}}finally{this._readCount--}}}class ue{constructor(){this._hasZ=!1,this._hasM=!1,this._queue=new o({concurrency:Y,process:(e,t)=>this._executeQuery(e,t)}),this._streams=new Map,this._streamIdCounter=0,this._indexMap={},this._handles=new i}async load(e){const t=e.spatialReference?c.fromJSON(e.spatialReference):void 0;if(t&&!t.isWGS84&&!t.isWebMercator)throw new r("parquet:unsupported-projection","Only WGS84 and Web Mercator are supported");this._customParameters=e.customParameters,this._provider=P(e.provider,null,()=>this._customParameters),this._handles.add(this._provider.events.on("sourceChanged",async()=>{await this.reload(e),await this._source.onSourceChange()}));const s=await this._provider.getMetadata(),i=await D(s,{fields:e.fields?.map(e=>N.fromJSON(e)),geometryEncoding:e.geometryEncoding?G(e.geometryEncoding):null,geometryType:e.geometryType?z(e.geometryType):null,displayOptimization:e.displayOptimization,spatialReference:t});if(this._hasZ=!!s?.hasZ,this._hasM=!!s?.hasM,!i.fields)throw new r("parquet:unsupported","Fields must be defined");let n;if(i.spatialReference&&i.geometryType){if(!i.spatialReference)throw new r("parquet:unsupported","SpatialReference must be defined");if(!i.spatialReference.isGeographic&&!i.spatialReference.isWebMercator)throw new r("parquet:unsupported-projection","Only WGS84 and Web Mercator are supported");i.spatialReference.isGeographic&&!i.spatialReference.isWGS84&&(a.getLogger("parquet:unsupported-projection").warn("Found a geographic projection that is not WGS84. Handling as WGS84.",{spatialReference:i.spatialReference}),i.spatialReference=c.WGS84),n={geometry:i.geometryEncoding?{geometryType:V(i.geometryType),spatialReference:i.spatialReference.toJSON(),encoding:i.geometryEncoding.toJSON()}:null,displayOptimization:i.displayOptimization}}this.setCustomParameters(e.customParameters),this._displayOptimization=i.displayOptimization,await this._provider.updateGeometryInfo(n),this._capabilities=Ee(await this._getFileStatistics(),this._hasZ,this._hasM);const u=await this._provider.getFiles();if(!u.length)return{layerDefinition:{},capabilities:Ee(null,this._hasZ,this._hasM)};const o=await u[0].file;i.file=o;const{fields:l}=i;if(null==l)throw new r("parquet-layer:missing-metadata","Unable to create parquet source: cannot infer fields",l);l.push(new N({name:X,type:"oid",alias:X}));for(const r of l){const e=o.getColumnId(r.name);null!=e&&(this._indexMap[r.name]=e)}const p=new A(l.map(e=>e.toJSON()));this._fieldsIndex=p;const d=V(i.geometryType??"point");return this._metadata=J.createFeature({fieldsIndex:p.toJSON(),geometryType:d,hasZ:this._hasZ,hasM:this._hasM,featureIdInfo:{type:"object-id",fieldName:X},subtypes:null,subtypeField:null,types:null,typeIdField:null,globalIdField:null,spatialReference:i.spatialReference,outSpatialReference:null,attributeSpatialReference:null,timeInfo:null,timeReferenceUnknownClient:null,dateFieldsTimeZone:null}),this._queryEngineParams={fieldsIndex:this._metadata.fieldsIndex,geometryType:d,featureIdInfo:{type:"object-id",fieldName:X},hasM:this._hasM,hasZ:this._hasZ,spatialReference:i.spatialReference?.toJSON()??{wkid:4326},aggregateAdapter:null,timeInfo:null,definitionExpression:null},this._fullExtent=s?.extent?s.extent:await this._tryDeriveParquetFullExtent(i),{capabilities:this._capabilities,layerDefinition:{fields:i.fields?.map(e=>e.toJSON()),drawingInfo:M(d),extent:this._fullExtent??void 0,geometryType:d,geometryEncoding:i.geometryEncoding?.toJSON(),displayOptimization:i.displayOptimization}}}destroy(){this._provider.destroy(),this._queue.destroy();for(const{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._provider=P(e,this._provider.getGeometryInfo(),()=>this._customParameters)}async queryFeatures(e,t){const s=await O(e,null,this._queryEngineParams.spatialReference);if(this._validateQuery(s),Oe(s)||(s.resultRecordCount=s.resultRecordCount?Math.min(s.resultRecordCount,K):K,s.resultOffset=s.resultOffset??0),s.outStatistics)return this._queryStatistics(s,t);s.returnDistinctValues&&(s.returnGeometry=void 0);return(await this._enqueueQuery(s,t)).createQueryResponse()}async queryFeatureCount(e,t){const s=await O(e,null,this._queryEngineParams.spatialReference);if(this._validateQuery(s),!pe(s))return this._getFeatureCount();s.outFields=void 0,s.returnGeometry=void 0;return(await this._enqueueQuery(s,t)).createQueryResponseForCount()}async queryObjectIds(e,t){const s=await O(e,null,this._queryEngineParams.spatialReference);if(this._validateQuery(s),!pe(s))return Array.from({length:await this._getFeatureCount()},(e,t)=>t);s.resultRecordCount=s.resultRecordCount?Math.min(s.resultRecordCount,8e3):8e3,s.resultOffset=s.resultOffset??0,s.returnGeometry=void 0,s.outFields=void 0;return(await this._enqueueQuery(s,t)).items.map(e=>e.getObjectId())}async queryAttributeBins(e,t={}){throw new r("parquet:unsupported","queryAttributeBins not supported.")}async queryExtent(e,t){const r=await O(e,null,this._queryEngineParams.spatialReference);if(this._validateQuery(r),this._fullExtent&&!pe(r))return{count:await this._getFeatureCount(),extent:this._fullExtent};const i=s(this._metadata.spatialReference);r.returnGeometry=!0,r.outFields=void 0;const a=p(d(),m),n=d(),u=await this._enqueueQuery(r,t);let o=0;for(const s of u.items)s.getBounds(n)&&(f(a,n),o+=1);return{count:o,extent:q(a,i,r.outSR?s(r.outSR):i.toJSON(),i,!1)}}async queryStream(e,t){if(!t.signal)throw new Error("InternalError: AbortSignal must be passed");const s=await this._getCandidateFiles(e),r=new ie(s,async(t,s)=>{const r=await t.file,i=await this._createParquetDisplayQuery(r,t.id,e);return r.executeQuery(i,K,s)}),i=this._streamIdCounter++,a=n(t.signal,e=>{const t=this._streams.get(i);null!=t&&(t.handle.remove(),this._streams.delete(i))});return this._streams.set(i,{stream:r,handle:a}),i}async getStreamNext(e,t){if(!t.signal)throw new Error("InternalError: AbortSignal must be passed");const s=this._streams.get(e);if(!s)return{result:null};const r=await s.stream.next(t.signal);if(null==r)return s.handle.remove(),this._streams.delete(e),{result:null};const 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){const{result:s}=await this.getStreamNext(e,t);if(null==s)return null;const r=(await W()).ParquetChunk.deserialize(new Uint8Array(s.buffer)),i=new L(this._metadata,this._indexMap,r,s.fileId),a=[];for(;i.next();){const e=I(i.readGeometryWorldSpace(),i.geometryType,i.hasZ,i.hasM),t=i.readAttributes();a.push({attributes:t,geometry:e})}return{features:a}}async createPatch(e,t,s,r,i){if(!i.signal)throw new Error("InternalError: AbortSignal must be passed");const a=await this._getFileInfoById(e),n=await a.file;return(await n.createChunkPatch(t,s,r,i.signal)).serialize().buffer}async _getCandidateFiles(e){const t=await this._provider.getFiles(),s=await this._getSpatialFilePruning(e);if(null==s)return t;const r=t.filter(e=>this._mayIncludeFileForSpatialPruning(e,s));return"xz"===s.type?Ie(r,s):r}async _queryStatistics(e,t){const s=await O({...e},null,this._queryEngineParams.spatialReference);if(s.returnGeometry=void 0,he(s,this._fieldsIndex)){const e=await this._getStatisticsFromFiles(s);if(e)return e}return(await this._enqueueQuery(s,t)).createQueryResponse()}async _getStatisticsFromFiles(e){const t=await this._provider.getFiles(),s={},r=[];for(const i of e.outStatistics??[]){const e=ge(i,t);if(!e.available)return null;s[i.outStatisticFieldName]=e.value,r.push(ye(i,this._fieldsIndex))}return{fields:r,features:[{attributes:s}]}}async _getSpatialFilePruning(e){if("tile"!==e.type&&("arcade"!==e.type||null==e.extent))return null;const t=this._displayOptimization,s=t?.index;if(null==s)return null;const r=e.outSpatialReference.wkid;if(null==s.wkid||null==r)return null;const i=s.wkid,a=await W();switch(s.type){case"xz":return{type:"xz",fieldName:s.code,intersects:(t,n)=>a.queryIntersectsXZStatistics(s.fullExtent,e.extent,r,i,re,t,n)};case"z":return{type:"xy",xFieldName:s.xColumn,yFieldName:s.yColumn,intersects:(t,s,n,u)=>a.queryIntersectsXYStatistics(e.extent,r,i,t,s,n,u)}}}_mayIncludeFileForSpatialPruning(e,t){switch(t.type){case"xz":{const s=Se(e,t);return null==s||Re(s,t)}case"xy":{const{xStatistics:s,yStatistics:r}=qe(e,t);return null==s||null==r||Ce(s,r,t)}}}async _tryDeriveParquetFullExtent(s){if(!s.spatialReference)return null;if(null==this._fullExtent&&"location"===s.geometryEncoding?.type){const i=await this._provider.getFiles(),{xField:a,yField:n}=s.geometryEncoding,u=p(d(),m);for(const s of i){const i=await s.file;for(const s of i.rowGroups()){const i={stack:[],error:void 0,hasError:!1};try{const t=e(i,s.columnDescriptorForAttribute(a),!1),r=e(i,s.columnDescriptorForAttribute(n),!1),o=[t.minValue(),r.minValue(),t.maxValue(),r.maxValue()];h(u,o),s.free()}catch(r){i.error=r,i.hasError=!0}finally{t(i)}}}return{xmin:u[0],ymin:u[1],xmax:u[3],ymax:u[4],spatialReference:s.spatialReference?.toJSON()}}return null}async _getFileInfoById(e){const t=await this._provider.getFiles();for(const s of t)if(s.id===e)return s;throw new 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,s,r,i){const a=(await W()).Query.new();null!=s&&a.setPreFilterStart(s),null!=r&&a.setPreFilterCount(r),null!=i&&a.setPostFilterCount(i);const n=await this._getRequiredFields(e);a.setOutFields(n),(e.geometry||e.returnGeometry)&&a.setReturnGeometry(!0),a.setReturnZ(!!e.returnZ),a.setReturnM(!!e.returnM);const u=this._tryGetGeneralizedGeometryScale(e);null!=u&&a.setScale(u);const o=e.geometry?.spatialReference??this._queryEngineParams.spatialReference,l=o.wkid;if(e.geometry&&(F(o)||S(o))){const t=y(_(),g);for(const s of R(e.geometry))w(t,s);a.setOutSpatialReference(l),a.setExtent({xmin:t[0],ymin:t[1],xmax:t[2],ymax:t[3]})}if(e.where){const{id:s,file:r}=t;await this._setWhereClause(a,await r,s,e.where)}return a}async _createParquetDisplayQuery(e,t,s){const r=(await W()).Query.new();return"tile"===s.type?(r.setExtent(s.extent),r.setQuantizationTransform(s.transform),r.setScale(s.scale)):"arcade"===s.type&&null!=s.extent&&r.setExtent(s.extent),r.setOutFields(s.outFields.filter(e=>null!=this._indexMap[e])),r.setOutSpatialReference(s.outSpatialReference.wkid),r.setReturnGeometry(s.returnGeometry),r.setReturnZ(s.returnZ),r.setReturnM(s.returnM),s.where&&await this._setWhereClause(r,e,t,s.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 r("parquet:unsupported","Statistics queries are not supported",{query:e});if(!this._capabilities.query.supportsOrderBy&&e.orderByFields?.length)throw new r("parquet:unsupported","Queries using orderBy are not supported",{query:e});if(!this._capabilities.query.supportsDistinct&&e.returnDistinctValues)throw new r("parquet:unsupported","Queries using returnDistinctValues are not supported",{query:e})}async _setWhereClause(e,t,s,i){const a=this._indexMap,n=this._fieldsIndex,u={getAttribute(e,r){const i=a[r];if(null==i){const t=n.get(r);if("__OBJECTID"===t?.name){const t=e.row+e.rowGroupStart;return Q(s,t)}return null}const u=t.readAttribute(e.rowGroup,e.row,i);if(null==u)return null;const o=n.get(r);return"esriFieldTypeString"===o.type||"esriFieldTypeDateOnly"===o.type||"esriFieldTypeTimeOnly"===o.type||"esriFieldTypeTimestampOffset"===o.type?$.decode(u):u}},o=await l(i,this._fieldsIndex);if(!o.isStandardized)throw new r("sql-parse-error","expression is not standardized");const c=(e,t,s)=>o.testFeatureCompiled({rowGroup:e,row:t,rowGroupStart:s},u,null),p=o.fieldNames.map(e=>n.get(e)).filter(e=>e&&null!=this._indexMap[e?.name]);e.setWhere(i),e.setWhereEvaluator(c),e.setWhereFields(p.map(e=>e.name))}async*_streamFeatures(e,t,s,r,i){const a=await this._provider.getFiles();let n=0;for(const u of a){const a=n,o=n+u.statistics.rowCount;if(n+=u.statistics.rowCount,null!=t&&t>=o)continue;const l=null!=t?Math.max(t-a,0):null;let c=s;if(null!=s){const e=t??0,r=e+s,i=Math.max(e,a),n=Math.min(r,o);c=Math.max(n-i,0)}if(0===c)continue;const p=await this._createParquetQuery(e,u,l,c,r),d=await u.file,f=await d.executeQuery(p,K),h=async()=>{const e=await f.next(i);if(!e)return null;const t=new L(this._metadata,this._indexMap,e,u.id);return Fe([new k(t,null,0,!1)],this._queryEngineParams)};let m=await h();for(;null!=m;)yield m,m=await h()}}async _queryFeaturesWithQueryEnginePagination(e,t){const s=[],r=this._streamFeatures(e,null,null,null,t);let i=await r.next();for(;!i.done;){const a=await i.value.executeQueryForOpaqueFeatures({...e,where:void 0},t);for(const e of a)s.push(e);i=await r.next()}return s}async _queryFeaturesWithUpfrontPagination(e,t){let s,r,i,a=e.resultOffset??0,n=e.resultRecordCount??K;de(e)?fe(e)||(i=a+n):(a&&(s=a,a=0),r=e.resultRecordCount);const u=[],o=this._streamFeatures(e,s,r,i,t);let l=await o.next();for(;!l.done&&n>0;){const s=await l.value.executeQueryForOpaqueFeatures({...e,where:void 0},t);for(const e of s)if(a>0)a--;else if(u.push(e),--n<=0)return u;l=await o.next()}return u}_enqueueQuery(e,t){return this._queue.push(e,t)}async _executeQuery(e,t){if(e.objectIds?.length){const s=new Map;for(const t of e.objectIds){const e=T(t),r=j(t);let i=s.get(e);i||(i=[],s.set(e,i)),i.push(r)}const r=[];for(const[i,a]of s.entries()){const s=await this._executeFileIdQuery(e,i,a,t);for(const e of s)r.push(e)}return new E(r,e,{fieldsIndex:this._fieldsIndex,geometryType:this._metadata.geometryType,spatialReference:this._queryEngineParams.spatialReference,hasM:this._hasM,hasZ:this._hasZ,featureAdapter:H,featureIdInfo:this._queryEngineParams.featureIdInfo})}if("1=1"===e.where&&(e.where=null),e.resultOffset??=0,e.resultRecordCount??=await this._getFeatureCount(),e.resultRecordCount>ee){if(!(this._displayOptimization&&e.geometry))throw new r("parquet:cannot-execute-query","Unable to execute query, dataset is too large.")}const s=!!e.orderByFields?.length||!!e.outStatistics?.length||!!e.returnDistinctValues,i=s?await this._queryFeaturesWithQueryEnginePagination(e,t):await this._queryFeaturesWithUpfrontPagination(e,t);return s||(e.resultOffset=0),new E(i,e,{fieldsIndex:this._fieldsIndex,geometryType:this._metadata.geometryType,spatialReference:this._queryEngineParams.spatialReference,hasM:this._hasM,hasZ:this._hasZ,featureAdapter:H,featureIdInfo:this._queryEngineParams.featureIdInfo})}async _executeFileIdQuery(e,t,s,r){const i=await this._getRequiredFields(e),a=(await W()).Query.new();a.setOutFields(i),a.setReturnGeometry(!!e.returnGeometry),a.setReturnZ(!!e.returnZ),a.setReturnM(!!e.returnM),a.setIds(new Uint32Array(s));const n=await this._getFile(t),u=await n.executeQuery(a,K,r);let o=await u.next(r),l=0;const c=[];for(;null!=o;){const e=new L(this._metadata,this._indexMap,o,t),s=new k(e,null,l++,!1);c.push(s),o=await u.next(r)}return Fe(c,this._queryEngineParams).executeQueryForOpaqueFeatures(e,r)}async _getRequiredFields(e){const t=new Set;if(e.outStatistics)for(const s of v(this._fieldsIndex,e.outStatistics,e.groupByFieldsForStatistics))t.add(s);else if(e.outFields)for(const s of e.outFields)t.add(s);return(t.has("*")?this._fieldsIndex.fields.map(e=>e.name):Array.from(t)).filter(e=>null!=this._indexMap[e])}_tryGetGeneralizedGeometryScale(e){if(!this._displayOptimization)return null;const t=e.outSR??this._queryEngineParams.spatialReference;if(!F(t)&&!S(t))return null;const s=e.quantizationParameters?.tolerance??e.maxAllowableOffset;return s?x(s,t):null}}function oe(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 le(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 ce(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 pe(e){for(const t in e){const s=t;if(oe(s)&&null!==e[s])return!0}return!1}function de(e){for(const t in e){const s=t;if(le(s)&&null!==e[s])return!0}return!1}function fe(e){for(const t in e){const s=t;if(ce(s)&&null!==e[s])return!0}return!1}function he(e,t){return!!e.outStatistics?.length&&!pe(e)&&!e.groupByFieldsForStatistics?.length&&!e.orderByFields?.length&&!e.returnDistinctValues&&!e.returnAggIds&&e.outStatistics.every(e=>me(e,t))}function me(e,t){switch(e.statisticType){case"count":return"1"===e.onStatisticField||null!=t.get(e.onStatisticField);case"min":case"max":{const s=t.get(e.onStatisticField);return null!=s&&B(s)}default:return!1}}function ye(e,t){const s="exceedslimit"!==e.statisticType?t.get(e.onStatisticField):null,r="min"!==e.statisticType&&"max"!==e.statisticType||"esriFieldTypeDate"!==s?.type?"esriFieldTypeDouble":s.type;return{name:e.outStatisticFieldName,alias:e.outStatisticFieldName,type:r}}function ge(e,t){switch(e.statisticType){case"count":return _e(e,t);case"min":return we(e,t,Math.min);case"max":return we(e,t,Math.max);default:return{available:!1,value:null}}}function _e(e,t){if("count"!==e.statisticType)return{available:!1,value:null};if("1"===e.onStatisticField)return{available:!0,value:t.reduce((e,t)=>e+t.statistics.rowCount,0)};let s=0;for(const r of t){const t=r.statistics.statistics.get(e.onStatisticField);if(null==t||null==t.nullCount)return{available:!1,value:null};s+=r.statistics.rowCount-t.nullCount}return{available:!0,value:s}}function we(e,t,s){if("min"!==e.statisticType&&"max"!==e.statisticType)return{available:!1,value:null};let r=null;const i="min"===e.statisticType?"minValue":"maxValue";for(const a of t){const t=a.statistics.statistics.get(e.onStatisticField);if(null==t)return{available:!1,value:null};const n=xe(t[i]);null!=n&&(r=null==r?n:s(r,n))}return{available:!0,value:r}}function xe(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function Fe(e,t){const s=new Z;for(const r of e)s.insert(r);return new C({...t,featureStore:s})}function Se(e,t){return e.statistics.statistics.get(t.fieldName)??null}function Ie(e,t){return e.slice().sort((e,s)=>{const r=ve(e,t),i=ve(s,t);return r===i?0:r<i?-1:1})}function ve(e,t){const s=Se(e,t);if(null==s)return Number.POSITIVE_INFINITY;const r=be(s.minValue),i=be(s.maxValue);return null==r||null==i||i<r?Number.POSITIVE_INFINITY:i-r}function qe(e,t){return{xStatistics:e.statistics.statistics.get(t.xFieldName)??null,yStatistics:e.statistics.statistics.get(t.yFieldName)??null}}function Re(e,t){const s=be(e.minValue),r=be(e.maxValue);return null==s||null==r||t.intersects(s,r)}function Ce(e,t,s){const r=be(e.minValue),i=be(e.maxValue),a=be(t.minValue),n=be(t.maxValue);return null==r||null==i||null==a||null==n||s.intersects(r,i,a,n)}function be(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function Ee(e,t,s){const r=e?.featureCount;let i=!1;return null!=r&&r<has("parquetlayer-full-query-feature-count")&&(i=!0),{analytics:{supportsCacheHint:!1},attachment:null,data:{isVersioned:!1,isBranchVersioned:!1,supportedCurveTypes:[],supportsAttachment:!1,supportsM:s,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:{...b,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 Oe(e){return!!(e.objectIds?.length||e.outStatistics||e.orderByFields?.length||e.returnDistinctValues)}export{ue as default};
2
+ import{__addDisposableResource as e,__disposeResources as t}from"tslib";import{toConst as s}from"../../../../core/compilerUtils.js";import r from"../../../../core/Error.js";import i from"../../../../core/Handles.js";import has from"../../../../core/has.js";import a from"../../../../core/Logger.js";import{onAbortOrThrow as n,throwIfAborted as u}from"../../../../core/promiseUtils.js";import{QueueProcessor as o}from"../../../../core/QueueProcessor.js";import{parseWhereClause as l}from"../../../../core/sql.js";import c from"../../../../geometry/SpatialReference.js";import{set as p,create as d,expandWithAABB as f,expandWithRect as h,negativeInfinity as m}from"../../../../geometry/support/aaBoundingBox.js";import{copy as y,negativeInfinity as g,create as _,expandWithRect as w}from"../../../../geometry/support/aaBoundingRect.js";import{getScaleForResolution as x}from"../../../../geometry/support/scaleUtils.js";import{isWebMercator as F,isWGS84 as S}from"../../../../geometry/support/spatialReferenceUtils.js";import{convertToGeometry as I}from"../../featureConversionUtils.js";import{getFieldNamesFromStatistics as v}from"../../data/attributeSupport.js";import{getQueryResultExtent as q,getQueryBoundingRects as R,QueryEngine as b}from"../../data/QueryEngine.js";import{queryCapabilities as C}from"../../data/QueryEngineCapabilities.js";import{QueryEngineResult as E}from"../../data/QueryEngineResult.js";import{normalizeQueryLike as O}from"../../data/queryUtils.js";import{createFileProvider as P}from"../parquet/createFileProvider.js";import{readFieldStatistic as M}from"../parquet/ParquetFileStatistics.js";import{createDrawingInfo as T}from"./clientSideDefaults.js";import{getParquetFileId as j,getParquetRowId as Q,getParquetObjectId as A}from"./parquetIdUtils.js";import B from"../../../support/Field.js";import G from"../../../support/FieldsIndex.js";import{isNumericField as N}from"../../../support/fieldUtils.js";import{fromParquetGeometryEncodingJSON as D}from"../../../support/parquetEncodingUtils.js";import{completeParquetLayerInfo as z,fromParquetJSONGeometryType as V,toParquetJSONGeometryType as k}from"../../../support/parquetUtils.js";import{loadParquetModule as W}from"../../../../libs/parquet/loadParquetModule.js";import{FeatureStoreQueryAdapter as U}from"../../../../views/2d/layers/features/FeatureStoreQueryAdapter.js";import{FeatureSnapshotSourceChunk as Z}from"../../../../views/2d/layers/features/sources/strategies/chunks/FeatureSnapshotSourceChunk.js";import{FeatureSourceChunkStore as J}from"../../../../views/2d/layers/features/sources/strategies/chunks/SourceChunkStore.js";import{FeatureMetadata as L}from"../../../../views/2d/layers/features/support/FeatureMetadata.js";import{FeatureSetReaderParquet as H}from"../../../../views/2d/layers/features/support/FeatureSetReaderParquet.js";const X=new U,Y=4,$="__OBJECTID",K=new TextDecoder,ee=8e3,te=2e7,se=8,re=2,ie=20;class ae{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;){u(e),await this._fill(e);const t=await ne(this._pending);if(this._pending.delete(t.read),this._resolvedCount++,null!=t.chunk)return t.chunk}return null}async _fill(e){for(this._removeDone();this._pending.size<se;){const t=this._getOrCreateNextStream(e);if(null==t)return;this._pending.add(t.read(e))}}_getOrCreateNextStream(e){const t=this._resolvedCount>=se?se:re;if(this._fileIndex<this._files.length&&this._streams.length<t){const t=this._files[this._fileIndex++],s=new ue(t.id,this._createFileStream(t,e));return this._streams.push(s),s}return this._getNextStream()}_getNextStream(){const e=this._streams.length;for(let t=0;t<e;t++){const s=(this._streamIndex+t)%e,r=this._streams[s];if(r.canRead)return this._streamIndex=(s+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 ne(e){return Promise.race(Array.from(e,async e=>({read:e,chunk:await e})))}class ue{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&&0===this._readCount}async read(e){this._readCount++;try{const t=await this._stream,s=await t.next(e);return null==s?(this._reachedEnd=!0,null):{fileId:this._fileId,chunk:s}}finally{this._readCount--}}}class oe{constructor(){this._hasZ=!1,this._hasM=!1,this._queue=new o({concurrency:Y,process:(e,t)=>this._executeQuery(e,t)}),this._streams=new Map,this._streamIdCounter=0,this._indexMap={},this._handles=new i}async load(e){const t=e.spatialReference?c.fromJSON(e.spatialReference):void 0;if(t&&!t.isWGS84&&!t.isWebMercator)throw new r("parquet:unsupported-projection","Only WGS84 and Web Mercator are supported");this._customParameters=e.customParameters,this._provider=P(e.provider,null,()=>this._customParameters),this._handles.add(this._provider.events.on("sourceChanged",async()=>{await this.reload(e),await this._source.onSourceChange()}));const s=await this._provider.getMetadata(),i=await z(s,{fields:e.fields?.map(e=>B.fromJSON(e)),geometryEncoding:e.geometryEncoding?D(e.geometryEncoding):null,geometryType:e.geometryType?V(e.geometryType):null,displayOptimization:e.displayOptimization,spatialReference:t});if(this._hasZ=!!s?.hasZ,this._hasM=!!s?.hasM,!i.fields)throw new r("parquet:unsupported","Fields must be defined");let n;if(i.spatialReference&&i.geometryType){if(!i.spatialReference)throw new r("parquet:unsupported","SpatialReference must be defined");if(!i.spatialReference.isGeographic&&!i.spatialReference.isWebMercator)throw new r("parquet:unsupported-projection","Only WGS84 and Web Mercator are supported");i.spatialReference.isGeographic&&!i.spatialReference.isWGS84&&(a.getLogger("parquet:unsupported-projection").warn("Found a geographic projection that is not WGS84. Handling as WGS84.",{spatialReference:i.spatialReference}),i.spatialReference=c.WGS84),n={geometry:i.geometryEncoding?{geometryType:k(i.geometryType),spatialReference:i.spatialReference.toJSON(),encoding:i.geometryEncoding.toJSON()}:null,displayOptimization:i.displayOptimization}}this.setCustomParameters(e.customParameters),this._displayOptimization=i.displayOptimization,await this._provider.updateGeometryInfo(n),this._capabilities=Re(await this._getFileStatistics(),this._hasZ,this._hasM);const u=await this._provider.getFiles();if(!u.length)return{layerDefinition:{},capabilities:Re(null,this._hasZ,this._hasM)};const o=await u[0].file;i.file=o;const{fields:l}=i;if(null==l)throw new r("parquet-layer:missing-metadata","Unable to create parquet source: cannot infer fields",l);l.push(new B({name:$,type:"oid",alias:$}));for(const r of l){const e=o.getColumnId(r.name);null!=e&&(this._indexMap[r.name]=e)}const p=new G(l.map(e=>e.toJSON()));this._fieldsIndex=p;const d=k(i.geometryType??"point");return this._metadata=L.createFeature({fieldsIndex:p.toJSON(),geometryType:d,hasZ:this._hasZ,hasM:this._hasM,featureIdInfo:{type:"object-id",fieldName:$},subtypes:null,subtypeField:null,types:null,typeIdField:null,globalIdField:null,spatialReference:i.spatialReference,outSpatialReference:null,attributeSpatialReference:null,timeInfo:null,timeReferenceUnknownClient:null,dateFieldsTimeZone:null}),this._queryEngineParams={fieldsIndex:this._metadata.fieldsIndex,geometryType:d,featureIdInfo:{type:"object-id",fieldName:$},hasM:this._hasM,hasZ:this._hasZ,spatialReference:i.spatialReference?.toJSON()??{wkid:4326},aggregateAdapter:null,timeInfo:null,definitionExpression:null},this._fullExtent=s?.extent?s.extent:await this._tryDeriveParquetFullExtent(i),{capabilities:this._capabilities,layerDefinition:{fields:i.fields?.map(e=>e.toJSON()),drawingInfo:T(d),extent:this._fullExtent??void 0,geometryType:d,geometryEncoding:i.geometryEncoding?.toJSON(),displayOptimization:i.displayOptimization}}}destroy(){this._provider.destroy(),this._queue.destroy();for(const{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._provider=P(e,this._provider.getGeometryInfo(),()=>this._customParameters)}async queryFeatures(e,t){const s=await O(e,null,this._queryEngineParams.spatialReference);if(this._validateQuery(s),be(s)||(s.resultRecordCount=s.resultRecordCount?Math.min(s.resultRecordCount,ee):ee,s.resultOffset=s.resultOffset??0),s.outStatistics)return this._queryStatistics(s,t);s.returnDistinctValues&&(s.returnGeometry=void 0);return(await this._enqueueQuery(s,t)).createQueryResponse()}async queryFeatureCount(e,t){const s=await O(e,null,this._queryEngineParams.spatialReference);if(this._validateQuery(s),!de(s))return this._getFeatureCount();s.outFields=void 0,s.returnGeometry=void 0;return(await this._enqueueQuery(s,t)).createQueryResponseForCount()}async queryObjectIds(e,t){const s=await O(e,null,this._queryEngineParams.spatialReference);if(this._validateQuery(s),!de(s))return Array.from({length:await this._getFeatureCount()},(e,t)=>t);s.resultRecordCount=s.resultRecordCount?Math.min(s.resultRecordCount,8e3):8e3,s.resultOffset=s.resultOffset??0,s.returnGeometry=void 0,s.outFields=void 0;return(await this._enqueueQuery(s,t)).items.map(e=>e.getObjectId())}async queryAttributeBins(e,t={}){throw new r("parquet:unsupported","queryAttributeBins not supported.")}async queryExtent(e,t){const r=await O(e,null,this._queryEngineParams.spatialReference);if(this._validateQuery(r),this._fullExtent&&!de(r))return{count:await this._getFeatureCount(),extent:this._fullExtent};const i=s(this._metadata.spatialReference);r.returnGeometry=!0,r.outFields=void 0;const a=p(d(),m),n=d(),u=await this._enqueueQuery(r,t);let o=0;for(const s of u.items)s.getBounds(n)&&(f(a,n),o+=1);return{count:o,extent:q(a,i,r.outSR?s(r.outSR):i.toJSON(),i,!1)}}async queryStream(e,t){if(!t.signal)throw new Error("InternalError: AbortSignal must be passed");const s=await this._getCandidateFiles(e),r=new ae(s,async(t,s)=>{const r=await t.file,i=await this._createParquetDisplayQuery(r,t.id,e);return r.executeQuery(i,ee,s)}),i=this._streamIdCounter++,a=n(t.signal,e=>{const t=this._streams.get(i);null!=t&&(t.handle.remove(),this._streams.delete(i))});return this._streams.set(i,{stream:r,handle:a}),i}async getStreamNext(e,t){if(!t.signal)throw new Error("InternalError: AbortSignal must be passed");const s=this._streams.get(e);if(!s)return{result:null};const r=await s.stream.next(t.signal);if(null==r)return s.handle.remove(),this._streams.delete(e),{result:null};const 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){const{result:s}=await this.getStreamNext(e,t);if(null==s)return null;const r=(await W()).ParquetChunk.deserialize(new Uint8Array(s.buffer)),i=new H(this._metadata,this._indexMap,r,s.fileId),a=[];for(;i.next();){const e=I(i.readGeometryWorldSpace(),i.geometryType,i.hasZ,i.hasM),t=i.readAttributes();a.push({attributes:t,geometry:e})}return{features:a}}async createPatch(e,t,s,r,i){if(!i.signal)throw new Error("InternalError: AbortSignal must be passed");const a=await this._getFileInfoById(e),n=await a.file;return(await n.createChunkPatch(t,s,r,i.signal)).serialize().buffer}async _getCandidateFiles(e){const t=await this._provider.getFiles(),s=await this._getSpatialFilePruning(e);if(null==s)return t;const r=t.filter(e=>this._mayIncludeFileForSpatialPruning(e,s));return"xz"===s.type?ve(r,s):r}async _queryStatistics(e,t){const s=await O({...e},null,this._queryEngineParams.spatialReference);if(s.returnGeometry=void 0,me(s,this._fieldsIndex)){const e=await this._getStatisticsFromFiles(s);if(e)return e}return(await this._enqueueQuery(s,t)).createQueryResponse()}async _getStatisticsFromFiles(e){const t=await this._provider.getFiles(),s={},r=[];for(const i of e.outStatistics??[]){const e=_e(i,t);if(!e.available)return null;s[i.outStatisticFieldName]=e.value,r.push(ge(i,this._fieldsIndex))}return{fields:r,features:[{attributes:s}]}}async _getSpatialFilePruning(e){if("tile"!==e.type&&("arcade"!==e.type||null==e.extent))return null;const t=this._displayOptimization,s=t?.index;if(null==s)return null;const r=e.outSpatialReference.wkid;if(null==s.wkid||null==r)return null;const i=s.wkid,a=await W();switch(s.type){case"xz":return{type:"xz",fieldName:s.code,intersects:(t,n)=>a.queryIntersectsXZStatistics(s.fullExtent,e.extent,r,i,ie,t,n)};case"z":return{type:"xy",xFieldName:s.xColumn,yFieldName:s.yColumn,intersects:(t,s,n,u)=>a.queryIntersectsXYStatistics(e.extent,r,i,t,s,n,u)}}}_mayIncludeFileForSpatialPruning(e,t){switch(t.type){case"xz":{const s=Ie(e,t);return"null-only"!==s?.type&&("bounds"!==s?.type||t.intersects(s.minValue,s.maxValue))}case"xy":{const s=e.statistics.statistics.get(t.xFieldName),r=e.statistics.statistics.get(t.yFieldName);return"null-only"!==s?.type&&"null-only"!==r?.type&&("bounds"!==s?.type||"bounds"!==r?.type||t.intersects(s.minValue,s.maxValue,r.minValue,r.maxValue))}}}async _tryDeriveParquetFullExtent(s){if(!s.spatialReference)return null;if(null==this._fullExtent&&"location"===s.geometryEncoding?.type){const i=await this._provider.getFiles(),{xField:a,yField:n}=s.geometryEncoding,u=p(d(),m);let o=!1;for(const s of i){const i=await s.file;for(const s of i.rowGroups()){const i={stack:[],error:void 0,hasError:!1};try{const t=e(i,s.columnDescriptorForAttribute(a),!1),r=e(i,s.columnDescriptorForAttribute(n),!1),l=M(t),c=M(r);if("bounds"===l?.type&&"bounds"===c?.type){const e=[l.minValue,c.minValue,l.maxValue,c.maxValue];h(u,e),o=!0}s.free()}catch(r){i.error=r,i.hasError=!0}finally{t(i)}}}return o?{xmin:u[0],ymin:u[1],xmax:u[3],ymax:u[4],spatialReference:s.spatialReference?.toJSON()}:null}return null}async _getFileInfoById(e){const t=await this._provider.getFiles();for(const s of t)if(s.id===e)return s;throw new 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,s,r,i){const a=(await W()).Query.new();null!=s&&a.setPreFilterStart(s),null!=r&&a.setPreFilterCount(r),null!=i&&a.setPostFilterCount(i);const n=await this._getRequiredFields(e);a.setOutFields(n),(e.geometry||e.returnGeometry)&&a.setReturnGeometry(!0),a.setReturnZ(!!e.returnZ),a.setReturnM(!!e.returnM);const u=this._tryGetGeneralizedGeometryScale(e);null!=u&&a.setScale(u);const o=e.geometry?.spatialReference??this._queryEngineParams.spatialReference,l=o.wkid;if(e.geometry&&(F(o)||S(o))){const t=y(_(),g);for(const s of R(e.geometry))w(t,s);a.setOutSpatialReference(l),a.setExtent({xmin:t[0],ymin:t[1],xmax:t[2],ymax:t[3]})}if(e.where){const{id:s,file:r}=t;await this._setWhereClause(a,await r,s,e.where)}return a}async _createParquetDisplayQuery(e,t,s){const r=(await W()).Query.new();return"tile"===s.type?(r.setExtent(s.extent),r.setQuantizationTransform(s.transform),r.setScale(s.scale)):"arcade"===s.type&&null!=s.extent&&r.setExtent(s.extent),r.setOutFields(s.outFields.filter(e=>null!=this._indexMap[e])),r.setOutSpatialReference(s.outSpatialReference.wkid),r.setReturnGeometry(s.returnGeometry),r.setReturnZ(s.returnZ),r.setReturnM(s.returnM),s.where&&await this._setWhereClause(r,e,t,s.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 r("parquet:unsupported","Statistics queries are not supported",{query:e});if(!this._capabilities.query.supportsOrderBy&&e.orderByFields?.length)throw new r("parquet:unsupported","Queries using orderBy are not supported",{query:e});if(!this._capabilities.query.supportsDistinct&&e.returnDistinctValues)throw new r("parquet:unsupported","Queries using returnDistinctValues are not supported",{query:e})}async _setWhereClause(e,t,s,i){const a=this._indexMap,n=this._fieldsIndex,u={getAttribute(e,r){const i=a[r];if(null==i){const t=n.get(r);if("__OBJECTID"===t?.name){const t=e.row+e.rowGroupStart;return A(s,t)}return null}const u=t.readAttribute(e.rowGroup,e.row,i);if(null==u)return null;const o=n.get(r);return"esriFieldTypeString"===o.type||"esriFieldTypeDateOnly"===o.type||"esriFieldTypeTimeOnly"===o.type||"esriFieldTypeTimestampOffset"===o.type?K.decode(u):u}},o=await l(i,this._fieldsIndex);if(!o.isStandardized)throw new r("sql-parse-error","expression is not standardized");const c=(e,t,s)=>o.testFeatureCompiled({rowGroup:e,row:t,rowGroupStart:s},u,null),p=o.fieldNames.map(e=>n.get(e)).filter(e=>e&&null!=this._indexMap[e?.name]);e.setWhere(i),e.setWhereEvaluator(c),e.setWhereFields(p.map(e=>e.name))}async*_streamFeatures(e,t,s,r,i){const a=await this._provider.getFiles();let n=0;for(const u of a){const a=n,o=n+u.statistics.rowCount;if(n+=u.statistics.rowCount,null!=t&&t>=o)continue;const l=null!=t?Math.max(t-a,0):null;let c=s;if(null!=s){const e=t??0,r=e+s,i=Math.max(e,a),n=Math.min(r,o);c=Math.max(n-i,0)}if(0===c)continue;const p=await this._createParquetQuery(e,u,l,c,r),d=await u.file,f=await d.executeQuery(p,ee),h=async()=>{const e=await f.next(i);if(!e)return null;const t=new H(this._metadata,this._indexMap,e,u.id);return Se([new Z(t,null,0,!1)],this._queryEngineParams)};let m=await h();for(;null!=m;)yield m,m=await h()}}async _queryFeaturesWithQueryEnginePagination(e,t){const s=[],r=this._streamFeatures(e,null,null,null,t);let i=await r.next();for(;!i.done;){const a=await i.value.executeQueryForOpaqueFeatures({...e,where:void 0},t);for(const e of a)s.push(e);i=await r.next()}return s}async _queryFeaturesWithUpfrontPagination(e,t){let s,r,i,a=e.resultOffset??0,n=e.resultRecordCount??ee;fe(e)?he(e)||(i=a+n):(a&&(s=a,a=0),r=e.resultRecordCount);const u=[],o=this._streamFeatures(e,s,r,i,t);let l=await o.next();for(;!l.done&&n>0;){const s=await l.value.executeQueryForOpaqueFeatures({...e,where:void 0},t);for(const e of s)if(a>0)a--;else if(u.push(e),--n<=0)return u;l=await o.next()}return u}_enqueueQuery(e,t){return this._queue.push(e,t)}async _executeQuery(e,t){if(e.objectIds?.length){const s=new Map;for(const t of e.objectIds){const e=j(t),r=Q(t);let i=s.get(e);i||(i=[],s.set(e,i)),i.push(r)}const r=[];for(const[i,a]of s.entries()){const s=await this._executeFileIdQuery(e,i,a,t);for(const e of s)r.push(e)}return new E(r,e,{fieldsIndex:this._fieldsIndex,geometryType:this._metadata.geometryType,spatialReference:this._queryEngineParams.spatialReference,hasM:this._hasM,hasZ:this._hasZ,featureAdapter:X,featureIdInfo:this._queryEngineParams.featureIdInfo})}if("1=1"===e.where&&(e.where=null),e.resultOffset??=0,e.resultRecordCount??=await this._getFeatureCount(),e.resultRecordCount>te){if(!(this._displayOptimization&&e.geometry))throw new r("parquet:cannot-execute-query","Unable to execute query, dataset is too large.")}const s=!!e.orderByFields?.length||!!e.outStatistics?.length||!!e.returnDistinctValues,i=s?await this._queryFeaturesWithQueryEnginePagination(e,t):await this._queryFeaturesWithUpfrontPagination(e,t);return s||(e.resultOffset=0),new E(i,e,{fieldsIndex:this._fieldsIndex,geometryType:this._metadata.geometryType,spatialReference:this._queryEngineParams.spatialReference,hasM:this._hasM,hasZ:this._hasZ,featureAdapter:X,featureIdInfo:this._queryEngineParams.featureIdInfo})}async _executeFileIdQuery(e,t,s,r){const i=await this._getRequiredFields(e),a=(await W()).Query.new();a.setOutFields(i),a.setReturnGeometry(!!e.returnGeometry),a.setReturnZ(!!e.returnZ),a.setReturnM(!!e.returnM),a.setIds(new Uint32Array(s));const n=await this._getFile(t),u=await n.executeQuery(a,ee,r);let o=await u.next(r),l=0;const c=[];for(;null!=o;){const e=new H(this._metadata,this._indexMap,o,t),s=new Z(e,null,l++,!1);c.push(s),o=await u.next(r)}return Se(c,this._queryEngineParams).executeQueryForOpaqueFeatures(e,r)}async _getRequiredFields(e){const t=new Set;if(e.outStatistics)for(const s of v(this._fieldsIndex,e.outStatistics,e.groupByFieldsForStatistics))t.add(s);else if(e.outFields)for(const s of e.outFields)t.add(s);return(t.has("*")?this._fieldsIndex.fields.map(e=>e.name):Array.from(t)).filter(e=>null!=this._indexMap[e])}_tryGetGeneralizedGeometryScale(e){if(!this._displayOptimization)return null;const t=e.outSR??this._queryEngineParams.spatialReference;if(!F(t)&&!S(t))return null;const s=e.quantizationParameters?.tolerance??e.maxAllowableOffset;return s?x(s,t):null}}function le(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 ce(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 pe(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 de(e){for(const t in e){const s=t;if(le(s)&&null!==e[s])return!0}return!1}function fe(e){for(const t in e){const s=t;if(ce(s)&&null!==e[s])return!0}return!1}function he(e){for(const t in e){const s=t;if(pe(s)&&null!==e[s])return!0}return!1}function me(e,t){return!!e.outStatistics?.length&&!de(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"1"===e.onStatisticField||null!=t.get(e.onStatisticField);case"min":case"max":{const s=t.get(e.onStatisticField);return null!=s&&N(s)}default:return!1}}function ge(e,t){const s="exceedslimit"!==e.statisticType?t.get(e.onStatisticField):null,r="min"!==e.statisticType&&"max"!==e.statisticType||"esriFieldTypeDate"!==s?.type?"esriFieldTypeDouble":s.type;return{name:e.outStatisticFieldName,alias:e.outStatisticFieldName,type:r}}function _e(e,t){switch(e.statisticType){case"count":return we(e,t);case"min":return xe(e,t,Math.min);case"max":return xe(e,t,Math.max);default:return{available:!1,value:null}}}function we(e,t){if("count"!==e.statisticType)return{available:!1,value:null};if("1"===e.onStatisticField)return{available:!0,value:t.reduce((e,t)=>e+t.statistics.rowCount,0)};let s=0;for(const r of t){const t=r.statistics.statistics.get(e.onStatisticField);if(null==t||null==t.nullCount)return{available:!1,value:null};s+=r.statistics.rowCount-t.nullCount}return{available:!0,value:s}}function xe(e,t,s){if("min"!==e.statisticType&&"max"!==e.statisticType)return{available:!1,value:null};let r=null;const i="min"===e.statisticType?"minValue":"maxValue";for(const a of t){const t=a.statistics.statistics.get(e.onStatisticField);if(null==t)return{available:!1,value:null};switch(t.type){case"null-only":continue;case"unknown":return{available:!1,value:null};case"bounds":{const e=Fe(t[i]);if(null==e)return{available:!1,value:null};r=null==r?e:s(r,e);break}}}return{available:!0,value:r}}function Fe(e){return"number"==typeof e&&Number.isFinite(e)?e:null}function Se(e,t){const s=new J;for(const r of e)s.insert(r);return new b({...t,featureStore:s})}function Ie(e,t){return e.statistics.statistics.get(t.fieldName)??null}function ve(e,t){return e.slice().sort((e,s)=>{const r=qe(e,t),i=qe(s,t);return r===i?0:r<i?-1:1})}function qe(e,t){const s=Ie(e,t);return"bounds"!==s?.type?Number.POSITIVE_INFINITY:s.maxValue-s.minValue}function Re(e,t,s){const r=e?.featureCount;let i=!1;return null!=r&&r<has("parquetlayer-full-query-feature-count")&&(i=!0),{analytics:{supportsCacheHint:!1},attachment:null,data:{isVersioned:!1,isBranchVersioned:!1,supportedCurveTypes:[],supportsAttachment:!1,supportsM:s,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:{...C,maxRecordCount:ee,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 be(e){return!!(e.objectIds?.length||e.outStatistics||e.orderByFields?.length||e.returnDistinctValues)}export{oe as default};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import t from"../../../../core/Accessor.js";import r from"../../../../core/Error.js";import has from"../../../../core/has.js";import{whenOrAbort as o}from"../../../../core/promiseUtils.js";import{urlToObject as s}from"../../../../core/urlUtils.js";import{property as i,subclass as u}from"../../../../core/accessorSupport/decorators.js";import{equals as n}from"../../../../geometry/support/spatialReferenceUtils.js";import{isHostedAgolService as a}from"../../../support/arcgisLayerUrl.js";import{getGltfQueryFormat as c}from"../../../support/infoFor3D.js";import{parseUrl as p}from"../../../../rest/utils.js";import l from"../../../../rest/layerSources/DynamicDataLayer.js";import{executeForCount as d}from"../../../../rest/query/executeForCount.js";import{executeForExtent as m}from"../../../../rest/query/executeForExtent.js";import{executeForIds as y}from"../../../../rest/query/executeForIds.js";import{executeRawQueryJSON as h}from"../../../../rest/query/executeQueryJSON.js";import{executeRawQueryPBF as f}from"../../../../rest/query/executeQueryPBF.js";import F from"../../../../rest/support/FeatureSet.js";import S from"../../../../rest/support/Query.js";let x=class extends t{constructor(e){super(e),this.dynamicDataSource=null,this.fieldsIndex=null,this.gdbVersion=null,this.infoFor3D=null,this.pbfSupported=!1,this.pbfSupportedWithCurves=!1,this.queryAttachmentsSupported=!1,this.relativeTimeBinWindow=0,this.sourceSpatialReference=null,this.uniqueIdFields=null,this.url=null}get parsedUrl(){return s(this.url)}async execute(e,t){const r=await this.executeJSON(e,t);return this.featureSetFromJSON(e,r,t)}async executeJSON(e,t){const r=this._normalizeQuery(e),o=null!=e.outStatistics?.[0],s=has("featurelayer-pbf-statistics");let i;if(this.pbfSupported&&(!o||s)&&(!e.returnTrueCurves||this.pbfSupportedWithCurves))try{i=await f(this.url,r,t,{uniqueIdFields:this.uniqueIdFields})}catch(u){if("query:parsing-pbf"!==u.name)throw u;this.pbfSupported=!1}return i??=await h(this.url,r,t,{uniqueIdFields:this.uniqueIdFields}),this._normalizeFields(i.fields),i}async featureSetFromJSON(e,t,r){if(!this._queryGet3DObjectFormat(e)||null==this.infoFor3D||!t.features)return F.fromJSON(t);const{meshFeatureSetFromJSON:s}=await o(import("../../../../rest/support/meshFeatureSet.js"),r);return s(e,this.infoFor3D,t)}executeForCount(e,t){return d(this.url,this._normalizeQuery(e),t,{uniqueIdFields:this.uniqueIdFields})}executeForExtent(e,t){return m(this.url,this._normalizeQuery(e),t)}executeForIds(e,t){return y(this.url,this._normalizeQuery(e),t,{uniqueIdFields:this.uniqueIdFields})}async executeRelationshipQuery(e,t){const[{default:r},{executeRelationshipQuery:s}]=await o(Promise.all([import("../../../../rest/support/RelationshipQuery.js"),import("../../../../rest/query/executeRelationshipQuery.js")]),t);let i=r.from(e);return(this.gdbVersion||this.dynamicDataSource)&&(i=i.clone(),i.gdbVersion=i.gdbVersion||this.gdbVersion,i.dynamicDataSource=i.dynamicDataSource||this.dynamicDataSource),s(this.url,i,t)}async executeRelationshipQueryForCount(e,t){const[{default:r},{executeRelationshipQueryForCount:s}]=await o(Promise.all([import("../../../../rest/support/RelationshipQuery.js"),import("../../../../rest/query/executeRelationshipQuery.js")]),t);let i=r.from(e);return(this.gdbVersion||this.dynamicDataSource)&&(i=i.clone(),i.gdbVersion=i.gdbVersion||this.gdbVersion,i.dynamicDataSource=i.dynamicDataSource||this.dynamicDataSource),s(this.url,i,t)}async executeAttachmentQuery(e,t){const{executeAttachmentQuery:r,fetchAttachments:s,processAttachmentQueryResult:i}=await o(import("../../../../rest/query/operations/queryAttachments.js"),t),u=p(this.url);return i(u,await(this.queryAttachmentsSupported?r(u,e,t):s(u,e,t)))}async executeAttributeBinsQuery(e,t){const{executeAttributeBinsQuery:r}=await o(import("../../../../rest/query/executeAttributeBinsQuery.js"),t);return r(this.parsedUrl,e,t)}async executePivotQuery(e,t){const{executePivotQuery:r}=await o(import("../../../../rest/query/executePivotQuery.js"),t);return r(this.parsedUrl,e,t)}async executeTopFeaturesQuery(e,t){const{executeTopFeaturesQuery:r}=await o(import("../../../../rest/query/executeTopFeaturesQuery.js"),t);return r(this.parsedUrl,e,this.sourceSpatialReference,t)}async executeForTopIds(e,t){const{executeForTopIds:r}=await o(import("../../../../rest/query/executeForTopIds.js"),t);return r(this.parsedUrl,e,t)}async executeForTopExtents(e,t){const{executeForTopExtents:r}=await o(import("../../../../rest/query/executeForTopExtents.js"),t);return r(this.parsedUrl,e,t)}async executeForTopCount(e,t){const{executeForTopCount:r}=await o(import("../../../../rest/query/executeForTopCount.js"),t);return r(this.parsedUrl,e,t)}_normalizeQuery(e){let t=S.from(e);t.sourceSpatialReference=t.sourceSpatialReference||this.sourceSpatialReference,(this.gdbVersion||this.dynamicDataSource)&&(t=t===e?t.clone():t,t.gdbVersion=e.gdbVersion||this.gdbVersion,t.dynamicDataSource=e.dynamicDataSource?l.from(e.dynamicDataSource):this.dynamicDataSource),t.geometry&&null!=t.num&&null!=t.start&&a(this.url)&&(t=t===e?t.clone():t,t.resultType="tile");const{infoFor3D:o}=this,s=this._queryGet3DObjectFormat(e);if(null!=o&&s){if(t=t===e?t.clone():t,t.formatOf3DObjects=s,t.outSpatialReference&&!n(t.outSpatialReference,this.sourceSpatialReference))throw new r("query:unsupported-out-spatial-reference","3D object feature services do not support projection of geometries");if(null==t.outFields||!t.outFields.includes("*")){t=t===e?t.clone():t,null==t.outFields&&(t.outFields=[]);const{originX:r,originY:s,originZ:i,translationX:u,translationY:n,translationZ:a,scaleX:c,scaleY:p,scaleZ:l,rotationX:d,rotationY:m,rotationZ:y,rotationDeg:h}=o.transformFieldRoles;t.outFields.push(r,s,i,u,n,a,c,p,l,d,m,y,h)}}return t}_normalizeFields(e){if(null!=this.fieldsIndex&&null!=e)for(const t of e){const e=this.fieldsIndex.get(t.name);e&&Object.assign(t,e.toJSON())}}_queryGet3DObjectFormat({returnGeometry:e,multipatchOption:t,outStatistics:r}){return!0!==e||"xyFootprint"===t||r?null:c(this.infoFor3D)}};e([i({type:l})],x.prototype,"dynamicDataSource",void 0),e([i()],x.prototype,"fieldsIndex",void 0),e([i()],x.prototype,"gdbVersion",void 0),e([i()],x.prototype,"infoFor3D",void 0),e([i({readOnly:!0})],x.prototype,"parsedUrl",null),e([i()],x.prototype,"pbfSupported",void 0),e([i()],x.prototype,"pbfSupportedWithCurves",void 0),e([i()],x.prototype,"queryAttachmentsSupported",void 0),e([i()],x.prototype,"relativeTimeBinWindow",void 0),e([i()],x.prototype,"sourceSpatialReference",void 0),e([i()],x.prototype,"uniqueIdFields",void 0),e([i({type:String})],x.prototype,"url",void 0),x=e([u("esri.layers.graphics.sources.support.QueryTask")],x);export{x as default};
2
+ import{__decorate as e}from"tslib";import t from"../../../../core/Accessor.js";import r from"../../../../core/Error.js";import has from"../../../../core/has.js";import{whenOrAbort as o}from"../../../../core/promiseUtils.js";import{urlToObject as s}from"../../../../core/urlUtils.js";import{property as i,subclass as u}from"../../../../core/accessorSupport/decorators.js";import{equals as n}from"../../../../geometry/support/spatialReferenceUtils.js";import{getGltfQueryFormat as a}from"../../../support/infoFor3D.js";import{parseUrl as c}from"../../../../rest/utils.js";import p from"../../../../rest/layerSources/DynamicDataLayer.js";import{executeForCount as l}from"../../../../rest/query/executeForCount.js";import{executeForExtent as d}from"../../../../rest/query/executeForExtent.js";import{executeForIds as m}from"../../../../rest/query/executeForIds.js";import{executeRawQueryJSON as y}from"../../../../rest/query/executeQueryJSON.js";import{executeRawQueryPBF as h}from"../../../../rest/query/executeQueryPBF.js";import f from"../../../../rest/support/FeatureSet.js";import F from"../../../../rest/support/Query.js";let S=class extends t{constructor(e){super(e),this.dynamicDataSource=null,this.fieldsIndex=null,this.gdbVersion=null,this.infoFor3D=null,this.pbfSupported=!1,this.pbfSupportedWithCurves=!1,this.queryAttachmentsSupported=!1,this.relativeTimeBinWindow=0,this.sourceSpatialReference=null,this.uniqueIdFields=null,this.url=null}get parsedUrl(){return s(this.url)}async execute(e,t){const r=await this.executeJSON(e,t);return this.featureSetFromJSON(e,r,t)}async executeJSON(e,t){const r=this._normalizeQuery(e),o=null!=e.outStatistics?.[0],s=has("featurelayer-pbf-statistics");let i;if(this.pbfSupported&&(!o||s)&&(!e.returnTrueCurves||this.pbfSupportedWithCurves))try{i=await h(this.url,r,t,{uniqueIdFields:this.uniqueIdFields})}catch(u){if("query:parsing-pbf"!==u.name)throw u;this.pbfSupported=!1}return i??=await y(this.url,r,t,{uniqueIdFields:this.uniqueIdFields}),this._normalizeFields(i.fields),i}async featureSetFromJSON(e,t,r){if(!this._queryGet3DObjectFormat(e)||null==this.infoFor3D||!t.features)return f.fromJSON(t);const{meshFeatureSetFromJSON:s}=await o(import("../../../../rest/support/meshFeatureSet.js"),r);return s(e,this.infoFor3D,t)}executeForCount(e,t){return l(this.url,this._normalizeQuery(e),t,{uniqueIdFields:this.uniqueIdFields})}executeForExtent(e,t){return d(this.url,this._normalizeQuery(e),t)}executeForIds(e,t){return m(this.url,this._normalizeQuery(e),t,{uniqueIdFields:this.uniqueIdFields})}async executeRelationshipQuery(e,t){const[{default:r},{executeRelationshipQuery:s}]=await o(Promise.all([import("../../../../rest/support/RelationshipQuery.js"),import("../../../../rest/query/executeRelationshipQuery.js")]),t);let i=r.from(e);return(this.gdbVersion||this.dynamicDataSource)&&(i=i.clone(),i.gdbVersion=i.gdbVersion||this.gdbVersion,i.dynamicDataSource=i.dynamicDataSource||this.dynamicDataSource),s(this.url,i,t)}async executeRelationshipQueryForCount(e,t){const[{default:r},{executeRelationshipQueryForCount:s}]=await o(Promise.all([import("../../../../rest/support/RelationshipQuery.js"),import("../../../../rest/query/executeRelationshipQuery.js")]),t);let i=r.from(e);return(this.gdbVersion||this.dynamicDataSource)&&(i=i.clone(),i.gdbVersion=i.gdbVersion||this.gdbVersion,i.dynamicDataSource=i.dynamicDataSource||this.dynamicDataSource),s(this.url,i,t)}async executeAttachmentQuery(e,t){const{executeAttachmentQuery:r,fetchAttachments:s,processAttachmentQueryResult:i}=await o(import("../../../../rest/query/operations/queryAttachments.js"),t),u=c(this.url);return i(u,await(this.queryAttachmentsSupported?r(u,e,t):s(u,e,t)))}async executeAttributeBinsQuery(e,t){const{executeAttributeBinsQuery:r}=await o(import("../../../../rest/query/executeAttributeBinsQuery.js"),t);return r(this.parsedUrl,e,t)}async executePivotQuery(e,t){const{executePivotQuery:r}=await o(import("../../../../rest/query/executePivotQuery.js"),t);return r(this.parsedUrl,e,t)}async executeTopFeaturesQuery(e,t){const{executeTopFeaturesQuery:r}=await o(import("../../../../rest/query/executeTopFeaturesQuery.js"),t);return r(this.parsedUrl,e,this.sourceSpatialReference,t)}async executeForTopIds(e,t){const{executeForTopIds:r}=await o(import("../../../../rest/query/executeForTopIds.js"),t);return r(this.parsedUrl,e,t)}async executeForTopExtents(e,t){const{executeForTopExtents:r}=await o(import("../../../../rest/query/executeForTopExtents.js"),t);return r(this.parsedUrl,e,t)}async executeForTopCount(e,t){const{executeForTopCount:r}=await o(import("../../../../rest/query/executeForTopCount.js"),t);return r(this.parsedUrl,e,t)}_normalizeQuery(e){let t=F.from(e);t.sourceSpatialReference=t.sourceSpatialReference||this.sourceSpatialReference,(this.gdbVersion||this.dynamicDataSource)&&(t=t===e?t.clone():t,t.gdbVersion=e.gdbVersion||this.gdbVersion,t.dynamicDataSource=e.dynamicDataSource?p.from(e.dynamicDataSource):this.dynamicDataSource);const{infoFor3D:o}=this,s=this._queryGet3DObjectFormat(e);if(null!=o&&s){if(t=t===e?t.clone():t,t.formatOf3DObjects=s,t.outSpatialReference&&!n(t.outSpatialReference,this.sourceSpatialReference))throw new r("query:unsupported-out-spatial-reference","3D object feature services do not support projection of geometries");if(null==t.outFields||!t.outFields.includes("*")){t=t===e?t.clone():t,null==t.outFields&&(t.outFields=[]);const{originX:r,originY:s,originZ:i,translationX:u,translationY:n,translationZ:a,scaleX:c,scaleY:p,scaleZ:l,rotationX:d,rotationY:m,rotationZ:y,rotationDeg:h}=o.transformFieldRoles;t.outFields.push(r,s,i,u,n,a,c,p,l,d,m,y,h)}}return t}_normalizeFields(e){if(null!=this.fieldsIndex&&null!=e)for(const t of e){const e=this.fieldsIndex.get(t.name);e&&Object.assign(t,e.toJSON())}}_queryGet3DObjectFormat({returnGeometry:e,multipatchOption:t,outStatistics:r}){return!0!==e||"xyFootprint"===t||r?null:a(this.infoFor3D)}};e([i({type:p})],S.prototype,"dynamicDataSource",void 0),e([i()],S.prototype,"fieldsIndex",void 0),e([i()],S.prototype,"gdbVersion",void 0),e([i()],S.prototype,"infoFor3D",void 0),e([i({readOnly:!0})],S.prototype,"parsedUrl",null),e([i()],S.prototype,"pbfSupported",void 0),e([i()],S.prototype,"pbfSupportedWithCurves",void 0),e([i()],S.prototype,"queryAttachmentsSupported",void 0),e([i()],S.prototype,"relativeTimeBinWindow",void 0),e([i()],S.prototype,"sourceSpatialReference",void 0),e([i()],S.prototype,"uniqueIdFields",void 0),e([i({type:String})],S.prototype,"url",void 0),S=e([u("esri.layers.graphics.sources.support.QueryTask")],S);export{S as default};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import t from"../../request.js";import r from"../../core/Error.js";import i from"../../core/Logger.js";import{debounce as o}from"../../core/promiseUtils.js";import{property as s,subclass as a}from"../../core/accessorSupport/decorators.js";import{updateOrigins as n}from"../../core/accessorSupport/originUtils.js";import l from"../../geometry/Extent.js";import p from"../../geometry/HeightModelInfo.js";import c from"../../geometry/SpatialReference.js";import{titleFromUrlAndName as u,parse as d,cleanTitle as y,sanitizeUrlWithLayerId as m}from"../support/arcgisLayerUrl.js";import{id as h}from"../support/commonProperties.js";import{fetchIndexInfo as f}from"../support/I3SIndexInfo.js";import{urlProperty as v,normalizeParsedUrlObject as S}from"../support/multiLayerServiceUtils.js";import{getLoader as g}from"../support/schemaValidatorLoader.js";import w from"../../portal/Portal.js";import x from"../../portal/PortalItem.js";import{createForItemWrite as I}from"../../portal/support/jsonContext.js";import{saveResources as j,updateItemWithResources as b}from"../../webdoc/support/resourceUtils.js";import{evaluateWriteErrors as N}from"../../webdoc/support/saveUtils.js";import{reader as _}from"../../core/accessorSupport/decorators/reader.js";const R=m=>{const R=m;let E=class extends R{constructor(){super(...arguments),this.spatialReference=null,this.fullExtent=null,this.heightModelInfo=null,this.minScale=0,this.maxScale=0,this.version={major:Number.NaN,minor:Number.NaN,versionString:""},this.copyright=null,this.sublayerTitleMode="item-title",this.title=null,this.layerId=null,this.url=null,this.indexInfo=null,this._debouncedSaveOperations=o(async(e,t,r)=>{switch(e){case 0:return this._save(t);case 1:return this._saveAs(r,t)}})}readSpatialReference(e,t){return T(t)}readFullExtent(e,t,r){if(null!=e&&"object"==typeof e){const i=null==e.spatialReference?{...e,spatialReference:T(t)}:e;return l.fromJSON(i,r)}const i=t.store,o=T(t);return null==o||null==i?.extent||!Array.isArray(i.extent)||i.extent.some(e=>e<L)?null:new l({xmin:i.extent[0],ymin:i.extent[1],xmax:i.extent[2],ymax:i.extent[3],spatialReference:o})}parseVersionString(e){const t={major:Number.NaN,minor:Number.NaN,versionString:e},r=e.split(".");return r.length>=2&&(t.major=parseInt(r[0],10),t.minor=parseInt(r[1],10)),t}readVersion(e,t){const r=t.store,i=null!=r.version?r.version.toString():"";return this.parseVersionString(i)}readTitlePortalItem(e){return"item-title"!==this.sublayerTitleMode?void 0:e}readTitleService(e,t){if("item-title"===this.sublayerTitleMode)return this.url?u(this.url,t.name):t.name;let r=t.name;if(!r&&this.url){const e=d(this.url);null!=e&&(r=e.title)}const i=this.portalItem?.title;return"item-title-and-service-name"===this.sublayerTitleMode&&i&&(r=i+" - "+r),y(r)}get parsedUrl(){return S(this,{separator:"layers"})}async _fetchIndexAndUpdateExtent(e,t){this.indexInfo=f(this.parsedUrl?.path??"",this.rootNode,e,this.customParameters,this.apiKey,i.getLogger(this),t),this.indexInfo.catch(()=>{});const{fullExtent:r}=this;null==r||r.hasZ||this._updateExtent(r,await this.indexInfo)}_updateExtent(e,t){if("page"===t?.type){const r=t.rootIndex%t.pageSize,i=t.rootPage?.nodes?.[r];A(e,i?.obb)}else if("node"===t?.type){const r=t.rootNode?.mbs;if(!Array.isArray(r)||4!==r.length||r[0]<L)return;const i=r[2],o=r[3];e.zmin=i-o,e.zmax=i+o}}async _fetchService(e){if(null==this.url)throw new r("sceneservice:url-not-set","Scene service can not be loaded without valid portal item or url");if(null==this.layerId&&/SceneServer\/*$/i.test(this.url)){const t=await this._fetchFirstLayerId(e);null!=t&&(this.layerId=t)}return this._fetchServiceLayer(e)}async _fetchFirstLayerId(e){const r=await t(this.url??"",{query:{f:"json",...this.customParameters,token:this.apiKey},responseType:"json",signal:e});if(r.data&&Array.isArray(r.data.layers)&&r.data.layers.length>0)return r.data.layers[0].id}async _fetchServiceLayer(e){const r=await t(this.parsedUrl?.path??"",{query:{f:"json",...this.customParameters,token:this.apiKey},responseType:"json",signal:e});r.ssl&&this.url&&(this.url=this.url.replace(/^http:/i,"https:"));let i=!1;if(r.data.layerType&&"Voxel"===r.data.layerType&&(i=!0),i)return this._fetchVoxelServiceLayer();const o=r.data;this.read(o,this._getServiceContext()),this.validateLayer(o)}async _fetchVoxelServiceLayer(e){const r=(await t(this.parsedUrl?.path+"/layer",{query:{f:"json",...this.customParameters,token:this.apiKey},responseType:"json",signal:e})).data;this.read(r,this._getServiceContext()),this.validateLayer(r)}_getServiceContext(){return{origin:"service",portalItem:this.portalItem,portal:this.portalItem?.portal,url:this.parsedUrl}}async _ensureLoadBeforeSave(){await this.load(),"beforeSave"in this&&"function"==typeof this.beforeSave&&await this.beforeSave()}validateLayer(e){}async _saveAs(e,t){const i={...P,...t};let o=x.from(e);if(!o)throw new r("sceneservice:portal-item-required","_saveAs() requires a portal item to save to");o.id&&(o=o.clone(),o.id=null);const s=o.portal||w.getDefault();await this._ensureLoadBeforeSave(),o.type=U,o.portal=s;const a=I(o,"portal-item",!0),l={layers:[this.write({},a)]};return await Promise.all(a.resources.pendingOperations??[]),await this._validateAgainstJSONSchema(l,a,i),this.url&&(o.url=this.url),o.title||(o.title=this.title),O(o,i,1),await s.signIn(),await s.user.addItem({item:o,folder:i?.folder,data:l}),await j(this.resourceReferences,a),this.portalItem=o,n(a),a.portalItem=o,o}async _save(e){const t={...P,...e};if(!this.portalItem)throw new r("sceneservice:portal-item-not-set","Portal item to save to has not been set on this SceneService");if(this.portalItem.type!==U)throw new r("sceneservice:portal-item-wrong-type",`Portal item needs to have type "${U}"`);await this._ensureLoadBeforeSave();const i=I(this.portalItem,"portal-item",!0),o=this.write({},i),s=await C(this.portalItem,o);await Promise.all(i.resources.pendingOperations??[]),await this._validateAgainstJSONSchema(s,i,t);const a=q(this.portalItem,this.url);return a&&(this.portalItem.url=a),this.portalItem.title||(this.portalItem.title=this.title),O(this.portalItem,t,0),await b(this.portalItem,s,this.resourceReferences,i),n(i),this.portalItem}async _validateAgainstJSONSchema(e,t,o){const s=o?.validationOptions;N(t,{errorName:"sceneservice:save"},{ignoreUnsupported:s?.ignoreUnsupported,supplementalUnsupportedErrors:["scenemodification:unsupported"]});const a=s?.enabled,n=g();if(a&&n){const t=(await n()).validate(e,o.portalItemLayerType);if(!t.length)return;const a=`Layer item did not validate:\n${t.join("\n")}`;if(i.getLogger(this).error(`_validateAgainstJSONSchema(): ${a}`),"throw"===s.failPolicy){const e=t.map(e=>new r("sceneservice:schema-validation",e));throw new r("sceneservice-validate:error","Failed to save layer item due to schema validation, see `details.errors`.",{validationErrors:e})}}}};return e([s(h)],E.prototype,"id",void 0),e([s({type:c})],E.prototype,"spatialReference",void 0),e([_("spatialReference",["spatialReference","store.indexCRS","store.geographicCRS"])],E.prototype,"readSpatialReference",null),e([s({type:l})],E.prototype,"fullExtent",void 0),e([_("fullExtent",["fullExtent","store.extent","spatialReference","store.indexCRS","store.geographicCRS"])],E.prototype,"readFullExtent",null),e([s({readOnly:!0,type:p})],E.prototype,"heightModelInfo",void 0),e([s({type:Number,json:{name:"layerDefinition.minScale",write:!0,origins:{service:{read:{source:"minScale"},write:!1}}}})],E.prototype,"minScale",void 0),e([s({type:Number,json:{name:"layerDefinition.maxScale",write:!0,origins:{service:{read:{source:"maxScale"},write:!1}}}})],E.prototype,"maxScale",void 0),e([s({readOnly:!0})],E.prototype,"version",void 0),e([_("version",["store.version"])],E.prototype,"readVersion",null),e([s({type:String,json:{read:{source:"copyrightText"}}})],E.prototype,"copyright",void 0),e([s({type:String,json:{read:!1}})],E.prototype,"sublayerTitleMode",void 0),e([s({type:String})],E.prototype,"title",void 0),e([_("portal-item","title")],E.prototype,"readTitlePortalItem",null),e([_("service","title",["name"])],E.prototype,"readTitleService",null),e([s({type:Number,json:{origins:{service:{read:{source:"id"}},"portal-item":{write:{target:"id",isRequired:!0,ignoreOrigin:!0},read:!1}}}})],E.prototype,"layerId",void 0),e([s(v({separator:"layers"}))],E.prototype,"url",void 0),e([s({readOnly:!0})],E.prototype,"parsedUrl",null),e([s({readOnly:!0})],E.prototype,"store",void 0),e([s({type:String,readOnly:!0,json:{read:{source:"store.rootNode"}}})],E.prototype,"rootNode",void 0),E=e([a("esri.layers.mixins.SceneService")],E),E},L=-1e38;function T(e){if(null!=e.spatialReference)return c.fromJSON(e.spatialReference);const t=e.store,r=t.indexCRS||t.geographicCRS,i=r&&parseInt(r.slice(r.lastIndexOf("/")+1),10);return null!=i?new c(i):null}function A(e,t){if(null==t?.center||null==t.halfSize)throw new r("sceneservice:invalid-node-page","Invalid node page.");if(t.center[0]<L)return;const i=t.halfSize,o=t.center[2],s=Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]);e.zmin=o-s,e.zmax=o+s}function O(e,t,r){e.typeKeywords||(e.typeKeywords=[]);const i=t.getTypeKeywords();for(const o of i)e.typeKeywords.push(o);e.typeKeywords&&(e.typeKeywords=e.typeKeywords.filter((e,t,r)=>r.indexOf(e)===t),1===r&&(e.typeKeywords=e.typeKeywords.filter(e=>"Hosted Service"!==e)))}const U="Scene Service",P={getTypeKeywords:()=>[],portalItemLayerType:"unknown",validationOptions:{enabled:!0,ignoreUnsupported:!1,failPolicy:"throw"}},E={layerId:null};function K(e,t){const r=e.findIndex(({id:e})=>e===t.id);-1===r?e.push(t):e[r]=t}async function C(e,t){const r=await e.fetchData("json")??{};return Array.isArray(r.layers)||(r.layers=await V(e,t)),K(r.layers,t),r}function q(e,t){return t&&M(e.url,t)?e.url:t}function M(e,t){const r=J(e);return!!r&&r===F(t).url}async function V(e,t){const r=await z(e).catch(()=>null);return r?.some(({id:e})=>e===t.id)?r:[t]}async function z(e){const r=J(e.url);if(!r)return null;const i=(await t(r,{query:{f:"json"},responseType:"json"})).data.layers;if(!Array.isArray(i))return null;const o=i.filter(({id:e})=>null!=e).map(({id:e})=>({id:e}));return o.length?o:null}function J(e){if(!e)return null;const t=F(e);if(null!=t.layerId)return null;const r=d(t.url);return null==r||"SceneServer"===r.serverType?t.url:null}function F(e){return m({layer:E,url:e,nonStandardUrlAllowed:!0})}export{R as SceneService,U as sceneServiceItemType,A as updateExtentFromPageObb};
2
+ import{__decorate as e}from"tslib";import t from"../../request.js";import r from"../../core/Error.js";import i from"../../core/Logger.js";import{debounce as o}from"../../core/promiseUtils.js";import{property as s,subclass as a}from"../../core/accessorSupport/decorators.js";import{updateOrigins as n}from"../../core/accessorSupport/originUtils.js";import l from"../../geometry/Extent.js";import p from"../../geometry/HeightModelInfo.js";import c from"../../geometry/SpatialReference.js";import{titleFromUrlAndName as u,parse as d,cleanTitle as y,sanitizeUrlWithLayerId as m}from"../support/arcgisLayerUrl.js";import{id as h}from"../support/commonProperties.js";import{fetchIndexInfo as f}from"../support/I3SIndexInfo.js";import{urlProperty as v,normalizeParsedUrlObject as S}from"../support/multiLayerServiceUtils.js";import{getLoader as g}from"../support/schemaValidatorLoader.js";import w from"../../portal/Portal.js";import x from"../../portal/PortalItem.js";import{createForItemWrite as I}from"../../portal/support/jsonContext.js";import{saveResources as j,updateItemWithResources as b}from"../../webdoc/support/resourceUtils.js";import{evaluateWriteErrors as N}from"../../webdoc/support/saveUtils.js";import{reader as _}from"../../core/accessorSupport/decorators/reader.js";const R=m=>{const R=m;let E=class extends R{constructor(){super(...arguments),this.spatialReference=null,this.fullExtent=null,this.heightModelInfo=null,this.minScale=0,this.maxScale=0,this.version={major:Number.NaN,minor:Number.NaN,versionString:""},this.copyright=null,this.sublayerTitleMode="item-title",this.title=null,this.layerId=null,this.url=null,this.indexInfo=null,this._debouncedSaveOperations=o(async(e,t,r)=>{switch(e){case 0:return this._save(t);case 1:return this._saveAs(r,t)}})}readSpatialReference(e,t){return T(t)}readFullExtent(e,t,r){if(null!=e&&"object"==typeof e){const i=null==e.spatialReference?{...e,spatialReference:T(t)}:e;return l.fromJSON(i,r)}const i=t.store,o=T(t);return null==o||null==i?.extent||!Array.isArray(i.extent)||i.extent.some(e=>e<L)?null:new l({xmin:i.extent[0],ymin:i.extent[1],xmax:i.extent[2],ymax:i.extent[3],spatialReference:o})}parseVersionString(e){const t={major:Number.NaN,minor:Number.NaN,versionString:e},r=e.split(".");return r.length>=2&&(t.major=parseInt(r[0],10),t.minor=parseInt(r[1],10)),t}readVersion(e,t){const r=t.store,i=null!=r.version?r.version.toString():"";return this.parseVersionString(i)}readTitlePortalItem(e){return"item-title"!==this.sublayerTitleMode?void 0:e}readTitleService(e,t){if("item-title"===this.sublayerTitleMode)return this.url?u(this.url,t.name):t.name;let r=t.name;if(!r&&this.url){const e=d(this.url);null!=e&&(r=e.title)}const i=this.portalItem?.title;return"item-title-and-service-name"===this.sublayerTitleMode&&i&&(r=i+" - "+r),y(r)}get parsedUrl(){return S(this,{separator:"layers"})}async _fetchIndexAndUpdateExtent(e,t){this.indexInfo=f(this.parsedUrl?.path??"",this.rootNode,e,this.customParameters,this.apiKey,i.getLogger(this),t),this.indexInfo.catch(()=>{});const{fullExtent:r}=this;null==r||r.hasZ||this._updateExtent(r,await this.indexInfo)}_updateExtent(e,t){if("page"===t?.type){const r=t.rootIndex%t.pageSize,i=t.rootPage?.nodes?.[r];A(e,i?.obb)}else if("node"===t?.type){const r=t.rootNode?.mbs;if(!Array.isArray(r)||4!==r.length||r[0]<L)return;const i=r[2],o=r[3];e.zmin=i-o,e.zmax=i+o}}async _fetchService(e){if(null==this.url)throw new r("sceneservice:url-not-set","Scene service can not be loaded without valid portal item or url");if(null==this.layerId&&/SceneServer\/*$/i.test(this.url)){const t=await this._fetchFirstLayerId(e);null!=t&&(this.layerId=t)}return this._fetchServiceLayer(e)}async _fetchFirstLayerId(e){const r=await t(this.url??"",{query:{f:"json",...this.customParameters,token:this.apiKey},responseType:"json",signal:e});if(r.data&&Array.isArray(r.data.layers)&&r.data.layers.length>0)return r.data.layers[0].id}async _fetchServiceLayer(e){const r=await t(this.parsedUrl?.path??"",{query:{f:"json",...this.customParameters,token:this.apiKey},responseType:"json",signal:e});r.ssl&&this.url&&(this.url=this.url.replace(/^http:/i,"https:"));let i=!1;if(r.data.layerType&&"Voxel"===r.data.layerType&&(i=!0),i)return this._fetchVoxelServiceLayer();const o=r.data;this.read(o,this._getServiceContext()),this.validateLayer(o)}async _fetchVoxelServiceLayer(e){const r=(await t(this.parsedUrl?.path+"/layer",{query:{f:"json",...this.customParameters,token:this.apiKey},responseType:"json",signal:e})).data;this.read(r,this._getServiceContext()),this.validateLayer(r)}_getServiceContext(){return{origin:"service",portalItem:this.portalItem,portal:this.portalItem?.portal,url:this.parsedUrl}}async _ensureLoadBeforeSave(){await this.load(),"beforeSave"in this&&"function"==typeof this.beforeSave&&await this.beforeSave()}validateLayer(e){}async _saveAs(e,t){const i={...P,...t};let o=x.from(e);if(!o)throw new r("sceneservice:portal-item-required","_saveAs() requires a portal item to save to");o.id&&(o=o.clone(),o.id=null);const s=o.portal||w.getDefault();await this._ensureLoadBeforeSave(),o.type=U,o.portal=s;const a=I(o,"portal-item",{withResources:!0}),l={layers:[this.write({},a)]};return await Promise.all(a.resources.pendingOperations??[]),await this._validateAgainstJSONSchema(l,a,i),this.url&&(o.url=this.url),o.title||(o.title=this.title),O(o,i,1),await s.signIn(),await s.user.addItem({item:o,folder:i?.folder,data:l}),await j(this.resourceReferences,a),this.portalItem=o,n(a),a.portalItem=o,o}async _save(e){const t={...P,...e};if(!this.portalItem)throw new r("sceneservice:portal-item-not-set","Portal item to save to has not been set on this SceneService");if(this.portalItem.type!==U)throw new r("sceneservice:portal-item-wrong-type",`Portal item needs to have type "${U}"`);await this._ensureLoadBeforeSave();const i=I(this.portalItem,"portal-item",{withResources:!0}),o=this.write({},i),s=await C(this.portalItem,o);await Promise.all(i.resources.pendingOperations??[]),await this._validateAgainstJSONSchema(s,i,t);const a=q(this.portalItem,this.url);return a&&(this.portalItem.url=a),this.portalItem.title||(this.portalItem.title=this.title),O(this.portalItem,t,0),await b(this.portalItem,s,this.resourceReferences,i),n(i),this.portalItem}async _validateAgainstJSONSchema(e,t,o){const s=o?.validationOptions;N(t,{errorName:"sceneservice:save"},{ignoreUnsupported:s?.ignoreUnsupported,supplementalUnsupportedErrors:["scenemodification:unsupported"]});const a=s?.enabled,n=g();if(a&&n){const t=(await n()).validate(e,o.portalItemLayerType);if(!t.length)return;const a=`Layer item did not validate:\n${t.join("\n")}`;if(i.getLogger(this).error(`_validateAgainstJSONSchema(): ${a}`),"throw"===s.failPolicy){const e=t.map(e=>new r("sceneservice:schema-validation",e));throw new r("sceneservice-validate:error","Failed to save layer item due to schema validation, see `details.errors`.",{validationErrors:e})}}}};return e([s(h)],E.prototype,"id",void 0),e([s({type:c})],E.prototype,"spatialReference",void 0),e([_("spatialReference",["spatialReference","store.indexCRS","store.geographicCRS"])],E.prototype,"readSpatialReference",null),e([s({type:l})],E.prototype,"fullExtent",void 0),e([_("fullExtent",["fullExtent","store.extent","spatialReference","store.indexCRS","store.geographicCRS"])],E.prototype,"readFullExtent",null),e([s({readOnly:!0,type:p})],E.prototype,"heightModelInfo",void 0),e([s({type:Number,json:{name:"layerDefinition.minScale",write:!0,origins:{service:{read:{source:"minScale"},write:!1}}}})],E.prototype,"minScale",void 0),e([s({type:Number,json:{name:"layerDefinition.maxScale",write:!0,origins:{service:{read:{source:"maxScale"},write:!1}}}})],E.prototype,"maxScale",void 0),e([s({readOnly:!0})],E.prototype,"version",void 0),e([_("version",["store.version"])],E.prototype,"readVersion",null),e([s({type:String,json:{read:{source:"copyrightText"}}})],E.prototype,"copyright",void 0),e([s({type:String,json:{read:!1}})],E.prototype,"sublayerTitleMode",void 0),e([s({type:String})],E.prototype,"title",void 0),e([_("portal-item","title")],E.prototype,"readTitlePortalItem",null),e([_("service","title",["name"])],E.prototype,"readTitleService",null),e([s({type:Number,json:{origins:{service:{read:{source:"id"}},"portal-item":{write:{target:"id",isRequired:!0,ignoreOrigin:!0},read:!1}}}})],E.prototype,"layerId",void 0),e([s(v({separator:"layers"}))],E.prototype,"url",void 0),e([s({readOnly:!0})],E.prototype,"parsedUrl",null),e([s({readOnly:!0})],E.prototype,"store",void 0),e([s({type:String,readOnly:!0,json:{read:{source:"store.rootNode"}}})],E.prototype,"rootNode",void 0),E=e([a("esri.layers.mixins.SceneService")],E),E},L=-1e38;function T(e){if(null!=e.spatialReference)return c.fromJSON(e.spatialReference);const t=e.store,r=t.indexCRS||t.geographicCRS,i=r&&parseInt(r.slice(r.lastIndexOf("/")+1),10);return null!=i?new c(i):null}function A(e,t){if(null==t?.center||null==t.halfSize)throw new r("sceneservice:invalid-node-page","Invalid node page.");if(t.center[0]<L)return;const i=t.halfSize,o=t.center[2],s=Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]);e.zmin=o-s,e.zmax=o+s}function O(e,t,r){e.typeKeywords||(e.typeKeywords=[]);const i=t.getTypeKeywords();for(const o of i)e.typeKeywords.push(o);e.typeKeywords&&(e.typeKeywords=e.typeKeywords.filter((e,t,r)=>r.indexOf(e)===t),1===r&&(e.typeKeywords=e.typeKeywords.filter(e=>"Hosted Service"!==e)))}const U="Scene Service",P={getTypeKeywords:()=>[],portalItemLayerType:"unknown",validationOptions:{enabled:!0,ignoreUnsupported:!1,failPolicy:"throw"}},E={layerId:null};function K(e,t){const r=e.findIndex(({id:e})=>e===t.id);-1===r?e.push(t):e[r]=t}async function C(e,t){const r=await e.fetchData("json")??{};return Array.isArray(r.layers)||(r.layers=await V(e,t)),K(r.layers,t),r}function q(e,t){return t&&M(e.url,t)?e.url:t}function M(e,t){const r=J(e);return!!r&&r===F(t).url}async function V(e,t){const r=await z(e).catch(()=>null);return r?.some(({id:e})=>e===t.id)?r:[t]}async function z(e){const r=J(e.url);if(!r)return null;const i=(await t(r,{query:{f:"json"},responseType:"json"})).data.layers;if(!Array.isArray(i))return null;const o=i.filter(({id:e})=>null!=e).map(({id:e})=>({id:e}));return o.length?o:null}function J(e){if(!e)return null;const t=F(e);if(null!=t.layerId)return null;const r=d(t.url);return null==r||"SceneServer"===r.serverType?t.url:null}function F(e){return m({layer:E,url:e,nonStandardUrlAllowed:!0})}export{R as SceneService,U as sceneServiceItemType,A as updateExtentFromPageObb};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import t from"../../../request.js";import i from"../../../core/Error.js";import{JSONSupport as o}from"../../../core/JSONSupport.js";import r from"../../../core/Logger.js";import{debounce as n,onAbort as s}from"../../../core/promiseUtils.js";import{QueueProcessor as l}from"../../../core/QueueProcessor.js";import{property as a,subclass as c}from"../../../core/accessorSupport/decorators.js";import{ensureClass as f}from"../../../core/accessorSupport/ensureType.js";import u from"../../../geometry/Extent.js";import m from"../../../geometry/Point.js";import h from"../../../geometry/SpatialReference.js";import{isFunctionRaster as p,getPixelSpaceCoverage as d}from"./datasetUtils.js";import{isMultiSliceOrRangeDefinition as x,getSliceIndex as y,createSlices as g,getSliceIds as I}from"./multidimensionalUtils.js";import{clearRegisteredIds as R,getRasterId as w,getBlock as S,putBlock as k,deleteBlock as b,decreaseRefCount as T}from"./RawBlockCache.js";import{convertNoDataToMask as v}from"../formats/pixelRangeUtils.js";import{decode as P}from"../formats/RasterCodec.js";import{mosaic as B,approximateTransform as _,getLocalArithmeticNorthRotations as M,compositeBands as W}from"../functions/pixelUtils.js";import{getWorldWidth as C,load as H,projectPoint as z,snapPyramid as L,shiftExtent as j,getWorldWrapCount as E,projectExtent as D,getProjectionOffsetGrid as O,getRasterDatasetAlignmentInfo as A,projectResolution as q}from"../functions/rasterProjectionHelper.js";import{convertToLocalDirections as F,uvComponentToVector as G}from"../functions/vectorFieldUtils.js";import{sanitizeUrl as J}from"../../support/arcgisLayerUrl.js";import{url as N}from"../../support/commonProperties.js";import V from"../../support/DimensionalDefinition.js";import U from"../../support/LOD.js";import Q from"../../support/RasterStorageInfo.js";import $ from"../../support/TileInfo.js";const X=8,K=256;let Y=0,Z=class extends o{constructor(){super(...arguments),this._tileFetchQueue=new l({concurrency:32,process:(e,t)=>this.fetchRawTile(e.pyramidLevel,e.row,e.col,{...e.options,signal:t})}),this.datasetName=null,this.datasetFormat=null,this.hasUniqueSourceStorageInfo=!0,this.rasterInfo=null,this.ioConfig={sampling:"closest"},this.rawBlockRegistryIds=[],this.refresh=n(async e=>{await this._openPromise;const t=await this._refresh(e);return t.dataChanged&&R(this.rasterId,this.rawBlockRegistryIds),t})}normalizeCtorArgs(e){return e?.ioConfig&&(e={...e,ioConfig:{resolution:null,bandIds:null,sampling:"closest",tileInfo:$.create(),...e.ioConfig}}),e}get _isGlobalWrappableSource(){const{rasterInfo:e}=this,t=C(e.spatialReference);return null!=t&&e.extent.width>=t/2}get _hasNoneOrGCSShiftTransform(){const{transform:e}=this.rasterInfo;return null==e||"gcs-shift"===e.type}set rasterJobHandler(e){this._set("rasterJobHandler",e),p(this)&&this.primaryRasters?.rasters?.forEach(t=>t.rasterJobHandler=e)}get rasterId(){return this.url||"rasterId-"+Y++}set url(e){this._set("url",J(e,r.getLogger(this)))}async open(e){return this._openPromise??=H().then(()=>this._open(e)),this._openPromise}async fetchTile(e,t,o,r={}){const n=r.tileInfo||this.rasterInfo.storageInfo.tileInfo,s=this.getTileExtentFromTileInfo(e,t,o,n);if(!s)throw new i("imagery-tile:out-of-bounds","Level for fetch tile out of range");return r={noClip:!0,...r},this.fetchPixels(s,n.size[0],n.size[1],r)}async identify(e,t={}){e=f(m,e).clone().normalize();const{multidimensionalDefinition:i,timeExtent:o}=t,{rasterInfo:r}=this,{hasMultidimensionalTranspose:n,multidimensionalInfo:s}=r;let{transposedVariableName:l}=t;const a=null!=s&&n&&(null!=o||x(i));if(a&&!l){l=null!=i&&i.length>0?i[0].variableName??void 0:s.variables[0].name,t={...t,transposedVariableName:l}}t=this._getRequestOptionsWithSliceId(t);const{spatialReference:c,extent:h}=r,{datumTransformation:d}=t;let y=z(e,c,d);if(!h.intersects(y))return{location:y,value:null};if(null!=r.transform){const e=r.transform.inverseTransform(y);if(!r.nativeExtent.intersects(e))return{location:e,value:null};y=e}let g=0;const I=null!=l&&null!=s&&r.hasMultidimensionalTranspose;if(p(this)){const e=this.primaryRasters.rasters[0];if(I)return e.identify(y,t);const{pixelSize:o}=r,n=3,s=o.x*n/2,l=o.y*n/2,a=new u({xmin:y.x-s,xmax:y.x+s,ymin:y.y-l,ymax:y.y+l,spatialReference:c}),f={interpolation:"nearest",multidimensionalDefinition:i,sliceId:t.sliceId,bandIds:t.bandIds},{pixelBlock:m}=await e.fetchPixels(a,n,n,f),{pixelBlock:h}=await this.fetchPixels(a,n,n,f);if(null==m)return{location:y,value:null};const p=Math.floor(n*n*.5),d=!m.mask||m.mask[p]?m.pixels.map(e=>e[p]):null;let x;return null!=h&&(x=!h.mask||h.mask[p]?h.pixels.map(e=>e[p]):void 0),{location:y,value:d,processedValue:x,pyramidLevel:0}}if(!I)if(t.srcResolution){g=L(t.srcResolution,r,this.ioConfig.sampling).pyramidLevel}else if(g=await this.computeBestPyramidLevelForLocation(e,t),null==g)return{location:y,value:null};const R=this.identifyPixelLocation(y,g,null,I);if(null===R)return{location:y,value:null};const{row:w,col:S,rowOffset:k,colOffset:b,blockWidth:T}=R,v=await this._fetchRawTile(g,w,S,t);if(!v?.pixels?.length)return{location:y,value:null};const P=k*T+b;return this._processIdentifyResult(v,{srcLocation:y,position:P,pyramidLevel:g,useTransposedTile:!!I,requestSomeSlices:a,identifyOptions:t})}async fetchPixels(e,t,i,o={}){e=j(e),o=this._getRequestOptionsWithSliceId(o);const{_hasNoneOrGCSShiftTransform:r}=this;if(o.requestRawData&&r)return this._fetchPixels(e,t,i,o);const n=C(e.spatialReference),s=E(e);if(null==n||0===s||1===s&&this._isGlobalWrappableSource&&r)return this._fetchPixels(e,t,i,o);if(s>=3)return{extent:e,pixelBlock:null};const l=[],{xmin:a,xmax:c}=e,f=Math.round(n/(c-a)*t),m=f-Math.round((n/2-a)/(c-a)*t);let h=0;const p=[];for(let g=0;g<=s;g++){const r=new u({xmin:0===g?a:-n/2,xmax:g===s?c-n*g:n/2,ymin:e.ymin,ymax:e.ymax,spatialReference:e.spatialReference}),d=0===g?f-m:g===s?t-h:f;h+=d,p.push(d);const x=o.disableWrapAround&&g>0?null:this._fetchPixels(r,d,i,o);l.push(x)}const d=(await Promise.all(l)).map(e=>e?.pixelBlock);let x=null;const y={width:t,height:i};if(this.rasterJobHandler){x=(await this.rasterJobHandler.mosaicAndTransform({srcPixelBlocks:d,srcMosaicSize:y,destDimension:null,coefs:null,sampleSpacing:null,interpolation:"nearest",alignmentInfo:null,blockWidths:p},o)).pixelBlock}else x=B(d,y,{blockWidths:p});return{extent:e,srcExtent:D(e,this.rasterInfo.spatialReference,o.datumTransformation),pixelBlock:x}}async fetchRawPixels(e,t,i,o={}){t={x:Math.floor(t.x),y:Math.floor(t.y)};const r=await this._fetchRawTiles(e,t,i,o),{nativeExtent:n,nativePixelSize:s,storageInfo:l}=this.rasterInfo,a=2**e,c=s.x*a,f=s.y*a,m=new u({xmin:n.xmin+c*t.x,xmax:n.xmin+c*(t.x+i.width-1),ymin:n.ymax-f*(t.y+i.height-1),ymax:n.ymax-f*t.y,spatialReference:n.spatialReference});if(!r)return{extent:m,srcExtent:m,pixelBlock:null};const{pixelBlocks:h,mosaicSize:p}=r;if(1===h.length&&null!=h[0]&&h[0].width===i.width&&h[0].height===i.height)return{extent:m,srcExtent:m,pixelBlock:r.pixelBlocks[0]};const d=e>0?l.pyramidBlockWidth:l.blockWidth,x=e>0?l.pyramidBlockHeight:l.blockHeight,y={x:t.x%d,y:t.y%x};let g;if(this.rasterJobHandler){g=(await this.rasterJobHandler.mosaicAndTransform({srcPixelBlocks:h,srcMosaicSize:p,destDimension:i,clipOffset:y,clipSize:i,coefs:null,sampleSpacing:null,interpolation:o.interpolation,alignmentInfo:null,blockWidths:null},o)).pixelBlock}else g=B(h,p,{clipOffset:y,clipSize:i});return{extent:m,srcExtent:m,pixelBlock:g}}fetchRawTile(e,t,o,r){throw new i("BaseRaster:read-not-implemented","fetchRawTile() is not implemented")}computeExtent(e){return D(this.rasterInfo.extent,e)}decodePixelBlock(e,t){return this.rasterJobHandler?this.rasterJobHandler.decode({data:e,options:t}):P(e,t)}async request(e,i,o=0){const{customFetchParameters:r}=this.ioConfig,{range:n,query:s,headers:l}=i;o=o??i.retryCount??this.ioConfig.retryCount;const a=n?{Range:`bytes=${n.from}-${n.to}`}:null;try{return await t(e,{...i,query:{...s,...r},headers:{...l,...a}})}catch(c){if(o>0)return o--,this.request(e,i,o);throw c}}getSliceIndex(e){const{multidimensionalInfo:t}=this.rasterInfo;return null==t||null==e||0===e.length?null:y(e,t)}getTileExtentFromTileInfo(e,t,i,o){const r=o.lodAt(e);return r?this.getTileExtent({x:r.resolution,y:r.resolution},t,i,o.origin,o.spatialReference,o.size):null}updateTileInfo(){const{storageInfo:e,spatialReference:t,extent:i,pixelSize:o}=this.rasterInfo,{pyramidResolutions:r}=e;if(!e.tileInfo){const n=[],s=e.maximumPyramidLevel||0;let l=(o.x+o.y)/2,a=1/.0254*96*l;for(let e=0;e<=s&&(n.unshift(new U({level:s-e,resolution:l,scale:a})),e!==s);e++)if(r){const t=(r[e].x+r[e].y)/2;a*=t/l,l=t}else l*=2,a*=2;const c=new m({x:i.xmin,y:i.ymax,spatialReference:t});e.tileInfo=new $({origin:c,size:[e.blockWidth,e.blockHeight],spatialReference:t,lods:n}),e.isVirtualTileInfo=!0}}createRemoteDatasetStorageInfo(e,t=512,i=512,o){const{width:r,height:n,nativeExtent:s,pixelSize:l,spatialReference:a}=e,c=new m({x:s.xmin,y:s.ymax,spatialReference:a});null==o&&(o=Math.max(0,Math.round(Math.log(Math.max(r,n))/Math.LN2-8)));const f=this.computeBlockBoundary(s,512,512,{x:s.xmin,y:s.ymax},[l],o);e.storageInfo=new Q({blockWidth:t,blockHeight:i,pyramidBlockWidth:t,pyramidBlockHeight:i,origin:c,firstPyramidLevel:1,maximumPyramidLevel:o,blockBoundary:f})}async computeBestPyramidLevelForLocation(e,t={}){return 0}computeBlockBoundary(e,t,i,o,r,n=0,s=2){if(1===r.length&&n>0){r=[...r];let{x:e,y:t}=r[0];for(let i=0;i<n;i++)e*=s,t*=s,r.push({x:e,y:t})}const l=[],{x:a,y:c}=o;for(let f=0;f<r.length;f++){const{x:o,y:n}=r[f];l.push({minCol:Math.floor((e.xmin-a+.1*o)/t/o),maxCol:Math.floor((e.xmax-a-.1*o)/t/o),minRow:Math.floor((c-e.ymax+.1*n)/i/n),maxRow:Math.floor((c-e.ymin-.1*n)/i/n)})}return l}getPyramidPixelSize(e){const{nativePixelSize:t}=this.rasterInfo,{pyramidResolutions:i,pyramidScalingFactor:o}=this.rasterInfo.storageInfo;if(0===e)return t;if(null!=i&&i.length)return i[e-1];const r=o**e;return{x:t.x*r,y:t.y*r}}identifyPixelLocation(e,t,i,o){const{spatialReference:r,nativeExtent:n,storageInfo:s}=this.rasterInfo,{maximumPyramidLevel:l,origin:a,transposeInfo:c}=s,f=o&&null!=c?c.tileSize[0]:s.blockWidth,u=o&&null!=c?c.tileSize[1]:s.blockHeight,m=z(e,r,i);if(!n.intersects(m))return null;if(t<0||t>l)return null;const h=this.getPyramidPixelSize(t),{x:p,y:d}=h,x=(a.y-m.y)/d/u,y=(m.x-a.x)/p/f,g=Math.min(u-1,Math.floor((x-Math.floor(x))*u)),I=Math.min(f-1,Math.floor((y-Math.floor(y))*f));return{pyramidLevel:t,row:Math.floor(x),col:Math.floor(y),rowOffset:g,colOffset:I,blockWidth:f,srcLocation:m}}getTileExtent(e,t,i,o,r,n){const[s,l]=n,a=o.x+i*s*e.x,c=a+s*e.x,f=o.y-t*l*e.y,m=f-l*e.y;return new u({xmin:a,xmax:c,ymin:m,ymax:f,spatialReference:r})}getBlockWidthHeight(e){return{blockWidth:e>0?this.rasterInfo.storageInfo.pyramidBlockWidth:this.rasterInfo.storageInfo.blockWidth,blockHeight:e>0?this.rasterInfo.storageInfo.pyramidBlockHeight:this.rasterInfo.storageInfo.blockHeight}}isBlockOutside(e,t,i){const o=this.rasterInfo.storageInfo.blockBoundary[e];return!o||o.maxRow<t||o.maxCol<i||o.minRow>t||o.minCol>i}updateImageSpaceRasterInfo(e){const{pixelSize:t}=e,{width:i,height:o}=e,r=h.WebMercator;e.spatialReference=r,e.extent=e.nativeExtent=new u({xmin:-.5,ymax:.5,xmax:i-.5,ymin:.5-o,spatialReference:r}),e.isPseudoSpatialReference=!0,e.transform=null,e.pixelSize=new m({x:1,y:1,spatialReference:r});const{extent:n,storageInfo:s}=e;if(s){s.origin=new m({x:n.xmin,y:n.ymax,spatialReference:r});const{pyramidResolutions:i,tileInfo:o}=s;if(i&&i.forEach(e=>{e.x/=t.x,e.y/=t.y}),o){o.origin=s.origin;const t=(e.nativePixelSize.x+e.nativePixelSize.y)/2;o.lods.forEach((e,i)=>{e.resolution=t*2**i,e.scale=96*e.resolution/.0254})}}}async _refresh(e){return{dataChanged:!0}}async _fetchPixels(e,t,i,o={}){let r=E(e);if(r>=2)return{extent:e,pixelBlock:null};const n=this._getSourceDataInfo(e,t,i,o),{pyramidLevel:s,srcResolution:l,srcWidth:a,srcHeight:c,ul:f}=n;let{srcExtent:u}=n;if(0===a||0===c)return{extent:e,srcExtent:u,pixelBlock:null};const{rasterInfo:h}=this,p=h.transform,d="gcs-shift"===p?.type,x=null!=C(e.spatialReference);!d&&x||(r=E(u,d));const y=await this._fetchRawTiles(s,f,{width:a,height:c,wrapCount:r},o);if(!y)return{extent:e,srcExtent:u,pixelBlock:null};u=y.extent;const g=h.storageInfo,I=s>0?g.pyramidBlockWidth:g.blockWidth,R=s>0?g.pyramidBlockHeight:g.blockHeight;let{x:w,y:S}=h.pixelSize;if(s>0){const{pyramidResolutions:e,pyramidScalingFactor:t}=g;if(null!=e&&e[s-1])({x:w,y:S}=e[s-1]);else{const e=t**s;w*=e,S*=e}}const k=h.spatialReference,b=new m({x:w,y:S,spatialReference:k}),T=I===a&&R===c&&f.x%I===0&&f.y%R===0,v=new m({x:(e.xmax-e.xmin)/t,y:(e.ymax-e.ymin)/i,spatialReference:e.spatialReference}),P=!e.spatialReference.equals(k),W=k.isGeographic?1e-9:1e-4,{datumTransformation:z}=o;if(!P&&T&&1===y.pixelBlocks.length&&I===t&&R===i&&ee(l,v,W))return{extent:e,srcExtent:u,srcTilePixelSize:b,pixelBlock:y.pixelBlocks[0]};const L=x&&null!=C(u.spatialReference)&&this._hasNoneOrGCSShiftTransform,j=o.requestProjectedLocalDirections&&this.rasterInfo.dataType.startsWith("vector");j&&!this.rasterJobHandler&&await H();const D=this.rasterJobHandler?await this.rasterJobHandler.getProjectionOffsetGrid({projectedExtent:e,srcBufferExtent:u,pixelSize:v.toJSON(),datumTransformation:z,rasterTransform:p,hasWrapAround:r>0||L,isAdaptive:!1!==this.ioConfig.optimizeProjectionAccuracy,includeGCSGrid:j},o):O({projectedExtent:e,srcBufferExtent:u,pixelSize:v,datumTransformation:z,rasterTransform:p,hasWrapAround:r>0||L,isAdaptive:!1,includeGCSGrid:j});let A;const q=!o.requestRawData,G={rows:D.spacing[0],cols:D.spacing[1]},J=this._hasNoneOrGCSShiftTransform?this._getRasterTileAlignmentInfo(s,u.xmin):void 0,{pixelBlocks:N,mosaicSize:V,isPartiallyFilled:U}=y;let Q=null;if(this.rasterJobHandler){const e=await this.rasterJobHandler.mosaicAndTransform({srcPixelBlocks:N,srcMosaicSize:V,destDimension:q?{width:t,height:i}:null,coefs:q?D.coefficients:null,sampleSpacing:q?G:null,projectDirections:j,gcsGrid:j?D.gcsGrid:null,isUV:"vector-uv"===this.rasterInfo.dataType,interpolation:o.interpolation,alignmentInfo:J,blockWidths:null},o);({pixelBlock:A,localNorthDirections:Q}=e)}else{const e=B(N,V,{alignmentInfo:J});A=q?_(e,{width:t,height:i},D.coefficients,G,o.interpolation):e,j&&D.gcsGrid&&(Q=M({width:t,height:i},D.gcsGrid),A=F(A,this.rasterInfo.dataType,Q))}return o.requestRawData||j?{extent:e,srcExtent:u,srcTilePixelSize:b,pixelBlock:A,transformGrid:D,localNorthDirections:Q,isPartiallyFilled:U}:{extent:e,srcExtent:e,srcTilePixelSize:b,pixelBlock:A}}async _fetchRawTiles(e,t,i,o){const{origin:r,blockBoundary:n}=this.rasterInfo.storageInfo,{blockWidth:s,blockHeight:l}=this.getBlockWidthHeight(e);let{x:a,y:c}=t,{width:f,height:m,wrapCount:h}=i;const p=this._getRasterTileAlignmentInfo(e,0);o.buffer&&(a-=o.buffer.cols,c-=o.buffer.rows,f+=2*o.buffer.cols,m+=2*o.buffer.rows);let d=0,x=0,y=0;if(h&&null!=p){({worldColumnCountFromOrigin:x,originColumnOffset:y,rightPadding:d}=p);x*p.blockWidth-d>=a+f&&(d=0)}const g=Math.floor(a/s),I=Math.floor(c/l),R=Math.floor((a+f+d-1)/s),w=Math.floor((c+m+d-1)/l),S=n[e];if(!S)return null;const{minRow:k,minCol:b,maxCol:T,maxRow:v}=S;if(0===h&&(w<k||R<b||I>v||g>T))return null;const P=new Array;let B=!1;const _=null==this.ioConfig.allowPartialFill?o.allowPartialFill:this.ioConfig.allowPartialFill;for(let u=I;u<=w;u++)for(let t=g;t<=R;t++){let i=t;if(!o.disableWrapAround&&h&&null!=p&&x<=t&&(i=t-x-y),u>=k&&i>=b&&v>=u&&T>=i){const t=this._fetchRawTile(e,u,i,o);_?P.push(new Promise(e=>{t.then(t=>e(t)).catch(()=>{B=!0,e(null)})})):P.push(t)}else P.push(Promise.resolve(null))}if(0===P.length)return null;const M=await Promise.all(P),W={height:(w-I+1)*l,width:(R-g+1)*s},{spatialReference:C}=this.rasterInfo,H=this.getPyramidPixelSize(e),{x:z,y:L}=H;return{extent:new u({xmin:r.x+g*s*z,xmax:r.x+(R+1)*s*z,ymin:r.y-(w+1)*l*L,ymax:r.y-I*l*L,spatialReference:C}),pixelBlocks:M,mosaicSize:W,isPartiallyFilled:B}}_fetchRawTile(e,t,i,o){const{storageInfo:r}=this.rasterInfo,n=null!=r.transposeInfo&&!!o.transposedVariableName;if(!n){const o=r.blockBoundary[e];if(!o)return Promise.resolve(null);const{minRow:n,minCol:s,maxCol:l,maxRow:a}=o;if(t<n||i<s||t>a||i>l)return Promise.resolve(null)}const l=n?o.transposeVariableName:o.sliceId,a=r.isBsqTile?o.bandIds:null,c=w(this.rasterId,l,a),f=`${e}/${t}/${i}`;let u=S(c,o.registryId,f);if(null==u){const n=new AbortController,s=o.bandIds?.slice();if(s?.length&&r.isBsqTile){const r=new Set(s),l=[],a=Array.from(r);for(const s of a)l.push(this._tileFetchQueue.push({pyramidLevel:e,row:t,col:i,options:{...o,bandIds:[s]}},{signal:n.signal}));u=Promise.all(l).then(e=>{if(e.some(e=>null==e))return null;if(a.length!==s.length){const t=[];for(const i of s){let o=e[a.indexOf(i)];t.includes(o)&&(o=o.clone()),t.push(o)}e=t}return this.rasterJobHandler?this.rasterJobHandler.compositeBands({pixelBlocks:e},{signal:n.signal,transferPixelsToWorker:!0}):W(e)})}else u=this._tileFetchQueue.push({pyramidLevel:e,row:t,col:i,options:o},{signal:n.signal});k(c,o.registryId,f,u,n),u.catch(()=>b(c,o.registryId,f))}return o.signal&&s(o,()=>{T(c,o.registryId,f)}),u}_computeMagDirValues(e){const{bandCount:t,dataType:i}=this.rasterInfo;if(!(2===t&&"vector-magdir"===i||"vector-uv"===i)||2!==e?.length||!e[0]?.length)return null;const o=e[0].length;if("vector-magdir"===i){const t=e[1].map(e=>(e+360)%360);return[e[0],t]}const[r,n]=e,s=[],l=[];for(let a=0;a<o;a++){const[e,t]=G([r[a],n[a]]);s.push(e),l.push(t)}return[s,l]}_getRasterTileAlignmentInfo(e,t){return null==this._rasterTileAlignmentInfo&&(this._rasterTileAlignmentInfo=A(this.rasterInfo)),null==this._rasterTileAlignmentInfo.pyramidsInfo?null:{startX:t,halfWorldWidth:this._rasterTileAlignmentInfo.halfWorldWidth,hasGCSSShiftTransform:this._rasterTileAlignmentInfo.hasGCSSShiftTransform,...this._rasterTileAlignmentInfo.pyramidsInfo[e]}}_getSourceDataInfo(e,t,i,o={}){const r={datumTransformation:o.datumTransformation,pyramidLevel:0,pyramidResolution:null,srcExtent:null,srcHeight:0,srcResolution:null,srcWidth:0,ul:{x:0,y:0}};o.srcResolution&&(r.srcResolution=o.srcResolution,this._updateSourceDataInfo(e,r));const n=this.rasterInfo.storageInfo.maximumPyramidLevel||0,{srcWidth:s,srcHeight:l,pyramidLevel:a}=r,c=s/t,f=l/i,u=a<n&&c*f>=16,h=a===n&&this._requireTooManySrcTiles(s,l,t,i);if(u||h||(0===s||0===l)){const s=new m({x:(e.xmax-e.xmin)/t,y:(e.ymax-e.ymin)/i,spatialReference:e.spatialReference});let l=q(s,this.rasterInfo.spatialReference,e,r.datumTransformation);const h=!l||o.srcResolution&&l.x+l.y<o.srcResolution.x+o.srcResolution.y;if(u&&o.srcResolution&&h){const e=Math.round(Math.log(Math.max(c,f))/Math.LN2)-1;if(n-a+3>=e){const t=2**e;l={x:o.srcResolution.x*t,y:o.srcResolution.y*t}}}l&&(r.srcResolution=l,this._updateSourceDataInfo(e,r))}return this._requireTooManySrcTiles(r.srcWidth,r.srcHeight,t,i)&&(r.srcWidth=0,r.srcHeight=0),r}_requireTooManySrcTiles(e,t,i,o){const{tileInfo:r}=this.rasterInfo.storageInfo,n=Math.ceil(e/r.size[0])*Math.ceil(t/r.size[1]),s=e/i,l=t/o,a=Math.max(1,(i+o)/1024);return n>=K*a||s>X||l>X}_updateSourceDataInfo(e,t){t.srcWidth=0,t.srcHeight=0;const{rasterInfo:i}=this,o=i.spatialReference,{srcResolution:r,datumTransformation:n}=t,{pyramidLevel:s,pyramidResolution:l,excessiveReading:a}=L(r,i,this.ioConfig.sampling);if(a)return;let c=t.srcExtent||D(e,o,n);if(null==c)return;const f=i.transform;f&&(c=f.inverseTransform(c)),t.srcExtent=c;const{origin:u}=i.storageInfo,{width:m,height:h,ul:p}=d(c,u,l,s);t.pyramidLevel=s,t.pyramidResolution=l,t.srcWidth=m,t.srcHeight=h,t.ul=p}_getRequestOptionsWithSliceId(e){return null!=this.rasterInfo.multidimensionalInfo&&null==e.sliceId&&(e={...e,sliceId:this.getSliceIndex(e.multidimensionalDefinition)}),e}_processIdentifyResult(e,t){const{srcLocation:i,position:o,pyramidLevel:r,useTransposedTile:n}=t,s=e.pixels[0].length/e.width/e.height;if(!(!e.mask||e.mask[o]))return{location:i,value:null};const{multidimensionalInfo:l}=this.rasterInfo;if(null==l||!n){const t=e.pixels.map(e=>e[o]),n={location:i,value:t,pyramidLevel:r},s=this._computeMagDirValues(t.map(e=>[e]));return s?.length&&(n.magdirValue=s.map(e=>e[0])),n}let a=e.pixels.map(e=>e.slice(o*s,o*s+s)),c=this._computeMagDirValues(a);const{requestSomeSlices:f,identifyOptions:u}=t;let m=g(l,u.transposedVariableName);if(f){const e=I(m,u.multidimensionalDefinition,u.timeExtent);a=a.map(t=>e.map(e=>t[e])),c=c?.map(t=>e.map(e=>t[e])),m=e.map(e=>m[e])}const h=e.noDataValues||this.rasterInfo.noDataValue,p={pixels:a,pixelType:e.pixelType};let d;null!=h&&(v(p,h),d=p.mask);return{location:i,value:null,dataSeries:m.map((e,t)=>{const i={value:0===d?.[t]?null:a.map(e=>e[t]),multidimensionalDefinition:e.multidimensionalDefinition.map(e=>new V({...e,isSlice:!0}))};return c?.length&&(i.magdirValue=[c[0][t],c[1][t]]),i}),pyramidLevel:r}}};function ee(e,t,i){return Math.abs(e.x-t.x)<i&&Math.abs(e.y-t.y)<i}e([a()],Z.prototype,"_rasterTileAlignmentInfo",void 0),e([a()],Z.prototype,"_tileFetchQueue",void 0),e([a({readOnly:!0})],Z.prototype,"_isGlobalWrappableSource",null),e([a({readOnly:!0})],Z.prototype,"_hasNoneOrGCSShiftTransform",null),e([a()],Z.prototype,"_openPromise",void 0),e([a()],Z.prototype,"rasterJobHandler",null),e([a({readOnly:!0})],Z.prototype,"rasterId",null),e([a(N)],Z.prototype,"url",null),e([a({type:String,json:{write:!0}})],Z.prototype,"datasetName",void 0),e([a({type:String,json:{write:!0}})],Z.prototype,"datasetFormat",void 0),e([a()],Z.prototype,"hasUniqueSourceStorageInfo",void 0),e([a()],Z.prototype,"rasterInfo",void 0),e([a()],Z.prototype,"ioConfig",void 0),e([a()],Z.prototype,"sourceJSON",void 0),e([a()],Z.prototype,"rawBlockRegistryIds",void 0),Z=e([c("esri.layers.raster.datasets.BaseRaster")],Z);export{Z as default};
2
+ import{__decorate as e}from"tslib";import t from"../../../request.js";import i from"../../../core/Error.js";import{JSONSupport as r}from"../../../core/JSONSupport.js";import o from"../../../core/Logger.js";import{debounce as n,onAbort as s}from"../../../core/promiseUtils.js";import{QueueProcessor as l}from"../../../core/QueueProcessor.js";import{property as a,subclass as c}from"../../../core/accessorSupport/decorators.js";import{ensureClass as f}from"../../../core/accessorSupport/ensureType.js";import u from"../../../geometry/Extent.js";import m from"../../../geometry/Point.js";import h from"../../../geometry/SpatialReference.js";import{isFunctionRaster as p,getPixelSpaceCoverage as d}from"./datasetUtils.js";import{isMultiSliceOrRangeDefinition as x,getSliceIndex as y,createSlices as g,getSliceIds as I}from"./multidimensionalUtils.js";import{clearRegisteredIds as w,getRasterId as R,getBlock as S,putBlock as k,deleteBlock as b,decreaseRefCount as T}from"./RawBlockCache.js";import{convertNoDataToMask as v}from"../formats/pixelRangeUtils.js";import{decode as P}from"../formats/RasterCodec.js";import{convertPixelSize as B}from"../functions/clipUtils.js";import{mosaic as _,approximateTransform as M,getLocalArithmeticNorthRotations as W,compositeBands as C}from"../functions/pixelUtils.js";import{getWorldWidth as H,load as z,projectPoint as L,snapPyramid as j,shiftExtent as E,getWorldWrapCount as D,projectExtent as O,getProjectionOffsetGrid as A,getRasterDatasetAlignmentInfo as q,projectResolution as F}from"../functions/rasterProjectionHelper.js";import{convertToLocalDirections as G,uvComponentToVector as J}from"../functions/vectorFieldUtils.js";import{sanitizeUrl as N}from"../../support/arcgisLayerUrl.js";import{url as V}from"../../support/commonProperties.js";import U from"../../support/DimensionalDefinition.js";import Q from"../../support/LOD.js";import $ from"../../support/RasterStorageInfo.js";import X from"../../support/TileInfo.js";const K=8,Y=256;let Z=0,ee=class extends r{constructor(){super(...arguments),this._tileFetchQueue=new l({concurrency:32,process:(e,t)=>this.fetchRawTile(e.pyramidLevel,e.row,e.col,{...e.options,signal:t})}),this.datasetName=null,this.datasetFormat=null,this.hasUniqueSourceStorageInfo=!0,this.rasterInfo=null,this.ioConfig={sampling:"closest"},this.rawBlockRegistryIds=[],this.refresh=n(async e=>{await this._openPromise;const t=await this._refresh(e);return t.dataChanged&&w(this.rasterId,this.rawBlockRegistryIds),t})}normalizeCtorArgs(e){return e?.ioConfig&&(e={...e,ioConfig:{resolution:null,bandIds:null,sampling:"closest",tileInfo:X.create(),...e.ioConfig}}),e}get _isGlobalWrappableSource(){const{rasterInfo:e}=this,t=H(e.spatialReference);return null!=t&&e.extent.width>=t/2}get _hasNoneOrGCSShiftTransform(){const{transform:e}=this.rasterInfo;return null==e||"gcs-shift"===e.type}set rasterJobHandler(e){this._set("rasterJobHandler",e),p(this)&&this.primaryRasters?.rasters?.forEach(t=>t.rasterJobHandler=e)}get rasterId(){return this.url||"rasterId-"+Z++}set url(e){this._set("url",N(e,o.getLogger(this)))}async open(e){return this._openPromise??=z().then(()=>this._open(e)),this._openPromise}async fetchTile(e,t,r,o={}){const n=o.tileInfo||this.rasterInfo.storageInfo.tileInfo,s=this.getTileExtentFromTileInfo(e,t,r,n);if(!s)throw new i("imagery-tile:out-of-bounds","Level for fetch tile out of range");return o={noClip:!0,...o},this.fetchPixels(s,n.size[0],n.size[1],o)}async identify(e,t={}){e=f(m,e).clone().normalize();const{multidimensionalDefinition:i,timeExtent:r}=t,{rasterInfo:o}=this,{hasMultidimensionalTranspose:n,multidimensionalInfo:s}=o;let{transposedVariableName:l}=t;const a=null!=s&&n&&(null!=r||x(i));if(a&&!l){l=null!=i&&i.length>0?i[0].variableName??void 0:s.variables[0].name,t={...t,transposedVariableName:l}}t=this._getRequestOptionsWithSliceId(t);const{spatialReference:c,extent:h}=o,{datumTransformation:d}=t;let y=L(e,c,d);if(!h.intersects(y))return{location:y,value:null};if(null!=o.transform){const e=o.transform.inverseTransform(y);if(!o.nativeExtent.intersects(e))return{location:e,value:null};y=e}const g=null!=l&&null!=s&&o.hasMultidimensionalTranspose;if(p(this)){const e=this.primaryRasters.rasters[0];if(g)return e.identify(y,t);const{pixelSize:r}=o,n=3,s=r.x*n/2,l=r.y*n/2,a=new u({xmin:y.x-s,xmax:y.x+s,ymin:y.y-l,ymax:y.y+l,spatialReference:c}),f={interpolation:"nearest",multidimensionalDefinition:i,sliceId:t.sliceId,bandIds:t.bandIds},{pixelBlock:m}=await e.fetchPixels(a,n,n,f),{pixelBlock:h}=await this.fetchPixels(a,n,n,f);if(null==m)return{location:y,value:null};const p=Math.floor(n*n*.5),d=!m.mask||m.mask[p]?m.pixels.map(e=>e[p]):null;let x;return null!=h&&(x=!h.mask||h.mask[p]?h.pixels.map(e=>e[p]):void 0),{location:y,value:d,processedValue:x,pyramidLevel:0}}let I=0;if(!g){let{srcResolution:i}=t;if(i){i.spatialReference&&(i=B(new m(i),c));I=j(i,o,this.ioConfig.sampling).pyramidLevel}else if(I=await this.computeBestPyramidLevelForLocation(e,t),null==I)return{location:y,value:null}}const w=this.identifyPixelLocation(y,I,null,g);if(null===w)return{location:y,value:null};const{row:R,col:S,rowOffset:k,colOffset:b,blockWidth:T}=w,v=await this._fetchRawTile(I,R,S,t);if(!v?.pixels?.length)return{location:y,value:null};const P=k*T+b;return this._processIdentifyResult(v,{srcLocation:y,position:P,pyramidLevel:I,useTransposedTile:!!g,requestSomeSlices:a,identifyOptions:t})}async fetchPixels(e,t,i,r={}){e=E(e),r=this._getRequestOptionsWithSliceId(r);const{_hasNoneOrGCSShiftTransform:o}=this;if(r.requestRawData&&o)return this._fetchPixels(e,t,i,r);const n=H(e.spatialReference),s=D(e);if(null==n||0===s||1===s&&this._isGlobalWrappableSource&&o)return this._fetchPixels(e,t,i,r);if(s>=3)return{extent:e,pixelBlock:null};const l=[],{xmin:a,xmax:c}=e,f=Math.round(n/(c-a)*t),m=f-Math.round((n/2-a)/(c-a)*t);let h=0;const p=[];for(let g=0;g<=s;g++){const o=new u({xmin:0===g?a:-n/2,xmax:g===s?c-n*g:n/2,ymin:e.ymin,ymax:e.ymax,spatialReference:e.spatialReference}),d=0===g?f-m:g===s?t-h:f;h+=d,p.push(d);const x=r.disableWrapAround&&g>0?null:this._fetchPixels(o,d,i,r);l.push(x)}const d=(await Promise.all(l)).map(e=>e?.pixelBlock);let x=null;const y={width:t,height:i};if(this.rasterJobHandler){x=(await this.rasterJobHandler.mosaicAndTransform({srcPixelBlocks:d,srcMosaicSize:y,destDimension:null,coefs:null,sampleSpacing:null,interpolation:"nearest",alignmentInfo:null,blockWidths:p},r)).pixelBlock}else x=_(d,y,{blockWidths:p});return{extent:e,srcExtent:O(e,this.rasterInfo.spatialReference,r.datumTransformation),pixelBlock:x}}async fetchRawPixels(e,t,i,r={}){t={x:Math.floor(t.x),y:Math.floor(t.y)};const o=await this._fetchRawTiles(e,t,i,r),{nativeExtent:n,nativePixelSize:s,storageInfo:l}=this.rasterInfo,a=2**e,c=s.x*a,f=s.y*a,m=new u({xmin:n.xmin+c*t.x,xmax:n.xmin+c*(t.x+i.width-1),ymin:n.ymax-f*(t.y+i.height-1),ymax:n.ymax-f*t.y,spatialReference:n.spatialReference});if(!o)return{extent:m,srcExtent:m,pixelBlock:null};const{pixelBlocks:h,mosaicSize:p}=o;if(1===h.length&&null!=h[0]&&h[0].width===i.width&&h[0].height===i.height)return{extent:m,srcExtent:m,pixelBlock:o.pixelBlocks[0]};const d=e>0?l.pyramidBlockWidth:l.blockWidth,x=e>0?l.pyramidBlockHeight:l.blockHeight,y={x:t.x%d,y:t.y%x};let g;if(this.rasterJobHandler){g=(await this.rasterJobHandler.mosaicAndTransform({srcPixelBlocks:h,srcMosaicSize:p,destDimension:i,clipOffset:y,clipSize:i,coefs:null,sampleSpacing:null,interpolation:r.interpolation,alignmentInfo:null,blockWidths:null},r)).pixelBlock}else g=_(h,p,{clipOffset:y,clipSize:i});return{extent:m,srcExtent:m,pixelBlock:g}}fetchRawTile(e,t,r,o){throw new i("BaseRaster:read-not-implemented","fetchRawTile() is not implemented")}computeExtent(e){return O(this.rasterInfo.extent,e)}decodePixelBlock(e,t){return this.rasterJobHandler?this.rasterJobHandler.decode({data:e,options:t}):P(e,t)}async request(e,i,r=0){const{customFetchParameters:o}=this.ioConfig,{range:n,query:s,headers:l}=i;r=r??i.retryCount??this.ioConfig.retryCount;const a=n?{Range:`bytes=${n.from}-${n.to}`}:null;try{return await t(e,{...i,query:{...s,...o},headers:{...l,...a}})}catch(c){if(r>0)return r--,this.request(e,i,r);throw c}}getSliceIndex(e){const{multidimensionalInfo:t}=this.rasterInfo;return null==t||null==e||0===e.length?null:y(e,t)}getTileExtentFromTileInfo(e,t,i,r){const o=r.lodAt(e);return o?this.getTileExtent({x:o.resolution,y:o.resolution},t,i,r.origin,r.spatialReference,r.size):null}updateTileInfo(){const{storageInfo:e,spatialReference:t,extent:i,pixelSize:r}=this.rasterInfo,{pyramidResolutions:o}=e;if(!e.tileInfo){const n=[],s=e.maximumPyramidLevel||0;let l=(r.x+r.y)/2,a=1/.0254*96*l;for(let e=0;e<=s&&(n.unshift(new Q({level:s-e,resolution:l,scale:a})),e!==s);e++)if(o){const t=(o[e].x+o[e].y)/2;a*=t/l,l=t}else l*=2,a*=2;const c=new m({x:i.xmin,y:i.ymax,spatialReference:t});e.tileInfo=new X({origin:c,size:[e.blockWidth,e.blockHeight],spatialReference:t,lods:n}),e.isVirtualTileInfo=!0}}createRemoteDatasetStorageInfo(e,t=512,i=512,r){const{width:o,height:n,nativeExtent:s,pixelSize:l,spatialReference:a}=e,c=new m({x:s.xmin,y:s.ymax,spatialReference:a});null==r&&(r=Math.max(0,Math.round(Math.log(Math.max(o,n))/Math.LN2-8)));const f=this.computeBlockBoundary(s,512,512,{x:s.xmin,y:s.ymax},[l],r);e.storageInfo=new $({blockWidth:t,blockHeight:i,pyramidBlockWidth:t,pyramidBlockHeight:i,origin:c,firstPyramidLevel:1,maximumPyramidLevel:r,blockBoundary:f})}async computeBestPyramidLevelForLocation(e,t={}){return 0}computeBlockBoundary(e,t,i,r,o,n=0,s=2){if(1===o.length&&n>0){o=[...o];let{x:e,y:t}=o[0];for(let i=0;i<n;i++)e*=s,t*=s,o.push({x:e,y:t})}const l=[],{x:a,y:c}=r;for(let f=0;f<o.length;f++){const{x:r,y:n}=o[f];l.push({minCol:Math.floor((e.xmin-a+.1*r)/t/r),maxCol:Math.floor((e.xmax-a-.1*r)/t/r),minRow:Math.floor((c-e.ymax+.1*n)/i/n),maxRow:Math.floor((c-e.ymin-.1*n)/i/n)})}return l}getPyramidPixelSize(e){const{nativePixelSize:t}=this.rasterInfo,{pyramidResolutions:i,pyramidScalingFactor:r}=this.rasterInfo.storageInfo;if(0===e)return t;if(null!=i&&i.length)return i[e-1];const o=r**e;return{x:t.x*o,y:t.y*o}}identifyPixelLocation(e,t,i,r){const{spatialReference:o,nativeExtent:n,storageInfo:s}=this.rasterInfo,{maximumPyramidLevel:l,origin:a,transposeInfo:c}=s,f=r&&null!=c?c.tileSize[0]:s.blockWidth,u=r&&null!=c?c.tileSize[1]:s.blockHeight,m=L(e,o,i);if(!n.intersects(m))return null;if(t<0||t>l)return null;const h=this.getPyramidPixelSize(t),{x:p,y:d}=h,x=(a.y-m.y)/d/u,y=(m.x-a.x)/p/f,g=Math.min(u-1,Math.floor((x-Math.floor(x))*u)),I=Math.min(f-1,Math.floor((y-Math.floor(y))*f));return{pyramidLevel:t,row:Math.floor(x),col:Math.floor(y),rowOffset:g,colOffset:I,blockWidth:f,srcLocation:m}}getTileExtent(e,t,i,r,o,n){const[s,l]=n,a=r.x+i*s*e.x,c=a+s*e.x,f=r.y-t*l*e.y,m=f-l*e.y;return new u({xmin:a,xmax:c,ymin:m,ymax:f,spatialReference:o})}getBlockWidthHeight(e){return{blockWidth:e>0?this.rasterInfo.storageInfo.pyramidBlockWidth:this.rasterInfo.storageInfo.blockWidth,blockHeight:e>0?this.rasterInfo.storageInfo.pyramidBlockHeight:this.rasterInfo.storageInfo.blockHeight}}isBlockOutside(e,t,i){const r=this.rasterInfo.storageInfo.blockBoundary[e];return!r||r.maxRow<t||r.maxCol<i||r.minRow>t||r.minCol>i}updateImageSpaceRasterInfo(e){const{pixelSize:t}=e,{width:i,height:r}=e,o=h.WebMercator;e.spatialReference=o,e.extent=e.nativeExtent=new u({xmin:-.5,ymax:.5,xmax:i-.5,ymin:.5-r,spatialReference:o}),e.isPseudoSpatialReference=!0,e.transform=null,e.pixelSize=new m({x:1,y:1,spatialReference:o});const{extent:n,storageInfo:s}=e;if(s){s.origin=new m({x:n.xmin,y:n.ymax,spatialReference:o});const{pyramidResolutions:i,tileInfo:r}=s;if(i&&i.forEach(e=>{e.x/=t.x,e.y/=t.y}),r){r.origin=s.origin;const t=(e.nativePixelSize.x+e.nativePixelSize.y)/2;r.lods.forEach((e,i)=>{e.resolution=t*2**i,e.scale=96*e.resolution/.0254})}}}async _refresh(e){return{dataChanged:!0}}async _fetchPixels(e,t,i,r={}){let o=D(e);if(o>=2)return{extent:e,pixelBlock:null};const n=this._getSourceDataInfo(e,t,i,r),{pyramidLevel:s,srcResolution:l,srcWidth:a,srcHeight:c,ul:f}=n;let{srcExtent:u}=n;if(0===a||0===c)return{extent:e,srcExtent:u,pixelBlock:null};const{rasterInfo:h}=this,p=h.transform,d="gcs-shift"===p?.type,x=null!=H(e.spatialReference);!d&&x||(o=D(u,d));const y=await this._fetchRawTiles(s,f,{width:a,height:c,wrapCount:o},r);if(!y)return{extent:e,srcExtent:u,pixelBlock:null};u=y.extent;const g=h.storageInfo,I=s>0?g.pyramidBlockWidth:g.blockWidth,w=s>0?g.pyramidBlockHeight:g.blockHeight;let{x:R,y:S}=h.pixelSize;if(s>0){const{pyramidResolutions:e,pyramidScalingFactor:t}=g;if(null!=e&&e[s-1])({x:R,y:S}=e[s-1]);else{const e=t**s;R*=e,S*=e}}const k=h.spatialReference,b=new m({x:R,y:S,spatialReference:k}),T=I===a&&w===c&&f.x%I===0&&f.y%w===0,v=new m({x:(e.xmax-e.xmin)/t,y:(e.ymax-e.ymin)/i,spatialReference:e.spatialReference}),P=!e.spatialReference.equals(k),B=k.isGeographic?1e-9:1e-4,{datumTransformation:C}=r;if(!P&&T&&1===y.pixelBlocks.length&&I===t&&w===i&&te(l,v,B))return{extent:e,srcExtent:u,srcTilePixelSize:b,pixelBlock:y.pixelBlocks[0]};const L=x&&null!=H(u.spatialReference)&&this._hasNoneOrGCSShiftTransform,j=r.requestProjectedLocalDirections&&this.rasterInfo.dataType.startsWith("vector");j&&!this.rasterJobHandler&&await z();const E=this.rasterJobHandler?await this.rasterJobHandler.getProjectionOffsetGrid({projectedExtent:e,srcBufferExtent:u,pixelSize:v.toJSON(),datumTransformation:C,rasterTransform:p,hasWrapAround:o>0||L,isAdaptive:!1!==this.ioConfig.optimizeProjectionAccuracy,includeGCSGrid:j},r):A({projectedExtent:e,srcBufferExtent:u,pixelSize:v,datumTransformation:C,rasterTransform:p,hasWrapAround:o>0||L,isAdaptive:!1,includeGCSGrid:j});let O;const q=!r.requestRawData,F={rows:E.spacing[0],cols:E.spacing[1]},J=this._hasNoneOrGCSShiftTransform?this._getRasterTileAlignmentInfo(s,u.xmin):void 0,{pixelBlocks:N,mosaicSize:V,isPartiallyFilled:U}=y;let Q=null;if(this.rasterJobHandler){const e=await this.rasterJobHandler.mosaicAndTransform({srcPixelBlocks:N,srcMosaicSize:V,destDimension:q?{width:t,height:i}:null,coefs:q?E.coefficients:null,sampleSpacing:q?F:null,projectDirections:j,gcsGrid:j?E.gcsGrid:null,isUV:"vector-uv"===this.rasterInfo.dataType,interpolation:r.interpolation,alignmentInfo:J,blockWidths:null},r);({pixelBlock:O,localNorthDirections:Q}=e)}else{const e=_(N,V,{alignmentInfo:J});O=q?M(e,{width:t,height:i},E.coefficients,F,r.interpolation):e,j&&E.gcsGrid&&(Q=W({width:t,height:i},E.gcsGrid),O=G(O,this.rasterInfo.dataType,Q))}return r.requestRawData||j?{extent:e,srcExtent:u,srcTilePixelSize:b,pixelBlock:O,transformGrid:E,localNorthDirections:Q,isPartiallyFilled:U}:{extent:e,srcExtent:e,srcTilePixelSize:b,pixelBlock:O}}async _fetchRawTiles(e,t,i,r){const{origin:o,blockBoundary:n}=this.rasterInfo.storageInfo,{blockWidth:s,blockHeight:l}=this.getBlockWidthHeight(e);let{x:a,y:c}=t,{width:f,height:m,wrapCount:h}=i;const p=this._getRasterTileAlignmentInfo(e,0);r.buffer&&(a-=r.buffer.cols,c-=r.buffer.rows,f+=2*r.buffer.cols,m+=2*r.buffer.rows);let d=0,x=0,y=0;if(h&&null!=p){({worldColumnCountFromOrigin:x,originColumnOffset:y,rightPadding:d}=p);x*p.blockWidth-d>=a+f&&(d=0)}const g=Math.floor(a/s),I=Math.floor(c/l),w=Math.floor((a+f+d-1)/s),R=Math.floor((c+m+d-1)/l),S=n[e];if(!S)return null;const{minRow:k,minCol:b,maxCol:T,maxRow:v}=S;if(0===h&&(R<k||w<b||I>v||g>T))return null;const P=new Array;let B=!1;const _=null==this.ioConfig.allowPartialFill?r.allowPartialFill:this.ioConfig.allowPartialFill;for(let u=I;u<=R;u++)for(let t=g;t<=w;t++){let i=t;if(!r.disableWrapAround&&h&&null!=p&&x<=t&&(i=t-x-y),u>=k&&i>=b&&v>=u&&T>=i){const t=this._fetchRawTile(e,u,i,r);_?P.push(new Promise(e=>{t.then(t=>e(t)).catch(()=>{B=!0,e(null)})})):P.push(t)}else P.push(Promise.resolve(null))}if(0===P.length)return null;const M=await Promise.all(P),W={height:(R-I+1)*l,width:(w-g+1)*s},{spatialReference:C}=this.rasterInfo,H=this.getPyramidPixelSize(e),{x:z,y:L}=H;return{extent:new u({xmin:o.x+g*s*z,xmax:o.x+(w+1)*s*z,ymin:o.y-(R+1)*l*L,ymax:o.y-I*l*L,spatialReference:C}),pixelBlocks:M,mosaicSize:W,isPartiallyFilled:B}}_fetchRawTile(e,t,i,r){const{storageInfo:o}=this.rasterInfo,n=null!=o.transposeInfo&&!!r.transposedVariableName;if(!n){const r=o.blockBoundary[e];if(!r)return Promise.resolve(null);const{minRow:n,minCol:s,maxCol:l,maxRow:a}=r;if(t<n||i<s||t>a||i>l)return Promise.resolve(null)}const l=n?r.transposeVariableName:r.sliceId,a=o.isBsqTile?r.bandIds:null,c=R(this.rasterId,l,a),f=`${e}/${t}/${i}`;let u=S(c,r.registryId,f);if(null==u){const n=new AbortController,s=r.bandIds?.slice();if(s?.length&&o.isBsqTile){const o=new Set(s),l=[],a=Array.from(o);for(const s of a)l.push(this._tileFetchQueue.push({pyramidLevel:e,row:t,col:i,options:{...r,bandIds:[s]}},{signal:n.signal}));u=Promise.all(l).then(e=>{if(e.some(e=>null==e))return null;if(a.length!==s.length){const t=[];for(const i of s){let r=e[a.indexOf(i)];t.includes(r)&&(r=r.clone()),t.push(r)}e=t}return this.rasterJobHandler?this.rasterJobHandler.compositeBands({pixelBlocks:e},{signal:n.signal,transferPixelsToWorker:!0}):C(e)})}else u=this._tileFetchQueue.push({pyramidLevel:e,row:t,col:i,options:r},{signal:n.signal});k(c,r.registryId,f,u,n),u.catch(()=>b(c,r.registryId,f))}return r.signal&&s(r,()=>{T(c,r.registryId,f)}),u}_computeMagDirValues(e){const{bandCount:t,dataType:i}=this.rasterInfo;if(!(2===t&&"vector-magdir"===i||"vector-uv"===i)||2!==e?.length||!e[0]?.length)return null;const r=e[0].length;if("vector-magdir"===i){const t=e[1].map(e=>(e+360)%360);return[e[0],t]}const[o,n]=e,s=[],l=[];for(let a=0;a<r;a++){const[e,t]=J([o[a],n[a]]);s.push(e),l.push(t)}return[s,l]}_getRasterTileAlignmentInfo(e,t){return null==this._rasterTileAlignmentInfo&&(this._rasterTileAlignmentInfo=q(this.rasterInfo)),null==this._rasterTileAlignmentInfo.pyramidsInfo?null:{startX:t,halfWorldWidth:this._rasterTileAlignmentInfo.halfWorldWidth,hasGCSSShiftTransform:this._rasterTileAlignmentInfo.hasGCSSShiftTransform,...this._rasterTileAlignmentInfo.pyramidsInfo[e]}}_getSourceDataInfo(e,t,i,r={}){const o={datumTransformation:r.datumTransformation,pyramidLevel:0,pyramidResolution:null,srcExtent:null,srcHeight:0,srcResolution:null,srcWidth:0,ul:{x:0,y:0}};r.srcResolution&&(o.srcResolution=r.srcResolution,this._updateSourceDataInfo(e,o));const n=this.rasterInfo.storageInfo.maximumPyramidLevel||0,{srcWidth:s,srcHeight:l,pyramidLevel:a}=o,c=s/t,f=l/i,u=a<n&&c*f>=16,h=a===n&&this._requireTooManySrcTiles(s,l,t,i);if(u||h||(0===s||0===l)){const s=new m({x:(e.xmax-e.xmin)/t,y:(e.ymax-e.ymin)/i,spatialReference:e.spatialReference});let l=F(s,this.rasterInfo.spatialReference,e,o.datumTransformation);const h=!l||r.srcResolution&&l.x+l.y<r.srcResolution.x+r.srcResolution.y;if(u&&r.srcResolution&&h){const e=Math.round(Math.log(Math.max(c,f))/Math.LN2)-1;if(n-a+3>=e){const t=2**e;l={x:r.srcResolution.x*t,y:r.srcResolution.y*t}}}l&&(o.srcResolution=l,this._updateSourceDataInfo(e,o))}return this._requireTooManySrcTiles(o.srcWidth,o.srcHeight,t,i)&&(o.srcWidth=0,o.srcHeight=0),o}_requireTooManySrcTiles(e,t,i,r){const{tileInfo:o}=this.rasterInfo.storageInfo,n=Math.ceil(e/o.size[0])*Math.ceil(t/o.size[1]),s=e/i,l=t/r,a=Math.max(1,(i+r)/1024);return n>=Y*a||s>K||l>K}_updateSourceDataInfo(e,t){t.srcWidth=0,t.srcHeight=0;const{rasterInfo:i}=this,r=i.spatialReference,{srcResolution:o,datumTransformation:n}=t,{pyramidLevel:s,pyramidResolution:l,excessiveReading:a}=j(o,i,this.ioConfig.sampling);if(a)return;let c=t.srcExtent||O(e,r,n);if(null==c)return;const f=i.transform;f&&(c=f.inverseTransform(c)),t.srcExtent=c;const{origin:u}=i.storageInfo,{width:m,height:h,ul:p}=d(c,u,l,s);t.pyramidLevel=s,t.pyramidResolution=l,t.srcWidth=m,t.srcHeight=h,t.ul=p}_getRequestOptionsWithSliceId(e){return null!=this.rasterInfo.multidimensionalInfo&&null==e.sliceId&&(e={...e,sliceId:this.getSliceIndex(e.multidimensionalDefinition)}),e}_processIdentifyResult(e,t){const{srcLocation:i,position:r,pyramidLevel:o,useTransposedTile:n}=t,s=e.pixels[0].length/e.width/e.height;if(!(!e.mask||e.mask[r]))return{location:i,value:null};const{multidimensionalInfo:l}=this.rasterInfo;if(null==l||!n){const t=e.pixels.map(e=>e[r]),n={location:i,value:t,pyramidLevel:o},s=this._computeMagDirValues(t.map(e=>[e]));return s?.length&&(n.magdirValue=s.map(e=>e[0])),n}let a=e.pixels.map(e=>e.slice(r*s,r*s+s)),c=this._computeMagDirValues(a);const{requestSomeSlices:f,identifyOptions:u}=t;let m=g(l,u.transposedVariableName);if(f){const e=I(m,u.multidimensionalDefinition,u.timeExtent);a=a.map(t=>e.map(e=>t[e])),c=c?.map(t=>e.map(e=>t[e])),m=e.map(e=>m[e])}const h=e.noDataValues||this.rasterInfo.noDataValue,p={pixels:a,pixelType:e.pixelType};let d;null!=h&&(v(p,h),d=p.mask);return{location:i,value:null,dataSeries:m.map((e,t)=>{const i={value:0===d?.[t]?null:a.map(e=>e[t]),multidimensionalDefinition:e.multidimensionalDefinition.map(e=>new U({...e,isSlice:!0}))};return c?.length&&(i.magdirValue=[c[0][t],c[1][t]]),i}),pyramidLevel:o}}};function te(e,t,i){return Math.abs(e.x-t.x)<i&&Math.abs(e.y-t.y)<i}e([a()],ee.prototype,"_rasterTileAlignmentInfo",void 0),e([a()],ee.prototype,"_tileFetchQueue",void 0),e([a({readOnly:!0})],ee.prototype,"_isGlobalWrappableSource",null),e([a({readOnly:!0})],ee.prototype,"_hasNoneOrGCSShiftTransform",null),e([a()],ee.prototype,"_openPromise",void 0),e([a()],ee.prototype,"rasterJobHandler",null),e([a({readOnly:!0})],ee.prototype,"rasterId",null),e([a(V)],ee.prototype,"url",null),e([a({type:String,json:{write:!0}})],ee.prototype,"datasetName",void 0),e([a({type:String,json:{write:!0}})],ee.prototype,"datasetFormat",void 0),e([a()],ee.prototype,"hasUniqueSourceStorageInfo",void 0),e([a()],ee.prototype,"rasterInfo",void 0),e([a()],ee.prototype,"ioConfig",void 0),e([a()],ee.prototype,"sourceJSON",void 0),e([a()],ee.prototype,"rawBlockRegistryIds",void 0),ee=e([c("esri.layers.raster.datasets.BaseRaster")],ee);export{ee as default};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{saveAs as e,save as r}from"./utils.js";import{createForItemWrite as t}from"../../portal/support/jsonContext.js";import{typeKeyword as o,hasTypeKeyword as s,removeTypeKeyword as a,addTypeKeyword as n,toggleTypeKeyword as i}from"../../portal/support/portalItemUtils.js";import{saveResources as u}from"../../webdoc/support/resourceUtils.js";import{hasCharts as c}from"../../webdoc/support/saveUtils.js";const p="Group Layer",l="group-layer-save",m="group-layer-save-as",y=o.GROUP_LAYER_MAP;function f(e){return{isValid:"group"===e.type,errorMessage:"Layer.type should be 'group'"}}function v(e){return{isValid:s(e,y),errorMessage:`Layer.portalItem.typeKeywords should have '${y}'`}}function d(e,r){return{...t(e,"web-map",!0),initiator:r}}function I(e){const r=e.layerJSON;return Promise.resolve(r&&Object.keys(r).length?r:null)}function A(e,r){i(r,o.CHARTS,c(e))}function P(e,r){A(e,r)}async function R(e,r){r.title||=e.title,a(r,o.METADATA),n(r,y),A(e,r)}async function g(e,t){return r({layer:e,itemType:p,validateLayer:f,validateItem:v,createJSONContext:r=>d(r,e),createItemData:I,errorNamePrefix:l,setItemProperties:P,saveResources:async(r,t)=>(e.sourceIsPortalItem||await r.removeAllResources().catch(()=>{}),u(e.resourceReferences,t))},t)}async function j(r,t,o){return e({layer:r,itemType:p,validateLayer:f,createJSONContext:e=>d(e,r),createItemData:I,errorNamePrefix:m,newItem:t,setItemProperties:R,saveResources:(e,t)=>u(r.resourceReferences,t)},o)}export{g as save,j as saveAs};
2
+ import{saveAs as e,save as r}from"./utils.js";import{createForItemWrite as t}from"../../portal/support/jsonContext.js";import{typeKeyword as o,hasTypeKeyword as s,removeTypeKeyword as a,addTypeKeyword as n,toggleTypeKeyword as i}from"../../portal/support/portalItemUtils.js";import{saveResources as u}from"../../webdoc/support/resourceUtils.js";import{hasCharts as c}from"../../webdoc/support/saveUtils.js";const p="Group Layer",l="group-layer-save",m="group-layer-save-as",y=o.GROUP_LAYER_MAP;function f(e){return{isValid:"group"===e.type,errorMessage:"Layer.type should be 'group'"}}function v(e){return{isValid:s(e,y),errorMessage:`Layer.portalItem.typeKeywords should have '${y}'`}}function d(e,r){return{...t(e,"web-map",{withResources:!0}),initiator:r}}function I(e){const r=e.layerJSON;return Promise.resolve(r&&Object.keys(r).length?r:null)}function R(e,r){i(r,o.CHARTS,c(e))}function A(e,r){R(e,r)}async function P(e,r){r.title||=e.title,a(r,o.METADATA),n(r,y),R(e,r)}async function g(e,t){return r({layer:e,itemType:p,validateLayer:f,validateItem:v,createJSONContext:r=>d(r,e),createItemData:I,errorNamePrefix:l,setItemProperties:A,saveResources:async(r,t)=>(e.sourceIsPortalItem||await r.removeAllResources().catch(()=>{}),u(e.resourceReferences,t))},t)}async function j(r,t,o){return e({layer:r,itemType:p,validateLayer:f,createJSONContext:e=>d(e,r),createItemData:I,errorNamePrefix:m,newItem:t,setItemProperties:P,saveResources:(e,t)=>u(r.resourceReferences,t)},o)}export{g as save,j as saveAs};