@arcgis/core 4.26.0-next.20230127 → 4.26.0-next.20230129

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 (252) hide show
  1. package/WebMap.js +1 -1
  2. package/arcade/featureSetUtils.js +1 -1
  3. package/arcade/featureset/sources/FeatureLayerDynamic.js +1 -1
  4. package/arcade/featureset/sources/FeatureLayerMemory.js +1 -1
  5. package/arcade/featureset/support/FeatureSet.js +1 -1
  6. package/arcade/functions/featuresetbase.js +1 -1
  7. package/arcade/functions/geomasync.js +1 -1
  8. package/arcade/functions/string.js +1 -1
  9. package/arcade/kernel.js +1 -1
  10. package/arcade/portalUtils.js +5 -0
  11. package/arcade/treeAnalysis.js +1 -1
  12. package/assets/esri/core/workers/RemoteClient.js +1 -1
  13. package/assets/esri/core/workers/chunks/{ce3b6f9be5d68dea8596.js → 02157c876c0c0886e2f7.js} +1 -1
  14. package/assets/esri/core/workers/chunks/03bd9250ad5c5ecead91.js +1 -0
  15. package/assets/esri/core/workers/chunks/06b50ac3478de95a0024.js +1 -0
  16. package/assets/esri/core/workers/chunks/09975049ce6c426af5a7.js +1 -0
  17. package/assets/esri/core/workers/chunks/0f08b5f4f85d82c1a938.js +1 -0
  18. package/assets/esri/core/workers/chunks/10c5627deb2af6163ad2.js +1 -0
  19. package/assets/esri/core/workers/chunks/{accb53e75a168ca56f98.js → 10ed4c92d56a0a4061a6.js} +1 -1
  20. package/assets/esri/core/workers/chunks/12234fd9bdd0d836f64c.js +1 -0
  21. package/assets/esri/core/workers/chunks/144a0b86d5b3db7db2f6.js +1 -0
  22. package/assets/esri/core/workers/chunks/{4b56a15d904a64747e64.js → 1756e2395cd5f83deac9.js} +1 -1
  23. package/assets/esri/core/workers/chunks/1aff09c90f287eeba408.js +1 -0
  24. package/assets/esri/core/workers/chunks/1fcc385a9a8904354a67.js +1 -0
  25. package/assets/esri/core/workers/chunks/22e0a27e1751418d9b50.js +1 -0
  26. package/assets/esri/core/workers/chunks/{16e9d07533a6e3cf0ca0.js → 2ad66950b345bc8b5fba.js} +1 -1
  27. package/assets/esri/core/workers/chunks/{c98c39ce91f075539d15.js → 2d12dfe287842923d1f5.js} +1 -1
  28. package/assets/esri/core/workers/chunks/3cc8526d3c0bb08be773.js +1 -0
  29. package/assets/esri/core/workers/chunks/4cb41045be4ee7ac0455.js +1 -0
  30. package/assets/esri/core/workers/chunks/5399e92295d759134780.js +1 -0
  31. package/assets/esri/core/workers/chunks/{0f29a06eba4aae3eca11.js → 5486255598e3e765e1a4.js} +1 -1
  32. package/assets/esri/core/workers/chunks/5c18d37ada9af55037d9.js +1 -0
  33. package/assets/esri/core/workers/chunks/{b27448eddd486645f682.js → 6ba6d42e102fc27186f6.js} +1 -1
  34. package/assets/esri/core/workers/chunks/6fee0bf26d3a142ec75c.js +1 -0
  35. package/assets/esri/core/workers/chunks/71a975eb4407cc255c4a.js +1 -0
  36. package/assets/esri/core/workers/chunks/{3a00f94f8f0d49c60969.js → 724cfd0ca8e7e0476f99.js} +1 -1
  37. package/assets/esri/core/workers/chunks/7835f9472ee9013964f7.js +1 -0
  38. package/assets/esri/core/workers/chunks/786acd608d8e4499b4b4.js +1 -0
  39. package/assets/esri/core/workers/chunks/7ca5e2e4a35358786bf1.js +1 -0
  40. package/assets/esri/core/workers/chunks/872b71499801a7a17314.js +1 -0
  41. package/assets/esri/core/workers/chunks/889325cf1ae14bbce862.js +1 -0
  42. package/assets/esri/core/workers/chunks/8c8de7cee237117f2365.js +1 -0
  43. package/assets/esri/core/workers/chunks/{30ae4c22f6b8aab9f841.js → 97ba79f9bceb42405573.js} +1 -1
  44. package/assets/esri/core/workers/chunks/{b5a823da33cdcf4efe2d.js → 999698bb5c1babff2edd.js} +1 -1
  45. package/assets/esri/core/workers/chunks/a0922cbd36abd9e734b5.js +1 -0
  46. package/assets/esri/core/workers/chunks/{4b116ecd96059f0588be.js → a17e66d63389f1c520dc.js} +1 -1
  47. package/assets/esri/core/workers/chunks/{0f7d53062ee425243aa1.js → a213fb1cd2b5da2b7027.js} +1 -1
  48. package/assets/esri/core/workers/chunks/a6e9bbcfb2990e2af8db.js +1 -0
  49. package/assets/esri/core/workers/chunks/a7d2caa47df34a66445a.js +1 -0
  50. package/assets/esri/core/workers/chunks/a935803e70a75e04d0de.js +1 -0
  51. package/assets/esri/core/workers/chunks/ae9f84da87c2d035f5bb.js +1 -0
  52. package/assets/esri/core/workers/chunks/b429569521a96133f2ff.js +1 -0
  53. package/assets/esri/core/workers/chunks/{4a2b4574b87be7b98481.js → bbd8c877224b1d56e125.js} +1 -1
  54. package/assets/esri/core/workers/chunks/beb8a9ceaee0a1a5441a.js +1 -0
  55. package/assets/esri/core/workers/chunks/{2e7e8b035673d90deefd.js → c704ca53f18751204949.js} +1 -1
  56. package/assets/esri/core/workers/chunks/c7ea6f1b1a01fc118434.js +1 -0
  57. package/assets/esri/core/workers/chunks/cfc20e0efdc984972d5d.js +1 -0
  58. package/assets/esri/core/workers/chunks/d66e7866dd203b93b73e.js +1 -0
  59. package/assets/esri/core/workers/chunks/da748aadf96b9112c01a.js +1 -0
  60. package/assets/esri/core/workers/chunks/e6d10bbb3b6e875bf217.js +1 -0
  61. package/assets/esri/core/workers/chunks/e9b43ea40587d2c5d039.js +1 -0
  62. package/assets/esri/core/workers/chunks/{0e67a5caab64ddd90a5d.js → eda4c60b34833af1d139.js} +1 -1
  63. package/assets/esri/core/workers/chunks/{3714482f3a829d122da1.js → efade11c5dc55465a95e.js} +1 -1
  64. package/assets/esri/core/workers/chunks/f6c39edd04cb96d98240.js +1 -0
  65. package/assets/esri/core/workers/chunks/fa2695b40825b85320e2.js +1 -0
  66. package/assets/esri/core/workers/chunks/fa84f79aa6c2926c1a69.js +1 -0
  67. package/assets/esri/core/workers/chunks/{1e55c5e9a0bfb92f36aa.js → fb2403601ff985f4d493.js} +1 -1
  68. package/assets/esri/themes/base/widgets/_Editor.scss +1 -1
  69. package/assets/esri/themes/dark/main.css +1 -1
  70. package/assets/esri/themes/light/main.css +1 -1
  71. package/assets/esri/themes/light/view.css +1 -1
  72. package/assets/esri/views/interactive/tooltip/t9n/Tooltip.json +1 -1
  73. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_ar.json +1 -1
  74. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_bg.json +1 -1
  75. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_bs.json +1 -1
  76. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_ca.json +1 -1
  77. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_cs.json +1 -1
  78. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_da.json +1 -1
  79. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_de.json +1 -1
  80. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_el.json +1 -1
  81. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_en.json +1 -1
  82. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_es.json +1 -1
  83. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_et.json +1 -1
  84. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_fi.json +1 -1
  85. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_fr.json +1 -1
  86. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_he.json +1 -1
  87. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_hr.json +1 -1
  88. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_hu.json +1 -1
  89. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_id.json +1 -1
  90. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_it.json +1 -1
  91. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_ja.json +1 -1
  92. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_ko.json +1 -1
  93. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_lt.json +1 -1
  94. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_lv.json +1 -1
  95. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_nb.json +1 -1
  96. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_nl.json +1 -1
  97. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_pl.json +1 -1
  98. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_pt-BR.json +1 -1
  99. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_pt-PT.json +1 -1
  100. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_ro.json +1 -1
  101. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_ru.json +1 -1
  102. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_sk.json +1 -1
  103. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_sl.json +1 -1
  104. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_sr.json +1 -1
  105. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_sv.json +1 -1
  106. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_th.json +1 -1
  107. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_tr.json +1 -1
  108. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_uk.json +1 -1
  109. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_vi.json +1 -1
  110. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_zh-CN.json +1 -1
  111. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_zh-HK.json +1 -1
  112. package/assets/esri/views/interactive/tooltip/t9n/Tooltip_zh-TW.json +1 -1
  113. package/assets/esri/widgets/Editor/t9n/Editor.json +1 -1
  114. package/assets/esri/widgets/Editor/t9n/Editor_ar.json +1 -1
  115. package/assets/esri/widgets/Editor/t9n/Editor_bg.json +1 -1
  116. package/assets/esri/widgets/Editor/t9n/Editor_bs.json +1 -1
  117. package/assets/esri/widgets/Editor/t9n/Editor_ca.json +1 -1
  118. package/assets/esri/widgets/Editor/t9n/Editor_cs.json +1 -1
  119. package/assets/esri/widgets/Editor/t9n/Editor_da.json +1 -1
  120. package/assets/esri/widgets/Editor/t9n/Editor_de.json +1 -1
  121. package/assets/esri/widgets/Editor/t9n/Editor_el.json +1 -1
  122. package/assets/esri/widgets/Editor/t9n/Editor_en.json +1 -1
  123. package/assets/esri/widgets/Editor/t9n/Editor_es.json +1 -1
  124. package/assets/esri/widgets/Editor/t9n/Editor_et.json +1 -1
  125. package/assets/esri/widgets/Editor/t9n/Editor_fi.json +1 -1
  126. package/assets/esri/widgets/Editor/t9n/Editor_fr.json +1 -1
  127. package/assets/esri/widgets/Editor/t9n/Editor_he.json +1 -1
  128. package/assets/esri/widgets/Editor/t9n/Editor_hr.json +1 -1
  129. package/assets/esri/widgets/Editor/t9n/Editor_hu.json +1 -1
  130. package/assets/esri/widgets/Editor/t9n/Editor_id.json +1 -1
  131. package/assets/esri/widgets/Editor/t9n/Editor_it.json +1 -1
  132. package/assets/esri/widgets/Editor/t9n/Editor_ja.json +1 -1
  133. package/assets/esri/widgets/Editor/t9n/Editor_ko.json +1 -1
  134. package/assets/esri/widgets/Editor/t9n/Editor_lt.json +1 -1
  135. package/assets/esri/widgets/Editor/t9n/Editor_lv.json +1 -1
  136. package/assets/esri/widgets/Editor/t9n/Editor_nb.json +1 -1
  137. package/assets/esri/widgets/Editor/t9n/Editor_nl.json +1 -1
  138. package/assets/esri/widgets/Editor/t9n/Editor_pl.json +1 -1
  139. package/assets/esri/widgets/Editor/t9n/Editor_pt-BR.json +1 -1
  140. package/assets/esri/widgets/Editor/t9n/Editor_pt-PT.json +1 -1
  141. package/assets/esri/widgets/Editor/t9n/Editor_ro.json +1 -1
  142. package/assets/esri/widgets/Editor/t9n/Editor_ru.json +1 -1
  143. package/assets/esri/widgets/Editor/t9n/Editor_sk.json +1 -1
  144. package/assets/esri/widgets/Editor/t9n/Editor_sl.json +1 -1
  145. package/assets/esri/widgets/Editor/t9n/Editor_sr.json +1 -1
  146. package/assets/esri/widgets/Editor/t9n/Editor_sv.json +1 -1
  147. package/assets/esri/widgets/Editor/t9n/Editor_th.json +1 -1
  148. package/assets/esri/widgets/Editor/t9n/Editor_tr.json +1 -1
  149. package/assets/esri/widgets/Editor/t9n/Editor_uk.json +1 -1
  150. package/assets/esri/widgets/Editor/t9n/Editor_vi.json +1 -1
  151. package/assets/esri/widgets/Editor/t9n/Editor_zh-CN.json +1 -1
  152. package/assets/esri/widgets/Editor/t9n/Editor_zh-HK.json +1 -1
  153. package/assets/esri/widgets/Editor/t9n/Editor_zh-TW.json +1 -1
  154. package/core/accessorSupport/decorators/persistable.js +1 -1
  155. package/geometry/support/TileClipper.js +5 -0
  156. package/interfaces.d.ts +6 -18
  157. package/layers/MediaLayer.js +1 -1
  158. package/layers/mixins/operationalLayerModuleMap.js +1 -1
  159. package/layers/mixins/operationalLayers.js +1 -1
  160. package/layers/support/ImageElement.js +1 -1
  161. package/layers/support/MediaElementBase.js +1 -1
  162. package/layers/support/layersCreator.js +1 -1
  163. package/layers/support/lazyLayerLoader.js +1 -1
  164. package/layers/support/rasterFunctions/AspectFunction.js +1 -1
  165. package/layers/support/rasterFunctions/LocalFunction.js +1 -1
  166. package/layers/support/rasterFunctions/RemapFunction.js +1 -1
  167. package/layers/support/rasterFunctions/SlopeFunction.js +1 -1
  168. package/layers/support/rasterFunctions/localUtils.js +1 -1
  169. package/layers/support/rasterFunctions/pixelUtils.js +1 -1
  170. package/package.json +1 -1
  171. package/support/revision.js +1 -1
  172. package/symbols/cim/CIMEffects.js +1 -1
  173. package/symbols/cim/CIMResourceManager.js +1 -1
  174. package/symbols/cim/CIMSymbolDrawHelper.js +1 -1
  175. package/symbols/cim/CIMSymbolHelper.js +1 -1
  176. package/symbols/cim/effects/CIMEffectHelper.js +1 -1
  177. package/symbols/cim/effects/EffectAddControlPoints.js +1 -1
  178. package/symbols/cim/effects/EffectArrow.js +1 -1
  179. package/symbols/cim/effects/EffectBuffer.js +1 -1
  180. package/symbols/cim/effects/EffectControlMeasureLine.js +1 -1
  181. package/symbols/cim/effects/EffectCut.js +1 -1
  182. package/symbols/cim/effects/EffectDashes.js +1 -1
  183. package/symbols/cim/effects/EffectDonut.js +1 -1
  184. package/symbols/cim/effects/EffectJog.js +1 -1
  185. package/symbols/cim/effects/EffectMove.js +1 -1
  186. package/symbols/cim/effects/EffectOffset.js +1 -1
  187. package/symbols/cim/effects/EffectReverse.js +1 -1
  188. package/symbols/cim/effects/EffectRotate.js +1 -1
  189. package/symbols/cim/effects/EffectScale.js +1 -1
  190. package/symbols/cim/effects/EffectWave.js +1 -1
  191. package/symbols/cim/utils.js +1 -1
  192. package/views/2d/engine/imagery/processor/utils.js +1 -1
  193. package/views/2d/engine/vectorTiles/Feature.js +1 -1
  194. package/views/2d/engine/vectorTiles/Placement.js +1 -1
  195. package/views/2d/engine/vectorTiles/TileParser.js +1 -1
  196. package/views/2d/engine/vectorTiles/buckets/FillBucket.js +1 -1
  197. package/views/2d/engine/vectorTiles/buckets/SymbolBucket.js +1 -1
  198. package/views/2d/engine/vectorTiles/expression/expression.js +1 -1
  199. package/views/2d/engine/webgl/mesh/templates/WGLMeshTemplate.js +1 -1
  200. package/views/2d/engine/webgl/mesh/templates/templateUtils.js +1 -1
  201. package/views/2d/engine/webgl/shaders/sources/shaderRepository.js +1 -1
  202. package/views/2d/interactive/editingTools/TransformTool.js +1 -1
  203. package/views/2d/layers/features/support/ResourceManagerProxy.js +1 -1
  204. package/views/draw/DrawGraphicTool.js +1 -1
  205. package/views/draw/support/helpMessageUtils.js +1 -1
  206. package/views/interactive/tooltip/DrawTooltipInfos.js +1 -1
  207. package/views/interactive/tooltip/content/TooltipContent.js +1 -1
  208. package/webdoc/support/writeUtils.js +1 -1
  209. package/widgets/Editor/CreateFeaturesWorkflow.js +1 -1
  210. package/widgets/Editor/CreateWorkflow.js +1 -1
  211. package/widgets/Editor/UpdateWorkflow.js +1 -1
  212. package/widgets/Editor/Workflow.js +1 -1
  213. package/widgets/Editor.js +1 -1
  214. package/assets/esri/core/workers/chunks/006af87392d7136fb8c7.js +0 -1
  215. package/assets/esri/core/workers/chunks/011ae8db708c1817e982.js +0 -1
  216. package/assets/esri/core/workers/chunks/09556ef505728089b3b1.js +0 -1
  217. package/assets/esri/core/workers/chunks/14b304e9c609e491f86c.js +0 -1
  218. package/assets/esri/core/workers/chunks/1d61a96a517ce1ea2a20.js +0 -1
  219. package/assets/esri/core/workers/chunks/2312c752419c7c1d7e4a.js +0 -1
  220. package/assets/esri/core/workers/chunks/23f83625d9f6998cfa7b.js +0 -1
  221. package/assets/esri/core/workers/chunks/3161400f0c67198ed10b.js +0 -1
  222. package/assets/esri/core/workers/chunks/3b6402b2929ba339468f.js +0 -1
  223. package/assets/esri/core/workers/chunks/3ca8ff2c0f65872bc81a.js +0 -1
  224. package/assets/esri/core/workers/chunks/486a604808692d3e7bfc.js +0 -1
  225. package/assets/esri/core/workers/chunks/49123b80c25068dbdcd5.js +0 -1
  226. package/assets/esri/core/workers/chunks/4b2edcb8ef7fae4f7d28.js +0 -1
  227. package/assets/esri/core/workers/chunks/5c8fd7842bdfe912eef2.js +0 -1
  228. package/assets/esri/core/workers/chunks/5f0e211f07d8abe5e764.js +0 -1
  229. package/assets/esri/core/workers/chunks/63706a04e173000994db.js +0 -1
  230. package/assets/esri/core/workers/chunks/64b63a6f82d3969af846.js +0 -1
  231. package/assets/esri/core/workers/chunks/681682830ee669d876a6.js +0 -1
  232. package/assets/esri/core/workers/chunks/6bc90a5ebfbfbb998656.js +0 -1
  233. package/assets/esri/core/workers/chunks/6bff516e49b488531e87.js +0 -1
  234. package/assets/esri/core/workers/chunks/719ee5c4a064ea9bdfcf.js +0 -1
  235. package/assets/esri/core/workers/chunks/798cd875d64182741364.js +0 -1
  236. package/assets/esri/core/workers/chunks/878a51ff8267f4b26ebb.js +0 -1
  237. package/assets/esri/core/workers/chunks/96a2c5d1b5ad633e3b54.js +0 -1
  238. package/assets/esri/core/workers/chunks/985154f1cd74dc762894.js +0 -1
  239. package/assets/esri/core/workers/chunks/9aee6f171d4fbac941d9.js +0 -1
  240. package/assets/esri/core/workers/chunks/aa8bcdbd715921b56c1c.js +0 -1
  241. package/assets/esri/core/workers/chunks/b26a671d3523b8a48404.js +0 -1
  242. package/assets/esri/core/workers/chunks/b3a717b7e41f3b0180be.js +0 -1
  243. package/assets/esri/core/workers/chunks/b9743aed120acb208b13.js +0 -1
  244. package/assets/esri/core/workers/chunks/bb8a670d4a1eaa458bef.js +0 -1
  245. package/assets/esri/core/workers/chunks/d0e4dbe41fd77d00a60b.js +0 -1
  246. package/assets/esri/core/workers/chunks/d3e21ad05030bb14e844.js +0 -1
  247. package/assets/esri/core/workers/chunks/db96a2dc1879b4944cb8.js +0 -1
  248. package/assets/esri/core/workers/chunks/de4b687431b4d5cf0369.js +0 -1
  249. package/assets/esri/core/workers/chunks/e74b9b5a8ace6a4a5c38.js +0 -1
  250. package/assets/esri/core/workers/chunks/f1f9a65fbcb404a8ccf5.js +0 -1
  251. package/views/2d/engine/webgl/Geometry.js +0 -5
  252. package/views/2d/engine/webgl/TileClipper.js +0 -5
package/WebMap.js CHANGED
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.26/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"./chunks/tslib.es6.js";import{version as t}from"./kernel.js";import r from"./Map.js";import i from"./Viewpoint.js";import o from"./core/Collection.js";import a from"./core/Error.js";import s from"./core/Loadable.js";import{loadAll as n}from"./core/loadAll.js";import l from"./core/Logger.js";import{unwrap as p,isSome as m}from"./core/maybe.js";import{MultiOriginJSONMixin as u,MultiOriginJSONSupport as h}from"./core/MultiOriginJSONSupport.js";import{EsriPromiseMixin as d}from"./core/Promise.js";import{eachAlways as c}from"./core/promiseUtils.js";import{whenOnce as y}from"./core/reactiveUtils.js";import{urlToObject as w,isDataProtocol as g,dataComponents as f,addQueryParameter as b}from"./core/urlUtils.js";import{property as _}from"./core/accessorSupport/decorators/property.js";import"./core/accessorSupport/ensureType.js";import"./core/arrayUtils.js";import{reader as v}from"./core/accessorSupport/decorators/reader.js";import{subclass as I}from"./core/accessorSupport/decorators/subclass.js";import{writer as A}from"./core/accessorSupport/decorators/writer.js";import{updateOrigins as S}from"./core/accessorSupport/originUtils.js";import{readLoadable as j}from"./core/accessorSupport/read.js";import U from"./geometry/SpatialReference.js";import{equals as P}from"./geometry/support/spatialReferenceUtils.js";import{geographicToWebMercator as O,webMercatorToGeographic as L}from"./geometry/support/webMercatorUtils.js";import{isServerOrServicesAGOLUrl as V}from"./layers/support/arcgisLayerUrl.js";import{isFeatureServiceLayer as R,isFeatureCollectionLayer as F}from"./layers/support/layerUtils.js";import T from"./networks/UtilityNetwork.js";import W from"./portal/Portal.js";import k from"./portal/PortalItem.js";import{removeTypeKeyword as N,addTypeKeyword as C,hasTypeKeyword as M,TypeKeyword as x}from"./portal/support/portalItemUtils.js";import{project as E}from"./rest/geometryService/project.js";import B from"./rest/support/ProjectParameters.js";import{hasDeveloperBasemapLayer as G,isDeveloperBasemapLayer as J,findSpatialReference as D}from"./support/basemapUtils.js";import K from"./support/MapFloorInfo.js";import $ from"./webdoc/GeotriggersInfo.js";import z from"./webdoc/RangeInfo.js";import q from"./webdoc/Widgets.js";import{getOptimalThumbnailSize as H}from"./webdoc/support/thumbnailUtils.js";import{getLayerJSON as Q}from"./webdoc/support/writeUtils.js";import X from"./webmap/ApplicationProperties.js";import Y from"./webmap/Bookmark.js";import Z from"./webmap/InitialViewProperties.js";import{Version as ee}from"./webmap/Version.js";import te from"./webmap/background/ColorBackground.js";const re=new ee(2,26),ie="Web Map",oe=o.ofType(Y),ae=o.ofType(T),se=new Map;se.set("image/jpeg","jpeg"),se.set("image/jpg","jpg"),se.set("image/png","png"),se.set("image/gif","gif");const ne="ArcGIS Pro",le=x.JSAPI,pe="CollectorDisabled",me="Collector",ue="Data Editing",he="OfflineDisabled",de="Offline",ce="Workforce Project",ye="Workforce Worker",we="Workforce Dispatcher",ge="Offline Map Areas",fe="FieldMapsDisabled",be=x.DEVELOPER_BASEMAP,_e="UtilityNetwork",ve=["NatGeo_World_Map","Ocean_Basemap","USA_Topo_Maps","World_Imagery","World_Street_Map","World_Terrain_Base","World_Topo_Map","World_Hillshade","Canvas/World_Light_Gray_Base","Canvas/World_Light_Gray_Reference","Canvas/World_Dark_Gray_Base","Canvas/World_Dark_Gray_Reference","Ocean/World_Ocean_Base","Ocean/World_Ocean_Reference","Reference/World_Boundaries_and_Places","Reference/World_Reference_Overlay","Reference/World_Transportation"].map((e=>e.toLowerCase()));let Ie=class extends(u(s.LoadableMixin(d(r)))){constructor(e){super(e),this._isAuthoringAppSetByUser=!1,this._isAuthoringAppVersionSetByUser=!1,this._thumbnailFilename=null,this._updateFromPromise=null,this._resourceReferences={portalItem:null,paths:[]},this.applicationProperties=null,this.bookmarks=new oe,this.floorInfo=null,this.geotriggersInfo=null,this.initialViewProperties=new Z,this.portalItem=null,this.presentation=null,this.sourceVersion=null,this.widgets=null,this.utilityNetworks=null,this.authoringApp=this.authoringAppVersion=null,this._isAuthoringAppSetByUser=this._isAuthoringAppVersionSetByUser=!1}destroy(){const e=this.portalItem;this.portalItem=null,e?.destroy()}initialize(){if(this.when().catch((e=>{l.getLogger(this.declaredClass).error("#load()","Failed to load web map",e)})),this.resourceInfo){let t;try{t=this._validateJSON(this.resourceInfo)}catch(e){return void this.addResolvingPromise(Promise.reject(e))}this.read(t)}}set authoringApp(e){this._isAuthoringAppSetByUser=!0,this._set("authoringApp",e)}writeAuthoringApp(e,t){e&&this._isAuthoringAppSetByUser?t.authoringApp=e:t.authoringApp=le}set authoringAppVersion(e){this._isAuthoringAppVersionSetByUser=!0,this._set("authoringAppVersion",e)}writeAuthoringAppVersion(e,r){e&&this._isAuthoringAppVersionSetByUser?r.authoringAppVersion=e:r.authoringAppVersion=t}readInitialViewProperties(e,t){const r=new Z;t.background&&(r.background=te.fromJSON(t.background));const o=t.initialState?.viewpoint;if(o){if(o.rotation){ee.parse(t.version||"","webmap").lessThan(2,20)&&t.authoringApp===ne&&(o.rotation*=-1)}r.viewpoint=i.fromJSON(o)}return t.mapRangeInfo&&(r.rangeInfo=z.fromJSON(t.mapRangeInfo)),t.spatialReference&&(r.spatialReference=U.fromJSON(t.spatialReference)),r}writeInitialViewProperties(e,t,r,i){if(!e)return;const o=e.background;o&&o.color&&(t.background=o.write({},i)),e.viewpoint&&(t.initialState={viewpoint:e.viewpoint.write({},i)}),e.rangeInfo&&(t.mapRangeInfo=e.rangeInfo.toJSON(i)),e.spatialReference&&(t.spatialReference=e.spatialReference.write({},i))}writeLayers(e,t,r,i){t[r]=this._writeLayers(e,i,"operational-layers")}readSourceVersion(e,t){const[r,i]=t.version.split(".");return new ee(parseInt(r,10),parseInt(i,10))}writeSourceVersion(e,t,r){t[r]=`${re.major}.${re.minor}`}writeTables(e,t,r,i){const o=this._writeLayers(e,i,"tables");o.length&&(t[r]=o)}get thumbnailUrl(){return this.portalItem&&this.portalItem.thumbnailUrl||null}set thumbnailUrl(e){e?(this._override("thumbnailUrl",e),this._thumbnailFilename=this._generateCustomThumbnailFilename(e)):this._clearThumbnailOverride()}load(e){return this.addResolvingPromise(this._loadFromSource()),Promise.resolve(this)}loadAll(){return n(this,(e=>{e(this.ground,this.basemap,this.layers,this.tables)}))}read(e,t){t={...t,origin:"web-map"};const r=this._getAuthoringPropsState();j(this,e,(t=>super.read(e,t)),t),this._restoreAuthoringPropsFromState(r)}write(e,t){if("loaded"!==this.loadStatus){const e=new a("webmap:not-loaded","Web map must be loaded before it can be serialized");throw l.getLogger(this.declaredClass).error("#toJSON()","Web map must be loaded before it can be serialized",this.loadError||this.loadStatus),e}return this._removeDanglingLayerRefs(),t={...t,origin:"web-map",restrictedWebMapWriting:!0,webmap:this},super.write(e,t)}async save(e){e=e||{},this._validateItem();const t=import("./webdoc/support/saveUtils.js");await this._updateFromPromise,await this.load(),await this._loadLayerContainers(),await this._beforeSave(),await this._validateMap();const r=this.portalItem,i=w(r.itemUrl),o={origin:"web-map",messages:[],writtenProperties:[],url:i,portal:r.portal||W.getDefault(),portalItem:r,verifyItemRelativeUrls:i?{rootPath:i.path,writtenUrls:[]}:null,blockedRelativeUrls:[],resources:{toAdd:[],toUpdate:[],toKeep:[],pendingOperations:[]}},a=this.write({},o);return await Promise.all(o.resources.pendingOperations),this._validateJSONForWriting(o,e),await this._updateItemProperties(r),await this._updateItem(r,a,o),await Promise.all([this._updateItemThumbnail(),t.then((({saveResources:e})=>e(this._resourceReferences,o,null)))]),r}async saveAs(e,t){t=t||{};const r=this._getPortalItem(e),i=import("./webdoc/support/saveUtils.js");await this._updateFromPromise,await this.load(),await this._loadLayerContainers(),await this._beforeSave(),await this._validateMap();const o={origin:"web-map",messages:[],writtenProperties:[],url:null,portal:r.portal,portalItem:r,blockedRelativeUrls:[],resources:{toAdd:[],toUpdate:[],toKeep:[],pendingOperations:[]}},a=this.write({},o);await Promise.all(o.resources.pendingOperations),this._validateJSONForWriting(o,t),await this._updateItemPropertiesForSaveAs(r);const s=this._getThumbnailState();return await this._createItem(r,a,o,t),this._restoreThumbnailFromState(s),await Promise.all([this._updateItemThumbnail(),i.then((({saveResources:e})=>e(this._resourceReferences,o,null)))]),r}async updateFrom(e,t){const r=this._updateFromInternal(e,t);this._updateFromPromise=r,await r;r===this._updateFromPromise&&(this._updateFromPromise=null)}getLayerJSONFromResourceInfo(e){const t=this.resourceInfo;return this._collectAllLayersJSON([...t?.baseMap?.baseMapLayers||[],...t?.operationalLayers||[],...this.basemap?.resourceInfo?.data?.baseMapLayers||[]]).find((t=>t.id===e.id))}_collectAllLayersJSON(e){return e.reduce(((e,t)=>(e.push(t),"GroupLayer"===t.layerType&&(e=e.concat(this._collectAllLayersJSON(t.layers||[]))),e)),[])}_writeLayers(e,t,r){t={...t,layerContainerType:r};return e.map((e=>p(Q(e,"tables"===r?null:this.getLayerJSONFromResourceInfo(e),t)))).filter(Boolean).toArray()}_loadFromSource(){return this.resourceInfo?this._loadFromJSON(this.resourceInfo,{origin:"web-map"}):this.portalItem&&this.portalItem.id?this._loadFromItem(this.portalItem):Promise.resolve()}_loadFromItem(e){return e.load().catch((e=>{throw new a("webmap:load-portal-item","Failed to load portal item",{error:e})})).then((()=>{if("Web Map"!==e.type)throw new a("webmap:invalid-portal-item","Invalid portal item type '${type}', expected 'Web Map'",{type:e.type})})).then((()=>e.fetchData())).then((t=>(this.resourceInfo=t,this._readAndLoadFromJSON(t,{origin:"web-map",portal:e.portal||W.getDefault()})))).then((()=>this._computeInitialViewpoint()))}_readAndLoadFromJSON(e,t){const r=this._validateJSON(e);return this.read(r,t),this._loadFromJSON(r,t)}_validateJSON(e){const t=ee.parse(e.version||"","webmap");return re.validate(t),e.version=`${t.major}.${t.minor}`,e}_loadFromJSON(e,t){const r={context:{...t,layerContainerType:"operational-layers"}};return this.portalItem&&(r.context.portal=this.portalItem.portal||W.getDefault()),import("./layers/support/layersCreator.js").then((({populateOperationalLayers:t})=>{const i=[],o=e.operationalLayers;o&&o.length&&i.push(t(this.layers,o,r));const a={...r,context:{...r.context,layerContainerType:"tables"},defaultLayerType:"ArcGISFeatureLayer"},s=e.tables;return s&&s.length&&i.push(t(this.tables,s,a)),c(i).then((()=>{}))}))}async _computeInitialViewpoint(){let e=this.initialViewProperties;const t=e?.viewpoint?.targetGeometry;if(t)return;const r=await this._getExtentFromItem();r&&(e=e?e.clone():new Z,e.viewpoint=new i,e.viewpoint.targetGeometry=r,this.initialViewProperties=e)}async _getExtentFromItem(){const e=this.initialViewProperties?.spatialReference,t=this.portalItem?.extent;if(e&&t){if(e.isWGS84)return t.clone();if(e.isWebMercator)return O(t);return(await import("./portal/support/geometryServiceUtils.js")).getGeometryServiceURL(this.portalItem).then((r=>{const i=new B;return i.geometries=[t],i.outSpatialReference=e,E(r,i)})).then((e=>e[0])).catch((e=>(l.getLogger(this.declaredClass).error("Error projecting item's extent:",e),null)))}return null}_removeDanglingLayerRefs(){const e=this.applicationProperties,t=e&&e.viewing&&e.viewing.search,r=e=>this.allLayers.some((t=>t.id===e));t&&t.layers&&(t.layers=t.layers.filter((e=>r(e.id)))),t&&t.tables&&(t.tables=t.tables.filter((e=>this.tables.some((t=>t.id===e.id)))));const i=e&&e.editing&&e.editing.locationTracking;i&&i.info&&!r(i.info.layerId)&&(e.editing=null);const o=this.presentation&&this.presentation.slides;o&&o.forEach((e=>{e.visibleLayers&&(e.visibleLayers=e.visibleLayers.filter((e=>r(e.id))))}))}async _validateMap(){if(!this.basemap?.baseLayers.length)throw new a("webmap:save","Map does not have a valid basemap with a base layer.");let e=null;if(await y((()=>{const t=D(this.initialViewProperties,this.basemap);return e=t.spatialReference,!t.updating})),!P(e,this.initialViewProperties.spatialReference))throw new a("webmap:save","The spatial reference of the basemap is not compatible with the one from the map.",{expected:this.initialViewProperties.spatialReference,actual:e})}_validateItem(){if(!this.portalItem)throw l.getLogger(this.declaredClass).error("save: requires the portalItem property to be set"),new a("webmap:portal-item-not-set","Portal item to save to has not been set on the WebMap");this._validateItemType(this.portalItem)}_validateItemType(e){if(e.type!==ie)throw new a("webmap:portal-item-wrong-type",`Portal item needs to have type "${ie}"`)}_loadLayerContainers(){const e=[];return this.basemap&&e.push(this.basemap.load()),this.ground&&e.push(this.ground.load()),c(e).then((()=>{}))}async _beforeSave(){const e=[];for(const t of this.allLayers)if("beforeSave"in t&&"function"==typeof t.beforeSave){const r=t.beforeSave();r&&e.push(r)}await c(e)}_loadAllLayers(){const e=this._getAllLayersAndTables().map((e=>e.load()));return c(e).then((()=>{}))}_getAllLayersAndTables(){return this.allLayers.concat(this.allTables)}_validateJSONForWriting(e,t){let r=(e.messages?e.messages:[]).filter((e=>"error"===e.type)).map((e=>new a(e.name,e.message,e.details)));if(e.blockedRelativeUrls&&(r=r.concat(e.blockedRelativeUrls.map((e=>new a("url:unsupported",`Relative url '${e}' is not supported in Web Map`))))),t.ignoreUnsupported&&(r=r.filter((e=>"layer:unsupported"!==e.name&&"symbol:unsupported"!==e.name&&"symbol-layer:unsupported"!==e.name&&"property:unsupported"!==e.name&&"url:unsupported"!==e.name))),r.length>0)throw new a("webmap:save","Failed to save webmap due to unsupported or invalid content. See 'details.errors' for more detailed information",{errors:r})}async _updateItemProperties(e){e.extent=await this._getWGS84Extent(this.initialViewProperties.viewpoint.targetGeometry),await this._updateTypeKeywords(e)}async _updateItemPropertiesForSaveAs(e){N(e,pe),N(e,fe),N(e,x.METADATA),N(e,he),N(e,ge),N(e,we),N(e,ce),N(e,ye),await this._updateItemProperties(e)}async _getWGS84Extent(e){const t=e.clone().normalize();let r;if(t.length>1)for(const i of t)r?i.width>r.width&&(r=i):r=i;else r=t[0];return this._projectToWGS84(r)}async _projectToWGS84(e){const t=e.spatialReference;if(t.isWGS84)return e.clone();if(t.isWebMercator)return L(e);const r=await import("./portal/support/geometryServiceUtils.js"),i=await r.getGeometryServiceURL(this.portalItem),o=new B;o.geometries=[e],o.outSpatialReference=U.WGS84;return(await E(i,o))[0]}async _updateTypeKeywords(e){C(e,le),await this._loadAllLayers(),this._evalCollectorKeyword(e),this._evalDataEditingKeyword(e),this._evalOfflineKeyword(e),this._evalDeveloperBasemapKeyword(e),this._evalUtilityNetworkKeyword(e),e.typeKeywords&&(e.typeKeywords=e.typeKeywords.filter(((e,t,r)=>r.indexOf(e)===t)))}_evalCollectorKeyword(e){M(e,pe)||M(e,ce)||M(e,ye)||M(e,we)||!this._hasEditableFeatureLayer()?N(e,me):C(e,me)}_evalDataEditingKeyword(e){this._hasEditableFeatureLayer()?C(e,ue):N(e,ue)}_evalOfflineKeyword(e){!M(e,he)&&this._isOfflineCapableMap()?C(e,de):N(e,de)}_evalDeveloperBasemapKeyword(e){G(this.basemap)?C(e,be):N(e,be)}_evalUtilityNetworkKeyword(e){this.utilityNetworks?.length?C(e,_e):N(e,_e)}_hasEditableFeatureLayer(){return this._getAllLayersAndTables().some((e=>e.loaded&&R(e)&&e.capabilities.operations.supportsEditing&&e.editingEnabled))}_isOfflineCapableMap(){return this._getAllLayersAndTables().filter((e=>"group"!==e.type)).every((e=>e.loaded&&this._isOfflineCapableLayer(e)))}_isFeatureCollectionLike(e){return F(e)||"map-notes"===e.type||"route"===e.type}_isOfflineCapableLayer(e){return R(e)&&e.capabilities.operations.supportsSync||this._isFeatureCollectionLike(e)&&!e.portalItem||("tile"===e.type||"vector-tile"===e.type)&&(e.capabilities.operations.supportsExportTiles||this._isExportableAGOLTileLayer(e)||J(e))&&e.spatialReference.equals(this.initialViewProperties.spatialReference)}_isExportableAGOLTileLayer(e){return"tile"===e.type&&(V(e.url)&&ve.some((t=>e.url?.toLowerCase().includes("/"+t+"/"))))}async _updateItem(e,t,r){await e.update({data:t}),this._syncUpInstanceWithItem(e,t,r)}async _createItem(e,t,r,i){const o=this.portalItem,s=!!(o&&o.id&&o.portal.user),n=e.portal;if(await n.signIn(),!await this._canCopyItem(o,s,n))throw new a("webmap:save-as-copy-not-allowed","Owner of this map does not allow others to save a copy");await(n.user?.addItem({item:e,folder:i.folder,data:t})),this.portalItem=e,this._syncUpInstanceWithItem(e,t,r)}async _canCopyItem(e,t,r){return!(m(e)&&e.id&&e.typeKeywords&&e.typeKeywords.includes("useOnly"))||e.portal.portalHostname===r.portalHostname&&(t||await e.reload(),"admin"===e.itemControl||"update"===e.itemControl)}_syncUpInstanceWithItem(e,t,r){h.prototype.read.call(this,{version:t.version,authoringApp:t.authoringApp,authoringAppVersion:t.authoringAppVersion},{origin:"web-map",ignoreDefaults:!0,url:e.itemUrl&&w(e.itemUrl)}),S(r),this.resourceInfo=t}async _updateItemThumbnail(){this.thumbnailUrl&&this._isOverridden("thumbnailUrl")&&(await(this.portalItem?.updateThumbnail({thumbnail:this.thumbnailUrl,filename:this._thumbnailFilename})),this._clearThumbnailOverride())}_getPortalItem(e){let t=k.from(e);return t.id&&(t=t.clone(),t.id=null),t.type||(t.type=ie),t.portal||(t.portal=W.getDefault()),this._validateItemType(t),t}async _updateFromInternal(e,t){if(t=t||{},await y((()=>e.ready)),this._updateInitialViewProperties(e,t),e.map===this)for(const r of e.allLayerViews)for(const e of["visible","featureEffect"])e in r&&e in r.layer&&r._isOverridden(e)&&(r.layer[e]=r[e]);await this._updateThumbnailUrl(e,t)}_updateInitialViewProperties(e,t){if(t.backgroundExcluded||(this.initialViewProperties.background=e.background?.clone()),this.initialViewProperties.spatialReference=e.spatialReference?.clone(),t.viewpointExcluded||(this.initialViewProperties.viewpoint=new i({rotation:e.rotation,scale:t.scalePreserved?e.scale:null,targetGeometry:this._getViewExtent(e)})),!t.widgetsExcluded)for(const r of e.persistableViewModels)r.updateWebDocument(this)}_getViewExtent(e){const t=e.center.clone().normalize(),r=e.extent.clone(),i=r.width/2;return r.xmin=t.x-i,r.xmax=t.x+i,r}async _updateThumbnailUrl(e,t){if(t.thumbnailExcluded)return;const r=H(e,t.thumbnailSize),i=await e.takeScreenshot({format:"png",width:r.width,height:r.height});this._setAutoGeneratedThumbnail(i.dataUrl)}_setAutoGeneratedThumbnail(e){this.thumbnailUrl=e,this._thumbnailFilename=null}_clearThumbnailOverride(){this._clearOverride("thumbnailUrl"),this.clear("thumbnailUrl","user"),this._thumbnailFilename=null}_generateCustomThumbnailFilename(e){if(g(e)){const t=f(e),r=t&&t.mediaType,i=r&&se.get(r.toLowerCase())||null,o=`thumbnail${Date.now()}`;return i?`${o}.${i}`:o}return null}_getThumbnailState(){let e=this.thumbnailUrl;return e&&(e=this._isOverridden("thumbnailUrl")?e:b(e,"w","8192")),{thumbnailUrl:e,filename:this._thumbnailFilename}}_restoreThumbnailFromState(e){this.thumbnailUrl=e.thumbnailUrl,this._thumbnailFilename=e.filename}_getAuthoringPropsState(){return{authoringApp:this.authoringApp,authoringAppVersion:this.authoringAppVersion,isAuthoringAppSetByUser:this._isAuthoringAppSetByUser,isAuthoringAppVersionSetByUser:this._isAuthoringAppVersionSetByUser}}_restoreAuthoringPropsFromState(e){e.isAuthoringAppSetByUser?this.authoringApp=e.authoringApp:this._isAuthoringAppSetByUser=!1,e.isAuthoringAppVersionSetByUser?this.authoringAppVersion=e.authoringAppVersion:this._isAuthoringAppVersionSetByUser=!1}static fromJSON(e){const t=e;if(!t)throw new a("webmap:empty-resource","Expected a JSON resource but got nothing");return new this({resourceInfo:t})}};Ie.VERSION=re,e([_({type:X,json:{write:!0}})],Ie.prototype,"applicationProperties",void 0),e([_({type:String,json:{write:{allowNull:!0,ignoreOrigin:!0}}})],Ie.prototype,"authoringApp",null),e([A("authoringApp")],Ie.prototype,"writeAuthoringApp",null),e([_({type:String,json:{write:{allowNull:!0,ignoreOrigin:!0}}})],Ie.prototype,"authoringAppVersion",null),e([A("authoringAppVersion")],Ie.prototype,"writeAuthoringAppVersion",null),e([_({json:{read:{source:"baseMap"},write:{target:"baseMap"}}})],Ie.prototype,"basemap",void 0),e([_({type:oe,json:{write:{overridePolicy:e=>({enabled:!!(e&&e.length>0),ignoreOrigin:!0})}}})],Ie.prototype,"bookmarks",void 0),e([_({type:K,json:{read:{source:"mapFloorInfo"},write:{target:"mapFloorInfo"}}})],Ie.prototype,"floorInfo",void 0),e([_({type:$,json:{write:!0}})],Ie.prototype,"geotriggersInfo",void 0),e([_({type:Z,nonNullable:!0,json:{read:{source:["background","initialState.viewpoint","mapRangeInfo","spatialReference"]},write:{ignoreOrigin:!0,target:{background:{type:te},"initialState.viewpoint":{type:i},mapRangeInfo:{type:z},spatialReference:{type:U}}}}})],Ie.prototype,"initialViewProperties",void 0),e([v("initialViewProperties")],Ie.prototype,"readInitialViewProperties",null),e([A("initialViewProperties")],Ie.prototype,"writeInitialViewProperties",null),e([_({json:{read:!1,write:{target:"operationalLayers",ignoreOrigin:!0}}})],Ie.prototype,"layers",void 0),e([A("layers")],Ie.prototype,"writeLayers",null),e([_({type:k})],Ie.prototype,"portalItem",void 0),e([_({json:{write:!0}})],Ie.prototype,"presentation",void 0),e([_()],Ie.prototype,"resourceInfo",void 0),e([_({readOnly:!0,type:ee,json:{read:{source:"version"},write:{allowNull:!0,ignoreOrigin:!0,target:"version",isRequired:!0}}})],Ie.prototype,"sourceVersion",void 0),e([v("sourceVersion")],Ie.prototype,"readSourceVersion",null),e([A("sourceVersion")],Ie.prototype,"writeSourceVersion",null),e([_({json:{read:!1,write:{ignoreOrigin:!0}}})],Ie.prototype,"tables",void 0),e([A("tables")],Ie.prototype,"writeTables",null),e([_()],Ie.prototype,"thumbnailUrl",null),e([_({type:q,json:{write:!0}})],Ie.prototype,"widgets",void 0),e([_({type:ae,json:{read:!0,write:!0}})],Ie.prototype,"utilityNetworks",void 0),Ie=e([I("esri.WebMap")],Ie);const Ae=Ie;export{Ae as default};
5
+ import{_ as e}from"./chunks/tslib.es6.js";import{version as t}from"./kernel.js";import r from"./Map.js";import i from"./Viewpoint.js";import o from"./core/Collection.js";import a from"./core/Error.js";import s from"./core/Loadable.js";import{loadAll as n}from"./core/loadAll.js";import l from"./core/Logger.js";import{unwrap as p,isSome as m}from"./core/maybe.js";import{MultiOriginJSONMixin as u,MultiOriginJSONSupport as h}from"./core/MultiOriginJSONSupport.js";import{EsriPromiseMixin as c}from"./core/Promise.js";import{eachAlways as d}from"./core/promiseUtils.js";import{whenOnce as y}from"./core/reactiveUtils.js";import{urlToObject as w,isDataProtocol as g,dataComponents as f,addQueryParameter as b}from"./core/urlUtils.js";import{property as _}from"./core/accessorSupport/decorators/property.js";import"./core/accessorSupport/ensureType.js";import"./core/arrayUtils.js";import{reader as v}from"./core/accessorSupport/decorators/reader.js";import{subclass as I}from"./core/accessorSupport/decorators/subclass.js";import{writer as A}from"./core/accessorSupport/decorators/writer.js";import{updateOrigins as S}from"./core/accessorSupport/originUtils.js";import{readLoadable as j}from"./core/accessorSupport/read.js";import U from"./geometry/SpatialReference.js";import{equals as P}from"./geometry/support/spatialReferenceUtils.js";import{geographicToWebMercator as O,webMercatorToGeographic as L}from"./geometry/support/webMercatorUtils.js";import{isServerOrServicesAGOLUrl as V}from"./layers/support/arcgisLayerUrl.js";import{isFeatureServiceLayer as R,isFeatureCollectionLayer as F}from"./layers/support/layerUtils.js";import T from"./networks/UtilityNetwork.js";import W from"./portal/Portal.js";import k from"./portal/PortalItem.js";import{removeTypeKeyword as N,addTypeKeyword as C,hasTypeKeyword as M,TypeKeyword as x}from"./portal/support/portalItemUtils.js";import{project as E}from"./rest/geometryService/project.js";import B from"./rest/support/ProjectParameters.js";import{hasDeveloperBasemapLayer as G,isDeveloperBasemapLayer as J,findSpatialReference as D}from"./support/basemapUtils.js";import K from"./support/MapFloorInfo.js";import $ from"./webdoc/GeotriggersInfo.js";import z from"./webdoc/RangeInfo.js";import q from"./webdoc/Widgets.js";import{getOptimalThumbnailSize as H}from"./webdoc/support/thumbnailUtils.js";import{getLayerJSON as Q}from"./webdoc/support/writeUtils.js";import X from"./webmap/ApplicationProperties.js";import Y from"./webmap/Bookmark.js";import Z from"./webmap/InitialViewProperties.js";import{Version as ee}from"./webmap/Version.js";import te from"./webmap/background/ColorBackground.js";const re=new ee(2,26),ie="Web Map",oe=o.ofType(Y),ae=o.ofType(T),se=new Map;se.set("image/jpeg","jpeg"),se.set("image/jpg","jpg"),se.set("image/png","png"),se.set("image/gif","gif");const ne="ArcGIS Pro",le=x.JSAPI,pe="CollectorDisabled",me="Collector",ue="Data Editing",he="OfflineDisabled",ce="Offline",de="Workforce Project",ye="Workforce Worker",we="Workforce Dispatcher",ge="Offline Map Areas",fe="FieldMapsDisabled",be=x.DEVELOPER_BASEMAP,_e="UtilityNetwork",ve=["NatGeo_World_Map","Ocean_Basemap","USA_Topo_Maps","World_Imagery","World_Street_Map","World_Terrain_Base","World_Topo_Map","World_Hillshade","Canvas/World_Light_Gray_Base","Canvas/World_Light_Gray_Reference","Canvas/World_Dark_Gray_Base","Canvas/World_Dark_Gray_Reference","Ocean/World_Ocean_Base","Ocean/World_Ocean_Reference","Reference/World_Boundaries_and_Places","Reference/World_Reference_Overlay","Reference/World_Transportation"].map((e=>e.toLowerCase()));let Ie=class extends(u(s.LoadableMixin(c(r)))){constructor(e){super(e),this._isAuthoringAppSetByUser=!1,this._isAuthoringAppVersionSetByUser=!1,this._thumbnailFilename=null,this._updateFromPromise=null,this._resourceReferences={portalItem:null,paths:[]},this.applicationProperties=null,this.bookmarks=new oe,this.floorInfo=null,this.geotriggersInfo=null,this.initialViewProperties=new Z,this.portalItem=null,this.presentation=null,this.sourceVersion=null,this.widgets=null,this.utilityNetworks=null,this.authoringApp=this.authoringAppVersion=null,this._isAuthoringAppSetByUser=this._isAuthoringAppVersionSetByUser=!1}destroy(){const e=this.portalItem;this.portalItem=null,e?.destroy()}initialize(){if(this.when().catch((e=>{l.getLogger(this.declaredClass).error("#load()","Failed to load web map",e)})),this.resourceInfo){let t;try{t=this._validateJSON(this.resourceInfo)}catch(e){return void this.addResolvingPromise(Promise.reject(e))}this.read(t)}}set authoringApp(e){this._isAuthoringAppSetByUser=!0,this._set("authoringApp",e)}writeAuthoringApp(e,t){e&&this._isAuthoringAppSetByUser?t.authoringApp=e:t.authoringApp=le}set authoringAppVersion(e){this._isAuthoringAppVersionSetByUser=!0,this._set("authoringAppVersion",e)}writeAuthoringAppVersion(e,r){e&&this._isAuthoringAppVersionSetByUser?r.authoringAppVersion=e:r.authoringAppVersion=t}readInitialViewProperties(e,t){const r=new Z;t.background&&(r.background=te.fromJSON(t.background));const o=t.initialState?.viewpoint;if(o){if(o.rotation){ee.parse(t.version||"","webmap").lessThan(2,20)&&t.authoringApp===ne&&(o.rotation*=-1)}r.viewpoint=i.fromJSON(o)}return t.mapRangeInfo&&(r.rangeInfo=z.fromJSON(t.mapRangeInfo)),t.spatialReference&&(r.spatialReference=U.fromJSON(t.spatialReference)),r}writeInitialViewProperties(e,t,r,i){if(!e)return;const o=e.background;o&&o.color&&(t.background=o.write({},i)),e.viewpoint&&(t.initialState={viewpoint:e.viewpoint.write({},i)}),e.rangeInfo&&(t.mapRangeInfo=e.rangeInfo.toJSON(i)),e.spatialReference&&(t.spatialReference=e.spatialReference.write({},i))}writeLayers(e,t,r,i){t[r]=this._writeLayers(e,i,"operational-layers")}readSourceVersion(e,t){const[r,i]=t.version.split(".");return new ee(parseInt(r,10),parseInt(i,10))}writeSourceVersion(e,t,r){t[r]=`${re.major}.${re.minor}`}writeTables(e,t,r,i){const o=this._writeLayers(e,i,"tables");o.length&&(t[r]=o)}get thumbnailUrl(){return this.portalItem&&this.portalItem.thumbnailUrl||null}set thumbnailUrl(e){e?(this._override("thumbnailUrl",e),this._thumbnailFilename=this._generateCustomThumbnailFilename(e)):this._clearThumbnailOverride()}load(e){return this.addResolvingPromise(this._loadFromSource()),Promise.resolve(this)}loadAll(){return n(this,(e=>{e(this.ground,this.basemap,this.layers,this.tables)}))}read(e,t){t={...t,origin:"web-map"};const r=this._getAuthoringPropsState();j(this,e,(t=>super.read(e,t)),t),this._restoreAuthoringPropsFromState(r)}write(e,t){if("loaded"!==this.loadStatus){const e=new a("webmap:not-loaded","Web map must be loaded before it can be serialized");throw l.getLogger(this.declaredClass).error("#toJSON()","Web map must be loaded before it can be serialized",this.loadError||this.loadStatus),e}return this._removeDanglingLayerRefs(),t={...t,origin:"web-map",restrictedWebMapWriting:!0,webmap:this},super.write(e,t)}async save(e){e=e||{},this._validateItem();const t=import("./webdoc/support/saveUtils.js");await this._updateFromPromise,await this.load(),await this._loadLayerContainers(),await this._beforeSave(),await this._validateMap();const r=this.portalItem,i=w(r.itemUrl),o={origin:"web-map",messages:[],writtenProperties:[],url:i,portal:r.portal||W.getDefault(),portalItem:r,verifyItemRelativeUrls:i?{rootPath:i.path,writtenUrls:[]}:null,blockedRelativeUrls:[],resources:{toAdd:[],toUpdate:[],toKeep:[],pendingOperations:[]}},a=this.write({},o);return await Promise.all(o.resources.pendingOperations),this._validateJSONForWriting(o,e),await this._updateItemProperties(r),await this._updateItem(r,a,o),await Promise.all([this._updateItemThumbnail(),t.then((({saveResources:e})=>e(this._resourceReferences,o,null)))]),r}async saveAs(e,t){t=t||{};const r=this._getPortalItem(e),i=import("./webdoc/support/saveUtils.js");await this._updateFromPromise,await this.load(),await this._loadLayerContainers(),await this._beforeSave(),await this._validateMap();const o={origin:"web-map",messages:[],writtenProperties:[],url:null,portal:r.portal,portalItem:r,blockedRelativeUrls:[],resources:{toAdd:[],toUpdate:[],toKeep:[],pendingOperations:[]}},a=this.write({},o);await Promise.all(o.resources.pendingOperations),this._validateJSONForWriting(o,t),await this._updateItemPropertiesForSaveAs(r);const s=this._getThumbnailState();return await this._createItem(r,a,o,t),this._restoreThumbnailFromState(s),await Promise.all([this._updateItemThumbnail(),i.then((({saveResources:e})=>e(this._resourceReferences,o,null)))]),r}async updateFrom(e,t){const r=this._updateFromInternal(e,t);this._updateFromPromise=r,await r;r===this._updateFromPromise&&(this._updateFromPromise=null)}getLayerJSONFromResourceInfo(e){const t=this.resourceInfo;return this._collectAllLayersJSON([...t?.baseMap?.baseMapLayers||[],...t?.operationalLayers||[],...this.basemap?.resourceInfo?.data?.baseMapLayers||[]]).find((t=>t.id===e.id))}_collectAllLayersJSON(e){return e.reduce(((e,t)=>(e.push(t),"GroupLayer"===t.layerType&&(e=e.concat(this._collectAllLayersJSON(t.layers||[]))),e)),[])}_writeLayers(e,t,r){t={...t,layerContainerType:r};return e.map((e=>p(Q(e,"tables"===r?null:this.getLayerJSONFromResourceInfo(e),t)))).filter(Boolean).toArray()}_loadFromSource(){return this.resourceInfo?this._loadFromJSON(this.resourceInfo,{origin:"web-map"}):this.portalItem&&this.portalItem.id?this._loadFromItem(this.portalItem):Promise.resolve()}async _loadFromItem(e){if(await e.load().catch((e=>{throw new a("webmap:load-portal-item","Failed to load portal item",{error:e})})),"Web Map"!==e.type)throw new a("webmap:invalid-portal-item",`Invalid portal item type '${e.type}', expected 'Web Map'`,{type:e.type});const t=await e.fetchData();this.resourceInfo=t;const r={origin:"web-map",url:w(e.itemUrl),portal:e.portal||W.getDefault(),portalItem:e,readResourcePaths:[]};return await this._readAndLoadFromJSON(t,r),this._resourceReferences={portalItem:e,paths:r.readResourcePaths??[]},this._computeInitialViewpoint()}_readAndLoadFromJSON(e,t){const r=this._validateJSON(e);return this.read(r,t),this._loadFromJSON(r,t)}_validateJSON(e){const t=ee.parse(e.version||"","webmap");return re.validate(t),e.version=`${t.major}.${t.minor}`,e}_loadFromJSON(e,t){const r={context:{...t,layerContainerType:"operational-layers"}};return this.portalItem&&(r.context.portal=this.portalItem.portal||W.getDefault()),import("./layers/support/layersCreator.js").then((({populateOperationalLayers:t})=>{const i=[],o=e.operationalLayers;o&&o.length&&i.push(t(this.layers,o,r));const a={...r,context:{...r.context,layerContainerType:"tables"},defaultLayerType:"ArcGISFeatureLayer"},s=e.tables;return s&&s.length&&i.push(t(this.tables,s,a)),d(i).then((()=>{}))}))}async _computeInitialViewpoint(){let e=this.initialViewProperties;const t=e?.viewpoint?.targetGeometry;if(t)return;const r=await this._getExtentFromItem();r&&(e=e?e.clone():new Z,e.viewpoint=new i,e.viewpoint.targetGeometry=r,this.initialViewProperties=e)}async _getExtentFromItem(){const e=this.initialViewProperties?.spatialReference,t=this.portalItem?.extent;if(e&&t){if(e.isWGS84)return t.clone();if(e.isWebMercator)return O(t);return(await import("./portal/support/geometryServiceUtils.js")).getGeometryServiceURL(this.portalItem).then((r=>{const i=new B;return i.geometries=[t],i.outSpatialReference=e,E(r,i)})).then((e=>e[0])).catch((e=>(l.getLogger(this.declaredClass).error("Error projecting item's extent:",e),null)))}return null}_removeDanglingLayerRefs(){const e=this.applicationProperties,t=e&&e.viewing&&e.viewing.search,r=e=>this.allLayers.some((t=>t.id===e));t&&t.layers&&(t.layers=t.layers.filter((e=>r(e.id)))),t&&t.tables&&(t.tables=t.tables.filter((e=>this.tables.some((t=>t.id===e.id)))));const i=e&&e.editing&&e.editing.locationTracking;i&&i.info&&!r(i.info.layerId)&&(e.editing=null);const o=this.presentation&&this.presentation.slides;o&&o.forEach((e=>{e.visibleLayers&&(e.visibleLayers=e.visibleLayers.filter((e=>r(e.id))))}))}async _validateMap(){if(!this.basemap?.baseLayers.length)throw new a("webmap:save","Map does not have a valid basemap with a base layer.");let e=null;if(await y((()=>{const t=D(this.initialViewProperties,this.basemap);return e=t.spatialReference,!t.updating})),!P(e,this.initialViewProperties.spatialReference))throw new a("webmap:save","The spatial reference of the basemap is not compatible with the one from the map.",{expected:this.initialViewProperties.spatialReference,actual:e})}_validateItem(){if(!this.portalItem)throw l.getLogger(this.declaredClass).error("save: requires the portalItem property to be set"),new a("webmap:portal-item-not-set","Portal item to save to has not been set on the WebMap");this._validateItemType(this.portalItem)}_validateItemType(e){if(e.type!==ie)throw new a("webmap:portal-item-wrong-type",`Portal item needs to have type "${ie}"`)}_loadLayerContainers(){const e=[];return this.basemap&&e.push(this.basemap.load()),this.ground&&e.push(this.ground.load()),d(e).then((()=>{}))}async _beforeSave(){const e=[];for(const t of this.allLayers)if("beforeSave"in t&&"function"==typeof t.beforeSave){const r=t.beforeSave();r&&e.push(r)}await d(e)}_loadAllLayers(){const e=this._getAllLayersAndTables().map((e=>e.load()));return d(e).then((()=>{}))}_getAllLayersAndTables(){return this.allLayers.concat(this.allTables)}_validateJSONForWriting(e,t){let r=(e.messages?e.messages:[]).filter((e=>"error"===e.type)).map((e=>new a(e.name,e.message,e.details)));if(e.blockedRelativeUrls&&(r=r.concat(e.blockedRelativeUrls.map((e=>new a("url:unsupported",`Relative url '${e}' is not supported in Web Map`))))),t.ignoreUnsupported&&(r=r.filter((e=>"layer:unsupported"!==e.name&&"symbol:unsupported"!==e.name&&"symbol-layer:unsupported"!==e.name&&"property:unsupported"!==e.name&&"url:unsupported"!==e.name))),r.length>0)throw new a("webmap:save","Failed to save webmap due to unsupported or invalid content. See 'details.errors' for more detailed information",{errors:r})}async _updateItemProperties(e){e.extent=await this._getWGS84Extent(this.initialViewProperties.viewpoint.targetGeometry),await this._updateTypeKeywords(e)}async _updateItemPropertiesForSaveAs(e){N(e,pe),N(e,fe),N(e,x.METADATA),N(e,he),N(e,ge),N(e,we),N(e,de),N(e,ye),await this._updateItemProperties(e)}async _getWGS84Extent(e){const t=e.clone().normalize();let r;if(t.length>1)for(const i of t)r?i.width>r.width&&(r=i):r=i;else r=t[0];return this._projectToWGS84(r)}async _projectToWGS84(e){const t=e.spatialReference;if(t.isWGS84)return e.clone();if(t.isWebMercator)return L(e);const r=await import("./portal/support/geometryServiceUtils.js"),i=await r.getGeometryServiceURL(this.portalItem),o=new B;o.geometries=[e],o.outSpatialReference=U.WGS84;return(await E(i,o))[0]}async _updateTypeKeywords(e){C(e,le),await this._loadAllLayers(),this._evalCollectorKeyword(e),this._evalDataEditingKeyword(e),this._evalOfflineKeyword(e),this._evalDeveloperBasemapKeyword(e),this._evalUtilityNetworkKeyword(e),e.typeKeywords&&(e.typeKeywords=e.typeKeywords.filter(((e,t,r)=>r.indexOf(e)===t)))}_evalCollectorKeyword(e){M(e,pe)||M(e,de)||M(e,ye)||M(e,we)||!this._hasEditableFeatureLayer()?N(e,me):C(e,me)}_evalDataEditingKeyword(e){this._hasEditableFeatureLayer()?C(e,ue):N(e,ue)}_evalOfflineKeyword(e){!M(e,he)&&this._isOfflineCapableMap()?C(e,ce):N(e,ce)}_evalDeveloperBasemapKeyword(e){G(this.basemap)?C(e,be):N(e,be)}_evalUtilityNetworkKeyword(e){this.utilityNetworks?.length?C(e,_e):N(e,_e)}_hasEditableFeatureLayer(){return this._getAllLayersAndTables().some((e=>e.loaded&&R(e)&&e.capabilities.operations.supportsEditing&&e.editingEnabled))}_isOfflineCapableMap(){return this._getAllLayersAndTables().filter((e=>"group"!==e.type)).every((e=>e.loaded&&this._isOfflineCapableLayer(e)))}_isFeatureCollectionLike(e){return F(e)||"map-notes"===e.type||"route"===e.type}_isOfflineCapableLayer(e){return R(e)&&e.capabilities.operations.supportsSync||this._isFeatureCollectionLike(e)&&!e.portalItem||("tile"===e.type||"vector-tile"===e.type)&&(e.capabilities.operations.supportsExportTiles||this._isExportableAGOLTileLayer(e)||J(e))&&e.spatialReference.equals(this.initialViewProperties.spatialReference)}_isExportableAGOLTileLayer(e){return"tile"===e.type&&(V(e.url)&&ve.some((t=>e.url?.toLowerCase().includes("/"+t+"/"))))}async _updateItem(e,t,r){await e.update({data:t}),this._syncUpInstanceWithItem(e,t,r)}async _createItem(e,t,r,i){const o=this.portalItem,s=!!(o&&o.id&&o.portal.user),n=e.portal;if(await n.signIn(),!await this._canCopyItem(o,s,n))throw new a("webmap:save-as-copy-not-allowed","Owner of this map does not allow others to save a copy");await(n.user?.addItem({item:e,folder:i.folder,data:t})),this.portalItem=e,this._syncUpInstanceWithItem(e,t,r)}async _canCopyItem(e,t,r){return!(m(e)&&e.id&&e.typeKeywords&&e.typeKeywords.includes("useOnly"))||e.portal.portalHostname===r.portalHostname&&(t||await e.reload(),"admin"===e.itemControl||"update"===e.itemControl)}_syncUpInstanceWithItem(e,t,r){h.prototype.read.call(this,{version:t.version,authoringApp:t.authoringApp,authoringAppVersion:t.authoringAppVersion},{origin:"web-map",ignoreDefaults:!0,url:e.itemUrl&&w(e.itemUrl)}),S(r),this.resourceInfo=t}async _updateItemThumbnail(){this.thumbnailUrl&&this._isOverridden("thumbnailUrl")&&(await(this.portalItem?.updateThumbnail({thumbnail:this.thumbnailUrl,filename:this._thumbnailFilename})),this._clearThumbnailOverride())}_getPortalItem(e){let t=k.from(e);return t.id&&(t=t.clone(),t.id=null),t.type||(t.type=ie),t.portal||(t.portal=W.getDefault()),this._validateItemType(t),t}async _updateFromInternal(e,t){if(t=t||{},await y((()=>e.ready)),this._updateInitialViewProperties(e,t),e.map===this)for(const r of e.allLayerViews)for(const e of["visible","featureEffect"])e in r&&e in r.layer&&r._isOverridden(e)&&(r.layer[e]=r[e]);await this._updateThumbnailUrl(e,t)}_updateInitialViewProperties(e,t){if(t.backgroundExcluded||(this.initialViewProperties.background=e.background?.clone()),this.initialViewProperties.spatialReference=e.spatialReference?.clone(),t.viewpointExcluded||(this.initialViewProperties.viewpoint=new i({rotation:e.rotation,scale:t.scalePreserved?e.scale:null,targetGeometry:this._getViewExtent(e)})),!t.widgetsExcluded)for(const r of e.persistableViewModels)r.updateWebDocument(this)}_getViewExtent(e){const t=e.center.clone().normalize(),r=e.extent.clone(),i=r.width/2;return r.xmin=t.x-i,r.xmax=t.x+i,r}async _updateThumbnailUrl(e,t){if(t.thumbnailExcluded)return;const r=H(e,t.thumbnailSize),i=await e.takeScreenshot({format:"png",width:r.width,height:r.height});this._setAutoGeneratedThumbnail(i.dataUrl)}_setAutoGeneratedThumbnail(e){this.thumbnailUrl=e,this._thumbnailFilename=null}_clearThumbnailOverride(){this._clearOverride("thumbnailUrl"),this.clear("thumbnailUrl","user"),this._thumbnailFilename=null}_generateCustomThumbnailFilename(e){if(g(e)){const t=f(e),r=t&&t.mediaType,i=r&&se.get(r.toLowerCase())||null,o=`thumbnail${Date.now()}`;return i?`${o}.${i}`:o}return null}_getThumbnailState(){let e=this.thumbnailUrl;return e&&(e=this._isOverridden("thumbnailUrl")?e:b(e,"w","8192")),{thumbnailUrl:e,filename:this._thumbnailFilename}}_restoreThumbnailFromState(e){this.thumbnailUrl=e.thumbnailUrl,this._thumbnailFilename=e.filename}_getAuthoringPropsState(){return{authoringApp:this.authoringApp,authoringAppVersion:this.authoringAppVersion,isAuthoringAppSetByUser:this._isAuthoringAppSetByUser,isAuthoringAppVersionSetByUser:this._isAuthoringAppVersionSetByUser}}_restoreAuthoringPropsFromState(e){e.isAuthoringAppSetByUser?this.authoringApp=e.authoringApp:this._isAuthoringAppSetByUser=!1,e.isAuthoringAppVersionSetByUser?this.authoringAppVersion=e.authoringAppVersion:this._isAuthoringAppVersionSetByUser=!1}static fromJSON(e){const t=e;if(!t)throw new a("webmap:empty-resource","Expected a JSON resource but got nothing");return new this({resourceInfo:t})}};Ie.VERSION=re,e([_({type:X,json:{write:!0}})],Ie.prototype,"applicationProperties",void 0),e([_({type:String,json:{write:{allowNull:!0,ignoreOrigin:!0}}})],Ie.prototype,"authoringApp",null),e([A("authoringApp")],Ie.prototype,"writeAuthoringApp",null),e([_({type:String,json:{write:{allowNull:!0,ignoreOrigin:!0}}})],Ie.prototype,"authoringAppVersion",null),e([A("authoringAppVersion")],Ie.prototype,"writeAuthoringAppVersion",null),e([_({json:{read:{source:"baseMap"},write:{target:"baseMap"}}})],Ie.prototype,"basemap",void 0),e([_({type:oe,json:{write:{overridePolicy:e=>({enabled:!!(e&&e.length>0),ignoreOrigin:!0})}}})],Ie.prototype,"bookmarks",void 0),e([_({type:K,json:{read:{source:"mapFloorInfo"},write:{target:"mapFloorInfo"}}})],Ie.prototype,"floorInfo",void 0),e([_({type:$,json:{write:!0}})],Ie.prototype,"geotriggersInfo",void 0),e([_({type:Z,nonNullable:!0,json:{read:{source:["background","initialState.viewpoint","mapRangeInfo","spatialReference"]},write:{ignoreOrigin:!0,target:{background:{type:te},"initialState.viewpoint":{type:i},mapRangeInfo:{type:z},spatialReference:{type:U}}}}})],Ie.prototype,"initialViewProperties",void 0),e([v("initialViewProperties")],Ie.prototype,"readInitialViewProperties",null),e([A("initialViewProperties")],Ie.prototype,"writeInitialViewProperties",null),e([_({json:{read:!1,write:{target:"operationalLayers",ignoreOrigin:!0}}})],Ie.prototype,"layers",void 0),e([A("layers")],Ie.prototype,"writeLayers",null),e([_({type:k})],Ie.prototype,"portalItem",void 0),e([_({json:{write:!0}})],Ie.prototype,"presentation",void 0),e([_()],Ie.prototype,"resourceInfo",void 0),e([_({readOnly:!0,type:ee,json:{read:{source:"version"},write:{allowNull:!0,ignoreOrigin:!0,target:"version",isRequired:!0}}})],Ie.prototype,"sourceVersion",void 0),e([v("sourceVersion")],Ie.prototype,"readSourceVersion",null),e([A("sourceVersion")],Ie.prototype,"writeSourceVersion",null),e([_({json:{read:!1,write:{ignoreOrigin:!0}}})],Ie.prototype,"tables",void 0),e([A("tables")],Ie.prototype,"writeTables",null),e([_()],Ie.prototype,"thumbnailUrl",null),e([_({type:q,json:{write:!0}})],Ie.prototype,"widgets",void 0),e([_({type:ae,json:{read:!0,write:!0}})],Ie.prototype,"utilityNetworks",void 0),Ie=e([I("esri.WebMap")],Ie);const Ae=Ie;export{Ae as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.26/esri/copyright.txt for details.
4
4
  */
5
- import{id as e}from"../kernel.js";import t from"../request.js";import a from"./featureSetCollection.js";import r from"./featureset/actions/AttributeFilter.js";import n from"./featureset/actions/GroupBy.js";import s from"./featureset/actions/OrderBy.js";import i from"./featureset/actions/SpatialFilter.js";import l from"./featureset/actions/Top.js";import o from"./featureset/sources/FeatureLayerDynamic.js";import u from"./featureset/sources/FeatureLayerMemory.js";import c from"./featureset/sources/FeatureLayerRelated.js";import d from"./featureset/support/cache.js";import{FeatureSetError as f,FeatureSetErrorCodes as m}from"./featureset/support/errorsupport.js";import p from"./featureset/support/FeatureSet.js";import{extractServiceUrl as y}from"./featureset/support/shared.js";import{WhereClause as h}from"../core/sql/WhereClause.js";import _ from"../layers/FeatureLayer.js";import L from"../portal/Portal.js";import w from"../portal/PortalItem.js";function I(){null===d.applicationCache&&(d.applicationCache=new d)}async function S(e,t){if(d.applicationCache){const r=d.applicationCache.getLayerInfo(e);if(r){const a=await r;return new _({url:e,outFields:t,sourceJSON:a})}const n=new _({url:e,outFields:t}),s=(async()=>(await n.load(),n.sourceJSON))();if(d.applicationCache){d.applicationCache.setLayerInfo(e,s);try{return await s,n}catch(a){throw d.applicationCache.clearLayerInfo(e),a}}return await s,n}return new _({url:e,outFields:t})}async function N(e,t,a,r,n,s=null){return F(await S(e,["*"]),t,a,r,n,s)}function F(e,t=null,a=null,r=!0,n=null,s=null){const i={layer:e,spatialReference:t,outFields:a,includeGeometry:r,lrucache:n,interceptor:s};return!0===e._hasMemorySource()?new u(i):new o(i)}async function T(e){if(null!==d.applicationCache){const t=d.applicationCache.getLayerInfo(e);if(null!==t)return t}const a=(async()=>{const a=await t(e,{responseType:"json",query:{f:"json"}});return a.data?a.data:null})();if(null!==d.applicationCache){d.applicationCache.setLayerInfo(e,a);try{return await a}catch(r){throw d.applicationCache.clearLayerInfo(e),r}}return a}async function g(e,a){const r="QUERYDATAELEMTS:"+a.toString()+":"+e;if(null!==d.applicationCache){const e=d.applicationCache.getLayerInfo(r);if(null!==e)return e}const n=(async()=>{const r=await t(e+"/queryDataElements",{method:"post",responseType:"json",query:{layers:JSON.stringify([a.toString()]),f:"json"}});if(r.data){const e=r.data;if(e.layerDataElements&&e.layerDataElements[0])return e.layerDataElements[0]}throw new f(m.DataElementsNotFound)})();if(null!==d.applicationCache){d.applicationCache.setLayerInfo(r,n);try{return await n}catch(s){throw d.applicationCache.clearLayerInfo(r),s}}return n}async function A(e){if(null!==d.applicationCache){const t=d.applicationCache.getLayerInfo(e);if(null!==t)return t}const a=(async()=>{const a=await t(e,{responseType:"json",query:{f:"json"}});if(a.data){const e=a.data;return e.layers||(e.layers=[]),e.tables||(e.tables=[]),e}return{layers:[],tables:[]}})();if(null!==d.applicationCache){d.applicationCache.setLayerInfo(e,a);try{return await a}catch(r){throw d.applicationCache.clearLayerInfo(e),r}}return a}async function C(e,t){const a={metadata:null,networkId:-1,unVersion:3,terminals:[],queryelem:null,layerNameLkp:{},lkp:null},r=await A(e);if(a.metadata=r,r.controllerDatasetLayers&&void 0!==r.controllerDatasetLayers.utilityNetworkLayerId&&null!==r.controllerDatasetLayers.utilityNetworkLayerId){if(r.layers)for(const e of r.layers)a.layerNameLkp[e.id]=e.name;if(r.tables)for(const e of r.tables)a.layerNameLkp[e.id]=e.name;const n=r.controllerDatasetLayers.utilityNetworkLayerId;a.networkId=n;const s=await g(e,n);if(s){a.queryelem=s,a.queryelem&&a.queryelem.dataElement&&void 0!==a.queryelem.dataElement.schemaGeneration&&(a.unVersion=a.queryelem.dataElement.schemaGeneration),a.lkp={},a.queryelem.dataElement.domainNetworks||(a.queryelem.dataElement.domainNetworks=[]);for(const e of a.queryelem.dataElement.domainNetworks){for(const t of e.edgeSources?e.edgeSources:[]){const e={layerId:t.layerId,sourceId:t.sourceId,className:a.layerNameLkp[t.layerId]?a.layerNameLkp[t.layerId]:null};e.className&&(a.lkp[e.className]=e)}for(const t of e.junctionSources?e.junctionSources:[]){const e={layerId:t.layerId,sourceId:t.sourceId,className:a.layerNameLkp[t.layerId]?a.layerNameLkp[t.layerId]:null};e.className&&(a.lkp[e.className]=e)}}if(a.queryelem.dataElement.terminalConfigurations)for(const e of a.queryelem.dataElement.terminalConfigurations)for(const t of e.terminals)a.terminals.push({terminalId:t.terminalId,terminalName:t.terminalName});const r=await T(e+"/"+n);if(r.systemLayers&&void 0!==r.systemLayers.associationsTableId&&null!==r.systemLayers.associationsTableId){const n=[];a.unVersion>=4&&(n.push("STATUS"),n.push("PERCENTALONG"));let s=await N(e+"/"+r.systemLayers.associationsTableId.toString(),t,["OBJECTID","FROMNETWORKSOURCEID","TONETWORKSOURCEID","FROMGLOBALID","TOGLOBALID","TOTERMINALID","FROMTERMINALID","ASSOCIATIONTYPE","ISCONTENTVISIBLE","GLOBALID",...n],!1,null,null);return await s.load(),a.unVersion>=4&&(s=s.filter(h.create("STATUS NOT IN (1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 30, 31, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 46, 47, 49, 50, 51, 52, 53, 54, 55, 57, 58, 59, 60, 61, 62,63)",s.getFieldsIndex())),await s.load()),{lkp:a.lkp,associations:s,unVersion:a.unVersion,terminals:a.terminals}}return{associations:null,unVersion:a.unVersion,lkp:null,terminals:[]}}return{associations:null,unVersion:a.unVersion,lkp:null,terminals:[]}}return{associations:null,unVersion:a.unVersion,lkp:null,terminals:[]}}async function k(e,t,a,r=null,n=null,s=!0,i=null,l=null){let o=e.serviceUrl();if(!o)return null;o="/"===o.charAt(o.length-1)?o+t.relatedTableId.toString():o+"/"+t.relatedTableId.toString();const u=await N(o,r,n,s,i,l);return new c({layer:e,relatedLayer:u,relationship:t,objectId:a,spatialReference:r,outFields:n,includeGeometry:s,lrucache:i,interceptor:l})}r.registerAction(),n.registerAction(),s.registerAction(),i.registerAction(),l.registerAction();class j extends a{constructor(e,t=null,a=null,r=null){super(),this._map=e,this._overridespref=t,this._lrucache=a,this._interceptor=r,this._instantLayers=[]}_makeAndAddFeatureSet(e,t=!0,a=null){const r=F(e,this._overridespref,null===a?["*"]:a,t,this._lrucache,this._interceptor);return this._instantLayers.push({featureset:r,opitem:e,includeGeometry:t,outFields:JSON.stringify(a)}),r}async featureSetByName(e,t=!0,a=null){if(void 0!==this._map.loaded&&void 0!==this._map.load&&!1===this._map.loaded)return await this._map.load(),this.featureSetByName(e,t,a);null===a&&(a=["*"]),a=(a=a.slice(0)).sort();const r=JSON.stringify(a);for(let s=0;s<this._instantLayers.length;s++){const a=this._instantLayers[s];if(a.opitem.title===e&&a.includeGeometry===t&&a.outFields===r)return this._instantLayers[s].featureset}const n=this._map.allLayers.find((t=>t instanceof _&&t.title===e));if(n)return this._makeAndAddFeatureSet(n,t,a);if(this._map.tables){const r=this._map.tables.find((t=>!!(t.title&&t.title===e||t.title&&t.title===e)));if(r){if(r instanceof _)return this._makeAndAddFeatureSet(r,t,a);if(r._materializedTable);else{const e=r.outFields?r:{...r,outFields:["*"]};r._materializedTable=new _(e)}return await r._materializedTable.load(),this._makeAndAddFeatureSet(r._materializedTable,t,a)}}return null}async featureSetById(e,t=!0,a=["*"]){if(void 0!==this._map.loaded&&void 0!==this._map.load&&!1===this._map.loaded)return await this._map.load(),this.featureSetById(e,t,a);null===a&&(a=["*"]),a=(a=a.slice(0)).sort();const r=JSON.stringify(a);for(let s=0;s<this._instantLayers.length;s++){const a=this._instantLayers[s];if(a.opitem.id===e&&a.includeGeometry===t&&a.outFields===r)return this._instantLayers[s].featureset}const n=this._map.allLayers.find((t=>t instanceof _&&t.id===e));if(n)return this._makeAndAddFeatureSet(n,t,a);if(this._map.tables){const r=this._map.tables.find((t=>t.id===e));if(r){if(r instanceof _)return this._makeAndAddFeatureSet(r,t,a);if(r._materializedTable);else{const e={...r,outFields:["*"]};r._materializedTable=new _(e)}return await r._materializedTable.load(),this._makeAndAddFeatureSet(r._materializedTable,t,a)}}return null}}class O extends a{constructor(e,t=null,a=null,r=null){super(),this._url=e,this._overridespref=t,this._lrucache=a,this._interceptor=r,this.metadata=null,this._instantLayers=[]}get url(){return this._url}_makeAndAddFeatureSet(e,t=!0,a=null){const r=F(e,this._overridespref,null===a?["*"]:a,t,this._lrucache);return this._instantLayers.push({featureset:r,opitem:e,includeGeometry:t,outFields:JSON.stringify(a)}),r}async _loadMetaData(){const e=await A(this._url);return this.metadata=e,e}load(){return this._loadMetaData()}clone(){return new O(this._url,this._overridespref,this._lrucache,this._interceptor)}async featureSetByName(e,t=!0,a=null){null===a&&(a=["*"]),a=(a=a.slice(0)).sort();const r=JSON.stringify(a);for(let i=0;i<this._instantLayers.length;i++){const a=this._instantLayers[i];if(a.opitem.title===e&&a.includeGeometry===t&&a.outFields===r)return this._instantLayers[i].featureset}const n=await this._loadMetaData();let s=null;for(const i of n.layers?n.layers:[])i.name===e&&(s=i);if(!s)for(const i of n.tables?n.tables:[])i.name===e&&(s=i);if(s){const e=await S(this._url+"/"+s.id,["*"]);return this._makeAndAddFeatureSet(e,t,a)}return null}async featureSetById(e,t=!0,a=["*"]){null===a&&(a=["*"]),a=(a=a.slice(0)).sort();const r=JSON.stringify(a);e=null!=e?e.toString():"";for(let i=0;i<this._instantLayers.length;i++){const a=this._instantLayers[i];if(a.opitem.id===e&&a.includeGeometry===t&&a.outFields===r)return this._instantLayers[i].featureset}const n=await this._loadMetaData();let s=null;for(const i of n.layers?n.layers:[])null!==i.id&&void 0!==i.id&&i.id.toString()===e&&(s=i);if(!s)for(const i of n.tables?n.tables:[])null!==i.id&&void 0!==i.id&&i.id.toString()===e&&(s=i);if(s){const e=await S(this._url+"/"+s.id,["*"]);return this._makeAndAddFeatureSet(e,t,a)}return null}}function E(e,t,a=null,r=null){return new j(e,t,a,r)}function b(e,t,a=null,r=null){return new O(e,t,a,r)}function D(e,t){if(null===e)return t;return new L({url:e.field("url")})}async function q(a,r,n){if(!e.findCredential(a.restUrl))return null;if("loaded"===a.loadStatus&&""===r&&a.user&&a.user.sourceJSON&&!1===n)return a.user.sourceJSON;if(""===r){const e=await t(a.restUrl+"/community/self",{responseType:"json",query:{f:"json",...!1===n?{}:{returnUserLicenseTypeExtensions:!0}}});if(e.data){const t=e.data;if(t&&t.username)return t}return null}const s=await t(a.restUrl+"/community/users/"+r,{responseType:"json",query:{f:"json"}});if(s.data){const e=s.data;return e.error?null:e}return null}function v(e,t,a,r,n){if(null===e)return null;if(e instanceof _){switch(t){case"datasource":return F(e,n,e.outFields,!0,a,r).getDataSourceFeatureSet();case"parent":case"root":return F(e,n,e.outFields,!0,a,r)}return null}if(e instanceof p)switch(t){case"datasource":return e.getDataSourceFeatureSet();case"parent":return e;case"root":return e.getRootFeatureSet()}return null}async function G(e,t,a,r,n,s,i,l=null){if(d.applicationCache){const o=d.applicationCache.getLayerInfo(e+":"+s.url);if(o){const e=await o;return F(new _({url:y(e.url)+"/"+t,outFields:["*"]}),a,r,n,i,l)}}const o=new w({id:e,portal:s}).load();d.applicationCache&&d.applicationCache.setLayerInfo(e+":"+s.url,o);try{const e=await o;return F(new _({url:y(e.url??"")+"/"+t,outFields:["*"]}),a,r,n,i,l)}catch(u){throw d.applicationCache&&d.applicationCache.clearLayerInfo(e+":"+s.url),u}}export{C as constructAssociationMetaDataFeatureSetFromUrl,F as constructFeatureSet,G as constructFeatureSetFromPortalItem,k as constructFeatureSetFromRelationship,N as constructFeatureSetFromUrl,v as convertToFeatureSet,E as createFeatureSetCollectionFromMap,b as createFeatureSetCollectionFromService,D as getPortal,I as initialiseMetaDataCache,q as lookupUser};
5
+ import e from"../request.js";import t from"./featureSetCollection.js";import a from"./featureset/actions/AttributeFilter.js";import r from"./featureset/actions/GroupBy.js";import n from"./featureset/actions/OrderBy.js";import i from"./featureset/actions/SpatialFilter.js";import s from"./featureset/actions/Top.js";import l from"./featureset/sources/FeatureLayerDynamic.js";import o from"./featureset/sources/FeatureLayerMemory.js";import u from"./featureset/sources/FeatureLayerRelated.js";import c from"./featureset/support/cache.js";import{FeatureSetError as d,FeatureSetErrorCodes as f}from"./featureset/support/errorsupport.js";import m from"./featureset/support/FeatureSet.js";import{extractServiceUrl as p}from"./featureset/support/shared.js";import{WhereClause as y}from"../core/sql/WhereClause.js";import h from"../layers/FeatureLayer.js";import _ from"../portal/PortalItem.js";function L(){null===c.applicationCache&&(c.applicationCache=new c)}async function w(e,t){if(c.applicationCache){const r=c.applicationCache.getLayerInfo(e);if(r){const a=await r;return new h({url:e,outFields:t,sourceJSON:a})}const n=new h({url:e,outFields:t}),i=(async()=>(await n.load(),n.sourceJSON))();if(c.applicationCache){c.applicationCache.setLayerInfo(e,i);try{return await i,n}catch(a){throw c.applicationCache.clearLayerInfo(e),a}}return await i,n}return new h({url:e,outFields:t})}async function I(e,t,a,r,n,i=null){return S(await w(e,["*"]),t,a,r,n,i)}function S(e,t=null,a=null,r=!0,n=null,i=null){const s={layer:e,spatialReference:t,outFields:a,includeGeometry:r,lrucache:n,interceptor:i};return!0===e._hasMemorySource()?new o(s):new l(s)}async function N(t){if(null!==c.applicationCache){const e=c.applicationCache.getLayerInfo(t);if(null!==e)return e}const a=(async()=>{const a=await e(t,{responseType:"json",query:{f:"json"}});return a.data?a.data:null})();if(null!==c.applicationCache){c.applicationCache.setLayerInfo(t,a);try{return await a}catch(r){throw c.applicationCache.clearLayerInfo(t),r}}return a}async function F(t,a){const r="QUERYDATAELEMTS:"+a.toString()+":"+t;if(null!==c.applicationCache){const e=c.applicationCache.getLayerInfo(r);if(null!==e)return e}const n=(async()=>{const r=await e(t+"/queryDataElements",{method:"post",responseType:"json",query:{layers:JSON.stringify([a.toString()]),f:"json"}});if(r.data){const e=r.data;if(e.layerDataElements&&e.layerDataElements[0])return e.layerDataElements[0]}throw new d(f.DataElementsNotFound)})();if(null!==c.applicationCache){c.applicationCache.setLayerInfo(r,n);try{return await n}catch(i){throw c.applicationCache.clearLayerInfo(r),i}}return n}async function g(t){if(null!==c.applicationCache){const e=c.applicationCache.getLayerInfo(t);if(null!==e)return e}const a=(async()=>{const a=await e(t,{responseType:"json",query:{f:"json"}});if(a.data){const e=a.data;return e.layers||(e.layers=[]),e.tables||(e.tables=[]),e}return{layers:[],tables:[]}})();if(null!==c.applicationCache){c.applicationCache.setLayerInfo(t,a);try{return await a}catch(r){throw c.applicationCache.clearLayerInfo(t),r}}return a}async function A(e,t){const a={metadata:null,networkId:-1,unVersion:3,terminals:[],queryelem:null,layerNameLkp:{},lkp:null},r=await g(e);if(a.metadata=r,r.controllerDatasetLayers&&void 0!==r.controllerDatasetLayers.utilityNetworkLayerId&&null!==r.controllerDatasetLayers.utilityNetworkLayerId){if(r.layers)for(const e of r.layers)a.layerNameLkp[e.id]=e.name;if(r.tables)for(const e of r.tables)a.layerNameLkp[e.id]=e.name;const n=r.controllerDatasetLayers.utilityNetworkLayerId;a.networkId=n;const i=await F(e,n);if(i){a.queryelem=i,a.queryelem&&a.queryelem.dataElement&&void 0!==a.queryelem.dataElement.schemaGeneration&&(a.unVersion=a.queryelem.dataElement.schemaGeneration),a.lkp={},a.queryelem.dataElement.domainNetworks||(a.queryelem.dataElement.domainNetworks=[]);for(const e of a.queryelem.dataElement.domainNetworks){for(const t of e.edgeSources?e.edgeSources:[]){const e={layerId:t.layerId,sourceId:t.sourceId,className:a.layerNameLkp[t.layerId]?a.layerNameLkp[t.layerId]:null};e.className&&(a.lkp[e.className]=e)}for(const t of e.junctionSources?e.junctionSources:[]){const e={layerId:t.layerId,sourceId:t.sourceId,className:a.layerNameLkp[t.layerId]?a.layerNameLkp[t.layerId]:null};e.className&&(a.lkp[e.className]=e)}}if(a.queryelem.dataElement.terminalConfigurations)for(const e of a.queryelem.dataElement.terminalConfigurations)for(const t of e.terminals)a.terminals.push({terminalId:t.terminalId,terminalName:t.terminalName});const r=await N(e+"/"+n);if(r.systemLayers&&void 0!==r.systemLayers.associationsTableId&&null!==r.systemLayers.associationsTableId){const n=[];a.unVersion>=4&&(n.push("STATUS"),n.push("PERCENTALONG"));let i=await I(e+"/"+r.systemLayers.associationsTableId.toString(),t,["OBJECTID","FROMNETWORKSOURCEID","TONETWORKSOURCEID","FROMGLOBALID","TOGLOBALID","TOTERMINALID","FROMTERMINALID","ASSOCIATIONTYPE","ISCONTENTVISIBLE","GLOBALID",...n],!1,null,null);return await i.load(),a.unVersion>=4&&(i=i.filter(y.create("STATUS NOT IN (1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 30, 31, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 46, 47, 49, 50, 51, 52, 53, 54, 55, 57, 58, 59, 60, 61, 62,63)",i.getFieldsIndex())),await i.load()),{lkp:a.lkp,associations:i,unVersion:a.unVersion,terminals:a.terminals}}return{associations:null,unVersion:a.unVersion,lkp:null,terminals:[]}}return{associations:null,unVersion:a.unVersion,lkp:null,terminals:[]}}return{associations:null,unVersion:a.unVersion,lkp:null,terminals:[]}}async function C(e,t,a,r=null,n=null,i=!0,s=null,l=null){let o=e.serviceUrl();if(!o)return null;o="/"===o.charAt(o.length-1)?o+t.relatedTableId.toString():o+"/"+t.relatedTableId.toString();const c=await I(o,r,n,i,s,l);return new u({layer:e,relatedLayer:c,relationship:t,objectId:a,spatialReference:r,outFields:n,includeGeometry:i,lrucache:s,interceptor:l})}a.registerAction(),r.registerAction(),n.registerAction(),i.registerAction(),s.registerAction();class T extends t{constructor(e,t=null,a=null,r=null){super(),this._map=e,this._overridespref=t,this._lrucache=a,this._interceptor=r,this._instantLayers=[]}_makeAndAddFeatureSet(e,t=!0,a=null){const r=S(e,this._overridespref,null===a?["*"]:a,t,this._lrucache,this._interceptor);return this._instantLayers.push({featureset:r,opitem:e,includeGeometry:t,outFields:JSON.stringify(a)}),r}async featureSetByName(e,t=!0,a=null){if(void 0!==this._map.loaded&&void 0!==this._map.load&&!1===this._map.loaded)return await this._map.load(),this.featureSetByName(e,t,a);null===a&&(a=["*"]),a=(a=a.slice(0)).sort();const r=JSON.stringify(a);for(let i=0;i<this._instantLayers.length;i++){const a=this._instantLayers[i];if(a.opitem.title===e&&a.includeGeometry===t&&a.outFields===r)return this._instantLayers[i].featureset}const n=this._map.allLayers.find((t=>t instanceof h&&t.title===e));if(n)return this._makeAndAddFeatureSet(n,t,a);if(this._map.tables){const r=this._map.tables.find((t=>!!(t.title&&t.title===e||t.title&&t.title===e)));if(r){if(r instanceof h)return this._makeAndAddFeatureSet(r,t,a);if(r._materializedTable);else{const e=r.outFields?r:{...r,outFields:["*"]};r._materializedTable=new h(e)}return await r._materializedTable.load(),this._makeAndAddFeatureSet(r._materializedTable,t,a)}}return null}async featureSetById(e,t=!0,a=["*"]){if(void 0!==this._map.loaded&&void 0!==this._map.load&&!1===this._map.loaded)return await this._map.load(),this.featureSetById(e,t,a);null===a&&(a=["*"]),a=(a=a.slice(0)).sort();const r=JSON.stringify(a);for(let i=0;i<this._instantLayers.length;i++){const a=this._instantLayers[i];if(a.opitem.id===e&&a.includeGeometry===t&&a.outFields===r)return this._instantLayers[i].featureset}const n=this._map.allLayers.find((t=>t instanceof h&&t.id===e));if(n)return this._makeAndAddFeatureSet(n,t,a);if(this._map.tables){const r=this._map.tables.find((t=>t.id===e));if(r){if(r instanceof h)return this._makeAndAddFeatureSet(r,t,a);if(r._materializedTable);else{const e={...r,outFields:["*"]};r._materializedTable=new h(e)}return await r._materializedTable.load(),this._makeAndAddFeatureSet(r._materializedTable,t,a)}}return null}}class k extends t{constructor(e,t=null,a=null,r=null){super(),this._url=e,this._overridespref=t,this._lrucache=a,this._interceptor=r,this.metadata=null,this._instantLayers=[]}get url(){return this._url}_makeAndAddFeatureSet(e,t=!0,a=null){const r=S(e,this._overridespref,null===a?["*"]:a,t,this._lrucache);return this._instantLayers.push({featureset:r,opitem:e,includeGeometry:t,outFields:JSON.stringify(a)}),r}async _loadMetaData(){const e=await g(this._url);return this.metadata=e,e}load(){return this._loadMetaData()}clone(){return new k(this._url,this._overridespref,this._lrucache,this._interceptor)}async featureSetByName(e,t=!0,a=null){null===a&&(a=["*"]),a=(a=a.slice(0)).sort();const r=JSON.stringify(a);for(let s=0;s<this._instantLayers.length;s++){const a=this._instantLayers[s];if(a.opitem.title===e&&a.includeGeometry===t&&a.outFields===r)return this._instantLayers[s].featureset}const n=await this._loadMetaData();let i=null;for(const s of n.layers?n.layers:[])s.name===e&&(i=s);if(!i)for(const s of n.tables?n.tables:[])s.name===e&&(i=s);if(i){const e=await w(this._url+"/"+i.id,["*"]);return this._makeAndAddFeatureSet(e,t,a)}return null}async featureSetById(e,t=!0,a=["*"]){null===a&&(a=["*"]),a=(a=a.slice(0)).sort();const r=JSON.stringify(a);e=null!=e?e.toString():"";for(let s=0;s<this._instantLayers.length;s++){const a=this._instantLayers[s];if(a.opitem.id===e&&a.includeGeometry===t&&a.outFields===r)return this._instantLayers[s].featureset}const n=await this._loadMetaData();let i=null;for(const s of n.layers?n.layers:[])null!==s.id&&void 0!==s.id&&s.id.toString()===e&&(i=s);if(!i)for(const s of n.tables?n.tables:[])null!==s.id&&void 0!==s.id&&s.id.toString()===e&&(i=s);if(i){const e=await w(this._url+"/"+i.id,["*"]);return this._makeAndAddFeatureSet(e,t,a)}return null}}function O(e,t,a=null,r=null){return new T(e,t,a,r)}function b(e,t,a=null,r=null){return new k(e,t,a,r)}function E(e,t,a,r,n){if(null===e)return null;if(e instanceof h){switch(t){case"datasource":return S(e,n,e.outFields,!0,a,r).getDataSourceFeatureSet();case"parent":case"root":return S(e,n,e.outFields,!0,a,r)}return null}if(e instanceof m)switch(t){case"datasource":return e.getDataSourceFeatureSet();case"parent":return e;case"root":return e.getRootFeatureSet()}return null}async function j(e,t,a,r,n,i,s,l=null){if(c.applicationCache){const o=c.applicationCache.getLayerInfo(e+":"+i.url);if(o){const e=await o;return S(new h({url:p(e.url)+"/"+t,outFields:["*"]}),a,r,n,s,l)}}const o=new _({id:e,portal:i}).load();c.applicationCache&&c.applicationCache.setLayerInfo(e+":"+i.url,o);try{const e=await o;return S(new h({url:p(e.url??"")+"/"+t,outFields:["*"]}),a,r,n,s,l)}catch(u){throw c.applicationCache&&c.applicationCache.clearLayerInfo(e+":"+i.url),u}}export{A as constructAssociationMetaDataFeatureSetFromUrl,S as constructFeatureSet,j as constructFeatureSetFromPortalItem,C as constructFeatureSetFromRelationship,I as constructFeatureSetFromUrl,E as convertToFeatureSet,O as createFeatureSetCollectionFromMap,b as createFeatureSetCollectionFromService,L as initialiseMetaDataCache};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.26/esri/copyright.txt for details.
4
4
  */
5
- import e from"../../../Graphic.js";import t from"../../../request.js";import i from"../../Attachment.js";import r from"../support/FeatureSet.js";import s from"../support/IdSet.js";import{defaultMaxRecords as a,stableStringify as n,FeatureServiceDatabaseType as l,IdState as o,extractServiceUrl as u}from"../support/shared.js";import{toWhereClause as d,isSingleField as h}from"../support/sqlUtils.js";import{decodeStatType as c}from"../support/stats.js";import{createMD5Hash as p,outputTypes as y}from"../../../core/MD5.js";import{id as f}from"../../../kernel.js";import{fromJSON as _}from"../../../geometry/support/jsonUtils.js";import m from"../../../layers/FeatureLayer.js";import{convertToFeatureSet as g}from"../../../layers/graphics/featureConversionUtils.js";import"../../../core/Error.js";import"../../../core/has.js";import"../../../core/Logger.js";import"../../../layers/support/source/DataLayerSource.js";import{executeQueryJSON as S}from"../../../rest/query/executeQueryJSON.js";import"../../../config.js";import"../../../core/arrayUtils.js";import"../../../core/urlUtils.js";import"../../../core/unitUtils.js";import"../../../geometry/support/spatialReferenceUtils.js";import{executeQueryPBF as F}from"../../../rest/query/operations/query.js";import R from"../../../rest/support/FeatureSet.js";import w from"../../../rest/support/Query.js";import"../../../rest/query/support/AttachmentInfo.js";import"../../../rest/support/AttachmentQuery.js";import{executeForCount as b}from"../../../rest/query/executeForCount.js";import"../../../geometry.js";import{executeForIds as D}from"../../../rest/query/executeForIds.js";import"../../../rest/support/RelationshipQuery.js";import"../../../geometry/support/normalizeUtils.js";import"../../../rest/support/TopFeaturesQuery.js";import{OptimizedFeatureSetParserContext as I}from"../../../rest/query/operations/pbfOptimizedFeatureSet.js";import x from"../../../rest/support/StatisticDefinition.js";import P from"../../Dictionary.js";import{FeatureSetError as j,FeatureSetErrorCodes as q}from"../support/errorsupport.js";class C extends r{constructor(e){super(e),this.declaredClass="esri.arcade.featureset.sources.FeatureLayerDynamic",this._removeGeometry=!1,this._overrideFields=null,this.formulaCredential=null,this._pageJustIds=!1,this._requestStandardised=!1,this._useDefinitionExpression=!0,e.spatialReference&&(this.spatialReference=e.spatialReference),this._transparent=!0,this._maxProcessing=1e3,this._layer=e.layer,this._wset=null,void 0!==e.outFields&&(this._overrideFields=e.outFields),void 0!==e.includeGeometry&&(this._removeGeometry=!1===e.includeGeometry)}_maxQueryRate(){return a}end(){return this._layer}optimisePagingFeatureQueries(e){this._pageJustIds=e}get urlQueryPath(){return this._layer.parsedUrl.path||""}convertQueryToLruCacheKey(e){const t=this.urlQueryPath+","+n(e.toJSON());return p(t,y.String)}async loadImpl(){return!0===this._layer.loaded?(this._initialiseFeatureSet(),this):(await this._layer.load(),this._initialiseFeatureSet(),this)}_initialiseFeatureSet(){if(null==this.spatialReference&&(this.spatialReference=this._layer.spatialReference),this.geometryType=this._layer.geometryType,this.fields=this._layer.fields.slice(0),this._layer.outFields)if(1===this._layer.outFields.length&&"*"===this._layer.outFields[0]);else{const e=[];for(const t of this.fields)if("oid"===t.type)e.push(t);else for(const i of this._layer.outFields)if(i.toLowerCase()===t.name.toLowerCase()){e.push(t);break}this.fields=e}else;if(null!==this._overrideFields)if(1===this._overrideFields.length&&"*"===this._overrideFields[0])this._overrideFields=null;else{const e=[],t=[];for(const i of this.fields)if("oid"===i.type)e.push(i),t.push(i.name);else for(const r of this._overrideFields)if(r.toLowerCase()===i.name.toLowerCase()){e.push(i),t.push(i.name);break}this.fields=e,this._overrideFields=t}if(this._layer.source&&this._layer.source.sourceJSON){const e=this._layer.source.sourceJSON.currentVersion;!0===this._layer.source.sourceJSON.useStandardizedQueries?(this._databaseType=l.StandardisedNoInterval,null!=e&&e>=10.61&&(this._databaseType=l.Standardised)):null!=e&&(e>=10.5&&(this._databaseType=l.StandardisedNoInterval,this._requestStandardised=!0),e>=10.61&&(this._databaseType=l.Standardised))}this.objectIdField=this._layer.objectIdField;for(const e of this.fields)"global-id"===e.type&&(this.globalIdField=e.name);this.hasM=this._layer.supportsM,this.hasZ=this._layer.supportsZ,this.typeIdField=this._layer.typeIdField??"",this.types=this._layer.types}_isInFeatureSet(){return o.InFeatureSet}async _refineSetBlock(e){return e}_candidateIdTransform(e){return e}async _getSet(e){if(null===this._wset){await this._ensureLoaded();const t=await this._getFilteredSet("",null,null,null,e);return this._wset=t,t}return this._wset}async _runDatabaseProbe(e){await this._ensureLoaded();const t=new w;t.where=e.replace("OBJECTID",this._layer.objectIdField);try{return await this._layer.queryObjectIds(t),!0}catch(i){return!1}}_canUsePagination(){return!(!this._layer.capabilities||!this._layer.capabilities.query||!0!==this._layer.capabilities.query.supportsPagination)}_cacheableFeatureSetSourceKey(){return this._layer.url}pbfSupportedForQuery(e){const t=this._layer?.capabilities?.query;return!e.outStatistics&&!0===t?.supportsFormatPBF&&!0===t?.supportsQuantizationEditMode}async queryPBF(e){e.quantizationParameters={mode:"edit"};const t=await F(this._layer.parsedUrl,e,new I({}));return R.fromJSON(g(t.data)).unquantize()}get gdbVersion(){return this._layer&&this._layer.capabilities&&this._layer.capabilities.data&&this._layer.capabilities.data.isVersioned?this._layer.gdbVersion?this._layer.gdbVersion:"SDE.DEFAULT":""}nativeCapabilities(){return{title:this._layer.title??"",source:this,canQueryRelated:!0,capabilities:this._layer.capabilities,databaseType:this._databaseType,requestStandardised:this._requestStandardised}}executeQuery(e,t){const i="execute"===t?S:"executeForCount"===t?b:D,r="execute"===t&&this.pbfSupportedForQuery(e);let s=null;if(this.recentlyUsedQueries){const t=this.convertQueryToLruCacheKey(e);s=this.recentlyUsedQueries.getFromCache(t),null===s&&(s=!0!==r?i(this._layer.parsedUrl.path,e):this.queryPBF(e),this.recentlyUsedQueries.addToCache(t,s),s=s.catch((e=>{throw this.recentlyUsedQueries?.removeFromCache(t),e})))}return this.featureSetQueryInterceptor&&this.featureSetQueryInterceptor.preLayerQueryCallback({layer:this._layer,query:e,method:t}),null===s&&(s=!0!==r?i(this._layer.parsedUrl.path,e):this.queryPBF(e)),s}async _getFilteredSet(e,t,i,r,a){const n=await this.databaseType();if(this.isTable()&&t&&null!==e&&""!==e){return new s([],[],!0,null)}if(this._canUsePagination())return this._getFilteredSetUsingPaging(e,t,i,r,a);let l="",o=!1;null!==r&&this._layer.capabilities&&this._layer.capabilities.query&&!0===this._layer.capabilities.query.supportsOrderBy&&(l=r.constructClause(),o=!0);const u=new w;u.where=null===i?null===t?"1=1":"":d(i,n),this._requestStandardised&&(u.sqlFormat="standard"),u.spatialRelationship=this._makeRelationshipEnum(e),u.outSpatialReference=this.spatialReference,u.orderByFields=""!==l?l.split(","):null,u.geometry=null===t?null:t,u.relationParameter=this._makeRelationshipParam(e);let h=await this.executeQuery(u,"executeForIds");null===h&&(h=[]),this._checkCancelled(a);return new s([],h,o,null)}_expandPagedSet(e,t,i,r,s){return this._expandPagedSetFeatureSet(e,t,i,r,s)}async _getFilteredSetUsingPaging(e,t,i,r,a){let n="",l=!1;null!==r&&this._layer.capabilities&&this._layer.capabilities.query&&!0===this._layer.capabilities.query.supportsOrderBy&&(n=r.constructClause(),l=!0);const o=await this.databaseType();let u=null===i?null===t?"1=1":"":d(i,o);this._layer.definitionExpression&&this._useDefinitionExpression&&(u=""!==u?"(("+this._layer.definitionExpression+") AND ("+u+"))":this._layer.definitionExpression);let h=this._maxQueryRate();const c=this._layer.capabilities?.query.maxRecordCount;null!=c&&c<h&&(h=c);let p=null;if(!0===this._pageJustIds)p=new s([],["GETPAGES"],l,{spatialRel:this._makeRelationshipEnum(e),relationParam:this._makeRelationshipParam(e),outFields:this._layer.objectIdField,resultRecordCount:h,resultOffset:0,geometry:null===t?null:t,where:u,orderByFields:n,returnGeometry:!1,returnIdsOnly:"false",internal:{set:[],lastRetrieved:0,lastPage:0,fullyResolved:!1}});else{let i=!0;!0===this._removeGeometry&&(i=!1);const r=null!==this._overrideFields?this._overrideFields:this._fieldsIncludingObjectId(this._layer.outFields?this._layer.outFields:["*"]);p=new s([],["GETPAGES"],l,{spatialRel:this._makeRelationshipEnum(e),relationParam:this._makeRelationshipParam(e),outFields:r.join(","),resultRecordCount:h,resultOffset:0,geometry:null===t?null:t,where:u,orderByFields:n,returnGeometry:i,returnIdsOnly:"false",internal:{set:[],lastRetrieved:0,lastPage:0,fullyResolved:!1}})}return await this._expandPagedSet(p,h,0,1,a),p}_clonePageDefinition(e){return null===e?null:!0!==e.groupbypage?{groupbypage:!1,spatialRel:e.spatialRel,relationParam:e.relationParam,outFields:e.outFields,resultRecordCount:e.resultRecordCount,resultOffset:e.resultOffset,geometry:e.geometry,where:e.where,orderByFields:e.orderByFields,returnGeometry:e.returnGeometry,returnIdsOnly:e.returnIdsOnly,internal:e.internal}:{groupbypage:!0,spatialRel:e.spatialRel,relationParam:e.relationParam,outFields:e.outFields,resultRecordCount:e.resultRecordCount,useOIDpagination:e.useOIDpagination,generatedOid:e.generatedOid,groupByFieldsForStatistics:e.groupByFieldsForStatistics,resultOffset:e.resultOffset,outStatistics:e.outStatistics,geometry:e.geometry,where:e.where,orderByFields:e.orderByFields,returnGeometry:e.returnGeometry,returnIdsOnly:e.returnIdsOnly,internal:e.internal}}async _getPhysicalPage(e,t,i){const r=e.pagesDefinition.internal.lastRetrieved,s=r,a=e.pagesDefinition.internal.lastPage,n=new w;this._requestStandardised&&(n.sqlFormat="standard"),n.spatialRelationship=e.pagesDefinition.spatialRel,n.relationParameter=e.pagesDefinition.relationParam,n.outFields=e.pagesDefinition.outFields.split(","),n.num=e.pagesDefinition.resultRecordCount,n.start=e.pagesDefinition.internal.lastPage,n.geometry=e.pagesDefinition.geometry,n.where=e.pagesDefinition.where,n.orderByFields=""!==e.pagesDefinition.orderByFields?e.pagesDefinition.orderByFields.split(","):null,n.returnGeometry=e.pagesDefinition.returnGeometry,n.outSpatialReference=this.spatialReference;const l=await this.executeQuery(n,"execute");if(this._checkCancelled(i),e.pagesDefinition.internal.lastPage!==a)return"done";const o=this._layer.objectIdField;for(let u=0;u<l.features.length;u++)e.pagesDefinition.internal.set[s+u]=l.features[u].attributes[o];if(!1===this._pageJustIds)for(let u=0;u<l.features.length;u++)this._featureCache[l.features[u].attributes[o]]=l.features[u];return(void 0===l.exceededTransferLimit&&l.features.length!==e.pagesDefinition.resultRecordCount||!1===l.exceededTransferLimit)&&(e.pagesDefinition.internal.fullyResolved=!0),e.pagesDefinition.internal.lastRetrieved=r+l.features.length,e.pagesDefinition.internal.lastPage+=e.pagesDefinition.resultRecordCount,"done"}_fieldsIncludingObjectId(e){if(null===e)return[this.objectIdField];const t=e.slice(0);if(t.includes("*"))return t;let i=!1;for(const r of t)if(r.toUpperCase()===this.objectIdField.toUpperCase()){i=!0;break}return!1===i&&t.push(this.objectIdField),t}async _getFeatures(e,t,i,r){const s=[];if(-1!==t&&void 0===this._featureCache[t]&&s.push(t),!0===this._checkIfNeedToExpandKnownPage(e,this._maxProcessingRate()))return await this._expandPagedSet(e,this._maxProcessingRate(),0,0,r),this._getFeatures(e,t,i,r);let a=0;for(let u=e._lastFetchedIndex;u<e._known.length;u++){if(e._lastFetchedIndex+=1,a++,void 0===this._featureCache[e._known[u]]){let i=!1;if(null!==this._layer._mode&&void 0!==this._layer._mode){const t=this._layer._mode;if(void 0!==t._featureMap[e._known[u]]){const r=t._featureMap[e._known[u]];null!==r&&(i=!0,this._featureCache[e._known[u]]=r)}}if(!1===i&&(e._known[u]!==t&&s.push(e._known[u]),s.length>=this._maxProcessingRate()-1))break}if(a>=i&&0===s.length)break}if(0===s.length)return"success";const n=new w;this._requestStandardised&&(n.sqlFormat="standard"),n.objectIds=s,n.outFields=null!==this._overrideFields?this._overrideFields:this._fieldsIncludingObjectId(this._layer.outFields?this._layer.outFields:["*"]),n.returnGeometry=!0,!0===this._removeGeometry&&(n.returnGeometry=!1),n.outSpatialReference=this.spatialReference;const l=await this.executeQuery(n,"execute");if(this._checkCancelled(r),void 0!==l.error)throw new j(q.RequestFailed,{reason:l.error});const o=this._layer.objectIdField;for(let u=0;u<l.features.length;u++)this._featureCache[l.features[u].attributes[o]]=l.features[u];return"success"}async _getDistinctPages(e,t,i,r,s,a,n,l,o){await this._ensureLoaded();const u=await this.databaseType();let h=i.parseTree.column;const c=this._layer.fields??[];for(let d=0;d<c.length;d++)if(c[d].name.toLowerCase()===h.toLowerCase()){h=c[d].name;break}const p=new w;this._requestStandardised&&(p.sqlFormat="standard");let y=null===a?null===s?"1=1":"":d(a,u);this._layer.definitionExpression&&this._useDefinitionExpression&&(y=""!==y?"(("+this._layer.definitionExpression+") AND ("+y+"))":this._layer.definitionExpression),p.where=y,p.spatialRelationship=this._makeRelationshipEnum(r),p.relationParameter=this._makeRelationshipParam(r),p.geometry=null===s?null:s,p.returnDistinctValues=!0,p.returnGeometry=!1,p.outFields=[h];const f=await this.executeQuery(p,"execute");if(this._checkCancelled(o),!f.hasOwnProperty("features"))throw new j(q.InvalidStatResponse);let _=!1;for(let d=0;d<c.length;d++)if(c[d].name===h){"date"===c[d].type&&(_=!0);break}for(let d=0;d<f.features.length;d++){if(_){const e=f.features[d].attributes[h];null!==e?l.push(new Date(e)):l.push(e)}else l.push(f.features[d].attributes[h]);if(l.length>=n)break}if(0===f.features.length)return l;if(f.features.length===this._layer.capabilities?.query.maxRecordCount&&l.length<n){return{calculated:!0,result:await this._getDistinctPages(e+f.features.length,t,i,r,s,a,n,l,o)}}return l}async _distinctStat(e,t,i,r,s,a,n){return{calculated:!0,result:await this._getDistinctPages(0,e,t,i,r,s,a,[],n)}}isTable(){return this._layer.isTable||null===this._layer.geometryType||"table"===this._layer.type||""===this._layer.geometryType}async _countstat(e,t,i,r){const s=await this.databaseType(),a=new w;if(this._requestStandardised&&(a.sqlFormat="standard"),this.isTable()&&i&&null!==t&&""!==t)return{calculated:!0,result:0};let n=null===r?null===i?"1=1":"":d(r,s);this._layer.definitionExpression&&this._useDefinitionExpression&&(n=""!==n?"(("+this._layer.definitionExpression+") AND ("+n+"))":this._layer.definitionExpression),a.where=n,a.where=n,a.spatialRelationship=this._makeRelationshipEnum(t),a.relationParameter=this._makeRelationshipParam(t),a.geometry=null===i?null:i,a.returnGeometry=!1;return{calculated:!0,result:await this.executeQuery(a,"executeForCount")}}async _stats(e,t,i,r,s,a,n){await this._ensureLoaded();const l=this._layer.capabilities&&this._layer.capabilities.query&&!0===this._layer.capabilities.query.supportsSqlExpression,o=this._layer.capabilities&&this._layer.capabilities.query&&!0===this._layer.capabilities.query.supportsStatistics,u=this._layer.capabilities&&this._layer.capabilities.query&&!0===this._layer.capabilities.query.supportsDistinct;if("count"===e)return u?this._countstat(e,i,r,s):{calculated:!1};if(!1===o||!1===h(t)&&!1===l||!1===t.isStandardized)return""!==i||null!==s?{calculated:!1}:this._manualStat(e,t,a,n);if("distinct"===e)return!1===u?""!==i||null!==s?{calculated:!1}:this._manualStat(e,t,a,n):this._distinctStat(e,t,i,r,s,a,n);const p=await this.databaseType();if(this.isTable()&&r&&null!==i&&""!==i)return{calculated:!0,result:null};const y=new w;this._requestStandardised&&(y.sqlFormat="standard");let f=null===s?null===r?"1=1":"":d(s,p);this._layer.definitionExpression&&this._useDefinitionExpression&&(f=""!==f?"(("+this._layer.definitionExpression+") AND ("+f+"))":this._layer.definitionExpression),y.where=f,y.spatialRelationship=this._makeRelationshipEnum(i),y.relationParameter=this._makeRelationshipParam(i),y.geometry=null===r?null:r;const _=new x;_.statisticType=c(e),_.onStatisticField=d(t,p),_.outStatisticFieldName="ARCADE_STAT_RESULT",y.returnGeometry=!1;let m="ARCADE_STAT_RESULT";y.outStatistics=[_];const g=await this.executeQuery(y,"execute");if(!g.hasOwnProperty("features")||0===g.features.length)throw new j(q.InvalidStatResponse);let S=!1;const F=g.fields??[];for(let d=0;d<F.length;d++)if("ARCADE_STAT_RESULT"===F[d].name.toUpperCase()){m=F[d].name,"date"===F[d].type&&(S=!0);break}if(S){let e=g.features[0].attributes[m];return null!==e&&(e=new Date(g.features[0].attributes[m])),{calculated:!0,result:e}}return{calculated:!0,result:g.features[0].attributes[m]}}_stat(e,t,i,r,s,a,n){return this._stats(e,t,i,r,s,a,n)}async _canDoAggregates(e,t){await this._ensureLoaded();let i=!1;const r=this._layer.capabilities?.query,s=!0===r?.supportsSqlExpression;if(null!=r&&!0===r.supportsStatistics&&!0===r.supportsOrderBy&&(i=!0),i)for(let a=0;a<t.length-1;a++)(!1===t[a].workingexpr?.isStandardized||!1===h(t[a].workingexpr)&&!1===s)&&(i=!1);return!1!==i}_makeRelationshipEnum(e){if(e.includes("esriSpatialRelRelation"))return"relation";switch(e){case"esriSpatialRelRelation":return"relation";case"esriSpatialRelIntersects":return"intersects";case"esriSpatialRelContains":return"contains";case"esriSpatialRelOverlaps":return"overlaps";case"esriSpatialRelWithin":return"within";case"esriSpatialRelTouches":return"touches";case"esriSpatialRelCrosses":return"crosses";case"esriSpatialRelEnvelopeIntersects":return"envelope-intersects"}return e}_makeRelationshipParam(e){return e.includes("esriSpatialRelRelation")?e.split(":")[1]:""}async _getAggregatePagesDataSourceDefinition(e,t,i,r,a,n,l){await this._ensureLoaded();const o=await this.databaseType();let u="",h=!1,c=!1;null!==n&&this._layer.capabilities&&this._layer.capabilities.query&&!0===this._layer.capabilities.query.supportsOrderBy&&(u=n.constructClause(),c=!0),this._layer.capabilities&&this._layer.capabilities.query&&!1===this._layer.capabilities.query.supportsPagination&&(c=!1,h=!0,u=this._layer.objectIdField);const p=[];for(let s=0;s<t.length;s++){const e=new x;e.onStatisticField=null!==t[s].workingexpr?d(t[s].workingexpr,o):"",e.outStatisticFieldName=t[s].field,e.statisticType=t[s].toStatisticsName(),p.push(e)}""===u&&(u=e.join(","));let y=this._maxQueryRate();const f=this._layer.capabilities?.query.maxRecordCount;null!=f&&f<y&&(y=f);let _=null===a?null===r?"1=1":"":d(a,o);this._layer.definitionExpression&&this._useDefinitionExpression&&(_=""!==_?"(("+this._layer.definitionExpression+") AND ("+_+"))":this._layer.definitionExpression);return new s([],["GETPAGES"],c,{groupbypage:!0,spatialRel:this._makeRelationshipEnum(i),relationParam:this._makeRelationshipParam(i),outFields:["*"],useOIDpagination:h,generatedOid:l,resultRecordCount:y,resultOffset:0,groupByFieldsForStatistics:e,outStatistics:p,geometry:null===r?null:r,where:_,orderByFields:u,returnGeometry:!1,returnIdsOnly:!1,internal:{lastMaxId:-1,set:[],lastRetrieved:0,lastPage:0,fullyResolved:!1}})}async _getAgregagtePhysicalPage(t,i,r){let s=t.pagesDefinition.where;!0===t.pagesDefinition.useOIDpagination&&(s=""!==s?"("+s+") AND ("+t.pagesDefinition.generatedOid+">"+t.pagesDefinition.internal.lastMaxId.toString()+")":t.pagesDefinition.generatedOid+">"+t.pagesDefinition.internal.lastMaxId.toString());const a=t.pagesDefinition.internal.lastRetrieved,n=a,l=t.pagesDefinition.internal.lastPage,o=new w;if(this._requestStandardised&&(o.sqlFormat="standard"),o.where=s,o.spatialRelationship=t.pagesDefinition.spatialRel,o.relationParameter=t.pagesDefinition.relationParam,o.outFields=t.pagesDefinition.outFields,o.outStatistics=t.pagesDefinition.outStatistics,o.geometry=t.pagesDefinition.geometry,o.groupByFieldsForStatistics=t.pagesDefinition.groupByFieldsForStatistics,o.num=t.pagesDefinition.resultRecordCount,o.start=t.pagesDefinition.internal.lastPage,o.returnGeometry=t.pagesDefinition.returnGeometry,o.orderByFields=""!==t.pagesDefinition.orderByFields?t.pagesDefinition.orderByFields.split(","):null,this.isTable()&&o.geometry&&o.spatialRelationship)return[];const u=await this.executeQuery(o,"execute");if(this._checkCancelled(r),!u.hasOwnProperty("features"))throw new j(q.InvalidStatResponse);const d=[];if(t.pagesDefinition.internal.lastPage!==l)return[];for(let e=0;e<u.features.length;e++)t.pagesDefinition.internal.set[n+e]=u.features[e].attributes[t.pagesDefinition.generatedOid];for(let h=0;h<u.features.length;h++)d.push(new e({attributes:u.features[h].attributes,geometry:null}));return!0===t.pagesDefinition.useOIDpagination?0===u.features.length?t.pagesDefinition.internal.fullyResolved=!0:t.pagesDefinition.internal.lastMaxId=u.features[u.features.length-1].attributes[t.pagesDefinition.generatedOid]:(void 0===u.exceededTransferLimit&&u.features.length!==t.pagesDefinition.resultRecordCount||!1===u.exceededTransferLimit)&&(t.pagesDefinition.internal.fullyResolved=!0),t.pagesDefinition.internal.lastRetrieved=a+u.features.length,t.pagesDefinition.internal.lastPage+=t.pagesDefinition.resultRecordCount,d}static create(e,t,i,r,s){const a=new m({url:e,outFields:null===t?["*"]:t});return new C({layer:a,spatialReference:i,lrucache:r,interceptor:s})}relationshipMetaData(){return this._layer&&this._layer.source&&this._layer.source.sourceJSON&&this._layer.source.sourceJSON.relationships?this._layer.source.sourceJSON.relationships:[]}serviceUrl(){return u(this._layer.parsedUrl.path)}async queryAttachments(e,t,r,s,a){const n=this._layer.capabilities;if(n?.data.supportsAttachment&&n?.operations.supportsQueryAttachments){const n={objectIds:[e],returnMetadata:a};(t&&t>0||r&&r>0)&&(n.size=[t&&t>0?t:0,r&&r>0?r:t+1]),s&&s.length>0&&(n.attachmentTypes=s),this.featureSetQueryInterceptor&&this.featureSetQueryInterceptor.preLayerQueryCallback({layer:this._layer,query:n,method:"attachments"});const l=await this._layer.queryAttachments(n),o=[];return l&&l[e]&&l[e].forEach((t=>{const r=this._layer.parsedUrl.path+"/"+e.toString()+"/attachments/"+t.id.toString();let s=null;a&&t.exifInfo&&(s=P.convertJsonToArcade(t.exifInfo,"system",!0)),o.push(new i(t.id,t.name,t.contentType,t.size,r,s))})),o}return[]}async queryRelatedFeatures(i){const r={f:"json",relationshipId:i.relationshipId.toString(),definitionExpression:i.where,outFields:i.outFields?.join(","),returnGeometry:i.returnGeometry.toString()};void 0!==i.resultOffset&&null!==i.resultOffset&&(r.resultOffset=i.resultOffset.toString()),void 0!==i.resultRecordCount&&null!==i.resultRecordCount&&(r.resultRecordCount=i.resultRecordCount.toString()),i.orderByFields&&(r.orderByFields=i.orderByFields.join(",")),i.objectIds&&i.objectIds.length>0&&(r.objectIds=i.objectIds.join(",")),i.outSpatialReference&&(r.outSR=JSON.stringify(i.outSpatialReference.toJSON())),this.featureSetQueryInterceptor&&this.featureSetQueryInterceptor.preRequestCallback({layer:this._layer,queryPayload:r,method:"relatedrecords",url:this._layer.parsedUrl.path+"/queryRelatedRecords"});const s=await t(this._layer.parsedUrl.path+"/queryRelatedRecords",{responseType:"json",query:r});if(s.data){const t={},i=s.data;if(i&&i.relatedRecordGroups){const r=i.spatialReference;for(const s of i.relatedRecordGroups){const a=s.objectId,n=[];for(const t of s.relatedRecords){t.geometry&&(t.geometry.spatialReference=r);const i=new e({geometry:t.geometry?_(t.geometry):null,attributes:t.attributes});n.push(i)}t[a]={features:n,exceededTransferLimit:!0===i.exceededTransferLimit}}}return t}throw new j(q.InvalidRequest)}async getFeatureByObjectId(e,t){const i=new w;i.outFields=t,i.returnGeometry=!1,i.outSpatialReference=this.spatialReference,i.where=this.objectIdField+"="+e.toString(),this.featureSetQueryInterceptor&&this.featureSetQueryInterceptor.preLayerQueryCallback({layer:this._layer,query:i,method:"execute"});const r=await S(this._layer.parsedUrl.path,i);return 1===r.features.length?r.features[0]:null}async getIdentityUser(){await this.load();const e=f?.findCredential(this._layer.url);return e?e.userId:null}async getOwningSystemUrl(){await this.load();const e=f?.findServerInfo(this._layer.url);if(e)return e.owningSystemUrl;let i=this._layer.url;const r=i.toLowerCase().indexOf("/rest/services");if(i=r>-1?i.substring(0,r):i,i){i+="/rest/info";try{const e=await t(i,{query:{f:"json"}});let r="";return e.data&&e.data.owningSystemUrl&&(r=e.data.owningSystemUrl),r}catch(s){return""}}return""}getDataSourceFeatureSet(){const e=new C({layer:this._layer,spatialReference:this.spatialReference??void 0,outFields:this._overrideFields??void 0,includeGeometry:!this._removeGeometry,lrucache:this.recentlyUsedQueries??void 0,interceptor:this.featureSetQueryInterceptor??void 0});return e._useDefinitionExpression=!1,e}get preferredTimeReference(){return this._layer?.preferredTimeReference?.toJSON()??null}get dateFieldsTimeReference(){return this._layer?.dateFieldsTimeReference?.toJSON()??null}get datesInUnknownTimezone(){return this._layer.datesInUnknownTimezone}get editFieldsInfo(){return this._layer?.editFieldsInfo?.toJSON()??null}get timeInfo(){return this._layer?.timeInfo?.toJSON()??null}}export{C as default};
5
+ import e from"../../../Graphic.js";import t from"../../../request.js";import i from"../../Attachment.js";import r from"../support/FeatureSet.js";import s from"../support/IdSet.js";import{defaultMaxRecords as a,stableStringify as n,FeatureServiceDatabaseType as l,IdState as o,extractServiceUrl as u}from"../support/shared.js";import{toWhereClause as d,isSingleField as h}from"../support/sqlUtils.js";import{decodeStatType as c}from"../support/stats.js";import{createMD5Hash as p,outputTypes as y}from"../../../core/MD5.js";import{id as f}from"../../../kernel.js";import{fromJSON as _}from"../../../geometry/support/jsonUtils.js";import m from"../../../layers/FeatureLayer.js";import{convertToFeatureSet as g}from"../../../layers/graphics/featureConversionUtils.js";import"../../../core/Error.js";import"../../../core/has.js";import"../../../core/Logger.js";import"../../../layers/support/source/DataLayerSource.js";import{executeQueryJSON as S}from"../../../rest/query/executeQueryJSON.js";import"../../../config.js";import"../../../core/arrayUtils.js";import"../../../core/urlUtils.js";import"../../../core/unitUtils.js";import"../../../geometry/support/spatialReferenceUtils.js";import{executeQueryPBF as F}from"../../../rest/query/operations/query.js";import R from"../../../rest/support/FeatureSet.js";import w from"../../../rest/support/Query.js";import"../../../rest/query/support/AttachmentInfo.js";import"../../../rest/support/AttachmentQuery.js";import{executeForCount as b}from"../../../rest/query/executeForCount.js";import"../../../geometry.js";import{executeForIds as D}from"../../../rest/query/executeForIds.js";import"../../../rest/support/RelationshipQuery.js";import"../../../geometry/support/normalizeUtils.js";import"../../../rest/support/TopFeaturesQuery.js";import{OptimizedFeatureSetParserContext as I}from"../../../rest/query/operations/pbfOptimizedFeatureSet.js";import x from"../../../rest/support/StatisticDefinition.js";import P from"../../Dictionary.js";import{FeatureSetError as j,FeatureSetErrorCodes as q}from"../support/errorsupport.js";class C extends r{constructor(e){super(e),this.declaredClass="esri.arcade.featureset.sources.FeatureLayerDynamic",this._removeGeometry=!1,this._overrideFields=null,this.formulaCredential=null,this._pageJustIds=!1,this._requestStandardised=!1,this._useDefinitionExpression=!0,e.spatialReference&&(this.spatialReference=e.spatialReference),this._transparent=!0,this._maxProcessing=1e3,this._layer=e.layer,this._wset=null,void 0!==e.outFields&&(this._overrideFields=e.outFields),void 0!==e.includeGeometry&&(this._removeGeometry=!1===e.includeGeometry)}_maxQueryRate(){return a}end(){return this._layer}optimisePagingFeatureQueries(e){this._pageJustIds=e}get urlQueryPath(){return this._layer.parsedUrl.path||""}convertQueryToLruCacheKey(e){const t=this.urlQueryPath+","+n(e.toJSON());return p(t,y.String)}async loadImpl(){return!0===this._layer.loaded?(this._initialiseFeatureSet(),this):(await this._layer.load(),this._initialiseFeatureSet(),this)}_initialiseFeatureSet(){if(null==this.spatialReference&&(this.spatialReference=this._layer.spatialReference),this.geometryType=this._layer.geometryType,this.fields=this._layer.fields.slice(0),this._layer.outFields)if(1===this._layer.outFields.length&&"*"===this._layer.outFields[0]);else{const e=[];for(const t of this.fields)if("oid"===t.type)e.push(t);else for(const i of this._layer.outFields)if(i.toLowerCase()===t.name.toLowerCase()){e.push(t);break}this.fields=e}else;if(null!==this._overrideFields)if(1===this._overrideFields.length&&"*"===this._overrideFields[0])this._overrideFields=null;else{const e=[],t=[];for(const i of this.fields)if("oid"===i.type)e.push(i),t.push(i.name);else for(const r of this._overrideFields)if(r.toLowerCase()===i.name.toLowerCase()){e.push(i),t.push(i.name);break}this.fields=e,this._overrideFields=t}if(this._layer.source&&this._layer.source.sourceJSON){const e=this._layer.source.sourceJSON.currentVersion;!0===this._layer.source.sourceJSON.useStandardizedQueries?(this._databaseType=l.StandardisedNoInterval,null!=e&&e>=10.61&&(this._databaseType=l.Standardised)):null!=e&&(e>=10.5&&(this._databaseType=l.StandardisedNoInterval,this._requestStandardised=!0),e>=10.61&&(this._databaseType=l.Standardised))}this.objectIdField=this._layer.objectIdField;for(const e of this.fields)"global-id"===e.type&&(this.globalIdField=e.name);this.hasM=this._layer.supportsM,this.hasZ=this._layer.supportsZ,this.typeIdField=this._layer.typeIdField??"",this.types=this._layer.types}_isInFeatureSet(){return o.InFeatureSet}async _refineSetBlock(e){return e}_candidateIdTransform(e){return e}async _getSet(e){if(null===this._wset){await this._ensureLoaded();const t=await this._getFilteredSet("",null,null,null,e);return this._wset=t,t}return this._wset}async _runDatabaseProbe(e){await this._ensureLoaded();const t=new w;t.where=e.replace("OBJECTID",this._layer.objectIdField);try{return await this._layer.queryObjectIds(t),!0}catch(i){return!1}}_canUsePagination(){return!(!this._layer.capabilities||!this._layer.capabilities.query||!0!==this._layer.capabilities.query.supportsPagination)}_cacheableFeatureSetSourceKey(){return this._layer.url}pbfSupportedForQuery(e){const t=this._layer?.capabilities?.query;return!e.outStatistics&&!0===t?.supportsFormatPBF&&!0===t?.supportsQuantizationEditMode}async queryPBF(e){e.quantizationParameters={mode:"edit"};const t=await F(this._layer.parsedUrl,e,new I({}));return R.fromJSON(g(t.data)).unquantize()}get gdbVersion(){return this._layer&&this._layer.capabilities&&this._layer.capabilities.data&&this._layer.capabilities.data.isVersioned?this._layer.gdbVersion?this._layer.gdbVersion:"SDE.DEFAULT":""}nativeCapabilities(){return{title:this._layer.title??"",source:this,canQueryRelated:!0,capabilities:this._layer.capabilities,databaseType:this._databaseType,requestStandardised:this._requestStandardised}}executeQuery(e,t){const i="execute"===t?S:"executeForCount"===t?b:D,r="execute"===t&&this.pbfSupportedForQuery(e);let s=null;if(this.recentlyUsedQueries){const t=this.convertQueryToLruCacheKey(e);s=this.recentlyUsedQueries.getFromCache(t),null===s&&(s=!0!==r?i(this._layer.parsedUrl.path,e):this.queryPBF(e),this.recentlyUsedQueries.addToCache(t,s),s=s.catch((e=>{throw this.recentlyUsedQueries?.removeFromCache(t),e})))}return this.featureSetQueryInterceptor&&this.featureSetQueryInterceptor.preLayerQueryCallback({layer:this._layer,query:e,method:t}),null===s&&(s=!0!==r?i(this._layer.parsedUrl.path,e):this.queryPBF(e)),s}async _getFilteredSet(e,t,i,r,a){const n=await this.databaseType();if(this.isTable()&&t&&null!==e&&""!==e){return new s([],[],!0,null)}if(this._canUsePagination())return this._getFilteredSetUsingPaging(e,t,i,r,a);let l="",o=!1;null!==r&&this._layer.capabilities&&this._layer.capabilities.query&&!0===this._layer.capabilities.query.supportsOrderBy&&(l=r.constructClause(),o=!0);const u=new w;u.where=null===i?null===t?"1=1":"":d(i,n),this._requestStandardised&&(u.sqlFormat="standard"),u.spatialRelationship=this._makeRelationshipEnum(e),u.outSpatialReference=this.spatialReference,u.orderByFields=""!==l?l.split(","):null,u.geometry=null===t?null:t,u.relationParameter=this._makeRelationshipParam(e);let h=await this.executeQuery(u,"executeForIds");null===h&&(h=[]),this._checkCancelled(a);return new s([],h,o,null)}_expandPagedSet(e,t,i,r,s){return this._expandPagedSetFeatureSet(e,t,i,r,s)}async _getFilteredSetUsingPaging(e,t,i,r,a){let n="",l=!1;null!==r&&this._layer.capabilities&&this._layer.capabilities.query&&!0===this._layer.capabilities.query.supportsOrderBy&&(n=r.constructClause(),l=!0);const o=await this.databaseType();let u=null===i?null===t?"1=1":"":d(i,o);this._layer.definitionExpression&&this._useDefinitionExpression&&(u=""!==u?"(("+this._layer.definitionExpression+") AND ("+u+"))":this._layer.definitionExpression);let h=this._maxQueryRate();const c=this._layer.capabilities?.query.maxRecordCount;null!=c&&c<h&&(h=c);let p=null;if(!0===this._pageJustIds)p=new s([],["GETPAGES"],l,{spatialRel:this._makeRelationshipEnum(e),relationParam:this._makeRelationshipParam(e),outFields:this._layer.objectIdField,resultRecordCount:h,resultOffset:0,geometry:null===t?null:t,where:u,orderByFields:n,returnGeometry:!1,returnIdsOnly:"false",internal:{set:[],lastRetrieved:0,lastPage:0,fullyResolved:!1}});else{let i=!0;!0===this._removeGeometry&&(i=!1);const r=null!==this._overrideFields?this._overrideFields:this._fieldsIncludingObjectId(this._layer.outFields?this._layer.outFields:["*"]);p=new s([],["GETPAGES"],l,{spatialRel:this._makeRelationshipEnum(e),relationParam:this._makeRelationshipParam(e),outFields:r.join(","),resultRecordCount:h,resultOffset:0,geometry:null===t?null:t,where:u,orderByFields:n,returnGeometry:i,returnIdsOnly:"false",internal:{set:[],lastRetrieved:0,lastPage:0,fullyResolved:!1}})}return await this._expandPagedSet(p,h,0,1,a),p}_clonePageDefinition(e){return null===e?null:!0!==e.groupbypage?{groupbypage:!1,spatialRel:e.spatialRel,relationParam:e.relationParam,outFields:e.outFields,resultRecordCount:e.resultRecordCount,resultOffset:e.resultOffset,geometry:e.geometry,where:e.where,orderByFields:e.orderByFields,returnGeometry:e.returnGeometry,returnIdsOnly:e.returnIdsOnly,internal:e.internal}:{groupbypage:!0,spatialRel:e.spatialRel,relationParam:e.relationParam,outFields:e.outFields,resultRecordCount:e.resultRecordCount,useOIDpagination:e.useOIDpagination,generatedOid:e.generatedOid,groupByFieldsForStatistics:e.groupByFieldsForStatistics,resultOffset:e.resultOffset,outStatistics:e.outStatistics,geometry:e.geometry,where:e.where,orderByFields:e.orderByFields,returnGeometry:e.returnGeometry,returnIdsOnly:e.returnIdsOnly,internal:e.internal}}async _getPhysicalPage(e,t,i){const r=e.pagesDefinition.internal.lastRetrieved,s=r,a=e.pagesDefinition.internal.lastPage,n=new w;this._requestStandardised&&(n.sqlFormat="standard"),n.spatialRelationship=e.pagesDefinition.spatialRel,n.relationParameter=e.pagesDefinition.relationParam,n.outFields=e.pagesDefinition.outFields.split(","),n.num=e.pagesDefinition.resultRecordCount,n.start=e.pagesDefinition.internal.lastPage,n.geometry=e.pagesDefinition.geometry,n.where=e.pagesDefinition.where,n.orderByFields=""!==e.pagesDefinition.orderByFields?e.pagesDefinition.orderByFields.split(","):null,n.returnGeometry=e.pagesDefinition.returnGeometry,n.outSpatialReference=this.spatialReference;const l=await this.executeQuery(n,"execute");if(this._checkCancelled(i),e.pagesDefinition.internal.lastPage!==a)return"done";const o=this._layer.objectIdField;for(let u=0;u<l.features.length;u++)e.pagesDefinition.internal.set[s+u]=l.features[u].attributes[o];if(!1===this._pageJustIds)for(let u=0;u<l.features.length;u++)this._featureCache[l.features[u].attributes[o]]=l.features[u];return(void 0===l.exceededTransferLimit&&l.features.length!==e.pagesDefinition.resultRecordCount||!1===l.exceededTransferLimit)&&(e.pagesDefinition.internal.fullyResolved=!0),e.pagesDefinition.internal.lastRetrieved=r+l.features.length,e.pagesDefinition.internal.lastPage+=e.pagesDefinition.resultRecordCount,"done"}_fieldsIncludingObjectId(e){if(null===e)return[this.objectIdField];const t=e.slice(0);if(t.includes("*"))return t;let i=!1;for(const r of t)if(r.toUpperCase()===this.objectIdField.toUpperCase()){i=!0;break}return!1===i&&t.push(this.objectIdField),t}async _getFeatures(e,t,i,r){const s=[];if(-1!==t&&void 0===this._featureCache[t]&&s.push(t),!0===this._checkIfNeedToExpandKnownPage(e,this._maxProcessingRate()))return await this._expandPagedSet(e,this._maxProcessingRate(),0,0,r),this._getFeatures(e,t,i,r);let a=0;for(let u=e._lastFetchedIndex;u<e._known.length;u++){if(e._lastFetchedIndex+=1,a++,void 0===this._featureCache[e._known[u]]){let i=!1;if(null!==this._layer._mode&&void 0!==this._layer._mode){const t=this._layer._mode;if(void 0!==t._featureMap[e._known[u]]){const r=t._featureMap[e._known[u]];null!==r&&(i=!0,this._featureCache[e._known[u]]=r)}}if(!1===i&&(e._known[u]!==t&&s.push(e._known[u]),s.length>=this._maxProcessingRate()-1))break}if(a>=i&&0===s.length)break}if(0===s.length)return"success";const n=new w;this._requestStandardised&&(n.sqlFormat="standard"),n.objectIds=s,n.outFields=null!==this._overrideFields?this._overrideFields:this._fieldsIncludingObjectId(this._layer.outFields?this._layer.outFields:["*"]),n.returnGeometry=!0,!0===this._removeGeometry&&(n.returnGeometry=!1),n.outSpatialReference=this.spatialReference;const l=await this.executeQuery(n,"execute");if(this._checkCancelled(r),void 0!==l.error)throw new j(q.RequestFailed,{reason:l.error});const o=this._layer.objectIdField;for(let u=0;u<l.features.length;u++)this._featureCache[l.features[u].attributes[o]]=l.features[u];return"success"}async _getDistinctPages(e,t,i,r,s,a,n,l,o){await this._ensureLoaded();const u=await this.databaseType();let h=i.parseTree.column;const c=this._layer.fields??[];for(let d=0;d<c.length;d++)if(c[d].name.toLowerCase()===h.toLowerCase()){h=c[d].name;break}const p=new w;this._requestStandardised&&(p.sqlFormat="standard");let y=null===a?null===s?"1=1":"":d(a,u);this._layer.definitionExpression&&this._useDefinitionExpression&&(y=""!==y?"(("+this._layer.definitionExpression+") AND ("+y+"))":this._layer.definitionExpression),p.where=y,p.spatialRelationship=this._makeRelationshipEnum(r),p.relationParameter=this._makeRelationshipParam(r),p.geometry=null===s?null:s,p.returnDistinctValues=!0,p.returnGeometry=!1,p.outFields=[h];const f=await this.executeQuery(p,"execute");if(this._checkCancelled(o),!f.hasOwnProperty("features"))throw new j(q.InvalidStatResponse);let _=!1;for(let d=0;d<c.length;d++)if(c[d].name===h){"date"===c[d].type&&(_=!0);break}for(let d=0;d<f.features.length;d++){if(_){const e=f.features[d].attributes[h];null!==e?l.push(new Date(e)):l.push(e)}else l.push(f.features[d].attributes[h]);if(l.length>=n)break}if(0===f.features.length)return l;if(f.features.length===this._layer.capabilities?.query.maxRecordCount&&l.length<n){return{calculated:!0,result:await this._getDistinctPages(e+f.features.length,t,i,r,s,a,n,l,o)}}return l}async _distinctStat(e,t,i,r,s,a,n){return{calculated:!0,result:await this._getDistinctPages(0,e,t,i,r,s,a,[],n)}}isTable(){return this._layer.isTable||null===this._layer.geometryType||"table"===this._layer.type||""===this._layer.geometryType||"esriGeometryNull"===this._layer.geometryType}async _countstat(e,t,i,r){const s=await this.databaseType(),a=new w;if(this._requestStandardised&&(a.sqlFormat="standard"),this.isTable()&&i&&null!==t&&""!==t)return{calculated:!0,result:0};let n=null===r?null===i?"1=1":"":d(r,s);this._layer.definitionExpression&&this._useDefinitionExpression&&(n=""!==n?"(("+this._layer.definitionExpression+") AND ("+n+"))":this._layer.definitionExpression),a.where=n,a.where=n,a.spatialRelationship=this._makeRelationshipEnum(t),a.relationParameter=this._makeRelationshipParam(t),a.geometry=null===i?null:i,a.returnGeometry=!1;return{calculated:!0,result:await this.executeQuery(a,"executeForCount")}}async _stats(e,t,i,r,s,a,n){await this._ensureLoaded();const l=this._layer.capabilities&&this._layer.capabilities.query&&!0===this._layer.capabilities.query.supportsSqlExpression,o=this._layer.capabilities&&this._layer.capabilities.query&&!0===this._layer.capabilities.query.supportsStatistics,u=this._layer.capabilities&&this._layer.capabilities.query&&!0===this._layer.capabilities.query.supportsDistinct;if("count"===e)return u?this._countstat(e,i,r,s):{calculated:!1};if(!1===o||!1===h(t)&&!1===l||!1===t.isStandardized)return""!==i||null!==s?{calculated:!1}:this._manualStat(e,t,a,n);if("distinct"===e)return!1===u?""!==i||null!==s?{calculated:!1}:this._manualStat(e,t,a,n):this._distinctStat(e,t,i,r,s,a,n);const p=await this.databaseType();if(this.isTable()&&r&&null!==i&&""!==i)return{calculated:!0,result:null};const y=new w;this._requestStandardised&&(y.sqlFormat="standard");let f=null===s?null===r?"1=1":"":d(s,p);this._layer.definitionExpression&&this._useDefinitionExpression&&(f=""!==f?"(("+this._layer.definitionExpression+") AND ("+f+"))":this._layer.definitionExpression),y.where=f,y.spatialRelationship=this._makeRelationshipEnum(i),y.relationParameter=this._makeRelationshipParam(i),y.geometry=null===r?null:r;const _=new x;_.statisticType=c(e),_.onStatisticField=d(t,p),_.outStatisticFieldName="ARCADE_STAT_RESULT",y.returnGeometry=!1;let m="ARCADE_STAT_RESULT";y.outStatistics=[_];const g=await this.executeQuery(y,"execute");if(!g.hasOwnProperty("features")||0===g.features.length)throw new j(q.InvalidStatResponse);let S=!1;const F=g.fields??[];for(let d=0;d<F.length;d++)if("ARCADE_STAT_RESULT"===F[d].name.toUpperCase()){m=F[d].name,"date"===F[d].type&&(S=!0);break}if(S){let e=g.features[0].attributes[m];return null!==e&&(e=new Date(g.features[0].attributes[m])),{calculated:!0,result:e}}return{calculated:!0,result:g.features[0].attributes[m]}}_stat(e,t,i,r,s,a,n){return this._stats(e,t,i,r,s,a,n)}async _canDoAggregates(e,t){await this._ensureLoaded();let i=!1;const r=this._layer.capabilities?.query,s=!0===r?.supportsSqlExpression;if(null!=r&&!0===r.supportsStatistics&&!0===r.supportsOrderBy&&(i=!0),i)for(let a=0;a<t.length-1;a++)(!1===t[a].workingexpr?.isStandardized||!1===h(t[a].workingexpr)&&!1===s)&&(i=!1);return!1!==i}_makeRelationshipEnum(e){if(e.includes("esriSpatialRelRelation"))return"relation";switch(e){case"esriSpatialRelRelation":return"relation";case"esriSpatialRelIntersects":return"intersects";case"esriSpatialRelContains":return"contains";case"esriSpatialRelOverlaps":return"overlaps";case"esriSpatialRelWithin":return"within";case"esriSpatialRelTouches":return"touches";case"esriSpatialRelCrosses":return"crosses";case"esriSpatialRelEnvelopeIntersects":return"envelope-intersects"}return e}_makeRelationshipParam(e){return e.includes("esriSpatialRelRelation")?e.split(":")[1]:""}async _getAggregatePagesDataSourceDefinition(e,t,i,r,a,n,l){await this._ensureLoaded();const o=await this.databaseType();let u="",h=!1,c=!1;null!==n&&this._layer.capabilities&&this._layer.capabilities.query&&!0===this._layer.capabilities.query.supportsOrderBy&&(u=n.constructClause(),c=!0),this._layer.capabilities&&this._layer.capabilities.query&&!1===this._layer.capabilities.query.supportsPagination&&(c=!1,h=!0,u=this._layer.objectIdField);const p=[];for(let s=0;s<t.length;s++){const e=new x;e.onStatisticField=null!==t[s].workingexpr?d(t[s].workingexpr,o):"",e.outStatisticFieldName=t[s].field,e.statisticType=t[s].toStatisticsName(),p.push(e)}""===u&&(u=e.join(","));let y=this._maxQueryRate();const f=this._layer.capabilities?.query.maxRecordCount;null!=f&&f<y&&(y=f);let _=null===a?null===r?"1=1":"":d(a,o);this._layer.definitionExpression&&this._useDefinitionExpression&&(_=""!==_?"(("+this._layer.definitionExpression+") AND ("+_+"))":this._layer.definitionExpression);return new s([],["GETPAGES"],c,{groupbypage:!0,spatialRel:this._makeRelationshipEnum(i),relationParam:this._makeRelationshipParam(i),outFields:["*"],useOIDpagination:h,generatedOid:l,resultRecordCount:y,resultOffset:0,groupByFieldsForStatistics:e,outStatistics:p,geometry:null===r?null:r,where:_,orderByFields:u,returnGeometry:!1,returnIdsOnly:!1,internal:{lastMaxId:-1,set:[],lastRetrieved:0,lastPage:0,fullyResolved:!1}})}async _getAgregagtePhysicalPage(t,i,r){let s=t.pagesDefinition.where;!0===t.pagesDefinition.useOIDpagination&&(s=""!==s?"("+s+") AND ("+t.pagesDefinition.generatedOid+">"+t.pagesDefinition.internal.lastMaxId.toString()+")":t.pagesDefinition.generatedOid+">"+t.pagesDefinition.internal.lastMaxId.toString());const a=t.pagesDefinition.internal.lastRetrieved,n=a,l=t.pagesDefinition.internal.lastPage,o=new w;if(this._requestStandardised&&(o.sqlFormat="standard"),o.where=s,o.spatialRelationship=t.pagesDefinition.spatialRel,o.relationParameter=t.pagesDefinition.relationParam,o.outFields=t.pagesDefinition.outFields,o.outStatistics=t.pagesDefinition.outStatistics,o.geometry=t.pagesDefinition.geometry,o.groupByFieldsForStatistics=t.pagesDefinition.groupByFieldsForStatistics,o.num=t.pagesDefinition.resultRecordCount,o.start=t.pagesDefinition.internal.lastPage,o.returnGeometry=t.pagesDefinition.returnGeometry,o.orderByFields=""!==t.pagesDefinition.orderByFields?t.pagesDefinition.orderByFields.split(","):null,this.isTable()&&o.geometry&&o.spatialRelationship)return[];const u=await this.executeQuery(o,"execute");if(this._checkCancelled(r),!u.hasOwnProperty("features"))throw new j(q.InvalidStatResponse);const d=[];if(t.pagesDefinition.internal.lastPage!==l)return[];for(let e=0;e<u.features.length;e++)t.pagesDefinition.internal.set[n+e]=u.features[e].attributes[t.pagesDefinition.generatedOid];for(let h=0;h<u.features.length;h++)d.push(new e({attributes:u.features[h].attributes,geometry:null}));return!0===t.pagesDefinition.useOIDpagination?0===u.features.length?t.pagesDefinition.internal.fullyResolved=!0:t.pagesDefinition.internal.lastMaxId=u.features[u.features.length-1].attributes[t.pagesDefinition.generatedOid]:(void 0===u.exceededTransferLimit&&u.features.length!==t.pagesDefinition.resultRecordCount||!1===u.exceededTransferLimit)&&(t.pagesDefinition.internal.fullyResolved=!0),t.pagesDefinition.internal.lastRetrieved=a+u.features.length,t.pagesDefinition.internal.lastPage+=t.pagesDefinition.resultRecordCount,d}static create(e,t,i,r,s){const a=new m({url:e,outFields:null===t?["*"]:t});return new C({layer:a,spatialReference:i,lrucache:r,interceptor:s})}relationshipMetaData(){return this._layer&&this._layer.source&&this._layer.source.sourceJSON&&this._layer.source.sourceJSON.relationships?this._layer.source.sourceJSON.relationships:[]}serviceUrl(){return u(this._layer.parsedUrl.path)}async queryAttachments(e,t,r,s,a){const n=this._layer.capabilities;if(n?.data.supportsAttachment&&n?.operations.supportsQueryAttachments){const n={objectIds:[e],returnMetadata:a};(t&&t>0||r&&r>0)&&(n.size=[t&&t>0?t:0,r&&r>0?r:t+1]),s&&s.length>0&&(n.attachmentTypes=s),this.featureSetQueryInterceptor&&this.featureSetQueryInterceptor.preLayerQueryCallback({layer:this._layer,query:n,method:"attachments"});const l=await this._layer.queryAttachments(n),o=[];return l&&l[e]&&l[e].forEach((t=>{const r=this._layer.parsedUrl.path+"/"+e.toString()+"/attachments/"+t.id.toString();let s=null;a&&t.exifInfo&&(s=P.convertJsonToArcade(t.exifInfo,"system",!0)),o.push(new i(t.id,t.name,t.contentType,t.size,r,s))})),o}return[]}async queryRelatedFeatures(i){const r={f:"json",relationshipId:i.relationshipId.toString(),definitionExpression:i.where,outFields:i.outFields?.join(","),returnGeometry:i.returnGeometry.toString()};void 0!==i.resultOffset&&null!==i.resultOffset&&(r.resultOffset=i.resultOffset.toString()),void 0!==i.resultRecordCount&&null!==i.resultRecordCount&&(r.resultRecordCount=i.resultRecordCount.toString()),i.orderByFields&&(r.orderByFields=i.orderByFields.join(",")),i.objectIds&&i.objectIds.length>0&&(r.objectIds=i.objectIds.join(",")),i.outSpatialReference&&(r.outSR=JSON.stringify(i.outSpatialReference.toJSON())),this.featureSetQueryInterceptor&&this.featureSetQueryInterceptor.preRequestCallback({layer:this._layer,queryPayload:r,method:"relatedrecords",url:this._layer.parsedUrl.path+"/queryRelatedRecords"});const s=await t(this._layer.parsedUrl.path+"/queryRelatedRecords",{responseType:"json",query:r});if(s.data){const t={},i=s.data;if(i&&i.relatedRecordGroups){const r=i.spatialReference;for(const s of i.relatedRecordGroups){const a=s.objectId,n=[];for(const t of s.relatedRecords){t.geometry&&(t.geometry.spatialReference=r);const i=new e({geometry:t.geometry?_(t.geometry):null,attributes:t.attributes});n.push(i)}t[a]={features:n,exceededTransferLimit:!0===i.exceededTransferLimit}}}return t}throw new j(q.InvalidRequest)}async getFeatureByObjectId(e,t){const i=new w;i.outFields=t,i.returnGeometry=!1,i.outSpatialReference=this.spatialReference,i.where=this.objectIdField+"="+e.toString(),this.featureSetQueryInterceptor&&this.featureSetQueryInterceptor.preLayerQueryCallback({layer:this._layer,query:i,method:"execute"});const r=await S(this._layer.parsedUrl.path,i);return 1===r.features.length?r.features[0]:null}async getIdentityUser(){await this.load();const e=f?.findCredential(this._layer.url);return e?e.userId:null}async getOwningSystemUrl(){await this.load();const e=f?.findServerInfo(this._layer.url);if(e)return e.owningSystemUrl;let i=this._layer.url;const r=i.toLowerCase().indexOf("/rest/services");if(i=r>-1?i.substring(0,r):i,i){i+="/rest/info";try{const e=await t(i,{query:{f:"json"}});let r="";return e.data&&e.data.owningSystemUrl&&(r=e.data.owningSystemUrl),r}catch(s){return""}}return""}getDataSourceFeatureSet(){const e=new C({layer:this._layer,spatialReference:this.spatialReference??void 0,outFields:this._overrideFields??void 0,includeGeometry:!this._removeGeometry,lrucache:this.recentlyUsedQueries??void 0,interceptor:this.featureSetQueryInterceptor??void 0});return e._useDefinitionExpression=!1,e}get preferredTimeReference(){return this._layer?.preferredTimeReference?.toJSON()??null}get dateFieldsTimeReference(){return this._layer?.dateFieldsTimeReference?.toJSON()??null}get datesInUnknownTimezone(){return this._layer.datesInUnknownTimezone}get editFieldsInfo(){return this._layer?.editFieldsInfo?.toJSON()??null}get timeInfo(){return this._layer?.timeInfo?.toJSON()??null}}export{C as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.26/esri/copyright.txt for details.
4
4
  */
5
- import e from"../../../Graphic.js";import{FeatureSetError as t,FeatureSetErrorCodes as s}from"../support/errorsupport.js";import r from"../support/FeatureSet.js";import i from"../support/IdSet.js";import{defaultMaxRecords as a,FeatureServiceDatabaseType as n,IdState as l}from"../support/shared.js";import{toWhereClause as o}from"../support/sqlUtils.js";import u from"../../../geometry/Geometry.js";import h from"../../../layers/FeatureLayer.js";import c from"../../../layers/support/FeatureType.js";import y from"../../../layers/support/Field.js";import d from"../../../rest/support/Query.js";class f extends r{constructor(e){super(e),this.declaredClass="esri.arcade.featureset.sources.FeatureLayerMemory",this._removeGeometry=!1,this._overrideFields=null,this._forceIsTable=!1,e.spatialReference&&(this.spatialReference=e.spatialReference),this._transparent=!0,this._maxProcessing=1e3,this._layer=e.layer,this._wset=null,!0===e.isTable&&(this._forceIsTable=!0),void 0!==e.outFields&&(this._overrideFields=e.outFields),void 0!==e.includeGeometry&&(this._removeGeometry=!1===e.includeGeometry)}_maxQueryRate(){return a}end(){return this._layer}optimisePagingFeatureQueries(){}async loadImpl(){return!0===this._layer.loaded?(this._initialiseFeatureSet(),this):(await this._layer.load(),this._initialiseFeatureSet(),this)}get gdbVersion(){return""}_initialiseFeatureSet(){if(null==this.spatialReference&&(this.spatialReference=this._layer.spatialReference),this.geometryType=this._layer.geometryType,this.fields=this._layer.fields.slice(0),this._layer.outFields)if(1===this._layer.outFields.length&&"*"===this._layer.outFields[0]);else{const e=[];for(const t of this.fields)if("oid"===t.type)e.push(t);else for(const s of this._layer.outFields)if(s.toLowerCase()===t.name.toLowerCase()){e.push(t);break}this.fields=e}else;if(null!==this._overrideFields)if(1===this._overrideFields.length&&"*"===this._overrideFields[0])this._overrideFields=null;else{const e=[],t=[];for(const s of this.fields)if("oid"===s.type)e.push(s),t.push(s.name);else for(const r of this._overrideFields)if(r.toLowerCase()===s.name.toLowerCase()){e.push(s),t.push(s.name);break}this.fields=e,this._overrideFields=t}this.objectIdField=this._layer.objectIdField;for(const e of this.fields)"global-id"===e.type&&(this.globalIdField=e.name);this.hasM=this._layer.supportsM,this.hasZ=this._layer.supportsZ,this._databaseType=n.Standardised,this.typeIdField=this._layer.typeIdField,this.types=this._layer.types}isTable(){return this._forceIsTable||this._layer.isTable||"table"===this._layer.type||!this._layer.geometryType}_isInFeatureSet(){return l.InFeatureSet}_candidateIdTransform(e){return e}async _getSet(e){if(null===this._wset){await this._ensureLoaded();const t=await this._getFilteredSet("",null,null,null,e);return this._wset=t,t}return this._wset}_changeFeature(t){const s={};for(const e of this.fields)s[e.name]=t.attributes[e.name];return new e({geometry:!0===this._removeGeometry?null:t.geometry,attributes:s})}async _getFilteredSet(e,t,s,r,a){let l="",u=!1;if(null!==r&&(l=r.constructClause(),u=!0),this.isTable()&&t&&null!==e&&""!==e){return new i([],[],!0,null)}const h=new d;h.where=null===s?null===t?"1=1":"":o(s,n.Standardised),h.spatialRelationship=this._makeRelationshipEnum(e),h.outSpatialReference=this.spatialReference,h.orderByFields=""!==l?l.split(","):null,h.geometry=null===t?null:t,h.returnGeometry=!0,h.relationParameter=this._makeRelationshipParam(e);const c=await this._layer.queryFeatures(h);if(null===c)return new i([],[],u,null);this._checkCancelled(a);const y=[];c.features.forEach((e=>{const t=e.attributes[this._layer.objectIdField];y.push(t),this._featureCache[t]=this._changeFeature(e)}));return new i([],y,u,null)}_makeRelationshipEnum(e){if(e.includes("esriSpatialRelRelation"))return"relation";switch(e){case"esriSpatialRelRelation":return"relation";case"esriSpatialRelIntersects":return"intersects";case"esriSpatialRelContains":return"contains";case"esriSpatialRelOverlaps":return"overlaps";case"esriSpatialRelWithin":return"within";case"esriSpatialRelTouches":return"touches";case"esriSpatialRelCrosses":return"crosses";case"esriSpatialRelEnvelopeIntersects":return"envelope-intersects"}return e}_makeRelationshipParam(e){return e.includes("esriSpatialRelRelation")?e.split(":")[1]:""}async _queryAllFeatures(){if(this._wset)return this._wset;const e=new d;if(e.where="1=1",await this._ensureLoaded(),this._layer.source&&this._layer.source.items){const e=[];return this._layer.source.items.forEach((t=>{const s=t.attributes[this._layer.objectIdField];e.push(s),this._featureCache[s]=this._changeFeature(t)})),this._wset=new i([],e,!1,null),this._wset}const t=await this._layer.queryFeatures(e),s=[];return t.features.forEach((e=>{const t=e.attributes[this._layer.objectIdField];s.push(t),this._featureCache[t]=this._changeFeature(e)})),this._wset=new i([],s,!1,null),this._wset}async _getFeatures(e,r,i){const a=[];-1!==r&&void 0===this._featureCache[r]&&a.push(r);for(let t=e._lastFetchedIndex;t<e._known.length&&(e._lastFetchedIndex+=1,!(void 0===this._featureCache[e._known[t]]&&(e._known[t]!==r&&a.push(e._known[t]),a.length>i)));t++);if(0===a.length)return"success";throw new t(s.MissingFeatures)}async _refineSetBlock(e){return e}async _stat(){return{calculated:!1}}async _canDoAggregates(){return!1}relationshipMetaData(){return[]}static _cloneAttr(e){const t={};for(const s in e)t[s]=e[s];return t}nativeCapabilities(){return{title:this._layer.title??"",canQueryRelated:!1,source:this,capabilities:this._layer.capabilities,databaseType:this._databaseType,requestStandardised:!0}}static create(e,t){let s=e.layerDefinition.objectIdField;const r=e.layerDefinition.typeIdField?e.layerDefinition.typeIdField:"",i=[];if(e.layerDefinition.types)for(const u of e.layerDefinition.types)i.push(c.fromJSON(u));let a=e.layerDefinition.geometryType;void 0===a&&(a=e.featureSet.geometryType||"");let n=e.featureSet.features;const l=t.toJSON();if(""===s||void 0===s){let t=!1;for(const r of e.layerDefinition.fields)if("oid"===r.type||"esriFieldTypeOID"===r.type){s=r.name,t=!0;break}if(!1===t){let t="FID",r=!0,i=0;for(;r;){let s=!0;for(const r of e.layerDefinition.fields)if(r.name===t){s=!1;break}!0===s?r=!1:(i++,t="FID"+i.toString())}e.layerDefinition.fields.push({type:"esriFieldTypeOID",name:t,alias:t});const a=[];for(let s=0;s<n.length;s++)a.push({geometry:e.featureSet.features[s].geometry,attributes:e.featureSet.features[s].attributes?this._cloneAttr(e.featureSet.features[s].attributes):{}}),a[s].attributes[t]=s;n=a,s=t}}const o=[];for(const u of e.layerDefinition.fields)u instanceof y?o.push(u):o.push(y.fromJSON(u));let d=a;switch(d){case"esriGeometryPoint":d="point";break;case"esriGeometryPolyline":d="polyline";break;case"esriGeometryPolygon":d="polygon";break;case"esriGeometryExtent":d="extent";break;case"esriGeometryMultipoint":d="multipoint"}for(const h of n)h.geometry&&h.geometry instanceof u==!1&&(h.geometry.type=d,void 0===h.geometry.spatialReference&&(h.geometry.spatialReference=l));const p={outFields:["*"],source:n,fields:o,types:i,typeIdField:r,objectIdField:s,spatialReference:t};p.geometryType=d||"point";const _=new h(p);return new f({layer:_,spatialReference:t,isTable:null===d||""===d})}async queryAttachments(){return[]}async getFeatureByObjectId(e){const t=new d;t.where=this.objectIdField+"="+e.toString();const s=await this._layer.queryFeatures(t);return 1===s.features.length?s.features[0]:null}async getOwningSystemUrl(){return""}async getIdentityUser(){return""}get preferredTimeReference(){return this._layer?.preferredTimeReference?.toJSON()??null}get dateFieldsTimeReference(){return this._layer?.dateFieldsTimeReference?.toJSON()??null}get datesInUnknownTimezone(){return this._layer?.datesInUnknownTimezone}get editFieldsInfo(){return this._layer?.editFieldsInfo?.toJSON()??null}get timeInfo(){return this._layer?.timeInfo?.toJSON()??null}}export{f as default};
5
+ import e from"../../../Graphic.js";import{FeatureSetError as t,FeatureSetErrorCodes as r}from"../support/errorsupport.js";import s from"../support/FeatureSet.js";import i from"../support/IdSet.js";import{defaultMaxRecords as a,FeatureServiceDatabaseType as l,IdState as n}from"../support/shared.js";import{toWhereClause as o}from"../support/sqlUtils.js";import u from"../../../geometry/Geometry.js";import h from"../../../layers/FeatureLayer.js";import c from"../../../layers/support/FeatureType.js";import y from"../../../layers/support/Field.js";import d from"../../../rest/support/Query.js";class f extends s{constructor(e){super(e),this.declaredClass="esri.arcade.featureset.sources.FeatureLayerMemory",this._removeGeometry=!1,this._overrideFields=null,this._forceIsTable=!1,e.spatialReference&&(this.spatialReference=e.spatialReference),this._transparent=!0,this._maxProcessing=1e3,this._layer=e.layer,this._wset=null,!0===e.isTable&&(this._forceIsTable=!0),void 0!==e.outFields&&(this._overrideFields=e.outFields),void 0!==e.includeGeometry&&(this._removeGeometry=!1===e.includeGeometry)}_maxQueryRate(){return a}end(){return this._layer}optimisePagingFeatureQueries(){}async loadImpl(){return!0===this._layer.loaded?(this._initialiseFeatureSet(),this):(await this._layer.load(),this._initialiseFeatureSet(),this)}get gdbVersion(){return""}_initialiseFeatureSet(){if(null==this.spatialReference&&(this.spatialReference=this._layer.spatialReference),this.geometryType=this._layer.geometryType,this.fields=this._layer.fields.slice(0),this._layer.outFields)if(1===this._layer.outFields.length&&"*"===this._layer.outFields[0]);else{const e=[];for(const t of this.fields)if("oid"===t.type)e.push(t);else for(const r of this._layer.outFields)if(r.toLowerCase()===t.name.toLowerCase()){e.push(t);break}this.fields=e}else;if(null!==this._overrideFields)if(1===this._overrideFields.length&&"*"===this._overrideFields[0])this._overrideFields=null;else{const e=[],t=[];for(const r of this.fields)if("oid"===r.type)e.push(r),t.push(r.name);else for(const s of this._overrideFields)if(s.toLowerCase()===r.name.toLowerCase()){e.push(r),t.push(r.name);break}this.fields=e,this._overrideFields=t}this.objectIdField=this._layer.objectIdField;for(const e of this.fields)"global-id"===e.type&&(this.globalIdField=e.name);this.hasM=this._layer.supportsM,this.hasZ=this._layer.supportsZ,this._databaseType=l.Standardised,this.typeIdField=this._layer.typeIdField,this.types=this._layer.types}isTable(){return this._forceIsTable||this._layer.isTable||"table"===this._layer.type||!this._layer.geometryType}_isInFeatureSet(){return n.InFeatureSet}_candidateIdTransform(e){return e}async _getSet(e){if(null===this._wset){await this._ensureLoaded();const t=await this._getFilteredSet("",null,null,null,e);return this._wset=t,t}return this._wset}_changeFeature(t){const r={};for(const e of this.fields)r[e.name]=t.attributes[e.name];return new e({geometry:!0===this._removeGeometry?null:t.geometry,attributes:r})}async _getFilteredSet(e,t,r,s,a){let n="",u=!1;if(null!==s&&(n=s.constructClause(),u=!0),this.isTable()&&t&&null!==e&&""!==e){return new i([],[],!0,null)}const h=new d;h.where=null===r?null===t?"1=1":"":o(r,l.Standardised),h.spatialRelationship=this._makeRelationshipEnum(e),h.outSpatialReference=this.spatialReference,h.orderByFields=""!==n?n.split(","):null,h.geometry=null===t?null:t,h.returnGeometry=!0,h.relationParameter=this._makeRelationshipParam(e);const c=await this._layer.queryFeatures(h);if(null===c)return new i([],[],u,null);this._checkCancelled(a);const y=[];c.features.forEach((e=>{const t=e.attributes[this._layer.objectIdField];y.push(t),this._featureCache[t]=this._changeFeature(e)}));return new i([],y,u,null)}_makeRelationshipEnum(e){if(e.includes("esriSpatialRelRelation"))return"relation";switch(e){case"esriSpatialRelRelation":return"relation";case"esriSpatialRelIntersects":return"intersects";case"esriSpatialRelContains":return"contains";case"esriSpatialRelOverlaps":return"overlaps";case"esriSpatialRelWithin":return"within";case"esriSpatialRelTouches":return"touches";case"esriSpatialRelCrosses":return"crosses";case"esriSpatialRelEnvelopeIntersects":return"envelope-intersects"}return e}_makeRelationshipParam(e){return e.includes("esriSpatialRelRelation")?e.split(":")[1]:""}async _queryAllFeatures(){if(this._wset)return this._wset;const e=new d;if(e.where="1=1",await this._ensureLoaded(),this._layer.source&&this._layer.source.items){const e=[];return this._layer.source.items.forEach((t=>{const r=t.attributes[this._layer.objectIdField];e.push(r),this._featureCache[r]=this._changeFeature(t)})),this._wset=new i([],e,!1,null),this._wset}const t=await this._layer.queryFeatures(e),r=[];return t.features.forEach((e=>{const t=e.attributes[this._layer.objectIdField];r.push(t),this._featureCache[t]=this._changeFeature(e)})),this._wset=new i([],r,!1,null),this._wset}async _getFeatures(e,s,i){const a=[];-1!==s&&void 0===this._featureCache[s]&&a.push(s);for(let t=e._lastFetchedIndex;t<e._known.length&&(e._lastFetchedIndex+=1,!(void 0===this._featureCache[e._known[t]]&&(e._known[t]!==s&&a.push(e._known[t]),a.length>i)));t++);if(0===a.length)return"success";throw new t(r.MissingFeatures)}async _refineSetBlock(e){return e}async _stat(){return{calculated:!1}}async _canDoAggregates(){return!1}relationshipMetaData(){return[]}static _cloneAttr(e){const t={};for(const r in e)t[r]=e[r];return t}nativeCapabilities(){return{title:this._layer.title??"",canQueryRelated:!1,source:this,capabilities:this._layer.capabilities,databaseType:this._databaseType,requestStandardised:!0}}static create(e,t){let r=e.layerDefinition.objectIdField;const s=e.layerDefinition.typeIdField?e.layerDefinition.typeIdField:"",i=[];if(e.layerDefinition.types)for(const u of e.layerDefinition.types)i.push(c.fromJSON(u));let a=e.layerDefinition.geometryType;void 0===a&&(a=e.featureSet.geometryType||"");let l=e.featureSet.features;const n=t.toJSON();if(""===r||void 0===r){let t=!1;for(const s of e.layerDefinition.fields)if("oid"===s.type||"esriFieldTypeOID"===s.type){r=s.name,t=!0;break}if(!1===t){let t="FID",s=!0,i=0;for(;s;){let r=!0;for(const s of e.layerDefinition.fields)if(s.name===t){r=!1;break}!0===r?s=!1:(i++,t="FID"+i.toString())}e.layerDefinition.fields.push({type:"esriFieldTypeOID",name:t,alias:t});const a=[];for(let r=0;r<l.length;r++)a.push({geometry:e.featureSet.features[r].geometry,attributes:e.featureSet.features[r].attributes?this._cloneAttr(e.featureSet.features[r].attributes):{}}),a[r].attributes[t]=r;l=a,r=t}}const o=[];for(const u of e.layerDefinition.fields)u instanceof y?o.push(u):o.push(y.fromJSON(u));let d=a;switch(d||(d=""),d){case"esriGeometryPoint":d="point";break;case"esriGeometryPolyline":d="polyline";break;case"esriGeometryPolygon":d="polygon";break;case"esriGeometryExtent":d="extent";break;case"esriGeometryMultipoint":d="multipoint";break;case"":case"esriGeometryNull":d="esriGeometryNull"}if("esriGeometryNull"!==d)for(const h of l)h.geometry&&h.geometry instanceof u==!1&&(h.geometry.type=d,void 0===h.geometry.spatialReference&&(h.geometry.spatialReference=n));else for(const u of l)u.geometry&&(u.geometry=null);const p={outFields:["*"],source:l,fields:o,types:i,typeIdField:s,objectIdField:r,spatialReference:t};""!==d&&"esriGeometryNull"!==d&&null!==d&&(p.geometryType=d);const m=new h(p);return new f({layer:m,spatialReference:t,isTable:null===d||""===d||"esriGeometryNull"===d})}async queryAttachments(){return[]}async getFeatureByObjectId(e){const t=new d;t.where=this.objectIdField+"="+e.toString();const r=await this._layer.queryFeatures(t);return 1===r.features.length?r.features[0]:null}async getOwningSystemUrl(){return""}async getIdentityUser(){return""}get preferredTimeReference(){return this._layer?.preferredTimeReference?.toJSON()??null}get dateFieldsTimeReference(){return this._layer?.dateFieldsTimeReference?.toJSON()??null}get datesInUnknownTimezone(){return this._layer?.datesInUnknownTimezone}get editFieldsInfo(){return this._layer?.editFieldsInfo?.toJSON()??null}get timeInfo(){return this._layer?.timeInfo?.toJSON()??null}}export{f as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.26/esri/copyright.txt for details.
4
4
  */
5
- import{DateTimeReferenceFieldIndex as e}from"../../arcadeTimeUtils.js";import t from"./cache.js";import{FeatureSetError as s,FeatureSetErrorCodes as r}from"./errorsupport.js";import n from"./FeatureSetIterator.js";import i from"./IdSet.js";import{FeatureServiceDatabaseType as a,layerGeometryEsriConstants as l,IdState as u,convertSquareUnitsToCode as h,convertLinearUnitsToCode as c,esriFieldToJson as o,layerGeometryEsriRestConstants as d}from"./shared.js";import{max as _,min as p,sum as f,variance as g,stdev as m,mean as y,distinct as F,count as b}from"./stats.js";import{isPromiseLike as I}from"../../../core/promiseUtils.js";import{WhereClause as w}from"../../../core/sql/WhereClause.js";import{union as S,geodesicArea as T,planarArea as P,geodesicLength as x,planarLength as k}from"../../../geometry/geometryEngineAsync.js";import D from"../../../geometry/SpatialReference.js";import C from"../../../layers/support/FieldsIndex.js";class v{constructor(e){this.recentlyUsedQueries=null,this.featureSetQueryInterceptor=null,this._idstates=[],this._parent=null,this._wset=null,this._mainSetInUse=null,this._maxProcessing=200,this._maxQuery=500,this._totalCount=-1,this._databaseType=a.NotEvaluated,this._databaseTypeProbed=null,this.declaredRootClass="esri.arcade.featureset.support.FeatureSet",this._featureCache=[],this.typeIdField=null,this.types=null,this.fields=null,this.geometryType="",this.objectIdField="",this.globalIdField="",this.spatialReference=null,this.hasM=!1,this.hasZ=!1,this._transparent=!1,this.loaded=!1,this._loadPromise=null,this._fieldsIndex=null,this._dateFieldIndex=null,e&&e.lrucache&&(this.recentlyUsedQueries=e.lrucache),e&&e.interceptor&&(this.featureSetQueryInterceptor=e.interceptor)}optimisePagingFeatureQueries(e){this._parent&&this._parent.optimisePagingFeatureQueries(e)}_hasMemorySource(){return!0}prop(e,t){return void 0===t?this[e]:(void 0!==this[e]&&(this[e]=t),this)}end(){return null!==this._parent&&!0===this._parent._transparent?this._parent.end():this._parent}_ensureLoaded(){return this.load()}load(){return null===this._loadPromise&&(this._loadPromise=this.loadImpl()),this._loadPromise}async loadImpl(){return!0===this._parent?.loaded?(this._initialiseFeatureSet(),this):(await(this._parent?.load()),this._initialiseFeatureSet(),this)}_initialiseFeatureSet(){null!==this._parent?(this.fields=this._parent.fields.slice(0),this.geometryType=this._parent.geometryType,this.objectIdField=this._parent.objectIdField,this.globalIdField=this._parent.globalIdField,this.spatialReference=this._parent.spatialReference,this.hasM=this._parent.hasM,this.hasZ=this._parent.hasZ,this.typeIdField=this._parent.typeIdField,this.types=this._parent.types):(this.fields=[],this.typeIdField="",this.objectIdField="",this.globalIdField="",this.spatialReference=new D({wkid:4326}),this.geometryType=l.point)}getField(e,t){let s;return(t=t||this.fields)&&(e=e.toLowerCase(),t.some((t=>(t&&t.name.toLowerCase()===e&&(s=t),!!s)))),s}getFieldsIndex(){return null===this._fieldsIndex&&(this._fieldsIndex=new C(this.fields)),this._fieldsIndex}_maxProcessingRate(){return null!==this._parent?Math.min(this._maxProcessing,this._parent._maxProcessingRate()):Math.min(this._maxProcessing,this._maxQueryRate())}_maxQueryRate(){return null!==this._parent?Math.max(this._maxQuery,this._parent._maxQueryRate()):this._maxQuery}_checkCancelled(e){if(null!=e&&e.aborted)throw new s(r.Cancelled)}nativeCapabilities(){return this._parent.nativeCapabilities()}async _canDoAggregates(e,t,s,r,n){return null!==this._parent&&this._parent._canDoAggregates(e,t,s,r,n)}async _getAggregatePagesDataSourceDefinition(e,t,n,i,a,l,u){if(null===this._parent)throw new s(r.NeverReach);return this._parent._getAggregatePagesDataSourceDefinition(e,t,n,i,a,l,u)}async _getAgregagtePhysicalPage(e,t,n){if(null===this._parent)throw new s(r.NeverReach);return this._parent._getAgregagtePhysicalPage(e,t,n)}async databaseType(){if(this._databaseType===a.NotEvaluated){if(null!==t.applicationCache){const e=t.applicationCache.getDatabaseType(this._cacheableFeatureSetSourceKey());if(null!==e)return e}if(null!==this._databaseTypeProbed)return this._databaseTypeProbed;try{this._databaseTypeProbed=this._getDatabaseTypeImpl(),null!==t.applicationCache&&t.applicationCache.setDatabaseType(this._cacheableFeatureSetSourceKey(),this._databaseTypeProbed)}catch(e){throw null!==t.applicationCache&&t.applicationCache.clearDatabaseType(this._cacheableFeatureSetSourceKey()),e}return this._databaseTypeProbed}return this._databaseType}async _getDatabaseTypeImpl(){const e=[{thetype:a.SqlServer,testwhere:"(CAST( '2015-01-01' as DATETIME) = CAST( '2015-01-01' as DATETIME)) AND OBJECTID<0"},{thetype:a.Oracle,testwhere:"(TO_DATE('2003-11-18','YYYY-MM-DD') = TO_DATE('2003-11-18','YYYY-MM-DD')) AND OBJECTID<0"},{thetype:a.StandardisedNoInterval,testwhere:"(date '2015-01-01 10:10:10' = date '2015-01-01 10:10:10') AND OBJECTID<0"}];for(const t of e){if(!0===await this._runDatabaseProbe(t.testwhere))return t.thetype}return a.StandardisedNoInterval}_cacheableFeatureSetSourceKey(){return"MUSTBESET"}async _runDatabaseProbe(e){if(null!==this._parent)return this._parent._runDatabaseProbe(e);throw new s(r.NotImplemented)}isTable(){return this._parent?.isTable()??!1}_featureFromCache(e){if(void 0!==this._featureCache[e])return this._featureCache[e]}_isInFeatureSet(e){return u.Unknown}_getSet(e){throw new s(r.NotImplemented)}async _getFeature(e,t,n){if(this._checkCancelled(n),void 0!==this._featureFromCache(t))return this._featureFromCache(t);if(await this._getFeatures(e,t,this._maxProcessingRate(),n),this._checkCancelled(n),void 0!==this._featureFromCache(t))return this._featureFromCache(t);throw new s(r.MissingFeatures)}async _getFeatureBatch(e,t){this._checkCancelled(t);const s=new i([],e,!1,null),r=[];await this._getFeatures(s,-1,e.length,t),this._checkCancelled(t);for(const n of e)void 0!==this._featureFromCache(n)&&r.push(this._featureFromCache(n));return r}async _getFeatures(e,t,s,r){return"success"}_getFilteredSet(e,t,n,i,a){throw new s(r.NotImplemented)}async _refineSetBlock(e,t,s){if(!0===this._checkIfNeedToExpandCandidatePage(e,this._maxQueryRate()))return await this._expandPagedSet(e,this._maxQueryRate(),0,0,s),this._refineSetBlock(e,t,s);this._checkCancelled(s);const r=e._candidates.length;this._refineKnowns(e,t);let n=r-e._candidates.length;if(0===e._candidates.length)return e;if(n>=t)return e;if(await this._refineIfParentKnown(e,t-n,s),this._checkCancelled(s),this._refineKnowns(e,t-n),n=r-e._candidates.length,n<t&&e._candidates.length>0){const r=t-n,i=this._prepareFetchAndRefineSet(e._candidates);return await this._fetchAndRefineFeatures(i,i.length>r?r:e._candidates.length,s),this._checkCancelled(s),this._refineKnowns(e,t-n),e}return e}_fetchAndRefineFeatures(e,t,s){return null}_prepareFetchAndRefineSet(e){const t=[];for(let s=0;s<e.length;s++)this._isPhysicalFeature(e[s])&&t.push(e[s]);return t}_isPhysicalFeature(e){return null===this._parent||this._parent._isPhysicalFeature(e)}_refineKnowns(e,t){let s=0,r=null;const n=[];t=this._maxQueryRate();for(let i=0;i<e._candidates.length&&"GETPAGES"!==e._candidates[i];i++){let a=!1;const l=this._candidateIdTransform(e._candidates[i]);l!==e._candidates[i]&&(a=!0);const h=this._isInFeatureSet(l);if(h===u.InFeatureSet)!0===a?e._known.includes(l)||(e._known.push(l),s+=1):(e._known.push(e._candidates[i]),s+=1),null===r?r={start:i,end:i}:r.end===i-1?r.end=i:(n.push(r),r={start:i,end:i});else if(h===u.NotInFeatureSet)null===r?r={start:i,end:i}:r.end===i-1?r.end=i:(n.push(r),r={start:i,end:i}),s+=1;else if(h===u.Unknown&&(s+=1,!0===e._ordered))break;if(s>=t)break}null!==r&&n.push(r);for(let i=n.length-1;i>=0;i--)e._candidates.splice(n[i].start,n[i].end-n[i].start+1)}_refineIfParentKnown(e,t,s){const r=new i([],[],e._ordered,null);return r._candidates=e._candidates.slice(0),this._parent._refineSetBlock(r,t,s)}_candidateIdTransform(e){return this._parent._candidateIdTransform(e)}_checkIfNeedToExpandKnownPage(e,t){if(null===e.pagesDefinition)return!1;let s=0;for(let r=e._lastFetchedIndex;r<e._known.length;r++){if("GETPAGES"===e._known[r])return!0;if(void 0===this._featureCache[e._known[r]]&&(s+=1,s>=t))break}return!1}_checkIfNeedToExpandCandidatePage(e,t){if(null===e.pagesDefinition)return!1;let s=0;for(let r=0;r<e._candidates.length;r++){if("GETPAGES"===e._candidates[r])return!0;if(s+=1,s>=t)break}return!1}async _expandPagedSet(e,t,n,i,a){if(null===this._parent)throw new s(r.NotImplemented);return this._parent._expandPagedSet(e,t,n,i,a)}async _expandPagedSetFeatureSet(e,t,s,r,n){if(e._known.length>0&&"GETPAGES"===e._known[e._known.length-1]&&(r=1),0===r&&e._candidates.length>0&&"GETPAGES"===e._candidates[e._candidates.length-1]&&(r=2),0===r)return"finished";const i=await this._getPage(e,r,n);return s+i<t?this._expandPagedSet(e,t,s+i,0,n):"success"}async _getPage(e,t,s){const r=1===t?e._known:e._candidates;if(e.pagesDefinition.internal.set.length>e.pagesDefinition.resultOffset||!0===e.pagesDefinition.internal.fullyResolved){r.length=r.length-1;let t=0;for(let n=0;n<e.pagesDefinition.resultRecordCount&&!(e.pagesDefinition.resultOffset+n>=e.pagesDefinition.internal.set.length);n++)r[r.length]=e.pagesDefinition.internal.set[e.pagesDefinition.resultOffset+n],t++;e.pagesDefinition.resultOffset+=t;let s=!1;return!0===e.pagesDefinition.internal.fullyResolved&&e.pagesDefinition.internal.set.length<=e.pagesDefinition.resultOffset&&(s=!0),!1===s&&r.push("GETPAGES"),t}return await this._getPhysicalPage(e,t,s),this._getPage(e,t,s)}_getPhysicalPage(e,t,s){return null}_clonePageDefinition(e){return null===this._parent?null:this._parent._clonePageDefinition(e)}_first(e){return this.iterator(e).next()}first(e){return this._first(e)}async calculateStatistic(e,t,s,r){await this._ensureLoaded();let n=await this._stat(e,t,"",null,null,s,r);return!1===n.calculated&&(n=await this._manualStat(e,t,s,r)),n.result}async _manualStat(e,t,s,r){let n=null;switch(e.toLowerCase()){case"count":return n=await b(this,r),{calculated:!0,result:n};case"distinct":return n=await F(this,t,s,r),{calculated:!0,result:n};case"avg":case"mean":return n=await y(this,t,r),{calculated:!0,result:n};case"stdev":return n=await m(this,t,r),{calculated:!0,result:n};case"variance":return n=await g(this,t,r),{calculated:!0,result:n};case"sum":return n=await f(this,t,r),{calculated:!0,result:n};case"min":return n=await p(this,t,r),{calculated:!0,result:n};case"max":return n=await _(this,t,r),{calculated:!0,result:n};default:return{calculated:!0,result:0}}}async _stat(e,t,s,r,n,i,a){const l=await this._parent._stat(e,t,s,r,n,i,a);return!1===l.calculated?null===n&&""===s&&null===r?this._manualStat(e,t,i,a):{calculated:!1}:l}_unionAllGeomSelf(e){const t=this.iterator(this._defaultTracker(e)),s=[];return new Promise(((e,r)=>{this._unionShapeInBatches(s,t,e,r)}))}_unionAllGeom(e){return new Promise(((t,s)=>{const r=this.iterator(this._defaultTracker(e)),n=[];this._unionShapeInBatches(n,r,t,s)}))}_unionShapeInBatches(e,t,s,r){t.next().then((n=>{try{null!==n&&null!==n.geometry&&e.push(n.geometry),e.length>30||null===n&&e.length>1?S(e).then((i=>{try{null===n?s(i):(e=[i],this._unionShapeInBatches(e,t,s,r))}catch(a){r(a)}}),r):null===n?1===e.length?s(e[0]):s(null):this._unionShapeInBatches(e,t,s,r)}catch(i){r(i)}}),r)}iterator(e){return new n(this,e)}intersection(e,t=!1){return v._featuresetFunctions.intersection.bind(this)(e,t)}difference(e,t=!1,s=!0){return v._featuresetFunctions.difference.bind(this)(e,t,s)}symmetricDifference(e,t=!1,s=!0){return v._featuresetFunctions.symmetricDifference.bind(this)(e,t,s)}morphShape(e,t,s="unknown",r=null){return v._featuresetFunctions.morphShape.bind(this)(e,t,s,r)}morphShapeAndAttributes(e,t,s="unknown"){return v._featuresetFunctions.morphShapeAndAttributes.bind(this)(e,t,s)}union(e,t=!1){return v._featuresetFunctions.union.bind(this)(e,t)}intersects(e){return v._featuresetFunctions.intersects.bind(this)(e)}envelopeIntersects(e){return v._featuresetFunctions.envelopeIntersects.bind(this)(e)}contains(e){return v._featuresetFunctions.contains.bind(this)(e)}overlaps(e){return v._featuresetFunctions.overlaps.bind(this)(e)}relate(e,t){return v._featuresetFunctions.relate.bind(this)(e,t)}within(e){return v._featuresetFunctions.within.bind(this)(e)}touches(e){return v._featuresetFunctions.touches.bind(this)(e)}top(e){return v._featuresetFunctions.top.bind(this)(e)}crosses(e){return v._featuresetFunctions.crosses.bind(this)(e)}buffer(e,t,s,r=!0){return v._featuresetFunctions.buffer.bind(this)(e,t,s,r)}filter(e,t=null){return v._featuresetFunctions.filter.bind(this)(e,t)}orderBy(e){return v._featuresetFunctions.orderBy.bind(this)(e)}dissolve(e,t){return v._featuresetFunctions.dissolve.bind(this)(e,t)}groupby(e,t){return v._featuresetFunctions.groupby.bind(this)(e,t)}reduce(e,t=null,s){return new Promise(((r,n)=>{this._reduceImpl(this.iterator(this._defaultTracker(s)),e,t,0,r,n,0)}))}_reduceImpl(e,t,s,r,n,i,a){try{if(++a>1e3)return void setTimeout((()=>{a=0,this._reduceImpl(e,t,s,r,n,i,a)}));e.next().then((l=>{try{if(null===l)n(s);else{const u=t(s,l,r,this);I(u)?u.then((s=>{this._reduceImpl(e,t,s,r+1,n,i,a)}),i):this._reduceImpl(e,t,u,r+1,n,i,a)}}catch(u){i(u)}}),i)}catch(l){i(l)}}removeField(e){return v._featuresetFunctions.removeField.bind(this)(e)}addField(e,t,s=null){return v._featuresetFunctions.addField.bind(this)(e,t,s)}sumArea(e,t=!1,s){const r=h(e);return this.reduce(((e,s)=>null===s.geometry?0:t?T(s.geometry,r).then((t=>e+t)):P(s.geometry,r).then((t=>e+t))),0,s)}sumLength(e,t=!1,s){const r=c(e);return this.reduce(((e,s)=>null===s.geometry?0:t?x(s.geometry,r).then((t=>e+t)):k(s.geometry,r).then((t=>e+t))),0,s)}_substituteVars(e,t){if(null!==t){const s={};for(const e in t)s[e.toLowerCase()]=t[e];e.parameters=s}}async distinct(e,t=1e3,s=null,r){await this.load();const n=w.create(e,this.getFieldsIndex());return this._substituteVars(n,s),this.calculateStatistic("distinct",n,t,this._defaultTracker(r))}async min(e,t=null,s){await this.load();const r=w.create(e,this.getFieldsIndex());return this._substituteVars(r,t),this.calculateStatistic("min",r,-1,this._defaultTracker(s))}async max(e,t=null,s){await this.load();const r=w.create(e,this.getFieldsIndex());return this._substituteVars(r,t),this.calculateStatistic("max",r,-1,this._defaultTracker(s))}async avg(e,t=null,s){await this.load();const r=w.create(e,this.getFieldsIndex());return this._substituteVars(r,t),this.calculateStatistic("avg",r,-1,this._defaultTracker(s))}async sum(e,t=null,s){await this.load();const r=w.create(e,this.getFieldsIndex());return this._substituteVars(r,t),this.calculateStatistic("sum",r,-1,this._defaultTracker(s))}async stdev(e,t=null,s){await this.load();const r=w.create(e,this.getFieldsIndex());return this._substituteVars(r,t),this.calculateStatistic("stdev",r,-1,this._defaultTracker(s))}async variance(e,t=null,s){await this.load();const r=w.create(e,this.getFieldsIndex());return this._substituteVars(r,t),this.calculateStatistic("variance",r,-1,this._defaultTracker(s))}async count(e){return await this.load(),this.calculateStatistic("count",w.create("1",this.getFieldsIndex()),-1,this._defaultTracker(e))}_defaultTracker(e){return e||{aborted:!1}}forEach(e,t){return new Promise(((s,r)=>{this._forEachImpl(this.iterator(this._defaultTracker(t)),e,this,s,r,0)}))}_forEachImpl(e,t,s,r,n,i){try{if(++i>1e3)return void setTimeout((()=>{i=0,this._forEachImpl(e,t,s,r,n,i)}),0);e.next().then((a=>{try{if(null===a)r(s);else{const l=t(a);null==l?this._forEachImpl(e,t,s,r,n,i):I(l)?l.then((()=>{try{this._forEachImpl(e,t,s,r,n,i)}catch(a){n(a)}}),n):this._forEachImpl(e,t,s,r,n,i)}}catch(l){n(l)}}),n)}catch(a){n(a)}}convertToJSON(e){const t={layerDefinition:{geometryType:this.geometryType,fields:[]},featureSet:{features:[],geometryType:this.geometryType}};for(let s=0;s<this.fields.length;s++)t.layerDefinition.fields.push(o(this.fields[s]));return this.reduce(((e,s)=>{const r={geometry:s.geometry&&s.geometry.toJSON(),attributes:{}};for(const t in s.attributes)r.attributes[t]=s.attributes[t];return t.featureSet.features.push(r),1}),0,e).then((()=>t))}castToText(e=!1){return"object, FeatureSet"}queryAttachments(e,t,s,r,n){return this._parent.queryAttachments(e,t,s,r,n)}serviceUrl(){return this._parent.serviceUrl()}subtypes(){return this.typeIdField?{subtypeField:this.typeIdField,subtypes:this.types?this.types.map((e=>({name:e.name,code:e.id}))):[]}:null}relationshipMetaData(){return this._parent.relationshipMetaData()}get gdbVersion(){return this._parent?this._parent.gdbVersion:""}schema(){const e=[];for(const t of this.fields)e.push(o(t));return{objectIdField:this.objectIdField,globalIdField:this.globalIdField,geometryType:void 0===d[this.geometryType]?"":d[this.geometryType],fields:e}}async convertToText(e,t){if("schema"===e)return await this._ensureLoaded(),JSON.stringify(this.schema());if("featureset"===e){await this._ensureLoaded();const e=[];await this.reduce(((t,s)=>{const r={geometry:s.geometry?s.geometry.toJSON():null,attributes:s.attributes};return null!==r.geometry&&r.geometry.spatialReference&&delete r.geometry.spatialReference,e.push(r),1}),0,t);const s=this.schema();return s.features=e,s.spatialReference=this.spatialReference.toJSON(),JSON.stringify(s)}return this.castToText()}getFeatureByObjectId(e,t){return this._parent.getFeatureByObjectId(e,t)}getOwningSystemUrl(){return this._parent.getOwningSystemUrl()}getIdentityUser(){return this._parent.getIdentityUser()}getRootFeatureSet(){return null!==this._parent?this._parent.getRootFeatureSet():this}getDataSourceFeatureSet(){return null!==this._parent?this._parent.getDataSourceFeatureSet():this}castAsJson(e=null){return"keeptype"===e?.featureset?this:"none"===e?.featureset?null:{type:"FeatureSet"}}async castAsJsonAsync(e=null,t=null){if("keeptype"===t?.featureset)return this;if("schema"===t?.featureset)return await this._ensureLoaded(),JSON.parse(JSON.stringify(this.schema()));if("none"===t?.featureset)return null;await this._ensureLoaded();const s=[];await this.reduce(((e,r)=>{const n={geometry:r.geometry?!0===t?.keepGeometryType?r.geometry:r.geometry.toJSON():null,attributes:r.attributes};return null!==n.geometry&&n.geometry.spatialReference&&!0!==t?.keepGeometryType&&delete n.geometry.spatialReference,s.push(n),1}),0,e);const r=this.schema();return r.features=s,r.spatialReference=!0===t?.keepGeometryType?this.spatialReference:this.spatialReference?.toJSON(),r}get dateTimeReferenceFieldIndex(){return null===this._dateFieldIndex&&(this._dateFieldIndex=e.create(this.getFieldsIndex(),this)),this._dateFieldIndex}fieldTimeZone(e){return this.dateTimeReferenceFieldIndex.fieldTimeZone(e)}get preferredTimeReference(){return this._parent?.preferredTimeReference??null}get dateFieldsTimeReference(){return this._parent?.dateFieldsTimeReference??null}get datesInUnknownTimezone(){return this._parent.datesInUnknownTimezone}get editFieldsInfo(){return this._parent?.editFieldsInfo??null}get timeInfo(){return this._parent?.timeInfo??null}}v._featuresetFunctions={};export{v as default};
5
+ import{DateTimeReferenceFieldIndex as e}from"../../arcadeTimeUtils.js";import t from"./cache.js";import{FeatureSetError as s,FeatureSetErrorCodes as r}from"./errorsupport.js";import n from"./FeatureSetIterator.js";import i from"./IdSet.js";import{FeatureServiceDatabaseType as a,layerGeometryEsriConstants as l,IdState as u,convertSquareUnitsToCode as h,convertLinearUnitsToCode as c,esriFieldToJson as o,layerGeometryEsriRestConstants as d}from"./shared.js";import{max as _,min as p,sum as f,variance as g,stdev as m,mean as y,distinct as F,count as b}from"./stats.js";import{isPromiseLike as I}from"../../../core/promiseUtils.js";import{WhereClause as w}from"../../../core/sql/WhereClause.js";import{union as S,geodesicArea as T,planarArea as P,geodesicLength as x,planarLength as k}from"../../../geometry/geometryEngineAsync.js";import D from"../../../geometry/SpatialReference.js";import C from"../../../layers/support/FieldsIndex.js";class v{constructor(e){this.recentlyUsedQueries=null,this.featureSetQueryInterceptor=null,this._idstates=[],this._parent=null,this._wset=null,this._mainSetInUse=null,this._maxProcessing=200,this._maxQuery=500,this._totalCount=-1,this._databaseType=a.NotEvaluated,this._databaseTypeProbed=null,this.declaredRootClass="esri.arcade.featureset.support.FeatureSet",this._featureCache=[],this.typeIdField=null,this.types=null,this.fields=null,this.geometryType="",this.objectIdField="",this.globalIdField="",this.spatialReference=null,this.hasM=!1,this.hasZ=!1,this._transparent=!1,this.loaded=!1,this._loadPromise=null,this._fieldsIndex=null,this._dateFieldIndex=null,e&&e.lrucache&&(this.recentlyUsedQueries=e.lrucache),e&&e.interceptor&&(this.featureSetQueryInterceptor=e.interceptor)}optimisePagingFeatureQueries(e){this._parent&&this._parent.optimisePagingFeatureQueries(e)}_hasMemorySource(){return!0}prop(e,t){return void 0===t?this[e]:(void 0!==this[e]&&(this[e]=t),this)}end(){return null!==this._parent&&!0===this._parent._transparent?this._parent.end():this._parent}_ensureLoaded(){return this.load()}load(){return null===this._loadPromise&&(this._loadPromise=this.loadImpl()),this._loadPromise}async loadImpl(){return!0===this._parent?.loaded?(this._initialiseFeatureSet(),this):(await(this._parent?.load()),this._initialiseFeatureSet(),this)}_initialiseFeatureSet(){null!==this._parent?(this.fields=this._parent.fields.slice(0),this.geometryType=this._parent.geometryType,this.objectIdField=this._parent.objectIdField,this.globalIdField=this._parent.globalIdField,this.spatialReference=this._parent.spatialReference,this.hasM=this._parent.hasM,this.hasZ=this._parent.hasZ,this.typeIdField=this._parent.typeIdField,this.types=this._parent.types):(this.fields=[],this.typeIdField="",this.objectIdField="",this.globalIdField="",this.spatialReference=new D({wkid:4326}),this.geometryType=l.point)}getField(e,t){let s;return(t=t||this.fields)&&(e=e.toLowerCase(),t.some((t=>(t&&t.name.toLowerCase()===e&&(s=t),!!s)))),s}getFieldsIndex(){return null===this._fieldsIndex&&(this._fieldsIndex=new C(this.fields)),this._fieldsIndex}_maxProcessingRate(){return null!==this._parent?Math.min(this._maxProcessing,this._parent._maxProcessingRate()):Math.min(this._maxProcessing,this._maxQueryRate())}_maxQueryRate(){return null!==this._parent?Math.max(this._maxQuery,this._parent._maxQueryRate()):this._maxQuery}_checkCancelled(e){if(null!=e&&e.aborted)throw new s(r.Cancelled)}nativeCapabilities(){return this._parent.nativeCapabilities()}async _canDoAggregates(e,t,s,r,n){return null!==this._parent&&this._parent._canDoAggregates(e,t,s,r,n)}async _getAggregatePagesDataSourceDefinition(e,t,n,i,a,l,u){if(null===this._parent)throw new s(r.NeverReach);return this._parent._getAggregatePagesDataSourceDefinition(e,t,n,i,a,l,u)}async _getAgregagtePhysicalPage(e,t,n){if(null===this._parent)throw new s(r.NeverReach);return this._parent._getAgregagtePhysicalPage(e,t,n)}async databaseType(){if(this._databaseType===a.NotEvaluated){if(null!==t.applicationCache){const e=t.applicationCache.getDatabaseType(this._cacheableFeatureSetSourceKey());if(null!==e)return e}if(null!==this._databaseTypeProbed)return this._databaseTypeProbed;try{this._databaseTypeProbed=this._getDatabaseTypeImpl(),null!==t.applicationCache&&t.applicationCache.setDatabaseType(this._cacheableFeatureSetSourceKey(),this._databaseTypeProbed)}catch(e){throw null!==t.applicationCache&&t.applicationCache.clearDatabaseType(this._cacheableFeatureSetSourceKey()),e}return this._databaseTypeProbed}return this._databaseType}async _getDatabaseTypeImpl(){const e=[{thetype:a.SqlServer,testwhere:"(CAST( '2015-01-01' as DATETIME) = CAST( '2015-01-01' as DATETIME)) AND OBJECTID<0"},{thetype:a.Oracle,testwhere:"(TO_DATE('2003-11-18','YYYY-MM-DD') = TO_DATE('2003-11-18','YYYY-MM-DD')) AND OBJECTID<0"},{thetype:a.StandardisedNoInterval,testwhere:"(date '2015-01-01 10:10:10' = date '2015-01-01 10:10:10') AND OBJECTID<0"}];for(const t of e){if(!0===await this._runDatabaseProbe(t.testwhere))return t.thetype}return a.StandardisedNoInterval}_cacheableFeatureSetSourceKey(){return"MUSTBESET"}async _runDatabaseProbe(e){if(null!==this._parent)return this._parent._runDatabaseProbe(e);throw new s(r.NotImplemented)}isTable(){return this._parent?.isTable()??!1}_featureFromCache(e){if(void 0!==this._featureCache[e])return this._featureCache[e]}_isInFeatureSet(e){return u.Unknown}_getSet(e){throw new s(r.NotImplemented)}async _getFeature(e,t,n){if(this._checkCancelled(n),void 0!==this._featureFromCache(t))return this._featureFromCache(t);if(await this._getFeatures(e,t,this._maxProcessingRate(),n),this._checkCancelled(n),void 0!==this._featureFromCache(t))return this._featureFromCache(t);throw new s(r.MissingFeatures)}async _getFeatureBatch(e,t){this._checkCancelled(t);const s=new i([],e,!1,null),r=[];await this._getFeatures(s,-1,e.length,t),this._checkCancelled(t);for(const n of e)void 0!==this._featureFromCache(n)&&r.push(this._featureFromCache(n));return r}async _getFeatures(e,t,s,r){return"success"}_getFilteredSet(e,t,n,i,a){throw new s(r.NotImplemented)}async _refineSetBlock(e,t,s){if(!0===this._checkIfNeedToExpandCandidatePage(e,this._maxQueryRate()))return await this._expandPagedSet(e,this._maxQueryRate(),0,0,s),this._refineSetBlock(e,t,s);this._checkCancelled(s);const r=e._candidates.length;this._refineKnowns(e,t);let n=r-e._candidates.length;if(0===e._candidates.length)return e;if(n>=t)return e;if(await this._refineIfParentKnown(e,t-n,s),this._checkCancelled(s),this._refineKnowns(e,t-n),n=r-e._candidates.length,n<t&&e._candidates.length>0){const r=t-n,i=this._prepareFetchAndRefineSet(e._candidates);return await this._fetchAndRefineFeatures(i,i.length>r?r:e._candidates.length,s),this._checkCancelled(s),this._refineKnowns(e,t-n),e}return e}_fetchAndRefineFeatures(e,t,s){return null}_prepareFetchAndRefineSet(e){const t=[];for(let s=0;s<e.length;s++)this._isPhysicalFeature(e[s])&&t.push(e[s]);return t}_isPhysicalFeature(e){return null===this._parent||this._parent._isPhysicalFeature(e)}_refineKnowns(e,t){let s=0,r=null;const n=[];t=this._maxQueryRate();for(let i=0;i<e._candidates.length&&"GETPAGES"!==e._candidates[i];i++){let a=!1;const l=this._candidateIdTransform(e._candidates[i]);l!==e._candidates[i]&&(a=!0);const h=this._isInFeatureSet(l);if(h===u.InFeatureSet)!0===a?e._known.includes(l)||(e._known.push(l),s+=1):(e._known.push(e._candidates[i]),s+=1),null===r?r={start:i,end:i}:r.end===i-1?r.end=i:(n.push(r),r={start:i,end:i});else if(h===u.NotInFeatureSet)null===r?r={start:i,end:i}:r.end===i-1?r.end=i:(n.push(r),r={start:i,end:i}),s+=1;else if(h===u.Unknown&&(s+=1,!0===e._ordered))break;if(s>=t)break}null!==r&&n.push(r);for(let i=n.length-1;i>=0;i--)e._candidates.splice(n[i].start,n[i].end-n[i].start+1)}_refineIfParentKnown(e,t,s){const r=new i([],[],e._ordered,null);return r._candidates=e._candidates.slice(0),this._parent._refineSetBlock(r,t,s)}_candidateIdTransform(e){return this._parent._candidateIdTransform(e)}_checkIfNeedToExpandKnownPage(e,t){if(null===e.pagesDefinition)return!1;let s=0;for(let r=e._lastFetchedIndex;r<e._known.length;r++){if("GETPAGES"===e._known[r])return!0;if(void 0===this._featureCache[e._known[r]]&&(s+=1,s>=t))break}return!1}_checkIfNeedToExpandCandidatePage(e,t){if(null===e.pagesDefinition)return!1;let s=0;for(let r=0;r<e._candidates.length;r++){if("GETPAGES"===e._candidates[r])return!0;if(s+=1,s>=t)break}return!1}async _expandPagedSet(e,t,n,i,a){if(null===this._parent)throw new s(r.NotImplemented);return this._parent._expandPagedSet(e,t,n,i,a)}async _expandPagedSetFeatureSet(e,t,s,r,n){if(e._known.length>0&&"GETPAGES"===e._known[e._known.length-1]&&(r=1),0===r&&e._candidates.length>0&&"GETPAGES"===e._candidates[e._candidates.length-1]&&(r=2),0===r)return"finished";const i=await this._getPage(e,r,n);return s+i<t?this._expandPagedSet(e,t,s+i,0,n):"success"}async _getPage(e,t,s){const r=1===t?e._known:e._candidates;if(e.pagesDefinition.internal.set.length>e.pagesDefinition.resultOffset||!0===e.pagesDefinition.internal.fullyResolved){r.length=r.length-1;let t=0;for(let n=0;n<e.pagesDefinition.resultRecordCount&&!(e.pagesDefinition.resultOffset+n>=e.pagesDefinition.internal.set.length);n++)r[r.length]=e.pagesDefinition.internal.set[e.pagesDefinition.resultOffset+n],t++;e.pagesDefinition.resultOffset+=t;let s=!1;return!0===e.pagesDefinition.internal.fullyResolved&&e.pagesDefinition.internal.set.length<=e.pagesDefinition.resultOffset&&(s=!0),!1===s&&r.push("GETPAGES"),t}return await this._getPhysicalPage(e,t,s),this._getPage(e,t,s)}_getPhysicalPage(e,t,s){return null}_clonePageDefinition(e){return null===this._parent?null:this._parent._clonePageDefinition(e)}_first(e){return this.iterator(e).next()}first(e){return this._first(e)}async calculateStatistic(e,t,s,r){await this._ensureLoaded();let n=await this._stat(e,t,"",null,null,s,r);return!1===n.calculated&&(n=await this._manualStat(e,t,s,r)),n.result}async _manualStat(e,t,s,r){let n=null;switch(e.toLowerCase()){case"count":return n=await b(this,r),{calculated:!0,result:n};case"distinct":return n=await F(this,t,s,r),{calculated:!0,result:n};case"avg":case"mean":return n=await y(this,t,r),{calculated:!0,result:n};case"stdev":return n=await m(this,t,r),{calculated:!0,result:n};case"variance":return n=await g(this,t,r),{calculated:!0,result:n};case"sum":return n=await f(this,t,r),{calculated:!0,result:n};case"min":return n=await p(this,t,r),{calculated:!0,result:n};case"max":return n=await _(this,t,r),{calculated:!0,result:n};default:return{calculated:!0,result:0}}}async _stat(e,t,s,r,n,i,a){const l=await this._parent._stat(e,t,s,r,n,i,a);return!1===l.calculated?null===n&&""===s&&null===r?this._manualStat(e,t,i,a):{calculated:!1}:l}_unionAllGeomSelf(e){const t=this.iterator(this._defaultTracker(e)),s=[];return new Promise(((e,r)=>{this._unionShapeInBatches(s,t,e,r)}))}_unionAllGeom(e){return new Promise(((t,s)=>{const r=this.iterator(this._defaultTracker(e)),n=[];this._unionShapeInBatches(n,r,t,s)}))}_unionShapeInBatches(e,t,s,r){t.next().then((n=>{try{null!==n&&null!==n.geometry&&e.push(n.geometry),e.length>30||null===n&&e.length>1?S(e).then((i=>{try{null===n?s(i):(e=[i],this._unionShapeInBatches(e,t,s,r))}catch(a){r(a)}}),r):null===n?1===e.length?s(e[0]):s(null):this._unionShapeInBatches(e,t,s,r)}catch(i){r(i)}}),r)}iterator(e){return new n(this,e)}intersection(e,t=!1){return v._featuresetFunctions.intersection.bind(this)(e,t)}difference(e,t=!1,s=!0){return v._featuresetFunctions.difference.bind(this)(e,t,s)}symmetricDifference(e,t=!1,s=!0){return v._featuresetFunctions.symmetricDifference.bind(this)(e,t,s)}morphShape(e,t,s="unknown",r=null){return v._featuresetFunctions.morphShape.bind(this)(e,t,s,r)}morphShapeAndAttributes(e,t,s="unknown"){return v._featuresetFunctions.morphShapeAndAttributes.bind(this)(e,t,s)}union(e,t=!1){return v._featuresetFunctions.union.bind(this)(e,t)}intersects(e){return v._featuresetFunctions.intersects.bind(this)(e)}envelopeIntersects(e){return v._featuresetFunctions.envelopeIntersects.bind(this)(e)}contains(e){return v._featuresetFunctions.contains.bind(this)(e)}overlaps(e){return v._featuresetFunctions.overlaps.bind(this)(e)}relate(e,t){return v._featuresetFunctions.relate.bind(this)(e,t)}within(e){return v._featuresetFunctions.within.bind(this)(e)}touches(e){return v._featuresetFunctions.touches.bind(this)(e)}top(e){return v._featuresetFunctions.top.bind(this)(e)}crosses(e){return v._featuresetFunctions.crosses.bind(this)(e)}buffer(e,t,s,r=!0){return v._featuresetFunctions.buffer.bind(this)(e,t,s,r)}filter(e,t=null){return v._featuresetFunctions.filter.bind(this)(e,t)}orderBy(e){return v._featuresetFunctions.orderBy.bind(this)(e)}dissolve(e,t){return v._featuresetFunctions.dissolve.bind(this)(e,t)}groupby(e,t){return v._featuresetFunctions.groupby.bind(this)(e,t)}reduce(e,t=null,s){return new Promise(((r,n)=>{this._reduceImpl(this.iterator(this._defaultTracker(s)),e,t,0,r,n,0)}))}_reduceImpl(e,t,s,r,n,i,a){try{if(++a>1e3)return void setTimeout((()=>{a=0,this._reduceImpl(e,t,s,r,n,i,a)}));e.next().then((l=>{try{if(null===l)n(s);else{const u=t(s,l,r,this);I(u)?u.then((s=>{this._reduceImpl(e,t,s,r+1,n,i,a)}),i):this._reduceImpl(e,t,u,r+1,n,i,a)}}catch(u){i(u)}}),i)}catch(l){i(l)}}removeField(e){return v._featuresetFunctions.removeField.bind(this)(e)}addField(e,t,s=null){return v._featuresetFunctions.addField.bind(this)(e,t,s)}sumArea(e,t=!1,s){const r=h(e);return this.reduce(((e,s)=>null===s.geometry?0:t?T(s.geometry,r).then((t=>e+t)):P(s.geometry,r).then((t=>e+t))),0,s)}sumLength(e,t=!1,s){const r=c(e);return this.reduce(((e,s)=>null===s.geometry?0:t?x(s.geometry,r).then((t=>e+t)):k(s.geometry,r).then((t=>e+t))),0,s)}_substituteVars(e,t){if(null!==t){const s={};for(const e in t)s[e.toLowerCase()]=t[e];e.parameters=s}}async distinct(e,t=1e3,s=null,r){await this.load();const n=w.create(e,this.getFieldsIndex());return this._substituteVars(n,s),this.calculateStatistic("distinct",n,t,this._defaultTracker(r))}async min(e,t=null,s){await this.load();const r=w.create(e,this.getFieldsIndex());return this._substituteVars(r,t),this.calculateStatistic("min",r,-1,this._defaultTracker(s))}async max(e,t=null,s){await this.load();const r=w.create(e,this.getFieldsIndex());return this._substituteVars(r,t),this.calculateStatistic("max",r,-1,this._defaultTracker(s))}async avg(e,t=null,s){await this.load();const r=w.create(e,this.getFieldsIndex());return this._substituteVars(r,t),this.calculateStatistic("avg",r,-1,this._defaultTracker(s))}async sum(e,t=null,s){await this.load();const r=w.create(e,this.getFieldsIndex());return this._substituteVars(r,t),this.calculateStatistic("sum",r,-1,this._defaultTracker(s))}async stdev(e,t=null,s){await this.load();const r=w.create(e,this.getFieldsIndex());return this._substituteVars(r,t),this.calculateStatistic("stdev",r,-1,this._defaultTracker(s))}async variance(e,t=null,s){await this.load();const r=w.create(e,this.getFieldsIndex());return this._substituteVars(r,t),this.calculateStatistic("variance",r,-1,this._defaultTracker(s))}async count(e){return await this.load(),this.calculateStatistic("count",w.create("1",this.getFieldsIndex()),-1,this._defaultTracker(e))}_defaultTracker(e){return e||{aborted:!1}}forEach(e,t){return new Promise(((s,r)=>{this._forEachImpl(this.iterator(this._defaultTracker(t)),e,this,s,r,0)}))}_forEachImpl(e,t,s,r,n,i){try{if(++i>1e3)return void setTimeout((()=>{i=0,this._forEachImpl(e,t,s,r,n,i)}),0);e.next().then((a=>{try{if(null===a)r(s);else{const l=t(a);null==l?this._forEachImpl(e,t,s,r,n,i):I(l)?l.then((()=>{try{this._forEachImpl(e,t,s,r,n,i)}catch(a){n(a)}}),n):this._forEachImpl(e,t,s,r,n,i)}}catch(l){n(l)}}),n)}catch(a){n(a)}}convertToJSON(e){const t={layerDefinition:{geometryType:this.geometryType,fields:[]},featureSet:{features:[],geometryType:this.geometryType}};for(let s=0;s<this.fields.length;s++)t.layerDefinition.fields.push(o(this.fields[s]));return this.reduce(((e,s)=>{const r={geometry:s.geometry&&s.geometry.toJSON(),attributes:{}};for(const t in s.attributes)r.attributes[t]=s.attributes[t];return t.featureSet.features.push(r),1}),0,e).then((()=>t))}castToText(e=!1){return"object, FeatureSet"}queryAttachments(e,t,s,r,n){return this._parent.queryAttachments(e,t,s,r,n)}serviceUrl(){return this._parent.serviceUrl()}subtypes(){return this.typeIdField?{subtypeField:this.typeIdField,subtypes:this.types?this.types.map((e=>({name:e.name,code:e.id}))):[]}:null}relationshipMetaData(){return this._parent.relationshipMetaData()}get gdbVersion(){return this._parent?this._parent.gdbVersion:""}schema(){const e=[];for(const t of this.fields)e.push(o(t));return{objectIdField:this.objectIdField,globalIdField:this.globalIdField,geometryType:void 0===d[this.geometryType]?"esriGeometryNull":d[this.geometryType],fields:e}}async convertToText(e,t){if("schema"===e)return await this._ensureLoaded(),JSON.stringify(this.schema());if("featureset"===e){await this._ensureLoaded();const e=[];await this.reduce(((t,s)=>{const r={geometry:s.geometry?s.geometry.toJSON():null,attributes:s.attributes};return null!==r.geometry&&r.geometry.spatialReference&&delete r.geometry.spatialReference,e.push(r),1}),0,t);const s=this.schema();return s.features=e,s.spatialReference=this.spatialReference.toJSON(),JSON.stringify(s)}return this.castToText()}getFeatureByObjectId(e,t){return this._parent.getFeatureByObjectId(e,t)}getOwningSystemUrl(){return this._parent.getOwningSystemUrl()}getIdentityUser(){return this._parent.getIdentityUser()}getRootFeatureSet(){return null!==this._parent?this._parent.getRootFeatureSet():this}getDataSourceFeatureSet(){return null!==this._parent?this._parent.getDataSourceFeatureSet():this}castAsJson(e=null){return"keeptype"===e?.featureset?this:"none"===e?.featureset?null:{type:"FeatureSet"}}async castAsJsonAsync(e=null,t=null){if("keeptype"===t?.featureset)return this;if("schema"===t?.featureset)return await this._ensureLoaded(),JSON.parse(JSON.stringify(this.schema()));if("none"===t?.featureset)return null;await this._ensureLoaded();const s=[];await this.reduce(((e,r)=>{const n={geometry:r.geometry?!0===t?.keepGeometryType?r.geometry:r.geometry.toJSON():null,attributes:r.attributes};return null!==n.geometry&&n.geometry.spatialReference&&!0!==t?.keepGeometryType&&delete n.geometry.spatialReference,s.push(n),1}),0,e);const r=this.schema();return r.features=s,r.spatialReference=!0===t?.keepGeometryType?this.spatialReference:this.spatialReference?.toJSON(),r}get dateTimeReferenceFieldIndex(){return null===this._dateFieldIndex&&(this._dateFieldIndex=e.create(this.getFieldsIndex(),this)),this._dateFieldIndex}fieldTimeZone(e){return this.dateTimeReferenceFieldIndex.fieldTimeZone(e)}get preferredTimeReference(){return this._parent?.preferredTimeReference??null}get dateFieldsTimeReference(){return this._parent?.dateFieldsTimeReference??null}get datesInUnknownTimezone(){return this._parent.datesInUnknownTimezone}get editFieldsInfo(){return this._parent?.editFieldsInfo??null}get timeInfo(){return this._parent?.timeInfo??null}}v._featuresetFunctions={};export{v as default};