@arcgis/core 4.26.0-next.20230119 → 4.26.0-next.20230121

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 (98) hide show
  1. package/arcade/ArcadeDate.js +1 -1
  2. package/arcade/Feature.js +1 -1
  3. package/arcade/featureset/support/shared.js +1 -1
  4. package/arcade/featureset/support/sqlUtils.js +1 -1
  5. package/arcade/languageUtils.js +1 -1
  6. package/arcade/lib/arcade-parser.js +1 -1
  7. package/arcade/lib/parser.js +1 -1
  8. package/arcade/lib/scanner.js +1 -1
  9. package/arcade/lib/types.js +1 -1
  10. package/arcade/validation/arcadeValidator.js +1 -1
  11. package/arcade/validation/diagnosticMessages.js +1 -1
  12. package/arcade/validation/languageKeywords.js +5 -0
  13. package/assets/esri/core/workers/RemoteClient.js +1 -1
  14. package/assets/esri/core/workers/chunks/{e6c6e3c9750829ec82c1.js → 09ac51aeb0f6fe16aa30.js} +1 -1
  15. package/assets/esri/core/workers/chunks/293594192932f0e00ecf.js +1 -0
  16. package/assets/esri/core/workers/chunks/4f4064eabbbc4a66f95a.js +1 -0
  17. package/assets/esri/core/workers/chunks/{0417369a1d563a6280ff.js → 63706a04e173000994db.js} +1 -1
  18. package/assets/esri/core/workers/chunks/6a90b1d73d5941ebb112.js +1 -0
  19. package/assets/esri/core/workers/chunks/{0c242aa92ab4f0c996db.js → 70f1fe5f36bc4abff2d2.js} +1 -1
  20. package/assets/esri/core/workers/chunks/96d4c50f74a9c0dcdb66.js +1 -0
  21. package/assets/esri/core/workers/chunks/b26a671d3523b8a48404.js +1 -0
  22. package/assets/esri/core/workers/chunks/{5dfed65b615b33588488.js → db96a2dc1879b4944cb8.js} +1 -1
  23. package/assets/esri/core/workers/chunks/fcf033c581f58d006cf6.js +1 -0
  24. package/assets/esri/core/workers/chunks/{5e872adb3a5e84c49865.js → fde8827bd7f1a97a6db3.js} +1 -1
  25. package/assets/esri/themes/base/widgets/_Editor.scss +9 -14
  26. package/assets/esri/themes/dark/main.css +1 -1
  27. package/assets/esri/themes/light/main.css +1 -1
  28. package/assets/esri/themes/light/view.css +1 -1
  29. package/chunks/languageUtils.js +1 -1
  30. package/core/scheduling.js +1 -1
  31. package/interfaces.d.ts +24 -12
  32. package/layers/StreamLayer.js +1 -1
  33. package/layers/VoxelWasmPerSceneView.js +1 -1
  34. package/layers/graphics/controllers/I3SOnDemandController.js +1 -1
  35. package/layers/graphics/controllers/StreamController.js +1 -1
  36. package/layers/graphics/data/StreamFeatureManager.js +1 -1
  37. package/layers/graphics/sources/connections/GeoEventConnection.js +1 -1
  38. package/layers/graphics/sources/connections/WebSocketConnection.js +1 -1
  39. package/layers/support/FeatureReductionBinning.js +1 -1
  40. package/layers/support/FeatureReductionCluster.js +1 -1
  41. package/layers/support/StreamConnection.js +1 -1
  42. package/layers/support/rasterDatasets/ImageServerRaster.js +1 -1
  43. package/layers/support/rasterFormats/pixelRangeUtils.js +1 -1
  44. package/layers/support/rasterFunctions/rasterProjectionHelper.js +1 -1
  45. package/package.json +1 -1
  46. package/support/revision.js +1 -1
  47. package/views/2d/interactive/editingTools/ControlPointsTransformTool.js +1 -1
  48. package/views/2d/interactive/editingTools/MediaTransformToolsWrapper.js +1 -1
  49. package/views/2d/interactive/editingTools/TransformTool.js +1 -1
  50. package/views/2d/layers/FeatureLayerView2D.js +1 -1
  51. package/views/2d/layers/StreamLayerView2D.js +1 -1
  52. package/views/2d/layers/features/controllers/FeatureController2D.js +1 -1
  53. package/views/2d/layers/features/schemaUtils.js +1 -1
  54. package/views/2d/layers/features/sources/GeoEventSource.js +1 -1
  55. package/views/2d/layers/features/support/FeatureSetReader.js +1 -1
  56. package/views/2d/layers/imagery/BaseImageryTileSubView2D.js +1 -1
  57. package/views/2d/layers/support/FeatureLayerProxy.js +1 -1
  58. package/views/3d/environment/EnvironmentRenderer.js +1 -1
  59. package/views/3d/environment/SceneViewEnvironmentManager.js +1 -1
  60. package/views/3d/layers/DynamicLayerView3D.js +1 -1
  61. package/views/3d/layers/I3SMeshView3D.js +1 -1
  62. package/views/3d/layers/I3SMeshViewLabeler.js +1 -1
  63. package/views/3d/layers/PointCloudLayerView3D.js +1 -1
  64. package/views/3d/layers/PointCloudWorker.js +1 -1
  65. package/views/3d/layers/RouteLayerView3D.js +1 -1
  66. package/views/3d/layers/SceneLayerGraphicsView3D.js +1 -1
  67. package/views/3d/layers/SceneLayerView3D.js +1 -1
  68. package/views/3d/layers/StreamLayerView3D.js +1 -1
  69. package/views/3d/layers/TileLayerView3D.js +1 -1
  70. package/views/3d/layers/i3s/I3SIndex.js +1 -1
  71. package/views/3d/layers/i3s/I3SLodHandling.js +1 -1
  72. package/views/3d/layers/i3s/I3SMaterialUtil.js +1 -1
  73. package/views/3d/layers/i3s/I3SMeshViewFilter.js +1 -1
  74. package/views/3d/layers/i3s/I3SNodeLoader.js +1 -1
  75. package/views/3d/layers/i3s/I3SQueryEngine.js +1 -1
  76. package/views/3d/layers/i3s/PointCloudRendererUtil.js +1 -1
  77. package/views/3d/layers/i3s/PointCloudWorkerUtil.js +1 -1
  78. package/views/3d/layers/support/FeatureTileTree3D.js +1 -1
  79. package/views/3d/layers/support/I3STreeDebugger.js +1 -1
  80. package/views/3d/layers/support/SceneLayerViewRequiredFields.js +1 -1
  81. package/views/3d/terrain/TerrainSurface.js +1 -1
  82. package/views/3d/webgl-engine/core/shaderLibrary/shading/ScreenSpaceReflections.glsl.js +1 -1
  83. package/views/3d/webgl-engine/lib/Renderer.js +1 -1
  84. package/views/PopupView.js +1 -1
  85. package/views/SceneView.js +1 -1
  86. package/views/interactive/SegmentLabels.js +1 -1
  87. package/views/layers/ImageryLayerView.js +1 -1
  88. package/views/layers/SceneLayerView.js +1 -1
  89. package/views/layers/StreamLayerView.js +1 -1
  90. package/widgets/Editor.js +1 -1
  91. package/widgets/Fullscreen/FullscreenViewModel.js +1 -1
  92. package/widgets/Home/HomeViewModel.js +1 -1
  93. package/assets/esri/core/workers/chunks/0efee8d9fc5632346cb4.js +0 -1
  94. package/assets/esri/core/workers/chunks/10e715aa4ac96d7dd1b4.js +0 -1
  95. package/assets/esri/core/workers/chunks/2dfb17fa5b6a5d239942.js +0 -1
  96. package/assets/esri/core/workers/chunks/2e3962506c353b562a88.js +0 -1
  97. package/assets/esri/core/workers/chunks/7320e6d8f207399bc8f1.js +0 -1
  98. package/assets/esri/core/workers/chunks/a194f90ffe13b3d448b0.js +0 -1
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.26/esri/copyright.txt for details.
4
4
  */
5
- import{doSubstitutions as e}from"./executionError.js";import{IANAZone as t,DateTime as n,Zone as r,FixedOffsetZone as s}from"luxon";class i{}var o;i.instance=new t("Etc/UTC"),function(e){e.TimeZoneNotRecognised="TimeZoneNotRecognised"}(o||(o={}));const a={[o.TimeZoneNotRecognised]:"Timezone identifier has not been recognised."};class d extends Error{constructor(t,n){super(e(a[t],n)),this.declaredRootClass="esri.arcade.arcadedate.dateerror",Error.captureStackTrace&&Error.captureStackTrace(this,d)}}class c{constructor(e){this._date=e}static fromParts(e=0,t=1,r=1,s=0,i=0,o=0,a=0,d){if(isNaN(e)||isNaN(t)||isNaN(r)||isNaN(s)||isNaN(i)||isNaN(o)||isNaN(a))return null;let m=0;const h=n.local(e,t).daysInMonth;r<1&&(m=r-1,r=1),r>h&&(m=r-h,r=h);let l=0;t>12?(l=t-12,t=12):t<1&&(l=t-1,t=1);let f=0;i>59?(f=i-59,i=59):i<0&&(f=i,i=0);let T=0;o>59?(T=o-59,o=59):o<0&&(T=o,o=0);let w=0;a>999?(w=a-999,a=999):a<0&&(w=a,a=0);let y=n.fromObject({day:r,year:e,month:t,hour:s,minute:i,second:o,millisecond:a},{zone:u(d)});return 0!==l&&(y=y.plus({months:l})),0!==m&&(y=y.plus({days:m})),0!==f&&(y=y.plus({minutes:f})),0!==T&&(y=y.plus({seconds:T})),0!==w&&(y=y.plus({milliseconds:w})),new c(y)}static get systemTimeZoneCanonicalName(){return Intl.DateTimeFormat().resolvedOptions().timeZone??"system"}static arcadeDateAndZoneToArcadeDate(e,t){const n=u(t);return e.isUnknownTimeZone||n===i.instance?c.fromParts(e.year,e.monthJS+1,e.day,e.hour,e.minute,e.second,e.millisecond,n):new c(e._date.setZone(t))}static dateJSToArcadeDate(e){return new c(n.fromJSDate(e))}static dateJSAndZoneToArcadeDate(e,t="system"){return new c(n.fromJSDate(e,{zone:t}))}static unknownEpochToArcadeDate(e){return new c(n.fromMillis(e,{zone:i.instance}))}static unknownDateJSToArcadeDate(e){return c.arcadeDateAndZoneToArcadeDate(c.dateJSToArcadeDate(e),i.instance)}static epochToArcadeDate(e){return new c(n.fromMillis(e))}static dateTimeToArcadeDate(e){return new c(e)}changeTimeZone(e){const t=u(e);return c.dateTimeToArcadeDate(this._date.setZone(t))}static dateTimeAndZoneToArcadeDate(e,t){const n=u(t);return e.zone===i.instance||n===i.instance?c.fromParts(e.year,e.month,e.day,e.hour,e.minute,e.second,e.millisecond,n):new c(e.setZone(n))}static nowToArcadeDate(e){return new c(n.fromJSDate(new Date,{zone:e}))}static nowUTCToArcadeDate(){return new c(n.utc())}get isSystem(){return"system"===this.timeZone||this.timeZone===c.systemTimeZoneCanonicalName}equals(e){return this.isSystem&&e.isSystem?this.toNumber()===e.toNumber():this.isUnknownTimeZone===e.isUnknownTimeZone&&this._date.equals(e._date)}get isUnknownTimeZone(){return this._date.zone===i.instance}get isValid(){return this._date.isValid}get hour(){return this._date.hour}get second(){return this._date.second}get day(){return this._date.day}get dayOfWeekISO(){return this._date.weekday}get dayOfWeekJS(){let e=this._date.weekday;return e>6&&(e=0),e}get millisecond(){return this._date.millisecond}get monthISO(){return this._date.month}get weekISO(){return this._date.weekNumber}get yearISO(){return this._date.weekYear}get monthJS(){return this._date.month-1}get year(){return this._date.year}get minute(){return this._date.minute}get zone(){return this._date.zone}get timeZoneOffset(){return this.isUnknownTimeZone?0:this._date.offset}get timeZone(){if(this.isUnknownTimeZone)return"unknown";if("system"===this._date.zone.type)return"system";const e=this.zone;return"fixed"===e.type?0===e.fixed?"utc":e.formatOffset(0,"short"):e.name}stringify(){return JSON.stringify(this.toJSDate())}plus(e){return new c(this._date.plus(e))}diff(e,t="milliseconds"){return this._date.diff(e._date,t)[t]}toISOString(e){return e?this._date.toISO({suppressMilliseconds:!0,includeOffset:!this.isUnknownTimeZone}):this._date.toISO({includeOffset:!this.isUnknownTimeZone})}toFormat(e,t){return this._date.toFormat(e,t)}toJSDate(){return this._date.toJSDate()}toSQLString(){return"timestamp '"+this._date.toFormat("yyyy-LL-dd HH:mm:ss")+"'"}toDateTime(){return this._date}toNumber(){return this._date.toMillis()}getTime(){return this._date.toMillis()}toUTC(){return new c(this._date.toUTC())}toLocal(){return new c(this._date.toLocal())}}function u(e){if(e instanceof r)return e;if("system"===e.toLowerCase())return"system";if("utc"===e.toLowerCase())return"utc";if("unknown"===e.toLowerCase())return i.instance;if(/^[\+\-]?[0-9]{1,2}([:][0-9]{2})?$/.test(e)){const t=s.parseSpecifier("UTC"+(e.startsWith("+")||e.startsWith("-")?"":"+")+e);if(t)return t}const n=t.create(e);if(!n.isValid)throw new d(o.TimeZoneNotRecognised);return n}export{c as ArcadeDate,d as ArcadeDateError,o as ArcadeDateErrorCodes,a as ArcadeDateErrorMessages,i as UnknownTimeZone,u as createDateTimeZone};
5
+ import{doSubstitutions as e}from"./executionError.js";import{IANAZone as t,DateTime as n,Zone as r,FixedOffsetZone as s}from"luxon";class i{}var a;i.instance=new t("Etc/UTC"),function(e){e.TimeZoneNotRecognised="TimeZoneNotRecognised"}(a||(a={}));const o={[a.TimeZoneNotRecognised]:"Timezone identifier has not been recognised."};class d extends Error{constructor(t,n){super(e(o[t],n)),this.declaredRootClass="esri.arcade.arcadedate.dateerror",Error.captureStackTrace&&Error.captureStackTrace(this,d)}}class c{constructor(e){this._date=e,this.declaredRootClass="esri.arcade.arcadedate"}static fromParts(e=0,t=1,r=1,s=0,i=0,a=0,o=0,d){if(isNaN(e)||isNaN(t)||isNaN(r)||isNaN(s)||isNaN(i)||isNaN(a)||isNaN(o))return null;let m=0;const h=n.local(e,t).daysInMonth;r<1&&(m=r-1,r=1),r>h&&(m=r-h,r=h);let l=0;t>12?(l=t-12,t=12):t<1&&(l=t-1,t=1);let f=0;i>59?(f=i-59,i=59):i<0&&(f=i,i=0);let T=0;a>59?(T=a-59,a=59):a<0&&(T=a,a=0);let w=0;o>999?(w=o-999,o=999):o<0&&(w=o,o=0);let y=n.fromObject({day:r,year:e,month:t,hour:s,minute:i,second:a,millisecond:o},{zone:u(d)});return 0!==l&&(y=y.plus({months:l})),0!==m&&(y=y.plus({days:m})),0!==f&&(y=y.plus({minutes:f})),0!==T&&(y=y.plus({seconds:T})),0!==w&&(y=y.plus({milliseconds:w})),new c(y)}static get systemTimeZoneCanonicalName(){return Intl.DateTimeFormat().resolvedOptions().timeZone??"system"}static arcadeDateAndZoneToArcadeDate(e,t){const n=u(t);return e.isUnknownTimeZone||n===i.instance?c.fromParts(e.year,e.monthJS+1,e.day,e.hour,e.minute,e.second,e.millisecond,n):new c(e._date.setZone(t))}static dateJSToArcadeDate(e){return new c(n.fromJSDate(e))}static dateJSAndZoneToArcadeDate(e,t="system"){return new c(n.fromJSDate(e,{zone:t}))}static unknownEpochToArcadeDate(e){return new c(n.fromMillis(e,{zone:i.instance}))}static unknownDateJSToArcadeDate(e){return c.arcadeDateAndZoneToArcadeDate(c.dateJSToArcadeDate(e),i.instance)}static epochToArcadeDate(e){return new c(n.fromMillis(e))}static dateTimeToArcadeDate(e){return new c(e)}changeTimeZone(e){const t=u(e);return c.dateTimeToArcadeDate(this._date.setZone(t))}static dateTimeAndZoneToArcadeDate(e,t){const n=u(t);return e.zone===i.instance||n===i.instance?c.fromParts(e.year,e.month,e.day,e.hour,e.minute,e.second,e.millisecond,n):new c(e.setZone(n))}static nowToArcadeDate(e){return new c(n.fromJSDate(new Date,{zone:e}))}static nowUTCToArcadeDate(){return new c(n.utc())}get isSystem(){return"system"===this.timeZone||this.timeZone===c.systemTimeZoneCanonicalName}equals(e){return this.isSystem&&e.isSystem?this.toNumber()===e.toNumber():this.isUnknownTimeZone===e.isUnknownTimeZone&&this._date.equals(e._date)}get isUnknownTimeZone(){return this._date.zone===i.instance}get isValid(){return this._date.isValid}get hour(){return this._date.hour}get second(){return this._date.second}get day(){return this._date.day}get dayOfWeekISO(){return this._date.weekday}get dayOfWeekJS(){let e=this._date.weekday;return e>6&&(e=0),e}get millisecond(){return this._date.millisecond}get monthISO(){return this._date.month}get weekISO(){return this._date.weekNumber}get yearISO(){return this._date.weekYear}get monthJS(){return this._date.month-1}get year(){return this._date.year}get minute(){return this._date.minute}get zone(){return this._date.zone}get timeZoneOffset(){return this.isUnknownTimeZone?0:this._date.offset}get timeZone(){if(this.isUnknownTimeZone)return"unknown";if("system"===this._date.zone.type)return"system";const e=this.zone;return"fixed"===e.type?0===e.fixed?"utc":e.formatOffset(0,"short"):e.name}stringify(){return JSON.stringify(this.toJSDate())}plus(e){return new c(this._date.plus(e))}diff(e,t="milliseconds"){return this._date.diff(e._date,t)[t]}toISOString(e){return e?this._date.toISO({suppressMilliseconds:!0,includeOffset:!this.isUnknownTimeZone}):this._date.toISO({includeOffset:!this.isUnknownTimeZone})}toFormat(e,t){return this._date.toFormat(e,t)}toJSDate(){return this._date.toJSDate()}toSQLString(){return"timestamp '"+this._date.toFormat("yyyy-LL-dd HH:mm:ss")+"'"}toDateTime(){return this._date}toNumber(){return this._date.toMillis()}getTime(){return this._date.toMillis()}toUTC(){return new c(this._date.toUTC())}toLocal(){return new c(this._date.toLocal())}}function u(e){if(e instanceof r)return e;if("system"===e.toLowerCase())return"system";if("utc"===e.toLowerCase())return"utc";if("unknown"===e.toLowerCase())return i.instance;if(/^[\+\-]?[0-9]{1,2}([:][0-9]{2})?$/.test(e)){const t=s.parseSpecifier("UTC"+(e.startsWith("+")||e.startsWith("-")?"":"+")+e);if(t)return t}const n=t.create(e);if(!n.isValid)throw new d(a.TimeZoneNotRecognised);return n}export{c as ArcadeDate,d as ArcadeDateError,a as ArcadeDateErrorCodes,o as ArcadeDateErrorMessages,i as UnknownTimeZone,u as createDateTimeZone};
package/arcade/Feature.js CHANGED
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.26/esri/copyright.txt for details.
4
4
  */
5
- import t from"./Dictionary.js";import e from"./ImmutableArray.js";import{a as i,b as s,c as r,t as a,k as n,f as o,d as l}from"../chunks/languageUtils.js";import u from"../geometry/Geometry.js";import h from"../geometry/Point.js";import{fromJSON as f}from"../geometry/support/jsonUtils.js";import{convertToGeometry as c}from"../layers/graphics/featureConversionUtils.js";import{isSome as d,unwrap as m}from"../core/maybe.js";import{ArcadeDate as y}from"./ArcadeDate.js";import{ArcadeExecutionError as _,ExecutionErrorCodes as b}from"./executionError.js";class p{constructor(){this.arcadeDeclaredClass="esri.arcade.Feature",this._optimizedGeomDefinition=null,this._geometry=null,this.attributes=null,this._layer=null,this._datesfixed=!0,this.dateTimeReferenceFieldIndex=null,this.immutable=!0,this._datefields=null,this.immutable=!0}static createFromGraphic(t){const e=new p;return e._geometry=d(t.geometry)?t.geometry:null,void 0===t.attributes||null===t.attributes?e.attributes={}:e.attributes=t.attributes,t._sourceLayer?(e._layer=t._sourceLayer,e._datesfixed=!1):t._layer?(e._layer=t._layer,e._datesfixed=!1):t.layer&&"fields"in t.layer?(e._layer=t.layer,e._datesfixed=!1):t.sourceLayer&&"fields"in t.sourceLayer&&(e._layer=t.sourceLayer,e._datesfixed=!1),e}static createFromArcadeFeature(t){const e=new p;return e._datesfixed=t._datesfixed,e.attributes=t.attributes,e._geometry=t._geometry,e._optimizedGeomDefinition=t._optimizedGeomDefinition,t._layer&&(e._layer=t._layer),e}static createFromOptimisedFeature(t,e,i){const s=new p;return s._geometry=t.geometry?{geometry:t.geometry}:null,s._optimizedGeomDefinition=i,s.attributes=t.attributes||{},s._layer=e,s._datesfixed=!1,s}static createFromArcadeDictionary(e){const i=new p;return i.attributes=e.field("attributes"),null!==i.attributes&&i.attributes instanceof t?(i.attributes=i.attributes.attributes,null===i.attributes&&(i.attributes={})):i.attributes={},i._geometry=e.field("geometry"),null!==i._geometry&&(i._geometry instanceof t?i._geometry=p.parseGeometryFromDictionary(i._geometry):i._geometry instanceof u||(i._geometry=null)),i}static createFromGraphicLikeObject(t,e,i=null){const s=new p;return null===e&&(e={}),s.attributes=e,s._geometry=d(t)?t:null,s._layer=i,s._layer&&(s._datesfixed=!1),s}repurposeFromGraphicLikeObject(t,e,i=null){null===e&&(e={}),this.attributes=e,this._geometry=t||null,this._layer=i,this._layer?this._datesfixed=!1:this._datesfixed=!0}get layerPreferredTimeZone(){return this.dateTimeReferenceFieldIndex?.layerPreferredTimeZone??""}fieldSourceTimeZone(t){return this.dateTimeReferenceFieldIndex?.fieldTimeZone(t)??""}castToText(t=!1){let n="";!1===this._datesfixed&&this._fixDates();for(const o in this.attributes){""!==n&&(n+=",");const l=this.attributes[o];null==l?n+=JSON.stringify(o)+":null":i(l)||s(l)||r(l)?n+=JSON.stringify(o)+":"+JSON.stringify(l):l instanceof u?n+=JSON.stringify(o)+":"+a(l):l instanceof e||l instanceof Array?n+=JSON.stringify(o)+":"+a(l,null,t):l instanceof y?n+=t?JSON.stringify(o)+":"+JSON.stringify(l.getTime()):JSON.stringify(o)+":"+l.stringify():null!==l&&"object"==typeof l&&void 0!==l.castToText&&(n+=JSON.stringify(o)+":"+l.castToText(t))}return'{"geometry":'+(null===this.geometry()?"null":a(this.geometry()))+',"attributes":{'+n+"}}"}_fixDates(){if(null!==this._datefields)return this._datefields.length>0&&this._fixDateFields(this._datefields),void(this._datesfixed=!0);const t=[],e=this._layer.fields;for(let i=0;i<e.length;i++){const s=e[i],r=s.type;"date"!==r&&"esriFieldTypeDate"!==r||t.push(s.name)}this._datefields=t,t.length>0&&this._fixDateFields(t),this._datesfixed=!0}isUnknownDateTimeField(t){return"unknown"===this.dateTimeReferenceFieldIndex?.fieldTimeZone(t)}_fixDateFields(t){this.attributes={...this.attributes};for(let e=0;e<t.length;e++){let i=this.attributes[t[e]];if(null===i);else if(void 0===i){for(const s in this.attributes)if(s.toLowerCase()===t[e].toLowerCase()){if(i=this.attributes[s],null!==i){const t=this.isUnknownDateTimeField(s);n(i)?this.attributes[s]=i:i instanceof Date?this.attributes[s]=t?y.unknownDateJSToArcadeDate(i):y.dateJSToArcadeDate(i):this.attributes[s]=t?y.unknownEpochToArcadeDate(i):y.epochToArcadeDate(i)}break}}else{const s=this.isUnknownDateTimeField(t[e]);n(i)?this.attributes[t[e]]=i:i instanceof Date?this.attributes[t[e]]=s?y.unknownDateJSToArcadeDate(i):y.dateJSToArcadeDate(i):this.attributes[t[e]]=s?y.unknownEpochToArcadeDate(i):y.epochToArcadeDate(i)}}}geometry(){return null===this._geometry||this._geometry instanceof u||(this._optimizedGeomDefinition?(this._geometry=m(f(c(this._geometry,this._optimizedGeomDefinition.geometryType,this._optimizedGeomDefinition.hasZ,this._optimizedGeomDefinition.hasM))),this._geometry.spatialReference=this._optimizedGeomDefinition.spatialReference):this._geometry=m(f(this._geometry))),this._geometry}field(t){!1===this._datesfixed&&this._fixDates();const e=this.attributes[t];if(void 0!==e)return e;const i=t.toLowerCase();for(const s in this.attributes)if(s.toLowerCase()===i)return this.attributes[s];if(this._hasFieldDefinition(i))return null;throw new _(null,b.FieldNotFound,null,{key:t})}_hasFieldDefinition(t){if(null===this._layer)return!1;for(let e=0;e<this._layer.fields.length;e++){if(this._layer.fields[e].name.toLowerCase()===t)return!0}return!1}setField(t,e){if(this.immutable)throw new _(null,b.Immutable,null);if(e instanceof Date&&(e=this.isUnknownDateTimeField(t)?y.unknownDateJSToArcadeDate(e):y.dateJSToArcadeDate(e)),!1===o(e))throw new _(null,b.TypeNotAllowedInFeature,null);const i=t.toLowerCase();if(void 0===this.attributes[t]){for(const t in this.attributes)if(t.toLowerCase()===i)return void(this.attributes[t]=e);this.attributes[t]=e}else this.attributes[t]=e}hasField(t){const e=t.toLowerCase();if(void 0!==this.attributes[t])return!0;for(const i in this.attributes)if(i.toLowerCase()===e)return!0;return!!this._hasFieldDefinition(e)}keys(){let t=[];const e={};for(const i in this.attributes)t.push(i),e[i.toLowerCase()]=1;if(null!==this._layer)for(let i=0;i<this._layer.fields.length;i++){const s=this._layer.fields[i];1!==e[s.name.toLowerCase()]&&t.push(s.name)}return t=t.sort(),t}static parseGeometryFromDictionary(t){const e=p._convertDictionaryToJson(t,!0);return void 0!==e.hasm&&(e.hasM=e.hasm,delete e.hasm),void 0!==e.hasz&&(e.hasZ=e.hasz,delete e.hasz),void 0!==e.spatialreference&&(e.spatialReference=e.spatialreference,delete e.spatialreference),void 0!==e.rings&&(e.rings=this._fixPathArrays(e.rings,!0===e.hasZ,!0===e.hasZ)),void 0!==e.paths&&(e.paths=this._fixPathArrays(e.paths,!0===e.hasZ,!0===e.hasM)),void 0!==e.points&&(e.points=this._fixPointArrays(e.points,!0===e.hasZ,!0===e.hasM)),f(e)}static _fixPathArrays(t,i,s){const r=[];if(t instanceof Array)for(let e=0;e<t.length;e++)r.push(this._fixPointArrays(t[e],i,s));else if(t instanceof e)for(let e=0;e<t.length();e++)r.push(this._fixPointArrays(t.get(e),i,s));return r}static _fixPointArrays(t,i,s){const r=[];if(t instanceof Array)for(let a=0;a<t.length;a++){const n=t[a];n instanceof h?i&&s?r.push([n.x,n.y,n.z,n.m]):i?r.push([n.x,n.y,n.z]):s?r.push([n.x,n.y,n.m]):r.push([n.x,n.y]):n instanceof e?r.push(n.toArray()):r.push(n)}else if(t instanceof e)for(let a=0;a<t.length();a++){const n=t.get(a);n instanceof h?i&&s?r.push([n.x,n.y,n.z,n.m]):i?r.push([n.x,n.y,n.z]):s?r.push([n.x,n.y,n.m]):r.push([n.x,n.y]):n instanceof e?r.push(n.toArray()):r.push(n)}return r}static _convertDictionaryToJson(e,i=!1){const s={};for(const r in e.attributes){let a=e.attributes[r];a instanceof t&&(a=p._convertDictionaryToJson(a)),i?s[r.toLowerCase()]=a:s[r]=a}return s}static parseAttributesFromDictionary(t){const e={};for(const i in t.attributes){const s=t.attributes[i];if(!o(s))throw new _(null,b.InvalidParameter,null);e[i]=s}return e}static fromJson(t){let e=null;null!==t.geometry&&void 0!==t.geometry&&(e=f(t.geometry));const a={};if(null!==t.attributes&&void 0!==t.attributes)for(const o in t.attributes){const e=t.attributes[o];if(null===e)a[o]=e;else{if(!(r(e)||s(e)||i(e)||n(e)))throw new _(null,b.InvalidParameter,null);a[o]=e}}return p.createFromGraphicLikeObject(e,a,null)}fullSchema(){return this._layer}gdbVersion(){if(null===this._layer)return"";const t=this._layer.gdbVersion;return void 0===t?"":""===t&&this._layer.capabilities&&this._layer.capabilities.isVersioned?"SDE.DEFAULT":t}castAsJson(t){const e={attributes:{},geometry:!0===t?.keepGeometryType?this.geometry():this.geometry().toJSON()};for(const i in this.attributes){const s=this.attributes[i];void 0!==s&&(e.attributes[i]=l(s,t))}return e}async castAsJsonAsync(t=null,e){return this.castAsJson(e)}}export{p as default};
5
+ import t from"./Dictionary.js";import e from"./ImmutableArray.js";import{a as i,b as s,c as r,t as a,k as n,f as o,d as l}from"../chunks/languageUtils.js";import u from"../geometry/Geometry.js";import h from"../geometry/Point.js";import{fromJSON as f}from"../geometry/support/jsonUtils.js";import{convertToGeometry as c}from"../layers/graphics/featureConversionUtils.js";import{isSome as d,unwrap as m}from"../core/maybe.js";import{ArcadeDate as y}from"./ArcadeDate.js";import{ArcadeExecutionError as _,ExecutionErrorCodes as b}from"./executionError.js";class p{constructor(){this.arcadeDeclaredClass="esri.arcade.Feature",this._optimizedGeomDefinition=null,this._geometry=null,this.attributes=null,this._layer=null,this._datesfixed=!0,this.dateTimeReferenceFieldIndex=null,this.immutable=!0,this._datefields=null,this.immutable=!0}static createFromGraphic(t){const e=new p;return e._geometry=d(t.geometry)?t.geometry:null,void 0===t.attributes||null===t.attributes?e.attributes={}:e.attributes=t.attributes,t._sourceLayer?(e._layer=t._sourceLayer,e._datesfixed=!1):t._layer?(e._layer=t._layer,e._datesfixed=!1):t.layer&&"fields"in t.layer?(e._layer=t.layer,e._datesfixed=!1):t.sourceLayer&&"fields"in t.sourceLayer&&(e._layer=t.sourceLayer,e._datesfixed=!1),e}static createFromArcadeFeature(t){const e=new p;return e._datesfixed=t._datesfixed,e.attributes=t.attributes,e._geometry=t._geometry,e._optimizedGeomDefinition=t._optimizedGeomDefinition,t._layer&&(e._layer=t._layer),e}static createFromOptimisedFeature(t,e,i){const s=new p;return s._geometry=t.geometry?{geometry:t.geometry}:null,s._optimizedGeomDefinition=i,s.attributes=t.attributes||{},s._layer=e,s._datesfixed=!1,s}static createFromArcadeDictionary(e){const i=new p;return i.attributes=e.field("attributes"),null!==i.attributes&&i.attributes instanceof t?(i.attributes=i.attributes.attributes,null===i.attributes&&(i.attributes={})):i.attributes={},i._geometry=e.field("geometry"),null!==i._geometry&&(i._geometry instanceof t?i._geometry=p.parseGeometryFromDictionary(i._geometry):i._geometry instanceof u||(i._geometry=null)),i}static createFromGraphicLikeObject(t,e,i=null){const s=new p;return null===e&&(e={}),s.attributes=e,s._geometry=d(t)?t:null,s._layer=i,s._layer&&(s._datesfixed=!1),s}repurposeFromGraphicLikeObject(t,e,i=null){null===e&&(e={}),this.attributes=e,this._geometry=t||null,this._layer=i,this._layer?this._datesfixed=!1:this._datesfixed=!0}get layerPreferredTimeZone(){return this.dateTimeReferenceFieldIndex?.layerPreferredTimeZone??""}fieldSourceTimeZone(t){return this.dateTimeReferenceFieldIndex?.fieldTimeZone(t)??""}castToText(t=!1){let n="";!1===this._datesfixed&&this._fixDates();for(const o in this.attributes){""!==n&&(n+=",");const l=this.attributes[o];null==l?n+=JSON.stringify(o)+":null":i(l)||s(l)||r(l)?n+=JSON.stringify(o)+":"+JSON.stringify(l):l instanceof u?n+=JSON.stringify(o)+":"+a(l):l instanceof e||l instanceof Array?n+=JSON.stringify(o)+":"+a(l,null,t):l instanceof y?n+=t?JSON.stringify(o)+":"+JSON.stringify(l.getTime()):JSON.stringify(o)+":"+l.stringify():null!==l&&"object"==typeof l&&void 0!==l.castToText&&(n+=JSON.stringify(o)+":"+l.castToText(t))}return'{"geometry":'+(null===this.geometry()?"null":a(this.geometry()))+',"attributes":{'+n+"}}"}_fixDates(){if(null!==this._datefields)return this._datefields.length>0&&this._fixDateFields(this._datefields),void(this._datesfixed=!0);const t=[],e=this._layer.fields;for(let i=0;i<e.length;i++){const s=e[i],r=s.type;"date"!==r&&"esriFieldTypeDate"!==r||t.push(s.name)}this._datefields=t,t.length>0&&this._fixDateFields(t),this._datesfixed=!0}isUnknownDateTimeField(t){return"unknown"===this.dateTimeReferenceFieldIndex?.fieldTimeZone(t)}_fixDateFields(t){this.attributes={...this.attributes};for(let e=0;e<t.length;e++){let i=this.attributes[t[e]];if(null===i);else if(void 0===i){for(const s in this.attributes)if(s.toLowerCase()===t[e].toLowerCase()){if(i=this.attributes[s],null!==i){const t=this.isUnknownDateTimeField(s);n(i)?this.attributes[s]=i:i instanceof Date?this.attributes[s]=t?y.unknownDateJSToArcadeDate(i):y.dateJSToArcadeDate(i):this.attributes[s]=t?y.unknownEpochToArcadeDate(i):y.epochToArcadeDate(i)}break}}else{const s=this.isUnknownDateTimeField(t[e]);n(i)?this.attributes[t[e]]=i:i instanceof Date?this.attributes[t[e]]=s?y.unknownDateJSToArcadeDate(i):y.dateJSToArcadeDate(i):this.attributes[t[e]]=s?y.unknownEpochToArcadeDate(i):y.epochToArcadeDate(i)}}}geometry(){return null===this._geometry||this._geometry instanceof u||(this._optimizedGeomDefinition?(this._geometry=m(f(c(this._geometry,this._optimizedGeomDefinition.geometryType,this._optimizedGeomDefinition.hasZ,this._optimizedGeomDefinition.hasM))),this._geometry.spatialReference=this._optimizedGeomDefinition.spatialReference):this._geometry=m(f(this._geometry))),this._geometry}field(t){!1===this._datesfixed&&this._fixDates();const e=this.attributes[t];if(void 0!==e)return e;const i=t.toLowerCase();for(const s in this.attributes)if(s.toLowerCase()===i)return this.attributes[s];if(this._hasFieldDefinition(i))return null;throw new _(null,b.FieldNotFound,null,{key:t})}_hasFieldDefinition(t){if(null===this._layer)return!1;for(let e=0;e<this._layer.fields.length;e++){if(this._layer.fields[e].name.toLowerCase()===t)return!0}return!1}setField(t,e){if(this.immutable)throw new _(null,b.Immutable,null);if(e instanceof Date&&(e=this.isUnknownDateTimeField(t)?y.unknownDateJSToArcadeDate(e):y.dateJSToArcadeDate(e)),!1===o(e))throw new _(null,b.TypeNotAllowedInFeature,null);const i=t.toLowerCase();if(void 0===this.attributes[t]){for(const t in this.attributes)if(t.toLowerCase()===i)return void(this.attributes[t]=e);this.attributes[t]=e}else this.attributes[t]=e}hasField(t){const e=t.toLowerCase();if(void 0!==this.attributes[t])return!0;for(const i in this.attributes)if(i.toLowerCase()===e)return!0;return!!this._hasFieldDefinition(e)}keys(){let t=[];const e={};for(const i in this.attributes)t.push(i),e[i.toLowerCase()]=1;if(null!==this._layer)for(let i=0;i<this._layer.fields.length;i++){const s=this._layer.fields[i];1!==e[s.name.toLowerCase()]&&t.push(s.name)}return t=t.sort(),t}static parseGeometryFromDictionary(t){const e=p._convertDictionaryToJson(t,!0);return void 0!==e.hasm&&(e.hasM=e.hasm,delete e.hasm),void 0!==e.hasz&&(e.hasZ=e.hasz,delete e.hasz),void 0!==e.spatialreference&&(e.spatialReference=e.spatialreference,delete e.spatialreference),void 0!==e.rings&&(e.rings=this._fixPathArrays(e.rings,!0===e.hasZ,!0===e.hasZ)),void 0!==e.paths&&(e.paths=this._fixPathArrays(e.paths,!0===e.hasZ,!0===e.hasM)),void 0!==e.points&&(e.points=this._fixPointArrays(e.points,!0===e.hasZ,!0===e.hasM)),f(e)}static _fixPathArrays(t,i,s){const r=[];if(t instanceof Array)for(let e=0;e<t.length;e++)r.push(this._fixPointArrays(t[e],i,s));else if(t instanceof e)for(let e=0;e<t.length();e++)r.push(this._fixPointArrays(t.get(e),i,s));return r}static _fixPointArrays(t,i,s){const r=[];if(t instanceof Array)for(let a=0;a<t.length;a++){const n=t[a];n instanceof h?i&&s?r.push([n.x,n.y,n.z,n.m]):i?r.push([n.x,n.y,n.z]):s?r.push([n.x,n.y,n.m]):r.push([n.x,n.y]):n instanceof e?r.push(n.toArray()):r.push(n)}else if(t instanceof e)for(let a=0;a<t.length();a++){const n=t.get(a);n instanceof h?i&&s?r.push([n.x,n.y,n.z,n.m]):i?r.push([n.x,n.y,n.z]):s?r.push([n.x,n.y,n.m]):r.push([n.x,n.y]):n instanceof e?r.push(n.toArray()):r.push(n)}return r}static _convertDictionaryToJson(e,i=!1){const s={};for(const r in e.attributes){let a=e.attributes[r];a instanceof t&&(a=p._convertDictionaryToJson(a)),i?s[r.toLowerCase()]=a:s[r]=a}return s}static parseAttributesFromDictionary(t){const e={};for(const i in t.attributes){const s=t.attributes[i];if(!o(s))throw new _(null,b.InvalidParameter,null);e[i]=s}return e}static fromJson(t){let e=null;null!==t.geometry&&void 0!==t.geometry&&(e=f(t.geometry));const a={};if(null!==t.attributes&&void 0!==t.attributes)for(const o in t.attributes){const e=t.attributes[o];if(null===e)a[o]=e;else{if(!(r(e)||s(e)||i(e)||n(e)))throw new _(null,b.InvalidParameter,null);a[o]=e}}return p.createFromGraphicLikeObject(e,a,null)}fullSchema(){return this._layer}gdbVersion(){if(null===this._layer)return"";const t=this._layer.gdbVersion;return void 0===t?"":""===t&&this._layer.capabilities&&this._layer.capabilities.isVersioned?"SDE.DEFAULT":t}castAsJson(t){const e={attributes:{},geometry:!0===t?.keepGeometryType?this.geometry():this.geometry()?.toJSON()??null};for(const i in this.attributes){const s=this.attributes[i];void 0!==s&&(e.attributes[i]=l(s,t))}return e}async castAsJsonAsync(t=null,e){return this.castAsJson(e)}}export{p as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.26/esri/copyright.txt for details.
4
4
  */
5
- import{ArcadeDate as e}from"../../ArcadeDate.js";import r from"../../../geometry/Extent.js";import t from"../../../layers/support/Field.js";var i,n;function o(e){return t.fromJSON(e.toJSON())}function l(e){return e.toJSON?e.toJSON():e}function s(e){return"string"==typeof e||e instanceof String}function y(e){return"boolean"==typeof e}function u(e){return"number"==typeof e}function p(e){return e instanceof Array}function a(e){return e instanceof Date}function c(r){return r instanceof e}function m(e,r){if(e===r)return!0;if(a(e)){if(a(r))return e.getTime()===r.getTime();if(c(r))return e.getTime()===r.getTime()}if(c(e)){if(a(r))return e.getTime()===r.getTime();if(c(r))return e.equals(r)}return!1}function f(e){const r={};for(const t in e)r[t]=e[t];return r}function d(e){if(null==e)return null;if("number"==typeof e)return e;switch(e.toLowerCase()){case"meters":case"meter":return 109404;case"miles":case"mile":return 109439;case"kilometers":case"kilometer":case"km":return 109414}return null}function g(e){if(null==e)return null;switch(e.type){case"polygon":case"multipoint":case"polyline":return e.extent;case"point":return new r({xmin:e.x,ymin:e.y,xmax:e.x,ymax:e.y,spatialReference:e.spatialReference});case"extent":return e}return null}function F(e){if(null==e)return null;if("number"==typeof e)return e;if("number"==typeof e)return e;switch(e.toLowerCase()){case"meters":case"meter":return 9001;case"miles":case"mile":return 9093;case"kilometers":case"kilometer":case"km":return 9036}return null}function T(e,r){return e===r||("point"===e&&"esriGeometryPoint"===r||("polyline"===e&&"esriGeometryPolyline"===r||("polygon"===e&&"esriGeometryPolygon"===r||("extent"===e&&"esriGeometryEnvelope"===r||("multipoint"===e&&"esriGeometryMultipoint"===r||("point"===r&&"esriGeometryPoint"===e||("polyline"===r&&"esriGeometryPolyline"===e||("polygon"===r&&"esriGeometryPolygon"===e||("extent"===r&&"esriGeometryEnvelope"===e||"multipoint"===r&&"esriGeometryMultipoint"===e)))))))))}!function(e){e[e.Standardised=0]="Standardised",e[e.StandardisedNoInterval=1]="StandardisedNoInterval",e[e.SqlServer=2]="SqlServer",e[e.Oracle=3]="Oracle",e[e.Postgres=4]="Postgres",e[e.PGDB=5]="PGDB",e[e.FILEGDB=6]="FILEGDB",e[e.NotEvaluated=7]="NotEvaluated"}(i||(i={})),function(e){e[e.InFeatureSet=0]="InFeatureSet",e[e.NotInFeatureSet=1]="NotInFeatureSet",e[e.Unknown=2]="Unknown"}(n||(n={}));const G=1e3;function S(e){return function(r){e.reject(r)}}function v(e,r){return function(){try{e.apply(null,arguments)}catch(t){r.reject(t)}}}const P={point:"point",polygon:"polygon",polyline:"polyline",multipoint:"multipoint",extent:"extent",esriGeometryPoint:"point",esriGeometryPolygon:"polygon",esriGeometryPolyline:"polyline",esriGeometryMultipoint:"multipoint",esriGeometryEnvelope:"extent",envelope:"extent"},I={point:"esriGeometryPoint",polygon:"esriGeometryPolygon",polyline:"esriGeometryPolyline",multipoint:"esriGeometryMultipoint",extent:"esriGeometryEnvelope",esriGeometryPoint:"esriGeometryPoint",esriGeometryPolygon:"esriGeometryPolygon",esriGeometryPolyline:"esriGeometryPolyline",esriGeometryMultipoint:"esriGeometryMultipoint",esriGeometryEnvelope:"esriGeometryEnvelope",envelope:"esriGeometryEnvelope"},b={"small-integer":"esriFieldTypeSmallInteger",integer:"esriFieldTypeInteger",long:"esriFieldTypeLong",single:"esriFieldTypeSingle",double:"esriFieldTypeDouble",string:"esriFieldTypeString",date:"esriFieldTypeDate",oid:"esriFieldTypeOID",geometry:"esriFieldTypeGeometry",blob:"esriFieldTypeBlob",raster:"esriFieldTypeRaster",guid:"esriFieldTypeGUID","global-id":"esriFieldTypeGlobalID",xml:"eesriFieldTypeXML",esriFieldTypeSmallInteger:"esriFieldTypeSmallInteger",esriFieldTypeInteger:"esriFieldTypeInteger",esriFieldTypeLong:"esriFieldTypeLong",esriFieldTypeSingle:"esriFieldTypeSingle",esriFieldTypeDouble:"esriFieldTypeDouble",esriFieldTypeString:"esriFieldTypeString",esriFieldTypeDate:"esriFieldTypeDate",esriFieldTypeOID:"esriFieldTypeOID",esriFieldTypeGeometry:"esriFieldTypeGeometry",esriFieldTypeBlob:"esriFieldTypeBlob",esriFieldTypeRaster:"esriFieldTypeRaster",esriFieldTypeGUID:"esriFieldTypeGUID",esriFieldTypeGlobalID:"esriFieldTypeGlobalID",esriFieldTypeXML:"eesriFieldTypeXML"};function D(e){switch(e){case"point":default:return"esriGeometryPoint";case"polygon":return"esriGeometryPolygon";case"multipoint":return"esriGeometryMultipoint";case"polyline":return"esriGeometryPolyline"}}function x(e){return void 0===e?"":e=(e=(e=e.replace(/\/featureserver\/[0-9]*/i,"/FeatureServer")).replace(/\/mapserver\/[0-9]*/i,"/MapServer")).split("?")[0]}function N(e,r){r||(r={}),"function"==typeof r&&(r={cmp:r});const t="boolean"==typeof r.cycles&&r.cycles,i=r.cmp&&(n=r.cmp,function(e){return function(r,t){const i={key:r,value:e[r]},o={key:t,value:e[t]};return n(i,o)}});var n;const o=[];return function e(r){if(r&&r.toJSON&&"function"==typeof r.toJSON&&(r=r.toJSON()),void 0===r)return;if("number"==typeof r)return isFinite(r)?""+r:"null";if("object"!=typeof r)return JSON.stringify(r);let n,l;if(Array.isArray(r)){for(l="[",n=0;n<r.length;n++)n&&(l+=","),l+=e(r[n])||"null";return l+"]"}if(null===r)return"null";if(o.includes(r)){if(t)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}const s=o.push(r)-1,y=Object.keys(r).sort(i&&i(r));for(l="",n=0;n<y.length;n++){const t=y[n],i=e(r[t]);i&&(l&&(l+=","),l+=JSON.stringify(t)+":"+i)}return o.splice(s,1),"{"+l+"}"}(e)}export{i as FeatureServiceDatabaseType,n as IdState,v as callback,f as cloneAttributes,o as cloneField,F as convertLinearUnitsToCode,d as convertSquareUnitsToCode,G as defaultMaxRecords,m as equalityTest,S as errback,l as esriFieldToJson,x as extractServiceUrl,p as isArray,y as isBoolean,u as isNumber,s as isString,b as layerFieldEsriConstants,P as layerGeometryEsriConstants,I as layerGeometryEsriRestConstants,T as sameGeomType,g as shapeExtent,N as stableStringify,D as toEsriGeometryType};
5
+ import{ArcadeDate as e}from"../../ArcadeDate.js";import r from"../../../geometry/Extent.js";import t from"../../../layers/support/Field.js";var i,n;function o(e){return t.fromJSON(e.toJSON())}function l(e){return e.toJSON?e.toJSON():e}function s(e){return"string"==typeof e||e instanceof String}function y(e){return"boolean"==typeof e}function u(e){return"number"==typeof e}function p(e){return e instanceof Array}function c(e){return e instanceof Date}function a(r){return r instanceof e}function m(e,r){return e===r||!(!c(e)&&!a(e)||!c(r)&&!a(r))&&e.getTime()===r.getTime()}function f(e){const r={};for(const t in e)r[t]=e[t];return r}function d(e){if(null==e)return null;if("number"==typeof e)return e;switch(e.toLowerCase()){case"meters":case"meter":return 109404;case"miles":case"mile":return 109439;case"kilometers":case"kilometer":case"km":return 109414}return null}function g(e){if(null==e)return null;switch(e.type){case"polygon":case"multipoint":case"polyline":return e.extent;case"point":return new r({xmin:e.x,ymin:e.y,xmax:e.x,ymax:e.y,spatialReference:e.spatialReference});case"extent":return e}return null}function F(e){if(null==e)return null;if("number"==typeof e)return e;if("number"==typeof e)return e;switch(e.toLowerCase()){case"meters":case"meter":return 9001;case"miles":case"mile":return 9093;case"kilometers":case"kilometer":case"km":return 9036}return null}function G(e,r){return e===r||("point"===e&&"esriGeometryPoint"===r||("polyline"===e&&"esriGeometryPolyline"===r||("polygon"===e&&"esriGeometryPolygon"===r||("extent"===e&&"esriGeometryEnvelope"===r||("multipoint"===e&&"esriGeometryMultipoint"===r||("point"===r&&"esriGeometryPoint"===e||("polyline"===r&&"esriGeometryPolyline"===e||("polygon"===r&&"esriGeometryPolygon"===e||("extent"===r&&"esriGeometryEnvelope"===e||"multipoint"===r&&"esriGeometryMultipoint"===e)))))))))}!function(e){e[e.Standardised=0]="Standardised",e[e.StandardisedNoInterval=1]="StandardisedNoInterval",e[e.SqlServer=2]="SqlServer",e[e.Oracle=3]="Oracle",e[e.Postgres=4]="Postgres",e[e.PGDB=5]="PGDB",e[e.FILEGDB=6]="FILEGDB",e[e.NotEvaluated=7]="NotEvaluated"}(i||(i={})),function(e){e[e.InFeatureSet=0]="InFeatureSet",e[e.NotInFeatureSet=1]="NotInFeatureSet",e[e.Unknown=2]="Unknown"}(n||(n={}));const T=1e3;function S(e){return function(r){e.reject(r)}}function v(e,r){return function(){try{e.apply(null,arguments)}catch(t){r.reject(t)}}}const P={point:"point",polygon:"polygon",polyline:"polyline",multipoint:"multipoint",extent:"extent",esriGeometryPoint:"point",esriGeometryPolygon:"polygon",esriGeometryPolyline:"polyline",esriGeometryMultipoint:"multipoint",esriGeometryEnvelope:"extent",envelope:"extent"},I={point:"esriGeometryPoint",polygon:"esriGeometryPolygon",polyline:"esriGeometryPolyline",multipoint:"esriGeometryMultipoint",extent:"esriGeometryEnvelope",esriGeometryPoint:"esriGeometryPoint",esriGeometryPolygon:"esriGeometryPolygon",esriGeometryPolyline:"esriGeometryPolyline",esriGeometryMultipoint:"esriGeometryMultipoint",esriGeometryEnvelope:"esriGeometryEnvelope",envelope:"esriGeometryEnvelope"},b={"small-integer":"esriFieldTypeSmallInteger",integer:"esriFieldTypeInteger",long:"esriFieldTypeLong",single:"esriFieldTypeSingle",double:"esriFieldTypeDouble",string:"esriFieldTypeString",date:"esriFieldTypeDate",oid:"esriFieldTypeOID",geometry:"esriFieldTypeGeometry",blob:"esriFieldTypeBlob",raster:"esriFieldTypeRaster",guid:"esriFieldTypeGUID","global-id":"esriFieldTypeGlobalID",xml:"eesriFieldTypeXML",esriFieldTypeSmallInteger:"esriFieldTypeSmallInteger",esriFieldTypeInteger:"esriFieldTypeInteger",esriFieldTypeLong:"esriFieldTypeLong",esriFieldTypeSingle:"esriFieldTypeSingle",esriFieldTypeDouble:"esriFieldTypeDouble",esriFieldTypeString:"esriFieldTypeString",esriFieldTypeDate:"esriFieldTypeDate",esriFieldTypeOID:"esriFieldTypeOID",esriFieldTypeGeometry:"esriFieldTypeGeometry",esriFieldTypeBlob:"esriFieldTypeBlob",esriFieldTypeRaster:"esriFieldTypeRaster",esriFieldTypeGUID:"esriFieldTypeGUID",esriFieldTypeGlobalID:"esriFieldTypeGlobalID",esriFieldTypeXML:"eesriFieldTypeXML"};function D(e){switch(e){case"point":default:return"esriGeometryPoint";case"polygon":return"esriGeometryPolygon";case"multipoint":return"esriGeometryMultipoint";case"polyline":return"esriGeometryPolyline"}}function x(e){return void 0===e?"":e=(e=(e=e.replace(/\/featureserver\/[0-9]*/i,"/FeatureServer")).replace(/\/mapserver\/[0-9]*/i,"/MapServer")).split("?")[0]}function N(e,r){r||(r={}),"function"==typeof r&&(r={cmp:r});const t="boolean"==typeof r.cycles&&r.cycles,i=r.cmp&&(n=r.cmp,function(e){return function(r,t){const i={key:r,value:e[r]},o={key:t,value:e[t]};return n(i,o)}});var n;const o=[];return function e(r){if(r&&r.toJSON&&"function"==typeof r.toJSON&&(r=r.toJSON()),void 0===r)return;if("number"==typeof r)return isFinite(r)?""+r:"null";if("object"!=typeof r)return JSON.stringify(r);let n,l;if(Array.isArray(r)){for(l="[",n=0;n<r.length;n++)n&&(l+=","),l+=e(r[n])||"null";return l+"]"}if(null===r)return"null";if(o.includes(r)){if(t)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}const s=o.push(r)-1,y=Object.keys(r).sort(i&&i(r));for(l="",n=0;n<y.length;n++){const t=y[n],i=e(r[t]);i&&(l&&(l+=","),l+=JSON.stringify(t)+":"+i)}return o.splice(s,1),"{"+l+"}"}(e)}export{i as FeatureServiceDatabaseType,n as IdState,v as callback,f as cloneAttributes,o as cloneField,F as convertLinearUnitsToCode,d as convertSquareUnitsToCode,T as defaultMaxRecords,m as equalityTest,S as errback,l as esriFieldToJson,x as extractServiceUrl,a as isArcadeDate,p as isArray,y as isBoolean,c as isDate,u as isNumber,s as isString,b as layerFieldEsriConstants,P as layerGeometryEsriConstants,I as layerGeometryEsriRestConstants,G as sameGeomType,g as shapeExtent,N as stableStringify,D as toEsriGeometryType};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.26/esri/copyright.txt for details.
4
4
  */
5
- import{ArcadeDate as e}from"../../ArcadeDate.js";import{FeatureServiceDatabaseType as r}from"./shared.js";import{WhereClause as t}from"../../../core/sql/WhereClause.js";import{SqlError as n,SqlErrorCodes as a}from"./errorsupport.js";import{convertTimeReference as s}from"../../arcadeTimeUtils.js";import{DateTime as o}from"luxon";function c(e,r){return p(e?.parseTree,r,e?.parameters)}function i(e,r,n,a){return u(t.create(e,r.fieldsIndex),n,a)}function u(e,t,n){const a=s(t),o=s(n);return p(e.parseTree,r.Standardised,null,null,null,{inputTimeReference:a,outputTimeReference:o})}function l(e,r,t){return p(e,r,t)}function d(e,n,a,s){return t.create(p(e.parseTree,r.Standardised,e.parameters,n,a),s)}function f(e,n,a="AND"){return t.create("(("+c(e,r.Standardised)+")"+a+"("+c(n,r.Standardised)+"))",e.fieldsIndex)}function p(r,t,s,o=null,c=null,i=null){let u,l,d,f;switch(r.type){case"interval":return O(p(r.value,t,s,o,c,i),r.qualifier,r.op);case"case-expression":{let e=" CASE ";"simple"===r.format&&(e+=p(r.operand,t,s,o,c,i));for(let n=0;n<r.clauses.length;n++)e+=" WHEN "+p(r.clauses[n].operand,t,s,o,c,i)+" THEN "+p(r.clauses[n].value,t,s,o,c,i);return null!==r.else&&(e+=" ELSE "+p(r.else,t,s,o,c,i)),e+=" END ",e}case"parameter":{const n=s[r.value.toLowerCase()];if("string"==typeof n){return"'"+s[r.value.toLowerCase()].toString().replace(/'/g,"''")+"'"}if(n instanceof Date)return g(n,t,i);if(n instanceof e)return m(n,t,i);if(n instanceof Array){const r=[];for(let a=0;a<n.length;a++)"string"==typeof n[a]?r.push("'"+n[a].toString().replace(/'/g,"''")+"'"):n[a]instanceof Date?r.push(g(n[a],t,i)):n[a]instanceof e?r.push(m(n[a],t,i)):r.push(n[a].toString());return r}return n.toString()}case"expression-list":l=[];for(const e of r.value)l.push(p(e,t,s,o,c,i));return l;case"unary-expression":return" ( NOT "+p(r.expr,t,s,o,c,i)+" ) ";case"binary-expression":switch(r.operator){case"AND":return" ("+p(r.left,t,s,o,c,i)+" AND "+p(r.right,t,s,o,c,i)+") ";case"OR":return" ("+p(r.left,t,s,o,c,i)+" OR "+p(r.right,t,s,o,c,i)+") ";case"IS":if("null"!==r.right.type)throw new n(a.UnsupportedIsRhs);return" ("+p(r.left,t,s,o,c,i)+" IS NULL )";case"ISNOT":if("null"!==r.right.type)throw new n(a.UnsupportedIsRhs);return" ("+p(r.left,t,s,o,c,i)+" IS NOT NULL )";case"IN":return u=[],"expression-list"===r.right.type?(u=p(r.right,t,s,o,c)," ("+p(r.left,t,s,o,c,i)+" IN ("+u.join(",")+")) "):(f=p(r.right,t,s,o,c,i),f instanceof Array?" ("+p(r.left,t,s,o,c,i)+" IN ("+f.join(",")+")) ":" ("+p(r.left,t,s,o,c,i)+" IN ("+f+")) ");case"NOT IN":return u=[],"expression-list"===r.right.type?(u=p(r.right,t,s,o,c)," ("+p(r.left,t,s,o,c,i)+" NOT IN ("+u.join(",")+")) "):(f=p(r.right,t,s,o,c,i),f instanceof Array?" ("+p(r.left,t,s,o,c,i)+" NOT IN ("+f.join(",")+")) ":" ("+p(r.left,t,s,o,c,i)+" NOT IN ("+f+")) ");case"BETWEEN":return d=p(r.right,t,s,o,c,i)," ("+p(r.left,t,s,o,c,i)+" BETWEEN "+d[0]+" AND "+d[1]+" ) ";case"NOTBETWEEN":return d=p(r.right,t,s,o,c,i)," ("+p(r.left,t,s,o,c,i)+" NOT BETWEEN "+d[0]+" AND "+d[1]+" ) ";case"LIKE":return""!==r.escape?" ("+p(r.left,t,s,o,c,i)+" LIKE "+p(r.right,t,s,o,c,i)+" ESCAPE '"+r.escape+"') ":" ("+p(r.left,t,s,o,c,i)+" LIKE "+p(r.right,t,s,o,c,i)+") ";case"NOT LIKE":return""!==r.escape?" ("+p(r.left,t,s,o,c,i)+" NOT LIKE "+p(r.right,t,s,o,c,i)+" ESCAPE '"+r.escape+"') ":" ("+p(r.left,t,s,o,c,i)+" NOT LIKE "+p(r.right,t,s,o,c,i)+") ";case"<>":case"<":case">":case">=":case"<=":case"=":case"*":case"-":case"+":case"/":return" ("+p(r.left,t,s,o,c,i)+" "+r.operator+" "+p(r.right,t,s,o,c,i)+") "}throw new n(a.UnsupportedOperator,{operator:r.operator});case"null":return"null";case"boolean":return!0===r.value?"1":"0";case"string":return"'"+r.value.toString().replace(/'/g,"''")+"'";case"timestamp":case"date":return g(r.value,t,i);case"number":return r.value.toString();case"current-time":return h("date"===r.mode,t);case"column-reference":return o&&o.toLowerCase()===r.column.toLowerCase()?"("+c+")":r.column;case"function":{const e=p(r.args,t,s,o,c,i);return y(r.name,e,t)}}throw new n(a.UnsupportedSyntax,{node:r.type})}function y(e,t,s){switch(e.toLowerCase().trim()){case"abs":if(1!==t.length)throw new n(a.InvalidFunctionParameters,{function:"abs"});return"abs("+t[0]+")";case"ceiling":case"ceil":if(1!==t.length)throw new n(a.InvalidFunctionParameters,{function:"ceiling"});switch(s){case r.Standardised:case r.StandardisedNoInterval:}return"CEILING("+t[0]+")";case"floor":if(1!==t.length)throw new n(a.InvalidFunctionParameters,{function:"floor"});return"FLOOR("+t[0]+")";case"log":if(1!==t.length)throw new n(a.InvalidFunctionParameters,{function:"log"});return"LOG("+t[0]+")";case"log10":if(1!==t.length)throw new n(a.InvalidFunctionParameters,{function:"log10"});return"LOG10("+t[0]+")";case"power":if(2!==t.length)throw new n(a.InvalidFunctionParameters,{function:"power"});return"POWER("+t[0]+","+t[1]+")";case"round":if(2===t.length)return"ROUND("+t[0]+","+t[1]+")";if(1===t.length)return"ROUND("+t[0]+")";throw new n(a.InvalidFunctionParameters,{function:"round"});case"truncate":if(t.length<1||t.length>2)throw new n(a.InvalidFunctionParameters,{function:"truncate"});return s===r.SqlServer?"ROUND("+t[0]+(1===t.length?"0":","+t[1])+",1)":"TRUNCATE("+t[0]+(1===t.length?")":","+t[1]+")");case"char_length":case"len":if(1!==t.length)throw new n(a.InvalidFunctionParameters,{function:"char_length"});switch(s){case r.SqlServer:return"LEN("+t[0]+")";case r.Oracle:return"LENGTH("+t[0]+")";default:return"CHAR_LENGTH("+t[0]+")"}case"concat":if(t.length<1)throw new n(a.InvalidFunctionParameters,{function:"concat"});{let e="CONCAT(";for(let r=0;r<t.length;r++)0!==r&&(e+=","),e+=t[r];return e+=")",e}case"lower":case"lcase":if(1!==t.length)throw new n(a.InvalidFunctionParameters,{function:"lower"});return"LOWER("+t[0]+")";case"upper":case"ucase":if(1!==t.length)throw new n(a.InvalidFunctionParameters,{function:"upper"});return"UPPER("+t[0]+")";case"substring":{let e="";switch(s){case r.Oracle:return e="SUBSTR("+t[0]+","+t[1],3===t.length&&(e+=","+t[2]),e+=")",e;case r.SqlServer:return e=3===t.length?"SUBSTRING("+t[0]+","+t[1]+","+t[2]+")":"SUBSTRING("+t[0]+", "+t[1]+", LEN("+t[0]+") - "+t[1]+")",e;default:return e="SUBSTRING("+t[0]+" FROM "+t[1],3===t.length&&(e+=" FOR "+t[2]),e+=")",e}}case"extract":return"EXTRACT("+t[0].replace(/\'/g,"")+" FROM "+t[1]+")"}throw new n(a.InvalidFunctionParameters,{function:e})}function m(t,n,a,s){a?.outputTimeReference&&(t=e.arcadeDateAndZoneToArcadeDate(t,a?.outputTimeReference));const o=t.toDateTime(),c=0===o.hour&&0===o.minute&&0===o.second&&0===o.millisecond;switch(n){case r.FILEGDB:case r.Standardised:case r.StandardisedNoInterval:return c?`date '${o.toFormat("yyyy-LL-dd")}'`:`date '${o.toFormat("yyyy-LL-dd HH:mm:ss")}'`;case r.Oracle:return c?`TO_DATE('${o.toFormat("yyyy-LL-dd")}','YYYY-MM-DD')`:`TO_DATE('${o.toFormat("yyyy-LL-dd HH:mm:ss")}','YYYY-MM-DD HH24:MI:SS')`;case r.SqlServer:return`'${o.toFormat(c?"yyyy-LL-dd":"yyyy-LL-dd HH:mm:ss")}'`;case r.PGDB:return`#${o.toFormat(c?"LL-dd-yyyy":"LL-dd-yyyy HH:mm:ss")}#`;case r.Postgres:return`TIMESTAMP '${o.toFormat(c?"yyyy-LL-dd":"yyyy-LL-dd HH:mm:ss")}'`;default:return`date '${o.toFormat("yyyy-LL-dd HH:mm:ss")}'`}}function g(e,t,n,a){let s=e instanceof Date?o.fromJSDate(e):o.fromSQL(e);const c=0===s.hour&&0===s.minute&&0===s.second&&0===s.millisecond;switch(n?.inputTimeReference&&(s=o.fromObject({day:s.day,year:s.year,month:s.month,hour:s.hour,minute:s.minute,second:s.second,millisecond:s.millisecond},{zone:n.inputTimeReference})),n?.outputTimeReference&&(s=s.setZone(n.outputTimeReference)),t){case r.FILEGDB:case r.Standardised:case r.StandardisedNoInterval:return c?`date '${s.toFormat("yyyy-LL-dd")}'`:`date '${s.toFormat("yyyy-LL-dd HH:mm:ss")}'`;case r.Oracle:return c?`TO_DATE('${s.toFormat("yyyy-LL-dd")}','YYYY-MM-DD')`:`TO_DATE('${s.toFormat("yyyy-LL-dd HH:mm:ss")}','YYYY-MM-DD HH24:MI:SS')`;case r.SqlServer:return`'${s.toFormat(c?"yyyy-LL-dd":"yyyy-LL-dd HH:mm:ss")}'`;case r.PGDB:return`#${s.toFormat(c?"LL-dd-yyyy":"LL-dd-yyyy HH:mm:ss")}#`;case r.Postgres:return`TIMESTAMP '${s.toFormat(c?"yyyy-LL-dd":"yyyy-LL-dd HH:mm:ss")}'`;default:return`date '${s.toFormat("yyyy-LL-dd HH:mm:ss")}'`}}function h(e,t){switch(t){case r.FILEGDB:case r.Standardised:case r.StandardisedNoInterval:case r.Oracle:return e?"CURRENT_DATE":"CURRENT_TIMESTAMP";case r.SqlServer:return e?"CAST(GETDATE() AS DATE)":"GETDATE()";case r.PGDB:case r.Postgres:default:return e?"CURRENT_DATE":"CURRENT_TIMESTAMP"}}function T(e,r,t={}){const n={},a={},s={esriFieldTypeSmallInteger:"integer",esriFieldTypeInteger:"integer",esriFieldTypeSingle:"double",esriFieldTypeDouble:"double",esriFieldTypeString:"string",esriFieldTypeDate:"date",esriFieldTypeOID:"integer",oid:"integer",long:"integer","small-integer":"integer",integer:"integer",single:"double",double:"double",date:"date",string:"string"};for(const o of r){const e=o.type?s[o.type]:void 0;n[o.name.toLowerCase()]=void 0===e?"":e}for(const o in t){const e=s[t[o]];a[o.toLowerCase()]=void 0===e?"":e}switch(L(n,e.parseTree,e.parameters,a)){case"double":return"double";case"integer":return"integer";case"date":return"date";case"string":return"string"}return""}function L(r,t,s,o){let c;switch(t.type){case"interval":return"integer";case"case-expression":{const e=[];if("simple"===t.format){for(let n=0;n<t.clauses.length;n++)e.push(L(r,t.clauses[n].value,s,o));null!==t.else&&e.push(L(r,t.else,s,o))}else{for(let n=0;n<t.clauses.length;n++)e.push(L(r,t.else,s,o));null!==t.else&&e.push(L(r,t.else,s,o))}return E(e)}case"parameter":{const r=o[t.value.toLowerCase()];if(void 0===r&&s){const r=s[t.value.toLowerCase()];if(void 0===r)return"";if(null===r)return"";if("string"==typeof r||r instanceof String)return"string";if("boolean"==typeof r)return"boolean";if(r instanceof Date)return"date";if(r instanceof e)return"date";if("number"==typeof r)return r%1==0?"integer":"double"}return void 0===r?"":r}case"expression-list":{const e=[];for(const n of t.value)e.push(L(r,n,s,o));return e}case"unary-expression":return"boolean";case"binary-expression":switch(t.operator){case"AND":case"OR":case"IN":case"NOT IN":case"BETWEEN":case"NOTBETWEEN":case"LIKE":case"NOT LIKE":case"<>":case"<":case">":case">=":case"<=":case"=":return"boolean";case"IS":case"ISNOT":if("null"!==t.right.type)throw new n(a.UnsupportedIsRhs);return"boolean";case"*":case"-":case"+":case"/":return E([L(r,t.left,s,o),L(r,t.right,s,o)]);default:throw new n(a.UnsupportedOperator,{operator:t.operator})}case"null":return"";case"boolean":return"boolean";case"string":return"string";case"number":return null===t.value?"":t.value%1==0?"integer":"double";case"date":case"timestamp":case"current-time":return"date";case"column-reference":{const e=r[t.column.toLowerCase()];return void 0===e?"":e}case"function":switch(t.name.toLowerCase()){case"position":case"extract":case"char_length":return"integer";case"round":return c=L(r,t.args,s,o),c instanceof Array?c.length>0?c[0]:"":c;case"sign":return c=L(r,t.args,s,o),c instanceof Array&&(c=E(c)),"integer"===c||"double"===c?c:"double";case"ceiling":case"floor":case"abs":{const e=L(r,t.args,s,o);return e instanceof Array?E(e):e}case"area":case"length":case"log":case"log10":case"sin":case"cos":case"tan":case"asin":case"acos":case"atan":case"power":case"truncate":return"double";case"substring":case"trim":case"concat":case"lower":case"upper":return"string"}return""}throw new n(a.UnsupportedSyntax,{node:t.type})}const w={boolean:1,string:2,integer:3,double:4,date:5};function E(e){if(e){let r="";for(const t of e)""!==t&&(r=""===r||w[r]<w[t]?t:r);return r}return""}function S(e,r){return I(e.parseTree,r)}function N(e){return"column-reference"===e?.parseTree.type}function I(e,r){if(null==e)return!1;switch(e.type){case"when-clause":return I(e.operand,r)||I(e.value,r);case"case-expression":for(const t of e.clauses)if(I(t,r))return!0;return!("simple"!==e.format||!I(e.operand,r))||!(null===e.else||!I(e.else,r));case"parameter":case"null":case"boolean":case"date":case"timestamp":case"string":case"number":return!1;case"expression-list":for(const t of e.value)if(I(t,r))return!0;return!1;case"unary-expression":return I(e.expr,r);case"binary-expression":return I(e.left,r)||I(e.right,r);case"column-reference":return r.toLowerCase()===e.column.toLowerCase();case"function":return I(e.args,r)}return!1}function v(e){let r="";return r+=e.period.toUpperCase(),r}function O(e,r,t){let n="";return n="interval-period"===r.type?v(r):v(r.start)+" TO "+v(r.end),"INTERVAL "+t+" "+e+" "+n}export{m as arcadeDateToSqlString,i as changeSqlTimeZones,u as changeWhereClauseTimeZone,f as combine,O as convertIntervalToSql,N as isSingleField,g as makeDateString,h as makeToday,T as predictType,d as reformulateWithoutField,S as scanForField,c as toWhereClause,l as toWhereClauseFromTree,y as translateFunctionToDatabaseSpecific};
5
+ import{ArcadeDate as e}from"../../ArcadeDate.js";import{FeatureServiceDatabaseType as r,isDate as t,isArcadeDate as n}from"./shared.js";import{WhereClause as a}from"../../../core/sql/WhereClause.js";import{SqlError as s,SqlErrorCodes as o}from"./errorsupport.js";import{convertTimeReference as c}from"../../arcadeTimeUtils.js";import{DateTime as i}from"luxon";function u(e,r){return m(e?.parseTree,r,e?.parameters)}function l(e,r,t,n){return d(a.create(e,r.fieldsIndex),t,n)}function d(e,t,n){const a=c(t),s=c(n);return m(e.parseTree,r.Standardised,null,null,null,{inputTimeReference:a,outputTimeReference:s})}function f(e,r,t){return m(e,r,t)}function p(e,t,n,s){return a.create(m(e.parseTree,r.Standardised,e.parameters,t,n),s)}function y(e,t,n="AND"){return a.create("(("+u(e,r.Standardised)+")"+n+"("+u(t,r.Standardised)+"))",e.fieldsIndex)}function m(e,r,a,c=null,i=null,u=null){let l,d,f,p;switch(e.type){case"interval":return D(m(e.value,r,a,c,i,u),e.qualifier,e.op);case"case-expression":{let t=" CASE ";"simple"===e.format&&(t+=m(e.operand,r,a,c,i,u));for(let n=0;n<e.clauses.length;n++)t+=" WHEN "+m(e.clauses[n].operand,r,a,c,i,u)+" THEN "+m(e.clauses[n].value,r,a,c,i,u);return null!==e.else&&(t+=" ELSE "+m(e.else,r,a,c,i,u)),t+=" END ",t}case"parameter":{const s=a[e.value.toLowerCase()];if("string"==typeof s){return"'"+a[e.value.toLowerCase()].toString().replace(/'/g,"''")+"'"}if(t(s))return T(s,r,u);if(n(s))return h(s,r,u);if(s instanceof Array){const e=[];for(let a=0;a<s.length;a++)"string"==typeof s[a]?e.push("'"+s[a].toString().replace(/'/g,"''")+"'"):t(s[a])?e.push(T(s[a],r,u)):n(s[a])?e.push(h(s[a],r,u)):e.push(s[a].toString());return e}return s.toString()}case"expression-list":d=[];for(const t of e.value)d.push(m(t,r,a,c,i,u));return d;case"unary-expression":return" ( NOT "+m(e.expr,r,a,c,i,u)+" ) ";case"binary-expression":switch(e.operator){case"AND":return" ("+m(e.left,r,a,c,i,u)+" AND "+m(e.right,r,a,c,i,u)+") ";case"OR":return" ("+m(e.left,r,a,c,i,u)+" OR "+m(e.right,r,a,c,i,u)+") ";case"IS":if("null"!==e.right.type)throw new s(o.UnsupportedIsRhs);return" ("+m(e.left,r,a,c,i,u)+" IS NULL )";case"ISNOT":if("null"!==e.right.type)throw new s(o.UnsupportedIsRhs);return" ("+m(e.left,r,a,c,i,u)+" IS NOT NULL )";case"IN":return l=[],"expression-list"===e.right.type?(l=m(e.right,r,a,c,i)," ("+m(e.left,r,a,c,i,u)+" IN ("+l.join(",")+")) "):(p=m(e.right,r,a,c,i,u),p instanceof Array?" ("+m(e.left,r,a,c,i,u)+" IN ("+p.join(",")+")) ":" ("+m(e.left,r,a,c,i,u)+" IN ("+p+")) ");case"NOT IN":return l=[],"expression-list"===e.right.type?(l=m(e.right,r,a,c,i)," ("+m(e.left,r,a,c,i,u)+" NOT IN ("+l.join(",")+")) "):(p=m(e.right,r,a,c,i,u),p instanceof Array?" ("+m(e.left,r,a,c,i,u)+" NOT IN ("+p.join(",")+")) ":" ("+m(e.left,r,a,c,i,u)+" NOT IN ("+p+")) ");case"BETWEEN":return f=m(e.right,r,a,c,i,u)," ("+m(e.left,r,a,c,i,u)+" BETWEEN "+f[0]+" AND "+f[1]+" ) ";case"NOTBETWEEN":return f=m(e.right,r,a,c,i,u)," ("+m(e.left,r,a,c,i,u)+" NOT BETWEEN "+f[0]+" AND "+f[1]+" ) ";case"LIKE":return""!==e.escape?" ("+m(e.left,r,a,c,i,u)+" LIKE "+m(e.right,r,a,c,i,u)+" ESCAPE '"+e.escape+"') ":" ("+m(e.left,r,a,c,i,u)+" LIKE "+m(e.right,r,a,c,i,u)+") ";case"NOT LIKE":return""!==e.escape?" ("+m(e.left,r,a,c,i,u)+" NOT LIKE "+m(e.right,r,a,c,i,u)+" ESCAPE '"+e.escape+"') ":" ("+m(e.left,r,a,c,i,u)+" NOT LIKE "+m(e.right,r,a,c,i,u)+") ";case"<>":case"<":case">":case">=":case"<=":case"=":case"*":case"-":case"+":case"/":return" ("+m(e.left,r,a,c,i,u)+" "+e.operator+" "+m(e.right,r,a,c,i,u)+") "}throw new s(o.UnsupportedOperator,{operator:e.operator});case"null":return"null";case"boolean":return!0===e.value?"1":"0";case"string":return"'"+e.value.toString().replace(/'/g,"''")+"'";case"timestamp":case"date":return T(e.value,r,u);case"number":return e.value.toString();case"current-time":return L("date"===e.mode,r);case"column-reference":return c&&c.toLowerCase()===e.column.toLowerCase()?"("+i+")":e.column;case"function":{const t=m(e.args,r,a,c,i,u);return g(e.name,t,r)}}throw new s(o.UnsupportedSyntax,{node:e.type})}function g(e,t,n){switch(e.toLowerCase().trim()){case"abs":if(1!==t.length)throw new s(o.InvalidFunctionParameters,{function:"abs"});return"abs("+t[0]+")";case"ceiling":case"ceil":if(1!==t.length)throw new s(o.InvalidFunctionParameters,{function:"ceiling"});switch(n){case r.Standardised:case r.StandardisedNoInterval:}return"CEILING("+t[0]+")";case"floor":if(1!==t.length)throw new s(o.InvalidFunctionParameters,{function:"floor"});return"FLOOR("+t[0]+")";case"log":if(1!==t.length)throw new s(o.InvalidFunctionParameters,{function:"log"});return"LOG("+t[0]+")";case"log10":if(1!==t.length)throw new s(o.InvalidFunctionParameters,{function:"log10"});return"LOG10("+t[0]+")";case"power":if(2!==t.length)throw new s(o.InvalidFunctionParameters,{function:"power"});return"POWER("+t[0]+","+t[1]+")";case"round":if(2===t.length)return"ROUND("+t[0]+","+t[1]+")";if(1===t.length)return"ROUND("+t[0]+")";throw new s(o.InvalidFunctionParameters,{function:"round"});case"truncate":if(t.length<1||t.length>2)throw new s(o.InvalidFunctionParameters,{function:"truncate"});return n===r.SqlServer?"ROUND("+t[0]+(1===t.length?"0":","+t[1])+",1)":"TRUNCATE("+t[0]+(1===t.length?")":","+t[1]+")");case"char_length":case"len":if(1!==t.length)throw new s(o.InvalidFunctionParameters,{function:"char_length"});switch(n){case r.SqlServer:return"LEN("+t[0]+")";case r.Oracle:return"LENGTH("+t[0]+")";default:return"CHAR_LENGTH("+t[0]+")"}case"concat":if(t.length<1)throw new s(o.InvalidFunctionParameters,{function:"concat"});{let e="CONCAT(";for(let r=0;r<t.length;r++)0!==r&&(e+=","),e+=t[r];return e+=")",e}case"lower":case"lcase":if(1!==t.length)throw new s(o.InvalidFunctionParameters,{function:"lower"});return"LOWER("+t[0]+")";case"upper":case"ucase":if(1!==t.length)throw new s(o.InvalidFunctionParameters,{function:"upper"});return"UPPER("+t[0]+")";case"substring":{let e="";switch(n){case r.Oracle:return e="SUBSTR("+t[0]+","+t[1],3===t.length&&(e+=","+t[2]),e+=")",e;case r.SqlServer:return e=3===t.length?"SUBSTRING("+t[0]+","+t[1]+","+t[2]+")":"SUBSTRING("+t[0]+", "+t[1]+", LEN("+t[0]+") - "+t[1]+")",e;default:return e="SUBSTRING("+t[0]+" FROM "+t[1],3===t.length&&(e+=" FOR "+t[2]),e+=")",e}}case"extract":return"EXTRACT("+t[0].replace(/\'/g,"")+" FROM "+t[1]+")"}throw new s(o.InvalidFunctionParameters,{function:e})}function h(t,n,a,s){a?.outputTimeReference&&(t=e.arcadeDateAndZoneToArcadeDate(t,a?.outputTimeReference));const o=t.toDateTime(),c=0===o.hour&&0===o.minute&&0===o.second&&0===o.millisecond;switch(n){case r.FILEGDB:case r.Standardised:case r.StandardisedNoInterval:return c?`date '${o.toFormat("yyyy-LL-dd")}'`:`date '${o.toFormat("yyyy-LL-dd HH:mm:ss")}'`;case r.Oracle:return c?`TO_DATE('${o.toFormat("yyyy-LL-dd")}','YYYY-MM-DD')`:`TO_DATE('${o.toFormat("yyyy-LL-dd HH:mm:ss")}','YYYY-MM-DD HH24:MI:SS')`;case r.SqlServer:return`'${o.toFormat(c?"yyyy-LL-dd":"yyyy-LL-dd HH:mm:ss")}'`;case r.PGDB:return`#${o.toFormat(c?"LL-dd-yyyy":"LL-dd-yyyy HH:mm:ss")}#`;case r.Postgres:return`TIMESTAMP '${o.toFormat(c?"yyyy-LL-dd":"yyyy-LL-dd HH:mm:ss")}'`;default:return`date '${o.toFormat("yyyy-LL-dd HH:mm:ss")}'`}}function T(e,n,a,s){let o=t(e)?i.fromJSDate(e):i.fromSQL(e);const c=0===o.hour&&0===o.minute&&0===o.second&&0===o.millisecond;switch(a?.inputTimeReference&&(o=i.fromObject({day:o.day,year:o.year,month:o.month,hour:o.hour,minute:o.minute,second:o.second,millisecond:o.millisecond},{zone:a.inputTimeReference})),a?.outputTimeReference&&(o=o.setZone(a.outputTimeReference)),n){case r.FILEGDB:case r.Standardised:case r.StandardisedNoInterval:return c?`date '${o.toFormat("yyyy-LL-dd")}'`:`date '${o.toFormat("yyyy-LL-dd HH:mm:ss")}'`;case r.Oracle:return c?`TO_DATE('${o.toFormat("yyyy-LL-dd")}','YYYY-MM-DD')`:`TO_DATE('${o.toFormat("yyyy-LL-dd HH:mm:ss")}','YYYY-MM-DD HH24:MI:SS')`;case r.SqlServer:return`'${o.toFormat(c?"yyyy-LL-dd":"yyyy-LL-dd HH:mm:ss")}'`;case r.PGDB:return`#${o.toFormat(c?"LL-dd-yyyy":"LL-dd-yyyy HH:mm:ss")}#`;case r.Postgres:return`TIMESTAMP '${o.toFormat(c?"yyyy-LL-dd":"yyyy-LL-dd HH:mm:ss")}'`;default:return`date '${o.toFormat("yyyy-LL-dd HH:mm:ss")}'`}}function L(e,t){switch(t){case r.FILEGDB:case r.Standardised:case r.StandardisedNoInterval:case r.Oracle:return e?"CURRENT_DATE":"CURRENT_TIMESTAMP";case r.SqlServer:return e?"CAST(GETDATE() AS DATE)":"GETDATE()";case r.PGDB:case r.Postgres:default:return e?"CURRENT_DATE":"CURRENT_TIMESTAMP"}}function w(e,r,t={}){const n={},a={},s={esriFieldTypeSmallInteger:"integer",esriFieldTypeInteger:"integer",esriFieldTypeSingle:"double",esriFieldTypeDouble:"double",esriFieldTypeString:"string",esriFieldTypeDate:"date",esriFieldTypeOID:"integer",oid:"integer",long:"integer","small-integer":"integer",integer:"integer",single:"double",double:"double",date:"date",string:"string"};for(const o of r){const e=o.type?s[o.type]:void 0;n[o.name.toLowerCase()]=void 0===e?"":e}for(const o in t){const e=s[t[o]];a[o.toLowerCase()]=void 0===e?"":e}switch(E(n,e.parseTree,e.parameters,a)){case"double":return"double";case"integer":return"integer";case"date":return"date";case"string":return"string"}return""}function E(e,r,a,c){let i;switch(r.type){case"interval":return"integer";case"case-expression":{const t=[];if("simple"===r.format){for(let n=0;n<r.clauses.length;n++)t.push(E(e,r.clauses[n].value,a,c));null!==r.else&&t.push(E(e,r.else,a,c))}else{for(let n=0;n<r.clauses.length;n++)t.push(E(e,r.else,a,c));null!==r.else&&t.push(E(e,r.else,a,c))}return N(t)}case"parameter":{const e=c[r.value.toLowerCase()];if(void 0===e&&a){const e=a[r.value.toLowerCase()];if(void 0===e)return"";if(null===e)return"";if("string"==typeof e||e instanceof String)return"string";if("boolean"==typeof e)return"boolean";if(t(e))return"date";if(n(e))return"date";if("number"==typeof e)return e%1==0?"integer":"double"}return void 0===e?"":e}case"expression-list":{const t=[];for(const n of r.value)t.push(E(e,n,a,c));return t}case"unary-expression":return"boolean";case"binary-expression":switch(r.operator){case"AND":case"OR":case"IN":case"NOT IN":case"BETWEEN":case"NOTBETWEEN":case"LIKE":case"NOT LIKE":case"<>":case"<":case">":case">=":case"<=":case"=":return"boolean";case"IS":case"ISNOT":if("null"!==r.right.type)throw new s(o.UnsupportedIsRhs);return"boolean";case"*":case"-":case"+":case"/":return N([E(e,r.left,a,c),E(e,r.right,a,c)]);default:throw new s(o.UnsupportedOperator,{operator:r.operator})}case"null":return"";case"boolean":return"boolean";case"string":return"string";case"number":return null===r.value?"":r.value%1==0?"integer":"double";case"date":case"timestamp":case"current-time":return"date";case"column-reference":{const t=e[r.column.toLowerCase()];return void 0===t?"":t}case"function":switch(r.name.toLowerCase()){case"position":case"extract":case"char_length":return"integer";case"round":return i=E(e,r.args,a,c),i instanceof Array?i.length>0?i[0]:"":i;case"sign":return i=E(e,r.args,a,c),i instanceof Array&&(i=N(i)),"integer"===i||"double"===i?i:"double";case"ceiling":case"floor":case"abs":{const t=E(e,r.args,a,c);return t instanceof Array?N(t):t}case"area":case"length":case"log":case"log10":case"sin":case"cos":case"tan":case"asin":case"acos":case"atan":case"power":case"truncate":return"double";case"substring":case"trim":case"concat":case"lower":case"upper":return"string"}return""}throw new s(o.UnsupportedSyntax,{node:r.type})}const S={boolean:1,string:2,integer:3,double:4,date:5};function N(e){if(e){let r="";for(const t of e)""!==t&&(r=""===r||S[r]<S[t]?t:r);return r}return""}function I(e,r){return O(e.parseTree,r)}function v(e){return"column-reference"===e?.parseTree.type}function O(e,r){if(null==e)return!1;switch(e.type){case"when-clause":return O(e.operand,r)||O(e.value,r);case"case-expression":for(const t of e.clauses)if(O(t,r))return!0;return!("simple"!==e.format||!O(e.operand,r))||!(null===e.else||!O(e.else,r));case"parameter":case"null":case"boolean":case"date":case"timestamp":case"string":case"number":return!1;case"expression-list":for(const t of e.value)if(O(t,r))return!0;return!1;case"unary-expression":return O(e.expr,r);case"binary-expression":return O(e.left,r)||O(e.right,r);case"column-reference":return r.toLowerCase()===e.column.toLowerCase();case"function":return O(e.args,r)}return!1}function F(e){let r="";return r+=e.period.toUpperCase(),r}function D(e,r,t){let n="";return n="interval-period"===r.type?F(r):F(r.start)+" TO "+F(r.end),"INTERVAL "+t+" "+e+" "+n}export{h as arcadeDateToSqlString,l as changeSqlTimeZones,d as changeWhereClauseTimeZone,y as combine,D as convertIntervalToSql,v as isSingleField,T as makeDateString,L as makeToday,w as predictType,p as reformulateWithoutField,I as scanForField,u as toWhereClause,f as toWhereClauseFromTree,g as translateFunctionToDatabaseSpecific};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.26/esri/copyright.txt for details.
4
4
  */
5
- import"./FunctionWrapper.js";import"./ImmutableArray.js";import"./ImmutablePathArray.js";import"./ImmutablePointArray.js";import"./ArcadeDate.js";import"../geometry/Extent.js";import"../geometry/Geometry.js";import"../geometry/Multipoint.js";import"../geometry/Point.js";import"../geometry/Polygon.js";import"../geometry/Polyline.js";import"luxon";import"../core/maybe.js";import"../core/number.js";import"../geometry/support/coordsUtils.js";import"../intl/locale.js";import"./featureset/support/shared.js";import"./ArcadeModule.js";import"./executionError.js";export{I as ImplicitResult,a0 as ImplicitResultE,R as ReturnResult,$ as ReturnResultE,E as absRound,K as autoCastArrayOfPointsToMultiPoint,J as autoCastArrayOfPointsToPolygon,H as autoCastArrayOfPointsToPolyline,G as autoCastFeatureToGeometry,u as binaryOperator,o as breakResult,d as castAsJson,e as castAsJsonAsync,p as continueResult,C as defaultTimeZone,A as defaultUndefined,s as equalityTest,S as featureDomainCodeLookup,Q as featureDomainValueLookup,P as featureFullDomain,N as featureSchema,O as featureSubtypes,F as fixNullGeometry,q as fixSpatialReference,a4 as formatDate,a3 as formatNumber,M as generateUUID,Y as getDomain,_ as getDomainCode,Z as getDomainValue,B as getType,r as greaterThanLessThan,m as isArray,a as isBoolean,k as isDate,w as isFeature,T as isFeatureSet,U as isFeatureSetCollection,i as isFunctionParameter,x as isImmutableArray,z as isInteger,a2 as isJsDate,a1 as isModule,b as isNumber,f as isSimpleType,c as isString,L as multiReplace,y as pcCheck,a5 as stableStringify,D as standardiseDateFormat,W as tick,h as toBoolean,l as toDate,g as toNumber,V as toNumberArray,j as toString,X as toStringArray,t as toStringExplicit,v as voidOperation}from"../chunks/languageUtils.js";
5
+ import"./FunctionWrapper.js";import"./ImmutableArray.js";import"./ImmutablePathArray.js";import"./ImmutablePointArray.js";import"./ArcadeDate.js";import"../geometry/Extent.js";import"../geometry/Geometry.js";import"../geometry/Multipoint.js";import"../geometry/Point.js";import"../geometry/Polygon.js";import"../geometry/Polyline.js";import"luxon";import"../core/maybe.js";import"../core/number.js";import"../geometry/support/coordsUtils.js";import"../intl/locale.js";import"./featureset/support/shared.js";import"./ArcadeModule.js";import"./executionError.js";export{I as ImplicitResult,a0 as ImplicitResultE,R as ReturnResult,$ as ReturnResultE,E as absRound,K as autoCastArrayOfPointsToMultiPoint,J as autoCastArrayOfPointsToPolygon,H as autoCastArrayOfPointsToPolyline,G as autoCastFeatureToGeometry,u as binaryOperator,o as breakResult,d as castAsJson,e as castAsJsonAsync,p as continueResult,C as defaultTimeZone,A as defaultUndefined,s as equalityTest,S as featureDomainCodeLookup,Q as featureDomainValueLookup,P as featureFullDomain,N as featureSchema,O as featureSubtypes,F as fixNullGeometry,q as fixSpatialReference,a5 as formatDate,a4 as formatNumber,M as generateUUID,Y as getDomain,_ as getDomainCode,Z as getDomainValue,B as getType,r as greaterThanLessThan,m as isArray,a as isBoolean,k as isDate,w as isFeature,T as isFeatureSet,U as isFeatureSetCollection,i as isFunctionParameter,x as isImmutableArray,z as isInteger,a3 as isJsDate,a1 as isModule,b as isNumber,a2 as isObject,f as isSimpleType,c as isString,L as multiReplace,y as pcCheck,a6 as stableStringify,D as standardiseDateFormat,W as tick,h as toBoolean,l as toDate,g as toNumber,V as toNumberArray,j as toString,X as toStringArray,t as toStringExplicit,v as voidOperation}from"../chunks/languageUtils.js";
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.26/esri/copyright.txt for details.
4
4
  */
5
- import{Parser as e}from"./parser.js";import{Tokenizer as r}from"./tokenizer.js";export{AssignmentOperators,BinaryOperators,LogicalOperators,OperatorPrecedence,ParsingError,ParsingErrorCodes,ParsingErrorMessages,Syntax,TokenNames,TokenType,UnaryOperators,UpdateOperators,isArrayExpression,isAssignmentExpression,isBinaryExpression,isBlockComment,isBlockStatement,isBreakStatement,isCallExpression,isContinueStatement,isEmptyStatement,isExpression,isExpressionStatement,isForInStatement,isForStatement,isFunctionDeclaration,isIdentifier,isIfStatement,isLiteral,isLogicalExpression,isMemberExpression,isObjectExpression,isProgram,isProperty,isReturnStatement,isStatement,isTemplateElement,isTemplateLiteral,isUnaryExpression,isUpdateExpression,isVariableDeclaration,isVariableDeclarator}from"./types.js";function s(r,s,t){return new e(r,s,t).parseScript()}function t(e,s,t){const i=new r(e,s),n=[];let o;try{let e;for(;e=i.getNextToken();)t&&(e=t(e)),n.push(e)}catch(a){i.errorHandler.tolerate(a)}return i.errorHandler.tolerant&&(o=i.errors()),{tokens:n,errors:o}}export{s as parse,t as tokenize};
5
+ import{Parser as e}from"./parser.js";import{Tokenizer as r}from"./tokenizer.js";export{AssignmentOperators,BinaryOperators,Keywords,LogicalOperators,OperatorPrecedence,ParsingError,ParsingErrorCodes,ParsingErrorMessages,Syntax,TokenNames,TokenType,UnaryOperators,UpdateOperators,isArrayExpression,isAssignmentExpression,isBinaryExpression,isBlockComment,isBlockStatement,isBreakStatement,isCallExpression,isContinueStatement,isEmptyStatement,isExpression,isExpressionStatement,isForInStatement,isForStatement,isFunctionDeclaration,isIdentifier,isIfStatement,isLiteral,isLogicalExpression,isMemberExpression,isObjectExpression,isProgram,isProperty,isReturnStatement,isStatement,isTemplateElement,isTemplateLiteral,isUnaryExpression,isUpdateExpression,isVariableDeclaration,isVariableDeclarator}from"./types.js";function s(r,s,t){return new e(r,s,t).parseScript()}function t(e,s,t){const i=new r(e,s),n=[];let o;try{let e;for(;e=i.getNextToken();)t&&(e=t(e)),n.push(e)}catch(a){i.errorHandler.tolerate(a)}return i.errorHandler.tolerant&&(o=i.errors()),{tokens:n,errors:o}}export{s as parse,t as tokenize};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.26/esri/copyright.txt for details.
4
4
  */
5
- import{CommentHandler as t}from"./comment-handler.js";import{ErrorHandler as e,formatErrorDescription as r}from"./error-handler.js";import{Scanner as i}from"./scanner.js";import{OperatorPrecedence as n,TokenType as s,ParsingErrorCodes as a,ParsingError as o,Syntax as h,TokenNames as c,UpdateOperators as p,UnaryOperators as l,LogicalOperators as u,AssignmentOperators as m,isEmptyStatement as d}from"./types.js";var x,k;function w(t,e=0){let r=t.start-t.lineStart,i=t.lineNumber;return r<0&&(r+=e,i--),{index:t.start,line:i,column:r}}function g(t){return[{index:t.range[0],...t.loc.start},{index:t.range[1],...t.loc.end}]}function y(t){return n[t]??0}!function(t){t[t.None=0]="None",t[t.Function=1]="Function",t[t.IfClause=2]="IfClause",t[t.ForLoop=4]="ForLoop",t[t.WhileLoop=8]="WhileLoop"}(x||(x={})),function(t){t[t.AsObject=0]="AsObject",t[t.Automatic=1]="Automatic"}(k||(k={}));class T{constructor(r,n={},a){this.delegate=a,this.hasLineTerminator=!1,this.options={tokens:"boolean"==typeof n.tokens&&n.tokens,comments:"boolean"==typeof n.comments&&n.comments,tolerant:"boolean"==typeof n.tolerant&&n.tolerant},this.options.comments&&(this.commentHandler=new t),this.errorHandler=new e(this.options.tolerant),this.scanner=new i(r,this.errorHandler),this.context={isAssignmentTarget:!1,blockContext:x.None,curlyParsingType:k.AsObject},this.rawToken={type:s.EOF,value:"",lineNumber:this.scanner.lineNumber,lineStart:0,start:0,end:0},this.tokens=[],this.startMarker={index:0,line:this.scanner.lineNumber,column:0},this.endMarker={index:0,line:this.scanner.lineNumber,column:0},this.readNextRawToken(),this.endMarker={index:this.scanner.index,line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}}throwIfInvalidType(t,e,{validTypes:r,invalidTypes:i}){r?.some((e=>t.type===e))||i?.some((e=>t.type===e))&&this.throwError(a.InvalidExpression,e)}throwError(t,e,r=this.endMarker){const{index:i,line:n,column:s}=e,a=r.index-i-1;this.errorHandler.throwError({code:t,index:i,line:n,column:s+1,len:a})}tolerateError(t,e){throw new Error("######################################### !!!")}unexpectedTokenError(t={}){const{rawToken:e}=t;let i,{code:n,data:h}=t;if(e){if(!n)switch(e.type){case s.EOF:n=a.UnexpectedEndOfScript;break;case s.Identifier:n=a.UnexpectedIdentifier;break;case s.NumericLiteral:n=a.UnexpectedNumber;break;case s.StringLiteral:n=a.UnexpectedString;break;case s.Template:n=a.UnexpectedTemplate}i=e.value.toString()}else i="ILLEGAL";n=n??a.UnexpectedToken,h||(h={value:i});const c=r(n,h);if(e){const t=e.start,r=e.lineNumber,i=e.start-e.lineStart+1;return new o({code:n,index:t,line:r,column:i,len:e.end-e.start-1,data:h,description:c})}const{index:p,line:l}=this.endMarker;return new o({code:n,index:p,line:l,column:this.endMarker.column+1,data:h,description:c})}throwUnexpectedToken(t={}){throw t.rawToken=t.rawToken??this.rawToken,this.unexpectedTokenError(t)}collectComments(t){const{commentHandler:e}=this;e&&t?.length&&t.forEach((t=>{const r={type:t.multiLine?h.BlockComment:h.LineComment,value:this.getSourceValue(t),range:t.range,loc:t.loc};e.collectComment(r)}))}peekAhead(t){const e=()=>(this.scanner.scanComments(),this.scanner.lex()),r=this.scanner.saveState(),i=t.call(this,e);return this.scanner.restoreState(r),i}getSourceValue(t){return this.scanner.source.slice(t.start,t.end)}convertToToken(t){return{type:c[t.type],value:this.getSourceValue(t),range:[t.start,t.end],loc:{start:{line:this.startMarker.line,column:this.startMarker.column},end:{line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}}}}readNextRawToken(){this.endMarker.index=this.scanner.index,this.endMarker.line=this.scanner.lineNumber,this.endMarker.column=this.scanner.index-this.scanner.lineStart;const t=this.rawToken;this.collectComments(this.scanner.scanComments()),this.scanner.index!==this.startMarker.index&&(this.startMarker.index=this.scanner.index,this.startMarker.line=this.scanner.lineNumber,this.startMarker.column=this.scanner.index-this.scanner.lineStart),this.rawToken=this.scanner.lex(),this.hasLineTerminator=t.lineNumber!==this.rawToken.lineNumber,this.options.tokens&&this.rawToken.type!==s.EOF&&this.tokens.push(this.convertToToken(this.rawToken))}captureStartMarker(){return{index:this.startMarker.index,line:this.startMarker.line,column:this.startMarker.column}}getItemLocation(t){return{range:[t.index,this.endMarker.index],loc:{start:{line:t.line,column:t.column},end:{line:this.endMarker.line,column:this.endMarker.column}}}}finalize(t){return(this.delegate||this.commentHandler)&&(this.commentHandler?.attachComments(t),this.delegate?.(t)),t}expectPunctuator(t){const e=this.rawToken;this.matchPunctuator(t)?this.readNextRawToken():this.throwUnexpectedToken({rawToken:e,code:a.PunctuatorExpected,data:{value:t}})}expectKeyword(t){this.rawToken.type!==s.Keyword||this.rawToken.value.toLowerCase()!==t?this.throwUnexpectedToken({rawToken:this.rawToken}):this.readNextRawToken()}expectContextualKeyword(t){this.rawToken.type!==s.Identifier||this.rawToken.value.toLowerCase()!==t?this.throwUnexpectedToken({rawToken:this.rawToken}):this.readNextRawToken()}matchKeyword(t){return this.rawToken.type===s.Keyword&&this.rawToken.value.toLowerCase()===t}matchContextualKeyword(t){return this.rawToken.type===s.Identifier&&this.rawToken.value===t}matchPunctuator(t){return this.rawToken.type===s.Punctuator&&this.rawToken.value===t}getMatchingPunctuator(t){if("string"==typeof t&&(t=t.split("")),this.rawToken.type===s.Punctuator&&t?.length)return t.find(this.matchPunctuator,this)}isolateCoverGrammar(t){const e=this.context.isAssignmentTarget;this.context.isAssignmentTarget=!0;const r=t.call(this);return this.context.isAssignmentTarget=e,r}inheritCoverGrammar(t){const e=this.context.isAssignmentTarget;this.context.isAssignmentTarget=!0;const r=t.call(this);return this.context.isAssignmentTarget=this.context.isAssignmentTarget&&e,r}withBlockContext(t,e){const r=this.context.blockContext;this.context.blockContext=this.context.blockContext|t;const i=this.context.curlyParsingType;this.context.curlyParsingType=k.Automatic;const n=e.call(this);return this.context.blockContext=r,this.context.curlyParsingType=i,n}consumeSemicolon(){if(this.matchPunctuator(";"))this.readNextRawToken();else if(!this.hasLineTerminator)return this.rawToken.type===s.EOF||this.matchPunctuator("}")?(this.endMarker.index=this.startMarker.index,this.endMarker.line=this.startMarker.line,void(this.endMarker.column=this.startMarker.column)):void this.throwUnexpectedToken({rawToken:this.rawToken})}parsePrimaryExpression(){const t=this.captureStartMarker(),e=this.rawToken;switch(e.type){case s.Identifier:return this.readNextRawToken(),this.finalize({type:h.Identifier,name:e.value,...this.getItemLocation(t)});case s.NumericLiteral:case s.StringLiteral:return this.context.isAssignmentTarget=!1,this.readNextRawToken(),this.finalize({type:h.Literal,value:e.value,raw:this.getSourceValue(e),isString:"string"==typeof e.value,...this.getItemLocation(t)});case s.BooleanLiteral:return this.context.isAssignmentTarget=!1,this.readNextRawToken(),this.finalize({type:h.Literal,value:"true"===e.value.toLowerCase(),raw:this.getSourceValue(e),isString:!1,...this.getItemLocation(t)});case s.NullLiteral:return this.context.isAssignmentTarget=!1,this.readNextRawToken(),this.finalize({type:h.Literal,value:null,raw:this.getSourceValue(e),isString:!1,...this.getItemLocation(t)});case s.Template:return this.parseTemplateLiteral();case s.Punctuator:switch(e.value){case"(":return this.inheritCoverGrammar(this.parseGroupExpression);case"[":return this.inheritCoverGrammar(this.parseArrayInitializer);case"{":return this.inheritCoverGrammar(this.parseObjectExpression);default:return this.throwUnexpectedToken({rawToken:this.rawToken})}case s.Keyword:return this.context.isAssignmentTarget=!1,this.throwUnexpectedToken({rawToken:this.rawToken});default:return this.throwUnexpectedToken({rawToken:this.rawToken})}}parseArrayInitializer(){const t=this.captureStartMarker();this.expectPunctuator("[");const e=[];for(;!this.matchPunctuator("]");)this.matchPunctuator(",")?(this.readNextRawToken(),e.push(null)):(e.push(this.inheritCoverGrammar(this.parseAssignmentExpression)),this.matchPunctuator("]")||this.expectPunctuator(","));return this.expectPunctuator("]"),this.finalize({type:h.ArrayExpression,elements:e,...this.getItemLocation(t)})}parseObjectPropertyKey(){const t=this.captureStartMarker(),e=this.rawToken;switch(e.type){case s.StringLiteral:return this.readNextRawToken(),this.finalize({type:h.Literal,value:e.value,raw:this.getSourceValue(e),isString:!0,...this.getItemLocation(t)});case s.Identifier:case s.BooleanLiteral:case s.NullLiteral:case s.Keyword:return this.readNextRawToken(),this.finalize({type:h.Identifier,name:e.value,...this.getItemLocation(t)});default:this.throwError(a.KeyMustBeString,t)}}parseObjectProperty(){const t=this.rawToken,e=this.captureStartMarker(),r=this.parseObjectPropertyKey();let i=!1,n=null;return this.matchPunctuator(":")?(this.readNextRawToken(),n=this.inheritCoverGrammar(this.parseAssignmentExpression)):t.type===s.Identifier?(i=!0,n=this.finalize({type:h.Identifier,name:t.value,...this.getItemLocation(e)})):this.throwUnexpectedToken({rawToken:this.rawToken}),this.finalize({type:h.Property,kind:"init",key:r,value:n,shorthand:i,...this.getItemLocation(e)})}parseObjectExpression(){const t=this.captureStartMarker();this.expectPunctuator("{");const e=[];for(;!this.matchPunctuator("}");)e.push(this.parseObjectProperty()),this.matchPunctuator("}")||this.expectPunctuator(",");return this.expectPunctuator("}"),this.finalize({type:h.ObjectExpression,properties:e,...this.getItemLocation(t)})}parseTemplateElement(t=!1){const e=this.rawToken;e.type!==s.Template&&this.throwUnexpectedToken({rawToken:e}),t&&!e.head&&this.throwUnexpectedToken({code:a.InvalidTemplateHead,rawToken:e});const r=this.captureStartMarker();this.readNextRawToken();const{value:i,cooked:n,tail:o}=e,c=this.finalize({type:h.TemplateElement,value:{raw:i,cooked:n},tail:o,...this.getItemLocation(r)});return c.loc.start.column++,c.loc.end.column=c.loc.end.column-(o?1:2),c}parseTemplateLiteral(){const t=this.captureStartMarker(),e=[],r=[];let i=this.parseTemplateElement(!0);for(r.push(i);!i.tail;)e.push(this.parseExpression()),i=this.parseTemplateElement(),r.push(i);return this.finalize({type:h.TemplateLiteral,quasis:r,expressions:e,...this.getItemLocation(t)})}parseGroupExpression(){this.expectPunctuator("(");const t=this.inheritCoverGrammar(this.parseAssignmentExpression);return this.expectPunctuator(")"),t}parseArguments(){this.expectPunctuator("(");const t=[];if(!this.matchPunctuator(")"))for(;;){const e=this.isolateCoverGrammar(this.parseAssignmentExpression);if(t.push(e),this.matchPunctuator(")"))break;if(this.expectPunctuator(","),this.matchPunctuator(")"))break}return this.expectPunctuator(")"),t}parseMemberName(){const t=this.rawToken,e=this.captureStartMarker();return this.readNextRawToken(),t.type!==s.NullLiteral&&t.type!==s.Identifier&&t.type!==s.Keyword&&t.type!==s.BooleanLiteral&&this.throwUnexpectedToken({rawToken:t}),this.finalize({type:h.Identifier,name:t.value,...this.getItemLocation(e)})}parseLeftHandSideExpression(){const t=this.captureStartMarker();let e=this.inheritCoverGrammar(this.parsePrimaryExpression);const r=this.captureStartMarker();let i;for(;i=this.getMatchingPunctuator("([.");)switch(i){case"(":{this.context.isAssignmentTarget=!1,e.type!==h.Identifier&&e.type!==h.MemberExpression&&this.throwError(a.IdentiferExpected,t,r);const i=this.parseArguments();e=this.finalize({type:h.CallExpression,callee:e,arguments:i,...this.getItemLocation(t)});continue}case"[":{this.context.isAssignmentTarget=!0,this.expectPunctuator("[");const r=this.isolateCoverGrammar(this.parseExpression);this.expectPunctuator("]"),e=this.finalize({type:h.MemberExpression,computed:!0,object:e,property:r,...this.getItemLocation(t)});continue}case".":{this.context.isAssignmentTarget=!0,this.expectPunctuator(".");const r=this.parseMemberName();e=this.finalize({type:h.MemberExpression,computed:!1,object:e,property:r,...this.getItemLocation(t)});continue}}return e}parseUpdateExpression(){const t=this.captureStartMarker();let e=this.getMatchingPunctuator(p);if(e){this.readNextRawToken();const r=this.captureStartMarker(),i=this.inheritCoverGrammar(this.parseUnaryExpression);return i.type!==h.Identifier&&i.type!==h.MemberExpression&&i.type!==h.CallExpression&&this.throwError(a.InvalidExpression,r),this.context.isAssignmentTarget||this.tolerateError(a.InvalidLeftHandSideInAssignment,t),this.context.isAssignmentTarget=!1,this.finalize({type:h.UpdateExpression,operator:e,argument:i,prefix:!0,...this.getItemLocation(t)})}const r=this.captureStartMarker(),i=this.inheritCoverGrammar(this.parseLeftHandSideExpression),n=this.captureStartMarker();return this.hasLineTerminator?i:(e=this.getMatchingPunctuator(p),e?(i.type!==h.Identifier&&i.type!==h.MemberExpression&&this.throwError(a.InvalidExpression,r,n),this.context.isAssignmentTarget||this.tolerateError(a.InvalidLeftHandSideInAssignment,t),this.readNextRawToken(),this.context.isAssignmentTarget=!1,this.finalize({type:h.UpdateExpression,operator:e,argument:i,prefix:!1,...this.getItemLocation(t)})):i)}parseUnaryExpression(){const t=this.getMatchingPunctuator(l);if(t){const e=this.captureStartMarker();this.readNextRawToken();const r=this.inheritCoverGrammar(this.parseUnaryExpression);return this.context.isAssignmentTarget=!1,this.finalize({type:h.UnaryExpression,operator:t,argument:r,prefix:!0,...this.getItemLocation(e)})}return this.parseUpdateExpression()}parseBinaryExpression(){const t=this.rawToken;let e=this.inheritCoverGrammar(this.parseUnaryExpression);if(this.rawToken.type!==s.Punctuator)return e;const r=this.rawToken.value;let i=y(r);if(0===i)return e;this.readNextRawToken(),this.context.isAssignmentTarget=!1;const n=[t,this.rawToken];let a=e,o=this.inheritCoverGrammar(this.parseUnaryExpression);const h=[a,r,o],c=[i];for(;this.rawToken.type===s.Punctuator&&(i=y(this.rawToken.value))>0;){for(;h.length>2&&i<=c[c.length-1];){o=h.pop();const t=h.pop();c.pop(),a=h.pop(),n.pop();const e=n[n.length-1],r=w(e,e.lineStart);h.push(this.finalize(this.createBinaryOrLogicalExpression(r,t,a,o)))}h.push(this.rawToken.value),c.push(i),n.push(this.rawToken),this.readNextRawToken(),h.push(this.inheritCoverGrammar(this.parseUnaryExpression))}let p=h.length-1;e=h[p];let l=n.pop();for(;p>1;){const t=n.pop();if(!t)break;const r=l?.lineStart,i=w(t,r),s=h[p-1];e=this.finalize(this.createBinaryOrLogicalExpression(i,s,h[p-2],e)),p-=2,l=t}return e}createBinaryOrLogicalExpression(t,e,r,i){const n=u.includes(e)?h.LogicalExpression:h.BinaryExpression;return n===h.BinaryExpression||(r.type!==h.AssignmentExpression&&r.type!==h.UpdateExpression||this.throwError(a.InvalidExpression,...g(r)),i.type!==h.AssignmentExpression&&i.type!==h.UpdateExpression||this.throwError(a.InvalidExpression,...g(r))),{type:n,operator:e,left:r,right:i,...this.getItemLocation(t)}}parseAssignmentExpression(){const t=this.captureStartMarker(),e=this.inheritCoverGrammar(this.parseBinaryExpression),r=this.captureStartMarker(),i=this.getMatchingPunctuator(m);if(!i)return e;e.type!==h.Identifier&&e.type!==h.MemberExpression&&this.throwError(a.InvalidExpression,t,r),this.context.isAssignmentTarget||this.tolerateError(a.InvalidLeftHandSideInAssignment,t),this.matchPunctuator("=")||(this.context.isAssignmentTarget=!1),this.readNextRawToken();const n=this.isolateCoverGrammar(this.parseAssignmentExpression);return this.finalize({type:h.AssignmentExpression,left:e,operator:i,right:n,...this.getItemLocation(t)})}parseExpression(){return this.isolateCoverGrammar(this.parseAssignmentExpression)}parseStatements(t=null){const e=[];for(;this.rawToken.type!==s.EOF&&!this.matchPunctuator(t);){const t=this.parseStatementListItem();d(t)||e.push(t)}return e}parseStatementListItem(){return this.context.isAssignmentTarget=!0,this.matchKeyword("function")?this.parseFunctionDeclaration():this.matchKeyword("export")?this.parseExportDeclaration():this.matchKeyword("import")?this.parseImportDeclaration():this.parseStatement()}parseBlock(){const t=this.captureStartMarker();this.expectPunctuator("{");const e=this.parseStatements("}");return this.expectPunctuator("}"),this.finalize({type:h.BlockStatement,body:e,...this.getItemLocation(t)})}parseObjectStatement(){const t=this.captureStartMarker(),e=this.parseObjectExpression();return this.finalize({type:h.ExpressionStatement,expression:e,...this.getItemLocation(t)})}parseBlockOrObjectStatement(){if(this.context.curlyParsingType===k.AsObject)return this.parseObjectStatement();return this.peekAhead((t=>{let e=t();return(e.type===s.Identifier||e.type===s.StringLiteral)&&(e=t(),e.type===s.Punctuator&&":"===e.value)}))?this.parseObjectStatement():this.parseBlock()}parseIdentifier(){const t=this.rawToken;if(t.type!==s.Identifier)return null;const e=this.captureStartMarker();return this.readNextRawToken(),this.finalize({type:h.Identifier,name:t.value,...this.getItemLocation(e)})}parseVariableDeclarator(){const t=this.captureStartMarker(),e=this.parseIdentifier();e||this.throwUnexpectedToken({code:a.IdentiferExpected});let r=null;if(this.matchPunctuator("=")){this.readNextRawToken();const t=this.rawToken;try{r=this.isolateCoverGrammar(this.parseAssignmentExpression)}catch(i){this.throwUnexpectedToken({rawToken:t,code:a.InvalidVariableAssignment})}}return this.finalize({type:h.VariableDeclarator,id:e,init:r,...this.getItemLocation(t)})}parseVariableDeclarationList(){const t=[this.parseVariableDeclarator()];for(;this.matchPunctuator(",");)this.readNextRawToken(),t.push(this.parseVariableDeclarator());return t}parseVariableDeclaration(){const t=this.captureStartMarker();this.expectKeyword("var");const e=this.parseVariableDeclarationList();return this.consumeSemicolon(),this.finalize({type:h.VariableDeclaration,declarations:e,kind:"var",...this.getItemLocation(t)})}parseEmptyStatement(){const t=this.captureStartMarker();return this.expectPunctuator(";"),this.finalize({type:h.EmptyStatement,...this.getItemLocation(t)})}parseExpressionStatement(){const t=this.captureStartMarker(),e=this.parseExpression();return this.consumeSemicolon(),this.finalize({type:h.ExpressionStatement,expression:e,...this.getItemLocation(t)})}parseIfClause(){return this.withBlockContext(x.IfClause,this.parseStatement)}parseIfStatement(){const t=this.captureStartMarker();this.expectKeyword("if"),this.expectPunctuator("(");const e=this.captureStartMarker(),r=this.parseExpression(),i=this.captureStartMarker();this.expectPunctuator(")"),r.type!==h.AssignmentExpression&&r.type!==h.UpdateExpression||this.throwError(a.InvalidExpression,e,i);const n=this.parseIfClause();let s=null;return this.matchKeyword("else")&&(this.readNextRawToken(),s=this.parseIfClause()),this.finalize({type:h.IfStatement,test:r,consequent:n,alternate:s,...this.getItemLocation(t)})}parseWhileStatement(){const t=this.captureStartMarker();this.expectKeyword("while"),this.expectPunctuator("(");const e=this.captureStartMarker(),r=this.parseExpression(),i=this.captureStartMarker();this.expectPunctuator(")"),r.type!==h.AssignmentExpression&&r.type!==h.UpdateExpression||this.throwError(a.InvalidExpression,e,i);const n=this.withBlockContext(x.WhileLoop,this.parseStatement);return this.finalize({type:h.WhileStatement,test:r,body:n,...this.getItemLocation(t)})}parseForStatement(){let t=null,e=null,r=null,i=null,n=null;const s=this.captureStartMarker();if(this.expectKeyword("for"),this.expectPunctuator("("),this.matchPunctuator(";"))this.readNextRawToken();else if(this.matchKeyword("var")){const e=this.captureStartMarker();this.readNextRawToken();const r=this.parseVariableDeclarationList();if(1===r.length&&this.matchKeyword("in")){r[0].init&&this.throwError(a.ForInOfLoopInitializer,e),i=this.finalize({type:h.VariableDeclaration,declarations:r,kind:"var",...this.getItemLocation(e)}),this.readNextRawToken(),n=this.parseExpression()}else this.matchKeyword("in")&&this.throwError(a.InvalidLeftHandSideInForIn,e),t=this.finalize({type:h.VariableDeclaration,declarations:r,kind:"var",...this.getItemLocation(e)}),this.expectPunctuator(";")}else{const e=this.context.isAssignmentTarget,r=this.captureStartMarker();t=this.inheritCoverGrammar(this.parseAssignmentExpression),this.matchKeyword("in")?(this.context.isAssignmentTarget||this.tolerateError(a.InvalidLeftHandSideInForIn,r),t.type!==h.Identifier&&this.throwError(a.InvalidLeftHandSideInForIn,r),this.readNextRawToken(),i=t,n=this.parseExpression(),t=null):(this.context.isAssignmentTarget=e,this.expectPunctuator(";"))}i||(this.matchPunctuator(";")||(e=this.isolateCoverGrammar(this.parseExpression)),this.expectPunctuator(";"),this.matchPunctuator(")")||(r=this.isolateCoverGrammar(this.parseExpression))),this.expectPunctuator(")");const o=this.withBlockContext(x.ForLoop,(()=>this.isolateCoverGrammar(this.parseStatement)));return i&&n?this.finalize({type:h.ForInStatement,left:i,right:n,body:o,...this.getItemLocation(s)}):this.finalize({type:h.ForStatement,init:t,test:e,update:r,body:o,...this.getItemLocation(s)})}parseContinueStatement(){const t=this.captureStartMarker();return this.expectKeyword("continue"),this.consumeSemicolon(),this.finalize({type:h.ContinueStatement,...this.getItemLocation(t)})}parseBreakStatement(){const t=this.captureStartMarker();return this.expectKeyword("break"),this.consumeSemicolon(),this.finalize({type:h.BreakStatement,...this.getItemLocation(t)})}parseReturnStatement(){const t=this.captureStartMarker();this.expectKeyword("return");const e=!this.matchPunctuator(";")&&!this.matchPunctuator("}")&&!this.hasLineTerminator&&this.rawToken.type!==s.EOF||this.rawToken.type===s.StringLiteral||this.rawToken.type===s.Template?this.parseExpression():null;return this.consumeSemicolon(),this.finalize({type:h.ReturnStatement,argument:e,...this.getItemLocation(t)})}parseStatement(){switch(this.rawToken.type){case s.BooleanLiteral:case s.NullLiteral:case s.NumericLiteral:case s.StringLiteral:case s.Template:case s.Identifier:return this.parseExpressionStatement();case s.Punctuator:return"{"===this.rawToken.value?this.parseBlockOrObjectStatement():"("===this.rawToken.value?this.parseExpressionStatement():";"===this.rawToken.value?this.parseEmptyStatement():this.parseExpressionStatement();case s.Keyword:switch(this.rawToken.value.toLowerCase()){case"break":return this.parseBreakStatement();case"continue":return this.parseContinueStatement();case"for":return this.parseForStatement();case"function":return this.parseFunctionDeclaration();case"if":return this.parseIfStatement();case"return":return this.parseReturnStatement();case"var":return this.parseVariableDeclaration();case"while":return this.parseWhileStatement();default:return this.parseExpressionStatement()}default:return this.throwUnexpectedToken({rawToken:this.rawToken})}}parseFormalParameters(){const t=[];if(this.expectPunctuator("("),!this.matchPunctuator(")"))for(;this.rawToken.type!==s.EOF;){const e=this.parseIdentifier();if(e||this.throwUnexpectedToken({rawToken:this.rawToken,code:a.IdentiferExpected}),t.push(e),this.matchPunctuator(")"))break;if(this.expectPunctuator(","),this.matchPunctuator(")"))break}return this.expectPunctuator(")"),t}parseFunctionDeclaration(){(this.context.blockContext&x.Function)===x.Function&&this.throwUnexpectedToken({code:a.NoFunctionInsideFunction}),(this.context.blockContext&x.WhileLoop)!==x.WhileLoop&&(this.context.blockContext&x.IfClause)!==x.IfClause||this.throwUnexpectedToken({code:a.NoFunctionInsideBlock});const t=this.captureStartMarker();this.expectKeyword("function");const e=this.parseIdentifier();e||this.throwUnexpectedToken({code:a.InvalidFunctionIdentifier});const r=this.parseFormalParameters(),i=this.context.blockContext;this.context.blockContext=this.context.blockContext|x.Function;const n=this.parseBlock();return this.context.blockContext=i,this.finalize({type:h.FunctionDeclaration,id:e,params:r,body:n,...this.getItemLocation(t)})}parseScript(){const t=this.captureStartMarker(),e=this.parseStatements(),r=this.finalize({type:h.Program,body:e,...this.getItemLocation(t)});return this.options.tokens&&(r.tokens=this.tokens),this.options.tolerant&&(r.errors=this.errorHandler.errors),r}parseExportDeclaration(){this.context.blockContext!==x.None&&this.throwUnexpectedToken({code:a.ModuleExportRootOnly});let t=null;const e=this.captureStartMarker();return this.expectKeyword("export"),this.matchKeyword("var")?t=this.parseVariableDeclaration():this.matchKeyword("function")?t=this.parseFunctionDeclaration():this.throwUnexpectedToken({code:a.InvalidExpression}),this.finalize({type:h.ExportNamedDeclaration,declaration:t,specifiers:[],source:null,...this.getItemLocation(e)})}parseModuleSpecifier(){const t=this.captureStartMarker(),e=this.rawToken;if(e.type===s.StringLiteral)return this.readNextRawToken(),this.finalize({type:h.Literal,value:e.value,raw:this.getSourceValue(e),isString:!0,...this.getItemLocation(t)});this.throwError(a.InvalidModuleUri,t)}parseDefaultSpecifier(){const t=this.captureStartMarker(),e=this.parseIdentifier();return e||this.throwUnexpectedToken({code:a.InvalidFunctionIdentifier}),this.finalize({type:h.ImportDefaultSpecifier,local:e,...this.getItemLocation(t)})}parseImportDeclaration(){this.context.blockContext!==x.None&&this.throwUnexpectedToken({code:a.ModuleImportRootOnly});const t=this.captureStartMarker();this.expectKeyword("import");const e=this.parseDefaultSpecifier();this.expectContextualKeyword("from");const r=this.parseModuleSpecifier();return this.finalize({type:h.ImportDeclaration,specifiers:[e],source:r,...this.getItemLocation(t)})}}export{T as Parser,y as binaryOperatorPrecedence};
5
+ import{CommentHandler as t}from"./comment-handler.js";import{ErrorHandler as e,formatErrorDescription as r}from"./error-handler.js";import{Scanner as i}from"./scanner.js";import{OperatorPrecedence as n,TokenType as s,ParsingErrorCodes as a,ParsingError as o,Syntax as h,TokenNames as c,Keywords as p,UpdateOperators as l,UnaryOperators as u,LogicalOperators as m,AssignmentOperators as d,isEmptyStatement as x}from"./types.js";var k,w;function g(t,e=0){let r=t.start-t.lineStart,i=t.lineNumber;return r<0&&(r+=e,i--),{index:t.start,line:i,column:r}}function y(t){return[{index:t.range[0],...t.loc.start},{index:t.range[1],...t.loc.end}]}function T(t){return n[t]??0}!function(t){t[t.None=0]="None",t[t.Function=1]="Function",t[t.IfClause=2]="IfClause",t[t.ForLoop=4]="ForLoop",t[t.WhileLoop=8]="WhileLoop"}(k||(k={})),function(t){t[t.AsObject=0]="AsObject",t[t.Automatic=1]="Automatic"}(w||(w={}));class f{constructor(r,n={},a){this.delegate=a,this.hasLineTerminator=!1,this.options={tokens:"boolean"==typeof n.tokens&&n.tokens,comments:"boolean"==typeof n.comments&&n.comments,tolerant:"boolean"==typeof n.tolerant&&n.tolerant},this.options.comments&&(this.commentHandler=new t),this.errorHandler=new e(this.options.tolerant),this.scanner=new i(r,this.errorHandler),this.context={isAssignmentTarget:!1,blockContext:k.None,curlyParsingType:w.AsObject},this.rawToken={type:s.EOF,value:"",lineNumber:this.scanner.lineNumber,lineStart:0,start:0,end:0},this.tokens=[],this.startMarker={index:0,line:this.scanner.lineNumber,column:0},this.endMarker={index:0,line:this.scanner.lineNumber,column:0},this.readNextRawToken(),this.endMarker={index:this.scanner.index,line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}}throwIfInvalidType(t,e,{validTypes:r,invalidTypes:i}){r?.some((e=>t.type===e))||i?.some((e=>t.type===e))&&this.throwError(a.InvalidExpression,e)}throwError(t,e,r=this.endMarker){const{index:i,line:n,column:s}=e,a=r.index-i-1;this.errorHandler.throwError({code:t,index:i,line:n,column:s+1,len:a})}tolerateError(t,e){throw new Error("######################################### !!!")}unexpectedTokenError(t={}){const{rawToken:e}=t;let i,{code:n,data:h}=t;if(e){if(!n)switch(e.type){case s.EOF:n=a.UnexpectedEndOfScript;break;case s.Identifier:n=a.UnexpectedIdentifier;break;case s.NumericLiteral:n=a.UnexpectedNumber;break;case s.StringLiteral:n=a.UnexpectedString;break;case s.Template:n=a.UnexpectedTemplate}i=e.value.toString()}else i="ILLEGAL";n=n??a.UnexpectedToken,h||(h={value:i});const c=r(n,h);if(e){const t=e.start,r=e.lineNumber,i=e.start-e.lineStart+1;return new o({code:n,index:t,line:r,column:i,len:e.end-e.start-1,data:h,description:c})}const{index:p,line:l}=this.endMarker;return new o({code:n,index:p,line:l,column:this.endMarker.column+1,data:h,description:c})}throwUnexpectedToken(t={}){throw t.rawToken=t.rawToken??this.rawToken,this.unexpectedTokenError(t)}collectComments(t){const{commentHandler:e}=this;e&&t.length&&t.forEach((t=>{const r={type:t.multiLine?h.BlockComment:h.LineComment,value:this.getSourceValue(t),range:t.range,loc:t.loc};e.collectComment(r)}))}peekAhead(t){const e=()=>(this.scanner.scanComments(),this.scanner.lex()),r=this.scanner.saveState(),i=t.call(this,e);return this.scanner.restoreState(r),i}getSourceValue(t){return this.scanner.source.slice(t.start,t.end)}convertToToken(t){return{type:c[t.type],value:this.getSourceValue(t),range:[t.start,t.end],loc:{start:{line:this.startMarker.line,column:this.startMarker.column},end:{line:this.scanner.lineNumber,column:this.scanner.index-this.scanner.lineStart}}}}readNextRawToken(){this.endMarker.index=this.scanner.index,this.endMarker.line=this.scanner.lineNumber,this.endMarker.column=this.scanner.index-this.scanner.lineStart;const t=this.rawToken;this.collectComments(this.scanner.scanComments()),this.scanner.index!==this.startMarker.index&&(this.startMarker.index=this.scanner.index,this.startMarker.line=this.scanner.lineNumber,this.startMarker.column=this.scanner.index-this.scanner.lineStart),this.rawToken=this.scanner.lex(),this.hasLineTerminator=t.lineNumber!==this.rawToken.lineNumber,this.options.tokens&&this.rawToken.type!==s.EOF&&this.tokens.push(this.convertToToken(this.rawToken))}captureStartMarker(){return{index:this.startMarker.index,line:this.startMarker.line,column:this.startMarker.column}}getItemLocation(t){return{range:[t.index,this.endMarker.index],loc:{start:{line:t.line,column:t.column},end:{line:this.endMarker.line,column:this.endMarker.column}}}}finalize(t){return(this.delegate||this.commentHandler)&&(this.commentHandler?.attachComments(t),this.delegate?.(t)),t}expectPunctuator(t){const e=this.rawToken;this.matchPunctuator(t)?this.readNextRawToken():this.throwUnexpectedToken({rawToken:e,code:a.PunctuatorExpected,data:{value:t}})}expectKeyword(t){this.rawToken.type!==s.Keyword||this.rawToken.value.toLowerCase()!==t?this.throwUnexpectedToken({rawToken:this.rawToken}):this.readNextRawToken()}expectContextualKeyword(t){this.rawToken.type!==s.Identifier||this.rawToken.value.toLowerCase()!==t?this.throwUnexpectedToken({rawToken:this.rawToken}):this.readNextRawToken()}matchKeyword(t){return this.rawToken.type===s.Keyword&&this.rawToken.value.toLowerCase()===t}matchContextualKeyword(t){return this.rawToken.type===s.Identifier&&this.rawToken.value===t}matchPunctuator(t){return this.rawToken.type===s.Punctuator&&this.rawToken.value===t}getMatchingPunctuator(t){if("string"==typeof t&&(t=t.split("")),this.rawToken.type===s.Punctuator&&t?.length)return t.find(this.matchPunctuator,this)}isolateCoverGrammar(t){const e=this.context.isAssignmentTarget;this.context.isAssignmentTarget=!0;const r=t.call(this);return this.context.isAssignmentTarget=e,r}inheritCoverGrammar(t){const e=this.context.isAssignmentTarget;this.context.isAssignmentTarget=!0;const r=t.call(this);return this.context.isAssignmentTarget=this.context.isAssignmentTarget&&e,r}withBlockContext(t,e){const r=this.context.blockContext;this.context.blockContext=this.context.blockContext|t;const i=this.context.curlyParsingType;this.context.curlyParsingType=w.Automatic;const n=e.call(this);return this.context.blockContext=r,this.context.curlyParsingType=i,n}consumeSemicolon(){if(this.matchPunctuator(";"))this.readNextRawToken();else if(!this.hasLineTerminator)return this.rawToken.type===s.EOF||this.matchPunctuator("}")?(this.endMarker.index=this.startMarker.index,this.endMarker.line=this.startMarker.line,void(this.endMarker.column=this.startMarker.column)):void this.throwUnexpectedToken({rawToken:this.rawToken})}parsePrimaryExpression(){const t=this.captureStartMarker(),e=this.rawToken;switch(e.type){case s.Identifier:return this.readNextRawToken(),this.finalize({type:h.Identifier,name:e.value,...this.getItemLocation(t)});case s.NumericLiteral:case s.StringLiteral:return this.context.isAssignmentTarget=!1,this.readNextRawToken(),this.finalize({type:h.Literal,value:e.value,raw:this.getSourceValue(e),isString:"string"==typeof e.value,...this.getItemLocation(t)});case s.BooleanLiteral:return this.context.isAssignmentTarget=!1,this.readNextRawToken(),this.finalize({type:h.Literal,value:e.value.toLowerCase()===p.True,raw:this.getSourceValue(e),isString:!1,...this.getItemLocation(t)});case s.NullLiteral:return this.context.isAssignmentTarget=!1,this.readNextRawToken(),this.finalize({type:h.Literal,value:null,raw:this.getSourceValue(e),isString:!1,...this.getItemLocation(t)});case s.Template:return this.parseTemplateLiteral();case s.Punctuator:switch(e.value){case"(":return this.inheritCoverGrammar(this.parseGroupExpression);case"[":return this.inheritCoverGrammar(this.parseArrayInitializer);case"{":return this.inheritCoverGrammar(this.parseObjectExpression);default:return this.throwUnexpectedToken({rawToken:this.rawToken})}case s.Keyword:return this.context.isAssignmentTarget=!1,this.throwUnexpectedToken({rawToken:this.rawToken});default:return this.throwUnexpectedToken({rawToken:this.rawToken})}}parseArrayInitializer(){const t=this.captureStartMarker();this.expectPunctuator("[");const e=[];for(;!this.matchPunctuator("]");){const t=this.captureStartMarker();this.matchPunctuator(",")?(this.readNextRawToken(),this.throwError(a.InvalidExpression,t)):(e.push(this.inheritCoverGrammar(this.parseAssignmentExpression)),this.matchPunctuator("]")||this.expectPunctuator(","))}return this.expectPunctuator("]"),this.finalize({type:h.ArrayExpression,elements:e,...this.getItemLocation(t)})}parseObjectPropertyKey(){const t=this.captureStartMarker(),e=this.rawToken;switch(e.type){case s.StringLiteral:return this.readNextRawToken(),this.finalize({type:h.Literal,value:e.value,raw:this.getSourceValue(e),isString:!0,...this.getItemLocation(t)});case s.Identifier:case s.BooleanLiteral:case s.NullLiteral:case s.Keyword:return this.readNextRawToken(),this.finalize({type:h.Identifier,name:e.value,...this.getItemLocation(t)});default:this.throwError(a.KeyMustBeString,t)}}parseObjectProperty(){const t=this.rawToken,e=this.captureStartMarker(),r=this.parseObjectPropertyKey();let i=!1,n=null;return this.matchPunctuator(":")?(this.readNextRawToken(),n=this.inheritCoverGrammar(this.parseAssignmentExpression)):t.type===s.Identifier?(i=!0,n=this.finalize({type:h.Identifier,name:t.value,...this.getItemLocation(e)})):this.throwUnexpectedToken({rawToken:this.rawToken}),this.finalize({type:h.Property,kind:"init",key:r,value:n,shorthand:i,...this.getItemLocation(e)})}parseObjectExpression(){const t=this.captureStartMarker();this.expectPunctuator("{");const e=[];for(;!this.matchPunctuator("}");)e.push(this.parseObjectProperty()),this.matchPunctuator("}")||this.expectPunctuator(",");return this.expectPunctuator("}"),this.finalize({type:h.ObjectExpression,properties:e,...this.getItemLocation(t)})}parseTemplateElement(t=!1){const e=this.rawToken;e.type!==s.Template&&this.throwUnexpectedToken({rawToken:e}),t&&!e.head&&this.throwUnexpectedToken({code:a.InvalidTemplateHead,rawToken:e});const r=this.captureStartMarker();this.readNextRawToken();const{value:i,cooked:n,tail:o}=e,c=this.finalize({type:h.TemplateElement,value:{raw:i,cooked:n},tail:o,...this.getItemLocation(r)});return c.loc.start.column++,c.loc.end.column=c.loc.end.column-(o?1:2),c}parseTemplateLiteral(){const t=this.captureStartMarker(),e=[],r=[];let i=this.parseTemplateElement(!0);for(r.push(i);!i.tail;)e.push(this.parseExpression()),i=this.parseTemplateElement(),r.push(i);return this.finalize({type:h.TemplateLiteral,quasis:r,expressions:e,...this.getItemLocation(t)})}parseGroupExpression(){this.expectPunctuator("(");const t=this.inheritCoverGrammar(this.parseAssignmentExpression);return this.expectPunctuator(")"),t}parseArguments(){this.expectPunctuator("(");const t=[];if(!this.matchPunctuator(")"))for(;;){const e=this.isolateCoverGrammar(this.parseAssignmentExpression);if(t.push(e),this.matchPunctuator(")"))break;if(this.expectPunctuator(","),this.matchPunctuator(")"))break}return this.expectPunctuator(")"),t}parseMemberName(){const t=this.rawToken,e=this.captureStartMarker();return this.readNextRawToken(),t.type!==s.NullLiteral&&t.type!==s.Identifier&&t.type!==s.Keyword&&t.type!==s.BooleanLiteral&&this.throwUnexpectedToken({rawToken:t}),this.finalize({type:h.Identifier,name:t.value,...this.getItemLocation(e)})}parseLeftHandSideExpression(){const t=this.captureStartMarker();let e=this.inheritCoverGrammar(this.parsePrimaryExpression);const r=this.captureStartMarker();let i;for(;i=this.getMatchingPunctuator("([.");)switch(i){case"(":{this.context.isAssignmentTarget=!1,e.type!==h.Identifier&&e.type!==h.MemberExpression&&this.throwError(a.IdentiferExpected,t,r);const i=this.parseArguments();e=this.finalize({type:h.CallExpression,callee:e,arguments:i,...this.getItemLocation(t)});continue}case"[":{this.context.isAssignmentTarget=!0,this.expectPunctuator("[");const r=this.isolateCoverGrammar(this.parseExpression);this.expectPunctuator("]"),e=this.finalize({type:h.MemberExpression,computed:!0,object:e,property:r,...this.getItemLocation(t)});continue}case".":{this.context.isAssignmentTarget=!0,this.expectPunctuator(".");const r=this.parseMemberName();e=this.finalize({type:h.MemberExpression,computed:!1,object:e,property:r,...this.getItemLocation(t)});continue}}return e}parseUpdateExpression(){const t=this.captureStartMarker();let e=this.getMatchingPunctuator(l);if(e){this.readNextRawToken();const r=this.captureStartMarker(),i=this.inheritCoverGrammar(this.parseUnaryExpression);return i.type!==h.Identifier&&i.type!==h.MemberExpression&&i.type!==h.CallExpression&&this.throwError(a.InvalidExpression,r),this.context.isAssignmentTarget||this.tolerateError(a.InvalidLeftHandSideInAssignment,t),this.context.isAssignmentTarget=!1,this.finalize({type:h.UpdateExpression,operator:e,argument:i,prefix:!0,...this.getItemLocation(t)})}const r=this.captureStartMarker(),i=this.inheritCoverGrammar(this.parseLeftHandSideExpression),n=this.captureStartMarker();return this.hasLineTerminator?i:(e=this.getMatchingPunctuator(l),e?(i.type!==h.Identifier&&i.type!==h.MemberExpression&&this.throwError(a.InvalidExpression,r,n),this.context.isAssignmentTarget||this.tolerateError(a.InvalidLeftHandSideInAssignment,t),this.readNextRawToken(),this.context.isAssignmentTarget=!1,this.finalize({type:h.UpdateExpression,operator:e,argument:i,prefix:!1,...this.getItemLocation(t)})):i)}parseUnaryExpression(){const t=this.getMatchingPunctuator(u);if(t){const e=this.captureStartMarker();this.readNextRawToken();const r=this.inheritCoverGrammar(this.parseUnaryExpression);return this.context.isAssignmentTarget=!1,this.finalize({type:h.UnaryExpression,operator:t,argument:r,prefix:!0,...this.getItemLocation(e)})}return this.parseUpdateExpression()}parseBinaryExpression(){const t=this.rawToken;let e=this.inheritCoverGrammar(this.parseUnaryExpression);if(this.rawToken.type!==s.Punctuator)return e;const r=this.rawToken.value;let i=T(r);if(0===i)return e;this.readNextRawToken(),this.context.isAssignmentTarget=!1;const n=[t,this.rawToken];let a=e,o=this.inheritCoverGrammar(this.parseUnaryExpression);const h=[a,r,o],c=[i];for(;this.rawToken.type===s.Punctuator&&(i=T(this.rawToken.value))>0;){for(;h.length>2&&i<=c[c.length-1];){o=h.pop();const t=h.pop();c.pop(),a=h.pop(),n.pop();const e=n[n.length-1],r=g(e,e.lineStart);h.push(this.finalize(this.createBinaryOrLogicalExpression(r,t,a,o)))}h.push(this.rawToken.value),c.push(i),n.push(this.rawToken),this.readNextRawToken(),h.push(this.inheritCoverGrammar(this.parseUnaryExpression))}let p=h.length-1;e=h[p];let l=n.pop();for(;p>1;){const t=n.pop();if(!t)break;const r=l?.lineStart,i=g(t,r),s=h[p-1];e=this.finalize(this.createBinaryOrLogicalExpression(i,s,h[p-2],e)),p-=2,l=t}return e}createBinaryOrLogicalExpression(t,e,r,i){const n=m.includes(e)?h.LogicalExpression:h.BinaryExpression;return n===h.BinaryExpression||(r.type!==h.AssignmentExpression&&r.type!==h.UpdateExpression||this.throwError(a.InvalidExpression,...y(r)),i.type!==h.AssignmentExpression&&i.type!==h.UpdateExpression||this.throwError(a.InvalidExpression,...y(r))),{type:n,operator:e,left:r,right:i,...this.getItemLocation(t)}}parseAssignmentExpression(){const t=this.captureStartMarker(),e=this.inheritCoverGrammar(this.parseBinaryExpression),r=this.captureStartMarker(),i=this.getMatchingPunctuator(d);if(!i)return e;e.type!==h.Identifier&&e.type!==h.MemberExpression&&this.throwError(a.InvalidExpression,t,r),this.context.isAssignmentTarget||this.tolerateError(a.InvalidLeftHandSideInAssignment,t),this.matchPunctuator("=")||(this.context.isAssignmentTarget=!1),this.readNextRawToken();const n=this.isolateCoverGrammar(this.parseAssignmentExpression);return this.finalize({type:h.AssignmentExpression,left:e,operator:i,right:n,...this.getItemLocation(t)})}parseExpression(){return this.isolateCoverGrammar(this.parseAssignmentExpression)}parseStatements(t){const e=[];for(;this.rawToken.type!==s.EOF&&!this.matchPunctuator(t);){const t=this.parseStatementListItem();x(t)||e.push(t)}return e}parseStatementListItem(){return this.context.isAssignmentTarget=!0,this.matchKeyword(p.Function)?this.parseFunctionDeclaration():this.matchKeyword(p.Export)?this.parseExportDeclaration():this.matchKeyword(p.Import)?this.parseImportDeclaration():this.parseStatement()}parseBlock(){const t=this.captureStartMarker();this.expectPunctuator("{");const e=this.parseStatements("}");return this.expectPunctuator("}"),this.finalize({type:h.BlockStatement,body:e,...this.getItemLocation(t)})}parseObjectStatement(){const t=this.captureStartMarker(),e=this.parseObjectExpression();return this.finalize({type:h.ExpressionStatement,expression:e,...this.getItemLocation(t)})}parseBlockOrObjectStatement(){if(this.context.curlyParsingType===w.AsObject)return this.parseObjectStatement();return this.peekAhead((t=>{let e=t();return(e.type===s.Identifier||e.type===s.StringLiteral)&&(e=t(),e.type===s.Punctuator&&":"===e.value)}))?this.parseObjectStatement():this.parseBlock()}parseIdentifier(){const t=this.rawToken;if(t.type!==s.Identifier)return null;const e=this.captureStartMarker();return this.readNextRawToken(),this.finalize({type:h.Identifier,name:t.value,...this.getItemLocation(e)})}parseVariableDeclarator(){const t=this.captureStartMarker(),e=this.parseIdentifier();e||this.throwUnexpectedToken({code:a.IdentiferExpected});let r=null;if(this.matchPunctuator("=")){this.readNextRawToken();const t=this.rawToken;try{r=this.isolateCoverGrammar(this.parseAssignmentExpression)}catch(i){this.throwUnexpectedToken({rawToken:t,code:a.InvalidVariableAssignment})}}return this.finalize({type:h.VariableDeclarator,id:e,init:r,...this.getItemLocation(t)})}parseVariableDeclarationList(){const t=[this.parseVariableDeclarator()];for(;this.matchPunctuator(",");)this.readNextRawToken(),t.push(this.parseVariableDeclarator());return t}parseVariableDeclaration(){const t=this.captureStartMarker();this.expectKeyword(p.Var);const e=this.parseVariableDeclarationList();return this.consumeSemicolon(),this.finalize({type:h.VariableDeclaration,declarations:e,kind:"var",...this.getItemLocation(t)})}parseEmptyStatement(){const t=this.captureStartMarker();return this.expectPunctuator(";"),this.finalize({type:h.EmptyStatement,...this.getItemLocation(t)})}parseExpressionStatement(){const t=this.captureStartMarker(),e=this.parseExpression();return this.consumeSemicolon(),this.finalize({type:h.ExpressionStatement,expression:e,...this.getItemLocation(t)})}parseIfClause(){return this.withBlockContext(k.IfClause,this.parseStatement)}parseIfStatement(){const t=this.captureStartMarker();this.expectKeyword(p.If),this.expectPunctuator("(");const e=this.captureStartMarker(),r=this.parseExpression(),i=this.captureStartMarker();this.expectPunctuator(")"),r.type!==h.AssignmentExpression&&r.type!==h.UpdateExpression||this.throwError(a.InvalidExpression,e,i);const n=this.parseIfClause();let s=null;return this.matchKeyword(p.Else)&&(this.readNextRawToken(),s=this.parseIfClause()),this.finalize({type:h.IfStatement,test:r,consequent:n,alternate:s,...this.getItemLocation(t)})}parseWhileStatement(){const t=this.captureStartMarker();this.expectKeyword(p.While),this.expectPunctuator("(");const e=this.captureStartMarker(),r=this.parseExpression(),i=this.captureStartMarker();this.expectPunctuator(")"),r.type!==h.AssignmentExpression&&r.type!==h.UpdateExpression||this.throwError(a.InvalidExpression,e,i);const n=this.withBlockContext(k.WhileLoop,this.parseStatement);return this.finalize({type:h.WhileStatement,test:r,body:n,...this.getItemLocation(t)})}parseForStatement(){let t=null,e=null,r=null,i=null,n=null;const s=this.captureStartMarker();if(this.expectKeyword(p.For),this.expectPunctuator("("),this.matchPunctuator(";"))this.readNextRawToken();else if(this.matchKeyword(p.Var)){const e=this.captureStartMarker();this.readNextRawToken();const r=this.parseVariableDeclarationList();if(1===r.length&&this.matchKeyword(p.In)){r[0].init&&this.throwError(a.ForInOfLoopInitializer,e),i=this.finalize({type:h.VariableDeclaration,declarations:r,kind:"var",...this.getItemLocation(e)}),this.readNextRawToken(),n=this.parseExpression()}else this.matchKeyword(p.In)&&this.throwError(a.InvalidLeftHandSideInForIn,e),t=this.finalize({type:h.VariableDeclaration,declarations:r,kind:"var",...this.getItemLocation(e)}),this.expectPunctuator(";")}else{const e=this.context.isAssignmentTarget,r=this.captureStartMarker();t=this.inheritCoverGrammar(this.parseAssignmentExpression),this.matchKeyword(p.In)?(this.context.isAssignmentTarget||this.tolerateError(a.InvalidLeftHandSideInForIn,r),t.type!==h.Identifier&&this.throwError(a.InvalidLeftHandSideInForIn,r),this.readNextRawToken(),i=t,n=this.parseExpression(),t=null):(this.context.isAssignmentTarget=e,this.expectPunctuator(";"))}i||(this.matchPunctuator(";")||(e=this.isolateCoverGrammar(this.parseExpression)),this.expectPunctuator(";"),this.matchPunctuator(")")||(r=this.isolateCoverGrammar(this.parseExpression))),this.expectPunctuator(")");const o=this.withBlockContext(k.ForLoop,(()=>this.isolateCoverGrammar(this.parseStatement)));return i&&n?this.finalize({type:h.ForInStatement,left:i,right:n,body:o,...this.getItemLocation(s)}):this.finalize({type:h.ForStatement,init:t,test:e,update:r,body:o,...this.getItemLocation(s)})}parseContinueStatement(){const t=this.captureStartMarker();return this.expectKeyword(p.Continue),this.consumeSemicolon(),this.finalize({type:h.ContinueStatement,...this.getItemLocation(t)})}parseBreakStatement(){const t=this.captureStartMarker();return this.expectKeyword(p.Break),this.consumeSemicolon(),this.finalize({type:h.BreakStatement,...this.getItemLocation(t)})}parseReturnStatement(){const t=this.captureStartMarker();this.expectKeyword(p.Return);const e=!this.matchPunctuator(";")&&!this.matchPunctuator("}")&&!this.hasLineTerminator&&this.rawToken.type!==s.EOF||this.rawToken.type===s.StringLiteral||this.rawToken.type===s.Template?this.parseExpression():null;return this.consumeSemicolon(),this.finalize({type:h.ReturnStatement,argument:e,...this.getItemLocation(t)})}parseStatement(){switch(this.rawToken.type){case s.BooleanLiteral:case s.NullLiteral:case s.NumericLiteral:case s.StringLiteral:case s.Template:case s.Identifier:return this.parseExpressionStatement();case s.Punctuator:return"{"===this.rawToken.value?this.parseBlockOrObjectStatement():"("===this.rawToken.value?this.parseExpressionStatement():";"===this.rawToken.value?this.parseEmptyStatement():this.parseExpressionStatement();case s.Keyword:switch(this.rawToken.value.toLowerCase()){case p.Break:return this.parseBreakStatement();case p.Continue:return this.parseContinueStatement();case p.For:return this.parseForStatement();case p.Function:return this.parseFunctionDeclaration();case p.If:return this.parseIfStatement();case p.Return:return this.parseReturnStatement();case p.Var:return this.parseVariableDeclaration();case p.While:return this.parseWhileStatement();default:return this.parseExpressionStatement()}default:return this.throwUnexpectedToken({rawToken:this.rawToken})}}parseFormalParameters(){const t=[];if(this.expectPunctuator("("),!this.matchPunctuator(")"))for(;this.rawToken.type!==s.EOF;){const e=this.parseIdentifier();if(e||this.throwUnexpectedToken({rawToken:this.rawToken,code:a.IdentiferExpected}),t.push(e),this.matchPunctuator(")"))break;if(this.expectPunctuator(","),this.matchPunctuator(")"))break}return this.expectPunctuator(")"),t}parseFunctionDeclaration(){(this.context.blockContext&k.Function)===k.Function&&this.throwUnexpectedToken({code:a.NoFunctionInsideFunction}),(this.context.blockContext&k.WhileLoop)!==k.WhileLoop&&(this.context.blockContext&k.IfClause)!==k.IfClause||this.throwUnexpectedToken({code:a.NoFunctionInsideBlock});const t=this.captureStartMarker();this.expectKeyword(p.Function);const e=this.parseIdentifier();e||this.throwUnexpectedToken({code:a.InvalidFunctionIdentifier});const r=this.parseFormalParameters(),i=this.context.blockContext;this.context.blockContext=this.context.blockContext|k.Function;const n=this.parseBlock();return this.context.blockContext=i,this.finalize({type:h.FunctionDeclaration,id:e,params:r,body:n,...this.getItemLocation(t)})}parseScript(){const t=this.captureStartMarker(),e=this.parseStatements(),r=this.finalize({type:h.Program,body:e,...this.getItemLocation(t)});return this.options.tokens&&(r.tokens=this.tokens),this.options.tolerant&&(r.errors=this.errorHandler.errors),r}parseExportDeclaration(){this.context.blockContext!==k.None&&this.throwUnexpectedToken({code:a.ModuleExportRootOnly});let t=null;const e=this.captureStartMarker();return this.expectKeyword(p.Export),this.matchKeyword(p.Var)?t=this.parseVariableDeclaration():this.matchKeyword("function")?t=this.parseFunctionDeclaration():this.throwUnexpectedToken({code:a.InvalidExpression}),this.finalize({type:h.ExportNamedDeclaration,declaration:t,specifiers:[],source:null,...this.getItemLocation(e)})}parseModuleSpecifier(){const t=this.captureStartMarker(),e=this.rawToken;if(e.type===s.StringLiteral)return this.readNextRawToken(),this.finalize({type:h.Literal,value:e.value,raw:this.getSourceValue(e),isString:!0,...this.getItemLocation(t)});this.throwError(a.InvalidModuleUri,t)}parseDefaultSpecifier(){const t=this.captureStartMarker(),e=this.parseIdentifier();return e||this.throwUnexpectedToken({code:a.IdentiferExpected}),this.finalize({type:h.ImportDefaultSpecifier,local:e,...this.getItemLocation(t)})}parseImportDeclaration(){this.context.blockContext!==k.None&&this.throwUnexpectedToken({code:a.ModuleImportRootOnly});const t=this.captureStartMarker();this.expectKeyword(p.Import);const e=this.parseDefaultSpecifier();this.expectContextualKeyword(p.From);const r=this.parseModuleSpecifier();return this.finalize({type:h.ImportDeclaration,specifiers:[e],source:r,...this.getItemLocation(t)})}}export{f as Parser,T as binaryOperatorPrecedence};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.26/esri/copyright.txt for details.
4
4
  */
5
- import{assert as e}from"./assert.js";import{Character as t}from"./character.js";import{UpdateOperators as i,UnaryOperators as s,LogicalOperators as n,AssignmentOperators as r,BinaryOperators as h,ParsingErrorCodes as c,TokenType as o}from"./types.js";function a(e){return"0123456789abcdef".indexOf(e.toLowerCase())}function d(e){return"01234567".indexOf(e)}const l=[[],[],[]];i.forEach((e=>l[e.length-1].push(e))),s.forEach((e=>l[e.length-1].push(e))),n.forEach((e=>l[e.length-1].push(e))),r.forEach((e=>l[e.length-1].push(e))),h.forEach((e=>l[e.length-1].push(e)));class u{constructor(e,t){this.source=e,this.errorHandler=t,this._length=e.length,this.index=0,this.lineNumber=1,this.lineStart=0,this.curlyStack=[]}saveState(){return{index:this.index,lineNumber:this.lineNumber,lineStart:this.lineStart,curlyStack:this.curlyStack.slice()}}restoreState(e){this.index=e.index,this.lineNumber=e.lineNumber,this.lineStart=e.lineStart,this.curlyStack=e.curlyStack}eof(){return this.index>=this._length}throwUnexpectedToken(e=c.UnexpectedToken){this.errorHandler.throwError({code:e,index:this.index,line:this.lineNumber,column:this.index-this.lineStart+1})}tolerateUnexpectedToken(e=c.UnexpectedToken){this.errorHandler.tolerateError({code:e,index:this.index,line:this.lineNumber,column:this.index-this.lineStart+1})}skipSingleLineComment(e){const i=[],s=this.index-e,n={start:{line:this.lineNumber,column:this.index-this.lineStart-e},end:{line:0,column:0}};for(;!this.eof();){const r=this.source.charCodeAt(this.index);if(++this.index,t.isLineTerminator(r)){if(n){n.end={line:this.lineNumber,column:this.index-this.lineStart-1};const t={multiLine:!1,start:s+e,end:this.index-1,range:[s,this.index-1],loc:n};i.push(t)}return 13===r&&10===this.source.charCodeAt(this.index)&&++this.index,++this.lineNumber,this.lineStart=this.index,i}}if(n){n.end={line:this.lineNumber,column:this.index-this.lineStart};const t={multiLine:!1,start:s+e,end:this.index,range:[s,this.index],loc:n};i.push(t)}return i}skipMultiLineComment(){const e=[],i=this.index-2,s={start:{line:this.lineNumber,column:this.index-this.lineStart-2},end:{line:0,column:0}};for(;!this.eof();){const n=this.source.charCodeAt(this.index);if(t.isLineTerminator(n))13===n&&10===this.source.charCodeAt(this.index+1)&&++this.index,++this.lineNumber,++this.index,this.lineStart=this.index;else if(42===n){if(47===this.source.charCodeAt(this.index+1)){if(this.index+=2,s){s.end={line:this.lineNumber,column:this.index-this.lineStart};const t={multiLine:!0,start:i+2,end:this.index-2,range:[i,this.index],loc:s};e.push(t)}return e}++this.index}else++this.index}if(s){s.end={line:this.lineNumber,column:this.index-this.lineStart};const t={multiLine:!0,start:i+2,end:this.index,range:[i,this.index],loc:s};e.push(t)}return this.tolerateUnexpectedToken(),e}scanComments(){let e=[];for(;!this.eof();){let i=this.source.charCodeAt(this.index);if(t.isWhiteSpace(i))++this.index;else if(t.isLineTerminator(i))++this.index,13===i&&10===this.source.charCodeAt(this.index)&&++this.index,++this.lineNumber,this.lineStart=this.index;else{if(47!==i)break;if(i=this.source.charCodeAt(this.index+1),47===i){this.index+=2;const t=this.skipSingleLineComment(2);e=[...e,...t]}else{if(42!==i)break;{this.index+=2;const t=this.skipMultiLineComment();e=[...e,...t]}}}}return e}isKeyword(e){switch((e=e.toLowerCase()).length){case 2:return"if"===e||"in"===e;case 3:return"var"===e||"for"===e;case 4:return"else"===e;case 5:return"break"===e||"while"===e;case 6:return"return"===e||"import"===e||"export"===e;case 8:return"function"===e||"continue"===e;default:return!1}}codePointAt(e){let t=this.source.charCodeAt(e);if(t>=55296&&t<=56319){const i=this.source.charCodeAt(e+1);if(i>=56320&&i<=57343){t=1024*(t-55296)+i-56320+65536}}return t}scanHexEscape(e){const i="u"===e?4:2;let s=0;for(let n=0;n<i;++n){if(this.eof()||!t.isHexDigit(this.source.charCodeAt(this.index)))return null;s=16*s+a(this.source[this.index++])}return String.fromCharCode(s)}scanUnicodeCodePointEscape(){let e=this.source[this.index],i=0;for("}"===e&&this.throwUnexpectedToken();!this.eof()&&(e=this.source[this.index++],t.isHexDigit(e.charCodeAt(0)));)i=16*i+a(e);return(i>1114111||"}"!==e)&&this.throwUnexpectedToken(),t.fromCodePoint(i)}getIdentifier(){const e=this.index++;for(;!this.eof();){const i=this.source.charCodeAt(this.index);if(92===i)return this.index=e,this.getComplexIdentifier();if(i>=55296&&i<57343)return this.index=e,this.getComplexIdentifier();if(!t.isIdentifierPart(i))break;++this.index}return this.source.slice(e,this.index)}getComplexIdentifier(){let e,i=this.codePointAt(this.index),s=t.fromCodePoint(i);for(this.index+=s.length,92===i&&(117!==this.source.charCodeAt(this.index)&&this.throwUnexpectedToken(),++this.index,"{"===this.source[this.index]?(++this.index,e=this.scanUnicodeCodePointEscape()):(e=this.scanHexEscape("u"),null!==e&&"\\"!==e&&t.isIdentifierStart(e.charCodeAt(0))||this.throwUnexpectedToken()),s=e);!this.eof()&&(i=this.codePointAt(this.index),t.isIdentifierPart(i));)e=t.fromCodePoint(i),s+=e,this.index+=e.length,92===i&&(s=s.substring(0,s.length-1),117!==this.source.charCodeAt(this.index)&&this.throwUnexpectedToken(),++this.index,"{"===this.source[this.index]?(++this.index,e=this.scanUnicodeCodePointEscape()):(e=this.scanHexEscape("u"),null!==e&&"\\"!==e&&t.isIdentifierPart(e.charCodeAt(0))||this.throwUnexpectedToken()),s+=e);return s}octalToDecimal(e){let i="0"!==e,s=d(e);return!this.eof()&&t.isOctalDigit(this.source.charCodeAt(this.index))&&(i=!0,s=8*s+d(this.source[this.index++]),"0123".includes(e)&&!this.eof()&&t.isOctalDigit(this.source.charCodeAt(this.index))&&(s=8*s+d(this.source[this.index++]))),{code:s,octal:i}}scanIdentifier(){let e;const t=this.index,i=92===this.source.charCodeAt(t)?this.getComplexIdentifier():this.getIdentifier();if(e=1===i.length?o.Identifier:this.isKeyword(i)?o.Keyword:"null"===i.toLowerCase()?o.NullLiteral:"true"===i.toLowerCase()||"false"===i.toLowerCase()?o.BooleanLiteral:o.Identifier,e!==o.Identifier&&t+i.length!==this.index){const e=this.index;this.index=t,this.tolerateUnexpectedToken(c.InvalidEscapedReservedWord),this.index=e}return{type:e,value:i,lineNumber:this.lineNumber,lineStart:this.lineStart,start:t,end:this.index}}scanPunctuator(){const e=this.index;let t=this.source[this.index];switch(t){case"(":case"{":"{"===t&&this.curlyStack.push("{"),++this.index;break;case".":case")":case";":case",":case"[":case"]":case":":case"?":case"~":++this.index;break;case"}":++this.index,this.curlyStack.pop();break;default:for(let e=l.length;e>0;e--)if(t=this.source.substring(this.index,this.index+e),l[e-1].includes(t)){this.index+=e;break}}return this.index===e&&this.throwUnexpectedToken(),{type:o.Punctuator,value:t,lineNumber:this.lineNumber,lineStart:this.lineStart,start:e,end:this.index}}scanHexLiteral(e){let i="";for(;!this.eof()&&t.isHexDigit(this.source.charCodeAt(this.index));)i+=this.source[this.index++];return 0===i.length&&this.throwUnexpectedToken(),t.isIdentifierStart(this.source.charCodeAt(this.index))&&this.throwUnexpectedToken(),{type:o.NumericLiteral,value:parseInt("0x"+i,16),lineNumber:this.lineNumber,lineStart:this.lineStart,start:e,end:this.index}}scanBinaryLiteral(e){let i="";for(;!this.eof();){const e=this.source[this.index];if("0"!==e&&"1"!==e)break;i+=this.source[this.index++]}if(0===i.length&&this.throwUnexpectedToken(),!this.eof()){const e=this.source.charCodeAt(this.index);(t.isIdentifierStart(e)||t.isDecimalDigit(e))&&this.throwUnexpectedToken()}return{type:o.NumericLiteral,value:parseInt(i,2),lineNumber:this.lineNumber,lineStart:this.lineStart,start:e,end:this.index}}scanOctalLiteral(e,i){let s="",n=!1;for(t.isOctalDigit(e.charCodeAt(0))?(n=!0,s="0"+this.source[this.index++]):++this.index;!this.eof()&&t.isOctalDigit(this.source.charCodeAt(this.index));)s+=this.source[this.index++];return n||0!==s.length||this.throwUnexpectedToken(),(t.isIdentifierStart(this.source.charCodeAt(this.index))||t.isDecimalDigit(this.source.charCodeAt(this.index)))&&this.throwUnexpectedToken(),{type:o.NumericLiteral,value:parseInt(s,8),lineNumber:this.lineNumber,lineStart:this.lineStart,start:i,end:this.index}}scanNumericLiteral(){const i=this.index;let s=this.source[i];e(t.isDecimalDigit(s.charCodeAt(0))||"."===s,"Numeric literal must start with a decimal digit or a decimal point");let n="";if("."!==s){if(n=this.source[this.index++],s=this.source[this.index],"0"===n){if("x"===s||"X"===s)return++this.index,this.scanHexLiteral(i);if("b"===s||"B"===s)return++this.index,this.scanBinaryLiteral(i);if("o"===s||"O"===s)return this.scanOctalLiteral(s,i)}for(;t.isDecimalDigit(this.source.charCodeAt(this.index));)n+=this.source[this.index++];s=this.source[this.index]}if("."===s){for(n+=this.source[this.index++];t.isDecimalDigit(this.source.charCodeAt(this.index));)n+=this.source[this.index++];s=this.source[this.index]}if("e"===s||"E"===s)if(n+=this.source[this.index++],s=this.source[this.index],"+"!==s&&"-"!==s||(n+=this.source[this.index++]),t.isDecimalDigit(this.source.charCodeAt(this.index)))for(;t.isDecimalDigit(this.source.charCodeAt(this.index));)n+=this.source[this.index++];else this.throwUnexpectedToken();return t.isIdentifierStart(this.source.charCodeAt(this.index))&&this.throwUnexpectedToken(),{type:o.NumericLiteral,value:parseFloat(n),lineNumber:this.lineNumber,lineStart:this.lineStart,start:i,end:this.index}}scanStringLiteral(){const i=this.index;let s=this.source[i];e("'"===s||'"'===s,"String literal must starts with a quote"),++this.index;let n=!1,r="";for(;!this.eof();){let e=this.source[this.index++];if(e===s){s="";break}if("\\"===e)if(e=this.source[this.index++],e&&t.isLineTerminator(e.charCodeAt(0)))++this.lineNumber,"\r"===e&&"\n"===this.source[this.index]&&++this.index,this.lineStart=this.index;else switch(e){case"u":if("{"===this.source[this.index])++this.index,r+=this.scanUnicodeCodePointEscape();else{const t=this.scanHexEscape(e);null===t&&this.throwUnexpectedToken(),r+=t}break;case"x":{const t=this.scanHexEscape(e);null===t&&this.throwUnexpectedToken(c.InvalidHexEscapeSequence),r+=t;break}case"n":r+="\n";break;case"r":r+="\r";break;case"t":r+="\t";break;case"b":r+="\b";break;case"f":r+="\f";break;case"v":r+="\v";break;case"8":case"9":r+=e,this.tolerateUnexpectedToken();break;default:if(e&&t.isOctalDigit(e.charCodeAt(0))){const t=this.octalToDecimal(e);n=t.octal||n,r+=String.fromCharCode(t.code)}else r+=e}else{if(t.isLineTerminator(e.charCodeAt(0)))break;r+=e}}return""!==s&&(this.index=i,this.throwUnexpectedToken()),{type:o.StringLiteral,value:r,lineNumber:this.lineNumber,lineStart:this.lineStart,start:i,end:this.index}}scanTemplate(){let e="",i=!1;const s=this.index,n="`"===this.source[s];let r=!1,h=2;for(++this.index;!this.eof();){let s=this.source[this.index++];if("`"===s){h=1,r=!0,i=!0;break}if("$"!==s)if("\\"!==s)t.isLineTerminator(s.charCodeAt(0))?(++this.lineNumber,"\r"===s&&"\n"===this.source[this.index]&&++this.index,this.lineStart=this.index,e+="\n"):e+=s;else if(s=this.source[this.index++],t.isLineTerminator(s.charCodeAt(0)))++this.lineNumber,"\r"===s&&"\n"===this.source[this.index]&&++this.index,this.lineStart=this.index;else switch(s){case"n":e+="\n";break;case"r":e+="\r";break;case"t":e+="\t";break;case"u":if("{"===this.source[this.index])++this.index,e+=this.scanUnicodeCodePointEscape();else{const t=this.index,i=this.scanHexEscape(s);null!==i?e+=i:(this.index=t,e+=s)}break;case"x":{const t=this.scanHexEscape(s);null===t&&this.throwUnexpectedToken(c.InvalidHexEscapeSequence),e+=t;break}case"b":e+="\b";break;case"f":e+="\f";break;case"v":e+="\v";break;default:"0"===s?(t.isDecimalDigit(this.source.charCodeAt(this.index))&&this.throwUnexpectedToken(c.TemplateOctalLiteral),e+="\0"):t.isOctalDigit(s.charCodeAt(0))?this.throwUnexpectedToken(c.TemplateOctalLiteral):e+=s}else{if("{"===this.source[this.index]){this.curlyStack.push("${"),++this.index,i=!0;break}e+=s}}return i||this.throwUnexpectedToken(),n||this.curlyStack.pop(),{type:o.Template,value:this.source.slice(s+1,this.index-h),cooked:e,head:n,tail:r,lineNumber:this.lineNumber,lineStart:this.lineStart,start:s,end:this.index}}lex(){if(this.eof())return{type:o.EOF,value:"",lineNumber:this.lineNumber,lineStart:this.lineStart,start:this.index,end:this.index};const e=this.source.charCodeAt(this.index);return t.isIdentifierStart(e)?this.scanIdentifier():40===e||41===e||59===e?this.scanPunctuator():39===e||34===e?this.scanStringLiteral():46===e?t.isDecimalDigit(this.source.charCodeAt(this.index+1))?this.scanNumericLiteral():this.scanPunctuator():t.isDecimalDigit(e)?this.scanNumericLiteral():96===e||125===e&&"${"===this.curlyStack[this.curlyStack.length-1]?this.scanTemplate():e>=55296&&e<57343&&t.isIdentifierStart(this.codePointAt(this.index))?this.scanIdentifier():this.scanPunctuator()}}export{u as Scanner};
5
+ import{assert as e}from"./assert.js";import{Character as t}from"./character.js";import{UpdateOperators as i,UnaryOperators as s,LogicalOperators as n,AssignmentOperators as r,BinaryOperators as h,ParsingErrorCodes as c,Keywords as o,TokenType as a}from"./types.js";function d(e){return"0123456789abcdef".indexOf(e.toLowerCase())}function l(e){return"01234567".indexOf(e)}const u=[[],[],[]];i.forEach((e=>u[e.length-1].push(e))),s.forEach((e=>u[e.length-1].push(e))),n.forEach((e=>u[e.length-1].push(e))),r.forEach((e=>u[e.length-1].push(e))),h.forEach((e=>u[e.length-1].push(e)));class x{constructor(e,t){this.source=e,this.errorHandler=t,this._length=e.length,this.index=0,this.lineNumber=1,this.lineStart=0,this.curlyStack=[]}saveState(){return{index:this.index,lineNumber:this.lineNumber,lineStart:this.lineStart,curlyStack:this.curlyStack.slice()}}restoreState(e){this.index=e.index,this.lineNumber=e.lineNumber,this.lineStart=e.lineStart,this.curlyStack=e.curlyStack}eof(){return this.index>=this._length}throwUnexpectedToken(e=c.UnexpectedToken){this.errorHandler.throwError({code:e,index:this.index,line:this.lineNumber,column:this.index-this.lineStart+1})}tolerateUnexpectedToken(e=c.UnexpectedToken){this.errorHandler.tolerateError({code:e,index:this.index,line:this.lineNumber,column:this.index-this.lineStart+1})}skipSingleLineComment(e){const i=[],s=this.index-e,n={start:{line:this.lineNumber,column:this.index-this.lineStart-e},end:{line:0,column:0}};for(;!this.eof();){const r=this.source.charCodeAt(this.index);if(++this.index,t.isLineTerminator(r)){if(n){n.end={line:this.lineNumber,column:this.index-this.lineStart-1};const t={multiLine:!1,start:s+e,end:this.index-1,range:[s,this.index-1],loc:n};i.push(t)}return 13===r&&10===this.source.charCodeAt(this.index)&&++this.index,++this.lineNumber,this.lineStart=this.index,i}}if(n){n.end={line:this.lineNumber,column:this.index-this.lineStart};const t={multiLine:!1,start:s+e,end:this.index,range:[s,this.index],loc:n};i.push(t)}return i}skipMultiLineComment(){const e=[],i=this.index-2,s={start:{line:this.lineNumber,column:this.index-this.lineStart-2},end:{line:0,column:0}};for(;!this.eof();){const n=this.source.charCodeAt(this.index);if(t.isLineTerminator(n))13===n&&10===this.source.charCodeAt(this.index+1)&&++this.index,++this.lineNumber,++this.index,this.lineStart=this.index;else if(42===n){if(47===this.source.charCodeAt(this.index+1)){if(this.index+=2,s){s.end={line:this.lineNumber,column:this.index-this.lineStart};const t={multiLine:!0,start:i+2,end:this.index-2,range:[i,this.index],loc:s};e.push(t)}return e}++this.index}else++this.index}if(s){s.end={line:this.lineNumber,column:this.index-this.lineStart};const t={multiLine:!0,start:i+2,end:this.index,range:[i,this.index],loc:s};e.push(t)}return this.tolerateUnexpectedToken(),e}scanComments(){let e=[];for(;!this.eof();){let i=this.source.charCodeAt(this.index);if(t.isWhiteSpace(i))++this.index;else if(t.isLineTerminator(i))++this.index,13===i&&10===this.source.charCodeAt(this.index)&&++this.index,++this.lineNumber,this.lineStart=this.index;else{if(47!==i)break;if(i=this.source.charCodeAt(this.index+1),47===i){this.index+=2;const t=this.skipSingleLineComment(2);e=[...e,...t]}else{if(42!==i)break;{this.index+=2;const t=this.skipMultiLineComment();e=[...e,...t]}}}}return e}isKeyword(e){switch((e=e.toLowerCase()).length){case 2:return e===o.If||e===o.In;case 3:return e===o.Var||e===o.For;case 4:return e===o.Else;case 5:return e===o.Break||e===o.While;case 6:return e===o.Return||e===o.Import||e===o.Export;case 8:return e===o.Function||e===o.Continue;default:return!1}}codePointAt(e){let t=this.source.charCodeAt(e);if(t>=55296&&t<=56319){const i=this.source.charCodeAt(e+1);if(i>=56320&&i<=57343){t=1024*(t-55296)+i-56320+65536}}return t}scanHexEscape(e){const i="u"===e?4:2;let s=0;for(let n=0;n<i;++n){if(this.eof()||!t.isHexDigit(this.source.charCodeAt(this.index)))return null;s=16*s+d(this.source[this.index++])}return String.fromCharCode(s)}scanUnicodeCodePointEscape(){let e=this.source[this.index],i=0;for("}"===e&&this.throwUnexpectedToken();!this.eof()&&(e=this.source[this.index++],t.isHexDigit(e.charCodeAt(0)));)i=16*i+d(e);return(i>1114111||"}"!==e)&&this.throwUnexpectedToken(),t.fromCodePoint(i)}getIdentifier(){const e=this.index++;for(;!this.eof();){const i=this.source.charCodeAt(this.index);if(92===i)return this.index=e,this.getComplexIdentifier();if(i>=55296&&i<57343)return this.index=e,this.getComplexIdentifier();if(!t.isIdentifierPart(i))break;++this.index}return this.source.slice(e,this.index)}getComplexIdentifier(){let e,i=this.codePointAt(this.index),s=t.fromCodePoint(i);for(this.index+=s.length,92===i&&(117!==this.source.charCodeAt(this.index)&&this.throwUnexpectedToken(),++this.index,"{"===this.source[this.index]?(++this.index,e=this.scanUnicodeCodePointEscape()):(e=this.scanHexEscape("u"),null!==e&&"\\"!==e&&t.isIdentifierStart(e.charCodeAt(0))||this.throwUnexpectedToken()),s=e);!this.eof()&&(i=this.codePointAt(this.index),t.isIdentifierPart(i));)e=t.fromCodePoint(i),s+=e,this.index+=e.length,92===i&&(s=s.substring(0,s.length-1),117!==this.source.charCodeAt(this.index)&&this.throwUnexpectedToken(),++this.index,"{"===this.source[this.index]?(++this.index,e=this.scanUnicodeCodePointEscape()):(e=this.scanHexEscape("u"),null!==e&&"\\"!==e&&t.isIdentifierPart(e.charCodeAt(0))||this.throwUnexpectedToken()),s+=e);return s}octalToDecimal(e){let i="0"!==e,s=l(e);return!this.eof()&&t.isOctalDigit(this.source.charCodeAt(this.index))&&(i=!0,s=8*s+l(this.source[this.index++]),"0123".includes(e)&&!this.eof()&&t.isOctalDigit(this.source.charCodeAt(this.index))&&(s=8*s+l(this.source[this.index++]))),{code:s,octal:i}}scanIdentifier(){let e;const t=this.index,i=92===this.source.charCodeAt(t)?this.getComplexIdentifier():this.getIdentifier();if(e=1===i.length?a.Identifier:this.isKeyword(i)?a.Keyword:i.toLowerCase()===o.Null?a.NullLiteral:i.toLowerCase()===o.True||i.toLowerCase()===o.False?a.BooleanLiteral:a.Identifier,e!==a.Identifier&&t+i.length!==this.index){const e=this.index;this.index=t,this.tolerateUnexpectedToken(c.InvalidEscapedReservedWord),this.index=e}return{type:e,value:i,lineNumber:this.lineNumber,lineStart:this.lineStart,start:t,end:this.index}}scanPunctuator(){const e=this.index;let t=this.source[this.index];switch(t){case"(":case"{":"{"===t&&this.curlyStack.push("{"),++this.index;break;case".":case")":case";":case",":case"[":case"]":case":":case"?":case"~":++this.index;break;case"}":++this.index,this.curlyStack.pop();break;default:for(let e=u.length;e>0;e--)if(t=this.source.substring(this.index,this.index+e),u[e-1].includes(t)){this.index+=e;break}}return this.index===e&&this.throwUnexpectedToken(),{type:a.Punctuator,value:t,lineNumber:this.lineNumber,lineStart:this.lineStart,start:e,end:this.index}}scanHexLiteral(e){let i="";for(;!this.eof()&&t.isHexDigit(this.source.charCodeAt(this.index));)i+=this.source[this.index++];return 0===i.length&&this.throwUnexpectedToken(),t.isIdentifierStart(this.source.charCodeAt(this.index))&&this.throwUnexpectedToken(),{type:a.NumericLiteral,value:parseInt("0x"+i,16),lineNumber:this.lineNumber,lineStart:this.lineStart,start:e,end:this.index}}scanBinaryLiteral(e){let i="";for(;!this.eof();){const e=this.source[this.index];if("0"!==e&&"1"!==e)break;i+=this.source[this.index++]}if(0===i.length&&this.throwUnexpectedToken(),!this.eof()){const e=this.source.charCodeAt(this.index);(t.isIdentifierStart(e)||t.isDecimalDigit(e))&&this.throwUnexpectedToken()}return{type:a.NumericLiteral,value:parseInt(i,2),lineNumber:this.lineNumber,lineStart:this.lineStart,start:e,end:this.index}}scanOctalLiteral(e,i){let s="",n=!1;for(t.isOctalDigit(e.charCodeAt(0))?(n=!0,s="0"+this.source[this.index++]):++this.index;!this.eof()&&t.isOctalDigit(this.source.charCodeAt(this.index));)s+=this.source[this.index++];return n||0!==s.length||this.throwUnexpectedToken(),(t.isIdentifierStart(this.source.charCodeAt(this.index))||t.isDecimalDigit(this.source.charCodeAt(this.index)))&&this.throwUnexpectedToken(),{type:a.NumericLiteral,value:parseInt(s,8),lineNumber:this.lineNumber,lineStart:this.lineStart,start:i,end:this.index}}scanNumericLiteral(){const i=this.index;let s=this.source[i];e(t.isDecimalDigit(s.charCodeAt(0))||"."===s,"Numeric literal must start with a decimal digit or a decimal point");let n="";if("."!==s){if(n=this.source[this.index++],s=this.source[this.index],"0"===n){if("x"===s||"X"===s)return++this.index,this.scanHexLiteral(i);if("b"===s||"B"===s)return++this.index,this.scanBinaryLiteral(i);if("o"===s||"O"===s)return this.scanOctalLiteral(s,i)}for(;t.isDecimalDigit(this.source.charCodeAt(this.index));)n+=this.source[this.index++];s=this.source[this.index]}if("."===s){for(n+=this.source[this.index++];t.isDecimalDigit(this.source.charCodeAt(this.index));)n+=this.source[this.index++];s=this.source[this.index]}if("e"===s||"E"===s)if(n+=this.source[this.index++],s=this.source[this.index],"+"!==s&&"-"!==s||(n+=this.source[this.index++]),t.isDecimalDigit(this.source.charCodeAt(this.index)))for(;t.isDecimalDigit(this.source.charCodeAt(this.index));)n+=this.source[this.index++];else this.throwUnexpectedToken();return t.isIdentifierStart(this.source.charCodeAt(this.index))&&this.throwUnexpectedToken(),{type:a.NumericLiteral,value:parseFloat(n),lineNumber:this.lineNumber,lineStart:this.lineStart,start:i,end:this.index}}scanStringLiteral(){const i=this.index;let s=this.source[i];e("'"===s||'"'===s,"String literal must starts with a quote"),++this.index;let n=!1,r="";for(;!this.eof();){let e=this.source[this.index++];if(e===s){s="";break}if("\\"===e)if(e=this.source[this.index++],e&&t.isLineTerminator(e.charCodeAt(0)))++this.lineNumber,"\r"===e&&"\n"===this.source[this.index]&&++this.index,this.lineStart=this.index;else switch(e){case"u":if("{"===this.source[this.index])++this.index,r+=this.scanUnicodeCodePointEscape();else{const t=this.scanHexEscape(e);null===t&&this.throwUnexpectedToken(),r+=t}break;case"x":{const t=this.scanHexEscape(e);null===t&&this.throwUnexpectedToken(c.InvalidHexEscapeSequence),r+=t;break}case"n":r+="\n";break;case"r":r+="\r";break;case"t":r+="\t";break;case"b":r+="\b";break;case"f":r+="\f";break;case"v":r+="\v";break;case"8":case"9":r+=e,this.tolerateUnexpectedToken();break;default:if(e&&t.isOctalDigit(e.charCodeAt(0))){const t=this.octalToDecimal(e);n=t.octal||n,r+=String.fromCharCode(t.code)}else r+=e}else{if(t.isLineTerminator(e.charCodeAt(0)))break;r+=e}}return""!==s&&(this.index=i,this.throwUnexpectedToken()),{type:a.StringLiteral,value:r,lineNumber:this.lineNumber,lineStart:this.lineStart,start:i,end:this.index}}scanTemplate(){let e="",i=!1;const s=this.index,n="`"===this.source[s];let r=!1,h=2;for(++this.index;!this.eof();){let s=this.source[this.index++];if("`"===s){h=1,r=!0,i=!0;break}if("$"!==s)if("\\"!==s)t.isLineTerminator(s.charCodeAt(0))?(++this.lineNumber,"\r"===s&&"\n"===this.source[this.index]&&++this.index,this.lineStart=this.index,e+="\n"):e+=s;else if(s=this.source[this.index++],t.isLineTerminator(s.charCodeAt(0)))++this.lineNumber,"\r"===s&&"\n"===this.source[this.index]&&++this.index,this.lineStart=this.index;else switch(s){case"n":e+="\n";break;case"r":e+="\r";break;case"t":e+="\t";break;case"u":if("{"===this.source[this.index])++this.index,e+=this.scanUnicodeCodePointEscape();else{const t=this.index,i=this.scanHexEscape(s);null!==i?e+=i:(this.index=t,e+=s)}break;case"x":{const t=this.scanHexEscape(s);null===t&&this.throwUnexpectedToken(c.InvalidHexEscapeSequence),e+=t;break}case"b":e+="\b";break;case"f":e+="\f";break;case"v":e+="\v";break;default:"0"===s?(t.isDecimalDigit(this.source.charCodeAt(this.index))&&this.throwUnexpectedToken(c.TemplateOctalLiteral),e+="\0"):t.isOctalDigit(s.charCodeAt(0))?this.throwUnexpectedToken(c.TemplateOctalLiteral):e+=s}else{if("{"===this.source[this.index]){this.curlyStack.push("${"),++this.index,i=!0;break}e+=s}}return i||this.throwUnexpectedToken(),n||this.curlyStack.pop(),{type:a.Template,value:this.source.slice(s+1,this.index-h),cooked:e,head:n,tail:r,lineNumber:this.lineNumber,lineStart:this.lineStart,start:s,end:this.index}}lex(){if(this.eof())return{type:a.EOF,value:"",lineNumber:this.lineNumber,lineStart:this.lineStart,start:this.index,end:this.index};const e=this.source.charCodeAt(this.index);return t.isIdentifierStart(e)?this.scanIdentifier():40===e||41===e||59===e?this.scanPunctuator():39===e||34===e?this.scanStringLiteral():46===e?t.isDecimalDigit(this.source.charCodeAt(this.index+1))?this.scanNumericLiteral():this.scanPunctuator():t.isDecimalDigit(e)?this.scanNumericLiteral():96===e||125===e&&"${"===this.curlyStack[this.curlyStack.length-1]?this.scanTemplate():e>=55296&&e<57343&&t.isIdentifierStart(this.codePointAt(this.index))?this.scanIdentifier():this.scanPunctuator()}}export{x as Scanner};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.26/esri/copyright.txt for details.
4
4
  */
5
- var e;!function(e){e.AssignmentExpression="AssignmentExpression",e.ArrayExpression="ArrayExpression",e.BlockComment="BlockComment",e.BlockStatement="BlockStatement",e.BinaryExpression="BinaryExpression",e.BreakStatement="BreakStatement",e.CallExpression="CallExpression",e.ContinueStatement="ContinueStatement",e.EmptyStatement="EmptyStatement",e.ExpressionStatement="ExpressionStatement",e.ExportNamedDeclaration="ExportNamedDeclaration",e.ExportSpecifier="ExportSpecifier",e.ForStatement="ForStatement",e.ForInStatement="ForInStatement",e.FunctionDeclaration="FunctionDeclaration",e.Identifier="Identifier",e.IfStatement="IfStatement",e.ImportDeclaration="ImportDeclaration",e.ImportDefaultSpecifier="ImportDefaultSpecifier",e.LineComment="LineComment",e.Literal="Literal",e.LogicalExpression="LogicalExpression",e.MemberExpression="MemberExpression",e.ObjectExpression="ObjectExpression",e.Program="Program",e.Property="Property",e.ReturnStatement="ReturnStatement",e.TemplateElement="TemplateElement",e.TemplateLiteral="TemplateLiteral",e.UnaryExpression="UnaryExpression",e.UpdateExpression="UpdateExpression",e.VariableDeclaration="VariableDeclaration",e.VariableDeclarator="VariableDeclarator",e.WhileStatement="WhileStatement"}(e||(e={}));const t=["++","--"],n=["-","+","!","~"],i=["=","/=","*=","%=","+=","-="],r=["||","&&"],a=["|","&",">>","<<",">>>","^","==","!=","<","<=",">",">=","+","-","*","/","%"],o={"||":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":10,"/":10,"%":10};var c;!function(e){e[e.Unknown=0]="Unknown",e[e.BooleanLiteral=1]="BooleanLiteral",e[e.EOF=2]="EOF",e[e.Identifier=3]="Identifier",e[e.Keyword=4]="Keyword",e[e.NullLiteral=5]="NullLiteral",e[e.NumericLiteral=6]="NumericLiteral",e[e.Punctuator=7]="Punctuator",e[e.StringLiteral=8]="StringLiteral",e[e.Template=10]="Template"}(c||(c={}));const s=["Unknown","Boolean","<end>","Identifier","Keyword","Null","Numeric","Punctuator","String","RegularExpression","Template"];var l;!function(e){e.InvalidModuleUri="InvalidModuleUri",e.ForInOfLoopInitializer="ForInOfLoopInitializer",e.IdentiferExpected="IdentiferExpected",e.InvalidEscapedReservedWord="InvalidEscapedReservedWord",e.InvalidExpression="InvalidExpression",e.InvalidFunctionIdentifier="InvalidFunctionIdentifier",e.InvalidHexEscapeSequence="InvalidHexEscapeSequence",e.InvalidLeftHandSideInAssignment="InvalidLeftHandSideInAssignment",e.InvalidLeftHandSideInForIn="InvalidLeftHandSideInForIn",e.InvalidTemplateHead="InvalidTemplateHead",e.InvalidVariableAssignment="InvalidVariableAssignment",e.KeyMustBeString="KeyMustBeString",e.NoFunctionInsideBlock="NoFunctionInsideBlock",e.NoFunctionInsideFunction="NoFunctionInsideFunction",e.ModuleExportRootOnly="ModuleExportRootOnly",e.ModuleImportRootOnly="ModuleImportRootOnly",e.PunctuatorExpected="PunctuatorExpected",e.TemplateOctalLiteral="TemplateOctalLiteral",e.UnexpectedEndOfScript="UnexpectedEndOfScript",e.UnexpectedIdentifier="UnexpectedIdentifier",e.UnexpectedNumber="UnexpectedNumber",e.UnexpectedString="UnexpectedString",e.UnexpectedTemplate="UnexpectedTemplate",e.UnexpectedToken="UnexpectedToken"}(l||(l={}));const p={[l.InvalidModuleUri]:"Module uri must be a string literal",[l.ForInOfLoopInitializer]:"for-in loop variable declaration may not have an initializer",[l.IdentiferExpected]:"Identifier expected",[l.InvalidEscapedReservedWord]:"Keyword cannot contain escaped characters",[l.InvalidExpression]:"Invalid expression",[l.InvalidFunctionIdentifier]:"Invalid function identifier",[l.InvalidHexEscapeSequence]:"Invalid hexadecimal escape sequence",[l.InvalidLeftHandSideInAssignment]:"Invalid left-hand side in assignment",[l.InvalidLeftHandSideInForIn]:"Invalid left-hand side in for-in",[l.InvalidTemplateHead]:"Invalid template structure",[l.InvalidVariableAssignment]:"Invalid variable assignment",[l.KeyMustBeString]:"Object keys must be a string",[l.NoFunctionInsideBlock]:"Functions cannot be declared inside of code blocks",[l.NoFunctionInsideFunction]:"Functions cannot be declared inside another function",[l.ModuleExportRootOnly]:"Module exports cannot be declared inside of code blocks",[l.ModuleImportRootOnly]:"Module import cannot be declared inside of code blocks",[l.PunctuatorExpected]:"'${value}' expected",[l.TemplateOctalLiteral]:"Octal literals are not allowed in template strings.",[l.UnexpectedEndOfScript]:"Unexpected end of script",[l.UnexpectedIdentifier]:"Unexpected identifier",[l.UnexpectedNumber]:"Unexpected number",[l.UnexpectedString]:"Unexpected string",[l.UnexpectedTemplate]:"Unexpected quasi '${value}'",[l.UnexpectedToken]:"Unexpected token"};class d extends Error{constructor({code:e,index:t,line:n,column:i,len:r=0,description:a,data:o}){super(`${a??e}`),this.declaredRootClass="esri.arcade.lib.parsingerror",this.name="ParsingError",this.code=e,this.index=t,this.line=n,this.column=i,this.len=r,this.data=o,this.description=a,this.range={start:{line:n,column:i-1},end:{line:n,column:i+r}},Error.captureStackTrace?.(this,d)}}function u(t){return t?.type===e.Program}function m(t){switch(t?.type){case e.BlockStatement:case e.BreakStatement:case e.ContinueStatement:case e.EmptyStatement:case e.ExpressionStatement:case e.ForInStatement:case e.ForStatement:case e.FunctionDeclaration:case e.IfStatement:case e.ReturnStatement:case e.VariableDeclaration:return!0;default:return!1}}function x(t){return t?.type===e.BlockStatement}function I(t){return t?.type===e.BlockComment}function f(t){return t?.type===e.BreakStatement}function E(t){return t?.type===e.ContinueStatement}function y(t){return t?.type===e.EmptyStatement}function S(t){return t?.type===e.ExpressionStatement}function v(t){return t?.type===e.ForInStatement}function U(t){return t?.type===e.ForStatement}function g(t){return t?.type===e.FunctionDeclaration}function b(t){return t?.type===e.IfStatement}function F(t){return t?.type===e.ReturnStatement}function L(t){return t?.type===e.VariableDeclaration}function k(t){switch(t?.type){case e.ArrayExpression:case e.AssignmentExpression:case e.BinaryExpression:case e.CallExpression:case e.Identifier:case e.Literal:case e.LogicalExpression:case e.MemberExpression:case e.ObjectExpression:case e.TemplateLiteral:case e.UpdateExpression:case e.UnaryExpression:return!0;default:return!1}}function B(t){return t?.type===e.ArrayExpression}function O(t){return t?.type===e.AssignmentExpression}function T(t){return t?.type===e.BinaryExpression}function h(t){return t?.type===e.CallExpression}function M(t){return t?.type===e.Identifier}function D(t){return t?.type===e.Literal}function N(t){return t?.type===e.LogicalExpression}function R(t){return t?.type===e.ObjectExpression}function A(t){return t?.type===e.TemplateLiteral}function C(t){return t?.type===e.MemberExpression}function P(t){return t?.type===e.UnaryExpression}function H(t){return t?.type===e.UpdateExpression}function w(t){return t?.type===e.VariableDeclarator}function V(t){return t?.type===e.Property}function K(t){return t?.type===e.TemplateElement}export{i as AssignmentOperators,a as BinaryOperators,r as LogicalOperators,o as OperatorPrecedence,d as ParsingError,l as ParsingErrorCodes,p as ParsingErrorMessages,e as Syntax,s as TokenNames,c as TokenType,n as UnaryOperators,t as UpdateOperators,B as isArrayExpression,O as isAssignmentExpression,T as isBinaryExpression,I as isBlockComment,x as isBlockStatement,f as isBreakStatement,h as isCallExpression,E as isContinueStatement,y as isEmptyStatement,k as isExpression,S as isExpressionStatement,v as isForInStatement,U as isForStatement,g as isFunctionDeclaration,M as isIdentifier,b as isIfStatement,D as isLiteral,N as isLogicalExpression,C as isMemberExpression,R as isObjectExpression,u as isProgram,V as isProperty,F as isReturnStatement,m as isStatement,K as isTemplateElement,A as isTemplateLiteral,P as isUnaryExpression,H as isUpdateExpression,L as isVariableDeclaration,w as isVariableDeclarator};
5
+ var e,t;!function(e){e.Break="break",e.Continue="continue",e.Else="else",e.False="false",e.For="for",e.From="from",e.Function="function",e.If="if",e.Import="import",e.Export="export",e.In="in",e.Null="null",e.Return="return",e.True="true",e.Var="var",e.While="while"}(e||(e={})),function(e){e.AssignmentExpression="AssignmentExpression",e.ArrayExpression="ArrayExpression",e.BlockComment="BlockComment",e.BlockStatement="BlockStatement",e.BinaryExpression="BinaryExpression",e.BreakStatement="BreakStatement",e.CallExpression="CallExpression",e.ContinueStatement="ContinueStatement",e.EmptyStatement="EmptyStatement",e.ExpressionStatement="ExpressionStatement",e.ExportNamedDeclaration="ExportNamedDeclaration",e.ExportSpecifier="ExportSpecifier",e.ForStatement="ForStatement",e.ForInStatement="ForInStatement",e.FunctionDeclaration="FunctionDeclaration",e.Identifier="Identifier",e.IfStatement="IfStatement",e.ImportDeclaration="ImportDeclaration",e.ImportDefaultSpecifier="ImportDefaultSpecifier",e.LineComment="LineComment",e.Literal="Literal",e.LogicalExpression="LogicalExpression",e.MemberExpression="MemberExpression",e.ObjectExpression="ObjectExpression",e.Program="Program",e.Property="Property",e.ReturnStatement="ReturnStatement",e.TemplateElement="TemplateElement",e.TemplateLiteral="TemplateLiteral",e.UnaryExpression="UnaryExpression",e.UpdateExpression="UpdateExpression",e.VariableDeclaration="VariableDeclaration",e.VariableDeclarator="VariableDeclarator",e.WhileStatement="WhileStatement"}(t||(t={}));const n=["++","--"],r=["-","+","!","~"],i=["=","/=","*=","%=","+=","-="],a=["||","&&"],o=["|","&",">>","<<",">>>","^","==","!=","<","<=",">",">=","+","-","*","/","%"],c={"||":1,"&&":2,"|":3,"^":4,"&":5,"==":6,"!=":6,"<":7,">":7,"<=":7,">=":7,"<<":8,">>":8,">>>":8,"+":9,"-":9,"*":10,"/":10,"%":10};var l;!function(e){e[e.Unknown=0]="Unknown",e[e.BooleanLiteral=1]="BooleanLiteral",e[e.EOF=2]="EOF",e[e.Identifier=3]="Identifier",e[e.Keyword=4]="Keyword",e[e.NullLiteral=5]="NullLiteral",e[e.NumericLiteral=6]="NumericLiteral",e[e.Punctuator=7]="Punctuator",e[e.StringLiteral=8]="StringLiteral",e[e.Template=10]="Template"}(l||(l={}));const s=["Unknown","Boolean","<end>","Identifier","Keyword","Null","Numeric","Punctuator","String","RegularExpression","Template"];var p;!function(e){e.InvalidModuleUri="InvalidModuleUri",e.ForInOfLoopInitializer="ForInOfLoopInitializer",e.IdentiferExpected="IdentiferExpected",e.InvalidEscapedReservedWord="InvalidEscapedReservedWord",e.InvalidExpression="InvalidExpression",e.InvalidFunctionIdentifier="InvalidFunctionIdentifier",e.InvalidHexEscapeSequence="InvalidHexEscapeSequence",e.InvalidLeftHandSideInAssignment="InvalidLeftHandSideInAssignment",e.InvalidLeftHandSideInForIn="InvalidLeftHandSideInForIn",e.InvalidTemplateHead="InvalidTemplateHead",e.InvalidVariableAssignment="InvalidVariableAssignment",e.KeyMustBeString="KeyMustBeString",e.NoFunctionInsideBlock="NoFunctionInsideBlock",e.NoFunctionInsideFunction="NoFunctionInsideFunction",e.ModuleExportRootOnly="ModuleExportRootOnly",e.ModuleImportRootOnly="ModuleImportRootOnly",e.PunctuatorExpected="PunctuatorExpected",e.TemplateOctalLiteral="TemplateOctalLiteral",e.UnexpectedBoolean="UnexpectedBoolean",e.UnexpectedEndOfScript="UnexpectedEndOfScript",e.UnexpectedIdentifier="UnexpectedIdentifier",e.UnexpectedKeyword="UnexpectedKeyword",e.UnexpectedNull="UnexpectedNull",e.UnexpectedNumber="UnexpectedNumber",e.UnexpectedPunctuator="UnexpectedPunctuator",e.UnexpectedString="UnexpectedString",e.UnexpectedTemplate="UnexpectedTemplate",e.UnexpectedToken="UnexpectedToken"}(p||(p={}));const d={[p.InvalidModuleUri]:"Module uri must be a text literal.",[p.ForInOfLoopInitializer]:"for-in loop variable declaration may not have an initializer.",[p.IdentiferExpected]:"'${value}' is an invalid identifier.",[p.InvalidEscapedReservedWord]:"Keyword cannot contain escaped characters.",[p.InvalidExpression]:"Invalid expression.",[p.InvalidFunctionIdentifier]:"'${value}' is an invalid function identifier.",[p.InvalidHexEscapeSequence]:"Invalid hexadecimal escape sequence.",[p.InvalidLeftHandSideInAssignment]:"Invalid left-hand side in assignment.",[p.InvalidLeftHandSideInForIn]:"Invalid left-hand side in for-in.",[p.InvalidTemplateHead]:"Invalid template structure.",[p.InvalidVariableAssignment]:"Invalid variable assignment.",[p.KeyMustBeString]:"Object property keys must be a word starting with a letter.",[p.NoFunctionInsideBlock]:"Functions cannot be declared inside of code blocks.",[p.NoFunctionInsideFunction]:"Functions cannot be declared inside another function.",[p.ModuleExportRootOnly]:"Module exports cannot be declared inside of code blocks.",[p.ModuleImportRootOnly]:"Module import cannot be declared inside of code blocks.",[p.PunctuatorExpected]:"'${value}' expected.",[p.TemplateOctalLiteral]:"Octal literals are not allowed in template literals.",[p.UnexpectedBoolean]:"Unexpected boolean literal.",[p.UnexpectedEndOfScript]:"Unexpected end of Arcade expression.",[p.UnexpectedIdentifier]:"Unexpected identifier.",[p.UnexpectedKeyword]:"Unexpected keyword.",[p.UnexpectedNull]:"Unexpected null literal.",[p.UnexpectedNumber]:"Unexpected number.",[p.UnexpectedPunctuator]:"Unexpected ponctuator.",[p.UnexpectedString]:"Unexpected text literal.",[p.UnexpectedTemplate]:"Unexpected quasi '${value}'.",[p.UnexpectedToken]:"Unexpected token '${value}'."};class u extends Error{constructor({code:e,index:t,line:n,column:r,len:i=0,description:a,data:o}){super(`${a??e}`),this.declaredRootClass="esri.arcade.lib.parsingerror",this.name="ParsingError",this.code=e,this.index=t,this.line=n,this.column=r,this.len=i,this.data=o,this.description=a,this.range={start:{line:n,column:r-1},end:{line:n,column:r+i}},Error.captureStackTrace?.(this,u)}}function m(e){return e?.type===t.Program}function x(e){switch(e?.type){case t.BlockStatement:case t.BreakStatement:case t.ContinueStatement:case t.EmptyStatement:case t.ExpressionStatement:case t.ForInStatement:case t.ForStatement:case t.FunctionDeclaration:case t.IfStatement:case t.ReturnStatement:case t.VariableDeclaration:return!0;default:return!1}}function f(e){return e?.type===t.BlockStatement}function I(e){return e?.type===t.BlockComment}function E(e){return e?.type===t.BreakStatement}function y(e){return e?.type===t.ContinueStatement}function S(e){return e?.type===t.EmptyStatement}function U(e){return e?.type===t.ExpressionStatement}function v(e){return e?.type===t.ForInStatement}function F(e){return e?.type===t.ForStatement}function b(e){return e?.type===t.FunctionDeclaration}function L(e){return e?.type===t.IfStatement}function g(e){return e?.type===t.ReturnStatement}function k(e){return e?.type===t.VariableDeclaration}function B(e){switch(e?.type){case t.ArrayExpression:case t.AssignmentExpression:case t.BinaryExpression:case t.CallExpression:case t.Identifier:case t.Literal:case t.LogicalExpression:case t.MemberExpression:case t.ObjectExpression:case t.TemplateLiteral:case t.UpdateExpression:case t.UnaryExpression:return!0;default:return!1}}function h(e){return e?.type===t.ArrayExpression}function T(e){return e?.type===t.AssignmentExpression}function O(e){return e?.type===t.BinaryExpression}function N(e){return e?.type===t.CallExpression}function M(e){return e?.type===t.Identifier}function w(e){return e?.type===t.Literal}function D(e){return e?.type===t.LogicalExpression}function P(e){return e?.type===t.ObjectExpression}function R(e){return e?.type===t.TemplateLiteral}function A(e){return e?.type===t.MemberExpression}function C(e){return e?.type===t.UnaryExpression}function H(e){return e?.type===t.UpdateExpression}function V(e){return e?.type===t.VariableDeclarator}function K(e){return e?.type===t.Property}function W(e){return e?.type===t.TemplateElement}export{i as AssignmentOperators,o as BinaryOperators,e as Keywords,a as LogicalOperators,c as OperatorPrecedence,u as ParsingError,p as ParsingErrorCodes,d as ParsingErrorMessages,t as Syntax,s as TokenNames,l as TokenType,r as UnaryOperators,n as UpdateOperators,h as isArrayExpression,T as isAssignmentExpression,O as isBinaryExpression,I as isBlockComment,f as isBlockStatement,E as isBreakStatement,N as isCallExpression,y as isContinueStatement,S as isEmptyStatement,B as isExpression,U as isExpressionStatement,v as isForInStatement,F as isForStatement,b as isFunctionDeclaration,M as isIdentifier,L as isIfStatement,w as isLiteral,D as isLogicalExpression,A as isMemberExpression,P as isObjectExpression,m as isProgram,K as isProperty,g as isReturnStatement,x as isStatement,W as isTemplateElement,R as isTemplateLiteral,C as isUnaryExpression,H as isUpdateExpression,k as isVariableDeclaration,V as isVariableDeclarator};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.26/esri/copyright.txt for details.
4
4
  */
5
- import{parse as e}from"../lib/arcade-parser.js";import{DiagnosticCodes as i,DiagnosticMessages as t}from"./diagnosticMessages.js";import{DiagnosticSeverity as n}from"./types.js";import{ParsingErrorMessages as s,Syntax as r,isVariableDeclaration as o,isIdentifier as a,isEmptyStatement as d,isBlockStatement as c}from"../lib/types.js";function l(e,i){return i?e.replace(/\${(.*?)}/g,((e,t)=>i[t]?.toString()??"")):e}function p(e){return!!e&&"dictionary"!==e.type}class f{constructor(e,i=[]){this._apiDefinitions=e,this._profileVariables=i,this._isInBlock=!1,this._recordIdentifierAssignment=!1,this._scriptScopeIdentifiers=new Map,this._diagnostics=new Array,this._undeclaredIdentifiersInFunctions=new Map}validateScript(t){if(!t)return{diagnostics:[],program:null};this._isInBlock=!1,this._recordIdentifierAssignment=!1,this._diagnostics=[],this._scriptScopeIdentifiers.clear(),this._undeclaredIdentifiersInFunctions.clear(),this._functionScopeIdentifiers=void 0;let n=null;try{n=e(t,{tolerant:!0}),this.handleErrors(n.errors),n.body.forEach((e=>this.validateStatement(e))),this.diagnoseIdentifiers(),this._undeclaredIdentifiersInFunctions.size>0&&this._undeclaredIdentifiersInFunctions.forEach((e=>{for(const t of e)this.logDiagnostic(t.node.loc,{code:i.NotDefined,data:{identifier:t.node.name}})}))}catch(s){this.handleException(s)}return{diagnostics:this._diagnostics,program:n}}recordIdentifierAssignment(e,i,t=!0){const n=this._recordIdentifierAssignment;this._recordIdentifierAssignment=t,e.call(this,i),this._recordIdentifierAssignment=n}inBlock(e,i){const t=this._isInBlock;this._isInBlock=!0,e.call(this,i),this._isInBlock=t}get _isInFunctionScope(){return!!this._functionScopeIdentifiers}inFunctionScope(e){this._functionScopeIdentifiers=new Map,e.call(this),this.diagnoseIdentifiers(),this._functionScopeIdentifiers=void 0}logDiagnostic(e,i){const r={severity:n.Error,...i,message:l(t[i.code]??s[i.code],i.data),range:{start:{line:e.start.line-1,character:e.start.column},end:{line:e.end.line-1,character:e.end.column}}};this._diagnostics.push(r)}handleErrors(e){(e??[]).forEach(this.handleException,this)}handleException(e){if(h(e)){const{range:i,code:t,data:n}=e;this.logDiagnostic(i,{code:t,data:n})}else this.logDiagnostic({start:{line:1,column:0},end:{line:1,column:0}},{code:i.ExecutionError,data:{stack:e.stack}})}getIdentifierInfo(e){return this._functionScopeIdentifiers?.get(e)??this._scriptScopeIdentifiers.get(e)}setIdentiferInfo(e,i){this._functionScopeIdentifiers?this._functionScopeIdentifiers.set(e,i):((this._functionScopeIdentifiers??this._scriptScopeIdentifiers).set(e,i),this._functionScopeIdentifiers||this._undeclaredIdentifiersInFunctions.has(e)&&(this._undeclaredIdentifiersInFunctions.delete(e),i.used=!0))}isProfileVariable(e){return(this._profileVariables??[]).some((i=>i.name.toLowerCase()===e))}isApiItem(e){const i=!!this._apiDefinitions?.constantDefinitions?.get(e),t=!!this._apiDefinitions?.functionDefinitions?.get(e);return i||t}validateStatement(e){if(e)switch(e.type){case r.BlockStatement:return void e.body.forEach((e=>this.validateStatement(e)));case r.VariableDeclaration:return void e.declarations.forEach((e=>this.validateVariableDeclarator(e)));case r.FunctionDeclaration:return void this.validateFunctionDeclaration(e);case r.ExportNamedDeclaration:return void this.validateExportDeclaration(e);case r.ImportDeclaration:return void this.validateImportDeclaration(e);case r.WhileStatement:return void this.validateWhileStatement(e);case r.ForStatement:return void this.validateForStatement(e);case r.ForInStatement:return void this.validateForInStatement(e);case r.IfStatement:return void this.validateIfStatement(e);case r.ReturnStatement:return void this.validateExpression(e.argument);case r.ExpressionStatement:return void this.validateExpression(e.expression);case r.BreakStatement:case r.ContinueStatement:case r.EmptyStatement:return}}validateVariableDeclarator(e){this.validateExpression(e.init),this.recordVariableIdentifier(e.id,{initialized:!!e.init})}validateFunctionDeclaration(e){this.recordFunctionIdentifier(e),this.inFunctionScope((()=>{e.params.forEach((e=>this.recordParamAsIdentifier(e))),u(e.body)&&this.logDiagnostic(e.body.loc,{code:i.UnexpectedEmptyFunction,data:{identifier:e.id.name},severity:n.Warning}),this.validateStatement(e.body)}))}validateExportDeclaration(e){this.validateStatement(e.declaration)}validateImportDeclaration(e){this.recordImportIdentifier(e)}validateForStatement(e){o(e.init)?this.inBlock(this.validateStatement,e.init):this.validateExpression(e.init),this.validateExpression(e.update),this.validateExpression(e.test),u(e.body)&&this.logDiagnostic(e.body.loc,{code:i.EmptyBlockStatement,severity:n.Warning}),this.inBlock(this.validateStatement,e.body)}validateWhileStatement(e){this.validateExpression(e.test),u(e.body)&&this.logDiagnostic(e.body.loc,{code:i.EmptyBlockStatement,severity:n.Warning}),this.inBlock(this.validateStatement,e.body)}validateForInStatement(e){a(e.left)?this.validateExpression(e.left):this.recordVariableIdentifier(e.left.declarations[0].id,{initialized:!0,inBlock:!0}),this.validateExpression(e.right),u(e.body)&&this.logDiagnostic(e.body.loc,{code:i.EmptyBlockStatement,severity:n.Warning}),this.validateStatement(e.body)}validateIfStatement(e){this.validateExpression(e.test),u(e.consequent)&&this.logDiagnostic(e.consequent.loc,{code:i.EmptyBlockStatement,severity:n.Warning}),e.alternate&&u(e.alternate)&&this.logDiagnostic(e.alternate.loc,{code:i.EmptyBlockStatement,severity:n.Warning}),this.inBlock(this.validateStatement,e.consequent),this.inBlock(this.validateStatement,e.alternate)}validateExpression(e){if(e)switch(e.type){case r.AssignmentExpression:return void this.validateAssignmentExpression(e);case r.CallExpression:return void this.validateCallExpression(e);case r.Identifier:return void this.validateIdentifier(e);case r.Literal:return;case r.ArrayExpression:return void e.elements.forEach((e=>this.validateExpression(e)));case r.ObjectExpression:return void this.validateObjectExpression(e);case r.UnaryExpression:return void this.validateUnaryExpression(e);case r.UpdateExpression:return void this.validateUpdateExpression(e);case r.BinaryExpression:case r.LogicalExpression:return void this.validateBinaryAndLogicalExpression(e);case r.MemberExpression:return void this.validateMemberExpression(e);case r.TemplateLiteral:return void e.expressions.forEach((e=>this.validateExpression(e)));default:return}}validateAssignmentExpression(e){this.recordIdentifierAssignment(this.validateExpression,e.left),this.validateExpression(e.right)}validateCallExpression(e){if(this.validateExpression(e.callee),a(e.callee)){const i=e.callee.name.toLowerCase(),t=this.getIdentifierInfo(i),n=this._apiDefinitions?.functionDefinitions?.get(i);if(!t&&n){const i=m(n,e.arguments.length);i&&this.logDiagnostic(e.loc,i)}}e.arguments.forEach((e=>this.validateExpression(e)))}validateIdentifier(e){const t=e.name.toLowerCase(),n=this.getIdentifierInfo(t);if(n)return this._recordIdentifierAssignment?void(n.initialized=!0):void(n.used=!0);if(!this.isProfileVariable(t)&&!this.isApiItem(t)){if(this._isInFunctionScope){let i=this._undeclaredIdentifiersInFunctions.get(t);return i||(i=[],this._undeclaredIdentifiersInFunctions.set(t,i)),void i.push({node:e,identifier:t})}this.logDiagnostic(e.loc,{code:i.NotDefined,data:{identifier:e.name}})}}logProfileOrApiConflict(e){const t=e.name.toLowerCase(),s=this.isProfileVariable(t),r=this.isApiItem(t);(s||r)&&this.logDiagnostic(e.loc,{code:s?i.ProfileVariablesConflict:i.ApiConflict,severity:n.Warning,data:{identifier:e.name}})}validateObjectExpression(e){e.properties.forEach((e=>{this.validateExpression(e.value)}))}validateUnaryExpression(e){this.validateExpression(e.argument)}validateUpdateExpression(e){this.validateExpression(e.argument)}validateBinaryAndLogicalExpression(e){this.validateExpression(e.left),this.validateExpression(e.right)}validateMemberExpression(e){const i=this.flattenMemberExpressionAndValidate(e),t=i[0].object;this.recordIdentifierAssignment(this.validateExpression,t,!1),a(t)&&(this.getIdentifierInfo(t.name.toLowerCase())||this.validateMemberExpressionWithProfile(i)||this.validateConstantMemberExpression(i))}flattenMemberExpressionAndValidate(e){return e.type===r.MemberExpression?(a(e.property)&&!e.computed||this.validateExpression(e.property),[...this.flattenMemberExpressionAndValidate(e.object),e]):[]}extractAndValidatePropertyName(e){switch(e.type){case"Identifier":return e.name.toLowerCase();case"Literal":return"string"!=typeof e.value?(this.logDiagnostic(e.loc,{code:i.UnexpectedPropertyIdentifier}),null):e.value.toLowerCase();default:return this.logDiagnostic(e.loc,{code:i.UnexpectedPropertyIdentifier}),null}}validateConstantMemberExpression(e){const t=e[0];if(!a(t.object))return!1;const n=t.object.name.toLowerCase(),s=this._apiDefinitions?.constantDefinitions?.get(n);if(!s)return!1;if("namespace"!==s.type)return this.logDiagnostic(t.property.loc,{code:i.NotADictionary,data:{identifier:n}}),!0;const r=this.extractAndValidatePropertyName(t.property);if(!r)return!0;if(!s.members.some((e=>e.key===r))){const e=s.members.reduce(((e,i)=>`${e}${e?" | ":""}${i.completion.label.split(".").pop()}`),"");this.logDiagnostic(t.property.loc,{code:i.InvalidConstantIdentifier,data:{list:e}})}return e.length>1&&this.logDiagnostic(e[1].property.loc,{code:i.UnexpectedPropertyIdentifier}),!0}validateMemberExpressionWithProfile(e){const t=e[0];if(t.object.type!==r.Identifier)return!1;const s=t.object.name.toLowerCase(),o=this._profileVariables?.find((e=>e.key===s));if(!o)return!1;if(p(o))return this.logDiagnostic(t.object.loc,{code:i.NotADictionary,data:{identifier:o.name}}),!0;if(this._recordIdentifierAssignment)return this.logDiagnostic(t.loc,{code:i.ProfileVariablesAreImmutable}),!0;let a=o;for(let r=0;r<e.length;r++){if(e[r].computed)return!0;if(p(a))return this.logDiagnostic(e[r-1]?.property.loc??e[r].object.loc,{code:i.NotADictionary,data:{identifier:a.name}}),!0;const t=this.extractAndValidatePropertyName(e[r].property);if(!t)return!0;if(0===a.properties.length)return this.logDiagnostic(e[r].property.loc,{code:i.UnknownPropertyIdentifier,data:{identifier:t},severity:n.Warning}),!0;const s=a.properties.find((e=>e.name.toLowerCase()===t));if(!s){const t=a.properties.reduce(((e,i)=>`${e}${e?" | ":""}${i.name.split(".").pop()}`),"");return this.logDiagnostic(e[r].property.loc,{code:i.InvalidPropertyIdentifier,data:{list:t}}),!0}a=s}return!0}recordVariableIdentifier(e,t){this.logProfileOrApiConflict(e);const s=e.name.toLowerCase();let r=this.getIdentifierInfo(s);const o=r&&this._isInFunctionScope&&"function"===r.scope,a=r&&!this._isInFunctionScope&&"script"===r.scope;(o||a)&&this.logDiagnostic(e.loc,{code:i.AlreadyDefined,data:{identifier:e.name},severity:n.Warning});const d=t.inBlock??this._isInBlock,{initialized:c}=t;if(!r||this._isInFunctionScope&&"function"!==r.scope){r={node:e,used:!1,initialized:c,scope:this._isInFunctionScope?"function":d?"block":"script"}}else r.node=e,r.used=!1,r.initialized=c;return"block"!==r.scope||d||(r.scope="script",this.logDiagnostic(e.loc,{code:i.AlreadyDefined,data:{identifier:e.name},severity:n.Warning})),this.setIdentiferInfo(s,r),!1}recordImportIdentifier(e){const t=e.specifiers[0].local;this.logProfileOrApiConflict(t);const s=t.name.toLowerCase();let r=this.getIdentifierInfo(s);r?.scope&&this.logDiagnostic(e.specifiers[0].local.loc,{code:i.AlreadyDefined,data:{identifier:e.specifiers[0].local.name},severity:n.Warning}),r={node:e.specifiers[0].local,used:!1,...r,scope:"script",initialized:!0},this.setIdentiferInfo(s,r)}recordFunctionIdentifier(e){this.logProfileOrApiConflict(e.id);const t=e.id.name.toLowerCase();let s=this.getIdentifierInfo(t);s?.scope&&this.logDiagnostic(e.id.loc,{code:i.AlreadyDefined,data:{identifier:e.id.name},severity:n.Warning}),s={node:e.id,used:!1,...s,scope:"script",initialized:!0},this.setIdentiferInfo(t,s)}recordParamAsIdentifier(e){return this.recordVariableIdentifier(e,{initialized:!0})}diagnoseIdentifiers(){(this._functionScopeIdentifiers??this._scriptScopeIdentifiers).forEach((e=>{e.node&&(e.used?e.initialized||this.logDiagnostic(e.node.loc,{code:i.DefinedNeverAssigned,data:{identifier:e.node.name},severity:n.Warning}):this.logDiagnostic(e.node.loc,{code:e.initialized?i.AssignedNeverUsed:i.DefinedNeverUsed,data:{identifier:e.node.name},severity:n.Warning}))}))}}function h(e){return"ParsingError"===e?.name}function u(e){return d(e)||c(e)&&!e?.body.length}function m(e,t){if(!e||null==t||t<0)return null;let n=null;for(const s of e.overloads){const{min:e,max:r}=s.parametersInfo;if(t<e)n=e>0?{code:i.NotEnoughArguments,data:{min:e}}:{code:i.NoArgumentExpected};else{if(!(r>=0&&t>r))return null;n={code:i.TooManyArguments,data:{max:r}}}}return n}function g(e,i=[],t){if(!e)return{diagnostics:[]};return new f(t,i).validateScript(e)}export{f as ArcadeValidationService,l as format,p as isValueVariable,g as validateScript};
5
+ import{parse as e}from"../lib/arcade-parser.js";import{DiagnosticCodes as i,DiagnosticMessages as t}from"./diagnosticMessages.js";import{ArcadeReservedKeywords as n}from"./languageKeywords.js";import{DiagnosticSeverity as s}from"./types.js";import{ParsingErrorMessages as a,Syntax as o,isVariableDeclaration as r,isIdentifier as d,isEmptyStatement as c,isBlockStatement as l}from"../lib/types.js";function h(e,i){return i?e.replace(/\${(.*?)}/g,((e,t)=>i[t]?.toString()??"")):e}function f(e){return!!e&&"dictionary"!==e.type}class p{constructor(e,i=[]){this._apiDefinitions=e,this._profileVariables=i,this._isInBlock=!1,this._identifierBeingAssigned=void 0,this._assignmentValidationMode="disabled",this._scriptScopeIdentifiers=new Map,this._diagnostics=new Array,this._undeclaredIdentifiersInFunctions=new Map}validateScript(t){if(!t)return{diagnostics:[],program:null};this._isInBlock=!1,this._identifierBeingAssigned=void 0,this._assignmentValidationMode="disabled",this._diagnostics=[],this._scriptScopeIdentifiers.clear(),this._undeclaredIdentifiersInFunctions.clear(),this._functionScopeIdentifiers=void 0;let n=null;try{n=e(t,{tolerant:!0}),this.handleErrors(n.errors),n.body.forEach((e=>this.validateStatement(e))),this.diagnoseIdentifiers(),this._undeclaredIdentifiersInFunctions.size>0&&this._undeclaredIdentifiersInFunctions.forEach((e=>{for(const t of e)this.logDiagnostic(t.node.loc,{code:i.NotDefined,data:{identifier:t.node.name}})}))}catch(s){this.handleException(s)}return{diagnostics:this._diagnostics,program:n}}disableRecordIdentifierAssignment(e,i){const t=this._assignmentValidationMode;this._assignmentValidationMode="disabled",e.call(this,i),this._assignmentValidationMode=t}inBlock(e,i){const t=this._isInBlock;this._isInBlock=!0,e.call(this,i),this._isInBlock=t}get _isInFunctionScope(){return!!this._functionScopeIdentifiers}inFunctionScope(e){this._functionScopeIdentifiers=new Map,e.call(this),this.diagnoseIdentifiers(),this._functionScopeIdentifiers=void 0}logDiagnostic(e,i){const n={severity:s.Error,...i,message:h(t[i.code]??a[i.code],i.data),range:{start:{line:e.start.line-1,character:e.start.column},end:{line:e.end.line-1,character:e.end.column}}};this._diagnostics.push(n)}handleErrors(e){(e??[]).forEach(this.handleException,this)}handleException(e){if(g(e)){const{range:i,code:t,data:n}=e;this.logDiagnostic(i,{code:t,data:n})}else this.logDiagnostic({start:{line:1,column:0},end:{line:1,column:0}},{code:i.ExecutionError,data:{stack:e.stack}})}getIdentifierInfo(e){return this._functionScopeIdentifiers?.get(e)??this._scriptScopeIdentifiers.get(e)}setIdentiferInfo(e,i){this._functionScopeIdentifiers?this._functionScopeIdentifiers.set(e,i):((this._functionScopeIdentifiers??this._scriptScopeIdentifiers).set(e,i),this._functionScopeIdentifiers||this._undeclaredIdentifiersInFunctions.has(e)&&(this._undeclaredIdentifiersInFunctions.delete(e),i.used=!0))}isProfileVariable(e){return(this._profileVariables??[]).some((i=>i.name.toLowerCase()===e))}isApiItem(e){const i=!!this._apiDefinitions?.constantDefinitions?.get(e),t=!!this._apiDefinitions?.functionDefinitions?.get(e);return i||t}validateStatement(e){if(e)switch(e.type){case o.BlockStatement:return void e.body.forEach((e=>this.validateStatement(e)));case o.VariableDeclaration:return void e.declarations.forEach((e=>this.validateVariableDeclarator(e)));case o.FunctionDeclaration:return void this.validateFunctionDeclaration(e);case o.ExportNamedDeclaration:return void this.validateExportDeclaration(e);case o.ImportDeclaration:return void this.validateImportDeclaration(e);case o.WhileStatement:return void this.validateWhileStatement(e);case o.ForStatement:return void this.validateForStatement(e);case o.ForInStatement:return void this.validateForInStatement(e);case o.IfStatement:return void this.validateIfStatement(e);case o.ReturnStatement:return void this.validateExpression(e.argument);case o.ExpressionStatement:return void this.validateExpression(e.expression);case o.BreakStatement:case o.ContinueStatement:case o.EmptyStatement:return}}validateVariableDeclarator(e){this.validateExpression(e.init),this.recordVariableIdentifier(e.id,{initialized:!!e.init})}validateFunctionDeclaration(e){this.recordFunctionIdentifier(e),this.inFunctionScope((()=>{e.params.forEach((e=>this.recordParamAsIdentifier(e))),m(e.body)&&this.logDiagnostic(e.body.loc,{code:i.UnexpectedEmptyFunction,data:{identifier:e.id.name},severity:s.Warning}),this.validateStatement(e.body)}))}validateExportDeclaration(e){this.validateStatement(e.declaration)}validateImportDeclaration(e){this.recordImportIdentifier(e)}validateForStatement(e){r(e.init)?this.inBlock(this.validateStatement,e.init):this.validateExpression(e.init),this.validateExpression(e.update),this.validateExpression(e.test),m(e.body)&&this.logDiagnostic(e.body.loc,{code:i.EmptyBlockStatement,severity:s.Warning}),this.inBlock(this.validateStatement,e.body)}validateWhileStatement(e){this.validateExpression(e.test),m(e.body)&&this.logDiagnostic(e.body.loc,{code:i.EmptyBlockStatement,severity:s.Warning}),this.inBlock(this.validateStatement,e.body)}validateForInStatement(e){d(e.left)?this.validateExpression(e.left):this.recordVariableIdentifier(e.left.declarations[0].id,{initialized:!0,inBlock:!0}),this.validateExpression(e.right),m(e.body)&&this.logDiagnostic(e.body.loc,{code:i.EmptyBlockStatement,severity:s.Warning}),this.validateStatement(e.body)}validateIfStatement(e){this.validateExpression(e.test),m(e.consequent)&&this.logDiagnostic(e.consequent.loc,{code:i.EmptyBlockStatement,severity:s.Warning}),e.alternate&&m(e.alternate)&&this.logDiagnostic(e.alternate.loc,{code:i.EmptyBlockStatement,severity:s.Warning}),this.inBlock(this.validateStatement,e.consequent),this.inBlock(this.validateStatement,e.alternate)}validateExpression(e){if(e)switch(e.type){case o.AssignmentExpression:return void this.validateAssignmentExpression(e);case o.CallExpression:return void this.validateCallExpression(e);case o.Identifier:return void this.validateIdentifier(e);case o.Literal:return void this.validateLiteral(e);case o.ArrayExpression:return void e.elements.forEach((e=>this.validateExpression(e)));case o.ObjectExpression:return void this.validateObjectExpression(e);case o.UnaryExpression:return void this.validateUnaryExpression(e);case o.UpdateExpression:return void this.validateUpdateExpression(e);case o.BinaryExpression:case o.LogicalExpression:return void this.validateBinaryAndLogicalExpression(e);case o.MemberExpression:return void this.validateMemberExpression(e);case o.TemplateLiteral:return void e.expressions.forEach((e=>this.validateExpression(e)));default:return}}validateAssignmentExpression(e){const i=this._identifierBeingAssigned,t=this._assignmentValidationMode;d(e.left)&&(this._identifierBeingAssigned=e.left.name.toLowerCase(),this._assignmentValidationMode="left"),this.validateExpression(e.left),d(e.left)&&(this._assignmentValidationMode="right"),this.validateExpression(e.right),this._identifierBeingAssigned=i,this._assignmentValidationMode=t}validateCallExpression(e){if(this.validateExpression(e.callee),d(e.callee)){const i=e.callee.name.toLowerCase(),t=this.getIdentifierInfo(i),n=this._apiDefinitions?.functionDefinitions?.get(i);if(!t&&n){const i=u(n,e.arguments.length);i&&this.logDiagnostic(e.loc,i)}}e.arguments.forEach((e=>this.validateExpression(e)))}validateIdentifier(e){const t=e.name.toLowerCase(),n=this.getIdentifierInfo(t);if(n){if("left"===this._assignmentValidationMode&&this._identifierBeingAssigned===t)return void(n.initialized=!0);if("right"===this._assignmentValidationMode&&this._identifierBeingAssigned===t)return;n.used=!0}else if(!this.isProfileVariable(t)&&!this.isApiItem(t)){if(this._isInFunctionScope){let i=this._undeclaredIdentifiersInFunctions.get(t);return i||(i=[],this._undeclaredIdentifiersInFunctions.set(t,i)),void i.push({node:e,identifier:t})}this.logDiagnostic(e.loc,{code:i.NotDefined,data:{identifier:e.name}})}}validateLiteral(e){I(e.raw).forEach((e=>{const i=this.getIdentifierInfo(e.toLowerCase());i&&(i.used=!0)}))}logProfileOrApiConflict(e){const t=e.name.toLowerCase(),n=this.isProfileVariable(t),a=this.isApiItem(t);(n||a)&&this.logDiagnostic(e.loc,{code:n?i.ProfileVariablesConflict:i.ApiConflict,severity:s.Warning,data:{identifier:e.name}})}logReservedKeywordsConflict(e){const t=e.name.toLowerCase();n.includes(t)&&this.logDiagnostic(e.loc,{code:i.ReservedKeyword,severity:s.Warning,data:{identifier:e.name}})}validateObjectExpression(e){e.properties.forEach((e=>{this.validateExpression(e.value)}))}validateUnaryExpression(e){this.validateExpression(e.argument)}validateUpdateExpression(e){this.validateExpression(e.argument)}validateBinaryAndLogicalExpression(e){this.validateExpression(e.left),this.validateExpression(e.right)}validateMemberExpression(e){const i=this.flattenMemberExpressionAndValidate(e),t=i[0].object;this.disableRecordIdentifierAssignment(this.validateExpression,t),d(t)&&(this.getIdentifierInfo(t.name.toLowerCase())||this.validateMemberExpressionWithProfile(i)||this.validateConstantMemberExpression(i))}flattenMemberExpressionAndValidate(e){return e.type===o.MemberExpression?(d(e.property)&&!e.computed||this.validateExpression(e.property),[...this.flattenMemberExpressionAndValidate(e.object),e]):[]}extractAndValidatePropertyName(e){switch(e.type){case"Identifier":return e.name.toLowerCase();case"Literal":return"string"!=typeof e.value?(this.logDiagnostic(e.loc,{code:i.UnexpectedPropertyIdentifier}),null):e.value.toLowerCase();default:return this.logDiagnostic(e.loc,{code:i.UnexpectedPropertyIdentifier}),null}}validateConstantMemberExpression(e){const t=e[0];if(!d(t.object))return!1;const n=t.object.name.toLowerCase(),s=this._apiDefinitions?.constantDefinitions?.get(n);if(!s)return!1;if("namespace"!==s.type)return this.logDiagnostic(t.property.loc,{code:i.NotADictionary,data:{identifier:n}}),!0;const a=this.extractAndValidatePropertyName(t.property);if(!a)return!0;if(!s.members.some((e=>e.key===a))){const e=s.members.reduce(((e,i)=>`${e}${e?" | ":""}${i.completion.label.split(".").pop()}`),"");this.logDiagnostic(t.property.loc,{code:i.InvalidConstantIdentifier,data:{list:e}})}return e.length>1&&this.logDiagnostic(e[1].property.loc,{code:i.UnexpectedPropertyIdentifier}),!0}validateMemberExpressionWithProfile(e){const t=e[0];if(t.object.type!==o.Identifier)return!1;const n=t.object.name.toLowerCase(),a=this._profileVariables?.find((e=>e.key===n));if(!a)return!1;if(f(a))return this.logDiagnostic(t.object.loc,{code:i.NotADictionary,data:{identifier:a.name}}),!0;if(this._identifierBeingAssigned===n)return this.logDiagnostic(t.loc,{code:i.ProfileVariablesAreImmutable}),!0;let r=a;for(let o=0;o<e.length;o++){if(e[o].computed)return!0;if(f(r))return this.logDiagnostic(e[o-1]?.property.loc??e[o].object.loc,{code:i.NotADictionary,data:{identifier:r.name}}),!0;const t=this.extractAndValidatePropertyName(e[o].property);if(!t)return!0;if(0===r.properties.length)return this.logDiagnostic(e[o].property.loc,{code:i.UnknownPropertyIdentifier,data:{identifier:t},severity:s.Warning}),!0;const n=r.properties.find((e=>e.name.toLowerCase()===t));if(!n){const t=r.properties.reduce(((e,i)=>`${e}${e?" | ":""}${i.name.split(".").pop()}`),"");return this.logDiagnostic(e[o].property.loc,{code:i.InvalidPropertyIdentifier,data:{list:t}}),!0}r=n}return!0}recordVariableIdentifier(e,t){this.logReservedKeywordsConflict(e),this.logProfileOrApiConflict(e);const n=e.name.toLowerCase();let a=this.getIdentifierInfo(n);const o=a&&this._isInFunctionScope&&"function"===a.scope,r=a&&!this._isInFunctionScope&&"script"===a.scope;(o||r)&&this.logDiagnostic(e.loc,{code:i.AlreadyDefined,data:{identifier:e.name},severity:s.Warning});const d=t.inBlock??this._isInBlock,{initialized:c}=t;if(!a||this._isInFunctionScope&&"function"!==a.scope){a={node:e,used:!1,initialized:c,scope:this._isInFunctionScope?"function":d?"block":"script"}}else a.node=e,a.used=!1,a.initialized=c;return"block"!==a.scope||d||(a.scope="script",this.logDiagnostic(e.loc,{code:i.AlreadyDefined,data:{identifier:e.name},severity:s.Warning})),this.setIdentiferInfo(n,a),!1}recordImportIdentifier(e){const t=e.specifiers[0].local;this.logProfileOrApiConflict(t);const n=t.name.toLowerCase();let a=this.getIdentifierInfo(n);a?.scope&&this.logDiagnostic(e.specifiers[0].local.loc,{code:i.AlreadyDefined,data:{identifier:e.specifiers[0].local.name},severity:s.Warning}),a={node:e.specifiers[0].local,used:!1,...a,scope:"script",initialized:!0},this.setIdentiferInfo(n,a)}recordFunctionIdentifier(e){this.logProfileOrApiConflict(e.id);const t=e.id.name.toLowerCase();let n=this.getIdentifierInfo(t);n?.scope&&this.logDiagnostic(e.id.loc,{code:i.AlreadyDefined,data:{identifier:e.id.name},severity:s.Warning}),n={node:e.id,used:!1,...n,scope:"script",initialized:!0},this.setIdentiferInfo(t,n)}recordParamAsIdentifier(e){return this.recordVariableIdentifier(e,{initialized:!0})}diagnoseIdentifiers(){(this._functionScopeIdentifiers??this._scriptScopeIdentifiers).forEach((e=>{e.node&&(e.used?e.initialized||this.logDiagnostic(e.node.loc,{code:i.DefinedNeverAssigned,data:{identifier:e.node.name},severity:s.Warning}):this.logDiagnostic(e.node.loc,{code:e.initialized?i.AssignedNeverUsed:i.DefinedNeverUsed,data:{identifier:e.node.name},severity:s.Warning}))}))}}function g(e){return"ParsingError"===e?.name}function m(e){return c(e)||l(e)&&!e?.body.length}function u(e,t){if(!e||null==t||t<0)return null;const{min:n,max:s}=e.overloads.reduce(((e,i)=>{const{min:t,max:n}=i.parametersInfo;return e.min>=0&&(e.min=Math.min(t,e.min)),e.max>=0&&(e.max=n<0?n:Math.max(n,e.max)),e}),{min:1/0,max:0});return t<n?n>0?{code:i.NotEnoughArguments,data:{min:n}}:{code:i.NoArgumentExpected}:s>=0&&t>s?{code:i.TooManyArguments,data:{max:s}}:null}const v=new RegExp(/\B@\w+/g);function I(e){return Array.from((e??"").matchAll(v),(e=>e[0].slice(1)))}function y(e,i=[],t){if(!e)return{diagnostics:[]};return new p(t,i).validateScript(e)}export{p as ArcadeValidationService,h as format,f as isValueVariable,y as validateScript};