@arcgis/core 4.34.0-next.51 → 4.34.0-next.53
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.
- package/assets/esri/core/workers/RemoteClient.js +1 -1
- package/assets/esri/core/workers/chunks/{beb77cdae0b1b6ad73da.js → 0445de3a8968c0734c91.js} +1 -1
- package/assets/esri/core/workers/chunks/{35fc8a64674005b1d1d7.js → 0a4357af5b8c0532b439.js} +1 -1
- package/assets/esri/core/workers/chunks/{b87ed14fde381f79bc9f.js → 17776d9d3558d45ea7b5.js} +1 -1
- package/assets/esri/core/workers/chunks/2efa4d8fe5454f8b2a05.js +1 -0
- package/assets/esri/core/workers/chunks/{a69e885336eb5d2729fd.js → 3505988ce3839cdbbc98.js} +1 -1
- package/assets/esri/core/workers/chunks/{46ab551bd19e52e73649.js → 3800764932a1c32cb29f.js} +1 -1
- package/assets/esri/core/workers/chunks/3c57b2e13628b5c1f6de.js +1 -0
- package/assets/esri/core/workers/chunks/{77493aa2118d462612a0.js → 43bd338bb0de375b9bb7.js} +1 -1
- package/assets/esri/core/workers/chunks/{5a016dcd3192d42d363e.js → 5fc414fc2cfc68828c5b.js} +1 -1
- package/assets/esri/core/workers/chunks/{ecd673eccf89643df07a.js → 659f7e99b2d524ef53fb.js} +2 -2
- package/assets/esri/core/workers/chunks/{037bc400257bc13b3ec8.js → 772e81e9162e2240a7a6.js} +1 -1
- package/assets/esri/core/workers/chunks/81e518dd62bd95611d00.js +1 -0
- package/assets/esri/core/workers/chunks/{f1de768b0a6d345f7e39.js → 8f6ff09e7d2f01b79faf.js} +1 -1
- package/assets/esri/core/workers/chunks/{cfa8b17cf1349f6ed355.js → 9e9be7f6ea32957f1088.js} +1 -1
- package/assets/esri/core/workers/chunks/9fef330b241f958b55df.js +1 -0
- package/assets/esri/core/workers/chunks/aab349d4624b78ef429f.js +1 -0
- package/assets/esri/core/workers/chunks/b9f5672093727c6f92c9.js +1 -0
- package/assets/esri/core/workers/chunks/bcc233a86e01ff1eac16.js +1 -0
- package/assets/esri/core/workers/chunks/cac060a187f3a27a19ba.js +1 -0
- package/assets/esri/core/workers/chunks/cda27c0fafd687dfa72e.js +1 -0
- package/assets/esri/core/workers/chunks/{82a390be9500b629f6bc.js → d0bf1fc6e3c198bc565d.js} +1 -1
- package/assets/esri/core/workers/chunks/dd2b5f115d156b5b212e.js +1 -0
- package/assets/esri/core/workers/chunks/e28d3ed65c3a76a044c8.js +1 -0
- package/assets/esri/core/workers/chunks/f75ddd79be506423be09.js +1 -0
- package/assets/esri/core/workers/chunks/{c5b2a261d8c216ca4a10.js → f8505bf69795f5293a79.js} +1 -1
- package/assets/esri/core/workers/chunks/fae6030a81cb91a91b69.js +1 -0
- package/assets/esri/core/workers/chunks/ff7962063d132c1ec814.js +1 -0
- package/assets/esri/themes/base/widgets/_FloorFilter.scss +23 -19
- package/assets/esri/themes/base/widgets/_Search.scss +12 -0
- package/assets/esri/themes/dark/main.css +1 -1
- package/assets/esri/themes/light/main.css +1 -1
- package/assets/esri/themes/light/view.css +1 -1
- package/config.js +1 -1
- package/identity/OAuthCredential.js +1 -1
- package/interfaces.d.ts +3 -2
- package/kernel.js +1 -1
- package/layers/KMLLayer.js +1 -1
- package/layers/graphics/controllers/I3SOnDemandController.js +1 -1
- package/layers/graphics/data/QueryEngine.js +1 -1
- package/layers/graphics/sources/WFSSourceWorker.js +1 -1
- package/layers/graphics/sources/geojson/GeoJSONSourceWorker.js +1 -1
- package/layers/graphics/sources/support/CSVSourceWorker.js +1 -1
- package/layers/graphics/sources/support/MemorySourceWorker.js +1 -1
- package/layers/support/ElevationQuery.js +1 -1
- package/layers/support/ExportImageParameters.js +1 -1
- package/networks/UtilityNetwork.js +1 -1
- package/package.json +3 -3
- package/portal/Portal.js +1 -1
- package/renderers/support/rasterRendererHelper.js +1 -1
- package/renderers/support/utils.js +1 -1
- package/request.js +1 -1
- package/rest/featureService/FeatureService.js +1 -1
- package/rest/print.js +1 -1
- package/support/revision.js +1 -1
- package/views/3d/analysis/ElevationProfile/HoveredPointsVisualization.js +1 -1
- package/views/3d/layers/PointCloudLayerView3D.js +1 -1
- package/views/3d/layers/graphics/Graphics3DCore.js +1 -1
- package/views/3d/terrain/TerrainSurface.js +1 -1
- package/views/3d/webgl-engine/lib/Octree.js +1 -1
- package/views/draw/Draw.js +1 -1
- package/views/draw/support/Box.js +1 -1
- package/views/draw/support/GraphicMover.js +1 -1
- package/views/draw/support/Reshape.js +1 -1
- package/views/interactive/snapping/featureSources/GraphicsSnappingSource.js +1 -1
- package/views/interactive/snapping/featureSources/featureServiceSource/FeatureServiceSnappingSourceWorker.js +1 -1
- package/views/layers/support/popupUtils.js +1 -1
- package/views/support/PromiseQueue.js +5 -0
- package/views/support/Scheduler.js +1 -1
- package/widgets/FeatureTable/Grid/support/ButtonMenu.js +1 -1
- package/widgets/FloorFilter/css.js +1 -1
- package/widgets/FloorFilter.js +1 -1
- package/widgets/HistogramRangeSlider.js +1 -1
- package/widgets/Search/css.js +1 -1
- package/widgets/Search.js +1 -1
- package/widgets/Sketch/SketchViewModel.js +1 -1
- package/widgets/support/ItemList.js +1 -1
- package/assets/esri/core/workers/chunks/0874b88d5ae7c2b78b3b.js +0 -1
- package/assets/esri/core/workers/chunks/0c129b78e5cfe96795e1.js +0 -1
- package/assets/esri/core/workers/chunks/1a3a4c2c642899be37a0.js +0 -1
- package/assets/esri/core/workers/chunks/30169cf969d36ea8654e.js +0 -1
- package/assets/esri/core/workers/chunks/37a97e690786814bf0b3.js +0 -1
- package/assets/esri/core/workers/chunks/48e64f99720907017778.js +0 -1
- package/assets/esri/core/workers/chunks/4d544e3e19ce07c2c195.js +0 -1
- package/assets/esri/core/workers/chunks/8c1bd9bcfc59497de3b5.js +0 -1
- package/assets/esri/core/workers/chunks/8cc700da2ac58849a708.js +0 -1
- package/assets/esri/core/workers/chunks/9b7fee0adffeee8d45ae.js +0 -1
- package/assets/esri/core/workers/chunks/9d30fed26e0d84ef893b.js +0 -1
- package/assets/esri/core/workers/chunks/b29f0b32787edb4e75cf.js +0 -1
- package/assets/esri/core/workers/chunks/c87bb42f825c39f9cce3.js +0 -1
- package/assets/esri/core/workers/chunks/f667096ea325f690c4a6.js +0 -1
- package/assets/esri/core/workers/chunks/f9f94b5efa9a64cdb407.js +0 -1
- package/layers/graphics/data/executeQueryForSnapping.js +0 -5
- package/layers/support/PromiseQueue.js +0 -5
- /package/assets/esri/core/workers/chunks/{ecd673eccf89643df07a.js.LICENSE.txt → 659f7e99b2d524ef53fb.js.LICENSE.txt} +0 -0
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.34/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import{result as e}from"../../core/asyncUtils.js";import t from"../../core/Error.js";import{assertIsSome as i}from"../../core/maybe.js";import{whenOrAbort as n,throwIfAbortError as o}from"../../core/promiseUtils.js";import{getMetersPerUnitForSR as l}from"../../core/unitUtils.js";import s from"../../geometry/Multipoint.js";import a from"../../geometry/Point.js";import r from"../../geometry/Polyline.js";import{initializeProjection as c,project as u}from"../../geometry/projectionUtils.js";import{fromExtent as h,create as f,contains as m}from"../../geometry/support/aaBoundingRect.js";import{MultiTileElevationSampler as p}from"./ElevationSampler.js";import{ElevationTile as d}from"./ElevationTile.js";import{TileKey as y}from"./TileKey.js";class T{async queryAll(e,i,n){if(!(e=n?.ignoreInvisibleLayers?e.filter(e=>e.visible):e.slice()).length)throw new t("elevation-query:invalid-layer","Elevation queries require at least one elevation layer to fetch tiles from");const o=v.fromGeometry(i);let l=!1;n?.returnSampleInfo||(l=!0);const s={...R,...n,returnSampleInfo:!0},a=await this.query(e[e.length-1],o,s),r=await this._queryAllContinue(e,a,s);return r.geometry=r.geometry.export(),l&&delete r.sampleInfo,r}async query(e,i,n){if(!e)throw new t("elevation-query:invalid-layer","Elevation queries require an elevation layer to fetch tiles from");if(!i||!(i instanceof v)&&"point"!==i.type&&"multipoint"!==i.type&&"polyline"!==i.type)throw new t("elevation-query:invalid-geometry","Only point, polyline and multipoint geometries can be used to query elevation");const o={...R,...n},l=new x(e,i.spatialReference,o),s=o.signal;return await e.load({signal:s}),await q(l,i,s),await this._selectTiles(l,s),await F(l,s),b(l),z(l,s)}async createSampler(e,i,n){if(!e)throw new t("elevation-query:invalid-layer","Elevation queries require an elevation layer to fetch tiles from");if(!i||"extent"!==i.type)throw new t("elevation-query:invalid-extent","Invalid or undefined extent");const o={...R,...n};return this._createSampler(e,i,o)}async createSamplerAll(e,i,n){if(!(e=n?.ignoreInvisibleLayers?e.filter(e=>e.visible):e.slice()).length)throw new t("elevation-query:invalid-layer","Elevation queries require at least one elevation layer to fetch tiles from");if(!i||"extent"!==i.type)throw new t("elevation-query:invalid-extent","Invalid or undefined extent");const o={...R,...n,returnSampleInfo:!0},l=await this._createSampler(e[e.length-1],i,o);return this._createSamplerAllContinue(e,i,l,o)}async _createSampler(e,t,i,n){const o=i.signal;await e.load({signal:o});const l=t.spatialReference,s=e.tileInfo.spatialReference;l.equals(s)||(await c([{source:l,dest:s}],{signal:o}),t=u(t,s));const a=new _(e,t,i,n);return await this._selectTiles(a,o),await F(a,o),new p(a.elevationTiles,a.layer.tileInfo,a.options.noDataValue)}async _createSamplerAllContinue(e,t,i,n){if(e.pop(),!e.length)return i;const o=i.samplers.filter(e=>!e.tile.hasNoDataValues).map(e=>h(e.extent)),l=await this._createSampler(e[e.length-1],t,n,o);if(0===l.samplers.length)return i;const s=i.samplers.concat(l.samplers),a=new p(s,n.noDataValue);return this._createSamplerAllContinue(e,t,a,n)}async _queryAllContinue(e,t,n){const o=e.pop(),l=t.geometry.coordinates,s=t.sampleInfo;i(s);const a=[],r=[];for(let i=0;i<l.length;i++){const t=s[i];t.demResolution>=0?t.source||(t.source=o):e.length&&(a.push(l[i]),r.push(i))}if(!e.length||0===a.length)return t;const c=t.geometry.clone(a),u=await this.query(e[e.length-1],c,n),h=u.sampleInfo;if(!h)throw new Error("no sampleInfo");return r.forEach((e,t)=>{l[e].z=u.geometry.coordinates[t].z,s[e].demResolution=h[t].demResolution}),this._queryAllContinue(e,t,n)}async _selectTiles(e,i){"geometry"===e.type&&I(e);const n=e.options.demResolution;if("number"==typeof n)C(e,n);else if("finest-contiguous"===n)await this._selectTilesFinestContiguous(e,i);else{if("auto"!==n)throw new t("elevation-query:invalid-dem-resolution",`Invalid dem resolution value '${n}', expected a number, "finest-contiguous" or "auto"`);await this._selectTilesAuto(e,i)}}async _selectTilesFinestContiguous(e,t){const{tileInfo:i,tilemapCache:n}=e.layer,o=E(i,n,e.options.minDemResolution);await this._selectTilesFinestContiguousAt(e,o,t)}async _selectTilesFinestContiguousAt(e,i,l){const s=e.layer;if(e.selectTilesAtLOD(i),i<0)return;const a=s.tilemapCache,r=e.getTilesToFetch();try{if(a&&!L(a))await n(Promise.all(r.map(e=>a.fetchAvailability(e.level,e.row,e.col,{signal:l}))),l);else if(await F(e,l),!e.allElevationTilesFetched())throw e.clearElevationTiles(),new t("elevation-query:has-unavailable-tiles","Some elevation tiles are unavailable")}catch(c){o(c),await this._selectTilesFinestContiguousAt(e,i-1,l)}}async _selectTilesAuto(t,i){M(t),S(t);const l=t.layer.tilemapCache;if(!l||L(l))return this._selectTilesAutoPrefetchUpsample(t,i);const s=t.getTilesToFetch(),a={},r=s.map(async t=>{const n=new y(null,0,0,0,f()),s=await e(l.fetchAvailabilityUpsample(t.level,t.row,t.col,n,{signal:i}));!1!==s.ok?null!=t.id&&(a[t.id]=n):o(s.error)});await n(Promise.all(r),i),t.remapTiles(a)}async _selectTilesAutoPrefetchUpsample(e,t){const i=e.layer.tileInfo;await F(e,t);let n=!1;e.forEachTileToFetch((e,t)=>{i.upsampleTile(e)?n=!0:t()}),n&&await this._selectTilesAutoPrefetchUpsample(e,t)}}class v{export(){return this._exporter(this.coordinates,this.spatialReference)}clone(e){const t=new v;return t.geometry=this.geometry,t.spatialReference=this.spatialReference,t.coordinates=e||this.coordinates.map(e=>e.clone()),t._exporter=this._exporter,t}async project(e,t){if(this.spatialReference.equals(e))return this.clone();await c([{source:this.spatialReference,dest:e}],{signal:t});const i=new s({spatialReference:this.spatialReference,points:this.coordinates.map(e=>[e.x,e.y])}),n=u(i,e);if(!n)return null;const o=this.coordinates.map((e,t)=>{const i=e.clone(),o=n.points[t];return i.x=o[0],i.y=o[1],i}),l=this.clone(o);return l.spatialReference=e,l}static fromGeometry(e){const t=new v;if(t.geometry=e,t.spatialReference=e.spatialReference,e instanceof v)t.coordinates=e.coordinates.map(e=>e.clone()),t._exporter=(t,i)=>{const n=e.clone(t);return n.spatialReference=i,n};else switch(e.type){case"point":{const i=e,{hasZ:n,hasM:o}=i;t.coordinates=n&&o?[new w(i.x,i.y,i.z,i.m)]:n?[new w(i.x,i.y,i.z)]:o?[new w(i.x,i.y,null,i.m)]:[new w(i.x,i.y)],t._exporter=(t,i)=>e.hasM?new a(t[0].x,t[0].y,t[0].z,t[0].m,i):new a(t[0].x,t[0].y,t[0].z,i);break}case"multipoint":{const i=e,{hasZ:n,hasM:o}=i;t.coordinates=n&&o?i.points.map(e=>new w(e[0],e[1],e[2],e[3])):n?i.points.map(e=>new w(e[0],e[1],e[2])):o?i.points.map(e=>new w(e[0],e[1],null,e[2])):i.points.map(e=>new w(e[0],e[1])),t._exporter=(t,i)=>e.hasM?new s({points:t.map(e=>[e.x,e.y,e.z,e.m]),hasZ:!0,hasM:!0,spatialReference:i}):new s(t.map(e=>[e.x,e.y,e.z]),i);break}case"polyline":{const i=e,n=[],o=[],{hasZ:l,hasM:s}=e;let a=0;for(const e of i.paths)if(o.push([a,a+e.length]),a+=e.length,l&&s)for(const t of e)n.push(new w(t[0],t[1],t[2],t[3]));else if(l)for(const t of e)n.push(new w(t[0],t[1],t[2]));else if(s)for(const t of e)n.push(new w(t[0],t[1],null,t[2]));else for(const t of e)n.push(new w(t[0],t[1]));t.coordinates=n,t._exporter=(t,i)=>{const n=e.hasM?t.map(e=>[e.x,e.y,e.z??0,e.m??0]):t.map(e=>[e.x,e.y,e.z??0]),l=o.map(e=>n.slice(e[0],e[1]));return new r({paths:l,hasM:e.hasM,hasZ:!0,spatialReference:i})};break}}return t}}class w{constructor(e,t,i=null,n=null,o=null,l=null){this.x=e,this.y=t,this.z=i,this.m=n,this.tile=o,this.elevationTile=l}clone(){return new w(this.x,this.y,this.z,this.m)}}class g{constructor(e,t){this.layer=e,this.options=t}}class x extends g{constructor(e,t,i){super(e,i),this.outSpatialReference=t,this.type="geometry"}selectTilesAtLOD(e){if(e<0)this.geometry.coordinates.forEach(e=>e.tile=null);else{const{tileInfo:t,tilemapCache:i}=this.layer,n=D(t,i)[e].level;this.geometry.coordinates.forEach(e=>e.tile=t.tileAt(n,e.x,e.y))}}allElevationTilesFetched(){return!this.geometry.coordinates.some(e=>!e.elevationTile)}clearElevationTiles(){for(const e of this.geometry.coordinates)e.elevationTile!==this.outsideExtentTile&&(e.elevationTile=null)}populateElevationTiles(e){for(const t of this.geometry.coordinates)!t.elevationTile&&t.tile?.id&&(t.elevationTile=e[t.tile.id])}remapTiles(e){for(const t of this.geometry.coordinates){const i=t.tile?.id;t.tile=i?e[i]:null}}getTilesToFetch(){const e={},t=[];for(const i of this.geometry.coordinates){const n=i.tile;if(!n)continue;const o=i.tile?.id;i.elevationTile||!o||e[o]||(e[o]=n,t.push(n))}return t}forEachTileToFetch(e){for(const t of this.geometry.coordinates)t.tile&&!t.elevationTile&&e(t.tile,()=>{t.tile=null})}}class _ extends g{constructor(e,t,i,n){super(e,i),this.type="extent",this.elevationTiles=[],this._candidateTiles=[],this._fetchedCandidates=new Set,this.extent=t.clone().intersection(e.fullExtent),this.maskExtents=n}selectTilesAtLOD(e,t){const i=this._maximumLodForRequests(t),n=Math.min(i,e);n<0?this._candidateTiles.length=0:this._selectCandidateTilesCoveringExtentAt(n)}_maximumLodForRequests(e){const{tileInfo:t,tilemapCache:i}=this.layer,n=D(t,i);if(!e)return n.length-1;const o=this.extent;if(null==o)return-1;for(let l=n.length-1;l>=0;l--){const i=n[l],s=i.resolution*t.size[0],a=i.resolution*t.size[1];if(Math.ceil(o.width/s)*Math.ceil(o.height/a)<=e)return l}return-1}allElevationTilesFetched(){return this._candidateTiles.length===this.elevationTiles.length}clearElevationTiles(){this.elevationTiles.length=0,this._fetchedCandidates.clear()}populateElevationTiles(e){for(const t of this._candidateTiles){const i=t.id&&e[t.id];i&&(this._fetchedCandidates.add(t),this.elevationTiles.push(i))}}remapTiles(e){this._candidateTiles=j(this._candidateTiles.map(t=>e[t.id]))}getTilesToFetch(){return this._candidateTiles}forEachTileToFetch(e,t){const i=this._candidateTiles;this._candidateTiles=[],i.forEach(i=>{if(this._fetchedCandidates.has(i))return void(t&&t(i));let n=!1;e(i,()=>n=!0),n?t&&t(i):this._candidateTiles.push(i)}),this._candidateTiles=j(this._candidateTiles,t)}_selectCandidateTilesCoveringExtentAt(e){this._candidateTiles.length=0;const t=this.extent;if(null==t)return;const{tileInfo:i,tilemapCache:n}=this.layer,o=D(i,n)[e],l=i.tileAt(o.level,t.xmin,t.ymin),s=l.extent;if(null==s)return;const a=o.resolution*i.size[0],r=o.resolution*i.size[1],c=Math.ceil((t.xmax-s[0])/a),u=Math.ceil((t.ymax-s[1])/r);for(let h=0;h<u;h++)for(let e=0;e<c;e++){const t=new y(null,l.level,l.row-h,l.col+e);i.updateTileInfo(t),this._tileIsMasked(t)||this._candidateTiles.push(t)}}_tileIsMasked(e){return!!this.maskExtents&&this.maskExtents.some(t=>e.extent&&m(t,e.extent))}}function E(e,t,i=0){const n=D(e,t);let o=n.length-1;if(i>0){const t=i/l(e.spatialReference),s=n.findIndex(e=>e.resolution<t);0===s?o=0:s>0&&(o=s-1)}return o}const R={maximumAutoTileRequests:20,noDataValue:0,returnSampleInfo:!1,demResolution:"auto",minDemResolution:0};async function q(e,i,n){let o;const l=e.layer.tileInfo.spatialReference;if(i instanceof v?o=await i.project(l,n):(await c([{source:i.spatialReference,dest:l}],{signal:n}),o=u(i,l)),!o)throw new t("elevation-query:spatial-reference-mismatch",`Cannot query elevation in '${i.spatialReference.wkid}' on an elevation service in '${l.wkid}'`);e.geometry=v.fromGeometry(o)}function I(e){if(null==e.layer.fullExtent)return;const t=new d(null);t.sample=()=>e.options.noDataValue,e.outsideExtentTile=t;const i=e.layer.fullExtent;e.geometry.coordinates.forEach(e=>{const n=e.x,o=e.y;(n<i.xmin||n>i.xmax||o<i.ymin||o>i.ymax)&&(e.elevationTile=t)})}function A(e,t){const{tileInfo:i,tilemapCache:n}=e.layer,o=t/l(i.spatialReference),s=D(i,n);let a=s[0],r=0;for(let l=1;l<s.length;l++){const e=s[l];Math.abs(e.resolution-o)<Math.abs(a.resolution-o)&&(a=e,r=l)}return r}function C(e,t){const i=A(e,t);e.selectTilesAtLOD(i)}function M(e){const{tileInfo:t,tilemapCache:i}=e.layer,n=E(t,i,e.options.minDemResolution);e.selectTilesAtLOD(n,e.options.maximumAutoTileRequests)}function D(e,t){const i=e.lods;if(L(t)){const{effectiveMinLOD:e,effectiveMaxLOD:n}=t;return i.filter(t=>t.level>=e&&t.level<=n)}return i}async function F(e,t){const i=e.getTilesToFetch(),o={},l=e.options.cache,s=e.options.noDataValue,a=i.map(async i=>{if(null==i.id)return;const n=`${e.layer.uid}:${i.id}:${s}`,a=null!=l?l.get(n):null,r=null!=a?a:await e.layer.fetchTile(i.level,i.row,i.col,{noDataValue:s,signal:t});null!=l&&l.put(n,r),o[i.id]=new d(i,r)});await n(Promise.allSettled(a),t),e.populateElevationTiles(o)}function S(e){const t=e.layer.tileInfo;let i=0;const n={},o=e=>{null!=e.id&&(e.id in n?n[e.id]++:(n[e.id]=1,i++))},l=e=>{if(null==e.id)return;const t=n[e.id];1===t?(delete n[e.id],i--):n[e.id]=t-1};e.forEachTileToFetch(o,l);let s=!0;for(;s&&(s=!1,e.forEachTileToFetch(n=>{i<=e.options.maximumAutoTileRequests||(l(n),t.upsampleTile(n)&&(s=!0),o(n))},l),s););}function b(e){e.geometry.coordinates.forEach(t=>{const i=t.elevationTile;let n=e.options.noDataValue;if(i){const e=i.sample(t.x,t.y);null!=e?n=e:t.elevationTile=null}t.z=n})}function j(e,t){const i={},n=[];for(const l of e){const e=l.id;e&&!i[e]?(i[e]=l,n.push(l)):t&&t(l)}const o=n.sort((e,t)=>e.level-t.level);return o.filter((e,i)=>{for(let n=0;n<i;n++){const i=o[n].extent;if(i&&e.extent&&m(i,e.extent))return t&&t(e),!1}return!0})}async function z(e,t){const n=await e.geometry.project(e.outSpatialReference,t);i(n);const o={geometry:n.export(),noDataValue:e.options.noDataValue};return e.options.returnSampleInfo&&(o.sampleInfo=k(e)),e.geometry.coordinates.forEach(e=>{e.tile=null,e.elevationTile=null}),o}function k(e){const t=e.layer.tileInfo,i=l(t.spatialReference);return e.geometry.coordinates.map(n=>{let o=-1;if(n.elevationTile&&n.elevationTile!==e.outsideExtentTile){o=t.lodAt(n.elevationTile.tile.level).resolution*i}return{demResolution:o}})}function L(e){return null!=e?.tileInfo}export{T as ElevationQuery,v as GeometryDescriptor,E as getFinestLodIndex};
|
|
5
|
+
import{result as e}from"../../core/asyncUtils.js";import t from"../../core/Error.js";import{assertIsSome as i}from"../../core/maybe.js";import{whenOrAbort as n,throwIfAbortError as o}from"../../core/promiseUtils.js";import{getMetersPerUnitForSR as l}from"../../core/unitUtils.js";import s from"../../geometry/Multipoint.js";import a from"../../geometry/Point.js";import r from"../../geometry/Polyline.js";import{initializeProjection as c,project as u}from"../../geometry/projectionUtils.js";import{fromExtent as h,create as f,contains as m}from"../../geometry/support/aaBoundingRect.js";import{MultiTileElevationSampler as p}from"./ElevationSampler.js";import{ElevationTile as d}from"./ElevationTile.js";import{TileKey as y}from"./TileKey.js";class T{async queryAll(e,i,n){if(!(e=n?.ignoreInvisibleLayers?e.filter(e=>e.visible):e.slice()).length)throw new t("elevation-query:invalid-layer","Elevation queries require at least one elevation layer to fetch tiles from");const o=v.fromGeometry(i);let l=!1;n?.returnSampleInfo||(l=!0);const s={...R,...n,returnSampleInfo:!0},a=await this.query(e[e.length-1],o,s),r=await this._queryAllContinue(e,a,s);return r.geometry=r.geometry.export(),l&&delete r.sampleInfo,r}async query(e,i,n){if(!e)throw new t("elevation-query:invalid-layer","Elevation queries require an elevation layer to fetch tiles from");if(!i||!(i instanceof v)&&"point"!==i.type&&"multipoint"!==i.type&&"polyline"!==i.type)throw new t("elevation-query:invalid-geometry","Only point, polyline and multipoint geometries can be used to query elevation");const o={...R,...n},l=new x(e,i.spatialReference,o),s=o.signal;return await e.load({signal:s}),await q(l,i,s),await this._selectTiles(l,s),await F(l,s),b(l),z(l,s)}async createSampler(e,i,n){if(!e)throw new t("elevation-query:invalid-layer","Elevation queries require an elevation layer to fetch tiles from");if(!i||"extent"!==i.type)throw new t("elevation-query:invalid-extent","Invalid or undefined extent");const o={...R,...n};return this._createSampler(e,i,o)}async createSamplerAll(e,i,n){if(!(e=n?.ignoreInvisibleLayers?e.filter(e=>e.visible):e.slice()).length)throw new t("elevation-query:invalid-layer","Elevation queries require at least one elevation layer to fetch tiles from");if(!i||"extent"!==i.type)throw new t("elevation-query:invalid-extent","Invalid or undefined extent");const o={...R,...n,returnSampleInfo:!0},l=await this._createSampler(e[e.length-1],i,o);return this._createSamplerAllContinue(e,i,l,o)}async _createSampler(e,t,i,n){const o=i.signal;await e.load({signal:o});const l=t.spatialReference,s=e.tileInfo.spatialReference;l.equals(s)||(await c([{source:l,dest:s}],{signal:o}),t=u(t,s));const a=new _(e,t,i,n);return await this._selectTiles(a,o),await F(a,o),new p(a.elevationTiles,a.layer.tileInfo,a.options.noDataValue)}async _createSamplerAllContinue(e,t,i,n){if(e.pop(),!e.length)return i;const o=i.samplers.filter(e=>!e.tile.hasNoDataValues).map(e=>h(e.extent)),l=await this._createSampler(e[e.length-1],t,n,o);if(0===l.samplers.length)return i;const s=i.samplers.concat(l.samplers),a=new p(s,n.noDataValue);return this._createSamplerAllContinue(e,t,a,n)}async _queryAllContinue(e,t,n){const o=e.pop(),l=t.geometry.coordinates,s=t.sampleInfo;i(s);const a=[],r=[];for(let i=0;i<l.length;i++){const t=s[i];t.demResolution>=0?t.source||(t.source=o):e.length&&(a.push(l[i]),r.push(i))}if(!e.length||0===a.length)return t;const c=t.geometry.clone(a),u=await this.query(e[e.length-1],c,n),h=u.sampleInfo;if(!h)throw new Error("no sampleInfo");return r.forEach((e,t)=>{l[e].z=u.geometry.coordinates[t].z,s[e].demResolution=h[t].demResolution}),this._queryAllContinue(e,t,n)}async _selectTiles(e,i){"geometry"===e.type&&I(e);const n=e.options.demResolution;if("number"==typeof n)C(e,n);else if("finest-contiguous"===n)await this._selectTilesFinestContiguous(e,i);else{if("auto"!==n)throw new t("elevation-query:invalid-dem-resolution",`Invalid dem resolution value '${n}', expected a number, "finest-contiguous" or "auto"`);await this._selectTilesAuto(e,i)}}async _selectTilesFinestContiguous(e,t){const{tileInfo:i,tilemapCache:n}=e.layer,o=E(i,n,e.options.minDemResolution);await this._selectTilesFinestContiguousAt(e,o,t)}async _selectTilesFinestContiguousAt(e,i,l){const s=e.layer;if(e.selectTilesAtLOD(i),i<0)return;const a=s.tilemapCache,r=e.getTilesToFetch();try{if(a&&!L(a))await n(Promise.all(r.map(e=>a.fetchAvailability(e.level,e.row,e.col,{signal:l}))),l);else if(await F(e,l),!e.allElevationTilesFetched())throw e.clearElevationTiles(),new t("elevation-query:has-unavailable-tiles","Some elevation tiles are unavailable")}catch(c){o(c),await this._selectTilesFinestContiguousAt(e,i-1,l)}}async _selectTilesAuto(t,i){M(t),S(t);const l=t.layer.tilemapCache;if(!l||L(l))return this._selectTilesAutoPrefetchUpsample(t,i);const s=t.getTilesToFetch(),a={},r=s.map(async t=>{const n=new y(null,0,0,0,f()),s=await e(l.fetchAvailabilityUpsample(t.level,t.row,t.col,n,{signal:i}));!1!==s.ok?null!=t.id&&(a[t.id]=n):o(s.error)});await n(Promise.all(r),i),t.remapTiles(a)}async _selectTilesAutoPrefetchUpsample(e,t){const i=e.layer.tileInfo;await F(e,t);let n=!1;e.forEachTileToFetch((e,t)=>{i.upsampleTile(e)?n=!0:t()}),n&&await this._selectTilesAutoPrefetchUpsample(e,t)}}class v{export(){return this._exporter(this.coordinates,this.spatialReference)}clone(e){const t=new v;return t.geometry=this.geometry,t.spatialReference=this.spatialReference,t.coordinates=e||this.coordinates.map(e=>e.clone()),t._exporter=this._exporter,t}async project(e,t){if(this.spatialReference.equals(e))return this.clone();await c([{source:this.spatialReference,dest:e}],{signal:t});const i=new s({spatialReference:this.spatialReference,points:this.coordinates.map(e=>[e.x,e.y])}),n=u(i,e);if(!n)return null;const o=this.coordinates.map((e,t)=>{const i=e.clone(),o=n.points[t];return i.x=o[0],i.y=o[1],i}),l=this.clone(o);return l.spatialReference=e,l}static fromGeometry(e){const t=new v;if(t.geometry=e,t.spatialReference=e.spatialReference,e instanceof v)t.coordinates=e.coordinates.map(e=>e.clone()),t._exporter=(t,i)=>{const n=e.clone(t);return n.spatialReference=i,n};else switch(e.type){case"point":{const i=e,{hasZ:n,hasM:o}=i;t.coordinates=n&&o?[new w(i.x,i.y,i.z,i.m)]:n?[new w(i.x,i.y,i.z)]:o?[new w(i.x,i.y,null,i.m)]:[new w(i.x,i.y)],t._exporter=(t,i)=>e.hasM?new a(t[0].x,t[0].y,t[0].z,t[0].m,i):new a(t[0].x,t[0].y,t[0].z,i);break}case"multipoint":{const i=e,{hasZ:n,hasM:o}=i;t.coordinates=n&&o?i.points.map(e=>new w(e[0],e[1],e[2],e[3])):n?i.points.map(e=>new w(e[0],e[1],e[2])):o?i.points.map(e=>new w(e[0],e[1],null,e[2])):i.points.map(e=>new w(e[0],e[1])),t._exporter=(t,i)=>e.hasM?new s({points:t.map(e=>[e.x,e.y,e.z,e.m]),hasZ:!0,hasM:!0,spatialReference:i}):new s(t.map(e=>[e.x,e.y,e.z]),i);break}case"polyline":{const i=e,n=[],o=[],{hasZ:l,hasM:s}=e;let a=0;for(const e of i.paths)if(o.push([a,a+e.length]),a+=e.length,l&&s)for(const t of e)n.push(new w(t[0],t[1],t[2],t[3]));else if(l)for(const t of e)n.push(new w(t[0],t[1],t[2]));else if(s)for(const t of e)n.push(new w(t[0],t[1],null,t[2]));else for(const t of e)n.push(new w(t[0],t[1]));t.coordinates=n,t._exporter=(t,i)=>{const n=e.hasM?t.map(e=>[e.x,e.y,e.z??0,e.m??0]):t.map(e=>[e.x,e.y,e.z??0]),l=o.map(e=>n.slice(e[0],e[1]));return new r({paths:l,hasM:e.hasM,hasZ:!0,spatialReference:i})};break}}return t}}class w{constructor(e,t,i=null,n=null,o=null,l=null){this.x=e,this.y=t,this.z=i,this.m=n,this.tile=o,this.elevationTile=l}clone(){return new w(this.x,this.y,this.z,this.m)}}class g{constructor(e,t){this.layer=e,this.options=t}}class x extends g{constructor(e,t,i){super(e,i),this.outSpatialReference=t,this.type="geometry"}selectTilesAtLOD(e){if(e<0)this.geometry.coordinates.forEach(e=>e.tile=null);else{const{tileInfo:t,tilemapCache:i}=this.layer,n=D(t,i)[e].level;this.geometry.coordinates.forEach(e=>e.tile=t.tileAt(n,e.x,e.y))}}allElevationTilesFetched(){return!this.geometry.coordinates.some(e=>!e.elevationTile)}clearElevationTiles(){for(const e of this.geometry.coordinates)e.elevationTile!==this.outsideExtentTile&&(e.elevationTile=null)}populateElevationTiles(e){for(const t of this.geometry.coordinates)!t.elevationTile&&t.tile?.id&&(t.elevationTile=e[t.tile.id])}remapTiles(e){for(const t of this.geometry.coordinates){const i=t.tile?.id;t.tile=i?e[i]:null}}getTilesToFetch(){const e={},t=[];for(const i of this.geometry.coordinates){const n=i.tile;if(!n)continue;const o=i.tile?.id;i.elevationTile||!o||e[o]||(e[o]=n,t.push(n))}return t}forEachTileToFetch(e){for(const t of this.geometry.coordinates)t.tile&&!t.elevationTile&&e(t.tile,()=>{t.tile=null})}}class _ extends g{constructor(e,t,i,n){super(e,i),this.type="extent",this.elevationTiles=[],this._candidateTiles=[],this._fetchedCandidates=new Set,this.extent=t.clone().intersection(e.fullExtent),this.maskExtents=n}selectTilesAtLOD(e,t){const i=this._maximumLodForRequests(t),n=Math.min(i,e);n<0?this._candidateTiles.length=0:this._selectCandidateTilesCoveringExtentAt(n)}_maximumLodForRequests(e){const{tileInfo:t,tilemapCache:i}=this.layer,n=D(t,i);if(!e)return n.length-1;const o=this.extent;if(null==o)return-1;for(let l=n.length-1;l>=0;l--){const i=n[l],s=i.resolution*t.size[0],a=i.resolution*t.size[1];if(Math.ceil(o.width/s)*Math.ceil(o.height/a)<=e)return l}return-1}allElevationTilesFetched(){return this._candidateTiles.length===this.elevationTiles.length}clearElevationTiles(){this.elevationTiles.length=0,this._fetchedCandidates.clear()}populateElevationTiles(e){for(const t of this._candidateTiles){const i=t.id&&e[t.id];i&&(this._fetchedCandidates.add(t),this.elevationTiles.push(i))}}remapTiles(e){this._candidateTiles=j(this._candidateTiles.map(t=>e[t.id]))}getTilesToFetch(){return this._candidateTiles}forEachTileToFetch(e,t){const i=this._candidateTiles;this._candidateTiles=[],i.forEach(i=>{if(this._fetchedCandidates.has(i))return void t?.(i);let n=!1;e(i,()=>n=!0),n?t?.(i):this._candidateTiles.push(i)}),this._candidateTiles=j(this._candidateTiles,t)}_selectCandidateTilesCoveringExtentAt(e){this._candidateTiles.length=0;const t=this.extent;if(null==t)return;const{tileInfo:i,tilemapCache:n}=this.layer,o=D(i,n)[e],l=i.tileAt(o.level,t.xmin,t.ymin),s=l.extent;if(null==s)return;const a=o.resolution*i.size[0],r=o.resolution*i.size[1],c=Math.ceil((t.xmax-s[0])/a),u=Math.ceil((t.ymax-s[1])/r);for(let h=0;h<u;h++)for(let e=0;e<c;e++){const t=new y(null,l.level,l.row-h,l.col+e);i.updateTileInfo(t),this._tileIsMasked(t)||this._candidateTiles.push(t)}}_tileIsMasked(e){return!!this.maskExtents&&this.maskExtents.some(t=>e.extent&&m(t,e.extent))}}function E(e,t,i=0){const n=D(e,t);let o=n.length-1;if(i>0){const t=i/l(e.spatialReference),s=n.findIndex(e=>e.resolution<t);0===s?o=0:s>0&&(o=s-1)}return o}const R={maximumAutoTileRequests:20,noDataValue:0,returnSampleInfo:!1,demResolution:"auto",minDemResolution:0};async function q(e,i,n){let o;const l=e.layer.tileInfo.spatialReference;if(i instanceof v?o=await i.project(l,n):(await c([{source:i.spatialReference,dest:l}],{signal:n}),o=u(i,l)),!o)throw new t("elevation-query:spatial-reference-mismatch",`Cannot query elevation in '${i.spatialReference.wkid}' on an elevation service in '${l.wkid}'`);e.geometry=v.fromGeometry(o)}function I(e){if(null==e.layer.fullExtent)return;const t=new d(null);t.sample=()=>e.options.noDataValue,e.outsideExtentTile=t;const i=e.layer.fullExtent;e.geometry.coordinates.forEach(e=>{const n=e.x,o=e.y;(n<i.xmin||n>i.xmax||o<i.ymin||o>i.ymax)&&(e.elevationTile=t)})}function A(e,t){const{tileInfo:i,tilemapCache:n}=e.layer,o=t/l(i.spatialReference),s=D(i,n);let a=s[0],r=0;for(let l=1;l<s.length;l++){const e=s[l];Math.abs(e.resolution-o)<Math.abs(a.resolution-o)&&(a=e,r=l)}return r}function C(e,t){const i=A(e,t);e.selectTilesAtLOD(i)}function M(e){const{tileInfo:t,tilemapCache:i}=e.layer,n=E(t,i,e.options.minDemResolution);e.selectTilesAtLOD(n,e.options.maximumAutoTileRequests)}function D(e,t){const i=e.lods;if(L(t)){const{effectiveMinLOD:e,effectiveMaxLOD:n}=t;return i.filter(t=>t.level>=e&&t.level<=n)}return i}async function F(e,t){const i=e.getTilesToFetch(),o={},l=e.options.cache,s=e.options.noDataValue,a=i.map(async i=>{if(null==i.id)return;const n=`${e.layer.uid}:${i.id}:${s}`,a=null!=l?l.get(n):null,r=null!=a?a:await e.layer.fetchTile(i.level,i.row,i.col,{noDataValue:s,signal:t});null!=l&&l.put(n,r),o[i.id]=new d(i,r)});await n(Promise.allSettled(a),t),e.populateElevationTiles(o)}function S(e){const t=e.layer.tileInfo;let i=0;const n={},o=e=>{null!=e.id&&(e.id in n?n[e.id]++:(n[e.id]=1,i++))},l=e=>{if(null==e.id)return;const t=n[e.id];1===t?(delete n[e.id],i--):n[e.id]=t-1};e.forEachTileToFetch(o,l);let s=!0;for(;s&&(s=!1,e.forEachTileToFetch(n=>{i<=e.options.maximumAutoTileRequests||(l(n),t.upsampleTile(n)&&(s=!0),o(n))},l),s););}function b(e){e.geometry.coordinates.forEach(t=>{const i=t.elevationTile;let n=e.options.noDataValue;if(i){const e=i.sample(t.x,t.y);null!=e?n=e:t.elevationTile=null}t.z=n})}function j(e,t){const i={},n=[];for(const l of e){const e=l.id;e&&!i[e]?(i[e]=l,n.push(l)):t?.(l)}const o=n.sort((e,t)=>e.level-t.level);return o.filter((e,i)=>{for(let n=0;n<i;n++){const i=o[n].extent;if(i&&e.extent&&m(i,e.extent))return t?.(e),!1}return!0})}async function z(e,t){const n=await e.geometry.project(e.outSpatialReference,t);i(n);const o={geometry:n.export(),noDataValue:e.options.noDataValue};return e.options.returnSampleInfo&&(o.sampleInfo=k(e)),e.geometry.coordinates.forEach(e=>{e.tile=null,e.elevationTile=null}),o}function k(e){const t=e.layer.tileInfo,i=l(t.spatialReference);return e.geometry.coordinates.map(n=>{let o=-1;if(n.elevationTile&&n.elevationTile!==e.outsideExtentTile){o=t.lodAt(n.elevationTile.tile.level).resolution*i}return{demResolution:o}})}function L(e){return null!=e?.tileInfo}export{T as ElevationQuery,v as GeometryDescriptor,E as getFinestLodIndex};
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.34/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import{__decorate as e}from"tslib";import r from"../../core/Accessor.js";import{sqlAnd as s}from"../../core/sql.js";import{property as t}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/Logger.js";import"../../core/RandomLCG.js";import{subclass as i}from"../../core/accessorSupport/decorators/subclass.js";import{isInScaleRange as a}from"../../geometry/support/scaleUtils.js";import{getLayerFloorFilterClause as o}from"./floorFilterUtils.js";import{isExportDynamic as l}from"./sublayerUtils.js";const n={visible:"visibleSublayers",definitionExpression:"layerDefs",labelingInfo:"hasDynamicLayers",labelsVisible:"hasDynamicLayers",opacity:"hasDynamicLayers",minScale:"visibleSublayers",maxScale:"visibleSublayers",renderer:"hasDynamicLayers",source:"hasDynamicLayers"};let y=class extends r{constructor(e){super(e),this.floors=null,this.scale=0}destroy(){this.layer=null}get dynamicLayers(){if(!this.hasDynamicLayers)return null;const e=this.visibleSublayers.map(e=>{const r=o(this.floors,e);return e.toExportImageJSON(r)});return e.length?JSON.stringify(e):null}get hasDynamicLayers(){return this.layer&&l(this.visibleSublayers,this.layer.serviceSublayers,this.layer.gdbVersion)}set layer(e){this._get("layer")!==e&&(this._set("layer",e),this.removeHandles("layer"),e&&this.addHandles([e.allSublayers.on("change",()=>this.notifyChange("visibleSublayers")),e.on("sublayer-update",e=>this.notifyChange(n[e.propertyName]))],"layer"))}get layers(){const e=this.visibleSublayers;return e?e.length?"show:"+e.map(e=>e.id).join(","):"show:-1":null}get layerDefs(){const e=!!this.floors?.length,r=this.visibleSublayers.filter(r=>null!=r.definitionExpression||e&&null!=r.floorInfo);return r.length?JSON.stringify(r.reduce((e,r)=>{const t=o(this.floors,r),i=s(t,r.definitionExpression);return null!=i&&(e[r.id]=i),e},{})):null}get version(){this.commitProperty("layers"),this.commitProperty("layerDefs"),this.commitProperty("dynamicLayers");const e=this.layer;return e&&(e.commitProperty("dpi"),e.commitProperty("imageFormat"),e.commitProperty("imageTransparency"),e.commitProperty("gdbVersion")),(this._get("version")||0)+1}get visibleSublayers(){const e=[];if(!this.layer)return e;const r=this.layer.sublayers,s=this.scale,t=r=>{r.visible&&(0===s||a(s,r.minScale,r.maxScale))&&(r.sublayers?r.sublayers.forEach(t):e.unshift(r))};r
|
|
5
|
+
import{__decorate as e}from"tslib";import r from"../../core/Accessor.js";import{sqlAnd as s}from"../../core/sql.js";import{property as t}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/Logger.js";import"../../core/RandomLCG.js";import{subclass as i}from"../../core/accessorSupport/decorators/subclass.js";import{isInScaleRange as a}from"../../geometry/support/scaleUtils.js";import{getLayerFloorFilterClause as o}from"./floorFilterUtils.js";import{isExportDynamic as l}from"./sublayerUtils.js";const n={visible:"visibleSublayers",definitionExpression:"layerDefs",labelingInfo:"hasDynamicLayers",labelsVisible:"hasDynamicLayers",opacity:"hasDynamicLayers",minScale:"visibleSublayers",maxScale:"visibleSublayers",renderer:"hasDynamicLayers",source:"hasDynamicLayers"};let y=class extends r{constructor(e){super(e),this.floors=null,this.scale=0}destroy(){this.layer=null}get dynamicLayers(){if(!this.hasDynamicLayers)return null;const e=this.visibleSublayers.map(e=>{const r=o(this.floors,e);return e.toExportImageJSON(r)});return e.length?JSON.stringify(e):null}get hasDynamicLayers(){return this.layer&&l(this.visibleSublayers,this.layer.serviceSublayers,this.layer.gdbVersion)}set layer(e){this._get("layer")!==e&&(this._set("layer",e),this.removeHandles("layer"),e&&this.addHandles([e.allSublayers.on("change",()=>this.notifyChange("visibleSublayers")),e.on("sublayer-update",e=>this.notifyChange(n[e.propertyName]))],"layer"))}get layers(){const e=this.visibleSublayers;return e?e.length?"show:"+e.map(e=>e.id).join(","):"show:-1":null}get layerDefs(){const e=!!this.floors?.length,r=this.visibleSublayers.filter(r=>null!=r.definitionExpression||e&&null!=r.floorInfo);return r.length?JSON.stringify(r.reduce((e,r)=>{const t=o(this.floors,r),i=s(t,r.definitionExpression);return null!=i&&(e[r.id]=i),e},{})):null}get version(){this.commitProperty("layers"),this.commitProperty("layerDefs"),this.commitProperty("dynamicLayers");const e=this.layer;return e&&(e.commitProperty("dpi"),e.commitProperty("imageFormat"),e.commitProperty("imageTransparency"),e.commitProperty("gdbVersion")),(this._get("version")||0)+1}get visibleSublayers(){const e=[];if(!this.layer)return e;const r=this.layer.sublayers,s=this.scale,t=r=>{r.visible&&(0===s||a(s,r.minScale,r.maxScale))&&(r.sublayers?r.sublayers.forEach(t):e.unshift(r))};r?.forEach(t);const i=this._get("visibleSublayers");return!i||i.length!==e.length||i.some((r,s)=>e[s]!==r)?e:i}toJSON(){const e=this.layer;let r={dpi:e.dpi,format:e.imageFormat,transparent:e.imageTransparency,gdbVersion:e.gdbVersion||null};return this.hasDynamicLayers&&this.dynamicLayers?r.dynamicLayers=this.dynamicLayers:r={...r,layers:this.layers,layerDefs:this.layerDefs},r}};e([t({readOnly:!0})],y.prototype,"dynamicLayers",null),e([t()],y.prototype,"floors",void 0),e([t({readOnly:!0})],y.prototype,"hasDynamicLayers",null),e([t()],y.prototype,"layer",null),e([t({readOnly:!0})],y.prototype,"layers",null),e([t({readOnly:!0})],y.prototype,"layerDefs",null),e([t({type:Number})],y.prototype,"scale",void 0),e([t({readOnly:!0})],y.prototype,"version",null),e([t({readOnly:!0})],y.prototype,"visibleSublayers",null),y=e([i("esri.layers.support.ExportImageParameters")],y);export{y as ExportImageParameters};
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.34/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import{__decorate as e}from"tslib";import t from"../Graphic.js";import{getOrCreateMapValue as r}from"../core/MapUtils.js";import{watch as s}from"../core/reactiveUtils.js";import{property as o}from"../core/accessorSupport/decorators/property.js";import"../core/has.js";import"../core/Logger.js";import"../core/RandomLCG.js";import{subclass as i}from"../core/accessorSupport/decorators/subclass.js";import a from"../layers/FeatureLayer.js";import{queryAllJSON as n}from"../layers/support/featureQueryAll.js";import l from"./Network.js";import u from"./RulesTable.js";import m from"./support/NamedTraceConfiguration.js";import{getAssociationsTableFields as d}from"./support/networkFieldUtils.js";import c from"./support/NetworkSystemLayers.js";import y from"./support/TerminalConfiguration.js";import p from"./support/TraceJobInfo.js";import{AssociationTypeEnum as f,associationTypeKebabDict as h}from"./support/typeUtils.js";import{doesRuleAllowAssociation as I}from"./support/utils.js";import b from"../rest/networks/support/TelecomNetworkElement.js";import g from"../rest/support/Query.js";let w=class extends l{constructor(e){super(e),this.sharedNamedTraceConfigurations=[],this.type="utility",this._circuitManagerMap=new Map,this._terminalById=new Map,this._unitIdentifierManager=null}initialize(){this.addHandles(s(()=>[this.gdbVersion,this.historicMoment],()=>{this.networkSystemLayers.associationsTable&&(this.networkSystemLayers.associationsTable.gdbVersion!==this.gdbVersion&&(this.networkSystemLayers.associationsTable.gdbVersion=this.gdbVersion),this.networkSystemLayers.associationsTable.historicMoment!==this.historicMoment&&(this.networkSystemLayers.associationsTable.historicMoment=this.historicMoment))}))}get _rulesLayer(){const{gdbVersion:e,historicMoment:t}=this,r=this.networkSystemLayers.rulesTableUrl;return new a({url:r,gdbVersion:e,historicMoment:t})}get _utilityLayerList(){const e=new Set;return this.dataElement?.domainNetworks?.map(t=>{t?.edgeSources?.map(({layerId:t,sourceId:r})=>{this._layerIdBySourceId.set(r,t),this._sourceIdByLayerId.set(t,r),e.add(t)}),t?.junctionSources?.map(({layerId:t,sourceId:r})=>{this._layerIdBySourceId.set(r,t),this._sourceIdByLayerId.set(t,r),e.add(t)})}),e}get serviceTerritoryFeatureLayerId(){return this.dataElement?.serviceTerritoryFeatureLayerId??null}get networkSystemLayers(){return new c({rulesTableId:this.sourceJSON?.systemLayers.rulesTableId,rulesTableUrl:this.sourceJSON?`${this.featureServiceUrl}/${this.sourceJSON?.systemLayers.rulesTableId}`:null,subnetworksTableId:this.sourceJSON?.systemLayers.subnetworksTableId,subnetworksTableUrl:this.sourceJSON?`${this.featureServiceUrl}/${this.sourceJSON?.systemLayers.subnetworksTableId}`:null,dirtyAreasLayerId:this.sourceJSON?.systemLayers.dirtyAreasLayerId,dirtyAreasLayerUrl:this.sourceJSON?`${this.featureServiceUrl}/${this.sourceJSON?.systemLayers.dirtyAreasLayerId}`:null,associationsTableId:this.sourceJSON?.systemLayers.associationsTableId,associationsTableUrl:this.sourceJSON?`${this.featureServiceUrl}/${this.sourceJSON?.systemLayers.associationsTableId}`:null})}get terminalConfigurations(){return this.dataElement?.terminalConfigurations.map(e=>y.fromJSON(e))||[]}get domainNetworkNames(){return this.dataElement?.domainNetworks.map(e=>e.domainNetworkName)||[]}get hasTelecomNetwork(){return this.dataElement?.domainNetworks.some(e=>e.isTelecomNetwork)??!1}get associationsTable(){return this.networkSystemLayers.associationsTable}async load(e){return this.addResolvingPromise(this._load(e)),this}async _load(e){await super._load(e),await Promise.all([this._loadNamedTraceConfigurationsFromNetwork(e),this.networkSystemLayers.loadAssociationsTable(e)])}getTerminalConfiguration(e){let t=null,r=null;const s=e.sourceLayer;let o=null;if("feature"===s?.type){if(o=s.layerId,null===o)return null}else{if("subtype-sublayer"!==s?.type)return null;if(o=s?.parent?.layerId??null,null===o)return null}const i=e.attributes;if(null==i)return null;for(const l of Object.keys(i))"ASSETGROUP"===l.toUpperCase()&&(t=e.getAttribute(l)),"ASSETTYPE"===l.toUpperCase()&&(r=e.getAttribute(l));if(!this.dataElement)return null;let a=null;const n=this.dataElement.domainNetworks;for(const l of n){const e=l.junctionSources?.find(e=>e.layerId===o);if(e){const s=e.assetGroups?.find(e=>e.assetGroupCode===t);if(s){const e=s.assetTypes?.find(e=>e.assetTypeCode===r);if(e?.isTerminalConfigurationSupported){a=e.terminalConfigurationId;break}}}}if(null!=a){const e=this.dataElement.terminalConfigurations,t=e?.find(e=>e.terminalConfigurationId===a);return t?y.fromJSON(t):null}return null}getTierNames(e){const t=this.dataElement?.domainNetworks.find(t=>t.domainNetworkName===e);return t?.tiers?.map(e=>e.name)||[]}async getRulesTable(){const e=this._rulesLayer;e.loaded||await e.load();const t=this.dataElement?.domainNetworks;if(!t)return null;const r=t.flatMap(e=>[...e.edgeSources||[],...e.junctionSources||[]]),s=(await this._queryRulesTable(e)).map(t=>this._hydrateRuleInfo(e,r,t));return new u({rulesLayer:e,rules:s})}async getCircuitManager(e){if(!this.hasTelecomNetwork)return null;const t=this.dataElement?.domainNetworks.find(t=>t.domainNetworkName===e&&t.isTelecomNetwork);if(!t)return null;const{default:s}=await import("./CircuitManager.js");return r(this._circuitManagerMap,e,()=>new s({utilityNetwork:this,telecomDomainNetwork:t}))}async getUnitIdentifierManager(){if(!this.hasTelecomNetwork)return null;if(this._unitIdentifierManager)return this._unitIdentifierManager;const{default:e}=await import("./UnitIdentifierManager.js");return this._unitIdentifierManager=new e({utilityNetwork:this}),this._unitIdentifierManager}getTerminalById(e){if(!this.dataElement||null==e)return null;const t=this._terminalById.get(e);return null!=t?t:(this.terminalConfigurations.forEach(e=>{e.terminals.forEach(e=>{this._terminalById.set(e.id,e)})}),this._terminalById.get(e))}isUtilityLayer(e){return"layerId"in e?null!=e.layerId&&this._utilityLayerList.has(e.layerId)&&(e.url?.startsWith(this.featureServiceUrl)??!1):!("subtype-sublayer"!==e.type||!e.parent)&&(this._utilityLayerList.has(e.parent.layerId)&&(e.parent.url?.startsWith(this.featureServiceUrl)??!1))}async queryAssociations(e,t){const[{queryAssociations:r},{default:s}]=await Promise.all([import("../rest/networks/queryAssociations.js"),import("../rest/networks/support/QueryAssociationsParameters.js")]),o=s.from(e);o.gdbVersion=this.gdbVersion,o.moment=this.historicMoment;return(await r(this.networkServiceUrl,o,t)).associations}async synthesizeAssociationGeometries(e){const[{synthesizeAssociationGeometries:t},{default:r}]=await Promise.all([import("../rest/networks/synthesizeAssociationGeometries.js"),import("../rest/networks/support/SynthesizeAssociationGeometriesParameters.js")]),s=r.from(e);return s.gdbVersion=this.gdbVersion,s.moment=this.historicMoment,t(this.networkServiceUrl,s)}async trace(e){const[{trace:t},{default:r}]=await Promise.all([import("../rest/networks/trace.js"),import("../rest/networks/support/TraceParameters.js")]),s=r.from(e);return s.gdbVersion=this.gdbVersion,s.moment=this.historicMoment,t(this.networkServiceUrl,s)}async submitTraceJob(e){const[{submitTraceJob:t},{default:r}]=await Promise.all([import("../rest/networks/trace.js"),import("../rest/networks/support/TraceParameters.js")]),s=r.from(e);s.gdbVersion=this.gdbVersion,s.moment=this.historicMoment;const o=await t(this.networkServiceUrl,s);return new p({statusUrl:o})}async canAddAssociation(e){const t=await this.getRulesTable();if(!t)return!1;const{fromNetworkElement:r,toNetworkElement:s}=e;if(!r||!s)return!1;await t.load();let o=null;switch(e.associationType){case"containment":o=t.rulesCategorized.containment;break;case"attachment":o=t.rulesCategorized.attachment;break;default:o=t.rulesCategorized.connectivity}return o.some(e=>I(e,r,s))}generateAddAssociations(e){const{associationsTable:r}=this.networkSystemLayers,{fromNetworkSourceId:s,fromGlobalId:o,fromTerminalId:i,fromFirstUnit:a,fromNumUnits:n,toNetworkSourceId:l,toGlobalId:u,toTerminalId:m,toFirstUnit:c,toNumUnits:y,associationType:p,isContentVisible:h,percentAlong:I,globalId:g}=d(r);return{addFeatures:e.map(e=>{const r=new t({attributes:{[s]:e.fromNetworkElement?.networkSourceId,[o]:e.fromNetworkElement?.globalId,[i]:e.fromNetworkElement?.terminalId,[l]:e.toNetworkElement?.networkSourceId,[u]:e.toNetworkElement?.globalId,[m]:e.toNetworkElement?.terminalId,[p]:f[e.associationType],[h]:null==e.isContentVisible?void 0:e.isContentVisible?1:0,[I]:e.percentAlong,[g]:e.globalId}});return e.fromNetworkElement instanceof b&&(r.attributes[a]=e.fromNetworkElement?.firstUnit,r.attributes[n]=e.fromNetworkElement?.numUnits),e.toNetworkElement instanceof b&&(r.attributes[c]=e.toNetworkElement?.firstUnit,r.attributes[y]=e.toNetworkElement?.numUnits),r}),id:this.networkSystemLayers.associationsTableId,identifierFields:{globalIdField:r?.globalIdField??"globalid",objectIdField:r?.objectIdField??"objectid"}}}generateDeleteAssociations(e){const{associationsTable:t,associationsTableId:r}=this.networkSystemLayers,s={id:r,identifierFields:{globalIdField:t?.globalIdField??"globalid",objectIdField:t?.objectIdField??"objectid"}};if(-8===this.dataElement?.schemaGeneration){const t=this._generateDeleteTelecomAssociationPayload(e);return{...s,deleteAssociations:t}}const o=e.map(e=>({globalId:e.globalId}));return{...s,deleteFeatures:o}}async loadAssociationsTable(){return this.networkSystemLayers.loadAssociationsTable()}async _loadNamedTraceConfigurationsFromNetwork(e){if(0===this.sharedNamedTraceConfigurations?.length)return;const t=this.sharedNamedTraceConfigurations.map(e=>e.globalId),r=await this.queryNamedTraceConfigurations({globalIds:t},e);for(const s of this.sharedNamedTraceConfigurations){const e=r?.find(e=>e.globalId===s.globalId);if(e){const t=e.write({},{origin:"service"});s.read(t,{origin:"service"})}}}_hydrateRuleInfo(e,t,r){const s=e.fieldsIndex,o=s.get("RULETYPE"),i=s.get("CREATIONDATE"),a=s.get("FROMNETWORKSOURCEID"),n=s.get("FROMASSETGROUP"),l=s.get("FROMASSETTYPE"),u=s.get("FROMTERMINALID"),m=s.get("TONETWORKSOURCEID"),d=s.get("TOASSETGROUP"),c=s.get("TOASSETTYPE"),y=s.get("TOTERMINALID"),p=s.get("VIANETWORKSOURCEID"),f=s.get("VIAASSETGROUP"),h=s.get("VIAASSETTYPE"),I=s.get("VIATERMINALID"),b=r.attributes[o.name],g=new Date(r.attributes[i.name]),w=[{networkSourceId:r.attributes[a.name],assetGroupId:r.attributes[n.name],assetTypeId:r.attributes[l.name],terminalId:r.attributes[u.name]},{networkSourceId:r.attributes[m.name],assetGroupId:r.attributes[d.name],assetTypeId:r.attributes[c.name],terminalId:r.attributes[y.name]},{networkSourceId:r.attributes[p.name],assetGroupId:r.attributes[f.name],assetTypeId:r.attributes[h.name],terminalId:r.attributes[I.name]}],T={ruleType:b,creationDate:g};for(const k of[0,1,2]){if(5!==b&&2===k)continue;const e=w[k],r=t.find(t=>t.sourceId===e.networkSourceId),s=r?.assetGroups.find(t=>t.assetGroupCode===e.assetGroupId),o=s?.assetTypes.find(t=>t.assetTypeCode===e.assetTypeId),i=this._getTerminal(o,e);let a="";switch(k){case 0:a="from";break;case 1:a="to";break;case 2:a="via"}T[`${a}NetworkSource`]=r,T[`${a}AssetGroup`]=s,T[`${a}AssetType`]=o,T[`${a}Terminal`]=i?.toJSON()}return T}_getTerminal(e,t){const r=e?.terminalConfigurationId,s=this.terminalConfigurations?.find(e=>e.id===r);return s?.terminals?.find(e=>e.id===t.terminalId)??null}async _queryRulesTable(e){const{gdbVersion:t,historicMoment:r}=this,s=new g({where:"1=1",outFields:["*"],gdbVersion:t,historicMoment:r});return(await n(e,s)).features}_generateDeleteTelecomAssociationPayload(e){return e.map(e=>({globalId:e.globalId??"{00000000-0000-0000-0000-000000000000}",associationType:h.toJSON(e.associationType),fromSourceId:e.fromNetworkElement.networkSourceId,fromGlobalId:e.fromNetworkElement.globalId,fromTerminalId:e.fromNetworkElement.terminalId,toSourceId:e.toNetworkElement.networkSourceId,toGlobalId:e.toNetworkElement.globalId,toTerminalId:e.toNetworkElement.terminalId}))}};e([o({readOnly:!0})],w.prototype,"_rulesLayer",null),e([o({type:[m],json:{origins:{"web-map":{read:{source:"traceConfigurations"},write:{target:"traceConfigurations"}},service:{read:{source:"traceConfigurations"}}},read:!1}})],w.prototype,"sharedNamedTraceConfigurations",void 0),e([o({type:["utility"],readOnly:!0,json:{read:!1,write:!1}})],w.prototype,"type",void 0),e([o({readOnly:!0})],w.prototype,"serviceTerritoryFeatureLayerId",null),e([o({readOnly:!0})],w.prototype,"networkSystemLayers",null),e([o({readOnly:!0})],w.prototype,"terminalConfigurations",null),e([o({readOnly:!0})],w.prototype,"domainNetworkNames",null),e([o({readOnly:!0})],w.prototype,"hasTelecomNetwork",null),e([o({readOnly:!0,json:{read:!1}})],w.prototype,"associationsTable",null),w=e([i("esri.networks.UtilityNetwork")],w);const T=w;export{T as default};
|
|
5
|
+
import{__decorate as e}from"tslib";import t from"../Graphic.js";import{unique as r}from"../core/arrayUtils.js";import s from"../core/Error.js";import{getOrCreateMapValue as o}from"../core/MapUtils.js";import{watch as i}from"../core/reactiveUtils.js";import{property as a}from"../core/accessorSupport/decorators/property.js";import"../core/has.js";import"../core/Logger.js";import{subclass as n}from"../core/accessorSupport/decorators/subclass.js";import l from"../layers/FeatureLayer.js";import{queryAllJSON as u}from"../layers/support/featureQueryAll.js";import d from"./Network.js";import m from"./RulesTable.js";import c from"./support/NamedTraceConfiguration.js";import{getAssociationsTableFields as y}from"./support/networkFieldUtils.js";import h from"./support/NetworkSystemLayers.js";import p from"./support/TerminalConfiguration.js";import f from"./support/TraceJobInfo.js";import{AssociationTypeEnum as I,associationTypeKebabDict as w}from"./support/typeUtils.js";import{doesRuleAllowAssociation as g}from"./support/utils.js";import b from"../rest/networks/support/TelecomNetworkElement.js";import T from"../rest/support/Query.js";let k=class extends d{constructor(e){super(e),this.sharedNamedTraceConfigurations=[],this.type="utility",this._circuitManagerMap=new Map,this._terminalById=new Map,this._unitIdentifierManager=null}initialize(){this.addHandles(i(()=>[this.gdbVersion,this.historicMoment],()=>{this.networkSystemLayers.associationsTable&&(this.networkSystemLayers.associationsTable.gdbVersion!==this.gdbVersion&&(this.networkSystemLayers.associationsTable.gdbVersion=this.gdbVersion),this.networkSystemLayers.associationsTable.historicMoment!==this.historicMoment&&(this.networkSystemLayers.associationsTable.historicMoment=this.historicMoment))}))}get _rulesLayer(){const{gdbVersion:e,historicMoment:t}=this,r=this.networkSystemLayers.rulesTableUrl;return new l({url:r,gdbVersion:e,historicMoment:t})}get _utilityLayerList(){const e=new Set;return this.dataElement?.domainNetworks?.map(t=>{t?.edgeSources?.map(({layerId:t,sourceId:r})=>{this._layerIdBySourceId.set(r,t),this._sourceIdByLayerId.set(t,r),e.add(t)}),t?.junctionSources?.map(({layerId:t,sourceId:r})=>{this._layerIdBySourceId.set(r,t),this._sourceIdByLayerId.set(t,r),e.add(t)})}),e}get serviceTerritoryFeatureLayerId(){return this.dataElement?.serviceTerritoryFeatureLayerId??null}get networkSystemLayers(){return new h({rulesTableId:this.sourceJSON?.systemLayers.rulesTableId,rulesTableUrl:this.sourceJSON?`${this.featureServiceUrl}/${this.sourceJSON?.systemLayers.rulesTableId}`:null,subnetworksTableId:this.sourceJSON?.systemLayers.subnetworksTableId,subnetworksTableUrl:this.sourceJSON?`${this.featureServiceUrl}/${this.sourceJSON?.systemLayers.subnetworksTableId}`:null,dirtyAreasLayerId:this.sourceJSON?.systemLayers.dirtyAreasLayerId,dirtyAreasLayerUrl:this.sourceJSON?`${this.featureServiceUrl}/${this.sourceJSON?.systemLayers.dirtyAreasLayerId}`:null,associationsTableId:this.sourceJSON?.systemLayers.associationsTableId,associationsTableUrl:this.sourceJSON?`${this.featureServiceUrl}/${this.sourceJSON?.systemLayers.associationsTableId}`:null})}get terminalConfigurations(){return this.dataElement?.terminalConfigurations.map(e=>p.fromJSON(e))||[]}get domainNetworkNames(){return this.dataElement?.domainNetworks.map(e=>e.domainNetworkName)||[]}get hasTelecomNetwork(){return this.dataElement?.domainNetworks.some(e=>e.isTelecomNetwork)??!1}get associationsTable(){return this.networkSystemLayers.associationsTable}async load(e){return this.addResolvingPromise(this._load(e)),this}async _load(e){await super._load(e),await Promise.all([this._loadNamedTraceConfigurationsFromNetwork(e),this.networkSystemLayers.loadAssociationsTable(e)])}getTerminalConfiguration(e){let t=null,r=null;const s=e.sourceLayer;let o=null;if("feature"===s?.type){if(o=s.layerId,null===o)return null}else{if("subtype-sublayer"!==s?.type)return null;if(o=s?.parent?.layerId??null,null===o)return null}const i=e.attributes;if(null==i)return null;for(const l of Object.keys(i))"ASSETGROUP"===l.toUpperCase()&&(t=e.getAttribute(l)),"ASSETTYPE"===l.toUpperCase()&&(r=e.getAttribute(l));if(!this.dataElement)return null;let a=null;const n=this.dataElement.domainNetworks;for(const l of n){const e=l.junctionSources?.find(e=>e.layerId===o);if(e){const s=e.assetGroups?.find(e=>e.assetGroupCode===t);if(s){const e=s.assetTypes?.find(e=>e.assetTypeCode===r);if(e?.isTerminalConfigurationSupported){a=e.terminalConfigurationId;break}}}}if(null!=a){const e=this.dataElement.terminalConfigurations,t=e?.find(e=>e.terminalConfigurationId===a);return t?p.fromJSON(t):null}return null}getTierNames(e){const t=this.dataElement?.domainNetworks.find(t=>t.domainNetworkName===e);return t?.tiers?.map(e=>e.name)||[]}async getRulesTable(){const e=this._rulesLayer;e.loaded||await e.load();const t=this.dataElement?.domainNetworks;if(!t)return null;const r=t.flatMap(e=>[...e.edgeSources||[],...e.junctionSources||[]]),s=(await this._queryRulesTable(e)).map(t=>this._hydrateRuleInfo(e,r,t));return new m({rulesLayer:e,rules:s})}async getCircuitManager(e){if(!this.hasTelecomNetwork)return null;const t=this.dataElement?.domainNetworks.find(t=>t.domainNetworkName===e&&t.isTelecomNetwork);if(!t)return null;const{default:r}=await import("./CircuitManager.js");return o(this._circuitManagerMap,e,()=>new r({utilityNetwork:this,telecomDomainNetwork:t}))}async getUnitIdentifierManager(){if(!this.hasTelecomNetwork)return null;if(this._unitIdentifierManager)return this._unitIdentifierManager;const{default:e}=await import("./UnitIdentifierManager.js");return this._unitIdentifierManager=new e({utilityNetwork:this}),this._unitIdentifierManager}getTerminalById(e){if(!this.dataElement||null==e)return null;const t=this._terminalById.get(e);return null!=t?t:(this.terminalConfigurations.forEach(e=>{e.terminals.forEach(e=>{this._terminalById.set(e.id,e)})}),this._terminalById.get(e))}isUtilityLayer(e){return"layerId"in e?null!=e.layerId&&this._utilityLayerList.has(e.layerId)&&(e.url?.startsWith(this.featureServiceUrl)??!1):!("subtype-sublayer"!==e.type||!e.parent)&&(this._utilityLayerList.has(e.parent.layerId)&&(e.parent.url?.startsWith(this.featureServiceUrl)??!1))}async queryAssociations(e,t){const[{queryAssociations:r},{default:s}]=await Promise.all([import("../rest/networks/queryAssociations.js"),import("../rest/networks/support/QueryAssociationsParameters.js")]),o=s.from(e);o.gdbVersion=this.gdbVersion,o.moment=this.historicMoment;return(await r(this.networkServiceUrl,o,t)).associations}async synthesizeAssociationGeometries(e){const[{synthesizeAssociationGeometries:t},{default:r}]=await Promise.all([import("../rest/networks/synthesizeAssociationGeometries.js"),import("../rest/networks/support/SynthesizeAssociationGeometriesParameters.js")]),s=r.from(e);return s.gdbVersion=this.gdbVersion,s.moment=this.historicMoment,t(this.networkServiceUrl,s)}async trace(e){const[{trace:t},{default:r}]=await Promise.all([import("../rest/networks/trace.js"),import("../rest/networks/support/TraceParameters.js")]),s=r.from(e);return s.gdbVersion=this.gdbVersion,s.moment=this.historicMoment,t(this.networkServiceUrl,s)}async submitTraceJob(e){const[{submitTraceJob:t},{default:r}]=await Promise.all([import("../rest/networks/trace.js"),import("../rest/networks/support/TraceParameters.js")]),s=r.from(e);s.gdbVersion=this.gdbVersion,s.moment=this.historicMoment;const o=await t(this.networkServiceUrl,s);return new f({statusUrl:o})}async canAddAssociation(e){const t=await this.getRulesTable();if(!t)return!1;const{fromNetworkElement:r,toNetworkElement:s}=e;if(!r||!s)return!1;await t.load();let o=null;switch(e.associationType){case"containment":o=t.rulesCategorized.containment;break;case"attachment":o=t.rulesCategorized.attachment;break;default:o=t.rulesCategorized.connectivity}return o.some(e=>g(e,r,s))}generateAddAssociations(e){const{associationsTable:r}=this.networkSystemLayers,{fromNetworkSourceId:s,fromGlobalId:o,fromTerminalId:i,fromFirstUnit:a,fromNumUnits:n,toNetworkSourceId:l,toGlobalId:u,toTerminalId:d,toFirstUnit:m,toNumUnits:c,associationType:h,isContentVisible:p,percentAlong:f,globalId:w}=y(r);return{addFeatures:e.map(e=>{const r=new t({attributes:{[s]:e.fromNetworkElement?.networkSourceId,[o]:e.fromNetworkElement?.globalId,[i]:e.fromNetworkElement?.terminalId,[l]:e.toNetworkElement?.networkSourceId,[u]:e.toNetworkElement?.globalId,[d]:e.toNetworkElement?.terminalId,[h]:I[e.associationType],[p]:null==e.isContentVisible?void 0:e.isContentVisible?1:0,[f]:e.percentAlong,[w]:e.globalId}});return e.fromNetworkElement instanceof b&&(r.attributes[a]=e.fromNetworkElement?.firstUnit,r.attributes[n]=e.fromNetworkElement?.numUnits),e.toNetworkElement instanceof b&&(r.attributes[m]=e.toNetworkElement?.firstUnit,r.attributes[c]=e.toNetworkElement?.numUnits),r}),id:this.networkSystemLayers.associationsTableId,identifierFields:{globalIdField:r?.globalIdField??"globalid",objectIdField:r?.objectIdField??"objectid"}}}generateDeleteAssociations(e){const{associationsTable:t,associationsTableId:r}=this.networkSystemLayers,s={id:r,identifierFields:{globalIdField:t?.globalIdField??"globalid",objectIdField:t?.objectIdField??"objectid"}};if(-8===this.dataElement?.schemaGeneration){const t=this._generateDeleteTelecomAssociationPayload(e);return{...s,deleteAssociations:t}}const o=e.map(e=>({globalId:e.globalId}));return{...s,deleteFeatures:o}}generateCombineNetworkElements(e){return{id:this._ensureSingleSourceIdAsValidLayerId(e),combineGroupedObjects:[{globalIds:e.map(e=>e.globalId)}]}}generateDivideNetworkElements(e,t){return{id:this._ensureSingleSourceIdAsValidLayerId([e]),divideGroupedObjects:[{globalId:e.globalId,numUnits:t}]}}async loadAssociationsTable(){return this.networkSystemLayers.loadAssociationsTable()}async _loadNamedTraceConfigurationsFromNetwork(e){if(0===this.sharedNamedTraceConfigurations?.length)return;const t=this.sharedNamedTraceConfigurations.map(e=>e.globalId),r=await this.queryNamedTraceConfigurations({globalIds:t},e);for(const s of this.sharedNamedTraceConfigurations){const e=r?.find(e=>e.globalId===s.globalId);if(e){const t=e.write({},{origin:"service"});s.read(t,{origin:"service"})}}}_hydrateRuleInfo(e,t,r){const s=e.fieldsIndex,o=s.get("RULETYPE"),i=s.get("CREATIONDATE"),a=s.get("FROMNETWORKSOURCEID"),n=s.get("FROMASSETGROUP"),l=s.get("FROMASSETTYPE"),u=s.get("FROMTERMINALID"),d=s.get("TONETWORKSOURCEID"),m=s.get("TOASSETGROUP"),c=s.get("TOASSETTYPE"),y=s.get("TOTERMINALID"),h=s.get("VIANETWORKSOURCEID"),p=s.get("VIAASSETGROUP"),f=s.get("VIAASSETTYPE"),I=s.get("VIATERMINALID"),w=r.attributes[o.name],g=new Date(r.attributes[i.name]),b=[{networkSourceId:r.attributes[a.name],assetGroupId:r.attributes[n.name],assetTypeId:r.attributes[l.name],terminalId:r.attributes[u.name]},{networkSourceId:r.attributes[d.name],assetGroupId:r.attributes[m.name],assetTypeId:r.attributes[c.name],terminalId:r.attributes[y.name]},{networkSourceId:r.attributes[h.name],assetGroupId:r.attributes[p.name],assetTypeId:r.attributes[f.name],terminalId:r.attributes[I.name]}],T={ruleType:w,creationDate:g};for(const k of[0,1,2]){if(5!==w&&2===k)continue;const e=b[k],r=t.find(t=>t.sourceId===e.networkSourceId),s=r?.assetGroups.find(t=>t.assetGroupCode===e.assetGroupId),o=s?.assetTypes.find(t=>t.assetTypeCode===e.assetTypeId),i=this._getTerminal(o,e);let a="";switch(k){case 0:a="from";break;case 1:a="to";break;case 2:a="via"}T[`${a}NetworkSource`]=r,T[`${a}AssetGroup`]=s,T[`${a}AssetType`]=o,T[`${a}Terminal`]=i?.toJSON()}return T}_getTerminal(e,t){const r=e?.terminalConfigurationId,s=this.terminalConfigurations?.find(e=>e.id===r);return s?.terminals?.find(e=>e.id===t.terminalId)??null}async _queryRulesTable(e){const{gdbVersion:t,historicMoment:r}=this,s=new T({where:"1=1",outFields:["*"],gdbVersion:t,historicMoment:r});return(await u(e,s)).features}_generateDeleteTelecomAssociationPayload(e){return e.map(e=>({globalId:e.globalId??"{00000000-0000-0000-0000-000000000000}",associationType:w.toJSON(e.associationType),fromSourceId:e.fromNetworkElement.networkSourceId,fromGlobalId:e.fromNetworkElement.globalId,fromTerminalId:e.fromNetworkElement.terminalId,toSourceId:e.toNetworkElement.networkSourceId,toGlobalId:e.toNetworkElement.globalId,toTerminalId:e.toNetworkElement.terminalId}))}_ensureSingleSourceIdAsValidLayerId(e){const t=r(e.map(e=>e.networkSourceId));if(t.length>1)throw new s("utility-network:invalid-source-id","'networkSourceId' is not valid. Ensure that all network elements have the same 'networkSourceId' and that it corresponds to a valid layer in the utility network.");const o=t[0],i=this.getLayerIdBySourceId(o);if(null==i)throw new s("utility-network:invalid-source-id","'networkSourceId' is not valid. Ensure that all network elements have the same 'networkSourceId' and that it corresponds to a valid layer in the utility network.");return i}};e([a({readOnly:!0})],k.prototype,"_rulesLayer",null),e([a({type:[c],json:{origins:{"web-map":{read:{source:"traceConfigurations"},write:{target:"traceConfigurations"}},service:{read:{source:"traceConfigurations"}}},read:!1}})],k.prototype,"sharedNamedTraceConfigurations",void 0),e([a({type:["utility"],readOnly:!0,json:{read:!1,write:!1}})],k.prototype,"type",void 0),e([a({readOnly:!0})],k.prototype,"serviceTerritoryFeatureLayerId",null),e([a({readOnly:!0})],k.prototype,"networkSystemLayers",null),e([a({readOnly:!0})],k.prototype,"terminalConfigurations",null),e([a({readOnly:!0})],k.prototype,"domainNetworkNames",null),e([a({readOnly:!0})],k.prototype,"hasTelecomNetwork",null),e([a({readOnly:!0,json:{read:!1}})],k.prototype,"associationsTable",null),k=e([n("esri.networks.UtilityNetwork")],k);const S=k;export{S as default};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@arcgis/core",
|
|
3
|
-
"version": "4.34.0-next.
|
|
3
|
+
"version": "4.34.0-next.53",
|
|
4
4
|
"homepage": "https://js.arcgis.com",
|
|
5
5
|
"description": "ArcGIS Maps SDK for JavaScript: A complete 2D and 3D mapping and data visualization API",
|
|
6
6
|
"keywords": [
|
|
@@ -21,9 +21,9 @@
|
|
|
21
21
|
"@esri/arcgis-html-sanitizer": "~4.1.0",
|
|
22
22
|
"@esri/calcite-components": "^3.2.1",
|
|
23
23
|
"@vaadin/grid": "~24.8.4",
|
|
24
|
-
"@zip.js/zip.js": "~2.7.
|
|
24
|
+
"@zip.js/zip.js": "~2.7.72",
|
|
25
25
|
"luxon": "~3.7.1",
|
|
26
|
-
"marked": "~16.1.
|
|
26
|
+
"marked": "~16.1.2",
|
|
27
27
|
"tslib": "^2.8.1"
|
|
28
28
|
},
|
|
29
29
|
"type": "module"
|
package/portal/Portal.js
CHANGED
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.34/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import{__decorate as e}from"tslib";import t from"../config.js";import{id as r}from"../kernel.js";import o from"../request.js";import s from"../core/Error.js";import{JSONSupportMixin as a}from"../core/JSONSupport.js";import{Loadable as i}from"../core/Loadable.js";import{destroyMaybe as l,removeMaybe as u}from"../core/maybe.js";import{throwIfAborted as n,isAborted as p,createAbortError as h,throwIfAbortError as d}from"../core/promiseUtils.js";import{property as c}from"../core/accessorSupport/decorators/property.js";import{ensureType as y}from"../core/accessorSupport/ensureType.js";import"../core/has.js";import"../core/RandomLCG.js";import{reader as m}from"../core/accessorSupport/decorators/reader.js";import{subclass as f}from"../core/accessorSupport/decorators/subclass.js";import v from"../geometry/Extent.js";import{getLocale as S}from"../intl/locale.js";import{ensureDefaultPortalInstance as P}from"./portalDefault.js";import g from"./PortalGroup.js";import O from"./PortalQueryParams.js";import B from"./PortalQueryResult.js";import D from"./PortalUser.js";import{isApiKeyApplicable as G,hasBasemapStylesApiKey as _}from"../support/apiKeyUtils.js";var U;let M;const Q={PortalGroup:()=>Promise.resolve({default:g}),PortalItem:()=>import("./PortalItem.js"),PortalUser:()=>Promise.resolve({default:D})};let C=class extends(a(i)){static{U=this}static{this.AUTH_MODE_ANONYMOUS="anonymous"}static{this.AUTH_MODE_AUTO="auto"}static{this.AUTH_MODE_IMMEDIATE="immediate"}static{this.AUTH_MODE_NO_PROMPT="no-prompt"}constructor(e){super(e),this._esriIdCredentialCreateHandle=null,this.access=null,this.allSSL=!1,this.authMode="auto",this.authorizedCrossOriginDomains=null,this.basemapGalleryGroupQuery=null,this.basemapGalleryGroupQuery3D=null,this.bingKey=null,this.canListApps=!1,this.canListData=!1,this.canListPreProvisionedItems=!1,this.canProvisionDirectPurchase=!1,this.canSearchPublic=!0,this.canShareBingPublic=!1,this.canSharePublic=!1,this.canSignInArcGIS=!1,this.canSignInIDP=!1,this.colorSetsGroupQuery=null,this.commentsEnabled=!1,this.created=null,this.culture=null,this.customBaseUrl=null,this.default3DBasemapQuery=null,this.defaultBasemap=null,this.defaultDevBasemap=null,this.defaultExtent=null,this.defaultVectorBasemap=null,this.description=null,this.devBasemapGalleryGroupQuery=null,this.eueiEnabled=null,this.featuredGroups=null,this.featuredItemsGroupQuery=null,this.galleryTemplatesGroupQuery=null,this.layoutGroupQuery=null,this.livingAtlasGroupQuery=null,this.hasCategorySchema=!1,this.hasClassificationSchema=!1,this.helperServices=null,this.homePageFeaturedContent=null,this.homePageFeaturedContentCount=null,this.httpPort=null,this.httpsPort=null,this.id=null,this.ipCntryCode=null,this.isPortal=!1,this.isReadOnly=!1,this.layerTemplatesGroupQuery=null,this.maxTokenExpirationMinutes=null,this.modified=null,this.name=null,this.portalHostname=null,this.portalMode=null,this.portalProperties=null,this.region=null,this.recycleBinEnabled=!1,this.rotatorPanels=null,this.showHomePageDescription=!1,this.sourceJSON=null,this.supportsHostedServices=!1,this.symbolSetsGroupQuery=null,this.templatesGroupQuery=null,this.units=null,this.url=t.portalUrl,this.urlKey=null,this.user=null,this.use3dBasemaps=!0,this.useDefault3dBasemap=!1,this.useStandardizedQuery=!1,this.useVectorBasemaps=!1,this.vectorBasemapGalleryGroupQuery=null}normalizeCtorArgs(e){return"string"==typeof e?{url:e}:e}destroy(){b.unregister(this),this.defaultBasemap=l(this.defaultBasemap),this.defaultDevBasemap=l(this.defaultDevBasemap),this.defaultVectorBasemap=l(this.defaultVectorBasemap),this._esriIdCredentialCreateHandle=u(this._esriIdCredentialCreateHandle)}readAuthorizedCrossOriginDomains(e){if(e)for(const r of e)t.request.trustedServers.includes(r)||t.request.trustedServers.push(r);return e}readDefaultBasemap(e){return this._readBasemap(e)}readDefaultDevBasemap(e){return this._readBasemap(e)}readDefaultVectorBasemap(e){return this._readBasemap(e)}get extraQuery(){const e=this.user?.orgId,t=!e||this.canSearchPublic;return this.id&&!t?` AND orgid:${this.id}`:null}get hasAPIKey(){return G(this.restUrl)}get isOrganization(){return!!this.access}get itemPageUrl(){return this.url?`${this.url}/home/item.html`:null}get loaded(){return super.loaded}get restUrl(){let e=this.url;if(e){const t=e.indexOf("/sharing");e=t>0?e.slice(0,t):this.url.replace(/\/+$/,""),e+="/sharing/rest"}return e}get thumbnailUrl(){const e=this.restUrl,t=this.thumbnail;return e&&t?this._normalizeSSL(e+"/portals/self/resources/"+t):null}readUrlKey(e){return e?e.toLowerCase():e}readUser(e){let t=null;return e&&(t=D.fromJSON(e),t.portal=this),t}load(e){const t=import("../Basemap.js").then(({default:t})=>{n(e),M=t}).then(()=>this.sourceJSON?this.sourceJSON:this.fetchSelf(this.authMode,!1,e)).then(e=>{if(!this.hasAPIKey&&r){const e=r;this.credential=e.findCredential(this.restUrl),this.credential||this.authMode!==U.AUTH_MODE_AUTO&&this.authMode!==U.AUTH_MODE_NO_PROMPT||(this._esriIdCredentialCreateHandle?.remove(),this._esriIdCredentialCreateHandle=e.on("credential-create",w(new WeakRef(this))),b.register(this,this._esriIdCredentialCreateHandle,this))}this.sourceJSON=e,this.read(e)});return this.addResolvingPromise(t),Promise.resolve(this)}async createElevationLayers(){await this.load();const e=this._getHelperService("defaultElevationLayers"),t=(await import("../layers/ElevationLayer.js")).default;return e?e.map(e=>new t({id:e.id,url:e.url})):[]}async fetchBasemaps(e,t){const r=await this._fetchBasemaps(e,t);if(!0===t?.include3d&&!1!==this.use3dBasemaps){const o=await this._fetchBasemaps3D(e,t);r.unshift(...o)}return r}async fetchDefault3DBasemap(e){if(!this.useDefault3dBasemap||!this.default3DBasemapQuery||"none"===this.default3DBasemapQuery)return null;const t=new O;t.query=this.default3DBasemapQuery,t.disableExtraQuery=!0;const r=(await this.queryItems(t,e)).results.find(e=>"Web Scene"===e.type);return r?new M({portalItem:r}):null}fetchCategorySchema(e){return this.hasCategorySchema?this.request(this.restUrl+"/portals/self/categorySchema",e).then(e=>e.categorySchema):p(e)?Promise.reject(h()):Promise.resolve([])}async fetchClassificationSchema(e){return this.hasClassificationSchema?this.request(this.restUrl+"/portals/self/classification/classificationSchema",e).then(e=>e.classificationSchema):null}fetchFeaturedGroups(e){const t=this.featuredGroups,r=new O({num:100,sortField:"title"});if(t?.length){const o=[];for(const e of t)o.push(`(title:"${e.title}" AND owner:${e.owner})`);return r.query=o.join(" OR "),this.queryGroups(r,e).then(e=>e.results)}return p(e)?Promise.reject(h()):Promise.resolve([])}fetchRegions(e){const t=this.user?.culture||this.culture||S();return this.request(this.restUrl+"/portals/regions",{...e,query:{culture:t}})}fetchSettings(e){const t=this.user?.culture||this.culture||S();return this.request(this.restUrl+"/portals/self/settings",{...e,query:{culture:t}})}static getDefault(){return P(()=>new U)}queryGroups(e,t){return this.queryPortal("/community/groups",e,"PortalGroup",t)}queryItems(e,t){return this.queryPortal("/search",e,"PortalItem",t)}queryUsers(e,t){return e.sortField||(e.sortField="username"),this.queryPortal("/community/users",e,"PortalUser",t)}fetchSelf(e=this.authMode,t=!1,r){const o=this.restUrl+"/portals/self",s={authMode:e,query:{culture:S().toLowerCase()},withCredentials:!0,...r};return"auto"===s.authMode&&(s.authMode="no-prompt"),t&&(s.query.default=!0),this.request(o,s)}queryPortal(e,t,r,o){const s=y(O,t),a=t=>this.request(this.restUrl+e,{...s.toRequestOptions(this),...o}).then(e=>{const r=s.clone();return r.start=e.nextStart,new B({nextQueryParams:r,queryParams:s,total:e.total,results:U._resultsToTypedArray(t,{portal:this},e,o)})}).then(e=>Promise.all(e.results.map(t=>"function"==typeof t.when?t.when():e)).then(()=>e,t=>(d(t),e)));return r&&Q[r]?Q[r]().then(({default:e})=>(n(o),a(e))):a()}signIn(){if(this.hasAPIKey)return this.load().then(()=>{if(!this.user)throw new s("portal:not-authenticated","Unable to authenticate user. Portal.user is missing")});if(this.authMode===U.AUTH_MODE_ANONYMOUS||this.authMode===U.AUTH_MODE_NO_PROMPT&&!r)return Promise.reject(new s("portal:invalid-auth-mode",`Current "authMode"' is "${this.authMode}"`));if("failed"===this.loadStatus)return Promise.reject(this.loadError);const e=e=>Promise.resolve().then(()=>"not-loaded"===this.loadStatus?(e||(this.authMode="immediate"),this.load().then(()=>null)):"loading"===this.loadStatus?this.load().then(()=>this.credential?null:(this.credential=e,this.fetchSelf("immediate"))):this.user&&this.credential===e?null:(this.credential=e,this.fetchSelf("immediate"))).then(e=>{e&&(this.sourceJSON=e,this.read(e))});return r?r.getCredential(this.restUrl,{prompt:this.authMode!==U.AUTH_MODE_NO_PROMPT}).then(t=>e(t)):e(this.credential)}normalizeUrl(e){const t=this.credential?.token;return this._normalizeSSL(t?e+(e.includes("?")?"&":"?")+"token="+t:e)}requestToTypedArray(e,t,r){return this.request(e,t).then(e=>{const t=U._resultsToTypedArray(r,{portal:this},e);return Promise.all(t.map(t=>"function"==typeof t.when?t.when():e)).then(()=>t,()=>t)})}request(e,t={}){const r={f:"json",...t.query},{authMode:s=(this.authMode===U.AUTH_MODE_ANONYMOUS||this.authMode===U.AUTH_MODE_NO_PROMPT?this.authMode:"auto"),body:a=null,cacheBust:i=!1,method:l="auto",responseType:u="json",signal:n}=t,p={authMode:s,body:a,cacheBust:i,method:l,query:r,responseType:u,timeout:0,signal:n};return t.withCredentials&&(p.withCredentials=!0),o(this._normalizeSSL(e),p).then(e=>e.data)}toJSON(){throw new s("internal:not-yet-implemented","Portal.toJSON is not yet implemented")}static fromJSON(e){if(!e)return null;if(e.declaredClass)throw new Error("JSON object is already hydrated");return new U({sourceJSON:e})}_getHelperService(e){const t=this.helperServices&&this.helperServices[e];if(!t)throw new s("portal:service-not-found",`The \`helperServices\` do not include an entry named "${e}"`);return t}async _fetchBasemaps(e,t){const r=new O;r.query=e||(_()?this.devBasemapGalleryGroupQuery:this.useVectorBasemaps?this.vectorBasemapGalleryGroupQuery:this.basemapGalleryGroupQuery),r.disableExtraQuery=!0;const o=await this.queryGroups(r,t);if(!o.total)return[];const s=o.results[0];r.num=100,r.query='type:"Web Map" -type:"Web Application"',r.sortField=s.sortField||"name",r.sortOrder=s.sortOrder||"desc";const a=await s.queryItems(r,t);if(!a.total)return[];return a.results.filter(e=>"Web Map"===e.type).map(e=>new M({portalItem:e}))}async _fetchBasemaps3D(e,t){const r=e||this.basemapGalleryGroupQuery3D;if(!r)return[];if(_())return[];const o=new O({query:r,disableExtraQuery:!0}),s=await this.queryGroups(o,t);if(!s.total)return[];const a=s.results[0];o.num=100,o.query='type:"Web Scene"',o.sortField=a.sortField||"name",o.sortOrder=a.sortOrder||"desc";const i=await a.queryItems(o,t);if(!i.total)return[];return i.results.filter(e=>"Web Scene"===e.type).map(e=>new M({portalItem:e}))}_normalizeSSL(e){return e.replace(/^http:/i,"https:").replace(":7080",":7443")}_readBasemap(e){if(e){const t=M.fromJSON(e);return t.portalItem={portal:this},t}return null}static _resultsToTypedArray(e,t,r,o){let s;if(r){const a=null!=o?o.signal:null;s=r.listings||r.notifications||r.userInvitations||r.tags||r.items||r.groups||r.comments||r.provisions||r.results||r.relatedItems||r,(e||t)&&(s=s.map(r=>{const o=Object.assign(e?e.fromJSON(r):r,t);return"function"==typeof o.load&&o.load(a),o}))}else s=[];return s}};e([c()],C.prototype,"access",void 0),e([c()],C.prototype,"allSSL",void 0),e([c()],C.prototype,"authMode",void 0),e([c()],C.prototype,"authorizedCrossOriginDomains",void 0),e([m("authorizedCrossOriginDomains")],C.prototype,"readAuthorizedCrossOriginDomains",null),e([c()],C.prototype,"basemapGalleryGroupQuery",void 0),e([c({json:{name:"3DBasemapGalleryGroupQuery"}})],C.prototype,"basemapGalleryGroupQuery3D",void 0),e([c()],C.prototype,"bingKey",void 0),e([c()],C.prototype,"canListApps",void 0),e([c()],C.prototype,"canListData",void 0),e([c()],C.prototype,"canListPreProvisionedItems",void 0),e([c()],C.prototype,"canProvisionDirectPurchase",void 0),e([c()],C.prototype,"canSearchPublic",void 0),e([c()],C.prototype,"canShareBingPublic",void 0),e([c()],C.prototype,"canSharePublic",void 0),e([c()],C.prototype,"canSignInArcGIS",void 0),e([c()],C.prototype,"canSignInIDP",void 0),e([c()],C.prototype,"colorSetsGroupQuery",void 0),e([c()],C.prototype,"commentsEnabled",void 0),e([c({type:Date})],C.prototype,"created",void 0),e([c()],C.prototype,"credential",void 0),e([c()],C.prototype,"culture",void 0),e([c()],C.prototype,"currentVersion",void 0),e([c()],C.prototype,"customBaseUrl",void 0),e([c()],C.prototype,"default3DBasemapQuery",void 0),e([c()],C.prototype,"defaultBasemap",void 0),e([m("defaultBasemap")],C.prototype,"readDefaultBasemap",null),e([c()],C.prototype,"defaultDevBasemap",void 0),e([m("defaultDevBasemap")],C.prototype,"readDefaultDevBasemap",null),e([c({type:v})],C.prototype,"defaultExtent",void 0),e([c()],C.prototype,"defaultVectorBasemap",void 0),e([m("defaultVectorBasemap")],C.prototype,"readDefaultVectorBasemap",null),e([c()],C.prototype,"description",void 0),e([c()],C.prototype,"devBasemapGalleryGroupQuery",void 0),e([c()],C.prototype,"eueiEnabled",void 0),e([c({readOnly:!0})],C.prototype,"extraQuery",null),e([c()],C.prototype,"featuredGroups",void 0),e([c()],C.prototype,"featuredItemsGroupQuery",void 0),e([c()],C.prototype,"galleryTemplatesGroupQuery",void 0),e([c()],C.prototype,"layoutGroupQuery",void 0),e([c()],C.prototype,"livingAtlasGroupQuery",void 0),e([c({readOnly:!0})],C.prototype,"hasAPIKey",null),e([c()],C.prototype,"hasCategorySchema",void 0),e([c()],C.prototype,"hasClassificationSchema",void 0),e([c()],C.prototype,"helpBase",void 0),e([c()],C.prototype,"helperServices",void 0),e([c()],C.prototype,"helpMap",void 0),e([c()],C.prototype,"homePageFeaturedContent",void 0),e([c()],C.prototype,"homePageFeaturedContentCount",void 0),e([c()],C.prototype,"httpPort",void 0),e([c()],C.prototype,"httpsPort",void 0),e([c()],C.prototype,"id",void 0),e([c()],C.prototype,"ipCntryCode",void 0),e([c({readOnly:!0})],C.prototype,"isOrganization",null),e([c()],C.prototype,"isPortal",void 0),e([c()],C.prototype,"isReadOnly",void 0),e([c({readOnly:!0})],C.prototype,"itemPageUrl",null),e([c()],C.prototype,"layerTemplatesGroupQuery",void 0),e([c()],C.prototype,"maxTokenExpirationMinutes",void 0),e([c({type:Date})],C.prototype,"modified",void 0),e([c()],C.prototype,"name",void 0),e([c()],C.prototype,"portalHostname",void 0),e([c()],C.prototype,"portalMode",void 0),e([c()],C.prototype,"portalProperties",void 0),e([c()],C.prototype,"region",void 0),e([c()],C.prototype,"recycleBinEnabled",void 0),e([c({readOnly:!0})],C.prototype,"restUrl",null),e([c()],C.prototype,"rotatorPanels",void 0),e([c()],C.prototype,"showHomePageDescription",void 0),e([c()],C.prototype,"sourceJSON",void 0),e([c()],C.prototype,"staticImagesUrl",void 0),e([c({json:{name:"2DStylesGroupQuery"}})],C.prototype,"stylesGroupQuery2d",void 0),e([c({json:{name:"stylesGroupQuery"}})],C.prototype,"stylesGroupQuery3d",void 0),e([c()],C.prototype,"supportsHostedServices",void 0),e([c()],C.prototype,"symbolSetsGroupQuery",void 0),e([c()],C.prototype,"templatesGroupQuery",void 0),e([c()],C.prototype,"thumbnail",void 0),e([c({readOnly:!0})],C.prototype,"thumbnailUrl",null),e([c()],C.prototype,"units",void 0),e([c()],C.prototype,"url",void 0),e([c()],C.prototype,"urlKey",void 0),e([m("urlKey")],C.prototype,"readUrlKey",null),e([c()],C.prototype,"user",void 0),e([m("user")],C.prototype,"readUser",null),e([c()],C.prototype,"use3dBasemaps",void 0),e([c()],C.prototype,"useDefault3dBasemap",void 0),e([c()],C.prototype,"useStandardizedQuery",void 0),e([c()],C.prototype,"useVectorBasemaps",void 0),e([c()],C.prototype,"vectorBasemapGalleryGroupQuery",void 0),C=U=e([f("esri.portal.Portal")],C);const b=new FinalizationRegistry(e=>{e.remove()});function w(e){const t=r;return()=>{const r=e.deref();r&&t.findCredential(r.restUrl)&&r.signIn().catch(()=>{})}}export{C as default};
|
|
5
|
+
import{__decorate as e}from"tslib";import t from"../config.js";import{id as r}from"../kernel.js";import o from"../request.js";import s from"../core/Error.js";import{JSONSupportMixin as a}from"../core/JSONSupport.js";import{Loadable as i}from"../core/Loadable.js";import{destroyMaybe as l,removeMaybe as u}from"../core/maybe.js";import{throwIfAborted as n,isAborted as p,createAbortError as h,throwIfAbortError as d}from"../core/promiseUtils.js";import{property as c}from"../core/accessorSupport/decorators/property.js";import{ensureType as y}from"../core/accessorSupport/ensureType.js";import"../core/has.js";import"../core/RandomLCG.js";import{reader as m}from"../core/accessorSupport/decorators/reader.js";import{subclass as f}from"../core/accessorSupport/decorators/subclass.js";import v from"../geometry/Extent.js";import{getLocale as S}from"../intl/locale.js";import{ensureDefaultPortalInstance as P}from"./portalDefault.js";import g from"./PortalGroup.js";import O from"./PortalQueryParams.js";import B from"./PortalQueryResult.js";import D from"./PortalUser.js";import{isApiKeyApplicable as G,hasBasemapStylesApiKey as _}from"../support/apiKeyUtils.js";var U;let M;const Q={PortalGroup:()=>Promise.resolve({default:g}),PortalItem:()=>import("./PortalItem.js"),PortalUser:()=>Promise.resolve({default:D})};let C=class extends(a(i)){static{U=this}static{this.AUTH_MODE_ANONYMOUS="anonymous"}static{this.AUTH_MODE_AUTO="auto"}static{this.AUTH_MODE_IMMEDIATE="immediate"}static{this.AUTH_MODE_NO_PROMPT="no-prompt"}constructor(e){super(e),this._esriIdCredentialCreateHandle=null,this.access=null,this.allSSL=!1,this.authMode="auto",this.authorizedCrossOriginDomains=null,this.basemapGalleryGroupQuery=null,this.basemapGalleryGroupQuery3D=null,this.bingKey=null,this.canListApps=!1,this.canListData=!1,this.canListPreProvisionedItems=!1,this.canProvisionDirectPurchase=!1,this.canSearchPublic=!0,this.canShareBingPublic=!1,this.canSharePublic=!1,this.canSignInArcGIS=!1,this.canSignInIDP=!1,this.colorSetsGroupQuery=null,this.commentsEnabled=!1,this.created=null,this.culture=null,this.customBaseUrl=null,this.default3DBasemapQuery=null,this.defaultBasemap=null,this.defaultDevBasemap=null,this.defaultExtent=null,this.defaultVectorBasemap=null,this.description=null,this.devBasemapGalleryGroupQuery=null,this.eueiEnabled=null,this.featuredGroups=null,this.featuredItemsGroupQuery=null,this.galleryTemplatesGroupQuery=null,this.layoutGroupQuery=null,this.livingAtlasGroupQuery=null,this.hasCategorySchema=!1,this.hasClassificationSchema=!1,this.helperServices=null,this.homePageFeaturedContent=null,this.homePageFeaturedContentCount=null,this.httpPort=null,this.httpsPort=null,this.id=null,this.ipCntryCode=null,this.isPortal=!1,this.isReadOnly=!1,this.layerTemplatesGroupQuery=null,this.maxTokenExpirationMinutes=null,this.modified=null,this.name=null,this.portalHostname=null,this.portalMode=null,this.portalProperties=null,this.region=null,this.recycleBinEnabled=!1,this.rotatorPanels=null,this.showHomePageDescription=!1,this.sourceJSON=null,this.supportsHostedServices=!1,this.symbolSetsGroupQuery=null,this.templatesGroupQuery=null,this.units=null,this.url=t.portalUrl,this.urlKey=null,this.user=null,this.use3dBasemaps=!0,this.useDefault3dBasemap=!1,this.useStandardizedQuery=!1,this.useVectorBasemaps=!1,this.vectorBasemapGalleryGroupQuery=null}normalizeCtorArgs(e){return"string"==typeof e?{url:e}:e}destroy(){b.unregister(this),this.defaultBasemap=l(this.defaultBasemap),this.defaultDevBasemap=l(this.defaultDevBasemap),this.defaultVectorBasemap=l(this.defaultVectorBasemap),this._esriIdCredentialCreateHandle=u(this._esriIdCredentialCreateHandle)}readAuthorizedCrossOriginDomains(e){if(e)for(const r of e)t.request.trustedServers.includes(r)||t.request.trustedServers.push(r);return e}readDefaultBasemap(e){return this._readBasemap(e)}readDefaultDevBasemap(e){return this._readBasemap(e)}readDefaultVectorBasemap(e){return this._readBasemap(e)}get extraQuery(){const e=this.user?.orgId,t=!e||this.canSearchPublic;return this.id&&!t?` AND orgid:${this.id}`:null}get hasAPIKey(){return G(this.restUrl)}get isOrganization(){return!!this.access}get itemPageUrl(){return this.url?`${this.url}/home/item.html`:null}get loaded(){return super.loaded}get restUrl(){let e=this.url;if(e){const t=e.indexOf("/sharing");e=t>0?e.slice(0,t):this.url.replace(/\/+$/,""),e+="/sharing/rest"}return e}get thumbnailUrl(){const e=this.restUrl,t=this.thumbnail;return e&&t?this._normalizeSSL(e+"/portals/self/resources/"+t):null}readUrlKey(e){return e?e.toLowerCase():e}readUser(e){let t=null;return e&&(t=D.fromJSON(e),t.portal=this),t}load(e){const t=import("../Basemap.js").then(({default:t})=>{n(e),M=t}).then(()=>this.sourceJSON?this.sourceJSON:this.fetchSelf(this.authMode,!1,e)).then(e=>{if(!this.hasAPIKey&&r){const e=r;this.credential=e.findCredential(this.restUrl),this.credential||this.authMode!==U.AUTH_MODE_AUTO&&this.authMode!==U.AUTH_MODE_NO_PROMPT||(this._esriIdCredentialCreateHandle?.remove(),this._esriIdCredentialCreateHandle=e.on("credential-create",w(new WeakRef(this))),b.register(this,this._esriIdCredentialCreateHandle,this))}this.sourceJSON=e,this.read(e)});return this.addResolvingPromise(t),Promise.resolve(this)}async createElevationLayers(){await this.load();const e=this._getHelperService("defaultElevationLayers"),t=(await import("../layers/ElevationLayer.js")).default;return e?e.map(e=>new t({id:e.id,url:e.url})):[]}async fetchBasemaps(e,t){const r=await this._fetchBasemaps(e,t);if(!0===t?.include3d&&!1!==this.use3dBasemaps){const o=await this._fetchBasemaps3D(e,t);r.unshift(...o)}return r}async fetchDefault3DBasemap(e){if(!this.useDefault3dBasemap||!this.default3DBasemapQuery||"none"===this.default3DBasemapQuery)return null;const t=new O;t.query=this.default3DBasemapQuery,t.disableExtraQuery=!0;const r=(await this.queryItems(t,e)).results.find(e=>"Web Scene"===e.type);return r?new M({portalItem:r}):null}fetchCategorySchema(e){return this.hasCategorySchema?this.request(this.restUrl+"/portals/self/categorySchema",e).then(e=>e.categorySchema):p(e)?Promise.reject(h()):Promise.resolve([])}async fetchClassificationSchema(e){return this.hasClassificationSchema?this.request(this.restUrl+"/portals/self/classification/classificationSchema",e).then(e=>e.classificationSchema):null}fetchFeaturedGroups(e){const t=this.featuredGroups,r=new O({num:100,sortField:"title"});if(t?.length){const o=[];for(const e of t)o.push(`(title:"${e.title}" AND owner:${e.owner})`);return r.query=o.join(" OR "),this.queryGroups(r,e).then(e=>e.results)}return p(e)?Promise.reject(h()):Promise.resolve([])}fetchRegions(e){const t=this.user?.culture||this.culture||S();return this.request(this.restUrl+"/portals/regions",{...e,query:{culture:t}})}fetchSettings(e){const t=this.user?.culture||this.culture||S();return this.request(this.restUrl+"/portals/self/settings",{...e,query:{culture:t}})}static getDefault(){return P(()=>new U)}queryGroups(e,t){return this.queryPortal("/community/groups",e,"PortalGroup",t)}queryItems(e,t){return this.queryPortal("/search",e,"PortalItem",t)}queryUsers(e,t){return e.sortField||(e.sortField="username"),this.queryPortal("/community/users",e,"PortalUser",t)}fetchSelf(e=this.authMode,t=!1,r){const o=this.restUrl+"/portals/self",s={authMode:e,query:{culture:S().toLowerCase()},withCredentials:!0,...r};return"auto"===s.authMode&&(s.authMode="no-prompt"),t&&(s.query.default=!0),this.request(o,s)}queryPortal(e,t,r,o){const s=y(O,t),a=t=>this.request(this.restUrl+e,{...s.toRequestOptions(this),...o}).then(e=>{const r=s.clone();return r.start=e.nextStart,new B({nextQueryParams:r,queryParams:s,total:e.total,results:U._resultsToTypedArray(t,{portal:this},e,o)})}).then(e=>Promise.all(e.results.map(t=>"function"==typeof t.when?t.when():e)).then(()=>e,t=>(d(t),e)));return r&&Q[r]?Q[r]().then(({default:e})=>(n(o),a(e))):a()}signIn(){if(this.hasAPIKey)return this.load().then(()=>{if(!this.user)throw new s("portal:not-authenticated","Unable to authenticate user. Portal.user is missing")});if(this.authMode===U.AUTH_MODE_ANONYMOUS||this.authMode===U.AUTH_MODE_NO_PROMPT&&!r)return Promise.reject(new s("portal:invalid-auth-mode",`Current "authMode"' is "${this.authMode}"`));if("failed"===this.loadStatus)return Promise.reject(this.loadError);const e=e=>Promise.resolve().then(()=>"not-loaded"===this.loadStatus?(e||(this.authMode="immediate"),this.load().then(()=>null)):"loading"===this.loadStatus?this.load().then(()=>this.credential?null:(this.credential=e,this.fetchSelf("immediate"))):this.user&&this.credential===e?null:(this.credential=e,this.fetchSelf("immediate"))).then(e=>{e&&(this.sourceJSON=e,this.read(e))});return r?r.getCredential(this.restUrl,{prompt:this.authMode!==U.AUTH_MODE_NO_PROMPT}).then(t=>e(t)):e(this.credential)}normalizeUrl(e){const t=this.credential?.token;return this._normalizeSSL(t?e+(e.includes("?")?"&":"?")+"token="+t:e)}requestToTypedArray(e,t,r){return this.request(e,t).then(e=>{const t=U._resultsToTypedArray(r,{portal:this},e);return Promise.all(t.map(t=>"function"==typeof t.when?t.when():e)).then(()=>t,()=>t)})}request(e,t={}){const r={f:"json",...t.query},{authMode:s=(this.authMode===U.AUTH_MODE_ANONYMOUS||this.authMode===U.AUTH_MODE_NO_PROMPT?this.authMode:"auto"),body:a=null,cacheBust:i=!1,method:l="auto",responseType:u="json",signal:n}=t,p={authMode:s,body:a,cacheBust:i,method:l,query:r,responseType:u,timeout:0,signal:n};return t.withCredentials&&(p.withCredentials=!0),o(this._normalizeSSL(e),p).then(e=>e.data)}toJSON(){throw new s("internal:not-yet-implemented","Portal.toJSON is not yet implemented")}static fromJSON(e){if(!e)return null;if(e.declaredClass)throw new Error("JSON object is already hydrated");return new U({sourceJSON:e})}_getHelperService(e){const t=this.helperServices?.[e];if(!t)throw new s("portal:service-not-found",`The \`helperServices\` do not include an entry named "${e}"`);return t}async _fetchBasemaps(e,t){const r=new O;r.query=e||(_()?this.devBasemapGalleryGroupQuery:this.useVectorBasemaps?this.vectorBasemapGalleryGroupQuery:this.basemapGalleryGroupQuery),r.disableExtraQuery=!0;const o=await this.queryGroups(r,t);if(!o.total)return[];const s=o.results[0];r.num=100,r.query='type:"Web Map" -type:"Web Application"',r.sortField=s.sortField||"name",r.sortOrder=s.sortOrder||"desc";const a=await s.queryItems(r,t);if(!a.total)return[];return a.results.filter(e=>"Web Map"===e.type).map(e=>new M({portalItem:e}))}async _fetchBasemaps3D(e,t){const r=e||this.basemapGalleryGroupQuery3D;if(!r)return[];if(_())return[];const o=new O({query:r,disableExtraQuery:!0}),s=await this.queryGroups(o,t);if(!s.total)return[];const a=s.results[0];o.num=100,o.query='type:"Web Scene"',o.sortField=a.sortField||"name",o.sortOrder=a.sortOrder||"desc";const i=await a.queryItems(o,t);if(!i.total)return[];return i.results.filter(e=>"Web Scene"===e.type).map(e=>new M({portalItem:e}))}_normalizeSSL(e){return e.replace(/^http:/i,"https:").replace(":7080",":7443")}_readBasemap(e){if(e){const t=M.fromJSON(e);return t.portalItem={portal:this},t}return null}static _resultsToTypedArray(e,t,r,o){let s;if(r){const a=null!=o?o.signal:null;s=r.listings||r.notifications||r.userInvitations||r.tags||r.items||r.groups||r.comments||r.provisions||r.results||r.relatedItems||r,(e||t)&&(s=s.map(r=>{const o=Object.assign(e?e.fromJSON(r):r,t);return"function"==typeof o.load&&o.load(a),o}))}else s=[];return s}};e([c()],C.prototype,"access",void 0),e([c()],C.prototype,"allSSL",void 0),e([c()],C.prototype,"authMode",void 0),e([c()],C.prototype,"authorizedCrossOriginDomains",void 0),e([m("authorizedCrossOriginDomains")],C.prototype,"readAuthorizedCrossOriginDomains",null),e([c()],C.prototype,"basemapGalleryGroupQuery",void 0),e([c({json:{name:"3DBasemapGalleryGroupQuery"}})],C.prototype,"basemapGalleryGroupQuery3D",void 0),e([c()],C.prototype,"bingKey",void 0),e([c()],C.prototype,"canListApps",void 0),e([c()],C.prototype,"canListData",void 0),e([c()],C.prototype,"canListPreProvisionedItems",void 0),e([c()],C.prototype,"canProvisionDirectPurchase",void 0),e([c()],C.prototype,"canSearchPublic",void 0),e([c()],C.prototype,"canShareBingPublic",void 0),e([c()],C.prototype,"canSharePublic",void 0),e([c()],C.prototype,"canSignInArcGIS",void 0),e([c()],C.prototype,"canSignInIDP",void 0),e([c()],C.prototype,"colorSetsGroupQuery",void 0),e([c()],C.prototype,"commentsEnabled",void 0),e([c({type:Date})],C.prototype,"created",void 0),e([c()],C.prototype,"credential",void 0),e([c()],C.prototype,"culture",void 0),e([c()],C.prototype,"currentVersion",void 0),e([c()],C.prototype,"customBaseUrl",void 0),e([c()],C.prototype,"default3DBasemapQuery",void 0),e([c()],C.prototype,"defaultBasemap",void 0),e([m("defaultBasemap")],C.prototype,"readDefaultBasemap",null),e([c()],C.prototype,"defaultDevBasemap",void 0),e([m("defaultDevBasemap")],C.prototype,"readDefaultDevBasemap",null),e([c({type:v})],C.prototype,"defaultExtent",void 0),e([c()],C.prototype,"defaultVectorBasemap",void 0),e([m("defaultVectorBasemap")],C.prototype,"readDefaultVectorBasemap",null),e([c()],C.prototype,"description",void 0),e([c()],C.prototype,"devBasemapGalleryGroupQuery",void 0),e([c()],C.prototype,"eueiEnabled",void 0),e([c({readOnly:!0})],C.prototype,"extraQuery",null),e([c()],C.prototype,"featuredGroups",void 0),e([c()],C.prototype,"featuredItemsGroupQuery",void 0),e([c()],C.prototype,"galleryTemplatesGroupQuery",void 0),e([c()],C.prototype,"layoutGroupQuery",void 0),e([c()],C.prototype,"livingAtlasGroupQuery",void 0),e([c({readOnly:!0})],C.prototype,"hasAPIKey",null),e([c()],C.prototype,"hasCategorySchema",void 0),e([c()],C.prototype,"hasClassificationSchema",void 0),e([c()],C.prototype,"helpBase",void 0),e([c()],C.prototype,"helperServices",void 0),e([c()],C.prototype,"helpMap",void 0),e([c()],C.prototype,"homePageFeaturedContent",void 0),e([c()],C.prototype,"homePageFeaturedContentCount",void 0),e([c()],C.prototype,"httpPort",void 0),e([c()],C.prototype,"httpsPort",void 0),e([c()],C.prototype,"id",void 0),e([c()],C.prototype,"ipCntryCode",void 0),e([c({readOnly:!0})],C.prototype,"isOrganization",null),e([c()],C.prototype,"isPortal",void 0),e([c()],C.prototype,"isReadOnly",void 0),e([c({readOnly:!0})],C.prototype,"itemPageUrl",null),e([c()],C.prototype,"layerTemplatesGroupQuery",void 0),e([c()],C.prototype,"maxTokenExpirationMinutes",void 0),e([c({type:Date})],C.prototype,"modified",void 0),e([c()],C.prototype,"name",void 0),e([c()],C.prototype,"portalHostname",void 0),e([c()],C.prototype,"portalMode",void 0),e([c()],C.prototype,"portalProperties",void 0),e([c()],C.prototype,"region",void 0),e([c()],C.prototype,"recycleBinEnabled",void 0),e([c({readOnly:!0})],C.prototype,"restUrl",null),e([c()],C.prototype,"rotatorPanels",void 0),e([c()],C.prototype,"showHomePageDescription",void 0),e([c()],C.prototype,"sourceJSON",void 0),e([c()],C.prototype,"staticImagesUrl",void 0),e([c({json:{name:"2DStylesGroupQuery"}})],C.prototype,"stylesGroupQuery2d",void 0),e([c({json:{name:"stylesGroupQuery"}})],C.prototype,"stylesGroupQuery3d",void 0),e([c()],C.prototype,"supportsHostedServices",void 0),e([c()],C.prototype,"symbolSetsGroupQuery",void 0),e([c()],C.prototype,"templatesGroupQuery",void 0),e([c()],C.prototype,"thumbnail",void 0),e([c({readOnly:!0})],C.prototype,"thumbnailUrl",null),e([c()],C.prototype,"units",void 0),e([c()],C.prototype,"url",void 0),e([c()],C.prototype,"urlKey",void 0),e([m("urlKey")],C.prototype,"readUrlKey",null),e([c()],C.prototype,"user",void 0),e([m("user")],C.prototype,"readUser",null),e([c()],C.prototype,"use3dBasemaps",void 0),e([c()],C.prototype,"useDefault3dBasemap",void 0),e([c()],C.prototype,"useStandardizedQuery",void 0),e([c()],C.prototype,"useVectorBasemaps",void 0),e([c()],C.prototype,"vectorBasemapGalleryGroupQuery",void 0),C=U=e([f("esri.portal.Portal")],C);const b=new FinalizationRegistry(e=>{e.remove()});function w(e){const t=r;return()=>{const r=e.deref();r&&t.findCredential(r.restUrl)&&r.signIn().catch(()=>{})}}export{C as default};
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.34/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import e from"../../Color.js";import{getMetersPerUnitForSR as t}from"../../core/unitUtils.js";import n from"../../layers/support/Field.js";import{isFunctionRaster as a}from"../../layers/support/rasterDatasets/datasetUtils.js";import r from"../ClassBreaksRenderer.js";import l from"../FlowRenderer.js";import s from"../RasterColormapRenderer.js";import o from"../RasterShadedReliefRenderer.js";import i from"../RasterStretchRenderer.js";import u from"../UniqueValueRenderer.js";import m from"../VectorFieldRenderer.js";import c from"./AuthoringInfo.js";import f from"./ClassBreakInfo.js";import{convertColorRampToColormap as p,predefinedJsonColorRamps as d}from"./colorRampUtils.js";import{isVectorFieldRendererSupported as b,isColormapRendererSupported as h,isUVRendererSupported as g,isClassBreaksSupported as v,isShadedReliefRendererSupported as y,isFlowRendererSupported as w}from"./rasterRendererChecks.js";import C from"./UniqueValueInfo.js";import x from"../visualVariables/ColorVariable.js";import M from"../visualVariables/SizeVariable.js";import R from"../visualVariables/support/ColorStop.js";import j from"../../rest/support/ClassBreaksDefinition.js";import{createGenerateRendererClassBreaks as V}from"../../rest/support/generateRendererUtils.js";import T from"../../rest/support/MultipartColorRamp.js";import S from"../../symbols/SimpleFillSymbol.js";const I=.25,k=T.fromJSON({type:"multipart",colorRamps:[{fromColor:[0,0,255],toColor:[0,255,255]},{fromColor:[0,255,255],toColor:[255,255,0]},{fromColor:[255,255,0],toColor:[255,0,0]}]}),F=T.fromJSON(d[0]),L=new Set(["scientific","standard-time","vector-uv","vector-magdir","vector-u","vector-v","vector-magnitude","vector-direction"]);function q(e){return e.presetRenderers?.find(({method:t,value:n})=>"raster-function-template"===t?n===e.rasterFunctionName:"variable"===t&&n===e.variableName)}function B(e,t){const{attributeTable:n,colormap:a}=e;if(b(e)){const t=$(e);if(null!=t)return t}if(t?.rasterFunctionColorRamp){const n=U(e,t);return n.colorRamp=t.rasterFunctionColorRamp,n}if(null!=a){const t=K(e);if(null!=t)return t}if(null!=n){const t=P(e);if(null!=t)return t}return U(e,t)}function E(e,t=!1){const n=["raster-stretch"];return h(e,t)&&n.push("raster-colormap"),g(e)&&n.push("unique-value"),v(e,t)&&n.push("class-breaks"),y(e)&&n.push("raster-shaded-relief"),b(e)&&n.push("vector-field"),w(e)&&n.push("flow"),n}function z(e){return a(e)&&"Colormap"===e.rasterFunction.functionName?e.rasterFunction.colorRamp:void 0}function N(e,t,n){const a=["nearest","bilinear","cubic","majority"],r=n?.toLowerCase().replace("bicubic","cubic"),l=a.find(e=>e===r);if("Map"===t)return l??"bilinear";if("standard-time"===e.dataType)return l??"nearest";return"thematic"===e.dataType||e.attributeTable||e.colormap?"nearest"===l||"majority"===l?l:"nearest":l??"bilinear"}function U(e,t){e=W(e,t?.variableName);const{bandCount:n}=e;let{bandIds:a,stretchType:r}=t||{};a?.some(e=>e>=n)&&(a=null);let l=e.statistics,s=e.histograms;n>1?(a=a?.length?a:D(e),l=null==l?null:a?.map(e=>l[e]),s=null==s?null:a?.map(e=>s[e])):a=[0],null==r&&(r=J(e)),t?.includeStatisticsInStretch&&("percent-clip"===r||"histogram-equalization"===r)&&e.statistics?.length&&(r="min-max");let o=!1;switch(r){case"none":o=!1;break;case"percent-clip":o=!s?.length;break;default:o=!l?.length}const{dataType:u}=e,m=1===a?.length&&L.has(u)?k:null,c=new i({stretchType:r,dynamicRangeAdjustment:o,colorRamp:m,outputMin:0,outputMax:255,gamma:1===a?.length?[1]:[1,1,1],useGamma:!1});return"percent-clip"===r?c.maxPercent=c.minPercent=I:"standard-deviation"===r&&(c.numberOfStandardDeviations=2),o||null==e.multidimensionalInfo&&!t?.includeStatisticsInStretch||("percent-clip"===r?c.histograms=s:"min-max"!==r&&"standard-deviation"!==r||(c.customStatistics=l?.map(e=>({...e})))),c}function W(e,t){const{multidimensionalInfo:n}=e;if(!t||!n)return e;const a=n.variables.find(e=>e.name===t);if(!a)return e;if(e=e.clone(),a){const{statistics:t,histograms:n}=a;t?.length&&(e.statistics=t.map(e=>({min:e.min,max:e.max,avg:e.avg,stddev:e.stddev}))),n?.length&&(e.histograms=n)}return e}function D(e){const t=e.bandCount;if(1===t)return null;if(2===t)return[0];const{bandInfos:n}=e;let a;if(n.length===t){const{red:e,green:t,blue:r,nir:l}=A(n);null!=e&&null!=t&&null!=r?a=[e,t,r]:null!=l&&null!=e&&null!=t&&(a=[l,e,t])}return!a&&t>=3&&(a=[0,1,2]),a}function O(e,t){const n=e.bandInfos.map(({name:e})=>e);return t?.length?t.map(e=>n[e]):n}function A(e){const t={};for(let n=0;n<e.length;n++){const a=e[n],r=a.name.toLowerCase();if("red"===r)t.red=n;else if("green"===r)t.green=n;else if("blue"===r)t.blue=n;else if("nearinfrared"===r||"nearinfrared_1"===r||"nir"===r)t.nir=n;else if(a.maxWavelength&&a.minWavelength){const e=a.minWavelength,r=a.maxWavelength;null==t.blue&&e>=410&&e<=480&&r>=480&&r<=540?t.blue=n:null==t.green&&e>=490&&e<=560&&r>=560&&r<=610?t.green=n:null==t.red&&e>=595&&e<=670&&r>=660&&r<=730?t.red=n:null==t.nir&&e>=700&&e<=860&&r>=800&&r<=950&&(t.nir=n)}}return t}function J(e){let t="percent-clip";const{pixelType:n,dataType:a,histograms:r,statistics:l,multidimensionalInfo:s}=e,o=L.has(a)||"generic"===a&&null!=s;return"u8"!==n||"processed"!==a&&null!=r&&null!=l?"u8"===n||"elevation"===a||o?t="min-max":null!=r?t="percent-clip":null!=l&&(t="min-max"):t="none",t}function P(t,n,a,r){if(!g(t,n))return null;const{attributeTable:l,statistics:s}=t,o=G(l,n),i=H(l,"red"),m=H(l,"green"),f=H(l,"blue"),d=new c,b=[],h=new Set,v=!!(i&&m&&f);if(null!=l)l.features.forEach(t=>{const n=t.attributes[o.name];if(!h.has(t.attributes[o.name])&&null!=n){h.add(n);const a=v&&("single"===i.type||"double"===i.type)&&("single"===m.type||"double"===m.type)&&("single"===f.type||"double"===f.type)&&!l.features.some(e=>e.attributes[i.name]>1||e.attributes[m.name]>1||e.attributes[f.name]>1),r=a?255:1;b.push(new C({value:t.attributes[o.name],label:t.attributes[o.name]+"",symbol:new S({style:"solid",outline:null,color:new e(v?[t.attributes[i.name]*r,t.attributes[m.name]*r,t.attributes[f.name]*r,1]:[0,0,0,0])})}))}});else if(s?.[0])for(let u=s[0].min;u<=s[0].max;u++)b.push(new C({value:u,label:u.toString(),symbol:new S({style:"solid",outline:null,color:new e([0,0,0,0])})}));if(b.sort((e,t)=>e.value&&"string"==typeof e.value.valueOf()?0:e.value>t.value?1:-1),!v){const t=p(F,{numColors:b.length});b.forEach((n,a)=>n.symbol.color=new e(t[a].slice(1,4))),d.colorRamp=F}if(a||r){const t=a||p(r,{numColors:b.length}).map(e=>e.slice(1));b.forEach((n,a)=>n.symbol.color=new e(t[a])),d.colorRamp=r}return new u({field:o.name,uniqueValueInfos:b,authoringInfo:d})}function G(e,t,a){let r;return null!=e?(r=t?e.fields.find(e=>t.toLowerCase()===e.name.toLowerCase()):_(e.fields),r||(a||(r=e.fields.find(e=>"string"===e.type)),r||(r=H(e,"value")))):r=new n({name:"value"}),r}function _(e){let t;for(let n=0;n<e.length;n++){const a=e[n].name.toLowerCase();if("string"===e[n].type){if(a.startsWith("class")){t=e[n];break}null==t&&(a.endsWith("name")||a.endsWith("type"))&&(t=e[n])}}return t}function H(e,t){return null==e?null:e.fields.find(e=>e.name.toLowerCase()===t)}function K(e){if(!h(e))return null;let t;const{attributeTable:n,colormap:a}=e;if(null!=n){const e=H(n,"value"),a=G(n,null,!0);"string"===a.type&&(t={},n.features.forEach(n=>{const r=n.attributes;t[r[e.name]]=a?r[a.name]:r[e.name]}))}return s.createFromColormap(a,t)}function Q(e,n="traditional"){if(!y(e))return null;const{extent:a}=e,r=a.width*t(a.spatialReference);return new o({hillshadeType:n,scalingType:r>5e6?"adjusted":"none"})}function X(e,t){e=W(e,t?.variableName);const{attributeTable:n}=e;if(!v(e))return null;const a=null!=e.histograms?e.histograms[0]:null,l=null!=t?.numClasses&&isFinite(t?.numClasses)?t.numClasses:5,s=new c({classificationMethod:t?.classificationMethod,colorRamp:t?.colorRamp});let o=t?.field||"value";const i=[],u=[],m=1e3,d=null!=n,b=d&&n.fields.find(e=>"count"===e.name.toLowerCase()),h=d?n.fields.find(e=>e.name.toLowerCase()===o.toLowerCase()):void 0;if(h&&d){o=h.name;const e=n.features.length;let t=0;n.features.forEach(n=>t+=(b?n.attributes[b.name]:50)/e),n.features.forEach(n=>{const a=n.attributes[h.name],r=b?n.attributes[b.name]:50;if(r>0){u.push(r);const n=Math.max(1,Math.round(r/e/t*m));for(let e=0;e<n;e++)i.push(a)}})}else{const{pixelType:t}=e,r=(a.max-a.min)/a.size,l=t.includes("s")||t.includes("u"),s=l&&1===r?Math.floor(a.min+.5):a.min,o=l&&1===r?Math.floor(a.max-.5):a.max,c=a.size;let f,p=0;a.counts.forEach(e=>p+=e/c),a.counts.forEach((e,t)=>{if(e>0){u.push(e);const l=Math.max(1,Math.round(e/c/p*m));f=d?n.features[t].attributes[h.name]:0===t?s:t===c-1?o:a.min+r*(t+.5);for(let e=0;e<l;e++)i.push(f)}})}const g=t?.classificationMethod||"natural-breaks";let y=t?.definedInterval;"defined-interval"!==g||y||(y=Y(e,h,l));const w=V({values:i,valueFrequency:u,normalizationTotal:null,definition:new j({classificationMethod:g,breakCount:l,definedInterval:y})});let C=t?.colors;if(!C){const e=t?.colorRamp||k;s.colorRamp=e;const n=p(e,{numColors:w.classBreaks.length,interpolateAlpha:!0});C=n.map(e=>e.slice(1))}const x=w.classBreaks.map((e,t)=>new f({minValue:e.minValue,maxValue:e.maxValue,label:e.label,symbol:new S({color:C[t]})}));return new r({field:o,classBreakInfos:x,authoringInfo:s})}function Y(e,t,n){let a=0,r=0;if(null!=e.attributeTable){const n=e.attributeTable;a=r=n.features[0].attributes[t.name],n.features.forEach(e=>{const n=e.attributes[t.name];n<a&&(a=n),n>r&&(r=n)})}else if(null!=e.histograms){const t=e.histograms;a=t[0].min,r=t[0].max}return(r-a)/n}const Z=new Map([["m/s","meter-per-second"],["km/h","kilometer-per-hour"],["knots","knots"],["ft/s","feet-per-second"],["mph","mile-per-hour"]]);function $(e){if(!b(e))return null;let t;if(null!=e.statistics&&e.statistics.length&&("vector-magdir"===e.dataType||"vector-uv"===e.dataType)){const{minMagnitude:n,maxMagnitude:a}=ae(e.dataType,e.statistics);t=[new M({field:"Magnitude",minSize:10,maxSize:40,minDataValue:n,maxDataValue:a})]}const n=null!=e.multidimensionalInfo?Z.get(e.multidimensionalInfo.variables[0].unit):void 0,a=new m({visualVariables:t,inputUnit:n,rotationType:"geographic"});return a.visualVariables=[...a.sizeVariables,...a.rotationVariables],a}function ee(e){return{color:e.symbolLayers[0].material?.color,type:"esriSFS",style:"esriSFSSolid"}}function te(e){if("uniqueValue"===e.type){const t=e.uniqueValueInfos,n=t?.[0].symbol;return n?.symbolLayers?.length&&(e.uniqueValueInfos=t?.map(e=>({value:e.value,label:e.label,symbol:e.symbol?ee(e.symbol):null}))),e}if("classBreaks"===e.type){const t=e.classBreakInfos,n=t[0].symbol;return n?.symbolLayers?.length&&(e.classBreakInfos=t.map(e=>({classMinValue:e.classMinValue,classMaxValue:e.classMaxValue,label:e.label,symbol:e.symbol?ee(e.symbol):null}))),e}return e}function ne(t){if(!w(t))return null;let n;if(null!=t.statistics&&t.statistics.length>0&&("vector-magdir"===t.dataType||"vector-uv"===t.dataType)){const{minMagnitude:a,maxMagnitude:r}=ae(t.dataType,t.statistics);n=[new x({field:"Magnitude",stops:[new R({value:a,color:new e("#1020c0")}),new R({value:r,color:new e("#c02010")})]})]}return new l({visualVariables:n})}function ae(e,t){let n,a;if("vector-magdir"===e)n=t[0].min,a=t[0].max;else{const e=t[0].min,r=t[0].max,l=t[1].min,s=t[1].max;n=0,a=Math.max(Math.abs(e),Math.abs(l),Math.abs(r),Math.abs(s))}return{minMagnitude:n,maxMagnitude:a}}export{X as createClassBreaksRenderer,K as createColormapRenderer,B as createDefaultRenderer,ne as createFlowRenderer,Q as createShadedReliefRenderer,U as createStretchRenderer,P as createUVRenderer,$ as createVectorFieldRenderer,ae as estimateMagnitudeRange,O as getBandNames,G as getClassField,D as getDefaultBandCombination,N as getDefaultInterpolation,Y as getDefinedInterval,H as getField,z as getFunctionColorRamp,E as getSupportedRendererTypes,W as getVariableRasterInfo,A as getWellKnownBandIndexes,q as matchPresetRenderer,te as normalizeRendererJSON};
|
|
5
|
+
import e from"../../Color.js";import{getMetersPerUnitForSR as t}from"../../core/unitUtils.js";import n from"../../layers/support/Field.js";import{isFunctionRaster as a}from"../../layers/support/rasterDatasets/datasetUtils.js";import r from"../ClassBreaksRenderer.js";import l from"../FlowRenderer.js";import s from"../RasterColormapRenderer.js";import o from"../RasterShadedReliefRenderer.js";import i from"../RasterStretchRenderer.js";import u from"../UniqueValueRenderer.js";import m from"../VectorFieldRenderer.js";import c from"./AuthoringInfo.js";import f from"./ClassBreakInfo.js";import{convertColorRampToColormap as p,predefinedJsonColorRamps as d}from"./colorRampUtils.js";import{isVectorFieldRendererSupported as b,isColormapRendererSupported as h,isUVRendererSupported as g,isClassBreaksSupported as v,isShadedReliefRendererSupported as y,isFlowRendererSupported as w}from"./rasterRendererChecks.js";import C from"./UniqueValueInfo.js";import x from"../visualVariables/ColorVariable.js";import M from"../visualVariables/SizeVariable.js";import R from"../visualVariables/support/ColorStop.js";import j from"../../rest/support/ClassBreaksDefinition.js";import{createGenerateRendererClassBreaks as V}from"../../rest/support/generateRendererUtils.js";import T from"../../rest/support/MultipartColorRamp.js";import S from"../../symbols/SimpleFillSymbol.js";const I=.25,k=T.fromJSON({type:"multipart",colorRamps:[{fromColor:[0,0,255],toColor:[0,255,255]},{fromColor:[0,255,255],toColor:[255,255,0]},{fromColor:[255,255,0],toColor:[255,0,0]}]}),F=T.fromJSON(d[0]),L=new Set(["scientific","standard-time","vector-uv","vector-magdir","vector-u","vector-v","vector-magnitude","vector-direction"]);function q(e){return e.presetRenderers?.find(({method:t,value:n})=>"raster-function-template"===t?n===e.rasterFunctionName:"variable"===t&&n===e.variableName)}function B(e,t){const{attributeTable:n,colormap:a}=e;if(b(e)){const t=te(e);if(null!=t)return t}if(t?.rasterFunctionColorRamp){const n=U(e,t);return n.colorRamp=t.rasterFunctionColorRamp,n}if(null!=a){const t=X(e);if(null!=t)return t}if(null!=n){const t=_(e);if(null!=t)return t}return U(e,t)}function E(e,t=!1){const n=["raster-stretch"];return h(e,t)&&n.push("raster-colormap"),g(e)&&n.push("unique-value"),v(e,t)&&n.push("class-breaks"),y(e)&&n.push("raster-shaded-relief"),b(e)&&n.push("vector-field"),w(e)&&n.push("flow"),n}function z(e){return a(e)&&"Colormap"===e.rasterFunction.functionName?e.rasterFunction.colorRamp:void 0}function N(e,t,n){const a=["nearest","bilinear","cubic","majority"],r=n?.toLowerCase().replace("bicubic","cubic"),l=a.find(e=>e===r);if("Map"===t)return l??"bilinear";if("standard-time"===e.dataType)return l??"nearest";return"thematic"===e.dataType||e.attributeTable||e.colormap?"nearest"===l||"majority"===l?l:"nearest":l??"bilinear"}function U(e,t){e=D(e,t?.variableName);const{bandCount:n}=e;let{bandIds:a,stretchType:r}=t||{};a?.some(e=>e>=n)&&(a=null);let l=e.statistics,s=e.histograms;n>1?(a=a?.length?a:W(e),l=null==l?null:a?.map(e=>l[e]),s=null==s?null:a?.map(e=>s[e])):a=[0],null==r&&(r=G(e)),t?.includeStatisticsInStretch&&("percent-clip"===r||"histogram-equalization"===r)&&e.statistics?.length&&(r="min-max");let o=!1;switch(r){case"none":o=!1;break;case"percent-clip":o=!s?.length;break;default:o=!l?.length}const{dataType:u}=e,m=1===a?.length&&L.has(u)?k:null,c=new i({stretchType:r,dynamicRangeAdjustment:o,colorRamp:m,outputMin:0,outputMax:255,gamma:1===a?.length?[1]:[1,1,1],useGamma:!1});return"percent-clip"===r?c.maxPercent=c.minPercent=I:"standard-deviation"===r&&(c.numberOfStandardDeviations=2),o||null==e.multidimensionalInfo&&!t?.includeStatisticsInStretch||("percent-clip"===r?c.histograms=s:"min-max"!==r&&"standard-deviation"!==r||(c.customStatistics=l?.map(e=>({...e})))),c}function D(e,t){const{multidimensionalInfo:n}=e;if(!t||!n)return e;const a=n.variables.find(e=>e.name===t);if(!a)return e;if(e=e.clone(),a){const{statistics:t,histograms:n}=a;t?.length&&(e.statistics=t.map(e=>({min:e.min,max:e.max,avg:e.avg,stddev:e.stddev}))),n?.length&&(e.histograms=n)}return e}function W(e){const t=e.bandCount;if(1===t)return null;if(2===t)return[0];const{bandInfos:n}=e;let a;if(n.length===t){const{red:e,green:t,blue:r,nir:l}=A(n);null!=e&&null!=t&&null!=r?a=[e,t,r]:null!=l&&null!=e&&null!=t&&(a=[l,e,t])}return!a&&t>=3&&(a=[0,1,2]),a}function O(e,t){const n=e.bandInfos.map(({name:e})=>e);return t?.length?t.map(e=>n[e]):n}function A(e){const t={};for(let n=0;n<e.length;n++){const a=e[n].name.toLowerCase();"red"===a?t.red=n:"green"===a?t.green=n:"blue"===a?t.blue=n:"nearinfrared"!==a&&"nearinfrared_1"!==a&&"nir"!==a||(t.nir=n)}if(null==t.blue||null==t.green||null==t.red||null==t.nir){const n=P(e);if(t.blue??=J(n,480),t.green??=J(n,550),t.red??=J(n,660),null==t.nir){const a=P(e,800);t.nir=J(a,810)??J(n,810)}}return t}function J(e,t,n=60){let a,r=n;for(const l of e){const e=Math.abs(l.wavelength-t);e<=r&&(r=e,a=l.index)}return a}function P(e,t){return e.map(({name:e,minWavelength:n,maxWavelength:a},r)=>{if(/thermal/i.test(e)||/pan/i.test(e))return null;if(null!=t&&null!=a&&a<t)return null;return{wavelength:null!=n&&null!=a?(n+a)/2:n??a??0,index:r}}).filter(e=>null!=e)}function G(e){let t="percent-clip";const{pixelType:n,dataType:a,histograms:r,statistics:l,multidimensionalInfo:s}=e,o=L.has(a)||"generic"===a&&null!=s;return"u8"!==n||"processed"!==a&&null!=r&&null!=l?"u8"===n||"elevation"===a||o?t="min-max":null!=r?t="percent-clip":null!=l&&(t="min-max"):t="none",t}function _(t,n,a,r){if(!g(t,n))return null;const{attributeTable:l,statistics:s}=t,o=H(l,n),i=Q(l,"red"),m=Q(l,"green"),f=Q(l,"blue"),d=new c,b=[],h=new Set,v=!!(i&&m&&f);if(null!=l)l.features.forEach(t=>{const n=t.attributes[o.name];if(!h.has(t.attributes[o.name])&&null!=n){h.add(n);const a=v&&("single"===i.type||"double"===i.type)&&("single"===m.type||"double"===m.type)&&("single"===f.type||"double"===f.type)&&!l.features.some(e=>e.attributes[i.name]>1||e.attributes[m.name]>1||e.attributes[f.name]>1),r=a?255:1;b.push(new C({value:t.attributes[o.name],label:t.attributes[o.name]+"",symbol:new S({style:"solid",outline:null,color:new e(v?[t.attributes[i.name]*r,t.attributes[m.name]*r,t.attributes[f.name]*r,1]:[0,0,0,0])})}))}});else if(s?.[0])for(let u=s[0].min;u<=s[0].max;u++)b.push(new C({value:u,label:u.toString(),symbol:new S({style:"solid",outline:null,color:new e([0,0,0,0])})}));if(b.sort((e,t)=>e.value&&"string"==typeof e.value.valueOf()?0:e.value>t.value?1:-1),!v){const t=p(F,{numColors:b.length});b.forEach((n,a)=>n.symbol.color=new e(t[a].slice(1,4))),d.colorRamp=F}if(a||r){const t=a||p(r,{numColors:b.length}).map(e=>e.slice(1));b.forEach((n,a)=>n.symbol.color=new e(t[a])),d.colorRamp=r}return new u({field:o.name,uniqueValueInfos:b,authoringInfo:d})}function H(e,t,a){let r;return null!=e?(r=t?e.fields.find(e=>t.toLowerCase()===e.name.toLowerCase()):K(e.fields),r||(a||(r=e.fields.find(e=>"string"===e.type)),r||(r=Q(e,"value")))):r=new n({name:"value"}),r}function K(e){let t;for(let n=0;n<e.length;n++){const a=e[n].name.toLowerCase();if("string"===e[n].type){if(a.startsWith("class")){t=e[n];break}null==t&&(a.endsWith("name")||a.endsWith("type"))&&(t=e[n])}}return t}function Q(e,t){return null==e?null:e.fields.find(e=>e.name.toLowerCase()===t)}function X(e){if(!h(e))return null;let t;const{attributeTable:n,colormap:a}=e;if(null!=n){const e=Q(n,"value"),a=H(n,null,!0);"string"===a.type&&(t={},n.features.forEach(n=>{const r=n.attributes;t[r[e.name]]=a?r[a.name]:r[e.name]}))}return s.createFromColormap(a,t)}function Y(e,n="traditional"){if(!y(e))return null;const{extent:a}=e,r=a.width*t(a.spatialReference);return new o({hillshadeType:n,scalingType:r>5e6?"adjusted":"none"})}function Z(e,t){e=D(e,t?.variableName);const{attributeTable:n}=e;if(!v(e))return null;const a=null!=e.histograms?e.histograms[0]:null,l=null!=t?.numClasses&&isFinite(t?.numClasses)?t.numClasses:5,s=new c({classificationMethod:t?.classificationMethod,colorRamp:t?.colorRamp});let o=t?.field||"value";const i=[],u=[],m=1e3,d=null!=n,b=d&&n.fields.find(e=>"count"===e.name.toLowerCase()),h=d?n.fields.find(e=>e.name.toLowerCase()===o.toLowerCase()):void 0;if(h&&d){o=h.name;const e=n.features.length;let t=0;n.features.forEach(n=>t+=(b?n.attributes[b.name]:50)/e),n.features.forEach(n=>{const a=n.attributes[h.name],r=b?n.attributes[b.name]:50;if(r>0){u.push(r);const n=Math.max(1,Math.round(r/e/t*m));for(let e=0;e<n;e++)i.push(a)}})}else{const{pixelType:t}=e,r=(a.max-a.min)/a.size,l=t.includes("s")||t.includes("u"),s=l&&1===r?Math.floor(a.min+.5):a.min,o=l&&1===r?Math.floor(a.max-.5):a.max,c=a.size;let f,p=0;a.counts.forEach(e=>p+=e/c),a.counts.forEach((e,t)=>{if(e>0){u.push(e);const l=Math.max(1,Math.round(e/c/p*m));f=d?n.features[t].attributes[h.name]:0===t?s:t===c-1?o:a.min+r*(t+.5);for(let e=0;e<l;e++)i.push(f)}})}const g=t?.classificationMethod||"natural-breaks";let y=t?.definedInterval;"defined-interval"!==g||y||(y=$(e,h,l));const w=V({values:i,valueFrequency:u,normalizationTotal:null,definition:new j({classificationMethod:g,breakCount:l,definedInterval:y})});let C=t?.colors;if(!C){const e=t?.colorRamp||k;s.colorRamp=e;const n=p(e,{numColors:w.classBreaks.length,interpolateAlpha:!0});C=n.map(e=>e.slice(1))}const x=w.classBreaks.map((e,t)=>new f({minValue:e.minValue,maxValue:e.maxValue,label:e.label,symbol:new S({color:C[t]})}));return new r({field:o,classBreakInfos:x,authoringInfo:s})}function $(e,t,n){let a=0,r=0;if(null!=e.attributeTable){const n=e.attributeTable;a=r=n.features[0].attributes[t.name],n.features.forEach(e=>{const n=e.attributes[t.name];n<a&&(a=n),n>r&&(r=n)})}else if(null!=e.histograms){const t=e.histograms;a=t[0].min,r=t[0].max}return(r-a)/n}const ee=new Map([["m/s","meter-per-second"],["km/h","kilometer-per-hour"],["knots","knots"],["ft/s","feet-per-second"],["mph","mile-per-hour"]]);function te(e){if(!b(e))return null;let t;if(null!=e.statistics&&e.statistics.length&&("vector-magdir"===e.dataType||"vector-uv"===e.dataType)){const{minMagnitude:n,maxMagnitude:a}=le(e.dataType,e.statistics);t=[new M({field:"Magnitude",minSize:10,maxSize:40,minDataValue:n,maxDataValue:a})]}const n=null!=e.multidimensionalInfo?ee.get(e.multidimensionalInfo.variables[0].unit):void 0,a=new m({visualVariables:t,inputUnit:n,rotationType:"geographic"});return a.visualVariables=[...a.sizeVariables,...a.rotationVariables],a}function ne(e){return{color:e.symbolLayers[0].material?.color,type:"esriSFS",style:"esriSFSSolid"}}function ae(e){if("uniqueValue"===e.type){const t=e.uniqueValueInfos,n=t?.[0].symbol;return n?.symbolLayers?.length&&(e.uniqueValueInfos=t?.map(e=>({value:e.value,label:e.label,symbol:e.symbol?ne(e.symbol):null}))),e}if("classBreaks"===e.type){const t=e.classBreakInfos,n=t[0].symbol;return n?.symbolLayers?.length&&(e.classBreakInfos=t.map(e=>({classMinValue:e.classMinValue,classMaxValue:e.classMaxValue,label:e.label,symbol:e.symbol?ne(e.symbol):null}))),e}return e}function re(t){if(!w(t))return null;let n;if(null!=t.statistics&&t.statistics.length>0&&("vector-magdir"===t.dataType||"vector-uv"===t.dataType)){const{minMagnitude:a,maxMagnitude:r}=le(t.dataType,t.statistics);n=[new x({field:"Magnitude",stops:[new R({value:a,color:new e("#1020c0")}),new R({value:r,color:new e("#c02010")})]})]}return new l({visualVariables:n})}function le(e,t){let n,a;if("vector-magdir"===e)n=t[0].min,a=t[0].max;else{const e=t[0].min,r=t[0].max,l=t[1].min,s=t[1].max;n=0,a=Math.max(Math.abs(e),Math.abs(l),Math.abs(r),Math.abs(s))}return{minMagnitude:n,maxMagnitude:a}}export{Z as createClassBreaksRenderer,X as createColormapRenderer,B as createDefaultRenderer,re as createFlowRenderer,Y as createShadedReliefRenderer,U as createStretchRenderer,_ as createUVRenderer,te as createVectorFieldRenderer,le as estimateMagnitudeRange,O as getBandNames,H as getClassField,W as getDefaultBandCombination,N as getDefaultInterpolation,$ as getDefinedInterval,Q as getField,z as getFunctionColorRamp,E as getSupportedRendererTypes,D as getVariableRasterInfo,A as getWellKnownBandIndexes,q as matchPresetRenderer,ae as normalizeRendererJSON};
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.34/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import{unique as e,isSome as l}from"../../core/arrayUtils.js";import t from"../../core/Logger.js";import{getOrCreateMapValue as i}from"../../core/MapUtils.js";import{convertDateFormatToIntlOptions as o,formatDate as a}from"../../intl/date.js";import{isTimeOnlyField as n}from"../../layers/support/fieldUtils.js";import{format as s,round as r}from"./numberUtils.js";import u from"../visualVariables/support/ColorStop.js";import{isAnyDateField as f,formatAnyDate as d}from"../../smartMapping/support/utils.js";import{getColorFromSymbol as p}from"../../symbols/support/utils.js";import{getRampStops as m}from"../../widgets/Legend/support/colorRampUtils.js";import{getHeatmapRampStops as c}from"../../widgets/Legend/support/heatmapRampUtils.js";const y=()=>t.getLogger("esri.renderers.support.utils"),g={lt:"<",gt:">",pct:"%",ld:"–"},h={millisecond:0,second:1,minute:2,hour:3,day:4,month:5,year:6},b={millisecond:"long-month-day-year-long-time",second:"long-month-day-year-long-time",minute:"long-month-day-year-short-time",hour:"long-month-day-year-short-time",day:"long-month-day-year",month:"long-month-day-year",year:"year"},v=o("short-date");async function w(e,l,t){i(e,l,()=>[]).push(...t)}async function x(l){const t=new Map;if(!l)return t;if("visualVariables"in l&&l.visualVariables)for(const e of l.visualVariables)if(D(e)){const l=(await m(e)??[]).map(e=>e.color);await w(t,e.field||e.valueExpression,l)}if("heatmap"===l.type){const e=c(l).map(e=>e.color);await w(t,l.field||l.valueExpression,e)}else if("pie-chart"===l.type){for(const e of l.attributes)await w(t,e.field||e.valueExpression,[e.color]);await w(t,"default",[l?.othersCategory?.color,p(l.backgroundFillSymbol,null)])}else if("dot-density"===l.type){for(const e of l.attributes)await w(t,e.field||e.valueExpression,[e.color]);await w(t,"default",[l.backgroundColor])}else if("unique-value"===l.type)if("predominance"===l.authoringInfo?.type)for(const e of l.uniqueValueInfos??[])await w(t,e.value.toString(),[p(e.symbol,null)]);else{const e=(l.uniqueValueInfos??[]).map(e=>p(e.symbol,null)),{field:i,field2:o,field3:a,valueExpression:n}=l;(i||n)&&await w(t,i||n,e),o&&await w(t,o,e),a&&await w(t,a,e)}else if("class-breaks"===l.type){const e=l.classBreakInfos.map(e=>p(e.symbol,null)),{field:i,valueExpression:o}=l;await w(t,i??o,e)}else"simple"===l.type&&await w(t,"default",[p(l.symbol,null)]);return"defaultSymbol"in l&&l.defaultSymbol&&await w(t,"default",[p(l.defaultSymbol,null)]),t.forEach((l,i)=>{const o=e(l.filter(Boolean),(e,l)=>JSON.stringify(e)===JSON.stringify(l));t.set(i,o)}),t}async function V(e,l,t){const o=i(e,l,()=>new Map);for(const i of t)o.set(i.value,i.color)}async function E(e){const l=new Map;if(!e)return l;if("unique-value"!==e.type||e.authoringInfo?.type)if("class-breaks"===e.type){const t=e.classBreakInfos.map(e=>({value:e.minValue,color:p(e.symbol,null)})).reverse(),{field:i,valueExpression:o}=e;await V(l,i??o,t)}else"simple"===e.type&&await V(l,"default",[{value:"default",color:p(e.symbol,null)}]);else{const t=(e.uniqueValueInfos??[]).map(e=>({value:e.value,color:p(e.symbol,null)})),{field:i,field2:o,field3:a,valueExpression:n,fieldDelimiter:s}=e,r=[i,o,a].filter(Boolean).join(s||"");(r||n)&&await V(l,r||n,t)}if("defaultSymbol"in e&&e.defaultSymbol&&await V(l,"default",[{value:"default",color:p(e.defaultSymbol,null)}]),"visualVariables"in e&&e.visualVariables){const t=e.visualVariables.filter(e=>"color"===e.type);for(const e of t){const t=await m(e)??[];await V(l,e.field||e.valueExpression,t)}}return l}function F(e,l,t){let i="";return 0===l?i=g.lt+" ":l===t&&(i=g.gt+" "),i+e}function z(e){const{values:l,colors:t,labelIndexes:i,isDate:o}=e;return l.map((e,n)=>{let r=null;if(!i||i.includes(n)){const t=o?a(e):s(e);t&&(r=F(t,n,l.length-1))}return new u({value:e,color:t[n],label:r})})}function S(e){let l=e.minValue,t=e.maxValue;const i=e.isFirstBreak?"":g.gt+" ",o="percent-of-total"===e.normalizationType?g.pct:"";return l=null==l?"":s(l),t=null==t?"":s(t),i+l+o+" "+g.ld+" "+t+o}function k(e){const l=e.classBreakInfos,t=e.normalizationType;let i=[];if(l?.length)if("standard-deviation"!==e.classificationMethod)if(e.round){i.push(l[0].minValue);for(const e of l)i.push(e.maxValue);i=r(i),l.forEach((e,l)=>{e.label=S({minValue:0===l?i[0]:i[l],maxValue:i[l+1],isFirstBreak:0===l,normalizationType:t})})}else l.forEach((e,l)=>{e.label=S({minValue:e.minValue,maxValue:e.maxValue,isFirstBreak:0===l,normalizationType:t})});else y().warn("setLabelsForClassBreaks","cannot set labels for class breaks generated using 'standard-deviation' method.")}function j(e){const l=e.map(e=>new Date(e)),t=l.length;let i=1/0,o=null;for(let a=0;a<t-1;a++){const e=l[a];let n=1/0,s=null;for(let i=a+1;i<t;i++){const t=l[i],o=(e.getFullYear()!==t.getFullYear()?"year":e.getMonth()!==t.getMonth()&&"month")||e.getDate()!==t.getDate()&&"day"||e.getHours()!==t.getHours()&&"hour"||e.getMinutes()!==t.getMinutes()&&"minute"||e.getSeconds()!==t.getSeconds()&&"second"||"millisecond",a=h[o];a<n&&(n=a,s=o)}n<i&&(i=n,o=s)}return o}function I(e){const{value:l,domain:t,fieldInfo:i,dateFormatOptions:o}=e;let a=String(l);const r=t&&"codedValues"in t&&t.codedValues?t.getName(l):null;return r?a=r:null!=l&&i&&(f(i)||n(i))?a=d(l,o??{fieldType:i.type}):"number"==typeof l&&(a=s(l)),a}function M(e,l){return"normalizationField"in e&&e.normalizationField?q(e.field,e.normalizationField):"field"in e&&e.field?B(e.field):"valueExpression"in e&&e.valueExpression?T(e.valueExpression,e.valueExpressionTitle,l):null}function B(e){return{type:"field",field:e}}function q(e,l){return{type:"normalized-field",field:e,normalizationField:l}}function T(e,l,t){return{type:"expression",expression:e,title:l,returnType:t}}function U(t,i){const o=[];if("class-breaks"===t.type||"heatmap"===t.type)o.push(M(t,"number"));else if("unique-value"===t.type){const e=t.authoringInfo;if(e&&"relationship"===e.type){if(e.field1&&e.field2){const l=e.field1.field,t=e.field2.field,i=e.field1.normalizationField,a=e.field2.normalizationField;o.push(M({field:l,normalizationField:i})),o.push(M({field:t,normalizationField:a}))}}else{const e=t.uniqueValueInfos?.[0];let l=null;if(e?.value){const t=typeof e.value;"string"!==t&&"number"!==t||(l=t)}o.push(M(t,l)),[t.field2,t.field3].forEach(e=>e&&o.push(B(e)))}}else"attributes"in t&&t.attributes?.forEach(e=>o.push(M(e,"number")));const a=i?i(t):"visualVariables"in t?t.visualVariables:null;return a
|
|
5
|
+
import{unique as e,isSome as l}from"../../core/arrayUtils.js";import t from"../../core/Logger.js";import{getOrCreateMapValue as i}from"../../core/MapUtils.js";import{convertDateFormatToIntlOptions as o,formatDate as a}from"../../intl/date.js";import{isTimeOnlyField as n}from"../../layers/support/fieldUtils.js";import{format as s,round as r}from"./numberUtils.js";import u from"../visualVariables/support/ColorStop.js";import{isAnyDateField as f,formatAnyDate as d}from"../../smartMapping/support/utils.js";import{getColorFromSymbol as p}from"../../symbols/support/utils.js";import{getRampStops as m}from"../../widgets/Legend/support/colorRampUtils.js";import{getHeatmapRampStops as c}from"../../widgets/Legend/support/heatmapRampUtils.js";const y=()=>t.getLogger("esri.renderers.support.utils"),g={lt:"<",gt:">",pct:"%",ld:"–"},h={millisecond:0,second:1,minute:2,hour:3,day:4,month:5,year:6},b={millisecond:"long-month-day-year-long-time",second:"long-month-day-year-long-time",minute:"long-month-day-year-short-time",hour:"long-month-day-year-short-time",day:"long-month-day-year",month:"long-month-day-year",year:"year"},v=o("short-date");async function w(e,l,t){i(e,l,()=>[]).push(...t)}async function x(l){const t=new Map;if(!l)return t;if("visualVariables"in l&&l.visualVariables)for(const e of l.visualVariables)if(D(e)){const l=(await m(e)??[]).map(e=>e.color);await w(t,e.field||e.valueExpression,l)}if("heatmap"===l.type){const e=c(l).map(e=>e.color);await w(t,l.field||l.valueExpression,e)}else if("pie-chart"===l.type){for(const e of l.attributes)await w(t,e.field||e.valueExpression,[e.color]);await w(t,"default",[l?.othersCategory?.color,p(l.backgroundFillSymbol,null)])}else if("dot-density"===l.type){for(const e of l.attributes)await w(t,e.field||e.valueExpression,[e.color]);await w(t,"default",[l.backgroundColor])}else if("unique-value"===l.type)if("predominance"===l.authoringInfo?.type)for(const e of l.uniqueValueInfos??[])await w(t,e.value.toString(),[p(e.symbol,null)]);else{const e=(l.uniqueValueInfos??[]).map(e=>p(e.symbol,null)),{field:i,field2:o,field3:a,valueExpression:n}=l;(i||n)&&await w(t,i||n,e),o&&await w(t,o,e),a&&await w(t,a,e)}else if("class-breaks"===l.type){const e=l.classBreakInfos.map(e=>p(e.symbol,null)),{field:i,valueExpression:o}=l;await w(t,i??o,e)}else"simple"===l.type&&await w(t,"default",[p(l.symbol,null)]);return"defaultSymbol"in l&&l.defaultSymbol&&await w(t,"default",[p(l.defaultSymbol,null)]),t.forEach((l,i)=>{const o=e(l.filter(Boolean),(e,l)=>JSON.stringify(e)===JSON.stringify(l));t.set(i,o)}),t}async function V(e,l,t){const o=i(e,l,()=>new Map);for(const i of t)o.set(i.value,i.color)}async function E(e){const l=new Map;if(!e)return l;if("unique-value"!==e.type||e.authoringInfo?.type)if("class-breaks"===e.type){const t=e.classBreakInfos.map(e=>({value:e.minValue,color:p(e.symbol,null)})).reverse(),{field:i,valueExpression:o}=e;await V(l,i??o,t)}else"simple"===e.type&&await V(l,"default",[{value:"default",color:p(e.symbol,null)}]);else{const t=(e.uniqueValueInfos??[]).map(e=>({value:e.value,color:p(e.symbol,null)})),{field:i,field2:o,field3:a,valueExpression:n,fieldDelimiter:s}=e,r=[i,o,a].filter(Boolean).join(s||"");(r||n)&&await V(l,r||n,t)}if("defaultSymbol"in e&&e.defaultSymbol&&await V(l,"default",[{value:"default",color:p(e.defaultSymbol,null)}]),"visualVariables"in e&&e.visualVariables){const t=e.visualVariables.filter(e=>"color"===e.type);for(const e of t){const t=await m(e)??[];await V(l,e.field||e.valueExpression,t)}}return l}function F(e,l,t){let i="";return 0===l?i=g.lt+" ":l===t&&(i=g.gt+" "),i+e}function z(e){const{values:l,colors:t,labelIndexes:i,isDate:o}=e;return l.map((e,n)=>{let r=null;if(!i||i.includes(n)){const t=o?a(e):s(e);t&&(r=F(t,n,l.length-1))}return new u({value:e,color:t[n],label:r})})}function S(e){let l=e.minValue,t=e.maxValue;const i=e.isFirstBreak?"":g.gt+" ",o="percent-of-total"===e.normalizationType?g.pct:"";return l=null==l?"":s(l),t=null==t?"":s(t),i+l+o+" "+g.ld+" "+t+o}function k(e){const l=e.classBreakInfos,t=e.normalizationType;let i=[];if(l?.length)if("standard-deviation"!==e.classificationMethod)if(e.round){i.push(l[0].minValue);for(const e of l)i.push(e.maxValue);i=r(i),l.forEach((e,l)=>{e.label=S({minValue:0===l?i[0]:i[l],maxValue:i[l+1],isFirstBreak:0===l,normalizationType:t})})}else l.forEach((e,l)=>{e.label=S({minValue:e.minValue,maxValue:e.maxValue,isFirstBreak:0===l,normalizationType:t})});else y().warn("setLabelsForClassBreaks","cannot set labels for class breaks generated using 'standard-deviation' method.")}function j(e){const l=e.map(e=>new Date(e)),t=l.length;let i=1/0,o=null;for(let a=0;a<t-1;a++){const e=l[a];let n=1/0,s=null;for(let i=a+1;i<t;i++){const t=l[i],o=(e.getFullYear()!==t.getFullYear()?"year":e.getMonth()!==t.getMonth()&&"month")||e.getDate()!==t.getDate()&&"day"||e.getHours()!==t.getHours()&&"hour"||e.getMinutes()!==t.getMinutes()&&"minute"||e.getSeconds()!==t.getSeconds()&&"second"||"millisecond",a=h[o];a<n&&(n=a,s=o)}n<i&&(i=n,o=s)}return o}function I(e){const{value:l,domain:t,fieldInfo:i,dateFormatOptions:o}=e;let a=String(l);const r=t&&"codedValues"in t&&t.codedValues?t.getName(l):null;return r?a=r:null!=l&&i&&(f(i)||n(i))?a=d(l,o??{fieldType:i.type}):"number"==typeof l&&(a=s(l)),a}function M(e,l){return"normalizationField"in e&&e.normalizationField?q(e.field,e.normalizationField):"field"in e&&e.field?B(e.field):"valueExpression"in e&&e.valueExpression?T(e.valueExpression,e.valueExpressionTitle,l):null}function B(e){return{type:"field",field:e}}function q(e,l){return{type:"normalized-field",field:e,normalizationField:l}}function T(e,l,t){return{type:"expression",expression:e,title:l,returnType:t}}function U(t,i){const o=[];if("class-breaks"===t.type||"heatmap"===t.type)o.push(M(t,"number"));else if("unique-value"===t.type){const e=t.authoringInfo;if(e&&"relationship"===e.type){if(e.field1&&e.field2){const l=e.field1.field,t=e.field2.field,i=e.field1.normalizationField,a=e.field2.normalizationField;o.push(M({field:l,normalizationField:i})),o.push(M({field:t,normalizationField:a}))}}else{const e=t.uniqueValueInfos?.[0];let l=null;if(e?.value){const t=typeof e.value;"string"!==t&&"number"!==t||(l=t)}o.push(M(t,l)),[t.field2,t.field3].forEach(e=>e&&o.push(B(e)))}}else"attributes"in t&&t.attributes?.forEach(e=>o.push(M(e,"number")));const a=i?i(t):"visualVariables"in t?t.visualVariables:null;return a?.forEach(e=>o.push(M(e,"number"))),e(o.filter(l),(e,l)=>"field"===e.type&&"field"===l.type?e.field===l.field:"normalized-field"===e.type&&"normalized-field"===l.type?e.field===l.field&&e.normalizationField===l.normalizationField:"expression"===e.type&&"expression"===l.type&&e.expression===l.expression)}function D(e){return"color"===e.type}export{j as calculateDateFormatInterval,S as createClassBreakLabel,z as createColorStops,I as createUniqueValueLabel,b as dateFormatIntervalOptions,M as getAttribute,U as getAttributes,E as getColorsForRendererValues,x as getColorsFromRenderer,k as setLabelsForClassBreaks,v as timelineDateFormatOptions};
|
package/request.js
CHANGED
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.34/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import e from"./config.js";import{id as r}from"./kernel.js";import t from"./core/Error.js";import has from"./core/has.js";import{clone as s}from"./core/lang.js";import{getOrCreateMapValue as o}from"./core/MapUtils.js";import{onAbort as n,createAbortError as a,isAbortError as i,isAborted as l}from"./core/promiseUtils.js";import{queryToObject as u,isDataProtocol as c,isBlobProtocol as d,normalize as p,getInterceptor as m,isTrustedServer as h,getOrigin as f,toHTTPS as y,objectToQuery as w,getProxyRule as g,getProxyUrl as q,addQueryParameters as b,hasSameOrigin as S,addProxyRule as T,getAppUrl as k}from"./core/urlUtils.js";import{isHostedAgolService as O}from"./layers/support/arcgisLayerUrl.js";import{isSecureProxyService as v}from"./portal/support/urlUtils.js";import{getApiKey as C}from"./support/apiKeyUtils.js";import{registerNoCorsDomains as x,setPreferredHost as L,getPreferredUrl as j,isNoCorsRequestRequired as E,sendNoCorsRequest as U,createTimeoutError as P,loadImageAsync as A}from"./support/requestUtils.js";async function H(e,r){e instanceof URL&&(e=e.toString()),r?.query instanceof URLSearchParams&&(r.query=u(r.query.toString().replaceAll("+"," ")));const t=c(e),s=d(e);s||t||(e=p(e));const o={url:e,requestOptions:{...r}},a=e=>({data:e,getAllHeaders:B,getHeader:B,httpStatus:200,requestOptions:o.requestOptions,url:o.url}),i=m(e,_.internalInterceptors);if(i){const e=await Y(i,o);if(null!=e)return a(e)}let l=m(e);if(l){const e=await Y(l,o);if(null!=e)return a(e);l.after||l.error||(l=null)}if(e=o.url,"image"===(r=o.requestOptions).responseType&&(has("host-webworker")||has("host-node")))throw W("request:invalid-parameters",new Error("responseType 'image' is not supported in Web Workers or Node environment"),o);if("head"===r.method){if(r.body)throw W("request:invalid-parameters",new Error("body parameter cannot be set when method is 'head'"),o);if(t||s)throw W("request:invalid-parameters",new Error("data and blob URLs are not supported for method 'head'"),o)}if(await G(),M)return M.execute(e,r);const h=new AbortController,f=n(r,()=>h.abort()),y={controller:h,credential:void 0,credentialToken:void 0,fetchOptions:void 0,hasToken:!1,interceptor:l,params:o,redoRequest:!1,useIdentity:_.useIdentity,useProxy:!1,useSSL:!1,withCredentials:!1},w=r.useRequestQueue?te(y):se(y),g=await w.finally(()=>f?.remove());return l?.after?.(g),g}let M,R=!1;const _=e.request,D="FormData"in globalThis,F=new Set([499,498,403,401]),I=new Set(["COM_0056","COM_0057","SB_0008"]),N=[/\/arcgis\/tokens/i,/\/sharing(\/rest)?\/generatetoken/i,/\/rest\/info/i],B=()=>null,$=Symbol();function z(e){const r=f(e);r&&!H._corsServers.includes(r)&&H._corsServers.push(r)}function Q(e){const r=f(e);return!r||r.endsWith(".arcgis.com")||H._corsServers.includes(r)||h(r)}function W(e,r,o,n){let l;const u={url:o.url,requestOptions:o.requestOptions,getAllHeaders:B,getHeader:B,ssl:!1};if(r instanceof t)return r.details?(r.details=s(r.details),r.details.url=o.url,r.details.requestOptions=o.requestOptions):r.details=u,r;if(r){const e=n&&(()=>Array.from(n.headers)),t=n&&(e=>n.headers.get(e)),s=n?.status,o=r.message;o&&(l=o),e&&t&&(u.getAllHeaders=e,u.getHeader=t),u.httpStatus=(null!=r.httpCode?r.httpCode:r.code)||s||0,u.subCode=r.subcode,u.messageCode=r.messageCode,"string"==typeof r.details?(u.messages=[r.details],l??=r.details):(u.messages=r.details,l??=u.messages?.[0]),u.raw=$ in r?r[$]:r}return l??="Error",i(r)?a():new t(e,l,u)}async function G(){has("host-webworker")&&(!M&&globalThis.invokeStaticMessage?M=await import("./core/workers/request.js"):R=!0)}async function J(){r||await import("./identity/IdentityManager.js")}async function K(e){const t=e.params.url,s=e.params.requestOptions,o=e.controller.signal,n=s.body;let a=null,i=null;if(D&&"HTMLFormElement"in globalThis&&(n instanceof FormData?a=n:n instanceof HTMLFormElement&&(a=new FormData(n))),"string"==typeof n&&(i=n),e.fetchOptions={cache:s.cacheBust?"no-cache":"default",credentials:"same-origin",headers:s.headers||{},method:"head"===s.method?"HEAD":"GET",mode:"cors",priority:_.priority,redirect:"follow",signal:o},(a||i)&&(e.fetchOptions.body=a||i),(R||"anonymous"===s.authMode)&&(e.useIdentity=!1),e.hasToken=!!(/token=/i.test(t)||s.query?.token||a?.get("token")),!e.hasToken){const r=C(t);r&&(s.query??={},s.query.token=r,e.hasToken=!0)}if(e.useIdentity&&!e.hasToken&&!e.credential&&!e.credentialToken&&!X(t)&&!l(o)){let n;"immediate"===s.authMode?(await J(),n=await r.getCredential(t,{signal:o})):"no-prompt"===s.authMode?(await J(),n=await r.getCredential(t,{prompt:!1,signal:o}).catch(()=>{})):r&&(n=r.findCredential(t)),n&&(e.credential=n,e.credentialToken=n.token,e.useSSL=!!n.ssl)}}function X(e){return N.some(r=>r.test(e))}async function V(e){let t=e.params.url,s=j(t);const o=e.params.requestOptions,n=e.fetchOptions??{},i=d(t)||c(t),l=o.responseType||"json",u=i?0:null!=o.timeout?o.timeout:_.timeout;let p=!1;if(!i){e.useSSL&&(t=y(t));let a={...o.query};e.credentialToken&&(a.token=e.credentialToken);let i=w(a);has("esri-url-encodes-apostrophe")&&(i=i.replaceAll("'","%27"));const l=s.length+1+i.length;let u;p="delete"===o.method||"post"===o.method||"put"===o.method||!!o.body||l>_.maxUrlLength;const c=o.useProxy||!!g(t);if(c){const e=q(t);u=e.path,!p&&u.length+1+l>_.maxUrlLength&&(p=!0),e.query&&(a={...e.query,...a})}if("HEAD"===n.method&&(p||c)){if(p){if(l>_.maxUrlLength)throw W("request:invalid-parameters",new Error("URL exceeds maximum length"),e.params);throw W("request:invalid-parameters",new Error("cannot use POST request when method is 'head'"),e.params)}if(c)throw W("request:invalid-parameters",new Error("cannot use proxy when method is 'head'"),e.params)}if(p?(n.method="delete"===o.method?"DELETE":"put"===o.method?"PUT":"POST",o.body?t=b(t,a):(n.body=w(a),n.headers||(n.headers={}),n.headers["Content-Type"]="application/x-www-form-urlencoded")):t=b(t,a),c&&(e.useProxy=!0,t=`${u}?${t}`),a.token&&D&&n.body instanceof FormData&&!v(t)&&n.body.set("token",a.token),o.hasOwnProperty("withCredentials"))e.withCredentials=o.withCredentials;else if(!S(t,k()))if(h(t))e.withCredentials=!0;else if(r){const s=r.findServerInfo(t);s?.webTierAuth&&(e.withCredentials=!0)}e.withCredentials&&(n.credentials="include",E(t)&&await U(p?b(t,a):t)),s=j(t)}let m,O,C=0,x=!1;u>0&&(C=setTimeout(()=>{x=!0,e.controller.abort()},u));try{if("native-request-init"===o.responseType)O=n,O.url=s,o.signal?O.signal=o.signal:delete O.signal;else if("image"!==o.responseType||"default"!==n.cache||"GET"!==n.method||p||Z(o.headers)||!i&&!e.useProxy&&_.proxyUrl&&!Q(t)){if(H._beforeFetch&&await H._beforeFetch(t,n),m=await fetch(s,n),H._afterFetch&&await H._afterFetch(m),e.useProxy||z(t),"native"===o.responseType)O=m;else if("HEAD"!==n.method)if(m.ok){switch(l){case"array-buffer":O=await m.arrayBuffer();break;case"blob":case"image":O=await m.blob();break;default:O=await m.text()}if(C&&(clearTimeout(C),C=0),"json"===l||"xml"===l||"document"===l)if(O)switch(l){case"json":O=JSON.parse(O);break;case"xml":O=ee(O,"application/xml");break;case"document":O=ee(O,"text/html")}else O=null;if(O){if("array-buffer"===l||"blob"===l){const e=m.headers.get("Content-Type");if(e&&/application\/json|text\/plain/i.test(e)&&O["blob"===l?"size":"byteLength"]<=750)try{const e=await new Response(O).json();e.error&&(O=e)}catch{}}"image"===l&&O instanceof Blob&&(O=await ne(URL.createObjectURL(O),e,!0))}}else{O=await m.text();try{O=JSON.parse(O)}catch{}}}else O=await ne(s,e)}catch(L){if("AbortError"===L.name){if(x)throw P();throw a("Request canceled")}if(!(!m&&L instanceof TypeError&&_.proxyUrl)||o.body||"delete"===o.method||"head"===o.method||"post"===o.method||"put"===o.method||e.useProxy||Q(t))throw L;e.redoRequest=!0,T({proxyUrl:_.proxyUrl,urlPrefix:f(t)??""})}finally{C&&clearTimeout(C)}return[m,O]}async function Y(e,r){if(null!=e.responseData)return e.responseData;if(e.headers&&(r.requestOptions.headers={...r.requestOptions.headers,...e.headers}),e.query&&(r.requestOptions.query={...r.requestOptions.query,...e.query}),e.before){let o,n;try{n=await e.before(r)}catch(s){o=W("request:interceptor",s,r)}if((n instanceof Error||n instanceof t)&&(o=W("request:interceptor",n,r)),o)throw e.error&&e.error(o),o;return n}}function Z(e){if(e)for(const r of Object.getOwnPropertyNames(e))if(e[r])return!0;return!1}function ee(e,r){let t;try{t=(new DOMParser).parseFromString(e,r)}catch{}if(!t||t.getElementsByTagName("parsererror").length)throw new SyntaxError("XML Parse error");return t}H._corsServers=["https://server.arcgisonline.com","https://services.arcgisonline.com"],H._beforeFetch=void 0,H._afterFetch=void 0;const re=new Map;async function te(e){const r=ae(e.params.url);if(!r)return se(e);const{QueueProcessor:t}=await import("./core/QueueProcessor.js"),s=o(re,r.origin,()=>{const e=r.isHosted?has("request-queue-concurrency-hosted"):has("request-queue-concurrency-non-hosted");return new t({concurrency:e,process:e=>{if(l(e.params.requestOptions))throw W("",a("Request canceled"),e.params);return se(e)}})});return s.push(e)}async function se(e){let t,s;await K(e);try{do{[t,s]=await V(e)}while(!await oe(e,t,s))}catch(a){const r=W("request:server",a,e.params,t);throw r.details.ssl=e.useSSL,e.interceptor?.error&&e.interceptor.error(r),r}const o=e.params.url;if(s)if(/\/sharing\/rest\/(accounts|portals)\/self/i.test(o)){if(!e.hasToken&&!e.credentialToken&&s.user?.username&&!h(o)){const e=f(o,!0);e&&_.trustedServers.push(e)}Array.isArray(s.authorizedCrossOriginNoCorsDomains)&&x(s.authorizedCrossOriginNoCorsDomains)}else{"json"===(e.params.requestOptions.responseType||"json")&&L(o,s)}const n=e.credential;if(n&&r){const e=r.findServerInfo(n.server);let t=e?.owningSystemUrl;if(t){t=t.replace(/\/?$/,"/sharing");const e=r.findCredential(t,n.userId);e&&-1===r._getIdenticalSvcIdx(t,e)&&e.resources.unshift(t)}}return{data:s,getAllHeaders:t?()=>Array.from(t.headers):B,getHeader:t?e=>t.headers.get(e):B,httpStatus:t?.status??200,requestOptions:e.params.requestOptions,ssl:e.useSSL,url:e.params.url}}async function oe(e,t,s){if(e.redoRequest)return e.redoRequest=!1,!1;const o=e.params.requestOptions;if(!t||"native"===o.responseType||"native-request-init"===o.responseType)return!0;let n,a;if(s&&(s.error&&"object"==typeof s.error?n=s.error:"error"===s.status&&Array.isArray(s.messages)&&(n={...s},n[$]=s,n.details=s.messages)),!n&&!t.ok)throw n=new Error(`Unable to load ${t.url} status: ${t.status}`),n[$]=s,n;let i,l=null;n&&(a=Number(n.code),l=n.hasOwnProperty("subcode")?Number(n.subcode):null,i=n.messageCode,i=i?.toUpperCase());const u=o.authMode;if(403===a&&(4===l||n.message?.toLowerCase().includes("ssl")&&!n.message.toLowerCase().includes("permission"))){if(!e.useSSL)return e.useSSL=!0,!1}else if(!e.hasToken&&e.useIdentity&&("no-prompt"!==u||498===a)&&void 0!==a&&F.has(a)&&!X(e.params.url)&&(403!==a||(!i||!I.has(i))&&(null==l||2===l&&e.credentialToken))){await J();try{const t=await r.getCredential(e.params.url,{error:W("request:server",n,e.params),credential:e.credential,prompt:"no-prompt"!==u,signal:e.controller.signal,token:e.credentialToken});return e.credential=t,e.credentialToken=t.token,e.useSSL=e.useSSL||t.ssl,!1}catch(c){if("no-prompt"===u)return e.credential=void 0,e.credentialToken=void 0,!1;n=c}}if(n)throw n;return!0}function ne(e,r,t=!1){const s=r.controller.signal,o=new Image;return r.withCredentials?o.crossOrigin="use-credentials":o.crossOrigin="anonymous",o.alt="",o.fetchPriority=_.priority,o.src=e,A(o,e,t,s)}function ae(e){let r,t;return"string"==typeof e?(r=f(e,!0),t=O(e)):(r=e.origin,t=O(e.toString())),null==r?null:{origin:r,isHosted:t}}export{H as default};
|
|
5
|
+
import e from"./config.js";import{id as r}from"./kernel.js";import t from"./core/Error.js";import has from"./core/has.js";import{clone as s}from"./core/lang.js";import{getOrCreateMapValue as o}from"./core/MapUtils.js";import{onAbort as n,createAbortError as a,isAbortError as i,isAborted as l}from"./core/promiseUtils.js";import{queryToObject as u,isDataProtocol as c,isBlobProtocol as d,normalize as p,getInterceptor as m,isTrustedServer as h,getOrigin as f,toHTTPS as y,objectToQuery as w,getProxyRule as g,getProxyUrl as q,addQueryParameters as b,hasSameOrigin as k,addProxyRule as S,getAppUrl as T}from"./core/urlUtils.js";import{isHostedAgolService as O}from"./layers/support/arcgisLayerUrl.js";import{isSecureProxyService as v}from"./portal/support/urlUtils.js";import{getApiKey as C}from"./support/apiKeyUtils.js";import{registerNoCorsDomains as x,setPreferredHost as L,getPreferredUrl as j,isNoCorsRequestRequired as E,sendNoCorsRequest as U,createTimeoutError as A,loadImageAsync as P}from"./support/requestUtils.js";async function H(e,r){e instanceof URL&&(e=e.toString()),r?.query instanceof URLSearchParams&&(r.query=u(r.query.toString().replaceAll("+"," ")));const t=c(e),s=d(e);s||t||(e=p(e));const o={url:e,requestOptions:{...r}},a=e=>({data:e,getAllHeaders:B,getHeader:B,httpStatus:200,requestOptions:o.requestOptions,url:o.url}),i=m(e,_.internalInterceptors);if(i){const e=await Y(i,o);if(null!=e)return a(e)}let l=m(e);if(l){const e=await Y(l,o);if(null!=e)return a(e);l.after||l.error||(l=null)}if(e=o.url,"image"===(r=o.requestOptions).responseType&&(has("host-webworker")||has("host-node")))throw W("request:invalid-parameters",new Error("responseType 'image' is not supported in Web Workers or Node environment"),o);if("head"===r.method){if(r.body)throw W("request:invalid-parameters",new Error("body parameter cannot be set when method is 'head'"),o);if(t||s)throw W("request:invalid-parameters",new Error("data and blob URLs are not supported for method 'head'"),o)}if(await G(),M)return M.execute(e,r);const h=new AbortController,f=n(r,()=>h.abort()),y={controller:h,credential:void 0,credentialToken:void 0,fetchOptions:void 0,hasToken:!1,interceptor:l,params:o,redoRequest:!1,useIdentity:_.useIdentity,useProxy:!1,useSSL:!1,withCredentials:!1},w=r.useRequestQueue?te(y):se(y),g=await w.finally(()=>f?.remove());return l?.after?.(g),g}let M,R=!1;const _=e.request,D="FormData"in globalThis,F=new Set([499,498,403,401]),I=new Set(["COM_0056","COM_0057","SB_0008"]),N=[/\/arcgis\/tokens/i,/\/sharing(\/rest)?\/generatetoken/i,/\/rest\/info/i],B=()=>null,$=Symbol();function z(e){const r=f(e);r&&!H._corsServers.includes(r)&&H._corsServers.push(r)}function Q(e){const r=f(e);return!r||r.endsWith(".arcgis.com")||H._corsServers.includes(r)||h(r)}function W(e,r,o,n){let l;const u={url:o.url,requestOptions:o.requestOptions,getAllHeaders:B,getHeader:B,ssl:!1};if(r instanceof t)return r.details?(r.details=s(r.details),r.details.url=o.url,r.details.requestOptions=o.requestOptions):r.details=u,r;if(r){const e=n&&(()=>Array.from(n.headers)),t=n&&(e=>n.headers.get(e)),s=n?.status,o=r.message;o&&(l=o),e&&t&&(u.getAllHeaders=e,u.getHeader=t),u.httpStatus=(null!=r.httpCode?r.httpCode:r.code)||s||0,u.subCode=r.subcode,u.messageCode=r.messageCode,"string"==typeof r.details?(u.messages=[r.details],l??=r.details):(u.messages=r.details,l??=u.messages?.[0]),u.raw=$ in r?r[$]:r}return l??="Error",i(r)?a():new t(e,l,u)}async function G(){has("host-webworker")&&(!M&&globalThis.invokeStaticMessage?M=await import("./core/workers/request.js"):R=!0)}async function J(){r||await import("./identity/IdentityManager.js")}async function K(e){const t=e.params.url,s=e.params.requestOptions,o=e.controller.signal,n=s.body;let a=null,i=null;if(D&&"HTMLFormElement"in globalThis&&(n instanceof FormData?a=n:n instanceof HTMLFormElement&&(a=new FormData(n))),"string"==typeof n&&(i=n),e.fetchOptions={cache:s.cacheBust?"no-cache":"default",credentials:"same-origin",headers:s.headers||{},keepalive:s.keepAlive??!1,method:"head"===s.method?"HEAD":"GET",mode:"cors",priority:_.priority,redirect:"follow",signal:o},(a||i)&&(e.fetchOptions.body=a||i),(R||"anonymous"===s.authMode)&&(e.useIdentity=!1),e.hasToken=!!(/token=/i.test(t)||s.query?.token||a?.get("token")),!e.hasToken){const r=C(t);r&&(s.query??={},s.query.token=r,e.hasToken=!0)}if(e.useIdentity&&!e.hasToken&&!e.credential&&!e.credentialToken&&!X(t)&&!l(o)){let n;"immediate"===s.authMode?(await J(),n=await r.getCredential(t,{signal:o})):"no-prompt"===s.authMode?(await J(),n=await r.getCredential(t,{prompt:!1,signal:o}).catch(()=>{})):r&&(n=r.findCredential(t)),n&&(e.credential=n,e.credentialToken=n.token,e.useSSL=!!n.ssl)}}function X(e){return N.some(r=>r.test(e))}async function V(e){let t=e.params.url,s=j(t);const o=e.params.requestOptions,n=e.fetchOptions??{},i=d(t)||c(t),l=o.responseType||"json",u=i?0:null!=o.timeout?o.timeout:_.timeout;let p=!1;if(!i){e.useSSL&&(t=y(t));let a={...o.query};e.credentialToken&&(a.token=e.credentialToken);let i=w(a);has("esri-url-encodes-apostrophe")&&(i=i.replaceAll("'","%27"));const l=s.length+1+i.length;let u;p="delete"===o.method||"post"===o.method||"put"===o.method||!!o.body||l>_.maxUrlLength;const c=o.useProxy||!!g(t);if(c){const e=q(t);u=e.path,!p&&u.length+1+l>_.maxUrlLength&&(p=!0),e.query&&(a={...e.query,...a})}if("HEAD"===n.method&&(p||c)){if(p){if(l>_.maxUrlLength)throw W("request:invalid-parameters",new Error("URL exceeds maximum length"),e.params);throw W("request:invalid-parameters",new Error("cannot use POST request when method is 'head'"),e.params)}if(c)throw W("request:invalid-parameters",new Error("cannot use proxy when method is 'head'"),e.params)}if(p?(n.method="delete"===o.method?"DELETE":"put"===o.method?"PUT":"POST",o.body?t=b(t,a):(n.body=w(a),n.headers||(n.headers={}),n.headers["Content-Type"]="application/x-www-form-urlencoded")):t=b(t,a),c&&(e.useProxy=!0,t=`${u}?${t}`),a.token&&D&&n.body instanceof FormData&&!v(t)&&n.body.set("token",a.token),o.hasOwnProperty("withCredentials"))e.withCredentials=o.withCredentials;else if(!k(t,T()))if(h(t))e.withCredentials=!0;else if(r){const s=r.findServerInfo(t);s?.webTierAuth&&(e.withCredentials=!0)}e.withCredentials&&(n.credentials="include",E(t)&&await U(p?b(t,a):t)),s=j(t)}let m,O,C=0,x=!1;u>0&&(C=setTimeout(()=>{x=!0,e.controller.abort()},u));try{if("native-request-init"===o.responseType)O=n,O.url=s,o.signal?O.signal=o.signal:delete O.signal;else if("image"!==o.responseType||"default"!==n.cache||n.keepalive||"GET"!==n.method||p||Z(o.headers)||!i&&!e.useProxy&&_.proxyUrl&&!Q(t)){if(H._beforeFetch&&await H._beforeFetch(t,n),m=await fetch(s,n),H._afterFetch&&await H._afterFetch(m),e.useProxy||z(t),"native"===o.responseType)O=m;else if("HEAD"!==n.method)if(m.ok){switch(l){case"array-buffer":O=await m.arrayBuffer();break;case"blob":case"image":O=await m.blob();break;default:O=await m.text()}if(C&&(clearTimeout(C),C=0),"json"===l||"xml"===l||"document"===l)if(O)switch(l){case"json":O=JSON.parse(O);break;case"xml":O=ee(O,"application/xml");break;case"document":O=ee(O,"text/html")}else O=null;if(O){if("array-buffer"===l||"blob"===l){const e=m.headers.get("Content-Type");if(e&&/application\/json|text\/plain/i.test(e)&&O["blob"===l?"size":"byteLength"]<=750)try{const e=await new Response(O).json();e.error&&(O=e)}catch{}}"image"===l&&O instanceof Blob&&(O=await ne(URL.createObjectURL(O),e,!0))}}else{O=await m.text();try{O=JSON.parse(O)}catch{}}}else O=await ne(s,e)}catch(L){if("AbortError"===L.name){if(x)throw A();throw a("Request canceled")}if(!(!m&&L instanceof TypeError&&_.proxyUrl)||o.body||"delete"===o.method||"head"===o.method||"post"===o.method||"put"===o.method||e.useProxy||Q(t))throw L;e.redoRequest=!0,S({proxyUrl:_.proxyUrl,urlPrefix:f(t)??""})}finally{C&&clearTimeout(C)}return[m,O]}async function Y(e,r){if(null!=e.responseData)return e.responseData;if(e.headers&&(r.requestOptions.headers={...r.requestOptions.headers,...e.headers}),e.query&&(r.requestOptions.query={...r.requestOptions.query,...e.query}),e.before){let o,n;try{n=await e.before(r)}catch(s){o=W("request:interceptor",s,r)}if((n instanceof Error||n instanceof t)&&(o=W("request:interceptor",n,r)),o)throw e.error&&e.error(o),o;return n}}function Z(e){if(e)for(const r of Object.getOwnPropertyNames(e))if(e[r])return!0;return!1}function ee(e,r){let t;try{t=(new DOMParser).parseFromString(e,r)}catch{}if(!t||t.getElementsByTagName("parsererror").length)throw new SyntaxError("XML Parse error");return t}H._corsServers=["https://server.arcgisonline.com","https://services.arcgisonline.com"],H._beforeFetch=void 0,H._afterFetch=void 0;const re=new Map;async function te(e){const r=ae(e.params.url);if(!r)return se(e);const{QueueProcessor:t}=await import("./core/QueueProcessor.js"),s=o(re,r.origin,()=>{const e=r.isHosted?has("request-queue-concurrency-hosted"):has("request-queue-concurrency-non-hosted");return new t({concurrency:e,process:e=>{if(l(e.params.requestOptions))throw W("",a("Request canceled"),e.params);return se(e)}})});return s.push(e)}async function se(e){let t,s;await K(e);try{do{[t,s]=await V(e)}while(!await oe(e,t,s))}catch(a){const r=W("request:server",a,e.params,t);throw r.details.ssl=e.useSSL,e.interceptor?.error&&e.interceptor.error(r),r}const o=e.params.url;if(s)if(/\/sharing\/rest\/(accounts|portals)\/self/i.test(o)){if(!e.hasToken&&!e.credentialToken&&s.user?.username&&!h(o)){const e=f(o,!0);e&&_.trustedServers.push(e)}Array.isArray(s.authorizedCrossOriginNoCorsDomains)&&x(s.authorizedCrossOriginNoCorsDomains)}else{"json"===(e.params.requestOptions.responseType||"json")&&L(o,s)}const n=e.credential;if(n&&r){const e=r.findServerInfo(n.server);let t=e?.owningSystemUrl;if(t){t=t.replace(/\/?$/,"/sharing");const e=r.findCredential(t,n.userId);e&&-1===r._getIdenticalSvcIdx(t,e)&&e.resources.unshift(t)}}return{data:s,getAllHeaders:t?()=>Array.from(t.headers):B,getHeader:t?e=>t.headers.get(e):B,httpStatus:t?.status??200,requestOptions:e.params.requestOptions,ssl:e.useSSL,url:e.params.url}}async function oe(e,t,s){if(e.redoRequest)return e.redoRequest=!1,!1;const o=e.params.requestOptions;if(!t||"native"===o.responseType||"native-request-init"===o.responseType)return!0;let n,a;if(s&&(s.error&&"object"==typeof s.error?n=s.error:"error"===s.status&&Array.isArray(s.messages)&&(n={...s},n[$]=s,n.details=s.messages)),!n&&!t.ok)throw n=new Error(`Unable to load ${t.url} status: ${t.status}`),n[$]=s,n;let i,l=null;n&&(a=Number(n.code),l=n.hasOwnProperty("subcode")?Number(n.subcode):null,i=n.messageCode,i=i?.toUpperCase());const u=o.authMode;if(403===a&&(4===l||n.message?.toLowerCase().includes("ssl")&&!n.message.toLowerCase().includes("permission"))){if(!e.useSSL)return e.useSSL=!0,!1}else if(!e.hasToken&&e.useIdentity&&("no-prompt"!==u||498===a)&&void 0!==a&&F.has(a)&&!X(e.params.url)&&(403!==a||(!i||!I.has(i))&&(null==l||2===l&&e.credentialToken))){await J();try{const t=await r.getCredential(e.params.url,{error:W("request:server",n,e.params),credential:e.credential,prompt:"no-prompt"!==u,signal:e.controller.signal,token:e.credentialToken});return e.credential=t,e.credentialToken=t.token,e.useSSL=e.useSSL||t.ssl,!1}catch(c){if("no-prompt"===u)return e.credential=void 0,e.credentialToken=void 0,!1;n=c}}if(n)throw n;return!0}function ne(e,r,t=!1){const s=r.controller.signal,o=new Image;return r.withCredentials?o.crossOrigin="use-credentials":o.crossOrigin="anonymous",o.alt="",o.fetchPriority=_.priority,o.src=e,P(o,e,t,s)}function ae(e){let r,t;return"string"==typeof e?(r=f(e,!0),t=O(e)):(r=e.origin,t=O(e.toString())),null==r?null:{origin:r,isHosted:t}}export{H as default};
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
|
|
3
3
|
See https://js.arcgis.com/4.34/esri/copyright.txt for details.
|
|
4
4
|
*/
|
|
5
|
-
import{__decorate as e}from"tslib";import t from"../../config.js";import{id as s}from"../../kernel.js";import r from"../../request.js";import{isSome as i}from"../../core/arrayUtils.js";import a from"../../core/Error.js";import{IdentifiableMixin as o}from"../../core/Identifiable.js";import{JSONSupportMixin as n}from"../../core/JSONSupport.js";import{clone as l}from"../../core/lang.js";import{Loadable as u}from"../../core/Loadable.js";import{throwIfAborted as d,throwIfAbortError as p}from"../../core/promiseUtils.js";import{property as c}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/Logger.js";import{reader as m}from"../../core/accessorSupport/decorators/reader.js";import{subclass as y}from"../../core/accessorSupport/decorators/subclass.js";import h from"../../geometry/SpatialReference.js";import{getFeatureJSON as f,getFeatureIds as b,getAttachmentEditsJSON as g,isProtectedOrPrivateVersionError as v,unpackEditResultData as j,createEditedFeatures as S}from"../../layers/graphics/applyEditsUtils.js";import{checkEditingCapabilities as E,normalizeEdits as O,normalizeGeometries as R}from"../../layers/graphics/editingSupport.js";import{emitApplyEditsEvent as A}from"../../layers/mixins/EditBusLayer.js";import{ensureCredentialIfSignedIn as w}from"../../layers/support/featureLayerUtils.js";import{getOwningPortalUrl as F}from"../../layers/support/layerUtils.js";import{getFeatureLayerCapabilities as I}from"../../layers/support/serviceCapabilitiesUtils.js";import U from"../../portal/PortalItem.js";import{getUserPrivileges as C}from"../../portal/support/portalItemUtils.js";import{isSecureProxyService as T}from"../../portal/support/urlUtils.js";import{parseUrl as D,asValidOptions as P,encode as V}from"../utils.js";import{unapplyEditsZUnitScaling as G}from"../query/operations/editsZScale.js";import{readBoolean as k,readNumber as N}from"../support/jsonUtils.js";import{isSafeToEditVersion as L,isVersionInEditSession as M,currentSessionId as _}from"../../versionManagement/support/versionManagementUtils.js";function x(e,t){const s=t.id;return{id:s,name:t.name,url:`${e}/${s}`,type:t.type||"Table"}}function Q(e){return{data:J(e),sync:B(e),operations:q(e.capabilities,e),query:W(e),editing:H(e)}}function J(e){return{isDataVersioned:k(e,"hasVersionedData",!1),isDataBranchVersioned:k(e,"hasBranchVersionedData",!1)}}function q(e,t){const s=e?e.toLowerCase().split(",").map(e=>e.trim()):[],r=s.includes("query"),i=s.includes("editing")&&!t.datesInUnknownTimezone;let a=i&&s.includes("create"),o=i&&s.includes("delete"),n=i&&s.includes("update");return i&&!(a||o||n)&&(a=o=n=!0),{supportsAdd:a,supportsDelete:o,supportsEditing:i,supportsChangeTracking:s.includes("changetracking"),supportsQuery:r,supportsQueryDataElements:k(t,"supportsQueryDataElements",!1),supportsQueryDomains:k(t,"supportsQueryDomains",!1),supportsQueryContingentValues:k(t,"supportsQueryContingentValues",!1),supportsSync:s.includes("sync"),supportsUpdate:n}}function W(e){return{maxRecordCountFactor:N(e,"maxRecordCountFactor",void 0),maxRecordCount:N(e,"maxRecordCount",void 0)}}function H(e){const t=e?.advancedEditingCapabilities;return{supportsAsyncApplyEdits:k(t,"supportsAsyncApplyEdits",!1),supportsGlobalId:k(e,"supportsApplyEditsWithGlobalIds",!1),supportsReturnServiceEditsInSourceSpatialReference:k(t,"supportsReturnServiceEditsInSourceSR",!1),supportsSharedTemplates:k(e,"supportsSharedTemplates",!1)||k(e,"hasSharedTemplates",!1),supportsSplit:k(t,"supportsSplit",!1)}}function B(e){const t=e?.syncCapabilities,s=t?.supportedSyncDataOptions;return{supportsAsync:k(t,"supportsAsync",!1),supportedSyncDataOptions:{annotations:!(1&~s),dimensions:!(2&~s),contingentValues:!(4&~s),attributeRules:!(8&~s),utilityNetworkSystem:!(16&~s),annotationFullModel:!(32&~s),include3DObjects:!(64&~s),utilityNetworkMissingLayers:!(128&~s),preserveTrueCurves:!(256&~s)}}}let $=class extends(n(o(u))){constructor(e){super(e),this.url=null,this.sourceJSON=null,this.userHasFullEditingPrivileges=!1,this.userHasUpdateItemPrivileges=!1,this.userTypeExtensions=[],this.layerInfos=null,this.tableInfos=null,this.capabilities=null}read(e,t){this.sourceJSON=e,super.read(e,t)}get utilityNetworkUrl(){if(this.sourceJSON)for(const e of this.sourceJSON.layers)if("Utility Network Layer"===e.type)return`${this.url}/${e.id}`;return null}get versionManagementServiceUrl(){return this.sourceJSON?.hasBranchVersionedData&&!T(this.url)?this.url.replace(/\/FeatureServer/i,"/VersionManagementServer"):null}readLayerInfos(e,t){return(t.layers||[]).map(e=>{const{type:t,geometryType:s}=e;return{...x(this.url,e),type:t||"Feature Layer",geometryType:s}})}readTableInfos(e,t){return(t.tables||[]).map(e=>x(this.url,e))}readCapabilities(e,t){return Q(t)}get effectiveCapabilities(){const e=this.capabilities;if(!e)return null;const t=l(e),{operations:s}=t;return this.userHasUpdateItemPrivileges?(s.supportsAdd=s.supportsDelete=s.supportsEditing=s.supportsQuery=s.supportsUpdate=!0,t):(this.userHasFullEditingPrivileges&&s.supportsEditing&&(s.supportsAdd=s.supportsDelete=s.supportsUpdate=!0),t)}get loaded(){return super.loaded}load(e){return this.addResolvingPromise(this._fetchService(this.url,e).then(()=>this._setUserPrivileges(e))),Promise.resolve(this)}async fetchAllLayersAndTables(e){return await this.load(e),this._fetchLayersAndTablesPromise||=this._fetchLayersAndTables(this.url),d(e),this._fetchLayersAndTablesPromise}async applyEdits(e,t){let s=null;try{const{results:r,edits:i,editedFeatures:a}=await this._internalApplyEdits(e,t),o=e=>e.filter(e=>!e.error).map(l);let n=0;return r.map(e=>{s=A(this.url,e.id,t?.gdbVersion,!0);const r={edits:i[n],addedFeatures:o(e.addFeatureResults),updatedFeatures:o(e.updateFeatureResults),deletedFeatures:o(e.deleteFeatureResults),addedAttachments:o(e.addAttachmentResults),updatedAttachments:o(e.updateAttachmentResults),deletedAttachments:o(e.deleteAttachmentResults),exceededTransferLimit:!1,historicMoment:e.editMoment?new Date(e.editMoment):null};n+=1,a.length>0&&(r.editedFeatures=a),s.resolve(r),s=null}),r}catch(r){throw s&&s.reject(r),r}}async _setUserPrivileges(e){if(t.userPrivilegesApplied)try{const{features:{fullEdit:t},content:{updateItem:s}}=await this._fetchUserPrivileges(this.sourceJSON.serviceItemId,e);this._set("userHasFullEditingPrivileges",t),this._set("userHasUpdateItemPrivileges",s)}catch(s){p(s)}}async _fetchUserPrivileges(e,t){const r=!0,i=!1,a=!1;if(!e)return{features:{edit:r,fullEdit:i},content:{updateItem:a}};let o,n,l;try{o=await F(this.url,t)}catch(u){p(u)}try{const e=null!=t?t.signal:null;n=await(s?.getCredential(`${o}/sharing`,{prompt:!1,signal:e}))}catch(u){p(u)}if(!n)return{features:{edit:r,fullEdit:i},content:{updateItem:a}};try{if(l=new U({id:e,portal:{url:o}}),await l.load(t),l.portal.user)return C(l)}catch(u){p(u)}return{features:{edit:r,fullEdit:i},content:{updateItem:a}}}async _internalApplyEdits(e,t){await w(this.url);const s=t?.globalIdUsed??!1,a=h.fromJSON(this.sourceJSON.spatialReference),{edits:o,options:n}=await this._processApplyEditsParams(e,t),l=await Promise.all(o.map(async e=>{const t=e.addFeatures?.map(e=>f({spatialReference:a},e,null))??[],r=(await Promise.all(t)).filter(i),o=r.length>0?r:null,n=e.updateFeatures?.map(e=>f({spatialReference:a},e,null))??[],l=(await Promise.all(n)).filter(i),u=l.length>0?l:null,d=b(e.identifierFields,e.deleteFeatures,s),p=d.length>0?d:null;G(o,u,a);const c=await g(e.identifierFields,e);let m=null;if(c){m={adds:c.adds.length>0?c.adds:void 0,updates:c.updates.length>0?c.updates:void 0,deletes:c.deletes.length>0?c.deletes:void 0}}const y={};return e.deleteAssociations&&(y.deleteAssociations=e.deleteAssociations),e.combineGroupedObjects&&(y.combineGroupedObjects=e.combineGroupedObjects),e.divideGroupedObjects&&(y.divideGroupedObjects=e.divideGroupedObjects),{id:e.id,adds:o,updates:u,deletes:p,attachments:m,...y}})),u={gdbVersion:n?.gdbVersion,rollbackOnFailure:!0,useGlobalIds:s,returnEditMoment:!0,honorSequenceOfEdits:n?.honorSequenceOfEdits,usePreviousEditMoment:n?.usePreviousEditMoment,returnServiceEditsInSourceSR:!1,returnServiceEditsOption:"originalAndCurrentFeatures",async:!1};await L(this.url,t?.gdbVersion,!0);const d=M(this.url,t?.gdbVersion||null);u.edits=JSON.stringify(l);const p=D(this.url),c=P(p.query,{query:V({...u,f:"json"}),method:"post"});let m;d&&(c.authMode="immediate",c.query.sessionId=_);try{m=await r(this.url+"/applyEdits",c)}catch(y){if(!v(y))throw y;c.authMode="immediate",m=await r(this.url+"/applyEdits",c)}return{...z(m),edits:o}}async _processApplyEditsParams(e,t){const s={...t,usingFeatureServiceEndpoint:!0,usingTelecomOperations:e.some(e=>e.deleteAssociations||e.combineGroupedObjects||e.divideGroupedObjects)};return{edits:await Promise.all(e.map(async e=>{const t=this.effectiveCapabilities,r=e&&(e.addFeatures||e.updateFeatures||e.deleteFeatures),i=e&&(e.addAttachments||e.updateAttachments||e.deleteAttachments);if(E(e,t,s,!!r,!!i,"feature-service"),!t.data.isDataVersioned&&s?.gdbVersion)throw new a("feature-service:invalid-parameter","'gdbVersion' is applicable only if the layer supports versioned data. See: 'capabilities.data.isDataVersioned'");const o=O(e,t,"feature-service"),n={};e.deleteAssociations&&(n.deleteAssociations=e.deleteAssociations),e.combineGroupedObjects&&(n.combineGroupedObjects=e.combineGroupedObjects),e.divideGroupedObjects&&(n.divideGroupedObjects=e.divideGroupedObjects);const l=await R(o);return{id:e.id,...l,...n,identifierFields:e.identifierFields}})),options:s}}async _fetchService(e,t){if(this.sourceJSON)return void this.read(this.sourceJSON,{url:D(e)});const s=await r(e,{responseType:"json",query:{f:"json"},...t});this.read(s.data,{url:D(e)})}async _fetchLayersAndTables(e){const t=`${e}/layers`,s=await r(t,{responseType:"json",query:{f:"json"}});return{layers:s.data.layers.map(e=>{const{type:t,geometryType:s}=e,r=x(this.url,e),i=I(e,r.url);return{...r,type:t||"Feature Layer",geometryType:s,capabilities:i}}),tables:s.data.tables.map(e=>{const t=x(this.url,e),s=I(e,t.url);return{...t,capabilities:s}})}}};function z(e){const t=e.data,s=[];return{results:t.map(e=>{const t={addResults:e.addResults??[],updateResults:e.updateResults??[],deleteResults:e.deleteResults??[],attachments:e.attachments,editMoment:e.editMoment},r=j(t),i=e.editedFeatures,a=i?.spatialReference?new h({wkid:i?.spatialReference.wkid,wkt:i?.spatialReference.wkt,latestWkid:i?.spatialReference.latestWkid,latestVcsWkid:i?.spatialReference.latestVcsWkid,vcsWkid:i?.spatialReference.vcsWkid}):null,o=i?S(i,a):null;o&&s.push({layerId:e.id,editedFeatures:o});const n={};return e.divideGroupedObjectResults&&(n.divideGroupedObjectResults=e.divideGroupedObjectResults),e.combineGroupedObjectResults&&(n.combineGroupedObjectResults=e.combineGroupedObjectResults),{id:e.id,editedFeatures:o,...r,...n}}),editedFeatures:s}}e([c()],$.prototype,"url",void 0),e([c()],$.prototype,"sourceJSON",void 0),e([c()],$.prototype,"userHasFullEditingPrivileges",void 0),e([c()],$.prototype,"userHasUpdateItemPrivileges",void 0),e([c({readOnly:!0})],$.prototype,"utilityNetworkUrl",null),e([c({readOnly:!0})],$.prototype,"versionManagementServiceUrl",null),e([c()],$.prototype,"userTypeExtensions",void 0),e([c({json:{read:{source:["layers"]}}})],$.prototype,"layerInfos",void 0),e([m("layerInfos",["layers"])],$.prototype,"readLayerInfos",null),e([c({json:{read:{source:["tables"]}}})],$.prototype,"tableInfos",void 0),e([m("tableInfos",["tables"])],$.prototype,"readTableInfos",null),e([c({readOnly:!0,json:{read:{source:["hasVersionedData","hasSharedTemplates","hasBranchVersionedData","capabilities","supportsQueryDataElements","supportsQueryDomains","supportsQueryContingentValues","maxRecordCountFactor","maxRecordCount","advancedEditingCapabilities","supportsApplyEditsWithGlobalIds","syncCapabilities","datesInUnknownTimezone"]}}})],$.prototype,"capabilities",void 0),e([m("capabilities",["hasVersionedData","hasSharedTemplates","hasBranchVersionedData","capabilities","supportsQueryDataElements","supportsQueryDomains","supportsQueryContingentValues","maxRecordCountFactor","maxRecordCount","advancedEditingCapabilities","supportsApplyEditsWithGlobalIds","syncCapabilities","datesInUnknownTimezone"])],$.prototype,"readCapabilities",null),e([c({readOnly:!0})],$.prototype,"effectiveCapabilities",null),$=e([y("esri.rest.featureService.FeatureService")],$);const Z=$;export{Z as default};
|
|
5
|
+
import{__decorate as e}from"tslib";import t from"../../config.js";import{id as s}from"../../kernel.js";import r from"../../request.js";import{isSome as i}from"../../core/arrayUtils.js";import a from"../../core/Error.js";import{IdentifiableMixin as o}from"../../core/Identifiable.js";import{JSONSupportMixin as n}from"../../core/JSONSupport.js";import{clone as l}from"../../core/lang.js";import{Loadable as d}from"../../core/Loadable.js";import{throwIfAborted as u,throwIfAbortError as p}from"../../core/promiseUtils.js";import{property as c}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/Logger.js";import{reader as m}from"../../core/accessorSupport/decorators/reader.js";import{subclass as y}from"../../core/accessorSupport/decorators/subclass.js";import h from"../../geometry/SpatialReference.js";import{getFeatureJSON as f,getFeatureIds as b,getAttachmentEditsJSON as g,isProtectedOrPrivateVersionError as v,unpackEditResultData as j,createEditedFeatures as S}from"../../layers/graphics/applyEditsUtils.js";import{checkEditingCapabilities as E,normalizeEdits as I,normalizeGeometries as O}from"../../layers/graphics/editingSupport.js";import{emitApplyEditsEvent as F}from"../../layers/mixins/EditBusLayer.js";import{ensureCredentialIfSignedIn as R}from"../../layers/support/featureLayerUtils.js";import{getOwningPortalUrl as A}from"../../layers/support/layerUtils.js";import{getFeatureLayerCapabilities as w}from"../../layers/support/serviceCapabilitiesUtils.js";import T from"../../portal/PortalItem.js";import{getUserPrivileges as U}from"../../portal/support/portalItemUtils.js";import{isSecureProxyService as C}from"../../portal/support/urlUtils.js";import{parseUrl as D,asValidOptions as P,encode as V}from"../utils.js";import{unapplyEditsZUnitScaling as G}from"../query/operations/editsZScale.js";import{readBoolean as k,readNumber as _}from"../support/jsonUtils.js";import{isSafeToEditVersion as x,isVersionInEditSession as L,currentSessionId as M}from"../../versionManagement/support/versionManagementUtils.js";function N(e,t){const s=t.id;return{id:s,name:t.name,url:`${e}/${s}`,type:t.type||"Table"}}function Q(e){return{data:J(e),sync:B(e),operations:q(e.capabilities,e),query:W(e),editing:H(e)}}function J(e){return{isDataVersioned:k(e,"hasVersionedData",!1),isDataBranchVersioned:k(e,"hasBranchVersionedData",!1)}}function q(e,t){const s=e?e.toLowerCase().split(",").map(e=>e.trim()):[],r=s.includes("query"),i=s.includes("editing")&&!t.datesInUnknownTimezone;let a=i&&s.includes("create"),o=i&&s.includes("delete"),n=i&&s.includes("update");return i&&!(a||o||n)&&(a=o=n=!0),{supportsAdd:a,supportsDelete:o,supportsEditing:i,supportsChangeTracking:s.includes("changetracking"),supportsQuery:r,supportsQueryDataElements:k(t,"supportsQueryDataElements",!1),supportsQueryDomains:k(t,"supportsQueryDomains",!1),supportsQueryContingentValues:k(t,"supportsQueryContingentValues",!1),supportsSync:s.includes("sync"),supportsUpdate:n}}function W(e){return{maxRecordCountFactor:_(e,"maxRecordCountFactor",void 0),maxRecordCount:_(e,"maxRecordCount",void 0)}}function H(e){const t=e?.advancedEditingCapabilities;return{supportsAsyncApplyEdits:k(t,"supportsAsyncApplyEdits",!1),supportsGlobalId:k(e,"supportsApplyEditsWithGlobalIds",!1),supportsReturnServiceEditsInSourceSpatialReference:k(t,"supportsReturnServiceEditsInSourceSR",!1),supportsSharedTemplates:k(e,"supportsSharedTemplates",!1)||k(e,"hasSharedTemplates",!1),supportsSplit:k(t,"supportsSplit",!1)}}function B(e){const t=e?.syncCapabilities,s=t?.supportedSyncDataOptions;return{supportsAsync:k(t,"supportsAsync",!1),supportedSyncDataOptions:{annotations:!(1&~s),dimensions:!(2&~s),contingentValues:!(4&~s),attributeRules:!(8&~s),utilityNetworkSystem:!(16&~s),annotationFullModel:!(32&~s),include3DObjects:!(64&~s),utilityNetworkMissingLayers:!(128&~s),preserveTrueCurves:!(256&~s)}}}let $=class extends(n(o(d))){constructor(e){super(e),this.url=null,this.sourceJSON=null,this.userHasFullEditingPrivileges=!1,this.userHasUpdateItemPrivileges=!1,this.userTypeExtensions=[],this.layerInfos=null,this.tableInfos=null,this.capabilities=null,this._layerTableIndex=new Map}read(e,t){this.sourceJSON=e,super.read(e,t)}get utilityNetworkUrl(){if(this.sourceJSON)for(const e of this.sourceJSON.layers)if("Utility Network Layer"===e.type)return`${this.url}/${e.id}`;return null}get versionManagementServiceUrl(){return this.sourceJSON?.hasBranchVersionedData&&!C(this.url)?this.url.replace(/\/FeatureServer/i,"/VersionManagementServer"):null}readLayerInfos(e,t){return(t.layers||[]).map(e=>{const{type:t,geometryType:s}=e;return{...N(this.url,e),type:t||"Feature Layer",geometryType:s}})}readTableInfos(e,t){return(t.tables||[]).map(e=>N(this.url,e))}readCapabilities(e,t){return Q(t)}get effectiveCapabilities(){const e=this.capabilities;if(!e)return null;const t=l(e),{operations:s}=t;return this.userHasUpdateItemPrivileges?(s.supportsAdd=s.supportsDelete=s.supportsEditing=s.supportsQuery=s.supportsUpdate=!0,t):(this.userHasFullEditingPrivileges&&s.supportsEditing&&(s.supportsAdd=s.supportsDelete=s.supportsUpdate=!0),t)}get loaded(){return super.loaded}load(e){return this.addResolvingPromise(this._fetchService(this.url,e).then(()=>this._setUserPrivileges(e))),Promise.resolve(this)}async fetchAllLayersAndTables(e){return await this.load(e),this._fetchLayersAndTablesPromise||=this._fetchLayersAndTables(this.url),u(e),this._fetchLayersAndTablesPromise}async applyEdits(e,t){let s=null;try{const{results:r,edits:i,editedFeatures:a}=await this._internalApplyEdits(e,t),o=e=>e.filter(e=>!e.error).map(l);let n=0;return r.map(e=>{s=F(this.url,e.id,t?.gdbVersion,!0);const r={edits:i[n],addedFeatures:o(e.addFeatureResults),updatedFeatures:o(e.updateFeatureResults),deletedFeatures:o(e.deleteFeatureResults),addedAttachments:o(e.addAttachmentResults),updatedAttachments:o(e.updateAttachmentResults),deletedAttachments:o(e.deleteAttachmentResults),exceededTransferLimit:!1,historicMoment:e.editMoment?new Date(e.editMoment):null};n+=1,a.length>0&&(r.editedFeatures=a),s.resolve(r),s=null}),r}catch(r){throw s&&s.reject(r),r}}async _setUserPrivileges(e){if(t.userPrivilegesApplied)try{const{features:{fullEdit:t},content:{updateItem:s}}=await this._fetchUserPrivileges(this.sourceJSON.serviceItemId,e);this._set("userHasFullEditingPrivileges",t),this._set("userHasUpdateItemPrivileges",s)}catch(s){p(s)}}async _fetchUserPrivileges(e,t){const r=!0,i=!1,a=!1;if(!e)return{features:{edit:r,fullEdit:i},content:{updateItem:a}};let o,n,l;try{o=await A(this.url,t)}catch(d){p(d)}try{const e=null!=t?t.signal:null;n=await(s?.getCredential(`${o}/sharing`,{prompt:!1,signal:e}))}catch(d){p(d)}if(!n)return{features:{edit:r,fullEdit:i},content:{updateItem:a}};try{if(l=new T({id:e,portal:{url:o}}),await l.load(t),l.portal.user)return U(l)}catch(d){p(d)}return{features:{edit:r,fullEdit:i},content:{updateItem:a}}}async _internalApplyEdits(e,t){await R(this.url);const s=t?.globalIdUsed??!1,a=h.fromJSON(this.sourceJSON.spatialReference),{edits:o,options:n}=await this._processApplyEditsParams(e,t),l=await Promise.all(o.map(async e=>{const t=e.addFeatures?.map(e=>f({spatialReference:a},e,null))??[],r=(await Promise.all(t)).filter(i),o=r.length>0?r:null,n=e.updateFeatures?.map(e=>f({spatialReference:a},e,null))??[],l=(await Promise.all(n)).filter(i),d=l.length>0?l:null,u=b(e.identifierFields,e.deleteFeatures,s),p=u.length>0?u:null;G(o,d,a);const c=await g(e.identifierFields,e);let m=null;if(c){m={adds:c.adds.length>0?c.adds:void 0,updates:c.updates.length>0?c.updates:void 0,deletes:c.deletes.length>0?c.deletes:void 0}}const y={};return e.deleteAssociations&&(y.deleteAssociations=e.deleteAssociations),e.combineGroupedObjects&&(y.combineGroupedObjects=e.combineGroupedObjects),e.divideGroupedObjects&&(y.divideGroupedObjects=e.divideGroupedObjects),{id:e.id,adds:o,updates:d,deletes:p,attachments:m,...y}})),d={gdbVersion:n?.gdbVersion,rollbackOnFailure:!0,useGlobalIds:s,returnEditMoment:!0,honorSequenceOfEdits:n?.honorSequenceOfEdits,usePreviousEditMoment:n?.usePreviousEditMoment,returnServiceEditsInSourceSR:!1,returnServiceEditsOption:"originalAndCurrentFeatures",async:!1};await x(this.url,t?.gdbVersion,!0);const u=L(this.url,t?.gdbVersion||null);d.edits=JSON.stringify(l);const p=D(this.url),c=P(p.query,{query:V({...d,f:"json"}),method:"post"});let m;u&&(c.authMode="immediate",c.query.sessionId=M);try{m=await r(this.url+"/applyEdits",c)}catch(y){if(!v(y))throw y;c.authMode="immediate",m=await r(this.url+"/applyEdits",c)}return{...z(m),edits:o}}async _processApplyEditsParams(e,t){const s={...t,usingFeatureServiceEndpoint:!0,usingTelecomOperations:e.some(e=>e.deleteAssociations||e.combineGroupedObjects||e.divideGroupedObjects)};return{edits:await Promise.all(e.map(async e=>{const t=this.effectiveCapabilities,r=e&&(e.addFeatures||e.updateFeatures||e.deleteFeatures),i=e&&(e.addAttachments||e.updateAttachments||e.deleteAttachments);if(E(e,t,s,!!r,!!i,"feature-service"),!t.data.isDataVersioned&&s?.gdbVersion)throw new a("feature-service:invalid-parameter","'gdbVersion' is applicable only if the layer supports versioned data. See: 'capabilities.data.isDataVersioned'");const o=I(e,t,"feature-service"),n={};if(e.deleteAssociations&&(n.deleteAssociations=e.deleteAssociations),e.combineGroupedObjects&&(n.combineGroupedObjects=e.combineGroupedObjects),e.divideGroupedObjects&&(n.divideGroupedObjects=e.divideGroupedObjects),!e.identifierFields){await this.fetchAllLayersAndTables();const t=this._layerTableIndex.get(e.id);t&&(e.identifierFields={globalIdField:t.globalIdField,objectIdField:t.objectIdField})}const l=await O(o);return{id:e.id,...l,...n,identifierFields:e.identifierFields}})),options:s}}async _fetchService(e,t){if(this.sourceJSON)return void this.read(this.sourceJSON,{url:D(e)});const s=await r(e,{responseType:"json",query:{f:"json"},...t});this.read(s.data,{url:D(e)})}async _fetchLayersAndTables(e){const t=`${e}/layers`,s=await r(t,{responseType:"json",query:{f:"json"}});return{layers:s.data.layers.map(e=>{const{type:t,geometryType:s}=e,r=N(this.url,e),i=w(e,r.url);return this._layerTableIndex.set(e.id,e),{...r,type:t||"Feature Layer",geometryType:s,capabilities:i}}),tables:s.data.tables.map(e=>{const t=N(this.url,e),s=w(e,t.url);return this._layerTableIndex.set(e.id,e),{...t,capabilities:s}})}}};function z(e){const t=e.data,s=[];return{results:t.map(e=>{const t={addResults:e.addResults??[],updateResults:e.updateResults??[],deleteResults:e.deleteResults??[],attachments:e.attachments,editMoment:e.editMoment},r=j(t),i=e.editedFeatures,a=i?.spatialReference?new h({wkid:i?.spatialReference.wkid,wkt:i?.spatialReference.wkt,latestWkid:i?.spatialReference.latestWkid,latestVcsWkid:i?.spatialReference.latestVcsWkid,vcsWkid:i?.spatialReference.vcsWkid}):null,o=i?S(i,a):null;o&&s.push({layerId:e.id,editedFeatures:o});const n={};return e.divideGroupedObjectResults&&(n.divideGroupedObjectResults=e.divideGroupedObjectResults),e.combineGroupedObjectResults&&(n.combineGroupedObjectResults=e.combineGroupedObjectResults),{id:e.id,editedFeatures:o,...r,...n}}),editedFeatures:s}}e([c()],$.prototype,"url",void 0),e([c()],$.prototype,"sourceJSON",void 0),e([c()],$.prototype,"userHasFullEditingPrivileges",void 0),e([c()],$.prototype,"userHasUpdateItemPrivileges",void 0),e([c({readOnly:!0})],$.prototype,"utilityNetworkUrl",null),e([c({readOnly:!0})],$.prototype,"versionManagementServiceUrl",null),e([c()],$.prototype,"userTypeExtensions",void 0),e([c({json:{read:{source:["layers"]}}})],$.prototype,"layerInfos",void 0),e([m("layerInfos",["layers"])],$.prototype,"readLayerInfos",null),e([c({json:{read:{source:["tables"]}}})],$.prototype,"tableInfos",void 0),e([m("tableInfos",["tables"])],$.prototype,"readTableInfos",null),e([c({readOnly:!0,json:{read:{source:["hasVersionedData","hasSharedTemplates","hasBranchVersionedData","capabilities","supportsQueryDataElements","supportsQueryDomains","supportsQueryContingentValues","maxRecordCountFactor","maxRecordCount","advancedEditingCapabilities","supportsApplyEditsWithGlobalIds","syncCapabilities","datesInUnknownTimezone"]}}})],$.prototype,"capabilities",void 0),e([m("capabilities",["hasVersionedData","hasSharedTemplates","hasBranchVersionedData","capabilities","supportsQueryDataElements","supportsQueryDomains","supportsQueryContingentValues","maxRecordCountFactor","maxRecordCount","advancedEditingCapabilities","supportsApplyEditsWithGlobalIds","syncCapabilities","datesInUnknownTimezone"])],$.prototype,"readCapabilities",null),e([c({readOnly:!0})],$.prototype,"effectiveCapabilities",null),$=e([y("esri.rest.featureService.FeatureService")],$);const Z=$;export{Z as default};
|