@arcgis/core 5.1.0-next.60 → 5.1.0-next.62

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 (125) hide show
  1. package/assets/esri/core/workers/RemoteClient.js +1 -1
  2. package/assets/esri/core/workers/chunks/{ab223c508f3dd562e7d3.js → 32e9e92bbbd000fbbaf7.js} +2 -2
  3. package/assets/esri/core/workers/chunks/{68475eba323b4aa892a3.js → 354351ab3fc79dedf9a8.js} +1 -1
  4. package/assets/esri/core/workers/chunks/45f1e682668cffc00b44.js +1 -0
  5. package/assets/esri/core/workers/chunks/4dbbf59c79d9e72f20ee.js +1 -0
  6. package/assets/esri/core/workers/chunks/{6172715b2b2853819d8a.js → 5eeb6d3a7b815d41621e.js} +1 -1
  7. package/assets/esri/core/workers/chunks/{2f74147597805828cb38.js → 5ff41f43e57be0557541.js} +22 -29
  8. package/assets/esri/core/workers/chunks/{6355de3ee89916b74dae.js → 6b32b3f98872771ff81e.js} +1 -1
  9. package/assets/esri/core/workers/chunks/71326d16b5cc35c3ff7f.js +1 -0
  10. package/assets/esri/core/workers/chunks/{c69fefe9d51ac7c2b0a6.js → 75f7c1f600c4051bc905.js} +1 -1
  11. package/assets/esri/core/workers/chunks/{8083dface1ca2dbd12b2.js → 811b378fa5bf8a4d3d66.js} +1 -1
  12. package/assets/esri/core/workers/chunks/{8432ffc33843e898bab7.js → 8166ad6bbd7d7a8f91cf.js} +1 -1
  13. package/assets/esri/core/workers/chunks/{58614f12796dbba013f4.js → 9d289cee96e7c7fe1029.js} +1 -1
  14. package/assets/esri/core/workers/chunks/{c4da2ca1dee0c44051d0.js → 9d7ffd83f69d6e639f09.js} +1 -1
  15. package/assets/esri/core/workers/chunks/{0622e238693c257abacb.js → 9eef3cd5f519c8ae88c0.js} +1 -1
  16. package/assets/esri/core/workers/chunks/{2541ac6e0ed1184edc9b.js → af3bd661b355eed3da21.js} +1 -1
  17. package/assets/esri/core/workers/chunks/{e4144ccc85ad4c76a9b7.js → af40e2e6eaf3d2226812.js} +1 -1
  18. package/assets/esri/core/workers/chunks/{0fd191f9c10b3b7c83f4.js → c319c3b85cdec73a9f45.js} +1 -1
  19. package/assets/esri/core/workers/chunks/{7e1ef2a55f8d123f31e2.js → cbb50415f7de8746ee1a.js} +1 -1
  20. package/assets/esri/core/workers/chunks/{48d289db3145ce6c02bb.js → d4368e281c12fa7c17c5.js} +1 -1
  21. package/assets/esri/core/workers/chunks/{266933f1139ed0e8919f.js → e645f992ec6f935ee3a5.js} +1 -1
  22. package/assets/esri/core/workers/chunks/{bf4bad2c9a541cd425f5.js → e9dd60d0220036545ebb.js} +1 -1
  23. package/assets/esri/core/workers/chunks/ed60b5eaa5765bfcb99c.js +1 -0
  24. package/assets/esri/core/workers/chunks/{a226ba96d9a3ecc14e3e.js → f550fc8c078ebd47d7a3.js} +1 -1
  25. package/assets/esri/libs/parquet/pkg/bundle_bg.wasm +0 -0
  26. package/assets/esri/widgets/FeatureTable/t9n/FeatureTable.json +1 -1
  27. package/assets/esri/widgets/FeatureTable/t9n/FeatureTable_en.json +1 -1
  28. package/chunks/GlowComposition.glsl.js +4 -5
  29. package/chunks/ShadowHighlight.glsl.js +5 -5
  30. package/config.js +1 -1
  31. package/geometry/libtess.js +1 -1
  32. package/geometry/support/curves/bezierCurveUtils.js +1 -1
  33. package/geometry/support/curves/circularArcUtils.js +1 -1
  34. package/geometry/support/curves/ellipticArc4Utils.js +1 -1
  35. package/geometry/support/curves/ellipticArc7Utils.js +1 -1
  36. package/interfaces.d.ts +14 -0
  37. package/kernel.js +1 -1
  38. package/layers/CSVLayer.d.ts +38 -6
  39. package/layers/CatalogLayer.d.ts +39 -8
  40. package/layers/FeatureLayer.d.ts +25 -23
  41. package/layers/GeoJSONLayer.d.ts +36 -6
  42. package/layers/ParquetLayer.d.ts +58 -0
  43. package/layers/SubtypeGroupLayer.d.ts +27 -25
  44. package/layers/WFSLayer.d.ts +51 -8
  45. package/layers/catalog/CatalogFootprintLayer.d.ts +37 -7
  46. package/layers/graphics/sources/csv/csv.js +1 -1
  47. package/layers/knowledgeGraph/KnowledgeGraphSublayer.d.ts +41 -17
  48. package/layers/mixins/ArcGISImageService.d.ts +58 -0
  49. package/layers/mixins/ArcGISImageService.js +1 -1
  50. package/layers/raster/datasets/BaseRaster.js +1 -1
  51. package/layers/raster/datasets/ImageAuxRaster.js +1 -1
  52. package/layers/raster/datasets/ImageServerRaster.js +1 -1
  53. package/layers/raster/formats/ImageCanvasDecoder.js +1 -1
  54. package/layers/raster/formats/JpgPlus.js +1 -1
  55. package/layers/raster/formats/RasterCodec.js +1 -1
  56. package/layers/support/csvUtils.js +1 -1
  57. package/package.json +3 -3
  58. package/popup/Feature.d.ts +33 -35
  59. package/popup/Feature.js +1 -1
  60. package/popup/Features.d.ts +663 -0
  61. package/popup/Features.js +2 -0
  62. package/popup/support/FeatureAbilities.d.ts +30 -0
  63. package/popup/support/FeatureAbilities.js +2 -0
  64. package/support/revision.js +1 -1
  65. package/views/2d/analysis/analysisViewModuleImportUtils.js +1 -1
  66. package/views/2d/engine/webgl/shaders/sources/shaderRepository.js +1 -1
  67. package/views/2d/layerViewModuleImportUtils.js +1 -1
  68. package/views/3d/FocusAreasView.js +1 -1
  69. package/views/3d/analysis/analysisViewModuleImportUtils.js +1 -1
  70. package/views/3d/interactive/visualElements/PointVisualElement.js +1 -1
  71. package/views/3d/layerViewModuleImportUtils.js +1 -1
  72. package/views/3d/layers/I3SMeshView3D.js +1 -1
  73. package/views/3d/layers/graphics/Graphics3DTextSymbolLayer.js +1 -1
  74. package/views/3d/layers/graphics/tessellationUtils.js +1 -1
  75. package/views/3d/support/renderInfoUtils/polygon.js +1 -1
  76. package/views/3d/webgl-engine/core/shaderLibrary/shading/ReadShadowMap.glsl.js +6 -11
  77. package/views/3d/webgl-engine/effects/focusArea/FocusAreaOutlineItem.js +1 -1
  78. package/views/3d/webgl-engine/effects/glow/GlowComposition.glsl.js +1 -1
  79. package/views/3d/webgl-engine/effects/highlight/ShadowHighlight.js +1 -1
  80. package/views/3d/webgl-engine/effects/highlight/{ScreenSpaceShadowHighlight.glsl.js → ShadowHighlightBuffer.glsl.js} +1 -1
  81. package/views/3d/webgl-engine/effects/highlight/ShadowHighlightBuffer.js +2 -0
  82. package/views/3d/webgl-engine/effects/highlight/ShadowHighlightBufferTechnique.js +2 -0
  83. package/views/3d/webgl-engine/lib/BindParameters.js +1 -1
  84. package/views/3d/webgl-engine/lib/MainFramebuffer.js +1 -1
  85. package/views/3d/webgl-engine/lib/Renderer.js +1 -1
  86. package/views/3d/webgl-engine/materials/CheckerBoardMaterial.js +1 -1
  87. package/views/3d/webgl-engine/materials/HUDMaterial.js +1 -1
  88. package/views/3d/webgl-engine/materials/PolygonOffset.js +1 -1
  89. package/views/3d/webgl-engine/parts/RenderView.js +1 -1
  90. package/views/3d/webgl-engine/shaders/HUDMaterialTechnique.js +1 -1
  91. package/views/3d/webgl-engine/shaders/HUDMaterialTechniqueConfiguration.js +1 -1
  92. package/views/3d/webgl-engine/shaders/OutputColorHighlightOLID.glsl.js +11 -11
  93. package/views/3d/webgl-engine/shaders/ReceiveShadowsConfiguration.js +1 -1
  94. package/views/3d/webgl-engine/shaders/ditherNoise.glsl.js +2 -0
  95. package/views/3d/webgl.js +1 -1
  96. package/views/SceneView.js +1 -1
  97. package/views/draw/plugins/TangentArcSegmentPlugin.js +1 -1
  98. package/views/support/AnalysisViewManager.js +1 -1
  99. package/widgets/ElevationProfile/support/ElevationProfileView.js +1 -1
  100. package/widgets/ElevationProfile/support/ElevationProfileView3D.js +1 -1
  101. package/widgets/Feature/FeatureViewModel.d.ts +2 -1
  102. package/widgets/Feature/FeatureViewModel.js +1 -1
  103. package/widgets/Feature.js +1 -1
  104. package/widgets/FeatureTable/ColumnVisibilityMenuVisibleElements.d.ts +27 -0
  105. package/widgets/FeatureTable/ColumnVisibilityMenuVisibleElements.js +2 -0
  106. package/widgets/FeatureTable/FeatureTableViewModel.d.ts +10 -1
  107. package/widgets/FeatureTable/FeatureTableViewModel.js +1 -1
  108. package/widgets/FeatureTable/TableMenuVisibleElements.d.ts +0 -1
  109. package/widgets/FeatureTable/TableMenuVisibleElements.js +1 -1
  110. package/widgets/FeatureTable/VisibleElements.d.ts +23 -1
  111. package/widgets/FeatureTable/VisibleElements.js +1 -1
  112. package/widgets/FeatureTable/support/FeatureStore.js +1 -1
  113. package/widgets/FeatureTable.d.ts +10 -1
  114. package/widgets/FeatureTable.js +1 -1
  115. package/widgets/Popup/actionUtils.js +1 -1
  116. package/widgets/Widget.js +1 -1
  117. package/assets/esri/core/workers/chunks/16806f5044a9da553b66.js +0 -1
  118. package/assets/esri/core/workers/chunks/5f3f50fec18d1642fdf9.js +0 -1
  119. package/assets/esri/core/workers/chunks/b42487c6a989e11a2559.js +0 -1
  120. package/assets/esri/core/workers/chunks/dba479176db0a23c8034.js +0 -1
  121. package/views/3d/webgl-engine/effects/highlight/ScreenSpaceShadowHighlightRenderNode.js +0 -2
  122. package/views/3d/webgl-engine/effects/highlight/ScreenSpaceShadowHighlightTechnique.js +0 -2
  123. package/views/3d/webgl-engine/shaders/Dithering.glsl.js +0 -4
  124. /package/assets/esri/core/workers/chunks/{ab223c508f3dd562e7d3.js.LICENSE.txt → 32e9e92bbbd000fbbaf7.js.LICENSE.txt} +0 -0
  125. /package/chunks/{ScreenSpaceShadowHighlight.glsl.js → ShadowHighlightBuffer.glsl.js} +0 -0
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import t from"../../Graphic.js";import i from"../../request.js";import r from"../../core/Error.js";import{clone as s}from"../../core/lang.js";import n from"../../core/Logger.js";import{watch as a}from"../../core/reactiveUtils.js";import{urlToObject as o}from"../../core/urlUtils.js";import{property as l,subclass as u}from"../../core/accessorSupport/decorators.js";import{Integer as p,ensureClass as m,ensureRange as c,ensureNumber as d}from"../../core/accessorSupport/ensureType.js";import{runUntracked as h}from"../../core/accessorSupport/tracking.js";import f from"../../geometry/Extent.js";import y from"../../geometry/Polygon.js";import g from"../../geometry/SpatialReference.js";import{srToRESTValue as R}from"../../geometry/support/spatialReferenceUtils.js";import{intersectMultimensionalSubset as I,getEffectiveMultidimensionalDefinition as v,getSubsetVariablesFromMdInfo as w,getDefaultMultidimensionalDefinition as b}from"../raster/datasets/multidimensionalUtils.js";import{decode as S,getFormat as x}from"../raster/formats/RasterCodec.js";import{uvComponentToVector as _}from"../raster/functions/vectorFieldUtils.js";import{opacity as F,url as D}from"../support/commonProperties.js";import O from"../support/DimensionalDefinition.js";import{ExportImageServiceParameters as T}from"../support/ExportImageServiceParameters.js";import C from"../support/Field.js";import M from"../support/FieldsIndex.js";import{createBitmap as N}from"../support/imageBitmapUtils.js";import{isSupportedRendererType as q}from"../support/imageryRendererUtils.js";import P from"../support/MosaicRule.js";import j from"../support/MultidimensionalSubset.js";import E from"../support/PixelBlock.js";import{interpolationKebab as A,noDataInterpretationKebab as V,pixelTypeKebabDict as Q}from"../support/rasterEnums.js";import{getServicePixelValueField as J,getItemPixelValueField as U,getRawServicePixelValueField as B,getProcessedServicePixelValueField as z,getMagnitudeField as L,getDirectionField as H,getMultidimensionalFields as G,getRasterAttributeTableFields as W,addMultidimensionalFieldValues as k,commonRasterFieldNames as $,rasterFieldPrefix as X}from"../support/rasterFieldUtils.js";import K from"../support/RasterFunction.js";import Y from"../support/RasterInfo.js";import{createDefaultRenderer as Z,getDefaultBandCombination as ee,getSupportedRendererTypes as te,matchPresetRenderer as ie,normalizeRendererJSON as re}from"../../renderers/support/rasterRendererHelper.js";import se from"../../renderers/support/RasterSymbolizer.js";import{rasterRendererTypes as ne,websceneRasterRendererTypes as ae,read as oe}from"../../renderers/support/rasterTypeUtils.js";import{calculateVolume as le,computeAngles as ue,computePixelSpaceLocations as pe,computeHistograms as me,computeStatisticsHistograms as ce,measureHeight as de,measureAreaAndPerimeter as he,measureDistanceAndAngle as fe,measurePointOrCentroid as ye,measureLengthFromImage as ge,measureAreaFromImage as Re,getImageSpatialReferenceQueryParameter as Ie,getSamples as ve,identify as we,imageToMap as be,imageToMapMultiray as Se,mapToImage as xe,findImages as _e,getImageUrl as Fe,queryBoundary as De,queryGPSInfo as Oe}from"../../rest/imageService.js";import{fetchServiceRasterInfo as Te,generateRasterInfo as Ce,patchServiceInfo as Me}from"../../rest/imageService/fetchRasterInfo.js";import{getCatalogItemRasterInfo as Ne}from"../../rest/imageService/getCatalogItemRasterInfo.js";import{executeForCount as qe}from"../../rest/query/executeForCount.js";import{executeForExtent as Pe}from"../../rest/query/executeForExtent.js";import{executeForIds as je}from"../../rest/query/executeForIds.js";import{executeQueryJSON as Ee}from"../../rest/query/executeQueryJSON.js";import Ae from"../../rest/support/FeatureSet.js";import Ve from"../../rest/support/ImageIdentifyParameters.js";import Qe from"../../rest/support/Query.js";import{reader as Je}from"../../core/accessorSupport/decorators/reader.js";import{writer as Ue}from"../../core/accessorSupport/decorators/writer.js";const Be=new Set(["png","png8","png24","png32","jpg","bmp","gif","jpgpng","lerc","tiff"]),ze=c(d,{min:0,max:255});function Le(e){const t=JSON.stringify(e),i=t.includes('"rasterFunctionDefinition":{'),r=i?t.match(/"type":"(.*?FunctionArguments")/gi):t.match(/"rasterFunction":"(.*?")/gi),s=r?.map(e=>i?e.slice(8,-18):e.slice(18,-1));return s?s.join("/"):null}const He=c=>{const d=c;let He=class extends d{constructor(){super(...arguments),this._functionRasterInfos={},this._serviceSupportsMosaicRule=null,this.adjustAspectRatio=null,this.bandIds=void 0,this.capabilities=null,this.compressionQuality=void 0,this.compressionTolerance=.01,this.copyright=null,this.defaultMosaicRule=null,this.definitionExpression=null,this.exportImageServiceParameters=null,this.rasterInfo=null,this.fields=null,this.fullExtent=null,this.hasMultidimensions=!1,this.imageMaxHeight=4100,this.imageMaxWidth=4100,this.interpolation=void 0,this.minScale=0,this.maxScale=0,this.multidimensionalInfo=null,this.multidimensionalSubset=null,this.noData=null,this.noDataInterpretation=void 0,this.objectIdField=null,this.geometryType="polygon",this.typeIdField=null,this.types=[],this.pixelFilter=null,this.raster=void 0,this.sourceType=null,this.viewId=void 0,this.symbolizer=null,this.rasterFunctionInfos=null,this.serviceDataType=null,this.spatialReference=null,this.pixelType=null,this.serviceRasterInfo=null,this.sourceJSON=null,this.url=null,this.version=void 0}initialize(){this._set("exportImageServiceParameters",new T({layer:this}))}readServiceSupportsMosaicRule(e,t){return this._isMosaicRuleSupported(t)}get _rasterFunctionNamesIndex(){const e=new Map;return!this.rasterFunctionInfos||null!=this.rasterFunctionInfos&&this.rasterFunctionInfos.length<1||null!=this.rasterFunctionInfos&&this.rasterFunctionInfos.forEach(t=>{e.set(t.name.toLowerCase().replaceAll(/ /gi,"_"),t.name)}),e}readBandIds(e,t){if(Array.isArray(e)&&e.length>0&&e.every(e=>"number"==typeof e))return e}readCapabilities(e,t){return this._readCapabilities(t)}writeCompressionQuality(e,t,i){null!=e&&"lerc"!==this.format&&(t[i]=e)}writeCompressionTolerance(e,t,i){"lerc"===this.format&&null!=e&&(t[i]=e)}readDefaultMosaicRule(e,t){return this._serviceSupportsMosaicRule?h(()=>P.fromJSON(t)):null}get fieldsIndex(){return this.fields?new M(this.fields):null}set format(e){e&&Be.has(e.toLowerCase())&&this._set("format",e.toLowerCase())}readFormat(e,t){return"esriImageServiceDataTypeVector-UV"===t.serviceDataType||"esriImageServiceDataTypeVector-MagDir"===t.serviceDataType||null!=this.pixelFilter?"lerc":"jpgpng"}readMinScale(e,t){return null!=t.minLOD&&null!=t.maxLOD?e:0}readMaxScale(e,t){return null!=t.minLOD&&null!=t.maxLOD?e:0}set mosaicRule(e){let t=e;t?.mosaicMethod&&(t=P.fromJSON({...t.toJSON(),mosaicMethod:t.mosaicMethod,mosaicOperation:t.mosaicOperation})),this._set("mosaicRule",t)}readMosaicRule(e,t){const i=e||t.mosaicRule;return i?P.fromJSON(i):this._isMosaicRuleSupported(t)?P.fromJSON(t):null}writeMosaicRule(e,t,i){const{mosaicRule:r}=this;this._isValidCustomizedMosaicRule(r)&&(t[i]=r.toJSON())}writeNoData(e,t,i){null!=e&&"number"==typeof e&&(t[i]=ze(e))}readObjectIdField(e,t){if(!e){const i=t.fields.find(e=>"esriFieldTypeOID"===e.type||"oid"===e.type);e=i?.name}return e}get parsedUrl(){return o(this.url)}readSourceType(e,t){return this._isMosaicDataset(t)?"mosaic-dataset":"raster-dataset"}get renderer(){const{activePresetRendererName:e,presetRenderers:t}=this;if(e){const i=t?.find(({name:t})=>t===e);return i?.renderer.clone()}return this.internalRenderer}set renderer(e){this.activePresetRendererName=null,this.internalRenderer=e}set internalRenderer(e){this.loaded&&(e=this._configRenderer(e)),this._set("internalRenderer",e)}readRenderer(e,t,i){const r=t?.layerDefinition?.drawingInfo?.renderer,s=oe(r,i);return null==s?null:("vector-field"===s.type&&t.symbolTileSize&&!r.symbolTileSize&&(s.symbolTileSize=t.symbolTileSize),q(s)||n.getLogger(this).warn("ArcGISImageService","Imagery layer doesn't support given renderer type."),s)}writeRenderer(e,t,i){t.layerDefinition=t.layerDefinition||{},t.layerDefinition.drawingInfo=t.layerDefinition.drawingInfo||{},t.layerDefinition.drawingInfo.renderer=e.toJSON()}get rasterFields(){const e=this.fields?.map(e=>e.clone())??[];e.push(J()),"mosaic-dataset"===this.sourceType&&this.fields?.length&&e.push(U()),this.version>=10.4&&null!=this.rasterFunctionInfos&&this.rasterFunctionInfos.some(({name:e})=>"none"===e.toLowerCase())&&e.push(B()),null!=this.rasterFunctionInfos&&this.rasterFunctionInfos.filter(({name:e})=>"none"!==e.toLowerCase()).forEach(({name:t})=>e.push(z(t)));const{rasterInfo:t}=this;if(this._isVectorDataSet()){const i=t?.multidimensionalInfo?.variables[0].unit?.trim(),r=L(i),s=H();e.push(r,s)}if(t?.multidimensionalInfo&&"raster-dataset"===this.sourceType){const i=G(t.multidimensionalInfo);e.push(...i)}const i=t?.attributeTable;if(null!=i){const t=W(i);e.push(...t)}return e}set rasterFunction(e){let t=e;t?.rasterFunction&&(t=K.fromJSON({...t.toJSON(),rasterFunction:t.rasterFunction,rasterFunctionArguments:t.rasterFunctionArguments})),this._set("rasterFunction",t)}readRasterFunction(e,t){const i=t.rasterFunctionInfos;return t.renderingRule||i?.length&&"None"!==i[0].name?this._isRFTJson(t.renderingRule)?K.fromJSON({rasterFunctionDefinition:t.renderingRule}):K.fromJSON(t.renderingRule||{rasterFunctionInfos:t.rasterFunctionInfos}):null}readSpatialReference(e,t){const i=e||t.extent.spatialReference;return i?g.fromJSON(i):null}writePixelType(e,t,i){null!=this.serviceRasterInfo&&this.pixelType===this.serviceRasterInfo.pixelType||(t[i]=Q.toJSON(e))}readVersion(e,t){let i=t.currentVersion;return i||(i=t.hasOwnProperty("fields")||t.hasOwnProperty("timeInfo")?10:9.3),i}applyFilter(e){let t=e;return this.pixelFilter&&(t=this._clonePixelData(e),this.pixelFilter(t)),t}async applyRenderer(e,t){let i=e,{renderer:r,symbolizer:s,pixelFilter:n}=this;const{isRawData:a}=e;if(a&&"lerc"!==this.format&&(r??=Z(this.rasterInfo,{bandIds:this.bandIds,variableName:this.rasterFunction?null:this.mosaicRule?.multidimensionalDefinition?.[0].variableName}),s||(this.symbolizer=new se({rendererJSON:r.toJSON(),rasterInfo:this.rasterInfo}),s=this.symbolizer)),(a||!this._isPicture())&&r&&s&&!n){await this._updateSymbolizer(s,r);const n=this.bandIds?.length?this.bandIds:ee(this.rasterInfo);i=await this._symbolize({pixelData:e,bandIds:n,symbolizer:s},t)}return i}destroy(){this._shutdownJobHandler()}async calculateVolume(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsCalculateVolume)throw new r("imagery-layer:compute-pixel-space-locations","this operation is not supported on the input image service");return e=s(e),this.mosaicRule&&null==e.mosaicRule&&(e.mosaicRule=this.mosaicRule),le(this.url,e,this._getRequestOptions(t))}async computeAngles(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsComputeAngles)throw new r("imagery-layer:compute-angles","this operation is not supported on the input image service");return ue(this.url,e,this._getRequestOptions(t))}async computePixelSpaceLocations(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsComputePixelLocation)throw new r("imagery-layer:compute-pixel-space-locations","this operation is not supported on the input image service");return pe(this.url,e,this._getRequestOptions(t))}async computeHistograms(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsComputeHistograms)throw new r("imagery-layer:compute-histograms","this operation is not supported on the input image service");return e=s(e),this._applyMosaicAndRenderingRules(e),me(this.url,e,this._getRequestOptions(t))}async computeStatisticsHistograms(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsComputeStatisticsHistograms)throw new r("imagery-layer:compute-statistics-histograms","this operation is not supported on the input image service");return e=s(e),this._applyMosaicAndRenderingRules(e),ce(this.url,e,this._getRequestOptions(t))}async measureHeight(e,t){const i=await this._fetchCapabilities(t?.signal);if(!("base-and-top"===e.operationType?i.mensuration.supportsHeightFromBaseAndTop:"base-and-top-shadow"===e.operationType?i.mensuration.supportsHeightFromBaseAndTopShadow:i.mensuration.supportsHeightFromTopAndTopShadow))throw new r("imagery-layer:measure-height","this operation is not supported on the input image service");return e=s(e),this._applyMosaicRule(e),de(this.url,e,this._getRequestOptions(t))}async measureAreaAndPerimeter(e,t){const i=await this._fetchCapabilities(t?.signal);if(!(i.mensuration.supportsAreaAndPerimeter&&(!e.is3D||i.mensuration.supports3D)))throw new r("imagery-layer:measure-area-and-perimeter","this operation is not supported on the input image service");return e=s(e),this._applyMosaicRule(e),he(this.url,e,this._getRequestOptions(t))}async measureDistanceAndAngle(e,t){const i=await this._fetchCapabilities(t?.signal);if(!(i.mensuration.supportsDistanceAndAngle&&(!e.is3D||i.mensuration.supports3D)))throw new r("imagery-layer:measure-distance-and-angle","this operation is not supported on the input image service");return e=s(e),this._applyMosaicRule(e),fe(this.url,e,this._getRequestOptions(t))}async measurePointOrCentroid(e,t){const i=await this._fetchCapabilities(t?.signal);if(!(i.mensuration.supportsPointOrCentroid&&(!e.is3D||i.mensuration.supports3D)))throw new r("imagery-layer:measure-point-or-centroid","this operation is not supported on the input image service");return e=s(e),this._applyMosaicRule(e),ye(this.url,e,this._getRequestOptions(t))}async measureLengthFromImage(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsMeasureFromImage)throw new r("imagery-layer:measure-length-from-image","this operation is not supported on the input image service");if("polyline"!==e.geometry.type)throw new r("imagery-layer:measure-length-from-image","this input geometry must be a polyline");return ge(this.url,e,this._getRequestOptions(t))}async measureAreaFromImage(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsMeasureFromImage)throw new r("imagery-layer:measure-area-from-image","this operation is not supported on the input image service");if("polygon"!==e.geometry.type)throw new r("imagery-layer:measure-area-from-image","this input geometry must be a polygon");return Re(this.url,e,this._getRequestOptions(t))}getField(e){const{fieldsIndex:t}=this;return null!=t?t.get(e):void 0}getFieldDomain(e,t){const i=this.getField(e);return i?i.domain:null}async internalFetchImage(e,t,i,r={}){await this._updateCurrentRasterInfo();const{exportImageServiceParameters:s}=this;let n=!1;r.requestRawData&&(await this._initJobHandler(),s.requestRawData||"lerc"===this.format||(n=!0,s.requestRawData=!0));const a=this.getExportImageServiceParameters(e,t,i,r.timeExtent);if(n&&(s.requestRawData=!1,a&&!this.bandIds?.length&&(null==a.bandIds||""===a.bandIds))){const e=ee(this.rasterInfo);a.bandIds=e?.join(",")}if(null==a){if(r.requestAsImageElement&&this._canRequestImageElement(this.format)){const e=document.createElement("canvas");if(e.width=t,e.height=i,r.returnImageBitmap){return{imageBitmap:await N(e,`${Ge(this.parsedUrl)}/exportImage`,r.signal)}}return{imageOrCanvasElement:e}}const{bandIds:s,rasterInfo:n}=this,a=(s?.length||n.bandCount)??0,o=t*i,l=n.pixelType,u=[];for(let e=0;e<a;e++)u.push(E.createEmptyBand(l,o));return{pixelData:{pixelBlock:new E({width:t,height:i,pixels:u,mask:new Uint8Array(o),pixelType:l}),extent:e}}}const o=!!r.requestAsImageElement&&!this.pixelFilter,l=o&&!!r.returnImageBitmap,u={imageServiceParameters:a,imageProps:{extent:e,width:t,height:i,format:this.format},requestAsImageElement:o,returnImageBitmap:l,signal:r.signal};return this._requestArrayBuffer(u)}async fetchPixels(e,t,i,r={}){await this._initJobHandler(),r.applyRendering&&this._updateCurrentRasterInfo();const s=r.applyRendering?void 0:new T({layer:this,requestRawData:!0,interpolation:r.interpolation??"nearest",bandIds:r.bandIds??[]}),n=this.getExportImageServiceParameters(e,t,i,r.timeExtent,s);if(null==n)return{extent:e,pixelBlock:null};delete n.pixelType,r.bandIds||delete n.bandIds,delete n.compressionQuality;const a={imageServiceParameters:n,imageProps:{extent:e,width:t,height:i,format:this.format},requestAsImageElement:!1,returnImageBitmap:!1,signal:r.signal},{pixelData:o}=await this._requestArrayBuffer(a);return o??{extent:e,pixelBlock:null}}fetchKeyProperties(e){return i(Ge(this.parsedUrl)+"/keyProperties",{query:this._getQueryParams({renderingRule:this.version>=10.3?e?.rasterFunction:null})}).then(e=>e.data)}fetchRasterAttributeTable(e){return this.version<10.1?Promise.reject(new r("#fetchRasterAttributeTable()","Failed to get rasterAttributeTable")):i(Ge(this.parsedUrl)+"/rasterAttributeTable",{query:this._getQueryParams({renderingRule:this.version>=10.3?e?.rasterFunction:null})}).then(e=>Ae.fromJSON(e.data))}getCatalogItemRasterInfo(e,t){const i={...t,query:this._getQueryParams()};return Ne(Ge(this.parsedUrl),e,i)}async getCatalogItemICSInfo(e,t){const{data:r}=await i(Ge(this.parsedUrl)+"/"+e+"/info/ics",{query:this._getQueryParams(),...t}),s=r?.ics;if(!s)return;let n=null;try{n=(await i(Ge(this.parsedUrl)+"/"+e+"/info",{query:this._getQueryParams(),...t})).data.extent}catch{}if(!n?.spatialReference)return{ics:s,icsToPixelTransform:null,icsExtent:null,northDirection:null};const a=this.version>=10.7?i(Ge(this.parsedUrl)+"/"+e+"/info/icstopixel",{query:this._getQueryParams(),...t}).then(e=>e.data).catch(()=>({})):{},o=n.spatialReference,l={geometries:JSON.stringify({geometryType:"esriGeometryEnvelope",geometries:[n]}),inSR:R(o),outSR:"0:"+e},u=i(Ge(this.parsedUrl)+"/project",{query:this._getQueryParams(l),...t}).then(e=>e.data).catch(()=>({})),p=5,m=(n.xmin+n.xmax)/2,c=(n.ymax-n.ymin)/(p+1),d=n.ymin+c,h=[];for(let i=0;i<p;i++)h.push({x:m,y:d+c*i});const y={geometries:JSON.stringify({geometryType:"esriGeometryPoint",geometries:h}),inSR:R(o),outSR:"0:"+e},I=i(Ge(this.parsedUrl)+"/project",{query:this._getQueryParams(y),...t}).then(e=>e.data).catch(()=>({})),v=await Promise.all([a,u,I]);let w=v[0].ipxf;if(null==w){const e=s.geodataXform?.xf_0;"topup"===e?.name?.toLowerCase()&&6===e?.coefficients?.length&&(w={affine:{name:"ics [sensor: Frame] to pixel (column, row) transformation",coefficients:e.coefficients,cellsizeRatio:0,type:"GeometricXform"}})}const b=f.fromJSON(v[1]?.geometries?.[0]);b&&(b.spatialReference=new g({wkid:0,imageCoordinateSystem:s}));const S=v[2].geometries?v[2].geometries.filter(e=>null!=e?.x&&null!=e.y&&"NaN"!==e.x&&"NaN"!==e.y):[],x=S.length;if(x<3)return{ics:s,icsToPixelTransform:w,icsExtent:b,northDirection:null};let _=0,F=0,D=0,O=0;for(let i=0;i<x;i++)_+=S[i].x,F+=S[i].y,D+=S[i].x*S[i].x,O+=S[i].x*S[i].y;const T=(x*O-_*F)/(x*D-_*_);let C=0;const M=S[p-1].x>S[0].x,N=S[p-1].y>S[0].y;return T===1/0?C=N?90:270:0===T?C=M?0:180:T>0?C=M?180*Math.atan(T)/Math.PI:180*Math.atan(T)/Math.PI+180:T<0&&(C=N?180+180*Math.atan(T)/Math.PI:360+180*Math.atan(T)/Math.PI),{ics:s,icsToPixelTransform:w,icsExtent:b,northDirection:C}}async generateRasterInfo(e,t){const i=m(K,e),s={...t,query:this._getQueryParams()};if(!i||"none"===i.functionName?.toLowerCase()||this._isVectorFieldResampleFunction(i))return this.serviceRasterInfo??Te(Ge(this.parsedUrl),this.sourceJSON,s);const n=Le(i);if(!n)throw new r("imagery-layer:generate-raster-info","the rendering rule is not supported");if(this._functionRasterInfos[n])return this._functionRasterInfos[n];const a=Ce(Ge(this.parsedUrl),i,s);this._functionRasterInfos[n]=a;try{return await a}catch(o){throw this._functionRasterInfos[n]=null,o}}getExportImageServiceParameters(e,t,i,r,s){e=e.clone().shiftCentralMeridian();const n=Ie(e.spatialReference,Ge(this.parsedUrl));s??=this.exportImageServiceParameters;const a=s.toJSON(),{bandIds:o,noData:l}=a;let{renderingRule:u}=a;const p=this.rasterFunction?.rasterFunctionDefinition,m=this.renderer?.type,c=!m||"raster-stretch"===m||"raster-colormap"===m||"unique-value"===m||"class-breaks"===m||"raster-shaded-relief"===m;if(o?.length&&this._hasRasterFunction(this.rasterFunction)&&!p&&c){const e={rasterFunction:"ExtractBand",rasterFunctionArguments:{BandIds:o}};if("Stretch"===u.rasterFunction)e.rasterFunctionArguments.Raster=u.rasterFunctionArguments.Raster,u.rasterFunctionArguments.Raster=e;else if("Colormap"===u.rasterFunction){const t=u.rasterFunctionArguments.Raster;"Stretch"===t?.rasterFunction?(e.rasterFunctionArguments.Raster=t.rasterFunctionArguments.Raster,t.rasterFunctionArguments.Raster=e):(e.rasterFunctionArguments.Raster=t,u.rasterFunctionArguments.Raster=e)}else e.rasterFunctionArguments.Raster=u,u=e;a.bandIds=void 0}else a.bandIds=o?.join(",");Array.isArray(l)&&l.length>0&&(a.noData=l.join(","));const d=this._processMultidimensionalIntersection(null,r,s.mosaicRule);if(d.isOutSide)return null;a.mosaicRule=null!=d.mosaicRule?JSON.stringify(d.mosaicRule):null,r=d.timeExtent,a.renderingRule=this._getRenderingRuleString(K.fromJSON(u));const h={};if(null!=r){const{start:e,end:t}=r.toJSON();e&&t&&e===t?h.time=""+e:null==e&&null==t||(h.time=`${e??"null"},${t??"null"}`)}return{bbox:e.xmin+","+e.ymin+","+e.xmax+","+e.ymax,bboxSR:n,imageSR:n,size:t+","+i,...a,...h}}async getSamples(e,t){const i=await this._fetchCapabilities(t?.signal);if(!i?.operations.supportsGetSamples)throw new r("imagery-layer:get-samples","getSamples operation is not supported on the input image service");e=s(e);const{raster:n}=this;return n&&null==e.raster&&(e.raster=n),ve(this.url,e,this._getRequestOptions(t))}async identify(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsIdentify)throw new r("imagery-layer:identify","identify operation is not supported on the input image service");e=s(e),this.version<10.91&&"extent"===e.geometry?.type&&(e.geometry=y.fromExtent(e.geometry));const i=this._processMultidimensionalIntersection(e.geometry,e.timeExtent,e.mosaicRule||this.mosaicRule);if(i.isOutSide)throw new r("imagery-layer:identify","the request cannot be fulfilled when falling outside of the multidimensional subset");e.timeExtent=i.timeExtent,e.mosaicRule=i.mosaicRule;const{raster:n,rasterFunction:a}=this;return a&&null==e.rasterFunction&&(e.rasterFunction=a),n&&null==e.raster&&(e.raster=n),we(this.url,e,this._getRequestOptions(t))}async imageToMap(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsImageToMap)throw new r("imagery-layer:image-to-map","imageToMap operation is not supported on the input image service");return be(Ge(this.parsedUrl),e,this._getRequestOptions(t))}async imageToMapMultiray(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsImageToMapMultiray)throw new r("imagery-layer:image-to-map-multiray","imageToMapMultiray operation is not supported on the input image service");return Se(Ge(this.parsedUrl),e,this._getRequestOptions(t))}async mapToImage(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsMapToImage)throw new r("imagery-layer:map-to-image","mapToImage operation is not supported on the input image service");return xe(Ge(this.parsedUrl),e,this._getRequestOptions(t))}async findImages(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsFindImages)throw new r("imagery-layer:find-images","findImages operation is not supported on the input image service");return _e(Ge(this.parsedUrl),e,this._getRequestOptions(t))}async getImageUrl(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsGetImageUrl)throw new r("imagery-layer:get-image-url","getImageUrl operation is not supported on the input image service");return Fe(Ge(this.parsedUrl),e,this._getRequestOptions(t))}createQuery(){return new Qe({outFields:["*"],returnGeometry:!0,where:this.definitionExpression||"1=1"})}async queryBoundary(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsQueryBoundary)throw new r("imagery-layer:query-boundary","queryBoundary operation is not supported on the input image service");return e=e??{outSpatialReference:this.spatialReference},De(Ge(this.parsedUrl),e,this._getRequestOptions(t))}async queryExtent(e,t){return({query:e,requestOptions:t}=await this._prepareForQuery(e,t)),Pe(this.url,e,t)}async queryRasters(e,t){({query:e,requestOptions:t}=await this._prepareForQuery(e,t));const i=await Ee(this.url,e,t),r=this.graphicOrigin;return i.features.forEach(e=>{e.layer=this,e.origin=r}),i}async queryObjectIds(e,t){return({query:e,requestOptions:t}=await this._prepareForQuery(e,t)),je(this.url,e,t)}async queryGPSInfo(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsQueryGPSInfo)throw new r("imagery-layer:query-gps-info","queryGPSInfo operation is not supported on the input image service");return e=e??{where:"1=1"},Oe(Ge(this.parsedUrl),e,this._getRequestOptions(t))}async queryRasterCount(e,t){return({query:e,requestOptions:t}=await this._prepareForQuery(e,t)),qe(this.url,e,t)}async queryVisibleRasters(e,t){if(!e)throw new r("imagery-layer: query-visible-rasters","missing query parameter");await this.load();const{pixelSize:i,returnDomainValues:s,returnTopmostRaster:n,showNoDataRecords:a}=t||{pixelSize:null,returnDomainValues:!1,returnTopmostRaster:!1,showNoDataRecords:!1};let o=!1,l=null,u=null;const p=$.servicePixelValue.toLowerCase(),m=this._rasterFunctionNamesIndex;if(null!=e.outFields&&(o=e.outFields.some(e=>!e.toLowerCase().startsWith(p)),this.version>=10.4)){const t=e.outFields.filter(e=>e.toLowerCase().startsWith(p)&&e.length>p.length).map(e=>{const t=e.slice(p.length+1);return[this._updateRenderingRulesFunctionName(t,m),t]});l=t.map(e=>new K({functionName:e[0]})),u=t.map(e=>e[1]);const{rasterFunction:i}=this;0===l.length?i?.functionName?(l.push(i),u.push(i.functionName)):l=null:i?.functionName&&!l.some(e=>e.functionName===i.functionName)&&(l.push(i),u.push(i.functionName))}const c=null==e.outSpatialReference||e.outSpatialReference.equals(this.spatialReference),{multidimensionalSubset:d}=this;let h=e.timeExtent||this.timeExtent;if(d){const{isOutside:t,intersection:i}=I(d,{geometry:e.geometry,timeExtent:e.timeExtent,multidimensionalDefinition:this.exportImageServiceParameters.mosaicRule?.multidimensionalDefinition});if(t)throw new r("imagery-layer:query-visible-rasters","the request cannot be fulfilled when falling outside of the multidimensional subset");null!=i?.timeExtent&&(h=i.timeExtent)}const f=this._combineMosaicRuleWithTimeExtent(this.exportImageServiceParameters.mosaicRule,h);let g=e.geometry;this.version<10.91&&"extent"===g?.type&&(g=y.fromExtent(g));const R=this._getQueryParams({geometry:g,timeExtent:h,mosaicRule:f,rasterFunction:this.version<10.4?this.rasterFunction:null,rasterFunctions:l,pixelSize:i,returnCatalogItems:o,returnGeometry:c,raster:this.raster,maxItemCount:n?1:null});delete R.f;const w=new Ve(R);try{await this._generateRasterInfo(this.rasterFunction);const i=await we(this.url,w,{signal:t?.signal,query:{...this.customParameters}}),r=e.outFields,n=null!=i.value&&i.value.toLowerCase().includes("nodata"),l=o&&!c&&i?.catalogItems?.features.length&&(a||!n),p=this.multidimensionalInfo&&"raster-dataset"===this.sourceType?v({rasterInfo:this.rasterInfo,multidimensionalDefinition:f?.multidimensionalDefinition,timeExtent:h,multidimensionalSubset:this.multidimensionalSubset}):null;if(!l)return this._processVisibleRastersResponse(i,{returnDomainValues:s,templateRRFunctionNames:u,showNoDataRecords:a,templateFields:r,effectiveMultidimensionalDefinition:p});const m=this.objectIdField||"ObjectId",d=i.catalogItems?.features??[],y=d.map(e=>e.attributes?.[m]),g=new Qe({objectIds:y,returnGeometry:!0,outSpatialReference:e.outSpatialReference,outFields:[m]}),R=await this.queryRasters(g);return R?.features?.length&&R.features.forEach(t=>{d.forEach(i=>{i.attributes[m]===t.attributes[m]&&t.geometry&&(i.geometry=t.geometry.clone(),null!=e.outSpatialReference&&(i.geometry.spatialReference=e.outSpatialReference))})}),this._processVisibleRastersResponse(i,{returnDomainValues:s,templateRRFunctionNames:u,showNoDataRecords:a,templateFields:r,effectiveMultidimensionalDefinition:p})}catch{throw new r("imagery-layer:query-visible-rasters","encountered error when querying visible rasters")}}async fetchVariableStatisticsHistograms(e,t){const r=i(Ge(this.parsedUrl)+"/statistics",{query:this._getQueryParams({variable:e}),signal:t}).then(e=>e.data?.statistics),s=i(Ge(this.parsedUrl)+"/histograms",{query:this._getQueryParams({variable:e}),signal:t}).then(e=>e.data?.histograms),n=await Promise.all([r,s]);return n[0]&&n[0].forEach(e=>{e.avg=e.mean,e.stddev=e.standardDeviation}),{statistics:n[0]||null,histograms:n[1]||null}}getMultidimensionalSubsetVariables(e){const t=e??this.serviceRasterInfo.multidimensionalInfo;return w(this.multidimensionalSubset,t)}async _fetchService(e){await this._fetchServiceInfo(e),this.rasterInfo||(this.rasterInfo=this.serviceRasterInfo);const t=this.sourceJSON,i=null!=this.serviceRasterInfo?Promise.resolve(this.serviceRasterInfo):Te(Ge(this.parsedUrl),t,{signal:e,query:this._getQueryParams()}).then(e=>(this._set("serviceRasterInfo",e),this._set("multidimensionalInfo",e.multidimensionalInfo),Me(e,t),e)),r=this._hasRasterFunction(this.rasterFunction)?this._generateRasterInfo(this.rasterFunction,{signal:e}):null,s=this._getRasterFunctionInfos();return Promise.all([i,r,s]).then(e=>{e[1]?this._set("rasterInfo",e[1]):this._set("rasterInfo",e[0]),e[2]&&this._set("rasterFunctionInfos",e[2]),this.internalRenderer&&!this._isSupportedRenderer(this.internalRenderer)&&(this._set("internalRenderer",null),n.getLogger(this).warn("ArcGISImageService","Switching to the default renderer. Renderer applied is not valid for this Imagery Layer")),this._set("internalRenderer",this._configRenderer(this.renderer)),this.addHandles([a(()=>this.rasterFunction,e=>{(this.renderer||this.symbolizer||this.popupEnabled&&this.popupTemplate)&&this._generateRasterInfo(e).then(e=>{e&&(this.rasterInfo=e)})})]);const{serviceRasterInfo:t}=this;null!=t.multidimensionalInfo&&this._updateMultidimensionalDefinition(t)})}_combineMosaicRuleWithTimeExtent(e,t){const i=this.timeInfo,{multidimensionalInfo:r}=this.serviceRasterInfo;if(null==e||null==r||null==t||null==i?.startField)return e;const{startField:s}=i,n=r.variables.some(e=>e.dimensions.some(e=>e.name===s))?s:"StdTime";if(e=e.clone(),"mosaic-dataset"===this.sourceType)return e.multidimensionalDefinition=e.multidimensionalDefinition?.filter(e=>e.dimensionName!==n),this._cleanupMultidimensionalDefinition(e);e.multidimensionalDefinition=e.multidimensionalDefinition||[];const a=e.multidimensionalDefinition.filter(e=>e.dimensionName===n),o=null!=t.start?t.start.getTime():null,l=null!=t.end?t.end.getTime():null,u=null==o||null==l||o===l,p=u?[o||l]:[[o,l]],m=this.version>=10.8;if(a.length)a.forEach(e=>{e.dimensionName===n&&(m?(e.dimensionName=null,e.isSlice=!1,e.values=[]):(e.isSlice=u,e.values=p))});else if(!m){const t=e.multidimensionalDefinition.filter(e=>null!=e.variableName&&null==e.dimensionName);t.length?t.forEach(e=>{e.dimensionName=n,e.isSlice=u,e.values=p}):e.multidimensionalDefinition.push(new O({variableName:"",dimensionName:n,isSlice:u,values:p}))}return this._cleanupMultidimensionalDefinition(e)}_cleanupMultidimensionalDefinition(e){return null==e?null:(e.multidimensionalDefinition&&(e.multidimensionalDefinition=e.multidimensionalDefinition.filter(e=>!(!e.variableName&&!e.dimensionName)),0===e.multidimensionalDefinition.length&&(e.multidimensionalDefinition=null)),"mosaic-dataset"!==this.sourceType&&null==e.multidimensionalDefinition?null:e)}async _prepareForQuery(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsQuery)throw new r("imagery-layer:query-rasters","query operation is not supported on the input image service");const i=null!=e?m(Qe,e):this.createQuery();return t=this._getRequestOptions(t),this.raster&&(t.query={...t.query,raster:this.raster}),{query:i,requestOptions:t}}_isSupportedRenderer(e){const{rasterInfo:t,rasterFunction:i}=this;return"unique-value"===e.type&&this._hasRasterFunction(i)&&1===t?.bandCount&&["u8","s8"].includes(t.pixelType)||null!=t&&null!=e&&te(t).includes(e.type)}async _fetchCapabilities(e){return this.capabilities||await this._fetchServiceInfo(e),this.capabilities}async _fetchServiceInfo(e){let t=this.sourceJSON;if(!t){const{data:r,ssl:s}=await i(Ge(this.parsedUrl),{query:this._getQueryParams(),signal:e});t=r,this.sourceJSON=t,s&&(this.url=this.url.replace(/^http:/i,"https:"))}if(t.capabilities?.toLowerCase().split(",").map(e=>e.trim()).indexOf("tilesonly")>-1)throw new r("imagery-layer:fetch-service-info","use ImageryTileLayer to open tiles-only image services");this.read(t,{origin:"service",url:this.parsedUrl})}_isMosaicDataset(e){return e.serviceSourceType?"esriImageServiceSourceTypeMosaicDataset"===e.serviceSourceType:e.fields?.length>0}_isMosaicRuleSupported(e){if(!e)return!1;const t=this._isMosaicDataset(e),i=e.currentVersion>=10.71&&e.hasMultidimensions&&!(e.fields?.length>1);return t||i}_isVectorFieldResampleFunction(e){if(null==e)return!1;const{functionName:t,functionArguments:i}=e,r="resample"===t?.toLowerCase(),s=i?.ResampleType||i?.resampleType;return r&&(7===s||10===s)}_isPicture(){return!this.format||this.format.includes("jpg")||this.format.includes("png")}_configRenderer(e){const t=this._isPicture(),{rasterInfo:i}=this;if(!t&&!this.pixelFilter||this._isVectorDataSet()){const t=this.mosaicRule?.multidimensionalDefinition?.[0].variableName,r=ie({variableName:t,rasterFunctionName:this.rasterFunction?.functionName,presetRenderers:this.presetRenderers});if(!this.bandIds&&i.bandCount>=3){const e=r?.bandIds??ee(i);!e||3===i.bandCount&&0===e[0]&&1===e[1]&&2===e[2]||(this.bandIds=e)}e||(e=r?.renderer??Z(i,{bandIds:this.bandIds,variableName:this.rasterFunction?null:t}));const s=re(e.toJSON());this.symbolizer?(this.symbolizer.rendererJSON=s,this.symbolizer.rasterInfo=i):this.symbolizer=new se({rendererJSON:s,rasterInfo:i}),this.symbolizer.bind().success||(this.symbolizer=null)}return e}_clonePixelData(e){return null==e?e:{extent:e.extent&&e.extent.clone(),pixelBlock:null!=e.pixelBlock?e.pixelBlock.clone():null}}_getQueryParams(e){null!=e?.renderingRule&&"string"!=typeof e.renderingRule&&(e.renderingRule=this._getRenderingRuleString(e.renderingRule));const{raster:t,viewId:i}=this;return{raster:t,viewId:i,f:"json",...e,...this.customParameters}}_getRequestOptions(e){return{...e,query:{...e?.query,...this.customParameters}}}_decodePixelBlock(e,t,i){return this._rasterJobHandler?this._rasterJobHandler.decode({data:e,options:t}):S(e,t,i)}async _getRasterFunctionInfos(e){const t=this.sourceJSON.rasterFunctionInfos;if(this.loaded)return t;if(t&&this.version>=10.3){if(1===t.length&&"none"===t[0].name.toLowerCase())return t;const r=await i(Ge(this.parsedUrl)+"/rasterFunctionInfos",{query:this._getQueryParams(),signal:e});return r.data?.rasterFunctionInfos}return null}_canRequestImageElement(e){return!this.pixelFilter&&(!e||e.includes("png"))}async _requestArrayBuffer(e){const{imageProps:t,requestAsImageElement:s,returnImageBitmap:n,signal:a}=e;if(s&&this._canRequestImageElement(t.format)){const r=`${Ge(this.parsedUrl)}/exportImage`,{data:s}=await i(r,{responseType:n?"blob":"image",query:this._getQueryParams({f:"image",...this.refreshParameters,...e.imageServiceParameters}),signal:a});if(s instanceof Blob){return{imageBitmap:await N(s,r,a),params:t}}return{imageOrCanvasElement:s,params:t}}const o=this._initJobHandler(),l=i(Ge(this.parsedUrl)+"/exportImage",{responseType:"array-buffer",query:this._getQueryParams({f:"image",...e.imageServiceParameters}),signal:a}),u=(await Promise.all([l,o]))[0].data,p=t.format||"jpgpng";let m=p;if("bsq"!==m&&"bip"!==m&&(m=x(u)),!m)throw new r("imagery-layer:fetch-image","unsupported format signature "+String.fromCharCode.apply(null,new Uint8Array(u)));const c={signal:a},d="gif"===p||"bmp"===p||p.includes("png")&&("png"===m||"jpg"===m)?S(u,{useCanvas:!0,...t},c):this._decodePixelBlock(u,{width:t.width,height:t.height,planes:null,pixelType:null,noDataValue:null,format:p},c);return{pixelData:{pixelBlock:await d,extent:t.extent},params:t}}_generateRasterInfo(e,t){return this.generateRasterInfo(e,t).catch(()=>null)}_isValidCustomizedMosaicRule(e){return e&&JSON.stringify(e.toJSON())!==JSON.stringify(this.defaultMosaicRule?.toJSON())}_updateMultidimensionalDefinition(e){if(this._isValidCustomizedMosaicRule(this.mosaicRule))return;let t=b(e,{multidimensionalSubset:this.multidimensionalSubset});if(null!=t&&t.length>0){this.mosaicRule=this.mosaicRule||new P;const e=this.mosaicRule.multidimensionalDefinition;!this.sourceJSON.defaultVariableName&&this.rasterFunction&&"none"!==this.rasterFunction.functionName?.toLowerCase()&&t.forEach(e=>e.variableName=""),t=t.filter(({variableName:e,dimensionName:t})=>e&&"*"!==e||t),!e?.length&&t.length&&(this.mosaicRule.multidimensionalDefinition=t)}}_processVisibleRastersResponse(e,i){i=i||{};const r=e.value,{templateRRFunctionNames:s,showNoDataRecords:n,returnDomainValues:a,templateFields:o}=i,l=e.processedValues;let u=e.catalogItems?.features,p=e.properties?.Values?.map(e=>e.replaceAll(/ /gi,", "))||[];const m=this.objectIdField||"ObjectId",c="string"==typeof r&&r.toLowerCase().includes("nodata"),d=[];if(r&&!u&&(!c||n)){const e={};e[m]=0;p=[r],u=[new t({geometry:this.fullExtent,attributes:e})],this.multidimensionalInfo&&"raster-dataset"===this.sourceType&&k(this.rasterFields,e,i.effectiveMultidimensionalDefinition)}if(!u)return[];this._updateResponseFieldNames(u,o),c&&!n&&(u=[]);const{itemPixelValue:h,servicePixelValue:f}=$,y=this.rasterFields.some(e=>e.name===h),g=this.graphicOrigin;for(let t=0;t<u.length;t++){const e=u[t];if(null!=r){const i=p[t],a=this.rasterFunction&&l&&l.length>0&&s&&s.length>0&&s.includes(this.rasterFunction.functionName)?l[s.indexOf(this.rasterFunction.functionName)]:r;if("nodata"===i.toLowerCase()&&!n)continue;y&&(e.attributes[h]=i),e.attributes[f]=a,this._updateFeatureWithMagDirValues(e,i);const o=this.fields&&this.fields.length>0;let u=this.rasterFunction&&null!=this.serviceRasterInfo.attributeTable?o?i:r:a;this.rasterFunction||(u=o?i:r),this._updateFeatureWithRasterAttributeTableValues(e,u)}if(e.sourceLayer=e.layer=this,e.origin=g,a&&this._updateFeatureWithDomainValues(e),s&&l&&s.length===l.length)for(let t=0;t<s.length;t++){const i=`${$.servicePixelValue}.${s[t]}`;e.attributes[i]=l[t]}d.push(u[t])}return d}_processMultidimensionalIntersection(e,t,i){const{multidimensionalSubset:r}=this;if(!r)return{isOutSide:!1,timeExtent:t,mosaicRule:i=this._combineMosaicRuleWithTimeExtent(i,t)};if(r){const{isOutside:i,intersection:s}=I(r,{geometry:e,timeExtent:t});if(i)return{isOutSide:!0,timeExtent:null,mosaicRule:null};null!=s?.timeExtent&&(t=s.timeExtent)}if(i=this._combineMosaicRuleWithTimeExtent(i,t),i?.multidimensionalDefinition){const{isOutside:e}=I(r,{multidimensionalDefinition:i.multidimensionalDefinition});if(e)return{isOutSide:!0,timeExtent:null,mosaicRule:null}}return{isOutSide:!1,timeExtent:t,mosaicRule:i}}_updateFeatureWithRasterAttributeTableValues(e,t){const i=this.rasterInfo.attributeTable||this.serviceRasterInfo.attributeTable;if(null==i)return;const{features:r,fields:s}=i,n=s.map(e=>e.name).find(e=>"value"===e.toLowerCase());if(!n)return;const a=r.filter(e=>e.attributes[n]===(null!=t?parseInt(t,10):null));a&&a[0]&&s.forEach(t=>{const i=X+t.name;e.attributes[i]=a[0].attributes[t.name]})}_updateFeatureWithMagDirValues(e,t){if(!this._isVectorDataSet())return;const i=t.split(/,\s*/).map(e=>parseFloat(e)),r=i.map(e=>[e]),s=i.map(e=>({minValue:e,maxValue:e,noDataValue:null})),n=new E({height:1,width:1,pixelType:"f32",pixels:r,statistics:s});null!=this.pixelFilter&&this.pixelFilter({pixelBlock:n,extent:new f(0,0,0,0,this.spatialReference)});const a="esriImageServiceDataTypeVector-MagDir"===this.serviceDataType?[n.pixels[0][0],n.pixels[1][0]]:_([n.pixels[0][0],n.pixels[1][0]]);e.attributes[$.magnitude]=a[0],e.attributes[$.direction]=a[1]}_updateFeatureWithDomainValues(e){const t=this.fields&&this.fields.filter(e=>"coded-value"===e.domain?.type);null!=t&&t.forEach(t=>{const i=e.attributes[t.name];if(null!=i){const r=t.domain.codedValues.find(e=>e.code===i);r&&(e.attributes[t.name]=r.name)}})}_updateResponseFieldNames(e,t){if(!t||t.length<1)return;const i=this.fieldsIndex;null!=i&&e.forEach(e=>{if(e?.attributes)for(const r of t){const t=i.get(r)?.name;t&&t!==r&&(e.attributes[r]=e.attributes[t],delete e.attributes[t])}})}_getRenderingRuleString(e){if(e){let t=e.toJSON();return t=t.rasterFunctionDefinition??t,(t.thumbnail||t.thumbnailEx)&&(t.thumbnail=t.thumbnailEx=null),JSON.stringify(t)}return null}_hasRasterFunction(e){return null!=e?.functionName&&"none"!==e.functionName.toLowerCase()}_updateRenderingRulesFunctionName(e,t){if(!e||e.length<1)return;if("Raw"===e)return e.replace("Raw","None");const i=e.toLowerCase().replaceAll(/ /gi,"_");return t.has(i)?t.get(i):e}_isRFTJson(e){return e?.name&&e.arguments&&e.function&&e.hasOwnProperty("functionType")}_isVectorDataSet(){return"esriImageServiceDataTypeVector-UV"===this.serviceDataType||"esriImageServiceDataTypeVector-MagDir"===this.serviceDataType}_applyMosaicAndRenderingRules(e){const{raster:t,mosaicRule:i,rasterFunction:r}=this;r&&null==e.rasterFunction&&(e.rasterFunction=r),i&&null==e.mosaicRule&&(e.mosaicRule=i),t&&null==e.raster&&(e.raster=t)}async _updateCurrentRasterInfo(e){if(this.renderer||this.symbolizer){const t=await this._generateRasterInfo(this.rasterFunction,{signal:e});t&&(this.rasterInfo=t)}}_applyMosaicRule(e){const{raster:t,mosaicRule:i}=this;i&&null==e.mosaicRule&&(e.mosaicRule=i),t&&null==e.raster&&(e.raster=t)}_readCapabilities(e){const t=e.capabilities?e.capabilities.toLowerCase().split(",").map(e=>e.trim()):["image","catalog"],{currentVersion:i,maxRecordCount:r}=e,s=t.includes("image"),n="esriImageServiceDataTypeElevation"===e.serviceDataType,a=!(!e.spatialReference&&!e.extent?.spatialReference),o=t.includes("edit"),l=t.includes("mensuration")&&a,u=null==e.mensurationCapabilities?[]:e.mensurationCapabilities.toLowerCase().split(",").map(e=>e.trim()),p=l&&u.includes("basic"),m=this._isMosaicDataset(e)&&t.includes("catalog"),c=t.includes("download"),d=i>=10.7&&n||i>=11.4&&(n||l&&u.includes("3d")),h=m&&e.fields&&e.fields.length>0,f=h&&e.supportsAdvancedQueries?e.advancedQueryCapabilities:void 0;return{data:{supportsAttachment:!1},operations:{supportsComputeHistograms:s,supportsExportImage:s,supportsIdentify:s,supportsImageToMap:i>=11.2&&m,supportsImageToMapMultiray:i>=11.2&&m,supportsMapToImage:i>=11.2&&m,supportsFindImages:i>=11.2&&m,supportsGetImageUrl:i>=11.3&&c,supportsMeasure:l,supportsMeasureFromImage:i>=11.2,supportsDownload:c,supportsQuery:h,supportsGetSamples:i>=10.2&&s,supportsProject:i>=10.3&&s,supportsComputeStatisticsHistograms:i>=10.4&&s,supportsQueryBoundary:i>=10.6&&s,supportsCalculateVolume:d,supportsComputePixelLocation:i>=10.7&&m,supportsComputeAngles:i>=10.91,supportsQueryGPSInfo:i>=11.2&&m,supportsAdd:o,supportsDelete:o,supportsEditing:o,supportsUpdate:o,supportsCalculate:!1,supportsTruncate:!1,supportsValidateSql:!1,supportsChangeTracking:!1,supportsQueryAttachments:!1,supportsResizeAttachments:!1,supportsSync:!1,supportsExceedsLimitStatistics:!1,supportsQueryAnalytics:!1,supportsQueryBins:!1,supportsQueryPivot:!1,supportsQueryTopFeatures:!1,supportsAsyncConvert3D:!1},query:{maxRecordCount:r,maxRecordCountFactor:void 0,maxUniqueIDCount:void 0,relativeTimeBinWindow:void 0,supportsStatistics:!!f?.supportsStatistics,supportsOrderBy:!!f?.supportsOrderBy,supportsDistinct:!!f?.supportsDistinct,supportsPagination:!!f?.supportsPagination,supportsPaginationOnAggregatedQueries:!!f?.supportsPaginationOnAggregatedQueries,supportsStandardizedQueriesOnly:!!f?.useStandardizedQueries,supportsPercentileStatistics:!!f?.supportsPercentileStatistics,supportsCentroid:!!f?.supportsReturningGeometryCentroid,supportsCentroidOnDegeneratedQuantizedGeometry:!1,supportsCurrentUser:!1,supportsDegeneratedQuantizedGeometry:!1,supportsDistance:!!f?.supportsQueryWithDistance,supportsExtent:!!f?.supportsReturningQueryExtent,supportsGeometryProperties:!!f?.supportsReturningGeometryProperties,supportsHavingClause:!!f?.supportsHavingClause,supportsQuantization:!1,supportsQuantizationEditMode:!1,supportsQueryGeometry:!1,supportsResultType:!1,supportsReturnMesh:!1,supportsMaxRecordCountFactor:!1,supportsSqlExpression:f?.supportsSqlExpression??!!f,supportsTopFeaturesQuery:!1,supportsQueryByAnonymous:!1,supportsQueryByOthers:!1,supportsHistoricMoment:!1,supportsFormatPBF:!1,supportsFormatPBFWithCurves:!1,supportsDisjointSpatialRelationship:!1,supportsCacheHint:!1,supportsSpatialAggregationStatistics:!1,supportedSpatialAggregationStatistics:{envelope:!1,centroid:!1,convexHull:!1},supportsDefaultSpatialReference:!!f?.supportsDefaultSR,supportsFullTextSearch:!1,supportsCompactGeometry:!1,standardMaxRecordCount:void 0,standardMaxRecordCountNoGeometry:void 0,tileMaxRecordCount:void 0,supportsTrueCurve:!1},mensuration:{supportsDistanceAndAngle:p,supportsAreaAndPerimeter:p,supportsPointOrCentroid:p,supportsHeightFromBaseAndTop:l&&u.includes("base-top height"),supportsHeightFromBaseAndTopShadow:l&&u.includes("base-top shadow height"),supportsHeightFromTopAndTopShadow:l&&u.includes("top-top shadow height"),supports3D:l&&u.includes("3d")}}}};function Ge(e){return e?.path??""}return e([l({clonable:!1})],He.prototype,"_functionRasterInfos",void 0),e([l({readOnly:!0})],He.prototype,"_serviceSupportsMosaicRule",void 0),e([Je("_serviceSupportsMosaicRule",["currentVersion","fields"])],He.prototype,"readServiceSupportsMosaicRule",null),e([l({readOnly:!0})],He.prototype,"_rasterFunctionNamesIndex",null),e([l()],He.prototype,"adjustAspectRatio",void 0),e([l({type:[p],json:{write:!0}})],He.prototype,"bandIds",void 0),e([Je("bandIds")],He.prototype,"readBandIds",null),e([l({readOnly:!0,json:{read:!1}})],He.prototype,"capabilities",void 0),e([Je("service","capabilities",["capabilities","currentVersion","serviceDataType"])],He.prototype,"readCapabilities",null),e([l({type:Number})],He.prototype,"compressionQuality",void 0),e([Ue("compressionQuality")],He.prototype,"writeCompressionQuality",null),e([l({type:Number})],He.prototype,"compressionTolerance",void 0),e([Ue("compressionTolerance")],He.prototype,"writeCompressionTolerance",null),e([l({json:{read:{source:"copyrightText"}}})],He.prototype,"copyright",void 0),e([l({readOnly:!0})],He.prototype,"defaultMosaicRule",void 0),e([Je("defaultMosaicRule",["defaultMosaicMethod"])],He.prototype,"readDefaultMosaicRule",null),e([l({type:String,json:{name:"layerDefinition.definitionExpression",write:{enabled:!0,allowNull:!0}}})],He.prototype,"definitionExpression",void 0),e([l({readOnly:!0,constructOnly:!0})],He.prototype,"exportImageServiceParameters",void 0),e([l()],He.prototype,"rasterInfo",void 0),e([l({readOnly:!0,type:[C]})],He.prototype,"fields",void 0),e([l({readOnly:!0})],He.prototype,"fieldsIndex",null),e([l({type:["png","png8","png24","png32","jpg","bmp","gif","jpgpng","lerc","tiff","bip","bsq"],json:{write:!0}})],He.prototype,"format",null),e([Je("service","format",["serviceDataType"])],He.prototype,"readFormat",null),e([l({type:f})],He.prototype,"fullExtent",void 0),e([l({readOnly:!0})],He.prototype,"hasMultidimensions",void 0),e([l({json:{read:{source:"maxImageHeight"}}})],He.prototype,"imageMaxHeight",void 0),e([l({json:{read:{source:"maxImageWidth"}}})],He.prototype,"imageMaxWidth",void 0),e([l({type:String,json:{type:A.jsonValues,read:A.read,write:A.write}})],He.prototype,"interpolation",void 0),e([l()],He.prototype,"minScale",void 0),e([Je("service","minScale")],He.prototype,"readMinScale",null),e([l()],He.prototype,"maxScale",void 0),e([Je("service","maxScale")],He.prototype,"readMaxScale",null),e([l({type:P})],He.prototype,"mosaicRule",null),e([Je("mosaicRule",["mosaicRule","defaultMosaicMethod"])],He.prototype,"readMosaicRule",null),e([Ue("mosaicRule")],He.prototype,"writeMosaicRule",null),e([l()],He.prototype,"multidimensionalInfo",void 0),e([l({type:j,json:{write:!0}})],He.prototype,"multidimensionalSubset",void 0),e([l({json:{type:p}})],He.prototype,"noData",void 0),e([Ue("noData")],He.prototype,"writeNoData",null),e([l({type:String,json:{type:V.jsonValues,read:V.read,write:V.write}})],He.prototype,"noDataInterpretation",void 0),e([l({type:String,readOnly:!0,json:{read:{source:["fields"]}}})],He.prototype,"objectIdField",void 0),e([Je("objectIdField")],He.prototype,"readObjectIdField",null),e([l({readOnly:!0})],He.prototype,"geometryType",void 0),e([l({})],He.prototype,"typeIdField",void 0),e([l({})],He.prototype,"types",void 0),e([l({readOnly:!0})],He.prototype,"parsedUrl",null),e([l({type:Function})],He.prototype,"pixelFilter",void 0),e([l()],He.prototype,"raster",void 0),e([l({readOnly:!0})],He.prototype,"sourceType",void 0),e([Je("sourceType",["serviceSourceType","fields"])],He.prototype,"readSourceType",null),e([l()],He.prototype,"viewId",void 0),e([l({types:ne})],He.prototype,"renderer",null),e([l({types:ne,json:{name:"layerDefinition.drawingInfo.renderer",origins:{"web-scene":{types:ae,name:"layerDefinition.drawingInfo.renderer",write:{overridePolicy:e=>({enabled:e&&"vector-field"!==e.type})}}}}})],He.prototype,"internalRenderer",null),e([Je("internalRenderer")],He.prototype,"readRenderer",null),e([Ue("internalRenderer")],He.prototype,"writeRenderer",null),e([l({clonable:!1})],He.prototype,"symbolizer",void 0),e([l(F)],He.prototype,"opacity",void 0),e([l({readOnly:!0})],He.prototype,"rasterFields",null),e([l({constructOnly:!0})],He.prototype,"rasterFunctionInfos",void 0),e([l({type:K,json:{name:"renderingRule"}})],He.prototype,"rasterFunction",null),e([Je("rasterFunction",["renderingRule","rasterFunctionInfos"])],He.prototype,"readRasterFunction",null),e([l({readOnly:!0})],He.prototype,"serviceDataType",void 0),e([l({readOnly:!0,type:g})],He.prototype,"spatialReference",void 0),e([Je("spatialReference",["spatialReference","extent"])],He.prototype,"readSpatialReference",null),e([l({type:Q.apiValues,json:{read:Q.read,type:Q.jsonValues}})],He.prototype,"pixelType",void 0),e([Ue("pixelType")],He.prototype,"writePixelType",null),e([l({constructOnly:!0,type:Y})],He.prototype,"serviceRasterInfo",void 0),e([l()],He.prototype,"sourceJSON",void 0),e([l(D)],He.prototype,"url",void 0),e([l({readOnly:!0})],He.prototype,"version",void 0),e([Je("version",["currentVersion","fields","timeInfo"])],He.prototype,"readVersion",null),He=e([u("esri.layers.mixins.ArcGISImageService")],He),He};export{He as ArcGISImageService};
2
+ import{__decorate as e}from"tslib";import t from"../../Graphic.js";import i from"../../request.js";import r from"../../core/Error.js";import{clone as s}from"../../core/lang.js";import n from"../../core/Logger.js";import{watch as a}from"../../core/reactiveUtils.js";import{urlToObject as o}from"../../core/urlUtils.js";import{property as l,subclass as u}from"../../core/accessorSupport/decorators.js";import{Integer as p,ensureClass as m,ensureRange as c,ensureNumber as h}from"../../core/accessorSupport/ensureType.js";import{runUntracked as d}from"../../core/accessorSupport/tracking.js";import f from"../../geometry/Extent.js";import y from"../../geometry/Polygon.js";import g from"../../geometry/SpatialReference.js";import{srToRESTValue as R}from"../../geometry/support/spatialReferenceUtils.js";import{intersectMultimensionalSubset as I,getEffectiveMultidimensionalDefinition as v,getSubsetVariablesFromMdInfo as w,getDefaultMultidimensionalDefinition as b}from"../raster/datasets/multidimensionalUtils.js";import{decode as S,getFormat as x}from"../raster/formats/RasterCodec.js";import{uvComponentToVector as _}from"../raster/functions/vectorFieldUtils.js";import{opacity as F,url as D}from"../support/commonProperties.js";import O from"../support/DimensionalDefinition.js";import{ExportImageServiceParameters as T}from"../support/ExportImageServiceParameters.js";import C from"../support/Field.js";import M from"../support/FieldsIndex.js";import{createBitmap as N}from"../support/imageBitmapUtils.js";import{isSupportedRendererType as q}from"../support/imageryRendererUtils.js";import P from"../support/MosaicRule.js";import j from"../support/MultidimensionalSubset.js";import E from"../support/PixelBlock.js";import{interpolationKebab as A,noDataInterpretationKebab as Q,pixelTypeKebabDict as V}from"../support/rasterEnums.js";import{getServicePixelValueField as J,getItemPixelValueField as U,getRawServicePixelValueField as B,getProcessedServicePixelValueField as z,getMagnitudeField as L,getDirectionField as H,getMultidimensionalFields as G,getRasterAttributeTableFields as k,addMultidimensionalFieldValues as W,commonRasterFieldNames as $,rasterFieldPrefix as X}from"../support/rasterFieldUtils.js";import K from"../support/RasterFunction.js";import Y from"../support/RasterInfo.js";import{createDefaultRenderer as Z,getDefaultBandCombination as ee,getSupportedRendererTypes as te,matchPresetRenderer as ie,normalizeRendererJSON as re}from"../../renderers/support/rasterRendererHelper.js";import se from"../../renderers/support/RasterSymbolizer.js";import{rasterRendererTypes as ne,websceneRasterRendererTypes as ae,read as oe}from"../../renderers/support/rasterTypeUtils.js";import{calculateVolume as le,computeAngles as ue,computePixelSpaceLocations as pe,computeHistograms as me,computeStatisticsHistograms as ce,measureHeight as he,measureAreaAndPerimeter as de,measureDistanceAndAngle as fe,measurePointOrCentroid as ye,measureLengthFromImage as ge,measureAreaFromImage as Re,getImageSpatialReferenceQueryParameter as Ie,getSamples as ve,identify as we,imageToMap as be,imageToMapMultiray as Se,mapToImage as xe,findImages as _e,getImageUrl as Fe,queryBoundary as De,queryGPSInfo as Oe}from"../../rest/imageService.js";import{fetchServiceRasterInfo as Te,generateRasterInfo as Ce,patchServiceInfo as Me}from"../../rest/imageService/fetchRasterInfo.js";import{getCatalogItemRasterInfo as Ne}from"../../rest/imageService/getCatalogItemRasterInfo.js";import{executeForCount as qe}from"../../rest/query/executeForCount.js";import{executeForExtent as Pe}from"../../rest/query/executeForExtent.js";import{executeForIds as je}from"../../rest/query/executeForIds.js";import{executeQueryJSON as Ee}from"../../rest/query/executeQueryJSON.js";import Ae from"../../rest/support/FeatureSet.js";import Qe from"../../rest/support/ImageIdentifyParameters.js";import Ve from"../../rest/support/Query.js";import{reader as Je}from"../../core/accessorSupport/decorators/reader.js";import{writer as Ue}from"../../core/accessorSupport/decorators/writer.js";const Be=new Set(["png","png8","png24","png32","jpg","bmp","gif","jpgpng","lerc","tiff"]),ze=c(h,{min:0,max:255});function Le(e){const t=JSON.stringify(e),i=t.includes('"rasterFunctionDefinition":{'),r=i?t.match(/"type":"(.*?FunctionArguments")/gi):t.match(/"rasterFunction":"(.*?")/gi),s=r?.map(e=>i?e.slice(8,-18):e.slice(18,-1));return s?s.join("/"):null}const He=c=>{const h=c;let He=class extends h{constructor(){super(...arguments),this._functionRasterInfos={},this._serviceSupportsMosaicRule=null,this.adjustAspectRatio=null,this.bandIds=void 0,this.capabilities=null,this.compressionQuality=void 0,this.compressionTolerance=.01,this.copyright=null,this.defaultMosaicRule=null,this.definitionExpression=null,this.exportImageServiceParameters=null,this.rasterInfo=null,this.fields=null,this.fullExtent=null,this.hasMultidimensions=!1,this.imageMaxHeight=4100,this.imageMaxWidth=4100,this.interpolation=void 0,this.minScale=0,this.maxScale=0,this.multidimensionalInfo=null,this.multidimensionalSubset=null,this.noData=null,this.noDataInterpretation=void 0,this.objectIdField=null,this.geometryType="polygon",this.typeIdField=null,this.types=[],this.pixelFilter=null,this.raster=void 0,this.sourceType=null,this.viewId=void 0,this.symbolizer=null,this.rasterFunctionInfos=null,this.serviceDataType=null,this.spatialReference=null,this.pixelType=null,this.serviceRasterInfo=null,this.sourceJSON=null,this.url=null,this.version=void 0}initialize(){this._set("exportImageServiceParameters",new T({layer:this}))}readServiceSupportsMosaicRule(e,t){return this._isMosaicRuleSupported(t)}get _rasterFunctionNamesIndex(){const e=new Map;return!this.rasterFunctionInfos||null!=this.rasterFunctionInfos&&this.rasterFunctionInfos.length<1||null!=this.rasterFunctionInfos&&this.rasterFunctionInfos.forEach(t=>{e.set(t.name.toLowerCase().replaceAll(/ /gi,"_"),t.name)}),e}readBandIds(e,t){if(Array.isArray(e)&&e.length>0&&e.every(e=>"number"==typeof e))return e}readCapabilities(e,t){return this._readCapabilities(t)}writeCompressionQuality(e,t,i){null!=e&&"lerc"!==this.format&&(t[i]=e)}writeCompressionTolerance(e,t,i){"lerc"===this.format&&null!=e&&(t[i]=e)}readDefaultMosaicRule(e,t){return this._serviceSupportsMosaicRule?d(()=>P.fromJSON(t)):null}get fieldsIndex(){return this.fields?new M(this.fields):null}set format(e){e&&Be.has(e.toLowerCase())&&this._set("format",e.toLowerCase())}readFormat(e,t){return"esriImageServiceDataTypeVector-UV"===t.serviceDataType||"esriImageServiceDataTypeVector-MagDir"===t.serviceDataType||null!=this.pixelFilter?"lerc":"jpgpng"}readMinScale(e,t){return null!=t.minLOD&&null!=t.maxLOD?e:0}readMaxScale(e,t){return null!=t.minLOD&&null!=t.maxLOD?e:0}set mosaicRule(e){let t=e;t?.mosaicMethod&&(t=P.fromJSON({...t.toJSON(),mosaicMethod:t.mosaicMethod,mosaicOperation:t.mosaicOperation})),this._set("mosaicRule",t)}readMosaicRule(e,t){const i=e||t.mosaicRule;return i?P.fromJSON(i):this._isMosaicRuleSupported(t)?P.fromJSON(t):null}writeMosaicRule(e,t,i){const{mosaicRule:r}=this;this._isValidCustomizedMosaicRule(r)&&(t[i]=r.toJSON())}writeNoData(e,t,i){null!=e&&"number"==typeof e&&(t[i]=ze(e))}readObjectIdField(e,t){if(!e){const i=t.fields.find(e=>"esriFieldTypeOID"===e.type||"oid"===e.type);e=i?.name}return e}get parsedUrl(){return o(this.url)}readSourceType(e,t){return this._isMosaicDataset(t)?"mosaic-dataset":"raster-dataset"}get renderer(){const{activePresetRendererName:e,presetRenderers:t}=this;if(e){const i=t?.find(({name:t})=>t===e);return i?.renderer.clone()}return this.internalRenderer}set renderer(e){this.activePresetRendererName=null,this.internalRenderer=e}set internalRenderer(e){this.loaded&&(e=this._configRenderer(e)),this._set("internalRenderer",e)}readRenderer(e,t,i){const r=t?.layerDefinition?.drawingInfo?.renderer,s=oe(r,i);return null==s?null:("vector-field"===s.type&&t.symbolTileSize&&!r.symbolTileSize&&(s.symbolTileSize=t.symbolTileSize),q(s)||n.getLogger(this).warn("ArcGISImageService","Imagery layer doesn't support given renderer type."),s)}writeRenderer(e,t,i){t.layerDefinition=t.layerDefinition||{},t.layerDefinition.drawingInfo=t.layerDefinition.drawingInfo||{},t.layerDefinition.drawingInfo.renderer=e.toJSON()}get rasterFields(){const e=this.fields?.map(e=>e.clone())??[];e.push(J()),"mosaic-dataset"===this.sourceType&&this.fields?.length&&e.push(U()),this.version>=10.4&&null!=this.rasterFunctionInfos&&this.rasterFunctionInfos.some(({name:e})=>"none"===e.toLowerCase())&&e.push(B()),null!=this.rasterFunctionInfos&&this.rasterFunctionInfos.filter(({name:e})=>"none"!==e.toLowerCase()).forEach(({name:t})=>e.push(z(t)));const{rasterInfo:t}=this;if(this._isVectorDataSet()){const i=t?.multidimensionalInfo?.variables[0].unit?.trim(),r=L(i),s=H();e.push(r,s)}if(t?.multidimensionalInfo&&"raster-dataset"===this.sourceType){const i=G(t.multidimensionalInfo);e.push(...i)}const i=t?.attributeTable;if(null!=i){const t=k(i);e.push(...t)}return e}set rasterFunction(e){let t=e;t?.rasterFunction&&(t=K.fromJSON({...t.toJSON(),rasterFunction:t.rasterFunction,rasterFunctionArguments:t.rasterFunctionArguments})),this._set("rasterFunction",t)}readRasterFunction(e,t){const i=t.rasterFunctionInfos;return t.renderingRule||i?.length&&"None"!==i[0].name?this._isRFTJson(t.renderingRule)?K.fromJSON({rasterFunctionDefinition:t.renderingRule}):K.fromJSON(t.renderingRule||{rasterFunctionInfos:t.rasterFunctionInfos}):null}readSpatialReference(e,t){const i=e||t.extent.spatialReference;return i?g.fromJSON(i):null}writePixelType(e,t,i){null!=this.serviceRasterInfo&&this.pixelType===this.serviceRasterInfo.pixelType||(t[i]=V.toJSON(e))}readVersion(e,t){let i=t.currentVersion;return i||(i=t.hasOwnProperty("fields")||t.hasOwnProperty("timeInfo")?10:9.3),i}applyFilter(e){let t=e;return this.pixelFilter&&(t=this._clonePixelData(e),this.pixelFilter(t)),t}async applyRenderer(e,t){let i=e,{renderer:r,symbolizer:s,pixelFilter:n}=this;const{isRawData:a}=e;if(a&&"lerc"!==this.format&&(r??=Z(this.rasterInfo,{bandIds:this.bandIds,variableName:this.rasterFunction?null:this.mosaicRule?.multidimensionalDefinition?.[0].variableName}),s||(this.symbolizer=new se({rendererJSON:r.toJSON(),rasterInfo:this.rasterInfo}),s=this.symbolizer)),(a||!this._isPicture())&&r&&s&&!n){await this._updateSymbolizer(s,r);const n=this.bandIds?.length?this.bandIds:ee(this.rasterInfo);i=await this._symbolize({pixelData:e,bandIds:n,symbolizer:s},t)}return i}destroy(){this._shutdownJobHandler()}async calculateVolume(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsCalculateVolume)throw new r("imagery-layer:compute-pixel-space-locations","this operation is not supported on the input image service");return e=s(e),this.mosaicRule&&null==e.mosaicRule&&(e.mosaicRule=this.mosaicRule),le(this.url,e,this._getRequestOptions(t))}async computeAngles(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsComputeAngles)throw new r("imagery-layer:compute-angles","this operation is not supported on the input image service");return ue(this.url,e,this._getRequestOptions(t))}async computePixelSpaceLocations(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsComputePixelLocation)throw new r("imagery-layer:compute-pixel-space-locations","this operation is not supported on the input image service");return pe(this.url,e,this._getRequestOptions(t))}async computeHistograms(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsComputeHistograms)throw new r("imagery-layer:compute-histograms","this operation is not supported on the input image service");return e=s(e),this._applyMosaicAndRenderingRules(e),me(this.url,e,this._getRequestOptions(t))}async computeStatisticsHistograms(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsComputeStatisticsHistograms)throw new r("imagery-layer:compute-statistics-histograms","this operation is not supported on the input image service");return e=s(e),this._applyMosaicAndRenderingRules(e),ce(this.url,e,this._getRequestOptions(t))}async measureHeight(e,t){const i=await this._fetchCapabilities(t?.signal);if(!("base-and-top"===e.operationType?i.mensuration.supportsHeightFromBaseAndTop:"base-and-top-shadow"===e.operationType?i.mensuration.supportsHeightFromBaseAndTopShadow:i.mensuration.supportsHeightFromTopAndTopShadow))throw new r("imagery-layer:measure-height","this operation is not supported on the input image service");return e=s(e),this._applyMosaicRule(e),he(this.url,e,this._getRequestOptions(t))}async measureAreaAndPerimeter(e,t){const i=await this._fetchCapabilities(t?.signal);if(!(i.mensuration.supportsAreaAndPerimeter&&(!e.is3D||i.mensuration.supports3D)))throw new r("imagery-layer:measure-area-and-perimeter","this operation is not supported on the input image service");return e=s(e),this._applyMosaicRule(e),de(this.url,e,this._getRequestOptions(t))}async measureDistanceAndAngle(e,t){const i=await this._fetchCapabilities(t?.signal);if(!(i.mensuration.supportsDistanceAndAngle&&(!e.is3D||i.mensuration.supports3D)))throw new r("imagery-layer:measure-distance-and-angle","this operation is not supported on the input image service");return e=s(e),this._applyMosaicRule(e),fe(this.url,e,this._getRequestOptions(t))}async measurePointOrCentroid(e,t){const i=await this._fetchCapabilities(t?.signal);if(!(i.mensuration.supportsPointOrCentroid&&(!e.is3D||i.mensuration.supports3D)))throw new r("imagery-layer:measure-point-or-centroid","this operation is not supported on the input image service");return e=s(e),this._applyMosaicRule(e),ye(this.url,e,this._getRequestOptions(t))}async measureLengthFromImage(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsMeasureFromImage)throw new r("imagery-layer:measure-length-from-image","this operation is not supported on the input image service");if("polyline"!==e.geometry.type)throw new r("imagery-layer:measure-length-from-image","this input geometry must be a polyline");return ge(this.url,e,this._getRequestOptions(t))}async measureAreaFromImage(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsMeasureFromImage)throw new r("imagery-layer:measure-area-from-image","this operation is not supported on the input image service");if("polygon"!==e.geometry.type)throw new r("imagery-layer:measure-area-from-image","this input geometry must be a polygon");return Re(this.url,e,this._getRequestOptions(t))}getField(e){const{fieldsIndex:t}=this;return null!=t?t.get(e):void 0}getFieldDomain(e,t){const i=this.getField(e);return i?i.domain:null}async internalFetchImage(e,t,i,r={}){await this._updateCurrentRasterInfo();const{exportImageServiceParameters:s}=this;let n=!1;r.requestRawData&&(await this._initJobHandler(),s.requestRawData||"lerc"===this.format||(n=!0,s.requestRawData=!0));const a=this.getExportImageServiceParameters(e,t,i,r.timeExtent);if(n&&(s.requestRawData=!1,a&&!this.bandIds?.length&&(null==a.bandIds||""===a.bandIds))){const e=ee(this.rasterInfo);a.bandIds=e?.join(",")}if(null==a){if(r.requestAsImageElement&&this._canRequestImageElement(this.format)){const e=document.createElement("canvas");if(e.width=t,e.height=i,r.returnImageBitmap){return{imageBitmap:await N(e,`${Ge(this.parsedUrl)}/exportImage`,r.signal)}}return{imageOrCanvasElement:e}}const{bandIds:s,rasterInfo:n}=this,a=(s?.length||n.bandCount)??0,o=t*i,l=n.pixelType,u=[];for(let e=0;e<a;e++)u.push(E.createEmptyBand(l,o));return{pixelData:{pixelBlock:new E({width:t,height:i,pixels:u,mask:new Uint8Array(o),pixelType:l}),extent:e}}}const o=!!r.requestAsImageElement&&!this.pixelFilter,l=o&&!!r.returnImageBitmap,u={imageServiceParameters:a,imageProps:{extent:e,width:t,height:i,format:this.format},requestAsImageElement:o,returnImageBitmap:l,signal:r.signal};return this._requestArrayBuffer(u)}async fetchPixels(e,t,i,r={}){await this._initJobHandler(),r.applyRendering&&this._updateCurrentRasterInfo();const s=r.applyRendering?void 0:new T({layer:this,requestRawData:!0,interpolation:r.interpolation??"nearest",bandIds:r.bandIds??[]}),n=this.getExportImageServiceParameters(e,t,i,r.timeExtent,s);if(null==n)return{extent:e,pixelBlock:null};delete n.pixelType,r.bandIds||delete n.bandIds,delete n.compressionQuality;const a={imageServiceParameters:n,imageProps:{extent:e,width:t,height:i,format:this.format},requestAsImageElement:!1,returnImageBitmap:!1,signal:r.signal},{pixelData:o}=await this._requestArrayBuffer(a);return o??{extent:e,pixelBlock:null}}fetchKeyProperties(e){return i(Ge(this.parsedUrl)+"/keyProperties",{query:this._getQueryParams({renderingRule:this.version>=10.3?e?.rasterFunction:null})}).then(e=>e.data)}fetchRasterAttributeTable(e){return this.version<10.1?Promise.reject(new r("#fetchRasterAttributeTable()","Failed to get rasterAttributeTable")):i(Ge(this.parsedUrl)+"/rasterAttributeTable",{query:this._getQueryParams({renderingRule:this.version>=10.3?e?.rasterFunction:null})}).then(e=>Ae.fromJSON(e.data))}getCatalogItemRasterInfo(e,t){const i={...t,query:this._getQueryParams()};return Ne(Ge(this.parsedUrl),e,i)}async getCatalogItemICSInfo(e,t){const{data:r}=await i(Ge(this.parsedUrl)+"/"+e+"/info/ics",{query:this._getQueryParams(),...t}),s=r?.ics;if(!s)return;let n=null;try{n=(await i(Ge(this.parsedUrl)+"/"+e+"/info",{query:this._getQueryParams(),...t})).data.extent}catch{}if(!n?.spatialReference)return{ics:s,icsToPixelTransform:null,icsExtent:null,northDirection:null};const a=this.version>=10.7?i(Ge(this.parsedUrl)+"/"+e+"/info/icstopixel",{query:this._getQueryParams(),...t}).then(e=>e.data).catch(()=>({})):{},o=n.spatialReference,l={geometries:JSON.stringify({geometryType:"esriGeometryEnvelope",geometries:[n]}),inSR:R(o),outSR:"0:"+e},u=i(Ge(this.parsedUrl)+"/project",{query:this._getQueryParams(l),...t}).then(e=>e.data).catch(()=>({})),p=5,m=(n.xmin+n.xmax)/2,c=(n.ymax-n.ymin)/(p+1),h=n.ymin+c,d=[];for(let i=0;i<p;i++)d.push({x:m,y:h+c*i});const y={geometries:JSON.stringify({geometryType:"esriGeometryPoint",geometries:d}),inSR:R(o),outSR:"0:"+e},I=i(Ge(this.parsedUrl)+"/project",{query:this._getQueryParams(y),...t}).then(e=>e.data).catch(()=>({})),v=await Promise.all([a,u,I]);let w=v[0].ipxf;if(null==w){const e=s.geodataXform?.xf_0;"topup"===e?.name?.toLowerCase()&&6===e?.coefficients?.length&&(w={affine:{name:"ics [sensor: Frame] to pixel (column, row) transformation",coefficients:e.coefficients,cellsizeRatio:0,type:"GeometricXform"}})}const b=f.fromJSON(v[1]?.geometries?.[0]);b&&(b.spatialReference=new g({wkid:0,imageCoordinateSystem:s}));const S=v[2].geometries?v[2].geometries.filter(e=>null!=e?.x&&null!=e.y&&"NaN"!==e.x&&"NaN"!==e.y):[],x=S.length;if(x<3)return{ics:s,icsToPixelTransform:w,icsExtent:b,northDirection:null};let _=0,F=0,D=0,O=0;for(let i=0;i<x;i++)_+=S[i].x,F+=S[i].y,D+=S[i].x*S[i].x,O+=S[i].x*S[i].y;const T=(x*O-_*F)/(x*D-_*_);let C=0;const M=S[p-1].x>S[0].x,N=S[p-1].y>S[0].y;return T===1/0?C=N?90:270:0===T?C=M?0:180:T>0?C=M?180*Math.atan(T)/Math.PI:180*Math.atan(T)/Math.PI+180:T<0&&(C=N?180+180*Math.atan(T)/Math.PI:360+180*Math.atan(T)/Math.PI),{ics:s,icsToPixelTransform:w,icsExtent:b,northDirection:C}}async generateRasterInfo(e,t){const i=m(K,e),s={...t,query:this._getQueryParams()};if(!i||"none"===i.functionName?.toLowerCase()||this._isVectorFieldResampleFunction(i))return this.serviceRasterInfo??Te(Ge(this.parsedUrl),this.sourceJSON,s);const n=Le(i);if(!n)throw new r("imagery-layer:generate-raster-info","the rendering rule is not supported");if(this._functionRasterInfos[n])return this._functionRasterInfos[n];const a=Ce(Ge(this.parsedUrl),i,s);this._functionRasterInfos[n]=a;try{return await a}catch(o){throw this._functionRasterInfos[n]=null,o}}getExportImageServiceParameters(e,t,i,r,s){e=e.clone().shiftCentralMeridian();const n=Ie(e.spatialReference,Ge(this.parsedUrl));s??=this.exportImageServiceParameters;const a=s.toJSON(),{bandIds:o,noData:l}=a;let{renderingRule:u}=a;const p=this.rasterFunction?.rasterFunctionDefinition,m=this.renderer?.type,c=!m||"raster-stretch"===m||"raster-colormap"===m||"unique-value"===m||"class-breaks"===m||"raster-shaded-relief"===m;if(o?.length&&this._hasRasterFunction(this.rasterFunction)&&!p&&c){const e={rasterFunction:"ExtractBand",rasterFunctionArguments:{BandIds:o}};if("Stretch"===u.rasterFunction)e.rasterFunctionArguments.Raster=u.rasterFunctionArguments.Raster,u.rasterFunctionArguments.Raster=e;else if("Colormap"===u.rasterFunction){const t=u.rasterFunctionArguments.Raster;"Stretch"===t?.rasterFunction?(e.rasterFunctionArguments.Raster=t.rasterFunctionArguments.Raster,t.rasterFunctionArguments.Raster=e):(e.rasterFunctionArguments.Raster=t,u.rasterFunctionArguments.Raster=e)}else e.rasterFunctionArguments.Raster=u,u=e;a.bandIds=void 0}else a.bandIds=o?.join(",");Array.isArray(l)&&l.length>0&&(a.noData=l.join(","));const h=this._processMultidimensionalIntersection(null,r,s.mosaicRule);if(h.isOutSide)return null;a.mosaicRule=null!=h.mosaicRule?JSON.stringify(h.mosaicRule):null,r=h.timeExtent,a.renderingRule=this._getRenderingRuleString(K.fromJSON(u));const d={};if(null!=r){const{start:e,end:t}=r.toJSON();e&&t&&e===t?d.time=""+e:null==e&&null==t||(d.time=`${e??"null"},${t??"null"}`)}return{bbox:e.xmin+","+e.ymin+","+e.xmax+","+e.ymax,bboxSR:n,imageSR:n,size:t+","+i,...a,...d}}async getSamples(e,t){const i=await this._fetchCapabilities(t?.signal);if(!i?.operations.supportsGetSamples)throw new r("imagery-layer:get-samples","getSamples operation is not supported on the input image service");e=s(e);const{raster:n}=this;return n&&null==e.raster&&(e.raster=n),ve(this.url,e,this._getRequestOptions(t))}async identify(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsIdentify)throw new r("imagery-layer:identify","identify operation is not supported on the input image service");e=s(e),this.version<10.91&&"extent"===e.geometry?.type&&(e.geometry=y.fromExtent(e.geometry));const i=this._processMultidimensionalIntersection(e.geometry,e.timeExtent,e.mosaicRule||this.mosaicRule);if(i.isOutSide)throw new r("imagery-layer:identify","the request cannot be fulfilled when falling outside of the multidimensional subset");e.timeExtent=i.timeExtent,e.mosaicRule=i.mosaicRule;const{raster:n,rasterFunction:a}=this;return a&&null==e.rasterFunction&&(e.rasterFunction=a),n&&null==e.raster&&(e.raster=n),we(this.url,e,this._getRequestOptions(t))}async imageToMap(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsImageToMap)throw new r("imagery-layer:image-to-map","imageToMap operation is not supported on the input image service");return be(Ge(this.parsedUrl),e,this._getRequestOptions(t))}async imageToMapMultiray(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsImageToMapMultiray)throw new r("imagery-layer:image-to-map-multiray","imageToMapMultiray operation is not supported on the input image service");return Se(Ge(this.parsedUrl),e,this._getRequestOptions(t))}async mapToImage(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsMapToImage)throw new r("imagery-layer:map-to-image","mapToImage operation is not supported on the input image service");return xe(Ge(this.parsedUrl),e,this._getRequestOptions(t))}async findImages(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsFindImages)throw new r("imagery-layer:find-images","findImages operation is not supported on the input image service");return _e(Ge(this.parsedUrl),e,this._getRequestOptions(t))}async getImageUrl(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsGetImageUrl)throw new r("imagery-layer:get-image-url","getImageUrl operation is not supported on the input image service");return Fe(Ge(this.parsedUrl),e,this._getRequestOptions(t))}createQuery(){return new Ve({outFields:["*"],returnGeometry:!0,where:this.definitionExpression||"1=1"})}async queryBoundary(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsQueryBoundary)throw new r("imagery-layer:query-boundary","queryBoundary operation is not supported on the input image service");return e=e??{outSpatialReference:this.spatialReference},De(Ge(this.parsedUrl),e,this._getRequestOptions(t))}async queryExtent(e,t){return({query:e,requestOptions:t}=await this._prepareForQuery(e,t)),Pe(this.url,e,t)}async queryRasters(e,t){({query:e,requestOptions:t}=await this._prepareForQuery(e,t));const i=await Ee(this.url,e,t),r=this.graphicOrigin;return i.features.forEach(e=>{e.layer=this,e.origin=r}),i}async queryObjectIds(e,t){return({query:e,requestOptions:t}=await this._prepareForQuery(e,t)),je(this.url,e,t)}async queryGPSInfo(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsQueryGPSInfo)throw new r("imagery-layer:query-gps-info","queryGPSInfo operation is not supported on the input image service");return e=e??{where:"1=1"},Oe(Ge(this.parsedUrl),e,this._getRequestOptions(t))}async queryRasterCount(e,t){return({query:e,requestOptions:t}=await this._prepareForQuery(e,t)),qe(this.url,e,t)}async queryVisibleRasters(e,t){if(!e)throw new r("imagery-layer: query-visible-rasters","missing query parameter");await this.load();const{pixelSize:i,returnDomainValues:s,returnTopmostRaster:n,showNoDataRecords:a}=t||{pixelSize:null,returnDomainValues:!1,returnTopmostRaster:!1,showNoDataRecords:!1};let o=!1,l=null,u=null;const p=$.servicePixelValue.toLowerCase(),m=this._rasterFunctionNamesIndex;if(null!=e.outFields&&(o=e.outFields.some(e=>!e.toLowerCase().startsWith(p)),this.version>=10.4)){const t=e.outFields.filter(e=>e.toLowerCase().startsWith(p)&&e.length>p.length).map(e=>{const t=e.slice(p.length+1);return[this._updateRenderingRulesFunctionName(t,m),t]});l=t.map(e=>new K({functionName:e[0]})),u=t.map(e=>e[1]);const{rasterFunction:i}=this;0===l.length?i?.functionName?(l.push(i),u.push(i.functionName)):l=null:i?.functionName&&!l.some(e=>e.functionName===i.functionName)&&(l.push(i),u.push(i.functionName))}const c=null==e.outSpatialReference||e.outSpatialReference.equals(this.spatialReference),{multidimensionalSubset:h}=this;let d=e.timeExtent||this.timeExtent;if(h){const{isOutside:t,intersection:i}=I(h,{geometry:e.geometry,timeExtent:e.timeExtent,multidimensionalDefinition:this.exportImageServiceParameters.mosaicRule?.multidimensionalDefinition});if(t)throw new r("imagery-layer:query-visible-rasters","the request cannot be fulfilled when falling outside of the multidimensional subset");null!=i?.timeExtent&&(d=i.timeExtent)}const f=this._combineMosaicRuleWithTimeExtent(this.exportImageServiceParameters.mosaicRule,d);let g=e.geometry;this.version<10.91&&"extent"===g?.type&&(g=y.fromExtent(g));const R=this._getQueryParams({geometry:g,timeExtent:d,mosaicRule:f,rasterFunction:this.version<10.4?this.rasterFunction:null,rasterFunctions:l,pixelSize:i,returnCatalogItems:o,returnGeometry:c,raster:this.raster,maxItemCount:n?1:null});delete R.f;const w=new Qe(R);try{await this._generateRasterInfo(this.rasterFunction);const i=await we(this.url,w,{signal:t?.signal,query:{...this.customParameters}}),r=e.outFields,n=null!=i.value&&i.value.toLowerCase().includes("nodata"),l=o&&!c&&i?.catalogItems?.features.length&&(a||!n),p=this.multidimensionalInfo&&"raster-dataset"===this.sourceType?v({rasterInfo:this.rasterInfo,multidimensionalDefinition:f?.multidimensionalDefinition,timeExtent:d,multidimensionalSubset:this.multidimensionalSubset}):null;if(!l)return this._processVisibleRastersResponse(i,{returnDomainValues:s,templateRRFunctionNames:u,showNoDataRecords:a,templateFields:r,effectiveMultidimensionalDefinition:p});const m=this.objectIdField||"ObjectId",h=i.catalogItems?.features??[],y=h.map(e=>e.attributes?.[m]),g=new Ve({objectIds:y,returnGeometry:!0,outSpatialReference:e.outSpatialReference,outFields:[m]}),R=await this.queryRasters(g);return R?.features?.length&&R.features.forEach(t=>{h.forEach(i=>{i.attributes[m]===t.attributes[m]&&t.geometry&&(i.geometry=t.geometry.clone(),null!=e.outSpatialReference&&(i.geometry.spatialReference=e.outSpatialReference))})}),this._processVisibleRastersResponse(i,{returnDomainValues:s,templateRRFunctionNames:u,showNoDataRecords:a,templateFields:r,effectiveMultidimensionalDefinition:p})}catch{throw new r("imagery-layer:query-visible-rasters","encountered error when querying visible rasters")}}async fetchVariableStatisticsHistograms(e,t){const r=i(Ge(this.parsedUrl)+"/statistics",{query:this._getQueryParams({variable:e}),signal:t}).then(e=>e.data?.statistics),s=i(Ge(this.parsedUrl)+"/histograms",{query:this._getQueryParams({variable:e}),signal:t}).then(e=>e.data?.histograms),n=await Promise.all([r,s]);return n[0]&&n[0].forEach(e=>{e.avg=e.mean,e.stddev=e.standardDeviation}),{statistics:n[0]||null,histograms:n[1]||null}}getMultidimensionalSubsetVariables(e){const t=e??this.serviceRasterInfo.multidimensionalInfo;return w(this.multidimensionalSubset,t)}async _fetchService(e){await this._fetchServiceInfo(e),this.rasterInfo||(this.rasterInfo=this.serviceRasterInfo);const t=this.sourceJSON,i=null!=this.serviceRasterInfo?Promise.resolve(this.serviceRasterInfo):Te(Ge(this.parsedUrl),t,{signal:e,query:this._getQueryParams()}).then(e=>(this._set("serviceRasterInfo",e),this._set("multidimensionalInfo",e.multidimensionalInfo),Me(e,t),e)),r=this._hasRasterFunction(this.rasterFunction)?this._generateRasterInfo(this.rasterFunction,{signal:e}):null,s=this._getRasterFunctionInfos();return Promise.all([i,r,s]).then(e=>{e[1]?this._set("rasterInfo",e[1]):this._set("rasterInfo",e[0]),e[2]&&this._set("rasterFunctionInfos",e[2]),this.internalRenderer&&!this._isSupportedRenderer(this.internalRenderer)&&(this._set("internalRenderer",null),n.getLogger(this).warn("ArcGISImageService","Switching to the default renderer. Renderer applied is not valid for this Imagery Layer")),this._set("internalRenderer",this._configRenderer(this.renderer)),this.addHandles([a(()=>this.rasterFunction,e=>{(this.renderer||this.symbolizer||this.popupEnabled&&this.popupTemplate)&&this._generateRasterInfo(e).then(e=>{e&&(this.rasterInfo=e)})})]);const{serviceRasterInfo:t}=this;null!=t.multidimensionalInfo&&this._updateMultidimensionalDefinition(t)})}_combineMosaicRuleWithTimeExtent(e,t){const i=this.timeInfo,{multidimensionalInfo:r}=this.serviceRasterInfo;if(null==e||null==r||null==t||null==i?.startField)return e;const{startField:s}=i,n=r.variables.some(e=>e.dimensions.some(e=>e.name===s))?s:"StdTime";if(e=e.clone(),"mosaic-dataset"===this.sourceType)return e.multidimensionalDefinition=e.multidimensionalDefinition?.filter(e=>e.dimensionName!==n),this._cleanupMultidimensionalDefinition(e);e.multidimensionalDefinition=e.multidimensionalDefinition||[];const a=e.multidimensionalDefinition.filter(e=>e.dimensionName===n),o=null!=t.start?t.start.getTime():null,l=null!=t.end?t.end.getTime():null,u=null==o||null==l||o===l,p=u?[o||l]:[[o,l]],m=this.version>=10.8;if(a.length)a.forEach(e=>{e.dimensionName===n&&(m?(e.dimensionName=null,e.isSlice=!1,e.values=[]):(e.isSlice=u,e.values=p))});else if(!m){const t=e.multidimensionalDefinition.filter(e=>null!=e.variableName&&null==e.dimensionName);t.length?t.forEach(e=>{e.dimensionName=n,e.isSlice=u,e.values=p}):e.multidimensionalDefinition.push(new O({variableName:"",dimensionName:n,isSlice:u,values:p}))}return this._cleanupMultidimensionalDefinition(e)}_cleanupMultidimensionalDefinition(e){return null==e?null:(e.multidimensionalDefinition&&(e.multidimensionalDefinition=e.multidimensionalDefinition.filter(e=>!(!e.variableName&&!e.dimensionName)),0===e.multidimensionalDefinition.length&&(e.multidimensionalDefinition=null)),"mosaic-dataset"!==this.sourceType&&null==e.multidimensionalDefinition?null:e)}async _prepareForQuery(e,t){if(!(await this._fetchCapabilities(t?.signal)).operations.supportsQuery)throw new r("imagery-layer:query-rasters","query operation is not supported on the input image service");const i=null!=e?m(Ve,e):this.createQuery();return t=this._getRequestOptions(t),this.raster&&(t.query={...t.query,raster:this.raster}),{query:i,requestOptions:t}}_isSupportedRenderer(e){const{rasterInfo:t,rasterFunction:i}=this;return"unique-value"===e.type&&this._hasRasterFunction(i)&&1===t?.bandCount&&["u8","s8"].includes(t.pixelType)||null!=t&&null!=e&&te(t).includes(e.type)}async _fetchCapabilities(e){return this.capabilities||await this._fetchServiceInfo(e),this.capabilities}async _fetchServiceInfo(e){let t=this.sourceJSON;if(!t){const{data:r,ssl:s}=await i(Ge(this.parsedUrl),{query:this._getQueryParams(),signal:e});t=r,this.sourceJSON=t,s&&(this.url=this.url.replace(/^http:/i,"https:"))}if(t.capabilities?.toLowerCase().split(",").map(e=>e.trim()).indexOf("tilesonly")>-1)throw new r("imagery-layer:fetch-service-info","use ImageryTileLayer to open tiles-only image services");this.read(t,{origin:"service",url:this.parsedUrl})}_isMosaicDataset(e){return e.serviceSourceType?"esriImageServiceSourceTypeMosaicDataset"===e.serviceSourceType:e.fields?.length>0}_isMosaicRuleSupported(e){if(!e)return!1;const t=this._isMosaicDataset(e),i=e.currentVersion>=10.71&&e.hasMultidimensions&&!(e.fields?.length>1);return t||i}_isVectorFieldResampleFunction(e){if(null==e)return!1;const{functionName:t,functionArguments:i}=e,r="resample"===t?.toLowerCase(),s=i?.ResampleType||i?.resampleType;return r&&(7===s||10===s)}_isPicture(){return!this.format||this.format.includes("jpg")||this.format.includes("png")}_configRenderer(e){const t=this._isPicture(),{rasterInfo:i}=this;if(!t&&!this.pixelFilter||this._isVectorDataSet()){const t=this.mosaicRule?.multidimensionalDefinition?.[0].variableName,r=ie({variableName:t,rasterFunctionName:this.rasterFunction?.functionName,presetRenderers:this.presetRenderers});if(!this.bandIds&&i.bandCount>=3){const e=r?.bandIds??ee(i);!e||3===i.bandCount&&0===e[0]&&1===e[1]&&2===e[2]||(this.bandIds=e)}e||(e=r?.renderer??Z(i,{bandIds:this.bandIds,variableName:this.rasterFunction?null:t}));const s=re(e.toJSON());this.symbolizer?(this.symbolizer.rendererJSON=s,this.symbolizer.rasterInfo=i):this.symbolizer=new se({rendererJSON:s,rasterInfo:i}),this.symbolizer.bind().success||(this.symbolizer=null)}return e}_clonePixelData(e){return null==e?e:{extent:e.extent&&e.extent.clone(),pixelBlock:null!=e.pixelBlock?e.pixelBlock.clone():null}}_getQueryParams(e){null!=e?.renderingRule&&"string"!=typeof e.renderingRule&&(e.renderingRule=this._getRenderingRuleString(e.renderingRule));const{raster:t,viewId:i}=this;return{raster:t,viewId:i,f:"json",...e,...this.customParameters}}_getRequestOptions(e){return{...e,query:{...e?.query,...this.customParameters}}}_decodePixelBlock(e,t,i){return this._rasterJobHandler?this._rasterJobHandler.decode({data:e,options:t}):S(e,t,i)}async _getRasterFunctionInfos(e){const t=this.sourceJSON.rasterFunctionInfos;if(this.loaded)return t;if(t&&this.version>=10.3){if(1===t.length&&"none"===t[0].name.toLowerCase())return t;const r=await i(Ge(this.parsedUrl)+"/rasterFunctionInfos",{query:this._getQueryParams(),signal:e});return r.data?.rasterFunctionInfos}return null}_canRequestImageElement(e){return!this.pixelFilter&&(!e||e.includes("png"))}async _requestArrayBuffer(e){const{imageProps:t,requestAsImageElement:s,returnImageBitmap:n,signal:a}=e;if(s&&this._canRequestImageElement(t.format)){const r=`${Ge(this.parsedUrl)}/exportImage`,{data:s}=await i(r,{responseType:n?"blob":"image",query:this._getQueryParams({f:"image",...this.refreshParameters,...e.imageServiceParameters}),signal:a});if(s instanceof Blob){return{imageBitmap:await N(s,r,a),params:t}}return{imageOrCanvasElement:s,params:t}}const o=this._initJobHandler(),l=i(Ge(this.parsedUrl)+"/exportImage",{responseType:"array-buffer",query:this._getQueryParams({f:"image",...e.imageServiceParameters}),signal:a}),u=(await Promise.all([l,o]))[0].data,p=t.format||"jpgpng";let m=p;if("bsq"!==m&&"bip"!==m&&(m=x(u)),!m)throw new r("imagery-layer:fetch-image","unsupported format signature "+String.fromCharCode.apply(null,new Uint8Array(u)));const c={signal:a},h=this._decodePixelBlock(u,{width:t.width,height:t.height,format:p,applyJpegMask:!0},c);return{pixelData:{pixelBlock:await h,extent:t.extent},params:t}}_generateRasterInfo(e,t){return this.generateRasterInfo(e,t).catch(()=>null)}_isValidCustomizedMosaicRule(e){return e&&JSON.stringify(e.toJSON())!==JSON.stringify(this.defaultMosaicRule?.toJSON())}_updateMultidimensionalDefinition(e){if(this._isValidCustomizedMosaicRule(this.mosaicRule))return;let t=b(e,{multidimensionalSubset:this.multidimensionalSubset});if(null!=t&&t.length>0){this.mosaicRule=this.mosaicRule||new P;const e=this.mosaicRule.multidimensionalDefinition;!this.sourceJSON.defaultVariableName&&this.rasterFunction&&"none"!==this.rasterFunction.functionName?.toLowerCase()&&t.forEach(e=>e.variableName=""),t=t.filter(({variableName:e,dimensionName:t})=>e&&"*"!==e||t),!e?.length&&t.length&&(this.mosaicRule.multidimensionalDefinition=t)}}_processVisibleRastersResponse(e,i){i=i||{};const r=e.value,{templateRRFunctionNames:s,showNoDataRecords:n,returnDomainValues:a,templateFields:o}=i,l=e.processedValues;let u=e.catalogItems?.features,p=e.properties?.Values?.map(e=>e.replaceAll(/ /gi,", "))||[];const m=this.objectIdField||"ObjectId",c="string"==typeof r&&r.toLowerCase().includes("nodata"),h=[];if(r&&!u&&(!c||n)){const e={};e[m]=0;p=[r],u=[new t({geometry:this.fullExtent,attributes:e})],this.multidimensionalInfo&&"raster-dataset"===this.sourceType&&W(this.rasterFields,e,i.effectiveMultidimensionalDefinition)}if(!u)return[];this._updateResponseFieldNames(u,o),c&&!n&&(u=[]);const{itemPixelValue:d,servicePixelValue:f}=$,y=this.rasterFields.some(e=>e.name===d),g=this.graphicOrigin;for(let t=0;t<u.length;t++){const e=u[t];if(null!=r){const i=p[t],a=this.rasterFunction&&l&&l.length>0&&s&&s.length>0&&s.includes(this.rasterFunction.functionName)?l[s.indexOf(this.rasterFunction.functionName)]:r;if("nodata"===i.toLowerCase()&&!n)continue;y&&(e.attributes[d]=i),e.attributes[f]=a,this._updateFeatureWithMagDirValues(e,i);const o=this.fields&&this.fields.length>0;let u=this.rasterFunction&&null!=this.serviceRasterInfo.attributeTable?o?i:r:a;this.rasterFunction||(u=o?i:r),this._updateFeatureWithRasterAttributeTableValues(e,u)}if(e.sourceLayer=e.layer=this,e.origin=g,a&&this._updateFeatureWithDomainValues(e),s&&l&&s.length===l.length)for(let t=0;t<s.length;t++){const i=`${$.servicePixelValue}.${s[t]}`;e.attributes[i]=l[t]}h.push(u[t])}return h}_processMultidimensionalIntersection(e,t,i){const{multidimensionalSubset:r}=this;if(!r)return{isOutSide:!1,timeExtent:t,mosaicRule:i=this._combineMosaicRuleWithTimeExtent(i,t)};if(r){const{isOutside:i,intersection:s}=I(r,{geometry:e,timeExtent:t});if(i)return{isOutSide:!0,timeExtent:null,mosaicRule:null};null!=s?.timeExtent&&(t=s.timeExtent)}if(i=this._combineMosaicRuleWithTimeExtent(i,t),i?.multidimensionalDefinition){const{isOutside:e}=I(r,{multidimensionalDefinition:i.multidimensionalDefinition});if(e)return{isOutSide:!0,timeExtent:null,mosaicRule:null}}return{isOutSide:!1,timeExtent:t,mosaicRule:i}}_updateFeatureWithRasterAttributeTableValues(e,t){const i=this.rasterInfo.attributeTable||this.serviceRasterInfo.attributeTable;if(null==i)return;const{features:r,fields:s}=i,n=s.map(e=>e.name).find(e=>"value"===e.toLowerCase());if(!n)return;const a=r.filter(e=>e.attributes[n]===(null!=t?parseInt(t,10):null));a&&a[0]&&s.forEach(t=>{const i=X+t.name;e.attributes[i]=a[0].attributes[t.name]})}_updateFeatureWithMagDirValues(e,t){if(!this._isVectorDataSet())return;const i=t.split(/,\s*/).map(e=>parseFloat(e)),r=i.map(e=>[e]),s=i.map(e=>({minValue:e,maxValue:e,noDataValue:null})),n=new E({height:1,width:1,pixelType:"f32",pixels:r,statistics:s});null!=this.pixelFilter&&this.pixelFilter({pixelBlock:n,extent:new f(0,0,0,0,this.spatialReference)});const a="esriImageServiceDataTypeVector-MagDir"===this.serviceDataType?[n.pixels[0][0],n.pixels[1][0]]:_([n.pixels[0][0],n.pixels[1][0]]);e.attributes[$.magnitude]=a[0],e.attributes[$.direction]=a[1]}_updateFeatureWithDomainValues(e){const t=this.fields&&this.fields.filter(e=>"coded-value"===e.domain?.type);null!=t&&t.forEach(t=>{const i=e.attributes[t.name];if(null!=i){const r=t.domain.codedValues.find(e=>e.code===i);r&&(e.attributes[t.name]=r.name)}})}_updateResponseFieldNames(e,t){if(!t||t.length<1)return;const i=this.fieldsIndex;null!=i&&e.forEach(e=>{if(e?.attributes)for(const r of t){const t=i.get(r)?.name;t&&t!==r&&(e.attributes[r]=e.attributes[t],delete e.attributes[t])}})}_getRenderingRuleString(e){if(e){let t=e.toJSON();return t=t.rasterFunctionDefinition??t,(t.thumbnail||t.thumbnailEx)&&(t.thumbnail=t.thumbnailEx=null),JSON.stringify(t)}return null}_hasRasterFunction(e){return null!=e?.functionName&&"none"!==e.functionName.toLowerCase()}_updateRenderingRulesFunctionName(e,t){if(!e||e.length<1)return;if("Raw"===e)return e.replace("Raw","None");const i=e.toLowerCase().replaceAll(/ /gi,"_");return t.has(i)?t.get(i):e}_isRFTJson(e){return e?.name&&e.arguments&&e.function&&e.hasOwnProperty("functionType")}_isVectorDataSet(){return"esriImageServiceDataTypeVector-UV"===this.serviceDataType||"esriImageServiceDataTypeVector-MagDir"===this.serviceDataType}_applyMosaicAndRenderingRules(e){const{raster:t,mosaicRule:i,rasterFunction:r}=this;r&&null==e.rasterFunction&&(e.rasterFunction=r),i&&null==e.mosaicRule&&(e.mosaicRule=i),t&&null==e.raster&&(e.raster=t)}async _updateCurrentRasterInfo(e){if(this.renderer||this.symbolizer){const t=await this._generateRasterInfo(this.rasterFunction,{signal:e});t&&(this.rasterInfo=t)}}_applyMosaicRule(e){const{raster:t,mosaicRule:i}=this;i&&null==e.mosaicRule&&(e.mosaicRule=i),t&&null==e.raster&&(e.raster=t)}_readCapabilities(e){const t=e.capabilities?e.capabilities.toLowerCase().split(",").map(e=>e.trim()):["image","catalog"],{currentVersion:i,maxRecordCount:r}=e,s=t.includes("image"),n="esriImageServiceDataTypeElevation"===e.serviceDataType,a=!(!e.spatialReference&&!e.extent?.spatialReference),o=t.includes("edit"),l=t.includes("mensuration")&&a,u=null==e.mensurationCapabilities?[]:e.mensurationCapabilities.toLowerCase().split(",").map(e=>e.trim()),p=l&&u.includes("basic"),m=this._isMosaicDataset(e)&&t.includes("catalog"),c=t.includes("download"),h=i>=10.7&&n||i>=11.4&&(n||l&&u.includes("3d")),d=m&&e.fields&&e.fields.length>0,f=d&&e.supportsAdvancedQueries?e.advancedQueryCapabilities:void 0;return{data:{supportsAttachment:!1},operations:{supportsComputeHistograms:s,supportsExportImage:s,supportsIdentify:s,supportsImageToMap:i>=11.2&&m,supportsImageToMapMultiray:i>=11.2&&m,supportsMapToImage:i>=11.2&&m,supportsFindImages:i>=11.2&&m,supportsGetImageUrl:i>=11.3&&c,supportsMeasure:l,supportsMeasureFromImage:i>=11.2,supportsDownload:c,supportsQuery:d,supportsGetSamples:i>=10.2&&s,supportsProject:i>=10.3&&s,supportsComputeStatisticsHistograms:i>=10.4&&s,supportsQueryBoundary:i>=10.6&&s,supportsCalculateVolume:h,supportsComputePixelLocation:i>=10.7&&m,supportsComputeAngles:i>=10.91,supportsQueryGPSInfo:i>=11.2&&m,supportsAdd:o,supportsDelete:o,supportsEditing:o,supportsUpdate:o,supportsCalculate:!1,supportsTruncate:!1,supportsValidateSql:!1,supportsChangeTracking:!1,supportsQueryAttachments:!1,supportsResizeAttachments:!1,supportsSync:!1,supportsExceedsLimitStatistics:!1,supportsQueryAnalytics:!1,supportsQueryBins:!1,supportsQueryPivot:!1,supportsQueryTopFeatures:!1,supportsAsyncConvert3D:!1},query:{maxRecordCount:r,maxRecordCountFactor:void 0,maxUniqueIDCount:void 0,relativeTimeBinWindow:void 0,supportsStatistics:!!f?.supportsStatistics,supportsOrderBy:!!f?.supportsOrderBy,supportsDistinct:!!f?.supportsDistinct,supportsPagination:!!f?.supportsPagination,supportsPaginationOnAggregatedQueries:!!f?.supportsPaginationOnAggregatedQueries,supportsStandardizedQueriesOnly:!!f?.useStandardizedQueries,supportsPercentileStatistics:!!f?.supportsPercentileStatistics,supportsCentroid:!!f?.supportsReturningGeometryCentroid,supportsCentroidOnDegeneratedQuantizedGeometry:!1,supportsCurrentUser:!1,supportsDegeneratedQuantizedGeometry:!1,supportsDistance:!!f?.supportsQueryWithDistance,supportsExtent:!!f?.supportsReturningQueryExtent,supportsGeometryProperties:!!f?.supportsReturningGeometryProperties,supportsHavingClause:!!f?.supportsHavingClause,supportsQuantization:!1,supportsQuantizationEditMode:!1,supportsQueryGeometry:!1,supportsResultType:!1,supportsReturnMesh:!1,supportsMaxRecordCountFactor:!1,supportsSqlExpression:f?.supportsSqlExpression??!!f,supportsTopFeaturesQuery:!1,supportsQueryByAnonymous:!1,supportsQueryByOthers:!1,supportsHistoricMoment:!1,supportsFormatPBF:!1,supportsFormatPBFWithCurves:!1,supportsDisjointSpatialRelationship:!1,supportsCacheHint:!1,supportsSpatialAggregationStatistics:!1,supportedSpatialAggregationStatistics:{envelope:!1,centroid:!1,convexHull:!1},supportsDefaultSpatialReference:!!f?.supportsDefaultSR,supportsFullTextSearch:!1,supportsCompactGeometry:!1,standardMaxRecordCount:void 0,standardMaxRecordCountNoGeometry:void 0,tileMaxRecordCount:void 0,supportsTrueCurve:!1},mensuration:{supportsDistanceAndAngle:p,supportsAreaAndPerimeter:p,supportsPointOrCentroid:p,supportsHeightFromBaseAndTop:l&&u.includes("base-top height"),supportsHeightFromBaseAndTopShadow:l&&u.includes("base-top shadow height"),supportsHeightFromTopAndTopShadow:l&&u.includes("top-top shadow height"),supports3D:l&&u.includes("3d")}}}};function Ge(e){return e?.path??""}return e([l({clonable:!1})],He.prototype,"_functionRasterInfos",void 0),e([l({readOnly:!0})],He.prototype,"_serviceSupportsMosaicRule",void 0),e([Je("_serviceSupportsMosaicRule",["currentVersion","fields"])],He.prototype,"readServiceSupportsMosaicRule",null),e([l({readOnly:!0})],He.prototype,"_rasterFunctionNamesIndex",null),e([l()],He.prototype,"adjustAspectRatio",void 0),e([l({type:[p],json:{write:!0}})],He.prototype,"bandIds",void 0),e([Je("bandIds")],He.prototype,"readBandIds",null),e([l({readOnly:!0,json:{read:!1}})],He.prototype,"capabilities",void 0),e([Je("service","capabilities",["capabilities","currentVersion","serviceDataType"])],He.prototype,"readCapabilities",null),e([l({type:Number})],He.prototype,"compressionQuality",void 0),e([Ue("compressionQuality")],He.prototype,"writeCompressionQuality",null),e([l({type:Number})],He.prototype,"compressionTolerance",void 0),e([Ue("compressionTolerance")],He.prototype,"writeCompressionTolerance",null),e([l({json:{read:{source:"copyrightText"}}})],He.prototype,"copyright",void 0),e([l({readOnly:!0})],He.prototype,"defaultMosaicRule",void 0),e([Je("defaultMosaicRule",["defaultMosaicMethod"])],He.prototype,"readDefaultMosaicRule",null),e([l({type:String,json:{name:"layerDefinition.definitionExpression",write:{enabled:!0,allowNull:!0}}})],He.prototype,"definitionExpression",void 0),e([l({readOnly:!0,constructOnly:!0})],He.prototype,"exportImageServiceParameters",void 0),e([l()],He.prototype,"rasterInfo",void 0),e([l({readOnly:!0,type:[C]})],He.prototype,"fields",void 0),e([l({readOnly:!0})],He.prototype,"fieldsIndex",null),e([l({type:["png","png8","png24","png32","jpg","bmp","gif","jpgpng","lerc","tiff","bip","bsq"],json:{write:!0}})],He.prototype,"format",null),e([Je("service","format",["serviceDataType"])],He.prototype,"readFormat",null),e([l({type:f})],He.prototype,"fullExtent",void 0),e([l({readOnly:!0})],He.prototype,"hasMultidimensions",void 0),e([l({json:{read:{source:"maxImageHeight"}}})],He.prototype,"imageMaxHeight",void 0),e([l({json:{read:{source:"maxImageWidth"}}})],He.prototype,"imageMaxWidth",void 0),e([l({type:String,json:{type:A.jsonValues,read:A.read,write:A.write}})],He.prototype,"interpolation",void 0),e([l()],He.prototype,"minScale",void 0),e([Je("service","minScale")],He.prototype,"readMinScale",null),e([l()],He.prototype,"maxScale",void 0),e([Je("service","maxScale")],He.prototype,"readMaxScale",null),e([l({type:P})],He.prototype,"mosaicRule",null),e([Je("mosaicRule",["mosaicRule","defaultMosaicMethod"])],He.prototype,"readMosaicRule",null),e([Ue("mosaicRule")],He.prototype,"writeMosaicRule",null),e([l()],He.prototype,"multidimensionalInfo",void 0),e([l({type:j,json:{write:!0}})],He.prototype,"multidimensionalSubset",void 0),e([l({json:{type:p}})],He.prototype,"noData",void 0),e([Ue("noData")],He.prototype,"writeNoData",null),e([l({type:String,json:{type:Q.jsonValues,read:Q.read,write:Q.write}})],He.prototype,"noDataInterpretation",void 0),e([l({type:String,readOnly:!0,json:{read:{source:["fields"]}}})],He.prototype,"objectIdField",void 0),e([Je("objectIdField")],He.prototype,"readObjectIdField",null),e([l({readOnly:!0})],He.prototype,"geometryType",void 0),e([l({})],He.prototype,"typeIdField",void 0),e([l({})],He.prototype,"types",void 0),e([l({readOnly:!0})],He.prototype,"parsedUrl",null),e([l({type:Function})],He.prototype,"pixelFilter",void 0),e([l()],He.prototype,"raster",void 0),e([l({readOnly:!0})],He.prototype,"sourceType",void 0),e([Je("sourceType",["serviceSourceType","fields"])],He.prototype,"readSourceType",null),e([l()],He.prototype,"viewId",void 0),e([l({types:ne})],He.prototype,"renderer",null),e([l({types:ne,json:{name:"layerDefinition.drawingInfo.renderer",origins:{"web-scene":{types:ae,name:"layerDefinition.drawingInfo.renderer",write:{overridePolicy:e=>({enabled:e&&"vector-field"!==e.type})}}}}})],He.prototype,"internalRenderer",null),e([Je("internalRenderer")],He.prototype,"readRenderer",null),e([Ue("internalRenderer")],He.prototype,"writeRenderer",null),e([l({clonable:!1})],He.prototype,"symbolizer",void 0),e([l(F)],He.prototype,"opacity",void 0),e([l({readOnly:!0})],He.prototype,"rasterFields",null),e([l({constructOnly:!0})],He.prototype,"rasterFunctionInfos",void 0),e([l({type:K,json:{name:"renderingRule"}})],He.prototype,"rasterFunction",null),e([Je("rasterFunction",["renderingRule","rasterFunctionInfos"])],He.prototype,"readRasterFunction",null),e([l({readOnly:!0})],He.prototype,"serviceDataType",void 0),e([l({readOnly:!0,type:g})],He.prototype,"spatialReference",void 0),e([Je("spatialReference",["spatialReference","extent"])],He.prototype,"readSpatialReference",null),e([l({type:V.apiValues,json:{read:V.read,type:V.jsonValues}})],He.prototype,"pixelType",void 0),e([Ue("pixelType")],He.prototype,"writePixelType",null),e([l({constructOnly:!0,type:Y})],He.prototype,"serviceRasterInfo",void 0),e([l()],He.prototype,"sourceJSON",void 0),e([l(D)],He.prototype,"url",void 0),e([l({readOnly:!0})],He.prototype,"version",void 0),e([Je("version",["currentVersion","fields","timeInfo"])],He.prototype,"readVersion",null),He=e([u("esri.layers.mixins.ArcGISImageService")],He),He};export{He as ArcGISImageService};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import t from"../../../request.js";import i from"../../../core/Error.js";import{JSONSupport as o}from"../../../core/JSONSupport.js";import r from"../../../core/Logger.js";import{debounce as n,onAbort as s}from"../../../core/promiseUtils.js";import{QueueProcessor as l}from"../../../core/QueueProcessor.js";import{property as a,subclass as c}from"../../../core/accessorSupport/decorators.js";import{ensureClass as f}from"../../../core/accessorSupport/ensureType.js";import u from"../../../geometry/Extent.js";import m from"../../../geometry/Point.js";import h from"../../../geometry/SpatialReference.js";import{isFunctionRaster as p,getPixelSpaceCoverage as d}from"./datasetUtils.js";import{isMultiSliceOrRangeDefinition as x,getSliceIndex as y,createSlices as g,getSliceIds as I}from"./multidimensionalUtils.js";import{clearRegisteredIds as R,getRasterId as w,getBlock as S,putBlock as k,deleteBlock as b,decreaseRefCount as T}from"./RawBlockCache.js";import{convertNoDataToMask as v}from"../formats/pixelRangeUtils.js";import{decode as P}from"../formats/RasterCodec.js";import{mosaic as B,approximateTransform as _,getLocalArithmeticNorthRotations as M,compositeBands as C}from"../functions/pixelUtils.js";import{getWorldWidth as W,load as H,projectPoint as z,snapPyramid as L,shiftExtent as j,getWorldWrapCount as E,projectExtent as D,getProjectionOffsetGrid as O,getRasterDatasetAlignmentInfo as A,projectResolution as q}from"../functions/rasterProjectionHelper.js";import{convertToLocalDirections as F,uvComponentToVector as G}from"../functions/vectorFieldUtils.js";import{sanitizeUrl as J}from"../../support/arcgisLayerUrl.js";import{url as N}from"../../support/commonProperties.js";import V from"../../support/DimensionalDefinition.js";import U from"../../support/LOD.js";import Q from"../../support/RasterStorageInfo.js";import $ from"../../support/TileInfo.js";const X=8,K=256;let Y=0,Z=class extends o{constructor(){super(...arguments),this._tileFetchQueue=new l({concurrency:32,process:(e,t)=>this.fetchRawTile(e.pyramidLevel,e.row,e.col,{...e.options,signal:t})}),this.datasetName=null,this.datasetFormat=null,this.hasUniqueSourceStorageInfo=!0,this.rasterInfo=null,this.ioConfig={sampling:"closest"},this.rawBlockRegistryIds=[],this.refresh=n(async e=>{await this._openPromise;const t=await this._refresh(e);return t.dataChanged&&R(this.rasterId,this.rawBlockRegistryIds),t})}normalizeCtorArgs(e){return e?.ioConfig&&(e={...e,ioConfig:{resolution:null,bandIds:null,sampling:"closest",tileInfo:$.create(),...e.ioConfig}}),e}get _isGlobalWrappableSource(){const{rasterInfo:e}=this,t=W(e.spatialReference);return null!=t&&e.extent.width>=t/2}get _hasNoneOrGCSShiftTransform(){const{transform:e}=this.rasterInfo;return null==e||"gcs-shift"===e.type}set rasterJobHandler(e){this._set("rasterJobHandler",e),p(this)&&this.primaryRasters?.rasters?.forEach(t=>t.rasterJobHandler=e)}get rasterId(){return this.url||"rasterId-"+Y++}set url(e){this._set("url",J(e,r.getLogger(this)))}async open(e){return this._openPromise??=H().then(()=>this._open(e)),this._openPromise}async fetchTile(e,t,o,r={}){const n=r.tileInfo||this.rasterInfo.storageInfo.tileInfo,s=this.getTileExtentFromTileInfo(e,t,o,n);if(!s)throw new i("imagery-tile:out-of-bounds","Level for fetch tile out of range");return r={noClip:!0,...r},this.fetchPixels(s,n.size[0],n.size[1],r)}async identify(e,t={}){e=f(m,e).clone().normalize();const{multidimensionalDefinition:i,timeExtent:o}=t,{rasterInfo:r}=this,{hasMultidimensionalTranspose:n,multidimensionalInfo:s}=r;let{transposedVariableName:l}=t;const a=null!=s&&n&&(null!=o||x(i));if(a&&!l){l=null!=i&&i.length>0?i[0].variableName??void 0:s.variables[0].name,t={...t,transposedVariableName:l}}t=this._getRequestOptionsWithSliceId(t);const{spatialReference:c,extent:h}=r,{datumTransformation:d}=t;let y=z(e,c,d);if(!h.intersects(y))return{location:y,value:null};if(null!=r.transform){const e=r.transform.inverseTransform(y);if(!r.nativeExtent.intersects(e))return{location:e,value:null};y=e}let g=0;const I=null!=l&&null!=s&&r.hasMultidimensionalTranspose;if(p(this)){const e=this.primaryRasters.rasters[0];if(I)return e.identify(y,t);const{pixelSize:o}=r,n=3,s=o.x*n/2,l=o.y*n/2,a=new u({xmin:y.x-s,xmax:y.x+s,ymin:y.y-l,ymax:y.y+l,spatialReference:c}),f={interpolation:"nearest",multidimensionalDefinition:i,sliceId:t.sliceId,bandIds:t.bandIds},{pixelBlock:m}=await e.fetchPixels(a,n,n,f),{pixelBlock:h}=await this.fetchPixels(a,n,n,f);if(null==m)return{location:y,value:null};const p=Math.floor(n*n*.5),d=!m.mask||m.mask[p]?m.pixels.map(e=>e[p]):null;let x;return null!=h&&(x=!h.mask||h.mask[p]?h.pixels.map(e=>e[p]):void 0),{location:y,value:d,processedValue:x,pyramidLevel:0}}if(!I)if(t.srcResolution){g=L(t.srcResolution,r,this.ioConfig.sampling).pyramidLevel}else if(g=await this.computeBestPyramidLevelForLocation(e,t),null==g)return{location:y,value:null};const R=this.identifyPixelLocation(y,g,null,I);if(null===R)return{location:y,value:null};const{row:w,col:S,rowOffset:k,colOffset:b,blockWidth:T}=R,v=await this._fetchRawTile(g,w,S,t);if(!v?.pixels?.length)return{location:y,value:null};const P=k*T+b;return this._processIdentifyResult(v,{srcLocation:y,position:P,pyramidLevel:g,useTransposedTile:!!I,requestSomeSlices:a,identifyOptions:t})}async fetchPixels(e,t,i,o={}){e=j(e),o=this._getRequestOptionsWithSliceId(o);const{_hasNoneOrGCSShiftTransform:r}=this;if(o.requestRawData&&r)return this._fetchPixels(e,t,i,o);const n=W(e.spatialReference),s=E(e);if(null==n||0===s||1===s&&this._isGlobalWrappableSource&&r)return this._fetchPixels(e,t,i,o);if(s>=3)return{extent:e,pixelBlock:null};const l=[],{xmin:a,xmax:c}=e,f=Math.round(n/(c-a)*t),m=f-Math.round((n/2-a)/(c-a)*t);let h=0;const p=[];for(let g=0;g<=s;g++){const r=new u({xmin:0===g?a:-n/2,xmax:g===s?c-n*g:n/2,ymin:e.ymin,ymax:e.ymax,spatialReference:e.spatialReference}),d=0===g?f-m:g===s?t-h:f;h+=d,p.push(d);const x=o.disableWrapAround&&g>0?null:this._fetchPixels(r,d,i,o);l.push(x)}const d=(await Promise.all(l)).map(e=>e?.pixelBlock);let x=null;const y={width:t,height:i};if(this.rasterJobHandler){x=(await this.rasterJobHandler.mosaicAndTransform({srcPixelBlocks:d,srcMosaicSize:y,destDimension:null,coefs:null,sampleSpacing:null,interpolation:"nearest",alignmentInfo:null,blockWidths:p},o)).pixelBlock}else x=B(d,y,{blockWidths:p});return{extent:e,srcExtent:D(e,this.rasterInfo.spatialReference,o.datumTransformation),pixelBlock:x}}async fetchRawPixels(e,t,i,o={}){t={x:Math.floor(t.x),y:Math.floor(t.y)};const r=await this._fetchRawTiles(e,t,i,o),{nativeExtent:n,nativePixelSize:s,storageInfo:l}=this.rasterInfo,a=2**e,c=s.x*a,f=s.y*a,m=new u({xmin:n.xmin+c*t.x,xmax:n.xmin+c*(t.x+i.width-1),ymin:n.ymax-f*(t.y+i.height-1),ymax:n.ymax-f*t.y,spatialReference:n.spatialReference});if(!r)return{extent:m,srcExtent:m,pixelBlock:null};const{pixelBlocks:h,mosaicSize:p}=r;if(1===h.length&&null!=h[0]&&h[0].width===i.width&&h[0].height===i.height)return{extent:m,srcExtent:m,pixelBlock:r.pixelBlocks[0]};const d=e>0?l.pyramidBlockWidth:l.blockWidth,x=e>0?l.pyramidBlockHeight:l.blockHeight,y={x:t.x%d,y:t.y%x};let g;if(this.rasterJobHandler){g=(await this.rasterJobHandler.mosaicAndTransform({srcPixelBlocks:h,srcMosaicSize:p,destDimension:i,clipOffset:y,clipSize:i,coefs:null,sampleSpacing:null,interpolation:o.interpolation,alignmentInfo:null,blockWidths:null},o)).pixelBlock}else g=B(h,p,{clipOffset:y,clipSize:i});return{extent:m,srcExtent:m,pixelBlock:g}}fetchRawTile(e,t,o,r){throw new i("BaseRaster:read-not-implemented","fetchRawTile() is not implemented")}computeExtent(e){return D(this.rasterInfo.extent,e)}decodePixelBlock(e,t){return!this.rasterJobHandler||t.useCanvas?P(e,t):this.rasterJobHandler.decode({data:e,options:t})}async request(e,i,o=0){const{customFetchParameters:r}=this.ioConfig,{range:n,query:s,headers:l}=i;o=o??i.retryCount??this.ioConfig.retryCount;const a=n?{Range:`bytes=${n.from}-${n.to}`}:null;try{return await t(e,{...i,query:{...s,...r},headers:{...l,...a}})}catch(c){if(o>0)return o--,this.request(e,i,o);throw c}}getSliceIndex(e){const{multidimensionalInfo:t}=this.rasterInfo;return null==t||null==e||0===e.length?null:y(e,t)}getTileExtentFromTileInfo(e,t,i,o){const r=o.lodAt(e);return r?this.getTileExtent({x:r.resolution,y:r.resolution},t,i,o.origin,o.spatialReference,o.size):null}updateTileInfo(){const{storageInfo:e,spatialReference:t,extent:i,pixelSize:o}=this.rasterInfo,{pyramidResolutions:r}=e;if(!e.tileInfo){const n=[],s=e.maximumPyramidLevel||0;let l=(o.x+o.y)/2,a=1/.0254*96*l;for(let e=0;e<=s&&(n.unshift(new U({level:s-e,resolution:l,scale:a})),e!==s);e++)if(r){const t=(r[e].x+r[e].y)/2;a*=t/l,l=t}else l*=2,a*=2;const c=new m({x:i.xmin,y:i.ymax,spatialReference:t});e.tileInfo=new $({origin:c,size:[e.blockWidth,e.blockHeight],spatialReference:t,lods:n}),e.isVirtualTileInfo=!0}}createRemoteDatasetStorageInfo(e,t=512,i=512,o){const{width:r,height:n,nativeExtent:s,pixelSize:l,spatialReference:a}=e,c=new m({x:s.xmin,y:s.ymax,spatialReference:a});null==o&&(o=Math.max(0,Math.round(Math.log(Math.max(r,n))/Math.LN2-8)));const f=this.computeBlockBoundary(s,512,512,{x:s.xmin,y:s.ymax},[l],o);e.storageInfo=new Q({blockWidth:t,blockHeight:i,pyramidBlockWidth:t,pyramidBlockHeight:i,origin:c,firstPyramidLevel:1,maximumPyramidLevel:o,blockBoundary:f})}async computeBestPyramidLevelForLocation(e,t={}){return 0}computeBlockBoundary(e,t,i,o,r,n=0,s=2){if(1===r.length&&n>0){r=[...r];let{x:e,y:t}=r[0];for(let i=0;i<n;i++)e*=s,t*=s,r.push({x:e,y:t})}const l=[],{x:a,y:c}=o;for(let f=0;f<r.length;f++){const{x:o,y:n}=r[f];l.push({minCol:Math.floor((e.xmin-a+.1*o)/t/o),maxCol:Math.floor((e.xmax-a-.1*o)/t/o),minRow:Math.floor((c-e.ymax+.1*n)/i/n),maxRow:Math.floor((c-e.ymin-.1*n)/i/n)})}return l}getPyramidPixelSize(e){const{nativePixelSize:t}=this.rasterInfo,{pyramidResolutions:i,pyramidScalingFactor:o}=this.rasterInfo.storageInfo;if(0===e)return t;if(null!=i&&i.length)return i[e-1];const r=o**e;return{x:t.x*r,y:t.y*r}}identifyPixelLocation(e,t,i,o){const{spatialReference:r,nativeExtent:n,storageInfo:s}=this.rasterInfo,{maximumPyramidLevel:l,origin:a,transposeInfo:c}=s,f=o&&null!=c?c.tileSize[0]:s.blockWidth,u=o&&null!=c?c.tileSize[1]:s.blockHeight,m=z(e,r,i);if(!n.intersects(m))return null;if(t<0||t>l)return null;const h=this.getPyramidPixelSize(t),{x:p,y:d}=h,x=(a.y-m.y)/d/u,y=(m.x-a.x)/p/f,g=Math.min(u-1,Math.floor((x-Math.floor(x))*u)),I=Math.min(f-1,Math.floor((y-Math.floor(y))*f));return{pyramidLevel:t,row:Math.floor(x),col:Math.floor(y),rowOffset:g,colOffset:I,blockWidth:f,srcLocation:m}}getTileExtent(e,t,i,o,r,n){const[s,l]=n,a=o.x+i*s*e.x,c=a+s*e.x,f=o.y-t*l*e.y,m=f-l*e.y;return new u({xmin:a,xmax:c,ymin:m,ymax:f,spatialReference:r})}getBlockWidthHeight(e){return{blockWidth:e>0?this.rasterInfo.storageInfo.pyramidBlockWidth:this.rasterInfo.storageInfo.blockWidth,blockHeight:e>0?this.rasterInfo.storageInfo.pyramidBlockHeight:this.rasterInfo.storageInfo.blockHeight}}isBlockOutside(e,t,i){const o=this.rasterInfo.storageInfo.blockBoundary[e];return!o||o.maxRow<t||o.maxCol<i||o.minRow>t||o.minCol>i}updateImageSpaceRasterInfo(e){const{pixelSize:t}=e,{width:i,height:o}=e,r=h.WebMercator;e.spatialReference=r,e.extent=e.nativeExtent=new u({xmin:-.5,ymax:.5,xmax:i-.5,ymin:.5-o,spatialReference:r}),e.isPseudoSpatialReference=!0,e.transform=null,e.pixelSize=new m({x:1,y:1,spatialReference:r});const{extent:n,storageInfo:s}=e;if(s){s.origin=new m({x:n.xmin,y:n.ymax,spatialReference:r});const{pyramidResolutions:i,tileInfo:o}=s;if(i&&i.forEach(e=>{e.x/=t.x,e.y/=t.y}),o){o.origin=s.origin;const t=(e.nativePixelSize.x+e.nativePixelSize.y)/2;o.lods.forEach((e,i)=>{e.resolution=t*2**i,e.scale=96*e.resolution/.0254})}}}async _refresh(e){return{dataChanged:!0}}async _fetchPixels(e,t,i,o={}){let r=E(e);if(r>=2)return{extent:e,pixelBlock:null};const n=this._getSourceDataInfo(e,t,i,o),{pyramidLevel:s,srcResolution:l,srcWidth:a,srcHeight:c,ul:f}=n;let{srcExtent:u}=n;if(0===a||0===c)return{extent:e,srcExtent:u,pixelBlock:null};const{rasterInfo:h}=this,p=h.transform,d="gcs-shift"===p?.type,x=null!=W(e.spatialReference);!d&&x||(r=E(u,d));const y=await this._fetchRawTiles(s,f,{width:a,height:c,wrapCount:r},o);if(!y)return{extent:e,srcExtent:u,pixelBlock:null};u=y.extent;const g=h.storageInfo,I=s>0?g.pyramidBlockWidth:g.blockWidth,R=s>0?g.pyramidBlockHeight:g.blockHeight;let{x:w,y:S}=h.pixelSize;if(s>0){const{pyramidResolutions:e,pyramidScalingFactor:t}=g;if(null!=e&&e[s-1])({x:w,y:S}=e[s-1]);else{const e=t**s;w*=e,S*=e}}const k=h.spatialReference,b=new m({x:w,y:S,spatialReference:k}),T=I===a&&R===c&&f.x%I===0&&f.y%R===0,v=new m({x:(e.xmax-e.xmin)/t,y:(e.ymax-e.ymin)/i,spatialReference:e.spatialReference}),P=!e.spatialReference.equals(k),C=k.isGeographic?1e-9:1e-4,{datumTransformation:z}=o;if(!P&&T&&1===y.pixelBlocks.length&&I===t&&R===i&&ee(l,v,C))return{extent:e,srcExtent:u,srcTilePixelSize:b,pixelBlock:y.pixelBlocks[0]};const L=x&&null!=W(u.spatialReference)&&this._hasNoneOrGCSShiftTransform,j=o.requestProjectedLocalDirections&&this.rasterInfo.dataType.startsWith("vector");j&&!this.rasterJobHandler&&await H();const D=this.rasterJobHandler?await this.rasterJobHandler.getProjectionOffsetGrid({projectedExtent:e,srcBufferExtent:u,pixelSize:v.toJSON(),datumTransformation:z,rasterTransform:p,hasWrapAround:r>0||L,isAdaptive:!1!==this.ioConfig.optimizeProjectionAccuracy,includeGCSGrid:j},o):O({projectedExtent:e,srcBufferExtent:u,pixelSize:v,datumTransformation:z,rasterTransform:p,hasWrapAround:r>0||L,isAdaptive:!1,includeGCSGrid:j});let A;const q=!o.requestRawData,G={rows:D.spacing[0],cols:D.spacing[1]},J=this._hasNoneOrGCSShiftTransform?this._getRasterTileAlignmentInfo(s,u.xmin):void 0,{pixelBlocks:N,mosaicSize:V,isPartiallyFilled:U}=y;let Q=null;if(this.rasterJobHandler){const e=await this.rasterJobHandler.mosaicAndTransform({srcPixelBlocks:N,srcMosaicSize:V,destDimension:q?{width:t,height:i}:null,coefs:q?D.coefficients:null,sampleSpacing:q?G:null,projectDirections:j,gcsGrid:j?D.gcsGrid:null,isUV:"vector-uv"===this.rasterInfo.dataType,interpolation:o.interpolation,alignmentInfo:J,blockWidths:null},o);({pixelBlock:A,localNorthDirections:Q}=e)}else{const e=B(N,V,{alignmentInfo:J});A=q?_(e,{width:t,height:i},D.coefficients,G,o.interpolation):e,j&&D.gcsGrid&&(Q=M({width:t,height:i},D.gcsGrid),A=F(A,this.rasterInfo.dataType,Q))}return o.requestRawData||j?{extent:e,srcExtent:u,srcTilePixelSize:b,pixelBlock:A,transformGrid:D,localNorthDirections:Q,isPartiallyFilled:U}:{extent:e,srcExtent:e,srcTilePixelSize:b,pixelBlock:A}}async _fetchRawTiles(e,t,i,o){const{origin:r,blockBoundary:n}=this.rasterInfo.storageInfo,{blockWidth:s,blockHeight:l}=this.getBlockWidthHeight(e);let{x:a,y:c}=t,{width:f,height:m,wrapCount:h}=i;const p=this._getRasterTileAlignmentInfo(e,0);o.buffer&&(a-=o.buffer.cols,c-=o.buffer.rows,f+=2*o.buffer.cols,m+=2*o.buffer.rows);let d=0,x=0,y=0;if(h&&null!=p){({worldColumnCountFromOrigin:x,originColumnOffset:y,rightPadding:d}=p);x*p.blockWidth-d>=a+f&&(d=0)}const g=Math.floor(a/s),I=Math.floor(c/l),R=Math.floor((a+f+d-1)/s),w=Math.floor((c+m+d-1)/l),S=n[e];if(!S)return null;const{minRow:k,minCol:b,maxCol:T,maxRow:v}=S;if(0===h&&(w<k||R<b||I>v||g>T))return null;const P=new Array;let B=!1;const _=null==this.ioConfig.allowPartialFill?o.allowPartialFill:this.ioConfig.allowPartialFill;for(let u=I;u<=w;u++)for(let t=g;t<=R;t++){let i=t;if(!o.disableWrapAround&&h&&null!=p&&x<=t&&(i=t-x-y),u>=k&&i>=b&&v>=u&&T>=i){const t=this._fetchRawTile(e,u,i,o);_?P.push(new Promise(e=>{t.then(t=>e(t)).catch(()=>{B=!0,e(null)})})):P.push(t)}else P.push(Promise.resolve(null))}if(0===P.length)return null;const M=await Promise.all(P),C={height:(w-I+1)*l,width:(R-g+1)*s},{spatialReference:W}=this.rasterInfo,H=this.getPyramidPixelSize(e),{x:z,y:L}=H;return{extent:new u({xmin:r.x+g*s*z,xmax:r.x+(R+1)*s*z,ymin:r.y-(w+1)*l*L,ymax:r.y-I*l*L,spatialReference:W}),pixelBlocks:M,mosaicSize:C,isPartiallyFilled:B}}_fetchRawTile(e,t,i,o){const{storageInfo:r}=this.rasterInfo,n=null!=r.transposeInfo&&!!o.transposedVariableName;if(!n){const o=r.blockBoundary[e];if(!o)return Promise.resolve(null);const{minRow:n,minCol:s,maxCol:l,maxRow:a}=o;if(t<n||i<s||t>a||i>l)return Promise.resolve(null)}const l=n?o.transposeVariableName:o.sliceId,a=r.isBsqTile?o.bandIds:null,c=w(this.rasterId,l,a),f=`${e}/${t}/${i}`;let u=S(c,o.registryId,f);if(null==u){const n=new AbortController,s=o.bandIds?.slice();if(s?.length&&r.isBsqTile){const r=new Set(s),l=[],a=Array.from(r);for(const s of a)l.push(this._tileFetchQueue.push({pyramidLevel:e,row:t,col:i,options:{...o,bandIds:[s]}},{signal:n.signal}));u=Promise.all(l).then(e=>{if(e.some(e=>null==e))return null;if(a.length!==s.length){const t=[];for(const i of s){let o=e[a.indexOf(i)];t.includes(o)&&(o=o.clone()),t.push(o)}e=t}return this.rasterJobHandler?this.rasterJobHandler.compositeBands({pixelBlocks:e},{signal:n.signal,transferPixelsToWorker:!0}):C(e)})}else u=this._tileFetchQueue.push({pyramidLevel:e,row:t,col:i,options:o},{signal:n.signal});k(c,o.registryId,f,u,n),u.catch(()=>b(c,o.registryId,f))}return o.signal&&s(o,()=>{T(c,o.registryId,f)}),u}_computeMagDirValues(e){const{bandCount:t,dataType:i}=this.rasterInfo;if(!(2===t&&"vector-magdir"===i||"vector-uv"===i)||2!==e?.length||!e[0]?.length)return null;const o=e[0].length;if("vector-magdir"===i){const t=e[1].map(e=>(e+360)%360);return[e[0],t]}const[r,n]=e,s=[],l=[];for(let a=0;a<o;a++){const[e,t]=G([r[a],n[a]]);s.push(e),l.push(t)}return[s,l]}_getRasterTileAlignmentInfo(e,t){return null==this._rasterTileAlignmentInfo&&(this._rasterTileAlignmentInfo=A(this.rasterInfo)),null==this._rasterTileAlignmentInfo.pyramidsInfo?null:{startX:t,halfWorldWidth:this._rasterTileAlignmentInfo.halfWorldWidth,hasGCSSShiftTransform:this._rasterTileAlignmentInfo.hasGCSSShiftTransform,...this._rasterTileAlignmentInfo.pyramidsInfo[e]}}_getSourceDataInfo(e,t,i,o={}){const r={datumTransformation:o.datumTransformation,pyramidLevel:0,pyramidResolution:null,srcExtent:null,srcHeight:0,srcResolution:null,srcWidth:0,ul:{x:0,y:0}};o.srcResolution&&(r.srcResolution=o.srcResolution,this._updateSourceDataInfo(e,r));const n=this.rasterInfo.storageInfo.maximumPyramidLevel||0,{srcWidth:s,srcHeight:l,pyramidLevel:a}=r,c=s/t,f=l/i,u=a<n&&c*f>=16,h=a===n&&this._requireTooManySrcTiles(s,l,t,i);if(u||h||(0===s||0===l)){const s=new m({x:(e.xmax-e.xmin)/t,y:(e.ymax-e.ymin)/i,spatialReference:e.spatialReference});let l=q(s,this.rasterInfo.spatialReference,e,r.datumTransformation);const h=!l||o.srcResolution&&l.x+l.y<o.srcResolution.x+o.srcResolution.y;if(u&&o.srcResolution&&h){const e=Math.round(Math.log(Math.max(c,f))/Math.LN2)-1;if(n-a+3>=e){const t=2**e;l={x:o.srcResolution.x*t,y:o.srcResolution.y*t}}}l&&(r.srcResolution=l,this._updateSourceDataInfo(e,r))}return this._requireTooManySrcTiles(r.srcWidth,r.srcHeight,t,i)&&(r.srcWidth=0,r.srcHeight=0),r}_requireTooManySrcTiles(e,t,i,o){const{tileInfo:r}=this.rasterInfo.storageInfo,n=Math.ceil(e/r.size[0])*Math.ceil(t/r.size[1]),s=e/i,l=t/o,a=Math.max(1,(i+o)/1024);return n>=K*a||s>X||l>X}_updateSourceDataInfo(e,t){t.srcWidth=0,t.srcHeight=0;const{rasterInfo:i}=this,o=i.spatialReference,{srcResolution:r,datumTransformation:n}=t,{pyramidLevel:s,pyramidResolution:l,excessiveReading:a}=L(r,i,this.ioConfig.sampling);if(a)return;let c=t.srcExtent||D(e,o,n);if(null==c)return;const f=i.transform;f&&(c=f.inverseTransform(c)),t.srcExtent=c;const{origin:u}=i.storageInfo,{width:m,height:h,ul:p}=d(c,u,l,s);t.pyramidLevel=s,t.pyramidResolution=l,t.srcWidth=m,t.srcHeight=h,t.ul=p}_getRequestOptionsWithSliceId(e){return null!=this.rasterInfo.multidimensionalInfo&&null==e.sliceId&&(e={...e,sliceId:this.getSliceIndex(e.multidimensionalDefinition)}),e}_processIdentifyResult(e,t){const{srcLocation:i,position:o,pyramidLevel:r,useTransposedTile:n}=t,s=e.pixels[0].length/e.width/e.height;if(!(!e.mask||e.mask[o]))return{location:i,value:null};const{multidimensionalInfo:l}=this.rasterInfo;if(null==l||!n){const t=e.pixels.map(e=>e[o]),n={location:i,value:t,pyramidLevel:r},s=this._computeMagDirValues(t.map(e=>[e]));return s?.length&&(n.magdirValue=s.map(e=>e[0])),n}let a=e.pixels.map(e=>e.slice(o*s,o*s+s)),c=this._computeMagDirValues(a);const{requestSomeSlices:f,identifyOptions:u}=t;let m=g(l,u.transposedVariableName);if(f){const e=I(m,u.multidimensionalDefinition,u.timeExtent);a=a.map(t=>e.map(e=>t[e])),c=c?.map(t=>e.map(e=>t[e])),m=e.map(e=>m[e])}const h=e.noDataValues||this.rasterInfo.noDataValue,p={pixels:a,pixelType:e.pixelType};let d;null!=h&&(v(p,h),d=p.mask);return{location:i,value:null,dataSeries:m.map((e,t)=>{const i={value:0===d?.[t]?null:a.map(e=>e[t]),multidimensionalDefinition:e.multidimensionalDefinition.map(e=>new V({...e,isSlice:!0}))};return c?.length&&(i.magdirValue=[c[0][t],c[1][t]]),i}),pyramidLevel:r}}};function ee(e,t,i){return Math.abs(e.x-t.x)<i&&Math.abs(e.y-t.y)<i}e([a()],Z.prototype,"_rasterTileAlignmentInfo",void 0),e([a()],Z.prototype,"_tileFetchQueue",void 0),e([a({readOnly:!0})],Z.prototype,"_isGlobalWrappableSource",null),e([a({readOnly:!0})],Z.prototype,"_hasNoneOrGCSShiftTransform",null),e([a()],Z.prototype,"_openPromise",void 0),e([a()],Z.prototype,"rasterJobHandler",null),e([a({readOnly:!0})],Z.prototype,"rasterId",null),e([a(N)],Z.prototype,"url",null),e([a({type:String,json:{write:!0}})],Z.prototype,"datasetName",void 0),e([a({type:String,json:{write:!0}})],Z.prototype,"datasetFormat",void 0),e([a()],Z.prototype,"hasUniqueSourceStorageInfo",void 0),e([a()],Z.prototype,"rasterInfo",void 0),e([a()],Z.prototype,"ioConfig",void 0),e([a()],Z.prototype,"sourceJSON",void 0),e([a()],Z.prototype,"rawBlockRegistryIds",void 0),Z=e([c("esri.layers.raster.datasets.BaseRaster")],Z);export{Z as default};
2
+ import{__decorate as e}from"tslib";import t from"../../../request.js";import i from"../../../core/Error.js";import{JSONSupport as o}from"../../../core/JSONSupport.js";import r from"../../../core/Logger.js";import{debounce as n,onAbort as s}from"../../../core/promiseUtils.js";import{QueueProcessor as l}from"../../../core/QueueProcessor.js";import{property as a,subclass as c}from"../../../core/accessorSupport/decorators.js";import{ensureClass as f}from"../../../core/accessorSupport/ensureType.js";import u from"../../../geometry/Extent.js";import m from"../../../geometry/Point.js";import h from"../../../geometry/SpatialReference.js";import{isFunctionRaster as p,getPixelSpaceCoverage as d}from"./datasetUtils.js";import{isMultiSliceOrRangeDefinition as x,getSliceIndex as y,createSlices as g,getSliceIds as I}from"./multidimensionalUtils.js";import{clearRegisteredIds as R,getRasterId as w,getBlock as S,putBlock as k,deleteBlock as b,decreaseRefCount as T}from"./RawBlockCache.js";import{convertNoDataToMask as v}from"../formats/pixelRangeUtils.js";import{decode as P}from"../formats/RasterCodec.js";import{mosaic as B,approximateTransform as _,getLocalArithmeticNorthRotations as M,compositeBands as W}from"../functions/pixelUtils.js";import{getWorldWidth as C,load as H,projectPoint as z,snapPyramid as L,shiftExtent as j,getWorldWrapCount as E,projectExtent as D,getProjectionOffsetGrid as O,getRasterDatasetAlignmentInfo as A,projectResolution as q}from"../functions/rasterProjectionHelper.js";import{convertToLocalDirections as F,uvComponentToVector as G}from"../functions/vectorFieldUtils.js";import{sanitizeUrl as J}from"../../support/arcgisLayerUrl.js";import{url as N}from"../../support/commonProperties.js";import V from"../../support/DimensionalDefinition.js";import U from"../../support/LOD.js";import Q from"../../support/RasterStorageInfo.js";import $ from"../../support/TileInfo.js";const X=8,K=256;let Y=0,Z=class extends o{constructor(){super(...arguments),this._tileFetchQueue=new l({concurrency:32,process:(e,t)=>this.fetchRawTile(e.pyramidLevel,e.row,e.col,{...e.options,signal:t})}),this.datasetName=null,this.datasetFormat=null,this.hasUniqueSourceStorageInfo=!0,this.rasterInfo=null,this.ioConfig={sampling:"closest"},this.rawBlockRegistryIds=[],this.refresh=n(async e=>{await this._openPromise;const t=await this._refresh(e);return t.dataChanged&&R(this.rasterId,this.rawBlockRegistryIds),t})}normalizeCtorArgs(e){return e?.ioConfig&&(e={...e,ioConfig:{resolution:null,bandIds:null,sampling:"closest",tileInfo:$.create(),...e.ioConfig}}),e}get _isGlobalWrappableSource(){const{rasterInfo:e}=this,t=C(e.spatialReference);return null!=t&&e.extent.width>=t/2}get _hasNoneOrGCSShiftTransform(){const{transform:e}=this.rasterInfo;return null==e||"gcs-shift"===e.type}set rasterJobHandler(e){this._set("rasterJobHandler",e),p(this)&&this.primaryRasters?.rasters?.forEach(t=>t.rasterJobHandler=e)}get rasterId(){return this.url||"rasterId-"+Y++}set url(e){this._set("url",J(e,r.getLogger(this)))}async open(e){return this._openPromise??=H().then(()=>this._open(e)),this._openPromise}async fetchTile(e,t,o,r={}){const n=r.tileInfo||this.rasterInfo.storageInfo.tileInfo,s=this.getTileExtentFromTileInfo(e,t,o,n);if(!s)throw new i("imagery-tile:out-of-bounds","Level for fetch tile out of range");return r={noClip:!0,...r},this.fetchPixels(s,n.size[0],n.size[1],r)}async identify(e,t={}){e=f(m,e).clone().normalize();const{multidimensionalDefinition:i,timeExtent:o}=t,{rasterInfo:r}=this,{hasMultidimensionalTranspose:n,multidimensionalInfo:s}=r;let{transposedVariableName:l}=t;const a=null!=s&&n&&(null!=o||x(i));if(a&&!l){l=null!=i&&i.length>0?i[0].variableName??void 0:s.variables[0].name,t={...t,transposedVariableName:l}}t=this._getRequestOptionsWithSliceId(t);const{spatialReference:c,extent:h}=r,{datumTransformation:d}=t;let y=z(e,c,d);if(!h.intersects(y))return{location:y,value:null};if(null!=r.transform){const e=r.transform.inverseTransform(y);if(!r.nativeExtent.intersects(e))return{location:e,value:null};y=e}let g=0;const I=null!=l&&null!=s&&r.hasMultidimensionalTranspose;if(p(this)){const e=this.primaryRasters.rasters[0];if(I)return e.identify(y,t);const{pixelSize:o}=r,n=3,s=o.x*n/2,l=o.y*n/2,a=new u({xmin:y.x-s,xmax:y.x+s,ymin:y.y-l,ymax:y.y+l,spatialReference:c}),f={interpolation:"nearest",multidimensionalDefinition:i,sliceId:t.sliceId,bandIds:t.bandIds},{pixelBlock:m}=await e.fetchPixels(a,n,n,f),{pixelBlock:h}=await this.fetchPixels(a,n,n,f);if(null==m)return{location:y,value:null};const p=Math.floor(n*n*.5),d=!m.mask||m.mask[p]?m.pixels.map(e=>e[p]):null;let x;return null!=h&&(x=!h.mask||h.mask[p]?h.pixels.map(e=>e[p]):void 0),{location:y,value:d,processedValue:x,pyramidLevel:0}}if(!I)if(t.srcResolution){g=L(t.srcResolution,r,this.ioConfig.sampling).pyramidLevel}else if(g=await this.computeBestPyramidLevelForLocation(e,t),null==g)return{location:y,value:null};const R=this.identifyPixelLocation(y,g,null,I);if(null===R)return{location:y,value:null};const{row:w,col:S,rowOffset:k,colOffset:b,blockWidth:T}=R,v=await this._fetchRawTile(g,w,S,t);if(!v?.pixels?.length)return{location:y,value:null};const P=k*T+b;return this._processIdentifyResult(v,{srcLocation:y,position:P,pyramidLevel:g,useTransposedTile:!!I,requestSomeSlices:a,identifyOptions:t})}async fetchPixels(e,t,i,o={}){e=j(e),o=this._getRequestOptionsWithSliceId(o);const{_hasNoneOrGCSShiftTransform:r}=this;if(o.requestRawData&&r)return this._fetchPixels(e,t,i,o);const n=C(e.spatialReference),s=E(e);if(null==n||0===s||1===s&&this._isGlobalWrappableSource&&r)return this._fetchPixels(e,t,i,o);if(s>=3)return{extent:e,pixelBlock:null};const l=[],{xmin:a,xmax:c}=e,f=Math.round(n/(c-a)*t),m=f-Math.round((n/2-a)/(c-a)*t);let h=0;const p=[];for(let g=0;g<=s;g++){const r=new u({xmin:0===g?a:-n/2,xmax:g===s?c-n*g:n/2,ymin:e.ymin,ymax:e.ymax,spatialReference:e.spatialReference}),d=0===g?f-m:g===s?t-h:f;h+=d,p.push(d);const x=o.disableWrapAround&&g>0?null:this._fetchPixels(r,d,i,o);l.push(x)}const d=(await Promise.all(l)).map(e=>e?.pixelBlock);let x=null;const y={width:t,height:i};if(this.rasterJobHandler){x=(await this.rasterJobHandler.mosaicAndTransform({srcPixelBlocks:d,srcMosaicSize:y,destDimension:null,coefs:null,sampleSpacing:null,interpolation:"nearest",alignmentInfo:null,blockWidths:p},o)).pixelBlock}else x=B(d,y,{blockWidths:p});return{extent:e,srcExtent:D(e,this.rasterInfo.spatialReference,o.datumTransformation),pixelBlock:x}}async fetchRawPixels(e,t,i,o={}){t={x:Math.floor(t.x),y:Math.floor(t.y)};const r=await this._fetchRawTiles(e,t,i,o),{nativeExtent:n,nativePixelSize:s,storageInfo:l}=this.rasterInfo,a=2**e,c=s.x*a,f=s.y*a,m=new u({xmin:n.xmin+c*t.x,xmax:n.xmin+c*(t.x+i.width-1),ymin:n.ymax-f*(t.y+i.height-1),ymax:n.ymax-f*t.y,spatialReference:n.spatialReference});if(!r)return{extent:m,srcExtent:m,pixelBlock:null};const{pixelBlocks:h,mosaicSize:p}=r;if(1===h.length&&null!=h[0]&&h[0].width===i.width&&h[0].height===i.height)return{extent:m,srcExtent:m,pixelBlock:r.pixelBlocks[0]};const d=e>0?l.pyramidBlockWidth:l.blockWidth,x=e>0?l.pyramidBlockHeight:l.blockHeight,y={x:t.x%d,y:t.y%x};let g;if(this.rasterJobHandler){g=(await this.rasterJobHandler.mosaicAndTransform({srcPixelBlocks:h,srcMosaicSize:p,destDimension:i,clipOffset:y,clipSize:i,coefs:null,sampleSpacing:null,interpolation:o.interpolation,alignmentInfo:null,blockWidths:null},o)).pixelBlock}else g=B(h,p,{clipOffset:y,clipSize:i});return{extent:m,srcExtent:m,pixelBlock:g}}fetchRawTile(e,t,o,r){throw new i("BaseRaster:read-not-implemented","fetchRawTile() is not implemented")}computeExtent(e){return D(this.rasterInfo.extent,e)}decodePixelBlock(e,t){return this.rasterJobHandler?this.rasterJobHandler.decode({data:e,options:t}):P(e,t)}async request(e,i,o=0){const{customFetchParameters:r}=this.ioConfig,{range:n,query:s,headers:l}=i;o=o??i.retryCount??this.ioConfig.retryCount;const a=n?{Range:`bytes=${n.from}-${n.to}`}:null;try{return await t(e,{...i,query:{...s,...r},headers:{...l,...a}})}catch(c){if(o>0)return o--,this.request(e,i,o);throw c}}getSliceIndex(e){const{multidimensionalInfo:t}=this.rasterInfo;return null==t||null==e||0===e.length?null:y(e,t)}getTileExtentFromTileInfo(e,t,i,o){const r=o.lodAt(e);return r?this.getTileExtent({x:r.resolution,y:r.resolution},t,i,o.origin,o.spatialReference,o.size):null}updateTileInfo(){const{storageInfo:e,spatialReference:t,extent:i,pixelSize:o}=this.rasterInfo,{pyramidResolutions:r}=e;if(!e.tileInfo){const n=[],s=e.maximumPyramidLevel||0;let l=(o.x+o.y)/2,a=1/.0254*96*l;for(let e=0;e<=s&&(n.unshift(new U({level:s-e,resolution:l,scale:a})),e!==s);e++)if(r){const t=(r[e].x+r[e].y)/2;a*=t/l,l=t}else l*=2,a*=2;const c=new m({x:i.xmin,y:i.ymax,spatialReference:t});e.tileInfo=new $({origin:c,size:[e.blockWidth,e.blockHeight],spatialReference:t,lods:n}),e.isVirtualTileInfo=!0}}createRemoteDatasetStorageInfo(e,t=512,i=512,o){const{width:r,height:n,nativeExtent:s,pixelSize:l,spatialReference:a}=e,c=new m({x:s.xmin,y:s.ymax,spatialReference:a});null==o&&(o=Math.max(0,Math.round(Math.log(Math.max(r,n))/Math.LN2-8)));const f=this.computeBlockBoundary(s,512,512,{x:s.xmin,y:s.ymax},[l],o);e.storageInfo=new Q({blockWidth:t,blockHeight:i,pyramidBlockWidth:t,pyramidBlockHeight:i,origin:c,firstPyramidLevel:1,maximumPyramidLevel:o,blockBoundary:f})}async computeBestPyramidLevelForLocation(e,t={}){return 0}computeBlockBoundary(e,t,i,o,r,n=0,s=2){if(1===r.length&&n>0){r=[...r];let{x:e,y:t}=r[0];for(let i=0;i<n;i++)e*=s,t*=s,r.push({x:e,y:t})}const l=[],{x:a,y:c}=o;for(let f=0;f<r.length;f++){const{x:o,y:n}=r[f];l.push({minCol:Math.floor((e.xmin-a+.1*o)/t/o),maxCol:Math.floor((e.xmax-a-.1*o)/t/o),minRow:Math.floor((c-e.ymax+.1*n)/i/n),maxRow:Math.floor((c-e.ymin-.1*n)/i/n)})}return l}getPyramidPixelSize(e){const{nativePixelSize:t}=this.rasterInfo,{pyramidResolutions:i,pyramidScalingFactor:o}=this.rasterInfo.storageInfo;if(0===e)return t;if(null!=i&&i.length)return i[e-1];const r=o**e;return{x:t.x*r,y:t.y*r}}identifyPixelLocation(e,t,i,o){const{spatialReference:r,nativeExtent:n,storageInfo:s}=this.rasterInfo,{maximumPyramidLevel:l,origin:a,transposeInfo:c}=s,f=o&&null!=c?c.tileSize[0]:s.blockWidth,u=o&&null!=c?c.tileSize[1]:s.blockHeight,m=z(e,r,i);if(!n.intersects(m))return null;if(t<0||t>l)return null;const h=this.getPyramidPixelSize(t),{x:p,y:d}=h,x=(a.y-m.y)/d/u,y=(m.x-a.x)/p/f,g=Math.min(u-1,Math.floor((x-Math.floor(x))*u)),I=Math.min(f-1,Math.floor((y-Math.floor(y))*f));return{pyramidLevel:t,row:Math.floor(x),col:Math.floor(y),rowOffset:g,colOffset:I,blockWidth:f,srcLocation:m}}getTileExtent(e,t,i,o,r,n){const[s,l]=n,a=o.x+i*s*e.x,c=a+s*e.x,f=o.y-t*l*e.y,m=f-l*e.y;return new u({xmin:a,xmax:c,ymin:m,ymax:f,spatialReference:r})}getBlockWidthHeight(e){return{blockWidth:e>0?this.rasterInfo.storageInfo.pyramidBlockWidth:this.rasterInfo.storageInfo.blockWidth,blockHeight:e>0?this.rasterInfo.storageInfo.pyramidBlockHeight:this.rasterInfo.storageInfo.blockHeight}}isBlockOutside(e,t,i){const o=this.rasterInfo.storageInfo.blockBoundary[e];return!o||o.maxRow<t||o.maxCol<i||o.minRow>t||o.minCol>i}updateImageSpaceRasterInfo(e){const{pixelSize:t}=e,{width:i,height:o}=e,r=h.WebMercator;e.spatialReference=r,e.extent=e.nativeExtent=new u({xmin:-.5,ymax:.5,xmax:i-.5,ymin:.5-o,spatialReference:r}),e.isPseudoSpatialReference=!0,e.transform=null,e.pixelSize=new m({x:1,y:1,spatialReference:r});const{extent:n,storageInfo:s}=e;if(s){s.origin=new m({x:n.xmin,y:n.ymax,spatialReference:r});const{pyramidResolutions:i,tileInfo:o}=s;if(i&&i.forEach(e=>{e.x/=t.x,e.y/=t.y}),o){o.origin=s.origin;const t=(e.nativePixelSize.x+e.nativePixelSize.y)/2;o.lods.forEach((e,i)=>{e.resolution=t*2**i,e.scale=96*e.resolution/.0254})}}}async _refresh(e){return{dataChanged:!0}}async _fetchPixels(e,t,i,o={}){let r=E(e);if(r>=2)return{extent:e,pixelBlock:null};const n=this._getSourceDataInfo(e,t,i,o),{pyramidLevel:s,srcResolution:l,srcWidth:a,srcHeight:c,ul:f}=n;let{srcExtent:u}=n;if(0===a||0===c)return{extent:e,srcExtent:u,pixelBlock:null};const{rasterInfo:h}=this,p=h.transform,d="gcs-shift"===p?.type,x=null!=C(e.spatialReference);!d&&x||(r=E(u,d));const y=await this._fetchRawTiles(s,f,{width:a,height:c,wrapCount:r},o);if(!y)return{extent:e,srcExtent:u,pixelBlock:null};u=y.extent;const g=h.storageInfo,I=s>0?g.pyramidBlockWidth:g.blockWidth,R=s>0?g.pyramidBlockHeight:g.blockHeight;let{x:w,y:S}=h.pixelSize;if(s>0){const{pyramidResolutions:e,pyramidScalingFactor:t}=g;if(null!=e&&e[s-1])({x:w,y:S}=e[s-1]);else{const e=t**s;w*=e,S*=e}}const k=h.spatialReference,b=new m({x:w,y:S,spatialReference:k}),T=I===a&&R===c&&f.x%I===0&&f.y%R===0,v=new m({x:(e.xmax-e.xmin)/t,y:(e.ymax-e.ymin)/i,spatialReference:e.spatialReference}),P=!e.spatialReference.equals(k),W=k.isGeographic?1e-9:1e-4,{datumTransformation:z}=o;if(!P&&T&&1===y.pixelBlocks.length&&I===t&&R===i&&ee(l,v,W))return{extent:e,srcExtent:u,srcTilePixelSize:b,pixelBlock:y.pixelBlocks[0]};const L=x&&null!=C(u.spatialReference)&&this._hasNoneOrGCSShiftTransform,j=o.requestProjectedLocalDirections&&this.rasterInfo.dataType.startsWith("vector");j&&!this.rasterJobHandler&&await H();const D=this.rasterJobHandler?await this.rasterJobHandler.getProjectionOffsetGrid({projectedExtent:e,srcBufferExtent:u,pixelSize:v.toJSON(),datumTransformation:z,rasterTransform:p,hasWrapAround:r>0||L,isAdaptive:!1!==this.ioConfig.optimizeProjectionAccuracy,includeGCSGrid:j},o):O({projectedExtent:e,srcBufferExtent:u,pixelSize:v,datumTransformation:z,rasterTransform:p,hasWrapAround:r>0||L,isAdaptive:!1,includeGCSGrid:j});let A;const q=!o.requestRawData,G={rows:D.spacing[0],cols:D.spacing[1]},J=this._hasNoneOrGCSShiftTransform?this._getRasterTileAlignmentInfo(s,u.xmin):void 0,{pixelBlocks:N,mosaicSize:V,isPartiallyFilled:U}=y;let Q=null;if(this.rasterJobHandler){const e=await this.rasterJobHandler.mosaicAndTransform({srcPixelBlocks:N,srcMosaicSize:V,destDimension:q?{width:t,height:i}:null,coefs:q?D.coefficients:null,sampleSpacing:q?G:null,projectDirections:j,gcsGrid:j?D.gcsGrid:null,isUV:"vector-uv"===this.rasterInfo.dataType,interpolation:o.interpolation,alignmentInfo:J,blockWidths:null},o);({pixelBlock:A,localNorthDirections:Q}=e)}else{const e=B(N,V,{alignmentInfo:J});A=q?_(e,{width:t,height:i},D.coefficients,G,o.interpolation):e,j&&D.gcsGrid&&(Q=M({width:t,height:i},D.gcsGrid),A=F(A,this.rasterInfo.dataType,Q))}return o.requestRawData||j?{extent:e,srcExtent:u,srcTilePixelSize:b,pixelBlock:A,transformGrid:D,localNorthDirections:Q,isPartiallyFilled:U}:{extent:e,srcExtent:e,srcTilePixelSize:b,pixelBlock:A}}async _fetchRawTiles(e,t,i,o){const{origin:r,blockBoundary:n}=this.rasterInfo.storageInfo,{blockWidth:s,blockHeight:l}=this.getBlockWidthHeight(e);let{x:a,y:c}=t,{width:f,height:m,wrapCount:h}=i;const p=this._getRasterTileAlignmentInfo(e,0);o.buffer&&(a-=o.buffer.cols,c-=o.buffer.rows,f+=2*o.buffer.cols,m+=2*o.buffer.rows);let d=0,x=0,y=0;if(h&&null!=p){({worldColumnCountFromOrigin:x,originColumnOffset:y,rightPadding:d}=p);x*p.blockWidth-d>=a+f&&(d=0)}const g=Math.floor(a/s),I=Math.floor(c/l),R=Math.floor((a+f+d-1)/s),w=Math.floor((c+m+d-1)/l),S=n[e];if(!S)return null;const{minRow:k,minCol:b,maxCol:T,maxRow:v}=S;if(0===h&&(w<k||R<b||I>v||g>T))return null;const P=new Array;let B=!1;const _=null==this.ioConfig.allowPartialFill?o.allowPartialFill:this.ioConfig.allowPartialFill;for(let u=I;u<=w;u++)for(let t=g;t<=R;t++){let i=t;if(!o.disableWrapAround&&h&&null!=p&&x<=t&&(i=t-x-y),u>=k&&i>=b&&v>=u&&T>=i){const t=this._fetchRawTile(e,u,i,o);_?P.push(new Promise(e=>{t.then(t=>e(t)).catch(()=>{B=!0,e(null)})})):P.push(t)}else P.push(Promise.resolve(null))}if(0===P.length)return null;const M=await Promise.all(P),W={height:(w-I+1)*l,width:(R-g+1)*s},{spatialReference:C}=this.rasterInfo,H=this.getPyramidPixelSize(e),{x:z,y:L}=H;return{extent:new u({xmin:r.x+g*s*z,xmax:r.x+(R+1)*s*z,ymin:r.y-(w+1)*l*L,ymax:r.y-I*l*L,spatialReference:C}),pixelBlocks:M,mosaicSize:W,isPartiallyFilled:B}}_fetchRawTile(e,t,i,o){const{storageInfo:r}=this.rasterInfo,n=null!=r.transposeInfo&&!!o.transposedVariableName;if(!n){const o=r.blockBoundary[e];if(!o)return Promise.resolve(null);const{minRow:n,minCol:s,maxCol:l,maxRow:a}=o;if(t<n||i<s||t>a||i>l)return Promise.resolve(null)}const l=n?o.transposeVariableName:o.sliceId,a=r.isBsqTile?o.bandIds:null,c=w(this.rasterId,l,a),f=`${e}/${t}/${i}`;let u=S(c,o.registryId,f);if(null==u){const n=new AbortController,s=o.bandIds?.slice();if(s?.length&&r.isBsqTile){const r=new Set(s),l=[],a=Array.from(r);for(const s of a)l.push(this._tileFetchQueue.push({pyramidLevel:e,row:t,col:i,options:{...o,bandIds:[s]}},{signal:n.signal}));u=Promise.all(l).then(e=>{if(e.some(e=>null==e))return null;if(a.length!==s.length){const t=[];for(const i of s){let o=e[a.indexOf(i)];t.includes(o)&&(o=o.clone()),t.push(o)}e=t}return this.rasterJobHandler?this.rasterJobHandler.compositeBands({pixelBlocks:e},{signal:n.signal,transferPixelsToWorker:!0}):W(e)})}else u=this._tileFetchQueue.push({pyramidLevel:e,row:t,col:i,options:o},{signal:n.signal});k(c,o.registryId,f,u,n),u.catch(()=>b(c,o.registryId,f))}return o.signal&&s(o,()=>{T(c,o.registryId,f)}),u}_computeMagDirValues(e){const{bandCount:t,dataType:i}=this.rasterInfo;if(!(2===t&&"vector-magdir"===i||"vector-uv"===i)||2!==e?.length||!e[0]?.length)return null;const o=e[0].length;if("vector-magdir"===i){const t=e[1].map(e=>(e+360)%360);return[e[0],t]}const[r,n]=e,s=[],l=[];for(let a=0;a<o;a++){const[e,t]=G([r[a],n[a]]);s.push(e),l.push(t)}return[s,l]}_getRasterTileAlignmentInfo(e,t){return null==this._rasterTileAlignmentInfo&&(this._rasterTileAlignmentInfo=A(this.rasterInfo)),null==this._rasterTileAlignmentInfo.pyramidsInfo?null:{startX:t,halfWorldWidth:this._rasterTileAlignmentInfo.halfWorldWidth,hasGCSSShiftTransform:this._rasterTileAlignmentInfo.hasGCSSShiftTransform,...this._rasterTileAlignmentInfo.pyramidsInfo[e]}}_getSourceDataInfo(e,t,i,o={}){const r={datumTransformation:o.datumTransformation,pyramidLevel:0,pyramidResolution:null,srcExtent:null,srcHeight:0,srcResolution:null,srcWidth:0,ul:{x:0,y:0}};o.srcResolution&&(r.srcResolution=o.srcResolution,this._updateSourceDataInfo(e,r));const n=this.rasterInfo.storageInfo.maximumPyramidLevel||0,{srcWidth:s,srcHeight:l,pyramidLevel:a}=r,c=s/t,f=l/i,u=a<n&&c*f>=16,h=a===n&&this._requireTooManySrcTiles(s,l,t,i);if(u||h||(0===s||0===l)){const s=new m({x:(e.xmax-e.xmin)/t,y:(e.ymax-e.ymin)/i,spatialReference:e.spatialReference});let l=q(s,this.rasterInfo.spatialReference,e,r.datumTransformation);const h=!l||o.srcResolution&&l.x+l.y<o.srcResolution.x+o.srcResolution.y;if(u&&o.srcResolution&&h){const e=Math.round(Math.log(Math.max(c,f))/Math.LN2)-1;if(n-a+3>=e){const t=2**e;l={x:o.srcResolution.x*t,y:o.srcResolution.y*t}}}l&&(r.srcResolution=l,this._updateSourceDataInfo(e,r))}return this._requireTooManySrcTiles(r.srcWidth,r.srcHeight,t,i)&&(r.srcWidth=0,r.srcHeight=0),r}_requireTooManySrcTiles(e,t,i,o){const{tileInfo:r}=this.rasterInfo.storageInfo,n=Math.ceil(e/r.size[0])*Math.ceil(t/r.size[1]),s=e/i,l=t/o,a=Math.max(1,(i+o)/1024);return n>=K*a||s>X||l>X}_updateSourceDataInfo(e,t){t.srcWidth=0,t.srcHeight=0;const{rasterInfo:i}=this,o=i.spatialReference,{srcResolution:r,datumTransformation:n}=t,{pyramidLevel:s,pyramidResolution:l,excessiveReading:a}=L(r,i,this.ioConfig.sampling);if(a)return;let c=t.srcExtent||D(e,o,n);if(null==c)return;const f=i.transform;f&&(c=f.inverseTransform(c)),t.srcExtent=c;const{origin:u}=i.storageInfo,{width:m,height:h,ul:p}=d(c,u,l,s);t.pyramidLevel=s,t.pyramidResolution=l,t.srcWidth=m,t.srcHeight=h,t.ul=p}_getRequestOptionsWithSliceId(e){return null!=this.rasterInfo.multidimensionalInfo&&null==e.sliceId&&(e={...e,sliceId:this.getSliceIndex(e.multidimensionalDefinition)}),e}_processIdentifyResult(e,t){const{srcLocation:i,position:o,pyramidLevel:r,useTransposedTile:n}=t,s=e.pixels[0].length/e.width/e.height;if(!(!e.mask||e.mask[o]))return{location:i,value:null};const{multidimensionalInfo:l}=this.rasterInfo;if(null==l||!n){const t=e.pixels.map(e=>e[o]),n={location:i,value:t,pyramidLevel:r},s=this._computeMagDirValues(t.map(e=>[e]));return s?.length&&(n.magdirValue=s.map(e=>e[0])),n}let a=e.pixels.map(e=>e.slice(o*s,o*s+s)),c=this._computeMagDirValues(a);const{requestSomeSlices:f,identifyOptions:u}=t;let m=g(l,u.transposedVariableName);if(f){const e=I(m,u.multidimensionalDefinition,u.timeExtent);a=a.map(t=>e.map(e=>t[e])),c=c?.map(t=>e.map(e=>t[e])),m=e.map(e=>m[e])}const h=e.noDataValues||this.rasterInfo.noDataValue,p={pixels:a,pixelType:e.pixelType};let d;null!=h&&(v(p,h),d=p.mask);return{location:i,value:null,dataSeries:m.map((e,t)=>{const i={value:0===d?.[t]?null:a.map(e=>e[t]),multidimensionalDefinition:e.multidimensionalDefinition.map(e=>new V({...e,isSlice:!0}))};return c?.length&&(i.magdirValue=[c[0][t],c[1][t]]),i}),pyramidLevel:r}}};function ee(e,t,i){return Math.abs(e.x-t.x)<i&&Math.abs(e.y-t.y)<i}e([a()],Z.prototype,"_rasterTileAlignmentInfo",void 0),e([a()],Z.prototype,"_tileFetchQueue",void 0),e([a({readOnly:!0})],Z.prototype,"_isGlobalWrappableSource",null),e([a({readOnly:!0})],Z.prototype,"_hasNoneOrGCSShiftTransform",null),e([a()],Z.prototype,"_openPromise",void 0),e([a()],Z.prototype,"rasterJobHandler",null),e([a({readOnly:!0})],Z.prototype,"rasterId",null),e([a(N)],Z.prototype,"url",null),e([a({type:String,json:{write:!0}})],Z.prototype,"datasetName",void 0),e([a({type:String,json:{write:!0}})],Z.prototype,"datasetFormat",void 0),e([a()],Z.prototype,"hasUniqueSourceStorageInfo",void 0),e([a()],Z.prototype,"rasterInfo",void 0),e([a()],Z.prototype,"ioConfig",void 0),e([a()],Z.prototype,"sourceJSON",void 0),e([a()],Z.prototype,"rawBlockRegistryIds",void 0),Z=e([c("esri.layers.raster.datasets.BaseRaster")],Z);export{Z as default};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{__decorate as t}from"tslib";import e from"../../../core/Error.js";import has from"../../../core/has.js";import{eachAlways as s,createAbortError as r}from"../../../core/promiseUtils.js";import{property as a,subclass as o}from"../../../core/accessorSupport/decorators.js";import i from"../../../geometry/Extent.js";import n from"../../../geometry/SpatialReference.js";import l from"./BaseRaster.js";import m from"./InMemoryRaster.js";import{parsePAMInfo as f}from"./pamParser.js";import{getFormat as p}from"../formats/RasterCodec.js";import{estimateStatisticsFromHistograms as c}from"../functions/stretchUtils.js";import u from"../transforms/PolynomialTransform.js";let h=class extends l{fetchRawTile(t,e,s,r={}){return this._inMemoryRaster.fetchRawTile(t,e,s,r)}async _open(t){const e=await this._fetchData(t);let{spatialReference:s,statistics:r,histograms:a,transform:o}=await this._fetchAuxiliaryData(t);const l=!s;l&&(s=new n({wkid:3857})),a?.length&&null==r&&(r=c(a));const{width:f,height:p}=e;let u=new i({xmin:-.5,ymin:.5-p,xmax:f-.5,ymax:.5,spatialReference:s});const h=o?o.forwardTransform(u):u;let d=!0;if(o){const t=o.forwardCoefficients;d=t&&0===t[1]&&0===t[2],d&&(o=null,u=h)}const w=new m({source:{extent:h,nativeExtent:u,transform:o,pixelBlocks:[e],statistics:r,histograms:a,keyProperties:{DateType:"Processed"},isPseudoSpatialReference:l},ioConfig:{sampling:"closest",skipStatistics:!0}});this.ioConfig.skipMapInfo&&(w.ioConfig.skipMapInfo=!0),await w.open(),w.source=null,this._set("rasterInfo",w.rasterInfo),this._inMemoryRaster=w}async _fetchData(t){const{data:s}=await this.request(this.url,{responseType:"array-buffer",signal:t?.signal}),r=p(s).toUpperCase();if("JPG"!==r&&"PNG"!==r&&"GIF"!==r&&"BMP"!==r)throw new e("image-aux-raster:open","the data is not a supported format");this._set("datasetFormat",r);const a=r.toLowerCase(),o="gif"===a||"bmp"===a||!has("ios"),i=await this.decodePixelBlock(s,{format:a,useCanvas:o,hasNoZlibMask:!0});if(null==i)throw new e("image-aux-raster:open","the data cannot be decoded");return i}async _fetchAuxiliaryData(t){const e=t?.signal,{skipExtensions:a=[],skipMapInfo:o}=this.ioConfig,i=o||a.includes("aux.xml")?null:this.request(this.url+".aux.xml",{responseType:"xml",signal:e}),n=this.datasetFormat,l="JPG"===n?"jgw":"PNG"===n?"pgw":"BMP"===n?"bpw":null,m=l&&a.includes(l)?null:this.request(this.url.slice(0,this.url.lastIndexOf("."))+"."+l,{responseType:"text",signal:e}),p=await s([i,m]);if(e?.aborted)throw r();const c=f(p[0].value?.data);if(!c.transform){const t=p[1].value?p[1].value.data.split("\n").slice(0,6).map(t=>Number(t)):null;c.transform=6===t?.length?new u({forwardCoefficients:[t[4],t[5],t[0],-t[1],t[2],-t[3]]}):null}return c}};t([a({type:String,json:{write:!0}})],h.prototype,"datasetFormat",void 0),h=t([o("esri.layers.raster.datasets.ImageAuxRaster")],h);const d=h;export{d as default};
2
+ import{__decorate as t}from"tslib";import e from"../../../core/Error.js";import{eachAlways as s,createAbortError as r}from"../../../core/promiseUtils.js";import{property as a,subclass as o}from"../../../core/accessorSupport/decorators.js";import i from"../../../geometry/Extent.js";import n from"../../../geometry/SpatialReference.js";import l from"./BaseRaster.js";import m from"./InMemoryRaster.js";import{parsePAMInfo as f}from"./pamParser.js";import{getFormat as p}from"../formats/RasterCodec.js";import{estimateStatisticsFromHistograms as c}from"../functions/stretchUtils.js";import u from"../transforms/PolynomialTransform.js";let h=class extends l{fetchRawTile(t,e,s,r={}){return this._inMemoryRaster.fetchRawTile(t,e,s,r)}async _open(t){const e=await this._fetchData(t);let{spatialReference:s,statistics:r,histograms:a,transform:o}=await this._fetchAuxiliaryData(t);const l=!s;l&&(s=new n({wkid:3857})),a?.length&&null==r&&(r=c(a));const{width:f,height:p}=e;let u=new i({xmin:-.5,ymin:.5-p,xmax:f-.5,ymax:.5,spatialReference:s});const h=o?o.forwardTransform(u):u;let d=!0;if(o){const t=o.forwardCoefficients;d=t&&0===t[1]&&0===t[2],d&&(o=null,u=h)}const w=new m({source:{extent:h,nativeExtent:u,transform:o,pixelBlocks:[e],statistics:r,histograms:a,keyProperties:{DateType:"Processed"},isPseudoSpatialReference:l},ioConfig:{sampling:"closest",skipStatistics:!0}});this.ioConfig.skipMapInfo&&(w.ioConfig.skipMapInfo=!0),await w.open(),w.source=null,this._set("rasterInfo",w.rasterInfo),this._inMemoryRaster=w}async _fetchData(t){const{data:s}=await this.request(this.url,{responseType:"array-buffer",signal:t?.signal}),r=p(s).toUpperCase();if("JPG"!==r&&"PNG"!==r&&"GIF"!==r&&"BMP"!==r)throw new e("image-aux-raster:open","the data is not a supported format");this._set("datasetFormat",r);const a=r.toLowerCase(),o=await this.decodePixelBlock(s,{format:a});if(null==o)throw new e("image-aux-raster:open","the data cannot be decoded");return o}async _fetchAuxiliaryData(t){const e=t?.signal,{skipExtensions:a=[],skipMapInfo:o}=this.ioConfig,i=o||a.includes("aux.xml")?null:this.request(this.url+".aux.xml",{responseType:"xml",signal:e}),n=this.datasetFormat,l="JPG"===n?"jgw":"PNG"===n?"pgw":"BMP"===n?"bpw":null,m=l&&a.includes(l)?null:this.request(this.url.slice(0,this.url.lastIndexOf("."))+"."+l,{responseType:"text",signal:e}),p=await s([i,m]);if(e?.aborted)throw r();const c=f(p[0].value?.data);if(!c.transform){const t=p[1].value?p[1].value.data.split("\n").slice(0,6).map(t=>Number(t)):null;c.transform=6===t?.length?new u({forwardCoefficients:[t[4],t[5],t[0],-t[1],t[2],-t[3]]}):null}return c}};t([a({type:String,json:{write:!0}})],h.prototype,"datasetFormat",void 0),h=t([o("esri.layers.raster.datasets.ImageAuxRaster")],h);const d=h;export{d as default};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{__decorate as e}from"tslib";import t from"../../../core/Error.js";import{assertIsSome as i}from"../../../core/maybe.js";import{urlToObject as s}from"../../../core/urlUtils.js";import{property as r,subclass as a}from"../../../core/accessorSupport/decorators.js";import l from"../../../geometry/Extent.js";import n from"../../../geometry/Point.js";import o from"../../../geometry/SpatialReference.js";import c from"./BaseRaster.js";import{setValidBoundary as m}from"../functions/pixelUtils.js";import u from"../transforms/GCSShiftTransform.js";import h from"../../support/RasterInfo.js";import f from"../../support/RasterStorageInfo.js";import p from"../../support/TileInfo.js";import{TilemapCache as d}from"../../support/TilemapCache.js";import{patchServiceInfo as y,fetchServiceRasterInfo as x}from"../../../rest/imageService/fetchRasterInfo.js";let g=class extends c{constructor(){super(...arguments),this._levelOffset=0,this._tilemapCache=null,this._slices=null,this.datasetFormat="RasterTileServer",this.tileType=null}async fetchRawTile(e,t,i,s={}){const{storageInfo:r,extent:a}=this.rasterInfo,{transposeInfo:l}=r,n=null!=l&&!!s.transposedVariableName;if(this._slices&&!n&&null==s.sliceId)return null;const o=n?0:r.maximumPyramidLevel-e+this._levelOffset,c=`${this.url}/tile/${o}/${t}/${i}`,u={...this._slices?n?{variable:s.transposedVariableName}:{sliceId:s.sliceId||0}:null,...s.refreshParameters};let h,f;if(r.isBsqTile){const e=(s.bandIds?.length?s.bandIds:[0,1,2]).map(e=>this.request(c,{query:{...u,bandId:e},responseType:"array-buffer",signal:s.signal})),t=await Promise.all(e),i=t.map(e=>e.data.byteLength).reduce((e,t)=>e+t),r=new Uint8Array(i);f=[];let a=0;for(const{data:s}of t)f.push(a),r.set(new Uint8Array(s),a),a+=s.byteLength;h=r.buffer}else{h=(await this.request(c,{query:u,responseType:"array-buffer",signal:s.signal})).data}if(!h)return null;const p=n?l.tileSize:r.tileInfo.size,d=await this.decodePixelBlock(h,{width:p[0],height:p[1],planes:f?.length,offsets:f,pixelType:null,isPoint:"Elevation"===this.tileType,returnInterleaved:n,noDataValue:this.rasterInfo.noDataValue});if(null==d)return null;const y=r.blockBoundary[e];if("jpg"!==r.compression||i>y.minCol&&i<y.maxCol&&t>y.minRow&&t<y.maxRow)return d;const{origin:x,blockWidth:g,blockHeight:v}=r,{x:S,y:I}=this.getPyramidPixelSize(e),w=Math.round((a.xmin-x.x)/S)%g,b=Math.round((a.xmax-x.x)/S)%g||g,T=Math.round((x.y-a.ymax)/I)%v,M=Math.round((x.y-a.ymin)/I)%v||v,_=i===y.minCol?w:0,j=t===y.minRow?T:0,O=i===y.maxCol?b:g,R=t===y.maxRow?M:v;return m(d,{x:_,y:j},{width:O-_,height:R-j}),d}getSliceIndex(e){if(!this._slices||null==e||0===e.length)return null;const t=e;for(let i=0;i<this._slices.length;i++){const e=this._slices[i].multidimensionalDefinition;if(e.length===t.length&&!e.some(e=>{const i=t.find(t=>e.variableName===t.variableName&&t.dimensionName===e.dimensionName);if(!i)return!0;return(Array.isArray(e.values[0])?`${e.values[0][0]}-${e.values[0][1]}`:e.values[0])!==(Array.isArray(i.values[0])?`${i.values[0][0]}-${i.values[0][1]}`:i.values[0])}))return i}return null}async fetchVariableStatisticsHistograms(e,t){const i=this.request(this.url+"/statistics",{query:{variable:e,f:"json"},signal:t}).then(e=>e.data?.statistics),s=this.request(this.url+"/histograms",{query:{variable:e,f:"json"},signal:t}).then(e=>e.data?.histograms),r=await Promise.all([i,s]);return r[0]&&r[0].forEach(e=>{e.avg=e.mean,e.stddev=e.standardDeviation}),r[1]?.[0]?.counts?.length||(r[1]=null),{statistics:r[0]||null,histograms:r[1]||null}}async computeBestPyramidLevelForLocation(e,t={}){if(!this._tilemapCache)return 0;let i=this.identifyPixelLocation(e,0,t.datumTransformation);if(null===i)return null;let s=0;const{maximumPyramidLevel:r}=this.rasterInfo.storageInfo;let a=r-s+this._levelOffset;const l=i.srcLocation;for(;a>=0;){try{if("available"===await this._tilemapCache.fetchAvailability(a,i.row,i.col,t))break}catch{}if(a--,s++,i=this.identifyPixelLocation(l,s,t.datumTransformation),null===i)return null}return-1===a||null==i?null:s}async _open(e){const r=e?.signal,a=this.sourceJSON?{data:this.sourceJSON}:await this.request(this.url,{query:{f:"json"},signal:r});a.ssl&&(this.url=this.url.replace(/^http:/i,"https:"));const l=a.data;if(this.sourceJSON=l,!l)throw new t("imageserverraster:open","cannot initialize tiled image service, missing service info");if(!l.tileInfo)throw new t("imageserverraster:open","use ImageryLayer to open non-tiled image services");this._fixScaleInServiceInfo();const n=["jpg","jpeg","png","png8","png24","png32","mixed"];this.tileType=l.cacheType,null==this.tileType&&(n.includes(l.tileInfo.format.toLowerCase())?this.tileType="Map":"lerc"===l.tileInfo.format.toLowerCase()?this.tileType="Elevation":this.tileType="Raster"),this.datasetName=l.name?.slice(l.name.indexOf("/")+1)??"";const o=await this._fetchRasterInfo({signal:r});if(null==o)throw new t("image-server-raster:open","cannot initialize image service");y(o,l);const c="Map"===this.tileType?v(l.tileInfo,l):p.fromJSON(l.tileInfo);i(c);const[m,u]=this._computeMinMaxLOD(o,c),{extent:h,pixelSize:x}=o,g=.001*Math.min(x.x,x.y);(x.x!==x.y||Math.abs(m.resolution-x.x)>g)&&(x.x=x.y=m.resolution,o.width=Math.ceil((h.xmax-h.xmin)/x.x-.1),o.height=Math.ceil((h.ymax-h.ymin)/x.y-.1));const I=m.level-u.level,[w,b]=c.size,T=[],M=[],{lods:_}=c;_.forEach((e,t)=>{e.level>=u.level&&e.level<=m.level&&T.push({x:e.resolution,y:e.resolution}),t<_.length-1&&M.push(Math.round(10*e.resolution/_[t+1].resolution)/10)}),T.sort((e,t)=>e.x-t.x);const j=this.computeBlockBoundary(h,w,b,c.origin,T,I),O=T.length>1?T.slice(1):null;let R;l.transposeInfo&&(R={tileSize:[l.transposeInfo.rows,l.transposeInfo.cols],packetSize:o.keyProperties?._yxs.PacketSize??0});const z=M.length<=1||M.length>=3&&M.slice(0,-1).every(e=>e===M[0])?M[0]??2:Math.round(10/(u.resolution/m.resolution)**(-1/I))/10,N=!!l.bsq&&"Raster"===this.tileType;if(o.storageInfo=new f({blockWidth:c.size[0],blockHeight:c.size[1],pyramidBlockWidth:c.size[0],pyramidBlockHeight:c.size[1],pyramidResolutions:O,pyramidScalingFactor:z,compression:c.format,origin:c.origin,firstPyramidLevel:1,maximumPyramidLevel:I,tileInfo:c,isBsqTile:N,transposeInfo:R,blockBoundary:j}),S(o),this._set("rasterInfo",o),l.capabilities.toLowerCase().includes("tilemap")){const e={tileInfo:o.storageInfo.tileInfo,parsedUrl:s(this.url),url:this.url,tileServers:[]};this._tilemapCache=new d({layer:e})}}async _fetchRasterInfo(e){const t=this.sourceJSON;if("Map"===this.tileType){const e=t.fullExtent||t.extent,i=Math.ceil((e.xmax-e.xmin)/t.pixelSizeX-.1),s=Math.ceil((e.ymax-e.ymin)/t.pixelSizeY-.1),r=o.fromJSON(t.spatialReference||e.spatialReference),a=new n({x:t.pixelSizeX,y:t.pixelSizeY,spatialReference:r});return new h({width:i,height:s,bandCount:3,extent:l.fromJSON(e),spatialReference:r,pixelSize:a,pixelType:"u8",statistics:null,keyProperties:{DataType:"processed"}})}const i={...e,query:{...this.ioConfig.customFetchParameters,f:"json"}},s=x(this.url,this.sourceJSON,i),r=t.hasMultidimensions?this.request(`${this.url}/slices`,i).then(e=>e.data?.slices).catch(()=>null):null,a=await Promise.all([s,r]);return this._slices=a[1],a[0]}_fixScaleInServiceInfo(){const{sourceJSON:e}=this;e.minScale&&e.minScale<0&&(e.minScale=0),e.maxScale&&e.maxScale<0&&(e.maxScale=0)}_computeMinMaxLOD(e,t){const{pixelSize:i}=e,s=.5/e.width*i.x,{lods:r}=t,a=t.lodAt(Math.max.apply(null,r.map(e=>e.level))),l=t.lodAt(Math.min.apply(null,r.map(e=>e.level))),{tileType:n}=this;if("Map"===n)return this._levelOffset=r[0].level,[a,l];if("Raster"===n){return[r.find(e=>e.resolution===i.x)??a,l]}const{minScale:o,maxScale:c}=this.sourceJSON;let m=a;c>0&&(m=r.find(e=>Math.abs(e.scale-c)<s),m||(m=r.filter(e=>e.scale>c).sort((e,t)=>e.scale>t.scale?1:-1)[0]??a));let u=l;return o>0&&(u=r.find(e=>Math.abs(e.scale-o)<s)??l,this._levelOffset=u.level-l.level),[m,u]}};function v(e,t){if(!e)return null;const{minScale:i,maxScale:s,minLOD:r,maxLOD:a}=t;if(null!=r&&null!=a)return p.fromJSON({...e,lods:e.lods.filter(({level:e})=>null!=e&&e>=r&&e<=a)});if(0!==i&&0!==s){const t=e=>Math.round(1e4*e)/1e4,r=i?t(i):1/0,a=s?t(s):-1/0;return p.fromJSON({...e,lods:e.lods.filter(e=>{const i=t(e.scale);return i<=r&&i>=a})})}return p.fromJSON(e)}function S(e){const{extent:t,spatialReference:i}=e;t.xmin>-1&&t.xmax>181&&i?.wkid&&i.isGeographic&&(e.nativeExtent=e.extent,e.transform=new u,e.extent=e.transform.forwardTransform(t))}e([r({type:String,json:{write:!0}})],g.prototype,"datasetFormat",void 0),e([r()],g.prototype,"tileType",void 0),g=e([a("esri.layers.raster.datasets.ImageServerRaster")],g);const I=g;export{I as default};
2
+ import{__decorate as e}from"tslib";import t from"../../../core/Error.js";import{assertIsSome as i}from"../../../core/maybe.js";import{urlToObject as s}from"../../../core/urlUtils.js";import{property as r,subclass as a}from"../../../core/accessorSupport/decorators.js";import l from"../../../geometry/Extent.js";import n from"../../../geometry/Point.js";import o from"../../../geometry/SpatialReference.js";import c from"./BaseRaster.js";import{setValidBoundary as m}from"../functions/pixelUtils.js";import u from"../transforms/GCSShiftTransform.js";import f from"../../support/RasterInfo.js";import h from"../../support/RasterStorageInfo.js";import p from"../../support/TileInfo.js";import{TilemapCache as d}from"../../support/TilemapCache.js";import{patchServiceInfo as y,fetchServiceRasterInfo as x}from"../../../rest/imageService/fetchRasterInfo.js";let g=class extends c{constructor(){super(...arguments),this._levelOffset=0,this._tilemapCache=null,this._slices=null,this.datasetFormat="RasterTileServer",this.tileType=null}async fetchRawTile(e,t,i,s={}){const{storageInfo:r,extent:a}=this.rasterInfo,{transposeInfo:l}=r,n=null!=l&&!!s.transposedVariableName;if(this._slices&&!n&&null==s.sliceId)return null;const o=n?0:r.maximumPyramidLevel-e+this._levelOffset,c=`${this.url}/tile/${o}/${t}/${i}`,u={...this._slices?n?{variable:s.transposedVariableName}:{sliceId:s.sliceId||0}:null,...s.refreshParameters};let f,h;if(r.isBsqTile){const e=(s.bandIds?.length?s.bandIds:[0,1,2]).map(e=>this.request(c,{query:{...u,bandId:e},responseType:"array-buffer",signal:s.signal})),t=await Promise.all(e),i=t.map(e=>e.data.byteLength).reduce((e,t)=>e+t),r=new Uint8Array(i);h=[];let a=0;for(const{data:s}of t)h.push(a),r.set(new Uint8Array(s),a),a+=s.byteLength;f=r.buffer}else{f=(await this.request(c,{query:u,responseType:"array-buffer",signal:s.signal})).data}if(!f)return null;const{tileInfo:p}=r,d=n?l.tileSize:p.size,y=/^(mixed|jp)/i.test(p.format),x=await this.decodePixelBlock(f,{width:d[0],height:d[1],planes:h?.length,offsets:h,pixelType:null,isPoint:"Elevation"===this.tileType,returnInterleaved:n,noDataValue:this.rasterInfo.noDataValue,applyJpegMask:y});if(null==x)return null;const g=r.blockBoundary[e];if("jpg"!==r.compression||i>g.minCol&&i<g.maxCol&&t>g.minRow&&t<g.maxRow)return x;const{origin:v,blockWidth:S,blockHeight:I}=r,{x:w,y:b}=this.getPyramidPixelSize(e),T=Math.round((a.xmin-v.x)/w)%S,M=Math.round((a.xmax-v.x)/w)%S||S,_=Math.round((v.y-a.ymax)/b)%I,j=Math.round((v.y-a.ymin)/b)%I||I,O=i===g.minCol?T:0,R=t===g.minRow?_:0,z=i===g.maxCol?M:S,N=t===g.maxRow?j:I;return m(x,{x:O,y:R},{width:z-O,height:N-R}),x}getSliceIndex(e){if(!this._slices||null==e||0===e.length)return null;const t=e;for(let i=0;i<this._slices.length;i++){const e=this._slices[i].multidimensionalDefinition;if(e.length===t.length&&!e.some(e=>{const i=t.find(t=>e.variableName===t.variableName&&t.dimensionName===e.dimensionName);if(!i)return!0;return(Array.isArray(e.values[0])?`${e.values[0][0]}-${e.values[0][1]}`:e.values[0])!==(Array.isArray(i.values[0])?`${i.values[0][0]}-${i.values[0][1]}`:i.values[0])}))return i}return null}async fetchVariableStatisticsHistograms(e,t){const i=this.request(this.url+"/statistics",{query:{variable:e,f:"json"},signal:t}).then(e=>e.data?.statistics),s=this.request(this.url+"/histograms",{query:{variable:e,f:"json"},signal:t}).then(e=>e.data?.histograms),r=await Promise.all([i,s]);return r[0]&&r[0].forEach(e=>{e.avg=e.mean,e.stddev=e.standardDeviation}),r[1]?.[0]?.counts?.length||(r[1]=null),{statistics:r[0]||null,histograms:r[1]||null}}async computeBestPyramidLevelForLocation(e,t={}){if(!this._tilemapCache)return 0;let i=this.identifyPixelLocation(e,0,t.datumTransformation);if(null===i)return null;let s=0;const{maximumPyramidLevel:r}=this.rasterInfo.storageInfo;let a=r-s+this._levelOffset;const l=i.srcLocation;for(;a>=0;){try{if("available"===await this._tilemapCache.fetchAvailability(a,i.row,i.col,t))break}catch{}if(a--,s++,i=this.identifyPixelLocation(l,s,t.datumTransformation),null===i)return null}return-1===a||null==i?null:s}async _open(e){const r=e?.signal,a=this.sourceJSON?{data:this.sourceJSON}:await this.request(this.url,{query:{f:"json"},signal:r});a.ssl&&(this.url=this.url.replace(/^http:/i,"https:"));const l=a.data;if(this.sourceJSON=l,!l)throw new t("imageserverraster:open","cannot initialize tiled image service, missing service info");if(!l.tileInfo)throw new t("imageserverraster:open","use ImageryLayer to open non-tiled image services");this._fixScaleInServiceInfo();const n=["jpg","jpeg","png","png8","png24","png32","mixed"];this.tileType=l.cacheType,null==this.tileType&&(n.includes(l.tileInfo.format.toLowerCase())?this.tileType="Map":"lerc"===l.tileInfo.format.toLowerCase()?this.tileType="Elevation":this.tileType="Raster"),this.datasetName=l.name?.slice(l.name.indexOf("/")+1)??"";const o=await this._fetchRasterInfo({signal:r});if(null==o)throw new t("image-server-raster:open","cannot initialize image service");y(o,l);const c="Map"===this.tileType?v(l.tileInfo,l):p.fromJSON(l.tileInfo);i(c);const[m,u]=this._computeMinMaxLOD(o,c),{extent:f,pixelSize:x}=o,g=.001*Math.min(x.x,x.y);(x.x!==x.y||Math.abs(m.resolution-x.x)>g)&&(x.x=x.y=m.resolution,o.width=Math.ceil((f.xmax-f.xmin)/x.x-.1),o.height=Math.ceil((f.ymax-f.ymin)/x.y-.1));const I=m.level-u.level,[w,b]=c.size,T=[],M=[],{lods:_}=c;_.forEach((e,t)=>{e.level>=u.level&&e.level<=m.level&&T.push({x:e.resolution,y:e.resolution}),t<_.length-1&&M.push(Math.round(10*e.resolution/_[t+1].resolution)/10)}),T.sort((e,t)=>e.x-t.x);const j=this.computeBlockBoundary(f,w,b,c.origin,T,I),O=T.length>1?T.slice(1):null;let R;l.transposeInfo&&(R={tileSize:[l.transposeInfo.rows,l.transposeInfo.cols],packetSize:o.keyProperties?._yxs.PacketSize??0});const z=M.length<=1||M.length>=3&&M.slice(0,-1).every(e=>e===M[0])?M[0]??2:Math.round(10/(u.resolution/m.resolution)**(-1/I))/10,N=!!l.bsq&&"Raster"===this.tileType;if(o.storageInfo=new h({blockWidth:c.size[0],blockHeight:c.size[1],pyramidBlockWidth:c.size[0],pyramidBlockHeight:c.size[1],pyramidResolutions:O,pyramidScalingFactor:z,compression:c.format,origin:c.origin,firstPyramidLevel:1,maximumPyramidLevel:I,tileInfo:c,isBsqTile:N,transposeInfo:R,blockBoundary:j}),S(o),this._set("rasterInfo",o),l.capabilities.toLowerCase().includes("tilemap")){const e={tileInfo:o.storageInfo.tileInfo,parsedUrl:s(this.url),url:this.url,tileServers:[]};this._tilemapCache=new d({layer:e})}}async _fetchRasterInfo(e){const t=this.sourceJSON;if("Map"===this.tileType){const e=t.fullExtent||t.extent,i=Math.ceil((e.xmax-e.xmin)/t.pixelSizeX-.1),s=Math.ceil((e.ymax-e.ymin)/t.pixelSizeY-.1),r=o.fromJSON(t.spatialReference||e.spatialReference),a=new n({x:t.pixelSizeX,y:t.pixelSizeY,spatialReference:r});return new f({width:i,height:s,bandCount:3,extent:l.fromJSON(e),spatialReference:r,pixelSize:a,pixelType:"u8",statistics:null,keyProperties:{DataType:"processed"}})}const i={...e,query:{...this.ioConfig.customFetchParameters,f:"json"}},s=x(this.url,this.sourceJSON,i),r=t.hasMultidimensions?this.request(`${this.url}/slices`,i).then(e=>e.data?.slices).catch(()=>null):null,a=await Promise.all([s,r]);return this._slices=a[1],a[0]}_fixScaleInServiceInfo(){const{sourceJSON:e}=this;e.minScale&&e.minScale<0&&(e.minScale=0),e.maxScale&&e.maxScale<0&&(e.maxScale=0)}_computeMinMaxLOD(e,t){const{pixelSize:i}=e,s=.5/e.width*i.x,{lods:r}=t,a=t.lodAt(Math.max.apply(null,r.map(e=>e.level))),l=t.lodAt(Math.min.apply(null,r.map(e=>e.level))),{tileType:n}=this;if("Map"===n)return this._levelOffset=r[0].level,[a,l];if("Raster"===n){return[r.find(e=>e.resolution===i.x)??a,l]}const{minScale:o,maxScale:c}=this.sourceJSON;let m=a;c>0&&(m=r.find(e=>Math.abs(e.scale-c)<s),m||(m=r.filter(e=>e.scale>c).sort((e,t)=>e.scale>t.scale?1:-1)[0]??a));let u=l;return o>0&&(u=r.find(e=>Math.abs(e.scale-o)<s)??l,this._levelOffset=u.level-l.level),[m,u]}};function v(e,t){if(!e)return null;const{minScale:i,maxScale:s,minLOD:r,maxLOD:a}=t;if(null!=r&&null!=a)return p.fromJSON({...e,lods:e.lods.filter(({level:e})=>null!=e&&e>=r&&e<=a)});if(0!==i&&0!==s){const t=e=>Math.round(1e4*e)/1e4,r=i?t(i):1/0,a=s?t(s):-1/0;return p.fromJSON({...e,lods:e.lods.filter(e=>{const i=t(e.scale);return i<=r&&i>=a})})}return p.fromJSON(e)}function S(e){const{extent:t,spatialReference:i}=e;t.xmin>-1&&t.xmax>181&&i?.wkid&&i.isGeographic&&(e.nativeExtent=e.extent,e.transform=new u,e.extent=e.transform.forwardTransform(t))}e([r({type:String,json:{write:!0}})],g.prototype,"datasetFormat",void 0),e([r()],g.prototype,"tileType",void 0),g=e([a("esri.layers.raster.datasets.ImageServerRaster")],g);const I=g;export{I as default};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import t from"../../../core/Error.js";import{isAborted as e,createAbortError as a}from"../../../core/promiseUtils.js";import{F as n}from"../../../chunks/Zlib.js";class i{constructor(t){this._canvas=null,this._ctx=null,t&&(this._canvas=t.canvas,this._ctx=t.ctx||t.canvas&&t.canvas.getContext("2d"))}decode(n,s,r){if(!n||n.byteLength<10)throw new t("imagecanvasdecoder: decode","required a valid encoded data as input.");let{width:c=0,height:h=0,format:o}=s;const{applyJpegMask:l}=s;if(l&&(!c||!h))throw new t("imagecanvasdecoder: decode","image width and height are needed to apply jpeg mask directly to canvas");return new Promise((t,d)=>{let g=null;"jpg"===o&&l&&(g=i._getMask(n,{width:c,height:h}));const w=new Blob([new Uint8Array(n)],{type:"image/"+o=="jpg"?"jpeg":o}),v=URL.createObjectURL(w),m=new Image;m.src=v,m.onload=()=>{if(URL.revokeObjectURL(v),e(r))return void d(a());c=m.width,h=m.height,this._canvas&&this._ctx?(this._canvas.width===c&&this._canvas.height===h||(this._canvas.width=c,this._canvas.height=h),this._ctx.clearRect(0,0,c,h)):(this._canvas=document.createElement("canvas"),this._canvas.width=c,this._canvas.height=h,this._ctx=this._canvas.getContext("2d")),this._ctx.drawImage(m,0,0);const n=this._ctx.getImageData(0,0,c,h),i=n.data;if(s.renderOnCanvas){if(g)for(let t=0;t<g.length;t++)g[t]?i[4*t+3]=255:i[4*t+3]=0;return this._ctx.putImageData(n,0,0),void t(null)}const o=c*h,l=new Uint8Array(o),w=new Uint8Array(o),_=new Uint8Array(o);if(g)for(let t=0;t<o;t++)l[t]=i[4*t],w[t]=i[4*t+1],_[t]=i[4*t+2];else{g=new Uint8Array(o);for(let t=0;t<o;t++)l[t]=i[4*t],w[t]=i[4*t+1],_[t]=i[4*t+2],g[t]=i[4*t+3]}t({width:c,height:h,pixels:[l,w,_],mask:g,pixelType:"u8"})},m.onerror=()=>{URL.revokeObjectURL(v),d("cannot load image")}})}static _getMask(t,e){let a=null;try{const i=new Uint8Array(t),s=Math.ceil(i.length/2);let r=0;const c=i.length-2;for(r=s;r<c&&(255!==i[r]||217!==i[r+1]);r++);if(r+=2,r<i.length-1){const t=new n(i.subarray(r)).getBytes();a=new Uint8Array(e.width*e.height);let s=0;for(let e=0;e<t.length;e++)for(let n=7;n>=0;n--)a[s++]=t[e]>>n&1}}catch(i){}return a}}export{i as default};
2
+ import e from"../../../core/Error.js";import{isAborted as t,createAbortError as a}from"../../../core/promiseUtils.js";import{F as n}from"../../../chunks/Zlib.js";async function r(n,r,o){if(!n||n.byteLength<10)throw new e("imagecanvasdecoder: decode","required a valid encoded data as input.");let{width:h,height:c,format:d}=r;const{applyJpegMask:l}=r;if(l&&(!h||!c))throw new e("imagecanvasdecoder: decode","image width and height are needed to apply jpeg mask directly to canvas");let g=null;"jpg"===d&&l&&h&&c&&(g=i(n,{width:h,height:c}));try{const e=new Blob([new Uint8Array(n)],{type:"image/"+d=="jpg"?"jpeg":d}),r=await createImageBitmap(e);if(t(o))throw a();h=r.width,c=r.height;const i=new OffscreenCanvas(h,c),l=i.getContext("2d");l.drawImage(r,0,0);const s=l.getImageData(0,0,h,c).data,w=h*c,m=new Uint8Array(w),p=new Uint8Array(w),f=new Uint8Array(w);if(g)for(let t=0;t<w;t++)m[t]=s[4*t],p[t]=s[4*t+1],f[t]=s[4*t+2];else{g=new Uint8Array(w);for(let e=0;e<w;e++)m[e]=s[4*e],p[e]=s[4*e+1],f[e]=s[4*e+2],g[e]=s[4*e+3]}return i.width=0,i.height=0,{width:h,height:c,pixels:[m,p,f],mask:g,pixelType:"u8"}}catch{throw new e("imagecanvasdecoder: decode","cannot load image")}}function i(e,t){try{const a=new Uint8Array(e);let r=Math.ceil(a.length/2);const i=a.length-2;for(;r<i&&(255!==a[r]||217!==a[r+1]);r++);r+=2;let o=null;if(r<a.length-1){const e=new n(a.subarray(r)).getBytes();o=new Uint8Array(t.width*t.height);let i=0;for(let t=0;t<e.length;t++)for(let a=7;a>=0;a--)o[i++]=e[t]>>a&1}return o}catch{return null}}export{r as decode};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import{J as t}from"../../../chunks/Jpg.js";import{F as e}from"../../../chunks/Zlib.js";class r{static decode(r,n=!1){const s=new Uint8Array(r),l=new t;l.parse(s);const{width:o,height:a,numComponents:i,eof:f}=l,h=l.getData(o,a,!0),c=o*a;let u,g=null;if(!n&&f<s.length-1)try{const t=new e(s.subarray(f)).getBytes();g=new Uint8Array(c);let r=0;for(let e=0;e<t.length;e++)for(let n=7;n>=0;n--)g[r++]=t[e]>>n&1}catch{}if(1===i&&h.length===o*a){const t=new Uint8Array(h.buffer);u=[t,t,t]}else{u=[];for(let e=0;e<3;e++)u.push(new Uint8Array(c));let t=0;for(let e=0;e<c;e++)for(let r=0;r<3;r++)u[r][e]=h[t++]}return{width:o,height:a,pixels:u,mask:g}}}export{r as default};
2
+ import{J as t}from"../../../chunks/Jpg.js";import{F as e}from"../../../chunks/Zlib.js";class r{static decode(r,n=!1){const s=new Uint8Array(r),l=new t;l.parse(s);const{width:o,height:a,numComponents:i,eof:f}=l,h=l.getData(o,a,!0),c=o*a;let u,g=null;if(n&&f<s.length-1)try{const t=new e(s.subarray(f)).getBytes();g=new Uint8Array(c);let r=0;for(let e=0;e<t.length;e++)for(let n=7;n>=0;n--)g[r++]=t[e]>>n&1}catch{}if(1===i&&h.length===o*a){const t=new Uint8Array(h.buffer);u=[t,t,t]}else{u=[];for(let e=0;e<3;e++)u.push(new Uint8Array(c));let t=0;for(let e=0;e<c;e++)for(let r=0;r<3;r++)u[r][e]=h[t++]}return{width:o,height:a,pixels:u,mask:g}}}export{r as default};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import t from"../../../core/Error.js";import{assertIsSome as e}from"../../../core/maybe.js";import a from"./ImageCanvasDecoder.js";import i from"./JpgPlus.js";import{load as s,decode as r}from"./Lerc.js";import{decode as n}from"./Lzw.js";import{convertNoDataToMask as o}from"./pixelRangeUtils.js";import{F as h}from"../../../chunks/Zlib.js";import{load as c,decode as l}from"./Qb3.js";import p from"./Raw.js";import{decodeTileOrStrip as d,decode as u}from"./TiffDecoder.js";import{isPlatformLittleEndian as f}from"./utils.js";import m from"../../support/PixelBlock.js";import w from"../../support/SimpleBandStatistics.js";var g=function(t){var e,a,i,s,r,n;function o(t){var e,a,i,s,r,n,o,h,c,l,p,d,u;for(this.data=t,this.pos=8,this.palette=[],this.imgData=[],this.transparency={},this.animation=null,this.text={},r=null;;){switch(e=this.readUInt32(),h=function(){var t,e;for(e=[],t=0;t<4;++t)e.push(String.fromCharCode(this.data[this.pos++]));return e}.call(this).join(""),h){case"IHDR":this.width=this.readUInt32(),this.height=this.readUInt32(),this.bits=this.data[this.pos++],this.colorType=this.data[this.pos++],this.compressionMethod=this.data[this.pos++],this.filterMethod=this.data[this.pos++],this.interlaceMethod=this.data[this.pos++];break;case"acTL":this.animation={numFrames:this.readUInt32(),numPlays:this.readUInt32()||1/0,frames:[]};break;case"PLTE":this.palette=this.read(e);break;case"fcTL":r&&this.animation.frames.push(r),this.pos+=4,r={width:this.readUInt32(),height:this.readUInt32(),xOffset:this.readUInt32(),yOffset:this.readUInt32()},s=this.readUInt16(),i=this.readUInt16()||100,r.delay=1e3*s/i,r.disposeOp=this.data[this.pos++],r.blendOp=this.data[this.pos++],r.data=[];break;case"IDAT":case"fdAT":for("fdAT"===h&&(this.pos+=4,e-=4),t=(null!=r?r.data:void 0)||this.imgData,p=0;0<=e?p<e:p>e;0<=e?++p:--p)t.push(this.data[this.pos++]);break;case"tRNS":switch(this.transparency={},this.colorType){case 3:if(this.transparency.indexed=this.read(e),(c=255-this.transparency.indexed.length)>0)for(d=0;0<=c?d<c:d>c;0<=c?++d:--d)this.transparency.indexed.push(255);break;case 0:this.transparency.grayscale=this.read(e)[0];break;case 2:this.transparency.rgb=this.read(e)}break;case"tEXt":n=(l=this.read(e)).indexOf(0),o=String.fromCharCode.apply(String,l.slice(0,n)),this.text[o]=String.fromCharCode.apply(String,l.slice(n+1));break;case"IEND":return r&&this.animation.frames.push(r),this.colors=function(){switch(this.colorType){case 0:case 3:case 4:return 1;case 2:case 6:return 3}}.call(this),this.hasAlphaChannel=4===(u=this.colorType)||6===u,a=this.colors+(this.hasAlphaChannel?1:0),this.pixelBitlength=this.bits*a,this.colorSpace=function(){switch(this.colors){case 1:return"DeviceGray";case 3:return"DeviceRGB"}}.call(this),void(this.imgData=new Uint8Array(this.imgData));default:this.pos+=e}if(this.pos+=4,this.pos>this.data.length)throw new Error("Incomplete or corrupt PNG file")}}return o.load=function(t,e,a){var i;return"function"==typeof e&&(a=e),(i=new XMLHttpRequest).open("GET",t,!0),i.responseType="arraybuffer",i.onload=function(){var t;return t=new o(new Uint8Array(i.response||i.mozResponseArrayBuffer)),"function"==typeof(null!=e?e.getContext:void 0)&&t.render(e),"function"==typeof a?a(t):void 0},i.send(null)},a=1,i=2,e=0,o.prototype.read=function(t){var e,a;for(a=[],e=0;0<=t?e<t:e>t;0<=t?++e:--e)a.push(this.data[this.pos++]);return a},o.prototype.readUInt32=function(){return this.data[this.pos++]<<24|this.data[this.pos++]<<16|this.data[this.pos++]<<8|this.data[this.pos++]},o.prototype.readUInt16=function(){return this.data[this.pos++]<<8|this.data[this.pos++]},o.prototype.decodePixels=function(t){var e,a,i,s,r,n,o,c,l,p,d,u,f,m,w,g,y,x,b,k,T,C,I;if(null==t&&(t=this.imgData),0===t.length)return new Uint8Array(0);for(t=(t=new h(t)).getBytes(),g=(u=this.pixelBitlength/8)*this.width,f=new Uint8Array(g*this.height),n=t.length,w=0,m=0,a=0;m<n;){switch(t[m++]){case 0:for(s=b=0;b<g;s=b+=1)f[a++]=t[m++];break;case 1:for(s=k=0;k<g;s=k+=1)e=t[m++],r=s<u?0:f[a-u],f[a++]=(e+r)%256;break;case 2:for(s=T=0;T<g;s=T+=1)e=t[m++],i=(s-s%u)/u,y=w&&f[(w-1)*g+i*u+s%u],f[a++]=(y+e)%256;break;case 3:for(s=C=0;C<g;s=C+=1)e=t[m++],i=(s-s%u)/u,r=s<u?0:f[a-u],y=w&&f[(w-1)*g+i*u+s%u],f[a++]=(e+Math.floor((r+y)/2))%256;break;case 4:for(s=I=0;I<g;s=I+=1)e=t[m++],i=(s-s%u)/u,r=s<u?0:f[a-u],0===w?y=x=0:(y=f[(w-1)*g+i*u+s%u],x=i&&f[(w-1)*g+(i-1)*u+s%u]),o=r+y-x,c=Math.abs(o-r),p=Math.abs(o-y),d=Math.abs(o-x),l=c<=p&&c<=d?r:p<=d?y:x,f[a++]=(e+l)%256;break;default:throw new Error("Invalid filter algorithm: "+t[m-1])}w++}return f},o.prototype.decodePalette=function(){var t,e,a,i,s,r,n,o,h;for(a=this.palette,r=this.transparency.indexed||[],s=new Uint8Array((r.length||0)+a.length),i=0,a.length,t=0,e=n=0,o=a.length;n<o;e=n+=3)s[i++]=a[e],s[i++]=a[e+1],s[i++]=a[e+2],s[i++]=null!=(h=r[t++])?h:255;return s},o.prototype.copyToImageData=function(t,e){var a,i,s,r,n,o,h,c,l,p,d;if(i=this.colors,l=null,a=this.hasAlphaChannel,this.palette.length&&(l=null!=(d=this._decodedPalette)?d:this._decodedPalette=this.decodePalette(),i=4,a=!0),c=(s=t.data||t).length,n=l||e,r=o=0,1===i)for(;r<c;)h=l?4*e[r/4]:o,p=n[h++],s[r++]=p,s[r++]=p,s[r++]=p,s[r++]=a?n[h++]:this.transparency.grayscale&&this.transparency.grayscale===p?0:255,o=h;else for(;r<c;)h=l?4*e[r/4]:o,s[r++]=n[h++],s[r++]=n[h++],s[r++]=n[h++],s[r++]=a?n[h++]:this.transparency.rgb&&this.transparency.rgb[1]===n[h-3]&&this.transparency.rgb[3]===n[h-2]&&this.transparency.rgb[5]===n[h-1]?0:255,o=h},o.prototype.decode=function(){var t;return t=new Uint8Array(this.width*this.height*4),this.copyToImageData(t,this.decodePixels()),t},r=t.document&&t.document.createElement("canvas"),n=r&&r.getContext("2d"),s=function(t){var e;return n.width=t.width,n.height=t.height,n.clearRect(0,0,t.width,t.height),n.putImageData(t,0,0),(e=new Image).src=r.toDataURL(),e},o.prototype.decodeFrames=function(t){var e,a,i,r,n,o,h,c;if(this.animation){for(c=[],a=n=0,o=(h=this.animation.frames).length;n<o;a=++n)e=h[a],i=t.createImageData(e.width,e.height),r=this.decodePixels(new Uint8Array(e.data)),this.copyToImageData(i,r),e.imageData=i,c.push(e.image=s(i));return c}},o.prototype.renderFrame=function(t,s){var r,n,o;return r=(n=this.animation.frames)[s],o=n[s-1],0===s&&t.clearRect(0,0,this.width,this.height),(null!=o?o.disposeOp:void 0)===a?t.clearRect(o.xOffset,o.yOffset,o.width,o.height):(null!=o?o.disposeOp:void 0)===i&&t.putImageData(o.imageData,o.xOffset,o.yOffset),r.blendOp===e&&t.clearRect(r.xOffset,r.yOffset,r.width,r.height),t.drawImage(r.image,r.xOffset,r.yOffset)},o.prototype.animate=function(t){var e,a,i,s,r,n,o=this;return a=0,n=this.animation,s=n.numFrames,i=n.frames,r=n.numPlays,(e=function(){var n,h;if(n=a++%s,h=i[n],o.renderFrame(t,n),s>1&&a/s<r)return o.animation._timeout=setTimeout(e,h.delay)})()},o.prototype.stopAnimation=function(){var t;return clearTimeout(null!=(t=this.animation)?t._timeout:void 0)},o.prototype.render=function(t){var e,a;return t._png&&t._png.stopAnimation(),t._png=this,t.width=this.width,t.height=this.height,e=t.getContext("2d"),this.animation?(this.decodeFrames(e),this.animate(e)):(a=e.createImageData(this.width,this.height),this.copyToImageData(a,this.decodePixels()),e.putImageData(a,0,0))},o}(self);const y=new Set(["jpg","png","bmp","gif"]);async function x(e,a){if(!f)throw new t("rasterCoded:decode","lerc decoder is not supported on big endian platform");await s();const{offset:i}=a,{width:n,height:o,pixelType:h,statistics:c,depthCount:l,noDataValues:p,bandMasks:d,pixels:u,mask:g}=r(e,{inputOffset:i,returnInterleaved:a.returnInterleaved}),y=new m({width:n,height:o,pixelType:h.toLowerCase(),pixels:u,mask:g,statistics:c.map(({minValue:t,maxValue:e})=>new w(t,e)),bandMasks:d,depthCount:l,noDataValues:p});return c?.length||y.updateStatistics(),y}async function b(e,a){await c();const i=l(e);if(!i)throw new t("rasterCodec:decode","failed to decode the input data.");const{width:s,height:r,pixels:n,pixelType:o}=i,h=new m({width:s,height:r,pixelType:o,pixels:n});return h.updateStatistics(),h}async function k(t,a){const i=await u(t,{...a,noDataValue:a.tiffNoDataValue,matchAllNoData:a.matchAllNoData});e(i);const s=new m({width:i.width,height:i.height,pixels:i.pixels,pixelType:i.pixelType.toLowerCase(),mask:i.mask,bandMasks:i.bandMasks,statistics:null});return s.updateStatistics(),s}async function T(t,e){const a=await d(t,e.customOptions),i=new m({width:a.width,height:a.height,pixels:a.pixels,pixelType:a.pixelType.toLowerCase(),mask:a.mask,statistics:null});return i.updateStatistics(),i}function C(t,e){const a=e.pixelType||"u8",i=m.getPixelArrayConstructor(a),s="u8"===a?t:new i(t.buffer),r=[],n=e.planes||1;if(1===n)r.push(s);else for(let h=0;h<n;h++){const a=(e.width||1)*(e.height||t.length),o=new i(a);for(let t=0;t<a;t++)o[t]=s[t*n+h];r.push(o)}const o=new m({width:e.width||1,height:e.height||t.length,pixels:r,pixelType:a,statistics:null});return o.updateStatistics(),o}function I(t,e){return C(new h(new Uint8Array(t)).getBytes(),e)}function A(t,e){return C(n(t,e.offset,e.eof,!e.isInputBigEndian),e)}function v(t,e,a){const{pixelTypeCtor:i}=P(e.pixelType),s=(0,p.decode)(t,{width:e.width,height:e.height,pixelType:i,format:a}),r=new m({width:e.width,height:e.height,pixels:s.pixels,pixelType:e.pixelType,mask:s.mask,statistics:null});return r.updateStatistics(),r}function D(t,e){const a=i.decode(t,e.hasNoZlibMask??void 0),s=new m({width:a.width,height:a.height,pixels:a.pixels,pixelType:"u8",mask:a.mask,statistics:null});return s.updateStatistics(),s}function U(t,e){const a=new Uint8Array(t),i=new g(a),{width:s,height:r}=e,n=s*r,o=i.decode();let h,c=0,l=0;const p=new Uint8Array(n);for(c=0;c<n;c++)p[c]=o[4*c+3];const d=new m({width:s,height:r,pixels:[],pixelType:"u8",mask:p,statistics:[]});for(c=0;c<3;c++){for(h=new Uint8Array(n),l=0;l<n;l++)h[l]=o[4*l+c];d.addData({pixels:h})}return d.updateStatistics(),d}async function S(t,e,i,s){const r=new a,n={applyJpegMask:!1,format:e,...i},o=await r.decode(t,n,s),h=new m(o);return h.updateStatistics(),h}function j(e){if(null==e)throw new t("rasterCodec:decode","parameter encodeddata is required.");const a=new Uint8Array(e,0,10);let i="";return 255===a[0]&&216===a[1]?i="jpg":137===a[0]&&80===a[1]&&78===a[2]&&71===a[3]?i="png":67===a[0]&&110===a[1]&&116===a[2]&&90===a[3]&&73===a[4]&&109===a[5]&&97===a[6]&&103===a[7]&&101===a[8]&&32===a[9]?i="lerc":76===a[0]&&101===a[1]&&114===a[2]&&99===a[3]&&50===a[4]&&32===a[5]?i="lerc2":73===a[0]&&73===a[1]&&42===a[2]&&0===a[3]||77===a[0]&&77===a[1]&&0===a[2]&&42===a[3]||73===a[0]&&73===a[1]&&43===a[2]&&0===a[3]||77===a[0]&&77===a[1]&&0===a[2]&&43===a[3]?i="tiff":71===a[0]&&73===a[1]&&70===a[2]?i="gif":66===a[0]&&77===a[1]?i="bmp":81===a[0]&&66===a[1]&&51===a[2]?i="qb3":String.fromCharCode.apply(null,a).toLowerCase().includes("error")&&(i="error"),i}function O(e){let a=null;switch(e){case"lerc":case"lerc2":a=x;break;case"jpg":a=D;break;case"png":a=U;break;case"bsq":case"bip":a=(t,a)=>v(t,a,e);break;case"tiff":a=k;break;case"deflate":a=I;break;case"lzw":a=A;break;case"qb3":a=b;break;case"error":a=()=>{throw new t("rasterCodec:decode","input data contains error")};break;default:a=()=>{throw new t("rasterCodec:decode","unsupported raster format")}}return a}function P(t){let e=null,a=null;switch(t?t.toLowerCase():"f32"){case"u1":case"u2":case"u4":case"u8":a=255,e=Uint8Array;break;case"u16":a=a||65535,e=Uint16Array;break;case"u32":a=a||2**32-1,e=Uint32Array;break;case"s8":a=a||-128,e=Int8Array;break;case"s16":a=a||-32768,e=Int16Array;break;case"s32":a=a||0-2**31,e=Int32Array;break;default:e=Float32Array}return{pixelTypeCtor:e,noDataValue:a}}function M(t,e=1){if(!t)return;const{pixels:a,width:i,height:s,mask:r}=t;if(!a||0===a.length)return;const n=i-1,o=s-1,h=[];let c=null;const l=m.getPixelArrayConstructor(t.pixelType);if(0===e){for(const t of a){const e=new l(n*o);for(let a=0;a<o;a++){const s=a*i;for(let i=0;i<n;i++)e[a*n+i]=t[s+i]}h.push(e)}if(null!=r){c=new Uint8Array(n*o);for(let t=0;t<o;t++){const e=t*i;for(let a=0;a<n;a++)c[t*n+a]=r[e+a]}}}else{for(const t of a){const e=new l(n*o);for(let a=0;a<o;a++){const s=a*i;for(let r=0;r<n;r++)e[a*n+r]=(t[s+r]+t[s+r+1]+t[s+i+r]+t[s+i+r+1])/4}h.push(e)}if(r){c=new Uint8Array(n*o);for(let t=0;t<o;t++){const e=t*i;for(let a=0;a<n;a++)c[t*n+a]=Math.min.apply(null,[r[e+a],r[e+a+1],r[e+i+a],r[e+i+a+1]])}}}t.width=n,t.height=o,t.mask=c,t.pixels=h}function L(t){let e=j(t);return"lerc2"===e?e="lerc":"error"===e&&(e=""),e}async function R(e,a={},i){if(null==e)throw new t("rasterCodec:decode","missing encodeddata parameter.");let s=a.format?.toLowerCase();if(!("bsq"!==s&&"bip"!==s||null!=a.width&&null!=a.height))throw new t("rasterCodec:decode","requires width and height in options parameter.");if("tiff"===s&&a.customOptions)return T(e,a);if((!s||"bsq"!==s&&"bip"!==s&&"deflate"!==s&&"lzw"!==s)&&(s=j(e)),a.useCanvas&&y.has(s))return S(e,s,a,i);const r=O(s);let n;a.isPoint&&(null!=(a={...a}).width&&a.width++,null!=a.height&&a.height++);const{offsets:h}=a;if(h&&h.length>1){const t=h.map((t,i)=>r(e.slice(t,h[i+1]),a)),i=await Promise.all(t);n=i[0],n.pixels=i.map(t=>t.pixels[0]);const s=i.map(t=>t.mask);i.some(t=>null!=t)&&(s.forEach((t,e)=>{null==t&&(s[e]=new Uint8Array(n.width*n.height).fill(255))}),n.bandMasks=s,n.mask=m.combineBandMasks(s)),n.updateStatistics()}else n=await r(e,{...a,offset:h?.[0]??a.offset});return"jpg"!==s&&null!=a.noDataValue&&1===n.depthCount&&o(n,a.noDataValue,{customFloatTolerance:a.tolerance}),a.isPoint&&M(n),n}export{R as decode,L as getFormat};
2
+ import t from"../../../core/Error.js";import{assertIsSome as e}from"../../../core/maybe.js";import{isAbortError as a}from"../../../core/promiseUtils.js";import{decode as i}from"./ImageCanvasDecoder.js";import s from"./JpgPlus.js";import{load as r,decode as n}from"./Lerc.js";import{decode as o}from"./Lzw.js";import{convertNoDataToMask as h}from"./pixelRangeUtils.js";import{F as c}from"../../../chunks/Zlib.js";import{load as l,decode as p}from"./Qb3.js";import d from"./Raw.js";import{decodeTileOrStrip as u,decode as f}from"./TiffDecoder.js";import{isPlatformLittleEndian as m}from"./utils.js";import w from"../../support/PixelBlock.js";import g from"../../support/SimpleBandStatistics.js";var y=function(t){var e,a,i,s,r,n;function o(t){var e,a,i,s,r,n,o,h,c,l,p,d,u;for(this.data=t,this.pos=8,this.palette=[],this.imgData=[],this.transparency={},this.animation=null,this.text={},r=null;;){switch(e=this.readUInt32(),h=function(){var t,e;for(e=[],t=0;t<4;++t)e.push(String.fromCharCode(this.data[this.pos++]));return e}.call(this).join(""),h){case"IHDR":this.width=this.readUInt32(),this.height=this.readUInt32(),this.bits=this.data[this.pos++],this.colorType=this.data[this.pos++],this.compressionMethod=this.data[this.pos++],this.filterMethod=this.data[this.pos++],this.interlaceMethod=this.data[this.pos++];break;case"acTL":this.animation={numFrames:this.readUInt32(),numPlays:this.readUInt32()||1/0,frames:[]};break;case"PLTE":this.palette=this.read(e);break;case"fcTL":r&&this.animation.frames.push(r),this.pos+=4,r={width:this.readUInt32(),height:this.readUInt32(),xOffset:this.readUInt32(),yOffset:this.readUInt32()},s=this.readUInt16(),i=this.readUInt16()||100,r.delay=1e3*s/i,r.disposeOp=this.data[this.pos++],r.blendOp=this.data[this.pos++],r.data=[];break;case"IDAT":case"fdAT":for("fdAT"===h&&(this.pos+=4,e-=4),t=(null!=r?r.data:void 0)||this.imgData,p=0;0<=e?p<e:p>e;0<=e?++p:--p)t.push(this.data[this.pos++]);break;case"tRNS":switch(this.transparency={},this.colorType){case 3:if(this.transparency.indexed=this.read(e),(c=255-this.transparency.indexed.length)>0)for(d=0;0<=c?d<c:d>c;0<=c?++d:--d)this.transparency.indexed.push(255);break;case 0:this.transparency.grayscale=this.read(e)[0];break;case 2:this.transparency.rgb=this.read(e)}break;case"tEXt":n=(l=this.read(e)).indexOf(0),o=String.fromCharCode.apply(String,l.slice(0,n)),this.text[o]=String.fromCharCode.apply(String,l.slice(n+1));break;case"IEND":return r&&this.animation.frames.push(r),this.colors=function(){switch(this.colorType){case 0:case 3:case 4:return 1;case 2:case 6:return 3}}.call(this),this.hasAlphaChannel=4===(u=this.colorType)||6===u,a=this.colors+(this.hasAlphaChannel?1:0),this.pixelBitlength=this.bits*a,this.colorSpace=function(){switch(this.colors){case 1:return"DeviceGray";case 3:return"DeviceRGB"}}.call(this),void(this.imgData=new Uint8Array(this.imgData));default:this.pos+=e}if(this.pos+=4,this.pos>this.data.length)throw new Error("Incomplete or corrupt PNG file")}}return o.load=function(t,e,a){var i;return"function"==typeof e&&(a=e),(i=new XMLHttpRequest).open("GET",t,!0),i.responseType="arraybuffer",i.onload=function(){var t;return t=new o(new Uint8Array(i.response||i.mozResponseArrayBuffer)),"function"==typeof(null!=e?e.getContext:void 0)&&t.render(e),"function"==typeof a?a(t):void 0},i.send(null)},a=1,i=2,e=0,o.prototype.read=function(t){var e,a;for(a=[],e=0;0<=t?e<t:e>t;0<=t?++e:--e)a.push(this.data[this.pos++]);return a},o.prototype.readUInt32=function(){return this.data[this.pos++]<<24|this.data[this.pos++]<<16|this.data[this.pos++]<<8|this.data[this.pos++]},o.prototype.readUInt16=function(){return this.data[this.pos++]<<8|this.data[this.pos++]},o.prototype.decodePixels=function(t){var e,a,i,s,r,n,o,h,l,p,d,u,f,m,w,g,y,x,b,k,T,I,A;if(null==t&&(t=this.imgData),0===t.length)return new Uint8Array(0);for(t=(t=new c(t)).getBytes(),g=(u=this.pixelBitlength/8)*this.width,f=new Uint8Array(g*this.height),n=t.length,w=0,m=0,a=0;m<n;){switch(t[m++]){case 0:for(s=b=0;b<g;s=b+=1)f[a++]=t[m++];break;case 1:for(s=k=0;k<g;s=k+=1)e=t[m++],r=s<u?0:f[a-u],f[a++]=(e+r)%256;break;case 2:for(s=T=0;T<g;s=T+=1)e=t[m++],i=(s-s%u)/u,y=w&&f[(w-1)*g+i*u+s%u],f[a++]=(y+e)%256;break;case 3:for(s=I=0;I<g;s=I+=1)e=t[m++],i=(s-s%u)/u,r=s<u?0:f[a-u],y=w&&f[(w-1)*g+i*u+s%u],f[a++]=(e+Math.floor((r+y)/2))%256;break;case 4:for(s=A=0;A<g;s=A+=1)e=t[m++],i=(s-s%u)/u,r=s<u?0:f[a-u],0===w?y=x=0:(y=f[(w-1)*g+i*u+s%u],x=i&&f[(w-1)*g+(i-1)*u+s%u]),o=r+y-x,h=Math.abs(o-r),p=Math.abs(o-y),d=Math.abs(o-x),l=h<=p&&h<=d?r:p<=d?y:x,f[a++]=(e+l)%256;break;default:throw new Error("Invalid filter algorithm: "+t[m-1])}w++}return f},o.prototype.decodePalette=function(){var t,e,a,i,s,r,n,o,h;for(a=this.palette,r=this.transparency.indexed||[],s=new Uint8Array((r.length||0)+a.length),i=0,a.length,t=0,e=n=0,o=a.length;n<o;e=n+=3)s[i++]=a[e],s[i++]=a[e+1],s[i++]=a[e+2],s[i++]=null!=(h=r[t++])?h:255;return s},o.prototype.copyToImageData=function(t,e){var a,i,s,r,n,o,h,c,l,p,d;if(i=this.colors,l=null,a=this.hasAlphaChannel,this.palette.length&&(l=null!=(d=this._decodedPalette)?d:this._decodedPalette=this.decodePalette(),i=4,a=!0),c=(s=t.data||t).length,n=l||e,r=o=0,1===i)for(;r<c;)h=l?4*e[r/4]:o,p=n[h++],s[r++]=p,s[r++]=p,s[r++]=p,s[r++]=a?n[h++]:this.transparency.grayscale&&this.transparency.grayscale===p?0:255,o=h;else for(;r<c;)h=l?4*e[r/4]:o,s[r++]=n[h++],s[r++]=n[h++],s[r++]=n[h++],s[r++]=a?n[h++]:this.transparency.rgb&&this.transparency.rgb[1]===n[h-3]&&this.transparency.rgb[3]===n[h-2]&&this.transparency.rgb[5]===n[h-1]?0:255,o=h},o.prototype.decode=function(){var t;return t=new Uint8Array(this.width*this.height*4),this.copyToImageData(t,this.decodePixels()),t},r=t.document&&t.document.createElement("canvas"),n=r&&r.getContext("2d"),s=function(t){var e;return n.width=t.width,n.height=t.height,n.clearRect(0,0,t.width,t.height),n.putImageData(t,0,0),(e=new Image).src=r.toDataURL(),e},o.prototype.decodeFrames=function(t){var e,a,i,r,n,o,h,c;if(this.animation){for(c=[],a=n=0,o=(h=this.animation.frames).length;n<o;a=++n)e=h[a],i=t.createImageData(e.width,e.height),r=this.decodePixels(new Uint8Array(e.data)),this.copyToImageData(i,r),e.imageData=i,c.push(e.image=s(i));return c}},o.prototype.renderFrame=function(t,s){var r,n,o;return r=(n=this.animation.frames)[s],o=n[s-1],0===s&&t.clearRect(0,0,this.width,this.height),(null!=o?o.disposeOp:void 0)===a?t.clearRect(o.xOffset,o.yOffset,o.width,o.height):(null!=o?o.disposeOp:void 0)===i&&t.putImageData(o.imageData,o.xOffset,o.yOffset),r.blendOp===e&&t.clearRect(r.xOffset,r.yOffset,r.width,r.height),t.drawImage(r.image,r.xOffset,r.yOffset)},o.prototype.animate=function(t){var e,a,i,s,r,n,o=this;return a=0,n=this.animation,s=n.numFrames,i=n.frames,r=n.numPlays,(e=function(){var n,h;if(n=a++%s,h=i[n],o.renderFrame(t,n),s>1&&a/s<r)return o.animation._timeout=setTimeout(e,h.delay)})()},o.prototype.stopAnimation=function(){var t;return clearTimeout(null!=(t=this.animation)?t._timeout:void 0)},o.prototype.render=function(t){var e,a;return t._png&&t._png.stopAnimation(),t._png=this,t.width=this.width,t.height=this.height,e=t.getContext("2d"),this.animation?(this.decodeFrames(e),this.animate(e)):(a=e.createImageData(this.width,this.height),this.copyToImageData(a,this.decodePixels()),e.putImageData(a,0,0))},o}(self);const x=new Set(["jpg","png","bmp","gif"]);async function b(e,a){if(!m)throw new t("rasterCoded:decode","lerc decoder is not supported on big endian platform");await r();const{offset:i}=a,{width:s,height:o,pixelType:h,statistics:c,depthCount:l,noDataValues:p,bandMasks:d,pixels:u,mask:f}=n(e,{inputOffset:i,returnInterleaved:a.returnInterleaved}),y=new w({width:s,height:o,pixelType:h.toLowerCase(),pixels:u,mask:f,statistics:c.map(({minValue:t,maxValue:e})=>new g(t,e)),bandMasks:d,depthCount:l,noDataValues:p});return c?.length||y.updateStatistics(),y}async function k(e,a){await l();const i=p(e);if(!i)throw new t("rasterCodec:decode","failed to decode the input data.");const{width:s,height:r,pixels:n,pixelType:o}=i,h=new w({width:s,height:r,pixelType:o,pixels:n});return h.updateStatistics(),h}async function T(t,a){const i=await f(t,{...a,noDataValue:a.tiffNoDataValue,matchAllNoData:a.matchAllNoData});e(i);const s=new w({width:i.width,height:i.height,pixels:i.pixels,pixelType:i.pixelType.toLowerCase(),mask:i.mask,bandMasks:i.bandMasks,statistics:null});return s.updateStatistics(),s}async function I(t,e){const a=await u(t,e.customOptions),i=new w({width:a.width,height:a.height,pixels:a.pixels,pixelType:a.pixelType.toLowerCase(),mask:a.mask,statistics:null});return i.updateStatistics(),i}function A(t,e){const a=e.pixelType||"u8",i=w.getPixelArrayConstructor(a),s="u8"===a?t:new i(t.buffer),r=[],n=e.planes||1;if(1===n)r.push(s);else for(let h=0;h<n;h++){const a=(e.width||1)*(e.height||t.length),o=new i(a);for(let t=0;t<a;t++)o[t]=s[t*n+h];r.push(o)}const o=new w({width:e.width||1,height:e.height||t.length,pixels:r,pixelType:a,statistics:null});return o.updateStatistics(),o}function C(t,e){return A(new c(new Uint8Array(t)).getBytes(),e)}function D(t,e){return A(o(t,e.offset,e.eof,!e.isInputBigEndian),e)}function U(t,e,a){const{pixelTypeCtor:i}=M(e.pixelType),s=(0,d.decode)(t,{width:e.width,height:e.height,pixelType:i,format:a}),r=new w({width:e.width,height:e.height,pixels:s.pixels,pixelType:e.pixelType,mask:s.mask,statistics:null});return r.updateStatistics(),r}function v(t,e){const a=s.decode(t,e.applyJpegMask),i=new w({width:a.width,height:a.height,pixels:a.pixels,pixelType:"u8",mask:a.mask,statistics:null});return i.updateStatistics(),i}function S(t,e){const a=new Uint8Array(t),i=new y(a),{width:s,height:r}=e,n=s*r,o=i.decode(),h=new Uint8Array(n);for(let l=0;l<n;l++)h[l]=o[4*l+3];const c=new w({width:s,height:r,pixels:[],pixelType:"u8",mask:h,statistics:[]});for(let l=0;l<3;l++){const t=new Uint8Array(n);for(let e=0;e<n;e++)t[e]=o[4*e+l];c.addData({pixels:t})}return c.updateStatistics(),c}async function j(t,e,a,s){const r={...a,format:e},n=await i(t,r,s),o=new w(n);return o.updateStatistics(),o}function O(e){if(null==e)throw new t("rasterCodec:decode","parameter encodeddata is required.");const a=new Uint8Array(e,0,10);let i="";return 255===a[0]&&216===a[1]?i="jpg":137===a[0]&&80===a[1]&&78===a[2]&&71===a[3]?i="png":67===a[0]&&110===a[1]&&116===a[2]&&90===a[3]&&73===a[4]&&109===a[5]&&97===a[6]&&103===a[7]&&101===a[8]&&32===a[9]?i="lerc":76===a[0]&&101===a[1]&&114===a[2]&&99===a[3]&&50===a[4]&&32===a[5]?i="lerc2":73===a[0]&&73===a[1]&&42===a[2]&&0===a[3]||77===a[0]&&77===a[1]&&0===a[2]&&42===a[3]||73===a[0]&&73===a[1]&&43===a[2]&&0===a[3]||77===a[0]&&77===a[1]&&0===a[2]&&43===a[3]?i="tiff":71===a[0]&&73===a[1]&&70===a[2]?i="gif":66===a[0]&&77===a[1]?i="bmp":81===a[0]&&66===a[1]&&51===a[2]?i="qb3":String.fromCharCode.apply(null,a).toLowerCase().includes("error")&&(i="error"),i}function P(e){let a=null;switch(e){case"lerc":case"lerc2":a=b;break;case"jpg":a=v;break;case"png":a=S;break;case"bsq":case"bip":a=(t,a)=>U(t,a,e);break;case"tiff":a=T;break;case"deflate":a=C;break;case"lzw":a=D;break;case"qb3":a=k;break;case"error":a=()=>{throw new t("rasterCodec:decode","input data contains error")};break;default:a=()=>{throw new t("rasterCodec:decode","unsupported raster format")}}return a}function M(t){let e=null,a=null;switch(t?t.toLowerCase():"f32"){case"u1":case"u2":case"u4":case"u8":a=255,e=Uint8Array;break;case"u16":a=a||65535,e=Uint16Array;break;case"u32":a=a||2**32-1,e=Uint32Array;break;case"s8":a=a||-128,e=Int8Array;break;case"s16":a=a||-32768,e=Int16Array;break;case"s32":a=a||0-2**31,e=Int32Array;break;default:e=Float32Array}return{pixelTypeCtor:e,noDataValue:a}}function L(t,e=1){if(!t)return;const{pixels:a,width:i,height:s,mask:r}=t;if(!a||0===a.length)return;const n=i-1,o=s-1,h=[];let c=null;const l=w.getPixelArrayConstructor(t.pixelType);if(0===e){for(const t of a){const e=new l(n*o);for(let a=0;a<o;a++){const s=a*i;for(let i=0;i<n;i++)e[a*n+i]=t[s+i]}h.push(e)}if(null!=r){c=new Uint8Array(n*o);for(let t=0;t<o;t++){const e=t*i;for(let a=0;a<n;a++)c[t*n+a]=r[e+a]}}}else{for(const t of a){const e=new l(n*o);for(let a=0;a<o;a++){const s=a*i;for(let r=0;r<n;r++)e[a*n+r]=(t[s+r]+t[s+r+1]+t[s+i+r]+t[s+i+r+1])/4}h.push(e)}if(r){c=new Uint8Array(n*o);for(let t=0;t<o;t++){const e=t*i;for(let a=0;a<n;a++)c[t*n+a]=Math.min.apply(null,[r[e+a],r[e+a+1],r[e+i+a],r[e+i+a+1]])}}}t.width=n,t.height=o,t.mask=c,t.pixels=h}function R(t){let e=O(t);return"lerc2"===e?e="lerc":"error"===e&&(e=""),e}async function B(e,i={},s){if(null==e)throw new t("rasterCodec:decode","missing encodeddata parameter.");let r=i.format?.toLowerCase();if(!("bsq"!==r&&"bip"!==r||null!=i.width&&null!=i.height))throw new t("rasterCodec:decode","requires width and height in options parameter.");if("tiff"===r&&i.customOptions)return I(e,i);if((!r||"bsq"!==r&&"bip"!==r&&"deflate"!==r&&"lzw"!==r)&&(r=O(e)),x.has(r))try{return await j(e,r,i,s)}catch(l){if(a(l))throw l}const n=P(r);let o;i.isPoint&&(null!=(i={...i}).width&&i.width++,null!=i.height&&i.height++);const{offsets:c}=i;if(c&&c.length>1){const t=c.map((t,a)=>n(e.slice(t,c[a+1]),i)),a=await Promise.all(t);o=a[0],o.pixels=a.map(t=>t.pixels[0]);const s=a.map(t=>t.mask);a.some(t=>null!=t)&&(s.forEach((t,e)=>{null==t&&(s[e]=new Uint8Array(o.width*o.height).fill(255))}),o.bandMasks=s,o.mask=w.combineBandMasks(s)),o.updateStatistics()}else o=await n(e,{...i,offset:c?.[0]??i.offset});return"jpg"!==r&&null!=i.noDataValue&&1===o.depthCount&&h(o,i.noDataValue,{customFloatTolerance:i.tolerance}),i.isPoint&&L(o),o}export{B as decode,R as getFormat};
@@ -1,2 +1,2 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
2
- import e from"../../request.js";import{isSome as t}from"../../core/arrayUtils.js";import{isDateString as i}from"../../core/date.js";import r from"../../core/Error.js";import{cacheAsync as n,getYieldedValue as o}from"../../core/iteratorUtils.js";import{_parseInfo as l}from"../../core/number.js";import{urlToObject as s}from"../../core/urlUtils.js";import a from"./Field.js";import{normalizeFieldName as c,getFieldDefaultLength as f}from"./fieldUtils.js";import{inferLocationInfo as u}from"./locationUtils.js";async function d(t,i={}){const{customParameters:n,signal:o}=i,l=s(t),a=await e(l.path,{query:{...l.query,...n},responseType:"native",signal:o});if(!a.data.body)throw new r("csv-utils:empty-csv","CSV is empty");const[c]=await Promise.allSettled([m(a.data.body)]);if(await a.data.body.cancel(),"rejected"===c.status)throw c.reason;return{url:t,customParameters:n,...c.value}}async function m(e){const t=e.getReader(),i=n(w(t)),l=i(),s=o(await l.next())?.trim(),c=o(await l.next())?.trim();if(!s)throw new r("csv-utils:empty-csv","CSV is empty");const{delimiter:f,locationInfo:u}=N(s,c);if(!f)throw new r("csv-utils:invalid-delimiter","Unable to detect the delimiter from CSV",{firstLine:s,secondLine:c});const{names:d,aliases:m}=S(s,f),p=i();await p.next();const y=await j(p,f,d,m,u);return t.releaseLock(),e.cancel().catch(()=>{}),{delimiter:f,fields:y.map(e=>a.fromJSON(e)),latitudeField:u?.latitudeFieldName,longitudeField:u?.longitudeFieldName}}const p=/^\s*"([\S\s]*)"\s*$/,y=/""/g,g="\n",h=[","," ",";","|","\t"];async function*w(e){const t=/\r?\n/gm,i=new TextDecoder;let r="";for await(const n of F(e)){const e=`${r}${i.decode(n)}`.split(t).filter(Boolean);r=e.pop()||"",yield*e}}async function*F(e){let t=await e.read();for(;!t.done;)yield t.value,t=await e.read();e.releaseLock()}function N(e,t,i){e=e.trim(),t=t?.trim();const r=[],n=Array.from(new Set([i?.delimiter,...h])).filter(e=>null!=e);for(const l of n){const i=v(e,l).length,n=v(t,l).length??i;i>1&&r.push({weight:Math.min(i,n),delimiter:l})}const o=r.sort(({weight:e},{weight:t})=>t-e).map(({delimiter:e})=>e);for(const l of o){const t=S(e,l).names,r=u(t,i?.longitudeField,i?.latitudeField);if(r.longitudeFieldName&&r.latitudeFieldName)return{delimiter:l,locationInfo:r}}return{delimiter:o[0],locationInfo:null}}async function*b(e,t,i,r=()=>Object.create(null)){let n="",o="",l=0,s=r(),a=0;for await(const c of e){const e=T(c,i);for(const c of e)if(n+=o+c,o="",l+=I(c),l%2==0){if(l>0){const e=p.exec(n);if(!e)return s=r(),a=0,n="",void(l=0);s[t[a]]=U(e[1]).replaceAll(y,'"'),a++}else s[t[a]]=U(n),a++;n="",l=0}else o=i;0===l?(yield s,s=r(),a=0):o=g}}function T(e,t){return x(e,t)}function*x(e,t){let i=0;for(;i<=e.length;){const r=e.indexOf(t,i),n=e.slice(i,r>-1?r:void 0);i+=n.length+t.length,yield n}}function S(e,i){const r=v(e,i).filter(t),n=r.map(e=>c(e));for(let t=n.length-1;t>=0;t--)n[t]||(n.splice(t,1),r.splice(t,1));return{names:n,aliases:r}}function v(e,t){if(!e?.length)return[];const i=[];let r="",n="",o=0;const l=T(e,t);for(const s of l)if(r+=n+s,n="",o+=I(s),o%2==0){if(o>0){const e=p.exec(r);e&&i.push(e[1].replaceAll(y,'"'))}else i.push(r);r="",o=0}else n=t;return i}async function j(e,t,i,r,n){const o=[],l=[];for await(const s of b(e,i,t)){if(10===l.length)break;l.push(s)}for(let s=0;s<i.length;s++){const e=i[s],t=r[s];if(e===n?.longitudeFieldName||e===n?.latitudeFieldName)o.push({name:e,type:"esriFieldTypeDouble",alias:t});else{const i=D(l.map(t=>t[e]))??"esriFieldTypeString";o.push({name:e,type:i,alias:t,length:f(i)})}}return o}function D(e){if(!e.length)return"esriFieldTypeString";const t=/[^+\-.,0-9]/;return e.map(e=>{if(""!==e){if(!t.test(e)){let t=O(e);if(!isNaN(t))return/[.,]/.test(e)||!Number.isInteger(t)||t>214783647||t<-214783648?"esriFieldTypeDouble":"esriFieldTypeInteger";if(e.includes("E")){if(t=Number(e),!Number.isNaN(t))return"esriFieldTypeDouble";if(e.includes(",")&&(e=e.replace(",","."),t=Number(e),!Number.isNaN(t)))return"esriFieldTypeDouble"}}return i(e)?"esriFieldTypeDate":"esriFieldTypeString"}}).reduce((e,t)=>void 0===e?t:void 0===t?e:e===t?t:"esriFieldTypeString"===e||"esriFieldTypeString"===t?"esriFieldTypeString":"esriFieldTypeDouble"===e||"esriFieldTypeDouble"===t?"esriFieldTypeDouble":void 0)}const O=function(){const e=l(),t=new RegExp("^"+e.regexp+"$"),i=new RegExp("["+e.group+"\\s\\xa0]","g"),r=e.factor;return n=>{const o=t.exec(n);if(e.factor=r,!o)return NaN;let l=o[1];if(!o[1]){if(!o[2])return NaN;l=o[2],e.factor*=-1}return l=l.replace(i,"").replace(e.decimal,"."),+l*e.factor}}();function U(e){return JSON.parse(JSON.stringify(e))}function I(e){let t=0,i=0;for(i=e.indexOf('"',i);i>=0;)t++,i=e.indexOf('"',i+1);return t}export{d as getCSVLayerInfo};
2
+ import e from"../../request.js";import{isSome as t}from"../../core/arrayUtils.js";import{isDateString as i}from"../../core/date.js";import r from"../../core/Error.js";import{cacheAsync as n,getYieldedValue as o}from"../../core/iteratorUtils.js";import{_parseInfo as l}from"../../core/number.js";import{urlToObject as s}from"../../core/urlUtils.js";import a from"./Field.js";import{normalizeFieldName as c,getFieldDefaultLength as f}from"./fieldUtils.js";import{inferLocationInfo as u}from"./locationUtils.js";async function d(t,i={}){const{customParameters:n,signal:o}=i,l=s(t),a=await e(l.path,{query:{...l.query,...n},responseType:"native",signal:o});if(!a.data.body)throw new r("csv-utils:empty-csv","CSV is empty");const[c]=await Promise.allSettled([m(a.data.body)]);if(await a.data.body.cancel(),"rejected"===c.status)throw c.reason;return{url:t,customParameters:n,...c.value}}async function m(e){const t=e.getReader(),i=n(w(t)),l=i(),s=o(await l.next())?.trim(),c=o(await l.next())?.trim();if(!s)throw new r("csv-utils:empty-csv","CSV is empty");const{delimiter:f,locationInfo:u}=N(s,c);if(!f)throw new r("csv-utils:invalid-delimiter","Unable to detect the delimiter from CSV",{firstLine:s,secondLine:c});const{names:d,aliases:m}=S(s,f),p=i();await p.next();const y=await j(p,f,d,m,u);return t.releaseLock(),e.cancel().catch(()=>{}),{delimiter:f,fields:y.map(e=>a.fromJSON(e)),latitudeField:u?.latitudeFieldName,longitudeField:u?.longitudeFieldName}}const p=/^\s*"([\S\s]*)"\s*$/,y=/""/g,g="\n",h=[",",";","|","\t"];async function*w(e){const t=/\r?\n/gm,i=new TextDecoder;let r="";for await(const n of F(e)){const e=`${r}${i.decode(n)}`.split(t).filter(Boolean);r=e.pop()||"",yield*e}}async function*F(e){let t=await e.read();for(;!t.done;)yield t.value,t=await e.read();e.releaseLock()}function N(e,t,i){e=e.trim(),t=t?.trim();const r=[],n=Array.from(new Set([i?.delimiter,...h])).filter(e=>null!=e);for(const l of n){const i=v(e,l).length,n=v(t,l).length??i;i>1&&r.push({weight:Math.min(i,n),delimiter:l})}const o=r.sort(({weight:e},{weight:t})=>t-e).map(({delimiter:e})=>e);for(const l of o){const t=S(e,l).names,r=u(t,i?.longitudeField,i?.latitudeField);if(r.longitudeFieldName&&r.latitudeFieldName)return{delimiter:l,locationInfo:r}}return{delimiter:o[0],locationInfo:null}}async function*b(e,t,i,r=()=>Object.create(null)){let n="",o="",l=0,s=r(),a=0;for await(const c of e){const e=T(c,i);for(const c of e)if(n+=o+c,o="",l+=I(c),l%2==0){if(l>0){const e=p.exec(n);if(!e)return s=r(),a=0,n="",void(l=0);s[t[a]]=U(e[1]).replaceAll(y,'"'),a++}else s[t[a]]=U(n),a++;n="",l=0}else o=i;0===l?(yield s,s=r(),a=0):o=g}}function T(e,t){return x(e,t)}function*x(e,t){let i=0;for(;i<=e.length;){const r=e.indexOf(t,i),n=e.slice(i,r>-1?r:void 0);i+=n.length+t.length,yield n}}function S(e,i){const r=v(e,i).filter(t),n=r.map(e=>c(e));for(let t=n.length-1;t>=0;t--)n[t]||(n.splice(t,1),r.splice(t,1));return{names:n,aliases:r}}function v(e,t){if(!e?.length)return[];const i=[];let r="",n="",o=0;const l=T(e,t);for(const s of l)if(r+=n+s,n="",o+=I(s),o%2==0){if(o>0){const e=p.exec(r);e&&i.push(e[1].replaceAll(y,'"'))}else i.push(r);r="",o=0}else n=t;return i}async function j(e,t,i,r,n){const o=[],l=[];for await(const s of b(e,i,t)){if(10===l.length)break;l.push(s)}for(let s=0;s<i.length;s++){const e=i[s],t=r[s];if(e===n?.longitudeFieldName||e===n?.latitudeFieldName)o.push({name:e,type:"esriFieldTypeDouble",alias:t});else{const i=D(l.map(t=>t[e]))??"esriFieldTypeString";o.push({name:e,type:i,alias:t,length:f(i)})}}return o}function D(e){if(!e.length)return"esriFieldTypeString";const t=/[^+\-.,0-9]/;return e.map(e=>{if(""!==e){if(!t.test(e)){let t=O(e);if(!isNaN(t))return/[.,]/.test(e)||!Number.isInteger(t)||t>214783647||t<-214783648?"esriFieldTypeDouble":"esriFieldTypeInteger";if(e.includes("E")){if(t=Number(e),!Number.isNaN(t))return"esriFieldTypeDouble";if(e.includes(",")&&(e=e.replace(",","."),t=Number(e),!Number.isNaN(t)))return"esriFieldTypeDouble"}}return i(e)?"esriFieldTypeDate":"esriFieldTypeString"}}).reduce((e,t)=>void 0===e?t:void 0===t?e:e===t?t:"esriFieldTypeString"===e||"esriFieldTypeString"===t?"esriFieldTypeString":"esriFieldTypeDouble"===e||"esriFieldTypeDouble"===t?"esriFieldTypeDouble":void 0)}const O=function(){const e=l(),t=new RegExp("^"+e.regexp+"$"),i=new RegExp("["+e.group+"\\s\\xa0]","g"),r=e.factor;return n=>{const o=t.exec(n);if(e.factor=r,!o)return NaN;let l=o[1];if(!o[1]){if(!o[2])return NaN;l=o[2],e.factor*=-1}return l=l.replace(i,"").replace(e.decimal,"."),+l*e.factor}}();function U(e){return JSON.parse(JSON.stringify(e))}function I(e){let t=0,i=0;for(i=e.indexOf('"',i);i>=0;)t++,i=e.indexOf('"',i+1);return t}export{d as getCSVLayerInfo};