@vertigis/arcgis-extensions 53.5.1 → 53.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/data/FeatureSet.js +1 -1
  2. package/data/Schema.d.ts +10 -0
  3. package/data/Schema.js +1 -1
  4. package/data/convert.js +1 -1
  5. package/docs/html/assets/search.js +1 -1
  6. package/docs/html/classes/data_Schema.Schema.html +7 -2
  7. package/docs/html/classes/data__TableExtension.TableSchema.html +8 -3
  8. package/docs/html/classes/mapping_BuildingComponentSublayerExtension.BuildingComponentSublayerSchema.html +8 -3
  9. package/docs/html/classes/mapping_BuildingGroupSublayerExtension.BuildingGroupSublayerSchema.html +8 -3
  10. package/docs/html/classes/mapping_BuildingSceneLayerExtension.BuildingSceneLayerReadOnlySchema.html +7 -2
  11. package/docs/html/classes/mapping_BuildingSublayerExtension.BuildingSublayerSchema.html +8 -3
  12. package/docs/html/classes/mapping_FeatureLayerExtensionBase.FeatureLayerReadOnlySchema.html +7 -2
  13. package/docs/html/classes/mapping_FeatureLayerExtensionBase.FeatureLayerSchema.html +7 -2
  14. package/docs/html/classes/mapping_MapNotesSublayerExtension.MapNotesSublayerExtensionSchema.html +8 -3
  15. package/docs/html/classes/mapping_RouteLayerExtension.RouteLayerExtensionSchema.html +7 -2
  16. package/docs/html/classes/mapping_StreamLayerExtension.StreamLayerSchema.html +7 -2
  17. package/docs/html/classes/mapping_SubtypeGroupLayerExtension.SubtypeGroupLayerSchema.html +7 -2
  18. package/docs/html/classes/mapping_SubtypeSublayerExtension.SubtypeSublayerSchema.html +8 -3
  19. package/docs/html/classes/mapping__LayerExtension.LayerExtensionReadOnlySchema.html +7 -2
  20. package/docs/html/classes/mapping__LayerExtension.LayerExtensionSchema.html +7 -2
  21. package/docs/html/classes/mapping__SublayerExtension.SublayerSchema.html +8 -3
  22. package/docs/html/variables/version.version.html +1 -1
  23. package/mapping/ArcGISSublayerExtension.js +1 -1
  24. package/package.json +1 -1
  25. package/version.d.ts +1 -1
  26. package/version.js +1 -1
@@ -1 +1 @@
1
- var e;import{__decorate as t}from"tslib";import r from"@arcgis/core/core/Collection";import{Evented as s}from"@arcgis/core/core/Evented.js";import{generateId as i}from"../Entity.js";import{isFeature as a,ItemType as h}from"../ItemType.js";import{assignProperties as o,assignPropertiesAsync as n,filterJSONProperties as u,getDefaults as d,getSerializableProperties as c,serializable as m}from"../support/Serializable.js";import{notifyChange as g,observable as l,watchEach as y}from"../support/observableUtils.js";import{ObservableMap as p}from"../utilities/ObservableMap.js";import{groupBy as _}from"../utilities/array.js";import{toArray as f,from as S,empty as v}from"../utilities/asyncIterable.js";import{compare as b,find as F}from"../utilities/iterable.js";import{getLogger as z}from"../utilities/log.js";import{Feature as j}from"./Feature.js";import{FeatureSettings as E}from"./FeatureSettings.js";import{Schema as P}from"./Schema.js";const k=z("feature-set");let C=e=class extends(l(s)){[Symbol.toStringTag];id;title;get size(){return this._features.size}get source(){return this._source}set source(e){this._source===e||null==this._source&&null==e||(this._source&&this.settings.parent===this._source.featureSettings&&(this.settings.parent=void 0),this._source&&this.schema.parent===this._source.schema&&(this.schema.parent=void 0),this._source=e,this.settings.parent||(this.settings.parent=e?e.featureSettings:void 0),this.schema.parent||(this.schema.parent=e?e.schema:void 0))}settings=new E;schema=new P;get itemType(){return h.FEATURE_SET}_source;_rehydratingFeatureCount=0;_rehydratingFeatures=new r;_features=new p;constructor(e){super(),this.schema._featureSettings=this.settings,this.id=e?.id??i(),y(this._rehydratingFeatures,"[]._hydrationStatus",(()=>{if(this._rehydratingFeatureCount--,!this._rehydratingFeatureCount){const e=this._rehydratingFeatures.toArray();this.addMany(e),this.emit("feature-hydration-complete",e)}})),this.on("dehydrated-features-added",(async e=>{this._rehydratingFeatures.addMany(e);const t=_(e,(e=>e.source)),r=_(await f(S([...t.entries()].map((([e,t])=>{let r;try{r=e?.getFeatures(t.map((e=>e.primaryKey)).filter((e=>!!e)))??v()}catch(t){r=v(),k.error({error:t,message:`Failed to hydrate features from source '${e?.title??e?.id}`})}return r})))),(e=>e.source));[...t.entries()].forEach((([e,t])=>{const s=r.get(e);t.forEach((e=>{const t=s?.find((t=>t.primaryKey===e.primaryKey));t&&(e.geometry=t.geometry,[...t.attributes.entries()].forEach((([t,r])=>{e.attributes.set(t,r)}))),e._hydrationStatus=void 0}))}))})),this.assignProperties(e)}static async fromFeatureStream(t,r){const s=new e(r);for await(const e of t)s.add(e);return s}assignProperties(e){o(this._getSerializableProperties(),this,e)}async assignPropertiesAsync(e){return n(this._getSerializableProperties(),this,e)}async finishAssignProperties(){}has(e){return this._features.has(e._key)}entries(){return[...this._features].map((([e,t])=>[t,t]))[Symbol.iterator]()}keys(){return this._features.values()}values(){return this._features.values()}toJSON(e="all"){return u(this._getSerializableProperties(),this,e)}toItemUri(){return`item://${encodeURIComponent(h.FEATURE_SET)}/${encodeURIComponent(this.id)}`}add(e){return this._add(e)}addMany(e){const t=[],r=[];for(const s of e){const e=this._features.get(s._key);s!==e&&(this._add(s,!1),t.push(s),e&&r.push(e))}return t.length&&(g(this,"size"),this.emit("change",{added:t,removed:r,moved:[],target:this})),this}clear(){const e=Array.from(this.values());this._features.clear(),g(this,"size"),this.emit("change",{added:[],removed:e,moved:[],target:this})}delete(e){return this._delete(e)}deleteMany(e){const t=[];for(const r of e){const e=this._features.get(r._key);this._delete(r,!1)&&t.push(e)}return t.length&&(g(this,"size"),this.emit("change",{added:[],removed:t,moved:[],target:this})),!!t.length}forEach(e,t){this._features.forEach((t=>e(t,t,this)),t)}findById(e){return F(this,(t=>t.id===e))}findByPrimaryKey(e){return F(this,(t=>t.primaryKey===e))}getSerializableProperties(e="all"){return c(this._getSerializableProperties(),e)}getDefaults(){return d(this._getSerializableProperties())}getDefault(e){return this.getDefaults()[e]}[Symbol.iterator](){return this._features.values()[Symbol.iterator]()}_add(e,t=!0){const r=this._features.get(e._key);return r&&r!==e&&this._delete(r,!1),this._features.set(e._key,e),t&&r!==e&&(g(this,"size"),this.emit("change",{added:[e],removed:r?[r]:[],moved:[],target:this})),this.source&&!e.source&&(e.source=this.source),e.schema.parent||(e.schema.parent=this.schema),e.settings.parent||(e.settings.parent=this.settings),this}_delete(e,t=!0){if(!this.has(e))return!1;const r=this._features.get(e._key);return this._features.delete(e._key),t&&(g(this,"size"),this.emit("change",{added:[],removed:[r],moved:[],target:this})),e.schema.parent===this.schema&&(e.schema.parent=void 0),e.settings.parent===this.settings&&(e.settings.parent=void 0),!0}_getSerializableProperties(){return{id:["project"],features:{serializeModes:["project"],serialize:()=>[...this],deserialize:e=>{const t=[],r=[];b(this._rehydratingFeatures.concat([...this]),e,{onNew:e=>{if(a(e))"dehydrated"===e._hydrationStatus?(e._hydrationStatus="rehydrating",this._rehydratingFeatureCount++,t.push(e)):"rehydrating"===e._hydrationStatus?(this._rehydratingFeatureCount++,this._rehydratingFeatures.push(e)):(r.push(e),this.add(e));else{const t=new j(e);r.push(t),this.add(t)}},onMatch:(e,r)=>{a(r)?"dehydrated"===e._hydrationStatus?(e._hydrationStatus="rehydrating",this._rehydratingFeatureCount++,t.push(e)):e!==r&&this.add(r):e.assignProperties(r)},onMissing:e=>{this.delete(e)},equals:(e,t)=>a(t)?e._key===t._key:e.id===t.id}),t.length?this.emit("dehydrated-features-added",t):this._rehydratingFeatureCount||this.emit("feature-hydration-complete",r)}},title:["project"],source:[],schema:[],settings:[]}}};C=e=t([m],C);export{C as FeatureSet};
1
+ var e;import{__decorate as t}from"tslib";import r from"@arcgis/core/core/Collection";import{Evented as s}from"@arcgis/core/core/Evented.js";import{generateId as i}from"../Entity.js";import{isFeature as a,ItemType as h}from"../ItemType.js";import{assignProperties as o,assignPropertiesAsync as n,filterJSONProperties as u,getDefaults as d,getSerializableProperties as c,serializable as m}from"../support/Serializable.js";import{notifyChange as g,observable as l,watchEach as p}from"../support/observableUtils.js";import{ObservableMap as y}from"../utilities/ObservableMap.js";import{groupBy as _}from"../utilities/array.js";import{toArray as f,from as S,empty as v}from"../utilities/asyncIterable.js";import{compare as b,find as F}from"../utilities/iterable.js";import{getLogger as z}from"../utilities/log.js";import{Feature as j}from"./Feature.js";import{FeatureSettings as E}from"./FeatureSettings.js";import{Schema as P}from"./Schema.js";const C=z("feature-set");let k=e=class extends(l(s)){[Symbol.toStringTag];id;title;get size(){return this._features.size}get source(){return this._source}set source(e){this._source===e||null==this._source&&null==e||(this._source&&this.settings.parent===this._source.featureSettings&&(this.settings.parent=void 0),this._source&&this.schema.parent===this._source.schema&&(this.schema.parent=void 0),this._source=e,this.settings.parent||(this.settings.parent=e?e.featureSettings:void 0),this.schema.parent||(this.schema.parent=e?e.schema:void 0))}settings=new E;schema=new P;get itemType(){return h.FEATURE_SET}_source;_rehydratingFeatureCount=0;_rehydratingFeatures=new r;_features=new y;constructor(e){super(),this.schema._featureSettings=this.settings,this.id=e?.id??i(),p(this._rehydratingFeatures,"[]._hydrationStatus",(()=>{if(this._rehydratingFeatureCount--,!this._rehydratingFeatureCount){const e=this._rehydratingFeatures.toArray();this.addMany(e),this.emit("feature-hydration-complete",e)}})),this.on("dehydrated-features-added",(async e=>{this._rehydratingFeatures.addMany(e);const t=_(e,(e=>e.source)),r=_(await f(S([...t.entries()].map((([e,t])=>{let r;try{r=e?.getFeatures(t.map((e=>e.primaryKey)).filter((e=>!!e)))??v()}catch(t){r=v(),C.error({error:t,message:`Failed to hydrate features from source '${e?.title??e?.id}`})}return r})))),(e=>e.source));[...t.entries()].forEach((([e,t])=>{const s=r.get(e);t.forEach((e=>{const t=s?.find((t=>t.primaryKey===e.primaryKey));t&&(e.geometry=t.geometry,[...t.attributes.entries()].forEach((([t,r])=>{e.attributes.set(t,r)}))),e._hydrationStatus=void 0}))}))})),this.assignProperties(e)}static async fromFeatureStream(t,r){const s=new e(r);for await(const e of t)s.add(e);return s}assignProperties(e){o(this._getSerializableProperties(),this,e)}async assignPropertiesAsync(e){return n(this._getSerializableProperties(),this,e)}async finishAssignProperties(){}has(e){return this._features.has(e._key)}entries(){return[...this._features].map((([e,t])=>[t,t]))[Symbol.iterator]()}keys(){return this._features.values()}values(){return this._features.values()}toJSON(e="all"){return u(this._getSerializableProperties(),this,e)}toItemUri(){return`item://${encodeURIComponent(h.FEATURE_SET)}/${encodeURIComponent(this.id)}`}add(e){return this._add(e)}addMany(e){const t=[],r=[];for(const s of e){const e=this._features.get(s._key);s!==e&&(this._add(s,!1),t.push(s),e&&r.push(e))}return t.length&&(g(this,"size"),this.emit("change",{added:t,removed:r,moved:[],target:this})),this}clear(){const e=Array.from(this.values());this._features.clear(),g(this,"size"),this.emit("change",{added:[],removed:e,moved:[],target:this})}delete(e){return this._delete(e)}deleteMany(e){const t=[];for(const r of e){const e=this._features.get(r._key);this._delete(r,!1)&&t.push(e)}return t.length&&(g(this,"size"),this.emit("change",{added:[],removed:t,moved:[],target:this})),!!t.length}forEach(e,t){this._features.forEach((t=>e(t,t,this)),t)}findById(e){return F(this,(t=>t.id===e))}findByPrimaryKey(e){return F(this,(t=>t.primaryKey===e))}getSerializableProperties(e="all"){return c(this._getSerializableProperties(),e)}getDefaults(){return d(this._getSerializableProperties())}getDefault(e){return this.getDefaults()[e]}[Symbol.iterator](){return this._features.values()[Symbol.iterator]()}_add(e,t=!0){const r=e._key,s=this._features.get(r);return s&&s!==e&&this._delete(s,!1),this._features.set(r,e),t&&s!==e&&(g(this,"size"),this.emit("change",{added:[e],removed:s?[s]:[],moved:[],target:this})),this.source&&!e.source&&(e.source=this.source),e.schema.parent||(e.schema.parent=this.schema),e.settings.parent||(e.settings.parent=this.settings),this}_delete(e,t=!0){if(!this.has(e))return!1;const r=this._features.get(e._key);return this._features.delete(e._key),t&&(g(this,"size"),this.emit("change",{added:[],removed:[r],moved:[],target:this})),e.schema.parent===this.schema&&(e.schema.parent=void 0),e.settings.parent===this.settings&&(e.settings.parent=void 0),!0}_getSerializableProperties(){return{id:["project"],features:{serializeModes:["project"],serialize:()=>[...this],deserialize:e=>{const t=[],r=[];b(this._rehydratingFeatures.concat([...this]),e,{onNew:e=>{if(a(e))"dehydrated"===e._hydrationStatus?(e._hydrationStatus="rehydrating",this._rehydratingFeatureCount++,t.push(e)):"rehydrating"===e._hydrationStatus?(this._rehydratingFeatureCount++,this._rehydratingFeatures.push(e)):(r.push(e),this.add(e));else{const t=new j(e);r.push(t),this.add(t)}},onMatch:(e,r)=>{a(r)?"dehydrated"===e._hydrationStatus?(e._hydrationStatus="rehydrating",this._rehydratingFeatureCount++,t.push(e)):e!==r&&this.add(r):e.assignProperties(r)},onMissing:e=>{this.delete(e)},equals:(e,t)=>a(t)?e._key===t._key:e.id===t.id}),t.length?this.emit("dehydrated-features-added",t):this._rehydratingFeatureCount||this.emit("feature-hydration-complete",r)}},title:["project"],source:[],schema:[],settings:[]}}};k=e=t([m],k);export{k as FeatureSet};
package/data/Schema.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import PopupTemplate from "@arcgis/core/PopupTemplate";
2
2
  import Collection from "@arcgis/core/core/Collection";
3
+ import type { ResourceHandle } from "@arcgis/core/core/Handles.js";
3
4
  import type SpatialReference from "@arcgis/core/geometry/SpatialReference";
4
5
  import FeatureType from "@arcgis/core/layers/support/FeatureType";
5
6
  import Field from "@arcgis/core/layers/support/Field";
@@ -119,6 +120,15 @@ export declare class Schema extends Settings<SchemaProperties> {
119
120
  * A collection of Field objects describing each field in the schema.
120
121
  */
121
122
  readonly fields: FieldCollection;
123
+ /**
124
+ * A set of watch handles that get cleaned up when the class instance is
125
+ * destroyed.
126
+ */
127
+ protected readonly _watchHandles: ResourceHandle[];
128
+ /**
129
+ * A cache of the primary key field name used to speed up lookup.
130
+ */
131
+ protected _primaryKeyField: string | undefined;
122
132
  /**
123
133
  * The spatial reference of the schema. Can be defined using a well-known ID
124
134
  * (WKID) or well-known text (WKT).
package/data/Schema.js CHANGED
@@ -1 +1 @@
1
- var e;import{__decorate as i}from"tslib";import t from"@arcgis/core/PopupTemplate";import s from"@arcgis/core/core/Collection";import o from"@arcgis/core/layers/support/FeatureType";import l from"@arcgis/core/layers/support/Field";import d from"@arcgis/core/popup/FieldInfo";import{InvalidOperationError as n}from"../InvalidOperationError.js";import{isFieldExtension as r}from"../ItemType.js";import{jsonToGeometryType as a}from"../json/GeometryJson.js";import{InitializableCollectionProxy as h}from"../support/InitializableCollectionProxy.js";import{filterJSONProperties as m,isDefault as f,serializable as p,shouldExcludeDefaults as c}from"../support/Serializable.js";import{Settings as _}from"../support/Settings.js";import{createIHandle as u,notifyChange as g,onWatch as F,watch as y}from"../support/observableUtils.js";import{CaseInsensitiveObservableMap as x}from"../utilities/CaseInsensitiveObservableMap.js";import{CollectionProxy as v}from"../utilities/CollectionProxy.js";import{ReadOnlyCollection as b}from"../utilities/ReadOnlyCollection.js";import S from"../utilities/_ReferenceCountedHandle.js";import{checkArg as T}from"../utilities/checkArg.js";import{compare as z}from"../utilities/collection.js";import{isFeatureType as w,isField as I}from"../utilities/esri.js";import{fieldWithArcadeXRegex as N,fieldWithRelationshipRegex as E,getArcadeExpressionFromField as A}from"../utilities/field.js";import{ERR_TIME_ZONE_INVALID as j,isValidTimeZone as H}from"../utilities/format/date.js";import{objectKeys as C}from"../utilities/object.js";import{caseInsensitiveEquals as R}from"../utilities/string.js";import{_fieldExtensionMap as M,FieldExtension as O}from"./FieldExtension.js";const B=new Map;B.set("objectid","oid"),B.set("oid","oid"),B.set("fid","oid"),B.set("shape","geometry"),B.set("shape__length","double"),B.set("shape_length","double"),B.set("shape__area","double"),B.set("shape_area","double"),B.set("area","double"),B.set("perimeter","double"),B.set("length","double"),B.set("fnode_","double"),B.set("tnode_","double"),B.set("lpoly_","double"),B.set("rpoly_","double"),B.set("cover_","integer"),B.set("cover_id","integer"),B.set("idtic","integer"),B.set("xtic","double"),B.set("ytic","double"),B.set("xmin","double"),B.set("ymin","double"),B.set("xmax","double"),B.set("ymax","double"),B.set("arc_","double"),B.set("subclass_","integer"),B.set("subclass_id","integer"),B.set("routelink","integer"),B.set("arclink","integer"),B.set("f_meas","double"),B.set("t_meas","double"),B.set("f_pos","double"),B.set("t_pos","double"),B.set("f_meas","double"),B.set("globalid","global-id"),B.set("guid","guid");export{N as fieldWithArcadeXRegex,E as fieldWithRelationshipRegex};const P=new WeakMap;let Z=e=class extends _{fieldExtensions;fields;get spatialReference(){return this._getSetting("spatialReference")}set spatialReference(e){this._setSetting("spatialReference",e)}get primaryKeyField(){const e=this._getSetting("primaryKeyField");if(!e){const e=this.fields.filter((e=>"oid"===e.type));if(1===e.length)return e.getItemAt(0).name}return e}set primaryKeyField(e){this._setSetting("primaryKeyField",e)}get displayField(){return this._getSetting("displayField",this.primaryKeyField)}set displayField(e){!this._featureSettings?.popupTemplate||this._featureSettings.popupTemplate.title&&this._featureSettings.popupTemplate.title!==`{${this.displayField}}`||(this._featureSettings.popupTemplate.title=`{${e}}`),this._setSetting("displayField",e)}get geometryType(){return this._getSetting("geometryType")}set geometryType(e){this._setSetting("geometryType",e)}get hasGeometry(){return void 0!==this.geometryType&&null!==this.geometryType}get timeZone(){return this._getSetting("timeZone","UTC")}set timeZone(e){T("timeZone",e).satisfies((e=>H(e)),j(e)),this._setSetting("timeZone",e)}get typeIdField(){return this._getSetting("typeIdField")}set typeIdField(e){this._setSetting("typeIdField",e)}get types(){return this._getCollectionSetting("types")}get _fields(){return this._getCollectionSetting("_fields")}_featureSettings;_alwaysSerializeFieldExtensions;constructor(e){super(e),this.fieldExtensions=new K(this),this.fields=new J(this)}static createFieldInfoFromField(e){let i=!0;const t=e.name.toLowerCase();return("oid"===e.type||"geometry"===e.type||B.has(t)&&B.get(t)===e.type)&&(i=!1),new d({visible:i,fieldName:e.name,format:void 0,label:e.alias,stringFieldOption:void 0,tooltip:void 0,isEditable:e.editable})}destroy(){this.parent=void 0,this.fieldExtensions?.destroy(),this.fields?.destroy(),super.destroy()}findFieldByName(e){return this.fields.findFieldByName(e)}toJSON(e="all"){const i=m(this._getSerializableProperties(),this,e)||{};let t=i.fieldExtensions;this.parent&&(t=t?.filter((e=>{const i=this.parent;return!i?.fieldExtensions?.some((i=>i.id===e.id))})));const{fields:s}=i;if(i)for(const e of C(i))this.isModified(e)||delete i[e];if(s&&(i.fields=s),t?.length&&(i.fieldExtensions=t),!c(e)||!f(i))return i}createPopupTemplate(){const e=this.createAllFieldInfos();return new t({fieldInfos:e,content:[{type:"fields"},{type:"attachments"}]})}createAllFieldInfos(){return this.fields.toArray().filter((e=>!!e.name)).map((i=>e.createFieldInfoFromField(i)))}_getSerializableProperties(){return{geometryType:{serialize:!1,deserialize:e=>{this.geometryType=e?a(e):void 0}},spatialReference:{serialize:!1},primaryKeyField:{serialize:!1},displayField:{serialize:!1},typeIdField:{serialize:!1},fields:{serializeModes:["initial","project"],serialize:()=>this.isModified("_fields")?this.fields.toArray().map((e=>e.toJSON())):void 0,deserialize:e=>{if(!e)return;const i=e.map((e=>I(e)?e:l.fromJSON(e)));z(this.fields,i,{onNew:(e,i)=>{this.fields.add(e,i)},onMatch:(e,i,t,s)=>{e!==i&&(e.alias=i.alias,e.editable=i.editable,e.length=i.length,e.nullable=i.nullable,e.type=i.type),t!==s&&this.fields.reorder(e,s)},onMissing:e=>{this.fields.remove(e)},equals:(e,i)=>R(e.name,i.name)})}},fieldExtensions:{serializeModes:["initial"],serialize:e=>this.fieldExtensions.toArray().map((i=>i.toJSON(e))).filter((e=>this._alwaysSerializeFieldExtensions||!(e&&2===Object.keys(e).length&&e.id&&e.field))),deserialize:e=>{e&&z(this.fieldExtensions,e,{onNew:(e,i)=>{this.fieldExtensions.add(r(e)?e:new O(e),i)},onMatch:(e,i,t,s)=>{r(i)||e.assignProperties(i),t!==s&&this.fieldExtensions.reorder(e,s)},onMissing:e=>{this._alwaysSerializeFieldExtensions&&this.fieldExtensions.remove(e)},equals:(e,i)=>r(i)?i===e:!(!i?.field||!O.matchesRef(e,i.field))||e.id===i.id})}},types:{serialize:!1,deserialize:e=>{if(!e)return;const i=e.map((e=>w(e)||!e?e:o.fromJSON(e)));z(this.types,i,{onNew:(e,i)=>{this.types.add(e,i)},onMatch:(e,i,t,s)=>{e!==i&&(e.name=i.name,e.templates=i.templates?[...i.templates]:[],e.domains=i.domains),t!==s&&this.types.reorder(e,s)},onMissing:e=>{this.types.remove(e)},equals:(e,i)=>e.id===i.id})}},timeZone:{serialize:!1,deserialize:e=>{e&&(this.timeZone=e)}}}}};Z=e=i([p],Z);export{Z as Schema};class J extends v{_schema;_fieldNameToField=new x;_expressionFields=new s;_expressionFieldsReadOnly=new b(this._expressionFields);get _expressionFieldsLength(){return this.expressionFields.length}get expressionFields(){return this._expressionFieldsReadOnly}get _popupTemplate(){return this._schema._featureSettings?this._schema._featureSettings.popupTemplate:void 0}constructor(e){super(new s),this._schema=e,this._handles.add(F(this,"length",(()=>y(this._schema,"_fields.length",(()=>g(this,"length")),{sync:!0})))),this._handles.add(y(this._schema,"_fields",(e=>{if(this._handles.remove("schema-field-collection-schema-fields"),null!=e){this._handles.add([e.on("after-add",(i=>{this._collection.add(i.item,e.indexOf(i.item)),this._fieldNameToField.set(i.item.name,i.item)})),e.on("after-remove",(e=>{this._collection.remove(e.item),this._fieldNameToField.delete(e.item.name)}))],"schema-field-collection-schema-fields");for(const i of this._collection)e.includes(i)||(this._collection.remove(i),this._fieldNameToField.delete(i.name));for(const i of e)this._collection.includes(i)||(this._collection.add(i),this._fieldNameToField.set(i.name,i))}else for(const e of this._collection.filter((e=>!this._expressionFields.includes(e))))this._collection.remove(e),this._fieldNameToField.delete(e.name)}),{sync:!0,initial:!0})),this._generateExpressionFields(),this._handles.add([y(this._schema,"_featureSettings.popupTemplate.fieldInfos",(()=>{this._generateExpressionFields()}),{sync:!0}),y(this._schema,"_featureSettings.popupTemplate.expressionInfos",(()=>{this._generateExpressionFields()}),{sync:!0})])}clone(){return new J(this._schema)}add(e,i){T("field",e).isNotMissing();const t=A(e.name);if(t){if(!this._popupTemplate)throw new n("Cannot create a field that references an arcade expression without a feature source and popup template.");const i=this._popupTemplate.expressionInfos.find((e=>R(e.name,t)));if(!i)throw new n("Cannot create a field that references a non-existent arcade expression.");this._popupTemplate.fieldInfos||(this._popupTemplate.fieldInfos=[]);let s=this._popupTemplate.fieldInfos.find((i=>R(i.fieldName,e.name)));s||(s=new d({fieldName:e.name,label:i.title}),this._popupTemplate.fieldInfos.push(s));const o=P.get(s);P.set(s,e),null!=this._expressionFields&&(this._expressionFields.remove(o),this._expressionFields.includes(e)||(this._expressionFields.add(e),this._collection.add(e),this._fieldNameToField.set(e.name,e))),g(this,"_expressionFieldsLength")}else this._schema._fields.add(e,i);return this}destroy(){this._fieldNameToField.clear(),this._expressionFields.removeAll(),this._collection.removeAll(),super.destroy()}removeAt(e){T("index",e).isNotMissing();const i=this.getItemAt(e);if(!i)return;if(A(i.name)){const e=this._popupTemplate.fieldInfos.findIndex((e=>R(e.fieldName,i.name)));this._popupTemplate.fieldInfos.splice(e,1),this._expressionFields.remove(i),this._collection.remove(i),this._fieldNameToField.delete(i.name),g(this,"_expressionFieldsLength")}else this._schema._fields.remove(i);return i}reorder(e,i){if(e&&this._schema._fields.includes(e))return this._schema._fields.reorder(e,i),this._collection.reorder(e,i),e}sort(e){return this._schema._fields.sort(e),this._collection.sort(((i,t)=>this._expressionFields.includes(i)&&this._expressionFields.includes(t)?0:this._expressionFields.includes(i)?1:this._expressionFields.includes(t)?-1:e(i,t))),this}findFieldByName(e){return this._fieldNameToField.get(e)}_generateExpressionFields(){if(!this._popupTemplate?.fieldInfos||!this._popupTemplate?.expressionInfos){for(const e of this._expressionFields)this._collection.remove(e),this._fieldNameToField.delete(e.name);return void this._expressionFields.removeAll()}const e=this._expressionFields.slice();for(const i of this._popupTemplate.fieldInfos){const t=A(i.fieldName);if(null==t)continue;const s=this._popupTemplate.expressionInfos.find((e=>R(e.name,t)));if(null==s)continue;let o=P.get(i);null==o&&(o=new l({name:i.fieldName,alias:i.label||s.title||i.fieldName,type:"number"===s.returnType?"double":"string",editable:!1})),this._expressionFields.includes(o)?e.remove(o):(P.set(i,o),this._expressionFields.add(o),this._collection.add(o),this._fieldNameToField.set(o.name,o),e.remove(o))}for(const i of e)this._expressionFields.remove(i),this._collection.remove(i),this._fieldNameToField.delete(i.name)}}class K extends h{get _collection(){return this._schema.fields.map((e=>this._forField(e))).concat(Array.from(this._uninitializedFieldExtensions))}_schema;_uninitializedFieldExtensions=new Set;_onChangeSchemaFieldsHandle=new S((()=>this._schema.fields.on("change",(e=>{const i={added:(e.added||[]).map((e=>this._forField(e))),moved:(e.moved||[]).map((e=>this._forField(e))),removed:(e.removed||[]).map((e=>this._forField(e))),target:this};this.emit("change",i)}))));_onBeforeAddSchemaFieldsHandle=new S((()=>this._schema.fields.on("before-add",(e=>{this.emit("before-add",{...e,item:this._forField(e.item)})}))));_onBeforeRemoveSchemaFieldsHandle=new S((()=>this._schema.fields.on("before-remove",(e=>{this.emit("before-remove",{...e,item:this._forField(e.item)})}))));_onBeforeChangesSchemaFieldsHandle=new S((()=>this._schema.fields.on("before-changes",(e=>{this.emit("before-changes",{...e,item:this._forField(e.item)})}))));_onAfterAddSchemaFieldsHandle=new S((()=>this._schema.fields.on("after-add",(e=>{this.emit("after-add",{...e,item:this._forField(e.item)})}))));_onAfterRemoveSchemaFieldsHandle=new S((()=>this._schema.fields.on("after-remove",(e=>{this.emit("after-remove",{...e,item:this._forField(e.item)})}))));_onAfterChangesSchemaFieldsHandle=new S((()=>this._schema.fields.on("after-changes",(e=>{this.emit("after-changes",{...e,target:this})}))));constructor(e){super(),this._schema=e,this._handles.add(F(this,"length",(()=>y(this._schema.fields,"length",(()=>g(this,"length")),{sync:!0}))))}async destroy(){this._onChangeSchemaFieldsHandle.destroy(),this._onBeforeAddSchemaFieldsHandle.destroy(),this._onBeforeRemoveSchemaFieldsHandle.destroy(),this._onBeforeChangesSchemaFieldsHandle.destroy(),this._onAfterAddSchemaFieldsHandle.destroy(),this._onAfterRemoveSchemaFieldsHandle.destroy(),this._onAfterChangesSchemaFieldsHandle.destroy();const e=[];for(const i of this._schema.fields){const t=M.get(i);t&&t.schema===this._schema&&(M.delete(i),this._onRemoved(t),e.push(t.destroy()))}this._uninitializedFieldExtensions.forEach((i=>{this._onRemoved(i),e.push(i.destroy())})),this._uninitializedFieldExtensions.clear(),await Promise.all(e),super.destroy()}forField(e){if(T("field",e).isNotMissing(),this._schema.fields.includes(e))return this._forField(e)}add(e,i){if(T("fieldX",e).isNotMissing(),e.schema&&e.schema.fieldExtensions.remove(e),e._setSchema(this._schema),e.field){const t=M.get(e.field);if(M.set(e.field,e),t&&t!==e&&this._onRemoved(t),this._schema.fields.includes(e.field))if(void 0===i){const i={added:[e],moved:[],removed:t?[t]:[],target:this};this.emit("change",i),this.emit("after-add",{item:e}),this.emit("after-changes",{})}else this._schema.fields.reorder(e.field,i);else this._schema.fields.add(e.field,i)}else{this._uninitializedFieldExtensions.add(e);const i={added:[e],moved:[],removed:[],target:this};this.emit("change",i),this.emit("after-add",{item:e}),this.emit("after-changes",{})}return this._onAdded(e),this}removeAt(e){const i=this.getItemAt(e);if(void 0!==i){if(this._uninitializedFieldExtensions.has(i)){this._uninitializedFieldExtensions.delete(i);const e={added:[],moved:[],removed:[i],target:this};this.emit("change",e),this.emit("after-remove",{item:i}),this.emit("after-changes",{})}else this._schema.fields.remove(i.field);return this._onRemoved(i),i}}reorder(e,i){if(e&&this._schema.fields.includes(e.field))return this._schema.fields.reorder(e.field,i),e}sort(e){return this._schema.fields.sort(((i,t)=>e(this._forField(i),this._forField(t)))),this}on(e,i){const t=[];return"change"===e?t.push(this._onChangeSchemaFieldsHandle.add()):"before-add"===e?t.push(this._onBeforeAddSchemaFieldsHandle.add()):"before-remove"===e?t.push(this._onBeforeRemoveSchemaFieldsHandle.add()):"before-changes"===e?t.push(this._onBeforeChangesSchemaFieldsHandle.add()):"after-add"===e?t.push(this._onAfterAddSchemaFieldsHandle.add()):"after-remove"===e?t.push(this._onAfterRemoveSchemaFieldsHandle.add()):"after-changes"===e&&t.push(this._onAfterChangesSchemaFieldsHandle.add()),t.push(super.on(e,i)),u(t)}_itemIsInitialized(e){return super._itemIsInitialized(e)&&!!e.field}_onAdded(e){}_onRemoved(e){e.schema===this._schema&&e._setSchema(void 0)}_forField(e){if(this._uninitializedFieldExtensions.size)for(const e of this._uninitializedFieldExtensions)e._resolveField(),e.field&&(M.set(e.field,e),this._uninitializedFieldExtensions.delete(e));if(!M.has(e)){const i=new O({field:e});M.set(e,i),i._setSchema(this._schema),this._onAdded(i),i.initialize()}return M.get(e)}}
1
+ var e;import{__decorate as i}from"tslib";import t from"@arcgis/core/PopupTemplate";import s from"@arcgis/core/core/Collection";import o from"@arcgis/core/layers/support/FeatureType";import l from"@arcgis/core/layers/support/Field";import d from"@arcgis/core/popup/FieldInfo";import{InvalidOperationError as n}from"../InvalidOperationError.js";import{isFieldExtension as r}from"../ItemType.js";import{jsonToGeometryType as a}from"../json/GeometryJson.js";import{InitializableCollectionProxy as h}from"../support/InitializableCollectionProxy.js";import{filterJSONProperties as m,isDefault as f,serializable as p,shouldExcludeDefaults as c}from"../support/Serializable.js";import{Settings as _}from"../support/Settings.js";import{createIHandle as u,notifyChange as g,onWatch as F,watch as y}from"../support/observableUtils.js";import{CaseInsensitiveObservableMap as x}from"../utilities/CaseInsensitiveObservableMap.js";import{CollectionProxy as v}from"../utilities/CollectionProxy.js";import{ReadOnlyCollection as b}from"../utilities/ReadOnlyCollection.js";import S from"../utilities/_ReferenceCountedHandle.js";import{checkArg as T}from"../utilities/checkArg.js";import{compare as w}from"../utilities/collection.js";import{isFeatureType as z,isField as I}from"../utilities/esri.js";import{fieldWithArcadeXRegex as N,fieldWithRelationshipRegex as E,getArcadeExpressionFromField as A}from"../utilities/field.js";import{ERR_TIME_ZONE_INVALID as j,isValidTimeZone as H}from"../utilities/format/date.js";import{objectKeys as C}from"../utilities/object.js";import{caseInsensitiveEquals as R}from"../utilities/string.js";import{_fieldExtensionMap as M,FieldExtension as K}from"./FieldExtension.js";const O=new Map;O.set("objectid","oid"),O.set("oid","oid"),O.set("fid","oid"),O.set("shape","geometry"),O.set("shape__length","double"),O.set("shape_length","double"),O.set("shape__area","double"),O.set("shape_area","double"),O.set("area","double"),O.set("perimeter","double"),O.set("length","double"),O.set("fnode_","double"),O.set("tnode_","double"),O.set("lpoly_","double"),O.set("rpoly_","double"),O.set("cover_","integer"),O.set("cover_id","integer"),O.set("idtic","integer"),O.set("xtic","double"),O.set("ytic","double"),O.set("xmin","double"),O.set("ymin","double"),O.set("xmax","double"),O.set("ymax","double"),O.set("arc_","double"),O.set("subclass_","integer"),O.set("subclass_id","integer"),O.set("routelink","integer"),O.set("arclink","integer"),O.set("f_meas","double"),O.set("t_meas","double"),O.set("f_pos","double"),O.set("t_pos","double"),O.set("f_meas","double"),O.set("globalid","global-id"),O.set("guid","guid");export{N as fieldWithArcadeXRegex,E as fieldWithRelationshipRegex};const B=new WeakMap;let P=e=class extends _{fieldExtensions;fields;_featureSettings;_alwaysSerializeFieldExtensions;_watchHandles=[];_primaryKeyField;get spatialReference(){return this._getSetting("spatialReference")}set spatialReference(e){this._setSetting("spatialReference",e)}get primaryKeyField(){if(!this._primaryKeyField){const e=this._getSetting("primaryKeyField");if(e)this._primaryKeyField=e;else{const e=this.fields.filter((e=>"oid"===e.type));1===e.length&&(this._primaryKeyField=e.getItemAt(0).name)}}return this._primaryKeyField}set primaryKeyField(e){this._primaryKeyField=e,this._setSetting("primaryKeyField",e)}get displayField(){return this._getSetting("displayField",this.primaryKeyField)}set displayField(e){!this._featureSettings?.popupTemplate||this._featureSettings.popupTemplate.title&&this._featureSettings.popupTemplate.title!==`{${this.displayField}}`||(this._featureSettings.popupTemplate.title=`{${e}}`),this._setSetting("displayField",e)}get geometryType(){return this._getSetting("geometryType")}set geometryType(e){this._setSetting("geometryType",e)}get hasGeometry(){return void 0!==this.geometryType&&null!==this.geometryType}get timeZone(){return this._getSetting("timeZone","UTC")}set timeZone(e){T("timeZone",e).satisfies((e=>H(e)),j(e)),this._setSetting("timeZone",e)}get typeIdField(){return this._getSetting("typeIdField")}set typeIdField(e){this._setSetting("typeIdField",e)}get types(){return this._getCollectionSetting("types")}get _fields(){return this._getCollectionSetting("_fields")}constructor(e){super(e),this.fieldExtensions=new J(this),this.fields=new Z(this),this._primaryKeyField=void 0,this._handles.add(this.fields.on("before-changes",(()=>{this._primaryKeyField=void 0})))}static createFieldInfoFromField(e){let i=!0;const t=e.name.toLowerCase();return("oid"===e.type||"geometry"===e.type||O.has(t)&&O.get(t)===e.type)&&(i=!1),new d({visible:i,fieldName:e.name,format:void 0,label:e.alias,stringFieldOption:void 0,tooltip:void 0,isEditable:e.editable})}destroy(){this.parent=void 0,this.fieldExtensions?.destroy(),this.fields?.destroy(),super.destroy()}findFieldByName(e){return this.fields.findFieldByName(e)}toJSON(e="all"){const i=m(this._getSerializableProperties(),this,e)||{};let t=i.fieldExtensions;this.parent&&(t=t?.filter((e=>{const i=this.parent;return!i?.fieldExtensions?.some((i=>i.id===e.id))})));const{fields:s}=i;if(i)for(const e of C(i))this.isModified(e)||delete i[e];if(s&&(i.fields=s),t?.length&&(i.fieldExtensions=t),!c(e)||!f(i))return i}createPopupTemplate(){const e=this.createAllFieldInfos();return new t({fieldInfos:e,content:[{type:"fields"},{type:"attachments"}]})}createAllFieldInfos(){return this.fields.toArray().filter((e=>!!e.name)).map((i=>e.createFieldInfoFromField(i)))}_getSerializableProperties(){return{geometryType:{serialize:!1,deserialize:e=>{this.geometryType=e?a(e):void 0}},spatialReference:{serialize:!1},primaryKeyField:{serialize:!1},displayField:{serialize:!1},typeIdField:{serialize:!1},fields:{serializeModes:["initial","project"],serialize:()=>this.isModified("_fields")?this.fields.toArray().map((e=>e.toJSON())):void 0,deserialize:e=>{if(!e)return;const i=e.map((e=>I(e)?e:l.fromJSON(e)));w(this.fields,i,{onNew:(e,i)=>{this.fields.add(e,i)},onMatch:(e,i,t,s)=>{e!==i&&(e.alias=i.alias,e.editable=i.editable,e.length=i.length,e.nullable=i.nullable,e.type=i.type),t!==s&&this.fields.reorder(e,s)},onMissing:e=>{this.fields.remove(e)},equals:(e,i)=>R(e.name,i.name)})}},fieldExtensions:{serializeModes:["initial"],serialize:e=>this.fieldExtensions.toArray().map((i=>i.toJSON(e))).filter((e=>this._alwaysSerializeFieldExtensions||!(e&&2===Object.keys(e).length&&e.id&&e.field))),deserialize:e=>{e&&w(this.fieldExtensions,e,{onNew:(e,i)=>{this.fieldExtensions.add(r(e)?e:new K(e),i)},onMatch:(e,i,t,s)=>{r(i)||e.assignProperties(i),t!==s&&this.fieldExtensions.reorder(e,s)},onMissing:e=>{this._alwaysSerializeFieldExtensions&&this.fieldExtensions.remove(e)},equals:(e,i)=>r(i)?i===e:!(!i?.field||!K.matchesRef(e,i.field))||e.id===i.id})}},types:{serialize:!1,deserialize:e=>{if(!e)return;const i=e.map((e=>z(e)||!e?e:o.fromJSON(e)));w(this.types,i,{onNew:(e,i)=>{this.types.add(e,i)},onMatch:(e,i,t,s)=>{e!==i&&(e.name=i.name,e.templates=i.templates?[...i.templates]:[],e.domains=i.domains),t!==s&&this.types.reorder(e,s)},onMissing:e=>{this.types.remove(e)},equals:(e,i)=>e.id===i.id})}},timeZone:{serialize:!1,deserialize:e=>{e&&(this.timeZone=e)}}}}};P=e=i([p],P);export{P as Schema};class Z extends v{_schema;_fieldNameToField=new x;_expressionFields=new s;_expressionFieldsReadOnly=new b(this._expressionFields);get _expressionFieldsLength(){return this.expressionFields.length}get expressionFields(){return this._expressionFieldsReadOnly}get _popupTemplate(){return this._schema._featureSettings?this._schema._featureSettings.popupTemplate:void 0}constructor(e){super(new s),this._schema=e,this._handles.add(F(this,"length",(()=>y(this._schema,"_fields.length",(()=>g(this,"length")),{sync:!0})))),this._handles.add(y(this._schema,"_fields",(e=>{if(this._handles.remove("schema-field-collection-schema-fields"),null!=e){this._handles.add([e.on("after-add",(i=>{this._collection.add(i.item,e.indexOf(i.item)),this._fieldNameToField.set(i.item.name,i.item)})),e.on("after-remove",(e=>{this._collection.remove(e.item),this._fieldNameToField.delete(e.item.name)}))],"schema-field-collection-schema-fields");for(const i of this._collection)e.includes(i)||(this._collection.remove(i),this._fieldNameToField.delete(i.name));for(const i of e)this._collection.includes(i)||(this._collection.add(i),this._fieldNameToField.set(i.name,i))}else for(const e of this._collection.filter((e=>!this._expressionFields.includes(e))))this._collection.remove(e),this._fieldNameToField.delete(e.name)}),{sync:!0,initial:!0})),this._generateExpressionFields(),this._handles.add([y(this._schema,"_featureSettings.popupTemplate.fieldInfos",(()=>{this._generateExpressionFields()}),{sync:!0}),y(this._schema,"_featureSettings.popupTemplate.expressionInfos",(()=>{this._generateExpressionFields()}),{sync:!0})])}clone(){return new Z(this._schema)}add(e,i){T("field",e).isNotMissing();const t=A(e.name);if(t){if(!this._popupTemplate)throw new n("Cannot create a field that references an arcade expression without a feature source and popup template.");const i=this._popupTemplate.expressionInfos.find((e=>R(e.name,t)));if(!i)throw new n("Cannot create a field that references a non-existent arcade expression.");this._popupTemplate.fieldInfos||(this._popupTemplate.fieldInfos=[]);let s=this._popupTemplate.fieldInfos.find((i=>R(i.fieldName,e.name)));s||(s=new d({fieldName:e.name,label:i.title}),this._popupTemplate.fieldInfos.push(s));const o=B.get(s);B.set(s,e),null!=this._expressionFields&&(this._expressionFields.remove(o),this._expressionFields.includes(e)||(this._expressionFields.add(e),this._collection.add(e),this._fieldNameToField.set(e.name,e))),g(this,"_expressionFieldsLength")}else this._schema._fields.add(e,i);return this}destroy(){this._fieldNameToField.clear(),this._expressionFields.removeAll(),this._collection.removeAll(),super.destroy()}removeAt(e){T("index",e).isNotMissing();const i=this.getItemAt(e);if(!i)return;if(A(i.name)){const e=this._popupTemplate.fieldInfos.findIndex((e=>R(e.fieldName,i.name)));this._popupTemplate.fieldInfos.splice(e,1),this._expressionFields.remove(i),this._collection.remove(i),this._fieldNameToField.delete(i.name),g(this,"_expressionFieldsLength")}else this._schema._fields.remove(i);return i}reorder(e,i){if(e&&this._schema._fields.includes(e))return this._schema._fields.reorder(e,i),this._collection.reorder(e,i),e}sort(e){return this._schema._fields.sort(e),this._collection.sort(((i,t)=>this._expressionFields.includes(i)&&this._expressionFields.includes(t)?0:this._expressionFields.includes(i)?1:this._expressionFields.includes(t)?-1:e(i,t))),this}findFieldByName(e){return this._fieldNameToField.get(e)}_generateExpressionFields(){if(!this._popupTemplate?.fieldInfos||!this._popupTemplate?.expressionInfos){for(const e of this._expressionFields)this._collection.remove(e),this._fieldNameToField.delete(e.name);return void this._expressionFields.removeAll()}const e=this._expressionFields.slice();for(const i of this._popupTemplate.fieldInfos){const t=A(i.fieldName);if(null==t)continue;const s=this._popupTemplate.expressionInfos.find((e=>R(e.name,t)));if(null==s)continue;let o=B.get(i);null==o&&(o=new l({name:i.fieldName,alias:i.label||s.title||i.fieldName,type:"number"===s.returnType?"double":"string",editable:!1})),this._expressionFields.includes(o)?e.remove(o):(B.set(i,o),this._expressionFields.add(o),this._collection.add(o),this._fieldNameToField.set(o.name,o),e.remove(o))}for(const i of e)this._expressionFields.remove(i),this._collection.remove(i),this._fieldNameToField.delete(i.name)}}class J extends h{get _collection(){return this._schema.fields.map((e=>this._forField(e))).concat(Array.from(this._uninitializedFieldExtensions))}_schema;_uninitializedFieldExtensions=new Set;_onChangeSchemaFieldsHandle=new S((()=>this._schema.fields.on("change",(e=>{const i={added:(e.added||[]).map((e=>this._forField(e))),moved:(e.moved||[]).map((e=>this._forField(e))),removed:(e.removed||[]).map((e=>this._forField(e))),target:this};this.emit("change",i)}))));_onBeforeAddSchemaFieldsHandle=new S((()=>this._schema.fields.on("before-add",(e=>{this.emit("before-add",{...e,item:this._forField(e.item)})}))));_onBeforeRemoveSchemaFieldsHandle=new S((()=>this._schema.fields.on("before-remove",(e=>{this.emit("before-remove",{...e,item:this._forField(e.item)})}))));_onBeforeChangesSchemaFieldsHandle=new S((()=>this._schema.fields.on("before-changes",(e=>{this.emit("before-changes",{...e,item:this._forField(e.item)})}))));_onAfterAddSchemaFieldsHandle=new S((()=>this._schema.fields.on("after-add",(e=>{this.emit("after-add",{...e,item:this._forField(e.item)})}))));_onAfterRemoveSchemaFieldsHandle=new S((()=>this._schema.fields.on("after-remove",(e=>{this.emit("after-remove",{...e,item:this._forField(e.item)})}))));_onAfterChangesSchemaFieldsHandle=new S((()=>this._schema.fields.on("after-changes",(e=>{this.emit("after-changes",{...e,target:this})}))));constructor(e){super(),this._schema=e,this._handles.add(F(this,"length",(()=>y(this._schema.fields,"length",(()=>g(this,"length")),{sync:!0}))))}async destroy(){this._onChangeSchemaFieldsHandle.destroy(),this._onBeforeAddSchemaFieldsHandle.destroy(),this._onBeforeRemoveSchemaFieldsHandle.destroy(),this._onBeforeChangesSchemaFieldsHandle.destroy(),this._onAfterAddSchemaFieldsHandle.destroy(),this._onAfterRemoveSchemaFieldsHandle.destroy(),this._onAfterChangesSchemaFieldsHandle.destroy();const e=[];for(const i of this._schema.fields){const t=M.get(i);t&&t.schema===this._schema&&(M.delete(i),this._onRemoved(t),e.push(t.destroy()))}this._uninitializedFieldExtensions.forEach((i=>{this._onRemoved(i),e.push(i.destroy())})),this._uninitializedFieldExtensions.clear(),await Promise.all(e),super.destroy()}forField(e){if(T("field",e).isNotMissing(),this._schema.fields.includes(e))return this._forField(e)}add(e,i){if(T("fieldX",e).isNotMissing(),e.schema&&e.schema.fieldExtensions.remove(e),e._setSchema(this._schema),e.field){const t=M.get(e.field);if(M.set(e.field,e),t&&t!==e&&this._onRemoved(t),this._schema.fields.includes(e.field))if(void 0===i){const i={added:[e],moved:[],removed:t?[t]:[],target:this};this.emit("change",i),this.emit("after-add",{item:e}),this.emit("after-changes",{})}else this._schema.fields.reorder(e.field,i);else this._schema.fields.add(e.field,i)}else{this._uninitializedFieldExtensions.add(e);const i={added:[e],moved:[],removed:[],target:this};this.emit("change",i),this.emit("after-add",{item:e}),this.emit("after-changes",{})}return this._onAdded(e),this}removeAt(e){const i=this.getItemAt(e);if(void 0!==i){if(this._uninitializedFieldExtensions.has(i)){this._uninitializedFieldExtensions.delete(i);const e={added:[],moved:[],removed:[i],target:this};this.emit("change",e),this.emit("after-remove",{item:i}),this.emit("after-changes",{})}else this._schema.fields.remove(i.field);return this._onRemoved(i),i}}reorder(e,i){if(e&&this._schema.fields.includes(e.field))return this._schema.fields.reorder(e.field,i),e}sort(e){return this._schema.fields.sort(((i,t)=>e(this._forField(i),this._forField(t)))),this}on(e,i){const t=[];return"change"===e?t.push(this._onChangeSchemaFieldsHandle.add()):"before-add"===e?t.push(this._onBeforeAddSchemaFieldsHandle.add()):"before-remove"===e?t.push(this._onBeforeRemoveSchemaFieldsHandle.add()):"before-changes"===e?t.push(this._onBeforeChangesSchemaFieldsHandle.add()):"after-add"===e?t.push(this._onAfterAddSchemaFieldsHandle.add()):"after-remove"===e?t.push(this._onAfterRemoveSchemaFieldsHandle.add()):"after-changes"===e&&t.push(this._onAfterChangesSchemaFieldsHandle.add()),t.push(super.on(e,i)),u(t)}_itemIsInitialized(e){return super._itemIsInitialized(e)&&!!e.field}_onAdded(e){}_onRemoved(e){e.schema===this._schema&&e._setSchema(void 0)}_forField(e){if(this._uninitializedFieldExtensions.size)for(const e of this._uninitializedFieldExtensions)e._resolveField(),e.field&&(M.set(e.field,e),this._uninitializedFieldExtensions.delete(e));if(!M.has(e)){const i=new K({field:e});M.set(e,i),i._setSchema(this._schema),this._onAdded(i),i.initialize()}return M.get(e)}}
package/data/convert.js CHANGED
@@ -1 +1 @@
1
- import e from"@arcgis/core/Color.js";import t from"@arcgis/core/Graphic.js";import r from"@arcgis/core/geometry/Point";import o from"@arcgis/core/geometry/Polygon.js";import n from"@arcgis/core/geometry/Polyline.js";import a from"@arcgis/core/geometry/SpatialReference";import i from"@arcgis/core/layers/FeatureLayer.js";import s from"@arcgis/core/layers/GroupLayer.js";import l from"@arcgis/core/layers/support/Field.js";import c from"@arcgis/core/renderers/SimpleRenderer.js";import m from"@arcgis/core/renderers/UniqueValueRenderer.js";import u from"@arcgis/core/renderers/support/UniqueValueInfo.js";import f from"@arcgis/core/symbols/MeshSymbol3D.js";import y from"@arcgis/core/symbols/PictureMarkerSymbol.js";import p from"@arcgis/core/symbols/SimpleFillSymbol.js";import d from"@arcgis/core/symbols/SimpleLineSymbol.js";import g from"@arcgis/core/symbols/SimpleMarkerSymbol.js";import w from"dxf-parser";import{geometryTypeToJson as h}from"../json/GeometryJson.js";import{translate as F}from"../locale/language.js";import{INVARIANT as S}from"../locale.js";import{FeatureCollectionLayerExtension as T}from"../mapping/FeatureCollectionLayerExtension.js";import{GroupLayerExtension as N}from"../mapping/GroupLayerExtension.js";import{CaseInsensitiveObservableMap as O}from"../utilities/CaseInsensitiveObservableMap.js";import{Time as D}from"../utilities/Time.js";import{checkArg as b,assertNever as x}from"../utilities/checkArg.js";import{isPoint as M,isMultipoint as E,isPolyline as R,isPolygon as A,isExtent as I}from"../utilities/esri.js";import{parse as G,format as _,DEFAULT_PARSING_FORMATS as C,INVALID_DATE as L}from"../utilities/format/date.js";import{DateFormat as v,NumberFormat as P,TimeFormat as j}from"../utilities/format/formats.js";import{parse as U,format as $}from"../utilities/format/number.js";import{parse as H,format as B,DEFAULT_PARSING_FORMATS as J}from"../utilities/format/time.js";import{project as z,esriToWKT as k,wktToEsri as W,esriWkidToWkt as X,esriWktToWkid as q,esriToGeoJSON as Y,geoJSONToEsri as Z}from"../utilities/geometry.js";import{getLogger as K}from"../utilities/log.js";import{isNumeric as V}from"../utilities/number.js";import{delay as Q}from"../utilities/promise.js";import{caseInsensitiveEquals as ee}from"../utilities/string.js";import{Feature as te}from"./Feature.js";import{FeatureSet as re}from"./FeatureSet.js";import{DxfEntityProcessor as oe}from"./support/_dxfConverters.js";const ne=["=","-","+","@"],ae='"',ie="\r\n",se="\n",le=[...C.map(He),"M/d/yy"],ce=[...J.map(Je).map((e=>e.replace("AM/PM","tt")))],me=/(\w+)_(point|multipoint|polyline|polygon)z?/;var ue;function fe(){return K("geocortex.api.data.convert")}!function(e){e.DATE="D",e.NUMBER="N",e.STRING="C",e.BOOLEAN="L"}(ue||(ue={}));export const FIELD_NAME_REGEX=/[^a-zA-Z\d_]/g;export var GeometryFormat;!function(e){e.NONE="NONE",e.WKT="WKT",e.XY="XY",e.XYZ="XYZ",e.LAT_LON="LAT_LONG",e.GEO_JSON="GEO_JSON",e.ARCGIS_JSON="ARCGIS_JSON"}(GeometryFormat||(GeometryFormat={}));export const geometryTypeHeaders={[GeometryFormat.XYZ]:[["x","y","z"]],[GeometryFormat.XY]:[["x","y"]],[GeometryFormat.LAT_LON]:[["latitude","longitude"],["lat","lon"],["lat","long"]],[GeometryFormat.ARCGIS_JSON]:[["geometry"]],[GeometryFormat.GEO_JSON]:[["geometry"]],[GeometryFormat.WKT]:[["geometry"]]};const ye=[[GeometryFormat.ARCGIS_JSON,Ie],[GeometryFormat.GEO_JSON,Ge],[GeometryFormat.WKT,_e]],pe=new Map(ye);export async function uploadDataToFeatureSet(e){const t=await async function(e){const{data:t,includeHeaderRow:o,geometryFormat:n,geometryFields:a,locale:i,numberFormat:s,inSpatialReference:l}=e,c=o?t.slice(1):t;if(n===GeometryFormat.NONE)return{columnIndices:[]};const m=e=>ve(e,i,s),u=(e,t)=>{const o=t===GeometryFormat.XYZ,n=t===GeometryFormat.LAT_LON;return{columnIndices:e,geometries:c.map((t=>{if(t.length>=Math.max(...e)&&V(t[e[0]]?.raw,i)&&V(t[e[1]]?.raw,i)&&(!o||V(t[e[2]]?.raw,i)))return new r({x:m(n?t[e[1]].raw:t[e[0]].raw),y:m(n?t[e[0]].raw:t[e[1]].raw),z:o?m(t[e[2]].raw):0,spatialReference:l})}))}},f=async(e,t)=>({columnIndices:[e],geometries:await Promise.all(c.map((t=>t[e])).map((e=>{if(e?.raw)return t(e.raw.toString(),l)})))}),y=async(e,t)=>{switch(t){case GeometryFormat.NONE:return{columnIndices:[0]};case GeometryFormat.LAT_LON:case GeometryFormat.XYZ:case GeometryFormat.XY:return u(e,t);case GeometryFormat.ARCGIS_JSON:return f(e[0],Ie);case GeometryFormat.GEO_JSON:return f(e[0],Ge);case GeometryFormat.WKT:return f(e[0],_e);default:return x(t,new Error(`Unknown geometry format "${t}".`))}};if(n){const e=Ce(o?t[0]:t[0].map(((e,t)=>({raw:t.toString()}))),n,o?a:a.map((e=>""+(parseInt(e.match(/\d+/g)[0])-1))));if(o&&void 0===e)throw new Error(`Error parsing file data: Expected geometry columns ${geometryTypeHeaders[n][0].join(",")} are missing for GeometryType.${n}`);return y(e??[0],n)}const[p,d]=await Pe(t,l,o);if(p===GeometryFormat.NONE)return{columnIndices:[]};return d.length>1?u(d,p):f(d[0],pe.get(p))}(e),o=function(e,t){const{data:r,displayField:o,includeHeaderRow:n,inSpatialReference:a,outSpatialReference:i,generatePrimaryKey:s}=e,l={fields:[]},c=e=>!(!t.columnIndices||0===t.columnIndices.length)&&t.columnIndices.includes(e);let{primaryKeyField:m}=e,u=0;for(let t=0;t<r[0].length;t++){if(c(t))continue;const o=Ue(e,t,!s&&!m&&!l.fields.find((e=>"esriFieldTypeOID"===e.type)));let a=r[0][t]?.raw?.toString(),i=a?.replace(FIELD_NAME_REGEX,"_");n&&i||(i="field"+ ++u,a=F("gcx.api.data.convert.import-field-alias",u)),l.fields.push({alias:a,name:i,type:o}),"esriFieldTypeOID"===o&&(m=i)}if(l.spatialReference=i??t.geometries?.[0]?.spatialReference??a,t.geometries?.length){const e=t.geometries.filter((e=>void 0!==e)).map((e=>e.type)),r=e[0];l.geometryType=e.every((e=>e===r))?h(r):void 0}if(!l.fields.find((e=>"esriFieldTypeOID"===e.type))){const e=l.fields.length+1,t=!!l.fields.find((e=>"objectid"===e.name.toLowerCase()));m=t?`OBJECTID_${e}`:"OBJECTID",l.fields.push({name:m,alias:m,type:"esriFieldTypeOID"})}return l.displayField=o??l.fields.find((e=>!ee(e.name,m)&&"esriFieldTypeString"===e.type))?.name??l.fields.find((e=>!ee(e.name,m)))?.name??m,l.primaryKeyField=m,l}(e,t),n=await async function(e,t,r){const{data:o,includeHeaderRow:n,outFields:a,escapeFormulaChars:i,locale:s,numberFormat:l,dateFormat:c,timeFormat:m}=e,{spatialReference:u}=r,f=[],y=n?o.slice(1):o,p=(e,r)=>!t.columnIndices||0===t.columnIndices.length||!t.columnIndices.includes(r);return await Promise.all(y.map((async(e,o)=>{const n=new te;for(let t=0;t<r.fields.length;t++){const u=r.fields[t],f=e.filter(p);if(a.includes("*")||a.filter((e=>ee(e,u.name))).length>0){let e=await $e(f[t]?.raw,u,{escapeFormulaChars:i,dateFormat:c,numberFormat:l,timeFormat:m,locale:s});"esriFieldTypeOID"===u.type&&null===e&&(e=o),n.attributes.set(u.name,e)}}t.geometries&&(n.geometry=await Oe(t.geometries[o],u)),f.push(n)}))),f}(e,t,o);return new re({features:n,schema:o})}export async function toCsv(e,t){b("featureSet",e).isNotMissing();const r=Array.from(e),o={...{useFormattedValues:!1,alwaysQuote:!1,escapeFormulaChars:!0,delimiter:",",dateFormat:v.ROUND_TRIP,timeFormat:j.ROUND_TRIP,geometryFormat:r.some((e=>void 0!==e.geometry&&null!==e.geometry))?GeometryFormat.WKT:GeometryFormat.NONE,includeByteOrderMark:!0,outSpatialReference:a.WGS84,includeHeaderRow:!0,outFields:Te(e.source),rowDelimiter:navigator.platform?.startsWith("Win")?ie:"\n"},...t},{includeByteOrderMark:n,includeHeaderRow:i,delimiter:s,outFields:l,rowDelimiter:c}=o,m=[];n&&m.push("\ufeff");const u=Fe(r,o),f=Se(r,l,e.schema,!0),y=Se(r,l,e.schema,!1);if(i){const e=[];for(const t of u)e.push(De(t,o));for(const t of f)e.push(De(t,o));for(const t of y)e.push(De(t,o));const t=e.join(s)+c;m.push(t)}await Promise.all(r.map((async e=>{const t=[],r=(t,r)=>{const o=xe(e,t,r),n=e.schema.findFieldByName(t)?.type;return De(be(o,{...r,isDateOnly:"date-only"===n}),r)};t.push(...await async function(e,t){let r=await Ne(e,t);t.geometryFormat!==GeometryFormat.XYZ&&t.geometryFormat!==GeometryFormat.XY&&t.geometryFormat!==GeometryFormat.LAT_LON||(r=r.map((e=>void 0===e?"":be(e,t))));return r.map((e=>""===e?"":De(e,t)))}(e.geometry,o)),t.push(...f.map((e=>r(e,o)))),t.push(...y.map((e=>r(e,o))));const n=`${t.join(s)}${c}`;m.push(n)})));return new Blob(m,{type:"text/plain",endings:"\n"===c||c===ie?"transparent":"native"})}export async function csvToUploadData(e,t){let r;if(b("csvData",e).isNotMissing(),e instanceof Blob){const t=new Promise(((t,r)=>{const o=new FileReader;o.onload=()=>{t(o.result)},o.onerror=()=>{r(o.error)},o.readAsText(e)}));r=await t}else r=e;const o=ge(t),n=o.rowDelimiter||function(e){let t=se;return Ae(e,ie,((r,o)=>(0===r&&o===e.length||(t=ie),!1))),t}(r),a=o.delimiter??function(e,t,r){const o=",";if(0===e.length)return o;const n=[];if(Ae(e,t,((t,r)=>(r!==e.length||t!==r)&&(n.push(e.substring(t,r)),n.length<3))),0===n.length)return o;let a=[{delimiter:",",rowsDelimiterOccurrences:[],rowsNumberAdjacentOccurrences:[]},{delimiter:";",rowsDelimiterOccurrences:[]},{delimiter:"|",rowsDelimiterOccurrences:[]},{delimiter:"\t",rowsDelimiterOccurrences:[]},{delimiter:" ",rowsDelimiterOccurrences:[]}].filter((e=>n[0].includes(e.delimiter)));if(0===a.length)return o;for(const e of n)for(const t of a){let o=0,n=0;Ae(e,t.delimiter,((a,i)=>{if(i!==e.length&&o++,","===t.delimiter){const t=e.charAt(i-1),o=e.charAt(i+1);V(t,r)&&V(o,r)&&n++}return!0})),t.rowsDelimiterOccurrences.push(o),","===t.delimiter&&t.rowsNumberAdjacentOccurrences.push(n)}if(a=a.filter((e=>e.rowsDelimiterOccurrences.every((t=>e.rowsDelimiterOccurrences[0]===t)))).sort(((e,t)=>t.rowsDelimiterOccurrences[0]-e.rowsDelimiterOccurrences[0])),a.length>1&&","===a[0].delimiter&&null!=r&&r!==S){const e=a[0];if(null!=e&&","===e.delimiter&&","===Intl.NumberFormat(r).formatToParts(1.1).find((e=>"decimal"===e.type))?.value)for(let t=0;t<e.rowsDelimiterOccurrences.length;t++)if(e.rowsDelimiterOccurrences[t]<=e.rowsNumberAdjacentOccurrences[t]){a=a.filter((e=>","!==e.delimiter));break}}if(0===a.length)return o;return a[0].delimiter}(r,n,t.locale),i=function(e,t,r){const o=[],n=(e,t)=>{const o=[];return Ae(e,r,((r,n)=>{const a=e.substring(r,n);return o.push({raw:Re(a,t,o.length)}),!0})),o};if(Ae(e,t,((t,r)=>{const a=e.substring(t,r);return a.length>0&&o.push(n(a,o.length)),!0})),o.length){const e=o[0].length;o.forEach(((t,r)=>{if(t.length!==e)throw new Error(`Detected invalid CSV: Row ${r} does not have expected number of columns: ${e}`)}))}return o}(r,n,a);let{geometryFormat:s,geometryFields:l}=t;if(!s){const[e,t]=await Pe(i,o.inSpatialReference,o.includeHeaderRow);s=e,l=t.map((e=>o.includeHeaderRow?i[0][e]?.raw??F("gcx.api.data.convert.import-field-alias",(e+1).toString()):F("gcx.api.data.convert.import-field-alias",(e+1).toString())))}return{data:i,...o,geometryFormat:s,geometryFields:l}}export async function csvToFeatureSet(e,t){const r=ge(t);return uploadDataToFeatureSet(await csvToUploadData(e,r))}export async function toXLSX(e,t){b("featureSet",e).isNotMissing();const r=Array.from(e),o={...{useFormattedValues:!1,includeHeaderRow:!0,escapeFormulaChars:!0,geometryFormat:r.some((e=>void 0!==e.geometry&&null!==e.geometry))?GeometryFormat.WKT:GeometryFormat.NONE,outFields:Te(e.source),outSpatialReference:a.WGS84,dateFormat:v.DEFAULT,timeFormat:j.DEFAULT,numberFormat:P.DEFAULT,sheetName:"sheet1"},...t},{outFields:n,includeHeaderRow:i,dateFormat:s,timeFormat:l,numberFormat:c}=o,m=Fe(r,o),u=Se(r,n,e.schema,!0),f=Se(r,n,e.schema,!1),y=await import("xlsx"),p=y.utils.sheet_new();let d=!1;if(i){const t=m.concat(u).concat(function(e,t){const r=t?.schema?.fieldExtensions.initializedItems.map((e=>e.field));return e.map((e=>r?.find((t=>ee(t.name,e)))?.alias??e))}(f,e.source));d=!0,y.utils.sheet_add_aoa(p,[t],{cellDates:!0})}await Promise.all(r.map((async e=>{const t=[],r=new Set,n=new Set;t.push(...await Ne(e.geometry,o));for(const r of u){const n=ke(e.attributes.get(r),o);t.push(n)}for(const a of f){const i=xe(e,a,o);if(i instanceof D){const o=e.schema.findFieldByName(a);"time-only"===o?.type&&r.add(t.length)}else if(i instanceof Date){const r=e.schema.findFieldByName(a);"date-only"===r?.type&&n.add(t.length)}const s=ke(i,o);t.push(s)}if(!t.every((e=>"string"!=typeof e||e.length<=32767)))return void fe().warn(`toXLSX cell limit exceeded, feature (${e.primaryKey??e.id}) omitted.`);y.utils.sheet_add_aoa(p,[t],{cellDates:!0,origin:d?-1:void 0}),d=!0;const a=y.utils.decode_range(p["!ref"]);for(let e=a.s.c;e<=a.e.c;e++){const t=p[y.utils.encode_cell({r:a.e.r,c:e})];"d"===t.t?r.has(e)?t.z=Je(l??j.ROUND_TRIP):n.has(e)?t.z=Be(s??v.ROUND_TRIP):t.z=He(s??v.ROUND_TRIP):"n"===t.t&&(t.z=ze(c))}})));const g={SheetNames:[],Sheets:{}};g.SheetNames.push(o.sheetName),g.Sheets[o.sheetName]=p;const w=y.write(g,{type:"binary",bookType:"xlsx",compression:!0,bookSST:!0,cellDates:!0}),h=new Uint8Array(w.length);for(let e=0;e<w.length;e++)h[e]=w.charCodeAt(e);return new Blob([h.buffer],{type:"text/plain"})}export async function xlsxToUploadData(e,t){b("xlsxData",e).isNotMissing();const r=we(t),o=await async function(e,t){const r=await import("xlsx"),o=new Promise(((o,n)=>{const a=new FileReader;a.onload=()=>{const e=new Uint8Array(a.result);let n="";for(const t of e)n+=String.fromCharCode(t);const i=r.read(n,{type:"binary",cellDates:!0}),s=t.sheetName||i.SheetNames[0],l=i.Sheets[s];o(l)},a.onerror=()=>{n(a.error)},a.readAsArrayBuffer(e)})),n=await o,a=r.utils.decode_range(n["!ref"]),i=[];for(let e=a.s.r;e<=a.e.r;e++){const t=[];for(let o=a.s.c;o<=a.e.c;o++){const a=n[`${r.utils.encode_cell({r:e,c:o})}`];a&&"d"===a.t&&a.v instanceof Date&&(a.v=new Date(a.v.getTime()+6e4*a.v.getTimezoneOffset())),t.push(a?{raw:a.v,formatted:"s"===a.t?void 0:a.w}:{raw:""})}i.push(t)}return i}(e,r);let{geometryFormat:n,geometryFields:a}=t;if(!n){const[e,t]=await Pe(o,r.inSpatialReference,r.includeHeaderRow);n=e,a=t.map((e=>r.includeHeaderRow?o[0][e]?.raw.toString()??F("gcx.api.data.convert.import-field-alias",(e+1).toString()):F("gcx.api.data.convert.import-field-alias",(e+1).toString())))}return{data:o,...r,geometryFormat:n,geometryFields:a}}export async function xlsxToFeatureSet(e,t){b("xlsxData",e).isNotMissing();const r=we(t);return uploadDataToFeatureSet(await xlsxToUploadData(e,r))}export function kmlHexToEsriColor(t){return e.fromHex(`#${t.match(/.{2}/g).reverse().join("")}`)}export function parseKMLCoordinates(e){return e.trim().split(/\s+/).map((e=>{const[t,r,o]=e.split(",").map(Number);return{x:t,y:r,z:o}}))}export function parseKMLSymbol(t,r,o){if(t){const r=t.querySelector("IconStyle > Icon > href")?.textContent;if(r)return new y({url:r,width:32,height:32});const o=t.querySelector("PolyStyle");if(o){const t=o.querySelector("color")?.textContent,r=t?kmlHexToEsriColor(t):new e([0,0,0,1]);return new p({color:r,outline:{color:[0,0,0,.5],width:1}})}const n=t.querySelector("LineStyle");if(n){const t=n.querySelector("color")?.textContent,r=t?kmlHexToEsriColor(t):new e([0,0,0,1]),o=parseFloat(n.querySelector("width")?.textContent||"1");return new d({color:r,width:o})}}return getDefaultSymbol(o,"polygon"===r?"polygon":"point"===r?"point":"polyline")}export async function toShapefile(e,t){b("featureSet",e).isNotMissing();const[{default:r},o]=await Promise.all([import("jszip"),import("../forked-libs/shp-write/index.js")]),n=Array.from(e),i={...{useFormattedValues:!1,outFields:Te(e.source),fileName:e.title||"export"},...t},{outFields:s,outSpatialReference:l,fileName:c}=i,m=e=>e.geometry.hasZ||e.geometry.hasM,u=new Map,f=n.filter((e=>M(e.geometry)));u.set("POINTZ",f.filter(m)),u.set("POINT",f.filter((e=>!m(e))));const y=n.filter((e=>E(e.geometry)));u.set("MULTIPOINTZ",y.filter(m)),u.set("MULTIPOINT",y.filter((e=>!m(e))));const p=n.filter((e=>R(e.geometry)));u.set("POLYLINEZ",p.filter(m)),u.set("POLYLINE",p.filter((e=>!m(e))));const d=n.filter((e=>A(e.geometry)||I(e.geometry)));u.set("POLYGONZ",d.filter(m)),u.set("POLYGON",d.filter((e=>!m(e))));const g=Se(n,s,e.schema,!0);let w=Se(n,s,e.schema,!1);w=g.concat(w);const h=new r,F=Array.from(u.keys()).filter((e=>u.get(e).length>0));await Promise.all(F.map((async t=>{const r=u.get(t),n=await Promise.all(r.map((e=>Oe(e.geometry,l)))),s=await async function(e){const{wkid:t,wkt:r}=e[0].spatialReference;if(!e.every((e=>e.spatialReference.wkid===t&&e.spatialReference.wkt===r)))throw new Error("Cannot create shapefile that contains geometries with different spatial references.");return r??await X(t??a.WGS84.wkid)}(n),m=i.useFormattedValues?Object.assign({},...w.map((e=>({[e]:ue.STRING})))):function(e,t,r,o){const n={};for(const a of t){if(e.some((e=>Me(e,a)))){n[a]=ue.STRING;continue}const t=r?r.fields.find((e=>ee(e.name,a))):void 0;if(t){switch(t.type){case"oid":case"double":case"integer":case"single":case"small-integer":case"big-integer":n[a]=ue.NUMBER;break;case"date":case"timestamp-offset":n[a]=o?ue.NUMBER:ue.DATE;break;default:n[a]=ue.STRING}continue}const i=(e,t)=>e.attributes.get(t)??e.presentableAttributes.get(t);e.every((e=>i(e,a)instanceof Date||void 0===i(e,a)))&&e.some((e=>i(e,a)instanceof Date))?n[a]=o?ue.NUMBER:ue.DATE:e.every((e=>"number"==typeof i(e,a)||void 0===i(e,a)))&&e.some((e=>"number"==typeof i(e,a)))?n[a]=ue.NUMBER:e.every((e=>"boolean"==typeof i(e,a)||void 0===i(e,a)))&&e.some((e=>"boolean"==typeof i(e,a)))?n[a]=ue.BOOLEAN:n[a]=ue.STRING}return n}(r,w,e.schema,"timestamp"===i.dateFormat),f=function(e){return e.map((e=>{if(M(e)){const{x:t,y:r,z:o,m:n}=e,a=[t,r];return e.hasZ&&a.push(o),e.hasM&&a.push(n),We(a,e)}if(E(e))return Xe(e.points,e);if(R(e))return qe(e.paths,e);if(A(e))return qe(e.rings,e);if(I(e)){const t=[e.xmin,e.ymax];return[[t,[e.xmax,e.ymax],[e.xmax,e.ymin],[e.xmin,e.ymin],t]]}throw new Error("Unsupported geometry type.")}))}(n),y=function(e,t,r,o){const n=[];for(const a of e){const e={};for(const n of t){let t=xe(a,n,o);if(null==t&&(t=""),o.useFormattedValues)t=t.toString();else{t=Ye(t,r[n],{...o,isDateOnly:"date-only"===a.schema.findFieldByName(n)?.type})}e[n.replaceAll(".","_")]=t}n.push(e)}return n}(r,w,m,i);o.write(y,t,f,((e,r)=>{const o=F.length>1?`${c}_${t.toLowerCase()}`:c;h.file(`${o}.shp`,r.shp.buffer,{binary:!0}),h.file(`${o}.shx`,r.shx.buffer,{binary:!0}),h.file(`${o}.dbf`,r.dbf.buffer,{binary:!0}),h.file(`${o}.prj`,s)}))})));const S=await h.generateAsync({type:"uint8array"});return new Blob([S.buffer],{type:"text/plain"})}export async function kmlToLayerExtensions(e){b("blob",e).isNotMissing();const a=await e.text(),c=(new DOMParser).parseFromString(a,"application/xml"),m=function(e,a,u=!1){const f={};c.querySelectorAll("Style").forEach((e=>{f[`#${e.id}`]=e}));const y=e.querySelector(":scope > name")?.textContent??"Unnamed Container",p=new Map;e.querySelectorAll(":scope > Placemark").forEach(((e,i)=>{const s=e.querySelector("name")?.textContent??"",l=e.querySelector("description")?.textContent??"",c=function(e){const t=e.querySelector("Point > coordinates"),a=e.querySelector("LineString > coordinates"),i=e.querySelector("Polygon");if(t?.textContent){const[e]=parseKMLCoordinates(t.textContent.replace(/ /g,""));return new r(e)}if(a?.textContent)return new n({paths:[parseKMLCoordinates(a.textContent).map((({x:e,y:t})=>[e,t]))]});if(i?.textContent){const e=i.querySelector("outerBoundaryIs > LinearRing > coordinates");if(e?.textContent){const t=[parseKMLCoordinates(e.textContent).map((({x:e,y:t})=>[e,t]))];return new o({rings:t})}}return}(e);if(c?.type){const r=e.querySelector("styleUrl")?.textContent,o=parseKMLSymbol(r?f[r]:e.querySelector("Style"),c.type,a);p.has(c.type)||p.set(c.type,{graphics:[],symbols:[]});let n=function(e,t){for(let r=0;r<e.length;r++)if(Ze(e[r],t))return r;return-1}(p.get(c.type).symbols,o);-1===n&&(p.get(c.type).symbols.push(o),n=p.get(c.type).symbols.length-1),p.get(c.type).graphics.push(new t({geometry:c,attributes:{name:s,description:l,SymbolID:n,OBJECTID:y+i}}))}}));const d=e.querySelectorAll(":scope > Folder, :scope > Document");if(u||1!==p.size||0!==d.length){const e=new N({layer:new s({title:y})});return p.forEach(((t,r)=>{const o=new i({displayField:"name",title:`${r.slice(0,1).toUpperCase()+r.slice(1)}s`,source:t.graphics,renderer:Ke(t.symbols),fields:[new l({name:"OBJECTID",type:"oid",alias:"OBJECTID"}),new l({name:"SymbolID",type:"integer",alias:"SymbolID",editable:!1}),new l({name:"name",type:"string",alias:"name"}),new l({name:"description",type:"string",alias:"description",defaultValue:""})]}),n=new T({layer:o});e.layerExtensions.add(n)})),d.forEach(((t,r)=>{const o=m(t,r);e.layerExtensions.add(o)})),e}{const e=[...p.values()][0],t=new i({displayField:"name",title:y,source:e.graphics,renderer:Ke(e.symbols),fields:[new l({name:"OBJECTID",type:"oid",alias:"OBJECTID"}),new l({name:"SymbolID",type:"integer",alias:"SymbolID",editable:!1}),new l({name:"name",type:"string",alias:"name"}),new l({name:"description",type:"string",alias:"description",defaultValue:""})]});return new T({layer:t})}},u=[];return c.querySelectorAll("kml > Document, kml > Folder").forEach(((e,t)=>{const r=m(e,t,!0);r.layerExtensions.length&&u.push(r)})),u}export async function dxfToLayerExtensions(e,t,r){const{inputSpatialReference:o,outputSpatialReference:n}=t;b("options.dxfBlob",e).isNotMissing(),b("options.inputSpatialReference",o).isNotMissing(),b("options.outputSpatialReference",n).isNotMissing();const a=new oe(o,n,r),i=a.getContext(),l=await e.text(),c=new w;await Q();try{const e=c.parseSync(l);if(!e)throw new Error("DXF parsing failed: parser returned null");i.dxf=e}catch(e){throw e instanceof Error?e:new Error(String(e))}const m=e instanceof File?e.name:"dxf-layer",u=m.replace(/[^a-zA-Z0-9_.-]/g,"_");if(i.fileName=m,i.sanitizedFileName=u,i.subLayers=await a.processAll(),!i.subLayers||0===i.subLayers.length)return[];const f=new s({id:`dxf-group-${u}-${(new Date).getTime()}`,title:m,visible:!0}),y={layer:f,visibilityMode:"independent"};return f.layers.addMany(i.subLayers),[new N(y)]}export async function shapefileToUploadData(e,t){b("shapefileData",e).isNotMissing();const o=he(t),n=new Promise(((t,r)=>{const o=new FileReader;o.onload=()=>{t(o.result)},o.onerror=()=>{r(o.error)},o.readAsArrayBuffer(e)})),[{default:i},{default:s}]=await Promise.all([import("jszip"),import("shpjs")]),l=await n,c=await i.loadAsync(new Uint8Array(l)),m=new O;c.forEach(((e,t)=>{t&&m.set(t.name,t)}));const u=c.filter((()=>!0)).map((e=>e.name));let f,y=u.filter((e=>e.endsWith(".shp"))).map((e=>e.substring(0,e.length-4)));if(y=function(e){if(!e.length)return[];let t=e[0];const r=t.match(me);return r?(t=r[1],e.filter((e=>{const r=e.match(me);return r&&r[1]===t}))):[t]}(y),u.some((e=>e.endsWith(".prj")))&&!y.every((e=>m.has(`${e}.prj`))))throw new Error("Shapefile zip must contain the same prj file for each separate shapefile");await Promise.all(u.filter((e=>e.endsWith(".prj"))).map((async e=>{const t=await c.file(e).async("string");if(f){if(t!==f)throw new Error("Shapefile zip must contain the same prj file for each separate shapefile")}else f=t})));let p=[],d=[];for(const e of y){if(!m.has(`${e}.shp`)||!m.has(`${e}.shx`)||!m.has(`${e}.dbf`))throw new Error("Shapefile must contain shp, shx, and dbf files.");const t=s.parseShp(await m.get(`${e}.shp`).async("uint8array")),r=s.parseDbf(await m.get(`${e}.dbf`).async("uint8array"));if(r.length!==t.length)throw new Error("Shapefile must contain shp, shx, and dbf files.");p=p.concat(r),d=d.concat(t)}const g=await Promise.all(d.map((e=>async function(e,t){const o=M(e)?function(e){b("geometry.coordinates",e.type).matches("Point"),b("geometry.coordinates",e.coordinates).satisfies((e=>"number"==typeof e||Array.isArray(e)));const[t,o,n]=e.coordinates,i=new r({x:t,y:o,spatialReference:a.WGS84});if(Array.isArray(n)){const[e,t]=n;!e&&!t||e?i.z=e:i.m=t}return i}(e):await Z(e);if(t){let e;try{const r=await q(t);e=new a({wkid:U(r)})}catch{}e||(e=new a({wkt:t})),o.spatialReference=e}return o}(e,f)))),w=geometryTypeHeaders[GeometryFormat.ARCGIS_JSON][0][0];p.forEach(((e,t)=>e[w]=JSON.stringify(g[t].toJSON())));return{data:function(e){const t=e.map((e=>Object.keys(e))).reduce(((e,t)=>e.concat(t.filter((t=>!e.includes(t))))),[]);return[t.map((e=>({raw:e}))),...e.map((e=>t.map((t=>({raw:e[t]})))))]}(p),...o,includeHeaderRow:!0,geometryFormat:GeometryFormat.ARCGIS_JSON,geometryFields:[w],inSpatialReference:g[0]?.spatialReference??a.fromJSON({wkid:4326})}}export async function shapefileToFeatureSet(e,t){b("shapefileData",e).isNotMissing();const r=he(t);return uploadDataToFeatureSet(await shapefileToUploadData(e,r))}export function getDefaultSymbol(e,t){const r=e%8;let o=["#FFDBFF","#88D6FF","#7F9FC3","#FF8200","#F34A53","#76E3B9","#E7BFFF","#FFC467"][r],n=["#EF3786","#005A99","#2D5070","#790C00","#4C0000","#006543","#6244A9","#904200"][r];if(Math.floor(e/8)%2!=0){const e=o;o=n,n=e}switch(t){case"point":case"multipoint":return new g({color:o,outline:{color:n}});case"polyline":return new d({color:o,width:"2"});case"polygon":return new p({color:o,outline:{color:n}});case"mesh":return new f({symbolLayers:[{type:"fill",material:{color:o},outline:{color:n}}]})}}function de(e){return{escapeFormulaChars:!0,outFields:["*"],generatePrimaryKey:!1,locale:S,detectOid:!e?.primaryKeyField}}function ge(e){return{...{includeHeaderRow:!0,inSpatialReference:a.WGS84,...de(e)},...e}}function we(e){return{...{includeHeaderRow:!0,inSpatialReference:a.WGS84,...de(e)},...e}}function he(e){return{...{...de(e)},...e}}function Fe(e,t){return t.geometryFormat===GeometryFormat.XYZ?["x","y","z"]:t.geometryFormat===GeometryFormat.XY?["x","y"]:t.geometryFormat===GeometryFormat.LAT_LON?["latitude","longitude"]:t.geometryFormat===GeometryFormat.NONE?[]:["geometry"]}function Se(e,t,r,o){const n=r.fields.filter((e=>"oid"===e.type)).map((e=>e.name)).toArray();if(o)return n;if(t&&!t.includes("*"))return t.filter((e=>!n.includes(e)));{const t=r.fields.filter((e=>"oid"!==e.type)).map((e=>e.name)).toArray();let o=[];for(const r of e)for(const e of r.attributes.keys())t.includes(e)||n.includes(e)||o.includes(e)||o.push(e);return o=o.sort(),t.concat(o)}}function Te(e){if(!e)return["*"];const t=e.featureSettings.popupTemplate?.content;return(Array.isArray(t)?t.find((e=>"fields"===e.type))?.fieldInfos?.filter((e=>e.visible))?.map((e=>e.fieldName)):void 0)??e.featureSettings.popupTemplate?.fieldInfos?.filter((e=>e.visible))?.map((e=>e.fieldName))??["*"]}async function Ne(e,t){const r=await Oe(e,t.outSpatialReference);if(t.geometryFormat===GeometryFormat.XYZ){if(!r)return["","",""];if(!M(r))throw new Error("Cannot use geometry format XYZ with non-point geometry");return[r.x,r.y,r.z]}if(t.geometryFormat===GeometryFormat.XY){if(!r)return["",""];if(!M(r))throw new Error("Cannot use geometry format XY with non-point geometry");return[r.x,r.y]}if(t.geometryFormat===GeometryFormat.LAT_LON){if(!r)return["",""];if(!M(r))throw new Error("Cannot use geometry format LAT_LONG with non-point geometry");return[r.y,r.x]}return t.geometryFormat===GeometryFormat.ARCGIS_JSON?r?[JSON.stringify(r.toJSON())]:[""]:t.geometryFormat===GeometryFormat.WKT?r?[await k(r)]:[""]:t.geometryFormat===GeometryFormat.GEO_JSON?r?[JSON.stringify(await Y(r))]:[""]:[]}async function Oe(e,t){return e?.spatialReference&&!e.spatialReference.equals(t)&&t?(await z([e],t))[0]:e}function De(e,t){const r=[t.delimiter,ae,"\r","\n",t.rowDelimiter];if(t.alwaysQuote||r.some((t=>e.includes(t)))){const t=e.replace(new RegExp(ae,"g"),`${ae}${ae}`);return`${ae}${t}${ae}`}return e}function be(e,t){if(null==e)return"";if(!t.useFormattedValues){if("number"==typeof e){const r=t.numberFormat||P.ROUND_TRIP;return $(r,e)}if(e instanceof Date)return"timestamp"===t.dateFormat?e.getTime().toString():_({format:t.dateFormat,timeZone:"UTC",isDateOnly:t.isDateOnly},e);if(e instanceof D)return B({format:t.timeFormat},e)}let r=e.toString();return t.escapeFormulaChars&&(r=Ee(r)),r}function xe(e,t,r){if(r.useFormattedValues||Me(e,t))return e.presentableAttributes.get(t)??e.attributes.get(t);const o=e.schema.findFieldByName(t)?.type;if(null!=o)switch(o){case"date":case"date-only":case"timestamp-offset":{const r=G(e.attributes.get(t));if(!isNaN(r.getTime()))return r;break}case"time-only":{const r=H(e.attributes.get(t));if(r.isValid)return r;break}}return e.attributes.get(t)??e.presentableAttributes.get(t)}function Me(e,t){return!!ee(t,e.schema.typeIdField)||("coded-value"===e.type?.domains?.[t]?.type||"coded-value"===e.schema.findFieldByName(t)?.domain?.type)}function Ee(e){for(const t of ne)if(e.startsWith(t))return`\t${e}`;return e}function Re(e,t,r){const o=e.startsWith(ae),n=e.endsWith(ae);if(o&&!n||!o&&n)throw new Error(`Detected invalid CSV: Missing opening or closing quote for value at row:${t} column:${r}`);const a=o?e.substring(1,e.length-1):e;let i=-1;return Ae(a,ae,((e,o)=>{if(o===a.length)return!0;if(i<0){if(o!==a.length)return i=o,!0}else if(o===i+1)return i=-1,!0;throw new Error(`Detected invalid CSV: Non-escaped quote for value at row:${t} column:${r}`)})),a.replace(new RegExp(`${ae}${ae}`,"g"),ae)}function Ae(e,t,r){let o,n=!1,a=0,i=0;for(;o=e.indexOf(t,a),!(o<0);){for(let t=a;t<o;)e.substring(t).startsWith(ae)?(n=!n,t+=1):t++;const s=o+t.length;if(!n){const e=r(i,o);if(i=s,!e)return}a=s}r(i,e.length)}async function Ie(e,t){const r=JSON.parse(e),o=(await import("@arcgis/core/geometry/support/jsonUtils")).fromJSON(r);return r.spatialReference||(o.spatialReference=t),o}async function Ge(e,t){const r=await Z(JSON.parse(e));return r.spatialReference=t,r}async function _e(e,t){const r=await W(e);return r.spatialReference=t,r}function Ce(e,t,r){const o=r?[r]:geometryTypeHeaders[t];for(const t of o){const r=t.map((t=>e.map((e=>e?.raw?.toString().trim().toLowerCase())).indexOf(t.trim().toLowerCase())));if(r.every((e=>e>=0)))return r}}async function Le(e,t){return(await Promise.all(e.map((async(e,r)=>{const o=e?.raw;if("string"==typeof o&&""!==o)try{return await t(o,void 0),r}catch{return}})))).find((e=>void 0!==e))}function ve(e,t,r){return"inv"===t?"string"==typeof e?parseFloat(e.replaceAll(",","")):e:U({locale:t,format:r},e)}async function Pe(e,t,r){const o=r?e.slice(1):e;if(r){const r=Ce(e[0],GeometryFormat.ARCGIS_JSON);if(void 0!==r)for(const[e,n]of ye){try{await je(r[0],n,t,o)}catch{continue}return[e,[r[0]]]}const n=[GeometryFormat.XYZ,GeometryFormat.XY,GeometryFormat.LAT_LON];for(const t of n){const r=Ce(e[0],t);if(void 0!==r)return[t,r]}}for(const[e,r]of ye){const n=await Le(o[0],r);if(void 0!==n){try{await je(n,r,t,o)}catch{continue}return[e,[n]]}}return[GeometryFormat.NONE,[]]}async function je(e,t,r,o){return{columnIndices:[e],geometries:await Promise.all(o.map((t=>t[e])).map((e=>{if(e?.raw)return t(e.raw.toString(),r)})))}}function Ue(e,t,r){let o=!1,n=!0,a=!0,i=!0,s=!0,l=!0;const c=new Set,{data:m,includeHeaderRow:u,dateFormat:f,timeFormat:y,primaryKeyField:p,locale:d}=e,g=u?m[0]:[],w=u?m.slice(1):m;for(const e of w){const r=e[t];r?.raw&&(c.add(r.raw),o=!0,n&&(n=V(r.raw,d)||Number.isNaN(r.raw)),a&&(a=r.raw instanceof Date||G(f||C,r.raw)!==L),s&&(s=G(f||le,r.formatted)!==L),i&&(i=r.raw instanceof D||H(y||J,r.raw).isValid),l&&(l=H({format:y||ce,locale:"en"},r.formatted).isValid))}const h=c.size===w.length;return p&&g[t]?.raw===p||r&&o&&h&&n?"esriFieldTypeOID":o&&l?"esriFieldTypeTimeOnly":o&&s?"esriFieldTypeDate":o&&n?"esriFieldTypeDouble":o&&i?"esriFieldTypeTimeOnly":o&&a?"esriFieldTypeDate":"esriFieldTypeString"}async function $e(e,t,r){const{escapeFormulaChars:o,locale:n,numberFormat:a,dateFormat:i,timeFormat:s}=r;if("esriFieldTypeDouble"===t.type||"esriFieldTypeOID"===t.type)return"number"==typeof e?e:e?ve(e,n,a):null;if("esriFieldTypeDate"===t.type){if(e instanceof Date)return e.getTime();if("number"==typeof e){const t=(await import("xlsx")).SSF.parse_date_code(e);return t?new Date(t.y,t.m-1,t.d,t.H,t.M,t.S).getTime():void 0}return""===e?null:G({locale:n,format:i},e).getTime()}if("esriFieldTypeTimeOnly"===t.type){if(e instanceof D)return e.toString();if(e instanceof Date)return new D(e).toString();if("number"==typeof e){const t=(await import("xlsx")).SSF.parse_date_code(e);return t?new D(`${t.H.toString().padStart(2,"0")}:${t.M.toString().padStart(2,"0")}:${t.S.toString().padStart(2,"0")}`).toString():void 0}return""===e?null:H({locale:n,format:s},e).toString()}const l=e?.toString()??"";if(o&&l.startsWith("\t"))for(const e of ne)if(l.length>1&&l.charAt(1)===e)return l.substring(1);return l}function He(e){switch(e){case v.DATE_SHORT:return"dd/MM/yyyy";case v.DATE_LONG:return"MMMM d, yyyy";case v.TIME_SHORT:return"h:mm AM/PM";case v.TIME_LONG:return"h:mm:ss AM/PM";case v.DATE_TIME_SHORT:case v.DEFAULT:return"MMM d yyyy h:mm AM/PM";case v.DATE_TIME_LONG:return"MMMM d yyyy h:mm AM/PM";case v.FULL:return"dddd, MMMM d yyyy h:mm AM/PM";case v.ISO_8601:case v.ROUND_TRIP:return'yyyy-MM-dd"T"HH:mm:ss';default:{const t=e.replace(/tt/g,"AM/PM");return t.includes("z")&&fe().warn("Warning: Excel will not recognize timezone format 'z', 'zz', or 'zzz'"),t.includes("h")&&!t.includes("AM/PM")&&fe().warn("Warning: Excel will interpret 'h' as 'H' if the format does not have an AM/PM designator"),t}}}function Be(e){switch(e){case v.DATE_SHORT:return"dd/MM/yyyy";case v.DATE_LONG:return"MMMM d, yyyy";case v.DATE_TIME_SHORT:case v.DEFAULT:return"MMM d yyyy";case v.DATE_TIME_LONG:return"MMMM d yyyy";case v.FULL:return"dddd, MMMM d yyyy";case v.ISO_8601:case v.ROUND_TRIP:return"yyyy-MM-dd";default:return e.replace(/TtZzHhmSsUua/g,"")}}function Je(e){switch(e){case j.TIME_SHORT:return"h:mm AM/PM";case j.TIME_LONG:return"h:mm:ss AM/PM";case j.ISO_8601:case j.ROUND_TRIP:return"HH:mm:ss";default:{const t=e.replace(/tt/g,"AM/PM");return t.includes("h")&&!t.includes("AM/PM")&&fe().warn("Warning: Excel will interpret 'h' as 'H' if the format does not have an AM/PM designator"),t}}}function ze(e){switch(e){case P.ACCOUNTING:return'_("$"* #,##0.00_);_("$"* (#,##0.00);_("$"* "-"??_);_(@_)';case P.CURRENCY:return'"$"#,##0.00';case P.FIXED_POINT:case P.DEFAULT:return"0.0000";case P.NUMBER:return"#,##0.0000";case P.PERCENT:return"0%";case P.ROUND_TRIP:return"0.00000";default:return e}}function ke(e,t){if(null==e)return"";if(!t.useFormattedValues){if("number"==typeof e)return e;if(e instanceof Date)return"timestamp"===t.dateFormat?e.getTime():e;if(e instanceof D)return e.toDate()}let r=e.toString();return t.escapeFormulaChars&&(r=Ee(r)),r}function We(e,t){return 3===e.length&&!t.hasZ&&t.hasM?[e[0],e[1],void 0,e[2]]:e}function Xe(e,t){return e.map((e=>We(e,t)))}function qe(e,t){return e.map((e=>Xe(e,t)))}function Ye(e,t,r){switch(t){case ue.NUMBER:return e instanceof Date?e.getTime():U(e);case ue.STRING:return e instanceof Date?_({format:r.dateFormat??v.ROUND_TRIP,timeZone:"UTC",isDateOnly:r.isDateOnly},e):e instanceof D?B({format:r.timeFormat??j.ROUND_TRIP},e):"number"==typeof e?$(r.numberFormat??P.DEFAULT,e):e.toString();case ue.BOOLEAN:return!!e;case ue.DATE:return G(e);default:return e.toString()}}function Ze(e,t){return JSON.stringify(e.toJSON())===JSON.stringify(t.toJSON())}function Ke(e){return 1===e.length?new c({symbol:e[0]}):new m({field:"SymbolID",uniqueValueInfos:[...e.map(((e,t)=>new u({label:t.toString(),symbol:e,value:t})))]})}
1
+ import e from"@arcgis/core/Color.js";import t from"@arcgis/core/Graphic.js";import r from"@arcgis/core/geometry/Point";import o from"@arcgis/core/geometry/Polygon.js";import n from"@arcgis/core/geometry/Polyline.js";import a from"@arcgis/core/geometry/SpatialReference";import i from"@arcgis/core/layers/FeatureLayer.js";import s from"@arcgis/core/layers/GroupLayer.js";import c from"@arcgis/core/layers/support/Field.js";import l from"@arcgis/core/renderers/SimpleRenderer.js";import m from"@arcgis/core/renderers/UniqueValueRenderer.js";import u from"@arcgis/core/renderers/support/UniqueValueInfo.js";import f from"@arcgis/core/symbols/MeshSymbol3D.js";import y from"@arcgis/core/symbols/PictureMarkerSymbol.js";import p from"@arcgis/core/symbols/SimpleFillSymbol.js";import d from"@arcgis/core/symbols/SimpleLineSymbol.js";import g from"@arcgis/core/symbols/SimpleMarkerSymbol.js";import w from"dxf-parser";import{geometryTypeToJson as h}from"../json/GeometryJson.js";import{translate as F}from"../locale/language.js";import{INVARIANT as S}from"../locale.js";import{FeatureCollectionLayerExtension as T}from"../mapping/FeatureCollectionLayerExtension.js";import{GroupLayerExtension as N}from"../mapping/GroupLayerExtension.js";import{CaseInsensitiveObservableMap as O}from"../utilities/CaseInsensitiveObservableMap.js";import{Time as D}from"../utilities/Time.js";import{checkArg as b,assertNever as x}from"../utilities/checkArg.js";import{isPoint as M,isMultipoint as E,isPolyline as R,isPolygon as A,isExtent as I}from"../utilities/esri.js";import{parse as G,format as _,DEFAULT_PARSING_FORMATS as C,INVALID_DATE as L}from"../utilities/format/date.js";import{DateFormat as v,NumberFormat as P,TimeFormat as j}from"../utilities/format/formats.js";import{parse as U,format as $}from"../utilities/format/number.js";import{parse as H,format as B,DEFAULT_PARSING_FORMATS as J}from"../utilities/format/time.js";import{project as z,esriToWKT as k,wktToEsri as W,esriWkidToWkt as X,esriWktToWkid as q,esriToGeoJSON as Y,geoJSONToEsri as Z}from"../utilities/geometry.js";import{getLogger as K}from"../utilities/log.js";import{isNumeric as V}from"../utilities/number.js";import{delay as Q}from"../utilities/promise.js";import{caseInsensitiveEquals as ee}from"../utilities/string.js";import{Feature as te}from"./Feature.js";import{FeatureSet as re}from"./FeatureSet.js";import{DxfEntityProcessor as oe}from"./support/_dxfConverters.js";const ne=["=","-","+","@"],ae='"',ie="\r\n",se="\n",ce=[...C.map(He),"M/d/yy"],le=[...J.map(Je).map((e=>e.replace("AM/PM","tt")))],me=/(\w+)_(point|multipoint|polyline|polygon)z?/;var ue;function fe(){return K("geocortex.api.data.convert")}!function(e){e.DATE="D",e.NUMBER="N",e.STRING="C",e.BOOLEAN="L"}(ue||(ue={}));export const FIELD_NAME_REGEX=/[^a-zA-Z\d_]/g;export var GeometryFormat;!function(e){e.NONE="NONE",e.WKT="WKT",e.XY="XY",e.XYZ="XYZ",e.LAT_LON="LAT_LONG",e.GEO_JSON="GEO_JSON",e.ARCGIS_JSON="ARCGIS_JSON"}(GeometryFormat||(GeometryFormat={}));export const geometryTypeHeaders={[GeometryFormat.XYZ]:[["x","y","z"]],[GeometryFormat.XY]:[["x","y"]],[GeometryFormat.LAT_LON]:[["latitude","longitude"],["lat","lon"],["lat","long"]],[GeometryFormat.ARCGIS_JSON]:[["geometry"]],[GeometryFormat.GEO_JSON]:[["geometry"]],[GeometryFormat.WKT]:[["geometry"]]};const ye=[[GeometryFormat.ARCGIS_JSON,Ie],[GeometryFormat.GEO_JSON,Ge],[GeometryFormat.WKT,_e]],pe=new Map(ye);export async function uploadDataToFeatureSet(e){const t=await async function(e){const{data:t,includeHeaderRow:o,geometryFormat:n,geometryFields:a,locale:i,numberFormat:s,inSpatialReference:c}=e,l=o?t.slice(1):t;if(n===GeometryFormat.NONE)return{columnIndices:[]};const m=e=>ve(e,i,s),u=(e,t)=>{const o=t===GeometryFormat.XYZ,n=t===GeometryFormat.LAT_LON;return{columnIndices:e,geometries:l.map((t=>{if(t.length>=Math.max(...e)&&V(t[e[0]]?.raw,i)&&V(t[e[1]]?.raw,i)&&(!o||V(t[e[2]]?.raw,i)))return new r({x:m(n?t[e[1]].raw:t[e[0]].raw),y:m(n?t[e[0]].raw:t[e[1]].raw),z:o?m(t[e[2]].raw):0,spatialReference:c})}))}},f=async(e,t)=>({columnIndices:[e],geometries:await Promise.all(l.map((t=>t[e])).map((e=>{if(e?.raw)return t(e.raw.toString(),c)})))}),y=async(e,t)=>{switch(t){case GeometryFormat.NONE:return{columnIndices:[0]};case GeometryFormat.LAT_LON:case GeometryFormat.XYZ:case GeometryFormat.XY:return u(e,t);case GeometryFormat.ARCGIS_JSON:return f(e[0],Ie);case GeometryFormat.GEO_JSON:return f(e[0],Ge);case GeometryFormat.WKT:return f(e[0],_e);default:return x(t,new Error(`Unknown geometry format "${t}".`))}};if(n){const e=Ce(o?t[0]:t[0].map(((e,t)=>({raw:t.toString()}))),n,o?a:a.map((e=>""+(parseInt(e.match(/\d+/g)[0])-1))));if(o&&void 0===e)throw new Error(`Error parsing file data: Expected geometry columns ${geometryTypeHeaders[n][0].join(",")} are missing for GeometryType.${n}`);return y(e??[0],n)}const[p,d]=await Pe(t,c,o);if(p===GeometryFormat.NONE)return{columnIndices:[]};return d.length>1?u(d,p):f(d[0],pe.get(p))}(e),o=function(e,t){const{data:r,displayField:o,includeHeaderRow:n,inSpatialReference:a,outSpatialReference:i,generatePrimaryKey:s}=e,c={fields:[]},l=e=>!(!t.columnIndices||0===t.columnIndices.length)&&t.columnIndices.includes(e);let{primaryKeyField:m}=e,u=0;for(let t=0;t<r[0].length;t++){if(l(t))continue;const o=Ue(e,t,!s&&!m&&!c.fields.find((e=>"esriFieldTypeOID"===e.type)));let a=r[0][t]?.raw?.toString(),i=a?.replace(FIELD_NAME_REGEX,"_");n&&i||(i="field"+ ++u,a=F("gcx.api.data.convert.import-field-alias",u)),c.fields.push({alias:a,name:i,type:o}),"esriFieldTypeOID"===o&&(m=i)}if(c.spatialReference=i??t.geometries?.[0]?.spatialReference??a,t.geometries?.length){const e=t.geometries.filter((e=>void 0!==e)).map((e=>e.type)),r=e[0];c.geometryType=e.every((e=>e===r))?h(r):void 0}if(!c.fields.find((e=>"esriFieldTypeOID"===e.type))){const e=c.fields.length+1,t=!!c.fields.find((e=>"objectid"===e.name.toLowerCase()));m=t?`OBJECTID_${e}`:"OBJECTID",c.fields.push({name:m,alias:m,type:"esriFieldTypeOID"})}return c.displayField=o??c.fields.find((e=>!ee(e.name,m)&&"esriFieldTypeString"===e.type))?.name??c.fields.find((e=>!ee(e.name,m)))?.name??m,c.primaryKeyField=m,c}(e,t),n=await async function(e,t,r){const{data:o,includeHeaderRow:n,outFields:a,escapeFormulaChars:i,locale:s,numberFormat:c,dateFormat:l,timeFormat:m}=e,{spatialReference:u}=r,f=[],y=n?o.slice(1):o,p=(e,r)=>!t.columnIndices||0===t.columnIndices.length||!t.columnIndices.includes(r);return await Promise.all(y.map((async(e,o)=>{const n=new te;for(let t=0;t<r.fields.length;t++){const u=r.fields[t],f=e.filter(p);if(a.includes("*")||a.filter((e=>ee(e,u.name))).length>0){let e=await $e(f[t]?.raw,u,{escapeFormulaChars:i,dateFormat:l,numberFormat:c,timeFormat:m,locale:s});"esriFieldTypeOID"===u.type&&null===e&&(e=o),n.attributes.set(u.name,e)}}t.geometries&&(n.geometry=await Oe(t.geometries[o],u)),f.push(n)}))),f}(e,t,o);return new re({features:n,schema:o})}export async function toCsv(e,t){b("featureSet",e).isNotMissing();const r=Array.from(e),o={...{useFormattedValues:!1,alwaysQuote:!1,escapeFormulaChars:!0,delimiter:",",dateFormat:v.ROUND_TRIP,timeFormat:j.ROUND_TRIP,geometryFormat:r.some((e=>void 0!==e.geometry&&null!==e.geometry))?GeometryFormat.WKT:GeometryFormat.NONE,includeByteOrderMark:!0,outSpatialReference:a.WGS84,includeHeaderRow:!0,outFields:Te(e.source),rowDelimiter:navigator.platform?.startsWith("Win")?ie:"\n"},...t},{includeByteOrderMark:n,includeHeaderRow:i,delimiter:s,outFields:c,rowDelimiter:l}=o,m=[];n&&m.push("\ufeff");const u=Fe(r,o),f=Se(r,c,e.schema,!0),y=Se(r,c,e.schema,!1);if(i){const e=[];for(const t of u)e.push(De(t,o));for(const t of f)e.push(De(t,o));for(const t of y)e.push(De(t,o));const t=e.join(s)+l;m.push(t)}await Promise.all(r.map((async e=>{const t=[],r=(t,r)=>{const o=xe(e,t,r),n=e.schema.findFieldByName(t)?.type;return De(be(o,{...r,isDateOnly:"date-only"===n}),r)};t.push(...await async function(e,t){let r=await Ne(e,t);t.geometryFormat!==GeometryFormat.XYZ&&t.geometryFormat!==GeometryFormat.XY&&t.geometryFormat!==GeometryFormat.LAT_LON||(r=r.map((e=>void 0===e?"":be(e,t))));return r.map((e=>""===e?"":De(e,t)))}(e.geometry,o)),t.push(...f.map((e=>r(e,o)))),t.push(...y.map((e=>r(e,o))));const n=`${t.join(s)}${l}`;m.push(n)})));return new Blob(m,{type:"text/plain",endings:"\n"===l||l===ie?"transparent":"native"})}export async function csvToUploadData(e,t){let r;if(b("csvData",e).isNotMissing(),e instanceof Blob){const t=new Promise(((t,r)=>{const o=new FileReader;o.onload=()=>{t(o.result)},o.onerror=()=>{r(o.error)},o.readAsText(e)}));r=await t}else r=e;const o=ge(t),n=o.rowDelimiter||function(e){let t=se;return Ae(e,ie,((r,o)=>(0===r&&o===e.length||(t=ie),!1))),t}(r),a=o.delimiter??function(e,t,r){const o=",";if(0===e.length)return o;const n=[];if(Ae(e,t,((t,r)=>(r!==e.length||t!==r)&&(n.push(e.substring(t,r)),n.length<3))),0===n.length)return o;let a=[{delimiter:",",rowsDelimiterOccurrences:[],rowsNumberAdjacentOccurrences:[]},{delimiter:";",rowsDelimiterOccurrences:[]},{delimiter:"|",rowsDelimiterOccurrences:[]},{delimiter:"\t",rowsDelimiterOccurrences:[]},{delimiter:" ",rowsDelimiterOccurrences:[]}].filter((e=>n[0].includes(e.delimiter)));if(0===a.length)return o;for(const e of n)for(const t of a){let o=0,n=0;Ae(e,t.delimiter,((a,i)=>{if(i!==e.length&&o++,","===t.delimiter){const t=e.charAt(i-1),o=e.charAt(i+1);V(t,r)&&V(o,r)&&n++}return!0})),t.rowsDelimiterOccurrences.push(o),","===t.delimiter&&t.rowsNumberAdjacentOccurrences.push(n)}if(a=a.filter((e=>e.rowsDelimiterOccurrences.every((t=>e.rowsDelimiterOccurrences[0]===t)))).sort(((e,t)=>t.rowsDelimiterOccurrences[0]-e.rowsDelimiterOccurrences[0])),a.length>1&&","===a[0].delimiter&&null!=r&&r!==S){const e=a[0];if(null!=e&&","===e.delimiter&&","===Intl.NumberFormat(r).formatToParts(1.1).find((e=>"decimal"===e.type))?.value)for(let t=0;t<e.rowsDelimiterOccurrences.length;t++)if(e.rowsDelimiterOccurrences[t]<=e.rowsNumberAdjacentOccurrences[t]){a=a.filter((e=>","!==e.delimiter));break}}if(0===a.length)return o;return a[0].delimiter}(r,n,t.locale),i=function(e,t,r){const o=[],n=(e,t)=>{const o=[];return Ae(e,r,((r,n)=>{const a=e.substring(r,n);return o.push({raw:Re(a,t,o.length)}),!0})),o};if(Ae(e,t,((t,r)=>{const a=e.substring(t,r);return a.length>0&&o.push(n(a,o.length)),!0})),o.length){const e=o[0].length;o.forEach(((t,r)=>{if(t.length!==e)throw new Error(`Detected invalid CSV: Row ${r} does not have expected number of columns: ${e}`)}))}return o}(r,n,a);let{geometryFormat:s,geometryFields:c}=t;if(!s){const[e,t]=await Pe(i,o.inSpatialReference,o.includeHeaderRow);s=e,c=t.map((e=>o.includeHeaderRow?i[0][e]?.raw??F("gcx.api.data.convert.import-field-alias",(e+1).toString()):F("gcx.api.data.convert.import-field-alias",(e+1).toString())))}return{data:i,...o,geometryFormat:s,geometryFields:c}}export async function csvToFeatureSet(e,t){const r=ge(t);return uploadDataToFeatureSet(await csvToUploadData(e,r))}export async function toXLSX(e,t){b("featureSet",e).isNotMissing();const r=Array.from(e),o={...{useFormattedValues:!1,includeHeaderRow:!0,escapeFormulaChars:!0,geometryFormat:r.some((e=>void 0!==e.geometry&&null!==e.geometry))?GeometryFormat.WKT:GeometryFormat.NONE,outFields:Te(e.source),outSpatialReference:a.WGS84,dateFormat:v.DEFAULT,timeFormat:j.DEFAULT,numberFormat:P.DEFAULT,sheetName:"sheet1"},...t},{outFields:n,includeHeaderRow:i,dateFormat:s,timeFormat:c,numberFormat:l}=o,m=Fe(r,o),u=Se(r,n,e.schema,!0),f=Se(r,n,e.schema,!1),y=await import("xlsx"),p=y.utils.sheet_new();let d=!1;if(i){const t=m.concat(u).concat(function(e,t){const r=t?.schema?.fieldExtensions.initializedItems.map((e=>e.field));return e.map((e=>r?.find((t=>ee(t.name,e)))?.alias??e))}(f,e.source));d=!0,y.utils.sheet_add_aoa(p,[t],{cellDates:!0})}await Promise.all(r.map((async e=>{const t=[],r=new Set,n=new Set;t.push(...await Ne(e.geometry,o));for(const r of u){const n=ke(e.attributes.get(r),o);t.push(n)}for(const a of f){const i=xe(e,a,o);if(i instanceof D){const o=e.schema.findFieldByName(a);"time-only"===o?.type&&r.add(t.length)}else if(i instanceof Date){const r=e.schema.findFieldByName(a);"date-only"===r?.type&&n.add(t.length)}const s=ke(i,o);t.push(s)}if(!t.every((e=>"string"!=typeof e||e.length<=32767)))return void fe().warn(`toXLSX cell limit exceeded, feature (${e.primaryKey??e.id}) omitted.`);y.utils.sheet_add_aoa(p,[t],{cellDates:!0,origin:d?-1:void 0}),d=!0;const a=y.utils.decode_range(p["!ref"]);for(let e=a.s.c;e<=a.e.c;e++){const t=p[y.utils.encode_cell({r:a.e.r,c:e})];"d"===t.t?r.has(e)?t.z=Je(c??j.ROUND_TRIP):n.has(e)?t.z=Be(s??v.ROUND_TRIP):t.z=He(s??v.ROUND_TRIP):"n"===t.t&&(t.z=ze(l))}})));const g={SheetNames:[],Sheets:{}};g.SheetNames.push(o.sheetName),g.Sheets[o.sheetName]=p;const w=y.write(g,{type:"binary",bookType:"xlsx",compression:!0,bookSST:!0,cellDates:!0}),h=new Uint8Array(w.length);for(let e=0;e<w.length;e++)h[e]=w.charCodeAt(e);return new Blob([h.buffer],{type:"text/plain"})}export async function xlsxToUploadData(e,t){b("xlsxData",e).isNotMissing();const r=we(t),o=await async function(e,t){const r=await import("xlsx"),o=new Promise(((o,n)=>{const a=new FileReader;a.onload=()=>{const e=new Uint8Array(a.result);let n="";for(const t of e)n+=String.fromCharCode(t);const i=r.read(n,{type:"binary",cellDates:!0}),s=t.sheetName||i.SheetNames[0],c=i.Sheets[s];o(c)},a.onerror=()=>{n(a.error)},a.readAsArrayBuffer(e)})),n=await o,a=r.utils.decode_range(n["!ref"]),i=[];for(let e=a.s.r;e<=a.e.r;e++){const t=[];for(let o=a.s.c;o<=a.e.c;o++){const a=n[`${r.utils.encode_cell({r:e,c:o})}`];a&&"d"===a.t&&a.v instanceof Date&&(a.v=new Date(a.v.getTime()+6e4*a.v.getTimezoneOffset())),t.push(a?{raw:a.v,formatted:"s"===a.t?void 0:a.w}:{raw:""})}i.push(t)}return i}(e,r);let{geometryFormat:n,geometryFields:a}=t;if(!n){const[e,t]=await Pe(o,r.inSpatialReference,r.includeHeaderRow);n=e,a=t.map((e=>r.includeHeaderRow?o[0][e]?.raw.toString()??F("gcx.api.data.convert.import-field-alias",(e+1).toString()):F("gcx.api.data.convert.import-field-alias",(e+1).toString())))}return{data:o,...r,geometryFormat:n,geometryFields:a}}export async function xlsxToFeatureSet(e,t){b("xlsxData",e).isNotMissing();const r=we(t);return uploadDataToFeatureSet(await xlsxToUploadData(e,r))}export function kmlHexToEsriColor(t){return e.fromHex(`#${t.match(/.{2}/g).reverse().join("")}`)}export function parseKMLCoordinates(e){return e.trim().split(/\s+/).map((e=>{const[t,r,o]=e.split(",").map(Number);return{x:t,y:r,z:o}}))}export function parseKMLSymbol(t,r,o){if(t){const r=t.querySelector("IconStyle > Icon > href")?.textContent;if(r)return new y({url:r,width:32,height:32});const o=t.querySelector("PolyStyle");if(o){const t=o.querySelector("color")?.textContent,r=t?kmlHexToEsriColor(t):new e([0,0,0,1]);return new p({color:r,outline:{color:[0,0,0,.5],width:1}})}const n=t.querySelector("LineStyle");if(n){const t=n.querySelector("color")?.textContent,r=t?kmlHexToEsriColor(t):new e([0,0,0,1]),o=parseFloat(n.querySelector("width")?.textContent||"1");return new d({color:r,width:o})}}return getDefaultSymbol(o,"polygon"===r?"polygon":"point"===r?"point":"polyline")}export async function toShapefile(e,t){b("featureSet",e).isNotMissing();const[{default:r},o]=await Promise.all([import("jszip"),import("../forked-libs/shp-write/index.js")]),n=Array.from(e),i={...{useFormattedValues:!1,outFields:Te(e.source),fileName:e.title||"export"},...t},{outFields:s,outSpatialReference:c,fileName:l}=i,m=e=>e.geometry.hasZ||e.geometry.hasM,u=new Map,f=n.filter((e=>M(e.geometry)));u.set("POINTZ",f.filter(m)),u.set("POINT",f.filter((e=>!m(e))));const y=n.filter((e=>E(e.geometry)));u.set("MULTIPOINTZ",y.filter(m)),u.set("MULTIPOINT",y.filter((e=>!m(e))));const p=n.filter((e=>R(e.geometry)));u.set("POLYLINEZ",p.filter(m)),u.set("POLYLINE",p.filter((e=>!m(e))));const d=n.filter((e=>A(e.geometry)||I(e.geometry)));u.set("POLYGONZ",d.filter(m)),u.set("POLYGON",d.filter((e=>!m(e))));const g=Se(n,s,e.schema,!0);let w=Se(n,s,e.schema,!1);w=g.concat(w);const h=new r,F=Array.from(u.keys()).filter((e=>u.get(e).length>0));await Promise.all(F.map((async t=>{const r=u.get(t),n=await Promise.all(r.map((e=>Oe(e.geometry,c)))),s=await async function(e){const{wkid:t,wkt:r}=e[0].spatialReference;if(!e.every((e=>e.spatialReference.wkid===t&&e.spatialReference.wkt===r)))throw new Error("Cannot create shapefile that contains geometries with different spatial references.");return r??await X(t??a.WGS84.wkid)}(n),m=i.useFormattedValues?Object.assign({},...w.map((e=>({[e]:ue.STRING})))):function(e,t,r,o){const n={};for(const a of t){if(e.some((e=>Me(e,a)))){n[a]=ue.STRING;continue}const t=r?r.fields.find((e=>ee(e.name,a))):void 0;if(t){switch(t.type){case"oid":case"double":case"integer":case"single":case"small-integer":case"big-integer":n[a]=ue.NUMBER;break;case"date":case"timestamp-offset":n[a]=o?ue.NUMBER:ue.DATE;break;default:n[a]=ue.STRING}continue}const i=(e,t)=>e.attributes.get(t)??e.presentableAttributes.get(t);e.every((e=>i(e,a)instanceof Date||void 0===i(e,a)))&&e.some((e=>i(e,a)instanceof Date))?n[a]=o?ue.NUMBER:ue.DATE:e.every((e=>"number"==typeof i(e,a)||void 0===i(e,a)))&&e.some((e=>"number"==typeof i(e,a)))?n[a]=ue.NUMBER:e.every((e=>"boolean"==typeof i(e,a)||void 0===i(e,a)))&&e.some((e=>"boolean"==typeof i(e,a)))?n[a]=ue.BOOLEAN:n[a]=ue.STRING}return n}(r,w,e.schema,"timestamp"===i.dateFormat),f=function(e){return e.map((e=>{if(M(e)){const{x:t,y:r,z:o,m:n}=e,a=[t,r];return e.hasZ&&a.push(o),e.hasM&&a.push(n),We(a,e)}if(E(e))return Xe(e.points,e);if(R(e))return qe(e.paths,e);if(A(e))return qe(e.rings,e);if(I(e)){const t=[e.xmin,e.ymax];return[[t,[e.xmax,e.ymax],[e.xmax,e.ymin],[e.xmin,e.ymin],t]]}throw new Error("Unsupported geometry type.")}))}(n),y=function(e,t,r,o){const n=[];for(const a of e){const e={};for(const n of t){let t=xe(a,n,o);if(null==t&&(t=""),o.useFormattedValues)t=t.toString();else{t=Ye(t,r[n],{...o,isDateOnly:"date-only"===a.schema.findFieldByName(n)?.type})}e[n.replaceAll(".","_")]=t}n.push(e)}return n}(r,w,m,i);o.write(y,t,f,((e,r)=>{const o=F.length>1?`${l}_${t.toLowerCase()}`:l;h.file(`${o}.shp`,r.shp.buffer,{binary:!0}),h.file(`${o}.shx`,r.shx.buffer,{binary:!0}),h.file(`${o}.dbf`,r.dbf.buffer,{binary:!0}),h.file(`${o}.prj`,s)}))})));const S=await h.generateAsync({type:"uint8array"});return new Blob([S.buffer],{type:"text/plain"})}export async function kmlToLayerExtensions(e){b("blob",e).isNotMissing();const a=await e.text(),l=(new DOMParser).parseFromString(a,"application/xml"),m=function(e,a,u=!1){const f={};l.querySelectorAll("Style").forEach((e=>{f[`#${e.id}`]=e}));const y=e.querySelector(":scope > name")?.textContent??"Unnamed Container",p=new Map;e.querySelectorAll(":scope > Placemark").forEach(((e,i)=>{const s=e.querySelector("name")?.textContent??"",c=e.querySelector("description")?.textContent??"",l=function(e){const t=e.querySelector("Point > coordinates"),a=e.querySelector("LineString > coordinates"),i=e.querySelector("Polygon");if(t?.textContent){const[e]=parseKMLCoordinates(t.textContent.replace(/ /g,""));return new r(e)}if(a?.textContent)return new n({paths:[parseKMLCoordinates(a.textContent).map((({x:e,y:t})=>[e,t]))]});if(i?.textContent){const e=i.querySelector("outerBoundaryIs > LinearRing > coordinates");if(e?.textContent){const t=[parseKMLCoordinates(e.textContent).map((({x:e,y:t})=>[e,t]))];return new o({rings:t})}}return}(e);if(l?.type){const r=e.querySelector("styleUrl")?.textContent,o=parseKMLSymbol(r?f[r]:e.querySelector("Style"),l.type,a);p.has(l.type)||p.set(l.type,{graphics:[],symbols:[]});let n=function(e,t){for(let r=0;r<e.length;r++)if(Ze(e[r],t))return r;return-1}(p.get(l.type).symbols,o);-1===n&&(p.get(l.type).symbols.push(o),n=p.get(l.type).symbols.length-1),p.get(l.type).graphics.push(new t({geometry:l,attributes:{name:s,description:c,SymbolID:n,OBJECTID:y+i}}))}}));const d=e.querySelectorAll(":scope > Folder, :scope > Document");if(u||1!==p.size||0!==d.length){const e=new N({layer:new s({title:y})});return p.forEach(((t,r)=>{const o=new i({displayField:"name",title:`${r.slice(0,1).toUpperCase()+r.slice(1)}s`,source:t.graphics,renderer:Ke(t.symbols),fields:[new c({name:"OBJECTID",type:"oid",alias:"OBJECTID"}),new c({name:"SymbolID",type:"integer",alias:"SymbolID",editable:!1}),new c({name:"name",type:"string",alias:"name"}),new c({name:"description",type:"string",alias:"description",defaultValue:""})]}),n=new T({layer:o});e.layerExtensions.add(n)})),d.forEach(((t,r)=>{const o=m(t,r);e.layerExtensions.add(o)})),e}{const e=[...p.values()][0],t=new i({displayField:"name",title:y,source:e.graphics,renderer:Ke(e.symbols),fields:[new c({name:"OBJECTID",type:"oid",alias:"OBJECTID"}),new c({name:"SymbolID",type:"integer",alias:"SymbolID",editable:!1}),new c({name:"name",type:"string",alias:"name"}),new c({name:"description",type:"string",alias:"description",defaultValue:""})]});return new T({layer:t})}},u=[];return l.querySelectorAll("kml > Document, kml > Folder").forEach(((e,t)=>{const r=m(e,t,!0);r.layerExtensions.length&&u.push(r)})),u}export async function dxfToLayerExtensions(e,t,r){const{inputSpatialReference:o,outputSpatialReference:n}=t;b("options.dxfBlob",e).isNotMissing(),b("options.inputSpatialReference",o).isNotMissing(),b("options.outputSpatialReference",n).isNotMissing();const a=new oe(o,n,r),i=a.getContext(),c=await e.text(),l=new w;await Q();try{const e=l.parseSync(c);if(!e)throw new Error("DXF parsing failed: parser returned null");i.dxf=e}catch(e){throw e instanceof Error?e:new Error(String(e))}const m=e instanceof File?e.name:"dxf-layer",u=m.replace(/[^a-zA-Z0-9_.-]/g,"_");if(i.fileName=m,i.sanitizedFileName=u,i.subLayers=await a.processAll(),!i.subLayers||0===i.subLayers.length)return[];const f=new s({id:`dxf-group-${u}-${(new Date).getTime()}`,title:m,visible:!0}),y={layer:f,visibilityMode:"independent"};return f.layers.addMany(i.subLayers),[new N(y)]}export async function shapefileToUploadData(e,t){b("shapefileData",e).isNotMissing();const o=he(t),n=new Promise(((t,r)=>{const o=new FileReader;o.onload=()=>{t(o.result)},o.onerror=()=>{r(o.error)},o.readAsArrayBuffer(e)})),[{default:i},{default:s}]=await Promise.all([import("jszip"),import("shpjs")]),c=await n,l=await i.loadAsync(new Uint8Array(c)),m=new O;l.forEach(((e,t)=>{t&&m.set(t.name,t)}));const u=l.filter((()=>!0)).map((e=>e.name));let f,y=u.filter((e=>e.endsWith(".shp"))).map((e=>e.substring(0,e.length-4)));if(y=function(e){if(!e.length)return[];let t=e[0];const r=t.match(me);return r?(t=r[1],e.filter((e=>{const r=e.match(me);return r&&r[1]===t}))):[t]}(y),u.some((e=>e.endsWith(".prj")))&&!y.every((e=>m.has(`${e}.prj`))))throw new Error("Shapefile zip must contain the same prj file for each separate shapefile");await Promise.all(u.filter((e=>e.endsWith(".prj"))).map((async e=>{const t=await l.file(e).async("string");if(f){if(t!==f)throw new Error("Shapefile zip must contain the same prj file for each separate shapefile")}else f=t})));let p=[],d=[];for(const e of y){if(!m.has(`${e}.shp`)||!m.has(`${e}.shx`)||!m.has(`${e}.dbf`))throw new Error("Shapefile must contain shp, shx, and dbf files.");const t=s.parseShp(await m.get(`${e}.shp`).async("uint8array")),r=s.parseDbf(await m.get(`${e}.dbf`).async("uint8array"));if(r.length!==t.length)throw new Error("Shapefile must contain shp, shx, and dbf files.");p=p.concat(r),d=d.concat(t)}const g=await Promise.all(d.map((e=>async function(e,t){const o=M(e)?function(e){b("geometry.coordinates",e.type).matches("Point"),b("geometry.coordinates",e.coordinates).satisfies((e=>"number"==typeof e||Array.isArray(e)));const[t,o,n]=e.coordinates,i=new r({x:t,y:o,spatialReference:a.WGS84});if(Array.isArray(n)){const[e,t]=n;!e&&!t||e?i.z=e:i.m=t}return i}(e):await Z(e);if(t){let e;try{const r=await q(t);e=new a({wkid:U(r)})}catch{}e||(e=new a({wkt:t})),o.spatialReference=e}return o}(e,f)))),w=geometryTypeHeaders[GeometryFormat.ARCGIS_JSON][0][0];p.forEach(((e,t)=>e[w]=JSON.stringify(g[t].toJSON())));return{data:function(e){const t=e.map((e=>Object.keys(e))).reduce(((e,t)=>e.concat(t.filter((t=>!e.includes(t))))),[]);return[t.map((e=>({raw:e}))),...e.map((e=>t.map((t=>({raw:e[t]})))))]}(p),...o,includeHeaderRow:!0,geometryFormat:GeometryFormat.ARCGIS_JSON,geometryFields:[w],inSpatialReference:g[0]?.spatialReference??a.fromJSON({wkid:4326})}}export async function shapefileToFeatureSet(e,t){b("shapefileData",e).isNotMissing();const r=he(t);return uploadDataToFeatureSet(await shapefileToUploadData(e,r))}export function getDefaultSymbol(e,t){const r=e%8;let o=["#FFDBFF","#88D6FF","#7F9FC3","#FF8200","#F34A53","#76E3B9","#E7BFFF","#FFC467"][r],n=["#EF3786","#005A99","#2D5070","#790C00","#4C0000","#006543","#6244A9","#904200"][r];if(Math.floor(e/8)%2!=0){const e=o;o=n,n=e}switch(t){case"point":case"multipoint":return new g({color:o,outline:{color:n}});case"polyline":return new d({color:o,width:"2"});case"polygon":return new p({color:o,outline:{color:n}});case"mesh":return new f({symbolLayers:[{type:"fill",material:{color:o},outline:{color:n}}]})}}function de(e){return{escapeFormulaChars:!0,outFields:["*"],generatePrimaryKey:!1,locale:S,detectOid:!e?.primaryKeyField}}function ge(e){return{...{includeHeaderRow:!0,inSpatialReference:a.WGS84,...de(e)},...e}}function we(e){return{...{includeHeaderRow:!0,inSpatialReference:a.WGS84,...de(e)},...e}}function he(e){return{...{...de(e)},...e}}function Fe(e,t){return t.geometryFormat===GeometryFormat.XYZ?["x","y","z"]:t.geometryFormat===GeometryFormat.XY?["x","y"]:t.geometryFormat===GeometryFormat.LAT_LON?["latitude","longitude"]:t.geometryFormat===GeometryFormat.NONE?[]:["geometry"]}function Se(e,t,r,o){const n=r.fields.filter((e=>"oid"===e.type)).map((e=>e.name)).toArray();if(o)return n;if(t&&!t.includes("*"))return t.filter((e=>!n.includes(e)));{const t=r.fields.filter((e=>"oid"!==e.type)).map((e=>e.name)).toArray();let o=[];for(const r of e)for(const e of r.attributes.keys())t.includes(e)||n.includes(e)||o.includes(e)||o.push(e);return o=o.sort(),t.concat(o)}}function Te(e){if(!e)return["*"];const t=e.featureSettings.popupTemplate?.content;if(Array.isArray(t)){const e=new Set;for(const r of t)if("fields"===r.type&&Array.isArray(r.fieldInfos))for(const t of r.fieldInfos)t.visible&&e.add(t.fieldName);if(e.size>0)return Array.from(e)}const r=e.featureSettings.popupTemplate?.fieldInfos;if(Array.isArray(r)){const e=[];for(const t of r)t.visible&&e.push(t.fieldName);if(e.length>0)return e}return["*"]}async function Ne(e,t){const r=await Oe(e,t.outSpatialReference);if(t.geometryFormat===GeometryFormat.XYZ){if(!r)return["","",""];if(!M(r))throw new Error("Cannot use geometry format XYZ with non-point geometry");return[r.x,r.y,r.z]}if(t.geometryFormat===GeometryFormat.XY){if(!r)return["",""];if(!M(r))throw new Error("Cannot use geometry format XY with non-point geometry");return[r.x,r.y]}if(t.geometryFormat===GeometryFormat.LAT_LON){if(!r)return["",""];if(!M(r))throw new Error("Cannot use geometry format LAT_LONG with non-point geometry");return[r.y,r.x]}return t.geometryFormat===GeometryFormat.ARCGIS_JSON?r?[JSON.stringify(r.toJSON())]:[""]:t.geometryFormat===GeometryFormat.WKT?r?[await k(r)]:[""]:t.geometryFormat===GeometryFormat.GEO_JSON?r?[JSON.stringify(await Y(r))]:[""]:[]}async function Oe(e,t){return e?.spatialReference&&!e.spatialReference.equals(t)&&t?(await z([e],t))[0]:e}function De(e,t){const r=[t.delimiter,ae,"\r","\n",t.rowDelimiter];if(t.alwaysQuote||r.some((t=>e.includes(t)))){const t=e.replace(new RegExp(ae,"g"),`${ae}${ae}`);return`${ae}${t}${ae}`}return e}function be(e,t){if(null==e)return"";if(!t.useFormattedValues){if("number"==typeof e){const r=t.numberFormat||P.ROUND_TRIP;return $(r,e)}if(e instanceof Date)return"timestamp"===t.dateFormat?e.getTime().toString():_({format:t.dateFormat,timeZone:"UTC",isDateOnly:t.isDateOnly},e);if(e instanceof D)return B({format:t.timeFormat},e)}let r=e.toString();return t.escapeFormulaChars&&(r=Ee(r)),r}function xe(e,t,r){if(r.useFormattedValues||Me(e,t))return e.presentableAttributes.get(t)??e.attributes.get(t);const o=e.schema.findFieldByName(t)?.type;if(null!=o)switch(o){case"date":case"date-only":case"timestamp-offset":{const r=G(e.attributes.get(t));if(!isNaN(r.getTime()))return r;break}case"time-only":{const r=H(e.attributes.get(t));if(r.isValid)return r;break}}return e.attributes.get(t)??e.presentableAttributes.get(t)}function Me(e,t){return!!ee(t,e.schema.typeIdField)||("coded-value"===e.type?.domains?.[t]?.type||"coded-value"===e.schema.findFieldByName(t)?.domain?.type)}function Ee(e){for(const t of ne)if(e.startsWith(t))return`\t${e}`;return e}function Re(e,t,r){const o=e.startsWith(ae),n=e.endsWith(ae);if(o&&!n||!o&&n)throw new Error(`Detected invalid CSV: Missing opening or closing quote for value at row:${t} column:${r}`);const a=o?e.substring(1,e.length-1):e;let i=-1;return Ae(a,ae,((e,o)=>{if(o===a.length)return!0;if(i<0){if(o!==a.length)return i=o,!0}else if(o===i+1)return i=-1,!0;throw new Error(`Detected invalid CSV: Non-escaped quote for value at row:${t} column:${r}`)})),a.replace(new RegExp(`${ae}${ae}`,"g"),ae)}function Ae(e,t,r){let o,n=!1,a=0,i=0;for(;o=e.indexOf(t,a),!(o<0);){for(let t=a;t<o;)e.substring(t).startsWith(ae)?(n=!n,t+=1):t++;const s=o+t.length;if(!n){const e=r(i,o);if(i=s,!e)return}a=s}r(i,e.length)}async function Ie(e,t){const r=JSON.parse(e),o=(await import("@arcgis/core/geometry/support/jsonUtils")).fromJSON(r);return r.spatialReference||(o.spatialReference=t),o}async function Ge(e,t){const r=await Z(JSON.parse(e));return r.spatialReference=t,r}async function _e(e,t){const r=await W(e);return r.spatialReference=t,r}function Ce(e,t,r){const o=r?[r]:geometryTypeHeaders[t];for(const t of o){const r=t.map((t=>e.map((e=>e?.raw?.toString().trim().toLowerCase())).indexOf(t.trim().toLowerCase())));if(r.every((e=>e>=0)))return r}}async function Le(e,t){return(await Promise.all(e.map((async(e,r)=>{const o=e?.raw;if("string"==typeof o&&""!==o)try{return await t(o,void 0),r}catch{return}})))).find((e=>void 0!==e))}function ve(e,t,r){return"inv"===t?"string"==typeof e?parseFloat(e.replaceAll(",","")):e:U({locale:t,format:r},e)}async function Pe(e,t,r){const o=r?e.slice(1):e;if(r){const r=Ce(e[0],GeometryFormat.ARCGIS_JSON);if(void 0!==r)for(const[e,n]of ye){try{await je(r[0],n,t,o)}catch{continue}return[e,[r[0]]]}const n=[GeometryFormat.XYZ,GeometryFormat.XY,GeometryFormat.LAT_LON];for(const t of n){const r=Ce(e[0],t);if(void 0!==r)return[t,r]}}for(const[e,r]of ye){const n=await Le(o[0],r);if(void 0!==n){try{await je(n,r,t,o)}catch{continue}return[e,[n]]}}return[GeometryFormat.NONE,[]]}async function je(e,t,r,o){return{columnIndices:[e],geometries:await Promise.all(o.map((t=>t[e])).map((e=>{if(e?.raw)return t(e.raw.toString(),r)})))}}function Ue(e,t,r){let o=!1,n=!0,a=!0,i=!0,s=!0,c=!0;const l=new Set,{data:m,includeHeaderRow:u,dateFormat:f,timeFormat:y,primaryKeyField:p,locale:d}=e,g=u?m[0]:[],w=u?m.slice(1):m;for(const e of w){const r=e[t];r?.raw&&(l.add(r.raw),o=!0,n&&(n=V(r.raw,d)||Number.isNaN(r.raw)),a&&(a=r.raw instanceof Date||G(f||C,r.raw)!==L),s&&(s=G(f||ce,r.formatted)!==L),i&&(i=r.raw instanceof D||H(y||J,r.raw).isValid),c&&(c=H({format:y||le,locale:"en"},r.formatted).isValid))}const h=l.size===w.length;return p&&g[t]?.raw===p||r&&o&&h&&n?"esriFieldTypeOID":o&&c?"esriFieldTypeTimeOnly":o&&s?"esriFieldTypeDate":o&&n?"esriFieldTypeDouble":o&&i?"esriFieldTypeTimeOnly":o&&a?"esriFieldTypeDate":"esriFieldTypeString"}async function $e(e,t,r){const{escapeFormulaChars:o,locale:n,numberFormat:a,dateFormat:i,timeFormat:s}=r;if("esriFieldTypeDouble"===t.type||"esriFieldTypeOID"===t.type)return"number"==typeof e?e:e?ve(e,n,a):null;if("esriFieldTypeDate"===t.type){if(e instanceof Date)return e.getTime();if("number"==typeof e){const t=(await import("xlsx")).SSF.parse_date_code(e);return t?new Date(t.y,t.m-1,t.d,t.H,t.M,t.S).getTime():void 0}return""===e?null:G({locale:n,format:i},e).getTime()}if("esriFieldTypeTimeOnly"===t.type){if(e instanceof D)return e.toString();if(e instanceof Date)return new D(e).toString();if("number"==typeof e){const t=(await import("xlsx")).SSF.parse_date_code(e);return t?new D(`${t.H.toString().padStart(2,"0")}:${t.M.toString().padStart(2,"0")}:${t.S.toString().padStart(2,"0")}`).toString():void 0}return""===e?null:H({locale:n,format:s},e).toString()}const c=e?.toString()??"";if(o&&c.startsWith("\t"))for(const e of ne)if(c.length>1&&c.charAt(1)===e)return c.substring(1);return c}function He(e){switch(e){case v.DATE_SHORT:return"dd/MM/yyyy";case v.DATE_LONG:return"MMMM d, yyyy";case v.TIME_SHORT:return"h:mm AM/PM";case v.TIME_LONG:return"h:mm:ss AM/PM";case v.DATE_TIME_SHORT:case v.DEFAULT:return"MMM d yyyy h:mm AM/PM";case v.DATE_TIME_LONG:return"MMMM d yyyy h:mm AM/PM";case v.FULL:return"dddd, MMMM d yyyy h:mm AM/PM";case v.ISO_8601:case v.ROUND_TRIP:return'yyyy-MM-dd"T"HH:mm:ss';default:{const t=e.replace(/tt/g,"AM/PM");return t.includes("z")&&fe().warn("Warning: Excel will not recognize timezone format 'z', 'zz', or 'zzz'"),t.includes("h")&&!t.includes("AM/PM")&&fe().warn("Warning: Excel will interpret 'h' as 'H' if the format does not have an AM/PM designator"),t}}}function Be(e){switch(e){case v.DATE_SHORT:return"dd/MM/yyyy";case v.DATE_LONG:return"MMMM d, yyyy";case v.DATE_TIME_SHORT:case v.DEFAULT:return"MMM d yyyy";case v.DATE_TIME_LONG:return"MMMM d yyyy";case v.FULL:return"dddd, MMMM d yyyy";case v.ISO_8601:case v.ROUND_TRIP:return"yyyy-MM-dd";default:return e.replace(/TtZzHhmSsUua/g,"")}}function Je(e){switch(e){case j.TIME_SHORT:return"h:mm AM/PM";case j.TIME_LONG:return"h:mm:ss AM/PM";case j.ISO_8601:case j.ROUND_TRIP:return"HH:mm:ss";default:{const t=e.replace(/tt/g,"AM/PM");return t.includes("h")&&!t.includes("AM/PM")&&fe().warn("Warning: Excel will interpret 'h' as 'H' if the format does not have an AM/PM designator"),t}}}function ze(e){switch(e){case P.ACCOUNTING:return'_("$"* #,##0.00_);_("$"* (#,##0.00);_("$"* "-"??_);_(@_)';case P.CURRENCY:return'"$"#,##0.00';case P.FIXED_POINT:case P.DEFAULT:return"0.0000";case P.NUMBER:return"#,##0.0000";case P.PERCENT:return"0%";case P.ROUND_TRIP:return"0.00000";default:return e}}function ke(e,t){if(null==e)return"";if(!t.useFormattedValues){if("number"==typeof e)return e;if(e instanceof Date)return"timestamp"===t.dateFormat?e.getTime():e;if(e instanceof D)return e.toDate()}let r=e.toString();return t.escapeFormulaChars&&(r=Ee(r)),r}function We(e,t){return 3===e.length&&!t.hasZ&&t.hasM?[e[0],e[1],void 0,e[2]]:e}function Xe(e,t){return e.map((e=>We(e,t)))}function qe(e,t){return e.map((e=>Xe(e,t)))}function Ye(e,t,r){switch(t){case ue.NUMBER:return e instanceof Date?e.getTime():U(e);case ue.STRING:return e instanceof Date?_({format:r.dateFormat??v.ROUND_TRIP,timeZone:"UTC",isDateOnly:r.isDateOnly},e):e instanceof D?B({format:r.timeFormat??j.ROUND_TRIP},e):"number"==typeof e?$(r.numberFormat??P.DEFAULT,e):e.toString();case ue.BOOLEAN:return!!e;case ue.DATE:return G(e);default:return e.toString()}}function Ze(e,t){return JSON.stringify(e.toJSON())===JSON.stringify(t.toJSON())}function Ke(e){return 1===e.length?new l({symbol:e[0]}):new m({field:"SymbolID",uniqueValueInfos:[...e.map(((e,t)=>new u({label:t.toString(),symbol:e,value:t})))]})}