diff --git a/dist/renderers/maplibre.js b/dist/renderers/maplibre.js index 60706b4..896972d 100644 --- a/dist/renderers/maplibre.js +++ b/dist/renderers/maplibre.js @@ -1,4360 +1,5 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.maplibre = {})); -})(this, (function (exports) { 'use strict'; - - function t(){return t=Object.assign?Object.assign.bind():function(t){for(var e=1;e{const{x:i,y:o}=t,{x:s,y:r}=e,n=s-i,a=r-o;return Math.sqrt(a*a+n*n)};class o{constructor({name:t,callback:e,unregister:i,register:o}){this.name=undefined,this.callback=undefined,this.registered=false,this.register=undefined,this.unregister=undefined,this.name=t,this.register=()=>{this.registered||(this.registered=true,o(e));},this.unregister=()=>{this.register&&(this.registered=false,i(e));},this.callback=e;}}class s{constructor(t){this._minPixelDragDistance=undefined,this._minPixelDragDistanceDrawing=undefined,this._minPixelDragDistanceSelecting=undefined,this._lastDrawEvent=undefined,this._coordinatePrecision=undefined,this._heldKeys=new Set,this._listeners=[],this._dragState="not-dragging",this._currentModeCallbacks=undefined,this._minPixelDragDistance="number"==typeof t.minPixelDragDistance?t.minPixelDragDistance:1,this._minPixelDragDistanceSelecting="number"==typeof t.minPixelDragDistanceSelecting?t.minPixelDragDistanceSelecting:1,this._minPixelDragDistanceDrawing="number"==typeof t.minPixelDragDistanceDrawing?t.minPixelDragDistanceDrawing:8,this._coordinatePrecision="number"==typeof t.coordinatePrecision?t.coordinatePrecision:9;}getButton(t){return -1===t.button?"neither":0===t.button?"left":1===t.button?"middle":2===t.button?"right":"neither"}getMapElementXYPosition(t){const e=this.getMapEventElement(),{left:i,top:o}=e.getBoundingClientRect();return {containerX:t.clientX-i,containerY:t.clientY-o}}getDrawEventFromEvent(t){const i=this.getLngLatFromEvent(t);if(!i)return null;const{lng:o,lat:s}=i,{containerX:r,containerY:n}=this.getMapElementXYPosition(t),a=this.getButton(t),l=Array.from(this._heldKeys);return {lng:e(o,this._coordinatePrecision),lat:e(s,this._coordinatePrecision),containerX:r,containerY:n,button:a,heldKeys:l}}register(t){this._currentModeCallbacks=t,this._listeners=this.getAdapterListeners(),this._listeners.forEach(t=>{t.register();});}getCoordinatePrecision(){return this._coordinatePrecision}getAdapterListeners(){return [new o({name:"pointerdown",callback:t=>{if(!this._currentModeCallbacks)return;if(!t.isPrimary)return;const e=this.getDrawEventFromEvent(t);e&&(this._dragState="pre-dragging",this._lastDrawEvent=e);},register:t=>{this.getMapEventElement().addEventListener("pointerdown",t);},unregister:t=>{this.getMapEventElement().removeEventListener("pointerdown",t);}}),new o({name:"pointermove",callback:t=>{if(!this._currentModeCallbacks)return;if(!t.isPrimary)return;t.preventDefault();const e=this.getDrawEventFromEvent(t);if(e)if("not-dragging"===this._dragState)this._currentModeCallbacks.onMouseMove(e),this._lastDrawEvent=e;else if("pre-dragging"===this._dragState){if(!this._lastDrawEvent)return;const t={x:this._lastDrawEvent.containerX,y:this._lastDrawEvent.containerY},o={x:e.containerX,y:e.containerY},s=this._currentModeCallbacks.getState(),r=i(t,o);let n=false;if(n="drawing"===s?r{this.setDraggability.bind(this)(t);});}else "dragging"===this._dragState&&this._currentModeCallbacks.onDrag(e,t=>{this.setDraggability.bind(this)(t);});},register:t=>{this.getMapEventElement().addEventListener("pointermove",t);},unregister:t=>{this.getMapEventElement().removeEventListener("pointermove",t);}}),new o({name:"contextmenu",callback:t=>{this._currentModeCallbacks&&t.preventDefault();},register:t=>{this.getMapEventElement().addEventListener("contextmenu",t);},unregister:t=>{this.getMapEventElement().removeEventListener("contextmenu",t);}}),new o({name:"pointerup",callback:t=>{if(!this._currentModeCallbacks)return;if(t.target!==this.getMapEventElement())return;if(!t.isPrimary)return;const e=this.getDrawEventFromEvent(t);e&&("dragging"===this._dragState?this._currentModeCallbacks.onDragEnd(e,t=>{this.setDraggability.bind(this)(t);}):"not-dragging"!==this._dragState&&"pre-dragging"!==this._dragState||this._currentModeCallbacks.onClick(e),this._dragState="not-dragging",this.setDraggability(true));},register:t=>{this.getMapEventElement().addEventListener("pointerup",t);},unregister:t=>{this.getMapEventElement().removeEventListener("pointerup",t);}}),new o({name:"keyup",callback:t=>{this._currentModeCallbacks&&(this._heldKeys.delete(t.key),this._currentModeCallbacks.onKeyUp({key:t.key,heldKeys:Array.from(this._heldKeys),preventDefault:()=>t.preventDefault()}));},register:t=>{this.getMapEventElement().addEventListener("keyup",t);},unregister:t=>{this.getMapEventElement().removeEventListener("keyup",t);}}),new o({name:"keydown",callback:t=>{this._currentModeCallbacks&&(this._heldKeys.add(t.key),this._currentModeCallbacks.onKeyDown({key:t.key,heldKeys:Array.from(this._heldKeys),preventDefault:()=>t.preventDefault()}));},register:t=>{this.getMapEventElement().addEventListener("keydown",t);},unregister:t=>{this.getMapEventElement().removeEventListener("keydown",t);}})]}unregister(){this._listeners.forEach(t=>{t.unregister();}),this.clear();}}class a extends s{constructor(t){super(t),this._nextRender=undefined,this._map=undefined,this._container=undefined,this._rendered=false,this.changedIds={deletion:false,points:false,linestrings:false,polygons:false,styling:false},this._map=t.map,this._container=this._map.getContainer();}clearLayers(){this._rendered&&(["point","linestring","polygon"].forEach(t=>{const e=`td-${t.toLowerCase()}`;this._map.removeLayer(e),"polygon"===t&&this._map.removeLayer(e+"-outline"),this._map.removeSource(e);}),this._rendered=false,this._nextRender&&(cancelAnimationFrame(this._nextRender),this._nextRender=undefined));}_addGeoJSONSource(t,e){this._map.addSource(t,{type:"geojson",data:{type:"FeatureCollection",features:e},tolerance:0});}_addFillLayer(t){return this._map.addLayer({id:t,source:t,type:"fill",paint:{"fill-color":["get","polygonFillColor"],"fill-opacity":["get","polygonFillOpacity"]}})}_addFillOutlineLayer(t,e){const i=this._map.addLayer({id:t+"-outline",source:t,type:"line",paint:{"line-width":["get","polygonOutlineWidth"],"line-color":["get","polygonOutlineColor"]}});return e&&this._map.moveLayer(t,e),i}_addLineLayer(t,e){const i=this._map.addLayer({id:t,source:t,type:"line",paint:{"line-width":["get","lineStringWidth"],"line-color":["get","lineStringColor"]}});return e&&this._map.moveLayer(t,e),i}_addPointLayer(t,e){const i=this._map.addLayer({id:t,source:t,type:"circle",paint:{"circle-stroke-color":["get","pointOutlineColor"],"circle-stroke-width":["get","pointOutlineWidth"],"circle-radius":["get","pointWidth"],"circle-color":["get","pointColor"]}});return e&&this._map.moveLayer(t,e),i}_addLayer(t,e,i){"Point"===e&&this._addPointLayer(t,i),"LineString"===e&&this._addLineLayer(t,i),"Polygon"===e&&(this._addFillLayer(t),this._addFillOutlineLayer(t,i));}_addGeoJSONLayer(t,e){const i=`td-${t.toLowerCase()}`;return this._addGeoJSONSource(i,e),this._addLayer(i,t),i}_setGeoJSONLayerData(t,e){const i=`td-${t.toLowerCase()}`;return this._map.getSource(i).setData({type:"FeatureCollection",features:e}),i}getEmptyGeometries(){return {points:[],linestrings:[],polygons:[]}}updateChangedIds(t){[...t.updated,...t.created].forEach(t=>{"Point"===t.geometry.type?this.changedIds.points=true:"LineString"===t.geometry.type?this.changedIds.linestrings=true:"Polygon"===t.geometry.type&&(this.changedIds.polygons=true);}),t.deletedIds.length>0&&(this.changedIds.deletion=true),0===t.created.length&&0===t.updated.length&&0===t.deletedIds.length&&(this.changedIds.styling=true);}getLngLatFromEvent(t){const{left:e,top:i}=this._container.getBoundingClientRect();return this.unproject(t.clientX-e,t.clientY-i)}getMapEventElement(){return this._map.getCanvas()}setDraggability(t){t?(this._map.dragRotate.enable(),this._map.dragPan.enable()):(this._map.dragRotate.disable(),this._map.dragPan.disable());}project(t,e){const{x:i,y:o}=this._map.project({lng:t,lat:e});return {x:i,y:o}}unproject(t,e){const{lng:i,lat:o}=this._map.unproject({x:t,y:e});return {lng:i,lat:o}}setCursor(t){const e=this._map.getCanvas();"unset"===t?e.style.removeProperty("cursor"):e.style.cursor=t;}setDoubleClickToZoom(t){t?this._map.doubleClickZoom.enable():this._map.doubleClickZoom.disable();}render(t,e){this.updateChangedIds(t),this._nextRender&&cancelAnimationFrame(this._nextRender),this._nextRender=requestAnimationFrame(()=>{const i=[...t.created,...t.updated,...t.unchanged],o=this.getEmptyGeometries();for(let t=0;t{const{properties:i}=s;if(i.mode!==t)return;const r=e[t](s);"Point"===s.geometry.type?(i.pointColor=r.pointColor,i.pointOutlineColor=r.pointOutlineColor,i.pointOutlineWidth=r.pointOutlineWidth,i.pointWidth=r.pointWidth,o.points.push(s)):"LineString"===s.geometry.type?(i.lineStringColor=r.lineStringColor,i.lineStringWidth=r.lineStringWidth,o.linestrings.push(s)):"Polygon"===s.geometry.type&&(i.polygonFillColor=r.polygonFillColor,i.polygonFillOpacity=r.polygonFillOpacity,i.polygonOutlineColor=r.polygonOutlineColor,i.polygonOutlineWidth=r.polygonOutlineWidth,o.polygons.push(s));});}const{points:s,linestrings:r,polygons:n}=o;if(this._rendered){const t=this.changedIds.deletion||this.changedIds.styling,e=t||this.changedIds.linestrings,i=t||this.changedIds.polygons;let o;(t||this.changedIds.points)&&(o=this._setGeoJSONLayerData("Point",s)),e&&this._setGeoJSONLayerData("LineString",r),i&&this._setGeoJSONLayerData("Polygon",n),o&&this._map.moveLayer(o);}else {const t=this._addGeoJSONLayer("Point",s);this._addGeoJSONLayer("LineString",r),this._addGeoJSONLayer("Polygon",n),this._rendered=true,t&&this._map.moveLayer(t);}this.changedIds={points:false,linestrings:false,polygons:false,deletion:false,styling:false};});}clear(){this._currentModeCallbacks&&(this._currentModeCallbacks.onClear(),this.clearLayers());}getCoordinatePrecision(){return super.getCoordinatePrecision()}unregister(){return super.unregister()}register(t){super.register(t),this._currentModeCallbacks&&this._currentModeCallbacks.onReady&&this._currentModeCallbacks.onReady();}}class l extends s{constructor(t){super(t),this.mapboxglAdapter=undefined,this.mapboxglAdapter=new a(t);}register(t){this.mapboxglAdapter.register(t);}unregister(){this.mapboxglAdapter.unregister();}getCoordinatePrecision(){return this.mapboxglAdapter.getCoordinatePrecision()}getLngLatFromEvent(t){return this.mapboxglAdapter.getLngLatFromEvent(t)}getMapEventElement(){return this.mapboxglAdapter.getMapEventElement()}setDraggability(t){this.mapboxglAdapter.setDraggability(t);}project(t,e){return this.mapboxglAdapter.project(t,e)}unproject(t,e){return this.mapboxglAdapter.unproject(t,e)}setCursor(t){this.mapboxglAdapter.setCursor(t);}setDoubleClickToZoom(t){this.mapboxglAdapter.setDoubleClickToZoom(t);}render(t,e){this.mapboxglAdapter.render(t,e);}clear(){this.mapboxglAdapter.clear();}}let c=0;const b="undefined"!=typeof navigator&&undefined!==navigator.userAgent?navigator.userAgent.toLowerCase():"";b.includes("firefox"),b.includes("safari")&&!b.includes("chrom")&&(b.includes("version/15.4")||/cpu (os|iphone os) 15_4 like mac os x/.test(b)),b.includes("webkit")&&b.includes("edge"),b.includes("macintosh");"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof OffscreenCanvas&&self instanceof WorkerGlobalScope;!function(){let t=false;try{const e=Object.defineProperty({},"passive",{get:function(){t=!0;}});window.addEventListener("_",null,e),window.removeEventListener("_",null,e);}catch(t){}}();var O=class{constructor(){this.disposed=false;}dispose(){this.disposed||(this.disposed=true,this.disposeInternal());}disposeInternal(){}},L=class{constructor(t){this.type=t,this.target=null;}preventDefault(){this.defaultPrevented=true;}stopPropagation(){this.propagationStopped=true;}};function W(){}function j(t){for(const e in t)delete t[e];}var B=class extends O{constructor(t){super(),this.eventTarget_=t,this.pendingRemovals_=null,this.dispatching_=null,this.listeners_=null;}addEventListener(t,e){if(!t||!e)return;const i=this.listeners_||(this.listeners_={}),o=i[t]||(i[t]=[]);o.includes(e)||o.push(e);}dispatchEvent(t){const e="string"==typeof t,i=e?t:t.type,o=this.listeners_&&this.listeners_[i];if(!o)return;const s=e?new L(t):t;s.target||(s.target=this.eventTarget_||this);const r=this.dispatching_||(this.dispatching_={}),n=this.pendingRemovals_||(this.pendingRemovals_={});let a;i in r||(r[i]=0,n[i]=0),++r[i];for(let t=0,e=o.length;t0)}removeEventListener(t,e){if(!this.listeners_)return;const i=this.listeners_[t];if(!i)return;const o=i.indexOf(e);-1!==o&&(this.pendingRemovals_&&t in this.pendingRemovals_?(i[o]=W,++this.pendingRemovals_[t]):(i.splice(o,1),0===i.length&&delete this.listeners_[t]));}},G="change";function N(t,e,i,o,s){if(s){const s=i;i=function(){t.removeEventListener(e,i),s.apply(this,arguments);};}const r={target:t,type:e,listener:i};return t.addEventListener(e,i),r}function A(t,e,i,o){return N(t,e,i,o,true)}function R(t){t&&t.target&&(t.target.removeEventListener(t.type,t.listener),j(t));}var H=class extends B{constructor(){super(),this.on=this.onInternal,this.once=this.onceInternal,this.un=this.unInternal,this.revision_=0;}changed(){++this.revision_,this.dispatchEvent(G);}getRevision(){return this.revision_}onInternal(t,e){if(Array.isArray(t)){const i=t.length,o=new Array(i);for(let s=0;s1?i:2,undefined===e&&(e=i>2?t.slice():new Array(o));for(let s=0;syt?i=yt:i<-yt&&(i=-yt),e[s+1]=i;}return e},Lt=function(t,e,i){const o=t.length;i=i>1?i:2,undefined===e&&(e=i>2?t.slice():new Array(o));for(let s=0;st*Math.PI/180,o=i(t[1]),s=i(t[0]),r=i(e[1]),n=r-o,a=i(e[0])-s,l=Math.sin(n/2)*Math.sin(n/2)+Math.cos(o)*Math.cos(r)*Math.sin(a/2)*Math.sin(a/2);return 2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l))*6371e3/1e3}const Yt=6371008.8;function Ht(t){return t%360*Math.PI/180}function Kt(t){return t/(Yt/1e3)}function Jt(t){return t%(2*Math.PI)*180/Math.PI}const $t=57.29577951308232,qt=.017453292519943295,Zt=6378137,Qt=(t,e)=>({x:0===t?0:t*qt*Zt,y:0===e?0:Math.log(Math.tan(Math.PI/4+e*qt/2))*Zt}),te=(t,e)=>({lng:0===t?0:$t*(t/Zt),lat:0===e?0:(2*Math.atan(Math.exp(e/Zt))-Math.PI/2)*$t});function ee(t,e,i){const o=Ht(t[0]),s=Ht(t[1]),r=Ht(i),n=Kt(e),a=Math.asin(Math.sin(s)*Math.cos(n)+Math.cos(s)*Math.sin(n)*Math.cos(r));return [Jt(o+Math.atan2(Math.sin(r)*Math.sin(n)*Math.cos(s),Math.cos(n)-Math.sin(s)*Math.sin(a))),Jt(a)]}function ie(t){const{center:i,radiusKilometers:o,coordinatePrecision:s}=t,r=t.steps?t.steps:64,n=[];for(let t=0;t0;function s(t){return t<0-e.epsilon||t>1+e.epsilon}function r(t,e,r,n){const a=i[t][e],l=i[t][e+1],h=i[r][n],c=i[r][n+1],d=function(t,e,i,o){if(se(t,i)||se(t,o)||se(e,i)||se(o,i))return null;const s=t[0],r=t[1],n=e[0],a=e[1],l=i[0],h=i[1],c=o[0],d=o[1],u=(s-n)*(h-d)-(r-a)*(l-c);return 0===u?null:[((s*a-r*n)*(l-c)-(s-n)*(l*d-h*c))/u,((s*a-r*n)*(h-d)-(r-a)*(l*d-h*c))/u]}(a,l,h,c);if(null===d)return;let u,g;u=l[0]!==a[0]?(d[0]-a[0])/(l[0]-a[0]):(d[1]-a[1])/(l[1]-a[1]),g=c[0]!==h[0]?(d[0]-h[0])/(c[0]-h[0]):(d[1]-h[1])/(c[1]-h[1]),s(u)||s(g)||(d.toString(),o.push(d));}}function se(t,e){return t[0]===e[0]&&t[1]===e[1]}function re(t,e){return 2===t.length&&"number"==typeof t[0]&&"number"==typeof t[1]&&Infinity!==t[0]&&Infinity!==t[1]&&(o=t[0])>=-180&&o<=180&&(i=t[1])>=-90&&i<=90&&ne(t[0])<=e&&ne(t[1])<=e;var i,o;}function ne(t){let e=1,i=0;for(;Math.round(t*e)/e!==t;)e*=10,i++;return i}function ae(t,e){return "Polygon"===t.geometry.type&&1===t.geometry.coordinates.length&&t.geometry.coordinates[0].length>=4&&t.geometry.coordinates[0].every(t=>re(t,e))&&(i=t.geometry.coordinates[0][0])[0]===(o=t.geometry.coordinates[0][t.geometry.coordinates[0].length-1])[0]&&i[1]===o[1];var i,o;}function le(t,e){return ae(t,e)&&!oe(t)}class he extends Tt{constructor(e){var i;super(e),this.mode="circle",this.center=undefined,this.clickCount=0,this.currentCircleId=undefined,this.keyEvents=undefined,this.cursors=undefined,this.startingRadiusKilometers=1e-5;const o={start:"crosshair"};if(this.cursors=e&&e.cursors?t({},o,e.cursors):o,null===(null==e?undefined:e.keyEvents))this.keyEvents={cancel:null,finish:null};else {const i={cancel:"Escape",finish:"Enter"};this.keyEvents=e&&e.keyEvents?t({},i,e.keyEvents):i;}this.startingRadiusKilometers=null!=(i=null==e?undefined:e.startingRadiusKilometers)?i:1e-5,this.validate=null==e?undefined:e.validation;}close(){if(undefined===this.currentCircleId)return;const t=this.currentCircleId;if(this.validate&&t){const e=this.store.getGeometryCopy(t);if(!this.validate({type:"Feature",id:t,geometry:e,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:Wt.Finish}))return}this.center=undefined,this.currentCircleId=undefined,this.clickCount=0,"drawing"===this.state&&this.setStarted(),this.onFinish(t,{mode:this.mode,action:"draw"});}start(){this.setStarted(),this.setCursor(this.cursors.start);}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset");}onClick(t){if(0===this.clickCount){this.center=[t.lng,t.lat];const e=ie({center:this.center,radiusKilometers:this.startingRadiusKilometers,coordinatePrecision:this.coordinatePrecision}),[i]=this.store.create([{geometry:e.geometry,properties:{mode:this.mode,radiusKilometers:this.startingRadiusKilometers}}]);this.currentCircleId=i,this.clickCount++,this.setDrawing();}else 1===this.clickCount&&this.center&&undefined!==this.currentCircleId&&this.updateCircle(t),this.close();}onMouseMove(t){this.updateCircle(t);}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close();}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const t=this.currentCircleId;this.center=undefined,this.currentCircleId=undefined,this.clickCount=0,"drawing"===this.state&&this.setStarted();try{void 0!==t&&this.store.delete([t]);}catch(t){}}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});return "Feature"===e.type&&"Polygon"===e.geometry.type&&e.properties.mode===this.mode?(i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=10,i):i}validateFeature(t){return !!super.validateFeature(t)&&t.properties.mode===this.mode&&le(t,this.coordinatePrecision)}updateCircle(t){if(1===this.clickCount&&this.center&&this.currentCircleId){const i=Ut(this.center,[t.lng,t.lat]);let o;if("web-mercator"===this.projection){const s=function(t,e){const i=1e3*Ut(t,e);if(0===i)return 1;const{x:o,y:s}=Qt(t[0],t[1]),{x:r,y:n}=Qt(e[0],e[1]);return Math.sqrt(Math.pow(r-o,2)+Math.pow(n-s,2))/i}(this.center,[t.lng,t.lat]);o=function(t){const{center:i,radiusKilometers:o,coordinatePrecision:s}=t,r=t.steps?t.steps:64,n=1e3*o,[a,l]=i,{x:h,y:c}=Qt(a,l),d=[];for(let t=0;t[t.lng,t.lat])]}}}class ge extends de{constructor(t){super(t);}create(t){const{containerX:e,containerY:i}=t;return ue({unproject:this.unproject,point:{x:e,y:i},pointerDistance:this.pointerDistance})}}class pe extends de{constructor(t){super(t);}measure(t,e){const{x:o,y:s}=this.project(e[0],e[1]);return i({x:o,y:s},{x:t.containerX,y:t.containerY})}}class ye extends de{constructor(t,e,i){super(t),this.config=undefined,this.pixelDistance=undefined,this.clickBoundingBox=undefined,this.getSnappableCoordinateFirstClick=t=>this.getSnappable(t,t=>Boolean(t.properties&&t.properties.mode===this.mode)),this.getSnappableCoordinate=(t,e)=>this.getSnappable(t,t=>Boolean(t.properties&&t.properties.mode===this.mode&&t.id!==e)),this.config=t,this.pixelDistance=e,this.clickBoundingBox=i;}getSnappable(t,e){const i=this.clickBoundingBox.create(t),o=this.store.search(i,e),s={coord:undefined,minDist:Infinity};return o.forEach(e=>{let i;if("Polygon"===e.geometry.type)i=e.geometry.coordinates[0];else {if("LineString"!==e.geometry.type)return;i=e.geometry.coordinates;}i.forEach(e=>{const i=this.pixelDistance.measure(t,e);i180?s-=360:s<-180&&(s+=360),s}function Ce(t,e,i){const o=[],s=t.length;let r,n,a,l=0;for(let s=0;s=l&&s===t.length-1);s++){if(l>e&&0===o.length){if(r=e-l,!r)return o.push(t[s]),o;n=ve(t[s],t[s-1])-180,a=me(t[s],r,n),o.push(a);}if(l>=i)return r=i-l,r?(n=ve(t[s],t[s-1])-180,a=me(t[s],r,n),o.push(a),o):(o.push(t[s]),o);if(l>=e&&o.push(t[s]),s===t.length-1)return o;l+=Ut(t[s],t[s+1]);}if(l[e(t[0],this.config.coordinatePrecision),e(t[1],this.config.coordinatePrecision)])}}function we(t,e){return t[0]===e[0]&&t[1]===e[1]}class Se extends Tt{constructor(e){super(e),this.mode="linestring",this.currentCoordinate=0,this.currentId=undefined,this.closingPointId=undefined,this.keyEvents=undefined,this.snappingEnabled=undefined,this.cursors=undefined,this.mouseMove=false,this.insertCoordinates=undefined,this.lastCommitedCoordinates=undefined,this.snapping=undefined,this.insertPoint=undefined;const i={start:"crosshair",close:"pointer"};if(this.cursors=e&&e.cursors?t({},i,e.cursors):i,this.snappingEnabled=!(!e||undefined===e.snapping)&&e.snapping,null===(null==e?undefined:e.keyEvents))this.keyEvents={cancel:null,finish:null};else {const i={cancel:"Escape",finish:"Enter"};this.keyEvents=e&&e.keyEvents?t({},i,e.keyEvents):i;}this.validate=null==e?undefined:e.validation,this.insertCoordinates=null==e?undefined:e.insertCoordinates;}close(){if(undefined===this.currentId)return;const t=this.store.getGeometryCopy(this.currentId);t.coordinates.pop(),this.updateGeometries([...t.coordinates],undefined,Wt.Commit);const e=this.currentId;this.closingPointId&&this.store.delete([this.closingPointId]),this.currentCoordinate=0,this.currentId=undefined,this.closingPointId=undefined,this.lastCommitedCoordinates=undefined,"drawing"===this.state&&this.setStarted(),this.onFinish(e,{mode:this.mode,action:"draw"});}updateGeometries(t,e,i){if(!this.currentId)return;const o={type:"LineString",coordinates:t};if(this.validate&&!this.validate({type:"Feature",geometry:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:i}))return;const s=[{id:this.currentId,geometry:o}];this.closingPointId&&e&&s.push({id:this.closingPointId,geometry:{type:"Point",coordinates:e}}),"commit"===i&&(this.lastCommitedCoordinates=o.coordinates),this.store.updateGeometry(s);}generateInsertCoordinates(t,e){if(!this.insertCoordinates||!this.lastCommitedCoordinates)throw new Error("Not able to insert coordinates");if("amount"!==this.insertCoordinates.strategy)throw new Error("Strategy does not exist");const i=Ut(t,e)/(this.insertCoordinates.value+1);let o=[];return "globe"===this.projection?o=this.insertPoint.generateInsertionGeodesicCoordinates(t,e,i):"web-mercator"===this.projection&&(o=this.insertPoint.generateInsertionCoordinates(t,e,i)),o}createLine(t){const[e]=this.store.create([{geometry:{type:"LineString",coordinates:[t,t]},properties:{mode:this.mode}}]);this.lastCommitedCoordinates=[t,t],this.currentId=e,this.currentCoordinate++,this.setDrawing();}firstUpdateToLine(t){if(!this.currentId)return;const e=this.store.getGeometryCopy(this.currentId).coordinates,[i]=this.store.create([{geometry:{type:"Point",coordinates:[...t]},properties:{mode:this.mode}}]);this.closingPointId=i,this.setCursor(this.cursors.close);const o=[...e,t];this.updateGeometries(o,undefined,Wt.Commit),this.currentCoordinate++;}updateToLine(t,e){if(!this.currentId)return;const o=this.store.getGeometryCopy(this.currentId).coordinates,[s,r]=this.lastCommitedCoordinates?this.lastCommitedCoordinates[this.lastCommitedCoordinates.length-1]:o[o.length-2],{x:n,y:a}=this.project(s,r);if(i({x:n,y:a},{x:e.x,y:e.y})0&&!this.mouseMove&&this.onMouseMove(t),this.mouseMove=false;const e=this.currentId&&this.snappingEnabled&&this.snapping.getSnappableCoordinate(t,this.currentId)||[t.lng,t.lat];0===this.currentCoordinate?this.createLine(e):1===this.currentCoordinate&&this.currentId?this.firstUpdateToLine(e):this.currentId&&this.updateToLine(e,{x:t.containerX,y:t.containerY});}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel&&this.cleanUp(),t.key===this.keyEvents.finish&&this.close();}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const t=this.currentId;this.closingPointId=undefined,this.currentId=undefined,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted();try{void 0!==t&&this.store.delete([t]),void 0!==this.closingPointId&&this.store.delete([this.closingPointId]);}catch(t){}}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});return "Feature"===e.type&&"LineString"===e.geometry.type&&e.properties.mode===this.mode?(i.lineStringColor=this.getHexColorStylingValue(this.styles.lineStringColor,i.lineStringColor,e),i.lineStringWidth=this.getNumericStylingValue(this.styles.lineStringWidth,i.lineStringWidth,e),i.zIndex=10,i):"Feature"===e.type&&"Point"===e.geometry.type&&e.properties.mode===this.mode?(i.pointColor=this.getHexColorStylingValue(this.styles.closingPointColor,i.pointColor,e),i.pointWidth=this.getNumericStylingValue(this.styles.closingPointWidth,i.pointWidth,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.closingPointOutlineColor,"#ffffff",e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.closingPointOutlineWidth,2,e),i.zIndex=40,i):i}validateFeature(t){return !!super.validateFeature(t)&&"LineString"===t.geometry.type&&t.properties.mode===this.mode&&t.geometry.coordinates.length>=2}}function be(t,e){return "Point"===t.geometry.type&&re(t.geometry.coordinates,e)}class Ee extends Tt{constructor(e){super(e),this.mode="point",this.cursors=undefined;const i={create:"crosshair"};this.cursors=e&&e.cursors?t({},i,e.cursors):i;}start(){this.setStarted(),this.setCursor(this.cursors.create);}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset");}onClick(t){if(!this.store)throw new Error("Mode must be registered first");const e={type:"Point",coordinates:[t.lng,t.lat]},i={mode:this.mode};if(this.validate&&!this.validate({type:"Feature",geometry:e,properties:i},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:Wt.Finish}))return;const[o]=this.store.create([{geometry:e,properties:i}]);this.onFinish(o,{mode:this.mode,action:"draw"});}onMouseMove(){}onKeyDown(){}onKeyUp(){}cleanUp(){}onDragStart(){}onDrag(){}onDragEnd(){}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});return "Feature"===e.type&&"Point"===e.geometry.type&&e.properties.mode===this.mode&&(i.pointWidth=this.getNumericStylingValue(this.styles.pointWidth,i.pointWidth,e),i.pointColor=this.getHexColorStylingValue(this.styles.pointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.pointOutlineColor,i.pointOutlineColor,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.pointOutlineWidth,2,e),i.zIndex=30),i}validateFeature(t){return !!super.validateFeature(t)&&t.properties.mode===this.mode&&be(t,this.coordinatePrecision)}}class Ie extends de{constructor(t,e){super(t),this.config=undefined,this.pixelDistance=undefined,this._startEndPoints=[],this.config=t,this.pixelDistance=e;}get ids(){return this._startEndPoints.concat()}set ids(t){}create(t,e){if(this.ids.length)throw new Error("Opening and closing points already created");if(t.length<=3)throw new Error("Requires at least 4 coordinates");this._startEndPoints=this.store.create([{geometry:{type:"Point",coordinates:t[0]},properties:{mode:e,[At]:true}},{geometry:{type:"Point",coordinates:t[t.length-2]},properties:{mode:e,[At]:true}}]);}delete(){this.ids.length&&(this.store.delete(this.ids),this._startEndPoints=[]);}update(t){if(2!==this.ids.length)throw new Error("No closing points to update");this.store.updateGeometry([{id:this.ids[0],geometry:{type:"Point",coordinates:t[0]}},{id:this.ids[1],geometry:{type:"Point",coordinates:t[t.length-3]}}]);}isClosingPoint(t){const e=this.store.getGeometryCopy(this.ids[0]),i=this.store.getGeometryCopy(this.ids[1]),o=this.pixelDistance.measure(t,e.coordinates),s=this.pixelDistance.measure(t,i.coordinates);return {isClosing:o0&&!this.mouseMove&&this.onMouseMove(t),this.mouseMove=false,0===this.currentCoordinate){const e=this.snappingEnabled?this.snapping.getSnappableCoordinateFirstClick(t):undefined;e&&(t.lng=e[0],t.lat=e[1]);const[i]=this.store.create([{geometry:{type:"Polygon",coordinates:[[[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat]]]},properties:{mode:this.mode}}]);this.currentId=i,this.currentCoordinate++,this.setDrawing();}else if(1===this.currentCoordinate&&this.currentId){const e=this.snappingEnabled?this.snapping.getSnappableCoordinate(t,this.currentId):undefined;e&&(t.lng=e[0],t.lat=e[1]);const i=this.store.getGeometryCopy(this.currentId);if(we([t.lng,t.lat],i.coordinates[0][0]))return;if(!this.updatePolygonGeometry([i.coordinates[0][0],[t.lng,t.lat],[t.lng,t.lat],i.coordinates[0][0]],Wt.Commit))return;this.currentCoordinate++;}else if(2===this.currentCoordinate&&this.currentId){const e=this.snappingEnabled?this.snapping.getSnappableCoordinate(t,this.currentId):undefined;e&&(t.lng=e[0],t.lat=e[1]);const i=this.store.getGeometryCopy(this.currentId).coordinates[0];if(we([t.lng,t.lat],i[1]))return;if(!this.updatePolygonGeometry([i[0],i[1],[t.lng,t.lat],[t.lng,t.lat],i[0]],Wt.Commit))return;2===this.currentCoordinate&&this.closingPoints.create(i,"polygon"),this.currentCoordinate++;}else if(this.currentId){const e=this.snappingEnabled?this.snapping.getSnappableCoordinate(t,this.currentId):undefined,i=this.store.getGeometryCopy(this.currentId).coordinates[0],{isClosing:o,isPreviousClosing:s}=this.closingPoints.isClosingPoint(t);if(s||o)this.close();else {if(e&&(t.lng=e[0],t.lat=e[1]),we([t.lng,t.lat],i[this.currentCoordinate-1]))return;const o=function(t=[[[0,0],[0,1],[1,1],[1,0],[0,0]]]){return {type:"Feature",geometry:{type:"Polygon",coordinates:t},properties:{}}}([[...i.slice(0,-1),[t.lng,t.lat],i[0]]]);if(!this.updatePolygonGeometry(o.geometry.coordinates[0],Wt.Commit))return;this.currentCoordinate++,this.closingPoints.ids.length&&this.closingPoints.update(o.geometry.coordinates[0]);}}}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close();}onKeyDown(){}onDragStart(){this.setCursor("unset");}onDrag(){}onDragEnd(){this.setCursor(this.cursors.start);}cleanUp(){const t=this.currentId;this.currentId=undefined,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted();try{void 0!==t&&this.store.delete([t]),this.closingPoints.ids.length&&this.closingPoints.delete();}catch(t){}}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});if(e.properties.mode===this.mode){if("Polygon"===e.geometry.type)return i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=10,i;if("Point"===e.geometry.type)return i.pointWidth=this.getNumericStylingValue(this.styles.closingPointWidth,i.pointWidth,e),i.pointColor=this.getHexColorStylingValue(this.styles.closingPointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.closingPointOutlineColor,i.pointOutlineColor,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.closingPointOutlineWidth,2,e),i.zIndex=30,i}return i}validateFeature(t){return !!super.validateFeature(t)&&t.properties.mode===this.mode&&ae(t,this.coordinatePrecision)}}class ke extends Tt{constructor(e){super(e),this.mode="rectangle",this.center=undefined,this.clickCount=0,this.currentRectangleId=undefined,this.keyEvents=undefined,this.cursors=undefined;const i={start:"crosshair"};if(this.cursors=e&&e.cursors?t({},i,e.cursors):i,null===(null==e?undefined:e.keyEvents))this.keyEvents={cancel:null,finish:null};else {const i={cancel:"Escape",finish:"Enter"};this.keyEvents=e&&e.keyEvents?t({},i,e.keyEvents):i;}}updateRectangle(t,e){if(1===this.clickCount&&this.center&&this.currentRectangleId){const i=this.store.getGeometryCopy(this.currentRectangleId).coordinates[0][0],o={type:"Polygon",coordinates:[[i,[t.lng,i[1]],[t.lng,t.lat],[i[0],t.lat],i]]};if(this.validate&&!this.validate({id:this.currentRectangleId,geometry:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e}))return;this.store.updateGeometry([{id:this.currentRectangleId,geometry:o}]);}}close(){const t=this.currentRectangleId;this.center=undefined,this.currentRectangleId=undefined,this.clickCount=0,"drawing"===this.state&&this.setStarted(),t&&this.onFinish(t,{mode:this.mode,action:"draw"});}start(){this.setStarted(),this.setCursor(this.cursors.start);}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset");}onClick(t){if(0===this.clickCount){this.center=[t.lng,t.lat];const[e]=this.store.create([{geometry:{type:"Polygon",coordinates:[[[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat]]]},properties:{mode:this.mode}}]);this.currentRectangleId=e,this.clickCount++,this.setDrawing();}else this.updateRectangle(t,Wt.Finish),this.close();}onMouseMove(t){this.updateRectangle(t,Wt.Provisional);}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close();}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const t=this.currentRectangleId;this.center=undefined,this.currentRectangleId=undefined,this.clickCount=0,"drawing"===this.state&&this.setStarted(),undefined!==t&&this.store.delete([t]);}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});return "Feature"===e.type&&"Polygon"===e.geometry.type&&e.properties.mode===this.mode?(i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=10,i):i}validateFeature(t){return !!super.validateFeature(t)&&t.properties.mode===this.mode&&le(t,this.coordinatePrecision)}}class Fe extends Tt{constructor(t){super({styles:t.styles}),this.type=zt.Render,this.mode="render",this.mode=t.modeName;}registerBehaviors(t){this.mode=t.mode;}start(){this.setStarted();}stop(){this.setStopped();}onKeyUp(){}onKeyDown(){}onClick(){}onDragStart(){}onDrag(){}onDragEnd(){}onMouseMove(){}cleanUp(){}styleFeature(t){return {pointColor:this.getHexColorStylingValue(this.styles.pointColor,"#3f97e0",t),pointWidth:this.getNumericStylingValue(this.styles.pointWidth,6,t),pointOutlineColor:this.getHexColorStylingValue(this.styles.pointOutlineColor,"#ffffff",t),pointOutlineWidth:this.getNumericStylingValue(this.styles.pointOutlineWidth,0,t),polygonFillColor:this.getHexColorStylingValue(this.styles.polygonFillColor,"#3f97e0",t),polygonFillOpacity:this.getNumericStylingValue(this.styles.polygonFillOpacity,.3,t),polygonOutlineColor:this.getHexColorStylingValue(this.styles.polygonOutlineColor,"#3f97e0",t),polygonOutlineWidth:this.getNumericStylingValue(this.styles.polygonOutlineWidth,4,t),lineStringWidth:this.getNumericStylingValue(this.styles.lineStringWidth,4,t),lineStringColor:this.getHexColorStylingValue(this.styles.lineStringColor,"#3f97e0",t),zIndex:this.getNumericStylingValue(this.styles.zIndex,0,t)}}validateFeature(t){return super.validateFeature(t)&&(be(t,this.coordinatePrecision)||ae(t,this.coordinatePrecision)||function(t,e){return "LineString"===t.geometry.type&&t.geometry.coordinates.length>=2&&t.geometry.coordinates.every(t=>re(t,e))}(t,this.coordinatePrecision))}}function Oe(t,e){const i=t,o=e,s=Ht(i[1]),r=Ht(o[1]);let n=Ht(o[0]-i[0]);n>Math.PI&&(n-=2*Math.PI),n<-Math.PI&&(n+=2*Math.PI);const a=Math.log(Math.tan(r/2+Math.PI/4)/Math.tan(s/2+Math.PI/4)),l=(Jt(Math.atan2(n,a))+360)%360;return l>180?-(360-l):l}function Le(t,e,i){let o=e;e<0&&(o=-Math.abs(o));const s=o/Yt,r=t[0]*Math.PI/180,n=Ht(t[1]),a=Ht(i),l=s*Math.cos(a);let h=n+l;Math.abs(h)>Math.PI/2&&(h=h>0?Math.PI-h:-Math.PI-h);const c=Math.log(Math.tan(h/2+Math.PI/4)/Math.tan(n/2+Math.PI/4)),d=Math.abs(c)>1e-11?l/c:Math.cos(n),u=[(180*(r+s*Math.sin(a)/d)/Math.PI+540)%360-180,180*h/Math.PI];return u[0]+=u[0]-t[0]>180?-360:t[0]-u[0]>180?360:0,u}function We(t,i,o,s,r){const n=s(t[0],t[1]),a=s(i[0],i[1]),{lng:l,lat:h}=r((n.x+a.x)/2,(n.y+a.y)/2);return [e(l,o),e(h,o)]}function je(t,i,o){const s=Le(t,1e3*Ut(t,i)/2,Oe(t,i));return [e(s[0],o),e(s[1],o)]}function Be({featureCoords:t,precision:e,unproject:i,project:o,projection:s}){const r=[];for(let n=0;n({geometry:{type:"Point",coordinates:t},properties:e(i)}))}(t,t=>({mode:this.mode,[Nt]:true,midPointSegment:t,midPointFeatureId:e}),i,this.config.project,this.config.unproject,this.projection));}delete(){this._midPoints.length&&(this.store.delete(this._midPoints),this._midPoints=[]);}getUpdated(t){if(0!==this._midPoints.length)return Be({featureCoords:t,precision:this.coordinatePrecision,project:this.config.project,unproject:this.config.unproject,projection:this.config.projection}).map((t,e)=>({id:this._midPoints[e],geometry:{type:"Point",coordinates:t}}))}}class Ne extends de{constructor(t){super(t),this._selectionPoints=[];}get ids(){return this._selectionPoints.concat()}set ids(t){}create(t,e,i){this._selectionPoints=this.store.create(function(t,e,i){const o=[],s="Polygon"===e?t.length-1:t.length;for(let e=0;e({mode:this.mode,selectionPoint:true,selectionPointFeatureId:i,index:t})));}delete(){this.ids.length&&(this.store.delete(this.ids),this._selectionPoints=[]);}getUpdated(t){if(0!==this._selectionPoints.length)return this._selectionPoints.map((e,i)=>({id:e,geometry:{type:"Point",coordinates:t[i]}}))}getOneUpdated(t,e){if(undefined!==this._selectionPoints[t])return {id:this._selectionPoints[t],geometry:{type:"Point",coordinates:e}}}}function Ae(t,e){let i=false;for(let n=0,a=e.length;n(o=t)[1]!=(r=a[l])[1]>o[1]&&o[0]<(r[0]-s[0])*(o[1]-s[1])/(r[1]-s[1])+s[0]&&(i=!i);}var o,s,r;return i}const Re=(t,e,i)=>{const o=t=>t*t,s=(t,e)=>o(t.x-e.x)+o(t.y-e.y);return Math.sqrt(((t,e,i)=>{const o=s(e,i);if(0===o)return s(t,e);let r=((t.x-e.x)*(i.x-e.x)+(t.y-e.y)*(i.y-e.y))/o;return r=Math.max(0,Math.min(1,r)),s(t,{x:e.x+r*(i.x-e.x),y:e.y+r*(i.y-e.y)})})(t,e,i))};class Ve extends de{constructor(t,e,i){super(t),this.config=undefined,this.createClickBoundingBox=undefined,this.pixelDistance=undefined,this.config=t,this.createClickBoundingBox=e,this.pixelDistance=i;}find(t,e){let i,o,s=Infinity,r=Infinity;const n=this.createClickBoundingBox.create(t),a=this.store.search(n);for(let n=0;n180||n<-180||a>90||a<-90)return false;r[t]=[n,a];}"Polygon"===o.type&&(r[r.length-1]=[r[0][0],r[0][1]]);const a=this.selectionPoints.getUpdated(r)||[],l=this.midPoints.getUpdated(r)||[];if(i&&!i({type:"Feature",id:this.draggedFeatureId,geometry:o,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:Wt.Provisional}))return false;this.store.updateGeometry([{id:this.draggedFeatureId,geometry:o},...a,...l]),this.dragPosition=[t.lng,t.lat];}else "Point"===o.type&&(this.store.updateGeometry([{id:this.draggedFeatureId,geometry:{type:"Point",coordinates:s}}]),this.dragPosition=[t.lng,t.lat]);}}class Te extends de{constructor(t,e,i,o){super(t),this.config=undefined,this.pixelDistance=undefined,this.selectionPoints=undefined,this.midPoints=undefined,this.draggedCoordinate={id:null,index:-1},this.config=t,this.pixelDistance=e,this.selectionPoints=i,this.midPoints=o;}getClosestCoordinate(t,e){const i={dist:Infinity,index:-1,isFirstOrLastPolygonCoord:false};let o;if("LineString"===e.type)o=e.coordinates;else {if("Polygon"!==e.type)return i;o=e.coordinates[0];}for(let s=0;s180||t.lng<-180||t.lat>90||t.lat<-90)return false;if("Polygon"!==s.type||o!==r.length-1&&0!==o)r[o]=n;else {const t=r.length-1;r[0]=n,r[t]=n;}const a=this.selectionPoints.getOneUpdated(o,n),l=a?[a]:[],h=this.midPoints.getUpdated(r)||[];return !("Point"!==s.type&&!e&&oe({type:"Feature",geometry:s,properties:{}})||i&&!i({type:"Feature",id:this.draggedCoordinate.id,geometry:s,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:Wt.Provisional})||(this.store.updateGeometry([{id:this.draggedCoordinate.id,geometry:s},...l,...h]),0))}isDragging(){return null!==this.draggedCoordinate.id}startDragging(t,e){this.draggedCoordinate={id:t,index:e};}stopDragging(){this.draggedCoordinate={id:null,index:-1};}}function Xe(t){let e=0,i=0,o=0;return ("Polygon"===t.geometry.type?t.geometry.coordinates[0].slice(0,-1):t.geometry.coordinates).forEach(t=>{e+=t[0],i+=t[1],o++;},true),[e/o,i/o]}function Ue(t,e){t[0]+=t[0]-e[0]>180?-360:e[0]-t[0]>180?360:0;const i=Yt,o=e[1]*Math.PI/180,s=t[1]*Math.PI/180,r=s-o;let n=Math.abs(t[0]-e[0])*Math.PI/180;n>Math.PI&&(n-=2*Math.PI);const a=Math.log(Math.tan(s/2+Math.PI/4)/Math.tan(o/2+Math.PI/4)),l=Math.abs(a)>1e-11?r/a:Math.cos(o);return Math.sqrt(r*r+l*l*n*n)*i}function Ye(t){const e=("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).map(t=>{const{x:e,y:i}=Qt(t[0],t[1]);return [e,i]});return "Polygon"===t.geometry.type?function(t){let e=0,i=0,o=0;const s=t.length;for(let r=0;r{if(0===e||360===e||-360===e)return t;const i=.017453292519943295*e,o=("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).map(([t,e])=>Qt(t,e)),s=o.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0});s.x/=o.length,s.y/=o.length;const r=o.map(t=>({x:s.x+(t.x-s.x)*Math.cos(i)-(t.y-s.y)*Math.sin(i),y:s.y+(t.x-s.x)*Math.sin(i)+(t.y-s.y)*Math.cos(i)})).map(({x:t,y:e})=>[te(t,e).lng,te(t,e).lat]);"Polygon"===t.geometry.type?t.geometry.coordinates[0]=r:(console.log("rotatedCoordinates linestring",r),t.geometry.coordinates=r);})(a,-(this.lastBearing-n));}else {if("globe"!==this.config.projection)throw new Error("Unsupported projection");if(n=Oe(Xe({type:"Feature",geometry:s,properties:{}}),r),!this.lastBearing)return void(this.lastBearing=n+180);!function(t,e){if(0===e||360===e||-360===e)return t;const i=Xe(t);("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).forEach(t=>{const o=Oe(i,t)+e,s=Ue(i,t),r=Le(i,s,o);t[0]=r[0],t[1]=r[1];});}(a,-(this.lastBearing-(n+180)));}const l="Polygon"===s.type?s.coordinates[0]:s.coordinates;l.forEach(t=>{t[0]=e(t[0],this.coordinatePrecision),t[1]=e(t[1],this.coordinatePrecision);});const h=this.midPoints.getUpdated(l)||[],c=this.selectionPoints.getUpdated(l)||[];if(o&&!o({id:i,type:"Feature",geometry:s,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:Wt.Provisional}))return false;this.store.updateGeometry([{id:i,geometry:s},...c,...h]),"web-mercator"===this.projection?this.lastBearing=n:"globe"===this.projection&&(this.lastBearing=n+180);}}class Ke extends de{constructor(t,e,i){super(t),this.config=undefined,this.selectionPoints=undefined,this.midPoints=undefined,this.lastDistance=undefined,this.config=t,this.selectionPoints=e,this.midPoints=i;}reset(){this.lastDistance=undefined;}scale(t,o,s){const r=this.store.getGeometryCopy(o);if("Polygon"!==r.type&&"LineString"!==r.type)return;const n=[t.lng,t.lat],a={type:"Feature",geometry:r,properties:{}};let l;const h=Ye(a);if("web-mercator"===this.config.projection){const e=Qt(t.lng,t.lat);l=i(h,e);}else {if("globe"!==this.config.projection)throw new Error("Invalid projection");l=Ut(Xe({type:"Feature",geometry:r,properties:{}}),n);}if(!this.lastDistance)return void(this.lastDistance=l);const c=1-(this.lastDistance-l)/l;if("web-mercator"===this.config.projection){const{lng:t,lat:e}=te(h.x,h.y);!function(t,e,i){if(1===e)return t;const o=("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).map(([t,e])=>Qt(t,e)),s=Qt(i[0],i[1]),r=o.map(t=>({x:s.x+(t.x-s.x)*e,y:s.y+(t.y-s.y)*e})).map(({x:t,y:e})=>[te(t,e).lng,te(t,e).lat]);"Polygon"===t.geometry.type?t.geometry.coordinates[0]=r:t.geometry.coordinates=r;}(a,c,[t,e]);}else "globe"===this.config.projection&&function(t,e,i,o="xy"){1===e||("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).forEach(t=>{const s=Ue(i,t),r=Oe(i,t),n=Le(i,s*e,r);"x"!==o&&"xy"!==o||(t[0]=n[0]),"y"!==o&&"xy"!==o||(t[1]=n[1]);});}(a,c,Xe(a));const d="Polygon"===r.type?r.coordinates[0]:r.coordinates;d.forEach(t=>{t[0]=e(t[0],this.coordinatePrecision),t[1]=e(t[1],this.coordinatePrecision);});const u=this.midPoints.getUpdated(d)||[],g=this.selectionPoints.getUpdated(d)||[];if(s&&!s({id:o,type:"Feature",geometry:r,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:Wt.Provisional}))return false;this.store.updateGeometry([{id:o,geometry:r},...g,...u]),this.lastDistance=l;}}class Je extends de{constructor(t,e,i,o){super(t),this.config=undefined,this.pixelDistance=undefined,this.selectionPoints=undefined,this.midPoints=undefined,this.minimumScale=1e-4,this.draggedCoordinate={id:null,index:-1},this.boundingBoxMaps={opposite:{0:4,1:5,2:6,3:7,4:0,5:1,6:2,7:3}},this.config=t,this.pixelDistance=e,this.selectionPoints=i,this.midPoints=o;}getClosestCoordinate(t,e){const i={dist:Infinity,index:-1,isFirstOrLastPolygonCoord:false};let o;if("LineString"===e.type)o=e.coordinates;else {if("Polygon"!==e.type)return i;o=e.coordinates[0];}for(let s=0;s=0)return false;break;case 1:if(i>=0)return false;break;case 2:if(e>=0||i>=0)return false;break;case 3:if(e>=0)return false;break;case 4:if(e>=0||i<=0)return false;break;case 5:if(i<=0)return false;break;case 6:if(e<=0||i<=0)return false;break;case 7:if(e<=0)return false}return true}getSelectedFeatureDataWebMercator(){if(!this.draggedCoordinate.id||-1===this.draggedCoordinate.index)return null;const t=this.getFeature(this.draggedCoordinate.id);if(!t)return null;const e=this.getNormalisedCoordinates(t.geometry);return {boundingBox:this.getBBoxWebMercator(e),feature:t,updatedCoords:e,selectedCoordinate:e[this.draggedCoordinate.index]}}centerWebMercatorDrag(t){const e=this.getSelectedFeatureDataWebMercator();if(!e)return null;const{feature:i,boundingBox:o,updatedCoords:s,selectedCoordinate:r}=e,n=Ye(i);if(!n)return null;const a=Qt(r[0],r[1]),{closestBBoxIndex:l}=this.getIndexesWebMercator(o,a),h=Qt(t.lng,t.lat);return this.scaleWebMercator({closestBBoxIndex:l,updatedCoords:s,webMercatorCursor:h,webMercatorSelected:a,webMercatorOrigin:n}),s}centerFixedWebMercatorDrag(t){const e=this.getSelectedFeatureDataWebMercator();if(!e)return null;const{feature:i,boundingBox:o,updatedCoords:s,selectedCoordinate:r}=e,n=Ye(i);if(!n)return null;const a=Qt(r[0],r[1]),{closestBBoxIndex:l}=this.getIndexesWebMercator(o,a),h=Qt(t.lng,t.lat);return this.scaleFixedWebMercator({closestBBoxIndex:l,updatedCoords:s,webMercatorCursor:h,webMercatorSelected:a,webMercatorOrigin:n}),s}scaleFixedWebMercator({closestBBoxIndex:t,webMercatorOrigin:e,webMercatorSelected:o,webMercatorCursor:s,updatedCoords:r}){if(!this.isValidDragWebMercator(t,e.x-s.x,e.y-s.y))return null;let n=i(e,s)/i(e,o);return n<0&&(n=this.minimumScale),this.performWebMercatorScale(r,e.x,e.y,n,n),r}oppositeFixedWebMercatorDrag(t){const e=this.getSelectedFeatureDataWebMercator();if(!e)return null;const{boundingBox:i,updatedCoords:o,selectedCoordinate:s}=e,r=Qt(s[0],s[1]),{oppositeBboxIndex:n,closestBBoxIndex:a}=this.getIndexesWebMercator(i,r),l={x:i[n][0],y:i[n][1]},h=Qt(t.lng,t.lat);return this.scaleFixedWebMercator({closestBBoxIndex:a,updatedCoords:o,webMercatorCursor:h,webMercatorSelected:r,webMercatorOrigin:l}),o}oppositeWebMercatorDrag(t){const e=this.getSelectedFeatureDataWebMercator();if(!e)return null;const{boundingBox:i,updatedCoords:o,selectedCoordinate:s}=e,r=Qt(s[0],s[1]),{oppositeBboxIndex:n,closestBBoxIndex:a}=this.getIndexesWebMercator(i,r),l={x:i[n][0],y:i[n][1]},h=Qt(t.lng,t.lat);return this.scaleWebMercator({closestBBoxIndex:a,updatedCoords:o,webMercatorCursor:h,webMercatorSelected:r,webMercatorOrigin:l}),o}scaleWebMercator({closestBBoxIndex:t,webMercatorOrigin:e,webMercatorSelected:i,webMercatorCursor:o,updatedCoords:s}){const r=e.x-o.x,n=e.y-o.y;if(!this.isValidDragWebMercator(t,r,n))return null;let a=1;0!==r&&1!==t&&5!==t&&(a=1-(e.x-i.x-r)/r);let l=1;return 0!==n&&3!==t&&7!==t&&(l=1-(e.y-i.y-n)/n),this.validateScale(a,l)?(a<0&&(a=this.minimumScale),l<0&&(l=this.minimumScale),this.performWebMercatorScale(s,e.x,e.y,a,l),s):null}getFeature(t){if(null===this.draggedCoordinate.id)return null;const e=this.store.getGeometryCopy(t);return "Polygon"!==e.type&&"LineString"!==e.type?null:{type:"Feature",geometry:e,properties:{}}}getNormalisedCoordinates(t){return "Polygon"===t.type?t.coordinates[0]:t.coordinates}validateScale(t,e){const i=!isNaN(t)&&e{const{x:r,y:n}=Qt(t[0],t[1]),a=e+(r-e)*o,l=i+(n-i)*s,{lng:h,lat:c}=te(a,l);t[0]=h,t[1]=c;});}getBBoxWebMercator(t){const e=[Infinity,Infinity,-Infinity,-Infinity];(t=t.map(t=>{const{x:e,y:i}=Qt(t[0],t[1]);return [e,i]})).forEach(([t,i])=>{te[2]&&(e[2]=t),i>e[3]&&(e[3]=i);});const[i,o,s,r]=e;return [[i,r],[(i+s)/2,r],[s,r],[s,r+(o-r)/2],[s,o],[(i+s)/2,o],[i,o],[i,r+(o-r)/2]]}getIndexesWebMercator(t,e){let o,s=Infinity;for(let r=0;rthis.store.has(t)).map(t=>({id:t,property:Gt,value:false}));this.store.updateProperty(t),this.onDeselect(this.selected[0]),this.selected=[],this.selectionPoints.delete(),this.midPoints.delete();}deleteSelected(){this.store.delete(this.selected),this.selected=[];}onRightClick(t){if(!this.selectionPoints.ids.length)return;let e,i=Infinity;if(this.selectionPoints.ids.forEach(o=>{const s=this.store.getGeometryCopy(o),r=this.pixelDistance.measure(t,s.coordinates);r0);if(this.selected.length&&i)this.midPoints.insert(i.id,this.coordinatePrecision);else if(e&&e.id)this.select(e.id,true);else if(this.selected.length&&this.allowManualDeselection)return void this.deselect()}start(){this.setStarted(),this.setSelecting();}stop(){this.cleanUp(),this.setStarted(),this.setStopped();}onClick(t){"right"!==t.button?"left"===t.button&&this.onLeftClick(t):this.onRightClick(t);}canScale(t){return this.keyEvents.scale&&this.keyEvents.scale.every(e=>t.heldKeys.includes(e))}canRotate(t){return this.keyEvents.rotate&&this.keyEvents.rotate.every(e=>t.heldKeys.includes(e))}preventDefaultKeyEvent(t){const e=this.canRotate(t),i=this.canScale(t);(e||i)&&t.preventDefault();}onKeyDown(t){this.preventDefaultKeyEvent(t);}onKeyUp(t){if(this.preventDefaultKeyEvent(t),this.keyEvents.delete&&t.key===this.keyEvents.delete){if(!this.selected.length)return;this.onDeselect(this.selected[0]),this.deleteSelected(),this.selectionPoints.delete(),this.midPoints.delete();}else this.keyEvents.deselect&&t.key===this.keyEvents.deselect&&this.cleanUp();}cleanUp(){this.selected.length&&this.deselect();}onDragStart(t,e){if(!this.selected.length)return;const i=this.store.getPropertiesCopy(this.selected[0]),o=this.flags[i.mode];if(!(o&&o.feature&&(o.feature.draggable||o.feature.coordinates&&o.feature.coordinates.draggable||o.feature.coordinates&&o.feature.coordinates.resizable)))return;this.dragEventCount=0;const s=this.selected[0],r=this.dragCoordinate.getDraggableIndex(t,s);return o&&o.feature&&o.feature.coordinates&&(o.feature.coordinates.draggable||o.feature.coordinates.resizable)&&-1!==r?(this.setCursor(this.cursors.dragStart),o.feature.coordinates.resizable?this.dragCoordinateResizeFeature.startDragging(s,r):this.dragCoordinate.startDragging(s,r),void e(false)):o&&o.feature&&o.feature.draggable&&this.dragFeature.canDrag(t,s)?(this.setCursor(this.cursors.dragStart),this.dragFeature.startDragging(t,s),void e(false)):undefined}onDrag(t,e){const i=this.selected[0];if(!i)return;const o=this.store.getPropertiesCopy(i),s=this.flags[o.mode],r=true===(s&&s.feature&&s.feature.selfIntersectable);if(this.dragEventCount++,this.dragEventCount%this.dragEventThrottle==0)return;const n=this.validations[o.mode];if(s&&s.feature&&s.feature.rotateable&&this.canRotate(t))return e(false),void this.rotateFeature.rotate(t,i,n);if(s&&s.feature&&s.feature.scaleable&&this.canScale(t))return e(false),void this.scaleFeature.scale(t,i,n);if(this.dragCoordinateResizeFeature.isDragging()&&s.feature&&s.feature.coordinates&&s.feature.coordinates.resizable){if("globe"===this.projection)throw new Error("Globe is currently unsupported projection for resizable");return e(false),void this.dragCoordinateResizeFeature.drag(t,s.feature.coordinates.resizable,n)}this.dragCoordinate.isDragging()?this.dragCoordinate.drag(t,r,n):this.dragFeature.isDragging()?this.dragFeature.drag(t,n):e(true);}onDragEnd(t,e){this.setCursor(this.cursors.dragEnd),this.dragCoordinate.isDragging()?this.onFinish(this.selected[0],{mode:this.mode,action:"dragCoordinate"}):this.dragFeature.isDragging()?this.onFinish(this.selected[0],{mode:this.mode,action:"dragFeature"}):this.dragCoordinateResizeFeature.isDragging()&&this.onFinish(this.selected[0],{mode:this.mode,action:"dragCoordinateResize"}),this.dragCoordinate.stopDragging(),this.dragFeature.stopDragging(),this.dragCoordinateResizeFeature.stopDragging(),this.rotateFeature.reset(),this.scaleFeature.reset(),e(true);}onMouseMove(t){if(!this.selected.length)return void this.setCursor("unset");if(this.dragFeature.isDragging())return;let e=false;this.midPoints.ids.forEach(i=>{if(e)return;const o=this.store.getGeometryCopy(i);this.pixelDistance.measure(t,o.coordinates){const s=this.store.getGeometryCopy(o);this.pixelDistance.measure(t,s.coordinates)0&&(o&&o.id===this.selected[0]||i)?this.cursors.pointerOver:"unset");}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});if(e.properties.mode===this.mode&&"Point"===e.geometry.type){if(e.properties.selectionPoint)return i.pointColor=this.getHexColorStylingValue(this.styles.selectionPointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectionPointOutlineColor,i.pointOutlineColor,e),i.pointWidth=this.getNumericStylingValue(this.styles.selectionPointWidth,i.pointWidth,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectionPointOutlineWidth,2,e),i.zIndex=30,i;if(e.properties.midPoint)return i.pointColor=this.getHexColorStylingValue(this.styles.midPointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.midPointOutlineColor,i.pointOutlineColor,e),i.pointWidth=this.getNumericStylingValue(this.styles.midPointWidth,4,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.midPointOutlineWidth,2,e),i.zIndex=40,i}else if(e.properties[Gt]){if("Polygon"===e.geometry.type)return i.polygonFillColor=this.getHexColorStylingValue(this.styles.selectedPolygonColor,i.polygonFillColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.selectedPolygonOutlineWidth,i.polygonOutlineWidth,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.selectedPolygonOutlineColor,i.polygonOutlineColor,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.selectedPolygonFillOpacity,i.polygonFillOpacity,e),i.zIndex=10,i;if("LineString"===e.geometry.type)return i.lineStringColor=this.getHexColorStylingValue(this.styles.selectedLineStringColor,i.lineStringColor,e),i.lineStringWidth=this.getNumericStylingValue(this.styles.selectedLineStringWidth,i.lineStringWidth,e),i.zIndex=10,i;if("Point"===e.geometry.type)return i.pointWidth=this.getNumericStylingValue(this.styles.selectedPointWidth,i.pointWidth,e),i.pointColor=this.getHexColorStylingValue(this.styles.selectedPointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectedPointOutlineColor,i.pointOutlineColor,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectedPointOutlineWidth,i.pointOutlineWidth,e),i.zIndex=10,i}return i}}class qe extends Tt{constructor(...t){super(...t),this.type=zt.Static,this.mode="static";}start(){}stop(){}onKeyUp(){}onKeyDown(){}onClick(){}onDragStart(){}onDrag(){}onDragEnd(){}onMouseMove(){}cleanUp(){}styleFeature(){return t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0})}}function Ze(t,e,i,o,s){for(;o>i;){if(o-i>600){const r=o-i+1,n=e-i+1,a=Math.log(r),l=.5*Math.exp(2*a/3),h=.5*Math.sqrt(a*l*(r-l)/r)*(n-r/2<0?-1:1);Ze(t,e,Math.max(i,Math.floor(e-n*l/r+h)),Math.min(o,Math.floor(e+(r-n)*l/r+h)),s);}const r=t[e];let n=i,a=o;for(Qe(t,i,e),s(t[o],r)>0&&Qe(t,i,o);n0;)a--;}0===s(t[i],r)?Qe(t,i,a):(a++,Qe(t,a,o)),a<=e&&(i=a+1),e<=a&&(o=a-1);}}function Qe(t,e,i){const o=t[e];t[e]=t[i],t[i]=o;}function ti(t,e){ei(t,0,t.children.length,e,t);}function ei(t,e,i,o,s){s||(s=ci([])),s.minX=Infinity,s.minY=Infinity,s.maxX=-Infinity,s.maxY=-Infinity;for(let r=e;r=t.minX&&e.maxY>=t.minY}function ci(t){return {children:t,height:1,leaf:true,minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity}}function di(t,e,i,o,s){const r=[e,i];for(;r.length;){if((i=r.pop())-(e=r.pop())<=o)continue;const n=e+Math.ceil((i-e)/o/2)*o;Ze(t,n,e,i,s),r.push(e,n,n,i);}}class ui{constructor(t){this._maxEntries=undefined,this._minEntries=undefined,this.data=undefined,this._maxEntries=Math.max(4,t),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear();}search(t){let e=this.data;const i=[];if(!hi(t,e))return i;const o=this.toBBox,s=[];for(;e;){for(let r=0;r=0&&s[e].children.length>this._maxEntries;)this._split(s,e),e--;this._adjustParentBBoxes(o,s,e);}_split(t,e){const i=t[e],o=i.children.length,s=this._minEntries;this._chooseSplitAxis(i,s,o);const r=this._chooseSplitIndex(i,s,o),n=ci(i.children.splice(r,i.children.length-r));n.height=i.height,n.leaf=i.leaf,ti(i,this.toBBox),ti(n,this.toBBox),e?t[e-1].children.push(n):this._splitRoot(i,n);}_splitRoot(t,e){this.data=ci([t,e]),this.data.height=t.height+1,this.data.leaf=false,ti(this.data,this.toBBox);}_chooseSplitIndex(t,e,i){let o,s=Infinity,r=Infinity;for(let n=e;n<=i-e;n++){const e=ei(t,0,n,this.toBBox),a=ei(t,n,i,this.toBBox),l=ai(e,a),h=ri(e)+ri(a);l=e;o--){const e=t.children[o];ii(n,t.leaf?s(e):e),a+=ni(n);}return a}_adjustParentBBoxes(t,e,i){for(let o=i;o>=0;o--)ii(e[o],t);}_condense(t){for(let e,i=t.length-1;i>=0;i--)0===t[i].children.length?i>0?(e=t[i-1].children,e.splice(e.indexOf(t[i]),1)):this.clear():ti(t[i],this.toBBox);}}class gi{constructor(t){this.tree=undefined,this.idToNode=undefined,this.nodeToId=undefined,this.tree=new ui(t&&t.maxEntries?t.maxEntries:9),this.idToNode=new Map,this.nodeToId=new Map;}setMaps(t,e){this.idToNode.set(t.id,e),this.nodeToId.set(e,t.id);}toBBox(t){const e=[],i=[];let o;if("Polygon"===t.geometry.type)o=t.geometry.coordinates[0];else if("LineString"===t.geometry.type)o=t.geometry.coordinates;else {if("Point"!==t.geometry.type)throw new Error("Not a valid feature to turn into a bounding box");o=[t.geometry.coordinates];}for(let t=0;t{const o=this.toBBox(t);if(this.setMaps(t,o),i.has(String(t.id)))throw new Error(`Duplicate feature ID found ${t.id}`);i.add(String(t.id)),e.push(o);}),this.tree.load(e);}update(t){this.remove(t.id);const e=this.toBBox(t);this.setMaps(t,e),this.tree.insert(e);}remove(t){const e=this.idToNode.get(t);if(!e)throw new Error(`${t} not inserted into the spatial index`);this.tree.remove(e);}clear(){this.tree.clear();}search(t){return this.tree.search(this.toBBox(t)).map(t=>this.nodeToId.get(t))}collides(t){return this.tree.collides(this.toBBox(t))}}const pi={getId:()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return ("x"==t?e:3&e|8).toString(16)}),isValidId:t=>"string"==typeof t&&36===t.length};class yi{constructor(t){this.idStrategy=undefined,this.tracked=undefined,this.spatialIndex=undefined,this.store=undefined,this._onChange=()=>{},this.store={},this.spatialIndex=new gi,this.tracked=!t||false!==t.tracked,this.idStrategy=t&&t.idStrategy?t.idStrategy:pi;}clone(t){return JSON.parse(JSON.stringify(t))}getId(){return this.idStrategy.getId()}has(t){return Boolean(this.store[t])}load(t,e){if(0===t.length)return;const i=this.clone(t);i.forEach(t=>{null==t.id&&(t.id=this.idStrategy.getId()),this.tracked&&(t.properties.createdAt?Vt(t.properties.createdAt):t.properties.createdAt=+new Date,t.properties.updatedAt?Vt(t.properties.updatedAt):t.properties.updatedAt=+new Date);});const o=[];i.forEach(t=>{const i=t.id;if(e&&!e(t))throw new Error(`Feature is not ${i} valid: ${JSON.stringify(t)}`);if(this.has(i))throw new Error(`Feature already exists with this id: ${i}`);this.store[i]=t,o.push(i);}),this.spatialIndex.load(i),this._onChange(o,"create");}search(t,e){const i=this.spatialIndex.search(t).map(t=>this.store[t]);return this.clone(e?i.filter(e):i)}registerOnChange(t){this._onChange=(e,i)=>{t(e,i);};}getGeometryCopy(t){const e=this.store[t];if(!e)throw new Error(`No feature with this id (${t}), can not get geometry copy`);return this.clone(e.geometry)}getPropertiesCopy(t){const e=this.store[t];if(!e)throw new Error(`No feature with this id (${t}), can not get properties copy`);return this.clone(e.properties)}updateProperty(t){const e=[];t.forEach(({id:t,property:i,value:o})=>{const s=this.store[t];if(!s)throw new Error(`No feature with this (${t}), can not update geometry`);e.push(t),s.properties[i]=o,this.tracked&&(s.properties.updatedAt=+new Date);}),this._onChange&&this._onChange(e,"update");}updateGeometry(t){const e=[];t.forEach(({id:t,geometry:i})=>{e.push(t);const o=this.store[t];if(!o)throw new Error(`No feature with this (${t}), can not update geometry`);o.geometry=this.clone(i),this.spatialIndex.update(o),this.tracked&&(o.properties.updatedAt=+new Date);}),this._onChange&&this._onChange(e,"update");}create(e){const i=[];return e.forEach(({geometry:e,properties:o})=>{let s,r=t({},o);this.tracked&&(s=+new Date,o?(r.createdAt="number"==typeof o.createdAt?o.createdAt:s,r.updatedAt="number"==typeof o.updatedAt?o.updatedAt:s):r={createdAt:s,updatedAt:s});const n=this.getId(),a={id:n,type:"Feature",geometry:e,properties:r};this.store[n]=a,this.spatialIndex.insert(a),i.push(n);}),this._onChange&&this._onChange([...i],"create"),i}delete(t){t.forEach(t=>{if(!this.store[t])throw new Error("No feature with this id, can not delete");delete this.store[t],this.spatialIndex.remove(t);}),this._onChange&&this._onChange([...t],"delete");}copyAll(){return this.clone(Object.keys(this.store).map(t=>this.store[t]))}clear(){this.store={},this.spatialIndex.clear();}size(){return Object.keys(this.store).length}}class Si{constructor(e){this._modes=undefined,this._mode=undefined,this._adapter=undefined,this._enabled=false,this._store=undefined,this._eventListeners=undefined,this._instanceSelectMode=undefined,this._adapter=e.adapter,this._mode=new qe;const i=new Set,o=e.modes.reduce((t,e)=>{if(i.has(e.mode))throw new Error(`There is already a ${e.mode} mode provided`);return i.add(e.mode),t[e.mode]=e,t},{}),s=Object.keys(o);if(0===s.length)throw new Error("No modes provided");s.forEach(t=>{if(o[t].type===zt.Select){if(this._instanceSelectMode)throw new Error("only one type of select mode can be provided");this._instanceSelectMode=t;}}),this._modes=t({},o,{static:this._mode}),this._eventListeners={change:[],select:[],deselect:[],finish:[],ready:[]},this._store=new yi({tracked:!!e.tracked,idStrategy:e.idStrategy?e.idStrategy:undefined});const r=t=>{const e=[],i=this._store.copyAll().filter(i=>!t.includes(i.id)||(e.push(i),false));return {changed:e,unchanged:i}},n=(t,e)=>{this._enabled&&this._eventListeners.finish.forEach(i=>{i(t,e);});},a=(t,e)=>{if(!this._enabled)return;this._eventListeners.change.forEach(i=>{i(t,e);});const{changed:i,unchanged:o}=r(t);"create"===e?this._adapter.render({created:i,deletedIds:[],unchanged:o,updated:[]},this.getModeStyles()):"update"===e?this._adapter.render({created:[],deletedIds:[],unchanged:o,updated:i},this.getModeStyles()):"delete"===e?this._adapter.render({created:[],deletedIds:t,unchanged:o,updated:[]},this.getModeStyles()):"styling"===e&&this._adapter.render({created:[],deletedIds:[],unchanged:o,updated:[]},this.getModeStyles());},l=t=>{if(!this._enabled)return;this._eventListeners.select.forEach(e=>{e(t);});const{changed:e,unchanged:i}=r([t]);this._adapter.render({created:[],deletedIds:[],unchanged:i,updated:e},this.getModeStyles());},h=t=>{if(!this._enabled)return;this._eventListeners.deselect.forEach(t=>{t();});const{changed:e,unchanged:i}=r([t]);e&&this._adapter.render({created:[],deletedIds:[],unchanged:i,updated:e},this.getModeStyles());};Object.keys(this._modes).forEach(t=>{this._modes[t].register({mode:t,store:this._store,setCursor:this._adapter.setCursor.bind(this._adapter),project:this._adapter.project.bind(this._adapter),unproject:this._adapter.unproject.bind(this._adapter),setDoubleClickToZoom:this._adapter.setDoubleClickToZoom.bind(this._adapter),onChange:a,onSelect:l,onDeselect:h,onFinish:n,coordinatePrecision:this._adapter.getCoordinatePrecision()});});}checkEnabled(){if(!this._enabled)throw new Error("Terra Draw is not enabled")}getModeStyles(){const t={};return Object.keys(this._modes).forEach(e=>{t[e]=t=>this._instanceSelectMode&&t.properties[Gt]?this._modes[this._instanceSelectMode].styleFeature.bind(this._modes[this._instanceSelectMode])(t):this._modes[e].styleFeature.bind(this._modes[e])(t);}),t}featuresAtLocation({lng:t,lat:e},o){const s=o&&undefined!==o.pointerDistance?o.pointerDistance:30,r=!o||undefined===o.ignoreSelectFeatures||o.ignoreSelectFeatures,n=this._adapter.unproject.bind(this._adapter),a=this._adapter.project.bind(this._adapter),l=a(t,e),h=ue({unproject:n,point:l,pointerDistance:s});return this._store.search(h).filter(o=>{if(r&&(o.properties[Nt]||o.properties.selectionPoint))return false;if("Point"===o.geometry.type){const t=o.geometry.coordinates,e=a(t[0],t[1]);return i(l,e){if(Boolean(t&&"object"==typeof t&&"properties"in t&&"object"==typeof t.properties&&null!==t.properties&&"mode"in t.properties)){const e=this._modes[t.properties.mode];return !!e&&e.validateFeature.bind(e)(t)}return false});}start(){this._enabled=true,this._adapter.register({onReady:()=>{this._eventListeners.ready.forEach(t=>{t();});},getState:()=>this._mode.state,onClick:t=>{this._mode.onClick(t);},onMouseMove:t=>{this._mode.onMouseMove(t);},onKeyDown:t=>{this._mode.onKeyDown(t);},onKeyUp:t=>{this._mode.onKeyUp(t);},onDragStart:(t,e)=>{this._mode.onDragStart(t,e);},onDrag:(t,e)=>{this._mode.onDrag(t,e);},onDragEnd:(t,e)=>{this._mode.onDragEnd(t,e);},onClear:()=>{this._mode.cleanUp(),this._store.clear();}});}getFeaturesAtLngLat(t,e){const{lng:i,lat:o}=t;return this.featuresAtLocation({lng:i,lat:o},e)}getFeaturesAtPointerEvent(t,e){const i=this._adapter.getLngLatFromEvent.bind(this._adapter)(t);return null===i?[]:this.featuresAtLocation(i,e)}stop(){this._enabled=false,this._adapter.unregister();}on(t,e){const i=this._eventListeners[t];i.includes(e)||i.push(e);}off(t,e){const i=this._eventListeners[t];i.includes(e)&&i.splice(i.indexOf(e),1);}} - - /** Import */ - - /** - * BasicDrawComponent. - * ref: https://github.com/JamesLMilner/terra-draw/blob/main/guides/4.MODES.md#selection-mode - * @param {TerraDrawBaseAdapter} adapter - * @param {Object} options - * @return TerraDratxw - */ - const BasicDrawComponent = (adapter, options = {}) => - new Si({ - adapter, - modes: [ - new $e({ - modename: 'modify', - flags: { - render: { - feature: { - // draggable: true, - coordinates: { - midpoints: true, - draggable: true, - deletable: true, - validation: () => true, - }, - }, - }, - }, - }), - new Ee(), - new Se(), - new De(), - new he(), - new ke(), - new Fe({ - modeName: 'render', - // TODO More styles by feature properties - styles: { - pointColor: 'red', - pointOutlineWidth: 2, - lineStringColor: 'red', - lineStringWidth: 2, - polygonFillColor: '#00FFFF', - polygonFillOpacity: 0, - polygonOutlineColor: 'red', - polygonOutlineWidth: 2, - }, - }), - ], - ...options, - }); - - /** - * getUtils. - * - * @param {HTMLElement} target - * @param {TerraDraw} draw - * @param {Object} options - */ - const getUtils = (target, draw, options = {}) => { - draw.start(); - draw.setMode('render'); - - // Resume drawn features - const storageId = target.id - ? `terra-draw-data-${target.id}` - : 'terra-draw-data'; - const featureData = window.localStorage.getItem(storageId); - if (featureData) { - try { - const features = JSON.parse(featureData); - features.forEach(f => (f.properties = { mode: 'render' })); - draw.addFeatures(features); - } catch (err) { - console.warn( - 'Fail to drawn features from Local Storage.', - featureData, - err, - ); - window.localStorage.removeItem(storageId); - } - } - - const cursorHolder = target.querySelector('canvas') ?? target; - cursorHolder.style.removeProperty('cursor'); - const features = draw.getSnapshot(); - - new window.MutationObserver(() => { - switch (target.dataset.draw) { - case '': - case undefined: - draw.setMode('render'); - break - case 'modify': - draw.setMode('select'); - break - case 'delete': - draw.setMode('render'); - cursorHolder.style.cursor = 'not-allowed'; - break - case 'clear': - window.localStorage.removeItem(storageId); - target.dataset.draw = ''; - draw.clear(); - break - case 'features': - window.alert( - `${features.length} features\n\n${JSON.stringify(features, null, 4)}`, - ); - break - default: - draw.setMode(target.dataset.draw); - break - } - }).observe(target, { - attributes: true, - attributeFilter: ['data-draw'], - }); - - draw.on('change', () => { }); - draw.on('finish', (id, context) => { - if (context.action === 'draw') { - const feature = draw.getSnapshot().find(feature => feature.id === id); - if (feature) { - draw.removeFeatures([id]); - feature.properties.mode = 'render'; - draw.addFeatures([feature]); - } - } - - const idFilter = options.idFilter ?? (() => true); - const features = draw.getSnapshot().filter(idFilter); - window.localStorage.setItem(storageId, JSON.stringify(features)); - - if (context.mode !== 'point' && context.action === 'draw') { - target.dataset.draw = ''; - } - }); - document.onclick = event => { - if (target.dataset.draw === 'delete') { - const features = draw.getFeaturesAtPointerEvent(event, { - pointerDistance: 40, - }); - if (features.length > 0) { - draw.removeFeatures([features[0].id]); - if (draw.getSnapshot().length === 0) { - target.dataset.draw = ''; - } - } - } - }; - }; - - /** - * loadCSS. - * @description Dynamically import CSS, simply add stylesheet at - * @param {String} url - */ - const loadCSS = url => { - if (document.head.querySelector(`link[href="${url}"]`)) return - - const link = document.createElement('link'); - Object.assign(link, { - rel: 'stylesheet', - href: url, - onerror: () => console.warn('Fail to load stylesheet:', url), - }); - document.head.appendChild(link); - }; - - /** - * MapOption. - * @description Class for valid options - */ - class MapOption { - constructor ({ name, desc, example, exampleDesc, isValid }) { - this.name = name; - this.desc = desc; - this.example = example; - this.exampleDesc = exampleDesc; - this.isValid = isValid; - } - - valueOf () { - return this.name - } - } - - /** - * Class: base class for Map Renderer - */ - class defaultExport { - /** fields */ - width = '300px' - height = '300px' - center = [121, 24] - zoom = 7 - control = { - scale: false, - fullscreen: false, - } - - layers = [] - data = [] - aliases = [] - svgPin = { - html: '', - size: [27, 41], - anchor: [13.5, 35.25], - } - - get map () { - if (this._map === undefined) { - throw Error('map is not set in current Renderer') - } - return this._map - } - - set map (value) { - if (this._map) throw Error('map cannot be reassigned') - this._map = value; - } - - get steps () { - return [ - this.setOptionAliases, - this.createView, - this.addMap, - this.setControl, - this.addTileData, - this.addGPXFile, - this.getTerraDrawAdapter, - { - valueOf: () => this.setDraw, - depends: this.getTerraDrawAdapter, - }, - this.setExtra, - ] - } - - validateOption (option, value) { - const isValid = this.constructor.validOptions.find( - opt => opt.valueOf() === option, - )?.isValid; - if (!isValid) { throw Error(`Cannot find inValid method for option ${option}`) } - - return isValid(value) - } - - /** options */ - static validOptions = Object.freeze([ - new MapOption({ - name: 'id', - desc: 'id of map HTML element', - isValid: value => (!!value?.match(/\w+/)), - }), - new MapOption({ - name: 'width', - desc: 'CSS width of map HTML element', - example: '200px', - exampleDesc: '', - isValid: value => window.CSS.supports(`width: ${value}`), - }), - new MapOption({ - name: 'height', - desc: 'CSS height of map HTML element', - example: '200px', - exampleDesc: '', - isValid: value => window.CSS.supports(`height: ${value}`), - }), - new MapOption({ - name: 'center', - desc: 'Center of camera map, value: [lon, lat]', - example: '[121, 24]', - exampleDesc: 'Center of Taiwan', - isValid: value => { - // TODO xy value other than WGS84 - try { - const [x, y] = JSON.parse(value); - return !isNaN(x) && !isNaN(y) - } catch { - return false - } - }, - }), - new MapOption({ - name: 'zoom', - desc: 'Zoom level for map camera, number between: 0-22', - example: '7.0', - exampleDesc: 'Small country / US state', - isValid: value => { - const zoom = Number(value); - return !isNaN(zoom) && zoom >= 0 && zoom <= 22 - }, - }), - new MapOption({ - name: 'control', - desc: 'Object of control options, supports: fullscreen, scale', - example: '\n scale: true', - exampleDesc: 'Add Scale bar', - isValid: value => typeof value === 'object', - }), - new MapOption({ - name: 'debug', - desc: 'Set true to show tile boundary', - example: 'true', - exampleDesc: '', - isValid: value => value === 'true', - }), - new MapOption({ - name: 'XYZ', - desc: 'Raster tile format with {x}, {y} and {z}', - example: - 'https://tile.openstreetmap.jp/styles/osm-bright/512/{z}/{x}/{y}.png', - exampleDesc: 'Tile from OSM Japan!', - isValid: value => { - return ( - URL.parse(value) && - value.includes('{x}') && - value.includes('{y}') && - value.includes('z') - ) - }, - }), - new MapOption({ - name: 'GPX', - desc: 'URL of GPX file', - example: - 'https://raw.githubusercontent.com/openlayers/openlayers/main/examples/data/gpx/fells_loop.gpx', - exampleDesc: 'Example from topografix', - isValid: value => URL.parse(value), - }), - new MapOption({ - name: 'WMTS', - desc: 'URL of WMTS document', - example: 'https://gis.sinica.edu.tw/tileserver/wmts', - exampleDesc: 'SINICA Taiwan', - isValid: value => URL.parse(value), - }), - new MapOption({ - name: 'draw', - desc: 'Draw Something on map', - example: 'true', - exampleDesc: 'Enable Draw Tools', - isValid: value => value === 'true', - }), - new MapOption({ - name: 'eval', - desc: 'Custom Script', - example: "console.log('this', this)", - exampleDesc: 'Print Renderer info', - isValid: () => true, - }), - ]) - - /** step: options */ - setOptionAliases (config) { - if (config.XYZ) { - const xyzArray = - typeof config.XYZ === 'string' ? [config.XYZ] : config.XYZ; - xyzArray.forEach(record => { - let obj; - let url; - if (typeof record === 'string') { - url = new URL(record); - obj = { - type: 'tile', - url: record, - title: `${url.host}${url.pathname.split('%7B')[0]}`, - }; - } else if (typeof record === 'object') { - url = new URL(record.url); - obj = { - type: 'tile', - url: record.url, - title: record.title - ? record.title - : `${url.host}${url.pathname.split('%7B')[0]}`, - }; - } else { - return - } - config.data.push(obj); - }); - delete config.XYZ; - } - - if (config.WMTS) { - config.data.push({ - type: 'wmts', - url: config.aliases[config.WMTS] ?? config.WMTS, - }); - delete config.WMTS; - } - - if (config.GPX) { - config.data.push({ - type: 'gpx', - url: config.GPX, - }); - delete config.GPX; - } - - // Replace aliases into real string - if ( - typeof config.center === 'string' && - Object.prototype.hasOwnProperty.call(config.aliases, config.center) - ) { - config.center = config.aliases[config.center]; - } - config.data?.forEach(record => { - if (Object.prototype.hasOwnProperty.call(config.aliases, record.url)) { - record.title = record.url; - record.url = config.aliases[record.url]; - } - }); - } - - /** step: HTMLElement */ - createView ({ target, width, height }) { - target.style.width = width; - target.style.height = height; - if (window.getComputedStyle(target.parentElement).display === 'flex') { - target.style.flexBasis = `calc(${width})`; - } - } - - /** step: draw */ - setDraw = ({ target, terraDrawAdapter }) => { - const idPrefix = target?.id ? target.id + '-' : ''; - const options = { - idStrategy: { - isValidId: _ => true, - getId: (function () { - let id = idPrefix + window.crypto.randomUUID(); - return function () { - id = idPrefix + window.crypto.randomUUID(); - return id - } - })(), - }, - }; - this.terraDraw = BasicDrawComponent(terraDrawAdapter, options); - target.dataset.draw = ''; - getUtils(target, this.terraDraw, { - idFilter: feature => feature.id.startsWith(idPrefix), - }); - - return this.terraDraw - } - - /** options: not-implemented */ - getTerraDrawAdapter () { - return { state: 'skip' } - } - - addTileData () { - return { state: 'skip' } - } - - addGPXFile () { - return { state: 'skip' } - } - - addMarker () { - return { state: 'skip' } - } - - setControl () { - return { state: 'skip' } - } - - setExtra () { - return { state: 'skip' } - } - - updateCamera () { - return { state: 'skip' } - } - - project () { - return { state: 'skip' } - } - - unproject () { - return { state: 'skip' } - } - - restoreCamera () { - this.updateCamera({ center: this.center, zoom: this.zoom }); - } - - /** utils: eval */ - propsForEval () { - let currentPrototype = this; - let props = []; - let entries = []; - while (currentPrototype !== Object.prototype) { - props = props.concat(Object.getOwnPropertyNames(currentPrototype)); - entries = entries.concat(Object.entries(currentPrototype)); - currentPrototype = Object.getPrototypeOf(currentPrototype); - } - return props - } - - evalScript (script, entries = []) { - const props = this.propsForEval(); - const extraArgNames = entries.map(([key, _]) => key); - const args = [ - ...props.map(prop => this[prop]), - ...entries.map(([_, value]) => value), - ]; - /* eslint no-new-func: 0 */ - const func = Function([...props, ...extraArgNames], script).bind( - this, - ...args, - ); - - try { - return func() - } catch (err) { - console.warn('Fail to run custom script:', err); - return null - } - } - } - - function getDefaultExportFromCjs$1 (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - var maplibreGl$1 = {exports: {}}; - - /** +!function(M,et){"object"==typeof exports&&"undefined"!=typeof module?et(exports):"function"==typeof define&&define.amd?define(["exports"],et):et((M="undefined"!=typeof globalThis?globalThis:M||self).maplibre={})}(this,(function(M){"use strict";function t(){return t=Object.assign?Object.assign.bind():function(M){for(var et=1;et{const{x:Bt,y:Wt}=M,{x:Nt,y:$t}=et,Gr=Nt-Bt,mn=$t-Wt;return Math.sqrt(mn*mn+Gr*Gr)};class o{constructor({name:M,callback:et,unregister:Bt,register:Wt}){this.name=void 0,this.callback=void 0,this.registered=!1,this.register=void 0,this.unregister=void 0,this.name=M,this.register=()=>{this.registered||(this.registered=!0,Wt(et))},this.unregister=()=>{this.register&&(this.registered=!1,Bt(et))},this.callback=et}}class s{constructor(M){this._minPixelDragDistance=void 0,this._minPixelDragDistanceDrawing=void 0,this._minPixelDragDistanceSelecting=void 0,this._lastDrawEvent=void 0,this._coordinatePrecision=void 0,this._heldKeys=new Set,this._listeners=[],this._dragState="not-dragging",this._currentModeCallbacks=void 0,this._minPixelDragDistance="number"==typeof M.minPixelDragDistance?M.minPixelDragDistance:1,this._minPixelDragDistanceSelecting="number"==typeof M.minPixelDragDistanceSelecting?M.minPixelDragDistanceSelecting:1,this._minPixelDragDistanceDrawing="number"==typeof M.minPixelDragDistanceDrawing?M.minPixelDragDistanceDrawing:8,this._coordinatePrecision="number"==typeof M.coordinatePrecision?M.coordinatePrecision:9}getButton(M){return-1===M.button?"neither":0===M.button?"left":1===M.button?"middle":2===M.button?"right":"neither"}getMapElementXYPosition(M){const et=this.getMapEventElement(),{left:Bt,top:Wt}=et.getBoundingClientRect();return{containerX:M.clientX-Bt,containerY:M.clientY-Wt}}getDrawEventFromEvent(M){const et=this.getLngLatFromEvent(M);if(!et)return null;const{lng:Bt,lat:Wt}=et,{containerX:Nt,containerY:$t}=this.getMapElementXYPosition(M),Gr=this.getButton(M),mn=Array.from(this._heldKeys);return{lng:e(Bt,this._coordinatePrecision),lat:e(Wt,this._coordinatePrecision),containerX:Nt,containerY:$t,button:Gr,heldKeys:mn}}register(M){this._currentModeCallbacks=M,this._listeners=this.getAdapterListeners(),this._listeners.forEach((M=>{M.register()}))}getCoordinatePrecision(){return this._coordinatePrecision}getAdapterListeners(){return[new o({name:"pointerdown",callback:M=>{if(!this._currentModeCallbacks)return;if(!M.isPrimary)return;const et=this.getDrawEventFromEvent(M);et&&(this._dragState="pre-dragging",this._lastDrawEvent=et)},register:M=>{this.getMapEventElement().addEventListener("pointerdown",M)},unregister:M=>{this.getMapEventElement().removeEventListener("pointerdown",M)}}),new o({name:"pointermove",callback:M=>{if(!this._currentModeCallbacks)return;if(!M.isPrimary)return;M.preventDefault();const et=this.getDrawEventFromEvent(M);if(et)if("not-dragging"===this._dragState)this._currentModeCallbacks.onMouseMove(et),this._lastDrawEvent=et;else if("pre-dragging"===this._dragState){if(!this._lastDrawEvent)return;const M={x:this._lastDrawEvent.containerX,y:this._lastDrawEvent.containerY},Bt={x:et.containerX,y:et.containerY},Wt=this._currentModeCallbacks.getState(),Nt=i(M,Bt);let $t=!1;if($t="drawing"===Wt?Nt{this.setDraggability.bind(this)(M)}))}else"dragging"===this._dragState&&this._currentModeCallbacks.onDrag(et,(M=>{this.setDraggability.bind(this)(M)}))},register:M=>{this.getMapEventElement().addEventListener("pointermove",M)},unregister:M=>{this.getMapEventElement().removeEventListener("pointermove",M)}}),new o({name:"contextmenu",callback:M=>{this._currentModeCallbacks&&M.preventDefault()},register:M=>{this.getMapEventElement().addEventListener("contextmenu",M)},unregister:M=>{this.getMapEventElement().removeEventListener("contextmenu",M)}}),new o({name:"pointerup",callback:M=>{if(!this._currentModeCallbacks)return;if(M.target!==this.getMapEventElement())return;if(!M.isPrimary)return;const et=this.getDrawEventFromEvent(M);et&&("dragging"===this._dragState?this._currentModeCallbacks.onDragEnd(et,(M=>{this.setDraggability.bind(this)(M)})):"not-dragging"!==this._dragState&&"pre-dragging"!==this._dragState||this._currentModeCallbacks.onClick(et),this._dragState="not-dragging",this.setDraggability(!0))},register:M=>{this.getMapEventElement().addEventListener("pointerup",M)},unregister:M=>{this.getMapEventElement().removeEventListener("pointerup",M)}}),new o({name:"keyup",callback:M=>{this._currentModeCallbacks&&(this._heldKeys.delete(M.key),this._currentModeCallbacks.onKeyUp({key:M.key,heldKeys:Array.from(this._heldKeys),preventDefault:()=>M.preventDefault()}))},register:M=>{this.getMapEventElement().addEventListener("keyup",M)},unregister:M=>{this.getMapEventElement().removeEventListener("keyup",M)}}),new o({name:"keydown",callback:M=>{this._currentModeCallbacks&&(this._heldKeys.add(M.key),this._currentModeCallbacks.onKeyDown({key:M.key,heldKeys:Array.from(this._heldKeys),preventDefault:()=>M.preventDefault()}))},register:M=>{this.getMapEventElement().addEventListener("keydown",M)},unregister:M=>{this.getMapEventElement().removeEventListener("keydown",M)}})]}unregister(){this._listeners.forEach((M=>{M.unregister()})),this.clear()}}class a extends s{constructor(M){super(M),this._nextRender=void 0,this._map=void 0,this._container=void 0,this._rendered=!1,this.changedIds={deletion:!1,points:!1,linestrings:!1,polygons:!1,styling:!1},this._map=M.map,this._container=this._map.getContainer()}clearLayers(){this._rendered&&(["point","linestring","polygon"].forEach((M=>{const et=`td-${M.toLowerCase()}`;this._map.removeLayer(et),"polygon"===M&&this._map.removeLayer(et+"-outline"),this._map.removeSource(et)})),this._rendered=!1,this._nextRender&&(cancelAnimationFrame(this._nextRender),this._nextRender=void 0))}_addGeoJSONSource(M,et){this._map.addSource(M,{type:"geojson",data:{type:"FeatureCollection",features:et},tolerance:0})}_addFillLayer(M){return this._map.addLayer({id:M,source:M,type:"fill",paint:{"fill-color":["get","polygonFillColor"],"fill-opacity":["get","polygonFillOpacity"]}})}_addFillOutlineLayer(M,et){const Bt=this._map.addLayer({id:M+"-outline",source:M,type:"line",paint:{"line-width":["get","polygonOutlineWidth"],"line-color":["get","polygonOutlineColor"]}});return et&&this._map.moveLayer(M,et),Bt}_addLineLayer(M,et){const Bt=this._map.addLayer({id:M,source:M,type:"line",paint:{"line-width":["get","lineStringWidth"],"line-color":["get","lineStringColor"]}});return et&&this._map.moveLayer(M,et),Bt}_addPointLayer(M,et){const Bt=this._map.addLayer({id:M,source:M,type:"circle",paint:{"circle-stroke-color":["get","pointOutlineColor"],"circle-stroke-width":["get","pointOutlineWidth"],"circle-radius":["get","pointWidth"],"circle-color":["get","pointColor"]}});return et&&this._map.moveLayer(M,et),Bt}_addLayer(M,et,Bt){"Point"===et&&this._addPointLayer(M,Bt),"LineString"===et&&this._addLineLayer(M,Bt),"Polygon"===et&&(this._addFillLayer(M),this._addFillOutlineLayer(M,Bt))}_addGeoJSONLayer(M,et){const Bt=`td-${M.toLowerCase()}`;return this._addGeoJSONSource(Bt,et),this._addLayer(Bt,M),Bt}_setGeoJSONLayerData(M,et){const Bt=`td-${M.toLowerCase()}`;return this._map.getSource(Bt).setData({type:"FeatureCollection",features:et}),Bt}getEmptyGeometries(){return{points:[],linestrings:[],polygons:[]}}updateChangedIds(M){[...M.updated,...M.created].forEach((M=>{"Point"===M.geometry.type?this.changedIds.points=!0:"LineString"===M.geometry.type?this.changedIds.linestrings=!0:"Polygon"===M.geometry.type&&(this.changedIds.polygons=!0)})),M.deletedIds.length>0&&(this.changedIds.deletion=!0),0===M.created.length&&0===M.updated.length&&0===M.deletedIds.length&&(this.changedIds.styling=!0)}getLngLatFromEvent(M){const{left:et,top:Bt}=this._container.getBoundingClientRect();return this.unproject(M.clientX-et,M.clientY-Bt)}getMapEventElement(){return this._map.getCanvas()}setDraggability(M){M?(this._map.dragRotate.enable(),this._map.dragPan.enable()):(this._map.dragRotate.disable(),this._map.dragPan.disable())}project(M,et){const{x:Bt,y:Wt}=this._map.project({lng:M,lat:et});return{x:Bt,y:Wt}}unproject(M,et){const{lng:Bt,lat:Wt}=this._map.unproject({x:M,y:et});return{lng:Bt,lat:Wt}}setCursor(M){const et=this._map.getCanvas();"unset"===M?et.style.removeProperty("cursor"):et.style.cursor=M}setDoubleClickToZoom(M){M?this._map.doubleClickZoom.enable():this._map.doubleClickZoom.disable()}render(M,et){this.updateChangedIds(M),this._nextRender&&cancelAnimationFrame(this._nextRender),this._nextRender=requestAnimationFrame((()=>{const Bt=[...M.created,...M.updated,...M.unchanged],Wt=this.getEmptyGeometries();for(let M=0;M{const{properties:Bt}=Nt;if(Bt.mode!==M)return;const $t=et[M](Nt);"Point"===Nt.geometry.type?(Bt.pointColor=$t.pointColor,Bt.pointOutlineColor=$t.pointOutlineColor,Bt.pointOutlineWidth=$t.pointOutlineWidth,Bt.pointWidth=$t.pointWidth,Wt.points.push(Nt)):"LineString"===Nt.geometry.type?(Bt.lineStringColor=$t.lineStringColor,Bt.lineStringWidth=$t.lineStringWidth,Wt.linestrings.push(Nt)):"Polygon"===Nt.geometry.type&&(Bt.polygonFillColor=$t.polygonFillColor,Bt.polygonFillOpacity=$t.polygonFillOpacity,Bt.polygonOutlineColor=$t.polygonOutlineColor,Bt.polygonOutlineWidth=$t.polygonOutlineWidth,Wt.polygons.push(Nt))}))}const{points:Nt,linestrings:$t,polygons:Gr}=Wt;if(this._rendered){const M=this.changedIds.deletion||this.changedIds.styling,et=M||this.changedIds.linestrings,Bt=M||this.changedIds.polygons;let Wt;(M||this.changedIds.points)&&(Wt=this._setGeoJSONLayerData("Point",Nt)),et&&this._setGeoJSONLayerData("LineString",$t),Bt&&this._setGeoJSONLayerData("Polygon",Gr),Wt&&this._map.moveLayer(Wt)}else{const M=this._addGeoJSONLayer("Point",Nt);this._addGeoJSONLayer("LineString",$t),this._addGeoJSONLayer("Polygon",Gr),this._rendered=!0,M&&this._map.moveLayer(M)}this.changedIds={points:!1,linestrings:!1,polygons:!1,deletion:!1,styling:!1}}))}clear(){this._currentModeCallbacks&&(this._currentModeCallbacks.onClear(),this.clearLayers())}getCoordinatePrecision(){return super.getCoordinatePrecision()}unregister(){return super.unregister()}register(M){super.register(M),this._currentModeCallbacks&&this._currentModeCallbacks.onReady&&this._currentModeCallbacks.onReady()}}class l extends s{constructor(M){super(M),this.mapboxglAdapter=void 0,this.mapboxglAdapter=new a(M)}register(M){this.mapboxglAdapter.register(M)}unregister(){this.mapboxglAdapter.unregister()}getCoordinatePrecision(){return this.mapboxglAdapter.getCoordinatePrecision()}getLngLatFromEvent(M){return this.mapboxglAdapter.getLngLatFromEvent(M)}getMapEventElement(){return this.mapboxglAdapter.getMapEventElement()}setDraggability(M){this.mapboxglAdapter.setDraggability(M)}project(M,et){return this.mapboxglAdapter.project(M,et)}unproject(M,et){return this.mapboxglAdapter.unproject(M,et)}setCursor(M){this.mapboxglAdapter.setCursor(M)}setDoubleClickToZoom(M){this.mapboxglAdapter.setDoubleClickToZoom(M)}render(M,et){this.mapboxglAdapter.render(M,et)}clear(){this.mapboxglAdapter.clear()}}let et=0;const Bt="undefined"!=typeof navigator&&void 0!==navigator.userAgent?navigator.userAgent.toLowerCase():"";Bt.includes("firefox"),Bt.includes("safari")&&!Bt.includes("chrom")&&(Bt.includes("version/15.4")||/cpu (os|iphone os) 15_4 like mac os x/.test(Bt)),Bt.includes("webkit")&&Bt.includes("edge"),Bt.includes("macintosh"),"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof OffscreenCanvas&&(self,WorkerGlobalScope),function(){let M=!1;try{const et=Object.defineProperty({},"passive",{get:function(){M=!0}});window.addEventListener("_",null,et),window.removeEventListener("_",null,et)}catch(M){}}();var Wt=class{constructor(){this.disposed=!1}dispose(){this.disposed||(this.disposed=!0,this.disposeInternal())}disposeInternal(){}},Nt=class{constructor(M){this.type=M,this.target=null}preventDefault(){this.defaultPrevented=!0}stopPropagation(){this.propagationStopped=!0}};function W(){}function j(M){for(const et in M)delete M[et]}var $t=class extends Wt{constructor(M){super(),this.eventTarget_=M,this.pendingRemovals_=null,this.dispatching_=null,this.listeners_=null}addEventListener(M,et){if(!M||!et)return;const Bt=this.listeners_||(this.listeners_={}),Wt=Bt[M]||(Bt[M]=[]);Wt.includes(et)||Wt.push(et)}dispatchEvent(M){const et="string"==typeof M,Bt=et?M:M.type,Wt=this.listeners_&&this.listeners_[Bt];if(!Wt)return;const $t=et?new Nt(M):M;$t.target||($t.target=this.eventTarget_||this);const Gr=this.dispatching_||(this.dispatching_={}),mn=this.pendingRemovals_||(this.pendingRemovals_={});let Hn;Bt in Gr||(Gr[Bt]=0,mn[Bt]=0),++Gr[Bt];for(let M=0,et=Wt.length;M0)}removeEventListener(M,et){if(!this.listeners_)return;const Bt=this.listeners_[M];if(!Bt)return;const Wt=Bt.indexOf(et);-1!==Wt&&(this.pendingRemovals_&&M in this.pendingRemovals_?(Bt[Wt]=W,++this.pendingRemovals_[M]):(Bt.splice(Wt,1),0===Bt.length&&delete this.listeners_[M]))}};function N(M,et,Bt,Wt,Nt){if(Nt){const Wt=Bt;Bt=function(){M.removeEventListener(et,Bt),Wt.apply(this,arguments)}}const $t={target:M,type:et,listener:Bt};return M.addEventListener(et,Bt),$t}function A(M,et,Bt,Wt){return N(M,et,Bt,0,!0)}function R(M){M&&M.target&&(M.target.removeEventListener(M.type,M.listener),j(M))}var Gr=class extends $t{constructor(){super(),this.on=this.onInternal,this.once=this.onceInternal,this.un=this.unInternal,this.revision_=0}changed(){++this.revision_,this.dispatchEvent("change")}getRevision(){return this.revision_}onInternal(M,et){if(Array.isArray(M)){const Bt=M.length,Wt=new Array(Bt);for(let Nt=0;Nt1?Bt:2,void 0===et&&(et=Bt>2?M.slice():new Array(Wt));for(let Nt=0;NtTo?Bt=To:Bt<-To&&(Bt=-To),et[Nt+1]=Bt}return et},Ea=function(M,et,Bt){const Wt=M.length;Bt=Bt>1?Bt:2,void 0===et&&(et=Bt>2?M.slice():new Array(Wt));for(let Nt=0;NtM*Math.PI/180,Bt=i(M[1]),Wt=i(M[0]),Nt=i(et[1]),$t=Nt-Bt,Gr=i(et[0])-Wt,mn=Math.sin($t/2)*Math.sin($t/2)+Math.cos(Bt)*Math.cos(Nt)*Math.sin(Gr/2)*Math.sin(Gr/2);return 2*Math.atan2(Math.sqrt(mn),Math.sqrt(1-mn))*6371e3/1e3}const Al=6371008.8;function Ht(M){return M%360*Math.PI/180}function Kt(M){return M/(Al/1e3)}function Jt(M){return M%(2*Math.PI)*180/Math.PI}const Sl=57.29577951308232,Zl=.017453292519943295,Gl=6378137,Qt=(M,et)=>({x:0===M?0:M*Zl*Gl,y:0===et?0:Math.log(Math.tan(Math.PI/4+et*Zl/2))*Gl}),te=(M,et)=>({lng:0===M?0:Sl*(M/Gl),lat:0===et?0:(2*Math.atan(Math.exp(et/Gl))-Math.PI/2)*Sl});function ee(M,et,Bt){const Wt=Ht(M[0]),Nt=Ht(M[1]),$t=Ht(Bt),Gr=Kt(et),mn=Math.asin(Math.sin(Nt)*Math.cos(Gr)+Math.cos(Nt)*Math.sin(Gr)*Math.cos($t));return[Jt(Wt+Math.atan2(Math.sin($t)*Math.sin(Gr)*Math.cos(Nt),Math.cos(Gr)-Math.sin(Nt)*Math.sin(mn))),Jt(mn)]}function ie(M){const{center:et,radiusKilometers:Bt,coordinatePrecision:Wt}=M,Nt=M.steps?M.steps:64,$t=[];for(let M=0;M0;function s(M){return M<0-et||M>1+et}function r(M,et,Nt,$t){const Gr=Bt[M][et],mn=Bt[M][et+1],Hn=Bt[Nt][$t],so=Bt[Nt][$t+1],uo=function(M,et,Bt,Wt){if(se(M,Bt)||se(M,Wt)||se(et,Bt)||se(Wt,Bt))return null;const Nt=M[0],$t=M[1],Gr=et[0],mn=et[1],Hn=Bt[0],so=Bt[1],uo=Wt[0],Io=Wt[1],Po=(Nt-Gr)*(so-Io)-($t-mn)*(Hn-uo);return 0===Po?null:[((Nt*mn-$t*Gr)*(Hn-uo)-(Nt-Gr)*(Hn*Io-so*uo))/Po,((Nt*mn-$t*Gr)*(so-Io)-($t-mn)*(Hn*Io-so*uo))/Po]}(Gr,mn,Hn,so);if(null===uo)return;let Io,Po;Io=mn[0]!==Gr[0]?(uo[0]-Gr[0])/(mn[0]-Gr[0]):(uo[1]-Gr[1])/(mn[1]-Gr[1]),Po=so[0]!==Hn[0]?(uo[0]-Hn[0])/(so[0]-Hn[0]):(uo[1]-Hn[1])/(so[1]-Hn[1]),s(Io)||s(Po)||(uo.toString(),Wt.push(uo))}}function se(M,et){return M[0]===et[0]&&M[1]===et[1]}function re(M,et){return 2===M.length&&"number"==typeof M[0]&&"number"==typeof M[1]&&1/0!==M[0]&&1/0!==M[1]&&(Wt=M[0])>=-180&&Wt<=180&&(Bt=M[1])>=-90&&Bt<=90&&ne(M[0])<=et&&ne(M[1])<=et;var Bt,Wt}function ne(M){let et=1,Bt=0;for(;Math.round(M*et)/et!==M;)et*=10,Bt++;return Bt}function ae(M,et){return"Polygon"===M.geometry.type&&1===M.geometry.coordinates.length&&M.geometry.coordinates[0].length>=4&&M.geometry.coordinates[0].every((M=>re(M,et)))&&(Bt=M.geometry.coordinates[0][0])[0]===(Wt=M.geometry.coordinates[0][M.geometry.coordinates[0].length-1])[0]&&Bt[1]===Wt[1];var Bt,Wt}function le(M,et){return ae(M,et)&&!oe(M)}class he extends Tt{constructor(M){var et;super(M),this.mode="circle",this.center=void 0,this.clickCount=0,this.currentCircleId=void 0,this.keyEvents=void 0,this.cursors=void 0,this.startingRadiusKilometers=1e-5;const Bt={start:"crosshair"};if(this.cursors=M&&M.cursors?t({},Bt,M.cursors):Bt,null===(null==M?void 0:M.keyEvents))this.keyEvents={cancel:null,finish:null};else{const et={cancel:"Escape",finish:"Enter"};this.keyEvents=M&&M.keyEvents?t({},et,M.keyEvents):et}this.startingRadiusKilometers=null!=(et=null==M?void 0:M.startingRadiusKilometers)?et:1e-5,this.validate=null==M?void 0:M.validation}close(){if(void 0===this.currentCircleId)return;const M=this.currentCircleId;if(this.validate&&M){const et=this.store.getGeometryCopy(M);if(!this.validate({type:"Feature",id:M,geometry:et,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:La.Finish}))return}this.center=void 0,this.currentCircleId=void 0,this.clickCount=0,"drawing"===this.state&&this.setStarted(),this.onFinish(M,{mode:this.mode,action:"draw"})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onClick(M){if(0===this.clickCount){this.center=[M.lng,M.lat];const et=ie({center:this.center,radiusKilometers:this.startingRadiusKilometers,coordinatePrecision:this.coordinatePrecision}),[Bt]=this.store.create([{geometry:et.geometry,properties:{mode:this.mode,radiusKilometers:this.startingRadiusKilometers}}]);this.currentCircleId=Bt,this.clickCount++,this.setDrawing()}else 1===this.clickCount&&this.center&&void 0!==this.currentCircleId&&this.updateCircle(M),this.close()}onMouseMove(M){this.updateCircle(M)}onKeyDown(){}onKeyUp(M){M.key===this.keyEvents.cancel?this.cleanUp():M.key===this.keyEvents.finish&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const M=this.currentCircleId;this.center=void 0,this.currentCircleId=void 0,this.clickCount=0,"drawing"===this.state&&this.setStarted();try{void 0!==M&&this.store.delete([M])}catch(M){}}styleFeature(M){const et=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});return"Feature"===M.type&&"Polygon"===M.geometry.type&&M.properties.mode===this.mode?(et.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,et.polygonFillColor,M),et.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,et.polygonOutlineColor,M),et.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,et.polygonOutlineWidth,M),et.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,et.polygonFillOpacity,M),et.zIndex=10,et):et}validateFeature(M){return!!super.validateFeature(M)&&M.properties.mode===this.mode&&le(M,this.coordinatePrecision)}updateCircle(M){if(1===this.clickCount&&this.center&&this.currentCircleId){const et=Ut(this.center,[M.lng,M.lat]);let Bt;if("web-mercator"===this.projection){const Wt=function(M,et){const Bt=1e3*Ut(M,et);if(0===Bt)return 1;const{x:Wt,y:Nt}=Qt(M[0],M[1]),{x:$t,y:Gr}=Qt(et[0],et[1]);return Math.sqrt(Math.pow($t-Wt,2)+Math.pow(Gr-Nt,2))/Bt}(this.center,[M.lng,M.lat]);Bt=function(M){const{center:et,radiusKilometers:Bt,coordinatePrecision:Wt}=M,Nt=M.steps?M.steps:64,$t=1e3*Bt,[Gr,mn]=et,{x:Hn,y:so}=Qt(Gr,mn),uo=[];for(let M=0;M[M.lng,M.lat]))]}}}class ge extends de{constructor(M){super(M)}create(M){const{containerX:et,containerY:Bt}=M;return ue({unproject:this.unproject,point:{x:et,y:Bt},pointerDistance:this.pointerDistance})}}class pe extends de{constructor(M){super(M)}measure(M,et){const{x:Bt,y:Wt}=this.project(et[0],et[1]);return i({x:Bt,y:Wt},{x:M.containerX,y:M.containerY})}}class ye extends de{constructor(M,et,Bt){super(M),this.config=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.getSnappableCoordinateFirstClick=M=>this.getSnappable(M,(M=>Boolean(M.properties&&M.properties.mode===this.mode))),this.getSnappableCoordinate=(M,et)=>this.getSnappable(M,(M=>Boolean(M.properties&&M.properties.mode===this.mode&&M.id!==et))),this.config=M,this.pixelDistance=et,this.clickBoundingBox=Bt}getSnappable(M,et){const Bt=this.clickBoundingBox.create(M),Wt=this.store.search(Bt,et),Nt={coord:void 0,minDist:1/0};return Wt.forEach((et=>{let Bt;if("Polygon"===et.geometry.type)Bt=et.geometry.coordinates[0];else{if("LineString"!==et.geometry.type)return;Bt=et.geometry.coordinates}Bt.forEach((et=>{const Bt=this.pixelDistance.measure(M,et);Bt=Hn&&Nt===M.length-1);Nt++){if(Hn>et&&0===Wt.length){if($t=et-Hn,!$t)return Wt.push(M[Nt]),Wt;Gr=ve(M[Nt],M[Nt-1])-180,mn=me(M[Nt],$t,Gr),Wt.push(mn)}if(Hn>=Bt)return $t=Bt-Hn,$t?(Gr=ve(M[Nt],M[Nt-1])-180,mn=me(M[Nt],$t,Gr),Wt.push(mn),Wt):(Wt.push(M[Nt]),Wt);if(Hn>=et&&Wt.push(M[Nt]),Nt===M.length-1)return Wt;Hn+=Ut(M[Nt],M[Nt+1])}if(Hn[e(M[0],this.config.coordinatePrecision),e(M[1],this.config.coordinatePrecision)]))}}function we(M,et){return M[0]===et[0]&&M[1]===et[1]}class Se extends Tt{constructor(M){super(M),this.mode="linestring",this.currentCoordinate=0,this.currentId=void 0,this.closingPointId=void 0,this.keyEvents=void 0,this.snappingEnabled=void 0,this.cursors=void 0,this.mouseMove=!1,this.insertCoordinates=void 0,this.lastCommitedCoordinates=void 0,this.snapping=void 0,this.insertPoint=void 0;const et={start:"crosshair",close:"pointer"};if(this.cursors=M&&M.cursors?t({},et,M.cursors):et,this.snappingEnabled=!(!M||void 0===M.snapping)&&M.snapping,null===(null==M?void 0:M.keyEvents))this.keyEvents={cancel:null,finish:null};else{const et={cancel:"Escape",finish:"Enter"};this.keyEvents=M&&M.keyEvents?t({},et,M.keyEvents):et}this.validate=null==M?void 0:M.validation,this.insertCoordinates=null==M?void 0:M.insertCoordinates}close(){if(void 0===this.currentId)return;const M=this.store.getGeometryCopy(this.currentId);M.coordinates.pop(),this.updateGeometries([...M.coordinates],void 0,La.Commit);const et=this.currentId;this.closingPointId&&this.store.delete([this.closingPointId]),this.currentCoordinate=0,this.currentId=void 0,this.closingPointId=void 0,this.lastCommitedCoordinates=void 0,"drawing"===this.state&&this.setStarted(),this.onFinish(et,{mode:this.mode,action:"draw"})}updateGeometries(M,et,Bt){if(!this.currentId)return;const Wt={type:"LineString",coordinates:M};if(this.validate&&!this.validate({type:"Feature",geometry:Wt},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:Bt}))return;const Nt=[{id:this.currentId,geometry:Wt}];this.closingPointId&&et&&Nt.push({id:this.closingPointId,geometry:{type:"Point",coordinates:et}}),"commit"===Bt&&(this.lastCommitedCoordinates=Wt.coordinates),this.store.updateGeometry(Nt)}generateInsertCoordinates(M,et){if(!this.insertCoordinates||!this.lastCommitedCoordinates)throw new Error("Not able to insert coordinates");if("amount"!==this.insertCoordinates.strategy)throw new Error("Strategy does not exist");const Bt=Ut(M,et)/(this.insertCoordinates.value+1);let Wt=[];return"globe"===this.projection?Wt=this.insertPoint.generateInsertionGeodesicCoordinates(M,et,Bt):"web-mercator"===this.projection&&(Wt=this.insertPoint.generateInsertionCoordinates(M,et,Bt)),Wt}createLine(M){const[et]=this.store.create([{geometry:{type:"LineString",coordinates:[M,M]},properties:{mode:this.mode}}]);this.lastCommitedCoordinates=[M,M],this.currentId=et,this.currentCoordinate++,this.setDrawing()}firstUpdateToLine(M){if(!this.currentId)return;const et=this.store.getGeometryCopy(this.currentId).coordinates,[Bt]=this.store.create([{geometry:{type:"Point",coordinates:[...M]},properties:{mode:this.mode}}]);this.closingPointId=Bt,this.setCursor(this.cursors.close);const Wt=[...et,M];this.updateGeometries(Wt,void 0,La.Commit),this.currentCoordinate++}updateToLine(M,et){if(!this.currentId)return;const Bt=this.store.getGeometryCopy(this.currentId).coordinates,[Wt,Nt]=this.lastCommitedCoordinates?this.lastCommitedCoordinates[this.lastCommitedCoordinates.length-1]:Bt[Bt.length-2],{x:$t,y:Gr}=this.project(Wt,Nt);if(i({x:$t,y:Gr},{x:et.x,y:et.y})0&&!this.mouseMove&&this.onMouseMove(M),this.mouseMove=!1;const et=this.currentId&&this.snappingEnabled&&this.snapping.getSnappableCoordinate(M,this.currentId)||[M.lng,M.lat];0===this.currentCoordinate?this.createLine(et):1===this.currentCoordinate&&this.currentId?this.firstUpdateToLine(et):this.currentId&&this.updateToLine(et,{x:M.containerX,y:M.containerY})}onKeyDown(){}onKeyUp(M){M.key===this.keyEvents.cancel&&this.cleanUp(),M.key===this.keyEvents.finish&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const M=this.currentId;this.closingPointId=void 0,this.currentId=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted();try{void 0!==M&&this.store.delete([M]),void 0!==this.closingPointId&&this.store.delete([this.closingPointId])}catch(M){}}styleFeature(M){const et=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});return"Feature"===M.type&&"LineString"===M.geometry.type&&M.properties.mode===this.mode?(et.lineStringColor=this.getHexColorStylingValue(this.styles.lineStringColor,et.lineStringColor,M),et.lineStringWidth=this.getNumericStylingValue(this.styles.lineStringWidth,et.lineStringWidth,M),et.zIndex=10,et):"Feature"===M.type&&"Point"===M.geometry.type&&M.properties.mode===this.mode?(et.pointColor=this.getHexColorStylingValue(this.styles.closingPointColor,et.pointColor,M),et.pointWidth=this.getNumericStylingValue(this.styles.closingPointWidth,et.pointWidth,M),et.pointOutlineColor=this.getHexColorStylingValue(this.styles.closingPointOutlineColor,"#ffffff",M),et.pointOutlineWidth=this.getNumericStylingValue(this.styles.closingPointOutlineWidth,2,M),et.zIndex=40,et):et}validateFeature(M){return!!super.validateFeature(M)&&"LineString"===M.geometry.type&&M.properties.mode===this.mode&&M.geometry.coordinates.length>=2}}function be(M,et){return"Point"===M.geometry.type&&re(M.geometry.coordinates,et)}class Ee extends Tt{constructor(M){super(M),this.mode="point",this.cursors=void 0;const et={create:"crosshair"};this.cursors=M&&M.cursors?t({},et,M.cursors):et}start(){this.setStarted(),this.setCursor(this.cursors.create)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onClick(M){if(!this.store)throw new Error("Mode must be registered first");const et={type:"Point",coordinates:[M.lng,M.lat]},Bt={mode:this.mode};if(this.validate&&!this.validate({type:"Feature",geometry:et,properties:Bt},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:La.Finish}))return;const[Wt]=this.store.create([{geometry:et,properties:Bt}]);this.onFinish(Wt,{mode:this.mode,action:"draw"})}onMouseMove(){}onKeyDown(){}onKeyUp(){}cleanUp(){}onDragStart(){}onDrag(){}onDragEnd(){}styleFeature(M){const et=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});return"Feature"===M.type&&"Point"===M.geometry.type&&M.properties.mode===this.mode&&(et.pointWidth=this.getNumericStylingValue(this.styles.pointWidth,et.pointWidth,M),et.pointColor=this.getHexColorStylingValue(this.styles.pointColor,et.pointColor,M),et.pointOutlineColor=this.getHexColorStylingValue(this.styles.pointOutlineColor,et.pointOutlineColor,M),et.pointOutlineWidth=this.getNumericStylingValue(this.styles.pointOutlineWidth,2,M),et.zIndex=30),et}validateFeature(M){return!!super.validateFeature(M)&&M.properties.mode===this.mode&&be(M,this.coordinatePrecision)}}class Ie extends de{constructor(M,et){super(M),this.config=void 0,this.pixelDistance=void 0,this._startEndPoints=[],this.config=M,this.pixelDistance=et}get ids(){return this._startEndPoints.concat()}set ids(M){}create(M,et){if(this.ids.length)throw new Error("Opening and closing points already created");if(M.length<=3)throw new Error("Requires at least 4 coordinates");this._startEndPoints=this.store.create([{geometry:{type:"Point",coordinates:M[0]},properties:{mode:et,[Oa]:!0}},{geometry:{type:"Point",coordinates:M[M.length-2]},properties:{mode:et,[Oa]:!0}}])}delete(){this.ids.length&&(this.store.delete(this.ids),this._startEndPoints=[])}update(M){if(2!==this.ids.length)throw new Error("No closing points to update");this.store.updateGeometry([{id:this.ids[0],geometry:{type:"Point",coordinates:M[0]}},{id:this.ids[1],geometry:{type:"Point",coordinates:M[M.length-3]}}])}isClosingPoint(M){const et=this.store.getGeometryCopy(this.ids[0]),Bt=this.store.getGeometryCopy(this.ids[1]),Wt=this.pixelDistance.measure(M,et.coordinates),Nt=this.pixelDistance.measure(M,Bt.coordinates);return{isClosing:Wt0&&!this.mouseMove&&this.onMouseMove(M),this.mouseMove=!1,0===this.currentCoordinate){const et=this.snappingEnabled?this.snapping.getSnappableCoordinateFirstClick(M):void 0;et&&(M.lng=et[0],M.lat=et[1]);const[Bt]=this.store.create([{geometry:{type:"Polygon",coordinates:[[[M.lng,M.lat],[M.lng,M.lat],[M.lng,M.lat],[M.lng,M.lat]]]},properties:{mode:this.mode}}]);this.currentId=Bt,this.currentCoordinate++,this.setDrawing()}else if(1===this.currentCoordinate&&this.currentId){const et=this.snappingEnabled?this.snapping.getSnappableCoordinate(M,this.currentId):void 0;et&&(M.lng=et[0],M.lat=et[1]);const Bt=this.store.getGeometryCopy(this.currentId);if(we([M.lng,M.lat],Bt.coordinates[0][0]))return;if(!this.updatePolygonGeometry([Bt.coordinates[0][0],[M.lng,M.lat],[M.lng,M.lat],Bt.coordinates[0][0]],La.Commit))return;this.currentCoordinate++}else if(2===this.currentCoordinate&&this.currentId){const et=this.snappingEnabled?this.snapping.getSnappableCoordinate(M,this.currentId):void 0;et&&(M.lng=et[0],M.lat=et[1]);const Bt=this.store.getGeometryCopy(this.currentId).coordinates[0];if(we([M.lng,M.lat],Bt[1]))return;if(!this.updatePolygonGeometry([Bt[0],Bt[1],[M.lng,M.lat],[M.lng,M.lat],Bt[0]],La.Commit))return;2===this.currentCoordinate&&this.closingPoints.create(Bt,"polygon"),this.currentCoordinate++}else if(this.currentId){const et=this.snappingEnabled?this.snapping.getSnappableCoordinate(M,this.currentId):void 0,Bt=this.store.getGeometryCopy(this.currentId).coordinates[0],{isClosing:Wt,isPreviousClosing:Nt}=this.closingPoints.isClosingPoint(M);if(Nt||Wt)this.close();else{if(et&&(M.lng=et[0],M.lat=et[1]),we([M.lng,M.lat],Bt[this.currentCoordinate-1]))return;const Wt=function(M=[[[0,0],[0,1],[1,1],[1,0],[0,0]]]){return{type:"Feature",geometry:{type:"Polygon",coordinates:M},properties:{}}}([[...Bt.slice(0,-1),[M.lng,M.lat],Bt[0]]]);if(!this.updatePolygonGeometry(Wt.geometry.coordinates[0],La.Commit))return;this.currentCoordinate++,this.closingPoints.ids.length&&this.closingPoints.update(Wt.geometry.coordinates[0])}}}onKeyUp(M){M.key===this.keyEvents.cancel?this.cleanUp():M.key===this.keyEvents.finish&&this.close()}onKeyDown(){}onDragStart(){this.setCursor("unset")}onDrag(){}onDragEnd(){this.setCursor(this.cursors.start)}cleanUp(){const M=this.currentId;this.currentId=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted();try{void 0!==M&&this.store.delete([M]),this.closingPoints.ids.length&&this.closingPoints.delete()}catch(M){}}styleFeature(M){const et=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});if(M.properties.mode===this.mode){if("Polygon"===M.geometry.type)return et.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,et.polygonFillColor,M),et.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,et.polygonOutlineColor,M),et.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,et.polygonOutlineWidth,M),et.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,et.polygonFillOpacity,M),et.zIndex=10,et;if("Point"===M.geometry.type)return et.pointWidth=this.getNumericStylingValue(this.styles.closingPointWidth,et.pointWidth,M),et.pointColor=this.getHexColorStylingValue(this.styles.closingPointColor,et.pointColor,M),et.pointOutlineColor=this.getHexColorStylingValue(this.styles.closingPointOutlineColor,et.pointOutlineColor,M),et.pointOutlineWidth=this.getNumericStylingValue(this.styles.closingPointOutlineWidth,2,M),et.zIndex=30,et}return et}validateFeature(M){return!!super.validateFeature(M)&&M.properties.mode===this.mode&&ae(M,this.coordinatePrecision)}}class ke extends Tt{constructor(M){super(M),this.mode="rectangle",this.center=void 0,this.clickCount=0,this.currentRectangleId=void 0,this.keyEvents=void 0,this.cursors=void 0;const et={start:"crosshair"};if(this.cursors=M&&M.cursors?t({},et,M.cursors):et,null===(null==M?void 0:M.keyEvents))this.keyEvents={cancel:null,finish:null};else{const et={cancel:"Escape",finish:"Enter"};this.keyEvents=M&&M.keyEvents?t({},et,M.keyEvents):et}}updateRectangle(M,et){if(1===this.clickCount&&this.center&&this.currentRectangleId){const Bt=this.store.getGeometryCopy(this.currentRectangleId).coordinates[0][0],Wt={type:"Polygon",coordinates:[[Bt,[M.lng,Bt[1]],[M.lng,M.lat],[Bt[0],M.lat],Bt]]};if(this.validate&&!this.validate({id:this.currentRectangleId,geometry:Wt},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:et}))return;this.store.updateGeometry([{id:this.currentRectangleId,geometry:Wt}])}}close(){const M=this.currentRectangleId;this.center=void 0,this.currentRectangleId=void 0,this.clickCount=0,"drawing"===this.state&&this.setStarted(),M&&this.onFinish(M,{mode:this.mode,action:"draw"})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onClick(M){if(0===this.clickCount){this.center=[M.lng,M.lat];const[et]=this.store.create([{geometry:{type:"Polygon",coordinates:[[[M.lng,M.lat],[M.lng,M.lat],[M.lng,M.lat],[M.lng,M.lat]]]},properties:{mode:this.mode}}]);this.currentRectangleId=et,this.clickCount++,this.setDrawing()}else this.updateRectangle(M,La.Finish),this.close()}onMouseMove(M){this.updateRectangle(M,La.Provisional)}onKeyDown(){}onKeyUp(M){M.key===this.keyEvents.cancel?this.cleanUp():M.key===this.keyEvents.finish&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const M=this.currentRectangleId;this.center=void 0,this.currentRectangleId=void 0,this.clickCount=0,"drawing"===this.state&&this.setStarted(),void 0!==M&&this.store.delete([M])}styleFeature(M){const et=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});return"Feature"===M.type&&"Polygon"===M.geometry.type&&M.properties.mode===this.mode?(et.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,et.polygonFillColor,M),et.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,et.polygonOutlineColor,M),et.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,et.polygonOutlineWidth,M),et.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,et.polygonFillOpacity,M),et.zIndex=10,et):et}validateFeature(M){return!!super.validateFeature(M)&&M.properties.mode===this.mode&&le(M,this.coordinatePrecision)}}class Fe extends Tt{constructor(M){super({styles:M.styles}),this.type=$a.Render,this.mode="render",this.mode=M.modeName}registerBehaviors(M){this.mode=M.mode}start(){this.setStarted()}stop(){this.setStopped()}onKeyUp(){}onKeyDown(){}onClick(){}onDragStart(){}onDrag(){}onDragEnd(){}onMouseMove(){}cleanUp(){}styleFeature(M){return{pointColor:this.getHexColorStylingValue(this.styles.pointColor,"#3f97e0",M),pointWidth:this.getNumericStylingValue(this.styles.pointWidth,6,M),pointOutlineColor:this.getHexColorStylingValue(this.styles.pointOutlineColor,"#ffffff",M),pointOutlineWidth:this.getNumericStylingValue(this.styles.pointOutlineWidth,0,M),polygonFillColor:this.getHexColorStylingValue(this.styles.polygonFillColor,"#3f97e0",M),polygonFillOpacity:this.getNumericStylingValue(this.styles.polygonFillOpacity,.3,M),polygonOutlineColor:this.getHexColorStylingValue(this.styles.polygonOutlineColor,"#3f97e0",M),polygonOutlineWidth:this.getNumericStylingValue(this.styles.polygonOutlineWidth,4,M),lineStringWidth:this.getNumericStylingValue(this.styles.lineStringWidth,4,M),lineStringColor:this.getHexColorStylingValue(this.styles.lineStringColor,"#3f97e0",M),zIndex:this.getNumericStylingValue(this.styles.zIndex,0,M)}}validateFeature(M){return super.validateFeature(M)&&(be(M,this.coordinatePrecision)||ae(M,this.coordinatePrecision)||function(M,et){return"LineString"===M.geometry.type&&M.geometry.coordinates.length>=2&&M.geometry.coordinates.every((M=>re(M,et)))}(M,this.coordinatePrecision))}}function Oe(M,et){const Bt=M,Wt=et,Nt=Ht(Bt[1]),$t=Ht(Wt[1]);let Gr=Ht(Wt[0]-Bt[0]);Gr>Math.PI&&(Gr-=2*Math.PI),Gr<-Math.PI&&(Gr+=2*Math.PI);const mn=Math.log(Math.tan($t/2+Math.PI/4)/Math.tan(Nt/2+Math.PI/4)),Hn=(Jt(Math.atan2(Gr,mn))+360)%360;return Hn>180?-(360-Hn):Hn}function Le(M,et,Bt){let Wt=et;et<0&&(Wt=-Math.abs(Wt));const Nt=Wt/Al,$t=M[0]*Math.PI/180,Gr=Ht(M[1]),mn=Ht(Bt),Hn=Nt*Math.cos(mn);let so=Gr+Hn;Math.abs(so)>Math.PI/2&&(so=so>0?Math.PI-so:-Math.PI-so);const uo=Math.log(Math.tan(so/2+Math.PI/4)/Math.tan(Gr/2+Math.PI/4)),Io=Math.abs(uo)>1e-11?Hn/uo:Math.cos(Gr),Po=[(180*($t+Nt*Math.sin(mn)/Io)/Math.PI+540)%360-180,180*so/Math.PI];return Po[0]+=Po[0]-M[0]>180?-360:M[0]-Po[0]>180?360:0,Po}function We(M,et,Bt,Wt,Nt){const $t=Wt(M[0],M[1]),Gr=Wt(et[0],et[1]),{lng:mn,lat:Hn}=Nt(($t.x+Gr.x)/2,($t.y+Gr.y)/2);return[e(mn,Bt),e(Hn,Bt)]}function je(M,et,Bt){const Wt=Le(M,1e3*Ut(M,et)/2,Oe(M,et));return[e(Wt[0],Bt),e(Wt[1],Bt)]}function Be({featureCoords:M,precision:et,unproject:Bt,project:Wt,projection:Nt}){const $t=[];for(let Gr=0;Gr({geometry:{type:"Point",coordinates:M},properties:et(Bt)})))}(M,(M=>({mode:this.mode,[Ka]:!0,midPointSegment:M,midPointFeatureId:et})),Bt,this.config.project,this.config.unproject,this.projection))}delete(){this._midPoints.length&&(this.store.delete(this._midPoints),this._midPoints=[])}getUpdated(M){if(0!==this._midPoints.length)return Be({featureCoords:M,precision:this.coordinatePrecision,project:this.config.project,unproject:this.config.unproject,projection:this.config.projection}).map(((M,et)=>({id:this._midPoints[et],geometry:{type:"Point",coordinates:M}})))}}class Ne extends de{constructor(M){super(M),this._selectionPoints=[]}get ids(){return this._selectionPoints.concat()}set ids(M){}create(M,et,Bt){this._selectionPoints=this.store.create(function(M,et,Bt){const Wt=[],Nt="Polygon"===et?M.length-1:M.length;for(let et=0;et({mode:this.mode,selectionPoint:!0,selectionPointFeatureId:Bt,index:M}))))}delete(){this.ids.length&&(this.store.delete(this.ids),this._selectionPoints=[])}getUpdated(M){if(0!==this._selectionPoints.length)return this._selectionPoints.map(((et,Bt)=>({id:et,geometry:{type:"Point",coordinates:M[Bt]}})))}getOneUpdated(M,et){if(void 0!==this._selectionPoints[M])return{id:this._selectionPoints[M],geometry:{type:"Point",coordinates:et}}}}function Ae(M,et){let Bt=!1;for(let Gr=0,mn=et.length;Gr(Wt=M)[1]!=($t=mn[Hn])[1]>Wt[1]&&Wt[0]<($t[0]-Nt[0])*(Wt[1]-Nt[1])/($t[1]-Nt[1])+Nt[0]&&(Bt=!Bt)}var Wt,Nt,$t;return Bt}const Re=(M,et,Bt)=>{const o=M=>M*M,s=(M,et)=>o(M.x-et.x)+o(M.y-et.y);return Math.sqrt(((M,et,Bt)=>{const Wt=s(et,Bt);if(0===Wt)return s(M,et);let Nt=((M.x-et.x)*(Bt.x-et.x)+(M.y-et.y)*(Bt.y-et.y))/Wt;return Nt=Math.max(0,Math.min(1,Nt)),s(M,{x:et.x+Nt*(Bt.x-et.x),y:et.y+Nt*(Bt.y-et.y)})})(M,et,Bt))};class Ve extends de{constructor(M,et,Bt){super(M),this.config=void 0,this.createClickBoundingBox=void 0,this.pixelDistance=void 0,this.config=M,this.createClickBoundingBox=et,this.pixelDistance=Bt}find(M,et){let Bt,Wt,Nt=1/0,$t=1/0;const Gr=this.createClickBoundingBox.create(M),mn=this.store.search(Gr);for(let Gr=0;Gr180||$t<-180||Gr>90||Gr<-90)return!1;Nt[M]=[$t,Gr]}"Polygon"===Bt.type&&(Nt[Nt.length-1]=[Nt[0][0],Nt[0][1]]);const Gr=this.selectionPoints.getUpdated(Nt)||[],mn=this.midPoints.getUpdated(Nt)||[];if(et&&!et({type:"Feature",id:this.draggedFeatureId,geometry:Bt,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:La.Provisional}))return!1;this.store.updateGeometry([{id:this.draggedFeatureId,geometry:Bt},...Gr,...mn]),this.dragPosition=[M.lng,M.lat]}else"Point"===Bt.type&&(this.store.updateGeometry([{id:this.draggedFeatureId,geometry:{type:"Point",coordinates:Wt}}]),this.dragPosition=[M.lng,M.lat])}}class Te extends de{constructor(M,et,Bt,Wt){super(M),this.config=void 0,this.pixelDistance=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.draggedCoordinate={id:null,index:-1},this.config=M,this.pixelDistance=et,this.selectionPoints=Bt,this.midPoints=Wt}getClosestCoordinate(M,et){const Bt={dist:1/0,index:-1,isFirstOrLastPolygonCoord:!1};let Wt;if("LineString"===et.type)Wt=et.coordinates;else{if("Polygon"!==et.type)return Bt;Wt=et.coordinates[0]}for(let Nt=0;Nt180||M.lng<-180||M.lat>90||M.lat<-90)return!1;if("Polygon"!==Nt.type||Wt!==$t.length-1&&0!==Wt)$t[Wt]=Gr;else{const M=$t.length-1;$t[0]=Gr,$t[M]=Gr}const mn=this.selectionPoints.getOneUpdated(Wt,Gr),Hn=mn?[mn]:[],so=this.midPoints.getUpdated($t)||[];return!("Point"!==Nt.type&&!et&&oe({type:"Feature",geometry:Nt,properties:{}})||Bt&&!Bt({type:"Feature",id:this.draggedCoordinate.id,geometry:Nt,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:La.Provisional})||(this.store.updateGeometry([{id:this.draggedCoordinate.id,geometry:Nt},...Hn,...so]),0))}isDragging(){return null!==this.draggedCoordinate.id}startDragging(M,et){this.draggedCoordinate={id:M,index:et}}stopDragging(){this.draggedCoordinate={id:null,index:-1}}}function Xe(M){let et=0,Bt=0,Wt=0;return("Polygon"===M.geometry.type?M.geometry.coordinates[0].slice(0,-1):M.geometry.coordinates).forEach((M=>{et+=M[0],Bt+=M[1],Wt++}),!0),[et/Wt,Bt/Wt]}function Ue(M,et){M[0]+=M[0]-et[0]>180?-360:et[0]-M[0]>180?360:0;const Bt=Al,Wt=et[1]*Math.PI/180,Nt=M[1]*Math.PI/180,$t=Nt-Wt;let Gr=Math.abs(M[0]-et[0])*Math.PI/180;Gr>Math.PI&&(Gr-=2*Math.PI);const mn=Math.log(Math.tan(Nt/2+Math.PI/4)/Math.tan(Wt/2+Math.PI/4)),Hn=Math.abs(mn)>1e-11?$t/mn:Math.cos(Wt);return Math.sqrt($t*$t+Hn*Hn*Gr*Gr)*Bt}function Ye(M){const et=("Polygon"===M.geometry.type?M.geometry.coordinates[0]:M.geometry.coordinates).map((M=>{const{x:et,y:Bt}=Qt(M[0],M[1]);return[et,Bt]}));return"Polygon"===M.geometry.type?function(M){let et=0,Bt=0,Wt=0;const Nt=M.length;for(let $t=0;$t180?Nt-=360:Nt<-180&&(Nt+=360),Nt}(Ye(Gr),Qt(M.lng,M.lat)),!this.lastBearing)return void(this.lastBearing=$t);((M,et)=>{if(0===et||360===et||-360===et)return M;const Bt=.017453292519943295*et,Wt=("Polygon"===M.geometry.type?M.geometry.coordinates[0]:M.geometry.coordinates).map((([M,et])=>Qt(M,et))),Nt=Wt.reduce(((M,et)=>({x:M.x+et.x,y:M.y+et.y})),{x:0,y:0});Nt.x/=Wt.length,Nt.y/=Wt.length;const $t=Wt.map((M=>({x:Nt.x+(M.x-Nt.x)*Math.cos(Bt)-(M.y-Nt.y)*Math.sin(Bt),y:Nt.y+(M.x-Nt.x)*Math.sin(Bt)+(M.y-Nt.y)*Math.cos(Bt)}))).map((({x:M,y:et})=>[te(M,et).lng,te(M,et).lat]));"Polygon"===M.geometry.type?M.geometry.coordinates[0]=$t:(console.log("rotatedCoordinates linestring",$t),M.geometry.coordinates=$t)})(Gr,-(this.lastBearing-$t))}else{if("globe"!==this.config.projection)throw new Error("Unsupported projection");if($t=Oe(Xe({type:"Feature",geometry:Wt,properties:{}}),Nt),!this.lastBearing)return void(this.lastBearing=$t+180);!function(M,et){if(0===et||360===et||-360===et)return M;const Bt=Xe(M);("Polygon"===M.geometry.type?M.geometry.coordinates[0]:M.geometry.coordinates).forEach((M=>{const Wt=Oe(Bt,M)+et,Nt=Ue(Bt,M),$t=Le(Bt,Nt,Wt);M[0]=$t[0],M[1]=$t[1]}))}(Gr,-(this.lastBearing-($t+180)))}const mn="Polygon"===Wt.type?Wt.coordinates[0]:Wt.coordinates;mn.forEach((M=>{M[0]=e(M[0],this.coordinatePrecision),M[1]=e(M[1],this.coordinatePrecision)}));const Hn=this.midPoints.getUpdated(mn)||[],so=this.selectionPoints.getUpdated(mn)||[];if(Bt&&!Bt({id:et,type:"Feature",geometry:Wt,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:La.Provisional}))return!1;this.store.updateGeometry([{id:et,geometry:Wt},...so,...Hn]),"web-mercator"===this.projection?this.lastBearing=$t:"globe"===this.projection&&(this.lastBearing=$t+180)}}class Ke extends de{constructor(M,et,Bt){super(M),this.config=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.lastDistance=void 0,this.config=M,this.selectionPoints=et,this.midPoints=Bt}reset(){this.lastDistance=void 0}scale(M,et,Bt){const Wt=this.store.getGeometryCopy(et);if("Polygon"!==Wt.type&&"LineString"!==Wt.type)return;const Nt=[M.lng,M.lat],$t={type:"Feature",geometry:Wt,properties:{}};let Gr;const mn=Ye($t);if("web-mercator"===this.config.projection){const et=Qt(M.lng,M.lat);Gr=i(mn,et)}else{if("globe"!==this.config.projection)throw new Error("Invalid projection");Gr=Ut(Xe({type:"Feature",geometry:Wt,properties:{}}),Nt)}if(!this.lastDistance)return void(this.lastDistance=Gr);const Hn=1-(this.lastDistance-Gr)/Gr;if("web-mercator"===this.config.projection){const{lng:M,lat:et}=te(mn.x,mn.y);!function(M,et,Bt){if(1===et)return M;const Wt=("Polygon"===M.geometry.type?M.geometry.coordinates[0]:M.geometry.coordinates).map((([M,et])=>Qt(M,et))),Nt=Qt(Bt[0],Bt[1]),$t=Wt.map((M=>({x:Nt.x+(M.x-Nt.x)*et,y:Nt.y+(M.y-Nt.y)*et}))).map((({x:M,y:et})=>[te(M,et).lng,te(M,et).lat]));"Polygon"===M.geometry.type?M.geometry.coordinates[0]=$t:M.geometry.coordinates=$t}($t,Hn,[M,et])}else"globe"===this.config.projection&&function(M,et,Bt,Wt="xy"){1===et||("Polygon"===M.geometry.type?M.geometry.coordinates[0]:M.geometry.coordinates).forEach((M=>{const Nt=Ue(Bt,M),$t=Oe(Bt,M),Gr=Le(Bt,Nt*et,$t);"x"!==Wt&&"xy"!==Wt||(M[0]=Gr[0]),"y"!==Wt&&"xy"!==Wt||(M[1]=Gr[1])}))}($t,Hn,Xe($t));const so="Polygon"===Wt.type?Wt.coordinates[0]:Wt.coordinates;so.forEach((M=>{M[0]=e(M[0],this.coordinatePrecision),M[1]=e(M[1],this.coordinatePrecision)}));const uo=this.midPoints.getUpdated(so)||[],Io=this.selectionPoints.getUpdated(so)||[];if(Bt&&!Bt({id:et,type:"Feature",geometry:Wt,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:La.Provisional}))return!1;this.store.updateGeometry([{id:et,geometry:Wt},...Io,...uo]),this.lastDistance=Gr}}class Je extends de{constructor(M,et,Bt,Wt){super(M),this.config=void 0,this.pixelDistance=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.minimumScale=1e-4,this.draggedCoordinate={id:null,index:-1},this.boundingBoxMaps={opposite:{0:4,1:5,2:6,3:7,4:0,5:1,6:2,7:3}},this.config=M,this.pixelDistance=et,this.selectionPoints=Bt,this.midPoints=Wt}getClosestCoordinate(M,et){const Bt={dist:1/0,index:-1,isFirstOrLastPolygonCoord:!1};let Wt;if("LineString"===et.type)Wt=et.coordinates;else{if("Polygon"!==et.type)return Bt;Wt=et.coordinates[0]}for(let Nt=0;Nt=0)return!1;break;case 1:if(Bt>=0)return!1;break;case 2:if(et>=0||Bt>=0)return!1;break;case 3:if(et>=0)return!1;break;case 4:if(et>=0||Bt<=0)return!1;break;case 5:if(Bt<=0)return!1;break;case 6:if(et<=0||Bt<=0)return!1;break;case 7:if(et<=0)return!1}return!0}getSelectedFeatureDataWebMercator(){if(!this.draggedCoordinate.id||-1===this.draggedCoordinate.index)return null;const M=this.getFeature(this.draggedCoordinate.id);if(!M)return null;const et=this.getNormalisedCoordinates(M.geometry);return{boundingBox:this.getBBoxWebMercator(et),feature:M,updatedCoords:et,selectedCoordinate:et[this.draggedCoordinate.index]}}centerWebMercatorDrag(M){const et=this.getSelectedFeatureDataWebMercator();if(!et)return null;const{feature:Bt,boundingBox:Wt,updatedCoords:Nt,selectedCoordinate:$t}=et,Gr=Ye(Bt);if(!Gr)return null;const mn=Qt($t[0],$t[1]),{closestBBoxIndex:Hn}=this.getIndexesWebMercator(Wt,mn),so=Qt(M.lng,M.lat);return this.scaleWebMercator({closestBBoxIndex:Hn,updatedCoords:Nt,webMercatorCursor:so,webMercatorSelected:mn,webMercatorOrigin:Gr}),Nt}centerFixedWebMercatorDrag(M){const et=this.getSelectedFeatureDataWebMercator();if(!et)return null;const{feature:Bt,boundingBox:Wt,updatedCoords:Nt,selectedCoordinate:$t}=et,Gr=Ye(Bt);if(!Gr)return null;const mn=Qt($t[0],$t[1]),{closestBBoxIndex:Hn}=this.getIndexesWebMercator(Wt,mn),so=Qt(M.lng,M.lat);return this.scaleFixedWebMercator({closestBBoxIndex:Hn,updatedCoords:Nt,webMercatorCursor:so,webMercatorSelected:mn,webMercatorOrigin:Gr}),Nt}scaleFixedWebMercator({closestBBoxIndex:M,webMercatorOrigin:et,webMercatorSelected:Bt,webMercatorCursor:Wt,updatedCoords:Nt}){if(!this.isValidDragWebMercator(M,et.x-Wt.x,et.y-Wt.y))return null;let $t=i(et,Wt)/i(et,Bt);return $t<0&&($t=this.minimumScale),this.performWebMercatorScale(Nt,et.x,et.y,$t,$t),Nt}oppositeFixedWebMercatorDrag(M){const et=this.getSelectedFeatureDataWebMercator();if(!et)return null;const{boundingBox:Bt,updatedCoords:Wt,selectedCoordinate:Nt}=et,$t=Qt(Nt[0],Nt[1]),{oppositeBboxIndex:Gr,closestBBoxIndex:mn}=this.getIndexesWebMercator(Bt,$t),Hn={x:Bt[Gr][0],y:Bt[Gr][1]},so=Qt(M.lng,M.lat);return this.scaleFixedWebMercator({closestBBoxIndex:mn,updatedCoords:Wt,webMercatorCursor:so,webMercatorSelected:$t,webMercatorOrigin:Hn}),Wt}oppositeWebMercatorDrag(M){const et=this.getSelectedFeatureDataWebMercator();if(!et)return null;const{boundingBox:Bt,updatedCoords:Wt,selectedCoordinate:Nt}=et,$t=Qt(Nt[0],Nt[1]),{oppositeBboxIndex:Gr,closestBBoxIndex:mn}=this.getIndexesWebMercator(Bt,$t),Hn={x:Bt[Gr][0],y:Bt[Gr][1]},so=Qt(M.lng,M.lat);return this.scaleWebMercator({closestBBoxIndex:mn,updatedCoords:Wt,webMercatorCursor:so,webMercatorSelected:$t,webMercatorOrigin:Hn}),Wt}scaleWebMercator({closestBBoxIndex:M,webMercatorOrigin:et,webMercatorSelected:Bt,webMercatorCursor:Wt,updatedCoords:Nt}){const $t=et.x-Wt.x,Gr=et.y-Wt.y;if(!this.isValidDragWebMercator(M,$t,Gr))return null;let mn=1;0!==$t&&1!==M&&5!==M&&(mn=1-(et.x-Bt.x-$t)/$t);let Hn=1;return 0!==Gr&&3!==M&&7!==M&&(Hn=1-(et.y-Bt.y-Gr)/Gr),this.validateScale(mn,Hn)?(mn<0&&(mn=this.minimumScale),Hn<0&&(Hn=this.minimumScale),this.performWebMercatorScale(Nt,et.x,et.y,mn,Hn),Nt):null}getFeature(M){if(null===this.draggedCoordinate.id)return null;const et=this.store.getGeometryCopy(M);return"Polygon"!==et.type&&"LineString"!==et.type?null:{type:"Feature",geometry:et,properties:{}}}getNormalisedCoordinates(M){return"Polygon"===M.type?M.coordinates[0]:M.coordinates}validateScale(M,et){const Bt=!isNaN(M)&&et{const{x:$t,y:Gr}=Qt(M[0],M[1]),mn=et+($t-et)*Wt,Hn=Bt+(Gr-Bt)*Nt,{lng:so,lat:uo}=te(mn,Hn);M[0]=so,M[1]=uo}))}getBBoxWebMercator(M){const et=[1/0,1/0,-1/0,-1/0];(M=M.map((M=>{const{x:et,y:Bt}=Qt(M[0],M[1]);return[et,Bt]}))).forEach((([M,Bt])=>{Met[2]&&(et[2]=M),Bt>et[3]&&(et[3]=Bt)}));const[Bt,Wt,Nt,$t]=et;return[[Bt,$t],[(Bt+Nt)/2,$t],[Nt,$t],[Nt,$t+(Wt-$t)/2],[Nt,Wt],[(Bt+Nt)/2,Wt],[Bt,Wt],[Bt,$t+(Wt-$t)/2]]}getIndexesWebMercator(M,et){let Bt,Wt=1/0;for(let Nt=0;Ntthis.store.has(M))).map((M=>({id:M,property:Da,value:!1})));this.store.updateProperty(M),this.onDeselect(this.selected[0]),this.selected=[],this.selectionPoints.delete(),this.midPoints.delete()}deleteSelected(){this.store.delete(this.selected),this.selected=[]}onRightClick(M){if(!this.selectionPoints.ids.length)return;let et,Bt=1/0;if(this.selectionPoints.ids.forEach((Wt=>{const Nt=this.store.getGeometryCopy(Wt),$t=this.pixelDistance.measure(M,Nt.coordinates);$t0);if(this.selected.length&&Bt)this.midPoints.insert(Bt.id,this.coordinatePrecision);else if(et&&et.id)this.select(et.id,!0);else if(this.selected.length&&this.allowManualDeselection)return void this.deselect()}start(){this.setStarted(),this.setSelecting()}stop(){this.cleanUp(),this.setStarted(),this.setStopped()}onClick(M){"right"!==M.button?"left"===M.button&&this.onLeftClick(M):this.onRightClick(M)}canScale(M){return this.keyEvents.scale&&this.keyEvents.scale.every((et=>M.heldKeys.includes(et)))}canRotate(M){return this.keyEvents.rotate&&this.keyEvents.rotate.every((et=>M.heldKeys.includes(et)))}preventDefaultKeyEvent(M){const et=this.canRotate(M),Bt=this.canScale(M);(et||Bt)&&M.preventDefault()}onKeyDown(M){this.preventDefaultKeyEvent(M)}onKeyUp(M){if(this.preventDefaultKeyEvent(M),this.keyEvents.delete&&M.key===this.keyEvents.delete){if(!this.selected.length)return;this.onDeselect(this.selected[0]),this.deleteSelected(),this.selectionPoints.delete(),this.midPoints.delete()}else this.keyEvents.deselect&&M.key===this.keyEvents.deselect&&this.cleanUp()}cleanUp(){this.selected.length&&this.deselect()}onDragStart(M,et){if(!this.selected.length)return;const Bt=this.store.getPropertiesCopy(this.selected[0]),Wt=this.flags[Bt.mode];if(!(Wt&&Wt.feature&&(Wt.feature.draggable||Wt.feature.coordinates&&Wt.feature.coordinates.draggable||Wt.feature.coordinates&&Wt.feature.coordinates.resizable)))return;this.dragEventCount=0;const Nt=this.selected[0],$t=this.dragCoordinate.getDraggableIndex(M,Nt);return Wt&&Wt.feature&&Wt.feature.coordinates&&(Wt.feature.coordinates.draggable||Wt.feature.coordinates.resizable)&&-1!==$t?(this.setCursor(this.cursors.dragStart),Wt.feature.coordinates.resizable?this.dragCoordinateResizeFeature.startDragging(Nt,$t):this.dragCoordinate.startDragging(Nt,$t),void et(!1)):Wt&&Wt.feature&&Wt.feature.draggable&&this.dragFeature.canDrag(M,Nt)?(this.setCursor(this.cursors.dragStart),this.dragFeature.startDragging(M,Nt),void et(!1)):void 0}onDrag(M,et){const Bt=this.selected[0];if(!Bt)return;const Wt=this.store.getPropertiesCopy(Bt),Nt=this.flags[Wt.mode],$t=!0===(Nt&&Nt.feature&&Nt.feature.selfIntersectable);if(this.dragEventCount++,this.dragEventCount%this.dragEventThrottle==0)return;const Gr=this.validations[Wt.mode];if(Nt&&Nt.feature&&Nt.feature.rotateable&&this.canRotate(M))return et(!1),void this.rotateFeature.rotate(M,Bt,Gr);if(Nt&&Nt.feature&&Nt.feature.scaleable&&this.canScale(M))return et(!1),void this.scaleFeature.scale(M,Bt,Gr);if(this.dragCoordinateResizeFeature.isDragging()&&Nt.feature&&Nt.feature.coordinates&&Nt.feature.coordinates.resizable){if("globe"===this.projection)throw new Error("Globe is currently unsupported projection for resizable");return et(!1),void this.dragCoordinateResizeFeature.drag(M,Nt.feature.coordinates.resizable,Gr)}this.dragCoordinate.isDragging()?this.dragCoordinate.drag(M,$t,Gr):this.dragFeature.isDragging()?this.dragFeature.drag(M,Gr):et(!0)}onDragEnd(M,et){this.setCursor(this.cursors.dragEnd),this.dragCoordinate.isDragging()?this.onFinish(this.selected[0],{mode:this.mode,action:"dragCoordinate"}):this.dragFeature.isDragging()?this.onFinish(this.selected[0],{mode:this.mode,action:"dragFeature"}):this.dragCoordinateResizeFeature.isDragging()&&this.onFinish(this.selected[0],{mode:this.mode,action:"dragCoordinateResize"}),this.dragCoordinate.stopDragging(),this.dragFeature.stopDragging(),this.dragCoordinateResizeFeature.stopDragging(),this.rotateFeature.reset(),this.scaleFeature.reset(),et(!0)}onMouseMove(M){if(!this.selected.length)return void this.setCursor("unset");if(this.dragFeature.isDragging())return;let et=!1;this.midPoints.ids.forEach((Bt=>{if(et)return;const Wt=this.store.getGeometryCopy(Bt);this.pixelDistance.measure(M,Wt.coordinates){const Nt=this.store.getGeometryCopy(Wt);this.pixelDistance.measure(M,Nt.coordinates)0&&(Wt&&Wt.id===this.selected[0]||Bt)?this.cursors.pointerOver:"unset")}styleFeature(M){const et=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});if(M.properties.mode===this.mode&&"Point"===M.geometry.type){if(M.properties.selectionPoint)return et.pointColor=this.getHexColorStylingValue(this.styles.selectionPointColor,et.pointColor,M),et.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectionPointOutlineColor,et.pointOutlineColor,M),et.pointWidth=this.getNumericStylingValue(this.styles.selectionPointWidth,et.pointWidth,M),et.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectionPointOutlineWidth,2,M),et.zIndex=30,et;if(M.properties.midPoint)return et.pointColor=this.getHexColorStylingValue(this.styles.midPointColor,et.pointColor,M),et.pointOutlineColor=this.getHexColorStylingValue(this.styles.midPointOutlineColor,et.pointOutlineColor,M),et.pointWidth=this.getNumericStylingValue(this.styles.midPointWidth,4,M),et.pointOutlineWidth=this.getNumericStylingValue(this.styles.midPointOutlineWidth,2,M),et.zIndex=40,et}else if(M.properties[Da]){if("Polygon"===M.geometry.type)return et.polygonFillColor=this.getHexColorStylingValue(this.styles.selectedPolygonColor,et.polygonFillColor,M),et.polygonOutlineWidth=this.getNumericStylingValue(this.styles.selectedPolygonOutlineWidth,et.polygonOutlineWidth,M),et.polygonOutlineColor=this.getHexColorStylingValue(this.styles.selectedPolygonOutlineColor,et.polygonOutlineColor,M),et.polygonFillOpacity=this.getNumericStylingValue(this.styles.selectedPolygonFillOpacity,et.polygonFillOpacity,M),et.zIndex=10,et;if("LineString"===M.geometry.type)return et.lineStringColor=this.getHexColorStylingValue(this.styles.selectedLineStringColor,et.lineStringColor,M),et.lineStringWidth=this.getNumericStylingValue(this.styles.selectedLineStringWidth,et.lineStringWidth,M),et.zIndex=10,et;if("Point"===M.geometry.type)return et.pointWidth=this.getNumericStylingValue(this.styles.selectedPointWidth,et.pointWidth,M),et.pointColor=this.getHexColorStylingValue(this.styles.selectedPointColor,et.pointColor,M),et.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectedPointOutlineColor,et.pointOutlineColor,M),et.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectedPointOutlineWidth,et.pointOutlineWidth,M),et.zIndex=10,et}return et}}class qe extends Tt{constructor(...M){super(...M),this.type=$a.Static,this.mode="static"}start(){}stop(){}onKeyUp(){}onKeyDown(){}onClick(){}onDragStart(){}onDrag(){}onDragEnd(){}onMouseMove(){}cleanUp(){}styleFeature(){return t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0})}}function Ze(M,et,Bt,Wt,Nt){for(;Wt>Bt;){if(Wt-Bt>600){const $t=Wt-Bt+1,Gr=et-Bt+1,mn=Math.log($t),Hn=.5*Math.exp(2*mn/3),so=.5*Math.sqrt(mn*Hn*($t-Hn)/$t)*(Gr-$t/2<0?-1:1);Ze(M,et,Math.max(Bt,Math.floor(et-Gr*Hn/$t+so)),Math.min(Wt,Math.floor(et+($t-Gr)*Hn/$t+so)),Nt)}const $t=M[et];let Gr=Bt,mn=Wt;for(Qe(M,Bt,et),Nt(M[Wt],$t)>0&&Qe(M,Bt,Wt);Gr0;)mn--}0===Nt(M[Bt],$t)?Qe(M,Bt,mn):(mn++,Qe(M,mn,Wt)),mn<=et&&(Bt=mn+1),et<=mn&&(Wt=mn-1)}}function Qe(M,et,Bt){const Wt=M[et];M[et]=M[Bt],M[Bt]=Wt}function ti(M,et){ei(M,0,M.children.length,et,M)}function ei(M,et,Bt,Wt,Nt){Nt||(Nt=ci([])),Nt.minX=1/0,Nt.minY=1/0,Nt.maxX=-1/0,Nt.maxY=-1/0;for(let $t=et;$t=M.minX&&et.maxY>=M.minY}function ci(M){return{children:M,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function di(M,et,Bt,Wt,Nt){const $t=[et,Bt];for(;$t.length;){if((Bt=$t.pop())-(et=$t.pop())<=Wt)continue;const Gr=et+Math.ceil((Bt-et)/Wt/2)*Wt;Ze(M,Gr,et,Bt,Nt),$t.push(et,Gr,Gr,Bt)}}class ui{constructor(M){this._maxEntries=void 0,this._minEntries=void 0,this.data=void 0,this._maxEntries=Math.max(4,M),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}search(M){let et=this.data;const Bt=[];if(!hi(M,et))return Bt;const Wt=this.toBBox,Nt=[];for(;et;){for(let $t=0;$t=0&&Nt[et].children.length>this._maxEntries;)this._split(Nt,et),et--;this._adjustParentBBoxes(Wt,Nt,et)}_split(M,et){const Bt=M[et],Wt=Bt.children.length,Nt=this._minEntries;this._chooseSplitAxis(Bt,Nt,Wt);const $t=this._chooseSplitIndex(Bt,Nt,Wt),Gr=ci(Bt.children.splice($t,Bt.children.length-$t));Gr.height=Bt.height,Gr.leaf=Bt.leaf,ti(Bt,this.toBBox),ti(Gr,this.toBBox),et?M[et-1].children.push(Gr):this._splitRoot(Bt,Gr)}_splitRoot(M,et){this.data=ci([M,et]),this.data.height=M.height+1,this.data.leaf=!1,ti(this.data,this.toBBox)}_chooseSplitIndex(M,et,Bt){let Wt,Nt=1/0,$t=1/0;for(let Gr=et;Gr<=Bt-et;Gr++){const et=ei(M,0,Gr,this.toBBox),mn=ei(M,Gr,Bt,this.toBBox),Hn=ai(et,mn),so=ri(et)+ri(mn);Hn=et;Wt--){const et=M.children[Wt];ii(Gr,M.leaf?Nt(et):et),mn+=ni(Gr)}return mn}_adjustParentBBoxes(M,et,Bt){for(let Wt=Bt;Wt>=0;Wt--)ii(et[Wt],M)}_condense(M){for(let et,Bt=M.length-1;Bt>=0;Bt--)0===M[Bt].children.length?Bt>0?(et=M[Bt-1].children,et.splice(et.indexOf(M[Bt]),1)):this.clear():ti(M[Bt],this.toBBox)}}class gi{constructor(M){this.tree=void 0,this.idToNode=void 0,this.nodeToId=void 0,this.tree=new ui(M&&M.maxEntries?M.maxEntries:9),this.idToNode=new Map,this.nodeToId=new Map}setMaps(M,et){this.idToNode.set(M.id,et),this.nodeToId.set(et,M.id)}toBBox(M){const et=[],Bt=[];let Wt;if("Polygon"===M.geometry.type)Wt=M.geometry.coordinates[0];else if("LineString"===M.geometry.type)Wt=M.geometry.coordinates;else{if("Point"!==M.geometry.type)throw new Error("Not a valid feature to turn into a bounding box");Wt=[M.geometry.coordinates]}for(let M=0;M{const Wt=this.toBBox(M);if(this.setMaps(M,Wt),Bt.has(String(M.id)))throw new Error(`Duplicate feature ID found ${M.id}`);Bt.add(String(M.id)),et.push(Wt)})),this.tree.load(et)}update(M){this.remove(M.id);const et=this.toBBox(M);this.setMaps(M,et),this.tree.insert(et)}remove(M){const et=this.idToNode.get(M);if(!et)throw new Error(`${M} not inserted into the spatial index`);this.tree.remove(et)}clear(){this.tree.clear()}search(M){return this.tree.search(this.toBBox(M)).map((M=>this.nodeToId.get(M)))}collides(M){return this.tree.collides(this.toBBox(M))}}const Rl={getId:()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(M){const et=16*Math.random()|0;return("x"==M?et:3&et|8).toString(16)})),isValidId:M=>"string"==typeof M&&36===M.length};class yi{constructor(M){this.idStrategy=void 0,this.tracked=void 0,this.spatialIndex=void 0,this.store=void 0,this._onChange=()=>{},this.store={},this.spatialIndex=new gi,this.tracked=!M||!1!==M.tracked,this.idStrategy=M&&M.idStrategy?M.idStrategy:Rl}clone(M){return JSON.parse(JSON.stringify(M))}getId(){return this.idStrategy.getId()}has(M){return Boolean(this.store[M])}load(M,et){if(0===M.length)return;const Bt=this.clone(M);Bt.forEach((M=>{null==M.id&&(M.id=this.idStrategy.getId()),this.tracked&&(M.properties.createdAt?Vt(M.properties.createdAt):M.properties.createdAt=+new Date,M.properties.updatedAt?Vt(M.properties.updatedAt):M.properties.updatedAt=+new Date)}));const Wt=[];Bt.forEach((M=>{const Bt=M.id;if(et&&!et(M))throw new Error(`Feature is not ${Bt} valid: ${JSON.stringify(M)}`);if(this.has(Bt))throw new Error(`Feature already exists with this id: ${Bt}`);this.store[Bt]=M,Wt.push(Bt)})),this.spatialIndex.load(Bt),this._onChange(Wt,"create")}search(M,et){const Bt=this.spatialIndex.search(M).map((M=>this.store[M]));return this.clone(et?Bt.filter(et):Bt)}registerOnChange(M){this._onChange=(et,Bt)=>{M(et,Bt)}}getGeometryCopy(M){const et=this.store[M];if(!et)throw new Error(`No feature with this id (${M}), can not get geometry copy`);return this.clone(et.geometry)}getPropertiesCopy(M){const et=this.store[M];if(!et)throw new Error(`No feature with this id (${M}), can not get properties copy`);return this.clone(et.properties)}updateProperty(M){const et=[];M.forEach((({id:M,property:Bt,value:Wt})=>{const Nt=this.store[M];if(!Nt)throw new Error(`No feature with this (${M}), can not update geometry`);et.push(M),Nt.properties[Bt]=Wt,this.tracked&&(Nt.properties.updatedAt=+new Date)})),this._onChange&&this._onChange(et,"update")}updateGeometry(M){const et=[];M.forEach((({id:M,geometry:Bt})=>{et.push(M);const Wt=this.store[M];if(!Wt)throw new Error(`No feature with this (${M}), can not update geometry`);Wt.geometry=this.clone(Bt),this.spatialIndex.update(Wt),this.tracked&&(Wt.properties.updatedAt=+new Date)})),this._onChange&&this._onChange(et,"update")}create(M){const et=[];return M.forEach((({geometry:M,properties:Bt})=>{let Wt,Nt=t({},Bt);this.tracked&&(Wt=+new Date,Bt?(Nt.createdAt="number"==typeof Bt.createdAt?Bt.createdAt:Wt,Nt.updatedAt="number"==typeof Bt.updatedAt?Bt.updatedAt:Wt):Nt={createdAt:Wt,updatedAt:Wt});const $t=this.getId(),Gr={id:$t,type:"Feature",geometry:M,properties:Nt};this.store[$t]=Gr,this.spatialIndex.insert(Gr),et.push($t)})),this._onChange&&this._onChange([...et],"create"),et}delete(M){M.forEach((M=>{if(!this.store[M])throw new Error("No feature with this id, can not delete");delete this.store[M],this.spatialIndex.remove(M)})),this._onChange&&this._onChange([...M],"delete")}copyAll(){return this.clone(Object.keys(this.store).map((M=>this.store[M])))}clear(){this.store={},this.spatialIndex.clear()}size(){return Object.keys(this.store).length}}class Si{constructor(M){this._modes=void 0,this._mode=void 0,this._adapter=void 0,this._enabled=!1,this._store=void 0,this._eventListeners=void 0,this._instanceSelectMode=void 0,this._adapter=M.adapter,this._mode=new qe;const et=new Set,Bt=M.modes.reduce(((M,Bt)=>{if(et.has(Bt.mode))throw new Error(`There is already a ${Bt.mode} mode provided`);return et.add(Bt.mode),M[Bt.mode]=Bt,M}),{}),Wt=Object.keys(Bt);if(0===Wt.length)throw new Error("No modes provided");Wt.forEach((M=>{if(Bt[M].type===$a.Select){if(this._instanceSelectMode)throw new Error("only one type of select mode can be provided");this._instanceSelectMode=M}})),this._modes=t({},Bt,{static:this._mode}),this._eventListeners={change:[],select:[],deselect:[],finish:[],ready:[]},this._store=new yi({tracked:!!M.tracked,idStrategy:M.idStrategy?M.idStrategy:void 0});const r=M=>{const et=[],Bt=this._store.copyAll().filter((Bt=>!M.includes(Bt.id)||(et.push(Bt),!1)));return{changed:et,unchanged:Bt}},n=(M,et)=>{this._enabled&&this._eventListeners.finish.forEach((Bt=>{Bt(M,et)}))},a=(M,et)=>{if(!this._enabled)return;this._eventListeners.change.forEach((Bt=>{Bt(M,et)}));const{changed:Bt,unchanged:Wt}=r(M);"create"===et?this._adapter.render({created:Bt,deletedIds:[],unchanged:Wt,updated:[]},this.getModeStyles()):"update"===et?this._adapter.render({created:[],deletedIds:[],unchanged:Wt,updated:Bt},this.getModeStyles()):"delete"===et?this._adapter.render({created:[],deletedIds:M,unchanged:Wt,updated:[]},this.getModeStyles()):"styling"===et&&this._adapter.render({created:[],deletedIds:[],unchanged:Wt,updated:[]},this.getModeStyles())},l=M=>{if(!this._enabled)return;this._eventListeners.select.forEach((et=>{et(M)}));const{changed:et,unchanged:Bt}=r([M]);this._adapter.render({created:[],deletedIds:[],unchanged:Bt,updated:et},this.getModeStyles())},h=M=>{if(!this._enabled)return;this._eventListeners.deselect.forEach((M=>{M()}));const{changed:et,unchanged:Bt}=r([M]);et&&this._adapter.render({created:[],deletedIds:[],unchanged:Bt,updated:et},this.getModeStyles())};Object.keys(this._modes).forEach((M=>{this._modes[M].register({mode:M,store:this._store,setCursor:this._adapter.setCursor.bind(this._adapter),project:this._adapter.project.bind(this._adapter),unproject:this._adapter.unproject.bind(this._adapter),setDoubleClickToZoom:this._adapter.setDoubleClickToZoom.bind(this._adapter),onChange:a,onSelect:l,onDeselect:h,onFinish:n,coordinatePrecision:this._adapter.getCoordinatePrecision()})}))}checkEnabled(){if(!this._enabled)throw new Error("Terra Draw is not enabled")}getModeStyles(){const M={};return Object.keys(this._modes).forEach((et=>{M[et]=M=>this._instanceSelectMode&&M.properties[Da]?this._modes[this._instanceSelectMode].styleFeature.bind(this._modes[this._instanceSelectMode])(M):this._modes[et].styleFeature.bind(this._modes[et])(M)})),M}featuresAtLocation({lng:M,lat:et},Bt){const Wt=Bt&&void 0!==Bt.pointerDistance?Bt.pointerDistance:30,Nt=!Bt||void 0===Bt.ignoreSelectFeatures||Bt.ignoreSelectFeatures,$t=this._adapter.unproject.bind(this._adapter),Gr=this._adapter.project.bind(this._adapter),mn=Gr(M,et),Hn=ue({unproject:$t,point:mn,pointerDistance:Wt});return this._store.search(Hn).filter((Bt=>{if(Nt&&(Bt.properties[Ka]||Bt.properties.selectionPoint))return!1;if("Point"===Bt.geometry.type){const M=Bt.geometry.coordinates,et=Gr(M[0],M[1]);return i(mn,et){if(Boolean(M&&"object"==typeof M&&"properties"in M&&"object"==typeof M.properties&&null!==M.properties&&"mode"in M.properties)){const et=this._modes[M.properties.mode];return!!et&&et.validateFeature.bind(et)(M)}return!1}))}start(){this._enabled=!0,this._adapter.register({onReady:()=>{this._eventListeners.ready.forEach((M=>{M()}))},getState:()=>this._mode.state,onClick:M=>{this._mode.onClick(M)},onMouseMove:M=>{this._mode.onMouseMove(M)},onKeyDown:M=>{this._mode.onKeyDown(M)},onKeyUp:M=>{this._mode.onKeyUp(M)},onDragStart:(M,et)=>{this._mode.onDragStart(M,et)},onDrag:(M,et)=>{this._mode.onDrag(M,et)},onDragEnd:(M,et)=>{this._mode.onDragEnd(M,et)},onClear:()=>{this._mode.cleanUp(),this._store.clear()}})}getFeaturesAtLngLat(M,et){const{lng:Bt,lat:Wt}=M;return this.featuresAtLocation({lng:Bt,lat:Wt},et)}getFeaturesAtPointerEvent(M,et){const Bt=this._adapter.getLngLatFromEvent.bind(this._adapter)(M);return null===Bt?[]:this.featuresAtLocation(Bt,et)}stop(){this._enabled=!1,this._adapter.unregister()}on(M,et){const Bt=this._eventListeners[M];Bt.includes(et)||Bt.push(et)}off(M,et){const Bt=this._eventListeners[M];Bt.includes(et)&&Bt.splice(Bt.indexOf(et),1)}}class MapOption{constructor({name:M,desc:et,example:Bt,exampleDesc:Wt,isValid:Nt}){this.name=M,this.desc=et,this.example=Bt,this.exampleDesc=Wt,this.isValid=Nt}valueOf(){return this.name}}class defaultExport{width="300px";height="300px";center=[121,24];zoom=7;control={scale:!1,fullscreen:!1};layers=[];data=[];aliases=[];svgPin={html:'',size:[27,41],anchor:[13.5,35.25]};get map(){if(void 0===this._map)throw Error("map is not set in current Renderer");return this._map}set map(M){if(this._map)throw Error("map cannot be reassigned");this._map=M}get steps(){return[this.setOptionAliases,this.createView,this.addMap,this.setControl,this.addTileData,this.addGPXFile,this.getTerraDrawAdapter,{valueOf:()=>this.setDraw,depends:this.getTerraDrawAdapter},this.setExtra]}validateOption(M,et){const Bt=this.constructor.validOptions.find((et=>et.valueOf()===M))?.isValid;if(!Bt)throw Error(`Cannot find inValid method for option ${M}`);return Bt(et)}static validOptions=Object.freeze([new MapOption({name:"id",desc:"id of map HTML element",isValid:M=>!!M?.match(/\w+/)}),new MapOption({name:"width",desc:"CSS width of map HTML element",example:"200px",exampleDesc:"",isValid:M=>window.CSS.supports(`width: ${M}`)}),new MapOption({name:"height",desc:"CSS height of map HTML element",example:"200px",exampleDesc:"",isValid:M=>window.CSS.supports(`height: ${M}`)}),new MapOption({name:"center",desc:"Center of camera map, value: [lon, lat]",example:"[121, 24]",exampleDesc:"Center of Taiwan",isValid:M=>{try{const[et,Bt]=JSON.parse(M);return!isNaN(et)&&!isNaN(Bt)}catch{return!1}}}),new MapOption({name:"zoom",desc:"Zoom level for map camera, number between: 0-22",example:"7.0",exampleDesc:"Small country / US state",isValid:M=>{const et=Number(M);return!isNaN(et)&&et>=0&&et<=22}}),new MapOption({name:"control",desc:"Object of control options, supports: fullscreen, scale",example:"\n scale: true",exampleDesc:"Add Scale bar",isValid:M=>"object"==typeof M}),new MapOption({name:"debug",desc:"Set true to show tile boundary",example:"true",exampleDesc:"",isValid:M=>"true"===M}),new MapOption({name:"XYZ",desc:"Raster tile format with {x}, {y} and {z}",example:"https://tile.openstreetmap.jp/styles/osm-bright/512/{z}/{x}/{y}.png",exampleDesc:"Tile from OSM Japan!",isValid:M=>URL.parse(M)&&M.includes("{x}")&&M.includes("{y}")&&M.includes("z")}),new MapOption({name:"GPX",desc:"URL of GPX file",example:"https://raw.githubusercontent.com/openlayers/openlayers/main/examples/data/gpx/fells_loop.gpx",exampleDesc:"Example from topografix",isValid:M=>URL.parse(M)}),new MapOption({name:"WMTS",desc:"URL of WMTS document",example:"https://gis.sinica.edu.tw/tileserver/wmts",exampleDesc:"SINICA Taiwan",isValid:M=>URL.parse(M)}),new MapOption({name:"draw",desc:"Draw Something on map",example:"true",exampleDesc:"Enable Draw Tools",isValid:M=>"true"===M}),new MapOption({name:"eval",desc:"Custom Script",example:"console.log('this', this)",exampleDesc:"Print Renderer info",isValid:()=>!0})]);setOptionAliases(M){if(M.XYZ){("string"==typeof M.XYZ?[M.XYZ]:M.XYZ).forEach((et=>{let Bt,Wt;if("string"==typeof et)Wt=new URL(et),Bt={type:"tile",url:et,title:`${Wt.host}${Wt.pathname.split("%7B")[0]}`};else{if("object"!=typeof et)return;Wt=new URL(et.url),Bt={type:"tile",url:et.url,title:et.title?et.title:`${Wt.host}${Wt.pathname.split("%7B")[0]}`}}M.data.push(Bt)})),delete M.XYZ}M.WMTS&&(M.data.push({type:"wmts",url:M.aliases[M.WMTS]??M.WMTS}),delete M.WMTS),M.GPX&&(M.data.push({type:"gpx",url:M.GPX}),delete M.GPX),"string"==typeof M.center&&Object.prototype.hasOwnProperty.call(M.aliases,M.center)&&(M.center=M.aliases[M.center]),M.data?.forEach((et=>{Object.prototype.hasOwnProperty.call(M.aliases,et.url)&&(et.title=et.url,et.url=M.aliases[et.url])}))}createView({target:M,width:et,height:Bt}){M.style.width=et,M.style.height=Bt,"flex"===window.getComputedStyle(M.parentElement).display&&(M.style.flexBasis=`calc(${et})`)}setDraw=({target:M,terraDrawAdapter:et})=>{const Bt=M?.id?M.id+"-":"",Wt={idStrategy:{isValidId:M=>!0,getId:function(){let M=Bt+window.crypto.randomUUID();return function(){return M=Bt+window.crypto.randomUUID(),M}}()}};return this.terraDraw=((M,et={})=>new Si({adapter:M,modes:[new $e({modename:"modify",flags:{render:{feature:{coordinates:{midpoints:!0,draggable:!0,deletable:!0,validation:()=>!0}}}}}),new Ee,new Se,new De,new he,new ke,new Fe({modeName:"render",styles:{pointColor:"red",pointOutlineWidth:2,lineStringColor:"red",lineStringWidth:2,polygonFillColor:"#00FFFF",polygonFillOpacity:0,polygonOutlineColor:"red",polygonOutlineWidth:2}})],...et}))(et,Wt),M.dataset.draw="",((M,et,Bt={})=>{et.start(),et.setMode("render");const Wt=M.id?`terra-draw-data-${M.id}`:"terra-draw-data",Nt=window.localStorage.getItem(Wt);if(Nt)try{const M=JSON.parse(Nt);M.forEach((M=>M.properties={mode:"render"})),et.addFeatures(M)}catch(M){console.warn("Fail to drawn features from Local Storage.",Nt,M),window.localStorage.removeItem(Wt)}const $t=M.querySelector("canvas")??M;$t.style.removeProperty("cursor");const Gr=et.getSnapshot();new window.MutationObserver((()=>{switch(M.dataset.draw){case"":case void 0:et.setMode("render");break;case"modify":et.setMode("select");break;case"delete":et.setMode("render"),$t.style.cursor="not-allowed";break;case"clear":window.localStorage.removeItem(Wt),M.dataset.draw="",et.clear();break;case"features":window.alert(`${Gr.length} features\n\n${JSON.stringify(Gr,null,4)}`);break;default:et.setMode(M.dataset.draw)}})).observe(M,{attributes:!0,attributeFilter:["data-draw"]}),et.on("change",(()=>{})),et.on("finish",((Nt,$t)=>{if("draw"===$t.action){const M=et.getSnapshot().find((M=>M.id===Nt));M&&(et.removeFeatures([Nt]),M.properties.mode="render",et.addFeatures([M]))}const Gr=Bt.idFilter??(()=>!0),mn=et.getSnapshot().filter(Gr);window.localStorage.setItem(Wt,JSON.stringify(mn)),"point"!==$t.mode&&"draw"===$t.action&&(M.dataset.draw="")})),document.onclick=Bt=>{if("delete"===M.dataset.draw){const Wt=et.getFeaturesAtPointerEvent(Bt,{pointerDistance:40});Wt.length>0&&(et.removeFeatures([Wt[0].id]),0===et.getSnapshot().length&&(M.dataset.draw=""))}}})(M,this.terraDraw,{idFilter:M=>M.id.startsWith(Bt)}),this.terraDraw};getTerraDrawAdapter(){return{state:"skip"}}addTileData(){return{state:"skip"}}addGPXFile(){return{state:"skip"}}addMarker(){return{state:"skip"}}setControl(){return{state:"skip"}}setExtra(){return{state:"skip"}}updateCamera(){return{state:"skip"}}project(){return{state:"skip"}}unproject(){return{state:"skip"}}restoreCamera(){this.updateCamera({center:this.center,zoom:this.zoom})}propsForEval(){let M=this,et=[],Bt=[];for(;M!==Object.prototype;)et=et.concat(Object.getOwnPropertyNames(M)),Bt=Bt.concat(Object.entries(M)),M=Object.getPrototypeOf(M);return et}evalScript(M,et=[]){const Bt=this.propsForEval(),Wt=et.map((([M,et])=>M)),Nt=[...Bt.map((M=>this[M])),...et.map((([M,et])=>et))],$t=Function([...Bt,...Wt],M).bind(this,...Nt);try{return $t()}catch(M){return console.warn("Fail to run custom script:",M),null}}}function getDefaultExportFromCjs$1(M){return M&&M.__esModule&&Object.prototype.hasOwnProperty.call(M,"default")?M.default:M}var Tl,Vl={exports:{}}; +/** * MapLibre GL JS * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v5.0.0/LICENSE.txt - */ - var maplibreGl = maplibreGl$1.exports; - - var hasRequiredMaplibreGl; - - function requireMaplibreGl () { - if (hasRequiredMaplibreGl) return maplibreGl$1.exports; - hasRequiredMaplibreGl = 1; - (function (module, exports) { - (function (global, factory) { - module.exports = factory() ; - })(maplibreGl, (function () { - /* eslint-disable */ - - var maplibregl = {}; - var modules = {}; - function define(moduleName, _dependencies, moduleFactory) { - modules[moduleName] = moduleFactory; - - // to get the list of modules see generated dist/maplibre-gl-dev.js file (look for `define(` calls) - if (moduleName !== 'index') { - return; - } - - // we assume that when an index module is initializing then other modules are loaded already - var workerBundleString = 'var sharedModule = {}; (' + modules.shared + ')(sharedModule); (' + modules.worker + ')(sharedModule);'; - - var sharedModule = {}; - // the order of arguments of a module factory depends on rollup (it decides who is whose dependency) - // to check the correct order, see dist/maplibre-gl-dev.js file (look for `define(` calls) - // we assume that for our 3 chunks it will generate 3 modules and their order is predefined like the following - modules.shared(sharedModule); - modules.index(maplibregl, sharedModule); - - if (typeof window !== 'undefined') { - maplibregl.setWorkerUrl(window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }))); - } - - return maplibregl; - } - - - define("shared",["exports"],(function(t){function e(t,e,r,n){return new(r||(r=Promise))((function(i,s){function a(t){try{l(n.next(t));}catch(t){s(t);}}function o(t){try{l(n.throw(t));}catch(t){s(t);}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e);}))).then(a,o);}l((n=n.apply(t,e||[])).next());}))}function r(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var n,i;function s(){if(i)return n;function t(t,e){this.x=t,this.y=e;}return i=1,n=t,t.prototype={clone:function(){return new t(this.x,this.y)},add:function(t){return this.clone()._add(t)},sub:function(t){return this.clone()._sub(t)},multByPoint:function(t){return this.clone()._multByPoint(t)},divByPoint:function(t){return this.clone()._divByPoint(t)},mult:function(t){return this.clone()._mult(t)},div:function(t){return this.clone()._div(t)},rotate:function(t){return this.clone()._rotate(t)},rotateAround:function(t,e){return this.clone()._rotateAround(t,e)},matMult:function(t){return this.clone()._matMult(t)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(t){return this.x===t.x&&this.y===t.y},dist:function(t){return Math.sqrt(this.distSqr(t))},distSqr:function(t){var e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith:function(t){return this.angleWithSep(t.x,t.y)},angleWithSep:function(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult:function(t){var e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add:function(t){return this.x+=t.x,this.y+=t.y,this},_sub:function(t){return this.x-=t.x,this.y-=t.y,this},_mult:function(t){return this.x*=t,this.y*=t,this},_div:function(t){return this.x/=t,this.y/=t,this},_multByPoint:function(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint:function(t){return this.x/=t.x,this.y/=t.y,this},_unit:function(){return this._div(this.mag()),this},_perp:function(){var t=this.y;return this.y=this.x,this.x=-t,this},_rotate:function(t){var e=Math.cos(t),r=Math.sin(t),n=r*this.x+e*this.y;return this.x=e*this.x-r*this.y,this.y=n,this},_rotateAround:function(t,e){var r=Math.cos(t),n=Math.sin(t),i=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=e.x+r*(this.x-e.x)-n*(this.y-e.y),this.y=i,this},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}},t.convert=function(e){return e instanceof t?e:Array.isArray(e)?new t(e[0],e[1]):e},n}"function"==typeof SuppressedError&&SuppressedError;var a,o,l=r(s()),u=function(){if(o)return a;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return o=1,a=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(undefined===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},a}(),c=r(u);let h,p;function f(){return null==h&&(h="undefined"!=typeof OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof createImageBitmap),h}function d(){if(null==p&&(p=false,f())){const t=5,e=new OffscreenCanvas(t,t).getContext("2d",{willReadFrequently:true});if(e){for(let r=0;r=1)return 1;const e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function B(t,e,r,n){const i=new c(t,e,r,n);return t=>i.solve(t)}const V=B(.25,.1,.25,1);function E(t,e,r){return Math.min(r,Math.max(e,t))}function T(t,e,r){const n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i}function F(t,...e){for(const r of e)for(const e in r)t[e]=r[e];return t}let $=1;function L(t,e,r){const n={};for(const r in t)n[r]=e.call(this,t[r],r,t);return n}function D(t,e,r){const n={};for(const r in t)e.call(this,t[r],r,t)&&(n[r]=t[r]);return n}function O(t){return Array.isArray(t)?t.map(O):"object"==typeof t&&t?L(t,O):t}const R={};function j(t){R[t]||("undefined"!=typeof console&&console.warn(t),R[t]=true);}function N(t,e,r){return (r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function U(t){return "undefined"!=typeof WorkerGlobalScope&&undefined!==t&&t instanceof WorkerGlobalScope}let q=null;function G(t){return "undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap}const Z="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";function X(t,r,n,i,s){return e(this,undefined,undefined,(function*(){if("undefined"==typeof VideoFrame)throw new Error("VideoFrame not supported");const e=new VideoFrame(t,{timestamp:0});try{const a=null==e?void 0:e.format;if(!a||!a.startsWith("BGR")&&!a.startsWith("RGB"))throw new Error(`Unrecognized format ${a}`);const o=a.startsWith("BGR"),l=new Uint8ClampedArray(i*s*4);if(yield e.copyTo(l,function(t,e,r,n,i){const s=4*Math.max(-e,0),a=(Math.max(0,r)-r)*n*4+s,o=4*n,l=Math.max(0,e),u=Math.max(0,r);return {rect:{x:l,y:u,width:Math.min(t.width,e+n)-l,height:Math.min(t.height,r+i)-u},layout:[{offset:a,stride:o}]}}(t,r,n,i,s)),o)for(let t=0;tU(self)?self.worker&&self.worker.referrer:("blob:"===window.location.protocol?window.parent:window).location.href,it=function(t,r){if(/:\/\//.test(t.url)&&!/^https?:|^file:/.test(t.url)){const e=tt(t.url);if(e)return e(t,r);if(U(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,targetMapId:et},r)}if(!(/^file:/.test(n=t.url)||/^file:/.test(nt())&&!/^\w+:/.test(n))){if(fetch&&Request&&AbortController&&Object.prototype.hasOwnProperty.call(Request.prototype,"signal"))return function(t,r){return e(this,undefined,undefined,(function*(){const e=new Request(t.url,{method:t.method||"GET",body:t.body,credentials:t.credentials,headers:t.headers,cache:t.cache,referrer:nt(),signal:r.signal});let n,i;"json"!==t.type||e.headers.has("Accept")||e.headers.set("Accept","application/json");try{n=yield fetch(e);}catch(e){throw new rt(0,e.message,t.url,new Blob)}if(!n.ok){const e=yield n.blob();throw new rt(n.status,n.statusText,t.url,e)}i="arrayBuffer"===t.type||"image"===t.type?n.arrayBuffer():"json"===t.type?n.json():n.text();const s=yield i;if(r.signal.aborted)throw W();return {data:s,cacheControl:n.headers.get("Cache-Control"),expires:n.headers.get("Expires")}}))}(t,r);if(U(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,mustQueue:true,targetMapId:et},r)}var n;return function(t,e){return new Promise(((r,n)=>{var i;const s=new XMLHttpRequest;s.open(t.method||"GET",t.url,true),"arrayBuffer"!==t.type&&"image"!==t.type||(s.responseType="arraybuffer");for(const e in t.headers)s.setRequestHeader(e,t.headers[e]);"json"===t.type&&(s.responseType="text",(null===(i=t.headers)||undefined===i?undefined:i.Accept)||s.setRequestHeader("Accept","application/json")),s.withCredentials="include"===t.credentials,s.onerror=()=>{n(new Error(s.statusText));},s.onload=()=>{if(!e.signal.aborted)if((s.status>=200&&s.status<300||0===s.status)&&null!==s.response){let e=s.response;if("json"===t.type)try{e=JSON.parse(s.response);}catch(t){return void n(t)}r({data:e,cacheControl:s.getResponseHeader("Cache-Control"),expires:s.getResponseHeader("Expires")});}else {const e=new Blob([s.response],{type:s.getResponseHeader("Content-Type")});n(new rt(s.status,s.statusText,t.url,e));}},e.signal.addEventListener("abort",(()=>{s.abort(),n(W());})),s.send(t.body);}))}(t,r)};function st(t){if(!t||t.indexOf("://")<=0||0===t.indexOf("data:image/")||0===t.indexOf("blob:"))return true;const e=new URL(t),r=window.location;return e.protocol===r.protocol&&e.host===r.host}function at(t,e,r){r[t]&&-1!==r[t].indexOf(e)||(r[t]=r[t]||[],r[t].push(e));}function ot(t,e,r){if(r&&r[t]){const n=r[t].indexOf(e);-1!==n&&r[t].splice(n,1);}}class lt{constructor(t,e={}){F(this,e),this.type=t;}}class ut extends lt{constructor(t,e={}){super("error",F({error:t},e));}}class ct{on(t,e){return this._listeners=this._listeners||{},at(t,e,this._listeners),{unsubscribe:()=>{this.off(t,e);}}}off(t,e){return ot(t,e,this._listeners),ot(t,e,this._oneTimeListeners),this}once(t,e){return e?(this._oneTimeListeners=this._oneTimeListeners||{},at(t,e,this._oneTimeListeners),this):new Promise((e=>this.once(t,e)))}fire(t,e){"string"==typeof t&&(t=new lt(t,e||{}));const r=t.type;if(this.listens(r)){t.target=this;const e=this._listeners&&this._listeners[r]?this._listeners[r].slice():[];for(const r of e)r.call(this,t);const n=this._oneTimeListeners&&this._oneTimeListeners[r]?this._oneTimeListeners[r].slice():[];for(const e of n)ot(r,e,this._oneTimeListeners),e.call(this,t);const i=this._eventedParent;i&&(F(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),i.fire(t));}else t instanceof ut&&console.error(t.error);return this}listens(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)}setEventedParent(t,e){return this._eventedParent=t,this._eventedParentData=e,this}}var ht={$version:8,$root:{version:{required:true,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},centerAltitude:{type:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},roll:{type:"number",default:0,units:"degrees"},light:{type:"light"},sky:{type:"sky"},projection:{type:"projection"},terrain:{type:"terrain"},sources:{required:true,type:"sources"},sprite:{type:"sprite"},glyphs:{type:"string"},transition:{type:"transition"},layers:{required:true,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:true,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},volatile:{type:"boolean",default:false},"*":{type:"*"}},source_raster:{type:{required:true,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},volatile:{type:"boolean",default:false},"*":{type:"*"}},source_raster_dem:{type:{required:true,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{},custom:{}},default:"mapbox"},redFactor:{type:"number",default:1},blueFactor:{type:"number",default:1},greenFactor:{type:"number",default:1},baseShift:{type:"number",default:0},volatile:{type:"boolean",default:false},"*":{type:"*"}},source_geojson:{type:{required:true,type:"enum",values:{geojson:{}}},data:{required:true,type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},filter:{type:"*"},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:false},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:false},generateId:{type:"boolean",default:false},promoteId:{type:"promoteId"}},source_video:{type:{required:true,type:"enum",values:{video:{}}},urls:{required:true,type:"array",value:"string"},coordinates:{required:true,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:true,type:"enum",values:{image:{}}},url:{required:true,type:"string"},coordinates:{required:true,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:true},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},background:{}},required:true},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:false,expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:false,requires:["icon-image",{"!":"icon-overlap"}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["icon-image"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:false,requires:["icon-image"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:false,requires:["icon-image","text-field"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:true,expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"padding",default:[2],units:"pixels",requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-keep-upright":{type:"boolean",default:false,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},"viewport-glyph":{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:true,expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:true,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-variable-anchor-offset":{type:"variableAnchorOffsetCollection",requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:true,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:false,requires:["text-field",{"!":"text-overlap"}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["text-field"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:false,requires:["text-field"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:false,requires:["text-field","icon-image"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:false}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:false,expression:{interpolated:false,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:true,expression:{interpolated:true,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:true,parameters:["zoom"]},transition:true},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:true,parameters:["zoom"]},transition:true}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:true,parameters:["zoom"]},transition:true},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:true,parameters:["zoom"]},transition:true},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:true,parameters:["zoom"]},transition:true},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:true,parameters:["zoom"]},transition:true},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:true,parameters:["zoom"]},transition:true},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:true,parameters:["zoom"]},transition:true},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:true,parameters:["zoom"]},transition:true}},terrain:{source:{type:"string",required:true},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:false,expression:{interpolated:true,parameters:["zoom"]}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:true,expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:true,requires:[{"!":"fill-pattern"}],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:true,requires:[{"!":"fill-pattern"},{"fill-antialias":true}],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:true,expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:true,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:true,expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:true,requires:["fill-extrusion-height"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:true,transition:false,expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:true,requires:[{"!":"line-pattern"}],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:true,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:true,expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:false,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:true}}],expression:{interpolated:true,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:false,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:false,expression:{interpolated:true,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:true,requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:true,requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:true,units:"pixels",requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:true,units:"pixels",requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:true,units:"pixels",requires:["icon-image"],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:true,overridable:true,requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:true,requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:true,units:"pixels",requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:true,units:"pixels",requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:true,units:"pixels",requires:["text-field"],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:true,units:"degrees",expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:false,units:"milliseconds",expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,transition:false,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"color",default:"#000000",transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:true,requires:[{"!":"background-pattern"}],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:true,expression:{interpolated:false,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}};const pt=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function ft(t,e){const r={};for(const e in t)"ref"!==e&&(r[e]=t[e]);return pt.forEach((t=>{t in e&&(r[t]=e[t]);})),r}function dt(t,e){if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return false;for(let r=0;r`:"value"===t.itemType.kind?"array":`array<${e}>`}return t.kind}const Nt=[It,zt,Pt,Ct,Bt,Vt,$t,Et,Rt(Tt),Lt,Dt,Ot];function Ut(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!Ut(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else {if(t.kind===e.kind)return null;if("value"===t.kind)for(const t of Nt)if(!Ut(t,e))return null}return `Expected ${jt(t)} but found ${jt(e)} instead.`}function qt(t,e){return e.some((e=>e.kind===t.kind))}function Gt(t,e){return e.some((e=>"null"===e?null===t:"array"===e?Array.isArray(t):"object"===e?t&&!Array.isArray(t)&&"object"==typeof t:e===typeof t))}function Zt(t,e){return "array"===t.kind&&"array"===e.kind?t.itemType.kind===e.itemType.kind&&"number"==typeof t.N:t.kind===e.kind}const Xt=.96422,Kt=.82521,Ht=4/29,Yt=6/29,Jt=3*Yt*Yt,Wt=Yt*Yt*Yt,Qt=Math.PI/180,te=180/Math.PI;function ee(t){return (t%=360)<0&&(t+=360),t}function re([t,e,r,n]){let i,s;const a=ie((.2225045*(t=ne(t))+.7168786*(e=ne(e))+.0606169*(r=ne(r)))/1);t===e&&e===r?i=s=a:(i=ie((.4360747*t+.3850649*e+.1430804*r)/Xt),s=ie((.0139322*t+.0971045*e+.7141733*r)/Kt));const o=116*a-16;return [o<0?0:o,500*(i-a),200*(a-s),n]}function ne(t){return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function ie(t){return t>Wt?Math.pow(t,1/3):t/Jt+Ht}function se([t,e,r,n]){let i=(t+16)/116,s=isNaN(e)?i:i+e/500,a=isNaN(r)?i:i-r/200;return i=1*oe(i),s=Xt*oe(s),a=Kt*oe(a),[ae(3.1338561*s-1.6168667*i-.4906146*a),ae(-0.9787684*s+1.9161415*i+.033454*a),ae(.0719453*s-.2289914*i+1.4052427*a),n]}function ae(t){return (t=t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055)<0?0:t>1?1:t}function oe(t){return t>Yt?t*t*t:Jt*(t-Ht)}function le(t){return parseInt(t.padEnd(2,t),16)/255}function ue(t,e){return ce(e?t/100:t,0,1)}function ce(t,e,r){return Math.min(Math.max(e,t),r)}function he(t){return !t.some(Number.isNaN)}const pe={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function fe(t,e,r){return t+r*(e-t)}function de(t,e,r){return t.map(((t,n)=>fe(t,e[n],r)))}class ye{constructor(t,e,r,n=1,i=true){this.r=t,this.g=e,this.b=r,this.a=n,i||(this.r*=n,this.g*=n,this.b*=n,n||this.overwriteGetter("rgb",[t,e,r,n]));}static parse(t){if(t instanceof ye)return t;if("string"!=typeof t)return;const e=function(t){if("transparent"===(t=t.toLowerCase().trim()))return [0,0,0,0];const e=pe[t];if(e){const[t,r,n]=e;return [t/255,r/255,n/255,1]}if(t.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)){const e=t.length<6?1:2;let r=1;return [le(t.slice(r,r+=e)),le(t.slice(r,r+=e)),le(t.slice(r,r+=e)),le(t.slice(r,r+e)||"ff")]}if(t.startsWith("rgb")){const e=t.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(e){const[t,r,n,i,s,a,o,l,u,c,h,p]=e,f=[i||" ",o||" ",c].join("");if(" "===f||" /"===f||",,"===f||",,,"===f){const t=[n,a,u].join(""),e="%%%"===t?100:""===t?255:0;if(e){const t=[ce(+r/e,0,1),ce(+s/e,0,1),ce(+l/e,0,1),h?ue(+h,p):1];if(he(t))return t}}return}}const r=t.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(r){const[t,e,n,i,s,a,o,l,u]=r,c=[n||" ",s||" ",o].join("");if(" "===c||" /"===c||",,"===c||",,,"===c){const t=[+e,ce(+i,0,100),ce(+a,0,100),l?ue(+l,u):1];if(he(t))return function([t,e,r,n]){function i(n){const i=(n+t/30)%12,s=e*Math.min(r,1-r);return r-s*Math.max(-1,Math.min(i-3,9-i,1))}return t=ee(t),e/=100,r/=100,[i(0),i(8),i(4),n]}(t)}}}(t);return e?new ye(...e,false):undefined}get rgb(){const{r:t,g:e,b:r,a:n}=this,i=n||1/0;return this.overwriteGetter("rgb",[t/i,e/i,r/i,n])}get hcl(){return this.overwriteGetter("hcl",function(t){const[e,r,n,i]=re(t),s=Math.sqrt(r*r+n*n);return [Math.round(1e4*s)?ee(Math.atan2(n,r)*te):NaN,s,e,i]}(this.rgb))}get lab(){return this.overwriteGetter("lab",re(this.rgb))}overwriteGetter(t,e){return Object.defineProperty(this,t,{value:e}),e}toString(){const[t,e,r,n]=this.rgb;return `rgba(${[t,e,r].map((t=>Math.round(255*t))).join(",")},${n})`}static interpolate(t,e,r,n="rgb"){switch(n){case"rgb":{const[n,i,s,a]=de(t.rgb,e.rgb,r);return new ye(n,i,s,a,false)}case"hcl":{const[n,i,s,a]=t.hcl,[o,l,u,c]=e.hcl;let h,p;if(isNaN(n)||isNaN(o))isNaN(n)?isNaN(o)?h=NaN:(h=o,1!==s&&0!==s||(p=l)):(h=n,1!==u&&0!==u||(p=i));else {let t=o-n;o>n&&t>180?t-=360:o180&&(t+=360),h=n+r*t;}const[f,d,y,m]=function([t,e,r,n]){return t=isNaN(t)?0:t*Qt,se([r,Math.cos(t)*e,Math.sin(t)*e,n])}([h,null!=p?p:fe(i,l,r),fe(s,u,r),fe(a,c,r)]);return new ye(f,d,y,m,false)}case"lab":{const[n,i,s,a]=se(de(t.lab,e.lab,r));return new ye(n,i,s,a,false)}}}}ye.black=new ye(0,0,0,1),ye.white=new ye(1,1,1,1),ye.transparent=new ye(0,0,0,0),ye.red=new ye(1,0,0,1);class me{constructor(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});}compare(t,e){return this.collator.compare(t,e)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class ge{constructor(t,e,r,n,i){this.text=t,this.image=e,this.scale=r,this.fontStack=n,this.textColor=i;}}class xe{constructor(t){this.sections=t;}static fromString(t){return new xe([new ge(t,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some((t=>0!==t.text.length||t.image&&0!==t.image.name.length))}static factory(t){return t instanceof xe?t:xe.fromString(t)}toString(){return 0===this.sections.length?"":this.sections.map((t=>t.text)).join("")}}class ve{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof ve)return t;if("number"==typeof t)return new ve([t,t,t,t]);if(Array.isArray(t)&&!(t.length<1||t.length>4)){for(const e of t)if("number"!=typeof e)return;switch(t.length){case 1:t=[t[0],t[0],t[0],t[0]];break;case 2:t=[t[0],t[1],t[0],t[1]];break;case 3:t=[t[0],t[1],t[2],t[1]];}return new ve(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r){return new ve(de(t.values,e.values,r))}}class be{constructor(t){this.name="ExpressionEvaluationError",this.message=t;}toJSON(){return this.message}}const we=new Set(["center","left","right","top","bottom","top-left","top-right","bottom-left","bottom-right"]);class _e{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof _e)return t;if(Array.isArray(t)&&!(t.length<1)&&t.length%2==0){for(let e=0;e=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?undefined===n||"number"==typeof n&&n>=0&&n<=1?null:`Invalid rgba value [${[t,e,r,n].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Me(t){if(null===t||"string"==typeof t||"boolean"==typeof t||"number"==typeof t||t instanceof Ae||t instanceof ye||t instanceof me||t instanceof xe||t instanceof ve||t instanceof _e||t instanceof Se)return true;if(Array.isArray(t)){for(const e of t)if(!Me(e))return false;return true}if("object"==typeof t){for(const e in t)if(!Me(t[e]))return false;return true}return false}function Ie(t){if(null===t)return It;if("string"==typeof t)return Pt;if("boolean"==typeof t)return Ct;if("number"==typeof t)return zt;if(t instanceof ye)return Bt;if(t instanceof Ae)return Vt;if(t instanceof me)return Ft;if(t instanceof xe)return $t;if(t instanceof ve)return Lt;if(t instanceof _e)return Ot;if(t instanceof Se)return Dt;if(Array.isArray(t)){const e=t.length;let r;for(const e of t){const t=Ie(e);if(r){if(r===t)continue;r=Tt;break}r=t;}return Rt(r||Tt,e)}return Et}function ze(t){const e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof ye||t instanceof Ae||t instanceof xe||t instanceof ve||t instanceof _e||t instanceof Se?t.toString():JSON.stringify(t)}class Pe{constructor(t,e){this.type=t,this.value=e;}static parse(t,e){if(2!==t.length)return e.error(`'literal' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!Me(t[1]))return e.error("invalid value");const r=t[1];let n=Ie(r);const i=e.expectedType;return "array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new Pe(n,r)}evaluate(){return this.value}eachChild(){}outputDefined(){return true}}const Ce={string:Pt,number:zt,boolean:Ct,object:Et};class Be{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r,n=1;const i=t[0];if("array"===i){let i,s;if(t.length>2){const r=t[1];if("string"!=typeof r||!(r in Ce)||"object"===r)return e.error('The item type argument of "array" must be one of string, number, boolean',1);i=Ce[r],n++;}else i=Tt;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);s=t[2],n++;}r=Rt(i,s);}else {if(!Ce[i])throw new Error(`Types doesn't contain name = ${i}`);r=Ce[i];}const s=[];for(;nt.outputDefined()))}}const Ve={"to-boolean":Ct,"to-color":Bt,"to-number":zt,"to-string":Pt};class Ee{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[0];if(!Ve[r])throw new Error(`Can't parse ${r} as it is not part of the known types`);if(("to-boolean"===r||"to-string"===r)&&2!==t.length)return e.error("Expected one argument.");const n=Ve[r],i=[];for(let r=1;r4?`Invalid rgba value ${JSON.stringify(e)}: expected an array containing either three or four numeric values.`:ke(e[0],e[1],e[2],e[3]),!r))return new ye(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new be(r||`Could not parse color from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"padding":{let e;for(const r of this.args){e=r.evaluate(t);const n=ve.parse(e);if(n)return n}throw new be(`Could not parse padding from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"variableAnchorOffsetCollection":{let e;for(const r of this.args){e=r.evaluate(t);const n=_e.parse(e);if(n)return n}throw new be(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"number":{let e=null;for(const r of this.args){if(e=r.evaluate(t),null===e)return 0;const n=Number(e);if(!isNaN(n))return n}throw new be(`Could not convert ${JSON.stringify(e)} to number.`)}case"formatted":return xe.fromString(ze(this.args[0].evaluate(t)));case"resolvedImage":return Se.fromString(ze(this.args[0].evaluate(t)));case"projectionDefinition":return this.args[0].evaluate(t);default:return ze(this.args[0].evaluate(t))}}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}function Te(t,e,r=0,n=t.length-1,i=$e){for(;n>r;){if(n-r>600){const s=n-r+1,a=e-r+1,o=Math.log(s),l=.5*Math.exp(2*o/3),u=.5*Math.sqrt(o*l*(s-l)/s)*(a-s/2<0?-1:1);Te(t,e,Math.max(r,Math.floor(e-a*l/s+u)),Math.min(n,Math.floor(e+(s-a)*l/s+u)),i);}const s=t[e];let a=r,o=n;for(Fe(t,r,e),i(t[n],s)>0&&Fe(t,r,n);a0;)o--;}0===i(t[r],s)?Fe(t,r,o):(o++,Fe(t,o,n)),o<=e&&(r=o+1),e<=o&&(n=o-1);}}function Fe(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function $e(t,e){return te?1:0}function Le(t,e){if(t.length<=1)return [t];const r=[];let n,i;for(const e of t){const t=Oe(e);0!==t&&(e.area=Math.abs(t),undefined===i&&(i=t<0),i===t<0?(n&&r.push(n),n=[e]):n.push(e));}if(n&&r.push(n),e>1)for(let t=0;t`[${t}]`)).join(""),this.scope=i,this.errors=s,this.expectedType=n,this._isConstant=e;}parse(t,e,r,n,i={}){return e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)}_parse(t,e){function r(t,e,r){return "assert"===r?new Be(e,[t]):"coerce"===r?new Ee(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const n=t[0];if("string"!=typeof n)return this.error(`Expression name must be a string, but found ${typeof n} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const i=this.registry[n];if(i){let n=i.parse(t,this);if(!n)return null;if(this.expectedType){const t=this.expectedType,i=n.type;if("string"!==t.kind&&"number"!==t.kind&&"boolean"!==t.kind&&"object"!==t.kind&&"array"!==t.kind||"value"!==i.kind)if("projectionDefinition"!==t.kind||"string"!==i.kind&&"array"!==i.kind)if("color"!==t.kind&&"formatted"!==t.kind&&"resolvedImage"!==t.kind||"value"!==i.kind&&"string"!==i.kind)if("padding"!==t.kind||"value"!==i.kind&&"number"!==i.kind&&"array"!==i.kind)if("variableAnchorOffsetCollection"!==t.kind||"value"!==i.kind&&"array"!==i.kind){if(this.checkSubtype(t,i))return null}else n=r(n,t,e.typeAnnotation||"coerce");else n=r(n,t,e.typeAnnotation||"coerce");else n=r(n,t,e.typeAnnotation||"coerce");else n=r(n,t,e.typeAnnotation||"coerce");else n=r(n,t,e.typeAnnotation||"assert");}if(!(n instanceof Pe)&&"resolvedImage"!==n.type.kind&&this._isConstant(n)){const t=new Ne;try{n=new Pe(n.type,n.evaluate(t));}catch(t){return this.error(t.message),null}}return n}return this.error(`Unknown expression "${n}". If you wanted a literal array, use ["literal", [...]].`,0)}return this.error(undefined===t?"'undefined' value invalid. Use null instead.":"object"==typeof t?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof t} instead.`)}concat(t,e,r){const n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new Ue(this.registry,this._isConstant,n,e||null,i,this.errors)}error(t,...e){const r=`${this.key}${e.map((t=>`[${t}]`)).join("")}`;this.errors.push(new kt(r,t));}checkSubtype(t,e){const r=Ut(t,e);return r&&this.error(r),r}}class qe{constructor(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e;}evaluate(t){return this.result.evaluate(t)}eachChild(t){for(const e of this.bindings)t(e[1]);t(this.result);}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found ${t.length-1} instead.`);const r=[];for(let n=1;n=r.length)throw new be(`Array index out of bounds: ${e} > ${r.length-1}.`);if(e!==Math.floor(e))throw new be(`Array index must be an integer, but found ${e} instead.`);return r[e]}eachChild(t){t(this.index),t(this.input);}outputDefined(){return false}}class Xe{constructor(t,e){this.type=Ct,this.needle=t,this.haystack=e;}static parse(t,e){if(3!==t.length)return e.error(`Expected 2 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Tt),n=e.parse(t[2],2,Tt);return r&&n?qt(r.type,[Ct,Pt,zt,It,Tt])?new Xe(r,n):e.error(`Expected first argument to be of type boolean, string, number or null, but found ${jt(r.type)} instead`):null}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!r)return false;if(!Gt(e,["boolean","string","number","null"]))throw new be(`Expected first argument to be of type boolean, string, number or null, but found ${jt(Ie(e))} instead.`);if(!Gt(r,["string","array"]))throw new be(`Expected second argument to be of type array or string, but found ${jt(Ie(r))} instead.`);return r.indexOf(e)>=0}eachChild(t){t(this.needle),t(this.haystack);}outputDefined(){return true}}class Ke{constructor(t,e,r){this.type=zt,this.needle=t,this.haystack=e,this.fromIndex=r;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 3 or 4 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Tt),n=e.parse(t[2],2,Tt);if(!r||!n)return null;if(!qt(r.type,[Ct,Pt,zt,It,Tt]))return e.error(`Expected first argument to be of type boolean, string, number or null, but found ${jt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,zt);return i?new Ke(r,n,i):null}return new Ke(r,n)}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!Gt(e,["boolean","string","number","null"]))throw new be(`Expected first argument to be of type boolean, string, number or null, but found ${jt(Ie(e))} instead.`);let n;if(this.fromIndex&&(n=this.fromIndex.evaluate(t)),Gt(r,["string"])){const t=r.indexOf(e,n);return -1===t?-1:[...r.slice(0,t)].length}if(Gt(r,["array"]))return r.indexOf(e,n);throw new be(`Expected second argument to be of type array or string, but found ${jt(Ie(r))} instead.`)}eachChild(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex);}outputDefined(){return false}}class He{constructor(t,e,r,n,i,s){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=s;}static parse(t,e){if(t.length<5)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if(t.length%2!=1)return e.error("Expected an even number of arguments.");let r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);const i={},s=[];for(let a=2;aNumber.MAX_SAFE_INTEGER)return u.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof t&&Math.floor(t)!==t)return u.error("Numeric branch labels must be integer values.");if(r){if(u.checkSubtype(r,Ie(t)))return null}else r=Ie(t);if(undefined!==i[String(t)])return u.error("Branch labels must be unique.");i[String(t)]=s.length;}const c=e.parse(l,a,n);if(!c)return null;n=n||c.type,s.push(c);}const a=e.parse(t[1],1,Tt);if(!a)return null;const o=e.parse(t[t.length-1],t.length-1,n);return o?"value"!==a.type.kind&&e.concat(1).checkSubtype(r,a.type)?null:new He(r,n,a,i,s,o):null}evaluate(t){const e=this.input.evaluate(t);return (Ie(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)}eachChild(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))&&this.otherwise.outputDefined()}}class Ye{constructor(t,e,r){this.type=t,this.branches=e,this.otherwise=r;}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found only ${t.length-1}.`);if(t.length%2!=0)return e.error("Expected an odd number of arguments.");let r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);const n=[];for(let i=1;ie.outputDefined()))&&this.otherwise.outputDefined()}}class Je{constructor(t,e,r,n){this.type=t,this.input=e,this.beginIndex=r,this.endIndex=n;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 3 or 4 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Tt),n=e.parse(t[2],2,zt);if(!r||!n)return null;if(!qt(r.type,[Rt(Tt),Pt,Tt]))return e.error(`Expected first argument to be of type array or string, but found ${jt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,zt);return i?new Je(r.type,r,n,i):null}return new Je(r.type,r,n)}evaluate(t){const e=this.input.evaluate(t),r=this.beginIndex.evaluate(t);let n;if(this.endIndex&&(n=this.endIndex.evaluate(t)),Gt(e,["string"]))return [...e].slice(r,n).join("");if(Gt(e,["array"]))return e.slice(r,n);throw new be(`Expected first argument to be of type array or string, but found ${jt(Ie(e))} instead.`)}eachChild(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex);}outputDefined(){return false}}function We(t,e){const r=t.length-1;let n,i,s=0,a=r,o=0;for(;s<=a;)if(o=Math.floor((s+a)/2),n=t[o],i=t[o+1],n<=e){if(o===r||ee))throw new be("Input is not a number.");a=o-1;}return 0}class Qe{constructor(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(const[t,e]of r)this.labels.push(t),this.outputs.push(e);}static parse(t,e){if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");const r=e.parse(t[1],1,zt);if(!r)return null;const n=[];let i=null;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);for(let r=1;r=s)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',o);const u=e.parse(a,l,i);if(!u)return null;i=i||u.type,n.push([s,u]);}return new Qe(i,r,n)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[We(e,n)].evaluate(t)}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function tr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var er,rr,nr=function(){if(rr)return er;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return rr=1,er=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(undefined===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},er}(),ir=tr(nr);class sr{constructor(t,e,r,n,i){this.type=t,this.operator=e,this.interpolation=r,this.input=n,this.labels=[],this.outputs=[];for(const[t,e]of i)this.labels.push(t),this.outputs.push(e);}static interpolationFactor(t,e,r,n){let i=0;if("exponential"===t.name)i=ar(e,t.base,r,n);else if("linear"===t.name)i=ar(e,1,r,n);else if("cubic-bezier"===t.name){const s=t.controlPoints;i=new ir(s[0],s[1],s[2],s[3]).solve(ar(e,1,r,n));}return i}static parse(t,e){let[r,n,i,...s]=t;if(!Array.isArray(n)||0===n.length)return e.error("Expected an interpolation type expression.",1);if("linear"===n[0])n={name:"linear"};else if("exponential"===n[0]){const t=n[1];if("number"!=typeof t)return e.error("Exponential interpolation requires a numeric base.",1,1);n={name:"exponential",base:t};}else {if("cubic-bezier"!==n[0])return e.error(`Unknown interpolation type ${String(n[0])}`,1,0);{const t=n.slice(1);if(4!==t.length||t.some((t=>"number"!=typeof t||t<0||t>1)))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:t};}}if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(i=e.parse(i,2,zt),!i)return null;const a=[];let o=null;"interpolate-hcl"===r||"interpolate-lab"===r?o=Bt:e.expectedType&&"value"!==e.expectedType.kind&&(o=e.expectedType);for(let t=0;t=r)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',i);const u=e.parse(n,l,o);if(!u)return null;o=o||u.type,a.push([r,u]);}return Zt(o,zt)||Zt(o,Vt)||Zt(o,Bt)||Zt(o,Lt)||Zt(o,Ot)||Zt(o,Rt(zt))?new sr(o,r,n,i,a):e.error(`Type ${jt(o)} is not interpolatable.`)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);const s=We(e,n),a=sr.interpolationFactor(this.interpolation,n,e[s],e[s+1]),o=r[s].evaluate(t),l=r[s+1].evaluate(t);switch(this.operator){case"interpolate":switch(this.type.kind){case"number":return fe(o,l,a);case"color":return ye.interpolate(o,l,a);case"padding":return ve.interpolate(o,l,a);case"variableAnchorOffsetCollection":return _e.interpolate(o,l,a);case"array":return de(o,l,a);case"projectionDefinition":return Ae.interpolate(o,l,a)}case"interpolate-hcl":return ye.interpolate(o,l,a,"hcl");case"interpolate-lab":return ye.interpolate(o,l,a,"lab")}}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function ar(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}const or={color:ye.interpolate,number:fe,padding:ve.interpolate,variableAnchorOffsetCollection:_e.interpolate,array:de};class lr{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r=null;const n=e.expectedType;n&&"value"!==n.kind&&(r=n);const i=[];for(const n of t.slice(1)){const t=e.parse(n,1+i.length,r,undefined,{typeAnnotation:"omit"});if(!t)return null;r=r||t.type,i.push(t);}if(!r)throw new Error("No output type");const s=n&&i.some((t=>Ut(n,t.type)));return new lr(s?Tt:r,i)}evaluate(t){let e,r=null,n=0;for(const i of this.args)if(n++,r=i.evaluate(t),r&&r instanceof Se&&!r.available&&(e||(e=r.name),r=null,n===this.args.length&&(r=e)),null!==r)break;return r}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}function ur(t,e){return "=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function cr(t,e,r,n){return 0===n.compare(e,r)}function hr(t,e,r){const n="=="!==t&&"!="!==t;return class i{constructor(t,e,r){this.type=Ct,this.lhs=t,this.rhs=e,this.collator=r,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind;}static parse(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");const r=t[0];let s=e.parse(t[1],1,Tt);if(!s)return null;if(!ur(r,s.type))return e.concat(1).error(`"${r}" comparisons are not supported for type '${jt(s.type)}'.`);let a=e.parse(t[2],2,Tt);if(!a)return null;if(!ur(r,a.type))return e.concat(2).error(`"${r}" comparisons are not supported for type '${jt(a.type)}'.`);if(s.type.kind!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error(`Cannot compare types '${jt(s.type)}' and '${jt(a.type)}'.`);n&&("value"===s.type.kind&&"value"!==a.type.kind?s=new Be(a.type,[s]):"value"!==s.type.kind&&"value"===a.type.kind&&(a=new Be(s.type,[a])));let o=null;if(4===t.length){if("string"!==s.type.kind&&"string"!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error("Cannot use collator to compare non-string types.");if(o=e.parse(t[3],3,Ft),!o)return null}return new i(s,a,o)}evaluate(i){const s=this.lhs.evaluate(i),a=this.rhs.evaluate(i);if(n&&this.hasUntypedArgument){const e=Ie(s),r=Ie(a);if(e.kind!==r.kind||"string"!==e.kind&&"number"!==e.kind)throw new be(`Expected arguments for "${t}" to be (string, string) or (number, number), but found (${e.kind}, ${r.kind}) instead.`)}if(this.collator&&!n&&this.hasUntypedArgument){const t=Ie(s),r=Ie(a);if("string"!==t.kind||"string"!==r.kind)return e(i,s,a)}return this.collator?r(i,s,a,this.collator.evaluate(i)):e(i,s,a)}eachChild(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator);}outputDefined(){return true}}}const pr=hr("==",(function(t,e,r){return e===r}),cr),fr=hr("!=",(function(t,e,r){return e!==r}),(function(t,e,r,n){return !cr(0,e,r,n)})),dr=hr("<",(function(t,e,r){return e",(function(t,e,r){return e>r}),(function(t,e,r,n){return n.compare(e,r)>0})),mr=hr("<=",(function(t,e,r){return e<=r}),(function(t,e,r,n){return n.compare(e,r)<=0})),gr=hr(">=",(function(t,e,r){return e>=r}),(function(t,e,r,n){return n.compare(e,r)>=0}));class xr{constructor(t,e,r){this.type=Ft,this.locale=r,this.caseSensitive=t,this.diacriticSensitive=e;}static parse(t,e){if(2!==t.length)return e.error("Expected one argument.");const r=t[1];if("object"!=typeof r||Array.isArray(r))return e.error("Collator options argument must be an object.");const n=e.parse(undefined!==r["case-sensitive"]&&r["case-sensitive"],1,Ct);if(!n)return null;const i=e.parse(undefined!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,Ct);if(!i)return null;let s=null;return r.locale&&(s=e.parse(r.locale,1,Pt),!s)?null:new xr(n,i,s)}evaluate(t){return new me(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)}eachChild(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale);}outputDefined(){return false}}class vr{constructor(t,e,r,n,i){this.type=Pt,this.number=t,this.locale=e,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i;}static parse(t,e){if(3!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,zt);if(!r)return null;const n=t[2];if("object"!=typeof n||Array.isArray(n))return e.error("NumberFormat options argument must be an object.");let i=null;if(n.locale&&(i=e.parse(n.locale,1,Pt),!i))return null;let s=null;if(n.currency&&(s=e.parse(n.currency,1,Pt),!s))return null;let a=null;if(n["min-fraction-digits"]&&(a=e.parse(n["min-fraction-digits"],1,zt),!a))return null;let o=null;return n["max-fraction-digits"]&&(o=e.parse(n["max-fraction-digits"],1,zt),!o)?null:new vr(r,i,s,a,o)}evaluate(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):undefined,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):undefined,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):undefined}).format(this.number.evaluate(t))}eachChild(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits);}outputDefined(){return false}}class br{constructor(t){this.type=$t,this.sections=t;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[1];if(!Array.isArray(r)&&"object"==typeof r)return e.error("First argument must be an image or text section.");const n=[];let i=false;for(let r=1;r<=t.length-1;++r){const s=t[r];if(i&&"object"==typeof s&&!Array.isArray(s)){i=false;let t=null;if(s["font-scale"]&&(t=e.parse(s["font-scale"],1,zt),!t))return null;let r=null;if(s["text-font"]&&(r=e.parse(s["text-font"],1,Rt(Pt)),!r))return null;let a=null;if(s["text-color"]&&(a=e.parse(s["text-color"],1,Bt),!a))return null;const o=n[n.length-1];o.scale=t,o.font=r,o.textColor=a;}else {const s=e.parse(t[r],1,Tt);if(!s)return null;const a=s.type.kind;if("string"!==a&&"value"!==a&&"null"!==a&&"resolvedImage"!==a)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=true,n.push({content:s,scale:null,font:null,textColor:null});}}return new br(n)}evaluate(t){return new xe(this.sections.map((e=>{const r=e.content.evaluate(t);return Ie(r)===Dt?new ge("",r,null,null,null):new ge(ze(r),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null)})))}eachChild(t){for(const e of this.sections)t(e.content),e.scale&&t(e.scale),e.font&&t(e.font),e.textColor&&t(e.textColor);}outputDefined(){return false}}class wr{constructor(t){this.type=Dt,this.input=t;}static parse(t,e){if(2!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,Pt);return r?new wr(r):e.error("No image name provided.")}evaluate(t){const e=this.input.evaluate(t),r=Se.fromString(e);return r&&t.availableImages&&(r.available=t.availableImages.indexOf(e)>-1),r}eachChild(t){t(this.input);}outputDefined(){return false}}class _r{constructor(t){this.type=zt,this.input=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error(`Expected argument of type string or array, but found ${jt(r.type)} instead.`):new _r(r):null}evaluate(t){const e=this.input.evaluate(t);if("string"==typeof e)return [...e].length;if(Array.isArray(e))return e.length;throw new be(`Expected value to be of type string or array, but found ${jt(Ie(e))} instead.`)}eachChild(t){t(this.input);}outputDefined(){return false}}const Sr=8192;function Ar(t,e){const r=(180+t[0])/360,n=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,i=Math.pow(2,e.z);return [Math.round(r*i*Sr),Math.round(n*i*Sr)]}function kr(t,e){const r=Math.pow(2,e.z);return [(i=(t[0]/Sr+e.x)/r,360*i-180),(n=(t[1]/Sr+e.y)/r,360/Math.PI*Math.atan(Math.exp((180-360*n)*Math.PI/180))-90)];var n,i;}function Mr(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.min(t[1],e[1]),t[2]=Math.max(t[2],e[0]),t[3]=Math.max(t[3],e[1]);}function Ir(t,e){return !(t[0]<=e[0]||t[2]>=e[2]||t[1]<=e[1]||t[3]>=e[3])}function zr(t,e,r){const n=t[0]-e[0],i=t[1]-e[1],s=t[0]-r[0],a=t[1]-r[1];return n*a-s*i==0&&n*s<=0&&i*a<=0}function Pr(t,e,r,n){return 0!=(i=[n[0]-r[0],n[1]-r[1]])[0]*(s=[e[0]-t[0],e[1]-t[1]])[1]-i[1]*s[0]&&!(!Fr(t,e,r,n)||!Fr(r,n,t,e));var i,s;}function Cr(t,e,r){for(const n of r)for(let r=0;r(i=t)[1]!=(a=o[e+1])[1]>i[1]&&i[0]<(a[0]-s[0])*(i[1]-s[1])/(a[1]-s[1])+s[0]&&(n=!n);}var i,s,a;return n}function Vr(t,e){for(const r of e)if(Br(t,r))return true;return false}function Er(t,e){for(const r of t)if(!Br(r,e))return false;for(let r=0;r0&&o<0||a<0&&o>0}function $r(t,e,r){const n=[];for(let i=0;ir[2]){const e=.5*n;let i=t[0]-r[0]>e?-n:r[0]-t[0]>e?n:0;0===i&&(i=t[0]-r[2]>e?-n:r[2]-t[0]>e?n:0),t[0]+=i;}Mr(e,t);}function Or(t,e,r,n){const i=Math.pow(2,n.z)*Sr,s=[n.x*Sr,n.y*Sr],a=[];for(const n of t)for(const t of n){const n=[t.x+s[0],t.y+s[1]];Dr(n,e,r,i),a.push(n);}return a}function Rr(t,e,r,n){const i=Math.pow(2,n.z)*Sr,s=[n.x*Sr,n.y*Sr],a=[];for(const r of t){const t=[];for(const n of r){const r=[n.x+s[0],n.y+s[1]];Mr(e,r),t.push(r);}a.push(t);}if(e[2]-e[0]<=i/2){(o=e)[0]=o[1]=1/0,o[2]=o[3]=-1/0;for(const t of a)for(const n of t)Dr(n,e,r,i);}var o;return a}class jr{constructor(t,e){this.type=Ct,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'within' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Me(t[1])){const e=t[1];if("FeatureCollection"===e.type){const t=[];for(const r of e.features){const{type:e,coordinates:n}=r.geometry;"Polygon"===e&&t.push(n),"MultiPolygon"===e&&t.push(...n);}if(t.length)return new jr(e,{type:"MultiPolygon",coordinates:t})}else if("Feature"===e.type){const t=e.geometry.type;if("Polygon"===t||"MultiPolygon"===t)return new jr(e,e.geometry)}else if("Polygon"===e.type||"MultiPolygon"===e.type)return new jr(e,e)}return e.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryDollarType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=$r(e.coordinates,n,i),a=Or(t.geometry(),r,n,i);if(!Ir(r,n))return false;for(const t of a)if(!Br(t,s))return false}if("MultiPolygon"===e.type){const s=Lr(e.coordinates,n,i),a=Or(t.geometry(),r,n,i);if(!Ir(r,n))return false;for(const t of a)if(!Vr(t,s))return false}return true}(t,this.geometries);if("LineString"===t.geometryDollarType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=$r(e.coordinates,n,i),a=Rr(t.geometry(),r,n,i);if(!Ir(r,n))return false;for(const t of a)if(!Er(t,s))return false}if("MultiPolygon"===e.type){const s=Lr(e.coordinates,n,i),a=Rr(t.geometry(),r,n,i);if(!Ir(r,n))return false;for(const t of a)if(!Tr(t,s))return false}return true}(t,this.geometries)}return false}eachChild(){}outputDefined(){return true}}let Nr=class{constructor(t=[],e=((t,e)=>te?1:0)){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}};const Ur=1/298.257223563,qr=Ur*(2-Ur),Gr=Math.PI/180;class Zr{constructor(t){const e=6378.137*Gr*1e3,r=Math.cos(t*Gr),n=1/(1-qr*(1-r*r)),i=Math.sqrt(n);this.kx=e*i*r,this.ky=e*i*n*(1-qr);}distance(t,e){const r=this.wrap(t[0]-e[0])*this.kx,n=(t[1]-e[1])*this.ky;return Math.sqrt(r*r+n*n)}pointOnLine(t,e){let r,n,i,s,a=1/0;for(let o=0;o1?(l=t[o+1][0],u=t[o+1][1]):p>0&&(l+=c/this.kx*p,u+=h/this.ky*p)),c=this.wrap(e[0]-l)*this.kx,h=(e[1]-u)*this.ky;const f=c*c+h*h;f180;)t-=360;return t}}function Xr(t,e){return e[0]-t[0]}function Kr(t){return t[1]-t[0]+1}function Hr(t,e){return t[1]>=t[0]&&t[1]t[1])return [null,null];const r=Kr(t);if(e){if(2===r)return [t,null];const e=Math.floor(r/2);return [[t[0],t[0]+e],[t[0]+e,t[1]]]}if(1===r)return [t,null];const n=Math.floor(r/2)-1;return [[t[0],t[0]+n],[t[0]+n+1,t[1]]]}function Jr(t,e){if(!Hr(e,t.length))return [1/0,1/0,-1/0,-1/0];const r=[1/0,1/0,-1/0,-1/0];for(let n=e[0];n<=e[1];++n)Mr(r,t[n]);return r}function Wr(t){const e=[1/0,1/0,-1/0,-1/0];for(const r of t)for(const t of r)Mr(e,t);return e}function Qr(t){return t[0]!==-1/0&&t[1]!==-1/0&&t[2]!==1/0&&t[3]!==1/0}function tn(t,e,r){if(!Qr(t)||!Qr(e))return NaN;let n=0,i=0;return t[2]e[2]&&(n=t[0]-e[2]),t[1]>e[3]&&(i=t[1]-e[3]),t[3]=n)return n;if(Ir(i,s)){if(ln(t,e))return 0}else if(ln(e,t))return 0;let a=1/0;for(const n of t)for(let t=0,i=n.length,s=i-1;t0;){const i=a.pop();if(i[0]>=s)continue;const l=i[1],u=e?50:100;if(Kr(l)<=u){if(!Hr(l,t.length))return NaN;if(e){const e=on(t,l,r,n);if(isNaN(e)||0===e)return e;s=Math.min(s,e);}else for(let e=l[0];e<=l[1];++e){const i=an(t[e],r,n);if(s=Math.min(s,i),0===s)return 0}}else {const r=Yr(l,e);cn(a,s,n,t,o,r[0]),cn(a,s,n,t,o,r[1]);}}return s}function fn(t,e,r,n,i,s=1/0){let a=Math.min(s,i.distance(t[0],r[0]));if(0===a)return a;const o=new Nr([[0,[0,t.length-1],[0,r.length-1]]],Xr);for(;o.length>0;){const s=o.pop();if(s[0]>=a)continue;const l=s[1],u=s[2],c=e?50:100,h=n?50:100;if(Kr(l)<=c&&Kr(u)<=h){if(!Hr(l,t.length)&&Hr(u,r.length))return NaN;let s;if(e&&n)s=nn(t,l,r,u,i),a=Math.min(a,s);else if(e&&!n){const e=t.slice(l[0],l[1]+1);for(let t=u[0];t<=u[1];++t)if(s=en(r[t],e,i),a=Math.min(a,s),0===a)return a}else if(!e&&n){const e=r.slice(u[0],u[1]+1);for(let r=l[0];r<=l[1];++r)if(s=en(t[r],e,i),a=Math.min(a,s),0===a)return a}else s=sn(t,l,r,u,i),a=Math.min(a,s);}else {const s=Yr(l,e),c=Yr(u,n);hn(o,a,i,t,r,s[0],c[0]),hn(o,a,i,t,r,s[0],c[1]),hn(o,a,i,t,r,s[1],c[0]),hn(o,a,i,t,r,s[1],c[1]);}}return a}function dn(t){return "MultiPolygon"===t.type?t.coordinates.map((t=>({type:"Polygon",coordinates:t}))):"MultiLineString"===t.type?t.coordinates.map((t=>({type:"LineString",coordinates:t}))):"MultiPoint"===t.type?t.coordinates.map((t=>({type:"Point",coordinates:t}))):[t]}class yn{constructor(t,e){this.type=zt,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'distance' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Me(t[1])){const e=t[1];if("FeatureCollection"===e.type)return new yn(e,e.features.map((t=>dn(t.geometry))).flat());if("Feature"===e.type)return new yn(e,dn(e.geometry));if("type"in e&&"coordinates"in e)return new yn(e,dn(e))}return e.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>kr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new Zr(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case"Point":s=Math.min(s,fn(n,false,[t.coordinates],false,i,s));break;case"LineString":s=Math.min(s,fn(n,false,t.coordinates,true,i,s));break;case"Polygon":s=Math.min(s,pn(n,false,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>kr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new Zr(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case"Point":s=Math.min(s,fn(n,true,[t.coordinates],false,i,s));break;case"LineString":s=Math.min(s,fn(n,true,t.coordinates,true,i,s));break;case"Polygon":s=Math.min(s,pn(n,true,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("Polygon"===t.geometryType())return function(t,e){const r=t.geometry();if(0===r.length||0===r[0].length)return NaN;const n=Le(r,0).map((e=>e.map((e=>e.map((e=>kr([e.x,e.y],t.canonical))))))),i=new Zr(n[0][0][0][1]);let s=1/0;for(const t of e)for(const e of n){switch(t.type){case"Point":s=Math.min(s,pn([t.coordinates],false,e,i,s));break;case"LineString":s=Math.min(s,pn(t.coordinates,true,e,i,s));break;case"Polygon":s=Math.min(s,un(e,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries)}return NaN}eachChild(){}outputDefined(){return true}}const mn={"==":pr,"!=":fr,">":yr,"<":dr,">=":gr,"<=":mr,array:Be,at:Ze,boolean:Be,case:Ye,coalesce:lr,collator:xr,format:br,image:wr,in:Xe,"index-of":Ke,interpolate:sr,"interpolate-hcl":sr,"interpolate-lab":sr,length:_r,let:qe,literal:Pe,match:He,number:Be,"number-format":vr,object:Be,slice:Je,step:Qe,string:Be,"to-boolean":Ee,"to-color":Ee,"to-number":Ee,"to-string":Ee,var:Ge,within:jr,distance:yn};class gn{constructor(t,e,r,n){this.name=t,this.type=e,this._evaluate=r,this.args=n;}evaluate(t){return this._evaluate(t,this.args)}eachChild(t){this.args.forEach(t);}outputDefined(){return false}static parse(t,e){const r=t[0],n=gn.definitions[r];if(!n)return e.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0);const i=Array.isArray(n)?n[0]:n.type,s=Array.isArray(n)?[[n[1],n[2]]]:n.overloads,a=s.filter((([e])=>!Array.isArray(e)||e.length===t.length-1));let o=null;for(const[n,s]of a){o=new Ue(e.registry,_n,e.path,null,e.scope);const a=[];let l=false;for(let e=1;e{return e=t,Array.isArray(e)?`(${e.map(jt).join(", ")})`:`(${jt(e.type)}...)`;var e;})).join(" | "),n=[];for(let r=1;r{r=e?r&&_n(t):r&&t instanceof Pe;})),!!r&&Sn(t)&&kn(t,["zoom","heatmap-density","line-progress","accumulated","is-supported-script"])}function Sn(t){if(t instanceof gn){if("get"===t.name&&1===t.args.length)return false;if("feature-state"===t.name)return false;if("has"===t.name&&1===t.args.length)return false;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return false;if(/^filter-/.test(t.name))return false}if(t instanceof jr)return false;if(t instanceof yn)return false;let e=true;return t.eachChild((t=>{e&&!Sn(t)&&(e=false);})),e}function An(t){if(t instanceof gn&&"feature-state"===t.name)return false;let e=true;return t.eachChild((t=>{e&&!An(t)&&(e=false);})),e}function kn(t,e){if(t instanceof gn&&e.indexOf(t.name)>=0)return false;let r=true;return t.eachChild((t=>{r&&!kn(t,e)&&(r=false);})),r}function Mn(t){return {result:"success",value:t}}function In(t){return {result:"error",value:t}}function zn(t){return "data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function Pn(t){return !!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function Cn(t){return !!t.expression&&t.expression.interpolated}function Bn(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function Vn(t){return "object"==typeof t&&null!==t&&!Array.isArray(t)}function En(t){return t}function Tn(t,e){const r="color"===e.type,n=t.stops&&"object"==typeof t.stops[0][0],i=n||!(n||undefined!==t.property),s=t.type||(Cn(e)?"exponential":"interval");if(r||"padding"===e.type){const n=r?ye.parse:ve.parse;(t=At({},t)).stops&&(t.stops=t.stops.map((t=>[t[0],n(t[1])]))),t.default=n(t.default?t.default:e.default);}if(t.colorSpace&&"rgb"!==(a=t.colorSpace)&&"hcl"!==a&&"lab"!==a)throw new Error(`Unknown color space: "${t.colorSpace}"`);var a;let o,l,u;if("exponential"===s)o=Dn;else if("interval"===s)o=Ln;else if("categorical"===s){o=$n,l=Object.create(null);for(const e of t.stops)l[e[0]]=e[1];u=typeof t.stops[0][0];}else {if("identity"!==s)throw new Error(`Unknown function type "${s}"`);o=On;}if(n){const r={},n=[];for(let e=0;et[0])),evaluate:({zoom:r},n)=>Dn({stops:i,base:t.base},e,r).evaluate(r,n)}}if(i){const r="exponential"===s?{name:"exponential",base:undefined!==t.base?t.base:1}:null;return {kind:"camera",interpolationType:r,interpolationFactor:sr.interpolationFactor.bind(undefined,r),zoomStops:t.stops.map((t=>t[0])),evaluate:({zoom:r})=>o(t,e,r,l,u)}}return {kind:"source",evaluate(r,n){const i=n&&n.properties?n.properties[t.property]:undefined;return undefined===i?Fn(t.default,e.default):o(t,e,i,l,u)}}}function Fn(t,e,r){return undefined!==t?t:undefined!==e?e:undefined!==r?r:undefined}function $n(t,e,r,n,i){return Fn(typeof r===i?n[r]:undefined,t.default,e.default)}function Ln(t,e,r){if("number"!==Bn(r))return Fn(t.default,e.default);const n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];const i=We(t.stops.map((t=>t[0])),r);return t.stops[i][1]}function Dn(t,e,r){const n=undefined!==t.base?t.base:1;if("number"!==Bn(r))return Fn(t.default,e.default);const i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];const s=We(t.stops.map((t=>t[0])),r),a=function(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[s][0],t.stops[s+1][0]),o=t.stops[s][1],l=t.stops[s+1][1],u=or[e.type]||En;return "function"==typeof o.evaluate?{evaluate(...e){const r=o.evaluate.apply(undefined,e),n=l.evaluate.apply(undefined,e);if(undefined!==r&&undefined!==n)return u(r,n,a,t.colorSpace)}}:u(o,l,a,t.colorSpace)}function On(t,e,r){switch(e.type){case"color":r=ye.parse(r);break;case"formatted":r=xe.fromString(r.toString());break;case"resolvedImage":r=Se.fromString(r.toString());break;case"padding":r=ve.parse(r);break;default:Bn(r)===e.type||"enum"===e.type&&e.values[r]||(r=undefined);}return Fn(r,t.default,e.default)}gn.register(mn,{error:[{kind:"error"},[Pt],(t,[e])=>{throw new be(e.evaluate(t))}],typeof:[Pt,[Tt],(t,[e])=>jt(Ie(e.evaluate(t)))],"to-rgba":[Rt(zt,4),[Bt],(t,[e])=>{const[r,n,i,s]=e.evaluate(t).rgb;return [255*r,255*n,255*i,s]}],rgb:[Bt,[zt,zt,zt],xn],rgba:[Bt,[zt,zt,zt,zt],xn],has:{type:Ct,overloads:[[[Pt],(t,[e])=>vn(e.evaluate(t),t.properties())],[[Pt,Et],(t,[e,r])=>vn(e.evaluate(t),r.evaluate(t))]]},get:{type:Tt,overloads:[[[Pt],(t,[e])=>bn(e.evaluate(t),t.properties())],[[Pt,Et],(t,[e,r])=>bn(e.evaluate(t),r.evaluate(t))]]},"feature-state":[Tt,[Pt],(t,[e])=>bn(e.evaluate(t),t.featureState||{})],properties:[Et,[],t=>t.properties()],"geometry-type":[Pt,[],t=>t.geometryType()],id:[Tt,[],t=>t.id()],zoom:[zt,[],t=>t.globals.zoom],"heatmap-density":[zt,[],t=>t.globals.heatmapDensity||0],"line-progress":[zt,[],t=>t.globals.lineProgress||0],accumulated:[Tt,[],t=>undefined===t.globals.accumulated?null:t.globals.accumulated],"+":[zt,wn(zt),(t,e)=>{let r=0;for(const n of e)r+=n.evaluate(t);return r}],"*":[zt,wn(zt),(t,e)=>{let r=1;for(const n of e)r*=n.evaluate(t);return r}],"-":{type:zt,overloads:[[[zt,zt],(t,[e,r])=>e.evaluate(t)-r.evaluate(t)],[[zt],(t,[e])=>-e.evaluate(t)]]},"/":[zt,[zt,zt],(t,[e,r])=>e.evaluate(t)/r.evaluate(t)],"%":[zt,[zt,zt],(t,[e,r])=>e.evaluate(t)%r.evaluate(t)],ln2:[zt,[],()=>Math.LN2],pi:[zt,[],()=>Math.PI],e:[zt,[],()=>Math.E],"^":[zt,[zt,zt],(t,[e,r])=>Math.pow(e.evaluate(t),r.evaluate(t))],sqrt:[zt,[zt],(t,[e])=>Math.sqrt(e.evaluate(t))],log10:[zt,[zt],(t,[e])=>Math.log(e.evaluate(t))/Math.LN10],ln:[zt,[zt],(t,[e])=>Math.log(e.evaluate(t))],log2:[zt,[zt],(t,[e])=>Math.log(e.evaluate(t))/Math.LN2],sin:[zt,[zt],(t,[e])=>Math.sin(e.evaluate(t))],cos:[zt,[zt],(t,[e])=>Math.cos(e.evaluate(t))],tan:[zt,[zt],(t,[e])=>Math.tan(e.evaluate(t))],asin:[zt,[zt],(t,[e])=>Math.asin(e.evaluate(t))],acos:[zt,[zt],(t,[e])=>Math.acos(e.evaluate(t))],atan:[zt,[zt],(t,[e])=>Math.atan(e.evaluate(t))],min:[zt,wn(zt),(t,e)=>Math.min(...e.map((e=>e.evaluate(t))))],max:[zt,wn(zt),(t,e)=>Math.max(...e.map((e=>e.evaluate(t))))],abs:[zt,[zt],(t,[e])=>Math.abs(e.evaluate(t))],round:[zt,[zt],(t,[e])=>{const r=e.evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[zt,[zt],(t,[e])=>Math.floor(e.evaluate(t))],ceil:[zt,[zt],(t,[e])=>Math.ceil(e.evaluate(t))],"filter-==":[Ct,[Pt,Tt],(t,[e,r])=>t.properties()[e.value]===r.value],"filter-id-==":[Ct,[Tt],(t,[e])=>t.id()===e.value],"filter-type-==":[Ct,[Pt],(t,[e])=>t.geometryDollarType()===e.value],"filter-<":[Ct,[Pt,Tt],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n{const r=t.id(),n=e.value;return typeof r==typeof n&&r":[Ct,[Pt,Tt],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>i}],"filter-id->":[Ct,[Tt],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>n}],"filter-<=":[Ct,[Pt,Tt],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n<=i}],"filter-id-<=":[Ct,[Tt],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r<=n}],"filter->=":[Ct,[Pt,Tt],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>=i}],"filter-id->=":[Ct,[Tt],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>=n}],"filter-has":[Ct,[Tt],(t,[e])=>e.value in t.properties()],"filter-has-id":[Ct,[],t=>null!==t.id()&&undefined!==t.id()],"filter-type-in":[Ct,[Rt(Pt)],(t,[e])=>e.value.indexOf(t.geometryDollarType())>=0],"filter-id-in":[Ct,[Rt(Tt)],(t,[e])=>e.value.indexOf(t.id())>=0],"filter-in-small":[Ct,[Pt,Rt(Tt)],(t,[e,r])=>r.value.indexOf(t.properties()[e.value])>=0],"filter-in-large":[Ct,[Pt,Rt(Tt)],(t,[e,r])=>function(t,e,r,n){for(;r<=n;){const i=r+n>>1;if(e[i]===t)return true;e[i]>t?n=i-1:r=i+1;}return false}(t.properties()[e.value],r.value,0,r.value.length-1)],all:{type:Ct,overloads:[[[Ct,Ct],(t,[e,r])=>e.evaluate(t)&&r.evaluate(t)],[wn(Ct),(t,e)=>{for(const r of e)if(!r.evaluate(t))return false;return true}]]},any:{type:Ct,overloads:[[[Ct,Ct],(t,[e,r])=>e.evaluate(t)||r.evaluate(t)],[wn(Ct),(t,e)=>{for(const r of e)if(r.evaluate(t))return true;return false}]]},"!":[Ct,[Ct],(t,[e])=>!e.evaluate(t)],"is-supported-script":[Ct,[Pt],(t,[e])=>{const r=t.globals&&t.globals.isSupportedScript;return !r||r(e.evaluate(t))}],upcase:[Pt,[Pt],(t,[e])=>e.evaluate(t).toUpperCase()],downcase:[Pt,[Pt],(t,[e])=>e.evaluate(t).toLowerCase()],concat:[Pt,wn(Tt),(t,e)=>e.map((e=>ze(e.evaluate(t)))).join("")],"resolved-locale":[Pt,[Ft],(t,[e])=>e.evaluate(t).resolvedLocale()]});class Rn{constructor(t,e){var r;this.expression=t,this._warningHistory={},this._evaluator=new Ne,this._defaultValue=e?"color"===(r=e).type&&Vn(r.default)?new ye(0,0,0,0):"color"===r.type?ye.parse(r.default)||null:"padding"===r.type?ve.parse(r.default)||null:"variableAnchorOffsetCollection"===r.type?_e.parse(r.default)||null:"projectionDefinition"===r.type?Ae.parse(r.default)||null:undefined===r.default?null:r.default:null,this._enumValues=e&&"enum"===e.type?e.values:null;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=r,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s,this.expression.evaluate(this._evaluator)}evaluate(t,e,r,n,i,s){this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s||null;try{const t=this.expression.evaluate(this._evaluator);if(null==t||"number"==typeof t&&t!=t)return this._defaultValue;if(this._enumValues&&!(t in this._enumValues))throw new be(`Expected value to be one of ${Object.keys(this._enumValues).map((t=>JSON.stringify(t))).join(", ")}, but found ${JSON.stringify(t)} instead.`);return t}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=true,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}}}function jn(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in mn}function Nn(t,e){const r=new Ue(mn,_n,[],e?function(t){const e={color:Bt,string:Pt,number:zt,enum:Pt,boolean:Ct,formatted:$t,padding:Lt,projectionDefinition:Vt,resolvedImage:Dt,variableAnchorOffsetCollection:Ot};return "array"===t.type?Rt(e[t.value]||Tt,t.length):e[t.type]}(e):undefined),n=r.parse(t,undefined,undefined,undefined,e&&"string"===e.type?{typeAnnotation:"coerce"}:undefined);return n?Mn(new Rn(n,e)):In(r.errors)}class Un{constructor(t,e){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!An(e.expression);}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._styleExpression.evaluate(t,e,r,n,i,s)}}class qn{constructor(t,e,r,n){this.kind=t,this.zoomStops=r,this._styleExpression=e,this.isStateDependent="camera"!==t&&!An(e.expression),this.interpolationType=n;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._styleExpression.evaluate(t,e,r,n,i,s)}interpolationFactor(t,e,r){return this.interpolationType?sr.interpolationFactor(this.interpolationType,t,e,r):0}}function Gn(t,e){const r=Nn(t,e);if("error"===r.result)return r;const n=r.value.expression,i=Sn(n);if(!i&&!zn(e))return In([new kt("","data expressions not supported")]);const s=kn(n,["zoom"]);if(!s&&!Pn(e))return In([new kt("","zoom expressions not supported")]);const a=Xn(n);return a||s?a instanceof kt?In([a]):a instanceof sr&&!Cn(e)?In([new kt("",'"interpolate" expressions cannot be used with this property')]):Mn(a?new qn(i?"camera":"composite",r.value,a.labels,a instanceof sr?a.interpolation:undefined):new Un(i?"constant":"source",r.value)):In([new kt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}class Zn{constructor(t,e){this._parameters=t,this._specification=e,At(this,Tn(this._parameters,this._specification));}static deserialize(t){return new Zn(t._parameters,t._specification)}static serialize(t){return {_parameters:t._parameters,_specification:t._specification}}}function Xn(t){let e=null;if(t instanceof qe)e=Xn(t.result);else if(t instanceof lr){for(const r of t.args)if(e=Xn(r),e)break}else (t instanceof Qe||t instanceof sr)&&t.input instanceof gn&&"zoom"===t.input.name&&(e=t);return e instanceof kt||t.eachChild((t=>{const r=Xn(t);r instanceof kt?e=r:!e&&r?e=new kt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):e&&r&&e!==r&&(e=new kt("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));})),e}function Kn(t){if(true===t||false===t)return true;if(!Array.isArray(t)||0===t.length)return false;switch(t[0]){case"has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case"!in":case"!has":case"none":return false;case"==":case"!=":case">":case">=":case"<":case"<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case"any":case"all":for(const e of t.slice(1))if(!Kn(e)&&"boolean"!=typeof e)return false;return true;default:return true}}const Hn={type:"boolean",default:false,transition:false,"property-type":"data-driven",expression:{interpolated:false,parameters:["zoom","feature"]}};function Yn(t){if(null==t)return {filter:()=>true,needGeometry:false};Kn(t)||(t=Qn(t));const e=Nn(t,Hn);if("error"===e.result)throw new Error(e.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return {filter:(t,r,n)=>e.value.evaluate(t,r,{},n),needGeometry:Wn(t)}}function Jn(t,e){return te?1:0}function Wn(t){if(!Array.isArray(t))return false;if("within"===t[0]||"distance"===t[0]||"geometry-type"===t[0])return true;for(let e=1;e"===e||"<="===e||">="===e?ti(t[1],t[2],e):"any"===e?(r=t.slice(1),["any"].concat(r.map(Qn))):"all"===e?["all"].concat(t.slice(1).map(Qn)):"none"===e?["all"].concat(t.slice(1).map(Qn).map(ni)):"in"===e?ei(t[1],t.slice(2)):"!in"===e?ni(ei(t[1],t.slice(2))):"has"===e?ri(t[1]):"!has"!==e||ni(ri(t[1]));var r;}function ti(t,e,r){switch(t){case"$type":return [`filter-type-${r}`,e];case"$id":return [`filter-id-${r}`,e];default:return [`filter-${r}`,t,e]}}function ei(t,e){if(0===e.length)return false;switch(t){case"$type":return ["filter-type-in",["literal",e]];case"$id":return ["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((t=>typeof t!=typeof e[0]))?["filter-in-large",t,["literal",e.sort(Jn)]]:["filter-in-small",t,["literal",e]]}}function ri(t){switch(t){case"$type":return true;case"$id":return ["filter-has-id"];default:return ["filter-has",t]}}function ni(t){return ["!",t]}function ii(t){const e=typeof t;if("number"===e||"boolean"===e||"string"===e||null==t)return JSON.stringify(t);if(Array.isArray(t)){let e="[";for(const r of t)e+=`${ii(r)},`;return `${e}]`}const r=Object.keys(t).sort();let n="{";for(let e=0;en.maximum?[new St(e,r,`${r} is greater than the maximum value ${n.maximum}`)]:[]}function pi(t){const e=t.valueSpec,r=oi(t.value.type);let n,i,s,a={};const o="categorical"!==r&&undefined===t.value.property,l=!o,u="array"===Bn(t.value.stops)&&"array"===Bn(t.value.stops[0])&&"object"===Bn(t.value.stops[0][0]),c=ui({key:t.key,value:t.value,valueSpec:t.styleSpec.function,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===r)return [new St(t.key,t.value,'identity function may not have a "stops" property')];let e=[];const n=t.value;return e=e.concat(ci({key:t.key,value:n,valueSpec:t.valueSpec,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:h})),"array"===Bn(n)&&0===n.length&&e.push(new St(t.key,n,"array must have at least one stop")),e},default:function(t){return t.validateSpec({key:t.key,value:t.value,valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec})}}});return "identity"===r&&o&&c.push(new St(t.key,t.value,'missing required property "property"')),"identity"===r||t.value.stops||c.push(new St(t.key,t.value,'missing required property "stops"')),"exponential"===r&&t.valueSpec.expression&&!Cn(t.valueSpec)&&c.push(new St(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(l&&!zn(t.valueSpec)?c.push(new St(t.key,t.value,"property functions not supported")):o&&!Pn(t.valueSpec)&&c.push(new St(t.key,t.value,"zoom functions not supported"))),"categorical"!==r&&!u||undefined!==t.value.property||c.push(new St(t.key,t.value,'"property" property is required')),c;function h(t){let r=[];const n=t.value,o=t.key;if("array"!==Bn(n))return [new St(o,n,`array expected, ${Bn(n)} found`)];if(2!==n.length)return [new St(o,n,`array length 2 expected, length ${n.length} found`)];if(u){if("object"!==Bn(n[0]))return [new St(o,n,`object expected, ${Bn(n[0])} found`)];if(undefined===n[0].zoom)return [new St(o,n,"object stop key must have zoom")];if(undefined===n[0].value)return [new St(o,n,"object stop key must have value")];if(s&&s>oi(n[0].zoom))return [new St(o,n[0].zoom,"stop zoom values must appear in ascending order")];oi(n[0].zoom)!==s&&(s=oi(n[0].zoom),i=undefined,a={}),r=r.concat(ui({key:`${o}[0]`,value:n[0],valueSpec:{zoom:{}},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:hi,value:p}}));}else r=r.concat(p({key:`${o}[0]`,value:n[0],valueSpec:{},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec},n));return jn(li(n[1]))?r.concat([new St(`${o}[1]`,n[1],"expressions are not allowed in function stops.")]):r.concat(t.validateSpec({key:`${o}[1]`,value:n[1],valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec}))}function p(t,s){const o=Bn(t.value),l=oi(t.value),u=null!==t.value?t.value:s;if(n){if(o!==n)return [new St(t.key,u,`${o} stop domain type must match previous stop domain type ${n}`)]}else n=o;if("number"!==o&&"string"!==o&&"boolean"!==o)return [new St(t.key,u,"stop domain value must be a number, string, or boolean")];if("number"!==o&&"categorical"!==r){let n=`number expected, ${o} found`;return zn(e)&&undefined===r&&(n+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new St(t.key,u,n)]}return "categorical"!==r||"number"!==o||isFinite(l)&&Math.floor(l)===l?"categorical"!==r&&"number"===o&&undefined!==i&&lnew St(`${t.key}${e.key}`,t.value,e.message)));const r=e.value.expression||e.value._styleExpression.expression;if("property"===t.expressionContext&&"text-font"===t.propertyKey&&!r.outputDefined())return [new St(t.key,t.value,`Invalid data expression for "${t.propertyKey}". Output values must be contained as literals within the expression.`)];if("property"===t.expressionContext&&"layout"===t.propertyType&&!An(r))return [new St(t.key,t.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===t.expressionContext&&!An(r))return [new St(t.key,t.value,'"feature-state" data expressions are not supported with filters.')];if(t.expressionContext&&0===t.expressionContext.indexOf("cluster")){if(!kn(r,["zoom","feature-state"]))return [new St(t.key,t.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===t.expressionContext&&!Sn(r))return [new St(t.key,t.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return []}function di(t){const e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(oi(r))&&i.push(new St(e,r,`expected one of [${n.values.join(", ")}], ${JSON.stringify(r)} found`)):-1===Object.keys(n.values).indexOf(oi(r))&&i.push(new St(e,r,`expected one of [${Object.keys(n.values).join(", ")}], ${JSON.stringify(r)} found`)),i}function yi(t){return Kn(li(t.value))?fi(At({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):mi(t)}function mi(t){const e=t.value,r=t.key;if("array"!==Bn(e))return [new St(r,e,`array expected, ${Bn(e)} found`)];const n=t.styleSpec;let i,s=[];if(e.length<1)return [new St(r,e,"filter array must have at least 1 element")];switch(s=s.concat(di({key:`${r}[0]`,value:e[0],valueSpec:n.filter_operator,style:t.style,styleSpec:t.styleSpec})),oi(e[0])){case"<":case"<=":case">":case">=":e.length>=2&&"$type"===oi(e[1])&&s.push(new St(r,e,`"$type" cannot be use with operator "${e[0]}"`));case"==":case"!=":3!==e.length&&s.push(new St(r,e,`filter array for operator "${e[0]}" must have 3 elements`));case"in":case"!in":e.length>=2&&(i=Bn(e[1]),"string"!==i&&s.push(new St(`${r}[1]`,e[1],`string expected, ${i} found`)));for(let a=2;a{t in r&&e.push(new St(n,r[t],`"${t}" is prohibited for ref layers`));})),i.layers.forEach((e=>{oi(e.id)===o&&(t=e);})),t?t.ref?e.push(new St(n,r.ref,"ref cannot reference another ref layer")):a=oi(t.type):e.push(new St(n,r.ref,`ref layer "${o}" not found`));}else if("background"!==a)if(r.source){const t=i.sources&&i.sources[r.source],s=t&&oi(t.type);t?"vector"===s&&"raster"===a?e.push(new St(n,r.source,`layer "${r.id}" requires a raster source`)):"raster-dem"!==s&&"hillshade"===a?e.push(new St(n,r.source,`layer "${r.id}" requires a raster-dem source`)):"raster"===s&&"raster"!==a?e.push(new St(n,r.source,`layer "${r.id}" requires a vector source`)):"vector"!==s||r["source-layer"]?"raster-dem"===s&&"hillshade"!==a?e.push(new St(n,r.source,"raster-dem source can only be used with layer type 'hillshade'.")):"line"!==a||!r.paint||!r.paint["line-gradient"]||"geojson"===s&&t.lineMetrics||e.push(new St(n,r,`layer "${r.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):e.push(new St(n,r,`layer "${r.id}" must specify a "source-layer"`)):e.push(new St(n,r.source,`source "${r.source}" not found`));}else e.push(new St(n,r,'missing required property "source"'));return e=e.concat(ui({key:n,value:r,valueSpec:s.layer,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":()=>[],type:()=>t.validateSpec({key:`${n}.type`,value:r.type,valueSpec:s.layer.type,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,object:r,objectKey:"type"}),filter:yi,layout:t=>ui({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>vi(At({layerType:a},t))}}),paint:t=>ui({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>xi(At({layerType:a},t))}})}})),e}function wi(t){const e=t.value,r=t.key,n=Bn(e);return "string"!==n?[new St(r,e,`string expected, ${n} found`)]:[]}const _i={promoteId:function({key:t,value:e}){if("string"===Bn(e))return wi({key:t,value:e});{const r=[];for(const n in e)r.push(...wi({key:`${t}.${n}`,value:e[n]}));return r}}};function Si(t){const e=t.value,r=t.key,n=t.styleSpec,i=t.style,s=t.validateSpec;if(!e.type)return [new St(r,e,'"type" is required')];const a=oi(e.type);let o;switch(a){case"vector":case"raster":return o=ui({key:r,value:e,valueSpec:n[`source_${a.replace("-","_")}`],style:t.style,styleSpec:n,objectElementValidators:_i,validateSpec:s}),o;case"raster-dem":return o=function(t){var e;const r=null!==(e=t.sourceName)&&undefined!==e?e:"",n=t.value,i=t.styleSpec,s=i.source_raster_dem,a=t.style;let o=[];const l=Bn(n);if(undefined===n)return o;if("object"!==l)return o.push(new St("source_raster_dem",n,`object expected, ${l} found`)),o;const u="custom"===oi(n.encoding),c=["redFactor","greenFactor","blueFactor","baseShift"],h=t.value.encoding?`"${t.value.encoding}"`:"Default";for(const e in n)!u&&c.includes(e)?o.push(new St(e,n[e],`In "${r}": "${e}" is only valid when "encoding" is set to "custom". ${h} encoding found`)):s[e]?o=o.concat(t.validateSpec({key:e,value:n[e],valueSpec:s[e],validateSpec:t.validateSpec,style:a,styleSpec:i})):o.push(new St(e,n[e],`unknown property "${e}"`));return o}({sourceName:r,value:e,style:t.style,styleSpec:n,validateSpec:s}),o;case"geojson":if(o=ui({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n,validateSpec:s,objectElementValidators:_i}),e.cluster)for(const t in e.clusterProperties){const[n,i]=e.clusterProperties[t],a="string"==typeof n?[n,["accumulated"],["get",t]]:n;o.push(...fi({key:`${r}.${t}.map`,value:i,validateSpec:s,expressionContext:"cluster-map"})),o.push(...fi({key:`${r}.${t}.reduce`,value:a,validateSpec:s,expressionContext:"cluster-reduce"}));}return o;case"video":return ui({key:r,value:e,valueSpec:n.source_video,style:i,validateSpec:s,styleSpec:n});case"image":return ui({key:r,value:e,valueSpec:n.source_image,style:i,validateSpec:s,styleSpec:n});case"canvas":return [new St(r,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return di({key:`${r}.type`,value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]},style:i,validateSpec:s,styleSpec:n})}}function Ai(t){const e=t.value,r=t.styleSpec,n=r.light,i=t.style;let s=[];const a=Bn(e);if(undefined===e)return s;if("object"!==a)return s=s.concat([new St("light",e,`object expected, ${a} found`)]),s;for(const a in e){const o=a.match(/^(.*)-transition$/);s=s.concat(o&&n[o[1]]&&n[o[1]].transition?t.validateSpec({key:a,value:e[a],valueSpec:r.transition,validateSpec:t.validateSpec,style:i,styleSpec:r}):n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new St(a,e[a],`unknown property "${a}"`)]);}return s}function ki(t){const e=t.value,r=t.styleSpec,n=r.sky,i=t.style,s=Bn(e);if(undefined===e)return [];if("object"!==s)return [new St("sky",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new St(s,e[s],`unknown property "${s}"`)]);return a}function Mi(t){const e=t.value,r=t.styleSpec,n=r.terrain,i=t.style;let s=[];const a=Bn(e);if(undefined===e)return s;if("object"!==a)return s=s.concat([new St("terrain",e,`object expected, ${a} found`)]),s;for(const a in e)s=s.concat(n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new St(a,e[a],`unknown property "${a}"`)]);return s}function Ii(t){let e=[];const r=t.value,n=t.key;if(Array.isArray(r)){const i=[],s=[];for(const a in r)r[a].id&&i.includes(r[a].id)&&e.push(new St(n,r,`all the sprites' ids must be unique, but ${r[a].id} is duplicated`)),i.push(r[a].id),r[a].url&&s.includes(r[a].url)&&e.push(new St(n,r,`all the sprites' URLs must be unique, but ${r[a].url} is duplicated`)),s.push(r[a].url),e=e.concat(ui({key:`${n}[${a}]`,value:r[a],valueSpec:{id:{type:"string",required:true},url:{type:"string",required:true}},validateSpec:t.validateSpec}));return e}return wi({key:n,value:r})}const zi={"*":()=>[],array:ci,boolean:function(t){const e=t.value,r=t.key,n=Bn(e);return "boolean"!==n?[new St(r,e,`boolean expected, ${n} found`)]:[]},number:hi,color:function(t){const e=t.key,r=t.value,n=Bn(r);return "string"!==n?[new St(e,r,`color expected, ${n} found`)]:ye.parse(String(r))?[]:[new St(e,r,`color expected, "${r}" found`)]},constants:ai,enum:di,filter:yi,function:pi,layer:bi,object:ui,source:Si,light:Ai,sky:ki,terrain:Mi,projection:function(t){const e=t.value,r=t.styleSpec,n=r.projection,i=t.style,s=Bn(e);if(undefined===e)return [];if("object"!==s)return [new St("projection",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new St(s,e[s],`unknown property "${s}"`)]);return a},projectionDefinition:function(t){const e=t.key;let r=t.value;r=r instanceof String?r.valueOf():r;const n=Bn(r);return "array"!==n||function(t){return Array.isArray(t)&&3===t.length&&"string"==typeof t[0]&&"string"==typeof t[1]&&"number"==typeof t[2]}(r)||function(t){return !!["interpolate","step","literal"].includes(t[0])}(r)?["array","string"].includes(n)?[]:[new St(e,r,`projection expected, invalid type "${n}" found`)]:[new St(e,r,`projection expected, invalid array ${JSON.stringify(r)} found`)]},string:wi,formatted:function(t){return 0===wi(t).length?[]:fi(t)},resolvedImage:function(t){return 0===wi(t).length?[]:fi(t)},padding:function(t){const e=t.key,r=t.value;if("array"===Bn(r)){if(r.length<1||r.length>4)return [new St(e,r,`padding requires 1 to 4 values; ${r.length} values found`)];const n={type:"number"};let i=[];for(let s=0;s[]}})),t.constants&&(r=r.concat(ai({key:"constants",value:t.constants,style:t,styleSpec:e,validateSpec:Pi}))),Ei(r)}function Vi(t){return function(e){return t({...e,validateSpec:Pi})}}function Ei(t){return [].concat(t).sort(((t,e)=>t.line-e.line))}function Ti(t){return function(...e){return Ei(t.apply(this,e))}}Bi.source=Ti(Vi(Si)),Bi.sprite=Ti(Vi(Ii)),Bi.glyphs=Ti(Vi(Ci)),Bi.light=Ti(Vi(Ai)),Bi.sky=Ti(Vi(ki)),Bi.terrain=Ti(Vi(Mi)),Bi.layer=Ti(Vi(bi)),Bi.filter=Ti(Vi(yi)),Bi.paintProperty=Ti(Vi(xi)),Bi.layoutProperty=Ti(Vi(vi));const Fi=Bi,$i=Fi.light,Li=Fi.sky,Di=Fi.paintProperty,Oi=Fi.layoutProperty;function Ri(t,e){let r=false;if(e&&e.length)for(const n of e)t.fire(new ut(new Error(n.message))),r=true;return r}class ji{constructor(t,e,r){const n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;const i=new Int32Array(this.arrayBuffer);t=i[0],this.d=(e=i[1])+2*(r=i[2]);for(let t=0;t=u[l+0]&&n>=u[l+1])?(a[h]=true,s.push(i[h])):a[h]=false;}}}}_forEachCell(t,e,r,n,i,s,a,o){const l=this._convertToCellCoord(t),u=this._convertToCellCoord(e),c=this._convertToCellCoord(r),h=this._convertToCellCoord(n);for(let p=l;p<=c;p++)for(let l=u;l<=h;l++){const u=this.d*l+p;if((!o||o(this._convertFromCellCoord(p),this._convertFromCellCoord(l),this._convertFromCellCoord(p+1),this._convertFromCellCoord(l+1)))&&i.call(this,t,e,r,n,u,s,a,o))return}}_convertFromCellCoord(t){return (t-this.padding)/this.scale}_convertToCellCoord(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;const t=this.cells,e=3+this.cells.length+1+1;let r=0;for(let t=0;t=0)continue;const s=t[n];i[n]=Ni[r].shallow.indexOf(n)>=0?s:Xi(s,e);}t instanceof Error&&(i.message=t.message);}if(i.$name)throw new Error("$name property is reserved for worker serialization logic.");return "Object"!==r&&(i.$name=r),i}function Ki(t){if(Zi(t))return t;if(Array.isArray(t))return t.map(Ki);if("object"!=typeof t)throw new Error("can't deserialize object of type "+typeof t);const e=Gi(t)||"Object";if(!Ni[e])throw new Error(`can't deserialize unregistered class ${e}`);const{klass:r}=Ni[e];if(!r)throw new Error(`can't deserialize unregistered class ${e}`);if(r.deserialize)return r.deserialize(t);const n=Object.create(r.prototype);for(const r of Object.keys(t)){if("$name"===r)continue;const i=t[r];n[r]=Ni[e].shallow.indexOf(r)>=0?i:Ki(i);}return n}class Hi{constructor(){this.first=true;}update(t,e){const r=Math.floor(t);return this.first?(this.first=false,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,true):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoomt>=128&&t<=255,"Hangul Jamo":t=>t>=4352&&t<=4607,Khmer:t=>t>=6016&&t<=6143,"General Punctuation":t=>t>=8192&&t<=8303,"Letterlike Symbols":t=>t>=8448&&t<=8527,"Number Forms":t=>t>=8528&&t<=8591,"Miscellaneous Technical":t=>t>=8960&&t<=9215,"Control Pictures":t=>t>=9216&&t<=9279,"Optical Character Recognition":t=>t>=9280&&t<=9311,"Enclosed Alphanumerics":t=>t>=9312&&t<=9471,"Geometric Shapes":t=>t>=9632&&t<=9727,"Miscellaneous Symbols":t=>t>=9728&&t<=9983,"Miscellaneous Symbols and Arrows":t=>t>=11008&&t<=11263,"Ideographic Description Characters":t=>t>=12272&&t<=12287,"CJK Symbols and Punctuation":t=>t>=12288&&t<=12351,Katakana:t=>t>=12448&&t<=12543,Kanbun:t=>t>=12688&&t<=12703,"CJK Strokes":t=>t>=12736&&t<=12783,"Enclosed CJK Letters and Months":t=>t>=12800&&t<=13055,"CJK Compatibility":t=>t>=13056&&t<=13311,"Yijing Hexagram Symbols":t=>t>=19904&&t<=19967,"Private Use Area":t=>t>=57344&&t<=63743,"Vertical Forms":t=>t>=65040&&t<=65055,"CJK Compatibility Forms":t=>t>=65072&&t<=65103,"Small Form Variants":t=>t>=65104&&t<=65135,"Halfwidth and Fullwidth Forms":t=>t>=65280&&t<=65519};function Ji(t){for(const e of t)if(ns(e.charCodeAt(0)))return true;return false}function Wi(t){for(const e of t)if(!es(e.charCodeAt(0)))return false;return true}function Qi(t){const e=t.map((t=>{try{return new RegExp(`\\p{sc=${t}}`,"u").source}catch(t){return null}})).filter((t=>t));return new RegExp(e.join("|"),"u")}const ts=Qi(["Arab","Dupl","Mong","Ougr","Syrc"]);function es(t){return !ts.test(String.fromCodePoint(t))}const rs=Qi(["Bopo","Hani","Hira","Kana","Kits","Nshu","Tang","Yiii"]);function ns(t){return !(746!==t&&747!==t&&(t<4352||!(Yi["CJK Compatibility Forms"](t)&&!(t>=65097&&t<=65103)||Yi["CJK Compatibility"](t)||Yi["CJK Strokes"](t)||!(!Yi["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||Yi["Enclosed CJK Letters and Months"](t)||Yi["Ideographic Description Characters"](t)||Yi.Kanbun(t)||Yi.Katakana(t)&&12540!==t||!(!Yi["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!Yi["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||Yi["Vertical Forms"](t)||Yi["Yijing Hexagram Symbols"](t)||/\p{sc=Cans}/u.test(String.fromCodePoint(t))||/\p{sc=Hang}/u.test(String.fromCodePoint(t))||rs.test(String.fromCodePoint(t)))))}function is(t){return !(ns(t)||function(t){return !!(Yi["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||Yi["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||Yi["Letterlike Symbols"](t)||Yi["Number Forms"](t)||Yi["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||Yi["Control Pictures"](t)&&9251!==t||Yi["Optical Character Recognition"](t)||Yi["Enclosed Alphanumerics"](t)||Yi["Geometric Shapes"](t)||Yi["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||Yi["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||Yi["CJK Symbols and Punctuation"](t)||Yi.Katakana(t)||Yi["Private Use Area"](t)||Yi["CJK Compatibility Forms"](t)||Yi["Small Form Variants"](t)||Yi["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}const ss=Qi(["Adlm","Arab","Armi","Avst","Chrs","Cprt","Egyp","Elym","Gara","Hatr","Hebr","Hung","Khar","Lydi","Mand","Mani","Mend","Merc","Mero","Narb","Nbat","Nkoo","Orkh","Palm","Phli","Phlp","Phnx","Prti","Rohg","Samr","Sarb","Sogo","Syrc","Thaa","Todr","Yezi"]);function as(t){return ss.test(String.fromCodePoint(t))}function os(t,e){return !(!e&&as(t)||t>=2304&&t<=3583||t>=3840&&t<=4255||Yi.Khmer(t))}function ls(t){for(const e of t)if(as(e.charCodeAt(0)))return true;return false}const us=new class{constructor(){this.TIMEOUT=5e3,this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus="unavailable",this.pluginURL=null,this.loadScriptResolve=()=>{};}setState(t){this.pluginStatus=t.pluginStatus,this.pluginURL=t.pluginURL;}getState(){return {pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(t){if(us.isParsed())throw new Error("RTL text plugin already registered.");this.applyArabicShaping=t.applyArabicShaping,this.processBidirectionalText=t.processBidirectionalText,this.processStyledBidirectionalText=t.processStyledBidirectionalText,this.loadScriptResolve();}isParsed(){return null!=this.applyArabicShaping&&null!=this.processBidirectionalText&&null!=this.processStyledBidirectionalText}getRTLTextPluginStatus(){return this.pluginStatus}syncState(t,r){return e(this,undefined,undefined,(function*(){if(this.isParsed())return this.getState();if("loading"!==t.pluginStatus)return this.setState(t),t;const e=t.pluginURL,n=new Promise((t=>{this.loadScriptResolve=t;}));r(e);const i=new Promise((t=>setTimeout((()=>t()),this.TIMEOUT)));if(yield Promise.race([n,i]),this.isParsed()){const t={pluginStatus:"loaded",pluginURL:e};return this.setState(t),t}throw this.setState({pluginStatus:"error",pluginURL:""}),new Error(`RTL Text Plugin failed to import scripts from ${e}`)}))}};class cs{constructor(t,e){this.zoom=t,e?(this.now=e.now,this.fadeDuration=e.fadeDuration,this.zoomHistory=e.zoomHistory,this.transition=e.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new Hi,this.transition={});}isSupportedScript(t){return function(t,e){for(const r of t)if(!os(r.charCodeAt(0),e))return false;return true}(t,"loaded"===us.getRTLTextPluginStatus())}crossFadingFactor(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}getCrossfadeParameters(){const t=this.zoom,e=t-Math.floor(t),r=this.crossFadingFactor();return t>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*r}:{fromScale:.5,toScale:1,t:1-(1-r)*e}}}class hs{constructor(t,e){this.property=t,this.value=e,this.expression=function(t,e){if(Vn(t))return new Zn(t,e);if(jn(t)){const r=Gn(t,e);if("error"===r.result)throw new Error(r.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return r.value}{let r=t;return "color"===e.type&&"string"==typeof t?r=ye.parse(t):"padding"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"variableAnchorOffsetCollection"===e.type&&Array.isArray(t)?r=_e.parse(t):"projectionDefinition"===e.type&&"string"==typeof t&&(r=Ae.parse(t)):r=ve.parse(t),{kind:"constant",evaluate:()=>r}}}(undefined===e?t.specification.default:e,t.specification);}isDataDriven(){return "source"===this.expression.kind||"composite"===this.expression.kind}possiblyEvaluate(t,e,r){return this.property.possiblyEvaluate(this,t,e,r)}}class ps{constructor(t){this.property=t,this.value=new hs(t,undefined);}transitioned(t,e){return new ds(this.property,this.value,e,F({},t.transition,this.transition),t.now)}untransitioned(){return new ds(this.property,this.value,null,{},0)}}class fs{constructor(t){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues);}getValue(t){return O(this._values[t].value.value)}setValue(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new ps(this._values[t].property)),this._values[t].value=new hs(this._values[t].property,null===e?undefined:O(e));}getTransition(t){return O(this._values[t].transition)}setTransition(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new ps(this._values[t].property)),this._values[t].transition=O(e)||undefined;}serialize(){const t={};for(const e of Object.keys(this._values)){const r=this.getValue(e);undefined!==r&&(t[e]=r);const n=this.getTransition(e);undefined!==n&&(t[`${e}-transition`]=n);}return t}transitioned(t,e){const r=new ys(this._properties);for(const n of Object.keys(this._values))r._values[n]=this._values[n].transitioned(t,e._values[n]);return r}untransitioned(){const t=new ys(this._properties);for(const e of Object.keys(this._values))t._values[e]=this._values[e].untransitioned();return t}}class ds{constructor(t,e,r,n,i){this.property=t,this.value=e,this.begin=i+n.delay||0,this.end=this.begin+n.duration||0,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r);}possiblyEvaluate(t,e,r){const n=t.now||0,i=this.value.possiblyEvaluate(t,e,r),s=this.prior;if(s){if(n>this.end)return this.prior=null,i;if(this.value.isDataDriven())return this.prior=null,i;if(nn.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class _s{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){if(undefined!==t.value){if("constant"===t.expression.kind){const i=t.expression.evaluate(e,null,{},r,n);return this._calculate(i,i,i,e)}return this._calculate(t.expression.evaluate(new cs(Math.floor(e.zoom-1),e)),t.expression.evaluate(new cs(Math.floor(e.zoom),e)),t.expression.evaluate(new cs(Math.floor(e.zoom+1),e)),e)}}_calculate(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Ss{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){return !!t.expression.evaluate(e,null,{},r,n)}interpolate(){return false}}class As{constructor(t){this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(const e in t){const r=t[e];r.specification.overridable&&this.overridableProperties.push(e);const n=this.defaultPropertyValues[e]=new hs(r,undefined),i=this.defaultTransitionablePropertyValues[e]=new ps(r);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({});}}}Ui("DataDrivenProperty",bs),Ui("DataConstantProperty",vs),Ui("CrossFadedDataDrivenProperty",ws),Ui("CrossFadedProperty",_s),Ui("ColorRampProperty",Ss);const ks="-transition";class Ms extends ct{constructor(t,e){if(super(),this.id=t.id,this.type=t.type,this._featureFilter={filter:()=>true,needGeometry:false},"custom"!==t.type&&(this.metadata=t.metadata,this.minzoom=t.minzoom,this.maxzoom=t.maxzoom,"background"!==t.type&&(this.source=t.source,this.sourceLayer=t["source-layer"],this.filter=t.filter),e.layout&&(this._unevaluatedLayout=new ms(e.layout)),e.paint)){this._transitionablePaint=new fs(e.paint);for(const e in t.paint)this.setPaintProperty(e,t.paint[e],{validate:false});for(const e in t.layout)this.setLayoutProperty(e,t.layout[e],{validate:false});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new xs(e.paint);}}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(t){return "visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)}setLayoutProperty(t,e,r={}){null!=e&&this._validate(Oi,`layers.${this.id}.layout.${t}`,t,e,r)||("visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility=e);}getPaintProperty(t){return t.endsWith(ks)?this._transitionablePaint.getTransition(t.slice(0,-11)):this._transitionablePaint.getValue(t)}setPaintProperty(t,e,r={}){if(null!=e&&this._validate(Di,`layers.${this.id}.paint.${t}`,t,e,r))return false;if(t.endsWith(ks))return this._transitionablePaint.setTransition(t.slice(0,-11),e||undefined),false;{const r=this._transitionablePaint._values[t],n="cross-faded-data-driven"===r.property.specification["property-type"],i=r.value.isDataDriven(),s=r.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);const a=this._transitionablePaint._values[t].value;return a.isDataDriven()||i||n||this._handleOverridablePaintPropertyUpdate(t,s,a)}}_handleSpecialPaintPropertyUpdate(t){}_handleOverridablePaintPropertyUpdate(t,e,r){return false}isHidden(t){return !!(this.minzoom&&t=this.maxzoom)||"none"===this.visibility}updateTransitions(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,undefined,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,undefined,e);}serialize(){const t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(t.layout=t.layout||{},t.layout.visibility=this.visibility),D(t,((t,e)=>!(undefined===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)))}_validate(t,e,r,n,i={}){return (!i||false!==i.validate)&&Ri(this,t.call(Fi,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:ht,style:{glyphs:true,sprite:true}}))}is3D(){return false}isTileClipped(){return false}hasOffscreenPass(){return false}resize(){}isStateDependent(){for(const t in this.paint._values){const e=this.paint.get(t);if(e instanceof gs&&zn(e.property.specification)&&("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent)return true}return false}}const Is={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class zs{constructor(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;}}class Ps{constructor(){this.isTransferred=false,this.capacity=-1,this.resize(0);}static serialize(t,e){return t._trim(),e&&(t.isTransferred=true,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}}static deserialize(t){const e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());}clear(){this.length=0;}resize(t){this.reserve(t),this.length=t;}reserve(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}}function Cs(t,e=1){let r=0,n=0;return {members:t.map((t=>{const i=Is[t.type].BYTES_PER_ELEMENT,s=r=Bs(r,Math.max(e,i)),a=t.components||1;return n=Math.max(n,i),r+=i*a,{name:t.name,type:t.type,components:a,offset:s}})),size:Bs(r,Math.max(n,e)),alignment:e}}function Bs(t,e){return Math.ceil(t/e)*e}class Vs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.int16[n+0]=e,this.int16[n+1]=r,t}}Vs.prototype.bytesPerElement=4,Ui("StructArrayLayout2i4",Vs);class Es extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.int16[i+0]=e,this.int16[i+1]=r,this.int16[i+2]=n,t}}Es.prototype.bytesPerElement=6,Ui("StructArrayLayout3i6",Es);class Ts extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,t}}Ts.prototype.bytesPerElement=8,Ui("StructArrayLayout4i8",Ts);class Fs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}Fs.prototype.bytesPerElement=12,Ui("StructArrayLayout2i4i12",Fs);class $s extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=4*t,l=8*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.uint8[l+4]=n,this.uint8[l+5]=i,this.uint8[l+6]=s,this.uint8[l+7]=a,t}}$s.prototype.bytesPerElement=8,Ui("StructArrayLayout2i4ub8",$s);class Ls extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.float32[n+0]=e,this.float32[n+1]=r,t}}Ls.prototype.bytesPerElement=8,Ui("StructArrayLayout2f8",Ls);class Ds extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u){const c=this.length;return this.resize(c+1),this.emplace(c,t,e,r,n,i,s,a,o,l,u)}emplace(t,e,r,n,i,s,a,o,l,u,c){const h=10*t;return this.uint16[h+0]=e,this.uint16[h+1]=r,this.uint16[h+2]=n,this.uint16[h+3]=i,this.uint16[h+4]=s,this.uint16[h+5]=a,this.uint16[h+6]=o,this.uint16[h+7]=l,this.uint16[h+8]=u,this.uint16[h+9]=c,t}}Ds.prototype.bytesPerElement=20,Ui("StructArrayLayout10ui20",Ds);class Os extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h){const p=this.length;return this.resize(p+1),this.emplace(p,t,e,r,n,i,s,a,o,l,u,c,h)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p){const f=12*t;return this.int16[f+0]=e,this.int16[f+1]=r,this.int16[f+2]=n,this.int16[f+3]=i,this.uint16[f+4]=s,this.uint16[f+5]=a,this.uint16[f+6]=o,this.uint16[f+7]=l,this.int16[f+8]=u,this.int16[f+9]=c,this.int16[f+10]=h,this.int16[f+11]=p,t}}Os.prototype.bytesPerElement=24,Ui("StructArrayLayout4i4ui4i24",Os);class Rs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.float32[i+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}Rs.prototype.bytesPerElement=12,Ui("StructArrayLayout3f12",Rs);class js extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint32[1*t+0]=e,t}}js.prototype.bytesPerElement=4,Ui("StructArrayLayout1ul4",js);class Ns extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l){const u=this.length;return this.resize(u+1),this.emplace(u,t,e,r,n,i,s,a,o,l)}emplace(t,e,r,n,i,s,a,o,l,u){const c=10*t,h=5*t;return this.int16[c+0]=e,this.int16[c+1]=r,this.int16[c+2]=n,this.int16[c+3]=i,this.int16[c+4]=s,this.int16[c+5]=a,this.uint32[h+3]=o,this.uint16[c+8]=l,this.uint16[c+9]=u,t}}Ns.prototype.bytesPerElement=20,Ui("StructArrayLayout6i1ul2ui20",Ns);class Us extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}Us.prototype.bytesPerElement=12,Ui("StructArrayLayout2i2i2i12",Us);class qs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,r,n,i)}emplace(t,e,r,n,i,s){const a=4*t,o=8*t;return this.float32[a+0]=e,this.float32[a+1]=r,this.float32[a+2]=n,this.int16[o+6]=i,this.int16[o+7]=s,t}}qs.prototype.bytesPerElement=16,Ui("StructArrayLayout2f1f2i16",qs);class Gs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=16*t,l=4*t,u=8*t;return this.uint8[o+0]=e,this.uint8[o+1]=r,this.float32[l+1]=n,this.float32[l+2]=i,this.int16[u+6]=s,this.int16[u+7]=a,t}}Gs.prototype.bytesPerElement=16,Ui("StructArrayLayout2ub2f2i16",Gs);class Zs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=r,this.uint16[i+2]=n,t}}Zs.prototype.bytesPerElement=6,Ui("StructArrayLayout3ui6",Zs);class Xs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m){const g=this.length;return this.resize(g+1),this.emplace(g,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g){const x=24*t,v=12*t,b=48*t;return this.int16[x+0]=e,this.int16[x+1]=r,this.uint16[x+2]=n,this.uint16[x+3]=i,this.uint32[v+2]=s,this.uint32[v+3]=a,this.uint32[v+4]=o,this.uint16[x+10]=l,this.uint16[x+11]=u,this.uint16[x+12]=c,this.float32[v+7]=h,this.float32[v+8]=p,this.uint8[b+36]=f,this.uint8[b+37]=d,this.uint8[b+38]=y,this.uint32[v+10]=m,this.int16[x+22]=g,t}}Xs.prototype.bytesPerElement=48,Ui("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",Xs);class Ks extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I){const z=this.length;return this.resize(z+1),this.emplace(z,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I,z){const P=32*t,C=16*t;return this.int16[P+0]=e,this.int16[P+1]=r,this.int16[P+2]=n,this.int16[P+3]=i,this.int16[P+4]=s,this.int16[P+5]=a,this.int16[P+6]=o,this.int16[P+7]=l,this.uint16[P+8]=u,this.uint16[P+9]=c,this.uint16[P+10]=h,this.uint16[P+11]=p,this.uint16[P+12]=f,this.uint16[P+13]=d,this.uint16[P+14]=y,this.uint16[P+15]=m,this.uint16[P+16]=g,this.uint16[P+17]=x,this.uint16[P+18]=v,this.uint16[P+19]=b,this.uint16[P+20]=w,this.uint16[P+21]=_,this.uint16[P+22]=S,this.uint32[C+12]=A,this.float32[C+13]=k,this.float32[C+14]=M,this.uint16[P+30]=I,this.uint16[P+31]=z,t}}Ks.prototype.bytesPerElement=64,Ui("StructArrayLayout8i15ui1ul2f2ui64",Ks);class Hs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.float32[1*t+0]=e,t}}Hs.prototype.bytesPerElement=4,Ui("StructArrayLayout1f4",Hs);class Ys extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[6*t+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}Ys.prototype.bytesPerElement=12,Ui("StructArrayLayout1ui2f12",Ys);class Js extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=4*t;return this.uint32[2*t+0]=e,this.uint16[i+2]=r,this.uint16[i+3]=n,t}}Js.prototype.bytesPerElement=8,Ui("StructArrayLayout1ul2ui8",Js);class Ws extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.uint16[n+0]=e,this.uint16[n+1]=r,t}}Ws.prototype.bytesPerElement=4,Ui("StructArrayLayout2ui4",Ws);class Qs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint16[1*t+0]=e,t}}Qs.prototype.bytesPerElement=2,Ui("StructArrayLayout1ui2",Qs);class ta extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.float32[s+0]=e,this.float32[s+1]=r,this.float32[s+2]=n,this.float32[s+3]=i,t}}ta.prototype.bytesPerElement=16,Ui("StructArrayLayout4f16",ta);class ea extends zs{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new l(this.anchorPointX,this.anchorPointY)}}ea.prototype.size=20;class ra extends Ns{get(t){return new ea(this,t)}}Ui("CollisionBoxArray",ra);class na extends zs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(t){this._structArray.uint8[this._pos1+37]=t;}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(t){this._structArray.uint8[this._pos1+38]=t;}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(t){this._structArray.uint32[this._pos4+10]=t;}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}na.prototype.size=48;class ia extends Xs{get(t){return new na(this,t)}}Ui("PlacedSymbolArray",ia);class sa extends zs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(t){this._structArray.uint32[this._pos4+12]=t;}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}sa.prototype.size=64;class aa extends Ks{get(t){return new sa(this,t)}}Ui("SymbolInstanceArray",aa);class oa extends Hs{getoffsetX(t){return this.float32[1*t+0]}}Ui("GlyphOffsetArray",oa);class la extends Es{getx(t){return this.int16[3*t+0]}gety(t){return this.int16[3*t+1]}gettileUnitDistanceFromAnchor(t){return this.int16[3*t+2]}}Ui("SymbolLineVertexArray",la);class ua extends zs{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}ua.prototype.size=12;class ca extends Ys{get(t){return new ua(this,t)}}Ui("TextAnchorOffsetArray",ca);class ha extends zs{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}ha.prototype.size=8;class pa extends Js{get(t){return new ha(this,t)}}Ui("FeatureIndexArray",pa);class fa extends Vs{}class da extends Vs{}class ya extends Vs{}class ma extends Fs{}class ga extends $s{}class xa extends Ls{}class va extends Ds{}class ba extends Os{}class wa extends Rs{}class _a extends js{}class Sa extends Us{}class Aa extends Gs{}class ka extends Zs{}class Ma extends Ws{}const Ia=Cs([{name:"a_pos",components:2,type:"Int16"}],4),{members:za}=Ia;class Pa{constructor(t=[]){this._forceNewSegmentOnNextPrepare=false,this.segments=t;}prepareSegment(t,e,r,n){const i=this.segments[this.segments.length-1];return t>Pa.MAX_VERTEX_ARRAY_LENGTH&&j(`Max vertices per segment is ${Pa.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${t}. Consider using the \`fillLargeMeshArrays\` function if you require meshes with more than ${Pa.MAX_VERTEX_ARRAY_LENGTH} vertices.`),this._forceNewSegmentOnNextPrepare||!i||i.vertexLength+t>Pa.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==n?this.createNewSegment(e,r,n):i}createNewSegment(t,e,r){const n={vertexOffset:t.length,primitiveOffset:e.length,vertexLength:0,primitiveLength:0,vaos:{}};return undefined!==r&&(n.sortKey=r),this._forceNewSegmentOnNextPrepare=false,this.segments.push(n),n}getOrCreateLatestSegment(t,e,r){return this.prepareSegment(0,t,e,r)}forceNewSegmentOnNextPrepare(){this._forceNewSegmentOnNextPrepare=true;}get(){return this.segments}destroy(){for(const t of this.segments)for(const e in t.vaos)t.vaos[e].destroy();}static simpleSegment(t,e,r,n){return new Pa([{vertexOffset:t,primitiveOffset:e,vertexLength:r,primitiveLength:n,vaos:{},sortKey:0}])}}function Ca(t,e){return 256*(t=E(Math.floor(t),0,255))+E(Math.floor(e),0,255)}Pa.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Ui("SegmentVector",Pa);const Ba=Cs([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]);var Va,Ea,Ta,Fa={exports:{}},$a={exports:{}},La={exports:{}},Da=function(){if(Ta)return Fa.exports;Ta=1;var t=(Va||(Va=1,$a.exports=function(t,e){var r,n,i,s,a,o,l,u;for(n=t.length-(r=3&t.length),i=e,a=3432918353,o=461845907,u=0;u>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(s>>>16)&65535)<<16);switch(l=0,r){case 3:l^=(255&t.charCodeAt(u+2))<<16;case 2:l^=(255&t.charCodeAt(u+1))<<8;case 1:i^=l=(65535&(l=(l=(65535&(l^=255&t.charCodeAt(u)))*a+(((l>>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295;}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0}),$a.exports),e=(Ea||(Ea=1,La.exports=function(t,e){for(var r,n=t.length,i=e^n,s=0;n>=4;)r=1540483477*(65535&(r=255&t.charCodeAt(s)|(255&t.charCodeAt(++s))<<8|(255&t.charCodeAt(++s))<<16|(255&t.charCodeAt(++s))<<24))+((1540483477*(r>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(r=1540483477*(65535&(r^=r>>>24))+((1540483477*(r>>>16)&65535)<<16)),n-=4,++s;switch(n){case 3:i^=(255&t.charCodeAt(s+2))<<16;case 2:i^=(255&t.charCodeAt(s+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(s)))+((1540483477*(i>>>16)&65535)<<16);}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0}),La.exports);return Fa.exports=t,Fa.exports.murmur3=t,Fa.exports.murmur2=e,Fa.exports}(),Oa=r(Da);class Ra{constructor(){this.ids=[],this.positions=[],this.indexed=false;}add(t,e,r,n){this.ids.push(ja(t)),this.positions.push(e,r,n);}getPositions(t){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");const e=ja(t);let r=0,n=this.ids.length-1;for(;r>1;this.ids[t]>=e?n=t:r=t+1;}const i=[];for(;this.ids[r]===e;)i.push({index:this.positions[3*r],start:this.positions[3*r+1],end:this.positions[3*r+2]}),r++;return i}static serialize(t,e){const r=new Float64Array(t.ids),n=new Uint32Array(t.positions);return Na(r,n,0,r.length-1),e&&e.push(r.buffer,n.buffer),{ids:r,positions:n}}static deserialize(t){const e=new Ra;return e.ids=t.ids,e.positions=t.positions,e.indexed=true,e}}function ja(t){const e=+t;return !isNaN(e)&&e<=Number.MAX_SAFE_INTEGER?e:Oa(String(t))}function Na(t,e,r,n){for(;r>1];let s=r-1,a=n+1;for(;;){do{s++;}while(t[s]i);if(s>=a)break;Ua(t,s,a),Ua(e,3*s,3*a),Ua(e,3*s+1,3*a+1),Ua(e,3*s+2,3*a+2);}a-r`u_${t}`)),this.type=r;}setUniform(t,e,r){t.set(r.constantOr(this.value));}getBinding(t,e,r){return "color"===this.type?new Xa(t,e):new Ga(t,e)}}class Ja{constructor(t,e){this.uniformNames=e.map((t=>`u_${t}`)),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1;}setConstantPatternPositions(t,e){this.pixelRatioFrom=e.pixelRatio,this.pixelRatioTo=t.pixelRatio,this.patternFrom=e.tlbr,this.patternTo=t.tlbr;}setUniform(t,e,r,n){const i="u_pattern_to"===n?this.patternTo:"u_pattern_from"===n?this.patternFrom:"u_pixel_ratio_to"===n?this.pixelRatioTo:"u_pixel_ratio_from"===n?this.pixelRatioFrom:null;i&&t.set(i);}getBinding(t,e,r){return "u_pattern"===r.substr(0,9)?new Za(t,e):new Ga(t,e)}}class Wa{constructor(t,e,r,n){this.expression=t,this.type=r,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?2:1,offset:0}))),this.paintVertexArray=new n;}populatePaintArray(t,e,r,n,i){const s=this.paintVertexArray.length,a=this.expression.evaluate(new cs(0),e,{},n,[],i);this.paintVertexArray.resize(t),this._setPaintValue(s,t,a);}updatePaintArray(t,e,r,n){const i=this.expression.evaluate({zoom:0},r,n);this._setPaintValue(t,e,i);}_setPaintValue(t,e,r){if("color"===this.type){const n=Ha(r);for(let r=t;r`u_${t}_t`)),this.type=r,this.useIntegerZoom=n,this.zoom=i,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?4:2,offset:0}))),this.paintVertexArray=new s;}populatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new cs(this.zoom),e,{},n,[],i),a=this.expression.evaluate(new cs(this.zoom+1),e,{},n,[],i),o=this.paintVertexArray.length;this.paintVertexArray.resize(t),this._setPaintValue(o,t,s,a);}updatePaintArray(t,e,r,n){const i=this.expression.evaluate({zoom:this.zoom},r,n),s=this.expression.evaluate({zoom:this.zoom+1},r,n);this._setPaintValue(t,e,i,s);}_setPaintValue(t,e,r,n){if("color"===this.type){const i=Ha(r),s=Ha(n);for(let r=t;r`#define HAS_UNIFORM_${t}`)));}return t}getBinderAttributes(){const t=[];for(const e in this.binders){const r=this.binders[e];if(r instanceof Wa||r instanceof Qa)for(let e=0;etrue)){this.programConfigurations={};for(const n of t)this.programConfigurations[n.id]=new eo(n,e,r);this.needsUpload=false,this._featureMap=new Ra,this._bufferOffset=0;}populatePaintArrays(t,e,r,n,i,s){for(const r in this.programConfigurations)this.programConfigurations[r].populatePaintArrays(t,e,n,i,s);undefined!==e.id&&this._featureMap.add(e.id,r,this._bufferOffset,t),this._bufferOffset=t,this.needsUpload=true;}updatePaintArrays(t,e,r,n){for(const i of r)this.needsUpload=this.programConfigurations[i.id].updatePaintArrays(t,this._featureMap,e,i,n)||this.needsUpload;}get(t){return this.programConfigurations[t]}upload(t){if(this.needsUpload){for(const e in this.programConfigurations)this.programConfigurations[e].upload(t);this.needsUpload=false;}}destroy(){for(const t in this.programConfigurations)this.programConfigurations[t].destroy();}}function no(t,e){return {"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[t]||[t.replace(`${e}-`,"").replace(/-/g,"_")]}function io(t,e,r){const n={color:{source:Ls,composite:ta},number:{source:Hs,composite:Ls}},i=function(t){return {"line-pattern":{source:va,composite:va},"fill-pattern":{source:va,composite:va},"fill-extrusion-pattern":{source:va,composite:va}}[t]}(t);return i&&i[r]||n[e][r]}Ui("ConstantBinder",Ya),Ui("CrossFadedConstantBinder",Ja),Ui("SourceExpressionBinder",Wa),Ui("CrossFadedCompositeBinder",to),Ui("CompositeExpressionBinder",Qa),Ui("ProgramConfiguration",eo,{omit:["_buffers"]}),Ui("ProgramConfigurationSet",ro);const so=Math.pow(2,14)-1,ao=-so-1;function oo(t){const e=M/t.extent,r=t.loadGeometry();for(let t=0;tr.x+1||sr.y+1)&&j("Geometry exceeds allowed extent, reduce your vector tile buffer size");}}return r}function lo(t,e){return {type:t.type,id:t.id,properties:t.properties,geometry:e?oo(t):[]}}const uo=-32768;function co(t,e,r,n,i){t.emplaceBack(uo+8*e+n,uo+8*r+i);}class ho{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=false,this.layoutVertexArray=new da,this.indexArray=new ka,this.segments=new Pa,this.programConfigurations=new ro(t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){const n=this.layers[0],i=[];let s=null,a=false,o="heatmap"===n.type;if("circle"===n.type){const t=n;s=t.layout.get("circle-sort-key"),a=!s.isConstant(),o=o||"map"===t.paint.get("circle-pitch-alignment");}const l=o?e.subdivisionGranularity.circle:1;for(const{feature:e,id:n,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=lo(e,t);if(!this.layers[0]._featureFilter.filter(new cs(this.zoom),u,r))continue;const c=a?s.evaluate(u,{},r):undefined,h={id:n,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:oo(e),patterns:{},sortKey:c};i.push(h);}a&&i.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of i){const{geometry:i,index:s,sourceLayerIndex:a}=n,o=t[s].feature;this.addFeature(n,i,s,r,l),e.featureIndex.insert(o,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,za),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=true;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}addFeature(t,e,r,n,i=1){let s;switch(i){case 1:s=[0,7];break;case 3:s=[0,2,5,7];break;case 5:s=[0,1,3,4,6,7];break;case 7:s=[0,1,2,3,4,5,6,7];break;default:throw new Error(`Invalid circle bucket granularity: ${i}; valid values are 1, 3, 5, 7.`)}const a=s.length;for(const r of e)for(const e of r){const r=e.x,n=e.y;if(r<0||r>=M||n<0||n>=M)continue;const i=this.segments.prepareSegment(a*a,this.layoutVertexArray,this.indexArray,t.sortKey),o=i.vertexLength;for(let t=0;t1){if(go(t,e))return true;for(let n=0;n1?r:r.sub(e)._mult(i)._add(e))}function wo(t,e){let r,n,i,s=false;for(let a=0;ae.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(s=!s);}return s}function _o(t,e){let r=false;for(let n=0,i=t.length-1;ne.y!=a.y>e.y&&e.x<(a.x-s.x)*(e.y-s.y)/(a.y-s.y)+s.x&&(r=!r);}return r}function So(t,e,r){const n=r[0],i=r[2];if(t.xi.x&&e.x>i.x||t.yi.y&&e.y>i.y)return false;const s=N(t,e,r[0]);return s!==N(t,e,r[1])||s!==N(t,e,r[2])||s!==N(t,e,r[3])}function Ao(t,e,r){const n=e.paint.get(t).value;return "constant"===n.kind?n.value:r.programConfigurations.get(e.id).getMaxValue(t)}function ko(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function Mo(t,e,r,n,i){if(!e[0]&&!e[1])return t;const s=l.convert(e)._mult(i);"viewport"===r&&s._rotate(-n);const a=[];for(let e=0;eBo(t,e)))}(o,a),h=u?l*s:l;for(const t of n)for(const e of t){const t=u?e:Bo(e,a);let r=h;const n=_([],[e.x,e.y,0,1],a);if("viewport"===this.paint.get("circle-pitch-scale")&&"map"===this.paint.get("circle-pitch-alignment")?r*=n[3]/i.cameraToCenterDistance:"map"===this.paint.get("circle-pitch-scale")&&"viewport"===this.paint.get("circle-pitch-alignment")&&(r*=i.cameraToCenterDistance/n[3]),fo(c,t,r))return true}return false}}function Bo(t,e){const r=_([],[t.x,t.y,0,1],e);return new l(r[0]/r[3],r[1]/r[3])}class Vo extends ho{}let Eo;Ui("HeatmapBucket",Vo,{omit:["layers"]});var To={get paint(){return Eo=Eo||new As({"heatmap-radius":new bs(ht.paint_heatmap["heatmap-radius"]),"heatmap-weight":new bs(ht.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new vs(ht.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Ss(ht.paint_heatmap["heatmap-color"]),"heatmap-opacity":new vs(ht.paint_heatmap["heatmap-opacity"])})}};function Fo(t,{width:e,height:r},n,i){if(i){if(i instanceof Uint8ClampedArray)i=new Uint8Array(i.buffer);else if(i.length!==e*r*n)throw new RangeError(`mismatched image size. expected: ${i.length} but got: ${e*r*n}`)}else i=new Uint8Array(e*r*n);return t.width=e,t.height=r,t.data=i,t}function $o(t,{width:e,height:r},n){if(e===t.width&&r===t.height)return;const i=Fo({},{width:e,height:r},n);Lo(t,i,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,e),height:Math.min(t.height,r)},n),t.width=e,t.height=r,t.data=i.data;}function Lo(t,e,r,n,i,s){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");const a=t.data,o=e.data;if(a===o)throw new Error("srcData equals dstData, so image is already copied");for(let l=0;l{e[t.evaluationKey]=s;const a=t.expression.evaluate(e);i.data[r+n+0]=Math.floor(255*a.r/a.a),i.data[r+n+1]=Math.floor(255*a.g/a.a),i.data[r+n+2]=Math.floor(255*a.b/a.a),i.data[r+n+3]=Math.floor(255*a.a);};if(t.clips)for(let e=0,i=0;e0)for(let i=e;i=e;i-=n)s=xl(i/n|0,t[i],t[i+1],s);return s&&pl(s,s.next)&&(vl(s),s=s.next),s}function Jo(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=false,n.steiner||!pl(n,n.next)&&0!==hl(n.prev,n,n.next))n=n.next;else {if(vl(n),n=e=n.prev,n===n.next)break;r=true;}}while(r||n!==e);return e}function Wo(t,e,r,n,i,s,a){if(!t)return;!a&&s&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=al(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let s=null;for(e=0;i;){e++;let a=i,o=0;for(let t=0;t0||l>0&&a;)0!==o&&(0===l||!a||i.z<=a.z)?(n=i,i=i.nextZ,o--):(n=a,a=a.nextZ,l--),s?s.nextZ=n:t=n,n.prevZ=s,s=n;i=a;}s.nextZ=null,r*=2;}while(e>1)}(i);}(t,n,i,s);let o=t;for(;t.prev!==t.next;){const l=t.prev,u=t.next;if(s?tl(t,n,i,s):Qo(t))e.push(l.i,t.i,u.i),vl(t),t=u.next,o=u.next;else if((t=u)===o){a?1===a?Wo(t=el(Jo(t),e),e,r,n,i,s,2):2===a&&rl(t,e,r,n,i,s):Wo(Jo(t),e,r,n,i,s,1);break}}}function Qo(t){const e=t.prev,r=t,n=t.next;if(hl(e,r,n)>=0)return false;const i=e.x,s=r.x,a=n.x,o=e.y,l=r.y,u=n.y,c=Math.min(i,s,a),h=Math.min(o,l,u),p=Math.max(i,s,a),f=Math.max(o,l,u);let d=n.next;for(;d!==e;){if(d.x>=c&&d.x<=p&&d.y>=h&&d.y<=f&&ul(i,o,s,l,a,u,d.x,d.y)&&hl(d.prev,d,d.next)>=0)return false;d=d.next;}return true}function tl(t,e,r,n){const i=t.prev,s=t,a=t.next;if(hl(i,s,a)>=0)return false;const o=i.x,l=s.x,u=a.x,c=i.y,h=s.y,p=a.y,f=Math.min(o,l,u),d=Math.min(c,h,p),y=Math.max(o,l,u),m=Math.max(c,h,p),g=al(f,d,e,r,n),x=al(y,m,e,r,n);let v=t.prevZ,b=t.nextZ;for(;v&&v.z>=g&&b&&b.z<=x;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&ul(o,c,l,h,u,p,v.x,v.y)&&hl(v.prev,v,v.next)>=0)return false;if(v=v.prevZ,b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&ul(o,c,l,h,u,p,b.x,b.y)&&hl(b.prev,b,b.next)>=0)return false;b=b.nextZ;}for(;v&&v.z>=g;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&ul(o,c,l,h,u,p,v.x,v.y)&&hl(v.prev,v,v.next)>=0)return false;v=v.prevZ;}for(;b&&b.z<=x;){if(b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&ul(o,c,l,h,u,p,b.x,b.y)&&hl(b.prev,b,b.next)>=0)return false;b=b.nextZ;}return true}function el(t,e){let r=t;do{const n=r.prev,i=r.next.next;!pl(n,i)&&fl(n,r,r.next,i)&&ml(n,i)&&ml(i,n)&&(e.push(n.i,r.i,i.i),vl(r),vl(r.next),r=t=i),r=r.next;}while(r!==t);return Jo(r)}function rl(t,e,r,n,i,s){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&cl(a,t)){let o=gl(a,t);return a=Jo(a,a.next),o=Jo(o,o.next),Wo(a,e,r,n,i,s,0),void Wo(o,e,r,n,i,s,0)}t=t.next;}a=a.next;}while(a!==t)}function nl(t,e){let r=t.x-e.x;return 0===r&&(r=t.y-e.y,0===r)&&(r=(t.next.y-t.y)/(t.next.x-t.x)-(e.next.y-e.y)/(e.next.x-e.x)),r}function il(t,e){const r=function(t,e){let r=e;const n=t.x,i=t.y;let s,a=-1/0;if(pl(t,r))return r;do{if(pl(t,r.next))return r.next;if(i<=r.y&&i>=r.next.y&&r.next.y!==r.y){const t=r.x+(i-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(t<=n&&t>a&&(a=t,s=r.x=r.x&&r.x>=l&&n!==r.x&&ll(is.x||r.x===s.x&&sl(s,r)))&&(s=r,c=e);}r=r.next;}while(r!==o);return s}(t,e);if(!r)return e;const n=gl(r,t);return Jo(n,n.next),Jo(r,r.next)}function sl(t,e){return hl(t.prev,t,e.prev)<0&&hl(e.next,t,t.next)<0}function al(t,e,r,n,i){return (t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function ol(t){let e=t,r=t;do{(e.x=(t-a)*(s-o)&&(t-a)*(n-o)>=(r-a)*(e-o)&&(r-a)*(s-o)>=(i-a)*(n-o)}function ul(t,e,r,n,i,s,a,o){return !(t===a&&e===o)&&ll(t,e,r,n,i,s,a,o)}function cl(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&fl(r,r.next,t,e))return true;r=r.next;}while(r!==t);return false}(t,e)&&(ml(t,e)&&ml(e,t)&&function(t,e){let r=t,n=false;const i=(t.x+e.x)/2,s=(t.y+e.y)/2;do{r.y>s!=r.next.y>s&&r.next.y!==r.y&&i<(r.next.x-r.x)*(s-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)&&(hl(t.prev,t,e.prev)||hl(t,e.prev,e))||pl(t,e)&&hl(t.prev,t,t.next)>0&&hl(e.prev,e,e.next)>0)}function hl(t,e,r){return (e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function pl(t,e){return t.x===e.x&&t.y===e.y}function fl(t,e,r,n){const i=yl(hl(t,e,r)),s=yl(hl(t,e,n)),a=yl(hl(r,n,t)),o=yl(hl(r,n,e));return i!==s&&a!==o||!(0!==i||!dl(t,r,e))||!(0!==s||!dl(t,n,e))||!(0!==a||!dl(r,t,n))||!(0!==o||!dl(r,e,n))}function dl(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function yl(t){return t>0?1:t<0?-1:0}function ml(t,e){return hl(t.prev,t,t.next)<0?hl(t,e,t.next)>=0&&hl(t,t.prev,e)>=0:hl(t,e,t.prev)<0||hl(t,t.next,e)<0}function gl(t,e){const r=bl(t.i,t.x,t.y),n=bl(e.i,e.x,e.y),i=t.next,s=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,s.next=n,n.prev=s,n}function xl(t,e,r,n){const i=bl(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function vl(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ);}function bl(t,e,r){return {i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:false}}class wl{constructor(t,e){if(e>t)throw new Error("Min granularity must not be greater than base granularity.");this._baseZoomGranularity=t,this._minGranularity=e;}getGranularityForZoomLevel(t){return Math.max(Math.floor(this._baseZoomGranularity/(1<32767||e>32767)throw new Error("Vertex coordinates are out of signed 16 bit integer range.");const r=0|Math.round(t),n=0|Math.round(e),i=this._getKey(r,n);if(this._vertexDictionary.has(i))return this._vertexDictionary.get(i);const s=this._vertexBuffer.length/2;return this._vertexDictionary.set(i,s),this._vertexBuffer.push(r,n),s}_subdivideTrianglesScanline(t){if(this._granularity<2)return function(t,e){const r=[];for(let n=0;n0?(r.push(i),r.push(a),r.push(s)):(r.push(i),r.push(s),r.push(a));}return r}(this._vertexBuffer,t);const e=[],r=t.length;for(let n=0;n=1||v<=0)||y&&(oi)){u>=n&&u<=i&&s.push(r[(t+1)%3]);continue}!y&&x>0&&s.push(this._vertexToIndex(a+p*x,o+f*x));const b=a+p*Math.max(x,0),w=a+p*Math.min(v,1);d||this._generateIntraEdgeVertices(s,a,o,l,u,b,w),!y&&v<1&&s.push(this._vertexToIndex(a+p*v,o+f*v)),(y||u>=n&&u<=i)&&s.push(r[(t+1)%3]),!y&&(u<=n||u>=i)&&this._generateInterEdgeVertices(s,a,o,l,u,c,h,w,n,i);}return s}_generateIntraEdgeVertices(t,e,r,n,i,s,a){const o=n-e,l=i-r,u=0===l,c=u?Math.min(e,n):Math.min(s,a),h=u?Math.max(e,n):Math.max(s,a),p=Math.floor(c/this._granularityCellSize)+1,f=Math.ceil(h/this._granularityCellSize)-1;if(u?e=p;n--){const i=n*this._granularityCellSize;t.push(this._vertexToIndex(i,r+l*(i-e)/o));}}_generateInterEdgeVertices(t,e,r,n,i,s,a,o,l,u){const c=i-r,h=s-n,p=a-i,f=(l-i)/p,d=(u-i)/p,y=Math.min(f,d),m=Math.max(f,d),g=n+h*y;let x=Math.floor(Math.min(g,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(g,o)/this._granularityCellSize)-1,b=o=1||m<=0){const t=r-a,n=s+(e-s)*Math.min((l-a)/t,(u-a)/t);x=Math.floor(Math.min(n,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(n,o)/this._granularityCellSize)-1,b=o0?u:l;if(b)for(let e=x;e<=v;e++)t.push(this._vertexToIndex(e*this._granularityCellSize,_));else for(let e=v;e>=x;e--)t.push(this._vertexToIndex(e*this._granularityCellSize,_));}_generateOutline(t){const e=[];for(const r of t){const t=Il(r,this._granularity,true),n=this._pointArrayToIndices(t),i=[];for(let t=1;ti!=(s===Sl)?(t.push(e),t.push(r),t.push(this._vertexToIndex(n,s)),t.push(r),t.push(this._vertexToIndex(i,s)),t.push(this._vertexToIndex(n,s))):(t.push(r),t.push(e),t.push(this._vertexToIndex(n,s)),t.push(this._vertexToIndex(i,s)),t.push(r),t.push(this._vertexToIndex(n,s)));}_fillPoles(t,e,r){const n=this._vertexBuffer,i=M,s=t.length;for(let a=2;a80*r){o=1/0,l=1/0;let e=-1/0,n=-1/0;for(let s=r;se&&(e=r),i>n&&(n=i);}u=Math.max(e-o,n-l),u=0!==u?32767/u:0;}return Wo(s,a,r,o,l,u,0),a}(r,n),e=this._convertIndices(r,t);i=this._subdivideTrianglesScanline(e);}catch(t){console.error(t);}let s=[];return e&&(s=this._generateOutline(t)),this._ensureNoPoleVertices(),this._handlePoles(i),{verticesFlattened:this._vertexBuffer,indicesTriangles:i,indicesLineList:s}}_convertIndices(t,e){const r=[];for(let n=0;n0?(Math.floor(x/a)+1)*a:(Math.ceil(x/a)-1)*a,e=y>0?(Math.floor(v/a)+1)*a:(Math.ceil(v/a)-1)*a,r=Math.abs(x-t),n=Math.abs(v-e),i=Math.abs(x-c),s=Math.abs(v-h),u=p?r/m:Number.POSITIVE_INFINITY,b=f?n/g:Number.POSITIVE_INFINITY;if((i<=r||!p)&&(s<=n||!f))break;if(u=0?a-1:s-1,i=(o+1)%s,l=t[2*e[n]],u=t[2*e[i]],c=t[2*e[a]],h=t[2*e[a]+1],p=t[2*e[o]+1];let f=false;if(lu)f=false;else {const r=p-h,s=-(t[2*e[o]]-c),a=h((u-c)*r+(t[2*e[i]+1]-h)*s)*a&&(f=true);}if(f){const t=e[n],i=e[a],l=e[o];t!==i&&t!==l&&i!==l&&r.push(l,i,t),a--,a<0&&(a=s-1);}else {const t=e[i],n=e[a],l=e[o];t!==n&&t!==l&&n!==l&&r.push(l,n,t),o++,o>=s&&(o=0);}if(n===i)break}}function Pl(t,e,r,n,i,s,a,o,l){const u=i.length/2,c=a&&o&&l;if(uPa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,y=true,m=true,g=true,c=0);const x=Cl(a,n,s,o,p,y,u),v=Cl(a,n,s,o,f,m,u),b=Cl(a,n,s,o,d,g,u);r.emplaceBack(c+x-l,c+v-l,c+b-l),u.primitiveLength++;}}(e,r,n,i,s,t),c&&function(t,e,r,n,i,s){const a=[];for(let t=0;tPa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,d=true,y=true,c=0);const m=Cl(a,n,s,o,i,d,u),g=Cl(a,n,s,o,h,y,u);r.emplaceBack(c+m-l,c+g-l),u.primitiveLength++;}}}(a,r,o,i,l,t),e.forceNewSegmentOnNextPrepare(),null==a||a.forceNewSegmentOnNextPrepare();}function Cl(t,e,r,n,i,s,a){if(s){const s=n.count;return r(e[2*i],e[2*i+1]),t[i]=n.count,n.count++,a.vertexLength++,s}return t[i]}class Bl{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=false,this.patternFeatures=[],this.layoutVertexArray=new ya,this.indexArray=new ka,this.indexArray2=new Ma,this.programConfigurations=new ro(t.layers,t.zoom),this.segments=new Pa,this.segments2=new Pa,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=Ko("fill",this.layers,e);const n=this.layers[0].layout.get("fill-sort-key"),i=!n.isConstant(),s=[];for(const{feature:a,id:o,index:l,sourceLayerIndex:u}of t){const t=this.layers[0]._featureFilter.needGeometry,c=lo(a,t);if(!this.layers[0]._featureFilter.filter(new cs(this.zoom),c,r))continue;const h=i?n.evaluate(c,{},r,e.availableImages):undefined,p={id:o,properties:a.properties,type:a.type,sourceLayerIndex:u,index:l,geometry:t?c.geometry:oo(a),patterns:{},sortKey:h};s.push(p);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=Ho("fill",this.layers,n,this.zoom,e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Xo),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(t),this.uploaded=true;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy());}addFeature(t,e,r,n,i,s){for(const t of Le(e,500)){const e=Ml(t,n,s.fill.getGranularityForZoomLevel(n.z)),r=this.layoutVertexArray;Pl(((t,e)=>{r.emplaceBack(t,e);}),this.segments,this.layoutVertexArray,this.indexArray,e.verticesFlattened,e.indicesTriangles,this.segments2,this.indexArray2,e.indicesLineList);}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,i,n);}}let Vl,El;Ui("FillBucket",Bl,{omit:["layers","patternFeatures"]});var Tl={get paint(){return El=El||new As({"fill-antialias":new vs(ht.paint_fill["fill-antialias"]),"fill-opacity":new bs(ht.paint_fill["fill-opacity"]),"fill-color":new bs(ht.paint_fill["fill-color"]),"fill-outline-color":new bs(ht.paint_fill["fill-outline-color"]),"fill-translate":new vs(ht.paint_fill["fill-translate"]),"fill-translate-anchor":new vs(ht.paint_fill["fill-translate-anchor"]),"fill-pattern":new ws(ht.paint_fill["fill-pattern"])})},get layout(){return Vl=Vl||new As({"fill-sort-key":new bs(ht.layout_fill["fill-sort-key"])})}};class Fl extends Ms{constructor(t){super(t,Tl);}recalculate(t,e){super.recalculate(t,e);const r=this.paint._values["fill-outline-color"];"constant"===r.value.kind&&undefined===r.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"]);}createBucket(t){return new Bl(t)}queryRadius(){return ko(this.paint.get("fill-translate"))}queryIntersectsFeature({queryGeometry:t,geometry:e,transform:r,pixelsToTileUnits:n}){return yo(Mo(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),-r.bearingInRadians,n),e)}isTileClipped(){return true}}const $l=Cs([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4),Ll=Cs([{name:"a_centroid",components:2,type:"Int16"}],4),{members:Dl}=$l;var Ol,Rl,jl,Nl,Ul,ql,Gl,Zl={};function Xl(){if(Rl)return Ol;Rl=1;var t=s();function e(t,e,n,i,s){this.properties={},this.extent=n,this.type=0,this._pbf=t,this._geometry=-1,this._keys=i,this._values=s,t.readFields(r,this,e);}function r(t,e,r){1==t?e.id=r.readVarint():2==t?function(t,e){for(var r=t.readVarint()+t.pos;t.pos>3;}if(s--,1===i||2===i)a+=e.readSVarint(),o+=e.readSVarint(),1===i&&(r&&l.push(r),r=[]),r.push(new t(a,o));else {if(7!==i)throw new Error("unknown command "+i);r&&r.push(r[0].clone());}}return r&&l.push(r),l},e.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,s=0,a=1/0,o=-1/0,l=1/0,u=-1/0;t.pos>3;}if(n--,1===r||2===r)(i+=t.readSVarint())o&&(o=i),(s+=t.readSVarint())u&&(u=s);else if(7!==r)throw new Error("unknown command "+r)}return [a,l,o,u]},e.prototype.toGeoJSON=function(t,r,i){var s,a,o=this.extent*Math.pow(2,i),l=this.extent*t,u=this.extent*r,c=this.loadGeometry(),h=e.types[this.type];function p(t){for(var e=0;e>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null;}return e}(r));}return jl=e,e.prototype.feature=function(e){if(e<0||e>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[e];var r=this._pbf.readVarint()+this._pbf.pos;return new t(this._pbf,r,this.extent,this._keys,this._values)},jl}function Hl(){return Gl||(Gl=1,Zl.VectorTile=function(){if(ql)return Ul;ql=1;var t=Kl();function e(e,r,n){if(3===e){var i=new t(n,n.readVarint()+n.pos);i.length&&(r[i.name]=i);}}return Ul=function(t,r){this.layers=t.readFields(e,{},r);},Ul}(),Zl.VectorTileFeature=Xl(),Zl.VectorTileLayer=Kl()),Zl}var Yl=r(Hl());const Jl=Yl.VectorTileFeature.types,Wl=Math.pow(2,13);function Ql(t,e,r,n,i,s,a,o){t.emplaceBack(e,r,2*Math.floor(n*Wl)+a,i*Wl*2,s*Wl*2,Math.round(o));}class tu{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=false,this.layoutVertexArray=new ma,this.centroidVertexArray=new fa,this.indexArray=new ka,this.programConfigurations=new ro(t.layers,t.zoom),this.segments=new Pa,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.features=[],this.hasPattern=Ko("fill-extrusion",this.layers,e);for(const{feature:n,id:i,index:s,sourceLayerIndex:a}of t){const t=this.layers[0]._featureFilter.needGeometry,o=lo(n,t);if(!this.layers[0]._featureFilter.filter(new cs(this.zoom),o,r))continue;const l={id:i,sourceLayerIndex:a,index:s,geometry:t?o.geometry:oo(n),properties:n.properties,type:n.type,patterns:{}};this.hasPattern?this.features.push(Ho("fill-extrusion",this.layers,l,this.zoom,e)):this.addFeature(l,l.geometry,s,r,{},e.subdivisionGranularity),e.featureIndex.insert(n,l.geometry,s,a,this.index,true);}}addFeatures(t,e,r){for(const n of this.features){const{geometry:i}=n;this.addFeature(n,i,n.index,e,r,t.subdivisionGranularity);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);}isEmpty(){return 0===this.layoutVertexArray.length&&0===this.centroidVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Dl),this.centroidVertexBuffer=t.createVertexBuffer(this.centroidVertexArray,Ll.members,true),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=true;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy());}addFeature(t,e,r,n,i,s){for(const r of Le(e,500)){const e={x:0,y:0,sampleCount:0},i=this.layoutVertexArray.length;this.processPolygon(e,n,t,r,s);const a=this.layoutVertexArray.length-i,o=Math.floor(e.x/e.sampleCount),l=Math.floor(e.y/e.sampleCount);for(let t=0;t{Ql(u,t,e,0,0,1,1,0);}),this.segments,this.layoutVertexArray,this.indexArray,l.verticesFlattened,l.indicesTriangles);}_generateSideFaces(t,e){let r=0;for(let n=1;nPa.MAX_VERTEX_ARRAY_LENGTH&&(e.segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));const a=i.sub(s)._perp()._unit(),o=s.dist(i);r+o>32768&&(r=0),Ql(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,0,r),Ql(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,1,r),r+=o,Ql(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,0,r),Ql(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,1,r);const l=e.segment.vertexLength;this.indexArray.emplaceBack(l,l+2,l+1),this.indexArray.emplaceBack(l+1,l+2,l+3),e.segment.vertexLength+=4,e.segment.primitiveLength+=2;}}}function eu(t,e){for(let r=0;rM)||t.y===e.y&&(t.y<0||t.y>M)}function nu(t){return t.every((t=>t.x<0))||t.every((t=>t.x>M))||t.every((t=>t.y<0))||t.every((t=>t.y>M))}let iu;Ui("FillExtrusionBucket",tu,{omit:["layers","features"]});var su={get paint(){return iu=iu||new As({"fill-extrusion-opacity":new vs(ht["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new bs(ht["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new vs(ht["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new vs(ht["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new ws(ht["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new bs(ht["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new bs(ht["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new vs(ht["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})}};class au extends Ms{constructor(t){super(t,su);}createBucket(t){return new tu(t)}queryRadius(){return ko(this.paint.get("fill-extrusion-translate"))}is3D(){return true}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:r,geometry:n,transform:i,pixelsToTileUnits:s,pixelPosMatrix:a}){const o=Mo(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),-i.bearingInRadians,s),u=this.paint.get("fill-extrusion-height").evaluate(e,r),c=this.paint.get("fill-extrusion-base").evaluate(e,r),h=function(t,e,r){const n=[];for(const r of t){const t=[r.x,r.y,0,1];_(t,t,e),n.push(new l(t[0]/t[3],t[1]/t[3]));}return n}(o,a),p=function(t,e,r,n){const i=[],s=[],a=n[8]*e,o=n[9]*e,u=n[10]*e,c=n[11]*e,h=n[8]*r,p=n[9]*r,f=n[10]*r,d=n[11]*r;for(const e of t){const t=[],r=[];for(const i of e){const e=i.x,s=i.y,y=n[0]*e+n[4]*s+n[12],m=n[1]*e+n[5]*s+n[13],g=n[2]*e+n[6]*s+n[14],x=n[3]*e+n[7]*s+n[15],v=g+u,b=x+c,w=y+h,_=m+p,S=g+f,A=x+d,k=new l((y+a)/b,(m+o)/b);k.z=v/b,t.push(k);const M=new l(w/A,_/A);M.z=S/A,r.push(M);}i.push(t),s.push(r);}return [i,s]}(n,c,u,a);return function(t,e,r){let n=1/0;yo(r,e)&&(n=lu(r,e[0]));for(let i=0;it.id)),this.index=t.index,this.hasPattern=false,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach((t=>{this.gradients[t.id]={};})),this.layoutVertexArray=new ga,this.layoutVertexArray2=new xa,this.indexArray=new ka,this.programConfigurations=new ro(t.layers,t.zoom),this.segments=new Pa,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=Ko("line",this.layers,e);const n=this.layers[0].layout.get("line-sort-key"),i=!n.isConstant(),s=[];for(const{feature:e,id:a,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=lo(e,t);if(!this.layers[0]._featureFilter.filter(new cs(this.zoom),u,r))continue;const c=i?n.evaluate(u,{},r):undefined,h={id:a,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:oo(e),patterns:{},sortKey:c};s.push(h);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=Ho("line",this.layers,n,this.zoom,e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(0!==this.layoutVertexArray2.length&&(this.layoutVertexBuffer2=t.createVertexBuffer(this.layoutVertexArray2,pu)),this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,cu),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=true;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}lineFeatureClips(t){if(t.properties&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_start")&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_end"))return {start:+t.properties.mapbox_clip_start,end:+t.properties.mapbox_clip_end}}addFeature(t,e,r,n,i,s){const a=this.layers[0].layout,o=a.get("line-join").evaluate(t,{}),l=a.get("line-cap"),u=a.get("line-miter-limit"),c=a.get("line-round-limit");this.lineClips=this.lineFeatureClips(t);for(const r of e)this.addLine(r,t,o,l,u,c,n,s);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,i,n);}addLine(t,e,r,n,i,s,a,o){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,t=Il(t,a?o.line.getGranularityForZoomLevel(a.z):1),this.lineClips){this.lineClipsArray.push(this.lineClips);for(let e=0;e=2&&t[u-1].equals(t[u-2]);)u--;let c=0;for(;c0;if(w&&e>c){const t=f.dist(d);if(t>2*h){const e=f.sub(f.sub(d)._mult(h/t)._round());this.updateDistance(d,e),this.addCurrentVertex(e,m,0,0,p),d=e;}}const S=d&&y;let A=S?r:l?"butt":n;if(S&&"round"===A&&(vi&&(A="bevel"),"bevel"===A&&(v>2&&(A="flipbevel"),v100)a=g.mult(-1);else {const t=v*m.add(g).mag()/m.sub(g).mag();a._perp()._mult(t*(_?-1:1));}this.addCurrentVertex(f,a,0,0,p),this.addCurrentVertex(f,a.mult(-1),0,0,p);}else if("bevel"===A||"fakeround"===A){const t=-Math.sqrt(v*v-1),e=_?t:0,r=_?0:t;if(d&&this.addCurrentVertex(f,m,e,r,p),"fakeround"===A){const t=Math.round(180*b/Math.PI/20);for(let e=1;e2*h){const e=f.add(y.sub(f)._mult(h/t)._round());this.updateDistance(f,e),this.addCurrentVertex(e,g,0,0,p),f=e;}}}}addCurrentVertex(t,e,r,n,i,s=false){const a=e.y*n-e.x,o=-e.y-e.x*n;this.addHalfVertex(t,e.x+e.y*r,e.y-e.x*r,s,false,r,i),this.addHalfVertex(t,a,o,s,true,-n,i),this.distance>yu/2&&0===this.totalDistance&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(t,e,r,n,i,s));}addHalfVertex({x:t,y:e},r,n,i,s,a,o){const l=.5*(this.lineClips?this.scaledDistance*(yu-1):this.scaledDistance);this.layoutVertexArray.emplaceBack((t<<1)+(i?1:0),(e<<1)+(s?1:0),Math.round(63*r)+128,Math.round(63*n)+128,1+(0===a?0:a<0?-1:1)|(63&l)<<2,l>>6),this.lineClips&&this.layoutVertexArray2.emplaceBack((this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start),this.lineClipsArray.length);const u=o.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,u,this.e2),o.primitiveLength++),s?this.e2=u:this.e1=u;}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance;}updateDistance(t,e){this.distance+=t.dist(e),this.updateScaledDistance();}}let gu,xu;Ui("LineBucket",mu,{omit:["layers","patternFeatures"]});var vu={get paint(){return xu=xu||new As({"line-opacity":new bs(ht.paint_line["line-opacity"]),"line-color":new bs(ht.paint_line["line-color"]),"line-translate":new vs(ht.paint_line["line-translate"]),"line-translate-anchor":new vs(ht.paint_line["line-translate-anchor"]),"line-width":new bs(ht.paint_line["line-width"]),"line-gap-width":new bs(ht.paint_line["line-gap-width"]),"line-offset":new bs(ht.paint_line["line-offset"]),"line-blur":new bs(ht.paint_line["line-blur"]),"line-dasharray":new _s(ht.paint_line["line-dasharray"]),"line-pattern":new ws(ht.paint_line["line-pattern"]),"line-gradient":new Ss(ht.paint_line["line-gradient"])})},get layout(){return gu=gu||new As({"line-cap":new vs(ht.layout_line["line-cap"]),"line-join":new bs(ht.layout_line["line-join"]),"line-miter-limit":new vs(ht.layout_line["line-miter-limit"]),"line-round-limit":new vs(ht.layout_line["line-round-limit"]),"line-sort-key":new bs(ht.layout_line["line-sort-key"])})}};class bu extends bs{possiblyEvaluate(t,e){return e=new cs(Math.floor(e.zoom),{now:e.now,fadeDuration:e.fadeDuration,zoomHistory:e.zoomHistory,transition:e.transition}),super.possiblyEvaluate(t,e)}evaluate(t,e,r,n){return e=F({},e,{zoom:Math.floor(e.zoom)}),super.evaluate(t,e,r,n)}}let wu;class _u extends Ms{constructor(t){super(t,vu),this.gradientVersion=0,wu||(wu=new bu(vu.paint.properties["line-width"].specification),wu.useIntegerZoom=true);}_handleSpecialPaintPropertyUpdate(t){if("line-gradient"===t){const t=this.gradientExpression();this.stepInterpolant=!!function(t){return undefined!==t._styleExpression}(t)&&t._styleExpression.expression instanceof Qe,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER;}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(t,e){super.recalculate(t,e),this.paint._values["line-floorwidth"]=wu.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,t);}createBucket(t){return new mu(t)}queryRadius(t){const e=t,r=Su(Ao("line-width",this,e),Ao("line-gap-width",this,e)),n=Ao("line-offset",this,e);return r/2+Math.abs(n)+ko(this.paint.get("line-translate"))}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:r,geometry:n,transform:i,pixelsToTileUnits:s}){const a=Mo(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),-i.bearingInRadians,s),o=s/2*Su(this.paint.get("line-width").evaluate(e,r),this.paint.get("line-gap-width").evaluate(e,r)),u=this.paint.get("line-offset").evaluate(e,r);return u&&(n=function(t,e){const r=[];for(let n=0;n=3)for(let e=0;e0?e+2*t:t}const Au=Cs([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),ku=Cs([{name:"a_projected_pos",components:3,type:"Float32"}],4);Cs([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const Mu=Cs([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_box_real",components:2,type:"Int16"}]);Cs([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const Iu=Cs([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),zu=Cs([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function Pu(t,e,r){return t.sections.forEach((t=>{t.text=function(t,e,r){const n=e.layout.get("text-transform").evaluate(r,{});return "uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),us.applyArabicShaping&&(t=us.applyArabicShaping(t)),t}(t.text,e,r);})),t}Cs([{name:"triangle",components:3,type:"Uint16"}]),Cs([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),Cs([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]),Cs([{type:"Float32",name:"offsetX"}]),Cs([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]),Cs([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);const Cu={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};var Bu,Vu,Eu,Tu=24,Fu={};function $u(){return Bu||(Bu=1,Fu.read=function(t,e,r,n,i){var s,a,o=8*i-n-1,l=(1<>1,c=-7,h=r?i-1:0,p=r?-1:1,f=t[e+h];for(h+=p,s=f&(1<<-c)-1,f>>=-c,c+=o;c>0;s=256*s+t[e+h],h+=p,c-=8);for(a=s&(1<<-c)-1,s>>=-c,c+=n;c>0;a=256*a+t[e+h],h+=p,c-=8);if(0===s)s=1-u;else {if(s===l)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),s-=u;}return (f?-1:1)*a*Math.pow(2,s-n)},Fu.write=function(t,e,r,n,i,s){var a,o,l,u=8*s-i-1,c=(1<>1,p=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:s-1,d=n?1:-1,y=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(o=isNaN(e)?1:0,a=c):(a=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-a))<1&&(a--,l*=2),(e+=a+h>=1?p/l:p*Math.pow(2,1-h))*l>=2&&(a++,l/=2),a+h>=c?(o=0,a=c):a+h>=1?(o=(e*l-1)*Math.pow(2,i),a+=h):(o=e*Math.pow(2,h-1)*Math.pow(2,i),a=0));i>=8;t[r+f]=255&o,f+=d,o/=256,i-=8);for(a=a<0;t[r+f]=255&a,f+=d,a/=256,u-=8);t[r+f-d]|=128*y;}),Fu}function Lu(){if(Eu)return Vu;Eu=1,Vu=e;var t=$u();function e(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length;}e.Varint=0,e.Fixed64=1,e.Bytes=2,e.Fixed32=5;var r=4294967296,n=1/r,i="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");function s(t){return t.type===e.Bytes?t.readVarint()+t.pos:t.pos+1}function a(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function o(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i];}function l(t,e){for(var r=0;r>>8,t[r+2]=e>>>16,t[r+3]=e>>>24;}function v(t,e){return (t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}return e.prototype={destroy:function(){this.buf=null;},readFields:function(t,e,r){for(r=r||this.length;this.pos>3,s=this.pos;this.type=7&n,t(i,e,this),this.pos===s&&this.skip(n);}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=g(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=v(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=g(this.buf,this.pos)+g(this.buf,this.pos+4)*r;return this.pos+=8,t},readSFixed64:function(){var t=g(this.buf,this.pos)+v(this.buf,this.pos+4)*r;return this.pos+=8,t},readFloat:function(){var e=t.read(this.buf,this.pos,true,23,4);return this.pos+=4,e},readDouble:function(){var e=t.read(this.buf,this.pos,true,52,8);return this.pos+=8,e},readVarint:function(t){var e,r,n=this.buf;return e=127&(r=n[this.pos++]),r<128?e:(e|=(127&(r=n[this.pos++]))<<7,r<128?e:(e|=(127&(r=n[this.pos++]))<<14,r<128?e:(e|=(127&(r=n[this.pos++]))<<21,r<128?e:function(t,e,r){var n,i,s=r.buf;if(n=(112&(i=s[r.pos++]))>>4,i<128)return a(t,n,e);if(n|=(127&(i=s[r.pos++]))<<3,i<128)return a(t,n,e);if(n|=(127&(i=s[r.pos++]))<<10,i<128)return a(t,n,e);if(n|=(127&(i=s[r.pos++]))<<17,i<128)return a(t,n,e);if(n|=(127&(i=s[r.pos++]))<<24,i<128)return a(t,n,e);if(n|=(1&(i=s[r.pos++]))<<31,i<128)return a(t,n,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=n[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(true)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&i?function(t,e,r){return i.decode(t.subarray(e,r))}(this.buf,e,t):function(t,e,r){for(var n="",i=e;i239?4:l>223?3:l>191?2:1;if(i+c>r)break;1===c?l<128&&(u=l):2===c?128==(192&(s=t[i+1]))&&(u=(31&l)<<6|63&s)<=127&&(u=null):3===c?(a=t[i+2],128==(192&(s=t[i+1]))&&128==(192&a)&&((u=(15&l)<<12|(63&s)<<6|63&a)<=2047||u>=55296&&u<=57343)&&(u=null)):4===c&&(a=t[i+2],o=t[i+3],128==(192&(s=t[i+1]))&&128==(192&a)&&128==(192&o)&&((u=(15&l)<<18|(63&s)<<12|(63&a)<<6|63&o)<=65535||u>=1114112)&&(u=null)),null===u?(u=65533,c=1):u>65535&&(u-=65536,n+=String.fromCharCode(u>>>10&1023|55296),u=56320|1023&u),n+=String.fromCharCode(u),i+=c;}return n}(this.buf,e,t)},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,r){if(this.type!==e.Bytes)return t.push(this.readVarint(r));var n=s(this);for(t=t||[];this.pos127;);else if(r===e.Bytes)this.pos=this.readVarint()+this.pos;else if(r===e.Fixed32)this.pos+=4;else {if(r!==e.Fixed64)throw new Error("Unimplemented type: "+r);this.pos+=8;}},writeTag:function(t,e){this.writeVarint(t<<3|e);},realloc:function(t){for(var e=this.length||16;e268435455||t<0?function(t,e){var r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(r=~(-t%4294967296))?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,r.buf[r.pos]=127&(t>>>=7);}(r,0,e),function(t,e){var r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t)))));}(n,e);}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))));},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t);},writeBoolean:function(t){this.writeVarint(Boolean(t));},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,r){for(var n,i,s=0;s55295&&n<57344){if(!i){n>56319||s+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);var r=this.pos-e;r>=128&&o(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;},writeFloat:function(e){this.realloc(4),t.write(this.buf,e,this.pos,true,23,4),this.pos+=4;},writeDouble:function(e){this.realloc(8),t.write(this.buf,e,this.pos,true,52,8),this.pos+=8;},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r=128&&o(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;},writeMessage:function(t,r,n){this.writeTag(t,e.Bytes),this.writeRawMessage(r,n);},writePackedVarint:function(t,e){e.length&&this.writeMessage(t,l,e);},writePackedSVarint:function(t,e){e.length&&this.writeMessage(t,u,e);},writePackedBoolean:function(t,e){e.length&&this.writeMessage(t,p,e);},writePackedFloat:function(t,e){e.length&&this.writeMessage(t,c,e);},writePackedDouble:function(t,e){e.length&&this.writeMessage(t,h,e);},writePackedFixed32:function(t,e){e.length&&this.writeMessage(t,f,e);},writePackedSFixed32:function(t,e){e.length&&this.writeMessage(t,d,e);},writePackedFixed64:function(t,e){e.length&&this.writeMessage(t,y,e);},writePackedSFixed64:function(t,e){e.length&&this.writeMessage(t,m,e);},writeBytesField:function(t,r){this.writeTag(t,e.Bytes),this.writeBytes(r);},writeFixed32Field:function(t,r){this.writeTag(t,e.Fixed32),this.writeFixed32(r);},writeSFixed32Field:function(t,r){this.writeTag(t,e.Fixed32),this.writeSFixed32(r);},writeFixed64Field:function(t,r){this.writeTag(t,e.Fixed64),this.writeFixed64(r);},writeSFixed64Field:function(t,r){this.writeTag(t,e.Fixed64),this.writeSFixed64(r);},writeVarintField:function(t,r){this.writeTag(t,e.Varint),this.writeVarint(r);},writeSVarintField:function(t,r){this.writeTag(t,e.Varint),this.writeSVarint(r);},writeStringField:function(t,r){this.writeTag(t,e.Bytes),this.writeString(r);},writeFloatField:function(t,r){this.writeTag(t,e.Fixed32),this.writeFloat(r);},writeDoubleField:function(t,r){this.writeTag(t,e.Fixed64),this.writeDouble(r);},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e));}},Vu}var Du=r(Lu());const Ou=3;function Ru(t,e,r){1===t&&r.readMessage(ju,e);}function ju(t,e,r){if(3===t){const{id:t,bitmap:n,width:i,height:s,left:a,top:o,advance:l}=r.readMessage(Nu,{});e.push({id:t,bitmap:new Do({width:i+2*Ou,height:s+2*Ou},n),metrics:{width:i,height:s,left:a,top:o,advance:l}});}}function Nu(t,e,r){1===t?e.id=r.readVarint():2===t?e.bitmap=r.readBytes():3===t?e.width=r.readVarint():4===t?e.height=r.readVarint():5===t?e.left=r.readSVarint():6===t?e.top=r.readSVarint():7===t&&(e.advance=r.readVarint());}const Uu=Ou;function qu(t){let e=0,r=0;for(const n of t)e+=n.w*n.h,r=Math.max(r,n.w);t.sort(((t,e)=>e.h-t.h));const n=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),r),h:1/0}];let i=0,s=0;for(const e of t)for(let t=n.length-1;t>=0;t--){const r=n[t];if(!(e.w>r.w||e.h>r.h)){if(e.x=r.x,e.y=r.y,s=Math.max(s,e.y+e.h),i=Math.max(i,e.x+e.w),e.w===r.w&&e.h===r.h){const e=n.pop();t=0&&r>=t&&Qu[this.text.charCodeAt(r)];r--)e--;this.text=this.text.substring(t,e),this.sectionIndex=this.sectionIndex.slice(t,e);}substring(t,e){const r=new Ju;return r.text=this.text.substring(t,e),r.sectionIndex=this.sectionIndex.slice(t,e),r.sections=this.sections,r}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce(((t,e)=>Math.max(t,this.sections[e].scale)),0)}addTextSection(t,e){this.text+=t.text,this.sections.push(Yu.forText(t.scale,t.fontStack||e));const r=this.sections.length-1;for(let e=0;e=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function Wu(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y){const m=Ju.fromFeature(e,s);let g;p===t.ai.vertical&&m.verticalizePunctuation();const{processBidirectionalText:x,processStyledBidirectionalText:v}=us;if(x&&1===m.sections.length){g=[];const t=x(m.toString(),oc(m,c,a,r,i,d));for(const e of t){const t=new Ju;t.text=e,t.sections=m.sections;for(let r=0;r0&&n>_&&(_=n);}else {const t=n[y.fontStack],e=t&&t[g];if(e&&e.rect)S=e.rect,b=e.metrics;else {const t=r[y.fontStack],e=t&&t[g];if(!e)continue;b=e.metrics;}x=(s-y.scale)*Tu;}M?(e.verticalizable=true,w.push({glyph:g,imageName:A,x:f,y:d+x,vertical:M,scale:y.scale,fontStack:y.fontStack,sectionIndex:m,metrics:b,rect:S}),f+=k*y.scale+c):(w.push({glyph:g,imageName:A,x:f,y:d+x,vertical:M,scale:y.scale,fontStack:y.fontStack,sectionIndex:m,metrics:b,rect:S}),f+=b.advance*y.scale+c);}0!==w.length&&(y=Math.max(f-c,y),uc(w,0,w.length-1,g,_)),f=0;const S=a*s+_;b.lineOffset=Math.max(_,l),d+=S,m=Math.max(S,m),++x;}var v;const b=d-Hu,{horizontalAlign:w,verticalAlign:_}=lc(o);(((function(t,e,r,n,i,s,a,o,l){const u=(e-r)*i;let c=0;c=s!==a?-o*n-Hu:(-n*l+.5)*a;for(const e of t)for(const t of e.positionedGlyphs)t.x+=u,t.y+=c;})))(e.positionedLines,g,w,_,y,m,a,b,s.length),e.top+=-_*b,e.bottom=e.top+b,e.left+=-w*y,e.right=e.left+y;}(w,r,n,i,g,o,l,u,p,c,f,y),!function(t){for(const e of t)if(0!==e.positionedGlyphs.length)return false;return true}(b)&&w}const Qu={9:true,10:true,11:true,12:true,13:true,32:true},tc={10:true,32:true,38:true,41:true,43:true,45:true,47:true,173:true,183:true,8203:true,8208:true,8211:true,8231:true},ec={40:true};function rc(t,e,r,n,i,s){if(e.imageName){const t=n[e.imageName];return t?t.displaySize[0]*e.scale*Tu/s+i:0}{const n=r[e.fontStack],s=n&&n[t];return s?s.metrics.advance*e.scale+i:0}}function nc(t,e,r,n){const i=Math.pow(t-e,2);return n?t=0;let u=0;for(let r=0;ru){const t=Math.ceil(s/u);i*=t/a,a=t;}return {x1:n,y1:i,x2:n+s,y2:i+a}}function pc(t,e,r,n,i,s){const a=t.image;let o;if(a.content){const t=a.content,e=a.pixelRatio||1;o=[t[0]/e,t[1]/e,a.displaySize[0]-t[2]/e,a.displaySize[1]-t[3]/e];}const l=e.left*s,u=e.right*s;let c,h,p,f;"width"===r||"both"===r?(f=i[0]+l-n[3],h=i[0]+u+n[1]):(f=i[0]+(l+u-a.displaySize[0])/2,h=f+a.displaySize[0]);const d=e.top*s,y=e.bottom*s;return "height"===r||"both"===r?(c=i[1]+d-n[0],p=i[1]+y+n[2]):(c=i[1]+(d+y-a.displaySize[1])/2,p=c+a.displaySize[1]),{image:a,top:c,right:h,bottom:p,left:f,collisionPadding:o}}const fc=255,dc=128,yc=fc*dc;function mc(t,e){const{expression:r}=e;if("constant"===r.kind)return {kind:"constant",layoutSize:r.evaluate(new cs(t+1))};if("source"===r.kind)return {kind:"source"};{const{zoomStops:e,interpolationType:n}=r;let i=0;for(;it.id)),this.index=e.index,this.pixelRatio=e.pixelRatio,this.sourceLayerIndex=e.sourceLayerIndex,this.hasPattern=false,this.hasRTLText=false,this.sortKeyRanges=[],this.collisionCircleArray=[];const r=this.layers[0]._unevaluatedLayout._values;this.textSizeData=mc(this.zoom,r["text-size"]),this.iconSizeData=mc(this.zoom,r["icon-size"]);const n=this.layers[0].layout,i=n.get("symbol-sort-key"),s=n.get("symbol-z-order");this.canOverlap="never"!==gc(n,"text-overlap","text-allow-overlap")||"never"!==gc(n,"icon-overlap","icon-allow-overlap")||n.get("text-ignore-placement")||n.get("icon-ignore-placement"),this.sortFeaturesByKey="viewport-y"!==s&&!i.isConstant(),this.sortFeaturesByY=("viewport-y"===s||"auto"===s&&!this.sortFeaturesByKey)&&this.canOverlap,"point"===n.get("symbol-placement")&&(this.writingModes=n.get("text-writing-mode").map((e=>t.ai[e]))),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id)),this.sourceID=e.sourceID;}createArrays(){this.text=new Sc(new ro(this.layers,this.zoom,(t=>/^text/.test(t)))),this.icon=new Sc(new ro(this.layers,this.zoom,(t=>/^icon/.test(t)))),this.glyphOffsetArray=new oa,this.lineVertexArray=new la,this.symbolInstances=new aa,this.textAnchorOffsets=new ca;}calculateGlyphDependencies(t,e,r,n,i){for(let s=0;s0)&&("constant"!==a.value.kind||a.value.value.length>0),c="constant"!==l.value.kind||!!l.value.value||Object.keys(l.parameters).length>0,h=s.get("symbol-sort-key");if(this.features=[],!u&&!c)return;const p=r.iconDependencies,f=r.glyphDependencies,d=r.availableImages,y=new cs(this.zoom);for(const{feature:r,id:o,index:l,sourceLayerIndex:m}of e){const e=i._featureFilter.needGeometry,g=lo(r,e);if(!i._featureFilter.filter(y,g,n))continue;let x,v;if(e||(g.geometry=oo(r)),u){const t=i.getValueAndResolveTokens("text-field",g,n,d),e=xe.factory(t),r=this.hasRTLText=this.hasRTLText||_c(e);(!r||"unavailable"===us.getRTLTextPluginStatus()||r&&us.isParsed())&&(x=Pu(e,i,g));}if(c){const t=i.getValueAndResolveTokens("icon-image",g,n,d);v=t instanceof Se?t:Se.fromString(t);}if(!x&&!v)continue;const b=this.sortFeaturesByKey?h.evaluate(g,{},n):undefined;if(this.features.push({id:o,text:x,icon:v,index:l,sourceLayerIndex:m,geometry:g.geometry,properties:r.properties,type:xc[r.type],sortKey:b}),v&&(p[v.name]=true),x){const e=a.evaluate(g,{},n).join(","),r="viewport"!==s.get("text-rotation-alignment")&&"point"!==s.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(t.ai.vertical)>=0;for(const t of x.sections)if(t.image)p[t.image.name]=true;else {const n=Ji(x.toString()),i=t.fontStack||e,s=f[i]=f[i]||{};this.calculateGlyphDependencies(t.text,s,r,this.allowVerticalPlacement,n);}}}"line"===s.get("symbol-placement")&&(this.features=function(t){const e={},r={},n=[];let i=0;function s(e){n.push(t[e]),i++;}function a(t,e,i){const s=r[t];return delete r[t],r[e]=s,n[s].geometry[0].pop(),n[s].geometry[0]=n[s].geometry[0].concat(i[0]),s}function o(t,r,i){const s=e[r];return delete e[r],e[t]=s,n[s].geometry[0].shift(),n[s].geometry[0]=i[0].concat(n[s].geometry[0]),s}function l(t,e,r){const n=r?e[0][e[0].length-1]:e[0][0];return `${t}:${n.x}:${n.y}`}for(let u=0;ut.geometry))}(this.features)),this.sortFeaturesByKey&&this.features.sort(((t,e)=>t.sortKey-e.sortKey));}update(t,e,r){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(t,e,this.layers,r),this.icon.programConfigurations.updatePaintArrays(t,e,this.layers,r));}isEmpty(){return 0===this.symbolInstances.length&&!this.hasRTLText}uploadPending(){return !this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(t){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(t),this.iconCollisionBox.upload(t)),this.text.upload(t,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(t,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=true;}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy();}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData();}addToLineVertexArray(t,e){const r=this.lineVertexArray.length;if(undefined!==t.segment){let r=t.dist(e[t.segment+1]),n=t.dist(e[t.segment]);const i={};for(let n=t.segment+1;n=0;r--)i[r]={x:e[r].x,y:e[r].y,tileUnitDistanceFromAnchor:n},r>0&&(n+=e[r-1].dist(e[r]));for(let t=0;t0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(t,e){const r=t.placedSymbolArray.get(e),n=r.vertexStartIndex+4*r.numGlyphs;for(let e=r.vertexStartIndex;en[t]-n[e]||i[e]-i[t])),s}addToSortKeyRanges(t,e){const r=this.sortKeyRanges[this.sortKeyRanges.length-1];r&&r.sortKey===e?r.symbolInstanceEnd=t+1:this.sortKeyRanges.push({sortKey:e,symbolInstanceStart:t,symbolInstanceEnd:t+1});}sortFeatures(t){if(this.sortFeaturesByY&&this.sortedAngle!==t&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const t of this.symbolInstanceIndexes){const e=this.symbolInstances.get(t);this.featureSortOrder.push(e.featureIndex),[e.rightJustifiedTextSymbolIndex,e.centerJustifiedTextSymbolIndex,e.leftJustifiedTextSymbolIndex].forEach(((t,e,r)=>{t>=0&&r.indexOf(t)===e&&this.addIndicesForPlacedSymbol(this.text,t);})),e.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,e.verticalPlacedTextSymbolIndex),e.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.placedIconSymbolIndex),e.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.verticalPlacedIconSymbolIndex);}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}}}let Mc,Ic;Ui("SymbolBucket",kc,{omit:["layers","collisionBoxArray","features","compareText"]}),kc.MAX_GLYPHS=65535,kc.addDynamicAttributes=wc;var zc={get paint(){return Ic=Ic||new As({"icon-opacity":new bs(ht.paint_symbol["icon-opacity"]),"icon-color":new bs(ht.paint_symbol["icon-color"]),"icon-halo-color":new bs(ht.paint_symbol["icon-halo-color"]),"icon-halo-width":new bs(ht.paint_symbol["icon-halo-width"]),"icon-halo-blur":new bs(ht.paint_symbol["icon-halo-blur"]),"icon-translate":new vs(ht.paint_symbol["icon-translate"]),"icon-translate-anchor":new vs(ht.paint_symbol["icon-translate-anchor"]),"text-opacity":new bs(ht.paint_symbol["text-opacity"]),"text-color":new bs(ht.paint_symbol["text-color"],{runtimeType:Bt,getOverride:t=>t.textColor,hasOverride:t=>!!t.textColor}),"text-halo-color":new bs(ht.paint_symbol["text-halo-color"]),"text-halo-width":new bs(ht.paint_symbol["text-halo-width"]),"text-halo-blur":new bs(ht.paint_symbol["text-halo-blur"]),"text-translate":new vs(ht.paint_symbol["text-translate"]),"text-translate-anchor":new vs(ht.paint_symbol["text-translate-anchor"])})},get layout(){return Mc=Mc||new As({"symbol-placement":new vs(ht.layout_symbol["symbol-placement"]),"symbol-spacing":new vs(ht.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new vs(ht.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new bs(ht.layout_symbol["symbol-sort-key"]),"symbol-z-order":new vs(ht.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new vs(ht.layout_symbol["icon-allow-overlap"]),"icon-overlap":new vs(ht.layout_symbol["icon-overlap"]),"icon-ignore-placement":new vs(ht.layout_symbol["icon-ignore-placement"]),"icon-optional":new vs(ht.layout_symbol["icon-optional"]),"icon-rotation-alignment":new vs(ht.layout_symbol["icon-rotation-alignment"]),"icon-size":new bs(ht.layout_symbol["icon-size"]),"icon-text-fit":new vs(ht.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new vs(ht.layout_symbol["icon-text-fit-padding"]),"icon-image":new bs(ht.layout_symbol["icon-image"]),"icon-rotate":new bs(ht.layout_symbol["icon-rotate"]),"icon-padding":new bs(ht.layout_symbol["icon-padding"]),"icon-keep-upright":new vs(ht.layout_symbol["icon-keep-upright"]),"icon-offset":new bs(ht.layout_symbol["icon-offset"]),"icon-anchor":new bs(ht.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new vs(ht.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new vs(ht.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new vs(ht.layout_symbol["text-rotation-alignment"]),"text-field":new bs(ht.layout_symbol["text-field"]),"text-font":new bs(ht.layout_symbol["text-font"]),"text-size":new bs(ht.layout_symbol["text-size"]),"text-max-width":new bs(ht.layout_symbol["text-max-width"]),"text-line-height":new vs(ht.layout_symbol["text-line-height"]),"text-letter-spacing":new bs(ht.layout_symbol["text-letter-spacing"]),"text-justify":new bs(ht.layout_symbol["text-justify"]),"text-radial-offset":new bs(ht.layout_symbol["text-radial-offset"]),"text-variable-anchor":new vs(ht.layout_symbol["text-variable-anchor"]),"text-variable-anchor-offset":new bs(ht.layout_symbol["text-variable-anchor-offset"]),"text-anchor":new bs(ht.layout_symbol["text-anchor"]),"text-max-angle":new vs(ht.layout_symbol["text-max-angle"]),"text-writing-mode":new vs(ht.layout_symbol["text-writing-mode"]),"text-rotate":new bs(ht.layout_symbol["text-rotate"]),"text-padding":new vs(ht.layout_symbol["text-padding"]),"text-keep-upright":new vs(ht.layout_symbol["text-keep-upright"]),"text-transform":new bs(ht.layout_symbol["text-transform"]),"text-offset":new bs(ht.layout_symbol["text-offset"]),"text-allow-overlap":new vs(ht.layout_symbol["text-allow-overlap"]),"text-overlap":new vs(ht.layout_symbol["text-overlap"]),"text-ignore-placement":new vs(ht.layout_symbol["text-ignore-placement"]),"text-optional":new vs(ht.layout_symbol["text-optional"])})}};class Pc{constructor(t){if(undefined===t.property.overrides)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=t.property.overrides?t.property.overrides.runtimeType:It,this.defaultValue=t;}evaluate(t){if(t.formattedSection){const e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default}eachChild(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression);}outputDefined(){return false}serialize(){return null}}Ui("FormatSectionOverride",Pc,{omit:["defaultValue"]});class Cc extends Ms{constructor(t){super(t,zc);}recalculate(t,e){if(super.recalculate(t,e),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]="map"===this.layout.get("text-rotation-alignment")?"map":"viewport"),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){const t=this.layout.get("text-writing-mode");if(t){const e=[];for(const r of t)e.indexOf(r)<0&&e.push(r);this.layout._values["text-writing-mode"]=e;}else this.layout._values["text-writing-mode"]=["horizontal"];}this._setPaintOverrides();}getValueAndResolveTokens(t,e,r,n){const i=this.layout.get(t).evaluate(e,{},r,n),s=this._unevaluatedLayout._values[t];return s.isDataDriven()||jn(s.value)||!i?i:function(t,e){return e.replace(/{([^{}]+)}/g,((e,r)=>t&&r in t?String(t[r]):""))}(e.properties,i)}createBucket(t){return new kc(t)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(const t of zc.paint.overridableProperties){if(!Cc.hasPaintOverride(this.layout,t))continue;const e=this.paint.get(t),r=new Pc(e),n=new Rn(r,e.property.specification);let i=null;i="constant"===e.value.kind||"source"===e.value.kind?new Un("source",n):new qn("composite",n,e.value.zoomStops),this.paint._values[t]=new gs(e.property,i,e.parameters);}}_handleOverridablePaintPropertyUpdate(t,e,r){return !(!this.layout||e.isDataDriven()||r.isDataDriven())&&Cc.hasPaintOverride(this.layout,t)}static hasPaintOverride(t,e){const r=t.get("text-field"),n=zc.paint.properties[e];let i=false;const s=t=>{for(const e of t)if(n.overrides&&n.overrides.hasOverride(e))return void(i=true)};if("constant"===r.value.kind&&r.value.value instanceof xe)s(r.value.value.sections);else if("source"===r.value.kind){const t=e=>{i||(e instanceof Pe&&Ie(e.value)===$t?s(e.value.sections):e instanceof br?s(e.sections):e.eachChild(t));},e=r.value;e._styleExpression&&t(e._styleExpression.expression);}return i}}let Bc;var Vc={get paint(){return Bc=Bc||new As({"background-color":new vs(ht.paint_background["background-color"]),"background-pattern":new _s(ht.paint_background["background-pattern"]),"background-opacity":new vs(ht.paint_background["background-opacity"])})}};class Ec extends Ms{constructor(t){super(t,Vc);}}let Tc;var Fc={get paint(){return Tc=Tc||new As({"raster-opacity":new vs(ht.paint_raster["raster-opacity"]),"raster-hue-rotate":new vs(ht.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new vs(ht.paint_raster["raster-brightness-min"]),"raster-brightness-max":new vs(ht.paint_raster["raster-brightness-max"]),"raster-saturation":new vs(ht.paint_raster["raster-saturation"]),"raster-contrast":new vs(ht.paint_raster["raster-contrast"]),"raster-resampling":new vs(ht.paint_raster["raster-resampling"]),"raster-fade-duration":new vs(ht.paint_raster["raster-fade-duration"])})}};class $c extends Ms{constructor(t){super(t,Fc);}}class Lc extends Ms{constructor(t){super(t,{}),this.onAdd=t=>{this.implementation.onAdd&&this.implementation.onAdd(t,t.painter.context.gl);},this.onRemove=t=>{this.implementation.onRemove&&this.implementation.onRemove(t,t.painter.context.gl);},this.implementation=t;}is3D(){return "3d"===this.implementation.renderingMode}hasOffscreenPass(){return undefined!==this.implementation.prerender}recalculate(){}updateTransitions(){}hasTransition(){return false}serialize(){throw new Error("Custom layers cannot be serialized")}}class Dc{constructor(t){this._methodToThrottle=t,this._triggered=false,"undefined"!=typeof MessageChannel&&(this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=false,this._methodToThrottle();});}trigger(){this._triggered||(this._triggered=true,this._channel?this._channel.port1.postMessage(true):setTimeout((()=>{this._triggered=false,this._methodToThrottle();}),0));}remove(){delete this._channel,this._methodToThrottle=()=>{};}}const Oc=6371008.8;class Rc{constructor(t,e){if(isNaN(t)||isNaN(e))throw new Error(`Invalid LngLat object: (${t}, ${e})`);if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new Rc(T(this.lng,-180,180),this.lat)}toArray(){return [this.lng,this.lat]}toString(){return `LngLat(${this.lng}, ${this.lat})`}distanceTo(t){const e=Math.PI/180,r=this.lat*e,n=t.lat*e,i=Math.sin(r)*Math.sin(n)+Math.cos(r)*Math.cos(n)*Math.cos((t.lng-this.lng)*e);return Oc*Math.acos(Math.min(i,1))}static convert(t){if(t instanceof Rc)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new Rc(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new Rc(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}const jc=2*Math.PI*Oc;function Nc(t){return jc*Math.cos(t*Math.PI/180)}function Uc(t){return (180+t)/360}function qc(t){return (180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function Gc(t,e){return t/Nc(e)}function Zc(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}function Xc(t,e){return t*Nc(Zc(e))}class Kc{constructor(t,e,r=0){this.x=+t,this.y=+e,this.z=+r;}static fromLngLat(t,e=0){const r=Rc.convert(t);return new Kc(Uc(r.lng),qc(r.lat),Gc(e,r.lat))}toLngLat(){return new Rc(360*this.x-180,Zc(this.y))}toAltitude(){return Xc(this.z,this.y)}meterInMercatorCoordinateUnits(){return 1/jc*(t=Zc(this.y),1/Math.cos(t*Math.PI/180));var t;}}function Hc(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return [t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}class Yc{constructor(t,e,r){if(!function(t,e,r){return !(t<0||t>25||r<0||r>=Math.pow(2,t)||e<0||e>=Math.pow(2,t))}(t,e,r))throw new Error(`x=${e}, y=${r}, z=${t} outside of bounds. 0<=x<${Math.pow(2,t)}, 0<=y<${Math.pow(2,t)} 0<=z<=25 `);this.z=t,this.x=e,this.y=r,this.key=Qc(0,t,t,e,r);}equals(t){return this.z===t.z&&this.x===t.x&&this.y===t.y}url(t,e,r){const n=(s=this.y,a=this.z,o=Hc(256*(i=this.x),256*(s=Math.pow(2,a)-s-1),a),l=Hc(256*(i+1),256*(s+1),a),o[0]+","+o[1]+","+l[0]+","+l[1]);var i,s,a,o,l;const u=function(t,e,r){let n,i="";for(let s=t;s>0;s--)n=1<1?"@2x":"").replace(/{quadkey}/g,u).replace(/{bbox-epsg-3857}/g,n)}isChildOf(t){const e=this.z-t.z;return e>0&&t.x===this.x>>e&&t.y===this.y>>e}getTilePoint(t){const e=Math.pow(2,this.z);return new l((t.x*e-this.x)*M,(t.y*e-this.y)*M)}toString(){return `${this.z}/${this.x}/${this.y}`}}class Jc{constructor(t,e){this.wrap=t,this.canonical=e,this.key=Qc(t,e.z,e.z,e.x,e.y);}}class Wc{constructor(t,e,r,n,i){if(this.terrainRttPosMatrix32f=null,t= z; overscaledZ = ${t}; z = ${r}`);this.overscaledZ=t,this.wrap=e,this.canonical=new Yc(r,+n,+i),this.key=Qc(e,t,r,n,i);}clone(){return new Wc(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)}scaledTo(t){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const e=this.canonical.z-t;return t>this.canonical.z?new Wc(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new Wc(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)}calculateScaledKey(t,e){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const r=this.canonical.z-t;return t>this.canonical.z?Qc(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Qc(this.wrap*+e,t,t,this.canonical.x>>r,this.canonical.y>>r)}isChildOf(t){if(t.wrap!==this.wrap)return false;const e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e}children(t){if(this.overscaledZ>=t)return [new Wc(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return [new Wc(e,this.wrap,e,r,n),new Wc(e,this.wrap,e,r+1,n),new Wc(e,this.wrap,e,r,n+1),new Wc(e,this.wrap,e,r+1,n+1)]}isLessThan(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.ythis.max&&(this.max=r),r=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return (e+1)*this.stride+(t+1)}unpack(t,e,r){return t*this.redFactor+e*this.greenFactor+r*this.blueFactor-this.baseShift}getPixels(){return new Oo({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(t,e,r){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");let n=e*this.dim,i=e*this.dim+this.dim,s=r*this.dim,a=r*this.dim+this.dim;switch(e){case-1:n=i-1;break;case 1:i=n+1;}switch(r){case-1:s=a-1;break;case 1:a=s+1;}const o=-e*this.dim,l=-r*this.dim;for(let e=s;e=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${t} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[t]}}class rh{constructor(t,e,r,n,i){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,this.id=i;}get geometry(){return undefined===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry}set geometry(t){this._geometry=t;}toJSON(){const t={geometry:this.geometry};for(const e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t}}class nh{constructor(t,e){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=new ji(M,16,0),this.grid3D=new ji(M,16,0),this.featureIndexArray=new pa,this.promoteId=e;}insert(t,e,r,n,i,s){const a=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(r,n,i);const o=s?this.grid3D:this.grid;for(let t=0;t=0&&n[3]>=0&&o.insert(a,n[0],n[1],n[2],n[3]);}}loadVTLayers(){return this.vtLayers||(this.vtLayers=new Yl.VectorTile(new Du(this.rawTileData)).layers,this.sourceLayerCoder=new eh(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers}query(t,e,r,n){this.loadVTLayers();const i=t.params,s=M/t.tileSize/t.scale,a=Yn(i.filter),o=t.queryGeometry,u=t.queryPadding*s,c=sh(o),h=this.grid.query(c.minX-u,c.minY-u,c.maxX+u,c.maxY+u),p=sh(t.cameraQueryGeometry),f=this.grid3D.query(p.minX-u,p.minY-u,p.maxX+u,p.maxY+u,((e,r,n,i)=>function(t,e,r,n,i){for(const s of t)if(e<=s.x&&r<=s.y&&n>=s.x&&i>=s.y)return true;const s=[new l(e,r),new l(e,i),new l(n,i),new l(n,r)];if(t.length>2)for(const e of s)if(_o(t,e))return true;for(let e=0;e(p||(p=oo(e)),r.queryIntersectsFeature({queryGeometry:o,feature:e,featureState:n,geometry:p,zoom:this.z,transform:t.transform,pixelsToTileUnits:s,pixelPosMatrix:t.pixelPosMatrix}))));}return d}loadMatchingFeature(t,e,r,n,i,s,a,o,l,u,c){const h=this.bucketLayerIDs[e];if(s&&!h.some((t=>s.has(t))))return;const p=this.sourceLayerCoder.decode(r),f=this.vtLayers[p].feature(n);if(i.needGeometry){const t=lo(f,true);if(!i.filter(new cs(this.tileID.overscaledZ),t,this.tileID.canonical))return}else if(!i.filter(new cs(this.tileID.overscaledZ),f))return;const d=this.getId(f,p);for(let e=0;e{const a=e instanceof xs?e.get(s):null;return a&&a.evaluate?a.evaluate(r,n,i):a}))}function sh(t){let e=1/0,r=1/0,n=-1/0,i=-1/0;for(const s of t)e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);return {minX:e,minY:r,maxX:n,maxY:i}}function ah(t,e){return e-t}function oh(t,e,r,n,i){const s=[];for(let a=0;a=n&&c.x>=n||(a.x>=n?a=new l(n,a.y+(n-a.x)/(c.x-a.x)*(c.y-a.y))._round():c.x>=n&&(c=new l(n,a.y+(n-a.x)/(c.x-a.x)*(c.y-a.y))._round()),a.y>=i&&c.y>=i||(a.y>=i?a=new l(a.x+(i-a.y)/(c.y-a.y)*(c.x-a.x),i)._round():c.y>=i&&(c=new l(a.x+(i-a.y)/(c.y-a.y)*(c.x-a.x),i)._round()),u&&a.equals(u[u.length-1])||(u=[a],s.push(u)),u.push(c)))));}}return s}Ui("FeatureIndex",nh,{omit:["rawTileData","sourceLayerCoder"]});class lh extends l{constructor(t,e,r,n){super(t,e),this.angle=r,undefined!==n&&(this.segment=n);}clone(){return new lh(this.x,this.y,this.angle,this.segment)}}function uh(t,e,r,n,i){if(undefined===e.segment||0===r)return true;let s=e,a=e.segment+1,o=0;for(;o>-r/2;){if(a--,a<0)return false;o-=t[a].dist(s),s=t[a];}o+=t[a].dist(t[a+1]),a++;const l=[];let u=0;for(;on;)u-=l.shift().angleDelta;if(u>i)return false;a++,o+=e.dist(r);}return true}function ch(t){let e=0;for(let r=0;ru){const c=(u-l)/s,h=or.number(n.x,i.x,c),p=or.number(n.y,i.y,c),f=new lh(h,p,i.angleTo(n),r);return f._round(),!a||uh(t,f,o,a,e)?f:undefined}l+=s;}}function dh(t,e,r,n,i,s,a,o,l){const u=hh(n,s,a),c=ph(n,i),h=c*a,p=0===t[0].x||t[0].x===l||0===t[0].y||t[0].y===l;return e-h=0&&g=0&&x=0&&p+u<=c){const r=new lh(g,x,y,e);r._round(),n&&!uh(t,r,s,n,i)||f.push(r);}}h+=d;}return o||f.length||a||(f=yh(t,h/2,r,n,i,s,a,true,l)),f}Ui("Anchor",lh);const mh=Gu;function gh(t,e,r,n){const i=[],s=t.image,a=s.pixelRatio,o=s.paddedRect.w-2*mh,u=s.paddedRect.h-2*mh;let c={x1:t.left,y1:t.top,x2:t.right,y2:t.bottom};const h=s.stretchX||[[0,o]],p=s.stretchY||[[0,u]],f=(t,e)=>t+e[1]-e[0],d=h.reduce(f,0),y=p.reduce(f,0),m=o-d,g=u-y;let x=0,v=d,b=0,w=y,_=0,S=m,A=0,k=g;if(s.content&&n){const e=s.content,r=e[2]-e[0],n=e[3]-e[1];(s.textFitWidth||s.textFitHeight)&&(c=hc(t)),x=xh(h,0,e[0]),b=xh(p,0,e[1]),v=xh(h,e[0],e[2]),w=xh(p,e[1],e[3]),_=e[0]-x,A=e[1]-b,S=r-v,k=n-w;}const M=c.x1,I=c.y1,z=c.x2-M,P=c.y2-I,C=(t,n,i,o)=>{const u=bh(t.stretch-x,v,z,M),c=wh(t.fixed-_,S,t.stretch,d),h=bh(n.stretch-b,w,P,I),p=wh(n.fixed-A,k,n.stretch,y),f=bh(i.stretch-x,v,z,M),m=wh(i.fixed-_,S,i.stretch,d),g=bh(o.stretch-b,w,P,I),C=wh(o.fixed-A,k,o.stretch,y),B=new l(u,h),V=new l(f,h),E=new l(f,g),T=new l(u,g),F=new l(c/a,p/a),$=new l(m/a,C/a),L=e*Math.PI/180;if(L){const t=Math.sin(L),e=Math.cos(L),r=[e,-t,t,e];B._matMult(r),V._matMult(r),T._matMult(r),E._matMult(r);}const D=t.stretch+t.fixed,O=n.stretch+n.fixed;return {tl:B,tr:V,bl:T,br:E,tex:{x:s.paddedRect.x+mh+D,y:s.paddedRect.y+mh+O,w:i.stretch+i.fixed-D,h:o.stretch+o.fixed-O},writingMode:undefined,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:F,pixelOffsetBR:$,minFontScaleX:S/a/z,minFontScaleY:k/a/P,isSDF:r}};if(n&&(s.stretchX||s.stretchY)){const t=vh(h,m,d),e=vh(p,g,y);for(let r=0;r0&&(n=Math.max(10,n),this.circleDiameter=n);}else {const u=(null===(h=s.image)||undefined===h?undefined:h.content)&&(s.image.textFitWidth||s.image.textFitHeight)?hc(s):{x1:s.left,y1:s.top,x2:s.right,y2:s.bottom};u.y1=u.y1*a-o[0],u.y2=u.y2*a+o[2],u.x1=u.x1*a-o[3],u.x2=u.x2*a+o[1];const p=s.collisionPadding;if(p&&(u.x1-=p[0]*a,u.y1-=p[1]*a,u.x2+=p[2]*a,u.y2+=p[3]*a),c){const t=new l(u.x1,u.y1),e=new l(u.x2,u.y1),r=new l(u.x1,u.y2),n=new l(u.x2,u.y2),i=c*Math.PI/180;t._rotate(i),e._rotate(i),r._rotate(i),n._rotate(i),u.x1=Math.min(t.x,e.x,r.x,n.x),u.x2=Math.max(t.x,e.x,r.x,n.x),u.y1=Math.min(t.y,e.y,r.y,n.y),u.y2=Math.max(t.y,e.y,r.y,n.y);}t.emplaceBack(e.x,e.y,u.x1,u.y1,u.x2,u.y2,r,n,i);}this.boxEndIndex=t.length;}}class Sh{constructor(t=[],e=((t,e)=>te?1:0)){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}}function Ah(t,e=1,r=false){let n=1/0,i=1/0,s=-1/0,a=-1/0;const o=t[0];for(let t=0;ts)&&(s=e.x),(!t||e.y>a)&&(a=e.y);}const u=Math.min(s-n,a-i);let c=u/2;const h=new Sh([],kh);if(0===u)return new l(n,i);for(let e=n;ep.d||!p.d)&&(p=n,r&&console.log("found best %d after %d probes",Math.round(1e4*n.d)/1e4,f)),n.max-p.d<=e||(c=n.h/2,h.push(new Mh(n.p.x-c,n.p.y-c,c,t)),h.push(new Mh(n.p.x+c,n.p.y-c,c,t)),h.push(new Mh(n.p.x-c,n.p.y+c,c,t)),h.push(new Mh(n.p.x+c,n.p.y+c,c,t)),f+=4);}return r&&(console.log(`num probes: ${f}`),console.log(`best distance: ${p.d}`)),p.p}function kh(t,e){return e.max-t.max}function Mh(t,e,r,n){this.p=new l(t,e),this.h=r,this.d=function(t,e){let r=false,n=1/0;for(let i=0;it.y!=o.y>t.y&&t.x<(o.x-i.x)*(t.y-i.y)/(o.y-i.y)+i.x&&(r=!r),n=Math.min(n,bo(t,i,o));}}return (r?1:-1)*Math.sqrt(n)}(this.p,n),this.max=this.d+this.h*Math.SQRT2;}var Ih;t.av=undefined,(Ih=t.av||(t.av={}))[Ih.center=1]="center",Ih[Ih.left=2]="left",Ih[Ih.right=3]="right",Ih[Ih.top=4]="top",Ih[Ih.bottom=5]="bottom",Ih[Ih["top-left"]=6]="top-left",Ih[Ih["top-right"]=7]="top-right",Ih[Ih["bottom-left"]=8]="bottom-left",Ih[Ih["bottom-right"]=9]="bottom-right";const zh=7,Ph=Number.POSITIVE_INFINITY;function Ch(t,e){return e[1]!==Ph?function(t,e,r){let n=0,i=0;switch(e=Math.abs(e),r=Math.abs(r),t){case"top-right":case"top-left":case"top":i=r-zh;break;case"bottom-right":case"bottom-left":case"bottom":i=-r+zh;}switch(t){case"top-right":case"bottom-right":case"right":n=-e;break;case"top-left":case"bottom-left":case"left":n=e;}return [n,i]}(t,e[0],e[1]):function(t,e){let r=0,n=0;e<0&&(e=0);const i=e/Math.SQRT2;switch(t){case"top-right":case"top-left":n=i-zh;break;case"bottom-right":case"bottom-left":n=-i+zh;break;case"bottom":n=-e+zh;break;case"top":n=e-zh;}switch(t){case"top-right":case"bottom-right":r=-i;break;case"top-left":case"bottom-left":r=i;break;case"left":r=e;break;case"right":r=-e;}return [r,n]}(t,e[0])}function Bh(t,e,r){var n;const i=t.layout,s=null===(n=i.get("text-variable-anchor-offset"))||undefined===n?undefined:n.evaluate(e,{},r);if(s){const t=s.values,e=[];for(let r=0;rt*Tu));n.startsWith("top")?i[1]-=zh:n.startsWith("bottom")&&(i[1]+=zh),e[r+1]=i;}return new _e(e)}const a=i.get("text-variable-anchor");if(a){let n;n=undefined!==t._unevaluatedLayout.getValue("text-radial-offset")?[i.get("text-radial-offset").evaluate(e,{},r)*Tu,Ph]:i.get("text-offset").evaluate(e,{},r).map((t=>t*Tu));const s=[];for(const t of a)s.push(t,Ch(t,n));return new _e(s)}return null}function Vh(t){switch(t){case"right":case"top-right":case"bottom-right":return "right";case"left":case"top-left":case"bottom-left":return "left"}return "center"}function Eh(e,r,n,i,s,a,o,l,u,c,h,p){let f=a.textMaxSize.evaluate(r,{});undefined===f&&(f=o);const d=e.layers[0].layout,y=d.get("icon-offset").evaluate(r,{},h),m=Fh(n.horizontal),g=o/24,x=e.tilePixelRatio*g,v=e.tilePixelRatio*f/24,b=e.tilePixelRatio*l,w=e.tilePixelRatio*d.get("symbol-spacing"),_=d.get("text-padding")*e.tilePixelRatio,S=function(t,e,r,n=1){const i=t.get("icon-padding").evaluate(e,{},r),s=i&&i.values;return [s[0]*n,s[1]*n,s[2]*n,s[3]*n]}(d,r,h,e.tilePixelRatio),A=d.get("text-max-angle")/180*Math.PI,k="viewport"!==d.get("text-rotation-alignment")&&"point"!==d.get("symbol-placement"),I="map"===d.get("icon-rotation-alignment")&&"point"!==d.get("symbol-placement"),z=d.get("symbol-placement"),P=w/2,C=d.get("icon-text-fit");let B;i&&"none"!==C&&(e.allowVerticalPlacement&&n.vertical&&(B=pc(i,n.vertical,C,d.get("icon-text-fit-padding"),y,g)),m&&(i=pc(i,m,C,d.get("icon-text-fit-padding"),y,g)));const V=h?p.line.getGranularityForZoomLevel(h.z):1,E=(l,p)=>{p.x<0||p.x>=M||p.y<0||p.y>=M||function(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k){const M=e.addToLineVertexArray(r,n);let I,z,P,C,B=0,V=0,E=0,T=0,F=-1,$=-1;const L={};let D=Oa("");if(e.allowVerticalPlacement&&i.vertical){const t=l.layout.get("text-rotate").evaluate(w,{},A)+90;P=new _h(u,r,c,h,p,i.vertical,f,d,y,t),o&&(C=new _h(u,r,c,h,p,o,g,x,y,t));}if(s){const n=l.layout.get("icon-rotate").evaluate(w,{}),i="none"!==l.layout.get("icon-text-fit"),a=gh(s,n,S,i),f=o?gh(o,n,S,i):undefined;z=new _h(u,r,c,h,p,s,g,x,false,n),B=4*a.length;const d=e.iconSizeData;let y=null;"source"===d.kind?(y=[dc*l.layout.get("icon-size").evaluate(w,{})],y[0]>yc&&j(`${e.layerIds[0]}: Value for "icon-size" is >= ${fc}. Reduce your "icon-size".`)):"composite"===d.kind&&(y=[dc*_.compositeIconSizes[0].evaluate(w,{},A),dc*_.compositeIconSizes[1].evaluate(w,{},A)],(y[0]>yc||y[1]>yc)&&j(`${e.layerIds[0]}: Value for "icon-size" is >= ${fc}. Reduce your "icon-size".`)),e.addSymbols(e.icon,a,y,b,v,w,t.ai.none,r,M.lineStartIndex,M.lineLength,-1,A),F=e.icon.placedSymbolArray.length-1,f&&(V=4*f.length,e.addSymbols(e.icon,f,y,b,v,w,t.ai.vertical,r,M.lineStartIndex,M.lineLength,-1,A),$=e.icon.placedSymbolArray.length-1);}const O=Object.keys(i.horizontal);for(const n of O){const s=i.horizontal[n];if(!I){D=Oa(s.text);const t=l.layout.get("text-rotate").evaluate(w,{},A);I=new _h(u,r,c,h,p,s,f,d,y,t);}const o=1===s.positionedLines.length;if(E+=Th(e,r,s,a,l,y,w,m,M,i.vertical?t.ai.horizontal:t.ai.horizontalOnly,o?O:[n],L,F,_,A),o)break}i.vertical&&(T+=Th(e,r,i.vertical,a,l,y,w,m,M,t.ai.vertical,["vertical"],L,$,_,A));const R=I?I.boxStartIndex:e.collisionBoxArray.length,N=I?I.boxEndIndex:e.collisionBoxArray.length,U=P?P.boxStartIndex:e.collisionBoxArray.length,q=P?P.boxEndIndex:e.collisionBoxArray.length,G=z?z.boxStartIndex:e.collisionBoxArray.length,Z=z?z.boxEndIndex:e.collisionBoxArray.length,X=C?C.boxStartIndex:e.collisionBoxArray.length,K=C?C.boxEndIndex:e.collisionBoxArray.length;let H=-1;const Y=(t,e)=>t&&t.circleDiameter?Math.max(t.circleDiameter,e):e;H=Y(I,H),H=Y(P,H),H=Y(z,H),H=Y(C,H);const J=H>-1?1:0;J&&(H*=k/Tu),e.glyphOffsetArray.length>=kc.MAX_GLYPHS&&j("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),undefined!==w.sortKey&&e.addToSortKeyRanges(e.symbolInstances.length,w.sortKey);const W=Bh(l,w,A),[Q,tt]=function(e,r){const n=e.length,i=null==r?undefined:r.values;if((null==i?undefined:i.length)>0)for(let r=0;r=0?L.right:-1,L.center>=0?L.center:-1,L.left>=0?L.left:-1,L.vertical||-1,F,$,D,R,N,U,q,G,Z,X,K,c,E,T,B,V,J,0,f,H,Q,tt);}(e,p,l,n,i,s,B,e.layers[0],e.collisionBoxArray,r.index,r.sourceLayerIndex,e.index,x,[_,_,_,_],k,u,b,S,I,y,r,a,c,h,o);};if("line"===z)for(const t of oh(r.geometry,0,0,M,M)){const r=Il(t,V),s=dh(r,w,A,n.vertical||m,i,24,v,e.overscaling,M);for(const t of s)m&&$h(e,m.text,P,t)||E(r,t);}else if("line-center"===z){for(const t of r.geometry)if(t.length>1){const e=Il(t,V),r=fh(e,A,n.vertical||m,i,24,v);r&&E(e,r);}}else if("Polygon"===r.type)for(const t of Le(r.geometry,0)){const e=Ah(t,16);E(Il(t[0],V,true),new lh(e.x,e.y,0));}else if("LineString"===r.type)for(const t of r.geometry){const e=Il(t,V);E(e,new lh(e[0].x,e[0].y,0));}else if("Point"===r.type)for(const t of r.geometry)for(const e of t)E([e],new lh(e.x,e.y,0));}function Th(t,e,r,n,i,s,a,o,u,c,h,p,f,d,y){const m=function(t,e,r,n,i,s,a,o){const u=n.layout.get("text-rotate").evaluate(s,{})*Math.PI/180,c=[];for(const t of e.positionedLines)for(const n of t.positionedGlyphs){if(!n.rect)continue;const s=n.rect||{};let h=Uu+1,p=true,f=1,d=0;const y=(i||o)&&n.vertical,m=n.metrics.advance*n.scale/2;if(o&&e.verticalizable&&(d=t.lineOffset/2-(n.imageName?-(Tu-n.metrics.width*n.scale)/2:(n.scale-1)*Tu)),n.imageName){const t=a[n.imageName];p=t.sdf,f=t.pixelRatio,h=Gu/f;}const g=i?[n.x+m,n.y]:[0,0];let x=i?[0,0]:[n.x+m+r[0],n.y+r[1]-d],v=[0,0];y&&(v=x,x=[0,0]);const b=n.metrics.isDoubleResolution?2:1,w=(n.metrics.left-h)*n.scale-m+x[0],_=(-n.metrics.top-h)*n.scale+x[1],S=w+s.w/b*n.scale/f,A=_+s.h/b*n.scale/f,k=new l(w,_),M=new l(S,_),I=new l(w,A),z=new l(S,A);if(y){const t=new l(-m,m-Hu),e=-Math.PI/2,r=Tu/2-m,i=new l(5-Hu-r,-(n.imageName?r:0)),s=new l(...v);k._rotateAround(e,t)._add(i)._add(s),M._rotateAround(e,t)._add(i)._add(s),I._rotateAround(e,t)._add(i)._add(s),z._rotateAround(e,t)._add(i)._add(s);}if(u){const t=Math.sin(u),e=Math.cos(u),r=[e,-t,t,e];k._matMult(r),M._matMult(r),I._matMult(r),z._matMult(r);}const P=new l(0,0),C=new l(0,0);c.push({tl:k,tr:M,bl:I,br:z,tex:s,writingMode:e.writingMode,glyphOffset:g,sectionIndex:n.sectionIndex,isSDF:p,pixelOffsetTL:P,pixelOffsetBR:C,minFontScaleX:0,minFontScaleY:0});}return c}(0,r,o,i,s,a,n,t.allowVerticalPlacement),g=t.textSizeData;let x=null;"source"===g.kind?(x=[dc*i.layout.get("text-size").evaluate(a,{})],x[0]>yc&&j(`${t.layerIds[0]}: Value for "text-size" is >= ${fc}. Reduce your "text-size".`)):"composite"===g.kind&&(x=[dc*d.compositeTextSizes[0].evaluate(a,{},y),dc*d.compositeTextSizes[1].evaluate(a,{},y)],(x[0]>yc||x[1]>yc)&&j(`${t.layerIds[0]}: Value for "text-size" is >= ${fc}. Reduce your "text-size".`)),t.addSymbols(t.text,m,x,o,s,a,c,e,u.lineStartIndex,u.lineLength,f,y);for(const e of h)p[e]=t.text.placedSymbolArray.length-1;return 4*m.length}function Fh(t){for(const e in t)return t[e];return null}function $h(t,e,r,n){const i=t.compareText;if(e in i){const t=i[e];for(let e=t.length-1;e>=0;e--)if(n.dist(t[e])>4;if(1!==n)throw new Error(`Got v${n} data when expected v1.`);const i=Lh[15&r];if(!i)throw new Error("Unrecognized array type.");const[s]=new Uint16Array(t,2,1),[a]=new Uint32Array(t,4,1);return new Dh(a,s,i,t)}constructor(t,e=64,r=Float64Array,n){if(isNaN(t)||t<0)throw new Error(`Unpexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+e,2),65535),this.ArrayType=r,this.IndexArrayType=t<65536?Uint16Array:Uint32Array;const i=Lh.indexOf(this.ArrayType),s=2*t*this.ArrayType.BYTES_PER_ELEMENT,a=t*this.IndexArrayType.BYTES_PER_ELEMENT,o=(8-a%8)%8;if(i<0)throw new Error(`Unexpected typed array class: ${r}.`);n&&n instanceof ArrayBuffer?(this.data=n,this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=2*t,this._finished=true):(this.data=new ArrayBuffer(8+s+a+o),this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=0,this._finished=false,new Uint8Array(this.data,0,2).set([219,16+i]),new Uint16Array(this.data,2,1)[0]=e,new Uint32Array(this.data,4,1)[0]=t);}add(t,e){const r=this._pos>>1;return this.ids[r]=r,this.coords[this._pos++]=t,this.coords[this._pos++]=e,r}finish(){const t=this._pos>>1;if(t!==this.numItems)throw new Error(`Added ${t} items when expected ${this.numItems}.`);return Oh(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=true,this}range(t,e,r,n){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:i,coords:s,nodeSize:a}=this,o=[0,i.length-1,0],l=[];for(;o.length;){const u=o.pop()||0,c=o.pop()||0,h=o.pop()||0;if(c-h<=a){for(let a=h;a<=c;a++){const o=s[2*a],u=s[2*a+1];o>=t&&o<=r&&u>=e&&u<=n&&l.push(i[a]);}continue}const p=h+c>>1,f=s[2*p],d=s[2*p+1];f>=t&&f<=r&&d>=e&&d<=n&&l.push(i[p]),(0===u?t<=f:e<=d)&&(o.push(h),o.push(p-1),o.push(1-u)),(0===u?r>=f:n>=d)&&(o.push(p+1),o.push(c),o.push(1-u));}return l}within(t,e,r){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:n,coords:i,nodeSize:s}=this,a=[0,n.length-1,0],o=[],l=r*r;for(;a.length;){const u=a.pop()||0,c=a.pop()||0,h=a.pop()||0;if(c-h<=s){for(let r=h;r<=c;r++)Uh(i[2*r],i[2*r+1],t,e)<=l&&o.push(n[r]);continue}const p=h+c>>1,f=i[2*p],d=i[2*p+1];Uh(f,d,t,e)<=l&&o.push(n[p]),(0===u?t-r<=f:e-r<=d)&&(a.push(h),a.push(p-1),a.push(1-u)),(0===u?t+r>=f:e+r>=d)&&(a.push(p+1),a.push(c),a.push(1-u));}return o}}function Oh(t,e,r,n,i,s){if(i-n<=r)return;const a=n+i>>1;Rh(t,e,a,n,i,s),Oh(t,e,r,n,a-1,1-s),Oh(t,e,r,a+1,i,1-s);}function Rh(t,e,r,n,i,s){for(;i>n;){if(i-n>600){const a=i-n+1,o=r-n+1,l=Math.log(a),u=.5*Math.exp(2*l/3),c=.5*Math.sqrt(l*u*(a-u)/a)*(o-a/2<0?-1:1);Rh(t,e,r,Math.max(n,Math.floor(r-o*u/a+c)),Math.min(i,Math.floor(r+(a-o)*u/a+c)),s);}const a=e[2*r+s];let o=n,l=i;for(jh(t,e,n,r),e[2*i+s]>a&&jh(t,e,n,i);oa;)l--;}e[2*n+s]===a?jh(t,e,n,l):(l++,jh(t,e,l,i)),l<=r&&(n=l+1),r<=l&&(i=l-1);}}function jh(t,e,r,n){Nh(t,r,n),Nh(e,2*r,2*n),Nh(e,2*r+1,2*n+1);}function Nh(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function Uh(t,e,r,n){const i=t-r,s=e-n;return i*i+s*s}var qh;t.ce=undefined,(qh=t.ce||(t.ce={})).create="create",qh.load="load",qh.fullLoad="fullLoad";let Gh=null,Zh=[];const Xh=1e3/60,Kh="loadTime",Hh="fullLoadTime",Yh={mark(t){performance.mark(t);},frame(t){const e=t;null!=Gh&&Zh.push(e-Gh),Gh=e;},clearMetrics(){Gh=null,Zh=[],performance.clearMeasures(Kh),performance.clearMeasures(Hh);for(const e in t.ce)performance.clearMarks(t.ce[e]);},getPerformanceMetrics(){performance.measure(Kh,t.ce.create,t.ce.load),performance.measure(Hh,t.ce.create,t.ce.fullLoad);const e=performance.getEntriesByName(Kh)[0].duration,r=performance.getEntriesByName(Hh)[0].duration,n=Zh.length,i=1/(Zh.reduce(((t,e)=>t+e),0)/n/1e3),s=Zh.filter((t=>t>Xh)).reduce(((t,e)=>t+(e-Xh)/Xh),0);return {loadTime:e,fullLoadTime:r,fps:i,percentDroppedFrames:s/(n+s)*100,totalFrames:n}}};t.$=St,t.A=g,t.B=Li,t.C=function(t){if(null==q){const e=t.navigator?t.navigator.userAgent:null;q=!!t.safari||!(!e||!(/\b(iPad|iPhone|iPod)\b/.test(e)||e.match("Safari")&&!e.match("Chrome")));}return q},t.D=vs,t.E=ct,t.F=class{constructor(t,e){this.target=t,this.mapId=e,this.resolveRejects={},this.tasks={},this.taskQueue=[],this.abortControllers={},this.messageHandlers={},this.invoker=new Dc((()=>this.process())),this.subscription=function(t,e,r,n){return t.addEventListener(e,r,false),{unsubscribe:()=>{t.removeEventListener(e,r,false);}}}(this.target,"message",(t=>this.receive(t))),this.globalScope=U(self)?t:window;}registerMessageHandler(t,e){this.messageHandlers[t]=e;}sendAsync(t,e){return new Promise(((r,n)=>{const i=Math.round(1e18*Math.random()).toString(36).substring(0,10);this.resolveRejects[i]={resolve:r,reject:n},e&&e.signal.addEventListener("abort",(()=>{delete this.resolveRejects[i];const e={id:i,type:"",origin:location.origin,targetMapId:t.targetMapId,sourceMapId:this.mapId};this.target.postMessage(e);}),{once:true});const s=[],a=Object.assign(Object.assign({},t),{id:i,sourceMapId:this.mapId,origin:location.origin,data:Xi(t.data,s)});this.target.postMessage(a,{transfer:s});}))}receive(t){const e=t.data,r=e.id;if(!("file://"!==e.origin&&"file://"!==location.origin&&"resource://android"!==e.origin&&"resource://android"!==location.origin&&e.origin!==location.origin||e.targetMapId&&this.mapId!==e.targetMapId)){if(""===e.type){delete this.tasks[r];const t=this.abortControllers[r];return delete this.abortControllers[r],void(t&&t.abort())}if(U(self)||e.mustQueue)return this.tasks[r]=e,this.taskQueue.push(r),void this.invoker.trigger();this.processTask(r,e);}}process(){if(0===this.taskQueue.length)return;const t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length>0&&this.invoker.trigger(),e&&this.processTask(t,e);}processTask(t,r){return e(this,undefined,undefined,(function*(){if(""===r.type){const e=this.resolveRejects[t];if(delete this.resolveRejects[t],!e)return;return void(r.error?e.reject(Ki(r.error)):e.resolve(Ki(r.data)))}if(!this.messageHandlers[r.type])return void this.completeTask(t,new Error(`Could not find a registered handler for ${r.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));const e=Ki(r.data),n=new AbortController;this.abortControllers[t]=n;try{const i=yield this.messageHandlers[r.type](r.sourceMapId,e,n);this.completeTask(t,null,i);}catch(e){this.completeTask(t,e);}}))}completeTask(t,e,r){const n=[];delete this.abortControllers[t];const i={id:t,type:"",sourceMapId:this.mapId,origin:location.origin,error:e?Xi(e):null,data:Xi(r,n)};this.target.postMessage(i,{transfer:n});}remove(){this.invoker.remove(),this.subscription.unsubscribe();}},t.G=et,t.H=function(){var t=new g(16);return g!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},t.I=Zu,t.J=function(t,e,r){var n,i,s,a,o,l,u,c,h,p,f,d,y=r[0],m=r[1],g=r[2];return e===t?(t[12]=e[0]*y+e[4]*m+e[8]*g+e[12],t[13]=e[1]*y+e[5]*m+e[9]*g+e[13],t[14]=e[2]*y+e[6]*m+e[10]*g+e[14],t[15]=e[3]*y+e[7]*m+e[11]*g+e[15]):(i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],t[0]=n=e[0],t[1]=i,t[2]=s,t[3]=a,t[4]=o,t[5]=l,t[6]=u,t[7]=c,t[8]=h,t[9]=p,t[10]=f,t[11]=d,t[12]=n*y+o*m+h*g+e[12],t[13]=i*y+l*m+p*g+e[13],t[14]=s*y+u*m+f*g+e[14],t[15]=a*y+c*m+d*g+e[15]),t},t.K=function(t,e,r){var n=r[0],i=r[1],s=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*s,t[9]=e[9]*s,t[10]=e[10]*s,t[11]=e[11]*s,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.L=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],y=e[12],m=e[13],g=e[14],x=e[15],v=r[0],b=r[1],w=r[2],_=r[3];return t[0]=v*n+b*o+w*h+_*y,t[1]=v*i+b*l+w*p+_*m,t[2]=v*s+b*u+w*f+_*g,t[3]=v*a+b*c+w*d+_*x,t[4]=(v=r[4])*n+(b=r[5])*o+(w=r[6])*h+(_=r[7])*y,t[5]=v*i+b*l+w*p+_*m,t[6]=v*s+b*u+w*f+_*g,t[7]=v*a+b*c+w*d+_*x,t[8]=(v=r[8])*n+(b=r[9])*o+(w=r[10])*h+(_=r[11])*y,t[9]=v*i+b*l+w*p+_*m,t[10]=v*s+b*u+w*f+_*g,t[11]=v*a+b*c+w*d+_*x,t[12]=(v=r[12])*n+(b=r[13])*o+(w=r[14])*h+(_=r[15])*y,t[13]=v*i+b*l+w*p+_*m,t[14]=v*s+b*u+w*f+_*g,t[15]=v*a+b*c+w*d+_*x,t},t.M=function(t,e){const r={};for(let n=0;n{const e=window.document.createElement("video");return e.muted=true,new Promise((r=>{e.onloadstart=()=>{r(e);};for(const r of t){const t=window.document.createElement("source");st(r)||(e.crossOrigin="Anonymous"),t.src=r,e.appendChild(t);}}))},t.a1=function(){return $++},t.a2=ra,t.a3=kc,t.a4=Yn,t.a5=lo,t.a6=rh,t.a7=function(t){const e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,((t,r,n,i)=>{const s=n||i;return e[r]=!s||s.toLowerCase(),""})),e["max-age"]){const t=parseInt(e["max-age"],10);isNaN(t)?delete e["max-age"]:e["max-age"]=t;}return e},t.a8=function(t){return Math.log(t)/Math.LN2},t.a9=function(t){var e=t[0],r=t[1];return e*e+r*r},t.aA=Cs,t.aB=_l,t.aC=fa,t.aD=Pa,t.aE=ka,t.aF=85.051129,t.aG=function(t){return Math.pow(2,t)},t.aH=Gc,t.aI=T,t.aJ=Y,t.aK=Xc,t.aL=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t},t.aM=function(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t},t.aN=function(t){var e=new g(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e},t.aO=function(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t[3]=e[3]*r[3],t},t.aP=function(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t},t.aQ=function(t,e){var r=e[0],n=e[1],i=e[2],s=r*r+n*n+i*i;return s>0&&(s=1/Math.sqrt(s)),t[0]=e[0]*s,t[1]=e[1]*s,t[2]=e[2]*s,t},t.aR=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=r[0],o=r[1],l=r[2];return t[0]=i*l-s*o,t[1]=s*a-n*l,t[2]=n*o-i*a,t},t.aS=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]},t.aT=Jc,t.aU=Qc,t.aV=function(t,e,r,n,i){var s,a=1/Math.tan(e/2);return t[0]=a/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=i&&i!==1/0?(t[10]=(i+n)*(s=1/(n-i)),t[14]=2*i*n*s):(t[10]=-1,t[14]=-2*n),t},t.aW=function(t){var e=new g(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},t.aX=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[4],c=e[5],h=e[6],p=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i+u*n,t[1]=a*i+c*n,t[2]=o*i+h*n,t[3]=l*i+p*n,t[4]=u*i-s*n,t[5]=c*i-a*n,t[6]=h*i-o*n,t[7]=p*i-l*n,t},t.aY=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=s*i+u*n,t[5]=a*i+c*n,t[6]=o*i+h*n,t[7]=l*i+p*n,t[8]=u*i-s*n,t[9]=c*i-a*n,t[10]=h*i-o*n,t[11]=p*i-l*n,t},t.aZ=function(){const t=new Float32Array(16);return v(t),t},t.a_=function(){const t=new Float64Array(16);return v(t),t},t.aa=function(t){return t*Math.PI/180},t.ab=E,t.ac=function(t,e){const r=[];for(const n in t)n in e||r.push(n);return r},t.ad=A,t.ae=function(t){return Math.hypot(t[0],t[1])},t.af=function(t){return t[0]=0,t[1]=0,t},t.ag=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t},t.ah=function(t,e){let r=0,n=0;if("constant"===t.kind)n=t.layoutSize;else if("source"!==t.kind){const{interpolationType:i,minZoom:s,maxZoom:a}=t,o=i?E(sr.interpolationFactor(i,e,s,a),0,1):0;"camera"===t.kind?n=or.number(t.minSize,t.maxSize,o):r=o;}return {uSizeT:r,uSize:n}},t.aj=function(t,{uSize:e,uSizeT:r},{lowerSize:n,upperSize:i}){return "source"===t.kind?n/dc:"composite"===t.kind?or.number(n/dc,i/dc,r):e},t.ak=wc,t.al=_,t.am=function(t,e,r,n){const i=e.y-t.y,s=e.x-t.x,a=n.y-r.y,o=n.x-r.x,u=a*s-o*i;if(0===u)return null;const c=(o*(t.y-r.y)-a*(t.x-r.x))/u;return new l(t.x+c*s,t.y+c*i)},t.an=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],u=e[7],c=e[8],h=e[9],p=e[10],f=e[11],d=e[12],y=e[13],m=e[14],g=e[15],x=r*o-n*a,v=r*l-i*a,b=r*u-s*a,w=n*l-i*o,_=n*u-s*o,S=i*u-s*l,A=c*y-h*d,k=c*m-p*d,M=c*g-f*d,I=h*m-p*y,z=h*g-f*y,P=p*g-f*m,C=x*P-v*z+b*I+w*M-_*k+S*A;return C?(t[0]=(o*P-l*z+u*I)*(C=1/C),t[1]=(i*z-n*P-s*I)*C,t[2]=(y*S-m*_+g*w)*C,t[3]=(p*_-h*S-f*w)*C,t[4]=(l*M-a*P-u*k)*C,t[5]=(r*P-i*M+s*k)*C,t[6]=(m*b-d*S-g*v)*C,t[7]=(c*S-p*b+f*v)*C,t[8]=(a*z-o*M+u*A)*C,t[9]=(n*M-r*z-s*A)*C,t[10]=(d*_-y*b+g*x)*C,t[11]=(h*b-c*_-f*x)*C,t[12]=(o*k-a*I-l*A)*C,t[13]=(r*I-n*k+i*A)*C,t[14]=(y*v-d*w-m*x)*C,t[15]=(c*w-h*v+p*x)*C,t):null},t.ao=oh,t.ap=po,t.aq=v,t.ar=function(t){let e=1/0,r=1/0,n=-1/0,i=-1/0;for(const s of t)e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);return [e,r,n,i]},t.as=Tu,t.at=I,t.au=function(t,e,r,n,i=false){if(!r[0]&&!r[1])return [0,0];const s=i?"map"===n?-t.bearingInRadians:0:"viewport"===n?t.bearingInRadians:0;if(s){const t=Math.sin(s),e=Math.cos(s);r=[r[0]*e-r[1]*t,r[0]*t+r[1]*e];}return [i?r[0]:I(e,r[0],t.zoom),i?r[1]:I(e,r[1],t.zoom)]},t.aw=gc,t.ax=Vh,t.ay=lc,t.az=Dh,t.b=G,t.b$=t=>"line"===t.type,t.b0=function(t,e,r){const n=new Float64Array(4);return function(t,e,r,n){var i=.5*Math.PI/180;e*=i,r*=i,n*=i;var s=Math.sin(e),a=Math.cos(e),o=Math.sin(r),l=Math.cos(r),u=Math.sin(n),c=Math.cos(n);t[0]=s*l*c-a*o*u,t[1]=a*o*c+s*l*u,t[2]=a*l*u-s*o*c,t[3]=a*l*c+s*o*u;}(n,t,e-90,r),n},t.b1=function(t,e,r,n){var i,s,a,o,l,u=e[0],c=e[1],h=e[2],p=e[3],f=r[0],d=r[1],y=r[2],g=r[3];return (s=u*f+c*d+h*y+p*g)<0&&(s=-s,f=-f,d=-d,y=-y,g=-g),1-s>m?(i=Math.acos(s),a=Math.sin(i),o=Math.sin((1-n)*i)/a,l=Math.sin(n*i)/a):(o=1-n,l=n),t[0]=o*u+l*f,t[1]=o*c+l*d,t[2]=o*h+l*y,t[3]=o*p+l*g,t},t.b2=function(t){const e=new Float64Array(9);var r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v;h=(i=(n=t)[0])*(l=i+i),p=(s=n[1])*l,d=(a=n[2])*l,y=a*(u=s+s),g=(o=n[3])*l,x=o*u,v=o*(c=a+a),(r=e)[0]=1-(f=s*u)-(m=a*c),r[3]=p-v,r[6]=d+x,r[1]=p+v,r[4]=1-h-m,r[7]=y-g,r[2]=d-x,r[5]=y+g,r[8]=1-h-f;const b=Y(-Math.asin(E(e[2],-1,1)));let w,_;return Math.hypot(e[5],e[8])<.001?(w=0,_=-Y(Math.atan2(e[3],e[4]))):(w=Y(0===e[5]&&0===e[8]?0:Math.atan2(e[5],e[8])),_=Y(0===e[1]&&0===e[0]?0:Math.atan2(e[1],e[0]))),{roll:w,pitch:b+90,bearing:_}},t.b3=function(t,e){return t.roll==e.roll&&t.pitch==e.pitch&&t.bearing==e.bearing},t.b4=ye,t.b5=Ga,t.b6=Sl,t.b7=Al,t.b8=wl,t.b9=P,t.bA=L,t.bB=D,t.bC=class extends qa{constructor(t,e){super(t,e),this.current=0;}set(t){this.current!==t&&(this.current=t,this.gl.uniform1i(this.location,t));}},t.bD=class extends qa{constructor(t,e){super(t,e),this.current=Ka;}set(t){if(t[12]!==this.current[12]||t[0]!==this.current[0])return this.current=t,void this.gl.uniformMatrix4fv(this.location,false,t);for(let e=1;e<16;e++)if(t[e]!==this.current[e]){this.current=t,this.gl.uniformMatrix4fv(this.location,false,t);break}}},t.bE=Za,t.bF=Xa,t.bG=class extends qa{constructor(t,e){super(t,e),this.current=[0,0,0];}set(t){t[0]===this.current[0]&&t[1]===this.current[1]&&t[2]===this.current[2]||(this.current=t,this.gl.uniform3f(this.location,t[0],t[1],t[2]));}},t.bH=class extends qa{constructor(t,e){super(t,e),this.current=[0,0];}set(t){t[0]===this.current[0]&&t[1]===this.current[1]||(this.current=t,this.gl.uniform2f(this.location,t[0],t[1]));}},t.bI=x,t.bJ=function(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=r,t[2]=0,t[3]=-r,t[4]=n,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t},t.bK=function(t,e,r){var n=e[0],i=e[1],s=e[2];return t[0]=n*r[0]+i*r[3]+s*r[6],t[1]=n*r[1]+i*r[4]+s*r[7],t[2]=n*r[2]+i*r[5]+s*r[8],t},t.bL=function(t,e,r,n,i,s,a){var o=1/(e-r),l=1/(n-i),u=1/(s-a);return t[0]=-2*o,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*l,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*u,t[11]=0,t[12]=(e+r)*o,t[13]=(i+n)*l,t[14]=(a+s)*u,t[15]=1,t},t.bM=class extends qs{},t.bN=zu,t.bO=class extends Zs{},t.bP=jo,t.bQ=function(t){return t<=1?1:Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))},t.bR=Ro,t.bS=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=r[3]*n+r[7]*i+r[11]*s+r[15];return t[0]=(r[0]*n+r[4]*i+r[8]*s+r[12])/(a=a||1),t[1]=(r[1]*n+r[5]*i+r[9]*s+r[13])/a,t[2]=(r[2]*n+r[6]*i+r[10]*s+r[14])/a,t},t.bT=class extends Ts{},t.bU=class extends Qs{},t.bV=function(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]&&t[4]===e[4]&&t[5]===e[5]&&t[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]&&t[9]===e[9]&&t[10]===e[10]&&t[11]===e[11]&&t[12]===e[12]&&t[13]===e[13]&&t[14]===e[14]&&t[15]===e[15]},t.bW=function(t,e){var r=t[0],n=t[1],i=t[2],s=t[3],a=t[4],o=t[5],l=t[6],u=t[7],c=t[8],h=t[9],p=t[10],f=t[11],d=t[12],y=t[13],g=t[14],x=t[15],v=e[0],b=e[1],w=e[2],_=e[3],S=e[4],A=e[5],k=e[6],M=e[7],I=e[8],z=e[9],P=e[10],C=e[11],B=e[12],V=e[13],E=e[14],T=e[15];return Math.abs(r-v)<=m*Math.max(1,Math.abs(r),Math.abs(v))&&Math.abs(n-b)<=m*Math.max(1,Math.abs(n),Math.abs(b))&&Math.abs(i-w)<=m*Math.max(1,Math.abs(i),Math.abs(w))&&Math.abs(s-_)<=m*Math.max(1,Math.abs(s),Math.abs(_))&&Math.abs(a-S)<=m*Math.max(1,Math.abs(a),Math.abs(S))&&Math.abs(o-A)<=m*Math.max(1,Math.abs(o),Math.abs(A))&&Math.abs(l-k)<=m*Math.max(1,Math.abs(l),Math.abs(k))&&Math.abs(u-M)<=m*Math.max(1,Math.abs(u),Math.abs(M))&&Math.abs(c-I)<=m*Math.max(1,Math.abs(c),Math.abs(I))&&Math.abs(h-z)<=m*Math.max(1,Math.abs(h),Math.abs(z))&&Math.abs(p-P)<=m*Math.max(1,Math.abs(p),Math.abs(P))&&Math.abs(f-C)<=m*Math.max(1,Math.abs(f),Math.abs(C))&&Math.abs(d-B)<=m*Math.max(1,Math.abs(d),Math.abs(B))&&Math.abs(y-V)<=m*Math.max(1,Math.abs(y),Math.abs(V))&&Math.abs(g-E)<=m*Math.max(1,Math.abs(g),Math.abs(E))&&Math.abs(x-T)<=m*Math.max(1,Math.abs(x),Math.abs(T))},t.bX=function(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.bY=t=>"symbol"===t.type,t.bZ=t=>"circle"===t.type,t.b_=t=>"heatmap"===t.type,t.ba=C,t.bb=Ae,t.bc=function(t,e,r,n,i){return P(n,i,E((t-e)/(r-e),0,1))},t.bd=z,t.be=function(){return new Float64Array(4)},t.bf=function(){return new Float64Array(3)},t.bg=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0]*Math.cos(n)-i[1]*Math.sin(n),s[1]=i[0]*Math.sin(n)+i[1]*Math.cos(n),s[2]=i[2],t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bh=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0],s[1]=i[1]*Math.cos(n)-i[2]*Math.sin(n),s[2]=i[1]*Math.sin(n)+i[2]*Math.cos(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bi=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[2]*Math.sin(n)+i[0]*Math.cos(n),s[1]=i[1],s[2]=i[2]*Math.cos(n)-i[0]*Math.sin(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bj=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i-u*n,t[1]=a*i-c*n,t[2]=o*i-h*n,t[3]=l*i-p*n,t[8]=s*n+u*i,t[9]=a*n+c*i,t[10]=o*n+h*i,t[11]=l*n+p*i,t},t.bk=function(t,e){const r=z(t,360),n=z(e,360),i=n-r,s=n>r?i-360:i+360;return Math.abs(i)0?a:-a},t.bn=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]},t.bo=Oc,t.bp=function(t,e){const r=z(t,2*Math.PI),n=z(e,2*Math.PI);return Math.min(Math.abs(r-n),Math.abs(r-n+2*Math.PI),Math.abs(r-n-2*Math.PI))},t.bq=function(t){return Math.hypot(t[0],t[1],t[2])},t.br=function(){const t={},e=ht.$version;for(const r in ht.$root){const n=ht.$root[r];if(n.required){let i=null;i="version"===r?e:"array"===n.type?[]:{},null!=i&&(t[r]=i);}}return t},t.bs=Hi,t.bt=nt,t.bu=function(t){t=t.slice();const e=Object.create(null);for(let r=0;r{"source"in t&&n[t.source]?r.push({command:"removeLayer",args:[t.id]}):s.push(t);})),r=r.concat(i),function(t,e,r){e=e||[];const n=(t=t||[]).map(wt),i=e.map(wt),s=t.reduce(_t,{}),a=e.reduce(_t,{}),o=n.slice(),l=Object.create(null);let u,c,h,p,f;for(let t=0,e=0;t"fill"===t.type,t.c1=t=>"fill-extrusion"===t.type,t.c2=t=>"hillshade"===t.type,t.c3=t=>"raster"===t.type,t.c4=t=>"background"===t.type,t.c5=t=>"custom"===t.type,t.c6=B,t.c7=function(t,e,r){const n=k(e.x-r.x,e.y-r.y),i=k(t.x-r.x,t.y-r.y);var s,a;return Y(Math.atan2(n[0]*i[1]-n[1]*i[0],(s=n)[0]*(a=i)[0]+s[1]*a[1]))},t.c8=V,t.c9=function(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[4]*i+r[12],t[1]=r[1]*n+r[5]*i+r[13],t},t.cA=Lu,t.cB=Nn,t.cC=us,t.ca=function(t,e){const{x:r,y:n}=Kc.fromLngLat(e);return !(t<0||t>25||n<0||n>=1||r<0||r>=1)},t.cb=function(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},t.cc=class extends Es{},t.cd=Yh,t.cf=function(t){return t.message===J},t.cg=rt,t.ch=function(t,e){Q.REGISTERED_PROTOCOLS[t]=e;},t.ci=function(t){delete Q.REGISTERED_PROTOCOLS[t];},t.cj=function(t,e){const r={};for(let n=0;nt*Tu));}let v=o?"center":n.get("text-justify").evaluate(i,{},e.canonical);const b="point"===n.get("symbol-placement")?n.get("text-max-width").evaluate(i,{},e.canonical)*Tu:1/0,w=()=>{e.bucket.allowVerticalPlacement&&Ji(s)&&(d.vertical=Wu(y,e.glyphMap,e.glyphPositions,e.imagePositions,c,b,a,m,"left",f,g,t.ai.vertical,true,p,h));};if(!o&&x){const r=new Set;if("auto"===v)for(let t=0;te(undefined,undefined,undefined,(function*(){if(0===t.byteLength)return createImageBitmap(new ImageData(1,1));const e=new Blob([new Uint8Array(t)],{type:"image/png"});try{return createImageBitmap(e)}catch(t){throw new Error(`Could not load image because of ${t.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)}})),t.e=F,t.f=t=>new Promise(((e,r)=>{const n=new Image;n.onload=()=>{e(n),URL.revokeObjectURL(n.src),n.onload=null,window.requestAnimationFrame((()=>{n.src=Z;}));},n.onerror=()=>r(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));const i=new Blob([new Uint8Array(t)],{type:"image/png"});n.src=t.byteLength?URL.createObjectURL(i):Z;})),t.g=tt,t.h=(t,e)=>it(F(t,{type:"json"}),e),t.i=U,t.j=ut,t.k=lt,t.l=(t,e)=>it(F(t,{type:"arrayBuffer"}),e),t.m=it,t.n=function(t){return new Du(t).readFields(Ru,[])},t.o=Do,t.p=qu,t.q=As,t.r=$i,t.s=st,t.t=Ri,t.u=Fi,t.v=ht,t.w=j,t.x=function([t,e,r]){return e+=90,e*=Math.PI/180,r*=Math.PI/180,{x:t*Math.cos(e)*Math.sin(r),y:t*Math.sin(e)*Math.sin(r),z:t*Math.cos(r)}},t.y=or,t.z=cs;})); - - define("worker",["./shared"],(function(e){class t{constructor(e){this.keyCache={},e&&this.replace(e);}replace(e){this._layerConfigs={},this._layers={},this.update(e,[]);}update(t,o){for(const o of t){this._layerConfigs[o.id]=o;const t=this._layers[o.id]=e.bv(o);t._featureFilter=e.a4(t.filter),this.keyCache[o.id]&&delete this.keyCache[o.id];}for(const e of o)delete this.keyCache[e],delete this._layerConfigs[e],delete this._layers[e];this.familiesBySource={};const i=e.cj(Object.values(this._layerConfigs),this.keyCache);for(const e of i){const t=e.map((e=>this._layers[e.id])),o=t[0];if("none"===o.visibility)continue;const i=o.source||"";let r=this.familiesBySource[i];r||(r=this.familiesBySource[i]={});const s=o.sourceLayer||"_geojsonTileLayer";let n=r[s];n||(n=r[s]=[]),n.push(t);}}}class o{constructor(t){const o={},i=[];for(const e in t){const r=t[e],s=o[e]={};for(const e in r){const t=r[+e];if(!t||0===t.bitmap.width||0===t.bitmap.height)continue;const o={x:0,y:0,w:t.bitmap.width+2,h:t.bitmap.height+2};i.push(o),s[e]={rect:o,metrics:t.metrics};}}const{w:r,h:s}=e.p(i),n=new e.o({width:r||1,height:s||1});for(const i in t){const r=t[i];for(const t in r){const s=r[+t];if(!s||0===s.bitmap.width||0===s.bitmap.height)continue;const a=o[i][t].rect;e.o.copy(s.bitmap,n,{x:0,y:0},{x:a.x+1,y:a.y+1},s.bitmap);}}this.image=n,this.positions=o;}}e.ck("GlyphAtlas",o);class i{constructor(t){this.tileID=new e.S(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.uid=t.uid,this.zoom=t.zoom,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=t.showCollisionBoxes,this.collectResourceTiming=!!t.collectResourceTiming,this.returnDependencies=!!t.returnDependencies,this.promoteId=t.promoteId,this.inFlightDependencies=[];}parse(t,i,s,n,a){return e._(this,undefined,undefined,(function*(){this.status="parsing",this.data=t,this.collisionBoxArray=new e.a2;const l=new e.cl(Object.keys(t.layers).sort()),c=new e.cm(this.tileID,this.promoteId);c.bucketLayerIDs=[];const u={},h={featureIndex:c,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:s,subdivisionGranularity:a},d=i.familiesBySource[this.source];for(const o in d){const i=t.layers[o];if(!i)continue;1===i.version&&e.w(`Vector tile source "${this.source}" layer "${o}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const n=l.encode(o),a=[];for(let e=0;e=o.maxzoom||"none"!==o.visibility&&(r(t,this.zoom,s),(u[o.id]=o.createBucket({index:c.bucketLayerIDs.length,layers:t,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:n,sourceID:this.source})).populate(a,h,this.tileID.canonical),c.bucketLayerIDs.push(t.map((e=>e.id))));}}const f=e.bA(h.glyphDependencies,(e=>Object.keys(e).map(Number)));this.inFlightDependencies.forEach((e=>null==e?undefined:e.abort())),this.inFlightDependencies=[];let g=Promise.resolve({});if(Object.keys(f).length){const e=new AbortController;this.inFlightDependencies.push(e),g=n.sendAsync({type:"GG",data:{stacks:f,source:this.source,tileID:this.tileID,type:"glyphs"}},e);}const p=Object.keys(h.iconDependencies);let m=Promise.resolve({});if(p.length){const e=new AbortController;this.inFlightDependencies.push(e),m=n.sendAsync({type:"GI",data:{icons:p,source:this.source,tileID:this.tileID,type:"icons"}},e);}const y=Object.keys(h.patternDependencies);let v=Promise.resolve({});if(y.length){const e=new AbortController;this.inFlightDependencies.push(e),v=n.sendAsync({type:"GI",data:{icons:y,source:this.source,tileID:this.tileID,type:"patterns"}},e);}const[w,x,_]=yield Promise.all([g,m,v]),b=new o(w),M=new e.cn(x,_);for(const t in u){const o=u[t];o instanceof e.a3?(r(o.layers,this.zoom,s),e.co({bucket:o,glyphMap:w,glyphPositions:b.positions,imageMap:x,imagePositions:M.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical,subdivisionGranularity:h.subdivisionGranularity})):o.hasPattern&&(o instanceof e.cp||o instanceof e.cq||o instanceof e.cr)&&(r(o.layers,this.zoom,s),o.addFeatures(h,this.tileID.canonical,M.patternPositions));}return this.status="done",{buckets:Object.values(u).filter((e=>!e.isEmpty())),featureIndex:c,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:b.image,imageAtlas:M,glyphMap:this.returnDependencies?w:null,iconMap:this.returnDependencies?x:null,glyphPositions:this.returnDependencies?b.positions:null}}))}}function r(t,o,i){const r=new e.z(o);for(const e of t)e.recalculate(r,i);}class s{constructor(e,t,o){this.actor=e,this.layerIndex=t,this.availableImages=o,this.fetching={},this.loading={},this.loaded={};}loadVectorTile(t,o){return e._(this,undefined,undefined,(function*(){const i=yield e.l(t.request,o);try{return {vectorTile:new e.cs.VectorTile(new e.ct(i.data)),rawData:i.data,cacheControl:i.cacheControl,expires:i.expires}}catch(e){const o=new Uint8Array(i.data);let r=`Unable to parse the tile at ${t.request.url}, `;throw r+=31===o[0]&&139===o[1]?"please make sure the data is not gzipped and that you have configured the relevant header in the server":`got error: ${e.message}`,new Error(r)}}))}loadTile(t){return e._(this,undefined,undefined,(function*(){const o=t.uid,r=!!(t&&t.request&&t.request.collectResourceTiming)&&new e.cu(t.request),s=new i(t);this.loading[o]=s;const n=new AbortController;s.abort=n;try{const i=yield this.loadVectorTile(t,n);if(delete this.loading[o],!i)return null;const a=i.rawData,l={};i.expires&&(l.expires=i.expires),i.cacheControl&&(l.cacheControl=i.cacheControl);const c={};if(r){const e=r.finish();e&&(c.resourceTiming=JSON.parse(JSON.stringify(e)));}s.vectorTile=i.vectorTile;const u=s.parse(i.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);this.loaded[o]=s,this.fetching[o]={rawTileData:a,cacheControl:l,resourceTiming:c};try{const t=yield u;return e.e({rawTileData:a.slice(0)},t,l,c)}finally{delete this.fetching[o];}}catch(e){throw delete this.loading[o],s.status="done",this.loaded[o]=s,e}}))}reloadTile(t){return e._(this,undefined,undefined,(function*(){const o=t.uid;if(!this.loaded||!this.loaded[o])throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");const i=this.loaded[o];if(i.showCollisionBoxes=t.showCollisionBoxes,"parsing"===i.status){const r=yield i.parse(i.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);let s;if(this.fetching[o]){const{rawTileData:t,cacheControl:i,resourceTiming:n}=this.fetching[o];delete this.fetching[o],s=e.e({rawTileData:t.slice(0)},r,i,n);}else s=r;return s}if("done"===i.status&&i.vectorTile)return i.parse(i.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity)}))}abortTile(t){return e._(this,undefined,undefined,(function*(){const e=this.loading,o=t.uid;e&&e[o]&&e[o].abort&&(e[o].abort.abort(),delete e[o]);}))}removeTile(t){return e._(this,undefined,undefined,(function*(){this.loaded&&this.loaded[t.uid]&&delete this.loaded[t.uid];}))}}class n{constructor(){this.loaded={};}loadTile(t){return e._(this,undefined,undefined,(function*(){const{uid:o,encoding:i,rawImageData:r,redFactor:s,greenFactor:n,blueFactor:a,baseShift:l}=t,c=r.width+2,u=r.height+2,h=e.b(r)?new e.R({width:c,height:u},yield e.cv(r,-1,-1,c,u)):r,d=new e.cw(o,h,i,s,n,a,l);return this.loaded=this.loaded||{},this.loaded[o]=d,d}))}removeTile(e){const t=this.loaded,o=e.uid;t&&t[o]&&delete t[o];}}var a,l,c=function(){if(l)return a;function e(e,o){if(0!==e.length){t(e[0],o);for(var i=1;i=Math.abs(a)?o-l+a:a-l+o,o=l;}o+i>=0!=!!t&&e.reverse();}return l=1,a=function t(o,i){var r,s=o&&o.type;if("FeatureCollection"===s)for(r=0;r>31}function c(e,t){for(var o=e.loadGeometry(),i=e.type,r=0,s=0,n=o.length,c=0;ce},_=Math.fround||(b=new Float32Array(1),e=>(b[0]=+e,b[0]));var b;const M=3,S=5,I=6;class P{constructor(e){this.options=Object.assign(Object.create(x),e),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[];}load(e){const{log:t,minZoom:o,maxZoom:i}=this.options;t&&console.time("total time");const r=`prepare ${e.length} points`;t&&console.time(r),this.points=e;const s=[];for(let t=0;t=o;e--){const o=+Date.now();n=this.trees[e]=this._createTree(this._cluster(n,e)),t&&console.log("z%d: %d clusters in %dms",e,n.numItems,+Date.now()-o);}return t&&console.timeEnd("total time"),this}getClusters(e,t){let o=((e[0]+180)%360+360)%360-180;const i=Math.max(-90,Math.min(90,e[1]));let r=180===e[2]?180:((e[2]+180)%360+360)%360-180;const s=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)o=-180,r=180;else if(o>r){const e=this.getClusters([o,i,180,s],t),n=this.getClusters([-180,i,r,s],t);return e.concat(n)}const n=this.trees[this._limitZoom(t)],a=n.range(D(o),C(s),D(r),C(i)),l=n.data,c=[];for(const e of a){const t=this.stride*e;c.push(l[t+S]>1?k(l,t,this.clusterProps):this.points[l[t+M]]);}return c}getChildren(e){const t=this._getOriginId(e),o=this._getOriginZoom(e),i="No cluster with the specified id.",r=this.trees[o];if(!r)throw new Error(i);const s=r.data;if(t*this.stride>=s.length)throw new Error(i);const n=this.options.radius/(this.options.extent*Math.pow(2,o-1)),a=r.within(s[t*this.stride],s[t*this.stride+1],n),l=[];for(const t of a){const o=t*this.stride;s[o+4]===e&&l.push(s[o+S]>1?k(s,o,this.clusterProps):this.points[s[o+M]]);}if(0===l.length)throw new Error(i);return l}getLeaves(e,t,o){const i=[];return this._appendLeaves(i,e,t=t||10,o=o||0,0),i}getTile(e,t,o){const i=this.trees[this._limitZoom(e)],r=Math.pow(2,e),{extent:s,radius:n}=this.options,a=n/s,l=(o-a)/r,c=(o+1+a)/r,u={features:[]};return this._addTileFeatures(i.range((t-a)/r,l,(t+1+a)/r,c),i.data,t,o,r,u),0===t&&this._addTileFeatures(i.range(1-a/r,l,1,c),i.data,r,o,r,u),t===r-1&&this._addTileFeatures(i.range(0,l,a/r,c),i.data,-1,o,r,u),u.features.length?u:null}getClusterExpansionZoom(e){let t=this._getOriginZoom(e)-1;for(;t<=this.options.maxZoom;){const o=this.getChildren(e);if(t++,1!==o.length)break;e=o[0].properties.cluster_id;}return t}_appendLeaves(e,t,o,i,r){const s=this.getChildren(t);for(const t of s){const s=t.properties;if(s&&s.cluster?r+s.point_count<=i?r+=s.point_count:r=this._appendLeaves(e,s.cluster_id,o,i,r):r1;let l,c,u;if(a)l=T(t,e,this.clusterProps),c=t[e],u=t[e+1];else {const o=this.points[t[e+M]];l=o.properties;const[i,r]=o.geometry.coordinates;c=D(i),u=C(r);}const h={type:1,geometry:[[Math.round(this.options.extent*(c*r-o)),Math.round(this.options.extent*(u*r-i))]],tags:l};let d;d=a||this.options.generateId?t[e+M]:this.points[t[e+M]].id,undefined!==d&&(h.id=d),s.features.push(h);}}_limitZoom(e){return Math.max(this.options.minZoom,Math.min(Math.floor(+e),this.options.maxZoom+1))}_cluster(e,t){const{radius:o,extent:i,reduce:r,minPoints:s}=this.options,n=o/(i*Math.pow(2,t)),a=e.data,l=[],c=this.stride;for(let o=0;ot&&(f+=a[o+S]);}if(f>d&&f>=s){let e,s=i*d,n=u*d,g=-1;const p=((o/c|0)<<5)+(t+1)+this.points.length;for(const i of h){const l=i*c;if(a[l+2]<=t)continue;a[l+2]=t;const u=a[l+S];s+=a[l]*u,n+=a[l+1]*u,a[l+4]=p,r&&(e||(e=this._map(a,o,true),g=this.clusterProps.length,this.clusterProps.push(e)),r(e,this._map(a,l)));}a[o+4]=p,l.push(s/f,n/f,1/0,p,-1,f),r&&l.push(g);}else {for(let e=0;e1)for(const e of h){const o=e*c;if(!(a[o+2]<=t)){a[o+2]=t;for(let e=0;e>5}_getOriginZoom(e){return (e-this.points.length)%32}_map(e,t,o){if(e[t+S]>1){const i=this.clusterProps[e[t+I]];return o?Object.assign({},i):i}const i=this.points[e[t+M]].properties,r=this.options.map(i);return o&&r===i?Object.assign({},r):r}}function k(e,t,o){return {type:"Feature",id:e[t+M],properties:T(e,t,o),geometry:{type:"Point",coordinates:[(i=e[t],360*(i-.5)),O(e[t+1])]}};var i;}function T(e,t,o){const i=e[t+S],r=i>=1e4?`${Math.round(i/1e3)}k`:i>=1e3?Math.round(i/100)/10+"k":i,s=e[t+I],n=-1===s?{}:Object.assign({},o[s]);return Object.assign(n,{cluster:true,cluster_id:e[t+M],point_count:i,point_count_abbreviated:r})}function D(e){return e/360+.5}function C(e){const t=Math.sin(e*Math.PI/180),o=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return o<0?0:o>1?1:o}function O(e){const t=(180-360*e)*Math.PI/180;return 360*Math.atan(Math.exp(t))/Math.PI-90}function L(e,t,o,i){let r=i;const s=t+(o-t>>1);let n,a=o-t;const l=e[t],c=e[t+1],u=e[o],h=e[o+1];for(let i=t+3;ir)n=i,r=t;else if(t===r){const e=Math.abs(i-s);ei&&(n-t>3&&L(e,t,n,i),e[n+2]=r,o-n>3&&L(e,n,o,i));}function F(e,t,o,i,r,s){let n=r-o,a=s-i;if(0!==n||0!==a){const l=((e-o)*n+(t-i)*a)/(n*n+a*a);l>1?(o=r,i=s):l>0&&(o+=n*l,i+=a*l);}return n=e-o,a=t-i,n*n+a*a}function z(e,t,o,i){const r={id:null==e?null:e,type:t,geometry:o,tags:i,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("Point"===t||"MultiPoint"===t||"LineString"===t)G(r,o);else if("Polygon"===t)G(r,o[0]);else if("MultiLineString"===t)for(const e of o)G(r,e);else if("MultiPolygon"===t)for(const e of o)G(r,e[0]);return r}function G(e,t){for(let o=0;o0&&(n+=i?(r*l-a*s)/2:Math.sqrt(Math.pow(a-r,2)+Math.pow(l-s,2))),r=a,s=l;}const a=t.length-3;t[2]=1,L(t,0,a,o),t[a+2]=1,t.size=Math.abs(n),t.start=0,t.end=t.size;}function Z(e,t,o,i){for(let r=0;r1?1:o}function W(e,t,o,i,r,s,n,a){if(i/=t,s>=(o/=t)&&n=i)return null;const l=[];for(const t of e){const e=t.geometry;let s=t.type;const n=0===r?t.minX:t.minY,c=0===r?t.maxX:t.maxY;if(n>=o&&c=i)continue;let u=[];if("Point"===s||"MultiPoint"===s)R(e,u,o,i,r);else if("LineString"===s)Y(e,u,o,i,r,false,a.lineMetrics);else if("MultiLineString"===s)X(e,u,o,i,r,false);else if("Polygon"===s)X(e,u,o,i,r,true);else if("MultiPolygon"===s)for(const t of e){const e=[];X(t,e,o,i,r,true),e.length&&u.push(e);}if(u.length){if(a.lineMetrics&&"LineString"===s){for(const e of u)l.push(z(t.id,s,e,t.tags));continue}"LineString"!==s&&"MultiLineString"!==s||(1===u.length?(s="LineString",u=u[0]):s="MultiLineString"),"Point"!==s&&"MultiPoint"!==s||(s=3===u.length?"Point":"MultiPoint"),l.push(z(t.id,s,u,t.tags));}}return l.length?l:null}function R(e,t,o,i,r){for(let s=0;s=o&&n<=i&&q(t,e[s],e[s+1],e[s+2]);}}function Y(e,t,o,i,r,s,n){let a=V(e);const l=0===r?B:H;let c,u,h=e.start;for(let d=0;do&&(u=l(a,f,g,m,y,o),n&&(a.start=h+c*u)):v>i?w=o&&(u=l(a,f,g,m,y,o),x=true),w>i&&v<=i&&(u=l(a,f,g,m,y,i),x=true),!s&&x&&(n&&(a.end=h+c*u),t.push(a),a=V(e)),n&&(h+=c);}let d=e.length-3;const f=e[d],g=e[d+1],p=0===r?f:g;p>=o&&p<=i&&q(a,f,g,e[d+2]),d=a.length-3,s&&d>=3&&(a[d]!==a[0]||a[d+1]!==a[1])&&q(a,a[0],a[1],a[2]),a.length&&t.push(a);}function V(e){const t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function X(e,t,o,i,r,s){for(const n of e)Y(n,t,o,i,r,s,false);}function q(e,t,o,i){e.push(t,o,i);}function B(e,t,o,i,r,s){const n=(s-t)/(i-t);return q(e,s,o+(r-o)*n,1),n}function H(e,t,o,i,r,s){const n=(s-o)/(r-o);return q(e,t+(i-t)*n,s,1),n}function $(e,t){const o=[];for(let i=0;i0&&t.size<(r?n:i))return void(o.numPoints+=t.length/3);const a=[];for(let e=0;en)&&(o.numSimplified++,a.push(t[e],t[e+1])),o.numPoints++;r&&function(e,t){let o=0;for(let t=0,i=e.length,r=i-2;t0===t)for(let t=0,o=e.length;t24)throw new Error("maxZoom should be in the 0-24 range");if(t.promoteId&&t.generateId)throw new Error("promoteId and generateId cannot be used together.");let i=function(e,t){const o=[];if("FeatureCollection"===e.type)for(let i=0;i1&&console.time("creation"),d=this.tiles[h]=ee(e,t,o,i,l),this.tileCoords.push({z:t,x:o,y:i}),c)){c>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,o,i,d.numFeatures,d.numPoints,d.numSimplified),console.timeEnd("creation"));const e=`z${t}`;this.stats[e]=(this.stats[e]||0)+1,this.total++;}if(d.source=e,null==r){if(t===l.indexMaxZoom||d.numPoints<=l.indexMaxPoints)continue}else {if(t===l.maxZoom||t===r)continue;if(null!=r){const e=r-t;if(o!==s>>e||i!==n>>e)continue}}if(d.source=null,0===e.length)continue;c>1&&console.time("clipping");const f=.5*l.buffer/l.extent,g=.5-f,p=.5+f,m=1+f;let y=null,v=null,w=null,x=null,_=W(e,u,o-f,o+p,0,d.minX,d.maxX,l),b=W(e,u,o+g,o+m,0,d.minX,d.maxX,l);e=null,_&&(y=W(_,u,i-f,i+p,1,d.minY,d.maxY,l),v=W(_,u,i+g,i+m,1,d.minY,d.maxY,l),_=null),b&&(w=W(b,u,i-f,i+p,1,d.minY,d.maxY,l),x=W(b,u,i+g,i+m,1,d.minY,d.maxY,l),b=null),c>1&&console.timeEnd("clipping"),a.push(y||[],t+1,2*o,2*i),a.push(v||[],t+1,2*o,2*i+1),a.push(w||[],t+1,2*o+1,2*i),a.push(x||[],t+1,2*o+1,2*i+1);}}getTile(e,t,o){e=+e,t=+t,o=+o;const i=this.options,{extent:r,debug:s}=i;if(e<0||e>24)return null;const n=1<1&&console.log("drilling down to z%d-%d-%d",e,t,o);let l,c=e,u=t,h=o;for(;!l&&c>0;)c--,u>>=1,h>>=1,l=this.tiles[se(c,u,h)];return l&&l.source?(s>1&&(console.log("found parent tile z%d-%d-%d",c,u,h),console.time("drilling down")),this.splitTile(l.source,c,u,h,e,t,o),s>1&&console.timeEnd("drilling down"),this.tiles[a]?K(this.tiles[a],r):null):null}}function se(e,t,o){return 32*((1<{n.properties=e;const t={};for(const e of a)t[e]=i[e].evaluate(s,n);return t},t.reduce=(e,t)=>{n.properties=t;for(const t of a)s.accumulated=e[t],e[t]=r[t].evaluate(s,n);},t}(t)).load((yield this._pendingData).features):(r=yield this._pendingData,new re(r,t.geojsonVtOptions)),this.loaded={};const o={};if(i){const e=i.finish();e&&(o.resourceTiming={},o.resourceTiming[t.source]=JSON.parse(JSON.stringify(e)));}return o}catch(t){if(delete this._pendingRequest,e.cf(t))return {abandoned:true};throw t}var r;}))}getData(){return e._(this,undefined,undefined,(function*(){return this._pendingData}))}reloadTile(e){const t=this.loaded;return t&&t[e.uid]?super.reloadTile(e):this.loadTile(e)}loadAndProcessGeoJSON(t,o){return e._(this,undefined,undefined,(function*(){let i=yield this.loadGeoJSON(t,o);if(delete this._pendingRequest,"object"!=typeof i)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(u(i,true),t.filter){const o=e.cB(t.filter,{type:"boolean","property-type":"data-driven",overridable:false,transition:false});if("error"===o.result)throw new Error(o.value.map((e=>`${e.key}: ${e.message}`)).join(", "));const r=i.features.filter((e=>o.value.evaluate({zoom:0},e)));i={type:"FeatureCollection",features:r};}return i}))}loadGeoJSON(t,o){return e._(this,undefined,undefined,(function*(){const{promoteId:i}=t;if(t.request){const r=yield e.h(t.request,o);return this._dataUpdateable=ae(r.data,i)?le(r.data,i):undefined,r.data}if("string"==typeof t.data)try{const e=JSON.parse(t.data);return this._dataUpdateable=ae(e,i)?le(e,i):void 0,e}catch(e){throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`)}if(!t.dataDiff)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(!this._dataUpdateable)throw new Error(`Cannot update existing geojson data in ${t.source}`);return function(e,t,o){var i,r,s,n;if(t.removeAll&&e.clear(),t.remove)for(const o of t.remove)e.delete(o);if(t.add)for(const i of t.add){const t=ne(i,o);null!=t&&e.set(t,i);}if(t.update)for(const o of t.update){let t=e.get(o.id);if(null==t)continue;const a=!o.removeAllProperties&&((null===(i=o.removeProperties)||undefined===i?undefined:i.length)>0||(null===(r=o.addOrUpdateProperties)||undefined===r?undefined:r.length)>0);if((o.newGeometry||o.removeAllProperties||a)&&(t=Object.assign({},t),e.set(o.id,t),a&&(t.properties=Object.assign({},t.properties))),o.newGeometry&&(t.geometry=o.newGeometry),o.removeAllProperties)t.properties={};else if((null===(s=o.removeProperties)||undefined===s?undefined:s.length)>0)for(const e of o.removeProperties)Object.prototype.hasOwnProperty.call(t.properties,e)&&delete t.properties[e];if((null===(n=o.addOrUpdateProperties)||undefined===n?undefined:n.length)>0)for(const{key:e,value:i}of o.addOrUpdateProperties)t.properties[e]=i;}}(this._dataUpdateable,t.dataDiff,i),{type:"FeatureCollection",features:Array.from(this._dataUpdateable.values())}}))}removeSource(t){return e._(this,undefined,undefined,(function*(){this._pendingRequest&&this._pendingRequest.abort();}))}getClusterExpansionZoom(e){return this._geoJSONIndex.getClusterExpansionZoom(e.clusterId)}getClusterChildren(e){return this._geoJSONIndex.getChildren(e.clusterId)}getClusterLeaves(e){return this._geoJSONIndex.getLeaves(e.clusterId,e.limit,e.offset)}}class ue{constructor(t){this.self=t,this.actor=new e.F(t),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.self.registerWorkerSource=(e,t)=>{if(this.externalWorkerSourceTypes[e])throw new Error(`Worker source with name "${e}" already registered.`);this.externalWorkerSourceTypes[e]=t;},this.self.addProtocol=e.ch,this.self.removeProtocol=e.ci,this.self.registerRTLTextPlugin=t=>{e.cC.setMethods(t);},this.actor.registerMessageHandler("LDT",((e,t)=>this._getDEMWorkerSource(e,t.source).loadTile(t))),this.actor.registerMessageHandler("RDT",((t,o)=>e._(this,undefined,undefined,(function*(){this._getDEMWorkerSource(t,o.source).removeTile(o);})))),this.actor.registerMessageHandler("GCEZ",((t,o)=>e._(this,undefined,undefined,(function*(){return this._getWorkerSource(t,o.type,o.source).getClusterExpansionZoom(o)})))),this.actor.registerMessageHandler("GCC",((t,o)=>e._(this,undefined,undefined,(function*(){return this._getWorkerSource(t,o.type,o.source).getClusterChildren(o)})))),this.actor.registerMessageHandler("GCL",((t,o)=>e._(this,undefined,undefined,(function*(){return this._getWorkerSource(t,o.type,o.source).getClusterLeaves(o)})))),this.actor.registerMessageHandler("LD",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadData(t))),this.actor.registerMessageHandler("GD",((e,t)=>this._getWorkerSource(e,t.type,t.source).getData())),this.actor.registerMessageHandler("LT",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadTile(t))),this.actor.registerMessageHandler("RT",((e,t)=>this._getWorkerSource(e,t.type,t.source).reloadTile(t))),this.actor.registerMessageHandler("AT",((e,t)=>this._getWorkerSource(e,t.type,t.source).abortTile(t))),this.actor.registerMessageHandler("RMT",((e,t)=>this._getWorkerSource(e,t.type,t.source).removeTile(t))),this.actor.registerMessageHandler("RS",((t,o)=>e._(this,undefined,undefined,(function*(){if(!this.workerSources[t]||!this.workerSources[t][o.type]||!this.workerSources[t][o.type][o.source])return;const e=this.workerSources[t][o.type][o.source];delete this.workerSources[t][o.type][o.source],undefined!==e.removeSource&&e.removeSource(o);})))),this.actor.registerMessageHandler("RM",(t=>e._(this,undefined,undefined,(function*(){delete this.layerIndexes[t],delete this.availableImages[t],delete this.workerSources[t],delete this.demWorkerSources[t];})))),this.actor.registerMessageHandler("SR",((t,o)=>e._(this,undefined,undefined,(function*(){this.referrer=o;})))),this.actor.registerMessageHandler("SRPS",((e,t)=>this._syncRTLPluginState(e,t))),this.actor.registerMessageHandler("IS",((t,o)=>e._(this,undefined,undefined,(function*(){this.self.importScripts(o);})))),this.actor.registerMessageHandler("SI",((e,t)=>this._setImages(e,t))),this.actor.registerMessageHandler("UL",((t,o)=>e._(this,undefined,undefined,(function*(){this._getLayerIndex(t).update(o.layers,o.removedIds);})))),this.actor.registerMessageHandler("SL",((t,o)=>e._(this,undefined,undefined,(function*(){this._getLayerIndex(t).replace(o);}))));}_setImages(t,o){return e._(this,undefined,undefined,(function*(){this.availableImages[t]=o;for(const e in this.workerSources[t]){const i=this.workerSources[t][e];for(const e in i)i[e].availableImages=o;}}))}_syncRTLPluginState(t,o){return e._(this,undefined,undefined,(function*(){return yield e.cC.syncState(o,this.self.importScripts)}))}_getAvailableImages(e){let t=this.availableImages[e];return t||(t=[]),t}_getLayerIndex(e){let o=this.layerIndexes[e];return o||(o=this.layerIndexes[e]=new t),o}_getWorkerSource(e,t,o){if(this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][t]||(this.workerSources[e][t]={}),!this.workerSources[e][t][o]){const i={sendAsync:(t,o)=>(t.targetMapId=e,this.actor.sendAsync(t,o))};switch(t){case"vector":this.workerSources[e][t][o]=new s(i,this._getLayerIndex(e),this._getAvailableImages(e));break;case"geojson":this.workerSources[e][t][o]=new ce(i,this._getLayerIndex(e),this._getAvailableImages(e));break;default:this.workerSources[e][t][o]=new this.externalWorkerSourceTypes[t](i,this._getLayerIndex(e),this._getAvailableImages(e));}}return this.workerSources[e][t][o]}_getDEMWorkerSource(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new n),this.demWorkerSources[e][t]}}return e.i(self)&&(self.worker=new ue(self)),ue})); - - define("index",["exports","./shared"],(function(e,t){var i="5.0.0";function r(){var e=new t.A(4);return t.A!=Float32Array&&(e[1]=0,e[2]=0),e[0]=1,e[3]=1,e}let o,s;const a={now:"undefined"!=typeof performance&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date),frameAsync:e=>new Promise(((i,r)=>{const o=requestAnimationFrame(i);e.signal.addEventListener("abort",(()=>{cancelAnimationFrame(o),r(t.c());}));})),getImageData(e,t=0){return this.getImageCanvasContext(e).getImageData(-t,-t,e.width+2*t,e.height+2*t)},getImageCanvasContext(e){const t=window.document.createElement("canvas"),i=t.getContext("2d",{willReadFrequently:true});if(!i)throw new Error("failed to create canvas 2d context");return t.width=e.width,t.height=e.height,i.drawImage(e,0,0,e.width,e.height),i},resolveURL:e=>(o||(o=document.createElement("a")),o.href=e,o.href),hardwareConcurrency:"undefined"!=typeof navigator&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return !!matchMedia&&(null==s&&(s=matchMedia("(prefers-reduced-motion: reduce)")),s.matches)}};class n{static testProp(e){if(!n.docStyle)return e[0];for(let t=0;t{window.removeEventListener("click",n.suppressClickInternal,true);}),0);}static getScale(e){const t=e.getBoundingClientRect();return {x:t.width/e.offsetWidth||1,y:t.height/e.offsetHeight||1,boundingClientRect:t}}static getPoint(e,i,r){const o=i.boundingClientRect;return new t.P((r.clientX-o.left)/i.x-e.clientLeft,(r.clientY-o.top)/i.y-e.clientTop)}static mousePos(e,t){const i=n.getScale(e);return n.getPoint(e,i,t)}static touchPos(e,t){const i=[],r=n.getScale(e);for(let o=0;o{c&&_(c),c=null,d=true;},h.onerror=()=>{u=true,c=null;},h.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="),function(e){let i,r,o,s;e.resetRequestQueue=()=>{i=[],r=0,o=0,s={};},e.addThrottleControl=e=>{const t=o++;return s[t]=e,t},e.removeThrottleControl=e=>{delete s[e],n();},e.getImage=(e,r,o=true)=>new Promise(((s,a)=>{l.supported&&(e.headers||(e.headers={}),e.headers.accept="image/webp,*/*"),t.e(e,{type:"image"}),i.push({abortController:r,requestParameters:e,supportImageRefresh:o,state:"queued",onError:e=>{a(e);},onSuccess:e=>{s(e);}}),n();}));const a=e=>t._(this,undefined,undefined,(function*(){e.state="running";const{requestParameters:i,supportImageRefresh:o,onError:s,onSuccess:a,abortController:l}=e,h=false===o&&!t.i(self)&&!t.g(i.url)&&(!i.headers||Object.keys(i.headers).reduce(((e,t)=>e&&"accept"===t),true));r++;const u=h?c(i,l):t.m(i,l);try{const i=yield u;delete e.abortController,e.state="completed",i.data instanceof HTMLImageElement||t.b(i.data)?a(i):i.data&&a({data:yield(d=i.data,"function"==typeof createImageBitmap?t.d(d):t.f(d)),cacheControl:i.cacheControl,expires:i.expires});}catch(t){delete e.abortController,s(t);}finally{r--,n();}var d;})),n=()=>{const e=(()=>{for(const e of Object.keys(s))if(s[e]())return true;return false})()?t.a.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:t.a.MAX_PARALLEL_IMAGE_REQUESTS;for(let t=r;t0;t++){const e=i.shift();e.abortController.signal.aborted?t--:a(e);}},c=(e,i)=>new Promise(((r,o)=>{const s=new Image,a=e.url,n=e.credentials;n&&"include"===n?s.crossOrigin="use-credentials":(n&&"same-origin"===n||!t.s(a))&&(s.crossOrigin="anonymous"),i.signal.addEventListener("abort",(()=>{s.src="",o(t.c());})),s.fetchPriority="high",s.onload=()=>{s.onerror=s.onload=null,r({data:s});},s.onerror=()=>{s.onerror=s.onload=null,i.signal.aborted||o(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));},s.src=a;}));}(p||(p={})),p.resetRequestQueue();class m{constructor(e){this._transformRequestFn=e;}transformRequest(e,t){return this._transformRequestFn&&this._transformRequestFn(e,t)||{url:e}}setTransformRequest(e){this._transformRequestFn=e;}}function f(e){const t=[];if("string"==typeof e)t.push({id:"default",url:e});else if(e&&e.length>0){const i=[];for(const{id:r,url:o}of e){const e=`${r}${o}`;-1===i.indexOf(e)&&(i.push(e),t.push({id:r,url:o}));}}return t}function g(e,t,i){try{const r=new URL(e);return r.pathname+=`${t}${i}`,r.toString()}catch(t){throw new Error(`Invalid sprite URL "${e}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`)}}class v{constructor(e,t,i,r){this.context=e,this.format=i,this.texture=e.gl.createTexture(),this.update(t,r);}update(e,i,r){const{width:o,height:s}=e,a=!(this.size&&this.size[0]===o&&this.size[1]===s||r),{context:n}=this,{gl:l}=n;if(this.useMipmap=Boolean(i&&i.useMipmap),l.bindTexture(l.TEXTURE_2D,this.texture),n.pixelStoreUnpackFlipY.set(false),n.pixelStoreUnpack.set(1),n.pixelStoreUnpackPremultiplyAlpha.set(this.format===l.RGBA&&(!i||false!==i.premultiply)),a)this.size=[o,s],e instanceof HTMLImageElement||e instanceof HTMLCanvasElement||e instanceof HTMLVideoElement||e instanceof ImageData||t.b(e)?l.texImage2D(l.TEXTURE_2D,0,this.format,this.format,l.UNSIGNED_BYTE,e):l.texImage2D(l.TEXTURE_2D,0,this.format,o,s,0,this.format,l.UNSIGNED_BYTE,e.data);else {const{x:i,y:a}=r||{x:0,y:0};e instanceof HTMLImageElement||e instanceof HTMLCanvasElement||e instanceof HTMLVideoElement||e instanceof ImageData||t.b(e)?l.texSubImage2D(l.TEXTURE_2D,0,i,a,l.RGBA,l.UNSIGNED_BYTE,e):l.texSubImage2D(l.TEXTURE_2D,0,i,a,o,s,l.RGBA,l.UNSIGNED_BYTE,e.data);}this.useMipmap&&this.isSizePowerOfTwo()&&l.generateMipmap(l.TEXTURE_2D);}bind(e,t,i){const{context:r}=this,{gl:o}=r;o.bindTexture(o.TEXTURE_2D,this.texture),i!==o.LINEAR_MIPMAP_NEAREST||this.isSizePowerOfTwo()||(i=o.LINEAR),e!==this.filter&&(o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,e),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,i||e),this.filter=e),t!==this.wrap&&(o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,t),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,t),this.wrap=t);}isSizePowerOfTwo(){return this.size[0]===this.size[1]&&Math.log(this.size[0])/Math.LN2%1==0}destroy(){const{gl:e}=this.context;e.deleteTexture(this.texture),this.texture=null;}}function x(e){const{userImage:t}=e;return !!(t&&t.render&&t.render())&&(e.data.replace(new Uint8Array(t.data.buffer)),true)}class b extends t.E{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=false,this.requestors=[],this.patterns={},this.atlasImage=new t.R({width:1,height:1}),this.dirty=true;}isLoaded(){return this.loaded}setLoaded(e){if(this.loaded!==e&&(this.loaded=e,e)){for(const{ids:e,promiseResolve:t}of this.requestors)t(this._getImagesForIds(e));this.requestors=[];}}getImage(e){const i=this.images[e];if(i&&!i.data&&i.spriteData){const e=i.spriteData;i.data=new t.R({width:e.width,height:e.height},e.context.getImageData(e.x,e.y,e.width,e.height).data),i.spriteData=null;}return i}addImage(e,t){if(this.images[e])throw new Error(`Image id ${e} already exist, use updateImage instead`);this._validate(e,t)&&(this.images[e]=t);}_validate(e,i){let r=true;const o=i.data||i.spriteData;return this._validateStretch(i.stretchX,o&&o.width)||(this.fire(new t.j(new Error(`Image "${e}" has invalid "stretchX" value`))),r=false),this._validateStretch(i.stretchY,o&&o.height)||(this.fire(new t.j(new Error(`Image "${e}" has invalid "stretchY" value`))),r=false),this._validateContent(i.content,i)||(this.fire(new t.j(new Error(`Image "${e}" has invalid "content" value`))),r=false),r}_validateStretch(e,t){if(!e)return true;let i=0;for(const r of e){if(r[0]{let r=true;if(!this.isLoaded())for(const t of e)this.images[t]||(r=false);this.isLoaded()||r?t(this._getImagesForIds(e)):this.requestors.push({ids:e,promiseResolve:t});}))}_getImagesForIds(e){const i={};for(const r of e){let e=this.getImage(r);e||(this.fire(new t.k("styleimagemissing",{id:r})),e=this.getImage(r)),e?i[r]={data:e.data.clone(),pixelRatio:e.pixelRatio,sdf:e.sdf,version:e.version,stretchX:e.stretchX,stretchY:e.stretchY,content:e.content,textFitWidth:e.textFitWidth,textFitHeight:e.textFitHeight,hasRenderCallback:Boolean(e.userImage&&e.userImage.render)}:t.w(`Image "${r}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`);}return i}getPixelSize(){const{width:e,height:t}=this.atlasImage;return {width:e,height:t}}getPattern(e){const i=this.patterns[e],r=this.getImage(e);if(!r)return null;if(i&&i.position.version===r.version)return i.position;if(i)i.position.version=r.version;else {const i={w:r.data.width+2,h:r.data.height+2,x:0,y:0},o=new t.I(i,r);this.patterns[e]={bin:i,position:o};}return this._updatePatternAtlas(),this.patterns[e].position}bind(e){const t=e.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=false):this.atlasTexture=new v(e,this.atlasImage,t.RGBA),this.atlasTexture.bind(t.LINEAR,t.CLAMP_TO_EDGE);}_updatePatternAtlas(){const e=[];for(const t in this.patterns)e.push(this.patterns[t].bin);const{w:i,h:r}=t.p(e),o=this.atlasImage;o.resize({width:i||1,height:r||1});for(const e in this.patterns){const{bin:i}=this.patterns[e],r=i.x+1,s=i.y+1,a=this.getImage(e).data,n=a.width,l=a.height;t.R.copy(a,o,{x:0,y:0},{x:r,y:s},{width:n,height:l}),t.R.copy(a,o,{x:0,y:l-1},{x:r,y:s-1},{width:n,height:1}),t.R.copy(a,o,{x:0,y:0},{x:r,y:s+l},{width:n,height:1}),t.R.copy(a,o,{x:n-1,y:0},{x:r-1,y:s},{width:1,height:l}),t.R.copy(a,o,{x:0,y:0},{x:r+n,y:s},{width:1,height:l});}this.dirty=true;}beginFrame(){this.callbackDispatchedThisFrame={};}dispatchRenderCallbacks(e){for(const i of e){if(this.callbackDispatchedThisFrame[i])continue;this.callbackDispatchedThisFrame[i]=true;const e=this.getImage(i);e||t.w(`Image with ID: "${i}" was not found`),x(e)&&this.updateImage(i,e);}}}const y=1e20;function w(e,t,i,r,o,s,a,n,l){for(let c=t;c-1);l++,s[l]=n,a[l]=c,a[l+1]=y;}for(let n=0,l=0;n65535)throw new Error("glyphs > 65535 not supported");if(t.ranges[o])return {stack:e,id:i,glyph:r};if(!this.url)throw new Error("glyphsUrl is not set");if(!t.requests[o]){const i=P.loadGlyphRange(e,o,this.url,this.requestManager);t.requests[o]=i;}const s=yield t.requests[o];for(const e in s)this._doesCharSupportLocalGlyph(+e)||(t.glyphs[+e]=s[+e]);return t.ranges[o]=true,{stack:e,id:i,glyph:s[i]||null}}))}_doesCharSupportLocalGlyph(e){return !!this.localIdeographFontFamily&&/\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(e))}_tinySDF(e,i,r){const o=this.localIdeographFontFamily;if(!o)return;if(!this._doesCharSupportLocalGlyph(r))return;let s=e.tinySDF;if(!s){let t="400";/bold/i.test(i)?t="900":/medium/i.test(i)?t="500":/light/i.test(i)&&(t="200"),s=e.tinySDF=new P.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,fontFamily:o,fontWeight:t});}const a=s.draw(String.fromCharCode(r));return {id:r,bitmap:new t.o({width:a.width||60,height:a.height||60},a.data),metrics:{width:a.glyphWidth/2||24,height:a.glyphHeight/2||24,left:a.glyphLeft/2+.5||0,top:a.glyphTop/2-27.5||-8,advance:a.glyphAdvance/2||24,isDoubleResolution:true}}}}P.loadGlyphRange=function(e,i,r,o){return t._(this,undefined,undefined,(function*(){const s=256*i,a=s+255,n=o.transformRequest(r.replace("{fontstack}",e).replace("{range}",`${s}-${a}`),"Glyphs"),l=yield t.l(n,new AbortController);if(!l||!l.data)throw new Error(`Could not load glyph range. range: ${i}, ${s}-${a}`);const c={};for(const e of t.n(l.data))c[e.id]=e;return c}))},P.TinySDF=class{constructor({fontSize:e=24,buffer:t=3,radius:i=8,cutoff:r=.25,fontFamily:o="sans-serif",fontWeight:s="normal",fontStyle:a="normal"}={}){this.buffer=t,this.cutoff=r,this.radius=i;const n=this.size=e+4*t,l=this._createCanvas(n),c=this.ctx=l.getContext("2d",{willReadFrequently:true});c.font=`${a} ${s} ${e}px ${o}`,c.textBaseline="alphabetic",c.textAlign="left",c.fillStyle="black",this.gridOuter=new Float64Array(n*n),this.gridInner=new Float64Array(n*n),this.f=new Float64Array(n),this.z=new Float64Array(n+1),this.v=new Uint16Array(n);}_createCanvas(e){const t=document.createElement("canvas");return t.width=t.height=e,t}draw(e){const{width:t,actualBoundingBoxAscent:i,actualBoundingBoxDescent:r,actualBoundingBoxLeft:o,actualBoundingBoxRight:s}=this.ctx.measureText(e),a=Math.ceil(i),n=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(s-o))),l=Math.min(this.size-this.buffer,a+Math.ceil(r)),c=n+2*this.buffer,h=l+2*this.buffer,u=Math.max(c*h,0),d=new Uint8ClampedArray(u),_={data:d,width:c,height:h,glyphWidth:n,glyphHeight:l,glyphTop:a,glyphLeft:0,glyphAdvance:t};if(0===n||0===l)return _;const{ctx:p,buffer:m,gridInner:f,gridOuter:g}=this;p.clearRect(m,m,n,l),p.fillText(e,m,m+a);const v=p.getImageData(m,m,n,l);g.fill(y,0,u),f.fill(0,0,u);for(let e=0;e0?e*e:0,f[r]=e<0?e*e:0;}}w(g,0,0,c,h,c,this.f,this.v,this.z),w(f,m,m,n,l,c,this.f,this.v,this.z);for(let e=0;e1&&(a=e[++s]);const l=Math.abs(n-a.left),c=Math.abs(n-a.right),h=Math.min(l,c);let u;const d=t/i*(r+1);if(a.isDash){const e=r-Math.abs(d);u=Math.sqrt(h*h+e*e);}else u=r-Math.sqrt(h*h+d*d);this.data[o+n]=Math.max(0,Math.min(255,u+128));}}}addRegularDash(e){for(let t=e.length-1;t>=0;--t){const i=e[t],r=e[t+1];i.zeroLength?e.splice(t,1):r&&r.isDash===i.isDash&&(r.left=i.left,e.splice(t,1));}const t=e[0],i=e[e.length-1];t.isDash===i.isDash&&(t.left=i.left-this.width,i.right=t.right+this.width);const r=this.width*this.nextRow;let o=0,s=e[o];for(let t=0;t1&&(s=e[++o]);const i=Math.abs(t-s.left),a=Math.abs(t-s.right),n=Math.min(i,a);this.data[r+t]=Math.max(0,Math.min(255,(s.isDash?n:-n)+128));}}addDash(e,i){const r=i?7:0,o=2*r+1;if(this.nextRow+o>this.height)return t.w("LineAtlas out of space"),null;let s=0;for(let t=0;t{e.terminate();})),this.workers=null);}isPreloaded(){return !!this.active[D]}numActive(){return Object.keys(this.active).length}}const A=Math.floor(a.hardwareConcurrency/2);let L,k;function F(){return L||(L=new z),L}z.workerCount=t.C(globalThis)?Math.max(Math.min(A,3),1):1;class B{constructor(e,i){this.workerPool=e,this.actors=[],this.currentActor=0,this.id=i;const r=this.workerPool.acquire(i);for(let e=0;e{e.remove();})),this.actors=[],e&&this.workerPool.release(this.id);}registerMessageHandler(e,t){for(const i of this.actors)i.registerMessageHandler(e,t);}}function j(){return k||(k=new B(F(),t.G),k.registerMessageHandler("GR",((e,i,r)=>t.m(i,r)))),k}function O(e,i){const r=t.H();return t.J(r,r,[1,1,0]),t.K(r,r,[.5*e.width,.5*e.height,1]),e.calculatePosMatrix?t.L(r,r,e.calculatePosMatrix(i.toUnwrapped())):r}function N(e,t,i,r,o,s){var a;const n=function(e,t,i){if(e)for(const r of e){const e=t[r];if(e&&e.source===i&&"fill-extrusion"===e.type)return true}else for(const e in t){const r=t[e];if(r.source===i&&"fill-extrusion"===r.type)return true}return false}(null!==(a=null==o?undefined:o.layers)&&undefined!==a?a:null,t,e.id),l=s.maxPitchScaleFactor(),c=e.tilesIn(r,l,n);c.sort(Z);const h=[];for(const r of c)h.push({wrappedTileID:r.tileID.wrapped().key,queryResults:r.tile.queryRenderedFeatures(t,i,e._state,r.queryGeometry,r.cameraQueryGeometry,r.scale,o,s,l,O(e.transform,r.tileID))});return function(e,t){for(const i in e)for(const r of e[i])G(r,t);return e}(function(e){const t={},i={};for(const r of e){const e=r.queryResults,o=r.wrappedTileID,s=i[o]=i[o]||{};for(const i in e){const r=e[i],o=s[i]=s[i]||{},a=t[i]=t[i]||[];for(const e of r)o[e.featureIndex]||(o[e.featureIndex]=true,a.push(e));}}return t}(h),e)}function Z(e,t){const i=e.tileID,r=t.tileID;return i.overscaledZ-r.overscaledZ||i.canonical.y-r.canonical.y||i.wrap-r.wrap||i.canonical.x-r.canonical.x}function G(e,t){const i=e.feature,r=t.getFeatureState(i.layer["source-layer"],i.id);i.source=i.layer.source,i.layer["source-layer"]&&(i.sourceLayer=i.layer["source-layer"]),i.state=r;}function U(e,i,r){return t._(this,undefined,undefined,(function*(){let o=e;if(e.url?o=(yield t.h(i.transformRequest(e.url,"Source"),r)).data:yield a.frameAsync(r),!o)return null;const s=t.M(t.e(o,e),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return "vector_layers"in o&&o.vector_layers&&(s.vectorLayerIds=o.vector_layers.map((e=>e.id))),s}))}class V{constructor(e,t){e&&(t?this.setSouthWest(e).setNorthEast(t):Array.isArray(e)&&(4===e.length?this.setSouthWest([e[0],e[1]]).setNorthEast([e[2],e[3]]):this.setSouthWest(e[0]).setNorthEast(e[1])));}setNorthEast(e){return this._ne=e instanceof t.N?new t.N(e.lng,e.lat):t.N.convert(e),this}setSouthWest(e){return this._sw=e instanceof t.N?new t.N(e.lng,e.lat):t.N.convert(e),this}extend(e){const i=this._sw,r=this._ne;let o,s;if(e instanceof t.N)o=e,s=e;else {if(!(e instanceof V))return Array.isArray(e)?4===e.length||e.every(Array.isArray)?this.extend(V.convert(e)):this.extend(t.N.convert(e)):e&&("lng"in e||"lon"in e)&&"lat"in e?this.extend(t.N.convert(e)):this;if(o=e._sw,s=e._ne,!o||!s)return this}return i||r?(i.lng=Math.min(o.lng,i.lng),i.lat=Math.min(o.lat,i.lat),r.lng=Math.max(s.lng,r.lng),r.lat=Math.max(s.lat,r.lat)):(this._sw=new t.N(o.lng,o.lat),this._ne=new t.N(s.lng,s.lat)),this}getCenter(){return new t.N((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new t.N(this.getWest(),this.getNorth())}getSouthEast(){return new t.N(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return [this._sw.toArray(),this._ne.toArray()]}toString(){return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return !(this._sw&&this._ne)}contains(e){const{lng:i,lat:r}=t.N.convert(e);let o=this._sw.lng<=i&&i<=this._ne.lng;return this._sw.lng>this._ne.lng&&(o=this._sw.lng>=i&&i>=this._ne.lng),this._sw.lat<=r&&r<=this._ne.lat&&o}static convert(e){return e instanceof V?e:e?new V(e):e}static fromLngLat(e,i=0){const r=360*i/40075017,o=r/Math.cos(Math.PI/180*e.lat);return new V(new t.N(e.lng-o,e.lat-r),new t.N(e.lng+o,e.lat+r))}adjustAntiMeridian(){const e=new t.N(this._sw.lng,this._sw.lat),i=new t.N(this._ne.lng,this._ne.lat);return new V(e,e.lng>i.lng?new t.N(i.lng+360,i.lat):i)}}class q{constructor(e,t,i){this.bounds=V.convert(this.validateBounds(e)),this.minzoom=t||0,this.maxzoom=i||24;}validateBounds(e){return Array.isArray(e)&&4===e.length?[Math.max(-180,e[0]),Math.max(-90,e[1]),Math.min(180,e[2]),Math.min(90,e[3])]:[-180,-90,180,90]}contains(e){const i=Math.pow(2,e.z),r=Math.floor(t.O(this.bounds.getWest())*i),o=Math.floor(t.Q(this.bounds.getNorth())*i),s=Math.ceil(t.O(this.bounds.getEast())*i),a=Math.ceil(t.Q(this.bounds.getSouth())*i);return e.x>=r&&e.x=o&&e.y{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}serialize(){return t.e({},this._options)}loadTile(e){return t._(this,undefined,undefined,(function*(){const t=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),i={request:this.map._requestManager.transformRequest(t,"Tile"),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};i.request.collectResourceTiming=this._collectResourceTiming;let r="RT";if(e.actor&&"expired"!==e.state){if("loading"===e.state)return new Promise(((t,i)=>{e.reloadPromise={resolve:t,reject:i};}))}else e.actor=this.dispatcher.getActor(),r="LT";e.abortController=new AbortController;try{const t=yield e.actor.sendAsync({type:r,data:i},e.abortController);if(delete e.abortController,e.aborted)return;this._afterTileLoadWorkerResponse(e,t);}catch(t){if(delete e.abortController,e.aborted)return;if(t&&404!==t.status)throw t;this._afterTileLoadWorkerResponse(e,null);}}))}_afterTileLoadWorkerResponse(e,t){if(t&&t.resourceTiming&&(e.resourceTiming=t.resourceTiming),t&&this.map._refreshExpiredTiles&&e.setExpiryData(t),e.loadVectorData(t,this.map.painter),e.reloadPromise){const t=e.reloadPromise;e.reloadPromise=null,this.loadTile(e).then(t.resolve).catch(t.reject);}}abortTile(e){return t._(this,undefined,undefined,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.actor&&(yield e.actor.sendAsync({type:"AT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}unloadTile(e){return t._(this,undefined,undefined,(function*(){e.unloadVectorData(),e.actor&&(yield e.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}hasTransition(){return false}}class W extends t.E{constructor(e,i,r,o){super(),this.id=e,this.dispatcher=r,this.setEventedParent(o),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=true,this.scheme="xyz",this.tileSize=512,this._loaded=false,this._options=t.e({type:"raster"},i),t.e(this,t.M(i,["url","scheme","tileSize"]));}load(){return t._(this,arguments,undefined,(function*(e=false){this._loaded=false,this.fire(new t.k("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{const i=yield U(this._options,this.map._requestManager,this._tileJSONRequest);this._tileJSONRequest=null,this._loaded=!0,i&&(t.e(this,i),i.bounds&&(this.tileBounds=new q(i.bounds,this.minzoom,this.maxzoom)),this.fire(new t.k("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new t.k("data",{dataType:"source",sourceDataType:"content",sourceDataChanged:e})));}catch(e){this._tileJSONRequest=null,this.fire(new t.j(e));}}))}loaded(){return this._loaded}onAdd(e){this.map=e,this.load();}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}setSourceProperty(e){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),e(),this.load(true);}setTiles(e){return this.setSourceProperty((()=>{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}serialize(){return t.e({},this._options)}hasTile(e){return !this.tileBounds||this.tileBounds.contains(e.canonical)}loadTile(e){return t._(this,undefined,undefined,(function*(){const t=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);e.abortController=new AbortController;try{const i=yield p.getImage(this.map._requestManager.transformRequest(t,"Tile"),e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(i&&i.data){this.map._refreshExpiredTiles&&i.cacheControl&&i.expires&&e.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const t=this.map.painter.context,r=t.gl,o=i.data;e.texture=this.map.painter.getTileTexture(o.width),e.texture?e.texture.update(o,{useMipmap:!0}):(e.texture=new v(t,o,r.RGBA,{useMipmap:!0}),e.texture.bind(r.LINEAR,r.CLAMP_TO_EDGE,r.LINEAR_MIPMAP_NEAREST)),e.state="loaded";}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}abortTile(e){return t._(this,undefined,undefined,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController);}))}unloadTile(e){return t._(this,undefined,undefined,(function*(){e.texture&&this.map.painter.saveTileTexture(e.texture);}))}hasTransition(){return false}}class X extends W{constructor(e,i,r,o){super(e,i,r,o),this.type="raster-dem",this.maxzoom=22,this._options=t.e({type:"raster-dem"},i),this.encoding=i.encoding||"mapbox",this.redFactor=i.redFactor,this.greenFactor=i.greenFactor,this.blueFactor=i.blueFactor,this.baseShift=i.baseShift;}loadTile(e){return t._(this,undefined,undefined,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),r=this.map._requestManager.transformRequest(i,"Tile");e.neighboringTiles=this._getNeighboringTiles(e.tileID),e.abortController=new AbortController;try{const i=yield p.getImage(r,e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(i&&i.data){const r=i.data;this.map._refreshExpiredTiles&&i.cacheControl&&i.expires&&e.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const o=t.b(r)&&t.U()?r:yield this.readImageNow(r),s={type:this.type,uid:e.uid,source:this.id,rawImageData:o,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(!e.actor||"expired"===e.state){e.actor=this.dispatcher.getActor();const t=yield e.actor.sendAsync({type:"LDT",data:s});e.dem=t,e.needsHillshadePrepare=!0,e.needsTerrainPrepare=!0,e.state="loaded";}}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}readImageNow(e){return t._(this,undefined,undefined,(function*(){if("undefined"!=typeof VideoFrame&&t.V()){const i=e.width+2,r=e.height+2;try{return new t.R({width:i,height:r},yield t.W(e,-1,-1,i,r))}catch(e){}}return a.getImageData(e,1)}))}_getNeighboringTiles(e){const i=e.canonical,r=Math.pow(2,i.z),o=(i.x-1+r)%r,s=0===i.x?e.wrap-1:e.wrap,a=(i.x+1+r)%r,n=i.x+1===r?e.wrap+1:e.wrap,l={};return l[new t.S(e.overscaledZ,s,i.z,o,i.y).key]={backfilled:false},l[new t.S(e.overscaledZ,n,i.z,a,i.y).key]={backfilled:false},i.y>0&&(l[new t.S(e.overscaledZ,s,i.z,o,i.y-1).key]={backfilled:false},l[new t.S(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:false},l[new t.S(e.overscaledZ,n,i.z,a,i.y-1).key]={backfilled:false}),i.y+10&&t.e(o,{resourceTiming:r}),this.fire(new t.k("data",Object.assign(Object.assign({},o),{sourceDataType:"metadata"}))),this.fire(new t.k("data",Object.assign(Object.assign({},o),{sourceDataType:"content"})));}catch(e){if(this._pendingLoads--,this._removed)return void this.fire(new t.k("dataabort",{dataType:"source"}));this.fire(new t.j(e));}}))}loaded(){return 0===this._pendingLoads}loadTile(e){return t._(this,undefined,undefined,(function*(){const t=e.actor?"RT":"LT";e.actor=this.actor;const i={type:this.type,uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};e.abortController=new AbortController;const r=yield this.actor.sendAsync({type:t,data:i},e.abortController);delete e.abortController,e.unloadVectorData(),e.aborted||e.loadVectorData(r,this.map.painter,"RT"===t);}))}abortTile(e){return t._(this,undefined,undefined,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.aborted=true;}))}unloadTile(e){return t._(this,undefined,undefined,(function*(){e.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}});}))}onRemove(){this._removed=true,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}});}serialize(){return t.e({},this._options,{type:this.type,data:this._data})}hasTransition(){return false}}class K extends t.E{constructor(e,t,i,r){super(),this.flippedWindingOrder=false,this.id=e,this.dispatcher=i,this.coordinates=t.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=false,this.setEventedParent(r),this.options=t;}load(e){return t._(this,undefined,undefined,(function*(){this._loaded=false,this.fire(new t.k("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{const t=yield p.getImage(this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,t&&t.data&&(this.image=t.data,e&&(this.coordinates=e),this._finishLoading());}catch(e){this._request=null,this._loaded=true,this.fire(new t.j(e));}}))}loaded(){return this._loaded}updateImage(e){return e.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=e.url,this.load(e.coordinates).finally((()=>{this.texture=null;})),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.k("data",{dataType:"source",sourceDataType:"metadata"})));}onAdd(e){this.map=e,this.load();}onRemove(){this._request&&(this._request.abort(),this._request=null);}setCoordinates(e){this.coordinates=e;const i=e.map(t.Y.fromLngLat);var r;return this.tileID=function(e){let i=1/0,r=1/0,o=-1/0,s=-1/0;for(const t of e)i=Math.min(i,t.x),r=Math.min(r,t.y),o=Math.max(o,t.x),s=Math.max(s,t.y);const a=Math.max(o-i,s-r),n=Math.max(0,Math.floor(-Math.log(a)/Math.LN2)),l=Math.pow(2,n);return new t.Z(n,Math.floor((i+o)/2*l),Math.floor((r+s)/2*l))}(i),this.minzoom=this.maxzoom=this.tileID.z,this.tileCoords=i.map((e=>this.tileID.getTilePoint(e)._round())),this.flippedWindingOrder=((r=this.tileCoords)[1].x-r[0].x)*(r[2].y-r[0].y)-(r[1].y-r[0].y)*(r[2].x-r[0].x)<0,this.fire(new t.k("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(0===Object.keys(this.tiles).length||!this.image)return;const e=this.map.painter.context,i=e.gl;this.texture||(this.texture=new v(e,this.image,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let r=false;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,r=true);}r&&this.fire(new t.k("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}loadTile(e){return t._(this,undefined,undefined,(function*(){this.tileID&&this.tileID.equals(e.tileID.canonical)?(this.tiles[String(e.tileID.wrap)]=e,e.buckets={}):e.state="errored";}))}serialize(){return {type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return false}}class Y extends K{constructor(e,t,i,r){super(e,t,i,r),this.roundZoom=true,this.type="video",this.options=t;}load(){return t._(this,undefined,undefined,(function*(){this._loaded=false;const e=this.options;this.urls=[];for(const t of e.urls)this.urls.push(this.map._requestManager.transformRequest(t,"Source").url);try{const e=yield t.a0(this.urls);if(this._loaded=!0,!e)return;this.video=e,this.video.loop=!0,this.video.addEventListener("playing",(()=>{this.map.triggerRepaint();})),this.map&&this.video.play(),this._finishLoading();}catch(e){this.fire(new t.j(e));}}))}pause(){this.video&&this.video.pause();}play(){this.video&&this.video.play();}seek(e){if(this.video){const i=this.video.seekable;ei.end(0)?this.fire(new t.j(new t.$(`sources.${this.id}`,null,`Playback for this video can be set only between the ${i.start(0)} and ${i.end(0)}-second mark.`))):this.video.currentTime=e;}}getVideo(){return this.video}onAdd(e){this.map||(this.map=e,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));}prepare(){if(0===Object.keys(this.tiles).length||this.video.readyState<2)return;const e=this.map.painter.context,i=e.gl;this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new v(e,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let r=false;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,r=true);}r&&this.fire(new t.k("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class J extends K{constructor(e,i,r,o){super(e,i,r,o),i.coordinates?Array.isArray(i.coordinates)&&4===i.coordinates.length&&!i.coordinates.some((e=>!Array.isArray(e)||2!==e.length||e.some((e=>"number"!=typeof e))))||this.fire(new t.j(new t.$(`sources.${e}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.j(new t.$(`sources.${e}`,null,'missing required property "coordinates"'))),i.animate&&"boolean"!=typeof i.animate&&this.fire(new t.j(new t.$(`sources.${e}`,null,'optional "animate" property must be a boolean value'))),i.canvas?"string"==typeof i.canvas||i.canvas instanceof HTMLCanvasElement||this.fire(new t.j(new t.$(`sources.${e}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.j(new t.$(`sources.${e}`,null,'missing required property "canvas"'))),this.options=i,this.animate=undefined===i.animate||i.animate;}load(){return t._(this,undefined,undefined,(function*(){this._loaded=true,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.j(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=true,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=false);},this._finishLoading());}))}getCanvas(){return this.canvas}onAdd(e){this.map=e,this.load(),this.canvas&&this.animate&&this.play();}onRemove(){this.pause();}prepare(){let e=false;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=true),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=true),this._hasInvalidDimensions())return;if(0===Object.keys(this.tiles).length)return;const i=this.map.painter.context,r=i.gl;this.texture?(e||this._playing)&&this.texture.update(this.canvas,{premultiply:true}):this.texture=new v(i,this.canvas,r.RGBA,{premultiply:true});let o=false;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=true);}o&&this.fire(new t.k("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const e of [this.canvas.width,this.canvas.height])if(isNaN(e)||e<=0)return true;return false}}const Q={},ee=e=>{switch(e){case"geojson":return $;case"image":return K;case"raster":return W;case"raster-dem":return X;case"vector":return H;case"video":return Y;case"canvas":return J}return Q[e]},te="RTLPluginLoaded";class ie extends t.E{constructor(){super(...arguments),this.status="unavailable",this.url=null,this.dispatcher=j();}_syncState(e){return this.status=e,this.dispatcher.broadcast("SRPS",{pluginStatus:e,pluginURL:this.url}).catch((e=>{throw this.status="error",e}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null;}setRTLTextPlugin(e){return t._(this,arguments,undefined,(function*(e,t=false){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=a.resolveURL(e),!this.url)throw new Error(`requested url ${e} is invalid`);if("unavailable"===this.status){if(!t)return this._requestImport();this.status="deferred",this._syncState(this.status);}else if("requested"===this.status)return this._requestImport()}))}_requestImport(){return t._(this,undefined,undefined,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new t.k(te));}))}lazyLoad(){"unavailable"===this.status?this.status="requested":"deferred"===this.status&&this._requestImport();}}let re=null;function oe(){return re||(re=new ie),re}class se{constructor(e,i){this.timeAdded=0,this.fadeEndTime=0,this.tileID=e,this.uid=t.a1(),this.uses=0,this.tileSize=i,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=false,this.hasRTLText=false,this.dependencies={},this.rtt=[],this.rttCoords={},this.expiredRequestCount=0,this.state="loading";}registerFadeDuration(e){const t=e+this.timeAdded;tt.getLayer(e))).filter(Boolean);if(0!==e.length){r.layers=e,r.stateDependentLayerIds&&(r.stateDependentLayers=r.stateDependentLayerIds.map((t=>e.filter((e=>e.id===t))[0])));for(const t of e)i[t.id]=r;}}return i}(e.buckets,null==i?undefined:i.style),this.hasSymbolBuckets=false;for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a3){if(this.hasSymbolBuckets=true,!r)break;i.justReloaded=true;}}if(this.hasRTLText=false,this.hasSymbolBuckets)for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a3&&i.hasRTLText){this.hasRTLText=true,oe().lazyLoad();break}}this.queryPadding=0;for(const e in this.buckets){const t=this.buckets[e];this.queryPadding=Math.max(this.queryPadding,i.style.getLayer(e).queryRadius(t));}e.imageAtlas&&(this.imageAtlas=e.imageAtlas),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage);}else this.collisionBoxArray=new t.a2;}unloadVectorData(){for(const e in this.buckets)this.buckets[e].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded";}getBucket(e){return this.buckets[e.id]}upload(e){for(const t in this.buckets){const i=this.buckets[t];i.uploadPending()&&i.upload(e);}const t=e.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new v(e,this.imageAtlas.image,t.RGBA),this.imageAtlas.uploaded=true),this.glyphAtlasImage&&(this.glyphAtlasTexture=new v(e,this.glyphAtlasImage,t.ALPHA),this.glyphAtlasImage=null);}prepare(e){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(e,this.imageAtlasTexture);}queryRenderedFeatures(e,t,i,r,o,s,a,n,l,c){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:r,cameraQueryGeometry:o,scale:s,tileSize:this.tileSize,pixelPosMatrix:c,transform:n,params:a,queryPadding:this.queryPadding*l},e,t,i):{}}querySourceFeatures(e,i){const r=this.latestFeatureIndex;if(!r||!r.rawTileData)return;const o=r.loadVTLayers(),s=i&&i.sourceLayer?i.sourceLayer:"",a=o._geojsonTileLayer||o[s];if(!a)return;const n=t.a4(i&&i.filter),{z:l,x:c,y:h}=this.tileID.canonical,u={z:l,x:c,y:h};for(let i=0;ie)t=false;else if(i)if(this.expirationTime{this.remove(e,o);}),i)),this.data[r].push(o),this.order.push(r),this.order.length>this.max){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}has(e){return e.wrapped().key in this.data}getAndRemove(e){return this.has(e)?this._getAndRemoveByKey(e.wrapped().key):null}_getAndRemoveByKey(e){const t=this.data[e].shift();return t.timeout&&clearTimeout(t.timeout),0===this.data[e].length&&delete this.data[e],this.order.splice(this.order.indexOf(e),1),t.value}getByKey(e){const t=this.data[e];return t?t[0].value:null}get(e){return this.has(e)?this.data[e.wrapped().key][0].value:null}remove(e,t){if(!this.has(e))return this;const i=e.wrapped().key,r=undefined===t?0:this.data[i].indexOf(t),o=this.data[i][r];return this.data[i].splice(r,1),o.timeout&&clearTimeout(o.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(o.value),this.order.splice(this.order.indexOf(i),1),this}setMaxSize(e){for(this.max=e;this.order.length>this.max;){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}filter(e){const t=[];for(const i in this.data)for(const r of this.data[i])e(r.value)||t.push(r);for(const e of t)this.remove(e.value.tileID,e);}}class ne{constructor(){this.state={},this.stateChanges={},this.deletedStates={};}updateState(e,i,r){const o=String(i);if(this.stateChanges[e]=this.stateChanges[e]||{},this.stateChanges[e][o]=this.stateChanges[e][o]||{},t.e(this.stateChanges[e][o],r),null===this.deletedStates[e]){this.deletedStates[e]={};for(const t in this.state[e])t!==o&&(this.deletedStates[e][t]=null);}else if(this.deletedStates[e]&&null===this.deletedStates[e][o]){this.deletedStates[e][o]={};for(const t in this.state[e][o])r[t]||(this.deletedStates[e][o][t]=null);}else for(const t in r)this.deletedStates[e]&&this.deletedStates[e][o]&&null===this.deletedStates[e][o][t]&&delete this.deletedStates[e][o][t];}removeFeatureState(e,t,i){if(null===this.deletedStates[e])return;const r=String(t);if(this.deletedStates[e]=this.deletedStates[e]||{},i&&undefined!==t)null!==this.deletedStates[e][r]&&(this.deletedStates[e][r]=this.deletedStates[e][r]||{},this.deletedStates[e][r][i]=null);else if(undefined!==t)if(this.stateChanges[e]&&this.stateChanges[e][r])for(i in this.deletedStates[e][r]={},this.stateChanges[e][r])this.deletedStates[e][r][i]=null;else this.deletedStates[e][r]=null;else this.deletedStates[e]=null;}getState(e,i){const r=String(i),o=t.e({},(this.state[e]||{})[r],(this.stateChanges[e]||{})[r]);if(null===this.deletedStates[e])return {};if(this.deletedStates[e]){const t=this.deletedStates[e][i];if(null===t)return {};for(const e in t)delete o[e];}return o}initializeTileState(e,t){e.setFeatureState(this.state,t);}coalesceChanges(e,i){const r={};for(const e in this.stateChanges){this.state[e]=this.state[e]||{};const i={};for(const r in this.stateChanges[e])this.state[e][r]||(this.state[e][r]={}),t.e(this.state[e][r],this.stateChanges[e][r]),i[r]=this.state[e][r];r[e]=i;}for(const e in this.deletedStates){this.state[e]=this.state[e]||{};const i={};if(null===this.deletedStates[e])for(const t in this.state[e])i[t]={},this.state[e][t]={};else for(const t in this.deletedStates[e]){if(null===this.deletedStates[e][t])this.state[e][t]={};else for(const i of Object.keys(this.deletedStates[e][t]))delete this.state[e][t][i];i[t]=this.state[e][t];}r[e]=r[e]||{},t.e(r[e],i);}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(r).length)for(const t in e)e[t].setFeatureState(r,i);}}function le(e,t,i){const r=t.intersectsFrustum(e);if(!i)return r;const o=t.intersectsPlane(i);return 0===r||0===o?0:2===r&&2===o?2:1}function ce(e,i,r,o,s){let a=e;const n=Math.atan(i/r),l=Math.hypot(i,r);return a=e+t.a8(o/l/Math.max(.5,Math.cos(t.aa(s/2)))),a+=1*t.a8(Math.cos(n))/2,a+=t.ab(e-a,-0,0),a}function he(e,i){const r=(i.roundZoom?Math.round:Math.floor)(e.zoom+t.a8(e.tileSize/i.tileSize));return Math.max(0,r)}function ue(e,i){const r=e.getCameraFrustum(),o=e.getClippingPlane(),s=e.screenPointToMercatorCoordinate(e.getCameraPoint()),a=t.Y.fromLngLat(e.center,e.elevation);s.z=a.z+Math.cos(e.pitchInRadians)*e.cameraToCenterDistance/e.worldSize;const n=e.getCoveringTilesDetailsProvider(),l=n.allowVariableZoom(e,i),c=he(e,i),h=i.minzoom||0,u=undefined!==i.maxzoom?i.maxzoom:e.maxZoom,d=Math.min(Math.max(0,c),u),_=Math.pow(2,d),p=[_*s.x,_*s.y,0],m=[_*a.x,_*a.y,0],f=Math.hypot(a.x-s.x,a.y-s.y),g=Math.abs(a.z-s.z),v=Math.hypot(f,g),x=e=>({zoom:0,x:0,y:0,wrap:e,fullyVisible:false}),b=[],y=[];if(e.renderWorldCopies&&n.allowWorldCopies())for(let e=1;e<=3;e++)b.push(x(-e)),b.push(x(e));for(b.push(x(0));b.length>0;){const _=b.pop(),f=_.x,x=_.y;let w=_.fullyVisible;const T={x:f,y:x,z:_.zoom},P=n.getTileAABB(T,_.wrap,e.elevation,i);if(!w){const e=le(r,P,o);if(0===e)continue;w=2===e;}const C=n.distanceToTile2d(s.x,s.y,T,P);let I=c;l&&(I=(i.calculateTileZoom||ce)(e.zoom+t.a8(e.tileSize/i.tileSize),C,g,v,e.fov)),I=(i.roundZoom?Math.round:Math.floor)(I),I=Math.max(0,I);const E=Math.min(I,u);if(_.wrap=n.getWrap(a,T,_.wrap),_.zoom>=E){if(_.zoom>1),wrap:_.wrap,fullyVisible:w});}return y.sort(((e,t)=>e.distanceSq-t.distanceSq)).map((e=>e.tileID))}class de extends t.E{constructor(e,t,i){super(),this.id=e,this.dispatcher=i,this.on("data",(e=>this._dataHandler(e))),this.on("dataloading",(()=>{this._sourceErrored=false;})),this.on("error",(()=>{this._sourceErrored=this._source.loaded();})),this._source=((e,t,i,r)=>{const o=new(ee(t.type))(e,t,i,r);if(o.id!==e)throw new Error(`Expected Source id to be ${e} instead of ${o.id}`);return o})(e,t,i,this),this._tiles={},this._cache=new ae(0,(e=>this._unloadTile(e))),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new ne,this._didEmitContent=false,this._updated=false;}onAdd(e){this.map=e,this._maxTileCacheSize=e?e._maxTileCacheSize:null,this._maxTileCacheZoomLevels=e?e._maxTileCacheZoomLevels:null,this._source&&this._source.onAdd&&this._source.onAdd(e);}onRemove(e){this.clearTiles(),this._source&&this._source.onRemove&&this._source.onRemove(e);}loaded(){if(this._sourceErrored)return true;if(!this._sourceLoaded)return false;if(!this._source.loaded())return false;if(!(undefined===this.used&&undefined===this.usedForTerrain||this.used||this.usedForTerrain))return true;if(!this._updated)return false;for(const e in this._tiles){const t=this._tiles[e];if("loaded"!==t.state&&"errored"!==t.state)return false}return true}getSource(){return this._source}pause(){this._paused=true;}resume(){if(!this._paused)return;const e=this._shouldReloadOnResume;this._paused=false,this._shouldReloadOnResume=false,e&&this.reload(),this.transform&&this.update(this.transform,this.terrain);}_loadTile(e,i,r){return t._(this,undefined,undefined,(function*(){try{yield this._source.loadTile(e),this._tileLoaded(e,i,r);}catch(i){e.state="errored",404!==i.status?this._source.fire(new t.j(i,{tile:e})):this.update(this.transform,this.terrain);}}))}_unloadTile(e){this._source.unloadTile&&this._source.unloadTile(e);}_abortTile(e){this._source.abortTile&&this._source.abortTile(e),this._source.fire(new t.k("dataabort",{tile:e,coord:e.tileID,dataType:"source"}));}serialize(){return this._source.serialize()}prepare(e){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const t in this._tiles){const i=this._tiles[t];i.upload(e),i.prepare(this.map.style.imageManager);}}getIds(){return Object.values(this._tiles).map((e=>e.tileID)).sort(_e).map((e=>e.key))}getRenderableIds(e){const i=[];for(const t in this._tiles)this._isIdRenderable(t,e)&&i.push(this._tiles[t]);return e?i.sort(((e,i)=>{const r=e.tileID,o=i.tileID,s=new t.P(r.canonical.x,r.canonical.y)._rotate(-this.transform.bearingInRadians),a=new t.P(o.canonical.x,o.canonical.y)._rotate(-this.transform.bearingInRadians);return r.overscaledZ-o.overscaledZ||a.y-s.y||a.x-s.x})).map((e=>e.tileID.key)):i.map((e=>e.tileID)).sort(_e).map((e=>e.key))}hasRenderableParent(e){const t=this.findLoadedParent(e,0);return !!t&&this._isIdRenderable(t.tileID.key)}_isIdRenderable(e,t){return this._tiles[e]&&this._tiles[e].hasData()&&!this._coveredTiles[e]&&(t||!this._tiles[e].holdingForFade())}reload(e){if(this._paused)this._shouldReloadOnResume=true;else {this._cache.reset();for(const t in this._tiles)(e||"errored"!==this._tiles[t].state)&&this._reloadTile(t,"reloading");}}_reloadTile(e,i){return t._(this,undefined,undefined,(function*(){const t=this._tiles[e];t&&("loading"!==t.state&&(t.state=i),yield this._loadTile(t,e,i));}))}_tileLoaded(e,i,r){e.timeAdded=a.now(),"expired"===r&&(e.refreshedUponExpiration=true),this._setTileReloadTimer(i,e),"raster-dem"===this.getSource().type&&e.dem&&this._backfillDEM(e),this._state.initializeTileState(e,this.map?this.map.painter:null),e.aborted||this._source.fire(new t.k("data",{dataType:"source",tile:e,coord:e.tileID}));}_backfillDEM(e){const t=this.getRenderableIds();for(let r=0;r1||(Math.abs(i)>1&&(1===Math.abs(i+o)?i+=o:1===Math.abs(i-o)&&(i-=o)),t.dem&&e.dem&&(e.dem.backfillBorder(t.dem,i,r),e.neighboringTiles&&e.neighboringTiles[s]&&(e.neighboringTiles[s].backfilled=true)));}}getTile(e){return this.getTileByID(e.key)}getTileByID(e){return this._tiles[e]}_retainLoadedChildren(e,t,i,r){for(const o in this._tiles){let s=this._tiles[o];if(r[o]||!s.hasData()||s.tileID.overscaledZ<=t||s.tileID.overscaledZ>i)continue;let a=s.tileID;for(;s&&s.tileID.overscaledZ>t+1;){const e=s.tileID.scaledTo(s.tileID.overscaledZ-1);s=this._tiles[e.key],s&&s.hasData()&&(a=e);}let n=a;for(;n.overscaledZ>t;)if(n=n.scaledTo(n.overscaledZ-1),e[n.key]||e[n.canonical.key]){r[a.key]=a;break}}}findLoadedParent(e,t){if(e.key in this._loadedParentTiles){const i=this._loadedParentTiles[e.key];return i&&i.tileID.overscaledZ>=t?i:null}for(let i=e.overscaledZ-1;i>=t;i--){const t=e.scaledTo(i),r=this._getLoadedTile(t);if(r)return r}}findLoadedSibling(e){return this._getLoadedTile(e)}_getLoadedTile(e){const t=this._tiles[e.key];return t&&t.hasData()?t:this._cache.getByKey(e.wrapped().key)}updateCacheSize(e){const i=Math.ceil(e.width/this._source.tileSize)+1,r=Math.ceil(e.height/this._source.tileSize)+1,o=Math.floor(i*r*(null===this._maxTileCacheZoomLevels?t.a.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),s="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,o):o;this._cache.setMaxSize(s);}handleWrapJump(e){const t=Math.round((e-(undefined===this._prevLng?e:this._prevLng))/360);if(this._prevLng=e,t){const e={};for(const i in this._tiles){const r=this._tiles[i];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+t),e[r.tileID.key]=r;}this._tiles=e;for(const e in this._timers)clearTimeout(this._timers[e]),delete this._timers[e];for(const e in this._tiles)this._setTileReloadTimer(e,this._tiles[e]);}}_updateCoveredAndRetainedTiles(e,t,i,r,o,s){const n={},l={},c=Object.keys(e),h=a.now();for(const i of c){const r=e[i],o=this._tiles[i];if(!o||0!==o.fadeEndTime&&o.fadeEndTime<=h)continue;const s=this.findLoadedParent(r,t),a=this.findLoadedSibling(r),c=s||a||null;c&&(this._addTile(c.tileID),n[c.tileID.key]=c.tileID),l[i]=r;}this._retainLoadedChildren(l,r,i,e);for(const t in n)e[t]||(this._coveredTiles[t]=true,e[t]=n[t]);if(s){const t={},i={};for(const e of o)this._tiles[e.key].hasData()?t[e.key]=e:i[e.key]=e;for(const r in i){const o=i[r].children(this._source.maxzoom);this._tiles[o[0].key]&&this._tiles[o[1].key]&&this._tiles[o[2].key]&&this._tiles[o[3].key]&&(t[o[0].key]=e[o[0].key]=o[0],t[o[1].key]=e[o[1].key]=o[1],t[o[2].key]=e[o[2].key]=o[2],t[o[3].key]=e[o[3].key]=o[3],delete i[r]);}for(const r in i){const o=i[r],s=this.findLoadedParent(o,this._source.minzoom),a=this.findLoadedSibling(o),n=s||a||null;if(n){t[n.tileID.key]=e[n.tileID.key]=n.tileID;for(const e in t)t[e].isChildOf(n.tileID)&&delete t[e];}}for(const e in this._tiles)t[e]||(this._coveredTiles[e]=true);}}update(e,i){if(!this._sourceLoaded||this._paused)return;let r;this.transform=e,this.terrain=i,this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used||this.usedForTerrain?this._source.tileID?r=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((e=>new t.S(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y))):(r=ue(e,{tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:i,calculateTileZoom:this._source.calculateTileZoom}),this._source.hasTile&&(r=r.filter((e=>this._source.hasTile(e))))):r=[];const o=he(e,this._source),s=Math.max(o-de.maxOverzooming,this._source.minzoom),a=Math.max(o+de.maxUnderzooming,this._source.minzoom);if(this.usedForTerrain){const e={};for(const t of r)if(t.canonical.z>this._source.minzoom){const i=t.scaledTo(t.canonical.z-1);e[i.key]=i;const r=t.scaledTo(Math.max(this._source.minzoom,Math.min(t.canonical.z,5)));e[r.key]=r;}r=r.concat(Object.values(e));}const n=0===r.length&&!this._updated&&this._didEmitContent;this._updated=true,n&&this.fire(new t.k("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));const l=this._updateRetainedTiles(r,o);pe(this._source.type)&&this._updateCoveredAndRetainedTiles(l,s,a,o,r,i);for(const e in l)this._tiles[e].clearFadeHold();const c=t.ac(this._tiles,l);for(const e of c){const t=this._tiles[e];t.hasSymbolBuckets&&!t.holdingForFade()?t.setHoldDuration(this.map._fadeDuration):t.hasSymbolBuckets&&!t.symbolFadeFinished()||this._removeTile(e);}this._updateLoadedParentTileCache(),this._updateLoadedSiblingTileCache();}releaseSymbolFadeTiles(){for(const e in this._tiles)this._tiles[e].holdingForFade()&&this._removeTile(e);}_updateRetainedTiles(e,t){var i;const r={},o={},s=Math.max(t-de.maxOverzooming,this._source.minzoom),a=Math.max(t+de.maxUnderzooming,this._source.minzoom),n={};for(const i of e){const e=this._addTile(i);r[i.key]=i,e.hasData()||tthis._source.maxzoom){const e=a.children(this._source.maxzoom)[0],t=this.getTile(e);if(t&&t.hasData()){r[e.key]=e;continue}}else {const e=a.children(this._source.maxzoom);if(r[e[0].key]&&r[e[1].key]&&r[e[2].key]&&r[e[3].key])continue}let n=e.wasRequested();for(let t=a.overscaledZ-1;t>=s;--t){const s=a.scaledTo(t);if(o[s.key])break;if(o[s.key]=true,e=this.getTile(s),!e&&n&&(e=this._addTile(s)),e){const t=e.hasData();if((t||!(null===(i=this.map)||undefined===i?undefined:i.cancelPendingTileRequestsWhileZooming)||n)&&(r[s.key]=s),n=e.wasRequested(),t)break}}}return r}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const e in this._tiles){const t=[];let i,r=this._tiles[e].tileID;for(;r.overscaledZ>0;){if(r.key in this._loadedParentTiles){i=this._loadedParentTiles[r.key];break}t.push(r.key);const e=r.scaledTo(r.overscaledZ-1);if(i=this._getLoadedTile(e),i)break;r=e;}for(const e of t)this._loadedParentTiles[e]=i;}}_updateLoadedSiblingTileCache(){this._loadedSiblingTiles={};for(const e in this._tiles){const t=this._tiles[e].tileID,i=this._getLoadedTile(t);this._loadedSiblingTiles[t.key]=i;}}_addTile(e){let i=this._tiles[e.key];if(i)return i;i=this._cache.getAndRemove(e),i&&(this._setTileReloadTimer(e.key,i),i.tileID=e,this._state.initializeTileState(i,this.map?this.map.painter:null),this._cacheTimers[e.key]&&(clearTimeout(this._cacheTimers[e.key]),delete this._cacheTimers[e.key],this._setTileReloadTimer(e.key,i)));const r=i;return i||(i=new se(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(i,e.key,i.state)),i.uses++,this._tiles[e.key]=i,r||this._source.fire(new t.k("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i}_setTileReloadTimer(e,t){e in this._timers&&(clearTimeout(this._timers[e]),delete this._timers[e]);const i=t.getExpiryTimeout();i&&(this._timers[e]=setTimeout((()=>{this._reloadTile(e,"expired"),delete this._timers[e];}),i));}_removeTile(e){const t=this._tiles[e];t&&(t.uses--,delete this._tiles[e],this._timers[e]&&(clearTimeout(this._timers[e]),delete this._timers[e]),t.uses>0||(t.hasData()&&"reloading"!==t.state?this._cache.add(t.tileID,t,t.getExpiryTimeout()):(t.aborted=true,this._abortTile(t),this._unloadTile(t))));}_dataHandler(e){const t=e.sourceDataType;"source"===e.dataType&&"metadata"===t&&(this._sourceLoaded=true),this._sourceLoaded&&!this._paused&&"source"===e.dataType&&"content"===t&&(this.reload(e.sourceDataChanged),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=true);}clearTiles(){this._shouldReloadOnResume=false,this._paused=false;for(const e in this._tiles)this._removeTile(e);this._cache.reset();}tilesIn(e,i,r){const o=[],s=this.transform;if(!s)return o;const a=r?s.getCameraQueryGeometry(e):e,n=e.map((e=>s.screenPointToMercatorCoordinate(e,this.terrain))),l=a.map((e=>s.screenPointToMercatorCoordinate(e,this.terrain))),c=this.getIds();let h=1/0,u=1/0,d=-1/0,_=-1/0;for(const e of l)h=Math.min(h,e.x),u=Math.min(u,e.y),d=Math.max(d,e.x),_=Math.max(_,e.y);for(let e=0;e=0&&f[1].y+m>=0){const e=n.map((e=>a.getTilePoint(e))),t=l.map((e=>a.getTilePoint(e)));o.push({tile:r,tileID:a,queryGeometry:e,cameraQueryGeometry:t,scale:p});}}return o}getVisibleCoordinates(e){const t=this.getRenderableIds(e).map((e=>this._tiles[e].tileID));return this.transform&&this.transform.populateCache(t),t}hasTransition(){if(this._source.hasTransition())return true;if(pe(this._source.type)){const e=a.now();for(const t in this._tiles)if(this._tiles[t].fadeEndTime>=e)return true}return false}setFeatureState(e,t,i){this._state.updateState(e=e||"_geojsonTileLayer",t,i);}removeFeatureState(e,t,i){this._state.removeFeatureState(e=e||"_geojsonTileLayer",t,i);}getFeatureState(e,t){return this._state.getState(e=e||"_geojsonTileLayer",t)}setDependencies(e,t,i){const r=this._tiles[e];r&&r.setDependencies(t,i);}reloadTilesForDependencies(e,t){for(const i in this._tiles)this._tiles[i].hasDependency(e,t)&&this._reloadTile(i,"reloading");this._cache.filter((i=>!i.hasDependency(e,t)));}}function _e(e,t){const i=Math.abs(2*e.wrap)-+(e.wrap<0),r=Math.abs(2*t.wrap)-+(t.wrap<0);return e.overscaledZ-t.overscaledZ||r-i||t.canonical.y-e.canonical.y||t.canonical.x-e.canonical.x}function pe(e){return "raster"===e||"image"===e||"video"===e}de.maxOverzooming=10,de.maxUnderzooming=3;class me{constructor(e,t){this.reset(e,t);}reset(e,t){this.points=e||[],this._distances=[0];for(let e=1;e0?(o-a)/n:0;return this.points[s].mult(1-l).add(this.points[i].mult(l))}}function fe(e,t){let i=true;return "always"===e||"never"!==e&&"never"!==t||(i=false),i}class ge{constructor(e,t,i){const r=this.boxCells=[],o=this.circleCells=[];this.xCellCount=Math.ceil(e/i),this.yCellCount=Math.ceil(t/i);for(let e=0;ethis.width||r<0||t>this.height)return [];const n=[];if(e<=0&&t<=0&&this.width<=i&&this.height<=r){if(o)return [{key:null,x1:e,y1:t,x2:i,y2:r}];for(let e=0;e0}hitTestCircle(e,t,i,r,o){const s=e-i,a=e+i,n=t-i,l=t+i;if(a<0||s>this.width||l<0||n>this.height)return false;const c=[];return this._forEachCell(s,n,a,l,this._queryCellCircle,c,{hitTest:true,overlapMode:r,circle:{x:e,y:t,radius:i},seenUids:{box:{},circle:{}}},o),c.length>0}_queryCell(e,t,i,r,o,s,a,n){const{seenUids:l,hitTest:c,overlapMode:h}=a,u=this.boxCells[o];if(null!==u){const o=this.bboxes;for(const a of u)if(!l.box[a]){l.box[a]=true;const u=4*a,d=this.boxKeys[a];if(e<=o[u+2]&&t<=o[u+3]&&i>=o[u+0]&&r>=o[u+1]&&(!n||n(d))&&(!c||!fe(h,d.overlapMode))&&(s.push({key:d,x1:o[u],y1:o[u+1],x2:o[u+2],y2:o[u+3]}),c))return true}}const d=this.circleCells[o];if(null!==d){const o=this.circles;for(const a of d)if(!l.circle[a]){l.circle[a]=true;const u=3*a,d=this.circleKeys[a];if(this._circleAndRectCollide(o[u],o[u+1],o[u+2],e,t,i,r)&&(!n||n(d))&&(!c||!fe(h,d.overlapMode))){const e=o[u],t=o[u+1],i=o[u+2];if(s.push({key:d,x1:e-i,y1:t-i,x2:e+i,y2:t+i}),c)return true}}}return false}_queryCellCircle(e,t,i,r,o,s,a,n){const{circle:l,seenUids:c,overlapMode:h}=a,u=this.boxCells[o];if(null!==u){const e=this.bboxes;for(const t of u)if(!c.box[t]){c.box[t]=true;const i=4*t,r=this.boxKeys[t];if(this._circleAndRectCollide(l.x,l.y,l.radius,e[i+0],e[i+1],e[i+2],e[i+3])&&(!n||n(r))&&!fe(h,r.overlapMode))return s.push(true),true}}const d=this.circleCells[o];if(null!==d){const e=this.circles;for(const t of d)if(!c.circle[t]){c.circle[t]=true;const i=3*t,r=this.circleKeys[t];if(this._circlesCollide(e[i],e[i+1],e[i+2],l.x,l.y,l.radius)&&(!n||n(r))&&!fe(h,r.overlapMode))return s.push(true),true}}}_forEachCell(e,t,i,r,o,s,a,n){const l=this._convertToXCellCoord(e),c=this._convertToYCellCoord(t),h=this._convertToXCellCoord(i),u=this._convertToYCellCoord(r);for(let d=l;d<=h;d++)for(let l=c;l<=u;l++)if(o.call(this,e,t,i,r,this.xCellCount*l+d,s,a,n))return}_convertToXCellCoord(e){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(e*this.xScale)))}_convertToYCellCoord(e){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(e*this.yScale)))}_circlesCollide(e,t,i,r,o,s){const a=r-e,n=o-t,l=i+s;return l*l>a*a+n*n}_circleAndRectCollide(e,t,i,r,o,s,a){const n=(s-r)/2,l=Math.abs(e-(r+n));if(l>n+i)return false;const c=(a-o)/2,h=Math.abs(t-(o+c));if(h>c+i)return false;if(l<=n||h<=c)return true;const u=l-n,d=h-c;return u*u+d*d<=i*i}}function ve(e,i,o){const s=t.H();if(!e){const{vecSouth:e,vecEast:t}=be(i),o=r();o[0]=t[0],o[1]=t[1],o[2]=e[0],o[3]=e[1],a=o,(d=(l=(n=o)[0])*(u=n[3])-(h=n[2])*(c=n[1]))&&(a[0]=u*(d=1/d),a[1]=-c*d,a[2]=-h*d,a[3]=l*d),s[0]=o[0],s[1]=o[1],s[4]=o[2],s[5]=o[3];}var a,n,l,c,h,u,d;return t.K(s,s,[1/o,1/o,1]),s}function xe(e,i,r,o){if(e){const e=t.H();if(!i){const{vecSouth:t,vecEast:i}=be(r);e[0]=i[0],e[1]=i[1],e[4]=t[0],e[5]=t[1];}return t.K(e,e,[o,o,1]),e}return r.pixelsToClipSpaceMatrix}function be(e){const i=Math.cos(e.rollInRadians),r=Math.sin(e.rollInRadians),o=Math.cos(e.pitchInRadians),s=Math.cos(e.bearingInRadians),a=Math.sin(e.bearingInRadians),n=t.ad();n[0]=-s*o*r-a*i,n[1]=-a*o*r+s*i;const l=t.ae(n);l<1e-9?t.af(n):t.ag(n,n,1/l);const c=t.ad();c[0]=s*o*i-a*r,c[1]=a*o*i+s*r;const h=t.ae(c);return h<1e-9?t.af(c):t.ag(c,c,1/h),{vecEast:c,vecSouth:n}}function ye(e,i,r,o){let s;o?(s=[e,i,o(e,i),1],t.al(s,s,r)):(s=[e,i,0,1],je(s,s,r));const a=s[3];return {point:new t.P(s[0]/a,s[1]/a),signedDistanceFromCamera:a,isOccluded:false}}function we(e,t){return .5+e/t*.5}function Te(e,t){return e.x>=-t[0]&&e.x<=t[0]&&e.y>=-t[1]&&e.y<=t[1]}function Pe(e,i,r,o,s,a,n,l,c,h,u,d,_){const p=r?e.textSizeData:e.iconSizeData,m=t.ah(p,i.transform.zoom),f=[256/i.width*2+1,256/i.height*2+1],g=r?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;g.clear();const v=e.lineVertexArray,x=r?e.text.placedSymbolArray:e.icon.placedSymbolArray,b=i.transform.width/i.transform.height;let y=false;for(let r=0;rMath.abs(r.x-i.x)*o?{useVertical:true}:(e===t.ai.vertical?i.yr.x)?{needsFlipping:true}:null}function Ee(e){const{projectionContext:i,pitchedLabelPlaneMatrixInverse:r,symbol:o,fontSize:s,flip:a,keepUpright:n,glyphOffsetArray:l,dynamicLayoutVertexArray:c,aspectRatio:h,rotateToLine:u}=e,d=s/24,_=o.lineOffsetX*d,p=o.lineOffsetY*d;let m;if(o.numGlyphs>1){const e=o.glyphStartIndex+o.numGlyphs,t=o.lineStartIndex,s=o.lineStartIndex+o.lineLength,c=Ce(d,l,_,p,a,o,u,i);if(!c)return {notEnoughRoom:true};const f=De(c.first.point.x,c.first.point.y,i,r),g=De(c.last.point.x,c.last.point.y,i,r);if(n&&!a){const e=Ie(o.writingMode,f,g,h);if(e)return e}m=[c.first];for(let r=o.glyphStartIndex+1;r0?n.point:Me(i.tileAnchorPoint,a,e,1,i),c=De(e.x,e.y,i,r),u=De(l.x,l.y,i,r),d=Ie(o.writingMode,c,u,h);if(d)return d}const e=ke(d*l.getoffsetX(o.glyphStartIndex),_,p,a,o.segment,o.lineStartIndex,o.lineStartIndex+o.lineLength,i,u);if(!e||i.projectionCache.anyProjectionOccluded)return {notEnoughRoom:true};m=[e];}for(const e of m)t.ak(c,e.point,e.angle);return {}}function Me(e,t,i,r,o){const s=e.add(e.sub(t)._unit()),a=Re(s.x,s.y,o).point,n=i.sub(a);return i.add(n._mult(r/n.mag()))}function Se(e,i,r){const o=i.projectionCache;if(o.projections[e])return o.projections[e];const s=new t.P(i.lineVertexArray.getx(e),i.lineVertexArray.gety(e)),a=Re(s.x,s.y,i);if(a.signedDistanceFromCamera>0)return o.projections[e]=a.point,o.anyProjectionOccluded=o.anyProjectionOccluded||a.isOccluded,a.point;const n=e-r.direction;return Me(0===r.distanceFromAnchor?i.tileAnchorPoint:new t.P(i.lineVertexArray.getx(n),i.lineVertexArray.gety(n)),s,r.previousVertex,r.absOffsetX-r.distanceFromAnchor+1,i)}function Re(e,t,i){const r=e+i.translation[0],o=t+i.translation[1];let s;return i.pitchWithMap?(s=ye(r,o,i.pitchedLabelPlaneMatrix,i.getElevation),s.isOccluded=false):(s=i.transform.projectTileCoordinates(r,o,i.unwrappedTileID,i.getElevation),s.point.x=(.5*s.point.x+.5)*i.width,s.point.y=(.5*-s.point.y+.5)*i.height),s}function De(e,i,r,o){if(r.pitchWithMap){const s=[e,i,0,1];return t.al(s,s,o),r.transform.projectTileCoordinates(s[0]/s[3],s[1]/s[3],r.unwrappedTileID,r.getElevation).point}return {x:e/r.width*2-1,y:i/r.height*2-1}}function ze(e,t,i){return i.transform.projectTileCoordinates(e,t,i.unwrappedTileID,i.getElevation)}function Ae(e,t,i){return e._unit()._perp()._mult(t*i)}function Le(e,i,r,o,s,a,n,l,c){if(l.projectionCache.offsets[e])return l.projectionCache.offsets[e];const h=r.add(i);if(e+c.direction=s)return l.projectionCache.offsets[e]=h,h;const u=Se(e+c.direction,l,c),d=Ae(u.sub(r),n,c.direction),_=r.add(d),p=u.add(d);return l.projectionCache.offsets[e]=t.am(a,h,_,p)||h,l.projectionCache.offsets[e]}function ke(e,t,i,r,o,s,a,n,l){const c=r?e-t:e+t;let h=c>0?1:-1,u=0;r&&(h*=-1,u=Math.PI),h<0&&(u+=Math.PI);let d,_=h>0?s+o:s+o+1;n.projectionCache.cachedAnchorPoint?d=n.projectionCache.cachedAnchorPoint:(d=Re(n.tileAnchorPoint.x,n.tileAnchorPoint.y,n).point,n.projectionCache.cachedAnchorPoint=d);let p,m,f=d,g=d,v=0,x=0;const b=Math.abs(c),y=[];let w;for(;v+x<=b;){if(_+=h,_=a)return null;v+=x,g=f,m=p;const e={absOffsetX:b,direction:h,distanceFromAnchor:v,previousVertex:g};if(f=Se(_,n,e),0===i)y.push(g),w=f.sub(g);else {let t;const r=f.sub(g);t=0===r.mag()?Ae(Se(_+h,n,e).sub(f),i,h):Ae(r,i,h),m||(m=g.add(t)),p=Le(_,t,f,s,a,m,i,n,e),y.push(m),w=p.sub(m);}x=w.mag();}const T=w._mult((b-v)/x)._add(m||g),P=u+Math.atan2(f.y-g.y,f.x-g.x);return y.push(T),{point:T,angle:l?P:0,path:y}}const Fe=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function Be(e,t){for(let i=0;i=1;e--)_.push(a.path[e]);for(let e=1;ee.signedDistanceFromCamera<=0))?[]:e.map((e=>e.point));}let f=[];if(_.length>0){const e=_[0].clone(),i=_[0].clone();for(let t=1;t<_.length;t++)e.x=Math.min(e.x,_[t].x),e.y=Math.min(e.y,_[t].y),i.x=Math.max(i.x,_[t].x),i.y=Math.max(i.y,_[t].y);f=e.x>=r.x&&i.x<=o.x&&e.y>=r.y&&i.y<=o.y?[_]:i.xo.x||i.yo.y?[]:t.ao([_],r.x,r.y,o.x,o.y);}for(const t of f){s.reset(t,.25*i);let r=0;r=s.length<=.5*i?1:Math.ceil(s.paddedLength/p)+1;for(let t=0;t{const t=ye(e.x,e.y,r,i.getElevation),o=i.transform.projectTileCoordinates(t.point.x,t.point.y,i.unwrappedTileID,i.getElevation);return o.point.x=(.5*o.point.x+.5)*i.width,o.point.y=(.5*-o.point.y+.5)*i.height,o}))}(e,i);return function(e){let t=0,i=0,r=0,o=0;for(let s=0;si&&(i=o,t=r));return e.slice(t,t+i)}(r)}queryRenderedSymbols(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return {};const i=[];let r=1/0,o=1/0,s=-1/0,a=-1/0;for(const n of e){const e=new t.P(n.x+Oe,n.y+Oe);r=Math.min(r,e.x),o=Math.min(o,e.y),s=Math.max(s,e.x),a=Math.max(a,e.y),i.push(e);}const n=this.grid.query(r,o,s,a).concat(this.ignoredGrid.query(r,o,s,a)),l={},c={};for(const e of n){const r=e.key;if(undefined===l[r.bucketInstanceId]&&(l[r.bucketInstanceId]={}),l[r.bucketInstanceId][r.featureIndex])continue;const o=[new t.P(e.x1,e.y1),new t.P(e.x2,e.y1),new t.P(e.x2,e.y2),new t.P(e.x1,e.y2)];t.ap(i,o)&&(l[r.bucketInstanceId][r.featureIndex]=true,undefined===c[r.bucketInstanceId]&&(c[r.bucketInstanceId]=[]),c[r.bucketInstanceId].push(r.featureIndex));}return c}insertCollisionBox(e,t,i,r,o,s){(i?this.ignoredGrid:this.grid).insert({bucketInstanceId:r,featureIndex:o,collisionGroupID:s,overlapMode:t},e[0],e[1],e[2],e[3]);}insertCollisionCircles(e,t,i,r,o,s){const a=i?this.ignoredGrid:this.grid,n={bucketInstanceId:r,featureIndex:o,collisionGroupID:s,overlapMode:t};for(let t=0;t=this.screenRightBoundary||rthis.screenBottomBoundary}isInsideGrid(e,t,i,r){return i>=0&&e=0&&tthis.projectAndGetPerspectiveRatio(e.x,e.y,o,c,u)));S=e.some((e=>!e.isOccluded)),M=e.map((e=>new t.P(e.x,e.y)));}else S=true;return {box:t.ar(M),allPointsOccluded:!S}}}class Ze{constructor(e,t,i,r){this.opacity=e?Math.max(0,Math.min(1,e.opacity+(e.placed?t:-t))):r&&i?1:0,this.placed=i;}isHidden(){return 0===this.opacity&&!this.placed}}class Ge{constructor(e,t,i,r,o){this.text=new Ze(e?e.text:null,t,i,o),this.icon=new Ze(e?e.icon:null,t,r,o);}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class Ue{constructor(e,t,i){this.text=e,this.icon=t,this.skipFade=i;}}class Ve{constructor(e,t,i,r,o){this.bucketInstanceId=e,this.featureIndex=t,this.sourceLayerIndex=i,this.bucketIndex=r,this.tileID=o;}}class qe{constructor(e){this.crossSourceCollisions=e,this.maxGroupID=0,this.collisionGroups={};}get(e){if(this.crossSourceCollisions)return {ID:0,predicate:null};if(!this.collisionGroups[e]){const t=++this.maxGroupID;this.collisionGroups[e]={ID:t,predicate:e=>e.collisionGroupID===t};}return this.collisionGroups[e]}}function He(e,i,r,o,s){const{horizontalAlign:a,verticalAlign:n}=t.ay(e);return new t.P(-(a-.5)*i+o[0]*s,-(n-.5)*r+o[1]*s)}class We{constructor(e,t,i,r,o){this.transform=e.clone(),this.terrain=t,this.collisionIndex=new Ne(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=false,this.commitTime=0,this.fadeDuration=i,this.retainedQueryData={},this.collisionGroups=new qe(r),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=o,o&&(o.prevPlacement=undefined),this.placedOrientations={};}_getTerrainElevationFunc(e){const t=this.terrain;return t?(i,r)=>t.getElevation(e,i,r):null}getBucketParts(e,i,r,o){const s=r.getBucket(i),a=r.latestFeatureIndex;if(!s||!a||i.id!==s.layerIds[0])return;const n=r.collisionBoxArray,l=s.layers[0].layout,c=s.layers[0].paint,h=Math.pow(2,this.transform.zoom-r.tileID.overscaledZ),u=r.tileSize/t.X,d=r.tileID.toUnwrapped(),_="map"===l.get("text-rotation-alignment"),p=t.at(r,1,this.transform.zoom),m=t.au(this.collisionIndex.transform,r,c.get("text-translate"),c.get("text-translate-anchor")),f=t.au(this.collisionIndex.transform,r,c.get("icon-translate"),c.get("icon-translate-anchor")),g=ve(_,this.transform,p);this.retainedQueryData[s.bucketInstanceId]=new Ve(s.bucketInstanceId,a,s.sourceLayerIndex,s.index,r.tileID);const v={bucket:s,layout:l,translationText:m,translationIcon:f,unwrappedTileID:d,pitchedLabelPlaneMatrix:g,scale:h,textPixelRatio:u,holdingForFade:r.holdingForFade(),collisionBoxArray:n,partiallyEvaluatedTextSize:t.ah(s.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(s.sourceID)};if(o)for(const t of s.sortKeyRanges){const{sortKey:i,symbolInstanceStart:r,symbolInstanceEnd:o}=t;e.push({sortKey:i,symbolInstanceStart:r,symbolInstanceEnd:o,parameters:v});}else e.push({symbolInstanceStart:0,symbolInstanceEnd:s.symbolInstances.length,parameters:v});}attemptAnchorPlacement(e,i,r,o,s,a,n,l,c,h,u,d,_,p,m,f,g,v,x,b){const y=t.av[e.textAnchor],w=[e.textOffset0,e.textOffset1],T=He(y,r,o,w,s),P=this.collisionIndex.placeCollisionBox(i,d,l,c,h,n,a,f,u.predicate,x,T,b);if((!v||this.collisionIndex.placeCollisionBox(v,d,l,c,h,n,a,g,u.predicate,x,T,b).placeable)&&P.placeable){let e;if(this.prevPlacement&&this.prevPlacement.variableOffsets[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID].text&&(e=this.prevPlacement.variableOffsets[_.crossTileID].anchor),0===_.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[_.crossTileID]={textOffset:w,width:r,height:o,anchor:y,textBoxScale:s,prevAnchor:e},this.markUsedJustification(p,y,_,m),p.allowVerticalPlacement&&(this.markUsedOrientation(p,m,_),this.placedOrientations[_.crossTileID]=m),{shift:T,placedGlyphBoxes:P}}}placeLayerBucketPart(e,i,r){const{bucket:o,layout:s,translationText:a,translationIcon:n,unwrappedTileID:l,pitchedLabelPlaneMatrix:c,textPixelRatio:h,holdingForFade:u,collisionBoxArray:d,partiallyEvaluatedTextSize:_,collisionGroup:p}=e.parameters,m=s.get("text-optional"),f=s.get("icon-optional"),g=t.aw(s,"text-overlap","text-allow-overlap"),v="always"===g,x=t.aw(s,"icon-overlap","icon-allow-overlap"),b="always"===x,y="map"===s.get("text-rotation-alignment"),w="map"===s.get("text-pitch-alignment"),T="none"!==s.get("icon-text-fit"),P="viewport-y"===s.get("symbol-z-order"),C=v&&(b||!o.hasIconData()||f),I=b&&(v||!o.hasTextData()||m);!o.collisionArrays&&d&&o.deserializeCollisionBoxes(d);const E=this.retainedQueryData[o.bucketInstanceId].tileID,M=this._getTerrainElevationFunc(E),S=this.transform.getFastPathSimpleProjectionMatrix(E),R=(e,d,b)=>{var P,R;if(i[e.crossTileID])return;if(u)return void(this.placements[e.crossTileID]=new Ue(false,false,false));let D=false,z=false,A=true,L=null,k={box:null,placeable:false,offscreen:null,occluded:false},F={box:null,placeable:false,offscreen:null},B=null,j=null,O=null,N=0,Z=0,G=0;d.textFeatureIndex?N=d.textFeatureIndex:e.useRuntimeCollisionCircles&&(N=e.featureIndex),d.verticalTextFeatureIndex&&(Z=d.verticalTextFeatureIndex);const U=d.textBox;if(U){const i=i=>{let r=t.ai.horizontal;if(o.allowVerticalPlacement&&!i&&this.prevPlacement){const t=this.prevPlacement.placedOrientations[e.crossTileID];t&&(this.placedOrientations[e.crossTileID]=t,r=t,this.markUsedOrientation(o,r,e));}return r},s=(i,r)=>{if(o.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&d.verticalTextBox){for(const e of o.writingModes)if(e===t.ai.vertical?(k=r(),F=k):k=i(),k&&k.placeable)break}else k=i();},c=e.textAnchorOffsetStartIndex,u=e.textAnchorOffsetEndIndex;if(u===c){const r=(t,i)=>{const r=this.collisionIndex.placeCollisionBox(t,g,h,E,l,w,y,a,p.predicate,M,undefined,S);return r&&r.placeable&&(this.markUsedOrientation(o,i,e),this.placedOrientations[e.crossTileID]=i),r};s((()=>r(U,t.ai.horizontal)),(()=>{const i=d.verticalTextBox;return o.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&i?r(i,t.ai.vertical):{box:null,offscreen:null}})),i(k&&k.placeable);}else {let _=t.av[null===(R=null===(P=this.prevPlacement)||undefined===P?undefined:P.variableOffsets[e.crossTileID])||undefined===R?undefined:R.anchor];const m=(t,i,s)=>{const d=t.x2-t.x1,m=t.y2-t.y1,f=e.textBoxScale,v=T&&"never"===x?i:null;let b=null,P="never"===g?1:2,C="never";_&&P++;for(let i=0;im(U,d.iconBox,t.ai.horizontal)),(()=>{const i=d.verticalTextBox;return o.allowVerticalPlacement&&(!k||!k.placeable)&&e.numVerticalGlyphVertices>0&&i?m(i,d.verticalIconBox,t.ai.vertical):{box:null,occluded:true,offscreen:null}})),k&&(D=k.placeable,A=k.offscreen);const f=i(k&&k.placeable);if(!D&&this.prevPlacement){const t=this.prevPlacement.variableOffsets[e.crossTileID];t&&(this.variableOffsets[e.crossTileID]=t,this.markUsedJustification(o,t.anchor,e,f));}}}if(B=k,D=B&&B.placeable,A=B&&B.offscreen,e.useRuntimeCollisionCircles){const i=o.text.placedSymbolArray.get(e.centerJustifiedTextSymbolIndex),n=t.aj(o.textSizeData,_,i),h=s.get("text-padding");j=this.collisionIndex.placeCollisionCircles(g,i,o.lineVertexArray,o.glyphOffsetArray,n,l,c,r,w,p.predicate,e.collisionCircleDiameter,h,a,M),j.circles.length&&j.collisionDetected&&!r&&t.w("Collisions detected, but collision boxes are not shown"),D=v||j.circles.length>0&&!j.collisionDetected,A=A&&j.offscreen;}if(d.iconFeatureIndex&&(G=d.iconFeatureIndex),d.iconBox){const e=e=>this.collisionIndex.placeCollisionBox(e,x,h,E,l,w,y,n,p.predicate,M,T&&L?L:undefined,S);F&&F.placeable&&d.verticalIconBox?(O=e(d.verticalIconBox),z=O.placeable):(O=e(d.iconBox),z=O.placeable),A=A&&O.offscreen;}const V=m||0===e.numHorizontalGlyphVertices&&0===e.numVerticalGlyphVertices,q=f||0===e.numIconVertices;V||q?q?V||(z=z&&D):D=z&&D:z=D=z&&D;const H=z&&O.placeable;if(D&&B.placeable&&this.collisionIndex.insertCollisionBox(B.box,g,s.get("text-ignore-placement"),o.bucketInstanceId,F&&F.placeable&&Z?Z:N,p.ID),H&&this.collisionIndex.insertCollisionBox(O.box,x,s.get("icon-ignore-placement"),o.bucketInstanceId,G,p.ID),j&&D&&this.collisionIndex.insertCollisionCircles(j.circles,g,s.get("text-ignore-placement"),o.bucketInstanceId,N,p.ID),r&&this.storeCollisionData(o.bucketInstanceId,b,d,B,O,j),0===e.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");if(0===o.bucketInstanceId)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[e.crossTileID]=new Ue((D||C)&&!(null==B?undefined:B.occluded),(z||I)&&!(null==O?undefined:O.occluded),A||o.justReloaded),i[e.crossTileID]=true;};if(P){if(0!==e.symbolInstanceStart)throw new Error("bucket.bucketInstanceId should be 0");const t=o.getSortedSymbolIndexes(-this.transform.bearingInRadians);for(let e=t.length-1;e>=0;--e){const i=t[e];R(o.symbolInstances.get(i),o.collisionArrays[i],i);}}else for(let t=e.symbolInstanceStart;t=0&&(e.text.placedSymbolArray.get(t).crossTileID=s>=0&&t!==s?0:r.crossTileID);}markUsedOrientation(e,i,r){const o=i===t.ai.horizontal||i===t.ai.horizontalOnly?i:0,s=i===t.ai.vertical?i:0,a=[r.leftJustifiedTextSymbolIndex,r.centerJustifiedTextSymbolIndex,r.rightJustifiedTextSymbolIndex];for(const t of a)e.text.placedSymbolArray.get(t).placedOrientation=o;r.verticalPlacedTextSymbolIndex&&(e.text.placedSymbolArray.get(r.verticalPlacedTextSymbolIndex).placedOrientation=s);}commit(e){this.commitTime=e,this.zoomAtLastRecencyCheck=this.transform.zoom;const t=this.prevPlacement;let i=false;this.prevZoomAdjustment=t?t.zoomAdjustment(this.transform.zoom):0;const r=t?t.symbolFadeChange(e):1,o=t?t.opacities:{},s=t?t.variableOffsets:{},a=t?t.placedOrientations:{};for(const e in this.placements){const t=this.placements[e],s=o[e];s?(this.opacities[e]=new Ge(s,r,t.text,t.icon),i=i||t.text!==s.text.placed||t.icon!==s.icon.placed):(this.opacities[e]=new Ge(null,r,t.text,t.icon,t.skipFade),i=i||t.text||t.icon);}for(const e in o){const t=o[e];if(!this.opacities[e]){const o=new Ge(t,r,false,false);o.isHidden()||(this.opacities[e]=o,i=i||t.text.placed||t.icon.placed);}}for(const e in s)this.variableOffsets[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.variableOffsets[e]=s[e]);for(const e in a)this.placedOrientations[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.placedOrientations[e]=a[e]);if(t&&undefined===t.lastPlacementChangeTime)throw new Error("Last placement time for previous placement is not defined");i?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e);}updateLayerOpacities(e,t){const i={};for(const r of t){const t=r.getBucket(e);t&&r.latestFeatureIndex&&e.id===t.layerIds[0]&&this.updateBucketOpacities(t,r.tileID,i,r.collisionBoxArray);}}updateBucketOpacities(e,i,r,o){e.hasTextData()&&(e.text.opacityVertexArray.clear(),e.text.hasVisibleVertices=false),e.hasIconData()&&(e.icon.opacityVertexArray.clear(),e.icon.hasVisibleVertices=false),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexArray.clear(),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexArray.clear();const s=e.layers[0],a=s.layout,n=new Ge(null,0,false,false,true),l=a.get("text-allow-overlap"),c=a.get("icon-allow-overlap"),h=s._unevaluatedLayout.hasValue("text-variable-anchor")||s._unevaluatedLayout.hasValue("text-variable-anchor-offset"),u="map"===a.get("text-rotation-alignment"),d="map"===a.get("text-pitch-alignment"),_="none"!==a.get("icon-text-fit"),p=new Ge(null,0,l&&(c||!e.hasIconData()||a.get("icon-optional")),c&&(l||!e.hasTextData()||a.get("text-optional")),true);!e.collisionArrays&&o&&(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData())&&e.deserializeCollisionBoxes(o);const m=(e,t,i)=>{for(let r=0;r0,v=this.placedOrientations[o.crossTileID],x=v===t.ai.vertical,b=v===t.ai.horizontal||v===t.ai.horizontalOnly;if(s>0||a>0){const t=it(c.text);m(e.text,s,x?rt:t),m(e.text,a,b?rt:t);const i=c.text.isHidden();[o.rightJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.leftJustifiedTextSymbolIndex].forEach((t=>{t>=0&&(e.text.placedSymbolArray.get(t).hidden=i||x?1:0);})),o.verticalPlacedTextSymbolIndex>=0&&(e.text.placedSymbolArray.get(o.verticalPlacedTextSymbolIndex).hidden=i||b?1:0);const r=this.variableOffsets[o.crossTileID];r&&this.markUsedJustification(e,r.anchor,o,v);const n=this.placedOrientations[o.crossTileID];n&&(this.markUsedJustification(e,"left",o,n),this.markUsedOrientation(e,n,o));}if(g){const t=it(c.icon),i=!(_&&o.verticalPlacedIconSymbolIndex&&x);o.placedIconSymbolIndex>=0&&(m(e.icon,o.numIconVertices,i?t:rt),e.icon.placedSymbolArray.get(o.placedIconSymbolIndex).hidden=c.icon.isHidden()),o.verticalPlacedIconSymbolIndex>=0&&(m(e.icon,o.numVerticalIconVertices,i?rt:t),e.icon.placedSymbolArray.get(o.verticalPlacedIconSymbolIndex).hidden=c.icon.isHidden());}const y=f&&f.has(i)?f.get(i):{text:null,icon:null};if(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()){const r=e.collisionArrays[i];if(r){let i=new t.P(0,0);if(r.textBox||r.verticalTextBox){let t=true;if(h){const e=this.variableOffsets[l];e?(i=He(e.anchor,e.width,e.height,e.textOffset,e.textBoxScale),u&&i._rotate(d?-this.transform.bearingInRadians:this.transform.bearingInRadians)):t=false;}if(r.textBox||r.verticalTextBox){let o;r.textBox&&(o=x),r.verticalTextBox&&(o=b),Xe(e.textCollisionBox.collisionVertexArray,c.text.placed,!t||o,y.text,i.x,i.y);}}if(r.iconBox||r.verticalIconBox){const t=Boolean(!b&&r.verticalIconBox);let o;r.iconBox&&(o=t),r.verticalIconBox&&(o=!t),Xe(e.iconCollisionBox.collisionVertexArray,c.icon.placed,o,y.icon,_?i.x:0,_?i.y:0);}}}}if(e.sortFeatures(-this.transform.bearingInRadians),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),e.hasIconData()&&e.icon.opacityVertexBuffer&&e.icon.opacityVertexBuffer.updateData(e.icon.opacityVertexArray),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexBuffer&&e.iconCollisionBox.collisionVertexBuffer.updateData(e.iconCollisionBox.collisionVertexArray),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexBuffer&&e.textCollisionBox.collisionVertexBuffer.updateData(e.textCollisionBox.collisionVertexArray),e.text.opacityVertexArray.length!==e.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${e.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${e.text.layoutVertexArray.length}) / 4`);if(e.icon.opacityVertexArray.length!==e.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${e.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${e.icon.layoutVertexArray.length}) / 4`);e.bucketInstanceId in this.collisionCircleArrays&&(e.collisionCircleArray=this.collisionCircleArrays[e.bucketInstanceId],delete this.collisionCircleArrays[e.bucketInstanceId]);}symbolFadeChange(e){return 0===this.fadeDuration?1:(e-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(e){return Math.max(0,(this.transform.zoom-e)/1.5)}hasTransitions(e){return this.stale||e-this.lastPlacementChangeTimee}setStale(){this.stale=true;}}function Xe(e,t,i,r,o,s){r&&0!==r.length||(r=[0,0,0,0]);const a=r[0]-Oe,n=r[1]-Oe,l=r[2]-Oe,c=r[3]-Oe;e.emplaceBack(t?1:0,i?1:0,o||0,s||0,a,n),e.emplaceBack(t?1:0,i?1:0,o||0,s||0,l,n),e.emplaceBack(t?1:0,i?1:0,o||0,s||0,l,c),e.emplaceBack(t?1:0,i?1:0,o||0,s||0,a,c);}const $e=Math.pow(2,25),Ke=Math.pow(2,24),Ye=Math.pow(2,17),Je=Math.pow(2,16),Qe=Math.pow(2,9),et=Math.pow(2,8),tt=Math.pow(2,1);function it(e){if(0===e.opacity&&!e.placed)return 0;if(1===e.opacity&&e.placed)return 4294967295;const t=e.placed?1:0,i=Math.floor(127*e.opacity);return i*$e+t*Ke+i*Ye+t*Je+i*Qe+t*et+i*tt+t}const rt=0;class ot{constructor(e){this._sortAcrossTiles="viewport-y"!==e.layout.get("symbol-z-order")&&!e.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];}continuePlacement(e,t,i,r,o){const s=this._bucketParts;for(;this._currentTileIndexe.sortKey-t.sortKey)));this._currentPartIndex!this._forceFullPlacement&&a.now()-r>2;for(;this._currentPlacementIndex>=0;){const r=t[e[this._currentPlacementIndex]],s=this.placement.collisionIndex.transform.zoom;if("symbol"===r.type&&(!r.minzoom||r.minzoom<=s)&&(!r.maxzoom||r.maxzoom>s)){if(this._inProgressLayer||(this._inProgressLayer=new ot(r)),this._inProgressLayer.continuePlacement(i[r.source],this.placement,this._showCollisionBoxes,r,o))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=true;}commit(e){return this.placement.commit(e),this.placement}}const at=512/t.X/2;class nt{constructor(e,i,r){this.tileID=e,this.bucketInstanceId=r,this._symbolsByKey={};const o=new Map;for(let e=0;e({x:Math.floor(e.anchorX*at),y:Math.floor(e.anchorY*at)}))),crossTileIDs:i.map((e=>e.crossTileID))};if(r.positions.length>128){const e=new t.az(r.positions.length,16,Uint16Array);for(const{x:t,y:i}of r.positions)e.add(t,i);e.finish(),delete r.positions,r.index=e;}this._symbolsByKey[e]=r;}}getScaledCoordinates(e,i){const{x:r,y:o,z:s}=this.tileID.canonical,{x:a,y:n,z:l}=i.canonical,c=at/Math.pow(2,l-s),h=(n*t.X+e.anchorY)*c,u=o*t.X*at;return {x:Math.floor((a*t.X+e.anchorX)*c-r*t.X*at),y:Math.floor(h-u)}}findMatches(e,t,i){const r=this.tileID.canonical.ze))}}class lt{constructor(){this.maxCrossTileID=0;}generate(){return ++this.maxCrossTileID}}class ct{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;}handleWrapJump(e){const t=Math.round((e-this.lng)/360);if(0!==t)for(const e in this.indexes){const i=this.indexes[e],r={};for(const e in i){const o=i[e];o.tileID=o.tileID.unwrapTo(o.tileID.wrap+t),r[o.tileID.key]=o;}this.indexes[e]=r;}this.lng=e;}addBucket(e,t,i){if(this.indexes[e.overscaledZ]&&this.indexes[e.overscaledZ][e.key]){if(this.indexes[e.overscaledZ][e.key].bucketInstanceId===t.bucketInstanceId)return false;this.removeBucketCrossTileIDs(e.overscaledZ,this.indexes[e.overscaledZ][e.key]);}for(let e=0;ee.overscaledZ)for(const i in o){const s=o[i];s.tileID.isChildOf(e)&&s.findMatches(t.symbolInstances,e,r);}else {const s=o[e.scaledTo(Number(i)).key];s&&s.findMatches(t.symbolInstances,e,r);}}for(let e=0;e{t[e]=true;}));for(const e in this.layerIndexes)t[e]||delete this.layerIndexes[e];}}var ut="void main() {fragColor=vec4(1.0);}";const dt={prelude:_t("#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nout highp vec4 fragColor;","#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}mat3 rotationMatrixFromAxisAngle(vec3 u,float angle) {float c=cos(angle);float s=sin(angle);float c2=1.0-c;return mat3(u.x*u.x*c2+ c,u.x*u.y*c2-u.z*s,u.x*u.z*c2+u.y*s,u.y*u.x*c2+u.z*s,u.y*u.y*c2+ c,u.y*u.z*c2-u.x*s,u.z*u.x*c2-u.y*s,u.z*u.y*c2+u.x*s,u.z*u.z*c2+ c\n);}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\n#ifdef GLOBE\nif ((pos.y <-32767.5) || (pos.y > 32766.5)) {return 0.0;}\n#endif\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}const float PI=3.141592653589793;uniform mat4 u_projection_matrix;"),projectionMercator:_t("","float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}"),projectionGlobe:_t("","#define GLOBE_RADIUS 6371008.8\nuniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos\n);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float spherical_y=2.0*atan(exp(PI-(mercator_pos_y*PI*2.0)))-PI*0.5;return cos(spherical_y);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY); \nif (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 translatedPos,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*translatedPos;vec2 spherical;spherical.x=mercator_pos.x*PI*2.0+PI;spherical.y=2.0*atan(exp(PI-(mercator_pos.y*PI*2.0)))-PI*0.5;float len=cos(spherical.y);vec3 pos=vec3(sin(spherical.x)*len,sin(spherical.y),cos(spherical.x)*len\n);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeComputeClippingZ(vec3 spherePos) {return (1.0-(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphere(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphere(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphere(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphere(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}"),background:_t("uniform vec4 u_color;uniform float u_opacity;void main() {fragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),backgroundPattern:_t("uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}"),circle:_t("in vec3 v_data;in float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);float antialiased_blur=v_data.z;float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));fragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);const float epsilon=0.5/255.0;if (fragColor.r < epsilon && fragColor.g < epsilon && fragColor.b < epsilon && fragColor.a < epsilon) {discard;}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;uniform vec2 u_translate;in vec2 a_pos;out vec3 v_data;out float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 pos_raw=a_pos+32768.0;vec2 extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);vec2 circle_center=floor(pos_raw/8.0)+u_translate;float ele=get_elevation(circle_center);v_visibility=calculate_visibility(projectTileWithElevation(circle_center,ele));if (u_pitch_with_map) {\n#ifdef GLOBE\nvec3 center_vector=projectToSphere(circle_center);\n#endif\nfloat angle_scale=u_globe_extrude_scale;vec2 corner_position=circle_center;if (u_scale_with_map) {angle_scale*=(radius+stroke_width);corner_position+=extrude*u_extrude_scale*(radius+stroke_width);} else {\n#ifdef GLOBE\nvec4 projected_center=interpolateProjection(circle_center,center_vector,ele);\n#else\nvec4 projected_center=projectTileWithElevation(circle_center,ele);\n#endif\ncorner_position+=extrude*u_extrude_scale*(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);angle_scale*=(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);}\n#ifdef GLOBE\nvec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);\n#else\ngl_Position=projectTileWithElevation(corner_position,ele);\n#endif\n} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),clippingMask:_t(ut,"in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),heatmap:_t("uniform highp float u_intensity;in vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);fragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;uniform highp float u_globe_extrude_scale;in vec2 a_pos;out vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 pos_raw=a_pos+32768.0;vec2 unscaled_extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 circle_center=floor(pos_raw/8.0);\n#ifdef GLOBE\nvec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphere(circle_center);vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);\n#else\ngl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));\n#endif\n}"),heatmapTexture:_t("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(0.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),collisionBox:_t("in float v_placed;in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}","in vec2 a_anchor_pos;in vec2 a_placed;in vec2 a_box_real;uniform vec2 u_pixel_extrude_scale;out float v_placed;out float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}"),collisionCircle:_t("in float v_radius;in vec2 v_extrude;in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);fragColor=color*alpha*opacity_t;}","in vec2 a_pos;in float a_radius;in vec2 a_flags;uniform vec2 u_viewport_size;out float v_radius;out vec2 v_extrude;out float v_collision;void main() {float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),debug:_t("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);fragColor=mix(u_color,overlay_color,overlay_color.a);}","in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}"),depth:_t(ut,"in vec2 a_pos;void main() {\n#ifdef GLOBE\ngl_Position=projectTileFor3D(a_pos,0.0);\n#else\ngl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);\n#endif\n}"),fill:_t("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\nfragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_fill_translate;in vec2 a_pos;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);}"),fillOutline:_t("in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=outline_color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillOutlinePattern:_t("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillPattern:_t("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),fillExtrusion:_t("in vec4 v_color;void main() {fragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\nout vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nfloat colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;vec3 normalForLighting=normal/16384.0;float directional=clamp(dot(normalForLighting,u_lightpos),0.0,1.0);\n#ifdef GLOBE\nmat3 rotMatrix=globeGetRotationMatrix(spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);\n#endif\ndirectional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),fillExtrusionPattern:_t("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;in vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);fragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\n#ifdef GLOBE\nout vec3 v_sphere_pos;\n#endif\nout vec2 v_pos_a;out vec2 v_pos_b;out vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nvec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,elevation*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),hillshadePrepare:_t("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/pow(2.0,exaggeration+(19.2562-u_zoom));fragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;in vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),hillshade:_t("uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\n#define PI 3.141592653589793\nvoid main() {vec4 pixel=texture(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);fragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),line:_t("uniform lowp float u_device_pixel_ratio;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp float v_linesofar;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),lineGradient:_t("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture(u_image,v_uv);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;in float a_uv_x;in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),linePattern:_t("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;in vec2 v_normal;in vec2 v_width2;in float v_linesofar;in float v_gamma_scale;in float v_width;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture(u_image,pos_a),texture(u_image,pos_b),u_fade);fragColor=color*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_linesofar;out float v_gamma_scale;out float v_width;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),lineSDF:_t("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture(u_image,v_tex_a).a;float sdfdist_b=texture(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;out vec2 v_normal;out vec2 v_width2;out vec2 v_tex_a;out vec2 v_tex_b;out float v_gamma_scale;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),raster:_t("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec2 v_pos0;in vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture(u_image0,v_pos0);vec4 color1=texture(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;uniform vec4 u_coords_top;uniform vec4 u_coords_bottom;in vec2 a_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {vec2 fractionalPos=a_pos/8192.0;vec2 position=mix(mix(u_coords_top.xy,u_coords_top.zw,fractionalPos.x),mix(u_coords_bottom.xy,u_coords_bottom.zw,fractionalPos.x),fractionalPos.y);gl_Position=projectTile(position,position);v_pos0=((fractionalPos-0.5)/u_buffer_scale)+0.5;\n#ifdef GLOBE\nif (a_pos.y <-32767.5) {v_pos0.y=0.0;}if (a_pos.y > 32766.5) {v_pos0.y=1.0;}\n#endif\nv_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),symbolIcon:_t("uniform sampler2D u_texture;in vec2 v_tex;in float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;fragColor=texture(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_tex;out float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}"),symbolSDF:_t("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;in vec2 v_data0;in vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_data0;out vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),symbolTextAndIcon:_t("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;in vec4 v_data0;in vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;fragColor=texture(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec4 v_data0;out vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}"),terrain:_t("uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;uniform bool u_is_globe_mode;in vec2 v_texture_pos;in float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);fragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {fragColor=surface_color;}}","in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_texture_pos;out float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,get_elevation(a_pos3d.xy)-ele_delta);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}"),terrainDepth:_t("in float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {fragColor=pack(v_depth);}","in vec3 a_pos3d;uniform float u_ele_delta;out float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}"),terrainCoords:_t("precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;in vec2 v_texture_pos;void main() {vec4 rgba=texture(u_texture,v_texture_pos);fragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}","in vec3 a_pos3d;uniform float u_ele_delta;out vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);}"),projectionErrorMeasurement:_t("in vec4 v_output_error_encoded;void main() {fragColor=v_output_error_encoded;}","in vec2 a_pos;uniform highp float u_input;uniform highp float u_output_expected;out vec4 v_output_error_encoded;void main() {float real_output=2.0*atan(exp(PI-(u_input*PI*2.0)))-PI*0.5;float error=real_output-u_output_expected;float abs_error=abs(error)*128.0;v_output_error_encoded.x=min(floor(abs_error*256.0),255.0)/255.0;abs_error-=v_output_error_encoded.x;v_output_error_encoded.y=min(floor(abs_error*65536.0),255.0)/255.0;abs_error-=v_output_error_encoded.x/255.0;v_output_error_encoded.z=min(floor(abs_error*16777216.0),255.0)/255.0;v_output_error_encoded.w=error >=0.0 ? 1.0 : 0.0;gl_Position=vec4(a_pos,0.0,1.0);}"),atmosphere:_t("in vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) {return vec4(0.0,0.0,0.0,1.0);}if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie)));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758\n);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}","in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}"),sky:_t("uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor=mix(fragColor,vec4(vec3(0.0),0.0),u_sky_blend);}","in vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}")};function _t(e,t){const i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,r=t.match(/in ([\w]+) ([\w]+)/g),o=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),s=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=s?s.concat(o):o,n={};return {fragmentSource:e=e.replace(i,((e,t,i,r,o)=>(n[o]=true,"define"===t?`\n#ifndef HAS_UNIFORM_u_${o}\nin ${i} ${r} ${o};\n#else\nuniform ${i} ${r} u_${o};\n#endif\n`:`\n#ifdef HAS_UNIFORM_u_${o}\n ${i} ${r} ${o} = u_${o};\n#endif\n`))),vertexSource:t=t.replace(i,((e,t,i,r,o)=>{const s="float"===r?"vec2":"vec4",a=o.match(/color/)?"color":s;return n[o]?"define"===t?`\n#ifndef HAS_UNIFORM_u_${o}\nuniform lowp float u_${o}_t;\nin ${i} ${s} a_${o};\nout ${i} ${r} ${o};\n#else\nuniform ${i} ${r} u_${o};\n#endif\n`:"vec4"===a?`\n#ifndef HAS_UNIFORM_u_${o}\n ${o} = a_${o};\n#else\n ${i} ${r} ${o} = u_${o};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${o}\n ${o} = unpack_mix_${a}(a_${o}, u_${o}_t);\n#else\n ${i} ${r} ${o} = u_${o};\n#endif\n`:"define"===t?`\n#ifndef HAS_UNIFORM_u_${o}\nuniform lowp float u_${o}_t;\nin ${i} ${s} a_${o};\n#else\nuniform ${i} ${r} u_${o};\n#endif\n`:"vec4"===a?`\n#ifndef HAS_UNIFORM_u_${o}\n ${i} ${r} ${o} = a_${o};\n#else\n ${i} ${r} ${o} = u_${o};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${o}\n ${i} ${r} ${o} = unpack_mix_${a}(a_${o}, u_${o}_t);\n#else\n ${i} ${r} ${o} = u_${o};\n#endif\n`})),staticAttributes:r,staticUniforms:a}}class pt{constructor(e,t,i){this.vertexBuffer=e,this.indexBuffer=t,this.segments=i;}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.vertexBuffer=null,this.indexBuffer=null,this.segments=null;}}var mt=t.aA([{name:"a_pos",type:"Int16",components:2}]);const ft="#define PROJECTION_MERCATOR",gt="mercator";class vt{constructor(){this._cachedMesh=null;}get name(){return "mercator"}get useSubdivision(){return false}get shaderVariantName(){return gt}get shaderDefine(){return ft}get shaderPreludeCode(){return dt.projectionMercator}get vertexShaderPreludeCode(){return dt.projectionMercator.vertexSource}get subdivisionGranularity(){return t.aB.noSubdivision}get useGlobeControls(){return false}get transitionState(){return 0}get latitudeErrorCorrectionRadians(){return 0}destroy(){}updateGPUdependent(e){}getMeshFromTileID(e,i,r,o,s){if(this._cachedMesh)return this._cachedMesh;const a=new t.aC;a.emplaceBack(0,0),a.emplaceBack(t.X,0),a.emplaceBack(0,t.X),a.emplaceBack(t.X,t.X);const n=e.createVertexBuffer(a,mt.members),l=t.aD.simpleSegment(0,0,4,2),c=new t.aE;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3);const h=e.createIndexBuffer(c);return this._cachedMesh=new pt(n,h,l),this._cachedMesh}recalculate(){}hasTransition(){return false}setErrorQueryLatitudeDegrees(e){}}function xt(e,i){const r=t.ab(i.lat,-t.aF,t.aF);return new t.P(t.O(i.lng)*e,t.Q(r)*e)}function bt(e,i){return new t.Y(i.x/e,i.y/e).toLngLat()}function yt(e){return e.cameraToCenterDistance*Math.min(.85*Math.tan(t.aa(90-e.pitch)),Math.tan(t.aa(89.25-e.pitch)))}function wt(e,i){const r=e.canonical,o=i/t.aG(r.z),s=r.x+Math.pow(2,r.z)*e.wrap,a=t.aq(new Float64Array(16));return t.J(a,a,[s*o,r.y*o,0]),t.K(a,a,[o/t.X,o/t.X,1]),a}function Tt(e,i,r,o,s){const a=t.Y.fromLngLat(e,i),n=s*t.aH(1,e.lat),l=n*Math.cos(t.aa(r)),c=Math.sqrt(n*n-l*l),h=c*Math.sin(t.aa(-o)),u=c*Math.cos(t.aa(-o));return new t.Y(a.x+h,a.y+u,a.z+l)}class Pt{constructor(e=0,t=0,i=0,r=0){if(isNaN(e)||e<0||isNaN(t)||t<0||isNaN(i)||i<0||isNaN(r)||r<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=e,this.bottom=t,this.left=i,this.right=r;}interpolate(e,i,r){return null!=i.top&&null!=e.top&&(this.top=t.y.number(e.top,i.top,r)),null!=i.bottom&&null!=e.bottom&&(this.bottom=t.y.number(e.bottom,i.bottom,r)),null!=i.left&&null!=e.left&&(this.left=t.y.number(e.left,i.left,r)),null!=i.right&&null!=e.right&&(this.right=t.y.number(e.right,i.right,r)),this}getCenter(e,i){const r=t.ab((this.left+e-this.right)/2,0,e),o=t.ab((this.top+i-this.bottom)/2,0,i);return new t.P(r,o)}equals(e){return this.top===e.top&&this.bottom===e.bottom&&this.left===e.left&&this.right===e.right}clone(){return new Pt(this.top,this.bottom,this.left,this.right)}toJSON(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function Ct(e,t){if(!e.renderWorldCopies||e.lngRange)return;const i=t.lng-e.center.lng;t.lng+=i>180?-360:i<-180?360:0;}function It(e){return Math.max(0,Math.floor(e))}class Et{constructor(e,i,r,o,s,a){this._callbacks=e,this._tileSize=512,this._renderWorldCopies=undefined===a||!!a,this._minZoom=i||0,this._maxZoom=r||22,this._minPitch=null==o?0:o,this._maxPitch=null==s?60:s,this.setMaxBounds(),this._width=0,this._height=0,this._center=new t.N(0,0),this._elevation=0,this._zoom=0,this._tileZoom=It(this._zoom),this._scale=t.aG(this._zoom),this._bearingInRadians=0,this._fovInRadians=.6435011087932844,this._pitchInRadians=0,this._rollInRadians=0,this._unmodified=true,this._edgeInsets=new Pt,this._minElevationForCurrentTile=0,this._autoCalculateNearFarZ=true;}apply(e,i,r){this._latRange=e.latRange,this._lngRange=e.lngRange,this._width=e.width,this._height=e.height,this._center=e.center,this._elevation=e.elevation,this._minElevationForCurrentTile=e.minElevationForCurrentTile,this._zoom=e.zoom,this._tileZoom=It(this._zoom),this._scale=t.aG(this._zoom),this._bearingInRadians=e.bearingInRadians,this._fovInRadians=e.fovInRadians,this._pitchInRadians=e.pitchInRadians,this._rollInRadians=e.rollInRadians,this._unmodified=e.unmodified,this._edgeInsets=new Pt(e.padding.top,e.padding.bottom,e.padding.left,e.padding.right),this._minZoom=e.minZoom,this._maxZoom=e.maxZoom,this._minPitch=e.minPitch,this._maxPitch=e.maxPitch,this._renderWorldCopies=e.renderWorldCopies,this._cameraToCenterDistance=e.cameraToCenterDistance,this._nearZ=e.nearZ,this._farZ=e.farZ,this._autoCalculateNearFarZ=!r&&e.autoCalculateNearFarZ,i&&this._constrain(),this._calcMatrices();}get pixelsToClipSpaceMatrix(){return this._pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._clipSpaceToPixelsMatrix}get minElevationForCurrentTile(){return this._minElevationForCurrentTile}setMinElevationForCurrentTile(e){this._minElevationForCurrentTile=e;}get tileSize(){return this._tileSize}get tileZoom(){return this._tileZoom}get scale(){return this._scale}get width(){return this._width}get height(){return this._height}get bearingInRadians(){return this._bearingInRadians}get lngRange(){return this._lngRange}get latRange(){return this._latRange}get pixelsToGLUnits(){return this._pixelsToGLUnits}get minZoom(){return this._minZoom}setMinZoom(e){this._minZoom!==e&&(this._minZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get maxZoom(){return this._maxZoom}setMaxZoom(e){this._maxZoom!==e&&(this._maxZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get minPitch(){return this._minPitch}setMinPitch(e){this._minPitch!==e&&(this._minPitch=e,this.setPitch(Math.max(this.pitch,e)));}get maxPitch(){return this._maxPitch}setMaxPitch(e){this._maxPitch!==e&&(this._maxPitch=e,this.setPitch(Math.min(this.pitch,e)));}get renderWorldCopies(){return this._renderWorldCopies}setRenderWorldCopies(e){undefined===e?e=true:null===e&&(e=false),this._renderWorldCopies=e;}get worldSize(){return this._tileSize*this._scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new t.P(this._width,this._height)}get bearing(){return this._bearingInRadians/Math.PI*180}setBearing(e){const i=t.aI(e,-180,180)*Math.PI/180;var o,s,a,n,l,c,h,u,d;this._bearingInRadians!==i&&(this._unmodified=false,this._bearingInRadians=i,this._calcMatrices(),this._rotationMatrix=r(),o=this._rotationMatrix,a=-this._bearingInRadians,n=(s=this._rotationMatrix)[0],l=s[1],c=s[2],h=s[3],u=Math.sin(a),d=Math.cos(a),o[0]=n*d+c*u,o[1]=l*d+h*u,o[2]=n*-u+c*d,o[3]=l*-u+h*d);}get rotationMatrix(){return this._rotationMatrix}get pitchInRadians(){return this._pitchInRadians}get pitch(){return this._pitchInRadians/Math.PI*180}setPitch(e){const i=t.ab(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitchInRadians!==i&&(this._unmodified=false,this._pitchInRadians=i,this._calcMatrices());}get rollInRadians(){return this._rollInRadians}get roll(){return this._rollInRadians/Math.PI*180}setRoll(e){const t=e/180*Math.PI;this._rollInRadians!==t&&(this._unmodified=false,this._rollInRadians=t,this._calcMatrices());}get fovInRadians(){return this._fovInRadians}get fov(){return t.aJ(this._fovInRadians)}setFov(e){e=t.ab(e,.1,150),this.fov!==e&&(this._unmodified=false,this._fovInRadians=t.aa(e),this._calcMatrices());}get zoom(){return this._zoom}setZoom(e){const i=this.getConstrained(this._center,e).zoom;this._zoom!==i&&(this._unmodified=false,this._zoom=i,this._tileZoom=Math.max(0,Math.floor(i)),this._scale=t.aG(i),this._constrain(),this._calcMatrices());}get center(){return this._center}setCenter(e){e.lat===this._center.lat&&e.lng===this._center.lng||(this._unmodified=false,this._center=e,this._constrain(),this._calcMatrices());}get elevation(){return this._elevation}setElevation(e){e!==this._elevation&&(this._elevation=e,this._constrain(),this._calcMatrices());}get padding(){return this._edgeInsets.toJSON()}setPadding(e){this._edgeInsets.equals(e)||(this._unmodified=false,this._edgeInsets.interpolate(this._edgeInsets,e,1),this._calcMatrices());}get centerPoint(){return this._edgeInsets.getCenter(this._width,this._height)}get pixelsPerMeter(){return this._pixelPerMeter}get unmodified(){return this._unmodified}get cameraToCenterDistance(){return this._cameraToCenterDistance}get nearZ(){return this._nearZ}get farZ(){return this._farZ}get autoCalculateNearFarZ(){return this._autoCalculateNearFarZ}overrideNearFarZ(e,t){this._autoCalculateNearFarZ=false,this._nearZ=e,this._farZ=t,this._calcMatrices();}clearNearFarZOverride(){this._autoCalculateNearFarZ=true,this._calcMatrices();}isPaddingEqual(e){return this._edgeInsets.equals(e)}interpolatePadding(e,t,i){this._unmodified=false,this._edgeInsets.interpolate(e,t,i),this._constrain(),this._calcMatrices();}resize(e,t,i=true){this._width=e,this._height=t,i&&this._constrain(),this._calcMatrices();}getMaxBounds(){return this._latRange&&2===this._latRange.length&&this._lngRange&&2===this._lngRange.length?new V([this._lngRange[0],this._latRange[0]],[this._lngRange[1],this._latRange[1]]):null}setMaxBounds(e){e?(this._lngRange=[e.getWest(),e.getEast()],this._latRange=[e.getSouth(),e.getNorth()],this._constrain()):(this._lngRange=null,this._latRange=[-t.aF,t.aF]);}getConstrained(e,t){return this._callbacks.getConstrained(e,t)}getCameraQueryGeometry(e,i){if(1===i.length)return [i[0],e];{let r=e.x,o=e.y,s=e.x,a=e.y;for(const e of i)r=Math.min(r,e.x),o=Math.min(o,e.y),s=Math.max(s,e.x),a=Math.max(a,e.y);return [new t.P(r,o),new t.P(s,o),new t.P(s,a),new t.P(r,a),new t.P(r,o)]}}_constrain(){if(!this.center||!this._width||!this._height||this._constraining)return;this._constraining=true;const e=this._unmodified,{center:t,zoom:i}=this.getConstrained(this.center,this.zoom);this.setCenter(t),this.setZoom(i),this._unmodified=e,this._constraining=false;}_calcMatrices(){if(this._width&&this._height){this._pixelsToGLUnits=[2/this._width,-2/this._height];let e=t.aq(new Float64Array(16));t.K(e,e,[this._width/2,-this._height/2,1]),t.J(e,e,[1,-1,0]),this._clipSpaceToPixelsMatrix=e,e=t.aq(new Float64Array(16)),t.K(e,e,[1,-1,1]),t.J(e,e,[-1,-1,0]),t.K(e,e,[2/this._width,2/this._height,1]),this._pixelsToClipSpaceMatrix=e,this._cameraToCenterDistance=.5/Math.tan(this.fovInRadians/2)*this._height;}this._callbacks.calcMatrices();}calculateCenterFromCameraLngLatAlt(e,i,r,o){const s=undefined!==r?r:this.bearing,a=o=undefined!==o?o:this.pitch,n=t.Y.fromLngLat(e,i),l=-Math.cos(t.aa(a)),c=Math.sin(t.aa(a)),h=c*Math.sin(t.aa(s)),u=-c*Math.cos(t.aa(s));let d=this.elevation;const _=i-d;let p;l*_>=0||Math.abs(l)<.1?(p=1e4,d=i+p*l):p=-_/l;let m,f,g=t.aK(1,n.y),v=0;do{if(v+=1,v>10)break;f=p/g,m=new t.Y(n.x+h*f,n.y+u*f),g=1/m.meterInMercatorCoordinateUnits();}while(Math.abs(p-f*g)>1e-12);return {center:m.toLngLat(),elevation:d,zoom:t.a8(this.height/2/Math.tan(this.fovInRadians/2)/f/this.tileSize)}}recalculateZoomAndCenter(e){if(this.elevation-e==0)return;const i=t.aH(1,this.center.lat)*this.worldSize,r=this.cameraToCenterDistance/i,o=t.Y.fromLngLat(this.center,this.elevation),s=Tt(this.center,this.elevation,this.pitch,this.bearing,r);this._elevation=e;const a=this.calculateCenterFromCameraLngLatAlt(s.toLngLat(),t.aK(s.z,o.y),this.bearing,this.pitch);this._elevation=a.elevation,this._center=a.center,this.setZoom(a.zoom);}getCameraPoint(){const e=Math.tan(this.pitchInRadians)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new t.P(e*Math.sin(this.rollInRadians),e*Math.cos(this.rollInRadians)))}getCameraAltitude(){return Math.cos(this.pitchInRadians)*this._cameraToCenterDistance/this._pixelPerMeter+this.elevation}getCameraLngLat(){const e=t.aH(1,this.center.lat)*this.worldSize;return Tt(this.center,this.elevation,this.pitch,this.bearing,this.cameraToCenterDistance/e).toLngLat()}getMercatorTileCoordinates(e){if(!e)return [0,0,1,1];const i=e.canonical.z>=0?1<this.max[0]||e.aabb.min[1]>this.max[1]||e.aabb.min[2]>this.max[2]||e.aabb.max[0]0?(t+=e[r]*this.min[r],i+=e[r]*this.max[r]):(i+=e[r]*this.min[r],t+=e[r]*this.max[r]);return t>=0?2:i<0?0:1}}class St{distanceToTile2d(e,t,i,r){const o=r.distanceX([e,t]),s=r.distanceY([e,t]);return Math.hypot(o,s)}getWrap(e,t,i){return i}getTileAABB(e,i,r,o){var s,a;let n=r,l=r;if(o.terrain){const c=new t.S(e.z,i,e.z,e.x,e.y),h=o.terrain.getMinMaxElevation(c);n=null!==(s=h.minElevation)&&undefined!==s?s:r,l=null!==(a=h.maxElevation)&&undefined!==a?a:r;}const c=1<o||e.padding.top>=.1}allowWorldCopies(){return true}recalculateCache(){}}class Rt{constructor(e,t,i){this.points=e,this.planes=t,this.aabb=i;}static fromInvProjectionMatrix(e,i=1,r=0){const o=Math.pow(2,r),s=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((r=>{const s=1/(r=t.al([],r,e))[3]/i*o;return t.aO(r,r,[s,s,1/r[3],s])})),a=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map((e=>{const i=t.aP([],s[e[0]],s[e[1]]),r=t.aP([],s[e[2]],s[e[1]]),o=t.aQ([],t.aR([],i,r)),a=-t.aS(o,s[e[1]]);return o.concat(a)})),n=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],l=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];for(const e of s)for(let t=0;t<3;t++)n[t]=Math.min(n[t],e[t]),l[t]=Math.max(l[t],e[t]);return new Rt(s,a,new Mt(n,l))}}class Dt{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=true){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}setTransitionState(e,t){}constructor(e,t,i,r,o){this._posMatrixCache=new Map,this._alignedPosMatrixCache=new Map,this._fogMatrixCacheF32=new Map,this._helper=new Et({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)},e,t,i,r,o),this._coveringTilesDetailsProvider=new St;}clone(){const e=new Dt;return e.apply(this),e}apply(e,t,i){this._helper.apply(e,t,i);}get cameraPosition(){return this._cameraPosition}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._viewProjMatrix}get inverseProjectionMatrix(){return this._invProjMatrix}get mercatorMatrix(){return this._mercatorMatrix}getVisibleUnwrappedCoordinates(e){const i=[new t.aT(0,e)];if(this._helper._renderWorldCopies){const r=this.screenPointToMercatorCoordinate(new t.P(0,0)),o=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,0)),s=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,this._helper._height)),a=this.screenPointToMercatorCoordinate(new t.P(0,this._helper._height)),n=Math.floor(Math.min(r.x,o.x,s.x,a.x)),l=Math.floor(Math.max(r.x,o.x,s.x,a.x)),c=1;for(let r=n-c;r<=l+c;r++)0!==r&&i.push(new t.aT(r,e));}return i}getCameraFrustum(){return Rt.fromInvProjectionMatrix(this._invViewProjMatrix,this.worldSize)}getClippingPlane(){return null}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(e){const t=this.screenPointToLocation(this.centerPoint,e),i=e?e.getElevationForLngLatZoom(t,this._helper._tileZoom):0;this._helper.recalculateZoomAndCenter(i);}setLocationAtPoint(e,i){const r=t.aH(this.elevation,this.center.lat),o=this.screenPointToMercatorCoordinateAtZ(i,r),s=this.screenPointToMercatorCoordinateAtZ(this.centerPoint,r),a=t.Y.fromLngLat(e),n=new t.Y(a.x-(o.x-s.x),a.y-(o.y-s.y));this.setCenter(null==n?undefined:n.toLngLat()),this._helper._renderWorldCopies&&this.setCenter(this.center.wrap());}locationToScreenPoint(e,i){return i?this.coordinatePoint(t.Y.fromLngLat(e),i.getElevationForLngLatZoom(e,this._helper._tileZoom),this._pixelMatrix3D):this.coordinatePoint(t.Y.fromLngLat(e))}screenPointToLocation(e,t){var i;return null===(i=this.screenPointToMercatorCoordinate(e,t))||undefined===i?undefined:i.toLngLat()}screenPointToMercatorCoordinate(e,t){if(t){const i=t.pointCoordinate(e);if(null!=i)return i}return this.screenPointToMercatorCoordinateAtZ(e)}screenPointToMercatorCoordinateAtZ(e,i){const r=i||0,o=[e.x,e.y,0,1],s=[e.x,e.y,1,1];t.al(o,o,this._pixelMatrixInverse),t.al(s,s,this._pixelMatrixInverse);const a=o[3],n=s[3],l=o[1]/a,c=s[1]/n,h=o[2]/a,u=s[2]/n,d=h===u?0:(r-h)/(u-h);return new t.Y(t.y.number(o[0]/a,s[0]/n,d)/this.worldSize,t.y.number(l,c,d)/this.worldSize,r)}coordinatePoint(e,i=0,r=this._pixelMatrix){const o=[e.x*this.worldSize,e.y*this.worldSize,i,1];return t.al(o,o,r),new t.P(o[0]/o[3],o[1]/o[3])}getBounds(){const e=Math.max(0,this._helper._height/2-yt(this));return (new V).extend(this.screenPointToLocation(new t.P(0,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,this._helper._height))).extend(this.screenPointToLocation(new t.P(0,this._helper._height)))}isPointOnMapSurface(e,t){return t?null!=t.pointCoordinate(e):e.y>this.height/2-yt(this)}calculatePosMatrix(e,i=false,r){var o;const s=null!==(o=e.key)&&undefined!==o?o:t.aU(e.wrap,e.canonical.z,e.canonical.z,e.canonical.x,e.canonical.y),a=i?this._alignedPosMatrixCache:this._posMatrixCache;if(a.has(s)){const e=a.get(s);return r?e.f32:e.f64}const n=wt(e,this.worldSize);t.L(n,i?this._alignedProjMatrix:this._viewProjMatrix,n);const l={f64:n,f32:new Float32Array(n)};return a.set(s,l),r?l.f32:l.f64}calculateFogMatrix(e){const i=e.key,r=this._fogMatrixCacheF32;if(r.has(i))return r.get(i);const o=wt(e,this.worldSize);return t.L(o,this._fogMatrix,o),r.set(i,new Float32Array(o)),r.get(i)}getConstrained(e,i){i=t.ab(+i,this.minZoom,this.maxZoom);const r={center:new t.N(e.lng,e.lat),zoom:i};let o=this._helper._lngRange;if(!this._helper._renderWorldCopies&&null===o){const e=180-1e-10;o=[-179.9999999999,e];}const s=this.tileSize*t.aG(r.zoom);let a=0,n=s,l=0,c=s,h=0,u=0;const{x:d,y:_}=this.size;if(this._helper._latRange){const e=this._helper._latRange;a=t.Q(e[1])*s,n=t.Q(e[0])*s,n-a<_&&(h=_/(n-a));}o&&(l=t.aI(t.O(o[0])*s,0,s),c=t.aI(t.O(o[1])*s,0,s),cn&&(g=n-e);}if(o){const e=(l+c)/2;let i=p;this._helper._renderWorldCopies&&(i=t.aI(p,e-s/2,e+s/2));const r=d/2;i-rc&&(f=c-r);}if(undefined!==f||undefined!==g){const e=new t.P(null!=f?f:p,null!=g?g:m);r.center=bt(s,e).wrap();}return r}calculateCenterFromCameraLngLatAlt(e,t,i,r){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,r)}_calculateNearFarZIfNeeded(e,i,r){if(!this._helper.autoCalculateNearFarZ)return;const o=Math.min(this.elevation,this.minElevationForCurrentTile,this.getCameraAltitude()-100),s=e-o*this._helper._pixelPerMeter/Math.cos(i),a=o<0?s:e,n=Math.PI/2+this.pitchInRadians,l=t.aa(this.fov)*(Math.abs(Math.cos(t.aa(this.roll)))*this.height+Math.abs(Math.sin(t.aa(this.roll)))*this.width)/this.height*(.5+r.y/this.height),c=Math.sin(l)*a/Math.sin(t.ab(Math.PI-n-l,.01,Math.PI-.01)),h=yt(this),u=Math.atan(h/this._helper.cameraToCenterDistance),d=t.aa(.75),_=u>d?2*u*(.5+r.y/(2*h)):d,p=Math.sin(_)*a/Math.sin(t.ab(Math.PI-n-_,.01,Math.PI-.01)),m=Math.min(c,p);this._helper._farZ=1.01*(Math.cos(Math.PI/2-i)*m+a),this._helper._nearZ=this._helper._height/50;}_calcMatrices(){if(!this._helper._height)return;const e=this.centerOffset,i=xt(this.worldSize,this.center),r=i.x,o=i.y;this._helper._pixelPerMeter=t.aH(1,this.center.lat)*this.worldSize;const s=t.aa(Math.min(this.pitch,89.25)),a=Math.max(this._helper.cameraToCenterDistance/2,this._helper.cameraToCenterDistance+this._helper._elevation*this._helper._pixelPerMeter/Math.cos(s));let n;this._calculateNearFarZIfNeeded(a,s,e),n=new Float64Array(16),t.aV(n,this.fovInRadians,this._helper._width/this._helper._height,this._helper._nearZ,this._helper._farZ),this._invProjMatrix=new Float64Array(16),t.an(this._invProjMatrix,n),n[8]=2*-e.x/this._helper._width,n[9]=2*e.y/this._helper._height,this._projectionMatrix=t.aW(n),t.K(n,n,[1,-1,1]),t.J(n,n,[0,0,-this._helper.cameraToCenterDistance]),t.aX(n,n,-this.rollInRadians),t.aY(n,n,this.pitchInRadians),t.aX(n,n,-this.bearingInRadians),t.J(n,n,[-r,-o,0]),this._mercatorMatrix=t.K([],n,[this.worldSize,this.worldSize,this.worldSize]),t.K(n,n,[1,1,this._helper._pixelPerMeter]),this._pixelMatrix=t.L(new Float64Array(16),this.clipSpaceToPixelsMatrix,n),t.J(n,n,[0,0,-this.elevation]),this._viewProjMatrix=n,this._invViewProjMatrix=t.an([],n);const l=[0,0,-1,1];t.al(l,l,this._invViewProjMatrix),this._cameraPosition=[l[0]/l[3],l[1]/l[3],l[2]/l[3]],this._fogMatrix=new Float64Array(16),t.aV(this._fogMatrix,this.fovInRadians,this.width/this.height,a,this._helper._farZ),this._fogMatrix[8]=2*-e.x/this.width,this._fogMatrix[9]=2*e.y/this.height,t.K(this._fogMatrix,this._fogMatrix,[1,-1,1]),t.J(this._fogMatrix,this._fogMatrix,[0,0,-this.cameraToCenterDistance]),t.aX(this._fogMatrix,this._fogMatrix,-this.rollInRadians),t.aY(this._fogMatrix,this._fogMatrix,this.pitchInRadians),t.aX(this._fogMatrix,this._fogMatrix,-this.bearingInRadians),t.J(this._fogMatrix,this._fogMatrix,[-r,-o,0]),t.K(this._fogMatrix,this._fogMatrix,[1,1,this._helper._pixelPerMeter]),t.J(this._fogMatrix,this._fogMatrix,[0,0,-this.elevation]),this._pixelMatrix3D=t.L(new Float64Array(16),this.clipSpaceToPixelsMatrix,n);const c=this._helper._width%2/2,h=this._helper._height%2/2,u=Math.cos(this.bearingInRadians),d=Math.sin(-this.bearingInRadians),_=r-Math.round(r)+u*c+d*h,p=o-Math.round(o)+u*h+d*c,m=new Float64Array(n);if(t.J(m,m,[_>.5?_-1:_,p>.5?p-1:p,0]),this._alignedProjMatrix=m,n=t.an(new Float64Array(16),this._pixelMatrix),!n)throw new Error("failed to invert matrix");this._pixelMatrixInverse=n,this._clearMatrixCaches();}_clearMatrixCaches(){this._posMatrixCache.clear(),this._alignedPosMatrixCache.clear(),this._fogMatrixCacheF32.clear();}maxPitchScaleFactor(){if(!this._pixelMatrixInverse)return 1;const e=this.screenPointToMercatorCoordinate(new t.P(0,0)),i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.al(i,i,this._pixelMatrix)[3]/this._helper.cameraToCenterDistance}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){const e=t.aH(1,this.center.lat)*this.worldSize;return Tt(this.center,this.elevation,this.pitch,this.bearing,this._helper.cameraToCenterDistance/e).toLngLat()}lngLatToCameraDepth(e,i){const r=t.Y.fromLngLat(e),o=[r.x*this.worldSize,r.y*this.worldSize,i,1];return t.al(o,o,this._viewProjMatrix),o[2]/o[3]}getProjectionData(e){const{overscaledTileID:i,aligned:r,applyTerrainMatrix:o}=e,s=this._helper.getMercatorTileCoordinates(i),a=i?this.calculatePosMatrix(i,r,true):null;let n;return n=i&&i.terrainRttPosMatrix32f&&o?i.terrainRttPosMatrix32f:a||t.aZ(),{mainMatrix:n,tileMercatorCoords:s,clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:n}}isLocationOccluded(e){return false}getPixelScale(){return 1}getCircleRadiusCorrection(){return 1}getPitchedTextCorrection(e,t,i){return 1}transformLightDirection(e){return t.aN(e)}getRayDirectionFromPixel(e){throw new Error("Not implemented.")}projectTileCoordinates(e,i,r,o){const s=this.calculatePosMatrix(r);let a;o?(a=[e,i,o(e,i),1],t.al(a,a,s)):(a=[e,i,0,1],je(a,a,s));const n=a[3];return {point:new t.P(a[0]/n,a[1]/n),signedDistanceFromCamera:n,isOccluded:false}}populateCache(e){for(const t of e)this.calculatePosMatrix(t);}getMatrixForModel(e,i){const r=t.Y.fromLngLat(e,i),o=r.meterInMercatorCoordinateUnits(),s=t.a_();return t.J(s,s,[r.x,r.y,r.z]),t.aX(s,s,Math.PI),t.aY(s,s,Math.PI/2),t.K(s,s,[-o,o,o]),s}getProjectionDataForCustomLayer(e=true){const i=new t.S(0,0,0,0,0),r=this.getProjectionData({overscaledTileID:i,applyGlobeMatrix:e}),o=wt(i,this.worldSize);t.L(o,this._viewProjMatrix,o),r.tileMercatorCoords=[0,0,1,1];const s=[t.X,t.X,this.worldSize/this._helper.pixelsPerMeter],a=t.a$();return t.K(a,o,s),r.fallbackMatrix=a,r.mainMatrix=a,r}getFastPathSimpleProjectionMatrix(e){return this.calculatePosMatrix(e)}}function zt(){t.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");}function At(e){if(e.useSlerp)if(e.k<1){const i=t.b0(e.startEulerAngles.roll,e.startEulerAngles.pitch,e.startEulerAngles.bearing),r=t.b0(e.endEulerAngles.roll,e.endEulerAngles.pitch,e.endEulerAngles.bearing),o=new Float64Array(4);t.b1(o,i,r,e.k);const s=t.b2(o);e.tr.setRoll(s.roll),e.tr.setPitch(s.pitch),e.tr.setBearing(s.bearing);}else e.tr.setRoll(e.endEulerAngles.roll),e.tr.setPitch(e.endEulerAngles.pitch),e.tr.setBearing(e.endEulerAngles.bearing);else e.tr.setRoll(t.y.number(e.startEulerAngles.roll,e.endEulerAngles.roll,e.k)),e.tr.setPitch(t.y.number(e.startEulerAngles.pitch,e.endEulerAngles.pitch,e.k)),e.tr.setBearing(t.y.number(e.startEulerAngles.bearing,e.endEulerAngles.bearing,e.k));}function Lt(e,i,r,o,s){const a=s.padding,n=xt(s.worldSize,r.getNorthWest()),l=xt(s.worldSize,r.getNorthEast()),c=xt(s.worldSize,r.getSouthEast()),h=xt(s.worldSize,r.getSouthWest()),u=t.aa(-o),d=n.rotate(u),_=l.rotate(u),p=c.rotate(u),m=h.rotate(u),f=new t.P(Math.max(d.x,_.x,m.x,p.x),Math.max(d.y,_.y,m.y,p.y)),g=new t.P(Math.min(d.x,_.x,m.x,p.x),Math.min(d.y,_.y,m.y,p.y)),v=f.sub(g),x=(s.width-(a.left+a.right+i.left+i.right))/v.x,b=(s.height-(a.top+a.bottom+i.top+i.bottom))/v.y;if(b<0||x<0)return void zt();const y=Math.min(t.a8(s.scale*Math.min(x,b)),e.maxZoom),w=t.P.convert(e.offset),T=new t.P((i.left-i.right)/2,(i.top-i.bottom)/2).rotate(t.aa(o)),P=w.add(T).mult(s.scale/t.aG(y));return {center:bt(s.worldSize,n.add(c).div(2).sub(P)),zoom:y,bearing:o}}class kt{get useGlobeControls(){return false}handlePanInertia(e,t){return {easingOffset:e,easingCenter:t.center}}handleMapControlsRollPitchBearingZoom(e,t){e.bearingDelta&&t.setBearing(t.bearing+e.bearingDelta),e.pitchDelta&&t.setPitch(t.pitch+e.pitchDelta),e.rollDelta&&t.setRoll(t.roll+e.rollDelta),e.zoomDelta&&t.setZoom(t.zoom+e.zoomDelta);}handleMapControlsPan(e,t,i){e.around.distSqr(t.centerPoint)<.01||t.setLocationAtPoint(i,e.around);}cameraForBoxAndBearing(e,t,i,r,o){return Lt(e,t,i,r,o)}handleJumpToCenterZoom(e,i){e.zoom!==(undefined!==i.zoom?+i.zoom:e.zoom)&&e.setZoom(+i.zoom),undefined!==i.center&&e.setCenter(t.N.convert(i.center));}handleEaseTo(e,i){const r=e.zoom,o=e.padding,s={roll:e.roll,pitch:e.pitch,bearing:e.bearing},a={roll:undefined===i.roll?e.roll:i.roll,pitch:undefined===i.pitch?e.pitch:i.pitch,bearing:undefined===i.bearing?e.bearing:i.bearing},n=undefined!==i.zoom,l=!e.isPaddingEqual(i.padding);let c=false;const h=n?+i.zoom:e.zoom;let u=e.centerPoint.add(i.offsetAsPoint);const d=e.screenPointToLocation(u),{center:_,zoom:p}=e.getConstrained(t.N.convert(i.center||d),null!=h?h:r);Ct(e,_);const m=xt(e.worldSize,d),f=xt(e.worldSize,_).sub(m),g=t.aG(p-r);return c=p!==r,{easeFunc:n=>{if(c&&e.setZoom(t.y.number(r,p,n)),t.b3(s,a)||At({startEulerAngles:s,endEulerAngles:a,tr:e,k:n,useSlerp:s.roll!=a.roll}),l&&(e.interpolatePadding(o,i.padding,n),u=e.centerPoint.add(i.offsetAsPoint)),i.around)e.setLocationAtPoint(i.around,i.aroundPoint);else {const i=t.aG(e.zoom-r),o=p>r?Math.min(2,g):Math.max(.5,g),s=Math.pow(o,1-n),a=bt(e.worldSize,m.add(f.mult(n*s)).mult(i));e.setLocationAtPoint(e.renderWorldCopies?a.wrap():a,u);}},isZooming:c,elevationCenter:_}}handleFlyTo(e,i){const r=undefined!==i.zoom,o=e.zoom,s=e.getConstrained(t.N.convert(i.center||i.locationAtOffset),r?+i.zoom:o),a=s.center,n=s.zoom;Ct(e,a);const l=xt(e.worldSize,i.locationAtOffset),c=xt(e.worldSize,a).sub(l),h=c.mag(),u=t.aG(n-o);let d;if(undefined!==i.minZoom){const r=Math.min(+i.minZoom,o,n),s=e.getConstrained(a,r).zoom;d=t.aG(s-o);}return {easeFunc:(i,r,s,h)=>{e.setZoom(1===i?n:o+t.a8(r));const u=1===i?a:bt(e.worldSize,l.add(c.mult(s)).mult(r));e.setLocationAtPoint(e.renderWorldCopies?u.wrap():u,h);},scaleOfZoom:u,targetCenter:a,scaleOfMinZoom:d,pixelPathLength:h}}}class Ft{constructor(e,t,i){this.blendFunction=e,this.blendColor=t,this.mask=i;}}Ft.Replace=[1,0],Ft.disabled=new Ft(Ft.Replace,t.b4.transparent,[false,false,false,false]),Ft.unblended=new Ft(Ft.Replace,t.b4.transparent,[true,true,true,true]),Ft.alphaBlended=new Ft([1,771],t.b4.transparent,[true,true,true,true]);const Bt=2305;class jt{constructor(e,t,i){this.enable=e,this.mode=t,this.frontFace=i;}}jt.disabled=new jt(false,1029,Bt),jt.backCCW=new jt(true,1029,Bt),jt.frontCCW=new jt(true,1028,Bt);class Ot{constructor(e,t,i){this.func=e,this.mask=t,this.range=i;}}Ot.ReadOnly=false,Ot.ReadWrite=true,Ot.disabled=new Ot(519,Ot.ReadOnly,[0,1]);const Nt=7680;class Zt{constructor(e,t,i,r,o,s){this.test=e,this.ref=t,this.mask=i,this.fail=r,this.depthFail=o,this.pass=s;}}Zt.disabled=new Zt({func:519,mask:0},0,0,Nt,Nt,Nt);const Gt=new WeakMap;function Ut(e){var t;if(Gt.has(e))return Gt.get(e);{const i=null===(t=e.getParameter(e.VERSION))||undefined===t?undefined:t.startsWith("WebGL 2.0");return Gt.set(e,i),i}}class Vt{get awaitingQuery(){return !!this._readbackQueue}constructor(e){this._readbackWaitFrames=4,this._measureWaitFrames=6,this._texWidth=1,this._texHeight=1,this._measuredError=0,this._updateCount=0,this._lastReadbackFrame=-1e3,this._readbackQueue=null,this._cachedRenderContext=e;const i=e.context,r=i.gl;this._texFormat=r.RGBA,this._texType=r.UNSIGNED_BYTE;const o=new t.aC;o.emplaceBack(-1,-1),o.emplaceBack(2,-1),o.emplaceBack(-1,2);const s=new t.aE;s.emplaceBack(0,1,2),this._fullscreenTriangle=new pt(i.createVertexBuffer(o,mt.members),i.createIndexBuffer(s),t.aD.simpleSegment(0,0,o.length,s.length)),this._resultBuffer=new Uint8Array(4),i.activeTexture.set(r.TEXTURE1);const a=r.createTexture();r.bindTexture(r.TEXTURE_2D,a),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texImage2D(r.TEXTURE_2D,0,this._texFormat,this._texWidth,this._texHeight,0,this._texFormat,this._texType,null),this._fbo=i.createFramebuffer(this._texWidth,this._texHeight,false,false),this._fbo.colorAttachment.set(a),Ut(r)&&(this._pbo=r.createBuffer(),r.bindBuffer(r.PIXEL_PACK_BUFFER,this._pbo),r.bufferData(r.PIXEL_PACK_BUFFER,4,r.STREAM_READ),r.bindBuffer(r.PIXEL_PACK_BUFFER,null));}destroy(){const e=this._cachedRenderContext.context.gl;this._fullscreenTriangle.destroy(),this._fbo.destroy(),e.deleteBuffer(this._pbo),this._fullscreenTriangle=null,this._fbo=null,this._pbo=null,this._resultBuffer=null;}updateErrorLoop(e,t){const i=this._updateCount;return this._readbackQueue?i>=this._readbackQueue.frameNumberIssued+this._readbackWaitFrames&&this._tryReadback():i>=this._lastReadbackFrame+this._measureWaitFrames&&this._renderErrorTexture(e,t),this._updateCount++,this._measuredError}_bindFramebuffer(){const e=this._cachedRenderContext.context,t=e.gl;e.activeTexture.set(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this._fbo.colorAttachment.get()),e.bindFramebuffer.set(this._fbo.framebuffer);}_renderErrorTexture(e,i){const r=this._cachedRenderContext.context,o=r.gl;if(this._bindFramebuffer(),r.viewport.set([0,0,this._texWidth,this._texHeight]),r.clear({color:t.b4.transparent}),this._cachedRenderContext.useProgram("projectionErrorMeasurement").draw(r,o.TRIANGLES,Ot.disabled,Zt.disabled,Ft.unblended,jt.disabled,((e,t)=>({u_input:e,u_output_expected:t}))(e,i),null,null,"$clipping",this._fullscreenTriangle.vertexBuffer,this._fullscreenTriangle.indexBuffer,this._fullscreenTriangle.segments),this._pbo&&Ut(o)){o.bindBuffer(o.PIXEL_PACK_BUFFER,this._pbo),o.readBuffer(o.COLOR_ATTACHMENT0),o.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);const e=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);o.flush(),this._readbackQueue={frameNumberIssued:this._updateCount,sync:e};}else this._readbackQueue={frameNumberIssued:this._updateCount,sync:null};}_tryReadback(){const e=this._cachedRenderContext.context.gl;if(this._pbo&&this._readbackQueue&&Ut(e)){const i=e.clientWaitSync(this._readbackQueue.sync,0,0);if(i===e.WAIT_FAILED)return t.w("WebGL2 clientWaitSync failed."),this._readbackQueue=null,void(this._lastReadbackFrame=this._updateCount);if(i===e.TIMEOUT_EXPIRED)return;e.bindBuffer(e.PIXEL_PACK_BUFFER,this._pbo),e.getBufferSubData(e.PIXEL_PACK_BUFFER,0,this._resultBuffer,0,4),e.bindBuffer(e.PIXEL_PACK_BUFFER,null);}else this._bindFramebuffer(),e.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,this._resultBuffer);this._readbackQueue=null,this._measuredError=Vt._parseRGBA8float(this._resultBuffer),this._lastReadbackFrame=this._updateCount;}static _parseRGBA8float(e){let t=0;return t+=e[0]/256,t+=e[1]/65536,t+=e[2]/16777216,e[3]<127&&(t=-t),t/128}}const qt=t.X/128;function Ht(e,i){const r=undefined!==e.granularity?Math.max(e.granularity,1):1,o=r+(e.generateBorders?2:0),s=r+(e.extendToNorthPole||e.generateBorders?1:0)+(e.extendToSouthPole||e.generateBorders?1:0),a=o+1,n=s+1,l=e.generateBorders?-1:0,c=e.generateBorders||e.extendToNorthPole?-1:0,h=r+(e.generateBorders?1:0),u=r+(e.generateBorders||e.extendToSouthPole?1:0),d=a*n,_=o*s*6,p=a*n>65536;if(p&&"16bit"===i)throw new Error("Granularity is too large and meshes would not fit inside 16 bit vertex indices.");const m=p||"32bit"===i,f=new Int16Array(2*d);let g=0;for(let i=c;i<=u;i++)for(let o=l;o<=h;o++){let s=o/r*t.X;-1===o&&(s=-qt),o===r+1&&(s=t.X+qt);let a=i/r*t.X;-1===i&&(a=e.extendToNorthPole?t.b6:-qt),i===r+1&&(a=e.extendToSouthPole?t.b7:t.X+qt),f[g++]=s,f[g++]=a;}const v=m?new Uint32Array(_):new Uint16Array(_);let x=0;for(let e=0;e0}get latitudeErrorCorrectionRadians(){return this._verticalPerspectiveProjection.latitudeErrorCorrectionRadians}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return "globe"}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy();}updateGPUdependent(e){this._mercatorProjection.updateGPUdependent(e),this._verticalPerspectiveProjection.updateGPUdependent(e);}getMeshFromTileID(e,t,i,r,o){return this.currentProjection.getMeshFromTileID(e,t,i,r,o)}setProjection(e){this._transitionable.setValue("type",(null==e?undefined:e.type)||"mercator");}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning);}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e);}setErrorQueryLatitudeDegrees(e){this._verticalPerspectiveProjection.setErrorQueryLatitudeDegrees(e),this._mercatorProjection.setErrorQueryLatitudeDegrees(e);}}function Yt(e){const t=ei(e.worldSize,e.center.lat);return 2*Math.PI*t}function Jt(e,i,r,o,s){const a=1/(1<1e-6){const o=e[0]/r,s=Math.acos(e[2]/r),a=(o>0?s:-s)/Math.PI*180;return new t.N(t.aI(a,-180,180),i)}return new t.N(0,i)}function ii(e){return Math.cos(e*Math.PI/180)}function ri(e,i){const r=ii(e),o=ii(i);return t.a8(o/r)}function oi(e,i){const r=e.rotate(i.bearingInRadians),o=i.zoom+ri(i.center.lat,0),s=t.b9(1/ii(i.center.lat),1/ii(Math.min(Math.abs(i.center.lat),60)),t.bc(o,7,3,0,1)),a=360/Yt({worldSize:i.worldSize,center:{lat:i.center.lat}});return new t.N(i.center.lng-r.x*a*s,t.ab(i.center.lat+r.y*a,-t.aF,t.aF))}function si(e){const t=.5*e,i=Math.sin(t),r=Math.cos(t);return Math.log(i+r)-Math.log(r-i)}function ai(e,i,r,o){const s=e.lat+r*o;if(Math.abs(r)>1){const a=(Math.sign(e.lat+r)!==Math.sign(e.lat)?-Math.abs(e.lat):Math.abs(e.lat))*Math.PI/180,n=Math.abs(e.lat+r)*Math.PI/180,l=si(a+o*(n-a)),c=si(a),h=si(n);return new t.N(e.lng+i*((l-c)/(h-c)),s)}return new t.N(e.lng+i*o,s)}class ni{constructor(e){this._cachePrevious=new Map,this._cache=new Map,this._hadAnyChanges=false,this._aabbFactory=e;}recalculateCache(){if(!this._hadAnyChanges)return;const e=this._cachePrevious;this._cachePrevious=this._cache,this._cache=e,this._cache.clear(),this._hadAnyChanges=false;}getTileAABB(e,t,i,r){const o=`${e.z}_${e.x}_${e.y}`,s=this._cache.get(o);if(s)return s;const a=this._cachePrevious.get(o);if(a)return this._cache.set(o,a),a;const n=this._aabbFactory(e,t,i,r);return this._cache.set(o,n),this._hadAnyChanges=true,n}}function li(e,t,i){const r=e-t;return r<0?-r:Math.max(0,r-i)}function ci(e,t,i,r,o){const s=e-i;let a;return a=s<0?Math.min(-s,1+s-o):s>1?Math.min(Math.max(s-o,0),1-s):0,Math.max(a,li(t,r,o))}class hi{constructor(){this._aabbCache=new ni(this._computeTileAABB);}recalculateCache(){this._aabbCache.recalculateCache();}distanceToTile2d(e,t,i,r){const o=1<4}allowWorldCopies(){return false}getTileAABB(e,t,i,r){return this._aabbCache.getTileAABB(e,t,i,r)}_computeTileAABB(e,i,r,o){if(e.z<=0)return new Mt([-1,-1,-1],[1,1,1]);if(1===e.z)return new Mt([0===e.x?-1:0,0===e.y?0:-1,-1],[0===e.x?0:1,0===e.y?1:0,1]);{const i=[Jt(0,0,e.x,e.y,e.z),Jt(t.X,0,e.x,e.y,e.z),Jt(t.X,t.X,e.x,e.y,e.z),Jt(0,t.X,e.x,e.y,e.z)],r=[1,1,1],o=[-1,-1,-1];for(const e of i)for(let t=0;t<3;t++)r[t]=Math.min(r[t],e[t]),o[t]=Math.max(o[t],e[t]);if(0===e.y||e.y===(1<{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._coveringTilesDetailsProvider=new hi;}clone(){const e=new ui;return e.apply(this),e}apply(e,t){this._globeLatitudeErrorCorrectionRadians=t||0,this._helper.apply(e);}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._globeViewProjMatrixNoCorrection}get inverseProjectionMatrix(){return this._globeProjMatrixInverted}get cameraPosition(){const e=t.bf();return e[0]=this._cameraPosition[0],e[1]=this._cameraPosition[1],e[2]=this._cameraPosition[2],e}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}getProjectionData(e){const{overscaledTileID:t,applyGlobeMatrix:i}=e,r=this._helper.getMercatorTileCoordinates(t);return {mainMatrix:this._globeViewProjMatrix32f,tileMercatorCoords:r,clippingPlane:this._cachedClippingPlane,projectionTransition:i?1:0,fallbackMatrix:this._globeViewProjMatrix32f}}_computeClippingPlane(e){const i=this.pitchInRadians,r=this.cameraToCenterDistance/e,o=Math.sin(i)*r,s=Math.cos(i)*r+1,a=1/Math.sqrt(o*o+s*s)*1;let n=-o,l=s;const c=Math.sqrt(n*n+l*l);n/=c,l/=c;const h=[0,n,l];return t.bg(h,h,[0,0,0],-this.bearingInRadians),t.bh(h,h,[0,0,0],-1*this.center.lat*Math.PI/180),t.bi(h,h,[0,0,0],this.center.lng*Math.PI/180),t.aL(h,h,.25),[...h,.25*-a]}isLocationOccluded(e){return !this.isSurfacePointVisible(Qt(e))}transformLightDirection(e){const i=this._helper._center.lng*Math.PI/180,r=this._helper._center.lat*Math.PI/180,o=Math.cos(r),s=[Math.sin(i)*o,Math.sin(r),Math.cos(i)*o],a=[s[2],0,-s[0]],n=[0,0,0];t.aR(n,a,s),t.aQ(a,a),t.aQ(n,n);const l=[0,0,0];return t.aQ(l,[a[0]*e[0]+n[0]*e[1]+s[0]*e[2],a[1]*e[0]+n[1]*e[1]+s[1]*e[2],a[2]*e[0]+n[2]*e[1]+s[2]*e[2]]),l}getPixelScale(){return 1/Math.cos(this._helper._center.lat*Math.PI/180)}getCircleRadiusCorrection(){return Math.cos(this._helper._center.lat*Math.PI/180)}getPitchedTextCorrection(e,i,r){const o=function(e,i,r){const o=1/(1<s&&(s=i),rn&&(n=r);}const h=[c.lng+a,c.lat+l,c.lng+s,c.lat+n];return this.isSurfacePointOnScreen([0,1,0])&&(h[3]=90,h[0]=-180,h[2]=180),this.isSurfacePointOnScreen([0,-1,0])&&(h[1]=-90,h[0]=-180,h[2]=180),new V(h)}getConstrained(e,i){const r=t.ab(e.lat,-t.aF,t.aF),o=t.ab(+i,this.minZoom+ri(0,r),this.maxZoom);return {center:new t.N(e.lng,r),zoom:o}}calculateCenterFromCameraLngLatAlt(e,t,i,r){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,r)}setLocationAtPoint(e,i){const r=Qt(this.unprojectScreenPoint(i)),o=Qt(e),s=t.bf();t.bl(s);const a=t.bf();t.bi(a,r,s,-this.center.lng*Math.PI/180),t.bh(a,a,s,this.center.lat*Math.PI/180);const n=o[0]*o[0]+o[2]*o[2],l=a[0]*a[0];if(n=-g&&p<=g,x=f>=-g&&f<=g;let b,y;if(v&&x){const e=this.center.lng*Math.PI/180,i=this.center.lat*Math.PI/180;t.bp(u,e)+t.bp(p,i)=0}isSurfacePointOnScreen(e){if(!this.isSurfacePointVisible(e))return false;const i=t.be();return t.al(i,[...e,1],this._globeViewProjMatrixNoCorrection),i[0]/=i[3],i[1]/=i[3],i[2]/=i[3],i[0]>-1&&i[0]<1&&i[1]>-1&&i[1]<1&&i[2]>-1&&i[2]<1}rayPlanetIntersection(e,i){const r=t.aS(e,i),o=t.bf(),s=t.bf();t.aL(s,i,r),t.aP(o,e,s);const a=1-t.aS(o,o);if(a<0)return null;const n=t.aS(e,e)-1,l=-r+(r<0?1:-1)*Math.sqrt(a),c=n/l,h=l;return {tMin:Math.min(c,h),tMax:Math.max(c,h)}}unprojectScreenPoint(e){const i=this._cameraPosition,r=this.getRayDirectionFromPixel(e),o=this.rayPlanetIntersection(i,r);if(o){const e=t.bf();t.aM(e,i,[r[0]*o.tMin,r[1]*o.tMin,r[2]*o.tMin]);const s=t.bf();return t.aQ(s,e),ti(s)}const s=this._cachedClippingPlane[0]*r[0]+this._cachedClippingPlane[1]*r[1]+this._cachedClippingPlane[2]*r[2],a=-t.bn(this._cachedClippingPlane,i)/s,n=t.bf();if(a>0)t.aM(n,i,[r[0]*a,r[1]*a,r[2]*a]);else {const e=t.bf();t.aM(e,i,[2*r[0],2*r[1],2*r[2]]);const o=t.bn(this._cachedClippingPlane,e);t.aP(n,e,[this._cachedClippingPlane[0]*o,this._cachedClippingPlane[1]*o,this._cachedClippingPlane[2]*o]);}const l=t.bf();return t.aQ(l,n),ti(l)}getMatrixForModel(e,i){const r=t.N.convert(e),o=1/t.bo,s=t.a_();return t.bj(s,s,r.lng/180*Math.PI),t.aY(s,s,-r.lat/180*Math.PI),t.J(s,s,[0,0,1+i/t.bo]),t.aY(s,s,.5*Math.PI),t.K(s,s,[o,o,o]),s}getProjectionDataForCustomLayer(e=true){const i=this.getProjectionData({overscaledTileID:new t.S(0,0,0,0,0),applyGlobeMatrix:e});return i.tileMercatorCoords=[0,0,1,1],i}getFastPathSimpleProjectionMatrix(e){}}class di{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=true){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}get isGlobeRendering(){return this._globeness>0}setTransitionState(e,t){this._globeness=e,this._globeLatitudeErrorCorrectionRadians=t,this._calcMatrices(),this._verticalPerspectiveTransform.getCoveringTilesDetailsProvider().recalculateCache(),this._mercatorTransform.getCoveringTilesDetailsProvider().recalculateCache();}get currentTransform(){return this.isGlobeRendering?this._verticalPerspectiveTransform:this._mercatorTransform}constructor(){this._globeLatitudeErrorCorrectionRadians=0,this._globeness=1,this._helper=new Et({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._globeness=1,this._mercatorTransform=new Dt,this._verticalPerspectiveTransform=new ui;}clone(){const e=new di;return e._globeness=this._globeness,e._globeLatitudeErrorCorrectionRadians=this._globeLatitudeErrorCorrectionRadians,e.apply(this),e}apply(e){this._helper.apply(e),this._mercatorTransform.apply(this),this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians);}get projectionMatrix(){return this.currentTransform.projectionMatrix}get modelViewProjectionMatrix(){return this.currentTransform.modelViewProjectionMatrix}get inverseProjectionMatrix(){return this.currentTransform.inverseProjectionMatrix}get cameraPosition(){return this.currentTransform.cameraPosition}getProjectionData(e){const t=this._mercatorTransform.getProjectionData(e),i=this._verticalPerspectiveTransform.getProjectionData(e);return {mainMatrix:this.isGlobeRendering?i.mainMatrix:t.mainMatrix,clippingPlane:i.clippingPlane,tileMercatorCoords:i.tileMercatorCoords,projectionTransition:e.applyGlobeMatrix?this._globeness:0,fallbackMatrix:t.fallbackMatrix}}isLocationOccluded(e){return this.currentTransform.isLocationOccluded(e)}transformLightDirection(e){return this.currentTransform.transformLightDirection(e)}getPixelScale(){return t.b9(this._mercatorTransform.getPixelScale(),this._verticalPerspectiveTransform.getPixelScale(),this._globeness)}getCircleRadiusCorrection(){return t.b9(this._mercatorTransform.getCircleRadiusCorrection(),this._verticalPerspectiveTransform.getCircleRadiusCorrection(),this._globeness)}getPitchedTextCorrection(e,i,r){const o=this._mercatorTransform.getPitchedTextCorrection(e,i,r),s=this._verticalPerspectiveTransform.getPitchedTextCorrection(e,i,r);return t.b9(o,s,this._globeness)}projectTileCoordinates(e,t,i,r){return this.currentTransform.projectTileCoordinates(e,t,i,r)}_calcMatrices(){this._helper._width&&this._helper._height&&(this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians),this._helper._nearZ=this._verticalPerspectiveTransform.nearZ,this._helper._farZ=this._verticalPerspectiveTransform.farZ,this._mercatorTransform.apply(this,true,this.isGlobeRendering),this._helper._nearZ=this._mercatorTransform.nearZ,this._helper._farZ=this._mercatorTransform.farZ);}calculateFogMatrix(e){return this.currentTransform.calculateFogMatrix(e)}getVisibleUnwrappedCoordinates(e){return this.currentTransform.getVisibleUnwrappedCoordinates(e)}getCameraFrustum(){return this.currentTransform.getCameraFrustum()}getClippingPlane(){return this.currentTransform.getClippingPlane()}getCoveringTilesDetailsProvider(){return this.currentTransform.getCoveringTilesDetailsProvider()}recalculateZoomAndCenter(e){this._mercatorTransform.recalculateZoomAndCenter(e),this._verticalPerspectiveTransform.recalculateZoomAndCenter(e);}maxPitchScaleFactor(){return this._mercatorTransform.maxPitchScaleFactor()}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){return this._helper.getCameraLngLat()}lngLatToCameraDepth(e,t){return this.currentTransform.lngLatToCameraDepth(e,t)}populateCache(e){this._mercatorTransform.populateCache(e),this._verticalPerspectiveTransform.populateCache(e);}getBounds(){return this.currentTransform.getBounds()}getConstrained(e,t){return this.currentTransform.getConstrained(e,t)}calculateCenterFromCameraLngLatAlt(e,t,i,r){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,r)}setLocationAtPoint(e,t){if(!this.isGlobeRendering)return this._mercatorTransform.setLocationAtPoint(e,t),void this.apply(this._mercatorTransform);this._verticalPerspectiveTransform.setLocationAtPoint(e,t),this.apply(this._verticalPerspectiveTransform);}locationToScreenPoint(e,t){return this.currentTransform.locationToScreenPoint(e,t)}screenPointToMercatorCoordinate(e,t){return this.currentTransform.screenPointToMercatorCoordinate(e,t)}screenPointToLocation(e,t){return this.currentTransform.screenPointToLocation(e,t)}isPointOnMapSurface(e,t){return this.currentTransform.isPointOnMapSurface(e,t)}getRayDirectionFromPixel(e){return this._verticalPerspectiveTransform.getRayDirectionFromPixel(e)}getMatrixForModel(e,t){return this.currentTransform.getMatrixForModel(e,t)}getProjectionDataForCustomLayer(e=true){const t=this._mercatorTransform.getProjectionDataForCustomLayer(e);if(!this.isGlobeRendering)return t;const i=this._verticalPerspectiveTransform.getProjectionDataForCustomLayer(e);return i.fallbackMatrix=t.mainMatrix,i}getFastPathSimpleProjectionMatrix(e){return this.currentTransform.getFastPathSimpleProjectionMatrix(e)}}class _i{get useGlobeControls(){return true}handlePanInertia(e,i){const r=oi(e,i);return Math.abs(r.lng-i.center.lng)>180&&(r.lng=i.center.lng+179.5*Math.sign(r.lng-i.center.lng)),{easingCenter:r,easingOffset:new t.P(0,0)}}handleMapControlsRollPitchBearingZoom(e,i){const r=e.around,o=i.screenPointToLocation(r);e.bearingDelta&&i.setBearing(i.bearing+e.bearingDelta),e.pitchDelta&&i.setPitch(i.pitch+e.pitchDelta),e.rollDelta&&i.setRoll(i.roll+e.rollDelta);const s=i.zoom;e.zoomDelta&&i.setZoom(i.zoom+e.zoomDelta);const a=i.zoom-s;if(0===a)return;const n=t.bk(i.center.lng,o.lng),l=n/(Math.abs(n/180)+1),c=t.bk(i.center.lat,o.lat),h=i.getRayDirectionFromPixel(r),u=i.cameraPosition,d=-1*t.aS(u,h),_=t.bf();t.aM(_,u,[h[0]*d,h[1]*d,h[2]*d]);const p=t.bq(_)-1,m=Math.exp(.5*-Math.max(p-.3,0)),f=ei(i.worldSize,i.center.lat)/Math.min(i.width,i.height),g=t.bc(f,.9,.5,1,.25),v=(1-t.aG(-a))*Math.min(m,g),x=i.center.lat,b=i.zoom,y=new t.N(i.center.lng+l*v,t.ab(i.center.lat+c*v,-t.aF,t.aF));i.setLocationAtPoint(o,r);const w=i.center,T=t.bc(Math.abs(n),45,85,0,1),P=t.bc(f,.75,.35,0,1),C=Math.pow(Math.max(T,P),.25),I=t.bk(w.lng,y.lng),E=t.bk(w.lat,y.lat);i.setCenter(new t.N(w.lng+I*C,w.lat+E*C).wrap()),i.setZoom(b+ri(x,i.center.lat));}handleMapControlsPan(e,t,i){if(!e.panDelta)return;const r=t.center.lat,o=t.zoom;t.setCenter(oi(e.panDelta,t).wrap()),t.setZoom(o+ri(r,t.center.lat));}cameraForBoxAndBearing(e,i,r,o,s){const a=Lt(e,i,r,o,s),n=i.left/s.width*2-1,l=(s.width-i.right)/s.width*2-1,c=i.top/s.height*-2+1,h=(s.height-i.bottom)/s.height*-2+1,u=t.bk(r.getWest(),r.getEast())<0,d=u?r.getEast():r.getWest(),_=u?r.getWest():r.getEast(),p=Math.max(r.getNorth(),r.getSouth()),m=Math.min(r.getNorth(),r.getSouth()),f=d+.5*t.bk(d,_),g=p+.5*t.bk(p,m),v=s.clone();v.setCenter(a.center),v.setBearing(a.bearing),v.setPitch(0),v.setRoll(0),v.setZoom(a.zoom);const x=v.modelViewProjectionMatrix,b=[Qt(r.getNorthWest()),Qt(r.getNorthEast()),Qt(r.getSouthWest()),Qt(r.getSouthEast()),Qt(new t.N(_,g)),Qt(new t.N(d,g)),Qt(new t.N(f,p)),Qt(new t.N(f,m))],y=Qt(a.center);let w=Number.POSITIVE_INFINITY;for(const e of b)n<0&&(w=_i.getLesserNonNegativeNonNull(w,_i.solveVectorScale(e,y,x,"x",n))),l>0&&(w=_i.getLesserNonNegativeNonNull(w,_i.solveVectorScale(e,y,x,"x",l))),c>0&&(w=_i.getLesserNonNegativeNonNull(w,_i.solveVectorScale(e,y,x,"y",c))),h<0&&(w=_i.getLesserNonNegativeNonNull(w,_i.solveVectorScale(e,y,x,"y",h)));if(Number.isFinite(w)&&0!==w)return a.zoom=v.zoom+t.a8(w),a;zt();}handleJumpToCenterZoom(e,i){const r=e.center.lat,o=e.getConstrained(i.center?t.N.convert(i.center):e.center,e.zoom).center;e.setCenter(o.wrap());const s=undefined!==i.zoom?+i.zoom:e.zoom+ri(r,o.lat);e.zoom!==s&&e.setZoom(s);}handleEaseTo(e,i){const r=e.zoom,o=e.center,s=e.padding,a={roll:e.roll,pitch:e.pitch,bearing:e.bearing},n={roll:undefined===i.roll?e.roll:i.roll,pitch:undefined===i.pitch?e.pitch:i.pitch,bearing:undefined===i.bearing?e.bearing:i.bearing},l=undefined!==i.zoom,c=!e.isPaddingEqual(i.padding);let h=false;const u=i.center?t.N.convert(i.center):o,d=e.getConstrained(u,r).center;Ct(e,d);const _=e.clone();_.setCenter(d),_.setZoom(l?+i.zoom:r+ri(o.lat,u.lat)),_.setBearing(i.bearing);const p=new t.P(t.ab(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ab(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));_.setLocationAtPoint(d,p);const m=(i.offset&&i.offsetAsPoint.mag())>0?_.center:d,f=l?+i.zoom:r+ri(o.lat,m.lat),g=r+ri(o.lat,0),v=f+ri(m.lat,0),x=t.bk(o.lng,m.lng),b=t.bk(o.lat,m.lat),y=t.aG(v-g);return h=f!==r,{easeFunc:r=>{if(t.b3(a,n)||At({startEulerAngles:a,endEulerAngles:n,tr:e,k:r,useSlerp:a.roll!=n.roll}),c&&e.interpolatePadding(s,i.padding,r),i.around)t.w("Easing around a point is not supported under globe projection."),e.setLocationAtPoint(i.around,i.aroundPoint);else {const t=v>g?Math.min(2,y):Math.max(.5,y),i=Math.pow(t,1-r),s=ai(o,x,b,r*i);e.setCenter(s.wrap());}if(h){const i=t.y.number(g,v,r)+ri(0,e.center.lat);e.setZoom(i);}},isZooming:h,elevationCenter:m}}handleFlyTo(e,i){const r=undefined!==i.zoom,o=e.center,s=e.zoom,a=!e.isPaddingEqual(i.padding),n=e.getConstrained(t.N.convert(i.center||i.locationAtOffset),s).center,l=r?+i.zoom:e.zoom+ri(e.center.lat,n.lat),c=e.clone();c.setCenter(n),a&&c.setPadding(i.padding),c.setZoom(l),c.setBearing(i.bearing);const h=new t.P(t.ab(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ab(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));c.setLocationAtPoint(n,h);const u=c.center;Ct(e,u);const d=function(e,i,r){const o=Qt(i),s=Qt(r),a=t.aS(o,s),n=Math.acos(a),l=Yt(e);return n/(2*Math.PI)*l}(e,o,u),_=s+ri(o.lat,0),p=l+ri(u.lat,0),m=t.aG(p-_);let f;if("number"==typeof i.minZoom){const r=+i.minZoom+ri(u.lat,0),o=Math.min(r,_,p)+ri(0,u.lat),s=e.getConstrained(u,o).zoom+ri(u.lat,0);f=t.aG(s-_);}const g=t.bk(o.lng,u.lng),v=t.bk(o.lat,u.lat);return {easeFunc:(i,r,s,a)=>{const n=ai(o,g,v,s),c=1===i?u:n;e.setCenter(c.wrap());const h=_+t.a8(r);e.setZoom(1===i?l:h+ri(0,c.lat));},scaleOfZoom:m,targetCenter:u,scaleOfMinZoom:f,pixelPathLength:d}}static solveVectorScale(e,t,i,r,o){const s="x"===r?[i[0],i[4],i[8],i[12]]:[i[1],i[5],i[9],i[13]],a=[i[3],i[7],i[11],i[15]],n=e[0]*s[0]+e[1]*s[1]+e[2]*s[2],l=e[0]*a[0]+e[1]*a[1]+e[2]*a[2],c=t[0]*s[0]+t[1]*s[1]+t[2]*s[2],h=t[0]*a[0]+t[1]*a[1]+t[2]*a[2];return c+o*l===n+o*h||a[3]*(n-c)+s[3]*(h-l)+n*h==c*l?null:(c+s[3]-o*h-o*a[3])/(c-n-o*h+o*l)}static getLesserNonNegativeNonNull(e,t){return null!==t&&t>=0&&tt.t(e,i&&i.filter((e=>"source.canvas"!==e.identifier))),fi=t.br();class gi extends t.E{constructor(e,i={}){super(),this._rtlPluginLoaded=()=>{for(const e in this.sourceCaches){const t=this.sourceCaches[e].getSource().type;"vector"!==t&&"geojson"!==t||this.sourceCaches[e].reload();}},this.map=e,this.dispatcher=new B(F(),e._getMapId()),this.dispatcher.registerMessageHandler("GG",((e,t)=>this.getGlyphs(e,t))),this.dispatcher.registerMessageHandler("GI",((e,t)=>this.getImages(e,t))),this.imageManager=new b,this.imageManager.setEventedParent(this),this.glyphManager=new P(e._requestManager,i.localIdeographFontFamily),this.lineAtlas=new R(256,512),this.crossTileSymbolIndex=new ht,this._spritesImagesIds={},this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new t.bs,this._loaded=false,this._availableImages=[],this._resetUpdates(),this.dispatcher.broadcast("SR",t.bt()),oe().on(te,this._rtlPluginLoaded),this.on("data",(e=>{if("source"!==e.dataType||"metadata"!==e.sourceDataType)return;const t=this.sourceCaches[e.sourceId];if(!t)return;const i=t.getSource();if(i&&i.vectorLayerIds)for(const e in this._layers){const t=this._layers[e];t.source===i.id&&this._validateLayer(t);}}));}loadURL(e,i={},r){this.fire(new t.k("dataloading",{dataType:"style"})),i.validate="boolean"!=typeof i.validate||i.validate;const o=this.map._requestManager.transformRequest(e,"Style");this._loadStyleRequest=new AbortController;const s=this._loadStyleRequest;t.h(o,this._loadStyleRequest).then((e=>{this._loadStyleRequest=null,this._load(e.data,i,r);})).catch((e=>{this._loadStyleRequest=null,e&&!s.signal.aborted&&this.fire(new t.j(e));}));}loadJSON(e,i={},r){this.fire(new t.k("dataloading",{dataType:"style"})),this._frameRequest=new AbortController,a.frameAsync(this._frameRequest).then((()=>{this._frameRequest=null,i.validate=false!==i.validate,this._load(e,i,r);})).catch((()=>{}));}loadEmpty(){this.fire(new t.k("dataloading",{dataType:"style"})),this._load(fi,{validate:false});}_load(e,i,r){var o,s;const a=i.transformStyle?i.transformStyle(r,e):e;if(!i.validate||!mi(this,t.u(a))){this._loaded=true,this.stylesheet=a;for(const e in a.sources)this.addSource(e,a.sources[e],{validate:false});a.sprite?this._loadSprite(a.sprite):this.imageManager.setLoaded(true),this.glyphManager.setURL(a.glyphs),this._createLayers(),this.light=new E(this.stylesheet.light),this._setProjectionInternal((null===(o=this.stylesheet.projection)||undefined===o?undefined:o.type)||"mercator"),this.sky=new S(this.stylesheet.sky),this.map.setTerrain(null!==(s=this.stylesheet.terrain)&&undefined!==s?s:null),this.fire(new t.k("data",{dataType:"style"})),this.fire(new t.k("style.load"));}}_createLayers(){const e=t.bu(this.stylesheet.layers);this.dispatcher.broadcast("SL",e),this._order=e.map((e=>e.id)),this._layers={},this._serializedLayers=null;for(const i of e){const e=t.bv(i);e.setEventedParent(this,{layer:{id:i.id}}),this._layers[i.id]=e;}}_loadSprite(e,i=false,r=undefined){let o;this.imageManager.setLoaded(false),this._spriteRequest=new AbortController,function(e,i,r,o){return t._(this,undefined,undefined,(function*(){const s=f(e),n=r>1?"@2x":"",l={},c={};for(const{id:e,url:r}of s){const s=i.transformRequest(g(r,n,".json"),"SpriteJSON");l[e]=t.h(s,o);const a=i.transformRequest(g(r,n,".png"),"SpriteImage");c[e]=p.getImage(a,o);}return yield Promise.all([...Object.values(l),...Object.values(c)]),function(e,i){return t._(this,undefined,undefined,(function*(){const t={};for(const r in e){t[r]={};const o=a.getImageCanvasContext((yield i[r]).data),s=(yield e[r]).data;for(const e in s){const{width:i,height:a,x:n,y:l,sdf:c,pixelRatio:h,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m}=s[e];t[r][e]={data:null,pixelRatio:h,sdf:c,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m,spriteData:{width:i,height:a,x:n,y:l,context:o}};}}return t}))}(l,c)}))}(e,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((e=>{if(this._spriteRequest=null,e)for(const t in e){this._spritesImagesIds[t]=[];const r=this._spritesImagesIds[t]?this._spritesImagesIds[t].filter((t=>!(t in e))):[];for(const e of r)this.imageManager.removeImage(e),this._changedImages[e]=true;for(const r in e[t]){const o="default"===t?r:`${t}:${r}`;this._spritesImagesIds[t].push(o),o in this.imageManager.images?this.imageManager.updateImage(o,e[t][r],false):this.imageManager.addImage(o,e[t][r]),i&&(this._changedImages[o]=true);}}})).catch((e=>{this._spriteRequest=null,o=e,this.fire(new t.j(o));})).finally((()=>{this.imageManager.setLoaded(true),this._availableImages=this.imageManager.listImages(),i&&(this._changed=true),this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.k("data",{dataType:"style"})),r&&r(o);}));}_unloadSprite(){for(const e of Object.values(this._spritesImagesIds).flat())this.imageManager.removeImage(e),this._changedImages[e]=true;this._spritesImagesIds={},this._availableImages=this.imageManager.listImages(),this._changed=true,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.k("data",{dataType:"style"}));}_validateLayer(e){const i=this.sourceCaches[e.source];if(!i)return;const r=e.sourceLayer;if(!r)return;const o=i.getSource();("geojson"===o.type||o.vectorLayerIds&&-1===o.vectorLayerIds.indexOf(r))&&this.fire(new t.j(new Error(`Source layer "${r}" does not exist on source "${o.id}" as specified by style layer "${e.id}".`)));}loaded(){if(!this._loaded)return false;if(Object.keys(this._updatedSources).length)return false;for(const e in this.sourceCaches)if(!this.sourceCaches[e].loaded())return false;return !!this.imageManager.isLoaded()}_serializeByIds(e,i=false){const r=this._serializedAllLayers();if(!e||0===e.length)return Object.values(i?t.bw(r):r);const o=[];for(const s of e)if(r[s]){const e=i?t.bw(r[s]):r[s];o.push(e);}return o}_serializedAllLayers(){let e=this._serializedLayers;if(e)return e;e=this._serializedLayers={};const t=Object.keys(this._layers);for(const i of t){const t=this._layers[i];"custom"!==t.type&&(e[i]=t.serialize());}return e}hasTransitions(){var e,t,i;if(null===(e=this.light)||undefined===e?undefined:e.hasTransition())return true;if(null===(t=this.sky)||undefined===t?undefined:t.hasTransition())return true;if(null===(i=this.projection)||undefined===i?undefined:i.hasTransition())return true;for(const e in this.sourceCaches)if(this.sourceCaches[e].hasTransition())return true;for(const e in this._layers)if(this._layers[e].hasTransition())return true;return false}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading.")}update(e){if(!this._loaded)return;const i=this._changed;if(i){const t=Object.keys(this._updatedLayers),i=Object.keys(this._removedLayers);(t.length||i.length)&&this._updateWorkerLayers(t,i);for(const e in this._updatedSources){const t=this._updatedSources[e];if("reload"===t)this._reloadSource(e);else {if("clear"!==t)throw new Error(`Invalid action ${t}`);this._clearSource(e);}}this._updateTilesForChangedImages(),this._updateTilesForChangedGlyphs();for(const t in this._updatedPaintProps)this._layers[t].updateTransitions(e);this.light.updateTransitions(e),this.sky.updateTransitions(e),this._resetUpdates();}const r={};for(const e in this.sourceCaches){const t=this.sourceCaches[e];r[e]=t.used,t.used=false;}for(const t of this._order){const i=this._layers[t];i.recalculate(e,this._availableImages),!i.isHidden(e.zoom)&&i.source&&(this.sourceCaches[i.source].used=true);}for(const e in r){const i=this.sourceCaches[e];!!r[e]!=!!i.used&&i.fire(new t.k("data",{sourceDataType:"visibility",dataType:"source",sourceId:e}));}this.light.recalculate(e),this.sky.recalculate(e),this.projection.recalculate(e),this.z=e.zoom,i&&this.fire(new t.k("data",{dataType:"style"}));}_updateTilesForChangedImages(){const e=Object.keys(this._changedImages);if(e.length){for(const t in this.sourceCaches)this.sourceCaches[t].reloadTilesForDependencies(["icons","patterns"],e);this._changedImages={};}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const e in this.sourceCaches)this.sourceCaches[e].reloadTilesForDependencies(["glyphs"],[""]);this._glyphsDidChange=false;}}_updateWorkerLayers(e,t){this.dispatcher.broadcast("UL",{layers:this._serializeByIds(e,false),removedIds:t});}_resetUpdates(){this._changed=false,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={},this._glyphsDidChange=false;}setState(e,i={}){var r;this._checkLoaded();const o=this.serialize();if(e=i.transformStyle?i.transformStyle(o,e):e,(null===(r=i.validate)||undefined===r||r)&&mi(this,t.u(e)))return false;(e=t.bw(e)).layers=t.bu(e.layers);const s=t.bx(o,e),a=this._getOperationsToPerform(s);if(a.unimplemented.length>0)throw new Error(`Unimplemented: ${a.unimplemented.join(", ")}.`);if(0===a.operations.length)return false;for(const e of a.operations)e();return this.stylesheet=e,this._serializedLayers=null,true}_getOperationsToPerform(e){const t=[],i=[];for(const r of e)switch(r.command){case"setCenter":case"setZoom":case"setBearing":case"setPitch":case"setRoll":continue;case"addLayer":t.push((()=>this.addLayer.apply(this,r.args)));break;case"removeLayer":t.push((()=>this.removeLayer.apply(this,r.args)));break;case"setPaintProperty":t.push((()=>this.setPaintProperty.apply(this,r.args)));break;case"setLayoutProperty":t.push((()=>this.setLayoutProperty.apply(this,r.args)));break;case"setFilter":t.push((()=>this.setFilter.apply(this,r.args)));break;case"addSource":t.push((()=>this.addSource.apply(this,r.args)));break;case"removeSource":t.push((()=>this.removeSource.apply(this,r.args)));break;case"setLayerZoomRange":t.push((()=>this.setLayerZoomRange.apply(this,r.args)));break;case"setLight":t.push((()=>this.setLight.apply(this,r.args)));break;case"setGeoJSONSourceData":t.push((()=>this.setGeoJSONSourceData.apply(this,r.args)));break;case"setGlyphs":t.push((()=>this.setGlyphs.apply(this,r.args)));break;case"setSprite":t.push((()=>this.setSprite.apply(this,r.args)));break;case"setTerrain":t.push((()=>this.map.setTerrain.apply(this,r.args)));break;case"setSky":t.push((()=>this.setSky.apply(this,r.args)));break;case"setProjection":this.setProjection.apply(this,r.args);break;case"setTransition":t.push((()=>{}));break;default:i.push(r.command);}return {operations:t,unimplemented:i}}addImage(e,i){if(this.getImage(e))return this.fire(new t.j(new Error(`An image named "${e}" already exists.`)));this.imageManager.addImage(e,i),this._afterImageUpdated(e);}updateImage(e,t){this.imageManager.updateImage(e,t);}getImage(e){return this.imageManager.getImage(e)}removeImage(e){if(!this.getImage(e))return this.fire(new t.j(new Error(`An image named "${e}" does not exist.`)));this.imageManager.removeImage(e),this._afterImageUpdated(e);}_afterImageUpdated(e){this._availableImages=this.imageManager.listImages(),this._changedImages[e]=true,this._changed=true,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.k("data",{dataType:"style"}));}listImages(){return this._checkLoaded(),this.imageManager.listImages()}addSource(e,i,r={}){if(this._checkLoaded(),undefined!==this.sourceCaches[e])throw new Error(`Source "${e}" already exists.`);if(!i.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(i).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(i.type)>=0&&this._validate(t.u.source,`sources.${e}`,i,null,r))return;this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=true);const o=this.sourceCaches[e]=new de(e,i,this.dispatcher);o.style=this,o.setEventedParent(this,(()=>({isSourceLoaded:o.loaded(),source:o.serialize(),sourceId:e}))),o.onAdd(this.map),this._changed=true;}removeSource(e){if(this._checkLoaded(),undefined===this.sourceCaches[e])throw new Error("There is no source with this ID");for(const i in this._layers)if(this._layers[i].source===e)return this.fire(new t.j(new Error(`Source "${e}" cannot be removed while layer "${i}" is using it.`)));const i=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],i.fire(new t.k("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),i.setEventedParent(null),i.onRemove(this.map),this._changed=true;}setGeoJSONSourceData(e,t){if(this._checkLoaded(),undefined===this.sourceCaches[e])throw new Error(`There is no source with this ID=${e}`);const i=this.sourceCaches[e].getSource();if("geojson"!==i.type)throw new Error(`geojsonSource.type is ${i.type}, which is !== 'geojson`);i.setData(t),this._changed=true;}getSource(e){return this.sourceCaches[e]&&this.sourceCaches[e].getSource()}addLayer(e,i,r={}){this._checkLoaded();const o=e.id;if(this.getLayer(o))return void this.fire(new t.j(new Error(`Layer "${o}" already exists on this map.`)));let s;if("custom"===e.type){if(mi(this,t.by(e)))return;s=t.bv(e);}else {if("source"in e&&"object"==typeof e.source&&(this.addSource(o,e.source),e=t.bw(e),e=t.e(e,{source:o})),this._validate(t.u.layer,`layers.${o}`,e,{arrayIndex:-1},r))return;s=t.bv(e),this._validateLayer(s),s.setEventedParent(this,{layer:{id:o}});}const a=i?this._order.indexOf(i):this._order.length;if(i&&-1===a)this.fire(new t.j(new Error(`Cannot add layer "${o}" before non-existing layer "${i}".`)));else {if(this._order.splice(a,0,o),this._layerOrderChanged=true,this._layers[o]=s,this._removedLayers[o]&&s.source&&"custom"!==s.type){const e=this._removedLayers[o];delete this._removedLayers[o],e.type!==s.type?this._updatedSources[s.source]="clear":(this._updatedSources[s.source]="reload",this.sourceCaches[s.source].pause());}this._updateLayer(s),s.onAdd&&s.onAdd(this.map);}}moveLayer(e,i){if(this._checkLoaded(),this._changed=true,!this._layers[e])return void this.fire(new t.j(new Error(`The layer '${e}' does not exist in the map's style and cannot be moved.`)));if(e===i)return;const r=this._order.indexOf(e);this._order.splice(r,1);const o=i?this._order.indexOf(i):this._order.length;i&&-1===o?this.fire(new t.j(new Error(`Cannot move layer "${e}" before non-existing layer "${i}".`))):(this._order.splice(o,0,e),this._layerOrderChanged=true);}removeLayer(e){this._checkLoaded();const i=this._layers[e];if(!i)return void this.fire(new t.j(new Error(`Cannot remove non-existing layer "${e}".`)));i.setEventedParent(null);const r=this._order.indexOf(e);this._order.splice(r,1),this._layerOrderChanged=true,this._changed=true,this._removedLayers[e]=i,delete this._layers[e],this._serializedLayers&&delete this._serializedLayers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],i.onRemove&&i.onRemove(this.map);}getLayer(e){return this._layers[e]}getLayersOrder(){return [...this._order]}hasLayer(e){return e in this._layers}setLayerZoomRange(e,i,r){this._checkLoaded();const o=this.getLayer(e);o?o.minzoom===i&&o.maxzoom===r||(null!=i&&(o.minzoom=i),null!=r&&(o.maxzoom=r),this._updateLayer(o)):this.fire(new t.j(new Error(`Cannot set the zoom range of non-existing layer "${e}".`)));}setFilter(e,i,r={}){this._checkLoaded();const o=this.getLayer(e);if(o){if(!t.bz(o.filter,i))return null==i?(o.filter=undefined,void this._updateLayer(o)):void(this._validate(t.u.filter,`layers.${o.id}.filter`,i,null,r)||(o.filter=t.bw(i),this._updateLayer(o)))}else this.fire(new t.j(new Error(`Cannot filter non-existing layer "${e}".`)));}getFilter(e){return t.bw(this.getLayer(e).filter)}setLayoutProperty(e,i,r,o={}){this._checkLoaded();const s=this.getLayer(e);s?t.bz(s.getLayoutProperty(i),r)||(s.setLayoutProperty(i,r,o),this._updateLayer(s)):this.fire(new t.j(new Error(`Cannot style non-existing layer "${e}".`)));}getLayoutProperty(e,i){const r=this.getLayer(e);if(r)return r.getLayoutProperty(i);this.fire(new t.j(new Error(`Cannot get style of non-existing layer "${e}".`)));}setPaintProperty(e,i,r,o={}){this._checkLoaded();const s=this.getLayer(e);s?t.bz(s.getPaintProperty(i),r)||(s.setPaintProperty(i,r,o)&&this._updateLayer(s),this._changed=true,this._updatedPaintProps[e]=true,this._serializedLayers=null):this.fire(new t.j(new Error(`Cannot style non-existing layer "${e}".`)));}getPaintProperty(e,t){return this.getLayer(e).getPaintProperty(t)}setFeatureState(e,i){this._checkLoaded();const r=e.source,o=e.sourceLayer,s=this.sourceCaches[r];if(undefined===s)return void this.fire(new t.j(new Error(`The source '${r}' does not exist in the map's style.`)));const a=s.getSource().type;"geojson"===a&&o?this.fire(new t.j(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==a||o?(undefined===e.id&&this.fire(new t.j(new Error("The feature id parameter must be provided."))),s.setFeatureState(o,e.id,i)):this.fire(new t.j(new Error("The sourceLayer parameter must be provided for vector source types.")));}removeFeatureState(e,i){this._checkLoaded();const r=e.source,o=this.sourceCaches[r];if(undefined===o)return void this.fire(new t.j(new Error(`The source '${r}' does not exist in the map's style.`)));const s=o.getSource().type,a="vector"===s?e.sourceLayer:undefined;"vector"!==s||a?i&&"string"!=typeof e.id&&"number"!=typeof e.id?this.fire(new t.j(new Error("A feature id is required to remove its specific state property."))):o.removeFeatureState(a,e.id,i):this.fire(new t.j(new Error("The sourceLayer parameter must be provided for vector source types.")));}getFeatureState(e){this._checkLoaded();const i=e.source,r=e.sourceLayer,o=this.sourceCaches[i];if(undefined!==o)return "vector"!==o.getSource().type||r?(undefined===e.id&&this.fire(new t.j(new Error("The feature id parameter must be provided."))),o.getFeatureState(r,e.id)):void this.fire(new t.j(new Error("The sourceLayer parameter must be provided for vector source types.")));this.fire(new t.j(new Error(`The source '${i}' does not exist in the map's style.`)));}getTransition(){return t.e({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const e=t.bA(this.sourceCaches,(e=>e.serialize())),i=this._serializeByIds(this._order,true),r=this.map.getTerrain()||undefined,o=this.stylesheet;return t.bB({version:o.version,name:o.name,metadata:o.metadata,light:o.light,sky:o.sky,center:o.center,zoom:o.zoom,bearing:o.bearing,pitch:o.pitch,sprite:o.sprite,glyphs:o.glyphs,transition:o.transition,projection:o.projection,sources:e,layers:i,terrain:r},(e=>undefined!==e))}_updateLayer(e){this._updatedLayers[e.id]=true,e.source&&!this._updatedSources[e.source]&&"raster"!==this.sourceCaches[e.source].getSource().type&&(this._updatedSources[e.source]="reload",this.sourceCaches[e.source].pause()),this._serializedLayers=null,this._changed=true;}_flattenAndSortRenderedFeatures(e){const t=e=>"fill-extrusion"===this._layers[e].type,i={},r=[];for(let o=this._order.length-1;o>=0;o--){const s=this._order[o];if(t(s)){i[s]=o;for(const t of e){const e=t[s];if(e)for(const t of e)r.push(t);}}}r.sort(((e,t)=>t.intersectionZ-e.intersectionZ));const o=[];for(let s=this._order.length-1;s>=0;s--){const a=this._order[s];if(t(a))for(let e=r.length-1;e>=0;e--){const t=r[e].feature;if(i[t.layer.id]{const r=i.featureSortOrder;if(r){const i=r.indexOf(e.featureIndex);return r.indexOf(t.featureIndex)-i}return t.featureIndex-e.featureIndex}));for(const e of o)t.push(e);}}return function(e,t,i){for(const r in e)for(const o of e[r])G(o,i[t[r].source]);return e}(n,e,i)}(this._layers,a,this.sourceCaches,e,l,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(s)}querySourceFeatures(e,i){i&&i.filter&&this._validate(t.u.filter,"querySourceFeatures.filter",i.filter,null,i);const r=this.sourceCaches[e];return r?function(e,t){const i=e.getRenderableIds().map((t=>e.getTileByID(t))),r=[],o={};for(let e=0;ee.getTileByID(t))).sort(((e,t)=>t.tileID.overscaledZ-e.tileID.overscaledZ||(e.tileID.isLessThan(t.tileID)?-1:1)));}const r=this.crossTileSymbolIndex.addLayer(i,l[i.source],e.center.lng);s=s||r;}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((o=o||this._layerOrderChanged||0===i)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(a.now(),e.zoom))&&(this.pauseablePlacement=new st(e,this.map.terrain,this._order,o,t,i,r,this.placement),this._layerOrderChanged=false),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,l),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(a.now()),n=true),s&&this.pauseablePlacement.placement.setStale()),n||s)for(const e of this._order){const t=this._layers[e];"symbol"===t.type&&this.placement.updateLayerOpacities(t,l[t.source]);}return !this.pauseablePlacement.isDone()||this.placement.hasTransitions(a.now())}_releaseSymbolFadeTiles(){for(const e in this.sourceCaches)this.sourceCaches[e].releaseSymbolFadeTiles();}getImages(e,i){return t._(this,undefined,undefined,(function*(){const e=yield this.imageManager.getImages(i.icons);this._updateTilesForChangedImages();const t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,i.icons),e}))}getGlyphs(e,i){return t._(this,undefined,undefined,(function*(){const e=yield this.glyphManager.getGlyphs(i.stacks),t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,[""]),e}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(e,i={}){this._checkLoaded(),e&&this._validate(t.u.glyphs,"glyphs",e,null,i)||(this._glyphsDidChange=true,this.stylesheet.glyphs=e,this.glyphManager.entries={},this.glyphManager.setURL(e));}addSprite(e,i,r={},o){this._checkLoaded();const s=[{id:e,url:i}],a=[...f(this.stylesheet.sprite),...s];this._validate(t.u.sprite,"sprite",a,null,r)||(this.stylesheet.sprite=a,this._loadSprite(s,true,o));}removeSprite(e){this._checkLoaded();const i=f(this.stylesheet.sprite);if(i.find((t=>t.id===e))){if(this._spritesImagesIds[e])for(const t of this._spritesImagesIds[e])this.imageManager.removeImage(t),this._changedImages[t]=true;i.splice(i.findIndex((t=>t.id===e)),1),this.stylesheet.sprite=i.length>0?i:undefined,delete this._spritesImagesIds[e],this._availableImages=this.imageManager.listImages(),this._changed=true,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.k("data",{dataType:"style"}));}else this.fire(new t.j(new Error(`Sprite "${e}" doesn't exists on this map.`)));}getSprite(){return f(this.stylesheet.sprite)}setSprite(e,i={},r){this._checkLoaded(),e&&this._validate(t.u.sprite,"sprite",e,null,i)||(this.stylesheet.sprite=e,e?this._loadSprite(e,true,r):(this._unloadSprite(),r&&r(null)));}}var vi=t.aA([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]);class xi{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;}bind(e,t,i,r,o,s,a,n,l){this.context=e;let c=this.boundPaintVertexBuffers.length!==r.length;for(let e=0;!c&&e({u_texture:0,u_ele_delta:e,u_fog_matrix:i,u_fog_color:r?r.properties.get("fog-color"):t.b4.white,u_fog_ground_blend:r?r.properties.get("fog-ground-blend"):1,u_fog_ground_blend_opacity:s?0:r?r.calculateFogBlendOpacity(o):0,u_horizon_color:r?r.properties.get("horizon-color"):t.b4.white,u_horizon_fog_blend:r?r.properties.get("horizon-fog-blend"):1,u_is_globe_mode:s?1:0}),yi={mainMatrix:"u_projection_matrix",tileMercatorCoords:"u_projection_tile_mercator_coords",clippingPlane:"u_projection_clipping_plane",projectionTransition:"u_projection_transition",fallbackMatrix:"u_projection_fallback_matrix"};function wi(e){const t=[];for(let i=0;i({u_depth:new t.bC(e,i.u_depth),u_terrain:new t.bC(e,i.u_terrain),u_terrain_dim:new t.b5(e,i.u_terrain_dim),u_terrain_matrix:new t.bD(e,i.u_terrain_matrix),u_terrain_unpack:new t.bE(e,i.u_terrain_unpack),u_terrain_exaggeration:new t.b5(e,i.u_terrain_exaggeration)}))(e,P),this.projectionUniforms=((e,i)=>({u_projection_matrix:new t.bD(e,i.u_projection_matrix),u_projection_tile_mercator_coords:new t.bE(e,i.u_projection_tile_mercator_coords),u_projection_clipping_plane:new t.bE(e,i.u_projection_clipping_plane),u_projection_transition:new t.b5(e,i.u_projection_transition),u_projection_fallback_matrix:new t.bD(e,i.u_projection_fallback_matrix)}))(e,P),this.binderUniforms=r?r.getUniforms(e,P):[];}draw(e,t,i,r,o,s,a,n,l,c,h,u,d,_,p,m,f,g,v){const x=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.setDepthMode(i),e.setStencilMode(r),e.setColorMode(o),e.setCullFace(s),n){e.activeTexture.set(x.TEXTURE2),x.bindTexture(x.TEXTURE_2D,n.depthTexture),e.activeTexture.set(x.TEXTURE3),x.bindTexture(x.TEXTURE_2D,n.texture);for(const e in this.terrainUniforms)this.terrainUniforms[e].set(n[e]);}if(l)for(const e in l)this.projectionUniforms[yi[e]].set(l[e]);if(a)for(const e in this.fixedUniforms)this.fixedUniforms[e].set(a[e]);m&&m.setUniforms(e,this.binderUniforms,_,{zoom:p});let b=0;switch(t){case x.LINES:b=2;break;case x.TRIANGLES:b=3;break;case x.LINE_STRIP:b=1;}for(const i of d.get()){const r=i.vaos||(i.vaos={});(r[c]||(r[c]=new xi)).bind(e,this,h,m?m.getPaintVertexBuffers():[],u,i.vertexOffset,f,g,v),x.drawElements(t,i.primitiveLength*b,x.UNSIGNED_SHORT,i.primitiveOffset*b*2);}}}function Pi(e,i,r){const o=1/t.at(r,1,i.transform.tileZoom),s=Math.pow(2,r.tileID.overscaledZ),a=r.tileSize*Math.pow(2,i.transform.tileZoom)/s,n=a*(r.tileID.canonical.x+r.tileID.wrap*s),l=a*r.tileID.canonical.y;return {u_image:0,u_texsize:r.imageAtlasTexture.size,u_scale:[o,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[n>>16,l>>16],u_pixel_coord_lower:[65535&n,65535&l]}}const Ci=(e,i,r,o)=>{const s=e.style.light,a=s.properties.get("position"),n=[a.x,a.y,a.z],l=t.bI();"viewport"===s.properties.get("anchor")&&t.bJ(l,e.transform.bearingInRadians),t.bK(n,n,l);const c=e.transform.transformLightDirection(n),h=s.properties.get("color");return {u_lightpos:n,u_lightpos_globe:c,u_lightintensity:s.properties.get("intensity"),u_lightcolor:[h.r,h.g,h.b],u_vertical_gradient:+i,u_opacity:r,u_fill_translate:o}},Ii=(e,i,r,o,s,a,n)=>t.e(Ci(e,i,r,o),Pi(a,e,n),{u_height_factor:-Math.pow(2,s.overscaledZ)/n.tileSize/8}),Ei=(e,i,r,o)=>t.e(Pi(i,e,r),{u_fill_translate:o}),Mi=(e,t)=>({u_world:e,u_fill_translate:t}),Si=(e,i,r,o,s)=>t.e(Ei(e,i,r,s),{u_world:o}),Ri=(e,i,r,o,s)=>{const a=e.transform;let n,l,c=0;if("map"===r.paint.get("circle-pitch-alignment")){const e=t.at(i,1,a.zoom);n=true,l=[e,e],c=e/(t.X*Math.pow(2,i.tileID.overscaledZ))*2*Math.PI*s;}else n=false,l=a.pixelsToGLUnits;return {u_camera_to_center_distance:a.cameraToCenterDistance,u_scale_with_map:+("map"===r.paint.get("circle-pitch-scale")),u_pitch_with_map:+n,u_device_pixel_ratio:e.pixelRatio,u_extrude_scale:l,u_globe_extrude_scale:c,u_translate:o}},Di=e=>({u_pixel_extrude_scale:[1/e.width,1/e.height]}),zi=e=>({u_viewport_size:[e.width,e.height]}),Ai=(e,t=1)=>({u_color:e,u_overlay:0,u_overlay_scale:t}),Li=(e,i,r,o)=>{const s=t.at(e,1,i)/(t.X*Math.pow(2,e.tileID.overscaledZ))*2*Math.PI*o;return {u_extrude_scale:t.at(e,1,i),u_intensity:r,u_globe_extrude_scale:s}},ki=(e,i,r,o)=>{const s=t.H();t.bL(s,0,e.width,e.height,0,0,1);const a=e.context.gl;return {u_matrix:s,u_world:[a.drawingBufferWidth,a.drawingBufferHeight],u_image:r,u_color_ramp:o,u_opacity:i.paint.get("heatmap-opacity")}},Fi=(e,t,i)=>{const r=i.paint.get("hillshade-shadow-color"),o=i.paint.get("hillshade-highlight-color"),s=i.paint.get("hillshade-accent-color");let a=i.paint.get("hillshade-illumination-direction")*(Math.PI/180);return "viewport"===i.paint.get("hillshade-illumination-anchor")&&(a+=e.transform.bearingInRadians),{u_image:0,u_latrange:ji(0,t.tileID),u_light:[i.paint.get("hillshade-exaggeration"),a],u_shadow:r,u_highlight:o,u_accent:s}},Bi=(e,i)=>{const r=i.stride,o=t.H();return t.bL(o,0,t.X,-t.X,0,0,1),t.J(o,o,[0,-t.X,0]),{u_matrix:o,u_image:1,u_dimension:[r,r],u_zoom:e.overscaledZ,u_unpack:i.getUnpackVector()}};function ji(e,i){const r=Math.pow(2,i.canonical.z),o=i.canonical.y;return [new t.Y(0,o/r).toLngLat().lat,new t.Y(0,(o+1)/r).toLngLat().lat]}const Oi=(e,i,r,o)=>{const s=e.transform;return {u_translation:Vi(e,i,r),u_ratio:o/t.at(i,1,s.zoom),u_device_pixel_ratio:e.pixelRatio,u_units_to_pixels:[1/s.pixelsToGLUnits[0],1/s.pixelsToGLUnits[1]]}},Ni=(e,i,r,o,s)=>t.e(Oi(e,i,r,o),{u_image:0,u_image_height:s}),Zi=(e,i,r,o,s)=>{const a=e.transform,n=Ui(i,a);return {u_translation:Vi(e,i,r),u_texsize:i.imageAtlasTexture.size,u_ratio:o/t.at(i,1,a.zoom),u_device_pixel_ratio:e.pixelRatio,u_image:0,u_scale:[n,s.fromScale,s.toScale],u_fade:s.t,u_units_to_pixels:[1/a.pixelsToGLUnits[0],1/a.pixelsToGLUnits[1]]}},Gi=(e,i,r,o,s,a)=>{const n=e.lineAtlas,l=Ui(i,e.transform),c="round"===r.layout.get("line-cap"),h=n.getDash(s.from,c),u=n.getDash(s.to,c),d=h.width*a.fromScale,_=u.width*a.toScale;return t.e(Oi(e,i,r,o),{u_patternscale_a:[l/d,-h.height/2],u_patternscale_b:[l/_,-u.height/2],u_sdfgamma:n.width/(256*Math.min(d,_)*e.pixelRatio)/2,u_image:0,u_tex_y_a:h.y,u_tex_y_b:u.y,u_mix:a.t})};function Ui(e,i){return 1/t.at(e,1,i.tileZoom)}function Vi(e,i,r){return t.au(e.transform,i,r.paint.get("line-translate"),r.paint.get("line-translate-anchor"))}const qi=(e,t,i,r,o)=>{return {u_tl_parent:e,u_scale_parent:t,u_buffer_scale:1,u_fade_t:i.mix,u_opacity:i.opacity*r.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:r.paint.get("raster-brightness-min"),u_brightness_high:r.paint.get("raster-brightness-max"),u_saturation_factor:(a=r.paint.get("raster-saturation"),a>0?1-1/(1.001-a):-a),u_contrast_factor:(s=r.paint.get("raster-contrast"),s>0?1/(1-s):1+s),u_spin_weights:Hi(r.paint.get("raster-hue-rotate")),u_coords_top:[o[0].x,o[0].y,o[1].x,o[1].y],u_coords_bottom:[o[3].x,o[3].y,o[2].x,o[2].y]};var s,a;};function Hi(e){e*=Math.PI/180;const t=Math.sin(e),i=Math.cos(e);return [(2*i+1)/3,(-Math.sqrt(3)*t-i+1)/3,(Math.sqrt(3)*t-i+1)/3]}const Wi=(e,t,i,r,o,s,a,n,l,c,h,u,d)=>{const _=a.transform;return {u_is_size_zoom_constant:+("constant"===e||"source"===e),u_is_size_feature_constant:+("constant"===e||"camera"===e),u_size_t:t?t.uSizeT:0,u_size:t?t.uSize:0,u_camera_to_center_distance:_.cameraToCenterDistance,u_pitch:_.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:_.width/_.height,u_fade_change:a.options.fadeDuration?a.symbolFadeChange:1,u_label_plane_matrix:n,u_coord_matrix:l,u_is_text:+h,u_pitch_with_map:+r,u_is_along_line:o,u_is_variable_anchor:s,u_texsize:u,u_texture:0,u_translation:c,u_pitched_scale:d}},Xi=(e,i,r,o,s,a,n,l,c,h,u,d,_,p)=>{const m=n.transform;return t.e(Wi(e,i,r,o,s,a,n,l,c,h,u,d,p),{u_gamma_scale:o?Math.cos(m.pitch*Math.PI/180)*m.cameraToCenterDistance:1,u_device_pixel_ratio:n.pixelRatio,u_is_halo:1})},$i=(e,i,r,o,s,a,n,l,c,h,u,d,_)=>t.e(Xi(e,i,r,o,s,a,n,l,c,h,true,u,true,_),{u_texsize_icon:d,u_texture_icon:1}),Ki=(e,t)=>({u_opacity:e,u_color:t}),Yi=(e,i,r,o,s)=>t.e(function(e,i,r,o){const s=r.imageManager.getPattern(e.from.toString()),a=r.imageManager.getPattern(e.to.toString()),{width:n,height:l}=r.imageManager.getPixelSize(),c=Math.pow(2,o.tileID.overscaledZ),h=o.tileSize*Math.pow(2,r.transform.tileZoom)/c,u=h*(o.tileID.canonical.x+o.tileID.wrap*c),d=h*o.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:s.tl,u_pattern_br_a:s.br,u_pattern_tl_b:a.tl,u_pattern_br_b:a.br,u_texsize:[n,l],u_mix:i.t,u_pattern_size_a:s.displaySize,u_pattern_size_b:a.displaySize,u_scale_a:i.fromScale,u_scale_b:i.toScale,u_tile_units_to_pixels:1/t.at(o,1,r.transform.tileZoom),u_pixel_coord_upper:[u>>16,d>>16],u_pixel_coord_lower:[65535&u,65535&d]}}(r,s,i,o),{u_opacity:e}),Ji=(e,t)=>{},Qi={fillExtrusion:(e,i)=>({u_lightpos:new t.bG(e,i.u_lightpos),u_lightpos_globe:new t.bG(e,i.u_lightpos_globe),u_lightintensity:new t.b5(e,i.u_lightintensity),u_lightcolor:new t.bG(e,i.u_lightcolor),u_vertical_gradient:new t.b5(e,i.u_vertical_gradient),u_opacity:new t.b5(e,i.u_opacity),u_fill_translate:new t.bH(e,i.u_fill_translate)}),fillExtrusionPattern:(e,i)=>({u_lightpos:new t.bG(e,i.u_lightpos),u_lightpos_globe:new t.bG(e,i.u_lightpos_globe),u_lightintensity:new t.b5(e,i.u_lightintensity),u_lightcolor:new t.bG(e,i.u_lightcolor),u_vertical_gradient:new t.b5(e,i.u_vertical_gradient),u_height_factor:new t.b5(e,i.u_height_factor),u_opacity:new t.b5(e,i.u_opacity),u_fill_translate:new t.bH(e,i.u_fill_translate),u_image:new t.bC(e,i.u_image),u_texsize:new t.bH(e,i.u_texsize),u_pixel_coord_upper:new t.bH(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bH(e,i.u_pixel_coord_lower),u_scale:new t.bG(e,i.u_scale),u_fade:new t.b5(e,i.u_fade)}),fill:(e,i)=>({u_fill_translate:new t.bH(e,i.u_fill_translate)}),fillPattern:(e,i)=>({u_image:new t.bC(e,i.u_image),u_texsize:new t.bH(e,i.u_texsize),u_pixel_coord_upper:new t.bH(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bH(e,i.u_pixel_coord_lower),u_scale:new t.bG(e,i.u_scale),u_fade:new t.b5(e,i.u_fade),u_fill_translate:new t.bH(e,i.u_fill_translate)}),fillOutline:(e,i)=>({u_world:new t.bH(e,i.u_world),u_fill_translate:new t.bH(e,i.u_fill_translate)}),fillOutlinePattern:(e,i)=>({u_world:new t.bH(e,i.u_world),u_image:new t.bC(e,i.u_image),u_texsize:new t.bH(e,i.u_texsize),u_pixel_coord_upper:new t.bH(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bH(e,i.u_pixel_coord_lower),u_scale:new t.bG(e,i.u_scale),u_fade:new t.b5(e,i.u_fade),u_fill_translate:new t.bH(e,i.u_fill_translate)}),circle:(e,i)=>({u_camera_to_center_distance:new t.b5(e,i.u_camera_to_center_distance),u_scale_with_map:new t.bC(e,i.u_scale_with_map),u_pitch_with_map:new t.bC(e,i.u_pitch_with_map),u_extrude_scale:new t.bH(e,i.u_extrude_scale),u_device_pixel_ratio:new t.b5(e,i.u_device_pixel_ratio),u_globe_extrude_scale:new t.b5(e,i.u_globe_extrude_scale),u_translate:new t.bH(e,i.u_translate)}),collisionBox:(e,i)=>({u_pixel_extrude_scale:new t.bH(e,i.u_pixel_extrude_scale)}),collisionCircle:(e,i)=>({u_viewport_size:new t.bH(e,i.u_viewport_size)}),debug:(e,i)=>({u_color:new t.bF(e,i.u_color),u_overlay:new t.bC(e,i.u_overlay),u_overlay_scale:new t.b5(e,i.u_overlay_scale)}),depth:Ji,clippingMask:Ji,heatmap:(e,i)=>({u_extrude_scale:new t.b5(e,i.u_extrude_scale),u_intensity:new t.b5(e,i.u_intensity),u_globe_extrude_scale:new t.b5(e,i.u_globe_extrude_scale)}),heatmapTexture:(e,i)=>({u_matrix:new t.bD(e,i.u_matrix),u_world:new t.bH(e,i.u_world),u_image:new t.bC(e,i.u_image),u_color_ramp:new t.bC(e,i.u_color_ramp),u_opacity:new t.b5(e,i.u_opacity)}),hillshade:(e,i)=>({u_image:new t.bC(e,i.u_image),u_latrange:new t.bH(e,i.u_latrange),u_light:new t.bH(e,i.u_light),u_shadow:new t.bF(e,i.u_shadow),u_highlight:new t.bF(e,i.u_highlight),u_accent:new t.bF(e,i.u_accent)}),hillshadePrepare:(e,i)=>({u_matrix:new t.bD(e,i.u_matrix),u_image:new t.bC(e,i.u_image),u_dimension:new t.bH(e,i.u_dimension),u_zoom:new t.b5(e,i.u_zoom),u_unpack:new t.bE(e,i.u_unpack)}),line:(e,i)=>({u_translation:new t.bH(e,i.u_translation),u_ratio:new t.b5(e,i.u_ratio),u_device_pixel_ratio:new t.b5(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bH(e,i.u_units_to_pixels)}),lineGradient:(e,i)=>({u_translation:new t.bH(e,i.u_translation),u_ratio:new t.b5(e,i.u_ratio),u_device_pixel_ratio:new t.b5(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bH(e,i.u_units_to_pixels),u_image:new t.bC(e,i.u_image),u_image_height:new t.b5(e,i.u_image_height)}),linePattern:(e,i)=>({u_translation:new t.bH(e,i.u_translation),u_texsize:new t.bH(e,i.u_texsize),u_ratio:new t.b5(e,i.u_ratio),u_device_pixel_ratio:new t.b5(e,i.u_device_pixel_ratio),u_image:new t.bC(e,i.u_image),u_units_to_pixels:new t.bH(e,i.u_units_to_pixels),u_scale:new t.bG(e,i.u_scale),u_fade:new t.b5(e,i.u_fade)}),lineSDF:(e,i)=>({u_translation:new t.bH(e,i.u_translation),u_ratio:new t.b5(e,i.u_ratio),u_device_pixel_ratio:new t.b5(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bH(e,i.u_units_to_pixels),u_patternscale_a:new t.bH(e,i.u_patternscale_a),u_patternscale_b:new t.bH(e,i.u_patternscale_b),u_sdfgamma:new t.b5(e,i.u_sdfgamma),u_image:new t.bC(e,i.u_image),u_tex_y_a:new t.b5(e,i.u_tex_y_a),u_tex_y_b:new t.b5(e,i.u_tex_y_b),u_mix:new t.b5(e,i.u_mix)}),raster:(e,i)=>({u_tl_parent:new t.bH(e,i.u_tl_parent),u_scale_parent:new t.b5(e,i.u_scale_parent),u_buffer_scale:new t.b5(e,i.u_buffer_scale),u_fade_t:new t.b5(e,i.u_fade_t),u_opacity:new t.b5(e,i.u_opacity),u_image0:new t.bC(e,i.u_image0),u_image1:new t.bC(e,i.u_image1),u_brightness_low:new t.b5(e,i.u_brightness_low),u_brightness_high:new t.b5(e,i.u_brightness_high),u_saturation_factor:new t.b5(e,i.u_saturation_factor),u_contrast_factor:new t.b5(e,i.u_contrast_factor),u_spin_weights:new t.bG(e,i.u_spin_weights),u_coords_top:new t.bE(e,i.u_coords_top),u_coords_bottom:new t.bE(e,i.u_coords_bottom)}),symbolIcon:(e,i)=>({u_is_size_zoom_constant:new t.bC(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bC(e,i.u_is_size_feature_constant),u_size_t:new t.b5(e,i.u_size_t),u_size:new t.b5(e,i.u_size),u_camera_to_center_distance:new t.b5(e,i.u_camera_to_center_distance),u_pitch:new t.b5(e,i.u_pitch),u_rotate_symbol:new t.bC(e,i.u_rotate_symbol),u_aspect_ratio:new t.b5(e,i.u_aspect_ratio),u_fade_change:new t.b5(e,i.u_fade_change),u_label_plane_matrix:new t.bD(e,i.u_label_plane_matrix),u_coord_matrix:new t.bD(e,i.u_coord_matrix),u_is_text:new t.bC(e,i.u_is_text),u_pitch_with_map:new t.bC(e,i.u_pitch_with_map),u_is_along_line:new t.bC(e,i.u_is_along_line),u_is_variable_anchor:new t.bC(e,i.u_is_variable_anchor),u_texsize:new t.bH(e,i.u_texsize),u_texture:new t.bC(e,i.u_texture),u_translation:new t.bH(e,i.u_translation),u_pitched_scale:new t.b5(e,i.u_pitched_scale)}),symbolSDF:(e,i)=>({u_is_size_zoom_constant:new t.bC(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bC(e,i.u_is_size_feature_constant),u_size_t:new t.b5(e,i.u_size_t),u_size:new t.b5(e,i.u_size),u_camera_to_center_distance:new t.b5(e,i.u_camera_to_center_distance),u_pitch:new t.b5(e,i.u_pitch),u_rotate_symbol:new t.bC(e,i.u_rotate_symbol),u_aspect_ratio:new t.b5(e,i.u_aspect_ratio),u_fade_change:new t.b5(e,i.u_fade_change),u_label_plane_matrix:new t.bD(e,i.u_label_plane_matrix),u_coord_matrix:new t.bD(e,i.u_coord_matrix),u_is_text:new t.bC(e,i.u_is_text),u_pitch_with_map:new t.bC(e,i.u_pitch_with_map),u_is_along_line:new t.bC(e,i.u_is_along_line),u_is_variable_anchor:new t.bC(e,i.u_is_variable_anchor),u_texsize:new t.bH(e,i.u_texsize),u_texture:new t.bC(e,i.u_texture),u_gamma_scale:new t.b5(e,i.u_gamma_scale),u_device_pixel_ratio:new t.b5(e,i.u_device_pixel_ratio),u_is_halo:new t.bC(e,i.u_is_halo),u_translation:new t.bH(e,i.u_translation),u_pitched_scale:new t.b5(e,i.u_pitched_scale)}),symbolTextAndIcon:(e,i)=>({u_is_size_zoom_constant:new t.bC(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bC(e,i.u_is_size_feature_constant),u_size_t:new t.b5(e,i.u_size_t),u_size:new t.b5(e,i.u_size),u_camera_to_center_distance:new t.b5(e,i.u_camera_to_center_distance),u_pitch:new t.b5(e,i.u_pitch),u_rotate_symbol:new t.bC(e,i.u_rotate_symbol),u_aspect_ratio:new t.b5(e,i.u_aspect_ratio),u_fade_change:new t.b5(e,i.u_fade_change),u_label_plane_matrix:new t.bD(e,i.u_label_plane_matrix),u_coord_matrix:new t.bD(e,i.u_coord_matrix),u_is_text:new t.bC(e,i.u_is_text),u_pitch_with_map:new t.bC(e,i.u_pitch_with_map),u_is_along_line:new t.bC(e,i.u_is_along_line),u_is_variable_anchor:new t.bC(e,i.u_is_variable_anchor),u_texsize:new t.bH(e,i.u_texsize),u_texsize_icon:new t.bH(e,i.u_texsize_icon),u_texture:new t.bC(e,i.u_texture),u_texture_icon:new t.bC(e,i.u_texture_icon),u_gamma_scale:new t.b5(e,i.u_gamma_scale),u_device_pixel_ratio:new t.b5(e,i.u_device_pixel_ratio),u_is_halo:new t.bC(e,i.u_is_halo),u_translation:new t.bH(e,i.u_translation),u_pitched_scale:new t.b5(e,i.u_pitched_scale)}),background:(e,i)=>({u_opacity:new t.b5(e,i.u_opacity),u_color:new t.bF(e,i.u_color)}),backgroundPattern:(e,i)=>({u_opacity:new t.b5(e,i.u_opacity),u_image:new t.bC(e,i.u_image),u_pattern_tl_a:new t.bH(e,i.u_pattern_tl_a),u_pattern_br_a:new t.bH(e,i.u_pattern_br_a),u_pattern_tl_b:new t.bH(e,i.u_pattern_tl_b),u_pattern_br_b:new t.bH(e,i.u_pattern_br_b),u_texsize:new t.bH(e,i.u_texsize),u_mix:new t.b5(e,i.u_mix),u_pattern_size_a:new t.bH(e,i.u_pattern_size_a),u_pattern_size_b:new t.bH(e,i.u_pattern_size_b),u_scale_a:new t.b5(e,i.u_scale_a),u_scale_b:new t.b5(e,i.u_scale_b),u_pixel_coord_upper:new t.bH(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bH(e,i.u_pixel_coord_lower),u_tile_units_to_pixels:new t.b5(e,i.u_tile_units_to_pixels)}),terrain:(e,i)=>({u_texture:new t.bC(e,i.u_texture),u_ele_delta:new t.b5(e,i.u_ele_delta),u_fog_matrix:new t.bD(e,i.u_fog_matrix),u_fog_color:new t.bF(e,i.u_fog_color),u_fog_ground_blend:new t.b5(e,i.u_fog_ground_blend),u_fog_ground_blend_opacity:new t.b5(e,i.u_fog_ground_blend_opacity),u_horizon_color:new t.bF(e,i.u_horizon_color),u_horizon_fog_blend:new t.b5(e,i.u_horizon_fog_blend),u_is_globe_mode:new t.b5(e,i.u_is_globe_mode)}),terrainDepth:(e,i)=>({u_ele_delta:new t.b5(e,i.u_ele_delta)}),terrainCoords:(e,i)=>({u_texture:new t.bC(e,i.u_texture),u_terrain_coords_id:new t.b5(e,i.u_terrain_coords_id),u_ele_delta:new t.b5(e,i.u_ele_delta)}),projectionErrorMeasurement:(e,i)=>({u_input:new t.b5(e,i.u_input),u_output_expected:new t.b5(e,i.u_output_expected)}),atmosphere:(e,i)=>({u_sun_pos:new t.bG(e,i.u_sun_pos),u_atmosphere_blend:new t.b5(e,i.u_atmosphere_blend),u_globe_position:new t.bG(e,i.u_globe_position),u_globe_radius:new t.b5(e,i.u_globe_radius),u_inv_proj_matrix:new t.bD(e,i.u_inv_proj_matrix)}),sky:(e,i)=>({u_sky_color:new t.bF(e,i.u_sky_color),u_horizon_color:new t.bF(e,i.u_horizon_color),u_horizon:new t.bH(e,i.u_horizon),u_horizon_normal:new t.bH(e,i.u_horizon_normal),u_sky_horizon_blend:new t.b5(e,i.u_sky_horizon_blend),u_sky_blend:new t.b5(e,i.u_sky_blend)})};class er{constructor(e,t,i){this.context=e;const r=e.gl;this.buffer=r.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),e.bindElementBuffer.set(this.buffer),r.bufferData(r.ELEMENT_ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?r.DYNAMIC_DRAW:r.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindElementBuffer.set(this.buffer);}updateData(e){const t=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO(),this.bind(),t.bufferSubData(t.ELEMENT_ARRAY_BUFFER,0,e.arrayBuffer);}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);}}const tr={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class ir{constructor(e,t,i,r){this.length=t.length,this.attributes=i,this.itemSize=t.bytesPerElement,this.dynamicDraw=r,this.context=e;const o=e.gl;this.buffer=o.createBuffer(),e.bindVertexBuffer.set(this.buffer),o.bufferData(o.ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindVertexBuffer.set(this.buffer);}updateData(e){if(e.length!==this.length)throw new Error(`Length of new data is ${e.length}, which doesn't match current length of ${this.length}`);const t=this.context.gl;this.bind(),t.bufferSubData(t.ARRAY_BUFFER,0,e.arrayBuffer);}enableAttributes(e,t){for(let i=0;i0&&(h.push({circleArray:f,circleOffset:d,coord:_}),u+=f.length/4,d=u),m&&c.draw(a,l.LINES,Ot.disabled,Zt.disabled,e.colorModeForRenderPass(),jt.disabled,Di(e.transform),e.style.map.terrain&&e.style.map.terrain.getTerrainData(_),n.getProjectionData({overscaledTileID:_,applyGlobeMatrix:true,applyTerrainMatrix:true}),r.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,null,e.transform.zoom,null,null,m.collisionVertexBuffer);}if(!s||!h.length)return;const _=e.useProgram("collisionCircle"),p=new t.bM;p.resize(4*u),p._trim();let m=0;for(const e of h)for(let t=0;t=0&&(f[g.associatedIconIndex]={shiftedAnchor:M,angle:S});}else Be(g.numGlyphs,p);}if(c){m.clear();const i=e.icon.placedSymbolArray;for(let e=0;ee.style.map.terrain.getElevation(l,t,i):null,i="map"===r.layout.get("text-rotation-alignment");Pe(c,e,s,j,O,v,h,i,l.toUnwrapped(),f.width,f.height,Z,t);}const q=s&&P||V,H=x||q?Vr:v?j:e.transform.clipSpaceToPixelsMatrix,W=p&&0!==r.paint.get(s?"text-halo-width":"icon-halo-width").constantOr(1);let X;X=p?c.iconsInText?$i(T.kind,S,b,v,x,q,e,H,N,Z,D,k,I):Xi(T.kind,S,b,v,x,q,e,H,N,Z,s,D,true,I):Wi(T.kind,S,b,v,x,q,e,H,N,Z,s,D,I);const $={program:M,buffers:u,uniformValues:X,projectionData:G,atlasTexture:z,atlasTextureIcon:F,atlasInterpolation:A,atlasInterpolationIcon:L,isSDF:p,hasHalo:W};if(y&&c.canOverlap){w=true;const e=u.segments.get();for(const i of e)C.push({segments:new t.aD([i]),sortKey:i.sortKey,state:$,terrainData:R});}else C.push({segments:u.segments,sortKey:0,state:$,terrainData:R});}w&&C.sort(((e,t)=>e.sortKey-t.sortKey));for(const t of C){const i=t.state;if(p.activeTexture.set(m.TEXTURE0),i.atlasTexture.bind(i.atlasInterpolation,m.CLAMP_TO_EDGE),i.atlasTextureIcon&&(p.activeTexture.set(m.TEXTURE1),i.atlasTextureIcon&&i.atlasTextureIcon.bind(i.atlasInterpolationIcon,m.CLAMP_TO_EDGE)),i.isSDF){const o=i.uniformValues;i.hasHalo&&(o.u_is_halo=1,Kr(i.buffers,t.segments,r,e,i.program,T,u,d,o,i.projectionData,t.terrainData)),o.u_is_halo=0;}Kr(i.buffers,t.segments,r,e,i.program,T,u,d,i.uniformValues,i.projectionData,t.terrainData);}}function Kr(e,t,i,r,o,s,a,n,l,c,h){const u=r.context;o.draw(u,u.gl.TRIANGLES,s,a,n,jt.backCCW,l,h,c,i.id,e.layoutVertexBuffer,e.indexBuffer,t,i.paint,r.transform.zoom,e.programConfigurations.get(i.id),e.dynamicLayoutVertexBuffer,e.opacityVertexBuffer);}function Yr(e,i,r,o,s){const a=e.context,n=a.gl,l=Zt.disabled,c=new Ft([n.ONE,n.ONE],t.b4.transparent,[true,true,true,true]),h=i.getBucket(r);if(!h)return;const u=o.key;let d=r.heatmapFbos.get(u);d||(d=Qr(a,i.tileSize,i.tileSize),r.heatmapFbos.set(u,d)),a.bindFramebuffer.set(d.framebuffer),a.viewport.set([0,0,i.tileSize,i.tileSize]),a.clear({color:t.b4.transparent});const _=h.programConfigurations.get(r.id),p=e.useProgram("heatmap",_,!s),m=e.transform.getProjectionData({overscaledTileID:i.tileID,applyGlobeMatrix:true,applyTerrainMatrix:true}),f=e.style.map.terrain.getTerrainData(o);p.draw(a,n.TRIANGLES,Ot.disabled,l,c,jt.disabled,Li(i,e.transform.zoom,r.paint.get("heatmap-intensity"),1),f,m,r.id,h.layoutVertexBuffer,h.indexBuffer,h.segments,r.paint,e.transform.zoom,_);}function Jr(e,t,i,r,o){const s=e.context,a=s.gl,n=e.transform;s.setColorMode(e.colorModeForRenderPass());const l=eo(s,t),c=i.key,h=t.heatmapFbos.get(c);if(!h)return;s.activeTexture.set(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,h.colorAttachment.get()),s.activeTexture.set(a.TEXTURE1),l.bind(a.LINEAR,a.CLAMP_TO_EDGE);const u=n.getProjectionData({overscaledTileID:i,applyTerrainMatrix:o,applyGlobeMatrix:!r});e.useProgram("heatmapTexture").draw(s,a.TRIANGLES,Ot.disabled,Zt.disabled,e.colorModeForRenderPass(),jt.disabled,ki(e,t,0,1),null,u,t.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments,t.paint,n.zoom),h.destroy(),t.heatmapFbos.delete(c);}function Qr(e,t,i){var r,o;const s=e.gl,a=s.createTexture();s.bindTexture(s.TEXTURE_2D,a),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR);const n=null!==(r=e.HALF_FLOAT)&&undefined!==r?r:s.UNSIGNED_BYTE,l=null!==(o=e.RGBA16F)&&undefined!==o?o:s.RGBA;s.texImage2D(s.TEXTURE_2D,0,l,t,i,0,s.RGBA,n,null);const c=e.createFramebuffer(t,i,false,false);return c.colorAttachment.set(a),c}function eo(e,t){return t.colorRampTexture||(t.colorRampTexture=new v(e,t.colorRamp,e.gl.RGBA)),t.colorRampTexture}function to(e,t,i,r,o){if(!i||!r||!r.imageAtlas)return;const s=r.imageAtlas.patternPositions;let a=s[i.to.toString()],n=s[i.from.toString()];if(!a&&n&&(a=n),!n&&a&&(n=a),!a||!n){const e=o.getPaintProperty(t);a=s[e],n=s[e];}a&&n&&e.setConstantPatternPositions(a,n);}function io(e,i,r,o,s,a,n,l){const c=e.context.gl,h="fill-pattern",u=r.paint.get(h),d=u&&u.constantOr(1),_=r.getCrossfadeParameters();let p,m,f,g,v;const x=e.transform,b=r.paint.get("fill-translate"),y=r.paint.get("fill-translate-anchor");n?(m=d&&!r.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",p=c.LINES):(m=d?"fillPattern":"fill",p=c.TRIANGLES);const w=u.constantOr(null);for(const u of o){const T=i.getTile(u);if(d&&!T.patternsLoaded())continue;const P=T.getBucket(r);if(!P)continue;const C=P.programConfigurations.get(r.id),I=e.useProgram(m,C),E=e.style.map.terrain&&e.style.map.terrain.getTerrainData(u);d&&(e.context.activeTexture.set(c.TEXTURE0),T.imageAtlasTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE),C.updatePaintBuffers(_)),to(C,h,w,T,r);const M=x.getProjectionData({overscaledTileID:u,applyGlobeMatrix:!l,applyTerrainMatrix:true}),S=t.au(x,T,b,y);if(n){g=P.indexBuffer2,v=P.segments2;const t=[c.drawingBufferWidth,c.drawingBufferHeight];f="fillOutlinePattern"===m&&d?Si(e,_,T,t,S):Mi(t,S);}else g=P.indexBuffer,v=P.segments,f=d?Ei(e,_,T,S):{u_fill_translate:S};let R;if("translucent"===e.renderPass&&l){const[t]=e.getStencilConfigForOverlapAndUpdateStencilID(o);R=t[u.overscaledZ];}else R=e.stencilModeForClipping(u);I.draw(e.context,p,s,R,a,jt.backCCW,f,E,M,r.id,P.layoutVertexBuffer,g,v,r.paint,e.transform.zoom,C);}}function ro(e,i,r,o,s,a,n,l){const c=e.context,h=c.gl,u="fill-extrusion-pattern",d=r.paint.get(u),_=d.constantOr(1),p=r.getCrossfadeParameters(),m=r.paint.get("fill-extrusion-opacity"),f=d.constantOr(null),g=e.transform;for(const d of o){const o=i.getTile(d),v=o.getBucket(r);if(!v)continue;const x=e.style.map.terrain&&e.style.map.terrain.getTerrainData(d),b=v.programConfigurations.get(r.id),y=e.useProgram(_?"fillExtrusionPattern":"fillExtrusion",b);_&&(e.context.activeTexture.set(h.TEXTURE0),o.imageAtlasTexture.bind(h.LINEAR,h.CLAMP_TO_EDGE),b.updatePaintBuffers(p));const w=g.getProjectionData({overscaledTileID:d,applyGlobeMatrix:!l,applyTerrainMatrix:true});to(b,u,f,o,r);const T=t.au(g,o,r.paint.get("fill-extrusion-translate"),r.paint.get("fill-extrusion-translate-anchor")),P=r.paint.get("fill-extrusion-vertical-gradient"),C=_?Ii(e,P,m,T,d,p,o):Ci(e,P,m,T);y.draw(c,c.gl.TRIANGLES,s,a,n,jt.backCCW,C,x,w,r.id,v.layoutVertexBuffer,v.indexBuffer,v.segments,r.paint,e.transform.zoom,b,e.style.map.terrain&&v.centroidVertexBuffer);}}function oo(e,t,i,r,o,s,a,n,l){var c;const h=e.style.projection,u=e.context,d=e.transform,_=u.gl,p=e.useProgram("hillshade"),m=!e.options.moving;for(const f of r){const r=t.getTile(f),g=r.fbo;if(!g)continue;const v=h.getMeshFromTileID(u,f.canonical,n,true,"raster"),x=null===(c=e.style.map.terrain)||undefined===c?undefined:c.getTerrainData(f);u.activeTexture.set(_.TEXTURE0),_.bindTexture(_.TEXTURE_2D,g.colorAttachment.get());const b=d.getProjectionData({overscaledTileID:f,aligned:m,applyGlobeMatrix:!l,applyTerrainMatrix:true});p.draw(u,_.TRIANGLES,s,o[f.overscaledZ],a,jt.backCCW,Fi(e,r,i),x,b,i.id,v.vertexBuffer,v.indexBuffer,v.segments);}}const so=[new t.P(0,0),new t.P(t.X,0),new t.P(t.X,t.X),new t.P(0,t.X)];function ao(e,t,i,r,o,s,a,n,l=false,c=false){const h=r[r.length-1].overscaledZ,u=e.context,d=u.gl,_=e.useProgram("raster"),p=e.transform,m=e.style.projection,f=e.colorModeForRenderPass(),g=!e.options.moving;for(const v of r){const r=e.getDepthModeForSublayer(v.overscaledZ-h,1===i.paint.get("raster-opacity")?Ot.ReadWrite:Ot.ReadOnly,d.LESS),x=t.getTile(v);x.registerFadeDuration(i.paint.get("raster-fade-duration"));const b=t.findLoadedParent(v,0),y=t.findLoadedSibling(v),w=no(x,b||y||null,t,i,e.transform,e.style.map.terrain);let T,P;const C="nearest"===i.paint.get("raster-resampling")?d.NEAREST:d.LINEAR;u.activeTexture.set(d.TEXTURE0),x.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),u.activeTexture.set(d.TEXTURE1),b?(b.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),T=Math.pow(2,b.tileID.overscaledZ-x.tileID.overscaledZ),P=[x.tileID.canonical.x*T%1,x.tileID.canonical.y*T%1]):x.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),x.texture.useMipmap&&u.extTextureFilterAnisotropic&&e.transform.pitch>20&&d.texParameterf(d.TEXTURE_2D,u.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,u.extTextureFilterAnisotropicMax);const I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(v),E=p.getProjectionData({overscaledTileID:v,aligned:g,applyGlobeMatrix:!c,applyTerrainMatrix:true}),M=qi(P||[0,0],T||1,w,i,n),S=m.getMeshFromTileID(u,v.canonical,s,a,"raster");_.draw(u,d.TRIANGLES,r,o?o[v.overscaledZ]:Zt.disabled,f,l?jt.frontCCW:jt.backCCW,M,I,E,i.id,S.vertexBuffer,S.indexBuffer,S.segments);}}function no(e,i,r,o,s,n){const l=o.paint.get("raster-fade-duration");if(!n&&l>0){const o=a.now(),n=(o-e.timeAdded)/l,c=i?(o-i.timeAdded)/l:-1,h=r.getSource(),u=he(s,{tileSize:h.tileSize,roundZoom:h.roundZoom}),d=!i||Math.abs(i.tileID.overscaledZ-u)>Math.abs(e.tileID.overscaledZ-u),_=d&&e.refreshedUponExpiration?1:t.ab(d?n:1-c,0,1);return e.refreshedUponExpiration&&n>=1&&(e.refreshedUponExpiration=false),i?{opacity:1,mix:1-_}:{opacity:_,mix:0}}return {opacity:1,mix:0}}const lo=new t.b4(1,0,0,1),co=new t.b4(0,1,0,1),ho=new t.b4(0,0,1,1),uo=new t.b4(1,0,1,1),_o=new t.b4(0,1,1,1);function po(e,t,i,r){fo(e,0,t+i/2,e.transform.width,i,r);}function mo(e,t,i,r){fo(e,t-i/2,0,i,e.transform.height,r);}function fo(e,t,i,r,o,s){const a=e.context,n=a.gl;n.enable(n.SCISSOR_TEST),n.scissor(t*e.pixelRatio,i*e.pixelRatio,r*e.pixelRatio,o*e.pixelRatio),a.clear({color:s}),n.disable(n.SCISSOR_TEST);}function go(e,i,r){const o=e.context,s=o.gl,a=e.useProgram("debug"),n=Ot.disabled,l=Zt.disabled,c=e.colorModeForRenderPass(),h="$debug",u=e.style.map.terrain&&e.style.map.terrain.getTerrainData(r);o.activeTexture.set(s.TEXTURE0);const d=i.getTileByID(r.key).latestRawTileData,_=Math.floor((d&&d.byteLength||0)/1024),p=i.getTile(r).tileSize,m=512/Math.min(p,512)*(r.overscaledZ/e.transform.zoom)*.5;let f=r.canonical.toString();r.overscaledZ!==r.canonical.z&&(f+=` => ${r.overscaledZ}`),function(e,t){e.initDebugOverlayCanvas();const i=e.debugOverlayCanvas,r=e.context.gl,o=e.debugOverlayCanvas.getContext("2d");o.clearRect(0,0,i.width,i.height),o.shadowColor="white",o.shadowBlur=2,o.lineWidth=1.5,o.strokeStyle="white",o.textBaseline="top",o.font="bold 36px Open Sans, sans-serif",o.fillText(t,5,5),o.strokeText(t,5,5),e.debugOverlayTexture.update(i),e.debugOverlayTexture.bind(r.LINEAR,r.CLAMP_TO_EDGE);}(e,`${f} ${_}kB`);const g=e.transform.getProjectionData({overscaledTileID:r,applyGlobeMatrix:true,applyTerrainMatrix:true});a.draw(o,s.TRIANGLES,n,l,Ft.alphaBlended,jt.disabled,Ai(t.b4.transparent,m),null,g,h,e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments),a.draw(o,s.LINE_STRIP,n,l,c,jt.disabled,Ai(t.b4.red),u,g,h,e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments);}function vo(e,t,i,r){const{isRenderingGlobe:o}=r,s=e.context,a=s.gl,n=e.transform,l=e.colorModeForRenderPass(),c=e.getDepthModeFor3D(),h=e.useProgram("terrain");s.bindFramebuffer.set(null),s.viewport.set([0,0,e.width,e.height]);for(const r of i){const i=t.getTerrainMesh(r.tileID),u=e.renderToTexture.getTexture(r),d=t.getTerrainData(r.tileID);s.activeTexture.set(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,u.texture);const _=t.getMeshFrameDelta(n.zoom),p=n.calculateFogMatrix(r.tileID.toUnwrapped()),m=bi(_,p,e.style.sky,n.pitch,o),f=n.getProjectionData({overscaledTileID:r.tileID,applyTerrainMatrix:false,applyGlobeMatrix:true});h.draw(s,a.TRIANGLES,c,Zt.disabled,l,jt.backCCW,m,d,f,"terrain",i.vertexBuffer,i.indexBuffer,i.segments);}}function xo(e,i){if(!i.mesh){const r=new t.aC;r.emplaceBack(-1,-1),r.emplaceBack(1,-1),r.emplaceBack(1,1),r.emplaceBack(-1,1);const o=new t.aE;o.emplaceBack(0,1,2),o.emplaceBack(0,2,3),i.mesh=new pt(e.createVertexBuffer(r,mt.members),e.createIndexBuffer(o),t.aD.simpleSegment(0,0,r.length,o.length));}return i.mesh}class bo{constructor(e,i){this.context=new Zr(e),this.transform=i,this._tileTextures={},this.terrainFacilitator={dirty:true,matrix:t.aq(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=de.maxUnderzooming+de.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new ht;}resize(e,t,i){if(this.width=Math.floor(e*i),this.height=Math.floor(t*i),this.pixelRatio=i,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const e of this.style._order)this.style._layers[e].resize();}setup(){const e=this.context,i=new t.aC;i.emplaceBack(0,0),i.emplaceBack(t.X,0),i.emplaceBack(0,t.X),i.emplaceBack(t.X,t.X),this.tileExtentBuffer=e.createVertexBuffer(i,mt.members),this.tileExtentSegments=t.aD.simpleSegment(0,0,4,2);const r=new t.aC;r.emplaceBack(0,0),r.emplaceBack(t.X,0),r.emplaceBack(0,t.X),r.emplaceBack(t.X,t.X),this.debugBuffer=e.createVertexBuffer(r,mt.members),this.debugSegments=t.aD.simpleSegment(0,0,4,5);const o=new t.bT;o.emplaceBack(0,0,0,0),o.emplaceBack(t.X,0,t.X,0),o.emplaceBack(0,t.X,0,t.X),o.emplaceBack(t.X,t.X,t.X,t.X),this.rasterBoundsBuffer=e.createVertexBuffer(o,vi.members),this.rasterBoundsSegments=t.aD.simpleSegment(0,0,4,2);const s=new t.aC;s.emplaceBack(0,0),s.emplaceBack(t.X,0),s.emplaceBack(0,t.X),s.emplaceBack(t.X,t.X),this.rasterBoundsBufferPosOnly=e.createVertexBuffer(s,mt.members),this.rasterBoundsSegmentsPosOnly=t.aD.simpleSegment(0,0,4,5);const a=new t.aC;a.emplaceBack(0,0),a.emplaceBack(1,0),a.emplaceBack(0,1),a.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(a,mt.members),this.viewportSegments=t.aD.simpleSegment(0,0,4,2);const n=new t.bU;n.emplaceBack(0),n.emplaceBack(1),n.emplaceBack(3),n.emplaceBack(2),n.emplaceBack(0),this.tileBorderIndexBuffer=e.createIndexBuffer(n);const l=new t.aE;l.emplaceBack(1,0,2),l.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(l);const c=this.context.gl;this.stencilClearMode=new Zt({func:c.ALWAYS,mask:0},0,255,c.ZERO,c.ZERO,c.ZERO),this.tileExtentMesh=new pt(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments);}clearStencil(){const e=this.context,i=e.gl;this.nextStencilID=1,this.currentStencilSource=undefined;const r=t.H();t.bL(r,0,this.width,this.height,0,0,1),t.K(r,r,[i.drawingBufferWidth,i.drawingBufferHeight,0]);const o={mainMatrix:r,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:r};this.useProgram("clippingMask",null,true).draw(e,i.TRIANGLES,Ot.disabled,this.stencilClearMode,Ft.disabled,jt.disabled,null,null,o,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments);}_renderTileClippingMasks(e,t,i){if(this.currentStencilSource===e.source||!e.isTileClipped()||!t||!t.length)return;this.currentStencilSource=e.source,this.nextStencilID+t.length>256&&this.clearStencil();const r=this.context;r.setColorMode(Ft.disabled),r.setDepthMode(Ot.disabled);const o={};for(const e of t)o[e.key]=this.nextStencilID++;this._renderTileMasks(o,t,i,true),this._renderTileMasks(o,t,i,false),this._tileClippingMaskIDs=o;}_renderTileMasks(e,t,i,r){const o=this.context,s=o.gl,a=this.style.projection,n=this.transform,l=this.useProgram("clippingMask");for(const c of t){const t=e[c.key],h=this.style.map.terrain&&this.style.map.terrain.getTerrainData(c),u=a.getMeshFromTileID(this.context,c.canonical,r,true,"stencil"),d=n.getProjectionData({overscaledTileID:c,applyGlobeMatrix:true,applyTerrainMatrix:true});l.draw(o,s.TRIANGLES,Ot.disabled,new Zt({func:s.ALWAYS,mask:0},t,255,s.KEEP,s.KEEP,s.REPLACE),Ft.disabled,i?jt.disabled:jt.backCCW,null,h,d,"$clipping",u.vertexBuffer,u.indexBuffer,u.segments);}}_renderTilesDepthBuffer(){const e=this.context,t=e.gl,i=this.style.projection,r=this.transform,o=this.useProgram("depth"),s=this.getDepthModeFor3D(),a=ue(r,{tileSize:r.tileSize});for(const n of a){const a=this.style.map.terrain&&this.style.map.terrain.getTerrainData(n),l=i.getMeshFromTileID(this.context,n.canonical,true,true,"raster"),c=r.getProjectionData({overscaledTileID:n,applyGlobeMatrix:true,applyTerrainMatrix:true});o.draw(e,t.TRIANGLES,s,Zt.disabled,Ft.disabled,jt.backCCW,null,a,c,"$clipping",l.vertexBuffer,l.indexBuffer,l.segments);}}stencilModeFor3D(){this.currentStencilSource=undefined,this.nextStencilID+1>256&&this.clearStencil();const e=this.nextStencilID++,t=this.context.gl;return new Zt({func:t.NOTEQUAL,mask:255},e,255,t.KEEP,t.KEEP,t.REPLACE)}stencilModeForClipping(e){const t=this.context.gl;return new Zt({func:t.EQUAL,mask:255},this._tileClippingMaskIDs[e.key],0,t.KEEP,t.KEEP,t.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(e){const t=this.context.gl,i=e.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),r=i[i.length-1].overscaledZ,o=i[0].overscaledZ-r+1;if(o>1){this.currentStencilSource=undefined,this.nextStencilID+o>256&&this.clearStencil();const e={};for(let i=0;it.overscaledZ-e.overscaledZ)),r=i[i.length-1].overscaledZ,o=i[0].overscaledZ-r+1;if(this.clearStencil(),o>1){const e={},s={};for(let i=0;i0};for(const e in n){const t=n[e];t.used&&t.prepare(this.context),l[e]=t.getVisibleCoordinates(false),c[e]=l[e].slice().reverse(),h[e]=t.getVisibleCoordinates(true).reverse();}this.opaquePassCutoff=1/0;for(let e=0;ethis.useProgram(e)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:i.showOverdrawInspector?t.b4.black:t.b4.transparent,depth:1}),this.clearStencil(),this.style.sky&&function(e,t){const i=e.context,r=i.gl,o=((e,t,i)=>{const r=Math.cos(t.rollInRadians),o=Math.sin(t.rollInRadians),s=yt(t),a=t.getProjectionData({overscaledTileID:null,applyGlobeMatrix:true,applyTerrainMatrix:true}).projectionTransition;return {u_sky_color:e.properties.get("sky-color"),u_horizon_color:e.properties.get("horizon-color"),u_horizon:[(t.width/2-s*o)*i,(t.height/2+s*r)*i],u_horizon_normal:[-o,r],u_sky_horizon_blend:e.properties.get("sky-horizon-blend")*t.height/2*i,u_sky_blend:a}})(t,e.style.map.transform,e.pixelRatio),s=new Ot(r.LEQUAL,Ot.ReadWrite,[0,1]),a=Zt.disabled,n=e.colorModeForRenderPass(),l=e.useProgram("sky"),c=xo(i,t);l.draw(i,r.TRIANGLES,s,a,n,jt.disabled,o,null,undefined,"sky",c.vertexBuffer,c.indexBuffer,c.segments);}(this,this.style.sky),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRangeFor3D=[0,1-(e._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=s.length-1;this.currentLayer>=0;this.currentLayer--){const e=this.style._layers[s[this.currentLayer]],t=n[e.source],i=l[e.source];this._renderTileClippingMasks(e,i,false),this.renderLayer(this,t,e,i,u);}this.renderPass="translucent";let d=false;for(this.currentLayer=0;this.currentLayer({u_sun_pos:e,u_atmosphere_blend:t,u_globe_position:i,u_globe_radius:r,u_inv_proj_matrix:o}))(c,u,[p[0],p[1],p[2]],d,_),f=xo(o,i);a.draw(o,s.TRIANGLES,n,Zt.disabled,Ft.alphaBlended,jt.disabled,m,null,null,"atmosphere",f.vertexBuffer,f.indexBuffer,f.segments);}(this,this.style.sky,this.style.light),this.options.showTileBoundaries){const e=function(e,t){let i=null;const r=Object.values(e._layers).flatMap((i=>i.source&&!i.isHidden(t)?[e.sourceCaches[i.source]]:[])),o=r.filter((e=>"vector"===e.getSource().type)),s=r.filter((e=>"vector"!==e.getSource().type)),a=e=>{(!i||i.getSource().maxzooma(e))),i||s.forEach((e=>a(e))),i}(this.style,this.transform.zoom);e&&function(e,t,i){for(let r=0;ru.getElevation(s,e,t):null;Wr(a,d,_,c,h,f,i,p,g,t.au(h,e,n,l),s.toUnwrapped(),r);}}}(o,e,r,i,r.layout.get("text-rotation-alignment"),r.layout.get("text-pitch-alignment"),r.paint.get("text-translate"),r.paint.get("text-translate-anchor"),s),0!==r.paint.get("icon-opacity").constantOr(1)&&$r(e,i,r,o,false,r.paint.get("icon-translate"),r.paint.get("icon-translate-anchor"),r.layout.get("icon-rotation-alignment"),r.layout.get("icon-pitch-alignment"),r.layout.get("icon-keep-upright"),l,c,n),0!==r.paint.get("text-opacity").constantOr(1)&&$r(e,i,r,o,true,r.paint.get("text-translate"),r.paint.get("text-translate-anchor"),r.layout.get("text-rotation-alignment"),r.layout.get("text-pitch-alignment"),r.layout.get("text-keep-upright"),l,c,n),i.map.showCollisionBoxes&&(Ur(e,i,r,o,true),Ur(e,i,r,o,false));}(e,i,r,o,this.style.placement.variableOffsets,s):t.bZ(r)?function(e,i,r,o,s){if("translucent"!==e.renderPass)return;const{isRenderingToTexture:a}=s,n=r.paint.get("circle-opacity"),l=r.paint.get("circle-stroke-width"),c=r.paint.get("circle-stroke-opacity"),h=!r.layout.get("circle-sort-key").isConstant();if(0===n.constantOr(1)&&(0===l.constantOr(1)||0===c.constantOr(1)))return;const u=e.context,d=u.gl,_=e.transform,p=e.getDepthModeForSublayer(0,Ot.ReadOnly),m=Zt.disabled,f=e.colorModeForRenderPass(),g=[],v=_.getCircleRadiusCorrection();for(let s=0;se.sortKey-t.sortKey));for(const t of g){const{programConfiguration:i,program:o,layoutVertexBuffer:s,indexBuffer:a,uniformValues:n,terrainData:l,projectionData:c}=t.state;o.draw(u,d.TRIANGLES,p,m,f,jt.backCCW,n,l,c,r.id,s,a,t.segments,r.paint,e.transform.zoom,i);}}(e,i,r,o,s):t.b_(r)?function(e,i,r,o,s){if(0===r.paint.get("heatmap-opacity"))return;const a=e.context,{isRenderingToTexture:n,isRenderingGlobe:l}=s;if(e.style.map.terrain){for(const t of o){const o=i.getTile(t);i.hasRenderableParent(t)||("offscreen"===e.renderPass?Yr(e,o,r,t,l):"translucent"===e.renderPass&&Jr(e,r,t,n,l));}a.viewport.set([0,0,e.width,e.height]);}else "offscreen"===e.renderPass?function(e,i,r,o){const s=e.context,a=s.gl,n=e.transform,l=Zt.disabled,c=new Ft([a.ONE,a.ONE],t.b4.transparent,[true,true,true,true]);(((function(e,i,r){const o=e.gl;e.activeTexture.set(o.TEXTURE1),e.viewport.set([0,0,i.width/4,i.height/4]);let s=r.heatmapFbos.get(t.bP);s?(o.bindTexture(o.TEXTURE_2D,s.colorAttachment.get()),e.bindFramebuffer.set(s.framebuffer)):(s=Qr(e,i.width/4,i.height/4),r.heatmapFbos.set(t.bP,s));})))(s,e,r),s.clear({color:t.b4.transparent});for(let t=0;t0?t.pop():null}isPatternMissing(e){if(!e)return false;if(!e.from||!e.to)return true;const t=this.imageManager.getPattern(e.from.toString()),i=this.imageManager.getPattern(e.to.toString());return !t||!i}useProgram(e,t,i=false){this.cache=this.cache||{};const r=!!this.style.map.terrain,o=this.style.projection,s=e+(t?t.cacheKey:"")+`/${i?gt:o.shaderVariantName}`+(this._showOverdrawInspector?"/overdraw":"")+(r?"/terrain":"");return this.cache[s]||(this.cache[s]=new Ti(this.context,dt[e],t,Qi[e],this._showOverdrawInspector,r,i?dt.projectionMercator:o.shaderPreludeCode,i?ft:o.shaderDefine)),this.cache[s]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault();}setBaseState(){const e=this.context.gl;this.context.cullFace.set(false),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(e.FUNC_ADD);}initDebugOverlayCanvas(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new v(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));}destroy(){this.debugOverlayTexture&&this.debugOverlayTexture.destroy();}overLimit(){const{drawingBufferWidth:e,drawingBufferHeight:t}=this.context.gl;return this.width!==e||this.height!==t}}function yo(e,t){let i,r=false,o=null,s=null;const a=()=>{o=null,r&&(e.apply(s,i),o=setTimeout(a,t),r=false);};return (...e)=>(r=true,s=this,i=e,o||a(),o)}class wo{constructor(e){this._getCurrentHash=()=>{const e=window.location.hash.replace("#","");if(this._hashName){let t;return e.split("&").map((e=>e.split("="))).forEach((e=>{e[0]===this._hashName&&(t=e);})),(t&&t[1]||"").split("/")}return e.split("/")},this._onHashChange=()=>{const e=this._getCurrentHash();if(!this._isValidHash(e))return false;const t=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(e[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+e[2],+e[1]],zoom:+e[0],bearing:t,pitch:+(e[4]||0)}),true},this._updateHashUnthrottled=()=>{const e=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,e);},this._removeHash=()=>{const e=this._getCurrentHash();if(0===e.length)return;const t=e.join("/");let i=t;i.split("&").length>0&&(i=i.split("&")[0]),this._hashName&&(i=`${this._hashName}=${t}`);let r=window.location.hash.replace(i,"");r.startsWith("#&")?r=r.slice(0,1)+r.slice(2):"#"===r&&(r="");let o=window.location.href.replace(/(#.+)?$/,r);o=o.replace("&&","&"),window.history.replaceState(window.history.state,null,o);},this._updateHash=yo(this._updateHashUnthrottled,300),this._hashName=e&&encodeURIComponent(e);}addTo(e){return this._map=e,addEventListener("hashchange",this._onHashChange,false),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,false),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(e){const t=this._map.getCenter(),i=Math.round(100*this._map.getZoom())/100,r=Math.ceil((i*Math.LN2+Math.log(512/360/.5))/Math.LN10),o=Math.pow(10,r),s=Math.round(t.lng*o)/o,a=Math.round(t.lat*o)/o,n=this._map.getBearing(),l=this._map.getPitch();let c="";if(c+=e?`/${s}/${a}/${i}`:`${i}/${a}/${s}`,(n||l)&&(c+="/"+Math.round(10*n)/10),l&&(c+=`/${Math.round(l)}`),this._hashName){const e=this._hashName;let t=false;const i=window.location.hash.slice(1).split("&").map((i=>{const r=i.split("=")[0];return r===e?(t=true,`${r}=${c}`):i})).filter((e=>e));return t||i.push(`${e}=${c}`),`#${i.join("&")}`}return `#${c}`}_isValidHash(e){if(e.length<3||e.some(isNaN))return false;try{new t.N(+e[2],+e[1]);}catch(e){return false}const i=+e[0],r=+(e[3]||0),o=+(e[4]||0);return i>=this._map.getMinZoom()&&i<=this._map.getMaxZoom()&&r>=0&&r<=180&&o>=this._map.getMinPitch()&&o<=this._map.getMaxPitch()}}const To={linearity:.3,easing:t.c6(0,0,.3,1)},Po=t.e({deceleration:2500,maxSpeed:1400},To),Co=t.e({deceleration:20,maxSpeed:1400},To),Io=t.e({deceleration:1e3,maxSpeed:360},To),Eo=t.e({deceleration:1e3,maxSpeed:90},To),Mo=t.e({deceleration:1e3,maxSpeed:360},To);class So{constructor(e){this._map=e,this.clear();}clear(){this._inertiaBuffer=[];}record(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:a.now(),settings:e});}_drainInertiaBuffer(){const e=this._inertiaBuffer,t=a.now();for(;e.length>0&&t-e[0].time>160;)e.shift();}_onMoveEnd(e){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const i={zoom:0,bearing:0,pitch:0,roll:0,pan:new t.P(0,0),pinchAround:undefined,around:undefined};for(const{settings:e}of this._inertiaBuffer)i.zoom+=e.zoomDelta||0,i.bearing+=e.bearingDelta||0,i.pitch+=e.pitchDelta||0,i.roll+=e.rollDelta||0,e.panDelta&&i.pan._add(e.panDelta),e.around&&(i.around=e.around),e.pinchAround&&(i.pinchAround=e.pinchAround);const r=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,o={};if(i.pan.mag()){const s=Do(i.pan.mag(),r,t.e({},Po,e||{})),a=i.pan.mult(s.amount/i.pan.mag()),n=this._map.cameraHelper.handlePanInertia(a,this._map.transform);o.center=n.easingCenter,o.offset=n.easingOffset,Ro(o,s);}if(i.zoom){const e=Do(i.zoom,r,Co);o.zoom=this._map.transform.zoom+e.amount,Ro(o,e);}if(i.bearing){const e=Do(i.bearing,r,Io);o.bearing=this._map.transform.bearing+t.ab(e.amount,-179,179),Ro(o,e);}if(i.pitch){const e=Do(i.pitch,r,Eo);o.pitch=this._map.transform.pitch+e.amount,Ro(o,e);}if(i.roll){const e=Do(i.roll,r,Mo);o.roll=this._map.transform.roll+t.ab(e.amount,-179,179),Ro(o,e);}if(o.zoom||o.bearing){const e=undefined===i.pinchAround?i.around:i.pinchAround;o.around=e?this._map.unproject(e):this._map.getCenter();}return this.clear(),t.e(o,{noMoveStart:true})}}function Ro(e,t){(!e.duration||e.durationi.unproject(e))),l=s.reduce(((e,t,i,r)=>e.add(t.div(r.length))),new t.P(0,0));super(e,{points:s,point:l,lngLats:a,lngLat:i.unproject(l),originalEvent:r}),this._defaultPrevented=false;}}class Lo extends t.k{preventDefault(){this._defaultPrevented=true;}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i){super(e,{originalEvent:i}),this._defaultPrevented=false;}}class ko{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance;}reset(){delete this._mousedownPos;}wheel(e){return this._firePreventable(new Lo(e.type,this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new zo(e.type,this._map,e))}mouseup(e){this._map.fire(new zo(e.type,this._map,e));}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||this._map.fire(new zo(e.type,this._map,e));}dblclick(e){return this._firePreventable(new zo(e.type,this._map,e))}mouseover(e){this._map.fire(new zo(e.type,this._map,e));}mouseout(e){this._map.fire(new zo(e.type,this._map,e));}touchstart(e){return this._firePreventable(new Ao(e.type,this._map,e))}touchmove(e){this._map.fire(new Ao(e.type,this._map,e));}touchend(e){this._map.fire(new Ao(e.type,this._map,e));}touchcancel(e){this._map.fire(new Ao(e.type,this._map,e));}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return {}}isEnabled(){return true}isActive(){return false}enable(){}disable(){}}class Fo{constructor(e){this._map=e;}reset(){this._delayContextMenu=false,this._ignoreContextMenu=true,delete this._contextMenuEvent;}mousemove(e){this._map.fire(new zo(e.type,this._map,e));}mousedown(){this._delayContextMenu=true,this._ignoreContextMenu=false;}mouseup(){this._delayContextMenu=false,this._contextMenuEvent&&(this._map.fire(new zo("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._ignoreContextMenu||this._map.fire(new zo(e.type,this._map,e)),this._map.listens("contextmenu")&&e.preventDefault();}isEnabled(){return true}isActive(){return false}enable(){}disable(){}}class Bo{constructor(e){this._map=e;}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return {lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this._map.terrain)}}class jo{constructor(e,t){this._map=e,this._tr=new Bo(e),this._el=e.getCanvasContainer(),this._container=e.getContainer(),this._clickTolerance=t.clickTolerance||1;}isEnabled(){return !!this._enabled}isActive(){return !!this._active}enable(){this.isEnabled()||(this._enabled=true);}disable(){this.isEnabled()&&(this._enabled=false);}mousedown(e,t){this.isEnabled()&&e.shiftKey&&0===e.button&&(n.disableDrag(),this._startPos=this._lastPos=t,this._active=true);}mousemoveWindow(e,t){if(!this._active)return;const i=t;if(this._lastPos.equals(i)||!this._box&&i.dist(this._startPos)e.fitScreenCoordinates(r,o,this._tr.bearing,{linear:true})};this._fireEvent("boxzoomcancel",e);}keydown(e){this._active&&27===e.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",e));}reset(){this._active=false,this._container.classList.remove("maplibregl-crosshair"),this._box&&(n.remove(this._box),this._box=null),n.enableDrag(),delete this._startPos,delete this._lastPos;}_fireEvent(e,i){return this._map.fire(new t.k(e,{originalEvent:i}))}}function Oo(e,t){if(e.length!==t.length)throw new Error(`The number of touches and points are not equal - touches ${e.length}, points ${t.length}`);const i={};for(let r=0;rthis.numTouches)&&(this.aborted=true),this.aborted||(undefined===this.startTime&&(this.startTime=e.timeStamp),r.length===this.numTouches&&(this.centroid=function(e){const i=new t.P(0,0);for(const t of e)i._add(t);return i.div(e.length)}(i),this.touches=Oo(r,i)));}touchmove(e,t,i){if(this.aborted||!this.centroid)return;const r=Oo(i,t);for(const e in this.touches){const t=r[e];(!t||t.dist(this.touches[e])>30)&&(this.aborted=true);}}touchend(e,t,i){if((!this.centroid||e.timeStamp-this.startTime>500)&&(this.aborted=true),0===i.length){const e=!this.aborted&&this.centroid;if(this.reset(),e)return e}}}class Zo{constructor(e){this.singleTap=new No(e),this.numTaps=e.numTaps,this.reset();}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset();}touchstart(e,t,i){this.singleTap.touchstart(e,t,i);}touchmove(e,t,i){this.singleTap.touchmove(e,t,i);}touchend(e,t,i){const r=this.singleTap.touchend(e,t,i);if(r){const t=e.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(r)<30;if(t&&i||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=r,this.count===this.numTaps)return this.reset(),r}}}class Go{constructor(e){this._tr=new Bo(e),this._zoomIn=new Zo({numTouches:1,numTaps:2}),this._zoomOut=new Zo({numTouches:2,numTaps:1}),this.reset();}reset(){this._active=false,this._zoomIn.reset(),this._zoomOut.reset();}touchstart(e,t,i){this._zoomIn.touchstart(e,t,i),this._zoomOut.touchstart(e,t,i);}touchmove(e,t,i){this._zoomIn.touchmove(e,t,i),this._zoomOut.touchmove(e,t,i);}touchend(e,t,i){const r=this._zoomIn.touchend(e,t,i),o=this._zoomOut.touchend(e,t,i),s=this._tr;return r?(this._active=true,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:s.zoom+1,around:s.unproject(r)},{originalEvent:e})}):o?(this._active=true,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:s.zoom-1,around:s.unproject(o)},{originalEvent:e})}):undefined}touchcancel(){this.reset();}enable(){this._enabled=true;}disable(){this._enabled=false,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class Uo{constructor(e){this._enabled=!!e.enable,this._moveStateManager=e.moveStateManager,this._clickTolerance=e.clickTolerance||1,this._moveFunction=e.move,this._activateOnStart=!!e.activateOnStart,e.assignEvents(this),this.reset();}reset(e){this._active=false,this._moved=false,delete this._lastPoint,this._moveStateManager.endMove(e);}_move(...e){const t=this._moveFunction(...e);if(t.bearingDelta||t.pitchDelta||t.rollDelta||t.around||t.panDelta)return this._active=true,t}dragStart(e,t){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(e)&&(this._moveStateManager.startMove(e),this._lastPoint=Array.isArray(t)?t[0]:t,this._activateOnStart&&this._lastPoint&&(this._active=true));}dragMove(e,t){if(!this.isEnabled())return;const i=this._lastPoint;if(!i)return;if(e.preventDefault(),!this._moveStateManager.isValidMoveEvent(e))return void this.reset(e);const r=Array.isArray(t)?t[0]:t;return !this._moved&&r.dist(i)true}),t=new Ho){this.mouseMoveStateManager=e,this.oneFingerTouchMoveStateManager=t;}_executeRelevantHandler(e,t,i){return e instanceof MouseEvent?t(e):"undefined"!=typeof TouchEvent&&e instanceof TouchEvent?i(e):undefined}startMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.startMove(e)),(e=>this.oneFingerTouchMoveStateManager.startMove(e)));}endMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.endMove(e)),(e=>this.oneFingerTouchMoveStateManager.endMove(e)));}isValidStartEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidStartEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidStartEvent(e)))}isValidMoveEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidMoveEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidMoveEvent(e)))}isValidEndEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidEndEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidEndEvent(e)))}}const Xo=e=>{e.mousedown=e.dragStart,e.mousemoveWindow=e.dragMove,e.mouseup=e.dragEnd,e.contextmenu=e=>{e.preventDefault();};};class $o{constructor(e,t){this._clickTolerance=e.clickTolerance||1,this._map=t,this.reset();}reset(){this._active=false,this._touches={},this._sum=new t.P(0,0);}_shouldBePrevented(e){return e<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(e,t,i){return this._calculateTransform(e,t,i)}touchmove(e,t,i){if(this._active){if(!this._shouldBePrevented(i.length))return e.preventDefault(),this._calculateTransform(e,t,i);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",e);}}touchend(e,t,i){this._calculateTransform(e,t,i),this._active&&this._shouldBePrevented(i.length)&&this.reset();}touchcancel(){this.reset();}_calculateTransform(e,i,r){r.length>0&&(this._active=true);const o=Oo(r,i),s=new t.P(0,0),a=new t.P(0,0);let n=0;for(const e in o){const t=o[e],i=this._touches[e];i&&(s._add(t),a._add(t.sub(i)),n++,o[e]=t);}if(this._touches=o,this._shouldBePrevented(n)||!a.mag())return;const l=a.div(n);return this._sum._add(l),this._sum.mag()Math.abs(e.x)}class rs extends Ko{constructor(e){super(),this._currentTouchCount=0,this._map=e;}reset(){super.reset(),this._valid=undefined,delete this._firstMove,delete this._lastPoints;}touchstart(e,t,i){super.touchstart(e,t,i),this._currentTouchCount=i.length;}_start(e){this._lastPoints=e,is(e[0].sub(e[1]))&&(this._valid=false);}_move(e,t,i){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;const r=e[0].sub(this._lastPoints[0]),o=e[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(r,o,i.timeStamp),this._valid?(this._lastPoints=e,this._active=true,{pitchDelta:(r.y+o.y)/2*-0.5}):undefined}gestureBeginsVertically(e,t,i){if(undefined!==this._valid)return this._valid;const r=e.mag()>=2,o=t.mag()>=2;if(!r&&!o)return;if(!r||!o)return undefined===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&undefined;const s=e.y>0==t.y>0;return is(e)&&is(t)&&s}}const os={panStep:100,bearingStep:15,pitchStep:10};class ss{constructor(e){this._tr=new Bo(e);const t=os;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep,this._rotationDisabled=false;}reset(){this._active=false;}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let t=0,i=0,r=0,o=0,s=0;switch(e.keyCode){case 61:case 107:case 171:case 187:t=1;break;case 189:case 109:case 173:t=-1;break;case 37:e.shiftKey?i=-1:(e.preventDefault(),o=-1);break;case 39:e.shiftKey?i=1:(e.preventDefault(),o=1);break;case 38:e.shiftKey?r=1:(e.preventDefault(),s=-1);break;case 40:e.shiftKey?r=-1:(e.preventDefault(),s=1);break;default:return}return this._rotationDisabled&&(i=0,r=0),{cameraAnimation:a=>{const n=this._tr;a.easeTo({duration:300,easeId:"keyboardHandler",easing:as,zoom:t?Math.round(n.zoom)+t*(e.shiftKey?2:1):n.zoom,bearing:n.bearing+i*this._bearingStep,pitch:n.pitch+r*this._pitchStep,offset:[-o*this._panStep,-s*this._panStep],center:n.center},{originalEvent:e});}}}enable(){this._enabled=true;}disable(){this._enabled=false,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=true;}enableRotation(){this._rotationDisabled=false;}}function as(e){return e*(2-e)}const ns=4.000244140625;class ls{constructor(e,t){this._onTimeout=e=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(e);},this._map=e,this._tr=new Bo(e),this._triggerRenderFrame=t,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=.0022222222222222222;}setZoomRate(e){this._defaultZoomRate=e;}setWheelZoomRate(e){this._wheelZoomRate=e;}isEnabled(){return !!this._enabled}isActive(){return !!this._active||undefined!==this._finishTimeout}isZooming(){return !!this._zooming}enable(e){this.isEnabled()||(this._enabled=true,this._aroundCenter=!!e&&"center"===e.around);}disable(){this.isEnabled()&&(this._enabled=false);}_shouldBePrevented(e){return !!this._map.cooperativeGestures.isEnabled()&&!(e.ctrlKey||this._map.cooperativeGestures.isBypassed(e))}wheel(e){if(!this.isEnabled())return;if(this._shouldBePrevented(e))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",e);let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY;const i=a.now(),r=i-(this._lastWheelEventTime||0);this._lastWheelEventTime=i,0!==t&&t%ns==0?this._type="wheel":0!==t&&Math.abs(t)<4?this._type="trackpad":r>400?(this._type=null,this._lastValue=t,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(r*t)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,t+=this._lastValue)),e.shiftKey&&t&&(t/=4),this._type&&(this._lastWheelEvent=e,this._delta-=t,this._active||this._start(e)),e.preventDefault();}_start(e){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=true,this.isZooming()||(this._zooming=true),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const i=n.mousePos(this._map.getCanvas(),e),r=this._tr;this._aroundPoint=this._aroundCenter?r.transform.locationToScreenPoint(t.N.convert(r.center)):i,this._frameId||(this._frameId=true,this._triggerRenderFrame());}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const e=this._tr.transform;if("number"==typeof this._lastExpectedZoom){const t=e.zoom-this._lastExpectedZoom;"number"==typeof this._startZoom&&(this._startZoom+=t),"number"==typeof this._targetZoom&&(this._targetZoom+=t);}if(0!==this._delta){const i="wheel"===this._type&&Math.abs(this._delta)>ns?this._wheelZoomRate:this._defaultZoomRate;let r=2/(1+Math.exp(-Math.abs(this._delta*i)));this._delta<0&&0!==r&&(r=1/r);const o="number"!=typeof this._targetZoom?e.scale:t.aG(this._targetZoom);this._targetZoom=Math.min(e.maxZoom,Math.max(e.minZoom,t.a8(o*r))),"wheel"===this._type&&(this._startZoom=e.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}const i="number"!=typeof this._targetZoom?e.zoom:this._targetZoom,r=this._startZoom,o=this._easing;let s,n=false;if("wheel"===this._type&&r&&o){const e=a.now()-this._lastWheelEventTime,l=Math.min((e+5)/200,1),c=o(l);s=t.y.number(r,i,c),l<1?this._frameId||(this._frameId=true):n=true;}else s=i,n=true;return this._active=true,n&&(this._active=false,this._finishTimeout=setTimeout((()=>{this._zooming=false,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout;}),200)),this._lastExpectedZoom=s,{noInertia:true,needsRenderFrame:!n,zoomDelta:s-e.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(e){let i=t.c8;if(this._prevEase){const e=this._prevEase,r=(a.now()-e.start)/e.duration,o=e.easing(r+.01)-e.easing(r),s=.27/Math.sqrt(o*o+1e-4)*.01,n=Math.sqrt(.0729-s*s);i=t.c6(s,n,.25,1);}return this._prevEase={start:a.now(),duration:e,easing:i},i}reset(){this._active=false,this._zooming=false,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);}}class cs{constructor(e,t){this._clickZoom=e,this._tapZoom=t;}enable(){this._clickZoom.enable(),this._tapZoom.enable();}disable(){this._clickZoom.disable(),this._tapZoom.disable();}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class hs{constructor(e){this._tr=new Bo(e),this.reset();}reset(){this._active=false;}dblclick(e,t){return e.preventDefault(),{cameraAnimation:i=>{i.easeTo({duration:300,zoom:this._tr.zoom+(e.shiftKey?-1:1),around:this._tr.unproject(t)},{originalEvent:e});}}}enable(){this._enabled=true;}disable(){this._enabled=false,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class us{constructor(){this._tap=new Zo({numTouches:1,numTaps:1}),this.reset();}reset(){this._active=false,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset();}touchstart(e,t,i){if(!this._swipePoint)if(this._tapTime){const r=t[0],o=e.timeStamp-this._tapTime<500,s=this._tapPoint.dist(r)<30;o&&s?i.length>0&&(this._swipePoint=r,this._swipeTouch=i[0].identifier):this.reset();}else this._tap.touchstart(e,t,i);}touchmove(e,t,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;const r=t[0],o=r.y-this._swipePoint.y;return this._swipePoint=r,e.preventDefault(),this._active=true,{zoomDelta:o/128}}}else this._tap.touchmove(e,t,i);}touchend(e,t,i){if(this._tapTime)this._swipePoint&&0===i.length&&this.reset();else {const r=this._tap.touchend(e,t,i);r&&(this._tapTime=e.timeStamp,this._tapPoint=r);}}touchcancel(){this.reset();}enable(){this._enabled=true;}disable(){this._enabled=false,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class ds{constructor(e,t,i){this._el=e,this._mousePan=t,this._touchPan=i;}enable(e){this._inertiaOptions=e||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("maplibregl-touch-drag-pan");}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("maplibregl-touch-drag-pan");}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class _s{constructor(e,t,i,r){this._pitchWithRotate=e.pitchWithRotate,this._rollEnabled=e.rollEnabled,this._mouseRotate=t,this._mousePitch=i,this._mouseRoll=r;}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable();}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable();}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class ps{constructor(e,t,i,r){this._el=e,this._touchZoom=t,this._touchRotate=i,this._tapDragZoom=r,this._rotationDisabled=false,this._enabled=true;}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),this._tapDragZoom.enable(),this._el.classList.add("maplibregl-touch-zoom-rotate");}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("maplibregl-touch-zoom-rotate");}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=true,this._touchRotate.disable();}enableRotation(){this._rotationDisabled=false,this._touchZoom.isEnabled()&&this._touchRotate.enable();}}class ms{constructor(e,t){this._bypassKey=-1!==navigator.userAgent.indexOf("Mac")?"metaKey":"ctrlKey",this._map=e,this._options=t,this._enabled=false;}isActive(){return false}reset(){}_setupUI(){if(this._container)return;const e=this._map.getCanvasContainer();e.classList.add("maplibregl-cooperative-gestures"),this._container=n.create("div","maplibregl-cooperative-gesture-screen",e);let t=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");"metaKey"===this._bypassKey&&(t=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));const i=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),r=document.createElement("div");r.className="maplibregl-desktop-message",r.textContent=t,this._container.appendChild(r);const o=document.createElement("div");o.className="maplibregl-mobile-message",o.textContent=i,this._container.appendChild(o),this._container.setAttribute("aria-hidden","true");}_destroyUI(){this._container&&(n.remove(this._container),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container;}enable(){this._setupUI(),this._enabled=true;}disable(){this._enabled=false,this._destroyUI();}isEnabled(){return this._enabled}isBypassed(e){return e[this._bypassKey]}notifyGestureBlocked(e,i){this._enabled&&(this._map.fire(new t.k("cooperativegestureprevented",{gestureType:e,originalEvent:i})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show");}),100));}}const fs=e=>e.zoom||e.drag||e.roll||e.pitch||e.rotate;class gs extends t.k{}function vs(e){return e.panDelta&&e.panDelta.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta||e.rollDelta}class xs{constructor(e,t){this.handleWindowEvent=e=>{this.handleEvent(e,`${e.type}Window`);},this.handleEvent=(e,t)=>{if("blur"===e.type)return void this.stop(true);this._updatingCamera=true;const i="renderFrame"===e.type?undefined:e,r={needsRenderFrame:false},o={},s={},a=e.touches,l=a?this._getMapTouches(a):undefined,c=l?n.touchPos(this._map.getCanvas(),l):n.mousePos(this._map.getCanvas(),e);for(const{handlerName:a,handler:n,allowed:h}of this._handlers){if(!n.isEnabled())continue;let u;this._blockedByActive(s,h,a)?n.reset():n[t||e.type]&&(u=n[t||e.type](e,c,l),this.mergeHandlerResult(r,o,u,a,i),u&&u.needsRenderFrame&&this._triggerRenderFrame()),(u||n.isActive())&&(s[a]=n);}const h={};for(const e in this._previousActiveHandlers)s[e]||(h[e]=i);this._previousActiveHandlers=s,(Object.keys(h).length||vs(r))&&(this._changes.push([r,o,h]),this._triggerRenderFrame()),(Object.keys(s).length||vs(r))&&this._map._stop(true),this._updatingCamera=false;const{cameraAnimation:u}=r;u&&(this._inertia.clear(),this._fireEvents({},{},true),this._changes=[],u(this._map));},this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new So(e),this._bearingSnap=t.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(t);const i=this._el;this._listeners=[[i,"touchstart",{passive:true}],[i,"touchmove",{passive:false}],[i,"touchend",undefined],[i,"touchcancel",undefined],[i,"mousedown",undefined],[i,"mousemove",undefined],[i,"mouseup",undefined],[document,"mousemove",{capture:true}],[document,"mouseup",undefined],[i,"mouseover",undefined],[i,"mouseout",undefined],[i,"dblclick",undefined],[i,"click",undefined],[i,"keydown",{capture:false}],[i,"keyup",undefined],[i,"wheel",{passive:false}],[i,"contextmenu",undefined],[window,"blur",undefined]];for(const[e,t,i]of this._listeners)n.addEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}destroy(){for(const[e,t,i]of this._listeners)n.removeEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}_addDefaultHandlers(e){const i=this._map,r=i.getCanvasContainer();this._add("mapEvent",new ko(i,e));const o=i.boxZoom=new jo(i,e);this._add("boxZoom",o),e.interactive&&e.boxZoom&&o.enable();const s=i.cooperativeGestures=new ms(i,e.cooperativeGestures);this._add("cooperativeGestures",s),e.cooperativeGestures&&s.enable();const a=new Go(i),l=new hs(i);i.doubleClickZoom=new cs(l,a),this._add("tapZoom",a),this._add("clickZoom",l),e.interactive&&e.doubleClickZoom&&i.doubleClickZoom.enable();const c=new us;this._add("tapDragZoom",c);const h=i.touchPitch=new rs(i);this._add("touchPitch",h),e.interactive&&e.touchPitch&&i.touchPitch.enable(e.touchPitch);const u=()=>i.project(i.getCenter()),d=function({enable:e,clickTolerance:i,aroundCenter:r=true,minPixelCenterThreshold:o=100,rotateDegreesPerPixelMoved:s=.8},a){const l=new qo({checkCorrectEvent:e=>0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)&&!e.ctrlKey});return new Uo({clickTolerance:i,move:(e,i)=>{const n=a();if(r&&Math.abs(n.y-e.y)>o)return {bearingDelta:t.c7(new t.P(e.x,i.y),i,n)};let l=(i.x-e.x)*s;return r&&i.y0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)});return new Uo({clickTolerance:t,move:(e,t)=>({pitchDelta:(t.y-e.y)*i}),moveStateManager:r,enable:e,assignEvents:Xo})}(e),p=function({enable:e,clickTolerance:t,rollDegreesPerPixelMoved:i=.3},r){const o=new qo({checkCorrectEvent:e=>2===n.mouseButton(e)&&e.ctrlKey});return new Uo({clickTolerance:t,move:(e,t)=>{const o=r();let s=(t.x-e.x)*i;return t.y0===n.mouseButton(e)&&!e.ctrlKey});return new Uo({clickTolerance:t,move:(e,t)=>({around:t,panDelta:t.sub(e)}),activateOnStart:true,moveStateManager:i,enable:e,assignEvents:Xo})}(e),f=new $o(e,i);i.dragPan=new ds(r,m,f),this._add("mousePan",m),this._add("touchPan",f,["touchZoom","touchRotate"]),e.interactive&&e.dragPan&&i.dragPan.enable(e.dragPan);const g=new ts,v=new Qo;i.touchZoomRotate=new ps(r,v,g,c),this._add("touchRotate",g,["touchPan","touchZoom"]),this._add("touchZoom",v,["touchPan","touchRotate"]),e.interactive&&e.touchZoomRotate&&i.touchZoomRotate.enable(e.touchZoomRotate);const x=i.scrollZoom=new ls(i,(()=>this._triggerRenderFrame()));this._add("scrollZoom",x,["mousePan"]),e.interactive&&e.scrollZoom&&i.scrollZoom.enable(e.scrollZoom);const b=i.keyboard=new ss(i);this._add("keyboard",b),e.interactive&&e.keyboard&&i.keyboard.enable(),this._add("blockableMapEvent",new Fo(i));}_add(e,t,i){this._handlers.push({handlerName:e,handler:t,allowed:i}),this._handlersById[e]=t;}stop(e){if(!this._updatingCamera){for(const{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},e),this._changes=[];}}isActive(){for(const{handler:e}of this._handlers)if(e.isActive())return true;return false}isZooming(){return !!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return !!this._eventsInProgress.rotate}isMoving(){return Boolean(fs(this._eventsInProgress))||this.isZooming()}_blockedByActive(e,t,i){for(const r in e)if(r!==i&&(!t||t.indexOf(r)<0))return true;return false}_getMapTouches(e){const t=[];for(const i of e)this._el.contains(i.target)&&t.push(i);return t}mergeHandlerResult(e,i,r,o,s){if(!r)return;t.e(e,r);const a={handlerName:o,originalEvent:r.originalEvent||s};undefined!==r.zoomDelta&&(i.zoom=a),undefined!==r.panDelta&&(i.drag=a),undefined!==r.rollDelta&&(i.roll=a),undefined!==r.pitchDelta&&(i.pitch=a),undefined!==r.bearingDelta&&(i.rotate=a);}_applyChanges(){const e={},i={},r={};for(const[o,s,a]of this._changes)o.panDelta&&(e.panDelta=(e.panDelta||new t.P(0,0))._add(o.panDelta)),o.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+o.zoomDelta),o.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+o.bearingDelta),o.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+o.pitchDelta),o.rollDelta&&(e.rollDelta=(e.rollDelta||0)+o.rollDelta),undefined!==o.around&&(e.around=o.around),undefined!==o.pinchAround&&(e.pinchAround=o.pinchAround),o.noInertia&&(e.noInertia=o.noInertia),t.e(i,s),t.e(r,a);this._updateMapTransform(e,i,r),this._changes=[];}_updateMapTransform(e,t,i){const r=this._map,o=r._getTransformForUpdate(),s=r.terrain;if(!(vs(e)||s&&this._terrainMovement))return this._fireEvents(t,i,true);r._stop(true);let{panDelta:a,zoomDelta:n,bearingDelta:l,pitchDelta:c,rollDelta:h,around:u,pinchAround:d}=e;undefined!==d&&(u=d),u=u||r.transform.centerPoint,s&&!o.isPointOnMapSurface(u)&&(u=o.centerPoint);const _={panDelta:a,zoomDelta:n,rollDelta:h,pitchDelta:c,bearingDelta:l,around:u};this._map.cameraHelper.useGlobeControls&&!o.isPointOnMapSurface(u)&&(u=o.centerPoint);const p=u.distSqr(o.centerPoint)<.01?o.center:o.screenPointToLocation(a?u.sub(a):u);s?(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,o),this._terrainMovement||!t.drag&&!t.zoom?t.drag&&this._terrainMovement?o.setCenter(o.screenPointToLocation(o.centerPoint.sub(a))):this._map.cameraHelper.handleMapControlsPan(_,o,p):(this._terrainMovement=true,this._map._elevationFreeze=true,this._map.cameraHelper.handleMapControlsPan(_,o,p))):(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,o),this._map.cameraHelper.handleMapControlsPan(_,o,p)),r._applyUpdatedTransform(o),this._map._update(),e.noInertia||this._inertia.record(e),this._fireEvents(t,i,true);}_fireEvents(e,i,r){const o=fs(this._eventsInProgress),s=fs(e),n={};for(const t in e){const{originalEvent:i}=e[t];this._eventsInProgress[t]||(n[`${t}start`]=i),this._eventsInProgress[t]=e[t];}!o&&s&&this._fireEvent("movestart",s.originalEvent);for(const e in n)this._fireEvent(e,n[e]);s&&this._fireEvent("move",s.originalEvent);for(const t in e){const{originalEvent:i}=e[t];this._fireEvent(t,i);}const l={};let c;for(const e in this._eventsInProgress){const{handlerName:t,originalEvent:r}=this._eventsInProgress[e];this._handlersById[t].isActive()||(delete this._eventsInProgress[e],c=i[t]||r,l[`${e}end`]=c);}for(const e in l)this._fireEvent(e,l[e]);const h=fs(this._eventsInProgress),u=(o||s)&&!h;if(u&&this._terrainMovement){this._map._elevationFreeze=false,this._terrainMovement=false;const e=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&e.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(e);}if(r&&u){this._updatingCamera=true;const e=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),i=e=>0!==e&&-this._bearingSnap{delete this._frameId,this.handleEvent(new gs("renderFrame",{timeStamp:e})),this._applyChanges();}))}_triggerRenderFrame(){undefined===this._frameId&&(this._frameId=this._requestFrame());}}class bs extends t.E{constructor(e,t,i){super(),this._renderFrameCallback=()=>{const e=Math.min((a.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},this._moving=false,this._zooming=false,this.transform=e,this._bearingSnap=i.bearingSnap,this.cameraHelper=t,this.on("moveend",(()=>{delete this._requestedCameraState;}));}migrateProjection(e,t){e.apply(this.transform),this.transform=e,this.cameraHelper=t;}getCenter(){return new t.N(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}getCenterElevation(){return this.transform.elevation}setCenterElevation(e,t){return this.jumpTo({elevation:e},t),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(e){this._centerClampedToGround=e;}panBy(e,i,r){return e=t.P.convert(e).mult(-1),this.panTo(this.transform.center,t.e({offset:e},i),r)}panTo(e,i,r){return this.easeTo(t.e({center:e},i),r)}getZoom(){return this.transform.zoom}setZoom(e,t){return this.jumpTo({zoom:e},t),this}zoomTo(e,i,r){return this.easeTo(t.e({zoom:e},i),r)}zoomIn(e,t){return this.zoomTo(this.getZoom()+1,e,t),this}zoomOut(e,t){return this.zoomTo(this.getZoom()-1,e,t),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(e,i){return e!=this.transform.fov&&(this.transform.setFov(e),this.fire(new t.k("movestart",i)).fire(new t.k("move",i)).fire(new t.k("moveend",i))),this}getBearing(){return this.transform.bearing}setBearing(e,t){return this.jumpTo({bearing:e},t),this}getPadding(){return this.transform.padding}setPadding(e,t){return this.jumpTo({padding:e},t),this}rotateTo(e,i,r){return this.easeTo(t.e({bearing:e},i),r)}resetNorth(e,i){return this.rotateTo(0,t.e({duration:1e3},e),i),this}resetNorthPitch(e,i){return this.easeTo(t.e({bearing:0,pitch:0,roll:0,duration:1e3},e),i),this}snapToNorth(e,t){return Math.abs(this.getBearing()){f.easeFunc(t),this.terrain&&!e.freezeElevation&&this._updateElevation(t),this._applyUpdatedTransform(r),this._fireMoveEvents(i);}),(t=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i,t);}),e),this}_prepareEase(e,i,r={}){this._moving=true,i||r.moving||this.fire(new t.k("movestart",e)),this._zooming&&!r.zooming&&this.fire(new t.k("zoomstart",e)),this._rotating&&!r.rotating&&this.fire(new t.k("rotatestart",e)),this._pitching&&!r.pitching&&this.fire(new t.k("pitchstart",e)),this._rolling&&!r.rolling&&this.fire(new t.k("rollstart",e));}_prepareElevation(e){this._elevationCenter=e,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(e,this.transform.tileZoom),this._elevationFreeze=true;}_updateElevation(e){this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));const i=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(e<1&&i!==this._elevationTarget){const t=this._elevationTarget-this._elevationStart;this._elevationStart+=e*(t-(i-(t*e+this._elevationStart))/(1-e)),this._elevationTarget=i;}this.transform.setElevation(t.y.number(this._elevationStart,this._elevationTarget,e));}_finalizeElevation(){this._elevationFreeze=false,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain);}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(e){if(!this.terrain&&e.elevation>=0&&e.pitch<=90)return {};const t=e.getCameraLngLat(),i=e.getCameraAltitude(),r=this.terrain?this.terrain.getElevationForLngLatZoom(t,e.zoom):0;if(ithis._elevateCameraIfInsideTerrain(e))),this.transformCameraUpdate&&t.push((e=>this.transformCameraUpdate(e))),!t.length)return;const i=e.clone();for(const e of t){const t=i.clone(),{center:r,zoom:o,roll:s,pitch:a,bearing:n,elevation:l}=e(t);r&&t.setCenter(r),undefined!==l&&t.setElevation(l),undefined!==o&&t.setZoom(o),undefined!==s&&t.setRoll(s),undefined!==a&&t.setPitch(a),undefined!==n&&t.setBearing(n),i.apply(t);}this.transform.apply(i);}_fireMoveEvents(e){this.fire(new t.k("move",e)),this._zooming&&this.fire(new t.k("zoom",e)),this._rotating&&this.fire(new t.k("rotate",e)),this._pitching&&this.fire(new t.k("pitch",e)),this._rolling&&this.fire(new t.k("roll",e));}_afterEase(e,i){if(this._easeId&&i&&this._easeId===i)return;delete this._easeId;const r=this._zooming,o=this._rotating,s=this._pitching,a=this._rolling;this._moving=false,this._zooming=false,this._rotating=false,this._pitching=false,this._rolling=false,this._padding=false,r&&this.fire(new t.k("zoomend",e)),o&&this.fire(new t.k("rotateend",e)),s&&this.fire(new t.k("pitchend",e)),a&&this.fire(new t.k("rollend",e)),this.fire(new t.k("moveend",e));}flyTo(e,i){if(!e.essential&&a.prefersReducedMotion){const r=t.M(e,["center","zoom","bearing","pitch","roll","elevation"]);return this.jumpTo(r,i)}this.stop(),e=t.e({offset:[0,0],speed:1.2,curve:1.42,easing:t.c8},e);const r=this._getTransformForUpdate(),o=r.bearing,s=r.pitch,n=r.roll,l=r.padding,c="bearing"in e?this._normalizeBearing(e.bearing,o):o,h="pitch"in e?+e.pitch:s,u="roll"in e?this._normalizeBearing(e.roll,n):n,d="padding"in e?e.padding:r.padding,_=t.P.convert(e.offset);let p=r.centerPoint.add(_);const m=r.screenPointToLocation(p),f=this.cameraHelper.handleFlyTo(r,{bearing:c,pitch:h,roll:u,padding:d,locationAtOffset:m,offsetAsPoint:_,center:e.center,minZoom:e.minZoom,zoom:e.zoom});let g=e.curve;const v=Math.max(r.width,r.height),x=v/f.scaleOfZoom,b=f.pixelPathLength;"number"==typeof f.scaleOfMinZoom&&(g=Math.sqrt(v/f.scaleOfMinZoom/b*2));const y=g*g;function w(e){const t=(x*x-v*v+(e?-1:1)*y*y*b*b)/(2*(e?x:v)*y*b);return Math.log(Math.sqrt(t*t+1)-t)}function T(e){return (Math.exp(e)-Math.exp(-e))/2}function P(e){return (Math.exp(e)+Math.exp(-e))/2}const C=w(false);let I=function(e){return P(C)/P(C+g*e)},E=function(e){return v*((P(C)*(T(t=C+g*e)/P(t))-T(C))/y)/b;var t;},M=(w(true)-C)/g;if(Math.abs(b)<2e-6||!isFinite(M)){if(Math.abs(v-x)<1e-6)return this.easeTo(e,i);const t=x0,I=e=>Math.exp(t*g*e);}return e.duration="duration"in e?+e.duration:1e3*M/("screenSpeed"in e?+e.screenSpeed/g:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=true,this._rotating=o!==c,this._pitching=h!==s,this._rolling=u!==n,this._padding=!r.isPaddingEqual(d),this._prepareEase(i,false),this.terrain&&this._prepareElevation(f.targetCenter),this._ease((a=>{const m=a*M,g=1/I(m),v=E(m);this._rotating&&r.setBearing(t.y.number(o,c,a)),this._pitching&&r.setPitch(t.y.number(s,h,a)),this._rolling&&r.setRoll(t.y.number(n,u,a)),this._padding&&(r.interpolatePadding(l,d,a),p=r.centerPoint.add(_)),f.easeFunc(a,g,v,p),this.terrain&&!e.freezeElevation&&this._updateElevation(a),this._applyUpdatedTransform(r),this._fireMoveEvents(i);}),(()=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i);}),e),this}isEasing(){return !!this._easeFrameId}stop(){return this._stop()}_stop(e,t){var i;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){const e=this._onEaseEnd;delete this._onEaseEnd,e.call(this,t);}return e||null===(i=this.handlers)||undefined===i||i.stop(false),this}_ease(e,t,i){false===i.animate||0===i.duration?(e(1),t()):(this._easeStart=a.now(),this._easeOptions=i,this._onEaseFrame=e,this._onEaseEnd=t,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));}_normalizeBearing(e,i){e=t.aI(e,-180,180);const r=Math.abs(e-i);return Math.abs(e-360-i)MapLibre'};class ws{constructor(e=ys){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")));},this._updateData=e=>{!e||"metadata"!==e.sourceDataType&&"visibility"!==e.sourceDataType&&"style"!==e.dataType&&"terrain"!==e.type||this._updateAttributions();},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?false===this._compact?this._container.setAttribute("open",""):this._container.classList.contains("maplibregl-compact")||this._container.classList.contains("maplibregl-attrib-empty")||(this._container.setAttribute("open",""),this._container.classList.add("maplibregl-compact","maplibregl-compact-show")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"));},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show");},this.options=e;}getDefaultPosition(){return "bottom-right"}onAdd(e){return this._map=e,this._compact=this.options.compact,this._container=n.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=n.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=n.create("div","maplibregl-ctrl-attrib-inner",this._container),this._updateAttributions(),this._updateCompact(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("terrain",this._updateData),this._map.on("resize",this._updateCompact),this._map.on("drag",this._updateCompactMinimize),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("terrain",this._updateData),this._map.off("resize",this._updateCompact),this._map.off("drag",this._updateCompactMinimize),this._map=undefined,this._compact=undefined,this._sanitizedAttributionHTML=undefined;}_setElementTitle(e,t){const i=this._map._getUIString(`AttributionControl.${t}`);e.title=i,e.setAttribute("aria-label",i);}_updateAttributions(){if(!this._map.style)return;let e=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?e=e.concat(this.options.customAttribution.map((e=>"string"!=typeof e?"":e))):"string"==typeof this.options.customAttribution&&e.push(this.options.customAttribution)),this._map.style.stylesheet){const e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id;}const t=this._map.style.sourceCaches;for(const i in t){const r=t[i];if(r.used||r.usedForTerrain){const t=r.getSource();t.attribution&&e.indexOf(t.attribution)<0&&e.push(t.attribution);}}e=e.filter((e=>String(e).trim())),e.sort(((e,t)=>e.length-t.length)),e=e.filter(((t,i)=>{for(let r=i+1;r=0)return false;return true}));const i=e.join(" | ");i!==this._sanitizedAttributionHTML&&(this._sanitizedAttributionHTML=n.sanitize(i),e.length?(this._innerContainer.innerHTML=this._sanitizedAttributionHTML,this._container.classList.remove("maplibregl-attrib-empty")):this._container.classList.add("maplibregl-attrib-empty"),this._updateCompact(),this._editLink=null);}}class Ts{constructor(e={}){this._updateCompact=()=>{const e=this._container.children;if(e.length){const t=e[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?false!==this._compact&&t.classList.add("maplibregl-compact"):t.classList.remove("maplibregl-compact");}},this.options=e;}getDefaultPosition(){return "bottom-left"}onAdd(e){this._map=e,this._compact=this.options&&this.options.compact,this._container=n.create("div","maplibregl-ctrl");const t=n.create("a","maplibregl-ctrl-logo");return t.target="_blank",t.rel="noopener nofollow",t.href="https://maplibre.org/",t.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),t.setAttribute("rel","noopener nofollow"),this._container.appendChild(t),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){n.remove(this._container),this._map.off("resize",this._updateCompact),this._map=undefined,this._compact=undefined;}}class Ps{constructor(){this._queue=[],this._id=0,this._cleared=false,this._currentlyRunning=false;}add(e){const t=++this._id;return this._queue.push({callback:e,id:t,cancelled:false}),t}remove(e){const t=this._currentlyRunning,i=t?this._queue.concat(t):this._queue;for(const t of i)if(t.id===e)return void(t.cancelled=true)}run(e=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const t=this._currentlyRunning=this._queue;this._queue=[];for(const i of t)if(!i.cancelled&&(i.callback(e),this._cleared))break;this._cleared=false,this._currentlyRunning=false;}clear(){this._currentlyRunning&&(this._cleared=true),this._queue=[];}}var Cs=t.aA([{name:"a_pos3d",type:"Int16",components:3}]);class Is extends t.E{constructor(e){super(),this._lastTilesetChange=a.now(),this.sourceCache=e,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=e._source.tileSize*2**this.deltaZoom,e.usedForTerrain=true,e.tileSize=this.tileSize;}destruct(){this.sourceCache.usedForTerrain=false,this.sourceCache.tileSize=null;}update(e,i){this.sourceCache.update(e,i),this._renderableTilesKeys=[];const r={};for(const o of ue(e,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:false,terrain:i,calculateTileZoom:this.sourceCache._source.calculateTileZoom}))r[o.key]=true,this._renderableTilesKeys.push(o.key),this._tiles[o.key]||(o.terrainRttPosMatrix32f=new Float64Array(16),t.bL(o.terrainRttPosMatrix32f,0,t.X,t.X,0,0,1),this._tiles[o.key]=new se(o,this.tileSize),this._lastTilesetChange=a.now());for(const e in this._tiles)r[e]||delete this._tiles[e];}freeRtt(e){for(const t in this._tiles){const i=this._tiles[t];(!e||i.tileID.equals(e)||i.tileID.isChildOf(e)||e.isChildOf(i.tileID))&&(i.rtt=[]);}}getRenderableTiles(){return this._renderableTilesKeys.map((e=>this.getTileByID(e)))}getTileByID(e){return this._tiles[e]}getTerrainCoords(e){const i={};for(const r of this._renderableTilesKeys){const o=this._tiles[r].tileID,s=e.clone(),a=t.a$();if(o.canonical.equals(e.canonical))t.bL(a,0,t.X,t.X,0,0,1);else if(o.canonical.isChildOf(e.canonical)){const i=o.canonical.z-e.canonical.z,r=o.canonical.x-(o.canonical.x>>i<>i<>i;t.bL(a,0,n,n,0,0,1),t.J(a,a,[-r*n,-s*n,0]);}else {if(!e.canonical.isChildOf(o.canonical))continue;{const i=e.canonical.z-o.canonical.z,r=e.canonical.x-(e.canonical.x>>i<>i<>i;t.bL(a,0,t.X,t.X,0,0,1),t.J(a,a,[r*n,s*n,0]),t.K(a,a,[1/2**i,1/2**i,0]);}}s.terrainRttPosMatrix32f=new Float32Array(a),i[r]=s;}return i}getSourceTile(e,t){const i=this.sourceCache._source;let r=e.overscaledZ-this.deltaZoom;if(r>i.maxzoom&&(r=i.maxzoom),r=i.minzoom&&(!o||!o.dem);)o=this.sourceCache.getTileByID(e.scaledTo(r--).key);return o}anyTilesAfterTime(e=Date.now()){return this._lastTilesetChange>=e}}class Es{constructor(e,t,i){this._meshCache={},this.painter=e,this.sourceCache=new Is(t),this.options=i,this.exaggeration="number"==typeof i.exaggeration?i.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024;}getDEMElevation(e,i,r,o=t.X){var s;if(!(i>=0&&i=0&&re.canonical.z&&(e.canonical.z>=r?o=e.canonical.z-r:t.w("cannot calculate elevation if elevation maxzoom > source.maxzoom"));const s=e.canonical.x-(e.canonical.x>>o<>o<>8<<4|e>>8,i[t+3]=0;const r=new t.R({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(i.buffer)),o=new v(e,r,e.gl.RGBA,{premultiply:false});return o.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),this._coordsTexture=o,o}pointCoordinate(e){this.painter.maybeDrawDepthAndCoords(true);const i=new Uint8Array(4),r=this.painter.context,o=r.gl,s=Math.round(e.x*this.painter.pixelRatio/devicePixelRatio),a=Math.round(e.y*this.painter.pixelRatio/devicePixelRatio),n=Math.round(this.painter.height/devicePixelRatio);r.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),o.readPixels(s,n-a-1,1,1,o.RGBA,o.UNSIGNED_BYTE,i),r.bindFramebuffer.set(null);const l=i[0]+(i[2]>>4<<8),c=i[1]+((15&i[2])<<8),h=this.coordsIndex[255-i[3]],u=h&&this.sourceCache.getTileByID(h);if(!u)return null;const d=this._coordsTextureSize,_=(1<0,o=r&&0===e.canonical.y,s=r&&e.canonical.y===(1<e.id!==t)),this._recentlyUsed.push(e.id);}stampObject(e){e.stamp=++this._stamp;}getOrCreateFreeObject(){for(const e of this._recentlyUsed)if(!this._objects[e].inUse)return this._objects[e];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const e=this._createObject(this._objects.length);return this._objects.push(e),e}freeObject(e){e.inUse=false;}freeAllObjects(){for(const e of this._objects)this.freeObject(e);}isFull(){return !(this._objects.length!e.inUse))}}const Ss={background:true,fill:true,line:true,raster:true,hillshade:true};class Rs{constructor(e,t){this.painter=e,this.terrain=t,this.pool=new Ms(e.context,30,t.sourceCache.tileSize*t.qualityFactor);}destruct(){this.pool.destruct();}getTexture(e){return this.pool.getObjectForId(e.rtt[this._stacks.length-1].id).texture}prepareForRender(e,t){this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.sourceCache.getRenderableTiles(),this._renderableLayerIds=e._order.filter((i=>!e._layers[i].isHidden(t))),this._coordsAscending={};for(const t in e.sourceCaches){this._coordsAscending[t]={};const i=e.sourceCaches[t].getVisibleCoordinates();for(const e of i){const i=this.terrain.sourceCache.getTerrainCoords(e);for(const e in i)this._coordsAscending[t][e]||(this._coordsAscending[t][e]=[]),this._coordsAscending[t][e].push(i[e]);}}this._coordsAscendingStr={};for(const t of e._order){const i=e._layers[t],r=i.source;if(Ss[i.type]&&!this._coordsAscendingStr[r]){this._coordsAscendingStr[r]={};for(const e in this._coordsAscending[r])this._coordsAscendingStr[r][e]=this._coordsAscending[r][e].map((e=>e.key)).sort().join();}}for(const e of this._renderableTiles)for(const t in this._coordsAscendingStr){const i=this._coordsAscendingStr[t][e.tileID.key];i&&i!==e.rttCoords[t]&&(e.rtt=[]);}}renderLayer(e,i){if(e.isHidden(this.painter.transform.zoom))return false;const r=Object.assign(Object.assign({},i),{isRenderingToTexture:true}),o=e.type,s=this.painter,a=this._renderableLayerIds[this._renderableLayerIds.length-1]===e.id;if(Ss[o]&&(this._prevType&&Ss[this._prevType]||this._stacks.push([]),this._prevType=o,this._stacks[this._stacks.length-1].push(e.id),!a))return true;if(Ss[this._prevType]||Ss[o]&&a){this._prevType=o;const e=this._stacks.length-1,i=this._stacks[e]||[];for(const o of this._renderableTiles){if(this.pool.isFull()&&(vo(this.painter,this.terrain,this._rttTiles,r),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(o),o.rtt[e]){const t=this.pool.getObjectForId(o.rtt[e].id);if(t.stamp===o.rtt[e].stamp){this.pool.useObject(t);continue}}const a=this.pool.getOrCreateFreeObject();this.pool.useObject(a),this.pool.stampObject(a),o.rtt[e]={id:a.id,stamp:a.stamp},s.context.bindFramebuffer.set(a.fbo.framebuffer),s.context.clear({color:t.b4.transparent,stencil:0}),s.currentStencilSource=undefined;for(let e=0;e{this.startMove(e,n.mousePos(this.element,e)),n.addEventListener(window,"mousemove",this.mousemove),n.addEventListener(window,"mouseup",this.mouseup);},this.mousemove=e=>{this.move(e,n.mousePos(this.element,e));},this.mouseup=e=>{this._rotatePitchHanlder.dragEnd(e),this.offTemp();},this.touchstart=e=>{1!==e.targetTouches.length?this.reset():(this._startPos=this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.startMove(e,this._startPos),n.addEventListener(window,"touchmove",this.touchmove,{passive:false}),n.addEventListener(window,"touchend",this.touchend));},this.touchmove=e=>{1!==e.targetTouches.length?this.reset():(this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.move(e,this._lastPos));},this.touchend=e=>{0===e.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this._rotatePitchHanlder.reset(),delete this._startPos,delete this._lastPos,this.offTemp();},this._clickTolerance=10,this.element=i;const o=new Wo;this._rotatePitchHanlder=new Uo({clickTolerance:3,move:(e,o)=>{const s=i.getBoundingClientRect(),a=new t.P((s.bottom-s.top)/2,(s.right-s.left)/2);return {bearingDelta:t.c7(new t.P(e.x,o.y),o,a),pitchDelta:r?-0.5*(o.y-e.y):undefined}},moveStateManager:o,enable:true,assignEvents:()=>{}}),this.map=e,n.addEventListener(i,"mousedown",this.mousedown),n.addEventListener(i,"touchstart",this.touchstart,{passive:false}),n.addEventListener(i,"touchcancel",this.reset);}startMove(e,t){this._rotatePitchHanlder.dragStart(e,t),n.disableDrag();}move(e,t){const i=this.map,{bearingDelta:r,pitchDelta:o}=this._rotatePitchHanlder.dragMove(e,t)||{};r&&i.setBearing(i.getBearing()+r),o&&i.setPitch(i.getPitch()+o);}off(){const e=this.element;n.removeEventListener(e,"mousedown",this.mousedown),n.removeEventListener(e,"touchstart",this.touchstart,{passive:false}),n.removeEventListener(window,"touchmove",this.touchmove,{passive:false}),n.removeEventListener(window,"touchend",this.touchend),n.removeEventListener(e,"touchcancel",this.reset),this.offTemp();}offTemp(){n.enableDrag(),n.removeEventListener(window,"mousemove",this.mousemove),n.removeEventListener(window,"mouseup",this.mouseup),n.removeEventListener(window,"touchmove",this.touchmove,{passive:false}),n.removeEventListener(window,"touchend",this.touchend);}}let Fs;function Bs(e,i,r){const o=new t.N(e.lng,e.lat);if(e=new t.N(e.lng,e.lat),i){const o=new t.N(e.lng-360,e.lat),s=new t.N(e.lng+360,e.lat),a=r.locationToScreenPoint(e).distSqr(i);r.locationToScreenPoint(o).distSqr(i)180;){const t=r.locationToScreenPoint(e);if(t.x>=0&&t.y>=0&&t.x<=r.width&&t.y<=r.height)break;e.lng>r.center.lng?e.lng-=360:e.lng+=360;}return e.lng!==o.lng&&r.isPointOnMapSurface(r.locationToScreenPoint(e))?e:o}const js={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function Os(e,t,i){const r=e.classList;for(const e in js)r.remove(`maplibregl-${i}-anchor-${e}`);r.add(`maplibregl-${i}-anchor-${t}`);}class Ns extends t.E{constructor(e){if(super(),this._onKeyPress=e=>{const t=e.code,i=e.charCode||e.keyCode;"Space"!==t&&"Enter"!==t&&32!==i&&13!==i||this.togglePopup();},this._onMapClick=e=>{const t=e.originalEvent.target,i=this._element;this._popup&&(t===i||i.contains(t))&&this.togglePopup();},this._update=e=>{var t;if(!this._map)return;const i=this._map.loaded()&&!this._map.isMoving();("terrain"===(null==e?undefined:e.type)||"render"===(null==e?undefined:e.type)&&!i)&&this._map.once("render",this._update),this._lngLat=this._map.transform.renderWorldCopies?Bs(this._lngLat,this._flatPos,this._map.transform):null===(t=this._lngLat)||undefined===t?undefined:t.wrap(),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let r="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?r=`rotateZ(${this._rotation}deg)`:"map"===this._rotationAlignment&&(r=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let o="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?o="rotateX(0deg)":"map"===this._pitchAlignment&&(o=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||e&&"moveend"!==e.type||(this._pos=this._pos.round()),n.setTransform(this._element,`${js[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${o} ${r}`),a.frameAsync(new AbortController).then((()=>{this._updateOpacity(e&&"moveend"===e.type);})).catch((()=>{}));},this._onMove=e=>{if(!this._isDragging){const t=this._clickTolerance||this._map._clickTolerance;this._isDragging=e.point.dist(this._pointerdownPos)>=t;}this._isDragging&&(this._pos=e.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new t.k("dragstart"))),this.fire(new t.k("drag")));},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=false,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new t.k("dragend")),this._state="inactive";},this._addDragHandler=e=>{this._element.contains(e.originalEvent.target)&&(e.preventDefault(),this._positionDelta=e.point.sub(this._pos).add(this._offset),this._pointerdownPos=e.point,this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp));},this._anchor=e&&e.anchor||"center",this._color=e&&e.color||"#3FB1CE",this._scale=e&&e.scale||1,this._draggable=e&&e.draggable||false,this._clickTolerance=e&&e.clickTolerance||0,this._subpixelPositioning=e&&e.subpixelPositioning||false,this._isDragging=false,this._state="inactive",this._rotation=e&&e.rotation||0,this._rotationAlignment=e&&e.rotationAlignment||"auto",this._pitchAlignment=e&&e.pitchAlignment&&"auto"!==e.pitchAlignment?e.pitchAlignment:this._rotationAlignment,this.setOpacity(),this.setOpacity(null==e?undefined:e.opacity,null==e?undefined:e.opacityWhenCovered),e&&e.element)this._element=e.element,this._offset=t.P.convert(e&&e.offset||[0,0]);else {this._defaultMarker=true,this._element=n.create("div");const i=n.createNS("http://www.w3.org/2000/svg","svg"),r=41,o=27;i.setAttributeNS(null,"display","block"),i.setAttributeNS(null,"height",`${r}px`),i.setAttributeNS(null,"width",`${o}px`),i.setAttributeNS(null,"viewBox",`0 0 ${o} ${r}`);const s=n.createNS("http://www.w3.org/2000/svg","g");s.setAttributeNS(null,"stroke","none"),s.setAttributeNS(null,"stroke-width","1"),s.setAttributeNS(null,"fill","none"),s.setAttributeNS(null,"fill-rule","evenodd");const a=n.createNS("http://www.w3.org/2000/svg","g");a.setAttributeNS(null,"fill-rule","nonzero");const l=n.createNS("http://www.w3.org/2000/svg","g");l.setAttributeNS(null,"transform","translate(3.0, 29.0)"),l.setAttributeNS(null,"fill","#000000");const c=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(const e of c){const t=n.createNS("http://www.w3.org/2000/svg","ellipse");t.setAttributeNS(null,"opacity","0.04"),t.setAttributeNS(null,"cx","10.5"),t.setAttributeNS(null,"cy","5.80029008"),t.setAttributeNS(null,"rx",e.rx),t.setAttributeNS(null,"ry",e.ry),l.appendChild(t);}const h=n.createNS("http://www.w3.org/2000/svg","g");h.setAttributeNS(null,"fill",this._color);const u=n.createNS("http://www.w3.org/2000/svg","path");u.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),h.appendChild(u);const d=n.createNS("http://www.w3.org/2000/svg","g");d.setAttributeNS(null,"opacity","0.25"),d.setAttributeNS(null,"fill","#000000");const _=n.createNS("http://www.w3.org/2000/svg","path");_.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),d.appendChild(_);const p=n.createNS("http://www.w3.org/2000/svg","g");p.setAttributeNS(null,"transform","translate(6.0, 7.0)"),p.setAttributeNS(null,"fill","#FFFFFF");const m=n.createNS("http://www.w3.org/2000/svg","g");m.setAttributeNS(null,"transform","translate(8.0, 8.0)");const f=n.createNS("http://www.w3.org/2000/svg","circle");f.setAttributeNS(null,"fill","#000000"),f.setAttributeNS(null,"opacity","0.25"),f.setAttributeNS(null,"cx","5.5"),f.setAttributeNS(null,"cy","5.5"),f.setAttributeNS(null,"r","5.4999962");const g=n.createNS("http://www.w3.org/2000/svg","circle");g.setAttributeNS(null,"fill","#FFFFFF"),g.setAttributeNS(null,"cx","5.5"),g.setAttributeNS(null,"cy","5.5"),g.setAttributeNS(null,"r","5.4999962"),m.appendChild(f),m.appendChild(g),a.appendChild(l),a.appendChild(h),a.appendChild(d),a.appendChild(p),a.appendChild(m),i.appendChild(a),i.setAttributeNS(null,"height",r*this._scale+"px"),i.setAttributeNS(null,"width",o*this._scale+"px"),this._element.appendChild(i),this._offset=t.P.convert(e&&e.offset||[0,-14]);}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(e=>{e.preventDefault();})),this._element.addEventListener("mousedown",(e=>{e.preventDefault();})),Os(this._element,this._anchor,"marker"),e&&e.className)for(const t of e.className.split(" "))this._element.classList.add(t);this._popup=null;}addTo(e){return this.remove(),this._map=e,this._element.setAttribute("aria-label",e._getUIString("Marker.Title")),e.getCanvasContainer().appendChild(this._element),e.on("move",this._update),e.on("moveend",this._update),e.on("terrain",this._update),e.on("projectiontransition",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("projectiontransition",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),n.remove(this._element),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.N.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(e){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),e){if(!("offset"in e.options)){const t=38.1,i=13.5,r=Math.abs(i)/Math.SQRT2;e.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[r,-1*(t-i+r)],"bottom-right":[-r,-1*(t-i+r)],left:[i,-1*(t-i)],right:[-13.5,-1*(t-i)]}:this._offset;}this._popup=e,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress);}return this}setSubpixelPositioning(e){return this._subpixelPositioning=e,this}getPopup(){return this._popup}togglePopup(){const e=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:e?(e.isOpen()?e.remove():(e.setLngLat(this._lngLat),e.addTo(this._map)),this):this}_updateOpacity(e=false){var i,r;if(!(null===(i=this._map)||undefined===i?undefined:i.terrain)){const e=this._map.transform.isLocationOccluded(this._lngLat)?this._opacityWhenCovered:this._opacity;return void(this._element.style.opacity!==e&&(this._element.style.opacity=e))}if(e)this._opacityTimeout=null;else {if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null;}),100);}const o=this._map,s=o.terrain.depthAtPoint(this._pos),a=o.terrain.getElevationForLngLatZoom(this._lngLat,o.transform.tileZoom);if(o.transform.lngLatToCameraDepth(this._lngLat,a)-s<.006)return void(this._element.style.opacity=this._opacity);const n=-this._offset.y/o.transform.pixelsPerMeter,l=Math.sin(o.getPitch()*Math.PI/180)*n,c=o.terrain.depthAtPoint(new t.P(this._pos.x,this._pos.y-this._offset.y)),h=o.transform.lngLatToCameraDepth(this._lngLat,a+l)-c>.006;(null===(r=this._popup)||undefined===r?undefined:r.isOpen())&&h&&this._popup.remove(),this._element.style.opacity=h?this._opacityWhenCovered:this._opacity;}getOffset(){return this._offset}setOffset(e){return this._offset=t.P.convert(e),this._update(),this}addClassName(e){this._element.classList.add(e);}removeClassName(e){this._element.classList.remove(e);}toggleClassName(e){return this._element.classList.toggle(e)}setDraggable(e){return this._draggable=!!e,this._map&&(e?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(e){return this._rotation=e||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e&&"auto"!==e?e:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(e,t){return undefined===e&&undefined===t&&(this._opacity="1",this._opacityWhenCovered="0.2"),undefined!==e&&(this._opacity=e),undefined!==t&&(this._opacityWhenCovered=t),this._map&&this._updateOpacity(true),this}}const Zs={positionOptions:{enableHighAccuracy:false,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:false,showAccuracyCircle:true,showUserLocation:true};let Gs=0,Us=false;const Vs={maxWidth:100,unit:"metric"};function qs(e,t,i){const r=i&&i.maxWidth||100,o=e._container.clientHeight/2,s=e._container.clientWidth/2,a=e.unproject([s-r/2,o]),n=e.unproject([s+r/2,o]),l=Math.round(e.project(n).x-e.project(a).x),c=Math.min(r,l,e._container.clientWidth),h=a.distanceTo(n);if(i&&"imperial"===i.unit){const i=3.2808*h;i>5280?Hs(t,c,i/5280,e._getUIString("ScaleControl.Miles")):Hs(t,c,i,e._getUIString("ScaleControl.Feet"));}else i&&"nautical"===i.unit?Hs(t,c,h/1852,e._getUIString("ScaleControl.NauticalMiles")):h>=1e3?Hs(t,c,h/1e3,e._getUIString("ScaleControl.Kilometers")):Hs(t,c,h,e._getUIString("ScaleControl.Meters"));}function Hs(e,t,i,r){const o=function(e){const t=Math.pow(10,`${Math.floor(e)}`.length-1);let i=e/t;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:i>=1?1:function(e){const t=Math.pow(10,Math.ceil(-Math.log(e)/Math.LN10));return Math.round(e*t)/t}(i),t*i}(i);e.style.width=t*(o/i)+"px",e.innerHTML=`${o} ${r}`;}const Ws={closeButton:true,closeOnClick:true,focusAfterOpen:true,className:"",maxWidth:"240px",subpixelPositioning:false},Xs=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function $s(e){if(e){if("number"==typeof e){const i=Math.round(Math.abs(e)/Math.SQRT2);return {center:new t.P(0,0),top:new t.P(0,e),"top-left":new t.P(i,i),"top-right":new t.P(-i,i),bottom:new t.P(0,-e),"bottom-left":new t.P(i,-i),"bottom-right":new t.P(-i,-i),left:new t.P(e,0),right:new t.P(-e,0)}}if(e instanceof t.P||Array.isArray(e)){const i=t.P.convert(e);return {center:i,top:i,"top-left":i,"top-right":i,bottom:i,"bottom-left":i,"bottom-right":i,left:i,right:i}}return {center:t.P.convert(e.center||[0,0]),top:t.P.convert(e.top||[0,0]),"top-left":t.P.convert(e["top-left"]||[0,0]),"top-right":t.P.convert(e["top-right"]||[0,0]),bottom:t.P.convert(e.bottom||[0,0]),"bottom-left":t.P.convert(e["bottom-left"]||[0,0]),"bottom-right":t.P.convert(e["bottom-right"]||[0,0]),left:t.P.convert(e.left||[0,0]),right:t.P.convert(e.right||[0,0])}}return $s(new t.P(0,0))}const Ks=i;e.AJAXError=t.cg,e.Event=t.k,e.Evented=t.E,e.LngLat=t.N,e.MercatorCoordinate=t.Y,e.Point=t.P,e.addProtocol=t.ch,e.config=t.a,e.removeProtocol=t.ci,e.AttributionControl=ws,e.BoxZoomHandler=jo,e.CanvasSource=J,e.CooperativeGesturesHandler=ms,e.DoubleClickZoomHandler=cs,e.DragPanHandler=ds,e.DragRotateHandler=_s,e.EdgeInsets=Pt,e.FullscreenControl=class extends t.E{constructor(e={}){super(),this._onFullscreenChange=()=>{var e;let t=window.document.fullscreenElement||window.document.mozFullScreenElement||window.document.webkitFullscreenElement||window.document.msFullscreenElement;for(;null===(e=null==t?undefined:t.shadowRoot)||undefined===e?undefined:e.fullscreenElement;)t=t.shadowRoot.fullscreenElement;t===this._container!==this._fullscreen&&this._handleFullscreenChange();},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen();},this._fullscreen=false,e&&e.container&&(e.container instanceof HTMLElement?this._container=e.container:t.w("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange");}onAdd(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){n.remove(this._controlContainer),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange);}_setupUI(){const e=this._fullscreenButton=n.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);n.create("span","maplibregl-ctrl-icon",e).setAttribute("aria-hidden","true"),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange);}_updateTitle(){const e=this._getTitle();this._fullscreenButton.setAttribute("aria-label",e),this._fullscreenButton.title=e;}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink"),this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen"),this._updateTitle(),this._fullscreen?(this.fire(new t.k("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new t.k("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable());}_exitFullscreen(){window.document.exitFullscreen?window.document.exitFullscreen():window.document.mozCancelFullScreen?window.document.mozCancelFullScreen():window.document.msExitFullscreen?window.document.msExitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen();}_requestFullscreen(){this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen();}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize();}},e.GeoJSONSource=$,e.GeolocateControl=class extends t.E{constructor(e){super(),this._onSuccess=e=>{if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.k("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new t.k("geolocate",e)),this._finish();}},this._updateCamera=e=>{const i=new t.N(e.coords.longitude,e.coords.latitude),r=e.coords.accuracy,o=this._map.getBearing(),s=t.e({bearing:o},this.options.fitBoundsOptions),a=V.fromLngLat(i,r);this._map.fitBounds(a,s,{geolocateSource:true});},this._updateMarker=e=>{if(e){const i=new t.N(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=e.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},this._onZoom=()=>{this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();},this._onError=e=>{if(this._map){if(this.options.trackUserLocation)if(1===e.code){this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=true;const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e),undefined!==this._geolocationWatchID&&this._clearWatch();}else {if(3===e.code&&Us)return;this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new t.k("error",e)),this._finish();}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=undefined;},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this._geolocateButton=n.create("button","maplibregl-ctrl-geolocate",this._container),n.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=true);},this._finishSetupUI=e=>{if(this._map){if(false===e){t.w("Geolocation support is not available so the GeolocateControl will be disabled.");const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=true,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}else {const e=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=false,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=n.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new Ns({element:this._dotElement}),this._circleElement=n.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Ns({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=true,this.options.trackUserLocation&&this._map.on("movestart",(e=>{e.geolocateSource||"ACTIVE_LOCK"!==this._watchState||e.originalEvent&&"resize"===e.originalEvent.type||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new t.k("trackuserlocationend")),this.fire(new t.k("userlocationlostfocus")));}));}},this.options=t.e({},Zs,e);}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),function(){return t._(this,arguments,undefined,(function*(e=false){if(undefined!==Fs&&!e)return Fs;if(undefined===window.navigator.permissions)return Fs=!!window.navigator.geolocation,Fs;try{const e=yield window.navigator.permissions.query({name:"geolocation"});Fs="denied"!==e.state;}catch(e){Fs=!!window.navigator.geolocation;}return Fs}))}().then((e=>this._finishSetupUI(e))),this._container}onRemove(){undefined!==this._geolocationWatchID&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=undefined),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),n.remove(this._container),this._map.off("zoom",this._onZoom),this._map=undefined,Gs=0,Us=false;}_isOutOfMapMaxBounds(e){const t=this._map.getMaxBounds(),i=e.coords;return t&&(i.longitudet.getEast()||i.latitudet.getNorth())}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"ACTIVE_ERROR":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadius(){const e=this._map.getBounds(),t=e.getSouthEast(),i=e.getNorthEast(),r=t.distanceTo(i),o=Math.ceil(this._accuracy/(r/this._map._container.clientHeight)*2);this._circleElement.style.width=`${o}px`,this._circleElement.style.height=`${o}px`;}trigger(){if(!this._setup)return t.w("Geolocate control triggered before added to a map"),false;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.k("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":Gs--,Us=false,this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this.fire(new t.k("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.k("trackuserlocationstart")),this.fire(new t.k("userlocationfocus"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if("OFF"===this._watchState&&undefined!==this._geolocationWatchID)this._clearWatch();else if(undefined===this._geolocationWatchID){let e;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),Gs++,Gs>1?(e={maximumAge:6e5,timeout:0},Us=true):(e=this.options.positionOptions,Us=false),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e);}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return true}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=undefined,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);}},e.GlobeControl=class{constructor(){this._toggleProjection=()=>{var e;const t=null===(e=this._map.getProjection())||undefined===e?undefined:e.type;this._map.setProjection("mercator"!==t&&t?{type:"mercator"}:{type:"globe"}),this._updateGlobeIcon();},this._updateGlobeIcon=()=>{var e;this._globeButton.classList.remove("maplibregl-ctrl-globe"),this._globeButton.classList.remove("maplibregl-ctrl-globe-enabled"),"globe"===(null===(e=this._map.getProjection())||undefined===e?undefined:e.type)?(this._globeButton.classList.add("maplibregl-ctrl-globe-enabled"),this._globeButton.title=this._map._getUIString("GlobeControl.Disable")):(this._globeButton.classList.add("maplibregl-ctrl-globe"),this._globeButton.title=this._map._getUIString("GlobeControl.Enable"));};}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._globeButton=n.create("button","maplibregl-ctrl-globe",this._container),n.create("span","maplibregl-ctrl-icon",this._globeButton).setAttribute("aria-hidden","true"),this._globeButton.type="button",this._globeButton.addEventListener("click",this._toggleProjection),this._updateGlobeIcon(),this._map.on("styledata",this._updateGlobeIcon),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateGlobeIcon),this._globeButton.removeEventListener("click",this._toggleProjection),this._map=undefined;}},e.Hash=wo,e.ImageSource=K,e.KeyboardHandler=ss,e.LngLatBounds=V,e.LogoControl=Ts,e.Map=class extends bs{constructor(e){var i,r;t.cd.mark(t.ce.create);const o=Object.assign(Object.assign(Object.assign({},As),e),{canvasContextAttributes:Object.assign(Object.assign({},As.canvasContextAttributes),e.canvasContextAttributes)});if(null!=o.minZoom&&null!=o.maxZoom&&o.minZoom>o.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=o.minPitch&&null!=o.maxPitch&&o.minPitch>o.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=o.minPitch&&o.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=o.maxPitch&&o.maxPitch>180)throw new Error("maxPitch must be less than or equal to 180");const s=new Dt,a=new kt;if(undefined!==o.minZoom&&s.setMinZoom(o.minZoom),undefined!==o.maxZoom&&s.setMaxZoom(o.maxZoom),undefined!==o.minPitch&&s.setMinPitch(o.minPitch),undefined!==o.maxPitch&&s.setMaxPitch(o.maxPitch),undefined!==o.renderWorldCopies&&s.setRenderWorldCopies(o.renderWorldCopies),super(s,a,{bearingSnap:o.bearingSnap}),this._idleTriggered=false,this._crossFadingFactor=1,this._renderTaskQueue=new Ps,this._controls=[],this._mapId=t.a1(),this._contextLost=e=>{e.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.fire(new t.k("webglcontextlost",{originalEvent:e}));},this._contextRestored=e=>{this._setupPainter(),this.resize(),this._update(),this.fire(new t.k("webglcontextrestored",{originalEvent:e}));},this._onMapScroll=e=>{if(e.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,false},this._onWindowOnline=()=>{this._update();},this._interactive=o.interactive,this._maxTileCacheSize=o.maxTileCacheSize,this._maxTileCacheZoomLevels=o.maxTileCacheZoomLevels,this._canvasContextAttributes=Object.assign({},o.canvasContextAttributes),this._trackResize=true===o.trackResize,this._bearingSnap=o.bearingSnap,this._centerClampedToGround=o.centerClampedToGround,this._refreshExpiredTiles=true===o.refreshExpiredTiles,this._fadeDuration=o.fadeDuration,this._crossSourceCollisions=true===o.crossSourceCollisions,this._collectResourceTiming=true===o.collectResourceTiming,this._locale=Object.assign(Object.assign({},Ds),o.locale),this._clickTolerance=o.clickTolerance,this._overridePixelRatio=o.pixelRatio,this._maxCanvasSize=o.maxCanvasSize,this.transformCameraUpdate=o.transformCameraUpdate,this.cancelPendingTileRequestsWhileZooming=true===o.cancelPendingTileRequestsWhileZooming,this._imageQueueHandle=p.addThrottleControl((()=>this.isMoving())),this._requestManager=new m(o.transformRequest),"string"==typeof o.container){if(this._container=document.getElementById(o.container),!this._container)throw new Error(`Container '${o.container}' not found.`)}else {if(!(o.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=o.container;}if(o.maxBounds&&this.setMaxBounds(o.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(false))),this.on("moveend",(()=>this._update(false))),this.on("zoom",(()=>this._update(true))),this.on("terrain",(()=>{this.painter.terrainFacilitator.dirty=true,this._update(true);})),this.once("idle",(()=>{this._idleTriggered=true;})),"undefined"!=typeof window){addEventListener("online",this._onWindowOnline,false);let e=false;const t=yo((e=>{this._trackResize&&!this._removed&&(this.resize(e),this.redraw());}),50);this._resizeObserver=new ResizeObserver((i=>{e?t(i):e=true;})),this._resizeObserver.observe(this._container);}this.handlers=new xs(this,o),this._hash=o.hash&&new wo("string"==typeof o.hash&&o.hash||undefined).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:o.center,elevation:o.elevation,zoom:o.zoom,bearing:o.bearing,pitch:o.pitch,roll:o.roll}),o.bounds&&(this.resize(),this.fitBounds(o.bounds,t.e({},o.fitBoundsOptions,{duration:0}))));const n="string"==typeof o.style||!("globe"===(null===(r=null===(i=o.style)||undefined===i?undefined:i.projection)||undefined===r?undefined:r.type));this.resize(null,n),this._localIdeographFontFamily=o.localIdeographFontFamily,this._validateStyle=o.validateStyle,o.style&&this.setStyle(o.style,{localIdeographFontFamily:o.localIdeographFontFamily}),o.attributionControl&&this.addControl(new ws("boolean"==typeof o.attributionControl?undefined:o.attributionControl)),o.maplibreLogo&&this.addControl(new Ts,o.logoPosition),this.on("style.load",(()=>{if(n||this._resizeTransform(),this.transform.unmodified){const e=t.M(this.style.stylesheet,["center","zoom","bearing","pitch","roll"]);this.jumpTo(e);}})),this.on("data",(e=>{this._update("style"===e.dataType),this.fire(new t.k(`${e.dataType}data`,e));})),this.on("dataloading",(e=>{this.fire(new t.k(`${e.dataType}dataloading`,e));})),this.on("dataabort",(e=>{this.fire(new t.k("sourcedataabort",e));}));}_getMapId(){return this._mapId}addControl(e,i){if(undefined===i&&(i=e.getDefaultPosition?e.getDefaultPosition():"top-right"),!e||!e.onAdd)return this.fire(new t.j(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const r=e.onAdd(this);this._controls.push(e);const o=this._controlPositions[i];return -1!==i.indexOf("bottom")?o.insertBefore(r,o.firstChild):o.appendChild(r),this}removeControl(e){if(!e||!e.onRemove)return this.fire(new t.j(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const i=this._controls.indexOf(e);return i>-1&&this._controls.splice(i,1),e.onRemove(this),this}hasControl(e){return this._controls.indexOf(e)>-1}calculateCameraOptionsFromTo(e,t,i,r){return null==r&&this.terrain&&(r=this.terrain.getElevationForLngLatZoom(i,this.transform.tileZoom)),super.calculateCameraOptionsFromTo(e,t,i,r)}resize(e,i=true){const[r,o]=this._containerDimensions(),s=this._getClampedPixelRatio(r,o);if(this._resizeCanvas(r,o,s),this.painter.resize(r,o,s),this.painter.overLimit()){const e=this.painter.context.gl;this._maxCanvasSize=[e.drawingBufferWidth,e.drawingBufferHeight];const t=this._getClampedPixelRatio(r,o);this._resizeCanvas(r,o,t),this.painter.resize(r,o,t);}this._resizeTransform(i);const a=!this._moving;return a&&(this.stop(),this.fire(new t.k("movestart",e)).fire(new t.k("move",e))),this.fire(new t.k("resize",e)),a&&this.fire(new t.k("moveend",e)),this}_resizeTransform(e=true){var t;const[i,r]=this._containerDimensions();this.transform.resize(i,r,e),null===(t=this._requestedCameraState)||undefined===t||t.resize(i,r,e);}_getClampedPixelRatio(e,t){const{0:i,1:r}=this._maxCanvasSize,o=this.getPixelRatio(),s=e*o,a=t*o;return Math.min(s>i?i/s:1,a>r?r/a:1)*o}getPixelRatio(){var e;return null!==(e=this._overridePixelRatio)&&undefined!==e?e:devicePixelRatio}setPixelRatio(e){this._overridePixelRatio=e,this.resize();}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(e){return this.transform.setMaxBounds(V.convert(e)),this._update()}setMinZoom(e){if((e=null==e?-2:e)>=-2&&e<=this.transform.maxZoom)return this.transform.setMinZoom(e),this._update(),this.getZoom()=this.transform.minZoom)return this.transform.setMaxZoom(e),this._update(),this.getZoom()>e&&this.setZoom(e),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(e){if((e=null==e?0:e)<0)throw new Error("minPitch must be greater than or equal to 0");if(e>=0&&e<=this.transform.maxPitch)return this.transform.setMinPitch(e),this._update(),this.getPitch()180)throw new Error("maxPitch must be less than or equal to 180");if(e>=this.transform.minPitch)return this.transform.setMaxPitch(e),this._update(),this.getPitch()>e&&this.setPitch(e),this;throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(e){return this.transform.setRenderWorldCopies(e),this._update()}project(e){return this.transform.locationToScreenPoint(t.N.convert(e),this.style&&this.terrain)}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this.terrain)}isMoving(){var e;return this._moving||(null===(e=this.handlers)||undefined===e?undefined:e.isMoving())}isZooming(){var e;return this._zooming||(null===(e=this.handlers)||undefined===e?undefined:e.isZooming())}isRotating(){var e;return this._rotating||(null===(e=this.handlers)||undefined===e?undefined:e.isRotating())}_createDelegatedListener(e,t,i){if("mouseenter"===e||"mouseover"===e){let r=false;const o=o=>{const s=t.filter((e=>this.getLayer(e))),a=0!==s.length?this.queryRenderedFeatures(o.point,{layers:s}):[];a.length?r||(r=true,i.call(this,new zo(e,this,o.originalEvent,{features:a}))):r=false;};return {layers:t,listener:i,delegates:{mousemove:o,mouseout:()=>{r=false;}}}}if("mouseleave"===e||"mouseout"===e){let r=false;const o=o=>{const s=t.filter((e=>this.getLayer(e)));(0!==s.length?this.queryRenderedFeatures(o.point,{layers:s}):[]).length?r=true:r&&(r=false,i.call(this,new zo(e,this,o.originalEvent)));},s=t=>{r&&(r=false,i.call(this,new zo(e,this,t.originalEvent)));};return {layers:t,listener:i,delegates:{mousemove:o,mouseout:s}}}{const r=e=>{const r=t.filter((e=>this.getLayer(e))),o=0!==r.length?this.queryRenderedFeatures(e.point,{layers:r}):[];o.length&&(e.features=o,i.call(this,e),delete e.features);};return {layers:t,listener:i,delegates:{[e]:r}}}}_saveDelegatedListener(e,t){this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(t);}_removeDelegatedListener(e,t,i){if(!this._delegatedListeners||!this._delegatedListeners[e])return;const r=this._delegatedListeners[e];for(let e=0;et.includes(e)))){for(const e in o.delegates)this.off(e,o.delegates[e]);return void r.splice(e,1)}}}on(e,t,i){if(undefined===i)return super.on(e,t);const r="string"==typeof t?[t]:t,o=this._createDelegatedListener(e,r,i);this._saveDelegatedListener(e,o);for(const e in o.delegates)this.on(e,o.delegates[e]);return {unsubscribe:()=>{this._removeDelegatedListener(e,r,i);}}}once(e,t,i){if(undefined===i)return super.once(e,t);const r="string"==typeof t?[t]:t,o=this._createDelegatedListener(e,r,i);for(const t in o.delegates){const s=o.delegates[t];o.delegates[t]=(...t)=>{this._removeDelegatedListener(e,r,i),s(...t);};}this._saveDelegatedListener(e,o);for(const e in o.delegates)this.once(e,o.delegates[e]);return this}off(e,t,i){return undefined===i?super.off(e,t):(this._removeDelegatedListener(e,"string"==typeof t?[t]:t,i),this)}queryRenderedFeatures(e,i){if(!this.style)return [];let r;const o=e instanceof t.P||Array.isArray(e),s=o?e:[[0,0],[this.transform.width,this.transform.height]];if(i=i||(o?{}:e)||{},s instanceof t.P||"number"==typeof s[0])r=[t.P.convert(s)];else {const e=t.P.convert(s[0]),i=t.P.convert(s[1]);r=[e,new t.P(i.x,e.y),i,new t.P(e.x,i.y),e];}return this.style.queryRenderedFeatures(r,i,this.transform)}querySourceFeatures(e,t){return this.style.querySourceFeatures(e,t)}setStyle(e,i){return false!==(i=t.e({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},i)).diff&&i.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&e?(this._diffStyle(e,i),this):(this._localIdeographFontFamily=i.localIdeographFontFamily,this._updateStyle(e,i))}setTransformRequest(e){return this._requestManager.setTransformRequest(e),this}_getUIString(e){const t=this._locale[e];if(null==t)throw new Error(`Missing UI string '${e}'`);return t}_updateStyle(e,t){var i,r;if(t.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(e,t)));const o=this.style&&t.transformStyle?this.style.serialize():undefined;return this.style&&(this.style.setEventedParent(null),this.style._remove(!e)),e?(this.style=new gi(this,t||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof e?this.style.loadURL(e,t,o):this.style.loadJSON(e,t,o),this):(null===(r=null===(i=this.style)||undefined===i?undefined:i.projection)||undefined===r||r.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new gi(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty());}_diffStyle(e,i){if("string"==typeof e){const r=this._requestManager.transformRequest(e,"Style");t.h(r,new AbortController).then((e=>{this._updateDiff(e.data,i);})).catch((e=>{e&&this.fire(new t.j(e));}));}else "object"==typeof e&&this._updateDiff(e,i);}_updateDiff(e,i){try{this.style.setState(e,i)&&this._update(!0);}catch(r){t.w(`Unable to perform style diff: ${r.message||r.error||r}. Rebuilding the style from scratch.`),this._updateStyle(e,i);}}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():t.w("There is no style added to the map.")}addSource(e,t){return this._lazyInitEmptyStyle(),this.style.addSource(e,t),this._update(true)}isSourceLoaded(e){const i=this.style&&this.style.sourceCaches[e];if(undefined!==i)return i.loaded();this.fire(new t.j(new Error(`There is no source with ID '${e}'`)));}setTerrain(e){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),e){const i=this.style.sourceCaches[e.source];if(!i)throw new Error(`cannot load terrain, because there exists no source with ID: ${e.source}`);null===this.terrain&&i.reload();for(const i in this.style._layers){const r=this.style._layers[i];"hillshade"===r.type&&r.source===e.source&&t.w("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.");}this.terrain=new Es(this.painter,i,e),this.painter.renderToTexture=new Rs(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=t=>{"style"===t.dataType?this.terrain.sourceCache.freeRtt():"source"===t.dataType&&t.tile&&(t.sourceId!==e.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),this.terrain.sourceCache.freeRtt(t.tile.tileID));},this.style.on("data",this._terrainDataCallback);}else this.terrain&&this.terrain.sourceCache.destruct(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new t.k("terrain",{terrain:e})),this}getTerrain(){var e,t;return null!==(t=null===(e=this.terrain)||undefined===e?undefined:e.options)&&undefined!==t?t:null}areTilesLoaded(){const e=this.style&&this.style.sourceCaches;for(const t in e){const i=e[t]._tiles;for(const e in i){const t=i[e];if("loaded"!==t.state&&"errored"!==t.state)return false}}return true}removeSource(e){return this.style.removeSource(e),this._update(true)}getSource(e){return this.style.getSource(e)}addImage(e,i,r={}){const{pixelRatio:o=1,sdf:s=false,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u}=r;if(this._lazyInitEmptyStyle(),!(i instanceof HTMLImageElement||t.b(i))){if(undefined===i.width||undefined===i.height)return this.fire(new t.j(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{const{width:r,height:a,data:d}=i,_=i;return this.style.addImage(e,{data:new t.R({width:r,height:a},new Uint8Array(d)),pixelRatio:o,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:s,version:0,userImage:_}),_.onAdd&&_.onAdd(this,e),this}}{const{width:r,height:d,data:_}=a.getImageData(i);this.style.addImage(e,{data:new t.R({width:r,height:d},_),pixelRatio:o,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:s,version:0});}}updateImage(e,i){const r=this.style.getImage(e);if(!r)return this.fire(new t.j(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const o=i instanceof HTMLImageElement||t.b(i)?a.getImageData(i):i,{width:s,height:n,data:l}=o;if(undefined===s||undefined===n)return this.fire(new t.j(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(s!==r.data.width||n!==r.data.height)return this.fire(new t.j(new Error("The width and height of the updated image must be that same as the previous version of the image")));const c=!(i instanceof HTMLImageElement||t.b(i));return r.data.replace(l,c),this.style.updateImage(e,r),this}getImage(e){return this.style.getImage(e)}hasImage(e){return e?!!this.style.getImage(e):(this.fire(new t.j(new Error("Missing required image id"))),false)}removeImage(e){this.style.removeImage(e);}loadImage(e){return p.getImage(this._requestManager.transformRequest(e,"Image"),new AbortController)}listImages(){return this.style.listImages()}addLayer(e,t){return this._lazyInitEmptyStyle(),this.style.addLayer(e,t),this._update(true)}moveLayer(e,t){return this.style.moveLayer(e,t),this._update(true)}removeLayer(e){return this.style.removeLayer(e),this._update(true)}getLayer(e){return this.style.getLayer(e)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(e,t,i){return this.style.setLayerZoomRange(e,t,i),this._update(true)}setFilter(e,t,i={}){return this.style.setFilter(e,t,i),this._update(true)}getFilter(e){return this.style.getFilter(e)}setPaintProperty(e,t,i,r={}){return this.style.setPaintProperty(e,t,i,r),this._update(true)}getPaintProperty(e,t){return this.style.getPaintProperty(e,t)}setLayoutProperty(e,t,i,r={}){return this.style.setLayoutProperty(e,t,i,r),this._update(true)}getLayoutProperty(e,t){return this.style.getLayoutProperty(e,t)}setGlyphs(e,t={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(e,t),this._update(true)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(e,t,i={}){return this._lazyInitEmptyStyle(),this.style.addSprite(e,t,i,(e=>{e||this._update(true);})),this}removeSprite(e){return this._lazyInitEmptyStyle(),this.style.removeSprite(e),this._update(true)}getSprite(){return this.style.getSprite()}setSprite(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSprite(e,t,(e=>{e||this._update(true);})),this}setLight(e,t={}){return this._lazyInitEmptyStyle(),this.style.setLight(e,t),this._update(true)}getLight(){return this.style.getLight()}setSky(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSky(e,t),this._update(true)}getSky(){return this.style.getSky()}setFeatureState(e,t){return this.style.setFeatureState(e,t),this._update()}removeFeatureState(e,t){return this.style.removeFeatureState(e,t),this._update()}getFeatureState(e){return this.style.getFeatureState(e)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let e=0,t=0;return this._container&&(e=this._container.clientWidth||400,t=this._container.clientHeight||300),[e,t]}_setupContainer(){const e=this._container;e.classList.add("maplibregl-map");const t=this._canvasContainer=n.create("div","maplibregl-canvas-container",e);this._interactive&&t.classList.add("maplibregl-interactive"),this._canvas=n.create("canvas","maplibregl-canvas",t),this._canvas.addEventListener("webglcontextlost",this._contextLost,false),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,false),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");const i=this._containerDimensions(),r=this._getClampedPixelRatio(i[0],i[1]);this._resizeCanvas(i[0],i[1],r);const o=this._controlContainer=n.create("div","maplibregl-control-container",e),s=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((e=>{s[e]=n.create("div",`maplibregl-ctrl-${e} `,o);})),this._container.addEventListener("scroll",this._onMapScroll,false);}_resizeCanvas(e,t,i){this._canvas.width=Math.floor(i*e),this._canvas.height=Math.floor(i*t),this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`;}_setupPainter(){const e=Object.assign(Object.assign({},this._canvasContextAttributes),{alpha:true,depth:true,stencil:true,premultipliedAlpha:true});let t=null;this._canvas.addEventListener("webglcontextcreationerror",(i=>{t={requestedAttributes:e},i&&(t.statusMessage=i.statusMessage,t.type=i.type);}),{once:true});let i=null;if(i=this._canvasContextAttributes.contextType?this._canvas.getContext(this._canvasContextAttributes.contextType,e):this._canvas.getContext("webgl2",e)||this._canvas.getContext("webgl",e),!i){const e="Failed to initialize WebGL";throw t?(t.message=e,new Error(JSON.stringify(t))):new Error(e)}this.painter=new bo(i,this.transform),l.testSupport(i);}migrateProjection(e,i){super.migrateProjection(e,i),this.painter.transform=e,this.fire(new t.k("projectiontransition",{newProjection:this.style.projection.name}));}loaded(){return !this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(e){return this.style&&this.style._loaded?(this._styleDirty=this._styleDirty||e,this._sourcesDirty=true,this.triggerRepaint(),this):this}_requestRenderFrame(e){return this._update(),this._renderTaskQueue.add(e)}_cancelRenderFrame(e){this._renderTaskQueue.remove(e);}_render(e){var i,r,o,s,n;const l=this._idleTriggered?this._fadeDuration:0,c=(null===(i=this.style.projection)||undefined===i?undefined:i.transitionState)>0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(e),this._removed)return;let h=false;if(this.style&&this._styleDirty){this._styleDirty=false;const e=this.transform.zoom,i=a.now();this.style.zoomHistory.update(e,i);const r=new t.z(e,{now:i,fadeDuration:l,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),o=r.crossFadingFactor();1===o&&o===this._crossFadingFactor||(h=true,this._crossFadingFactor=o),this.style.update(r);}const u=(null===(r=this.style.projection)||undefined===r?undefined:r.transitionState)>0!==c;null===(o=this.style.projection)||undefined===o||o.setErrorQueryLatitudeDegrees(this.transform.center.lat),this.transform.setTransitionState(null===(s=this.style.projection)||undefined===s?undefined:s.transitionState,null===(n=this.style.projection)||undefined===n?undefined:n.latitudeErrorCorrectionRadians),this.style&&(this._sourcesDirty||u)&&(this._sourcesDirty=false,this.style._updateSources(this.transform)),this.terrain?(this.terrain.sourceCache.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=this.style&&this.style._updatePlacement(this.transform,this.showCollisionBoxes,l,this._crossSourceCollisions,u),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:l,showPadding:this.showPadding}),this.fire(new t.k("render")),this.loaded()&&!this._loaded&&(this._loaded=true,t.cd.mark(t.ce.load),this.fire(new t.k("load"))),this.style&&(this.style.hasTransitions()||h)&&(this._styleDirty=true),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();const d=this._sourcesDirty||this._styleDirty||this._placementDirty;return d||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new t.k("idle")),!this._loaded||this._fullyLoaded||d||(this._fullyLoaded=true,t.cd.mark(t.ce.fullLoad)),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var e;this._hash&&this._hash.remove();for(const e of this._controls)e.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),"undefined"!=typeof window&&removeEventListener("online",this._onWindowOnline,false),p.removeThrottleControl(this._imageQueueHandle),null===(e=this._resizeObserver)||undefined===e||e.disconnect();const i=this.painter.context.gl.getExtension("WEBGL_lose_context");(null==i?undefined:i.loseContext)&&i.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,false),this._canvas.removeEventListener("webglcontextlost",this._contextLost,false),n.remove(this._canvasContainer),n.remove(this._controlContainer),this._container.removeEventListener("scroll",this._onMapScroll,false),this._container.classList.remove("maplibregl-map"),t.cd.clearMetrics(),this._removed=true,this.fire(new t.k("remove"));}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,a.frameAsync(this._frameRequest).then((e=>{t.cd.frame(e),this._frameRequest=null,this._render(e);})).catch((e=>{if(!t.cf(e)&&!function(e){return e.message===Or}(e))throw e})));}get showTileBoundaries(){return !!this._showTileBoundaries}set showTileBoundaries(e){this._showTileBoundaries!==e&&(this._showTileBoundaries=e,this._update());}get showPadding(){return !!this._showPadding}set showPadding(e){this._showPadding!==e&&(this._showPadding=e,this._update());}get showCollisionBoxes(){return !!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,e?this.style._generateCollisionBoxes():this._update());}get showOverdrawInspector(){return !!this._showOverdrawInspector}set showOverdrawInspector(e){this._showOverdrawInspector!==e&&(this._showOverdrawInspector=e,this._update());}get repaint(){return !!this._repaint}set repaint(e){this._repaint!==e&&(this._repaint=e,this.triggerRepaint());}get vertices(){return !!this._vertices}set vertices(e){this._vertices=e,this._update();}get version(){return zs}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(e){return this._lazyInitEmptyStyle(),this.style.setProjection(e),this._update(true)}},e.MapMouseEvent=zo,e.MapTouchEvent=Ao,e.MapWheelEvent=Lo,e.Marker=Ns,e.NavigationControl=class{constructor(e){this._updateZoomButtons=()=>{const e=this._map.getZoom(),t=e===this._map.getMaxZoom(),i=e===this._map.getMinZoom();this._zoomInButton.disabled=t,this._zoomOutButton.disabled=i,this._zoomInButton.setAttribute("aria-disabled",t.toString()),this._zoomOutButton.setAttribute("aria-disabled",i.toString());},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`;},this._setButtonTitle=(e,t)=>{const i=this._map._getUIString(`NavigationControl.${t}`);e.title=i,e.setAttribute("aria-label",i);},this.options=t.e({},Ls,e),this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(e=>this._map.zoomIn({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(e=>this._map.zoomOut({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(e=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:e}):this._map.resetNorth({},{originalEvent:e});})),this._compassIcon=n.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"));}onAdd(e){return this._map=e,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on("roll",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new ks(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){n.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off("roll",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map;}_createButton(e,t){const i=n.create("button",e,this._container);return i.type="button",i.addEventListener("click",t),i}},e.Popup=class extends t.E{constructor(e){super(),this.remove=()=>(this._content&&n.remove(this._content),this._container&&(n.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._onMouseMove),this._map.off("mouseup",this._onMouseUp),this._map.off("drag",this._onDrag),this._map._canvasContainer.classList.remove("maplibregl-track-pointer"),delete this._map,this.fire(new t.k("close"))),this),this._onMouseUp=e=>{this._update(e.point);},this._onMouseMove=e=>{this._update(e.point);},this._onDrag=e=>{this._update(e.point);},this._update=e=>{var t;if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=n.create("div","maplibregl-popup",this._map.getContainer()),this._tip=n.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(const e of this.options.className.split(" "))this._container.classList.add(e);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),this._trackPointer&&this._container.classList.add("maplibregl-popup-track-pointer");}if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=this._map.transform.renderWorldCopies&&!this._trackPointer?Bs(this._lngLat,this._flatPos,this._map.transform):null===(t=this._lngLat)||undefined===t?undefined:t.wrap(),this._trackPointer&&!e)return;const i=this._flatPos=this._pos=this._trackPointer&&e?e:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&e?e:this._map.transform.locationToScreenPoint(this._lngLat));let r=this.options.anchor;const o=$s(this.options.offset);if(!r){const e=this._container.offsetWidth,t=this._container.offsetHeight;let s;s=i.y+o.bottom.ythis._map.transform.height-t?["bottom"]:[],i.xthis._map.transform.width-e/2&&s.push("right"),r=0===s.length?"bottom":s.join("-");}let s=i.add(o[r]);this.options.subpixelPositioning||(s=s.round()),n.setTransform(this._container,`${js[r]} translate(${s.x}px,${s.y}px)`),Os(this._container,r,"popup");},this._onClose=()=>{this.remove();},this.options=t.e(Object.create(Ws),e);}addTo(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new t.k("open")),this}isOpen(){return !!this._map}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.N.convert(e),this._pos=null,this._flatPos=null,this._trackPointer=false,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=true,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(e){return this.setDOMContent(document.createTextNode(e))}setHTML(e){const t=document.createDocumentFragment(),i=document.createElement("body");let r;for(i.innerHTML=e;r=i.firstChild,r;)t.appendChild(r);return this.setDOMContent(t)}getMaxWidth(){var e;return null===(e=this._container)||undefined===e?undefined:e.style.maxWidth}setMaxWidth(e){return this.options.maxWidth=e,this._update(),this}setDOMContent(e){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=n.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(e),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(e){return this._container&&this._container.classList.add(e),this}removeClassName(e){return this._container&&this._container.classList.remove(e),this}setOffset(e){return this.options.offset=e,this._update(),this}toggleClassName(e){if(this._container)return this._container.classList.toggle(e)}setSubpixelPositioning(e){this.options.subpixelPositioning=e;}_createCloseButton(){this.options.closeButton&&(this._closeButton=n.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose));}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const e=this._container.querySelector(Xs);e&&e.focus();}},e.RasterDEMTileSource=X,e.RasterTileSource=W,e.ScaleControl=class{constructor(e){this._onMove=()=>{qs(this._map,this._container,this.options);},this.setUnit=e=>{this.options.unit=e,qs(this._map,this._container,this.options);},this.options=Object.assign(Object.assign({},Vs),e);}getDefaultPosition(){return "bottom-left"}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-scale",e.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){n.remove(this._container),this._map.off("move",this._onMove),this._map=undefined;}},e.ScrollZoomHandler=ls,e.Style=gi,e.TerrainControl=class{constructor(e){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon();},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"));},this.options=e;}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=n.create("button","maplibregl-ctrl-terrain",this._container),n.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true"),this._terrainButton.type="button",this._terrainButton.addEventListener("click",this._toggleTerrain),this._updateTerrainIcon(),this._map.on("terrain",this._updateTerrainIcon),this._container}onRemove(){n.remove(this._container),this._map.off("terrain",this._updateTerrainIcon),this._map=undefined;}},e.TwoFingersTouchPitchHandler=rs,e.TwoFingersTouchRotateHandler=ts,e.TwoFingersTouchZoomHandler=Qo,e.TwoFingersTouchZoomRotateHandler=ps,e.VectorTileSource=H,e.VideoSource=Y,e.addSourceType=(e,i)=>t._(undefined,undefined,undefined,(function*(){if(ee(e))throw new Error(`A source type called "${e}" already exists.`);((e,t)=>{Q[e]=t;})(e,i);})),e.clearPrewarmedResources=function(){const e=L;e&&(e.isPreloaded()&&1===e.numActive()?(e.release(D),L=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"));},e.createTileMesh=Ht,e.getMaxParallelImageRequests=function(){return t.a.MAX_PARALLEL_IMAGE_REQUESTS},e.getRTLTextPluginStatus=function(){return oe().getRTLTextPluginStatus()},e.getVersion=function(){return Ks},e.getWorkerCount=function(){return z.workerCount},e.getWorkerUrl=function(){return t.a.WORKER_URL},e.importScriptInWorkers=function(e){return j().broadcast("IS",e)},e.prewarm=function(){F().acquire(D);},e.setMaxParallelImageRequests=function(e){t.a.MAX_PARALLEL_IMAGE_REQUESTS=e;},e.setRTLTextPlugin=function(e,t){return oe().setRTLTextPlugin(e,t)},e.setWorkerCount=function(e){z.workerCount=e;},e.setWorkerUrl=function(e){t.a.WORKER_URL=e;};})); - - // - // Our custom intro provides a specialized "define()" function, called by the - // AMD modules below, that sets up the worker blob URL and then executes the - // main module, storing its exported value as 'maplibregl' - - - var maplibregl$1 = maplibregl; - - return maplibregl$1; - - })); - - } (maplibreGl$1)); - return maplibreGl$1.exports; - } - - var maplibreGlExports = requireMaplibreGl(); - var maplibregl = /*@__PURE__*/getDefaultExportFromCjs$1(maplibreGlExports); - - function getDefaultExportFromCjs (x) { - return x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function getAugmentedNamespace(n) { - if (n.__esModule) return n; - var f = n.default; - if (typeof f == "function") { - var a = function a () { - if (this instanceof a) { - return Reflect.construct(f, arguments, this.constructor); - } - return f.apply(this, arguments); - }; - a.prototype = f.prototype; - } else a = {}; - Object.defineProperty(a, '__esModule', {value: true}); - Object.keys(n).forEach(function (k) { - var d = Object.getOwnPropertyDescriptor(n, k); - Object.defineProperty(a, k, d.get ? d : { - enumerable: true, - get: function () { - return n[k]; - } - }); - }); - return a; - } - - function objectConverter(columns) { - return new Function("d", "return {" + columns.map(function(name, i) { - return JSON.stringify(name) + ": d[" + i + "]"; - }).join(",") + "}"); - } - - function customConverter(columns, f) { - var object = objectConverter(columns); - return function(row, i) { - return f(object(row), i, columns); - }; - } - - // Compute unique columns in order of discovery. - function inferColumns(rows) { - var columnSet = Object.create(null), - columns = []; - - rows.forEach(function(row) { - for (var column in row) { - if (!(column in columnSet)) { - columns.push(columnSet[column] = column); - } - } - }); - - return columns; - } - - function dsv$1(delimiter) { - var reFormat = new RegExp("[\"" + delimiter + "\n]"), - delimiterCode = delimiter.charCodeAt(0); - - function parse(text, f) { - var convert, columns, rows = parseRows(text, function(row, i) { - if (convert) return convert(row, i - 1); - columns = row, convert = f ? customConverter(row, f) : objectConverter(row); - }); - rows.columns = columns; - return rows; - } - - function parseRows(text, f) { - var EOL = {}, // sentinel value for end-of-line - EOF = {}, // sentinel value for end-of-file - rows = [], // output rows - N = text.length, - I = 0, // current character index - n = 0, // the current line number - t, // the current token - eol; // is the current token followed by EOL? - - function token() { - if (I >= N) return EOF; // special case: end of file - if (eol) return eol = false, EOL; // special case: end of line - - // special case: quotes - var j = I, c; - if (text.charCodeAt(j) === 34) { - var i = j; - while (i++ < N) { - if (text.charCodeAt(i) === 34) { - if (text.charCodeAt(i + 1) !== 34) break; - ++i; - } - } - I = i + 2; - c = text.charCodeAt(i + 1); - if (c === 13) { - eol = true; - if (text.charCodeAt(i + 2) === 10) ++I; - } else if (c === 10) { - eol = true; - } - return text.slice(j + 1, i).replace(/""/g, "\""); - } - - // common case: find next delimiter or newline - while (I < N) { - var k = 1; - c = text.charCodeAt(I++); - if (c === 10) eol = true; // \n - else if (c === 13) { eol = true; if (text.charCodeAt(I) === 10) ++I, ++k; } // \r|\r\n - else if (c !== delimiterCode) continue; - return text.slice(j, I - k); - } - - // special case: last token before EOF - return text.slice(j); - } - - while ((t = token()) !== EOF) { - var a = []; - while (t !== EOL && t !== EOF) { - a.push(t); - t = token(); - } - if (f && (a = f(a, n++)) == null) continue; - rows.push(a); - } - - return rows; - } - - function format(rows, columns) { - if (columns == null) columns = inferColumns(rows); - return [columns.map(formatValue).join(delimiter)].concat(rows.map(function(row) { - return columns.map(function(column) { - return formatValue(row[column]); - }).join(delimiter); - })).join("\n"); - } - - function formatRows(rows) { - return rows.map(formatRow).join("\n"); - } - - function formatRow(row) { - return row.map(formatValue).join(delimiter); - } - - function formatValue(text) { - return text == null ? "" - : reFormat.test(text += "") ? "\"" + text.replace(/\"/g, "\"\"") + "\"" - : text; - } - - return { - parse: parse, - parseRows: parseRows, - format: format, - formatRows: formatRows - }; - } - - var csv = dsv$1(","); - - var csvParse = csv.parse; - var csvParseRows = csv.parseRows; - var csvFormat = csv.format; - var csvFormatRows = csv.formatRows; - - var tsv = dsv$1("\t"); - - var tsvParse = tsv.parse; - var tsvParseRows = tsv.parseRows; - var tsvFormat = tsv.format; - var tsvFormatRows = tsv.formatRows; - - var d3Dsv = /*#__PURE__*/Object.freeze({ - __proto__: null, - csvFormat: csvFormat, - csvFormatRows: csvFormatRows, - csvParse: csvParse, - csvParseRows: csvParseRows, - dsvFormat: dsv$1, - tsvFormat: tsvFormat, - tsvFormatRows: tsvFormatRows, - tsvParse: tsvParse, - tsvParseRows: tsvParseRows - }); - - var require$$0 = /*@__PURE__*/getAugmentedNamespace(d3Dsv); - - var sexagesimal$1 = {exports: {}}; - - sexagesimal$1.exports = element; - sexagesimal$1.exports.pair = pair; - sexagesimal$1.exports.format = format; - sexagesimal$1.exports.formatPair = formatPair; - sexagesimal$1.exports.coordToDMS = coordToDMS; - - - function element(input, dims) { - var result = search(input, dims); - return (result === null) ? null : result.val; - } - - - function formatPair(input) { - return format(input.lat, 'lat') + ' ' + format(input.lon, 'lon'); - } - - - // Is 0 North or South? - function format(input, dim) { - var dms = coordToDMS(input, dim); - return dms.whole + '° ' + - (dms.minutes ? dms.minutes + '\' ' : '') + - (dms.seconds ? dms.seconds + '" ' : '') + dms.dir; - } - - - function coordToDMS(input, dim) { - var dirs = { lat: ['N', 'S'], lon: ['E', 'W'] }[dim] || ''; - var dir = dirs[input >= 0 ? 0 : 1]; - var abs = Math.abs(input); - var whole = Math.floor(abs); - var fraction = abs - whole; - var fractionMinutes = fraction * 60; - var minutes = Math.floor(fractionMinutes); - var seconds = Math.floor((fractionMinutes - minutes) * 60); - - return { - whole: whole, - minutes: minutes, - seconds: seconds, - dir: dir - }; - } - - - function search(input, dims) { - if (!dims) dims = 'NSEW'; - if (typeof input !== 'string') return null; - - input = input.toUpperCase(); - var regex = /^[\s\,]*([NSEW])?\s*([\-|\—|\―]?[0-9.]+)[°º˚]?\s*(?:([0-9.]+)['’′‘]\s*)?(?:([0-9.]+)(?:''|"|”|″)\s*)?([NSEW])?/; - - var m = input.match(regex); - if (!m) return null; // no match - - var matched = m[0]; - - // extract dimension.. m[1] = leading, m[5] = trailing - var dim; - if (m[1] && m[5]) { // if matched both.. - dim = m[1]; // keep leading - matched = matched.slice(0, -1); // remove trailing dimension from match - } else { - dim = m[1] || m[5]; - } - - // if unrecognized dimension - if (dim && dims.indexOf(dim) === -1) return null; - - // extract DMS - var deg = m[2] ? parseFloat(m[2]) : 0; - var min = m[3] ? parseFloat(m[3]) / 60 : 0; - var sec = m[4] ? parseFloat(m[4]) / 3600 : 0; - var sign = (deg < 0) ? -1 : 1; - if (dim === 'S' || dim === 'W') sign *= -1; - - return { - val: (Math.abs(deg) + min + sec) * sign, - dim: dim, - matched: matched, - remain: input.slice(matched.length) - }; - } - - - function pair(input, dims) { - input = input.trim(); - var one = search(input, dims); - if (!one) return null; - - input = one.remain.trim(); - var two = search(input, dims); - if (!two || two.remain) return null; - - if (one.dim) { - return swapdim(one.val, two.val, one.dim); - } else { - return [one.val, two.val]; - } - } - - - function swapdim(a, b, dim) { - if (dim === 'N' || dim === 'S') return [a, b]; - if (dim === 'W' || dim === 'E') return [b, a]; - } - - var sexagesimalExports = sexagesimal$1.exports; - - var dsv = require$$0, - sexagesimal = sexagesimalExports; - - var latRegex = /(Lat)(itude)?/gi, - lonRegex = /(L)(on|ng)(gitude)?/i; - - function guessHeader(row, regexp) { - var name, match, score; - for (var f in row) { - match = f.match(regexp); - if (match && (!name || match[0].length / f.length > score)) { - score = match[0].length / f.length; - name = f; - } - } - return name; - } - - function guessLatHeader(row) { return guessHeader(row, latRegex); } - function guessLonHeader(row) { return guessHeader(row, lonRegex); } - - function isLat(f) { return !!f.match(latRegex); } - function isLon(f) { return !!f.match(lonRegex); } - - function keyCount(o) { - return (typeof o == 'object') ? Object.keys(o).length : 0; - } - - function autoDelimiter(x) { - var delimiters = [',', ';', '\t', '|']; - var results = []; - - delimiters.forEach(function (delimiter) { - var res = dsv.dsvFormat(delimiter).parse(x); - if (res.length >= 1) { - var count = keyCount(res[0]); - for (var i = 0; i < res.length; i++) { - if (keyCount(res[i]) !== count) return; - } - results.push({ - delimiter: delimiter, - arity: Object.keys(res[0]).length, - }); - } - }); - - if (results.length) { - return results.sort(function (a, b) { - return b.arity - a.arity; - })[0].delimiter; - } else { - return null; - } - } - - /** - * Silly stopgap for dsv to d3-dsv upgrade - * - * @param {Array} x dsv output - * @returns {Array} array without columns member - */ - function deleteColumns(x) { - delete x.columns; - return x; - } - - function auto(x) { - var delimiter = autoDelimiter(x); - if (!delimiter) return null; - return deleteColumns(dsv.dsvFormat(delimiter).parse(x)); - } - - function csv2geojson(x, options, callback) { - - if (!callback) { - callback = options; - options = {}; - } - - options.delimiter = options.delimiter || ','; - - var latfield = options.latfield || '', - lonfield = options.lonfield || '', - crs = options.crs || ''; - - var features = [], - featurecollection = {type: 'FeatureCollection', features: features}; - - if (crs !== '') { - featurecollection.crs = {type: 'name', properties: {name: crs}}; - } - - if (options.delimiter === 'auto' && typeof x == 'string') { - options.delimiter = autoDelimiter(x); - if (!options.delimiter) { - callback({ - type: 'Error', - message: 'Could not autodetect delimiter' - }); - return; - } - } - - var numericFields = options.numericFields ? options.numericFields.split(',') : null; - - var parsed = (typeof x == 'string') ? - dsv.dsvFormat(options.delimiter).parse(x, function (d) { - if (numericFields) { - for (var key in d) { - if (numericFields.includes(key)) { - d[key] = +d[key]; - } - } - } - return d; - }) : x; - - if (!parsed.length) { - callback(null, featurecollection); - return; - } - - var errors = []; - var i; - - - if (!latfield) latfield = guessLatHeader(parsed[0]); - if (!lonfield) lonfield = guessLonHeader(parsed[0]); - var noGeometry = (!latfield || !lonfield); - - if (noGeometry) { - for (i = 0; i < parsed.length; i++) { - features.push({ - type: 'Feature', - properties: parsed[i], - geometry: null - }); - } - callback(errors.length ? errors : null, featurecollection); - return; - } - - for (i = 0; i < parsed.length; i++) { - if (parsed[i][lonfield] !== undefined && - parsed[i][latfield] !== undefined) { - - var lonk = parsed[i][lonfield], - latk = parsed[i][latfield], - lonf, latf, - a; - - a = sexagesimal(lonk, 'EW'); - if (a) lonk = a; - a = sexagesimal(latk, 'NS'); - if (a) latk = a; - - lonf = parseFloat(lonk); - latf = parseFloat(latk); - - if (isNaN(lonf) || - isNaN(latf)) { - errors.push({ - message: 'A row contained an invalid value for latitude or longitude', - row: parsed[i], - index: i - }); - } else { - if (!options.includeLatLon) { - delete parsed[i][lonfield]; - delete parsed[i][latfield]; - } - - features.push({ - type: 'Feature', - properties: parsed[i], - geometry: { - type: 'Point', - coordinates: [ - parseFloat(lonf), - parseFloat(latf) - ] - } - }); - } - } - } - - callback(errors.length ? errors : null, featurecollection); - } - - function toLine(gj) { - var features = gj.features; - var line = { - type: 'Feature', - geometry: { - type: 'LineString', - coordinates: [] - } - }; - for (var i = 0; i < features.length; i++) { - line.geometry.coordinates.push(features[i].geometry.coordinates); - } - line.properties = features.reduce(function (aggregatedProperties, newFeature) { - for (var key in newFeature.properties) { - if (!aggregatedProperties[key]) { - aggregatedProperties[key] = []; - } - aggregatedProperties[key].push(newFeature.properties[key]); - } - return aggregatedProperties; - }, {}); - return { - type: 'FeatureCollection', - features: [line] - }; - } - - function toPolygon(gj) { - var features = gj.features; - var poly = { - type: 'Feature', - geometry: { - type: 'Polygon', - coordinates: [[]] - } - }; - for (var i = 0; i < features.length; i++) { - poly.geometry.coordinates[0].push(features[i].geometry.coordinates); - } - poly.properties = features.reduce(function (aggregatedProperties, newFeature) { - for (var key in newFeature.properties) { - if (!aggregatedProperties[key]) { - aggregatedProperties[key] = []; - } - aggregatedProperties[key].push(newFeature.properties[key]); - } - return aggregatedProperties; - }, {}); - return { - type: 'FeatureCollection', - features: [poly] - }; - } - - var csv2geojson_1 = { - isLon: isLon, - isLat: isLat, - guessLatHeader: guessLatHeader, - guessLonHeader: guessLonHeader, - csv: dsv.csvParse, - tsv: dsv.tsvParse, - dsv: dsv, - auto: auto, - csv2geojson: csv2geojson, - toLine: toLine, - toPolygon: toPolygon - }; - - function identity(x) { - return x; - } - - function transform(transform) { - if (transform == null) return identity; - var x0, - y0, - kx = transform.scale[0], - ky = transform.scale[1], - dx = transform.translate[0], - dy = transform.translate[1]; - return function(input, i) { - if (!i) x0 = y0 = 0; - var j = 2, n = input.length, output = new Array(n); - output[0] = (x0 += input[0]) * kx + dx; - output[1] = (y0 += input[1]) * ky + dy; - while (j < n) output[j] = input[j], ++j; - return output; - }; - } - - function reverse(array, n) { - var t, j = array.length, i = j - n; - while (i < --j) t = array[i], array[i++] = array[j], array[j] = t; - } - - function topojsonFeature(topology, o) { - if (typeof o === "string") o = topology.objects[o]; - return o.type === "GeometryCollection" - ? {type: "FeatureCollection", features: o.geometries.map(function(o) { return feature(topology, o); })} - : feature(topology, o); - } - - function feature(topology, o) { - var id = o.id, - bbox = o.bbox, - properties = o.properties == null ? {} : o.properties, - geometry = object(topology, o); - return id == null && bbox == null ? {type: "Feature", properties: properties, geometry: geometry} - : bbox == null ? {type: "Feature", id: id, properties: properties, geometry: geometry} - : {type: "Feature", id: id, bbox: bbox, properties: properties, geometry: geometry}; - } - - function object(topology, o) { - var transformPoint = transform(topology.transform), - arcs = topology.arcs; - - function arc(i, points) { - if (points.length) points.pop(); - for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length; k < n; ++k) { - points.push(transformPoint(a[k], k)); - } - if (i < 0) reverse(points, n); - } - - function point(p) { - return transformPoint(p); - } - - function line(arcs) { - var points = []; - for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points); - if (points.length < 2) points.push(points[0]); // This should never happen per the specification. - return points; - } - - function ring(arcs) { - var points = line(arcs); - while (points.length < 4) points.push(points[0]); // This may happen if an arc has only two points. - return points; - } - - function polygon(arcs) { - return arcs.map(ring); - } - - function geometry(o) { - var type = o.type, coordinates; - switch (type) { - case "GeometryCollection": return {type: type, geometries: o.geometries.map(geometry)}; - case "Point": coordinates = point(o.coordinates); break; - case "MultiPoint": coordinates = o.coordinates.map(point); break; - case "LineString": coordinates = line(o.arcs); break; - case "MultiLineString": coordinates = o.arcs.map(line); break; - case "Polygon": coordinates = polygon(o.arcs); break; - case "MultiPolygon": coordinates = o.arcs.map(polygon); break; - default: return null; - } - return {type: type, coordinates: coordinates}; - } - - return geometry(o); - } - - function $(element, tagName) { - return Array.from(element.getElementsByTagName(tagName)); - } - function normalizeId(id) { - return id[0] === "#" ? id : `#${id}`; - } - function $ns(element, tagName, ns) { - return Array.from(element.getElementsByTagNameNS(ns, tagName)); - } - /** - * get the content of a text node, if any - */ - function nodeVal(node) { - node?.normalize(); - return (node && node.textContent) || ""; - } - /** - * Get one Y child of X, if any, otherwise null - */ - function get1(node, tagName, callback) { - const n = node.getElementsByTagName(tagName); - const result = n.length ? n[0] : null; - if (result && callback) - callback(result); - return result; - } - function get(node, tagName, callback) { - const properties = {}; - if (!node) - return properties; - const n = node.getElementsByTagName(tagName); - const result = n.length ? n[0] : null; - if (result && callback) { - return callback(result, properties); - } - return properties; - } - function val1(node, tagName, callback) { - const val = nodeVal(get1(node, tagName)); - if (val && callback) - return callback(val) || {}; - return {}; - } - function $num(node, tagName, callback) { - const val = parseFloat(nodeVal(get1(node, tagName))); - if (isNaN(val)) - return undefined; - if (val && callback) - return callback(val) || {}; - return {}; - } - function num1(node, tagName, callback) { - const val = parseFloat(nodeVal(get1(node, tagName))); - if (isNaN(val)) - return undefined; - if (callback) - callback(val); - return val; - } - function getMulti(node, propertyNames) { - const properties = {}; - for (const property of propertyNames) { - val1(node, property, (val) => { - properties[property] = val; - }); - } - return properties; - } - function isElement(node) { - return node?.nodeType === 1; - } - - function getLineStyle(node) { - return get(node, "line", (lineStyle) => { - const val = Object.assign({}, val1(lineStyle, "color", (color) => { - return { stroke: `#${color}` }; - }), $num(lineStyle, "opacity", (opacity) => { - return { "stroke-opacity": opacity }; - }), $num(lineStyle, "width", (width) => { - // GPX width is in mm, convert to px with 96 px per inch - return { "stroke-width": (width * 96) / 25.4 }; - })); - return val; - }); - } - - function getExtensions(node) { - let values = []; - if (node === null) - return values; - for (const child of Array.from(node.childNodes)) { - if (!isElement(child)) - continue; - const name = abbreviateName(child.nodeName); - if (name === "gpxtpx:TrackPointExtension") { - // loop again for nested garmin extensions (eg. "gpxtpx:hr") - values = values.concat(getExtensions(child)); - } - else { - // push custom extension (eg. "power") - const val = nodeVal(child); - values.push([name, parseNumeric(val)]); - } - } - return values; - } - function abbreviateName(name) { - return ["heart", "gpxtpx:hr", "hr"].includes(name) ? "heart" : name; - } - function parseNumeric(val) { - const num = parseFloat(val); - return isNaN(num) ? val : num; - } - - function coordPair$1(node) { - const ll = [ - parseFloat(node.getAttribute("lon") || ""), - parseFloat(node.getAttribute("lat") || ""), - ]; - if (isNaN(ll[0]) || isNaN(ll[1])) { - return null; - } - num1(node, "ele", (val) => { - ll.push(val); - }); - const time = get1(node, "time"); - return { - coordinates: ll, - time: time ? nodeVal(time) : null, - extendedValues: getExtensions(get1(node, "extensions")), - }; - } - - function extractProperties(node) { - const properties = getMulti(node, [ - "name", - "cmt", - "desc", - "type", - "time", - "keywords", - ]); - const extensions = Array.from(node.getElementsByTagNameNS("http://www.garmin.com/xmlschemas/GpxExtensions/v3", "*")); - for (const child of extensions) { - if (child.parentNode?.parentNode === node) { - properties[child.tagName.replace(":", "_")] = nodeVal(child); - } - } - const links = $(node, "link"); - if (links.length) { - properties.links = links.map((link) => Object.assign({ href: link.getAttribute("href") }, getMulti(link, ["text", "type"]))); - } - return properties; - } - - /** - * Extract points from a trkseg or rte element. - */ - function getPoints$1(node, pointname) { - const pts = $(node, pointname); - const line = []; - const times = []; - const extendedValues = {}; - for (let i = 0; i < pts.length; i++) { - const c = coordPair$1(pts[i]); - if (!c) { - continue; - } - line.push(c.coordinates); - if (c.time) - times.push(c.time); - for (const [name, val] of c.extendedValues) { - const plural = name === "heart" ? name : name.replace("gpxtpx:", "") + "s"; - if (!extendedValues[plural]) { - extendedValues[plural] = Array(pts.length).fill(null); - } - extendedValues[plural][i] = val; - } - } - if (line.length < 2) - return; // Invalid line in GeoJSON - return { - line: line, - times: times, - extendedValues: extendedValues, - }; - } - /** - * Extract a LineString geometry from a rte - * element. - */ - function getRoute(node) { - const line = getPoints$1(node, "rtept"); - if (!line) - return; - return { - type: "Feature", - properties: Object.assign({ _gpxType: "rte" }, extractProperties(node), getLineStyle(get1(node, "extensions"))), - geometry: { - type: "LineString", - coordinates: line.line, - }, - }; - } - function getTrack(node) { - const segments = $(node, "trkseg"); - const track = []; - const times = []; - const extractedLines = []; - for (const segment of segments) { - const line = getPoints$1(segment, "trkpt"); - if (line) { - extractedLines.push(line); - if (line.times && line.times.length) - times.push(line.times); - } - } - if (extractedLines.length === 0) - return null; - const multi = extractedLines.length > 1; - const properties = Object.assign({ _gpxType: "trk" }, extractProperties(node), getLineStyle(get1(node, "extensions")), times.length - ? { - coordinateProperties: { - times: multi ? times : times[0], - }, - } - : {}); - for (const line of extractedLines) { - track.push(line.line); - if (!properties.coordinateProperties) { - properties.coordinateProperties = {}; - } - const props = properties.coordinateProperties; - const entries = Object.entries(line.extendedValues); - for (let i = 0; i < entries.length; i++) { - const [name, val] = entries[i]; - if (multi) { - if (!props[name]) { - props[name] = extractedLines.map((line) => new Array(line.line.length).fill(null)); - } - props[name][i] = val; - } - else { - props[name] = val; - } - } - } - return { - type: "Feature", - properties: properties, - geometry: multi - ? { - type: "MultiLineString", - coordinates: track, - } - : { - type: "LineString", - coordinates: track[0], - }, - }; - } - /** - * Extract a point, if possible, from a given node, - * which is usually a wpt or trkpt - */ - function getPoint(node) { - const properties = Object.assign(extractProperties(node), getMulti(node, ["sym"])); - const pair = coordPair$1(node); - if (!pair) - return null; - return { - type: "Feature", - properties, - geometry: { - type: "Point", - coordinates: pair.coordinates, - }, - }; - } - /** - * Convert GPX to GeoJSON incrementally, returning - * a [Generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators) - * that yields output feature by feature. - */ - function* gpxGen(node) { - for (const track of $(node, "trk")) { - const feature = getTrack(track); - if (feature) - yield feature; - } - for (const route of $(node, "rte")) { - const feature = getRoute(route); - if (feature) - yield feature; - } - for (const waypoint of $(node, "wpt")) { - const point = getPoint(waypoint); - if (point) - yield point; - } - } - /** - * - * Convert a GPX document to GeoJSON. The first argument, `doc`, must be a GPX - * document as an XML DOM - not as a string. You can get this using jQuery's default - * `.ajax` function or using a bare XMLHttpRequest with the `.response` property - * holding an XML DOM. - * - * The output is a JavaScript object of GeoJSON data, same as `.kml` outputs, with the - * addition of a `_gpxType` property on each `LineString` feature that indicates whether - * the feature was encoded as a route (`rte`) or track (`trk`) in the GPX document. - */ - function gpx(node) { - return { - type: "FeatureCollection", - features: Array.from(gpxGen(node)), - }; - } - - const EXTENSIONS_NS = "http://www.garmin.com/xmlschemas/ActivityExtension/v2"; - const TRACKPOINT_ATTRIBUTES = [ - ["heartRate", "heartRates"], - ["Cadence", "cadences"], - // Extended Trackpoint attributes - ["Speed", "speeds"], - ["Watts", "watts"], - ]; - const LAP_ATTRIBUTES = [ - ["TotalTimeSeconds", "totalTimeSeconds"], - ["DistanceMeters", "distanceMeters"], - ["MaximumSpeed", "maxSpeed"], - ["AverageHeartRateBpm", "avgHeartRate"], - ["MaximumHeartRateBpm", "maxHeartRate"], - // Extended Lap attributes - ["AvgSpeed", "avgSpeed"], - ["AvgWatts", "avgWatts"], - ["MaxWatts", "maxWatts"], - ]; - function getProperties(node, attributeNames) { - const properties = []; - for (const [tag, alias] of attributeNames) { - let elem = get1(node, tag); - if (!elem) { - const elements = node.getElementsByTagNameNS(EXTENSIONS_NS, tag); - if (elements.length) { - elem = elements[0]; - } - } - const val = parseFloat(nodeVal(elem)); - if (!isNaN(val)) { - properties.push([alias, val]); - } - } - return properties; - } - function coordPair(node) { - const ll = [num1(node, "LongitudeDegrees"), num1(node, "LatitudeDegrees")]; - if (ll[0] === undefined || - isNaN(ll[0]) || - ll[1] === undefined || - isNaN(ll[1])) { - return null; - } - const heartRate = get1(node, "HeartRateBpm"); - const time = nodeVal(get1(node, "Time")); - get1(node, "AltitudeMeters", (alt) => { - const a = parseFloat(nodeVal(alt)); - if (!isNaN(a)) { - ll.push(a); - } - }); - return { - coordinates: ll, - time: time || null, - heartRate: heartRate ? parseFloat(nodeVal(heartRate)) : null, - extensions: getProperties(node, TRACKPOINT_ATTRIBUTES), - }; - } - function getPoints(node) { - const pts = $(node, "Trackpoint"); - const line = []; - const times = []; - const heartRates = []; - if (pts.length < 2) - return null; // Invalid line in GeoJSON - const extendedProperties = {}; - const result = { extendedProperties }; - for (let i = 0; i < pts.length; i++) { - const c = coordPair(pts[i]); - if (c === null) - continue; - line.push(c.coordinates); - const { time, heartRate, extensions } = c; - if (time) - times.push(time); - if (heartRate) - heartRates.push(heartRate); - for (const [alias, value] of extensions) { - if (!extendedProperties[alias]) { - extendedProperties[alias] = Array(pts.length).fill(null); - } - extendedProperties[alias][i] = value; - } - } - if (line.length < 2) - return null; - return Object.assign(result, { - line: line, - times: times, - heartRates: heartRates, - }); - } - function getLap(node) { - const segments = $(node, "Track"); - const track = []; - const times = []; - const heartRates = []; - const allExtendedProperties = []; - let line; - const properties = Object.assign(Object.fromEntries(getProperties(node, LAP_ATTRIBUTES)), get(node, "Name", (nameElement) => { - return { name: nodeVal(nameElement) }; - })); - for (const segment of segments) { - line = getPoints(segment); - if (line) { - track.push(line.line); - if (line.times.length) - times.push(line.times); - if (line.heartRates.length) - heartRates.push(line.heartRates); - allExtendedProperties.push(line.extendedProperties); - } - } - for (let i = 0; i < allExtendedProperties.length; i++) { - const extendedProperties = allExtendedProperties[i]; - for (const property in extendedProperties) { - if (segments.length === 1) { - if (line) { - properties[property] = line.extendedProperties[property]; - } - } - else { - if (!properties[property]) { - properties[property] = track.map((track) => Array(track.length).fill(null)); - } - properties[property][i] = extendedProperties[property]; - } - } - } - if (track.length === 0) - return null; - if (times.length || heartRates.length) { - properties.coordinateProperties = Object.assign(times.length - ? { - times: track.length === 1 ? times[0] : times, - } - : {}, heartRates.length - ? { - heart: track.length === 1 ? heartRates[0] : heartRates, - } - : {}); - } - return { - type: "Feature", - properties: properties, - geometry: track.length === 1 - ? { - type: "LineString", - coordinates: track[0], - } - : { - type: "MultiLineString", - coordinates: track, - }, - }; - } - /** - * Incrementally convert a TCX document to GeoJSON. The - * first argument, `doc`, must be a TCX - * document as an XML DOM - not as a string. - */ - function* tcxGen(node) { - for (const lap of $(node, "Lap")) { - const feature = getLap(lap); - if (feature) - yield feature; - } - for (const course of $(node, "Courses")) { - const feature = getLap(course); - if (feature) - yield feature; - } - } - /** - * Convert a TCX document to GeoJSON. The first argument, `doc`, must be a TCX - * document as an XML DOM - not as a string. - */ - function tcx(node) { - return { - type: "FeatureCollection", - features: Array.from(tcxGen(node)), - }; - } - - function fixColor(v, prefix) { - const properties = {}; - const colorProp = prefix == "stroke" || prefix === "fill" ? prefix : prefix + "-color"; - if (v[0] === "#") { - v = v.substring(1); - } - if (v.length === 6 || v.length === 3) { - properties[colorProp] = "#" + v; - } - else if (v.length === 8) { - properties[prefix + "-opacity"] = parseInt(v.substring(0, 2), 16) / 255; - properties[colorProp] = - "#" + v.substring(6, 8) + v.substring(4, 6) + v.substring(2, 4); - } - return properties; - } - - function numericProperty(node, source, target) { - const properties = {}; - num1(node, source, (val) => { - properties[target] = val; - }); - return properties; - } - function getColor(node, output) { - return get(node, "color", (elem) => fixColor(nodeVal(elem), output)); - } - function extractIconHref(node) { - return get(node, "Icon", (icon, properties) => { - val1(icon, "href", (href) => { - properties.icon = href; - }); - return properties; - }); - } - function extractIcon(node) { - return get(node, "IconStyle", (iconStyle) => { - return Object.assign(getColor(iconStyle, "icon"), numericProperty(iconStyle, "scale", "icon-scale"), numericProperty(iconStyle, "heading", "icon-heading"), get(iconStyle, "hotSpot", (hotspot) => { - const left = parseFloat(hotspot.getAttribute("x") || ""); - const top = parseFloat(hotspot.getAttribute("y") || ""); - const xunits = hotspot.getAttribute("xunits") || ""; - const yunits = hotspot.getAttribute("yunits") || ""; - if (!isNaN(left) && !isNaN(top)) - return { - "icon-offset": [left, top], - "icon-offset-units": [xunits, yunits], - }; - return {}; - }), extractIconHref(iconStyle)); - }); - } - function extractLabel(node) { - return get(node, "LabelStyle", (labelStyle) => { - return Object.assign(getColor(labelStyle, "label"), numericProperty(labelStyle, "scale", "label-scale")); - }); - } - function extractLine(node) { - return get(node, "LineStyle", (lineStyle) => { - return Object.assign(getColor(lineStyle, "stroke"), numericProperty(lineStyle, "width", "stroke-width")); - }); - } - function extractPoly(node) { - return get(node, "PolyStyle", (polyStyle, properties) => { - return Object.assign(properties, get(polyStyle, "color", (elem) => fixColor(nodeVal(elem), "fill")), val1(polyStyle, "fill", (fill) => { - if (fill === "0") - return { "fill-opacity": 0 }; - }), val1(polyStyle, "outline", (outline) => { - if (outline === "0") - return { "stroke-opacity": 0 }; - })); - }); - } - function extractStyle(node) { - return Object.assign({}, extractPoly(node), extractLine(node), extractLabel(node), extractIcon(node)); - } - - const toNumber = (x) => Number(x); - const typeConverters = { - string: (x) => x, - int: toNumber, - uint: toNumber, - short: toNumber, - ushort: toNumber, - float: toNumber, - double: toNumber, - bool: (x) => Boolean(x), - }; - function extractExtendedData(node, schema) { - return get(node, "ExtendedData", (extendedData, properties) => { - for (const data of $(extendedData, "Data")) { - properties[data.getAttribute("name") || ""] = nodeVal(get1(data, "value")); - } - for (const simpleData of $(extendedData, "SimpleData")) { - const name = simpleData.getAttribute("name") || ""; - const typeConverter = schema[name] || typeConverters.string; - properties[name] = typeConverter(nodeVal(simpleData)); - } - return properties; - }); - } - function getMaybeHTMLDescription(node) { - const descriptionNode = get1(node, "description"); - for (const c of Array.from(descriptionNode?.childNodes || [])) { - if (c.nodeType === 4) { - return { - description: { - "@type": "html", - value: nodeVal(c), - }, - }; - } - } - return {}; - } - function extractTimeSpan(node) { - return get(node, "TimeSpan", (timeSpan) => { - return { - timespan: { - begin: nodeVal(get1(timeSpan, "begin")), - end: nodeVal(get1(timeSpan, "end")), - }, - }; - }); - } - function extractTimeStamp(node) { - return get(node, "TimeStamp", (timeStamp) => { - return { timestamp: nodeVal(get1(timeStamp, "when")) }; - }); - } - function extractCascadedStyle(node, styleMap) { - return val1(node, "styleUrl", (styleUrl) => { - styleUrl = normalizeId(styleUrl); - if (styleMap[styleUrl]) { - return Object.assign({ styleUrl }, styleMap[styleUrl]); - } - // For backward-compatibility. Should we still include - // styleUrl even if it's not resolved? - return { styleUrl }; - }); - } - - const removeSpace = /\s*/g; - const trimSpace = /^\s*|\s*$/g; - const splitSpace = /\s+/; - /** - * Get one coordinate from a coordinate array, if any - */ - function coord1(value) { - return value - .replace(removeSpace, "") - .split(",") - .map(parseFloat) - .filter((num) => !isNaN(num)) - .slice(0, 3); - } - /** - * Get all coordinates from a coordinate array as [[],[]] - */ - function coord(value) { - return value - .replace(trimSpace, "") - .split(splitSpace) - .map(coord1) - .filter((coord) => { - return coord.length >= 2; - }); - } - function gxCoords(node) { - let elems = $(node, "coord"); - if (elems.length === 0) { - elems = $ns(node, "coord", "*"); - } - const coordinates = elems.map((elem) => { - return nodeVal(elem).split(" ").map(parseFloat); - }); - if (coordinates.length === 0) { - return null; - } - return { - geometry: coordinates.length > 2 - ? { - type: "LineString", - coordinates, - } - : { - type: "Point", - coordinates: coordinates[0], - }, - times: $(node, "when").map((elem) => nodeVal(elem)), - }; - } - function fixRing(ring) { - if (ring.length === 0) - return ring; - const first = ring[0]; - const last = ring[ring.length - 1]; - let equal = true; - for (let i = 0; i < Math.max(first.length, last.length); i++) { - if (first[i] !== last[i]) { - equal = false; - break; - } - } - if (!equal) { - return ring.concat([ring[0]]); - } - return ring; - } - function getCoordinates(node) { - return nodeVal(get1(node, "coordinates")); - } - function getGeometry(node) { - let geometries = []; - let coordTimes = []; - for (let i = 0; i < node.childNodes.length; i++) { - const child = node.childNodes.item(i); - if (isElement(child)) { - switch (child.tagName) { - case "MultiGeometry": - case "MultiTrack": - case "gx:MultiTrack": { - const childGeometries = getGeometry(child); - geometries = geometries.concat(childGeometries.geometries); - coordTimes = coordTimes.concat(childGeometries.coordTimes); - break; - } - case "Point": { - const coordinates = coord1(getCoordinates(child)); - if (coordinates.length >= 2) { - geometries.push({ - type: "Point", - coordinates, - }); - } - break; - } - case "LinearRing": - case "LineString": { - const coordinates = coord(getCoordinates(child)); - if (coordinates.length >= 2) { - geometries.push({ - type: "LineString", - coordinates, - }); - } - break; - } - case "Polygon": { - const coords = []; - for (const linearRing of $(child, "LinearRing")) { - const ring = fixRing(coord(getCoordinates(linearRing))); - if (ring.length >= 4) { - coords.push(ring); - } - } - if (coords.length) { - geometries.push({ - type: "Polygon", - coordinates: coords, - }); - } - break; - } - case "Track": - case "gx:Track": { - const gx = gxCoords(child); - if (!gx) - break; - const { times, geometry } = gx; - geometries.push(geometry); - if (times.length) - coordTimes.push(times); - break; - } - } - } - } - return { - geometries, - coordTimes, - }; - } - - function geometryListToGeometry(geometries) { - return geometries.length === 0 - ? null - : geometries.length === 1 - ? geometries[0] - : { - type: "GeometryCollection", - geometries, - }; - } - function getPlacemark(node, styleMap, schema, options) { - const { coordTimes, geometries } = getGeometry(node); - const geometry = geometryListToGeometry(geometries); - if (!geometry && options.skipNullGeometry) { - return null; - } - const feature = { - type: "Feature", - geometry, - properties: Object.assign(getMulti(node, [ - "name", - "address", - "visibility", - "open", - "phoneNumber", - "description", - ]), getMaybeHTMLDescription(node), extractCascadedStyle(node, styleMap), extractStyle(node), extractExtendedData(node, schema), extractTimeSpan(node), extractTimeStamp(node), coordTimes.length - ? { - coordinateProperties: { - times: coordTimes.length === 1 ? coordTimes[0] : coordTimes, - }, - } - : {}), - }; - if (feature.properties?.visibility !== undefined) { - feature.properties.visibility = feature.properties.visibility !== "0"; - } - const id = node.getAttribute("id"); - if (id !== null && id !== "") - feature.id = id; - return feature; - } - - function getGroundOverlayBox(node) { - const latLonQuad = get1(node, "gx:LatLonQuad"); - if (latLonQuad) { - const ring = fixRing(coord(getCoordinates(node))); - return { - geometry: { - type: "Polygon", - coordinates: [ring], - }, - }; - } - return getLatLonBox(node); - } - const DEGREES_TO_RADIANS = Math.PI / 180; - function rotateBox(bbox, coordinates, rotation) { - const center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]; - return [ - coordinates[0].map((coordinate) => { - const dy = coordinate[1] - center[1]; - const dx = coordinate[0] - center[0]; - const distance = Math.sqrt(Math.pow(dy, 2) + Math.pow(dx, 2)); - const angle = Math.atan2(dy, dx) + rotation * DEGREES_TO_RADIANS; - return [ - center[0] + Math.cos(angle) * distance, - center[1] + Math.sin(angle) * distance, - ]; - }), - ]; - } - function getLatLonBox(node) { - const latLonBox = get1(node, "LatLonBox"); - if (latLonBox) { - const north = num1(latLonBox, "north"); - const west = num1(latLonBox, "west"); - const east = num1(latLonBox, "east"); - const south = num1(latLonBox, "south"); - const rotation = num1(latLonBox, "rotation"); - if (typeof north === "number" && - typeof south === "number" && - typeof west === "number" && - typeof east === "number") { - const bbox = [west, south, east, north]; - let coordinates = [ - [ - [west, north], - [east, north], - [east, south], - [west, south], - [west, north], // top left (again) - ], - ]; - if (typeof rotation === "number") { - coordinates = rotateBox(bbox, coordinates, rotation); - } - return { - bbox, - geometry: { - type: "Polygon", - coordinates, - }, - }; - } - } - return null; - } - function getGroundOverlay(node, styleMap, schema, options) { - const box = getGroundOverlayBox(node); - const geometry = box?.geometry || null; - if (!geometry && options.skipNullGeometry) { - return null; - } - const feature = { - type: "Feature", - geometry, - properties: Object.assign( - /** - * Related to - * https://gist.github.com/tmcw/037a1cb6660d74a392e9da7446540f46 - */ - { "@geometry-type": "groundoverlay" }, getMulti(node, [ - "name", - "address", - "visibility", - "open", - "phoneNumber", - "description", - ]), getMaybeHTMLDescription(node), extractCascadedStyle(node, styleMap), extractStyle(node), extractIconHref(node), extractExtendedData(node, schema), extractTimeSpan(node), extractTimeStamp(node)), - }; - if (box?.bbox) { - feature.bbox = box.bbox; - } - if (feature.properties?.visibility !== undefined) { - feature.properties.visibility = feature.properties.visibility !== "0"; - } - const id = node.getAttribute("id"); - if (id !== null && id !== "") - feature.id = id; - return feature; - } - - function getStyleId(style) { - let id = style.getAttribute("id"); - const parentNode = style.parentNode; - if (!id && - isElement(parentNode) && - parentNode.localName === "CascadingStyle") { - id = parentNode.getAttribute("kml:id") || parentNode.getAttribute("id"); - } - return normalizeId(id || ""); - } - function buildStyleMap(node) { - const styleMap = {}; - for (const style of $(node, "Style")) { - styleMap[getStyleId(style)] = extractStyle(style); - } - for (const map of $(node, "StyleMap")) { - const id = normalizeId(map.getAttribute("id") || ""); - val1(map, "styleUrl", (styleUrl) => { - styleUrl = normalizeId(styleUrl); - if (styleMap[styleUrl]) { - styleMap[id] = styleMap[styleUrl]; - } - }); - } - return styleMap; - } - function buildSchema(node) { - const schema = {}; - for (const field of $(node, "SimpleField")) { - schema[field.getAttribute("name") || ""] = - typeConverters[field.getAttribute("type") || ""] || - typeConverters["string"]; - } - return schema; - } - const FOLDER_PROPS = [ - "name", - "visibility", - "open", - "address", - "description", - "phoneNumber", - "visibility", - ]; - function getFolder(node) { - const meta = {}; - for (const child of Array.from(node.childNodes)) { - if (isElement(child) && FOLDER_PROPS.includes(child.tagName)) { - meta[child.tagName] = nodeVal(child); - } - } - return { - type: "folder", - meta, - children: [], - }; - } - /** - * Yield a nested tree with KML folder structure - * - * This generates a tree with the given structure: - * - * ```js - * { - * "type": "root", - * "children": [ - * { - * "type": "folder", - * "meta": { - * "name": "Test" - * }, - * "children": [ - * // ...features and folders - * ] - * } - * // ...features - * ] - * } - * ``` - * - * ### GroundOverlay - * - * GroundOverlay elements are converted into - * `Feature` objects with `Polygon` geometries, - * a property like: - * - * ```json - * { - * "@geometry-type": "groundoverlay" - * } - * ``` - * - * And the ground overlay's image URL in the `href` - * property. Ground overlays will need to be displayed - * with a separate method to other features, depending - * on which map framework you're using. - */ - function kmlWithFolders(node, options = { - skipNullGeometry: false, - }) { - const styleMap = buildStyleMap(node); - const schema = buildSchema(node); - const tree = { type: "root", children: [] }; - function traverse(node, pointer, options) { - if (isElement(node)) { - switch (node.tagName) { - case "GroundOverlay": { - const placemark = getGroundOverlay(node, styleMap, schema, options); - if (placemark) { - pointer.children.push(placemark); - } - break; - } - case "Placemark": { - const placemark = getPlacemark(node, styleMap, schema, options); - if (placemark) { - pointer.children.push(placemark); - } - break; - } - case "Folder": { - const folder = getFolder(node); - pointer.children.push(folder); - pointer = folder; - break; - } - } - } - if (node.childNodes) { - for (let i = 0; i < node.childNodes.length; i++) { - traverse(node.childNodes[i], pointer, options); - } - } - } - traverse(node, tree, options); - return tree; - } - /** - * Convert KML to GeoJSON incrementally, returning - * a [Generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators) - * that yields output feature by feature. - */ - function* kmlGen(node, options = { - skipNullGeometry: false, - }) { - const styleMap = buildStyleMap(node); - const schema = buildSchema(node); - for (const placemark of $(node, "Placemark")) { - const feature = getPlacemark(placemark, styleMap, schema, options); - if (feature) - yield feature; - } - for (const groundOverlay of $(node, "GroundOverlay")) { - const feature = getGroundOverlay(groundOverlay, styleMap, schema, options); - if (feature) - yield feature; - } - } - /** - * Convert a KML document to GeoJSON. The first argument, `doc`, must be a KML - * document as an XML DOM - not as a string. You can get this using jQuery's default - * `.ajax` function or using a bare XMLHttpRequest with the `.response` property - * holding an XML DOM. - * - * The output is a JavaScript object of GeoJSON data. You can convert it to a string - * with [JSON.stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) - * or use it directly in libraries. - */ - function kml(node, options = { - skipNullGeometry: false, - }) { - return { - type: "FeatureCollection", - features: Array.from(kmlGen(node, options)), - }; - } - - var toGeoJson = /*#__PURE__*/Object.freeze({ - __proto__: null, - gpx: gpx, - gpxGen: gpxGen, - kml: kml, - kmlGen: kmlGen, - kmlWithFolders: kmlWithFolders, - tcx: tcx, - tcxGen: tcxGen - }); - - var polyline = {exports: {}}; - - (function (module) { - - /** - * Based off of [the offical Google document](https://developers.google.com/maps/documentation/utilities/polylinealgorithm) - * - * Some parts from [this implementation](http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/PolylineEncoder.js) - * by [Mark McClure](http://facstaff.unca.edu/mcmcclur/) - * - * @module polyline - */ - - var polyline = {}; - - function py2_round(value) { - // Google's polyline algorithm uses the same rounding strategy as Python 2, which is different from JS for negative values - return Math.floor(Math.abs(value) + 0.5) * (value >= 0 ? 1 : -1); - } - - function encode(current, previous, factor) { - current = py2_round(current * factor); - previous = py2_round(previous * factor); - var coordinate = (current - previous) * 2; - if (coordinate < 0) { - coordinate = -coordinate - 1; - } - var output = ''; - while (coordinate >= 0x20) { - output += String.fromCharCode((0x20 | (coordinate & 0x1f)) + 63); - coordinate /= 32; - } - output += String.fromCharCode((coordinate | 0) + 63); - return output; - } - - /** - * Decodes to a [latitude, longitude] coordinates array. - * - * This is adapted from the implementation in Project-OSRM. - * - * @param {String} str - * @param {Number} precision - * @returns {Array} - * - * @see https://github.com/Project-OSRM/osrm-frontend/blob/master/WebContent/routing/OSRM.RoutingGeometry.js - */ - polyline.decode = function(str, precision) { - var index = 0, - lat = 0, - lng = 0, - coordinates = [], - shift = 0, - result = 0, - byte = null, - latitude_change, - longitude_change, - factor = Math.pow(10, Number.isInteger(precision) ? precision : 5); - - // Coordinates have variable length when encoded, so just keep - // track of whether we've hit the end of the string. In each - // loop iteration, a single coordinate is decoded. - while (index < str.length) { - - // Reset shift, result, and byte - byte = null; - shift = 1; - result = 0; - - do { - byte = str.charCodeAt(index++) - 63; - result += (byte & 0x1f) * shift; - shift *= 32; - } while (byte >= 0x20); - - latitude_change = (result & 1) ? ((-result - 1) / 2) : (result / 2); - - shift = 1; - result = 0; - - do { - byte = str.charCodeAt(index++) - 63; - result += (byte & 0x1f) * shift; - shift *= 32; - } while (byte >= 0x20); - - longitude_change = (result & 1) ? ((-result - 1) / 2) : (result / 2); - - lat += latitude_change; - lng += longitude_change; - - coordinates.push([lat / factor, lng / factor]); - } - - return coordinates; - }; - - /** - * Encodes the given [latitude, longitude] coordinates array. - * - * @param {Array.>} coordinates - * @param {Number} precision - * @returns {String} - */ - polyline.encode = function(coordinates, precision) { - if (!coordinates.length) { return ''; } - - var factor = Math.pow(10, Number.isInteger(precision) ? precision : 5), - output = encode(coordinates[0][0], 0, factor) + encode(coordinates[0][1], 0, factor); - - for (var i = 1; i < coordinates.length; i++) { - var a = coordinates[i], b = coordinates[i - 1]; - output += encode(a[0], b[0], factor); - output += encode(a[1], b[1], factor); - } - - return output; - }; - - function flipped(coords) { - var flipped = []; - for (var i = 0; i < coords.length; i++) { - var coord = coords[i].slice(); - flipped.push([coord[1], coord[0]]); - } - return flipped; - } - - /** - * Encodes a GeoJSON LineString feature/geometry. - * - * @param {Object} geojson - * @param {Number} precision - * @returns {String} - */ - polyline.fromGeoJSON = function(geojson, precision) { - if (geojson && geojson.type === 'Feature') { - geojson = geojson.geometry; - } - if (!geojson || geojson.type !== 'LineString') { - throw new Error('Input must be a GeoJSON LineString'); - } - return polyline.encode(flipped(geojson.coordinates), precision); - }; - - /** - * Decodes to a GeoJSON LineString geometry. - * - * @param {String} str - * @param {Number} precision - * @returns {Object} - */ - polyline.toGeoJSON = function(str, precision) { - var coords = polyline.decode(str, precision); - return { - type: 'LineString', - coordinates: flipped(coords) - }; - }; - - if (module.exports) { - module.exports = polyline; - } - } (polyline)); - - var polylineExports = polyline.exports; - - var utils = (() => { - - const purgeProps = (obj, blacklist) => { - if (obj) { - let rs = Object.assign({}, obj); - if (blacklist) { - for (let prop of blacklist) { - delete rs[prop]; - } - } - return rs; - } - return {}; - }; - - const mergeProps = (obj1, obj2) => { - obj1 = obj1 ? obj1 : {}; - obj2 = obj2 ? obj2 : {}; - return Object.assign(obj1, obj2); - }; - - const first = a => a[0]; - const last = a => a[a.length - 1]; - const coordsToKey = a => a.join(','); - - const addToMap = (m, k, v) => { - let a = m[k]; - if (a) { - a.push(v); - } else { - m[k] = [v]; - } - }; - - const removeFromMap = (m, k, v) => { - let a = m[k]; - let idx = null; - if (a && (idx = a.indexOf(v)) >= 0) { - a.splice(idx, 1); - } - }; - - const getFirstFromMap = (m, k) => { - let a = m[k]; - if (a && a.length > 0) { - return a[0]; - } - return null; - }; - - // need 3+ different points to form a ring, here using > 3 is 'coz a the first and the last points are actually the same - const isRing = a => a.length > 3 && coordsToKey(first(a)) === coordsToKey(last(a)); - - const ringDirection = (a, xIdx, yIdx) => { - xIdx = xIdx || 0, yIdx = yIdx || 1; - // get the index of the point which has the maximum x value - let m = a.reduce((maxxIdx, v, idx) => a[maxxIdx][xIdx] > v[xIdx] ? maxxIdx : idx, 0); - // 'coz the first point is virtually the same one as the last point, - // we need to skip a.length - 1 for left when m = 0, - // and skip 0 for right when m = a.length - 1; - let l = m <= 0 ? a.length - 2 : m - 1, r = m >= a.length - 1 ? 1 : m + 1; - let xa = a[l][xIdx], xb = a[m][xIdx], xc = a[r][xIdx]; - let ya = a[l][yIdx], yb = a[m][yIdx], yc = a[r][yIdx]; - let det = (xb - xa) * (yc - ya) - (xc - xa) * (yb - ya); - return det < 0 ? 'clockwise' : 'counterclockwise'; - }; - - const ptInsidePolygon = (pt, polygon, xIdx, yIdx) => { - xIdx = xIdx || 0, yIdx = yIdx || 1; - let result = false; - for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { - if ((polygon[i][xIdx] <= pt[xIdx] && pt[xIdx] < polygon[j][xIdx] || - polygon[j][xIdx] <= pt[xIdx] && pt[xIdx] < polygon[i][xIdx]) && - pt[yIdx] < (polygon[j][yIdx] - polygon[i][yIdx]) * (pt[xIdx] - polygon[i][xIdx]) / (polygon[j][xIdx] - polygon[i][xIdx]) + polygon[i][yIdx]) { - result = !result; - } - - } - return result; - }; - - const strToFloat = el => el instanceof Array ? el.map(strToFloat) : parseFloat(el); - - class RefElements extends Map { - constructor() { - super(); - this.binders = []; - } - - add(k, v) { - if (!this.has(k)) { - this.set(k, v); - } - // suppress duplcated key error - // else - // throw `Error: adding duplicated key '${k}' to RefElements`; - } - - addBinder(binder) { - this.binders.push(binder); - } - - bindAll() { - this.binders.forEach(binder => binder.bind()); - } - } - - class LateBinder { - constructor(container, valueFunc, ctx, args) { - this.container = container; - this.valueFunc = valueFunc; - this.ctx = ctx; - this.args = args; - } - - bind() { - let v = this.valueFunc.apply(this.ctx, this.args); - if (this.container instanceof Array) { - let idx = this.container.indexOf(this); - if (idx >= 0) { - let args = [idx, 1]; - if (v) { - args.push(v); - } - [].splice.apply(this.container, args); - } - } else if (typeof this.container === 'object') { - let k = Object.keys(this.container).find(v => this.container[v] === this); - if (k) { - if (v) { - this.container[k] = v; - } else { - delete this.container[k]; - } - } - } - } - } - - class WayCollection extends Array { - constructor() { - super(); - this.firstMap = {}; - this.lastMap = {}; - } - - addWay(way) { - way = way.toCoordsArray(); - if (way.length > 0) { - this.push(way); - addToMap(this.firstMap, coordsToKey(first(way)), way); - addToMap(this.lastMap, coordsToKey(last(way)), way); - } - } - - toStrings() { - let strings = [], way = null; - while (way = this.shift()) { - removeFromMap(this.firstMap, coordsToKey(first(way)), way); - removeFromMap(this.lastMap, coordsToKey(last(way)), way); - let current = way, next = null; - do { - let key = coordsToKey(last(current)), shouldReverse = false; - - next = getFirstFromMap(this.firstMap, key); - if (!next) { - next = getFirstFromMap(this.lastMap, key); - shouldReverse = true; - } - - if (next) { - this.splice(this.indexOf(next), 1); - removeFromMap(this.firstMap, coordsToKey(first(next)), next); - removeFromMap(this.lastMap, coordsToKey(last(next)), next); - if (shouldReverse) { - // always reverse shorter one to save time - if (next.length > current.length) { - [current, next] = [next, current]; - } - next.reverse(); - } - - current = current.concat(next.slice(1)); - } - } while (next); - strings.push(strToFloat(current)); - } - - return strings; - } - - toRings(direction) { - let strings = this.toStrings(); - let rings = [], string = null; - while (string = strings.shift()) { - if (isRing(string)) { - if (ringDirection(string) !== direction) { - string.reverse(); - } - rings.push(string); - } - } - return rings; - } - } - - return { - purgeProps, mergeProps, - first, last, coordsToKey, - addToMap, removeFromMap, getFirstFromMap, - isRing, ringDirection, ptInsidePolygon, strToFloat, - RefElements, LateBinder, WayCollection - }; - })(); - - var building = { - }; - var highway = { - whitelist: [ - "services", - "rest_area", - "escape", - "elevator" - ] - }; - var natural = { - blacklist: [ - "coastline", - "cliff", - "ridge", - "arete", - "tree_row" - ] - }; - var landuse = { - }; - var waterway = { - whitelist: [ - "riverbank", - "dock", - "boatyard", - "dam" - ] - }; - var amenity = { - }; - var leisure = { - }; - var barrier = { - whitelist: [ - "city_wall", - "ditch", - "hedge", - "retaining_wall", - "wall", - "spikes" - ] - }; - var railway = { - whitelist: [ - "station", - "turntable", - "roundhouse", - "platform" - ] - }; - var area = { - }; - var boundary = { - }; - var man_made = { - blacklist: [ - "cutline", - "embankment", - "pipeline" - ] - }; - var power = { - whitelist: [ - "plant", - "substation", - "generator", - "transformer" - ] - }; - var place = { - }; - var shop = { - }; - var aeroway = { - blacklist: [ - "taxiway" - ] - }; - var tourism = { - }; - var historic = { - }; - var public_transport = { - }; - var office = { - }; - var military = { - }; - var ruins = { - }; - var craft = { - }; - var golf = { - }; - var indoor = { - }; - var require$$1 = { - building: building, - highway: highway, - natural: natural, - landuse: landuse, - waterway: waterway, - amenity: amenity, - leisure: leisure, - barrier: barrier, - railway: railway, - area: area, - boundary: boundary, - man_made: man_made, - power: power, - place: place, - shop: shop, - aeroway: aeroway, - tourism: tourism, - historic: historic, - public_transport: public_transport, - office: office, - "building:part": { - }, - military: military, - ruins: ruins, - "area:highway": { - }, - craft: craft, - golf: golf, - indoor: indoor - }; - - var osmobjs = (() => { - - const { first, last, coordsToKey, - addToMap, removeFromMap, getFirstFromMap, - isRing, ringDirection, ptInsidePolygon, strToFloat, - LateBinder, WayCollection } = utils, - polygonTags = require$$1; - - class OsmObject { - constructor(type, id, refElems) { - this.type = type; - this.id = id; - this.refElems = refElems; - this.tags = {}; - this.props = { id: this.getCompositeId() }; - this.refCount = 0; - this.hasTag = false; - if (refElems) { - refElems.add(this.getCompositeId(), this); - } - } - - addTags(tags) { - this.tags = Object.assign(this.tags, tags); - this.hasTag = tags ? true : false; - } - - addTag(k, v) { - this.tags[k] = v; - this.hasTag = k ? true : false; - } - - addProp(k, v) { - this.props[k] = v; - } - - addProps(props) { - this.props = Object.assign(this.props, props); - } - - getCompositeId() { - return `${this.type}/${this.id}`; - } - - getProps() { - return Object.assign(this.props, this.tags); - } - - toFeatureArray() { - return []; - } - } - - class Node extends OsmObject { - constructor(id, refElems) { - super('node', id, refElems); - this.latLng = null; - } - - setLatLng(latLng) { - this.latLng = latLng; - } - - toFeatureArray() { - if (this.latLng) { - return [{ - type: 'Feature', - id: this.getCompositeId(), - properties: this.getProps(), - geometry: { - type: 'Point', - coordinates: strToFloat([this.latLng.lon, this.latLng.lat]) - } - }]; - } - - return []; - } - - getLatLng() { - return this.latLng; - } - } - - class Way extends OsmObject { - constructor(id, refElems) { - super('way', id, refElems); - this.latLngArray = []; - this.isPolygon = false; - } - - addLatLng(latLng) { - this.latLngArray.push(latLng); - } - - setLatLngArray(latLngArray) { - this.latLngArray = latLngArray; - } - - addNodeRef(ref) { - let binder = new LateBinder(this.latLngArray, function (id) { - let node = this.refElems.get(`node/${id}`); - if (node) { - node.refCount++; - return node.getLatLng(); - } - }, this, [ref]); - - this.latLngArray.push(binder); - this.refElems.addBinder(binder); - } - - analyzeGeometryType(k, v) { - let o = polygonTags[k]; - if (o) { - this.isPolygon = true; - if (o.whitelist) { - this.isPolygon = o.whitelist.indexOf(v) >= 0 ? true : false; - } else if (o.blacklist) { - this.isPolygon = o.blacklist.indexOf(v) >= 0 ? false : true; - } - } - } - - addTags(tags) { - super.addTags(tags); - for (let [k, v] of Object.entries(tags)) { - this.analyzeGeometryType(k, v); - } - } - - addTag(k, v) { - super.addTag(k, v); - this.analyzeGeometryType(k, v); - } - - toCoordsArray() { - return this.latLngArray.map(latLng => [latLng.lon, latLng.lat]); - } - - toFeatureArray() { - let coordsArray = this.toCoordsArray(); - if (coordsArray.length > 1) { - coordsArray = strToFloat(coordsArray); - let feature = { - type: 'Feature', - id: this.getCompositeId(), - properties: this.getProps(), - geometry: { - type: 'LineString', - coordinates: coordsArray - } - }; - - if (this.isPolygon && isRing(coordsArray)) { - if (ringDirection(coordsArray) !== 'counterclockwise') { - coordsArray.reverse(); - } - - feature.geometry = { - type: 'Polygon', - coordinates: [coordsArray] - }; - - return [feature]; - } - - return [feature]; - } - - return []; - } - } - - class Relation extends OsmObject { - constructor(id, refElems) { - super('relation', id, refElems); - this.relations = []; - this.nodes = []; - this.bounds = null; - } - - setBounds(bounds) { - this.bounds = bounds; - } - - addMember(member) { - switch (member.type) { - // super relation, need to do combination - case 'relation': - let binder = new LateBinder(this.relations, function (id) { - let relation = this.refElems.get(`relation/${id}`); - if (relation) { - relation.refCount++; - return relation; - } - }, this, [member.ref]); - this.relations.push(binder); - this.refElems.addBinder(binder); - break; - - case 'way': - if (!member.role) { - member.role = ''; - } - let ways = this[member.role]; - if (!ways) { - ways = this[member.role] = []; - } - if (member.geometry) { - let way = new Way(member.ref, this.refElems); - way.setLatLngArray(member.geometry); - way.refCount++; - ways.push(way); - } else if (member.nodes) { - let way = new Way(member.ref, this.refElems); - for (let nid of member.nodes) { - way.addNodeRef(nid); - } - way.refCount++; - ways.push(way); - } else { - let binder = new LateBinder(ways, function (id) { - let way = this.refElems.get(`way/${id}`); - if (way) { - way.refCount++; - return way; - } - }, this, [member.ref]); - ways.push(binder); - this.refElems.addBinder(binder); - } - break; - - case 'node': - let node = null; - if (member.lat && member.lon) { - node = new Node(member.ref, this.refElems); - node.setLatLng({ lon: member.lon, lat: member.lat }); - if (member.tags) { - node.addTags(member.tags); - } - for (let [k, v] of Object.entries(member)) { - if (['id', 'type', 'lat', 'lon'].indexOf(k) < 0) { - node.addProp(k, v); - } - } - - node.refCount++; - this.nodes.push(node); - } else { - let binder = new LateBinder(this.nodes, function (id) { - let node = this.refElems.get(`node/${id}`); - if (node) { - node.refCount++; - return node; - } - }, this, [member.ref]); - this.nodes.push(binder); - this.refElems.addBinder(binder); - } - break; - } - } - - toFeatureArray() { - const constructStringGeometry = (ws) => { - let strings = ws ? ws.toStrings() : []; - if (strings.length > 0) { - if (strings.length === 1) return { - type: 'LineString', - coordinates: strings[0] - } - - return { - type: 'MultiLineString', - coordinates: strings - } - } - return null; - }; - - const constructPolygonGeometry = (ows, iws) => { - let outerRings = ows ? ows.toRings('counterclockwise') : [], - innerRings = iws ? iws.toRings('clockwise') : []; - - if (outerRings.length > 0) { - let compositPolyons = []; - - let ring = null; - for (ring of outerRings) - compositPolyons.push([ring]); - - // link inner polygons to outer containers - while (ring = innerRings.shift()) { - for (let idx in outerRings) { - if (ptInsidePolygon(first(ring), outerRings[idx])) { - compositPolyons[idx].push(ring); - break; - } - } - } - - // construct the Polygon/MultiPolygon geometry - if (compositPolyons.length === 1) { - return { - type: 'Polygon', - coordinates: compositPolyons[0] - }; - } - - return { - type: 'MultiPolygon', - coordinates: compositPolyons - } - } - - return null; - }; - - let polygonFeatures = [], stringFeatures = [], pointFeatures = []; - const waysFieldNames = ['outer', 'inner', '']; - // need to do combination when there're nested relations - for (let relation of this.relations) { - if (relation) { - for (let fieldName of waysFieldNames) { - let ways = relation[fieldName]; - if (ways) { - let thisWays = this[fieldName]; - if (thisWays) { - [].splice.apply(thisWays, [thisWays.length, 0].concat(ways)); - } else { - this[fieldName] = ways; - } - } - } - } - } - - for (let fieldName of waysFieldNames) { - let ways = this[fieldName]; - if (ways) { - this[fieldName] = new WayCollection(); - for (let way of ways) { - this[fieldName].addWay(way); - } - } - } - - let geometry = null; - - let feature = { - type: 'Feature', - id: this.getCompositeId(), - bbox: this.bounds, - properties: this.getProps() - }; - - if (!this.bounds) { - delete feature.bbox; - } - - if (this.outer) { - geometry = constructPolygonGeometry(this.outer, this.inner); - if (geometry) { - feature.geometry = geometry; - polygonFeatures.push(feature); - } - } - else if (this['']) { - geometry = constructStringGeometry(this['']); - if (geometry) { - feature.geometry = geometry; - stringFeatures.push(feature); - } - } - - for (let node of this.nodes) { - pointFeatures = pointFeatures.concat(node.toFeatureArray()); - } - - return polygonFeatures.concat(stringFeatures).concat(pointFeatures); - } - } - - return { Node, Way, Relation }; - })(); - - var xmlparser = (() => { - - function conditioned(evt) { - return evt.match(/^(.+?)\[(.+?)\]>$/g) != null; - } - - function parseEvent(evt) { - let match = /^(.+?)\[(.+?)\]>$/g.exec(evt); - if (match) { - return { evt: match[1] + '>', exp: match[2] }; - } - return { evt: evt }; - } - - function genConditionFunc(cond) { - let body = 'return ' + cond.replace(/(\$.+?)(?=[=!.])/g, 'node.$&') + ';'; - return new Function('node', body); - } - - return class { - constructor(opts) { - if (opts) { - this.queryParent = opts.queryParent ? true : false; - this.progressive = opts.progressive; - if (this.queryParent) { - this.parentMap = new WeakMap(); - } - } - this.evtListeners = {}; - } - - parse(xml, parent, dir) { - dir = dir ? dir + '.' : ''; - let nodeRegEx = /<([^ >\/]+)(.*?)>/mg, nodeMatch = null, nodes = []; - while (nodeMatch = nodeRegEx.exec(xml)) { - let tag = nodeMatch[1], node = { $tag: tag }, fullTag = dir + tag; - - let attrText = nodeMatch[2].trim(), closed = false; - if (attrText.endsWith('/') || tag.startsWith('?') || tag.startsWith('!')) { - closed = true; - } - - let attRegEx1 = /([^ ]+?)="(.+?)"/g, attRegEx2 = /([^ ]+?)='(.+?)'/g; - let attMatch = null, hasAttrs = false; - while (attMatch = attRegEx1.exec(attrText)) { - hasAttrs = true; - node[attMatch[1]] = attMatch[2]; - } - if (!hasAttrs) - while (attMatch = attRegEx2.exec(attrText)) { - hasAttrs = true; - node[attMatch[1]] = attMatch[2]; - } - - if (!hasAttrs && attrText !== '') { - node.text = attrText; - } - if (this.progressive) { - this.emit(`<${fullTag}>`, node, parent); - } - - if (!closed) { - let innerRegEx = new RegExp(`([^]+?)<\/${tag}>`, 'g'); - innerRegEx.lastIndex = nodeRegEx.lastIndex; - let innerMatch = innerRegEx.exec(xml); - if (innerMatch && innerMatch[1]) { - nodeRegEx.lastIndex = innerRegEx.lastIndex; - let innerNodes = this.parse(innerMatch[1], node, fullTag); - if (innerNodes.length > 0) { - node.$innerNodes = innerNodes; - } else { - node.$innerText = innerMatch[1]; - } - } - } - if (this.queryParent && parent) { - this.parentMap.set(node, parent); - } - - if (this.progressive) { - this.emit(``, node, parent); - } - - nodes.push(node); - } - - return nodes; - } - - getParent(node) { - if (this.queryParent) { - return this.parentMap.get(node); - } - return null; - } - - #addListener(evt, func) { - let funcs = this.evtListeners[evt]; - if (funcs) { - funcs.push(func); - } else { - this.evtListeners[evt] = [func]; - } - } - - // support javascript condition for the last tag - addListener(evt, func) { - if (conditioned(evt)) { - // func.prototype = evt; - evt = parseEvent(evt); - func.condition = genConditionFunc(evt.exp); - evt = evt.evt; - } - this.#addListener(evt, func); - } - - #removeListener(evt, func) { - let funcs = this.evtListeners[evt]; - let idx = null; - if (funcs && (idx = funcs.indexOf(func)) >= 0) { - funcs.splice(idx, 1); - } - } - - removeListener(evt, func) { - if (conditioned(evt)) { - evt = parseEvent(evt); - evt = evt.evt; - } - this.#removeListener(evt, func); - } - - emit(evt, ...args) { - let funcs = this.evtListeners[evt]; - if (funcs) { - for (let func of funcs) { - if (func.condition) { - if (func.condition.apply(null, args) === true) { - func.apply(null, args); - } - } else { - func.apply(null, args); - } - } - } - } - - on(evt, func) { - this.addListener(evt, func); - } - - off(evt, func) { - this.removeListener(evt, func); - } - }; - })(); - - const { Node, Way, Relation } = osmobjs, - { purgeProps, RefElements } = utils, - XmlParser = xmlparser; - - var lib = (osm, opts) => { - let completeFeature = false, renderTagged = false, excludeWay = true; - - const parseOpts = opts => { - if (opts) { - completeFeature = opts.completeFeature || opts.allFeatures ? true : false; - renderTagged = opts.renderTagged ? true : false; - let wayOpt = opts.suppressWay || opts.excludeWay; - if (wayOpt !== undefined && !wayOpt) { - excludeWay = false; - } - } - }; - - parseOpts(opts); - - const detectFormat = osm => { - if (osm.elements) { - return 'json'; - } - if (osm.indexOf('= 0) { - return 'xml'; - } - if (osm.trim().startsWith('{')) { - return 'json-raw'; - } - return 'invalid'; - }; - - let format = detectFormat(osm); - - let refElements = new RefElements(), featureArray = []; - - const analyzeFeaturesFromJson = osm => { - for (let elem of osm.elements) { - switch (elem.type) { - case 'node': - let node = new Node(elem.id, refElements); - if (elem.tags) { - node.addTags(elem.tags); - } - node.addProps(purgeProps(elem, ['id', 'type', 'tags', 'lat', 'lon'])); - node.setLatLng(elem); - break; - - case 'way': - let way = new Way(elem.id, refElements); - if (elem.tags) { - way.addTags(elem.tags); - } - way.addProps(purgeProps(elem, ['id', 'type', 'tags', 'nodes', 'geometry'])); - if (elem.nodes) { - for (let n of elem.nodes) { - way.addNodeRef(n); - } - } else if (elem.geometry) { - way.setLatLngArray(elem.geometry); - } - break; - - case 'relation': - let relation = new Relation(elem.id, refElements); - if (elem.bounds) { - relation.setBounds([parseFloat(elem.bounds.minlon), parseFloat(elem.bounds.minlat), parseFloat(elem.bounds.maxlon), parseFloat(elem.bounds.maxlat)]); - } - if (elem.tags) { - relation.addTags(elem.tags); - } - relation.addProps(purgeProps(elem, ['id', 'type', 'tags', 'bounds', 'members'])); - if (elem.members) { - for (let member of elem.members) { - relation.addMember(member); - } - } - break; - } - } - }; - - const analyzeFeaturesFromXml = osm => { - const xmlParser = new XmlParser({ progressive: true }); - - xmlParser.on('', node => { - let nd = new Node(node.id, refElements); - for (let [k, v] of Object.entries(node)) - if (!k.startsWith('$') && ['id', 'lon', 'lat'].indexOf(k) < 0) { - nd.addProp(k, v); - } - nd.setLatLng(node); - if (node.$innerNodes) { - for (let ind of node.$innerNodes) { - if (ind.$tag === 'tag') { - nd.addTag(ind.k, ind.v); - } - } - } - }); - - xmlParser.on('', node => { - let way = new Way(node.id, refElements); - for (let [k, v] of Object.entries(node)) { - if (!k.startsWith('$') && ['id'].indexOf(k) < 0) { - way.addProp(k, v); - } - } - if (node.$innerNodes) { - for (let ind of node.$innerNodes) { - if (ind.$tag === 'nd') { - if (ind.lon && ind.lat) { - way.addLatLng(ind); - } else if (ind.ref) { - way.addNodeRef(ind.ref); - } - } else if (ind.$tag === 'tag') - way.addTag(ind.k, ind.v); - } - } - }); - - xmlParser.on('', node => { - new Relation(node.id, refElements); - }); - - xmlParser.on('', (node, parent) => { - let relation = refElements.get(`relation/${parent.id}`); - let member = { - type: node.type, - role: node.role ? node.role : '', - ref: node.ref - }; - if (node.lat && node.lon) { - member.lat = node.lat, member.lon = node.lon, member.tags = {}; - for (let [k, v] of Object.entries(node)) { - if (!k.startsWith('$') && ['type', 'lat', 'lon'].indexOf(k) < 0) { - member[k] = v; - } - } - } - if (node.$innerNodes) { - let geometry = []; - let nodes = []; - for (let ind of node.$innerNodes) { - if (ind.lat && ind.lon) { - geometry.push(ind); - } else { - nodes.push(ind.ref); - } - } - if (geometry.length > 0) { - member.geometry = geometry; - } else if (nodes.length > 0) { - member.nodes = nodes; - } - } - relation.addMember(member); - }); - - xmlParser.on('', (node, parent) => { - refElements.get(`relation/${parent.id}`).setBounds([parseFloat(node.minlon), parseFloat(node.minlat), parseFloat(node.maxlon), parseFloat(node.maxlat)]); - }); - - xmlParser.on('', (node, parent) => { - refElements.get(`relation/${parent.id}`).addTag(node.k, node.v); - }); - - xmlParser.parse(osm); - }; - - if (format === 'json-raw') { - osm = JSON.parse(osm); - if (osm.elements) { - format = 'json'; - } else { - format = 'invalid'; - } - } - - if (format === 'json') { - analyzeFeaturesFromJson(osm); - } else if (format === 'xml') { - analyzeFeaturesFromXml(osm); - } - - refElements.bindAll(); - - for (let v of refElements.values()) { - if (v.refCount <= 0 || (v.hasTag && renderTagged && !(v instanceof Way && excludeWay))) { - let features = v.toFeatureArray(); - // return the first geometry of the first relation element - if (v instanceof Relation && !completeFeature && features.length > 0) { - return features[0].geometry; - } - featureArray = featureArray.concat(features); - } - } - - return { type: 'FeatureCollection', features: featureArray }; - }; - - var osm2geojson = /*@__PURE__*/getDefaultExportFromCjs(lib); - - const supportedFormats = ['topojson', 'osm', 'kml', 'gpx', 'tcx', 'csv', 'tsv', 'polyline']; - class Converter { - constructor(format, data, options = {}) { - /** - * Creates a blank GeoJSON feature collection. - * @returns A new GeoJSON feature collection with no features. - */ - this.blankGeoJSON = () => ({ - type: 'FeatureCollection', - features: [], - }); - this._rawData = data; - this._format = format; - this._options = options; - const converters = { - 'topojson': this.loadTopoJson, - 'osm': this.loadOsm, - 'kml': this.loadXml, - 'gpx': this.loadXml, - 'tcx': this.loadXml, - 'csv': this.loadCsv, - 'tsv': this.loadCsv, - 'polyline': this.loadPolyline - }; - this._conversionFn = converters[format]; - } - async convert() { - if (!this._conversionFn) { - return new Promise((_, rej) => rej(`No converter exists for ${this._format}`)); - } - else { - return this._conversionFn(); - } - } - /** - * Load the XML data as GeoJSON - * @returns A promise resolving to a GeoJSON FeatureCollection - */ - async loadXml() { - // Use the appropriate parser based on the format - const geojson = toGeoJson[this._format](new DOMParser().parseFromString(this._rawData, "text/xml")); - return geojson; - } - /** - * Loads and parses CSV data into a GeoJSON FeatureCollection. - * @returns A Promise that resolves with the GeoJSON FeatureCollection. - */ - async loadCsv() { - // Define options for the csv2geojson library - let options = this._options.csvOptions || {}; // TODO allow CSV options - if (this._format === 'tsv') { - options.delimiter = '\t'; - } - // Use the csv2geojson library to convert the CSV to GeoJSON - const geojson = await new Promise((resolve, reject) => { - csv2geojson_1.csv2geojson(this._rawData, options, (err, data) => { - if (err) { - reject(err); - } - else { - resolve(data); - } - }); - }); - return geojson; - } - /** - * Loads TopoJSON data and converts it into a GeoJSON FeatureCollection - * @returns A Promise that resolves with the GeoJSON FeatureCollection. - */ - async loadTopoJson() { - let topoJsonData = {}; - try { - topoJsonData = JSON.parse(this._rawData); - } - catch (e) { - throw "Invalid TopoJson"; - } - // Convert the data - let result = this.blankGeoJSON(); - if (topoJsonData.type === "Topology" && topoJsonData.objects !== undefined) { - result = { - type: "FeatureCollection", - features: result.features = Object.keys(topoJsonData.objects).map(key => topojsonFeature(topoJsonData, key)).reduce((a, v) => [...a, ...v.features], []) - }; - } - return result; - } - ; - /** - * Loads OSM data and converts it into a GeoJSON FeatureCollection - * @returns A Promise that resolves with the GeoJSON FeatureCollection. - */ - async loadOsm() { - return osm2geojson(this._rawData); - } - /** - * Loads and parses Polyline data into a GeoJSON FeatureCollection. - * @returns A Promise that resolves with the GeoJSON FeatureCollection. - */ - async loadPolyline() { - let options = this._options.polylineOptions || {}; - // Use the @mapbox/polyline library to convert the polyline to GeoJSON - const geojson = await new Promise((resolve, reject) => { - try { - const lineString = polylineExports.toGeoJSON(this._rawData, options.precision); - let geometry = lineString; - if (options.type === 'point') { - if (lineString.coordinates.length === 1) { - // Make it a point - geometry = { - 'type': 'Point', - 'coordinates': lineString.coordinates[0] - }; - } - else { - console.warn('Cannot convert polyline to ' + options.type); - } - } - else if (options.type === 'polygon') { - if (lineString.coordinates[0][0] === lineString.coordinates[lineString.coordinates.length - 1][0] && - lineString.coordinates[0][1] === lineString.coordinates[lineString.coordinates.length - 1][1]) { - // Make it a polygon - geometry = { - 'type': 'Polygon', - 'coordinates': [lineString.coordinates] - }; - } - else { - console.warn('Cannot convert polyline to ' + options.type); - } - } - resolve({ - type: "FeatureCollection", - features: [{ - "type": "Feature", - "geometry": geometry, - "properties": options.properties || {} - }] - }); - } - catch (err) { - reject(err); - } - }); - return geojson; - } - } - - var WorkerClass = null; - - try { - var WorkerThreads = - typeof module !== 'undefined' && typeof module.require === 'function' && module.require('worker_threads') || - typeof __non_webpack_require__ === 'function' && __non_webpack_require__('worker_threads') || - typeof require === 'function' && require('worker_threads'); - WorkerClass = WorkerThreads.Worker; - } catch(e) {} // eslint-disable-line - - function decodeBase64$1(base64, enableUnicode) { - return Buffer.from(base64, 'base64').toString('utf8'); - } - - function createBase64WorkerFactory$2(base64, sourcemapArg, enableUnicodeArg) { - var source = decodeBase64$1(base64); - var start = source.indexOf('\n', 10) + 1; - var body = source.substring(start) + (''); - return function WorkerFactory(options) { - return new WorkerClass(body, Object.assign({}, options, { eval: true })); - }; - } - - function decodeBase64(base64, enableUnicode) { - var binaryString = atob(base64); - return binaryString; - } - - function createURL(base64, sourcemapArg, enableUnicodeArg) { - var source = decodeBase64(base64); - var start = source.indexOf('\n', 10) + 1; - var body = source.substring(start) + (''); - var blob = new Blob([body], { type: 'application/javascript' }); - return URL.createObjectURL(blob); - } - - function createBase64WorkerFactory$1(base64, sourcemapArg, enableUnicodeArg) { - var url; - return function WorkerFactory(options) { - url = url || createURL(base64); - return new Worker(url, options); - }; - } - - var kIsNodeJS = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'; - - function isNodeJS() { - return kIsNodeJS; - } - - function createBase64WorkerFactory(base64, sourcemapArg, enableUnicodeArg) { - if (isNodeJS()) { - return createBase64WorkerFactory$2(base64); - } - return createBase64WorkerFactory$1(base64); - } - - var WorkerFactory = createBase64WorkerFactory('Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewoJJ3VzZSBzdHJpY3QnOwoKCWZ1bmN0aW9uIGdldERlZmF1bHRFeHBvcnRGcm9tQ2pzICh4KSB7CgkJcmV0dXJuIHggJiYgeC5fX2VzTW9kdWxlICYmIE9iamVjdC5wcm90b3R5cGUuaGFzT3duUHJvcGVydHkuY2FsbCh4LCAnZGVmYXVsdCcpID8geFsnZGVmYXVsdCddIDogeDsKCX0KCglmdW5jdGlvbiBnZXRBdWdtZW50ZWROYW1lc3BhY2UobikgewoJICBpZiAobi5fX2VzTW9kdWxlKSByZXR1cm4gbjsKCSAgdmFyIGYgPSBuLmRlZmF1bHQ7CgkJaWYgKHR5cGVvZiBmID09ICJmdW5jdGlvbiIpIHsKCQkJdmFyIGEgPSBmdW5jdGlvbiBhICgpIHsKCQkJCWlmICh0aGlzIGluc3RhbmNlb2YgYSkgewoJICAgICAgICByZXR1cm4gUmVmbGVjdC5jb25zdHJ1Y3QoZiwgYXJndW1lbnRzLCB0aGlzLmNvbnN0cnVjdG9yKTsKCQkJCX0KCQkJCXJldHVybiBmLmFwcGx5KHRoaXMsIGFyZ3VtZW50cyk7CgkJCX07CgkJCWEucHJvdG90eXBlID0gZi5wcm90b3R5cGU7CgkgIH0gZWxzZSBhID0ge307CgkgIE9iamVjdC5kZWZpbmVQcm9wZXJ0eShhLCAnX19lc01vZHVsZScsIHt2YWx1ZTogdHJ1ZX0pOwoJCU9iamVjdC5rZXlzKG4pLmZvckVhY2goZnVuY3Rpb24g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vbnMuZGVsaW1pdGVyID09PSAnYXV0bycgJiYgdHlwZW9mIHggPT0gJ3N0cmluZycpIHsKCSAgICAgICAgb3B0aW9ucy5kZWxpbWl0ZXIgPSBhdXRvRGVsaW1pdGVyKHgpOwoJICAgICAgICBpZiAoIW9wdGlvbnMuZGVsaW1pdGVyKSB7CgkgICAgICAgICAgICBjYWxsYmFjayh7CgkgICAgICAgICAgICAgICAgdHlwZTogJ0Vycm9yJywKCSAgICAgICAgICAgICAgICBtZXNzYWdlOiAnQ291bGQgbm90IGF1dG9kZXRlY3QgZGVsaW1pdGVyJwoJICAgICAgICAgICAgfSk7CgkgICAgICAgICAgICByZXR1cm47CgkgICAgICAgIH0KCSAgICB9CgoJICAgIHZhciBudW1lcmljRmllbGRzID0gb3B0aW9ucy5udW1lcmljRmllbGRzID8gb3B0aW9ucy5udW1lcmljRmllbGRzLnNwbGl0KCcsJykgOiBudWxsOwoKCSAgICB2YXIgcGFyc2VkID0gKHR5cGVvZiB4ID09ICdzdHJpbmcnKSA/CgkgICAgICAgIGRzdi5kc3ZGb3JtYXQob3B0aW9ucy5kZWxpbWl0ZXIpLnBhcnNlKHgsIGZ1bmN0aW9uIChkKSB7CgkgICAgICAgICAgICBpZiAobnVtZXJpY0ZpZWxkcykgewoJICAgICAgICAgICAgICAgIGZvciAodmFyIGtleSBpbiBkKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmIChudW1lcmljRmllbGRzLmluY2x1ZGVzKGtleSkpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGRba2V5XSA9ICtkW2tleV07CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgICAgICByZXR1cm4gZDsKCSAgICAgICAgfSkgOiB4OwoKCSAgICBpZiAoIXBhcnNlZC5sZW5ndGgpIHsKCSAgICAgICAgY2FsbGJhY2sobnVsbCwgZmVhdHVyZWNvbGxlY3Rpb24pOwoJICAgICAgICByZXR1cm47CgkgICAgfQoKCSAgICB2YXIgZXJyb3JzID0gW107CgkgICAgdmFyIGk7CgoKCSAgICBpZiAoIWxhdGZpZWxkKSBsYXRmaWVsZCA9IGd1ZXNzTGF0SGVhZGVyKHBhcnNlZFswXSk7CgkgICAgaWYgKCFsb25maWVsZCkgbG9uZmllbGQgPSBndWVzc0xvbkhlYWRlcihwYXJzZWRbMF0pOwoJICAgIHZhciBub0dlb21ldHJ5ID0gKCFsYXRmaWVsZCB8fCAhbG9uZmllbGQpOwoKCSAgICBpZiAobm9HZW9tZXRyeSkgewoJICAgICAgICBmb3IgKGkgPSAwOyBpIDwgcGFyc2VkLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgICAgICBmZWF0dXJlcy5wdXNoKHsKCSAgICAgICAgICAgICAgICB0eXBlOiAnRmVhdHVyZScsCgkgICAgICAgICAgICAgICAgcHJvcGVydGllczogcGFyc2VkW2ldLAoJICAgICAgICAgICAgICAgIGdlb21ldHJ5OiBudWxsCgkgICAgICAgICAgICB9KTsKCSAgICAgICAgfQoJICAgICAgICBjYWxsYmFjayhlcnJvcnMubGVuZ3RoID8gZXJyb3JzIDogbnVsbCwgZmVhdHVyZWNvbGxlY3Rpb24pOwoJICAgICAgICByZXR1cm47CgkgICAgfQoKCSAgICBmb3IgKGkgPSAwOyBpIDwgcGFyc2VkLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgIGlmIChwYXJzZWRbaV1bbG9uZmllbGRdICE9PSB1bmRlZmluZWQgJiYKCSAgICAgICAgICAgIHBhcnNlZFtpXVtsYXRmaWVsZF0gIT09IHVuZGVmaW5lZCkgewoKCSAgICAgICAgICAgIHZhciBsb25rID0gcGFyc2VkW2ldW2xvbmZpZWxkXSwKCSAgICAgICAgICAgICAgICBsYXRrID0gcGFyc2VkW2ldW2xhdGZpZWxkXSwKCSAgICAgICAgICAgICAgICBsb25mLCBsYXRmLAoJICAgICAgICAgICAgICAgIGE7CgoJICAgICAgICAgICAgYSA9IHNleGFnZXNpbWFsKGxvbmssICdFVycpOwoJICAgICAgICAgICAgaWYgKGEpIGxvbmsgPSBhOwoJICAgICAgICAgICAgYSA9IHNleGFnZXNpbWFsKGxhdGssICdOUycpOwoJICAgICAgICAgICAgaWYgKGEpIGxhdGsgPSBhOwoKCSAgICAgICAgICAgIGxvbmYgPSBwYXJzZUZsb2F0KGxvbmspOwoJICAgICAgICAgICAgbGF0ZiA9IHBhcnNlRmxvYXQobGF0ayk7CgoJICAgICAgICAgICAgaWYgKGlzTmFOKGxvbmYpIHx8CgkgICAgICAgICAgICAgICAgaXNOYU4obGF0ZikpIHsKCSAgICAgICAgICAgICAgICBlcnJvcnMucHVzaCh7CgkgICAgICAgICAgICAgICAgICAgIG1lc3NhZ2U6ICdBIHJvdyBjb250YWluZWQgYW4gaW52YWxpZCB2YWx1ZSBmb3IgbGF0aXR1ZGUgb3IgbG9uZ2l0dWRlJywKCSAgICAgICAgICAgICAgICAgICAgcm93OiBwYXJzZWRbaV0sCgkgICAgICAgICAgICAgICAgICAgIGluZGV4OiBpCgkgICAgICAgICAgICAgICAgfSk7CgkgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgIGlmICghb3B0aW9ucy5pbmNsdWRlTGF0TG9uKSB7CgkgICAgICAgICAgICAgICAgICAgIGRlbGV0ZSBwYXJzZWRbaV1bbG9uZmllbGRdOwoJICAgICAgICAgICAgICAgICAgICBkZWxldGUgcGFyc2VkW2ldW2xhdGZpZWxkXTsKCSAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIGZlYXR1cmVzLnB1c2goewoJICAgICAgICAgICAgICAgICAgICB0eXBlOiAnRmVhdHVyZScsCgkgICAgICAgICAgICAgICAgICAgIHByb3BlcnRpZXM6IHBhcnNlZFtpXSwKCSAgICAgICAgICAgICAgICAgICAgZ2VvbWV0cnk6IHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICdQb2ludCcsCgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogWwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHBhcnNlRmxvYXQobG9uZiksCgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgcGFyc2VGbG9hdChsYXRmKQoJICAgICAgICAgICAgICAgICAgICAgICAgXQoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfSk7CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCSAgICB9CgoJICAgIGNhbGxiYWNrKGVycm9ycy5sZW5ndGggPyBlcnJvcnMgOiBudWxsLCBmZWF0dXJlY29sbGVjdGlvbik7Cgl9CgoJZnVuY3Rpb24gdG9MaW5lKGdqKSB7CgkgICAgdmFyIGZlYXR1cmVzID0gZ2ouZmVhdHVyZXM7CgkgICAgdmFyIGxpbmUgPSB7CgkgICAgICAgIHR5cGU6ICdGZWF0dXJlJywKCSAgICAgICAgZ2VvbWV0cnk6IHsKCSAgICAgICAgICAgIHR5cGU6ICdMaW5lU3RyaW5nJywKCSAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBbXQoJICAgICAgICB9CgkgICAgfTsKCSAgICBmb3IgKHZhciBpID0gMDsgaSA8IGZlYXR1cmVzLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgIGxpbmUuZ2VvbWV0cnkuY29vcmRpbmF0ZXMucHVzaChmZWF0dXJlc1tpXS5nZW9tZXRyeS5jb29yZGluYXRlcyk7CgkgICAgfQoJICAgIGxpbmUucHJvcGVydGllcyA9IGZlYXR1cmVzLnJlZHVjZShmdW5jdGlvbiAoYWdncmVnYXRlZFByb3BlcnRpZXMsIG5ld0ZlYXR1cmUpIHsKCSAgICAgICAgZm9yICh2YXIga2V5IGluIG5ld0ZlYXR1cmUucHJvcGVydGllcykgewoJICAgICAgICAgICAgaWYgKCFhZ2dyZWdhdGVkUHJvcGVydGllc1trZXldKSB7CgkgICAgICAgICAgICAgICAgYWdncmVnYXRlZFByb3BlcnRpZXNba2V5XSA9IFtdOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgYWdncmVnYXRlZFByb3BlcnRpZXNba2V5XS5wdXNoKG5ld0ZlYXR1cmUucHJvcGVydGllc1trZXldKTsKCSAgICAgICAgfQoJICAgICAgICByZXR1cm4gYWdncmVnYXRlZFByb3BlcnRpZXM7CgkgICAgfSwge30pOwoJICAgIHJldHVybiB7CgkgICAgICAgIHR5cGU6ICdGZWF0dXJlQ29sbGVjdGlvbicsCgkgICAgICAgIGZlYXR1cmVzOiBbbGluZV0KCSAgICB9OwoJfQoKCWZ1bmN0aW9uIHRvUG9seWdvbihnaikgewoJICAgIHZhciBmZWF0dXJlcyA9IGdqLmZlYXR1cmVzOwoJICAgIHZhciBwb2x5ID0gewoJICAgICAgICB0eXBlOiAnRmVhdHVyZScsCgkgICAgICAgIGdlb21ldHJ5OiB7CgkgICAgICAgICAgICB0eXBlOiAnUG9seWdvbicsCgkgICAgICAgICAgICBjb29yZGluYXRlczogW1tdXQoJICAgICAgICB9CgkgICAgfTsKCSAgICBmb3IgKHZhciBpID0gMDsgaSA8IGZlYXR1cmVzLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgIHBvbHkuZ2VvbWV0cnkuY29vcmRpbmF0ZXNbMF0ucHVzaChmZWF0dXJlc1tpXS5nZW9tZXRyeS5jb29yZGluYXRlcyk7CgkgICAgfQoJICAgIHBvbHkucHJvcGVydGllcyA9IGZlYXR1cmVzLnJlZHVjZShmdW5jdGlvbiAoYWdncmVnYXRlZFByb3BlcnRpZXMsIG5ld0ZlYXR1cmUpIHsKCSAgICAgICAgZm9yICh2YXIga2V5IGluIG5ld0ZlYXR1cmUucHJvcGVydGllcykgewoJICAgICAgICAgICAgaWYgKCFhZ2dyZWdhdGVkUHJvcGVydGllc1trZXldKSB7CgkgICAgICAgICAgICAgICAgYWdncmVnYXRlZFByb3BlcnRpZXNba2V5XSA9IFtdOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgYWdncmVnYXRlZFByb3BlcnRpZXNba2V5XS5wdXNoKG5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25zdCBwdHMgPSAkKG5vZGUsIHBvaW50bmFtZSk7CgkgICAgY29uc3QgbGluZSA9IFtdOwoJICAgIGNvbnN0IHRpbWVzID0gW107CgkgICAgY29uc3QgZXh0ZW5kZWRWYWx1ZXMgPSB7fTsKCSAgICBmb3IgKGxldCBpID0gMDsgaSA8IHB0cy5sZW5ndGg7IGkrKykgewoJICAgICAgICBjb25zdCBjID0gY29vcmRQYWlyJDEocHRzW2ldKTsKCSAgICAgICAgaWYgKCFjKSB7CgkgICAgICAgICAgICBjb250aW51ZTsKCSAgICAgICAgfQoJICAgICAgICBsaW5lLnB1c2goYy5jb29yZGluYXRlcyk7CgkgICAgICAgIGlmIChjLnRpbWUpCgkgICAgICAgICAgICB0aW1lcy5wdXNoKGMudGltZSk7CgkgICAgICAgIGZvciAoY29uc3QgW25hbWUsIHZhbF0gb2YgYy5leHRlbmRlZFZhbHVlcykgewoJICAgICAgICAgICAgY29uc3QgcGx1cmFsID0gbmFtZSA9PT0gImhlYXJ0IiA/IG5hbWUgOiBuYW1lLnJlcGxhY2UoImdweHRweDoiLCAiIikgKyAicyI7CgkgICAgICAgICAgICBpZiAoIWV4dGVuZGVkVmFsdWVzW3BsdXJhbF0pIHsKCSAgICAgICAgICAgICAgICBleHRlbmRlZFZhbHVlc1twbHVyYWxdID0gQXJyYXkocHRzLmxlbmd0aCkuZmlsbChudWxsKTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIGV4dGVuZGVkVmFsdWVzW3BsdXJhbF1baV0gPSB2YWw7CgkgICAgICAgIH0KCSAgICB9CgkgICAgaWYgKGxpbmUubGVuZ3RoIDwgMikKCSAgICAgICAgcmV0dXJuOyAvLyBJbnZhbGlkIGxpbmUgaW4gR2VvSlNPTgoJICAgIHJldHVybiB7CgkgICAgICAgIGxpbmU6IGxpbmUsCgkgICAgICAgIHRpbWVzOiB0aW1lcywKCSAgICAgICAgZXh0ZW5kZWRWYWx1ZXM6IGV4dGVuZGVkVmFsdWVzLAoJICAg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sdGkpIHsKCSAgICAgICAgICAgICAgICBpZiAoIXByb3BzW25hbWVdKSB7CgkgICAgICAgICAgICAgICAgICAgIHByb3BzW25hbWVdID0gZXh0cmFjdGVkTGluZXMubWFwKChsaW5lKSA9PiBuZXcgQXJyYXkobGluZS5saW5lLmxlbmd0aCkuZmlsbChudWxsKSk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIHByb3BzW25hbWVdW2ldID0gdmFsOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgZWxzZSB7CgkgICAgICAgICAgICAgICAgcHJvcHNbbmFtZV0gPSB2YWw7CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCSAgICB9CgkgICAgcmV0dXJuIHsKCSAgICAgICAgdHlwZTogIkZlYXR1cmUiLAoJICAgICAgICBwcm9wZXJ0aWVzOiBwcm9wZXJ0aWVzLAoJICAgICAgICBnZW9tZXRyeTogbXVsdGkKCSAgICAgICAgICAgID8gewoJICAgICAgICAgICAgICAgIHR5cGU6ICJNdWx0aUxpbmVTdHJpbmciLAoJICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiB0cmFjaywKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIDogewoJICAgICAgICAgICAgICAgIHR5cGU6ICJMaW5lU3RyaW5nIiwKCSAgICAgICAgICAgICAgICBjb29yZGluYXRlczogdHJhY2tbMF0sCgkgICAgICAgICAgICB9LAoJICAgIH07Cgl9CgkvKioKCSAqIEV4dHJhY3QgYSBwb2ludCwgaWYgcG9zc2libGUsIGZyb20gYSBnaXZlbiBub2RlLAoJICogd2hpY2ggaXMgdXN1YWxseSBhIHdwdCBvciB0cmtwdAoJICovCglmdW5jdGlvbiBnZXRQb2ludChub2RlKSB7CgkgICAgY29uc3QgcHJvcGVydGllcyA9IE9iamVjdC5hc3NpZ24oZXh0cmFjdFByb3BlcnRpZXMobm9kZSksIGdldE11bHRpKG5vZGUsIFsic3ltIl0pKTsKCSAgICBjb25zdCBwYWlyID0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SB7CgkgICAgICAgIGxpbmUgPSBnZXRQb2ludHMoc2VnbWVudCk7CgkgICAgICAgIGlmIChsaW5lKSB7CgkgICAgICAgICAgICB0cmFjay5wdXNoKGxpbmUubGluZSk7CgkgICAgICAgICAgICBpZiAobGluZS50aW1lcy5sZW5ndGgpCgkgICAgICAgICAgICAgICAgdGltZXMucHVzaChsaW5lLnRpbWVzKTsKCSAgICAgICAgICAgIGlmIChsaW5lLmhlYXJ0UmF0ZXMubGVuZ3RoKQoJICAgICAgICAgICAgICAgIGhlYXJ0UmF0ZXMucHVzaChsaW5lLmhlYXJ0UmF0ZXMpOwoJICAgICAgICAgICAgYWxsRXh0ZW5kZWRQcm9wZXJ0aWVzLnB1c2gobGluZS5leHRlbmRlZFByb3BlcnRpZXMpOwoJICAgICAgICB9CgkgICAgfQoJICAgIGZvciAobGV0IGkgPSAwOyBpIDwgYWxsRXh0ZW5kZWRQcm9wZXJ0aWVzLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgIGNvbnN0IGV4dGVuZGVkUHJvcGVydGllcyA9IGFsbEV4dGVuZGVkUHJvcGVydGllc1tpXTsKCSAgICAgICAgZm9yIChjb25zdCBwcm9wZXJ0eSBpbiBleHRlbmRlZFByb3BlcnRpZXMpIHsKCSAgICAgICAgICAgIGlmIChzZWdtZW50cy5sZW5ndGggPT09IDEpIHsKCSAgICAgICAgICAgICAgICBpZiAobGluZSkgewoJICAgICAgICAgICAgICAgICAgICBwcm9wZXJ0aWVzW3Byb3BlcnR5XSA9IGxpbmUuZXh0ZW5kZWRQcm9wZXJ0aWVzW3Byb3BlcnR5XTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgICAgICBlbHNlIHsKCSAgICAgICAgICAgICAgICBpZiAoIXByb3BlcnRpZXNbcHJvcGVydHldKSB7CgkgICAgICAgICAgICAgICAgICAgIHByb3BlcnRpZXNbcHJvcGVydHldID0gdHJhY2subWFwKCh0cmFjaykgPT4gQXJyYXkodHJhY2subGVuZ3RoKS5maWxsKG51bGwpKTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgcHJvcGVydGllc1twcm9wZXJ0eV1baV0gPSBleHRlbmRlZFByb3BlcnRpZXNbcHJvcGVydHldOwoJICAgICAgICAgICAgfQoJICAgICAgICB9CgkgICAgfQoJICAgIGlmICh0cmFjay5sZW5ndGggPT09IDApCgkgICAgICAgIHJldHVybiBudWxsOwoJICAgIGlmICh0aW1lcy5sZW5ndGggfHwgaGVhcnRSYXRlcy5sZW5ndGgpIHsKCSAgICAgICAgcHJvcGVydGllcy5jb29yZGluYXRlUHJvcGVydGllcyA9IE9iamVjdC5hc3NpZ24odGltZXMubGVuZ3RoCgkgICAgICAgICAgICA/IHsKCSAgICAgICAgICAgICAgICB0aW1lczogdHJhY2subGVuZ3RoID09PSAxID8gdGltZXNbMF0gOiB0aW1lcywKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIDoge30sIGhlYXJ0UmF0ZXMubGVuZ3RoCgkgICAgICAgICAgICA/IHsKCSAgICAgICAgICAgICAgICBoZWFydDogdHJhY2subGVuZ3RoID09PSAxID8gaGVhcnRSYXRlc1swXSA6IGhlYXJ0UmF0ZXMsCgkgICAgICAgICAgICB9CgkgICAgICAgICAgICA6IHt9KTsKCSAgICB9CgkgICAgcmV0dXJuIHsKCSAgICAgICAgdHlwZTogIkZlYXR1cmUiLAoJICAgICAgICBwcm9wZXJ0aWVzOiBwcm9wZXJ0aWVzLAoJICAgICAgICBnZW9tZXRyeTogdHJhY2subGVuZ3RoID09PSAxCgkgICAgICAgICAgICA/IHsKCSAgICAgICAgICAgICAgICB0eXBlOiAiTGluZVN0cmluZyIsCgkgICAgICAgICAgICAgICAgY29vcmRpbmF0ZXM6IHRyYWNrWzBdLAoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgOiB7CgkgICAgICAgICAgICAgICAgdHlwZTogIk11bHRpTGluZVN0cmluZyIsCgkgICAgICAgICAgICAgICAgY29vc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sKCSAgICAgICAgICAgICAgICAgICAgImljb24tb2Zmc2V0IjogW2xlZnQsIHRvcF0sCgkgICAgICAgICAgICAgICAgICAgICJpY29uLW9mZnNldC11bml0cyI6IFt4dW5pdHMsIHl1bml0c10sCgkgICAgICAgICAgICAgICAgfTsKCSAgICAgICAgICAgIHJldHVybiB7fTsKCSAgICAgICAgfSksIGV4dHJhY3RJY29uSHJlZihpY29uU3R5bGUpKTsKCSAgICB9KTsKCX0KCWZ1bmN0aW9uIGV4dHJhY3RMYWJlbChub2RlKSB7CgkgICAgcmV0dXJuIGdldChub2RlLCAiTGFiZWxTdHlsZSIsIChsYWJlbFN0eWxlKSA9PiB7CgkgICAgICAgIHJldHVybiBPYmplY3QuYXNzaWduKGdldENvbG9yKGxhYmVsU3R5bGUsICJsYWJlbCIpLCBudW1lcmljUHJvcGVydHkobGFiZWxTdHlsZSwgInNjYWxlIiwgImxhYmVsLXNjYWxlIikpOwoJICAgIH0pOwoJfQoJZnVuY3Rpb24gZXh0cmFjdExpbmUobm9kZSkgewoJICAgIHJldHVybiBnZXQobm9kZSwgIkxpbmVTdHlsZSIsIChsaW5lU3R5bGUpID0+IHsKCSAgICAgICAgcmV0dXJuIE9iamVjdC5hc3NpZ24oZ2V0Q29sb3IobGluZVN0eWxlLCAic3Ryb2tlIiksIG51bWVyaWNQcm9wZXJ0eShsaW5lU3R5bGUsICJ3aWR0aCIsICJzdHJva2Utd2lkdGgiKSk7CgkgICAgfSk7Cgl9CglmdW5jdGlvbiBleHRyYWN0UG9seShub2RlKSB7CgkgICAgcmV0dXJuIGdldChub2RlLCAiUG9seVN0eWxlIiwgKHBvbHlTdHlsZSwgcHJvcGVydGllcykgPT4gewoJICAgICAgICByZXR1cm4gT2JqZWN0LmFzc2lnbihwcm9wZXJ0aWVzLCBnZXQocG9seVN0eWxlLCAiY29sb3IiLCAoZWxlbSkgPT4gZml4Q29sb3Iobm9kZVZhbChlbGVtKSwgImZpbGwiKSksIHZhbDEocG9seVN0eWxl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GVWYWwoZWxlbSkuc3BsaXQoIiAiKS5tYXAocGFyc2VGbG9hdCk7CgkgICAgfSk7CgkgICAgaWYgKGNvb3JkaW5hdGVzLmxlbmd0aCA9PT0gMCkgewoJICAgICAgICByZXR1cm4gbnVsbDsKCSAgICB9CgkgICAgcmV0dXJuIHsKCSAgICAgICAgZ2VvbWV0cnk6IGNvb3JkaW5hdGVzLmxlbmd0aCA+IDIKCSAgICAgICAgICAgID8gewoJICAgICAgICAgICAgICAgIHR5cGU6ICJMaW5lU3RyaW5nIiwKCSAgICAgICAgICAgICAgICBjb29yZGluYXRlcywKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIDogewoJICAgICAgICAgICAgICAgIHR5cGU6ICJQb2ludCIsCgkgICAgICAgICAgICAgICAgY29vcmRpbmF0ZXM6IGNvb3JkaW5hdGVzWzBdLAoJICAgICAgICAgICAgfSwKCSAgICAgICAgdGltZXM6ICQobm9kZSwgIndoZW4iKS5tYXAoKGVsZW0pID0+IG5vZGVWYWwoZWxlbSkpLAoJICAgIH07Cgl9CglmdW5jdGlvbiBmaXhSaW5nKHJpbmcpIHsKCSAgICBpZiAocmluZy5sZW5ndGggPT09IDApCgkgICAgICAgIHJldHVybiByaW5nOwoJICAgIGNvbnN0IGZpcnN0ID0gcmluZ1swXTsKCSAgICBjb25zdCBsYXN0ID0gcmluZ1tyaW5nLmxlbmd0aCAtIDFdOwoJICAgIGxldCBlcXVhbCA9IHRydWU7CgkgICAgZm9yIChsZXQgaSA9IDA7IGkgPCBNYXRoLm1heChmaXJzdC5sZW5ndGgsIGxhc3QubGVuZ3RoKTsgaSsrKSB7CgkgICAgICAgIGlmIChmaXJzdFtpXSAhPT0gbGFzdFtpXSkgewoJICAgICAgICAgICAgZXF1YWwgPSBmYWxzZTsKCSAgICAgICAgICAgIGJyZWFrOwoJICAgICAgICB9CgkgICAgfQoJICAgIGlmICghZXF1YWwpIHsKCSAgICAgICAgcmV0dXJuIHJpbmcuY29uY2F0KFtyaW5nWzBdXSk7CgkgICAgfQoJICAgIHJldHVybiByaW5nOwoJfQoJZnVuY3Rpb24gZ2V0Q29vcmRpbmF0ZXMobm9kZSkgewoJICAgIHJldHVybiBub2RlVmFsKGdldDEobm9kZSwgImNvb3JkaW5hdGVzIikpOwoJfQoJZnVuY3Rpb24gZ2V0R2VvbWV0cnkobm9kZSkgewoJICAgIGxldCBnZW9tZXRyaWVzID0gW107CgkgICAgbGV0IGNvb3JkVGltZXMgPSBbXTsKCSAgICBmb3IgKGxldCBpID0gMDsgaSA8IG5vZGUuY2hpbGROb2Rlcy5sZW5ndGg7IGkrKykgewoJICAgICAgICBjb25zdCBjaGlsZCA9IG5vZGUuY2hpbGROb2Rlcy5pdGVtKGkpOwoJICAgICAgICBpZiAoaXNFbGVtZW50KGNoaWxkKSkgewoJICAgICAgICAgICAgc3dpdGNoIChjaGlsZC50YWdOYW1lKSB7CgkgICAgICAgICAgICAgICAgY2FzZSAiTXVsdGlHZW9tZXRyeSI6CgkgICAgICAgICAgICAgICAgY2FzZSAiTXVsdGlUcmFjayI6CgkgICAgICAgICAgICAgICAgY2FzZSAiZ3g6TXVsdGlUcmFjayI6IHsKCSAgICAgICAgICAgICAgICAgICAgY29uc3QgY2hpbGRHZW9tZXRyaWVzID0gZ2V0R2VvbWV0cnkoY2hpbGQpOwoJICAgICAgICAgICAgICAgICAgICBnZW9tZXRyaWVzID0gZ2VvbWV0cmllcy5jb25jYXQoY2hpbGRHZW9tZXRyaWVzLmdlb21ldHJpZXMpOwoJICAgICAgICAgICAgICAgICAgICBjb29yZFRpbWVzID0gY29vcmRUaW1lcy5jb25jYXQoY2hpbGRHZW9tZXRyaWVzLmNvb3JkVGltZXMpOwoJICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgY2FzZSAiUG9pbnQiOiB7CgkgICAgICAgICAgICAgICAgICAgIGNvbnN0IGNvb3JkaW5hdGVzID0gY29vcmQxKGdldENvb3JkaW5hdGVzKGNoaWxkKSk7CgkgICAgICAgICAgICAgICAgICAgIGlmIChjb29yZGluYXRlcy5sZW5ndGggPj0gMikgewoJICAgICAgICAgICAgICAgICAgICAgICAgZ2VvbWV0cmllcy5wdXNoKHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAiUG9pbnQiLAoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzLAoJICAgICAgICAgICAgICAgICAgICAgICAgfSk7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIGNhc2UgIkxpbmVhclJpbmciOgoJICAgICAgICAgICAgICAgIGNhc2UgIkxpbmVTdHJpbmciOiB7CgkgICAgICAgICAgICAgICAgICAgIGNvbnN0IGNvb3JkaW5hdGVzID0gY29vcmQoZ2V0Q29vcmRpbmF0ZXMoY2hpbGQpKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGNvb3JkaW5hdGVzLmxlbmd0aCA+PSAyKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBnZW9tZXRyaWVzLnB1c2goewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICJMaW5lU3RyaW5nIiwKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlcywKCSAgICAgICAgICAgICAgICAgICAgICAgIH0pOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGJyZWFrOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICBjYXNlICJQb2x5Z29uIjogewoJICAgICAgICAgICAgICAgICAgICBjb25zdCBjb29yZHMgPSBbXTsKCSAgICAgICAgICAgICAgICAgICAgZm9yIChjb25zdCBsaW5lYXJSaW5nIG9mICQoY2hpbGQsICJMaW5lYXJSaW5nIikpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvbnN0IHJpbmcgPSBmaXhSaW5nKGNvb3JkKGdldENvb3JkaW5hdGVzKGxpbmVhclJpbmcpKSk7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAocmluZy5sZW5ndGggPj0gNCkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGNvb3Jkcy5wdXNoKHJpbmcpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGlmIChjb29yZHMubGVuZ3RoKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBnZW9tZXRyaWVzLnB1c2goewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICJQb2x5Z29uIiwKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogY29vcmRzLAoJICAgICAgICAgICAgICAgICAgICAgICAgfSk7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIGNhc2UgIlRyYWNrIjoKCSAgICAgICAgICAgICAgICBjYXNlICJneDpUcmFjayI6IHsKCSAgICAgICAgICAgICAgICAgICAgY29uc3QgZ3ggPSBneENvb3JkcyhjaGlsZCk7CgkgICAgICAgICAgICAgICAgICAgIGlmICghZ3gpCgkgICAgICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICAgICAgY29uc3QgeyB0aW1lcywgZ2VvbWV0cnkgfSA9IGd4OwoJICAgICAgICAgICAgICAgICAgICBnZW9tZXRyaWVzLnB1c2goZ2VvbWV0cnkpOwoJICAgICAgICAgICAgICAgICAgICBpZiAodGltZXMubGVuZ3RoKQoJICAgICAgICAgICAgICAgICAgICAgICAgY29vcmRUaW1lcy5wdXNoKHRpbWVzKTsKCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICB9CgkgICAgfQoJICAgIHJldHVybiB7CgkgICAgICAgIGdlb21ldHJpZXMsCgkgICAgICAgIGNvb3JkVGltZXMsCgkgICAgfTsKCX0KCglmdW5jdGlvbiBnZW9tZXRyeUxpc3RUb0dlb21ldHJ5KGdlb21ldHJpZXMpIHsKCSAgICByZXR1cm4gZ2VvbWV0cmllcy5sZW5ndGggPT09IDAKCSAgICAgICAgPyBudWxsCgkgICAgICAgIDogZ2VvbWV0cmllcy5sZW5ndGggPT09IDEKCSAgICAgICAgICAgID8gZ2VvbWV0cmllc1swXQoJICAgICAgICAgICAgOiB7CgkgICAgICAgICAgICAgICAgdHlwZTogIkdlb21ldHJ5Q29sbGVjdGlvbiIsCgkgICAgICAgICAgICAgICAgZ2VvbWV0cmllcywKCSAgICAgICAgICAgIH07Cgl9CglmdW5jdGlvbiBnZXRQbGFjZW1hcmsobm9kZSwgc3R5bGVNYXAsIHNjaGVtYSwgb3B0aW9ucykgewoJICAgIGNvbnN0IHsgY29vcmRUaW1lcywgZ2VvbWV0cmllcyB9ID0gZ2V0R2VvbWV0cnkobm9kZSk7CgkgICAgY29uc3QgZ2VvbWV0cnkgPSBnZW9tZXRyeUxpc3RUb0dlb21ldHJ5KGdlb21ldHJpZXMpOwoJICAgIGlmICghZ2VvbWV0cnkgJiYgb3B0aW9ucy5za2lwTnVsbEdlb21ldHJ5KSB7CgkgICAgICAgIHJldHVybiBudWxsOwoJICAgIH0KCSAgICBjb25zdCBmZWF0dXJlID0gewoJICAgICAgICB0eXBlOiAiRmVhdHVyZSIsCgkgICAgICAgIGdlb21ldHJ5LAoJICAgICAgICBwcm9wZXJ0aWVzOiBPYmplY3QuYXNzaWduKGdldE11bHRpKG5vZGUsIFsKCSAgICAgICAgICAgICJuYW1lIiwKCSAgICAgICAgICAgICJhZGRyZXNzIiwKCSAgICAgICAgICAgICJ2aXNpYmlsaXR5IiwKCSAgICAgICAgICAgICJvcGVuIiwKCSAgICAgICAgICAgICJwaG9uZU51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QgcmluZyA9IGZpeFJpbmcoY29vcmQoZ2V0Q29vcmRpbmF0ZXMobm9kZSkpKTsKCSAgICAgICAgcmV0dXJuIHsKCSAgICAgICAgICAgIGdlb21ldHJ5OiB7CgkgICAgICAgICAgICAgICAgdHlwZTogIlBvbHlnb24iLAoJICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBbcmluZ10sCgkgICAgICAgICAgICB9LAoJICAgICAgICB9OwoJICAgIH0KCSAgICByZXR1cm4gZ2V0TGF0TG9uQm94KG5vZGUpOwoJfQoJY29uc3QgREVHUkVFU19UT19SQURJQU5TID0gTWF0aC5QSSAvIDE4MDsKCWZ1bmN0aW9uIHJvdGF0ZUJveChiYm94LCBjb29yZGluYXRlcywgcm90YXRpb24pIHsKCSAgICBjb25zdCBjZW50ZXIgPSBbKGJib3hbMF0gKyBiYm94WzJdKSAvIDIsIChiYm94WzFdICsgYmJveFszXSkgLyAyXTsKCSAgICByZXR1cm4gWwoJICAgICAgICBjb29yZGluYXRlc1swXS5tYXAoKGNvb3JkaW5hdGUpID0+IHsKCSAgICAgICAgICAgIGNvbnN0IGR5ID0gY29vcmRpbmF0ZVsxXSAtIGNlbnRlclsxXTsKCSAgICAgICAgICAgIGNvbnN0IGR4ID0gY29vcmRpbmF0ZVswXSAtIGNlbnRlclswXTsKCSAgICAgICAgICAgIGNvbnN0IGRpc3RhbmNlID0gTWF0aC5zcXJ0KE1hdGgucG93KGR5LCAyKSArIE1hdGgucG93KGR4LCAyKSk7CgkgICAgICAgICAgICBjb25zdCBhbmdsZSA9IE1hdGguYXRhbjIoZHksIGR4KSArIHJvdGF0aW9uICogREVHUkVFU19UT19SQURJQU5TOwoJICAgICAgICAgICAgcmV0dXJuIFsKCSAgICAgICAgICAgICAgICBjZW50ZXJbMF0gKyBNYXRoLmNvcyhhbmdsZSkgKiBkaXN0YW5jZSwKCSAgICAgICAgICAgICAgICBjZW50ZXJbMV0gKyBNYXRoLnNpbihhbmdsZSkgKiBkaXN0YW5jZSwKCSAgICAgICAgICAgIF07CgkgICAgICAgIH0pLAoJICAgIF07Cgl9CglmdW5jdGlvbiBnZXRMYXRMb25Cb3gobm9kZSkgewoJICAgIGNvbnN0IGxhdExvbkJveCA9IGdldDEobm9kZSwgIkxhdExvbkJveCIpOwoJICAgIGlmIChsYXRMb25Cb3gpIHsKCSAgICAgICAgY29uc3Qgbm9ydGggPSBudW0xKGxhdExvbkJveCwgIm5vcnRoIik7CgkgICAgICAgIGNvbnN0IHdlc3QgPSBudW0xKGxhdExvbkJveCwgIndlc3QiKTsKCSAgICAgICAgY29uc3QgZWFzdCA9IG51bTEobGF0TG9uQm94LCAiZWFzdCIpOwoJICAgICAgICBjb25zdCBzb3V0aCA9IG51bTEobGF0TG9uQm94LCAic291dGgiKTsKCSAgICAgICAgY29uc3Qgcm90YXRpb24gPSBudW0xKGxhdExvbkJveCwgInJvdGF0aW9uIik7CgkgICAgICAgIGlmICh0eXBlb2Ygbm9ydGggPT09ICJudW1iZXIiICYmCgkgICAgICAgICAgICB0eXBlb2Ygc291dGggPT09ICJudW1iZXIiICYmCgkgICAgICAgICAgICB0eXBlb2Ygd2VzdCA9PT0gIm51bWJlciIgJiYKCSAgICAgICAgICAgIHR5cGVvZiBlYXN0ID09PSAibnVtYmVyIikgewoJICAgICAgICAgICAgY29uc3QgYmJveCA9IFt3ZXN0LCBzb3V0aCwgZWFzdCwgbm9ydGhdOwoJICAgICAgICAgICAgbGV0IGNvb3JkaW5hdGVzID0gWwoJICAgICAgICAgICAgICAgIFsKCSAgICAgICAgICAgICAgICAgICAgW3dlc3QsIG5vcnRoXSwKCSAgICAgICAgICAgICAgICAgICAgW2Vhc3QsIG5vcnRoXSwKCSAgICAgICAgICAgICAgICAgICAgW2Vhc3QsIHNvdXRoXSwKCSAgICAgICAgICAgICAgICAgICAgW3dlc3QsIHNvdXRoXSwKCSAgICAgICAgICAgICAgICAgICAgW3dlc3QsIG5vcnRoXSwgLy8gdG9wIGxlZnQgKGFnYWluKQoJICAgICAgICAgICAgICAgIF0sCgkgICAgICAgICAgICBdOwoJICAgICAgICAgICAgaWYgKHR5cGVvZiByb3RhdGlvbiA9PT0gIm51bWJlciIpIHsKCSAgICAgICAgICAgICAgICBjb29yZGluYXRlcyA9IHJvdGF0ZUJveChiYm94LCBjb29yZGluYXRlcywgcm90YXRpb24pOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmV0dXJuIHsKCSAgICAgICAgICAgICAgICBiYm94LAoJICAgICAgICAgICAgICAgIGdlb21ldHJ5OiB7CgkgICAgICAgICAgICAgICAgICAgIHR5cGU6ICJQb2x5Z29uIiwKCSAgICAgICAgICAgICAgICAgICAgY29vcmRpbmF0ZXMsCgkgICAgICAgICAgICAgICAgfSwKCSAgICAgICAgICAgIH07CgkgICAgICAgIH0KCSAgICB9CgkgICAgcmV0dXJuIG51bGw7Cgl9CglmdW5jdGlvbiBnZXRHcm91bmRPdmVybGF5KG5vZGUsIHN0eWxlTWFwLCBzY2hlbWEsIG9wdGlvbnMpIHsKCSAgICBjb25zdCBib3ggPSBnZXRHcm91bmRPdmVybGF5Qm94KG5vZGUpOwoJICAgIGNvbnN0IGdlb21ldHJ5ID0gYm94Py5nZW9tZXRyeSB8fCBudWxsOwoJICAgIGlmICghZ2VvbWV0cnkgJiYgb3B0aW9ucy5za2lwTnVsbEdlb21ldHJ5KSB7CgkgICAgICAgIHJldHVybiBudWxsOwoJICAgIH0KCSAgICBjb25zdCBmZWF0dXJlID0gewoJICAgICAgICB0eXBlOiAiRmVhdHVyZSIsCgkgICAgICAgIGdlb21ldHJ5LAoJICAgICAgICBwcm9wZXJ0aWVzOiBPYmplY3QuYXNzaWduKAoJICAgICAgICAvKioKCSAgICAgICAgICogUmVsYXRlZCB0bwoJICAgICAgICAgKiBodHRwczovL2dpc3QuZ2l0aHViLmNvbS90bWN3LzAzN2ExY2I2NjYwZDc0YTM5MmU5ZGE3NDQ2NTQwZjQ2CgkgICAgICAgICAqLwoJICAgICAgICB7ICJAZ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HsKCSAgICBjb25zdCBzdHlsZU1hcCA9IGJ1aWxkU3R5bGVNYXAobm9kZSk7CgkgICAgY29uc3Qgc2NoZW1hID0gYnVpbGRTY2hlbWEobm9kZSk7CgkgICAgY29uc3QgdHJlZSA9IHsgdHlwZTogInJvb3QiLCBjaGlsZHJlbjogW10gfTsKCSAgICBmdW5jdGlvbiB0cmF2ZXJzZShub2RlLCBwb2ludGVyLCBvcHRpb25zKSB7CgkgICAgICAgIGlmIChpc0VsZW1lbnQobm9kZSkpIHsKCSAgICAgICAgICAgIHN3aXRjaCAobm9kZS50YWdOYW1lKSB7CgkgICAgICAgICAgICAgICAgY2FzZSAiR3JvdW5kT3ZlcmxheSI6IHsKCSAgICAgICAgICAgICAgICAgICAgY29uc3QgcGxhY2VtYXJrID0gZ2V0R3JvdW5kT3ZlcmxheShub2RlLCBzdHlsZU1hcCwgc2NoZW1hLCBvcHRpb25zKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKHBsYWNlbWFyaykgewoJICAgICAgICAgICAgICAgICAgICAgICAgcG9pbnRlci5jaGlsZHJlbi5wdXNoKHBsYWNlbWFyayk7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIGNhc2UgIlBsYWNlbWFyayI6IHsKCSAgICAgICAgICAgICAgICAgICAgY29uc3QgcGxhY2VtYXJrID0gZ2V0UGxhY2VtYXJrKG5vZGUsIHN0eWxlTWFwLCBzY2hlbWEsIG9wdGlvbnMpOwoJICAgICAgICAgICAgICAgICAgICBpZiAocGxhY2VtYXJrKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBwb2ludGVyLmNoaWxkcmVuLnB1c2gocGxhY2VtYXJrKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgY2FzZSAiRm9sZGVyIjogewoJICAgICAgICAgICAgICAgICAgICBjb25zdCBmb2xkZXIgPSBnZXRGb2xkZXIobm9kZSk7CgkgICAgICAgICAgICAgICAgICAgIHBvaW50ZXIuY2hpbGRyZW4ucHVzaChmb2xkZXIpOwoJICAgICAgICAgICAgICAgICAgICBwb2ludGVyID0gZm9sZGVyOwoJICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCSAgICAgICAgaWYgKG5vZGUuY2hpbGROb2RlcykgewoJICAgICAgICAgICAgZm9yIChsZXQgaSA9IDA7IGkgPCBub2RlLmNoaWxkTm9kZXMubGVuZ3RoOyBpKyspIHsKCSAgICAgICAgICAgICAgICB0cmF2ZXJzZShub2RlLmNoaWxkTm9kZXNbaV0sIHBvaW50ZXIsIG9wdGlvbnMpOwoJICAgICAgICAgICAgfQoJICAgICAgICB9CgkgICAgfQoJICAgIHRyYXZlcnNlKG5vZGUsIHRyZWUsIG9wdGlvbnMpOwoJICAgIHJldHVybiB0cmVlOwoJfQoJLyoqCgkgKiBDb252ZXJ0IEtNTCB0byBHZW9KU09OIGluY3JlbWVudGFsbHksIHJldHVybmluZwoJICogYSBbR2VuZXJhdG9yXShodHRwczovL2RldmVsb3Blci5tb3ppbGxhLm9yZy9lbi1VUy9kb2NzL1dlYi9KYXZhU2NyaXB0L0d1aWRlL0l0ZXJhdG9yc19hbmRfR2VuZXJhdG9ycykKCSAqIHRoYXQgeWllbGRzIG91dHB1dCBmZWF0dXJlIGJ5IGZlYXR1cmUuCgkgKi8KCWZ1bmN0aW9uKiBrbWxHZW4obm9kZSwgb3B0aW9ucyA9IHsKCSAgICBza2lwTnVsbEdlb21ldHJ5OiBmYWxzZSwKCX0pIHsKCSAgICBjb25zdCBzdHlsZU1hcCA9IGJ1aWxkU3R5bGVNYXAobm9kZSk7CgkgICAgY29uc3Qgc2NoZW1hID0gYnVpbGRTY2hlbWEobm9kZSk7CgkgIC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CgkJICogQHBhcmFtIHtTdHJpbmd9IHN0cgoJCSAqIEBwYXJhbSB7TnVtYmVyfSBwcmVjaXNpb24KCQkgKiBAcmV0dXJucyB7T2JqZWN0fQoJCSAqLwoJCXBvbHlsaW5lLnRvR2VvSlNPTiA9IGZ1bmN0aW9uKHN0ciwgcHJlY2lzaW9uKSB7CgkJICAgIHZhciBjb29yZHMgPSBwb2x5bGluZS5kZWNvZGUoc3RyLCBwcmVjaXNpb24pOwoJCSAgICByZXR1cm4gewoJCSAgICAgICAgdHlwZTogJ0xpbmVTdHJpbmcnLAoJCSAgICAgICAgY29vcmRpbmF0ZXM6IGZsaXBwZWQoY29vcmRzKQoJCSAgICB9OwoJCX07CgoJCWlmIChtb2R1bGUuZXhwb3J0cykgewoJCSAgICBtb2R1bGUuZXhwb3J0cyA9IHBvbHlsaW5lOwoJCX0gCgl9IChwb2x5bGluZSkpOwoKCXZhciBwb2x5bGluZUV4cG9ydHMgPSBwb2x5bGluZS5leHBvcnRzOwoKCXZhciB1dGlscyA9ICgoKSA9PiB7CgoJICAgIGNvbnN0IHB1cmdlUHJvcHMgPSAob2JqLCBibGFja2xpc3QpID0+IHsKCSAgICAgICAgaWYgKG9iaikgewoJICAgICAgICAgICAgbGV0IHJzID0gT2JqZWN0LmFzc2lnbih7fSwgb2JqKTsKCSAgICAgICAgICAgIGlmIChibGFja2xpc3QpIHsKCSAgICAgICAgICAgICAgICBmb3IgKGxldCBwcm9wIG9mIGJsYWNrbGlzdCkgewoJICAgICAgICAgICAgICAgICAgICBkZWxldGUgcnNbcHJvcF07CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmV0dXJuIHJzOwoJICAgICAgICB9CgkgICAgICAgIHJldHVybiB7fTsKCSAgICB9OwoKCSAgICBjb25zdCBtZXJnZVByb3BzID0gKG9iajEsIG9iajIpID0+IHsKCSAgICAgICAgb2JqMSA9IG9iajEgPyBvYmoxIDoge307CgkgICAgICAgIG9iajIg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gewoJICAgICAgICAgICAgc3VwZXIoKTsKCSAgICAgICAgICAgIHRoaXMuYmluZGVycyA9IFtdOwoJICAgICAgICB9CgoJICAgICAgICBhZGQoaywgdikgewoJICAgICAgICAgICAgaWYgKCF0aGlzLmhhcyhrKSkgewoJICAgICAgICAgICAgICAgIHRoaXMuc2V0KGssIHYpOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgLy8gc3VwcHJlc3MgZHVwbGNhdGVkIGtleSBlcnJvcgoJICAgICAgICAgICAgLy8gZWxzZQoJICAgICAgICAgICAgLy8gdGhyb3cgYEVycm9yOiBhZGRpbmcgZHVwbGljYXRlZCBrZXkgJyR7a30nIHRvIFJlZkVsZW1lbnRzYDsKCSAgICAgICAgfQoKCSAgICAgICAgYWRkQmluZGVyKGJpbmRlcikgewoJICAgICAgICAgICAgdGhpcy5iaW5kZXJzLnB1c2goYmluZGVyKTsKCSAgICAgICAgfQoKCSAgICAgICAgYmluZEFsbCgpIHsKCSAgICAgICAgICAgIHRoaXMuYmluZGVycy5mb3JFYWNoKGJpbmRlciA9PiBiaW5kZXIuYmluZCgpKTsKCSAgICAgICAgfQoJICAgIH0KCgkgICAgY2xhc3MgTGF0ZUJpbmRlciB7CgkgICAgICAgIGNvbnN0cnVjdG9yKGNvbnRhaW5lciwgdmFsdWVGdW5jLCBjdHgsIGFyZ3MpIHsKCSAgICAgICAgICAgIHRoaXMuY29udGFpbmVyID0gY29udGFpbmVyOwoJICAgICAgICAgICAgdGhpcy52YWx1ZUZ1bmMgPSB2YWx1ZUZ1bmM7CgkgICAgICAgICAgICB0aGlzLmN0eCA9IGN0eDsKCSAgICAgICAgICAgIHRoaXMuYXJncyA9IGFyZ3M7CgkgICAgICAgIH0KCgkgICAgICAgIGJpbmQoKSB7CgkgICAgICAgICAgICBsZXQgdiA9IHRoaXMudmFsdWVGdW5jLmFwcGx5KHRoaXMuY3R4LCB0aGlzLmFyZ3MpOwoJICAgICAgICAgICAgaWYgKHRoaXMuY29udGFpbmVyIGluc3RhbmNlb2YgQXJyYXkpIHsKCSAgICAgICAgICAgICAgICBsZXQgaWR4ID0gdGhpcy5jb250YWluZXIuaW5kZXhPZih0aGlzKTsKCSAgICAgICAgICAgICAgICBpZiAoaWR4ID49IDApIHsKCSAgICAgICAgICAgICAgICAgICAgbGV0IGFyZ3MgPSBbaWR4LCAxXTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKHYpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGFyZ3MucHVzaCh2KTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICBbXS5zcGxpY2UuYXBwbHkodGhpcy5jb250YWluZXIsIGFyZ3MpOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0gZWxzZSBpZiAodHlwZW9mIHRoaXMuY29udGFpbmVyID09PSAnb2JqZWN0JykgewoJICAgICAgICAgICAgICAgIGxldCBrID0gT2JqZWN0LmtleXModGhpcy5jb250YWluZXIpLmZpbmQodiA9PiB0aGlzLmNvbnRhaW5lclt2XSA9PT0gdGhpcyk7CgkgICAgICAgICAgICAgICAgaWYgKGspIHsKCSAgICAgICAgICAgICAgICAgICAgaWYgKHYpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHRoaXMuY29udGFpbmVyW2tdID0gdjsKCSAgICAgICAgICAgICAgICAgICAgfSBlbHNlIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGRlbGV0ZSB0aGlzLmNvbnRhaW5lcltrXTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgfQoJICAgIH0KCgkgICAgY2xhc3MgV2F5Q29sbGVjdGlvbiBleHRlbmRzIEFycmF5IHsKCSAgICAgICAgY29uc3RydWN0b3IoKSB7CgkgICAgICAgICAgICBzdXBlcigpOwoJICAgICAgICAgICAgdGhpcy5maXJzdE1hcCA9IHt9OwoJICAgICAgICAgICAgdGhpcy5sYXN0TWFwID0ge307CgkgICAgICAgIH0KCgkgICAgICAgIGFkZFdheSh3YXkpIHsKCSAgICAgICAgICAgIHdheSA9IHdheS50b0Nvb3Jkc0FycmF5KCk7CgkgICAgICAgICAgICBpZiAod2F5Lmxlbmd0aCA+IDApIHsKCSAgICAgICAgICAgICAgICB0aGlzLnB1c2god2F5KTsKCSAgICAgICAgICAgICAgICBhZGRUb01hcCh0aGlzLmZpcnN0TWFwLCBjb29yZHNUb0tleShmaXJzdCh3YXkpKSwgd2F5KTsKCSAgICAgICAgICAgICAgICBhZGRUb01hcCh0aGlzLmxhc3RNYXAsIGNvb3Jkc1RvS2V5KGxhc3Qod2F5KSksIHdheSk7CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCgkgICAgICAgIHRvU3RyaW5ncygpIHsKCSAgICAgICAgICAgIGxldCBzdHJpbmdzID0gW10sIHdheSA9IG51bGw7CgkgICAgICAgICAgICB3aGlsZSAod2F5ID0gdGhpcy5zaGlmdCgpKSB7CgkgICAgICAgICAgICAgICAgcmVtb3ZlRnJvbU1hcCh0aGlzLmZpcnN0TWFwLCBjb29yZHNUb0tleShmaXJzdCh3YXkpKSwgd2F5KTsKCSAgICAgICAgICAgICAgICByZW1vdmVGcm9tTWFwKHRoaXMubGFzdE1hcCwgY29vcmRzVG9LZXkobGFzdCh3YXkpKSwgd2F5KTsKCSAgICAgICAgICAgICAgICBsZXQgY3VycmVudCA9IHdheSwgbmV4dCA9IG51bGw7CgkgICAgICAgICAgICAgICAgZG8gewoJICAgICAgICAgICAgICAgICAgICBsZXQga2V5ID0gY29vcmRzVG9LZXkobGFzdChjdXJyZW50KSksIHNob3VsZFJldmVyc2UgPSBmYWxzZTsKCgkgICAgICAgICAgICAgICAgICAgIG5leHQgPSBnZXRGaXJzdEZyb21NYXAodGhpcy5maXJzdE1hcCwga2V5KTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKCFuZXh0KSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBuZXh0ID0gZ2V0Rmlyc3RGcm9tTWFwKHRoaXMubGFzdE1hcCwga2V5KTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHNob3VsZFJldmVyc2UgPSB0cnVlOwoJICAgICAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgICAgICBpZiAobmV4dCkgewoJICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5zcGxpY2UodGhpcy5pbmRleE9mKG5leHQpLCAxKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHJlbW92ZUZyb21NYXAodGhpcy5maXJzdE1hcCwgY29vcmRzVG9LZXkoZmlyc3QobmV4dCkpLCBuZXh0KTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHJlbW92ZUZyb21NYXAodGhpcy5sYXN0TWFwLCBjb29yZHNUb0tleShsYXN0KG5leHQpKSwgbmV4dCk7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAoc2hvdWxkUmV2ZXJzZSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIC8vIGFsd2F5cyByZXZlcnNlIHNob3J0ZXIgb25lIHRvIHNhdmUgdGltZQoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGlmIChuZXh0Lmxlbmd0aCA+IGN1cnJlbnQubGVuZ3RoKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFtjdXJyZW50LCBuZXh0XSA9IFtuZXh0LCBjdXJyZW50XTsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgbmV4dC5yZXZlcnNlKCk7CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgICAgICAgICAgY3VycmVudCA9IGN1cnJlbnQuY29uY2F0KG5leHQuc2xpY2UoMSkpOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfSB3aGlsZSAobmV4dCk7CgkgICAgICAgICAgICAgICAgc3RyaW5ncy5wdXNoKHN0clRvRmxvYXQoY3VycmVudCkpOwoJICAgICAgICAgICAgfQoKCSAgICAgICAgICAgIHJldHVybiBzdHJpbmdzOwoJICAgICAgICB9CgoJICAgICAgICB0b1JpbmdzKGRpcmVjdGlvbikgewoJICAgICAgICAgICAgbGV0IHN0cmluZ3MgPSB0aGlzLnRvU3RyaW5ncygpOwoJICAgICAgICAgICAgbGV0IHJpbmdzID0gW10sIHN0cmluZyA9IG51bGw7CgkgICAgICAgICAgICB3aGlsZSAoc3RyaW5nID0gc3RyaW5ncy5zaGlmdCgpKSB7CgkgICAgICAgICAgICAgICAgaWYgKGlzUmluZyhzdHJpbmcpKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmIChyaW5nRGlyZWN0aW9uKHN0cmluZykgIT09IGRpcmVjdGlvbikgewoJICAgICAgICAgICAgICAgICAgICAgICAgc3RyaW5nLnJldmVyc2UoKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICByaW5ncy5wdXNoKHN0cmluZyk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmV0dXJuIHJpbmdzOwoJICAgICAgICB9CgkgICAgfQoKCSAgICByZXR1cm4gewoJICAgICAgICBwdXJnZVByb3BzLCBtZXJnZVByb3BzLAoJICAgICAgICBmaXJzdCwgbGFzdCwgY29vcmRzVG9LZXksCgkgICAgICAgIGFkZFRvTWFwLCByZW1vdmVGcm9tTWFwLCBnZXRGaXJzdEZyb21NYXAsCgkgICAgICAgIGlzUmluZywgcmluZ0RpcmVjdGlvbiwgcHRJbnNpZGVQb2x5Z29uLCBzdHJUb0Zsb2F0LAoJICAgICAgICBSZWZFbGVtZW50cywgTGF0ZUJpbmRlciwgV2F5Q29sbGVjdGlvbgoJICAgIH07Cgl9KSgpOwoKCXZhciBidWlsZGluZyA9IHsKCX07Cgl2YXIgaGlnaHdheSA9IHsKCQl3aGl0ZWxpc3Q6IFsKCQkJInNlcnZpY2VzIiwKCQkJInJlc3R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yhrLCB2KSB7CgkgICAgICAgICAgICB0aGlzLnRhZ3Nba10gPSB2OwoJICAgICAgICAgICAgdGhpcy5oYXNUYWcgPSBrID8gdHJ1ZSA6IGZhbHNlOwoJICAgICAgICB9CgoJICAgICAgICBhZGRQcm9wKGssIHYpIHsKCSAgICAgICAgICAgIHRoaXMucHJvcHNba10gPSB2OwoJICAgICAgICB9CgoJICAgICAgICBhZGRQcm9wcyhwcm9wcykgewoJICAgICAgICAgICAgdGhpcy5wcm9wcyA9IE9iamVjdC5hc3NpZ24odGhpcy5wcm9wcywgcHJvcHMpOwoJICAgICAgICB9CgoJICAgICAgICBnZXRDb21wb3NpdGVJZCgpIHsKCSAgICAgICAgICAgIHJldHVybiBgJHt0aGlzLnR5cGV9LyR7dGhpcy5pZH1gOwoJICAgICAgICB9CgoJICAgICAgICBnZXRQcm9wcygpIHsKCSAgICAgICAgICAgIHJldHVybiBPYmplY3QuYXNzaWduKHRoaXMucHJvcHMsIHRoaXMudGFncyk7CgkgICAgICAgIH0KCgkgICAgICAgIHRvRmVhdHVyZUFycmF5KCkgewoJICAgICAgICAgICAgcmV0dXJuIFtdOwoJICAgICAgICB9CgkgICAgfQoKCSAgICBjbGFzcyBOb2RlIGV4dGVuZHMgT3NtT2JqZWN0IHsKCSAgICAgICAgY29uc3RydWN0b3IoaWQsIHJlZkVsZW1zKSB7CgkgICAgICAgICAgICBzdXBlcignbm9kZScsIGlkLCByZWZFbGVtcyk7CgkgICAgICAgICAgICB0aGlzLmxhdExuZyA9IG51bGw7CgkgICAgICAgIH0KCgkgICAgICAgIHNldExhdExuZyhsYXRMbmcpIHsKCSAgICAgICAgICAgIHRoaXMubGF0TG5nID0gbGF0TG5nOwoJICAgICAgICB9CgoJICAgICAgICB0b0ZlYXR1cmVBcnJheSgpIHsKCSAgICAgICAgICAgIGlmICh0aGlzLmxhdExuZykgewoJICAgICAgICAgICAgICAgIHJldHVybiBbewoJICAgICAgICAgICAgICAgICAgICB0eXBlOiAnRmVhdHVyZScsCgkgICAgICAgICAgICAgICAgICAgIGlkOiB0aGlzLmdldENvbXBvc2l0ZUlkKCksCgkgICAgICAgICAgICAgICAgICAgIHByb3BlcnRpZXM6IHRoaXMuZ2V0UHJvcHMoKSwKCSAgICAgICAgICAgICAgICAgICAgZ2VvbWV0cnk6IHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICdQb2ludCcsCgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogc3RyVG9GbG9hdChbdGhpcy5sYXRMbmcubG9uLCB0aGlzLmxhdExuZy5sYXRdKQoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfV07CgkgICAgICAgICAgICB9CgoJICAgICAgICAgICAgcmV0dXJuIFtdOwoJICAgICAgICB9CgoJICAgICAgICBnZXRMYXRMbmcoKSB7CgkgICAgICAgICAgICByZXR1cm4gdGhpcy5sYXRMbmc7CgkgICAgICAgIH0KCSAgICB9CgoJICAgIGNsYXNzIFdheSBleHRlbmRzIE9zbU9iamVjdCB7CgkgICAgICAgIGNvbnN0cnVjdG9yKGlkLCByZWZFbGVtcykgewoJICAgICAgICAgICAgc3VwZXIoJ3dheScsIGlkLCByZWZFbGVtcyk7CgkgICAgICAgICAgICB0aGlzLmxhdExuZ0FycmF5ID0gW107CgkgICAgICAgICAgICB0aGlzLmlzUG9seWdvbiA9IGZhbHNlOwoJICAgICAgICB9CgoJICAgICAgICBhZGRMYXRMbmcobGF0TG5nKSB7CgkgICAgICAgICAgICB0aGlzLmxhdExuZ0FycmF5LnB1c2gobGF0TG5nKTsKCSAgICAgICAgfQoKCSAgICAgICAgc2V0TGF0TG5nQXJyYXkobGF0TG5nQXJyYXkpIHsKCSAgICAgICAgICAgIHRoaXMubGF0TG5nQXJyYXkgPSBsYXRMbmdBcnJheTsKCSAgICAgICAgfQoKCSAgICAgICAgYWRkTm9kZVJlZihyZWYpIHsKCSAgICAgICAgICAgIGxldCBiaW5kZXIgPSBuZXcgTGF0ZUJpbmRlcih0aGlzLmxhdExuZ0FycmF5LCBmdW5jdGlvbiAoaWQpIHsKCSAgICAgICAgICAgICAgICBsZXQgbm9kZSA9IHRoaXMucmVmRWxlbXMuZ2V0KGBub2RlLyR7aWR9YCk7CgkgICAgICAgICAgICAgICAgaWYgKG5vZGUpIHsKCSAgICAgICAgICAgICAgICAgICAgbm9kZS5yZWZDb3VudCsrOwoJICAgICAgICAgICAgICAgICAgICByZXR1cm4gbm9kZS5nZXRMYXRMbmcoKTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9LCB0aGlzLCBbcmVmXSk7CgoJICAgICAgICAgICAgdGhpcy5sYXRMbmdBcnJheS5wdXNoKGJpbmRlcik7CgkgICAgICAgICAgICB0aGlzLnJlZkVsZW1zLmFkZEJpbmRlcihiaW5kZXIpOwoJICAgICAgICB9CgoJICAgICAgICBhbmFseXplR2VvbWV0cnlUeXBlKGssIHYpIHsKCSAgICAgICAgICAgIGxldCBvID0gcG9seWdvblRhZ3Nba107CgkgICAgICAgICAgICBpZiAobykgewoJICAgICAgICAgICAgICAgIHRoaXMuaXNQb2x5Z29uID0gdHJ1ZTsKCSAgICAgICAgICAgICAgICBpZiAoby53aGl0ZWxpc3QpIHsKCSAgICAgICAgICAgICAgICAgICAgdGhpcy5pc1BvbHlnb24gPSBvLndoaXRlbGlzdC5pbmRleE9mKHYpID49IDAgPyB0cnVlIDogZmFsc2U7CgkgICAgICAgICAgICAgICAgfSBlbHNlIGlmIChvLmJsYWNrbGlzdCkgewoJICAgICAgICAgICAgICAgICAgICB0aGlzLmlzUG9seWdvbiA9IG8uYmxhY2tsaXN0LmluZGV4T2YodikgPj0gMCA/IGZhbHNlIDogdHJ1ZTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCgkgICAgICAgIGFkZFRhZ3ModGFncykgewoJICAgICAgICAgICAgc3VwZXIuYWRkVGFncyh0YWdzKTsKCSAgICAgICAgICAgIGZvciAobGV0IFtrLCB2XSBvZiBPYmplY3QuZW50cmllcyh0YWdzKSkgewoJICAgICAgICAgICAgICAgIHRoaXMuYW5hbHl6ZUdlb21ldHJ5VHlwZShrLCB2KTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgfQoKCSAgICAgICAgYWRkVGFnKGssIHYpIHsKCSAgICAgICAgICAgIHN1cGVyLmFkZFRhZyhrLCB2KTsKCSAgICAgICAgICAgIHRoaXMuYW5hbHl6ZUdlb21ldHJ5VHlwZShrLCB2KTsKCSAgICAgICAgfQoKCSAgICAgICAgdG9Db29yZHNBcnJheSgpIHsKCSAgICAgICAgICAgIHJldHVybiB0aGlzLmxhdExuZ0FycmF5Lm1hcChsYXRMbmcgPT4gW2xhdExuZy5sb24sIGxhdExuZy5sYXRdKTsKCSAgICAgICAgfQoKCSAgICAgICAgdG9GZWF0dXJlQXJyYXkoKSB7CgkgICAgICAgICAgICBsZXQgY29vcmRzQXJyYXkgPSB0aGlzLnRvQ29vcmRzQXJyYXkoKTsKCSAgICAgICAgICAgIGlmIChjb29yZHNBcnJheS5sZW5ndGggPiAxKSB7CgkgICAgICAgICAgICAgICAgY29vcmRzQXJyYXkgPSBzdHJUb0Zsb2F0KGNvb3Jkc0FycmF5KTsKCSAgICAgICAgICAgICAgICBsZXQgZmVhdHVyZSA9IHsKCSAgICAgICAgICAgICAgICAgICAgdHlwZTogJ0ZlYXR1cmUnLAoJICAgICAgICAgICAgICAgICAgICBpZDogdGhpcy5nZXRDb21wb3NpdGVJZCgpLAoJICAgICAgICAgICAgICAgICAgICBwcm9wZXJ0aWVzOiB0aGlzLmdldFByb3BzKCksCgkgICAgICAgICAgICAgICAgICAgIGdlb21ldHJ5OiB7CgkgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAnTGluZVN0cmluZycsCgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogY29vcmRzQXJyYXkKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH07CgoJICAgICAgICAgICAgICAgIGlmICh0aGlzLmlzUG9seWdvbiAmJiBpc1JpbmcoY29vcmRzQXJyYXkpKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmIChyaW5nRGlyZWN0aW9uKGNvb3Jkc0FycmF5KSAhPT0gJ2NvdW50ZXJjbG9ja3dpc2UnKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZHNBcnJheS5yZXZlcnNlKCk7CgkgICAgICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgICAgIGZlYXR1cmUuZ2VvbWV0cnkgPSB7CgkgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAnUG9seWdvbicsCgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogW2Nvb3Jkc0FycmF5XQoJICAgICAgICAgICAgICAgICAgICB9OwoKCSAgICAgICAgICAgICAgICAgICAgcmV0dXJuIFtmZWF0dXJlXTsKCSAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIHJldHVybiBbZmVhdHVyZV07CgkgICAgICAgICAgICB9CgoJICAgICAgICAgICAgcmV0dXJuIFtdOwoJICAgICAgICB9CgkgICAgfQoKCSAgICBjbGFzcyBSZWxhdGlvbiBleHRlbmRzIE9zbU9iamVjdCB7CgkgICAgICAgIGNvbnN0cnVjdG9yKGlkLCByZWZFbGVtcykgewoJICAgICAgICAgICAgc3VwZXIoJ3JlbGF0aW9uJywgaWQsIHJlZkVsZW1zKTsKCSAgICAgICAgICAgIHRoaXMucmVsYXRpb25zID0gW107CgkgICAgICAgICAgICB0aGlzLm5vZGVzID0gW107CgkgICAgICAgICAgICB0aGlzLmJvdW5kcyA9IG51bGw7CgkgICAgICAgIH0KCgkgICAgICAgIHNldEJvdW5kcyhib3VuZHMpIHsKCSAgICAgICAgICAgIHRoaXMuYm91bmRzID0gYm91bmRzOwoJICAgICAgICB9CgoJICAgICAgICBhZGRNZW1iZXIobWVtYmVyKSB7CgkgICAgICAgICAgICBzd2l0Y2ggKG1lbWJlci50eXBlKSB7CgkgICAgICAgICAgICAgICAgLy8gc3VwZXIgcmVsYXRpb24sIG5lZWQgdG8gZG8gY29tYmluYXRpb24KCSAgICAgICAgICAgICAgICBjYXNlICdyZWxhdGlvbic6CgkgICAgICAgICAgICAgICAgICAgIGxldCBiaW5kZXIgPSBuZXcgTGF0ZUJpbmRlcih0aGlzLnJlbGF0aW9ucywgZnVuY3Rpb24gKGlkKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBsZXQgcmVsYXRpb24gPSB0aGlzLnJlZkVsZW1zLmdldChgcmVsYXRpb24vJHtpZH1gKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIGlmIChyZWxhdGlvbikgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJlbGF0aW9uLnJlZkNvdW50Kys7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHJlbGF0aW9uOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB9LCB0aGlzLCBbbWVtYmVyLnJlZl0pOwoJICAgICAgICAgICAgICAgICAgICB0aGlzLnJlbGF0aW9ucy5wdXNoKGJpbmRlcik7CgkgICAgICAgICAgICAgICAgICAgIHRoaXMucmVmRWxlbXMuYWRkQmluZGVyKGJpbmRlcik7CgkgICAgICAgICAgICAgICAgICAgIGJyZWFrOwoKCSAgICAgICAgICAgICAgICBjYXNlICd3YXknOgoJICAgICAgICAgICAgICAgICAgICBpZiAoIW1lbWJlci5yb2xlKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBtZW1iZXIucm9sZSA9ICcnOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGxldCB3YXlzID0gdGhpc1ttZW1iZXIucm9sZV07CgkgICAgICAgICAgICAgICAgICAgIGlmICghd2F5cykgewoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5cyA9IHRoaXNbbWVtYmVyLnJvbGVdID0gW107CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgaWYgKG1lbWJlci5nZW9tZXRyeSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgbGV0IHdheSA9IG5ldyBXYXkobWVtYmVyLnJlZiwgdGhpcy5yZWZFbGVtcyk7CgkgICAgICAgICAgICAgICAgICAgICAgICB3YXkuc2V0TGF0TG5nQXJyYXkobWVtYmVyLmdlb21ldHJ5KTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHdheS5yZWZDb3VudCsrOwoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5cy5wdXNoKHdheSk7CgkgICAgICAgICAgICAgICAgICAgIH0gZWxzZSBpZiAobWVtYmVyLm5vZGVzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBsZXQgd2F5ID0gbmV3IFdheShtZW1iZXIucmVmLCB0aGlzLnJlZkVsZW1zKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIGZvciAobGV0IG5pZCBvZiBtZW1iZXIubm9kZXMpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB3YXkuYWRkTm9kZVJlZihuaWQpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5LnJlZkNvdW50Kys7CgkgICAgICAgICAgICAgICAgICAgICAgICB3YXlzLnB1c2god2F5KTsKCSAgICAgICAgICAgICAgICAgICAgfSBlbHNlIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGxldCBiaW5kZXIgPSBuZXcgTGF0ZUJpbmRlcih3YXlzLCBmdW5jdGlvbiAoaWQpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBsZXQgd2F5ID0gdGhpcy5yZWZFbGVtcy5nZXQoYHdheS8ke2lkfWApOwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGlmICh3YXkpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgd2F5LnJlZkNvdW50Kys7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiB3YXk7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICAgICAgfSwgdGhpcywgW21lbWJlci5yZWZdKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHdheXMucHVzaChiaW5kZXIpOwoJICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5yZWZFbGVtcy5hZGRCaW5kZXIoYmluZGVyKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICBicmVhazsKCgkgICAgICAgICAgICAgICAgY2FzZSAnbm9kZSc6CgkgICAgICAgICAgICAgICAgICAgIGxldCBub2RlID0gbnVsbDsKCSAgICAgICAgICAgICAgICAgICAgaWYgKG1lbWJlci5sYXQgJiYgbWVtYmVyLmxvbikgewoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZSA9IG5ldyBOb2RlKG1lbWJlci5yZWYsIHRoaXMucmVmRWxlbXMpOwoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS5zZXRMYXRMbmcoeyBsb246IG1lbWJlci5sb24sIGxhdDogbWVtYmVyLmxhdCB9KTsKCSAgICAgICAgICAgICAgICAgICAgICAgIGlmIChtZW1iZXIudGFncykgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIG5vZGUuYWRkVGFncyhtZW1iZXIudGFncyk7CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgICAgICBmb3IgKGxldCBbaywgdl0gb2YgT2JqZWN0LmVudHJpZXMobWVtYmVyKSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGlmIChbJ2lkJywgJ3R5cGUnLCAnbGF0JywgJ2xvbiddLmluZGV4T2YoaykgPCAwKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIG5vZGUuYWRkUHJvcChrLCB2KTsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS5yZWZDb3VudCsrOwoJICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5ub2Rlcy5wdXNoKG5vZGUpOwoJICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgbGV0IGJpbmRlciA9IG5ldyBMYXRlQmluZGVyKHRoaXMubm9kZXMsIGZ1bmN0aW9uIChpZCkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGxldCBub2RlID0gdGhpcy5yZWZFbGVtcy5nZXQoYG5vZGUvJHtpZH1gKTsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBpZiAobm9kZSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBub2RlLnJlZkNvdW50Kys7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiBub2RlOwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgICAgIH0sIHRoaXMsIFttZW1iZXIucmVmXSk7CgkgICAgICAgICAgICAgICAgICAgICAgICB0aGlzLm5vZGVzLnB1c2goYmluZGVyKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHRoaXMucmVmRWxlbXMuYWRkQmluZGVyKGJpbmRlcik7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCgkgICAgICAgIHRvRmVhdHVyZUFycmF5KCkgewoJICAgICAgICAgICAgY29uc3QgY29uc3RydWN0U3RyaW5nR2VvbWV0cnkgPSAod3MpID0+IHsKCSAgICAgICAgICAgICAgICBsZXQgc3RyaW5ncyA9IHdzID8gd3MudG9TdHJpbmdzKCkgOiBbXTsKCSAgICAgICAgICAgICAgICBpZiAoc3RyaW5ncy5sZW5ndGggPiAwKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmIChzdHJpbmdzLmxlbmd0aCA9PT0gMSkgcmV0dXJuIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICdMaW5lU3RyaW5nJywKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBzdHJpbmdzWzBdCgkgICAgICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgICAgIHJldHVybiB7CgkgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAnTXVsdGlMaW5lU3RyaW5nJywKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBzdHJpbmdzCgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgcmV0dXJuIG51bGw7CgkgICAgICAgICAgICB9OwoKCSAgICAgICAgICAgIGNvbnN0IGNvbnN0cnVjdFBvbHlnb25HZW9tZXRyeSA9IChvd3MsIGl3cykgPT4gewoJICAgICAgICAgICAgICAgIGxldCBvdXRlclJpbmdzID0gb3dzID8gb3dzLnRvUmluZ3MoJ2NvdW50ZXJjbG9ja3dpc2UnKSA6IFtdLAoJICAgICAgICAgICAgICAgICAgICBpbm5lclJpbmdzID0gaXdzID8gaXdzLnRvUmluZ3MoJ2Nsb2Nrd2lzZScpIDogW107CgoJICAgICAgICAgICAgICAgIGlmIChvdXRlclJpbmdzLmxlbmd0aCA+IDApIHsKCSAgICAgICAgICAgICAgICAgICAgbGV0IGNvbXBvc2l0UG9seW9ucyA9IFtdOwoKCSAgICAgICAgICAgICAgICAgICAgbGV0IHJpbmcgPSBudWxsOwoJICAgICAgICAgICAgICAgICAgICBmb3IgKHJpbmcgb2Ygb3V0ZXJSaW5ncykKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvbXBvc2l0UG9seW9ucy5wdXNoKFtyaW5nXSk7CgoJICAgICAgICAgICAgICAgICAgICAvLyBsaW5rIGlubmVyIHBvbHlnb25zIHRvIG91dGVyIGNvbnRhaW5lcnMKCSAgICAgICAgICAgICAgICAgICAgd2hpbGUgKHJpbmcgPSBpbm5lclJpbmdzLnNoaWZ0KCkpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGZvciAobGV0IGlkeCBpbiBvdXRlclJpbmdzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgaWYgKHB0SW5zaWRlUG9seWdvbihmaXJzdChyaW5nKSwgb3V0ZXJSaW5nc1tpZHhdKSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb21wb3NpdFBvbHlvbnNbaWR4XS5wdXNoKHJpbmcpOwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgICAgIC8vIGNvbnN0cnVjdCB0aGUgUG9seWdvbi9NdWx0aVBvbHlnb24gZ2VvbWV0cnkKCSAgICAgICAgICAgICAgICAgICAgaWYgKGNvbXBvc2l0UG9seW9ucy5sZW5ndGggPT09IDEpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgdHlwZTogJ1BvbHlnb24nLAoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBjb21wb3NpdFBvbHlvbnNbMF0KCSAgICAgICAgICAgICAgICAgICAgICAgIH07CgkgICAgICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgICAgIHJldHVybiB7CgkgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAnTXVsdGlQb2x5Z29uJywKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBjb21wb3NpdFBvbHlvbnMKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgcmV0dXJuIG51bGw7CgkgICAgICAgICAgICB9OwoKCSAgICAgICAgICAgIGxldCBwb2x5Z29uRmVhdHVyZXMgPSBbXSwgc3RyaW5nRmVhdHVyZXMgPSBbXSwgcG9pbnRGZWF0dXJlcyA9IFtdOwoJICAgICAgICAgICAgY29uc3Qgd2F5c0ZpZWxkTmFtZXMgPSBbJ291dGVyJywgJ2lubmVyJywgJyddOwoJICAgICAgICAgICAgLy8gbmVlZCB0byBkbyBjb21iaW5hdGlvbiB3aGVuIHRoZXJlJ3JlIG5lc3RlZCByZWxhdGlvbnMKCSAgICAgICAgICAgIGZvciAobGV0IHJlbGF0aW9uIG9mIHRoaXMucmVsYXRpb25zKSB7CgkgICAgICAgICAgICAgICAgaWYgKHJlbGF0aW9uKSB7CgkgICAgICAgICAgICAgICAgICAgIGZvciAobGV0IGZpZWxkTmFtZSBvZiB3YXlzRmllbGROYW1lcykgewoJICAgICAgICAgICAgICAgICAgICAgICAgbGV0IHdheXMgPSByZWxhdGlvbltmaWVsZE5hbWVdOwoJICAgICAgICAgICAgICAgICAgICAgICAgaWYgKHdheXMpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBsZXQgdGhpc1dheXMgPSB0aGlzW2ZpZWxkTmFtZV07CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgaWYgKHRoaXNXYXlzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFtdLnNwbGljZS5hcHBseSh0aGlzV2F5cywgW3RoaXNXYXlzLmxlbmd0aCwgMF0uY29uY2F0KHdheXMpKTsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB0aGlzW2ZpZWxkTmFtZV0gPSB3YXlzOwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCgkgICAgICAgICAgICBmb3IgKGxldCBmaWVsZE5hbWUgb2Ygd2F5c0ZpZWxkTmFtZXMpIHsKCSAgICAgICAgICAgICAgICBsZXQgd2F5cyA9IHRoaXNbZmllbGROYW1lXTsKCSAgICAgICAgICAgICAgICBpZiAod2F5cykgewoJICAgICAgICAgICAgICAgICAgICB0aGlzW2ZpZWxkTmFtZV0gPSBuZXcgV2F5Q29sbGVjdGlvbigpOwoJICAgICAgICAgICAgICAgICAgICBmb3IgKGxldCB3YXkgb2Ygd2F5cykgewoJICAgICAgICAgICAgICAgICAgICAgICAgdGhpc1tmaWVsZE5hbWVdLmFkZFdheSh3YXkpOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoKCSAgICAgICAgICAgIGxldCBnZW9tZXRyeSA9IG51bGw7CgoJICAgICAgICAgICAgbGV0IGZlYXR1cmUgPSB7CgkgICAgICAgICAgICAgICAgdHlwZTogJ0ZlYXR1cmUnLAoJICAgICAgICAgICAgICAgIGlkOiB0aGlzLmdldENvbXBvc2l0ZUlkKCksCgkgICAgICAgICAgICAgICAgYmJveDogdGhpcy5ib3VuZHMsCgkgICAgICAgICAgICAgICAgcHJvcGVydGllczogdGhpcy5nZXRQcm9wcygpCgkgICAgICAgICAgICB9OwoKCSAgICAgICAgICAgIGlmICghdGhpcy5ib3VuZHMpIHsKCSAgICAgICAgICAgICAgICBkZWxldGUgZmVhdHVyZS5iYm94OwoJICAgICAgICAgICAgfQoKCSAgICAgICAgICAgIGlmICh0aGlzLm91dGVyKSB7CgkgICAgICAgICAgICAgICAgZ2VvbWV0cnkgPSBjb25zdHJ1Y3RQb2x5Z29uR2VvbWV0cnkodGhpcy5vdXRlciwgdGhpcy5pbm5lcik7CgkgICAgICAgICAgICAgICAgaWYgKGdlb21ldHJ5KSB7CgkgICAgICAgICAgICAgICAgICAgIGZlYXR1cmUuZ2VvbWV0cnkgPSBnZW9tZXRyeTsKCSAgICAgICAgICAgICAgICAgICAgcG9seWdvbkZlYXR1cmVzLnB1c2goZmVhdHVyZSk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgZWxzZSBpZiAodGhpc1snJ10pIHsKCSAgICAgICAgICAgICAgICBnZW9tZXRyeSA9IGNvbnN0cnVjdFN0cmluZ0dlb21ldHJ5KHRoaXNbJyddKTsKCSAgICAgICAgICAgICAgICBpZiAoZ2VvbWV0cnkpIHsKCSAgICAgICAgICAgICAgICAgICAgZmVhdHVyZS5nZW9tZXRyeSA9IGdlb21ldHJ5OwoJICAgICAgICAgICAgICAgICAgICBzdHJpbmdGZWF0dXJlcy5wdXNoKGZlYXR1cmUpOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCgkgICAgICAgICAgICBmb3IgKGxldCBub2RlIG9mIHRoaXMubm9kZXMpIHsKCSAgICAgICAgICAgICAgICBwb2ludEZlYXR1cmVzID0gcG9pbnRGZWF0dXJlcy5jb25jYXQobm9kZS50b0ZlYXR1cmVBcnJheSgpKTsKCSAgICAgICAgICAgIH0KCgkgICAgICAgICAgICByZXR1cm4gcG9seWdvbkZlYXR1cmVzLmNvbmNhdChzdHJpbmdGZWF0dXJlcykuY29uY2F0KHBvaW50RmVhdHVyZXMpOwoJICAgICAgICB9CgkgICAgfQoKCSAgICByZXR1cm4geyBOb2RlLCBXYXksIFJlbGF0aW9uIH07Cgl9KSgpOwoKCXZhciB4bWxwYXJzZXIgPSAoKCkgPT4gewoKCSAgICBmdW5jdGlvbiBjb25kaXRpb25lZChldnQpIHsKCSAgICAgICAgcmV0dXJuIGV2dC5tYXRjaCgvXiguKz8pXFsoLis/KVxdPiQvZykgIT0gbnVsbDsKCSAgICB9CgoJICAgIGZ1bmN0aW9uIHBhcnNlRXZlbnQoZXZ0KSB7CgkgICAgICAgIGxldCBtYXRjaCA9IC9eKC4rPylcWyguKz8pXF0+JC9nLmV4ZWMoZXZ0KTsKCSAgICAgICAgaWYgKG1hdGNoKSB7CgkgICAgICAgICAgICByZXR1cm4geyBldnQ6IG1hdGNoWzFdICsgJz4nLCBleHA6IG1hdGNoWzJdIH07CgkgICAgICAgIH0KCSAgICAgICAgcmV0dXJuIHsgZXZ0OiBldnQgfTsKCSAgICB9CgoJICAgIGZ1bmN0aW9uIGdlbkNvbmRpdGlvbkZ1bmMoY29uZCkgewoJICAgICAgICBsZXQgYm9keSA9ICdyZXR1cm4gJyArIGNvbmQucmVwbGFjZSgvKFwkLis/KSg/PVs9IS5dKS9nLCAnbm9kZS4kJicpICsgJzsnOwoJICAgICAgICByZXR1cm4gbmV3IEZ1bmN0aW9uKCdub2RlJywgYm9keSk7CgkgICAgfQoKCSAgICByZXR1cm4gY2xhc3MgewoJICAgICAgICBjb25zdHJ1Y3RvcihvcHRzKSB7CgkgICAgICAgICAgICBpZiAob3B0cykgewoJICAgICAgICAgICAgICAgIHRoaXMucXVlcnlQYXJlbnQgPSBvcHRzLnF1ZXJ5UGFyZW50ID8gdHJ1ZSA6IGZhbHNlOwoJICAgICAgICAgICAgICAgIHRoaXMucHJvZ3Jlc3NpdmUgPSBvcHRzLnByb2dyZXNzaXZlOwoJICAgICAgICAgICAgICAgIGlmICh0aGlzLnF1ZXJ5UGFyZW50KSB7CgkgICAgICAgICAgICAgICAgICAgIHRoaXMucGFyZW50TWFwID0gbmV3IFdlYWtNYXAoKTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgICAgICB0aGlzLmV2dExpc3RlbmVycyA9IHt9OwoJICAgICAgICB9CgoJICAgICAgICBwYXJzZSh4bWwsIHBhcmVudCwgZGlyKSB7CgkgICAgICAgICAgICBkaXIgPSBkaXIgPyBkaXIgKyAnLicgOiAnJzsKCSAgICAgICAgICAgIGxldCBub2RlUmVnRXggPSAvPChbXiA+XC9dKykoLio/KT4vbWcsIG5vZGVNYXRjaCA9IG51bGwsIG5vZGVzID0gW107CgkgICAgICAgICAgICB3aGlsZSAobm9kZU1hdGNoID0gbm9kZVJlZ0V4LmV4ZWMoeG1sKSkgewoJICAgICAgICAgICAgICAgIGxldCB0YWcgPSBub2RlTWF0Y2hbMV0sIG5vZGUgPSB7ICR0YWc6IHRhZyB9LCBmdWxsVGFnID0gZGlyICsgdGFnOwoKCSAgICAgICAgICAgICAgICBsZXQgYXR0clRleHQgPSBub2RlTWF0Y2hbMl0udHJpbSgpLCBjbG9zZWQgPSBmYWxzZTsKCSAgICAgICAgICAgICAgICBpZiAoYXR0clRleHQuZW5kc1dpdGgoJy8nKSB8fCB0YWcuc3RhcnRzV2l0aCgnPycpIHx8IHRhZy5zdGFydHNXaXRoKCchJykpIHsKCSAgICAgICAgICAgICAgICAgICAgY2xvc2VkID0gdHJ1ZTsKCSAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIGxldCBhdHRSZWdFeDEgPSAvKFteIF0rPyk9IiguKz8pIi9nLCBhdHRSZWdFeDIgPSAvKFteIF0rPyk9JyguKz8pJy9nOwoJICAgICAgICAgICAgICAgIGxldCBhdHRNYXRjaCA9IG51bGwsIGhhc0F0dHJzID0gZmFsc2U7CgkgICAgICAgICAgICAgICAgd2hpbGUgKGF0dE1hdGNoID0gYXR0UmVnRXgxLmV4ZWMoYXR0clRleHQpKSB7CgkgICAgICAgICAgICAgICAgICAgIGhhc0F0dHJzID0gdHJ1ZTsKCSAgICAgICAgICAgICAgICAgICAgbm9kZVthdHRNYXRjaFsxXV0gPSBhdHRNYXRjaFsyXTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgaWYgKCFoYXNBdHRycykKCSAgICAgICAgICAgICAgICAgICAgd2hpbGUgKGF0dE1hdGNoID0gYXR0UmVnRXgyLmV4ZWMoYXR0clRleHQpKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBoYXNBdHRycyA9IHRydWU7CgkgICAgICAgICAgICAgICAgICAgICAgICBub2RlW2F0dE1hdGNoWzFdXSA9IGF0dE1hdGNoWzJdOwoJICAgICAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIGlmICghaGFzQXR0cnMgJiYgYXR0clRleHQgIT09ICcnKSB7CgkgICAgICAgICAgICAgICAgICAgIG5vZGUudGV4dCA9IGF0dHJUZXh0OwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICBpZiAodGhpcy5wcm9ncmVzc2l2ZSkgewoJICAgICAgICAgICAgICAgICAgICB0aGlzLmVtaXQoYDwke2Z1bGxUYWd9PmAsIG5vZGUsIHBhcmVudCk7CgkgICAgICAgICAgICAgICAgfQoKCSAgICAgICAgICAgICAgICBpZiAoIWNsb3NlZCkgewoJICAgICAgICAgICAgICAgICAgICBsZXQgaW5uZXJSZWdFeCA9IG5ldyBSZWdFeHAoYChbXl0rPyk8XC8ke3RhZ30+YCwgJ2cnKTsKCSAgICAgICAgICAgICAgICAgICAgaW5uZXJSZWdFeC5sYXN0SW5kZXggPSBub2RlUmVnRXgubGFzdEluZGV4OwoJICAgICAgICAgICAgICAgICAgICBsZXQgaW5uZXJNYXRjaCA9IGlubmVyUmVnRXguZXhlYyh4bWwpOwoJICAgICAgICAgICAgICAgICAgICBpZiAoaW5uZXJNYXRjaCAmJiBpbm5lck1hdGNoWzFdKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBub2RlUmVnRXgubGFzdEluZGV4ID0gaW5uZXJSZWdFeC5sYXN0SW5kZXg7CgkgICAgICAgICAgICAgICAgICAgICAgICBsZXQgaW5uZXJOb2RlcyA9IHRoaXMucGFyc2UoaW5uZXJNYXRjaFsxXSwgbm9kZSwgZnVsbFRhZyk7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAoaW5uZXJOb2Rlcy5sZW5ndGggPiAwKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS4kaW5uZXJOb2RlcyA9IGlubmVyTm9kZXM7CgkgICAgICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIG5vZGUuJGlubmVyVGV4dCA9IGlubmVyTWF0Y2hbMV07CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgaWYgKHRoaXMucXVlcnlQYXJlbnQgJiYgcGFyZW50KSB7CgkgICAgICAgICAgICAgICAgICAgIHRoaXMucGFyZW50TWFwLnNldChub2RlLCBwYXJlbnQpOwoJICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgaWYgKHRoaXMucHJvZ3Jlc3NpdmUpIHsKCSAgICAgICAgICAgICAgICAgICAgdGhpcy5lbWl0KGA8LyR7ZnVsbFRhZ30+YCwgbm9kZSwgcGFyZW50KTsKCSAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIG5vZGVzLnB1c2gobm9kZSk7CgkgICAgICAgICAgICB9CgoJICAgICAgICAgICAgcmV0dXJuIG5vZGVzOwoJICAgICAgICB9CgoJICAgICAgICBnZXRQYXJlbnQobm9kZSkgewoJICAgICAgICAgICAgaWYgKHRoaXMucXVlcnlQYXJlbnQpIHsKCSAgICAgICAgICAgICAgICByZXR1cm4gdGhpcy5wYXJlbnRNYXAuZ2V0KG5vZGUpOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmV0dXJuIG51bGw7CgkgICAgICAgIH0KCgkgICAgICAgICNhZGRMaXN0ZW5lcihldnQsIGZ1bmMpIHsKCSAgICAgICAgICAgIGxldCBmdW5jcyA9IHRoaXMuZXZ0TGlzdGVuZXJzW2V2dF07CgkgICAgICAgICAgICBpZiAoZnVuY3MpIHsKCSAgICAgICAgICAgICAgICBmdW5jcy5wdXNoKGZ1bmMpOwoJICAgICAgICAgICAgfSBlbHNlIHsKCSAgICAgICAgICAgICAgICB0aGlzLmV2dExpc3RlbmVyc1tldnRdID0gW2Z1bmNdOwoJICAgICAgICAgICAgfQoJICAgICAgICB9CgoJICAgICAgICAvLyBz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i4uYXJncykgewoJICAgICAgICAgICAgbGV0IGZ1bmNzID0gdGhpcy5ldnRMaXN0ZW5lcnNbZXZ0XTsKCSAgICAgICAgICAgIGlmIChmdW5jcykgewoJICAgICAgICAgICAgICAgIGZvciAobGV0IGZ1bmMgb2YgZnVuY3MpIHsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGZ1bmMuY29uZGl0aW9uKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAoZnVuYy5jb25kaXRpb24uYXBwbHkobnVsbCwgYXJncykgPT09IHRydWUpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBmdW5jLmFwcGx5KG51bGwsIGFyZ3MpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgZnVuYy5hcHBseShudWxsLCBhcmdzKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgfQoKCSAgICAgICAgb24oZXZ0LCBmdW5jKSB7CgkgICAgICAgICAgICB0aGlzLmFkZExpc3RlbmVyKGV2dCwgZnVuYyk7CgkgICAgICAgIH0KCgkgICAgICAgIG9mZihldnQsIGZ1bmMpIHsKCSAgICAgICAgICAgIHRoaXMucmVtb3ZlTGlzdGVuZXIoZXZ0LCBmdW5jKTsKCSAgICAgICAgfQoJICAgIH07Cgl9KSgpOwoKCWNvbnN0IHsgTm9kZSwgV2F5LCBSZWxhdGlvbiB9ID0gb3Ntb2JqcywKCSAgICB7IHB1cmdlUHJvcHMsIFJlZkVsZW1lbnRzIH0gPSB1dGlscywKCSAgICBYbWxQYXJzZXIgPSB4bWxwYXJzZXI7CgoJdmFyIGxpYiA9IChvc20sIG9wdHMpID0+IHsKCSAgICBsZXQgY29tcGxldGVGZWF0dXJlID0gZmFsc2UsIHJlbmRlclRhZ2dlZCA9IGZhbHNlLCBleGNsdWRlV2F5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b25zdCBhbmFseXplRmVhdHVyZXNGcm9tSnNvbiA9IG9zbSA9PiB7CgkgICAgICAgIGZvciAobGV0IGVsZW0gb2Ygb3NtLmVsZW1lbnRzKSB7CgkgICAgICAgICAgICBzd2l0Y2ggKGVsZW0udHlwZSkgewoJICAgICAgICAgICAgICAgIGNhc2UgJ25vZGUnOgoJICAgICAgICAgICAgICAgICAgICBsZXQgbm9kZSA9IG5ldyBOb2RlKGVsZW0uaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGVsZW0udGFncykgewoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS5hZGRUYWdzKGVsZW0udGFncyk7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgbm9kZS5hZGRQcm9wcyhwdXJnZVByb3BzKGVsZW0sIFsnaWQnLCAndHlwZScsICd0YWdzJywgJ2xhdCcsICdsb24nXSkpOwoJICAgICAgICAgICAgICAgICAgICBub2RlLnNldExhdExuZyhlbGVtKTsKCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgoJICAgICAgICAgICAgICAgIGNhc2UgJ3dheSc6CgkgICAgICAgICAgICAgICAgICAgIGxldCB3YXkgPSBuZXcgV2F5KGVsZW0uaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGVsZW0udGFncykgewoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5LmFkZFRhZ3MoZWxlbS50YWdzKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB3YXkuYWRkUHJvcHMocHVyZ2VQcm9wcyhlbGVtLCBbJ2lkJywgJ3R5cGUnLCAndGFncycsICdub2RlcycsICdnZW9tZXRyeSddKSk7CgkgICAgICAgICAgICAgICAgICAgIGlmIChlbGVtLm5vZGVzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBmb3IgKGxldCBuIG9mIGVsZW0ubm9kZXMpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB3YXkuYWRkTm9kZVJlZihuKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgfSBlbHNlIGlmIChlbGVtLmdlb21ldHJ5KSB7CgkgICAgICAgICAgICAgICAgICAgICAgICB3YXkuc2V0TGF0TG5nQXJyYXkoZWxlbS5nZW9tZXRyeSk7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgoJICAgICAgICAgICAgICAgIGNhc2UgJ3JlbGF0aW9uJzoKCSAgICAgICAgICAgICAgICAgICAgbGV0IHJlbGF0aW9uID0gbmV3IFJlbGF0aW9uKGVsZW0uaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGVsZW0uYm91bmRzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICByZWxhdGlvbi5zZXRCb3VuZHMoW3BhcnNlRmxvYXQoZWxlbS5ib3VuZHMubWlubG9uKSwgcGFyc2VGbG9hdChlbGVtLmJvdW5kcy5taW5sYXQpLCBwYXJzZUZsb2F0KGVsZW0uYm91bmRzLm1heGxvbiksIHBhcnNlRmxvYXQoZWxlbS5ib3VuZHMubWF4bGF0KV0pOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGlmIChlbGVtLnRhZ3MpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHJlbGF0aW9uLmFkZFRhZ3MoZWxlbS50YWdzKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICByZWxhdGlvbi5hZGRQcm9wcyhwdXJnZVByb3BzKGVsZW0sIFsnaWQnLCAndHlwZScsICd0YWdzJywgJ2JvdW5kcycsICdtZW1iZXJzJ10pKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGVsZW0ubWVtYmVycykgewoJICAgICAgICAgICAgICAgICAgICAgICAgZm9yIChsZXQgbWVtYmVyIG9mIGVsZW0ubWVtYmVycykgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJlbGF0aW9uLmFkZE1lbWJlcihtZW1iZXIpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGJyZWFrOwoJICAgICAgICAgICAgfQoJICAgICAgICB9CgkgICAgfTsKCgkgICAgY29uc3QgYW5hbHl6ZUZlYXR1cmVzRnJvbVhtbCA9IG9zbSA9PiB7CgkgICAgICAgIGNvbnN0IHhtbFBhcnNlciA9IG5ldyBYbWxQYXJzZXIoeyBwcm9ncmVzc2l2ZTogdHJ1ZSB9KTsKCgkgICAgICAgIHhtbFBhcnNlci5vbignPC9vc20ubm9kZT4nLCBub2RlID0+IHsKCSAgICAgICAgICAgIGxldCBuZCA9IG5ldyBOb2RlKG5vZGUuaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgIGZvciAobGV0IFtrLCB2XSBvZiBPYmplY3QuZW50cmllcyhub2RlKSkKCSAgICAgICAgICAgICAgICBpZiAoIWsuc3RhcnRzV2l0aCgnJCcpICYmIFsnaWQnLCAnbG9uJywgJ2xhdCddLmluZGV4T2YoaykgPCAwKSB7CgkgICAgICAgICAgICAgICAgICAgIG5kLmFkZFByb3Aoaywgdik7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgbmQuc2V0TGF0TG5nKG5vZGUpOwoJICAgICAgICAgICAgaWYgKG5vZGUuJGlubmVyTm9kZXMpIHsKCSAgICAgICAgICAgICAgICBmb3IgKGxldCBpbmQgb2Ygbm9kZS4kaW5uZXJOb2RlcykgewoJICAgICAgICAgICAgICAgICAgICBpZiAoaW5kLiR0YWcgPT09ICd0YWcnKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBuZC5hZGRUYWcoaW5kLmssIGluZC52KTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgfSk7CgoJICAgICAgICB4bWxQYXJzZXIub24oJzwvb3NtLndheT4nLCBub2RlID0+IHsKCSAgICAgICAgICAgIGxldCB3YXkgPSBuZXcgV2F5KG5vZGUuaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgIGZvciAobGV0IFtrLCB2XSBvZiBPYmplY3QuZW50cmllcyhub2RlKSkgewoJICAgICAgICAgICAgICAgIGlmICghay5zdGFydHNXaXRoKCckJykgJiYgWydpZCddLmluZGV4T2YoaykgPCAwKSB7CgkgICAgICAgICAgICAgICAgICAgIHdheS5hZGRQcm9wKGssIHYpOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIGlmIChub2RlLiRpbm5lck5vZGVzKSB7CgkgICAgICAgICAgICAgICAgZm9yIChsZXQgaW5kIG9mIG5vZGUuJGlubmVyTm9kZXMpIHsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGluZC4kdGFnID09PSAnbmQnKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAoaW5kLmxvbiAmJiBpbmQubGF0KSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgd2F5LmFkZExhdExuZyhpbmQpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfSBlbHNlIGlmIChpbmQucmVmKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgd2F5LmFkZE5vZGVSZWYoaW5kLnJlZik7CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIH0gZWxzZSBpZiAoaW5kLiR0YWcgPT09ICd0YWcnKQoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5LmFkZFRhZyhpbmQuaywgaW5kLnYpOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgfSk7CgoJICAgICAgICB4bWxQYXJzZXIub24oJzxvc20ucmVsYXRpb24+Jywgbm9kZSA9PiB7CgkgICAgICAgICAgICBuZXcgUmVsYXRpb24obm9kZS5pZCwgcmVmRWxlbWVudHMpOwoJICAgICAgICB9KTsKCgkgICAgICAgIHhtbFBhcnNlci5vbignPC9vc20ucmVsYXRpb24ubWVtYmVyPicsIChub2RlLCBwYXJlbnQpID0+IHsKCSAgICAgICAgICAgIGxldCByZWxhdGlvbiA9IHJlZkVsZW1lbnRzLmdldChgcmVsYXRpb24vJHtwYXJlbnQuaWR9YCk7CgkgICAgICAgICAgICBsZXQgbWVtYmVyID0gewoJICAgICAgICAgICAgICAgIHR5cGU6IG5vZGUudHlwZSwKCSAgICAgICAgICAgICAgICByb2xlOiBub2RlLnJvbGUgPyBub2RlLnJvbGUgOiAnJywKCSAgICAgICAgICAgICAgICByZWY6IG5vZGUucmVmCgkgICAgICAgICAgICB9OwoJICAgICAgICAgICAgaWYgKG5vZGUubGF0ICYmIG5vZGUubG9uKSB7CgkgICAgICAgICAgICAgICAgbWVtYmVyLmxhdCA9IG5vZGUubGF0LCBtZW1iZXIubG9uID0gbm9kZS5sb24sIG1lbWJlci50YWdzID0ge307CgkgICAgICAgICAgICAgICAgZm9yIChsZXQgW2ssIHZdIG9mIE9iamVjdC5lbnRyaWVzKG5vZGUpKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmICghay5zdGFydHNXaXRoKCckJykgJiYgWyd0eXBlJywgJ2xhdCcsICdsb24nXS5pbmRleE9mKGspIDwgMCkgewoJICAgICAgICAgICAgICAgICAgICAgICAgbWVtYmVyW2tdID0gdjsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIGlmIChub2RlLiRpbm5lck5vZGVzKSB7CgkgICAgICAgICAgICAgICAgbGV0IGdlb21ldHJ5ID0gW107CgkgICAgICAgICAgICAgICAgbGV0IG5vZGVzID0gW107CgkgICAgICAgICAgICAgICAgZm9yIChsZXQgaW5kIG9mIG5vZGUuJGlubmVyTm9kZXMpIHsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGluZC5sYXQgJiYgaW5kLmxvbikgewoJICAgICAgICAgICAgICAgICAgICAgICAgZ2VvbWV0cnkucHVzaChpbmQpOwoJICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZXMucHVzaChpbmQucmVmKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICBpZiAoZ2VvbWV0cnkubGVuZ3RoID4gMCkgewoJICAgICAgICAgICAgICAgICAgICBtZW1iZXIuZ2VvbWV0cnkgPSBnZW9tZXRyeTsKCSAgICAgICAgICAgICAgICB9IGVsc2UgaWYgKG5vZGVzLmxlbmd0aCA+IDApIHsKCSAgICAgICAgICAgICAgICAgICAgbWVtYmVyLm5vZGVzID0gbm9kZXM7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmVsYXRpb24uYWRkTWVtYmVyKG1lbWJlcik7CgkgICAgICAgIH0pOwoKCSAgICAgICAgeG1sUGFyc2VyLm9uKCc8L29zbS5yZWxhdGlvbi5ib3VuZHM+JywgKG5vZGUsIHBhcmVudCkgPT4gewoJICAgICAgICAgICAgcmVmRWxlbWVudHMuZ2V0KGByZWxhdGlvbi8ke3BhcmVudC5pZH1gKS5zZXRCb3VuZHMoW3BhcnNlRmxvYXQobm9kZS5taW5sb24pLCBwYXJzZUZsb2F0KG5vZGUubWlubGF0KSwgcGFyc2VGbG9hdChub2RlLm1heGxvbiksIHBhcnNlRmxvYXQobm9kZS5tYXhsYXQpXSk7CgkgICAgICAgIH0pOwoKCSAgICAgICAgeG1sUGFyc2VyLm9uKCc8L29zbS5yZWxhdGlvbi50YWc+JywgKG5vZGUsIHBhcmVudCkgPT4gewoJICAgICAgICAgICAgcmVmRWxlbWVudHMuZ2V0KGByZWxhdGlvbi8ke3BhcmVudC5pZH1gKS5hZGRUYWcobm9kZS5rLCBub2RlLnYpOwoJICAgICAgICB9KTsKCgkgICAgICAgIHhtbFBhcnNlci5wYXJzZShvc20pOwoJICAgIH07CgoJICAgIGlmIChmb3JtYXQgPT09ICdqc29uLXJhdycpIHsKCSAgICAgICAgb3NtID0gSlNPTi5wYXJzZShvc20pOwoJICAgICAgICBpZiAob3NtLmVsZW1lbnRzKSB7CgkgICAgICAgICAgICBmb3JtYXQgPSAnanNvbic7CgkgICAgICAgIH0gZWxzZSB7CgkgICAgICAgICAgICBmb3JtYXQgPSAnaW52YWxpZCc7CgkgICAgICAgIH0KCSAgICB9CgoJICAgIGlmIChmb3JtYXQgPT09ICdqc29uJykgewoJICAgICAgICBhbmFseXplRmVhdHVyZXNGcm9tSnNvbihvc20pOwoJICAgIH0gZWxzZSBpZiAoZm9ybWF0ID09PSAneG1sJykgewoJICAgICAgICBhbmFseXplRmVhdHVyZXNGcm9tWG1sKG9zbSk7CgkgICAgfQoKCSAgICByZWZFbGVtZW50cy5iaW5kQWxsKCk7CgoJICAgIGZvciAobGV0IHYgb2YgcmVmRWxlbWVudHMudmFsdWVzKCkpIHsKCSAgICAgICAgaWYgKHYucmVmQ291bnQgPD0gMCB8fCAodi5oYXNUYWcgJiYgcmVuZGVyVGFnZ2VkICYmICEodiBpbnN0YW5jZW9mIFdheSAmJiBleGNsdWRlV2F5KSkpIHsKCSAgICAgICAgICAgIGxldCBmZWF0dXJlcyA9IHYudG9GZWF0dXJlQXJyYXkoKTsKCSAgICAgICAgICAgIC8vIHJldHVybiB0aGUgZmlyc3QgZ2VvbWV0cnkgb2YgdGhlIGZpcnN0IHJlbGF0aW9uIGVsZW1lbnQKCSAgICAgICAgICAgIGlmICh2IGluc3RhbmNlb2YgUmVsYXRpb24gJiYgIWNvbXBsZXRlRmVhdHVyZSAmJiBmZWF0dXJlcy5sZW5ndGggPiAwKSB7CgkgICAgICAgICAgICAgICAgcmV0dXJuIGZlYXR1cmVzWzBdLmdlb21ldHJ5OwoJICAgICAgICAgICA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YgKGxpbmVTdHJpbmcuY29vcmRpbmF0ZXMubGVuZ3RoID09PSAxKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAvLyBNYWtlIGl0IGEgcG9pbnQKCSAgICAgICAgICAgICAgICAgICAgICAgIGdlb21ldHJ5ID0gewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICd0eXBlJzogJ1BvaW50JywKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAnY29vcmRpbmF0ZXMnOiBsaW5lU3RyaW5nLmNvb3JkaW5hdGVzWzBdCgkgICAgICAgICAgICAgICAgICAgICAgICB9OwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgY29uc29sZS53YXJuKCdDYW5ub3QgY29udmVydCBwb2x5bGluZSB0byAnICsgb3B0aW9ucy50eXBlKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICBlbHNlIGlmIChvcHRpb25zLnR5cGUgPT09ICdwb2x5Z29uJykgewoJICAgICAgICAgICAgICAgICAgICBpZiAobGluZVN0cmluZy5jb29yZGluYXRlc1swXVswXSA9PT0gbGluZVN0cmluZy5jb29yZGluYXRlc1tsaW5lU3RyaW5nLmNvb3JkaW5hdGVzLmxlbmd0aCAtIDFdWzBdICYmCgkgICAgICAgICAgICAgICAgICAgICAgICBsaW5lU3RyaW5nLmNvb3JkaW5hdGVzWzBdWzFdID09PSBsaW5lU3RyaW5nLmNvb3JkaW5hdGVzW2xpbmVTdHJpbmcuY29vcmRpbmF0ZXMubGVuZ3RoIC0gMV1bMV0pIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIC8vIE1ha2UgaXQgYSBwb2x5Z29uCgkgICAgICAgICAgICAgICAgICAgICAgICBnZW9tZXRyeSA9IHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAndHlwZSc6ICdQb2x5Z29uJywKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAnY29vcmRpbmF0ZXMnOiBbbGluZVN0cmluZy5jb29yZGluYXRlc10KCSAgICAgICAgICAgICAgICAgICAgICAgIH07CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgZWxzZSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBjb25zb2xlLndhcm4oJ0Nhbm5vdCBjb252ZXJ0IHBvbHlsaW5lIHRvICcgKyBvcHRpb25zLnR5cGUpOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIHJlc29sdmUoewoJICAgICAgICAgICAgICAgICAgICB0eXBlOiAiRmVhdHVyZUNvbGxlY3Rpb24iLAoJICAgICAgICAgICAgICAgICAgICBmZWF0dXJlczogW3sKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAidHlwZSI6ICJGZWF0dXJlIiwKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAiZ2VvbWV0cnkiOiBnZW9tZXRyeSwKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAicHJvcGVydGllcyI6IG9wdGlvbnMucHJvcGVydGllcyB8fCB7fQoJICAgICAgICAgICAgICAgICAgICAgICAgfV0KCSAgICAgICAgICAgICAgICB9KTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIGNhdGNoIChlcnIpIHsKCSAgICAgICAgICAgICAgICByZWplY3QoZXJyKTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgfSk7CgkgICAgICAgIHJldHVybiBnZW9qc29uOwoJICAgIH0KCX0KCgljb25zdCBsaWJyYXJpZXMgPSB7CgkgICAgJ0NvbnZlcnRlcic6IENvbnZlcnRlcgoJfTsKCWxldCBzdWJDbGFzczsKCXNlbGYuYWRkRXZlbnRMaXN0ZW5lcignbWVzc2FnZScsIGUgPT4gewoJICAgIGNvbnN0IGRhdGEgPSAoZS5kYXRhIHx8IGUpOwoJICAgIGNvbnN0IHBvc3QgPSAoaWQsIGVyciwgcmVzLCB0eXBlKSA9PiB7CgkgICAgICAgIHBvc3RNZXNzYWdlKHsKCSAgICAgICAgICAgIHR5cGU6IHR5cGUgPyB0eXBlIDogKGVyciA/ICdlcnJvcicgOiAncmVzcG9uc2UnKSwKCSAgICAgICAgICAgIGlkOiBpZCwKCSAgICAgICAgICAgIG1lc3NhZ2U6IHJlcywKCSAgICAgICAgICAgIGVycm9yOiBlcnIKCSAgICAgICAgfSk7CgkgICAgfTsKCSAgICBjb25zdCBjb21tYW5kcyA9IHsKCSAgICAgICAgJ2luaXQnOiAobXNnKSA9PiB7CgkgICAgICAgICAgICBjb25zdCB7IGlkLCBjb21tYW5kLCBtZXNzYWdlIH0gPSBtc2c7CgkgICAgICAgICAgICBzdWJDbGFzcyA9IG5ldyBsaWJyYXJpZXNbY29tbWFuZF0obWVzc2FnZVswXSwgbWVzc2FnZVsxXSk7CgkgICAgICAgICAgICAvLyByZXR1cm4gdGhlIGNsYXNzJyBtZXRob2RzCgkgICAgICAgICAgICBjb25zdCBmbnMgPSBbCgkgICAgICAgICAgICAgICAgLi4uT2JqZWN0LmdldE93blByb3BlcnR5TmFtZXMobGlicmFyaWVzW2NvbW1hbmRdLnByb3RvdHlwZSksCgkgICAgICAgICAgICAgICAgLi4uT2JqZWN0LmtleXMoc3ViQ2xhc3MpCgkgICAgICAgICAgICBdLm1hcChrZXkgPT4gW2tleSwgdHlwZW9mIGxpYnJhcmllc1tjb21tYW5kXS5wcm90b3R5cGVba2V5XV0pCgkgICAgICAgICAgICAgICAgLnJlZHVjZSgoYSwgYykgPT4gKHsgLi4uYSwgLi4ueyBbY1swXV06IGNbMV0gfSB9KSwge30pOwoJICAgICAgICAgICAgcG9zdChpZCwgdW5kZWZpbmVkLCBmbnMsICdpbml0X3Jlc3BvbnNlJyk7CgkgICAgICAgIH0sCgkgICAgICAgICdnZXQnOiBmdW5jdGlvbiAobXNnKSB7CgkgICAgICAgICAgICBjb25zdCB7IGlkLCBjb21tYW5kIH0gPSBtc2c7CgkgICAgICAgICAgICBpZiAoc3ViQ2xhc3MgJiYgc3ViQ2xhc3NbY29tbWFuZF0pIHsKCSAgICAgICAgICAgICAgICBwb3N0KGlkLCB1bmRlZmluZWQsIHN1YkNsYXNzW2NvbW1hbmRdKTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIGVsc2UgewoJICAgICAgICAgICAgICAgIHBvc3QoaWQsIHVuZGVmaW5lZCwgdW5kZWZpbmVkKTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgfSwKCSAgICAgICAgJ2V4ZWMnOiBmdW5jdGlvbiAobXNnKSB7CgkgICAgICAgICAgICBjb25zdCB7IGlkLCBjb21tYW5kLCBtZXNzYWdlIH0gPSBtc2c7CgkgICAgICAgICAgICBpZiAoc3ViQ2xhc3MgJiYgc3ViQ2xhc3NbY29tbWFuZF0gJiYgdHlwZW9mIHN1YkNsYXNzW2NvbW1hbmRdID09PSAnZnVuY3Rpb24nKSB7CgkgICAgICAgICAgICAgICAgY29uc3QgY21kID0gc3ViQ2xhc3NbY29tbWFuZF0KCSAgICAgICAgICAgICAgICAgICAgLmFwcGx5KHN1YkNsYXNzLCBtZXNzYWdlKTsKCSAgICAgICAgICAgICAgICBpZiAoISFjbWQgJiYgdHlwZW9mIGNtZC50aGVuID09PSAnZnVuY3Rpb24nKSB7CgkgICAgICAgICAgICAgICAgICAgIC8vIEl0J3MgYSBwcm9taXNlLCBzbyB3YWl0IGZvciBpdAoJICAgICAgICAgICAgICAgICAgICBjbWQKCSAgICAgICAgICAgICAgICAgICAgICAgIC50aGVuKHJlcyA9PiBwb3N0KGlkLCB1bmRlZmluZWQsIHJlcykpCgkgICAgICAgICAgICAgICAgICAgICAgICAuY2F0Y2goZSA9PiBwb3N0KGlkLCBlKSk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAvLyBOb3QgYSBwcm9taXNlLCBqdXN0IHJldHVybiBpdAoJICAgICAgICAgICAgICAgICAgICBwb3N0KGlkLCB1bmRlZmluZWQsIGNtZCk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgZWxzZSB7CgkgICAgICAgICAgICAgICAgLy8gRXJyb3IKCSAgICAgICAgICAgICAgICBwb3N0KGlkLCBuZXcgRXJyb3IoYGNvbW1hbmQgIiR7Y29tbWFuZH0iIG5vdCBmb3VuZGApKTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgfQoJICAgIH07CgkgICAgaWYgKGNvbW1hbmRzW2RhdGEudHlwZV0pIHsKCSAgICAgICAgY29tbWFuZHNbZGF0YS50eXBlXShkYXRhKTsKCSAgICB9Cgl9KTsKCn0pKCk7Ci8vIyBzb3VyY2VNYXBwaW5nVVJMPXdvcmtlci5qcy5tYXAKCg=='); - /* eslint-enable */ - - const randomString = () => Math.random().toString(36).substring(2); - class Actor { - /** - * Creates a new instance of the `Actor` class. - * @param subClass - The name of the subclass. - * @param args - The arguments to pass to the subclass constructor. - */ - constructor(subClass, args) { - // Generate a random initialization ID - this.initId = randomString() + '-' + subClass; - // Create a new Web Worker and a new Map for handlers - this.worker = new WorkerFactory(); - this.handlers = new Map(); - // Listen for messages from the worker - this.worker.onmessage = (event) => { - const data = event.data; - const handler = this.handlers.get(data.id); - const that = this; - if (handler) { - // Handle responses from the worker - if (data.type === 'response') { - handler.resolve(data.message); - } - // Handle errors from the worker - if (data.type === 'error') { - const error = data.error || new Error(`Unknown error with ${subClass}`); - handler.reject(error); - } - // Handle initialization responses from the worker - if (data.type === 'init_response') { - this._ = Object.keys(data.message) - .map(key => { - const isFn = typeof data.message[key] === 'function'; - const subFunction = function () { - return isFn ? (that.exec(key))(...arguments) : that.get(key); - }; - return [key, subFunction]; - }) - .reduce((a, c) => ({ ...a, ...{ [c[0]]: c[1] } }), {}); - handler.resolve(this._); - } - } - }; - // Tell the worker to initialize the subclass - this.worker.postMessage({ - type: 'init', - id: this.initId, - command: subClass, - message: args - }); - } - /** - * Waits for the initialization of the object to complete and returns the resulting object. - * @returns A promise that resolves with the initialized object. - */ - onLoad() { - return new Promise((resolve) => { - // If initialization is still in progress, add a new handler for the initialization result - if (this._ === undefined) { - this.handlers.set(this.initId, { resolve, 'reject': resolve }); - } - else { - // Otherwise, immediately resolve the promise with the initialized object - resolve(this._); - } - }); - } - /** - * returns a Promise for a given command that will be executed in a worker. - * @param command - The command to execute. - * @returns A Promise that resolves with the result of the command execution or rejects with an error. - */ - exec(command) { - // Keep track of this class - const that = this; - // Return a function that returns a Promise - return function (...args) { - return new Promise((resolve, reject) => { - const id = randomString() + '-' + command; - // Set up the resolve and reject handlers for the Promise - that.handlers.set(id, { resolve, reject }); - // Tell the worker to run the command with the provided arguments - that.worker.postMessage({ - type: 'exec', - id: id, - command: command, - message: [...args] - }); - }); - }; - } - /** - * Returns a Promise that resolves with the result of a command sent to a Web Worker. - * @param command - The command to send to the Web Worker. - * @returns A Promise that resolves with the result of the command. - */ - get(command) { - return new Promise((resolve, reject) => { - // Generate a unique ID for this request - const id = randomString() + '-' + command; - // Store the resolve and reject functions for later use - this.handlers.set(id, { resolve, reject }); - // Send the command to the worker - this.worker.postMessage({ - type: 'get', - id, - command, - message: [], - }); - }); - } - } - - // Make sure we can support workers in the current browser / runtime - const supportsWorkers = () => { - let supported = false; - try { - supported = typeof (window.Worker) === 'function'; - } - catch (e) { - supported = false; - } - return supported; - }; - // Safari changes https:// to http// for some reason, so this is broken in Safari and iPhone - // So to fix this we add it back - const needsUrlCheck = (new URL('test://http://example.com')).href !== 'test://http://example.com'; - const checkUrl = (url) => { - const safariFixRegex = new RegExp('^(https?)(\/\/)'); - const cleanUrl = url.replace(safariFixRegex, '$1:$2'); - return cleanUrl; - }; - /** - * The processData function accepts a URL, prefix, and an optional controller - * and tries to read and convert the data - * @param url - The URL of the resource. - * @param prefix - The prefix used to process the data - * @param controller - optional controller that can be used to cancel a request - * @returns A geojson FeatureCollection (or undefined) - */ - async function processData(url, prefix, controller) { - const response = await fetch(url, controller ? { signal: controller.signal } : undefined); - let options = {}; - // Parse the URL - const urlObject = new URL(url, window.location.href); - if (urlObject.hash.length) { - // Extract the hash (including the "#" symbol) - const hash = urlObject.hash; - // Remove the "#" symbol from the hash and decode it - const decodedHash = decodeURIComponent(hash.slice(1)); // Remove the "#" symbol - try { - options = JSON.parse(decodedHash); - } - catch (e) { - console.warn('Error parsing or reading URL:', e); - } - } - if (response.status == 200) { - const rawData = await response.text(); - let convertPromise; - const usesDOM = (['kml', 'tcx', 'gpx'].includes(prefix)); - if (usesDOM || !supportsWorkers()) { - // XML uses the DOM, which isn't available to web workers - // It is possible to use xmldom to do this, but that increases the bundle size by 3x - const converter = new Converter(prefix, rawData, options); - convertPromise = converter.convert(); - } - else { - const converter = new Actor('Converter', [prefix, rawData, options]); - convertPromise = converter.exec('convert')(); - } - return await convertPromise; - } - else { - throw (new Error(`Data fetch error: ${response.statusText}`)); - } - } - /** - * Processes the URL and returns the prefix and cleaned URL. - * - * @param url - The URL to process. - * @returns An object with the prefix and cleaned URL. - */ - const processUrl = (url) => { - const prefix = url.split('://')[0]; - const replacedUrl = url.replace(new RegExp(`^${prefix}://`), ''); - // Apply the Safari fix (if needed) to the URL - const cleanUrl = needsUrlCheck ? checkUrl(replacedUrl) : replacedUrl; - return { prefix, url: cleanUrl }; - }; - /** - * Handles the Vector Text Protocol for version 4. - * - * @param requestParameters - The parameters for the request including the URL. - * @param controller - An AbortController instance to manage the request lifecycle. - * @returns A promise resolving to a GetResourceResponse containing a FeatureCollection or undefined. - * @throws Will throw an error if the URL is invalid or if any other error occurs during data processing. - */ - const VectorTextProtocolV4 = async (requestParameters, controller) => { - const { prefix, url } = processUrl(requestParameters.url); - if (url) { - try { - // Process the data and return the response - const data = await processData(url, prefix, controller); - return { data }; - } - catch (e) { - // Catch and rethrow errors with additional context - throw new Error(e || 'Unknown Error'); - } - } - else { - // Handle invalid URL case - throw new Error('Invalid URL: ' + requestParameters.url); - } - }; - /** - * Handles the Vector Text Protocol for version 3. - * - * @param requestParameters - The parameters for the request including the URL. - * @param callback - A callback function to handle the response or error. - * @returns An object with a cancel function to abort the request. - */ - const VectorTextProtocolV3 = (requestParameters, callback) => { - const controller = new AbortController(); - const { prefix, url } = processUrl(requestParameters.url); - if (url) { - processData(url, prefix, controller) - .then(data => callback(null, data)) - .catch(e => callback(e)); - } - // Return an object with a cancel method to abort the request - return { cancel: () => { controller.abort(); } }; - }; - /** - * Selects the appropriate Vector Text Protocol version based on the type of controller provided. - * - * @param requestParameters - The parameters for the request including the URL. - * @param controller - Either an AbortController or a callback function. - * @returns Either a Promise for V4 or an object with a cancel method for V3. - */ - const VectorTextProtocol = (requestParameters, controller) => { - if (controller instanceof AbortController) { - return VectorTextProtocolV4(requestParameters, controller); - } - else { - return VectorTextProtocolV3(requestParameters, controller); - } - }; - /** - * Add the vector text protocol to a map library for each supported format. - * @param mapLibrary - The MapLibrary object to add the protocols to. - */ - const addProtocols = (mapLibrary) => { - supportedFormats.forEach(type => { - mapLibrary.addProtocol(type, VectorTextProtocol); - }); - }; - - loadCSS('https://unpkg.com/maplibre-gl@4.5.2/dist/maplibre-gl.css'); - - /** class: Maplibre */ - const Renderer = class extends defaultExport { - /** fields */ - id = 'maplibre' - pitch = 0 - bearing = 0 - style = 'https://demotiles.maplibre.org/style.json' - link = false - globe = false - /* eslint-disable-next-line no-undef */ - maplibregl = maplibregl - - /** options */ - static validOptions = this.validOptions.concat([ - new MapOption({ - name: 'pitch', - desc: 'Pitch toward the horizon measured in degrees', - example: '60', - exampleDesc: 'Look a little upward', - isValid: value => value <= 90 && value >= 0, - }), - new MapOption({ - name: 'bearing', - desc: "The compass direction that is 'up'", - example: '-30', - exampleDesc: 'Rotate map a little', - isValid: value => value <= 180 && value >= -180, - }), - new MapOption({ - name: 'link', - desc: "Syn map's position with the hash fragment of the page's URL", - example: 'true', - exampleDesc: 'Add hash for page URL', - isValid: value => value === 'true', - }), - new MapOption({ - name: 'style', - desc: 'URL of style document, read https://maplibre.org/maplibre-style-spec/', - example: 'https://tile.openstreetmap.jp/styles/openmaptiles/style.json', - exampleDesc: 'Style form OSM japan!!!', - isValid: value => URL.parse(value), - }), - new MapOption({ - name: 'globe', - desc: 'Display a globe', - example: 'true', - exampleDesc: 'Add globe for lower zoom level', - isValid: value => value === 'true', - }), - ]) - - get steps () { - return [...super.steps, this.setProjection] - } - - /** options: center, zoom, pitch, bearing, link, globe */ - async addMap ({ - maplibregl, - target, - style, - data, - center, - zoom, - pitch, - bearing, - link, - globe, - }) { - const tileData = data.filter(d => d.type === 'tile'); - const maplibreStyle = - tileData.length !== 0 ? { version: 8, sources: {}, layers: [] } : style; - - this.map = new maplibregl.Map({ - container: target, - style: maplibreStyle, - center, - zoom, - pitch, - bearing, - hash: link, - }); - - return new Promise((resolve, _reject) => { - this.map.on('load', () => { - this.map.setProjection({ - type: globe ? 'globe' : 'mercator', // Set projection to globe - }); - resolve(this.map); - }); - }) - } - - /** options: draw */ - getTerraDrawAdapter ({ maplibregl, map, draw }) { - if (!draw) return { state: 'skip' } - - this.terraDrawAdapter = new l({ map, maplibregl }); - return this.terraDrawAdapter - } - - /** options: control */ - setControl ({ maplibregl, map, control }) { - if (!control || Object.values(control).filter(v => v).length === 0) { return { state: 'skip' } } - - if (control.fullscreen === true) { - map.addControl(new maplibregl.FullscreenControl()); - } - if (control.scale === true) { - const scale = new maplibregl.ScaleControl({ - unit: 'metric', - }); - map.addControl(scale); - } - } - - /** options: debug, eval */ - setExtra (config) { - const { map, debug } = config; - if (!debug && !config.eval) return { state: 'skip' } - - if (debug === true) { - map.showTileBoundaries = true; - } - if (config.eval) { - this.evalScript(config.eval, [['map', map]]); - } - } - - /** options: data */ - addTileData ({ map, data }) { - const tileData = data.filter(d => d.type === 'tile'); - if (tileData.length === 0) return { state: 'skip' } - - const style = map.getStyle(); - tileData.forEach((datum, index) => { - const source = datum.name ? datum.name : index.toString(); - style.sources[source] = { - type: 'raster', - tiles: [datum.url], - tileSize: 256, - }; - style.layers.push({ id: source, type: 'raster', source }); - }); - map.setStyle(style); - } - - /** options: data.gpx */ - async addGPXFile ({ maplibregl, map, data }) { - const gpxUrl = data.find(record => record.type === 'gpx'); - if (!gpxUrl) return { state: 'skip' } - - addProtocols(maplibregl); - - const gpxSourceName = 'gpx'; - const gpxLink = 'gpx://' + gpxUrl; - - const source = { - type: 'geojson', - data: gpxLink, - }; - map.addSource(gpxSourceName, source); - map.addLayer({ - id: 'id_' + gpxSourceName, - type: 'line', - source: gpxSourceName, - paint: { - 'line-color': 'red', - 'line-width': 3, - }, - }); - - if (!Object.prototype.hasOwnProperty.call(this, 'center')) { - const data = await map.getSource(gpxSourceName).getData(); - const coordinates = data.features[0].geometry.coordinates; - const bounds = coordinates.reduce( - (bounds, coord) => bounds.extend(coord), - new maplibregl.LngLatBounds(coordinates[0], coordinates[0]), - ); - map.fitBounds(bounds, { - padding: 20, - }); - } - } - - /** actions: marker */ - addMarker (config) { - const options = config.element - ? { - element: config.element, - anchor: config.type === 'pin' ? 'bottom' : 'center', - } - : {}; - const marker = new this.maplibregl.Marker(options) - .setLngLat(config.xy) - .addTo(this.map); - const element = marker.getElement(); - element.classList.add('marker'); - element.remove = () => marker.remove(); - - return element - } - - /** actions: camera */ - async updateCamera ({ bounds, center, zoom, animation, ...others }, useAnimation) { - if (bounds) { - this.map.fitBounds(bounds, { linear: true, ...others }); - } else if (animation || useAnimation) { - this.map.flyTo({ - center: center ?? this.map.getCenter(), - zoom: zoom ?? this.map.getZoom(), - ...others, - }); - } else { - this.map.setCenter(center); - this.map.setZoom(zoom); - } - - return new Promise(resolve => { - this.map.on('zoomend', () => { - resolve('zoomend'); - }); - }) - } - - /** utils: projection */ - project ([lng, lat]) { - return this.map.project([lng, lat]) - } - - unproject ([x, y]) { - const { lng, lat } = this.map.unproject([x, y]); - return [lng, lat] - } - }; - - exports.default = Renderer; - - Object.defineProperty(exports, '__esModule', { value: true }); - - renderByScriptTarget() - -})); + */var Wl=function requireMaplibreGl(){return Tl||(Tl=1,function(M){M.exports=function(){var M={},et={};function define(Bt,Wt,Nt){if(et[Bt]=Nt,"index"===Bt){var $t="var sharedModule = {}; ("+et.shared+")(sharedModule); ("+et.worker+")(sharedModule);",Gr={};return et.shared(Gr),et.index(M,Gr),"undefined"!=typeof window&&M.setWorkerUrl(window.URL.createObjectURL(new Blob([$t],{type:"text/javascript"}))),M}}define("shared",["exports"],(function(M){function e(M,et,Bt,Wt){return new(Bt||(Bt=Promise))((function(Nt,$t){function a(M){try{l(Wt.next(M))}catch(M){$t(M)}}function o(M){try{l(Wt.throw(M))}catch(M){$t(M)}}function l(M){var et;M.done?Nt(M.value):(et=M.value,et instanceof Bt?et:new Bt((function(M){M(et)}))).then(a,o)}l((Wt=Wt.apply(M,et||[])).next())}))}function r(M){return M&&M.__esModule&&Object.prototype.hasOwnProperty.call(M,"default")?M.default:M}var et,Bt;function s(){if(Bt)return et;function t(M,et){this.x=M,this.y=et}return Bt=1,et=t,t.prototype={clone:function(){return new t(this.x,this.y)},add:function(M){return this.clone()._add(M)},sub:function(M){return this.clone()._sub(M)},multByPoint:function(M){return this.clone()._multByPoint(M)},divByPoint:function(M){return this.clone()._divByPoint(M)},mult:function(M){return this.clone()._mult(M)},div:function(M){return this.clone()._div(M)},rotate:function(M){return this.clone()._rotate(M)},rotateAround:function(M,et){return this.clone()._rotateAround(M,et)},matMult:function(M){return this.clone()._matMult(M)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(M){return this.x===M.x&&this.y===M.y},dist:function(M){return Math.sqrt(this.distSqr(M))},distSqr:function(M){var et=M.x-this.x,Bt=M.y-this.y;return et*et+Bt*Bt},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(M){return Math.atan2(this.y-M.y,this.x-M.x)},angleWith:function(M){return this.angleWithSep(M.x,M.y)},angleWithSep:function(M,et){return Math.atan2(this.x*et-this.y*M,this.x*M+this.y*et)},_matMult:function(M){var et=M[2]*this.x+M[3]*this.y;return this.x=M[0]*this.x+M[1]*this.y,this.y=et,this},_add:function(M){return this.x+=M.x,this.y+=M.y,this},_sub:function(M){return this.x-=M.x,this.y-=M.y,this},_mult:function(M){return this.x*=M,this.y*=M,this},_div:function(M){return this.x/=M,this.y/=M,this},_multByPoint:function(M){return this.x*=M.x,this.y*=M.y,this},_divByPoint:function(M){return this.x/=M.x,this.y/=M.y,this},_unit:function(){return this._div(this.mag()),this},_perp:function(){var M=this.y;return this.y=this.x,this.x=-M,this},_rotate:function(M){var et=Math.cos(M),Bt=Math.sin(M),Wt=Bt*this.x+et*this.y;return this.x=et*this.x-Bt*this.y,this.y=Wt,this},_rotateAround:function(M,et){var Bt=Math.cos(M),Wt=Math.sin(M),Nt=et.y+Wt*(this.x-et.x)+Bt*(this.y-et.y);return this.x=et.x+Bt*(this.x-et.x)-Wt*(this.y-et.y),this.y=Nt,this},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}},t.convert=function(M){return M instanceof t?M:Array.isArray(M)?new t(M[0],M[1]):M},et}"function"==typeof SuppressedError&&SuppressedError;var Wt,Nt,$t=r(s()),Gr=function(){if(Nt)return Wt;function t(M,et,Bt,Wt){this.cx=3*M,this.bx=3*(Bt-M)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*et,this.by=3*(Wt-et)-this.cy,this.ay=1-this.cy-this.by,this.p1x=M,this.p1y=et,this.p2x=Bt,this.p2y=Wt}return Nt=1,Wt=t,t.prototype={sampleCurveX:function(M){return((this.ax*M+this.bx)*M+this.cx)*M},sampleCurveY:function(M){return((this.ay*M+this.by)*M+this.cy)*M},sampleCurveDerivativeX:function(M){return(3*this.ax*M+2*this.bx)*M+this.cx},solveCurveX:function(M,et){if(void 0===et&&(et=1e-6),M<0)return 0;if(M>1)return 1;for(var Bt=M,Wt=0;Wt<8;Wt++){var Nt=this.sampleCurveX(Bt)-M;if(Math.abs(Nt)Nt?Gr=Bt:mn=Bt,Bt=.5*(mn-Gr)+Gr;return Bt},solve:function(M,et){return this.sampleCurveY(this.solveCurveX(M,et))}},Wt}(),mn=r(Gr);let Hn,so;function f(){return null==Hn&&(Hn="undefined"!=typeof OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof createImageBitmap),Hn}function d(){if(null==so&&(so=!1,f())){const M=5,et=new OffscreenCanvas(M,M).getContext("2d",{willReadFrequently:!0});if(et){for(let Bt=0;Bt=1)return 1;const et=M*M,Bt=et*M;return 4*(M<.5?Bt:3*(M-et)+Bt-.75)}function B(M,et,Bt,Wt){const Nt=new mn(M,et,Bt,Wt);return M=>Nt.solve(M)}const Eo=B(.25,.1,.25,1);function E(M,et,Bt){return Math.min(Bt,Math.max(et,M))}function T(M,et,Bt){const Wt=Bt-et,Nt=((M-et)%Wt+Wt)%Wt+et;return Nt===et?Bt:Nt}function F(M,...et){for(const Bt of et)for(const et in Bt)M[et]=Bt[et];return M}let Ia=1;function L(M,et,Bt){const Wt={};for(const Bt in M)Wt[Bt]=et.call(this,M[Bt],Bt,M);return Wt}function D(M,et,Bt){const Wt={};for(const Bt in M)et.call(this,M[Bt],Bt,M)&&(Wt[Bt]=M[Bt]);return Wt}function O(M){return Array.isArray(M)?M.map(O):"object"==typeof M&&M?L(M,O):M}const Ba={};function j(M){Ba[M]||("undefined"!=typeof console&&console.warn(M),Ba[M]=!0)}function N(M,et,Bt){return(Bt.y-M.y)*(et.x-M.x)>(et.y-M.y)*(Bt.x-M.x)}function U(M){return"undefined"!=typeof WorkerGlobalScope&&void 0!==M&&M instanceof WorkerGlobalScope}let Ta=null;function G(M){return"undefined"!=typeof ImageBitmap&&M instanceof ImageBitmap}const Va="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";function X(M,et,Bt,Wt,Nt){return e(this,void 0,void 0,(function*(){if("undefined"==typeof VideoFrame)throw new Error("VideoFrame not supported");const $t=new VideoFrame(M,{timestamp:0});try{const Gr=null==$t?void 0:$t.format;if(!Gr||!Gr.startsWith("BGR")&&!Gr.startsWith("RGB"))throw new Error(`Unrecognized format ${Gr}`);const mn=Gr.startsWith("BGR"),Hn=new Uint8ClampedArray(Wt*Nt*4);if(yield $t.copyTo(Hn,function(M,et,Bt,Wt,Nt){const $t=4*Math.max(-et,0),Gr=(Math.max(0,Bt)-Bt)*Wt*4+$t,mn=4*Wt,Hn=Math.max(0,et),so=Math.max(0,Bt);return{rect:{x:Hn,y:so,width:Math.min(M.width,et+Wt)-Hn,height:Math.min(M.height,Bt+Nt)-so},layout:[{offset:Gr,stride:mn}]}}(M,et,Bt,Wt,Nt)),mn)for(let M=0;MU(self)?self.worker&&self.worker.referrer:("blob:"===window.location.protocol?window.parent:window).location.href,it=function(M,et){if(/:\/\//.test(M.url)&&!/^https?:|^file:/.test(M.url)){const Bt=tt(M.url);if(Bt)return Bt(M,et);if(U(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:M,targetMapId:Da},et)}if(!(/^file:/.test(Bt=M.url)||/^file:/.test(nt())&&!/^\w+:/.test(Bt))){if(fetch&&Request&&AbortController&&Object.prototype.hasOwnProperty.call(Request.prototype,"signal"))return function(M,et){return e(this,void 0,void 0,(function*(){const Bt=new Request(M.url,{method:M.method||"GET",body:M.body,credentials:M.credentials,headers:M.headers,cache:M.cache,referrer:nt(),signal:et.signal});let Wt,Nt;"json"!==M.type||Bt.headers.has("Accept")||Bt.headers.set("Accept","application/json");try{Wt=yield fetch(Bt)}catch(Bt){throw new rt(0,Bt.message,M.url,new Blob)}if(!Wt.ok){const et=yield Wt.blob();throw new rt(Wt.status,Wt.statusText,M.url,et)}Nt="arrayBuffer"===M.type||"image"===M.type?Wt.arrayBuffer():"json"===M.type?Wt.json():Wt.text();const $t=yield Nt;if(et.signal.aborted)throw W();return{data:$t,cacheControl:Wt.headers.get("Cache-Control"),expires:Wt.headers.get("Expires")}}))}(M,et);if(U(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:M,mustQueue:!0,targetMapId:Da},et)}var Bt;return function(M,et){return new Promise(((Bt,Wt)=>{var Nt;const $t=new XMLHttpRequest;$t.open(M.method||"GET",M.url,!0),"arrayBuffer"!==M.type&&"image"!==M.type||($t.responseType="arraybuffer");for(const et in M.headers)$t.setRequestHeader(et,M.headers[et]);"json"===M.type&&($t.responseType="text",(null===(Nt=M.headers)||void 0===Nt?void 0:Nt.Accept)||$t.setRequestHeader("Accept","application/json")),$t.withCredentials="include"===M.credentials,$t.onerror=()=>{Wt(new Error($t.statusText))},$t.onload=()=>{if(!et.signal.aborted)if(($t.status>=200&&$t.status<300||0===$t.status)&&null!==$t.response){let et=$t.response;if("json"===M.type)try{et=JSON.parse($t.response)}catch(M){return void Wt(M)}Bt({data:et,cacheControl:$t.getResponseHeader("Cache-Control"),expires:$t.getResponseHeader("Expires")})}else{const et=new Blob([$t.response],{type:$t.getResponseHeader("Content-Type")});Wt(new rt($t.status,$t.statusText,M.url,et))}},et.signal.addEventListener("abort",(()=>{$t.abort(),Wt(W())})),$t.send(M.body)}))}(M,et)};function st(M){if(!M||M.indexOf("://")<=0||0===M.indexOf("data:image/")||0===M.indexOf("blob:"))return!0;const et=new URL(M),Bt=window.location;return et.protocol===Bt.protocol&&et.host===Bt.host}function at(M,et,Bt){Bt[M]&&-1!==Bt[M].indexOf(et)||(Bt[M]=Bt[M]||[],Bt[M].push(et))}function ot(M,et,Bt){if(Bt&&Bt[M]){const Wt=Bt[M].indexOf(et);-1!==Wt&&Bt[M].splice(Wt,1)}}class lt{constructor(M,et={}){F(this,et),this.type=M}}class ut extends lt{constructor(M,et={}){super("error",F({error:M},et))}}class ct{on(M,et){return this._listeners=this._listeners||{},at(M,et,this._listeners),{unsubscribe:()=>{this.off(M,et)}}}off(M,et){return ot(M,et,this._listeners),ot(M,et,this._oneTimeListeners),this}once(M,et){return et?(this._oneTimeListeners=this._oneTimeListeners||{},at(M,et,this._oneTimeListeners),this):new Promise((et=>this.once(M,et)))}fire(M,et){"string"==typeof M&&(M=new lt(M,et||{}));const Bt=M.type;if(this.listens(Bt)){M.target=this;const et=this._listeners&&this._listeners[Bt]?this._listeners[Bt].slice():[];for(const Bt of et)Bt.call(this,M);const Wt=this._oneTimeListeners&&this._oneTimeListeners[Bt]?this._oneTimeListeners[Bt].slice():[];for(const et of Wt)ot(Bt,et,this._oneTimeListeners),et.call(this,M);const Nt=this._eventedParent;Nt&&(F(M,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),Nt.fire(M))}else M instanceof ut&&console.error(M.error);return this}listens(M){return this._listeners&&this._listeners[M]&&this._listeners[M].length>0||this._oneTimeListeners&&this._oneTimeListeners[M]&&this._oneTimeListeners[M].length>0||this._eventedParent&&this._eventedParent.listens(M)}setEventedParent(M,et){return this._eventedParent=M,this._eventedParentData=et,this}}var Ka={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},centerAltitude:{type:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},roll:{type:"number",default:0,units:"degrees"},light:{type:"light"},sky:{type:"sky"},projection:{type:"projection"},terrain:{type:"terrain"},sources:{required:!0,type:"sources"},sprite:{type:"sprite"},glyphs:{type:"string"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{},custom:{}},default:"mapbox"},redFactor:{type:"number",default:1},blueFactor:{type:"number",default:1},greenFactor:{type:"number",default:1},baseShift:{type:"number",default:0},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{required:!0,type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},filter:{type:"*"},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image",{"!":"icon-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"padding",default:[2],units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},"viewport-glyph":{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-variable-anchor-offset":{type:"variableAnchorOffsetCollection",requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field",{"!":"text-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain:{source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:!1,expression:{interpolated:!0,parameters:["zoom"]}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}};const Oa=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function ft(M,et){const Bt={};for(const et in M)"ref"!==et&&(Bt[et]=M[et]);return Oa.forEach((M=>{M in et&&(Bt[M]=et[M])})),Bt}function dt(M,et){if(Array.isArray(M)){if(!Array.isArray(et)||M.length!==et.length)return!1;for(let Bt=0;Bt`:"value"===M.itemType.kind?"array":`array<${et}>`}return M.kind}const Nl=[$a,Al,Sl,Zl,Gl,Rl,El,Tl,Rt(Vl),Jl,Ll,Dl];function Ut(M,et){if("error"===et.kind)return null;if("array"===M.kind){if("array"===et.kind&&(0===et.N&&"value"===et.itemType.kind||!Ut(M.itemType,et.itemType))&&("number"!=typeof M.N||M.N===et.N))return null}else{if(M.kind===et.kind)return null;if("value"===M.kind)for(const M of Nl)if(!Ut(M,et))return null}return`Expected ${jt(M)} but found ${jt(et)} instead.`}function qt(M,et){return et.some((et=>et.kind===M.kind))}function Gt(M,et){return et.some((et=>"null"===et?null===M:"array"===et?Array.isArray(M):"object"===et?M&&!Array.isArray(M)&&"object"==typeof M:et===typeof M))}function Zt(M,et){return"array"===M.kind&&"array"===et.kind?M.itemType.kind===et.itemType.kind&&"number"==typeof M.N:M.kind===et.kind}const Yl=.96422,Ol=.82521,jl=4/29,Ul=6/29,ql=3*Ul*Ul,$l=Ul*Ul*Ul,tc=Math.PI/180,ec=180/Math.PI;function ee(M){return(M%=360)<0&&(M+=360),M}function re([M,et,Bt,Wt]){let Nt,$t;const Gr=ie((.2225045*(M=ne(M))+.7168786*(et=ne(et))+.0606169*(Bt=ne(Bt)))/1);M===et&&et===Bt?Nt=$t=Gr:(Nt=ie((.4360747*M+.3850649*et+.1430804*Bt)/Yl),$t=ie((.0139322*M+.0971045*et+.7141733*Bt)/Ol));const mn=116*Gr-16;return[mn<0?0:mn,500*(Nt-Gr),200*(Gr-$t),Wt]}function ne(M){return M<=.04045?M/12.92:Math.pow((M+.055)/1.055,2.4)}function ie(M){return M>$l?Math.pow(M,1/3):M/ql+jl}function se([M,et,Bt,Wt]){let Nt=(M+16)/116,$t=isNaN(et)?Nt:Nt+et/500,Gr=isNaN(Bt)?Nt:Nt-Bt/200;return Nt=1*oe(Nt),$t=Yl*oe($t),Gr=Ol*oe(Gr),[ae(3.1338561*$t-1.6168667*Nt-.4906146*Gr),ae(-.9787684*$t+1.9161415*Nt+.033454*Gr),ae(.0719453*$t-.2289914*Nt+1.4052427*Gr),Wt]}function ae(M){return(M=M<=.00304?12.92*M:1.055*Math.pow(M,1/2.4)-.055)<0?0:M>1?1:M}function oe(M){return M>Ul?M*M*M:ql*(M-jl)}function le(M){return parseInt(M.padEnd(2,M),16)/255}function ue(M,et){return ce(et?M/100:M,0,1)}function ce(M,et,Bt){return Math.min(Math.max(et,M),Bt)}function he(M){return!M.some(Number.isNaN)}const dc={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function fe(M,et,Bt){return M+Bt*(et-M)}function de(M,et,Bt){return M.map(((M,Wt)=>fe(M,et[Wt],Bt)))}class ye{constructor(M,et,Bt,Wt=1,Nt=!0){this.r=M,this.g=et,this.b=Bt,this.a=Wt,Nt||(this.r*=Wt,this.g*=Wt,this.b*=Wt,Wt||this.overwriteGetter("rgb",[M,et,Bt,Wt]))}static parse(M){if(M instanceof ye)return M;if("string"!=typeof M)return;const et=function(M){if("transparent"===(M=M.toLowerCase().trim()))return[0,0,0,0];const et=dc[M];if(et){const[M,Bt,Wt]=et;return[M/255,Bt/255,Wt/255,1]}if(M.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(M)){const et=M.length<6?1:2;let Bt=1;return[le(M.slice(Bt,Bt+=et)),le(M.slice(Bt,Bt+=et)),le(M.slice(Bt,Bt+=et)),le(M.slice(Bt,Bt+et)||"ff")]}if(M.startsWith("rgb")){const et=M.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(et){const[M,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po]=et,To=[Nt||" ",mn||" ",uo].join("");if(" "===To||" /"===To||",,"===To||",,,"===To){const M=[Wt,Gr,so].join(""),et="%%%"===M?100:""===M?255:0;if(et){const M=[ce(+Bt/et,0,1),ce(+$t/et,0,1),ce(+Hn/et,0,1),Io?ue(+Io,Po):1];if(he(M))return M}}return}}const Bt=M.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(Bt){const[M,et,Wt,Nt,$t,Gr,mn,Hn,so]=Bt,uo=[Wt||" ",$t||" ",mn].join("");if(" "===uo||" /"===uo||",,"===uo||",,,"===uo){const M=[+et,ce(+Nt,0,100),ce(+Gr,0,100),Hn?ue(+Hn,so):1];if(he(M))return function([M,et,Bt,Wt]){function i(Wt){const Nt=(Wt+M/30)%12,$t=et*Math.min(Bt,1-Bt);return Bt-$t*Math.max(-1,Math.min(Nt-3,9-Nt,1))}return M=ee(M),et/=100,Bt/=100,[i(0),i(8),i(4),Wt]}(M)}}}(M);return et?new ye(...et,!1):void 0}get rgb(){const{r:M,g:et,b:Bt,a:Wt}=this,Nt=Wt||1/0;return this.overwriteGetter("rgb",[M/Nt,et/Nt,Bt/Nt,Wt])}get hcl(){return this.overwriteGetter("hcl",function(M){const[et,Bt,Wt,Nt]=re(M),$t=Math.sqrt(Bt*Bt+Wt*Wt);return[Math.round(1e4*$t)?ee(Math.atan2(Wt,Bt)*ec):NaN,$t,et,Nt]}(this.rgb))}get lab(){return this.overwriteGetter("lab",re(this.rgb))}overwriteGetter(M,et){return Object.defineProperty(this,M,{value:et}),et}toString(){const[M,et,Bt,Wt]=this.rgb;return`rgba(${[M,et,Bt].map((M=>Math.round(255*M))).join(",")},${Wt})`}static interpolate(M,et,Bt,Wt="rgb"){switch(Wt){case"rgb":{const[Wt,Nt,$t,Gr]=de(M.rgb,et.rgb,Bt);return new ye(Wt,Nt,$t,Gr,!1)}case"hcl":{const[Wt,Nt,$t,Gr]=M.hcl,[mn,Hn,so,uo]=et.hcl;let Io,Po;if(isNaN(Wt)||isNaN(mn))isNaN(Wt)?isNaN(mn)?Io=NaN:(Io=mn,1!==$t&&0!==$t||(Po=Hn)):(Io=Wt,1!==so&&0!==so||(Po=Nt));else{let M=mn-Wt;mn>Wt&&M>180?M-=360:mn180&&(M+=360),Io=Wt+Bt*M}const[To,Eo,Ia,Ba]=function([M,et,Bt,Wt]){return M=isNaN(M)?0:M*tc,se([Bt,Math.cos(M)*et,Math.sin(M)*et,Wt])}([Io,null!=Po?Po:fe(Nt,Hn,Bt),fe($t,so,Bt),fe(Gr,uo,Bt)]);return new ye(To,Eo,Ia,Ba,!1)}case"lab":{const[Wt,Nt,$t,Gr]=se(de(M.lab,et.lab,Bt));return new ye(Wt,Nt,$t,Gr,!1)}}}}ye.black=new ye(0,0,0,1),ye.white=new ye(1,1,1,1),ye.transparent=new ye(0,0,0,0),ye.red=new ye(1,0,0,1);class me{constructor(M,et,Bt){this.sensitivity=M?et?"variant":"case":et?"accent":"base",this.locale=Bt,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(M,et){return this.collator.compare(M,et)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class ge{constructor(M,et,Bt,Wt,Nt){this.text=M,this.image=et,this.scale=Bt,this.fontStack=Wt,this.textColor=Nt}}class xe{constructor(M){this.sections=M}static fromString(M){return new xe([new ge(M,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some((M=>0!==M.text.length||M.image&&0!==M.image.name.length))}static factory(M){return M instanceof xe?M:xe.fromString(M)}toString(){return 0===this.sections.length?"":this.sections.map((M=>M.text)).join("")}}class ve{constructor(M){this.values=M.slice()}static parse(M){if(M instanceof ve)return M;if("number"==typeof M)return new ve([M,M,M,M]);if(Array.isArray(M)&&!(M.length<1||M.length>4)){for(const et of M)if("number"!=typeof et)return;switch(M.length){case 1:M=[M[0],M[0],M[0],M[0]];break;case 2:M=[M[0],M[1],M[0],M[1]];break;case 3:M=[M[0],M[1],M[2],M[1]]}return new ve(M)}}toString(){return JSON.stringify(this.values)}static interpolate(M,et,Bt){return new ve(de(M.values,et.values,Bt))}}class be{constructor(M){this.name="ExpressionEvaluationError",this.message=M}toJSON(){return this.message}}const Ic=new Set(["center","left","right","top","bottom","top-left","top-right","bottom-left","bottom-right"]);class _e{constructor(M){this.values=M.slice()}static parse(M){if(M instanceof _e)return M;if(Array.isArray(M)&&!(M.length<1)&&M.length%2==0){for(let et=0;et=0&&M<=255&&"number"==typeof et&&et>=0&&et<=255&&"number"==typeof Bt&&Bt>=0&&Bt<=255?void 0===Wt||"number"==typeof Wt&&Wt>=0&&Wt<=1?null:`Invalid rgba value [${[M,et,Bt,Wt].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof Wt?[M,et,Bt,Wt]:[M,et,Bt]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Me(M){if(null===M||"string"==typeof M||"boolean"==typeof M||"number"==typeof M||M instanceof Ae||M instanceof ye||M instanceof me||M instanceof xe||M instanceof ve||M instanceof _e||M instanceof Se)return!0;if(Array.isArray(M)){for(const et of M)if(!Me(et))return!1;return!0}if("object"==typeof M){for(const et in M)if(!Me(M[et]))return!1;return!0}return!1}function Ie(M){if(null===M)return $a;if("string"==typeof M)return Sl;if("boolean"==typeof M)return Zl;if("number"==typeof M)return Al;if(M instanceof ye)return Gl;if(M instanceof Ae)return Rl;if(M instanceof me)return Wl;if(M instanceof xe)return El;if(M instanceof ve)return Jl;if(M instanceof _e)return Dl;if(M instanceof Se)return Ll;if(Array.isArray(M)){const et=M.length;let Bt;for(const et of M){const M=Ie(et);if(Bt){if(Bt===M)continue;Bt=Vl;break}Bt=M}return Rt(Bt||Vl,et)}return Tl}function ze(M){const et=typeof M;return null===M?"":"string"===et||"number"===et||"boolean"===et?String(M):M instanceof ye||M instanceof Ae||M instanceof xe||M instanceof ve||M instanceof _e||M instanceof Se?M.toString():JSON.stringify(M)}class Pe{constructor(M,et){this.type=M,this.value=et}static parse(M,et){if(2!==M.length)return et.error(`'literal' expression requires exactly one argument, but found ${M.length-1} instead.`);if(!Me(M[1]))return et.error("invalid value");const Bt=M[1];let Wt=Ie(Bt);const Nt=et.expectedType;return"array"!==Wt.kind||0!==Wt.N||!Nt||"array"!==Nt.kind||"number"==typeof Nt.N&&0!==Nt.N||(Wt=Nt),new Pe(Wt,Bt)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}}const fc={string:Sl,number:Al,boolean:Zl,object:Tl};class Be{constructor(M,et){this.type=M,this.args=et}static parse(M,et){if(M.length<2)return et.error("Expected at least one argument.");let Bt,Wt=1;const Nt=M[0];if("array"===Nt){let Nt,$t;if(M.length>2){const Bt=M[1];if("string"!=typeof Bt||!(Bt in fc)||"object"===Bt)return et.error('The item type argument of "array" must be one of string, number, boolean',1);Nt=fc[Bt],Wt++}else Nt=Vl;if(M.length>3){if(null!==M[2]&&("number"!=typeof M[2]||M[2]<0||M[2]!==Math.floor(M[2])))return et.error('The length argument to "array" must be a positive integer literal',2);$t=M[2],Wt++}Bt=Rt(Nt,$t)}else{if(!fc[Nt])throw new Error(`Types doesn't contain name = ${Nt}`);Bt=fc[Nt]}const $t=[];for(;WtM.outputDefined()))}}const yc={"to-boolean":Zl,"to-color":Gl,"to-number":Al,"to-string":Sl};class Ee{constructor(M,et){this.type=M,this.args=et}static parse(M,et){if(M.length<2)return et.error("Expected at least one argument.");const Bt=M[0];if(!yc[Bt])throw new Error(`Can't parse ${Bt} as it is not part of the known types`);if(("to-boolean"===Bt||"to-string"===Bt)&&2!==M.length)return et.error("Expected one argument.");const Wt=yc[Bt],Nt=[];for(let Bt=1;Bt4?`Invalid rgba value ${JSON.stringify(et)}: expected an array containing either three or four numeric values.`:ke(et[0],et[1],et[2],et[3]),!Bt))return new ye(et[0]/255,et[1]/255,et[2]/255,et[3])}throw new be(Bt||`Could not parse color from value '${"string"==typeof et?et:JSON.stringify(et)}'`)}case"padding":{let et;for(const Bt of this.args){et=Bt.evaluate(M);const Wt=ve.parse(et);if(Wt)return Wt}throw new be(`Could not parse padding from value '${"string"==typeof et?et:JSON.stringify(et)}'`)}case"variableAnchorOffsetCollection":{let et;for(const Bt of this.args){et=Bt.evaluate(M);const Wt=_e.parse(et);if(Wt)return Wt}throw new be(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof et?et:JSON.stringify(et)}'`)}case"number":{let et=null;for(const Bt of this.args){if(et=Bt.evaluate(M),null===et)return 0;const Wt=Number(et);if(!isNaN(Wt))return Wt}throw new be(`Could not convert ${JSON.stringify(et)} to number.`)}case"formatted":return xe.fromString(ze(this.args[0].evaluate(M)));case"resolvedImage":return Se.fromString(ze(this.args[0].evaluate(M)));case"projectionDefinition":return this.args[0].evaluate(M);default:return ze(this.args[0].evaluate(M))}}eachChild(M){this.args.forEach(M)}outputDefined(){return this.args.every((M=>M.outputDefined()))}}function Te(M,et,Bt=0,Wt=M.length-1,Nt=$e){for(;Wt>Bt;){if(Wt-Bt>600){const $t=Wt-Bt+1,Gr=et-Bt+1,mn=Math.log($t),Hn=.5*Math.exp(2*mn/3),so=.5*Math.sqrt(mn*Hn*($t-Hn)/$t)*(Gr-$t/2<0?-1:1);Te(M,et,Math.max(Bt,Math.floor(et-Gr*Hn/$t+so)),Math.min(Wt,Math.floor(et+($t-Gr)*Hn/$t+so)),Nt)}const $t=M[et];let Gr=Bt,mn=Wt;for(Fe(M,Bt,et),Nt(M[Wt],$t)>0&&Fe(M,Bt,Wt);Gr0;)mn--}0===Nt(M[Bt],$t)?Fe(M,Bt,mn):(mn++,Fe(M,mn,Wt)),mn<=et&&(Bt=mn+1),et<=mn&&(Wt=mn-1)}}function Fe(M,et,Bt){const Wt=M[et];M[et]=M[Bt],M[Bt]=Wt}function $e(M,et){return Met?1:0}function Le(M,et){if(M.length<=1)return[M];const Bt=[];let Wt,Nt;for(const et of M){const M=Oe(et);0!==M&&(et.area=Math.abs(M),void 0===Nt&&(Nt=M<0),Nt===M<0?(Wt&&Bt.push(Wt),Wt=[et]):Wt.push(et))}if(Wt&&Bt.push(Wt),et>1)for(let M=0;M`[${M}]`)).join(""),this.scope=Nt,this.errors=$t,this.expectedType=Wt,this._isConstant=et}parse(M,et,Bt,Wt,Nt={}){return et?this.concat(et,Bt,Wt)._parse(M,Nt):this._parse(M,Nt)}_parse(M,et){function r(M,et,Bt){return"assert"===Bt?new Be(et,[M]):"coerce"===Bt?new Ee(et,[M]):M}if(null!==M&&"string"!=typeof M&&"boolean"!=typeof M&&"number"!=typeof M||(M=["literal",M]),Array.isArray(M)){if(0===M.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const Bt=M[0];if("string"!=typeof Bt)return this.error(`Expression name must be a string, but found ${typeof Bt} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const Wt=this.registry[Bt];if(Wt){let Bt=Wt.parse(M,this);if(!Bt)return null;if(this.expectedType){const M=this.expectedType,Wt=Bt.type;if("string"!==M.kind&&"number"!==M.kind&&"boolean"!==M.kind&&"object"!==M.kind&&"array"!==M.kind||"value"!==Wt.kind)if("projectionDefinition"!==M.kind||"string"!==Wt.kind&&"array"!==Wt.kind)if("color"!==M.kind&&"formatted"!==M.kind&&"resolvedImage"!==M.kind||"value"!==Wt.kind&&"string"!==Wt.kind)if("padding"!==M.kind||"value"!==Wt.kind&&"number"!==Wt.kind&&"array"!==Wt.kind)if("variableAnchorOffsetCollection"!==M.kind||"value"!==Wt.kind&&"array"!==Wt.kind){if(this.checkSubtype(M,Wt))return null}else Bt=r(Bt,M,et.typeAnnotation||"coerce");else Bt=r(Bt,M,et.typeAnnotation||"coerce");else Bt=r(Bt,M,et.typeAnnotation||"coerce");else Bt=r(Bt,M,et.typeAnnotation||"coerce");else Bt=r(Bt,M,et.typeAnnotation||"assert")}if(!(Bt instanceof Pe)&&"resolvedImage"!==Bt.type.kind&&this._isConstant(Bt)){const et=new Ne;try{Bt=new Pe(Bt.type,Bt.evaluate(et))}catch(M){return this.error(M.message),null}}return Bt}return this.error(`Unknown expression "${Bt}". If you wanted a literal array, use ["literal", [...]].`,0)}return this.error(void 0===M?"'undefined' value invalid. Use null instead.":"object"==typeof M?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof M} instead.`)}concat(M,et,Bt){const Wt="number"==typeof M?this.path.concat(M):this.path,Nt=Bt?this.scope.concat(Bt):this.scope;return new Ue(this.registry,this._isConstant,Wt,et||null,Nt,this.errors)}error(M,...et){const Bt=`${this.key}${et.map((M=>`[${M}]`)).join("")}`;this.errors.push(new kt(Bt,M))}checkSubtype(M,et){const Bt=Ut(M,et);return Bt&&this.error(Bt),Bt}}class qe{constructor(M,et){this.type=et.type,this.bindings=[].concat(M),this.result=et}evaluate(M){return this.result.evaluate(M)}eachChild(M){for(const et of this.bindings)M(et[1]);M(this.result)}static parse(M,et){if(M.length<4)return et.error(`Expected at least 3 arguments, but found ${M.length-1} instead.`);const Bt=[];for(let Wt=1;Wt=Bt.length)throw new be(`Array index out of bounds: ${et} > ${Bt.length-1}.`);if(et!==Math.floor(et))throw new be(`Array index must be an integer, but found ${et} instead.`);return Bt[et]}eachChild(M){M(this.index),M(this.input)}outputDefined(){return!1}}class Xe{constructor(M,et){this.type=Zl,this.needle=M,this.haystack=et}static parse(M,et){if(3!==M.length)return et.error(`Expected 2 arguments, but found ${M.length-1} instead.`);const Bt=et.parse(M[1],1,Vl),Wt=et.parse(M[2],2,Vl);return Bt&&Wt?qt(Bt.type,[Zl,Sl,Al,$a,Vl])?new Xe(Bt,Wt):et.error(`Expected first argument to be of type boolean, string, number or null, but found ${jt(Bt.type)} instead`):null}evaluate(M){const et=this.needle.evaluate(M),Bt=this.haystack.evaluate(M);if(!Bt)return!1;if(!Gt(et,["boolean","string","number","null"]))throw new be(`Expected first argument to be of type boolean, string, number or null, but found ${jt(Ie(et))} instead.`);if(!Gt(Bt,["string","array"]))throw new be(`Expected second argument to be of type array or string, but found ${jt(Ie(Bt))} instead.`);return Bt.indexOf(et)>=0}eachChild(M){M(this.needle),M(this.haystack)}outputDefined(){return!0}}class Ke{constructor(M,et,Bt){this.type=Al,this.needle=M,this.haystack=et,this.fromIndex=Bt}static parse(M,et){if(M.length<=2||M.length>=5)return et.error(`Expected 3 or 4 arguments, but found ${M.length-1} instead.`);const Bt=et.parse(M[1],1,Vl),Wt=et.parse(M[2],2,Vl);if(!Bt||!Wt)return null;if(!qt(Bt.type,[Zl,Sl,Al,$a,Vl]))return et.error(`Expected first argument to be of type boolean, string, number or null, but found ${jt(Bt.type)} instead`);if(4===M.length){const Nt=et.parse(M[3],3,Al);return Nt?new Ke(Bt,Wt,Nt):null}return new Ke(Bt,Wt)}evaluate(M){const et=this.needle.evaluate(M),Bt=this.haystack.evaluate(M);if(!Gt(et,["boolean","string","number","null"]))throw new be(`Expected first argument to be of type boolean, string, number or null, but found ${jt(Ie(et))} instead.`);let Wt;if(this.fromIndex&&(Wt=this.fromIndex.evaluate(M)),Gt(Bt,["string"])){const M=Bt.indexOf(et,Wt);return-1===M?-1:[...Bt.slice(0,M)].length}if(Gt(Bt,["array"]))return Bt.indexOf(et,Wt);throw new be(`Expected second argument to be of type array or string, but found ${jt(Ie(Bt))} instead.`)}eachChild(M){M(this.needle),M(this.haystack),this.fromIndex&&M(this.fromIndex)}outputDefined(){return!1}}class He{constructor(M,et,Bt,Wt,Nt,$t){this.inputType=M,this.type=et,this.input=Bt,this.cases=Wt,this.outputs=Nt,this.otherwise=$t}static parse(M,et){if(M.length<5)return et.error(`Expected at least 4 arguments, but found only ${M.length-1}.`);if(M.length%2!=1)return et.error("Expected an even number of arguments.");let Bt,Wt;et.expectedType&&"value"!==et.expectedType.kind&&(Wt=et.expectedType);const Nt={},$t=[];for(let Gr=2;GrNumber.MAX_SAFE_INTEGER)return so.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof M&&Math.floor(M)!==M)return so.error("Numeric branch labels must be integer values.");if(Bt){if(so.checkSubtype(Bt,Ie(M)))return null}else Bt=Ie(M);if(void 0!==Nt[String(M)])return so.error("Branch labels must be unique.");Nt[String(M)]=$t.length}const uo=et.parse(Hn,Gr,Wt);if(!uo)return null;Wt=Wt||uo.type,$t.push(uo)}const Gr=et.parse(M[1],1,Vl);if(!Gr)return null;const mn=et.parse(M[M.length-1],M.length-1,Wt);return mn?"value"!==Gr.type.kind&&et.concat(1).checkSubtype(Bt,Gr.type)?null:new He(Bt,Wt,Gr,Nt,$t,mn):null}evaluate(M){const et=this.input.evaluate(M);return(Ie(et)===this.inputType&&this.outputs[this.cases[et]]||this.otherwise).evaluate(M)}eachChild(M){M(this.input),this.outputs.forEach(M),M(this.otherwise)}outputDefined(){return this.outputs.every((M=>M.outputDefined()))&&this.otherwise.outputDefined()}}class Ye{constructor(M,et,Bt){this.type=M,this.branches=et,this.otherwise=Bt}static parse(M,et){if(M.length<4)return et.error(`Expected at least 3 arguments, but found only ${M.length-1}.`);if(M.length%2!=0)return et.error("Expected an odd number of arguments.");let Bt;et.expectedType&&"value"!==et.expectedType.kind&&(Bt=et.expectedType);const Wt=[];for(let Nt=1;Ntet.outputDefined()))&&this.otherwise.outputDefined()}}class Je{constructor(M,et,Bt,Wt){this.type=M,this.input=et,this.beginIndex=Bt,this.endIndex=Wt}static parse(M,et){if(M.length<=2||M.length>=5)return et.error(`Expected 3 or 4 arguments, but found ${M.length-1} instead.`);const Bt=et.parse(M[1],1,Vl),Wt=et.parse(M[2],2,Al);if(!Bt||!Wt)return null;if(!qt(Bt.type,[Rt(Vl),Sl,Vl]))return et.error(`Expected first argument to be of type array or string, but found ${jt(Bt.type)} instead`);if(4===M.length){const Nt=et.parse(M[3],3,Al);return Nt?new Je(Bt.type,Bt,Wt,Nt):null}return new Je(Bt.type,Bt,Wt)}evaluate(M){const et=this.input.evaluate(M),Bt=this.beginIndex.evaluate(M);let Wt;if(this.endIndex&&(Wt=this.endIndex.evaluate(M)),Gt(et,["string"]))return[...et].slice(Bt,Wt).join("");if(Gt(et,["array"]))return et.slice(Bt,Wt);throw new be(`Expected first argument to be of type array or string, but found ${jt(Ie(et))} instead.`)}eachChild(M){M(this.input),M(this.beginIndex),this.endIndex&&M(this.endIndex)}outputDefined(){return!1}}function We(M,et){const Bt=M.length-1;let Wt,Nt,$t=0,Gr=Bt,mn=0;for(;$t<=Gr;)if(mn=Math.floor(($t+Gr)/2),Wt=M[mn],Nt=M[mn+1],Wt<=et){if(mn===Bt||etet))throw new be("Input is not a number.");Gr=mn-1}return 0}class Qe{constructor(M,et,Bt){this.type=M,this.input=et,this.labels=[],this.outputs=[];for(const[M,et]of Bt)this.labels.push(M),this.outputs.push(et)}static parse(M,et){if(M.length-1<4)return et.error(`Expected at least 4 arguments, but found only ${M.length-1}.`);if((M.length-1)%2!=0)return et.error("Expected an even number of arguments.");const Bt=et.parse(M[1],1,Al);if(!Bt)return null;const Wt=[];let Nt=null;et.expectedType&&"value"!==et.expectedType.kind&&(Nt=et.expectedType);for(let Bt=1;Bt=$t)return et.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',mn);const so=et.parse(Gr,Hn,Nt);if(!so)return null;Nt=Nt||so.type,Wt.push([$t,so])}return new Qe(Nt,Bt,Wt)}evaluate(M){const et=this.labels,Bt=this.outputs;if(1===et.length)return Bt[0].evaluate(M);const Wt=this.input.evaluate(M);if(Wt<=et[0])return Bt[0].evaluate(M);const Nt=et.length;return Wt>=et[Nt-1]?Bt[Nt-1].evaluate(M):Bt[We(et,Wt)].evaluate(M)}eachChild(M){M(this.input);for(const et of this.outputs)M(et)}outputDefined(){return this.outputs.every((M=>M.outputDefined()))}}function tr(M){return M&&M.__esModule&&Object.prototype.hasOwnProperty.call(M,"default")?M.default:M}var Bc,Tc,Mc=function(){if(Tc)return Bc;function t(M,et,Bt,Wt){this.cx=3*M,this.bx=3*(Bt-M)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*et,this.by=3*(Wt-et)-this.cy,this.ay=1-this.cy-this.by,this.p1x=M,this.p1y=et,this.p2x=Bt,this.p2y=Wt}return Tc=1,Bc=t,t.prototype={sampleCurveX:function(M){return((this.ax*M+this.bx)*M+this.cx)*M},sampleCurveY:function(M){return((this.ay*M+this.by)*M+this.cy)*M},sampleCurveDerivativeX:function(M){return(3*this.ax*M+2*this.bx)*M+this.cx},solveCurveX:function(M,et){if(void 0===et&&(et=1e-6),M<0)return 0;if(M>1)return 1;for(var Bt=M,Wt=0;Wt<8;Wt++){var Nt=this.sampleCurveX(Bt)-M;if(Math.abs(Nt)Nt?Gr=Bt:mn=Bt,Bt=.5*(mn-Gr)+Gr;return Bt},solve:function(M,et){return this.sampleCurveY(this.solveCurveX(M,et))}},Bc}(),Vc=tr(Mc);class sr{constructor(M,et,Bt,Wt,Nt){this.type=M,this.operator=et,this.interpolation=Bt,this.input=Wt,this.labels=[],this.outputs=[];for(const[M,et]of Nt)this.labels.push(M),this.outputs.push(et)}static interpolationFactor(M,et,Bt,Wt){let Nt=0;if("exponential"===M.name)Nt=ar(et,M.base,Bt,Wt);else if("linear"===M.name)Nt=ar(et,1,Bt,Wt);else if("cubic-bezier"===M.name){const $t=M.controlPoints;Nt=new Vc($t[0],$t[1],$t[2],$t[3]).solve(ar(et,1,Bt,Wt))}return Nt}static parse(M,et){let[Bt,Wt,Nt,...$t]=M;if(!Array.isArray(Wt)||0===Wt.length)return et.error("Expected an interpolation type expression.",1);if("linear"===Wt[0])Wt={name:"linear"};else if("exponential"===Wt[0]){const M=Wt[1];if("number"!=typeof M)return et.error("Exponential interpolation requires a numeric base.",1,1);Wt={name:"exponential",base:M}}else{if("cubic-bezier"!==Wt[0])return et.error(`Unknown interpolation type ${String(Wt[0])}`,1,0);{const M=Wt.slice(1);if(4!==M.length||M.some((M=>"number"!=typeof M||M<0||M>1)))return et.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);Wt={name:"cubic-bezier",controlPoints:M}}}if(M.length-1<4)return et.error(`Expected at least 4 arguments, but found only ${M.length-1}.`);if((M.length-1)%2!=0)return et.error("Expected an even number of arguments.");if(Nt=et.parse(Nt,2,Al),!Nt)return null;const Gr=[];let mn=null;"interpolate-hcl"===Bt||"interpolate-lab"===Bt?mn=Gl:et.expectedType&&"value"!==et.expectedType.kind&&(mn=et.expectedType);for(let M=0;M<$t.length;M+=2){const Bt=$t[M],Wt=$t[M+1],Nt=M+3,Hn=M+4;if("number"!=typeof Bt)return et.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.',Nt);if(Gr.length&&Gr[Gr.length-1][0]>=Bt)return et.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',Nt);const so=et.parse(Wt,Hn,mn);if(!so)return null;mn=mn||so.type,Gr.push([Bt,so])}return Zt(mn,Al)||Zt(mn,Rl)||Zt(mn,Gl)||Zt(mn,Jl)||Zt(mn,Dl)||Zt(mn,Rt(Al))?new sr(mn,Bt,Wt,Nt,Gr):et.error(`Type ${jt(mn)} is not interpolatable.`)}evaluate(M){const et=this.labels,Bt=this.outputs;if(1===et.length)return Bt[0].evaluate(M);const Wt=this.input.evaluate(M);if(Wt<=et[0])return Bt[0].evaluate(M);const Nt=et.length;if(Wt>=et[Nt-1])return Bt[Nt-1].evaluate(M);const $t=We(et,Wt),Gr=sr.interpolationFactor(this.interpolation,Wt,et[$t],et[$t+1]),mn=Bt[$t].evaluate(M),Hn=Bt[$t+1].evaluate(M);switch(this.operator){case"interpolate":switch(this.type.kind){case"number":return fe(mn,Hn,Gr);case"color":return ye.interpolate(mn,Hn,Gr);case"padding":return ve.interpolate(mn,Hn,Gr);case"variableAnchorOffsetCollection":return _e.interpolate(mn,Hn,Gr);case"array":return de(mn,Hn,Gr);case"projectionDefinition":return Ae.interpolate(mn,Hn,Gr)}case"interpolate-hcl":return ye.interpolate(mn,Hn,Gr,"hcl");case"interpolate-lab":return ye.interpolate(mn,Hn,Gr,"lab")}}eachChild(M){M(this.input);for(const et of this.outputs)M(et)}outputDefined(){return this.outputs.every((M=>M.outputDefined()))}}function ar(M,et,Bt,Wt){const Nt=Wt-Bt,$t=M-Bt;return 0===Nt?0:1===et?$t/Nt:(Math.pow(et,$t)-1)/(Math.pow(et,Nt)-1)}const zc={color:ye.interpolate,number:fe,padding:ve.interpolate,variableAnchorOffsetCollection:_e.interpolate,array:de};class lr{constructor(M,et){this.type=M,this.args=et}static parse(M,et){if(M.length<2)return et.error("Expected at least one argument.");let Bt=null;const Wt=et.expectedType;Wt&&"value"!==Wt.kind&&(Bt=Wt);const Nt=[];for(const Wt of M.slice(1)){const M=et.parse(Wt,1+Nt.length,Bt,void 0,{typeAnnotation:"omit"});if(!M)return null;Bt=Bt||M.type,Nt.push(M)}if(!Bt)throw new Error("No output type");const $t=Wt&&Nt.some((M=>Ut(Wt,M.type)));return new lr($t?Vl:Bt,Nt)}evaluate(M){let et,Bt=null,Wt=0;for(const Nt of this.args)if(Wt++,Bt=Nt.evaluate(M),Bt&&Bt instanceof Se&&!Bt.available&&(et||(et=Bt.name),Bt=null,Wt===this.args.length&&(Bt=et)),null!==Bt)break;return Bt}eachChild(M){this.args.forEach(M)}outputDefined(){return this.args.every((M=>M.outputDefined()))}}function ur(M,et){return"=="===M||"!="===M?"boolean"===et.kind||"string"===et.kind||"number"===et.kind||"null"===et.kind||"value"===et.kind:"string"===et.kind||"number"===et.kind||"value"===et.kind}function cr(M,et,Bt,Wt){return 0===Wt.compare(et,Bt)}function hr(M,et,Bt){const Wt="=="!==M&&"!="!==M;return class i{constructor(M,et,Bt){this.type=Zl,this.lhs=M,this.rhs=et,this.collator=Bt,this.hasUntypedArgument="value"===M.type.kind||"value"===et.type.kind}static parse(M,et){if(3!==M.length&&4!==M.length)return et.error("Expected two or three arguments.");const Bt=M[0];let Nt=et.parse(M[1],1,Vl);if(!Nt)return null;if(!ur(Bt,Nt.type))return et.concat(1).error(`"${Bt}" comparisons are not supported for type '${jt(Nt.type)}'.`);let $t=et.parse(M[2],2,Vl);if(!$t)return null;if(!ur(Bt,$t.type))return et.concat(2).error(`"${Bt}" comparisons are not supported for type '${jt($t.type)}'.`);if(Nt.type.kind!==$t.type.kind&&"value"!==Nt.type.kind&&"value"!==$t.type.kind)return et.error(`Cannot compare types '${jt(Nt.type)}' and '${jt($t.type)}'.`);Wt&&("value"===Nt.type.kind&&"value"!==$t.type.kind?Nt=new Be($t.type,[Nt]):"value"!==Nt.type.kind&&"value"===$t.type.kind&&($t=new Be(Nt.type,[$t])));let Gr=null;if(4===M.length){if("string"!==Nt.type.kind&&"string"!==$t.type.kind&&"value"!==Nt.type.kind&&"value"!==$t.type.kind)return et.error("Cannot use collator to compare non-string types.");if(Gr=et.parse(M[3],3,Wl),!Gr)return null}return new i(Nt,$t,Gr)}evaluate(Nt){const $t=this.lhs.evaluate(Nt),Gr=this.rhs.evaluate(Nt);if(Wt&&this.hasUntypedArgument){const et=Ie($t),Bt=Ie(Gr);if(et.kind!==Bt.kind||"string"!==et.kind&&"number"!==et.kind)throw new be(`Expected arguments for "${M}" to be (string, string) or (number, number), but found (${et.kind}, ${Bt.kind}) instead.`)}if(this.collator&&!Wt&&this.hasUntypedArgument){const M=Ie($t),Bt=Ie(Gr);if("string"!==M.kind||"string"!==Bt.kind)return et(Nt,$t,Gr)}return this.collator?Bt(Nt,$t,Gr,this.collator.evaluate(Nt)):et(Nt,$t,Gr)}eachChild(M){M(this.lhs),M(this.rhs),this.collator&&M(this.collator)}outputDefined(){return!0}}}const Fc=hr("==",(function(M,et,Bt){return et===Bt}),cr),Oc=hr("!=",(function(M,et,Bt){return et!==Bt}),(function(M,et,Bt,Wt){return!cr(0,et,Bt,Wt)})),jc=hr("<",(function(M,et,Bt){return et",(function(M,et,Bt){return et>Bt}),(function(M,et,Bt,Wt){return Wt.compare(et,Bt)>0})),Ih=hr("<=",(function(M,et,Bt){return et<=Bt}),(function(M,et,Bt,Wt){return Wt.compare(et,Bt)<=0})),Zh=hr(">=",(function(M,et,Bt){return et>=Bt}),(function(M,et,Bt,Wt){return Wt.compare(et,Bt)>=0}));class xr{constructor(M,et,Bt){this.type=Wl,this.locale=Bt,this.caseSensitive=M,this.diacriticSensitive=et}static parse(M,et){if(2!==M.length)return et.error("Expected one argument.");const Bt=M[1];if("object"!=typeof Bt||Array.isArray(Bt))return et.error("Collator options argument must be an object.");const Wt=et.parse(void 0!==Bt["case-sensitive"]&&Bt["case-sensitive"],1,Zl);if(!Wt)return null;const Nt=et.parse(void 0!==Bt["diacritic-sensitive"]&&Bt["diacritic-sensitive"],1,Zl);if(!Nt)return null;let $t=null;return Bt.locale&&($t=et.parse(Bt.locale,1,Sl),!$t)?null:new xr(Wt,Nt,$t)}evaluate(M){return new me(this.caseSensitive.evaluate(M),this.diacriticSensitive.evaluate(M),this.locale?this.locale.evaluate(M):null)}eachChild(M){M(this.caseSensitive),M(this.diacriticSensitive),this.locale&&M(this.locale)}outputDefined(){return!1}}class vr{constructor(M,et,Bt,Wt,Nt){this.type=Sl,this.number=M,this.locale=et,this.currency=Bt,this.minFractionDigits=Wt,this.maxFractionDigits=Nt}static parse(M,et){if(3!==M.length)return et.error("Expected two arguments.");const Bt=et.parse(M[1],1,Al);if(!Bt)return null;const Wt=M[2];if("object"!=typeof Wt||Array.isArray(Wt))return et.error("NumberFormat options argument must be an object.");let Nt=null;if(Wt.locale&&(Nt=et.parse(Wt.locale,1,Sl),!Nt))return null;let $t=null;if(Wt.currency&&($t=et.parse(Wt.currency,1,Sl),!$t))return null;let Gr=null;if(Wt["min-fraction-digits"]&&(Gr=et.parse(Wt["min-fraction-digits"],1,Al),!Gr))return null;let mn=null;return Wt["max-fraction-digits"]&&(mn=et.parse(Wt["max-fraction-digits"],1,Al),!mn)?null:new vr(Bt,Nt,$t,Gr,mn)}evaluate(M){return new Intl.NumberFormat(this.locale?this.locale.evaluate(M):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(M):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(M):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(M):void 0}).format(this.number.evaluate(M))}eachChild(M){M(this.number),this.locale&&M(this.locale),this.currency&&M(this.currency),this.minFractionDigits&&M(this.minFractionDigits),this.maxFractionDigits&&M(this.maxFractionDigits)}outputDefined(){return!1}}class br{constructor(M){this.type=El,this.sections=M}static parse(M,et){if(M.length<2)return et.error("Expected at least one argument.");const Bt=M[1];if(!Array.isArray(Bt)&&"object"==typeof Bt)return et.error("First argument must be an image or text section.");const Wt=[];let Nt=!1;for(let Bt=1;Bt<=M.length-1;++Bt){const $t=M[Bt];if(Nt&&"object"==typeof $t&&!Array.isArray($t)){Nt=!1;let M=null;if($t["font-scale"]&&(M=et.parse($t["font-scale"],1,Al),!M))return null;let Bt=null;if($t["text-font"]&&(Bt=et.parse($t["text-font"],1,Rt(Sl)),!Bt))return null;let Gr=null;if($t["text-color"]&&(Gr=et.parse($t["text-color"],1,Gl),!Gr))return null;const mn=Wt[Wt.length-1];mn.scale=M,mn.font=Bt,mn.textColor=Gr}else{const $t=et.parse(M[Bt],1,Vl);if(!$t)return null;const Gr=$t.type.kind;if("string"!==Gr&&"value"!==Gr&&"null"!==Gr&&"resolvedImage"!==Gr)return et.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");Nt=!0,Wt.push({content:$t,scale:null,font:null,textColor:null})}}return new br(Wt)}evaluate(M){return new xe(this.sections.map((et=>{const Bt=et.content.evaluate(M);return Ie(Bt)===Ll?new ge("",Bt,null,null,null):new ge(ze(Bt),null,et.scale?et.scale.evaluate(M):null,et.font?et.font.evaluate(M).join(","):null,et.textColor?et.textColor.evaluate(M):null)})))}eachChild(M){for(const et of this.sections)M(et.content),et.scale&&M(et.scale),et.font&&M(et.font),et.textColor&&M(et.textColor)}outputDefined(){return!1}}class wr{constructor(M){this.type=Ll,this.input=M}static parse(M,et){if(2!==M.length)return et.error("Expected two arguments.");const Bt=et.parse(M[1],1,Sl);return Bt?new wr(Bt):et.error("No image name provided.")}evaluate(M){const et=this.input.evaluate(M),Bt=Se.fromString(et);return Bt&&M.availableImages&&(Bt.available=M.availableImages.indexOf(et)>-1),Bt}eachChild(M){M(this.input)}outputDefined(){return!1}}class _r{constructor(M){this.type=Al,this.input=M}static parse(M,et){if(2!==M.length)return et.error(`Expected 1 argument, but found ${M.length-1} instead.`);const Bt=et.parse(M[1],1);return Bt?"array"!==Bt.type.kind&&"string"!==Bt.type.kind&&"value"!==Bt.type.kind?et.error(`Expected argument of type string or array, but found ${jt(Bt.type)} instead.`):new _r(Bt):null}evaluate(M){const et=this.input.evaluate(M);if("string"==typeof et)return[...et].length;if(Array.isArray(et))return et.length;throw new be(`Expected value to be of type string or array, but found ${jt(Ie(et))} instead.`)}eachChild(M){M(this.input)}outputDefined(){return!1}}const Gh=8192;function Ar(M,et){const Bt=(180+M[0])/360,Wt=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+M[1]*Math.PI/360)))/360,Nt=Math.pow(2,et.z);return[Math.round(Bt*Nt*Gh),Math.round(Wt*Nt*Gh)]}function kr(M,et){const Bt=Math.pow(2,et.z);return[(Nt=(M[0]/Gh+et.x)/Bt,360*Nt-180),(Wt=(M[1]/Gh+et.y)/Bt,360/Math.PI*Math.atan(Math.exp((180-360*Wt)*Math.PI/180))-90)];var Wt,Nt}function Mr(M,et){M[0]=Math.min(M[0],et[0]),M[1]=Math.min(M[1],et[1]),M[2]=Math.max(M[2],et[0]),M[3]=Math.max(M[3],et[1])}function Ir(M,et){return!(M[0]<=et[0]||M[2]>=et[2]||M[1]<=et[1]||M[3]>=et[3])}function zr(M,et,Bt){const Wt=M[0]-et[0],Nt=M[1]-et[1],$t=M[0]-Bt[0],Gr=M[1]-Bt[1];return Wt*Gr-$t*Nt==0&&Wt*$t<=0&&Nt*Gr<=0}function Pr(M,et,Bt,Wt){return 0!=(Nt=[Wt[0]-Bt[0],Wt[1]-Bt[1]])[0]*($t=[et[0]-M[0],et[1]-M[1]])[1]-Nt[1]*$t[0]&&!(!Fr(M,et,Bt,Wt)||!Fr(Bt,Wt,M,et));var Nt,$t}function Cr(M,et,Bt){for(const Wt of Bt)for(let Bt=0;Bt(Nt=M)[1]!=(Gr=mn[et+1])[1]>Nt[1]&&Nt[0]<(Gr[0]-$t[0])*(Nt[1]-$t[1])/(Gr[1]-$t[1])+$t[0]&&(Wt=!Wt)}var Nt,$t,Gr;return Wt}function Vr(M,et){for(const Bt of et)if(Br(M,Bt))return!0;return!1}function Er(M,et){for(const Bt of M)if(!Br(Bt,et))return!1;for(let Bt=0;Bt0&&mn<0||Gr<0&&mn>0}function $r(M,et,Bt){const Wt=[];for(let Nt=0;NtBt[2]){const et=.5*Wt;let Nt=M[0]-Bt[0]>et?-Wt:Bt[0]-M[0]>et?Wt:0;0===Nt&&(Nt=M[0]-Bt[2]>et?-Wt:Bt[2]-M[0]>et?Wt:0),M[0]+=Nt}Mr(et,M)}function Or(M,et,Bt,Wt){const Nt=Math.pow(2,Wt.z)*Gh,$t=[Wt.x*Gh,Wt.y*Gh],Gr=[];for(const Wt of M)for(const M of Wt){const Wt=[M.x+$t[0],M.y+$t[1]];Dr(Wt,et,Bt,Nt),Gr.push(Wt)}return Gr}function Rr(M,et,Bt,Wt){const Nt=Math.pow(2,Wt.z)*Gh,$t=[Wt.x*Gh,Wt.y*Gh],Gr=[];for(const Bt of M){const M=[];for(const Wt of Bt){const Bt=[Wt.x+$t[0],Wt.y+$t[1]];Mr(et,Bt),M.push(Bt)}Gr.push(M)}if(et[2]-et[0]<=Nt/2){(mn=et)[0]=mn[1]=1/0,mn[2]=mn[3]=-1/0;for(const M of Gr)for(const Wt of M)Dr(Wt,et,Bt,Nt)}var mn;return Gr}class jr{constructor(M,et){this.type=Zl,this.geojson=M,this.geometries=et}static parse(M,et){if(2!==M.length)return et.error(`'within' expression requires exactly one argument, but found ${M.length-1} instead.`);if(Me(M[1])){const et=M[1];if("FeatureCollection"===et.type){const M=[];for(const Bt of et.features){const{type:et,coordinates:Wt}=Bt.geometry;"Polygon"===et&&M.push(Wt),"MultiPolygon"===et&&M.push(...Wt)}if(M.length)return new jr(et,{type:"MultiPolygon",coordinates:M})}else if("Feature"===et.type){const M=et.geometry.type;if("Polygon"===M||"MultiPolygon"===M)return new jr(et,et.geometry)}else if("Polygon"===et.type||"MultiPolygon"===et.type)return new jr(et,et)}return et.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(M){if(null!=M.geometry()&&null!=M.canonicalID()){if("Point"===M.geometryDollarType())return function(M,et){const Bt=[1/0,1/0,-1/0,-1/0],Wt=[1/0,1/0,-1/0,-1/0],Nt=M.canonicalID();if("Polygon"===et.type){const $t=$r(et.coordinates,Wt,Nt),Gr=Or(M.geometry(),Bt,Wt,Nt);if(!Ir(Bt,Wt))return!1;for(const M of Gr)if(!Br(M,$t))return!1}if("MultiPolygon"===et.type){const $t=Lr(et.coordinates,Wt,Nt),Gr=Or(M.geometry(),Bt,Wt,Nt);if(!Ir(Bt,Wt))return!1;for(const M of Gr)if(!Vr(M,$t))return!1}return!0}(M,this.geometries);if("LineString"===M.geometryDollarType())return function(M,et){const Bt=[1/0,1/0,-1/0,-1/0],Wt=[1/0,1/0,-1/0,-1/0],Nt=M.canonicalID();if("Polygon"===et.type){const $t=$r(et.coordinates,Wt,Nt),Gr=Rr(M.geometry(),Bt,Wt,Nt);if(!Ir(Bt,Wt))return!1;for(const M of Gr)if(!Er(M,$t))return!1}if("MultiPolygon"===et.type){const $t=Lr(et.coordinates,Wt,Nt),Gr=Rr(M.geometry(),Bt,Wt,Nt);if(!Ir(Bt,Wt))return!1;for(const M of Gr)if(!Tr(M,$t))return!1}return!0}(M,this.geometries)}return!1}eachChild(){}outputDefined(){return!0}}let Ph=class{constructor(M=[],et=(M,et)=>Met?1:0){if(this.data=M,this.length=this.data.length,this.compare=et,this.length>0)for(let M=(this.length>>1)-1;M>=0;M--)this._down(M)}push(M){this.data.push(M),this._up(this.length++)}pop(){if(0===this.length)return;const M=this.data[0],et=this.data.pop();return--this.length>0&&(this.data[0]=et,this._down(0)),M}peek(){return this.data[0]}_up(M){const{data:et,compare:Bt}=this,Wt=et[M];for(;M>0;){const Nt=M-1>>1,$t=et[Nt];if(Bt(Wt,$t)>=0)break;et[M]=$t,M=Nt}et[M]=Wt}_down(M){const{data:et,compare:Bt}=this,Wt=this.length>>1,Nt=et[M];for(;M=0)break;et[M]=et[Wt],M=Wt}et[M]=Nt}};const Wh=1/298.257223563,zh=Wh*(2-Wh),Jh=Math.PI/180;class Zr{constructor(M){const et=6378.137*Jh*1e3,Bt=Math.cos(M*Jh),Wt=1/(1-zh*(1-Bt*Bt)),Nt=Math.sqrt(Wt);this.kx=et*Nt*Bt,this.ky=et*Nt*Wt*(1-zh)}distance(M,et){const Bt=this.wrap(M[0]-et[0])*this.kx,Wt=(M[1]-et[1])*this.ky;return Math.sqrt(Bt*Bt+Wt*Wt)}pointOnLine(M,et){let Bt,Wt,Nt,$t,Gr=1/0;for(let mn=0;mn1?(Hn=M[mn+1][0],so=M[mn+1][1]):Po>0&&(Hn+=uo/this.kx*Po,so+=Io/this.ky*Po)),uo=this.wrap(et[0]-Hn)*this.kx,Io=(et[1]-so)*this.ky;const To=uo*uo+Io*Io;To180;)M-=360;return M}}function Xr(M,et){return et[0]-M[0]}function Kr(M){return M[1]-M[0]+1}function Hr(M,et){return M[1]>=M[0]&&M[1]M[1])return[null,null];const Bt=Kr(M);if(et){if(2===Bt)return[M,null];const et=Math.floor(Bt/2);return[[M[0],M[0]+et],[M[0]+et,M[1]]]}if(1===Bt)return[M,null];const Wt=Math.floor(Bt/2)-1;return[[M[0],M[0]+Wt],[M[0]+Wt+1,M[1]]]}function Jr(M,et){if(!Hr(et,M.length))return[1/0,1/0,-1/0,-1/0];const Bt=[1/0,1/0,-1/0,-1/0];for(let Wt=et[0];Wt<=et[1];++Wt)Mr(Bt,M[Wt]);return Bt}function Wr(M){const et=[1/0,1/0,-1/0,-1/0];for(const Bt of M)for(const M of Bt)Mr(et,M);return et}function Qr(M){return M[0]!==-1/0&&M[1]!==-1/0&&M[2]!==1/0&&M[3]!==1/0}function tn(M,et,Bt){if(!Qr(M)||!Qr(et))return NaN;let Wt=0,Nt=0;return M[2]et[2]&&(Wt=M[0]-et[2]),M[1]>et[3]&&(Nt=M[1]-et[3]),M[3]=Wt)return Wt;if(Ir(Nt,$t)){if(ln(M,et))return 0}else if(ln(et,M))return 0;let Gr=1/0;for(const Wt of M)for(let M=0,Nt=Wt.length,$t=Nt-1;M0;){const Nt=Gr.pop();if(Nt[0]>=$t)continue;const Hn=Nt[1],so=et?50:100;if(Kr(Hn)<=so){if(!Hr(Hn,M.length))return NaN;if(et){const et=on(M,Hn,Bt,Wt);if(isNaN(et)||0===et)return et;$t=Math.min($t,et)}else for(let et=Hn[0];et<=Hn[1];++et){const Nt=an(M[et],Bt,Wt);if($t=Math.min($t,Nt),0===$t)return 0}}else{const Bt=Yr(Hn,et);cn(Gr,$t,Wt,M,mn,Bt[0]),cn(Gr,$t,Wt,M,mn,Bt[1])}}return $t}function fn(M,et,Bt,Wt,Nt,$t=1/0){let Gr=Math.min($t,Nt.distance(M[0],Bt[0]));if(0===Gr)return Gr;const mn=new Ph([[0,[0,M.length-1],[0,Bt.length-1]]],Xr);for(;mn.length>0;){const $t=mn.pop();if($t[0]>=Gr)continue;const Hn=$t[1],so=$t[2],uo=et?50:100,Io=Wt?50:100;if(Kr(Hn)<=uo&&Kr(so)<=Io){if(!Hr(Hn,M.length)&&Hr(so,Bt.length))return NaN;let $t;if(et&&Wt)$t=nn(M,Hn,Bt,so,Nt),Gr=Math.min(Gr,$t);else if(et&&!Wt){const et=M.slice(Hn[0],Hn[1]+1);for(let M=so[0];M<=so[1];++M)if($t=en(Bt[M],et,Nt),Gr=Math.min(Gr,$t),0===Gr)return Gr}else if(!et&&Wt){const et=Bt.slice(so[0],so[1]+1);for(let Bt=Hn[0];Bt<=Hn[1];++Bt)if($t=en(M[Bt],et,Nt),Gr=Math.min(Gr,$t),0===Gr)return Gr}else $t=sn(M,Hn,Bt,so,Nt),Gr=Math.min(Gr,$t)}else{const $t=Yr(Hn,et),uo=Yr(so,Wt);hn(mn,Gr,Nt,M,Bt,$t[0],uo[0]),hn(mn,Gr,Nt,M,Bt,$t[0],uo[1]),hn(mn,Gr,Nt,M,Bt,$t[1],uo[0]),hn(mn,Gr,Nt,M,Bt,$t[1],uo[1])}}return Gr}function dn(M){return"MultiPolygon"===M.type?M.coordinates.map((M=>({type:"Polygon",coordinates:M}))):"MultiLineString"===M.type?M.coordinates.map((M=>({type:"LineString",coordinates:M}))):"MultiPoint"===M.type?M.coordinates.map((M=>({type:"Point",coordinates:M}))):[M]}class yn{constructor(M,et){this.type=Al,this.geojson=M,this.geometries=et}static parse(M,et){if(2!==M.length)return et.error(`'distance' expression requires exactly one argument, but found ${M.length-1} instead.`);if(Me(M[1])){const et=M[1];if("FeatureCollection"===et.type)return new yn(et,et.features.map((M=>dn(M.geometry))).flat());if("Feature"===et.type)return new yn(et,dn(et.geometry));if("type"in et&&"coordinates"in et)return new yn(et,dn(et))}return et.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(M){if(null!=M.geometry()&&null!=M.canonicalID()){if("Point"===M.geometryType())return function(M,et){const Bt=M.geometry(),Wt=Bt.flat().map((et=>kr([et.x,et.y],M.canonical)));if(0===Bt.length)return NaN;const Nt=new Zr(Wt[0][1]);let $t=1/0;for(const M of et){switch(M.type){case"Point":$t=Math.min($t,fn(Wt,!1,[M.coordinates],!1,Nt,$t));break;case"LineString":$t=Math.min($t,fn(Wt,!1,M.coordinates,!0,Nt,$t));break;case"Polygon":$t=Math.min($t,pn(Wt,!1,M.coordinates,Nt,$t))}if(0===$t)return $t}return $t}(M,this.geometries);if("LineString"===M.geometryType())return function(M,et){const Bt=M.geometry(),Wt=Bt.flat().map((et=>kr([et.x,et.y],M.canonical)));if(0===Bt.length)return NaN;const Nt=new Zr(Wt[0][1]);let $t=1/0;for(const M of et){switch(M.type){case"Point":$t=Math.min($t,fn(Wt,!0,[M.coordinates],!1,Nt,$t));break;case"LineString":$t=Math.min($t,fn(Wt,!0,M.coordinates,!0,Nt,$t));break;case"Polygon":$t=Math.min($t,pn(Wt,!0,M.coordinates,Nt,$t))}if(0===$t)return $t}return $t}(M,this.geometries);if("Polygon"===M.geometryType())return function(M,et){const Bt=M.geometry();if(0===Bt.length||0===Bt[0].length)return NaN;const Wt=Le(Bt,0).map((et=>et.map((et=>et.map((et=>kr([et.x,et.y],M.canonical))))))),Nt=new Zr(Wt[0][0][0][1]);let $t=1/0;for(const M of et)for(const et of Wt){switch(M.type){case"Point":$t=Math.min($t,pn([M.coordinates],!1,et,Nt,$t));break;case"LineString":$t=Math.min($t,pn(M.coordinates,!0,et,Nt,$t));break;case"Polygon":$t=Math.min($t,un(et,M.coordinates,Nt,$t))}if(0===$t)return $t}return $t}(M,this.geometries)}return NaN}eachChild(){}outputDefined(){return!0}}const Xh={"==":Fc,"!=":Oc,">":mh,"<":jc,">=":Zh,"<=":Ih,array:Be,at:Ze,boolean:Be,case:Ye,coalesce:lr,collator:xr,format:br,image:wr,in:Xe,"index-of":Ke,interpolate:sr,"interpolate-hcl":sr,"interpolate-lab":sr,length:_r,let:qe,literal:Pe,match:He,number:Be,"number-format":vr,object:Be,slice:Je,step:Qe,string:Be,"to-boolean":Ee,"to-color":Ee,"to-number":Ee,"to-string":Ee,var:Ge,within:jr,distance:yn};class gn{constructor(M,et,Bt,Wt){this.name=M,this.type=et,this._evaluate=Bt,this.args=Wt}evaluate(M){return this._evaluate(M,this.args)}eachChild(M){this.args.forEach(M)}outputDefined(){return!1}static parse(M,et){const Bt=M[0],Wt=gn.definitions[Bt];if(!Wt)return et.error(`Unknown expression "${Bt}". If you wanted a literal array, use ["literal", [...]].`,0);const Nt=Array.isArray(Wt)?Wt[0]:Wt.type,$t=Array.isArray(Wt)?[[Wt[1],Wt[2]]]:Wt.overloads,Gr=$t.filter((([et])=>!Array.isArray(et)||et.length===M.length-1));let mn=null;for(const[Wt,$t]of Gr){mn=new Ue(et.registry,_n,et.path,null,et.scope);const Gr=[];let Hn=!1;for(let et=1;et{return et=M,Array.isArray(et)?`(${et.map(jt).join(", ")})`:`(${jt(et.type)}...)`;var et})).join(" | "),Wt=[];for(let Bt=1;Bt{Bt=et?Bt&&_n(M):Bt&&M instanceof Pe})),!!Bt&&Sn(M)&&kn(M,["zoom","heatmap-density","line-progress","accumulated","is-supported-script"])}function Sn(M){if(M instanceof gn){if("get"===M.name&&1===M.args.length)return!1;if("feature-state"===M.name)return!1;if("has"===M.name&&1===M.args.length)return!1;if("properties"===M.name||"geometry-type"===M.name||"id"===M.name)return!1;if(/^filter-/.test(M.name))return!1}if(M instanceof jr)return!1;if(M instanceof yn)return!1;let et=!0;return M.eachChild((M=>{et&&!Sn(M)&&(et=!1)})),et}function An(M){if(M instanceof gn&&"feature-state"===M.name)return!1;let et=!0;return M.eachChild((M=>{et&&!An(M)&&(et=!1)})),et}function kn(M,et){if(M instanceof gn&&et.indexOf(M.name)>=0)return!1;let Bt=!0;return M.eachChild((M=>{Bt&&!kn(M,et)&&(Bt=!1)})),Bt}function Mn(M){return{result:"success",value:M}}function In(M){return{result:"error",value:M}}function zn(M){return"data-driven"===M["property-type"]||"cross-faded-data-driven"===M["property-type"]}function Pn(M){return!!M.expression&&M.expression.parameters.indexOf("zoom")>-1}function Cn(M){return!!M.expression&&M.expression.interpolated}function Bn(M){return M instanceof Number?"number":M instanceof String?"string":M instanceof Boolean?"boolean":Array.isArray(M)?"array":null===M?"null":typeof M}function Vn(M){return"object"==typeof M&&null!==M&&!Array.isArray(M)}function En(M){return M}function Tn(M,et){const Bt="color"===et.type,Wt=M.stops&&"object"==typeof M.stops[0][0],Nt=Wt||!(Wt||void 0!==M.property),$t=M.type||(Cn(et)?"exponential":"interval");if(Bt||"padding"===et.type){const Wt=Bt?ye.parse:ve.parse;(M=At({},M)).stops&&(M.stops=M.stops.map((M=>[M[0],Wt(M[1])]))),M.default=Wt(M.default?M.default:et.default)}if(M.colorSpace&&"rgb"!==(Gr=M.colorSpace)&&"hcl"!==Gr&&"lab"!==Gr)throw new Error(`Unknown color space: "${M.colorSpace}"`);var Gr;let mn,Hn,so;if("exponential"===$t)mn=Dn;else if("interval"===$t)mn=Ln;else if("categorical"===$t){mn=$n,Hn=Object.create(null);for(const et of M.stops)Hn[et[0]]=et[1];so=typeof M.stops[0][0]}else{if("identity"!==$t)throw new Error(`Unknown function type "${$t}"`);mn=On}if(Wt){const Bt={},Wt=[];for(let et=0;etM[0])),evaluate:({zoom:Bt},Wt)=>Dn({stops:Nt,base:M.base},et,Bt).evaluate(Bt,Wt)}}if(Nt){const Bt="exponential"===$t?{name:"exponential",base:void 0!==M.base?M.base:1}:null;return{kind:"camera",interpolationType:Bt,interpolationFactor:sr.interpolationFactor.bind(void 0,Bt),zoomStops:M.stops.map((M=>M[0])),evaluate:({zoom:Bt})=>mn(M,et,Bt,Hn,so)}}return{kind:"source",evaluate(Bt,Wt){const Nt=Wt&&Wt.properties?Wt.properties[M.property]:void 0;return void 0===Nt?Fn(M.default,et.default):mn(M,et,Nt,Hn,so)}}}function Fn(M,et,Bt){return void 0!==M?M:void 0!==et?et:void 0!==Bt?Bt:void 0}function $n(M,et,Bt,Wt,Nt){return Fn(typeof Bt===Nt?Wt[Bt]:void 0,M.default,et.default)}function Ln(M,et,Bt){if("number"!==Bn(Bt))return Fn(M.default,et.default);const Wt=M.stops.length;if(1===Wt)return M.stops[0][1];if(Bt<=M.stops[0][0])return M.stops[0][1];if(Bt>=M.stops[Wt-1][0])return M.stops[Wt-1][1];const Nt=We(M.stops.map((M=>M[0])),Bt);return M.stops[Nt][1]}function Dn(M,et,Bt){const Wt=void 0!==M.base?M.base:1;if("number"!==Bn(Bt))return Fn(M.default,et.default);const Nt=M.stops.length;if(1===Nt)return M.stops[0][1];if(Bt<=M.stops[0][0])return M.stops[0][1];if(Bt>=M.stops[Nt-1][0])return M.stops[Nt-1][1];const $t=We(M.stops.map((M=>M[0])),Bt),Gr=function(M,et,Bt,Wt){const Nt=Wt-Bt,$t=M-Bt;return 0===Nt?0:1===et?$t/Nt:(Math.pow(et,$t)-1)/(Math.pow(et,Nt)-1)}(Bt,Wt,M.stops[$t][0],M.stops[$t+1][0]),mn=M.stops[$t][1],Hn=M.stops[$t+1][1],so=zc[et.type]||En;return"function"==typeof mn.evaluate?{evaluate(...et){const Bt=mn.evaluate.apply(void 0,et),Wt=Hn.evaluate.apply(void 0,et);if(void 0!==Bt&&void 0!==Wt)return so(Bt,Wt,Gr,M.colorSpace)}}:so(mn,Hn,Gr,M.colorSpace)}function On(M,et,Bt){switch(et.type){case"color":Bt=ye.parse(Bt);break;case"formatted":Bt=xe.fromString(Bt.toString());break;case"resolvedImage":Bt=Se.fromString(Bt.toString());break;case"padding":Bt=ve.parse(Bt);break;default:Bn(Bt)===et.type||"enum"===et.type&&et.values[Bt]||(Bt=void 0)}return Fn(Bt,M.default,et.default)}gn.register(Xh,{error:[{kind:"error"},[Sl],(M,[et])=>{throw new be(et.evaluate(M))}],typeof:[Sl,[Vl],(M,[et])=>jt(Ie(et.evaluate(M)))],"to-rgba":[Rt(Al,4),[Gl],(M,[et])=>{const[Bt,Wt,Nt,$t]=et.evaluate(M).rgb;return[255*Bt,255*Wt,255*Nt,$t]}],rgb:[Gl,[Al,Al,Al],xn],rgba:[Gl,[Al,Al,Al,Al],xn],has:{type:Zl,overloads:[[[Sl],(M,[et])=>vn(et.evaluate(M),M.properties())],[[Sl,Tl],(M,[et,Bt])=>vn(et.evaluate(M),Bt.evaluate(M))]]},get:{type:Vl,overloads:[[[Sl],(M,[et])=>bn(et.evaluate(M),M.properties())],[[Sl,Tl],(M,[et,Bt])=>bn(et.evaluate(M),Bt.evaluate(M))]]},"feature-state":[Vl,[Sl],(M,[et])=>bn(et.evaluate(M),M.featureState||{})],properties:[Tl,[],M=>M.properties()],"geometry-type":[Sl,[],M=>M.geometryType()],id:[Vl,[],M=>M.id()],zoom:[Al,[],M=>M.globals.zoom],"heatmap-density":[Al,[],M=>M.globals.heatmapDensity||0],"line-progress":[Al,[],M=>M.globals.lineProgress||0],accumulated:[Vl,[],M=>void 0===M.globals.accumulated?null:M.globals.accumulated],"+":[Al,wn(Al),(M,et)=>{let Bt=0;for(const Wt of et)Bt+=Wt.evaluate(M);return Bt}],"*":[Al,wn(Al),(M,et)=>{let Bt=1;for(const Wt of et)Bt*=Wt.evaluate(M);return Bt}],"-":{type:Al,overloads:[[[Al,Al],(M,[et,Bt])=>et.evaluate(M)-Bt.evaluate(M)],[[Al],(M,[et])=>-et.evaluate(M)]]},"/":[Al,[Al,Al],(M,[et,Bt])=>et.evaluate(M)/Bt.evaluate(M)],"%":[Al,[Al,Al],(M,[et,Bt])=>et.evaluate(M)%Bt.evaluate(M)],ln2:[Al,[],()=>Math.LN2],pi:[Al,[],()=>Math.PI],e:[Al,[],()=>Math.E],"^":[Al,[Al,Al],(M,[et,Bt])=>Math.pow(et.evaluate(M),Bt.evaluate(M))],sqrt:[Al,[Al],(M,[et])=>Math.sqrt(et.evaluate(M))],log10:[Al,[Al],(M,[et])=>Math.log(et.evaluate(M))/Math.LN10],ln:[Al,[Al],(M,[et])=>Math.log(et.evaluate(M))],log2:[Al,[Al],(M,[et])=>Math.log(et.evaluate(M))/Math.LN2],sin:[Al,[Al],(M,[et])=>Math.sin(et.evaluate(M))],cos:[Al,[Al],(M,[et])=>Math.cos(et.evaluate(M))],tan:[Al,[Al],(M,[et])=>Math.tan(et.evaluate(M))],asin:[Al,[Al],(M,[et])=>Math.asin(et.evaluate(M))],acos:[Al,[Al],(M,[et])=>Math.acos(et.evaluate(M))],atan:[Al,[Al],(M,[et])=>Math.atan(et.evaluate(M))],min:[Al,wn(Al),(M,et)=>Math.min(...et.map((et=>et.evaluate(M))))],max:[Al,wn(Al),(M,et)=>Math.max(...et.map((et=>et.evaluate(M))))],abs:[Al,[Al],(M,[et])=>Math.abs(et.evaluate(M))],round:[Al,[Al],(M,[et])=>{const Bt=et.evaluate(M);return Bt<0?-Math.round(-Bt):Math.round(Bt)}],floor:[Al,[Al],(M,[et])=>Math.floor(et.evaluate(M))],ceil:[Al,[Al],(M,[et])=>Math.ceil(et.evaluate(M))],"filter-==":[Zl,[Sl,Vl],(M,[et,Bt])=>M.properties()[et.value]===Bt.value],"filter-id-==":[Zl,[Vl],(M,[et])=>M.id()===et.value],"filter-type-==":[Zl,[Sl],(M,[et])=>M.geometryDollarType()===et.value],"filter-<":[Zl,[Sl,Vl],(M,[et,Bt])=>{const Wt=M.properties()[et.value],Nt=Bt.value;return typeof Wt==typeof Nt&&Wt{const Bt=M.id(),Wt=et.value;return typeof Bt==typeof Wt&&Bt":[Zl,[Sl,Vl],(M,[et,Bt])=>{const Wt=M.properties()[et.value],Nt=Bt.value;return typeof Wt==typeof Nt&&Wt>Nt}],"filter-id->":[Zl,[Vl],(M,[et])=>{const Bt=M.id(),Wt=et.value;return typeof Bt==typeof Wt&&Bt>Wt}],"filter-<=":[Zl,[Sl,Vl],(M,[et,Bt])=>{const Wt=M.properties()[et.value],Nt=Bt.value;return typeof Wt==typeof Nt&&Wt<=Nt}],"filter-id-<=":[Zl,[Vl],(M,[et])=>{const Bt=M.id(),Wt=et.value;return typeof Bt==typeof Wt&&Bt<=Wt}],"filter->=":[Zl,[Sl,Vl],(M,[et,Bt])=>{const Wt=M.properties()[et.value],Nt=Bt.value;return typeof Wt==typeof Nt&&Wt>=Nt}],"filter-id->=":[Zl,[Vl],(M,[et])=>{const Bt=M.id(),Wt=et.value;return typeof Bt==typeof Wt&&Bt>=Wt}],"filter-has":[Zl,[Vl],(M,[et])=>et.value in M.properties()],"filter-has-id":[Zl,[],M=>null!==M.id()&&void 0!==M.id()],"filter-type-in":[Zl,[Rt(Sl)],(M,[et])=>et.value.indexOf(M.geometryDollarType())>=0],"filter-id-in":[Zl,[Rt(Vl)],(M,[et])=>et.value.indexOf(M.id())>=0],"filter-in-small":[Zl,[Sl,Rt(Vl)],(M,[et,Bt])=>Bt.value.indexOf(M.properties()[et.value])>=0],"filter-in-large":[Zl,[Sl,Rt(Vl)],(M,[et,Bt])=>function(M,et,Bt,Wt){for(;Bt<=Wt;){const Nt=Bt+Wt>>1;if(et[Nt]===M)return!0;et[Nt]>M?Wt=Nt-1:Bt=Nt+1}return!1}(M.properties()[et.value],Bt.value,0,Bt.value.length-1)],all:{type:Zl,overloads:[[[Zl,Zl],(M,[et,Bt])=>et.evaluate(M)&&Bt.evaluate(M)],[wn(Zl),(M,et)=>{for(const Bt of et)if(!Bt.evaluate(M))return!1;return!0}]]},any:{type:Zl,overloads:[[[Zl,Zl],(M,[et,Bt])=>et.evaluate(M)||Bt.evaluate(M)],[wn(Zl),(M,et)=>{for(const Bt of et)if(Bt.evaluate(M))return!0;return!1}]]},"!":[Zl,[Zl],(M,[et])=>!et.evaluate(M)],"is-supported-script":[Zl,[Sl],(M,[et])=>{const Bt=M.globals&&M.globals.isSupportedScript;return!Bt||Bt(et.evaluate(M))}],upcase:[Sl,[Sl],(M,[et])=>et.evaluate(M).toUpperCase()],downcase:[Sl,[Sl],(M,[et])=>et.evaluate(M).toLowerCase()],concat:[Sl,wn(Vl),(M,et)=>et.map((et=>ze(et.evaluate(M)))).join("")],"resolved-locale":[Sl,[Wl],(M,[et])=>et.evaluate(M).resolvedLocale()]});class Rn{constructor(M,et){var Bt;this.expression=M,this._warningHistory={},this._evaluator=new Ne,this._defaultValue=et?"color"===(Bt=et).type&&Vn(Bt.default)?new ye(0,0,0,0):"color"===Bt.type?ye.parse(Bt.default)||null:"padding"===Bt.type?ve.parse(Bt.default)||null:"variableAnchorOffsetCollection"===Bt.type?_e.parse(Bt.default)||null:"projectionDefinition"===Bt.type?Ae.parse(Bt.default)||null:void 0===Bt.default?null:Bt.default:null,this._enumValues=et&&"enum"===et.type?et.values:null}evaluateWithoutErrorHandling(M,et,Bt,Wt,Nt,$t){return this._evaluator.globals=M,this._evaluator.feature=et,this._evaluator.featureState=Bt,this._evaluator.canonical=Wt,this._evaluator.availableImages=Nt||null,this._evaluator.formattedSection=$t,this.expression.evaluate(this._evaluator)}evaluate(M,et,Bt,Wt,Nt,$t){this._evaluator.globals=M,this._evaluator.feature=et||null,this._evaluator.featureState=Bt||null,this._evaluator.canonical=Wt,this._evaluator.availableImages=Nt||null,this._evaluator.formattedSection=$t||null;try{const M=this.expression.evaluate(this._evaluator);if(null==M||"number"==typeof M&&M!=M)return this._defaultValue;if(this._enumValues&&!(M in this._enumValues))throw new be(`Expected value to be one of ${Object.keys(this._enumValues).map((M=>JSON.stringify(M))).join(", ")}, but found ${JSON.stringify(M)} instead.`);return M}catch(M){return this._warningHistory[M.message]||(this._warningHistory[M.message]=!0,"undefined"!=typeof console&&console.warn(M.message)),this._defaultValue}}}function jn(M){return Array.isArray(M)&&M.length>0&&"string"==typeof M[0]&&M[0]in Xh}function Nn(M,et){const Bt=new Ue(Xh,_n,[],et?function(M){const et={color:Gl,string:Sl,number:Al,enum:Sl,boolean:Zl,formatted:El,padding:Jl,projectionDefinition:Rl,resolvedImage:Ll,variableAnchorOffsetCollection:Dl};return"array"===M.type?Rt(et[M.value]||Vl,M.length):et[M.type]}(et):void 0),Wt=Bt.parse(M,void 0,void 0,void 0,et&&"string"===et.type?{typeAnnotation:"coerce"}:void 0);return Wt?Mn(new Rn(Wt,et)):In(Bt.errors)}class Un{constructor(M,et){this.kind=M,this._styleExpression=et,this.isStateDependent="constant"!==M&&!An(et.expression)}evaluateWithoutErrorHandling(M,et,Bt,Wt,Nt,$t){return this._styleExpression.evaluateWithoutErrorHandling(M,et,Bt,Wt,Nt,$t)}evaluate(M,et,Bt,Wt,Nt,$t){return this._styleExpression.evaluate(M,et,Bt,Wt,Nt,$t)}}class qn{constructor(M,et,Bt,Wt){this.kind=M,this.zoomStops=Bt,this._styleExpression=et,this.isStateDependent="camera"!==M&&!An(et.expression),this.interpolationType=Wt}evaluateWithoutErrorHandling(M,et,Bt,Wt,Nt,$t){return this._styleExpression.evaluateWithoutErrorHandling(M,et,Bt,Wt,Nt,$t)}evaluate(M,et,Bt,Wt,Nt,$t){return this._styleExpression.evaluate(M,et,Bt,Wt,Nt,$t)}interpolationFactor(M,et,Bt){return this.interpolationType?sr.interpolationFactor(this.interpolationType,M,et,Bt):0}}function Gn(M,et){const Bt=Nn(M,et);if("error"===Bt.result)return Bt;const Wt=Bt.value.expression,Nt=Sn(Wt);if(!Nt&&!zn(et))return In([new kt("","data expressions not supported")]);const $t=kn(Wt,["zoom"]);if(!$t&&!Pn(et))return In([new kt("","zoom expressions not supported")]);const Gr=Xn(Wt);return Gr||$t?Gr instanceof kt?In([Gr]):Gr instanceof sr&&!Cn(et)?In([new kt("",'"interpolate" expressions cannot be used with this property')]):Mn(Gr?new qn(Nt?"camera":"composite",Bt.value,Gr.labels,Gr instanceof sr?Gr.interpolation:void 0):new Un(Nt?"constant":"source",Bt.value)):In([new kt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}class Zn{constructor(M,et){this._parameters=M,this._specification=et,At(this,Tn(this._parameters,this._specification))}static deserialize(M){return new Zn(M._parameters,M._specification)}static serialize(M){return{_parameters:M._parameters,_specification:M._specification}}}function Xn(M){let et=null;if(M instanceof qe)et=Xn(M.result);else if(M instanceof lr){for(const Bt of M.args)if(et=Xn(Bt),et)break}else(M instanceof Qe||M instanceof sr)&&M.input instanceof gn&&"zoom"===M.input.name&&(et=M);return et instanceof kt||M.eachChild((M=>{const Bt=Xn(M);Bt instanceof kt?et=Bt:!et&&Bt?et=new kt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):et&&Bt&&et!==Bt&&(et=new kt("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))})),et}function Kn(M){if(!0===M||!1===M)return!0;if(!Array.isArray(M)||0===M.length)return!1;switch(M[0]){case"has":return M.length>=2&&"$id"!==M[1]&&"$type"!==M[1];case"in":return M.length>=3&&("string"!=typeof M[1]||Array.isArray(M[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3!==M.length||Array.isArray(M[1])||Array.isArray(M[2]);case"any":case"all":for(const et of M.slice(1))if(!Kn(et)&&"boolean"!=typeof et)return!1;return!0;default:return!0}}const Lh={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function Yn(M){if(null==M)return{filter:()=>!0,needGeometry:!1};Kn(M)||(M=Qn(M));const et=Nn(M,Lh);if("error"===et.result)throw new Error(et.value.map((M=>`${M.key}: ${M.message}`)).join(", "));return{filter:(M,Bt,Wt)=>et.value.evaluate(M,Bt,{},Wt),needGeometry:Wn(M)}}function Jn(M,et){return Met?1:0}function Wn(M){if(!Array.isArray(M))return!1;if("within"===M[0]||"distance"===M[0]||"geometry-type"===M[0])return!0;for(let et=1;et"===et||"<="===et||">="===et?ti(M[1],M[2],et):"any"===et?(Bt=M.slice(1),["any"].concat(Bt.map(Qn))):"all"===et?["all"].concat(M.slice(1).map(Qn)):"none"===et?["all"].concat(M.slice(1).map(Qn).map(ni)):"in"===et?ei(M[1],M.slice(2)):"!in"===et?ni(ei(M[1],M.slice(2))):"has"===et?ri(M[1]):"!has"!==et||ni(ri(M[1]));var Bt}function ti(M,et,Bt){switch(M){case"$type":return[`filter-type-${Bt}`,et];case"$id":return[`filter-id-${Bt}`,et];default:return[`filter-${Bt}`,M,et]}}function ei(M,et){if(0===et.length)return!1;switch(M){case"$type":return["filter-type-in",["literal",et]];case"$id":return["filter-id-in",["literal",et]];default:return et.length>200&&!et.some((M=>typeof M!=typeof et[0]))?["filter-in-large",M,["literal",et.sort(Jn)]]:["filter-in-small",M,["literal",et]]}}function ri(M){switch(M){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",M]}}function ni(M){return["!",M]}function ii(M){const et=typeof M;if("number"===et||"boolean"===et||"string"===et||null==M)return JSON.stringify(M);if(Array.isArray(M)){let et="[";for(const Bt of M)et+=`${ii(Bt)},`;return`${et}]`}const Bt=Object.keys(M).sort();let Wt="{";for(let et=0;etWt.maximum?[new St(et,Bt,`${Bt} is greater than the maximum value ${Wt.maximum}`)]:[]}function pi(M){const et=M.valueSpec,Bt=oi(M.value.type);let Wt,Nt,$t,Gr={};const mn="categorical"!==Bt&&void 0===M.value.property,Hn=!mn,so="array"===Bn(M.value.stops)&&"array"===Bn(M.value.stops[0])&&"object"===Bn(M.value.stops[0][0]),uo=ui({key:M.key,value:M.value,valueSpec:M.styleSpec.function,validateSpec:M.validateSpec,style:M.style,styleSpec:M.styleSpec,objectElementValidators:{stops:function(M){if("identity"===Bt)return[new St(M.key,M.value,'identity function may not have a "stops" property')];let et=[];const Wt=M.value;return et=et.concat(ci({key:M.key,value:Wt,valueSpec:M.valueSpec,validateSpec:M.validateSpec,style:M.style,styleSpec:M.styleSpec,arrayElementValidator:h})),"array"===Bn(Wt)&&0===Wt.length&&et.push(new St(M.key,Wt,"array must have at least one stop")),et},default:function(M){return M.validateSpec({key:M.key,value:M.value,valueSpec:et,validateSpec:M.validateSpec,style:M.style,styleSpec:M.styleSpec})}}});return"identity"===Bt&&mn&&uo.push(new St(M.key,M.value,'missing required property "property"')),"identity"===Bt||M.value.stops||uo.push(new St(M.key,M.value,'missing required property "stops"')),"exponential"===Bt&&M.valueSpec.expression&&!Cn(M.valueSpec)&&uo.push(new St(M.key,M.value,"exponential functions not supported")),M.styleSpec.$version>=8&&(Hn&&!zn(M.valueSpec)?uo.push(new St(M.key,M.value,"property functions not supported")):mn&&!Pn(M.valueSpec)&&uo.push(new St(M.key,M.value,"zoom functions not supported"))),"categorical"!==Bt&&!so||void 0!==M.value.property||uo.push(new St(M.key,M.value,'"property" property is required')),uo;function h(M){let Bt=[];const Wt=M.value,mn=M.key;if("array"!==Bn(Wt))return[new St(mn,Wt,`array expected, ${Bn(Wt)} found`)];if(2!==Wt.length)return[new St(mn,Wt,`array length 2 expected, length ${Wt.length} found`)];if(so){if("object"!==Bn(Wt[0]))return[new St(mn,Wt,`object expected, ${Bn(Wt[0])} found`)];if(void 0===Wt[0].zoom)return[new St(mn,Wt,"object stop key must have zoom")];if(void 0===Wt[0].value)return[new St(mn,Wt,"object stop key must have value")];if($t&&$t>oi(Wt[0].zoom))return[new St(mn,Wt[0].zoom,"stop zoom values must appear in ascending order")];oi(Wt[0].zoom)!==$t&&($t=oi(Wt[0].zoom),Nt=void 0,Gr={}),Bt=Bt.concat(ui({key:`${mn}[0]`,value:Wt[0],valueSpec:{zoom:{}},validateSpec:M.validateSpec,style:M.style,styleSpec:M.styleSpec,objectElementValidators:{zoom:hi,value:p}}))}else Bt=Bt.concat(p({key:`${mn}[0]`,value:Wt[0],valueSpec:{},validateSpec:M.validateSpec,style:M.style,styleSpec:M.styleSpec},Wt));return jn(li(Wt[1]))?Bt.concat([new St(`${mn}[1]`,Wt[1],"expressions are not allowed in function stops.")]):Bt.concat(M.validateSpec({key:`${mn}[1]`,value:Wt[1],valueSpec:et,validateSpec:M.validateSpec,style:M.style,styleSpec:M.styleSpec}))}function p(M,$t){const mn=Bn(M.value),Hn=oi(M.value),so=null!==M.value?M.value:$t;if(Wt){if(mn!==Wt)return[new St(M.key,so,`${mn} stop domain type must match previous stop domain type ${Wt}`)]}else Wt=mn;if("number"!==mn&&"string"!==mn&&"boolean"!==mn)return[new St(M.key,so,"stop domain value must be a number, string, or boolean")];if("number"!==mn&&"categorical"!==Bt){let Wt=`number expected, ${mn} found`;return zn(et)&&void 0===Bt&&(Wt+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new St(M.key,so,Wt)]}return"categorical"!==Bt||"number"!==mn||isFinite(Hn)&&Math.floor(Hn)===Hn?"categorical"!==Bt&&"number"===mn&&void 0!==Nt&&Hnnew St(`${M.key}${et.key}`,M.value,et.message)));const Bt=et.value.expression||et.value._styleExpression.expression;if("property"===M.expressionContext&&"text-font"===M.propertyKey&&!Bt.outputDefined())return[new St(M.key,M.value,`Invalid data expression for "${M.propertyKey}". Output values must be contained as literals within the expression.`)];if("property"===M.expressionContext&&"layout"===M.propertyType&&!An(Bt))return[new St(M.key,M.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===M.expressionContext&&!An(Bt))return[new St(M.key,M.value,'"feature-state" data expressions are not supported with filters.')];if(M.expressionContext&&0===M.expressionContext.indexOf("cluster")){if(!kn(Bt,["zoom","feature-state"]))return[new St(M.key,M.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===M.expressionContext&&!Sn(Bt))return[new St(M.key,M.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function di(M){const et=M.key,Bt=M.value,Wt=M.valueSpec,Nt=[];return Array.isArray(Wt.values)?-1===Wt.values.indexOf(oi(Bt))&&Nt.push(new St(et,Bt,`expected one of [${Wt.values.join(", ")}], ${JSON.stringify(Bt)} found`)):-1===Object.keys(Wt.values).indexOf(oi(Bt))&&Nt.push(new St(et,Bt,`expected one of [${Object.keys(Wt.values).join(", ")}], ${JSON.stringify(Bt)} found`)),Nt}function yi(M){return Kn(li(M.value))?fi(At({},M,{expressionContext:"filter",valueSpec:{value:"boolean"}})):mi(M)}function mi(M){const et=M.value,Bt=M.key;if("array"!==Bn(et))return[new St(Bt,et,`array expected, ${Bn(et)} found`)];const Wt=M.styleSpec;let Nt,$t=[];if(et.length<1)return[new St(Bt,et,"filter array must have at least 1 element")];switch($t=$t.concat(di({key:`${Bt}[0]`,value:et[0],valueSpec:Wt.filter_operator,style:M.style,styleSpec:M.styleSpec})),oi(et[0])){case"<":case"<=":case">":case">=":et.length>=2&&"$type"===oi(et[1])&&$t.push(new St(Bt,et,`"$type" cannot be use with operator "${et[0]}"`));case"==":case"!=":3!==et.length&&$t.push(new St(Bt,et,`filter array for operator "${et[0]}" must have 3 elements`));case"in":case"!in":et.length>=2&&(Nt=Bn(et[1]),"string"!==Nt&&$t.push(new St(`${Bt}[1]`,et[1],`string expected, ${Nt} found`)));for(let Gr=2;Gr{M in Bt&&et.push(new St(Wt,Bt[M],`"${M}" is prohibited for ref layers`))})),Nt.layers.forEach((et=>{oi(et.id)===mn&&(M=et)})),M?M.ref?et.push(new St(Wt,Bt.ref,"ref cannot reference another ref layer")):Gr=oi(M.type):et.push(new St(Wt,Bt.ref,`ref layer "${mn}" not found`))}else if("background"!==Gr)if(Bt.source){const M=Nt.sources&&Nt.sources[Bt.source],$t=M&&oi(M.type);M?"vector"===$t&&"raster"===Gr?et.push(new St(Wt,Bt.source,`layer "${Bt.id}" requires a raster source`)):"raster-dem"!==$t&&"hillshade"===Gr?et.push(new St(Wt,Bt.source,`layer "${Bt.id}" requires a raster-dem source`)):"raster"===$t&&"raster"!==Gr?et.push(new St(Wt,Bt.source,`layer "${Bt.id}" requires a vector source`)):"vector"!==$t||Bt["source-layer"]?"raster-dem"===$t&&"hillshade"!==Gr?et.push(new St(Wt,Bt.source,"raster-dem source can only be used with layer type 'hillshade'.")):"line"!==Gr||!Bt.paint||!Bt.paint["line-gradient"]||"geojson"===$t&&M.lineMetrics||et.push(new St(Wt,Bt,`layer "${Bt.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):et.push(new St(Wt,Bt,`layer "${Bt.id}" must specify a "source-layer"`)):et.push(new St(Wt,Bt.source,`source "${Bt.source}" not found`))}else et.push(new St(Wt,Bt,'missing required property "source"'));return et=et.concat(ui({key:Wt,value:Bt,valueSpec:$t.layer,style:M.style,styleSpec:M.styleSpec,validateSpec:M.validateSpec,objectElementValidators:{"*":()=>[],type:()=>M.validateSpec({key:`${Wt}.type`,value:Bt.type,valueSpec:$t.layer.type,style:M.style,styleSpec:M.styleSpec,validateSpec:M.validateSpec,object:Bt,objectKey:"type"}),filter:yi,layout:M=>ui({layer:Bt,key:M.key,value:M.value,style:M.style,styleSpec:M.styleSpec,validateSpec:M.validateSpec,objectElementValidators:{"*":M=>vi(At({layerType:Gr},M))}}),paint:M=>ui({layer:Bt,key:M.key,value:M.value,style:M.style,styleSpec:M.styleSpec,validateSpec:M.validateSpec,objectElementValidators:{"*":M=>xi(At({layerType:Gr},M))}})}})),et}function wi(M){const et=M.value,Bt=M.key,Wt=Bn(et);return"string"!==Wt?[new St(Bt,et,`string expected, ${Wt} found`)]:[]}const Hh={promoteId:function({key:M,value:et}){if("string"===Bn(et))return wi({key:M,value:et});{const Bt=[];for(const Wt in et)Bt.push(...wi({key:`${M}.${Wt}`,value:et[Wt]}));return Bt}}};function Si(M){const et=M.value,Bt=M.key,Wt=M.styleSpec,Nt=M.style,$t=M.validateSpec;if(!et.type)return[new St(Bt,et,'"type" is required')];const Gr=oi(et.type);let mn;switch(Gr){case"vector":case"raster":return mn=ui({key:Bt,value:et,valueSpec:Wt[`source_${Gr.replace("-","_")}`],style:M.style,styleSpec:Wt,objectElementValidators:Hh,validateSpec:$t}),mn;case"raster-dem":return mn=function(M){var et;const Bt=null!==(et=M.sourceName)&&void 0!==et?et:"",Wt=M.value,Nt=M.styleSpec,$t=Nt.source_raster_dem,Gr=M.style;let mn=[];const Hn=Bn(Wt);if(void 0===Wt)return mn;if("object"!==Hn)return mn.push(new St("source_raster_dem",Wt,`object expected, ${Hn} found`)),mn;const so="custom"===oi(Wt.encoding),uo=["redFactor","greenFactor","blueFactor","baseShift"],Io=M.value.encoding?`"${M.value.encoding}"`:"Default";for(const et in Wt)!so&&uo.includes(et)?mn.push(new St(et,Wt[et],`In "${Bt}": "${et}" is only valid when "encoding" is set to "custom". ${Io} encoding found`)):$t[et]?mn=mn.concat(M.validateSpec({key:et,value:Wt[et],valueSpec:$t[et],validateSpec:M.validateSpec,style:Gr,styleSpec:Nt})):mn.push(new St(et,Wt[et],`unknown property "${et}"`));return mn}({sourceName:Bt,value:et,style:M.style,styleSpec:Wt,validateSpec:$t}),mn;case"geojson":if(mn=ui({key:Bt,value:et,valueSpec:Wt.source_geojson,style:Nt,styleSpec:Wt,validateSpec:$t,objectElementValidators:Hh}),et.cluster)for(const M in et.clusterProperties){const[Wt,Nt]=et.clusterProperties[M],Gr="string"==typeof Wt?[Wt,["accumulated"],["get",M]]:Wt;mn.push(...fi({key:`${Bt}.${M}.map`,value:Nt,validateSpec:$t,expressionContext:"cluster-map"})),mn.push(...fi({key:`${Bt}.${M}.reduce`,value:Gr,validateSpec:$t,expressionContext:"cluster-reduce"}))}return mn;case"video":return ui({key:Bt,value:et,valueSpec:Wt.source_video,style:Nt,validateSpec:$t,styleSpec:Wt});case"image":return ui({key:Bt,value:et,valueSpec:Wt.source_image,style:Nt,validateSpec:$t,styleSpec:Wt});case"canvas":return[new St(Bt,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return di({key:`${Bt}.type`,value:et.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]},style:Nt,validateSpec:$t,styleSpec:Wt})}}function Ai(M){const et=M.value,Bt=M.styleSpec,Wt=Bt.light,Nt=M.style;let $t=[];const Gr=Bn(et);if(void 0===et)return $t;if("object"!==Gr)return $t=$t.concat([new St("light",et,`object expected, ${Gr} found`)]),$t;for(const Gr in et){const mn=Gr.match(/^(.*)-transition$/);$t=$t.concat(mn&&Wt[mn[1]]&&Wt[mn[1]].transition?M.validateSpec({key:Gr,value:et[Gr],valueSpec:Bt.transition,validateSpec:M.validateSpec,style:Nt,styleSpec:Bt}):Wt[Gr]?M.validateSpec({key:Gr,value:et[Gr],valueSpec:Wt[Gr],validateSpec:M.validateSpec,style:Nt,styleSpec:Bt}):[new St(Gr,et[Gr],`unknown property "${Gr}"`)])}return $t}function ki(M){const et=M.value,Bt=M.styleSpec,Wt=Bt.sky,Nt=M.style,$t=Bn(et);if(void 0===et)return[];if("object"!==$t)return[new St("sky",et,`object expected, ${$t} found`)];let Gr=[];for(const $t in et)Gr=Gr.concat(Wt[$t]?M.validateSpec({key:$t,value:et[$t],valueSpec:Wt[$t],style:Nt,styleSpec:Bt}):[new St($t,et[$t],`unknown property "${$t}"`)]);return Gr}function Mi(M){const et=M.value,Bt=M.styleSpec,Wt=Bt.terrain,Nt=M.style;let $t=[];const Gr=Bn(et);if(void 0===et)return $t;if("object"!==Gr)return $t=$t.concat([new St("terrain",et,`object expected, ${Gr} found`)]),$t;for(const Gr in et)$t=$t.concat(Wt[Gr]?M.validateSpec({key:Gr,value:et[Gr],valueSpec:Wt[Gr],validateSpec:M.validateSpec,style:Nt,styleSpec:Bt}):[new St(Gr,et[Gr],`unknown property "${Gr}"`)]);return $t}function Ii(M){let et=[];const Bt=M.value,Wt=M.key;if(Array.isArray(Bt)){const Nt=[],$t=[];for(const Gr in Bt)Bt[Gr].id&&Nt.includes(Bt[Gr].id)&&et.push(new St(Wt,Bt,`all the sprites' ids must be unique, but ${Bt[Gr].id} is duplicated`)),Nt.push(Bt[Gr].id),Bt[Gr].url&&$t.includes(Bt[Gr].url)&&et.push(new St(Wt,Bt,`all the sprites' URLs must be unique, but ${Bt[Gr].url} is duplicated`)),$t.push(Bt[Gr].url),et=et.concat(ui({key:`${Wt}[${Gr}]`,value:Bt[Gr],valueSpec:{id:{type:"string",required:!0},url:{type:"string",required:!0}},validateSpec:M.validateSpec}));return et}return wi({key:Wt,value:Bt})}const Kh={"*":()=>[],array:ci,boolean:function(M){const et=M.value,Bt=M.key,Wt=Bn(et);return"boolean"!==Wt?[new St(Bt,et,`boolean expected, ${Wt} found`)]:[]},number:hi,color:function(M){const et=M.key,Bt=M.value,Wt=Bn(Bt);return"string"!==Wt?[new St(et,Bt,`color expected, ${Wt} found`)]:ye.parse(String(Bt))?[]:[new St(et,Bt,`color expected, "${Bt}" found`)]},constants:ai,enum:di,filter:yi,function:pi,layer:bi,object:ui,source:Si,light:Ai,sky:ki,terrain:Mi,projection:function(M){const et=M.value,Bt=M.styleSpec,Wt=Bt.projection,Nt=M.style,$t=Bn(et);if(void 0===et)return[];if("object"!==$t)return[new St("projection",et,`object expected, ${$t} found`)];let Gr=[];for(const $t in et)Gr=Gr.concat(Wt[$t]?M.validateSpec({key:$t,value:et[$t],valueSpec:Wt[$t],style:Nt,styleSpec:Bt}):[new St($t,et[$t],`unknown property "${$t}"`)]);return Gr},projectionDefinition:function(M){const et=M.key;let Bt=M.value;Bt=Bt instanceof String?Bt.valueOf():Bt;const Wt=Bn(Bt);return"array"!==Wt||function(M){return Array.isArray(M)&&3===M.length&&"string"==typeof M[0]&&"string"==typeof M[1]&&"number"==typeof M[2]}(Bt)||function(M){return!!["interpolate","step","literal"].includes(M[0])}(Bt)?["array","string"].includes(Wt)?[]:[new St(et,Bt,`projection expected, invalid type "${Wt}" found`)]:[new St(et,Bt,`projection expected, invalid array ${JSON.stringify(Bt)} found`)]},string:wi,formatted:function(M){return 0===wi(M).length?[]:fi(M)},resolvedImage:function(M){return 0===wi(M).length?[]:fi(M)},padding:function(M){const et=M.key,Bt=M.value;if("array"===Bn(Bt)){if(Bt.length<1||Bt.length>4)return[new St(et,Bt,`padding requires 1 to 4 values; ${Bt.length} values found`)];const Wt={type:"number"};let Nt=[];for(let $t=0;$t[]}})),M.constants&&(Bt=Bt.concat(ai({key:"constants",value:M.constants,style:M,styleSpec:et,validateSpec:Pi}))),Ei(Bt)}function Vi(M){return function(et){return M({...et,validateSpec:Pi})}}function Ei(M){return[].concat(M).sort(((M,et)=>M.line-et.line))}function Ti(M){return function(...et){return Ei(M.apply(this,et))}}Bi.source=Ti(Vi(Si)),Bi.sprite=Ti(Vi(Ii)),Bi.glyphs=Ti(Vi(Ci)),Bi.light=Ti(Vi(Ai)),Bi.sky=Ti(Vi(ki)),Bi.terrain=Ti(Vi(Mi)),Bi.layer=Ti(Vi(bi)),Bi.filter=Ti(Vi(yi)),Bi.paintProperty=Ti(Vi(xi)),Bi.layoutProperty=Ti(Vi(vi));const Yh=Bi,Qh=Yh.light,qh=Yh.sky,tg=Yh.paintProperty,eg=Yh.layoutProperty;function Ri(M,et){let Bt=!1;if(et&&et.length)for(const Wt of et)M.fire(new ut(new Error(Wt.message))),Bt=!0;return Bt}class ji{constructor(M,et,Bt){const Wt=this.cells=[];if(M instanceof ArrayBuffer){this.arrayBuffer=M;const Nt=new Int32Array(this.arrayBuffer);M=Nt[0],this.d=(et=Nt[1])+2*(Bt=Nt[2]);for(let M=0;M=so[Hn+0]&&Wt>=so[Hn+1])?(Gr[Io]=!0,$t.push(Nt[Io])):Gr[Io]=!1}}}}_forEachCell(M,et,Bt,Wt,Nt,$t,Gr,mn){const Hn=this._convertToCellCoord(M),so=this._convertToCellCoord(et),uo=this._convertToCellCoord(Bt),Io=this._convertToCellCoord(Wt);for(let Po=Hn;Po<=uo;Po++)for(let Hn=so;Hn<=Io;Hn++){const so=this.d*Hn+Po;if((!mn||mn(this._convertFromCellCoord(Po),this._convertFromCellCoord(Hn),this._convertFromCellCoord(Po+1),this._convertFromCellCoord(Hn+1)))&&Nt.call(this,M,et,Bt,Wt,so,$t,Gr,mn))return}}_convertFromCellCoord(M){return(M-this.padding)/this.scale}_convertToCellCoord(M){return Math.max(0,Math.min(this.d-1,Math.floor(M*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;const M=this.cells,et=3+this.cells.length+1+1;let Bt=0;for(let M=0;M=0)continue;const $t=M[Wt];Nt[Wt]=ig[Bt].shallow.indexOf(Wt)>=0?$t:Xi($t,et)}M instanceof Error&&(Nt.message=M.message)}if(Nt.$name)throw new Error("$name property is reserved for worker serialization logic.");return"Object"!==Bt&&(Nt.$name=Bt),Nt}function Ki(M){if(Zi(M))return M;if(Array.isArray(M))return M.map(Ki);if("object"!=typeof M)throw new Error("can't deserialize object of type "+typeof M);const et=Gi(M)||"Object";if(!ig[et])throw new Error(`can't deserialize unregistered class ${et}`);const{klass:Bt}=ig[et];if(!Bt)throw new Error(`can't deserialize unregistered class ${et}`);if(Bt.deserialize)return Bt.deserialize(M);const Wt=Object.create(Bt.prototype);for(const Bt of Object.keys(M)){if("$name"===Bt)continue;const Nt=M[Bt];Wt[Bt]=ig[et].shallow.indexOf(Bt)>=0?Nt:Ki(Nt)}return Wt}class Hi{constructor(){this.first=!0}update(M,et){const Bt=Math.floor(M);return this.first?(this.first=!1,this.lastIntegerZoom=Bt,this.lastIntegerZoomTime=0,this.lastZoom=M,this.lastFloorZoom=Bt,!0):(this.lastFloorZoom>Bt?(this.lastIntegerZoom=Bt+1,this.lastIntegerZoomTime=et):this.lastFloorZoomM>=128&&M<=255,"Hangul Jamo":M=>M>=4352&&M<=4607,Khmer:M=>M>=6016&&M<=6143,"General Punctuation":M=>M>=8192&&M<=8303,"Letterlike Symbols":M=>M>=8448&&M<=8527,"Number Forms":M=>M>=8528&&M<=8591,"Miscellaneous Technical":M=>M>=8960&&M<=9215,"Control Pictures":M=>M>=9216&&M<=9279,"Optical Character Recognition":M=>M>=9280&&M<=9311,"Enclosed Alphanumerics":M=>M>=9312&&M<=9471,"Geometric Shapes":M=>M>=9632&&M<=9727,"Miscellaneous Symbols":M=>M>=9728&&M<=9983,"Miscellaneous Symbols and Arrows":M=>M>=11008&&M<=11263,"Ideographic Description Characters":M=>M>=12272&&M<=12287,"CJK Symbols and Punctuation":M=>M>=12288&&M<=12351,Katakana:M=>M>=12448&&M<=12543,Kanbun:M=>M>=12688&&M<=12703,"CJK Strokes":M=>M>=12736&&M<=12783,"Enclosed CJK Letters and Months":M=>M>=12800&&M<=13055,"CJK Compatibility":M=>M>=13056&&M<=13311,"Yijing Hexagram Symbols":M=>M>=19904&&M<=19967,"Private Use Area":M=>M>=57344&&M<=63743,"Vertical Forms":M=>M>=65040&&M<=65055,"CJK Compatibility Forms":M=>M>=65072&&M<=65103,"Small Form Variants":M=>M>=65104&&M<=65135,"Halfwidth and Fullwidth Forms":M=>M>=65280&&M<=65519};function Ji(M){for(const et of M)if(ns(et.charCodeAt(0)))return!0;return!1}function Wi(M){for(const et of M)if(!es(et.charCodeAt(0)))return!1;return!0}function Qi(M){const et=M.map((M=>{try{return new RegExp(`\\p{sc=${M}}`,"u").source}catch(M){return null}})).filter((M=>M));return new RegExp(et.join("|"),"u")}const ng=Qi(["Arab","Dupl","Mong","Ougr","Syrc"]);function es(M){return!ng.test(String.fromCodePoint(M))}const og=Qi(["Bopo","Hani","Hira","Kana","Kits","Nshu","Tang","Yiii"]);function ns(M){return!(746!==M&&747!==M&&(M<4352||!(rg["CJK Compatibility Forms"](M)&&!(M>=65097&&M<=65103)||rg["CJK Compatibility"](M)||rg["CJK Strokes"](M)||!(!rg["CJK Symbols and Punctuation"](M)||M>=12296&&M<=12305||M>=12308&&M<=12319||12336===M)||rg["Enclosed CJK Letters and Months"](M)||rg["Ideographic Description Characters"](M)||rg.Kanbun(M)||rg.Katakana(M)&&12540!==M||!(!rg["Halfwidth and Fullwidth Forms"](M)||65288===M||65289===M||65293===M||M>=65306&&M<=65310||65339===M||65341===M||65343===M||M>=65371&&M<=65503||65507===M||M>=65512&&M<=65519)||!(!rg["Small Form Variants"](M)||M>=65112&&M<=65118||M>=65123&&M<=65126)||rg["Vertical Forms"](M)||rg["Yijing Hexagram Symbols"](M)||/\p{sc=Cans}/u.test(String.fromCodePoint(M))||/\p{sc=Hang}/u.test(String.fromCodePoint(M))||og.test(String.fromCodePoint(M)))))}function is(M){return!(ns(M)||function(M){return!!(rg["Latin-1 Supplement"](M)&&(167===M||169===M||174===M||177===M||188===M||189===M||190===M||215===M||247===M)||rg["General Punctuation"](M)&&(8214===M||8224===M||8225===M||8240===M||8241===M||8251===M||8252===M||8258===M||8263===M||8264===M||8265===M||8273===M)||rg["Letterlike Symbols"](M)||rg["Number Forms"](M)||rg["Miscellaneous Technical"](M)&&(M>=8960&&M<=8967||M>=8972&&M<=8991||M>=8996&&M<=9e3||9003===M||M>=9085&&M<=9114||M>=9150&&M<=9165||9167===M||M>=9169&&M<=9179||M>=9186&&M<=9215)||rg["Control Pictures"](M)&&9251!==M||rg["Optical Character Recognition"](M)||rg["Enclosed Alphanumerics"](M)||rg["Geometric Shapes"](M)||rg["Miscellaneous Symbols"](M)&&!(M>=9754&&M<=9759)||rg["Miscellaneous Symbols and Arrows"](M)&&(M>=11026&&M<=11055||M>=11088&&M<=11097||M>=11192&&M<=11243)||rg["CJK Symbols and Punctuation"](M)||rg.Katakana(M)||rg["Private Use Area"](M)||rg["CJK Compatibility Forms"](M)||rg["Small Form Variants"](M)||rg["Halfwidth and Fullwidth Forms"](M)||8734===M||8756===M||8757===M||M>=9984&&M<=10087||M>=10102&&M<=10131||65532===M||65533===M)}(M))}const sg=Qi(["Adlm","Arab","Armi","Avst","Chrs","Cprt","Egyp","Elym","Gara","Hatr","Hebr","Hung","Khar","Lydi","Mand","Mani","Mend","Merc","Mero","Narb","Nbat","Nkoo","Orkh","Palm","Phli","Phlp","Phnx","Prti","Rohg","Samr","Sarb","Sogo","Syrc","Thaa","Todr","Yezi"]);function as(M){return sg.test(String.fromCodePoint(M))}function os(M,et){return!(!et&&as(M)||M>=2304&&M<=3583||M>=3840&&M<=4255||rg.Khmer(M))}function ls(M){for(const et of M)if(as(et.charCodeAt(0)))return!0;return!1}const ag=new class{constructor(){this.TIMEOUT=5e3,this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus="unavailable",this.pluginURL=null,this.loadScriptResolve=()=>{}}setState(M){this.pluginStatus=M.pluginStatus,this.pluginURL=M.pluginURL}getState(){return{pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(M){if(ag.isParsed())throw new Error("RTL text plugin already registered.");this.applyArabicShaping=M.applyArabicShaping,this.processBidirectionalText=M.processBidirectionalText,this.processStyledBidirectionalText=M.processStyledBidirectionalText,this.loadScriptResolve()}isParsed(){return null!=this.applyArabicShaping&&null!=this.processBidirectionalText&&null!=this.processStyledBidirectionalText}getRTLTextPluginStatus(){return this.pluginStatus}syncState(M,et){return e(this,void 0,void 0,(function*(){if(this.isParsed())return this.getState();if("loading"!==M.pluginStatus)return this.setState(M),M;const Bt=M.pluginURL,Wt=new Promise((M=>{this.loadScriptResolve=M}));et(Bt);const Nt=new Promise((M=>setTimeout((()=>M()),this.TIMEOUT)));if(yield Promise.race([Wt,Nt]),this.isParsed()){const M={pluginStatus:"loaded",pluginURL:Bt};return this.setState(M),M}throw this.setState({pluginStatus:"error",pluginURL:""}),new Error(`RTL Text Plugin failed to import scripts from ${Bt}`)}))}};class cs{constructor(M,et){this.zoom=M,et?(this.now=et.now,this.fadeDuration=et.fadeDuration,this.zoomHistory=et.zoomHistory,this.transition=et.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new Hi,this.transition={})}isSupportedScript(M){return function(M,et){for(const Bt of M)if(!os(Bt.charCodeAt(0),et))return!1;return!0}(M,"loaded"===ag.getRTLTextPluginStatus())}crossFadingFactor(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}getCrossfadeParameters(){const M=this.zoom,et=M-Math.floor(M),Bt=this.crossFadingFactor();return M>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:et+(1-et)*Bt}:{fromScale:.5,toScale:1,t:1-(1-Bt)*et}}}class hs{constructor(M,et){this.property=M,this.value=et,this.expression=function(M,et){if(Vn(M))return new Zn(M,et);if(jn(M)){const Bt=Gn(M,et);if("error"===Bt.result)throw new Error(Bt.value.map((M=>`${M.key}: ${M.message}`)).join(", "));return Bt.value}{let Bt=M;return"color"===et.type&&"string"==typeof M?Bt=ye.parse(M):"padding"!==et.type||"number"!=typeof M&&!Array.isArray(M)?"variableAnchorOffsetCollection"===et.type&&Array.isArray(M)?Bt=_e.parse(M):"projectionDefinition"===et.type&&"string"==typeof M&&(Bt=Ae.parse(M)):Bt=ve.parse(M),{kind:"constant",evaluate:()=>Bt}}}(void 0===et?M.specification.default:et,M.specification)}isDataDriven(){return"source"===this.expression.kind||"composite"===this.expression.kind}possiblyEvaluate(M,et,Bt){return this.property.possiblyEvaluate(this,M,et,Bt)}}class ps{constructor(M){this.property=M,this.value=new hs(M,void 0)}transitioned(M,et){return new ds(this.property,this.value,et,F({},M.transition,this.transition),M.now)}untransitioned(){return new ds(this.property,this.value,null,{},0)}}class fs{constructor(M){this._properties=M,this._values=Object.create(M.defaultTransitionablePropertyValues)}getValue(M){return O(this._values[M].value.value)}setValue(M,et){Object.prototype.hasOwnProperty.call(this._values,M)||(this._values[M]=new ps(this._values[M].property)),this._values[M].value=new hs(this._values[M].property,null===et?void 0:O(et))}getTransition(M){return O(this._values[M].transition)}setTransition(M,et){Object.prototype.hasOwnProperty.call(this._values,M)||(this._values[M]=new ps(this._values[M].property)),this._values[M].transition=O(et)||void 0}serialize(){const M={};for(const et of Object.keys(this._values)){const Bt=this.getValue(et);void 0!==Bt&&(M[et]=Bt);const Wt=this.getTransition(et);void 0!==Wt&&(M[`${et}-transition`]=Wt)}return M}transitioned(M,et){const Bt=new ys(this._properties);for(const Wt of Object.keys(this._values))Bt._values[Wt]=this._values[Wt].transitioned(M,et._values[Wt]);return Bt}untransitioned(){const M=new ys(this._properties);for(const et of Object.keys(this._values))M._values[et]=this._values[et].untransitioned();return M}}class ds{constructor(M,et,Bt,Wt,Nt){this.property=M,this.value=et,this.begin=Nt+Wt.delay||0,this.end=this.begin+Wt.duration||0,M.specification.transition&&(Wt.delay||Wt.duration)&&(this.prior=Bt)}possiblyEvaluate(M,et,Bt){const Wt=M.now||0,Nt=this.value.possiblyEvaluate(M,et,Bt),$t=this.prior;if($t){if(Wt>this.end)return this.prior=null,Nt;if(this.value.isDataDriven())return this.prior=null,Nt;if(WtWt.zoomHistory.lastIntegerZoom?{from:M,to:et}:{from:Bt,to:et}}interpolate(M){return M}}class _s{constructor(M){this.specification=M}possiblyEvaluate(M,et,Bt,Wt){if(void 0!==M.value){if("constant"===M.expression.kind){const Nt=M.expression.evaluate(et,null,{},Bt,Wt);return this._calculate(Nt,Nt,Nt,et)}return this._calculate(M.expression.evaluate(new cs(Math.floor(et.zoom-1),et)),M.expression.evaluate(new cs(Math.floor(et.zoom),et)),M.expression.evaluate(new cs(Math.floor(et.zoom+1),et)),et)}}_calculate(M,et,Bt,Wt){return Wt.zoom>Wt.zoomHistory.lastIntegerZoom?{from:M,to:et}:{from:Bt,to:et}}interpolate(M){return M}}class Ss{constructor(M){this.specification=M}possiblyEvaluate(M,et,Bt,Wt){return!!M.expression.evaluate(et,null,{},Bt,Wt)}interpolate(){return!1}}class As{constructor(M){this.properties=M,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(const et in M){const Bt=M[et];Bt.specification.overridable&&this.overridableProperties.push(et);const Wt=this.defaultPropertyValues[et]=new hs(Bt,void 0),Nt=this.defaultTransitionablePropertyValues[et]=new ps(Bt);this.defaultTransitioningPropertyValues[et]=Nt.untransitioned(),this.defaultPossiblyEvaluatedValues[et]=Wt.possiblyEvaluate({})}}}Ui("DataDrivenProperty",bs),Ui("DataConstantProperty",vs),Ui("CrossFadedDataDrivenProperty",ws),Ui("CrossFadedProperty",_s),Ui("ColorRampProperty",Ss);const lg="-transition";class Ms extends ct{constructor(M,et){if(super(),this.id=M.id,this.type=M.type,this._featureFilter={filter:()=>!0,needGeometry:!1},"custom"!==M.type&&(this.metadata=M.metadata,this.minzoom=M.minzoom,this.maxzoom=M.maxzoom,"background"!==M.type&&(this.source=M.source,this.sourceLayer=M["source-layer"],this.filter=M.filter),et.layout&&(this._unevaluatedLayout=new ms(et.layout)),et.paint)){this._transitionablePaint=new fs(et.paint);for(const et in M.paint)this.setPaintProperty(et,M.paint[et],{validate:!1});for(const et in M.layout)this.setLayoutProperty(et,M.layout[et],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new xs(et.paint)}}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(M){return"visibility"===M?this.visibility:this._unevaluatedLayout.getValue(M)}setLayoutProperty(M,et,Bt={}){null!=et&&this._validate(eg,`layers.${this.id}.layout.${M}`,M,et,Bt)||("visibility"!==M?this._unevaluatedLayout.setValue(M,et):this.visibility=et)}getPaintProperty(M){return M.endsWith(lg)?this._transitionablePaint.getTransition(M.slice(0,-11)):this._transitionablePaint.getValue(M)}setPaintProperty(M,et,Bt={}){if(null!=et&&this._validate(tg,`layers.${this.id}.paint.${M}`,M,et,Bt))return!1;if(M.endsWith(lg))return this._transitionablePaint.setTransition(M.slice(0,-11),et||void 0),!1;{const Bt=this._transitionablePaint._values[M],Wt="cross-faded-data-driven"===Bt.property.specification["property-type"],Nt=Bt.value.isDataDriven(),$t=Bt.value;this._transitionablePaint.setValue(M,et),this._handleSpecialPaintPropertyUpdate(M);const Gr=this._transitionablePaint._values[M].value;return Gr.isDataDriven()||Nt||Wt||this._handleOverridablePaintPropertyUpdate(M,$t,Gr)}}_handleSpecialPaintPropertyUpdate(M){}_handleOverridablePaintPropertyUpdate(M,et,Bt){return!1}isHidden(M){return!!(this.minzoom&&M=this.maxzoom)||"none"===this.visibility}updateTransitions(M){this._transitioningPaint=this._transitionablePaint.transitioned(M,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(M,et){M.getCrossfadeParameters&&(this._crossfadeParameters=M.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(M,void 0,et)),this.paint=this._transitioningPaint.possiblyEvaluate(M,void 0,et)}serialize(){const M={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(M.layout=M.layout||{},M.layout.visibility=this.visibility),D(M,((M,et)=>!(void 0===M||"layout"===et&&!Object.keys(M).length||"paint"===et&&!Object.keys(M).length)))}_validate(M,et,Bt,Wt,Nt={}){return(!Nt||!1!==Nt.validate)&&Ri(this,M.call(Yh,{key:et,layerType:this.type,objectKey:Bt,value:Wt,styleSpec:Ka,style:{glyphs:!0,sprite:!0}}))}is3D(){return!1}isTileClipped(){return!1}hasOffscreenPass(){return!1}resize(){}isStateDependent(){for(const M in this.paint._values){const et=this.paint.get(M);if(et instanceof gs&&zn(et.property.specification)&&("source"===et.value.kind||"composite"===et.value.kind)&&et.value.isStateDependent)return!0}return!1}}const cg={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class zs{constructor(M,et){this._structArray=M,this._pos1=et*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}class Ps{constructor(){this.isTransferred=!1,this.capacity=-1,this.resize(0)}static serialize(M,et){return M._trim(),et&&(M.isTransferred=!0,et.push(M.arrayBuffer)),{length:M.length,arrayBuffer:M.arrayBuffer}}static deserialize(M){const et=Object.create(this.prototype);return et.arrayBuffer=M.arrayBuffer,et.length=M.length,et.capacity=M.arrayBuffer.byteLength/et.bytesPerElement,et._refreshViews(),et}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())}clear(){this.length=0}resize(M){this.reserve(M),this.length=M}reserve(M){if(M>this.capacity){this.capacity=Math.max(M,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const et=this.uint8;this._refreshViews(),et&&this.uint8.set(et)}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}}function Cs(M,et=1){let Bt=0,Wt=0;return{members:M.map((M=>{const Nt=cg[M.type].BYTES_PER_ELEMENT,$t=Bt=Bs(Bt,Math.max(et,Nt)),Gr=M.components||1;return Wt=Math.max(Wt,Nt),Bt+=Nt*Gr,{name:M.name,type:M.type,components:Gr,offset:$t}})),size:Bs(Bt,Math.max(Wt,et)),alignment:et}}function Bs(M,et){return Math.ceil(M/et)*et}class Vs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(M,et){const Bt=this.length;return this.resize(Bt+1),this.emplace(Bt,M,et)}emplace(M,et,Bt){const Wt=2*M;return this.int16[Wt+0]=et,this.int16[Wt+1]=Bt,M}}Vs.prototype.bytesPerElement=4,Ui("StructArrayLayout2i4",Vs);class Es extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(M,et,Bt){const Wt=this.length;return this.resize(Wt+1),this.emplace(Wt,M,et,Bt)}emplace(M,et,Bt,Wt){const Nt=3*M;return this.int16[Nt+0]=et,this.int16[Nt+1]=Bt,this.int16[Nt+2]=Wt,M}}Es.prototype.bytesPerElement=6,Ui("StructArrayLayout3i6",Es);class Ts extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt){const Nt=this.length;return this.resize(Nt+1),this.emplace(Nt,M,et,Bt,Wt)}emplace(M,et,Bt,Wt,Nt){const $t=4*M;return this.int16[$t+0]=et,this.int16[$t+1]=Bt,this.int16[$t+2]=Wt,this.int16[$t+3]=Nt,M}}Ts.prototype.bytesPerElement=8,Ui("StructArrayLayout4i8",Ts);class Fs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt,$t){const Gr=this.length;return this.resize(Gr+1),this.emplace(Gr,M,et,Bt,Wt,Nt,$t)}emplace(M,et,Bt,Wt,Nt,$t,Gr){const mn=6*M;return this.int16[mn+0]=et,this.int16[mn+1]=Bt,this.int16[mn+2]=Wt,this.int16[mn+3]=Nt,this.int16[mn+4]=$t,this.int16[mn+5]=Gr,M}}Fs.prototype.bytesPerElement=12,Ui("StructArrayLayout2i4i12",Fs);class $s extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt,$t){const Gr=this.length;return this.resize(Gr+1),this.emplace(Gr,M,et,Bt,Wt,Nt,$t)}emplace(M,et,Bt,Wt,Nt,$t,Gr){const mn=4*M,Hn=8*M;return this.int16[mn+0]=et,this.int16[mn+1]=Bt,this.uint8[Hn+4]=Wt,this.uint8[Hn+5]=Nt,this.uint8[Hn+6]=$t,this.uint8[Hn+7]=Gr,M}}$s.prototype.bytesPerElement=8,Ui("StructArrayLayout2i4ub8",$s);class Ls extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(M,et){const Bt=this.length;return this.resize(Bt+1),this.emplace(Bt,M,et)}emplace(M,et,Bt){const Wt=2*M;return this.float32[Wt+0]=et,this.float32[Wt+1]=Bt,M}}Ls.prototype.bytesPerElement=8,Ui("StructArrayLayout2f8",Ls);class Ds extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so){const uo=this.length;return this.resize(uo+1),this.emplace(uo,M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so)}emplace(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo){const Io=10*M;return this.uint16[Io+0]=et,this.uint16[Io+1]=Bt,this.uint16[Io+2]=Wt,this.uint16[Io+3]=Nt,this.uint16[Io+4]=$t,this.uint16[Io+5]=Gr,this.uint16[Io+6]=mn,this.uint16[Io+7]=Hn,this.uint16[Io+8]=so,this.uint16[Io+9]=uo,M}}Ds.prototype.bytesPerElement=20,Ui("StructArrayLayout10ui20",Ds);class Os extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io){const Po=this.length;return this.resize(Po+1),this.emplace(Po,M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io)}emplace(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po){const To=12*M;return this.int16[To+0]=et,this.int16[To+1]=Bt,this.int16[To+2]=Wt,this.int16[To+3]=Nt,this.uint16[To+4]=$t,this.uint16[To+5]=Gr,this.uint16[To+6]=mn,this.uint16[To+7]=Hn,this.int16[To+8]=so,this.int16[To+9]=uo,this.int16[To+10]=Io,this.int16[To+11]=Po,M}}Os.prototype.bytesPerElement=24,Ui("StructArrayLayout4i4ui4i24",Os);class Rs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(M,et,Bt){const Wt=this.length;return this.resize(Wt+1),this.emplace(Wt,M,et,Bt)}emplace(M,et,Bt,Wt){const Nt=3*M;return this.float32[Nt+0]=et,this.float32[Nt+1]=Bt,this.float32[Nt+2]=Wt,M}}Rs.prototype.bytesPerElement=12,Ui("StructArrayLayout3f12",Rs);class js extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(M){const et=this.length;return this.resize(et+1),this.emplace(et,M)}emplace(M,et){return this.uint32[1*M+0]=et,M}}js.prototype.bytesPerElement=4,Ui("StructArrayLayout1ul4",js);class Ns extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn){const so=this.length;return this.resize(so+1),this.emplace(so,M,et,Bt,Wt,Nt,$t,Gr,mn,Hn)}emplace(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so){const uo=10*M,Io=5*M;return this.int16[uo+0]=et,this.int16[uo+1]=Bt,this.int16[uo+2]=Wt,this.int16[uo+3]=Nt,this.int16[uo+4]=$t,this.int16[uo+5]=Gr,this.uint32[Io+3]=mn,this.uint16[uo+8]=Hn,this.uint16[uo+9]=so,M}}Ns.prototype.bytesPerElement=20,Ui("StructArrayLayout6i1ul2ui20",Ns);class Us extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt,$t){const Gr=this.length;return this.resize(Gr+1),this.emplace(Gr,M,et,Bt,Wt,Nt,$t)}emplace(M,et,Bt,Wt,Nt,$t,Gr){const mn=6*M;return this.int16[mn+0]=et,this.int16[mn+1]=Bt,this.int16[mn+2]=Wt,this.int16[mn+3]=Nt,this.int16[mn+4]=$t,this.int16[mn+5]=Gr,M}}Us.prototype.bytesPerElement=12,Ui("StructArrayLayout2i2i2i12",Us);class qs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt){const $t=this.length;return this.resize($t+1),this.emplace($t,M,et,Bt,Wt,Nt)}emplace(M,et,Bt,Wt,Nt,$t){const Gr=4*M,mn=8*M;return this.float32[Gr+0]=et,this.float32[Gr+1]=Bt,this.float32[Gr+2]=Wt,this.int16[mn+6]=Nt,this.int16[mn+7]=$t,M}}qs.prototype.bytesPerElement=16,Ui("StructArrayLayout2f1f2i16",qs);class Gs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt,$t){const Gr=this.length;return this.resize(Gr+1),this.emplace(Gr,M,et,Bt,Wt,Nt,$t)}emplace(M,et,Bt,Wt,Nt,$t,Gr){const mn=16*M,Hn=4*M,so=8*M;return this.uint8[mn+0]=et,this.uint8[mn+1]=Bt,this.float32[Hn+1]=Wt,this.float32[Hn+2]=Nt,this.int16[so+6]=$t,this.int16[so+7]=Gr,M}}Gs.prototype.bytesPerElement=16,Ui("StructArrayLayout2ub2f2i16",Gs);class Zs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(M,et,Bt){const Wt=this.length;return this.resize(Wt+1),this.emplace(Wt,M,et,Bt)}emplace(M,et,Bt,Wt){const Nt=3*M;return this.uint16[Nt+0]=et,this.uint16[Nt+1]=Bt,this.uint16[Nt+2]=Wt,M}}Zs.prototype.bytesPerElement=6,Ui("StructArrayLayout3ui6",Zs);class Xs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba){const Ta=this.length;return this.resize(Ta+1),this.emplace(Ta,M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba)}emplace(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba,Ta){const Va=24*M,za=12*M,Fa=48*M;return this.int16[Va+0]=et,this.int16[Va+1]=Bt,this.uint16[Va+2]=Wt,this.uint16[Va+3]=Nt,this.uint32[za+2]=$t,this.uint32[za+3]=Gr,this.uint32[za+4]=mn,this.uint16[Va+10]=Hn,this.uint16[Va+11]=so,this.uint16[Va+12]=uo,this.float32[za+7]=Io,this.float32[za+8]=Po,this.uint8[Fa+36]=To,this.uint8[Fa+37]=Eo,this.uint8[Fa+38]=Ia,this.uint32[za+10]=Ba,this.int16[Va+22]=Ta,M}}Xs.prototype.bytesPerElement=48,Ui("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",Xs);class Ks extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba,Ta,Va,za,Fa,Ea,La,Da,Ka,Oa,$a,Al){const Sl=this.length;return this.resize(Sl+1),this.emplace(Sl,M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba,Ta,Va,za,Fa,Ea,La,Da,Ka,Oa,$a,Al)}emplace(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba,Ta,Va,za,Fa,Ea,La,Da,Ka,Oa,$a,Al,Sl){const Zl=32*M,Gl=16*M;return this.int16[Zl+0]=et,this.int16[Zl+1]=Bt,this.int16[Zl+2]=Wt,this.int16[Zl+3]=Nt,this.int16[Zl+4]=$t,this.int16[Zl+5]=Gr,this.int16[Zl+6]=mn,this.int16[Zl+7]=Hn,this.uint16[Zl+8]=so,this.uint16[Zl+9]=uo,this.uint16[Zl+10]=Io,this.uint16[Zl+11]=Po,this.uint16[Zl+12]=To,this.uint16[Zl+13]=Eo,this.uint16[Zl+14]=Ia,this.uint16[Zl+15]=Ba,this.uint16[Zl+16]=Ta,this.uint16[Zl+17]=Va,this.uint16[Zl+18]=za,this.uint16[Zl+19]=Fa,this.uint16[Zl+20]=Ea,this.uint16[Zl+21]=La,this.uint16[Zl+22]=Da,this.uint32[Gl+12]=Ka,this.float32[Gl+13]=Oa,this.float32[Gl+14]=$a,this.uint16[Zl+30]=Al,this.uint16[Zl+31]=Sl,M}}Ks.prototype.bytesPerElement=64,Ui("StructArrayLayout8i15ui1ul2f2ui64",Ks);class Hs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(M){const et=this.length;return this.resize(et+1),this.emplace(et,M)}emplace(M,et){return this.float32[1*M+0]=et,M}}Hs.prototype.bytesPerElement=4,Ui("StructArrayLayout1f4",Hs);class Ys extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(M,et,Bt){const Wt=this.length;return this.resize(Wt+1),this.emplace(Wt,M,et,Bt)}emplace(M,et,Bt,Wt){const Nt=3*M;return this.uint16[6*M+0]=et,this.float32[Nt+1]=Bt,this.float32[Nt+2]=Wt,M}}Ys.prototype.bytesPerElement=12,Ui("StructArrayLayout1ui2f12",Ys);class Js extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(M,et,Bt){const Wt=this.length;return this.resize(Wt+1),this.emplace(Wt,M,et,Bt)}emplace(M,et,Bt,Wt){const Nt=4*M;return this.uint32[2*M+0]=et,this.uint16[Nt+2]=Bt,this.uint16[Nt+3]=Wt,M}}Js.prototype.bytesPerElement=8,Ui("StructArrayLayout1ul2ui8",Js);class Ws extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(M,et){const Bt=this.length;return this.resize(Bt+1),this.emplace(Bt,M,et)}emplace(M,et,Bt){const Wt=2*M;return this.uint16[Wt+0]=et,this.uint16[Wt+1]=Bt,M}}Ws.prototype.bytesPerElement=4,Ui("StructArrayLayout2ui4",Ws);class Qs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(M){const et=this.length;return this.resize(et+1),this.emplace(et,M)}emplace(M,et){return this.uint16[1*M+0]=et,M}}Qs.prototype.bytesPerElement=2,Ui("StructArrayLayout1ui2",Qs);class ta extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt){const Nt=this.length;return this.resize(Nt+1),this.emplace(Nt,M,et,Bt,Wt)}emplace(M,et,Bt,Wt,Nt){const $t=4*M;return this.float32[$t+0]=et,this.float32[$t+1]=Bt,this.float32[$t+2]=Wt,this.float32[$t+3]=Nt,M}}ta.prototype.bytesPerElement=16,Ui("StructArrayLayout4f16",ta);class ea extends zs{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new $t(this.anchorPointX,this.anchorPointY)}}ea.prototype.size=20;class ra extends Ns{get(M){return new ea(this,M)}}Ui("CollisionBoxArray",ra);class na extends zs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(M){this._structArray.uint8[this._pos1+37]=M}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(M){this._structArray.uint8[this._pos1+38]=M}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(M){this._structArray.uint32[this._pos4+10]=M}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}na.prototype.size=48;class ia extends Xs{get(M){return new na(this,M)}}Ui("PlacedSymbolArray",ia);class sa extends zs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(M){this._structArray.uint32[this._pos4+12]=M}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}sa.prototype.size=64;class aa extends Ks{get(M){return new sa(this,M)}}Ui("SymbolInstanceArray",aa);class oa extends Hs{getoffsetX(M){return this.float32[1*M+0]}}Ui("GlyphOffsetArray",oa);class la extends Es{getx(M){return this.int16[3*M+0]}gety(M){return this.int16[3*M+1]}gettileUnitDistanceFromAnchor(M){return this.int16[3*M+2]}}Ui("SymbolLineVertexArray",la);class ua extends zs{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}ua.prototype.size=12;class ca extends Ys{get(M){return new ua(this,M)}}Ui("TextAnchorOffsetArray",ca);class ha extends zs{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}ha.prototype.size=8;class pa extends Js{get(M){return new ha(this,M)}}Ui("FeatureIndexArray",pa);class fa extends Vs{}class da extends Vs{}class ya extends Vs{}class ma extends Fs{}class ga extends $s{}class xa extends Ls{}class va extends Ds{}class ba extends Os{}class wa extends Rs{}class _a extends js{}class Sa extends Us{}class Aa extends Gs{}class ka extends Zs{}class Ma extends Ws{}const hg=Cs([{name:"a_pos",components:2,type:"Int16"}],4),{members:gg}=hg;class Pa{constructor(M=[]){this._forceNewSegmentOnNextPrepare=!1,this.segments=M}prepareSegment(M,et,Bt,Wt){const Nt=this.segments[this.segments.length-1];return M>Pa.MAX_VERTEX_ARRAY_LENGTH&&j(`Max vertices per segment is ${Pa.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${M}. Consider using the \`fillLargeMeshArrays\` function if you require meshes with more than ${Pa.MAX_VERTEX_ARRAY_LENGTH} vertices.`),this._forceNewSegmentOnNextPrepare||!Nt||Nt.vertexLength+M>Pa.MAX_VERTEX_ARRAY_LENGTH||Nt.sortKey!==Wt?this.createNewSegment(et,Bt,Wt):Nt}createNewSegment(M,et,Bt){const Wt={vertexOffset:M.length,primitiveOffset:et.length,vertexLength:0,primitiveLength:0,vaos:{}};return void 0!==Bt&&(Wt.sortKey=Bt),this._forceNewSegmentOnNextPrepare=!1,this.segments.push(Wt),Wt}getOrCreateLatestSegment(M,et,Bt){return this.prepareSegment(0,M,et,Bt)}forceNewSegmentOnNextPrepare(){this._forceNewSegmentOnNextPrepare=!0}get(){return this.segments}destroy(){for(const M of this.segments)for(const et in M.vaos)M.vaos[et].destroy()}static simpleSegment(M,et,Bt,Wt){return new Pa([{vertexOffset:M,primitiveOffset:et,vertexLength:Bt,primitiveLength:Wt,vaos:{},sortKey:0}])}}function Ca(M,et){return 256*(M=E(Math.floor(M),0,255))+E(Math.floor(et),0,255)}Pa.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Ui("SegmentVector",Pa);const ug=Cs([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]);var dg,pg,mg,Cg={exports:{}},Ig={exports:{}},fg={exports:{}},yg=function(){if(mg)return Cg.exports;mg=1;var M=(dg||(dg=1,Ig.exports=function(M,et){var Bt,Wt,Nt,$t,Gr,mn,Hn,so;for(Wt=M.length-(Bt=3&M.length),Nt=et,Gr=3432918353,mn=461845907,so=0;so>>16)*Gr&65535)<<16)&4294967295)<<15|Hn>>>17))*mn+(((Hn>>>16)*mn&65535)<<16)&4294967295)<<13|Nt>>>19))+((5*(Nt>>>16)&65535)<<16)&4294967295))+((58964+($t>>>16)&65535)<<16);switch(Hn=0,Bt){case 3:Hn^=(255&M.charCodeAt(so+2))<<16;case 2:Hn^=(255&M.charCodeAt(so+1))<<8;case 1:Nt^=Hn=(65535&(Hn=(Hn=(65535&(Hn^=255&M.charCodeAt(so)))*Gr+(((Hn>>>16)*Gr&65535)<<16)&4294967295)<<15|Hn>>>17))*mn+(((Hn>>>16)*mn&65535)<<16)&4294967295}return Nt^=M.length,Nt=2246822507*(65535&(Nt^=Nt>>>16))+((2246822507*(Nt>>>16)&65535)<<16)&4294967295,Nt=3266489909*(65535&(Nt^=Nt>>>13))+((3266489909*(Nt>>>16)&65535)<<16)&4294967295,(Nt^=Nt>>>16)>>>0}),Ig.exports),et=(pg||(pg=1,fg.exports=function(M,et){for(var Bt,Wt=M.length,Nt=et^Wt,$t=0;Wt>=4;)Bt=1540483477*(65535&(Bt=255&M.charCodeAt($t)|(255&M.charCodeAt(++$t))<<8|(255&M.charCodeAt(++$t))<<16|(255&M.charCodeAt(++$t))<<24))+((1540483477*(Bt>>>16)&65535)<<16),Nt=1540483477*(65535&Nt)+((1540483477*(Nt>>>16)&65535)<<16)^(Bt=1540483477*(65535&(Bt^=Bt>>>24))+((1540483477*(Bt>>>16)&65535)<<16)),Wt-=4,++$t;switch(Wt){case 3:Nt^=(255&M.charCodeAt($t+2))<<16;case 2:Nt^=(255&M.charCodeAt($t+1))<<8;case 1:Nt=1540483477*(65535&(Nt^=255&M.charCodeAt($t)))+((1540483477*(Nt>>>16)&65535)<<16)}return Nt=1540483477*(65535&(Nt^=Nt>>>13))+((1540483477*(Nt>>>16)&65535)<<16),(Nt^=Nt>>>15)>>>0}),fg.exports);return Cg.exports=M,Cg.exports.murmur3=M,Cg.exports.murmur2=et,Cg.exports}(),Ag=r(yg);class Ra{constructor(){this.ids=[],this.positions=[],this.indexed=!1}add(M,et,Bt,Wt){this.ids.push(ja(M)),this.positions.push(et,Bt,Wt)}getPositions(M){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");const et=ja(M);let Bt=0,Wt=this.ids.length-1;for(;Bt>1;this.ids[M]>=et?Wt=M:Bt=M+1}const Nt=[];for(;this.ids[Bt]===et;)Nt.push({index:this.positions[3*Bt],start:this.positions[3*Bt+1],end:this.positions[3*Bt+2]}),Bt++;return Nt}static serialize(M,et){const Bt=new Float64Array(M.ids),Wt=new Uint32Array(M.positions);return Na(Bt,Wt,0,Bt.length-1),et&&et.push(Bt.buffer,Wt.buffer),{ids:Bt,positions:Wt}}static deserialize(M){const et=new Ra;return et.ids=M.ids,et.positions=M.positions,et.indexed=!0,et}}function ja(M){const et=+M;return!isNaN(et)&&et<=Number.MAX_SAFE_INTEGER?et:Ag(String(M))}function Na(M,et,Bt,Wt){for(;Bt>1];let $t=Bt-1,Gr=Wt+1;for(;;){do{$t++}while(M[$t]Nt);if($t>=Gr)break;Ua(M,$t,Gr),Ua(et,3*$t,3*Gr),Ua(et,3*$t+1,3*Gr+1),Ua(et,3*$t+2,3*Gr+2)}Gr-Bt`u_${M}`)),this.type=Bt}setUniform(M,et,Bt){M.set(Bt.constantOr(this.value))}getBinding(M,et,Bt){return"color"===this.type?new Xa(M,et):new Ga(M,et)}}class Ja{constructor(M,et){this.uniformNames=et.map((M=>`u_${M}`)),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1}setConstantPatternPositions(M,et){this.pixelRatioFrom=et.pixelRatio,this.pixelRatioTo=M.pixelRatio,this.patternFrom=et.tlbr,this.patternTo=M.tlbr}setUniform(M,et,Bt,Wt){const Nt="u_pattern_to"===Wt?this.patternTo:"u_pattern_from"===Wt?this.patternFrom:"u_pixel_ratio_to"===Wt?this.pixelRatioTo:"u_pixel_ratio_from"===Wt?this.pixelRatioFrom:null;Nt&&M.set(Nt)}getBinding(M,et,Bt){return"u_pattern"===Bt.substr(0,9)?new Za(M,et):new Ga(M,et)}}class Wa{constructor(M,et,Bt,Wt){this.expression=M,this.type=Bt,this.maxValue=0,this.paintVertexAttributes=et.map((M=>({name:`a_${M}`,type:"Float32",components:"color"===Bt?2:1,offset:0}))),this.paintVertexArray=new Wt}populatePaintArray(M,et,Bt,Wt,Nt){const $t=this.paintVertexArray.length,Gr=this.expression.evaluate(new cs(0),et,{},Wt,[],Nt);this.paintVertexArray.resize(M),this._setPaintValue($t,M,Gr)}updatePaintArray(M,et,Bt,Wt){const Nt=this.expression.evaluate({zoom:0},Bt,Wt);this._setPaintValue(M,et,Nt)}_setPaintValue(M,et,Bt){if("color"===this.type){const Wt=Ha(Bt);for(let Bt=M;Bt`u_${M}_t`)),this.type=Bt,this.useIntegerZoom=Wt,this.zoom=Nt,this.maxValue=0,this.paintVertexAttributes=et.map((M=>({name:`a_${M}`,type:"Float32",components:"color"===Bt?4:2,offset:0}))),this.paintVertexArray=new $t}populatePaintArray(M,et,Bt,Wt,Nt){const $t=this.expression.evaluate(new cs(this.zoom),et,{},Wt,[],Nt),Gr=this.expression.evaluate(new cs(this.zoom+1),et,{},Wt,[],Nt),mn=this.paintVertexArray.length;this.paintVertexArray.resize(M),this._setPaintValue(mn,M,$t,Gr)}updatePaintArray(M,et,Bt,Wt){const Nt=this.expression.evaluate({zoom:this.zoom},Bt,Wt),$t=this.expression.evaluate({zoom:this.zoom+1},Bt,Wt);this._setPaintValue(M,et,Nt,$t)}_setPaintValue(M,et,Bt,Wt){if("color"===this.type){const Nt=Ha(Bt),$t=Ha(Wt);for(let Bt=M;Bt`#define HAS_UNIFORM_${M}`)))}return M}getBinderAttributes(){const M=[];for(const et in this.binders){const Bt=this.binders[et];if(Bt instanceof Wa||Bt instanceof Qa)for(let et=0;et!0){this.programConfigurations={};for(const Wt of M)this.programConfigurations[Wt.id]=new eo(Wt,et,Bt);this.needsUpload=!1,this._featureMap=new Ra,this._bufferOffset=0}populatePaintArrays(M,et,Bt,Wt,Nt,$t){for(const Bt in this.programConfigurations)this.programConfigurations[Bt].populatePaintArrays(M,et,Wt,Nt,$t);void 0!==et.id&&this._featureMap.add(et.id,Bt,this._bufferOffset,M),this._bufferOffset=M,this.needsUpload=!0}updatePaintArrays(M,et,Bt,Wt){for(const Nt of Bt)this.needsUpload=this.programConfigurations[Nt.id].updatePaintArrays(M,this._featureMap,et,Nt,Wt)||this.needsUpload}get(M){return this.programConfigurations[M]}upload(M){if(this.needsUpload){for(const et in this.programConfigurations)this.programConfigurations[et].upload(M);this.needsUpload=!1}}destroy(){for(const M in this.programConfigurations)this.programConfigurations[M].destroy()}}function no(M,et){return{"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[M]||[M.replace(`${et}-`,"").replace(/-/g,"_")]}function io(M,et,Bt){const Wt={color:{source:Ls,composite:ta},number:{source:Hs,composite:Ls}},Nt=function(M){return{"line-pattern":{source:va,composite:va},"fill-pattern":{source:va,composite:va},"fill-extrusion-pattern":{source:va,composite:va}}[M]}(M);return Nt&&Nt[Bt]||Wt[et][Bt]}Ui("ConstantBinder",Ya),Ui("CrossFadedConstantBinder",Ja),Ui("SourceExpressionBinder",Wa),Ui("CrossFadedCompositeBinder",to),Ui("CompositeExpressionBinder",Qa),Ui("ProgramConfiguration",eo,{omit:["_buffers"]}),Ui("ProgramConfigurationSet",ro);const bg=Math.pow(2,14)-1,vg=-bg-1;function oo(M){const et=To/M.extent,Bt=M.loadGeometry();for(let M=0;MBt.x+1||$tBt.y+1)&&j("Geometry exceeds allowed extent, reduce your vector tile buffer size")}}return Bt}function lo(M,et){return{type:M.type,id:M.id,properties:M.properties,geometry:et?oo(M):[]}}const xg=-32768;function co(M,et,Bt,Wt,Nt){M.emplaceBack(xg+8*et+Wt,xg+8*Bt+Nt)}class ho{constructor(M){this.zoom=M.zoom,this.overscaling=M.overscaling,this.layers=M.layers,this.layerIds=this.layers.map((M=>M.id)),this.index=M.index,this.hasPattern=!1,this.layoutVertexArray=new da,this.indexArray=new ka,this.segments=new Pa,this.programConfigurations=new ro(M.layers,M.zoom),this.stateDependentLayerIds=this.layers.filter((M=>M.isStateDependent())).map((M=>M.id))}populate(M,et,Bt){const Wt=this.layers[0],Nt=[];let $t=null,Gr=!1,mn="heatmap"===Wt.type;if("circle"===Wt.type){const M=Wt;$t=M.layout.get("circle-sort-key"),Gr=!$t.isConstant(),mn=mn||"map"===M.paint.get("circle-pitch-alignment")}const Hn=mn?et.subdivisionGranularity.circle:1;for(const{feature:et,id:Wt,index:mn,sourceLayerIndex:Hn}of M){const M=this.layers[0]._featureFilter.needGeometry,so=lo(et,M);if(!this.layers[0]._featureFilter.filter(new cs(this.zoom),so,Bt))continue;const uo=Gr?$t.evaluate(so,{},Bt):void 0,Io={id:Wt,properties:et.properties,type:et.type,sourceLayerIndex:Hn,index:mn,geometry:M?so.geometry:oo(et),patterns:{},sortKey:uo};Nt.push(Io)}Gr&&Nt.sort(((M,et)=>M.sortKey-et.sortKey));for(const Wt of Nt){const{geometry:Nt,index:$t,sourceLayerIndex:Gr}=Wt,mn=M[$t].feature;this.addFeature(Wt,Nt,$t,Bt,Hn),et.featureIndex.insert(mn,Nt,$t,Gr,this.index)}}update(M,et,Bt){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(M,et,this.stateDependentLayers,Bt)}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(M){this.uploaded||(this.layoutVertexBuffer=M.createVertexBuffer(this.layoutVertexArray,gg),this.indexBuffer=M.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(M),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}addFeature(M,et,Bt,Wt,Nt=1){let $t;switch(Nt){case 1:$t=[0,7];break;case 3:$t=[0,2,5,7];break;case 5:$t=[0,1,3,4,6,7];break;case 7:$t=[0,1,2,3,4,5,6,7];break;default:throw new Error(`Invalid circle bucket granularity: ${Nt}; valid values are 1, 3, 5, 7.`)}const Gr=$t.length;for(const Bt of et)for(const et of Bt){const Bt=et.x,Wt=et.y;if(Bt<0||Bt>=To||Wt<0||Wt>=To)continue;const Nt=this.segments.prepareSegment(Gr*Gr,this.layoutVertexArray,this.indexArray,M.sortKey),mn=Nt.vertexLength;for(let M=0;M1){if(go(M,et))return!0;for(let Wt=0;Wt1?Bt:Bt.sub(et)._mult(Nt)._add(et))}function wo(M,et){let Bt,Wt,Nt,$t=!1;for(let Gr=0;Gret.y!=Nt.y>et.y&&et.x<(Nt.x-Wt.x)*(et.y-Wt.y)/(Nt.y-Wt.y)+Wt.x&&($t=!$t)}return $t}function _o(M,et){let Bt=!1;for(let Wt=0,Nt=M.length-1;Wtet.y!=Gr.y>et.y&&et.x<(Gr.x-$t.x)*(et.y-$t.y)/(Gr.y-$t.y)+$t.x&&(Bt=!Bt)}return Bt}function So(M,et,Bt){const Wt=Bt[0],Nt=Bt[2];if(M.xNt.x&&et.x>Nt.x||M.yNt.y&&et.y>Nt.y)return!1;const $t=N(M,et,Bt[0]);return $t!==N(M,et,Bt[1])||$t!==N(M,et,Bt[2])||$t!==N(M,et,Bt[3])}function Ao(M,et,Bt){const Wt=et.paint.get(M).value;return"constant"===Wt.kind?Wt.value:Bt.programConfigurations.get(et.id).getMaxValue(M)}function ko(M){return Math.sqrt(M[0]*M[0]+M[1]*M[1])}function Mo(M,et,Bt,Wt,Nt){if(!et[0]&&!et[1])return M;const Gr=$t.convert(et)._mult(Nt);"viewport"===Bt&&Gr._rotate(-Wt);const mn=[];for(let et=0;etBo(M,et)))}(mn,Gr),Io=so?Hn*$t:Hn;for(const M of Wt)for(const et of M){const M=so?et:Bo(et,Gr);let Bt=Io;const Wt=_([],[et.x,et.y,0,1],Gr);if("viewport"===this.paint.get("circle-pitch-scale")&&"map"===this.paint.get("circle-pitch-alignment")?Bt*=Wt[3]/Nt.cameraToCenterDistance:"map"===this.paint.get("circle-pitch-scale")&&"viewport"===this.paint.get("circle-pitch-alignment")&&(Bt*=Nt.cameraToCenterDistance/Wt[3]),fo(uo,M,Bt))return!0}return!1}}function Bo(M,et){const Bt=_([],[M.x,M.y,0,1],et);return new $t(Bt[0]/Bt[3],Bt[1]/Bt[3])}class Vo extends ho{}let Bg;Ui("HeatmapBucket",Vo,{omit:["layers"]});var Zg={get paint(){return Bg=Bg||new As({"heatmap-radius":new bs(Ka.paint_heatmap["heatmap-radius"]),"heatmap-weight":new bs(Ka.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new vs(Ka.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Ss(Ka.paint_heatmap["heatmap-color"]),"heatmap-opacity":new vs(Ka.paint_heatmap["heatmap-opacity"])})}};function Fo(M,{width:et,height:Bt},Wt,Nt){if(Nt){if(Nt instanceof Uint8ClampedArray)Nt=new Uint8Array(Nt.buffer);else if(Nt.length!==et*Bt*Wt)throw new RangeError(`mismatched image size. expected: ${Nt.length} but got: ${et*Bt*Wt}`)}else Nt=new Uint8Array(et*Bt*Wt);return M.width=et,M.height=Bt,M.data=Nt,M}function $o(M,{width:et,height:Bt},Wt){if(et===M.width&&Bt===M.height)return;const Nt=Fo({},{width:et,height:Bt},Wt);Lo(M,Nt,{x:0,y:0},{x:0,y:0},{width:Math.min(M.width,et),height:Math.min(M.height,Bt)},Wt),M.width=et,M.height=Bt,M.data=Nt.data}function Lo(M,et,Bt,Wt,Nt,$t){if(0===Nt.width||0===Nt.height)return et;if(Nt.width>M.width||Nt.height>M.height||Bt.x>M.width-Nt.width||Bt.y>M.height-Nt.height)throw new RangeError("out of range source coordinates for image copy");if(Nt.width>et.width||Nt.height>et.height||Wt.x>et.width-Nt.width||Wt.y>et.height-Nt.height)throw new RangeError("out of range destination coordinates for image copy");const Gr=M.data,mn=et.data;if(Gr===mn)throw new Error("srcData equals dstData, so image is already copied");for(let Hn=0;Hn{et[M.evaluationKey]=$t;const Gr=M.expression.evaluate(et);Nt.data[Bt+Wt+0]=Math.floor(255*Gr.r/Gr.a),Nt.data[Bt+Wt+1]=Math.floor(255*Gr.g/Gr.a),Nt.data[Bt+Wt+2]=Math.floor(255*Gr.b/Gr.a),Nt.data[Bt+Wt+3]=Math.floor(255*Gr.a)};if(M.clips)for(let et=0,Nt=0;et0)for(let Nt=et;Nt=et;Nt-=Wt)$t=xl(Nt/Wt|0,M[Nt],M[Nt+1],$t);return $t&&pl($t,$t.next)&&(vl($t),$t=$t.next),$t}function Jo(M,et){if(!M)return M;et||(et=M);let Bt,Wt=M;do{if(Bt=!1,Wt.steiner||!pl(Wt,Wt.next)&&0!==hl(Wt.prev,Wt,Wt.next))Wt=Wt.next;else{if(vl(Wt),Wt=et=Wt.prev,Wt===Wt.next)break;Bt=!0}}while(Bt||Wt!==et);return et}function Wo(M,et,Bt,Wt,Nt,$t,Gr){if(!M)return;!Gr&&$t&&function(M,et,Bt,Wt){let Nt=M;do{0===Nt.z&&(Nt.z=al(Nt.x,Nt.y,et,Bt,Wt)),Nt.prevZ=Nt.prev,Nt.nextZ=Nt.next,Nt=Nt.next}while(Nt!==M);Nt.prevZ.nextZ=null,Nt.prevZ=null,function(M){let et,Bt=1;do{let Wt,Nt=M;M=null;let $t=null;for(et=0;Nt;){et++;let Gr=Nt,mn=0;for(let M=0;M0||Hn>0&&Gr;)0!==mn&&(0===Hn||!Gr||Nt.z<=Gr.z)?(Wt=Nt,Nt=Nt.nextZ,mn--):(Wt=Gr,Gr=Gr.nextZ,Hn--),$t?$t.nextZ=Wt:M=Wt,Wt.prevZ=$t,$t=Wt;Nt=Gr}$t.nextZ=null,Bt*=2}while(et>1)}(Nt)}(M,Wt,Nt,$t);let mn=M;for(;M.prev!==M.next;){const Hn=M.prev,so=M.next;if($t?tl(M,Wt,Nt,$t):Qo(M))et.push(Hn.i,M.i,so.i),vl(M),M=so.next,mn=so.next;else if((M=so)===mn){Gr?1===Gr?Wo(M=el(Jo(M),et),et,Bt,Wt,Nt,$t,2):2===Gr&&rl(M,et,Bt,Wt,Nt,$t):Wo(Jo(M),et,Bt,Wt,Nt,$t,1);break}}}function Qo(M){const et=M.prev,Bt=M,Wt=M.next;if(hl(et,Bt,Wt)>=0)return!1;const Nt=et.x,$t=Bt.x,Gr=Wt.x,mn=et.y,Hn=Bt.y,so=Wt.y,uo=Math.min(Nt,$t,Gr),Io=Math.min(mn,Hn,so),Po=Math.max(Nt,$t,Gr),To=Math.max(mn,Hn,so);let Eo=Wt.next;for(;Eo!==et;){if(Eo.x>=uo&&Eo.x<=Po&&Eo.y>=Io&&Eo.y<=To&&ul(Nt,mn,$t,Hn,Gr,so,Eo.x,Eo.y)&&hl(Eo.prev,Eo,Eo.next)>=0)return!1;Eo=Eo.next}return!0}function tl(M,et,Bt,Wt){const Nt=M.prev,$t=M,Gr=M.next;if(hl(Nt,$t,Gr)>=0)return!1;const mn=Nt.x,Hn=$t.x,so=Gr.x,uo=Nt.y,Io=$t.y,Po=Gr.y,To=Math.min(mn,Hn,so),Eo=Math.min(uo,Io,Po),Ia=Math.max(mn,Hn,so),Ba=Math.max(uo,Io,Po),Ta=al(To,Eo,et,Bt,Wt),Va=al(Ia,Ba,et,Bt,Wt);let za=M.prevZ,Fa=M.nextZ;for(;za&&za.z>=Ta&&Fa&&Fa.z<=Va;){if(za.x>=To&&za.x<=Ia&&za.y>=Eo&&za.y<=Ba&&za!==Nt&&za!==Gr&&ul(mn,uo,Hn,Io,so,Po,za.x,za.y)&&hl(za.prev,za,za.next)>=0)return!1;if(za=za.prevZ,Fa.x>=To&&Fa.x<=Ia&&Fa.y>=Eo&&Fa.y<=Ba&&Fa!==Nt&&Fa!==Gr&&ul(mn,uo,Hn,Io,so,Po,Fa.x,Fa.y)&&hl(Fa.prev,Fa,Fa.next)>=0)return!1;Fa=Fa.nextZ}for(;za&&za.z>=Ta;){if(za.x>=To&&za.x<=Ia&&za.y>=Eo&&za.y<=Ba&&za!==Nt&&za!==Gr&&ul(mn,uo,Hn,Io,so,Po,za.x,za.y)&&hl(za.prev,za,za.next)>=0)return!1;za=za.prevZ}for(;Fa&&Fa.z<=Va;){if(Fa.x>=To&&Fa.x<=Ia&&Fa.y>=Eo&&Fa.y<=Ba&&Fa!==Nt&&Fa!==Gr&&ul(mn,uo,Hn,Io,so,Po,Fa.x,Fa.y)&&hl(Fa.prev,Fa,Fa.next)>=0)return!1;Fa=Fa.nextZ}return!0}function el(M,et){let Bt=M;do{const Wt=Bt.prev,Nt=Bt.next.next;!pl(Wt,Nt)&&fl(Wt,Bt,Bt.next,Nt)&&ml(Wt,Nt)&&ml(Nt,Wt)&&(et.push(Wt.i,Bt.i,Nt.i),vl(Bt),vl(Bt.next),Bt=M=Nt),Bt=Bt.next}while(Bt!==M);return Jo(Bt)}function rl(M,et,Bt,Wt,Nt,$t){let Gr=M;do{let M=Gr.next.next;for(;M!==Gr.prev;){if(Gr.i!==M.i&&cl(Gr,M)){let mn=gl(Gr,M);return Gr=Jo(Gr,Gr.next),mn=Jo(mn,mn.next),Wo(Gr,et,Bt,Wt,Nt,$t,0),void Wo(mn,et,Bt,Wt,Nt,$t,0)}M=M.next}Gr=Gr.next}while(Gr!==M)}function nl(M,et){let Bt=M.x-et.x;return 0===Bt&&(Bt=M.y-et.y,0===Bt)&&(Bt=(M.next.y-M.y)/(M.next.x-M.x)-(et.next.y-et.y)/(et.next.x-et.x)),Bt}function il(M,et){const Bt=function(M,et){let Bt=et;const Wt=M.x,Nt=M.y;let $t,Gr=-1/0;if(pl(M,Bt))return Bt;do{if(pl(M,Bt.next))return Bt.next;if(Nt<=Bt.y&&Nt>=Bt.next.y&&Bt.next.y!==Bt.y){const M=Bt.x+(Nt-Bt.y)*(Bt.next.x-Bt.x)/(Bt.next.y-Bt.y);if(M<=Wt&&M>Gr&&(Gr=M,$t=Bt.x=Bt.x&&Bt.x>=Hn&&Wt!==Bt.x&&ll(Nt$t.x||Bt.x===$t.x&&sl($t,Bt)))&&($t=Bt,uo=et)}Bt=Bt.next}while(Bt!==mn);return $t}(M,et);if(!Bt)return et;const Wt=gl(Bt,M);return Jo(Wt,Wt.next),Jo(Bt,Bt.next)}function sl(M,et){return hl(M.prev,M,et.prev)<0&&hl(et.next,M,M.next)<0}function al(M,et,Bt,Wt,Nt){return(M=1431655765&((M=858993459&((M=252645135&((M=16711935&((M=(M-Bt)*Nt|0)|M<<8))|M<<4))|M<<2))|M<<1))|(et=1431655765&((et=858993459&((et=252645135&((et=16711935&((et=(et-Wt)*Nt|0)|et<<8))|et<<4))|et<<2))|et<<1))<<1}function ol(M){let et=M,Bt=M;do{(et.x=(M-Gr)*($t-mn)&&(M-Gr)*(Wt-mn)>=(Bt-Gr)*(et-mn)&&(Bt-Gr)*($t-mn)>=(Nt-Gr)*(Wt-mn)}function ul(M,et,Bt,Wt,Nt,$t,Gr,mn){return!(M===Gr&&et===mn)&&ll(M,et,Bt,Wt,Nt,$t,Gr,mn)}function cl(M,et){return M.next.i!==et.i&&M.prev.i!==et.i&&!function(M,et){let Bt=M;do{if(Bt.i!==M.i&&Bt.next.i!==M.i&&Bt.i!==et.i&&Bt.next.i!==et.i&&fl(Bt,Bt.next,M,et))return!0;Bt=Bt.next}while(Bt!==M);return!1}(M,et)&&(ml(M,et)&&ml(et,M)&&function(M,et){let Bt=M,Wt=!1;const Nt=(M.x+et.x)/2,$t=(M.y+et.y)/2;do{Bt.y>$t!=Bt.next.y>$t&&Bt.next.y!==Bt.y&&Nt<(Bt.next.x-Bt.x)*($t-Bt.y)/(Bt.next.y-Bt.y)+Bt.x&&(Wt=!Wt),Bt=Bt.next}while(Bt!==M);return Wt}(M,et)&&(hl(M.prev,M,et.prev)||hl(M,et.prev,et))||pl(M,et)&&hl(M.prev,M,M.next)>0&&hl(et.prev,et,et.next)>0)}function hl(M,et,Bt){return(et.y-M.y)*(Bt.x-et.x)-(et.x-M.x)*(Bt.y-et.y)}function pl(M,et){return M.x===et.x&&M.y===et.y}function fl(M,et,Bt,Wt){const Nt=yl(hl(M,et,Bt)),$t=yl(hl(M,et,Wt)),Gr=yl(hl(Bt,Wt,M)),mn=yl(hl(Bt,Wt,et));return Nt!==$t&&Gr!==mn||!(0!==Nt||!dl(M,Bt,et))||!(0!==$t||!dl(M,Wt,et))||!(0!==Gr||!dl(Bt,M,Wt))||!(0!==mn||!dl(Bt,et,Wt))}function dl(M,et,Bt){return et.x<=Math.max(M.x,Bt.x)&&et.x>=Math.min(M.x,Bt.x)&&et.y<=Math.max(M.y,Bt.y)&&et.y>=Math.min(M.y,Bt.y)}function yl(M){return M>0?1:M<0?-1:0}function ml(M,et){return hl(M.prev,M,M.next)<0?hl(M,et,M.next)>=0&&hl(M,M.prev,et)>=0:hl(M,et,M.prev)<0||hl(M,M.next,et)<0}function gl(M,et){const Bt=bl(M.i,M.x,M.y),Wt=bl(et.i,et.x,et.y),Nt=M.next,$t=et.prev;return M.next=et,et.prev=M,Bt.next=Nt,Nt.prev=Bt,Wt.next=Bt,Bt.prev=Wt,$t.next=Wt,Wt.prev=$t,Wt}function xl(M,et,Bt,Wt){const Nt=bl(M,et,Bt);return Wt?(Nt.next=Wt.next,Nt.prev=Wt,Wt.next.prev=Nt,Wt.next=Nt):(Nt.prev=Nt,Nt.next=Nt),Nt}function vl(M){M.next.prev=M.prev,M.prev.next=M.next,M.prevZ&&(M.prevZ.nextZ=M.nextZ),M.nextZ&&(M.nextZ.prevZ=M.prevZ)}function bl(M,et,Bt){return{i:M,x:et,y:Bt,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}class wl{constructor(M,et){if(et>M)throw new Error("Min granularity must not be greater than base granularity.");this._baseZoomGranularity=M,this._minGranularity=et}getGranularityForZoomLevel(M){return Math.max(Math.floor(this._baseZoomGranularity/(1<32767||et>32767)throw new Error("Vertex coordinates are out of signed 16 bit integer range.");const Bt=0|Math.round(M),Wt=0|Math.round(et),Nt=this._getKey(Bt,Wt);if(this._vertexDictionary.has(Nt))return this._vertexDictionary.get(Nt);const $t=this._vertexBuffer.length/2;return this._vertexDictionary.set(Nt,$t),this._vertexBuffer.push(Bt,Wt),$t}_subdivideTrianglesScanline(M){if(this._granularity<2)return function(M,et){const Bt=[];for(let Wt=0;Wt0?(Bt.push(Nt),Bt.push(Gr),Bt.push($t)):(Bt.push(Nt),Bt.push($t),Bt.push(Gr))}return Bt}(this._vertexBuffer,M);const et=[],Bt=M.length;for(let Wt=0;Wt=1||za<=0)||Ia&&(mnNt)){so>=Wt&&so<=Nt&&$t.push(Bt[(M+1)%3]);continue}!Ia&&Va>0&&$t.push(this._vertexToIndex(Gr+Po*Va,mn+To*Va));const Fa=Gr+Po*Math.max(Va,0),Ea=Gr+Po*Math.min(za,1);Eo||this._generateIntraEdgeVertices($t,Gr,mn,Hn,so,Fa,Ea),!Ia&&za<1&&$t.push(this._vertexToIndex(Gr+Po*za,mn+To*za)),(Ia||so>=Wt&&so<=Nt)&&$t.push(Bt[(M+1)%3]),!Ia&&(so<=Wt||so>=Nt)&&this._generateInterEdgeVertices($t,Gr,mn,Hn,so,uo,Io,Ea,Wt,Nt)}return $t}_generateIntraEdgeVertices(M,et,Bt,Wt,Nt,$t,Gr){const mn=Wt-et,Hn=Nt-Bt,so=0===Hn,uo=so?Math.min(et,Wt):Math.min($t,Gr),Io=so?Math.max(et,Wt):Math.max($t,Gr),Po=Math.floor(uo/this._granularityCellSize)+1,To=Math.ceil(Io/this._granularityCellSize)-1;if(so?et=Po;Wt--){const Nt=Wt*this._granularityCellSize;M.push(this._vertexToIndex(Nt,Bt+Hn*(Nt-et)/mn))}}_generateInterEdgeVertices(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so){const uo=Nt-Bt,Io=$t-Wt,Po=Gr-Nt,To=(Hn-Nt)/Po,Eo=(so-Nt)/Po,Ia=Math.min(To,Eo),Ba=Math.max(To,Eo),Ta=Wt+Io*Ia;let Va=Math.floor(Math.min(Ta,mn)/this._granularityCellSize)+1,za=Math.ceil(Math.max(Ta,mn)/this._granularityCellSize)-1,Fa=mn=1||Ba<=0){const M=Bt-Gr,Wt=$t+(et-$t)*Math.min((Hn-Gr)/M,(so-Gr)/M);Va=Math.floor(Math.min(Wt,mn)/this._granularityCellSize)+1,za=Math.ceil(Math.max(Wt,mn)/this._granularityCellSize)-1,Fa=mn0?so:Hn;if(Fa)for(let et=Va;et<=za;et++)M.push(this._vertexToIndex(et*this._granularityCellSize,La));else for(let et=za;et>=Va;et--)M.push(this._vertexToIndex(et*this._granularityCellSize,La))}_generateOutline(M){const et=[];for(const Bt of M){const M=Il(Bt,this._granularity,!0),Wt=this._pointArrayToIndices(M),Nt=[];for(let M=1;MNt!=($t===Vg)?(M.push(et),M.push(Bt),M.push(this._vertexToIndex(Wt,$t)),M.push(Bt),M.push(this._vertexToIndex(Nt,$t)),M.push(this._vertexToIndex(Wt,$t))):(M.push(Bt),M.push(et),M.push(this._vertexToIndex(Wt,$t)),M.push(this._vertexToIndex(Nt,$t)),M.push(Bt),M.push(this._vertexToIndex(Wt,$t)))}_fillPoles(M,et,Bt){const Wt=this._vertexBuffer,Nt=To,$t=M.length;for(let Gr=2;Gr<$t;Gr+=3){const $t=M[Gr-2],mn=M[Gr-1],Hn=M[Gr],so=Wt[2*$t],uo=Wt[2*$t+1],Io=Wt[2*mn],Po=Wt[2*mn+1],To=Wt[2*Hn],Eo=Wt[2*Hn+1];et&&(0===uo&&0===Po&&this._generatePoleQuad(M,$t,mn,so,Io,Vg),0===Po&&0===Eo&&this._generatePoleQuad(M,mn,Hn,Io,To,Vg),0===Eo&&0===uo&&this._generatePoleQuad(M,Hn,$t,To,so,Vg)),Bt&&(uo===Nt&&Po===Nt&&this._generatePoleQuad(M,$t,mn,so,Io,Wg),Po===Nt&&Eo===Nt&&this._generatePoleQuad(M,mn,Hn,Io,To,Wg),Eo===Nt&&uo===Nt&&this._generatePoleQuad(M,Hn,$t,To,so,Wg))}}_initializeVertices(M){for(let et=0;et80*Bt){mn=1/0,Hn=1/0;let et=-1/0,Wt=-1/0;for(let $t=Bt;$tet&&(et=Bt),Nt>Wt&&(Wt=Nt)}so=Math.max(et-mn,Wt-Hn),so=0!==so?32767/so:0}return Wo($t,Gr,Bt,mn,Hn,so,0),Gr}(Bt,Wt),et=this._convertIndices(Bt,M);Nt=this._subdivideTrianglesScanline(et)}catch(M){console.error(M)}let $t=[];return et&&($t=this._generateOutline(M)),this._ensureNoPoleVertices(),this._handlePoles(Nt),{verticesFlattened:this._vertexBuffer,indicesTriangles:Nt,indicesLineList:$t}}_convertIndices(M,et){const Bt=[];for(let Wt=0;Wt0?(Math.floor(Va/mn)+1)*mn:(Math.ceil(Va/mn)-1)*mn,et=Ia>0?(Math.floor(za/mn)+1)*mn:(Math.ceil(za/mn)-1)*mn,Bt=Math.abs(Va-M),Wt=Math.abs(za-et),Nt=Math.abs(Va-uo),Gr=Math.abs(za-Io),so=Po?Bt/Ba:Number.POSITIVE_INFINITY,Fa=To?Wt/Ta:Number.POSITIVE_INFINITY;if((Nt<=Bt||!Po)&&(Gr<=Wt||!To))break;if(so=0?Gr-1:$t-1,Nt=(mn+1)%$t,Hn=M[2*et[Wt]],so=M[2*et[Nt]],uo=M[2*et[Gr]],Io=M[2*et[Gr]+1],Po=M[2*et[mn]+1];let To=!1;if(Hnso)To=!1;else{const Bt=Po-Io,$t=-(M[2*et[mn]]-uo),Gr=Io((so-uo)*Bt+(M[2*et[Nt]+1]-Io)*$t)*Gr&&(To=!0)}if(To){const M=et[Wt],Nt=et[Gr],Hn=et[mn];M!==Nt&&M!==Hn&&Nt!==Hn&&Bt.push(Hn,Nt,M),Gr--,Gr<0&&(Gr=$t-1)}else{const M=et[Nt],Wt=et[Gr],Hn=et[mn];M!==Wt&&M!==Hn&&Wt!==Hn&&Bt.push(Hn,Wt,M),mn++,mn>=$t&&(mn=0)}if(Wt===Nt)break}}function Pl(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn){const so=Nt.length/2,uo=Gr&&mn&&Hn;if(soPa.MAX_VERTEX_ARRAY_LENGTH&&(so=M.createNewSegment(et,Bt),Hn=mn.count,Ia=!0,Ba=!0,Ta=!0,uo=0);const Va=Cl(Gr,Wt,$t,mn,Po,Ia,so),za=Cl(Gr,Wt,$t,mn,To,Ba,so),Fa=Cl(Gr,Wt,$t,mn,Eo,Ta,so);Bt.emplaceBack(uo+Va-Hn,uo+za-Hn,uo+Fa-Hn),so.primitiveLength++}}(et,Bt,Wt,Nt,$t,M),uo&&function(M,et,Bt,Wt,Nt,$t){const Gr=[];for(let M=0;MPa.MAX_VERTEX_ARRAY_LENGTH&&(so=M.createNewSegment(et,Bt),Hn=mn.count,Eo=!0,Ia=!0,uo=0);const Ba=Cl(Gr,Wt,$t,mn,Nt,Eo,so),Ta=Cl(Gr,Wt,$t,mn,Io,Ia,so);Bt.emplaceBack(uo+Ba-Hn,uo+Ta-Hn),so.primitiveLength++}}}(Gr,Bt,mn,Nt,Hn,M),et.forceNewSegmentOnNextPrepare(),null==Gr||Gr.forceNewSegmentOnNextPrepare()}function Cl(M,et,Bt,Wt,Nt,$t,Gr){if($t){const $t=Wt.count;return Bt(et[2*Nt],et[2*Nt+1]),M[Nt]=Wt.count,Wt.count++,Gr.vertexLength++,$t}return M[Nt]}class Bl{constructor(M){this.zoom=M.zoom,this.overscaling=M.overscaling,this.layers=M.layers,this.layerIds=this.layers.map((M=>M.id)),this.index=M.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new ya,this.indexArray=new ka,this.indexArray2=new Ma,this.programConfigurations=new ro(M.layers,M.zoom),this.segments=new Pa,this.segments2=new Pa,this.stateDependentLayerIds=this.layers.filter((M=>M.isStateDependent())).map((M=>M.id))}populate(M,et,Bt){this.hasPattern=Ko("fill",this.layers,et);const Wt=this.layers[0].layout.get("fill-sort-key"),Nt=!Wt.isConstant(),$t=[];for(const{feature:Gr,id:mn,index:Hn,sourceLayerIndex:so}of M){const M=this.layers[0]._featureFilter.needGeometry,uo=lo(Gr,M);if(!this.layers[0]._featureFilter.filter(new cs(this.zoom),uo,Bt))continue;const Io=Nt?Wt.evaluate(uo,{},Bt,et.availableImages):void 0,Po={id:mn,properties:Gr.properties,type:Gr.type,sourceLayerIndex:so,index:Hn,geometry:M?uo.geometry:oo(Gr),patterns:{},sortKey:Io};$t.push(Po)}Nt&&$t.sort(((M,et)=>M.sortKey-et.sortKey));for(const Wt of $t){const{geometry:Nt,index:$t,sourceLayerIndex:Gr}=Wt;if(this.hasPattern){const M=Ho("fill",this.layers,Wt,this.zoom,et);this.patternFeatures.push(M)}else this.addFeature(Wt,Nt,$t,Bt,{},et.subdivisionGranularity);et.featureIndex.insert(M[$t].feature,Nt,$t,Gr,this.index)}}update(M,et,Bt){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(M,et,this.stateDependentLayers,Bt)}addFeatures(M,et,Bt){for(const Wt of this.patternFeatures)this.addFeature(Wt,Wt.geometry,Wt.index,et,Bt,M.subdivisionGranularity)}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(M){this.uploaded||(this.layoutVertexBuffer=M.createVertexBuffer(this.layoutVertexArray,Mg),this.indexBuffer=M.createIndexBuffer(this.indexArray),this.indexBuffer2=M.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(M),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy())}addFeature(M,et,Bt,Wt,Nt,$t){for(const M of Le(et,500)){const et=Ml(M,Wt,$t.fill.getGranularityForZoomLevel(Wt.z)),Bt=this.layoutVertexArray;Pl(((M,et)=>{Bt.emplaceBack(M,et)}),this.segments,this.layoutVertexArray,this.indexArray,et.verticesFlattened,et.indicesTriangles,this.segments2,this.indexArray2,et.indicesLineList)}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,M,Bt,Nt,Wt)}}let zg,Fg;Ui("FillBucket",Bl,{omit:["layers","patternFeatures"]});var Eg={get paint(){return Fg=Fg||new As({"fill-antialias":new vs(Ka.paint_fill["fill-antialias"]),"fill-opacity":new bs(Ka.paint_fill["fill-opacity"]),"fill-color":new bs(Ka.paint_fill["fill-color"]),"fill-outline-color":new bs(Ka.paint_fill["fill-outline-color"]),"fill-translate":new vs(Ka.paint_fill["fill-translate"]),"fill-translate-anchor":new vs(Ka.paint_fill["fill-translate-anchor"]),"fill-pattern":new ws(Ka.paint_fill["fill-pattern"])})},get layout(){return zg=zg||new As({"fill-sort-key":new bs(Ka.layout_fill["fill-sort-key"])})}};class Fl extends Ms{constructor(M){super(M,Eg)}recalculate(M,et){super.recalculate(M,et);const Bt=this.paint._values["fill-outline-color"];"constant"===Bt.value.kind&&void 0===Bt.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"])}createBucket(M){return new Bl(M)}queryRadius(){return ko(this.paint.get("fill-translate"))}queryIntersectsFeature({queryGeometry:M,geometry:et,transform:Bt,pixelsToTileUnits:Wt}){return yo(Mo(M,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),-Bt.bearingInRadians,Wt),et)}isTileClipped(){return!0}}const Jg=Cs([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4),Xg=Cs([{name:"a_centroid",components:2,type:"Int16"}],4),{members:Lg}=Jg;var Dg,Hg,Kg,Ng,Yg,Og,jg,Ug={};function Xl(){if(Hg)return Dg;Hg=1;var M=s();function e(M,et,Bt,Wt,Nt){this.properties={},this.extent=Bt,this.type=0,this._pbf=M,this._geometry=-1,this._keys=Wt,this._values=Nt,M.readFields(r,this,et)}function r(M,et,Bt){1==M?et.id=Bt.readVarint():2==M?function(M,et){for(var Bt=M.readVarint()+M.pos;M.pos>3}if($t--,1===Nt||2===Nt)Gr+=et.readSVarint(),mn+=et.readSVarint(),1===Nt&&(Bt&&Hn.push(Bt),Bt=[]),Bt.push(new M(Gr,mn));else{if(7!==Nt)throw new Error("unknown command "+Nt);Bt&&Bt.push(Bt[0].clone())}}return Bt&&Hn.push(Bt),Hn},e.prototype.bbox=function(){var M=this._pbf;M.pos=this._geometry;for(var et=M.readVarint()+M.pos,Bt=1,Wt=0,Nt=0,$t=0,Gr=1/0,mn=-1/0,Hn=1/0,so=-1/0;M.pos>3}if(Wt--,1===Bt||2===Bt)(Nt+=M.readSVarint())mn&&(mn=Nt),($t+=M.readSVarint())so&&(so=$t);else if(7!==Bt)throw new Error("unknown command "+Bt)}return[Gr,Hn,mn,so]},e.prototype.toGeoJSON=function(M,et,Bt){var Wt,Nt,$t=this.extent*Math.pow(2,Bt),Gr=this.extent*M,mn=this.extent*et,Hn=this.loadGeometry(),so=e.types[this.type];function p(M){for(var et=0;et>3;et=1===Wt?M.readString():2===Wt?M.readFloat():3===Wt?M.readDouble():4===Wt?M.readVarint64():5===Wt?M.readVarint():6===Wt?M.readSVarint():7===Wt?M.readBoolean():null}return et}(Bt))}return Kg=e,e.prototype.feature=function(et){if(et<0||et>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[et];var Bt=this._pbf.readVarint()+this._pbf.pos;return new M(this._pbf,Bt,this.extent,this._keys,this._values)},Kg}function Hl(){return jg||(jg=1,Ug.VectorTile=function(){if(Og)return Yg;Og=1;var M=Kl();function e(et,Bt,Wt){if(3===et){var Nt=new M(Wt,Wt.readVarint()+Wt.pos);Nt.length&&(Bt[Nt.name]=Nt)}}return Yg=function(M,et){this.layers=M.readFields(e,{},et)},Yg}(),Ug.VectorTileFeature=Xl(),Ug.VectorTileLayer=Kl()),Ug}var Qg=r(Hl());const qg=Qg.VectorTileFeature.types,$g=Math.pow(2,13);function Ql(M,et,Bt,Wt,Nt,$t,Gr,mn){M.emplaceBack(et,Bt,2*Math.floor(Wt*$g)+Gr,Nt*$g*2,$t*$g*2,Math.round(mn))}class tu{constructor(M){this.zoom=M.zoom,this.overscaling=M.overscaling,this.layers=M.layers,this.layerIds=this.layers.map((M=>M.id)),this.index=M.index,this.hasPattern=!1,this.layoutVertexArray=new ma,this.centroidVertexArray=new fa,this.indexArray=new ka,this.programConfigurations=new ro(M.layers,M.zoom),this.segments=new Pa,this.stateDependentLayerIds=this.layers.filter((M=>M.isStateDependent())).map((M=>M.id))}populate(M,et,Bt){this.features=[],this.hasPattern=Ko("fill-extrusion",this.layers,et);for(const{feature:Wt,id:Nt,index:$t,sourceLayerIndex:Gr}of M){const M=this.layers[0]._featureFilter.needGeometry,mn=lo(Wt,M);if(!this.layers[0]._featureFilter.filter(new cs(this.zoom),mn,Bt))continue;const Hn={id:Nt,sourceLayerIndex:Gr,index:$t,geometry:M?mn.geometry:oo(Wt),properties:Wt.properties,type:Wt.type,patterns:{}};this.hasPattern?this.features.push(Ho("fill-extrusion",this.layers,Hn,this.zoom,et)):this.addFeature(Hn,Hn.geometry,$t,Bt,{},et.subdivisionGranularity),et.featureIndex.insert(Wt,Hn.geometry,$t,Gr,this.index,!0)}}addFeatures(M,et,Bt){for(const Wt of this.features){const{geometry:Nt}=Wt;this.addFeature(Wt,Nt,Wt.index,et,Bt,M.subdivisionGranularity)}}update(M,et,Bt){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(M,et,this.stateDependentLayers,Bt)}isEmpty(){return 0===this.layoutVertexArray.length&&0===this.centroidVertexArray.length}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(M){this.uploaded||(this.layoutVertexBuffer=M.createVertexBuffer(this.layoutVertexArray,Lg),this.centroidVertexBuffer=M.createVertexBuffer(this.centroidVertexArray,Xg.members,!0),this.indexBuffer=M.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(M),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy())}addFeature(M,et,Bt,Wt,Nt,$t){for(const Bt of Le(et,500)){const et={x:0,y:0,sampleCount:0},Nt=this.layoutVertexArray.length;this.processPolygon(et,Wt,M,Bt,$t);const Gr=this.layoutVertexArray.length-Nt,mn=Math.floor(et.x/et.sampleCount),Hn=Math.floor(et.y/et.sampleCount);for(let M=0;M{Ql(so,M,et,0,0,1,1,0)}),this.segments,this.layoutVertexArray,this.indexArray,Hn.verticesFlattened,Hn.indicesTriangles)}_generateSideFaces(M,et){let Bt=0;for(let Wt=1;WtPa.MAX_VERTEX_ARRAY_LENGTH&&(et.segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));const Gr=Nt.sub($t)._perp()._unit(),mn=$t.dist(Nt);Bt+mn>32768&&(Bt=0),Ql(this.layoutVertexArray,Nt.x,Nt.y,Gr.x,Gr.y,0,0,Bt),Ql(this.layoutVertexArray,Nt.x,Nt.y,Gr.x,Gr.y,0,1,Bt),Bt+=mn,Ql(this.layoutVertexArray,$t.x,$t.y,Gr.x,Gr.y,0,0,Bt),Ql(this.layoutVertexArray,$t.x,$t.y,Gr.x,Gr.y,0,1,Bt);const Hn=et.segment.vertexLength;this.indexArray.emplaceBack(Hn,Hn+2,Hn+1),this.indexArray.emplaceBack(Hn+1,Hn+2,Hn+3),et.segment.vertexLength+=4,et.segment.primitiveLength+=2}}}function eu(M,et){for(let Bt=0;BtTo)||M.y===et.y&&(M.y<0||M.y>To)}function nu(M){return M.every((M=>M.x<0))||M.every((M=>M.x>To))||M.every((M=>M.y<0))||M.every((M=>M.y>To))}let iu;Ui("FillExtrusionBucket",tu,{omit:["layers","features"]});var su={get paint(){return iu=iu||new As({"fill-extrusion-opacity":new vs(Ka["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new bs(Ka["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new vs(Ka["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new vs(Ka["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new ws(Ka["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new bs(Ka["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new bs(Ka["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new vs(Ka["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})}};class au extends Ms{constructor(M){super(M,su)}createBucket(M){return new tu(M)}queryRadius(){return ko(this.paint.get("fill-extrusion-translate"))}is3D(){return!0}queryIntersectsFeature({queryGeometry:M,feature:et,featureState:Bt,geometry:Wt,transform:Nt,pixelsToTileUnits:Gr,pixelPosMatrix:mn}){const Hn=Mo(M,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),-Nt.bearingInRadians,Gr),so=this.paint.get("fill-extrusion-height").evaluate(et,Bt),uo=this.paint.get("fill-extrusion-base").evaluate(et,Bt),Io=function(M,et){const Bt=[];for(const Wt of M){const M=[Wt.x,Wt.y,0,1];_(M,M,et),Bt.push(new $t(M[0]/M[3],M[1]/M[3]))}return Bt}(Hn,mn),Po=function(M,et,Bt,Wt){const Nt=[],Gr=[],mn=Wt[8]*et,Hn=Wt[9]*et,so=Wt[10]*et,uo=Wt[11]*et,Io=Wt[8]*Bt,Po=Wt[9]*Bt,To=Wt[10]*Bt,Eo=Wt[11]*Bt;for(const et of M){const M=[],Bt=[];for(const Nt of et){const et=Nt.x,Gr=Nt.y,Ia=Wt[0]*et+Wt[4]*Gr+Wt[12],Ba=Wt[1]*et+Wt[5]*Gr+Wt[13],Ta=Wt[2]*et+Wt[6]*Gr+Wt[14],Va=Wt[3]*et+Wt[7]*Gr+Wt[15],za=Ta+so,Fa=Va+uo,Ea=Ia+Io,La=Ba+Po,Da=Ta+To,Ka=Va+Eo,Oa=new $t((Ia+mn)/Fa,(Ba+Hn)/Fa);Oa.z=za/Fa,M.push(Oa);const $a=new $t(Ea/Ka,La/Ka);$a.z=Da/Ka,Bt.push($a)}Nt.push(M),Gr.push(Bt)}return[Nt,Gr]}(Wt,uo,so,mn);return function(M,et,Bt){let Wt=1/0;yo(Bt,et)&&(Wt=lu(Bt,et[0]));for(let Nt=0;NtM.id)),this.index=M.index,this.hasPattern=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach((M=>{this.gradients[M.id]={}})),this.layoutVertexArray=new ga,this.layoutVertexArray2=new xa,this.indexArray=new ka,this.programConfigurations=new ro(M.layers,M.zoom),this.segments=new Pa,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((M=>M.isStateDependent())).map((M=>M.id))}populate(M,et,Bt){this.hasPattern=Ko("line",this.layers,et);const Wt=this.layers[0].layout.get("line-sort-key"),Nt=!Wt.isConstant(),$t=[];for(const{feature:et,id:Gr,index:mn,sourceLayerIndex:Hn}of M){const M=this.layers[0]._featureFilter.needGeometry,so=lo(et,M);if(!this.layers[0]._featureFilter.filter(new cs(this.zoom),so,Bt))continue;const uo=Nt?Wt.evaluate(so,{},Bt):void 0,Io={id:Gr,properties:et.properties,type:et.type,sourceLayerIndex:Hn,index:mn,geometry:M?so.geometry:oo(et),patterns:{},sortKey:uo};$t.push(Io)}Nt&&$t.sort(((M,et)=>M.sortKey-et.sortKey));for(const Wt of $t){const{geometry:Nt,index:$t,sourceLayerIndex:Gr}=Wt;if(this.hasPattern){const M=Ho("line",this.layers,Wt,this.zoom,et);this.patternFeatures.push(M)}else this.addFeature(Wt,Nt,$t,Bt,{},et.subdivisionGranularity);et.featureIndex.insert(M[$t].feature,Nt,$t,Gr,this.index)}}update(M,et,Bt){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(M,et,this.stateDependentLayers,Bt)}addFeatures(M,et,Bt){for(const Wt of this.patternFeatures)this.addFeature(Wt,Wt.geometry,Wt.index,et,Bt,M.subdivisionGranularity)}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(M){this.uploaded||(0!==this.layoutVertexArray2.length&&(this.layoutVertexBuffer2=M.createVertexBuffer(this.layoutVertexArray2,uu)),this.layoutVertexBuffer=M.createVertexBuffer(this.layoutVertexArray,hu),this.indexBuffer=M.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(M),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}lineFeatureClips(M){if(M.properties&&Object.prototype.hasOwnProperty.call(M.properties,"mapbox_clip_start")&&Object.prototype.hasOwnProperty.call(M.properties,"mapbox_clip_end"))return{start:+M.properties.mapbox_clip_start,end:+M.properties.mapbox_clip_end}}addFeature(M,et,Bt,Wt,Nt,$t){const Gr=this.layers[0].layout,mn=Gr.get("line-join").evaluate(M,{}),Hn=Gr.get("line-cap"),so=Gr.get("line-miter-limit"),uo=Gr.get("line-round-limit");this.lineClips=this.lineFeatureClips(M);for(const Bt of et)this.addLine(Bt,M,mn,Hn,so,uo,Wt,$t);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,M,Bt,Nt,Wt)}addLine(M,et,Bt,Wt,Nt,$t,Gr,mn){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,M=Il(M,Gr?mn.line.getGranularityForZoomLevel(Gr.z):1),this.lineClips){this.lineClipsArray.push(this.lineClips);for(let et=0;et=2&&M[so-1].equals(M[so-2]);)so--;let uo=0;for(;uo0;if(Ea&&et>uo){const M=Eo.dist(Ia);if(M>2*Io){const et=Eo.sub(Eo.sub(Ia)._mult(Io/M)._round());this.updateDistance(Ia,et),this.addCurrentVertex(et,Ta,0,0,Po),Ia=et}}const Da=Ia&&Ba;let Ka=Da?Bt:Hn?"butt":Wt;if(Da&&"round"===Ka&&(za<$t?Ka="miter":za<=2&&(Ka="fakeround")),"miter"===Ka&&za>Nt&&(Ka="bevel"),"bevel"===Ka&&(za>2&&(Ka="flipbevel"),za100)Gr=Va.mult(-1);else{const M=za*Ta.add(Va).mag()/Ta.sub(Va).mag();Gr._perp()._mult(M*(La?-1:1))}this.addCurrentVertex(Eo,Gr,0,0,Po),this.addCurrentVertex(Eo,Gr.mult(-1),0,0,Po)}else if("bevel"===Ka||"fakeround"===Ka){const M=-Math.sqrt(za*za-1),et=La?M:0,Bt=La?0:M;if(Ia&&this.addCurrentVertex(Eo,Ta,et,Bt,Po),"fakeround"===Ka){const M=Math.round(180*Fa/Math.PI/20);for(let et=1;et2*Io){const et=Eo.add(Ba.sub(Eo)._mult(Io/M)._round());this.updateDistance(Eo,et),this.addCurrentVertex(et,Va,0,0,Po),Eo=et}}}}addCurrentVertex(M,et,Bt,Wt,Nt,$t=!1){const Gr=et.y*Wt-et.x,mn=-et.y-et.x*Wt;this.addHalfVertex(M,et.x+et.y*Bt,et.y-et.x*Bt,$t,!1,Bt,Nt),this.addHalfVertex(M,Gr,mn,$t,!0,-Wt,Nt),this.distance>Cu/2&&0===this.totalDistance&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(M,et,Bt,Wt,Nt,$t))}addHalfVertex({x:M,y:et},Bt,Wt,Nt,$t,Gr,mn){const Hn=.5*(this.lineClips?this.scaledDistance*(Cu-1):this.scaledDistance);this.layoutVertexArray.emplaceBack((M<<1)+(Nt?1:0),(et<<1)+($t?1:0),Math.round(63*Bt)+128,Math.round(63*Wt)+128,1+(0===Gr?0:Gr<0?-1:1)|(63&Hn)<<2,Hn>>6),this.lineClips&&this.layoutVertexArray2.emplaceBack((this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start),this.lineClipsArray.length);const so=mn.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,so,this.e2),mn.primitiveLength++),$t?this.e2=so:this.e1=so}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance}updateDistance(M,et){this.distance+=M.dist(et),this.updateScaledDistance()}}let Iu,fu;Ui("LineBucket",mu,{omit:["layers","patternFeatures"]});var yu={get paint(){return fu=fu||new As({"line-opacity":new bs(Ka.paint_line["line-opacity"]),"line-color":new bs(Ka.paint_line["line-color"]),"line-translate":new vs(Ka.paint_line["line-translate"]),"line-translate-anchor":new vs(Ka.paint_line["line-translate-anchor"]),"line-width":new bs(Ka.paint_line["line-width"]),"line-gap-width":new bs(Ka.paint_line["line-gap-width"]),"line-offset":new bs(Ka.paint_line["line-offset"]),"line-blur":new bs(Ka.paint_line["line-blur"]),"line-dasharray":new _s(Ka.paint_line["line-dasharray"]),"line-pattern":new ws(Ka.paint_line["line-pattern"]),"line-gradient":new Ss(Ka.paint_line["line-gradient"])})},get layout(){return Iu=Iu||new As({"line-cap":new vs(Ka.layout_line["line-cap"]),"line-join":new bs(Ka.layout_line["line-join"]),"line-miter-limit":new vs(Ka.layout_line["line-miter-limit"]),"line-round-limit":new vs(Ka.layout_line["line-round-limit"]),"line-sort-key":new bs(Ka.layout_line["line-sort-key"])})}};class bu extends bs{possiblyEvaluate(M,et){return et=new cs(Math.floor(et.zoom),{now:et.now,fadeDuration:et.fadeDuration,zoomHistory:et.zoomHistory,transition:et.transition}),super.possiblyEvaluate(M,et)}evaluate(M,et,Bt,Wt){return et=F({},et,{zoom:Math.floor(et.zoom)}),super.evaluate(M,et,Bt,Wt)}}let Au;class _u extends Ms{constructor(M){super(M,yu),this.gradientVersion=0,Au||(Au=new bu(yu.paint.properties["line-width"].specification),Au.useIntegerZoom=!0)}_handleSpecialPaintPropertyUpdate(M){if("line-gradient"===M){const M=this.gradientExpression();this.stepInterpolant=!!function(M){return void 0!==M._styleExpression}(M)&&M._styleExpression.expression instanceof Qe,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(M,et){super.recalculate(M,et),this.paint._values["line-floorwidth"]=Au.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,M)}createBucket(M){return new mu(M)}queryRadius(M){const et=M,Bt=Su(Ao("line-width",this,et),Ao("line-gap-width",this,et)),Wt=Ao("line-offset",this,et);return Bt/2+Math.abs(Wt)+ko(this.paint.get("line-translate"))}queryIntersectsFeature({queryGeometry:M,feature:et,featureState:Bt,geometry:Wt,transform:Nt,pixelsToTileUnits:Gr}){const mn=Mo(M,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),-Nt.bearingInRadians,Gr),Hn=Gr/2*Su(this.paint.get("line-width").evaluate(et,Bt),this.paint.get("line-gap-width").evaluate(et,Bt)),so=this.paint.get("line-offset").evaluate(et,Bt);return so&&(Wt=function(M,et){const Bt=[];for(let Wt=0;Wt=3)for(let et=0;et0?et+2*M:M}const vu=Cs([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),xu=Cs([{name:"a_projected_pos",components:3,type:"Float32"}],4);Cs([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const wu=Cs([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_box_real",components:2,type:"Int16"}]);Cs([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const ku=Cs([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),Bu=Cs([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function Pu(M,et,Bt){return M.sections.forEach((M=>{M.text=function(M,et,Bt){const Wt=et.layout.get("text-transform").evaluate(Bt,{});return"uppercase"===Wt?M=M.toLocaleUpperCase():"lowercase"===Wt&&(M=M.toLocaleLowerCase()),ag.applyArabicShaping&&(M=ag.applyArabicShaping(M)),M}(M.text,et,Bt)})),M}Cs([{name:"triangle",components:3,type:"Uint16"}]),Cs([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),Cs([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]),Cs([{type:"Float32",name:"offsetX"}]),Cs([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]),Cs([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);const Gu={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};var Tu,Mu,Vu,zu=24,Fu={};function $u(){return Tu||(Tu=1,Fu.read=function(M,et,Bt,Wt,Nt){var $t,Gr,mn=8*Nt-Wt-1,Hn=(1<>1,uo=-7,Io=Bt?Nt-1:0,Po=Bt?-1:1,To=M[et+Io];for(Io+=Po,$t=To&(1<<-uo)-1,To>>=-uo,uo+=mn;uo>0;$t=256*$t+M[et+Io],Io+=Po,uo-=8);for(Gr=$t&(1<<-uo)-1,$t>>=-uo,uo+=Wt;uo>0;Gr=256*Gr+M[et+Io],Io+=Po,uo-=8);if(0===$t)$t=1-so;else{if($t===Hn)return Gr?NaN:1/0*(To?-1:1);Gr+=Math.pow(2,Wt),$t-=so}return(To?-1:1)*Gr*Math.pow(2,$t-Wt)},Fu.write=function(M,et,Bt,Wt,Nt,$t){var Gr,mn,Hn,so=8*$t-Nt-1,uo=(1<>1,Po=23===Nt?Math.pow(2,-24)-Math.pow(2,-77):0,To=Wt?0:$t-1,Eo=Wt?1:-1,Ia=et<0||0===et&&1/et<0?1:0;for(et=Math.abs(et),isNaN(et)||et===1/0?(mn=isNaN(et)?1:0,Gr=uo):(Gr=Math.floor(Math.log(et)/Math.LN2),et*(Hn=Math.pow(2,-Gr))<1&&(Gr--,Hn*=2),(et+=Gr+Io>=1?Po/Hn:Po*Math.pow(2,1-Io))*Hn>=2&&(Gr++,Hn/=2),Gr+Io>=uo?(mn=0,Gr=uo):Gr+Io>=1?(mn=(et*Hn-1)*Math.pow(2,Nt),Gr+=Io):(mn=et*Math.pow(2,Io-1)*Math.pow(2,Nt),Gr=0));Nt>=8;M[Bt+To]=255&mn,To+=Eo,mn/=256,Nt-=8);for(Gr=Gr<0;M[Bt+To]=255&Gr,To+=Eo,Gr/=256,so-=8);M[Bt+To-Eo]|=128*Ia}),Fu}function Lu(){if(Vu)return Mu;Vu=1,Mu=e;var M=$u();function e(M){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(M)?M:new Uint8Array(M||0),this.pos=0,this.type=0,this.length=this.buf.length}e.Varint=0,e.Fixed64=1,e.Bytes=2,e.Fixed32=5;var et=4294967296,Bt=1/et,Wt="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");function s(M){return M.type===e.Bytes?M.readVarint()+M.pos:M.pos+1}function a(M,et,Bt){return Bt?4294967296*et+(M>>>0):4294967296*(et>>>0)+(M>>>0)}function o(M,et,Bt){var Wt=et<=16383?1:et<=2097151?2:et<=268435455?3:Math.floor(Math.log(et)/(7*Math.LN2));Bt.realloc(Wt);for(var Nt=Bt.pos-1;Nt>=M;Nt--)Bt.buf[Nt+Wt]=Bt.buf[Nt]}function l(M,et){for(var Bt=0;Bt>>8,M[Bt+2]=et>>>16,M[Bt+3]=et>>>24}function v(M,et){return(M[et]|M[et+1]<<8|M[et+2]<<16)+(M[et+3]<<24)}return e.prototype={destroy:function(){this.buf=null},readFields:function(M,et,Bt){for(Bt=Bt||this.length;this.pos>3,$t=this.pos;this.type=7&Wt,M(Nt,et,this),this.pos===$t&&this.skip(Wt)}return et},readMessage:function(M,et){return this.readFields(M,et,this.readVarint()+this.pos)},readFixed32:function(){var M=g(this.buf,this.pos);return this.pos+=4,M},readSFixed32:function(){var M=v(this.buf,this.pos);return this.pos+=4,M},readFixed64:function(){var M=g(this.buf,this.pos)+g(this.buf,this.pos+4)*et;return this.pos+=8,M},readSFixed64:function(){var M=g(this.buf,this.pos)+v(this.buf,this.pos+4)*et;return this.pos+=8,M},readFloat:function(){var et=M.read(this.buf,this.pos,!0,23,4);return this.pos+=4,et},readDouble:function(){var et=M.read(this.buf,this.pos,!0,52,8);return this.pos+=8,et},readVarint:function(M){var et,Bt,Wt=this.buf;return et=127&(Bt=Wt[this.pos++]),Bt<128?et:(et|=(127&(Bt=Wt[this.pos++]))<<7,Bt<128?et:(et|=(127&(Bt=Wt[this.pos++]))<<14,Bt<128?et:(et|=(127&(Bt=Wt[this.pos++]))<<21,Bt<128?et:function(M,et,Bt){var Wt,Nt,$t=Bt.buf;if(Wt=(112&(Nt=$t[Bt.pos++]))>>4,Nt<128)return a(M,Wt,et);if(Wt|=(127&(Nt=$t[Bt.pos++]))<<3,Nt<128)return a(M,Wt,et);if(Wt|=(127&(Nt=$t[Bt.pos++]))<<10,Nt<128)return a(M,Wt,et);if(Wt|=(127&(Nt=$t[Bt.pos++]))<<17,Nt<128)return a(M,Wt,et);if(Wt|=(127&(Nt=$t[Bt.pos++]))<<24,Nt<128)return a(M,Wt,et);if(Wt|=(1&(Nt=$t[Bt.pos++]))<<31,Nt<128)return a(M,Wt,et);throw new Error("Expected varint not more than 10 bytes")}(et|=(15&(Bt=Wt[this.pos]))<<28,M,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var M=this.readVarint();return M%2==1?(M+1)/-2:M/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var M=this.readVarint()+this.pos,et=this.pos;return this.pos=M,M-et>=12&&Wt?function(M,et,Bt){return Wt.decode(M.subarray(et,Bt))}(this.buf,et,M):function(M,et,Bt){for(var Wt="",Nt=et;Nt239?4:Hn>223?3:Hn>191?2:1;if(Nt+uo>Bt)break;1===uo?Hn<128&&(so=Hn):2===uo?128==(192&($t=M[Nt+1]))&&(so=(31&Hn)<<6|63&$t)<=127&&(so=null):3===uo?(Gr=M[Nt+2],128==(192&($t=M[Nt+1]))&&128==(192&Gr)&&((so=(15&Hn)<<12|(63&$t)<<6|63&Gr)<=2047||so>=55296&&so<=57343)&&(so=null)):4===uo&&(Gr=M[Nt+2],mn=M[Nt+3],128==(192&($t=M[Nt+1]))&&128==(192&Gr)&&128==(192&mn)&&((so=(15&Hn)<<18|(63&$t)<<12|(63&Gr)<<6|63&mn)<=65535||so>=1114112)&&(so=null)),null===so?(so=65533,uo=1):so>65535&&(so-=65536,Wt+=String.fromCharCode(so>>>10&1023|55296),so=56320|1023&so),Wt+=String.fromCharCode(so),Nt+=uo}return Wt}(this.buf,et,M)},readBytes:function(){var M=this.readVarint()+this.pos,et=this.buf.subarray(this.pos,M);return this.pos=M,et},readPackedVarint:function(M,et){if(this.type!==e.Bytes)return M.push(this.readVarint(et));var Bt=s(this);for(M=M||[];this.pos127;);else if(et===e.Bytes)this.pos=this.readVarint()+this.pos;else if(et===e.Fixed32)this.pos+=4;else{if(et!==e.Fixed64)throw new Error("Unimplemented type: "+et);this.pos+=8}},writeTag:function(M,et){this.writeVarint(M<<3|et)},realloc:function(M){for(var et=this.length||16;et268435455||M<0?function(M,et){var Bt,Wt;if(M>=0?(Bt=M%4294967296|0,Wt=M/4294967296|0):(Wt=~(-M/4294967296),4294967295^(Bt=~(-M%4294967296))?Bt=Bt+1|0:(Bt=0,Wt=Wt+1|0)),M>=0x10000000000000000||M<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");et.realloc(10),function(M,et,Bt){Bt.buf[Bt.pos++]=127&M|128,M>>>=7,Bt.buf[Bt.pos++]=127&M|128,M>>>=7,Bt.buf[Bt.pos++]=127&M|128,M>>>=7,Bt.buf[Bt.pos++]=127&M|128,Bt.buf[Bt.pos]=127&(M>>>=7)}(Bt,0,et),function(M,et){var Bt=(7&M)<<4;et.buf[et.pos++]|=Bt|((M>>>=3)?128:0),M&&(et.buf[et.pos++]=127&M|((M>>>=7)?128:0),M&&(et.buf[et.pos++]=127&M|((M>>>=7)?128:0),M&&(et.buf[et.pos++]=127&M|((M>>>=7)?128:0),M&&(et.buf[et.pos++]=127&M|((M>>>=7)?128:0),M&&(et.buf[et.pos++]=127&M)))))}(Wt,et)}(M,this):(this.realloc(4),this.buf[this.pos++]=127&M|(M>127?128:0),M<=127||(this.buf[this.pos++]=127&(M>>>=7)|(M>127?128:0),M<=127||(this.buf[this.pos++]=127&(M>>>=7)|(M>127?128:0),M<=127||(this.buf[this.pos++]=M>>>7&127))))},writeSVarint:function(M){this.writeVarint(M<0?2*-M-1:2*M)},writeBoolean:function(M){this.writeVarint(Boolean(M))},writeString:function(M){M=String(M),this.realloc(4*M.length),this.pos++;var et=this.pos;this.pos=function(M,et,Bt){for(var Wt,Nt,$t=0;$t55295&&Wt<57344){if(!Nt){Wt>56319||$t+1===et.length?(M[Bt++]=239,M[Bt++]=191,M[Bt++]=189):Nt=Wt;continue}if(Wt<56320){M[Bt++]=239,M[Bt++]=191,M[Bt++]=189,Nt=Wt;continue}Wt=Nt-55296<<10|Wt-56320|65536,Nt=null}else Nt&&(M[Bt++]=239,M[Bt++]=191,M[Bt++]=189,Nt=null);Wt<128?M[Bt++]=Wt:(Wt<2048?M[Bt++]=Wt>>6|192:(Wt<65536?M[Bt++]=Wt>>12|224:(M[Bt++]=Wt>>18|240,M[Bt++]=Wt>>12&63|128),M[Bt++]=Wt>>6&63|128),M[Bt++]=63&Wt|128)}return Bt}(this.buf,M,this.pos);var Bt=this.pos-et;Bt>=128&&o(et,Bt,this),this.pos=et-1,this.writeVarint(Bt),this.pos+=Bt},writeFloat:function(et){this.realloc(4),M.write(this.buf,et,this.pos,!0,23,4),this.pos+=4},writeDouble:function(et){this.realloc(8),M.write(this.buf,et,this.pos,!0,52,8),this.pos+=8},writeBytes:function(M){var et=M.length;this.writeVarint(et),this.realloc(et);for(var Bt=0;Bt=128&&o(Bt,Wt,this),this.pos=Bt-1,this.writeVarint(Wt),this.pos+=Wt},writeMessage:function(M,et,Bt){this.writeTag(M,e.Bytes),this.writeRawMessage(et,Bt)},writePackedVarint:function(M,et){et.length&&this.writeMessage(M,l,et)},writePackedSVarint:function(M,et){et.length&&this.writeMessage(M,u,et)},writePackedBoolean:function(M,et){et.length&&this.writeMessage(M,p,et)},writePackedFloat:function(M,et){et.length&&this.writeMessage(M,c,et)},writePackedDouble:function(M,et){et.length&&this.writeMessage(M,h,et)},writePackedFixed32:function(M,et){et.length&&this.writeMessage(M,f,et)},writePackedSFixed32:function(M,et){et.length&&this.writeMessage(M,d,et)},writePackedFixed64:function(M,et){et.length&&this.writeMessage(M,y,et)},writePackedSFixed64:function(M,et){et.length&&this.writeMessage(M,m,et)},writeBytesField:function(M,et){this.writeTag(M,e.Bytes),this.writeBytes(et)},writeFixed32Field:function(M,et){this.writeTag(M,e.Fixed32),this.writeFixed32(et)},writeSFixed32Field:function(M,et){this.writeTag(M,e.Fixed32),this.writeSFixed32(et)},writeFixed64Field:function(M,et){this.writeTag(M,e.Fixed64),this.writeFixed64(et)},writeSFixed64Field:function(M,et){this.writeTag(M,e.Fixed64),this.writeSFixed64(et)},writeVarintField:function(M,et){this.writeTag(M,e.Varint),this.writeVarint(et)},writeSVarintField:function(M,et){this.writeTag(M,e.Varint),this.writeSVarint(et)},writeStringField:function(M,et){this.writeTag(M,e.Bytes),this.writeString(et)},writeFloatField:function(M,et){this.writeTag(M,e.Fixed32),this.writeFloat(et)},writeDoubleField:function(M,et){this.writeTag(M,e.Fixed64),this.writeDouble(et)},writeBooleanField:function(M,et){this.writeVarintField(M,Boolean(et))}},Mu}var Eu=r(Lu());const Du=3;function Ru(M,et,Bt){1===M&&Bt.readMessage(ju,et)}function ju(M,et,Bt){if(3===M){const{id:M,bitmap:Wt,width:Nt,height:$t,left:Gr,top:mn,advance:Hn}=Bt.readMessage(Nu,{});et.push({id:M,bitmap:new Do({width:Nt+2*Du,height:$t+2*Du},Wt),metrics:{width:Nt,height:$t,left:Gr,top:mn,advance:Hn}})}}function Nu(M,et,Bt){1===M?et.id=Bt.readVarint():2===M?et.bitmap=Bt.readBytes():3===M?et.width=Bt.readVarint():4===M?et.height=Bt.readVarint():5===M?et.left=Bt.readSVarint():6===M?et.top=Bt.readSVarint():7===M&&(et.advance=Bt.readVarint())}const Hu=Du;function qu(M){let et=0,Bt=0;for(const Wt of M)et+=Wt.w*Wt.h,Bt=Math.max(Bt,Wt.w);M.sort(((M,et)=>et.h-M.h));const Wt=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(et/.95)),Bt),h:1/0}];let Nt=0,$t=0;for(const et of M)for(let M=Wt.length-1;M>=0;M--){const Bt=Wt[M];if(!(et.w>Bt.w||et.h>Bt.h)){if(et.x=Bt.x,et.y=Bt.y,$t=Math.max($t,et.y+et.h),Nt=Math.max(Nt,et.x+et.w),et.w===Bt.w&&et.h===Bt.h){const et=Wt.pop();M=0&&Bt>=M&&Qu[this.text.charCodeAt(Bt)];Bt--)et--;this.text=this.text.substring(M,et),this.sectionIndex=this.sectionIndex.slice(M,et)}substring(M,et){const Bt=new Ju;return Bt.text=this.text.substring(M,et),Bt.sectionIndex=this.sectionIndex.slice(M,et),Bt.sections=this.sections,Bt}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce(((M,et)=>Math.max(M,this.sections[et].scale)),0)}addTextSection(M,et){this.text+=M.text,this.sections.push(Yu.forText(M.scale,M.fontStack||et));const Bt=this.sections.length-1;for(let et=0;et=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function Wu(et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia){const Ba=Ju.fromFeature(et,$t);let Ta;Po===M.ai.vertical&&Ba.verticalizePunctuation();const{processBidirectionalText:Va,processStyledBidirectionalText:za}=ag;if(Va&&1===Ba.sections.length){Ta=[];const M=Va(Ba.toString(),oc(Ba,uo,Gr,Bt,Nt,Eo));for(const et of M){const M=new Ju;M.text=et,M.sections=Ba.sections;for(let Bt=0;Bt0&&Wt>La&&(La=Wt)}else{const M=Wt[Ia.fontStack],et=M&&M[Ta];if(et&&et.rect)Da=et.rect,Fa=et.metrics;else{const M=Bt[Ia.fontStack],et=M&&M[Ta];if(!et)continue;Fa=et.metrics}Va=($t-Ia.scale)*zu}$a?(et.verticalizable=!0,Ea.push({glyph:Ta,imageName:Ka,x:To,y:Eo+Va,vertical:$a,scale:Ia.scale,fontStack:Ia.fontStack,sectionIndex:Ba,metrics:Fa,rect:Da}),To+=Oa*Ia.scale+uo):(Ea.push({glyph:Ta,imageName:Ka,x:To,y:Eo+Va,vertical:$a,scale:Ia.scale,fontStack:Ia.fontStack,sectionIndex:Ba,metrics:Fa,rect:Da}),To+=Fa.advance*Ia.scale+uo)}0!==Ea.length&&(Ia=Math.max(To-uo,Ia),uc(Ea,0,Ea.length-1,Ta,La)),To=0;const Da=Gr*$t+La;Fa.lineOffset=Math.max(La,Hn),Eo+=Da,Ba=Math.max(Da,Ba),++Va}var za;const Fa=Eo-Uu,{horizontalAlign:Ea,verticalAlign:La}=lc(mn);(function(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn){const so=(et-Bt)*Nt;let uo=0;uo=$t!==Gr?-mn*Wt-Uu:(-Wt*Hn+.5)*Gr;for(const et of M)for(const M of et.positionedGlyphs)M.x+=so,M.y+=uo})(et.positionedLines,Ta,Ea,La,Ia,Ba,Gr,Fa,$t.length),et.top+=-La*Fa,et.bottom=et.top+Fa,et.left+=-Ea*Ia,et.right=et.left+Ia}(Ea,Bt,Wt,Nt,Ta,mn,Hn,so,Po,uo,To,Ia),!function(M){for(const et of M)if(0!==et.positionedGlyphs.length)return!1;return!0}(Fa)&&Ea}const Qu={9:!0,10:!0,11:!0,12:!0,13:!0,32:!0},td={10:!0,32:!0,38:!0,41:!0,43:!0,45:!0,47:!0,173:!0,183:!0,8203:!0,8208:!0,8211:!0,8231:!0},ed={40:!0};function rc(M,et,Bt,Wt,Nt,$t){if(et.imageName){const M=Wt[et.imageName];return M?M.displaySize[0]*et.scale*zu/$t+Nt:0}{const Wt=Bt[et.fontStack],$t=Wt&&Wt[M];return $t?$t.metrics.advance*et.scale+Nt:0}}function nc(M,et,Bt,Wt){const Nt=Math.pow(M-et,2);return Wt?M=0;let so=0;for(let Bt=0;Btso){const M=Math.ceil($t/so);Nt*=M/Gr,Gr=M}return{x1:Wt,y1:Nt,x2:Wt+$t,y2:Nt+Gr}}function pc(M,et,Bt,Wt,Nt,$t){const Gr=M.image;let mn;if(Gr.content){const M=Gr.content,et=Gr.pixelRatio||1;mn=[M[0]/et,M[1]/et,Gr.displaySize[0]-M[2]/et,Gr.displaySize[1]-M[3]/et]}const Hn=et.left*$t,so=et.right*$t;let uo,Io,Po,To;"width"===Bt||"both"===Bt?(To=Nt[0]+Hn-Wt[3],Io=Nt[0]+so+Wt[1]):(To=Nt[0]+(Hn+so-Gr.displaySize[0])/2,Io=To+Gr.displaySize[0]);const Eo=et.top*$t,Ia=et.bottom*$t;return"height"===Bt||"both"===Bt?(uo=Nt[1]+Eo-Wt[0],Po=Nt[1]+Ia+Wt[2]):(uo=Nt[1]+(Eo+Ia-Gr.displaySize[1])/2,Po=uo+Gr.displaySize[1]),{image:Gr,top:uo,right:Io,bottom:Po,left:To,collisionPadding:mn}}const id=255,rd=128,nd=id*rd;function mc(M,et){const{expression:Bt}=et;if("constant"===Bt.kind)return{kind:"constant",layoutSize:Bt.evaluate(new cs(M+1))};if("source"===Bt.kind)return{kind:"source"};{const{zoomStops:et,interpolationType:Wt}=Bt;let Nt=0;for(;NtM.id)),this.index=et.index,this.pixelRatio=et.pixelRatio,this.sourceLayerIndex=et.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.sortKeyRanges=[],this.collisionCircleArray=[];const Bt=this.layers[0]._unevaluatedLayout._values;this.textSizeData=mc(this.zoom,Bt["text-size"]),this.iconSizeData=mc(this.zoom,Bt["icon-size"]);const Wt=this.layers[0].layout,Nt=Wt.get("symbol-sort-key"),$t=Wt.get("symbol-z-order");this.canOverlap="never"!==gc(Wt,"text-overlap","text-allow-overlap")||"never"!==gc(Wt,"icon-overlap","icon-allow-overlap")||Wt.get("text-ignore-placement")||Wt.get("icon-ignore-placement"),this.sortFeaturesByKey="viewport-y"!==$t&&!Nt.isConstant(),this.sortFeaturesByY=("viewport-y"===$t||"auto"===$t&&!this.sortFeaturesByKey)&&this.canOverlap,"point"===Wt.get("symbol-placement")&&(this.writingModes=Wt.get("text-writing-mode").map((et=>M.ai[et]))),this.stateDependentLayerIds=this.layers.filter((M=>M.isStateDependent())).map((M=>M.id)),this.sourceID=et.sourceID}createArrays(){this.text=new Sc(new ro(this.layers,this.zoom,(M=>/^text/.test(M)))),this.icon=new Sc(new ro(this.layers,this.zoom,(M=>/^icon/.test(M)))),this.glyphOffsetArray=new oa,this.lineVertexArray=new la,this.symbolInstances=new aa,this.textAnchorOffsets=new ca}calculateGlyphDependencies(M,et,Bt,Wt,Nt){for(let $t=0;$t0)&&("constant"!==Gr.value.kind||Gr.value.value.length>0),uo="constant"!==Hn.value.kind||!!Hn.value.value||Object.keys(Hn.parameters).length>0,Io=$t.get("symbol-sort-key");if(this.features=[],!so&&!uo)return;const Po=Bt.iconDependencies,To=Bt.glyphDependencies,Eo=Bt.availableImages,Ia=new cs(this.zoom);for(const{feature:Bt,id:mn,index:Hn,sourceLayerIndex:Ba}of et){const et=Nt._featureFilter.needGeometry,Ta=lo(Bt,et);if(!Nt._featureFilter.filter(Ia,Ta,Wt))continue;let Va,za;if(et||(Ta.geometry=oo(Bt)),so){const M=Nt.getValueAndResolveTokens("text-field",Ta,Wt,Eo),et=xe.factory(M),Bt=this.hasRTLText=this.hasRTLText||_c(et);(!Bt||"unavailable"===ag.getRTLTextPluginStatus()||Bt&&ag.isParsed())&&(Va=Pu(et,Nt,Ta))}if(uo){const M=Nt.getValueAndResolveTokens("icon-image",Ta,Wt,Eo);za=M instanceof Se?M:Se.fromString(M)}if(!Va&&!za)continue;const Fa=this.sortFeaturesByKey?Io.evaluate(Ta,{},Wt):void 0;if(this.features.push({id:mn,text:Va,icon:za,index:Hn,sourceLayerIndex:Ba,geometry:Ta.geometry,properties:Bt.properties,type:od[Bt.type],sortKey:Fa}),za&&(Po[za.name]=!0),Va){const et=Gr.evaluate(Ta,{},Wt).join(","),Bt="viewport"!==$t.get("text-rotation-alignment")&&"point"!==$t.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(M.ai.vertical)>=0;for(const M of Va.sections)if(M.image)Po[M.image.name]=!0;else{const Wt=Ji(Va.toString()),Nt=M.fontStack||et,$t=To[Nt]=To[Nt]||{};this.calculateGlyphDependencies(M.text,$t,Bt,this.allowVerticalPlacement,Wt)}}}"line"===$t.get("symbol-placement")&&(this.features=function(M){const et={},Bt={},Wt=[];let Nt=0;function s(et){Wt.push(M[et]),Nt++}function a(M,et,Nt){const $t=Bt[M];return delete Bt[M],Bt[et]=$t,Wt[$t].geometry[0].pop(),Wt[$t].geometry[0]=Wt[$t].geometry[0].concat(Nt[0]),$t}function o(M,Bt,Nt){const $t=et[Bt];return delete et[Bt],et[M]=$t,Wt[$t].geometry[0].shift(),Wt[$t].geometry[0]=Nt[0].concat(Wt[$t].geometry[0]),$t}function l(M,et,Bt){const Wt=Bt?et[0][et[0].length-1]:et[0][0];return`${M}:${Wt.x}:${Wt.y}`}for(let $t=0;$tM.geometry))}(this.features)),this.sortFeaturesByKey&&this.features.sort(((M,et)=>M.sortKey-et.sortKey))}update(M,et,Bt){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(M,et,this.layers,Bt),this.icon.programConfigurations.updatePaintArrays(M,et,this.layers,Bt))}isEmpty(){return 0===this.symbolInstances.length&&!this.hasRTLText}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(M){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(M),this.iconCollisionBox.upload(M)),this.text.upload(M,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(M,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(M,et){const Bt=this.lineVertexArray.length;if(void 0!==M.segment){let Bt=M.dist(et[M.segment+1]),Wt=M.dist(et[M.segment]);const Nt={};for(let Wt=M.segment+1;Wt=0;Bt--)Nt[Bt]={x:et[Bt].x,y:et[Bt].y,tileUnitDistanceFromAnchor:Wt},Bt>0&&(Wt+=et[Bt-1].dist(et[Bt]));for(let M=0;M0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(M,et){const Bt=M.placedSymbolArray.get(et),Wt=Bt.vertexStartIndex+4*Bt.numGlyphs;for(let et=Bt.vertexStartIndex;etWt[M]-Wt[et]||Nt[et]-Nt[M])),$t}addToSortKeyRanges(M,et){const Bt=this.sortKeyRanges[this.sortKeyRanges.length-1];Bt&&Bt.sortKey===et?Bt.symbolInstanceEnd=M+1:this.sortKeyRanges.push({sortKey:et,symbolInstanceStart:M,symbolInstanceEnd:M+1})}sortFeatures(M){if(this.sortFeaturesByY&&this.sortedAngle!==M&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(M),this.sortedAngle=M,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const M of this.symbolInstanceIndexes){const et=this.symbolInstances.get(M);this.featureSortOrder.push(et.featureIndex),[et.rightJustifiedTextSymbolIndex,et.centerJustifiedTextSymbolIndex,et.leftJustifiedTextSymbolIndex].forEach(((M,et,Bt)=>{M>=0&&Bt.indexOf(M)===et&&this.addIndicesForPlacedSymbol(this.text,M)})),et.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,et.verticalPlacedTextSymbolIndex),et.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,et.placedIconSymbolIndex),et.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,et.verticalPlacedIconSymbolIndex)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}}let ad,ld;Ui("SymbolBucket",kc,{omit:["layers","collisionBoxArray","features","compareText"]}),kc.MAX_GLYPHS=65535,kc.addDynamicAttributes=wc;var cd={get paint(){return ld=ld||new As({"icon-opacity":new bs(Ka.paint_symbol["icon-opacity"]),"icon-color":new bs(Ka.paint_symbol["icon-color"]),"icon-halo-color":new bs(Ka.paint_symbol["icon-halo-color"]),"icon-halo-width":new bs(Ka.paint_symbol["icon-halo-width"]),"icon-halo-blur":new bs(Ka.paint_symbol["icon-halo-blur"]),"icon-translate":new vs(Ka.paint_symbol["icon-translate"]),"icon-translate-anchor":new vs(Ka.paint_symbol["icon-translate-anchor"]),"text-opacity":new bs(Ka.paint_symbol["text-opacity"]),"text-color":new bs(Ka.paint_symbol["text-color"],{runtimeType:Gl,getOverride:M=>M.textColor,hasOverride:M=>!!M.textColor}),"text-halo-color":new bs(Ka.paint_symbol["text-halo-color"]),"text-halo-width":new bs(Ka.paint_symbol["text-halo-width"]),"text-halo-blur":new bs(Ka.paint_symbol["text-halo-blur"]),"text-translate":new vs(Ka.paint_symbol["text-translate"]),"text-translate-anchor":new vs(Ka.paint_symbol["text-translate-anchor"])})},get layout(){return ad=ad||new As({"symbol-placement":new vs(Ka.layout_symbol["symbol-placement"]),"symbol-spacing":new vs(Ka.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new vs(Ka.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new bs(Ka.layout_symbol["symbol-sort-key"]),"symbol-z-order":new vs(Ka.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new vs(Ka.layout_symbol["icon-allow-overlap"]),"icon-overlap":new vs(Ka.layout_symbol["icon-overlap"]),"icon-ignore-placement":new vs(Ka.layout_symbol["icon-ignore-placement"]),"icon-optional":new vs(Ka.layout_symbol["icon-optional"]),"icon-rotation-alignment":new vs(Ka.layout_symbol["icon-rotation-alignment"]),"icon-size":new bs(Ka.layout_symbol["icon-size"]),"icon-text-fit":new vs(Ka.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new vs(Ka.layout_symbol["icon-text-fit-padding"]),"icon-image":new bs(Ka.layout_symbol["icon-image"]),"icon-rotate":new bs(Ka.layout_symbol["icon-rotate"]),"icon-padding":new bs(Ka.layout_symbol["icon-padding"]),"icon-keep-upright":new vs(Ka.layout_symbol["icon-keep-upright"]),"icon-offset":new bs(Ka.layout_symbol["icon-offset"]),"icon-anchor":new bs(Ka.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new vs(Ka.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new vs(Ka.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new vs(Ka.layout_symbol["text-rotation-alignment"]),"text-field":new bs(Ka.layout_symbol["text-field"]),"text-font":new bs(Ka.layout_symbol["text-font"]),"text-size":new bs(Ka.layout_symbol["text-size"]),"text-max-width":new bs(Ka.layout_symbol["text-max-width"]),"text-line-height":new vs(Ka.layout_symbol["text-line-height"]),"text-letter-spacing":new bs(Ka.layout_symbol["text-letter-spacing"]),"text-justify":new bs(Ka.layout_symbol["text-justify"]),"text-radial-offset":new bs(Ka.layout_symbol["text-radial-offset"]),"text-variable-anchor":new vs(Ka.layout_symbol["text-variable-anchor"]),"text-variable-anchor-offset":new bs(Ka.layout_symbol["text-variable-anchor-offset"]),"text-anchor":new bs(Ka.layout_symbol["text-anchor"]),"text-max-angle":new vs(Ka.layout_symbol["text-max-angle"]),"text-writing-mode":new vs(Ka.layout_symbol["text-writing-mode"]),"text-rotate":new bs(Ka.layout_symbol["text-rotate"]),"text-padding":new vs(Ka.layout_symbol["text-padding"]),"text-keep-upright":new vs(Ka.layout_symbol["text-keep-upright"]),"text-transform":new bs(Ka.layout_symbol["text-transform"]),"text-offset":new bs(Ka.layout_symbol["text-offset"]),"text-allow-overlap":new vs(Ka.layout_symbol["text-allow-overlap"]),"text-overlap":new vs(Ka.layout_symbol["text-overlap"]),"text-ignore-placement":new vs(Ka.layout_symbol["text-ignore-placement"]),"text-optional":new vs(Ka.layout_symbol["text-optional"])})}};class Pc{constructor(M){if(void 0===M.property.overrides)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=M.property.overrides?M.property.overrides.runtimeType:$a,this.defaultValue=M}evaluate(M){if(M.formattedSection){const et=this.defaultValue.property.overrides;if(et&&et.hasOverride(M.formattedSection))return et.getOverride(M.formattedSection)}return M.feature&&M.featureState?this.defaultValue.evaluate(M.feature,M.featureState):this.defaultValue.property.specification.default}eachChild(M){this.defaultValue.isConstant()||M(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}Ui("FormatSectionOverride",Pc,{omit:["defaultValue"]});class Cc extends Ms{constructor(M){super(M,cd)}recalculate(M,et){if(super.recalculate(M,et),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]="map"===this.layout.get("text-rotation-alignment")?"map":"viewport"),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){const M=this.layout.get("text-writing-mode");if(M){const et=[];for(const Bt of M)et.indexOf(Bt)<0&&et.push(Bt);this.layout._values["text-writing-mode"]=et}else this.layout._values["text-writing-mode"]=["horizontal"]}this._setPaintOverrides()}getValueAndResolveTokens(M,et,Bt,Wt){const Nt=this.layout.get(M).evaluate(et,{},Bt,Wt),$t=this._unevaluatedLayout._values[M];return $t.isDataDriven()||jn($t.value)||!Nt?Nt:function(M,et){return et.replace(/{([^{}]+)}/g,((et,Bt)=>M&&Bt in M?String(M[Bt]):""))}(et.properties,Nt)}createBucket(M){return new kc(M)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(const M of cd.paint.overridableProperties){if(!Cc.hasPaintOverride(this.layout,M))continue;const et=this.paint.get(M),Bt=new Pc(et),Wt=new Rn(Bt,et.property.specification);let Nt=null;Nt="constant"===et.value.kind||"source"===et.value.kind?new Un("source",Wt):new qn("composite",Wt,et.value.zoomStops),this.paint._values[M]=new gs(et.property,Nt,et.parameters)}}_handleOverridablePaintPropertyUpdate(M,et,Bt){return!(!this.layout||et.isDataDriven()||Bt.isDataDriven())&&Cc.hasPaintOverride(this.layout,M)}static hasPaintOverride(M,et){const Bt=M.get("text-field"),Wt=cd.paint.properties[et];let Nt=!1;const s=M=>{for(const et of M)if(Wt.overrides&&Wt.overrides.hasOverride(et))return void(Nt=!0)};if("constant"===Bt.value.kind&&Bt.value.value instanceof xe)s(Bt.value.value.sections);else if("source"===Bt.value.kind){const t=M=>{Nt||(M instanceof Pe&&Ie(M.value)===El?s(M.value.sections):M instanceof br?s(M.sections):M.eachChild(t))},M=Bt.value;M._styleExpression&&t(M._styleExpression.expression)}return Nt}}let hd;var gd={get paint(){return hd=hd||new As({"background-color":new vs(Ka.paint_background["background-color"]),"background-pattern":new _s(Ka.paint_background["background-pattern"]),"background-opacity":new vs(Ka.paint_background["background-opacity"])})}};class Ec extends Ms{constructor(M){super(M,gd)}}let ud;var dd={get paint(){return ud=ud||new As({"raster-opacity":new vs(Ka.paint_raster["raster-opacity"]),"raster-hue-rotate":new vs(Ka.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new vs(Ka.paint_raster["raster-brightness-min"]),"raster-brightness-max":new vs(Ka.paint_raster["raster-brightness-max"]),"raster-saturation":new vs(Ka.paint_raster["raster-saturation"]),"raster-contrast":new vs(Ka.paint_raster["raster-contrast"]),"raster-resampling":new vs(Ka.paint_raster["raster-resampling"]),"raster-fade-duration":new vs(Ka.paint_raster["raster-fade-duration"])})}};class $c extends Ms{constructor(M){super(M,dd)}}class Lc extends Ms{constructor(M){super(M,{}),this.onAdd=M=>{this.implementation.onAdd&&this.implementation.onAdd(M,M.painter.context.gl)},this.onRemove=M=>{this.implementation.onRemove&&this.implementation.onRemove(M,M.painter.context.gl)},this.implementation=M}is3D(){return"3d"===this.implementation.renderingMode}hasOffscreenPass(){return void 0!==this.implementation.prerender}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){throw new Error("Custom layers cannot be serialized")}}class Dc{constructor(M){this._methodToThrottle=M,this._triggered=!1,"undefined"!=typeof MessageChannel&&(this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=!1,this._methodToThrottle()})}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout((()=>{this._triggered=!1,this._methodToThrottle()}),0))}remove(){delete this._channel,this._methodToThrottle=()=>{}}}const pd=6371008.8;class Rc{constructor(M,et){if(isNaN(M)||isNaN(et))throw new Error(`Invalid LngLat object: (${M}, ${et})`);if(this.lng=+M,this.lat=+et,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new Rc(T(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(M){const et=Math.PI/180,Bt=this.lat*et,Wt=M.lat*et,Nt=Math.sin(Bt)*Math.sin(Wt)+Math.cos(Bt)*Math.cos(Wt)*Math.cos((M.lng-this.lng)*et);return pd*Math.acos(Math.min(Nt,1))}static convert(M){if(M instanceof Rc)return M;if(Array.isArray(M)&&(2===M.length||3===M.length))return new Rc(Number(M[0]),Number(M[1]));if(!Array.isArray(M)&&"object"==typeof M&&null!==M)return new Rc(Number("lng"in M?M.lng:M.lon),Number(M.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}const md=2*Math.PI*pd;function Nc(M){return md*Math.cos(M*Math.PI/180)}function Uc(M){return(180+M)/360}function qc(M){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+M*Math.PI/360)))/360}function Gc(M,et){return M/Nc(et)}function Zc(M){return 360/Math.PI*Math.atan(Math.exp((180-360*M)*Math.PI/180))-90}function Xc(M,et){return M*Nc(Zc(et))}class Kc{constructor(M,et,Bt=0){this.x=+M,this.y=+et,this.z=+Bt}static fromLngLat(M,et=0){const Bt=Rc.convert(M);return new Kc(Uc(Bt.lng),qc(Bt.lat),Gc(et,Bt.lat))}toLngLat(){return new Rc(360*this.x-180,Zc(this.y))}toAltitude(){return Xc(this.z,this.y)}meterInMercatorCoordinateUnits(){return 1/md*(M=Zc(this.y),1/Math.cos(M*Math.PI/180));var M}}function Hc(M,et,Bt){var Wt=2*Math.PI*6378137/256/Math.pow(2,Bt);return[M*Wt-2*Math.PI*6378137/2,et*Wt-2*Math.PI*6378137/2]}class Yc{constructor(M,et,Bt){if(!function(M,et,Bt){return!(M<0||M>25||Bt<0||Bt>=Math.pow(2,M)||et<0||et>=Math.pow(2,M))}(M,et,Bt))throw new Error(`x=${et}, y=${Bt}, z=${M} outside of bounds. 0<=x<${Math.pow(2,M)}, 0<=y<${Math.pow(2,M)} 0<=z<=25 `);this.z=M,this.x=et,this.y=Bt,this.key=Qc(0,M,M,et,Bt)}equals(M){return this.z===M.z&&this.x===M.x&&this.y===M.y}url(M,et,Bt){const Wt=($t=this.y,Gr=this.z,mn=Hc(256*(Nt=this.x),256*($t=Math.pow(2,Gr)-$t-1),Gr),Hn=Hc(256*(Nt+1),256*($t+1),Gr),mn[0]+","+mn[1]+","+Hn[0]+","+Hn[1]);var Nt,$t,Gr,mn,Hn;const so=function(M,et,Bt){let Wt,Nt="";for(let $t=M;$t>0;$t--)Wt=1<<$t-1,Nt+=(et&Wt?1:0)+(Bt&Wt?2:0);return Nt}(this.z,this.x,this.y);return M[(this.x+this.y)%M.length].replace(/{prefix}/g,(this.x%16).toString(16)+(this.y%16).toString(16)).replace(/{z}/g,String(this.z)).replace(/{x}/g,String(this.x)).replace(/{y}/g,String("tms"===Bt?Math.pow(2,this.z)-this.y-1:this.y)).replace(/{ratio}/g,et>1?"@2x":"").replace(/{quadkey}/g,so).replace(/{bbox-epsg-3857}/g,Wt)}isChildOf(M){const et=this.z-M.z;return et>0&&M.x===this.x>>et&&M.y===this.y>>et}getTilePoint(M){const et=Math.pow(2,this.z);return new $t((M.x*et-this.x)*To,(M.y*et-this.y)*To)}toString(){return`${this.z}/${this.x}/${this.y}`}}class Jc{constructor(M,et){this.wrap=M,this.canonical=et,this.key=Qc(M,et.z,et.z,et.x,et.y)}}class Wc{constructor(M,et,Bt,Wt,Nt){if(this.terrainRttPosMatrix32f=null,M= z; overscaledZ = ${M}; z = ${Bt}`);this.overscaledZ=M,this.wrap=et,this.canonical=new Yc(Bt,+Wt,+Nt),this.key=Qc(et,M,Bt,Wt,Nt)}clone(){return new Wc(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(M){return this.overscaledZ===M.overscaledZ&&this.wrap===M.wrap&&this.canonical.equals(M.canonical)}scaledTo(M){if(M>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${M}; overscaledZ = ${this.overscaledZ}`);const et=this.canonical.z-M;return M>this.canonical.z?new Wc(M,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new Wc(M,this.wrap,M,this.canonical.x>>et,this.canonical.y>>et)}calculateScaledKey(M,et){if(M>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${M}; overscaledZ = ${this.overscaledZ}`);const Bt=this.canonical.z-M;return M>this.canonical.z?Qc(this.wrap*+et,M,this.canonical.z,this.canonical.x,this.canonical.y):Qc(this.wrap*+et,M,M,this.canonical.x>>Bt,this.canonical.y>>Bt)}isChildOf(M){if(M.wrap!==this.wrap)return!1;const et=this.canonical.z-M.canonical.z;return 0===M.overscaledZ||M.overscaledZ>et&&M.canonical.y===this.canonical.y>>et}children(M){if(this.overscaledZ>=M)return[new Wc(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const et=this.canonical.z+1,Bt=2*this.canonical.x,Wt=2*this.canonical.y;return[new Wc(et,this.wrap,et,Bt,Wt),new Wc(et,this.wrap,et,Bt+1,Wt),new Wc(et,this.wrap,et,Bt,Wt+1),new Wc(et,this.wrap,et,Bt+1,Wt+1)]}isLessThan(M){return this.wrapM.wrap)&&(this.overscaledZM.overscaledZ)&&(this.canonical.xM.canonical.x)&&this.canonical.ythis.max&&(this.max=Bt),Bt=this.dim+1||et<-1||et>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(et+1)*this.stride+(M+1)}unpack(M,et,Bt){return M*this.redFactor+et*this.greenFactor+Bt*this.blueFactor-this.baseShift}getPixels(){return new Oo({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(M,et,Bt){if(this.dim!==M.dim)throw new Error("dem dimension mismatch");let Wt=et*this.dim,Nt=et*this.dim+this.dim,$t=Bt*this.dim,Gr=Bt*this.dim+this.dim;switch(et){case-1:Wt=Nt-1;break;case 1:Nt=Wt+1}switch(Bt){case-1:$t=Gr-1;break;case 1:Gr=$t+1}const mn=-et*this.dim,Hn=-Bt*this.dim;for(let et=$t;et=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${M} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[M]}}class rh{constructor(M,et,Bt,Wt,Nt){this.type="Feature",this._vectorTileFeature=M,M._z=et,M._x=Bt,M._y=Wt,this.properties=M.properties,this.id=Nt}get geometry(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry}set geometry(M){this._geometry=M}toJSON(){const M={geometry:this.geometry};for(const et in this)"_geometry"!==et&&"_vectorTileFeature"!==et&&(M[et]=this[et]);return M}}class nh{constructor(M,et){this.tileID=M,this.x=M.canonical.x,this.y=M.canonical.y,this.z=M.canonical.z,this.grid=new ji(To,16,0),this.grid3D=new ji(To,16,0),this.featureIndexArray=new pa,this.promoteId=et}insert(M,et,Bt,Wt,Nt,$t){const Gr=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(Bt,Wt,Nt);const mn=$t?this.grid3D:this.grid;for(let M=0;M=0&&Wt[3]>=0&&mn.insert(Gr,Wt[0],Wt[1],Wt[2],Wt[3])}}loadVTLayers(){return this.vtLayers||(this.vtLayers=new Qg.VectorTile(new Eu(this.rawTileData)).layers,this.sourceLayerCoder=new eh(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers}query(M,et,Bt,Wt){this.loadVTLayers();const Nt=M.params,Gr=To/M.tileSize/M.scale,mn=Yn(Nt.filter),Hn=M.queryGeometry,so=M.queryPadding*Gr,uo=sh(Hn),Io=this.grid.query(uo.minX-so,uo.minY-so,uo.maxX+so,uo.maxY+so),Po=sh(M.cameraQueryGeometry),Eo=this.grid3D.query(Po.minX-so,Po.minY-so,Po.maxX+so,Po.maxY+so,((et,Bt,Wt,Nt)=>function(M,et,Bt,Wt,Nt){for(const $t of M)if(et<=$t.x&&Bt<=$t.y&&Wt>=$t.x&&Nt>=$t.y)return!0;const Gr=[new $t(et,Bt),new $t(et,Nt),new $t(Wt,Nt),new $t(Wt,Bt)];if(M.length>2)for(const et of Gr)if(_o(M,et))return!0;for(let et=0;et(Po||(Po=oo(et)),Bt.queryIntersectsFeature({queryGeometry:Hn,feature:et,featureState:Wt,geometry:Po,zoom:this.z,transform:M.transform,pixelsToTileUnits:Gr,pixelPosMatrix:M.pixelPosMatrix}))))}return Ia}loadMatchingFeature(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo){const Io=this.bucketLayerIDs[et];if($t&&!Io.some((M=>$t.has(M))))return;const Po=this.sourceLayerCoder.decode(Bt),To=this.vtLayers[Po].feature(Wt);if(Nt.needGeometry){const M=lo(To,!0);if(!Nt.filter(new cs(this.tileID.overscaledZ),M,this.tileID.canonical))return}else if(!Nt.filter(new cs(this.tileID.overscaledZ),To))return;const Eo=this.getId(To,Po);for(let et=0;et{const Gr=et instanceof xs?et.get($t):null;return Gr&&Gr.evaluate?Gr.evaluate(Bt,Wt,Nt):Gr}))}function sh(M){let et=1/0,Bt=1/0,Wt=-1/0,Nt=-1/0;for(const $t of M)et=Math.min(et,$t.x),Bt=Math.min(Bt,$t.y),Wt=Math.max(Wt,$t.x),Nt=Math.max(Nt,$t.y);return{minX:et,minY:Bt,maxX:Wt,maxY:Nt}}function ah(M,et){return et-M}function oh(M,et,Bt,Wt,Nt){const Gr=[];for(let mn=0;mn=Wt&&uo.x>=Wt||(mn.x>=Wt?mn=new $t(Wt,mn.y+(Wt-mn.x)/(uo.x-mn.x)*(uo.y-mn.y))._round():uo.x>=Wt&&(uo=new $t(Wt,mn.y+(Wt-mn.x)/(uo.x-mn.x)*(uo.y-mn.y))._round()),mn.y>=Nt&&uo.y>=Nt||(mn.y>=Nt?mn=new $t(mn.x+(Nt-mn.y)/(uo.y-mn.y)*(uo.x-mn.x),Nt)._round():uo.y>=Nt&&(uo=new $t(mn.x+(Nt-mn.y)/(uo.y-mn.y)*(uo.x-mn.x),Nt)._round()),so&&mn.equals(so[so.length-1])||(so=[mn],Gr.push(so)),so.push(uo)))))}}return Gr}Ui("FeatureIndex",nh,{omit:["rawTileData","sourceLayerCoder"]});class lh extends $t{constructor(M,et,Bt,Wt){super(M,et),this.angle=Bt,void 0!==Wt&&(this.segment=Wt)}clone(){return new lh(this.x,this.y,this.angle,this.segment)}}function uh(M,et,Bt,Wt,Nt){if(void 0===et.segment||0===Bt)return!0;let $t=et,Gr=et.segment+1,mn=0;for(;mn>-Bt/2;){if(Gr--,Gr<0)return!1;mn-=M[Gr].dist($t),$t=M[Gr]}mn+=M[Gr].dist(M[Gr+1]),Gr++;const Hn=[];let so=0;for(;mnWt;)so-=Hn.shift().angleDelta;if(so>Nt)return!1;Gr++,mn+=et.dist(Bt)}return!0}function ch(M){let et=0;for(let Bt=0;Btso){const uo=(so-Hn)/$t,Io=zc.number(Wt.x,Nt.x,uo),Po=zc.number(Wt.y,Nt.y,uo),To=new lh(Io,Po,Nt.angleTo(Wt),Bt);return To._round(),!Gr||uh(M,To,mn,Gr,et)?To:void 0}Hn+=$t}}function dh(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn){const so=hh(Wt,$t,Gr),uo=ph(Wt,Nt),Io=uo*Gr,Po=0===M[0].x||M[0].x===Hn||0===M[0].y||M[0].y===Hn;return et-Io=0&&Ta=0&&Va=0&&Po+so<=uo){const Bt=new lh(Ta,Va,Ia,et);Bt._round(),Wt&&!uh(M,Bt,$t,Wt,Nt)||To.push(Bt)}}Io+=Eo}return mn||To.length||Gr||(To=yh(M,Io/2,Bt,Wt,Nt,$t,Gr,!0,Hn)),To}Ui("Anchor",lh);const Cd=Ku;function gh(M,et,Bt,Wt){const Nt=[],Gr=M.image,mn=Gr.pixelRatio,Hn=Gr.paddedRect.w-2*Cd,so=Gr.paddedRect.h-2*Cd;let uo={x1:M.left,y1:M.top,x2:M.right,y2:M.bottom};const Io=Gr.stretchX||[[0,Hn]],Po=Gr.stretchY||[[0,so]],f=(M,et)=>M+et[1]-et[0],To=Io.reduce(f,0),Eo=Po.reduce(f,0),Ia=Hn-To,Ba=so-Eo;let Ta=0,Va=To,za=0,Fa=Eo,Ea=0,La=Ia,Da=0,Ka=Ba;if(Gr.content&&Wt){const et=Gr.content,Bt=et[2]-et[0],Wt=et[3]-et[1];(Gr.textFitWidth||Gr.textFitHeight)&&(uo=hc(M)),Ta=xh(Io,0,et[0]),za=xh(Po,0,et[1]),Va=xh(Io,et[0],et[2]),Fa=xh(Po,et[1],et[3]),Ea=et[0]-Ta,Da=et[1]-za,La=Bt-Va,Ka=Wt-Fa}const Oa=uo.x1,$a=uo.y1,Al=uo.x2-Oa,Sl=uo.y2-$a,C=(M,Wt,Nt,Hn)=>{const so=bh(M.stretch-Ta,Va,Al,Oa),uo=wh(M.fixed-Ea,La,M.stretch,To),Io=bh(Wt.stretch-za,Fa,Sl,$a),Po=wh(Wt.fixed-Da,Ka,Wt.stretch,Eo),Ia=bh(Nt.stretch-Ta,Va,Al,Oa),Ba=wh(Nt.fixed-Ea,La,Nt.stretch,To),Zl=bh(Hn.stretch-za,Fa,Sl,$a),Gl=wh(Hn.fixed-Da,Ka,Hn.stretch,Eo),Rl=new $t(so,Io),Tl=new $t(Ia,Io),Vl=new $t(Ia,Zl),Wl=new $t(so,Zl),El=new $t(uo/mn,Po/mn),Jl=new $t(Ba/mn,Gl/mn),Ll=et*Math.PI/180;if(Ll){const M=Math.sin(Ll),et=Math.cos(Ll),Bt=[et,-M,M,et];Rl._matMult(Bt),Tl._matMult(Bt),Wl._matMult(Bt),Vl._matMult(Bt)}const Dl=M.stretch+M.fixed,Nl=Wt.stretch+Wt.fixed;return{tl:Rl,tr:Tl,bl:Wl,br:Vl,tex:{x:Gr.paddedRect.x+Cd+Dl,y:Gr.paddedRect.y+Cd+Nl,w:Nt.stretch+Nt.fixed-Dl,h:Hn.stretch+Hn.fixed-Nl},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:El,pixelOffsetBR:Jl,minFontScaleX:La/mn/Al,minFontScaleY:Ka/mn/Sl,isSDF:Bt}};if(Wt&&(Gr.stretchX||Gr.stretchY)){const M=vh(Io,Ia,To),et=vh(Po,Ba,Eo);for(let Bt=0;Bt0&&(Wt=Math.max(10,Wt),this.circleDiameter=Wt)}else{const so=(null===(Io=Gr.image)||void 0===Io?void 0:Io.content)&&(Gr.image.textFitWidth||Gr.image.textFitHeight)?hc(Gr):{x1:Gr.left,y1:Gr.top,x2:Gr.right,y2:Gr.bottom};so.y1=so.y1*mn-Hn[0],so.y2=so.y2*mn+Hn[2],so.x1=so.x1*mn-Hn[3],so.x2=so.x2*mn+Hn[1];const Po=Gr.collisionPadding;if(Po&&(so.x1-=Po[0]*mn,so.y1-=Po[1]*mn,so.x2+=Po[2]*mn,so.y2+=Po[3]*mn),uo){const M=new $t(so.x1,so.y1),et=new $t(so.x2,so.y1),Bt=new $t(so.x1,so.y2),Wt=new $t(so.x2,so.y2),Nt=uo*Math.PI/180;M._rotate(Nt),et._rotate(Nt),Bt._rotate(Nt),Wt._rotate(Nt),so.x1=Math.min(M.x,et.x,Bt.x,Wt.x),so.x2=Math.max(M.x,et.x,Bt.x,Wt.x),so.y1=Math.min(M.y,et.y,Bt.y,Wt.y),so.y2=Math.max(M.y,et.y,Bt.y,Wt.y)}M.emplaceBack(et.x,et.y,so.x1,so.y1,so.x2,so.y2,Bt,Wt,Nt)}this.boxEndIndex=M.length}}class Sh{constructor(M=[],et=(M,et)=>Met?1:0){if(this.data=M,this.length=this.data.length,this.compare=et,this.length>0)for(let M=(this.length>>1)-1;M>=0;M--)this._down(M)}push(M){this.data.push(M),this._up(this.length++)}pop(){if(0===this.length)return;const M=this.data[0],et=this.data.pop();return--this.length>0&&(this.data[0]=et,this._down(0)),M}peek(){return this.data[0]}_up(M){const{data:et,compare:Bt}=this,Wt=et[M];for(;M>0;){const Nt=M-1>>1,$t=et[Nt];if(Bt(Wt,$t)>=0)break;et[M]=$t,M=Nt}et[M]=Wt}_down(M){const{data:et,compare:Bt}=this,Wt=this.length>>1,Nt=et[M];for(;M=0)break;et[M]=et[Wt],M=Wt}et[M]=Nt}}function Ah(M,et=1,Bt=!1){let Wt=1/0,Nt=1/0,Gr=-1/0,mn=-1/0;const Hn=M[0];for(let M=0;MGr)&&(Gr=et.x),(!M||et.y>mn)&&(mn=et.y)}const so=Math.min(Gr-Wt,mn-Nt);let uo=so/2;const Io=new Sh([],kh);if(0===so)return new $t(Wt,Nt);for(let et=Wt;etPo.d||!Po.d)&&(Po=Wt,Bt&&console.log("found best %d after %d probes",Math.round(1e4*Wt.d)/1e4,To)),Wt.max-Po.d<=et||(uo=Wt.h/2,Io.push(new Mh(Wt.p.x-uo,Wt.p.y-uo,uo,M)),Io.push(new Mh(Wt.p.x+uo,Wt.p.y-uo,uo,M)),Io.push(new Mh(Wt.p.x-uo,Wt.p.y+uo,uo,M)),Io.push(new Mh(Wt.p.x+uo,Wt.p.y+uo,uo,M)),To+=4)}return Bt&&(console.log(`num probes: ${To}`),console.log(`best distance: ${Po.d}`)),Po.p}function kh(M,et){return et.max-M.max}function Mh(M,et,Bt,Wt){this.p=new $t(M,et),this.h=Bt,this.d=function(M,et){let Bt=!1,Wt=1/0;for(let Nt=0;NtM.y!=mn.y>M.y&&M.x<(mn.x-Nt.x)*(M.y-Nt.y)/(mn.y-Nt.y)+Nt.x&&(Bt=!Bt),Wt=Math.min(Wt,bo(M,Nt,mn))}}return(Bt?1:-1)*Math.sqrt(Wt)}(this.p,Wt),this.max=this.d+this.h*Math.SQRT2}var Id;M.av=void 0,(Id=M.av||(M.av={}))[Id.center=1]="center",Id[Id.left=2]="left",Id[Id.right=3]="right",Id[Id.top=4]="top",Id[Id.bottom=5]="bottom",Id[Id["top-left"]=6]="top-left",Id[Id["top-right"]=7]="top-right",Id[Id["bottom-left"]=8]="bottom-left",Id[Id["bottom-right"]=9]="bottom-right";const fd=7,yd=Number.POSITIVE_INFINITY;function Ch(M,et){return et[1]!==yd?function(M,et,Bt){let Wt=0,Nt=0;switch(et=Math.abs(et),Bt=Math.abs(Bt),M){case"top-right":case"top-left":case"top":Nt=Bt-fd;break;case"bottom-right":case"bottom-left":case"bottom":Nt=-Bt+fd}switch(M){case"top-right":case"bottom-right":case"right":Wt=-et;break;case"top-left":case"bottom-left":case"left":Wt=et}return[Wt,Nt]}(M,et[0],et[1]):function(M,et){let Bt=0,Wt=0;et<0&&(et=0);const Nt=et/Math.SQRT2;switch(M){case"top-right":case"top-left":Wt=Nt-fd;break;case"bottom-right":case"bottom-left":Wt=-Nt+fd;break;case"bottom":Wt=-et+fd;break;case"top":Wt=et-fd}switch(M){case"top-right":case"bottom-right":Bt=-Nt;break;case"top-left":case"bottom-left":Bt=Nt;break;case"left":Bt=et;break;case"right":Bt=-et}return[Bt,Wt]}(M,et[0])}function Bh(M,et,Bt){var Wt;const Nt=M.layout,$t=null===(Wt=Nt.get("text-variable-anchor-offset"))||void 0===Wt?void 0:Wt.evaluate(et,{},Bt);if($t){const M=$t.values,et=[];for(let Bt=0;BtM*zu));Wt.startsWith("top")?Nt[1]-=fd:Wt.startsWith("bottom")&&(Nt[1]+=fd),et[Bt+1]=Nt}return new _e(et)}const Gr=Nt.get("text-variable-anchor");if(Gr){let Wt;Wt=void 0!==M._unevaluatedLayout.getValue("text-radial-offset")?[Nt.get("text-radial-offset").evaluate(et,{},Bt)*zu,yd]:Nt.get("text-offset").evaluate(et,{},Bt).map((M=>M*zu));const $t=[];for(const M of Gr)$t.push(M,Ch(M,Wt));return new _e($t)}return null}function Vh(M){switch(M){case"right":case"top-right":case"bottom-right":return"right";case"left":case"top-left":case"bottom-left":return"left"}return"center"}function Eh(et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po){let Eo=Gr.textMaxSize.evaluate(Bt,{});void 0===Eo&&(Eo=mn);const Ia=et.layers[0].layout,Ba=Ia.get("icon-offset").evaluate(Bt,{},Io),Ta=Fh(Wt.horizontal),Va=mn/24,za=et.tilePixelRatio*Va,Fa=et.tilePixelRatio*Eo/24,Ea=et.tilePixelRatio*Hn,La=et.tilePixelRatio*Ia.get("symbol-spacing"),Da=Ia.get("text-padding")*et.tilePixelRatio,Ka=function(M,et,Bt,Wt=1){const Nt=M.get("icon-padding").evaluate(et,{},Bt),$t=Nt&&Nt.values;return[$t[0]*Wt,$t[1]*Wt,$t[2]*Wt,$t[3]*Wt]}(Ia,Bt,Io,et.tilePixelRatio),Oa=Ia.get("text-max-angle")/180*Math.PI,$a="viewport"!==Ia.get("text-rotation-alignment")&&"point"!==Ia.get("symbol-placement"),Al="map"===Ia.get("icon-rotation-alignment")&&"point"!==Ia.get("symbol-placement"),Sl=Ia.get("symbol-placement"),Zl=La/2,Gl=Ia.get("icon-text-fit");let Rl;Nt&&"none"!==Gl&&(et.allowVerticalPlacement&&Wt.vertical&&(Rl=pc(Nt,Wt.vertical,Gl,Ia.get("icon-text-fit-padding"),Ba,Va)),Ta&&(Nt=pc(Nt,Ta,Gl,Ia.get("icon-text-fit-padding"),Ba,Va)));const Tl=Io?Po.line.getGranularityForZoomLevel(Io.z):1,E=(Hn,Po)=>{Po.x<0||Po.x>=To||Po.y<0||Po.y>=To||function(et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba,Ta,Va,za,Fa,Ea,La,Da,Ka,Oa){const $a=et.addToLineVertexArray(Bt,Wt);let Al,Sl,Zl,Gl,Rl=0,Tl=0,Vl=0,Wl=0,El=-1,Jl=-1;const Ll={};let Dl=Ag("");if(et.allowVerticalPlacement&&Nt.vertical){const M=Hn.layout.get("text-rotate").evaluate(Ea,{},Ka)+90;Zl=new _h(so,Bt,uo,Io,Po,Nt.vertical,To,Eo,Ia,M),mn&&(Gl=new _h(so,Bt,uo,Io,Po,mn,Ta,Va,Ia,M))}if($t){const Wt=Hn.layout.get("icon-rotate").evaluate(Ea,{}),Nt="none"!==Hn.layout.get("icon-text-fit"),Gr=gh($t,Wt,Da,Nt),To=mn?gh(mn,Wt,Da,Nt):void 0;Sl=new _h(so,Bt,uo,Io,Po,$t,Ta,Va,!1,Wt),Rl=4*Gr.length;const Eo=et.iconSizeData;let Ia=null;"source"===Eo.kind?(Ia=[rd*Hn.layout.get("icon-size").evaluate(Ea,{})],Ia[0]>nd&&j(`${et.layerIds[0]}: Value for "icon-size" is >= ${id}. Reduce your "icon-size".`)):"composite"===Eo.kind&&(Ia=[rd*La.compositeIconSizes[0].evaluate(Ea,{},Ka),rd*La.compositeIconSizes[1].evaluate(Ea,{},Ka)],(Ia[0]>nd||Ia[1]>nd)&&j(`${et.layerIds[0]}: Value for "icon-size" is >= ${id}. Reduce your "icon-size".`)),et.addSymbols(et.icon,Gr,Ia,Fa,za,Ea,M.ai.none,Bt,$a.lineStartIndex,$a.lineLength,-1,Ka),El=et.icon.placedSymbolArray.length-1,To&&(Tl=4*To.length,et.addSymbols(et.icon,To,Ia,Fa,za,Ea,M.ai.vertical,Bt,$a.lineStartIndex,$a.lineLength,-1,Ka),Jl=et.icon.placedSymbolArray.length-1)}const Nl=Object.keys(Nt.horizontal);for(const Wt of Nl){const $t=Nt.horizontal[Wt];if(!Al){Dl=Ag($t.text);const M=Hn.layout.get("text-rotate").evaluate(Ea,{},Ka);Al=new _h(so,Bt,uo,Io,Po,$t,To,Eo,Ia,M)}const mn=1===$t.positionedLines.length;if(Vl+=Th(et,Bt,$t,Gr,Hn,Ia,Ea,Ba,$a,Nt.vertical?M.ai.horizontal:M.ai.horizontalOnly,mn?Nl:[Wt],Ll,El,La,Ka),mn)break}Nt.vertical&&(Wl+=Th(et,Bt,Nt.vertical,Gr,Hn,Ia,Ea,Ba,$a,M.ai.vertical,["vertical"],Ll,Jl,La,Ka));const Yl=Al?Al.boxStartIndex:et.collisionBoxArray.length,Ol=Al?Al.boxEndIndex:et.collisionBoxArray.length,jl=Zl?Zl.boxStartIndex:et.collisionBoxArray.length,Ul=Zl?Zl.boxEndIndex:et.collisionBoxArray.length,ql=Sl?Sl.boxStartIndex:et.collisionBoxArray.length,$l=Sl?Sl.boxEndIndex:et.collisionBoxArray.length,tc=Gl?Gl.boxStartIndex:et.collisionBoxArray.length,ec=Gl?Gl.boxEndIndex:et.collisionBoxArray.length;let dc=-1;const Y=(M,et)=>M&&M.circleDiameter?Math.max(M.circleDiameter,et):et;dc=Y(Al,dc),dc=Y(Zl,dc),dc=Y(Sl,dc),dc=Y(Gl,dc);const Ic=dc>-1?1:0;Ic&&(dc*=Oa/zu),et.glyphOffsetArray.length>=kc.MAX_GLYPHS&&j("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),void 0!==Ea.sortKey&&et.addToSortKeyRanges(et.symbolInstances.length,Ea.sortKey);const fc=Bh(Hn,Ea,Ka),[yc,vc]=function(et,Bt){const Wt=et.length,Nt=null==Bt?void 0:Bt.values;if((null==Nt?void 0:Nt.length)>0)for(let Bt=0;Bt=0?Ll.right:-1,Ll.center>=0?Ll.center:-1,Ll.left>=0?Ll.left:-1,Ll.vertical||-1,El,Jl,Dl,Yl,Ol,jl,Ul,ql,$l,tc,ec,uo,Vl,Wl,Rl,Tl,Ic,0,To,dc,yc,vc)}(et,Po,Hn,Wt,Nt,$t,Rl,et.layers[0],et.collisionBoxArray,Bt.index,Bt.sourceLayerIndex,et.index,za,[Da,Da,Da,Da],$a,so,Ea,Ka,Al,Ba,Bt,Gr,uo,Io,mn)};if("line"===Sl)for(const M of oh(Bt.geometry,0,0,To,To)){const Bt=Il(M,Tl),$t=dh(Bt,La,Oa,Wt.vertical||Ta,Nt,24,Fa,et.overscaling,To);for(const M of $t)Ta&&$h(et,Ta.text,Zl,M)||E(Bt,M)}else if("line-center"===Sl){for(const M of Bt.geometry)if(M.length>1){const et=Il(M,Tl),Bt=fh(et,Oa,Wt.vertical||Ta,Nt,24,Fa);Bt&&E(et,Bt)}}else if("Polygon"===Bt.type)for(const M of Le(Bt.geometry,0)){const et=Ah(M,16);E(Il(M[0],Tl,!0),new lh(et.x,et.y,0))}else if("LineString"===Bt.type)for(const M of Bt.geometry){const et=Il(M,Tl);E(et,new lh(et[0].x,et[0].y,0))}else if("Point"===Bt.type)for(const M of Bt.geometry)for(const et of M)E([et],new lh(et.x,et.y,0))}function Th(M,et,Bt,Wt,Nt,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia){const Ba=function(M,et,Bt,Wt,Nt,Gr,mn,Hn){const so=Wt.layout.get("text-rotate").evaluate(Gr,{})*Math.PI/180,uo=[];for(const M of et.positionedLines)for(const Wt of M.positionedGlyphs){if(!Wt.rect)continue;const Gr=Wt.rect||{};let Io=Hu+1,Po=!0,To=1,Eo=0;const Ia=(Nt||Hn)&&Wt.vertical,Ba=Wt.metrics.advance*Wt.scale/2;if(Hn&&et.verticalizable&&(Eo=M.lineOffset/2-(Wt.imageName?-(zu-Wt.metrics.width*Wt.scale)/2:(Wt.scale-1)*zu)),Wt.imageName){const M=mn[Wt.imageName];Po=M.sdf,To=M.pixelRatio,Io=Ku/To}const Ta=Nt?[Wt.x+Ba,Wt.y]:[0,0];let Va=Nt?[0,0]:[Wt.x+Ba+Bt[0],Wt.y+Bt[1]-Eo],za=[0,0];Ia&&(za=Va,Va=[0,0]);const Fa=Wt.metrics.isDoubleResolution?2:1,Ea=(Wt.metrics.left-Io)*Wt.scale-Ba+Va[0],La=(-Wt.metrics.top-Io)*Wt.scale+Va[1],Da=Ea+Gr.w/Fa*Wt.scale/To,Ka=La+Gr.h/Fa*Wt.scale/To,Oa=new $t(Ea,La),$a=new $t(Da,La),Al=new $t(Ea,Ka),Sl=new $t(Da,Ka);if(Ia){const M=new $t(-Ba,Ba-Uu),et=-Math.PI/2,Bt=zu/2-Ba,Nt=new $t(5-Uu-Bt,-(Wt.imageName?Bt:0)),Gr=new $t(...za);Oa._rotateAround(et,M)._add(Nt)._add(Gr),$a._rotateAround(et,M)._add(Nt)._add(Gr),Al._rotateAround(et,M)._add(Nt)._add(Gr),Sl._rotateAround(et,M)._add(Nt)._add(Gr)}if(so){const M=Math.sin(so),et=Math.cos(so),Bt=[et,-M,M,et];Oa._matMult(Bt),$a._matMult(Bt),Al._matMult(Bt),Sl._matMult(Bt)}const Zl=new $t(0,0),Gl=new $t(0,0);uo.push({tl:Oa,tr:$a,bl:Al,br:Sl,tex:Gr,writingMode:et.writingMode,glyphOffset:Ta,sectionIndex:Wt.sectionIndex,isSDF:Po,pixelOffsetTL:Zl,pixelOffsetBR:Gl,minFontScaleX:0,minFontScaleY:0})}return uo}(0,Bt,Hn,Nt,Gr,mn,Wt,M.allowVerticalPlacement),Ta=M.textSizeData;let Va=null;"source"===Ta.kind?(Va=[rd*Nt.layout.get("text-size").evaluate(mn,{})],Va[0]>nd&&j(`${M.layerIds[0]}: Value for "text-size" is >= ${id}. Reduce your "text-size".`)):"composite"===Ta.kind&&(Va=[rd*Eo.compositeTextSizes[0].evaluate(mn,{},Ia),rd*Eo.compositeTextSizes[1].evaluate(mn,{},Ia)],(Va[0]>nd||Va[1]>nd)&&j(`${M.layerIds[0]}: Value for "text-size" is >= ${id}. Reduce your "text-size".`)),M.addSymbols(M.text,Ba,Va,Hn,Gr,mn,uo,et,so.lineStartIndex,so.lineLength,To,Ia);for(const et of Io)Po[et]=M.text.placedSymbolArray.length-1;return 4*Ba.length}function Fh(M){for(const et in M)return M[et];return null}function $h(M,et,Bt,Wt){const Nt=M.compareText;if(et in Nt){const M=Nt[et];for(let et=M.length-1;et>=0;et--)if(Wt.dist(M[et])>4;if(1!==Wt)throw new Error(`Got v${Wt} data when expected v1.`);const Nt=Ad[15&Bt];if(!Nt)throw new Error("Unrecognized array type.");const[$t]=new Uint16Array(M,2,1),[Gr]=new Uint32Array(M,4,1);return new Dh(Gr,$t,Nt,M)}constructor(M,et=64,Bt=Float64Array,Wt){if(isNaN(M)||M<0)throw new Error(`Unpexpected numItems value: ${M}.`);this.numItems=+M,this.nodeSize=Math.min(Math.max(+et,2),65535),this.ArrayType=Bt,this.IndexArrayType=M<65536?Uint16Array:Uint32Array;const Nt=Ad.indexOf(this.ArrayType),$t=2*M*this.ArrayType.BYTES_PER_ELEMENT,Gr=M*this.IndexArrayType.BYTES_PER_ELEMENT,mn=(8-Gr%8)%8;if(Nt<0)throw new Error(`Unexpected typed array class: ${Bt}.`);Wt&&Wt instanceof ArrayBuffer?(this.data=Wt,this.ids=new this.IndexArrayType(this.data,8,M),this.coords=new this.ArrayType(this.data,8+Gr+mn,2*M),this._pos=2*M,this._finished=!0):(this.data=new ArrayBuffer(8+$t+Gr+mn),this.ids=new this.IndexArrayType(this.data,8,M),this.coords=new this.ArrayType(this.data,8+Gr+mn,2*M),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+Nt]),new Uint16Array(this.data,2,1)[0]=et,new Uint32Array(this.data,4,1)[0]=M)}add(M,et){const Bt=this._pos>>1;return this.ids[Bt]=Bt,this.coords[this._pos++]=M,this.coords[this._pos++]=et,Bt}finish(){const M=this._pos>>1;if(M!==this.numItems)throw new Error(`Added ${M} items when expected ${this.numItems}.`);return Oh(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(M,et,Bt,Wt){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:Nt,coords:$t,nodeSize:Gr}=this,mn=[0,Nt.length-1,0],Hn=[];for(;mn.length;){const so=mn.pop()||0,uo=mn.pop()||0,Io=mn.pop()||0;if(uo-Io<=Gr){for(let Gr=Io;Gr<=uo;Gr++){const mn=$t[2*Gr],so=$t[2*Gr+1];mn>=M&&mn<=Bt&&so>=et&&so<=Wt&&Hn.push(Nt[Gr])}continue}const Po=Io+uo>>1,To=$t[2*Po],Eo=$t[2*Po+1];To>=M&&To<=Bt&&Eo>=et&&Eo<=Wt&&Hn.push(Nt[Po]),(0===so?M<=To:et<=Eo)&&(mn.push(Io),mn.push(Po-1),mn.push(1-so)),(0===so?Bt>=To:Wt>=Eo)&&(mn.push(Po+1),mn.push(uo),mn.push(1-so))}return Hn}within(M,et,Bt){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:Wt,coords:Nt,nodeSize:$t}=this,Gr=[0,Wt.length-1,0],mn=[],Hn=Bt*Bt;for(;Gr.length;){const so=Gr.pop()||0,uo=Gr.pop()||0,Io=Gr.pop()||0;if(uo-Io<=$t){for(let Bt=Io;Bt<=uo;Bt++)Uh(Nt[2*Bt],Nt[2*Bt+1],M,et)<=Hn&&mn.push(Wt[Bt]);continue}const Po=Io+uo>>1,To=Nt[2*Po],Eo=Nt[2*Po+1];Uh(To,Eo,M,et)<=Hn&&mn.push(Wt[Po]),(0===so?M-Bt<=To:et-Bt<=Eo)&&(Gr.push(Io),Gr.push(Po-1),Gr.push(1-so)),(0===so?M+Bt>=To:et+Bt>=Eo)&&(Gr.push(Po+1),Gr.push(uo),Gr.push(1-so))}return mn}}function Oh(M,et,Bt,Wt,Nt,$t){if(Nt-Wt<=Bt)return;const Gr=Wt+Nt>>1;Rh(M,et,Gr,Wt,Nt,$t),Oh(M,et,Bt,Wt,Gr-1,1-$t),Oh(M,et,Bt,Gr+1,Nt,1-$t)}function Rh(M,et,Bt,Wt,Nt,$t){for(;Nt>Wt;){if(Nt-Wt>600){const Gr=Nt-Wt+1,mn=Bt-Wt+1,Hn=Math.log(Gr),so=.5*Math.exp(2*Hn/3),uo=.5*Math.sqrt(Hn*so*(Gr-so)/Gr)*(mn-Gr/2<0?-1:1);Rh(M,et,Bt,Math.max(Wt,Math.floor(Bt-mn*so/Gr+uo)),Math.min(Nt,Math.floor(Bt+(Gr-mn)*so/Gr+uo)),$t)}const Gr=et[2*Bt+$t];let mn=Wt,Hn=Nt;for(jh(M,et,Wt,Bt),et[2*Nt+$t]>Gr&&jh(M,et,Wt,Nt);mnGr;)Hn--}et[2*Wt+$t]===Gr?jh(M,et,Wt,Hn):(Hn++,jh(M,et,Hn,Nt)),Hn<=Bt&&(Wt=Hn+1),Bt<=Hn&&(Nt=Hn-1)}}function jh(M,et,Bt,Wt){Nh(M,Bt,Wt),Nh(et,2*Bt,2*Wt),Nh(et,2*Bt+1,2*Wt+1)}function Nh(M,et,Bt){const Wt=M[et];M[et]=M[Bt],M[Bt]=Wt}function Uh(M,et,Bt,Wt){const Nt=M-Bt,$t=et-Wt;return Nt*Nt+$t*$t}var _d;M.ce=void 0,(_d=M.ce||(M.ce={})).create="create",_d.load="load",_d.fullLoad="fullLoad";let bd=null,vd=[];const xd=1e3/60,wd="loadTime",Sd="fullLoadTime",kd={mark(M){performance.mark(M)},frame(M){const et=M;null!=bd&&vd.push(et-bd),bd=et},clearMetrics(){bd=null,vd=[],performance.clearMeasures(wd),performance.clearMeasures(Sd);for(const et in M.ce)performance.clearMarks(M.ce[et])},getPerformanceMetrics(){performance.measure(wd,M.ce.create,M.ce.load),performance.measure(Sd,M.ce.create,M.ce.fullLoad);const et=performance.getEntriesByName(wd)[0].duration,Bt=performance.getEntriesByName(Sd)[0].duration,Wt=vd.length,Nt=1/(vd.reduce(((M,et)=>M+et),0)/Wt/1e3),$t=vd.filter((M=>M>xd)).reduce(((M,et)=>M+(et-xd)/xd),0);return{loadTime:et,fullLoadTime:Bt,fps:Nt,percentDroppedFrames:$t/(Wt+$t)*100,totalFrames:Wt}}};M.$=St,M.A=Po,M.B=qh,M.C=function(M){if(null==Ta){const et=M.navigator?M.navigator.userAgent:null;Ta=!!M.safari||!(!et||!(/\b(iPad|iPhone|iPod)\b/.test(et)||et.match("Safari")&&!et.match("Chrome")))}return Ta},M.D=vs,M.E=ct,M.F=class{constructor(M,et){this.target=M,this.mapId=et,this.resolveRejects={},this.tasks={},this.taskQueue=[],this.abortControllers={},this.messageHandlers={},this.invoker=new Dc((()=>this.process())),this.subscription=function(M,et,Bt){return M.addEventListener(et,Bt,!1),{unsubscribe:()=>{M.removeEventListener(et,Bt,!1)}}}(this.target,"message",(M=>this.receive(M))),this.globalScope=U(self)?M:window}registerMessageHandler(M,et){this.messageHandlers[M]=et}sendAsync(M,et){return new Promise(((Bt,Wt)=>{const Nt=Math.round(1e18*Math.random()).toString(36).substring(0,10);this.resolveRejects[Nt]={resolve:Bt,reject:Wt},et&&et.signal.addEventListener("abort",(()=>{delete this.resolveRejects[Nt];const et={id:Nt,type:"",origin:location.origin,targetMapId:M.targetMapId,sourceMapId:this.mapId};this.target.postMessage(et)}),{once:!0});const $t=[],Gr=Object.assign(Object.assign({},M),{id:Nt,sourceMapId:this.mapId,origin:location.origin,data:Xi(M.data,$t)});this.target.postMessage(Gr,{transfer:$t})}))}receive(M){const et=M.data,Bt=et.id;if(!("file://"!==et.origin&&"file://"!==location.origin&&"resource://android"!==et.origin&&"resource://android"!==location.origin&&et.origin!==location.origin||et.targetMapId&&this.mapId!==et.targetMapId)){if(""===et.type){delete this.tasks[Bt];const M=this.abortControllers[Bt];return delete this.abortControllers[Bt],void(M&&M.abort())}if(U(self)||et.mustQueue)return this.tasks[Bt]=et,this.taskQueue.push(Bt),void this.invoker.trigger();this.processTask(Bt,et)}}process(){if(0===this.taskQueue.length)return;const M=this.taskQueue.shift(),et=this.tasks[M];delete this.tasks[M],this.taskQueue.length>0&&this.invoker.trigger(),et&&this.processTask(M,et)}processTask(M,et){return e(this,void 0,void 0,(function*(){if(""===et.type){const Bt=this.resolveRejects[M];if(delete this.resolveRejects[M],!Bt)return;return void(et.error?Bt.reject(Ki(et.error)):Bt.resolve(Ki(et.data)))}if(!this.messageHandlers[et.type])return void this.completeTask(M,new Error(`Could not find a registered handler for ${et.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));const Bt=Ki(et.data),Wt=new AbortController;this.abortControllers[M]=Wt;try{const Nt=yield this.messageHandlers[et.type](et.sourceMapId,Bt,Wt);this.completeTask(M,null,Nt)}catch(Bt){this.completeTask(M,Bt)}}))}completeTask(M,et,Bt){const Wt=[];delete this.abortControllers[M];const Nt={id:M,type:"",sourceMapId:this.mapId,origin:location.origin,error:et?Xi(et):null,data:Xi(Bt,Wt)};this.target.postMessage(Nt,{transfer:Wt})}remove(){this.invoker.remove(),this.subscription.unsubscribe()}},M.G=Da,M.H=function(){var M=new Po(16);return Po!=Float32Array&&(M[1]=0,M[2]=0,M[3]=0,M[4]=0,M[6]=0,M[7]=0,M[8]=0,M[9]=0,M[11]=0,M[12]=0,M[13]=0,M[14]=0),M[0]=1,M[5]=1,M[10]=1,M[15]=1,M},M.I=Zu,M.J=function(M,et,Bt){var Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia=Bt[0],Ba=Bt[1],Ta=Bt[2];return et===M?(M[12]=et[0]*Ia+et[4]*Ba+et[8]*Ta+et[12],M[13]=et[1]*Ia+et[5]*Ba+et[9]*Ta+et[13],M[14]=et[2]*Ia+et[6]*Ba+et[10]*Ta+et[14],M[15]=et[3]*Ia+et[7]*Ba+et[11]*Ta+et[15]):(Nt=et[1],$t=et[2],Gr=et[3],mn=et[4],Hn=et[5],so=et[6],uo=et[7],Io=et[8],Po=et[9],To=et[10],Eo=et[11],M[0]=Wt=et[0],M[1]=Nt,M[2]=$t,M[3]=Gr,M[4]=mn,M[5]=Hn,M[6]=so,M[7]=uo,M[8]=Io,M[9]=Po,M[10]=To,M[11]=Eo,M[12]=Wt*Ia+mn*Ba+Io*Ta+et[12],M[13]=Nt*Ia+Hn*Ba+Po*Ta+et[13],M[14]=$t*Ia+so*Ba+To*Ta+et[14],M[15]=Gr*Ia+uo*Ba+Eo*Ta+et[15]),M},M.K=function(M,et,Bt){var Wt=Bt[0],Nt=Bt[1],$t=Bt[2];return M[0]=et[0]*Wt,M[1]=et[1]*Wt,M[2]=et[2]*Wt,M[3]=et[3]*Wt,M[4]=et[4]*Nt,M[5]=et[5]*Nt,M[6]=et[6]*Nt,M[7]=et[7]*Nt,M[8]=et[8]*$t,M[9]=et[9]*$t,M[10]=et[10]*$t,M[11]=et[11]*$t,M[12]=et[12],M[13]=et[13],M[14]=et[14],M[15]=et[15],M},M.L=function(M,et,Bt){var Wt=et[0],Nt=et[1],$t=et[2],Gr=et[3],mn=et[4],Hn=et[5],so=et[6],uo=et[7],Io=et[8],Po=et[9],To=et[10],Eo=et[11],Ia=et[12],Ba=et[13],Ta=et[14],Va=et[15],za=Bt[0],Fa=Bt[1],Ea=Bt[2],La=Bt[3];return M[0]=za*Wt+Fa*mn+Ea*Io+La*Ia,M[1]=za*Nt+Fa*Hn+Ea*Po+La*Ba,M[2]=za*$t+Fa*so+Ea*To+La*Ta,M[3]=za*Gr+Fa*uo+Ea*Eo+La*Va,M[4]=(za=Bt[4])*Wt+(Fa=Bt[5])*mn+(Ea=Bt[6])*Io+(La=Bt[7])*Ia,M[5]=za*Nt+Fa*Hn+Ea*Po+La*Ba,M[6]=za*$t+Fa*so+Ea*To+La*Ta,M[7]=za*Gr+Fa*uo+Ea*Eo+La*Va,M[8]=(za=Bt[8])*Wt+(Fa=Bt[9])*mn+(Ea=Bt[10])*Io+(La=Bt[11])*Ia,M[9]=za*Nt+Fa*Hn+Ea*Po+La*Ba,M[10]=za*$t+Fa*so+Ea*To+La*Ta,M[11]=za*Gr+Fa*uo+Ea*Eo+La*Va,M[12]=(za=Bt[12])*Wt+(Fa=Bt[13])*mn+(Ea=Bt[14])*Io+(La=Bt[15])*Ia,M[13]=za*Nt+Fa*Hn+Ea*Po+La*Ba,M[14]=za*$t+Fa*so+Ea*To+La*Ta,M[15]=za*Gr+Fa*uo+Ea*Eo+La*Va,M},M.M=function(M,et){const Bt={};for(let Wt=0;Wt{const et=window.document.createElement("video");return et.muted=!0,new Promise((Bt=>{et.onloadstart=()=>{Bt(et)};for(const Bt of M){const M=window.document.createElement("source");st(Bt)||(et.crossOrigin="Anonymous"),M.src=Bt,et.appendChild(M)}}))},M.a1=function(){return Ia++},M.a2=ra,M.a3=kc,M.a4=Yn,M.a5=lo,M.a6=rh,M.a7=function(M){const et={};if(M.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,((M,Bt,Wt,Nt)=>{const $t=Wt||Nt;return et[Bt]=!$t||$t.toLowerCase(),""})),et["max-age"]){const M=parseInt(et["max-age"],10);isNaN(M)?delete et["max-age"]:et["max-age"]=M}return et},M.a8=function(M){return Math.log(M)/Math.LN2},M.a9=function(M){var et=M[0],Bt=M[1];return et*et+Bt*Bt},M.aA=Cs,M.aB=_l,M.aC=fa,M.aD=Pa,M.aE=ka,M.aF=85.051129,M.aG=function(M){return Math.pow(2,M)},M.aH=Gc,M.aI=T,M.aJ=Y,M.aK=Xc,M.aL=function(M,et,Bt){return M[0]=et[0]*Bt,M[1]=et[1]*Bt,M[2]=et[2]*Bt,M},M.aM=function(M,et,Bt){return M[0]=et[0]+Bt[0],M[1]=et[1]+Bt[1],M[2]=et[2]+Bt[2],M},M.aN=function(M){var et=new Po(3);return et[0]=M[0],et[1]=M[1],et[2]=M[2],et},M.aO=function(M,et,Bt){return M[0]=et[0]*Bt[0],M[1]=et[1]*Bt[1],M[2]=et[2]*Bt[2],M[3]=et[3]*Bt[3],M},M.aP=function(M,et,Bt){return M[0]=et[0]-Bt[0],M[1]=et[1]-Bt[1],M[2]=et[2]-Bt[2],M},M.aQ=function(M,et){var Bt=et[0],Wt=et[1],Nt=et[2],$t=Bt*Bt+Wt*Wt+Nt*Nt;return $t>0&&($t=1/Math.sqrt($t)),M[0]=et[0]*$t,M[1]=et[1]*$t,M[2]=et[2]*$t,M},M.aR=function(M,et,Bt){var Wt=et[0],Nt=et[1],$t=et[2],Gr=Bt[0],mn=Bt[1],Hn=Bt[2];return M[0]=Nt*Hn-$t*mn,M[1]=$t*Gr-Wt*Hn,M[2]=Wt*mn-Nt*Gr,M},M.aS=function(M,et){return M[0]*et[0]+M[1]*et[1]+M[2]*et[2]},M.aT=Jc,M.aU=Qc,M.aV=function(M,et,Bt,Wt,Nt){var $t,Gr=1/Math.tan(et/2);return M[0]=Gr/Bt,M[1]=0,M[2]=0,M[3]=0,M[4]=0,M[5]=Gr,M[6]=0,M[7]=0,M[8]=0,M[9]=0,M[11]=-1,M[12]=0,M[13]=0,M[15]=0,null!=Nt&&Nt!==1/0?(M[10]=(Nt+Wt)*($t=1/(Wt-Nt)),M[14]=2*Nt*Wt*$t):(M[10]=-1,M[14]=-2*Wt),M},M.aW=function(M){var et=new Po(16);return et[0]=M[0],et[1]=M[1],et[2]=M[2],et[3]=M[3],et[4]=M[4],et[5]=M[5],et[6]=M[6],et[7]=M[7],et[8]=M[8],et[9]=M[9],et[10]=M[10],et[11]=M[11],et[12]=M[12],et[13]=M[13],et[14]=M[14],et[15]=M[15],et},M.aX=function(M,et,Bt){var Wt=Math.sin(Bt),Nt=Math.cos(Bt),$t=et[0],Gr=et[1],mn=et[2],Hn=et[3],so=et[4],uo=et[5],Io=et[6],Po=et[7];return et!==M&&(M[8]=et[8],M[9]=et[9],M[10]=et[10],M[11]=et[11],M[12]=et[12],M[13]=et[13],M[14]=et[14],M[15]=et[15]),M[0]=$t*Nt+so*Wt,M[1]=Gr*Nt+uo*Wt,M[2]=mn*Nt+Io*Wt,M[3]=Hn*Nt+Po*Wt,M[4]=so*Nt-$t*Wt,M[5]=uo*Nt-Gr*Wt,M[6]=Io*Nt-mn*Wt,M[7]=Po*Nt-Hn*Wt,M},M.aY=function(M,et,Bt){var Wt=Math.sin(Bt),Nt=Math.cos(Bt),$t=et[4],Gr=et[5],mn=et[6],Hn=et[7],so=et[8],uo=et[9],Io=et[10],Po=et[11];return et!==M&&(M[0]=et[0],M[1]=et[1],M[2]=et[2],M[3]=et[3],M[12]=et[12],M[13]=et[13],M[14]=et[14],M[15]=et[15]),M[4]=$t*Nt+so*Wt,M[5]=Gr*Nt+uo*Wt,M[6]=mn*Nt+Io*Wt,M[7]=Hn*Nt+Po*Wt,M[8]=so*Nt-$t*Wt,M[9]=uo*Nt-Gr*Wt,M[10]=Io*Nt-mn*Wt,M[11]=Po*Nt-Hn*Wt,M},M.aZ=function(){const M=new Float32Array(16);return v(M),M},M.a_=function(){const M=new Float64Array(16);return v(M),M},M.aa=function(M){return M*Math.PI/180},M.ab=E,M.ac=function(M,et){const Bt=[];for(const Wt in M)Wt in et||Bt.push(Wt);return Bt},M.ad=A,M.ae=function(M){return Math.hypot(M[0],M[1])},M.af=function(M){return M[0]=0,M[1]=0,M},M.ag=function(M,et,Bt){return M[0]=et[0]*Bt,M[1]=et[1]*Bt,M},M.ah=function(M,et){let Bt=0,Wt=0;if("constant"===M.kind)Wt=M.layoutSize;else if("source"!==M.kind){const{interpolationType:Nt,minZoom:$t,maxZoom:Gr}=M,mn=Nt?E(sr.interpolationFactor(Nt,et,$t,Gr),0,1):0;"camera"===M.kind?Wt=zc.number(M.minSize,M.maxSize,mn):Bt=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Fa+Ta*Va)*Gl,M[11]=(Io*Fa-uo*La-To*Va)*Gl,M[12]=(mn*Oa-Gr*Al-Hn*Ka)*Gl,M[13]=(Bt*Al-Wt*Oa+Nt*Ka)*Gl,M[14]=(Ia*za-Eo*Ea-Ba*Va)*Gl,M[15]=(uo*Ea-Io*za+Po*Va)*Gl,M):null},M.ao=oh,M.ap=po,M.aq=v,M.ar=function(M){let et=1/0,Bt=1/0,Wt=-1/0,Nt=-1/0;for(const $t of M)et=Math.min(et,$t.x),Bt=Math.min(Bt,$t.y),Wt=Math.max(Wt,$t.x),Nt=Math.max(Nt,$t.y);return[et,Bt,Wt,Nt]},M.as=zu,M.at=I,M.au=function(M,et,Bt,Wt,Nt=!1){if(!Bt[0]&&!Bt[1])return[0,0];const $t=Nt?"map"===Wt?-M.bearingInRadians:0:"viewport"===Wt?M.bearingInRadians:0;if($t){const M=Math.sin($t),et=Math.cos($t);Bt=[Bt[0]*et-Bt[1]*M,Bt[0]*M+Bt[1]*et]}return[Nt?Bt[0]:I(et,Bt[0],M.zoom),Nt?Bt[1]:I(et,Bt[1],M.zoom)]},M.aw=gc,M.ax=Vh,M.ay=lc,M.az=Dh,M.b=G,M.b$=M=>"line"===M.type,M.b0=function(M,et,Bt){const Wt=new Float64Array(4);return function(M,et,Bt,Wt){var Nt=.5*Math.PI/180;et*=Nt,Bt*=Nt,Wt*=Nt;var $t=Math.sin(et),Gr=Math.cos(et),mn=Math.sin(Bt),Hn=Math.cos(Bt),so=Math.sin(Wt),uo=Math.cos(Wt);M[0]=$t*Hn*uo-Gr*mn*so,M[1]=Gr*mn*uo+$t*Hn*so,M[2]=Gr*Hn*so-$t*mn*uo,M[3]=Gr*Hn*uo+$t*mn*so}(Wt,M,et-90,Bt),Wt},M.b1=function(M,et,Bt,Wt){var Nt,$t,Gr,mn,Hn,so=et[0],uo=et[1],Po=et[2],To=et[3],Eo=Bt[0],Ia=Bt[1],Ba=Bt[2],Ta=Bt[3];return($t=so*Eo+uo*Ia+Po*Ba+To*Ta)<0&&($t=-$t,Eo=-Eo,Ia=-Ia,Ba=-Ba,Ta=-Ta),1-$t>Io?(Nt=Math.acos($t),Gr=Math.sin(Nt),mn=Math.sin((1-Wt)*Nt)/Gr,Hn=Math.sin(Wt*Nt)/Gr):(mn=1-Wt,Hn=Wt),M[0]=mn*so+Hn*Eo,M[1]=mn*uo+Hn*Ia,M[2]=mn*Po+Hn*Ba,M[3]=mn*To+Hn*Ta,M},M.b2=function(M){const et=new Float64Array(9);var Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba,Ta,Va,za;Io=(Nt=(Wt=M)[0])*(Hn=Nt+Nt),Po=($t=Wt[1])*Hn,Eo=(Gr=Wt[2])*Hn,Ia=Gr*(so=$t+$t),Ta=(mn=Wt[3])*Hn,Va=mn*so,za=mn*(uo=Gr+Gr),(Bt=et)[0]=1-(To=$t*so)-(Ba=Gr*uo),Bt[3]=Po-za,Bt[6]=Eo+Va,Bt[1]=Po+za,Bt[4]=1-Io-Ba,Bt[7]=Ia-Ta,Bt[2]=Eo-Va,Bt[5]=Ia+Ta,Bt[8]=1-Io-To;const Fa=Y(-Math.asin(E(et[2],-1,1)));let Ea,La;return Math.hypot(et[5],et[8])<.001?(Ea=0,La=-Y(Math.atan2(et[3],et[4]))):(Ea=Y(0===et[5]&&0===et[8]?0:Math.atan2(et[5],et[8])),La=Y(0===et[1]&&0===et[0]?0:Math.atan2(et[1],et[0]))),{roll:Ea,pitch:Fa+90,bearing:La}},M.b3=function(M,et){return M.roll==et.roll&&M.pitch==et.pitch&&M.bearing==et.bearing},M.b4=ye,M.b5=Ga,M.b6=Vg,M.b7=Wg,M.b8=wl,M.b9=P,M.bA=L,M.bB=D,M.bC=class extends qa{constructor(M,et){super(M,et),this.current=0}set(M){this.current!==M&&(this.current=M,this.gl.uniform1i(this.location,M))}},M.bD=class extends qa{constructor(M,et){super(M,et),this.current=_g}set(M){if(M[12]!==this.current[12]||M[0]!==this.current[0])return this.current=M,void this.gl.uniformMatrix4fv(this.location,!1,M);for(let et=1;et<16;et++)if(M[et]!==this.current[et]){this.current=M,this.gl.uniformMatrix4fv(this.location,!1,M);break}}},M.bE=Za,M.bF=Xa,M.bG=class extends qa{constructor(M,et){super(M,et),this.current=[0,0,0]}set(M){M[0]===this.current[0]&&M[1]===this.current[1]&&M[2]===this.current[2]||(this.current=M,this.gl.uniform3f(this.location,M[0],M[1],M[2]))}},M.bH=class extends qa{constructor(M,et){super(M,et),this.current=[0,0]}set(M){M[0]===this.current[0]&&M[1]===this.current[1]||(this.current=M,this.gl.uniform2f(this.location,M[0],M[1]))}},M.bI=x,M.bJ=function(M,et){var Bt=Math.sin(et),Wt=Math.cos(et);return M[0]=Wt,M[1]=Bt,M[2]=0,M[3]=-Bt,M[4]=Wt,M[5]=0,M[6]=0,M[7]=0,M[8]=1,M},M.bK=function(M,et,Bt){var Wt=et[0],Nt=et[1],$t=et[2];return M[0]=Wt*Bt[0]+Nt*Bt[3]+$t*Bt[6],M[1]=Wt*Bt[1]+Nt*Bt[4]+$t*Bt[7],M[2]=Wt*Bt[2]+Nt*Bt[5]+$t*Bt[8],M},M.bL=function(M,et,Bt,Wt,Nt,$t,Gr){var mn=1/(et-Bt),Hn=1/(Wt-Nt),so=1/($t-Gr);return M[0]=-2*mn,M[1]=0,M[2]=0,M[3]=0,M[4]=0,M[5]=-2*Hn,M[6]=0,M[7]=0,M[8]=0,M[9]=0,M[10]=2*so,M[11]=0,M[12]=(et+Bt)*mn,M[13]=(Nt+Wt)*Hn,M[14]=(Gr+$t)*so,M[15]=1,M},M.bM=class extends qs{},M.bN=Bu,M.bO=class extends Zs{},M.bP=Gg,M.bQ=function(M){return M<=1?1:Math.pow(2,Math.ceil(Math.log(M)/Math.LN2))},M.bR=Ro,M.bS=function(M,et,Bt){var Wt=et[0],Nt=et[1],$t=et[2],Gr=Bt[3]*Wt+Bt[7]*Nt+Bt[11]*$t+Bt[15];return M[0]=(Bt[0]*Wt+Bt[4]*Nt+Bt[8]*$t+Bt[12])/(Gr=Gr||1),M[1]=(Bt[1]*Wt+Bt[5]*Nt+Bt[9]*$t+Bt[13])/Gr,M[2]=(Bt[2]*Wt+Bt[6]*Nt+Bt[10]*$t+Bt[14])/Gr,M},M.bT=class extends Ts{},M.bU=class extends Qs{},M.bV=function(M,et){return M[0]===et[0]&&M[1]===et[1]&&M[2]===et[2]&&M[3]===et[3]&&M[4]===et[4]&&M[5]===et[5]&&M[6]===et[6]&&M[7]===et[7]&&M[8]===et[8]&&M[9]===et[9]&&M[10]===et[10]&&M[11]===et[11]&&M[12]===et[12]&&M[13]===et[13]&&M[14]===et[14]&&M[15]===et[15]},M.bW=function(M,et){var Bt=M[0],Wt=M[1],Nt=M[2],$t=M[3],Gr=M[4],mn=M[5],Hn=M[6],so=M[7],uo=M[8],Po=M[9],To=M[10],Eo=M[11],Ia=M[12],Ba=M[13],Ta=M[14],Va=M[15],za=et[0],Fa=et[1],Ea=et[2],La=et[3],Da=et[4],Ka=et[5],Oa=et[6],$a=et[7],Al=et[8],Sl=et[9],Zl=et[10],Gl=et[11],Rl=et[12],Tl=et[13],Vl=et[14],Wl=et[15];return Math.abs(Bt-za)<=Io*Math.max(1,Math.abs(Bt),Math.abs(za))&&Math.abs(Wt-Fa)<=Io*Math.max(1,Math.abs(Wt),Math.abs(Fa))&&Math.abs(Nt-Ea)<=Io*Math.max(1,Math.abs(Nt),Math.abs(Ea))&&Math.abs($t-La)<=Io*Math.max(1,Math.abs($t),Math.abs(La))&&Math.abs(Gr-Da)<=Io*Math.max(1,Math.abs(Gr),Math.abs(Da))&&Math.abs(mn-Ka)<=Io*Math.max(1,Math.abs(mn),Math.abs(Ka))&&Math.abs(Hn-Oa)<=Io*Math.max(1,Math.abs(Hn),Math.abs(Oa))&&Math.abs(so-$a)<=Io*Math.max(1,Math.abs(so),Math.abs($a))&&Math.abs(uo-Al)<=Io*Math.max(1,Math.abs(uo),Math.abs(Al))&&Math.abs(Po-Sl)<=Io*Math.max(1,Math.abs(Po),Math.abs(Sl))&&Math.abs(To-Zl)<=Io*Math.max(1,Math.abs(To),Math.abs(Zl))&&Math.abs(Eo-Gl)<=Io*Math.max(1,Math.abs(Eo),Math.abs(Gl))&&Math.abs(Ia-Rl)<=Io*Math.max(1,Math.abs(Ia),Math.abs(Rl))&&Math.abs(Ba-Tl)<=Io*Math.max(1,Math.abs(Ba),Math.abs(Tl))&&Math.abs(Ta-Vl)<=Io*Math.max(1,Math.abs(Ta),Math.abs(Vl))&&Math.abs(Va-Wl)<=Io*Math.max(1,Math.abs(Va),Math.abs(Wl))},M.bX=function(M,et){return M[0]=et[0],M[1]=et[1],M[2]=et[2],M[3]=et[3],M[4]=et[4],M[5]=et[5],M[6]=et[6],M[7]=et[7],M[8]=et[8],M[9]=et[9],M[10]=et[10],M[11]=et[11],M[12]=et[12],M[13]=et[13],M[14]=et[14],M[15]=et[15],M},M.bY=M=>"symbol"===M.type,M.bZ=M=>"circle"===M.type,M.b_=M=>"heatmap"===M.type,M.ba=C,M.bb=Ae,M.bc=function(M,et,Bt,Wt,Nt){return P(Wt,Nt,E((M-et)/(Bt-et),0,1))},M.bd=z,M.be=function(){return new Float64Array(4)},M.bf=function(){return new Float64Array(3)},M.bg=function(M,et,Bt,Wt){var Nt=[],$t=[];return Nt[0]=et[0]-Bt[0],Nt[1]=et[1]-Bt[1],Nt[2]=et[2]-Bt[2],$t[0]=Nt[0]*Math.cos(Wt)-Nt[1]*Math.sin(Wt),$t[1]=Nt[0]*Math.sin(Wt)+Nt[1]*Math.cos(Wt),$t[2]=Nt[2],M[0]=$t[0]+Bt[0],M[1]=$t[1]+Bt[1],M[2]=$t[2]+Bt[2],M},M.bh=function(M,et,Bt,Wt){var Nt=[],$t=[];return Nt[0]=et[0]-Bt[0],Nt[1]=et[1]-Bt[1],Nt[2]=et[2]-Bt[2],$t[0]=Nt[0],$t[1]=Nt[1]*Math.cos(Wt)-Nt[2]*Math.sin(Wt),$t[2]=Nt[1]*Math.sin(Wt)+Nt[2]*Math.cos(Wt),M[0]=$t[0]+Bt[0],M[1]=$t[1]+Bt[1],M[2]=$t[2]+Bt[2],M},M.bi=function(M,et,Bt,Wt){var Nt=[],$t=[];return Nt[0]=et[0]-Bt[0],Nt[1]=et[1]-Bt[1],Nt[2]=et[2]-Bt[2],$t[0]=Nt[2]*Math.sin(Wt)+Nt[0]*Math.cos(Wt),$t[1]=Nt[1],$t[2]=Nt[2]*Math.cos(Wt)-Nt[0]*Math.sin(Wt),M[0]=$t[0]+Bt[0],M[1]=$t[1]+Bt[1],M[2]=$t[2]+Bt[2],M},M.bj=function(M,et,Bt){var Wt=Math.sin(Bt),Nt=Math.cos(Bt),$t=et[0],Gr=et[1],mn=et[2],Hn=et[3],so=et[8],uo=et[9],Io=et[10],Po=et[11];return et!==M&&(M[4]=et[4],M[5]=et[5],M[6]=et[6],M[7]=et[7],M[12]=et[12],M[13]=et[13],M[14]=et[14],M[15]=et[15]),M[0]=$t*Nt-so*Wt,M[1]=Gr*Nt-uo*Wt,M[2]=mn*Nt-Io*Wt,M[3]=Hn*Nt-Po*Wt,M[8]=$t*Wt+so*Nt,M[9]=Gr*Wt+uo*Nt,M[10]=mn*Wt+Io*Nt,M[11]=Hn*Wt+Po*Nt,M},M.bk=function(M,et){const Bt=z(M,360),Wt=z(et,360),Nt=Wt-Bt,$t=Wt>Bt?Nt-360:Nt+360;return Math.abs(Nt)0?Gr:-Gr},M.bn=function(M,et){return M[0]*et[0]+M[1]*et[1]+M[2]*et[2]+M[3]},M.bo=pd,M.bp=function(M,et){const Bt=z(M,2*Math.PI),Wt=z(et,2*Math.PI);return Math.min(Math.abs(Bt-Wt),Math.abs(Bt-Wt+2*Math.PI),Math.abs(Bt-Wt-2*Math.PI))},M.bq=function(M){return Math.hypot(M[0],M[1],M[2])},M.br=function(){const M={},et=Ka.$version;for(const Bt in Ka.$root){const Wt=Ka.$root[Bt];if(Wt.required){let Nt=null;Nt="version"===Bt?et:"array"===Wt.type?[]:{},null!=Nt&&(M[Bt]=Nt)}}return M},M.bs=Hi,M.bt=nt,M.bu=function(M){M=M.slice();const et=Object.create(null);for(let Bt=0;Bt{"source"in M&&Wt[M.source]?Bt.push({command:"removeLayer",args:[M.id]}):$t.push(M)})),Bt=Bt.concat(Nt),function(M,et,Bt){et=et||[];const Wt=(M=M||[]).map(wt),Nt=et.map(wt),$t=M.reduce(_t,{}),Gr=et.reduce(_t,{}),mn=Wt.slice(),Hn=Object.create(null);let so,uo,Io,Po,To;for(let M=0,et=0;M"fill"===M.type,M.c1=M=>"fill-extrusion"===M.type,M.c2=M=>"hillshade"===M.type,M.c3=M=>"raster"===M.type,M.c4=M=>"background"===M.type,M.c5=M=>"custom"===M.type,M.c6=B,M.c7=function(M,et,Bt){const Wt=k(et.x-Bt.x,et.y-Bt.y),Nt=k(M.x-Bt.x,M.y-Bt.y);var $t,Gr;return Y(Math.atan2(Wt[0]*Nt[1]-Wt[1]*Nt[0],($t=Wt)[0]*(Gr=Nt)[0]+$t[1]*Gr[1]))},M.c8=Eo,M.c9=function(M,et,Bt){var Wt=et[0],Nt=et[1];return M[0]=Bt[0]*Wt+Bt[4]*Nt+Bt[12],M[1]=Bt[1]*Wt+Bt[5]*Nt+Bt[13],M},M.cA=Lu,M.cB=Nn,M.cC=ag,M.ca=function(M,et){const{x:Bt,y:Wt}=Kc.fromLngLat(et);return!(M<0||M>25||Wt<0||Wt>=1||Bt<0||Bt>=1)},M.cb=function(M,et){return M[0]=et[0],M[1]=0,M[2]=0,M[3]=0,M[4]=0,M[5]=et[1],M[6]=0,M[7]=0,M[8]=0,M[9]=0,M[10]=et[2],M[11]=0,M[12]=0,M[13]=0,M[14]=0,M[15]=1,M},M.cc=class extends Es{},M.cd=kd,M.cf=function(M){return M.message===Ea},M.cg=rt,M.ch=function(M,et){La.REGISTERED_PROTOCOLS[M]=et},M.ci=function(M){delete La.REGISTERED_PROTOCOLS[M]},M.cj=function(M,et){const Bt={};for(let Wt=0;WtM*zu))}let za=mn?"center":Wt.get("text-justify").evaluate(Nt,{},et.canonical);const Fa="point"===Wt.get("symbol-placement")?Wt.get("text-max-width").evaluate(Nt,{},et.canonical)*zu:1/0,w=()=>{et.bucket.allowVerticalPlacement&&Ji($t)&&(Eo.vertical=Wu(Ia,et.glyphMap,et.glyphPositions,et.imagePositions,uo,Fa,Gr,Ba,"left",To,Ta,M.ai.vertical,!0,Po,Io))};if(!mn&&Va){const Bt=new Set;if("auto"===za)for(let M=0;Me(void 0,void 0,void 0,(function*(){if(0===M.byteLength)return createImageBitmap(new ImageData(1,1));const et=new Blob([new Uint8Array(M)],{type:"image/png"});try{return createImageBitmap(et)}catch(M){throw new Error(`Could not load image because of ${M.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)}})),M.e=F,M.f=M=>new Promise(((et,Bt)=>{const Wt=new Image;Wt.onload=()=>{et(Wt),URL.revokeObjectURL(Wt.src),Wt.onload=null,window.requestAnimationFrame((()=>{Wt.src=Va}))},Wt.onerror=()=>Bt(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));const Nt=new Blob([new Uint8Array(M)],{type:"image/png"});Wt.src=M.byteLength?URL.createObjectURL(Nt):Va})),M.g=tt,M.h=(M,et)=>it(F(M,{type:"json"}),et),M.i=U,M.j=ut,M.k=lt,M.l=(M,et)=>it(F(M,{type:"arrayBuffer"}),et),M.m=it,M.n=function(M){return new Eu(M).readFields(Ru,[])},M.o=Do,M.p=qu,M.q=As,M.r=Qh,M.s=st,M.t=Ri,M.u=Yh,M.v=Ka,M.w=j,M.x=function([M,et,Bt]){return et+=90,et*=Math.PI/180,Bt*=Math.PI/180,{x:M*Math.cos(et)*Math.sin(Bt),y:M*Math.sin(et)*Math.sin(Bt),z:M*Math.cos(Bt)}},M.y=zc,M.z=cs})),define("worker",["./shared"],(function(M){class t{constructor(M){this.keyCache={},M&&this.replace(M)}replace(M){this._layerConfigs={},this._layers={},this.update(M,[])}update(et,Bt){for(const Bt of et){this._layerConfigs[Bt.id]=Bt;const et=this._layers[Bt.id]=M.bv(Bt);et._featureFilter=M.a4(et.filter),this.keyCache[Bt.id]&&delete this.keyCache[Bt.id]}for(const M of Bt)delete this.keyCache[M],delete this._layerConfigs[M],delete this._layers[M];this.familiesBySource={};const Wt=M.cj(Object.values(this._layerConfigs),this.keyCache);for(const M of Wt){const et=M.map((M=>this._layers[M.id])),Bt=et[0];if("none"===Bt.visibility)continue;const Wt=Bt.source||"";let Nt=this.familiesBySource[Wt];Nt||(Nt=this.familiesBySource[Wt]={});const $t=Bt.sourceLayer||"_geojsonTileLayer";let Gr=Nt[$t];Gr||(Gr=Nt[$t]=[]),Gr.push(et)}}}class o{constructor(et){const Bt={},Wt=[];for(const M in et){const Nt=et[M],$t=Bt[M]={};for(const M in Nt){const et=Nt[+M];if(!et||0===et.bitmap.width||0===et.bitmap.height)continue;const Bt={x:0,y:0,w:et.bitmap.width+2,h:et.bitmap.height+2};Wt.push(Bt),$t[M]={rect:Bt,metrics:et.metrics}}}const{w:Nt,h:$t}=M.p(Wt),Gr=new M.o({width:Nt||1,height:$t||1});for(const Wt in et){const Nt=et[Wt];for(const et in Nt){const $t=Nt[+et];if(!$t||0===$t.bitmap.width||0===$t.bitmap.height)continue;const mn=Bt[Wt][et].rect;M.o.copy($t.bitmap,Gr,{x:0,y:0},{x:mn.x+1,y:mn.y+1},$t.bitmap)}}this.image=Gr,this.positions=Bt}}M.ck("GlyphAtlas",o);class i{constructor(et){this.tileID=new M.S(et.tileID.overscaledZ,et.tileID.wrap,et.tileID.canonical.z,et.tileID.canonical.x,et.tileID.canonical.y),this.uid=et.uid,this.zoom=et.zoom,this.pixelRatio=et.pixelRatio,this.tileSize=et.tileSize,this.source=et.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=et.showCollisionBoxes,this.collectResourceTiming=!!et.collectResourceTiming,this.returnDependencies=!!et.returnDependencies,this.promoteId=et.promoteId,this.inFlightDependencies=[]}parse(et,Bt,Wt,Nt,$t){return M._(this,void 0,void 0,(function*(){this.status="parsing",this.data=et,this.collisionBoxArray=new M.a2;const Gr=new M.cl(Object.keys(et.layers).sort()),mn=new M.cm(this.tileID,this.promoteId);mn.bucketLayerIDs=[];const Hn={},so={featureIndex:mn,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:Wt,subdivisionGranularity:$t},uo=Bt.familiesBySource[this.source];for(const Bt in uo){const Nt=et.layers[Bt];if(!Nt)continue;1===Nt.version&&M.w(`Vector tile source "${this.source}" layer "${Bt}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const $t=Gr.encode(Bt),Io=[];for(let M=0;M=Bt.maxzoom||"none"!==Bt.visibility&&(r(et,this.zoom,Wt),(Hn[Bt.id]=Bt.createBucket({index:mn.bucketLayerIDs.length,layers:et,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:$t,sourceID:this.source})).populate(Io,so,this.tileID.canonical),mn.bucketLayerIDs.push(et.map((M=>M.id))))}}const Io=M.bA(so.glyphDependencies,(M=>Object.keys(M).map(Number)));this.inFlightDependencies.forEach((M=>null==M?void 0:M.abort())),this.inFlightDependencies=[];let Po=Promise.resolve({});if(Object.keys(Io).length){const M=new AbortController;this.inFlightDependencies.push(M),Po=Nt.sendAsync({type:"GG",data:{stacks:Io,source:this.source,tileID:this.tileID,type:"glyphs"}},M)}const To=Object.keys(so.iconDependencies);let Eo=Promise.resolve({});if(To.length){const M=new AbortController;this.inFlightDependencies.push(M),Eo=Nt.sendAsync({type:"GI",data:{icons:To,source:this.source,tileID:this.tileID,type:"icons"}},M)}const Ia=Object.keys(so.patternDependencies);let Ba=Promise.resolve({});if(Ia.length){const M=new AbortController;this.inFlightDependencies.push(M),Ba=Nt.sendAsync({type:"GI",data:{icons:Ia,source:this.source,tileID:this.tileID,type:"patterns"}},M)}const[Ta,Va,za]=yield Promise.all([Po,Eo,Ba]),Fa=new o(Ta),Ea=new M.cn(Va,za);for(const et in Hn){const Bt=Hn[et];Bt instanceof M.a3?(r(Bt.layers,this.zoom,Wt),M.co({bucket:Bt,glyphMap:Ta,glyphPositions:Fa.positions,imageMap:Va,imagePositions:Ea.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical,subdivisionGranularity:so.subdivisionGranularity})):Bt.hasPattern&&(Bt instanceof M.cp||Bt instanceof M.cq||Bt instanceof M.cr)&&(r(Bt.layers,this.zoom,Wt),Bt.addFeatures(so,this.tileID.canonical,Ea.patternPositions))}return this.status="done",{buckets:Object.values(Hn).filter((M=>!M.isEmpty())),featureIndex:mn,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:Fa.image,imageAtlas:Ea,glyphMap:this.returnDependencies?Ta:null,iconMap:this.returnDependencies?Va:null,glyphPositions:this.returnDependencies?Fa.positions:null}}))}}function r(et,Bt,Wt){const Nt=new M.z(Bt);for(const M of et)M.recalculate(Nt,Wt)}class s{constructor(M,et,Bt){this.actor=M,this.layerIndex=et,this.availableImages=Bt,this.fetching={},this.loading={},this.loaded={}}loadVectorTile(et,Bt){return M._(this,void 0,void 0,(function*(){const Wt=yield M.l(et.request,Bt);try{return{vectorTile:new M.cs.VectorTile(new M.ct(Wt.data)),rawData:Wt.data,cacheControl:Wt.cacheControl,expires:Wt.expires}}catch(M){const Bt=new Uint8Array(Wt.data);let Nt=`Unable to parse the tile at ${et.request.url}, `;throw Nt+=31===Bt[0]&&139===Bt[1]?"please make sure the data is not gzipped and that you have configured the relevant header in the server":`got error: ${M.message}`,new Error(Nt)}}))}loadTile(et){return M._(this,void 0,void 0,(function*(){const Bt=et.uid,Wt=!!(et&&et.request&&et.request.collectResourceTiming)&&new M.cu(et.request),Nt=new i(et);this.loading[Bt]=Nt;const $t=new AbortController;Nt.abort=$t;try{const Gr=yield this.loadVectorTile(et,$t);if(delete this.loading[Bt],!Gr)return null;const mn=Gr.rawData,Hn={};Gr.expires&&(Hn.expires=Gr.expires),Gr.cacheControl&&(Hn.cacheControl=Gr.cacheControl);const so={};if(Wt){const M=Wt.finish();M&&(so.resourceTiming=JSON.parse(JSON.stringify(M)))}Nt.vectorTile=Gr.vectorTile;const uo=Nt.parse(Gr.vectorTile,this.layerIndex,this.availableImages,this.actor,et.subdivisionGranularity);this.loaded[Bt]=Nt,this.fetching[Bt]={rawTileData:mn,cacheControl:Hn,resourceTiming:so};try{const et=yield uo;return M.e({rawTileData:mn.slice(0)},et,Hn,so)}finally{delete this.fetching[Bt]}}catch(M){throw delete this.loading[Bt],Nt.status="done",this.loaded[Bt]=Nt,M}}))}reloadTile(et){return M._(this,void 0,void 0,(function*(){const Bt=et.uid;if(!this.loaded||!this.loaded[Bt])throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");const Wt=this.loaded[Bt];if(Wt.showCollisionBoxes=et.showCollisionBoxes,"parsing"===Wt.status){const Nt=yield Wt.parse(Wt.vectorTile,this.layerIndex,this.availableImages,this.actor,et.subdivisionGranularity);let $t;if(this.fetching[Bt]){const{rawTileData:et,cacheControl:Wt,resourceTiming:Gr}=this.fetching[Bt];delete this.fetching[Bt],$t=M.e({rawTileData:et.slice(0)},Nt,Wt,Gr)}else $t=Nt;return $t}if("done"===Wt.status&&Wt.vectorTile)return Wt.parse(Wt.vectorTile,this.layerIndex,this.availableImages,this.actor,et.subdivisionGranularity)}))}abortTile(et){return M._(this,void 0,void 0,(function*(){const M=this.loading,Bt=et.uid;M&&M[Bt]&&M[Bt].abort&&(M[Bt].abort.abort(),delete M[Bt])}))}removeTile(et){return M._(this,void 0,void 0,(function*(){this.loaded&&this.loaded[et.uid]&&delete this.loaded[et.uid]}))}}class n{constructor(){this.loaded={}}loadTile(et){return M._(this,void 0,void 0,(function*(){const{uid:Bt,encoding:Wt,rawImageData:Nt,redFactor:$t,greenFactor:Gr,blueFactor:mn,baseShift:Hn}=et,so=Nt.width+2,uo=Nt.height+2,Io=M.b(Nt)?new M.R({width:so,height:uo},yield M.cv(Nt,-1,-1,so,uo)):Nt,Po=new M.cw(Bt,Io,Wt,$t,Gr,mn,Hn);return this.loaded=this.loaded||{},this.loaded[Bt]=Po,Po}))}removeTile(M){const et=this.loaded,Bt=M.uid;et&&et[Bt]&&delete et[Bt]}}var et,Bt,Wt=function(){if(Bt)return et;function e(M,et){if(0!==M.length){t(M[0],et);for(var Bt=1;Bt=Math.abs(mn)?Bt-Hn+mn:mn-Hn+Bt,Bt=Hn}Bt+Wt>=0!=!!et&&M.reverse()}return Bt=1,et=function t(M,et){var Bt,Wt=M&&M.type;if("FeatureCollection"===Wt)for(Bt=0;Bt>31}function c(M,et){for(var Bt=M.loadGeometry(),Wt=M.type,Nt=0,$t=0,Gr=Bt.length,mn=0;mnM},To=Math.fround||(Eo=new Float32Array(1),M=>(Eo[0]=+M,Eo[0]));var Eo;const Ia=3,Ba=5,Ta=6;class P{constructor(M){this.options=Object.assign(Object.create(Po),M),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(M){const{log:et,minZoom:Bt,maxZoom:Wt}=this.options;et&&console.time("total time");const Nt=`prepare ${M.length} points`;et&&console.time(Nt),this.points=M;const $t=[];for(let et=0;et=Bt;M--){const Bt=+Date.now();Gr=this.trees[M]=this._createTree(this._cluster(Gr,M)),et&&console.log("z%d: %d clusters in %dms",M,Gr.numItems,+Date.now()-Bt)}return et&&console.timeEnd("total time"),this}getClusters(M,et){let Bt=((M[0]+180)%360+360)%360-180;const Wt=Math.max(-90,Math.min(90,M[1]));let Nt=180===M[2]?180:((M[2]+180)%360+360)%360-180;const $t=Math.max(-90,Math.min(90,M[3]));if(M[2]-M[0]>=360)Bt=-180,Nt=180;else if(Bt>Nt){const M=this.getClusters([Bt,Wt,180,$t],et),Gr=this.getClusters([-180,Wt,Nt,$t],et);return M.concat(Gr)}const Gr=this.trees[this._limitZoom(et)],mn=Gr.range(D(Bt),C($t),D(Nt),C(Wt)),Hn=Gr.data,so=[];for(const M of mn){const et=this.stride*M;so.push(Hn[et+Ba]>1?k(Hn,et,this.clusterProps):this.points[Hn[et+Ia]])}return so}getChildren(M){const et=this._getOriginId(M),Bt=this._getOriginZoom(M),Wt="No cluster with the specified id.",Nt=this.trees[Bt];if(!Nt)throw new Error(Wt);const $t=Nt.data;if(et*this.stride>=$t.length)throw new Error(Wt);const Gr=this.options.radius/(this.options.extent*Math.pow(2,Bt-1)),mn=Nt.within($t[et*this.stride],$t[et*this.stride+1],Gr),Hn=[];for(const et of mn){const Bt=et*this.stride;$t[Bt+4]===M&&Hn.push($t[Bt+Ba]>1?k($t,Bt,this.clusterProps):this.points[$t[Bt+Ia]])}if(0===Hn.length)throw new Error(Wt);return Hn}getLeaves(M,et,Bt){const Wt=[];return this._appendLeaves(Wt,M,et=et||10,Bt=Bt||0,0),Wt}getTile(M,et,Bt){const Wt=this.trees[this._limitZoom(M)],Nt=Math.pow(2,M),{extent:$t,radius:Gr}=this.options,mn=Gr/$t,Hn=(Bt-mn)/Nt,so=(Bt+1+mn)/Nt,uo={features:[]};return this._addTileFeatures(Wt.range((et-mn)/Nt,Hn,(et+1+mn)/Nt,so),Wt.data,et,Bt,Nt,uo),0===et&&this._addTileFeatures(Wt.range(1-mn/Nt,Hn,1,so),Wt.data,Nt,Bt,Nt,uo),et===Nt-1&&this._addTileFeatures(Wt.range(0,Hn,mn/Nt,so),Wt.data,-1,Bt,Nt,uo),uo.features.length?uo:null}getClusterExpansionZoom(M){let et=this._getOriginZoom(M)-1;for(;et<=this.options.maxZoom;){const Bt=this.getChildren(M);if(et++,1!==Bt.length)break;M=Bt[0].properties.cluster_id}return et}_appendLeaves(M,et,Bt,Wt,Nt){const $t=this.getChildren(et);for(const et of $t){const $t=et.properties;if($t&&$t.cluster?Nt+$t.point_count<=Wt?Nt+=$t.point_count:Nt=this._appendLeaves(M,$t.cluster_id,Bt,Wt,Nt):Nt1;let Hn,so,uo;if(mn)Hn=T(et,M,this.clusterProps),so=et[M],uo=et[M+1];else{const Bt=this.points[et[M+Ia]];Hn=Bt.properties;const[Wt,Nt]=Bt.geometry.coordinates;so=D(Wt),uo=C(Nt)}const Io={type:1,geometry:[[Math.round(this.options.extent*(so*Nt-Bt)),Math.round(this.options.extent*(uo*Nt-Wt))]],tags:Hn};let Po;Po=mn||this.options.generateId?et[M+Ia]:this.points[et[M+Ia]].id,void 0!==Po&&(Io.id=Po),$t.features.push(Io)}}_limitZoom(M){return Math.max(this.options.minZoom,Math.min(Math.floor(+M),this.options.maxZoom+1))}_cluster(M,et){const{radius:Bt,extent:Wt,reduce:Nt,minPoints:$t}=this.options,Gr=Bt/(Wt*Math.pow(2,et)),mn=M.data,Hn=[],so=this.stride;for(let Bt=0;Btet&&(To+=mn[Bt+Ba])}if(To>Po&&To>=$t){let M,$t=Wt*Po,Gr=uo*Po,Eo=-1;const Ia=(Bt/so<<5)+(et+1)+this.points.length;for(const Wt of Io){const Hn=Wt*so;if(mn[Hn+2]<=et)continue;mn[Hn+2]=et;const uo=mn[Hn+Ba];$t+=mn[Hn]*uo,Gr+=mn[Hn+1]*uo,mn[Hn+4]=Ia,Nt&&(M||(M=this._map(mn,Bt,!0),Eo=this.clusterProps.length,this.clusterProps.push(M)),Nt(M,this._map(mn,Hn)))}mn[Bt+4]=Ia,Hn.push($t/To,Gr/To,1/0,Ia,-1,To),Nt&&Hn.push(Eo)}else{for(let M=0;M1)for(const M of Io){const Bt=M*so;if(!(mn[Bt+2]<=et)){mn[Bt+2]=et;for(let M=0;M>5}_getOriginZoom(M){return(M-this.points.length)%32}_map(M,et,Bt){if(M[et+Ba]>1){const Wt=this.clusterProps[M[et+Ta]];return Bt?Object.assign({},Wt):Wt}const Wt=this.points[M[et+Ia]].properties,Nt=this.options.map(Wt);return Bt&&Nt===Wt?Object.assign({},Nt):Nt}}function k(M,et,Bt){return{type:"Feature",id:M[et+Ia],properties:T(M,et,Bt),geometry:{type:"Point",coordinates:[(Wt=M[et],360*(Wt-.5)),O(M[et+1])]}};var Wt}function T(M,et,Bt){const Wt=M[et+Ba],Nt=Wt>=1e4?`${Math.round(Wt/1e3)}k`:Wt>=1e3?Math.round(Wt/100)/10+"k":Wt,$t=M[et+Ta],Gr=-1===$t?{}:Object.assign({},Bt[$t]);return Object.assign(Gr,{cluster:!0,cluster_id:M[et+Ia],point_count:Wt,point_count_abbreviated:Nt})}function D(M){return M/360+.5}function C(M){const et=Math.sin(M*Math.PI/180),Bt=.5-.25*Math.log((1+et)/(1-et))/Math.PI;return Bt<0?0:Bt>1?1:Bt}function O(M){const et=(180-360*M)*Math.PI/180;return 360*Math.atan(Math.exp(et))/Math.PI-90}function L(M,et,Bt,Wt){let Nt=Wt;const $t=et+(Bt-et>>1);let Gr,mn=Bt-et;const Hn=M[et],so=M[et+1],uo=M[Bt],Io=M[Bt+1];for(let Wt=et+3;WtNt)Gr=Wt,Nt=et;else if(et===Nt){const M=Math.abs(Wt-$t);MWt&&(Gr-et>3&&L(M,et,Gr,Wt),M[Gr+2]=Nt,Bt-Gr>3&&L(M,Gr,Bt,Wt))}function F(M,et,Bt,Wt,Nt,$t){let Gr=Nt-Bt,mn=$t-Wt;if(0!==Gr||0!==mn){const Hn=((M-Bt)*Gr+(et-Wt)*mn)/(Gr*Gr+mn*mn);Hn>1?(Bt=Nt,Wt=$t):Hn>0&&(Bt+=Gr*Hn,Wt+=mn*Hn)}return Gr=M-Bt,mn=et-Wt,Gr*Gr+mn*mn}function z(M,et,Bt,Wt){const Nt={id:null==M?null:M,type:et,geometry:Bt,tags:Wt,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("Point"===et||"MultiPoint"===et||"LineString"===et)G(Nt,Bt);else if("Polygon"===et)G(Nt,Bt[0]);else if("MultiLineString"===et)for(const M of Bt)G(Nt,M);else if("MultiPolygon"===et)for(const M of Bt)G(Nt,M[0]);return Nt}function G(M,et){for(let Bt=0;Bt0&&(Gr+=Wt?(Nt*Hn-mn*$t)/2:Math.sqrt(Math.pow(mn-Nt,2)+Math.pow(Hn-$t,2))),Nt=mn,$t=Hn}const mn=et.length-3;et[2]=1,L(et,0,mn,Bt),et[mn+2]=1,et.size=Math.abs(Gr),et.start=0,et.end=et.size}function Z(M,et,Bt,Wt){for(let Nt=0;Nt1?1:Bt}function W(M,et,Bt,Wt,Nt,$t,Gr,mn){if(Wt/=et,$t>=(Bt/=et)&&Gr=Wt)return null;const Hn=[];for(const et of M){const M=et.geometry;let $t=et.type;const Gr=0===Nt?et.minX:et.minY,so=0===Nt?et.maxX:et.maxY;if(Gr>=Bt&&so=Wt)continue;let uo=[];if("Point"===$t||"MultiPoint"===$t)R(M,uo,Bt,Wt,Nt);else if("LineString"===$t)Y(M,uo,Bt,Wt,Nt,!1,mn.lineMetrics);else if("MultiLineString"===$t)X(M,uo,Bt,Wt,Nt,!1);else if("Polygon"===$t)X(M,uo,Bt,Wt,Nt,!0);else if("MultiPolygon"===$t)for(const et of M){const M=[];X(et,M,Bt,Wt,Nt,!0),M.length&&uo.push(M)}if(uo.length){if(mn.lineMetrics&&"LineString"===$t){for(const M of uo)Hn.push(z(et.id,$t,M,et.tags));continue}"LineString"!==$t&&"MultiLineString"!==$t||(1===uo.length?($t="LineString",uo=uo[0]):$t="MultiLineString"),"Point"!==$t&&"MultiPoint"!==$t||($t=3===uo.length?"Point":"MultiPoint"),Hn.push(z(et.id,$t,uo,et.tags))}}return Hn.length?Hn:null}function R(M,et,Bt,Wt,Nt){for(let $t=0;$t=Bt&&Gr<=Wt&&q(et,M[$t],M[$t+1],M[$t+2])}}function Y(M,et,Bt,Wt,Nt,$t,Gr){let mn=V(M);const Hn=0===Nt?B:H;let so,uo,Io=M.start;for(let Po=0;PoBt&&(uo=Hn(mn,To,Eo,Ba,Ta,Bt),Gr&&(mn.start=Io+so*uo)):Va>Wt?za=Bt&&(uo=Hn(mn,To,Eo,Ba,Ta,Bt),Fa=!0),za>Wt&&Va<=Wt&&(uo=Hn(mn,To,Eo,Ba,Ta,Wt),Fa=!0),!$t&&Fa&&(Gr&&(mn.end=Io+so*uo),et.push(mn),mn=V(M)),Gr&&(Io+=so)}let Po=M.length-3;const To=M[Po],Eo=M[Po+1],Ia=0===Nt?To:Eo;Ia>=Bt&&Ia<=Wt&&q(mn,To,Eo,M[Po+2]),Po=mn.length-3,$t&&Po>=3&&(mn[Po]!==mn[0]||mn[Po+1]!==mn[1])&&q(mn,mn[0],mn[1],mn[2]),mn.length&&et.push(mn)}function V(M){const et=[];return et.size=M.size,et.start=M.start,et.end=M.end,et}function X(M,et,Bt,Wt,Nt,$t){for(const Gr of M)Y(Gr,et,Bt,Wt,Nt,$t,!1)}function q(M,et,Bt,Wt){M.push(et,Bt,Wt)}function B(M,et,Bt,Wt,Nt,$t){const Gr=($t-et)/(Wt-et);return q(M,$t,Bt+(Nt-Bt)*Gr,1),Gr}function H(M,et,Bt,Wt,Nt,$t){const Gr=($t-Bt)/(Nt-Bt);return q(M,et+(Wt-et)*Gr,$t,1),Gr}function $(M,et){const Bt=[];for(let Wt=0;Wt0&&et.size<(Nt?Gr:Wt))return void(Bt.numPoints+=et.length/3);const mn=[];for(let M=0;MGr)&&(Bt.numSimplified++,mn.push(et[M],et[M+1])),Bt.numPoints++;Nt&&function(M,et){let Bt=0;for(let et=0,Wt=M.length,Nt=Wt-2;et0===et)for(let et=0,Bt=M.length;et24)throw new Error("maxZoom should be in the 0-24 range");if(et.promoteId&&et.generateId)throw new Error("promoteId and generateId cannot be used together.");let Wt=function(M,et){const Bt=[];if("FeatureCollection"===M.type)for(let Wt=0;Wt1&&console.time("creation"),Po=this.tiles[Io]=ee(M,et,Bt,Wt,Hn),this.tileCoords.push({z:et,x:Bt,y:Wt}),so)){so>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",et,Bt,Wt,Po.numFeatures,Po.numPoints,Po.numSimplified),console.timeEnd("creation"));const M=`z${et}`;this.stats[M]=(this.stats[M]||0)+1,this.total++}if(Po.source=M,null==Nt){if(et===Hn.indexMaxZoom||Po.numPoints<=Hn.indexMaxPoints)continue}else{if(et===Hn.maxZoom||et===Nt)continue;if(null!=Nt){const M=Nt-et;if(Bt!==$t>>M||Wt!==Gr>>M)continue}}if(Po.source=null,0===M.length)continue;so>1&&console.time("clipping");const To=.5*Hn.buffer/Hn.extent,Eo=.5-To,Ia=.5+To,Ba=1+To;let Ta=null,Va=null,za=null,Fa=null,Ea=W(M,uo,Bt-To,Bt+Ia,0,Po.minX,Po.maxX,Hn),La=W(M,uo,Bt+Eo,Bt+Ba,0,Po.minX,Po.maxX,Hn);M=null,Ea&&(Ta=W(Ea,uo,Wt-To,Wt+Ia,1,Po.minY,Po.maxY,Hn),Va=W(Ea,uo,Wt+Eo,Wt+Ba,1,Po.minY,Po.maxY,Hn),Ea=null),La&&(za=W(La,uo,Wt-To,Wt+Ia,1,Po.minY,Po.maxY,Hn),Fa=W(La,uo,Wt+Eo,Wt+Ba,1,Po.minY,Po.maxY,Hn),La=null),so>1&&console.timeEnd("clipping"),mn.push(Ta||[],et+1,2*Bt,2*Wt),mn.push(Va||[],et+1,2*Bt,2*Wt+1),mn.push(za||[],et+1,2*Bt+1,2*Wt),mn.push(Fa||[],et+1,2*Bt+1,2*Wt+1)}}getTile(M,et,Bt){M=+M,et=+et,Bt=+Bt;const Wt=this.options,{extent:Nt,debug:$t}=Wt;if(M<0||M>24)return null;const Gr=1<1&&console.log("drilling down to z%d-%d-%d",M,et,Bt);let Hn,so=M,uo=et,Io=Bt;for(;!Hn&&so>0;)so--,uo>>=1,Io>>=1,Hn=this.tiles[se(so,uo,Io)];return Hn&&Hn.source?($t>1&&(console.log("found parent tile z%d-%d-%d",so,uo,Io),console.time("drilling down")),this.splitTile(Hn.source,so,uo,Io,M,et,Bt),$t>1&&console.timeEnd("drilling down"),this.tiles[mn]?K(this.tiles[mn],Nt):null):null}}function se(M,et,Bt){return 32*((1<{Gr.properties=M;const et={};for(const M of mn)et[M]=Wt[M].evaluate($t,Gr);return et},et.reduce=(M,et)=>{Gr.properties=et;for(const et of mn)$t.accumulated=M[et],M[et]=Nt[et].evaluate($t,Gr)},et}(et)).load((yield this._pendingData).features):(Nt=yield this._pendingData,new re(Nt,et.geojsonVtOptions)),this.loaded={};const Bt={};if(Wt){const M=Wt.finish();M&&(Bt.resourceTiming={},Bt.resourceTiming[et.source]=JSON.parse(JSON.stringify(M)))}return Bt}catch(et){if(delete this._pendingRequest,M.cf(et))return{abandoned:!0};throw et}var Nt}))}getData(){return M._(this,void 0,void 0,(function*(){return this._pendingData}))}reloadTile(M){const et=this.loaded;return et&&et[M.uid]?super.reloadTile(M):this.loadTile(M)}loadAndProcessGeoJSON(et,Bt){return M._(this,void 0,void 0,(function*(){let Wt=yield this.loadGeoJSON(et,Bt);if(delete this._pendingRequest,"object"!=typeof Wt)throw new Error(`Input data given to '${et.source}' is not a valid GeoJSON object.`);if(Nt(Wt,!0),et.filter){const Bt=M.cB(et.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if("error"===Bt.result)throw new Error(Bt.value.map((M=>`${M.key}: ${M.message}`)).join(", "));const Nt=Wt.features.filter((M=>Bt.value.evaluate({zoom:0},M)));Wt={type:"FeatureCollection",features:Nt}}return Wt}))}loadGeoJSON(et,Bt){return M._(this,void 0,void 0,(function*(){const{promoteId:Wt}=et;if(et.request){const Nt=yield M.h(et.request,Bt);return this._dataUpdateable=ae(Nt.data,Wt)?le(Nt.data,Wt):void 0,Nt.data}if("string"==typeof et.data)try{const M=JSON.parse(et.data);return this._dataUpdateable=ae(M,Wt)?le(M,Wt):void 0,M}catch(M){throw new Error(`Input data given to '${et.source}' is not a valid GeoJSON object.`)}if(!et.dataDiff)throw new Error(`Input data given to '${et.source}' is not a valid GeoJSON object.`);if(!this._dataUpdateable)throw new Error(`Cannot update existing geojson data in ${et.source}`);return function(M,et,Bt){var Wt,Nt,$t,Gr;if(et.removeAll&&M.clear(),et.remove)for(const Bt of et.remove)M.delete(Bt);if(et.add)for(const Wt of et.add){const et=ne(Wt,Bt);null!=et&&M.set(et,Wt)}if(et.update)for(const Bt of et.update){let et=M.get(Bt.id);if(null==et)continue;const mn=!Bt.removeAllProperties&&((null===(Wt=Bt.removeProperties)||void 0===Wt?void 0:Wt.length)>0||(null===(Nt=Bt.addOrUpdateProperties)||void 0===Nt?void 0:Nt.length)>0);if((Bt.newGeometry||Bt.removeAllProperties||mn)&&(et=Object.assign({},et),M.set(Bt.id,et),mn&&(et.properties=Object.assign({},et.properties))),Bt.newGeometry&&(et.geometry=Bt.newGeometry),Bt.removeAllProperties)et.properties={};else if((null===($t=Bt.removeProperties)||void 0===$t?void 0:$t.length)>0)for(const M of Bt.removeProperties)Object.prototype.hasOwnProperty.call(et.properties,M)&&delete et.properties[M];if((null===(Gr=Bt.addOrUpdateProperties)||void 0===Gr?void 0:Gr.length)>0)for(const{key:M,value:Wt}of Bt.addOrUpdateProperties)et.properties[M]=Wt}}(this._dataUpdateable,et.dataDiff,Wt),{type:"FeatureCollection",features:Array.from(this._dataUpdateable.values())}}))}removeSource(et){return M._(this,void 0,void 0,(function*(){this._pendingRequest&&this._pendingRequest.abort()}))}getClusterExpansionZoom(M){return this._geoJSONIndex.getClusterExpansionZoom(M.clusterId)}getClusterChildren(M){return this._geoJSONIndex.getChildren(M.clusterId)}getClusterLeaves(M){return this._geoJSONIndex.getLeaves(M.clusterId,M.limit,M.offset)}}class ue{constructor(et){this.self=et,this.actor=new M.F(et),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.self.registerWorkerSource=(M,et)=>{if(this.externalWorkerSourceTypes[M])throw new Error(`Worker source with name "${M}" already registered.`);this.externalWorkerSourceTypes[M]=et},this.self.addProtocol=M.ch,this.self.removeProtocol=M.ci,this.self.registerRTLTextPlugin=et=>{M.cC.setMethods(et)},this.actor.registerMessageHandler("LDT",((M,et)=>this._getDEMWorkerSource(M,et.source).loadTile(et))),this.actor.registerMessageHandler("RDT",((et,Bt)=>M._(this,void 0,void 0,(function*(){this._getDEMWorkerSource(et,Bt.source).removeTile(Bt)})))),this.actor.registerMessageHandler("GCEZ",((et,Bt)=>M._(this,void 0,void 0,(function*(){return this._getWorkerSource(et,Bt.type,Bt.source).getClusterExpansionZoom(Bt)})))),this.actor.registerMessageHandler("GCC",((et,Bt)=>M._(this,void 0,void 0,(function*(){return this._getWorkerSource(et,Bt.type,Bt.source).getClusterChildren(Bt)})))),this.actor.registerMessageHandler("GCL",((et,Bt)=>M._(this,void 0,void 0,(function*(){return this._getWorkerSource(et,Bt.type,Bt.source).getClusterLeaves(Bt)})))),this.actor.registerMessageHandler("LD",((M,et)=>this._getWorkerSource(M,et.type,et.source).loadData(et))),this.actor.registerMessageHandler("GD",((M,et)=>this._getWorkerSource(M,et.type,et.source).getData())),this.actor.registerMessageHandler("LT",((M,et)=>this._getWorkerSource(M,et.type,et.source).loadTile(et))),this.actor.registerMessageHandler("RT",((M,et)=>this._getWorkerSource(M,et.type,et.source).reloadTile(et))),this.actor.registerMessageHandler("AT",((M,et)=>this._getWorkerSource(M,et.type,et.source).abortTile(et))),this.actor.registerMessageHandler("RMT",((M,et)=>this._getWorkerSource(M,et.type,et.source).removeTile(et))),this.actor.registerMessageHandler("RS",((et,Bt)=>M._(this,void 0,void 0,(function*(){if(!this.workerSources[et]||!this.workerSources[et][Bt.type]||!this.workerSources[et][Bt.type][Bt.source])return;const M=this.workerSources[et][Bt.type][Bt.source];delete this.workerSources[et][Bt.type][Bt.source],void 0!==M.removeSource&&M.removeSource(Bt)})))),this.actor.registerMessageHandler("RM",(et=>M._(this,void 0,void 0,(function*(){delete this.layerIndexes[et],delete this.availableImages[et],delete this.workerSources[et],delete this.demWorkerSources[et]})))),this.actor.registerMessageHandler("SR",((et,Bt)=>M._(this,void 0,void 0,(function*(){this.referrer=Bt})))),this.actor.registerMessageHandler("SRPS",((M,et)=>this._syncRTLPluginState(M,et))),this.actor.registerMessageHandler("IS",((et,Bt)=>M._(this,void 0,void 0,(function*(){this.self.importScripts(Bt)})))),this.actor.registerMessageHandler("SI",((M,et)=>this._setImages(M,et))),this.actor.registerMessageHandler("UL",((et,Bt)=>M._(this,void 0,void 0,(function*(){this._getLayerIndex(et).update(Bt.layers,Bt.removedIds)})))),this.actor.registerMessageHandler("SL",((et,Bt)=>M._(this,void 0,void 0,(function*(){this._getLayerIndex(et).replace(Bt)}))))}_setImages(et,Bt){return M._(this,void 0,void 0,(function*(){this.availableImages[et]=Bt;for(const M in this.workerSources[et]){const Wt=this.workerSources[et][M];for(const M in Wt)Wt[M].availableImages=Bt}}))}_syncRTLPluginState(et,Bt){return M._(this,void 0,void 0,(function*(){return yield M.cC.syncState(Bt,this.self.importScripts)}))}_getAvailableImages(M){let et=this.availableImages[M];return et||(et=[]),et}_getLayerIndex(M){let et=this.layerIndexes[M];return et||(et=this.layerIndexes[M]=new t),et}_getWorkerSource(M,et,Bt){if(this.workerSources[M]||(this.workerSources[M]={}),this.workerSources[M][et]||(this.workerSources[M][et]={}),!this.workerSources[M][et][Bt]){const Wt={sendAsync:(et,Bt)=>(et.targetMapId=M,this.actor.sendAsync(et,Bt))};switch(et){case"vector":this.workerSources[M][et][Bt]=new s(Wt,this._getLayerIndex(M),this._getAvailableImages(M));break;case"geojson":this.workerSources[M][et][Bt]=new ce(Wt,this._getLayerIndex(M),this._getAvailableImages(M));break;default:this.workerSources[M][et][Bt]=new this.externalWorkerSourceTypes[et](Wt,this._getLayerIndex(M),this._getAvailableImages(M))}}return this.workerSources[M][et][Bt]}_getDEMWorkerSource(M,et){return this.demWorkerSources[M]||(this.demWorkerSources[M]={}),this.demWorkerSources[M][et]||(this.demWorkerSources[M][et]=new n),this.demWorkerSources[M][et]}}return M.i(self)&&(self.worker=new ue(self)),ue})),define("index",["exports","./shared"],(function(M,et){var Bt="5.0.0";function r(){var M=new et.A(4);return et.A!=Float32Array&&(M[1]=0,M[2]=0),M[0]=1,M[3]=1,M}let Wt,Nt;const $t={now:"undefined"!=typeof performance&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date),frameAsync:M=>new Promise(((Bt,Wt)=>{const Nt=requestAnimationFrame(Bt);M.signal.addEventListener("abort",(()=>{cancelAnimationFrame(Nt),Wt(et.c())}))})),getImageData(M,et=0){return this.getImageCanvasContext(M).getImageData(-et,-et,M.width+2*et,M.height+2*et)},getImageCanvasContext(M){const et=window.document.createElement("canvas"),Bt=et.getContext("2d",{willReadFrequently:!0});if(!Bt)throw new Error("failed to create canvas 2d context");return et.width=M.width,et.height=M.height,Bt.drawImage(M,0,0,M.width,M.height),Bt},resolveURL:M=>(Wt||(Wt=document.createElement("a")),Wt.href=M,Wt.href),hardwareConcurrency:"undefined"!=typeof navigator&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return!!matchMedia&&(null==Nt&&(Nt=matchMedia("(prefers-reduced-motion: reduce)")),Nt.matches)}};class n{static testProp(M){if(!n.docStyle)return M[0];for(let et=0;et{window.removeEventListener("click",n.suppressClickInternal,!0)}),0)}static getScale(M){const et=M.getBoundingClientRect();return{x:et.width/M.offsetWidth||1,y:et.height/M.offsetHeight||1,boundingClientRect:et}}static getPoint(M,Bt,Wt){const Nt=Bt.boundingClientRect;return new et.P((Wt.clientX-Nt.left)/Bt.x-M.clientLeft,(Wt.clientY-Nt.top)/Bt.y-M.clientTop)}static mousePos(M,et){const Bt=n.getScale(M);return n.getPoint(M,Bt,et)}static touchPos(M,et){const Bt=[],Wt=n.getScale(M);for(let Nt=0;Nt{mn&&_(mn),mn=null,uo=!0},Hn.onerror=()=>{so=!0,mn=null},Hn.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="),function(M){let Bt,Wt,Nt,$t;M.resetRequestQueue=()=>{Bt=[],Wt=0,Nt=0,$t={}},M.addThrottleControl=M=>{const et=Nt++;return $t[et]=M,et},M.removeThrottleControl=M=>{delete $t[M],n()},M.getImage=(M,Wt,Nt=!0)=>new Promise((($t,mn)=>{Gr.supported&&(M.headers||(M.headers={}),M.headers.accept="image/webp,*/*"),et.e(M,{type:"image"}),Bt.push({abortController:Wt,requestParameters:M,supportImageRefresh:Nt,state:"queued",onError:M=>{mn(M)},onSuccess:M=>{$t(M)}}),n()}));const a=M=>et._(this,void 0,void 0,(function*(){M.state="running";const{requestParameters:Bt,supportImageRefresh:Nt,onError:$t,onSuccess:Gr,abortController:mn}=M,Hn=!1===Nt&&!et.i(self)&&!et.g(Bt.url)&&(!Bt.headers||Object.keys(Bt.headers).reduce(((M,et)=>M&&"accept"===et),!0));Wt++;const so=Hn?c(Bt,mn):et.m(Bt,mn);try{const Bt=yield so;delete M.abortController,M.state="completed",Bt.data instanceof HTMLImageElement||et.b(Bt.data)?Gr(Bt):Bt.data&&Gr({data:yield(uo=Bt.data,"function"==typeof createImageBitmap?et.d(uo):et.f(uo)),cacheControl:Bt.cacheControl,expires:Bt.expires})}catch(et){delete M.abortController,$t(et)}finally{Wt--,n()}var uo})),n=()=>{const M=(()=>{for(const M of Object.keys($t))if($t[M]())return!0;return!1})()?et.a.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:et.a.MAX_PARALLEL_IMAGE_REQUESTS;for(let et=Wt;et0;et++){const M=Bt.shift();M.abortController.signal.aborted?et--:a(M)}},c=(M,Bt)=>new Promise(((Wt,Nt)=>{const $t=new Image,Gr=M.url,mn=M.credentials;mn&&"include"===mn?$t.crossOrigin="use-credentials":(mn&&"same-origin"===mn||!et.s(Gr))&&($t.crossOrigin="anonymous"),Bt.signal.addEventListener("abort",(()=>{$t.src="",Nt(et.c())})),$t.fetchPriority="high",$t.onload=()=>{$t.onerror=$t.onload=null,Wt({data:$t})},$t.onerror=()=>{$t.onerror=$t.onload=null,Bt.signal.aborted||Nt(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."))},$t.src=Gr}))}(Io||(Io={})),Io.resetRequestQueue();class m{constructor(M){this._transformRequestFn=M}transformRequest(M,et){return this._transformRequestFn&&this._transformRequestFn(M,et)||{url:M}}setTransformRequest(M){this._transformRequestFn=M}}function f(M){const et=[];if("string"==typeof M)et.push({id:"default",url:M});else if(M&&M.length>0){const Bt=[];for(const{id:Wt,url:Nt}of M){const M=`${Wt}${Nt}`;-1===Bt.indexOf(M)&&(Bt.push(M),et.push({id:Wt,url:Nt}))}}return et}function g(M,et,Bt){try{const Wt=new URL(M);return Wt.pathname+=`${et}${Bt}`,Wt.toString()}catch(et){throw new Error(`Invalid sprite URL "${M}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`)}}class v{constructor(M,et,Bt,Wt){this.context=M,this.format=Bt,this.texture=M.gl.createTexture(),this.update(et,Wt)}update(M,Bt,Wt){const{width:Nt,height:$t}=M,Gr=!(this.size&&this.size[0]===Nt&&this.size[1]===$t||Wt),{context:mn}=this,{gl:Hn}=mn;if(this.useMipmap=Boolean(Bt&&Bt.useMipmap),Hn.bindTexture(Hn.TEXTURE_2D,this.texture),mn.pixelStoreUnpackFlipY.set(!1),mn.pixelStoreUnpack.set(1),mn.pixelStoreUnpackPremultiplyAlpha.set(this.format===Hn.RGBA&&(!Bt||!1!==Bt.premultiply)),Gr)this.size=[Nt,$t],M instanceof HTMLImageElement||M instanceof HTMLCanvasElement||M instanceof HTMLVideoElement||M instanceof ImageData||et.b(M)?Hn.texImage2D(Hn.TEXTURE_2D,0,this.format,this.format,Hn.UNSIGNED_BYTE,M):Hn.texImage2D(Hn.TEXTURE_2D,0,this.format,Nt,$t,0,this.format,Hn.UNSIGNED_BYTE,M.data);else{const{x:Bt,y:Gr}=Wt||{x:0,y:0};M instanceof HTMLImageElement||M instanceof HTMLCanvasElement||M instanceof HTMLVideoElement||M instanceof ImageData||et.b(M)?Hn.texSubImage2D(Hn.TEXTURE_2D,0,Bt,Gr,Hn.RGBA,Hn.UNSIGNED_BYTE,M):Hn.texSubImage2D(Hn.TEXTURE_2D,0,Bt,Gr,Nt,$t,Hn.RGBA,Hn.UNSIGNED_BYTE,M.data)}this.useMipmap&&this.isSizePowerOfTwo()&&Hn.generateMipmap(Hn.TEXTURE_2D)}bind(M,et,Bt){const{context:Wt}=this,{gl:Nt}=Wt;Nt.bindTexture(Nt.TEXTURE_2D,this.texture),Bt!==Nt.LINEAR_MIPMAP_NEAREST||this.isSizePowerOfTwo()||(Bt=Nt.LINEAR),M!==this.filter&&(Nt.texParameteri(Nt.TEXTURE_2D,Nt.TEXTURE_MAG_FILTER,M),Nt.texParameteri(Nt.TEXTURE_2D,Nt.TEXTURE_MIN_FILTER,Bt||M),this.filter=M),et!==this.wrap&&(Nt.texParameteri(Nt.TEXTURE_2D,Nt.TEXTURE_WRAP_S,et),Nt.texParameteri(Nt.TEXTURE_2D,Nt.TEXTURE_WRAP_T,et),this.wrap=et)}isSizePowerOfTwo(){return this.size[0]===this.size[1]&&Math.log(this.size[0])/Math.LN2%1==0}destroy(){const{gl:M}=this.context;M.deleteTexture(this.texture),this.texture=null}}function x(M){const{userImage:et}=M;return!!(et&&et.render&&et.render())&&(M.data.replace(new Uint8Array(et.data.buffer)),!0)}class b extends et.E{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new et.R({width:1,height:1}),this.dirty=!0}isLoaded(){return this.loaded}setLoaded(M){if(this.loaded!==M&&(this.loaded=M,M)){for(const{ids:M,promiseResolve:et}of this.requestors)et(this._getImagesForIds(M));this.requestors=[]}}getImage(M){const Bt=this.images[M];if(Bt&&!Bt.data&&Bt.spriteData){const M=Bt.spriteData;Bt.data=new et.R({width:M.width,height:M.height},M.context.getImageData(M.x,M.y,M.width,M.height).data),Bt.spriteData=null}return Bt}addImage(M,et){if(this.images[M])throw new Error(`Image id ${M} already exist, use updateImage instead`);this._validate(M,et)&&(this.images[M]=et)}_validate(M,Bt){let Wt=!0;const Nt=Bt.data||Bt.spriteData;return this._validateStretch(Bt.stretchX,Nt&&Nt.width)||(this.fire(new et.j(new Error(`Image "${M}" has invalid "stretchX" value`))),Wt=!1),this._validateStretch(Bt.stretchY,Nt&&Nt.height)||(this.fire(new et.j(new Error(`Image "${M}" has invalid "stretchY" value`))),Wt=!1),this._validateContent(Bt.content,Bt)||(this.fire(new et.j(new Error(`Image "${M}" has invalid "content" value`))),Wt=!1),Wt}_validateStretch(M,et){if(!M)return!0;let Bt=0;for(const Wt of M){if(Wt[0]{let Wt=!0;if(!this.isLoaded())for(const et of M)this.images[et]||(Wt=!1);this.isLoaded()||Wt?et(this._getImagesForIds(M)):this.requestors.push({ids:M,promiseResolve:et})}))}_getImagesForIds(M){const Bt={};for(const Wt of M){let M=this.getImage(Wt);M||(this.fire(new et.k("styleimagemissing",{id:Wt})),M=this.getImage(Wt)),M?Bt[Wt]={data:M.data.clone(),pixelRatio:M.pixelRatio,sdf:M.sdf,version:M.version,stretchX:M.stretchX,stretchY:M.stretchY,content:M.content,textFitWidth:M.textFitWidth,textFitHeight:M.textFitHeight,hasRenderCallback:Boolean(M.userImage&&M.userImage.render)}:et.w(`Image "${Wt}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`)}return Bt}getPixelSize(){const{width:M,height:et}=this.atlasImage;return{width:M,height:et}}getPattern(M){const Bt=this.patterns[M],Wt=this.getImage(M);if(!Wt)return null;if(Bt&&Bt.position.version===Wt.version)return Bt.position;if(Bt)Bt.position.version=Wt.version;else{const Bt={w:Wt.data.width+2,h:Wt.data.height+2,x:0,y:0},Nt=new et.I(Bt,Wt);this.patterns[M]={bin:Bt,position:Nt}}return this._updatePatternAtlas(),this.patterns[M].position}bind(M){const et=M.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new v(M,this.atlasImage,et.RGBA),this.atlasTexture.bind(et.LINEAR,et.CLAMP_TO_EDGE)}_updatePatternAtlas(){const M=[];for(const et in this.patterns)M.push(this.patterns[et].bin);const{w:Bt,h:Wt}=et.p(M),Nt=this.atlasImage;Nt.resize({width:Bt||1,height:Wt||1});for(const M in this.patterns){const{bin:Bt}=this.patterns[M],Wt=Bt.x+1,$t=Bt.y+1,Gr=this.getImage(M).data,mn=Gr.width,Hn=Gr.height;et.R.copy(Gr,Nt,{x:0,y:0},{x:Wt,y:$t},{width:mn,height:Hn}),et.R.copy(Gr,Nt,{x:0,y:Hn-1},{x:Wt,y:$t-1},{width:mn,height:1}),et.R.copy(Gr,Nt,{x:0,y:0},{x:Wt,y:$t+Hn},{width:mn,height:1}),et.R.copy(Gr,Nt,{x:mn-1,y:0},{x:Wt-1,y:$t},{width:1,height:Hn}),et.R.copy(Gr,Nt,{x:0,y:0},{x:Wt+mn,y:$t},{width:1,height:Hn})}this.dirty=!0}beginFrame(){this.callbackDispatchedThisFrame={}}dispatchRenderCallbacks(M){for(const Bt of M){if(this.callbackDispatchedThisFrame[Bt])continue;this.callbackDispatchedThisFrame[Bt]=!0;const M=this.getImage(Bt);M||et.w(`Image with ID: "${Bt}" was not found`),x(M)&&this.updateImage(Bt,M)}}}const Po=1e20;function w(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn){for(let so=et;so-1);Hn++,$t[Hn]=mn,Gr[Hn]=so,Gr[Hn+1]=Po}for(let mn=0,Hn=0;mn65535)throw new Error("glyphs > 65535 not supported");if(et.ranges[Nt])return{stack:M,id:Bt,glyph:Wt};if(!this.url)throw new Error("glyphsUrl is not set");if(!et.requests[Nt]){const Bt=P.loadGlyphRange(M,Nt,this.url,this.requestManager);et.requests[Nt]=Bt}const $t=yield et.requests[Nt];for(const M in $t)this._doesCharSupportLocalGlyph(+M)||(et.glyphs[+M]=$t[+M]);return et.ranges[Nt]=!0,{stack:M,id:Bt,glyph:$t[Bt]||null}}))}_doesCharSupportLocalGlyph(M){return!!this.localIdeographFontFamily&&/\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(M))}_tinySDF(M,Bt,Wt){const Nt=this.localIdeographFontFamily;if(!Nt)return;if(!this._doesCharSupportLocalGlyph(Wt))return;let $t=M.tinySDF;if(!$t){let et="400";/bold/i.test(Bt)?et="900":/medium/i.test(Bt)?et="500":/light/i.test(Bt)&&(et="200"),$t=M.tinySDF=new P.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,fontFamily:Nt,fontWeight:et})}const Gr=$t.draw(String.fromCharCode(Wt));return{id:Wt,bitmap:new et.o({width:Gr.width||60,height:Gr.height||60},Gr.data),metrics:{width:Gr.glyphWidth/2||24,height:Gr.glyphHeight/2||24,left:Gr.glyphLeft/2+.5||0,top:Gr.glyphTop/2-27.5||-8,advance:Gr.glyphAdvance/2||24,isDoubleResolution:!0}}}}P.loadGlyphRange=function(M,Bt,Wt,Nt){return et._(this,void 0,void 0,(function*(){const $t=256*Bt,Gr=$t+255,mn=Nt.transformRequest(Wt.replace("{fontstack}",M).replace("{range}",`${$t}-${Gr}`),"Glyphs"),Hn=yield et.l(mn,new AbortController);if(!Hn||!Hn.data)throw new Error(`Could not load glyph range. range: ${Bt}, ${$t}-${Gr}`);const so={};for(const M of et.n(Hn.data))so[M.id]=M;return so}))},P.TinySDF=class{constructor({fontSize:M=24,buffer:et=3,radius:Bt=8,cutoff:Wt=.25,fontFamily:Nt="sans-serif",fontWeight:$t="normal",fontStyle:Gr="normal"}={}){this.buffer=et,this.cutoff=Wt,this.radius=Bt;const mn=this.size=M+4*et,Hn=this._createCanvas(mn),so=this.ctx=Hn.getContext("2d",{willReadFrequently:!0});so.font=`${Gr} ${$t} ${M}px ${Nt}`,so.textBaseline="alphabetic",so.textAlign="left",so.fillStyle="black",this.gridOuter=new Float64Array(mn*mn),this.gridInner=new Float64Array(mn*mn),this.f=new Float64Array(mn),this.z=new Float64Array(mn+1),this.v=new Uint16Array(mn)}_createCanvas(M){const et=document.createElement("canvas");return et.width=et.height=M,et}draw(M){const{width:et,actualBoundingBoxAscent:Bt,actualBoundingBoxDescent:Wt,actualBoundingBoxLeft:Nt,actualBoundingBoxRight:$t}=this.ctx.measureText(M),Gr=Math.ceil(Bt),mn=Math.max(0,Math.min(this.size-this.buffer,Math.ceil($t-Nt))),Hn=Math.min(this.size-this.buffer,Gr+Math.ceil(Wt)),so=mn+2*this.buffer,uo=Hn+2*this.buffer,Io=Math.max(so*uo,0),To=new Uint8ClampedArray(Io),Eo={data:To,width:so,height:uo,glyphWidth:mn,glyphHeight:Hn,glyphTop:Gr,glyphLeft:0,glyphAdvance:et};if(0===mn||0===Hn)return Eo;const{ctx:Ia,buffer:Ba,gridInner:Ta,gridOuter:Va}=this;Ia.clearRect(Ba,Ba,mn,Hn),Ia.fillText(M,Ba,Ba+Gr);const za=Ia.getImageData(Ba,Ba,mn,Hn);Va.fill(Po,0,Io),Ta.fill(0,0,Io);for(let M=0;M0?M*M:0,Ta[Wt]=M<0?M*M:0}}w(Va,0,0,so,uo,so,this.f,this.v,this.z),w(Ta,Ba,Ba,mn,Hn,so,this.f,this.v,this.z);for(let M=0;M1&&(Gr=M[++$t]);const Hn=Math.abs(mn-Gr.left),so=Math.abs(mn-Gr.right),uo=Math.min(Hn,so);let Io;const Po=et/Bt*(Wt+1);if(Gr.isDash){const M=Wt-Math.abs(Po);Io=Math.sqrt(uo*uo+M*M)}else Io=Wt-Math.sqrt(uo*uo+Po*Po);this.data[Nt+mn]=Math.max(0,Math.min(255,Io+128))}}}addRegularDash(M){for(let et=M.length-1;et>=0;--et){const Bt=M[et],Wt=M[et+1];Bt.zeroLength?M.splice(et,1):Wt&&Wt.isDash===Bt.isDash&&(Wt.left=Bt.left,M.splice(et,1))}const et=M[0],Bt=M[M.length-1];et.isDash===Bt.isDash&&(et.left=Bt.left-this.width,Bt.right=et.right+this.width);const Wt=this.width*this.nextRow;let Nt=0,$t=M[Nt];for(let et=0;et1&&($t=M[++Nt]);const Bt=Math.abs(et-$t.left),Gr=Math.abs(et-$t.right),mn=Math.min(Bt,Gr);this.data[Wt+et]=Math.max(0,Math.min(255,($t.isDash?mn:-mn)+128))}}addDash(M,Bt){const Wt=Bt?7:0,Nt=2*Wt+1;if(this.nextRow+Nt>this.height)return et.w("LineAtlas out of space"),null;let $t=0;for(let et=0;et{M.terminate()})),this.workers=null)}isPreloaded(){return!!this.active[Ia]}numActive(){return Object.keys(this.active).length}}const Ba=Math.floor($t.hardwareConcurrency/2);let Ta,Va;function F(){return Ta||(Ta=new z),Ta}z.workerCount=et.C(globalThis)?Math.max(Math.min(Ba,3),1):1;class B{constructor(M,Bt){this.workerPool=M,this.actors=[],this.currentActor=0,this.id=Bt;const Wt=this.workerPool.acquire(Bt);for(let M=0;M{M.remove()})),this.actors=[],M&&this.workerPool.release(this.id)}registerMessageHandler(M,et){for(const Bt of this.actors)Bt.registerMessageHandler(M,et)}}function j(){return Va||(Va=new B(F(),et.G),Va.registerMessageHandler("GR",((M,Bt,Wt)=>et.m(Bt,Wt)))),Va}function O(M,Bt){const Wt=et.H();return et.J(Wt,Wt,[1,1,0]),et.K(Wt,Wt,[.5*M.width,.5*M.height,1]),M.calculatePosMatrix?et.L(Wt,Wt,M.calculatePosMatrix(Bt.toUnwrapped())):Wt}function N(M,et,Bt,Wt,Nt,$t){var Gr;const mn=function(M,et,Bt){if(M)for(const Wt of M){const M=et[Wt];if(M&&M.source===Bt&&"fill-extrusion"===M.type)return!0}else for(const M in et){const Wt=et[M];if(Wt.source===Bt&&"fill-extrusion"===Wt.type)return!0}return!1}(null!==(Gr=null==Nt?void 0:Nt.layers)&&void 0!==Gr?Gr:null,et,M.id),Hn=$t.maxPitchScaleFactor(),so=M.tilesIn(Wt,Hn,mn);so.sort(Z);const uo=[];for(const Wt of so)uo.push({wrappedTileID:Wt.tileID.wrapped().key,queryResults:Wt.tile.queryRenderedFeatures(et,Bt,M._state,Wt.queryGeometry,Wt.cameraQueryGeometry,Wt.scale,Nt,$t,Hn,O(M.transform,Wt.tileID))});return function(M,et){for(const Bt in M)for(const Wt of M[Bt])G(Wt,et);return M}(function(M){const et={},Bt={};for(const Wt of M){const M=Wt.queryResults,Nt=Wt.wrappedTileID,$t=Bt[Nt]=Bt[Nt]||{};for(const Bt in M){const Wt=M[Bt],Nt=$t[Bt]=$t[Bt]||{},Gr=et[Bt]=et[Bt]||[];for(const M of Wt)Nt[M.featureIndex]||(Nt[M.featureIndex]=!0,Gr.push(M))}}return et}(uo),M)}function Z(M,et){const Bt=M.tileID,Wt=et.tileID;return Bt.overscaledZ-Wt.overscaledZ||Bt.canonical.y-Wt.canonical.y||Bt.wrap-Wt.wrap||Bt.canonical.x-Wt.canonical.x}function G(M,et){const Bt=M.feature,Wt=et.getFeatureState(Bt.layer["source-layer"],Bt.id);Bt.source=Bt.layer.source,Bt.layer["source-layer"]&&(Bt.sourceLayer=Bt.layer["source-layer"]),Bt.state=Wt}function U(M,Bt,Wt){return et._(this,void 0,void 0,(function*(){let Nt=M;if(M.url?Nt=(yield et.h(Bt.transformRequest(M.url,"Source"),Wt)).data:yield $t.frameAsync(Wt),!Nt)return null;const Gr=et.M(et.e(Nt,M),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return"vector_layers"in Nt&&Nt.vector_layers&&(Gr.vectorLayerIds=Nt.vector_layers.map((M=>M.id))),Gr}))}class V{constructor(M,et){M&&(et?this.setSouthWest(M).setNorthEast(et):Array.isArray(M)&&(4===M.length?this.setSouthWest([M[0],M[1]]).setNorthEast([M[2],M[3]]):this.setSouthWest(M[0]).setNorthEast(M[1])))}setNorthEast(M){return this._ne=M instanceof et.N?new et.N(M.lng,M.lat):et.N.convert(M),this}setSouthWest(M){return this._sw=M instanceof et.N?new et.N(M.lng,M.lat):et.N.convert(M),this}extend(M){const Bt=this._sw,Wt=this._ne;let Nt,$t;if(M instanceof et.N)Nt=M,$t=M;else{if(!(M instanceof V))return Array.isArray(M)?4===M.length||M.every(Array.isArray)?this.extend(V.convert(M)):this.extend(et.N.convert(M)):M&&("lng"in M||"lon"in M)&&"lat"in M?this.extend(et.N.convert(M)):this;if(Nt=M._sw,$t=M._ne,!Nt||!$t)return this}return Bt||Wt?(Bt.lng=Math.min(Nt.lng,Bt.lng),Bt.lat=Math.min(Nt.lat,Bt.lat),Wt.lng=Math.max($t.lng,Wt.lng),Wt.lat=Math.max($t.lat,Wt.lat)):(this._sw=new et.N(Nt.lng,Nt.lat),this._ne=new et.N($t.lng,$t.lat)),this}getCenter(){return new et.N((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new et.N(this.getWest(),this.getNorth())}getSouthEast(){return new et.N(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return[this._sw.toArray(),this._ne.toArray()]}toString(){return`LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return!(this._sw&&this._ne)}contains(M){const{lng:Bt,lat:Wt}=et.N.convert(M);let Nt=this._sw.lng<=Bt&&Bt<=this._ne.lng;return this._sw.lng>this._ne.lng&&(Nt=this._sw.lng>=Bt&&Bt>=this._ne.lng),this._sw.lat<=Wt&&Wt<=this._ne.lat&&Nt}static convert(M){return M instanceof V?M:M?new V(M):M}static fromLngLat(M,Bt=0){const Wt=360*Bt/40075017,Nt=Wt/Math.cos(Math.PI/180*M.lat);return new V(new et.N(M.lng-Nt,M.lat-Wt),new et.N(M.lng+Nt,M.lat+Wt))}adjustAntiMeridian(){const M=new et.N(this._sw.lng,this._sw.lat),Bt=new et.N(this._ne.lng,this._ne.lat);return new V(M,M.lng>Bt.lng?new et.N(Bt.lng+360,Bt.lat):Bt)}}class q{constructor(M,et,Bt){this.bounds=V.convert(this.validateBounds(M)),this.minzoom=et||0,this.maxzoom=Bt||24}validateBounds(M){return Array.isArray(M)&&4===M.length?[Math.max(-180,M[0]),Math.max(-90,M[1]),Math.min(180,M[2]),Math.min(90,M[3])]:[-180,-90,180,90]}contains(M){const Bt=Math.pow(2,M.z),Wt=Math.floor(et.O(this.bounds.getWest())*Bt),Nt=Math.floor(et.Q(this.bounds.getNorth())*Bt),$t=Math.ceil(et.O(this.bounds.getEast())*Bt),Gr=Math.ceil(et.Q(this.bounds.getSouth())*Bt);return M.x>=Wt&&M.x<$t&&M.y>=Nt&&M.y{this._options.tiles=M})),this}setUrl(M){return this.setSourceProperty((()=>{this.url=M,this._options.url=M})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null)}serialize(){return et.e({},this._options)}loadTile(M){return et._(this,void 0,void 0,(function*(){const et=M.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),Bt={request:this.map._requestManager.transformRequest(et,"Tile"),uid:M.uid,tileID:M.tileID,zoom:M.tileID.overscaledZ,tileSize:this.tileSize*M.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};Bt.request.collectResourceTiming=this._collectResourceTiming;let Wt="RT";if(M.actor&&"expired"!==M.state){if("loading"===M.state)return new Promise(((et,Bt)=>{M.reloadPromise={resolve:et,reject:Bt}}))}else M.actor=this.dispatcher.getActor(),Wt="LT";M.abortController=new AbortController;try{const et=yield M.actor.sendAsync({type:Wt,data:Bt},M.abortController);if(delete M.abortController,M.aborted)return;this._afterTileLoadWorkerResponse(M,et)}catch(et){if(delete M.abortController,M.aborted)return;if(et&&404!==et.status)throw et;this._afterTileLoadWorkerResponse(M,null)}}))}_afterTileLoadWorkerResponse(M,et){if(et&&et.resourceTiming&&(M.resourceTiming=et.resourceTiming),et&&this.map._refreshExpiredTiles&&M.setExpiryData(et),M.loadVectorData(et,this.map.painter),M.reloadPromise){const et=M.reloadPromise;M.reloadPromise=null,this.loadTile(M).then(et.resolve).catch(et.reject)}}abortTile(M){return et._(this,void 0,void 0,(function*(){M.abortController&&(M.abortController.abort(),delete M.abortController),M.actor&&(yield M.actor.sendAsync({type:"AT",data:{uid:M.uid,type:this.type,source:this.id}}))}))}unloadTile(M){return et._(this,void 0,void 0,(function*(){M.unloadVectorData(),M.actor&&(yield M.actor.sendAsync({type:"RMT",data:{uid:M.uid,type:this.type,source:this.id}}))}))}hasTransition(){return!1}}class W extends et.E{constructor(M,Bt,Wt,Nt){super(),this.id=M,this.dispatcher=Wt,this.setEventedParent(Nt),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=et.e({type:"raster"},Bt),et.e(this,et.M(Bt,["url","scheme","tileSize"]))}load(){return et._(this,arguments,void 0,(function*(M=!1){this._loaded=!1,this.fire(new et.k("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{const Bt=yield U(this._options,this.map._requestManager,this._tileJSONRequest);this._tileJSONRequest=null,this._loaded=!0,Bt&&(et.e(this,Bt),Bt.bounds&&(this.tileBounds=new q(Bt.bounds,this.minzoom,this.maxzoom)),this.fire(new et.k("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new et.k("data",{dataType:"source",sourceDataType:"content",sourceDataChanged:M})))}catch(M){this._tileJSONRequest=null,this.fire(new et.j(M))}}))}loaded(){return this._loaded}onAdd(M){this.map=M,this.load()}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null)}setSourceProperty(M){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),M(),this.load(!0)}setTiles(M){return this.setSourceProperty((()=>{this._options.tiles=M})),this}setUrl(M){return this.setSourceProperty((()=>{this.url=M,this._options.url=M})),this}serialize(){return et.e({},this._options)}hasTile(M){return!this.tileBounds||this.tileBounds.contains(M.canonical)}loadTile(M){return et._(this,void 0,void 0,(function*(){const et=M.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);M.abortController=new AbortController;try{const Bt=yield Io.getImage(this.map._requestManager.transformRequest(et,"Tile"),M.abortController,this.map._refreshExpiredTiles);if(delete M.abortController,M.aborted)return void(M.state="unloaded");if(Bt&&Bt.data){this.map._refreshExpiredTiles&&Bt.cacheControl&&Bt.expires&&M.setExpiryData({cacheControl:Bt.cacheControl,expires:Bt.expires});const et=this.map.painter.context,Wt=et.gl,Nt=Bt.data;M.texture=this.map.painter.getTileTexture(Nt.width),M.texture?M.texture.update(Nt,{useMipmap:!0}):(M.texture=new v(et,Nt,Wt.RGBA,{useMipmap:!0}),M.texture.bind(Wt.LINEAR,Wt.CLAMP_TO_EDGE,Wt.LINEAR_MIPMAP_NEAREST)),M.state="loaded"}}catch(et){if(delete M.abortController,M.aborted)M.state="unloaded";else if(et)throw M.state="errored",et}}))}abortTile(M){return et._(this,void 0,void 0,(function*(){M.abortController&&(M.abortController.abort(),delete M.abortController)}))}unloadTile(M){return et._(this,void 0,void 0,(function*(){M.texture&&this.map.painter.saveTileTexture(M.texture)}))}hasTransition(){return!1}}class X extends W{constructor(M,Bt,Wt,Nt){super(M,Bt,Wt,Nt),this.type="raster-dem",this.maxzoom=22,this._options=et.e({type:"raster-dem"},Bt),this.encoding=Bt.encoding||"mapbox",this.redFactor=Bt.redFactor,this.greenFactor=Bt.greenFactor,this.blueFactor=Bt.blueFactor,this.baseShift=Bt.baseShift}loadTile(M){return et._(this,void 0,void 0,(function*(){const Bt=M.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),Wt=this.map._requestManager.transformRequest(Bt,"Tile");M.neighboringTiles=this._getNeighboringTiles(M.tileID),M.abortController=new AbortController;try{const Bt=yield Io.getImage(Wt,M.abortController,this.map._refreshExpiredTiles);if(delete M.abortController,M.aborted)return void(M.state="unloaded");if(Bt&&Bt.data){const Wt=Bt.data;this.map._refreshExpiredTiles&&Bt.cacheControl&&Bt.expires&&M.setExpiryData({cacheControl:Bt.cacheControl,expires:Bt.expires});const Nt=et.b(Wt)&&et.U()?Wt:yield this.readImageNow(Wt),$t={type:this.type,uid:M.uid,source:this.id,rawImageData:Nt,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(!M.actor||"expired"===M.state){M.actor=this.dispatcher.getActor();const et=yield M.actor.sendAsync({type:"LDT",data:$t});M.dem=et,M.needsHillshadePrepare=!0,M.needsTerrainPrepare=!0,M.state="loaded"}}}catch(et){if(delete M.abortController,M.aborted)M.state="unloaded";else if(et)throw M.state="errored",et}}))}readImageNow(M){return et._(this,void 0,void 0,(function*(){if("undefined"!=typeof VideoFrame&&et.V()){const Bt=M.width+2,Wt=M.height+2;try{return new et.R({width:Bt,height:Wt},yield et.W(M,-1,-1,Bt,Wt))}catch(M){}}return $t.getImageData(M,1)}))}_getNeighboringTiles(M){const Bt=M.canonical,Wt=Math.pow(2,Bt.z),Nt=(Bt.x-1+Wt)%Wt,$t=0===Bt.x?M.wrap-1:M.wrap,Gr=(Bt.x+1+Wt)%Wt,mn=Bt.x+1===Wt?M.wrap+1:M.wrap,Hn={};return Hn[new et.S(M.overscaledZ,$t,Bt.z,Nt,Bt.y).key]={backfilled:!1},Hn[new et.S(M.overscaledZ,mn,Bt.z,Gr,Bt.y).key]={backfilled:!1},Bt.y>0&&(Hn[new et.S(M.overscaledZ,$t,Bt.z,Nt,Bt.y-1).key]={backfilled:!1},Hn[new et.S(M.overscaledZ,M.wrap,Bt.z,Bt.x,Bt.y-1).key]={backfilled:!1},Hn[new et.S(M.overscaledZ,mn,Bt.z,Gr,Bt.y-1).key]={backfilled:!1}),Bt.y+10&&et.e(Nt,{resourceTiming:Wt}),this.fire(new et.k("data",Object.assign(Object.assign({},Nt),{sourceDataType:"metadata"}))),this.fire(new et.k("data",Object.assign(Object.assign({},Nt),{sourceDataType:"content"})))}catch(M){if(this._pendingLoads--,this._removed)return void this.fire(new et.k("dataabort",{dataType:"source"}));this.fire(new et.j(M))}}))}loaded(){return 0===this._pendingLoads}loadTile(M){return et._(this,void 0,void 0,(function*(){const et=M.actor?"RT":"LT";M.actor=this.actor;const Bt={type:this.type,uid:M.uid,tileID:M.tileID,zoom:M.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};M.abortController=new AbortController;const Wt=yield this.actor.sendAsync({type:et,data:Bt},M.abortController);delete M.abortController,M.unloadVectorData(),M.aborted||M.loadVectorData(Wt,this.map.painter,"RT"===et)}))}abortTile(M){return et._(this,void 0,void 0,(function*(){M.abortController&&(M.abortController.abort(),delete M.abortController),M.aborted=!0}))}unloadTile(M){return et._(this,void 0,void 0,(function*(){M.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:M.uid,type:this.type,source:this.id}})}))}onRemove(){this._removed=!0,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}})}serialize(){return et.e({},this._options,{type:this.type,data:this._data})}hasTransition(){return!1}}class K extends et.E{constructor(M,et,Bt,Wt){super(),this.flippedWindingOrder=!1,this.id=M,this.dispatcher=Bt,this.coordinates=et.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(Wt),this.options=et}load(M){return et._(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new et.k("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{const et=yield Io.getImage(this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,et&&et.data&&(this.image=et.data,M&&(this.coordinates=M),this._finishLoading())}catch(M){this._request=null,this._loaded=!0,this.fire(new et.j(M))}}))}loaded(){return this._loaded}updateImage(M){return M.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=M.url,this.load(M.coordinates).finally((()=>{this.texture=null})),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new et.k("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(M){this.map=M,this.load()}onRemove(){this._request&&(this._request.abort(),this._request=null)}setCoordinates(M){this.coordinates=M;const Bt=M.map(et.Y.fromLngLat);var Wt;return this.tileID=function(M){let Bt=1/0,Wt=1/0,Nt=-1/0,$t=-1/0;for(const et of M)Bt=Math.min(Bt,et.x),Wt=Math.min(Wt,et.y),Nt=Math.max(Nt,et.x),$t=Math.max($t,et.y);const Gr=Math.max(Nt-Bt,$t-Wt),mn=Math.max(0,Math.floor(-Math.log(Gr)/Math.LN2)),Hn=Math.pow(2,mn);return new et.Z(mn,Math.floor((Bt+Nt)/2*Hn),Math.floor((Wt+$t)/2*Hn))}(Bt),this.minzoom=this.maxzoom=this.tileID.z,this.tileCoords=Bt.map((M=>this.tileID.getTilePoint(M)._round())),this.flippedWindingOrder=((Wt=this.tileCoords)[1].x-Wt[0].x)*(Wt[2].y-Wt[0].y)-(Wt[1].y-Wt[0].y)*(Wt[2].x-Wt[0].x)<0,this.fire(new et.k("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(0===Object.keys(this.tiles).length||!this.image)return;const M=this.map.painter.context,Bt=M.gl;this.texture||(this.texture=new v(M,this.image,Bt.RGBA),this.texture.bind(Bt.LINEAR,Bt.CLAMP_TO_EDGE));let Wt=!1;for(const M in this.tiles){const et=this.tiles[M];"loaded"!==et.state&&(et.state="loaded",et.texture=this.texture,Wt=!0)}Wt&&this.fire(new et.k("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}loadTile(M){return et._(this,void 0,void 0,(function*(){this.tileID&&this.tileID.equals(M.tileID.canonical)?(this.tiles[String(M.tileID.wrap)]=M,M.buckets={}):M.state="errored"}))}serialize(){return{type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return!1}}class Y extends K{constructor(M,et,Bt,Wt){super(M,et,Bt,Wt),this.roundZoom=!0,this.type="video",this.options=et}load(){return et._(this,void 0,void 0,(function*(){this._loaded=!1;const M=this.options;this.urls=[];for(const et of M.urls)this.urls.push(this.map._requestManager.transformRequest(et,"Source").url);try{const M=yield et.a0(this.urls);if(this._loaded=!0,!M)return;this.video=M,this.video.loop=!0,this.video.addEventListener("playing",(()=>{this.map.triggerRepaint()})),this.map&&this.video.play(),this._finishLoading()}catch(M){this.fire(new et.j(M))}}))}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(M){if(this.video){const Bt=this.video.seekable;MBt.end(0)?this.fire(new et.j(new et.$(`sources.${this.id}`,null,`Playback for this video can be set only between the ${Bt.start(0)} and ${Bt.end(0)}-second mark.`))):this.video.currentTime=M}}getVideo(){return this.video}onAdd(M){this.map||(this.map=M,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)))}prepare(){if(0===Object.keys(this.tiles).length||this.video.readyState<2)return;const M=this.map.painter.context,Bt=M.gl;this.texture?this.video.paused||(this.texture.bind(Bt.LINEAR,Bt.CLAMP_TO_EDGE),Bt.texSubImage2D(Bt.TEXTURE_2D,0,0,0,Bt.RGBA,Bt.UNSIGNED_BYTE,this.video)):(this.texture=new v(M,this.video,Bt.RGBA),this.texture.bind(Bt.LINEAR,Bt.CLAMP_TO_EDGE));let Wt=!1;for(const M in this.tiles){const et=this.tiles[M];"loaded"!==et.state&&(et.state="loaded",et.texture=this.texture,Wt=!0)}Wt&&this.fire(new et.k("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}serialize(){return{type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class J extends K{constructor(M,Bt,Wt,Nt){super(M,Bt,Wt,Nt),Bt.coordinates?Array.isArray(Bt.coordinates)&&4===Bt.coordinates.length&&!Bt.coordinates.some((M=>!Array.isArray(M)||2!==M.length||M.some((M=>"number"!=typeof M))))||this.fire(new et.j(new et.$(`sources.${M}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new et.j(new et.$(`sources.${M}`,null,'missing required property "coordinates"'))),Bt.animate&&"boolean"!=typeof Bt.animate&&this.fire(new et.j(new et.$(`sources.${M}`,null,'optional "animate" property must be a boolean value'))),Bt.canvas?"string"==typeof Bt.canvas||Bt.canvas instanceof HTMLCanvasElement||this.fire(new et.j(new et.$(`sources.${M}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new et.j(new et.$(`sources.${M}`,null,'missing required property "canvas"'))),this.options=Bt,this.animate=void 0===Bt.animate||Bt.animate}load(){return et._(this,void 0,void 0,(function*(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new et.j(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint()},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1)},this._finishLoading())}))}getCanvas(){return this.canvas}onAdd(M){this.map=M,this.load(),this.canvas&&this.animate&&this.play()}onRemove(){this.pause()}prepare(){let M=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,M=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,M=!0),this._hasInvalidDimensions())return;if(0===Object.keys(this.tiles).length)return;const Bt=this.map.painter.context,Wt=Bt.gl;this.texture?(M||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new v(Bt,this.canvas,Wt.RGBA,{premultiply:!0});let Nt=!1;for(const M in this.tiles){const et=this.tiles[M];"loaded"!==et.state&&(et.state="loaded",et.texture=this.texture,Nt=!0)}Nt&&this.fire(new et.k("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const M of[this.canvas.width,this.canvas.height])if(isNaN(M)||M<=0)return!0;return!1}}const za={},ee=M=>{switch(M){case"geojson":return $;case"image":return K;case"raster":return W;case"raster-dem":return X;case"vector":return H;case"video":return Y;case"canvas":return J}return za[M]},Fa="RTLPluginLoaded";class ie extends et.E{constructor(){super(...arguments),this.status="unavailable",this.url=null,this.dispatcher=j()}_syncState(M){return this.status=M,this.dispatcher.broadcast("SRPS",{pluginStatus:M,pluginURL:this.url}).catch((M=>{throw this.status="error",M}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null}setRTLTextPlugin(M){return et._(this,arguments,void 0,(function*(M,et=!1){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=$t.resolveURL(M),!this.url)throw new Error(`requested url ${M} is invalid`);if("unavailable"===this.status){if(!et)return this._requestImport();this.status="deferred",this._syncState(this.status)}else if("requested"===this.status)return this._requestImport()}))}_requestImport(){return et._(this,void 0,void 0,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new et.k(Fa))}))}lazyLoad(){"unavailable"===this.status?this.status="requested":"deferred"===this.status&&this._requestImport()}}let Ea=null;function oe(){return Ea||(Ea=new ie),Ea}class se{constructor(M,Bt){this.timeAdded=0,this.fadeEndTime=0,this.tileID=M,this.uid=et.a1(),this.uses=0,this.tileSize=Bt,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.rtt=[],this.rttCoords={},this.expiredRequestCount=0,this.state="loading"}registerFadeDuration(M){const et=M+this.timeAdded;etet.getLayer(M))).filter(Boolean);if(0!==M.length){Wt.layers=M,Wt.stateDependentLayerIds&&(Wt.stateDependentLayers=Wt.stateDependentLayerIds.map((et=>M.filter((M=>M.id===et))[0])));for(const et of M)Bt[et.id]=Wt}}return Bt}(M.buckets,null==Bt?void 0:Bt.style),this.hasSymbolBuckets=!1;for(const M in this.buckets){const Bt=this.buckets[M];if(Bt instanceof et.a3){if(this.hasSymbolBuckets=!0,!Wt)break;Bt.justReloaded=!0}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const M in this.buckets){const Bt=this.buckets[M];if(Bt instanceof et.a3&&Bt.hasRTLText){this.hasRTLText=!0,oe().lazyLoad();break}}this.queryPadding=0;for(const M in this.buckets){const et=this.buckets[M];this.queryPadding=Math.max(this.queryPadding,Bt.style.getLayer(M).queryRadius(et))}M.imageAtlas&&(this.imageAtlas=M.imageAtlas),M.glyphAtlasImage&&(this.glyphAtlasImage=M.glyphAtlasImage)}else this.collisionBoxArray=new et.a2}unloadVectorData(){for(const M in this.buckets)this.buckets[M].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded"}getBucket(M){return this.buckets[M.id]}upload(M){for(const et in this.buckets){const Bt=this.buckets[et];Bt.uploadPending()&&Bt.upload(M)}const et=M.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new v(M,this.imageAtlas.image,et.RGBA),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new v(M,this.glyphAtlasImage,et.ALPHA),this.glyphAtlasImage=null)}prepare(M){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(M,this.imageAtlasTexture)}queryRenderedFeatures(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:Wt,cameraQueryGeometry:Nt,scale:$t,tileSize:this.tileSize,pixelPosMatrix:so,transform:mn,params:Gr,queryPadding:this.queryPadding*Hn},M,et,Bt):{}}querySourceFeatures(M,Bt){const Wt=this.latestFeatureIndex;if(!Wt||!Wt.rawTileData)return;const Nt=Wt.loadVTLayers(),$t=Bt&&Bt.sourceLayer?Bt.sourceLayer:"",Gr=Nt._geojsonTileLayer||Nt[$t];if(!Gr)return;const mn=et.a4(Bt&&Bt.filter),{z:Hn,x:so,y:uo}=this.tileID.canonical,Io={z:Hn,x:so,y:uo};for(let Bt=0;BtM)et=!1;else if(Bt)if(this.expirationTime{this.remove(M,Nt)}),Bt)),this.data[Wt].push(Nt),this.order.push(Wt),this.order.length>this.max){const M=this._getAndRemoveByKey(this.order[0]);M&&this.onRemove(M)}return this}has(M){return M.wrapped().key in this.data}getAndRemove(M){return this.has(M)?this._getAndRemoveByKey(M.wrapped().key):null}_getAndRemoveByKey(M){const et=this.data[M].shift();return et.timeout&&clearTimeout(et.timeout),0===this.data[M].length&&delete this.data[M],this.order.splice(this.order.indexOf(M),1),et.value}getByKey(M){const et=this.data[M];return et?et[0].value:null}get(M){return this.has(M)?this.data[M.wrapped().key][0].value:null}remove(M,et){if(!this.has(M))return this;const Bt=M.wrapped().key,Wt=void 0===et?0:this.data[Bt].indexOf(et),Nt=this.data[Bt][Wt];return this.data[Bt].splice(Wt,1),Nt.timeout&&clearTimeout(Nt.timeout),0===this.data[Bt].length&&delete this.data[Bt],this.onRemove(Nt.value),this.order.splice(this.order.indexOf(Bt),1),this}setMaxSize(M){for(this.max=M;this.order.length>this.max;){const M=this._getAndRemoveByKey(this.order[0]);M&&this.onRemove(M)}return this}filter(M){const et=[];for(const Bt in this.data)for(const Wt of this.data[Bt])M(Wt.value)||et.push(Wt);for(const M of et)this.remove(M.value.tileID,M)}}class ne{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(M,Bt,Wt){const Nt=String(Bt);if(this.stateChanges[M]=this.stateChanges[M]||{},this.stateChanges[M][Nt]=this.stateChanges[M][Nt]||{},et.e(this.stateChanges[M][Nt],Wt),null===this.deletedStates[M]){this.deletedStates[M]={};for(const et in this.state[M])et!==Nt&&(this.deletedStates[M][et]=null)}else if(this.deletedStates[M]&&null===this.deletedStates[M][Nt]){this.deletedStates[M][Nt]={};for(const et in this.state[M][Nt])Wt[et]||(this.deletedStates[M][Nt][et]=null)}else for(const et in Wt)this.deletedStates[M]&&this.deletedStates[M][Nt]&&null===this.deletedStates[M][Nt][et]&&delete this.deletedStates[M][Nt][et]}removeFeatureState(M,et,Bt){if(null===this.deletedStates[M])return;const Wt=String(et);if(this.deletedStates[M]=this.deletedStates[M]||{},Bt&&void 0!==et)null!==this.deletedStates[M][Wt]&&(this.deletedStates[M][Wt]=this.deletedStates[M][Wt]||{},this.deletedStates[M][Wt][Bt]=null);else if(void 0!==et)if(this.stateChanges[M]&&this.stateChanges[M][Wt])for(Bt in this.deletedStates[M][Wt]={},this.stateChanges[M][Wt])this.deletedStates[M][Wt][Bt]=null;else this.deletedStates[M][Wt]=null;else this.deletedStates[M]=null}getState(M,Bt){const Wt=String(Bt),Nt=et.e({},(this.state[M]||{})[Wt],(this.stateChanges[M]||{})[Wt]);if(null===this.deletedStates[M])return{};if(this.deletedStates[M]){const et=this.deletedStates[M][Bt];if(null===et)return{};for(const M in et)delete Nt[M]}return Nt}initializeTileState(M,et){M.setFeatureState(this.state,et)}coalesceChanges(M,Bt){const Wt={};for(const M in this.stateChanges){this.state[M]=this.state[M]||{};const Bt={};for(const Wt in this.stateChanges[M])this.state[M][Wt]||(this.state[M][Wt]={}),et.e(this.state[M][Wt],this.stateChanges[M][Wt]),Bt[Wt]=this.state[M][Wt];Wt[M]=Bt}for(const M in this.deletedStates){this.state[M]=this.state[M]||{};const Bt={};if(null===this.deletedStates[M])for(const et in this.state[M])Bt[et]={},this.state[M][et]={};else for(const et in this.deletedStates[M]){if(null===this.deletedStates[M][et])this.state[M][et]={};else for(const Bt of Object.keys(this.deletedStates[M][et]))delete this.state[M][et][Bt];Bt[et]=this.state[M][et]}Wt[M]=Wt[M]||{},et.e(Wt[M],Bt)}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(Wt).length)for(const et in M)M[et].setFeatureState(Wt,Bt)}}function le(M,et,Bt){const Wt=et.intersectsFrustum(M);if(!Bt)return Wt;const Nt=et.intersectsPlane(Bt);return 0===Wt||0===Nt?0:2===Wt&&2===Nt?2:1}function ce(M,Bt,Wt,Nt,$t){let Gr=M;const mn=Math.atan(Bt/Wt),Hn=Math.hypot(Bt,Wt);return Gr=M+et.a8(Nt/Hn/Math.max(.5,Math.cos(et.aa($t/2)))),Gr+=1*et.a8(Math.cos(mn))/2,Gr+=et.ab(M-Gr,-0,0),Gr}function he(M,Bt){const Wt=(Bt.roundZoom?Math.round:Math.floor)(M.zoom+et.a8(M.tileSize/Bt.tileSize));return Math.max(0,Wt)}function ue(M,Bt){const Wt=M.getCameraFrustum(),Nt=M.getClippingPlane(),$t=M.screenPointToMercatorCoordinate(M.getCameraPoint()),Gr=et.Y.fromLngLat(M.center,M.elevation);$t.z=Gr.z+Math.cos(M.pitchInRadians)*M.cameraToCenterDistance/M.worldSize;const mn=M.getCoveringTilesDetailsProvider(),Hn=mn.allowVariableZoom(M,Bt),so=he(M,Bt),uo=Bt.minzoom||0,Io=void 0!==Bt.maxzoom?Bt.maxzoom:M.maxZoom,Po=Math.min(Math.max(0,so),Io),To=Math.pow(2,Po),Eo=[To*$t.x,To*$t.y,0],Ia=[To*Gr.x,To*Gr.y,0],Ba=Math.hypot(Gr.x-$t.x,Gr.y-$t.y),Ta=Math.abs(Gr.z-$t.z),Va=Math.hypot(Ba,Ta),x=M=>({zoom:0,x:0,y:0,wrap:M,fullyVisible:!1}),za=[],Fa=[];if(M.renderWorldCopies&&mn.allowWorldCopies())for(let M=1;M<=3;M++)za.push(x(-M)),za.push(x(M));for(za.push(x(0));za.length>0;){const To=za.pop(),Ba=To.x,Ea=To.y;let La=To.fullyVisible;const Da={x:Ba,y:Ea,z:To.zoom},Ka=mn.getTileAABB(Da,To.wrap,M.elevation,Bt);if(!La){const M=le(Wt,Ka,Nt);if(0===M)continue;La=2===M}const Oa=mn.distanceToTile2d($t.x,$t.y,Da,Ka);let $a=so;Hn&&($a=(Bt.calculateTileZoom||ce)(M.zoom+et.a8(M.tileSize/Bt.tileSize),Oa,Ta,Va,M.fov)),$a=(Bt.roundZoom?Math.round:Math.floor)($a),$a=Math.max(0,$a);const Al=Math.min($a,Io);if(To.wrap=mn.getWrap(Gr,Da,To.wrap),To.zoom>=Al){if(To.zoom>1),wrap:To.wrap,fullyVisible:La})}return Fa.sort(((M,et)=>M.distanceSq-et.distanceSq)).map((M=>M.tileID))}class de extends et.E{constructor(M,et,Bt){super(),this.id=M,this.dispatcher=Bt,this.on("data",(M=>this._dataHandler(M))),this.on("dataloading",(()=>{this._sourceErrored=!1})),this.on("error",(()=>{this._sourceErrored=this._source.loaded()})),this._source=((M,et,Bt,Wt)=>{const Nt=new(ee(et.type))(M,et,Bt,Wt);if(Nt.id!==M)throw new Error(`Expected Source id to be ${M} instead of ${Nt.id}`);return Nt})(M,et,Bt,this),this._tiles={},this._cache=new ae(0,(M=>this._unloadTile(M))),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new ne,this._didEmitContent=!1,this._updated=!1}onAdd(M){this.map=M,this._maxTileCacheSize=M?M._maxTileCacheSize:null,this._maxTileCacheZoomLevels=M?M._maxTileCacheZoomLevels:null,this._source&&this._source.onAdd&&this._source.onAdd(M)}onRemove(M){this.clearTiles(),this._source&&this._source.onRemove&&this._source.onRemove(M)}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded)return!1;if(!this._source.loaded())return!1;if(!(void 0===this.used&&void 0===this.usedForTerrain||this.used||this.usedForTerrain))return!0;if(!this._updated)return!1;for(const M in this._tiles){const et=this._tiles[M];if("loaded"!==et.state&&"errored"!==et.state)return!1}return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const M=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,M&&this.reload(),this.transform&&this.update(this.transform,this.terrain)}_loadTile(M,Bt,Wt){return et._(this,void 0,void 0,(function*(){try{yield this._source.loadTile(M),this._tileLoaded(M,Bt,Wt)}catch(Bt){M.state="errored",404!==Bt.status?this._source.fire(new et.j(Bt,{tile:M})):this.update(this.transform,this.terrain)}}))}_unloadTile(M){this._source.unloadTile&&this._source.unloadTile(M)}_abortTile(M){this._source.abortTile&&this._source.abortTile(M),this._source.fire(new et.k("dataabort",{tile:M,coord:M.tileID,dataType:"source"}))}serialize(){return this._source.serialize()}prepare(M){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const et in this._tiles){const Bt=this._tiles[et];Bt.upload(M),Bt.prepare(this.map.style.imageManager)}}getIds(){return Object.values(this._tiles).map((M=>M.tileID)).sort(_e).map((M=>M.key))}getRenderableIds(M){const Bt=[];for(const et in this._tiles)this._isIdRenderable(et,M)&&Bt.push(this._tiles[et]);return M?Bt.sort(((M,Bt)=>{const Wt=M.tileID,Nt=Bt.tileID,$t=new et.P(Wt.canonical.x,Wt.canonical.y)._rotate(-this.transform.bearingInRadians),Gr=new et.P(Nt.canonical.x,Nt.canonical.y)._rotate(-this.transform.bearingInRadians);return Wt.overscaledZ-Nt.overscaledZ||Gr.y-$t.y||Gr.x-$t.x})).map((M=>M.tileID.key)):Bt.map((M=>M.tileID)).sort(_e).map((M=>M.key))}hasRenderableParent(M){const et=this.findLoadedParent(M,0);return!!et&&this._isIdRenderable(et.tileID.key)}_isIdRenderable(M,et){return this._tiles[M]&&this._tiles[M].hasData()&&!this._coveredTiles[M]&&(et||!this._tiles[M].holdingForFade())}reload(M){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const et in this._tiles)(M||"errored"!==this._tiles[et].state)&&this._reloadTile(et,"reloading")}}_reloadTile(M,Bt){return et._(this,void 0,void 0,(function*(){const et=this._tiles[M];et&&("loading"!==et.state&&(et.state=Bt),yield this._loadTile(et,M,Bt))}))}_tileLoaded(M,Bt,Wt){M.timeAdded=$t.now(),"expired"===Wt&&(M.refreshedUponExpiration=!0),this._setTileReloadTimer(Bt,M),"raster-dem"===this.getSource().type&&M.dem&&this._backfillDEM(M),this._state.initializeTileState(M,this.map?this.map.painter:null),M.aborted||this._source.fire(new et.k("data",{dataType:"source",tile:M,coord:M.tileID}))}_backfillDEM(M){const et=this.getRenderableIds();for(let Bt=0;Bt1||(Math.abs(Bt)>1&&(1===Math.abs(Bt+Nt)?Bt+=Nt:1===Math.abs(Bt-Nt)&&(Bt-=Nt)),et.dem&&M.dem&&(M.dem.backfillBorder(et.dem,Bt,Wt),M.neighboringTiles&&M.neighboringTiles[$t]&&(M.neighboringTiles[$t].backfilled=!0)))}}getTile(M){return this.getTileByID(M.key)}getTileByID(M){return this._tiles[M]}_retainLoadedChildren(M,et,Bt,Wt){for(const Nt in this._tiles){let $t=this._tiles[Nt];if(Wt[Nt]||!$t.hasData()||$t.tileID.overscaledZ<=et||$t.tileID.overscaledZ>Bt)continue;let Gr=$t.tileID;for(;$t&&$t.tileID.overscaledZ>et+1;){const M=$t.tileID.scaledTo($t.tileID.overscaledZ-1);$t=this._tiles[M.key],$t&&$t.hasData()&&(Gr=M)}let mn=Gr;for(;mn.overscaledZ>et;)if(mn=mn.scaledTo(mn.overscaledZ-1),M[mn.key]||M[mn.canonical.key]){Wt[Gr.key]=Gr;break}}}findLoadedParent(M,et){if(M.key in this._loadedParentTiles){const Bt=this._loadedParentTiles[M.key];return Bt&&Bt.tileID.overscaledZ>=et?Bt:null}for(let Bt=M.overscaledZ-1;Bt>=et;Bt--){const et=M.scaledTo(Bt),Wt=this._getLoadedTile(et);if(Wt)return Wt}}findLoadedSibling(M){return this._getLoadedTile(M)}_getLoadedTile(M){const et=this._tiles[M.key];return et&&et.hasData()?et:this._cache.getByKey(M.wrapped().key)}updateCacheSize(M){const Bt=Math.ceil(M.width/this._source.tileSize)+1,Wt=Math.ceil(M.height/this._source.tileSize)+1,Nt=Math.floor(Bt*Wt*(null===this._maxTileCacheZoomLevels?et.a.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),$t="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,Nt):Nt;this._cache.setMaxSize($t)}handleWrapJump(M){const et=Math.round((M-(void 0===this._prevLng?M:this._prevLng))/360);if(this._prevLng=M,et){const M={};for(const Bt in this._tiles){const Wt=this._tiles[Bt];Wt.tileID=Wt.tileID.unwrapTo(Wt.tileID.wrap+et),M[Wt.tileID.key]=Wt}this._tiles=M;for(const M in this._timers)clearTimeout(this._timers[M]),delete this._timers[M];for(const M in this._tiles)this._setTileReloadTimer(M,this._tiles[M])}}_updateCoveredAndRetainedTiles(M,et,Bt,Wt,Nt,Gr){const mn={},Hn={},so=Object.keys(M),uo=$t.now();for(const Bt of so){const Wt=M[Bt],Nt=this._tiles[Bt];if(!Nt||0!==Nt.fadeEndTime&&Nt.fadeEndTime<=uo)continue;const $t=this.findLoadedParent(Wt,et),Gr=this.findLoadedSibling(Wt),so=$t||Gr||null;so&&(this._addTile(so.tileID),mn[so.tileID.key]=so.tileID),Hn[Bt]=Wt}this._retainLoadedChildren(Hn,Wt,Bt,M);for(const et in mn)M[et]||(this._coveredTiles[et]=!0,M[et]=mn[et]);if(Gr){const et={},Bt={};for(const M of Nt)this._tiles[M.key].hasData()?et[M.key]=M:Bt[M.key]=M;for(const Wt in Bt){const Nt=Bt[Wt].children(this._source.maxzoom);this._tiles[Nt[0].key]&&this._tiles[Nt[1].key]&&this._tiles[Nt[2].key]&&this._tiles[Nt[3].key]&&(et[Nt[0].key]=M[Nt[0].key]=Nt[0],et[Nt[1].key]=M[Nt[1].key]=Nt[1],et[Nt[2].key]=M[Nt[2].key]=Nt[2],et[Nt[3].key]=M[Nt[3].key]=Nt[3],delete Bt[Wt])}for(const Wt in Bt){const Nt=Bt[Wt],$t=this.findLoadedParent(Nt,this._source.minzoom),Gr=this.findLoadedSibling(Nt),mn=$t||Gr||null;if(mn){et[mn.tileID.key]=M[mn.tileID.key]=mn.tileID;for(const M in et)et[M].isChildOf(mn.tileID)&&delete et[M]}}for(const M in this._tiles)et[M]||(this._coveredTiles[M]=!0)}}update(M,Bt){if(!this._sourceLoaded||this._paused)return;let Wt;this.transform=M,this.terrain=Bt,this.updateCacheSize(M),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used||this.usedForTerrain?this._source.tileID?Wt=M.getVisibleUnwrappedCoordinates(this._source.tileID).map((M=>new et.S(M.canonical.z,M.wrap,M.canonical.z,M.canonical.x,M.canonical.y))):(Wt=ue(M,{tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:Bt,calculateTileZoom:this._source.calculateTileZoom}),this._source.hasTile&&(Wt=Wt.filter((M=>this._source.hasTile(M))))):Wt=[];const Nt=he(M,this._source),$t=Math.max(Nt-de.maxOverzooming,this._source.minzoom),Gr=Math.max(Nt+de.maxUnderzooming,this._source.minzoom);if(this.usedForTerrain){const M={};for(const et of Wt)if(et.canonical.z>this._source.minzoom){const Bt=et.scaledTo(et.canonical.z-1);M[Bt.key]=Bt;const Wt=et.scaledTo(Math.max(this._source.minzoom,Math.min(et.canonical.z,5)));M[Wt.key]=Wt}Wt=Wt.concat(Object.values(M))}const mn=0===Wt.length&&!this._updated&&this._didEmitContent;this._updated=!0,mn&&this.fire(new et.k("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));const Hn=this._updateRetainedTiles(Wt,Nt);pe(this._source.type)&&this._updateCoveredAndRetainedTiles(Hn,$t,Gr,Nt,Wt,Bt);for(const M in Hn)this._tiles[M].clearFadeHold();const so=et.ac(this._tiles,Hn);for(const M of so){const et=this._tiles[M];et.hasSymbolBuckets&&!et.holdingForFade()?et.setHoldDuration(this.map._fadeDuration):et.hasSymbolBuckets&&!et.symbolFadeFinished()||this._removeTile(M)}this._updateLoadedParentTileCache(),this._updateLoadedSiblingTileCache()}releaseSymbolFadeTiles(){for(const M in this._tiles)this._tiles[M].holdingForFade()&&this._removeTile(M)}_updateRetainedTiles(M,et){var Bt;const Wt={},Nt={},$t=Math.max(et-de.maxOverzooming,this._source.minzoom),Gr=Math.max(et+de.maxUnderzooming,this._source.minzoom),mn={};for(const Bt of M){const M=this._addTile(Bt);Wt[Bt.key]=Bt,M.hasData()||etthis._source.maxzoom){const M=Gr.children(this._source.maxzoom)[0],et=this.getTile(M);if(et&&et.hasData()){Wt[M.key]=M;continue}}else{const M=Gr.children(this._source.maxzoom);if(Wt[M[0].key]&&Wt[M[1].key]&&Wt[M[2].key]&&Wt[M[3].key])continue}let mn=M.wasRequested();for(let et=Gr.overscaledZ-1;et>=$t;--et){const $t=Gr.scaledTo(et);if(Nt[$t.key])break;if(Nt[$t.key]=!0,M=this.getTile($t),!M&&mn&&(M=this._addTile($t)),M){const et=M.hasData();if((et||!(null===(Bt=this.map)||void 0===Bt?void 0:Bt.cancelPendingTileRequestsWhileZooming)||mn)&&(Wt[$t.key]=$t),mn=M.wasRequested(),et)break}}}return Wt}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const M in this._tiles){const et=[];let Bt,Wt=this._tiles[M].tileID;for(;Wt.overscaledZ>0;){if(Wt.key in this._loadedParentTiles){Bt=this._loadedParentTiles[Wt.key];break}et.push(Wt.key);const M=Wt.scaledTo(Wt.overscaledZ-1);if(Bt=this._getLoadedTile(M),Bt)break;Wt=M}for(const M of et)this._loadedParentTiles[M]=Bt}}_updateLoadedSiblingTileCache(){this._loadedSiblingTiles={};for(const M in this._tiles){const et=this._tiles[M].tileID,Bt=this._getLoadedTile(et);this._loadedSiblingTiles[et.key]=Bt}}_addTile(M){let Bt=this._tiles[M.key];if(Bt)return Bt;Bt=this._cache.getAndRemove(M),Bt&&(this._setTileReloadTimer(M.key,Bt),Bt.tileID=M,this._state.initializeTileState(Bt,this.map?this.map.painter:null),this._cacheTimers[M.key]&&(clearTimeout(this._cacheTimers[M.key]),delete this._cacheTimers[M.key],this._setTileReloadTimer(M.key,Bt)));const Wt=Bt;return Bt||(Bt=new se(M,this._source.tileSize*M.overscaleFactor()),this._loadTile(Bt,M.key,Bt.state)),Bt.uses++,this._tiles[M.key]=Bt,Wt||this._source.fire(new et.k("dataloading",{tile:Bt,coord:Bt.tileID,dataType:"source"})),Bt}_setTileReloadTimer(M,et){M in this._timers&&(clearTimeout(this._timers[M]),delete this._timers[M]);const Bt=et.getExpiryTimeout();Bt&&(this._timers[M]=setTimeout((()=>{this._reloadTile(M,"expired"),delete this._timers[M]}),Bt))}_removeTile(M){const et=this._tiles[M];et&&(et.uses--,delete this._tiles[M],this._timers[M]&&(clearTimeout(this._timers[M]),delete this._timers[M]),et.uses>0||(et.hasData()&&"reloading"!==et.state?this._cache.add(et.tileID,et,et.getExpiryTimeout()):(et.aborted=!0,this._abortTile(et),this._unloadTile(et))))}_dataHandler(M){const et=M.sourceDataType;"source"===M.dataType&&"metadata"===et&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&"source"===M.dataType&&"content"===et&&(this.reload(M.sourceDataChanged),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=!0)}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const M in this._tiles)this._removeTile(M);this._cache.reset()}tilesIn(M,Bt,Wt){const Nt=[],$t=this.transform;if(!$t)return Nt;const Gr=Wt?$t.getCameraQueryGeometry(M):M,mn=M.map((M=>$t.screenPointToMercatorCoordinate(M,this.terrain))),Hn=Gr.map((M=>$t.screenPointToMercatorCoordinate(M,this.terrain))),so=this.getIds();let uo=1/0,Io=1/0,Po=-1/0,To=-1/0;for(const M of Hn)uo=Math.min(uo,M.x),Io=Math.min(Io,M.y),Po=Math.max(Po,M.x),To=Math.max(To,M.y);for(let M=0;M=0&&Ba[1].y+Ia>=0){const M=mn.map((M=>Gr.getTilePoint(M))),et=Hn.map((M=>Gr.getTilePoint(M)));Nt.push({tile:Wt,tileID:Gr,queryGeometry:M,cameraQueryGeometry:et,scale:Eo})}}return Nt}getVisibleCoordinates(M){const et=this.getRenderableIds(M).map((M=>this._tiles[M].tileID));return this.transform&&this.transform.populateCache(et),et}hasTransition(){if(this._source.hasTransition())return!0;if(pe(this._source.type)){const M=$t.now();for(const et in this._tiles)if(this._tiles[et].fadeEndTime>=M)return!0}return!1}setFeatureState(M,et,Bt){this._state.updateState(M=M||"_geojsonTileLayer",et,Bt)}removeFeatureState(M,et,Bt){this._state.removeFeatureState(M=M||"_geojsonTileLayer",et,Bt)}getFeatureState(M,et){return this._state.getState(M=M||"_geojsonTileLayer",et)}setDependencies(M,et,Bt){const Wt=this._tiles[M];Wt&&Wt.setDependencies(et,Bt)}reloadTilesForDependencies(M,et){for(const Bt in this._tiles)this._tiles[Bt].hasDependency(M,et)&&this._reloadTile(Bt,"reloading");this._cache.filter((Bt=>!Bt.hasDependency(M,et)))}}function _e(M,et){const Bt=Math.abs(2*M.wrap)-+(M.wrap<0),Wt=Math.abs(2*et.wrap)-+(et.wrap<0);return M.overscaledZ-et.overscaledZ||Wt-Bt||et.canonical.y-M.canonical.y||et.canonical.x-M.canonical.x}function pe(M){return"raster"===M||"image"===M||"video"===M}de.maxOverzooming=10,de.maxUnderzooming=3;class me{constructor(M,et){this.reset(M,et)}reset(M,et){this.points=M||[],this._distances=[0];for(let M=1;M0?(Nt-Gr)/mn:0;return this.points[$t].mult(1-Hn).add(this.points[Bt].mult(Hn))}}function fe(M,et){let Bt=!0;return"always"===M||"never"!==M&&"never"!==et||(Bt=!1),Bt}class ge{constructor(M,et,Bt){const Wt=this.boxCells=[],Nt=this.circleCells=[];this.xCellCount=Math.ceil(M/Bt),this.yCellCount=Math.ceil(et/Bt);for(let M=0;Mthis.width||Wt<0||et>this.height)return[];const mn=[];if(M<=0&&et<=0&&this.width<=Bt&&this.height<=Wt){if(Nt)return[{key:null,x1:M,y1:et,x2:Bt,y2:Wt}];for(let M=0;M0}hitTestCircle(M,et,Bt,Wt,Nt){const $t=M-Bt,Gr=M+Bt,mn=et-Bt,Hn=et+Bt;if(Gr<0||$t>this.width||Hn<0||mn>this.height)return!1;const so=[];return this._forEachCell($t,mn,Gr,Hn,this._queryCellCircle,so,{hitTest:!0,overlapMode:Wt,circle:{x:M,y:et,radius:Bt},seenUids:{box:{},circle:{}}},Nt),so.length>0}_queryCell(M,et,Bt,Wt,Nt,$t,Gr,mn){const{seenUids:Hn,hitTest:so,overlapMode:uo}=Gr,Io=this.boxCells[Nt];if(null!==Io){const Nt=this.bboxes;for(const Gr of Io)if(!Hn.box[Gr]){Hn.box[Gr]=!0;const Io=4*Gr,Po=this.boxKeys[Gr];if(M<=Nt[Io+2]&&et<=Nt[Io+3]&&Bt>=Nt[Io+0]&&Wt>=Nt[Io+1]&&(!mn||mn(Po))&&(!so||!fe(uo,Po.overlapMode))&&($t.push({key:Po,x1:Nt[Io],y1:Nt[Io+1],x2:Nt[Io+2],y2:Nt[Io+3]}),so))return!0}}const Po=this.circleCells[Nt];if(null!==Po){const Nt=this.circles;for(const Gr of Po)if(!Hn.circle[Gr]){Hn.circle[Gr]=!0;const Io=3*Gr,Po=this.circleKeys[Gr];if(this._circleAndRectCollide(Nt[Io],Nt[Io+1],Nt[Io+2],M,et,Bt,Wt)&&(!mn||mn(Po))&&(!so||!fe(uo,Po.overlapMode))){const M=Nt[Io],et=Nt[Io+1],Bt=Nt[Io+2];if($t.push({key:Po,x1:M-Bt,y1:et-Bt,x2:M+Bt,y2:et+Bt}),so)return!0}}}return!1}_queryCellCircle(M,et,Bt,Wt,Nt,$t,Gr,mn){const{circle:Hn,seenUids:so,overlapMode:uo}=Gr,Io=this.boxCells[Nt];if(null!==Io){const M=this.bboxes;for(const et of Io)if(!so.box[et]){so.box[et]=!0;const Bt=4*et,Wt=this.boxKeys[et];if(this._circleAndRectCollide(Hn.x,Hn.y,Hn.radius,M[Bt+0],M[Bt+1],M[Bt+2],M[Bt+3])&&(!mn||mn(Wt))&&!fe(uo,Wt.overlapMode))return $t.push(!0),!0}}const Po=this.circleCells[Nt];if(null!==Po){const M=this.circles;for(const et of Po)if(!so.circle[et]){so.circle[et]=!0;const Bt=3*et,Wt=this.circleKeys[et];if(this._circlesCollide(M[Bt],M[Bt+1],M[Bt+2],Hn.x,Hn.y,Hn.radius)&&(!mn||mn(Wt))&&!fe(uo,Wt.overlapMode))return $t.push(!0),!0}}}_forEachCell(M,et,Bt,Wt,Nt,$t,Gr,mn){const Hn=this._convertToXCellCoord(M),so=this._convertToYCellCoord(et),uo=this._convertToXCellCoord(Bt),Io=this._convertToYCellCoord(Wt);for(let Po=Hn;Po<=uo;Po++)for(let Hn=so;Hn<=Io;Hn++)if(Nt.call(this,M,et,Bt,Wt,this.xCellCount*Hn+Po,$t,Gr,mn))return}_convertToXCellCoord(M){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(M*this.xScale)))}_convertToYCellCoord(M){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(M*this.yScale)))}_circlesCollide(M,et,Bt,Wt,Nt,$t){const Gr=Wt-M,mn=Nt-et,Hn=Bt+$t;return Hn*Hn>Gr*Gr+mn*mn}_circleAndRectCollide(M,et,Bt,Wt,Nt,$t,Gr){const mn=($t-Wt)/2,Hn=Math.abs(M-(Wt+mn));if(Hn>mn+Bt)return!1;const so=(Gr-Nt)/2,uo=Math.abs(et-(Nt+so));if(uo>so+Bt)return!1;if(Hn<=mn||uo<=so)return!0;const Io=Hn-mn,Po=uo-so;return Io*Io+Po*Po<=Bt*Bt}}function ve(M,Bt,Wt){const Nt=et.H();if(!M){const{vecSouth:M,vecEast:et}=be(Bt),Wt=r();Wt[0]=et[0],Wt[1]=et[1],Wt[2]=M[0],Wt[3]=M[1],$t=Wt,(Io=(mn=(Gr=Wt)[0])*(uo=Gr[3])-(so=Gr[2])*(Hn=Gr[1]))&&($t[0]=uo*(Io=1/Io),$t[1]=-Hn*Io,$t[2]=-so*Io,$t[3]=mn*Io),Nt[0]=Wt[0],Nt[1]=Wt[1],Nt[4]=Wt[2],Nt[5]=Wt[3]}var $t,Gr,mn,Hn,so,uo,Io;return et.K(Nt,Nt,[1/Wt,1/Wt,1]),Nt}function xe(M,Bt,Wt,Nt){if(M){const M=et.H();if(!Bt){const{vecSouth:et,vecEast:Bt}=be(Wt);M[0]=Bt[0],M[1]=Bt[1],M[4]=et[0],M[5]=et[1]}return et.K(M,M,[Nt,Nt,1]),M}return Wt.pixelsToClipSpaceMatrix}function be(M){const Bt=Math.cos(M.rollInRadians),Wt=Math.sin(M.rollInRadians),Nt=Math.cos(M.pitchInRadians),$t=Math.cos(M.bearingInRadians),Gr=Math.sin(M.bearingInRadians),mn=et.ad();mn[0]=-$t*Nt*Wt-Gr*Bt,mn[1]=-Gr*Nt*Wt+$t*Bt;const Hn=et.ae(mn);Hn<1e-9?et.af(mn):et.ag(mn,mn,1/Hn);const so=et.ad();so[0]=$t*Nt*Bt-Gr*Wt,so[1]=Gr*Nt*Bt+$t*Wt;const uo=et.ae(so);return uo<1e-9?et.af(so):et.ag(so,so,1/uo),{vecEast:so,vecSouth:mn}}function ye(M,Bt,Wt,Nt){let $t;Nt?($t=[M,Bt,Nt(M,Bt),1],et.al($t,$t,Wt)):($t=[M,Bt,0,1],je($t,$t,Wt));const Gr=$t[3];return{point:new et.P($t[0]/Gr,$t[1]/Gr),signedDistanceFromCamera:Gr,isOccluded:!1}}function we(M,et){return.5+M/et*.5}function Te(M,et){return M.x>=-et[0]&&M.x<=et[0]&&M.y>=-et[1]&&M.y<=et[1]}function Pe(M,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To){const Eo=Wt?M.textSizeData:M.iconSizeData,Ia=et.ah(Eo,Bt.transform.zoom),Ba=[256/Bt.width*2+1,256/Bt.height*2+1],Ta=Wt?M.text.dynamicLayoutVertexArray:M.icon.dynamicLayoutVertexArray;Ta.clear();const Va=M.lineVertexArray,za=Wt?M.text.placedSymbolArray:M.icon.placedSymbolArray,Fa=Bt.transform.width/Bt.transform.height;let Ea=!1;for(let Wt=0;WtMath.abs(Wt.x-Bt.x)*Nt?{useVertical:!0}:(M===et.ai.vertical?Bt.yWt.x)?{needsFlipping:!0}:null}function Ee(M){const{projectionContext:Bt,pitchedLabelPlaneMatrixInverse:Wt,symbol:Nt,fontSize:$t,flip:Gr,keepUpright:mn,glyphOffsetArray:Hn,dynamicLayoutVertexArray:so,aspectRatio:uo,rotateToLine:Io}=M,Po=$t/24,To=Nt.lineOffsetX*Po,Eo=Nt.lineOffsetY*Po;let Ia;if(Nt.numGlyphs>1){const M=Nt.glyphStartIndex+Nt.numGlyphs,et=Nt.lineStartIndex,$t=Nt.lineStartIndex+Nt.lineLength,so=Ce(Po,Hn,To,Eo,Gr,Nt,Io,Bt);if(!so)return{notEnoughRoom:!0};const Ba=De(so.first.point.x,so.first.point.y,Bt,Wt),Ta=De(so.last.point.x,so.last.point.y,Bt,Wt);if(mn&&!Gr){const M=Ie(Nt.writingMode,Ba,Ta,uo);if(M)return M}Ia=[so.first];for(let Wt=Nt.glyphStartIndex+1;Wt0?mn.point:Me(Bt.tileAnchorPoint,Gr,M,1,Bt),so=De(M.x,M.y,Bt,Wt),Io=De(Hn.x,Hn.y,Bt,Wt),Po=Ie(Nt.writingMode,so,Io,uo);if(Po)return Po}const M=ke(Po*Hn.getoffsetX(Nt.glyphStartIndex),To,Eo,Gr,Nt.segment,Nt.lineStartIndex,Nt.lineStartIndex+Nt.lineLength,Bt,Io);if(!M||Bt.projectionCache.anyProjectionOccluded)return{notEnoughRoom:!0};Ia=[M]}for(const M of Ia)et.ak(so,M.point,M.angle);return{}}function Me(M,et,Bt,Wt,Nt){const $t=M.add(M.sub(et)._unit()),Gr=Re($t.x,$t.y,Nt).point,mn=Bt.sub(Gr);return Bt.add(mn._mult(Wt/mn.mag()))}function Se(M,Bt,Wt){const Nt=Bt.projectionCache;if(Nt.projections[M])return Nt.projections[M];const $t=new et.P(Bt.lineVertexArray.getx(M),Bt.lineVertexArray.gety(M)),Gr=Re($t.x,$t.y,Bt);if(Gr.signedDistanceFromCamera>0)return Nt.projections[M]=Gr.point,Nt.anyProjectionOccluded=Nt.anyProjectionOccluded||Gr.isOccluded,Gr.point;const mn=M-Wt.direction;return Me(0===Wt.distanceFromAnchor?Bt.tileAnchorPoint:new et.P(Bt.lineVertexArray.getx(mn),Bt.lineVertexArray.gety(mn)),$t,Wt.previousVertex,Wt.absOffsetX-Wt.distanceFromAnchor+1,Bt)}function Re(M,et,Bt){const Wt=M+Bt.translation[0],Nt=et+Bt.translation[1];let $t;return Bt.pitchWithMap?($t=ye(Wt,Nt,Bt.pitchedLabelPlaneMatrix,Bt.getElevation),$t.isOccluded=!1):($t=Bt.transform.projectTileCoordinates(Wt,Nt,Bt.unwrappedTileID,Bt.getElevation),$t.point.x=(.5*$t.point.x+.5)*Bt.width,$t.point.y=(.5*-$t.point.y+.5)*Bt.height),$t}function De(M,Bt,Wt,Nt){if(Wt.pitchWithMap){const $t=[M,Bt,0,1];return et.al($t,$t,Nt),Wt.transform.projectTileCoordinates($t[0]/$t[3],$t[1]/$t[3],Wt.unwrappedTileID,Wt.getElevation).point}return{x:M/Wt.width*2-1,y:Bt/Wt.height*2-1}}function ze(M,et,Bt){return Bt.transform.projectTileCoordinates(M,et,Bt.unwrappedTileID,Bt.getElevation)}function Ae(M,et,Bt){return M._unit()._perp()._mult(et*Bt)}function Le(M,Bt,Wt,Nt,$t,Gr,mn,Hn,so){if(Hn.projectionCache.offsets[M])return Hn.projectionCache.offsets[M];const uo=Wt.add(Bt);if(M+so.direction=$t)return Hn.projectionCache.offsets[M]=uo,uo;const Io=Se(M+so.direction,Hn,so),Po=Ae(Io.sub(Wt),mn,so.direction),To=Wt.add(Po),Eo=Io.add(Po);return Hn.projectionCache.offsets[M]=et.am(Gr,uo,To,Eo)||uo,Hn.projectionCache.offsets[M]}function ke(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn){const so=Wt?M-et:M+et;let uo=so>0?1:-1,Io=0;Wt&&(uo*=-1,Io=Math.PI),uo<0&&(Io+=Math.PI);let Po,To=uo>0?$t+Nt:$t+Nt+1;mn.projectionCache.cachedAnchorPoint?Po=mn.projectionCache.cachedAnchorPoint:(Po=Re(mn.tileAnchorPoint.x,mn.tileAnchorPoint.y,mn).point,mn.projectionCache.cachedAnchorPoint=Po);let Eo,Ia,Ba=Po,Ta=Po,Va=0,za=0;const Fa=Math.abs(so),Ea=[];let La;for(;Va+za<=Fa;){if(To+=uo,To<$t||To>=Gr)return null;Va+=za,Ta=Ba,Ia=Eo;const M={absOffsetX:Fa,direction:uo,distanceFromAnchor:Va,previousVertex:Ta};if(Ba=Se(To,mn,M),0===Bt)Ea.push(Ta),La=Ba.sub(Ta);else{let et;const Wt=Ba.sub(Ta);et=0===Wt.mag()?Ae(Se(To+uo,mn,M).sub(Ba),Bt,uo):Ae(Wt,Bt,uo),Ia||(Ia=Ta.add(et)),Eo=Le(To,et,Ba,$t,Gr,Ia,Bt,mn,M),Ea.push(Ia),La=Eo.sub(Ia)}za=La.mag()}const Da=La._mult((Fa-Va)/za)._add(Ia||Ta),Ka=Io+Math.atan2(Ba.y-Ta.y,Ba.x-Ta.x);return Ea.push(Da),{point:Da,angle:Hn?Ka:0,path:Ea}}const La=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function Be(M,et){for(let Bt=0;Bt=1;M--)To.push(Gr.path[M]);for(let M=1;MM.signedDistanceFromCamera<=0))?[]:M.map((M=>M.point))}let Ba=[];if(To.length>0){const M=To[0].clone(),Bt=To[0].clone();for(let et=1;et=Wt.x&&Bt.x<=Nt.x&&M.y>=Wt.y&&Bt.y<=Nt.y?[To]:Bt.xNt.x||Bt.yNt.y?[]:et.ao([To],Wt.x,Wt.y,Nt.x,Nt.y)}for(const et of Ba){$t.reset(et,.25*Bt);let Wt=0;Wt=$t.length<=.5*Bt?1:Math.ceil($t.paddedLength/Eo)+1;for(let et=0;et{const et=ye(M.x,M.y,Wt,Bt.getElevation),Nt=Bt.transform.projectTileCoordinates(et.point.x,et.point.y,Bt.unwrappedTileID,Bt.getElevation);return Nt.point.x=(.5*Nt.point.x+.5)*Bt.width,Nt.point.y=(.5*-Nt.point.y+.5)*Bt.height,Nt}))}(M,Bt);return function(M){let et=0,Bt=0,Wt=0,Nt=0;for(let $t=0;$tBt&&(Bt=Nt,et=Wt));return M.slice(et,et+Bt)}(Wt)}queryRenderedSymbols(M){if(0===M.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return{};const Bt=[];let Wt=1/0,Nt=1/0,$t=-1/0,Gr=-1/0;for(const mn of M){const M=new et.P(mn.x+Da,mn.y+Da);Wt=Math.min(Wt,M.x),Nt=Math.min(Nt,M.y),$t=Math.max($t,M.x),Gr=Math.max(Gr,M.y),Bt.push(M)}const mn=this.grid.query(Wt,Nt,$t,Gr).concat(this.ignoredGrid.query(Wt,Nt,$t,Gr)),Hn={},so={};for(const M of mn){const Wt=M.key;if(void 0===Hn[Wt.bucketInstanceId]&&(Hn[Wt.bucketInstanceId]={}),Hn[Wt.bucketInstanceId][Wt.featureIndex])continue;const Nt=[new et.P(M.x1,M.y1),new et.P(M.x2,M.y1),new et.P(M.x2,M.y2),new et.P(M.x1,M.y2)];et.ap(Bt,Nt)&&(Hn[Wt.bucketInstanceId][Wt.featureIndex]=!0,void 0===so[Wt.bucketInstanceId]&&(so[Wt.bucketInstanceId]=[]),so[Wt.bucketInstanceId].push(Wt.featureIndex))}return so}insertCollisionBox(M,et,Bt,Wt,Nt,$t){(Bt?this.ignoredGrid:this.grid).insert({bucketInstanceId:Wt,featureIndex:Nt,collisionGroupID:$t,overlapMode:et},M[0],M[1],M[2],M[3])}insertCollisionCircles(M,et,Bt,Wt,Nt,$t){const Gr=Bt?this.ignoredGrid:this.grid,mn={bucketInstanceId:Wt,featureIndex:Nt,collisionGroupID:$t,overlapMode:et};for(let et=0;et=this.screenRightBoundary||Wtthis.screenBottomBoundary}isInsideGrid(M,et,Bt,Wt){return Bt>=0&&M=0&&etthis.projectAndGetPerspectiveRatio(M.x,M.y,Nt,so,Io)));Zl=M.some((M=>!M.isOccluded)),Sl=M.map((M=>new et.P(M.x,M.y)))}else Zl=!0;return{box:et.ar(Sl),allPointsOccluded:!Zl}}}class Ze{constructor(M,et,Bt,Wt){this.opacity=M?Math.max(0,Math.min(1,M.opacity+(M.placed?et:-et))):Wt&&Bt?1:0,this.placed=Bt}isHidden(){return 0===this.opacity&&!this.placed}}class Ge{constructor(M,et,Bt,Wt,Nt){this.text=new Ze(M?M.text:null,et,Bt,Nt),this.icon=new Ze(M?M.icon:null,et,Wt,Nt)}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class Ue{constructor(M,et,Bt){this.text=M,this.icon=et,this.skipFade=Bt}}class Ve{constructor(M,et,Bt,Wt,Nt){this.bucketInstanceId=M,this.featureIndex=et,this.sourceLayerIndex=Bt,this.bucketIndex=Wt,this.tileID=Nt}}class qe{constructor(M){this.crossSourceCollisions=M,this.maxGroupID=0,this.collisionGroups={}}get(M){if(this.crossSourceCollisions)return{ID:0,predicate:null};if(!this.collisionGroups[M]){const et=++this.maxGroupID;this.collisionGroups[M]={ID:et,predicate:M=>M.collisionGroupID===et}}return this.collisionGroups[M]}}function He(M,Bt,Wt,Nt,$t){const{horizontalAlign:Gr,verticalAlign:mn}=et.ay(M);return new et.P(-(Gr-.5)*Bt+Nt[0]*$t,-(mn-.5)*Wt+Nt[1]*$t)}class We{constructor(M,et,Bt,Wt,Nt){this.transform=M.clone(),this.terrain=et,this.collisionIndex=new Ne(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=Bt,this.retainedQueryData={},this.collisionGroups=new qe(Wt),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=Nt,Nt&&(Nt.prevPlacement=void 0),this.placedOrientations={}}_getTerrainElevationFunc(M){const et=this.terrain;return et?(Bt,Wt)=>et.getElevation(M,Bt,Wt):null}getBucketParts(M,Bt,Wt,Nt){const $t=Wt.getBucket(Bt),Gr=Wt.latestFeatureIndex;if(!$t||!Gr||Bt.id!==$t.layerIds[0])return;const mn=Wt.collisionBoxArray,Hn=$t.layers[0].layout,so=$t.layers[0].paint,uo=Math.pow(2,this.transform.zoom-Wt.tileID.overscaledZ),Io=Wt.tileSize/et.X,Po=Wt.tileID.toUnwrapped(),To="map"===Hn.get("text-rotation-alignment"),Eo=et.at(Wt,1,this.transform.zoom),Ia=et.au(this.collisionIndex.transform,Wt,so.get("text-translate"),so.get("text-translate-anchor")),Ba=et.au(this.collisionIndex.transform,Wt,so.get("icon-translate"),so.get("icon-translate-anchor")),Ta=ve(To,this.transform,Eo);this.retainedQueryData[$t.bucketInstanceId]=new Ve($t.bucketInstanceId,Gr,$t.sourceLayerIndex,$t.index,Wt.tileID);const Va={bucket:$t,layout:Hn,translationText:Ia,translationIcon:Ba,unwrappedTileID:Po,pitchedLabelPlaneMatrix:Ta,scale:uo,textPixelRatio:Io,holdingForFade:Wt.holdingForFade(),collisionBoxArray:mn,partiallyEvaluatedTextSize:et.ah($t.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get($t.sourceID)};if(Nt)for(const et of $t.sortKeyRanges){const{sortKey:Bt,symbolInstanceStart:Wt,symbolInstanceEnd:Nt}=et;M.push({sortKey:Bt,symbolInstanceStart:Wt,symbolInstanceEnd:Nt,parameters:Va})}else M.push({symbolInstanceStart:0,symbolInstanceEnd:$t.symbolInstances.length,parameters:Va})}attemptAnchorPlacement(M,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba,Ta,Va,za,Fa){const Ea=et.av[M.textAnchor],La=[M.textOffset0,M.textOffset1],Da=He(Ea,Wt,Nt,La,$t),Ka=this.collisionIndex.placeCollisionBox(Bt,Po,Hn,so,uo,mn,Gr,Ba,Io.predicate,za,Da,Fa);if((!Va||this.collisionIndex.placeCollisionBox(Va,Po,Hn,so,uo,mn,Gr,Ta,Io.predicate,za,Da,Fa).placeable)&&Ka.placeable){let M;if(this.prevPlacement&&this.prevPlacement.variableOffsets[To.crossTileID]&&this.prevPlacement.placements[To.crossTileID]&&this.prevPlacement.placements[To.crossTileID].text&&(M=this.prevPlacement.variableOffsets[To.crossTileID].anchor),0===To.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[To.crossTileID]={textOffset:La,width:Wt,height:Nt,anchor:Ea,textBoxScale:$t,prevAnchor:M},this.markUsedJustification(Eo,Ea,To,Ia),Eo.allowVerticalPlacement&&(this.markUsedOrientation(Eo,Ia,To),this.placedOrientations[To.crossTileID]=Ia),{shift:Da,placedGlyphBoxes:Ka}}}placeLayerBucketPart(M,Bt,Wt){const{bucket:Nt,layout:$t,translationText:Gr,translationIcon:mn,unwrappedTileID:Hn,pitchedLabelPlaneMatrix:so,textPixelRatio:uo,holdingForFade:Io,collisionBoxArray:Po,partiallyEvaluatedTextSize:To,collisionGroup:Eo}=M.parameters,Ia=$t.get("text-optional"),Ba=$t.get("icon-optional"),Ta=et.aw($t,"text-overlap","text-allow-overlap"),Va="always"===Ta,za=et.aw($t,"icon-overlap","icon-allow-overlap"),Fa="always"===za,Ea="map"===$t.get("text-rotation-alignment"),La="map"===$t.get("text-pitch-alignment"),Da="none"!==$t.get("icon-text-fit"),Ka="viewport-y"===$t.get("symbol-z-order"),Oa=Va&&(Fa||!Nt.hasIconData()||Ba),$a=Fa&&(Va||!Nt.hasTextData()||Ia);!Nt.collisionArrays&&Po&&Nt.deserializeCollisionBoxes(Po);const Al=this.retainedQueryData[Nt.bucketInstanceId].tileID,Sl=this._getTerrainElevationFunc(Al),Zl=this.transform.getFastPathSimpleProjectionMatrix(Al),R=(M,Po,Fa)=>{var Ka,Gl;if(Bt[M.crossTileID])return;if(Io)return void(this.placements[M.crossTileID]=new Ue(!1,!1,!1));let Rl=!1,Tl=!1,Vl=!0,Wl=null,El={box:null,placeable:!1,offscreen:null,occluded:!1},Jl={box:null,placeable:!1,offscreen:null},Ll=null,Dl=null,Nl=null,Yl=0,Ol=0,jl=0;Po.textFeatureIndex?Yl=Po.textFeatureIndex:M.useRuntimeCollisionCircles&&(Yl=M.featureIndex),Po.verticalTextFeatureIndex&&(Ol=Po.verticalTextFeatureIndex);const Ul=Po.textBox;if(Ul){const i=Bt=>{let Wt=et.ai.horizontal;if(Nt.allowVerticalPlacement&&!Bt&&this.prevPlacement){const et=this.prevPlacement.placedOrientations[M.crossTileID];et&&(this.placedOrientations[M.crossTileID]=et,Wt=et,this.markUsedOrientation(Nt,Wt,M))}return Wt},s=(Bt,Wt)=>{if(Nt.allowVerticalPlacement&&M.numVerticalGlyphVertices>0&&Po.verticalTextBox){for(const M of Nt.writingModes)if(M===et.ai.vertical?(El=Wt(),Jl=El):El=Bt(),El&&El.placeable)break}else El=Bt()},Bt=M.textAnchorOffsetStartIndex,$t=M.textAnchorOffsetEndIndex;if($t===Bt){const r=(et,Bt)=>{const Wt=this.collisionIndex.placeCollisionBox(et,Ta,uo,Al,Hn,La,Ea,Gr,Eo.predicate,Sl,void 0,Zl);return Wt&&Wt.placeable&&(this.markUsedOrientation(Nt,Bt,M),this.placedOrientations[M.crossTileID]=Bt),Wt};s((()=>r(Ul,et.ai.horizontal)),(()=>{const Bt=Po.verticalTextBox;return Nt.allowVerticalPlacement&&M.numVerticalGlyphVertices>0&&Bt?r(Bt,et.ai.vertical):{box:null,offscreen:null}})),i(El&&El.placeable)}else{let so=et.av[null===(Gl=null===(Ka=this.prevPlacement)||void 0===Ka?void 0:Ka.variableOffsets[M.crossTileID])||void 0===Gl?void 0:Gl.anchor];const m=(et,Io,Po)=>{const To=et.x2-et.x1,Ia=et.y2-et.y1,Ba=M.textBoxScale,Va=Da&&"never"===za?Io:null;let Fa=null,Ka="never"===Ta?1:2,Oa="never";so&&Ka++;for(let Wt=0;Wtm(Ul,Po.iconBox,et.ai.horizontal)),(()=>{const Bt=Po.verticalTextBox;return Nt.allowVerticalPlacement&&(!El||!El.placeable)&&M.numVerticalGlyphVertices>0&&Bt?m(Bt,Po.verticalIconBox,et.ai.vertical):{box:null,occluded:!0,offscreen:null}})),El&&(Rl=El.placeable,Vl=El.offscreen);const Io=i(El&&El.placeable);if(!Rl&&this.prevPlacement){const et=this.prevPlacement.variableOffsets[M.crossTileID];et&&(this.variableOffsets[M.crossTileID]=et,this.markUsedJustification(Nt,et.anchor,M,Io))}}}if(Ll=El,Rl=Ll&&Ll.placeable,Vl=Ll&&Ll.offscreen,M.useRuntimeCollisionCircles){const Bt=Nt.text.placedSymbolArray.get(M.centerJustifiedTextSymbolIndex),mn=et.aj(Nt.textSizeData,To,Bt),uo=$t.get("text-padding");Dl=this.collisionIndex.placeCollisionCircles(Ta,Bt,Nt.lineVertexArray,Nt.glyphOffsetArray,mn,Hn,so,Wt,La,Eo.predicate,M.collisionCircleDiameter,uo,Gr,Sl),Dl.circles.length&&Dl.collisionDetected&&!Wt&&et.w("Collisions detected, but collision boxes are not shown"),Rl=Va||Dl.circles.length>0&&!Dl.collisionDetected,Vl=Vl&&Dl.offscreen}if(Po.iconFeatureIndex&&(jl=Po.iconFeatureIndex),Po.iconBox){const e=M=>this.collisionIndex.placeCollisionBox(M,za,uo,Al,Hn,La,Ea,mn,Eo.predicate,Sl,Da&&Wl?Wl:void 0,Zl);Jl&&Jl.placeable&&Po.verticalIconBox?(Nl=e(Po.verticalIconBox),Tl=Nl.placeable):(Nl=e(Po.iconBox),Tl=Nl.placeable),Vl=Vl&&Nl.offscreen}const ql=Ia||0===M.numHorizontalGlyphVertices&&0===M.numVerticalGlyphVertices,$l=Ba||0===M.numIconVertices;ql||$l?$l?ql||(Tl=Tl&&Rl):Rl=Tl&&Rl:Tl=Rl=Tl&&Rl;const tc=Tl&&Nl.placeable;if(Rl&&Ll.placeable&&this.collisionIndex.insertCollisionBox(Ll.box,Ta,$t.get("text-ignore-placement"),Nt.bucketInstanceId,Jl&&Jl.placeable&&Ol?Ol:Yl,Eo.ID),tc&&this.collisionIndex.insertCollisionBox(Nl.box,za,$t.get("icon-ignore-placement"),Nt.bucketInstanceId,jl,Eo.ID),Dl&&Rl&&this.collisionIndex.insertCollisionCircles(Dl.circles,Ta,$t.get("text-ignore-placement"),Nt.bucketInstanceId,Yl,Eo.ID),Wt&&this.storeCollisionData(Nt.bucketInstanceId,Fa,Po,Ll,Nl,Dl),0===M.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");if(0===Nt.bucketInstanceId)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[M.crossTileID]=new Ue((Rl||Oa)&&!(null==Ll?void 0:Ll.occluded),(Tl||$a)&&!(null==Nl?void 0:Nl.occluded),Vl||Nt.justReloaded),Bt[M.crossTileID]=!0};if(Ka){if(0!==M.symbolInstanceStart)throw new Error("bucket.bucketInstanceId should be 0");const et=Nt.getSortedSymbolIndexes(-this.transform.bearingInRadians);for(let M=et.length-1;M>=0;--M){const Bt=et[M];R(Nt.symbolInstances.get(Bt),Nt.collisionArrays[Bt],Bt)}}else for(let et=M.symbolInstanceStart;et=0&&(M.text.placedSymbolArray.get(et).crossTileID=$t>=0&&et!==$t?0:Wt.crossTileID)}markUsedOrientation(M,Bt,Wt){const Nt=Bt===et.ai.horizontal||Bt===et.ai.horizontalOnly?Bt:0,$t=Bt===et.ai.vertical?Bt:0,Gr=[Wt.leftJustifiedTextSymbolIndex,Wt.centerJustifiedTextSymbolIndex,Wt.rightJustifiedTextSymbolIndex];for(const et of Gr)M.text.placedSymbolArray.get(et).placedOrientation=Nt;Wt.verticalPlacedTextSymbolIndex&&(M.text.placedSymbolArray.get(Wt.verticalPlacedTextSymbolIndex).placedOrientation=$t)}commit(M){this.commitTime=M,this.zoomAtLastRecencyCheck=this.transform.zoom;const et=this.prevPlacement;let Bt=!1;this.prevZoomAdjustment=et?et.zoomAdjustment(this.transform.zoom):0;const Wt=et?et.symbolFadeChange(M):1,Nt=et?et.opacities:{},$t=et?et.variableOffsets:{},Gr=et?et.placedOrientations:{};for(const M in this.placements){const et=this.placements[M],$t=Nt[M];$t?(this.opacities[M]=new Ge($t,Wt,et.text,et.icon),Bt=Bt||et.text!==$t.text.placed||et.icon!==$t.icon.placed):(this.opacities[M]=new Ge(null,Wt,et.text,et.icon,et.skipFade),Bt=Bt||et.text||et.icon)}for(const M in Nt){const et=Nt[M];if(!this.opacities[M]){const Nt=new Ge(et,Wt,!1,!1);Nt.isHidden()||(this.opacities[M]=Nt,Bt=Bt||et.text.placed||et.icon.placed)}}for(const M in $t)this.variableOffsets[M]||!this.opacities[M]||this.opacities[M].isHidden()||(this.variableOffsets[M]=$t[M]);for(const M in Gr)this.placedOrientations[M]||!this.opacities[M]||this.opacities[M].isHidden()||(this.placedOrientations[M]=Gr[M]);if(et&&void 0===et.lastPlacementChangeTime)throw new Error("Last placement time for previous placement is not defined");Bt?this.lastPlacementChangeTime=M:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=et?et.lastPlacementChangeTime:M)}updateLayerOpacities(M,et){const Bt={};for(const Wt of et){const et=Wt.getBucket(M);et&&Wt.latestFeatureIndex&&M.id===et.layerIds[0]&&this.updateBucketOpacities(et,Wt.tileID,Bt,Wt.collisionBoxArray)}}updateBucketOpacities(M,Bt,Wt,Nt){M.hasTextData()&&(M.text.opacityVertexArray.clear(),M.text.hasVisibleVertices=!1),M.hasIconData()&&(M.icon.opacityVertexArray.clear(),M.icon.hasVisibleVertices=!1),M.hasIconCollisionBoxData()&&M.iconCollisionBox.collisionVertexArray.clear(),M.hasTextCollisionBoxData()&&M.textCollisionBox.collisionVertexArray.clear();const $t=M.layers[0],Gr=$t.layout,mn=new Ge(null,0,!1,!1,!0),Hn=Gr.get("text-allow-overlap"),so=Gr.get("icon-allow-overlap"),uo=$t._unevaluatedLayout.hasValue("text-variable-anchor")||$t._unevaluatedLayout.hasValue("text-variable-anchor-offset"),Io="map"===Gr.get("text-rotation-alignment"),Po="map"===Gr.get("text-pitch-alignment"),To="none"!==Gr.get("icon-text-fit"),Eo=new Ge(null,0,Hn&&(so||!M.hasIconData()||Gr.get("icon-optional")),so&&(Hn||!M.hasTextData()||Gr.get("text-optional")),!0);!M.collisionArrays&&Nt&&(M.hasIconCollisionBoxData()||M.hasTextCollisionBoxData())&&M.deserializeCollisionBoxes(Nt);const m=(M,et,Bt)=>{for(let Wt=0;Wt0,Ta=this.placedOrientations[Nt.crossTileID],Va=Ta===et.ai.vertical,za=Ta===et.ai.horizontal||Ta===et.ai.horizontalOnly;if($t>0||Gr>0){const et=it(so.text);m(M.text,$t,Va?Rl:et),m(M.text,Gr,za?Rl:et);const Bt=so.text.isHidden();[Nt.rightJustifiedTextSymbolIndex,Nt.centerJustifiedTextSymbolIndex,Nt.leftJustifiedTextSymbolIndex].forEach((et=>{et>=0&&(M.text.placedSymbolArray.get(et).hidden=Bt||Va?1:0)})),Nt.verticalPlacedTextSymbolIndex>=0&&(M.text.placedSymbolArray.get(Nt.verticalPlacedTextSymbolIndex).hidden=Bt||za?1:0);const Wt=this.variableOffsets[Nt.crossTileID];Wt&&this.markUsedJustification(M,Wt.anchor,Nt,Ta);const mn=this.placedOrientations[Nt.crossTileID];mn&&(this.markUsedJustification(M,"left",Nt,mn),this.markUsedOrientation(M,mn,Nt))}if(Ba){const et=it(so.icon),Bt=!(To&&Nt.verticalPlacedIconSymbolIndex&&Va);Nt.placedIconSymbolIndex>=0&&(m(M.icon,Nt.numIconVertices,Bt?et:Rl),M.icon.placedSymbolArray.get(Nt.placedIconSymbolIndex).hidden=so.icon.isHidden()),Nt.verticalPlacedIconSymbolIndex>=0&&(m(M.icon,Nt.numVerticalIconVertices,Bt?Rl:et),M.icon.placedSymbolArray.get(Nt.verticalPlacedIconSymbolIndex).hidden=so.icon.isHidden())}const Fa=Ia&&Ia.has(Bt)?Ia.get(Bt):{text:null,icon:null};if(M.hasIconCollisionBoxData()||M.hasTextCollisionBoxData()){const Wt=M.collisionArrays[Bt];if(Wt){let Bt=new et.P(0,0);if(Wt.textBox||Wt.verticalTextBox){let et=!0;if(uo){const M=this.variableOffsets[Hn];M?(Bt=He(M.anchor,M.width,M.height,M.textOffset,M.textBoxScale),Io&&Bt._rotate(Po?-this.transform.bearingInRadians:this.transform.bearingInRadians)):et=!1}if(Wt.textBox||Wt.verticalTextBox){let Nt;Wt.textBox&&(Nt=Va),Wt.verticalTextBox&&(Nt=za),Xe(M.textCollisionBox.collisionVertexArray,so.text.placed,!et||Nt,Fa.text,Bt.x,Bt.y)}}if(Wt.iconBox||Wt.verticalIconBox){const et=Boolean(!za&&Wt.verticalIconBox);let Nt;Wt.iconBox&&(Nt=et),Wt.verticalIconBox&&(Nt=!et),Xe(M.iconCollisionBox.collisionVertexArray,so.icon.placed,Nt,Fa.icon,To?Bt.x:0,To?Bt.y:0)}}}}if(M.sortFeatures(-this.transform.bearingInRadians),this.retainedQueryData[M.bucketInstanceId]&&(this.retainedQueryData[M.bucketInstanceId].featureSortOrder=M.featureSortOrder),M.hasTextData()&&M.text.opacityVertexBuffer&&M.text.opacityVertexBuffer.updateData(M.text.opacityVertexArray),M.hasIconData()&&M.icon.opacityVertexBuffer&&M.icon.opacityVertexBuffer.updateData(M.icon.opacityVertexArray),M.hasIconCollisionBoxData()&&M.iconCollisionBox.collisionVertexBuffer&&M.iconCollisionBox.collisionVertexBuffer.updateData(M.iconCollisionBox.collisionVertexArray),M.hasTextCollisionBoxData()&&M.textCollisionBox.collisionVertexBuffer&&M.textCollisionBox.collisionVertexBuffer.updateData(M.textCollisionBox.collisionVertexArray),M.text.opacityVertexArray.length!==M.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${M.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${M.text.layoutVertexArray.length}) / 4`);if(M.icon.opacityVertexArray.length!==M.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${M.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${M.icon.layoutVertexArray.length}) / 4`);M.bucketInstanceId in this.collisionCircleArrays&&(M.collisionCircleArray=this.collisionCircleArrays[M.bucketInstanceId],delete this.collisionCircleArrays[M.bucketInstanceId])}symbolFadeChange(M){return 0===this.fadeDuration?1:(M-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(M){return Math.max(0,(this.transform.zoom-M)/1.5)}hasTransitions(M){return this.stale||M-this.lastPlacementChangeTimeM}setStale(){this.stale=!0}}function Xe(M,et,Bt,Wt,Nt,$t){Wt&&0!==Wt.length||(Wt=[0,0,0,0]);const Gr=Wt[0]-Da,mn=Wt[1]-Da,Hn=Wt[2]-Da,so=Wt[3]-Da;M.emplaceBack(et?1:0,Bt?1:0,Nt||0,$t||0,Gr,mn),M.emplaceBack(et?1:0,Bt?1:0,Nt||0,$t||0,Hn,mn),M.emplaceBack(et?1:0,Bt?1:0,Nt||0,$t||0,Hn,so),M.emplaceBack(et?1:0,Bt?1:0,Nt||0,$t||0,Gr,so)}const Ka=Math.pow(2,25),Oa=Math.pow(2,24),$a=Math.pow(2,17),Al=Math.pow(2,16),Sl=Math.pow(2,9),Zl=Math.pow(2,8),Gl=Math.pow(2,1);function it(M){if(0===M.opacity&&!M.placed)return 0;if(1===M.opacity&&M.placed)return 4294967295;const et=M.placed?1:0,Bt=Math.floor(127*M.opacity);return Bt*Ka+et*Oa+Bt*$a+et*Al+Bt*Sl+et*Zl+Bt*Gl+et}const Rl=0;class ot{constructor(M){this._sortAcrossTiles="viewport-y"!==M.layout.get("symbol-z-order")&&!M.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[]}continuePlacement(M,et,Bt,Wt,Nt){const $t=this._bucketParts;for(;this._currentTileIndexM.sortKey-et.sortKey)));this._currentPartIndex<$t.length;)if(et.placeLayerBucketPart($t[this._currentPartIndex],this._seenCrossTileIDs,Bt),this._currentPartIndex++,Nt())return!0;return!1}}class st{constructor(M,et,Bt,Wt,Nt,$t,Gr,mn){this.placement=new We(M,et,$t,Gr,mn),this._currentPlacementIndex=Bt.length-1,this._forceFullPlacement=Wt,this._showCollisionBoxes=Nt,this._done=!1}isDone(){return this._done}continuePlacement(M,et,Bt){const Wt=$t.now(),o=()=>!this._forceFullPlacement&&$t.now()-Wt>2;for(;this._currentPlacementIndex>=0;){const Wt=et[M[this._currentPlacementIndex]],Nt=this.placement.collisionIndex.transform.zoom;if("symbol"===Wt.type&&(!Wt.minzoom||Wt.minzoom<=Nt)&&(!Wt.maxzoom||Wt.maxzoom>Nt)){if(this._inProgressLayer||(this._inProgressLayer=new ot(Wt)),this._inProgressLayer.continuePlacement(Bt[Wt.source],this.placement,this._showCollisionBoxes,Wt,o))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._done=!0}commit(M){return this.placement.commit(M),this.placement}}const Tl=512/et.X/2;class nt{constructor(M,Bt,Wt){this.tileID=M,this.bucketInstanceId=Wt,this._symbolsByKey={};const Nt=new Map;for(let M=0;M({x:Math.floor(M.anchorX*Tl),y:Math.floor(M.anchorY*Tl)}))),crossTileIDs:Bt.map((M=>M.crossTileID))};if(Wt.positions.length>128){const M=new et.az(Wt.positions.length,16,Uint16Array);for(const{x:et,y:Bt}of Wt.positions)M.add(et,Bt);M.finish(),delete Wt.positions,Wt.index=M}this._symbolsByKey[M]=Wt}}getScaledCoordinates(M,Bt){const{x:Wt,y:Nt,z:$t}=this.tileID.canonical,{x:Gr,y:mn,z:Hn}=Bt.canonical,so=Tl/Math.pow(2,Hn-$t),uo=(mn*et.X+M.anchorY)*so,Io=Nt*et.X*Tl;return{x:Math.floor((Gr*et.X+M.anchorX)*so-Wt*et.X*Tl),y:Math.floor(uo-Io)}}findMatches(M,et,Bt){const Wt=this.tileID.canonical.zM))}}class lt{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class ct{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(M){const et=Math.round((M-this.lng)/360);if(0!==et)for(const M in this.indexes){const Bt=this.indexes[M],Wt={};for(const M in Bt){const Nt=Bt[M];Nt.tileID=Nt.tileID.unwrapTo(Nt.tileID.wrap+et),Wt[Nt.tileID.key]=Nt}this.indexes[M]=Wt}this.lng=M}addBucket(M,et,Bt){if(this.indexes[M.overscaledZ]&&this.indexes[M.overscaledZ][M.key]){if(this.indexes[M.overscaledZ][M.key].bucketInstanceId===et.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(M.overscaledZ,this.indexes[M.overscaledZ][M.key])}for(let M=0;MM.overscaledZ)for(const Bt in Nt){const $t=Nt[Bt];$t.tileID.isChildOf(M)&&$t.findMatches(et.symbolInstances,M,Wt)}else{const $t=Nt[M.scaledTo(Number(Bt)).key];$t&&$t.findMatches(et.symbolInstances,M,Wt)}}for(let M=0;M{et[M]=!0}));for(const M in this.layerIndexes)et[M]||delete this.layerIndexes[M]}}var Vl="void main() {fragColor=vec4(1.0);}";const Wl={prelude:_t("#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nout highp vec4 fragColor;","#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}mat3 rotationMatrixFromAxisAngle(vec3 u,float angle) {float c=cos(angle);float s=sin(angle);float c2=1.0-c;return mat3(u.x*u.x*c2+ c,u.x*u.y*c2-u.z*s,u.x*u.z*c2+u.y*s,u.y*u.x*c2+u.z*s,u.y*u.y*c2+ c,u.y*u.z*c2-u.x*s,u.z*u.x*c2-u.y*s,u.z*u.y*c2+u.x*s,u.z*u.z*c2+ c\n);}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\n#ifdef GLOBE\nif ((pos.y <-32767.5) || (pos.y > 32766.5)) {return 0.0;}\n#endif\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}const float PI=3.141592653589793;uniform mat4 u_projection_matrix;"),projectionMercator:_t("","float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}"),projectionGlobe:_t("","#define GLOBE_RADIUS 6371008.8\nuniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos\n);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float spherical_y=2.0*atan(exp(PI-(mercator_pos_y*PI*2.0)))-PI*0.5;return cos(spherical_y);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY); \nif (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 translatedPos,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*translatedPos;vec2 spherical;spherical.x=mercator_pos.x*PI*2.0+PI;spherical.y=2.0*atan(exp(PI-(mercator_pos.y*PI*2.0)))-PI*0.5;float len=cos(spherical.y);vec3 pos=vec3(sin(spherical.x)*len,sin(spherical.y),cos(spherical.x)*len\n);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeComputeClippingZ(vec3 spherePos) {return (1.0-(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphere(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphere(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphere(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphere(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}"),background:_t("uniform vec4 u_color;uniform float u_opacity;void main() {fragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),backgroundPattern:_t("uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}"),circle:_t("in vec3 v_data;in float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);float antialiased_blur=v_data.z;float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));fragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);const float epsilon=0.5/255.0;if (fragColor.r < epsilon && fragColor.g < epsilon && fragColor.b < epsilon && fragColor.a < epsilon) {discard;}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;uniform vec2 u_translate;in vec2 a_pos;out vec3 v_data;out float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 pos_raw=a_pos+32768.0;vec2 extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);vec2 circle_center=floor(pos_raw/8.0)+u_translate;float ele=get_elevation(circle_center);v_visibility=calculate_visibility(projectTileWithElevation(circle_center,ele));if (u_pitch_with_map) {\n#ifdef GLOBE\nvec3 center_vector=projectToSphere(circle_center);\n#endif\nfloat angle_scale=u_globe_extrude_scale;vec2 corner_position=circle_center;if (u_scale_with_map) {angle_scale*=(radius+stroke_width);corner_position+=extrude*u_extrude_scale*(radius+stroke_width);} else {\n#ifdef GLOBE\nvec4 projected_center=interpolateProjection(circle_center,center_vector,ele);\n#else\nvec4 projected_center=projectTileWithElevation(circle_center,ele);\n#endif\ncorner_position+=extrude*u_extrude_scale*(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);angle_scale*=(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);}\n#ifdef GLOBE\nvec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);\n#else\ngl_Position=projectTileWithElevation(corner_position,ele);\n#endif\n} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),clippingMask:_t(Vl,"in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),heatmap:_t("uniform highp float u_intensity;in vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);fragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;uniform highp float u_globe_extrude_scale;in vec2 a_pos;out vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 pos_raw=a_pos+32768.0;vec2 unscaled_extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 circle_center=floor(pos_raw/8.0);\n#ifdef GLOBE\nvec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphere(circle_center);vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);\n#else\ngl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));\n#endif\n}"),heatmapTexture:_t("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(0.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),collisionBox:_t("in float v_placed;in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}","in vec2 a_anchor_pos;in vec2 a_placed;in vec2 a_box_real;uniform vec2 u_pixel_extrude_scale;out float v_placed;out float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}"),collisionCircle:_t("in float v_radius;in vec2 v_extrude;in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);fragColor=color*alpha*opacity_t;}","in vec2 a_pos;in float a_radius;in vec2 a_flags;uniform vec2 u_viewport_size;out float v_radius;out vec2 v_extrude;out float v_collision;void main() {float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),debug:_t("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);fragColor=mix(u_color,overlay_color,overlay_color.a);}","in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}"),depth:_t(Vl,"in vec2 a_pos;void main() {\n#ifdef GLOBE\ngl_Position=projectTileFor3D(a_pos,0.0);\n#else\ngl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);\n#endif\n}"),fill:_t("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\nfragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_fill_translate;in vec2 a_pos;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);}"),fillOutline:_t("in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=outline_color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillOutlinePattern:_t("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillPattern:_t("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),fillExtrusion:_t("in vec4 v_color;void main() {fragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\nout vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nfloat colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;vec3 normalForLighting=normal/16384.0;float directional=clamp(dot(normalForLighting,u_lightpos),0.0,1.0);\n#ifdef GLOBE\nmat3 rotMatrix=globeGetRotationMatrix(spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);\n#endif\ndirectional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),fillExtrusionPattern:_t("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;in vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);fragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\n#ifdef GLOBE\nout vec3 v_sphere_pos;\n#endif\nout vec2 v_pos_a;out vec2 v_pos_b;out vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nvec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,elevation*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),hillshadePrepare:_t("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/pow(2.0,exaggeration+(19.2562-u_zoom));fragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;in vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),hillshade:_t("uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\n#define PI 3.141592653589793\nvoid main() {vec4 pixel=texture(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);fragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),line:_t("uniform lowp float u_device_pixel_ratio;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp float v_linesofar;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),lineGradient:_t("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture(u_image,v_uv);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;in float a_uv_x;in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),linePattern:_t("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;in vec2 v_normal;in vec2 v_width2;in float v_linesofar;in float v_gamma_scale;in float v_width;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture(u_image,pos_a),texture(u_image,pos_b),u_fade);fragColor=color*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_linesofar;out float v_gamma_scale;out float v_width;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),lineSDF:_t("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture(u_image,v_tex_a).a;float sdfdist_b=texture(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;out vec2 v_normal;out vec2 v_width2;out vec2 v_tex_a;out vec2 v_tex_b;out float v_gamma_scale;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),raster:_t("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec2 v_pos0;in vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture(u_image0,v_pos0);vec4 color1=texture(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;uniform vec4 u_coords_top;uniform vec4 u_coords_bottom;in vec2 a_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {vec2 fractionalPos=a_pos/8192.0;vec2 position=mix(mix(u_coords_top.xy,u_coords_top.zw,fractionalPos.x),mix(u_coords_bottom.xy,u_coords_bottom.zw,fractionalPos.x),fractionalPos.y);gl_Position=projectTile(position,position);v_pos0=((fractionalPos-0.5)/u_buffer_scale)+0.5;\n#ifdef GLOBE\nif (a_pos.y <-32767.5) {v_pos0.y=0.0;}if (a_pos.y > 32766.5) {v_pos0.y=1.0;}\n#endif\nv_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),symbolIcon:_t("uniform sampler2D u_texture;in vec2 v_tex;in float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;fragColor=texture(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_tex;out float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}"),symbolSDF:_t("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;in vec2 v_data0;in vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_data0;out vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),symbolTextAndIcon:_t("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;in vec4 v_data0;in vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;fragColor=texture(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec4 v_data0;out vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}"),terrain:_t("uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;uniform bool u_is_globe_mode;in vec2 v_texture_pos;in float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);fragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {fragColor=surface_color;}}","in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_texture_pos;out float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,get_elevation(a_pos3d.xy)-ele_delta);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}"),terrainDepth:_t("in float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {fragColor=pack(v_depth);}","in vec3 a_pos3d;uniform float u_ele_delta;out float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}"),terrainCoords:_t("precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;in vec2 v_texture_pos;void main() {vec4 rgba=texture(u_texture,v_texture_pos);fragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}","in vec3 a_pos3d;uniform float u_ele_delta;out vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);}"),projectionErrorMeasurement:_t("in vec4 v_output_error_encoded;void main() {fragColor=v_output_error_encoded;}","in vec2 a_pos;uniform highp float u_input;uniform highp float u_output_expected;out vec4 v_output_error_encoded;void main() {float real_output=2.0*atan(exp(PI-(u_input*PI*2.0)))-PI*0.5;float error=real_output-u_output_expected;float abs_error=abs(error)*128.0;v_output_error_encoded.x=min(floor(abs_error*256.0),255.0)/255.0;abs_error-=v_output_error_encoded.x;v_output_error_encoded.y=min(floor(abs_error*65536.0),255.0)/255.0;abs_error-=v_output_error_encoded.x/255.0;v_output_error_encoded.z=min(floor(abs_error*16777216.0),255.0)/255.0;v_output_error_encoded.w=error >=0.0 ? 1.0 : 0.0;gl_Position=vec4(a_pos,0.0,1.0);}"),atmosphere:_t("in vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) {return vec4(0.0,0.0,0.0,1.0);}if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie)));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758\n);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}","in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}"),sky:_t("uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor=mix(fragColor,vec4(vec3(0.0),0.0),u_sky_blend);}","in vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}")};function _t(M,et){const Bt=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,Wt=et.match(/in ([\w]+) ([\w]+)/g),Nt=M.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),$t=et.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),Gr=$t?$t.concat(Nt):Nt,mn={};return{fragmentSource:M=M.replace(Bt,((M,et,Bt,Wt,Nt)=>(mn[Nt]=!0,"define"===et?`\n#ifndef HAS_UNIFORM_u_${Nt}\nin ${Bt} ${Wt} ${Nt};\n#else\nuniform ${Bt} ${Wt} u_${Nt};\n#endif\n`:`\n#ifdef HAS_UNIFORM_u_${Nt}\n ${Bt} ${Wt} ${Nt} = u_${Nt};\n#endif\n`))),vertexSource:et=et.replace(Bt,((M,et,Bt,Wt,Nt)=>{const $t="float"===Wt?"vec2":"vec4",Gr=Nt.match(/color/)?"color":$t;return mn[Nt]?"define"===et?`\n#ifndef HAS_UNIFORM_u_${Nt}\nuniform lowp float u_${Nt}_t;\nin ${Bt} ${$t} a_${Nt};\nout ${Bt} ${Wt} ${Nt};\n#else\nuniform ${Bt} ${Wt} u_${Nt};\n#endif\n`:"vec4"===Gr?`\n#ifndef HAS_UNIFORM_u_${Nt}\n ${Nt} = a_${Nt};\n#else\n ${Bt} ${Wt} ${Nt} = u_${Nt};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${Nt}\n ${Nt} = unpack_mix_${Gr}(a_${Nt}, u_${Nt}_t);\n#else\n ${Bt} ${Wt} ${Nt} = u_${Nt};\n#endif\n`:"define"===et?`\n#ifndef HAS_UNIFORM_u_${Nt}\nuniform lowp float u_${Nt}_t;\nin ${Bt} ${$t} a_${Nt};\n#else\nuniform ${Bt} ${Wt} u_${Nt};\n#endif\n`:"vec4"===Gr?`\n#ifndef HAS_UNIFORM_u_${Nt}\n ${Bt} ${Wt} ${Nt} = a_${Nt};\n#else\n ${Bt} ${Wt} ${Nt} = u_${Nt};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${Nt}\n ${Bt} ${Wt} ${Nt} = unpack_mix_${Gr}(a_${Nt}, u_${Nt}_t);\n#else\n ${Bt} ${Wt} ${Nt} = u_${Nt};\n#endif\n`})),staticAttributes:Wt,staticUniforms:Gr}}class pt{constructor(M,et,Bt){this.vertexBuffer=M,this.indexBuffer=et,this.segments=Bt}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.vertexBuffer=null,this.indexBuffer=null,this.segments=null}}var El=et.aA([{name:"a_pos",type:"Int16",components:2}]);const Jl="#define PROJECTION_MERCATOR",Ll="mercator";class vt{constructor(){this._cachedMesh=null}get name(){return"mercator"}get useSubdivision(){return!1}get shaderVariantName(){return Ll}get shaderDefine(){return Jl}get shaderPreludeCode(){return Wl.projectionMercator}get vertexShaderPreludeCode(){return Wl.projectionMercator.vertexSource}get subdivisionGranularity(){return et.aB.noSubdivision}get useGlobeControls(){return!1}get transitionState(){return 0}get latitudeErrorCorrectionRadians(){return 0}destroy(){}updateGPUdependent(M){}getMeshFromTileID(M,Bt,Wt,Nt,$t){if(this._cachedMesh)return this._cachedMesh;const Gr=new et.aC;Gr.emplaceBack(0,0),Gr.emplaceBack(et.X,0),Gr.emplaceBack(0,et.X),Gr.emplaceBack(et.X,et.X);const mn=M.createVertexBuffer(Gr,El.members),Hn=et.aD.simpleSegment(0,0,4,2),so=new et.aE;so.emplaceBack(1,0,2),so.emplaceBack(1,2,3);const uo=M.createIndexBuffer(so);return this._cachedMesh=new pt(mn,uo,Hn),this._cachedMesh}recalculate(){}hasTransition(){return!1}setErrorQueryLatitudeDegrees(M){}}function xt(M,Bt){const Wt=et.ab(Bt.lat,-et.aF,et.aF);return new et.P(et.O(Bt.lng)*M,et.Q(Wt)*M)}function bt(M,Bt){return new et.Y(Bt.x/M,Bt.y/M).toLngLat()}function yt(M){return M.cameraToCenterDistance*Math.min(.85*Math.tan(et.aa(90-M.pitch)),Math.tan(et.aa(89.25-M.pitch)))}function wt(M,Bt){const Wt=M.canonical,Nt=Bt/et.aG(Wt.z),$t=Wt.x+Math.pow(2,Wt.z)*M.wrap,Gr=et.aq(new Float64Array(16));return et.J(Gr,Gr,[$t*Nt,Wt.y*Nt,0]),et.K(Gr,Gr,[Nt/et.X,Nt/et.X,1]),Gr}function Tt(M,Bt,Wt,Nt,$t){const Gr=et.Y.fromLngLat(M,Bt),mn=$t*et.aH(1,M.lat),Hn=mn*Math.cos(et.aa(Wt)),so=Math.sqrt(mn*mn-Hn*Hn),uo=so*Math.sin(et.aa(-Nt)),Io=so*Math.cos(et.aa(-Nt));return new et.Y(Gr.x+uo,Gr.y+Io,Gr.z+Hn)}class Pt{constructor(M=0,et=0,Bt=0,Wt=0){if(isNaN(M)||M<0||isNaN(et)||et<0||isNaN(Bt)||Bt<0||isNaN(Wt)||Wt<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=M,this.bottom=et,this.left=Bt,this.right=Wt}interpolate(M,Bt,Wt){return null!=Bt.top&&null!=M.top&&(this.top=et.y.number(M.top,Bt.top,Wt)),null!=Bt.bottom&&null!=M.bottom&&(this.bottom=et.y.number(M.bottom,Bt.bottom,Wt)),null!=Bt.left&&null!=M.left&&(this.left=et.y.number(M.left,Bt.left,Wt)),null!=Bt.right&&null!=M.right&&(this.right=et.y.number(M.right,Bt.right,Wt)),this}getCenter(M,Bt){const Wt=et.ab((this.left+M-this.right)/2,0,M),Nt=et.ab((this.top+Bt-this.bottom)/2,0,Bt);return new et.P(Wt,Nt)}equals(M){return this.top===M.top&&this.bottom===M.bottom&&this.left===M.left&&this.right===M.right}clone(){return new Pt(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function Ct(M,et){if(!M.renderWorldCopies||M.lngRange)return;const Bt=et.lng-M.center.lng;et.lng+=Bt>180?-360:Bt<-180?360:0}function It(M){return Math.max(0,Math.floor(M))}class Et{constructor(M,Bt,Wt,Nt,$t,Gr){this._callbacks=M,this._tileSize=512,this._renderWorldCopies=void 0===Gr||!!Gr,this._minZoom=Bt||0,this._maxZoom=Wt||22,this._minPitch=null==Nt?0:Nt,this._maxPitch=null==$t?60:$t,this.setMaxBounds(),this._width=0,this._height=0,this._center=new et.N(0,0),this._elevation=0,this._zoom=0,this._tileZoom=It(this._zoom),this._scale=et.aG(this._zoom),this._bearingInRadians=0,this._fovInRadians=.6435011087932844,this._pitchInRadians=0,this._rollInRadians=0,this._unmodified=!0,this._edgeInsets=new Pt,this._minElevationForCurrentTile=0,this._autoCalculateNearFarZ=!0}apply(M,Bt,Wt){this._latRange=M.latRange,this._lngRange=M.lngRange,this._width=M.width,this._height=M.height,this._center=M.center,this._elevation=M.elevation,this._minElevationForCurrentTile=M.minElevationForCurrentTile,this._zoom=M.zoom,this._tileZoom=It(this._zoom),this._scale=et.aG(this._zoom),this._bearingInRadians=M.bearingInRadians,this._fovInRadians=M.fovInRadians,this._pitchInRadians=M.pitchInRadians,this._rollInRadians=M.rollInRadians,this._unmodified=M.unmodified,this._edgeInsets=new Pt(M.padding.top,M.padding.bottom,M.padding.left,M.padding.right),this._minZoom=M.minZoom,this._maxZoom=M.maxZoom,this._minPitch=M.minPitch,this._maxPitch=M.maxPitch,this._renderWorldCopies=M.renderWorldCopies,this._cameraToCenterDistance=M.cameraToCenterDistance,this._nearZ=M.nearZ,this._farZ=M.farZ,this._autoCalculateNearFarZ=!Wt&&M.autoCalculateNearFarZ,Bt&&this._constrain(),this._calcMatrices()}get pixelsToClipSpaceMatrix(){return this._pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._clipSpaceToPixelsMatrix}get minElevationForCurrentTile(){return this._minElevationForCurrentTile}setMinElevationForCurrentTile(M){this._minElevationForCurrentTile=M}get tileSize(){return this._tileSize}get tileZoom(){return this._tileZoom}get scale(){return this._scale}get width(){return this._width}get height(){return this._height}get bearingInRadians(){return this._bearingInRadians}get lngRange(){return this._lngRange}get latRange(){return this._latRange}get pixelsToGLUnits(){return this._pixelsToGLUnits}get minZoom(){return this._minZoom}setMinZoom(M){this._minZoom!==M&&(this._minZoom=M,this.setZoom(this.getConstrained(this._center,this.zoom).zoom))}get maxZoom(){return this._maxZoom}setMaxZoom(M){this._maxZoom!==M&&(this._maxZoom=M,this.setZoom(this.getConstrained(this._center,this.zoom).zoom))}get minPitch(){return this._minPitch}setMinPitch(M){this._minPitch!==M&&(this._minPitch=M,this.setPitch(Math.max(this.pitch,M)))}get maxPitch(){return this._maxPitch}setMaxPitch(M){this._maxPitch!==M&&(this._maxPitch=M,this.setPitch(Math.min(this.pitch,M)))}get renderWorldCopies(){return this._renderWorldCopies}setRenderWorldCopies(M){void 0===M?M=!0:null===M&&(M=!1),this._renderWorldCopies=M}get worldSize(){return this._tileSize*this._scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new et.P(this._width,this._height)}get bearing(){return this._bearingInRadians/Math.PI*180}setBearing(M){const Bt=et.aI(M,-180,180)*Math.PI/180;var Wt,Nt,$t,Gr,mn,Hn,so,uo,Io;this._bearingInRadians!==Bt&&(this._unmodified=!1,this._bearingInRadians=Bt,this._calcMatrices(),this._rotationMatrix=r(),Wt=this._rotationMatrix,$t=-this._bearingInRadians,Gr=(Nt=this._rotationMatrix)[0],mn=Nt[1],Hn=Nt[2],so=Nt[3],uo=Math.sin($t),Io=Math.cos($t),Wt[0]=Gr*Io+Hn*uo,Wt[1]=mn*Io+so*uo,Wt[2]=Gr*-uo+Hn*Io,Wt[3]=mn*-uo+so*Io)}get rotationMatrix(){return this._rotationMatrix}get pitchInRadians(){return this._pitchInRadians}get pitch(){return this._pitchInRadians/Math.PI*180}setPitch(M){const Bt=et.ab(M,this.minPitch,this.maxPitch)/180*Math.PI;this._pitchInRadians!==Bt&&(this._unmodified=!1,this._pitchInRadians=Bt,this._calcMatrices())}get rollInRadians(){return this._rollInRadians}get roll(){return this._rollInRadians/Math.PI*180}setRoll(M){const et=M/180*Math.PI;this._rollInRadians!==et&&(this._unmodified=!1,this._rollInRadians=et,this._calcMatrices())}get fovInRadians(){return this._fovInRadians}get fov(){return et.aJ(this._fovInRadians)}setFov(M){M=et.ab(M,.1,150),this.fov!==M&&(this._unmodified=!1,this._fovInRadians=et.aa(M),this._calcMatrices())}get zoom(){return this._zoom}setZoom(M){const Bt=this.getConstrained(this._center,M).zoom;this._zoom!==Bt&&(this._unmodified=!1,this._zoom=Bt,this._tileZoom=Math.max(0,Math.floor(Bt)),this._scale=et.aG(Bt),this._constrain(),this._calcMatrices())}get center(){return this._center}setCenter(M){M.lat===this._center.lat&&M.lng===this._center.lng||(this._unmodified=!1,this._center=M,this._constrain(),this._calcMatrices())}get elevation(){return this._elevation}setElevation(M){M!==this._elevation&&(this._elevation=M,this._constrain(),this._calcMatrices())}get padding(){return this._edgeInsets.toJSON()}setPadding(M){this._edgeInsets.equals(M)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,M,1),this._calcMatrices())}get centerPoint(){return this._edgeInsets.getCenter(this._width,this._height)}get pixelsPerMeter(){return this._pixelPerMeter}get unmodified(){return this._unmodified}get cameraToCenterDistance(){return this._cameraToCenterDistance}get nearZ(){return this._nearZ}get farZ(){return this._farZ}get autoCalculateNearFarZ(){return this._autoCalculateNearFarZ}overrideNearFarZ(M,et){this._autoCalculateNearFarZ=!1,this._nearZ=M,this._farZ=et,this._calcMatrices()}clearNearFarZOverride(){this._autoCalculateNearFarZ=!0,this._calcMatrices()}isPaddingEqual(M){return this._edgeInsets.equals(M)}interpolatePadding(M,et,Bt){this._unmodified=!1,this._edgeInsets.interpolate(M,et,Bt),this._constrain(),this._calcMatrices()}resize(M,et,Bt=!0){this._width=M,this._height=et,Bt&&this._constrain(),this._calcMatrices()}getMaxBounds(){return this._latRange&&2===this._latRange.length&&this._lngRange&&2===this._lngRange.length?new V([this._lngRange[0],this._latRange[0]],[this._lngRange[1],this._latRange[1]]):null}setMaxBounds(M){M?(this._lngRange=[M.getWest(),M.getEast()],this._latRange=[M.getSouth(),M.getNorth()],this._constrain()):(this._lngRange=null,this._latRange=[-et.aF,et.aF])}getConstrained(M,et){return this._callbacks.getConstrained(M,et)}getCameraQueryGeometry(M,Bt){if(1===Bt.length)return[Bt[0],M];{let Wt=M.x,Nt=M.y,$t=M.x,Gr=M.y;for(const M of Bt)Wt=Math.min(Wt,M.x),Nt=Math.min(Nt,M.y),$t=Math.max($t,M.x),Gr=Math.max(Gr,M.y);return[new et.P(Wt,Nt),new et.P($t,Nt),new et.P($t,Gr),new et.P(Wt,Gr),new et.P(Wt,Nt)]}}_constrain(){if(!this.center||!this._width||!this._height||this._constraining)return;this._constraining=!0;const M=this._unmodified,{center:et,zoom:Bt}=this.getConstrained(this.center,this.zoom);this.setCenter(et),this.setZoom(Bt),this._unmodified=M,this._constraining=!1}_calcMatrices(){if(this._width&&this._height){this._pixelsToGLUnits=[2/this._width,-2/this._height];let M=et.aq(new Float64Array(16));et.K(M,M,[this._width/2,-this._height/2,1]),et.J(M,M,[1,-1,0]),this._clipSpaceToPixelsMatrix=M,M=et.aq(new Float64Array(16)),et.K(M,M,[1,-1,1]),et.J(M,M,[-1,-1,0]),et.K(M,M,[2/this._width,2/this._height,1]),this._pixelsToClipSpaceMatrix=M,this._cameraToCenterDistance=.5/Math.tan(this.fovInRadians/2)*this._height}this._callbacks.calcMatrices()}calculateCenterFromCameraLngLatAlt(M,Bt,Wt,Nt){const $t=void 0!==Wt?Wt:this.bearing,Gr=Nt=void 0!==Nt?Nt:this.pitch,mn=et.Y.fromLngLat(M,Bt),Hn=-Math.cos(et.aa(Gr)),so=Math.sin(et.aa(Gr)),uo=so*Math.sin(et.aa($t)),Io=-so*Math.cos(et.aa($t));let Po=this.elevation;const To=Bt-Po;let Eo;Hn*To>=0||Math.abs(Hn)<.1?(Eo=1e4,Po=Bt+Eo*Hn):Eo=-To/Hn;let Ia,Ba,Ta=et.aK(1,mn.y),Va=0;do{if(Va+=1,Va>10)break;Ba=Eo/Ta,Ia=new et.Y(mn.x+uo*Ba,mn.y+Io*Ba),Ta=1/Ia.meterInMercatorCoordinateUnits()}while(Math.abs(Eo-Ba*Ta)>1e-12);return{center:Ia.toLngLat(),elevation:Po,zoom:et.a8(this.height/2/Math.tan(this.fovInRadians/2)/Ba/this.tileSize)}}recalculateZoomAndCenter(M){if(this.elevation-M==0)return;const Bt=et.aH(1,this.center.lat)*this.worldSize,Wt=this.cameraToCenterDistance/Bt,Nt=et.Y.fromLngLat(this.center,this.elevation),$t=Tt(this.center,this.elevation,this.pitch,this.bearing,Wt);this._elevation=M;const Gr=this.calculateCenterFromCameraLngLatAlt($t.toLngLat(),et.aK($t.z,Nt.y),this.bearing,this.pitch);this._elevation=Gr.elevation,this._center=Gr.center,this.setZoom(Gr.zoom)}getCameraPoint(){const M=Math.tan(this.pitchInRadians)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new et.P(M*Math.sin(this.rollInRadians),M*Math.cos(this.rollInRadians)))}getCameraAltitude(){return Math.cos(this.pitchInRadians)*this._cameraToCenterDistance/this._pixelPerMeter+this.elevation}getCameraLngLat(){const M=et.aH(1,this.center.lat)*this.worldSize;return Tt(this.center,this.elevation,this.pitch,this.bearing,this.cameraToCenterDistance/M).toLngLat()}getMercatorTileCoordinates(M){if(!M)return[0,0,1,1];const Bt=M.canonical.z>=0?1<this.max[0]||M.aabb.min[1]>this.max[1]||M.aabb.min[2]>this.max[2]||M.aabb.max[0]0?(et+=M[Wt]*this.min[Wt],Bt+=M[Wt]*this.max[Wt]):(Bt+=M[Wt]*this.min[Wt],et+=M[Wt]*this.max[Wt]);return et>=0?2:Bt<0?0:1}}class St{distanceToTile2d(M,et,Bt,Wt){const Nt=Wt.distanceX([M,et]),$t=Wt.distanceY([M,et]);return Math.hypot(Nt,$t)}getWrap(M,et,Bt){return Bt}getTileAABB(M,Bt,Wt,Nt){var $t,Gr;let mn=Wt,Hn=Wt;if(Nt.terrain){const so=new et.S(M.z,Bt,M.z,M.x,M.y),uo=Nt.terrain.getMinMaxElevation(so);mn=null!==($t=uo.minElevation)&&void 0!==$t?$t:Wt,Hn=null!==(Gr=uo.maxElevation)&&void 0!==Gr?Gr:Wt}const so=1<Nt||M.padding.top>=.1}allowWorldCopies(){return!0}recalculateCache(){}}class Rt{constructor(M,et,Bt){this.points=M,this.planes=et,this.aabb=Bt}static fromInvProjectionMatrix(M,Bt=1,Wt=0){const Nt=Math.pow(2,Wt),$t=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((Wt=>{const $t=1/(Wt=et.al([],Wt,M))[3]/Bt*Nt;return et.aO(Wt,Wt,[$t,$t,1/Wt[3],$t])})),Gr=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map((M=>{const Bt=et.aP([],$t[M[0]],$t[M[1]]),Wt=et.aP([],$t[M[2]],$t[M[1]]),Nt=et.aQ([],et.aR([],Bt,Wt)),Gr=-et.aS(Nt,$t[M[1]]);return Nt.concat(Gr)})),mn=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],Hn=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];for(const M of $t)for(let et=0;et<3;et++)mn[et]=Math.min(mn[et],M[et]),Hn[et]=Math.max(Hn[et],M[et]);return new Rt($t,Gr,new Mt(mn,Hn))}}class Dt{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(M){this._helper.setMinZoom(M)}setMaxZoom(M){this._helper.setMaxZoom(M)}setMinPitch(M){this._helper.setMinPitch(M)}setMaxPitch(M){this._helper.setMaxPitch(M)}setRenderWorldCopies(M){this._helper.setRenderWorldCopies(M)}setBearing(M){this._helper.setBearing(M)}setPitch(M){this._helper.setPitch(M)}setRoll(M){this._helper.setRoll(M)}setFov(M){this._helper.setFov(M)}setZoom(M){this._helper.setZoom(M)}setCenter(M){this._helper.setCenter(M)}setElevation(M){this._helper.setElevation(M)}setMinElevationForCurrentTile(M){this._helper.setMinElevationForCurrentTile(M)}setPadding(M){this._helper.setPadding(M)}interpolatePadding(M,et,Bt){return this._helper.interpolatePadding(M,et,Bt)}isPaddingEqual(M){return this._helper.isPaddingEqual(M)}resize(M,et,Bt=!0){this._helper.resize(M,et,Bt)}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(M){this._helper.setMaxBounds(M)}overrideNearFarZ(M,et){this._helper.overrideNearFarZ(M,et)}clearNearFarZOverride(){this._helper.clearNearFarZOverride()}getCameraQueryGeometry(M){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),M)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}setTransitionState(M,et){}constructor(M,et,Bt,Wt,Nt){this._posMatrixCache=new Map,this._alignedPosMatrixCache=new Map,this._fogMatrixCacheF32=new Map,this._helper=new Et({calcMatrices:()=>{this._calcMatrices()},getConstrained:(M,et)=>this.getConstrained(M,et)},M,et,Bt,Wt,Nt),this._coveringTilesDetailsProvider=new St}clone(){const M=new Dt;return M.apply(this),M}apply(M,et,Bt){this._helper.apply(M,et,Bt)}get cameraPosition(){return this._cameraPosition}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._viewProjMatrix}get inverseProjectionMatrix(){return this._invProjMatrix}get mercatorMatrix(){return this._mercatorMatrix}getVisibleUnwrappedCoordinates(M){const Bt=[new et.aT(0,M)];if(this._helper._renderWorldCopies){const Wt=this.screenPointToMercatorCoordinate(new et.P(0,0)),Nt=this.screenPointToMercatorCoordinate(new et.P(this._helper._width,0)),$t=this.screenPointToMercatorCoordinate(new et.P(this._helper._width,this._helper._height)),Gr=this.screenPointToMercatorCoordinate(new et.P(0,this._helper._height)),mn=Math.floor(Math.min(Wt.x,Nt.x,$t.x,Gr.x)),Hn=Math.floor(Math.max(Wt.x,Nt.x,$t.x,Gr.x)),so=1;for(let Wt=mn-so;Wt<=Hn+so;Wt++)0!==Wt&&Bt.push(new et.aT(Wt,M))}return Bt}getCameraFrustum(){return Rt.fromInvProjectionMatrix(this._invViewProjMatrix,this.worldSize)}getClippingPlane(){return null}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(M){const et=this.screenPointToLocation(this.centerPoint,M),Bt=M?M.getElevationForLngLatZoom(et,this._helper._tileZoom):0;this._helper.recalculateZoomAndCenter(Bt)}setLocationAtPoint(M,Bt){const Wt=et.aH(this.elevation,this.center.lat),Nt=this.screenPointToMercatorCoordinateAtZ(Bt,Wt),$t=this.screenPointToMercatorCoordinateAtZ(this.centerPoint,Wt),Gr=et.Y.fromLngLat(M),mn=new et.Y(Gr.x-(Nt.x-$t.x),Gr.y-(Nt.y-$t.y));this.setCenter(null==mn?void 0:mn.toLngLat()),this._helper._renderWorldCopies&&this.setCenter(this.center.wrap())}locationToScreenPoint(M,Bt){return Bt?this.coordinatePoint(et.Y.fromLngLat(M),Bt.getElevationForLngLatZoom(M,this._helper._tileZoom),this._pixelMatrix3D):this.coordinatePoint(et.Y.fromLngLat(M))}screenPointToLocation(M,et){var Bt;return null===(Bt=this.screenPointToMercatorCoordinate(M,et))||void 0===Bt?void 0:Bt.toLngLat()}screenPointToMercatorCoordinate(M,et){if(et){const Bt=et.pointCoordinate(M);if(null!=Bt)return Bt}return this.screenPointToMercatorCoordinateAtZ(M)}screenPointToMercatorCoordinateAtZ(M,Bt){const Wt=Bt||0,Nt=[M.x,M.y,0,1],$t=[M.x,M.y,1,1];et.al(Nt,Nt,this._pixelMatrixInverse),et.al($t,$t,this._pixelMatrixInverse);const Gr=Nt[3],mn=$t[3],Hn=Nt[1]/Gr,so=$t[1]/mn,uo=Nt[2]/Gr,Io=$t[2]/mn,Po=uo===Io?0:(Wt-uo)/(Io-uo);return new et.Y(et.y.number(Nt[0]/Gr,$t[0]/mn,Po)/this.worldSize,et.y.number(Hn,so,Po)/this.worldSize,Wt)}coordinatePoint(M,Bt=0,Wt=this._pixelMatrix){const Nt=[M.x*this.worldSize,M.y*this.worldSize,Bt,1];return et.al(Nt,Nt,Wt),new et.P(Nt[0]/Nt[3],Nt[1]/Nt[3])}getBounds(){const M=Math.max(0,this._helper._height/2-yt(this));return(new V).extend(this.screenPointToLocation(new et.P(0,M))).extend(this.screenPointToLocation(new et.P(this._helper._width,M))).extend(this.screenPointToLocation(new et.P(this._helper._width,this._helper._height))).extend(this.screenPointToLocation(new et.P(0,this._helper._height)))}isPointOnMapSurface(M,et){return et?null!=et.pointCoordinate(M):M.y>this.height/2-yt(this)}calculatePosMatrix(M,Bt=!1,Wt){var Nt;const $t=null!==(Nt=M.key)&&void 0!==Nt?Nt:et.aU(M.wrap,M.canonical.z,M.canonical.z,M.canonical.x,M.canonical.y),Gr=Bt?this._alignedPosMatrixCache:this._posMatrixCache;if(Gr.has($t)){const M=Gr.get($t);return Wt?M.f32:M.f64}const mn=wt(M,this.worldSize);et.L(mn,Bt?this._alignedProjMatrix:this._viewProjMatrix,mn);const Hn={f64:mn,f32:new Float32Array(mn)};return Gr.set($t,Hn),Wt?Hn.f32:Hn.f64}calculateFogMatrix(M){const Bt=M.key,Wt=this._fogMatrixCacheF32;if(Wt.has(Bt))return Wt.get(Bt);const Nt=wt(M,this.worldSize);return et.L(Nt,this._fogMatrix,Nt),Wt.set(Bt,new Float32Array(Nt)),Wt.get(Bt)}getConstrained(M,Bt){Bt=et.ab(+Bt,this.minZoom,this.maxZoom);const Wt={center:new et.N(M.lng,M.lat),zoom:Bt};let Nt=this._helper._lngRange;this._helper._renderWorldCopies||null!==Nt||(Nt=[-179.9999999999,180-1e-10]);const $t=this.tileSize*et.aG(Wt.zoom);let Gr=0,mn=$t,Hn=0,so=$t,uo=0,Io=0;const{x:Po,y:To}=this.size;if(this._helper._latRange){const M=this._helper._latRange;Gr=et.Q(M[1])*$t,mn=et.Q(M[0])*$t,mn-Grmn&&(Ta=mn-M)}if(Nt){const M=(Hn+so)/2;let Bt=Eo;this._helper._renderWorldCopies&&(Bt=et.aI(Eo,M-$t/2,M+$t/2));const Wt=Po/2;Bt-Wtso&&(Ba=so-Wt)}if(void 0!==Ba||void 0!==Ta){const M=new et.P(null!=Ba?Ba:Eo,null!=Ta?Ta:Ia);Wt.center=bt($t,M).wrap()}return Wt}calculateCenterFromCameraLngLatAlt(M,et,Bt,Wt){return this._helper.calculateCenterFromCameraLngLatAlt(M,et,Bt,Wt)}_calculateNearFarZIfNeeded(M,Bt,Wt){if(!this._helper.autoCalculateNearFarZ)return;const Nt=Math.min(this.elevation,this.minElevationForCurrentTile,this.getCameraAltitude()-100),$t=M-Nt*this._helper._pixelPerMeter/Math.cos(Bt),Gr=Nt<0?$t:M,mn=Math.PI/2+this.pitchInRadians,Hn=et.aa(this.fov)*(Math.abs(Math.cos(et.aa(this.roll)))*this.height+Math.abs(Math.sin(et.aa(this.roll)))*this.width)/this.height*(.5+Wt.y/this.height),so=Math.sin(Hn)*Gr/Math.sin(et.ab(Math.PI-mn-Hn,.01,Math.PI-.01)),uo=yt(this),Io=Math.atan(uo/this._helper.cameraToCenterDistance),Po=et.aa(.75),To=Io>Po?2*Io*(.5+Wt.y/(2*uo)):Po,Eo=Math.sin(To)*Gr/Math.sin(et.ab(Math.PI-mn-To,.01,Math.PI-.01)),Ia=Math.min(so,Eo);this._helper._farZ=1.01*(Math.cos(Math.PI/2-Bt)*Ia+Gr),this._helper._nearZ=this._helper._height/50}_calcMatrices(){if(!this._helper._height)return;const M=this.centerOffset,Bt=xt(this.worldSize,this.center),Wt=Bt.x,Nt=Bt.y;this._helper._pixelPerMeter=et.aH(1,this.center.lat)*this.worldSize;const $t=et.aa(Math.min(this.pitch,89.25)),Gr=Math.max(this._helper.cameraToCenterDistance/2,this._helper.cameraToCenterDistance+this._helper._elevation*this._helper._pixelPerMeter/Math.cos($t));let mn;this._calculateNearFarZIfNeeded(Gr,$t,M),mn=new Float64Array(16),et.aV(mn,this.fovInRadians,this._helper._width/this._helper._height,this._helper._nearZ,this._helper._farZ),this._invProjMatrix=new Float64Array(16),et.an(this._invProjMatrix,mn),mn[8]=2*-M.x/this._helper._width,mn[9]=2*M.y/this._helper._height,this._projectionMatrix=et.aW(mn),et.K(mn,mn,[1,-1,1]),et.J(mn,mn,[0,0,-this._helper.cameraToCenterDistance]),et.aX(mn,mn,-this.rollInRadians),et.aY(mn,mn,this.pitchInRadians),et.aX(mn,mn,-this.bearingInRadians),et.J(mn,mn,[-Wt,-Nt,0]),this._mercatorMatrix=et.K([],mn,[this.worldSize,this.worldSize,this.worldSize]),et.K(mn,mn,[1,1,this._helper._pixelPerMeter]),this._pixelMatrix=et.L(new Float64Array(16),this.clipSpaceToPixelsMatrix,mn),et.J(mn,mn,[0,0,-this.elevation]),this._viewProjMatrix=mn,this._invViewProjMatrix=et.an([],mn);const Hn=[0,0,-1,1];et.al(Hn,Hn,this._invViewProjMatrix),this._cameraPosition=[Hn[0]/Hn[3],Hn[1]/Hn[3],Hn[2]/Hn[3]],this._fogMatrix=new Float64Array(16),et.aV(this._fogMatrix,this.fovInRadians,this.width/this.height,Gr,this._helper._farZ),this._fogMatrix[8]=2*-M.x/this.width,this._fogMatrix[9]=2*M.y/this.height,et.K(this._fogMatrix,this._fogMatrix,[1,-1,1]),et.J(this._fogMatrix,this._fogMatrix,[0,0,-this.cameraToCenterDistance]),et.aX(this._fogMatrix,this._fogMatrix,-this.rollInRadians),et.aY(this._fogMatrix,this._fogMatrix,this.pitchInRadians),et.aX(this._fogMatrix,this._fogMatrix,-this.bearingInRadians),et.J(this._fogMatrix,this._fogMatrix,[-Wt,-Nt,0]),et.K(this._fogMatrix,this._fogMatrix,[1,1,this._helper._pixelPerMeter]),et.J(this._fogMatrix,this._fogMatrix,[0,0,-this.elevation]),this._pixelMatrix3D=et.L(new Float64Array(16),this.clipSpaceToPixelsMatrix,mn);const so=this._helper._width%2/2,uo=this._helper._height%2/2,Io=Math.cos(this.bearingInRadians),Po=Math.sin(-this.bearingInRadians),To=Wt-Math.round(Wt)+Io*so+Po*uo,Eo=Nt-Math.round(Nt)+Io*uo+Po*so,Ia=new Float64Array(mn);if(et.J(Ia,Ia,[To>.5?To-1:To,Eo>.5?Eo-1:Eo,0]),this._alignedProjMatrix=Ia,mn=et.an(new Float64Array(16),this._pixelMatrix),!mn)throw new Error("failed to invert matrix");this._pixelMatrixInverse=mn,this._clearMatrixCaches()}_clearMatrixCaches(){this._posMatrixCache.clear(),this._alignedPosMatrixCache.clear(),this._fogMatrixCacheF32.clear()}maxPitchScaleFactor(){if(!this._pixelMatrixInverse)return 1;const M=this.screenPointToMercatorCoordinate(new et.P(0,0)),Bt=[M.x*this.worldSize,M.y*this.worldSize,0,1];return et.al(Bt,Bt,this._pixelMatrix)[3]/this._helper.cameraToCenterDistance}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){const M=et.aH(1,this.center.lat)*this.worldSize;return Tt(this.center,this.elevation,this.pitch,this.bearing,this._helper.cameraToCenterDistance/M).toLngLat()}lngLatToCameraDepth(M,Bt){const Wt=et.Y.fromLngLat(M),Nt=[Wt.x*this.worldSize,Wt.y*this.worldSize,Bt,1];return et.al(Nt,Nt,this._viewProjMatrix),Nt[2]/Nt[3]}getProjectionData(M){const{overscaledTileID:Bt,aligned:Wt,applyTerrainMatrix:Nt}=M,$t=this._helper.getMercatorTileCoordinates(Bt),Gr=Bt?this.calculatePosMatrix(Bt,Wt,!0):null;let mn;return mn=Bt&&Bt.terrainRttPosMatrix32f&&Nt?Bt.terrainRttPosMatrix32f:Gr||et.aZ(),{mainMatrix:mn,tileMercatorCoords:$t,clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:mn}}isLocationOccluded(M){return!1}getPixelScale(){return 1}getCircleRadiusCorrection(){return 1}getPitchedTextCorrection(M,et,Bt){return 1}transformLightDirection(M){return et.aN(M)}getRayDirectionFromPixel(M){throw new Error("Not implemented.")}projectTileCoordinates(M,Bt,Wt,Nt){const $t=this.calculatePosMatrix(Wt);let Gr;Nt?(Gr=[M,Bt,Nt(M,Bt),1],et.al(Gr,Gr,$t)):(Gr=[M,Bt,0,1],je(Gr,Gr,$t));const mn=Gr[3];return{point:new et.P(Gr[0]/mn,Gr[1]/mn),signedDistanceFromCamera:mn,isOccluded:!1}}populateCache(M){for(const et of M)this.calculatePosMatrix(et)}getMatrixForModel(M,Bt){const Wt=et.Y.fromLngLat(M,Bt),Nt=Wt.meterInMercatorCoordinateUnits(),$t=et.a_();return et.J($t,$t,[Wt.x,Wt.y,Wt.z]),et.aX($t,$t,Math.PI),et.aY($t,$t,Math.PI/2),et.K($t,$t,[-Nt,Nt,Nt]),$t}getProjectionDataForCustomLayer(M=!0){const Bt=new et.S(0,0,0,0,0),Wt=this.getProjectionData({overscaledTileID:Bt,applyGlobeMatrix:M}),Nt=wt(Bt,this.worldSize);et.L(Nt,this._viewProjMatrix,Nt),Wt.tileMercatorCoords=[0,0,1,1];const $t=[et.X,et.X,this.worldSize/this._helper.pixelsPerMeter],Gr=et.a$();return et.K(Gr,Nt,$t),Wt.fallbackMatrix=Gr,Wt.mainMatrix=Gr,Wt}getFastPathSimpleProjectionMatrix(M){return this.calculatePosMatrix(M)}}function zt(){et.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.")}function At(M){if(M.useSlerp)if(M.k<1){const Bt=et.b0(M.startEulerAngles.roll,M.startEulerAngles.pitch,M.startEulerAngles.bearing),Wt=et.b0(M.endEulerAngles.roll,M.endEulerAngles.pitch,M.endEulerAngles.bearing),Nt=new Float64Array(4);et.b1(Nt,Bt,Wt,M.k);const $t=et.b2(Nt);M.tr.setRoll($t.roll),M.tr.setPitch($t.pitch),M.tr.setBearing($t.bearing)}else M.tr.setRoll(M.endEulerAngles.roll),M.tr.setPitch(M.endEulerAngles.pitch),M.tr.setBearing(M.endEulerAngles.bearing);else M.tr.setRoll(et.y.number(M.startEulerAngles.roll,M.endEulerAngles.roll,M.k)),M.tr.setPitch(et.y.number(M.startEulerAngles.pitch,M.endEulerAngles.pitch,M.k)),M.tr.setBearing(et.y.number(M.startEulerAngles.bearing,M.endEulerAngles.bearing,M.k))}function Lt(M,Bt,Wt,Nt,$t){const Gr=$t.padding,mn=xt($t.worldSize,Wt.getNorthWest()),Hn=xt($t.worldSize,Wt.getNorthEast()),so=xt($t.worldSize,Wt.getSouthEast()),uo=xt($t.worldSize,Wt.getSouthWest()),Io=et.aa(-Nt),Po=mn.rotate(Io),To=Hn.rotate(Io),Eo=so.rotate(Io),Ia=uo.rotate(Io),Ba=new et.P(Math.max(Po.x,To.x,Ia.x,Eo.x),Math.max(Po.y,To.y,Ia.y,Eo.y)),Ta=new et.P(Math.min(Po.x,To.x,Ia.x,Eo.x),Math.min(Po.y,To.y,Ia.y,Eo.y)),Va=Ba.sub(Ta),za=($t.width-(Gr.left+Gr.right+Bt.left+Bt.right))/Va.x,Fa=($t.height-(Gr.top+Gr.bottom+Bt.top+Bt.bottom))/Va.y;if(Fa<0||za<0)return void zt();const Ea=Math.min(et.a8($t.scale*Math.min(za,Fa)),M.maxZoom),La=et.P.convert(M.offset),Da=new et.P((Bt.left-Bt.right)/2,(Bt.top-Bt.bottom)/2).rotate(et.aa(Nt)),Ka=La.add(Da).mult($t.scale/et.aG(Ea));return{center:bt($t.worldSize,mn.add(so).div(2).sub(Ka)),zoom:Ea,bearing:Nt}}class kt{get useGlobeControls(){return!1}handlePanInertia(M,et){return{easingOffset:M,easingCenter:et.center}}handleMapControlsRollPitchBearingZoom(M,et){M.bearingDelta&&et.setBearing(et.bearing+M.bearingDelta),M.pitchDelta&&et.setPitch(et.pitch+M.pitchDelta),M.rollDelta&&et.setRoll(et.roll+M.rollDelta),M.zoomDelta&&et.setZoom(et.zoom+M.zoomDelta)}handleMapControlsPan(M,et,Bt){M.around.distSqr(et.centerPoint)<.01||et.setLocationAtPoint(Bt,M.around)}cameraForBoxAndBearing(M,et,Bt,Wt,Nt){return Lt(M,et,Bt,Wt,Nt)}handleJumpToCenterZoom(M,Bt){M.zoom!==(void 0!==Bt.zoom?+Bt.zoom:M.zoom)&&M.setZoom(+Bt.zoom),void 0!==Bt.center&&M.setCenter(et.N.convert(Bt.center))}handleEaseTo(M,Bt){const Wt=M.zoom,Nt=M.padding,$t={roll:M.roll,pitch:M.pitch,bearing:M.bearing},Gr={roll:void 0===Bt.roll?M.roll:Bt.roll,pitch:void 0===Bt.pitch?M.pitch:Bt.pitch,bearing:void 0===Bt.bearing?M.bearing:Bt.bearing},mn=void 0!==Bt.zoom,Hn=!M.isPaddingEqual(Bt.padding);let so=!1;const uo=mn?+Bt.zoom:M.zoom;let Io=M.centerPoint.add(Bt.offsetAsPoint);const Po=M.screenPointToLocation(Io),{center:To,zoom:Eo}=M.getConstrained(et.N.convert(Bt.center||Po),null!=uo?uo:Wt);Ct(M,To);const Ia=xt(M.worldSize,Po),Ba=xt(M.worldSize,To).sub(Ia),Ta=et.aG(Eo-Wt);return so=Eo!==Wt,{easeFunc:mn=>{if(so&&M.setZoom(et.y.number(Wt,Eo,mn)),et.b3($t,Gr)||At({startEulerAngles:$t,endEulerAngles:Gr,tr:M,k:mn,useSlerp:$t.roll!=Gr.roll}),Hn&&(M.interpolatePadding(Nt,Bt.padding,mn),Io=M.centerPoint.add(Bt.offsetAsPoint)),Bt.around)M.setLocationAtPoint(Bt.around,Bt.aroundPoint);else{const Bt=et.aG(M.zoom-Wt),Nt=Eo>Wt?Math.min(2,Ta):Math.max(.5,Ta),$t=Math.pow(Nt,1-mn),Gr=bt(M.worldSize,Ia.add(Ba.mult(mn*$t)).mult(Bt));M.setLocationAtPoint(M.renderWorldCopies?Gr.wrap():Gr,Io)}},isZooming:so,elevationCenter:To}}handleFlyTo(M,Bt){const Wt=void 0!==Bt.zoom,Nt=M.zoom,$t=M.getConstrained(et.N.convert(Bt.center||Bt.locationAtOffset),Wt?+Bt.zoom:Nt),Gr=$t.center,mn=$t.zoom;Ct(M,Gr);const Hn=xt(M.worldSize,Bt.locationAtOffset),so=xt(M.worldSize,Gr).sub(Hn),uo=so.mag(),Io=et.aG(mn-Nt);let Po;if(void 0!==Bt.minZoom){const Wt=Math.min(+Bt.minZoom,Nt,mn),$t=M.getConstrained(Gr,Wt).zoom;Po=et.aG($t-Nt)}return{easeFunc:(Bt,Wt,$t,uo)=>{M.setZoom(1===Bt?mn:Nt+et.a8(Wt));const Io=1===Bt?Gr:bt(M.worldSize,Hn.add(so.mult($t)).mult(Wt));M.setLocationAtPoint(M.renderWorldCopies?Io.wrap():Io,uo)},scaleOfZoom:Io,targetCenter:Gr,scaleOfMinZoom:Po,pixelPathLength:uo}}}class Ft{constructor(M,et,Bt){this.blendFunction=M,this.blendColor=et,this.mask=Bt}}Ft.Replace=[1,0],Ft.disabled=new Ft(Ft.Replace,et.b4.transparent,[!1,!1,!1,!1]),Ft.unblended=new Ft(Ft.Replace,et.b4.transparent,[!0,!0,!0,!0]),Ft.alphaBlended=new Ft([1,771],et.b4.transparent,[!0,!0,!0,!0]);const Dl=2305;class jt{constructor(M,et,Bt){this.enable=M,this.mode=et,this.frontFace=Bt}}jt.disabled=new jt(!1,1029,Dl),jt.backCCW=new jt(!0,1029,Dl),jt.frontCCW=new jt(!0,1028,Dl);class Ot{constructor(M,et,Bt){this.func=M,this.mask=et,this.range=Bt}}Ot.ReadOnly=!1,Ot.ReadWrite=!0,Ot.disabled=new Ot(519,Ot.ReadOnly,[0,1]);const Nl=7680;class Zt{constructor(M,et,Bt,Wt,Nt,$t){this.test=M,this.ref=et,this.mask=Bt,this.fail=Wt,this.depthFail=Nt,this.pass=$t}}Zt.disabled=new Zt({func:519,mask:0},0,0,Nl,Nl,Nl);const Yl=new WeakMap;function Ut(M){var et;if(Yl.has(M))return Yl.get(M);{const Bt=null===(et=M.getParameter(M.VERSION))||void 0===et?void 0:et.startsWith("WebGL 2.0");return Yl.set(M,Bt),Bt}}class Vt{get awaitingQuery(){return!!this._readbackQueue}constructor(M){this._readbackWaitFrames=4,this._measureWaitFrames=6,this._texWidth=1,this._texHeight=1,this._measuredError=0,this._updateCount=0,this._lastReadbackFrame=-1e3,this._readbackQueue=null,this._cachedRenderContext=M;const Bt=M.context,Wt=Bt.gl;this._texFormat=Wt.RGBA,this._texType=Wt.UNSIGNED_BYTE;const Nt=new et.aC;Nt.emplaceBack(-1,-1),Nt.emplaceBack(2,-1),Nt.emplaceBack(-1,2);const $t=new et.aE;$t.emplaceBack(0,1,2),this._fullscreenTriangle=new pt(Bt.createVertexBuffer(Nt,El.members),Bt.createIndexBuffer($t),et.aD.simpleSegment(0,0,Nt.length,$t.length)),this._resultBuffer=new Uint8Array(4),Bt.activeTexture.set(Wt.TEXTURE1);const Gr=Wt.createTexture();Wt.bindTexture(Wt.TEXTURE_2D,Gr),Wt.texParameteri(Wt.TEXTURE_2D,Wt.TEXTURE_WRAP_S,Wt.CLAMP_TO_EDGE),Wt.texParameteri(Wt.TEXTURE_2D,Wt.TEXTURE_WRAP_T,Wt.CLAMP_TO_EDGE),Wt.texParameteri(Wt.TEXTURE_2D,Wt.TEXTURE_MIN_FILTER,Wt.NEAREST),Wt.texParameteri(Wt.TEXTURE_2D,Wt.TEXTURE_MAG_FILTER,Wt.NEAREST),Wt.texImage2D(Wt.TEXTURE_2D,0,this._texFormat,this._texWidth,this._texHeight,0,this._texFormat,this._texType,null),this._fbo=Bt.createFramebuffer(this._texWidth,this._texHeight,!1,!1),this._fbo.colorAttachment.set(Gr),Ut(Wt)&&(this._pbo=Wt.createBuffer(),Wt.bindBuffer(Wt.PIXEL_PACK_BUFFER,this._pbo),Wt.bufferData(Wt.PIXEL_PACK_BUFFER,4,Wt.STREAM_READ),Wt.bindBuffer(Wt.PIXEL_PACK_BUFFER,null))}destroy(){const M=this._cachedRenderContext.context.gl;this._fullscreenTriangle.destroy(),this._fbo.destroy(),M.deleteBuffer(this._pbo),this._fullscreenTriangle=null,this._fbo=null,this._pbo=null,this._resultBuffer=null}updateErrorLoop(M,et){const Bt=this._updateCount;return this._readbackQueue?Bt>=this._readbackQueue.frameNumberIssued+this._readbackWaitFrames&&this._tryReadback():Bt>=this._lastReadbackFrame+this._measureWaitFrames&&this._renderErrorTexture(M,et),this._updateCount++,this._measuredError}_bindFramebuffer(){const M=this._cachedRenderContext.context,et=M.gl;M.activeTexture.set(et.TEXTURE1),et.bindTexture(et.TEXTURE_2D,this._fbo.colorAttachment.get()),M.bindFramebuffer.set(this._fbo.framebuffer)}_renderErrorTexture(M,Bt){const Wt=this._cachedRenderContext.context,Nt=Wt.gl;if(this._bindFramebuffer(),Wt.viewport.set([0,0,this._texWidth,this._texHeight]),Wt.clear({color:et.b4.transparent}),this._cachedRenderContext.useProgram("projectionErrorMeasurement").draw(Wt,Nt.TRIANGLES,Ot.disabled,Zt.disabled,Ft.unblended,jt.disabled,((M,et)=>({u_input:M,u_output_expected:et}))(M,Bt),null,null,"$clipping",this._fullscreenTriangle.vertexBuffer,this._fullscreenTriangle.indexBuffer,this._fullscreenTriangle.segments),this._pbo&&Ut(Nt)){Nt.bindBuffer(Nt.PIXEL_PACK_BUFFER,this._pbo),Nt.readBuffer(Nt.COLOR_ATTACHMENT0),Nt.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,0),Nt.bindBuffer(Nt.PIXEL_PACK_BUFFER,null);const M=Nt.fenceSync(Nt.SYNC_GPU_COMMANDS_COMPLETE,0);Nt.flush(),this._readbackQueue={frameNumberIssued:this._updateCount,sync:M}}else this._readbackQueue={frameNumberIssued:this._updateCount,sync:null}}_tryReadback(){const M=this._cachedRenderContext.context.gl;if(this._pbo&&this._readbackQueue&&Ut(M)){const Bt=M.clientWaitSync(this._readbackQueue.sync,0,0);if(Bt===M.WAIT_FAILED)return et.w("WebGL2 clientWaitSync failed."),this._readbackQueue=null,void(this._lastReadbackFrame=this._updateCount);if(Bt===M.TIMEOUT_EXPIRED)return;M.bindBuffer(M.PIXEL_PACK_BUFFER,this._pbo),M.getBufferSubData(M.PIXEL_PACK_BUFFER,0,this._resultBuffer,0,4),M.bindBuffer(M.PIXEL_PACK_BUFFER,null)}else this._bindFramebuffer(),M.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,this._resultBuffer);this._readbackQueue=null,this._measuredError=Vt._parseRGBA8float(this._resultBuffer),this._lastReadbackFrame=this._updateCount}static _parseRGBA8float(M){let et=0;return et+=M[0]/256,et+=M[1]/65536,et+=M[2]/16777216,M[3]<127&&(et=-et),et/128}}const Ol=et.X/128;function Ht(M,Bt){const Wt=void 0!==M.granularity?Math.max(M.granularity,1):1,Nt=Wt+(M.generateBorders?2:0),$t=Wt+(M.extendToNorthPole||M.generateBorders?1:0)+(M.extendToSouthPole||M.generateBorders?1:0),Gr=Nt+1,mn=$t+1,Hn=M.generateBorders?-1:0,so=M.generateBorders||M.extendToNorthPole?-1:0,uo=Wt+(M.generateBorders?1:0),Io=Wt+(M.generateBorders||M.extendToSouthPole?1:0),Po=Gr*mn,To=Nt*$t*6,Eo=Gr*mn>65536;if(Eo&&"16bit"===Bt)throw new Error("Granularity is too large and meshes would not fit inside 16 bit vertex indices.");const Ia=Eo||"32bit"===Bt,Ba=new Int16Array(2*Po);let Ta=0;for(let Bt=so;Bt<=Io;Bt++)for(let Nt=Hn;Nt<=uo;Nt++){let $t=Nt/Wt*et.X;-1===Nt&&($t=-Ol),Nt===Wt+1&&($t=et.X+Ol);let Gr=Bt/Wt*et.X;-1===Bt&&(Gr=M.extendToNorthPole?et.b6:-Ol),Bt===Wt+1&&(Gr=M.extendToSouthPole?et.b7:et.X+Ol),Ba[Ta++]=$t,Ba[Ta++]=Gr}const Va=Ia?new Uint32Array(To):new Uint16Array(To);let za=0;for(let M=0;M<$t;M++)for(let et=0;et0}get latitudeErrorCorrectionRadians(){return this._verticalPerspectiveProjection.latitudeErrorCorrectionRadians}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return"globe"}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy()}updateGPUdependent(M){this._mercatorProjection.updateGPUdependent(M),this._verticalPerspectiveProjection.updateGPUdependent(M)}getMeshFromTileID(M,et,Bt,Wt,Nt){return this.currentProjection.getMeshFromTileID(M,et,Bt,Wt,Nt)}setProjection(M){this._transitionable.setValue("type",(null==M?void 0:M.type)||"mercator")}updateTransitions(M){this._transitioning=this._transitionable.transitioned(M,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(M){this.properties=this._transitioning.possiblyEvaluate(M)}setErrorQueryLatitudeDegrees(M){this._verticalPerspectiveProjection.setErrorQueryLatitudeDegrees(M),this._mercatorProjection.setErrorQueryLatitudeDegrees(M)}}function Yt(M){const et=ei(M.worldSize,M.center.lat);return 2*Math.PI*et}function Jt(M,Bt,Wt,Nt,$t){const Gr=1/(1<<$t),mn=Bt/et.X*Gr+Nt*Gr,Hn=et.bd((M/et.X*Gr+Wt*Gr)*Math.PI*2+Math.PI,2*Math.PI),so=2*Math.atan(Math.exp(Math.PI-mn*Math.PI*2))-.5*Math.PI,uo=Math.cos(so),Io=new Float64Array(3);return Io[0]=Math.sin(Hn)*uo,Io[1]=Math.sin(so),Io[2]=Math.cos(Hn)*uo,Io}function Qt(M){return function(M,et){const Bt=Math.cos(et),Wt=new Float64Array(3);return Wt[0]=Math.sin(M)*Bt,Wt[1]=Math.sin(et),Wt[2]=Math.cos(M)*Bt,Wt}(M.lng*Math.PI/180,M.lat*Math.PI/180)}function ei(M,et){return M/(2*Math.PI)/Math.cos(et*Math.PI/180)}function ti(M){const Bt=Math.asin(M[1])/Math.PI*180,Wt=Math.sqrt(M[0]*M[0]+M[2]*M[2]);if(Wt>1e-6){const Nt=M[0]/Wt,$t=Math.acos(M[2]/Wt),Gr=(Nt>0?$t:-$t)/Math.PI*180;return new et.N(et.aI(Gr,-180,180),Bt)}return new et.N(0,Bt)}function ii(M){return Math.cos(M*Math.PI/180)}function ri(M,Bt){const Wt=ii(M),Nt=ii(Bt);return et.a8(Nt/Wt)}function oi(M,Bt){const Wt=M.rotate(Bt.bearingInRadians),Nt=Bt.zoom+ri(Bt.center.lat,0),$t=et.b9(1/ii(Bt.center.lat),1/ii(Math.min(Math.abs(Bt.center.lat),60)),et.bc(Nt,7,3,0,1)),Gr=360/Yt({worldSize:Bt.worldSize,center:{lat:Bt.center.lat}});return new et.N(Bt.center.lng-Wt.x*Gr*$t,et.ab(Bt.center.lat+Wt.y*Gr,-et.aF,et.aF))}function si(M){const et=.5*M,Bt=Math.sin(et),Wt=Math.cos(et);return Math.log(Bt+Wt)-Math.log(Wt-Bt)}function ai(M,Bt,Wt,Nt){const $t=M.lat+Wt*Nt;if(Math.abs(Wt)>1){const Gr=(Math.sign(M.lat+Wt)!==Math.sign(M.lat)?-Math.abs(M.lat):Math.abs(M.lat))*Math.PI/180,mn=Math.abs(M.lat+Wt)*Math.PI/180,Hn=si(Gr+Nt*(mn-Gr)),so=si(Gr),uo=si(mn);return new et.N(M.lng+Bt*((Hn-so)/(uo-so)),$t)}return new et.N(M.lng+Bt*Nt,$t)}class ni{constructor(M){this._cachePrevious=new Map,this._cache=new Map,this._hadAnyChanges=!1,this._aabbFactory=M}recalculateCache(){if(!this._hadAnyChanges)return;const M=this._cachePrevious;this._cachePrevious=this._cache,this._cache=M,this._cache.clear(),this._hadAnyChanges=!1}getTileAABB(M,et,Bt,Wt){const Nt=`${M.z}_${M.x}_${M.y}`,$t=this._cache.get(Nt);if($t)return $t;const Gr=this._cachePrevious.get(Nt);if(Gr)return this._cache.set(Nt,Gr),Gr;const mn=this._aabbFactory(M,et,Bt,Wt);return this._cache.set(Nt,mn),this._hadAnyChanges=!0,mn}}function li(M,et,Bt){const Wt=M-et;return Wt<0?-Wt:Math.max(0,Wt-Bt)}function ci(M,et,Bt,Wt,Nt){const $t=M-Bt;let Gr;return Gr=$t<0?Math.min(-$t,1+$t-Nt):$t>1?Math.min(Math.max($t-Nt,0),1-$t):0,Math.max(Gr,li(et,Wt,Nt))}class hi{constructor(){this._aabbCache=new ni(this._computeTileAABB)}recalculateCache(){this._aabbCache.recalculateCache()}distanceToTile2d(M,et,Bt,Wt){const Nt=1<4}allowWorldCopies(){return!1}getTileAABB(M,et,Bt,Wt){return this._aabbCache.getTileAABB(M,et,Bt,Wt)}_computeTileAABB(M,Bt,Wt,Nt){if(M.z<=0)return new Mt([-1,-1,-1],[1,1,1]);if(1===M.z)return new Mt([0===M.x?-1:0,0===M.y?0:-1,-1],[0===M.x?0:1,0===M.y?1:0,1]);{const Bt=[Jt(0,0,M.x,M.y,M.z),Jt(et.X,0,M.x,M.y,M.z),Jt(et.X,et.X,M.x,M.y,M.z),Jt(0,et.X,M.x,M.y,M.z)],Wt=[1,1,1],Nt=[-1,-1,-1];for(const M of Bt)for(let et=0;et<3;et++)Wt[et]=Math.min(Wt[et],M[et]),Nt[et]=Math.max(Nt[et],M[et]);if(0===M.y||M.y===(1<{this._calcMatrices()},getConstrained:(M,et)=>this.getConstrained(M,et)}),this._coveringTilesDetailsProvider=new hi}clone(){const M=new ui;return M.apply(this),M}apply(M,et){this._globeLatitudeErrorCorrectionRadians=et||0,this._helper.apply(M)}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._globeViewProjMatrixNoCorrection}get inverseProjectionMatrix(){return this._globeProjMatrixInverted}get cameraPosition(){const M=et.bf();return M[0]=this._cameraPosition[0],M[1]=this._cameraPosition[1],M[2]=this._cameraPosition[2],M}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}getProjectionData(M){const{overscaledTileID:et,applyGlobeMatrix:Bt}=M,Wt=this._helper.getMercatorTileCoordinates(et);return{mainMatrix:this._globeViewProjMatrix32f,tileMercatorCoords:Wt,clippingPlane:this._cachedClippingPlane,projectionTransition:Bt?1:0,fallbackMatrix:this._globeViewProjMatrix32f}}_computeClippingPlane(M){const Bt=this.pitchInRadians,Wt=this.cameraToCenterDistance/M,Nt=Math.sin(Bt)*Wt,$t=Math.cos(Bt)*Wt+1,Gr=1/Math.sqrt(Nt*Nt+$t*$t)*1;let mn=-Nt,Hn=$t;const so=Math.sqrt(mn*mn+Hn*Hn);mn/=so,Hn/=so;const uo=[0,mn,Hn];return et.bg(uo,uo,[0,0,0],-this.bearingInRadians),et.bh(uo,uo,[0,0,0],-1*this.center.lat*Math.PI/180),et.bi(uo,uo,[0,0,0],this.center.lng*Math.PI/180),et.aL(uo,uo,.25),[...uo,.25*-Gr]}isLocationOccluded(M){return!this.isSurfacePointVisible(Qt(M))}transformLightDirection(M){const Bt=this._helper._center.lng*Math.PI/180,Wt=this._helper._center.lat*Math.PI/180,Nt=Math.cos(Wt),$t=[Math.sin(Bt)*Nt,Math.sin(Wt),Math.cos(Bt)*Nt],Gr=[$t[2],0,-$t[0]],mn=[0,0,0];et.aR(mn,Gr,$t),et.aQ(Gr,Gr),et.aQ(mn,mn);const Hn=[0,0,0];return et.aQ(Hn,[Gr[0]*M[0]+mn[0]*M[1]+$t[0]*M[2],Gr[1]*M[0]+mn[1]*M[1]+$t[1]*M[2],Gr[2]*M[0]+mn[2]*M[1]+$t[2]*M[2]]),Hn}getPixelScale(){return 1/Math.cos(this._helper._center.lat*Math.PI/180)}getCircleRadiusCorrection(){return Math.cos(this._helper._center.lat*Math.PI/180)}getPitchedTextCorrection(M,Bt,Wt){const Nt=function(M,Bt,Wt){const Nt=1/(1<$t&&($t=Bt),Wtmn&&(mn=Wt)}const uo=[so.lng+Gr,so.lat+Hn,so.lng+$t,so.lat+mn];return this.isSurfacePointOnScreen([0,1,0])&&(uo[3]=90,uo[0]=-180,uo[2]=180),this.isSurfacePointOnScreen([0,-1,0])&&(uo[1]=-90,uo[0]=-180,uo[2]=180),new V(uo)}getConstrained(M,Bt){const Wt=et.ab(M.lat,-et.aF,et.aF),Nt=et.ab(+Bt,this.minZoom+ri(0,Wt),this.maxZoom);return{center:new et.N(M.lng,Wt),zoom:Nt}}calculateCenterFromCameraLngLatAlt(M,et,Bt,Wt){return this._helper.calculateCenterFromCameraLngLatAlt(M,et,Bt,Wt)}setLocationAtPoint(M,Bt){const Wt=Qt(this.unprojectScreenPoint(Bt)),Nt=Qt(M),$t=et.bf();et.bl($t);const Gr=et.bf();et.bi(Gr,Wt,$t,-this.center.lng*Math.PI/180),et.bh(Gr,Gr,$t,this.center.lat*Math.PI/180);const mn=Nt[0]*Nt[0]+Nt[2]*Nt[2],Hn=Gr[0]*Gr[0];if(mn=-Ta&&Eo<=Ta,za=Ba>=-Ta&&Ba<=Ta;let Fa,Ea;if(Va&&za){const M=this.center.lng*Math.PI/180,Bt=this.center.lat*Math.PI/180;et.bp(Io,M)+et.bp(Eo,Bt)=0}isSurfacePointOnScreen(M){if(!this.isSurfacePointVisible(M))return!1;const Bt=et.be();return et.al(Bt,[...M,1],this._globeViewProjMatrixNoCorrection),Bt[0]/=Bt[3],Bt[1]/=Bt[3],Bt[2]/=Bt[3],Bt[0]>-1&&Bt[0]<1&&Bt[1]>-1&&Bt[1]<1&&Bt[2]>-1&&Bt[2]<1}rayPlanetIntersection(M,Bt){const Wt=et.aS(M,Bt),Nt=et.bf(),$t=et.bf();et.aL($t,Bt,Wt),et.aP(Nt,M,$t);const Gr=1-et.aS(Nt,Nt);if(Gr<0)return null;const mn=et.aS(M,M)-1,Hn=-Wt+(Wt<0?1:-1)*Math.sqrt(Gr),so=mn/Hn,uo=Hn;return{tMin:Math.min(so,uo),tMax:Math.max(so,uo)}}unprojectScreenPoint(M){const Bt=this._cameraPosition,Wt=this.getRayDirectionFromPixel(M),Nt=this.rayPlanetIntersection(Bt,Wt);if(Nt){const M=et.bf();et.aM(M,Bt,[Wt[0]*Nt.tMin,Wt[1]*Nt.tMin,Wt[2]*Nt.tMin]);const $t=et.bf();return et.aQ($t,M),ti($t)}const $t=this._cachedClippingPlane[0]*Wt[0]+this._cachedClippingPlane[1]*Wt[1]+this._cachedClippingPlane[2]*Wt[2],Gr=-et.bn(this._cachedClippingPlane,Bt)/$t,mn=et.bf();if(Gr>0)et.aM(mn,Bt,[Wt[0]*Gr,Wt[1]*Gr,Wt[2]*Gr]);else{const M=et.bf();et.aM(M,Bt,[2*Wt[0],2*Wt[1],2*Wt[2]]);const Nt=et.bn(this._cachedClippingPlane,M);et.aP(mn,M,[this._cachedClippingPlane[0]*Nt,this._cachedClippingPlane[1]*Nt,this._cachedClippingPlane[2]*Nt])}const Hn=et.bf();return et.aQ(Hn,mn),ti(Hn)}getMatrixForModel(M,Bt){const Wt=et.N.convert(M),Nt=1/et.bo,$t=et.a_();return et.bj($t,$t,Wt.lng/180*Math.PI),et.aY($t,$t,-Wt.lat/180*Math.PI),et.J($t,$t,[0,0,1+Bt/et.bo]),et.aY($t,$t,.5*Math.PI),et.K($t,$t,[Nt,Nt,Nt]),$t}getProjectionDataForCustomLayer(M=!0){const Bt=this.getProjectionData({overscaledTileID:new et.S(0,0,0,0,0),applyGlobeMatrix:M});return Bt.tileMercatorCoords=[0,0,1,1],Bt}getFastPathSimpleProjectionMatrix(M){}}class di{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(M){this._helper.setMinZoom(M)}setMaxZoom(M){this._helper.setMaxZoom(M)}setMinPitch(M){this._helper.setMinPitch(M)}setMaxPitch(M){this._helper.setMaxPitch(M)}setRenderWorldCopies(M){this._helper.setRenderWorldCopies(M)}setBearing(M){this._helper.setBearing(M)}setPitch(M){this._helper.setPitch(M)}setRoll(M){this._helper.setRoll(M)}setFov(M){this._helper.setFov(M)}setZoom(M){this._helper.setZoom(M)}setCenter(M){this._helper.setCenter(M)}setElevation(M){this._helper.setElevation(M)}setMinElevationForCurrentTile(M){this._helper.setMinElevationForCurrentTile(M)}setPadding(M){this._helper.setPadding(M)}interpolatePadding(M,et,Bt){return this._helper.interpolatePadding(M,et,Bt)}isPaddingEqual(M){return this._helper.isPaddingEqual(M)}resize(M,et,Bt=!0){this._helper.resize(M,et,Bt)}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(M){this._helper.setMaxBounds(M)}overrideNearFarZ(M,et){this._helper.overrideNearFarZ(M,et)}clearNearFarZOverride(){this._helper.clearNearFarZOverride()}getCameraQueryGeometry(M){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),M)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}get isGlobeRendering(){return this._globeness>0}setTransitionState(M,et){this._globeness=M,this._globeLatitudeErrorCorrectionRadians=et,this._calcMatrices(),this._verticalPerspectiveTransform.getCoveringTilesDetailsProvider().recalculateCache(),this._mercatorTransform.getCoveringTilesDetailsProvider().recalculateCache()}get currentTransform(){return this.isGlobeRendering?this._verticalPerspectiveTransform:this._mercatorTransform}constructor(){this._globeLatitudeErrorCorrectionRadians=0,this._globeness=1,this._helper=new Et({calcMatrices:()=>{this._calcMatrices()},getConstrained:(M,et)=>this.getConstrained(M,et)}),this._globeness=1,this._mercatorTransform=new Dt,this._verticalPerspectiveTransform=new ui}clone(){const M=new di;return M._globeness=this._globeness,M._globeLatitudeErrorCorrectionRadians=this._globeLatitudeErrorCorrectionRadians,M.apply(this),M}apply(M){this._helper.apply(M),this._mercatorTransform.apply(this),this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians)}get projectionMatrix(){return this.currentTransform.projectionMatrix}get modelViewProjectionMatrix(){return this.currentTransform.modelViewProjectionMatrix}get inverseProjectionMatrix(){return this.currentTransform.inverseProjectionMatrix}get cameraPosition(){return this.currentTransform.cameraPosition}getProjectionData(M){const et=this._mercatorTransform.getProjectionData(M),Bt=this._verticalPerspectiveTransform.getProjectionData(M);return{mainMatrix:this.isGlobeRendering?Bt.mainMatrix:et.mainMatrix,clippingPlane:Bt.clippingPlane,tileMercatorCoords:Bt.tileMercatorCoords,projectionTransition:M.applyGlobeMatrix?this._globeness:0,fallbackMatrix:et.fallbackMatrix}}isLocationOccluded(M){return this.currentTransform.isLocationOccluded(M)}transformLightDirection(M){return this.currentTransform.transformLightDirection(M)}getPixelScale(){return et.b9(this._mercatorTransform.getPixelScale(),this._verticalPerspectiveTransform.getPixelScale(),this._globeness)}getCircleRadiusCorrection(){return et.b9(this._mercatorTransform.getCircleRadiusCorrection(),this._verticalPerspectiveTransform.getCircleRadiusCorrection(),this._globeness)}getPitchedTextCorrection(M,Bt,Wt){const Nt=this._mercatorTransform.getPitchedTextCorrection(M,Bt,Wt),$t=this._verticalPerspectiveTransform.getPitchedTextCorrection(M,Bt,Wt);return et.b9(Nt,$t,this._globeness)}projectTileCoordinates(M,et,Bt,Wt){return this.currentTransform.projectTileCoordinates(M,et,Bt,Wt)}_calcMatrices(){this._helper._width&&this._helper._height&&(this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians),this._helper._nearZ=this._verticalPerspectiveTransform.nearZ,this._helper._farZ=this._verticalPerspectiveTransform.farZ,this._mercatorTransform.apply(this,!0,this.isGlobeRendering),this._helper._nearZ=this._mercatorTransform.nearZ,this._helper._farZ=this._mercatorTransform.farZ)}calculateFogMatrix(M){return this.currentTransform.calculateFogMatrix(M)}getVisibleUnwrappedCoordinates(M){return this.currentTransform.getVisibleUnwrappedCoordinates(M)}getCameraFrustum(){return this.currentTransform.getCameraFrustum()}getClippingPlane(){return this.currentTransform.getClippingPlane()}getCoveringTilesDetailsProvider(){return this.currentTransform.getCoveringTilesDetailsProvider()}recalculateZoomAndCenter(M){this._mercatorTransform.recalculateZoomAndCenter(M),this._verticalPerspectiveTransform.recalculateZoomAndCenter(M)}maxPitchScaleFactor(){return this._mercatorTransform.maxPitchScaleFactor()}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){return this._helper.getCameraLngLat()}lngLatToCameraDepth(M,et){return this.currentTransform.lngLatToCameraDepth(M,et)}populateCache(M){this._mercatorTransform.populateCache(M),this._verticalPerspectiveTransform.populateCache(M)}getBounds(){return this.currentTransform.getBounds()}getConstrained(M,et){return this.currentTransform.getConstrained(M,et)}calculateCenterFromCameraLngLatAlt(M,et,Bt,Wt){return this._helper.calculateCenterFromCameraLngLatAlt(M,et,Bt,Wt)}setLocationAtPoint(M,et){if(!this.isGlobeRendering)return this._mercatorTransform.setLocationAtPoint(M,et),void this.apply(this._mercatorTransform);this._verticalPerspectiveTransform.setLocationAtPoint(M,et),this.apply(this._verticalPerspectiveTransform)}locationToScreenPoint(M,et){return this.currentTransform.locationToScreenPoint(M,et)}screenPointToMercatorCoordinate(M,et){return this.currentTransform.screenPointToMercatorCoordinate(M,et)}screenPointToLocation(M,et){return this.currentTransform.screenPointToLocation(M,et)}isPointOnMapSurface(M,et){return this.currentTransform.isPointOnMapSurface(M,et)}getRayDirectionFromPixel(M){return this._verticalPerspectiveTransform.getRayDirectionFromPixel(M)}getMatrixForModel(M,et){return this.currentTransform.getMatrixForModel(M,et)}getProjectionDataForCustomLayer(M=!0){const et=this._mercatorTransform.getProjectionDataForCustomLayer(M);if(!this.isGlobeRendering)return et;const Bt=this._verticalPerspectiveTransform.getProjectionDataForCustomLayer(M);return Bt.fallbackMatrix=et.mainMatrix,Bt}getFastPathSimpleProjectionMatrix(M){return this.currentTransform.getFastPathSimpleProjectionMatrix(M)}}class _i{get useGlobeControls(){return!0}handlePanInertia(M,Bt){const Wt=oi(M,Bt);return Math.abs(Wt.lng-Bt.center.lng)>180&&(Wt.lng=Bt.center.lng+179.5*Math.sign(Wt.lng-Bt.center.lng)),{easingCenter:Wt,easingOffset:new et.P(0,0)}}handleMapControlsRollPitchBearingZoom(M,Bt){const Wt=M.around,Nt=Bt.screenPointToLocation(Wt);M.bearingDelta&&Bt.setBearing(Bt.bearing+M.bearingDelta),M.pitchDelta&&Bt.setPitch(Bt.pitch+M.pitchDelta),M.rollDelta&&Bt.setRoll(Bt.roll+M.rollDelta);const $t=Bt.zoom;M.zoomDelta&&Bt.setZoom(Bt.zoom+M.zoomDelta);const Gr=Bt.zoom-$t;if(0===Gr)return;const mn=et.bk(Bt.center.lng,Nt.lng),Hn=mn/(Math.abs(mn/180)+1),so=et.bk(Bt.center.lat,Nt.lat),uo=Bt.getRayDirectionFromPixel(Wt),Io=Bt.cameraPosition,Po=-1*et.aS(Io,uo),To=et.bf();et.aM(To,Io,[uo[0]*Po,uo[1]*Po,uo[2]*Po]);const Eo=et.bq(To)-1,Ia=Math.exp(.5*-Math.max(Eo-.3,0)),Ba=ei(Bt.worldSize,Bt.center.lat)/Math.min(Bt.width,Bt.height),Ta=et.bc(Ba,.9,.5,1,.25),Va=(1-et.aG(-Gr))*Math.min(Ia,Ta),za=Bt.center.lat,Fa=Bt.zoom,Ea=new et.N(Bt.center.lng+Hn*Va,et.ab(Bt.center.lat+so*Va,-et.aF,et.aF));Bt.setLocationAtPoint(Nt,Wt);const La=Bt.center,Da=et.bc(Math.abs(mn),45,85,0,1),Ka=et.bc(Ba,.75,.35,0,1),Oa=Math.pow(Math.max(Da,Ka),.25),$a=et.bk(La.lng,Ea.lng),Al=et.bk(La.lat,Ea.lat);Bt.setCenter(new et.N(La.lng+$a*Oa,La.lat+Al*Oa).wrap()),Bt.setZoom(Fa+ri(za,Bt.center.lat))}handleMapControlsPan(M,et,Bt){if(!M.panDelta)return;const Wt=et.center.lat,Nt=et.zoom;et.setCenter(oi(M.panDelta,et).wrap()),et.setZoom(Nt+ri(Wt,et.center.lat))}cameraForBoxAndBearing(M,Bt,Wt,Nt,$t){const Gr=Lt(M,Bt,Wt,Nt,$t),mn=Bt.left/$t.width*2-1,Hn=($t.width-Bt.right)/$t.width*2-1,so=Bt.top/$t.height*-2+1,uo=($t.height-Bt.bottom)/$t.height*-2+1,Io=et.bk(Wt.getWest(),Wt.getEast())<0,Po=Io?Wt.getEast():Wt.getWest(),To=Io?Wt.getWest():Wt.getEast(),Eo=Math.max(Wt.getNorth(),Wt.getSouth()),Ia=Math.min(Wt.getNorth(),Wt.getSouth()),Ba=Po+.5*et.bk(Po,To),Ta=Eo+.5*et.bk(Eo,Ia),Va=$t.clone();Va.setCenter(Gr.center),Va.setBearing(Gr.bearing),Va.setPitch(0),Va.setRoll(0),Va.setZoom(Gr.zoom);const za=Va.modelViewProjectionMatrix,Fa=[Qt(Wt.getNorthWest()),Qt(Wt.getNorthEast()),Qt(Wt.getSouthWest()),Qt(Wt.getSouthEast()),Qt(new et.N(To,Ta)),Qt(new et.N(Po,Ta)),Qt(new et.N(Ba,Eo)),Qt(new et.N(Ba,Ia))],Ea=Qt(Gr.center);let La=Number.POSITIVE_INFINITY;for(const M of Fa)mn<0&&(La=_i.getLesserNonNegativeNonNull(La,_i.solveVectorScale(M,Ea,za,"x",mn))),Hn>0&&(La=_i.getLesserNonNegativeNonNull(La,_i.solveVectorScale(M,Ea,za,"x",Hn))),so>0&&(La=_i.getLesserNonNegativeNonNull(La,_i.solveVectorScale(M,Ea,za,"y",so))),uo<0&&(La=_i.getLesserNonNegativeNonNull(La,_i.solveVectorScale(M,Ea,za,"y",uo)));if(Number.isFinite(La)&&0!==La)return Gr.zoom=Va.zoom+et.a8(La),Gr;zt()}handleJumpToCenterZoom(M,Bt){const Wt=M.center.lat,Nt=M.getConstrained(Bt.center?et.N.convert(Bt.center):M.center,M.zoom).center;M.setCenter(Nt.wrap());const $t=void 0!==Bt.zoom?+Bt.zoom:M.zoom+ri(Wt,Nt.lat);M.zoom!==$t&&M.setZoom($t)}handleEaseTo(M,Bt){const Wt=M.zoom,Nt=M.center,$t=M.padding,Gr={roll:M.roll,pitch:M.pitch,bearing:M.bearing},mn={roll:void 0===Bt.roll?M.roll:Bt.roll,pitch:void 0===Bt.pitch?M.pitch:Bt.pitch,bearing:void 0===Bt.bearing?M.bearing:Bt.bearing},Hn=void 0!==Bt.zoom,so=!M.isPaddingEqual(Bt.padding);let uo=!1;const Io=Bt.center?et.N.convert(Bt.center):Nt,Po=M.getConstrained(Io,Wt).center;Ct(M,Po);const To=M.clone();To.setCenter(Po),To.setZoom(Hn?+Bt.zoom:Wt+ri(Nt.lat,Io.lat)),To.setBearing(Bt.bearing);const Eo=new et.P(et.ab(M.centerPoint.x+Bt.offsetAsPoint.x,0,M.width),et.ab(M.centerPoint.y+Bt.offsetAsPoint.y,0,M.height));To.setLocationAtPoint(Po,Eo);const Ia=(Bt.offset&&Bt.offsetAsPoint.mag())>0?To.center:Po,Ba=Hn?+Bt.zoom:Wt+ri(Nt.lat,Ia.lat),Ta=Wt+ri(Nt.lat,0),Va=Ba+ri(Ia.lat,0),za=et.bk(Nt.lng,Ia.lng),Fa=et.bk(Nt.lat,Ia.lat),Ea=et.aG(Va-Ta);return uo=Ba!==Wt,{easeFunc:Wt=>{if(et.b3(Gr,mn)||At({startEulerAngles:Gr,endEulerAngles:mn,tr:M,k:Wt,useSlerp:Gr.roll!=mn.roll}),so&&M.interpolatePadding($t,Bt.padding,Wt),Bt.around)et.w("Easing around a point is not supported under globe projection."),M.setLocationAtPoint(Bt.around,Bt.aroundPoint);else{const et=Va>Ta?Math.min(2,Ea):Math.max(.5,Ea),Bt=Math.pow(et,1-Wt),$t=ai(Nt,za,Fa,Wt*Bt);M.setCenter($t.wrap())}if(uo){const Bt=et.y.number(Ta,Va,Wt)+ri(0,M.center.lat);M.setZoom(Bt)}},isZooming:uo,elevationCenter:Ia}}handleFlyTo(M,Bt){const Wt=void 0!==Bt.zoom,Nt=M.center,$t=M.zoom,Gr=!M.isPaddingEqual(Bt.padding),mn=M.getConstrained(et.N.convert(Bt.center||Bt.locationAtOffset),$t).center,Hn=Wt?+Bt.zoom:M.zoom+ri(M.center.lat,mn.lat),so=M.clone();so.setCenter(mn),Gr&&so.setPadding(Bt.padding),so.setZoom(Hn),so.setBearing(Bt.bearing);const uo=new et.P(et.ab(M.centerPoint.x+Bt.offsetAsPoint.x,0,M.width),et.ab(M.centerPoint.y+Bt.offsetAsPoint.y,0,M.height));so.setLocationAtPoint(mn,uo);const Io=so.center;Ct(M,Io);const Po=function(M,Bt,Wt){const Nt=Qt(Bt),$t=Qt(Wt),Gr=et.aS(Nt,$t),mn=Math.acos(Gr),Hn=Yt(M);return mn/(2*Math.PI)*Hn}(M,Nt,Io),To=$t+ri(Nt.lat,0),Eo=Hn+ri(Io.lat,0),Ia=et.aG(Eo-To);let Ba;if("number"==typeof Bt.minZoom){const Wt=+Bt.minZoom+ri(Io.lat,0),Nt=Math.min(Wt,To,Eo)+ri(0,Io.lat),$t=M.getConstrained(Io,Nt).zoom+ri(Io.lat,0);Ba=et.aG($t-To)}const Ta=et.bk(Nt.lng,Io.lng),Va=et.bk(Nt.lat,Io.lat);return{easeFunc:(Bt,Wt,$t,Gr)=>{const mn=ai(Nt,Ta,Va,$t),so=1===Bt?Io:mn;M.setCenter(so.wrap());const uo=To+et.a8(Wt);M.setZoom(1===Bt?Hn:uo+ri(0,so.lat))},scaleOfZoom:Ia,targetCenter:Io,scaleOfMinZoom:Ba,pixelPathLength:Po}}static solveVectorScale(M,et,Bt,Wt,Nt){const $t="x"===Wt?[Bt[0],Bt[4],Bt[8],Bt[12]]:[Bt[1],Bt[5],Bt[9],Bt[13]],Gr=[Bt[3],Bt[7],Bt[11],Bt[15]],mn=M[0]*$t[0]+M[1]*$t[1]+M[2]*$t[2],Hn=M[0]*Gr[0]+M[1]*Gr[1]+M[2]*Gr[2],so=et[0]*$t[0]+et[1]*$t[1]+et[2]*$t[2],uo=et[0]*Gr[0]+et[1]*Gr[1]+et[2]*Gr[2];return so+Nt*Hn===mn+Nt*uo||Gr[3]*(mn-so)+$t[3]*(uo-Hn)+mn*uo==so*Hn?null:(so+$t[3]-Nt*uo-Nt*Gr[3])/(so-mn-Nt*uo+Nt*Hn)}static getLesserNonNegativeNonNull(M,et){return null!==et&&et>=0&&etet.t(M,Bt&&Bt.filter((M=>"source.canvas"!==M.identifier))),ql=et.br();class gi extends et.E{constructor(M,Bt={}){super(),this._rtlPluginLoaded=()=>{for(const M in this.sourceCaches){const et=this.sourceCaches[M].getSource().type;"vector"!==et&&"geojson"!==et||this.sourceCaches[M].reload()}},this.map=M,this.dispatcher=new B(F(),M._getMapId()),this.dispatcher.registerMessageHandler("GG",((M,et)=>this.getGlyphs(M,et))),this.dispatcher.registerMessageHandler("GI",((M,et)=>this.getImages(M,et))),this.imageManager=new b,this.imageManager.setEventedParent(this),this.glyphManager=new P(M._requestManager,Bt.localIdeographFontFamily),this.lineAtlas=new R(256,512),this.crossTileSymbolIndex=new ht,this._spritesImagesIds={},this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new et.bs,this._loaded=!1,this._availableImages=[],this._resetUpdates(),this.dispatcher.broadcast("SR",et.bt()),oe().on(Fa,this._rtlPluginLoaded),this.on("data",(M=>{if("source"!==M.dataType||"metadata"!==M.sourceDataType)return;const et=this.sourceCaches[M.sourceId];if(!et)return;const Bt=et.getSource();if(Bt&&Bt.vectorLayerIds)for(const M in this._layers){const et=this._layers[M];et.source===Bt.id&&this._validateLayer(et)}}))}loadURL(M,Bt={},Wt){this.fire(new et.k("dataloading",{dataType:"style"})),Bt.validate="boolean"!=typeof Bt.validate||Bt.validate;const Nt=this.map._requestManager.transformRequest(M,"Style");this._loadStyleRequest=new AbortController;const $t=this._loadStyleRequest;et.h(Nt,this._loadStyleRequest).then((M=>{this._loadStyleRequest=null,this._load(M.data,Bt,Wt)})).catch((M=>{this._loadStyleRequest=null,M&&!$t.signal.aborted&&this.fire(new et.j(M))}))}loadJSON(M,Bt={},Wt){this.fire(new et.k("dataloading",{dataType:"style"})),this._frameRequest=new AbortController,$t.frameAsync(this._frameRequest).then((()=>{this._frameRequest=null,Bt.validate=!1!==Bt.validate,this._load(M,Bt,Wt)})).catch((()=>{}))}loadEmpty(){this.fire(new et.k("dataloading",{dataType:"style"})),this._load(ql,{validate:!1})}_load(M,Bt,Wt){var Nt,$t;const Gr=Bt.transformStyle?Bt.transformStyle(Wt,M):M;if(!Bt.validate||!mi(this,et.u(Gr))){this._loaded=!0,this.stylesheet=Gr;for(const M in Gr.sources)this.addSource(M,Gr.sources[M],{validate:!1});Gr.sprite?this._loadSprite(Gr.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(Gr.glyphs),this._createLayers(),this.light=new E(this.stylesheet.light),this._setProjectionInternal((null===(Nt=this.stylesheet.projection)||void 0===Nt?void 0:Nt.type)||"mercator"),this.sky=new S(this.stylesheet.sky),this.map.setTerrain(null!==($t=this.stylesheet.terrain)&&void 0!==$t?$t:null),this.fire(new et.k("data",{dataType:"style"})),this.fire(new et.k("style.load"))}}_createLayers(){const M=et.bu(this.stylesheet.layers);this.dispatcher.broadcast("SL",M),this._order=M.map((M=>M.id)),this._layers={},this._serializedLayers=null;for(const Bt of M){const M=et.bv(Bt);M.setEventedParent(this,{layer:{id:Bt.id}}),this._layers[Bt.id]=M}}_loadSprite(M,Bt=!1,Wt=void 0){let Nt;this.imageManager.setLoaded(!1),this._spriteRequest=new AbortController,function(M,Bt,Wt,Nt){return et._(this,void 0,void 0,(function*(){const Gr=f(M),mn=Wt>1?"@2x":"",Hn={},so={};for(const{id:M,url:Wt}of Gr){const $t=Bt.transformRequest(g(Wt,mn,".json"),"SpriteJSON");Hn[M]=et.h($t,Nt);const Gr=Bt.transformRequest(g(Wt,mn,".png"),"SpriteImage");so[M]=Io.getImage(Gr,Nt)}return yield Promise.all([...Object.values(Hn),...Object.values(so)]),function(M,Bt){return et._(this,void 0,void 0,(function*(){const et={};for(const Wt in M){et[Wt]={};const Nt=$t.getImageCanvasContext((yield Bt[Wt]).data),Gr=(yield M[Wt]).data;for(const M in Gr){const{width:Bt,height:$t,x:mn,y:Hn,sdf:so,pixelRatio:uo,stretchX:Io,stretchY:Po,content:To,textFitWidth:Eo,textFitHeight:Ia}=Gr[M];et[Wt][M]={data:null,pixelRatio:uo,sdf:so,stretchX:Io,stretchY:Po,content:To,textFitWidth:Eo,textFitHeight:Ia,spriteData:{width:Bt,height:$t,x:mn,y:Hn,context:Nt}}}}return et}))}(Hn,so)}))}(M,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((M=>{if(this._spriteRequest=null,M)for(const et in M){this._spritesImagesIds[et]=[];const Wt=this._spritesImagesIds[et]?this._spritesImagesIds[et].filter((et=>!(et in M))):[];for(const M of Wt)this.imageManager.removeImage(M),this._changedImages[M]=!0;for(const Wt in M[et]){const Nt="default"===et?Wt:`${et}:${Wt}`;this._spritesImagesIds[et].push(Nt),Nt in this.imageManager.images?this.imageManager.updateImage(Nt,M[et][Wt],!1):this.imageManager.addImage(Nt,M[et][Wt]),Bt&&(this._changedImages[Nt]=!0)}}})).catch((M=>{this._spriteRequest=null,Nt=M,this.fire(new et.j(Nt))})).finally((()=>{this.imageManager.setLoaded(!0),this._availableImages=this.imageManager.listImages(),Bt&&(this._changed=!0),this.dispatcher.broadcast("SI",this._availableImages),this.fire(new et.k("data",{dataType:"style"})),Wt&&Wt(Nt)}))}_unloadSprite(){for(const M of Object.values(this._spritesImagesIds).flat())this.imageManager.removeImage(M),this._changedImages[M]=!0;this._spritesImagesIds={},this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new et.k("data",{dataType:"style"}))}_validateLayer(M){const Bt=this.sourceCaches[M.source];if(!Bt)return;const Wt=M.sourceLayer;if(!Wt)return;const Nt=Bt.getSource();("geojson"===Nt.type||Nt.vectorLayerIds&&-1===Nt.vectorLayerIds.indexOf(Wt))&&this.fire(new et.j(new Error(`Source layer "${Wt}" does not exist on source "${Nt.id}" as specified by style layer "${M.id}".`)))}loaded(){if(!this._loaded)return!1;if(Object.keys(this._updatedSources).length)return!1;for(const M in this.sourceCaches)if(!this.sourceCaches[M].loaded())return!1;return!!this.imageManager.isLoaded()}_serializeByIds(M,Bt=!1){const Wt=this._serializedAllLayers();if(!M||0===M.length)return Object.values(Bt?et.bw(Wt):Wt);const Nt=[];for(const $t of M)if(Wt[$t]){const M=Bt?et.bw(Wt[$t]):Wt[$t];Nt.push(M)}return Nt}_serializedAllLayers(){let M=this._serializedLayers;if(M)return M;M=this._serializedLayers={};const et=Object.keys(this._layers);for(const Bt of et){const et=this._layers[Bt];"custom"!==et.type&&(M[Bt]=et.serialize())}return M}hasTransitions(){var M,et,Bt;if(null===(M=this.light)||void 0===M?void 0:M.hasTransition())return!0;if(null===(et=this.sky)||void 0===et?void 0:et.hasTransition())return!0;if(null===(Bt=this.projection)||void 0===Bt?void 0:Bt.hasTransition())return!0;for(const M in this.sourceCaches)if(this.sourceCaches[M].hasTransition())return!0;for(const M in this._layers)if(this._layers[M].hasTransition())return!0;return!1}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading.")}update(M){if(!this._loaded)return;const Bt=this._changed;if(Bt){const et=Object.keys(this._updatedLayers),Bt=Object.keys(this._removedLayers);(et.length||Bt.length)&&this._updateWorkerLayers(et,Bt);for(const M in this._updatedSources){const et=this._updatedSources[M];if("reload"===et)this._reloadSource(M);else{if("clear"!==et)throw new Error(`Invalid action ${et}`);this._clearSource(M)}}this._updateTilesForChangedImages(),this._updateTilesForChangedGlyphs();for(const et in this._updatedPaintProps)this._layers[et].updateTransitions(M);this.light.updateTransitions(M),this.sky.updateTransitions(M),this._resetUpdates()}const Wt={};for(const M in this.sourceCaches){const et=this.sourceCaches[M];Wt[M]=et.used,et.used=!1}for(const et of this._order){const Bt=this._layers[et];Bt.recalculate(M,this._availableImages),!Bt.isHidden(M.zoom)&&Bt.source&&(this.sourceCaches[Bt.source].used=!0)}for(const M in Wt){const Bt=this.sourceCaches[M];!!Wt[M]!=!!Bt.used&&Bt.fire(new et.k("data",{sourceDataType:"visibility",dataType:"source",sourceId:M}))}this.light.recalculate(M),this.sky.recalculate(M),this.projection.recalculate(M),this.z=M.zoom,Bt&&this.fire(new et.k("data",{dataType:"style"}))}_updateTilesForChangedImages(){const M=Object.keys(this._changedImages);if(M.length){for(const et in this.sourceCaches)this.sourceCaches[et].reloadTilesForDependencies(["icons","patterns"],M);this._changedImages={}}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const M in this.sourceCaches)this.sourceCaches[M].reloadTilesForDependencies(["glyphs"],[""]);this._glyphsDidChange=!1}}_updateWorkerLayers(M,et){this.dispatcher.broadcast("UL",{layers:this._serializeByIds(M,!1),removedIds:et})}_resetUpdates(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={},this._glyphsDidChange=!1}setState(M,Bt={}){var Wt;this._checkLoaded();const Nt=this.serialize();if(M=Bt.transformStyle?Bt.transformStyle(Nt,M):M,(null===(Wt=Bt.validate)||void 0===Wt||Wt)&&mi(this,et.u(M)))return!1;(M=et.bw(M)).layers=et.bu(M.layers);const $t=et.bx(Nt,M),Gr=this._getOperationsToPerform($t);if(Gr.unimplemented.length>0)throw new Error(`Unimplemented: ${Gr.unimplemented.join(", ")}.`);if(0===Gr.operations.length)return!1;for(const M of Gr.operations)M();return this.stylesheet=M,this._serializedLayers=null,!0}_getOperationsToPerform(M){const et=[],Bt=[];for(const Wt of M)switch(Wt.command){case"setCenter":case"setZoom":case"setBearing":case"setPitch":case"setRoll":continue;case"addLayer":et.push((()=>this.addLayer.apply(this,Wt.args)));break;case"removeLayer":et.push((()=>this.removeLayer.apply(this,Wt.args)));break;case"setPaintProperty":et.push((()=>this.setPaintProperty.apply(this,Wt.args)));break;case"setLayoutProperty":et.push((()=>this.setLayoutProperty.apply(this,Wt.args)));break;case"setFilter":et.push((()=>this.setFilter.apply(this,Wt.args)));break;case"addSource":et.push((()=>this.addSource.apply(this,Wt.args)));break;case"removeSource":et.push((()=>this.removeSource.apply(this,Wt.args)));break;case"setLayerZoomRange":et.push((()=>this.setLayerZoomRange.apply(this,Wt.args)));break;case"setLight":et.push((()=>this.setLight.apply(this,Wt.args)));break;case"setGeoJSONSourceData":et.push((()=>this.setGeoJSONSourceData.apply(this,Wt.args)));break;case"setGlyphs":et.push((()=>this.setGlyphs.apply(this,Wt.args)));break;case"setSprite":et.push((()=>this.setSprite.apply(this,Wt.args)));break;case"setTerrain":et.push((()=>this.map.setTerrain.apply(this,Wt.args)));break;case"setSky":et.push((()=>this.setSky.apply(this,Wt.args)));break;case"setProjection":this.setProjection.apply(this,Wt.args);break;case"setTransition":et.push((()=>{}));break;default:Bt.push(Wt.command)}return{operations:et,unimplemented:Bt}}addImage(M,Bt){if(this.getImage(M))return this.fire(new et.j(new Error(`An image named "${M}" already exists.`)));this.imageManager.addImage(M,Bt),this._afterImageUpdated(M)}updateImage(M,et){this.imageManager.updateImage(M,et)}getImage(M){return this.imageManager.getImage(M)}removeImage(M){if(!this.getImage(M))return this.fire(new et.j(new Error(`An image named "${M}" does not exist.`)));this.imageManager.removeImage(M),this._afterImageUpdated(M)}_afterImageUpdated(M){this._availableImages=this.imageManager.listImages(),this._changedImages[M]=!0,this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new et.k("data",{dataType:"style"}))}listImages(){return this._checkLoaded(),this.imageManager.listImages()}addSource(M,Bt,Wt={}){if(this._checkLoaded(),void 0!==this.sourceCaches[M])throw new Error(`Source "${M}" already exists.`);if(!Bt.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(Bt).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(Bt.type)>=0&&this._validate(et.u.source,`sources.${M}`,Bt,null,Wt))return;this.map&&this.map._collectResourceTiming&&(Bt.collectResourceTiming=!0);const Nt=this.sourceCaches[M]=new de(M,Bt,this.dispatcher);Nt.style=this,Nt.setEventedParent(this,(()=>({isSourceLoaded:Nt.loaded(),source:Nt.serialize(),sourceId:M}))),Nt.onAdd(this.map),this._changed=!0}removeSource(M){if(this._checkLoaded(),void 0===this.sourceCaches[M])throw new Error("There is no source with this ID");for(const Bt in this._layers)if(this._layers[Bt].source===M)return this.fire(new et.j(new Error(`Source "${M}" cannot be removed while layer "${Bt}" is using it.`)));const Bt=this.sourceCaches[M];delete this.sourceCaches[M],delete this._updatedSources[M],Bt.fire(new et.k("data",{sourceDataType:"metadata",dataType:"source",sourceId:M})),Bt.setEventedParent(null),Bt.onRemove(this.map),this._changed=!0}setGeoJSONSourceData(M,et){if(this._checkLoaded(),void 0===this.sourceCaches[M])throw new Error(`There is no source with this ID=${M}`);const Bt=this.sourceCaches[M].getSource();if("geojson"!==Bt.type)throw new Error(`geojsonSource.type is ${Bt.type}, which is !== 'geojson`);Bt.setData(et),this._changed=!0}getSource(M){return this.sourceCaches[M]&&this.sourceCaches[M].getSource()}addLayer(M,Bt,Wt={}){this._checkLoaded();const Nt=M.id;if(this.getLayer(Nt))return void this.fire(new et.j(new Error(`Layer "${Nt}" already exists on this map.`)));let $t;if("custom"===M.type){if(mi(this,et.by(M)))return;$t=et.bv(M)}else{if("source"in M&&"object"==typeof M.source&&(this.addSource(Nt,M.source),M=et.bw(M),M=et.e(M,{source:Nt})),this._validate(et.u.layer,`layers.${Nt}`,M,{arrayIndex:-1},Wt))return;$t=et.bv(M),this._validateLayer($t),$t.setEventedParent(this,{layer:{id:Nt}})}const Gr=Bt?this._order.indexOf(Bt):this._order.length;if(Bt&&-1===Gr)this.fire(new et.j(new Error(`Cannot add layer "${Nt}" before non-existing layer "${Bt}".`)));else{if(this._order.splice(Gr,0,Nt),this._layerOrderChanged=!0,this._layers[Nt]=$t,this._removedLayers[Nt]&&$t.source&&"custom"!==$t.type){const M=this._removedLayers[Nt];delete this._removedLayers[Nt],M.type!==$t.type?this._updatedSources[$t.source]="clear":(this._updatedSources[$t.source]="reload",this.sourceCaches[$t.source].pause())}this._updateLayer($t),$t.onAdd&&$t.onAdd(this.map)}}moveLayer(M,Bt){if(this._checkLoaded(),this._changed=!0,!this._layers[M])return void this.fire(new et.j(new Error(`The layer '${M}' does not exist in the map's style and cannot be moved.`)));if(M===Bt)return;const Wt=this._order.indexOf(M);this._order.splice(Wt,1);const Nt=Bt?this._order.indexOf(Bt):this._order.length;Bt&&-1===Nt?this.fire(new et.j(new Error(`Cannot move layer "${M}" before non-existing layer "${Bt}".`))):(this._order.splice(Nt,0,M),this._layerOrderChanged=!0)}removeLayer(M){this._checkLoaded();const Bt=this._layers[M];if(!Bt)return void this.fire(new et.j(new Error(`Cannot remove non-existing layer "${M}".`)));Bt.setEventedParent(null);const Wt=this._order.indexOf(M);this._order.splice(Wt,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[M]=Bt,delete this._layers[M],this._serializedLayers&&delete this._serializedLayers[M],delete this._updatedLayers[M],delete this._updatedPaintProps[M],Bt.onRemove&&Bt.onRemove(this.map)}getLayer(M){return this._layers[M]}getLayersOrder(){return[...this._order]}hasLayer(M){return M in this._layers}setLayerZoomRange(M,Bt,Wt){this._checkLoaded();const Nt=this.getLayer(M);Nt?Nt.minzoom===Bt&&Nt.maxzoom===Wt||(null!=Bt&&(Nt.minzoom=Bt),null!=Wt&&(Nt.maxzoom=Wt),this._updateLayer(Nt)):this.fire(new et.j(new Error(`Cannot set the zoom range of non-existing layer "${M}".`)))}setFilter(M,Bt,Wt={}){this._checkLoaded();const Nt=this.getLayer(M);if(Nt){if(!et.bz(Nt.filter,Bt))return null==Bt?(Nt.filter=void 0,void this._updateLayer(Nt)):void(this._validate(et.u.filter,`layers.${Nt.id}.filter`,Bt,null,Wt)||(Nt.filter=et.bw(Bt),this._updateLayer(Nt)))}else this.fire(new et.j(new Error(`Cannot filter non-existing layer "${M}".`)))}getFilter(M){return et.bw(this.getLayer(M).filter)}setLayoutProperty(M,Bt,Wt,Nt={}){this._checkLoaded();const $t=this.getLayer(M);$t?et.bz($t.getLayoutProperty(Bt),Wt)||($t.setLayoutProperty(Bt,Wt,Nt),this._updateLayer($t)):this.fire(new et.j(new Error(`Cannot style non-existing layer "${M}".`)))}getLayoutProperty(M,Bt){const Wt=this.getLayer(M);if(Wt)return Wt.getLayoutProperty(Bt);this.fire(new et.j(new Error(`Cannot get style of non-existing layer "${M}".`)))}setPaintProperty(M,Bt,Wt,Nt={}){this._checkLoaded();const $t=this.getLayer(M);$t?et.bz($t.getPaintProperty(Bt),Wt)||($t.setPaintProperty(Bt,Wt,Nt)&&this._updateLayer($t),this._changed=!0,this._updatedPaintProps[M]=!0,this._serializedLayers=null):this.fire(new et.j(new Error(`Cannot style non-existing layer "${M}".`)))}getPaintProperty(M,et){return this.getLayer(M).getPaintProperty(et)}setFeatureState(M,Bt){this._checkLoaded();const Wt=M.source,Nt=M.sourceLayer,$t=this.sourceCaches[Wt];if(void 0===$t)return void this.fire(new et.j(new Error(`The source '${Wt}' does not exist in the map's style.`)));const Gr=$t.getSource().type;"geojson"===Gr&&Nt?this.fire(new et.j(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==Gr||Nt?(void 0===M.id&&this.fire(new et.j(new Error("The feature id parameter must be provided."))),$t.setFeatureState(Nt,M.id,Bt)):this.fire(new et.j(new Error("The sourceLayer parameter must be provided for vector source types.")))}removeFeatureState(M,Bt){this._checkLoaded();const Wt=M.source,Nt=this.sourceCaches[Wt];if(void 0===Nt)return void this.fire(new et.j(new Error(`The source '${Wt}' does not exist in the map's style.`)));const $t=Nt.getSource().type,Gr="vector"===$t?M.sourceLayer:void 0;"vector"!==$t||Gr?Bt&&"string"!=typeof M.id&&"number"!=typeof M.id?this.fire(new et.j(new Error("A feature id is required to remove its specific state property."))):Nt.removeFeatureState(Gr,M.id,Bt):this.fire(new et.j(new Error("The sourceLayer parameter must be provided for vector source types.")))}getFeatureState(M){this._checkLoaded();const Bt=M.source,Wt=M.sourceLayer,Nt=this.sourceCaches[Bt];if(void 0!==Nt)return"vector"!==Nt.getSource().type||Wt?(void 0===M.id&&this.fire(new et.j(new Error("The feature id parameter must be provided."))),Nt.getFeatureState(Wt,M.id)):void this.fire(new et.j(new Error("The sourceLayer parameter must be provided for vector source types.")));this.fire(new et.j(new Error(`The source '${Bt}' does not exist in the map's style.`)))}getTransition(){return et.e({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const M=et.bA(this.sourceCaches,(M=>M.serialize())),Bt=this._serializeByIds(this._order,!0),Wt=this.map.getTerrain()||void 0,Nt=this.stylesheet;return et.bB({version:Nt.version,name:Nt.name,metadata:Nt.metadata,light:Nt.light,sky:Nt.sky,center:Nt.center,zoom:Nt.zoom,bearing:Nt.bearing,pitch:Nt.pitch,sprite:Nt.sprite,glyphs:Nt.glyphs,transition:Nt.transition,projection:Nt.projection,sources:M,layers:Bt,terrain:Wt},(M=>void 0!==M))}_updateLayer(M){this._updatedLayers[M.id]=!0,M.source&&!this._updatedSources[M.source]&&"raster"!==this.sourceCaches[M.source].getSource().type&&(this._updatedSources[M.source]="reload",this.sourceCaches[M.source].pause()),this._serializedLayers=null,this._changed=!0}_flattenAndSortRenderedFeatures(M){const t=M=>"fill-extrusion"===this._layers[M].type,et={},Bt=[];for(let Wt=this._order.length-1;Wt>=0;Wt--){const Nt=this._order[Wt];if(t(Nt)){et[Nt]=Wt;for(const et of M){const M=et[Nt];if(M)for(const et of M)Bt.push(et)}}}Bt.sort(((M,et)=>et.intersectionZ-M.intersectionZ));const Wt=[];for(let Nt=this._order.length-1;Nt>=0;Nt--){const $t=this._order[Nt];if(t($t))for(let M=Bt.length-1;M>=0;M--){const $t=Bt[M].feature;if(et[$t.layer.id]{const Wt=Bt.featureSortOrder;if(Wt){const Bt=Wt.indexOf(M.featureIndex);return Wt.indexOf(et.featureIndex)-Bt}return et.featureIndex-M.featureIndex}));for(const M of Nt)et.push(M)}}return function(M,et,Bt){for(const Wt in M)for(const Nt of M[Wt])G(Nt,Bt[et[Wt].source]);return M}(mn,M,Bt)}(this._layers,Gr,this.sourceCaches,M,Hn,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures($t)}querySourceFeatures(M,Bt){Bt&&Bt.filter&&this._validate(et.u.filter,"querySourceFeatures.filter",Bt.filter,null,Bt);const Wt=this.sourceCaches[M];return Wt?function(M,et){const Bt=M.getRenderableIds().map((et=>M.getTileByID(et))),Wt=[],Nt={};for(let M=0;MM.getTileByID(et))).sort(((M,et)=>et.tileID.overscaledZ-M.tileID.overscaledZ||(M.tileID.isLessThan(et.tileID)?-1:1)))}const Wt=this.crossTileSymbolIndex.addLayer(Bt,Hn[Bt.source],M.center.lng);Gr=Gr||Wt}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((Nt=Nt||this._layerOrderChanged||0===Bt)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent($t.now(),M.zoom))&&(this.pauseablePlacement=new st(M,this.map.terrain,this._order,Nt,et,Bt,Wt,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,Hn),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit($t.now()),mn=!0),Gr&&this.pauseablePlacement.placement.setStale()),mn||Gr)for(const M of this._order){const et=this._layers[M];"symbol"===et.type&&this.placement.updateLayerOpacities(et,Hn[et.source])}return!this.pauseablePlacement.isDone()||this.placement.hasTransitions($t.now())}_releaseSymbolFadeTiles(){for(const M in this.sourceCaches)this.sourceCaches[M].releaseSymbolFadeTiles()}getImages(M,Bt){return et._(this,void 0,void 0,(function*(){const M=yield this.imageManager.getImages(Bt.icons);this._updateTilesForChangedImages();const et=this.sourceCaches[Bt.source];return et&&et.setDependencies(Bt.tileID.key,Bt.type,Bt.icons),M}))}getGlyphs(M,Bt){return et._(this,void 0,void 0,(function*(){const M=yield this.glyphManager.getGlyphs(Bt.stacks),et=this.sourceCaches[Bt.source];return et&&et.setDependencies(Bt.tileID.key,Bt.type,[""]),M}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(M,Bt={}){this._checkLoaded(),M&&this._validate(et.u.glyphs,"glyphs",M,null,Bt)||(this._glyphsDidChange=!0,this.stylesheet.glyphs=M,this.glyphManager.entries={},this.glyphManager.setURL(M))}addSprite(M,Bt,Wt={},Nt){this._checkLoaded();const $t=[{id:M,url:Bt}],Gr=[...f(this.stylesheet.sprite),...$t];this._validate(et.u.sprite,"sprite",Gr,null,Wt)||(this.stylesheet.sprite=Gr,this._loadSprite($t,!0,Nt))}removeSprite(M){this._checkLoaded();const Bt=f(this.stylesheet.sprite);if(Bt.find((et=>et.id===M))){if(this._spritesImagesIds[M])for(const et of this._spritesImagesIds[M])this.imageManager.removeImage(et),this._changedImages[et]=!0;Bt.splice(Bt.findIndex((et=>et.id===M)),1),this.stylesheet.sprite=Bt.length>0?Bt:void 0,delete this._spritesImagesIds[M],this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new et.k("data",{dataType:"style"}))}else this.fire(new et.j(new Error(`Sprite "${M}" doesn't exists on this map.`)))}getSprite(){return f(this.stylesheet.sprite)}setSprite(M,Bt={},Wt){this._checkLoaded(),M&&this._validate(et.u.sprite,"sprite",M,null,Bt)||(this.stylesheet.sprite=M,M?this._loadSprite(M,!0,Wt):(this._unloadSprite(),Wt&&Wt(null)))}}var $l=et.aA([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]);class xi{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null}bind(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn){this.context=M;let so=this.boundPaintVertexBuffers.length!==Wt.length;for(let M=0;!so&&M({u_texture:0,u_ele_delta:M,u_fog_matrix:Bt,u_fog_color:Wt?Wt.properties.get("fog-color"):et.b4.white,u_fog_ground_blend:Wt?Wt.properties.get("fog-ground-blend"):1,u_fog_ground_blend_opacity:$t?0:Wt?Wt.calculateFogBlendOpacity(Nt):0,u_horizon_color:Wt?Wt.properties.get("horizon-color"):et.b4.white,u_horizon_fog_blend:Wt?Wt.properties.get("horizon-fog-blend"):1,u_is_globe_mode:$t?1:0}),tc={mainMatrix:"u_projection_matrix",tileMercatorCoords:"u_projection_tile_mercator_coords",clippingPlane:"u_projection_clipping_plane",projectionTransition:"u_projection_transition",fallbackMatrix:"u_projection_fallback_matrix"};function wi(M){const et=[];for(let Bt=0;Bt({u_depth:new et.bC(M,Bt.u_depth),u_terrain:new et.bC(M,Bt.u_terrain),u_terrain_dim:new et.b5(M,Bt.u_terrain_dim),u_terrain_matrix:new et.bD(M,Bt.u_terrain_matrix),u_terrain_unpack:new et.bE(M,Bt.u_terrain_unpack),u_terrain_exaggeration:new et.b5(M,Bt.u_terrain_exaggeration)}))(M,Ka),this.projectionUniforms=((M,Bt)=>({u_projection_matrix:new et.bD(M,Bt.u_projection_matrix),u_projection_tile_mercator_coords:new et.bE(M,Bt.u_projection_tile_mercator_coords),u_projection_clipping_plane:new et.bE(M,Bt.u_projection_clipping_plane),u_projection_transition:new et.b5(M,Bt.u_projection_transition),u_projection_fallback_matrix:new et.bD(M,Bt.u_projection_fallback_matrix)}))(M,Ka),this.binderUniforms=Wt?Wt.getUniforms(M,Ka):[]}draw(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba,Ta,Va){const za=M.gl;if(this.failedToCreate)return;if(M.program.set(this.program),M.setDepthMode(Bt),M.setStencilMode(Wt),M.setColorMode(Nt),M.setCullFace($t),mn){M.activeTexture.set(za.TEXTURE2),za.bindTexture(za.TEXTURE_2D,mn.depthTexture),M.activeTexture.set(za.TEXTURE3),za.bindTexture(za.TEXTURE_2D,mn.texture);for(const M in this.terrainUniforms)this.terrainUniforms[M].set(mn[M])}if(Hn)for(const M in Hn)this.projectionUniforms[tc[M]].set(Hn[M]);if(Gr)for(const M in this.fixedUniforms)this.fixedUniforms[M].set(Gr[M]);Ia&&Ia.setUniforms(M,this.binderUniforms,To,{zoom:Eo});let Fa=0;switch(et){case za.LINES:Fa=2;break;case za.TRIANGLES:Fa=3;break;case za.LINE_STRIP:Fa=1}for(const Bt of Po.get()){const Wt=Bt.vaos||(Bt.vaos={});(Wt[so]||(Wt[so]=new xi)).bind(M,this,uo,Ia?Ia.getPaintVertexBuffers():[],Io,Bt.vertexOffset,Ba,Ta,Va),za.drawElements(et,Bt.primitiveLength*Fa,za.UNSIGNED_SHORT,Bt.primitiveOffset*Fa*2)}}}function Pi(M,Bt,Wt){const Nt=1/et.at(Wt,1,Bt.transform.tileZoom),$t=Math.pow(2,Wt.tileID.overscaledZ),Gr=Wt.tileSize*Math.pow(2,Bt.transform.tileZoom)/$t,mn=Gr*(Wt.tileID.canonical.x+Wt.tileID.wrap*$t),Hn=Gr*Wt.tileID.canonical.y;return{u_image:0,u_texsize:Wt.imageAtlasTexture.size,u_scale:[Nt,M.fromScale,M.toScale],u_fade:M.t,u_pixel_coord_upper:[mn>>16,Hn>>16],u_pixel_coord_lower:[65535&mn,65535&Hn]}}const Ci=(M,Bt,Wt,Nt)=>{const $t=M.style.light,Gr=$t.properties.get("position"),mn=[Gr.x,Gr.y,Gr.z],Hn=et.bI();"viewport"===$t.properties.get("anchor")&&et.bJ(Hn,M.transform.bearingInRadians),et.bK(mn,mn,Hn);const so=M.transform.transformLightDirection(mn),uo=$t.properties.get("color");return{u_lightpos:mn,u_lightpos_globe:so,u_lightintensity:$t.properties.get("intensity"),u_lightcolor:[uo.r,uo.g,uo.b],u_vertical_gradient:+Bt,u_opacity:Wt,u_fill_translate:Nt}},Ii=(M,Bt,Wt,Nt,$t,Gr,mn)=>et.e(Ci(M,Bt,Wt,Nt),Pi(Gr,M,mn),{u_height_factor:-Math.pow(2,$t.overscaledZ)/mn.tileSize/8}),Ei=(M,Bt,Wt,Nt)=>et.e(Pi(Bt,M,Wt),{u_fill_translate:Nt}),Mi=(M,et)=>({u_world:M,u_fill_translate:et}),Si=(M,Bt,Wt,Nt,$t)=>et.e(Ei(M,Bt,Wt,$t),{u_world:Nt}),Ri=(M,Bt,Wt,Nt,$t)=>{const Gr=M.transform;let mn,Hn,so=0;if("map"===Wt.paint.get("circle-pitch-alignment")){const M=et.at(Bt,1,Gr.zoom);mn=!0,Hn=[M,M],so=M/(et.X*Math.pow(2,Bt.tileID.overscaledZ))*2*Math.PI*$t}else mn=!1,Hn=Gr.pixelsToGLUnits;return{u_camera_to_center_distance:Gr.cameraToCenterDistance,u_scale_with_map:+("map"===Wt.paint.get("circle-pitch-scale")),u_pitch_with_map:+mn,u_device_pixel_ratio:M.pixelRatio,u_extrude_scale:Hn,u_globe_extrude_scale:so,u_translate:Nt}},Di=M=>({u_pixel_extrude_scale:[1/M.width,1/M.height]}),zi=M=>({u_viewport_size:[M.width,M.height]}),Ai=(M,et=1)=>({u_color:M,u_overlay:0,u_overlay_scale:et}),Li=(M,Bt,Wt,Nt)=>{const $t=et.at(M,1,Bt)/(et.X*Math.pow(2,M.tileID.overscaledZ))*2*Math.PI*Nt;return{u_extrude_scale:et.at(M,1,Bt),u_intensity:Wt,u_globe_extrude_scale:$t}},ki=(M,Bt,Wt,Nt)=>{const $t=et.H();et.bL($t,0,M.width,M.height,0,0,1);const Gr=M.context.gl;return{u_matrix:$t,u_world:[Gr.drawingBufferWidth,Gr.drawingBufferHeight],u_image:Wt,u_color_ramp:Nt,u_opacity:Bt.paint.get("heatmap-opacity")}},Fi=(M,et,Bt)=>{const Wt=Bt.paint.get("hillshade-shadow-color"),Nt=Bt.paint.get("hillshade-highlight-color"),$t=Bt.paint.get("hillshade-accent-color");let Gr=Bt.paint.get("hillshade-illumination-direction")*(Math.PI/180);return"viewport"===Bt.paint.get("hillshade-illumination-anchor")&&(Gr+=M.transform.bearingInRadians),{u_image:0,u_latrange:ji(0,et.tileID),u_light:[Bt.paint.get("hillshade-exaggeration"),Gr],u_shadow:Wt,u_highlight:Nt,u_accent:$t}},Bi=(M,Bt)=>{const Wt=Bt.stride,Nt=et.H();return et.bL(Nt,0,et.X,-et.X,0,0,1),et.J(Nt,Nt,[0,-et.X,0]),{u_matrix:Nt,u_image:1,u_dimension:[Wt,Wt],u_zoom:M.overscaledZ,u_unpack:Bt.getUnpackVector()}};function ji(M,Bt){const Wt=Math.pow(2,Bt.canonical.z),Nt=Bt.canonical.y;return[new et.Y(0,Nt/Wt).toLngLat().lat,new et.Y(0,(Nt+1)/Wt).toLngLat().lat]}const Oi=(M,Bt,Wt,Nt)=>{const $t=M.transform;return{u_translation:Vi(M,Bt,Wt),u_ratio:Nt/et.at(Bt,1,$t.zoom),u_device_pixel_ratio:M.pixelRatio,u_units_to_pixels:[1/$t.pixelsToGLUnits[0],1/$t.pixelsToGLUnits[1]]}},Ni=(M,Bt,Wt,Nt,$t)=>et.e(Oi(M,Bt,Wt,Nt),{u_image:0,u_image_height:$t}),Zi=(M,Bt,Wt,Nt,$t)=>{const Gr=M.transform,mn=Ui(Bt,Gr);return{u_translation:Vi(M,Bt,Wt),u_texsize:Bt.imageAtlasTexture.size,u_ratio:Nt/et.at(Bt,1,Gr.zoom),u_device_pixel_ratio:M.pixelRatio,u_image:0,u_scale:[mn,$t.fromScale,$t.toScale],u_fade:$t.t,u_units_to_pixels:[1/Gr.pixelsToGLUnits[0],1/Gr.pixelsToGLUnits[1]]}},Gi=(M,Bt,Wt,Nt,$t,Gr)=>{const mn=M.lineAtlas,Hn=Ui(Bt,M.transform),so="round"===Wt.layout.get("line-cap"),uo=mn.getDash($t.from,so),Io=mn.getDash($t.to,so),Po=uo.width*Gr.fromScale,To=Io.width*Gr.toScale;return et.e(Oi(M,Bt,Wt,Nt),{u_patternscale_a:[Hn/Po,-uo.height/2],u_patternscale_b:[Hn/To,-Io.height/2],u_sdfgamma:mn.width/(256*Math.min(Po,To)*M.pixelRatio)/2,u_image:0,u_tex_y_a:uo.y,u_tex_y_b:Io.y,u_mix:Gr.t})};function Ui(M,Bt){return 1/et.at(M,1,Bt.tileZoom)}function Vi(M,Bt,Wt){return et.au(M.transform,Bt,Wt.paint.get("line-translate"),Wt.paint.get("line-translate-anchor"))}const qi=(M,et,Bt,Wt,Nt)=>{return{u_tl_parent:M,u_scale_parent:et,u_buffer_scale:1,u_fade_t:Bt.mix,u_opacity:Bt.opacity*Wt.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:Wt.paint.get("raster-brightness-min"),u_brightness_high:Wt.paint.get("raster-brightness-max"),u_saturation_factor:(Gr=Wt.paint.get("raster-saturation"),Gr>0?1-1/(1.001-Gr):-Gr),u_contrast_factor:($t=Wt.paint.get("raster-contrast"),$t>0?1/(1-$t):1+$t),u_spin_weights:Hi(Wt.paint.get("raster-hue-rotate")),u_coords_top:[Nt[0].x,Nt[0].y,Nt[1].x,Nt[1].y],u_coords_bottom:[Nt[3].x,Nt[3].y,Nt[2].x,Nt[2].y]};var $t,Gr};function Hi(M){M*=Math.PI/180;const et=Math.sin(M),Bt=Math.cos(M);return[(2*Bt+1)/3,(-Math.sqrt(3)*et-Bt+1)/3,(Math.sqrt(3)*et-Bt+1)/3]}const Wi=(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po)=>{const To=Gr.transform;return{u_is_size_zoom_constant:+("constant"===M||"source"===M),u_is_size_feature_constant:+("constant"===M||"camera"===M),u_size_t:et?et.uSizeT:0,u_size:et?et.uSize:0,u_camera_to_center_distance:To.cameraToCenterDistance,u_pitch:To.pitch/360*2*Math.PI,u_rotate_symbol:+Bt,u_aspect_ratio:To.width/To.height,u_fade_change:Gr.options.fadeDuration?Gr.symbolFadeChange:1,u_label_plane_matrix:mn,u_coord_matrix:Hn,u_is_text:+uo,u_pitch_with_map:+Wt,u_is_along_line:Nt,u_is_variable_anchor:$t,u_texsize:Io,u_texture:0,u_translation:so,u_pitched_scale:Po}},Xi=(M,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo)=>{const Ia=mn.transform;return et.e(Wi(M,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,Eo),{u_gamma_scale:Nt?Math.cos(Ia.pitch*Math.PI/180)*Ia.cameraToCenterDistance:1,u_device_pixel_ratio:mn.pixelRatio,u_is_halo:1})},$i=(M,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To)=>et.e(Xi(M,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,!0,Io,!0,To),{u_texsize_icon:Po,u_texture_icon:1}),Ki=(M,et)=>({u_opacity:M,u_color:et}),Yi=(M,Bt,Wt,Nt,$t)=>et.e(function(M,Bt,Wt,Nt){const $t=Wt.imageManager.getPattern(M.from.toString()),Gr=Wt.imageManager.getPattern(M.to.toString()),{width:mn,height:Hn}=Wt.imageManager.getPixelSize(),so=Math.pow(2,Nt.tileID.overscaledZ),uo=Nt.tileSize*Math.pow(2,Wt.transform.tileZoom)/so,Io=uo*(Nt.tileID.canonical.x+Nt.tileID.wrap*so),Po=uo*Nt.tileID.canonical.y;return{u_image:0,u_pattern_tl_a:$t.tl,u_pattern_br_a:$t.br,u_pattern_tl_b:Gr.tl,u_pattern_br_b:Gr.br,u_texsize:[mn,Hn],u_mix:Bt.t,u_pattern_size_a:$t.displaySize,u_pattern_size_b:Gr.displaySize,u_scale_a:Bt.fromScale,u_scale_b:Bt.toScale,u_tile_units_to_pixels:1/et.at(Nt,1,Wt.transform.tileZoom),u_pixel_coord_upper:[Io>>16,Po>>16],u_pixel_coord_lower:[65535&Io,65535&Po]}}(Wt,$t,Bt,Nt),{u_opacity:M}),Ji=(M,et)=>{},ec={fillExtrusion:(M,Bt)=>({u_lightpos:new et.bG(M,Bt.u_lightpos),u_lightpos_globe:new et.bG(M,Bt.u_lightpos_globe),u_lightintensity:new et.b5(M,Bt.u_lightintensity),u_lightcolor:new et.bG(M,Bt.u_lightcolor),u_vertical_gradient:new et.b5(M,Bt.u_vertical_gradient),u_opacity:new et.b5(M,Bt.u_opacity),u_fill_translate:new et.bH(M,Bt.u_fill_translate)}),fillExtrusionPattern:(M,Bt)=>({u_lightpos:new et.bG(M,Bt.u_lightpos),u_lightpos_globe:new et.bG(M,Bt.u_lightpos_globe),u_lightintensity:new et.b5(M,Bt.u_lightintensity),u_lightcolor:new et.bG(M,Bt.u_lightcolor),u_vertical_gradient:new et.b5(M,Bt.u_vertical_gradient),u_height_factor:new et.b5(M,Bt.u_height_factor),u_opacity:new et.b5(M,Bt.u_opacity),u_fill_translate:new et.bH(M,Bt.u_fill_translate),u_image:new et.bC(M,Bt.u_image),u_texsize:new et.bH(M,Bt.u_texsize),u_pixel_coord_upper:new et.bH(M,Bt.u_pixel_coord_upper),u_pixel_coord_lower:new et.bH(M,Bt.u_pixel_coord_lower),u_scale:new et.bG(M,Bt.u_scale),u_fade:new et.b5(M,Bt.u_fade)}),fill:(M,Bt)=>({u_fill_translate:new et.bH(M,Bt.u_fill_translate)}),fillPattern:(M,Bt)=>({u_image:new et.bC(M,Bt.u_image),u_texsize:new et.bH(M,Bt.u_texsize),u_pixel_coord_upper:new et.bH(M,Bt.u_pixel_coord_upper),u_pixel_coord_lower:new et.bH(M,Bt.u_pixel_coord_lower),u_scale:new et.bG(M,Bt.u_scale),u_fade:new et.b5(M,Bt.u_fade),u_fill_translate:new et.bH(M,Bt.u_fill_translate)}),fillOutline:(M,Bt)=>({u_world:new et.bH(M,Bt.u_world),u_fill_translate:new et.bH(M,Bt.u_fill_translate)}),fillOutlinePattern:(M,Bt)=>({u_world:new et.bH(M,Bt.u_world),u_image:new et.bC(M,Bt.u_image),u_texsize:new et.bH(M,Bt.u_texsize),u_pixel_coord_upper:new et.bH(M,Bt.u_pixel_coord_upper),u_pixel_coord_lower:new et.bH(M,Bt.u_pixel_coord_lower),u_scale:new et.bG(M,Bt.u_scale),u_fade:new et.b5(M,Bt.u_fade),u_fill_translate:new et.bH(M,Bt.u_fill_translate)}),circle:(M,Bt)=>({u_camera_to_center_distance:new et.b5(M,Bt.u_camera_to_center_distance),u_scale_with_map:new et.bC(M,Bt.u_scale_with_map),u_pitch_with_map:new et.bC(M,Bt.u_pitch_with_map),u_extrude_scale:new et.bH(M,Bt.u_extrude_scale),u_device_pixel_ratio:new et.b5(M,Bt.u_device_pixel_ratio),u_globe_extrude_scale:new et.b5(M,Bt.u_globe_extrude_scale),u_translate:new et.bH(M,Bt.u_translate)}),collisionBox:(M,Bt)=>({u_pixel_extrude_scale:new et.bH(M,Bt.u_pixel_extrude_scale)}),collisionCircle:(M,Bt)=>({u_viewport_size:new et.bH(M,Bt.u_viewport_size)}),debug:(M,Bt)=>({u_color:new et.bF(M,Bt.u_color),u_overlay:new et.bC(M,Bt.u_overlay),u_overlay_scale:new et.b5(M,Bt.u_overlay_scale)}),depth:Ji,clippingMask:Ji,heatmap:(M,Bt)=>({u_extrude_scale:new et.b5(M,Bt.u_extrude_scale),u_intensity:new et.b5(M,Bt.u_intensity),u_globe_extrude_scale:new et.b5(M,Bt.u_globe_extrude_scale)}),heatmapTexture:(M,Bt)=>({u_matrix:new et.bD(M,Bt.u_matrix),u_world:new et.bH(M,Bt.u_world),u_image:new et.bC(M,Bt.u_image),u_color_ramp:new et.bC(M,Bt.u_color_ramp),u_opacity:new et.b5(M,Bt.u_opacity)}),hillshade:(M,Bt)=>({u_image:new et.bC(M,Bt.u_image),u_latrange:new et.bH(M,Bt.u_latrange),u_light:new et.bH(M,Bt.u_light),u_shadow:new et.bF(M,Bt.u_shadow),u_highlight:new et.bF(M,Bt.u_highlight),u_accent:new et.bF(M,Bt.u_accent)}),hillshadePrepare:(M,Bt)=>({u_matrix:new et.bD(M,Bt.u_matrix),u_image:new et.bC(M,Bt.u_image),u_dimension:new et.bH(M,Bt.u_dimension),u_zoom:new et.b5(M,Bt.u_zoom),u_unpack:new et.bE(M,Bt.u_unpack)}),line:(M,Bt)=>({u_translation:new et.bH(M,Bt.u_translation),u_ratio:new et.b5(M,Bt.u_ratio),u_device_pixel_ratio:new et.b5(M,Bt.u_device_pixel_ratio),u_units_to_pixels:new et.bH(M,Bt.u_units_to_pixels)}),lineGradient:(M,Bt)=>({u_translation:new et.bH(M,Bt.u_translation),u_ratio:new et.b5(M,Bt.u_ratio),u_device_pixel_ratio:new et.b5(M,Bt.u_device_pixel_ratio),u_units_to_pixels:new et.bH(M,Bt.u_units_to_pixels),u_image:new et.bC(M,Bt.u_image),u_image_height:new et.b5(M,Bt.u_image_height)}),linePattern:(M,Bt)=>({u_translation:new et.bH(M,Bt.u_translation),u_texsize:new et.bH(M,Bt.u_texsize),u_ratio:new et.b5(M,Bt.u_ratio),u_device_pixel_ratio:new et.b5(M,Bt.u_device_pixel_ratio),u_image:new et.bC(M,Bt.u_image),u_units_to_pixels:new et.bH(M,Bt.u_units_to_pixels),u_scale:new et.bG(M,Bt.u_scale),u_fade:new et.b5(M,Bt.u_fade)}),lineSDF:(M,Bt)=>({u_translation:new et.bH(M,Bt.u_translation),u_ratio:new et.b5(M,Bt.u_ratio),u_device_pixel_ratio:new et.b5(M,Bt.u_device_pixel_ratio),u_units_to_pixels:new et.bH(M,Bt.u_units_to_pixels),u_patternscale_a:new et.bH(M,Bt.u_patternscale_a),u_patternscale_b:new et.bH(M,Bt.u_patternscale_b),u_sdfgamma:new et.b5(M,Bt.u_sdfgamma),u_image:new et.bC(M,Bt.u_image),u_tex_y_a:new et.b5(M,Bt.u_tex_y_a),u_tex_y_b:new et.b5(M,Bt.u_tex_y_b),u_mix:new et.b5(M,Bt.u_mix)}),raster:(M,Bt)=>({u_tl_parent:new et.bH(M,Bt.u_tl_parent),u_scale_parent:new et.b5(M,Bt.u_scale_parent),u_buffer_scale:new et.b5(M,Bt.u_buffer_scale),u_fade_t:new et.b5(M,Bt.u_fade_t),u_opacity:new et.b5(M,Bt.u_opacity),u_image0:new et.bC(M,Bt.u_image0),u_image1:new et.bC(M,Bt.u_image1),u_brightness_low:new et.b5(M,Bt.u_brightness_low),u_brightness_high:new et.b5(M,Bt.u_brightness_high),u_saturation_factor:new et.b5(M,Bt.u_saturation_factor),u_contrast_factor:new et.b5(M,Bt.u_contrast_factor),u_spin_weights:new et.bG(M,Bt.u_spin_weights),u_coords_top:new et.bE(M,Bt.u_coords_top),u_coords_bottom:new et.bE(M,Bt.u_coords_bottom)}),symbolIcon:(M,Bt)=>({u_is_size_zoom_constant:new et.bC(M,Bt.u_is_size_zoom_constant),u_is_size_feature_constant:new et.bC(M,Bt.u_is_size_feature_constant),u_size_t:new et.b5(M,Bt.u_size_t),u_size:new et.b5(M,Bt.u_size),u_camera_to_center_distance:new et.b5(M,Bt.u_camera_to_center_distance),u_pitch:new et.b5(M,Bt.u_pitch),u_rotate_symbol:new et.bC(M,Bt.u_rotate_symbol),u_aspect_ratio:new et.b5(M,Bt.u_aspect_ratio),u_fade_change:new et.b5(M,Bt.u_fade_change),u_label_plane_matrix:new et.bD(M,Bt.u_label_plane_matrix),u_coord_matrix:new et.bD(M,Bt.u_coord_matrix),u_is_text:new et.bC(M,Bt.u_is_text),u_pitch_with_map:new et.bC(M,Bt.u_pitch_with_map),u_is_along_line:new et.bC(M,Bt.u_is_along_line),u_is_variable_anchor:new et.bC(M,Bt.u_is_variable_anchor),u_texsize:new et.bH(M,Bt.u_texsize),u_texture:new et.bC(M,Bt.u_texture),u_translation:new et.bH(M,Bt.u_translation),u_pitched_scale:new et.b5(M,Bt.u_pitched_scale)}),symbolSDF:(M,Bt)=>({u_is_size_zoom_constant:new et.bC(M,Bt.u_is_size_zoom_constant),u_is_size_feature_constant:new et.bC(M,Bt.u_is_size_feature_constant),u_size_t:new et.b5(M,Bt.u_size_t),u_size:new et.b5(M,Bt.u_size),u_camera_to_center_distance:new et.b5(M,Bt.u_camera_to_center_distance),u_pitch:new et.b5(M,Bt.u_pitch),u_rotate_symbol:new et.bC(M,Bt.u_rotate_symbol),u_aspect_ratio:new et.b5(M,Bt.u_aspect_ratio),u_fade_change:new et.b5(M,Bt.u_fade_change),u_label_plane_matrix:new et.bD(M,Bt.u_label_plane_matrix),u_coord_matrix:new et.bD(M,Bt.u_coord_matrix),u_is_text:new et.bC(M,Bt.u_is_text),u_pitch_with_map:new et.bC(M,Bt.u_pitch_with_map),u_is_along_line:new et.bC(M,Bt.u_is_along_line),u_is_variable_anchor:new et.bC(M,Bt.u_is_variable_anchor),u_texsize:new et.bH(M,Bt.u_texsize),u_texture:new et.bC(M,Bt.u_texture),u_gamma_scale:new et.b5(M,Bt.u_gamma_scale),u_device_pixel_ratio:new et.b5(M,Bt.u_device_pixel_ratio),u_is_halo:new et.bC(M,Bt.u_is_halo),u_translation:new et.bH(M,Bt.u_translation),u_pitched_scale:new et.b5(M,Bt.u_pitched_scale)}),symbolTextAndIcon:(M,Bt)=>({u_is_size_zoom_constant:new et.bC(M,Bt.u_is_size_zoom_constant),u_is_size_feature_constant:new et.bC(M,Bt.u_is_size_feature_constant),u_size_t:new et.b5(M,Bt.u_size_t),u_size:new et.b5(M,Bt.u_size),u_camera_to_center_distance:new et.b5(M,Bt.u_camera_to_center_distance),u_pitch:new et.b5(M,Bt.u_pitch),u_rotate_symbol:new et.bC(M,Bt.u_rotate_symbol),u_aspect_ratio:new et.b5(M,Bt.u_aspect_ratio),u_fade_change:new et.b5(M,Bt.u_fade_change),u_label_plane_matrix:new et.bD(M,Bt.u_label_plane_matrix),u_coord_matrix:new et.bD(M,Bt.u_coord_matrix),u_is_text:new et.bC(M,Bt.u_is_text),u_pitch_with_map:new et.bC(M,Bt.u_pitch_with_map),u_is_along_line:new et.bC(M,Bt.u_is_along_line),u_is_variable_anchor:new et.bC(M,Bt.u_is_variable_anchor),u_texsize:new et.bH(M,Bt.u_texsize),u_texsize_icon:new et.bH(M,Bt.u_texsize_icon),u_texture:new et.bC(M,Bt.u_texture),u_texture_icon:new et.bC(M,Bt.u_texture_icon),u_gamma_scale:new et.b5(M,Bt.u_gamma_scale),u_device_pixel_ratio:new et.b5(M,Bt.u_device_pixel_ratio),u_is_halo:new et.bC(M,Bt.u_is_halo),u_translation:new et.bH(M,Bt.u_translation),u_pitched_scale:new et.b5(M,Bt.u_pitched_scale)}),background:(M,Bt)=>({u_opacity:new et.b5(M,Bt.u_opacity),u_color:new et.bF(M,Bt.u_color)}),backgroundPattern:(M,Bt)=>({u_opacity:new et.b5(M,Bt.u_opacity),u_image:new et.bC(M,Bt.u_image),u_pattern_tl_a:new et.bH(M,Bt.u_pattern_tl_a),u_pattern_br_a:new et.bH(M,Bt.u_pattern_br_a),u_pattern_tl_b:new et.bH(M,Bt.u_pattern_tl_b),u_pattern_br_b:new et.bH(M,Bt.u_pattern_br_b),u_texsize:new et.bH(M,Bt.u_texsize),u_mix:new et.b5(M,Bt.u_mix),u_pattern_size_a:new et.bH(M,Bt.u_pattern_size_a),u_pattern_size_b:new et.bH(M,Bt.u_pattern_size_b),u_scale_a:new et.b5(M,Bt.u_scale_a),u_scale_b:new et.b5(M,Bt.u_scale_b),u_pixel_coord_upper:new et.bH(M,Bt.u_pixel_coord_upper),u_pixel_coord_lower:new et.bH(M,Bt.u_pixel_coord_lower),u_tile_units_to_pixels:new et.b5(M,Bt.u_tile_units_to_pixels)}),terrain:(M,Bt)=>({u_texture:new et.bC(M,Bt.u_texture),u_ele_delta:new et.b5(M,Bt.u_ele_delta),u_fog_matrix:new et.bD(M,Bt.u_fog_matrix),u_fog_color:new et.bF(M,Bt.u_fog_color),u_fog_ground_blend:new et.b5(M,Bt.u_fog_ground_blend),u_fog_ground_blend_opacity:new et.b5(M,Bt.u_fog_ground_blend_opacity),u_horizon_color:new et.bF(M,Bt.u_horizon_color),u_horizon_fog_blend:new et.b5(M,Bt.u_horizon_fog_blend),u_is_globe_mode:new et.b5(M,Bt.u_is_globe_mode)}),terrainDepth:(M,Bt)=>({u_ele_delta:new et.b5(M,Bt.u_ele_delta)}),terrainCoords:(M,Bt)=>({u_texture:new et.bC(M,Bt.u_texture),u_terrain_coords_id:new et.b5(M,Bt.u_terrain_coords_id),u_ele_delta:new et.b5(M,Bt.u_ele_delta)}),projectionErrorMeasurement:(M,Bt)=>({u_input:new et.b5(M,Bt.u_input),u_output_expected:new et.b5(M,Bt.u_output_expected)}),atmosphere:(M,Bt)=>({u_sun_pos:new et.bG(M,Bt.u_sun_pos),u_atmosphere_blend:new et.b5(M,Bt.u_atmosphere_blend),u_globe_position:new et.bG(M,Bt.u_globe_position),u_globe_radius:new et.b5(M,Bt.u_globe_radius),u_inv_proj_matrix:new et.bD(M,Bt.u_inv_proj_matrix)}),sky:(M,Bt)=>({u_sky_color:new et.bF(M,Bt.u_sky_color),u_horizon_color:new et.bF(M,Bt.u_horizon_color),u_horizon:new et.bH(M,Bt.u_horizon),u_horizon_normal:new et.bH(M,Bt.u_horizon_normal),u_sky_horizon_blend:new et.b5(M,Bt.u_sky_horizon_blend),u_sky_blend:new et.b5(M,Bt.u_sky_blend)})};class er{constructor(M,et,Bt){this.context=M;const Wt=M.gl;this.buffer=Wt.createBuffer(),this.dynamicDraw=Boolean(Bt),this.context.unbindVAO(),M.bindElementBuffer.set(this.buffer),Wt.bufferData(Wt.ELEMENT_ARRAY_BUFFER,et.arrayBuffer,this.dynamicDraw?Wt.DYNAMIC_DRAW:Wt.STATIC_DRAW),this.dynamicDraw||delete et.arrayBuffer}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(M){const et=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO(),this.bind(),et.bufferSubData(et.ELEMENT_ARRAY_BUFFER,0,M.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}const dc={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class ir{constructor(M,et,Bt,Wt){this.length=et.length,this.attributes=Bt,this.itemSize=et.bytesPerElement,this.dynamicDraw=Wt,this.context=M;const Nt=M.gl;this.buffer=Nt.createBuffer(),M.bindVertexBuffer.set(this.buffer),Nt.bufferData(Nt.ARRAY_BUFFER,et.arrayBuffer,this.dynamicDraw?Nt.DYNAMIC_DRAW:Nt.STATIC_DRAW),this.dynamicDraw||delete et.arrayBuffer}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(M){if(M.length!==this.length)throw new Error(`Length of new data is ${M.length}, which doesn't match current length of ${this.length}`);const et=this.context.gl;this.bind(),et.bufferSubData(et.ARRAY_BUFFER,0,M.arrayBuffer)}enableAttributes(M,et){for(let Bt=0;Bt0&&(uo.push({circleArray:Ba,circleOffset:Po,coord:To}),Io+=Ba.length/4,Po=Io),Ia&&so.draw(Gr,Hn.LINES,Ot.disabled,Zt.disabled,M.colorModeForRenderPass(),jt.disabled,Di(M.transform),M.style.map.terrain&&M.style.map.terrain.getTerrainData(To),mn.getProjectionData({overscaledTileID:To,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),Wt.id,Ia.layoutVertexBuffer,Ia.indexBuffer,Ia.segments,null,M.transform.zoom,null,null,Ia.collisionVertexBuffer)}if(!$t||!uo.length)return;const To=M.useProgram("collisionCircle"),Eo=new et.bM;Eo.resize(4*Io),Eo._trim();let Ia=0;for(const M of uo)for(let et=0;et=0&&(Ba[Ta.associatedIconIndex]={shiftedAnchor:Sl,angle:Zl})}else Be(Ta.numGlyphs,Eo)}if(so){Ia.clear();const Bt=M.icon.placedSymbolArray;for(let M=0;MM.style.map.terrain.getElevation(Hn,et,Bt):null,Bt="map"===Wt.layout.get("text-rotation-alignment");Pe(so,M,$t,Dl,Nl,Va,uo,Bt,Hn.toUnwrapped(),Ba.width,Ba.height,Ol,et)}const $l=$t&&Ka||ql,tc=za||$l?yc:Va?Dl:M.transform.clipSpaceToPixelsMatrix,ec=Eo&&0!==Wt.paint.get($t?"text-halo-width":"icon-halo-width").constantOr(1);let dc;dc=Eo?so.iconsInText?$i(Da.kind,Zl,Fa,Va,za,$l,M,tc,Yl,Ol,Rl,El,$a):Xi(Da.kind,Zl,Fa,Va,za,$l,M,tc,Yl,Ol,$t,Rl,!0,$a):Wi(Da.kind,Zl,Fa,Va,za,$l,M,tc,Yl,Ol,$t,Rl,$a);const Ic={program:Sl,buffers:Io,uniformValues:dc,projectionData:jl,atlasTexture:Tl,atlasTextureIcon:Jl,atlasInterpolation:Vl,atlasInterpolationIcon:Wl,isSDF:Eo,hasHalo:ec};if(Ea&&so.canOverlap){La=!0;const M=Io.segments.get();for(const Bt of M)Oa.push({segments:new et.aD([Bt]),sortKey:Bt.sortKey,state:Ic,terrainData:Gl})}else Oa.push({segments:Io.segments,sortKey:0,state:Ic,terrainData:Gl})}La&&Oa.sort(((M,et)=>M.sortKey-et.sortKey));for(const et of Oa){const Bt=et.state;if(Eo.activeTexture.set(Ia.TEXTURE0),Bt.atlasTexture.bind(Bt.atlasInterpolation,Ia.CLAMP_TO_EDGE),Bt.atlasTextureIcon&&(Eo.activeTexture.set(Ia.TEXTURE1),Bt.atlasTextureIcon&&Bt.atlasTextureIcon.bind(Bt.atlasInterpolationIcon,Ia.CLAMP_TO_EDGE)),Bt.isSDF){const Nt=Bt.uniformValues;Bt.hasHalo&&(Nt.u_is_halo=1,Kr(Bt.buffers,et.segments,Wt,M,Bt.program,Da,Io,Po,Nt,Bt.projectionData,et.terrainData)),Nt.u_is_halo=0}Kr(Bt.buffers,et.segments,Wt,M,Bt.program,Da,Io,Po,Bt.uniformValues,Bt.projectionData,et.terrainData)}}function Kr(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo){const Io=Wt.context;Nt.draw(Io,Io.gl.TRIANGLES,$t,Gr,mn,jt.backCCW,Hn,uo,so,Bt.id,M.layoutVertexBuffer,M.indexBuffer,et,Bt.paint,Wt.transform.zoom,M.programConfigurations.get(Bt.id),M.dynamicLayoutVertexBuffer,M.opacityVertexBuffer)}function Yr(M,Bt,Wt,Nt,$t){const Gr=M.context,mn=Gr.gl,Hn=Zt.disabled,so=new Ft([mn.ONE,mn.ONE],et.b4.transparent,[!0,!0,!0,!0]),uo=Bt.getBucket(Wt);if(!uo)return;const Io=Nt.key;let Po=Wt.heatmapFbos.get(Io);Po||(Po=Qr(Gr,Bt.tileSize,Bt.tileSize),Wt.heatmapFbos.set(Io,Po)),Gr.bindFramebuffer.set(Po.framebuffer),Gr.viewport.set([0,0,Bt.tileSize,Bt.tileSize]),Gr.clear({color:et.b4.transparent});const To=uo.programConfigurations.get(Wt.id),Eo=M.useProgram("heatmap",To,!$t),Ia=M.transform.getProjectionData({overscaledTileID:Bt.tileID,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),Ba=M.style.map.terrain.getTerrainData(Nt);Eo.draw(Gr,mn.TRIANGLES,Ot.disabled,Hn,so,jt.disabled,Li(Bt,M.transform.zoom,Wt.paint.get("heatmap-intensity"),1),Ba,Ia,Wt.id,uo.layoutVertexBuffer,uo.indexBuffer,uo.segments,Wt.paint,M.transform.zoom,To)}function Jr(M,et,Bt,Wt,Nt){const $t=M.context,Gr=$t.gl,mn=M.transform;$t.setColorMode(M.colorModeForRenderPass());const Hn=eo($t,et),so=Bt.key,uo=et.heatmapFbos.get(so);if(!uo)return;$t.activeTexture.set(Gr.TEXTURE0),Gr.bindTexture(Gr.TEXTURE_2D,uo.colorAttachment.get()),$t.activeTexture.set(Gr.TEXTURE1),Hn.bind(Gr.LINEAR,Gr.CLAMP_TO_EDGE);const Io=mn.getProjectionData({overscaledTileID:Bt,applyTerrainMatrix:Nt,applyGlobeMatrix:!Wt});M.useProgram("heatmapTexture").draw($t,Gr.TRIANGLES,Ot.disabled,Zt.disabled,M.colorModeForRenderPass(),jt.disabled,ki(M,et,0,1),null,Io,et.id,M.rasterBoundsBuffer,M.quadTriangleIndexBuffer,M.rasterBoundsSegments,et.paint,mn.zoom),uo.destroy(),et.heatmapFbos.delete(so)}function Qr(M,et,Bt){var Wt,Nt;const $t=M.gl,Gr=$t.createTexture();$t.bindTexture($t.TEXTURE_2D,Gr),$t.texParameteri($t.TEXTURE_2D,$t.TEXTURE_WRAP_S,$t.CLAMP_TO_EDGE),$t.texParameteri($t.TEXTURE_2D,$t.TEXTURE_WRAP_T,$t.CLAMP_TO_EDGE),$t.texParameteri($t.TEXTURE_2D,$t.TEXTURE_MIN_FILTER,$t.LINEAR),$t.texParameteri($t.TEXTURE_2D,$t.TEXTURE_MAG_FILTER,$t.LINEAR);const mn=null!==(Wt=M.HALF_FLOAT)&&void 0!==Wt?Wt:$t.UNSIGNED_BYTE,Hn=null!==(Nt=M.RGBA16F)&&void 0!==Nt?Nt:$t.RGBA;$t.texImage2D($t.TEXTURE_2D,0,Hn,et,Bt,0,$t.RGBA,mn,null);const so=M.createFramebuffer(et,Bt,!1,!1);return so.colorAttachment.set(Gr),so}function eo(M,et){return et.colorRampTexture||(et.colorRampTexture=new v(M,et.colorRamp,M.gl.RGBA)),et.colorRampTexture}function to(M,et,Bt,Wt,Nt){if(!Bt||!Wt||!Wt.imageAtlas)return;const $t=Wt.imageAtlas.patternPositions;let Gr=$t[Bt.to.toString()],mn=$t[Bt.from.toString()];if(!Gr&&mn&&(Gr=mn),!mn&&Gr&&(mn=Gr),!Gr||!mn){const M=Nt.getPaintProperty(et);Gr=$t[M],mn=$t[M]}Gr&&mn&&M.setConstantPatternPositions(Gr,mn)}function io(M,Bt,Wt,Nt,$t,Gr,mn,Hn){const so=M.context.gl,uo="fill-pattern",Io=Wt.paint.get(uo),Po=Io&&Io.constantOr(1),To=Wt.getCrossfadeParameters();let Eo,Ia,Ba,Ta,Va;const za=M.transform,Fa=Wt.paint.get("fill-translate"),Ea=Wt.paint.get("fill-translate-anchor");mn?(Ia=Po&&!Wt.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",Eo=so.LINES):(Ia=Po?"fillPattern":"fill",Eo=so.TRIANGLES);const La=Io.constantOr(null);for(const Io of Nt){const Da=Bt.getTile(Io);if(Po&&!Da.patternsLoaded())continue;const Ka=Da.getBucket(Wt);if(!Ka)continue;const Oa=Ka.programConfigurations.get(Wt.id),$a=M.useProgram(Ia,Oa),Al=M.style.map.terrain&&M.style.map.terrain.getTerrainData(Io);Po&&(M.context.activeTexture.set(so.TEXTURE0),Da.imageAtlasTexture.bind(so.LINEAR,so.CLAMP_TO_EDGE),Oa.updatePaintBuffers(To)),to(Oa,uo,La,Da,Wt);const Sl=za.getProjectionData({overscaledTileID:Io,applyGlobeMatrix:!Hn,applyTerrainMatrix:!0}),Zl=et.au(za,Da,Fa,Ea);if(mn){Ta=Ka.indexBuffer2,Va=Ka.segments2;const et=[so.drawingBufferWidth,so.drawingBufferHeight];Ba="fillOutlinePattern"===Ia&&Po?Si(M,To,Da,et,Zl):Mi(et,Zl)}else Ta=Ka.indexBuffer,Va=Ka.segments,Ba=Po?Ei(M,To,Da,Zl):{u_fill_translate:Zl};let Gl;if("translucent"===M.renderPass&&Hn){const[et]=M.getStencilConfigForOverlapAndUpdateStencilID(Nt);Gl=et[Io.overscaledZ]}else Gl=M.stencilModeForClipping(Io);$a.draw(M.context,Eo,$t,Gl,Gr,jt.backCCW,Ba,Al,Sl,Wt.id,Ka.layoutVertexBuffer,Ta,Va,Wt.paint,M.transform.zoom,Oa)}}function ro(M,Bt,Wt,Nt,$t,Gr,mn,Hn){const so=M.context,uo=so.gl,Io="fill-extrusion-pattern",Po=Wt.paint.get(Io),To=Po.constantOr(1),Eo=Wt.getCrossfadeParameters(),Ia=Wt.paint.get("fill-extrusion-opacity"),Ba=Po.constantOr(null),Ta=M.transform;for(const Po of Nt){const Nt=Bt.getTile(Po),Va=Nt.getBucket(Wt);if(!Va)continue;const za=M.style.map.terrain&&M.style.map.terrain.getTerrainData(Po),Fa=Va.programConfigurations.get(Wt.id),Ea=M.useProgram(To?"fillExtrusionPattern":"fillExtrusion",Fa);To&&(M.context.activeTexture.set(uo.TEXTURE0),Nt.imageAtlasTexture.bind(uo.LINEAR,uo.CLAMP_TO_EDGE),Fa.updatePaintBuffers(Eo));const La=Ta.getProjectionData({overscaledTileID:Po,applyGlobeMatrix:!Hn,applyTerrainMatrix:!0});to(Fa,Io,Ba,Nt,Wt);const Da=et.au(Ta,Nt,Wt.paint.get("fill-extrusion-translate"),Wt.paint.get("fill-extrusion-translate-anchor")),Ka=Wt.paint.get("fill-extrusion-vertical-gradient"),Oa=To?Ii(M,Ka,Ia,Da,Po,Eo,Nt):Ci(M,Ka,Ia,Da);Ea.draw(so,so.gl.TRIANGLES,$t,Gr,mn,jt.backCCW,Oa,za,La,Wt.id,Va.layoutVertexBuffer,Va.indexBuffer,Va.segments,Wt.paint,M.transform.zoom,Fa,M.style.map.terrain&&Va.centroidVertexBuffer)}}function oo(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn){var so;const uo=M.style.projection,Io=M.context,Po=M.transform,To=Io.gl,Eo=M.useProgram("hillshade"),Ia=!M.options.moving;for(const Ba of Wt){const Wt=et.getTile(Ba),Ta=Wt.fbo;if(!Ta)continue;const Va=uo.getMeshFromTileID(Io,Ba.canonical,mn,!0,"raster"),za=null===(so=M.style.map.terrain)||void 0===so?void 0:so.getTerrainData(Ba);Io.activeTexture.set(To.TEXTURE0),To.bindTexture(To.TEXTURE_2D,Ta.colorAttachment.get());const Fa=Po.getProjectionData({overscaledTileID:Ba,aligned:Ia,applyGlobeMatrix:!Hn,applyTerrainMatrix:!0});Eo.draw(Io,To.TRIANGLES,$t,Nt[Ba.overscaledZ],Gr,jt.backCCW,Fi(M,Wt,Bt),za,Fa,Bt.id,Va.vertexBuffer,Va.indexBuffer,Va.segments)}}const vc=[new et.P(0,0),new et.P(et.X,0),new et.P(et.X,et.X),new et.P(0,et.X)];function ao(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn=!1,so=!1){const uo=Wt[Wt.length-1].overscaledZ,Io=M.context,Po=Io.gl,To=M.useProgram("raster"),Eo=M.transform,Ia=M.style.projection,Ba=M.colorModeForRenderPass(),Ta=!M.options.moving;for(const Va of Wt){const Wt=M.getDepthModeForSublayer(Va.overscaledZ-uo,1===Bt.paint.get("raster-opacity")?Ot.ReadWrite:Ot.ReadOnly,Po.LESS),za=et.getTile(Va);za.registerFadeDuration(Bt.paint.get("raster-fade-duration"));const Fa=et.findLoadedParent(Va,0),Ea=et.findLoadedSibling(Va),La=no(za,Fa||Ea||null,et,Bt,M.transform,M.style.map.terrain);let Da,Ka;const Oa="nearest"===Bt.paint.get("raster-resampling")?Po.NEAREST:Po.LINEAR;Io.activeTexture.set(Po.TEXTURE0),za.texture.bind(Oa,Po.CLAMP_TO_EDGE,Po.LINEAR_MIPMAP_NEAREST),Io.activeTexture.set(Po.TEXTURE1),Fa?(Fa.texture.bind(Oa,Po.CLAMP_TO_EDGE,Po.LINEAR_MIPMAP_NEAREST),Da=Math.pow(2,Fa.tileID.overscaledZ-za.tileID.overscaledZ),Ka=[za.tileID.canonical.x*Da%1,za.tileID.canonical.y*Da%1]):za.texture.bind(Oa,Po.CLAMP_TO_EDGE,Po.LINEAR_MIPMAP_NEAREST),za.texture.useMipmap&&Io.extTextureFilterAnisotropic&&M.transform.pitch>20&&Po.texParameterf(Po.TEXTURE_2D,Io.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,Io.extTextureFilterAnisotropicMax);const $a=M.style.map.terrain&&M.style.map.terrain.getTerrainData(Va),Al=Eo.getProjectionData({overscaledTileID:Va,aligned:Ta,applyGlobeMatrix:!so,applyTerrainMatrix:!0}),Sl=qi(Ka||[0,0],Da||1,La,Bt,mn),Zl=Ia.getMeshFromTileID(Io,Va.canonical,$t,Gr,"raster");To.draw(Io,Po.TRIANGLES,Wt,Nt?Nt[Va.overscaledZ]:Zt.disabled,Ba,Hn?jt.frontCCW:jt.backCCW,Sl,$a,Al,Bt.id,Zl.vertexBuffer,Zl.indexBuffer,Zl.segments)}}function no(M,Bt,Wt,Nt,Gr,mn){const Hn=Nt.paint.get("raster-fade-duration");if(!mn&&Hn>0){const Nt=$t.now(),mn=(Nt-M.timeAdded)/Hn,so=Bt?(Nt-Bt.timeAdded)/Hn:-1,uo=Wt.getSource(),Io=he(Gr,{tileSize:uo.tileSize,roundZoom:uo.roundZoom}),Po=!Bt||Math.abs(Bt.tileID.overscaledZ-Io)>Math.abs(M.tileID.overscaledZ-Io),To=Po&&M.refreshedUponExpiration?1:et.ab(Po?mn:1-so,0,1);return M.refreshedUponExpiration&&mn>=1&&(M.refreshedUponExpiration=!1),Bt?{opacity:1,mix:1-To}:{opacity:To,mix:0}}return{opacity:1,mix:0}}const xc=new et.b4(1,0,0,1),Bc=new et.b4(0,1,0,1),Tc=new et.b4(0,0,1,1),Mc=new et.b4(1,0,1,1),Vc=new et.b4(0,1,1,1);function po(M,et,Bt,Wt){fo(M,0,et+Bt/2,M.transform.width,Bt,Wt)}function mo(M,et,Bt,Wt){fo(M,et-Bt/2,0,Bt,M.transform.height,Wt)}function fo(M,et,Bt,Wt,Nt,$t){const Gr=M.context,mn=Gr.gl;mn.enable(mn.SCISSOR_TEST),mn.scissor(et*M.pixelRatio,Bt*M.pixelRatio,Wt*M.pixelRatio,Nt*M.pixelRatio),Gr.clear({color:$t}),mn.disable(mn.SCISSOR_TEST)}function go(M,Bt,Wt){const Nt=M.context,$t=Nt.gl,Gr=M.useProgram("debug"),mn=Ot.disabled,Hn=Zt.disabled,so=M.colorModeForRenderPass(),uo="$debug",Io=M.style.map.terrain&&M.style.map.terrain.getTerrainData(Wt);Nt.activeTexture.set($t.TEXTURE0);const Po=Bt.getTileByID(Wt.key).latestRawTileData,To=Math.floor((Po&&Po.byteLength||0)/1024),Eo=Bt.getTile(Wt).tileSize,Ia=512/Math.min(Eo,512)*(Wt.overscaledZ/M.transform.zoom)*.5;let Ba=Wt.canonical.toString();Wt.overscaledZ!==Wt.canonical.z&&(Ba+=` => ${Wt.overscaledZ}`),function(M,et){M.initDebugOverlayCanvas();const Bt=M.debugOverlayCanvas,Wt=M.context.gl,Nt=M.debugOverlayCanvas.getContext("2d");Nt.clearRect(0,0,Bt.width,Bt.height),Nt.shadowColor="white",Nt.shadowBlur=2,Nt.lineWidth=1.5,Nt.strokeStyle="white",Nt.textBaseline="top",Nt.font="bold 36px Open Sans, sans-serif",Nt.fillText(et,5,5),Nt.strokeText(et,5,5),M.debugOverlayTexture.update(Bt),M.debugOverlayTexture.bind(Wt.LINEAR,Wt.CLAMP_TO_EDGE)}(M,`${Ba} ${To}kB`);const Ta=M.transform.getProjectionData({overscaledTileID:Wt,applyGlobeMatrix:!0,applyTerrainMatrix:!0});Gr.draw(Nt,$t.TRIANGLES,mn,Hn,Ft.alphaBlended,jt.disabled,Ai(et.b4.transparent,Ia),null,Ta,uo,M.debugBuffer,M.quadTriangleIndexBuffer,M.debugSegments),Gr.draw(Nt,$t.LINE_STRIP,mn,Hn,so,jt.disabled,Ai(et.b4.red),Io,Ta,uo,M.debugBuffer,M.tileBorderIndexBuffer,M.debugSegments)}function vo(M,et,Bt,Wt){const{isRenderingGlobe:Nt}=Wt,$t=M.context,Gr=$t.gl,mn=M.transform,Hn=M.colorModeForRenderPass(),so=M.getDepthModeFor3D(),uo=M.useProgram("terrain");$t.bindFramebuffer.set(null),$t.viewport.set([0,0,M.width,M.height]);for(const Wt of Bt){const Bt=et.getTerrainMesh(Wt.tileID),Io=M.renderToTexture.getTexture(Wt),Po=et.getTerrainData(Wt.tileID);$t.activeTexture.set(Gr.TEXTURE0),Gr.bindTexture(Gr.TEXTURE_2D,Io.texture);const To=et.getMeshFrameDelta(mn.zoom),Eo=mn.calculateFogMatrix(Wt.tileID.toUnwrapped()),Ia=bi(To,Eo,M.style.sky,mn.pitch,Nt),Ba=mn.getProjectionData({overscaledTileID:Wt.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});uo.draw($t,Gr.TRIANGLES,so,Zt.disabled,Hn,jt.backCCW,Ia,Po,Ba,"terrain",Bt.vertexBuffer,Bt.indexBuffer,Bt.segments)}}function xo(M,Bt){if(!Bt.mesh){const Wt=new et.aC;Wt.emplaceBack(-1,-1),Wt.emplaceBack(1,-1),Wt.emplaceBack(1,1),Wt.emplaceBack(-1,1);const Nt=new et.aE;Nt.emplaceBack(0,1,2),Nt.emplaceBack(0,2,3),Bt.mesh=new pt(M.createVertexBuffer(Wt,El.members),M.createIndexBuffer(Nt),et.aD.simpleSegment(0,0,Wt.length,Nt.length))}return Bt.mesh}class bo{constructor(M,Bt){this.context=new Zr(M),this.transform=Bt,this._tileTextures={},this.terrainFacilitator={dirty:!0,matrix:et.aq(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=de.maxUnderzooming+de.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new ht}resize(M,et,Bt){if(this.width=Math.floor(M*Bt),this.height=Math.floor(et*Bt),this.pixelRatio=Bt,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const M of this.style._order)this.style._layers[M].resize()}setup(){const M=this.context,Bt=new et.aC;Bt.emplaceBack(0,0),Bt.emplaceBack(et.X,0),Bt.emplaceBack(0,et.X),Bt.emplaceBack(et.X,et.X),this.tileExtentBuffer=M.createVertexBuffer(Bt,El.members),this.tileExtentSegments=et.aD.simpleSegment(0,0,4,2);const Wt=new et.aC;Wt.emplaceBack(0,0),Wt.emplaceBack(et.X,0),Wt.emplaceBack(0,et.X),Wt.emplaceBack(et.X,et.X),this.debugBuffer=M.createVertexBuffer(Wt,El.members),this.debugSegments=et.aD.simpleSegment(0,0,4,5);const Nt=new et.bT;Nt.emplaceBack(0,0,0,0),Nt.emplaceBack(et.X,0,et.X,0),Nt.emplaceBack(0,et.X,0,et.X),Nt.emplaceBack(et.X,et.X,et.X,et.X),this.rasterBoundsBuffer=M.createVertexBuffer(Nt,$l.members),this.rasterBoundsSegments=et.aD.simpleSegment(0,0,4,2);const $t=new et.aC;$t.emplaceBack(0,0),$t.emplaceBack(et.X,0),$t.emplaceBack(0,et.X),$t.emplaceBack(et.X,et.X),this.rasterBoundsBufferPosOnly=M.createVertexBuffer($t,El.members),this.rasterBoundsSegmentsPosOnly=et.aD.simpleSegment(0,0,4,5);const Gr=new et.aC;Gr.emplaceBack(0,0),Gr.emplaceBack(1,0),Gr.emplaceBack(0,1),Gr.emplaceBack(1,1),this.viewportBuffer=M.createVertexBuffer(Gr,El.members),this.viewportSegments=et.aD.simpleSegment(0,0,4,2);const mn=new et.bU;mn.emplaceBack(0),mn.emplaceBack(1),mn.emplaceBack(3),mn.emplaceBack(2),mn.emplaceBack(0),this.tileBorderIndexBuffer=M.createIndexBuffer(mn);const Hn=new et.aE;Hn.emplaceBack(1,0,2),Hn.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=M.createIndexBuffer(Hn);const so=this.context.gl;this.stencilClearMode=new Zt({func:so.ALWAYS,mask:0},0,255,so.ZERO,so.ZERO,so.ZERO),this.tileExtentMesh=new pt(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments)}clearStencil(){const M=this.context,Bt=M.gl;this.nextStencilID=1,this.currentStencilSource=void 0;const Wt=et.H();et.bL(Wt,0,this.width,this.height,0,0,1),et.K(Wt,Wt,[Bt.drawingBufferWidth,Bt.drawingBufferHeight,0]);const Nt={mainMatrix:Wt,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:Wt};this.useProgram("clippingMask",null,!0).draw(M,Bt.TRIANGLES,Ot.disabled,this.stencilClearMode,Ft.disabled,jt.disabled,null,null,Nt,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}_renderTileClippingMasks(M,et,Bt){if(this.currentStencilSource===M.source||!M.isTileClipped()||!et||!et.length)return;this.currentStencilSource=M.source,this.nextStencilID+et.length>256&&this.clearStencil();const Wt=this.context;Wt.setColorMode(Ft.disabled),Wt.setDepthMode(Ot.disabled);const Nt={};for(const M of et)Nt[M.key]=this.nextStencilID++;this._renderTileMasks(Nt,et,Bt,!0),this._renderTileMasks(Nt,et,Bt,!1),this._tileClippingMaskIDs=Nt}_renderTileMasks(M,et,Bt,Wt){const Nt=this.context,$t=Nt.gl,Gr=this.style.projection,mn=this.transform,Hn=this.useProgram("clippingMask");for(const so of et){const et=M[so.key],uo=this.style.map.terrain&&this.style.map.terrain.getTerrainData(so),Io=Gr.getMeshFromTileID(this.context,so.canonical,Wt,!0,"stencil"),Po=mn.getProjectionData({overscaledTileID:so,applyGlobeMatrix:!0,applyTerrainMatrix:!0});Hn.draw(Nt,$t.TRIANGLES,Ot.disabled,new Zt({func:$t.ALWAYS,mask:0},et,255,$t.KEEP,$t.KEEP,$t.REPLACE),Ft.disabled,Bt?jt.disabled:jt.backCCW,null,uo,Po,"$clipping",Io.vertexBuffer,Io.indexBuffer,Io.segments)}}_renderTilesDepthBuffer(){const M=this.context,et=M.gl,Bt=this.style.projection,Wt=this.transform,Nt=this.useProgram("depth"),$t=this.getDepthModeFor3D(),Gr=ue(Wt,{tileSize:Wt.tileSize});for(const mn of Gr){const Gr=this.style.map.terrain&&this.style.map.terrain.getTerrainData(mn),Hn=Bt.getMeshFromTileID(this.context,mn.canonical,!0,!0,"raster"),so=Wt.getProjectionData({overscaledTileID:mn,applyGlobeMatrix:!0,applyTerrainMatrix:!0});Nt.draw(M,et.TRIANGLES,$t,Zt.disabled,Ft.disabled,jt.backCCW,null,Gr,so,"$clipping",Hn.vertexBuffer,Hn.indexBuffer,Hn.segments)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const M=this.nextStencilID++,et=this.context.gl;return new Zt({func:et.NOTEQUAL,mask:255},M,255,et.KEEP,et.KEEP,et.REPLACE)}stencilModeForClipping(M){const et=this.context.gl;return new Zt({func:et.EQUAL,mask:255},this._tileClippingMaskIDs[M.key],0,et.KEEP,et.KEEP,et.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(M){const et=this.context.gl,Bt=M.sort(((M,et)=>et.overscaledZ-M.overscaledZ)),Wt=Bt[Bt.length-1].overscaledZ,Nt=Bt[0].overscaledZ-Wt+1;if(Nt>1){this.currentStencilSource=void 0,this.nextStencilID+Nt>256&&this.clearStencil();const M={};for(let Bt=0;Btet.overscaledZ-M.overscaledZ)),Wt=Bt[Bt.length-1].overscaledZ,Nt=Bt[0].overscaledZ-Wt+1;if(this.clearStencil(),Nt>1){const M={},$t={};for(let Bt=0;Bt0};for(const M in mn){const et=mn[M];et.used&&et.prepare(this.context),Hn[M]=et.getVisibleCoordinates(!1),so[M]=Hn[M].slice().reverse(),uo[M]=et.getVisibleCoordinates(!0).reverse()}this.opaquePassCutoff=1/0;for(let M=0;Mthis.useProgram(M)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:Bt.showOverdrawInspector?et.b4.black:et.b4.transparent,depth:1}),this.clearStencil(),this.style.sky&&function(M,et){const Bt=M.context,Wt=Bt.gl,Nt=((M,et,Bt)=>{const Wt=Math.cos(et.rollInRadians),Nt=Math.sin(et.rollInRadians),$t=yt(et),Gr=et.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}).projectionTransition;return{u_sky_color:M.properties.get("sky-color"),u_horizon_color:M.properties.get("horizon-color"),u_horizon:[(et.width/2-$t*Nt)*Bt,(et.height/2+$t*Wt)*Bt],u_horizon_normal:[-Nt,Wt],u_sky_horizon_blend:M.properties.get("sky-horizon-blend")*et.height/2*Bt,u_sky_blend:Gr}})(et,M.style.map.transform,M.pixelRatio),$t=new Ot(Wt.LEQUAL,Ot.ReadWrite,[0,1]),Gr=Zt.disabled,mn=M.colorModeForRenderPass(),Hn=M.useProgram("sky"),so=xo(Bt,et);Hn.draw(Bt,Wt.TRIANGLES,$t,Gr,mn,jt.disabled,Nt,null,void 0,"sky",so.vertexBuffer,so.indexBuffer,so.segments)}(this,this.style.sky),this._showOverdrawInspector=Bt.showOverdrawInspector,this.depthRangeFor3D=[0,1-(M._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=Gr.length-1;this.currentLayer>=0;this.currentLayer--){const M=this.style._layers[Gr[this.currentLayer]],et=mn[M.source],Bt=Hn[M.source];this._renderTileClippingMasks(M,Bt,!1),this.renderLayer(this,et,M,Bt,Io)}this.renderPass="translucent";let Po=!1;for(this.currentLayer=0;this.currentLayer({u_sun_pos:M,u_atmosphere_blend:et,u_globe_position:Bt,u_globe_radius:Wt,u_inv_proj_matrix:Nt}))(so,Io,[Eo[0],Eo[1],Eo[2]],Po,To),Ba=xo(Nt,Bt);Gr.draw(Nt,$t.TRIANGLES,mn,Zt.disabled,Ft.alphaBlended,jt.disabled,Ia,null,null,"atmosphere",Ba.vertexBuffer,Ba.indexBuffer,Ba.segments)}(this,this.style.sky,this.style.light),this.options.showTileBoundaries){const M=function(M,et){let Bt=null;const Wt=Object.values(M._layers).flatMap((Bt=>Bt.source&&!Bt.isHidden(et)?[M.sourceCaches[Bt.source]]:[])),Nt=Wt.filter((M=>"vector"===M.getSource().type)),$t=Wt.filter((M=>"vector"!==M.getSource().type)),a=M=>{(!Bt||Bt.getSource().maxzooma(M))),Bt||$t.forEach((M=>a(M))),Bt}(this.style,this.transform.zoom);M&&function(M,et,Bt){for(let Wt=0;WtIo.getElevation($t,M,et):null;Wr(Gr,Po,To,so,uo,Ba,Bt,Eo,Ta,et.au(uo,M,mn,Hn),$t.toUnwrapped(),Wt)}}}(Nt,M,Wt,Bt,Wt.layout.get("text-rotation-alignment"),Wt.layout.get("text-pitch-alignment"),Wt.paint.get("text-translate"),Wt.paint.get("text-translate-anchor"),$t),0!==Wt.paint.get("icon-opacity").constantOr(1)&&$r(M,Bt,Wt,Nt,!1,Wt.paint.get("icon-translate"),Wt.paint.get("icon-translate-anchor"),Wt.layout.get("icon-rotation-alignment"),Wt.layout.get("icon-pitch-alignment"),Wt.layout.get("icon-keep-upright"),Hn,so,mn),0!==Wt.paint.get("text-opacity").constantOr(1)&&$r(M,Bt,Wt,Nt,!0,Wt.paint.get("text-translate"),Wt.paint.get("text-translate-anchor"),Wt.layout.get("text-rotation-alignment"),Wt.layout.get("text-pitch-alignment"),Wt.layout.get("text-keep-upright"),Hn,so,mn),Bt.map.showCollisionBoxes&&(Ur(M,Bt,Wt,Nt,!0),Ur(M,Bt,Wt,Nt,!1))}(M,Bt,Wt,Nt,this.style.placement.variableOffsets,$t):et.bZ(Wt)?function(M,Bt,Wt,Nt,$t){if("translucent"!==M.renderPass)return;const{isRenderingToTexture:Gr}=$t,mn=Wt.paint.get("circle-opacity"),Hn=Wt.paint.get("circle-stroke-width"),so=Wt.paint.get("circle-stroke-opacity"),uo=!Wt.layout.get("circle-sort-key").isConstant();if(0===mn.constantOr(1)&&(0===Hn.constantOr(1)||0===so.constantOr(1)))return;const Io=M.context,Po=Io.gl,To=M.transform,Eo=M.getDepthModeForSublayer(0,Ot.ReadOnly),Ia=Zt.disabled,Ba=M.colorModeForRenderPass(),Ta=[],Va=To.getCircleRadiusCorrection();for(let $t=0;$tM.sortKey-et.sortKey));for(const et of Ta){const{programConfiguration:Bt,program:Nt,layoutVertexBuffer:$t,indexBuffer:Gr,uniformValues:mn,terrainData:Hn,projectionData:so}=et.state;Nt.draw(Io,Po.TRIANGLES,Eo,Ia,Ba,jt.backCCW,mn,Hn,so,Wt.id,$t,Gr,et.segments,Wt.paint,M.transform.zoom,Bt)}}(M,Bt,Wt,Nt,$t):et.b_(Wt)?function(M,Bt,Wt,Nt,$t){if(0===Wt.paint.get("heatmap-opacity"))return;const Gr=M.context,{isRenderingToTexture:mn,isRenderingGlobe:Hn}=$t;if(M.style.map.terrain){for(const et of Nt){const Nt=Bt.getTile(et);Bt.hasRenderableParent(et)||("offscreen"===M.renderPass?Yr(M,Nt,Wt,et,Hn):"translucent"===M.renderPass&&Jr(M,Wt,et,mn,Hn))}Gr.viewport.set([0,0,M.width,M.height])}else"offscreen"===M.renderPass?function(M,Bt,Wt,Nt){const $t=M.context,Gr=$t.gl,mn=M.transform,Hn=Zt.disabled,so=new Ft([Gr.ONE,Gr.ONE],et.b4.transparent,[!0,!0,!0,!0]);(function(M,Bt,Wt){const Nt=M.gl;M.activeTexture.set(Nt.TEXTURE1),M.viewport.set([0,0,Bt.width/4,Bt.height/4]);let $t=Wt.heatmapFbos.get(et.bP);$t?(Nt.bindTexture(Nt.TEXTURE_2D,$t.colorAttachment.get()),M.bindFramebuffer.set($t.framebuffer)):($t=Qr(M,Bt.width/4,Bt.height/4),Wt.heatmapFbos.set(et.bP,$t))})($t,M,Wt),$t.clear({color:et.b4.transparent});for(let et=0;et0?et.pop():null}isPatternMissing(M){if(!M)return!1;if(!M.from||!M.to)return!0;const et=this.imageManager.getPattern(M.from.toString()),Bt=this.imageManager.getPattern(M.to.toString());return!et||!Bt}useProgram(M,et,Bt=!1){this.cache=this.cache||{};const Wt=!!this.style.map.terrain,Nt=this.style.projection,$t=M+(et?et.cacheKey:"")+`/${Bt?Ll:Nt.shaderVariantName}`+(this._showOverdrawInspector?"/overdraw":"")+(Wt?"/terrain":"");return this.cache[$t]||(this.cache[$t]=new Ti(this.context,Wl[M],et,ec[M],this._showOverdrawInspector,Wt,Bt?Wl.projectionMercator:Nt.shaderPreludeCode,Bt?Jl:Nt.shaderDefine)),this.cache[$t]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault()}setBaseState(){const M=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(M.FUNC_ADD)}initDebugOverlayCanvas(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new v(this.context,this.debugOverlayCanvas,this.context.gl.RGBA))}destroy(){this.debugOverlayTexture&&this.debugOverlayTexture.destroy()}overLimit(){const{drawingBufferWidth:M,drawingBufferHeight:et}=this.context.gl;return this.width!==M||this.height!==et}}function yo(M,et){let Bt,Wt=!1,Nt=null,$t=null;const a=()=>{Nt=null,Wt&&(M.apply($t,Bt),Nt=setTimeout(a,et),Wt=!1)};return(...M)=>(Wt=!0,$t=this,Bt=M,Nt||a(),Nt)}class wo{constructor(M){this._getCurrentHash=()=>{const M=window.location.hash.replace("#","");if(this._hashName){let et;return M.split("&").map((M=>M.split("="))).forEach((M=>{M[0]===this._hashName&&(et=M)})),(et&&et[1]||"").split("/")}return M.split("/")},this._onHashChange=()=>{const M=this._getCurrentHash();if(!this._isValidHash(M))return!1;const et=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(M[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+M[2],+M[1]],zoom:+M[0],bearing:et,pitch:+(M[4]||0)}),!0},this._updateHashUnthrottled=()=>{const M=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,M)},this._removeHash=()=>{const M=this._getCurrentHash();if(0===M.length)return;const et=M.join("/");let Bt=et;Bt.split("&").length>0&&(Bt=Bt.split("&")[0]),this._hashName&&(Bt=`${this._hashName}=${et}`);let Wt=window.location.hash.replace(Bt,"");Wt.startsWith("#&")?Wt=Wt.slice(0,1)+Wt.slice(2):"#"===Wt&&(Wt="");let Nt=window.location.href.replace(/(#.+)?$/,Wt);Nt=Nt.replace("&&","&"),window.history.replaceState(window.history.state,null,Nt)},this._updateHash=yo(this._updateHashUnthrottled,300),this._hashName=M&&encodeURIComponent(M)}addTo(M){return this._map=M,addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(M){const et=this._map.getCenter(),Bt=Math.round(100*this._map.getZoom())/100,Wt=Math.ceil((Bt*Math.LN2+Math.log(512/360/.5))/Math.LN10),Nt=Math.pow(10,Wt),$t=Math.round(et.lng*Nt)/Nt,Gr=Math.round(et.lat*Nt)/Nt,mn=this._map.getBearing(),Hn=this._map.getPitch();let so="";if(so+=M?`/${$t}/${Gr}/${Bt}`:`${Bt}/${Gr}/${$t}`,(mn||Hn)&&(so+="/"+Math.round(10*mn)/10),Hn&&(so+=`/${Math.round(Hn)}`),this._hashName){const M=this._hashName;let et=!1;const Bt=window.location.hash.slice(1).split("&").map((Bt=>{const Wt=Bt.split("=")[0];return Wt===M?(et=!0,`${Wt}=${so}`):Bt})).filter((M=>M));return et||Bt.push(`${M}=${so}`),`#${Bt.join("&")}`}return`#${so}`}_isValidHash(M){if(M.length<3||M.some(isNaN))return!1;try{new et.N(+M[2],+M[1])}catch(M){return!1}const Bt=+M[0],Wt=+(M[3]||0),Nt=+(M[4]||0);return Bt>=this._map.getMinZoom()&&Bt<=this._map.getMaxZoom()&&Wt>=0&&Wt<=180&&Nt>=this._map.getMinPitch()&&Nt<=this._map.getMaxPitch()}}const zc={linearity:.3,easing:et.c6(0,0,.3,1)},Fc=et.e({deceleration:2500,maxSpeed:1400},zc),Oc=et.e({deceleration:20,maxSpeed:1400},zc),jc=et.e({deceleration:1e3,maxSpeed:360},zc),mh=et.e({deceleration:1e3,maxSpeed:90},zc),Ih=et.e({deceleration:1e3,maxSpeed:360},zc);class So{constructor(M){this._map=M,this.clear()}clear(){this._inertiaBuffer=[]}record(M){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:$t.now(),settings:M})}_drainInertiaBuffer(){const M=this._inertiaBuffer,et=$t.now();for(;M.length>0&&et-M[0].time>160;)M.shift()}_onMoveEnd(M){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const Bt={zoom:0,bearing:0,pitch:0,roll:0,pan:new et.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:M}of this._inertiaBuffer)Bt.zoom+=M.zoomDelta||0,Bt.bearing+=M.bearingDelta||0,Bt.pitch+=M.pitchDelta||0,Bt.roll+=M.rollDelta||0,M.panDelta&&Bt.pan._add(M.panDelta),M.around&&(Bt.around=M.around),M.pinchAround&&(Bt.pinchAround=M.pinchAround);const Wt=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,Nt={};if(Bt.pan.mag()){const $t=Do(Bt.pan.mag(),Wt,et.e({},Fc,M||{})),Gr=Bt.pan.mult($t.amount/Bt.pan.mag()),mn=this._map.cameraHelper.handlePanInertia(Gr,this._map.transform);Nt.center=mn.easingCenter,Nt.offset=mn.easingOffset,Ro(Nt,$t)}if(Bt.zoom){const M=Do(Bt.zoom,Wt,Oc);Nt.zoom=this._map.transform.zoom+M.amount,Ro(Nt,M)}if(Bt.bearing){const M=Do(Bt.bearing,Wt,jc);Nt.bearing=this._map.transform.bearing+et.ab(M.amount,-179,179),Ro(Nt,M)}if(Bt.pitch){const M=Do(Bt.pitch,Wt,mh);Nt.pitch=this._map.transform.pitch+M.amount,Ro(Nt,M)}if(Bt.roll){const M=Do(Bt.roll,Wt,Ih);Nt.roll=this._map.transform.roll+et.ab(M.amount,-179,179),Ro(Nt,M)}if(Nt.zoom||Nt.bearing){const M=void 0===Bt.pinchAround?Bt.around:Bt.pinchAround;Nt.around=M?this._map.unproject(M):this._map.getCenter()}return this.clear(),et.e(Nt,{noMoveStart:!0})}}function Ro(M,et){(!M.duration||M.durationBt.unproject(M))),mn=$t.reduce(((M,et,Bt,Wt)=>M.add(et.div(Wt.length))),new et.P(0,0));super(M,{points:$t,point:mn,lngLats:Gr,lngLat:Bt.unproject(mn),originalEvent:Wt}),this._defaultPrevented=!1}}class Lo extends et.k{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(M,et,Bt){super(M,{originalEvent:Bt}),this._defaultPrevented=!1}}class ko{constructor(M,et){this._map=M,this._clickTolerance=et.clickTolerance}reset(){delete this._mousedownPos}wheel(M){return this._firePreventable(new Lo(M.type,this._map,M))}mousedown(M,et){return this._mousedownPos=et,this._firePreventable(new zo(M.type,this._map,M))}mouseup(M){this._map.fire(new zo(M.type,this._map,M))}click(M,et){this._mousedownPos&&this._mousedownPos.dist(et)>=this._clickTolerance||this._map.fire(new zo(M.type,this._map,M))}dblclick(M){return this._firePreventable(new zo(M.type,this._map,M))}mouseover(M){this._map.fire(new zo(M.type,this._map,M))}mouseout(M){this._map.fire(new zo(M.type,this._map,M))}touchstart(M){return this._firePreventable(new Ao(M.type,this._map,M))}touchmove(M){this._map.fire(new Ao(M.type,this._map,M))}touchend(M){this._map.fire(new Ao(M.type,this._map,M))}touchcancel(M){this._map.fire(new Ao(M.type,this._map,M))}_firePreventable(M){if(this._map.fire(M),M.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Fo{constructor(M){this._map=M}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent}mousemove(M){this._map.fire(new zo(M.type,this._map,M))}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new zo("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(M){this._delayContextMenu?this._contextMenuEvent=M:this._ignoreContextMenu||this._map.fire(new zo(M.type,this._map,M)),this._map.listens("contextmenu")&&M.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Bo{constructor(M){this._map=M}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return{lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(M){return this.transform.screenPointToLocation(et.P.convert(M),this._map.terrain)}}class jo{constructor(M,et){this._map=M,this._tr=new Bo(M),this._el=M.getCanvasContainer(),this._container=M.getContainer(),this._clickTolerance=et.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(M,et){this.isEnabled()&&M.shiftKey&&0===M.button&&(n.disableDrag(),this._startPos=this._lastPos=et,this._active=!0)}mousemoveWindow(M,et){if(!this._active)return;const Bt=et;if(this._lastPos.equals(Bt)||!this._box&&Bt.dist(this._startPos)M.fitScreenCoordinates(Wt,Nt,this._tr.bearing,{linear:!0})};this._fireEvent("boxzoomcancel",M)}keydown(M){this._active&&27===M.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",M))}reset(){this._active=!1,this._container.classList.remove("maplibregl-crosshair"),this._box&&(n.remove(this._box),this._box=null),n.enableDrag(),delete this._startPos,delete this._lastPos}_fireEvent(M,Bt){return this._map.fire(new et.k(M,{originalEvent:Bt}))}}function Oo(M,et){if(M.length!==et.length)throw new Error(`The number of touches and points are not equal - touches ${M.length}, points ${et.length}`);const Bt={};for(let Wt=0;Wtthis.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=M.timeStamp),Wt.length===this.numTouches&&(this.centroid=function(M){const Bt=new et.P(0,0);for(const et of M)Bt._add(et);return Bt.div(M.length)}(Bt),this.touches=Oo(Wt,Bt)))}touchmove(M,et,Bt){if(this.aborted||!this.centroid)return;const Wt=Oo(Bt,et);for(const M in this.touches){const et=Wt[M];(!et||et.dist(this.touches[M])>30)&&(this.aborted=!0)}}touchend(M,et,Bt){if((!this.centroid||M.timeStamp-this.startTime>500)&&(this.aborted=!0),0===Bt.length){const M=!this.aborted&&this.centroid;if(this.reset(),M)return M}}}class Zo{constructor(M){this.singleTap=new No(M),this.numTaps=M.numTaps,this.reset()}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset()}touchstart(M,et,Bt){this.singleTap.touchstart(M,et,Bt)}touchmove(M,et,Bt){this.singleTap.touchmove(M,et,Bt)}touchend(M,et,Bt){const Wt=this.singleTap.touchend(M,et,Bt);if(Wt){const et=M.timeStamp-this.lastTime<500,Bt=!this.lastTap||this.lastTap.dist(Wt)<30;if(et&&Bt||this.reset(),this.count++,this.lastTime=M.timeStamp,this.lastTap=Wt,this.count===this.numTaps)return this.reset(),Wt}}}class Go{constructor(M){this._tr=new Bo(M),this._zoomIn=new Zo({numTouches:1,numTaps:2}),this._zoomOut=new Zo({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(M,et,Bt){this._zoomIn.touchstart(M,et,Bt),this._zoomOut.touchstart(M,et,Bt)}touchmove(M,et,Bt){this._zoomIn.touchmove(M,et,Bt),this._zoomOut.touchmove(M,et,Bt)}touchend(M,et,Bt){const Wt=this._zoomIn.touchend(M,et,Bt),Nt=this._zoomOut.touchend(M,et,Bt),$t=this._tr;return Wt?(this._active=!0,M.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:et=>et.easeTo({duration:300,zoom:$t.zoom+1,around:$t.unproject(Wt)},{originalEvent:M})}):Nt?(this._active=!0,M.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:et=>et.easeTo({duration:300,zoom:$t.zoom-1,around:$t.unproject(Nt)},{originalEvent:M})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class Uo{constructor(M){this._enabled=!!M.enable,this._moveStateManager=M.moveStateManager,this._clickTolerance=M.clickTolerance||1,this._moveFunction=M.move,this._activateOnStart=!!M.activateOnStart,M.assignEvents(this),this.reset()}reset(M){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(M)}_move(...M){const et=this._moveFunction(...M);if(et.bearingDelta||et.pitchDelta||et.rollDelta||et.around||et.panDelta)return this._active=!0,et}dragStart(M,et){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(M)&&(this._moveStateManager.startMove(M),this._lastPoint=Array.isArray(et)?et[0]:et,this._activateOnStart&&this._lastPoint&&(this._active=!0))}dragMove(M,et){if(!this.isEnabled())return;const Bt=this._lastPoint;if(!Bt)return;if(M.preventDefault(),!this._moveStateManager.isValidMoveEvent(M))return void this.reset(M);const Wt=Array.isArray(et)?et[0]:et;return!this._moved&&Wt.dist(Bt)!0}),et=new Ho){this.mouseMoveStateManager=M,this.oneFingerTouchMoveStateManager=et}_executeRelevantHandler(M,et,Bt){return M instanceof MouseEvent?et(M):"undefined"!=typeof TouchEvent&&M instanceof TouchEvent?Bt(M):void 0}startMove(M){this._executeRelevantHandler(M,(M=>this.mouseMoveStateManager.startMove(M)),(M=>this.oneFingerTouchMoveStateManager.startMove(M)))}endMove(M){this._executeRelevantHandler(M,(M=>this.mouseMoveStateManager.endMove(M)),(M=>this.oneFingerTouchMoveStateManager.endMove(M)))}isValidStartEvent(M){return this._executeRelevantHandler(M,(M=>this.mouseMoveStateManager.isValidStartEvent(M)),(M=>this.oneFingerTouchMoveStateManager.isValidStartEvent(M)))}isValidMoveEvent(M){return this._executeRelevantHandler(M,(M=>this.mouseMoveStateManager.isValidMoveEvent(M)),(M=>this.oneFingerTouchMoveStateManager.isValidMoveEvent(M)))}isValidEndEvent(M){return this._executeRelevantHandler(M,(M=>this.mouseMoveStateManager.isValidEndEvent(M)),(M=>this.oneFingerTouchMoveStateManager.isValidEndEvent(M)))}}const Xo=M=>{M.mousedown=M.dragStart,M.mousemoveWindow=M.dragMove,M.mouseup=M.dragEnd,M.contextmenu=M=>{M.preventDefault()}};class $o{constructor(M,et){this._clickTolerance=M.clickTolerance||1,this._map=et,this.reset()}reset(){this._active=!1,this._touches={},this._sum=new et.P(0,0)}_shouldBePrevented(M){return M<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(M,et,Bt){return this._calculateTransform(M,et,Bt)}touchmove(M,et,Bt){if(this._active){if(!this._shouldBePrevented(Bt.length))return M.preventDefault(),this._calculateTransform(M,et,Bt);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",M)}}touchend(M,et,Bt){this._calculateTransform(M,et,Bt),this._active&&this._shouldBePrevented(Bt.length)&&this.reset()}touchcancel(){this.reset()}_calculateTransform(M,Bt,Wt){Wt.length>0&&(this._active=!0);const Nt=Oo(Wt,Bt),$t=new et.P(0,0),Gr=new et.P(0,0);let mn=0;for(const M in Nt){const et=Nt[M],Bt=this._touches[M];Bt&&($t._add(et),Gr._add(et.sub(Bt)),mn++,Nt[M]=et)}if(this._touches=Nt,this._shouldBePrevented(mn)||!Gr.mag())return;const Hn=Gr.div(mn);return this._sum._add(Hn),this._sum.mag()Math.abs(M.x)}class rs extends Ko{constructor(M){super(),this._currentTouchCount=0,this._map=M}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints}touchstart(M,et,Bt){super.touchstart(M,et,Bt),this._currentTouchCount=Bt.length}_start(M){this._lastPoints=M,is(M[0].sub(M[1]))&&(this._valid=!1)}_move(M,et,Bt){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;const Wt=M[0].sub(this._lastPoints[0]),Nt=M[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(Wt,Nt,Bt.timeStamp),this._valid?(this._lastPoints=M,this._active=!0,{pitchDelta:(Wt.y+Nt.y)/2*-.5}):void 0}gestureBeginsVertically(M,et,Bt){if(void 0!==this._valid)return this._valid;const Wt=M.mag()>=2,Nt=et.mag()>=2;if(!Wt&&!Nt)return;if(!Wt||!Nt)return void 0===this._firstMove&&(this._firstMove=Bt),Bt-this._firstMove<100&&void 0;const $t=M.y>0==et.y>0;return is(M)&&is(et)&&$t}}const Gh={panStep:100,bearingStep:15,pitchStep:10};class ss{constructor(M){this._tr=new Bo(M);const et=Gh;this._panStep=et.panStep,this._bearingStep=et.bearingStep,this._pitchStep=et.pitchStep,this._rotationDisabled=!1}reset(){this._active=!1}keydown(M){if(M.altKey||M.ctrlKey||M.metaKey)return;let et=0,Bt=0,Wt=0,Nt=0,$t=0;switch(M.keyCode){case 61:case 107:case 171:case 187:et=1;break;case 189:case 109:case 173:et=-1;break;case 37:M.shiftKey?Bt=-1:(M.preventDefault(),Nt=-1);break;case 39:M.shiftKey?Bt=1:(M.preventDefault(),Nt=1);break;case 38:M.shiftKey?Wt=1:(M.preventDefault(),$t=-1);break;case 40:M.shiftKey?Wt=-1:(M.preventDefault(),$t=1);break;default:return}return this._rotationDisabled&&(Bt=0,Wt=0),{cameraAnimation:Gr=>{const mn=this._tr;Gr.easeTo({duration:300,easeId:"keyboardHandler",easing:as,zoom:et?Math.round(mn.zoom)+et*(M.shiftKey?2:1):mn.zoom,bearing:mn.bearing+Bt*this._bearingStep,pitch:mn.pitch+Wt*this._pitchStep,offset:[-Nt*this._panStep,-$t*this._panStep],center:mn.center},{originalEvent:M})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0}enableRotation(){this._rotationDisabled=!1}}function as(M){return M*(2-M)}const Ph=4.000244140625;class ls{constructor(M,et){this._onTimeout=M=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(M)},this._map=M,this._tr=new Bo(M),this._triggerRenderFrame=et,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=.0022222222222222222}setZoomRate(M){this._defaultZoomRate=M}setWheelZoomRate(M){this._wheelZoomRate=M}isEnabled(){return!!this._enabled}isActive(){return!!this._active||void 0!==this._finishTimeout}isZooming(){return!!this._zooming}enable(M){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!M&&"center"===M.around)}disable(){this.isEnabled()&&(this._enabled=!1)}_shouldBePrevented(M){return!!this._map.cooperativeGestures.isEnabled()&&!(M.ctrlKey||this._map.cooperativeGestures.isBypassed(M))}wheel(M){if(!this.isEnabled())return;if(this._shouldBePrevented(M))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",M);let et=M.deltaMode===WheelEvent.DOM_DELTA_LINE?40*M.deltaY:M.deltaY;const Bt=$t.now(),Wt=Bt-(this._lastWheelEventTime||0);this._lastWheelEventTime=Bt,0!==et&&et%Ph==0?this._type="wheel":0!==et&&Math.abs(et)<4?this._type="trackpad":Wt>400?(this._type=null,this._lastValue=et,this._timeout=setTimeout(this._onTimeout,40,M)):this._type||(this._type=Math.abs(Wt*et)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,et+=this._lastValue)),M.shiftKey&&et&&(et/=4),this._type&&(this._lastWheelEvent=M,this._delta-=et,this._active||this._start(M)),M.preventDefault()}_start(M){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const Bt=n.mousePos(this._map.getCanvas(),M),Wt=this._tr;this._aroundPoint=this._aroundCenter?Wt.transform.locationToScreenPoint(et.N.convert(Wt.center)):Bt,this._frameId||(this._frameId=!0,this._triggerRenderFrame())}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const M=this._tr.transform;if("number"==typeof this._lastExpectedZoom){const et=M.zoom-this._lastExpectedZoom;"number"==typeof this._startZoom&&(this._startZoom+=et),"number"==typeof this._targetZoom&&(this._targetZoom+=et)}if(0!==this._delta){const Bt="wheel"===this._type&&Math.abs(this._delta)>Ph?this._wheelZoomRate:this._defaultZoomRate;let Wt=2/(1+Math.exp(-Math.abs(this._delta*Bt)));this._delta<0&&0!==Wt&&(Wt=1/Wt);const Nt="number"!=typeof this._targetZoom?M.scale:et.aG(this._targetZoom);this._targetZoom=Math.min(M.maxZoom,Math.max(M.minZoom,et.a8(Nt*Wt))),"wheel"===this._type&&(this._startZoom=M.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0}const Bt="number"!=typeof this._targetZoom?M.zoom:this._targetZoom,Wt=this._startZoom,Nt=this._easing;let Gr,mn=!1;if("wheel"===this._type&&Wt&&Nt){const M=$t.now()-this._lastWheelEventTime,Hn=Math.min((M+5)/200,1),so=Nt(Hn);Gr=et.y.number(Wt,Bt,so),Hn<1?this._frameId||(this._frameId=!0):mn=!0}else Gr=Bt,mn=!0;return this._active=!0,mn&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout}),200)),this._lastExpectedZoom=Gr,{noInertia:!0,needsRenderFrame:!mn,zoomDelta:Gr-M.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(M){let Bt=et.c8;if(this._prevEase){const M=this._prevEase,Wt=($t.now()-M.start)/M.duration,Nt=M.easing(Wt+.01)-M.easing(Wt),Gr=.27/Math.sqrt(Nt*Nt+1e-4)*.01,mn=Math.sqrt(.0729-Gr*Gr);Bt=et.c6(Gr,mn,.25,1)}return this._prevEase={start:$t.now(),duration:M,easing:Bt},Bt}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout)}}class cs{constructor(M,et){this._clickZoom=M,this._tapZoom=et}enable(){this._clickZoom.enable(),this._tapZoom.enable()}disable(){this._clickZoom.disable(),this._tapZoom.disable()}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class hs{constructor(M){this._tr=new Bo(M),this.reset()}reset(){this._active=!1}dblclick(M,et){return M.preventDefault(),{cameraAnimation:Bt=>{Bt.easeTo({duration:300,zoom:this._tr.zoom+(M.shiftKey?-1:1),around:this._tr.unproject(et)},{originalEvent:M})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class us{constructor(){this._tap=new Zo({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset()}touchstart(M,et,Bt){if(!this._swipePoint)if(this._tapTime){const Wt=et[0],Nt=M.timeStamp-this._tapTime<500,$t=this._tapPoint.dist(Wt)<30;Nt&&$t?Bt.length>0&&(this._swipePoint=Wt,this._swipeTouch=Bt[0].identifier):this.reset()}else this._tap.touchstart(M,et,Bt)}touchmove(M,et,Bt){if(this._tapTime){if(this._swipePoint){if(Bt[0].identifier!==this._swipeTouch)return;const Wt=et[0],Nt=Wt.y-this._swipePoint.y;return this._swipePoint=Wt,M.preventDefault(),this._active=!0,{zoomDelta:Nt/128}}}else this._tap.touchmove(M,et,Bt)}touchend(M,et,Bt){if(this._tapTime)this._swipePoint&&0===Bt.length&&this.reset();else{const Wt=this._tap.touchend(M,et,Bt);Wt&&(this._tapTime=M.timeStamp,this._tapPoint=Wt)}}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class ds{constructor(M,et,Bt){this._el=M,this._mousePan=et,this._touchPan=Bt}enable(M){this._inertiaOptions=M||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("maplibregl-touch-drag-pan")}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("maplibregl-touch-drag-pan")}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class _s{constructor(M,et,Bt,Wt){this._pitchWithRotate=M.pitchWithRotate,this._rollEnabled=M.rollEnabled,this._mouseRotate=et,this._mousePitch=Bt,this._mouseRoll=Wt}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable()}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class ps{constructor(M,et,Bt,Wt){this._el=M,this._touchZoom=et,this._touchRotate=Bt,this._tapDragZoom=Wt,this._rotationDisabled=!1,this._enabled=!0}enable(M){this._touchZoom.enable(M),this._rotationDisabled||this._touchRotate.enable(M),this._tapDragZoom.enable(),this._el.classList.add("maplibregl-touch-zoom-rotate")}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("maplibregl-touch-zoom-rotate")}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable()}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable()}}class ms{constructor(M,et){this._bypassKey=-1!==navigator.userAgent.indexOf("Mac")?"metaKey":"ctrlKey",this._map=M,this._options=et,this._enabled=!1}isActive(){return!1}reset(){}_setupUI(){if(this._container)return;const M=this._map.getCanvasContainer();M.classList.add("maplibregl-cooperative-gestures"),this._container=n.create("div","maplibregl-cooperative-gesture-screen",M);let et=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");"metaKey"===this._bypassKey&&(et=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));const Bt=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),Wt=document.createElement("div");Wt.className="maplibregl-desktop-message",Wt.textContent=et,this._container.appendChild(Wt);const Nt=document.createElement("div");Nt.className="maplibregl-mobile-message",Nt.textContent=Bt,this._container.appendChild(Nt),this._container.setAttribute("aria-hidden","true")}_destroyUI(){this._container&&(n.remove(this._container),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container}enable(){this._setupUI(),this._enabled=!0}disable(){this._enabled=!1,this._destroyUI()}isEnabled(){return this._enabled}isBypassed(M){return M[this._bypassKey]}notifyGestureBlocked(M,Bt){this._enabled&&(this._map.fire(new et.k("cooperativegestureprevented",{gestureType:M,originalEvent:Bt})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show")}),100))}}const fs=M=>M.zoom||M.drag||M.roll||M.pitch||M.rotate;class gs extends et.k{}function vs(M){return M.panDelta&&M.panDelta.mag()||M.zoomDelta||M.bearingDelta||M.pitchDelta||M.rollDelta}class xs{constructor(M,et){this.handleWindowEvent=M=>{this.handleEvent(M,`${M.type}Window`)},this.handleEvent=(M,et)=>{if("blur"===M.type)return void this.stop(!0);this._updatingCamera=!0;const Bt="renderFrame"===M.type?void 0:M,Wt={needsRenderFrame:!1},Nt={},$t={},Gr=M.touches,mn=Gr?this._getMapTouches(Gr):void 0,Hn=mn?n.touchPos(this._map.getCanvas(),mn):n.mousePos(this._map.getCanvas(),M);for(const{handlerName:Gr,handler:so,allowed:uo}of this._handlers){if(!so.isEnabled())continue;let Io;this._blockedByActive($t,uo,Gr)?so.reset():so[et||M.type]&&(Io=so[et||M.type](M,Hn,mn),this.mergeHandlerResult(Wt,Nt,Io,Gr,Bt),Io&&Io.needsRenderFrame&&this._triggerRenderFrame()),(Io||so.isActive())&&($t[Gr]=so)}const so={};for(const M in this._previousActiveHandlers)$t[M]||(so[M]=Bt);this._previousActiveHandlers=$t,(Object.keys(so).length||vs(Wt))&&(this._changes.push([Wt,Nt,so]),this._triggerRenderFrame()),(Object.keys($t).length||vs(Wt))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:uo}=Wt;uo&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],uo(this._map))},this._map=M,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new So(M),this._bearingSnap=et.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(et);const Bt=this._el;this._listeners=[[Bt,"touchstart",{passive:!0}],[Bt,"touchmove",{passive:!1}],[Bt,"touchend",void 0],[Bt,"touchcancel",void 0],[Bt,"mousedown",void 0],[Bt,"mousemove",void 0],[Bt,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[Bt,"mouseover",void 0],[Bt,"mouseout",void 0],[Bt,"dblclick",void 0],[Bt,"click",void 0],[Bt,"keydown",{capture:!1}],[Bt,"keyup",void 0],[Bt,"wheel",{passive:!1}],[Bt,"contextmenu",void 0],[window,"blur",void 0]];for(const[M,et,Bt]of this._listeners)n.addEventListener(M,et,M===document?this.handleWindowEvent:this.handleEvent,Bt)}destroy(){for(const[M,et,Bt]of this._listeners)n.removeEventListener(M,et,M===document?this.handleWindowEvent:this.handleEvent,Bt)}_addDefaultHandlers(M){const Bt=this._map,Wt=Bt.getCanvasContainer();this._add("mapEvent",new ko(Bt,M));const Nt=Bt.boxZoom=new jo(Bt,M);this._add("boxZoom",Nt),M.interactive&&M.boxZoom&&Nt.enable();const $t=Bt.cooperativeGestures=new ms(Bt,M.cooperativeGestures);this._add("cooperativeGestures",$t),M.cooperativeGestures&&$t.enable();const Gr=new Go(Bt),mn=new hs(Bt);Bt.doubleClickZoom=new cs(mn,Gr),this._add("tapZoom",Gr),this._add("clickZoom",mn),M.interactive&&M.doubleClickZoom&&Bt.doubleClickZoom.enable();const Hn=new us;this._add("tapDragZoom",Hn);const so=Bt.touchPitch=new rs(Bt);this._add("touchPitch",so),M.interactive&&M.touchPitch&&Bt.touchPitch.enable(M.touchPitch);const u=()=>Bt.project(Bt.getCenter()),uo=function({enable:M,clickTolerance:Bt,aroundCenter:Wt=!0,minPixelCenterThreshold:Nt=100,rotateDegreesPerPixelMoved:$t=.8},Gr){const mn=new qo({checkCorrectEvent:M=>0===n.mouseButton(M)&&M.ctrlKey||2===n.mouseButton(M)&&!M.ctrlKey});return new Uo({clickTolerance:Bt,move:(M,Bt)=>{const mn=Gr();if(Wt&&Math.abs(mn.y-M.y)>Nt)return{bearingDelta:et.c7(new et.P(M.x,Bt.y),Bt,mn)};let Hn=(Bt.x-M.x)*$t;return Wt&&Bt.y0===n.mouseButton(M)&&M.ctrlKey||2===n.mouseButton(M)});return new Uo({clickTolerance:et,move:(M,et)=>({pitchDelta:(et.y-M.y)*Bt}),moveStateManager:Wt,enable:M,assignEvents:Xo})}(M),Po=function({enable:M,clickTolerance:et,rollDegreesPerPixelMoved:Bt=.3},Wt){const Nt=new qo({checkCorrectEvent:M=>2===n.mouseButton(M)&&M.ctrlKey});return new Uo({clickTolerance:et,move:(M,et)=>{const Nt=Wt();let $t=(et.x-M.x)*Bt;return et.y0===n.mouseButton(M)&&!M.ctrlKey});return new Uo({clickTolerance:et,move:(M,et)=>({around:et,panDelta:et.sub(M)}),activateOnStart:!0,moveStateManager:Bt,enable:M,assignEvents:Xo})}(M),Eo=new $o(M,Bt);Bt.dragPan=new ds(Wt,To,Eo),this._add("mousePan",To),this._add("touchPan",Eo,["touchZoom","touchRotate"]),M.interactive&&M.dragPan&&Bt.dragPan.enable(M.dragPan);const Ia=new ts,Ba=new Qo;Bt.touchZoomRotate=new ps(Wt,Ba,Ia,Hn),this._add("touchRotate",Ia,["touchPan","touchZoom"]),this._add("touchZoom",Ba,["touchPan","touchRotate"]),M.interactive&&M.touchZoomRotate&&Bt.touchZoomRotate.enable(M.touchZoomRotate);const Ta=Bt.scrollZoom=new ls(Bt,(()=>this._triggerRenderFrame()));this._add("scrollZoom",Ta,["mousePan"]),M.interactive&&M.scrollZoom&&Bt.scrollZoom.enable(M.scrollZoom);const Va=Bt.keyboard=new ss(Bt);this._add("keyboard",Va),M.interactive&&M.keyboard&&Bt.keyboard.enable(),this._add("blockableMapEvent",new Fo(Bt))}_add(M,et,Bt){this._handlers.push({handlerName:M,handler:et,allowed:Bt}),this._handlersById[M]=et}stop(M){if(!this._updatingCamera){for(const{handler:M}of this._handlers)M.reset();this._inertia.clear(),this._fireEvents({},{},M),this._changes=[]}}isActive(){for(const{handler:M}of this._handlers)if(M.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return Boolean(fs(this._eventsInProgress))||this.isZooming()}_blockedByActive(M,et,Bt){for(const Wt in M)if(Wt!==Bt&&(!et||et.indexOf(Wt)<0))return!0;return!1}_getMapTouches(M){const et=[];for(const Bt of M)this._el.contains(Bt.target)&&et.push(Bt);return et}mergeHandlerResult(M,Bt,Wt,Nt,$t){if(!Wt)return;et.e(M,Wt);const Gr={handlerName:Nt,originalEvent:Wt.originalEvent||$t};void 0!==Wt.zoomDelta&&(Bt.zoom=Gr),void 0!==Wt.panDelta&&(Bt.drag=Gr),void 0!==Wt.rollDelta&&(Bt.roll=Gr),void 0!==Wt.pitchDelta&&(Bt.pitch=Gr),void 0!==Wt.bearingDelta&&(Bt.rotate=Gr)}_applyChanges(){const M={},Bt={},Wt={};for(const[Nt,$t,Gr]of this._changes)Nt.panDelta&&(M.panDelta=(M.panDelta||new et.P(0,0))._add(Nt.panDelta)),Nt.zoomDelta&&(M.zoomDelta=(M.zoomDelta||0)+Nt.zoomDelta),Nt.bearingDelta&&(M.bearingDelta=(M.bearingDelta||0)+Nt.bearingDelta),Nt.pitchDelta&&(M.pitchDelta=(M.pitchDelta||0)+Nt.pitchDelta),Nt.rollDelta&&(M.rollDelta=(M.rollDelta||0)+Nt.rollDelta),void 0!==Nt.around&&(M.around=Nt.around),void 0!==Nt.pinchAround&&(M.pinchAround=Nt.pinchAround),Nt.noInertia&&(M.noInertia=Nt.noInertia),et.e(Bt,$t),et.e(Wt,Gr);this._updateMapTransform(M,Bt,Wt),this._changes=[]}_updateMapTransform(M,et,Bt){const Wt=this._map,Nt=Wt._getTransformForUpdate(),$t=Wt.terrain;if(!(vs(M)||$t&&this._terrainMovement))return this._fireEvents(et,Bt,!0);Wt._stop(!0);let{panDelta:Gr,zoomDelta:mn,bearingDelta:Hn,pitchDelta:so,rollDelta:uo,around:Io,pinchAround:Po}=M;void 0!==Po&&(Io=Po),Io=Io||Wt.transform.centerPoint,$t&&!Nt.isPointOnMapSurface(Io)&&(Io=Nt.centerPoint);const To={panDelta:Gr,zoomDelta:mn,rollDelta:uo,pitchDelta:so,bearingDelta:Hn,around:Io};this._map.cameraHelper.useGlobeControls&&!Nt.isPointOnMapSurface(Io)&&(Io=Nt.centerPoint);const Eo=Io.distSqr(Nt.centerPoint)<.01?Nt.center:Nt.screenPointToLocation(Gr?Io.sub(Gr):Io);$t?(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(To,Nt),this._terrainMovement||!et.drag&&!et.zoom?et.drag&&this._terrainMovement?Nt.setCenter(Nt.screenPointToLocation(Nt.centerPoint.sub(Gr))):this._map.cameraHelper.handleMapControlsPan(To,Nt,Eo):(this._terrainMovement=!0,this._map._elevationFreeze=!0,this._map.cameraHelper.handleMapControlsPan(To,Nt,Eo))):(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(To,Nt),this._map.cameraHelper.handleMapControlsPan(To,Nt,Eo)),Wt._applyUpdatedTransform(Nt),this._map._update(),M.noInertia||this._inertia.record(M),this._fireEvents(et,Bt,!0)}_fireEvents(M,Bt,Wt){const Nt=fs(this._eventsInProgress),Gr=fs(M),mn={};for(const et in M){const{originalEvent:Bt}=M[et];this._eventsInProgress[et]||(mn[`${et}start`]=Bt),this._eventsInProgress[et]=M[et]}!Nt&&Gr&&this._fireEvent("movestart",Gr.originalEvent);for(const M in mn)this._fireEvent(M,mn[M]);Gr&&this._fireEvent("move",Gr.originalEvent);for(const et in M){const{originalEvent:Bt}=M[et];this._fireEvent(et,Bt)}const Hn={};let so;for(const M in this._eventsInProgress){const{handlerName:et,originalEvent:Wt}=this._eventsInProgress[M];this._handlersById[et].isActive()||(delete this._eventsInProgress[M],so=Bt[et]||Wt,Hn[`${M}end`]=so)}for(const M in Hn)this._fireEvent(M,Hn[M]);const uo=fs(this._eventsInProgress),Io=(Nt||Gr)&&!uo;if(Io&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;const M=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&M.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(M)}if(Wt&&Io){this._updatingCamera=!0;const M=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),i=M=>0!==M&&-this._bearingSnap{delete this._frameId,this.handleEvent(new gs("renderFrame",{timeStamp:M})),this._applyChanges()}))}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame())}}class bs extends et.E{constructor(M,et,Bt){super(),this._renderFrameCallback=()=>{const M=Math.min(($t.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(M)),M<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()},this._moving=!1,this._zooming=!1,this.transform=M,this._bearingSnap=Bt.bearingSnap,this.cameraHelper=et,this.on("moveend",(()=>{delete this._requestedCameraState}))}migrateProjection(M,et){M.apply(this.transform),this.transform=M,this.cameraHelper=et}getCenter(){return new et.N(this.transform.center.lng,this.transform.center.lat)}setCenter(M,et){return this.jumpTo({center:M},et)}getCenterElevation(){return this.transform.elevation}setCenterElevation(M,et){return this.jumpTo({elevation:M},et),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(M){this._centerClampedToGround=M}panBy(M,Bt,Wt){return M=et.P.convert(M).mult(-1),this.panTo(this.transform.center,et.e({offset:M},Bt),Wt)}panTo(M,Bt,Wt){return this.easeTo(et.e({center:M},Bt),Wt)}getZoom(){return this.transform.zoom}setZoom(M,et){return this.jumpTo({zoom:M},et),this}zoomTo(M,Bt,Wt){return this.easeTo(et.e({zoom:M},Bt),Wt)}zoomIn(M,et){return this.zoomTo(this.getZoom()+1,M,et),this}zoomOut(M,et){return this.zoomTo(this.getZoom()-1,M,et),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(M,Bt){return M!=this.transform.fov&&(this.transform.setFov(M),this.fire(new et.k("movestart",Bt)).fire(new et.k("move",Bt)).fire(new et.k("moveend",Bt))),this}getBearing(){return this.transform.bearing}setBearing(M,et){return this.jumpTo({bearing:M},et),this}getPadding(){return this.transform.padding}setPadding(M,et){return this.jumpTo({padding:M},et),this}rotateTo(M,Bt,Wt){return this.easeTo(et.e({bearing:M},Bt),Wt)}resetNorth(M,Bt){return this.rotateTo(0,et.e({duration:1e3},M),Bt),this}resetNorthPitch(M,Bt){return this.easeTo(et.e({bearing:0,pitch:0,roll:0,duration:1e3},M),Bt),this}snapToNorth(M,et){return Math.abs(this.getBearing()){Ba.easeFunc(et),this.terrain&&!M.freezeElevation&&this._updateElevation(et),this._applyUpdatedTransform(Wt),this._fireMoveEvents(Bt)}),(et=>{this.terrain&&M.freezeElevation&&this._finalizeElevation(),this._afterEase(Bt,et)}),M),this}_prepareEase(M,Bt,Wt={}){this._moving=!0,Bt||Wt.moving||this.fire(new et.k("movestart",M)),this._zooming&&!Wt.zooming&&this.fire(new et.k("zoomstart",M)),this._rotating&&!Wt.rotating&&this.fire(new et.k("rotatestart",M)),this._pitching&&!Wt.pitching&&this.fire(new et.k("pitchstart",M)),this._rolling&&!Wt.rolling&&this.fire(new et.k("rollstart",M))}_prepareElevation(M){this._elevationCenter=M,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(M,this.transform.tileZoom),this._elevationFreeze=!0}_updateElevation(M){this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));const Bt=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(M<1&&Bt!==this._elevationTarget){const et=this._elevationTarget-this._elevationStart;this._elevationStart+=M*(et-(Bt-(et*M+this._elevationStart))/(1-M)),this._elevationTarget=Bt}this.transform.setElevation(et.y.number(this._elevationStart,this._elevationTarget,M))}_finalizeElevation(){this._elevationFreeze=!1,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain)}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(M){if(!this.terrain&&M.elevation>=0&&M.pitch<=90)return{};const et=M.getCameraLngLat(),Bt=M.getCameraAltitude(),Wt=this.terrain?this.terrain.getElevationForLngLatZoom(et,M.zoom):0;if(Btthis._elevateCameraIfInsideTerrain(M))),this.transformCameraUpdate&&et.push((M=>this.transformCameraUpdate(M))),!et.length)return;const Bt=M.clone();for(const M of et){const et=Bt.clone(),{center:Wt,zoom:Nt,roll:$t,pitch:Gr,bearing:mn,elevation:Hn}=M(et);Wt&&et.setCenter(Wt),void 0!==Hn&&et.setElevation(Hn),void 0!==Nt&&et.setZoom(Nt),void 0!==$t&&et.setRoll($t),void 0!==Gr&&et.setPitch(Gr),void 0!==mn&&et.setBearing(mn),Bt.apply(et)}this.transform.apply(Bt)}_fireMoveEvents(M){this.fire(new et.k("move",M)),this._zooming&&this.fire(new et.k("zoom",M)),this._rotating&&this.fire(new et.k("rotate",M)),this._pitching&&this.fire(new et.k("pitch",M)),this._rolling&&this.fire(new et.k("roll",M))}_afterEase(M,Bt){if(this._easeId&&Bt&&this._easeId===Bt)return;delete this._easeId;const Wt=this._zooming,Nt=this._rotating,$t=this._pitching,Gr=this._rolling;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._rolling=!1,this._padding=!1,Wt&&this.fire(new et.k("zoomend",M)),Nt&&this.fire(new et.k("rotateend",M)),$t&&this.fire(new et.k("pitchend",M)),Gr&&this.fire(new et.k("rollend",M)),this.fire(new et.k("moveend",M))}flyTo(M,Bt){if(!M.essential&&$t.prefersReducedMotion){const Wt=et.M(M,["center","zoom","bearing","pitch","roll","elevation"]);return this.jumpTo(Wt,Bt)}this.stop(),M=et.e({offset:[0,0],speed:1.2,curve:1.42,easing:et.c8},M);const Wt=this._getTransformForUpdate(),Nt=Wt.bearing,Gr=Wt.pitch,mn=Wt.roll,Hn=Wt.padding,so="bearing"in M?this._normalizeBearing(M.bearing,Nt):Nt,uo="pitch"in M?+M.pitch:Gr,Io="roll"in M?this._normalizeBearing(M.roll,mn):mn,Po="padding"in M?M.padding:Wt.padding,To=et.P.convert(M.offset);let Eo=Wt.centerPoint.add(To);const Ia=Wt.screenPointToLocation(Eo),Ba=this.cameraHelper.handleFlyTo(Wt,{bearing:so,pitch:uo,roll:Io,padding:Po,locationAtOffset:Ia,offsetAsPoint:To,center:M.center,minZoom:M.minZoom,zoom:M.zoom});let Ta=M.curve;const Va=Math.max(Wt.width,Wt.height),za=Va/Ba.scaleOfZoom,Fa=Ba.pixelPathLength;"number"==typeof Ba.scaleOfMinZoom&&(Ta=Math.sqrt(Va/Ba.scaleOfMinZoom/Fa*2));const Ea=Ta*Ta;function w(M){const et=(za*za-Va*Va+(M?-1:1)*Ea*Ea*Fa*Fa)/(2*(M?za:Va)*Ea*Fa);return Math.log(Math.sqrt(et*et+1)-et)}function T(M){return(Math.exp(M)-Math.exp(-M))/2}function P(M){return(Math.exp(M)+Math.exp(-M))/2}const La=w(!1);let I=function(M){return P(La)/P(La+Ta*M)},E=function(M){return Va*((P(La)*(T(et=La+Ta*M)/P(et))-T(La))/Ea)/Fa;var et},Da=(w(!0)-La)/Ta;if(Math.abs(Fa)<2e-6||!isFinite(Da)){if(Math.abs(Va-za)<1e-6)return this.easeTo(M,Bt);const et=za0,I=M=>Math.exp(et*Ta*M)}return M.duration="duration"in M?+M.duration:1e3*Da/("screenSpeed"in M?+M.screenSpeed/Ta:+M.speed),M.maxDuration&&M.duration>M.maxDuration&&(M.duration=0),this._zooming=!0,this._rotating=Nt!==so,this._pitching=uo!==Gr,this._rolling=Io!==mn,this._padding=!Wt.isPaddingEqual(Po),this._prepareEase(Bt,!1),this.terrain&&this._prepareElevation(Ba.targetCenter),this._ease(($t=>{const Ia=$t*Da,Ta=1/I(Ia),Va=E(Ia);this._rotating&&Wt.setBearing(et.y.number(Nt,so,$t)),this._pitching&&Wt.setPitch(et.y.number(Gr,uo,$t)),this._rolling&&Wt.setRoll(et.y.number(mn,Io,$t)),this._padding&&(Wt.interpolatePadding(Hn,Po,$t),Eo=Wt.centerPoint.add(To)),Ba.easeFunc($t,Ta,Va,Eo),this.terrain&&!M.freezeElevation&&this._updateElevation($t),this._applyUpdatedTransform(Wt),this._fireMoveEvents(Bt)}),(()=>{this.terrain&&M.freezeElevation&&this._finalizeElevation(),this._afterEase(Bt)}),M),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_stop(M,et){var Bt;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){const M=this._onEaseEnd;delete this._onEaseEnd,M.call(this,et)}return M||null===(Bt=this.handlers)||void 0===Bt||Bt.stop(!1),this}_ease(M,et,Bt){!1===Bt.animate||0===Bt.duration?(M(1),et()):(this._easeStart=$t.now(),this._easeOptions=Bt,this._onEaseFrame=M,this._onEaseEnd=et,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_normalizeBearing(M,Bt){M=et.aI(M,-180,180);const Wt=Math.abs(M-Bt);return Math.abs(M-360-Bt)MapLibre'};class ws{constructor(M=Wh){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")))},this._updateData=M=>{!M||"metadata"!==M.sourceDataType&&"visibility"!==M.sourceDataType&&"style"!==M.dataType&&"terrain"!==M.type||this._updateAttributions()},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1===this._compact?this._container.setAttribute("open",""):this._container.classList.contains("maplibregl-compact")||this._container.classList.contains("maplibregl-attrib-empty")||(this._container.setAttribute("open",""),this._container.classList.add("maplibregl-compact","maplibregl-compact-show")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"))},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show")},this.options=M}getDefaultPosition(){return"bottom-right"}onAdd(M){return this._map=M,this._compact=this.options.compact,this._container=n.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=n.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=n.create("div","maplibregl-ctrl-attrib-inner",this._container),this._updateAttributions(),this._updateCompact(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("terrain",this._updateData),this._map.on("resize",this._updateCompact),this._map.on("drag",this._updateCompactMinimize),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("terrain",this._updateData),this._map.off("resize",this._updateCompact),this._map.off("drag",this._updateCompactMinimize),this._map=void 0,this._compact=void 0,this._sanitizedAttributionHTML=void 0}_setElementTitle(M,et){const Bt=this._map._getUIString(`AttributionControl.${et}`);M.title=Bt,M.setAttribute("aria-label",Bt)}_updateAttributions(){if(!this._map.style)return;let M=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?M=M.concat(this.options.customAttribution.map((M=>"string"!=typeof M?"":M))):"string"==typeof this.options.customAttribution&&M.push(this.options.customAttribution)),this._map.style.stylesheet){const M=this._map.style.stylesheet;this.styleOwner=M.owner,this.styleId=M.id}const et=this._map.style.sourceCaches;for(const Bt in et){const Wt=et[Bt];if(Wt.used||Wt.usedForTerrain){const et=Wt.getSource();et.attribution&&M.indexOf(et.attribution)<0&&M.push(et.attribution)}}M=M.filter((M=>String(M).trim())),M.sort(((M,et)=>M.length-et.length)),M=M.filter(((et,Bt)=>{for(let Wt=Bt+1;Wt=0)return!1;return!0}));const Bt=M.join(" | ");Bt!==this._sanitizedAttributionHTML&&(this._sanitizedAttributionHTML=n.sanitize(Bt),M.length?(this._innerContainer.innerHTML=this._sanitizedAttributionHTML,this._container.classList.remove("maplibregl-attrib-empty")):this._container.classList.add("maplibregl-attrib-empty"),this._updateCompact(),this._editLink=null)}}class Ts{constructor(M={}){this._updateCompact=()=>{const M=this._container.children;if(M.length){const et=M[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1!==this._compact&&et.classList.add("maplibregl-compact"):et.classList.remove("maplibregl-compact")}},this.options=M}getDefaultPosition(){return"bottom-left"}onAdd(M){this._map=M,this._compact=this.options&&this.options.compact,this._container=n.create("div","maplibregl-ctrl");const et=n.create("a","maplibregl-ctrl-logo");return et.target="_blank",et.rel="noopener nofollow",et.href="https://maplibre.org/",et.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),et.setAttribute("rel","noopener nofollow"),this._container.appendChild(et),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){n.remove(this._container),this._map.off("resize",this._updateCompact),this._map=void 0,this._compact=void 0}}class Ps{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(M){const et=++this._id;return this._queue.push({callback:M,id:et,cancelled:!1}),et}remove(M){const et=this._currentlyRunning,Bt=et?this._queue.concat(et):this._queue;for(const et of Bt)if(et.id===M)return void(et.cancelled=!0)}run(M=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const et=this._currentlyRunning=this._queue;this._queue=[];for(const Bt of et)if(!Bt.cancelled&&(Bt.callback(M),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}var zh=et.aA([{name:"a_pos3d",type:"Int16",components:3}]);class Is extends et.E{constructor(M){super(),this._lastTilesetChange=$t.now(),this.sourceCache=M,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=M._source.tileSize*2**this.deltaZoom,M.usedForTerrain=!0,M.tileSize=this.tileSize}destruct(){this.sourceCache.usedForTerrain=!1,this.sourceCache.tileSize=null}update(M,Bt){this.sourceCache.update(M,Bt),this._renderableTilesKeys=[];const Wt={};for(const Nt of ue(M,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:Bt,calculateTileZoom:this.sourceCache._source.calculateTileZoom}))Wt[Nt.key]=!0,this._renderableTilesKeys.push(Nt.key),this._tiles[Nt.key]||(Nt.terrainRttPosMatrix32f=new Float64Array(16),et.bL(Nt.terrainRttPosMatrix32f,0,et.X,et.X,0,0,1),this._tiles[Nt.key]=new se(Nt,this.tileSize),this._lastTilesetChange=$t.now());for(const M in this._tiles)Wt[M]||delete this._tiles[M]}freeRtt(M){for(const et in this._tiles){const Bt=this._tiles[et];(!M||Bt.tileID.equals(M)||Bt.tileID.isChildOf(M)||M.isChildOf(Bt.tileID))&&(Bt.rtt=[])}}getRenderableTiles(){return this._renderableTilesKeys.map((M=>this.getTileByID(M)))}getTileByID(M){return this._tiles[M]}getTerrainCoords(M){const Bt={};for(const Wt of this._renderableTilesKeys){const Nt=this._tiles[Wt].tileID,$t=M.clone(),Gr=et.a$();if(Nt.canonical.equals(M.canonical))et.bL(Gr,0,et.X,et.X,0,0,1);else if(Nt.canonical.isChildOf(M.canonical)){const Bt=Nt.canonical.z-M.canonical.z,Wt=Nt.canonical.x-(Nt.canonical.x>>Bt<>Bt<>Bt;et.bL(Gr,0,mn,mn,0,0,1),et.J(Gr,Gr,[-Wt*mn,-$t*mn,0])}else{if(!M.canonical.isChildOf(Nt.canonical))continue;{const Bt=M.canonical.z-Nt.canonical.z,Wt=M.canonical.x-(M.canonical.x>>Bt<>Bt<>Bt;et.bL(Gr,0,et.X,et.X,0,0,1),et.J(Gr,Gr,[Wt*mn,$t*mn,0]),et.K(Gr,Gr,[1/2**Bt,1/2**Bt,0])}}$t.terrainRttPosMatrix32f=new Float32Array(Gr),Bt[Wt]=$t}return Bt}getSourceTile(M,et){const Bt=this.sourceCache._source;let Wt=M.overscaledZ-this.deltaZoom;if(Wt>Bt.maxzoom&&(Wt=Bt.maxzoom),Wt=Bt.minzoom&&(!Nt||!Nt.dem);)Nt=this.sourceCache.getTileByID(M.scaledTo(Wt--).key);return Nt}anyTilesAfterTime(M=Date.now()){return this._lastTilesetChange>=M}}class Es{constructor(M,et,Bt){this._meshCache={},this.painter=M,this.sourceCache=new Is(et),this.options=Bt,this.exaggeration="number"==typeof Bt.exaggeration?Bt.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024}getDEMElevation(M,Bt,Wt,Nt=et.X){var $t;if(!(Bt>=0&&Bt=0&&WtM.canonical.z&&(M.canonical.z>=Wt?Nt=M.canonical.z-Wt:et.w("cannot calculate elevation if elevation maxzoom > source.maxzoom"));const $t=M.canonical.x-(M.canonical.x>>Nt<>Nt<>8<<4|M>>8,Bt[et+3]=0;const Wt=new et.R({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(Bt.buffer)),Nt=new v(M,Wt,M.gl.RGBA,{premultiply:!1});return Nt.bind(M.gl.NEAREST,M.gl.CLAMP_TO_EDGE),this._coordsTexture=Nt,Nt}pointCoordinate(M){this.painter.maybeDrawDepthAndCoords(!0);const Bt=new Uint8Array(4),Wt=this.painter.context,Nt=Wt.gl,$t=Math.round(M.x*this.painter.pixelRatio/devicePixelRatio),Gr=Math.round(M.y*this.painter.pixelRatio/devicePixelRatio),mn=Math.round(this.painter.height/devicePixelRatio);Wt.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),Nt.readPixels($t,mn-Gr-1,1,1,Nt.RGBA,Nt.UNSIGNED_BYTE,Bt),Wt.bindFramebuffer.set(null);const Hn=Bt[0]+(Bt[2]>>4<<8),so=Bt[1]+((15&Bt[2])<<8),uo=this.coordsIndex[255-Bt[3]],Io=uo&&this.sourceCache.getTileByID(uo);if(!Io)return null;const Po=this._coordsTextureSize,To=(1<0,Nt=Wt&&0===M.canonical.y,$t=Wt&&M.canonical.y===(1<M.id!==et)),this._recentlyUsed.push(M.id)}stampObject(M){M.stamp=++this._stamp}getOrCreateFreeObject(){for(const M of this._recentlyUsed)if(!this._objects[M].inUse)return this._objects[M];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const M=this._createObject(this._objects.length);return this._objects.push(M),M}freeObject(M){M.inUse=!1}freeAllObjects(){for(const M of this._objects)this.freeObject(M)}isFull(){return!(this._objects.length!M.inUse))}}const Jh={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0};class Rs{constructor(M,et){this.painter=M,this.terrain=et,this.pool=new Ms(M.context,30,et.sourceCache.tileSize*et.qualityFactor)}destruct(){this.pool.destruct()}getTexture(M){return this.pool.getObjectForId(M.rtt[this._stacks.length-1].id).texture}prepareForRender(M,et){this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.sourceCache.getRenderableTiles(),this._renderableLayerIds=M._order.filter((Bt=>!M._layers[Bt].isHidden(et))),this._coordsAscending={};for(const et in M.sourceCaches){this._coordsAscending[et]={};const Bt=M.sourceCaches[et].getVisibleCoordinates();for(const M of Bt){const Bt=this.terrain.sourceCache.getTerrainCoords(M);for(const M in Bt)this._coordsAscending[et][M]||(this._coordsAscending[et][M]=[]),this._coordsAscending[et][M].push(Bt[M])}}this._coordsAscendingStr={};for(const et of M._order){const Bt=M._layers[et],Wt=Bt.source;if(Jh[Bt.type]&&!this._coordsAscendingStr[Wt]){this._coordsAscendingStr[Wt]={};for(const M in this._coordsAscending[Wt])this._coordsAscendingStr[Wt][M]=this._coordsAscending[Wt][M].map((M=>M.key)).sort().join()}}for(const M of this._renderableTiles)for(const et in this._coordsAscendingStr){const Bt=this._coordsAscendingStr[et][M.tileID.key];Bt&&Bt!==M.rttCoords[et]&&(M.rtt=[])}}renderLayer(M,Bt){if(M.isHidden(this.painter.transform.zoom))return!1;const Wt=Object.assign(Object.assign({},Bt),{isRenderingToTexture:!0}),Nt=M.type,$t=this.painter,Gr=this._renderableLayerIds[this._renderableLayerIds.length-1]===M.id;if(Jh[Nt]&&(this._prevType&&Jh[this._prevType]||this._stacks.push([]),this._prevType=Nt,this._stacks[this._stacks.length-1].push(M.id),!Gr))return!0;if(Jh[this._prevType]||Jh[Nt]&&Gr){this._prevType=Nt;const M=this._stacks.length-1,Bt=this._stacks[M]||[];for(const Nt of this._renderableTiles){if(this.pool.isFull()&&(vo(this.painter,this.terrain,this._rttTiles,Wt),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(Nt),Nt.rtt[M]){const et=this.pool.getObjectForId(Nt.rtt[M].id);if(et.stamp===Nt.rtt[M].stamp){this.pool.useObject(et);continue}}const Gr=this.pool.getOrCreateFreeObject();this.pool.useObject(Gr),this.pool.stampObject(Gr),Nt.rtt[M]={id:Gr.id,stamp:Gr.stamp},$t.context.bindFramebuffer.set(Gr.fbo.framebuffer),$t.context.clear({color:et.b4.transparent,stencil:0}),$t.currentStencilSource=void 0;for(let M=0;M{this.startMove(M,n.mousePos(this.element,M)),n.addEventListener(window,"mousemove",this.mousemove),n.addEventListener(window,"mouseup",this.mouseup)},this.mousemove=M=>{this.move(M,n.mousePos(this.element,M))},this.mouseup=M=>{this._rotatePitchHanlder.dragEnd(M),this.offTemp()},this.touchstart=M=>{1!==M.targetTouches.length?this.reset():(this._startPos=this._lastPos=n.touchPos(this.element,M.targetTouches)[0],this.startMove(M,this._startPos),n.addEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.addEventListener(window,"touchend",this.touchend))},this.touchmove=M=>{1!==M.targetTouches.length?this.reset():(this._lastPos=n.touchPos(this.element,M.targetTouches)[0],this.move(M,this._lastPos))},this.touchend=M=>{0===M.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this._rotatePitchHanlder.reset(),delete this._startPos,delete this._lastPos,this.offTemp()},this._clickTolerance=10,this.element=Bt;const Nt=new Wo;this._rotatePitchHanlder=new Uo({clickTolerance:3,move:(M,Nt)=>{const $t=Bt.getBoundingClientRect(),Gr=new et.P(($t.bottom-$t.top)/2,($t.right-$t.left)/2);return{bearingDelta:et.c7(new et.P(M.x,Nt.y),Nt,Gr),pitchDelta:Wt?-.5*(Nt.y-M.y):void 0}},moveStateManager:Nt,enable:!0,assignEvents:()=>{}}),this.map=M,n.addEventListener(Bt,"mousedown",this.mousedown),n.addEventListener(Bt,"touchstart",this.touchstart,{passive:!1}),n.addEventListener(Bt,"touchcancel",this.reset)}startMove(M,et){this._rotatePitchHanlder.dragStart(M,et),n.disableDrag()}move(M,et){const Bt=this.map,{bearingDelta:Wt,pitchDelta:Nt}=this._rotatePitchHanlder.dragMove(M,et)||{};Wt&&Bt.setBearing(Bt.getBearing()+Wt),Nt&&Bt.setPitch(Bt.getPitch()+Nt)}off(){const M=this.element;n.removeEventListener(M,"mousedown",this.mousedown),n.removeEventListener(M,"touchstart",this.touchstart,{passive:!1}),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend),n.removeEventListener(M,"touchcancel",this.reset),this.offTemp()}offTemp(){n.enableDrag(),n.removeEventListener(window,"mousemove",this.mousemove),n.removeEventListener(window,"mouseup",this.mouseup),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend)}}let Yh;function Bs(M,Bt,Wt){const Nt=new et.N(M.lng,M.lat);if(M=new et.N(M.lng,M.lat),Bt){const Nt=new et.N(M.lng-360,M.lat),$t=new et.N(M.lng+360,M.lat),Gr=Wt.locationToScreenPoint(M).distSqr(Bt);Wt.locationToScreenPoint(Nt).distSqr(Bt)180;){const et=Wt.locationToScreenPoint(M);if(et.x>=0&&et.y>=0&&et.x<=Wt.width&&et.y<=Wt.height)break;M.lng>Wt.center.lng?M.lng-=360:M.lng+=360}return M.lng!==Nt.lng&&Wt.isPointOnMapSurface(Wt.locationToScreenPoint(M))?M:Nt}const Qh={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function Os(M,et,Bt){const Wt=M.classList;for(const M in Qh)Wt.remove(`maplibregl-${Bt}-anchor-${M}`);Wt.add(`maplibregl-${Bt}-anchor-${et}`)}class Ns extends et.E{constructor(M){if(super(),this._onKeyPress=M=>{const et=M.code,Bt=M.charCode||M.keyCode;"Space"!==et&&"Enter"!==et&&32!==Bt&&13!==Bt||this.togglePopup()},this._onMapClick=M=>{const et=M.originalEvent.target,Bt=this._element;this._popup&&(et===Bt||Bt.contains(et))&&this.togglePopup()},this._update=M=>{var et;if(!this._map)return;const Bt=this._map.loaded()&&!this._map.isMoving();("terrain"===(null==M?void 0:M.type)||"render"===(null==M?void 0:M.type)&&!Bt)&&this._map.once("render",this._update),this._lngLat=this._map.transform.renderWorldCopies?Bs(this._lngLat,this._flatPos,this._map.transform):null===(et=this._lngLat)||void 0===et?void 0:et.wrap(),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let Wt="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?Wt=`rotateZ(${this._rotation}deg)`:"map"===this._rotationAlignment&&(Wt=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let Nt="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?Nt="rotateX(0deg)":"map"===this._pitchAlignment&&(Nt=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||M&&"moveend"!==M.type||(this._pos=this._pos.round()),n.setTransform(this._element,`${Qh[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${Nt} ${Wt}`),$t.frameAsync(new AbortController).then((()=>{this._updateOpacity(M&&"moveend"===M.type)})).catch((()=>{}))},this._onMove=M=>{if(!this._isDragging){const et=this._clickTolerance||this._map._clickTolerance;this._isDragging=M.point.dist(this._pointerdownPos)>=et}this._isDragging&&(this._pos=M.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new et.k("dragstart"))),this.fire(new et.k("drag")))},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new et.k("dragend")),this._state="inactive"},this._addDragHandler=M=>{this._element.contains(M.originalEvent.target)&&(M.preventDefault(),this._positionDelta=M.point.sub(this._pos).add(this._offset),this._pointerdownPos=M.point,this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp))},this._anchor=M&&M.anchor||"center",this._color=M&&M.color||"#3FB1CE",this._scale=M&&M.scale||1,this._draggable=M&&M.draggable||!1,this._clickTolerance=M&&M.clickTolerance||0,this._subpixelPositioning=M&&M.subpixelPositioning||!1,this._isDragging=!1,this._state="inactive",this._rotation=M&&M.rotation||0,this._rotationAlignment=M&&M.rotationAlignment||"auto",this._pitchAlignment=M&&M.pitchAlignment&&"auto"!==M.pitchAlignment?M.pitchAlignment:this._rotationAlignment,this.setOpacity(),this.setOpacity(null==M?void 0:M.opacity,null==M?void 0:M.opacityWhenCovered),M&&M.element)this._element=M.element,this._offset=et.P.convert(M&&M.offset||[0,0]);else{this._defaultMarker=!0,this._element=n.create("div");const Bt=n.createNS("http://www.w3.org/2000/svg","svg"),Wt=41,Nt=27;Bt.setAttributeNS(null,"display","block"),Bt.setAttributeNS(null,"height",`${Wt}px`),Bt.setAttributeNS(null,"width",`${Nt}px`),Bt.setAttributeNS(null,"viewBox",`0 0 ${Nt} ${Wt}`);const $t=n.createNS("http://www.w3.org/2000/svg","g");$t.setAttributeNS(null,"stroke","none"),$t.setAttributeNS(null,"stroke-width","1"),$t.setAttributeNS(null,"fill","none"),$t.setAttributeNS(null,"fill-rule","evenodd");const Gr=n.createNS("http://www.w3.org/2000/svg","g");Gr.setAttributeNS(null,"fill-rule","nonzero");const mn=n.createNS("http://www.w3.org/2000/svg","g");mn.setAttributeNS(null,"transform","translate(3.0, 29.0)"),mn.setAttributeNS(null,"fill","#000000");const Hn=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(const M of Hn){const et=n.createNS("http://www.w3.org/2000/svg","ellipse");et.setAttributeNS(null,"opacity","0.04"),et.setAttributeNS(null,"cx","10.5"),et.setAttributeNS(null,"cy","5.80029008"),et.setAttributeNS(null,"rx",M.rx),et.setAttributeNS(null,"ry",M.ry),mn.appendChild(et)}const so=n.createNS("http://www.w3.org/2000/svg","g");so.setAttributeNS(null,"fill",this._color);const uo=n.createNS("http://www.w3.org/2000/svg","path");uo.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),so.appendChild(uo);const Io=n.createNS("http://www.w3.org/2000/svg","g");Io.setAttributeNS(null,"opacity","0.25"),Io.setAttributeNS(null,"fill","#000000");const Po=n.createNS("http://www.w3.org/2000/svg","path");Po.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),Io.appendChild(Po);const To=n.createNS("http://www.w3.org/2000/svg","g");To.setAttributeNS(null,"transform","translate(6.0, 7.0)"),To.setAttributeNS(null,"fill","#FFFFFF");const Eo=n.createNS("http://www.w3.org/2000/svg","g");Eo.setAttributeNS(null,"transform","translate(8.0, 8.0)");const Ia=n.createNS("http://www.w3.org/2000/svg","circle");Ia.setAttributeNS(null,"fill","#000000"),Ia.setAttributeNS(null,"opacity","0.25"),Ia.setAttributeNS(null,"cx","5.5"),Ia.setAttributeNS(null,"cy","5.5"),Ia.setAttributeNS(null,"r","5.4999962");const Ba=n.createNS("http://www.w3.org/2000/svg","circle");Ba.setAttributeNS(null,"fill","#FFFFFF"),Ba.setAttributeNS(null,"cx","5.5"),Ba.setAttributeNS(null,"cy","5.5"),Ba.setAttributeNS(null,"r","5.4999962"),Eo.appendChild(Ia),Eo.appendChild(Ba),Gr.appendChild(mn),Gr.appendChild(so),Gr.appendChild(Io),Gr.appendChild(To),Gr.appendChild(Eo),Bt.appendChild(Gr),Bt.setAttributeNS(null,"height",Wt*this._scale+"px"),Bt.setAttributeNS(null,"width",Nt*this._scale+"px"),this._element.appendChild(Bt),this._offset=et.P.convert(M&&M.offset||[0,-14])}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(M=>{M.preventDefault()})),this._element.addEventListener("mousedown",(M=>{M.preventDefault()})),Os(this._element,this._anchor,"marker"),M&&M.className)for(const et of M.className.split(" "))this._element.classList.add(et);this._popup=null}addTo(M){return this.remove(),this._map=M,this._element.setAttribute("aria-label",M._getUIString("Marker.Title")),M.getCanvasContainer().appendChild(this._element),M.on("move",this._update),M.on("moveend",this._update),M.on("terrain",this._update),M.on("projectiontransition",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("projectiontransition",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),n.remove(this._element),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(M){return this._lngLat=et.N.convert(M),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(M){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),M){if(!("offset"in M.options)){const et=38.1,Bt=13.5,Wt=Math.abs(Bt)/Math.SQRT2;M.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[Wt,-1*(et-Bt+Wt)],"bottom-right":[-Wt,-1*(et-Bt+Wt)],left:[Bt,-1*(et-Bt)],right:[-13.5,-1*(et-Bt)]}:this._offset}this._popup=M,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress)}return this}setSubpixelPositioning(M){return this._subpixelPositioning=M,this}getPopup(){return this._popup}togglePopup(){const M=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:M?(M.isOpen()?M.remove():(M.setLngLat(this._lngLat),M.addTo(this._map)),this):this}_updateOpacity(M=!1){var Bt,Wt;if(!(null===(Bt=this._map)||void 0===Bt?void 0:Bt.terrain)){const M=this._map.transform.isLocationOccluded(this._lngLat)?this._opacityWhenCovered:this._opacity;return void(this._element.style.opacity!==M&&(this._element.style.opacity=M))}if(M)this._opacityTimeout=null;else{if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null}),100)}const Nt=this._map,$t=Nt.terrain.depthAtPoint(this._pos),Gr=Nt.terrain.getElevationForLngLatZoom(this._lngLat,Nt.transform.tileZoom);if(Nt.transform.lngLatToCameraDepth(this._lngLat,Gr)-$t<.006)return void(this._element.style.opacity=this._opacity);const mn=-this._offset.y/Nt.transform.pixelsPerMeter,Hn=Math.sin(Nt.getPitch()*Math.PI/180)*mn,so=Nt.terrain.depthAtPoint(new et.P(this._pos.x,this._pos.y-this._offset.y)),uo=Nt.transform.lngLatToCameraDepth(this._lngLat,Gr+Hn)-so>.006;(null===(Wt=this._popup)||void 0===Wt?void 0:Wt.isOpen())&&uo&&this._popup.remove(),this._element.style.opacity=uo?this._opacityWhenCovered:this._opacity}getOffset(){return this._offset}setOffset(M){return this._offset=et.P.convert(M),this._update(),this}addClassName(M){this._element.classList.add(M)}removeClassName(M){this._element.classList.remove(M)}toggleClassName(M){return this._element.classList.toggle(M)}setDraggable(M){return this._draggable=!!M,this._map&&(M?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(M){return this._rotation=M||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(M){return this._rotationAlignment=M||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(M){return this._pitchAlignment=M&&"auto"!==M?M:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(M,et){return void 0===M&&void 0===et&&(this._opacity="1",this._opacityWhenCovered="0.2"),void 0!==M&&(this._opacity=M),void 0!==et&&(this._opacityWhenCovered=et),this._map&&this._updateOpacity(!0),this}}const qh={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0};let tg=0,eg=!1;const ig={maxWidth:100,unit:"metric"};function qs(M,et,Bt){const Wt=Bt&&Bt.maxWidth||100,Nt=M._container.clientHeight/2,$t=M._container.clientWidth/2,Gr=M.unproject([$t-Wt/2,Nt]),mn=M.unproject([$t+Wt/2,Nt]),Hn=Math.round(M.project(mn).x-M.project(Gr).x),so=Math.min(Wt,Hn,M._container.clientWidth),uo=Gr.distanceTo(mn);if(Bt&&"imperial"===Bt.unit){const Bt=3.2808*uo;Bt>5280?Hs(et,so,Bt/5280,M._getUIString("ScaleControl.Miles")):Hs(et,so,Bt,M._getUIString("ScaleControl.Feet"))}else Bt&&"nautical"===Bt.unit?Hs(et,so,uo/1852,M._getUIString("ScaleControl.NauticalMiles")):uo>=1e3?Hs(et,so,uo/1e3,M._getUIString("ScaleControl.Kilometers")):Hs(et,so,uo,M._getUIString("ScaleControl.Meters"))}function Hs(M,et,Bt,Wt){const Nt=function(M){const et=Math.pow(10,`${Math.floor(M)}`.length-1);let Bt=M/et;return Bt=Bt>=10?10:Bt>=5?5:Bt>=3?3:Bt>=2?2:Bt>=1?1:function(M){const et=Math.pow(10,Math.ceil(-Math.log(M)/Math.LN10));return Math.round(M*et)/et}(Bt),et*Bt}(Bt);M.style.width=et*(Nt/Bt)+"px",M.innerHTML=`${Nt} ${Wt}`}const rg={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",subpixelPositioning:!1},ng=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function $s(M){if(M){if("number"==typeof M){const Bt=Math.round(Math.abs(M)/Math.SQRT2);return{center:new et.P(0,0),top:new et.P(0,M),"top-left":new et.P(Bt,Bt),"top-right":new et.P(-Bt,Bt),bottom:new et.P(0,-M),"bottom-left":new et.P(Bt,-Bt),"bottom-right":new et.P(-Bt,-Bt),left:new et.P(M,0),right:new et.P(-M,0)}}if(M instanceof et.P||Array.isArray(M)){const Bt=et.P.convert(M);return{center:Bt,top:Bt,"top-left":Bt,"top-right":Bt,bottom:Bt,"bottom-left":Bt,"bottom-right":Bt,left:Bt,right:Bt}}return{center:et.P.convert(M.center||[0,0]),top:et.P.convert(M.top||[0,0]),"top-left":et.P.convert(M["top-left"]||[0,0]),"top-right":et.P.convert(M["top-right"]||[0,0]),bottom:et.P.convert(M.bottom||[0,0]),"bottom-left":et.P.convert(M["bottom-left"]||[0,0]),"bottom-right":et.P.convert(M["bottom-right"]||[0,0]),left:et.P.convert(M.left||[0,0]),right:et.P.convert(M.right||[0,0])}}return $s(new et.P(0,0))}const og=Bt;M.AJAXError=et.cg,M.Event=et.k,M.Evented=et.E,M.LngLat=et.N,M.MercatorCoordinate=et.Y,M.Point=et.P,M.addProtocol=et.ch,M.config=et.a,M.removeProtocol=et.ci,M.AttributionControl=ws,M.BoxZoomHandler=jo,M.CanvasSource=J,M.CooperativeGesturesHandler=ms,M.DoubleClickZoomHandler=cs,M.DragPanHandler=ds,M.DragRotateHandler=_s,M.EdgeInsets=Pt,M.FullscreenControl=class extends et.E{constructor(M={}){super(),this._onFullscreenChange=()=>{var M;let et=window.document.fullscreenElement||window.document.mozFullScreenElement||window.document.webkitFullscreenElement||window.document.msFullscreenElement;for(;null===(M=null==et?void 0:et.shadowRoot)||void 0===M?void 0:M.fullscreenElement;)et=et.shadowRoot.fullscreenElement;et===this._container!==this._fullscreen&&this._handleFullscreenChange()},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen()},this._fullscreen=!1,M&&M.container&&(M.container instanceof HTMLElement?this._container=M.container:et.w("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange")}onAdd(M){return this._map=M,this._container||(this._container=this._map.getContainer()),this._controlContainer=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){n.remove(this._controlContainer),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange)}_setupUI(){const M=this._fullscreenButton=n.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);n.create("span","maplibregl-ctrl-icon",M).setAttribute("aria-hidden","true"),M.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange)}_updateTitle(){const M=this._getTitle();this._fullscreenButton.setAttribute("aria-label",M),this._fullscreenButton.title=M}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink"),this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen"),this._updateTitle(),this._fullscreen?(this.fire(new et.k("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new et.k("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable())}_exitFullscreen(){window.document.exitFullscreen?window.document.exitFullscreen():window.document.mozCancelFullScreen?window.document.mozCancelFullScreen():window.document.msExitFullscreen?window.document.msExitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen()}_requestFullscreen(){this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen()}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize()}},M.GeoJSONSource=$,M.GeolocateControl=class extends et.E{constructor(M){super(),this._onSuccess=M=>{if(this._map){if(this._isOutOfMapMaxBounds(M))return this._setErrorState(),this.fire(new et.k("outofmaxbounds",M)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=M,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(M),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(M),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new et.k("geolocate",M)),this._finish()}},this._updateCamera=M=>{const Bt=new et.N(M.coords.longitude,M.coords.latitude),Wt=M.coords.accuracy,Nt=this._map.getBearing(),$t=et.e({bearing:Nt},this.options.fitBoundsOptions),Gr=V.fromLngLat(Bt,Wt);this._map.fitBounds(Gr,$t,{geolocateSource:!0})},this._updateMarker=M=>{if(M){const Bt=new et.N(M.coords.longitude,M.coords.latitude);this._accuracyCircleMarker.setLngLat(Bt).addTo(this._map),this._userLocationDotMarker.setLngLat(Bt).addTo(this._map),this._accuracy=M.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()},this._onZoom=()=>{this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()},this._onError=M=>{if(this._map){if(this.options.trackUserLocation)if(1===M.code){this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const M=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=M,this._geolocateButton.setAttribute("aria-label",M),void 0!==this._geolocationWatchID&&this._clearWatch()}else{if(3===M.code&&eg)return;this._setErrorState()}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new et.k("error",M)),this._finish()}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(M=>M.preventDefault())),this._geolocateButton=n.create("button","maplibregl-ctrl-geolocate",this._container),n.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=!0)},this._finishSetupUI=M=>{if(this._map){if(!1===M){et.w("Geolocation support is not available so the GeolocateControl will be disabled.");const M=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=M,this._geolocateButton.setAttribute("aria-label",M)}else{const M=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=!1,this._geolocateButton.title=M,this._geolocateButton.setAttribute("aria-label",M)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=n.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new Ns({element:this._dotElement}),this._circleElement=n.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Ns({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(M=>{M.geolocateSource||"ACTIVE_LOCK"!==this._watchState||M.originalEvent&&"resize"===M.originalEvent.type||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new et.k("trackuserlocationend")),this.fire(new et.k("userlocationlostfocus")))}))}},this.options=et.e({},qh,M)}onAdd(M){return this._map=M,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),function(){return et._(this,arguments,void 0,(function*(M=!1){if(void 0!==Yh&&!M)return Yh;if(void 0===window.navigator.permissions)return Yh=!!window.navigator.geolocation,Yh;try{const M=yield window.navigator.permissions.query({name:"geolocation"});Yh="denied"!==M.state}catch(M){Yh=!!window.navigator.geolocation}return Yh}))}().then((M=>this._finishSetupUI(M))),this._container}onRemove(){void 0!==this._geolocationWatchID&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),n.remove(this._container),this._map.off("zoom",this._onZoom),this._map=void 0,tg=0,eg=!1}_isOutOfMapMaxBounds(M){const et=this._map.getMaxBounds(),Bt=M.coords;return et&&(Bt.longitudeet.getEast()||Bt.latitudeet.getNorth())}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"ACTIVE_ERROR":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadius(){const M=this._map.getBounds(),et=M.getSouthEast(),Bt=M.getNorthEast(),Wt=et.distanceTo(Bt),Nt=Math.ceil(this._accuracy/(Wt/this._map._container.clientHeight)*2);this._circleElement.style.width=`${Nt}px`,this._circleElement.style.height=`${Nt}px`}trigger(){if(!this._setup)return et.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new et.k("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":tg--,eg=!1,this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this.fire(new et.k("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new et.k("trackuserlocationstart")),this.fire(new et.k("userlocationfocus"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let M;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),tg++,tg>1?(M={maximumAge:6e5,timeout:0},eg=!0):(M=this.options.positionOptions,eg=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,M)}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return!0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}},M.GlobeControl=class{constructor(){this._toggleProjection=()=>{var M;const et=null===(M=this._map.getProjection())||void 0===M?void 0:M.type;this._map.setProjection("mercator"!==et&&et?{type:"mercator"}:{type:"globe"}),this._updateGlobeIcon()},this._updateGlobeIcon=()=>{var M;this._globeButton.classList.remove("maplibregl-ctrl-globe"),this._globeButton.classList.remove("maplibregl-ctrl-globe-enabled"),"globe"===(null===(M=this._map.getProjection())||void 0===M?void 0:M.type)?(this._globeButton.classList.add("maplibregl-ctrl-globe-enabled"),this._globeButton.title=this._map._getUIString("GlobeControl.Disable")):(this._globeButton.classList.add("maplibregl-ctrl-globe"),this._globeButton.title=this._map._getUIString("GlobeControl.Enable"))}}onAdd(M){return this._map=M,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._globeButton=n.create("button","maplibregl-ctrl-globe",this._container),n.create("span","maplibregl-ctrl-icon",this._globeButton).setAttribute("aria-hidden","true"),this._globeButton.type="button",this._globeButton.addEventListener("click",this._toggleProjection),this._updateGlobeIcon(),this._map.on("styledata",this._updateGlobeIcon),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateGlobeIcon),this._globeButton.removeEventListener("click",this._toggleProjection),this._map=void 0}},M.Hash=wo,M.ImageSource=K,M.KeyboardHandler=ss,M.LngLatBounds=V,M.LogoControl=Ts,M.Map=class extends bs{constructor(M){var Bt,Wt;et.cd.mark(et.ce.create);const Nt=Object.assign(Object.assign(Object.assign({},Hh),M),{canvasContextAttributes:Object.assign(Object.assign({},Hh.canvasContextAttributes),M.canvasContextAttributes)});if(null!=Nt.minZoom&&null!=Nt.maxZoom&&Nt.minZoom>Nt.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=Nt.minPitch&&null!=Nt.maxPitch&&Nt.minPitch>Nt.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=Nt.minPitch&&Nt.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=Nt.maxPitch&&Nt.maxPitch>180)throw new Error("maxPitch must be less than or equal to 180");const $t=new Dt,Gr=new kt;if(void 0!==Nt.minZoom&&$t.setMinZoom(Nt.minZoom),void 0!==Nt.maxZoom&&$t.setMaxZoom(Nt.maxZoom),void 0!==Nt.minPitch&&$t.setMinPitch(Nt.minPitch),void 0!==Nt.maxPitch&&$t.setMaxPitch(Nt.maxPitch),void 0!==Nt.renderWorldCopies&&$t.setRenderWorldCopies(Nt.renderWorldCopies),super($t,Gr,{bearingSnap:Nt.bearingSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new Ps,this._controls=[],this._mapId=et.a1(),this._contextLost=M=>{M.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.fire(new et.k("webglcontextlost",{originalEvent:M}))},this._contextRestored=M=>{this._setupPainter(),this.resize(),this._update(),this.fire(new et.k("webglcontextrestored",{originalEvent:M}))},this._onMapScroll=M=>{if(M.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update()},this._interactive=Nt.interactive,this._maxTileCacheSize=Nt.maxTileCacheSize,this._maxTileCacheZoomLevels=Nt.maxTileCacheZoomLevels,this._canvasContextAttributes=Object.assign({},Nt.canvasContextAttributes),this._trackResize=!0===Nt.trackResize,this._bearingSnap=Nt.bearingSnap,this._centerClampedToGround=Nt.centerClampedToGround,this._refreshExpiredTiles=!0===Nt.refreshExpiredTiles,this._fadeDuration=Nt.fadeDuration,this._crossSourceCollisions=!0===Nt.crossSourceCollisions,this._collectResourceTiming=!0===Nt.collectResourceTiming,this._locale=Object.assign(Object.assign({},Xh),Nt.locale),this._clickTolerance=Nt.clickTolerance,this._overridePixelRatio=Nt.pixelRatio,this._maxCanvasSize=Nt.maxCanvasSize,this.transformCameraUpdate=Nt.transformCameraUpdate,this.cancelPendingTileRequestsWhileZooming=!0===Nt.cancelPendingTileRequestsWhileZooming,this._imageQueueHandle=Io.addThrottleControl((()=>this.isMoving())),this._requestManager=new m(Nt.transformRequest),"string"==typeof Nt.container){if(this._container=document.getElementById(Nt.container),!this._container)throw new Error(`Container '${Nt.container}' not found.`)}else{if(!(Nt.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=Nt.container}if(Nt.maxBounds&&this.setMaxBounds(Nt.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(!1))),this.on("moveend",(()=>this._update(!1))),this.on("zoom",(()=>this._update(!0))),this.on("terrain",(()=>{this.painter.terrainFacilitator.dirty=!0,this._update(!0)})),this.once("idle",(()=>{this._idleTriggered=!0})),"undefined"!=typeof window){addEventListener("online",this._onWindowOnline,!1);let M=!1;const et=yo((M=>{this._trackResize&&!this._removed&&(this.resize(M),this.redraw())}),50);this._resizeObserver=new ResizeObserver((Bt=>{M?et(Bt):M=!0})),this._resizeObserver.observe(this._container)}this.handlers=new xs(this,Nt),this._hash=Nt.hash&&new wo("string"==typeof Nt.hash&&Nt.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:Nt.center,elevation:Nt.elevation,zoom:Nt.zoom,bearing:Nt.bearing,pitch:Nt.pitch,roll:Nt.roll}),Nt.bounds&&(this.resize(),this.fitBounds(Nt.bounds,et.e({},Nt.fitBoundsOptions,{duration:0}))));const mn="string"==typeof Nt.style||!("globe"===(null===(Wt=null===(Bt=Nt.style)||void 0===Bt?void 0:Bt.projection)||void 0===Wt?void 0:Wt.type));this.resize(null,mn),this._localIdeographFontFamily=Nt.localIdeographFontFamily,this._validateStyle=Nt.validateStyle,Nt.style&&this.setStyle(Nt.style,{localIdeographFontFamily:Nt.localIdeographFontFamily}),Nt.attributionControl&&this.addControl(new ws("boolean"==typeof Nt.attributionControl?void 0:Nt.attributionControl)),Nt.maplibreLogo&&this.addControl(new Ts,Nt.logoPosition),this.on("style.load",(()=>{if(mn||this._resizeTransform(),this.transform.unmodified){const M=et.M(this.style.stylesheet,["center","zoom","bearing","pitch","roll"]);this.jumpTo(M)}})),this.on("data",(M=>{this._update("style"===M.dataType),this.fire(new et.k(`${M.dataType}data`,M))})),this.on("dataloading",(M=>{this.fire(new et.k(`${M.dataType}dataloading`,M))})),this.on("dataabort",(M=>{this.fire(new et.k("sourcedataabort",M))}))}_getMapId(){return this._mapId}addControl(M,Bt){if(void 0===Bt&&(Bt=M.getDefaultPosition?M.getDefaultPosition():"top-right"),!M||!M.onAdd)return this.fire(new et.j(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const Wt=M.onAdd(this);this._controls.push(M);const Nt=this._controlPositions[Bt];return-1!==Bt.indexOf("bottom")?Nt.insertBefore(Wt,Nt.firstChild):Nt.appendChild(Wt),this}removeControl(M){if(!M||!M.onRemove)return this.fire(new et.j(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const Bt=this._controls.indexOf(M);return Bt>-1&&this._controls.splice(Bt,1),M.onRemove(this),this}hasControl(M){return this._controls.indexOf(M)>-1}calculateCameraOptionsFromTo(M,et,Bt,Wt){return null==Wt&&this.terrain&&(Wt=this.terrain.getElevationForLngLatZoom(Bt,this.transform.tileZoom)),super.calculateCameraOptionsFromTo(M,et,Bt,Wt)}resize(M,Bt=!0){const[Wt,Nt]=this._containerDimensions(),$t=this._getClampedPixelRatio(Wt,Nt);if(this._resizeCanvas(Wt,Nt,$t),this.painter.resize(Wt,Nt,$t),this.painter.overLimit()){const M=this.painter.context.gl;this._maxCanvasSize=[M.drawingBufferWidth,M.drawingBufferHeight];const et=this._getClampedPixelRatio(Wt,Nt);this._resizeCanvas(Wt,Nt,et),this.painter.resize(Wt,Nt,et)}this._resizeTransform(Bt);const Gr=!this._moving;return Gr&&(this.stop(),this.fire(new et.k("movestart",M)).fire(new et.k("move",M))),this.fire(new et.k("resize",M)),Gr&&this.fire(new et.k("moveend",M)),this}_resizeTransform(M=!0){var et;const[Bt,Wt]=this._containerDimensions();this.transform.resize(Bt,Wt,M),null===(et=this._requestedCameraState)||void 0===et||et.resize(Bt,Wt,M)}_getClampedPixelRatio(M,et){const{0:Bt,1:Wt}=this._maxCanvasSize,Nt=this.getPixelRatio(),$t=M*Nt,Gr=et*Nt;return Math.min($t>Bt?Bt/$t:1,Gr>Wt?Wt/Gr:1)*Nt}getPixelRatio(){var M;return null!==(M=this._overridePixelRatio)&&void 0!==M?M:devicePixelRatio}setPixelRatio(M){this._overridePixelRatio=M,this.resize()}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(M){return this.transform.setMaxBounds(V.convert(M)),this._update()}setMinZoom(M){if((M=null==M?-2:M)>=-2&&M<=this.transform.maxZoom)return this.transform.setMinZoom(M),this._update(),this.getZoom()=this.transform.minZoom)return this.transform.setMaxZoom(M),this._update(),this.getZoom()>M&&this.setZoom(M),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(M){if((M=null==M?0:M)<0)throw new Error("minPitch must be greater than or equal to 0");if(M>=0&&M<=this.transform.maxPitch)return this.transform.setMinPitch(M),this._update(),this.getPitch()180)throw new Error("maxPitch must be less than or equal to 180");if(M>=this.transform.minPitch)return this.transform.setMaxPitch(M),this._update(),this.getPitch()>M&&this.setPitch(M),this;throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(M){return this.transform.setRenderWorldCopies(M),this._update()}project(M){return this.transform.locationToScreenPoint(et.N.convert(M),this.style&&this.terrain)}unproject(M){return this.transform.screenPointToLocation(et.P.convert(M),this.terrain)}isMoving(){var M;return this._moving||(null===(M=this.handlers)||void 0===M?void 0:M.isMoving())}isZooming(){var M;return this._zooming||(null===(M=this.handlers)||void 0===M?void 0:M.isZooming())}isRotating(){var M;return this._rotating||(null===(M=this.handlers)||void 0===M?void 0:M.isRotating())}_createDelegatedListener(M,et,Bt){if("mouseenter"===M||"mouseover"===M){let Wt=!1;const o=Nt=>{const $t=et.filter((M=>this.getLayer(M))),Gr=0!==$t.length?this.queryRenderedFeatures(Nt.point,{layers:$t}):[];Gr.length?Wt||(Wt=!0,Bt.call(this,new zo(M,this,Nt.originalEvent,{features:Gr}))):Wt=!1};return{layers:et,listener:Bt,delegates:{mousemove:o,mouseout:()=>{Wt=!1}}}}if("mouseleave"===M||"mouseout"===M){let Wt=!1;const o=Nt=>{const $t=et.filter((M=>this.getLayer(M)));(0!==$t.length?this.queryRenderedFeatures(Nt.point,{layers:$t}):[]).length?Wt=!0:Wt&&(Wt=!1,Bt.call(this,new zo(M,this,Nt.originalEvent)))},s=et=>{Wt&&(Wt=!1,Bt.call(this,new zo(M,this,et.originalEvent)))};return{layers:et,listener:Bt,delegates:{mousemove:o,mouseout:s}}}{const r=M=>{const Wt=et.filter((M=>this.getLayer(M))),Nt=0!==Wt.length?this.queryRenderedFeatures(M.point,{layers:Wt}):[];Nt.length&&(M.features=Nt,Bt.call(this,M),delete M.features)};return{layers:et,listener:Bt,delegates:{[M]:r}}}}_saveDelegatedListener(M,et){this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[M]=this._delegatedListeners[M]||[],this._delegatedListeners[M].push(et)}_removeDelegatedListener(M,et,Bt){if(!this._delegatedListeners||!this._delegatedListeners[M])return;const Wt=this._delegatedListeners[M];for(let M=0;Met.includes(M)))){for(const M in Nt.delegates)this.off(M,Nt.delegates[M]);return void Wt.splice(M,1)}}}on(M,et,Bt){if(void 0===Bt)return super.on(M,et);const Wt="string"==typeof et?[et]:et,Nt=this._createDelegatedListener(M,Wt,Bt);this._saveDelegatedListener(M,Nt);for(const M in Nt.delegates)this.on(M,Nt.delegates[M]);return{unsubscribe:()=>{this._removeDelegatedListener(M,Wt,Bt)}}}once(M,et,Bt){if(void 0===Bt)return super.once(M,et);const Wt="string"==typeof et?[et]:et,Nt=this._createDelegatedListener(M,Wt,Bt);for(const et in Nt.delegates){const $t=Nt.delegates[et];Nt.delegates[et]=(...et)=>{this._removeDelegatedListener(M,Wt,Bt),$t(...et)}}this._saveDelegatedListener(M,Nt);for(const M in Nt.delegates)this.once(M,Nt.delegates[M]);return this}off(M,et,Bt){return void 0===Bt?super.off(M,et):(this._removeDelegatedListener(M,"string"==typeof et?[et]:et,Bt),this)}queryRenderedFeatures(M,Bt){if(!this.style)return[];let Wt;const Nt=M instanceof et.P||Array.isArray(M),$t=Nt?M:[[0,0],[this.transform.width,this.transform.height]];if(Bt=Bt||(Nt?{}:M)||{},$t instanceof et.P||"number"==typeof $t[0])Wt=[et.P.convert($t)];else{const M=et.P.convert($t[0]),Bt=et.P.convert($t[1]);Wt=[M,new et.P(Bt.x,M.y),Bt,new et.P(M.x,Bt.y),M]}return this.style.queryRenderedFeatures(Wt,Bt,this.transform)}querySourceFeatures(M,et){return this.style.querySourceFeatures(M,et)}setStyle(M,Bt){return!1!==(Bt=et.e({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},Bt)).diff&&Bt.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&M?(this._diffStyle(M,Bt),this):(this._localIdeographFontFamily=Bt.localIdeographFontFamily,this._updateStyle(M,Bt))}setTransformRequest(M){return this._requestManager.setTransformRequest(M),this}_getUIString(M){const et=this._locale[M];if(null==et)throw new Error(`Missing UI string '${M}'`);return et}_updateStyle(M,et){var Bt,Wt;if(et.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(M,et)));const Nt=this.style&&et.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!M)),M?(this.style=new gi(this,et||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof M?this.style.loadURL(M,et,Nt):this.style.loadJSON(M,et,Nt),this):(null===(Wt=null===(Bt=this.style)||void 0===Bt?void 0:Bt.projection)||void 0===Wt||Wt.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new gi(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty())}_diffStyle(M,Bt){if("string"==typeof M){const Wt=this._requestManager.transformRequest(M,"Style");et.h(Wt,new AbortController).then((M=>{this._updateDiff(M.data,Bt)})).catch((M=>{M&&this.fire(new et.j(M))}))}else"object"==typeof M&&this._updateDiff(M,Bt)}_updateDiff(M,Bt){try{this.style.setState(M,Bt)&&this._update(!0)}catch(Wt){et.w(`Unable to perform style diff: ${Wt.message||Wt.error||Wt}. Rebuilding the style from scratch.`),this._updateStyle(M,Bt)}}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():et.w("There is no style added to the map.")}addSource(M,et){return this._lazyInitEmptyStyle(),this.style.addSource(M,et),this._update(!0)}isSourceLoaded(M){const Bt=this.style&&this.style.sourceCaches[M];if(void 0!==Bt)return Bt.loaded();this.fire(new et.j(new Error(`There is no source with ID '${M}'`)))}setTerrain(M){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),M){const Bt=this.style.sourceCaches[M.source];if(!Bt)throw new Error(`cannot load terrain, because there exists no source with ID: ${M.source}`);null===this.terrain&&Bt.reload();for(const Bt in this.style._layers){const Wt=this.style._layers[Bt];"hillshade"===Wt.type&&Wt.source===M.source&&et.w("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.")}this.terrain=new Es(this.painter,Bt,M),this.painter.renderToTexture=new Rs(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=et=>{"style"===et.dataType?this.terrain.sourceCache.freeRtt():"source"===et.dataType&&et.tile&&(et.sourceId!==M.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),this.terrain.sourceCache.freeRtt(et.tile.tileID))},this.style.on("data",this._terrainDataCallback)}else this.terrain&&this.terrain.sourceCache.destruct(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new et.k("terrain",{terrain:M})),this}getTerrain(){var M,et;return null!==(et=null===(M=this.terrain)||void 0===M?void 0:M.options)&&void 0!==et?et:null}areTilesLoaded(){const M=this.style&&this.style.sourceCaches;for(const et in M){const Bt=M[et]._tiles;for(const M in Bt){const et=Bt[M];if("loaded"!==et.state&&"errored"!==et.state)return!1}}return!0}removeSource(M){return this.style.removeSource(M),this._update(!0)}getSource(M){return this.style.getSource(M)}addImage(M,Bt,Wt={}){const{pixelRatio:Nt=1,sdf:Gr=!1,stretchX:mn,stretchY:Hn,content:so,textFitWidth:uo,textFitHeight:Io}=Wt;if(this._lazyInitEmptyStyle(),!(Bt instanceof HTMLImageElement||et.b(Bt))){if(void 0===Bt.width||void 0===Bt.height)return this.fire(new et.j(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{const{width:Wt,height:$t,data:Po}=Bt,To=Bt;return this.style.addImage(M,{data:new et.R({width:Wt,height:$t},new Uint8Array(Po)),pixelRatio:Nt,stretchX:mn,stretchY:Hn,content:so,textFitWidth:uo,textFitHeight:Io,sdf:Gr,version:0,userImage:To}),To.onAdd&&To.onAdd(this,M),this}}{const{width:Wt,height:Po,data:To}=$t.getImageData(Bt);this.style.addImage(M,{data:new et.R({width:Wt,height:Po},To),pixelRatio:Nt,stretchX:mn,stretchY:Hn,content:so,textFitWidth:uo,textFitHeight:Io,sdf:Gr,version:0})}}updateImage(M,Bt){const Wt=this.style.getImage(M);if(!Wt)return this.fire(new et.j(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const Nt=Bt instanceof HTMLImageElement||et.b(Bt)?$t.getImageData(Bt):Bt,{width:Gr,height:mn,data:Hn}=Nt;if(void 0===Gr||void 0===mn)return this.fire(new et.j(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(Gr!==Wt.data.width||mn!==Wt.data.height)return this.fire(new et.j(new Error("The width and height of the updated image must be that same as the previous version of the image")));const so=!(Bt instanceof HTMLImageElement||et.b(Bt));return Wt.data.replace(Hn,so),this.style.updateImage(M,Wt),this}getImage(M){return this.style.getImage(M)}hasImage(M){return M?!!this.style.getImage(M):(this.fire(new et.j(new Error("Missing required image id"))),!1)}removeImage(M){this.style.removeImage(M)}loadImage(M){return Io.getImage(this._requestManager.transformRequest(M,"Image"),new AbortController)}listImages(){return this.style.listImages()}addLayer(M,et){return this._lazyInitEmptyStyle(),this.style.addLayer(M,et),this._update(!0)}moveLayer(M,et){return this.style.moveLayer(M,et),this._update(!0)}removeLayer(M){return this.style.removeLayer(M),this._update(!0)}getLayer(M){return this.style.getLayer(M)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(M,et,Bt){return this.style.setLayerZoomRange(M,et,Bt),this._update(!0)}setFilter(M,et,Bt={}){return this.style.setFilter(M,et,Bt),this._update(!0)}getFilter(M){return this.style.getFilter(M)}setPaintProperty(M,et,Bt,Wt={}){return this.style.setPaintProperty(M,et,Bt,Wt),this._update(!0)}getPaintProperty(M,et){return this.style.getPaintProperty(M,et)}setLayoutProperty(M,et,Bt,Wt={}){return this.style.setLayoutProperty(M,et,Bt,Wt),this._update(!0)}getLayoutProperty(M,et){return this.style.getLayoutProperty(M,et)}setGlyphs(M,et={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(M,et),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(M,et,Bt={}){return this._lazyInitEmptyStyle(),this.style.addSprite(M,et,Bt,(M=>{M||this._update(!0)})),this}removeSprite(M){return this._lazyInitEmptyStyle(),this.style.removeSprite(M),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(M,et={}){return this._lazyInitEmptyStyle(),this.style.setSprite(M,et,(M=>{M||this._update(!0)})),this}setLight(M,et={}){return this._lazyInitEmptyStyle(),this.style.setLight(M,et),this._update(!0)}getLight(){return this.style.getLight()}setSky(M,et={}){return this._lazyInitEmptyStyle(),this.style.setSky(M,et),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(M,et){return this.style.setFeatureState(M,et),this._update()}removeFeatureState(M,et){return this.style.removeFeatureState(M,et),this._update()}getFeatureState(M){return this.style.getFeatureState(M)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let M=0,et=0;return this._container&&(M=this._container.clientWidth||400,et=this._container.clientHeight||300),[M,et]}_setupContainer(){const M=this._container;M.classList.add("maplibregl-map");const et=this._canvasContainer=n.create("div","maplibregl-canvas-container",M);this._interactive&&et.classList.add("maplibregl-interactive"),this._canvas=n.create("canvas","maplibregl-canvas",et),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");const Bt=this._containerDimensions(),Wt=this._getClampedPixelRatio(Bt[0],Bt[1]);this._resizeCanvas(Bt[0],Bt[1],Wt);const Nt=this._controlContainer=n.create("div","maplibregl-control-container",M),$t=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((M=>{$t[M]=n.create("div",`maplibregl-ctrl-${M} `,Nt)})),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(M,et,Bt){this._canvas.width=Math.floor(Bt*M),this._canvas.height=Math.floor(Bt*et),this._canvas.style.width=`${M}px`,this._canvas.style.height=`${et}px`}_setupPainter(){const M=Object.assign(Object.assign({},this._canvasContextAttributes),{alpha:!0,depth:!0,stencil:!0,premultipliedAlpha:!0});let et=null;this._canvas.addEventListener("webglcontextcreationerror",(Bt=>{et={requestedAttributes:M},Bt&&(et.statusMessage=Bt.statusMessage,et.type=Bt.type)}),{once:!0});let Bt=null;if(Bt=this._canvasContextAttributes.contextType?this._canvas.getContext(this._canvasContextAttributes.contextType,M):this._canvas.getContext("webgl2",M)||this._canvas.getContext("webgl",M),!Bt){const M="Failed to initialize WebGL";throw et?(et.message=M,new Error(JSON.stringify(et))):new Error(M)}this.painter=new bo(Bt,this.transform),Gr.testSupport(Bt)}migrateProjection(M,Bt){super.migrateProjection(M,Bt),this.painter.transform=M,this.fire(new et.k("projectiontransition",{newProjection:this.style.projection.name}))}loaded(){return!this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(M){return this.style&&this.style._loaded?(this._styleDirty=this._styleDirty||M,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(M){return this._update(),this._renderTaskQueue.add(M)}_cancelRenderFrame(M){this._renderTaskQueue.remove(M)}_render(M){var Bt,Wt,Nt,Gr,mn;const Hn=this._idleTriggered?this._fadeDuration:0,so=(null===(Bt=this.style.projection)||void 0===Bt?void 0:Bt.transitionState)>0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(M),this._removed)return;let uo=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;const M=this.transform.zoom,Bt=$t.now();this.style.zoomHistory.update(M,Bt);const Wt=new et.z(M,{now:Bt,fadeDuration:Hn,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),Nt=Wt.crossFadingFactor();1===Nt&&Nt===this._crossFadingFactor||(uo=!0,this._crossFadingFactor=Nt),this.style.update(Wt)}const Io=(null===(Wt=this.style.projection)||void 0===Wt?void 0:Wt.transitionState)>0!==so;null===(Nt=this.style.projection)||void 0===Nt||Nt.setErrorQueryLatitudeDegrees(this.transform.center.lat),this.transform.setTransitionState(null===(Gr=this.style.projection)||void 0===Gr?void 0:Gr.transitionState,null===(mn=this.style.projection)||void 0===mn?void 0:mn.latitudeErrorCorrectionRadians),this.style&&(this._sourcesDirty||Io)&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.sourceCache.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=this.style&&this.style._updatePlacement(this.transform,this.showCollisionBoxes,Hn,this._crossSourceCollisions,Io),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:Hn,showPadding:this.showPadding}),this.fire(new et.k("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,et.cd.mark(et.ce.load),this.fire(new et.k("load"))),this.style&&(this.style.hasTransitions()||uo)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();const Po=this._sourcesDirty||this._styleDirty||this._placementDirty;return Po||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new et.k("idle")),!this._loaded||this._fullyLoaded||Po||(this._fullyLoaded=!0,et.cd.mark(et.ce.fullLoad)),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var M;this._hash&&this._hash.remove();for(const M of this._controls)M.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),"undefined"!=typeof window&&removeEventListener("online",this._onWindowOnline,!1),Io.removeThrottleControl(this._imageQueueHandle),null===(M=this._resizeObserver)||void 0===M||M.disconnect();const Bt=this.painter.context.gl.getExtension("WEBGL_lose_context");(null==Bt?void 0:Bt.loseContext)&&Bt.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),n.remove(this._canvasContainer),n.remove(this._controlContainer),this._container.removeEventListener("scroll",this._onMapScroll,!1),this._container.classList.remove("maplibregl-map"),et.cd.clearMetrics(),this._removed=!0,this.fire(new et.k("remove"))}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,$t.frameAsync(this._frameRequest).then((M=>{et.cd.frame(M),this._frameRequest=null,this._render(M)})).catch((M=>{if(!et.cf(M)&&!function(M){return M.message===Ic}(M))throw M})))}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(M){this._showTileBoundaries!==M&&(this._showTileBoundaries=M,this._update())}get showPadding(){return!!this._showPadding}set showPadding(M){this._showPadding!==M&&(this._showPadding=M,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(M){this._showCollisionBoxes!==M&&(this._showCollisionBoxes=M,M?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(M){this._showOverdrawInspector!==M&&(this._showOverdrawInspector=M,this._update())}get repaint(){return!!this._repaint}set repaint(M){this._repaint!==M&&(this._repaint=M,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(M){this._vertices=M,this._update()}get version(){return Lh}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(M){return this._lazyInitEmptyStyle(),this.style.setProjection(M),this._update(!0)}},M.MapMouseEvent=zo,M.MapTouchEvent=Ao,M.MapWheelEvent=Lo,M.Marker=Ns,M.NavigationControl=class{constructor(M){this._updateZoomButtons=()=>{const M=this._map.getZoom(),et=M===this._map.getMaxZoom(),Bt=M===this._map.getMinZoom();this._zoomInButton.disabled=et,this._zoomOutButton.disabled=Bt,this._zoomInButton.setAttribute("aria-disabled",et.toString()),this._zoomOutButton.setAttribute("aria-disabled",Bt.toString())},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`},this._setButtonTitle=(M,et)=>{const Bt=this._map._getUIString(`NavigationControl.${et}`);M.title=Bt,M.setAttribute("aria-label",Bt)},this.options=et.e({},Kh,M),this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(M=>M.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(M=>this._map.zoomIn({},{originalEvent:M}))),n.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(M=>this._map.zoomOut({},{originalEvent:M}))),n.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(M=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:M}):this._map.resetNorth({},{originalEvent:M})})),this._compassIcon=n.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}onAdd(M){return this._map=M,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on("roll",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new ks(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){n.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off("roll",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map}_createButton(M,et){const Bt=n.create("button",M,this._container);return Bt.type="button",Bt.addEventListener("click",et),Bt}},M.Popup=class extends et.E{constructor(M){super(),this.remove=()=>(this._content&&n.remove(this._content),this._container&&(n.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._onMouseMove),this._map.off("mouseup",this._onMouseUp),this._map.off("drag",this._onDrag),this._map._canvasContainer.classList.remove("maplibregl-track-pointer"),delete this._map,this.fire(new et.k("close"))),this),this._onMouseUp=M=>{this._update(M.point)},this._onMouseMove=M=>{this._update(M.point)},this._onDrag=M=>{this._update(M.point)},this._update=M=>{var et;if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=n.create("div","maplibregl-popup",this._map.getContainer()),this._tip=n.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(const M of this.options.className.split(" "))this._container.classList.add(M);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),this._trackPointer&&this._container.classList.add("maplibregl-popup-track-pointer")}if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=this._map.transform.renderWorldCopies&&!this._trackPointer?Bs(this._lngLat,this._flatPos,this._map.transform):null===(et=this._lngLat)||void 0===et?void 0:et.wrap(),this._trackPointer&&!M)return;const Bt=this._flatPos=this._pos=this._trackPointer&&M?M:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&M?M:this._map.transform.locationToScreenPoint(this._lngLat));let Wt=this.options.anchor;const Nt=$s(this.options.offset);if(!Wt){const M=this._container.offsetWidth,et=this._container.offsetHeight;let $t;$t=Bt.y+Nt.bottom.ythis._map.transform.height-et?["bottom"]:[],Bt.xthis._map.transform.width-M/2&&$t.push("right"),Wt=0===$t.length?"bottom":$t.join("-")}let $t=Bt.add(Nt[Wt]);this.options.subpixelPositioning||($t=$t.round()),n.setTransform(this._container,`${Qh[Wt]} translate(${$t.x}px,${$t.y}px)`),Os(this._container,Wt,"popup")},this._onClose=()=>{this.remove()},this.options=et.e(Object.create(rg),M)}addTo(M){return this._map&&this.remove(),this._map=M,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new et.k("open")),this}isOpen(){return!!this._map}getLngLat(){return this._lngLat}setLngLat(M){return this._lngLat=et.N.convert(M),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(M){return this.setDOMContent(document.createTextNode(M))}setHTML(M){const et=document.createDocumentFragment(),Bt=document.createElement("body");let Wt;for(Bt.innerHTML=M;Wt=Bt.firstChild,Wt;)et.appendChild(Wt);return this.setDOMContent(et)}getMaxWidth(){var M;return null===(M=this._container)||void 0===M?void 0:M.style.maxWidth}setMaxWidth(M){return this.options.maxWidth=M,this._update(),this}setDOMContent(M){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=n.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(M),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(M){return this._container&&this._container.classList.add(M),this}removeClassName(M){return this._container&&this._container.classList.remove(M),this}setOffset(M){return this.options.offset=M,this._update(),this}toggleClassName(M){if(this._container)return this._container.classList.toggle(M)}setSubpixelPositioning(M){this.options.subpixelPositioning=M}_createCloseButton(){this.options.closeButton&&(this._closeButton=n.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose))}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const M=this._container.querySelector(ng);M&&M.focus()}},M.RasterDEMTileSource=X,M.RasterTileSource=W,M.ScaleControl=class{constructor(M){this._onMove=()=>{qs(this._map,this._container,this.options)},this.setUnit=M=>{this.options.unit=M,qs(this._map,this._container,this.options)},this.options=Object.assign(Object.assign({},ig),M)}getDefaultPosition(){return"bottom-left"}onAdd(M){return this._map=M,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-scale",M.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){n.remove(this._container),this._map.off("move",this._onMove),this._map=void 0}},M.ScrollZoomHandler=ls,M.Style=gi,M.TerrainControl=class{constructor(M){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon()},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"))},this.options=M}onAdd(M){return this._map=M,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=n.create("button","maplibregl-ctrl-terrain",this._container),n.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true"),this._terrainButton.type="button",this._terrainButton.addEventListener("click",this._toggleTerrain),this._updateTerrainIcon(),this._map.on("terrain",this._updateTerrainIcon),this._container}onRemove(){n.remove(this._container),this._map.off("terrain",this._updateTerrainIcon),this._map=void 0}},M.TwoFingersTouchPitchHandler=rs,M.TwoFingersTouchRotateHandler=ts,M.TwoFingersTouchZoomHandler=Qo,M.TwoFingersTouchZoomRotateHandler=ps,M.VectorTileSource=H,M.VideoSource=Y,M.addSourceType=(M,Bt)=>et._(void 0,void 0,void 0,(function*(){if(ee(M))throw new Error(`A source type called "${M}" already exists.`);((M,et)=>{za[M]=et})(M,Bt)})),M.clearPrewarmedResources=function(){const M=Ta;M&&(M.isPreloaded()&&1===M.numActive()?(M.release(Ia),Ta=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"))},M.createTileMesh=Ht,M.getMaxParallelImageRequests=function(){return et.a.MAX_PARALLEL_IMAGE_REQUESTS},M.getRTLTextPluginStatus=function(){return oe().getRTLTextPluginStatus()},M.getVersion=function(){return og},M.getWorkerCount=function(){return z.workerCount},M.getWorkerUrl=function(){return et.a.WORKER_URL},M.importScriptInWorkers=function(M){return j().broadcast("IS",M)},M.prewarm=function(){F().acquire(Ia)},M.setMaxParallelImageRequests=function(M){et.a.MAX_PARALLEL_IMAGE_REQUESTS=M},M.setRTLTextPlugin=function(M,et){return oe().setRTLTextPlugin(M,et)},M.setWorkerCount=function(M){z.workerCount=M},M.setWorkerUrl=function(M){et.a.WORKER_URL=M}}));var Bt=M;return Bt}()}(Vl)),Vl.exports}(),El=getDefaultExportFromCjs$1(Wl);function getDefaultExportFromCjs(M){return M.__esModule&&Object.prototype.hasOwnProperty.call(M,"default")?M.default:M}function getAugmentedNamespace(M){if(M.__esModule)return M;var et=M.default;if("function"==typeof et){var Bt=function a(){return this instanceof a?Reflect.construct(et,arguments,this.constructor):et.apply(this,arguments)};Bt.prototype=et.prototype}else Bt={};return Object.defineProperty(Bt,"__esModule",{value:!0}),Object.keys(M).forEach((function(et){var Wt=Object.getOwnPropertyDescriptor(M,et);Object.defineProperty(Bt,et,Wt.get?Wt:{enumerable:!0,get:function(){return M[et]}})})),Bt}function objectConverter(M){return new Function("d","return {"+M.map((function(M,et){return JSON.stringify(M)+": d["+et+"]"})).join(",")+"}")}function dsv$1(M){var et=new RegExp('["'+M+"\n]"),Bt=M.charCodeAt(0);function parseRows(M,et){var Wt,Nt,$t={},Gr={},mn=[],Hn=M.length,so=0,uo=0;function token(){if(so>=Hn)return Gr;if(Nt)return Nt=!1,$t;var et,Wt=so;if(34===M.charCodeAt(Wt)){for(var mn=Wt;mn++=0?0:1],Wt=Math.abs(M),Nt=Math.floor(Wt),$t=60*(Wt-Nt),Gr=Math.floor($t);return{whole:Nt,minutes:Gr,seconds:Math.floor(60*($t-Gr)),dir:Bt}}function search(M,et){if(et||(et="NSEW"),"string"!=typeof M)return null;var Bt=(M=M.toUpperCase()).match(/^[\s\,]*([NSEW])?\s*([\-|—|―]?[0-9.]+)[°º˚]?\s*(?:([0-9.]+)['’′‘]\s*)?(?:([0-9.]+)(?:''|"|”|″)\s*)?([NSEW])?/);if(!Bt)return null;var Wt,Nt=Bt[0];if(Bt[1]&&Bt[5]?(Wt=Bt[1],Nt=Nt.slice(0,-1)):Wt=Bt[1]||Bt[5],Wt&&-1===et.indexOf(Wt))return null;var $t=Bt[2]?parseFloat(Bt[2]):0,Gr=Bt[3]?parseFloat(Bt[3])/60:0,mn=Bt[4]?parseFloat(Bt[4])/3600:0,Hn=$t<0?-1:1;return"S"!==Wt&&"W"!==Wt||(Hn*=-1),{val:(Math.abs($t)+Gr+mn)*Hn,dim:Wt,matched:Nt,remain:M.slice(Nt.length)}}ec.exports=function element(M,et){var Bt=search(M,et);return null===Bt?null:Bt.val},ec.exports.pair=function pair(M,et){var Bt=search(M=M.trim(),et);if(!Bt)return null;var Wt=search(M=Bt.remain.trim(),et);if(!Wt||Wt.remain)return null;return Bt.dim?function swapdim(M,et,Bt){if("N"===Bt||"S"===Bt)return[M,et];if("W"===Bt||"E"===Bt)return[et,M]}(Bt.val,Wt.val,Bt.dim):[Bt.val,Wt.val]},ec.exports.format=format,ec.exports.formatPair=function formatPair(M){return format(M.lat,"lat")+" "+format(M.lon,"lon")},ec.exports.coordToDMS=coordToDMS;var dc=ec.exports,Ic=tc,fc=dc,yc=/(Lat)(itude)?/gi,vc=/(L)(on|ng)(gitude)?/i;function guessHeader(M,et){var Bt,Wt,Nt;for(var $t in M)(Wt=$t.match(et))&&(!Bt||Wt[0].length/$t.length>Nt)&&(Nt=Wt[0].length/$t.length,Bt=$t);return Bt}function guessLatHeader(M){return guessHeader(M,yc)}function guessLonHeader(M){return guessHeader(M,vc)}function keyCount(M){return"object"==typeof M?Object.keys(M).length:0}function autoDelimiter(M){var et=[];return[",",";","\t","|"].forEach((function(Bt){var Wt=Ic.dsvFormat(Bt).parse(M);if(Wt.length>=1){for(var Nt=keyCount(Wt[0]),$t=0;$t{Bt[Wt]=M}));return Bt}function isElement(M){return 1===M?.nodeType}function getLineStyle(M){return get(M,"line",(M=>Object.assign({},val1(M,"color",(M=>({stroke:`#${M}`}))),$num(M,"opacity",(M=>({"stroke-opacity":M}))),$num(M,"width",(M=>({"stroke-width":96*M/25.4}))))))}function getExtensions(M){let et=[];if(null===M)return et;for(const Bt of Array.from(M.childNodes)){if(!isElement(Bt))continue;const M=abbreviateName(Bt.nodeName);if("gpxtpx:TrackPointExtension"===M)et=et.concat(getExtensions(Bt));else{const Wt=nodeVal(Bt);et.push([M,parseNumeric(Wt)])}}return et}function abbreviateName(M){return["heart","gpxtpx:hr","hr"].includes(M)?"heart":M}function parseNumeric(M){const et=parseFloat(M);return isNaN(et)?M:et}function coordPair$1(M){const et=[parseFloat(M.getAttribute("lon")||""),parseFloat(M.getAttribute("lat")||"")];if(isNaN(et[0])||isNaN(et[1]))return null;num1(M,"ele",(M=>{et.push(M)}));const Bt=get1(M,"time");return{coordinates:et,time:Bt?nodeVal(Bt):null,extendedValues:getExtensions(get1(M,"extensions"))}}function extractProperties(M){const et=getMulti(M,["name","cmt","desc","type","time","keywords"]),Bt=Array.from(M.getElementsByTagNameNS("http://www.garmin.com/xmlschemas/GpxExtensions/v3","*"));for(const Wt of Bt)Wt.parentNode?.parentNode===M&&(et[Wt.tagName.replace(":","_")]=nodeVal(Wt));const Wt=$(M,"link");return Wt.length&&(et.links=Wt.map((M=>Object.assign({href:M.getAttribute("href")},getMulti(M,["text","type"]))))),et}function getPoints$1(M,et){const Bt=$(M,et),Wt=[],Nt=[],$t={};for(let M=0;M1,Gr=Object.assign({_gpxType:"trk"},extractProperties(M),getLineStyle(get1(M,"extensions")),Wt.length?{coordinateProperties:{times:$t?Wt:Wt[0]}}:{});for(const M of Nt){Bt.push(M.line),Gr.coordinateProperties||(Gr.coordinateProperties={});const et=Gr.coordinateProperties,Wt=Object.entries(M.extendedValues);for(let M=0;Mnew Array(M.line.length).fill(null)))),et[Bt][M]=Gr):et[Bt]=Gr}}return{type:"Feature",properties:Gr,geometry:$t?{type:"MultiLineString",coordinates:Bt}:{type:"LineString",coordinates:Bt[0]}}}function getPoint(M){const et=Object.assign(extractProperties(M),getMulti(M,["sym"])),Bt=coordPair$1(M);return Bt?{type:"Feature",properties:et,geometry:{type:"Point",coordinates:Bt.coordinates}}:null}function*gpxGen(M){for(const et of $(M,"trk")){const M=getTrack(et);M&&(yield M)}for(const et of $(M,"rte")){const M=getRoute(et);M&&(yield M)}for(const et of $(M,"wpt")){const M=getPoint(et);M&&(yield M)}}const Bc=[["heartRate","heartRates"],["Cadence","cadences"],["Speed","speeds"],["Watts","watts"]],Tc=[["TotalTimeSeconds","totalTimeSeconds"],["DistanceMeters","distanceMeters"],["MaximumSpeed","maxSpeed"],["AverageHeartRateBpm","avgHeartRate"],["MaximumHeartRateBpm","maxHeartRate"],["AvgSpeed","avgSpeed"],["AvgWatts","avgWatts"],["MaxWatts","maxWatts"]];function getProperties(M,et){const Bt=[];for(const[Wt,Nt]of et){let et=get1(M,Wt);if(!et){const Bt=M.getElementsByTagNameNS("http://www.garmin.com/xmlschemas/ActivityExtension/v2",Wt);Bt.length&&(et=Bt[0])}const $t=parseFloat(nodeVal(et));isNaN($t)||Bt.push([Nt,$t])}return Bt}function coordPair(M){const et=[num1(M,"LongitudeDegrees"),num1(M,"LatitudeDegrees")];if(void 0===et[0]||isNaN(et[0])||void 0===et[1]||isNaN(et[1]))return null;const Bt=get1(M,"HeartRateBpm"),Wt=nodeVal(get1(M,"Time"));return get1(M,"AltitudeMeters",(M=>{const Bt=parseFloat(nodeVal(M));isNaN(Bt)||et.push(Bt)})),{coordinates:et,time:Wt||null,heartRate:Bt?parseFloat(nodeVal(Bt)):null,extensions:getProperties(M,Bc)}}function getPoints(M){const et=$(M,"Trackpoint"),Bt=[],Wt=[],Nt=[];if(et.length<2)return null;const $t={},Gr={extendedProperties:$t};for(let M=0;M({name:nodeVal(M)}))));for(const M of et)Gr=getPoints(M),Gr&&(Bt.push(Gr.line),Gr.times.length&&Wt.push(Gr.times),Gr.heartRates.length&&Nt.push(Gr.heartRates),$t.push(Gr.extendedProperties));for(let M=0;M<$t.length;M++){const Wt=$t[M];for(const Nt in Wt)1===et.length?Gr&&(mn[Nt]=Gr.extendedProperties[Nt]):(mn[Nt]||(mn[Nt]=Bt.map((M=>Array(M.length).fill(null)))),mn[Nt][M]=Wt[Nt])}return 0===Bt.length?null:((Wt.length||Nt.length)&&(mn.coordinateProperties=Object.assign(Wt.length?{times:1===Bt.length?Wt[0]:Wt}:{},Nt.length?{heart:1===Bt.length?Nt[0]:Nt}:{})),{type:"Feature",properties:mn,geometry:1===Bt.length?{type:"LineString",coordinates:Bt[0]}:{type:"MultiLineString",coordinates:Bt}})}function*tcxGen(M){for(const et of $(M,"Lap")){const M=getLap(et);M&&(yield M)}for(const et of $(M,"Courses")){const M=getLap(et);M&&(yield M)}}function fixColor(M,et){const Bt={},Wt="stroke"==et||"fill"===et?et:et+"-color";return"#"===M[0]&&(M=M.substring(1)),6===M.length||3===M.length?Bt[Wt]="#"+M:8===M.length&&(Bt[et+"-opacity"]=parseInt(M.substring(0,2),16)/255,Bt[Wt]="#"+M.substring(6,8)+M.substring(4,6)+M.substring(2,4)),Bt}function numericProperty(M,et,Bt){const Wt={};return num1(M,et,(M=>{Wt[Bt]=M})),Wt}function getColor(M,et){return get(M,"color",(M=>fixColor(nodeVal(M),et)))}function extractIconHref(M){return get(M,"Icon",((M,et)=>(val1(M,"href",(M=>{et.icon=M})),et)))}function extractStyle(M){return Object.assign({},function extractPoly(M){return get(M,"PolyStyle",((M,et)=>Object.assign(et,get(M,"color",(M=>fixColor(nodeVal(M),"fill"))),val1(M,"fill",(M=>{if("0"===M)return{"fill-opacity":0}})),val1(M,"outline",(M=>{if("0"===M)return{"stroke-opacity":0}})))))}(M),function extractLine(M){return get(M,"LineStyle",(M=>Object.assign(getColor(M,"stroke"),numericProperty(M,"width","stroke-width"))))}(M),function extractLabel(M){return get(M,"LabelStyle",(M=>Object.assign(getColor(M,"label"),numericProperty(M,"scale","label-scale"))))}(M),function extractIcon(M){return get(M,"IconStyle",(M=>Object.assign(getColor(M,"icon"),numericProperty(M,"scale","icon-scale"),numericProperty(M,"heading","icon-heading"),get(M,"hotSpot",(M=>{const et=parseFloat(M.getAttribute("x")||""),Bt=parseFloat(M.getAttribute("y")||""),Wt=M.getAttribute("xunits")||"",Nt=M.getAttribute("yunits")||"";return isNaN(et)||isNaN(Bt)?{}:{"icon-offset":[et,Bt],"icon-offset-units":[Wt,Nt]}})),extractIconHref(M))))}(M))}const toNumber=M=>Number(M),Mc={string:M=>M,int:toNumber,uint:toNumber,short:toNumber,ushort:toNumber,float:toNumber,double:toNumber,bool:M=>Boolean(M)};function extractExtendedData(M,et){return get(M,"ExtendedData",((M,Bt)=>{for(const et of $(M,"Data"))Bt[et.getAttribute("name")||""]=nodeVal(get1(et,"value"));for(const Wt of $(M,"SimpleData")){const M=Wt.getAttribute("name")||"",Nt=et[M]||Mc.string;Bt[M]=Nt(nodeVal(Wt))}return Bt}))}function getMaybeHTMLDescription(M){const et=get1(M,"description");for(const M of Array.from(et?.childNodes||[]))if(4===M.nodeType)return{description:{"@type":"html",value:nodeVal(M)}};return{}}function extractTimeSpan(M){return get(M,"TimeSpan",(M=>({timespan:{begin:nodeVal(get1(M,"begin")),end:nodeVal(get1(M,"end"))}})))}function extractTimeStamp(M){return get(M,"TimeStamp",(M=>({timestamp:nodeVal(get1(M,"when"))})))}function extractCascadedStyle(M,et){return val1(M,"styleUrl",(M=>(M=normalizeId(M),et[M]?Object.assign({styleUrl:M},et[M]):{styleUrl:M})))}const Vc=/\s*/g,zc=/^\s*|\s*$/g,Fc=/\s+/;function coord1(M){return M.replace(Vc,"").split(",").map(parseFloat).filter((M=>!isNaN(M))).slice(0,3)}function coord(M){return M.replace(zc,"").split(Fc).map(coord1).filter((M=>M.length>=2))}function gxCoords(M){let et=$(M,"coord");0===et.length&&(et=function $ns(M,et,Bt){return Array.from(M.getElementsByTagNameNS(Bt,et))}(M,"coord","*"));const Bt=et.map((M=>nodeVal(M).split(" ").map(parseFloat)));return 0===Bt.length?null:{geometry:Bt.length>2?{type:"LineString",coordinates:Bt}:{type:"Point",coordinates:Bt[0]},times:$(M,"when").map((M=>nodeVal(M)))}}function fixRing(M){if(0===M.length)return M;const et=M[0],Bt=M[M.length-1];let Wt=!0;for(let M=0;M=2&&et.push({type:"Point",coordinates:M});break}case"LinearRing":case"LineString":{const M=coord(getCoordinates(Nt));M.length>=2&&et.push({type:"LineString",coordinates:M});break}case"Polygon":{const M=[];for(const et of $(Nt,"LinearRing")){const Bt=fixRing(coord(getCoordinates(et)));Bt.length>=4&&M.push(Bt)}M.length&&et.push({type:"Polygon",coordinates:M});break}case"Track":case"gx:Track":{const M=gxCoords(Nt);if(!M)break;const{times:Wt,geometry:$t}=M;et.push($t),Wt.length&&Bt.push(Wt);break}}}return{geometries:et,coordTimes:Bt}}function getPlacemark(M,et,Bt,Wt){const{coordTimes:Nt,geometries:$t}=getGeometry(M),Gr=function geometryListToGeometry(M){return 0===M.length?null:1===M.length?M[0]:{type:"GeometryCollection",geometries:M}}($t);if(!Gr&&Wt.skipNullGeometry)return null;const mn={type:"Feature",geometry:Gr,properties:Object.assign(getMulti(M,["name","address","visibility","open","phoneNumber","description"]),getMaybeHTMLDescription(M),extractCascadedStyle(M,et),extractStyle(M),extractExtendedData(M,Bt),extractTimeSpan(M),extractTimeStamp(M),Nt.length?{coordinateProperties:{times:1===Nt.length?Nt[0]:Nt}}:{})};void 0!==mn.properties?.visibility&&(mn.properties.visibility="0"!==mn.properties.visibility);const Hn=M.getAttribute("id");return null!==Hn&&""!==Hn&&(mn.id=Hn),mn}function getGroundOverlayBox(M){if(get1(M,"gx:LatLonQuad")){return{geometry:{type:"Polygon",coordinates:[fixRing(coord(getCoordinates(M)))]}}}return function getLatLonBox(M){const et=get1(M,"LatLonBox");if(et){const M=num1(et,"north"),Bt=num1(et,"west"),Wt=num1(et,"east"),Nt=num1(et,"south"),$t=num1(et,"rotation");if("number"==typeof M&&"number"==typeof Nt&&"number"==typeof Bt&&"number"==typeof Wt){const et=[Bt,Nt,Wt,M];let Gr=[[[Bt,M],[Wt,M],[Wt,Nt],[Bt,Nt],[Bt,M]]];return"number"==typeof $t&&(Gr=function rotateBox(M,et,Bt){const Wt=[(M[0]+M[2])/2,(M[1]+M[3])/2];return[et[0].map((M=>{const et=M[1]-Wt[1],Nt=M[0]-Wt[0],$t=Math.sqrt(Math.pow(et,2)+Math.pow(Nt,2)),Gr=Math.atan2(et,Nt)+Bt*Oc;return[Wt[0]+Math.cos(Gr)*$t,Wt[1]+Math.sin(Gr)*$t]}))]}(et,Gr,$t)),{bbox:et,geometry:{type:"Polygon",coordinates:Gr}}}}return null}(M)}const Oc=Math.PI/180;function getGroundOverlay(M,et,Bt,Wt){const Nt=getGroundOverlayBox(M),$t=Nt?.geometry||null;if(!$t&&Wt.skipNullGeometry)return null;const Gr={type:"Feature",geometry:$t,properties:Object.assign({"@geometry-type":"groundoverlay"},getMulti(M,["name","address","visibility","open","phoneNumber","description"]),getMaybeHTMLDescription(M),extractCascadedStyle(M,et),extractStyle(M),extractIconHref(M),extractExtendedData(M,Bt),extractTimeSpan(M),extractTimeStamp(M))};Nt?.bbox&&(Gr.bbox=Nt.bbox),void 0!==Gr.properties?.visibility&&(Gr.properties.visibility="0"!==Gr.properties.visibility);const mn=M.getAttribute("id");return null!==mn&&""!==mn&&(Gr.id=mn),Gr}function getStyleId(M){let et=M.getAttribute("id");const Bt=M.parentNode;return!et&&isElement(Bt)&&"CascadingStyle"===Bt.localName&&(et=Bt.getAttribute("kml:id")||Bt.getAttribute("id")),normalizeId(et||"")}function buildStyleMap(M){const et={};for(const Bt of $(M,"Style"))et[getStyleId(Bt)]=extractStyle(Bt);for(const Bt of $(M,"StyleMap")){const M=normalizeId(Bt.getAttribute("id")||"");val1(Bt,"styleUrl",(Bt=>{Bt=normalizeId(Bt),et[Bt]&&(et[M]=et[Bt])}))}return et}function buildSchema(M){const et={};for(const Bt of $(M,"SimpleField"))et[Bt.getAttribute("name")||""]=Mc[Bt.getAttribute("type")||""]||Mc.string;return et}const jc=["name","visibility","open","address","description","phoneNumber","visibility"];function*kmlGen(M,et={skipNullGeometry:!1}){const Bt=buildStyleMap(M),Wt=buildSchema(M);for(const Nt of $(M,"Placemark")){const M=getPlacemark(Nt,Bt,Wt,et);M&&(yield M)}for(const Nt of $(M,"GroundOverlay")){const M=getGroundOverlay(Nt,Bt,Wt,et);M&&(yield M)}}var mh=Object.freeze({__proto__:null,gpx:function gpx(M){return{type:"FeatureCollection",features:Array.from(gpxGen(M))}},gpxGen:gpxGen,kml:function kml(M,et={skipNullGeometry:!1}){return{type:"FeatureCollection",features:Array.from(kmlGen(M,et))}},kmlGen:kmlGen,kmlWithFolders:function kmlWithFolders(M,et={skipNullGeometry:!1}){const Bt=buildStyleMap(M),Wt=buildSchema(M),Nt={type:"root",children:[]};return function traverse(M,et,Nt){if(isElement(M))switch(M.tagName){case"GroundOverlay":{const $t=getGroundOverlay(M,Bt,Wt,Nt);$t&&et.children.push($t);break}case"Placemark":{const $t=getPlacemark(M,Bt,Wt,Nt);$t&&et.children.push($t);break}case"Folder":{const Bt=function getFolder(M){const et={};for(const Bt of Array.from(M.childNodes))isElement(Bt)&&jc.includes(Bt.tagName)&&(et[Bt.tagName]=nodeVal(Bt));return{type:"folder",meta:et,children:[]}}(M);et.children.push(Bt),et=Bt;break}}if(M.childNodes)for(let Bt=0;Bt=0?1:-1)}function encode(M,et,Bt){var Wt=2*((M=py2_round(M*Bt))-(et=py2_round(et*Bt)));Wt<0&&(Wt=-Wt-1);for(var Nt="";Wt>=32;)Nt+=String.fromCharCode(63+(32|31&Wt)),Wt/=32;return Nt+=String.fromCharCode(63+(0|Wt))}function flipped(M){for(var et=[],Bt=0;Bt=32);Bt=1&Hn?(-Hn-1)/2:Hn/2,mn=1,Hn=0;do{Hn+=(31&(so=M.charCodeAt(Wt++)-63))*mn,mn*=32}while(so>=32);Nt+=Bt,$t+=1&Hn?(-Hn-1)/2:Hn/2,Gr.push([Nt/uo,$t/uo])}return Gr},et.encode=function(M,et){if(!M.length)return"";for(var Bt=Math.pow(10,Number.isInteger(et)?et:5),Wt=encode(M[0][0],0,Bt)+encode(M[0][1],0,Bt),Nt=1;Nt{const first=M=>M[0],last=M=>M[M.length-1],coordsToKey=M=>M.join(","),addToMap=(M,et,Bt)=>{let Wt=M[et];Wt?Wt.push(Bt):M[et]=[Bt]},removeFromMap=(M,et,Bt)=>{let Wt=M[et],Nt=null;Wt&&(Nt=Wt.indexOf(Bt))>=0&&Wt.splice(Nt,1)},getFirstFromMap=(M,et)=>{let Bt=M[et];return Bt&&Bt.length>0?Bt[0]:null},isRing=M=>M.length>3&&coordsToKey(first(M))===coordsToKey(last(M)),ringDirection=(M,et,Bt)=>{et=et||0,Bt=Bt||1;let Wt=M.reduce(((Bt,Wt,Nt)=>M[Bt][et]>Wt[et]?Bt:Nt),0),Nt=Wt<=0?M.length-2:Wt-1,$t=Wt>=M.length-1?1:Wt+1,Gr=M[Nt][et],mn=M[Wt][et],Hn=M[$t][et],so=M[Nt][Bt],uo=M[Wt][Bt];return(mn-Gr)*(M[$t][Bt]-so)-(Hn-Gr)*(uo-so)<0?"clockwise":"counterclockwise"},strToFloat=M=>M instanceof Array?M.map(strToFloat):parseFloat(M);class RefElements extends Map{constructor(){super(),this.binders=[]}add(M,et){this.has(M)||this.set(M,et)}addBinder(M){this.binders.push(M)}bindAll(){this.binders.forEach((M=>M.bind()))}}return{purgeProps:(M,et)=>{if(M){let Bt=Object.assign({},M);if(et)for(let M of et)delete Bt[M];return Bt}return{}},mergeProps:(M,et)=>(M=M||{},et=et||{},Object.assign(M,et)),first:first,last:last,coordsToKey:coordsToKey,addToMap:addToMap,removeFromMap:removeFromMap,getFirstFromMap:getFirstFromMap,isRing:isRing,ringDirection:ringDirection,ptInsidePolygon:(M,et,Bt,Wt)=>{Bt=Bt||0,Wt=Wt||1;let Nt=!1;for(let $t=0,Gr=et.length-1;$t=0){let Bt=[et,1];M&&Bt.push(M),[].splice.apply(this.container,Bt)}}else if("object"==typeof this.container){let et=Object.keys(this.container).find((M=>this.container[M]===this));et&&(M?this.container[et]=M:delete this.container[et])}}},WayCollection:class WayCollection extends Array{constructor(){super(),this.firstMap={},this.lastMap={}}addWay(M){(M=M.toCoordsArray()).length>0&&(this.push(M),addToMap(this.firstMap,coordsToKey(first(M)),M),addToMap(this.lastMap,coordsToKey(last(M)),M))}toStrings(){let M=[],et=null;for(;et=this.shift();){removeFromMap(this.firstMap,coordsToKey(first(et)),et),removeFromMap(this.lastMap,coordsToKey(last(et)),et);let Bt=et,Wt=null;do{let M=coordsToKey(last(Bt)),et=!1;Wt=getFirstFromMap(this.firstMap,M),Wt||(Wt=getFirstFromMap(this.lastMap,M),et=!0),Wt&&(this.splice(this.indexOf(Wt),1),removeFromMap(this.firstMap,coordsToKey(first(Wt)),Wt),removeFromMap(this.lastMap,coordsToKey(last(Wt)),Wt),et&&(Wt.length>Bt.length&&([Bt,Wt]=[Wt,Bt]),Wt.reverse()),Bt=Bt.concat(Wt.slice(1)))}while(Wt);M.push(strToFloat(Bt))}return M}toRings(M){let et=this.toStrings(),Bt=[],Wt=null;for(;Wt=et.shift();)isRing(Wt)&&(ringDirection(Wt)!==M&&Wt.reverse(),Bt.push(Wt));return Bt}}}})(),Ph={building:{},highway:{whitelist:["services","rest_area","escape","elevator"]},natural:{blacklist:["coastline","cliff","ridge","arete","tree_row"]},landuse:{},waterway:{whitelist:["riverbank","dock","boatyard","dam"]},amenity:{},leisure:{},barrier:{whitelist:["city_wall","ditch","hedge","retaining_wall","wall","spikes"]},railway:{whitelist:["station","turntable","roundhouse","platform"]},area:{},boundary:{},man_made:{blacklist:["cutline","embankment","pipeline"]},power:{whitelist:["plant","substation","generator","transformer"]},place:{},shop:{},aeroway:{blacklist:["taxiway"]},tourism:{},historic:{},public_transport:{},office:{},"building:part":{},military:{},ruins:{},"area:highway":{},craft:{},golf:{},indoor:{}},Wh=(()=>{const{first:M,last:et,coordsToKey:Bt,addToMap:Wt,removeFromMap:Nt,getFirstFromMap:$t,isRing:Gr,ringDirection:mn,ptInsidePolygon:Hn,strToFloat:so,LateBinder:uo,WayCollection:Io}=Gh,Po=Ph;class OsmObject{constructor(M,et,Bt){this.type=M,this.id=et,this.refElems=Bt,this.tags={},this.props={id:this.getCompositeId()},this.refCount=0,this.hasTag=!1,Bt&&Bt.add(this.getCompositeId(),this)}addTags(M){this.tags=Object.assign(this.tags,M),this.hasTag=!!M}addTag(M,et){this.tags[M]=et,this.hasTag=!!M}addProp(M,et){this.props[M]=et}addProps(M){this.props=Object.assign(this.props,M)}getCompositeId(){return`${this.type}/${this.id}`}getProps(){return Object.assign(this.props,this.tags)}toFeatureArray(){return[]}}class Node extends OsmObject{constructor(M,et){super("node",M,et),this.latLng=null}setLatLng(M){this.latLng=M}toFeatureArray(){return this.latLng?[{type:"Feature",id:this.getCompositeId(),properties:this.getProps(),geometry:{type:"Point",coordinates:so([this.latLng.lon,this.latLng.lat])}}]:[]}getLatLng(){return this.latLng}}class Way extends OsmObject{constructor(M,et){super("way",M,et),this.latLngArray=[],this.isPolygon=!1}addLatLng(M){this.latLngArray.push(M)}setLatLngArray(M){this.latLngArray=M}addNodeRef(M){let et=new uo(this.latLngArray,(function(M){let et=this.refElems.get(`node/${M}`);if(et)return et.refCount++,et.getLatLng()}),this,[M]);this.latLngArray.push(et),this.refElems.addBinder(et)}analyzeGeometryType(M,et){let Bt=Po[M];Bt&&(this.isPolygon=!0,Bt.whitelist?this.isPolygon=Bt.whitelist.indexOf(et)>=0:Bt.blacklist&&(this.isPolygon=!(Bt.blacklist.indexOf(et)>=0)))}addTags(M){super.addTags(M);for(let[et,Bt]of Object.entries(M))this.analyzeGeometryType(et,Bt)}addTag(M,et){super.addTag(M,et),this.analyzeGeometryType(M,et)}toCoordsArray(){return this.latLngArray.map((M=>[M.lon,M.lat]))}toFeatureArray(){let M=this.toCoordsArray();if(M.length>1){M=so(M);let et={type:"Feature",id:this.getCompositeId(),properties:this.getProps(),geometry:{type:"LineString",coordinates:M}};return this.isPolygon&&Gr(M)?("counterclockwise"!==mn(M)&&M.reverse(),et.geometry={type:"Polygon",coordinates:[M]},[et]):[et]}return[]}}return{Node:Node,Way:Way,Relation:class Relation extends OsmObject{constructor(M,et){super("relation",M,et),this.relations=[],this.nodes=[],this.bounds=null}setBounds(M){this.bounds=M}addMember(M){switch(M.type){case"relation":let et=new uo(this.relations,(function(M){let et=this.refElems.get(`relation/${M}`);if(et)return et.refCount++,et}),this,[M.ref]);this.relations.push(et),this.refElems.addBinder(et);break;case"way":M.role||(M.role="");let Bt=this[M.role];if(Bt||(Bt=this[M.role]=[]),M.geometry){let et=new Way(M.ref,this.refElems);et.setLatLngArray(M.geometry),et.refCount++,Bt.push(et)}else if(M.nodes){let et=new Way(M.ref,this.refElems);for(let Bt of M.nodes)et.addNodeRef(Bt);et.refCount++,Bt.push(et)}else{let et=new uo(Bt,(function(M){let et=this.refElems.get(`way/${M}`);if(et)return et.refCount++,et}),this,[M.ref]);Bt.push(et),this.refElems.addBinder(et)}break;case"node":let Wt=null;if(M.lat&&M.lon){Wt=new Node(M.ref,this.refElems),Wt.setLatLng({lon:M.lon,lat:M.lat}),M.tags&&Wt.addTags(M.tags);for(let[et,Bt]of Object.entries(M))["id","type","lat","lon"].indexOf(et)<0&&Wt.addProp(et,Bt);Wt.refCount++,this.nodes.push(Wt)}else{let et=new uo(this.nodes,(function(M){let et=this.refElems.get(`node/${M}`);if(et)return et.refCount++,et}),this,[M.ref]);this.nodes.push(et),this.refElems.addBinder(et)}}}toFeatureArray(){let et=[],Bt=[],Wt=[];const Nt=["outer","inner",""];for(let M of this.relations)if(M)for(let et of Nt){let Bt=M[et];if(Bt){let M=this[et];M?[].splice.apply(M,[M.length,0].concat(Bt)):this[et]=Bt}}for(let M of Nt){let et=this[M];if(et){this[M]=new Io;for(let Bt of et)this[M].addWay(Bt)}}let $t=null,Gr={type:"Feature",id:this.getCompositeId(),bbox:this.bounds,properties:this.getProps()};this.bounds||delete Gr.bbox,this.outer?($t=((et,Bt)=>{let Wt=et?et.toRings("counterclockwise"):[],Nt=Bt?Bt.toRings("clockwise"):[];if(Wt.length>0){let et=[],Bt=null;for(Bt of Wt)et.push([Bt]);for(;Bt=Nt.shift();)for(let Nt in Wt)if(Hn(M(Bt),Wt[Nt])){et[Nt].push(Bt);break}return 1===et.length?{type:"Polygon",coordinates:et[0]}:{type:"MultiPolygon",coordinates:et}}return null})(this.outer,this.inner),$t&&(Gr.geometry=$t,et.push(Gr))):this[""]&&($t=(M=>{let et=M?M.toStrings():[];return et.length>0?1===et.length?{type:"LineString",coordinates:et[0]}:{type:"MultiLineString",coordinates:et}:null})(this[""]),$t&&(Gr.geometry=$t,Bt.push(Gr)));for(let M of this.nodes)Wt=Wt.concat(M.toFeatureArray());return et.concat(Bt).concat(Wt)}}}})(),zh=(()=>{function conditioned(M){return null!=M.match(/^(.+?)\[(.+?)\]>$/g)}function parseEvent(M){let et=/^(.+?)\[(.+?)\]>$/g.exec(M);return et?{evt:et[1]+">",exp:et[2]}:{evt:M}}return class{constructor(M){M&&(this.queryParent=!!M.queryParent,this.progressive=M.progressive,this.queryParent&&(this.parentMap=new WeakMap)),this.evtListeners={}}parse(M,et,Bt){Bt=Bt?Bt+".":"";let Wt=/<([^ >\/]+)(.*?)>/gm,Nt=null,$t=[];for(;Nt=Wt.exec(M);){let Gr=Nt[1],mn={$tag:Gr},Hn=Bt+Gr,so=Nt[2].trim(),uo=!1;(so.endsWith("/")||Gr.startsWith("?")||Gr.startsWith("!"))&&(uo=!0);let Io=/([^ ]+?)="(.+?)"/g,Po=/([^ ]+?)='(.+?)'/g,To=null,Eo=!1;for(;To=Io.exec(so);)Eo=!0,mn[To[1]]=To[2];if(!Eo)for(;To=Po.exec(so);)Eo=!0,mn[To[1]]=To[2];if(Eo||""===so||(mn.text=so),this.progressive&&this.emit(`<${Hn}>`,mn,et),!uo){let et=new RegExp(`([^]+?)`,"g");et.lastIndex=Wt.lastIndex;let Bt=et.exec(M);if(Bt&&Bt[1]){Wt.lastIndex=et.lastIndex;let M=this.parse(Bt[1],mn,Hn);M.length>0?mn.$innerNodes=M:mn.$innerText=Bt[1]}}this.queryParent&&et&&this.parentMap.set(mn,et),this.progressive&&this.emit(``,mn,et),$t.push(mn)}return $t}getParent(M){return this.queryParent?this.parentMap.get(M):null}#t(M,et){let Bt=this.evtListeners[M];Bt?Bt.push(et):this.evtListeners[M]=[et]}addListener(M,et){conditioned(M)&&(M=parseEvent(M),et.condition=function genConditionFunc(M){let et="return "+M.replace(/(\$.+?)(?=[=!.])/g,"node.$&")+";";return new Function("node",et)}(M.exp),M=M.evt),this.#t(M,et)}#e(M,et){let Bt=this.evtListeners[M],Wt=null;Bt&&(Wt=Bt.indexOf(et))>=0&&Bt.splice(Wt,1)}removeListener(M,et){conditioned(M)&&(M=(M=parseEvent(M)).evt),this.#e(M,et)}emit(M,...et){let Bt=this.evtListeners[M];if(Bt)for(let M of Bt)M.condition?!0===M.condition.apply(null,et)&&M.apply(null,et):M.apply(null,et)}on(M,et){this.addListener(M,et)}off(M,et){this.removeListener(M,et)}}})();const{Node:Jh,Way:Xh,Relation:Lh}=Wh,{purgeProps:Hh,RefElements:Kh}=Gh,Yh=zh;var lib=(M,et)=>{let Bt=!1,Wt=!1,Nt=!0;(M=>{if(M){Bt=!(!M.completeFeature&&!M.allFeatures),Wt=!!M.renderTagged;let et=M.suppressWay||M.excludeWay;void 0===et||et||(Nt=!1)}})(et);let $t=(M=>M.elements?"json":M.indexOf("=0?"xml":M.trim().startsWith("{")?"json-raw":"invalid")(M),Gr=new Kh,mn=[];"json-raw"===$t&&($t=(M=JSON.parse(M)).elements?"json":"invalid"),"json"===$t?(M=>{for(let et of M.elements)switch(et.type){case"node":let M=new Jh(et.id,Gr);et.tags&&M.addTags(et.tags),M.addProps(Hh(et,["id","type","tags","lat","lon"])),M.setLatLng(et);break;case"way":let Bt=new Xh(et.id,Gr);if(et.tags&&Bt.addTags(et.tags),Bt.addProps(Hh(et,["id","type","tags","nodes","geometry"])),et.nodes)for(let M of et.nodes)Bt.addNodeRef(M);else et.geometry&&Bt.setLatLngArray(et.geometry);break;case"relation":let Wt=new Lh(et.id,Gr);if(et.bounds&&Wt.setBounds([parseFloat(et.bounds.minlon),parseFloat(et.bounds.minlat),parseFloat(et.bounds.maxlon),parseFloat(et.bounds.maxlat)]),et.tags&&Wt.addTags(et.tags),Wt.addProps(Hh(et,["id","type","tags","bounds","members"])),et.members)for(let M of et.members)Wt.addMember(M)}})(M):"xml"===$t&&(M=>{const et=new Yh({progressive:!0});et.on("",(M=>{let et=new Jh(M.id,Gr);for(let[Bt,Wt]of Object.entries(M))!Bt.startsWith("$")&&["id","lon","lat"].indexOf(Bt)<0&&et.addProp(Bt,Wt);if(et.setLatLng(M),M.$innerNodes)for(let Bt of M.$innerNodes)"tag"===Bt.$tag&&et.addTag(Bt.k,Bt.v)})),et.on("",(M=>{let et=new Xh(M.id,Gr);for(let[Bt,Wt]of Object.entries(M))!Bt.startsWith("$")&&["id"].indexOf(Bt)<0&&et.addProp(Bt,Wt);if(M.$innerNodes)for(let Bt of M.$innerNodes)"nd"===Bt.$tag?Bt.lon&&Bt.lat?et.addLatLng(Bt):Bt.ref&&et.addNodeRef(Bt.ref):"tag"===Bt.$tag&&et.addTag(Bt.k,Bt.v)})),et.on("",(M=>{new Lh(M.id,Gr)})),et.on("",((M,et)=>{let Bt=Gr.get(`relation/${et.id}`),Wt={type:M.type,role:M.role?M.role:"",ref:M.ref};if(M.lat&&M.lon){Wt.lat=M.lat,Wt.lon=M.lon,Wt.tags={};for(let[et,Bt]of Object.entries(M))!et.startsWith("$")&&["type","lat","lon"].indexOf(et)<0&&(Wt[et]=Bt)}if(M.$innerNodes){let et=[],Bt=[];for(let Wt of M.$innerNodes)Wt.lat&&Wt.lon?et.push(Wt):Bt.push(Wt.ref);et.length>0?Wt.geometry=et:Bt.length>0&&(Wt.nodes=Bt)}Bt.addMember(Wt)})),et.on("",((M,et)=>{Gr.get(`relation/${et.id}`).setBounds([parseFloat(M.minlon),parseFloat(M.minlat),parseFloat(M.maxlon),parseFloat(M.maxlat)])})),et.on("",((M,et)=>{Gr.get(`relation/${et.id}`).addTag(M.k,M.v)})),et.parse(M)})(M),Gr.bindAll();for(let M of Gr.values())if(M.refCount<=0||M.hasTag&&Wt&&!(M instanceof Xh&&Nt)){let et=M.toFeatureArray();if(M instanceof Lh&&!Bt&&et.length>0)return et[0].geometry;mn=mn.concat(et)}return{type:"FeatureCollection",features:mn}},Qh=getDefaultExportFromCjs(lib);const qh=["topojson","osm","kml","gpx","tcx","csv","tsv","polyline"];class Converter{constructor(M,et,Bt={}){this.blankGeoJSON=()=>({type:"FeatureCollection",features:[]}),this._rawData=et,this._format=M,this._options=Bt;const Wt={topojson:this.loadTopoJson,osm:this.loadOsm,kml:this.loadXml,gpx:this.loadXml,tcx:this.loadXml,csv:this.loadCsv,tsv:this.loadCsv,polyline:this.loadPolyline};this._conversionFn=Wt[M]}async convert(){return this._conversionFn?this._conversionFn():new Promise(((M,et)=>et(`No converter exists for ${this._format}`)))}async loadXml(){return mh[this._format]((new DOMParser).parseFromString(this._rawData,"text/xml"))}async loadCsv(){let M=this._options.csvOptions||{};"tsv"===this._format&&(M.delimiter="\t");return await new Promise(((et,Bt)=>{xc.csv2geojson(this._rawData,M,((M,Wt)=>{M?Bt(M):et(Wt)}))}))}async loadTopoJson(){let M={};try{M=JSON.parse(this._rawData)}catch(M){throw"Invalid TopoJson"}let et=this.blankGeoJSON();return"Topology"===M.type&&void 0!==M.objects&&(et={type:"FeatureCollection",features:et.features=Object.keys(M.objects).map((et=>function topojsonFeature(M,et){return"string"==typeof et&&(et=M.objects[et]),"GeometryCollection"===et.type?{type:"FeatureCollection",features:et.geometries.map((function(et){return feature(M,et)}))}:feature(M,et)}(M,et))).reduce(((M,et)=>[...M,...et.features]),[])}),et}async loadOsm(){return Qh(this._rawData)}async loadPolyline(){let M=this._options.polylineOptions||{};return await new Promise(((et,Bt)=>{try{const Bt=Zh.toGeoJSON(this._rawData,M.precision);let Wt=Bt;"point"===M.type?1===Bt.coordinates.length?Wt={type:"Point",coordinates:Bt.coordinates[0]}:console.warn("Cannot convert polyline to "+M.type):"polygon"===M.type&&(Bt.coordinates[0][0]===Bt.coordinates[Bt.coordinates.length-1][0]&&Bt.coordinates[0][1]===Bt.coordinates[Bt.coordinates.length-1][1]?Wt={type:"Polygon",coordinates:[Bt.coordinates]}:console.warn("Cannot convert polyline to "+M.type)),et({type:"FeatureCollection",features:[{type:"Feature",geometry:Wt,properties:M.properties||{}}]})}catch(M){Bt(M)}}))}}var tg=null;try{var eg="undefined"!=typeof module&&"function"==typeof module.require&&module.require("worker_threads")||"function"==typeof __non_webpack_require__&&__non_webpack_require__("worker_threads")||"function"==typeof require&&require("worker_threads");tg=eg.Worker}catch(e){}function createBase64WorkerFactory$2(M,et,Bt){var Wt=function decodeBase64$1(M,et){return Buffer.from(M,"base64").toString("utf8")}(M),Nt=Wt.indexOf("\n",10)+1,$t=Wt.substring(Nt)+"";return function WorkerFactory(M){return new tg($t,Object.assign({},M,{eval:!0}))}}function createURL(M,et,Bt){var Wt=function decodeBase64(M,et){return atob(M)}(M),Nt=Wt.indexOf("\n",10)+1,$t=Wt.substring(Nt)+"",Gr=new Blob([$t],{type:"application/javascript"});return URL.createObjectURL(Gr)}var ig="[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0);var rg=function createBase64WorkerFactory(M,et,Bt){return function isNodeJS(){return ig}()?createBase64WorkerFactory$2(M):function createBase64WorkerFactory$1(M,et,Bt){var Wt;return function WorkerFactory(et){return Wt=Wt||createURL(M),new Worker(Wt,et)}}(M)}("Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewoJJ3VzZSBzdHJpY3QnOwoKCWZ1bmN0aW9uIGdldERlZmF1bHRFeHBvcnRGcm9tQ2pzICh4KSB7CgkJcmV0dXJuIHggJiYgeC5fX2VzTW9kdWxlICYmIE9iamVjdC5wcm90b3R5cGUuaGFzT3duUHJvcGVydHkuY2FsbCh4LCAnZGVmYXVsdCcpID8geFsnZGVmYXVsdCddIDogeDsKCX0KCglmdW5jdGlvbiBnZXRBdWdtZW50ZWROYW1lc3BhY2UobikgewoJICBpZiAobi5fX2VzTW9kdWxlKSByZXR1cm4gbjsKCSAgdmFyIGYgPSBuLmRlZmF1bHQ7CgkJaWYgKHR5cGVvZiBmID09ICJmdW5jdGlvbiIpIHs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ZiAobnVtZXJpY0ZpZWxkcykgewoJICAgICAgICAgICAgICAgIGZvciAodmFyIGtleSBpbiBkKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmIChudW1lcmljRmllbGRzLmluY2x1ZGVzKGtleSkpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGRba2V5XSA9ICtkW2tleV07CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgICAgICByZXR1cm4gZDsKCSAgICAgICAgfSkgOiB4OwoKCSAgICBpZiAoIXBhcnNlZC5sZW5ndGgpIHsKCSAgICAgICAgY2FsbGJhY2sobnVsbCwgZmVhdHVyZWNvbGxlY3Rpb24pOwoJICAgICAgICByZXR1cm47CgkgICAgfQoKCSAgICB2YXIgZXJyb3JzID0gW107CgkgICAgdmFyIGk7CgoKCSAgICBpZiAoIWxhdGZpZWxkKSBsYXRmaWVsZCA9IGd1ZXNzTGF0SGVhZGVyKHBhcnNlZFswXSk7CgkgICAgaWYgKCFsb25maWVsZCkgbG9uZmllbGQgPSBndWVzc0xvbkhlYWRlcihwYXJzZWRbMF0pOwoJICAgIHZhciBub0dlb21ldHJ5ID0gKCFsYXRmaWVsZCB8fCAhbG9uZmllbGQpOwoKCSAgICBpZiAobm9HZW9tZXRyeSkgewoJICAgICAgICBmb3IgKGkgPSAwOyBpIDwgcGFyc2VkLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgICAgICBmZWF0dXJlcy5wdXNoKHsKCSAgICAgICAgICAgICAgICB0eXBlOiAnRmVhdHVyZScsCgkgICAgICAgICAgICAgICAgcHJvcGVydGllczogcGFyc2VkW2ldLAoJICAgICAgICAgICAgICAgIGdlb21ldHJ5OiBudWxsCgkgICAgICAgICAgICB9KTsKCSAgICAgICAgfQoJICAgICAgICBjYWxsYmFjayhlcnJvcnMubGVuZ3RoID8gZXJyb3JzIDogbnVsbCwgZmVhdHVyZWNvbGxlY3Rpb24pOwoJICAgICAgICByZXR1cm47CgkgICAgfQoKCSAgICBmb3IgKGkgPSAwOyBpIDwgcGFyc2VkLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgIGlmIChwYXJzZWRbaV1bbG9uZmllbGRdICE9PSB1bmRlZmluZWQgJiYKCSAgICAgICAgICAgIHBhcnNlZFtpXVtsYXRmaWVsZF0gIT09IHVuZGVmaW5lZCkgewoKCSAgICAgICAgICAgIHZhciBsb25rID0gcGFyc2VkW2ldW2xvbmZpZWxkXSwKCSAgICAgICAgICAgICAgICBsYXRrID0gcGFyc2VkW2ldW2xhdGZpZWxkXSwKCSAgICAgICAgICAgICAgICBsb25mLCBsYXRmLAoJICAgICAgICAgICAgICAgIGE7CgoJICAgICAgICAgICAgYSA9IHNleGFnZXNpbWFsKGxvbmssICdFVycpOwoJICAgICAgICAgICAgaWYgKGEpIGxvbmsgPSBhOwoJICAgICAgICAgICAgYSA9IHNleGFnZXNpbWFsKGxhdGssICdOUycpOwoJICAgICAgICAgICAgaWYgKGEpIGxhdGsgPSBhOwoKCSAgICAgICAgICAgIGxvbmYgPSBwYXJzZUZsb2F0KGxvbmspOwoJICAgICAgICAgICAgbGF0ZiA9IHBhcnNlRmxvYXQobGF0ayk7CgoJICAgICAgICAgICAgaWYgKGlzTmFOKGxvbmYpIHx8CgkgICAgICAgICAgICAgICAgaXNOYU4obGF0ZikpIHsKCSAgICAgICAgICAgICAgICBlcnJvcnMucHVzaCh7CgkgICAgICAgICAgICAgICAgICAgIG1lc3NhZ2U6ICdBIHJvdyBjb250YWluZWQgYW4gaW52YWxpZCB2YWx1ZSBmb3IgbGF0aXR1ZGUgb3IgbG9uZ2l0dWRlJywKCSAgICAgICAgICAgICAgICAgICAgcm93OiBwYXJzZWRbaV0sCgkgICAgICAgICAgICAgICAgICAgIGluZGV4OiBpCgkgICAgICAgICAgICAgICAgfSk7CgkgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgIGlmICghb3B0aW9ucy5pbmNsdWRlTGF0TG9uKSB7CgkgICAgICAgICAgICAgICAgICAgIGRlbGV0ZSBwYXJzZWRbaV1bbG9uZmllbGRdOwoJICAgICAgICAgICAgICAgICAgICBkZWxldGUgcGFyc2VkW2ldW2xhdGZpZWxkXTsKCSAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIGZlYXR1cmVzLnB1c2goewoJICAgICAgICAgICAgICAgICAgICB0eXBlOiAnRmVhdHVyZScsCgkgICAgICAgICAgICAgICAgICAgIHByb3BlcnRpZXM6IHBhcnNlZFtpXSwKCSAgICAgICAgICAgICAgICAgICAgZ2VvbWV0cnk6IHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICdQb2ludCcsCgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogWwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHBhcnNlRmxvYXQobG9uZiksCgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgcGFyc2VGbG9hdChsYXRmKQoJICAgICAgICAgICAgICAgICAgICAgICAgXQoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfSk7CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCSAgICB9CgoJICAgIGNhbGxiYWNrKGVycm9ycy5sZW5ndGggPyBlcnJvcnMgOiBudWxsLCBmZWF0dXJlY29sbGVjdGlvbik7Cgl9CgoJZnVuY3Rpb24gdG9MaW5lKGdqKSB7CgkgICAgdmFyIGZlYXR1cmVzID0gZ2ouZmVhdHVyZXM7CgkgICAgdmFyIGxpbmUgPSB7CgkgICAgICAgIHR5cGU6ICdGZWF0dXJlJywKCSAgICAgICAgZ2VvbWV0cnk6IHsKCSAgICAgICAgICAgIHR5cGU6ICdMaW5lU3RyaW5nJywKCSAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBbXQoJICAgICAgICB9CgkgICAgfTsKCSAgICBmb3IgKHZhciBpID0gMDsgaSA8IGZlYXR1cmVzLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgIGxpbmUuZ2VvbWV0cnkuY29vcmRpbmF0ZXMucHVzaChmZWF0dXJlc1tpXS5nZW9tZXRyeS5jb29yZGluYXRlcyk7CgkgICAgfQoJICAgIGxpbmUucHJvcGVydGllcyA9IGZlYXR1cmVzLnJlZHVjZShmdW5jdGlvbiAoYWdncmVnYXRlZFByb3BlcnRpZXMsIG5ld0ZlYXR1cmUpIHsKCSAgICAgICAgZm9yICh2YXIga2V5IGluIG5ld0ZlYXR1cmUucHJvcGVydGllcykgewoJICAgICAgICAgICAgaWYgKCFhZ2dyZWdhdGVkUHJvcGVydGllc1trZXldKSB7CgkgICAgICAgICAgICAgICAgYWdncmVnYXRlZFByb3BlcnRpZXNba2V5XSA9IFtdOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgYWdncmVnYXRlZFByb3BlcnRpZXNba2V5XS5wdXNoKG5ld0ZlYXR1cmUucHJvcGVydGllc1trZXldKTsKCSAgICAgICAgfQoJICAgICAgICByZXR1cm4gYWdncmVnYXRlZFByb3BlcnRpZXM7CgkgICAgfSwge30pOwoJICAgIHJldHVybiB7CgkgICAgICAgIHR5cGU6ICdGZWF0dXJlQ29sbGVjdGlvbicsCgkgICAgICAgIGZlYXR1cmVzOiBbbGluZV0KCSAgICB9OwoJfQoKCWZ1bmN0aW9uIHRvUG9seWdvbihnaikgewoJICAgIHZhciBmZWF0dXJlcyA9IGdqLmZlYXR1cmVzOwoJICAgIHZhciBwb2x5ID0gewoJICAgICAgICB0eXBlOiAnRmVhdHVyZScsCgkgICAgICAgIGdlb21ldHJ5OiB7CgkgICAgICAgICAgICB0eXBlOiAnUG9seWdvbicsCgkgICAgICAgICAgICBjb29yZGluYXRlczogW1tdXQoJICAgICAgICB9CgkgICAgfTsKCSAgICBmb3IgKHZhciBpID0gMDsgaSA8IGZlYXR1cmVzLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgIHBvbHkuZ2VvbWV0cnkuY29vcmRpbmF0ZXNbMF0ucHVzaChmZWF0d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MuY29vcmRpbmF0ZVByb3BlcnRpZXMpIHsKCSAgICAgICAgICAgIHByb3BlcnRpZXMuY29vcmRpbmF0ZVByb3BlcnRpZXMgPSB7fTsKCSAgICAgICAgfQoJICAgICAgICBjb25zdCBwcm9wcyA9IHByb3BlcnRpZXMuY29vcmRpbmF0ZVByb3BlcnRpZXM7CgkgICAgICAgIGNvbnN0IGVudHJpZXMgPSBPYmplY3QuZW50cmllcyhsaW5lLmV4dGVuZGVkVmFsdWVzKTsKCSAgICAgICAgZm9yIChsZXQgaSA9IDA7IGkgPCBlbnRyaWVzLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgICAgICBjb25zdCBbbmFtZSwgdmFsXSA9IGVudHJpZXNbaV07CgkgICAgICAgICAgICBpZiAobXVsdGkpIHsKCSAgICAgICAgICAgICAgICBpZiAoIXByb3BzW25hbWVdKSB7CgkgICAgICAgICAgICAgICAgICAgIHByb3BzW25hbWVdID0gZXh0cmFjdGVkTGluZXMubWFwKChsaW5lKSA9PiBuZXcgQXJyYXkobGluZS5saW5lLmxlbmd0aCkuZmlsbChudWxsKSk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIHByb3BzW25hbWVdW2ldID0gdmFsOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgZWxzZSB7CgkgICAgICAgICAgICAgICAgcHJvcHNbbmFtZV0gPSB2YWw7CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCSAgICB9CgkgICAgcmV0dXJuIHsKCSAgICAgICAgdHlwZTogIkZlYXR1cmUiLAoJICAgICAgICBwcm9wZXJ0aWVzOiBwcm9wZXJ0aWVzLAoJICAgICAgICBnZW9tZXRyeTogbXVsdGkKCSAgICAgICAgICAgID8gewoJICAgICAgICAgICAgICAgIHR5cGU6ICJNdWx0aUxpbmVTdHJpbmciLAoJICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiB0cmFjaywKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIDogewoJICAgIC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gaSA9IDA7IGkgPCBwdHMubGVuZ3RoOyBpKyspIHsKCSAgICAgICAgY29uc3QgYyA9IGNvb3JkUGFpcihwdHNbaV0pOwoJICAgICAgICBpZiAoYyA9PT0gbnVsbCkKCSAgICAgICAgICAgIGNvbnRpbnVlOwoJICAgICAgICBsaW5lLnB1c2goYy5jb29yZGluYXRlcyk7CgkgICAgICAgIGNvbnN0IHsgdGltZSwgaGVhcnRSYXRlLCBleHRlbnNpb25zIH0gPSBjOwoJICAgICAgICBpZiAodGltZSkKCSAgICAgICAgICAgIHRpbWVzLnB1c2godGltZSk7CgkgICAgICAgIGlmIChoZWFydFJhdGUpCgkgICAgICAgICAgICBoZWFydFJhdGVzLnB1c2goaGVhcnRSYXRlKTsKCSAgICAgICAgZm9yIChjb25zdCBbYWxpYXMsIHZhbHVlXSBvZiBleHRlbnNpb25zKSB7CgkgICAgICAgICAgICBpZiAoIWV4dGVuZGVkUHJvcGVydGllc1thbGlhc10pIHsKCSAgICAgICAgICAgICAgICBleHRlbmRlZFByb3BlcnRpZXNbYWxpYXNdID0gQXJyYXkocHRzLmxlbmd0aCkuZmlsbChudWxsKTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIGV4dGVuZGVkUHJvcGVydGllc1thbGlhc11baV0gPSB2YWx1ZTsKCSAgICAgICAgfQoJICAgIH0KCSAgICBpZiAobGluZS5sZW5ndGggPCAyKQoJICAgICAgICByZXR1cm4gbnVsbDsKCSAgICByZXR1cm4gT2JqZWN0LmFzc2lnbihyZXN1bHQsIHsKCSAgICAgICAgbGluZTogbGluZSwKCSAgICAgICAgdGltZXM6IHRpbWVzLAoJICAgICAgICBoZWFydFJhdGVzOiBoZWFydFJhdGVzLAoJICAgIH0pOwoJfQoJZnVuY3Rpb24gZ2V0TGFwKG5vZGUpIHsKCSAgICBjb25zdCBzZWdtZW50cyA9ICQobm9kZSwgIlRyYWNrIik7CgkgICAgY29uc3QgdHJhY2sgPSBbXTsKCSAgICBjb25zdCB0aW1lc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Byb3BlcnRpZXMpIHsKCSAgICAgICAgICAgIGlmIChzZWdtZW50cy5sZW5ndGggPT09IDEpIHsKCSAgICAgICAgICAgICAgICBpZiAobGluZSkgewoJICAgICAgICAgICAgICAgICAgICBwcm9wZXJ0aWVzW3Byb3BlcnR5XSA9IGxpbmUuZXh0ZW5kZWRQcm9wZXJ0aWVzW3Byb3BlcnR5XTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgICAgICBlbHNlIHsKCSAgICAgICAgICAgICAgICBpZiAoIXByb3BlcnRpZXNbcHJvcGVydHldKSB7CgkgICAgICAgICAgICAgICAgICAgIHByb3BlcnRpZXNbcHJvcGVydHldID0gdHJhY2subWFwKCh0cmFjaykgPT4gQXJyYXkodHJhY2subGVuZ3RoKS5maWxsKG51bGwpKTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgcHJvcGVydGllc1twcm9wZXJ0eV1baV0gPSBleHRlbmRlZFByb3BlcnRpZXNbcHJvcGVydHldOwoJICAgICAgICAgICAgfQoJICAgICAgICB9CgkgICAgfQoJICAgIGlmICh0cmFjay5sZW5ndGggPT09IDApCgkgICAgICAgIHJldHVybiBudWxsOwoJICAgIGlmICh0aW1lcy5sZW5ndGggfHwgaGVhcnRSYXRlcy5sZW5ndGgpIHsKCSAgICAgICAgcHJvcGVydGllcy5jb29yZGluYXRlUHJvcGVydGllcyA9IE9iamVjdC5hc3NpZ24odGltZXMubGVuZ3RoCgkgICAgICAgICAgICA/IHsKCSAgICAgICAgICAgICAgICB0aW1lczogdHJhY2subGVuZ3RoID09PSAxID8gdGltZXNbMF0gOiB0aW1lcywKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIDoge30sIGhlYXJ0UmF0ZXMubGVuZ3RoCgkgICAgICAgICAgICA/IHsKCSAgICAgICAgICAgICAgICBoZWFydDogdHJhY2subGVuZ3RoID09PSAxID8gaGVhcnRSYXRlc1swXSA6IGhlYXJ0UmF0ZXMsCgk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gcHJvcGVydGllczsKCX0KCglmdW5jdGlvbiBudW1lcmljUHJvcGVydHkobm9kZSwgc291cmNlLCB0YXJnZXQpIHsKCSAgICBjb25zdCBwcm9wZXJ0aWVzID0ge307CgkgICAgbnVtMShub2RlLCBzb3VyY2UsICh2YWwpID0+IHsKCSAgICAgICAgcHJvcGVydGllc1t0YXJnZXRdID0gdmFsOwoJICAgIH0pOwoJICAgIHJldHVybiBwcm9wZXJ0aWVzOwoJfQoJZnVuY3Rpb24gZ2V0Q29sb3Iobm9kZSwgb3V0cHV0KSB7CgkgICAgcmV0dXJuIGdldChub2RlLCAiY29sb3IiLCAoZWxlbSkgPT4gZml4Q29sb3Iobm9kZVZhbChlbGVtKSwgb3V0cHV0KSk7Cgl9CglmdW5jdGlvbiBleHRyYWN0SWNvbkhyZWYobm9kZSkgewoJICAgIHJldHVybiBnZXQobm9kZSwgIkljb24iLCAoaWNvbiwgcHJvcGVydGllcykgPT4gewoJICAgICAgICB2YWwxKGljb24sICJocmVmIiwgKGhyZWYpID0+IHsKCSAgICAgICAgICAgIHByb3BlcnRpZXMuaWNvbiA9IGhyZWY7CgkgICAgICAgIH0pOwoJICAgICAgICByZXR1cm4gcHJvcGVydGllczsKCSAgICB9KTsKCX0KCWZ1bmN0aW9uIGV4dHJhY3RJY29uKG5vZGUpIHsKCSAgICByZXR1cm4gZ2V0KG5vZGUsICJJY29uU3R5bGUiLCAoaWNvblN0eWxlKSA9PiB7CgkgICAgICAgIHJldHVybiBPYmplY3QuYXNzaWduKGdldENvbG9yKGljb25TdHlsZSwgImljb24iKSwgbnVtZXJpY1Byb3BlcnR5KGljb25TdHlsZSwgInNjYWxlIiwgImljb24tc2NhbGUiKSwgbnVtZXJpY1Byb3BlcnR5KGljb25TdHlsZSwgImhlYWRpbmciLCAiaWNvbi1oZWFkaW5nIiksIGdldChpY29uU3R5bGUsICJob3RTcG90IiwgKGhvdHNwb3QpID0+IHsKCSAgICAgICAgICAgIGNvbnN0IGxlZnQgPSBwY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NyaXB0aW9uIik7CgkgICAgZm9yIChjb25zdCBjIG9mIEFycmF5LmZyb20oZGVzY3JpcHRpb25Ob2RlPy5jaGlsZE5vZGVzIHx8IFtdKSkgewoJICAgICAgICBpZiAoYy5ub2RlVHlwZSA9PT0gNCkgewoJICAgICAgICAgICAgcmV0dXJuIHsKCSAgICAgICAgICAgICAgICBkZXNjcmlwdGlvbjogewoJICAgICAgICAgICAgICAgICAgICAiQHR5cGUiOiAiaHRtbCIsCgkgICAgICAgICAgICAgICAgICAgIHZhbHVlOiBub2RlVmFsKGMpLAoJICAgICAgICAgICAgICAgIH0sCgkgICAgICAgICAgICB9OwoJICAgICAgICB9CgkgICAgfQoJICAgIHJldHVybiB7fTsKCX0KCWZ1bmN0aW9uIGV4dHJhY3RUaW1lU3Bhbihub2RlKSB7CgkgICAgcmV0dXJuIGdldChub2RlLCAiVGltZVNwYW4iLCAodGltZVNwYW4pID0+IHsKCSAgICAgICAgcmV0dXJuIHsKCSAgICAgICAgICAgIHRpbWVzcGFuOiB7CgkgICAgICAgICAgICAgICAgYmVnaW46IG5vZGVWYWwoZ2V0MSh0aW1lU3BhbiwgImJlZ2luIikpLAoJICAgICAgICAgICAgICAgIGVuZDogbm9kZVZhbChnZXQxKHRpbWVTcGFuLCAiZW5kIikpLAoJICAgICAgICAgICAgfSwKCSAgICAgICAgfTsKCSAgICB9KTsKCX0KCWZ1bmN0aW9uIGV4dHJhY3RUaW1lU3RhbXAobm9kZSkgewoJICAgIHJldHVybiBnZXQobm9kZSwgIlRpbWVTdGFtcCIsICh0aW1lU3RhbXApID0+IHsKCSAgICAgICAgcmV0dXJuIHsgdGltZXN0YW1wOiBub2RlVmFsKGdldDEodGltZVN0YW1wLCAid2hlbiIpKSB9OwoJICAgIH0pOwoJfQoJZnVuY3Rpb24gZXh0cmFjdENhc2NhZGVkU3R5bGUobm9kZSwgc3R5bGVNYXApIHsKCSAgICByZXR1cm4gdmFsMShub2RlLCAic3R5bGVVcmwiLCAoc3R5bG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hpbGRHZW9tZXRyaWVzID0gZ2V0R2VvbWV0cnkoY2hpbGQpOwoJICAgICAgICAgICAgICAgICAgICBnZW9tZXRyaWVzID0gZ2VvbWV0cmllcy5jb25jYXQoY2hpbGRHZW9tZXRyaWVzLmdlb21ldHJpZXMpOwoJICAgICAgICAgICAgICAgICAgICBjb29yZFRpbWVzID0gY29vcmRUaW1lcy5jb25jYXQoY2hpbGRHZW9tZXRyaWVzLmNvb3JkVGltZXMpOwoJICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgY2FzZSAiUG9pbnQiOiB7CgkgICAgICAgICAgICAgICAgICAgIGNvbnN0IGNvb3JkaW5hdGVzID0gY29vcmQxKGdldENvb3JkaW5hdGVzKGNoaWxkKSk7CgkgICAgICAgICAgICAgICAgICAgIGlmIChjb29yZGluYXRlcy5sZW5ndGggPj0gMikgewoJICAgICAgICAgICAgICAgICAgICAgICAgZ2VvbWV0cmllcy5wdXNoKHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAiUG9pbnQiLAoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzLAoJICAgICAgICAgICAgICAgICAgICAgICAgfSk7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIGNhc2UgIkxpbmVhclJpbmciOgoJICAgICAgICAgICAgICAgIGNhc2UgIkxpbmVTdHJpbmciOiB7CgkgICAgICAgICAgICAgICAgICAgIGNvbnN0IGNvb3JkaW5hdGVzID0gY29vcmQoZ2V0Q29vcmRpbmF0ZXMoY2hpbGQpKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGNvb3JkaW5hdGVzLmxlbmd0aCA+PSAyKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBnZW9tZXRyaWVzLnB1c2goewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICJMaW5lU3RyaW5nIiwKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlcywKCSAgICAgICAgICAgICAgICAgICAgICAgIH0pOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGJyZWFrOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICBjYXNlICJQb2x5Z29uIjogewoJICAgICAgICAgICAgICAgICAgICBjb25zdCBjb29yZHMgPSBbXTsKCSAgICAgICAgICAgICAgICAgICAgZm9yIChjb25zdCBsaW5lYXJSaW5nIG9mICQoY2hpbGQsICJMaW5lYXJSaW5nIikpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvbnN0IHJpbmcgPSBmaXhSaW5nKGNvb3JkKGdldENvb3JkaW5hdGVzKGxpbmVhclJpbmcpKSk7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAocmluZy5sZW5ndGggPj0gNCkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGNvb3Jkcy5wdXNoKHJpbmcpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGlmIChjb29yZHMubGVuZ3RoKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBnZW9tZXRyaWVzLnB1c2goewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICJQb2x5Z29uIiwKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogY29vcmRzLAoJICAgICAgICAgICAgICAgICAgICAgICAgfSk7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIGNhc2UgIlRyYWNrIjoKCSAgICAgICAgICAgICAgICBjYXNlICJneDpUcmFjayI6IHsKCSAgICAgICAgICAgICAgICAgICAgY29uc3QgZ3ggPSBneENvb3JkcyhjaGlsZCk7CgkgICAgICAgICAgICAgICAgICAgIGlmICghZ3gpCgkgICAgICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICAgICAgY29uc3QgeyB0aW1lcywgZ2VvbWV0cnkgfSA9IGd4OwoJICAgICAgICAgICAgICAgICAgICBnZW9tZXRyaWVzLnB1c2goZ2VvbWV0cnkpOwoJICAgICAgICAgICAgICAgICAgICBpZiAodGltZXMubGVuZ3RoKQoJICAgICAgICAgICAgICAgICAgICAgICAgY29vcmRUaW1lcy5wdXNoKHRpbWVzKTsKCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICB9CgkgICAgfQoJICAgIHJldHVybiB7CgkgICAgICAgIGdlb21ldHJpZXMsCgkgICAgICAgIGNvb3JkVGltZXMsCgkgICAgfTsKCX0KCglmdW5jdGlvbiBnZW9tZXRyeUxpc3RUb0dlb21ldHJ5KGdlb21ldHJpZXMpIHsKCSAgICByZXR1cm4gZ2VvbWV0cmllcy5sZW5ndGggPT09IDAKCSAgICAgICAgPyBudWxsCgkgICAgICAgIDogZ2VvbWV0cmllcy5sZW5ndGggPT09IDEKCSAgICAgICAgICAgID8gZ2VvbWV0cmllc1swXQoJICAgICAgICAgICAgOiB7CgkgICAgICAgICAgICAgICAgdHlwZTogIkdlb21ldHJ5Q29sbGVjdGlvbiIsCgkgICAgICAgICAgICAgICAgZ2VvbWV0cmllcywKCSAgICAgICAgICAgIH07Cgl9CglmdW5jdGlvbiBnZXRQbGFjZW1hcmsobm9kZSwgc3R5bGVNYXAsIHNjaGVtYSwgb3B0aW9ucykgewoJICAgIGNvbnN0IHsgY29vcmRUaW1lcywgZ2VvbWV0cmllcyB9ID0gZ2V0R2VvbWV0cnkobm9kZSk7CgkgICAgY29uc3QgZ2VvbWV0cnkgPSBnZW9tZXRyeUxpc3RUb0dlb21ldHJ5KGdlb21ldHJpZXMpOwoJICAgIGlmICghZ2VvbWV0cnkgJiYgb3B0aW9ucy5za2lwTnVsbEdlb21ldHJ5KSB7CgkgICAgICAgIHJldHVybiBudWxsOwoJICAgIH0KCSAgICBjb25zdCBmZWF0dXJlID0gewoJICAgICAgICB0eXBlOiAiRmVhdHVyZSIsCgkgICAgICAgIGdlb21ldHJ5LAoJICAgICAgICBwcm9wZXJ0aWVzOiBPYmplY3QuYXNzaWduKGdldE11bHRpKG5vZGUsIFsKCSAgICAgICAgICAgICJuYW1lIiwKCSAgICAgICAgICAgICJhZGRyZXNzIiwKCSAgICAgICAgICAgICJ2aXNpYmlsaXR5IiwKCSAgICAgICAgICAgICJvcGVuIiwKCSAgICAgICAgICAgICJwaG9uZU51bWJlciIsCgkgICAgICAgICAgICAiZGVzY3JpcHRpb24iLAoJICAgICAgICBdKSwgZ2V0TWF5YmVIVE1MRGVzY3JpcHRpb24obm9kZSksIGV4dHJhY3RDYXNjYWRlZFN0eWxlKG5vZGUsIHN0eWxlTWFwKSwgZXh0cmFjdFN0eWxlKG5vZGUpLCBleHRyYWN0RXh0ZW5kZWREYXRhKG5vZGUsIHNjaGVtYSksIGV4dHJhY3RUaW1lU3Bhbihub2RlKSwgZXh0cmFjdFRpbWVTdGFtcChub2RlKSwgY29vcmRUaW1lcy5sZW5ndGgKCSAgICAgICAgICAgID8gewoJICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVQcm9wZXJ0aWVzOiB7CgkgICAgICAgICAgICAgICAgICAgIHRpbWVzOiBjb29yZFRpbWVzLmxlbmd0aCA9PT0gMSA/IGNvb3JkVGltZXNbMF0gOiBjb29yZFRpbWVzLAoJICAgICAgICAgICAgICAgIH0sCgkgICAgICAgICAgICB9CgkgICAgICAgICAgICA6IHt9KSwKCSAgICB9OwoJICAgIGlmIChmZWF0dXJlLnByb3BlcnRpZXM/LnZpc2liaWxpdHkgIT09IHVuZGVmaW5lZCkgewoJICAgICAgICBmZWF0dXJlLnByb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NvbnN0IGR4ID0gY29vcmRpbmF0ZVswXSAtIGNlbnRlclswXTsKCSAgICAgICAgICAgIGNvbnN0IGRpc3RhbmNlID0gTWF0aC5zcXJ0KE1hdGgucG93KGR5LCAyKSArIE1hdGgucG93KGR4LCAyKSk7CgkgICAgICAgICAgICBjb25zdCBhbmdsZSA9IE1hdGguYXRhbjIoZHksIGR4KSArIHJvdGF0aW9uICogREVHUkVFU19UT19SQURJQU5TOwoJICAgICAgICAgICAgcmV0dXJuIFsKCSAgICAgICAgICAgICAgICBjZW50ZXJbMF0gKyBNYXRoLmNvcyhhbmdsZSkgKiBkaXN0YW5jZSwKCSAgICAgICAgICAgICAgICBjZW50ZXJbMV0gKyBNYXRoLnNpbihhbmdsZSkgKiBkaXN0YW5jZSwKCSAgICAgICAgICAgIF07CgkgICAgICAgIH0pLAoJICAgIF07Cgl9CglmdW5jdGlvbiBnZXRMYXRMb25Cb3gobm9kZSkgewoJICAgIGNvbnN0IGxhdExvbkJveCA9IGdldDEobm9kZSwgIkxhdExvbkJveCIpOwoJICAgIGlmIChsYXRMb25Cb3gpIHsKCSAgICAgICAgY29uc3Qgbm9ydGggPSBudW0xKGxhdExvbkJveCwgIm5vcnRoIik7CgkgICAgICAgIGNvbnN0IHdlc3QgPSBudW0xKGxhdExvbkJveCwgIndlc3QiKTsKCSAgICAgICAgY29uc3QgZWFzdCA9IG51bTEobGF0TG9uQm94LCAiZWFzdCIpOwoJICAgICAgICBjb25zdCBzb3V0aCA9IG51bTEobGF0TG9uQm94LCAic291dGgiKTsKCSAgICAgICAgY29uc3Qgcm90YXRpb24gPSBudW0xKGxhdExvbkJveCwgInJvdGF0aW9uIik7CgkgICAgICAgIGlmICh0eXBlb2Ygbm9ydGggPT09ICJudW1iZXIiICYmCgkgICAgICAgICAgICB0eXBlb2Ygc291dGggPT09ICJudW1iZXIiICYmCgkgICAgICAgICAgICB0eXBlb2Ygd2VzdCA9PT0gIm51bWJlciIgJiYKCSAgICAgICAgICAgIHR5cGVvZiBlYXN0ID09PSAibnVtYmVyIikgewoJICAgICAgICAgICAgY29uc3QgYmJveCA9IFt3ZXN0LCBzb3V0aCwgZWFzdCwgbm9ydGhdOwoJICAgICAgICAgICAgbGV0IGNvb3JkaW5hdGVzID0gWwoJICAgICAgICAgICAgICAgIFsKCSAgICAgICAgICAgICAgICAgICAgW3dlc3QsIG5vcnRoXSwKCSAgICAgICAgICAgICAgICAgICAgW2Vhc3QsIG5vcnRoXSwKCSAgICAgICAgICAgICAgICAgICAgW2Vhc3QsIHNvdXRoXSwKCSAgICAgICAgICAgICAgICAgICAgW3dlc3QsIHNvdXRoXSwKCSAgICAgICAgICAgICAgICAgICAgW3dlc3QsIG5vcnRoXSwgLy8gdG9wIGxlZnQgKGFnYWluKQoJICAgICAgICAgICAgICAgIF0sCgkgICAgICAgICAgICBdOwoJICAgICAgICAgICAgaWYgKHR5cGVvZiByb3RhdGlvbiA9PT0gIm51bWJlciIpIHsKCSAgICAgICAgICAgICAgICBjb29yZGluYXRlcyA9IHJvdGF0ZUJveChiYm94LCBjb29yZGluYXRlcywgcm90YXRpb24pOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmV0dXJuIHsKCSAgICAgICAgICAgICAgICBiYm94LAoJICAgICAgICAgICAgICAgIGdlb21ldHJ5OiB7CgkgICAgICAgICAgICAgICAgICAgIHR5cGU6ICJQb2x5Z29uIiwKCSAgICAgICAgICAgICAgICAgICAgY29vcmRpbmF0ZXMsCgkgICAgICAgICAgICAgICAgfSwKCSAgICAgICAgICAgIH07CgkgICAgICAgIH0KCSAgICB9CgkgICAgcmV0dXJuIG51bGw7Cgl9CglmdW5jdGlvbiBnZXRHcm91bmRPdmVybGF5KG5vZGUsIHN0eWxlTWFwLCBzY2hlbWEsIG9wdGlvbnMpIHsKCSAgICBjb25zdCBib3ggPSBnZXRHcm91bmRPdmVybGF5Qm94KG5vZGUpOwoJICAgIGNvbnN0IGdlb21ldHJ5ID0gYm94Py5nZW9tZXRyeSB8fCBudWxsOwoJICAgIGlmICghZ2VvbWV0cnkgJiYgb3B0aW9ucy5za2lwTnVsbEdlb21ldHJ5KSB7CgkgICAgICAgIHJldHVybiBudWxsOwoJICAgIH0KCSAgICBjb25zdCBmZWF0dXJlID0gewoJICAgICAgICB0eXBlOiAiRmVhdHVyZSIsCgkgICAgICAgIGdlb21ldHJ5LAoJICAgICAgICBwcm9wZXJ0aWVzOiBPYmplY3QuYXNzaWduKAoJICAgICAgICAvKioKCSAgICAgICAgICogUmVsYXRlZCB0bwoJICAgICAgICAgKiBodHRwczovL2dpc3QuZ2l0aHViLmNvbS90bWN3LzAzN2ExY2I2NjYwZDc0YTM5MmU5ZGE3NDQ2NTQwZjQ2CgkgICAgICAgICAqLwoJICAgICAgICB7ICJAZ2VvbWV0cnktdHlwZSI6ICJncm91bmRvdmVybGF5IiB9LCBnZXRNdWx0aShub2RlLCBbCgkgICAgICAgICAgICAibmFtZSIsCgkgICAgICAgICAgICAiYWRkcmVzcyIsCgkgICAgICAgICAgICAidmlzaWJpbGl0eSIsCgkgICAgICAgICAgICAib3BlbiIsCgkgICAgICAgICAgICAicGhvbmVOdW1iZXIiLAoJICAgICAgICAgICAgImRlc2NyaXB0aW9uIiwKCSAgICAgICAgXSksIGdldE1heWJlSFRNTERlc2NyaXB0aW9uKG5vZGUpLCBleHRyYWN0Q2FzY2FkZWRTdHlsZShub2RlLCBzdHlsZU1hcCksIGV4dHJhY3RTdHlsZShub2RlKSwgZXh0cmFjdEljb25IcmVmKG5vZGUpLCBleHRyYWN0RXh0ZW5kZWREYXRhKG5vZGUsIHNjaGVtYSksIGV4dHJhY3RUaW1lU3Bhbihub2RlKSwgZXh0cmFjdFRpbWVTdGFtcChub2RlKSksCgkgICAgfTsKCSAgICBpZiAoYm94Py5iYm94KSB7CgkgICAgICAgIGZlYXR1cmUuYmJveCA9IGJveC5iYm94OwoJICAgIH0KCSAgICBpZiAoZmVhdHVyZS5wcm9wZXJ0aWVzPy52aXNpYmlsaXR5ICE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YnJlYWs7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIGNhc2UgIlBsYWNlbWFyayI6IHsKCSAgICAgICAgICAgICAgICAgICAgY29uc3QgcGxhY2VtYXJrID0gZ2V0UGxhY2VtYXJrKG5vZGUsIHN0eWxlTWFwLCBzY2hlbWEsIG9wdGlvbnMpOwoJICAgICAgICAgICAgICAgICAgICBpZiAocGxhY2VtYXJrKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBwb2ludGVyLmNoaWxkcmVuLnB1c2gocGxhY2VtYXJrKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgY2FzZSAiRm9sZGVyIjogewoJICAgICAgICAgICAgICAgICAgICBjb25zdCBmb2xkZXIgPSBnZXRGb2xkZXIobm9kZSk7CgkgICAgICAgICAgICAgICAgICAgIHBvaW50ZXIuY2hpbGRyZW4ucHVzaChmb2xkZXIpOwoJICAgICAgICAgICAgICAgICAgICBwb2ludGVyID0gZm9sZGVyOwoJICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCSAgICAgICAgaWYgKG5vZGUuY2hpbGROb2RlcykgewoJICAgICAgICAgICAgZm9yIChsZXQgaSA9IDA7IGkgPCBub2RlLmNoaWxkTm9kZXMubGVuZ3RoOyBpKyspIHsKCSAgICAgICAgICAgICAgICB0cmF2ZXJzZShub2RlLmNoaWxkTm9kZXNbaV0sIHBvaW50ZXIsIG9wdGlvbnMpOwoJICAgICAgICAgICAgfQoJICAgICAgICB9CgkgICAgfQoJICAgIHRyYXZlcnNlKG5vZGUsIHRyZWUsIG9wdGlvbnMpOwoJICAgIHJldHVybiB0cmVlOwoJfQoJLyoqCgkgKiBDb252ZXJ0IEtNTCB0byBHZW9KU09OIGluY3JlbWVudGFsbHksIHJldHVybmluZwoJICog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gICAgICAgbGV0IHJzID0gT2JqZWN0LmFzc2lnbih7fSwgb2JqKTsKCSAgICAgICAgICAgIGlmIChibGFja2xpc3QpIHsKCSAgICAgICAgICAgICAgICBmb3IgKGxldCBwcm9wIG9mIGJsYWNrbGlzdCkgewoJICAgICAgICAgICAgICAgICAgICBkZWxldGUgcnNbcHJvcF07CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmV0dXJuIHJzOwoJICAgICAgICB9CgkgICAgICAgIHJldHVybiB7fTsKCSAgICB9OwoKCSAgICBjb25zdCBtZXJnZVByb3BzID0gKG9iajEsIG9iajIpID0+IHsKCSAgICAgICAgb2JqMSA9IG9iajEgPyBvYmoxIDoge307CgkgICAgICAgIG9iajIgPSBvYmoyID8gb2JqMiA6IHt9OwoJICAgICAgICByZXR1cm4gT2JqZWN0LmFzc2lnbihvYmoxLCBvYmoyKTsKCSAgICB9OwoKCSAgICBjb25zdCBmaXJzdCA9IGEgPT4gYVswXTsKCSAgICBjb25zdCBsYXN0ID0gYSA9PiBhW2EubGVuZ3RoIC0gMV07CgkgICAgY29uc3QgY29vcmRzVG9LZXkgPSBhID0+IGEuam9pbignLCcpOwoKCSAgICBjb25zdCBhZGRUb01hcCA9IChtLCBrLCB2KSA9PiB7CgkgICAgICAgIGxldCBhID0gbVtrXTsKCSAgICAgICAgaWYgKGEpIHsKCSAgICAgICAgICAgIGEucHVzaCh2KTsKCSAgICAgICAgfSBlbHNlIHsKCSAgICAgICAgICAgIG1ba10gPSBbdl07CgkgICAgICAgIH0KCSAgICB9OwoKCSAgICBjb25zdCByZW1vdmVGcm9tTWFwID0gKG0sIGssIHYpID0+IHsKCSAgICAgICAgbGV0IGEgPSBtW2tdOwoJICAgICAgICBsZXQgaWR4ID0gbnVsbDsKCSAgICAgICAgaWYgKGEgJiYgKGlkeCA9IGEuaW5kZXhPZih2KSkgPj0gMCkgewoJICAgICAgICAgICAgYS5zcGxpY2UoaWR4LCAxKTsKC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ICAgICAgIGNvbnN0cnVjdG9yKGNvbnRhaW5lciwgdmFsdWVGdW5jLCBjdHgsIGFyZ3MpIHsKCSAgICAgICAgICAgIHRoaXMuY29udGFpbmVyID0gY29udGFpbmVyOwoJICAgICAgICAgICAgdGhpcy52YWx1ZUZ1bmMgPSB2YWx1ZUZ1bmM7CgkgICAgICAgICAgICB0aGlzLmN0eCA9IGN0eDsKCSAgICAgICAgICAgIHRoaXMuYXJncyA9IGFyZ3M7CgkgICAgICAgIH0KCgkgICAgICAgIGJpbmQoKSB7CgkgICAgICAgICAgICBsZXQgdiA9IHRoaXMudmFsdWVGdW5jLmFwcGx5KHRoaXMuY3R4LCB0aGlzLmFyZ3MpOwoJICAgICAgICAgICAgaWYgKHRoaXMuY29udGFpbmVyIGluc3RhbmNlb2YgQXJyYXkpIHsKCSAgICAgICAgICAgICAgICBsZXQgaWR4ID0gdGhpcy5jb250YWluZXIuaW5kZXhPZih0aGlzKTsKCSAgICAgICAgICAgICAgICBpZiAoaWR4ID49IDApIHsKCSAgICAgICAgICAgICAgICAgICAgbGV0IGFyZ3MgPSBbaWR4LCAxXTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKHYpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGFyZ3MucHVzaCh2KTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICBbXS5zcGxpY2UuYXBwbHkodGhpcy5jb250YWluZXIsIGFyZ3MpOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0gZWxzZSBpZiAodHlwZW9mIHRoaXMuY29udGFpbmVyID09PSAnb2JqZWN0JykgewoJICAgICAgICAgICAgICAgIGxldCBrID0gT2JqZWN0LmtleXModGhpcy5jb250YWluZXIpLmZpbmQodiA9PiB0aGlzLmNvbnRhaW5lclt2XSA9PT0gdGhpcyk7CgkgICAgICAgICAgICAgICAgaWYgKGspIHsKCSAgICAgICAgICAgICAgICAgICAgaWYgKHYpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHRoaXMuY29udGFpbmVyW2tdID0gdjsKCSAgICAgICAgICAgICAgICAgICAgfSBlbHNlIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGRlbGV0ZSB0aGlzLmNvbnRhaW5lcltrXTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgfQoJICAgIH0KCgkgICAgY2xhc3MgV2F5Q29sbGVjdGlvbiBleHRlbmRzIEFycmF5IHsKCSAgICAgICAgY29uc3RydWN0b3IoKSB7CgkgICAgICAgICAgICBzdXBlcigpOwoJICAgICAgICAgICAgdGhpcy5maXJzdE1hcCA9IHt9OwoJICAgICAgICAgICAgdGhpcy5sYXN0TWFwID0ge307CgkgICAgICAgIH0KCgkgICAgICAgIGFkZFdheSh3YXkpIHsKCSAgICAgICAgICAgIHdheSA9IHdheS50b0Nvb3Jkc0FycmF5KCk7CgkgICAgICAgICAgICBpZiAod2F5Lmxlbmd0aCA+IDApIHsKCSAgICAgICAgICAgICAgICB0aGlzLnB1c2god2F5KTsKCSAgICAgICAgICAgICAgICBhZGRUb01hcCh0aGlzLmZpcnN0TWFwLCBjb29yZHNUb0tleShmaXJzdCh3YXkpKSwgd2F5KTsKCSAgICAgICAgICAgICAgICBhZGRUb01hcCh0aGlzLmxhc3RNYXAsIGNvb3Jkc1RvS2V5KGxhc3Qod2F5KSksIHdheSk7CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCgkgICAgICAgIHRvU3RyaW5ncygpIHsKCSAgICAgICAgICAgIGxldCBzdHJpbmdzID0gW10sIHdheSA9IG51bGw7CgkgICAgICAgICAgICB3aGlsZSAod2F5ID0gdGhpcy5zaGlmdCgpKSB7CgkgICAgICAgICAgICAgICAgcmVtb3ZlRnJvbU1hcCh0aGlzLmZpcnN0TWFwLCBjb29yZHNUb0tleShmaXJzdCh3YXkpKSwgd2F5KTsKCSAgICAgICAgICAgICAgICByZW1vdmVGcm9tTWFwKHRoaXMubGFzdE1hcCwgY29vcmRzVG9LZXkobGFzdCh3YXkpKSwgd2F5KTsKCSAgICAgICAgICAgICAgICBsZXQgY3VycmVudCA9IHdheSwgbmV4dCA9IG51bGw7CgkgICAgICAgICAgICAgICAgZG8gewoJICAgICAgICAgICAgICAgICAgICBsZXQga2V5ID0gY29vcmRzVG9LZXkobGFzdChjdXJyZW50KSksIHNob3VsZFJldmVyc2UgPSBmYWxzZTsKCgkgICAgICAgICAgICAgICAgICAgIG5leHQgPSBnZXRGaXJzdEZyb21NYXAodGhpcy5maXJzdE1hcCwga2V5KTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKCFuZXh0KSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBuZXh0ID0gZ2V0Rmlyc3RGcm9tTWFwKHRoaXMubGFzdE1hcCwga2V5KTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHNob3VsZFJldmVyc2UgPSB0cnVlOwoJICAgICAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgICAgICBpZiAobmV4dCkgewoJICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5zcGxpY2UodGhpcy5pbmRleE9mKG5leHQpLCAxKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHJlbW92ZUZyb21NYXAodGhpcy5maXJzdE1hcCwgY29vcmRzVG9LZXkoZmlyc3QobmV4dCkpLCBuZXh0KTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHJlbW92ZUZyb21NYXAodGhpcy5sYXN0TWFwLCBjb29yZHNUb0tleShsYXN0KG5leHQpKSwgbmV4dCk7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAoc2hvdWxkUmV2ZXJzZSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIC8vIGFsd2F5cyByZXZlcnNlIHNob3J0ZXIgb25lIHRvIHNhdmUgdGltZQoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGlmIChuZXh0Lmxlbmd0aCA+IGN1cnJlbnQubGVuZ3RoKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFtjdXJyZW50LCBuZXh0XSA9IFtuZXh0LCBjdXJyZW50XTsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgbmV4dC5yZXZlcnNlKCk7CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgICAgICAgICAgY3VycmVudCA9IGN1cnJlbnQuY29uY2F0KG5leHQuc2xpY2UoMSkpOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfSB3aGlsZSAobmV4dCk7CgkgICAgICAgICAgICAgICAgc3RyaW5ncy5wdXNoKHN0clRvRmxvYXQoY3VycmVudCkpOwoJICAgICAgICAgICAgfQoKCSAgICAgICAgICAgIHJldHVybiBzdHJpbmdzOwoJICAgICAgICB9CgoJICAgICAgICB0b1JpbmdzKGRpcmVjdGlvbikgewoJICAgICAgICAgICAgbGV0IHN0cmluZ3MgPSB0aGlzLnRvU3RyaW5ncygpOwoJICAgICAgICAgICAgbGV0IHJpbmdzID0gW10sIHN0cmluZyA9IG51bGw7CgkgICAgICAgICAgICB3aGlsZSAoc3RyaW5nID0gc3RyaW5ncy5zaGlmdCgpKSB7CgkgICAgICAgICAgICAgICAgaWYgKGlzUmluZyhzdHJpbmcpKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmIChyaW5nRGlyZWN0aW9uKHN0cmluZykgIT09IGRpcmVjdGlvbikgewoJICAgICAgICAgICAgICAgICAgICAgICAgc3RyaW5nLnJldmVyc2UoKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICByaW5ncy5wdXNoKHN0cmluZyk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmV0dXJuIHJpbmdzOwoJICAgICAgICB9CgkgICAgfQoKCSAgICByZXR1cm4gewoJICAgICAg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gICB0aGlzLnJlZkNvdW50ID0gMDsKCSAgICAgICAgICAgIHRoaXMuaGFzVGFnID0gZmFsc2U7CgkgICAgICAgICAgICBpZiAocmVmRWxlbXMpIHsKCSAgICAgICAgICAgICAgICByZWZFbGVtcy5hZGQodGhpcy5nZXRDb21wb3NpdGVJZCgpLCB0aGlzKTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgfQoKCSAgICAgICAgYWRkVGFncyh0YWdzKSB7CgkgICAgICAgICAgICB0aGlzLnRhZ3MgPSBPYmplY3QuYXNzaWduKHRoaXMudGFncywgdGFncyk7CgkgICAgICAgICAgICB0aGlzLmhhc1RhZyA9IHRhZ3MgPyB0cnVlIDogZmFsc2U7CgkgICAgICAgIH0KCgkgICAgICAgIGFkZFRhZyhrLCB2KSB7CgkgICAgICAgICAgICB0aGlzLnRhZ3Nba10gPSB2OwoJICAgICAgICAgICAgdGhpcy5oYXNUYWcgPSBrID8gdHJ1ZSA6IGZhbHNlOwoJICAgICAgICB9CgoJICAgICAgICBhZGRQcm9wKGssIHYpIHsKCSAgICAgICAgICAgIHRoaXMucHJvcHNba10gPSB2OwoJICAgICAgICB9CgoJICAgICAgICBhZGRQcm9wcyhwcm9wcykgewoJICAgICAgICAgICAgdGhpcy5wcm9wcyA9IE9iamVjdC5hc3NpZ24odGhpcy5wcm9wcywgcHJvcHMpOwoJICAgICAgICB9CgoJICAgICAgICBnZXRDb21wb3NpdGVJZCgpIHsKCSAgICAgICAgICAgIHJldHVybiBgJHt0aGlzLnR5cGV9LyR7dGhpcy5pZH1gOwoJICAgICAgICB9CgoJICAgICAgICBnZXRQcm9wcygpIHsKCSAgICAgICAgICAgIHJldHVybiBPYmplY3QuYXNzaWduKHRoaXMucHJvcHMsIHRoaXMudGFncyk7CgkgICAgICAgIH0KCgkgICAgICAgIHRvRmVhdHVyZUFycmF5KCkgewoJICAgICAgICAgICAgcmV0dXJuIFtdOwoJICAgICAgICB9CgkgICAgfQoKCSAgICBjbGFzcyBOb2RlIGV4dGVuZHMgT3NtT2JqZWN0IHsKCSAgICAgICAgY29uc3RydWN0b3IoaWQsIHJlZkVsZW1zKSB7CgkgICAgICAgICAgICBzdXBlcignbm9kZScsIGlkLCByZWZFbGVtcyk7CgkgICAgICAgICAgICB0aGlzLmxhdExuZyA9IG51bGw7CgkgICAgICAgIH0KCgkgICAgICAgIHNldExhdExuZyhsYXRMbmcpIHsKCSAgICAgICAgICAgIHRoaXMubGF0TG5nID0gbGF0TG5nOwoJICAgICAgICB9CgoJICAgICAgICB0b0ZlYXR1cmVBcnJheSgpIHsKCSAgICAgICAgICAgIGlmICh0aGlzLmxhdExuZykgewoJICAgICAgICAgICAgICAgIHJldHVybiBbewoJICAgICAgICAgICAgICAgICAgICB0eXBlOiAnRmVhdHVyZScsCgkgICAgICAgICAgICAgICAgICAgIGlkOiB0aGlzLmdldENvbXBvc2l0ZUlkKCksCgkgICAgICAgICAgICAgICAgICAgIHByb3BlcnRpZXM6IHRoaXMuZ2V0UHJvcHMoKSwKCSAgICAgICAgICAgICAgICAgICAgZ2VvbWV0cnk6IHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICdQb2ludCcsCgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogc3RyVG9GbG9hdChbdGhpcy5sYXRMbmcubG9uLCB0aGlzLmxhdExuZy5sYXRdKQoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfV07CgkgICAgICAgICAgICB9CgoJICAgICAgICAgICAgcmV0dXJuIFtdOwoJICAgICAgICB9CgoJICAgICAgICBnZXRMYXRMbmcoKSB7CgkgICAgICAgICAgICByZXR1cm4gdGhpcy5sYXRMbmc7CgkgICAgICAgIH0KCSAgICB9CgoJICAgIGNsYXNzIFdheSBleHRlbmRzIE9zbU9iamVjdCB7CgkgICAgICAgIGNvbnN0cnVjdG9yKGlkLCByZWZFbGVtcykgewoJICAgICAgICAgICAgc3VwZXIoJ3dheScsIGlkLCByZWZFbGVtcyk7CgkgICAgICAgICAgICB0aGlzLmxhdExuZ0FycmF5ID0gW107CgkgICAgICAgICAgICB0aGlzLmlzUG9seWdvbiA9IGZhbHNlOwoJICAgICAgICB9CgoJICAgICAgICBhZGRMYXRMbmcobGF0TG5nKSB7CgkgICAgICAgICAgICB0aGlzLmxhdExuZ0FycmF5LnB1c2gobGF0TG5nKTsKCSAgICAgICAgfQoKCSAgICAgICAgc2V0TGF0TG5nQXJyYXkobGF0TG5nQXJyYXkpIHsKCSAgICAgICAgICAgIHRoaXMubGF0TG5nQXJyYXkgPSBsYXRMbmdBcnJheTsKCSAgICAgICAgfQoKCSAgICAgICAgYWRkTm9kZVJlZihyZWYpIHsKCSAgICAgICAgICAgIGxldCBiaW5kZXIgPSBuZXcgTGF0ZUJpbmRlcih0aGlzLmxhdExuZ0FycmF5LCBmdW5jdGlvbiAoaWQpIHsKCSAgICAgICAgICAgICAgICBsZXQgbm9kZSA9IHRoaXMucmVmRWxlbXMuZ2V0KGBub2RlLyR7aWR9YCk7CgkgICAgICAgICAgICAgICAgaWYgKG5vZGUpIHsKCSAgICAgICAgICAgICAgICAgICAgbm9kZS5yZWZDb3VudCsrOwoJICAgICAgICAgICAgICAgICAgICByZXR1cm4gbm9kZS5nZXRMYXRMbmcoKTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9LCB0aGlzLCBbcmVmXSk7CgoJICAgICAgICAgICAgdGhpcy5sYXRMbmdBcnJheS5wdXNoKGJpbmRlcik7CgkgICAgICAgICAgICB0aGlzLnJlZkVsZW1zLmFkZEJpbmRlcihiaW5kZXIpOwoJICAgICAgICB9CgoJICAgICAgICBhbmFseXplR2VvbWV0cnlUeXBlKGssIHYpIHsKCSAgICAgICAgICAgIGxldCBvID0gcG9seWdvblRhZ3Nba107CgkgICAgICAgICAgICBpZiAobykgewoJICAgICAgICAgICAgICAgIHRoaXMuaXNQb2x5Z29uID0gdHJ1ZTsKCSAgICAgICAgICAgICAgICBpZiAoby53aGl0ZWxpc3QpIHsKCSAgICAgICAgICAgICAgICAgICAgdGhpcy5pc1BvbHlnb24gPSBvLndoaXRlbGlzdC5pbmRleE9mKHYpID49IDAgPyB0cnVlIDogZmFsc2U7CgkgICAgICAgICAgICAgICAgfSBlbHNlIGlmIChvLmJsYWNrbGlzdCkgewoJICAgICAgICAgICAgICAgICAgICB0aGlzLmlzUG9seWdvbiA9IG8uYmxhY2tsaXN0LmluZGV4T2YodikgPj0gMCA/IGZhbHNlIDogdHJ1ZTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCgkgICAgICAgIGFkZFRhZ3ModGFncykgewoJICAgICAgICAgICAgc3VwZXIuYWRkVGFncyh0YWdzKTsKCSAgICAgICAgICAgIGZvciAobGV0IFtrLCB2XSBvZiBPYmplY3QuZW50cmllcyh0YWdzKSkgewoJICAgICAgICAgICAgICAgIHRoaXMuYW5hbHl6ZUdlb21ldHJ5VHlwZShrLCB2KTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgfQoKCSAgICAgICAgYWRkVGFnKGssIHYpIHsKCSAgICAgICAgICAgIHN1cGVyLmFkZFRhZyhrLCB2KTsKCSAgICAgICAgICAgIHRoaXMuYW5hbHl6ZUdlb21ldHJ5VHlwZShrLCB2KTsKCSAgICAgICAgfQoKCSAgICAgICAgdG9Db29yZHNBcnJheSgpIHsKCSAgICAgICAgICAgIHJldHVybiB0aGlzLmxhdExuZ0FycmF5Lm1hcChsYXRMbmcgPT4gW2xhdExuZy5sb24sIGxhdExuZy5sYXRdKTsKCSAgICAgICAgfQoKCSAgICAgICAgdG9GZWF0dXJlQXJyYXkoKSB7CgkgICAgICAgICAgICBsZXQgY29vcmRzQXJyYXkgPSB0aGlzLnRvQ29vcmRzQXJyYXkoKTsKCSAgICAgICAgICAgIGlmIChjb29yZHNBcnJheS5sZW5ndGggPiAxKSB7CgkgICAgICAgICAgICAgICAgY29vcmRzQXJyYXkgPSBzdHJUb0Zsb2F0KGNvb3Jkc0FycmF5KTsKCSAgICAgICAgICAgICAgICBsZXQgZmVhdHVyZSA9IHsKCSAgICAgICAgICAgICAgICAgICAgdHlwZTogJ0ZlYXR1cmUnLAoJICAgICAgICAgICAgICAgICAgICBpZDogdGhpcy5nZXRDb21wb3NpdGVJZCgpLAoJICAgICAgICAgICAgICAgICAgICBwcm9wZXJ0aWVzOiB0aGlzLmdldFByb3BzKCksCgkgICAgICAgICAgICAgICAgICAgIGdlb21ldHJ5OiB7CgkgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAnTGluZVN0cmluZycsCgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogY29vcmRzQXJyYXkKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH07CgoJICAgICAgICAgICAgICAgIGlmICh0aGlzLmlzUG9seWdvbiAmJiBpc1JpbmcoY29vcmRzQXJyYXkpKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmIChyaW5nRGlyZWN0aW9uKGNvb3Jkc0FycmF5KSAhPT0gJ2NvdW50ZXJjbG9ja3dpc2UnKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZHNBcnJheS5yZXZlcnNlKCk7CgkgICAgICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgICAgIGZlYXR1cmUuZ2VvbWV0cnkgPSB7CgkgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAnUG9seWdvbicsCgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogW2Nvb3Jkc0FycmF5XQoJICAgICAgICAgICAgICAgICAgICB9OwoKCSAgICAgICAgICAgICAgICAgICAgcmV0dXJuIFtmZWF0dXJlXTsKCSAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIHJldHVybiBbZmVhdHVyZV07CgkgICAgICAgICAgICB9CgoJICAgICAgICAgICAgcmV0dXJuIFtdOwoJICAgICAgICB9CgkgICAgfQoKCSAgICBjbGFzcyBSZWxhdGlvbiBleHRlbmRzIE9zbU9iamVjdCB7CgkgICAgICAgIGNvbnN0cnVjdG9yKGlkLCByZWZFbGVtcykgewoJICAgICAgICAgICAgc3VwZXIoJ3JlbGF0aW9uJywgaWQsIHJlZkVsZW1zKTsKCSAgICAgICAgICAgIHRoaXMucmVsYXRpb25zID0gW107CgkgICAgICAgICAgICB0aGlzLm5vZGVzID0gW107CgkgICAgICAgICAgICB0aGlzLmJvdW5kcyA9IG51bGw7CgkgICAgICAgIH0KCgkgICAgICAgIHNldEJvdW5kcyhib3VuZHMpIHsKCSAgICAgICAgICAgIHRoaXMuYm91bmRzID0gYm91bmRzOwoJICAgICAgICB9CgoJICAgICAgICBhZGRNZW1iZXIobWVtYmVyKSB7CgkgICAgICAgICAgICBzd2l0Y2ggKG1lbWJlci50eXBlKSB7CgkgICAgICAgICAgICAgICAgLy8gc3VwZXIgcmVsYXRpb24sIG5lZWQgdG8gZG8gY29tYmluYXRpb24KCSAgICAgICAgICAgICAgICBjYXNlICdyZWxhdGlvbic6CgkgICAgICAgICAgICAgICAgICAgIGxldCBiaW5kZXIgPSBuZXcgTGF0ZUJpbmRlcih0aGlzLnJlbGF0aW9ucywgZnVuY3Rpb24gKGlkKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBsZXQgcmVsYXRpb24gPSB0aGlzLnJlZkVsZW1zLmdldChgcmVsYXRpb24vJHtpZH1gKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIGlmIChyZWxhdGlvbikgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJlbGF0aW9uLnJlZkNvdW50Kys7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHJlbGF0aW9uOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB9LCB0aGlzLCBbbWVtYmVyLnJlZl0pOwoJICAgICAgICAgICAgICAgICAgICB0aGlzLnJlbGF0aW9ucy5wdXNoKGJpbmRlcik7CgkgICAgICAgICAgICAgICAgICAgIHRoaXMucmVmRWxlbXMuYWRkQmluZGVyKGJpbmRlcik7CgkgICAgICAgICAgICAgICAgICAgIGJyZWFrOwoKCSAgICAgICAgICAgICAgICBjYXNlICd3YXknOgoJICAgICAgICAgICAgICAgICAgICBpZiAoIW1lbWJlci5yb2xlKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBtZW1iZXIucm9sZSA9ICcnOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGxldCB3YXlzID0gdGhpc1ttZW1iZXIucm9sZV07CgkgICAgICAgICAgICAgICAgICAgIGlmICghd2F5cykgewoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5cyA9IHRoaXNbbWVtYmVyLnJvbGVdID0gW107CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgaWYgKG1lbWJlci5nZW9tZXRyeSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgbGV0IHdheSA9IG5ldyBXYXkobWVtYmVyLnJlZiwgdGhpcy5yZWZFbGVtcyk7CgkgICAgICAgICAgICAgICAgICAgICAgICB3YXkuc2V0TGF0TG5nQXJyYXkobWVtYmVyLmdlb21ldHJ5KTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHdheS5yZWZDb3VudCsrOwoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5cy5wdXNoKHdheSk7CgkgICAgICAgICAgICAgICAgICAgIH0gZWxzZSBpZiAobWVtYmVyLm5vZGVzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBsZXQgd2F5ID0gbmV3IFdheShtZW1iZXIucmVmLCB0aGlzLnJlZkVsZW1zKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIGZvciAobGV0IG5pZCBvZiBtZW1iZXIubm9kZXMpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB3YXkuYWRkTm9kZVJlZihuaWQpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5LnJlZkNvdW50Kys7CgkgICAgICAgICAgICAgICAgICAgICAgICB3YXlzLnB1c2god2F5KTsKCSAgICAgICAgICAgICAgICAgICAgfSBlbHNlIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGxldCBiaW5kZXIgPSBuZXcgTGF0ZUJpbmRlcih3YXlzLCBmdW5jdGlvbiAoaWQpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBsZXQgd2F5ID0gdGhpcy5yZWZFbGVtcy5nZXQoYHdheS8ke2lkfWApOwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGlmICh3YXkpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgd2F5LnJlZkNvdW50Kys7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiB3YXk7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICAgICAgfSwgdGhpcywgW21lbWJlci5yZWZdKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHdheXMucHVzaChiaW5kZXIpOwoJICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5yZWZFbGVtcy5hZGRCaW5kZXIoYmluZGVyKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICBicmVhazsKCgkgICAgICAgICAgICAgICAgY2FzZSAnbm9kZSc6CgkgICAgICAgICAgICAgICAgICAgIGxldCBub2RlID0gbnVsbDsKCSAgICAgICAgICAgICAgICAgICAgaWYgKG1lbWJlci5sYXQgJiYgbWVtYmVyLmxvbikgewoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZSA9IG5ldyBOb2RlKG1lbWJlci5yZWYsIHRoaXMucmVmRWxlbXMpOwoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS5zZXRMYXRMbmcoeyBsb246IG1lbWJlci5sb24sIGxhdDogbWVtYmVyLmxhdCB9KTsKCSAgICAgICAgICAgICAgICAgICAgICAgIGlmIChtZW1iZXIudGFncykgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIG5vZGUuYWRkVGFncyhtZW1iZXIudGFncyk7CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgICAgICBmb3IgKGxldCBbaywgdl0gb2YgT2JqZWN0LmVudHJpZXMobWVtYmVyKSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGlmIChbJ2lkJywgJ3R5cGUnLCAnbGF0JywgJ2xvbiddLmluZGV4T2YoaykgPCAwKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIG5vZGUuYWRkUHJvcChrLCB2KTsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS5yZWZDb3VudCsrOwoJICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5ub2Rlcy5wdXNoKG5vZGUpOwoJICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgbGV0IGJpbmRlciA9IG5ldyBMYXRlQmluZGVyKHRoaXMubm9kZXMsIGZ1bmN0aW9uIChpZCkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGxldCBub2RlID0gdGhpcy5yZWZFbGVtcy5nZXQoYG5vZGUvJHtpZH1gKTsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBpZiAobm9kZSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBub2RlLnJlZkNvdW50Kys7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiBub2RlOwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgICAgIH0sIHRoaXMsIFttZW1iZXIucmVmXSk7CgkgICAgICAgICAgICAgICAgICAgICAgICB0aGlzLm5vZGVzLnB1c2goYmluZGVyKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHRoaXMucmVmRWxlbXMuYWRkQmluZGVyKGJpbmRlcik7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCgkgICAgICAgIHRvRmVhdHVyZUFycmF5KCkgewoJICAgICAgICAgICAgY29uc3QgY29uc3RydWN0U3RyaW5nR2VvbWV0cnkgPSAod3MpID0+IHsKCSAgICAgICAgICAgICAgICBsZXQgc3RyaW5ncyA9IHdzID8gd3MudG9TdHJpbmdzKCkgOiBbXTsKCSAgICAgICAgICAgICAgICBpZiAoc3RyaW5ncy5sZW5ndGggPiAwKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmIChzdHJpbmdzLmxlbmd0aCA9PT0gMSkgcmV0dXJuIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICdMaW5lU3RyaW5nJywKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBzdHJpbmdzWzBdCgkgICAgICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgICAgIHJldHVybiB7CgkgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAnTXVsdGlMaW5lU3RyaW5nJywKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBzdHJpbmdzCgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgcmV0dXJuIG51bGw7CgkgICAgICAgICAgICB9OwoKCSAgICAgICAgICAgIGNvbnN0IGNvbnN0cnVjdFBvbHlnb25HZW9tZXRyeSA9IChvd3MsIGl3cykgPT4gewoJICAgICAgICAgICAgICAgIGxldCBvdXRlclJpbmdzID0gb3dzID8gb3dzLnRvUmluZ3MoJ2NvdW50ZXJjbG9ja3dpc2UnKSA6IFtdLAoJICAgICAgICAgICAgICAgICAgICBpbm5lclJpbmdzID0gaXdzID8gaXdzLnRvUmluZ3MoJ2Nsb2Nrd2lzZScpIDogW107CgoJICAgICAgICAgICAgICAgIGlmIChvdXRlclJpbmdzLmxlbmd0aCA+IDApIHsKCSAgICAgICAgICAgICAgICAgICAgbGV0IGNvbXBvc2l0UG9seW9ucyA9IFtdOwoKCSAgICAgICAgICAgICAgICAgICAgbGV0IHJpbmcgPSBudWxsOwoJICAgICAgICAgICAgICAgICAgICBmb3IgKHJpbmcgb2Ygb3V0ZXJSaW5ncykKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvbXBvc2l0UG9seW9ucy5wdXNoKFtyaW5nXSk7CgoJICAgICAgICAgICAgICAgICAgICAvLyBsaW5rIGlubmVyIHBvbHlnb25zIHRvIG91dGVyIGNvbnRhaW5lcnMKCSAgICAgICAgICAgICAgICAgICAgd2hpbGUgKHJpbmcgPSBpbm5lclJpbmdzLnNoaWZ0KCkpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGZvciAobGV0IGlkeCBpbiBvdXRlclJpbmdzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgaWYgKHB0SW5zaWRlUG9seWdvbihmaXJzdChyaW5nKSwgb3V0ZXJSaW5nc1tpZHhdKSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb21wb3NpdFBvbHlvbnNbaWR4XS5wdXNoKHJpbmcpOwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgICAgIC8vIGNvbnN0cnVjdCB0aGUgUG9seWdvbi9NdWx0aVBvbHlnb24gZ2VvbWV0cnkKCSAgICAgICAgICAgICAgICAgICAgaWYgKGNvbXBvc2l0UG9seW9ucy5sZW5ndGggPT09IDEpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgdHlwZTogJ1BvbHlnb24nLAoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBjb21wb3NpdFBvbHlvbnNbMF0KCSAgICAgICAgICAgICAgICAgICAgICAgIH07CgkgICAgICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgICAgIHJldHVybiB7CgkgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAnTXVsdGlQb2x5Z29uJywKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBjb21wb3NpdFBvbHlvbnMKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgcmV0dXJuIG51bGw7CgkgICAgICAgICAgICB9OwoKCSAgICAgICAgICAgIGxldCBwb2x5Z29uRmVhdHVyZXMgPSBbXSwgc3RyaW5nRmVhdHVyZXMgPSBbXSwgcG9pbnRGZWF0dXJlcyA9IFtdOwoJICAgICAgICAgICAgY29uc3Qgd2F5c0ZpZWxkTmFtZXMgPSBbJ291dGVyJywgJ2lubmVyJywgJyddOwoJICAgICAgICAgICAgLy8gbmVlZCB0byBkbyBjb21iaW5hdGlvbiB3aGVuIHRoZXJlJ3JlIG5lc3RlZCByZWxhdGlvbnMKCSAgICAgICAgICAgIGZvciAobGV0IHJlbGF0aW9uIG9mIHRoaXMucmVsYXRpb25zKSB7CgkgICAgICAgICAgICAgICAgaWYgKHJlbGF0aW9uKSB7CgkgICAgICAgICAgICAgICAgICAgIGZvciAobGV0IGZpZWxkTmFtZSBvZiB3YXlzRmllbGROYW1lcykgewoJICAgICAgICAgICAgICAgICAgICAgICAgbGV0IHdheXMgPSByZWxhdGlvbltmaWVsZE5hbWVdOwoJICAgICAgICAgICAgICAgICAgICAgICAgaWYgKHdheXMpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBsZXQgdGhpc1dheXMgPSB0aGlzW2ZpZWxkTmFtZV07CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgaWYgKHRoaXNXYXlzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFtdLnNwbGljZS5hcHBseSh0aGlzV2F5cywgW3RoaXNXYXlzLmxlbmd0aCwgMF0uY29uY2F0KHdheXMpKTsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB0aGlzW2ZpZWxkTmFtZV0gPSB3YXlzOwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCgkgICAgICAgICAgICBmb3IgKGxldCBmaWVsZE5hbWUgb2Ygd2F5c0ZpZWxkTmFtZXMpIHsKCSAgICAgICAgICAgICAgICBsZXQgd2F5cyA9IHRoaXNbZmllbGROYW1lXTsKCSAgICAgICAgICAgICAgICBpZiAod2F5cykgewoJICAgICAgICAgICAgICAgICAgICB0aGlzW2ZpZWxkTmFtZV0gPSBuZXcgV2F5Q29sbGVjdGlvbigpOwoJICAgICAgICAgICAgICAgICAgICBmb3IgKGxldCB3YXkgb2Ygd2F5cykgewoJICAgICAgICAgICAgICAgICAgICAgICAgdGhpc1tmaWVsZE5hbWVdLmFkZFdheSh3YXkpOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoKCSAgICAgICAgICAgIGxldCBnZW9tZXRyeSA9IG51bGw7CgoJICAgICAgICAgICAgbGV0IGZlYXR1cmUgPSB7CgkgICAgICAgICAgICAgICAgdHlwZTogJ0ZlYXR1cmUnLAoJICAgICAgICAgICAgICAgIGlkOiB0aGlzLmdldENvbXBvc2l0ZUlkKCksCgkgICAgICAgICAgICAgICAgYmJveDogdGhpcy5ib3VuZHMsCgkgICAgICAgICAgICAgICAgcHJvcGVydGllczogdGhpcy5nZXRQcm9wcygpCgkgICAgICAgICAgICB9OwoKCSAgICAgICAgICAgIGlmICghdGhpcy5ib3VuZHMpIHsKCSAgICAgICAgICAgICAgICBkZWxldGUgZmVhdHVyZS5iYm94OwoJICAgICAgICAgICAgfQoKCSAgICAgICAgICAgIGlmICh0aGlzLm91dGVyKSB7CgkgICAgICAgICAgICAgICAgZ2VvbWV0cnkgPSBjb25zdHJ1Y3RQb2x5Z29uR2VvbWV0cnkodGhpcy5vdXRlciwgdGhpcy5pbm5lcik7CgkgICAgICAgICAgICAgICAgaWYgKGdlb21ldHJ5KSB7CgkgICAgICAgICAgICAgICAgICAgIGZlYXR1cmUuZ2VvbWV0cnkgPSBnZW9tZXRyeTsKCSAgICAgICAgICAgICAgICAgICAgcG9seWdvbkZlYXR1cmVzLnB1c2goZmVhdHVyZSk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgZWxzZSBpZiAodGhpc1snJ10pIHsKCSAgICAgICAgICAgICAgICBnZW9tZXRyeSA9IGNvbnN0cnVjdFN0cmluZ0dlb21ldHJ5KHRoaXNbJyddKTsKCSAgICAgICAgICAgICAgICBpZiAoZ2VvbWV0cnkpIHsKCSAgICAgICAgICAgICAgICAgICAgZmVhdHVyZS5nZW9tZXRyeSA9IGdlb21ldHJ5OwoJICAgICAgICAgICAgICAgICAgICBzdHJpbmdGZWF0dXJlcy5wdXNoKGZlYXR1cmUpOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCgkgICAgICAgICAgICBmb3IgKGxldCBub2RlIG9mIHRoaXMubm9kZXMpIHsKCSAgICAgICAgICAgICAgICBwb2ludEZlYXR1cmVzID0gcG9pbnRGZWF0dXJlcy5jb25jYXQobm9kZS50b0ZlYXR1cmVBcnJheSgpKTsKCSAgICAgICAgICAgIH0KCgkgICAgICAgICAgICByZXR1cm4gcG9seWdvbkZlYXR1cmVzLmNvbmNhdChzdHJp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h0aGlzLnF1ZXJ5UGFyZW50KSB7CgkgICAgICAgICAgICAgICAgICAgIHRoaXMucGFyZW50TWFwID0gbmV3IFdlYWtNYXAoKTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgICAgICB0aGlzLmV2dExpc3RlbmVycyA9IHt9OwoJICAgICAgICB9CgoJICAgICAgICBwYXJzZSh4bWwsIHBhcmVudCwgZGlyKSB7CgkgICAgICAgICAgICBkaXIgPSBkaXIgPyBkaXIgKyAnLicgOiAnJzsKCSAgICAgICAgICAgIGxldCBub2RlUmVnRXggPSAvPChbXiA+XC9dKykoLio/KT4vbWcsIG5vZGVNYXRjaCA9IG51bGwsIG5vZGVzID0gW107CgkgICAgICAgICAgICB3aGlsZSAobm9kZU1hdGNoID0gbm9kZVJlZ0V4LmV4ZWMoeG1sKSkgewoJICAgICAgICAgICAgICAgIGxldCB0YWcgPSBub2RlTWF0Y2hbMV0sIG5vZGUgPSB7ICR0YWc6IHRhZyB9LCBmdWxsVGFnID0gZGlyICsgdGFnOwoKCSAgICAgICAgICAgICAgICBsZXQgYXR0clRleHQgPSBub2RlTWF0Y2hbMl0udHJpbSgpLCBjbG9zZWQgPSBmYWxzZTsKCSAgICAgICAgICAgICAgICBpZiAoYXR0clRleHQuZW5kc1dpdGgoJy8nKSB8fCB0YWcuc3RhcnRzV2l0aCgnPycpIHx8IHRhZy5zdGFydHNXaXRoKCchJykpIHsKCSAgICAgICAgICAgICAgICAgICAgY2xvc2VkID0gdHJ1ZTsKCSAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIGxldCBhdHRSZWdFeDEgPSAvKFteIF0rPyk9IiguKz8pIi9nLCBhdHRSZWdFeDIgPSAvKFteIF0rPyk9JyguKz8pJy9nOwoJICAgICAgICAgICAgICAgIGxldCBhdHRNYXRjaCA9IG51bGwsIGhhc0F0dHJzID0gZmFsc2U7CgkgICAgICAgICAgICAgICAgd2hpbGUgKGF0dE1hdGNoID0gYXR0UmVnRXgxLmV4ZWMoYXR0clRleHQpKSB7CgkgICAgICAgICAgICAgICAgICAgIGhhc0F0dHJzID0gdHJ1ZTsKCSAgICAgICAgICAgICAgICAgICAgbm9kZVthdHRNYXRjaFsxXV0gPSBhdHRNYXRjaFsyXTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgaWYgKCFoYXNBdHRycykKCSAgICAgICAgICAgICAgICAgICAgd2hpbGUgKGF0dE1hdGNoID0gYXR0UmVnRXgyLmV4ZWMoYXR0clRleHQpKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBoYXNBdHRycyA9IHRydWU7CgkgICAgICAgICAgICAgICAgICAgICAgICBub2RlW2F0dE1hdGNoWzFdXSA9IGF0dE1hdGNoWzJdOwoJICAgICAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIGlmICghaGFzQXR0cnMgJiYgYXR0clRleHQgIT09ICcnKSB7CgkgICAgICAgICAgICAgICAgICAgIG5vZGUudGV4dCA9IGF0dHJUZXh0OwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICBpZiAodGhpcy5wcm9ncmVzc2l2ZSkgewoJICAgICAgICAgICAgICAgICAgICB0aGlzLmVtaXQoYDwke2Z1bGxUYWd9PmAsIG5vZGUsIHBhcmVudCk7CgkgICAgICAgICAgICAgICAgfQoKCSAgICAgICAgICAgICAgICBpZiAoIWNsb3NlZCkgewoJICAgICAgICAgICAgICAgICAgICBsZXQgaW5uZXJSZWdFeCA9IG5ldyBSZWdFeHAoYChbXl0rPyk8XC8ke3RhZ30+YCwgJ2cnKTsKCSAgICAgICAgICAgICAgICAgICAgaW5uZXJSZWdFeC5sYXN0SW5kZXggPSBub2RlUmVnRXgubGFzdEluZGV4OwoJICAgICAgICAgICAgICAgICAgICBsZXQgaW5uZXJNYXRjaCA9IGlubmVyUmVnRXguZXhlYyh4bWwpOwoJICAgICAgICAgICAgICAgICAgICBpZiAoaW5uZXJNYXRjaCAmJiBpbm5lck1hdGNoWzFdKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBub2RlUmVnRXgubGFzdEluZGV4ID0gaW5uZXJSZWdFeC5sYXN0SW5kZXg7CgkgICAgICAgICAgICAgICAgICAgICAgICBsZXQgaW5uZXJOb2RlcyA9IHRoaXMucGFyc2UoaW5uZXJNYXRjaFsxXSwgbm9kZSwgZnVsbFRhZyk7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAoaW5uZXJOb2Rlcy5sZW5ndGggPiAwKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS4kaW5uZXJOb2RlcyA9IGlubmVyTm9kZXM7CgkgICAgICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIG5vZGUuJGlubmVyVGV4dCA9IGlubmVyTWF0Y2hbMV07CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgaWYgKHRoaXMucXVlcnlQYXJlbnQgJiYgcGFyZW50KSB7CgkgICAgICAgICAgICAgICAgICAgIHRoaXMucGFyZW50TWFwLnNldChub2RlLCBwYXJlbnQpOwoJICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgaWYgKHRoaXMucHJvZ3Jlc3NpdmUpIHsKCSAgICAgICAgICAgICAgICAgICAgdGhpcy5lbWl0KGA8LyR7ZnVsbFRhZ30+YCwgbm9kZSwgcGFyZW50KTsKCSAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIG5vZGVzLnB1c2gobm9kZSk7CgkgICAgICAgICAgICB9CgoJICAgICAgICAgICAgcmV0dXJuIG5vZGVzOwoJICAgICAgICB9CgoJICAgICAgICBnZXRQYXJlbnQobm9kZSkgewoJICAgICAgICAgICAgaWYgKHRoaXMucXVlcnlQYXJlbnQpIHsKCSAgICAgICAgICAgICAgICByZXR1cm4gdGhpcy5w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gZnVuY3MuaW5kZXhPZihmdW5jKSkgPj0gMCkgewoJICAgICAgICAgICAgICAgIGZ1bmNzLnNwbGljZShpZHgsIDEpOwoJICAgICAgICAgICAgfQoJICAgICAgICB9CgoJICAgICAgICByZW1vdmVMaXN0ZW5lcihldnQsIGZ1bmMpIHsKCSAgICAgICAgICAgIGlmIChjb25kaXRpb25lZChldnQpKSB7CgkgICAgICAgICAgICAgICAgZXZ0ID0gcGFyc2VFdmVudChldnQpOwoJICAgICAgICAgICAgICAgIGV2dCA9IGV2dC5ldnQ7CgkgICAgICAgICAgICB9CgkgICAgICAgICAgICB0aGlzLiNyZW1vdmVMaXN0ZW5lcihldnQsIGZ1bmMpOwoJICAgICAgICB9CgoJICAgICAgICBlbWl0KGV2dCwgLi4uYXJncykgewoJICAgICAgICAgICAgbGV0IGZ1bmNzID0gdGhpcy5ldnRMaXN0ZW5lcnNbZXZ0XTsKCSAgICAgICAgICAgIGlmIChmdW5jcykgewoJICAgICAgICAgICAgICAgIGZvciAobGV0IGZ1bmMgb2YgZnVuY3MpIHsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGZ1bmMuY29uZGl0aW9uKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAoZnVuYy5jb25kaXRpb24uYXBwbHkobnVsbCwgYXJncykgPT09IHRydWUpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBmdW5jLmFwcGx5KG51bGwsIGFyZ3MpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgZnVuYy5hcHBseShudWxsLCBhcmdzKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgfQoKCSAgICAgICAgb24oZXZ0LCBmdW5jKSB7CgkgICAgICAgICAgICB0aGlzLmFkZExpc3RlbmVyKGV2dCwgZnVuYyk7CgkgICAgIC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JuICdqc29uJzsKCSAgICAgICAgfQoJICAgICAgICBpZiAob3NtLmluZGV4T2YoJzxvc20nKSA+PSAwKSB7CgkgICAgICAgICAgICByZXR1cm4gJ3htbCc7CgkgICAgICAgIH0KCSAgICAgICAgaWYgKG9zbS50cmltKCkuc3RhcnRzV2l0aCgneycpKSB7CgkgICAgICAgICAgICByZXR1cm4gJ2pzb24tcmF3JzsKCSAgICAgICAgfQoJICAgICAgICByZXR1cm4gJ2ludmFsaWQnOwoJICAgIH07CgoJICAgIGxldCBmb3JtYXQgPSBkZXRlY3RGb3JtYXQob3NtKTsKCgkgICAgbGV0IHJlZkVsZW1lbnRzID0gbmV3IFJlZkVsZW1lbnRzKCksIGZlYXR1cmVBcnJheSA9IFtdOwoKCSAgICBjb25zdCBhbmFseXplRmVhdHVyZXNGcm9tSnNvbiA9IG9zbSA9PiB7CgkgICAgICAgIGZvciAobGV0IGVsZW0gb2Ygb3NtLmVsZW1lbnRzKSB7CgkgICAgICAgICAgICBzd2l0Y2ggKGVsZW0udHlwZSkgewoJICAgICAgICAgICAgICAgIGNhc2UgJ25vZGUnOgoJICAgICAgICAgICAgICAgICAgICBsZXQgbm9kZSA9IG5ldyBOb2RlKGVsZW0uaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGVsZW0udGFncykgewoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS5hZGRUYWdzKGVsZW0udGFncyk7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgbm9kZS5hZGRQcm9wcyhwdXJnZVByb3BzKGVsZW0sIFsnaWQnLCAndHlwZScsICd0YWdzJywgJ2xhdCcsICdsb24nXSkpOwoJICAgICAgICAgICAgICAgICAgICBub2RlLnNldExhdExuZyhlbGVtKTsKCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgoJICAgICAgICAgICAgICAgIGNhc2UgJ3dheSc6CgkgICAgICAgICAgICAgICAgICAgIGxldCB3YXkgPSBuZXcgV2F5KGVsZW0uaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGVsZW0udGFncykgewoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5LmFkZFRhZ3MoZWxlbS50YWdzKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB3YXkuYWRkUHJvcHMocHVyZ2VQcm9wcyhlbGVtLCBbJ2lkJywgJ3R5cGUnLCAndGFncycsICdub2RlcycsICdnZW9tZXRyeSddKSk7CgkgICAgICAgICAgICAgICAgICAgIGlmIChlbGVtLm5vZGVzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBmb3IgKGxldCBuIG9mIGVsZW0ubm9kZXMpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB3YXkuYWRkTm9kZVJlZihuKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgfSBlbHNlIGlmIChlbGVtLmdlb21ldHJ5KSB7CgkgICAgICAgICAgICAgICAgICAgICAgICB3YXkuc2V0TGF0TG5nQXJyYXkoZWxlbS5nZW9tZXRyeSk7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgoJICAgICAgICAgICAgICAgIGNhc2UgJ3JlbGF0aW9uJzoKCSAgICAgICAgICAgICAgICAgICAgbGV0IHJlbGF0aW9uID0gbmV3IFJlbGF0aW9uKGVsZW0uaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGVsZW0uYm91bmRzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICByZWxhdGlvbi5zZXRCb3VuZHMoW3BhcnNlRmxvYXQoZWxlbS5ib3VuZHMubWlubG9uKSwgcGFyc2VGbG9hdChlbGVtLmJvdW5kcy5taW5sYXQpLCBwYXJzZUZsb2F0KGVsZW0uYm91bmRzLm1heGxvbiksIHBhcnNlRmxvYXQoZWxlbS5ib3VuZHMubWF4bGF0KV0pOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGlmIChlbGVtLnRhZ3MpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHJlbGF0aW9uLmFkZFRhZ3MoZWxlbS50YWdzKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICByZWxhdGlvbi5hZGRQcm9wcyhwdXJnZVByb3BzKGVsZW0sIFsnaWQnLCAndHlwZScsICd0YWdzJywgJ2JvdW5kcycsICdtZW1iZXJzJ10pKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGVsZW0ubWVtYmVycykgewoJICAgICAgICAgICAgICAgICAgICAgICAgZm9yIChsZXQgbWVtYmVyIG9mIGVsZW0ubWVtYmVycykgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJlbGF0aW9uLmFkZE1lbWJlcihtZW1iZXIpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGJyZWFrOwoJICAgICAgICAgICAgfQoJICAgICAgICB9CgkgICAgfTsKCgkgICAgY29uc3QgYW5hbHl6ZUZlYXR1cmVzRnJvbVhtbCA9IG9zbSA9PiB7CgkgICAgICAgIGNvbnN0IHhtbFBhcnNlciA9IG5ldyBYbWxQYXJzZXIoeyBwcm9ncmVzc2l2ZTogdHJ1ZSB9KTsKCgkgICAgICAgIHhtbFBhcnNlci5vbignPC9vc20ubm9kZT4nLCBub2RlID0+IHsKCSAgICAgICAgICAgIGxldCBuZCA9IG5ldyBOb2RlKG5vZGUuaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgIGZvciAobGV0IFtrLCB2XSBvZiBPYmplY3QuZW50cmllcyhub2RlKSkKCSAgICAgICAgICAgICAgICBpZiAoIWsuc3RhcnRzV2l0aCgnJCcpICYmIFsnaWQnLCAnbG9uJywgJ2xhdCddLmluZGV4T2YoaykgPCAwKSB7CgkgICAgICAgICAgICAgICAgICAgIG5kLmFkZFByb3Aoaywgdik7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgbmQuc2V0TGF0TG5nKG5vZGUpOwoJICAgICAgICAgICAgaWYgKG5vZGUuJGlubmVyTm9kZXMpIHsKCSAgICAgICAgICAgICAgICBmb3IgKGxldCBpbmQgb2Ygbm9kZS4kaW5uZXJOb2RlcykgewoJICAgICAgICAgICAgICAgICAgICBpZiAoaW5kLiR0YWcgPT09ICd0YWcnKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBuZC5hZGRUYWcoaW5kLmssIGluZC52KTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgfSk7CgoJICAgICAgICB4bWxQYXJzZXIub24oJzwvb3NtLndheT4nLCBub2RlID0+IHsKCSAgICAgICAgICAgIGxldCB3YXkgPSBuZXcgV2F5KG5vZGUuaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgIGZvciAobGV0IFtrLCB2XSBvZiBPYmplY3QuZW50cmllcyhub2RlKSkgewoJICAgICAgICAgICAgICAgIGlmICghay5zdGFydHNXaXRoKCckJykgJiYgWydpZCddLmluZGV4T2YoaykgPCAwKSB7CgkgICAgICAgICAgICAgICAgICAgIHdheS5hZGRQcm9wKGssIHYpOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIGlmIChub2RlLiRpbm5lck5vZGVzKSB7CgkgICAgICAgICAgICAgICAgZm9yIChsZXQgaW5kIG9mIG5vZGUuJGlubmVyTm9kZXMpIHsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGluZC4kdGFnID09PSAnbmQnKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAoaW5kLmxvbiAmJiBpbmQubGF0KSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgd2F5LmFkZExhdExuZyhpbmQpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfSBlbHNlIGlmIChpbmQucmVmKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgd2F5LmFkZE5vZGVSZWYoaW5kLnJlZik7CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIH0gZWxzZSBpZiAoaW5kLiR0YWcgPT09ICd0YWcnKQoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5LmFkZFRhZyhpbmQuaywgaW5kLnYpOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgfSk7CgoJICAgICAgICB4bWxQYXJzZXIub24oJzxvc20ucmVsYXRpb24+Jywgbm9kZSA9PiB7CgkgICAgICAgICAgICBuZXcgUmVsYXRpb24obm9kZS5pZCwgcmVmRWxlbWVudHMpOwoJICAgICAgICB9KTsKCgkgICAgICAgIHhtbFBhcnNlci5vbignPC9vc20ucmVsYXRpb24ubWVtYmVyPicsIChub2RlLCBwYXJlbnQpID0+IHsKCSAgICAgICAgICAgIGxldCByZWxhdGlvbiA9IHJlZkVsZW1lbnRzLmdldChgcmVsYXRpb24vJHtwYXJlbnQuaWR9YCk7CgkgICAgICAgICAgICBsZXQgbWVtYmVyID0gewoJICAgICAgICAgICAgICAgIHR5cGU6IG5vZGUudHlwZSwKCSAgICAgICAgICAgICAgICByb2xlOiBub2RlLnJvbGUgPyBub2RlLnJvbGUgOiAnJywKCSAgICAgICAgICAgICAgICByZWY6IG5vZGUucmVmCgkgICAgICAgICAgICB9OwoJICAgICAgICAgICAgaWYgKG5vZGUubGF0ICYmIG5vZGUubG9uKSB7CgkgICAgICAgICAgICAgICAgbWVtYmVyLmxhdCA9IG5vZGUubGF0LCBtZW1iZXIubG9uID0gbm9kZS5sb24sIG1lbWJlci50YWdzID0ge307CgkgICAgICAgICAgICAgICAgZm9yIChsZXQgW2ssIHZdIG9mIE9iamVjdC5lbnRyaWVzKG5vZGUpKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmICghay5zdGFydHNXaXRoKCckJykgJiYgWyd0eXBlJywgJ2xhdCcsICdsb24nXS5pbmRleE9mKGspIDwgMCkgewoJICAgICAgICAgICAgICAgICAgICAgICAgbWVtYmVyW2tdID0gdjsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIGlmIChub2RlLiRpbm5lck5vZGVzKSB7CgkgICAgICAgICAgICAgICAgbGV0IGdlb21ldHJ5ID0gW107CgkgICAgICAgICAgICAgICAgbGV0IG5vZGVzID0gW107CgkgICAgICAgICAgICAgICAgZm9yIChsZXQgaW5kIG9mIG5vZGUuJGlubmVyTm9kZXMpIHsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGluZC5sYXQgJiYgaW5kLmxvbikgewoJICAgICAgICAgICAgICAgICAgICAgICAgZ2VvbWV0cnkucHVzaChpbmQpOwoJICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZXMucHVzaChpbmQucmVmKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICBpZiAoZ2VvbWV0cnkubGVuZ3RoID4gMCkgewoJICAgICAgICAgICAgICAgICAgICBtZW1iZXIuZ2VvbWV0cnkgPSBnZW9tZXRyeTsKCSAgICAgICAgICAgICAgICB9IGVsc2UgaWYgKG5vZGVzLmxlbmd0aCA+IDApIHsKCSAgICAgICAgICAgICAgICAgICAgbWVtYmVyLm5vZGVzID0gbm9kZXM7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmVsYXRpb24uYWRkTWVtYmVyKG1lbWJlcik7CgkgICAgICAgIH0pOwoKCSAgICAgICAgeG1sUGFyc2VyLm9uKCc8L29zbS5yZWxhdGlvbi5ib3VuZHM+JywgKG5vZGUsIHBhcmVudCkgPT4gewoJICAgICAgICAgICAgcmVmRWxlbWVudHMuZ2V0KGByZWxhdGlvbi8ke3BhcmVudC5pZH1gKS5zZXRCb3VuZHMoW3BhcnNlRmxvYXQobm9kZS5taW5sb24pLCBwYXJzZUZsb2F0KG5vZGUubWlubGF0KSwgcGFyc2VGbG9hdChub2RlLm1heGxvbiksIHBhcnNlRmxvYXQobm9kZS5tYXhsYXQpXSk7CgkgICAgICAgIH0pOwoKCSAgICAgICAgeG1sUGFyc2VyLm9uKCc8L29zbS5yZWxhdGlvbi50YWc+JywgKG5vZGUsIHBhcmVudCkgPT4gewoJICAgICAgICAgICAgcmVmRWxlbWVudHMuZ2V0KGByZWxhdGlvbi8ke3BhcmVudC5pZH1gKS5hZGRUYWcobm9kZS5rLCBub2RlLnYpOwoJICAgICAgICB9KTsKCgkgICAgICAgIHhtbFBhcnNlci5wYXJzZShvc20pOwoJICAgIH07CgoJICAgIGlmIChmb3JtYXQgPT09ICdqc29uLXJhdycpIHsKCSAgICAgICAgb3NtID0gSlNPTi5wYXJzZShvc20pOwoJICAgICAgICBpZiAob3NtLmVsZW1lbnRzKSB7CgkgICAgICAgICAgICBmb3JtYXQgPSAnanNvbic7CgkgICAgICAgIH0gZWxzZSB7CgkgICAgICAgICAgICBmb3JtYXQgPSAnaW52YWxpZCc7CgkgICAgICAgIH0KCSAgICB9CgoJICAgIGlmIChmb3JtYXQgPT09ICdqc29uJykgewoJICAgICAgICBhbmFseXplRmVhdHVyZXNGcm9tSnNvbihvc20pOwoJICAgIH0gZWxzZSBpZiAoZm9ybWF0ID09PSAneG1sJykgewoJICAgICAgICBhbmFseXplRmVhdHVyZXNGcm9tWG1sKG9zbSk7CgkgICAgfQoKCSAgICByZWZFbGVtZW50cy5iaW5kQWxsKCk7CgoJICAgIGZvciAobGV0IHYgb2YgcmVmRWxlbWVudHMudmFsdWVzKCkpIHsKCSAgICAgICAgaWYgKHYucmVmQ291bnQgPD0gMCB8fCAodi5oYXNUYWcgJiYg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uJywKCSAgICAgICAgICAgIGZlYXR1cmVzOiBbXSwKCSAgICAgICAgfSk7CgkgICAgICAgIHRoaXMuX3Jhd0RhdGEgPSBkYXRhOwoJICAgICAgICB0aGlzLl9mb3JtYXQgPSBmb3JtYXQ7CgkgICAgICAgIHRoaXMuX29wdGlvbnMgPSBvcHRpb25zOwoJICAgICAgICBjb25zdCBjb252ZXJ0ZXJzID0gewoJICAgICAgICAgICAgJ3RvcG9qc29uJzogdGhpcy5sb2FkVG9wb0pzb24sCgkgICAgICAgICAgICAnb3NtJzogdGhpcy5sb2FkT3NtLAoJICAgICAgICAgICAgJ2ttbCc6IHRoaXMubG9hZFhtbCwKCSAgICAgICAgICAgICdncHgnOiB0aGlzLmxvYWRYbWwsCgkgICAgICAgICAgICAndGN4JzogdGhpcy5sb2FkWG1sLAoJICAgICAgICAgICAgJ2Nzdic6IHRoaXMubG9hZENzdiwKCSAgICAgICAgICAgICd0c3YnOiB0aGlzLmxvYWRDc3YsCgkgICAgICAgICAgICAncG9seWxpbmUnOiB0aGlzLmxvYWRQb2x5bGluZQoJICAgICAgICB9OwoJICAgICAgICB0aGlzLl9jb252ZXJzaW9uRm4gPSBjb252ZXJ0ZXJzW2Zvcm1hdF07CgkgICAgfQoJICAgIGFzeW5jIGNvbnZlcnQoKSB7CgkgICAgICAgIGlmICghdGhpcy5fY29udmVyc2lvbkZuKSB7CgkgICAgICAgICAgICByZXR1cm4gbmV3IFByb21pc2UoKF8sIHJlaikgPT4gcmVqKGBObyBjb252ZXJ0ZXIgZXhpc3RzIGZvciAke3RoaXMuX2Zvcm1hdH1gKSk7CgkgICAgICAgIH0KCSAgICAgICAgZWxzZSB7CgkgICAgICAgICAgICByZXR1cm4gdGhpcy5fY29udmVyc2lvbkZuKCk7CgkgICAgICAgIH0KCSAgICB9CgkgICAgLyoqCgkgICAgICogTG9hZCB0aGUgWE1MIGRhdGEgYXMgR2VvSlNPTgoJICAgICAqIEByZXR1cm5zIEEgcHJvbWlzZSByZXNv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gICBjc3YyZ2VvanNvbl8xLmNzdjJnZW9qc29uKHRoaXMuX3Jhd0RhdGEsIG9wdGlvbnMsIChlcnIsIGRhdGEpID0+IHsKCSAgICAgICAgICAgICAgICBpZiAoZXJyKSB7CgkgICAgICAgICAgICAgICAgICAgIHJlamVjdChlcnIpOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICBlbHNlIHsKCSAgICAgICAgICAgICAgICAgICAgcmVzb2x2ZShkYXRhKTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9KTsKCSAgICAgICAgfSk7CgkgICAgICAgIHJldHVybiBnZW9qc29uOwoJICAgIH0KCSAgICAvKioKCSAgICAgKiBMb2FkcyBUb3BvSlNPTiBkYXRhIGFuZCBjb252ZXJ0cyBpdCBpbnRvIGEgR2VvSlNPTiBGZWF0dXJlQ29sbGVjdGlvbgoJICAgICAqIEByZXR1cm5zIEEgUHJvbWlzZSB0aGF0IHJlc29sdmVzIHdpdGggdGhlIEdlb0pTT04gRmVhdHVyZUNvbGxlY3Rpb24uCgkgICAgICovCgkgICAgYXN5bmMgbG9hZFRvcG9Kc29uKCkgewoJICAgICAgICBsZXQgdG9wb0pzb25EYXRhID0ge307CgkgICAgICAgIHRyeSB7CgkgICAgICAgICAgICB0b3BvSnNvbkRhdGEgPSBKU09OLnBhcnNlKHRoaXMuX3Jhd0RhdGEpOwoJICAgICAgICB9CgkgICAgICAgIGNhdGNoIChlKSB7CgkgICAgICAgICAgICB0aHJvdyAiSW52YWxpZCBUb3BvSnNvbiI7CgkgICAgICAgIH0KCSAgICAgICAgLy8gQ29udmVydCB0aGUgZGF0YQoJICAgICAgICBsZXQgcmVzdWx0ID0gdGhpcy5ibGFua0dlb0pTT04oKTsKCSAgICAgICAgaWYgKHRvcG9Kc29uRGF0YS50eXBlID09PSAiVG9wb2xvZ3kiICYmIHRvcG9Kc29uRGF0YS5vYmplY3RzICE9PSB1bmRlZmluZWQpIHsKCSAgICAgICAgICAgIHJl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0IHRoZSBwb2x5bGluZSB0byBHZW9KU09OCgkgICAgICAgIGNvbnN0IGdlb2pzb24gPSBhd2FpdCBuZXcgUHJvbWlzZSgocmVzb2x2ZSwgcmVqZWN0KSA9PiB7CgkgICAgICAgICAgICB0cnkgewoJICAgICAgICAgICAgICAgIGNvbnN0IGxpbmVTdHJpbmcgPSBwb2x5bGluZUV4cG9ydHMudG9HZW9KU09OKHRoaXMuX3Jhd0RhdGEsIG9wdGlvbnMucHJlY2lzaW9uKTsKCSAgICAgICAgICAgICAgICBsZXQgZ2VvbWV0cnkgPSBsaW5lU3RyaW5nOwoJICAgICAgICAgICAgICAgIGlmIChvcHRpb25zLnR5cGUgPT09ICdwb2ludCcpIHsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGxpbmVTdHJpbmcuY29vcmRpbmF0ZXMubGVuZ3RoID09PSAxKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAvLyBNYWtlIGl0IGEgcG9pbnQKCSAgICAgICAgICAgICAgICAgICAgICAgIGdlb21ldHJ5ID0gewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICd0eXBlJzogJ1BvaW50JywKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAnY29vcmRpbmF0ZXMnOiBsaW5lU3RyaW5nLmNvb3JkaW5hdGVzWzBdCgkgICAgICAgICAgICAgICAgICAgICAgICB9OwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgY29uc29sZS53YXJuKCdDYW5ub3QgY29udmVydCBwb2x5bGluZSB0byAnICsgb3B0aW9ucy50eXBlKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICBlbHNlIGlmIChvcHRpb25zLnR5cGUgPT09ICdwb2x5Z29uJykgewoJICAgICAgICAgICAgICAgICAgICBpZiAobGluZVN0cmluZy5jb29yZGluYXRlc1swXVswXSA9PT0gbGluZVN0cmluZy5jb29yZGluYXRlc1tsaW5lU3RyaW5nLmNvb3JkaW5hdGVzLmxlbmd0aCAtIDFdWzBdICYmCgkgICAgICAgICAgICAgICAgICAgICAgICBsaW5lU3RyaW5nLmNvb3JkaW5hdGVzWzBdWzFdID09PSBsaW5lU3RyaW5nLmNvb3JkaW5hdGVzW2xpbmVTdHJpbmcuY29vcmRpbmF0ZXMubGVuZ3RoIC0gMV1bMV0pIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIC8vIE1ha2UgaXQgYSBwb2x5Z29uCgkgICAgICAgICAgICAgICAgICAgICAgICBnZW9tZXRyeSA9IHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAndHlwZSc6ICdQb2x5Z29uJywKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAnY29vcmRpbmF0ZXMnOiBbbGluZVN0cmluZy5jb29yZGluYXRlc10KCSAgICAgICAgICAgICAgICAgICAgICAgIH07CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgZWxzZSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBjb25zb2xlLndhcm4oJ0Nhbm5vdCBjb252ZXJ0IHBvbHlsaW5lIHRvICcgKyBvcHRpb25zLnR5cGUpOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIHJlc29sdmUoewoJICAgICAgICAgICAgICAgICAgICB0eXBlOiAiRmVhdHVyZUNvbGxlY3Rpb24iLAoJICAgICAgICAgICAgICAgICAgICBmZWF0dXJlczogW3sKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAidHlwZSI6ICJGZWF0dXJlIiwKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAiZ2VvbWV0cnkiOiBnZW9tZXRyeSwKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAicHJvcGVydGllcyI6IG9wdGlvbnMucHJvcGVydGllcyB8fCB7fQoJICAgICAgICAgICAgICAgICAgICAgICAgfV0KCSAgICAgICAgICAgICAgICB9KTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIGNhdGNoIChlcnIpIHsKCSAgICAgICAgICAgICAgICByZWplY3QoZXJyKTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgfSk7CgkgICAgICAgIHJldHVybiBnZW9qc29uOwoJICAgIH0KCX0KCgljb25zdCBsaWJyYXJpZXMgPSB7CgkgICAgJ0NvbnZlcnRlcic6IENvbnZlcnRlcgoJfTsKCWxldCBzdWJDbGFzczsKCXNlbGYuYWRkRXZlbnRMaXN0ZW5lcignbWVzc2FnZScsIGUgPT4gewoJICAgIGNvbnN0IGRhdGEgPSAoZS5kYXRhIHx8IGUpOwoJICAgIGNvbnN0IHBvc3QgPSAoaWQsIGVyciwgcmVzLCB0eXBlKSA9PiB7CgkgICAgICAgIHBvc3RNZXNzYWdlKHsKCSAgICAgICAgICAgIHR5cGU6IHR5cGUgPyB0eXBlIDogKGVyciA/ICdlcnJvcicgOiAncmVzcG9uc2UnKSwKCSAgICAgICAgICAgIGlkOiBpZCwKCSAgICAgICAgICAgIG1lc3NhZ2U6IHJlcywKCSAgICAgICAgICAgIGVycm9yOiBlcnIKCSAgICAgICAgfSk7CgkgICAgfTsKCSAgICBjb25zdCBjb21tYW5kcyA9IHsKCSAgICAgICAgJ2luaXQnOiAobXNnKSA9PiB7CgkgICAgICAgICAgICBjb25zdCB7IGlkLCBjb21tYW5kLCBtZXNzYWdlIH0gPSBtc2c7CgkgICAgICAgICAgICBzdWJDbGFzcyA9IG5ldyBsaWJyYXJpZXNbY29tbWFuZF0obWVzc2FnZVswXSwgbWVzc2FnZVsxXSk7CgkgICAgICAgICAgICAvLyByZXR1cm4gdGhlIGNsYXNzJyBtZXRob2RzCgkgICAgICAgICAgICBjb25zdCBmbnMgPSBbCgkgICAgICAgICAgICAgICAgLi4uT2JqZWN0LmdldE93blByb3BlcnR5TmFtZXMobGlicmFyaWVzW2NvbW1hbmRdLnByb3Rvd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ICAgICBpZiAoISFjbWQgJiYgdHlwZW9mIGNtZC50aGVuID09PSAnZnVuY3Rpb24nKSB7CgkgICAgICAgICAgICAgICAgICAgIC8vIEl0J3MgYSBwcm9taXNlLCBzbyB3YWl0IGZvciBpdAoJICAgICAgICAgICAgICAgICAgICBjbWQKCSAgICAgICAgICAgICAgICAgICAgICAgIC50aGVuKHJlcyA9PiBwb3N0KGlkLCB1bmRlZmluZWQsIHJlcykpCgkgICAgICAgICAgICAgICAgICAgICAgICAuY2F0Y2goZSA9PiBwb3N0KGlkLCBlKSk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAvLyBOb3QgYSBwcm9taXNlLCBqdXN0IHJldHVybiBpdAoJICAgICAgICAgICAgICAgICAgICBwb3N0KGlkLCB1bmRlZmluZWQsIGNtZCk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgZWxzZSB7CgkgICAgICAgICAgICAgICAgLy8gRXJyb3IKCSAgICAgICAgICAgICAgICBwb3N0KGlkLCBuZXcgRXJyb3IoYGNvbW1hbmQgIiR7Y29tbWFuZH0iIG5vdCBmb3VuZGApKTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgfQoJICAgIH07CgkgICAgaWYgKGNvbW1hbmRzW2RhdGEudHlwZV0pIHsKCSAgICAgICAgY29tbWFuZHNbZGF0YS50eXBlXShkYXRhKTsKCSAgICB9Cgl9KTsKCn0pKCk7Ci8vIyBzb3VyY2VNYXBwaW5nVVJMPXdvcmtlci5qcy5tYXAKCg==");const randomString=()=>Math.random().toString(36).substring(2);class Actor{constructor(M,et){this.initId=randomString()+"-"+M,this.worker=new rg,this.handlers=new Map,this.worker.onmessage=et=>{const Bt=et.data,Wt=this.handlers.get(Bt.id),Nt=this;if(Wt){if("response"===Bt.type&&Wt.resolve(Bt.message),"error"===Bt.type){const et=Bt.error||new Error(`Unknown error with ${M}`);Wt.reject(et)}"init_response"===Bt.type&&(this._=Object.keys(Bt.message).map((M=>{const et="function"==typeof Bt.message[M];return[M,function(){return et?Nt.exec(M)(...arguments):Nt.get(M)}]})).reduce(((M,et)=>({...M,[et[0]]:et[1]})),{}),Wt.resolve(this._))}},this.worker.postMessage({type:"init",id:this.initId,command:M,message:et})}onLoad(){return new Promise((M=>{void 0===this._?this.handlers.set(this.initId,{resolve:M,reject:M}):M(this._)}))}exec(M){const et=this;return function(...Bt){return new Promise(((Wt,Nt)=>{const $t=randomString()+"-"+M;et.handlers.set($t,{resolve:Wt,reject:Nt}),et.worker.postMessage({type:"exec",id:$t,command:M,message:[...Bt]})}))}}get(M){return new Promise(((et,Bt)=>{const Wt=randomString()+"-"+M;this.handlers.set(Wt,{resolve:et,reject:Bt}),this.worker.postMessage({type:"get",id:Wt,command:M,message:[]})}))}}const ng="test://http://example.com"!==new URL("test://http://example.com").href;async function processData(M,et,Bt){const Wt=await fetch(M,Bt?{signal:Bt.signal}:void 0);let Nt={};const $t=new URL(M,window.location.href);if($t.hash.length){const M=$t.hash,et=decodeURIComponent(M.slice(1));try{Nt=JSON.parse(et)}catch(M){console.warn("Error parsing or reading URL:",M)}}if(200==Wt.status){const M=await Wt.text();let Bt;if(["kml","tcx","gpx"].includes(et)||!(()=>{let M=!1;try{M="function"==typeof window.Worker}catch(et){M=!1}return M})()){Bt=new Converter(et,M,Nt).convert()}else{Bt=new Actor("Converter",[et,M,Nt]).exec("convert")()}return await Bt}throw new Error(`Data fetch error: ${Wt.statusText}`)}const processUrl=M=>{const et=M.split("://")[0],Bt=M.replace(new RegExp(`^${et}://`),""),Wt=ng?(M=>{const et=new RegExp("^(https?)(//)");return M.replace(et,"$1:$2")})(Bt):Bt;return{prefix:et,url:Wt}},VectorTextProtocol=(M,et)=>et instanceof AbortController?(async(M,et)=>{const{prefix:Bt,url:Wt}=processUrl(M.url);if(!Wt)throw new Error("Invalid URL: "+M.url);try{return{data:await processData(Wt,Bt,et)}}catch(M){throw new Error(M||"Unknown Error")}})(M,et):((M,et)=>{const Bt=new AbortController,{prefix:Wt,url:Nt}=processUrl(M.url);return Nt&&processData(Nt,Wt,Bt).then((M=>et(null,M))).catch((M=>et(M))),{cancel:()=>{Bt.abort()}}})(M,et);(M=>{if(document.head.querySelector(`link[href="${M}"]`))return;const et=document.createElement("link");Object.assign(et,{rel:"stylesheet",href:M,onerror:()=>console.warn("Fail to load stylesheet:",M)}),document.head.appendChild(et)})("https://unpkg.com/maplibre-gl@4.5.2/dist/maplibre-gl.css");const og=class extends defaultExport{id="maplibre";pitch=0;bearing=0;style="https://demotiles.maplibre.org/style.json";link=!1;globe=!1;maplibregl=El;static validOptions=this.validOptions.concat([new MapOption({name:"pitch",desc:"Pitch toward the horizon measured in degrees",example:"60",exampleDesc:"Look a little upward",isValid:M=>M<=90&&M>=0}),new MapOption({name:"bearing",desc:"The compass direction that is 'up'",example:"-30",exampleDesc:"Rotate map a little",isValid:M=>M<=180&&M>=-180}),new MapOption({name:"link",desc:"Syn map's position with the hash fragment of the page's URL",example:"true",exampleDesc:"Add hash for page URL",isValid:M=>"true"===M}),new MapOption({name:"style",desc:"URL of style document, read https://maplibre.org/maplibre-style-spec/",example:"https://tile.openstreetmap.jp/styles/openmaptiles/style.json",exampleDesc:"Style form OSM japan!!!",isValid:M=>URL.parse(M)}),new MapOption({name:"globe",desc:"Display a globe",example:"true",exampleDesc:"Add globe for lower zoom level",isValid:M=>"true"===M})]);async addMap({maplibregl:M,target:et,style:Bt,data:Wt,center:Nt,zoom:$t,pitch:Gr,bearing:mn,link:Hn,globe:so}){const uo=0!==Wt.filter((M=>"tile"===M.type)).length?{version:8,sources:{},layers:[]}:Bt;return this.map=new M.Map({container:et,style:uo,center:Nt,zoom:$t,pitch:Gr,bearing:mn,hash:Hn}),new Promise(((M,et)=>{this.map.on("load",(()=>{this.map.setProjection({type:so?"globe":"mercator"}),M(this.map)}))}))}getTerraDrawAdapter({maplibregl:M,map:et,draw:Bt}){return Bt?(this.terraDrawAdapter=new l({map:et,maplibregl:M}),this.terraDrawAdapter):{state:"skip"}}setControl({maplibregl:M,map:et,control:Bt}){if(!Bt||0===Object.values(Bt).filter((M=>M)).length)return{state:"skip"};if(!0===Bt.fullscreen&&et.addControl(new M.FullscreenControl),!0===Bt.scale){const Bt=new M.ScaleControl({unit:"metric"});et.addControl(Bt)}}setExtra(M){const{map:et,debug:Bt}=M;if(!Bt&&!M.eval)return{state:"skip"};!0===Bt&&(et.showTileBoundaries=!0),M.eval&&this.evalScript(M.eval,[["map",et]])}addTileData({map:M,data:et}){const Bt=et.filter((M=>"tile"===M.type));if(0===Bt.length)return{state:"skip"};const Wt=M.getStyle();Bt.forEach(((M,et)=>{const Bt=M.name?M.name:et.toString();Wt.sources[Bt]={type:"raster",tiles:[M.url],tileSize:256},Wt.layers.push({id:Bt,type:"raster",source:Bt})})),M.setStyle(Wt)}async addGPXFile({maplibregl:M,map:et,data:Bt}){const Wt=Bt.find((M=>"gpx"===M.type));if(!Wt)return{state:"skip"};var Nt;Nt=M,qh.forEach((M=>{Nt.addProtocol(M,VectorTextProtocol)}));const $t="gpx",Gr={type:"geojson",data:"gpx://"+Wt};if(et.addSource($t,Gr),et.addLayer({id:"id_"+$t,type:"line",source:$t,paint:{"line-color":"red","line-width":3}}),!Object.prototype.hasOwnProperty.call(this,"center")){const Bt=(await et.getSource($t).getData()).features[0].geometry.coordinates,Wt=Bt.reduce(((M,et)=>M.extend(et)),new M.LngLatBounds(Bt[0],Bt[0]));et.fitBounds(Wt,{padding:20})}}addMarker(M){const et=M.element?{element:M.element,anchor:"pin"===M.type?"bottom":"center"}:{},Bt=new this.maplibregl.Marker(et).setLngLat(M.xy).addTo(this.map),Wt=Bt.getElement();return Wt.classList.add("marker"),Wt.remove=()=>Bt.remove(),Wt}async updateCamera({bounds:M,center:et,zoom:Bt,animation:Wt,...Nt},$t){return M?this.map.fitBounds(M,{linear:!0,...Nt}):Wt||$t?this.map.flyTo({center:et??this.map.getCenter(),zoom:Bt??this.map.getZoom(),...Nt}):(this.map.setCenter(et),this.map.setZoom(Bt)),new Promise((M=>{this.map.on("zoomend",(()=>{M("zoomend")}))}))}project([M,et]){return this.map.project([M,et])}unproject([M,et]){const{lng:Bt,lat:Wt}=this.map.unproject([M,et]);return[Bt,Wt]}};M.default=og,Object.defineProperty(M,"__esModule",{value:!0}),renderByScriptTarget()})); diff --git a/dist/renderers/maplibre.mjs b/dist/renderers/maplibre.mjs index 86af72d..0af8f51 100644 --- a/dist/renderers/maplibre.mjs +++ b/dist/renderers/maplibre.mjs @@ -1,4348 +1,5 @@ -function t(){return t=Object.assign?Object.assign.bind():function(t){for(var e=1;e{const{x:i,y:o}=t,{x:s,y:r}=e,n=s-i,a=r-o;return Math.sqrt(a*a+n*n)};class o{constructor({name:t,callback:e,unregister:i,register:o}){this.name=undefined,this.callback=undefined,this.registered=false,this.register=undefined,this.unregister=undefined,this.name=t,this.register=()=>{this.registered||(this.registered=true,o(e));},this.unregister=()=>{this.register&&(this.registered=false,i(e));},this.callback=e;}}class s{constructor(t){this._minPixelDragDistance=undefined,this._minPixelDragDistanceDrawing=undefined,this._minPixelDragDistanceSelecting=undefined,this._lastDrawEvent=undefined,this._coordinatePrecision=undefined,this._heldKeys=new Set,this._listeners=[],this._dragState="not-dragging",this._currentModeCallbacks=undefined,this._minPixelDragDistance="number"==typeof t.minPixelDragDistance?t.minPixelDragDistance:1,this._minPixelDragDistanceSelecting="number"==typeof t.minPixelDragDistanceSelecting?t.minPixelDragDistanceSelecting:1,this._minPixelDragDistanceDrawing="number"==typeof t.minPixelDragDistanceDrawing?t.minPixelDragDistanceDrawing:8,this._coordinatePrecision="number"==typeof t.coordinatePrecision?t.coordinatePrecision:9;}getButton(t){return -1===t.button?"neither":0===t.button?"left":1===t.button?"middle":2===t.button?"right":"neither"}getMapElementXYPosition(t){const e=this.getMapEventElement(),{left:i,top:o}=e.getBoundingClientRect();return {containerX:t.clientX-i,containerY:t.clientY-o}}getDrawEventFromEvent(t){const i=this.getLngLatFromEvent(t);if(!i)return null;const{lng:o,lat:s}=i,{containerX:r,containerY:n}=this.getMapElementXYPosition(t),a=this.getButton(t),l=Array.from(this._heldKeys);return {lng:e(o,this._coordinatePrecision),lat:e(s,this._coordinatePrecision),containerX:r,containerY:n,button:a,heldKeys:l}}register(t){this._currentModeCallbacks=t,this._listeners=this.getAdapterListeners(),this._listeners.forEach(t=>{t.register();});}getCoordinatePrecision(){return this._coordinatePrecision}getAdapterListeners(){return [new o({name:"pointerdown",callback:t=>{if(!this._currentModeCallbacks)return;if(!t.isPrimary)return;const e=this.getDrawEventFromEvent(t);e&&(this._dragState="pre-dragging",this._lastDrawEvent=e);},register:t=>{this.getMapEventElement().addEventListener("pointerdown",t);},unregister:t=>{this.getMapEventElement().removeEventListener("pointerdown",t);}}),new o({name:"pointermove",callback:t=>{if(!this._currentModeCallbacks)return;if(!t.isPrimary)return;t.preventDefault();const e=this.getDrawEventFromEvent(t);if(e)if("not-dragging"===this._dragState)this._currentModeCallbacks.onMouseMove(e),this._lastDrawEvent=e;else if("pre-dragging"===this._dragState){if(!this._lastDrawEvent)return;const t={x:this._lastDrawEvent.containerX,y:this._lastDrawEvent.containerY},o={x:e.containerX,y:e.containerY},s=this._currentModeCallbacks.getState(),r=i(t,o);let n=false;if(n="drawing"===s?r{this.setDraggability.bind(this)(t);});}else "dragging"===this._dragState&&this._currentModeCallbacks.onDrag(e,t=>{this.setDraggability.bind(this)(t);});},register:t=>{this.getMapEventElement().addEventListener("pointermove",t);},unregister:t=>{this.getMapEventElement().removeEventListener("pointermove",t);}}),new o({name:"contextmenu",callback:t=>{this._currentModeCallbacks&&t.preventDefault();},register:t=>{this.getMapEventElement().addEventListener("contextmenu",t);},unregister:t=>{this.getMapEventElement().removeEventListener("contextmenu",t);}}),new o({name:"pointerup",callback:t=>{if(!this._currentModeCallbacks)return;if(t.target!==this.getMapEventElement())return;if(!t.isPrimary)return;const e=this.getDrawEventFromEvent(t);e&&("dragging"===this._dragState?this._currentModeCallbacks.onDragEnd(e,t=>{this.setDraggability.bind(this)(t);}):"not-dragging"!==this._dragState&&"pre-dragging"!==this._dragState||this._currentModeCallbacks.onClick(e),this._dragState="not-dragging",this.setDraggability(true));},register:t=>{this.getMapEventElement().addEventListener("pointerup",t);},unregister:t=>{this.getMapEventElement().removeEventListener("pointerup",t);}}),new o({name:"keyup",callback:t=>{this._currentModeCallbacks&&(this._heldKeys.delete(t.key),this._currentModeCallbacks.onKeyUp({key:t.key,heldKeys:Array.from(this._heldKeys),preventDefault:()=>t.preventDefault()}));},register:t=>{this.getMapEventElement().addEventListener("keyup",t);},unregister:t=>{this.getMapEventElement().removeEventListener("keyup",t);}}),new o({name:"keydown",callback:t=>{this._currentModeCallbacks&&(this._heldKeys.add(t.key),this._currentModeCallbacks.onKeyDown({key:t.key,heldKeys:Array.from(this._heldKeys),preventDefault:()=>t.preventDefault()}));},register:t=>{this.getMapEventElement().addEventListener("keydown",t);},unregister:t=>{this.getMapEventElement().removeEventListener("keydown",t);}})]}unregister(){this._listeners.forEach(t=>{t.unregister();}),this.clear();}}class a extends s{constructor(t){super(t),this._nextRender=undefined,this._map=undefined,this._container=undefined,this._rendered=false,this.changedIds={deletion:false,points:false,linestrings:false,polygons:false,styling:false},this._map=t.map,this._container=this._map.getContainer();}clearLayers(){this._rendered&&(["point","linestring","polygon"].forEach(t=>{const e=`td-${t.toLowerCase()}`;this._map.removeLayer(e),"polygon"===t&&this._map.removeLayer(e+"-outline"),this._map.removeSource(e);}),this._rendered=false,this._nextRender&&(cancelAnimationFrame(this._nextRender),this._nextRender=undefined));}_addGeoJSONSource(t,e){this._map.addSource(t,{type:"geojson",data:{type:"FeatureCollection",features:e},tolerance:0});}_addFillLayer(t){return this._map.addLayer({id:t,source:t,type:"fill",paint:{"fill-color":["get","polygonFillColor"],"fill-opacity":["get","polygonFillOpacity"]}})}_addFillOutlineLayer(t,e){const i=this._map.addLayer({id:t+"-outline",source:t,type:"line",paint:{"line-width":["get","polygonOutlineWidth"],"line-color":["get","polygonOutlineColor"]}});return e&&this._map.moveLayer(t,e),i}_addLineLayer(t,e){const i=this._map.addLayer({id:t,source:t,type:"line",paint:{"line-width":["get","lineStringWidth"],"line-color":["get","lineStringColor"]}});return e&&this._map.moveLayer(t,e),i}_addPointLayer(t,e){const i=this._map.addLayer({id:t,source:t,type:"circle",paint:{"circle-stroke-color":["get","pointOutlineColor"],"circle-stroke-width":["get","pointOutlineWidth"],"circle-radius":["get","pointWidth"],"circle-color":["get","pointColor"]}});return e&&this._map.moveLayer(t,e),i}_addLayer(t,e,i){"Point"===e&&this._addPointLayer(t,i),"LineString"===e&&this._addLineLayer(t,i),"Polygon"===e&&(this._addFillLayer(t),this._addFillOutlineLayer(t,i));}_addGeoJSONLayer(t,e){const i=`td-${t.toLowerCase()}`;return this._addGeoJSONSource(i,e),this._addLayer(i,t),i}_setGeoJSONLayerData(t,e){const i=`td-${t.toLowerCase()}`;return this._map.getSource(i).setData({type:"FeatureCollection",features:e}),i}getEmptyGeometries(){return {points:[],linestrings:[],polygons:[]}}updateChangedIds(t){[...t.updated,...t.created].forEach(t=>{"Point"===t.geometry.type?this.changedIds.points=true:"LineString"===t.geometry.type?this.changedIds.linestrings=true:"Polygon"===t.geometry.type&&(this.changedIds.polygons=true);}),t.deletedIds.length>0&&(this.changedIds.deletion=true),0===t.created.length&&0===t.updated.length&&0===t.deletedIds.length&&(this.changedIds.styling=true);}getLngLatFromEvent(t){const{left:e,top:i}=this._container.getBoundingClientRect();return this.unproject(t.clientX-e,t.clientY-i)}getMapEventElement(){return this._map.getCanvas()}setDraggability(t){t?(this._map.dragRotate.enable(),this._map.dragPan.enable()):(this._map.dragRotate.disable(),this._map.dragPan.disable());}project(t,e){const{x:i,y:o}=this._map.project({lng:t,lat:e});return {x:i,y:o}}unproject(t,e){const{lng:i,lat:o}=this._map.unproject({x:t,y:e});return {lng:i,lat:o}}setCursor(t){const e=this._map.getCanvas();"unset"===t?e.style.removeProperty("cursor"):e.style.cursor=t;}setDoubleClickToZoom(t){t?this._map.doubleClickZoom.enable():this._map.doubleClickZoom.disable();}render(t,e){this.updateChangedIds(t),this._nextRender&&cancelAnimationFrame(this._nextRender),this._nextRender=requestAnimationFrame(()=>{const i=[...t.created,...t.updated,...t.unchanged],o=this.getEmptyGeometries();for(let t=0;t{const{properties:i}=s;if(i.mode!==t)return;const r=e[t](s);"Point"===s.geometry.type?(i.pointColor=r.pointColor,i.pointOutlineColor=r.pointOutlineColor,i.pointOutlineWidth=r.pointOutlineWidth,i.pointWidth=r.pointWidth,o.points.push(s)):"LineString"===s.geometry.type?(i.lineStringColor=r.lineStringColor,i.lineStringWidth=r.lineStringWidth,o.linestrings.push(s)):"Polygon"===s.geometry.type&&(i.polygonFillColor=r.polygonFillColor,i.polygonFillOpacity=r.polygonFillOpacity,i.polygonOutlineColor=r.polygonOutlineColor,i.polygonOutlineWidth=r.polygonOutlineWidth,o.polygons.push(s));});}const{points:s,linestrings:r,polygons:n}=o;if(this._rendered){const t=this.changedIds.deletion||this.changedIds.styling,e=t||this.changedIds.linestrings,i=t||this.changedIds.polygons;let o;(t||this.changedIds.points)&&(o=this._setGeoJSONLayerData("Point",s)),e&&this._setGeoJSONLayerData("LineString",r),i&&this._setGeoJSONLayerData("Polygon",n),o&&this._map.moveLayer(o);}else {const t=this._addGeoJSONLayer("Point",s);this._addGeoJSONLayer("LineString",r),this._addGeoJSONLayer("Polygon",n),this._rendered=true,t&&this._map.moveLayer(t);}this.changedIds={points:false,linestrings:false,polygons:false,deletion:false,styling:false};});}clear(){this._currentModeCallbacks&&(this._currentModeCallbacks.onClear(),this.clearLayers());}getCoordinatePrecision(){return super.getCoordinatePrecision()}unregister(){return super.unregister()}register(t){super.register(t),this._currentModeCallbacks&&this._currentModeCallbacks.onReady&&this._currentModeCallbacks.onReady();}}class l extends s{constructor(t){super(t),this.mapboxglAdapter=undefined,this.mapboxglAdapter=new a(t);}register(t){this.mapboxglAdapter.register(t);}unregister(){this.mapboxglAdapter.unregister();}getCoordinatePrecision(){return this.mapboxglAdapter.getCoordinatePrecision()}getLngLatFromEvent(t){return this.mapboxglAdapter.getLngLatFromEvent(t)}getMapEventElement(){return this.mapboxglAdapter.getMapEventElement()}setDraggability(t){this.mapboxglAdapter.setDraggability(t);}project(t,e){return this.mapboxglAdapter.project(t,e)}unproject(t,e){return this.mapboxglAdapter.unproject(t,e)}setCursor(t){this.mapboxglAdapter.setCursor(t);}setDoubleClickToZoom(t){this.mapboxglAdapter.setDoubleClickToZoom(t);}render(t,e){this.mapboxglAdapter.render(t,e);}clear(){this.mapboxglAdapter.clear();}}let c=0;const b="undefined"!=typeof navigator&&undefined!==navigator.userAgent?navigator.userAgent.toLowerCase():"";b.includes("firefox"),b.includes("safari")&&!b.includes("chrom")&&(b.includes("version/15.4")||/cpu (os|iphone os) 15_4 like mac os x/.test(b)),b.includes("webkit")&&b.includes("edge"),b.includes("macintosh");"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof OffscreenCanvas&&self instanceof WorkerGlobalScope;!function(){let t=false;try{const e=Object.defineProperty({},"passive",{get:function(){t=!0;}});window.addEventListener("_",null,e),window.removeEventListener("_",null,e);}catch(t){}}();var O=class{constructor(){this.disposed=false;}dispose(){this.disposed||(this.disposed=true,this.disposeInternal());}disposeInternal(){}},L=class{constructor(t){this.type=t,this.target=null;}preventDefault(){this.defaultPrevented=true;}stopPropagation(){this.propagationStopped=true;}};function W(){}function j(t){for(const e in t)delete t[e];}var B=class extends O{constructor(t){super(),this.eventTarget_=t,this.pendingRemovals_=null,this.dispatching_=null,this.listeners_=null;}addEventListener(t,e){if(!t||!e)return;const i=this.listeners_||(this.listeners_={}),o=i[t]||(i[t]=[]);o.includes(e)||o.push(e);}dispatchEvent(t){const e="string"==typeof t,i=e?t:t.type,o=this.listeners_&&this.listeners_[i];if(!o)return;const s=e?new L(t):t;s.target||(s.target=this.eventTarget_||this);const r=this.dispatching_||(this.dispatching_={}),n=this.pendingRemovals_||(this.pendingRemovals_={});let a;i in r||(r[i]=0,n[i]=0),++r[i];for(let t=0,e=o.length;t0)}removeEventListener(t,e){if(!this.listeners_)return;const i=this.listeners_[t];if(!i)return;const o=i.indexOf(e);-1!==o&&(this.pendingRemovals_&&t in this.pendingRemovals_?(i[o]=W,++this.pendingRemovals_[t]):(i.splice(o,1),0===i.length&&delete this.listeners_[t]));}},G="change";function N(t,e,i,o,s){if(s){const s=i;i=function(){t.removeEventListener(e,i),s.apply(this,arguments);};}const r={target:t,type:e,listener:i};return t.addEventListener(e,i),r}function A(t,e,i,o){return N(t,e,i,o,true)}function R(t){t&&t.target&&(t.target.removeEventListener(t.type,t.listener),j(t));}var H=class extends B{constructor(){super(),this.on=this.onInternal,this.once=this.onceInternal,this.un=this.unInternal,this.revision_=0;}changed(){++this.revision_,this.dispatchEvent(G);}getRevision(){return this.revision_}onInternal(t,e){if(Array.isArray(t)){const i=t.length,o=new Array(i);for(let s=0;s1?i:2,undefined===e&&(e=i>2?t.slice():new Array(o));for(let s=0;syt?i=yt:i<-yt&&(i=-yt),e[s+1]=i;}return e},Lt=function(t,e,i){const o=t.length;i=i>1?i:2,undefined===e&&(e=i>2?t.slice():new Array(o));for(let s=0;st*Math.PI/180,o=i(t[1]),s=i(t[0]),r=i(e[1]),n=r-o,a=i(e[0])-s,l=Math.sin(n/2)*Math.sin(n/2)+Math.cos(o)*Math.cos(r)*Math.sin(a/2)*Math.sin(a/2);return 2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l))*6371e3/1e3}const Yt=6371008.8;function Ht(t){return t%360*Math.PI/180}function Kt(t){return t/(Yt/1e3)}function Jt(t){return t%(2*Math.PI)*180/Math.PI}const $t=57.29577951308232,qt=.017453292519943295,Zt=6378137,Qt=(t,e)=>({x:0===t?0:t*qt*Zt,y:0===e?0:Math.log(Math.tan(Math.PI/4+e*qt/2))*Zt}),te=(t,e)=>({lng:0===t?0:$t*(t/Zt),lat:0===e?0:(2*Math.atan(Math.exp(e/Zt))-Math.PI/2)*$t});function ee(t,e,i){const o=Ht(t[0]),s=Ht(t[1]),r=Ht(i),n=Kt(e),a=Math.asin(Math.sin(s)*Math.cos(n)+Math.cos(s)*Math.sin(n)*Math.cos(r));return [Jt(o+Math.atan2(Math.sin(r)*Math.sin(n)*Math.cos(s),Math.cos(n)-Math.sin(s)*Math.sin(a))),Jt(a)]}function ie(t){const{center:i,radiusKilometers:o,coordinatePrecision:s}=t,r=t.steps?t.steps:64,n=[];for(let t=0;t0;function s(t){return t<0-e.epsilon||t>1+e.epsilon}function r(t,e,r,n){const a=i[t][e],l=i[t][e+1],h=i[r][n],c=i[r][n+1],d=function(t,e,i,o){if(se(t,i)||se(t,o)||se(e,i)||se(o,i))return null;const s=t[0],r=t[1],n=e[0],a=e[1],l=i[0],h=i[1],c=o[0],d=o[1],u=(s-n)*(h-d)-(r-a)*(l-c);return 0===u?null:[((s*a-r*n)*(l-c)-(s-n)*(l*d-h*c))/u,((s*a-r*n)*(h-d)-(r-a)*(l*d-h*c))/u]}(a,l,h,c);if(null===d)return;let u,g;u=l[0]!==a[0]?(d[0]-a[0])/(l[0]-a[0]):(d[1]-a[1])/(l[1]-a[1]),g=c[0]!==h[0]?(d[0]-h[0])/(c[0]-h[0]):(d[1]-h[1])/(c[1]-h[1]),s(u)||s(g)||(d.toString(),o.push(d));}}function se(t,e){return t[0]===e[0]&&t[1]===e[1]}function re(t,e){return 2===t.length&&"number"==typeof t[0]&&"number"==typeof t[1]&&Infinity!==t[0]&&Infinity!==t[1]&&(o=t[0])>=-180&&o<=180&&(i=t[1])>=-90&&i<=90&&ne(t[0])<=e&&ne(t[1])<=e;var i,o;}function ne(t){let e=1,i=0;for(;Math.round(t*e)/e!==t;)e*=10,i++;return i}function ae(t,e){return "Polygon"===t.geometry.type&&1===t.geometry.coordinates.length&&t.geometry.coordinates[0].length>=4&&t.geometry.coordinates[0].every(t=>re(t,e))&&(i=t.geometry.coordinates[0][0])[0]===(o=t.geometry.coordinates[0][t.geometry.coordinates[0].length-1])[0]&&i[1]===o[1];var i,o;}function le(t,e){return ae(t,e)&&!oe(t)}class he extends Tt{constructor(e){var i;super(e),this.mode="circle",this.center=undefined,this.clickCount=0,this.currentCircleId=undefined,this.keyEvents=undefined,this.cursors=undefined,this.startingRadiusKilometers=1e-5;const o={start:"crosshair"};if(this.cursors=e&&e.cursors?t({},o,e.cursors):o,null===(null==e?undefined:e.keyEvents))this.keyEvents={cancel:null,finish:null};else {const i={cancel:"Escape",finish:"Enter"};this.keyEvents=e&&e.keyEvents?t({},i,e.keyEvents):i;}this.startingRadiusKilometers=null!=(i=null==e?undefined:e.startingRadiusKilometers)?i:1e-5,this.validate=null==e?undefined:e.validation;}close(){if(undefined===this.currentCircleId)return;const t=this.currentCircleId;if(this.validate&&t){const e=this.store.getGeometryCopy(t);if(!this.validate({type:"Feature",id:t,geometry:e,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:Wt.Finish}))return}this.center=undefined,this.currentCircleId=undefined,this.clickCount=0,"drawing"===this.state&&this.setStarted(),this.onFinish(t,{mode:this.mode,action:"draw"});}start(){this.setStarted(),this.setCursor(this.cursors.start);}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset");}onClick(t){if(0===this.clickCount){this.center=[t.lng,t.lat];const e=ie({center:this.center,radiusKilometers:this.startingRadiusKilometers,coordinatePrecision:this.coordinatePrecision}),[i]=this.store.create([{geometry:e.geometry,properties:{mode:this.mode,radiusKilometers:this.startingRadiusKilometers}}]);this.currentCircleId=i,this.clickCount++,this.setDrawing();}else 1===this.clickCount&&this.center&&undefined!==this.currentCircleId&&this.updateCircle(t),this.close();}onMouseMove(t){this.updateCircle(t);}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close();}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const t=this.currentCircleId;this.center=undefined,this.currentCircleId=undefined,this.clickCount=0,"drawing"===this.state&&this.setStarted();try{void 0!==t&&this.store.delete([t]);}catch(t){}}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});return "Feature"===e.type&&"Polygon"===e.geometry.type&&e.properties.mode===this.mode?(i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=10,i):i}validateFeature(t){return !!super.validateFeature(t)&&t.properties.mode===this.mode&&le(t,this.coordinatePrecision)}updateCircle(t){if(1===this.clickCount&&this.center&&this.currentCircleId){const i=Ut(this.center,[t.lng,t.lat]);let o;if("web-mercator"===this.projection){const s=function(t,e){const i=1e3*Ut(t,e);if(0===i)return 1;const{x:o,y:s}=Qt(t[0],t[1]),{x:r,y:n}=Qt(e[0],e[1]);return Math.sqrt(Math.pow(r-o,2)+Math.pow(n-s,2))/i}(this.center,[t.lng,t.lat]);o=function(t){const{center:i,radiusKilometers:o,coordinatePrecision:s}=t,r=t.steps?t.steps:64,n=1e3*o,[a,l]=i,{x:h,y:c}=Qt(a,l),d=[];for(let t=0;t[t.lng,t.lat])]}}}class ge extends de{constructor(t){super(t);}create(t){const{containerX:e,containerY:i}=t;return ue({unproject:this.unproject,point:{x:e,y:i},pointerDistance:this.pointerDistance})}}class pe extends de{constructor(t){super(t);}measure(t,e){const{x:o,y:s}=this.project(e[0],e[1]);return i({x:o,y:s},{x:t.containerX,y:t.containerY})}}class ye extends de{constructor(t,e,i){super(t),this.config=undefined,this.pixelDistance=undefined,this.clickBoundingBox=undefined,this.getSnappableCoordinateFirstClick=t=>this.getSnappable(t,t=>Boolean(t.properties&&t.properties.mode===this.mode)),this.getSnappableCoordinate=(t,e)=>this.getSnappable(t,t=>Boolean(t.properties&&t.properties.mode===this.mode&&t.id!==e)),this.config=t,this.pixelDistance=e,this.clickBoundingBox=i;}getSnappable(t,e){const i=this.clickBoundingBox.create(t),o=this.store.search(i,e),s={coord:undefined,minDist:Infinity};return o.forEach(e=>{let i;if("Polygon"===e.geometry.type)i=e.geometry.coordinates[0];else {if("LineString"!==e.geometry.type)return;i=e.geometry.coordinates;}i.forEach(e=>{const i=this.pixelDistance.measure(t,e);i180?s-=360:s<-180&&(s+=360),s}function Ce(t,e,i){const o=[],s=t.length;let r,n,a,l=0;for(let s=0;s=l&&s===t.length-1);s++){if(l>e&&0===o.length){if(r=e-l,!r)return o.push(t[s]),o;n=ve(t[s],t[s-1])-180,a=me(t[s],r,n),o.push(a);}if(l>=i)return r=i-l,r?(n=ve(t[s],t[s-1])-180,a=me(t[s],r,n),o.push(a),o):(o.push(t[s]),o);if(l>=e&&o.push(t[s]),s===t.length-1)return o;l+=Ut(t[s],t[s+1]);}if(l[e(t[0],this.config.coordinatePrecision),e(t[1],this.config.coordinatePrecision)])}}function we(t,e){return t[0]===e[0]&&t[1]===e[1]}class Se extends Tt{constructor(e){super(e),this.mode="linestring",this.currentCoordinate=0,this.currentId=undefined,this.closingPointId=undefined,this.keyEvents=undefined,this.snappingEnabled=undefined,this.cursors=undefined,this.mouseMove=false,this.insertCoordinates=undefined,this.lastCommitedCoordinates=undefined,this.snapping=undefined,this.insertPoint=undefined;const i={start:"crosshair",close:"pointer"};if(this.cursors=e&&e.cursors?t({},i,e.cursors):i,this.snappingEnabled=!(!e||undefined===e.snapping)&&e.snapping,null===(null==e?undefined:e.keyEvents))this.keyEvents={cancel:null,finish:null};else {const i={cancel:"Escape",finish:"Enter"};this.keyEvents=e&&e.keyEvents?t({},i,e.keyEvents):i;}this.validate=null==e?undefined:e.validation,this.insertCoordinates=null==e?undefined:e.insertCoordinates;}close(){if(undefined===this.currentId)return;const t=this.store.getGeometryCopy(this.currentId);t.coordinates.pop(),this.updateGeometries([...t.coordinates],undefined,Wt.Commit);const e=this.currentId;this.closingPointId&&this.store.delete([this.closingPointId]),this.currentCoordinate=0,this.currentId=undefined,this.closingPointId=undefined,this.lastCommitedCoordinates=undefined,"drawing"===this.state&&this.setStarted(),this.onFinish(e,{mode:this.mode,action:"draw"});}updateGeometries(t,e,i){if(!this.currentId)return;const o={type:"LineString",coordinates:t};if(this.validate&&!this.validate({type:"Feature",geometry:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:i}))return;const s=[{id:this.currentId,geometry:o}];this.closingPointId&&e&&s.push({id:this.closingPointId,geometry:{type:"Point",coordinates:e}}),"commit"===i&&(this.lastCommitedCoordinates=o.coordinates),this.store.updateGeometry(s);}generateInsertCoordinates(t,e){if(!this.insertCoordinates||!this.lastCommitedCoordinates)throw new Error("Not able to insert coordinates");if("amount"!==this.insertCoordinates.strategy)throw new Error("Strategy does not exist");const i=Ut(t,e)/(this.insertCoordinates.value+1);let o=[];return "globe"===this.projection?o=this.insertPoint.generateInsertionGeodesicCoordinates(t,e,i):"web-mercator"===this.projection&&(o=this.insertPoint.generateInsertionCoordinates(t,e,i)),o}createLine(t){const[e]=this.store.create([{geometry:{type:"LineString",coordinates:[t,t]},properties:{mode:this.mode}}]);this.lastCommitedCoordinates=[t,t],this.currentId=e,this.currentCoordinate++,this.setDrawing();}firstUpdateToLine(t){if(!this.currentId)return;const e=this.store.getGeometryCopy(this.currentId).coordinates,[i]=this.store.create([{geometry:{type:"Point",coordinates:[...t]},properties:{mode:this.mode}}]);this.closingPointId=i,this.setCursor(this.cursors.close);const o=[...e,t];this.updateGeometries(o,undefined,Wt.Commit),this.currentCoordinate++;}updateToLine(t,e){if(!this.currentId)return;const o=this.store.getGeometryCopy(this.currentId).coordinates,[s,r]=this.lastCommitedCoordinates?this.lastCommitedCoordinates[this.lastCommitedCoordinates.length-1]:o[o.length-2],{x:n,y:a}=this.project(s,r);if(i({x:n,y:a},{x:e.x,y:e.y})0&&!this.mouseMove&&this.onMouseMove(t),this.mouseMove=false;const e=this.currentId&&this.snappingEnabled&&this.snapping.getSnappableCoordinate(t,this.currentId)||[t.lng,t.lat];0===this.currentCoordinate?this.createLine(e):1===this.currentCoordinate&&this.currentId?this.firstUpdateToLine(e):this.currentId&&this.updateToLine(e,{x:t.containerX,y:t.containerY});}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel&&this.cleanUp(),t.key===this.keyEvents.finish&&this.close();}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const t=this.currentId;this.closingPointId=undefined,this.currentId=undefined,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted();try{void 0!==t&&this.store.delete([t]),void 0!==this.closingPointId&&this.store.delete([this.closingPointId]);}catch(t){}}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});return "Feature"===e.type&&"LineString"===e.geometry.type&&e.properties.mode===this.mode?(i.lineStringColor=this.getHexColorStylingValue(this.styles.lineStringColor,i.lineStringColor,e),i.lineStringWidth=this.getNumericStylingValue(this.styles.lineStringWidth,i.lineStringWidth,e),i.zIndex=10,i):"Feature"===e.type&&"Point"===e.geometry.type&&e.properties.mode===this.mode?(i.pointColor=this.getHexColorStylingValue(this.styles.closingPointColor,i.pointColor,e),i.pointWidth=this.getNumericStylingValue(this.styles.closingPointWidth,i.pointWidth,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.closingPointOutlineColor,"#ffffff",e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.closingPointOutlineWidth,2,e),i.zIndex=40,i):i}validateFeature(t){return !!super.validateFeature(t)&&"LineString"===t.geometry.type&&t.properties.mode===this.mode&&t.geometry.coordinates.length>=2}}function be(t,e){return "Point"===t.geometry.type&&re(t.geometry.coordinates,e)}class Ee extends Tt{constructor(e){super(e),this.mode="point",this.cursors=undefined;const i={create:"crosshair"};this.cursors=e&&e.cursors?t({},i,e.cursors):i;}start(){this.setStarted(),this.setCursor(this.cursors.create);}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset");}onClick(t){if(!this.store)throw new Error("Mode must be registered first");const e={type:"Point",coordinates:[t.lng,t.lat]},i={mode:this.mode};if(this.validate&&!this.validate({type:"Feature",geometry:e,properties:i},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:Wt.Finish}))return;const[o]=this.store.create([{geometry:e,properties:i}]);this.onFinish(o,{mode:this.mode,action:"draw"});}onMouseMove(){}onKeyDown(){}onKeyUp(){}cleanUp(){}onDragStart(){}onDrag(){}onDragEnd(){}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});return "Feature"===e.type&&"Point"===e.geometry.type&&e.properties.mode===this.mode&&(i.pointWidth=this.getNumericStylingValue(this.styles.pointWidth,i.pointWidth,e),i.pointColor=this.getHexColorStylingValue(this.styles.pointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.pointOutlineColor,i.pointOutlineColor,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.pointOutlineWidth,2,e),i.zIndex=30),i}validateFeature(t){return !!super.validateFeature(t)&&t.properties.mode===this.mode&&be(t,this.coordinatePrecision)}}class Ie extends de{constructor(t,e){super(t),this.config=undefined,this.pixelDistance=undefined,this._startEndPoints=[],this.config=t,this.pixelDistance=e;}get ids(){return this._startEndPoints.concat()}set ids(t){}create(t,e){if(this.ids.length)throw new Error("Opening and closing points already created");if(t.length<=3)throw new Error("Requires at least 4 coordinates");this._startEndPoints=this.store.create([{geometry:{type:"Point",coordinates:t[0]},properties:{mode:e,[At]:true}},{geometry:{type:"Point",coordinates:t[t.length-2]},properties:{mode:e,[At]:true}}]);}delete(){this.ids.length&&(this.store.delete(this.ids),this._startEndPoints=[]);}update(t){if(2!==this.ids.length)throw new Error("No closing points to update");this.store.updateGeometry([{id:this.ids[0],geometry:{type:"Point",coordinates:t[0]}},{id:this.ids[1],geometry:{type:"Point",coordinates:t[t.length-3]}}]);}isClosingPoint(t){const e=this.store.getGeometryCopy(this.ids[0]),i=this.store.getGeometryCopy(this.ids[1]),o=this.pixelDistance.measure(t,e.coordinates),s=this.pixelDistance.measure(t,i.coordinates);return {isClosing:o0&&!this.mouseMove&&this.onMouseMove(t),this.mouseMove=false,0===this.currentCoordinate){const e=this.snappingEnabled?this.snapping.getSnappableCoordinateFirstClick(t):undefined;e&&(t.lng=e[0],t.lat=e[1]);const[i]=this.store.create([{geometry:{type:"Polygon",coordinates:[[[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat]]]},properties:{mode:this.mode}}]);this.currentId=i,this.currentCoordinate++,this.setDrawing();}else if(1===this.currentCoordinate&&this.currentId){const e=this.snappingEnabled?this.snapping.getSnappableCoordinate(t,this.currentId):undefined;e&&(t.lng=e[0],t.lat=e[1]);const i=this.store.getGeometryCopy(this.currentId);if(we([t.lng,t.lat],i.coordinates[0][0]))return;if(!this.updatePolygonGeometry([i.coordinates[0][0],[t.lng,t.lat],[t.lng,t.lat],i.coordinates[0][0]],Wt.Commit))return;this.currentCoordinate++;}else if(2===this.currentCoordinate&&this.currentId){const e=this.snappingEnabled?this.snapping.getSnappableCoordinate(t,this.currentId):undefined;e&&(t.lng=e[0],t.lat=e[1]);const i=this.store.getGeometryCopy(this.currentId).coordinates[0];if(we([t.lng,t.lat],i[1]))return;if(!this.updatePolygonGeometry([i[0],i[1],[t.lng,t.lat],[t.lng,t.lat],i[0]],Wt.Commit))return;2===this.currentCoordinate&&this.closingPoints.create(i,"polygon"),this.currentCoordinate++;}else if(this.currentId){const e=this.snappingEnabled?this.snapping.getSnappableCoordinate(t,this.currentId):undefined,i=this.store.getGeometryCopy(this.currentId).coordinates[0],{isClosing:o,isPreviousClosing:s}=this.closingPoints.isClosingPoint(t);if(s||o)this.close();else {if(e&&(t.lng=e[0],t.lat=e[1]),we([t.lng,t.lat],i[this.currentCoordinate-1]))return;const o=function(t=[[[0,0],[0,1],[1,1],[1,0],[0,0]]]){return {type:"Feature",geometry:{type:"Polygon",coordinates:t},properties:{}}}([[...i.slice(0,-1),[t.lng,t.lat],i[0]]]);if(!this.updatePolygonGeometry(o.geometry.coordinates[0],Wt.Commit))return;this.currentCoordinate++,this.closingPoints.ids.length&&this.closingPoints.update(o.geometry.coordinates[0]);}}}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close();}onKeyDown(){}onDragStart(){this.setCursor("unset");}onDrag(){}onDragEnd(){this.setCursor(this.cursors.start);}cleanUp(){const t=this.currentId;this.currentId=undefined,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted();try{void 0!==t&&this.store.delete([t]),this.closingPoints.ids.length&&this.closingPoints.delete();}catch(t){}}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});if(e.properties.mode===this.mode){if("Polygon"===e.geometry.type)return i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=10,i;if("Point"===e.geometry.type)return i.pointWidth=this.getNumericStylingValue(this.styles.closingPointWidth,i.pointWidth,e),i.pointColor=this.getHexColorStylingValue(this.styles.closingPointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.closingPointOutlineColor,i.pointOutlineColor,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.closingPointOutlineWidth,2,e),i.zIndex=30,i}return i}validateFeature(t){return !!super.validateFeature(t)&&t.properties.mode===this.mode&&ae(t,this.coordinatePrecision)}}class ke extends Tt{constructor(e){super(e),this.mode="rectangle",this.center=undefined,this.clickCount=0,this.currentRectangleId=undefined,this.keyEvents=undefined,this.cursors=undefined;const i={start:"crosshair"};if(this.cursors=e&&e.cursors?t({},i,e.cursors):i,null===(null==e?undefined:e.keyEvents))this.keyEvents={cancel:null,finish:null};else {const i={cancel:"Escape",finish:"Enter"};this.keyEvents=e&&e.keyEvents?t({},i,e.keyEvents):i;}}updateRectangle(t,e){if(1===this.clickCount&&this.center&&this.currentRectangleId){const i=this.store.getGeometryCopy(this.currentRectangleId).coordinates[0][0],o={type:"Polygon",coordinates:[[i,[t.lng,i[1]],[t.lng,t.lat],[i[0],t.lat],i]]};if(this.validate&&!this.validate({id:this.currentRectangleId,geometry:o},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:e}))return;this.store.updateGeometry([{id:this.currentRectangleId,geometry:o}]);}}close(){const t=this.currentRectangleId;this.center=undefined,this.currentRectangleId=undefined,this.clickCount=0,"drawing"===this.state&&this.setStarted(),t&&this.onFinish(t,{mode:this.mode,action:"draw"});}start(){this.setStarted(),this.setCursor(this.cursors.start);}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset");}onClick(t){if(0===this.clickCount){this.center=[t.lng,t.lat];const[e]=this.store.create([{geometry:{type:"Polygon",coordinates:[[[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat],[t.lng,t.lat]]]},properties:{mode:this.mode}}]);this.currentRectangleId=e,this.clickCount++,this.setDrawing();}else this.updateRectangle(t,Wt.Finish),this.close();}onMouseMove(t){this.updateRectangle(t,Wt.Provisional);}onKeyDown(){}onKeyUp(t){t.key===this.keyEvents.cancel?this.cleanUp():t.key===this.keyEvents.finish&&this.close();}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const t=this.currentRectangleId;this.center=undefined,this.currentRectangleId=undefined,this.clickCount=0,"drawing"===this.state&&this.setStarted(),undefined!==t&&this.store.delete([t]);}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});return "Feature"===e.type&&"Polygon"===e.geometry.type&&e.properties.mode===this.mode?(i.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,i.polygonFillColor,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,i.polygonOutlineColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,i.polygonOutlineWidth,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,i.polygonFillOpacity,e),i.zIndex=10,i):i}validateFeature(t){return !!super.validateFeature(t)&&t.properties.mode===this.mode&&le(t,this.coordinatePrecision)}}class Fe extends Tt{constructor(t){super({styles:t.styles}),this.type=zt.Render,this.mode="render",this.mode=t.modeName;}registerBehaviors(t){this.mode=t.mode;}start(){this.setStarted();}stop(){this.setStopped();}onKeyUp(){}onKeyDown(){}onClick(){}onDragStart(){}onDrag(){}onDragEnd(){}onMouseMove(){}cleanUp(){}styleFeature(t){return {pointColor:this.getHexColorStylingValue(this.styles.pointColor,"#3f97e0",t),pointWidth:this.getNumericStylingValue(this.styles.pointWidth,6,t),pointOutlineColor:this.getHexColorStylingValue(this.styles.pointOutlineColor,"#ffffff",t),pointOutlineWidth:this.getNumericStylingValue(this.styles.pointOutlineWidth,0,t),polygonFillColor:this.getHexColorStylingValue(this.styles.polygonFillColor,"#3f97e0",t),polygonFillOpacity:this.getNumericStylingValue(this.styles.polygonFillOpacity,.3,t),polygonOutlineColor:this.getHexColorStylingValue(this.styles.polygonOutlineColor,"#3f97e0",t),polygonOutlineWidth:this.getNumericStylingValue(this.styles.polygonOutlineWidth,4,t),lineStringWidth:this.getNumericStylingValue(this.styles.lineStringWidth,4,t),lineStringColor:this.getHexColorStylingValue(this.styles.lineStringColor,"#3f97e0",t),zIndex:this.getNumericStylingValue(this.styles.zIndex,0,t)}}validateFeature(t){return super.validateFeature(t)&&(be(t,this.coordinatePrecision)||ae(t,this.coordinatePrecision)||function(t,e){return "LineString"===t.geometry.type&&t.geometry.coordinates.length>=2&&t.geometry.coordinates.every(t=>re(t,e))}(t,this.coordinatePrecision))}}function Oe(t,e){const i=t,o=e,s=Ht(i[1]),r=Ht(o[1]);let n=Ht(o[0]-i[0]);n>Math.PI&&(n-=2*Math.PI),n<-Math.PI&&(n+=2*Math.PI);const a=Math.log(Math.tan(r/2+Math.PI/4)/Math.tan(s/2+Math.PI/4)),l=(Jt(Math.atan2(n,a))+360)%360;return l>180?-(360-l):l}function Le(t,e,i){let o=e;e<0&&(o=-Math.abs(o));const s=o/Yt,r=t[0]*Math.PI/180,n=Ht(t[1]),a=Ht(i),l=s*Math.cos(a);let h=n+l;Math.abs(h)>Math.PI/2&&(h=h>0?Math.PI-h:-Math.PI-h);const c=Math.log(Math.tan(h/2+Math.PI/4)/Math.tan(n/2+Math.PI/4)),d=Math.abs(c)>1e-11?l/c:Math.cos(n),u=[(180*(r+s*Math.sin(a)/d)/Math.PI+540)%360-180,180*h/Math.PI];return u[0]+=u[0]-t[0]>180?-360:t[0]-u[0]>180?360:0,u}function We(t,i,o,s,r){const n=s(t[0],t[1]),a=s(i[0],i[1]),{lng:l,lat:h}=r((n.x+a.x)/2,(n.y+a.y)/2);return [e(l,o),e(h,o)]}function je(t,i,o){const s=Le(t,1e3*Ut(t,i)/2,Oe(t,i));return [e(s[0],o),e(s[1],o)]}function Be({featureCoords:t,precision:e,unproject:i,project:o,projection:s}){const r=[];for(let n=0;n({geometry:{type:"Point",coordinates:t},properties:e(i)}))}(t,t=>({mode:this.mode,[Nt]:true,midPointSegment:t,midPointFeatureId:e}),i,this.config.project,this.config.unproject,this.projection));}delete(){this._midPoints.length&&(this.store.delete(this._midPoints),this._midPoints=[]);}getUpdated(t){if(0!==this._midPoints.length)return Be({featureCoords:t,precision:this.coordinatePrecision,project:this.config.project,unproject:this.config.unproject,projection:this.config.projection}).map((t,e)=>({id:this._midPoints[e],geometry:{type:"Point",coordinates:t}}))}}class Ne extends de{constructor(t){super(t),this._selectionPoints=[];}get ids(){return this._selectionPoints.concat()}set ids(t){}create(t,e,i){this._selectionPoints=this.store.create(function(t,e,i){const o=[],s="Polygon"===e?t.length-1:t.length;for(let e=0;e({mode:this.mode,selectionPoint:true,selectionPointFeatureId:i,index:t})));}delete(){this.ids.length&&(this.store.delete(this.ids),this._selectionPoints=[]);}getUpdated(t){if(0!==this._selectionPoints.length)return this._selectionPoints.map((e,i)=>({id:e,geometry:{type:"Point",coordinates:t[i]}}))}getOneUpdated(t,e){if(undefined!==this._selectionPoints[t])return {id:this._selectionPoints[t],geometry:{type:"Point",coordinates:e}}}}function Ae(t,e){let i=false;for(let n=0,a=e.length;n(o=t)[1]!=(r=a[l])[1]>o[1]&&o[0]<(r[0]-s[0])*(o[1]-s[1])/(r[1]-s[1])+s[0]&&(i=!i);}var o,s,r;return i}const Re=(t,e,i)=>{const o=t=>t*t,s=(t,e)=>o(t.x-e.x)+o(t.y-e.y);return Math.sqrt(((t,e,i)=>{const o=s(e,i);if(0===o)return s(t,e);let r=((t.x-e.x)*(i.x-e.x)+(t.y-e.y)*(i.y-e.y))/o;return r=Math.max(0,Math.min(1,r)),s(t,{x:e.x+r*(i.x-e.x),y:e.y+r*(i.y-e.y)})})(t,e,i))};class Ve extends de{constructor(t,e,i){super(t),this.config=undefined,this.createClickBoundingBox=undefined,this.pixelDistance=undefined,this.config=t,this.createClickBoundingBox=e,this.pixelDistance=i;}find(t,e){let i,o,s=Infinity,r=Infinity;const n=this.createClickBoundingBox.create(t),a=this.store.search(n);for(let n=0;n180||n<-180||a>90||a<-90)return false;r[t]=[n,a];}"Polygon"===o.type&&(r[r.length-1]=[r[0][0],r[0][1]]);const a=this.selectionPoints.getUpdated(r)||[],l=this.midPoints.getUpdated(r)||[];if(i&&!i({type:"Feature",id:this.draggedFeatureId,geometry:o,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:Wt.Provisional}))return false;this.store.updateGeometry([{id:this.draggedFeatureId,geometry:o},...a,...l]),this.dragPosition=[t.lng,t.lat];}else "Point"===o.type&&(this.store.updateGeometry([{id:this.draggedFeatureId,geometry:{type:"Point",coordinates:s}}]),this.dragPosition=[t.lng,t.lat]);}}class Te extends de{constructor(t,e,i,o){super(t),this.config=undefined,this.pixelDistance=undefined,this.selectionPoints=undefined,this.midPoints=undefined,this.draggedCoordinate={id:null,index:-1},this.config=t,this.pixelDistance=e,this.selectionPoints=i,this.midPoints=o;}getClosestCoordinate(t,e){const i={dist:Infinity,index:-1,isFirstOrLastPolygonCoord:false};let o;if("LineString"===e.type)o=e.coordinates;else {if("Polygon"!==e.type)return i;o=e.coordinates[0];}for(let s=0;s180||t.lng<-180||t.lat>90||t.lat<-90)return false;if("Polygon"!==s.type||o!==r.length-1&&0!==o)r[o]=n;else {const t=r.length-1;r[0]=n,r[t]=n;}const a=this.selectionPoints.getOneUpdated(o,n),l=a?[a]:[],h=this.midPoints.getUpdated(r)||[];return !("Point"!==s.type&&!e&&oe({type:"Feature",geometry:s,properties:{}})||i&&!i({type:"Feature",id:this.draggedCoordinate.id,geometry:s,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:Wt.Provisional})||(this.store.updateGeometry([{id:this.draggedCoordinate.id,geometry:s},...l,...h]),0))}isDragging(){return null!==this.draggedCoordinate.id}startDragging(t,e){this.draggedCoordinate={id:t,index:e};}stopDragging(){this.draggedCoordinate={id:null,index:-1};}}function Xe(t){let e=0,i=0,o=0;return ("Polygon"===t.geometry.type?t.geometry.coordinates[0].slice(0,-1):t.geometry.coordinates).forEach(t=>{e+=t[0],i+=t[1],o++;},true),[e/o,i/o]}function Ue(t,e){t[0]+=t[0]-e[0]>180?-360:e[0]-t[0]>180?360:0;const i=Yt,o=e[1]*Math.PI/180,s=t[1]*Math.PI/180,r=s-o;let n=Math.abs(t[0]-e[0])*Math.PI/180;n>Math.PI&&(n-=2*Math.PI);const a=Math.log(Math.tan(s/2+Math.PI/4)/Math.tan(o/2+Math.PI/4)),l=Math.abs(a)>1e-11?r/a:Math.cos(o);return Math.sqrt(r*r+l*l*n*n)*i}function Ye(t){const e=("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).map(t=>{const{x:e,y:i}=Qt(t[0],t[1]);return [e,i]});return "Polygon"===t.geometry.type?function(t){let e=0,i=0,o=0;const s=t.length;for(let r=0;r{if(0===e||360===e||-360===e)return t;const i=.017453292519943295*e,o=("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).map(([t,e])=>Qt(t,e)),s=o.reduce((t,e)=>({x:t.x+e.x,y:t.y+e.y}),{x:0,y:0});s.x/=o.length,s.y/=o.length;const r=o.map(t=>({x:s.x+(t.x-s.x)*Math.cos(i)-(t.y-s.y)*Math.sin(i),y:s.y+(t.x-s.x)*Math.sin(i)+(t.y-s.y)*Math.cos(i)})).map(({x:t,y:e})=>[te(t,e).lng,te(t,e).lat]);"Polygon"===t.geometry.type?t.geometry.coordinates[0]=r:(console.log("rotatedCoordinates linestring",r),t.geometry.coordinates=r);})(a,-(this.lastBearing-n));}else {if("globe"!==this.config.projection)throw new Error("Unsupported projection");if(n=Oe(Xe({type:"Feature",geometry:s,properties:{}}),r),!this.lastBearing)return void(this.lastBearing=n+180);!function(t,e){if(0===e||360===e||-360===e)return t;const i=Xe(t);("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).forEach(t=>{const o=Oe(i,t)+e,s=Ue(i,t),r=Le(i,s,o);t[0]=r[0],t[1]=r[1];});}(a,-(this.lastBearing-(n+180)));}const l="Polygon"===s.type?s.coordinates[0]:s.coordinates;l.forEach(t=>{t[0]=e(t[0],this.coordinatePrecision),t[1]=e(t[1],this.coordinatePrecision);});const h=this.midPoints.getUpdated(l)||[],c=this.selectionPoints.getUpdated(l)||[];if(o&&!o({id:i,type:"Feature",geometry:s,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:Wt.Provisional}))return false;this.store.updateGeometry([{id:i,geometry:s},...c,...h]),"web-mercator"===this.projection?this.lastBearing=n:"globe"===this.projection&&(this.lastBearing=n+180);}}class Ke extends de{constructor(t,e,i){super(t),this.config=undefined,this.selectionPoints=undefined,this.midPoints=undefined,this.lastDistance=undefined,this.config=t,this.selectionPoints=e,this.midPoints=i;}reset(){this.lastDistance=undefined;}scale(t,o,s){const r=this.store.getGeometryCopy(o);if("Polygon"!==r.type&&"LineString"!==r.type)return;const n=[t.lng,t.lat],a={type:"Feature",geometry:r,properties:{}};let l;const h=Ye(a);if("web-mercator"===this.config.projection){const e=Qt(t.lng,t.lat);l=i(h,e);}else {if("globe"!==this.config.projection)throw new Error("Invalid projection");l=Ut(Xe({type:"Feature",geometry:r,properties:{}}),n);}if(!this.lastDistance)return void(this.lastDistance=l);const c=1-(this.lastDistance-l)/l;if("web-mercator"===this.config.projection){const{lng:t,lat:e}=te(h.x,h.y);!function(t,e,i){if(1===e)return t;const o=("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).map(([t,e])=>Qt(t,e)),s=Qt(i[0],i[1]),r=o.map(t=>({x:s.x+(t.x-s.x)*e,y:s.y+(t.y-s.y)*e})).map(({x:t,y:e})=>[te(t,e).lng,te(t,e).lat]);"Polygon"===t.geometry.type?t.geometry.coordinates[0]=r:t.geometry.coordinates=r;}(a,c,[t,e]);}else "globe"===this.config.projection&&function(t,e,i,o="xy"){1===e||("Polygon"===t.geometry.type?t.geometry.coordinates[0]:t.geometry.coordinates).forEach(t=>{const s=Ue(i,t),r=Oe(i,t),n=Le(i,s*e,r);"x"!==o&&"xy"!==o||(t[0]=n[0]),"y"!==o&&"xy"!==o||(t[1]=n[1]);});}(a,c,Xe(a));const d="Polygon"===r.type?r.coordinates[0]:r.coordinates;d.forEach(t=>{t[0]=e(t[0],this.coordinatePrecision),t[1]=e(t[1],this.coordinatePrecision);});const u=this.midPoints.getUpdated(d)||[],g=this.selectionPoints.getUpdated(d)||[];if(s&&!s({id:o,type:"Feature",geometry:r,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:Wt.Provisional}))return false;this.store.updateGeometry([{id:o,geometry:r},...g,...u]),this.lastDistance=l;}}class Je extends de{constructor(t,e,i,o){super(t),this.config=undefined,this.pixelDistance=undefined,this.selectionPoints=undefined,this.midPoints=undefined,this.minimumScale=1e-4,this.draggedCoordinate={id:null,index:-1},this.boundingBoxMaps={opposite:{0:4,1:5,2:6,3:7,4:0,5:1,6:2,7:3}},this.config=t,this.pixelDistance=e,this.selectionPoints=i,this.midPoints=o;}getClosestCoordinate(t,e){const i={dist:Infinity,index:-1,isFirstOrLastPolygonCoord:false};let o;if("LineString"===e.type)o=e.coordinates;else {if("Polygon"!==e.type)return i;o=e.coordinates[0];}for(let s=0;s=0)return false;break;case 1:if(i>=0)return false;break;case 2:if(e>=0||i>=0)return false;break;case 3:if(e>=0)return false;break;case 4:if(e>=0||i<=0)return false;break;case 5:if(i<=0)return false;break;case 6:if(e<=0||i<=0)return false;break;case 7:if(e<=0)return false}return true}getSelectedFeatureDataWebMercator(){if(!this.draggedCoordinate.id||-1===this.draggedCoordinate.index)return null;const t=this.getFeature(this.draggedCoordinate.id);if(!t)return null;const e=this.getNormalisedCoordinates(t.geometry);return {boundingBox:this.getBBoxWebMercator(e),feature:t,updatedCoords:e,selectedCoordinate:e[this.draggedCoordinate.index]}}centerWebMercatorDrag(t){const e=this.getSelectedFeatureDataWebMercator();if(!e)return null;const{feature:i,boundingBox:o,updatedCoords:s,selectedCoordinate:r}=e,n=Ye(i);if(!n)return null;const a=Qt(r[0],r[1]),{closestBBoxIndex:l}=this.getIndexesWebMercator(o,a),h=Qt(t.lng,t.lat);return this.scaleWebMercator({closestBBoxIndex:l,updatedCoords:s,webMercatorCursor:h,webMercatorSelected:a,webMercatorOrigin:n}),s}centerFixedWebMercatorDrag(t){const e=this.getSelectedFeatureDataWebMercator();if(!e)return null;const{feature:i,boundingBox:o,updatedCoords:s,selectedCoordinate:r}=e,n=Ye(i);if(!n)return null;const a=Qt(r[0],r[1]),{closestBBoxIndex:l}=this.getIndexesWebMercator(o,a),h=Qt(t.lng,t.lat);return this.scaleFixedWebMercator({closestBBoxIndex:l,updatedCoords:s,webMercatorCursor:h,webMercatorSelected:a,webMercatorOrigin:n}),s}scaleFixedWebMercator({closestBBoxIndex:t,webMercatorOrigin:e,webMercatorSelected:o,webMercatorCursor:s,updatedCoords:r}){if(!this.isValidDragWebMercator(t,e.x-s.x,e.y-s.y))return null;let n=i(e,s)/i(e,o);return n<0&&(n=this.minimumScale),this.performWebMercatorScale(r,e.x,e.y,n,n),r}oppositeFixedWebMercatorDrag(t){const e=this.getSelectedFeatureDataWebMercator();if(!e)return null;const{boundingBox:i,updatedCoords:o,selectedCoordinate:s}=e,r=Qt(s[0],s[1]),{oppositeBboxIndex:n,closestBBoxIndex:a}=this.getIndexesWebMercator(i,r),l={x:i[n][0],y:i[n][1]},h=Qt(t.lng,t.lat);return this.scaleFixedWebMercator({closestBBoxIndex:a,updatedCoords:o,webMercatorCursor:h,webMercatorSelected:r,webMercatorOrigin:l}),o}oppositeWebMercatorDrag(t){const e=this.getSelectedFeatureDataWebMercator();if(!e)return null;const{boundingBox:i,updatedCoords:o,selectedCoordinate:s}=e,r=Qt(s[0],s[1]),{oppositeBboxIndex:n,closestBBoxIndex:a}=this.getIndexesWebMercator(i,r),l={x:i[n][0],y:i[n][1]},h=Qt(t.lng,t.lat);return this.scaleWebMercator({closestBBoxIndex:a,updatedCoords:o,webMercatorCursor:h,webMercatorSelected:r,webMercatorOrigin:l}),o}scaleWebMercator({closestBBoxIndex:t,webMercatorOrigin:e,webMercatorSelected:i,webMercatorCursor:o,updatedCoords:s}){const r=e.x-o.x,n=e.y-o.y;if(!this.isValidDragWebMercator(t,r,n))return null;let a=1;0!==r&&1!==t&&5!==t&&(a=1-(e.x-i.x-r)/r);let l=1;return 0!==n&&3!==t&&7!==t&&(l=1-(e.y-i.y-n)/n),this.validateScale(a,l)?(a<0&&(a=this.minimumScale),l<0&&(l=this.minimumScale),this.performWebMercatorScale(s,e.x,e.y,a,l),s):null}getFeature(t){if(null===this.draggedCoordinate.id)return null;const e=this.store.getGeometryCopy(t);return "Polygon"!==e.type&&"LineString"!==e.type?null:{type:"Feature",geometry:e,properties:{}}}getNormalisedCoordinates(t){return "Polygon"===t.type?t.coordinates[0]:t.coordinates}validateScale(t,e){const i=!isNaN(t)&&e{const{x:r,y:n}=Qt(t[0],t[1]),a=e+(r-e)*o,l=i+(n-i)*s,{lng:h,lat:c}=te(a,l);t[0]=h,t[1]=c;});}getBBoxWebMercator(t){const e=[Infinity,Infinity,-Infinity,-Infinity];(t=t.map(t=>{const{x:e,y:i}=Qt(t[0],t[1]);return [e,i]})).forEach(([t,i])=>{te[2]&&(e[2]=t),i>e[3]&&(e[3]=i);});const[i,o,s,r]=e;return [[i,r],[(i+s)/2,r],[s,r],[s,r+(o-r)/2],[s,o],[(i+s)/2,o],[i,o],[i,r+(o-r)/2]]}getIndexesWebMercator(t,e){let o,s=Infinity;for(let r=0;rthis.store.has(t)).map(t=>({id:t,property:Gt,value:false}));this.store.updateProperty(t),this.onDeselect(this.selected[0]),this.selected=[],this.selectionPoints.delete(),this.midPoints.delete();}deleteSelected(){this.store.delete(this.selected),this.selected=[];}onRightClick(t){if(!this.selectionPoints.ids.length)return;let e,i=Infinity;if(this.selectionPoints.ids.forEach(o=>{const s=this.store.getGeometryCopy(o),r=this.pixelDistance.measure(t,s.coordinates);r0);if(this.selected.length&&i)this.midPoints.insert(i.id,this.coordinatePrecision);else if(e&&e.id)this.select(e.id,true);else if(this.selected.length&&this.allowManualDeselection)return void this.deselect()}start(){this.setStarted(),this.setSelecting();}stop(){this.cleanUp(),this.setStarted(),this.setStopped();}onClick(t){"right"!==t.button?"left"===t.button&&this.onLeftClick(t):this.onRightClick(t);}canScale(t){return this.keyEvents.scale&&this.keyEvents.scale.every(e=>t.heldKeys.includes(e))}canRotate(t){return this.keyEvents.rotate&&this.keyEvents.rotate.every(e=>t.heldKeys.includes(e))}preventDefaultKeyEvent(t){const e=this.canRotate(t),i=this.canScale(t);(e||i)&&t.preventDefault();}onKeyDown(t){this.preventDefaultKeyEvent(t);}onKeyUp(t){if(this.preventDefaultKeyEvent(t),this.keyEvents.delete&&t.key===this.keyEvents.delete){if(!this.selected.length)return;this.onDeselect(this.selected[0]),this.deleteSelected(),this.selectionPoints.delete(),this.midPoints.delete();}else this.keyEvents.deselect&&t.key===this.keyEvents.deselect&&this.cleanUp();}cleanUp(){this.selected.length&&this.deselect();}onDragStart(t,e){if(!this.selected.length)return;const i=this.store.getPropertiesCopy(this.selected[0]),o=this.flags[i.mode];if(!(o&&o.feature&&(o.feature.draggable||o.feature.coordinates&&o.feature.coordinates.draggable||o.feature.coordinates&&o.feature.coordinates.resizable)))return;this.dragEventCount=0;const s=this.selected[0],r=this.dragCoordinate.getDraggableIndex(t,s);return o&&o.feature&&o.feature.coordinates&&(o.feature.coordinates.draggable||o.feature.coordinates.resizable)&&-1!==r?(this.setCursor(this.cursors.dragStart),o.feature.coordinates.resizable?this.dragCoordinateResizeFeature.startDragging(s,r):this.dragCoordinate.startDragging(s,r),void e(false)):o&&o.feature&&o.feature.draggable&&this.dragFeature.canDrag(t,s)?(this.setCursor(this.cursors.dragStart),this.dragFeature.startDragging(t,s),void e(false)):undefined}onDrag(t,e){const i=this.selected[0];if(!i)return;const o=this.store.getPropertiesCopy(i),s=this.flags[o.mode],r=true===(s&&s.feature&&s.feature.selfIntersectable);if(this.dragEventCount++,this.dragEventCount%this.dragEventThrottle==0)return;const n=this.validations[o.mode];if(s&&s.feature&&s.feature.rotateable&&this.canRotate(t))return e(false),void this.rotateFeature.rotate(t,i,n);if(s&&s.feature&&s.feature.scaleable&&this.canScale(t))return e(false),void this.scaleFeature.scale(t,i,n);if(this.dragCoordinateResizeFeature.isDragging()&&s.feature&&s.feature.coordinates&&s.feature.coordinates.resizable){if("globe"===this.projection)throw new Error("Globe is currently unsupported projection for resizable");return e(false),void this.dragCoordinateResizeFeature.drag(t,s.feature.coordinates.resizable,n)}this.dragCoordinate.isDragging()?this.dragCoordinate.drag(t,r,n):this.dragFeature.isDragging()?this.dragFeature.drag(t,n):e(true);}onDragEnd(t,e){this.setCursor(this.cursors.dragEnd),this.dragCoordinate.isDragging()?this.onFinish(this.selected[0],{mode:this.mode,action:"dragCoordinate"}):this.dragFeature.isDragging()?this.onFinish(this.selected[0],{mode:this.mode,action:"dragFeature"}):this.dragCoordinateResizeFeature.isDragging()&&this.onFinish(this.selected[0],{mode:this.mode,action:"dragCoordinateResize"}),this.dragCoordinate.stopDragging(),this.dragFeature.stopDragging(),this.dragCoordinateResizeFeature.stopDragging(),this.rotateFeature.reset(),this.scaleFeature.reset(),e(true);}onMouseMove(t){if(!this.selected.length)return void this.setCursor("unset");if(this.dragFeature.isDragging())return;let e=false;this.midPoints.ids.forEach(i=>{if(e)return;const o=this.store.getGeometryCopy(i);this.pixelDistance.measure(t,o.coordinates){const s=this.store.getGeometryCopy(o);this.pixelDistance.measure(t,s.coordinates)0&&(o&&o.id===this.selected[0]||i)?this.cursors.pointerOver:"unset");}styleFeature(e){const i=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});if(e.properties.mode===this.mode&&"Point"===e.geometry.type){if(e.properties.selectionPoint)return i.pointColor=this.getHexColorStylingValue(this.styles.selectionPointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectionPointOutlineColor,i.pointOutlineColor,e),i.pointWidth=this.getNumericStylingValue(this.styles.selectionPointWidth,i.pointWidth,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectionPointOutlineWidth,2,e),i.zIndex=30,i;if(e.properties.midPoint)return i.pointColor=this.getHexColorStylingValue(this.styles.midPointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.midPointOutlineColor,i.pointOutlineColor,e),i.pointWidth=this.getNumericStylingValue(this.styles.midPointWidth,4,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.midPointOutlineWidth,2,e),i.zIndex=40,i}else if(e.properties[Gt]){if("Polygon"===e.geometry.type)return i.polygonFillColor=this.getHexColorStylingValue(this.styles.selectedPolygonColor,i.polygonFillColor,e),i.polygonOutlineWidth=this.getNumericStylingValue(this.styles.selectedPolygonOutlineWidth,i.polygonOutlineWidth,e),i.polygonOutlineColor=this.getHexColorStylingValue(this.styles.selectedPolygonOutlineColor,i.polygonOutlineColor,e),i.polygonFillOpacity=this.getNumericStylingValue(this.styles.selectedPolygonFillOpacity,i.polygonFillOpacity,e),i.zIndex=10,i;if("LineString"===e.geometry.type)return i.lineStringColor=this.getHexColorStylingValue(this.styles.selectedLineStringColor,i.lineStringColor,e),i.lineStringWidth=this.getNumericStylingValue(this.styles.selectedLineStringWidth,i.lineStringWidth,e),i.zIndex=10,i;if("Point"===e.geometry.type)return i.pointWidth=this.getNumericStylingValue(this.styles.selectedPointWidth,i.pointWidth,e),i.pointColor=this.getHexColorStylingValue(this.styles.selectedPointColor,i.pointColor,e),i.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectedPointOutlineColor,i.pointOutlineColor,e),i.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectedPointOutlineWidth,i.pointOutlineWidth,e),i.zIndex=10,i}return i}}class qe extends Tt{constructor(...t){super(...t),this.type=zt.Static,this.mode="static";}start(){}stop(){}onKeyUp(){}onKeyDown(){}onClick(){}onDragStart(){}onDrag(){}onDragEnd(){}onMouseMove(){}cleanUp(){}styleFeature(){return t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0})}}function Ze(t,e,i,o,s){for(;o>i;){if(o-i>600){const r=o-i+1,n=e-i+1,a=Math.log(r),l=.5*Math.exp(2*a/3),h=.5*Math.sqrt(a*l*(r-l)/r)*(n-r/2<0?-1:1);Ze(t,e,Math.max(i,Math.floor(e-n*l/r+h)),Math.min(o,Math.floor(e+(r-n)*l/r+h)),s);}const r=t[e];let n=i,a=o;for(Qe(t,i,e),s(t[o],r)>0&&Qe(t,i,o);n0;)a--;}0===s(t[i],r)?Qe(t,i,a):(a++,Qe(t,a,o)),a<=e&&(i=a+1),e<=a&&(o=a-1);}}function Qe(t,e,i){const o=t[e];t[e]=t[i],t[i]=o;}function ti(t,e){ei(t,0,t.children.length,e,t);}function ei(t,e,i,o,s){s||(s=ci([])),s.minX=Infinity,s.minY=Infinity,s.maxX=-Infinity,s.maxY=-Infinity;for(let r=e;r=t.minX&&e.maxY>=t.minY}function ci(t){return {children:t,height:1,leaf:true,minX:Infinity,minY:Infinity,maxX:-Infinity,maxY:-Infinity}}function di(t,e,i,o,s){const r=[e,i];for(;r.length;){if((i=r.pop())-(e=r.pop())<=o)continue;const n=e+Math.ceil((i-e)/o/2)*o;Ze(t,n,e,i,s),r.push(e,n,n,i);}}class ui{constructor(t){this._maxEntries=undefined,this._minEntries=undefined,this.data=undefined,this._maxEntries=Math.max(4,t),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear();}search(t){let e=this.data;const i=[];if(!hi(t,e))return i;const o=this.toBBox,s=[];for(;e;){for(let r=0;r=0&&s[e].children.length>this._maxEntries;)this._split(s,e),e--;this._adjustParentBBoxes(o,s,e);}_split(t,e){const i=t[e],o=i.children.length,s=this._minEntries;this._chooseSplitAxis(i,s,o);const r=this._chooseSplitIndex(i,s,o),n=ci(i.children.splice(r,i.children.length-r));n.height=i.height,n.leaf=i.leaf,ti(i,this.toBBox),ti(n,this.toBBox),e?t[e-1].children.push(n):this._splitRoot(i,n);}_splitRoot(t,e){this.data=ci([t,e]),this.data.height=t.height+1,this.data.leaf=false,ti(this.data,this.toBBox);}_chooseSplitIndex(t,e,i){let o,s=Infinity,r=Infinity;for(let n=e;n<=i-e;n++){const e=ei(t,0,n,this.toBBox),a=ei(t,n,i,this.toBBox),l=ai(e,a),h=ri(e)+ri(a);l=e;o--){const e=t.children[o];ii(n,t.leaf?s(e):e),a+=ni(n);}return a}_adjustParentBBoxes(t,e,i){for(let o=i;o>=0;o--)ii(e[o],t);}_condense(t){for(let e,i=t.length-1;i>=0;i--)0===t[i].children.length?i>0?(e=t[i-1].children,e.splice(e.indexOf(t[i]),1)):this.clear():ti(t[i],this.toBBox);}}class gi{constructor(t){this.tree=undefined,this.idToNode=undefined,this.nodeToId=undefined,this.tree=new ui(t&&t.maxEntries?t.maxEntries:9),this.idToNode=new Map,this.nodeToId=new Map;}setMaps(t,e){this.idToNode.set(t.id,e),this.nodeToId.set(e,t.id);}toBBox(t){const e=[],i=[];let o;if("Polygon"===t.geometry.type)o=t.geometry.coordinates[0];else if("LineString"===t.geometry.type)o=t.geometry.coordinates;else {if("Point"!==t.geometry.type)throw new Error("Not a valid feature to turn into a bounding box");o=[t.geometry.coordinates];}for(let t=0;t{const o=this.toBBox(t);if(this.setMaps(t,o),i.has(String(t.id)))throw new Error(`Duplicate feature ID found ${t.id}`);i.add(String(t.id)),e.push(o);}),this.tree.load(e);}update(t){this.remove(t.id);const e=this.toBBox(t);this.setMaps(t,e),this.tree.insert(e);}remove(t){const e=this.idToNode.get(t);if(!e)throw new Error(`${t} not inserted into the spatial index`);this.tree.remove(e);}clear(){this.tree.clear();}search(t){return this.tree.search(this.toBBox(t)).map(t=>this.nodeToId.get(t))}collides(t){return this.tree.collides(this.toBBox(t))}}const pi={getId:()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const e=16*Math.random()|0;return ("x"==t?e:3&e|8).toString(16)}),isValidId:t=>"string"==typeof t&&36===t.length};class yi{constructor(t){this.idStrategy=undefined,this.tracked=undefined,this.spatialIndex=undefined,this.store=undefined,this._onChange=()=>{},this.store={},this.spatialIndex=new gi,this.tracked=!t||false!==t.tracked,this.idStrategy=t&&t.idStrategy?t.idStrategy:pi;}clone(t){return JSON.parse(JSON.stringify(t))}getId(){return this.idStrategy.getId()}has(t){return Boolean(this.store[t])}load(t,e){if(0===t.length)return;const i=this.clone(t);i.forEach(t=>{null==t.id&&(t.id=this.idStrategy.getId()),this.tracked&&(t.properties.createdAt?Vt(t.properties.createdAt):t.properties.createdAt=+new Date,t.properties.updatedAt?Vt(t.properties.updatedAt):t.properties.updatedAt=+new Date);});const o=[];i.forEach(t=>{const i=t.id;if(e&&!e(t))throw new Error(`Feature is not ${i} valid: ${JSON.stringify(t)}`);if(this.has(i))throw new Error(`Feature already exists with this id: ${i}`);this.store[i]=t,o.push(i);}),this.spatialIndex.load(i),this._onChange(o,"create");}search(t,e){const i=this.spatialIndex.search(t).map(t=>this.store[t]);return this.clone(e?i.filter(e):i)}registerOnChange(t){this._onChange=(e,i)=>{t(e,i);};}getGeometryCopy(t){const e=this.store[t];if(!e)throw new Error(`No feature with this id (${t}), can not get geometry copy`);return this.clone(e.geometry)}getPropertiesCopy(t){const e=this.store[t];if(!e)throw new Error(`No feature with this id (${t}), can not get properties copy`);return this.clone(e.properties)}updateProperty(t){const e=[];t.forEach(({id:t,property:i,value:o})=>{const s=this.store[t];if(!s)throw new Error(`No feature with this (${t}), can not update geometry`);e.push(t),s.properties[i]=o,this.tracked&&(s.properties.updatedAt=+new Date);}),this._onChange&&this._onChange(e,"update");}updateGeometry(t){const e=[];t.forEach(({id:t,geometry:i})=>{e.push(t);const o=this.store[t];if(!o)throw new Error(`No feature with this (${t}), can not update geometry`);o.geometry=this.clone(i),this.spatialIndex.update(o),this.tracked&&(o.properties.updatedAt=+new Date);}),this._onChange&&this._onChange(e,"update");}create(e){const i=[];return e.forEach(({geometry:e,properties:o})=>{let s,r=t({},o);this.tracked&&(s=+new Date,o?(r.createdAt="number"==typeof o.createdAt?o.createdAt:s,r.updatedAt="number"==typeof o.updatedAt?o.updatedAt:s):r={createdAt:s,updatedAt:s});const n=this.getId(),a={id:n,type:"Feature",geometry:e,properties:r};this.store[n]=a,this.spatialIndex.insert(a),i.push(n);}),this._onChange&&this._onChange([...i],"create"),i}delete(t){t.forEach(t=>{if(!this.store[t])throw new Error("No feature with this id, can not delete");delete this.store[t],this.spatialIndex.remove(t);}),this._onChange&&this._onChange([...t],"delete");}copyAll(){return this.clone(Object.keys(this.store).map(t=>this.store[t]))}clear(){this.store={},this.spatialIndex.clear();}size(){return Object.keys(this.store).length}}class Si{constructor(e){this._modes=undefined,this._mode=undefined,this._adapter=undefined,this._enabled=false,this._store=undefined,this._eventListeners=undefined,this._instanceSelectMode=undefined,this._adapter=e.adapter,this._mode=new qe;const i=new Set,o=e.modes.reduce((t,e)=>{if(i.has(e.mode))throw new Error(`There is already a ${e.mode} mode provided`);return i.add(e.mode),t[e.mode]=e,t},{}),s=Object.keys(o);if(0===s.length)throw new Error("No modes provided");s.forEach(t=>{if(o[t].type===zt.Select){if(this._instanceSelectMode)throw new Error("only one type of select mode can be provided");this._instanceSelectMode=t;}}),this._modes=t({},o,{static:this._mode}),this._eventListeners={change:[],select:[],deselect:[],finish:[],ready:[]},this._store=new yi({tracked:!!e.tracked,idStrategy:e.idStrategy?e.idStrategy:undefined});const r=t=>{const e=[],i=this._store.copyAll().filter(i=>!t.includes(i.id)||(e.push(i),false));return {changed:e,unchanged:i}},n=(t,e)=>{this._enabled&&this._eventListeners.finish.forEach(i=>{i(t,e);});},a=(t,e)=>{if(!this._enabled)return;this._eventListeners.change.forEach(i=>{i(t,e);});const{changed:i,unchanged:o}=r(t);"create"===e?this._adapter.render({created:i,deletedIds:[],unchanged:o,updated:[]},this.getModeStyles()):"update"===e?this._adapter.render({created:[],deletedIds:[],unchanged:o,updated:i},this.getModeStyles()):"delete"===e?this._adapter.render({created:[],deletedIds:t,unchanged:o,updated:[]},this.getModeStyles()):"styling"===e&&this._adapter.render({created:[],deletedIds:[],unchanged:o,updated:[]},this.getModeStyles());},l=t=>{if(!this._enabled)return;this._eventListeners.select.forEach(e=>{e(t);});const{changed:e,unchanged:i}=r([t]);this._adapter.render({created:[],deletedIds:[],unchanged:i,updated:e},this.getModeStyles());},h=t=>{if(!this._enabled)return;this._eventListeners.deselect.forEach(t=>{t();});const{changed:e,unchanged:i}=r([t]);e&&this._adapter.render({created:[],deletedIds:[],unchanged:i,updated:e},this.getModeStyles());};Object.keys(this._modes).forEach(t=>{this._modes[t].register({mode:t,store:this._store,setCursor:this._adapter.setCursor.bind(this._adapter),project:this._adapter.project.bind(this._adapter),unproject:this._adapter.unproject.bind(this._adapter),setDoubleClickToZoom:this._adapter.setDoubleClickToZoom.bind(this._adapter),onChange:a,onSelect:l,onDeselect:h,onFinish:n,coordinatePrecision:this._adapter.getCoordinatePrecision()});});}checkEnabled(){if(!this._enabled)throw new Error("Terra Draw is not enabled")}getModeStyles(){const t={};return Object.keys(this._modes).forEach(e=>{t[e]=t=>this._instanceSelectMode&&t.properties[Gt]?this._modes[this._instanceSelectMode].styleFeature.bind(this._modes[this._instanceSelectMode])(t):this._modes[e].styleFeature.bind(this._modes[e])(t);}),t}featuresAtLocation({lng:t,lat:e},o){const s=o&&undefined!==o.pointerDistance?o.pointerDistance:30,r=!o||undefined===o.ignoreSelectFeatures||o.ignoreSelectFeatures,n=this._adapter.unproject.bind(this._adapter),a=this._adapter.project.bind(this._adapter),l=a(t,e),h=ue({unproject:n,point:l,pointerDistance:s});return this._store.search(h).filter(o=>{if(r&&(o.properties[Nt]||o.properties.selectionPoint))return false;if("Point"===o.geometry.type){const t=o.geometry.coordinates,e=a(t[0],t[1]);return i(l,e){if(Boolean(t&&"object"==typeof t&&"properties"in t&&"object"==typeof t.properties&&null!==t.properties&&"mode"in t.properties)){const e=this._modes[t.properties.mode];return !!e&&e.validateFeature.bind(e)(t)}return false});}start(){this._enabled=true,this._adapter.register({onReady:()=>{this._eventListeners.ready.forEach(t=>{t();});},getState:()=>this._mode.state,onClick:t=>{this._mode.onClick(t);},onMouseMove:t=>{this._mode.onMouseMove(t);},onKeyDown:t=>{this._mode.onKeyDown(t);},onKeyUp:t=>{this._mode.onKeyUp(t);},onDragStart:(t,e)=>{this._mode.onDragStart(t,e);},onDrag:(t,e)=>{this._mode.onDrag(t,e);},onDragEnd:(t,e)=>{this._mode.onDragEnd(t,e);},onClear:()=>{this._mode.cleanUp(),this._store.clear();}});}getFeaturesAtLngLat(t,e){const{lng:i,lat:o}=t;return this.featuresAtLocation({lng:i,lat:o},e)}getFeaturesAtPointerEvent(t,e){const i=this._adapter.getLngLatFromEvent.bind(this._adapter)(t);return null===i?[]:this.featuresAtLocation(i,e)}stop(){this._enabled=false,this._adapter.unregister();}on(t,e){const i=this._eventListeners[t];i.includes(e)||i.push(e);}off(t,e){const i=this._eventListeners[t];i.includes(e)&&i.splice(i.indexOf(e),1);}} - -/** Import */ - -/** - * BasicDrawComponent. - * ref: https://github.com/JamesLMilner/terra-draw/blob/main/guides/4.MODES.md#selection-mode - * @param {TerraDrawBaseAdapter} adapter - * @param {Object} options - * @return TerraDratxw - */ -const BasicDrawComponent = (adapter, options = {}) => - new Si({ - adapter, - modes: [ - new $e({ - modename: 'modify', - flags: { - render: { - feature: { - // draggable: true, - coordinates: { - midpoints: true, - draggable: true, - deletable: true, - validation: () => true, - }, - }, - }, - }, - }), - new Ee(), - new Se(), - new De(), - new he(), - new ke(), - new Fe({ - modeName: 'render', - // TODO More styles by feature properties - styles: { - pointColor: 'red', - pointOutlineWidth: 2, - lineStringColor: 'red', - lineStringWidth: 2, - polygonFillColor: '#00FFFF', - polygonFillOpacity: 0, - polygonOutlineColor: 'red', - polygonOutlineWidth: 2, - }, - }), - ], - ...options, - }); - -/** - * getUtils. - * - * @param {HTMLElement} target - * @param {TerraDraw} draw - * @param {Object} options - */ -const getUtils = (target, draw, options = {}) => { - draw.start(); - draw.setMode('render'); - - // Resume drawn features - const storageId = target.id - ? `terra-draw-data-${target.id}` - : 'terra-draw-data'; - const featureData = window.localStorage.getItem(storageId); - if (featureData) { - try { - const features = JSON.parse(featureData); - features.forEach(f => (f.properties = { mode: 'render' })); - draw.addFeatures(features); - } catch (err) { - console.warn( - 'Fail to drawn features from Local Storage.', - featureData, - err, - ); - window.localStorage.removeItem(storageId); - } - } - - const cursorHolder = target.querySelector('canvas') ?? target; - cursorHolder.style.removeProperty('cursor'); - const features = draw.getSnapshot(); - - new window.MutationObserver(() => { - switch (target.dataset.draw) { - case '': - case undefined: - draw.setMode('render'); - break - case 'modify': - draw.setMode('select'); - break - case 'delete': - draw.setMode('render'); - cursorHolder.style.cursor = 'not-allowed'; - break - case 'clear': - window.localStorage.removeItem(storageId); - target.dataset.draw = ''; - draw.clear(); - break - case 'features': - window.alert( - `${features.length} features\n\n${JSON.stringify(features, null, 4)}`, - ); - break - default: - draw.setMode(target.dataset.draw); - break - } - }).observe(target, { - attributes: true, - attributeFilter: ['data-draw'], - }); - - draw.on('change', () => { }); - draw.on('finish', (id, context) => { - if (context.action === 'draw') { - const feature = draw.getSnapshot().find(feature => feature.id === id); - if (feature) { - draw.removeFeatures([id]); - feature.properties.mode = 'render'; - draw.addFeatures([feature]); - } - } - - const idFilter = options.idFilter ?? (() => true); - const features = draw.getSnapshot().filter(idFilter); - window.localStorage.setItem(storageId, JSON.stringify(features)); - - if (context.mode !== 'point' && context.action === 'draw') { - target.dataset.draw = ''; - } - }); - document.onclick = event => { - if (target.dataset.draw === 'delete') { - const features = draw.getFeaturesAtPointerEvent(event, { - pointerDistance: 40, - }); - if (features.length > 0) { - draw.removeFeatures([features[0].id]); - if (draw.getSnapshot().length === 0) { - target.dataset.draw = ''; - } - } - } - }; -}; - -/** - * loadCSS. - * @description Dynamically import CSS, simply add stylesheet at - * @param {String} url - */ -const loadCSS = url => { - if (document.head.querySelector(`link[href="${url}"]`)) return - - const link = document.createElement('link'); - Object.assign(link, { - rel: 'stylesheet', - href: url, - onerror: () => console.warn('Fail to load stylesheet:', url), - }); - document.head.appendChild(link); -}; - -/** - * MapOption. - * @description Class for valid options - */ -class MapOption { - constructor ({ name, desc, example, exampleDesc, isValid }) { - this.name = name; - this.desc = desc; - this.example = example; - this.exampleDesc = exampleDesc; - this.isValid = isValid; - } - - valueOf () { - return this.name - } -} - -/** - * Class: base class for Map Renderer - */ -class defaultExport { - /** fields */ - width = '300px' - height = '300px' - center = [121, 24] - zoom = 7 - control = { - scale: false, - fullscreen: false, - } - - layers = [] - data = [] - aliases = [] - svgPin = { - html: '', - size: [27, 41], - anchor: [13.5, 35.25], - } - - get map () { - if (this._map === undefined) { - throw Error('map is not set in current Renderer') - } - return this._map - } - - set map (value) { - if (this._map) throw Error('map cannot be reassigned') - this._map = value; - } - - get steps () { - return [ - this.setOptionAliases, - this.createView, - this.addMap, - this.setControl, - this.addTileData, - this.addGPXFile, - this.getTerraDrawAdapter, - { - valueOf: () => this.setDraw, - depends: this.getTerraDrawAdapter, - }, - this.setExtra, - ] - } - - validateOption (option, value) { - const isValid = this.constructor.validOptions.find( - opt => opt.valueOf() === option, - )?.isValid; - if (!isValid) { throw Error(`Cannot find inValid method for option ${option}`) } - - return isValid(value) - } - - /** options */ - static validOptions = Object.freeze([ - new MapOption({ - name: 'id', - desc: 'id of map HTML element', - isValid: value => (!!value?.match(/\w+/)), - }), - new MapOption({ - name: 'width', - desc: 'CSS width of map HTML element', - example: '200px', - exampleDesc: '', - isValid: value => window.CSS.supports(`width: ${value}`), - }), - new MapOption({ - name: 'height', - desc: 'CSS height of map HTML element', - example: '200px', - exampleDesc: '', - isValid: value => window.CSS.supports(`height: ${value}`), - }), - new MapOption({ - name: 'center', - desc: 'Center of camera map, value: [lon, lat]', - example: '[121, 24]', - exampleDesc: 'Center of Taiwan', - isValid: value => { - // TODO xy value other than WGS84 - try { - const [x, y] = JSON.parse(value); - return !isNaN(x) && !isNaN(y) - } catch { - return false - } - }, - }), - new MapOption({ - name: 'zoom', - desc: 'Zoom level for map camera, number between: 0-22', - example: '7.0', - exampleDesc: 'Small country / US state', - isValid: value => { - const zoom = Number(value); - return !isNaN(zoom) && zoom >= 0 && zoom <= 22 - }, - }), - new MapOption({ - name: 'control', - desc: 'Object of control options, supports: fullscreen, scale', - example: '\n scale: true', - exampleDesc: 'Add Scale bar', - isValid: value => typeof value === 'object', - }), - new MapOption({ - name: 'debug', - desc: 'Set true to show tile boundary', - example: 'true', - exampleDesc: '', - isValid: value => value === 'true', - }), - new MapOption({ - name: 'XYZ', - desc: 'Raster tile format with {x}, {y} and {z}', - example: - 'https://tile.openstreetmap.jp/styles/osm-bright/512/{z}/{x}/{y}.png', - exampleDesc: 'Tile from OSM Japan!', - isValid: value => { - return ( - URL.parse(value) && - value.includes('{x}') && - value.includes('{y}') && - value.includes('z') - ) - }, - }), - new MapOption({ - name: 'GPX', - desc: 'URL of GPX file', - example: - 'https://raw.githubusercontent.com/openlayers/openlayers/main/examples/data/gpx/fells_loop.gpx', - exampleDesc: 'Example from topografix', - isValid: value => URL.parse(value), - }), - new MapOption({ - name: 'WMTS', - desc: 'URL of WMTS document', - example: 'https://gis.sinica.edu.tw/tileserver/wmts', - exampleDesc: 'SINICA Taiwan', - isValid: value => URL.parse(value), - }), - new MapOption({ - name: 'draw', - desc: 'Draw Something on map', - example: 'true', - exampleDesc: 'Enable Draw Tools', - isValid: value => value === 'true', - }), - new MapOption({ - name: 'eval', - desc: 'Custom Script', - example: "console.log('this', this)", - exampleDesc: 'Print Renderer info', - isValid: () => true, - }), - ]) - - /** step: options */ - setOptionAliases (config) { - if (config.XYZ) { - const xyzArray = - typeof config.XYZ === 'string' ? [config.XYZ] : config.XYZ; - xyzArray.forEach(record => { - let obj; - let url; - if (typeof record === 'string') { - url = new URL(record); - obj = { - type: 'tile', - url: record, - title: `${url.host}${url.pathname.split('%7B')[0]}`, - }; - } else if (typeof record === 'object') { - url = new URL(record.url); - obj = { - type: 'tile', - url: record.url, - title: record.title - ? record.title - : `${url.host}${url.pathname.split('%7B')[0]}`, - }; - } else { - return - } - config.data.push(obj); - }); - delete config.XYZ; - } - - if (config.WMTS) { - config.data.push({ - type: 'wmts', - url: config.aliases[config.WMTS] ?? config.WMTS, - }); - delete config.WMTS; - } - - if (config.GPX) { - config.data.push({ - type: 'gpx', - url: config.GPX, - }); - delete config.GPX; - } - - // Replace aliases into real string - if ( - typeof config.center === 'string' && - Object.prototype.hasOwnProperty.call(config.aliases, config.center) - ) { - config.center = config.aliases[config.center]; - } - config.data?.forEach(record => { - if (Object.prototype.hasOwnProperty.call(config.aliases, record.url)) { - record.title = record.url; - record.url = config.aliases[record.url]; - } - }); - } - - /** step: HTMLElement */ - createView ({ target, width, height }) { - target.style.width = width; - target.style.height = height; - if (window.getComputedStyle(target.parentElement).display === 'flex') { - target.style.flexBasis = `calc(${width})`; - } - } - - /** step: draw */ - setDraw = ({ target, terraDrawAdapter }) => { - const idPrefix = target?.id ? target.id + '-' : ''; - const options = { - idStrategy: { - isValidId: _ => true, - getId: (function () { - let id = idPrefix + window.crypto.randomUUID(); - return function () { - id = idPrefix + window.crypto.randomUUID(); - return id - } - })(), - }, - }; - this.terraDraw = BasicDrawComponent(terraDrawAdapter, options); - target.dataset.draw = ''; - getUtils(target, this.terraDraw, { - idFilter: feature => feature.id.startsWith(idPrefix), - }); - - return this.terraDraw - } - - /** options: not-implemented */ - getTerraDrawAdapter () { - return { state: 'skip' } - } - - addTileData () { - return { state: 'skip' } - } - - addGPXFile () { - return { state: 'skip' } - } - - addMarker () { - return { state: 'skip' } - } - - setControl () { - return { state: 'skip' } - } - - setExtra () { - return { state: 'skip' } - } - - updateCamera () { - return { state: 'skip' } - } - - project () { - return { state: 'skip' } - } - - unproject () { - return { state: 'skip' } - } - - restoreCamera () { - this.updateCamera({ center: this.center, zoom: this.zoom }); - } - - /** utils: eval */ - propsForEval () { - let currentPrototype = this; - let props = []; - let entries = []; - while (currentPrototype !== Object.prototype) { - props = props.concat(Object.getOwnPropertyNames(currentPrototype)); - entries = entries.concat(Object.entries(currentPrototype)); - currentPrototype = Object.getPrototypeOf(currentPrototype); - } - return props - } - - evalScript (script, entries = []) { - const props = this.propsForEval(); - const extraArgNames = entries.map(([key, _]) => key); - const args = [ - ...props.map(prop => this[prop]), - ...entries.map(([_, value]) => value), - ]; - /* eslint no-new-func: 0 */ - const func = Function([...props, ...extraArgNames], script).bind( - this, - ...args, - ); - - try { - return func() - } catch (err) { - console.warn('Fail to run custom script:', err); - return null - } - } -} - -function getDefaultExportFromCjs$1 (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; -} - -var maplibreGl$1 = {exports: {}}; - +function t(){return t=Object.assign?Object.assign.bind():function(M){for(var et=1;et{const{x:Bt,y:Wt}=M,{x:Nt,y:$t}=et,Gr=Nt-Bt,mn=$t-Wt;return Math.sqrt(mn*mn+Gr*Gr)};class o{constructor({name:M,callback:et,unregister:Bt,register:Wt}){this.name=void 0,this.callback=void 0,this.registered=!1,this.register=void 0,this.unregister=void 0,this.name=M,this.register=()=>{this.registered||(this.registered=!0,Wt(et))},this.unregister=()=>{this.register&&(this.registered=!1,Bt(et))},this.callback=et}}class s{constructor(M){this._minPixelDragDistance=void 0,this._minPixelDragDistanceDrawing=void 0,this._minPixelDragDistanceSelecting=void 0,this._lastDrawEvent=void 0,this._coordinatePrecision=void 0,this._heldKeys=new Set,this._listeners=[],this._dragState="not-dragging",this._currentModeCallbacks=void 0,this._minPixelDragDistance="number"==typeof M.minPixelDragDistance?M.minPixelDragDistance:1,this._minPixelDragDistanceSelecting="number"==typeof M.minPixelDragDistanceSelecting?M.minPixelDragDistanceSelecting:1,this._minPixelDragDistanceDrawing="number"==typeof M.minPixelDragDistanceDrawing?M.minPixelDragDistanceDrawing:8,this._coordinatePrecision="number"==typeof M.coordinatePrecision?M.coordinatePrecision:9}getButton(M){return-1===M.button?"neither":0===M.button?"left":1===M.button?"middle":2===M.button?"right":"neither"}getMapElementXYPosition(M){const et=this.getMapEventElement(),{left:Bt,top:Wt}=et.getBoundingClientRect();return{containerX:M.clientX-Bt,containerY:M.clientY-Wt}}getDrawEventFromEvent(M){const et=this.getLngLatFromEvent(M);if(!et)return null;const{lng:Bt,lat:Wt}=et,{containerX:Nt,containerY:$t}=this.getMapElementXYPosition(M),Gr=this.getButton(M),mn=Array.from(this._heldKeys);return{lng:e(Bt,this._coordinatePrecision),lat:e(Wt,this._coordinatePrecision),containerX:Nt,containerY:$t,button:Gr,heldKeys:mn}}register(M){this._currentModeCallbacks=M,this._listeners=this.getAdapterListeners(),this._listeners.forEach((M=>{M.register()}))}getCoordinatePrecision(){return this._coordinatePrecision}getAdapterListeners(){return[new o({name:"pointerdown",callback:M=>{if(!this._currentModeCallbacks)return;if(!M.isPrimary)return;const et=this.getDrawEventFromEvent(M);et&&(this._dragState="pre-dragging",this._lastDrawEvent=et)},register:M=>{this.getMapEventElement().addEventListener("pointerdown",M)},unregister:M=>{this.getMapEventElement().removeEventListener("pointerdown",M)}}),new o({name:"pointermove",callback:M=>{if(!this._currentModeCallbacks)return;if(!M.isPrimary)return;M.preventDefault();const et=this.getDrawEventFromEvent(M);if(et)if("not-dragging"===this._dragState)this._currentModeCallbacks.onMouseMove(et),this._lastDrawEvent=et;else if("pre-dragging"===this._dragState){if(!this._lastDrawEvent)return;const M={x:this._lastDrawEvent.containerX,y:this._lastDrawEvent.containerY},Bt={x:et.containerX,y:et.containerY},Wt=this._currentModeCallbacks.getState(),Nt=i(M,Bt);let $t=!1;if($t="drawing"===Wt?Nt{this.setDraggability.bind(this)(M)}))}else"dragging"===this._dragState&&this._currentModeCallbacks.onDrag(et,(M=>{this.setDraggability.bind(this)(M)}))},register:M=>{this.getMapEventElement().addEventListener("pointermove",M)},unregister:M=>{this.getMapEventElement().removeEventListener("pointermove",M)}}),new o({name:"contextmenu",callback:M=>{this._currentModeCallbacks&&M.preventDefault()},register:M=>{this.getMapEventElement().addEventListener("contextmenu",M)},unregister:M=>{this.getMapEventElement().removeEventListener("contextmenu",M)}}),new o({name:"pointerup",callback:M=>{if(!this._currentModeCallbacks)return;if(M.target!==this.getMapEventElement())return;if(!M.isPrimary)return;const et=this.getDrawEventFromEvent(M);et&&("dragging"===this._dragState?this._currentModeCallbacks.onDragEnd(et,(M=>{this.setDraggability.bind(this)(M)})):"not-dragging"!==this._dragState&&"pre-dragging"!==this._dragState||this._currentModeCallbacks.onClick(et),this._dragState="not-dragging",this.setDraggability(!0))},register:M=>{this.getMapEventElement().addEventListener("pointerup",M)},unregister:M=>{this.getMapEventElement().removeEventListener("pointerup",M)}}),new o({name:"keyup",callback:M=>{this._currentModeCallbacks&&(this._heldKeys.delete(M.key),this._currentModeCallbacks.onKeyUp({key:M.key,heldKeys:Array.from(this._heldKeys),preventDefault:()=>M.preventDefault()}))},register:M=>{this.getMapEventElement().addEventListener("keyup",M)},unregister:M=>{this.getMapEventElement().removeEventListener("keyup",M)}}),new o({name:"keydown",callback:M=>{this._currentModeCallbacks&&(this._heldKeys.add(M.key),this._currentModeCallbacks.onKeyDown({key:M.key,heldKeys:Array.from(this._heldKeys),preventDefault:()=>M.preventDefault()}))},register:M=>{this.getMapEventElement().addEventListener("keydown",M)},unregister:M=>{this.getMapEventElement().removeEventListener("keydown",M)}})]}unregister(){this._listeners.forEach((M=>{M.unregister()})),this.clear()}}class a extends s{constructor(M){super(M),this._nextRender=void 0,this._map=void 0,this._container=void 0,this._rendered=!1,this.changedIds={deletion:!1,points:!1,linestrings:!1,polygons:!1,styling:!1},this._map=M.map,this._container=this._map.getContainer()}clearLayers(){this._rendered&&(["point","linestring","polygon"].forEach((M=>{const et=`td-${M.toLowerCase()}`;this._map.removeLayer(et),"polygon"===M&&this._map.removeLayer(et+"-outline"),this._map.removeSource(et)})),this._rendered=!1,this._nextRender&&(cancelAnimationFrame(this._nextRender),this._nextRender=void 0))}_addGeoJSONSource(M,et){this._map.addSource(M,{type:"geojson",data:{type:"FeatureCollection",features:et},tolerance:0})}_addFillLayer(M){return this._map.addLayer({id:M,source:M,type:"fill",paint:{"fill-color":["get","polygonFillColor"],"fill-opacity":["get","polygonFillOpacity"]}})}_addFillOutlineLayer(M,et){const Bt=this._map.addLayer({id:M+"-outline",source:M,type:"line",paint:{"line-width":["get","polygonOutlineWidth"],"line-color":["get","polygonOutlineColor"]}});return et&&this._map.moveLayer(M,et),Bt}_addLineLayer(M,et){const Bt=this._map.addLayer({id:M,source:M,type:"line",paint:{"line-width":["get","lineStringWidth"],"line-color":["get","lineStringColor"]}});return et&&this._map.moveLayer(M,et),Bt}_addPointLayer(M,et){const Bt=this._map.addLayer({id:M,source:M,type:"circle",paint:{"circle-stroke-color":["get","pointOutlineColor"],"circle-stroke-width":["get","pointOutlineWidth"],"circle-radius":["get","pointWidth"],"circle-color":["get","pointColor"]}});return et&&this._map.moveLayer(M,et),Bt}_addLayer(M,et,Bt){"Point"===et&&this._addPointLayer(M,Bt),"LineString"===et&&this._addLineLayer(M,Bt),"Polygon"===et&&(this._addFillLayer(M),this._addFillOutlineLayer(M,Bt))}_addGeoJSONLayer(M,et){const Bt=`td-${M.toLowerCase()}`;return this._addGeoJSONSource(Bt,et),this._addLayer(Bt,M),Bt}_setGeoJSONLayerData(M,et){const Bt=`td-${M.toLowerCase()}`;return this._map.getSource(Bt).setData({type:"FeatureCollection",features:et}),Bt}getEmptyGeometries(){return{points:[],linestrings:[],polygons:[]}}updateChangedIds(M){[...M.updated,...M.created].forEach((M=>{"Point"===M.geometry.type?this.changedIds.points=!0:"LineString"===M.geometry.type?this.changedIds.linestrings=!0:"Polygon"===M.geometry.type&&(this.changedIds.polygons=!0)})),M.deletedIds.length>0&&(this.changedIds.deletion=!0),0===M.created.length&&0===M.updated.length&&0===M.deletedIds.length&&(this.changedIds.styling=!0)}getLngLatFromEvent(M){const{left:et,top:Bt}=this._container.getBoundingClientRect();return this.unproject(M.clientX-et,M.clientY-Bt)}getMapEventElement(){return this._map.getCanvas()}setDraggability(M){M?(this._map.dragRotate.enable(),this._map.dragPan.enable()):(this._map.dragRotate.disable(),this._map.dragPan.disable())}project(M,et){const{x:Bt,y:Wt}=this._map.project({lng:M,lat:et});return{x:Bt,y:Wt}}unproject(M,et){const{lng:Bt,lat:Wt}=this._map.unproject({x:M,y:et});return{lng:Bt,lat:Wt}}setCursor(M){const et=this._map.getCanvas();"unset"===M?et.style.removeProperty("cursor"):et.style.cursor=M}setDoubleClickToZoom(M){M?this._map.doubleClickZoom.enable():this._map.doubleClickZoom.disable()}render(M,et){this.updateChangedIds(M),this._nextRender&&cancelAnimationFrame(this._nextRender),this._nextRender=requestAnimationFrame((()=>{const Bt=[...M.created,...M.updated,...M.unchanged],Wt=this.getEmptyGeometries();for(let M=0;M{const{properties:Bt}=Nt;if(Bt.mode!==M)return;const $t=et[M](Nt);"Point"===Nt.geometry.type?(Bt.pointColor=$t.pointColor,Bt.pointOutlineColor=$t.pointOutlineColor,Bt.pointOutlineWidth=$t.pointOutlineWidth,Bt.pointWidth=$t.pointWidth,Wt.points.push(Nt)):"LineString"===Nt.geometry.type?(Bt.lineStringColor=$t.lineStringColor,Bt.lineStringWidth=$t.lineStringWidth,Wt.linestrings.push(Nt)):"Polygon"===Nt.geometry.type&&(Bt.polygonFillColor=$t.polygonFillColor,Bt.polygonFillOpacity=$t.polygonFillOpacity,Bt.polygonOutlineColor=$t.polygonOutlineColor,Bt.polygonOutlineWidth=$t.polygonOutlineWidth,Wt.polygons.push(Nt))}))}const{points:Nt,linestrings:$t,polygons:Gr}=Wt;if(this._rendered){const M=this.changedIds.deletion||this.changedIds.styling,et=M||this.changedIds.linestrings,Bt=M||this.changedIds.polygons;let Wt;(M||this.changedIds.points)&&(Wt=this._setGeoJSONLayerData("Point",Nt)),et&&this._setGeoJSONLayerData("LineString",$t),Bt&&this._setGeoJSONLayerData("Polygon",Gr),Wt&&this._map.moveLayer(Wt)}else{const M=this._addGeoJSONLayer("Point",Nt);this._addGeoJSONLayer("LineString",$t),this._addGeoJSONLayer("Polygon",Gr),this._rendered=!0,M&&this._map.moveLayer(M)}this.changedIds={points:!1,linestrings:!1,polygons:!1,deletion:!1,styling:!1}}))}clear(){this._currentModeCallbacks&&(this._currentModeCallbacks.onClear(),this.clearLayers())}getCoordinatePrecision(){return super.getCoordinatePrecision()}unregister(){return super.unregister()}register(M){super.register(M),this._currentModeCallbacks&&this._currentModeCallbacks.onReady&&this._currentModeCallbacks.onReady()}}class l extends s{constructor(M){super(M),this.mapboxglAdapter=void 0,this.mapboxglAdapter=new a(M)}register(M){this.mapboxglAdapter.register(M)}unregister(){this.mapboxglAdapter.unregister()}getCoordinatePrecision(){return this.mapboxglAdapter.getCoordinatePrecision()}getLngLatFromEvent(M){return this.mapboxglAdapter.getLngLatFromEvent(M)}getMapEventElement(){return this.mapboxglAdapter.getMapEventElement()}setDraggability(M){this.mapboxglAdapter.setDraggability(M)}project(M,et){return this.mapboxglAdapter.project(M,et)}unproject(M,et){return this.mapboxglAdapter.unproject(M,et)}setCursor(M){this.mapboxglAdapter.setCursor(M)}setDoubleClickToZoom(M){this.mapboxglAdapter.setDoubleClickToZoom(M)}render(M,et){this.mapboxglAdapter.render(M,et)}clear(){this.mapboxglAdapter.clear()}}let M=0;const et="undefined"!=typeof navigator&&void 0!==navigator.userAgent?navigator.userAgent.toLowerCase():"";et.includes("firefox"),et.includes("safari")&&!et.includes("chrom")&&(et.includes("version/15.4")||/cpu (os|iphone os) 15_4 like mac os x/.test(et)),et.includes("webkit")&&et.includes("edge"),et.includes("macintosh"),"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof OffscreenCanvas&&(self,WorkerGlobalScope),function(){let M=!1;try{const et=Object.defineProperty({},"passive",{get:function(){M=!0}});window.addEventListener("_",null,et),window.removeEventListener("_",null,et)}catch(M){}}();var Bt=class{constructor(){this.disposed=!1}dispose(){this.disposed||(this.disposed=!0,this.disposeInternal())}disposeInternal(){}},Wt=class{constructor(M){this.type=M,this.target=null}preventDefault(){this.defaultPrevented=!0}stopPropagation(){this.propagationStopped=!0}};function W(){}function j(M){for(const et in M)delete M[et]}var Nt=class extends Bt{constructor(M){super(),this.eventTarget_=M,this.pendingRemovals_=null,this.dispatching_=null,this.listeners_=null}addEventListener(M,et){if(!M||!et)return;const Bt=this.listeners_||(this.listeners_={}),Wt=Bt[M]||(Bt[M]=[]);Wt.includes(et)||Wt.push(et)}dispatchEvent(M){const et="string"==typeof M,Bt=et?M:M.type,Nt=this.listeners_&&this.listeners_[Bt];if(!Nt)return;const $t=et?new Wt(M):M;$t.target||($t.target=this.eventTarget_||this);const Gr=this.dispatching_||(this.dispatching_={}),mn=this.pendingRemovals_||(this.pendingRemovals_={});let Hn;Bt in Gr||(Gr[Bt]=0,mn[Bt]=0),++Gr[Bt];for(let M=0,et=Nt.length;M0)}removeEventListener(M,et){if(!this.listeners_)return;const Bt=this.listeners_[M];if(!Bt)return;const Wt=Bt.indexOf(et);-1!==Wt&&(this.pendingRemovals_&&M in this.pendingRemovals_?(Bt[Wt]=W,++this.pendingRemovals_[M]):(Bt.splice(Wt,1),0===Bt.length&&delete this.listeners_[M]))}};function N(M,et,Bt,Wt,Nt){if(Nt){const Wt=Bt;Bt=function(){M.removeEventListener(et,Bt),Wt.apply(this,arguments)}}const $t={target:M,type:et,listener:Bt};return M.addEventListener(et,Bt),$t}function A(M,et,Bt,Wt){return N(M,et,Bt,0,!0)}function R(M){M&&M.target&&(M.target.removeEventListener(M.type,M.listener),j(M))}var $t=class extends Nt{constructor(){super(),this.on=this.onInternal,this.once=this.onceInternal,this.un=this.unInternal,this.revision_=0}changed(){++this.revision_,this.dispatchEvent("change")}getRevision(){return this.revision_}onInternal(M,et){if(Array.isArray(M)){const Bt=M.length,Wt=new Array(Bt);for(let Nt=0;Nt1?Bt:2,void 0===et&&(et=Bt>2?M.slice():new Array(Wt));for(let Nt=0;NtPo?Bt=Po:Bt<-Po&&(Bt=-Po),et[Nt+1]=Bt}return et},Fa=function(M,et,Bt){const Wt=M.length;Bt=Bt>1?Bt:2,void 0===et&&(et=Bt>2?M.slice():new Array(Wt));for(let Nt=0;NtM*Math.PI/180,Bt=i(M[1]),Wt=i(M[0]),Nt=i(et[1]),$t=Nt-Bt,Gr=i(et[0])-Wt,mn=Math.sin($t/2)*Math.sin($t/2)+Math.cos(Bt)*Math.cos(Nt)*Math.sin(Gr/2)*Math.sin(Gr/2);return 2*Math.atan2(Math.sqrt(mn),Math.sqrt(1-mn))*6371e3/1e3}const $a=6371008.8;function Ht(M){return M%360*Math.PI/180}function Kt(M){return M/($a/1e3)}function Jt(M){return M%(2*Math.PI)*180/Math.PI}const Al=57.29577951308232,Sl=.017453292519943295,Zl=6378137,Qt=(M,et)=>({x:0===M?0:M*Sl*Zl,y:0===et?0:Math.log(Math.tan(Math.PI/4+et*Sl/2))*Zl}),te=(M,et)=>({lng:0===M?0:Al*(M/Zl),lat:0===et?0:(2*Math.atan(Math.exp(et/Zl))-Math.PI/2)*Al});function ee(M,et,Bt){const Wt=Ht(M[0]),Nt=Ht(M[1]),$t=Ht(Bt),Gr=Kt(et),mn=Math.asin(Math.sin(Nt)*Math.cos(Gr)+Math.cos(Nt)*Math.sin(Gr)*Math.cos($t));return[Jt(Wt+Math.atan2(Math.sin($t)*Math.sin(Gr)*Math.cos(Nt),Math.cos(Gr)-Math.sin(Nt)*Math.sin(mn))),Jt(mn)]}function ie(M){const{center:et,radiusKilometers:Bt,coordinatePrecision:Wt}=M,Nt=M.steps?M.steps:64,$t=[];for(let M=0;M0;function s(M){return M<0-et||M>1+et}function r(M,et,Nt,$t){const Gr=Bt[M][et],mn=Bt[M][et+1],Hn=Bt[Nt][$t],so=Bt[Nt][$t+1],uo=function(M,et,Bt,Wt){if(se(M,Bt)||se(M,Wt)||se(et,Bt)||se(Wt,Bt))return null;const Nt=M[0],$t=M[1],Gr=et[0],mn=et[1],Hn=Bt[0],so=Bt[1],uo=Wt[0],Io=Wt[1],Po=(Nt-Gr)*(so-Io)-($t-mn)*(Hn-uo);return 0===Po?null:[((Nt*mn-$t*Gr)*(Hn-uo)-(Nt-Gr)*(Hn*Io-so*uo))/Po,((Nt*mn-$t*Gr)*(so-Io)-($t-mn)*(Hn*Io-so*uo))/Po]}(Gr,mn,Hn,so);if(null===uo)return;let Io,Po;Io=mn[0]!==Gr[0]?(uo[0]-Gr[0])/(mn[0]-Gr[0]):(uo[1]-Gr[1])/(mn[1]-Gr[1]),Po=so[0]!==Hn[0]?(uo[0]-Hn[0])/(so[0]-Hn[0]):(uo[1]-Hn[1])/(so[1]-Hn[1]),s(Io)||s(Po)||(uo.toString(),Wt.push(uo))}}function se(M,et){return M[0]===et[0]&&M[1]===et[1]}function re(M,et){return 2===M.length&&"number"==typeof M[0]&&"number"==typeof M[1]&&1/0!==M[0]&&1/0!==M[1]&&(Wt=M[0])>=-180&&Wt<=180&&(Bt=M[1])>=-90&&Bt<=90&&ne(M[0])<=et&&ne(M[1])<=et;var Bt,Wt}function ne(M){let et=1,Bt=0;for(;Math.round(M*et)/et!==M;)et*=10,Bt++;return Bt}function ae(M,et){return"Polygon"===M.geometry.type&&1===M.geometry.coordinates.length&&M.geometry.coordinates[0].length>=4&&M.geometry.coordinates[0].every((M=>re(M,et)))&&(Bt=M.geometry.coordinates[0][0])[0]===(Wt=M.geometry.coordinates[0][M.geometry.coordinates[0].length-1])[0]&&Bt[1]===Wt[1];var Bt,Wt}function le(M,et){return ae(M,et)&&!oe(M)}class he extends Tt{constructor(M){var et;super(M),this.mode="circle",this.center=void 0,this.clickCount=0,this.currentCircleId=void 0,this.keyEvents=void 0,this.cursors=void 0,this.startingRadiusKilometers=1e-5;const Bt={start:"crosshair"};if(this.cursors=M&&M.cursors?t({},Bt,M.cursors):Bt,null===(null==M?void 0:M.keyEvents))this.keyEvents={cancel:null,finish:null};else{const et={cancel:"Escape",finish:"Enter"};this.keyEvents=M&&M.keyEvents?t({},et,M.keyEvents):et}this.startingRadiusKilometers=null!=(et=null==M?void 0:M.startingRadiusKilometers)?et:1e-5,this.validate=null==M?void 0:M.validation}close(){if(void 0===this.currentCircleId)return;const M=this.currentCircleId;if(this.validate&&M){const et=this.store.getGeometryCopy(M);if(!this.validate({type:"Feature",id:M,geometry:et,properties:{}},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:Ea.Finish}))return}this.center=void 0,this.currentCircleId=void 0,this.clickCount=0,"drawing"===this.state&&this.setStarted(),this.onFinish(M,{mode:this.mode,action:"draw"})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onClick(M){if(0===this.clickCount){this.center=[M.lng,M.lat];const et=ie({center:this.center,radiusKilometers:this.startingRadiusKilometers,coordinatePrecision:this.coordinatePrecision}),[Bt]=this.store.create([{geometry:et.geometry,properties:{mode:this.mode,radiusKilometers:this.startingRadiusKilometers}}]);this.currentCircleId=Bt,this.clickCount++,this.setDrawing()}else 1===this.clickCount&&this.center&&void 0!==this.currentCircleId&&this.updateCircle(M),this.close()}onMouseMove(M){this.updateCircle(M)}onKeyDown(){}onKeyUp(M){M.key===this.keyEvents.cancel?this.cleanUp():M.key===this.keyEvents.finish&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const M=this.currentCircleId;this.center=void 0,this.currentCircleId=void 0,this.clickCount=0,"drawing"===this.state&&this.setStarted();try{void 0!==M&&this.store.delete([M])}catch(M){}}styleFeature(M){const et=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});return"Feature"===M.type&&"Polygon"===M.geometry.type&&M.properties.mode===this.mode?(et.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,et.polygonFillColor,M),et.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,et.polygonOutlineColor,M),et.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,et.polygonOutlineWidth,M),et.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,et.polygonFillOpacity,M),et.zIndex=10,et):et}validateFeature(M){return!!super.validateFeature(M)&&M.properties.mode===this.mode&&le(M,this.coordinatePrecision)}updateCircle(M){if(1===this.clickCount&&this.center&&this.currentCircleId){const et=Ut(this.center,[M.lng,M.lat]);let Bt;if("web-mercator"===this.projection){const Wt=function(M,et){const Bt=1e3*Ut(M,et);if(0===Bt)return 1;const{x:Wt,y:Nt}=Qt(M[0],M[1]),{x:$t,y:Gr}=Qt(et[0],et[1]);return Math.sqrt(Math.pow($t-Wt,2)+Math.pow(Gr-Nt,2))/Bt}(this.center,[M.lng,M.lat]);Bt=function(M){const{center:et,radiusKilometers:Bt,coordinatePrecision:Wt}=M,Nt=M.steps?M.steps:64,$t=1e3*Bt,[Gr,mn]=et,{x:Hn,y:so}=Qt(Gr,mn),uo=[];for(let M=0;M[M.lng,M.lat]))]}}}class ge extends de{constructor(M){super(M)}create(M){const{containerX:et,containerY:Bt}=M;return ue({unproject:this.unproject,point:{x:et,y:Bt},pointerDistance:this.pointerDistance})}}class pe extends de{constructor(M){super(M)}measure(M,et){const{x:Bt,y:Wt}=this.project(et[0],et[1]);return i({x:Bt,y:Wt},{x:M.containerX,y:M.containerY})}}class ye extends de{constructor(M,et,Bt){super(M),this.config=void 0,this.pixelDistance=void 0,this.clickBoundingBox=void 0,this.getSnappableCoordinateFirstClick=M=>this.getSnappable(M,(M=>Boolean(M.properties&&M.properties.mode===this.mode))),this.getSnappableCoordinate=(M,et)=>this.getSnappable(M,(M=>Boolean(M.properties&&M.properties.mode===this.mode&&M.id!==et))),this.config=M,this.pixelDistance=et,this.clickBoundingBox=Bt}getSnappable(M,et){const Bt=this.clickBoundingBox.create(M),Wt=this.store.search(Bt,et),Nt={coord:void 0,minDist:1/0};return Wt.forEach((et=>{let Bt;if("Polygon"===et.geometry.type)Bt=et.geometry.coordinates[0];else{if("LineString"!==et.geometry.type)return;Bt=et.geometry.coordinates}Bt.forEach((et=>{const Bt=this.pixelDistance.measure(M,et);Bt=Hn&&Nt===M.length-1);Nt++){if(Hn>et&&0===Wt.length){if($t=et-Hn,!$t)return Wt.push(M[Nt]),Wt;Gr=ve(M[Nt],M[Nt-1])-180,mn=me(M[Nt],$t,Gr),Wt.push(mn)}if(Hn>=Bt)return $t=Bt-Hn,$t?(Gr=ve(M[Nt],M[Nt-1])-180,mn=me(M[Nt],$t,Gr),Wt.push(mn),Wt):(Wt.push(M[Nt]),Wt);if(Hn>=et&&Wt.push(M[Nt]),Nt===M.length-1)return Wt;Hn+=Ut(M[Nt],M[Nt+1])}if(Hn[e(M[0],this.config.coordinatePrecision),e(M[1],this.config.coordinatePrecision)]))}}function we(M,et){return M[0]===et[0]&&M[1]===et[1]}class Se extends Tt{constructor(M){super(M),this.mode="linestring",this.currentCoordinate=0,this.currentId=void 0,this.closingPointId=void 0,this.keyEvents=void 0,this.snappingEnabled=void 0,this.cursors=void 0,this.mouseMove=!1,this.insertCoordinates=void 0,this.lastCommitedCoordinates=void 0,this.snapping=void 0,this.insertPoint=void 0;const et={start:"crosshair",close:"pointer"};if(this.cursors=M&&M.cursors?t({},et,M.cursors):et,this.snappingEnabled=!(!M||void 0===M.snapping)&&M.snapping,null===(null==M?void 0:M.keyEvents))this.keyEvents={cancel:null,finish:null};else{const et={cancel:"Escape",finish:"Enter"};this.keyEvents=M&&M.keyEvents?t({},et,M.keyEvents):et}this.validate=null==M?void 0:M.validation,this.insertCoordinates=null==M?void 0:M.insertCoordinates}close(){if(void 0===this.currentId)return;const M=this.store.getGeometryCopy(this.currentId);M.coordinates.pop(),this.updateGeometries([...M.coordinates],void 0,Ea.Commit);const et=this.currentId;this.closingPointId&&this.store.delete([this.closingPointId]),this.currentCoordinate=0,this.currentId=void 0,this.closingPointId=void 0,this.lastCommitedCoordinates=void 0,"drawing"===this.state&&this.setStarted(),this.onFinish(et,{mode:this.mode,action:"draw"})}updateGeometries(M,et,Bt){if(!this.currentId)return;const Wt={type:"LineString",coordinates:M};if(this.validate&&!this.validate({type:"Feature",geometry:Wt},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:Bt}))return;const Nt=[{id:this.currentId,geometry:Wt}];this.closingPointId&&et&&Nt.push({id:this.closingPointId,geometry:{type:"Point",coordinates:et}}),"commit"===Bt&&(this.lastCommitedCoordinates=Wt.coordinates),this.store.updateGeometry(Nt)}generateInsertCoordinates(M,et){if(!this.insertCoordinates||!this.lastCommitedCoordinates)throw new Error("Not able to insert coordinates");if("amount"!==this.insertCoordinates.strategy)throw new Error("Strategy does not exist");const Bt=Ut(M,et)/(this.insertCoordinates.value+1);let Wt=[];return"globe"===this.projection?Wt=this.insertPoint.generateInsertionGeodesicCoordinates(M,et,Bt):"web-mercator"===this.projection&&(Wt=this.insertPoint.generateInsertionCoordinates(M,et,Bt)),Wt}createLine(M){const[et]=this.store.create([{geometry:{type:"LineString",coordinates:[M,M]},properties:{mode:this.mode}}]);this.lastCommitedCoordinates=[M,M],this.currentId=et,this.currentCoordinate++,this.setDrawing()}firstUpdateToLine(M){if(!this.currentId)return;const et=this.store.getGeometryCopy(this.currentId).coordinates,[Bt]=this.store.create([{geometry:{type:"Point",coordinates:[...M]},properties:{mode:this.mode}}]);this.closingPointId=Bt,this.setCursor(this.cursors.close);const Wt=[...et,M];this.updateGeometries(Wt,void 0,Ea.Commit),this.currentCoordinate++}updateToLine(M,et){if(!this.currentId)return;const Bt=this.store.getGeometryCopy(this.currentId).coordinates,[Wt,Nt]=this.lastCommitedCoordinates?this.lastCommitedCoordinates[this.lastCommitedCoordinates.length-1]:Bt[Bt.length-2],{x:$t,y:Gr}=this.project(Wt,Nt);if(i({x:$t,y:Gr},{x:et.x,y:et.y})0&&!this.mouseMove&&this.onMouseMove(M),this.mouseMove=!1;const et=this.currentId&&this.snappingEnabled&&this.snapping.getSnappableCoordinate(M,this.currentId)||[M.lng,M.lat];0===this.currentCoordinate?this.createLine(et):1===this.currentCoordinate&&this.currentId?this.firstUpdateToLine(et):this.currentId&&this.updateToLine(et,{x:M.containerX,y:M.containerY})}onKeyDown(){}onKeyUp(M){M.key===this.keyEvents.cancel&&this.cleanUp(),M.key===this.keyEvents.finish&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const M=this.currentId;this.closingPointId=void 0,this.currentId=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted();try{void 0!==M&&this.store.delete([M]),void 0!==this.closingPointId&&this.store.delete([this.closingPointId])}catch(M){}}styleFeature(M){const et=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});return"Feature"===M.type&&"LineString"===M.geometry.type&&M.properties.mode===this.mode?(et.lineStringColor=this.getHexColorStylingValue(this.styles.lineStringColor,et.lineStringColor,M),et.lineStringWidth=this.getNumericStylingValue(this.styles.lineStringWidth,et.lineStringWidth,M),et.zIndex=10,et):"Feature"===M.type&&"Point"===M.geometry.type&&M.properties.mode===this.mode?(et.pointColor=this.getHexColorStylingValue(this.styles.closingPointColor,et.pointColor,M),et.pointWidth=this.getNumericStylingValue(this.styles.closingPointWidth,et.pointWidth,M),et.pointOutlineColor=this.getHexColorStylingValue(this.styles.closingPointOutlineColor,"#ffffff",M),et.pointOutlineWidth=this.getNumericStylingValue(this.styles.closingPointOutlineWidth,2,M),et.zIndex=40,et):et}validateFeature(M){return!!super.validateFeature(M)&&"LineString"===M.geometry.type&&M.properties.mode===this.mode&&M.geometry.coordinates.length>=2}}function be(M,et){return"Point"===M.geometry.type&&re(M.geometry.coordinates,et)}class Ee extends Tt{constructor(M){super(M),this.mode="point",this.cursors=void 0;const et={create:"crosshair"};this.cursors=M&&M.cursors?t({},et,M.cursors):et}start(){this.setStarted(),this.setCursor(this.cursors.create)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onClick(M){if(!this.store)throw new Error("Mode must be registered first");const et={type:"Point",coordinates:[M.lng,M.lat]},Bt={mode:this.mode};if(this.validate&&!this.validate({type:"Feature",geometry:et,properties:Bt},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:Ea.Finish}))return;const[Wt]=this.store.create([{geometry:et,properties:Bt}]);this.onFinish(Wt,{mode:this.mode,action:"draw"})}onMouseMove(){}onKeyDown(){}onKeyUp(){}cleanUp(){}onDragStart(){}onDrag(){}onDragEnd(){}styleFeature(M){const et=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});return"Feature"===M.type&&"Point"===M.geometry.type&&M.properties.mode===this.mode&&(et.pointWidth=this.getNumericStylingValue(this.styles.pointWidth,et.pointWidth,M),et.pointColor=this.getHexColorStylingValue(this.styles.pointColor,et.pointColor,M),et.pointOutlineColor=this.getHexColorStylingValue(this.styles.pointOutlineColor,et.pointOutlineColor,M),et.pointOutlineWidth=this.getNumericStylingValue(this.styles.pointOutlineWidth,2,M),et.zIndex=30),et}validateFeature(M){return!!super.validateFeature(M)&&M.properties.mode===this.mode&&be(M,this.coordinatePrecision)}}class Ie extends de{constructor(M,et){super(M),this.config=void 0,this.pixelDistance=void 0,this._startEndPoints=[],this.config=M,this.pixelDistance=et}get ids(){return this._startEndPoints.concat()}set ids(M){}create(M,et){if(this.ids.length)throw new Error("Opening and closing points already created");if(M.length<=3)throw new Error("Requires at least 4 coordinates");this._startEndPoints=this.store.create([{geometry:{type:"Point",coordinates:M[0]},properties:{mode:et,[Ka]:!0}},{geometry:{type:"Point",coordinates:M[M.length-2]},properties:{mode:et,[Ka]:!0}}])}delete(){this.ids.length&&(this.store.delete(this.ids),this._startEndPoints=[])}update(M){if(2!==this.ids.length)throw new Error("No closing points to update");this.store.updateGeometry([{id:this.ids[0],geometry:{type:"Point",coordinates:M[0]}},{id:this.ids[1],geometry:{type:"Point",coordinates:M[M.length-3]}}])}isClosingPoint(M){const et=this.store.getGeometryCopy(this.ids[0]),Bt=this.store.getGeometryCopy(this.ids[1]),Wt=this.pixelDistance.measure(M,et.coordinates),Nt=this.pixelDistance.measure(M,Bt.coordinates);return{isClosing:Wt0&&!this.mouseMove&&this.onMouseMove(M),this.mouseMove=!1,0===this.currentCoordinate){const et=this.snappingEnabled?this.snapping.getSnappableCoordinateFirstClick(M):void 0;et&&(M.lng=et[0],M.lat=et[1]);const[Bt]=this.store.create([{geometry:{type:"Polygon",coordinates:[[[M.lng,M.lat],[M.lng,M.lat],[M.lng,M.lat],[M.lng,M.lat]]]},properties:{mode:this.mode}}]);this.currentId=Bt,this.currentCoordinate++,this.setDrawing()}else if(1===this.currentCoordinate&&this.currentId){const et=this.snappingEnabled?this.snapping.getSnappableCoordinate(M,this.currentId):void 0;et&&(M.lng=et[0],M.lat=et[1]);const Bt=this.store.getGeometryCopy(this.currentId);if(we([M.lng,M.lat],Bt.coordinates[0][0]))return;if(!this.updatePolygonGeometry([Bt.coordinates[0][0],[M.lng,M.lat],[M.lng,M.lat],Bt.coordinates[0][0]],Ea.Commit))return;this.currentCoordinate++}else if(2===this.currentCoordinate&&this.currentId){const et=this.snappingEnabled?this.snapping.getSnappableCoordinate(M,this.currentId):void 0;et&&(M.lng=et[0],M.lat=et[1]);const Bt=this.store.getGeometryCopy(this.currentId).coordinates[0];if(we([M.lng,M.lat],Bt[1]))return;if(!this.updatePolygonGeometry([Bt[0],Bt[1],[M.lng,M.lat],[M.lng,M.lat],Bt[0]],Ea.Commit))return;2===this.currentCoordinate&&this.closingPoints.create(Bt,"polygon"),this.currentCoordinate++}else if(this.currentId){const et=this.snappingEnabled?this.snapping.getSnappableCoordinate(M,this.currentId):void 0,Bt=this.store.getGeometryCopy(this.currentId).coordinates[0],{isClosing:Wt,isPreviousClosing:Nt}=this.closingPoints.isClosingPoint(M);if(Nt||Wt)this.close();else{if(et&&(M.lng=et[0],M.lat=et[1]),we([M.lng,M.lat],Bt[this.currentCoordinate-1]))return;const Wt=function(M=[[[0,0],[0,1],[1,1],[1,0],[0,0]]]){return{type:"Feature",geometry:{type:"Polygon",coordinates:M},properties:{}}}([[...Bt.slice(0,-1),[M.lng,M.lat],Bt[0]]]);if(!this.updatePolygonGeometry(Wt.geometry.coordinates[0],Ea.Commit))return;this.currentCoordinate++,this.closingPoints.ids.length&&this.closingPoints.update(Wt.geometry.coordinates[0])}}}onKeyUp(M){M.key===this.keyEvents.cancel?this.cleanUp():M.key===this.keyEvents.finish&&this.close()}onKeyDown(){}onDragStart(){this.setCursor("unset")}onDrag(){}onDragEnd(){this.setCursor(this.cursors.start)}cleanUp(){const M=this.currentId;this.currentId=void 0,this.currentCoordinate=0,"drawing"===this.state&&this.setStarted();try{void 0!==M&&this.store.delete([M]),this.closingPoints.ids.length&&this.closingPoints.delete()}catch(M){}}styleFeature(M){const et=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});if(M.properties.mode===this.mode){if("Polygon"===M.geometry.type)return et.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,et.polygonFillColor,M),et.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,et.polygonOutlineColor,M),et.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,et.polygonOutlineWidth,M),et.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,et.polygonFillOpacity,M),et.zIndex=10,et;if("Point"===M.geometry.type)return et.pointWidth=this.getNumericStylingValue(this.styles.closingPointWidth,et.pointWidth,M),et.pointColor=this.getHexColorStylingValue(this.styles.closingPointColor,et.pointColor,M),et.pointOutlineColor=this.getHexColorStylingValue(this.styles.closingPointOutlineColor,et.pointOutlineColor,M),et.pointOutlineWidth=this.getNumericStylingValue(this.styles.closingPointOutlineWidth,2,M),et.zIndex=30,et}return et}validateFeature(M){return!!super.validateFeature(M)&&M.properties.mode===this.mode&&ae(M,this.coordinatePrecision)}}class ke extends Tt{constructor(M){super(M),this.mode="rectangle",this.center=void 0,this.clickCount=0,this.currentRectangleId=void 0,this.keyEvents=void 0,this.cursors=void 0;const et={start:"crosshair"};if(this.cursors=M&&M.cursors?t({},et,M.cursors):et,null===(null==M?void 0:M.keyEvents))this.keyEvents={cancel:null,finish:null};else{const et={cancel:"Escape",finish:"Enter"};this.keyEvents=M&&M.keyEvents?t({},et,M.keyEvents):et}}updateRectangle(M,et){if(1===this.clickCount&&this.center&&this.currentRectangleId){const Bt=this.store.getGeometryCopy(this.currentRectangleId).coordinates[0][0],Wt={type:"Polygon",coordinates:[[Bt,[M.lng,Bt[1]],[M.lng,M.lat],[Bt[0],M.lat],Bt]]};if(this.validate&&!this.validate({id:this.currentRectangleId,geometry:Wt},{project:this.project,unproject:this.unproject,coordinatePrecision:this.coordinatePrecision,updateType:et}))return;this.store.updateGeometry([{id:this.currentRectangleId,geometry:Wt}])}}close(){const M=this.currentRectangleId;this.center=void 0,this.currentRectangleId=void 0,this.clickCount=0,"drawing"===this.state&&this.setStarted(),M&&this.onFinish(M,{mode:this.mode,action:"draw"})}start(){this.setStarted(),this.setCursor(this.cursors.start)}stop(){this.cleanUp(),this.setStopped(),this.setCursor("unset")}onClick(M){if(0===this.clickCount){this.center=[M.lng,M.lat];const[et]=this.store.create([{geometry:{type:"Polygon",coordinates:[[[M.lng,M.lat],[M.lng,M.lat],[M.lng,M.lat],[M.lng,M.lat]]]},properties:{mode:this.mode}}]);this.currentRectangleId=et,this.clickCount++,this.setDrawing()}else this.updateRectangle(M,Ea.Finish),this.close()}onMouseMove(M){this.updateRectangle(M,Ea.Provisional)}onKeyDown(){}onKeyUp(M){M.key===this.keyEvents.cancel?this.cleanUp():M.key===this.keyEvents.finish&&this.close()}onDragStart(){}onDrag(){}onDragEnd(){}cleanUp(){const M=this.currentRectangleId;this.center=void 0,this.currentRectangleId=void 0,this.clickCount=0,"drawing"===this.state&&this.setStarted(),void 0!==M&&this.store.delete([M])}styleFeature(M){const et=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});return"Feature"===M.type&&"Polygon"===M.geometry.type&&M.properties.mode===this.mode?(et.polygonFillColor=this.getHexColorStylingValue(this.styles.fillColor,et.polygonFillColor,M),et.polygonOutlineColor=this.getHexColorStylingValue(this.styles.outlineColor,et.polygonOutlineColor,M),et.polygonOutlineWidth=this.getNumericStylingValue(this.styles.outlineWidth,et.polygonOutlineWidth,M),et.polygonFillOpacity=this.getNumericStylingValue(this.styles.fillOpacity,et.polygonFillOpacity,M),et.zIndex=10,et):et}validateFeature(M){return!!super.validateFeature(M)&&M.properties.mode===this.mode&&le(M,this.coordinatePrecision)}}class Fe extends Tt{constructor(M){super({styles:M.styles}),this.type=Oa.Render,this.mode="render",this.mode=M.modeName}registerBehaviors(M){this.mode=M.mode}start(){this.setStarted()}stop(){this.setStopped()}onKeyUp(){}onKeyDown(){}onClick(){}onDragStart(){}onDrag(){}onDragEnd(){}onMouseMove(){}cleanUp(){}styleFeature(M){return{pointColor:this.getHexColorStylingValue(this.styles.pointColor,"#3f97e0",M),pointWidth:this.getNumericStylingValue(this.styles.pointWidth,6,M),pointOutlineColor:this.getHexColorStylingValue(this.styles.pointOutlineColor,"#ffffff",M),pointOutlineWidth:this.getNumericStylingValue(this.styles.pointOutlineWidth,0,M),polygonFillColor:this.getHexColorStylingValue(this.styles.polygonFillColor,"#3f97e0",M),polygonFillOpacity:this.getNumericStylingValue(this.styles.polygonFillOpacity,.3,M),polygonOutlineColor:this.getHexColorStylingValue(this.styles.polygonOutlineColor,"#3f97e0",M),polygonOutlineWidth:this.getNumericStylingValue(this.styles.polygonOutlineWidth,4,M),lineStringWidth:this.getNumericStylingValue(this.styles.lineStringWidth,4,M),lineStringColor:this.getHexColorStylingValue(this.styles.lineStringColor,"#3f97e0",M),zIndex:this.getNumericStylingValue(this.styles.zIndex,0,M)}}validateFeature(M){return super.validateFeature(M)&&(be(M,this.coordinatePrecision)||ae(M,this.coordinatePrecision)||function(M,et){return"LineString"===M.geometry.type&&M.geometry.coordinates.length>=2&&M.geometry.coordinates.every((M=>re(M,et)))}(M,this.coordinatePrecision))}}function Oe(M,et){const Bt=M,Wt=et,Nt=Ht(Bt[1]),$t=Ht(Wt[1]);let Gr=Ht(Wt[0]-Bt[0]);Gr>Math.PI&&(Gr-=2*Math.PI),Gr<-Math.PI&&(Gr+=2*Math.PI);const mn=Math.log(Math.tan($t/2+Math.PI/4)/Math.tan(Nt/2+Math.PI/4)),Hn=(Jt(Math.atan2(Gr,mn))+360)%360;return Hn>180?-(360-Hn):Hn}function Le(M,et,Bt){let Wt=et;et<0&&(Wt=-Math.abs(Wt));const Nt=Wt/$a,$t=M[0]*Math.PI/180,Gr=Ht(M[1]),mn=Ht(Bt),Hn=Nt*Math.cos(mn);let so=Gr+Hn;Math.abs(so)>Math.PI/2&&(so=so>0?Math.PI-so:-Math.PI-so);const uo=Math.log(Math.tan(so/2+Math.PI/4)/Math.tan(Gr/2+Math.PI/4)),Io=Math.abs(uo)>1e-11?Hn/uo:Math.cos(Gr),Po=[(180*($t+Nt*Math.sin(mn)/Io)/Math.PI+540)%360-180,180*so/Math.PI];return Po[0]+=Po[0]-M[0]>180?-360:M[0]-Po[0]>180?360:0,Po}function We(M,et,Bt,Wt,Nt){const $t=Wt(M[0],M[1]),Gr=Wt(et[0],et[1]),{lng:mn,lat:Hn}=Nt(($t.x+Gr.x)/2,($t.y+Gr.y)/2);return[e(mn,Bt),e(Hn,Bt)]}function je(M,et,Bt){const Wt=Le(M,1e3*Ut(M,et)/2,Oe(M,et));return[e(Wt[0],Bt),e(Wt[1],Bt)]}function Be({featureCoords:M,precision:et,unproject:Bt,project:Wt,projection:Nt}){const $t=[];for(let Gr=0;Gr({geometry:{type:"Point",coordinates:M},properties:et(Bt)})))}(M,(M=>({mode:this.mode,[Da]:!0,midPointSegment:M,midPointFeatureId:et})),Bt,this.config.project,this.config.unproject,this.projection))}delete(){this._midPoints.length&&(this.store.delete(this._midPoints),this._midPoints=[])}getUpdated(M){if(0!==this._midPoints.length)return Be({featureCoords:M,precision:this.coordinatePrecision,project:this.config.project,unproject:this.config.unproject,projection:this.config.projection}).map(((M,et)=>({id:this._midPoints[et],geometry:{type:"Point",coordinates:M}})))}}class Ne extends de{constructor(M){super(M),this._selectionPoints=[]}get ids(){return this._selectionPoints.concat()}set ids(M){}create(M,et,Bt){this._selectionPoints=this.store.create(function(M,et,Bt){const Wt=[],Nt="Polygon"===et?M.length-1:M.length;for(let et=0;et({mode:this.mode,selectionPoint:!0,selectionPointFeatureId:Bt,index:M}))))}delete(){this.ids.length&&(this.store.delete(this.ids),this._selectionPoints=[])}getUpdated(M){if(0!==this._selectionPoints.length)return this._selectionPoints.map(((et,Bt)=>({id:et,geometry:{type:"Point",coordinates:M[Bt]}})))}getOneUpdated(M,et){if(void 0!==this._selectionPoints[M])return{id:this._selectionPoints[M],geometry:{type:"Point",coordinates:et}}}}function Ae(M,et){let Bt=!1;for(let Gr=0,mn=et.length;Gr(Wt=M)[1]!=($t=mn[Hn])[1]>Wt[1]&&Wt[0]<($t[0]-Nt[0])*(Wt[1]-Nt[1])/($t[1]-Nt[1])+Nt[0]&&(Bt=!Bt)}var Wt,Nt,$t;return Bt}const Re=(M,et,Bt)=>{const o=M=>M*M,s=(M,et)=>o(M.x-et.x)+o(M.y-et.y);return Math.sqrt(((M,et,Bt)=>{const Wt=s(et,Bt);if(0===Wt)return s(M,et);let Nt=((M.x-et.x)*(Bt.x-et.x)+(M.y-et.y)*(Bt.y-et.y))/Wt;return Nt=Math.max(0,Math.min(1,Nt)),s(M,{x:et.x+Nt*(Bt.x-et.x),y:et.y+Nt*(Bt.y-et.y)})})(M,et,Bt))};class Ve extends de{constructor(M,et,Bt){super(M),this.config=void 0,this.createClickBoundingBox=void 0,this.pixelDistance=void 0,this.config=M,this.createClickBoundingBox=et,this.pixelDistance=Bt}find(M,et){let Bt,Wt,Nt=1/0,$t=1/0;const Gr=this.createClickBoundingBox.create(M),mn=this.store.search(Gr);for(let Gr=0;Gr180||$t<-180||Gr>90||Gr<-90)return!1;Nt[M]=[$t,Gr]}"Polygon"===Bt.type&&(Nt[Nt.length-1]=[Nt[0][0],Nt[0][1]]);const Gr=this.selectionPoints.getUpdated(Nt)||[],mn=this.midPoints.getUpdated(Nt)||[];if(et&&!et({type:"Feature",id:this.draggedFeatureId,geometry:Bt,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:Ea.Provisional}))return!1;this.store.updateGeometry([{id:this.draggedFeatureId,geometry:Bt},...Gr,...mn]),this.dragPosition=[M.lng,M.lat]}else"Point"===Bt.type&&(this.store.updateGeometry([{id:this.draggedFeatureId,geometry:{type:"Point",coordinates:Wt}}]),this.dragPosition=[M.lng,M.lat])}}class Te extends de{constructor(M,et,Bt,Wt){super(M),this.config=void 0,this.pixelDistance=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.draggedCoordinate={id:null,index:-1},this.config=M,this.pixelDistance=et,this.selectionPoints=Bt,this.midPoints=Wt}getClosestCoordinate(M,et){const Bt={dist:1/0,index:-1,isFirstOrLastPolygonCoord:!1};let Wt;if("LineString"===et.type)Wt=et.coordinates;else{if("Polygon"!==et.type)return Bt;Wt=et.coordinates[0]}for(let Nt=0;Nt180||M.lng<-180||M.lat>90||M.lat<-90)return!1;if("Polygon"!==Nt.type||Wt!==$t.length-1&&0!==Wt)$t[Wt]=Gr;else{const M=$t.length-1;$t[0]=Gr,$t[M]=Gr}const mn=this.selectionPoints.getOneUpdated(Wt,Gr),Hn=mn?[mn]:[],so=this.midPoints.getUpdated($t)||[];return!("Point"!==Nt.type&&!et&&oe({type:"Feature",geometry:Nt,properties:{}})||Bt&&!Bt({type:"Feature",id:this.draggedCoordinate.id,geometry:Nt,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:Ea.Provisional})||(this.store.updateGeometry([{id:this.draggedCoordinate.id,geometry:Nt},...Hn,...so]),0))}isDragging(){return null!==this.draggedCoordinate.id}startDragging(M,et){this.draggedCoordinate={id:M,index:et}}stopDragging(){this.draggedCoordinate={id:null,index:-1}}}function Xe(M){let et=0,Bt=0,Wt=0;return("Polygon"===M.geometry.type?M.geometry.coordinates[0].slice(0,-1):M.geometry.coordinates).forEach((M=>{et+=M[0],Bt+=M[1],Wt++}),!0),[et/Wt,Bt/Wt]}function Ue(M,et){M[0]+=M[0]-et[0]>180?-360:et[0]-M[0]>180?360:0;const Bt=$a,Wt=et[1]*Math.PI/180,Nt=M[1]*Math.PI/180,$t=Nt-Wt;let Gr=Math.abs(M[0]-et[0])*Math.PI/180;Gr>Math.PI&&(Gr-=2*Math.PI);const mn=Math.log(Math.tan(Nt/2+Math.PI/4)/Math.tan(Wt/2+Math.PI/4)),Hn=Math.abs(mn)>1e-11?$t/mn:Math.cos(Wt);return Math.sqrt($t*$t+Hn*Hn*Gr*Gr)*Bt}function Ye(M){const et=("Polygon"===M.geometry.type?M.geometry.coordinates[0]:M.geometry.coordinates).map((M=>{const{x:et,y:Bt}=Qt(M[0],M[1]);return[et,Bt]}));return"Polygon"===M.geometry.type?function(M){let et=0,Bt=0,Wt=0;const Nt=M.length;for(let $t=0;$t180?Nt-=360:Nt<-180&&(Nt+=360),Nt}(Ye(Gr),Qt(M.lng,M.lat)),!this.lastBearing)return void(this.lastBearing=$t);((M,et)=>{if(0===et||360===et||-360===et)return M;const Bt=.017453292519943295*et,Wt=("Polygon"===M.geometry.type?M.geometry.coordinates[0]:M.geometry.coordinates).map((([M,et])=>Qt(M,et))),Nt=Wt.reduce(((M,et)=>({x:M.x+et.x,y:M.y+et.y})),{x:0,y:0});Nt.x/=Wt.length,Nt.y/=Wt.length;const $t=Wt.map((M=>({x:Nt.x+(M.x-Nt.x)*Math.cos(Bt)-(M.y-Nt.y)*Math.sin(Bt),y:Nt.y+(M.x-Nt.x)*Math.sin(Bt)+(M.y-Nt.y)*Math.cos(Bt)}))).map((({x:M,y:et})=>[te(M,et).lng,te(M,et).lat]));"Polygon"===M.geometry.type?M.geometry.coordinates[0]=$t:(console.log("rotatedCoordinates linestring",$t),M.geometry.coordinates=$t)})(Gr,-(this.lastBearing-$t))}else{if("globe"!==this.config.projection)throw new Error("Unsupported projection");if($t=Oe(Xe({type:"Feature",geometry:Wt,properties:{}}),Nt),!this.lastBearing)return void(this.lastBearing=$t+180);!function(M,et){if(0===et||360===et||-360===et)return M;const Bt=Xe(M);("Polygon"===M.geometry.type?M.geometry.coordinates[0]:M.geometry.coordinates).forEach((M=>{const Wt=Oe(Bt,M)+et,Nt=Ue(Bt,M),$t=Le(Bt,Nt,Wt);M[0]=$t[0],M[1]=$t[1]}))}(Gr,-(this.lastBearing-($t+180)))}const mn="Polygon"===Wt.type?Wt.coordinates[0]:Wt.coordinates;mn.forEach((M=>{M[0]=e(M[0],this.coordinatePrecision),M[1]=e(M[1],this.coordinatePrecision)}));const Hn=this.midPoints.getUpdated(mn)||[],so=this.selectionPoints.getUpdated(mn)||[];if(Bt&&!Bt({id:et,type:"Feature",geometry:Wt,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:Ea.Provisional}))return!1;this.store.updateGeometry([{id:et,geometry:Wt},...so,...Hn]),"web-mercator"===this.projection?this.lastBearing=$t:"globe"===this.projection&&(this.lastBearing=$t+180)}}class Ke extends de{constructor(M,et,Bt){super(M),this.config=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.lastDistance=void 0,this.config=M,this.selectionPoints=et,this.midPoints=Bt}reset(){this.lastDistance=void 0}scale(M,et,Bt){const Wt=this.store.getGeometryCopy(et);if("Polygon"!==Wt.type&&"LineString"!==Wt.type)return;const Nt=[M.lng,M.lat],$t={type:"Feature",geometry:Wt,properties:{}};let Gr;const mn=Ye($t);if("web-mercator"===this.config.projection){const et=Qt(M.lng,M.lat);Gr=i(mn,et)}else{if("globe"!==this.config.projection)throw new Error("Invalid projection");Gr=Ut(Xe({type:"Feature",geometry:Wt,properties:{}}),Nt)}if(!this.lastDistance)return void(this.lastDistance=Gr);const Hn=1-(this.lastDistance-Gr)/Gr;if("web-mercator"===this.config.projection){const{lng:M,lat:et}=te(mn.x,mn.y);!function(M,et,Bt){if(1===et)return M;const Wt=("Polygon"===M.geometry.type?M.geometry.coordinates[0]:M.geometry.coordinates).map((([M,et])=>Qt(M,et))),Nt=Qt(Bt[0],Bt[1]),$t=Wt.map((M=>({x:Nt.x+(M.x-Nt.x)*et,y:Nt.y+(M.y-Nt.y)*et}))).map((({x:M,y:et})=>[te(M,et).lng,te(M,et).lat]));"Polygon"===M.geometry.type?M.geometry.coordinates[0]=$t:M.geometry.coordinates=$t}($t,Hn,[M,et])}else"globe"===this.config.projection&&function(M,et,Bt,Wt="xy"){1===et||("Polygon"===M.geometry.type?M.geometry.coordinates[0]:M.geometry.coordinates).forEach((M=>{const Nt=Ue(Bt,M),$t=Oe(Bt,M),Gr=Le(Bt,Nt*et,$t);"x"!==Wt&&"xy"!==Wt||(M[0]=Gr[0]),"y"!==Wt&&"xy"!==Wt||(M[1]=Gr[1])}))}($t,Hn,Xe($t));const so="Polygon"===Wt.type?Wt.coordinates[0]:Wt.coordinates;so.forEach((M=>{M[0]=e(M[0],this.coordinatePrecision),M[1]=e(M[1],this.coordinatePrecision)}));const uo=this.midPoints.getUpdated(so)||[],Io=this.selectionPoints.getUpdated(so)||[];if(Bt&&!Bt({id:et,type:"Feature",geometry:Wt,properties:{}},{project:this.config.project,unproject:this.config.unproject,coordinatePrecision:this.config.coordinatePrecision,updateType:Ea.Provisional}))return!1;this.store.updateGeometry([{id:et,geometry:Wt},...Io,...uo]),this.lastDistance=Gr}}class Je extends de{constructor(M,et,Bt,Wt){super(M),this.config=void 0,this.pixelDistance=void 0,this.selectionPoints=void 0,this.midPoints=void 0,this.minimumScale=1e-4,this.draggedCoordinate={id:null,index:-1},this.boundingBoxMaps={opposite:{0:4,1:5,2:6,3:7,4:0,5:1,6:2,7:3}},this.config=M,this.pixelDistance=et,this.selectionPoints=Bt,this.midPoints=Wt}getClosestCoordinate(M,et){const Bt={dist:1/0,index:-1,isFirstOrLastPolygonCoord:!1};let Wt;if("LineString"===et.type)Wt=et.coordinates;else{if("Polygon"!==et.type)return Bt;Wt=et.coordinates[0]}for(let Nt=0;Nt=0)return!1;break;case 1:if(Bt>=0)return!1;break;case 2:if(et>=0||Bt>=0)return!1;break;case 3:if(et>=0)return!1;break;case 4:if(et>=0||Bt<=0)return!1;break;case 5:if(Bt<=0)return!1;break;case 6:if(et<=0||Bt<=0)return!1;break;case 7:if(et<=0)return!1}return!0}getSelectedFeatureDataWebMercator(){if(!this.draggedCoordinate.id||-1===this.draggedCoordinate.index)return null;const M=this.getFeature(this.draggedCoordinate.id);if(!M)return null;const et=this.getNormalisedCoordinates(M.geometry);return{boundingBox:this.getBBoxWebMercator(et),feature:M,updatedCoords:et,selectedCoordinate:et[this.draggedCoordinate.index]}}centerWebMercatorDrag(M){const et=this.getSelectedFeatureDataWebMercator();if(!et)return null;const{feature:Bt,boundingBox:Wt,updatedCoords:Nt,selectedCoordinate:$t}=et,Gr=Ye(Bt);if(!Gr)return null;const mn=Qt($t[0],$t[1]),{closestBBoxIndex:Hn}=this.getIndexesWebMercator(Wt,mn),so=Qt(M.lng,M.lat);return this.scaleWebMercator({closestBBoxIndex:Hn,updatedCoords:Nt,webMercatorCursor:so,webMercatorSelected:mn,webMercatorOrigin:Gr}),Nt}centerFixedWebMercatorDrag(M){const et=this.getSelectedFeatureDataWebMercator();if(!et)return null;const{feature:Bt,boundingBox:Wt,updatedCoords:Nt,selectedCoordinate:$t}=et,Gr=Ye(Bt);if(!Gr)return null;const mn=Qt($t[0],$t[1]),{closestBBoxIndex:Hn}=this.getIndexesWebMercator(Wt,mn),so=Qt(M.lng,M.lat);return this.scaleFixedWebMercator({closestBBoxIndex:Hn,updatedCoords:Nt,webMercatorCursor:so,webMercatorSelected:mn,webMercatorOrigin:Gr}),Nt}scaleFixedWebMercator({closestBBoxIndex:M,webMercatorOrigin:et,webMercatorSelected:Bt,webMercatorCursor:Wt,updatedCoords:Nt}){if(!this.isValidDragWebMercator(M,et.x-Wt.x,et.y-Wt.y))return null;let $t=i(et,Wt)/i(et,Bt);return $t<0&&($t=this.minimumScale),this.performWebMercatorScale(Nt,et.x,et.y,$t,$t),Nt}oppositeFixedWebMercatorDrag(M){const et=this.getSelectedFeatureDataWebMercator();if(!et)return null;const{boundingBox:Bt,updatedCoords:Wt,selectedCoordinate:Nt}=et,$t=Qt(Nt[0],Nt[1]),{oppositeBboxIndex:Gr,closestBBoxIndex:mn}=this.getIndexesWebMercator(Bt,$t),Hn={x:Bt[Gr][0],y:Bt[Gr][1]},so=Qt(M.lng,M.lat);return this.scaleFixedWebMercator({closestBBoxIndex:mn,updatedCoords:Wt,webMercatorCursor:so,webMercatorSelected:$t,webMercatorOrigin:Hn}),Wt}oppositeWebMercatorDrag(M){const et=this.getSelectedFeatureDataWebMercator();if(!et)return null;const{boundingBox:Bt,updatedCoords:Wt,selectedCoordinate:Nt}=et,$t=Qt(Nt[0],Nt[1]),{oppositeBboxIndex:Gr,closestBBoxIndex:mn}=this.getIndexesWebMercator(Bt,$t),Hn={x:Bt[Gr][0],y:Bt[Gr][1]},so=Qt(M.lng,M.lat);return this.scaleWebMercator({closestBBoxIndex:mn,updatedCoords:Wt,webMercatorCursor:so,webMercatorSelected:$t,webMercatorOrigin:Hn}),Wt}scaleWebMercator({closestBBoxIndex:M,webMercatorOrigin:et,webMercatorSelected:Bt,webMercatorCursor:Wt,updatedCoords:Nt}){const $t=et.x-Wt.x,Gr=et.y-Wt.y;if(!this.isValidDragWebMercator(M,$t,Gr))return null;let mn=1;0!==$t&&1!==M&&5!==M&&(mn=1-(et.x-Bt.x-$t)/$t);let Hn=1;return 0!==Gr&&3!==M&&7!==M&&(Hn=1-(et.y-Bt.y-Gr)/Gr),this.validateScale(mn,Hn)?(mn<0&&(mn=this.minimumScale),Hn<0&&(Hn=this.minimumScale),this.performWebMercatorScale(Nt,et.x,et.y,mn,Hn),Nt):null}getFeature(M){if(null===this.draggedCoordinate.id)return null;const et=this.store.getGeometryCopy(M);return"Polygon"!==et.type&&"LineString"!==et.type?null:{type:"Feature",geometry:et,properties:{}}}getNormalisedCoordinates(M){return"Polygon"===M.type?M.coordinates[0]:M.coordinates}validateScale(M,et){const Bt=!isNaN(M)&&et{const{x:$t,y:Gr}=Qt(M[0],M[1]),mn=et+($t-et)*Wt,Hn=Bt+(Gr-Bt)*Nt,{lng:so,lat:uo}=te(mn,Hn);M[0]=so,M[1]=uo}))}getBBoxWebMercator(M){const et=[1/0,1/0,-1/0,-1/0];(M=M.map((M=>{const{x:et,y:Bt}=Qt(M[0],M[1]);return[et,Bt]}))).forEach((([M,Bt])=>{Met[2]&&(et[2]=M),Bt>et[3]&&(et[3]=Bt)}));const[Bt,Wt,Nt,$t]=et;return[[Bt,$t],[(Bt+Nt)/2,$t],[Nt,$t],[Nt,$t+(Wt-$t)/2],[Nt,Wt],[(Bt+Nt)/2,Wt],[Bt,Wt],[Bt,$t+(Wt-$t)/2]]}getIndexesWebMercator(M,et){let Bt,Wt=1/0;for(let Nt=0;Ntthis.store.has(M))).map((M=>({id:M,property:La,value:!1})));this.store.updateProperty(M),this.onDeselect(this.selected[0]),this.selected=[],this.selectionPoints.delete(),this.midPoints.delete()}deleteSelected(){this.store.delete(this.selected),this.selected=[]}onRightClick(M){if(!this.selectionPoints.ids.length)return;let et,Bt=1/0;if(this.selectionPoints.ids.forEach((Wt=>{const Nt=this.store.getGeometryCopy(Wt),$t=this.pixelDistance.measure(M,Nt.coordinates);$t0);if(this.selected.length&&Bt)this.midPoints.insert(Bt.id,this.coordinatePrecision);else if(et&&et.id)this.select(et.id,!0);else if(this.selected.length&&this.allowManualDeselection)return void this.deselect()}start(){this.setStarted(),this.setSelecting()}stop(){this.cleanUp(),this.setStarted(),this.setStopped()}onClick(M){"right"!==M.button?"left"===M.button&&this.onLeftClick(M):this.onRightClick(M)}canScale(M){return this.keyEvents.scale&&this.keyEvents.scale.every((et=>M.heldKeys.includes(et)))}canRotate(M){return this.keyEvents.rotate&&this.keyEvents.rotate.every((et=>M.heldKeys.includes(et)))}preventDefaultKeyEvent(M){const et=this.canRotate(M),Bt=this.canScale(M);(et||Bt)&&M.preventDefault()}onKeyDown(M){this.preventDefaultKeyEvent(M)}onKeyUp(M){if(this.preventDefaultKeyEvent(M),this.keyEvents.delete&&M.key===this.keyEvents.delete){if(!this.selected.length)return;this.onDeselect(this.selected[0]),this.deleteSelected(),this.selectionPoints.delete(),this.midPoints.delete()}else this.keyEvents.deselect&&M.key===this.keyEvents.deselect&&this.cleanUp()}cleanUp(){this.selected.length&&this.deselect()}onDragStart(M,et){if(!this.selected.length)return;const Bt=this.store.getPropertiesCopy(this.selected[0]),Wt=this.flags[Bt.mode];if(!(Wt&&Wt.feature&&(Wt.feature.draggable||Wt.feature.coordinates&&Wt.feature.coordinates.draggable||Wt.feature.coordinates&&Wt.feature.coordinates.resizable)))return;this.dragEventCount=0;const Nt=this.selected[0],$t=this.dragCoordinate.getDraggableIndex(M,Nt);return Wt&&Wt.feature&&Wt.feature.coordinates&&(Wt.feature.coordinates.draggable||Wt.feature.coordinates.resizable)&&-1!==$t?(this.setCursor(this.cursors.dragStart),Wt.feature.coordinates.resizable?this.dragCoordinateResizeFeature.startDragging(Nt,$t):this.dragCoordinate.startDragging(Nt,$t),void et(!1)):Wt&&Wt.feature&&Wt.feature.draggable&&this.dragFeature.canDrag(M,Nt)?(this.setCursor(this.cursors.dragStart),this.dragFeature.startDragging(M,Nt),void et(!1)):void 0}onDrag(M,et){const Bt=this.selected[0];if(!Bt)return;const Wt=this.store.getPropertiesCopy(Bt),Nt=this.flags[Wt.mode],$t=!0===(Nt&&Nt.feature&&Nt.feature.selfIntersectable);if(this.dragEventCount++,this.dragEventCount%this.dragEventThrottle==0)return;const Gr=this.validations[Wt.mode];if(Nt&&Nt.feature&&Nt.feature.rotateable&&this.canRotate(M))return et(!1),void this.rotateFeature.rotate(M,Bt,Gr);if(Nt&&Nt.feature&&Nt.feature.scaleable&&this.canScale(M))return et(!1),void this.scaleFeature.scale(M,Bt,Gr);if(this.dragCoordinateResizeFeature.isDragging()&&Nt.feature&&Nt.feature.coordinates&&Nt.feature.coordinates.resizable){if("globe"===this.projection)throw new Error("Globe is currently unsupported projection for resizable");return et(!1),void this.dragCoordinateResizeFeature.drag(M,Nt.feature.coordinates.resizable,Gr)}this.dragCoordinate.isDragging()?this.dragCoordinate.drag(M,$t,Gr):this.dragFeature.isDragging()?this.dragFeature.drag(M,Gr):et(!0)}onDragEnd(M,et){this.setCursor(this.cursors.dragEnd),this.dragCoordinate.isDragging()?this.onFinish(this.selected[0],{mode:this.mode,action:"dragCoordinate"}):this.dragFeature.isDragging()?this.onFinish(this.selected[0],{mode:this.mode,action:"dragFeature"}):this.dragCoordinateResizeFeature.isDragging()&&this.onFinish(this.selected[0],{mode:this.mode,action:"dragCoordinateResize"}),this.dragCoordinate.stopDragging(),this.dragFeature.stopDragging(),this.dragCoordinateResizeFeature.stopDragging(),this.rotateFeature.reset(),this.scaleFeature.reset(),et(!0)}onMouseMove(M){if(!this.selected.length)return void this.setCursor("unset");if(this.dragFeature.isDragging())return;let et=!1;this.midPoints.ids.forEach((Bt=>{if(et)return;const Wt=this.store.getGeometryCopy(Bt);this.pixelDistance.measure(M,Wt.coordinates){const Nt=this.store.getGeometryCopy(Wt);this.pixelDistance.measure(M,Nt.coordinates)0&&(Wt&&Wt.id===this.selected[0]||Bt)?this.cursors.pointerOver:"unset")}styleFeature(M){const et=t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0});if(M.properties.mode===this.mode&&"Point"===M.geometry.type){if(M.properties.selectionPoint)return et.pointColor=this.getHexColorStylingValue(this.styles.selectionPointColor,et.pointColor,M),et.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectionPointOutlineColor,et.pointOutlineColor,M),et.pointWidth=this.getNumericStylingValue(this.styles.selectionPointWidth,et.pointWidth,M),et.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectionPointOutlineWidth,2,M),et.zIndex=30,et;if(M.properties.midPoint)return et.pointColor=this.getHexColorStylingValue(this.styles.midPointColor,et.pointColor,M),et.pointOutlineColor=this.getHexColorStylingValue(this.styles.midPointOutlineColor,et.pointOutlineColor,M),et.pointWidth=this.getNumericStylingValue(this.styles.midPointWidth,4,M),et.pointOutlineWidth=this.getNumericStylingValue(this.styles.midPointOutlineWidth,2,M),et.zIndex=40,et}else if(M.properties[La]){if("Polygon"===M.geometry.type)return et.polygonFillColor=this.getHexColorStylingValue(this.styles.selectedPolygonColor,et.polygonFillColor,M),et.polygonOutlineWidth=this.getNumericStylingValue(this.styles.selectedPolygonOutlineWidth,et.polygonOutlineWidth,M),et.polygonOutlineColor=this.getHexColorStylingValue(this.styles.selectedPolygonOutlineColor,et.polygonOutlineColor,M),et.polygonFillOpacity=this.getNumericStylingValue(this.styles.selectedPolygonFillOpacity,et.polygonFillOpacity,M),et.zIndex=10,et;if("LineString"===M.geometry.type)return et.lineStringColor=this.getHexColorStylingValue(this.styles.selectedLineStringColor,et.lineStringColor,M),et.lineStringWidth=this.getNumericStylingValue(this.styles.selectedLineStringWidth,et.lineStringWidth,M),et.zIndex=10,et;if("Point"===M.geometry.type)return et.pointWidth=this.getNumericStylingValue(this.styles.selectedPointWidth,et.pointWidth,M),et.pointColor=this.getHexColorStylingValue(this.styles.selectedPointColor,et.pointColor,M),et.pointOutlineColor=this.getHexColorStylingValue(this.styles.selectedPointOutlineColor,et.pointOutlineColor,M),et.pointOutlineWidth=this.getNumericStylingValue(this.styles.selectedPointOutlineWidth,et.pointOutlineWidth,M),et.zIndex=10,et}return et}}class qe extends Tt{constructor(...M){super(...M),this.type=Oa.Static,this.mode="static"}start(){}stop(){}onKeyUp(){}onKeyDown(){}onClick(){}onDragStart(){}onDrag(){}onDragEnd(){}onMouseMove(){}cleanUp(){}styleFeature(){return t({},{polygonFillColor:"#3f97e0",polygonOutlineColor:"#3f97e0",polygonOutlineWidth:4,polygonFillOpacity:.3,pointColor:"#3f97e0",pointOutlineColor:"#ffffff",pointOutlineWidth:0,pointWidth:6,lineStringColor:"#3f97e0",lineStringWidth:4,zIndex:0})}}function Ze(M,et,Bt,Wt,Nt){for(;Wt>Bt;){if(Wt-Bt>600){const $t=Wt-Bt+1,Gr=et-Bt+1,mn=Math.log($t),Hn=.5*Math.exp(2*mn/3),so=.5*Math.sqrt(mn*Hn*($t-Hn)/$t)*(Gr-$t/2<0?-1:1);Ze(M,et,Math.max(Bt,Math.floor(et-Gr*Hn/$t+so)),Math.min(Wt,Math.floor(et+($t-Gr)*Hn/$t+so)),Nt)}const $t=M[et];let Gr=Bt,mn=Wt;for(Qe(M,Bt,et),Nt(M[Wt],$t)>0&&Qe(M,Bt,Wt);Gr0;)mn--}0===Nt(M[Bt],$t)?Qe(M,Bt,mn):(mn++,Qe(M,mn,Wt)),mn<=et&&(Bt=mn+1),et<=mn&&(Wt=mn-1)}}function Qe(M,et,Bt){const Wt=M[et];M[et]=M[Bt],M[Bt]=Wt}function ti(M,et){ei(M,0,M.children.length,et,M)}function ei(M,et,Bt,Wt,Nt){Nt||(Nt=ci([])),Nt.minX=1/0,Nt.minY=1/0,Nt.maxX=-1/0,Nt.maxY=-1/0;for(let $t=et;$t=M.minX&&et.maxY>=M.minY}function ci(M){return{children:M,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function di(M,et,Bt,Wt,Nt){const $t=[et,Bt];for(;$t.length;){if((Bt=$t.pop())-(et=$t.pop())<=Wt)continue;const Gr=et+Math.ceil((Bt-et)/Wt/2)*Wt;Ze(M,Gr,et,Bt,Nt),$t.push(et,Gr,Gr,Bt)}}class ui{constructor(M){this._maxEntries=void 0,this._minEntries=void 0,this.data=void 0,this._maxEntries=Math.max(4,M),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}search(M){let et=this.data;const Bt=[];if(!hi(M,et))return Bt;const Wt=this.toBBox,Nt=[];for(;et;){for(let $t=0;$t=0&&Nt[et].children.length>this._maxEntries;)this._split(Nt,et),et--;this._adjustParentBBoxes(Wt,Nt,et)}_split(M,et){const Bt=M[et],Wt=Bt.children.length,Nt=this._minEntries;this._chooseSplitAxis(Bt,Nt,Wt);const $t=this._chooseSplitIndex(Bt,Nt,Wt),Gr=ci(Bt.children.splice($t,Bt.children.length-$t));Gr.height=Bt.height,Gr.leaf=Bt.leaf,ti(Bt,this.toBBox),ti(Gr,this.toBBox),et?M[et-1].children.push(Gr):this._splitRoot(Bt,Gr)}_splitRoot(M,et){this.data=ci([M,et]),this.data.height=M.height+1,this.data.leaf=!1,ti(this.data,this.toBBox)}_chooseSplitIndex(M,et,Bt){let Wt,Nt=1/0,$t=1/0;for(let Gr=et;Gr<=Bt-et;Gr++){const et=ei(M,0,Gr,this.toBBox),mn=ei(M,Gr,Bt,this.toBBox),Hn=ai(et,mn),so=ri(et)+ri(mn);Hn=et;Wt--){const et=M.children[Wt];ii(Gr,M.leaf?Nt(et):et),mn+=ni(Gr)}return mn}_adjustParentBBoxes(M,et,Bt){for(let Wt=Bt;Wt>=0;Wt--)ii(et[Wt],M)}_condense(M){for(let et,Bt=M.length-1;Bt>=0;Bt--)0===M[Bt].children.length?Bt>0?(et=M[Bt-1].children,et.splice(et.indexOf(M[Bt]),1)):this.clear():ti(M[Bt],this.toBBox)}}class gi{constructor(M){this.tree=void 0,this.idToNode=void 0,this.nodeToId=void 0,this.tree=new ui(M&&M.maxEntries?M.maxEntries:9),this.idToNode=new Map,this.nodeToId=new Map}setMaps(M,et){this.idToNode.set(M.id,et),this.nodeToId.set(et,M.id)}toBBox(M){const et=[],Bt=[];let Wt;if("Polygon"===M.geometry.type)Wt=M.geometry.coordinates[0];else if("LineString"===M.geometry.type)Wt=M.geometry.coordinates;else{if("Point"!==M.geometry.type)throw new Error("Not a valid feature to turn into a bounding box");Wt=[M.geometry.coordinates]}for(let M=0;M{const Wt=this.toBBox(M);if(this.setMaps(M,Wt),Bt.has(String(M.id)))throw new Error(`Duplicate feature ID found ${M.id}`);Bt.add(String(M.id)),et.push(Wt)})),this.tree.load(et)}update(M){this.remove(M.id);const et=this.toBBox(M);this.setMaps(M,et),this.tree.insert(et)}remove(M){const et=this.idToNode.get(M);if(!et)throw new Error(`${M} not inserted into the spatial index`);this.tree.remove(et)}clear(){this.tree.clear()}search(M){return this.tree.search(this.toBBox(M)).map((M=>this.nodeToId.get(M)))}collides(M){return this.tree.collides(this.toBBox(M))}}const Gl={getId:()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(M){const et=16*Math.random()|0;return("x"==M?et:3&et|8).toString(16)})),isValidId:M=>"string"==typeof M&&36===M.length};class yi{constructor(M){this.idStrategy=void 0,this.tracked=void 0,this.spatialIndex=void 0,this.store=void 0,this._onChange=()=>{},this.store={},this.spatialIndex=new gi,this.tracked=!M||!1!==M.tracked,this.idStrategy=M&&M.idStrategy?M.idStrategy:Gl}clone(M){return JSON.parse(JSON.stringify(M))}getId(){return this.idStrategy.getId()}has(M){return Boolean(this.store[M])}load(M,et){if(0===M.length)return;const Bt=this.clone(M);Bt.forEach((M=>{null==M.id&&(M.id=this.idStrategy.getId()),this.tracked&&(M.properties.createdAt?Vt(M.properties.createdAt):M.properties.createdAt=+new Date,M.properties.updatedAt?Vt(M.properties.updatedAt):M.properties.updatedAt=+new Date)}));const Wt=[];Bt.forEach((M=>{const Bt=M.id;if(et&&!et(M))throw new Error(`Feature is not ${Bt} valid: ${JSON.stringify(M)}`);if(this.has(Bt))throw new Error(`Feature already exists with this id: ${Bt}`);this.store[Bt]=M,Wt.push(Bt)})),this.spatialIndex.load(Bt),this._onChange(Wt,"create")}search(M,et){const Bt=this.spatialIndex.search(M).map((M=>this.store[M]));return this.clone(et?Bt.filter(et):Bt)}registerOnChange(M){this._onChange=(et,Bt)=>{M(et,Bt)}}getGeometryCopy(M){const et=this.store[M];if(!et)throw new Error(`No feature with this id (${M}), can not get geometry copy`);return this.clone(et.geometry)}getPropertiesCopy(M){const et=this.store[M];if(!et)throw new Error(`No feature with this id (${M}), can not get properties copy`);return this.clone(et.properties)}updateProperty(M){const et=[];M.forEach((({id:M,property:Bt,value:Wt})=>{const Nt=this.store[M];if(!Nt)throw new Error(`No feature with this (${M}), can not update geometry`);et.push(M),Nt.properties[Bt]=Wt,this.tracked&&(Nt.properties.updatedAt=+new Date)})),this._onChange&&this._onChange(et,"update")}updateGeometry(M){const et=[];M.forEach((({id:M,geometry:Bt})=>{et.push(M);const Wt=this.store[M];if(!Wt)throw new Error(`No feature with this (${M}), can not update geometry`);Wt.geometry=this.clone(Bt),this.spatialIndex.update(Wt),this.tracked&&(Wt.properties.updatedAt=+new Date)})),this._onChange&&this._onChange(et,"update")}create(M){const et=[];return M.forEach((({geometry:M,properties:Bt})=>{let Wt,Nt=t({},Bt);this.tracked&&(Wt=+new Date,Bt?(Nt.createdAt="number"==typeof Bt.createdAt?Bt.createdAt:Wt,Nt.updatedAt="number"==typeof Bt.updatedAt?Bt.updatedAt:Wt):Nt={createdAt:Wt,updatedAt:Wt});const $t=this.getId(),Gr={id:$t,type:"Feature",geometry:M,properties:Nt};this.store[$t]=Gr,this.spatialIndex.insert(Gr),et.push($t)})),this._onChange&&this._onChange([...et],"create"),et}delete(M){M.forEach((M=>{if(!this.store[M])throw new Error("No feature with this id, can not delete");delete this.store[M],this.spatialIndex.remove(M)})),this._onChange&&this._onChange([...M],"delete")}copyAll(){return this.clone(Object.keys(this.store).map((M=>this.store[M])))}clear(){this.store={},this.spatialIndex.clear()}size(){return Object.keys(this.store).length}}class Si{constructor(M){this._modes=void 0,this._mode=void 0,this._adapter=void 0,this._enabled=!1,this._store=void 0,this._eventListeners=void 0,this._instanceSelectMode=void 0,this._adapter=M.adapter,this._mode=new qe;const et=new Set,Bt=M.modes.reduce(((M,Bt)=>{if(et.has(Bt.mode))throw new Error(`There is already a ${Bt.mode} mode provided`);return et.add(Bt.mode),M[Bt.mode]=Bt,M}),{}),Wt=Object.keys(Bt);if(0===Wt.length)throw new Error("No modes provided");Wt.forEach((M=>{if(Bt[M].type===Oa.Select){if(this._instanceSelectMode)throw new Error("only one type of select mode can be provided");this._instanceSelectMode=M}})),this._modes=t({},Bt,{static:this._mode}),this._eventListeners={change:[],select:[],deselect:[],finish:[],ready:[]},this._store=new yi({tracked:!!M.tracked,idStrategy:M.idStrategy?M.idStrategy:void 0});const r=M=>{const et=[],Bt=this._store.copyAll().filter((Bt=>!M.includes(Bt.id)||(et.push(Bt),!1)));return{changed:et,unchanged:Bt}},n=(M,et)=>{this._enabled&&this._eventListeners.finish.forEach((Bt=>{Bt(M,et)}))},a=(M,et)=>{if(!this._enabled)return;this._eventListeners.change.forEach((Bt=>{Bt(M,et)}));const{changed:Bt,unchanged:Wt}=r(M);"create"===et?this._adapter.render({created:Bt,deletedIds:[],unchanged:Wt,updated:[]},this.getModeStyles()):"update"===et?this._adapter.render({created:[],deletedIds:[],unchanged:Wt,updated:Bt},this.getModeStyles()):"delete"===et?this._adapter.render({created:[],deletedIds:M,unchanged:Wt,updated:[]},this.getModeStyles()):"styling"===et&&this._adapter.render({created:[],deletedIds:[],unchanged:Wt,updated:[]},this.getModeStyles())},l=M=>{if(!this._enabled)return;this._eventListeners.select.forEach((et=>{et(M)}));const{changed:et,unchanged:Bt}=r([M]);this._adapter.render({created:[],deletedIds:[],unchanged:Bt,updated:et},this.getModeStyles())},h=M=>{if(!this._enabled)return;this._eventListeners.deselect.forEach((M=>{M()}));const{changed:et,unchanged:Bt}=r([M]);et&&this._adapter.render({created:[],deletedIds:[],unchanged:Bt,updated:et},this.getModeStyles())};Object.keys(this._modes).forEach((M=>{this._modes[M].register({mode:M,store:this._store,setCursor:this._adapter.setCursor.bind(this._adapter),project:this._adapter.project.bind(this._adapter),unproject:this._adapter.unproject.bind(this._adapter),setDoubleClickToZoom:this._adapter.setDoubleClickToZoom.bind(this._adapter),onChange:a,onSelect:l,onDeselect:h,onFinish:n,coordinatePrecision:this._adapter.getCoordinatePrecision()})}))}checkEnabled(){if(!this._enabled)throw new Error("Terra Draw is not enabled")}getModeStyles(){const M={};return Object.keys(this._modes).forEach((et=>{M[et]=M=>this._instanceSelectMode&&M.properties[La]?this._modes[this._instanceSelectMode].styleFeature.bind(this._modes[this._instanceSelectMode])(M):this._modes[et].styleFeature.bind(this._modes[et])(M)})),M}featuresAtLocation({lng:M,lat:et},Bt){const Wt=Bt&&void 0!==Bt.pointerDistance?Bt.pointerDistance:30,Nt=!Bt||void 0===Bt.ignoreSelectFeatures||Bt.ignoreSelectFeatures,$t=this._adapter.unproject.bind(this._adapter),Gr=this._adapter.project.bind(this._adapter),mn=Gr(M,et),Hn=ue({unproject:$t,point:mn,pointerDistance:Wt});return this._store.search(Hn).filter((Bt=>{if(Nt&&(Bt.properties[Da]||Bt.properties.selectionPoint))return!1;if("Point"===Bt.geometry.type){const M=Bt.geometry.coordinates,et=Gr(M[0],M[1]);return i(mn,et){if(Boolean(M&&"object"==typeof M&&"properties"in M&&"object"==typeof M.properties&&null!==M.properties&&"mode"in M.properties)){const et=this._modes[M.properties.mode];return!!et&&et.validateFeature.bind(et)(M)}return!1}))}start(){this._enabled=!0,this._adapter.register({onReady:()=>{this._eventListeners.ready.forEach((M=>{M()}))},getState:()=>this._mode.state,onClick:M=>{this._mode.onClick(M)},onMouseMove:M=>{this._mode.onMouseMove(M)},onKeyDown:M=>{this._mode.onKeyDown(M)},onKeyUp:M=>{this._mode.onKeyUp(M)},onDragStart:(M,et)=>{this._mode.onDragStart(M,et)},onDrag:(M,et)=>{this._mode.onDrag(M,et)},onDragEnd:(M,et)=>{this._mode.onDragEnd(M,et)},onClear:()=>{this._mode.cleanUp(),this._store.clear()}})}getFeaturesAtLngLat(M,et){const{lng:Bt,lat:Wt}=M;return this.featuresAtLocation({lng:Bt,lat:Wt},et)}getFeaturesAtPointerEvent(M,et){const Bt=this._adapter.getLngLatFromEvent.bind(this._adapter)(M);return null===Bt?[]:this.featuresAtLocation(Bt,et)}stop(){this._enabled=!1,this._adapter.unregister()}on(M,et){const Bt=this._eventListeners[M];Bt.includes(et)||Bt.push(et)}off(M,et){const Bt=this._eventListeners[M];Bt.includes(et)&&Bt.splice(Bt.indexOf(et),1)}}class MapOption{constructor({name:M,desc:et,example:Bt,exampleDesc:Wt,isValid:Nt}){this.name=M,this.desc=et,this.example=Bt,this.exampleDesc=Wt,this.isValid=Nt}valueOf(){return this.name}}class defaultExport{width="300px";height="300px";center=[121,24];zoom=7;control={scale:!1,fullscreen:!1};layers=[];data=[];aliases=[];svgPin={html:'',size:[27,41],anchor:[13.5,35.25]};get map(){if(void 0===this._map)throw Error("map is not set in current Renderer");return this._map}set map(M){if(this._map)throw Error("map cannot be reassigned");this._map=M}get steps(){return[this.setOptionAliases,this.createView,this.addMap,this.setControl,this.addTileData,this.addGPXFile,this.getTerraDrawAdapter,{valueOf:()=>this.setDraw,depends:this.getTerraDrawAdapter},this.setExtra]}validateOption(M,et){const Bt=this.constructor.validOptions.find((et=>et.valueOf()===M))?.isValid;if(!Bt)throw Error(`Cannot find inValid method for option ${M}`);return Bt(et)}static validOptions=Object.freeze([new MapOption({name:"id",desc:"id of map HTML element",isValid:M=>!!M?.match(/\w+/)}),new MapOption({name:"width",desc:"CSS width of map HTML element",example:"200px",exampleDesc:"",isValid:M=>window.CSS.supports(`width: ${M}`)}),new MapOption({name:"height",desc:"CSS height of map HTML element",example:"200px",exampleDesc:"",isValid:M=>window.CSS.supports(`height: ${M}`)}),new MapOption({name:"center",desc:"Center of camera map, value: [lon, lat]",example:"[121, 24]",exampleDesc:"Center of Taiwan",isValid:M=>{try{const[et,Bt]=JSON.parse(M);return!isNaN(et)&&!isNaN(Bt)}catch{return!1}}}),new MapOption({name:"zoom",desc:"Zoom level for map camera, number between: 0-22",example:"7.0",exampleDesc:"Small country / US state",isValid:M=>{const et=Number(M);return!isNaN(et)&&et>=0&&et<=22}}),new MapOption({name:"control",desc:"Object of control options, supports: fullscreen, scale",example:"\n scale: true",exampleDesc:"Add Scale bar",isValid:M=>"object"==typeof M}),new MapOption({name:"debug",desc:"Set true to show tile boundary",example:"true",exampleDesc:"",isValid:M=>"true"===M}),new MapOption({name:"XYZ",desc:"Raster tile format with {x}, {y} and {z}",example:"https://tile.openstreetmap.jp/styles/osm-bright/512/{z}/{x}/{y}.png",exampleDesc:"Tile from OSM Japan!",isValid:M=>URL.parse(M)&&M.includes("{x}")&&M.includes("{y}")&&M.includes("z")}),new MapOption({name:"GPX",desc:"URL of GPX file",example:"https://raw.githubusercontent.com/openlayers/openlayers/main/examples/data/gpx/fells_loop.gpx",exampleDesc:"Example from topografix",isValid:M=>URL.parse(M)}),new MapOption({name:"WMTS",desc:"URL of WMTS document",example:"https://gis.sinica.edu.tw/tileserver/wmts",exampleDesc:"SINICA Taiwan",isValid:M=>URL.parse(M)}),new MapOption({name:"draw",desc:"Draw Something on map",example:"true",exampleDesc:"Enable Draw Tools",isValid:M=>"true"===M}),new MapOption({name:"eval",desc:"Custom Script",example:"console.log('this', this)",exampleDesc:"Print Renderer info",isValid:()=>!0})]);setOptionAliases(M){if(M.XYZ){("string"==typeof M.XYZ?[M.XYZ]:M.XYZ).forEach((et=>{let Bt,Wt;if("string"==typeof et)Wt=new URL(et),Bt={type:"tile",url:et,title:`${Wt.host}${Wt.pathname.split("%7B")[0]}`};else{if("object"!=typeof et)return;Wt=new URL(et.url),Bt={type:"tile",url:et.url,title:et.title?et.title:`${Wt.host}${Wt.pathname.split("%7B")[0]}`}}M.data.push(Bt)})),delete M.XYZ}M.WMTS&&(M.data.push({type:"wmts",url:M.aliases[M.WMTS]??M.WMTS}),delete M.WMTS),M.GPX&&(M.data.push({type:"gpx",url:M.GPX}),delete M.GPX),"string"==typeof M.center&&Object.prototype.hasOwnProperty.call(M.aliases,M.center)&&(M.center=M.aliases[M.center]),M.data?.forEach((et=>{Object.prototype.hasOwnProperty.call(M.aliases,et.url)&&(et.title=et.url,et.url=M.aliases[et.url])}))}createView({target:M,width:et,height:Bt}){M.style.width=et,M.style.height=Bt,"flex"===window.getComputedStyle(M.parentElement).display&&(M.style.flexBasis=`calc(${et})`)}setDraw=({target:M,terraDrawAdapter:et})=>{const Bt=M?.id?M.id+"-":"",Wt={idStrategy:{isValidId:M=>!0,getId:function(){let M=Bt+window.crypto.randomUUID();return function(){return M=Bt+window.crypto.randomUUID(),M}}()}};return this.terraDraw=((M,et={})=>new Si({adapter:M,modes:[new $e({modename:"modify",flags:{render:{feature:{coordinates:{midpoints:!0,draggable:!0,deletable:!0,validation:()=>!0}}}}}),new Ee,new Se,new De,new he,new ke,new Fe({modeName:"render",styles:{pointColor:"red",pointOutlineWidth:2,lineStringColor:"red",lineStringWidth:2,polygonFillColor:"#00FFFF",polygonFillOpacity:0,polygonOutlineColor:"red",polygonOutlineWidth:2}})],...et}))(et,Wt),M.dataset.draw="",((M,et,Bt={})=>{et.start(),et.setMode("render");const Wt=M.id?`terra-draw-data-${M.id}`:"terra-draw-data",Nt=window.localStorage.getItem(Wt);if(Nt)try{const M=JSON.parse(Nt);M.forEach((M=>M.properties={mode:"render"})),et.addFeatures(M)}catch(M){console.warn("Fail to drawn features from Local Storage.",Nt,M),window.localStorage.removeItem(Wt)}const $t=M.querySelector("canvas")??M;$t.style.removeProperty("cursor");const Gr=et.getSnapshot();new window.MutationObserver((()=>{switch(M.dataset.draw){case"":case void 0:et.setMode("render");break;case"modify":et.setMode("select");break;case"delete":et.setMode("render"),$t.style.cursor="not-allowed";break;case"clear":window.localStorage.removeItem(Wt),M.dataset.draw="",et.clear();break;case"features":window.alert(`${Gr.length} features\n\n${JSON.stringify(Gr,null,4)}`);break;default:et.setMode(M.dataset.draw)}})).observe(M,{attributes:!0,attributeFilter:["data-draw"]}),et.on("change",(()=>{})),et.on("finish",((Nt,$t)=>{if("draw"===$t.action){const M=et.getSnapshot().find((M=>M.id===Nt));M&&(et.removeFeatures([Nt]),M.properties.mode="render",et.addFeatures([M]))}const Gr=Bt.idFilter??(()=>!0),mn=et.getSnapshot().filter(Gr);window.localStorage.setItem(Wt,JSON.stringify(mn)),"point"!==$t.mode&&"draw"===$t.action&&(M.dataset.draw="")})),document.onclick=Bt=>{if("delete"===M.dataset.draw){const Wt=et.getFeaturesAtPointerEvent(Bt,{pointerDistance:40});Wt.length>0&&(et.removeFeatures([Wt[0].id]),0===et.getSnapshot().length&&(M.dataset.draw=""))}}})(M,this.terraDraw,{idFilter:M=>M.id.startsWith(Bt)}),this.terraDraw};getTerraDrawAdapter(){return{state:"skip"}}addTileData(){return{state:"skip"}}addGPXFile(){return{state:"skip"}}addMarker(){return{state:"skip"}}setControl(){return{state:"skip"}}setExtra(){return{state:"skip"}}updateCamera(){return{state:"skip"}}project(){return{state:"skip"}}unproject(){return{state:"skip"}}restoreCamera(){this.updateCamera({center:this.center,zoom:this.zoom})}propsForEval(){let M=this,et=[],Bt=[];for(;M!==Object.prototype;)et=et.concat(Object.getOwnPropertyNames(M)),Bt=Bt.concat(Object.entries(M)),M=Object.getPrototypeOf(M);return et}evalScript(M,et=[]){const Bt=this.propsForEval(),Wt=et.map((([M,et])=>M)),Nt=[...Bt.map((M=>this[M])),...et.map((([M,et])=>et))],$t=Function([...Bt,...Wt],M).bind(this,...Nt);try{return $t()}catch(M){return console.warn("Fail to run custom script:",M),null}}}function getDefaultExportFromCjs$1(M){return M&&M.__esModule&&Object.prototype.hasOwnProperty.call(M,"default")?M.default:M}var Rl,Tl={exports:{}}; /** * MapLibre GL JS * @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v5.0.0/LICENSE.txt - */ -var maplibreGl = maplibreGl$1.exports; - -var hasRequiredMaplibreGl; - -function requireMaplibreGl () { - if (hasRequiredMaplibreGl) return maplibreGl$1.exports; - hasRequiredMaplibreGl = 1; - (function (module, exports) { - (function (global, factory) { - module.exports = factory() ; - })(maplibreGl, (function () { - /* eslint-disable */ - - var maplibregl = {}; - var modules = {}; - function define(moduleName, _dependencies, moduleFactory) { - modules[moduleName] = moduleFactory; - - // to get the list of modules see generated dist/maplibre-gl-dev.js file (look for `define(` calls) - if (moduleName !== 'index') { - return; - } - - // we assume that when an index module is initializing then other modules are loaded already - var workerBundleString = 'var sharedModule = {}; (' + modules.shared + ')(sharedModule); (' + modules.worker + ')(sharedModule);'; - - var sharedModule = {}; - // the order of arguments of a module factory depends on rollup (it decides who is whose dependency) - // to check the correct order, see dist/maplibre-gl-dev.js file (look for `define(` calls) - // we assume that for our 3 chunks it will generate 3 modules and their order is predefined like the following - modules.shared(sharedModule); - modules.index(maplibregl, sharedModule); - - if (typeof window !== 'undefined') { - maplibregl.setWorkerUrl(window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' }))); - } - - return maplibregl; - } - - - define("shared",["exports"],(function(t){function e(t,e,r,n){return new(r||(r=Promise))((function(i,s){function a(t){try{l(n.next(t));}catch(t){s(t);}}function o(t){try{l(n.throw(t));}catch(t){s(t);}}function l(t){var e;t.done?i(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e);}))).then(a,o);}l((n=n.apply(t,e||[])).next());}))}function r(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var n,i;function s(){if(i)return n;function t(t,e){this.x=t,this.y=e;}return i=1,n=t,t.prototype={clone:function(){return new t(this.x,this.y)},add:function(t){return this.clone()._add(t)},sub:function(t){return this.clone()._sub(t)},multByPoint:function(t){return this.clone()._multByPoint(t)},divByPoint:function(t){return this.clone()._divByPoint(t)},mult:function(t){return this.clone()._mult(t)},div:function(t){return this.clone()._div(t)},rotate:function(t){return this.clone()._rotate(t)},rotateAround:function(t,e){return this.clone()._rotateAround(t,e)},matMult:function(t){return this.clone()._matMult(t)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(t){return this.x===t.x&&this.y===t.y},dist:function(t){return Math.sqrt(this.distSqr(t))},distSqr:function(t){var e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith:function(t){return this.angleWithSep(t.x,t.y)},angleWithSep:function(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult:function(t){var e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add:function(t){return this.x+=t.x,this.y+=t.y,this},_sub:function(t){return this.x-=t.x,this.y-=t.y,this},_mult:function(t){return this.x*=t,this.y*=t,this},_div:function(t){return this.x/=t,this.y/=t,this},_multByPoint:function(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint:function(t){return this.x/=t.x,this.y/=t.y,this},_unit:function(){return this._div(this.mag()),this},_perp:function(){var t=this.y;return this.y=this.x,this.x=-t,this},_rotate:function(t){var e=Math.cos(t),r=Math.sin(t),n=r*this.x+e*this.y;return this.x=e*this.x-r*this.y,this.y=n,this},_rotateAround:function(t,e){var r=Math.cos(t),n=Math.sin(t),i=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=e.x+r*(this.x-e.x)-n*(this.y-e.y),this.y=i,this},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}},t.convert=function(e){return e instanceof t?e:Array.isArray(e)?new t(e[0],e[1]):e},n}"function"==typeof SuppressedError&&SuppressedError;var a,o,l=r(s()),u=function(){if(o)return a;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return o=1,a=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(undefined===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},a}(),c=r(u);let h,p;function f(){return null==h&&(h="undefined"!=typeof OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof createImageBitmap),h}function d(){if(null==p&&(p=false,f())){const t=5,e=new OffscreenCanvas(t,t).getContext("2d",{willReadFrequently:true});if(e){for(let r=0;r=1)return 1;const e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function B(t,e,r,n){const i=new c(t,e,r,n);return t=>i.solve(t)}const V=B(.25,.1,.25,1);function E(t,e,r){return Math.min(r,Math.max(e,t))}function T(t,e,r){const n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i}function F(t,...e){for(const r of e)for(const e in r)t[e]=r[e];return t}let $=1;function L(t,e,r){const n={};for(const r in t)n[r]=e.call(this,t[r],r,t);return n}function D(t,e,r){const n={};for(const r in t)e.call(this,t[r],r,t)&&(n[r]=t[r]);return n}function O(t){return Array.isArray(t)?t.map(O):"object"==typeof t&&t?L(t,O):t}const R={};function j(t){R[t]||("undefined"!=typeof console&&console.warn(t),R[t]=true);}function N(t,e,r){return (r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function U(t){return "undefined"!=typeof WorkerGlobalScope&&undefined!==t&&t instanceof WorkerGlobalScope}let q=null;function G(t){return "undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap}const Z="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";function X(t,r,n,i,s){return e(this,undefined,undefined,(function*(){if("undefined"==typeof VideoFrame)throw new Error("VideoFrame not supported");const e=new VideoFrame(t,{timestamp:0});try{const a=null==e?void 0:e.format;if(!a||!a.startsWith("BGR")&&!a.startsWith("RGB"))throw new Error(`Unrecognized format ${a}`);const o=a.startsWith("BGR"),l=new Uint8ClampedArray(i*s*4);if(yield e.copyTo(l,function(t,e,r,n,i){const s=4*Math.max(-e,0),a=(Math.max(0,r)-r)*n*4+s,o=4*n,l=Math.max(0,e),u=Math.max(0,r);return {rect:{x:l,y:u,width:Math.min(t.width,e+n)-l,height:Math.min(t.height,r+i)-u},layout:[{offset:a,stride:o}]}}(t,r,n,i,s)),o)for(let t=0;tU(self)?self.worker&&self.worker.referrer:("blob:"===window.location.protocol?window.parent:window).location.href,it=function(t,r){if(/:\/\//.test(t.url)&&!/^https?:|^file:/.test(t.url)){const e=tt(t.url);if(e)return e(t,r);if(U(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,targetMapId:et},r)}if(!(/^file:/.test(n=t.url)||/^file:/.test(nt())&&!/^\w+:/.test(n))){if(fetch&&Request&&AbortController&&Object.prototype.hasOwnProperty.call(Request.prototype,"signal"))return function(t,r){return e(this,undefined,undefined,(function*(){const e=new Request(t.url,{method:t.method||"GET",body:t.body,credentials:t.credentials,headers:t.headers,cache:t.cache,referrer:nt(),signal:r.signal});let n,i;"json"!==t.type||e.headers.has("Accept")||e.headers.set("Accept","application/json");try{n=yield fetch(e);}catch(e){throw new rt(0,e.message,t.url,new Blob)}if(!n.ok){const e=yield n.blob();throw new rt(n.status,n.statusText,t.url,e)}i="arrayBuffer"===t.type||"image"===t.type?n.arrayBuffer():"json"===t.type?n.json():n.text();const s=yield i;if(r.signal.aborted)throw W();return {data:s,cacheControl:n.headers.get("Cache-Control"),expires:n.headers.get("Expires")}}))}(t,r);if(U(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:t,mustQueue:true,targetMapId:et},r)}var n;return function(t,e){return new Promise(((r,n)=>{var i;const s=new XMLHttpRequest;s.open(t.method||"GET",t.url,true),"arrayBuffer"!==t.type&&"image"!==t.type||(s.responseType="arraybuffer");for(const e in t.headers)s.setRequestHeader(e,t.headers[e]);"json"===t.type&&(s.responseType="text",(null===(i=t.headers)||undefined===i?undefined:i.Accept)||s.setRequestHeader("Accept","application/json")),s.withCredentials="include"===t.credentials,s.onerror=()=>{n(new Error(s.statusText));},s.onload=()=>{if(!e.signal.aborted)if((s.status>=200&&s.status<300||0===s.status)&&null!==s.response){let e=s.response;if("json"===t.type)try{e=JSON.parse(s.response);}catch(t){return void n(t)}r({data:e,cacheControl:s.getResponseHeader("Cache-Control"),expires:s.getResponseHeader("Expires")});}else {const e=new Blob([s.response],{type:s.getResponseHeader("Content-Type")});n(new rt(s.status,s.statusText,t.url,e));}},e.signal.addEventListener("abort",(()=>{s.abort(),n(W());})),s.send(t.body);}))}(t,r)};function st(t){if(!t||t.indexOf("://")<=0||0===t.indexOf("data:image/")||0===t.indexOf("blob:"))return true;const e=new URL(t),r=window.location;return e.protocol===r.protocol&&e.host===r.host}function at(t,e,r){r[t]&&-1!==r[t].indexOf(e)||(r[t]=r[t]||[],r[t].push(e));}function ot(t,e,r){if(r&&r[t]){const n=r[t].indexOf(e);-1!==n&&r[t].splice(n,1);}}class lt{constructor(t,e={}){F(this,e),this.type=t;}}class ut extends lt{constructor(t,e={}){super("error",F({error:t},e));}}class ct{on(t,e){return this._listeners=this._listeners||{},at(t,e,this._listeners),{unsubscribe:()=>{this.off(t,e);}}}off(t,e){return ot(t,e,this._listeners),ot(t,e,this._oneTimeListeners),this}once(t,e){return e?(this._oneTimeListeners=this._oneTimeListeners||{},at(t,e,this._oneTimeListeners),this):new Promise((e=>this.once(t,e)))}fire(t,e){"string"==typeof t&&(t=new lt(t,e||{}));const r=t.type;if(this.listens(r)){t.target=this;const e=this._listeners&&this._listeners[r]?this._listeners[r].slice():[];for(const r of e)r.call(this,t);const n=this._oneTimeListeners&&this._oneTimeListeners[r]?this._oneTimeListeners[r].slice():[];for(const e of n)ot(r,e,this._oneTimeListeners),e.call(this,t);const i=this._eventedParent;i&&(F(t,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),i.fire(t));}else t instanceof ut&&console.error(t.error);return this}listens(t){return this._listeners&&this._listeners[t]&&this._listeners[t].length>0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)}setEventedParent(t,e){return this._eventedParent=t,this._eventedParentData=e,this}}var ht={$version:8,$root:{version:{required:true,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},centerAltitude:{type:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},roll:{type:"number",default:0,units:"degrees"},light:{type:"light"},sky:{type:"sky"},projection:{type:"projection"},terrain:{type:"terrain"},sources:{required:true,type:"sources"},sprite:{type:"sprite"},glyphs:{type:"string"},transition:{type:"transition"},layers:{required:true,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:true,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},volatile:{type:"boolean",default:false},"*":{type:"*"}},source_raster:{type:{required:true,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},volatile:{type:"boolean",default:false},"*":{type:"*"}},source_raster_dem:{type:{required:true,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{},custom:{}},default:"mapbox"},redFactor:{type:"number",default:1},blueFactor:{type:"number",default:1},greenFactor:{type:"number",default:1},baseShift:{type:"number",default:0},volatile:{type:"boolean",default:false},"*":{type:"*"}},source_geojson:{type:{required:true,type:"enum",values:{geojson:{}}},data:{required:true,type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},filter:{type:"*"},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:false},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:false},generateId:{type:"boolean",default:false},promoteId:{type:"promoteId"}},source_video:{type:{required:true,type:"enum",values:{video:{}}},urls:{required:true,type:"array",value:"string"},coordinates:{required:true,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:true,type:"enum",values:{image:{}}},url:{required:true,type:"string"},coordinates:{required:true,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:true},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},background:{}},required:true},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:false,expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:false,requires:["icon-image",{"!":"icon-overlap"}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["icon-image"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:false,requires:["icon-image"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:false,requires:["icon-image","text-field"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:true,expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"padding",default:[2],units:"pixels",requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-keep-upright":{type:"boolean",default:false,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},"viewport-glyph":{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:true,expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:true,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-variable-anchor-offset":{type:"variableAnchorOffsetCollection",requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:true,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:true,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:false,requires:["text-field",{"!":"text-overlap"}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["text-field"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:false,requires:["text-field"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:false,requires:["text-field","icon-image"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:false}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:false,expression:{interpolated:false,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:true,expression:{interpolated:true,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:true,parameters:["zoom"]},transition:true},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:true,parameters:["zoom"]},transition:true}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:true,parameters:["zoom"]},transition:true},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:true,parameters:["zoom"]},transition:true},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:true,parameters:["zoom"]},transition:true},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:true,parameters:["zoom"]},transition:true},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:true,parameters:["zoom"]},transition:true},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:true,parameters:["zoom"]},transition:true},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:true,parameters:["zoom"]},transition:true}},terrain:{source:{type:"string",required:true},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:false,expression:{interpolated:true,parameters:["zoom"]}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:true,expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:true,requires:[{"!":"fill-pattern"}],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:true,requires:[{"!":"fill-pattern"},{"fill-antialias":true}],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:true,expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:true,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:true,expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:true,requires:["fill-extrusion-height"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:true,transition:false,expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:true,requires:[{"!":"line-pattern"}],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:true,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:false,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:true,expression:{interpolated:false,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:false,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:true}}],expression:{interpolated:true,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:true,units:"pixels",expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:false,expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:false,expression:{interpolated:true,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:true,requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:true,requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:true,units:"pixels",requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:true,units:"pixels",requires:["icon-image"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:true,units:"pixels",requires:["icon-image"],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:true,overridable:true,requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:true,requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:true,units:"pixels",requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:true,units:"pixels",requires:["text-field"],expression:{interpolated:true,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:true,units:"pixels",requires:["text-field"],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:true,units:"degrees",expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:false,units:"milliseconds",expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,transition:false,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:false,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"color",default:"#000000",transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:true,requires:[{"!":"background-pattern"}],expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:true,expression:{interpolated:false,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:true,expression:{interpolated:true,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}};const pt=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function ft(t,e){const r={};for(const e in t)"ref"!==e&&(r[e]=t[e]);return pt.forEach((t=>{t in e&&(r[t]=e[t]);})),r}function dt(t,e){if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return false;for(let r=0;r`:"value"===t.itemType.kind?"array":`array<${e}>`}return t.kind}const Nt=[It,zt,Pt,Ct,Bt,Vt,$t,Et,Rt(Tt),Lt,Dt,Ot];function Ut(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!Ut(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else {if(t.kind===e.kind)return null;if("value"===t.kind)for(const t of Nt)if(!Ut(t,e))return null}return `Expected ${jt(t)} but found ${jt(e)} instead.`}function qt(t,e){return e.some((e=>e.kind===t.kind))}function Gt(t,e){return e.some((e=>"null"===e?null===t:"array"===e?Array.isArray(t):"object"===e?t&&!Array.isArray(t)&&"object"==typeof t:e===typeof t))}function Zt(t,e){return "array"===t.kind&&"array"===e.kind?t.itemType.kind===e.itemType.kind&&"number"==typeof t.N:t.kind===e.kind}const Xt=.96422,Kt=.82521,Ht=4/29,Yt=6/29,Jt=3*Yt*Yt,Wt=Yt*Yt*Yt,Qt=Math.PI/180,te=180/Math.PI;function ee(t){return (t%=360)<0&&(t+=360),t}function re([t,e,r,n]){let i,s;const a=ie((.2225045*(t=ne(t))+.7168786*(e=ne(e))+.0606169*(r=ne(r)))/1);t===e&&e===r?i=s=a:(i=ie((.4360747*t+.3850649*e+.1430804*r)/Xt),s=ie((.0139322*t+.0971045*e+.7141733*r)/Kt));const o=116*a-16;return [o<0?0:o,500*(i-a),200*(a-s),n]}function ne(t){return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function ie(t){return t>Wt?Math.pow(t,1/3):t/Jt+Ht}function se([t,e,r,n]){let i=(t+16)/116,s=isNaN(e)?i:i+e/500,a=isNaN(r)?i:i-r/200;return i=1*oe(i),s=Xt*oe(s),a=Kt*oe(a),[ae(3.1338561*s-1.6168667*i-.4906146*a),ae(-0.9787684*s+1.9161415*i+.033454*a),ae(.0719453*s-.2289914*i+1.4052427*a),n]}function ae(t){return (t=t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055)<0?0:t>1?1:t}function oe(t){return t>Yt?t*t*t:Jt*(t-Ht)}function le(t){return parseInt(t.padEnd(2,t),16)/255}function ue(t,e){return ce(e?t/100:t,0,1)}function ce(t,e,r){return Math.min(Math.max(e,t),r)}function he(t){return !t.some(Number.isNaN)}const pe={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function fe(t,e,r){return t+r*(e-t)}function de(t,e,r){return t.map(((t,n)=>fe(t,e[n],r)))}class ye{constructor(t,e,r,n=1,i=true){this.r=t,this.g=e,this.b=r,this.a=n,i||(this.r*=n,this.g*=n,this.b*=n,n||this.overwriteGetter("rgb",[t,e,r,n]));}static parse(t){if(t instanceof ye)return t;if("string"!=typeof t)return;const e=function(t){if("transparent"===(t=t.toLowerCase().trim()))return [0,0,0,0];const e=pe[t];if(e){const[t,r,n]=e;return [t/255,r/255,n/255,1]}if(t.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(t)){const e=t.length<6?1:2;let r=1;return [le(t.slice(r,r+=e)),le(t.slice(r,r+=e)),le(t.slice(r,r+=e)),le(t.slice(r,r+e)||"ff")]}if(t.startsWith("rgb")){const e=t.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(e){const[t,r,n,i,s,a,o,l,u,c,h,p]=e,f=[i||" ",o||" ",c].join("");if(" "===f||" /"===f||",,"===f||",,,"===f){const t=[n,a,u].join(""),e="%%%"===t?100:""===t?255:0;if(e){const t=[ce(+r/e,0,1),ce(+s/e,0,1),ce(+l/e,0,1),h?ue(+h,p):1];if(he(t))return t}}return}}const r=t.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(r){const[t,e,n,i,s,a,o,l,u]=r,c=[n||" ",s||" ",o].join("");if(" "===c||" /"===c||",,"===c||",,,"===c){const t=[+e,ce(+i,0,100),ce(+a,0,100),l?ue(+l,u):1];if(he(t))return function([t,e,r,n]){function i(n){const i=(n+t/30)%12,s=e*Math.min(r,1-r);return r-s*Math.max(-1,Math.min(i-3,9-i,1))}return t=ee(t),e/=100,r/=100,[i(0),i(8),i(4),n]}(t)}}}(t);return e?new ye(...e,false):undefined}get rgb(){const{r:t,g:e,b:r,a:n}=this,i=n||1/0;return this.overwriteGetter("rgb",[t/i,e/i,r/i,n])}get hcl(){return this.overwriteGetter("hcl",function(t){const[e,r,n,i]=re(t),s=Math.sqrt(r*r+n*n);return [Math.round(1e4*s)?ee(Math.atan2(n,r)*te):NaN,s,e,i]}(this.rgb))}get lab(){return this.overwriteGetter("lab",re(this.rgb))}overwriteGetter(t,e){return Object.defineProperty(this,t,{value:e}),e}toString(){const[t,e,r,n]=this.rgb;return `rgba(${[t,e,r].map((t=>Math.round(255*t))).join(",")},${n})`}static interpolate(t,e,r,n="rgb"){switch(n){case"rgb":{const[n,i,s,a]=de(t.rgb,e.rgb,r);return new ye(n,i,s,a,false)}case"hcl":{const[n,i,s,a]=t.hcl,[o,l,u,c]=e.hcl;let h,p;if(isNaN(n)||isNaN(o))isNaN(n)?isNaN(o)?h=NaN:(h=o,1!==s&&0!==s||(p=l)):(h=n,1!==u&&0!==u||(p=i));else {let t=o-n;o>n&&t>180?t-=360:o180&&(t+=360),h=n+r*t;}const[f,d,y,m]=function([t,e,r,n]){return t=isNaN(t)?0:t*Qt,se([r,Math.cos(t)*e,Math.sin(t)*e,n])}([h,null!=p?p:fe(i,l,r),fe(s,u,r),fe(a,c,r)]);return new ye(f,d,y,m,false)}case"lab":{const[n,i,s,a]=se(de(t.lab,e.lab,r));return new ye(n,i,s,a,false)}}}}ye.black=new ye(0,0,0,1),ye.white=new ye(1,1,1,1),ye.transparent=new ye(0,0,0,0),ye.red=new ye(1,0,0,1);class me{constructor(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});}compare(t,e){return this.collator.compare(t,e)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class ge{constructor(t,e,r,n,i){this.text=t,this.image=e,this.scale=r,this.fontStack=n,this.textColor=i;}}class xe{constructor(t){this.sections=t;}static fromString(t){return new xe([new ge(t,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some((t=>0!==t.text.length||t.image&&0!==t.image.name.length))}static factory(t){return t instanceof xe?t:xe.fromString(t)}toString(){return 0===this.sections.length?"":this.sections.map((t=>t.text)).join("")}}class ve{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof ve)return t;if("number"==typeof t)return new ve([t,t,t,t]);if(Array.isArray(t)&&!(t.length<1||t.length>4)){for(const e of t)if("number"!=typeof e)return;switch(t.length){case 1:t=[t[0],t[0],t[0],t[0]];break;case 2:t=[t[0],t[1],t[0],t[1]];break;case 3:t=[t[0],t[1],t[2],t[1]];}return new ve(t)}}toString(){return JSON.stringify(this.values)}static interpolate(t,e,r){return new ve(de(t.values,e.values,r))}}class be{constructor(t){this.name="ExpressionEvaluationError",this.message=t;}toJSON(){return this.message}}const we=new Set(["center","left","right","top","bottom","top-left","top-right","bottom-left","bottom-right"]);class _e{constructor(t){this.values=t.slice();}static parse(t){if(t instanceof _e)return t;if(Array.isArray(t)&&!(t.length<1)&&t.length%2==0){for(let e=0;e=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?undefined===n||"number"==typeof n&&n>=0&&n<=1?null:`Invalid rgba value [${[t,e,r,n].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Me(t){if(null===t||"string"==typeof t||"boolean"==typeof t||"number"==typeof t||t instanceof Ae||t instanceof ye||t instanceof me||t instanceof xe||t instanceof ve||t instanceof _e||t instanceof Se)return true;if(Array.isArray(t)){for(const e of t)if(!Me(e))return false;return true}if("object"==typeof t){for(const e in t)if(!Me(t[e]))return false;return true}return false}function Ie(t){if(null===t)return It;if("string"==typeof t)return Pt;if("boolean"==typeof t)return Ct;if("number"==typeof t)return zt;if(t instanceof ye)return Bt;if(t instanceof Ae)return Vt;if(t instanceof me)return Ft;if(t instanceof xe)return $t;if(t instanceof ve)return Lt;if(t instanceof _e)return Ot;if(t instanceof Se)return Dt;if(Array.isArray(t)){const e=t.length;let r;for(const e of t){const t=Ie(e);if(r){if(r===t)continue;r=Tt;break}r=t;}return Rt(r||Tt,e)}return Et}function ze(t){const e=typeof t;return null===t?"":"string"===e||"number"===e||"boolean"===e?String(t):t instanceof ye||t instanceof Ae||t instanceof xe||t instanceof ve||t instanceof _e||t instanceof Se?t.toString():JSON.stringify(t)}class Pe{constructor(t,e){this.type=t,this.value=e;}static parse(t,e){if(2!==t.length)return e.error(`'literal' expression requires exactly one argument, but found ${t.length-1} instead.`);if(!Me(t[1]))return e.error("invalid value");const r=t[1];let n=Ie(r);const i=e.expectedType;return "array"!==n.kind||0!==n.N||!i||"array"!==i.kind||"number"==typeof i.N&&0!==i.N||(n=i),new Pe(n,r)}evaluate(){return this.value}eachChild(){}outputDefined(){return true}}const Ce={string:Pt,number:zt,boolean:Ct,object:Et};class Be{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r,n=1;const i=t[0];if("array"===i){let i,s;if(t.length>2){const r=t[1];if("string"!=typeof r||!(r in Ce)||"object"===r)return e.error('The item type argument of "array" must be one of string, number, boolean',1);i=Ce[r],n++;}else i=Tt;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);s=t[2],n++;}r=Rt(i,s);}else {if(!Ce[i])throw new Error(`Types doesn't contain name = ${i}`);r=Ce[i];}const s=[];for(;nt.outputDefined()))}}const Ve={"to-boolean":Ct,"to-color":Bt,"to-number":zt,"to-string":Pt};class Ee{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[0];if(!Ve[r])throw new Error(`Can't parse ${r} as it is not part of the known types`);if(("to-boolean"===r||"to-string"===r)&&2!==t.length)return e.error("Expected one argument.");const n=Ve[r],i=[];for(let r=1;r4?`Invalid rgba value ${JSON.stringify(e)}: expected an array containing either three or four numeric values.`:ke(e[0],e[1],e[2],e[3]),!r))return new ye(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new be(r||`Could not parse color from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"padding":{let e;for(const r of this.args){e=r.evaluate(t);const n=ve.parse(e);if(n)return n}throw new be(`Could not parse padding from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"variableAnchorOffsetCollection":{let e;for(const r of this.args){e=r.evaluate(t);const n=_e.parse(e);if(n)return n}throw new be(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof e?e:JSON.stringify(e)}'`)}case"number":{let e=null;for(const r of this.args){if(e=r.evaluate(t),null===e)return 0;const n=Number(e);if(!isNaN(n))return n}throw new be(`Could not convert ${JSON.stringify(e)} to number.`)}case"formatted":return xe.fromString(ze(this.args[0].evaluate(t)));case"resolvedImage":return Se.fromString(ze(this.args[0].evaluate(t)));case"projectionDefinition":return this.args[0].evaluate(t);default:return ze(this.args[0].evaluate(t))}}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}function Te(t,e,r=0,n=t.length-1,i=$e){for(;n>r;){if(n-r>600){const s=n-r+1,a=e-r+1,o=Math.log(s),l=.5*Math.exp(2*o/3),u=.5*Math.sqrt(o*l*(s-l)/s)*(a-s/2<0?-1:1);Te(t,e,Math.max(r,Math.floor(e-a*l/s+u)),Math.min(n,Math.floor(e+(s-a)*l/s+u)),i);}const s=t[e];let a=r,o=n;for(Fe(t,r,e),i(t[n],s)>0&&Fe(t,r,n);a0;)o--;}0===i(t[r],s)?Fe(t,r,o):(o++,Fe(t,o,n)),o<=e&&(r=o+1),e<=o&&(n=o-1);}}function Fe(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function $e(t,e){return te?1:0}function Le(t,e){if(t.length<=1)return [t];const r=[];let n,i;for(const e of t){const t=Oe(e);0!==t&&(e.area=Math.abs(t),undefined===i&&(i=t<0),i===t<0?(n&&r.push(n),n=[e]):n.push(e));}if(n&&r.push(n),e>1)for(let t=0;t`[${t}]`)).join(""),this.scope=i,this.errors=s,this.expectedType=n,this._isConstant=e;}parse(t,e,r,n,i={}){return e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)}_parse(t,e){function r(t,e,r){return "assert"===r?new Be(e,[t]):"coerce"===r?new Ee(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const n=t[0];if("string"!=typeof n)return this.error(`Expression name must be a string, but found ${typeof n} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const i=this.registry[n];if(i){let n=i.parse(t,this);if(!n)return null;if(this.expectedType){const t=this.expectedType,i=n.type;if("string"!==t.kind&&"number"!==t.kind&&"boolean"!==t.kind&&"object"!==t.kind&&"array"!==t.kind||"value"!==i.kind)if("projectionDefinition"!==t.kind||"string"!==i.kind&&"array"!==i.kind)if("color"!==t.kind&&"formatted"!==t.kind&&"resolvedImage"!==t.kind||"value"!==i.kind&&"string"!==i.kind)if("padding"!==t.kind||"value"!==i.kind&&"number"!==i.kind&&"array"!==i.kind)if("variableAnchorOffsetCollection"!==t.kind||"value"!==i.kind&&"array"!==i.kind){if(this.checkSubtype(t,i))return null}else n=r(n,t,e.typeAnnotation||"coerce");else n=r(n,t,e.typeAnnotation||"coerce");else n=r(n,t,e.typeAnnotation||"coerce");else n=r(n,t,e.typeAnnotation||"coerce");else n=r(n,t,e.typeAnnotation||"assert");}if(!(n instanceof Pe)&&"resolvedImage"!==n.type.kind&&this._isConstant(n)){const t=new Ne;try{n=new Pe(n.type,n.evaluate(t));}catch(t){return this.error(t.message),null}}return n}return this.error(`Unknown expression "${n}". If you wanted a literal array, use ["literal", [...]].`,0)}return this.error(undefined===t?"'undefined' value invalid. Use null instead.":"object"==typeof t?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof t} instead.`)}concat(t,e,r){const n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new Ue(this.registry,this._isConstant,n,e||null,i,this.errors)}error(t,...e){const r=`${this.key}${e.map((t=>`[${t}]`)).join("")}`;this.errors.push(new kt(r,t));}checkSubtype(t,e){const r=Ut(t,e);return r&&this.error(r),r}}class qe{constructor(t,e){this.type=e.type,this.bindings=[].concat(t),this.result=e;}evaluate(t){return this.result.evaluate(t)}eachChild(t){for(const e of this.bindings)t(e[1]);t(this.result);}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found ${t.length-1} instead.`);const r=[];for(let n=1;n=r.length)throw new be(`Array index out of bounds: ${e} > ${r.length-1}.`);if(e!==Math.floor(e))throw new be(`Array index must be an integer, but found ${e} instead.`);return r[e]}eachChild(t){t(this.index),t(this.input);}outputDefined(){return false}}class Xe{constructor(t,e){this.type=Ct,this.needle=t,this.haystack=e;}static parse(t,e){if(3!==t.length)return e.error(`Expected 2 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Tt),n=e.parse(t[2],2,Tt);return r&&n?qt(r.type,[Ct,Pt,zt,It,Tt])?new Xe(r,n):e.error(`Expected first argument to be of type boolean, string, number or null, but found ${jt(r.type)} instead`):null}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!r)return false;if(!Gt(e,["boolean","string","number","null"]))throw new be(`Expected first argument to be of type boolean, string, number or null, but found ${jt(Ie(e))} instead.`);if(!Gt(r,["string","array"]))throw new be(`Expected second argument to be of type array or string, but found ${jt(Ie(r))} instead.`);return r.indexOf(e)>=0}eachChild(t){t(this.needle),t(this.haystack);}outputDefined(){return true}}class Ke{constructor(t,e,r){this.type=zt,this.needle=t,this.haystack=e,this.fromIndex=r;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 3 or 4 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Tt),n=e.parse(t[2],2,Tt);if(!r||!n)return null;if(!qt(r.type,[Ct,Pt,zt,It,Tt]))return e.error(`Expected first argument to be of type boolean, string, number or null, but found ${jt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,zt);return i?new Ke(r,n,i):null}return new Ke(r,n)}evaluate(t){const e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!Gt(e,["boolean","string","number","null"]))throw new be(`Expected first argument to be of type boolean, string, number or null, but found ${jt(Ie(e))} instead.`);let n;if(this.fromIndex&&(n=this.fromIndex.evaluate(t)),Gt(r,["string"])){const t=r.indexOf(e,n);return -1===t?-1:[...r.slice(0,t)].length}if(Gt(r,["array"]))return r.indexOf(e,n);throw new be(`Expected second argument to be of type array or string, but found ${jt(Ie(r))} instead.`)}eachChild(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex);}outputDefined(){return false}}class He{constructor(t,e,r,n,i,s){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=s;}static parse(t,e){if(t.length<5)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if(t.length%2!=1)return e.error("Expected an even number of arguments.");let r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);const i={},s=[];for(let a=2;aNumber.MAX_SAFE_INTEGER)return u.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof t&&Math.floor(t)!==t)return u.error("Numeric branch labels must be integer values.");if(r){if(u.checkSubtype(r,Ie(t)))return null}else r=Ie(t);if(undefined!==i[String(t)])return u.error("Branch labels must be unique.");i[String(t)]=s.length;}const c=e.parse(l,a,n);if(!c)return null;n=n||c.type,s.push(c);}const a=e.parse(t[1],1,Tt);if(!a)return null;const o=e.parse(t[t.length-1],t.length-1,n);return o?"value"!==a.type.kind&&e.concat(1).checkSubtype(r,a.type)?null:new He(r,n,a,i,s,o):null}evaluate(t){const e=this.input.evaluate(t);return (Ie(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)}eachChild(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))&&this.otherwise.outputDefined()}}class Ye{constructor(t,e,r){this.type=t,this.branches=e,this.otherwise=r;}static parse(t,e){if(t.length<4)return e.error(`Expected at least 3 arguments, but found only ${t.length-1}.`);if(t.length%2!=0)return e.error("Expected an odd number of arguments.");let r;e.expectedType&&"value"!==e.expectedType.kind&&(r=e.expectedType);const n=[];for(let i=1;ie.outputDefined()))&&this.otherwise.outputDefined()}}class Je{constructor(t,e,r,n){this.type=t,this.input=e,this.beginIndex=r,this.endIndex=n;}static parse(t,e){if(t.length<=2||t.length>=5)return e.error(`Expected 3 or 4 arguments, but found ${t.length-1} instead.`);const r=e.parse(t[1],1,Tt),n=e.parse(t[2],2,zt);if(!r||!n)return null;if(!qt(r.type,[Rt(Tt),Pt,Tt]))return e.error(`Expected first argument to be of type array or string, but found ${jt(r.type)} instead`);if(4===t.length){const i=e.parse(t[3],3,zt);return i?new Je(r.type,r,n,i):null}return new Je(r.type,r,n)}evaluate(t){const e=this.input.evaluate(t),r=this.beginIndex.evaluate(t);let n;if(this.endIndex&&(n=this.endIndex.evaluate(t)),Gt(e,["string"]))return [...e].slice(r,n).join("");if(Gt(e,["array"]))return e.slice(r,n);throw new be(`Expected first argument to be of type array or string, but found ${jt(Ie(e))} instead.`)}eachChild(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex);}outputDefined(){return false}}function We(t,e){const r=t.length-1;let n,i,s=0,a=r,o=0;for(;s<=a;)if(o=Math.floor((s+a)/2),n=t[o],i=t[o+1],n<=e){if(o===r||ee))throw new be("Input is not a number.");a=o-1;}return 0}class Qe{constructor(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(const[t,e]of r)this.labels.push(t),this.outputs.push(e);}static parse(t,e){if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");const r=e.parse(t[1],1,zt);if(!r)return null;const n=[];let i=null;e.expectedType&&"value"!==e.expectedType.kind&&(i=e.expectedType);for(let r=1;r=s)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',o);const u=e.parse(a,l,i);if(!u)return null;i=i||u.type,n.push([s,u]);}return new Qe(i,r,n)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[We(e,n)].evaluate(t)}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function tr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var er,rr,nr=function(){if(rr)return er;function t(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=e,this.p2x=r,this.p2y=n;}return rr=1,er=t,t.prototype={sampleCurveX:function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},sampleCurveY:function(t){return ((this.ay*t+this.by)*t+this.cy)*t},sampleCurveDerivativeX:function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},solveCurveX:function(t,e){if(undefined===e&&(e=1e-6),t<0)return 0;if(t>1)return 1;for(var r=t,n=0;n<8;n++){var i=this.sampleCurveX(r)-t;if(Math.abs(i)i?a=r:o=r,r=.5*(o-a)+a;return r},solve:function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))}},er}(),ir=tr(nr);class sr{constructor(t,e,r,n,i){this.type=t,this.operator=e,this.interpolation=r,this.input=n,this.labels=[],this.outputs=[];for(const[t,e]of i)this.labels.push(t),this.outputs.push(e);}static interpolationFactor(t,e,r,n){let i=0;if("exponential"===t.name)i=ar(e,t.base,r,n);else if("linear"===t.name)i=ar(e,1,r,n);else if("cubic-bezier"===t.name){const s=t.controlPoints;i=new ir(s[0],s[1],s[2],s[3]).solve(ar(e,1,r,n));}return i}static parse(t,e){let[r,n,i,...s]=t;if(!Array.isArray(n)||0===n.length)return e.error("Expected an interpolation type expression.",1);if("linear"===n[0])n={name:"linear"};else if("exponential"===n[0]){const t=n[1];if("number"!=typeof t)return e.error("Exponential interpolation requires a numeric base.",1,1);n={name:"exponential",base:t};}else {if("cubic-bezier"!==n[0])return e.error(`Unknown interpolation type ${String(n[0])}`,1,0);{const t=n.slice(1);if(4!==t.length||t.some((t=>"number"!=typeof t||t<0||t>1)))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:t};}}if(t.length-1<4)return e.error(`Expected at least 4 arguments, but found only ${t.length-1}.`);if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(i=e.parse(i,2,zt),!i)return null;const a=[];let o=null;"interpolate-hcl"===r||"interpolate-lab"===r?o=Bt:e.expectedType&&"value"!==e.expectedType.kind&&(o=e.expectedType);for(let t=0;t=r)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',i);const u=e.parse(n,l,o);if(!u)return null;o=o||u.type,a.push([r,u]);}return Zt(o,zt)||Zt(o,Vt)||Zt(o,Bt)||Zt(o,Lt)||Zt(o,Ot)||Zt(o,Rt(zt))?new sr(o,r,n,i,a):e.error(`Type ${jt(o)} is not interpolatable.`)}evaluate(t){const e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);const n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);const i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);const s=We(e,n),a=sr.interpolationFactor(this.interpolation,n,e[s],e[s+1]),o=r[s].evaluate(t),l=r[s+1].evaluate(t);switch(this.operator){case"interpolate":switch(this.type.kind){case"number":return fe(o,l,a);case"color":return ye.interpolate(o,l,a);case"padding":return ve.interpolate(o,l,a);case"variableAnchorOffsetCollection":return _e.interpolate(o,l,a);case"array":return de(o,l,a);case"projectionDefinition":return Ae.interpolate(o,l,a)}case"interpolate-hcl":return ye.interpolate(o,l,a,"hcl");case"interpolate-lab":return ye.interpolate(o,l,a,"lab")}}eachChild(t){t(this.input);for(const e of this.outputs)t(e);}outputDefined(){return this.outputs.every((t=>t.outputDefined()))}}function ar(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}const or={color:ye.interpolate,number:fe,padding:ve.interpolate,variableAnchorOffsetCollection:_e.interpolate,array:de};class lr{constructor(t,e){this.type=t,this.args=e;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");let r=null;const n=e.expectedType;n&&"value"!==n.kind&&(r=n);const i=[];for(const n of t.slice(1)){const t=e.parse(n,1+i.length,r,undefined,{typeAnnotation:"omit"});if(!t)return null;r=r||t.type,i.push(t);}if(!r)throw new Error("No output type");const s=n&&i.some((t=>Ut(n,t.type)));return new lr(s?Tt:r,i)}evaluate(t){let e,r=null,n=0;for(const i of this.args)if(n++,r=i.evaluate(t),r&&r instanceof Se&&!r.available&&(e||(e=r.name),r=null,n===this.args.length&&(r=e)),null!==r)break;return r}eachChild(t){this.args.forEach(t);}outputDefined(){return this.args.every((t=>t.outputDefined()))}}function ur(t,e){return "=="===t||"!="===t?"boolean"===e.kind||"string"===e.kind||"number"===e.kind||"null"===e.kind||"value"===e.kind:"string"===e.kind||"number"===e.kind||"value"===e.kind}function cr(t,e,r,n){return 0===n.compare(e,r)}function hr(t,e,r){const n="=="!==t&&"!="!==t;return class i{constructor(t,e,r){this.type=Ct,this.lhs=t,this.rhs=e,this.collator=r,this.hasUntypedArgument="value"===t.type.kind||"value"===e.type.kind;}static parse(t,e){if(3!==t.length&&4!==t.length)return e.error("Expected two or three arguments.");const r=t[0];let s=e.parse(t[1],1,Tt);if(!s)return null;if(!ur(r,s.type))return e.concat(1).error(`"${r}" comparisons are not supported for type '${jt(s.type)}'.`);let a=e.parse(t[2],2,Tt);if(!a)return null;if(!ur(r,a.type))return e.concat(2).error(`"${r}" comparisons are not supported for type '${jt(a.type)}'.`);if(s.type.kind!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error(`Cannot compare types '${jt(s.type)}' and '${jt(a.type)}'.`);n&&("value"===s.type.kind&&"value"!==a.type.kind?s=new Be(a.type,[s]):"value"!==s.type.kind&&"value"===a.type.kind&&(a=new Be(s.type,[a])));let o=null;if(4===t.length){if("string"!==s.type.kind&&"string"!==a.type.kind&&"value"!==s.type.kind&&"value"!==a.type.kind)return e.error("Cannot use collator to compare non-string types.");if(o=e.parse(t[3],3,Ft),!o)return null}return new i(s,a,o)}evaluate(i){const s=this.lhs.evaluate(i),a=this.rhs.evaluate(i);if(n&&this.hasUntypedArgument){const e=Ie(s),r=Ie(a);if(e.kind!==r.kind||"string"!==e.kind&&"number"!==e.kind)throw new be(`Expected arguments for "${t}" to be (string, string) or (number, number), but found (${e.kind}, ${r.kind}) instead.`)}if(this.collator&&!n&&this.hasUntypedArgument){const t=Ie(s),r=Ie(a);if("string"!==t.kind||"string"!==r.kind)return e(i,s,a)}return this.collator?r(i,s,a,this.collator.evaluate(i)):e(i,s,a)}eachChild(t){t(this.lhs),t(this.rhs),this.collator&&t(this.collator);}outputDefined(){return true}}}const pr=hr("==",(function(t,e,r){return e===r}),cr),fr=hr("!=",(function(t,e,r){return e!==r}),(function(t,e,r,n){return !cr(0,e,r,n)})),dr=hr("<",(function(t,e,r){return e",(function(t,e,r){return e>r}),(function(t,e,r,n){return n.compare(e,r)>0})),mr=hr("<=",(function(t,e,r){return e<=r}),(function(t,e,r,n){return n.compare(e,r)<=0})),gr=hr(">=",(function(t,e,r){return e>=r}),(function(t,e,r,n){return n.compare(e,r)>=0}));class xr{constructor(t,e,r){this.type=Ft,this.locale=r,this.caseSensitive=t,this.diacriticSensitive=e;}static parse(t,e){if(2!==t.length)return e.error("Expected one argument.");const r=t[1];if("object"!=typeof r||Array.isArray(r))return e.error("Collator options argument must be an object.");const n=e.parse(undefined!==r["case-sensitive"]&&r["case-sensitive"],1,Ct);if(!n)return null;const i=e.parse(undefined!==r["diacritic-sensitive"]&&r["diacritic-sensitive"],1,Ct);if(!i)return null;let s=null;return r.locale&&(s=e.parse(r.locale,1,Pt),!s)?null:new xr(n,i,s)}evaluate(t){return new me(this.caseSensitive.evaluate(t),this.diacriticSensitive.evaluate(t),this.locale?this.locale.evaluate(t):null)}eachChild(t){t(this.caseSensitive),t(this.diacriticSensitive),this.locale&&t(this.locale);}outputDefined(){return false}}class vr{constructor(t,e,r,n,i){this.type=Pt,this.number=t,this.locale=e,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i;}static parse(t,e){if(3!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,zt);if(!r)return null;const n=t[2];if("object"!=typeof n||Array.isArray(n))return e.error("NumberFormat options argument must be an object.");let i=null;if(n.locale&&(i=e.parse(n.locale,1,Pt),!i))return null;let s=null;if(n.currency&&(s=e.parse(n.currency,1,Pt),!s))return null;let a=null;if(n["min-fraction-digits"]&&(a=e.parse(n["min-fraction-digits"],1,zt),!a))return null;let o=null;return n["max-fraction-digits"]&&(o=e.parse(n["max-fraction-digits"],1,zt),!o)?null:new vr(r,i,s,a,o)}evaluate(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):undefined,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):undefined,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):undefined}).format(this.number.evaluate(t))}eachChild(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits);}outputDefined(){return false}}class br{constructor(t){this.type=$t,this.sections=t;}static parse(t,e){if(t.length<2)return e.error("Expected at least one argument.");const r=t[1];if(!Array.isArray(r)&&"object"==typeof r)return e.error("First argument must be an image or text section.");const n=[];let i=false;for(let r=1;r<=t.length-1;++r){const s=t[r];if(i&&"object"==typeof s&&!Array.isArray(s)){i=false;let t=null;if(s["font-scale"]&&(t=e.parse(s["font-scale"],1,zt),!t))return null;let r=null;if(s["text-font"]&&(r=e.parse(s["text-font"],1,Rt(Pt)),!r))return null;let a=null;if(s["text-color"]&&(a=e.parse(s["text-color"],1,Bt),!a))return null;const o=n[n.length-1];o.scale=t,o.font=r,o.textColor=a;}else {const s=e.parse(t[r],1,Tt);if(!s)return null;const a=s.type.kind;if("string"!==a&&"value"!==a&&"null"!==a&&"resolvedImage"!==a)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=true,n.push({content:s,scale:null,font:null,textColor:null});}}return new br(n)}evaluate(t){return new xe(this.sections.map((e=>{const r=e.content.evaluate(t);return Ie(r)===Dt?new ge("",r,null,null,null):new ge(ze(r),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null)})))}eachChild(t){for(const e of this.sections)t(e.content),e.scale&&t(e.scale),e.font&&t(e.font),e.textColor&&t(e.textColor);}outputDefined(){return false}}class wr{constructor(t){this.type=Dt,this.input=t;}static parse(t,e){if(2!==t.length)return e.error("Expected two arguments.");const r=e.parse(t[1],1,Pt);return r?new wr(r):e.error("No image name provided.")}evaluate(t){const e=this.input.evaluate(t),r=Se.fromString(e);return r&&t.availableImages&&(r.available=t.availableImages.indexOf(e)>-1),r}eachChild(t){t(this.input);}outputDefined(){return false}}class _r{constructor(t){this.type=zt,this.input=t;}static parse(t,e){if(2!==t.length)return e.error(`Expected 1 argument, but found ${t.length-1} instead.`);const r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error(`Expected argument of type string or array, but found ${jt(r.type)} instead.`):new _r(r):null}evaluate(t){const e=this.input.evaluate(t);if("string"==typeof e)return [...e].length;if(Array.isArray(e))return e.length;throw new be(`Expected value to be of type string or array, but found ${jt(Ie(e))} instead.`)}eachChild(t){t(this.input);}outputDefined(){return false}}const Sr=8192;function Ar(t,e){const r=(180+t[0])/360,n=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,i=Math.pow(2,e.z);return [Math.round(r*i*Sr),Math.round(n*i*Sr)]}function kr(t,e){const r=Math.pow(2,e.z);return [(i=(t[0]/Sr+e.x)/r,360*i-180),(n=(t[1]/Sr+e.y)/r,360/Math.PI*Math.atan(Math.exp((180-360*n)*Math.PI/180))-90)];var n,i;}function Mr(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.min(t[1],e[1]),t[2]=Math.max(t[2],e[0]),t[3]=Math.max(t[3],e[1]);}function Ir(t,e){return !(t[0]<=e[0]||t[2]>=e[2]||t[1]<=e[1]||t[3]>=e[3])}function zr(t,e,r){const n=t[0]-e[0],i=t[1]-e[1],s=t[0]-r[0],a=t[1]-r[1];return n*a-s*i==0&&n*s<=0&&i*a<=0}function Pr(t,e,r,n){return 0!=(i=[n[0]-r[0],n[1]-r[1]])[0]*(s=[e[0]-t[0],e[1]-t[1]])[1]-i[1]*s[0]&&!(!Fr(t,e,r,n)||!Fr(r,n,t,e));var i,s;}function Cr(t,e,r){for(const n of r)for(let r=0;r(i=t)[1]!=(a=o[e+1])[1]>i[1]&&i[0]<(a[0]-s[0])*(i[1]-s[1])/(a[1]-s[1])+s[0]&&(n=!n);}var i,s,a;return n}function Vr(t,e){for(const r of e)if(Br(t,r))return true;return false}function Er(t,e){for(const r of t)if(!Br(r,e))return false;for(let r=0;r0&&o<0||a<0&&o>0}function $r(t,e,r){const n=[];for(let i=0;ir[2]){const e=.5*n;let i=t[0]-r[0]>e?-n:r[0]-t[0]>e?n:0;0===i&&(i=t[0]-r[2]>e?-n:r[2]-t[0]>e?n:0),t[0]+=i;}Mr(e,t);}function Or(t,e,r,n){const i=Math.pow(2,n.z)*Sr,s=[n.x*Sr,n.y*Sr],a=[];for(const n of t)for(const t of n){const n=[t.x+s[0],t.y+s[1]];Dr(n,e,r,i),a.push(n);}return a}function Rr(t,e,r,n){const i=Math.pow(2,n.z)*Sr,s=[n.x*Sr,n.y*Sr],a=[];for(const r of t){const t=[];for(const n of r){const r=[n.x+s[0],n.y+s[1]];Mr(e,r),t.push(r);}a.push(t);}if(e[2]-e[0]<=i/2){(o=e)[0]=o[1]=1/0,o[2]=o[3]=-1/0;for(const t of a)for(const n of t)Dr(n,e,r,i);}var o;return a}class jr{constructor(t,e){this.type=Ct,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'within' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Me(t[1])){const e=t[1];if("FeatureCollection"===e.type){const t=[];for(const r of e.features){const{type:e,coordinates:n}=r.geometry;"Polygon"===e&&t.push(n),"MultiPolygon"===e&&t.push(...n);}if(t.length)return new jr(e,{type:"MultiPolygon",coordinates:t})}else if("Feature"===e.type){const t=e.geometry.type;if("Polygon"===t||"MultiPolygon"===t)return new jr(e,e.geometry)}else if("Polygon"===e.type||"MultiPolygon"===e.type)return new jr(e,e)}return e.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryDollarType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=$r(e.coordinates,n,i),a=Or(t.geometry(),r,n,i);if(!Ir(r,n))return false;for(const t of a)if(!Br(t,s))return false}if("MultiPolygon"===e.type){const s=Lr(e.coordinates,n,i),a=Or(t.geometry(),r,n,i);if(!Ir(r,n))return false;for(const t of a)if(!Vr(t,s))return false}return true}(t,this.geometries);if("LineString"===t.geometryDollarType())return function(t,e){const r=[1/0,1/0,-1/0,-1/0],n=[1/0,1/0,-1/0,-1/0],i=t.canonicalID();if("Polygon"===e.type){const s=$r(e.coordinates,n,i),a=Rr(t.geometry(),r,n,i);if(!Ir(r,n))return false;for(const t of a)if(!Er(t,s))return false}if("MultiPolygon"===e.type){const s=Lr(e.coordinates,n,i),a=Rr(t.geometry(),r,n,i);if(!Ir(r,n))return false;for(const t of a)if(!Tr(t,s))return false}return true}(t,this.geometries)}return false}eachChild(){}outputDefined(){return true}}let Nr=class{constructor(t=[],e=((t,e)=>te?1:0)){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}};const Ur=1/298.257223563,qr=Ur*(2-Ur),Gr=Math.PI/180;class Zr{constructor(t){const e=6378.137*Gr*1e3,r=Math.cos(t*Gr),n=1/(1-qr*(1-r*r)),i=Math.sqrt(n);this.kx=e*i*r,this.ky=e*i*n*(1-qr);}distance(t,e){const r=this.wrap(t[0]-e[0])*this.kx,n=(t[1]-e[1])*this.ky;return Math.sqrt(r*r+n*n)}pointOnLine(t,e){let r,n,i,s,a=1/0;for(let o=0;o1?(l=t[o+1][0],u=t[o+1][1]):p>0&&(l+=c/this.kx*p,u+=h/this.ky*p)),c=this.wrap(e[0]-l)*this.kx,h=(e[1]-u)*this.ky;const f=c*c+h*h;f180;)t-=360;return t}}function Xr(t,e){return e[0]-t[0]}function Kr(t){return t[1]-t[0]+1}function Hr(t,e){return t[1]>=t[0]&&t[1]t[1])return [null,null];const r=Kr(t);if(e){if(2===r)return [t,null];const e=Math.floor(r/2);return [[t[0],t[0]+e],[t[0]+e,t[1]]]}if(1===r)return [t,null];const n=Math.floor(r/2)-1;return [[t[0],t[0]+n],[t[0]+n+1,t[1]]]}function Jr(t,e){if(!Hr(e,t.length))return [1/0,1/0,-1/0,-1/0];const r=[1/0,1/0,-1/0,-1/0];for(let n=e[0];n<=e[1];++n)Mr(r,t[n]);return r}function Wr(t){const e=[1/0,1/0,-1/0,-1/0];for(const r of t)for(const t of r)Mr(e,t);return e}function Qr(t){return t[0]!==-1/0&&t[1]!==-1/0&&t[2]!==1/0&&t[3]!==1/0}function tn(t,e,r){if(!Qr(t)||!Qr(e))return NaN;let n=0,i=0;return t[2]e[2]&&(n=t[0]-e[2]),t[1]>e[3]&&(i=t[1]-e[3]),t[3]=n)return n;if(Ir(i,s)){if(ln(t,e))return 0}else if(ln(e,t))return 0;let a=1/0;for(const n of t)for(let t=0,i=n.length,s=i-1;t0;){const i=a.pop();if(i[0]>=s)continue;const l=i[1],u=e?50:100;if(Kr(l)<=u){if(!Hr(l,t.length))return NaN;if(e){const e=on(t,l,r,n);if(isNaN(e)||0===e)return e;s=Math.min(s,e);}else for(let e=l[0];e<=l[1];++e){const i=an(t[e],r,n);if(s=Math.min(s,i),0===s)return 0}}else {const r=Yr(l,e);cn(a,s,n,t,o,r[0]),cn(a,s,n,t,o,r[1]);}}return s}function fn(t,e,r,n,i,s=1/0){let a=Math.min(s,i.distance(t[0],r[0]));if(0===a)return a;const o=new Nr([[0,[0,t.length-1],[0,r.length-1]]],Xr);for(;o.length>0;){const s=o.pop();if(s[0]>=a)continue;const l=s[1],u=s[2],c=e?50:100,h=n?50:100;if(Kr(l)<=c&&Kr(u)<=h){if(!Hr(l,t.length)&&Hr(u,r.length))return NaN;let s;if(e&&n)s=nn(t,l,r,u,i),a=Math.min(a,s);else if(e&&!n){const e=t.slice(l[0],l[1]+1);for(let t=u[0];t<=u[1];++t)if(s=en(r[t],e,i),a=Math.min(a,s),0===a)return a}else if(!e&&n){const e=r.slice(u[0],u[1]+1);for(let r=l[0];r<=l[1];++r)if(s=en(t[r],e,i),a=Math.min(a,s),0===a)return a}else s=sn(t,l,r,u,i),a=Math.min(a,s);}else {const s=Yr(l,e),c=Yr(u,n);hn(o,a,i,t,r,s[0],c[0]),hn(o,a,i,t,r,s[0],c[1]),hn(o,a,i,t,r,s[1],c[0]),hn(o,a,i,t,r,s[1],c[1]);}}return a}function dn(t){return "MultiPolygon"===t.type?t.coordinates.map((t=>({type:"Polygon",coordinates:t}))):"MultiLineString"===t.type?t.coordinates.map((t=>({type:"LineString",coordinates:t}))):"MultiPoint"===t.type?t.coordinates.map((t=>({type:"Point",coordinates:t}))):[t]}class yn{constructor(t,e){this.type=zt,this.geojson=t,this.geometries=e;}static parse(t,e){if(2!==t.length)return e.error(`'distance' expression requires exactly one argument, but found ${t.length-1} instead.`);if(Me(t[1])){const e=t[1];if("FeatureCollection"===e.type)return new yn(e,e.features.map((t=>dn(t.geometry))).flat());if("Feature"===e.type)return new yn(e,dn(e.geometry));if("type"in e&&"coordinates"in e)return new yn(e,dn(e))}return e.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(t){if(null!=t.geometry()&&null!=t.canonicalID()){if("Point"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>kr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new Zr(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case"Point":s=Math.min(s,fn(n,false,[t.coordinates],false,i,s));break;case"LineString":s=Math.min(s,fn(n,false,t.coordinates,true,i,s));break;case"Polygon":s=Math.min(s,pn(n,false,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("LineString"===t.geometryType())return function(t,e){const r=t.geometry(),n=r.flat().map((e=>kr([e.x,e.y],t.canonical)));if(0===r.length)return NaN;const i=new Zr(n[0][1]);let s=1/0;for(const t of e){switch(t.type){case"Point":s=Math.min(s,fn(n,true,[t.coordinates],false,i,s));break;case"LineString":s=Math.min(s,fn(n,true,t.coordinates,true,i,s));break;case"Polygon":s=Math.min(s,pn(n,true,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries);if("Polygon"===t.geometryType())return function(t,e){const r=t.geometry();if(0===r.length||0===r[0].length)return NaN;const n=Le(r,0).map((e=>e.map((e=>e.map((e=>kr([e.x,e.y],t.canonical))))))),i=new Zr(n[0][0][0][1]);let s=1/0;for(const t of e)for(const e of n){switch(t.type){case"Point":s=Math.min(s,pn([t.coordinates],false,e,i,s));break;case"LineString":s=Math.min(s,pn(t.coordinates,true,e,i,s));break;case"Polygon":s=Math.min(s,un(e,t.coordinates,i,s));}if(0===s)return s}return s}(t,this.geometries)}return NaN}eachChild(){}outputDefined(){return true}}const mn={"==":pr,"!=":fr,">":yr,"<":dr,">=":gr,"<=":mr,array:Be,at:Ze,boolean:Be,case:Ye,coalesce:lr,collator:xr,format:br,image:wr,in:Xe,"index-of":Ke,interpolate:sr,"interpolate-hcl":sr,"interpolate-lab":sr,length:_r,let:qe,literal:Pe,match:He,number:Be,"number-format":vr,object:Be,slice:Je,step:Qe,string:Be,"to-boolean":Ee,"to-color":Ee,"to-number":Ee,"to-string":Ee,var:Ge,within:jr,distance:yn};class gn{constructor(t,e,r,n){this.name=t,this.type=e,this._evaluate=r,this.args=n;}evaluate(t){return this._evaluate(t,this.args)}eachChild(t){this.args.forEach(t);}outputDefined(){return false}static parse(t,e){const r=t[0],n=gn.definitions[r];if(!n)return e.error(`Unknown expression "${r}". If you wanted a literal array, use ["literal", [...]].`,0);const i=Array.isArray(n)?n[0]:n.type,s=Array.isArray(n)?[[n[1],n[2]]]:n.overloads,a=s.filter((([e])=>!Array.isArray(e)||e.length===t.length-1));let o=null;for(const[n,s]of a){o=new Ue(e.registry,_n,e.path,null,e.scope);const a=[];let l=false;for(let e=1;e{return e=t,Array.isArray(e)?`(${e.map(jt).join(", ")})`:`(${jt(e.type)}...)`;var e;})).join(" | "),n=[];for(let r=1;r{r=e?r&&_n(t):r&&t instanceof Pe;})),!!r&&Sn(t)&&kn(t,["zoom","heatmap-density","line-progress","accumulated","is-supported-script"])}function Sn(t){if(t instanceof gn){if("get"===t.name&&1===t.args.length)return false;if("feature-state"===t.name)return false;if("has"===t.name&&1===t.args.length)return false;if("properties"===t.name||"geometry-type"===t.name||"id"===t.name)return false;if(/^filter-/.test(t.name))return false}if(t instanceof jr)return false;if(t instanceof yn)return false;let e=true;return t.eachChild((t=>{e&&!Sn(t)&&(e=false);})),e}function An(t){if(t instanceof gn&&"feature-state"===t.name)return false;let e=true;return t.eachChild((t=>{e&&!An(t)&&(e=false);})),e}function kn(t,e){if(t instanceof gn&&e.indexOf(t.name)>=0)return false;let r=true;return t.eachChild((t=>{r&&!kn(t,e)&&(r=false);})),r}function Mn(t){return {result:"success",value:t}}function In(t){return {result:"error",value:t}}function zn(t){return "data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function Pn(t){return !!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function Cn(t){return !!t.expression&&t.expression.interpolated}function Bn(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function Vn(t){return "object"==typeof t&&null!==t&&!Array.isArray(t)}function En(t){return t}function Tn(t,e){const r="color"===e.type,n=t.stops&&"object"==typeof t.stops[0][0],i=n||!(n||undefined!==t.property),s=t.type||(Cn(e)?"exponential":"interval");if(r||"padding"===e.type){const n=r?ye.parse:ve.parse;(t=At({},t)).stops&&(t.stops=t.stops.map((t=>[t[0],n(t[1])]))),t.default=n(t.default?t.default:e.default);}if(t.colorSpace&&"rgb"!==(a=t.colorSpace)&&"hcl"!==a&&"lab"!==a)throw new Error(`Unknown color space: "${t.colorSpace}"`);var a;let o,l,u;if("exponential"===s)o=Dn;else if("interval"===s)o=Ln;else if("categorical"===s){o=$n,l=Object.create(null);for(const e of t.stops)l[e[0]]=e[1];u=typeof t.stops[0][0];}else {if("identity"!==s)throw new Error(`Unknown function type "${s}"`);o=On;}if(n){const r={},n=[];for(let e=0;et[0])),evaluate:({zoom:r},n)=>Dn({stops:i,base:t.base},e,r).evaluate(r,n)}}if(i){const r="exponential"===s?{name:"exponential",base:undefined!==t.base?t.base:1}:null;return {kind:"camera",interpolationType:r,interpolationFactor:sr.interpolationFactor.bind(undefined,r),zoomStops:t.stops.map((t=>t[0])),evaluate:({zoom:r})=>o(t,e,r,l,u)}}return {kind:"source",evaluate(r,n){const i=n&&n.properties?n.properties[t.property]:undefined;return undefined===i?Fn(t.default,e.default):o(t,e,i,l,u)}}}function Fn(t,e,r){return undefined!==t?t:undefined!==e?e:undefined!==r?r:undefined}function $n(t,e,r,n,i){return Fn(typeof r===i?n[r]:undefined,t.default,e.default)}function Ln(t,e,r){if("number"!==Bn(r))return Fn(t.default,e.default);const n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];const i=We(t.stops.map((t=>t[0])),r);return t.stops[i][1]}function Dn(t,e,r){const n=undefined!==t.base?t.base:1;if("number"!==Bn(r))return Fn(t.default,e.default);const i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];const s=We(t.stops.map((t=>t[0])),r),a=function(t,e,r,n){const i=n-r,s=t-r;return 0===i?0:1===e?s/i:(Math.pow(e,s)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[s][0],t.stops[s+1][0]),o=t.stops[s][1],l=t.stops[s+1][1],u=or[e.type]||En;return "function"==typeof o.evaluate?{evaluate(...e){const r=o.evaluate.apply(undefined,e),n=l.evaluate.apply(undefined,e);if(undefined!==r&&undefined!==n)return u(r,n,a,t.colorSpace)}}:u(o,l,a,t.colorSpace)}function On(t,e,r){switch(e.type){case"color":r=ye.parse(r);break;case"formatted":r=xe.fromString(r.toString());break;case"resolvedImage":r=Se.fromString(r.toString());break;case"padding":r=ve.parse(r);break;default:Bn(r)===e.type||"enum"===e.type&&e.values[r]||(r=undefined);}return Fn(r,t.default,e.default)}gn.register(mn,{error:[{kind:"error"},[Pt],(t,[e])=>{throw new be(e.evaluate(t))}],typeof:[Pt,[Tt],(t,[e])=>jt(Ie(e.evaluate(t)))],"to-rgba":[Rt(zt,4),[Bt],(t,[e])=>{const[r,n,i,s]=e.evaluate(t).rgb;return [255*r,255*n,255*i,s]}],rgb:[Bt,[zt,zt,zt],xn],rgba:[Bt,[zt,zt,zt,zt],xn],has:{type:Ct,overloads:[[[Pt],(t,[e])=>vn(e.evaluate(t),t.properties())],[[Pt,Et],(t,[e,r])=>vn(e.evaluate(t),r.evaluate(t))]]},get:{type:Tt,overloads:[[[Pt],(t,[e])=>bn(e.evaluate(t),t.properties())],[[Pt,Et],(t,[e,r])=>bn(e.evaluate(t),r.evaluate(t))]]},"feature-state":[Tt,[Pt],(t,[e])=>bn(e.evaluate(t),t.featureState||{})],properties:[Et,[],t=>t.properties()],"geometry-type":[Pt,[],t=>t.geometryType()],id:[Tt,[],t=>t.id()],zoom:[zt,[],t=>t.globals.zoom],"heatmap-density":[zt,[],t=>t.globals.heatmapDensity||0],"line-progress":[zt,[],t=>t.globals.lineProgress||0],accumulated:[Tt,[],t=>undefined===t.globals.accumulated?null:t.globals.accumulated],"+":[zt,wn(zt),(t,e)=>{let r=0;for(const n of e)r+=n.evaluate(t);return r}],"*":[zt,wn(zt),(t,e)=>{let r=1;for(const n of e)r*=n.evaluate(t);return r}],"-":{type:zt,overloads:[[[zt,zt],(t,[e,r])=>e.evaluate(t)-r.evaluate(t)],[[zt],(t,[e])=>-e.evaluate(t)]]},"/":[zt,[zt,zt],(t,[e,r])=>e.evaluate(t)/r.evaluate(t)],"%":[zt,[zt,zt],(t,[e,r])=>e.evaluate(t)%r.evaluate(t)],ln2:[zt,[],()=>Math.LN2],pi:[zt,[],()=>Math.PI],e:[zt,[],()=>Math.E],"^":[zt,[zt,zt],(t,[e,r])=>Math.pow(e.evaluate(t),r.evaluate(t))],sqrt:[zt,[zt],(t,[e])=>Math.sqrt(e.evaluate(t))],log10:[zt,[zt],(t,[e])=>Math.log(e.evaluate(t))/Math.LN10],ln:[zt,[zt],(t,[e])=>Math.log(e.evaluate(t))],log2:[zt,[zt],(t,[e])=>Math.log(e.evaluate(t))/Math.LN2],sin:[zt,[zt],(t,[e])=>Math.sin(e.evaluate(t))],cos:[zt,[zt],(t,[e])=>Math.cos(e.evaluate(t))],tan:[zt,[zt],(t,[e])=>Math.tan(e.evaluate(t))],asin:[zt,[zt],(t,[e])=>Math.asin(e.evaluate(t))],acos:[zt,[zt],(t,[e])=>Math.acos(e.evaluate(t))],atan:[zt,[zt],(t,[e])=>Math.atan(e.evaluate(t))],min:[zt,wn(zt),(t,e)=>Math.min(...e.map((e=>e.evaluate(t))))],max:[zt,wn(zt),(t,e)=>Math.max(...e.map((e=>e.evaluate(t))))],abs:[zt,[zt],(t,[e])=>Math.abs(e.evaluate(t))],round:[zt,[zt],(t,[e])=>{const r=e.evaluate(t);return r<0?-Math.round(-r):Math.round(r)}],floor:[zt,[zt],(t,[e])=>Math.floor(e.evaluate(t))],ceil:[zt,[zt],(t,[e])=>Math.ceil(e.evaluate(t))],"filter-==":[Ct,[Pt,Tt],(t,[e,r])=>t.properties()[e.value]===r.value],"filter-id-==":[Ct,[Tt],(t,[e])=>t.id()===e.value],"filter-type-==":[Ct,[Pt],(t,[e])=>t.geometryDollarType()===e.value],"filter-<":[Ct,[Pt,Tt],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n{const r=t.id(),n=e.value;return typeof r==typeof n&&r":[Ct,[Pt,Tt],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>i}],"filter-id->":[Ct,[Tt],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>n}],"filter-<=":[Ct,[Pt,Tt],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n<=i}],"filter-id-<=":[Ct,[Tt],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r<=n}],"filter->=":[Ct,[Pt,Tt],(t,[e,r])=>{const n=t.properties()[e.value],i=r.value;return typeof n==typeof i&&n>=i}],"filter-id->=":[Ct,[Tt],(t,[e])=>{const r=t.id(),n=e.value;return typeof r==typeof n&&r>=n}],"filter-has":[Ct,[Tt],(t,[e])=>e.value in t.properties()],"filter-has-id":[Ct,[],t=>null!==t.id()&&undefined!==t.id()],"filter-type-in":[Ct,[Rt(Pt)],(t,[e])=>e.value.indexOf(t.geometryDollarType())>=0],"filter-id-in":[Ct,[Rt(Tt)],(t,[e])=>e.value.indexOf(t.id())>=0],"filter-in-small":[Ct,[Pt,Rt(Tt)],(t,[e,r])=>r.value.indexOf(t.properties()[e.value])>=0],"filter-in-large":[Ct,[Pt,Rt(Tt)],(t,[e,r])=>function(t,e,r,n){for(;r<=n;){const i=r+n>>1;if(e[i]===t)return true;e[i]>t?n=i-1:r=i+1;}return false}(t.properties()[e.value],r.value,0,r.value.length-1)],all:{type:Ct,overloads:[[[Ct,Ct],(t,[e,r])=>e.evaluate(t)&&r.evaluate(t)],[wn(Ct),(t,e)=>{for(const r of e)if(!r.evaluate(t))return false;return true}]]},any:{type:Ct,overloads:[[[Ct,Ct],(t,[e,r])=>e.evaluate(t)||r.evaluate(t)],[wn(Ct),(t,e)=>{for(const r of e)if(r.evaluate(t))return true;return false}]]},"!":[Ct,[Ct],(t,[e])=>!e.evaluate(t)],"is-supported-script":[Ct,[Pt],(t,[e])=>{const r=t.globals&&t.globals.isSupportedScript;return !r||r(e.evaluate(t))}],upcase:[Pt,[Pt],(t,[e])=>e.evaluate(t).toUpperCase()],downcase:[Pt,[Pt],(t,[e])=>e.evaluate(t).toLowerCase()],concat:[Pt,wn(Tt),(t,e)=>e.map((e=>ze(e.evaluate(t)))).join("")],"resolved-locale":[Pt,[Ft],(t,[e])=>e.evaluate(t).resolvedLocale()]});class Rn{constructor(t,e){var r;this.expression=t,this._warningHistory={},this._evaluator=new Ne,this._defaultValue=e?"color"===(r=e).type&&Vn(r.default)?new ye(0,0,0,0):"color"===r.type?ye.parse(r.default)||null:"padding"===r.type?ve.parse(r.default)||null:"variableAnchorOffsetCollection"===r.type?_e.parse(r.default)||null:"projectionDefinition"===r.type?Ae.parse(r.default)||null:undefined===r.default?null:r.default:null,this._enumValues=e&&"enum"===e.type?e.values:null;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=r,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s,this.expression.evaluate(this._evaluator)}evaluate(t,e,r,n,i,s){this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=s||null;try{const t=this.expression.evaluate(this._evaluator);if(null==t||"number"==typeof t&&t!=t)return this._defaultValue;if(this._enumValues&&!(t in this._enumValues))throw new be(`Expected value to be one of ${Object.keys(this._enumValues).map((t=>JSON.stringify(t))).join(", ")}, but found ${JSON.stringify(t)} instead.`);return t}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=true,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}}}function jn(t){return Array.isArray(t)&&t.length>0&&"string"==typeof t[0]&&t[0]in mn}function Nn(t,e){const r=new Ue(mn,_n,[],e?function(t){const e={color:Bt,string:Pt,number:zt,enum:Pt,boolean:Ct,formatted:$t,padding:Lt,projectionDefinition:Vt,resolvedImage:Dt,variableAnchorOffsetCollection:Ot};return "array"===t.type?Rt(e[t.value]||Tt,t.length):e[t.type]}(e):undefined),n=r.parse(t,undefined,undefined,undefined,e&&"string"===e.type?{typeAnnotation:"coerce"}:undefined);return n?Mn(new Rn(n,e)):In(r.errors)}class Un{constructor(t,e){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!An(e.expression);}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._styleExpression.evaluate(t,e,r,n,i,s)}}class qn{constructor(t,e,r,n){this.kind=t,this.zoomStops=r,this._styleExpression=e,this.isStateDependent="camera"!==t&&!An(e.expression),this.interpolationType=n;}evaluateWithoutErrorHandling(t,e,r,n,i,s){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,s)}evaluate(t,e,r,n,i,s){return this._styleExpression.evaluate(t,e,r,n,i,s)}interpolationFactor(t,e,r){return this.interpolationType?sr.interpolationFactor(this.interpolationType,t,e,r):0}}function Gn(t,e){const r=Nn(t,e);if("error"===r.result)return r;const n=r.value.expression,i=Sn(n);if(!i&&!zn(e))return In([new kt("","data expressions not supported")]);const s=kn(n,["zoom"]);if(!s&&!Pn(e))return In([new kt("","zoom expressions not supported")]);const a=Xn(n);return a||s?a instanceof kt?In([a]):a instanceof sr&&!Cn(e)?In([new kt("",'"interpolate" expressions cannot be used with this property')]):Mn(a?new qn(i?"camera":"composite",r.value,a.labels,a instanceof sr?a.interpolation:undefined):new Un(i?"constant":"source",r.value)):In([new kt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}class Zn{constructor(t,e){this._parameters=t,this._specification=e,At(this,Tn(this._parameters,this._specification));}static deserialize(t){return new Zn(t._parameters,t._specification)}static serialize(t){return {_parameters:t._parameters,_specification:t._specification}}}function Xn(t){let e=null;if(t instanceof qe)e=Xn(t.result);else if(t instanceof lr){for(const r of t.args)if(e=Xn(r),e)break}else (t instanceof Qe||t instanceof sr)&&t.input instanceof gn&&"zoom"===t.input.name&&(e=t);return e instanceof kt||t.eachChild((t=>{const r=Xn(t);r instanceof kt?e=r:!e&&r?e=new kt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):e&&r&&e!==r&&(e=new kt("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));})),e}function Kn(t){if(true===t||false===t)return true;if(!Array.isArray(t)||0===t.length)return false;switch(t[0]){case"has":return t.length>=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case"!in":case"!has":case"none":return false;case"==":case"!=":case">":case">=":case"<":case"<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case"any":case"all":for(const e of t.slice(1))if(!Kn(e)&&"boolean"!=typeof e)return false;return true;default:return true}}const Hn={type:"boolean",default:false,transition:false,"property-type":"data-driven",expression:{interpolated:false,parameters:["zoom","feature"]}};function Yn(t){if(null==t)return {filter:()=>true,needGeometry:false};Kn(t)||(t=Qn(t));const e=Nn(t,Hn);if("error"===e.result)throw new Error(e.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return {filter:(t,r,n)=>e.value.evaluate(t,r,{},n),needGeometry:Wn(t)}}function Jn(t,e){return te?1:0}function Wn(t){if(!Array.isArray(t))return false;if("within"===t[0]||"distance"===t[0]||"geometry-type"===t[0])return true;for(let e=1;e"===e||"<="===e||">="===e?ti(t[1],t[2],e):"any"===e?(r=t.slice(1),["any"].concat(r.map(Qn))):"all"===e?["all"].concat(t.slice(1).map(Qn)):"none"===e?["all"].concat(t.slice(1).map(Qn).map(ni)):"in"===e?ei(t[1],t.slice(2)):"!in"===e?ni(ei(t[1],t.slice(2))):"has"===e?ri(t[1]):"!has"!==e||ni(ri(t[1]));var r;}function ti(t,e,r){switch(t){case"$type":return [`filter-type-${r}`,e];case"$id":return [`filter-id-${r}`,e];default:return [`filter-${r}`,t,e]}}function ei(t,e){if(0===e.length)return false;switch(t){case"$type":return ["filter-type-in",["literal",e]];case"$id":return ["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((t=>typeof t!=typeof e[0]))?["filter-in-large",t,["literal",e.sort(Jn)]]:["filter-in-small",t,["literal",e]]}}function ri(t){switch(t){case"$type":return true;case"$id":return ["filter-has-id"];default:return ["filter-has",t]}}function ni(t){return ["!",t]}function ii(t){const e=typeof t;if("number"===e||"boolean"===e||"string"===e||null==t)return JSON.stringify(t);if(Array.isArray(t)){let e="[";for(const r of t)e+=`${ii(r)},`;return `${e}]`}const r=Object.keys(t).sort();let n="{";for(let e=0;en.maximum?[new St(e,r,`${r} is greater than the maximum value ${n.maximum}`)]:[]}function pi(t){const e=t.valueSpec,r=oi(t.value.type);let n,i,s,a={};const o="categorical"!==r&&undefined===t.value.property,l=!o,u="array"===Bn(t.value.stops)&&"array"===Bn(t.value.stops[0])&&"object"===Bn(t.value.stops[0][0]),c=ui({key:t.key,value:t.value,valueSpec:t.styleSpec.function,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===r)return [new St(t.key,t.value,'identity function may not have a "stops" property')];let e=[];const n=t.value;return e=e.concat(ci({key:t.key,value:n,valueSpec:t.valueSpec,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:h})),"array"===Bn(n)&&0===n.length&&e.push(new St(t.key,n,"array must have at least one stop")),e},default:function(t){return t.validateSpec({key:t.key,value:t.value,valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec})}}});return "identity"===r&&o&&c.push(new St(t.key,t.value,'missing required property "property"')),"identity"===r||t.value.stops||c.push(new St(t.key,t.value,'missing required property "stops"')),"exponential"===r&&t.valueSpec.expression&&!Cn(t.valueSpec)&&c.push(new St(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(l&&!zn(t.valueSpec)?c.push(new St(t.key,t.value,"property functions not supported")):o&&!Pn(t.valueSpec)&&c.push(new St(t.key,t.value,"zoom functions not supported"))),"categorical"!==r&&!u||undefined!==t.value.property||c.push(new St(t.key,t.value,'"property" property is required')),c;function h(t){let r=[];const n=t.value,o=t.key;if("array"!==Bn(n))return [new St(o,n,`array expected, ${Bn(n)} found`)];if(2!==n.length)return [new St(o,n,`array length 2 expected, length ${n.length} found`)];if(u){if("object"!==Bn(n[0]))return [new St(o,n,`object expected, ${Bn(n[0])} found`)];if(undefined===n[0].zoom)return [new St(o,n,"object stop key must have zoom")];if(undefined===n[0].value)return [new St(o,n,"object stop key must have value")];if(s&&s>oi(n[0].zoom))return [new St(o,n[0].zoom,"stop zoom values must appear in ascending order")];oi(n[0].zoom)!==s&&(s=oi(n[0].zoom),i=undefined,a={}),r=r.concat(ui({key:`${o}[0]`,value:n[0],valueSpec:{zoom:{}},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:hi,value:p}}));}else r=r.concat(p({key:`${o}[0]`,value:n[0],valueSpec:{},validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec},n));return jn(li(n[1]))?r.concat([new St(`${o}[1]`,n[1],"expressions are not allowed in function stops.")]):r.concat(t.validateSpec({key:`${o}[1]`,value:n[1],valueSpec:e,validateSpec:t.validateSpec,style:t.style,styleSpec:t.styleSpec}))}function p(t,s){const o=Bn(t.value),l=oi(t.value),u=null!==t.value?t.value:s;if(n){if(o!==n)return [new St(t.key,u,`${o} stop domain type must match previous stop domain type ${n}`)]}else n=o;if("number"!==o&&"string"!==o&&"boolean"!==o)return [new St(t.key,u,"stop domain value must be a number, string, or boolean")];if("number"!==o&&"categorical"!==r){let n=`number expected, ${o} found`;return zn(e)&&undefined===r&&(n+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new St(t.key,u,n)]}return "categorical"!==r||"number"!==o||isFinite(l)&&Math.floor(l)===l?"categorical"!==r&&"number"===o&&undefined!==i&&lnew St(`${t.key}${e.key}`,t.value,e.message)));const r=e.value.expression||e.value._styleExpression.expression;if("property"===t.expressionContext&&"text-font"===t.propertyKey&&!r.outputDefined())return [new St(t.key,t.value,`Invalid data expression for "${t.propertyKey}". Output values must be contained as literals within the expression.`)];if("property"===t.expressionContext&&"layout"===t.propertyType&&!An(r))return [new St(t.key,t.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===t.expressionContext&&!An(r))return [new St(t.key,t.value,'"feature-state" data expressions are not supported with filters.')];if(t.expressionContext&&0===t.expressionContext.indexOf("cluster")){if(!kn(r,["zoom","feature-state"]))return [new St(t.key,t.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===t.expressionContext&&!Sn(r))return [new St(t.key,t.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return []}function di(t){const e=t.key,r=t.value,n=t.valueSpec,i=[];return Array.isArray(n.values)?-1===n.values.indexOf(oi(r))&&i.push(new St(e,r,`expected one of [${n.values.join(", ")}], ${JSON.stringify(r)} found`)):-1===Object.keys(n.values).indexOf(oi(r))&&i.push(new St(e,r,`expected one of [${Object.keys(n.values).join(", ")}], ${JSON.stringify(r)} found`)),i}function yi(t){return Kn(li(t.value))?fi(At({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):mi(t)}function mi(t){const e=t.value,r=t.key;if("array"!==Bn(e))return [new St(r,e,`array expected, ${Bn(e)} found`)];const n=t.styleSpec;let i,s=[];if(e.length<1)return [new St(r,e,"filter array must have at least 1 element")];switch(s=s.concat(di({key:`${r}[0]`,value:e[0],valueSpec:n.filter_operator,style:t.style,styleSpec:t.styleSpec})),oi(e[0])){case"<":case"<=":case">":case">=":e.length>=2&&"$type"===oi(e[1])&&s.push(new St(r,e,`"$type" cannot be use with operator "${e[0]}"`));case"==":case"!=":3!==e.length&&s.push(new St(r,e,`filter array for operator "${e[0]}" must have 3 elements`));case"in":case"!in":e.length>=2&&(i=Bn(e[1]),"string"!==i&&s.push(new St(`${r}[1]`,e[1],`string expected, ${i} found`)));for(let a=2;a{t in r&&e.push(new St(n,r[t],`"${t}" is prohibited for ref layers`));})),i.layers.forEach((e=>{oi(e.id)===o&&(t=e);})),t?t.ref?e.push(new St(n,r.ref,"ref cannot reference another ref layer")):a=oi(t.type):e.push(new St(n,r.ref,`ref layer "${o}" not found`));}else if("background"!==a)if(r.source){const t=i.sources&&i.sources[r.source],s=t&&oi(t.type);t?"vector"===s&&"raster"===a?e.push(new St(n,r.source,`layer "${r.id}" requires a raster source`)):"raster-dem"!==s&&"hillshade"===a?e.push(new St(n,r.source,`layer "${r.id}" requires a raster-dem source`)):"raster"===s&&"raster"!==a?e.push(new St(n,r.source,`layer "${r.id}" requires a vector source`)):"vector"!==s||r["source-layer"]?"raster-dem"===s&&"hillshade"!==a?e.push(new St(n,r.source,"raster-dem source can only be used with layer type 'hillshade'.")):"line"!==a||!r.paint||!r.paint["line-gradient"]||"geojson"===s&&t.lineMetrics||e.push(new St(n,r,`layer "${r.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):e.push(new St(n,r,`layer "${r.id}" must specify a "source-layer"`)):e.push(new St(n,r.source,`source "${r.source}" not found`));}else e.push(new St(n,r,'missing required property "source"'));return e=e.concat(ui({key:n,value:r,valueSpec:s.layer,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":()=>[],type:()=>t.validateSpec({key:`${n}.type`,value:r.type,valueSpec:s.layer.type,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,object:r,objectKey:"type"}),filter:yi,layout:t=>ui({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>vi(At({layerType:a},t))}}),paint:t=>ui({layer:r,key:t.key,value:t.value,style:t.style,styleSpec:t.styleSpec,validateSpec:t.validateSpec,objectElementValidators:{"*":t=>xi(At({layerType:a},t))}})}})),e}function wi(t){const e=t.value,r=t.key,n=Bn(e);return "string"!==n?[new St(r,e,`string expected, ${n} found`)]:[]}const _i={promoteId:function({key:t,value:e}){if("string"===Bn(e))return wi({key:t,value:e});{const r=[];for(const n in e)r.push(...wi({key:`${t}.${n}`,value:e[n]}));return r}}};function Si(t){const e=t.value,r=t.key,n=t.styleSpec,i=t.style,s=t.validateSpec;if(!e.type)return [new St(r,e,'"type" is required')];const a=oi(e.type);let o;switch(a){case"vector":case"raster":return o=ui({key:r,value:e,valueSpec:n[`source_${a.replace("-","_")}`],style:t.style,styleSpec:n,objectElementValidators:_i,validateSpec:s}),o;case"raster-dem":return o=function(t){var e;const r=null!==(e=t.sourceName)&&undefined!==e?e:"",n=t.value,i=t.styleSpec,s=i.source_raster_dem,a=t.style;let o=[];const l=Bn(n);if(undefined===n)return o;if("object"!==l)return o.push(new St("source_raster_dem",n,`object expected, ${l} found`)),o;const u="custom"===oi(n.encoding),c=["redFactor","greenFactor","blueFactor","baseShift"],h=t.value.encoding?`"${t.value.encoding}"`:"Default";for(const e in n)!u&&c.includes(e)?o.push(new St(e,n[e],`In "${r}": "${e}" is only valid when "encoding" is set to "custom". ${h} encoding found`)):s[e]?o=o.concat(t.validateSpec({key:e,value:n[e],valueSpec:s[e],validateSpec:t.validateSpec,style:a,styleSpec:i})):o.push(new St(e,n[e],`unknown property "${e}"`));return o}({sourceName:r,value:e,style:t.style,styleSpec:n,validateSpec:s}),o;case"geojson":if(o=ui({key:r,value:e,valueSpec:n.source_geojson,style:i,styleSpec:n,validateSpec:s,objectElementValidators:_i}),e.cluster)for(const t in e.clusterProperties){const[n,i]=e.clusterProperties[t],a="string"==typeof n?[n,["accumulated"],["get",t]]:n;o.push(...fi({key:`${r}.${t}.map`,value:i,validateSpec:s,expressionContext:"cluster-map"})),o.push(...fi({key:`${r}.${t}.reduce`,value:a,validateSpec:s,expressionContext:"cluster-reduce"}));}return o;case"video":return ui({key:r,value:e,valueSpec:n.source_video,style:i,validateSpec:s,styleSpec:n});case"image":return ui({key:r,value:e,valueSpec:n.source_image,style:i,validateSpec:s,styleSpec:n});case"canvas":return [new St(r,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return di({key:`${r}.type`,value:e.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]},style:i,validateSpec:s,styleSpec:n})}}function Ai(t){const e=t.value,r=t.styleSpec,n=r.light,i=t.style;let s=[];const a=Bn(e);if(undefined===e)return s;if("object"!==a)return s=s.concat([new St("light",e,`object expected, ${a} found`)]),s;for(const a in e){const o=a.match(/^(.*)-transition$/);s=s.concat(o&&n[o[1]]&&n[o[1]].transition?t.validateSpec({key:a,value:e[a],valueSpec:r.transition,validateSpec:t.validateSpec,style:i,styleSpec:r}):n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new St(a,e[a],`unknown property "${a}"`)]);}return s}function ki(t){const e=t.value,r=t.styleSpec,n=r.sky,i=t.style,s=Bn(e);if(undefined===e)return [];if("object"!==s)return [new St("sky",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new St(s,e[s],`unknown property "${s}"`)]);return a}function Mi(t){const e=t.value,r=t.styleSpec,n=r.terrain,i=t.style;let s=[];const a=Bn(e);if(undefined===e)return s;if("object"!==a)return s=s.concat([new St("terrain",e,`object expected, ${a} found`)]),s;for(const a in e)s=s.concat(n[a]?t.validateSpec({key:a,value:e[a],valueSpec:n[a],validateSpec:t.validateSpec,style:i,styleSpec:r}):[new St(a,e[a],`unknown property "${a}"`)]);return s}function Ii(t){let e=[];const r=t.value,n=t.key;if(Array.isArray(r)){const i=[],s=[];for(const a in r)r[a].id&&i.includes(r[a].id)&&e.push(new St(n,r,`all the sprites' ids must be unique, but ${r[a].id} is duplicated`)),i.push(r[a].id),r[a].url&&s.includes(r[a].url)&&e.push(new St(n,r,`all the sprites' URLs must be unique, but ${r[a].url} is duplicated`)),s.push(r[a].url),e=e.concat(ui({key:`${n}[${a}]`,value:r[a],valueSpec:{id:{type:"string",required:true},url:{type:"string",required:true}},validateSpec:t.validateSpec}));return e}return wi({key:n,value:r})}const zi={"*":()=>[],array:ci,boolean:function(t){const e=t.value,r=t.key,n=Bn(e);return "boolean"!==n?[new St(r,e,`boolean expected, ${n} found`)]:[]},number:hi,color:function(t){const e=t.key,r=t.value,n=Bn(r);return "string"!==n?[new St(e,r,`color expected, ${n} found`)]:ye.parse(String(r))?[]:[new St(e,r,`color expected, "${r}" found`)]},constants:ai,enum:di,filter:yi,function:pi,layer:bi,object:ui,source:Si,light:Ai,sky:ki,terrain:Mi,projection:function(t){const e=t.value,r=t.styleSpec,n=r.projection,i=t.style,s=Bn(e);if(undefined===e)return [];if("object"!==s)return [new St("projection",e,`object expected, ${s} found`)];let a=[];for(const s in e)a=a.concat(n[s]?t.validateSpec({key:s,value:e[s],valueSpec:n[s],style:i,styleSpec:r}):[new St(s,e[s],`unknown property "${s}"`)]);return a},projectionDefinition:function(t){const e=t.key;let r=t.value;r=r instanceof String?r.valueOf():r;const n=Bn(r);return "array"!==n||function(t){return Array.isArray(t)&&3===t.length&&"string"==typeof t[0]&&"string"==typeof t[1]&&"number"==typeof t[2]}(r)||function(t){return !!["interpolate","step","literal"].includes(t[0])}(r)?["array","string"].includes(n)?[]:[new St(e,r,`projection expected, invalid type "${n}" found`)]:[new St(e,r,`projection expected, invalid array ${JSON.stringify(r)} found`)]},string:wi,formatted:function(t){return 0===wi(t).length?[]:fi(t)},resolvedImage:function(t){return 0===wi(t).length?[]:fi(t)},padding:function(t){const e=t.key,r=t.value;if("array"===Bn(r)){if(r.length<1||r.length>4)return [new St(e,r,`padding requires 1 to 4 values; ${r.length} values found`)];const n={type:"number"};let i=[];for(let s=0;s[]}})),t.constants&&(r=r.concat(ai({key:"constants",value:t.constants,style:t,styleSpec:e,validateSpec:Pi}))),Ei(r)}function Vi(t){return function(e){return t({...e,validateSpec:Pi})}}function Ei(t){return [].concat(t).sort(((t,e)=>t.line-e.line))}function Ti(t){return function(...e){return Ei(t.apply(this,e))}}Bi.source=Ti(Vi(Si)),Bi.sprite=Ti(Vi(Ii)),Bi.glyphs=Ti(Vi(Ci)),Bi.light=Ti(Vi(Ai)),Bi.sky=Ti(Vi(ki)),Bi.terrain=Ti(Vi(Mi)),Bi.layer=Ti(Vi(bi)),Bi.filter=Ti(Vi(yi)),Bi.paintProperty=Ti(Vi(xi)),Bi.layoutProperty=Ti(Vi(vi));const Fi=Bi,$i=Fi.light,Li=Fi.sky,Di=Fi.paintProperty,Oi=Fi.layoutProperty;function Ri(t,e){let r=false;if(e&&e.length)for(const n of e)t.fire(new ut(new Error(n.message))),r=true;return r}class ji{constructor(t,e,r){const n=this.cells=[];if(t instanceof ArrayBuffer){this.arrayBuffer=t;const i=new Int32Array(this.arrayBuffer);t=i[0],this.d=(e=i[1])+2*(r=i[2]);for(let t=0;t=u[l+0]&&n>=u[l+1])?(a[h]=true,s.push(i[h])):a[h]=false;}}}}_forEachCell(t,e,r,n,i,s,a,o){const l=this._convertToCellCoord(t),u=this._convertToCellCoord(e),c=this._convertToCellCoord(r),h=this._convertToCellCoord(n);for(let p=l;p<=c;p++)for(let l=u;l<=h;l++){const u=this.d*l+p;if((!o||o(this._convertFromCellCoord(p),this._convertFromCellCoord(l),this._convertFromCellCoord(p+1),this._convertFromCellCoord(l+1)))&&i.call(this,t,e,r,n,u,s,a,o))return}}_convertFromCellCoord(t){return (t-this.padding)/this.scale}_convertToCellCoord(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;const t=this.cells,e=3+this.cells.length+1+1;let r=0;for(let t=0;t=0)continue;const s=t[n];i[n]=Ni[r].shallow.indexOf(n)>=0?s:Xi(s,e);}t instanceof Error&&(i.message=t.message);}if(i.$name)throw new Error("$name property is reserved for worker serialization logic.");return "Object"!==r&&(i.$name=r),i}function Ki(t){if(Zi(t))return t;if(Array.isArray(t))return t.map(Ki);if("object"!=typeof t)throw new Error("can't deserialize object of type "+typeof t);const e=Gi(t)||"Object";if(!Ni[e])throw new Error(`can't deserialize unregistered class ${e}`);const{klass:r}=Ni[e];if(!r)throw new Error(`can't deserialize unregistered class ${e}`);if(r.deserialize)return r.deserialize(t);const n=Object.create(r.prototype);for(const r of Object.keys(t)){if("$name"===r)continue;const i=t[r];n[r]=Ni[e].shallow.indexOf(r)>=0?i:Ki(i);}return n}class Hi{constructor(){this.first=true;}update(t,e){const r=Math.floor(t);return this.first?(this.first=false,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,true):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoomt>=128&&t<=255,"Hangul Jamo":t=>t>=4352&&t<=4607,Khmer:t=>t>=6016&&t<=6143,"General Punctuation":t=>t>=8192&&t<=8303,"Letterlike Symbols":t=>t>=8448&&t<=8527,"Number Forms":t=>t>=8528&&t<=8591,"Miscellaneous Technical":t=>t>=8960&&t<=9215,"Control Pictures":t=>t>=9216&&t<=9279,"Optical Character Recognition":t=>t>=9280&&t<=9311,"Enclosed Alphanumerics":t=>t>=9312&&t<=9471,"Geometric Shapes":t=>t>=9632&&t<=9727,"Miscellaneous Symbols":t=>t>=9728&&t<=9983,"Miscellaneous Symbols and Arrows":t=>t>=11008&&t<=11263,"Ideographic Description Characters":t=>t>=12272&&t<=12287,"CJK Symbols and Punctuation":t=>t>=12288&&t<=12351,Katakana:t=>t>=12448&&t<=12543,Kanbun:t=>t>=12688&&t<=12703,"CJK Strokes":t=>t>=12736&&t<=12783,"Enclosed CJK Letters and Months":t=>t>=12800&&t<=13055,"CJK Compatibility":t=>t>=13056&&t<=13311,"Yijing Hexagram Symbols":t=>t>=19904&&t<=19967,"Private Use Area":t=>t>=57344&&t<=63743,"Vertical Forms":t=>t>=65040&&t<=65055,"CJK Compatibility Forms":t=>t>=65072&&t<=65103,"Small Form Variants":t=>t>=65104&&t<=65135,"Halfwidth and Fullwidth Forms":t=>t>=65280&&t<=65519};function Ji(t){for(const e of t)if(ns(e.charCodeAt(0)))return true;return false}function Wi(t){for(const e of t)if(!es(e.charCodeAt(0)))return false;return true}function Qi(t){const e=t.map((t=>{try{return new RegExp(`\\p{sc=${t}}`,"u").source}catch(t){return null}})).filter((t=>t));return new RegExp(e.join("|"),"u")}const ts=Qi(["Arab","Dupl","Mong","Ougr","Syrc"]);function es(t){return !ts.test(String.fromCodePoint(t))}const rs=Qi(["Bopo","Hani","Hira","Kana","Kits","Nshu","Tang","Yiii"]);function ns(t){return !(746!==t&&747!==t&&(t<4352||!(Yi["CJK Compatibility Forms"](t)&&!(t>=65097&&t<=65103)||Yi["CJK Compatibility"](t)||Yi["CJK Strokes"](t)||!(!Yi["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||Yi["Enclosed CJK Letters and Months"](t)||Yi["Ideographic Description Characters"](t)||Yi.Kanbun(t)||Yi.Katakana(t)&&12540!==t||!(!Yi["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!Yi["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||Yi["Vertical Forms"](t)||Yi["Yijing Hexagram Symbols"](t)||/\p{sc=Cans}/u.test(String.fromCodePoint(t))||/\p{sc=Hang}/u.test(String.fromCodePoint(t))||rs.test(String.fromCodePoint(t)))))}function is(t){return !(ns(t)||function(t){return !!(Yi["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||Yi["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||Yi["Letterlike Symbols"](t)||Yi["Number Forms"](t)||Yi["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||Yi["Control Pictures"](t)&&9251!==t||Yi["Optical Character Recognition"](t)||Yi["Enclosed Alphanumerics"](t)||Yi["Geometric Shapes"](t)||Yi["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||Yi["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||Yi["CJK Symbols and Punctuation"](t)||Yi.Katakana(t)||Yi["Private Use Area"](t)||Yi["CJK Compatibility Forms"](t)||Yi["Small Form Variants"](t)||Yi["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}const ss=Qi(["Adlm","Arab","Armi","Avst","Chrs","Cprt","Egyp","Elym","Gara","Hatr","Hebr","Hung","Khar","Lydi","Mand","Mani","Mend","Merc","Mero","Narb","Nbat","Nkoo","Orkh","Palm","Phli","Phlp","Phnx","Prti","Rohg","Samr","Sarb","Sogo","Syrc","Thaa","Todr","Yezi"]);function as(t){return ss.test(String.fromCodePoint(t))}function os(t,e){return !(!e&&as(t)||t>=2304&&t<=3583||t>=3840&&t<=4255||Yi.Khmer(t))}function ls(t){for(const e of t)if(as(e.charCodeAt(0)))return true;return false}const us=new class{constructor(){this.TIMEOUT=5e3,this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus="unavailable",this.pluginURL=null,this.loadScriptResolve=()=>{};}setState(t){this.pluginStatus=t.pluginStatus,this.pluginURL=t.pluginURL;}getState(){return {pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(t){if(us.isParsed())throw new Error("RTL text plugin already registered.");this.applyArabicShaping=t.applyArabicShaping,this.processBidirectionalText=t.processBidirectionalText,this.processStyledBidirectionalText=t.processStyledBidirectionalText,this.loadScriptResolve();}isParsed(){return null!=this.applyArabicShaping&&null!=this.processBidirectionalText&&null!=this.processStyledBidirectionalText}getRTLTextPluginStatus(){return this.pluginStatus}syncState(t,r){return e(this,undefined,undefined,(function*(){if(this.isParsed())return this.getState();if("loading"!==t.pluginStatus)return this.setState(t),t;const e=t.pluginURL,n=new Promise((t=>{this.loadScriptResolve=t;}));r(e);const i=new Promise((t=>setTimeout((()=>t()),this.TIMEOUT)));if(yield Promise.race([n,i]),this.isParsed()){const t={pluginStatus:"loaded",pluginURL:e};return this.setState(t),t}throw this.setState({pluginStatus:"error",pluginURL:""}),new Error(`RTL Text Plugin failed to import scripts from ${e}`)}))}};class cs{constructor(t,e){this.zoom=t,e?(this.now=e.now,this.fadeDuration=e.fadeDuration,this.zoomHistory=e.zoomHistory,this.transition=e.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new Hi,this.transition={});}isSupportedScript(t){return function(t,e){for(const r of t)if(!os(r.charCodeAt(0),e))return false;return true}(t,"loaded"===us.getRTLTextPluginStatus())}crossFadingFactor(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}getCrossfadeParameters(){const t=this.zoom,e=t-Math.floor(t),r=this.crossFadingFactor();return t>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*r}:{fromScale:.5,toScale:1,t:1-(1-r)*e}}}class hs{constructor(t,e){this.property=t,this.value=e,this.expression=function(t,e){if(Vn(t))return new Zn(t,e);if(jn(t)){const r=Gn(t,e);if("error"===r.result)throw new Error(r.value.map((t=>`${t.key}: ${t.message}`)).join(", "));return r.value}{let r=t;return "color"===e.type&&"string"==typeof t?r=ye.parse(t):"padding"!==e.type||"number"!=typeof t&&!Array.isArray(t)?"variableAnchorOffsetCollection"===e.type&&Array.isArray(t)?r=_e.parse(t):"projectionDefinition"===e.type&&"string"==typeof t&&(r=Ae.parse(t)):r=ve.parse(t),{kind:"constant",evaluate:()=>r}}}(undefined===e?t.specification.default:e,t.specification);}isDataDriven(){return "source"===this.expression.kind||"composite"===this.expression.kind}possiblyEvaluate(t,e,r){return this.property.possiblyEvaluate(this,t,e,r)}}class ps{constructor(t){this.property=t,this.value=new hs(t,undefined);}transitioned(t,e){return new ds(this.property,this.value,e,F({},t.transition,this.transition),t.now)}untransitioned(){return new ds(this.property,this.value,null,{},0)}}class fs{constructor(t){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues);}getValue(t){return O(this._values[t].value.value)}setValue(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new ps(this._values[t].property)),this._values[t].value=new hs(this._values[t].property,null===e?undefined:O(e));}getTransition(t){return O(this._values[t].transition)}setTransition(t,e){Object.prototype.hasOwnProperty.call(this._values,t)||(this._values[t]=new ps(this._values[t].property)),this._values[t].transition=O(e)||undefined;}serialize(){const t={};for(const e of Object.keys(this._values)){const r=this.getValue(e);undefined!==r&&(t[e]=r);const n=this.getTransition(e);undefined!==n&&(t[`${e}-transition`]=n);}return t}transitioned(t,e){const r=new ys(this._properties);for(const n of Object.keys(this._values))r._values[n]=this._values[n].transitioned(t,e._values[n]);return r}untransitioned(){const t=new ys(this._properties);for(const e of Object.keys(this._values))t._values[e]=this._values[e].untransitioned();return t}}class ds{constructor(t,e,r,n,i){this.property=t,this.value=e,this.begin=i+n.delay||0,this.end=this.begin+n.duration||0,t.specification.transition&&(n.delay||n.duration)&&(this.prior=r);}possiblyEvaluate(t,e,r){const n=t.now||0,i=this.value.possiblyEvaluate(t,e,r),s=this.prior;if(s){if(n>this.end)return this.prior=null,i;if(this.value.isDataDriven())return this.prior=null,i;if(nn.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class _s{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){if(undefined!==t.value){if("constant"===t.expression.kind){const i=t.expression.evaluate(e,null,{},r,n);return this._calculate(i,i,i,e)}return this._calculate(t.expression.evaluate(new cs(Math.floor(e.zoom-1),e)),t.expression.evaluate(new cs(Math.floor(e.zoom),e)),t.expression.evaluate(new cs(Math.floor(e.zoom+1),e)),e)}}_calculate(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}}interpolate(t){return t}}class Ss{constructor(t){this.specification=t;}possiblyEvaluate(t,e,r,n){return !!t.expression.evaluate(e,null,{},r,n)}interpolate(){return false}}class As{constructor(t){this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(const e in t){const r=t[e];r.specification.overridable&&this.overridableProperties.push(e);const n=this.defaultPropertyValues[e]=new hs(r,undefined),i=this.defaultTransitionablePropertyValues[e]=new ps(r);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({});}}}Ui("DataDrivenProperty",bs),Ui("DataConstantProperty",vs),Ui("CrossFadedDataDrivenProperty",ws),Ui("CrossFadedProperty",_s),Ui("ColorRampProperty",Ss);const ks="-transition";class Ms extends ct{constructor(t,e){if(super(),this.id=t.id,this.type=t.type,this._featureFilter={filter:()=>true,needGeometry:false},"custom"!==t.type&&(this.metadata=t.metadata,this.minzoom=t.minzoom,this.maxzoom=t.maxzoom,"background"!==t.type&&(this.source=t.source,this.sourceLayer=t["source-layer"],this.filter=t.filter),e.layout&&(this._unevaluatedLayout=new ms(e.layout)),e.paint)){this._transitionablePaint=new fs(e.paint);for(const e in t.paint)this.setPaintProperty(e,t.paint[e],{validate:false});for(const e in t.layout)this.setLayoutProperty(e,t.layout[e],{validate:false});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new xs(e.paint);}}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(t){return "visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)}setLayoutProperty(t,e,r={}){null!=e&&this._validate(Oi,`layers.${this.id}.layout.${t}`,t,e,r)||("visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility=e);}getPaintProperty(t){return t.endsWith(ks)?this._transitionablePaint.getTransition(t.slice(0,-11)):this._transitionablePaint.getValue(t)}setPaintProperty(t,e,r={}){if(null!=e&&this._validate(Di,`layers.${this.id}.paint.${t}`,t,e,r))return false;if(t.endsWith(ks))return this._transitionablePaint.setTransition(t.slice(0,-11),e||undefined),false;{const r=this._transitionablePaint._values[t],n="cross-faded-data-driven"===r.property.specification["property-type"],i=r.value.isDataDriven(),s=r.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);const a=this._transitionablePaint._values[t].value;return a.isDataDriven()||i||n||this._handleOverridablePaintPropertyUpdate(t,s,a)}}_handleSpecialPaintPropertyUpdate(t){}_handleOverridablePaintPropertyUpdate(t,e,r){return false}isHidden(t){return !!(this.minzoom&&t=this.maxzoom)||"none"===this.visibility}updateTransitions(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,undefined,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,undefined,e);}serialize(){const t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(t.layout=t.layout||{},t.layout.visibility=this.visibility),D(t,((t,e)=>!(undefined===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)))}_validate(t,e,r,n,i={}){return (!i||false!==i.validate)&&Ri(this,t.call(Fi,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:ht,style:{glyphs:true,sprite:true}}))}is3D(){return false}isTileClipped(){return false}hasOffscreenPass(){return false}resize(){}isStateDependent(){for(const t in this.paint._values){const e=this.paint.get(t);if(e instanceof gs&&zn(e.property.specification)&&("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent)return true}return false}}const Is={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class zs{constructor(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;}}class Ps{constructor(){this.isTransferred=false,this.capacity=-1,this.resize(0);}static serialize(t,e){return t._trim(),e&&(t.isTransferred=true,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}}static deserialize(t){const e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());}clear(){this.length=0;}resize(t){this.reserve(t),this.length=t;}reserve(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}}function Cs(t,e=1){let r=0,n=0;return {members:t.map((t=>{const i=Is[t.type].BYTES_PER_ELEMENT,s=r=Bs(r,Math.max(e,i)),a=t.components||1;return n=Math.max(n,i),r+=i*a,{name:t.name,type:t.type,components:a,offset:s}})),size:Bs(r,Math.max(n,e)),alignment:e}}function Bs(t,e){return Math.ceil(t/e)*e}class Vs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.int16[n+0]=e,this.int16[n+1]=r,t}}Vs.prototype.bytesPerElement=4,Ui("StructArrayLayout2i4",Vs);class Es extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.int16[i+0]=e,this.int16[i+1]=r,this.int16[i+2]=n,t}}Es.prototype.bytesPerElement=6,Ui("StructArrayLayout3i6",Es);class Ts extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,t}}Ts.prototype.bytesPerElement=8,Ui("StructArrayLayout4i8",Ts);class Fs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}Fs.prototype.bytesPerElement=12,Ui("StructArrayLayout2i4i12",Fs);class $s extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=4*t,l=8*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.uint8[l+4]=n,this.uint8[l+5]=i,this.uint8[l+6]=s,this.uint8[l+7]=a,t}}$s.prototype.bytesPerElement=8,Ui("StructArrayLayout2i4ub8",$s);class Ls extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.float32[n+0]=e,this.float32[n+1]=r,t}}Ls.prototype.bytesPerElement=8,Ui("StructArrayLayout2f8",Ls);class Ds extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u){const c=this.length;return this.resize(c+1),this.emplace(c,t,e,r,n,i,s,a,o,l,u)}emplace(t,e,r,n,i,s,a,o,l,u,c){const h=10*t;return this.uint16[h+0]=e,this.uint16[h+1]=r,this.uint16[h+2]=n,this.uint16[h+3]=i,this.uint16[h+4]=s,this.uint16[h+5]=a,this.uint16[h+6]=o,this.uint16[h+7]=l,this.uint16[h+8]=u,this.uint16[h+9]=c,t}}Ds.prototype.bytesPerElement=20,Ui("StructArrayLayout10ui20",Ds);class Os extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h){const p=this.length;return this.resize(p+1),this.emplace(p,t,e,r,n,i,s,a,o,l,u,c,h)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p){const f=12*t;return this.int16[f+0]=e,this.int16[f+1]=r,this.int16[f+2]=n,this.int16[f+3]=i,this.uint16[f+4]=s,this.uint16[f+5]=a,this.uint16[f+6]=o,this.uint16[f+7]=l,this.int16[f+8]=u,this.int16[f+9]=c,this.int16[f+10]=h,this.int16[f+11]=p,t}}Os.prototype.bytesPerElement=24,Ui("StructArrayLayout4i4ui4i24",Os);class Rs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.float32[i+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}Rs.prototype.bytesPerElement=12,Ui("StructArrayLayout3f12",Rs);class js extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint32[1*t+0]=e,t}}js.prototype.bytesPerElement=4,Ui("StructArrayLayout1ul4",js);class Ns extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l){const u=this.length;return this.resize(u+1),this.emplace(u,t,e,r,n,i,s,a,o,l)}emplace(t,e,r,n,i,s,a,o,l,u){const c=10*t,h=5*t;return this.int16[c+0]=e,this.int16[c+1]=r,this.int16[c+2]=n,this.int16[c+3]=i,this.int16[c+4]=s,this.int16[c+5]=a,this.uint32[h+3]=o,this.uint16[c+8]=l,this.uint16[c+9]=u,t}}Ns.prototype.bytesPerElement=20,Ui("StructArrayLayout6i1ul2ui20",Ns);class Us extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=6*t;return this.int16[o+0]=e,this.int16[o+1]=r,this.int16[o+2]=n,this.int16[o+3]=i,this.int16[o+4]=s,this.int16[o+5]=a,t}}Us.prototype.bytesPerElement=12,Ui("StructArrayLayout2i2i2i12",Us);class qs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i){const s=this.length;return this.resize(s+1),this.emplace(s,t,e,r,n,i)}emplace(t,e,r,n,i,s){const a=4*t,o=8*t;return this.float32[a+0]=e,this.float32[a+1]=r,this.float32[a+2]=n,this.int16[o+6]=i,this.int16[o+7]=s,t}}qs.prototype.bytesPerElement=16,Ui("StructArrayLayout2f1f2i16",qs);class Gs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s){const a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i,s)}emplace(t,e,r,n,i,s,a){const o=16*t,l=4*t,u=8*t;return this.uint8[o+0]=e,this.uint8[o+1]=r,this.float32[l+1]=n,this.float32[l+2]=i,this.int16[u+6]=s,this.int16[u+7]=a,t}}Gs.prototype.bytesPerElement=16,Ui("StructArrayLayout2ub2f2i16",Gs);class Zs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=r,this.uint16[i+2]=n,t}}Zs.prototype.bytesPerElement=6,Ui("StructArrayLayout3ui6",Zs);class Xs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m){const g=this.length;return this.resize(g+1),this.emplace(g,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g){const x=24*t,v=12*t,b=48*t;return this.int16[x+0]=e,this.int16[x+1]=r,this.uint16[x+2]=n,this.uint16[x+3]=i,this.uint32[v+2]=s,this.uint32[v+3]=a,this.uint32[v+4]=o,this.uint16[x+10]=l,this.uint16[x+11]=u,this.uint16[x+12]=c,this.float32[v+7]=h,this.float32[v+8]=p,this.uint8[b+36]=f,this.uint8[b+37]=d,this.uint8[b+38]=y,this.uint32[v+10]=m,this.int16[x+22]=g,t}}Xs.prototype.bytesPerElement=48,Ui("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",Xs);class Ks extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I){const z=this.length;return this.resize(z+1),this.emplace(z,t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I)}emplace(t,e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k,M,I,z){const P=32*t,C=16*t;return this.int16[P+0]=e,this.int16[P+1]=r,this.int16[P+2]=n,this.int16[P+3]=i,this.int16[P+4]=s,this.int16[P+5]=a,this.int16[P+6]=o,this.int16[P+7]=l,this.uint16[P+8]=u,this.uint16[P+9]=c,this.uint16[P+10]=h,this.uint16[P+11]=p,this.uint16[P+12]=f,this.uint16[P+13]=d,this.uint16[P+14]=y,this.uint16[P+15]=m,this.uint16[P+16]=g,this.uint16[P+17]=x,this.uint16[P+18]=v,this.uint16[P+19]=b,this.uint16[P+20]=w,this.uint16[P+21]=_,this.uint16[P+22]=S,this.uint32[C+12]=A,this.float32[C+13]=k,this.float32[C+14]=M,this.uint16[P+30]=I,this.uint16[P+31]=z,t}}Ks.prototype.bytesPerElement=64,Ui("StructArrayLayout8i15ui1ul2f2ui64",Ks);class Hs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.float32[1*t+0]=e,t}}Hs.prototype.bytesPerElement=4,Ui("StructArrayLayout1f4",Hs);class Ys extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=3*t;return this.uint16[6*t+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t}}Ys.prototype.bytesPerElement=12,Ui("StructArrayLayout1ui2f12",Ys);class Js extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e,r){const n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)}emplace(t,e,r,n){const i=4*t;return this.uint32[2*t+0]=e,this.uint16[i+2]=r,this.uint16[i+3]=n,t}}Js.prototype.bytesPerElement=8,Ui("StructArrayLayout1ul2ui8",Js);class Ws extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t,e){const r=this.length;return this.resize(r+1),this.emplace(r,t,e)}emplace(t,e,r){const n=2*t;return this.uint16[n+0]=e,this.uint16[n+1]=r,t}}Ws.prototype.bytesPerElement=4,Ui("StructArrayLayout2ui4",Ws);class Qs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);}emplaceBack(t){const e=this.length;return this.resize(e+1),this.emplace(e,t)}emplace(t,e){return this.uint16[1*t+0]=e,t}}Qs.prototype.bytesPerElement=2,Ui("StructArrayLayout1ui2",Qs);class ta extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);}emplaceBack(t,e,r,n){const i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)}emplace(t,e,r,n,i){const s=4*t;return this.float32[s+0]=e,this.float32[s+1]=r,this.float32[s+2]=n,this.float32[s+3]=i,t}}ta.prototype.bytesPerElement=16,Ui("StructArrayLayout4f16",ta);class ea extends zs{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new l(this.anchorPointX,this.anchorPointY)}}ea.prototype.size=20;class ra extends Ns{get(t){return new ea(this,t)}}Ui("CollisionBoxArray",ra);class na extends zs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(t){this._structArray.uint8[this._pos1+37]=t;}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(t){this._structArray.uint8[this._pos1+38]=t;}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(t){this._structArray.uint32[this._pos4+10]=t;}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}na.prototype.size=48;class ia extends Xs{get(t){return new na(this,t)}}Ui("PlacedSymbolArray",ia);class sa extends zs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(t){this._structArray.uint32[this._pos4+12]=t;}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}sa.prototype.size=64;class aa extends Ks{get(t){return new sa(this,t)}}Ui("SymbolInstanceArray",aa);class oa extends Hs{getoffsetX(t){return this.float32[1*t+0]}}Ui("GlyphOffsetArray",oa);class la extends Es{getx(t){return this.int16[3*t+0]}gety(t){return this.int16[3*t+1]}gettileUnitDistanceFromAnchor(t){return this.int16[3*t+2]}}Ui("SymbolLineVertexArray",la);class ua extends zs{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}ua.prototype.size=12;class ca extends Ys{get(t){return new ua(this,t)}}Ui("TextAnchorOffsetArray",ca);class ha extends zs{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}ha.prototype.size=8;class pa extends Js{get(t){return new ha(this,t)}}Ui("FeatureIndexArray",pa);class fa extends Vs{}class da extends Vs{}class ya extends Vs{}class ma extends Fs{}class ga extends $s{}class xa extends Ls{}class va extends Ds{}class ba extends Os{}class wa extends Rs{}class _a extends js{}class Sa extends Us{}class Aa extends Gs{}class ka extends Zs{}class Ma extends Ws{}const Ia=Cs([{name:"a_pos",components:2,type:"Int16"}],4),{members:za}=Ia;class Pa{constructor(t=[]){this._forceNewSegmentOnNextPrepare=false,this.segments=t;}prepareSegment(t,e,r,n){const i=this.segments[this.segments.length-1];return t>Pa.MAX_VERTEX_ARRAY_LENGTH&&j(`Max vertices per segment is ${Pa.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${t}. Consider using the \`fillLargeMeshArrays\` function if you require meshes with more than ${Pa.MAX_VERTEX_ARRAY_LENGTH} vertices.`),this._forceNewSegmentOnNextPrepare||!i||i.vertexLength+t>Pa.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==n?this.createNewSegment(e,r,n):i}createNewSegment(t,e,r){const n={vertexOffset:t.length,primitiveOffset:e.length,vertexLength:0,primitiveLength:0,vaos:{}};return undefined!==r&&(n.sortKey=r),this._forceNewSegmentOnNextPrepare=false,this.segments.push(n),n}getOrCreateLatestSegment(t,e,r){return this.prepareSegment(0,t,e,r)}forceNewSegmentOnNextPrepare(){this._forceNewSegmentOnNextPrepare=true;}get(){return this.segments}destroy(){for(const t of this.segments)for(const e in t.vaos)t.vaos[e].destroy();}static simpleSegment(t,e,r,n){return new Pa([{vertexOffset:t,primitiveOffset:e,vertexLength:r,primitiveLength:n,vaos:{},sortKey:0}])}}function Ca(t,e){return 256*(t=E(Math.floor(t),0,255))+E(Math.floor(e),0,255)}Pa.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Ui("SegmentVector",Pa);const Ba=Cs([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]);var Va,Ea,Ta,Fa={exports:{}},$a={exports:{}},La={exports:{}},Da=function(){if(Ta)return Fa.exports;Ta=1;var t=(Va||(Va=1,$a.exports=function(t,e){var r,n,i,s,a,o,l,u;for(n=t.length-(r=3&t.length),i=e,a=3432918353,o=461845907,u=0;u>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(s>>>16)&65535)<<16);switch(l=0,r){case 3:l^=(255&t.charCodeAt(u+2))<<16;case 2:l^=(255&t.charCodeAt(u+1))<<8;case 1:i^=l=(65535&(l=(l=(65535&(l^=255&t.charCodeAt(u)))*a+(((l>>>16)*a&65535)<<16)&4294967295)<<15|l>>>17))*o+(((l>>>16)*o&65535)<<16)&4294967295;}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0}),$a.exports),e=(Ea||(Ea=1,La.exports=function(t,e){for(var r,n=t.length,i=e^n,s=0;n>=4;)r=1540483477*(65535&(r=255&t.charCodeAt(s)|(255&t.charCodeAt(++s))<<8|(255&t.charCodeAt(++s))<<16|(255&t.charCodeAt(++s))<<24))+((1540483477*(r>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(r=1540483477*(65535&(r^=r>>>24))+((1540483477*(r>>>16)&65535)<<16)),n-=4,++s;switch(n){case 3:i^=(255&t.charCodeAt(s+2))<<16;case 2:i^=(255&t.charCodeAt(s+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(s)))+((1540483477*(i>>>16)&65535)<<16);}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0}),La.exports);return Fa.exports=t,Fa.exports.murmur3=t,Fa.exports.murmur2=e,Fa.exports}(),Oa=r(Da);class Ra{constructor(){this.ids=[],this.positions=[],this.indexed=false;}add(t,e,r,n){this.ids.push(ja(t)),this.positions.push(e,r,n);}getPositions(t){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");const e=ja(t);let r=0,n=this.ids.length-1;for(;r>1;this.ids[t]>=e?n=t:r=t+1;}const i=[];for(;this.ids[r]===e;)i.push({index:this.positions[3*r],start:this.positions[3*r+1],end:this.positions[3*r+2]}),r++;return i}static serialize(t,e){const r=new Float64Array(t.ids),n=new Uint32Array(t.positions);return Na(r,n,0,r.length-1),e&&e.push(r.buffer,n.buffer),{ids:r,positions:n}}static deserialize(t){const e=new Ra;return e.ids=t.ids,e.positions=t.positions,e.indexed=true,e}}function ja(t){const e=+t;return !isNaN(e)&&e<=Number.MAX_SAFE_INTEGER?e:Oa(String(t))}function Na(t,e,r,n){for(;r>1];let s=r-1,a=n+1;for(;;){do{s++;}while(t[s]i);if(s>=a)break;Ua(t,s,a),Ua(e,3*s,3*a),Ua(e,3*s+1,3*a+1),Ua(e,3*s+2,3*a+2);}a-r`u_${t}`)),this.type=r;}setUniform(t,e,r){t.set(r.constantOr(this.value));}getBinding(t,e,r){return "color"===this.type?new Xa(t,e):new Ga(t,e)}}class Ja{constructor(t,e){this.uniformNames=e.map((t=>`u_${t}`)),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1;}setConstantPatternPositions(t,e){this.pixelRatioFrom=e.pixelRatio,this.pixelRatioTo=t.pixelRatio,this.patternFrom=e.tlbr,this.patternTo=t.tlbr;}setUniform(t,e,r,n){const i="u_pattern_to"===n?this.patternTo:"u_pattern_from"===n?this.patternFrom:"u_pixel_ratio_to"===n?this.pixelRatioTo:"u_pixel_ratio_from"===n?this.pixelRatioFrom:null;i&&t.set(i);}getBinding(t,e,r){return "u_pattern"===r.substr(0,9)?new Za(t,e):new Ga(t,e)}}class Wa{constructor(t,e,r,n){this.expression=t,this.type=r,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?2:1,offset:0}))),this.paintVertexArray=new n;}populatePaintArray(t,e,r,n,i){const s=this.paintVertexArray.length,a=this.expression.evaluate(new cs(0),e,{},n,[],i);this.paintVertexArray.resize(t),this._setPaintValue(s,t,a);}updatePaintArray(t,e,r,n){const i=this.expression.evaluate({zoom:0},r,n);this._setPaintValue(t,e,i);}_setPaintValue(t,e,r){if("color"===this.type){const n=Ha(r);for(let r=t;r`u_${t}_t`)),this.type=r,this.useIntegerZoom=n,this.zoom=i,this.maxValue=0,this.paintVertexAttributes=e.map((t=>({name:`a_${t}`,type:"Float32",components:"color"===r?4:2,offset:0}))),this.paintVertexArray=new s;}populatePaintArray(t,e,r,n,i){const s=this.expression.evaluate(new cs(this.zoom),e,{},n,[],i),a=this.expression.evaluate(new cs(this.zoom+1),e,{},n,[],i),o=this.paintVertexArray.length;this.paintVertexArray.resize(t),this._setPaintValue(o,t,s,a);}updatePaintArray(t,e,r,n){const i=this.expression.evaluate({zoom:this.zoom},r,n),s=this.expression.evaluate({zoom:this.zoom+1},r,n);this._setPaintValue(t,e,i,s);}_setPaintValue(t,e,r,n){if("color"===this.type){const i=Ha(r),s=Ha(n);for(let r=t;r`#define HAS_UNIFORM_${t}`)));}return t}getBinderAttributes(){const t=[];for(const e in this.binders){const r=this.binders[e];if(r instanceof Wa||r instanceof Qa)for(let e=0;etrue)){this.programConfigurations={};for(const n of t)this.programConfigurations[n.id]=new eo(n,e,r);this.needsUpload=false,this._featureMap=new Ra,this._bufferOffset=0;}populatePaintArrays(t,e,r,n,i,s){for(const r in this.programConfigurations)this.programConfigurations[r].populatePaintArrays(t,e,n,i,s);undefined!==e.id&&this._featureMap.add(e.id,r,this._bufferOffset,t),this._bufferOffset=t,this.needsUpload=true;}updatePaintArrays(t,e,r,n){for(const i of r)this.needsUpload=this.programConfigurations[i.id].updatePaintArrays(t,this._featureMap,e,i,n)||this.needsUpload;}get(t){return this.programConfigurations[t]}upload(t){if(this.needsUpload){for(const e in this.programConfigurations)this.programConfigurations[e].upload(t);this.needsUpload=false;}}destroy(){for(const t in this.programConfigurations)this.programConfigurations[t].destroy();}}function no(t,e){return {"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[t]||[t.replace(`${e}-`,"").replace(/-/g,"_")]}function io(t,e,r){const n={color:{source:Ls,composite:ta},number:{source:Hs,composite:Ls}},i=function(t){return {"line-pattern":{source:va,composite:va},"fill-pattern":{source:va,composite:va},"fill-extrusion-pattern":{source:va,composite:va}}[t]}(t);return i&&i[r]||n[e][r]}Ui("ConstantBinder",Ya),Ui("CrossFadedConstantBinder",Ja),Ui("SourceExpressionBinder",Wa),Ui("CrossFadedCompositeBinder",to),Ui("CompositeExpressionBinder",Qa),Ui("ProgramConfiguration",eo,{omit:["_buffers"]}),Ui("ProgramConfigurationSet",ro);const so=Math.pow(2,14)-1,ao=-so-1;function oo(t){const e=M/t.extent,r=t.loadGeometry();for(let t=0;tr.x+1||sr.y+1)&&j("Geometry exceeds allowed extent, reduce your vector tile buffer size");}}return r}function lo(t,e){return {type:t.type,id:t.id,properties:t.properties,geometry:e?oo(t):[]}}const uo=-32768;function co(t,e,r,n,i){t.emplaceBack(uo+8*e+n,uo+8*r+i);}class ho{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=false,this.layoutVertexArray=new da,this.indexArray=new ka,this.segments=new Pa,this.programConfigurations=new ro(t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){const n=this.layers[0],i=[];let s=null,a=false,o="heatmap"===n.type;if("circle"===n.type){const t=n;s=t.layout.get("circle-sort-key"),a=!s.isConstant(),o=o||"map"===t.paint.get("circle-pitch-alignment");}const l=o?e.subdivisionGranularity.circle:1;for(const{feature:e,id:n,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=lo(e,t);if(!this.layers[0]._featureFilter.filter(new cs(this.zoom),u,r))continue;const c=a?s.evaluate(u,{},r):undefined,h={id:n,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:oo(e),patterns:{},sortKey:c};i.push(h);}a&&i.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of i){const{geometry:i,index:s,sourceLayerIndex:a}=n,o=t[s].feature;this.addFeature(n,i,s,r,l),e.featureIndex.insert(o,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,za),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=true;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}addFeature(t,e,r,n,i=1){let s;switch(i){case 1:s=[0,7];break;case 3:s=[0,2,5,7];break;case 5:s=[0,1,3,4,6,7];break;case 7:s=[0,1,2,3,4,5,6,7];break;default:throw new Error(`Invalid circle bucket granularity: ${i}; valid values are 1, 3, 5, 7.`)}const a=s.length;for(const r of e)for(const e of r){const r=e.x,n=e.y;if(r<0||r>=M||n<0||n>=M)continue;const i=this.segments.prepareSegment(a*a,this.layoutVertexArray,this.indexArray,t.sortKey),o=i.vertexLength;for(let t=0;t1){if(go(t,e))return true;for(let n=0;n1?r:r.sub(e)._mult(i)._add(e))}function wo(t,e){let r,n,i,s=false;for(let a=0;ae.y!=i.y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(s=!s);}return s}function _o(t,e){let r=false;for(let n=0,i=t.length-1;ne.y!=a.y>e.y&&e.x<(a.x-s.x)*(e.y-s.y)/(a.y-s.y)+s.x&&(r=!r);}return r}function So(t,e,r){const n=r[0],i=r[2];if(t.xi.x&&e.x>i.x||t.yi.y&&e.y>i.y)return false;const s=N(t,e,r[0]);return s!==N(t,e,r[1])||s!==N(t,e,r[2])||s!==N(t,e,r[3])}function Ao(t,e,r){const n=e.paint.get(t).value;return "constant"===n.kind?n.value:r.programConfigurations.get(e.id).getMaxValue(t)}function ko(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function Mo(t,e,r,n,i){if(!e[0]&&!e[1])return t;const s=l.convert(e)._mult(i);"viewport"===r&&s._rotate(-n);const a=[];for(let e=0;eBo(t,e)))}(o,a),h=u?l*s:l;for(const t of n)for(const e of t){const t=u?e:Bo(e,a);let r=h;const n=_([],[e.x,e.y,0,1],a);if("viewport"===this.paint.get("circle-pitch-scale")&&"map"===this.paint.get("circle-pitch-alignment")?r*=n[3]/i.cameraToCenterDistance:"map"===this.paint.get("circle-pitch-scale")&&"viewport"===this.paint.get("circle-pitch-alignment")&&(r*=i.cameraToCenterDistance/n[3]),fo(c,t,r))return true}return false}}function Bo(t,e){const r=_([],[t.x,t.y,0,1],e);return new l(r[0]/r[3],r[1]/r[3])}class Vo extends ho{}let Eo;Ui("HeatmapBucket",Vo,{omit:["layers"]});var To={get paint(){return Eo=Eo||new As({"heatmap-radius":new bs(ht.paint_heatmap["heatmap-radius"]),"heatmap-weight":new bs(ht.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new vs(ht.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Ss(ht.paint_heatmap["heatmap-color"]),"heatmap-opacity":new vs(ht.paint_heatmap["heatmap-opacity"])})}};function Fo(t,{width:e,height:r},n,i){if(i){if(i instanceof Uint8ClampedArray)i=new Uint8Array(i.buffer);else if(i.length!==e*r*n)throw new RangeError(`mismatched image size. expected: ${i.length} but got: ${e*r*n}`)}else i=new Uint8Array(e*r*n);return t.width=e,t.height=r,t.data=i,t}function $o(t,{width:e,height:r},n){if(e===t.width&&r===t.height)return;const i=Fo({},{width:e,height:r},n);Lo(t,i,{x:0,y:0},{x:0,y:0},{width:Math.min(t.width,e),height:Math.min(t.height,r)},n),t.width=e,t.height=r,t.data=i.data;}function Lo(t,e,r,n,i,s){if(0===i.width||0===i.height)return e;if(i.width>t.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");const a=t.data,o=e.data;if(a===o)throw new Error("srcData equals dstData, so image is already copied");for(let l=0;l{e[t.evaluationKey]=s;const a=t.expression.evaluate(e);i.data[r+n+0]=Math.floor(255*a.r/a.a),i.data[r+n+1]=Math.floor(255*a.g/a.a),i.data[r+n+2]=Math.floor(255*a.b/a.a),i.data[r+n+3]=Math.floor(255*a.a);};if(t.clips)for(let e=0,i=0;e0)for(let i=e;i=e;i-=n)s=xl(i/n|0,t[i],t[i+1],s);return s&&pl(s,s.next)&&(vl(s),s=s.next),s}function Jo(t,e){if(!t)return t;e||(e=t);let r,n=t;do{if(r=false,n.steiner||!pl(n,n.next)&&0!==hl(n.prev,n,n.next))n=n.next;else {if(vl(n),n=e=n.prev,n===n.next)break;r=true;}}while(r||n!==e);return e}function Wo(t,e,r,n,i,s,a){if(!t)return;!a&&s&&function(t,e,r,n){let i=t;do{0===i.z&&(i.z=al(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){let e,r=1;do{let n,i=t;t=null;let s=null;for(e=0;i;){e++;let a=i,o=0;for(let t=0;t0||l>0&&a;)0!==o&&(0===l||!a||i.z<=a.z)?(n=i,i=i.nextZ,o--):(n=a,a=a.nextZ,l--),s?s.nextZ=n:t=n,n.prevZ=s,s=n;i=a;}s.nextZ=null,r*=2;}while(e>1)}(i);}(t,n,i,s);let o=t;for(;t.prev!==t.next;){const l=t.prev,u=t.next;if(s?tl(t,n,i,s):Qo(t))e.push(l.i,t.i,u.i),vl(t),t=u.next,o=u.next;else if((t=u)===o){a?1===a?Wo(t=el(Jo(t),e),e,r,n,i,s,2):2===a&&rl(t,e,r,n,i,s):Wo(Jo(t),e,r,n,i,s,1);break}}}function Qo(t){const e=t.prev,r=t,n=t.next;if(hl(e,r,n)>=0)return false;const i=e.x,s=r.x,a=n.x,o=e.y,l=r.y,u=n.y,c=Math.min(i,s,a),h=Math.min(o,l,u),p=Math.max(i,s,a),f=Math.max(o,l,u);let d=n.next;for(;d!==e;){if(d.x>=c&&d.x<=p&&d.y>=h&&d.y<=f&&ul(i,o,s,l,a,u,d.x,d.y)&&hl(d.prev,d,d.next)>=0)return false;d=d.next;}return true}function tl(t,e,r,n){const i=t.prev,s=t,a=t.next;if(hl(i,s,a)>=0)return false;const o=i.x,l=s.x,u=a.x,c=i.y,h=s.y,p=a.y,f=Math.min(o,l,u),d=Math.min(c,h,p),y=Math.max(o,l,u),m=Math.max(c,h,p),g=al(f,d,e,r,n),x=al(y,m,e,r,n);let v=t.prevZ,b=t.nextZ;for(;v&&v.z>=g&&b&&b.z<=x;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&ul(o,c,l,h,u,p,v.x,v.y)&&hl(v.prev,v,v.next)>=0)return false;if(v=v.prevZ,b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&ul(o,c,l,h,u,p,b.x,b.y)&&hl(b.prev,b,b.next)>=0)return false;b=b.nextZ;}for(;v&&v.z>=g;){if(v.x>=f&&v.x<=y&&v.y>=d&&v.y<=m&&v!==i&&v!==a&&ul(o,c,l,h,u,p,v.x,v.y)&&hl(v.prev,v,v.next)>=0)return false;v=v.prevZ;}for(;b&&b.z<=x;){if(b.x>=f&&b.x<=y&&b.y>=d&&b.y<=m&&b!==i&&b!==a&&ul(o,c,l,h,u,p,b.x,b.y)&&hl(b.prev,b,b.next)>=0)return false;b=b.nextZ;}return true}function el(t,e){let r=t;do{const n=r.prev,i=r.next.next;!pl(n,i)&&fl(n,r,r.next,i)&&ml(n,i)&&ml(i,n)&&(e.push(n.i,r.i,i.i),vl(r),vl(r.next),r=t=i),r=r.next;}while(r!==t);return Jo(r)}function rl(t,e,r,n,i,s){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&cl(a,t)){let o=gl(a,t);return a=Jo(a,a.next),o=Jo(o,o.next),Wo(a,e,r,n,i,s,0),void Wo(o,e,r,n,i,s,0)}t=t.next;}a=a.next;}while(a!==t)}function nl(t,e){let r=t.x-e.x;return 0===r&&(r=t.y-e.y,0===r)&&(r=(t.next.y-t.y)/(t.next.x-t.x)-(e.next.y-e.y)/(e.next.x-e.x)),r}function il(t,e){const r=function(t,e){let r=e;const n=t.x,i=t.y;let s,a=-1/0;if(pl(t,r))return r;do{if(pl(t,r.next))return r.next;if(i<=r.y&&i>=r.next.y&&r.next.y!==r.y){const t=r.x+(i-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(t<=n&&t>a&&(a=t,s=r.x=r.x&&r.x>=l&&n!==r.x&&ll(is.x||r.x===s.x&&sl(s,r)))&&(s=r,c=e);}r=r.next;}while(r!==o);return s}(t,e);if(!r)return e;const n=gl(r,t);return Jo(n,n.next),Jo(r,r.next)}function sl(t,e){return hl(t.prev,t,e.prev)<0&&hl(e.next,t,t.next)<0}function al(t,e,r,n,i){return (t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*i|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*i|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function ol(t){let e=t,r=t;do{(e.x=(t-a)*(s-o)&&(t-a)*(n-o)>=(r-a)*(e-o)&&(r-a)*(s-o)>=(i-a)*(n-o)}function ul(t,e,r,n,i,s,a,o){return !(t===a&&e===o)&&ll(t,e,r,n,i,s,a,o)}function cl(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&fl(r,r.next,t,e))return true;r=r.next;}while(r!==t);return false}(t,e)&&(ml(t,e)&&ml(e,t)&&function(t,e){let r=t,n=false;const i=(t.x+e.x)/2,s=(t.y+e.y)/2;do{r.y>s!=r.next.y>s&&r.next.y!==r.y&&i<(r.next.x-r.x)*(s-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)&&(hl(t.prev,t,e.prev)||hl(t,e.prev,e))||pl(t,e)&&hl(t.prev,t,t.next)>0&&hl(e.prev,e,e.next)>0)}function hl(t,e,r){return (e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function pl(t,e){return t.x===e.x&&t.y===e.y}function fl(t,e,r,n){const i=yl(hl(t,e,r)),s=yl(hl(t,e,n)),a=yl(hl(r,n,t)),o=yl(hl(r,n,e));return i!==s&&a!==o||!(0!==i||!dl(t,r,e))||!(0!==s||!dl(t,n,e))||!(0!==a||!dl(r,t,n))||!(0!==o||!dl(r,e,n))}function dl(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function yl(t){return t>0?1:t<0?-1:0}function ml(t,e){return hl(t.prev,t,t.next)<0?hl(t,e,t.next)>=0&&hl(t,t.prev,e)>=0:hl(t,e,t.prev)<0||hl(t,t.next,e)<0}function gl(t,e){const r=bl(t.i,t.x,t.y),n=bl(e.i,e.x,e.y),i=t.next,s=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,s.next=n,n.prev=s,n}function xl(t,e,r,n){const i=bl(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function vl(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ);}function bl(t,e,r){return {i:t,x:e,y:r,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:false}}class wl{constructor(t,e){if(e>t)throw new Error("Min granularity must not be greater than base granularity.");this._baseZoomGranularity=t,this._minGranularity=e;}getGranularityForZoomLevel(t){return Math.max(Math.floor(this._baseZoomGranularity/(1<32767||e>32767)throw new Error("Vertex coordinates are out of signed 16 bit integer range.");const r=0|Math.round(t),n=0|Math.round(e),i=this._getKey(r,n);if(this._vertexDictionary.has(i))return this._vertexDictionary.get(i);const s=this._vertexBuffer.length/2;return this._vertexDictionary.set(i,s),this._vertexBuffer.push(r,n),s}_subdivideTrianglesScanline(t){if(this._granularity<2)return function(t,e){const r=[];for(let n=0;n0?(r.push(i),r.push(a),r.push(s)):(r.push(i),r.push(s),r.push(a));}return r}(this._vertexBuffer,t);const e=[],r=t.length;for(let n=0;n=1||v<=0)||y&&(oi)){u>=n&&u<=i&&s.push(r[(t+1)%3]);continue}!y&&x>0&&s.push(this._vertexToIndex(a+p*x,o+f*x));const b=a+p*Math.max(x,0),w=a+p*Math.min(v,1);d||this._generateIntraEdgeVertices(s,a,o,l,u,b,w),!y&&v<1&&s.push(this._vertexToIndex(a+p*v,o+f*v)),(y||u>=n&&u<=i)&&s.push(r[(t+1)%3]),!y&&(u<=n||u>=i)&&this._generateInterEdgeVertices(s,a,o,l,u,c,h,w,n,i);}return s}_generateIntraEdgeVertices(t,e,r,n,i,s,a){const o=n-e,l=i-r,u=0===l,c=u?Math.min(e,n):Math.min(s,a),h=u?Math.max(e,n):Math.max(s,a),p=Math.floor(c/this._granularityCellSize)+1,f=Math.ceil(h/this._granularityCellSize)-1;if(u?e=p;n--){const i=n*this._granularityCellSize;t.push(this._vertexToIndex(i,r+l*(i-e)/o));}}_generateInterEdgeVertices(t,e,r,n,i,s,a,o,l,u){const c=i-r,h=s-n,p=a-i,f=(l-i)/p,d=(u-i)/p,y=Math.min(f,d),m=Math.max(f,d),g=n+h*y;let x=Math.floor(Math.min(g,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(g,o)/this._granularityCellSize)-1,b=o=1||m<=0){const t=r-a,n=s+(e-s)*Math.min((l-a)/t,(u-a)/t);x=Math.floor(Math.min(n,o)/this._granularityCellSize)+1,v=Math.ceil(Math.max(n,o)/this._granularityCellSize)-1,b=o0?u:l;if(b)for(let e=x;e<=v;e++)t.push(this._vertexToIndex(e*this._granularityCellSize,_));else for(let e=v;e>=x;e--)t.push(this._vertexToIndex(e*this._granularityCellSize,_));}_generateOutline(t){const e=[];for(const r of t){const t=Il(r,this._granularity,true),n=this._pointArrayToIndices(t),i=[];for(let t=1;ti!=(s===Sl)?(t.push(e),t.push(r),t.push(this._vertexToIndex(n,s)),t.push(r),t.push(this._vertexToIndex(i,s)),t.push(this._vertexToIndex(n,s))):(t.push(r),t.push(e),t.push(this._vertexToIndex(n,s)),t.push(this._vertexToIndex(i,s)),t.push(r),t.push(this._vertexToIndex(n,s)));}_fillPoles(t,e,r){const n=this._vertexBuffer,i=M,s=t.length;for(let a=2;a80*r){o=1/0,l=1/0;let e=-1/0,n=-1/0;for(let s=r;se&&(e=r),i>n&&(n=i);}u=Math.max(e-o,n-l),u=0!==u?32767/u:0;}return Wo(s,a,r,o,l,u,0),a}(r,n),e=this._convertIndices(r,t);i=this._subdivideTrianglesScanline(e);}catch(t){console.error(t);}let s=[];return e&&(s=this._generateOutline(t)),this._ensureNoPoleVertices(),this._handlePoles(i),{verticesFlattened:this._vertexBuffer,indicesTriangles:i,indicesLineList:s}}_convertIndices(t,e){const r=[];for(let n=0;n0?(Math.floor(x/a)+1)*a:(Math.ceil(x/a)-1)*a,e=y>0?(Math.floor(v/a)+1)*a:(Math.ceil(v/a)-1)*a,r=Math.abs(x-t),n=Math.abs(v-e),i=Math.abs(x-c),s=Math.abs(v-h),u=p?r/m:Number.POSITIVE_INFINITY,b=f?n/g:Number.POSITIVE_INFINITY;if((i<=r||!p)&&(s<=n||!f))break;if(u=0?a-1:s-1,i=(o+1)%s,l=t[2*e[n]],u=t[2*e[i]],c=t[2*e[a]],h=t[2*e[a]+1],p=t[2*e[o]+1];let f=false;if(lu)f=false;else {const r=p-h,s=-(t[2*e[o]]-c),a=h((u-c)*r+(t[2*e[i]+1]-h)*s)*a&&(f=true);}if(f){const t=e[n],i=e[a],l=e[o];t!==i&&t!==l&&i!==l&&r.push(l,i,t),a--,a<0&&(a=s-1);}else {const t=e[i],n=e[a],l=e[o];t!==n&&t!==l&&n!==l&&r.push(l,n,t),o++,o>=s&&(o=0);}if(n===i)break}}function Pl(t,e,r,n,i,s,a,o,l){const u=i.length/2,c=a&&o&&l;if(uPa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,y=true,m=true,g=true,c=0);const x=Cl(a,n,s,o,p,y,u),v=Cl(a,n,s,o,f,m,u),b=Cl(a,n,s,o,d,g,u);r.emplaceBack(c+x-l,c+v-l,c+b-l),u.primitiveLength++;}}(e,r,n,i,s,t),c&&function(t,e,r,n,i,s){const a=[];for(let t=0;tPa.MAX_VERTEX_ARRAY_LENGTH&&(u=t.createNewSegment(e,r),l=o.count,d=true,y=true,c=0);const m=Cl(a,n,s,o,i,d,u),g=Cl(a,n,s,o,h,y,u);r.emplaceBack(c+m-l,c+g-l),u.primitiveLength++;}}}(a,r,o,i,l,t),e.forceNewSegmentOnNextPrepare(),null==a||a.forceNewSegmentOnNextPrepare();}function Cl(t,e,r,n,i,s,a){if(s){const s=n.count;return r(e[2*i],e[2*i+1]),t[i]=n.count,n.count++,a.vertexLength++,s}return t[i]}class Bl{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=false,this.patternFeatures=[],this.layoutVertexArray=new ya,this.indexArray=new ka,this.indexArray2=new Ma,this.programConfigurations=new ro(t.layers,t.zoom),this.segments=new Pa,this.segments2=new Pa,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=Ko("fill",this.layers,e);const n=this.layers[0].layout.get("fill-sort-key"),i=!n.isConstant(),s=[];for(const{feature:a,id:o,index:l,sourceLayerIndex:u}of t){const t=this.layers[0]._featureFilter.needGeometry,c=lo(a,t);if(!this.layers[0]._featureFilter.filter(new cs(this.zoom),c,r))continue;const h=i?n.evaluate(c,{},r,e.availableImages):undefined,p={id:o,properties:a.properties,type:a.type,sourceLayerIndex:u,index:l,geometry:t?c.geometry:oo(a),patterns:{},sortKey:h};s.push(p);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=Ho("fill",this.layers,n,this.zoom,e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Xo),this.indexBuffer=t.createIndexBuffer(this.indexArray),this.indexBuffer2=t.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(t),this.uploaded=true;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy());}addFeature(t,e,r,n,i,s){for(const t of Le(e,500)){const e=Ml(t,n,s.fill.getGranularityForZoomLevel(n.z)),r=this.layoutVertexArray;Pl(((t,e)=>{r.emplaceBack(t,e);}),this.segments,this.layoutVertexArray,this.indexArray,e.verticesFlattened,e.indicesTriangles,this.segments2,this.indexArray2,e.indicesLineList);}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,i,n);}}let Vl,El;Ui("FillBucket",Bl,{omit:["layers","patternFeatures"]});var Tl={get paint(){return El=El||new As({"fill-antialias":new vs(ht.paint_fill["fill-antialias"]),"fill-opacity":new bs(ht.paint_fill["fill-opacity"]),"fill-color":new bs(ht.paint_fill["fill-color"]),"fill-outline-color":new bs(ht.paint_fill["fill-outline-color"]),"fill-translate":new vs(ht.paint_fill["fill-translate"]),"fill-translate-anchor":new vs(ht.paint_fill["fill-translate-anchor"]),"fill-pattern":new ws(ht.paint_fill["fill-pattern"])})},get layout(){return Vl=Vl||new As({"fill-sort-key":new bs(ht.layout_fill["fill-sort-key"])})}};class Fl extends Ms{constructor(t){super(t,Tl);}recalculate(t,e){super.recalculate(t,e);const r=this.paint._values["fill-outline-color"];"constant"===r.value.kind&&undefined===r.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"]);}createBucket(t){return new Bl(t)}queryRadius(){return ko(this.paint.get("fill-translate"))}queryIntersectsFeature({queryGeometry:t,geometry:e,transform:r,pixelsToTileUnits:n}){return yo(Mo(t,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),-r.bearingInRadians,n),e)}isTileClipped(){return true}}const $l=Cs([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4),Ll=Cs([{name:"a_centroid",components:2,type:"Int16"}],4),{members:Dl}=$l;var Ol,Rl,jl,Nl,Ul,ql,Gl,Zl={};function Xl(){if(Rl)return Ol;Rl=1;var t=s();function e(t,e,n,i,s){this.properties={},this.extent=n,this.type=0,this._pbf=t,this._geometry=-1,this._keys=i,this._values=s,t.readFields(r,this,e);}function r(t,e,r){1==t?e.id=r.readVarint():2==t?function(t,e){for(var r=t.readVarint()+t.pos;t.pos>3;}if(s--,1===i||2===i)a+=e.readSVarint(),o+=e.readSVarint(),1===i&&(r&&l.push(r),r=[]),r.push(new t(a,o));else {if(7!==i)throw new Error("unknown command "+i);r&&r.push(r[0].clone());}}return r&&l.push(r),l},e.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,s=0,a=1/0,o=-1/0,l=1/0,u=-1/0;t.pos>3;}if(n--,1===r||2===r)(i+=t.readSVarint())o&&(o=i),(s+=t.readSVarint())u&&(u=s);else if(7!==r)throw new Error("unknown command "+r)}return [a,l,o,u]},e.prototype.toGeoJSON=function(t,r,i){var s,a,o=this.extent*Math.pow(2,i),l=this.extent*t,u=this.extent*r,c=this.loadGeometry(),h=e.types[this.type];function p(t){for(var e=0;e>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null;}return e}(r));}return jl=e,e.prototype.feature=function(e){if(e<0||e>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[e];var r=this._pbf.readVarint()+this._pbf.pos;return new t(this._pbf,r,this.extent,this._keys,this._values)},jl}function Hl(){return Gl||(Gl=1,Zl.VectorTile=function(){if(ql)return Ul;ql=1;var t=Kl();function e(e,r,n){if(3===e){var i=new t(n,n.readVarint()+n.pos);i.length&&(r[i.name]=i);}}return Ul=function(t,r){this.layers=t.readFields(e,{},r);},Ul}(),Zl.VectorTileFeature=Xl(),Zl.VectorTileLayer=Kl()),Zl}var Yl=r(Hl());const Jl=Yl.VectorTileFeature.types,Wl=Math.pow(2,13);function Ql(t,e,r,n,i,s,a,o){t.emplaceBack(e,r,2*Math.floor(n*Wl)+a,i*Wl*2,s*Wl*2,Math.round(o));}class tu{constructor(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((t=>t.id)),this.index=t.index,this.hasPattern=false,this.layoutVertexArray=new ma,this.centroidVertexArray=new fa,this.indexArray=new ka,this.programConfigurations=new ro(t.layers,t.zoom),this.segments=new Pa,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.features=[],this.hasPattern=Ko("fill-extrusion",this.layers,e);for(const{feature:n,id:i,index:s,sourceLayerIndex:a}of t){const t=this.layers[0]._featureFilter.needGeometry,o=lo(n,t);if(!this.layers[0]._featureFilter.filter(new cs(this.zoom),o,r))continue;const l={id:i,sourceLayerIndex:a,index:s,geometry:t?o.geometry:oo(n),properties:n.properties,type:n.type,patterns:{}};this.hasPattern?this.features.push(Ho("fill-extrusion",this.layers,l,this.zoom,e)):this.addFeature(l,l.geometry,s,r,{},e.subdivisionGranularity),e.featureIndex.insert(n,l.geometry,s,a,this.index,true);}}addFeatures(t,e,r){for(const n of this.features){const{geometry:i}=n;this.addFeature(n,i,n.index,e,r,t.subdivisionGranularity);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);}isEmpty(){return 0===this.layoutVertexArray.length&&0===this.centroidVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,Dl),this.centroidVertexBuffer=t.createVertexBuffer(this.centroidVertexArray,Ll.members,true),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=true;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy());}addFeature(t,e,r,n,i,s){for(const r of Le(e,500)){const e={x:0,y:0,sampleCount:0},i=this.layoutVertexArray.length;this.processPolygon(e,n,t,r,s);const a=this.layoutVertexArray.length-i,o=Math.floor(e.x/e.sampleCount),l=Math.floor(e.y/e.sampleCount);for(let t=0;t{Ql(u,t,e,0,0,1,1,0);}),this.segments,this.layoutVertexArray,this.indexArray,l.verticesFlattened,l.indicesTriangles);}_generateSideFaces(t,e){let r=0;for(let n=1;nPa.MAX_VERTEX_ARRAY_LENGTH&&(e.segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));const a=i.sub(s)._perp()._unit(),o=s.dist(i);r+o>32768&&(r=0),Ql(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,0,r),Ql(this.layoutVertexArray,i.x,i.y,a.x,a.y,0,1,r),r+=o,Ql(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,0,r),Ql(this.layoutVertexArray,s.x,s.y,a.x,a.y,0,1,r);const l=e.segment.vertexLength;this.indexArray.emplaceBack(l,l+2,l+1),this.indexArray.emplaceBack(l+1,l+2,l+3),e.segment.vertexLength+=4,e.segment.primitiveLength+=2;}}}function eu(t,e){for(let r=0;rM)||t.y===e.y&&(t.y<0||t.y>M)}function nu(t){return t.every((t=>t.x<0))||t.every((t=>t.x>M))||t.every((t=>t.y<0))||t.every((t=>t.y>M))}let iu;Ui("FillExtrusionBucket",tu,{omit:["layers","features"]});var su={get paint(){return iu=iu||new As({"fill-extrusion-opacity":new vs(ht["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new bs(ht["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new vs(ht["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new vs(ht["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new ws(ht["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new bs(ht["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new bs(ht["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new vs(ht["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})}};class au extends Ms{constructor(t){super(t,su);}createBucket(t){return new tu(t)}queryRadius(){return ko(this.paint.get("fill-extrusion-translate"))}is3D(){return true}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:r,geometry:n,transform:i,pixelsToTileUnits:s,pixelPosMatrix:a}){const o=Mo(t,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),-i.bearingInRadians,s),u=this.paint.get("fill-extrusion-height").evaluate(e,r),c=this.paint.get("fill-extrusion-base").evaluate(e,r),h=function(t,e,r){const n=[];for(const r of t){const t=[r.x,r.y,0,1];_(t,t,e),n.push(new l(t[0]/t[3],t[1]/t[3]));}return n}(o,a),p=function(t,e,r,n){const i=[],s=[],a=n[8]*e,o=n[9]*e,u=n[10]*e,c=n[11]*e,h=n[8]*r,p=n[9]*r,f=n[10]*r,d=n[11]*r;for(const e of t){const t=[],r=[];for(const i of e){const e=i.x,s=i.y,y=n[0]*e+n[4]*s+n[12],m=n[1]*e+n[5]*s+n[13],g=n[2]*e+n[6]*s+n[14],x=n[3]*e+n[7]*s+n[15],v=g+u,b=x+c,w=y+h,_=m+p,S=g+f,A=x+d,k=new l((y+a)/b,(m+o)/b);k.z=v/b,t.push(k);const M=new l(w/A,_/A);M.z=S/A,r.push(M);}i.push(t),s.push(r);}return [i,s]}(n,c,u,a);return function(t,e,r){let n=1/0;yo(r,e)&&(n=lu(r,e[0]));for(let i=0;it.id)),this.index=t.index,this.hasPattern=false,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach((t=>{this.gradients[t.id]={};})),this.layoutVertexArray=new ga,this.layoutVertexArray2=new xa,this.indexArray=new ka,this.programConfigurations=new ro(t.layers,t.zoom),this.segments=new Pa,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id));}populate(t,e,r){this.hasPattern=Ko("line",this.layers,e);const n=this.layers[0].layout.get("line-sort-key"),i=!n.isConstant(),s=[];for(const{feature:e,id:a,index:o,sourceLayerIndex:l}of t){const t=this.layers[0]._featureFilter.needGeometry,u=lo(e,t);if(!this.layers[0]._featureFilter.filter(new cs(this.zoom),u,r))continue;const c=i?n.evaluate(u,{},r):undefined,h={id:a,properties:e.properties,type:e.type,sourceLayerIndex:l,index:o,geometry:t?u.geometry:oo(e),patterns:{},sortKey:c};s.push(h);}i&&s.sort(((t,e)=>t.sortKey-e.sortKey));for(const n of s){const{geometry:i,index:s,sourceLayerIndex:a}=n;if(this.hasPattern){const t=Ho("line",this.layers,n,this.zoom,e);this.patternFeatures.push(t);}else this.addFeature(n,i,s,r,{},e.subdivisionGranularity);e.featureIndex.insert(t[s].feature,i,s,a,this.index);}}update(t,e,r){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(t,e,this.stateDependentLayers,r);}addFeatures(t,e,r){for(const n of this.patternFeatures)this.addFeature(n,n.geometry,n.index,e,r,t.subdivisionGranularity);}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return !this.uploaded||this.programConfigurations.needsUpload}upload(t){this.uploaded||(0!==this.layoutVertexArray2.length&&(this.layoutVertexBuffer2=t.createVertexBuffer(this.layoutVertexArray2,pu)),this.layoutVertexBuffer=t.createVertexBuffer(this.layoutVertexArray,cu),this.indexBuffer=t.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(t),this.uploaded=true;}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy());}lineFeatureClips(t){if(t.properties&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_start")&&Object.prototype.hasOwnProperty.call(t.properties,"mapbox_clip_end"))return {start:+t.properties.mapbox_clip_start,end:+t.properties.mapbox_clip_end}}addFeature(t,e,r,n,i,s){const a=this.layers[0].layout,o=a.get("line-join").evaluate(t,{}),l=a.get("line-cap"),u=a.get("line-miter-limit"),c=a.get("line-round-limit");this.lineClips=this.lineFeatureClips(t);for(const r of e)this.addLine(r,t,o,l,u,c,n,s);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,i,n);}addLine(t,e,r,n,i,s,a,o){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,t=Il(t,a?o.line.getGranularityForZoomLevel(a.z):1),this.lineClips){this.lineClipsArray.push(this.lineClips);for(let e=0;e=2&&t[u-1].equals(t[u-2]);)u--;let c=0;for(;c0;if(w&&e>c){const t=f.dist(d);if(t>2*h){const e=f.sub(f.sub(d)._mult(h/t)._round());this.updateDistance(d,e),this.addCurrentVertex(e,m,0,0,p),d=e;}}const S=d&&y;let A=S?r:l?"butt":n;if(S&&"round"===A&&(vi&&(A="bevel"),"bevel"===A&&(v>2&&(A="flipbevel"),v100)a=g.mult(-1);else {const t=v*m.add(g).mag()/m.sub(g).mag();a._perp()._mult(t*(_?-1:1));}this.addCurrentVertex(f,a,0,0,p),this.addCurrentVertex(f,a.mult(-1),0,0,p);}else if("bevel"===A||"fakeround"===A){const t=-Math.sqrt(v*v-1),e=_?t:0,r=_?0:t;if(d&&this.addCurrentVertex(f,m,e,r,p),"fakeround"===A){const t=Math.round(180*b/Math.PI/20);for(let e=1;e2*h){const e=f.add(y.sub(f)._mult(h/t)._round());this.updateDistance(f,e),this.addCurrentVertex(e,g,0,0,p),f=e;}}}}addCurrentVertex(t,e,r,n,i,s=false){const a=e.y*n-e.x,o=-e.y-e.x*n;this.addHalfVertex(t,e.x+e.y*r,e.y-e.x*r,s,false,r,i),this.addHalfVertex(t,a,o,s,true,-n,i),this.distance>yu/2&&0===this.totalDistance&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(t,e,r,n,i,s));}addHalfVertex({x:t,y:e},r,n,i,s,a,o){const l=.5*(this.lineClips?this.scaledDistance*(yu-1):this.scaledDistance);this.layoutVertexArray.emplaceBack((t<<1)+(i?1:0),(e<<1)+(s?1:0),Math.round(63*r)+128,Math.round(63*n)+128,1+(0===a?0:a<0?-1:1)|(63&l)<<2,l>>6),this.lineClips&&this.layoutVertexArray2.emplaceBack((this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start),this.lineClipsArray.length);const u=o.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,u,this.e2),o.primitiveLength++),s?this.e2=u:this.e1=u;}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance;}updateDistance(t,e){this.distance+=t.dist(e),this.updateScaledDistance();}}let gu,xu;Ui("LineBucket",mu,{omit:["layers","patternFeatures"]});var vu={get paint(){return xu=xu||new As({"line-opacity":new bs(ht.paint_line["line-opacity"]),"line-color":new bs(ht.paint_line["line-color"]),"line-translate":new vs(ht.paint_line["line-translate"]),"line-translate-anchor":new vs(ht.paint_line["line-translate-anchor"]),"line-width":new bs(ht.paint_line["line-width"]),"line-gap-width":new bs(ht.paint_line["line-gap-width"]),"line-offset":new bs(ht.paint_line["line-offset"]),"line-blur":new bs(ht.paint_line["line-blur"]),"line-dasharray":new _s(ht.paint_line["line-dasharray"]),"line-pattern":new ws(ht.paint_line["line-pattern"]),"line-gradient":new Ss(ht.paint_line["line-gradient"])})},get layout(){return gu=gu||new As({"line-cap":new vs(ht.layout_line["line-cap"]),"line-join":new bs(ht.layout_line["line-join"]),"line-miter-limit":new vs(ht.layout_line["line-miter-limit"]),"line-round-limit":new vs(ht.layout_line["line-round-limit"]),"line-sort-key":new bs(ht.layout_line["line-sort-key"])})}};class bu extends bs{possiblyEvaluate(t,e){return e=new cs(Math.floor(e.zoom),{now:e.now,fadeDuration:e.fadeDuration,zoomHistory:e.zoomHistory,transition:e.transition}),super.possiblyEvaluate(t,e)}evaluate(t,e,r,n){return e=F({},e,{zoom:Math.floor(e.zoom)}),super.evaluate(t,e,r,n)}}let wu;class _u extends Ms{constructor(t){super(t,vu),this.gradientVersion=0,wu||(wu=new bu(vu.paint.properties["line-width"].specification),wu.useIntegerZoom=true);}_handleSpecialPaintPropertyUpdate(t){if("line-gradient"===t){const t=this.gradientExpression();this.stepInterpolant=!!function(t){return undefined!==t._styleExpression}(t)&&t._styleExpression.expression instanceof Qe,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER;}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(t,e){super.recalculate(t,e),this.paint._values["line-floorwidth"]=wu.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,t);}createBucket(t){return new mu(t)}queryRadius(t){const e=t,r=Su(Ao("line-width",this,e),Ao("line-gap-width",this,e)),n=Ao("line-offset",this,e);return r/2+Math.abs(n)+ko(this.paint.get("line-translate"))}queryIntersectsFeature({queryGeometry:t,feature:e,featureState:r,geometry:n,transform:i,pixelsToTileUnits:s}){const a=Mo(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),-i.bearingInRadians,s),o=s/2*Su(this.paint.get("line-width").evaluate(e,r),this.paint.get("line-gap-width").evaluate(e,r)),u=this.paint.get("line-offset").evaluate(e,r);return u&&(n=function(t,e){const r=[];for(let n=0;n=3)for(let e=0;e0?e+2*t:t}const Au=Cs([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),ku=Cs([{name:"a_projected_pos",components:3,type:"Float32"}],4);Cs([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const Mu=Cs([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_box_real",components:2,type:"Int16"}]);Cs([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const Iu=Cs([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),zu=Cs([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function Pu(t,e,r){return t.sections.forEach((t=>{t.text=function(t,e,r){const n=e.layout.get("text-transform").evaluate(r,{});return "uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),us.applyArabicShaping&&(t=us.applyArabicShaping(t)),t}(t.text,e,r);})),t}Cs([{name:"triangle",components:3,type:"Uint16"}]),Cs([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),Cs([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]),Cs([{type:"Float32",name:"offsetX"}]),Cs([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]),Cs([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);const Cu={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};var Bu,Vu,Eu,Tu=24,Fu={};function $u(){return Bu||(Bu=1,Fu.read=function(t,e,r,n,i){var s,a,o=8*i-n-1,l=(1<>1,c=-7,h=r?i-1:0,p=r?-1:1,f=t[e+h];for(h+=p,s=f&(1<<-c)-1,f>>=-c,c+=o;c>0;s=256*s+t[e+h],h+=p,c-=8);for(a=s&(1<<-c)-1,s>>=-c,c+=n;c>0;a=256*a+t[e+h],h+=p,c-=8);if(0===s)s=1-u;else {if(s===l)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),s-=u;}return (f?-1:1)*a*Math.pow(2,s-n)},Fu.write=function(t,e,r,n,i,s){var a,o,l,u=8*s-i-1,c=(1<>1,p=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:s-1,d=n?1:-1,y=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(o=isNaN(e)?1:0,a=c):(a=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-a))<1&&(a--,l*=2),(e+=a+h>=1?p/l:p*Math.pow(2,1-h))*l>=2&&(a++,l/=2),a+h>=c?(o=0,a=c):a+h>=1?(o=(e*l-1)*Math.pow(2,i),a+=h):(o=e*Math.pow(2,h-1)*Math.pow(2,i),a=0));i>=8;t[r+f]=255&o,f+=d,o/=256,i-=8);for(a=a<0;t[r+f]=255&a,f+=d,a/=256,u-=8);t[r+f-d]|=128*y;}),Fu}function Lu(){if(Eu)return Vu;Eu=1,Vu=e;var t=$u();function e(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length;}e.Varint=0,e.Fixed64=1,e.Bytes=2,e.Fixed32=5;var r=4294967296,n=1/r,i="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");function s(t){return t.type===e.Bytes?t.readVarint()+t.pos:t.pos+1}function a(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function o(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i];}function l(t,e){for(var r=0;r>>8,t[r+2]=e>>>16,t[r+3]=e>>>24;}function v(t,e){return (t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}return e.prototype={destroy:function(){this.buf=null;},readFields:function(t,e,r){for(r=r||this.length;this.pos>3,s=this.pos;this.type=7&n,t(i,e,this),this.pos===s&&this.skip(n);}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=g(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=v(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=g(this.buf,this.pos)+g(this.buf,this.pos+4)*r;return this.pos+=8,t},readSFixed64:function(){var t=g(this.buf,this.pos)+v(this.buf,this.pos+4)*r;return this.pos+=8,t},readFloat:function(){var e=t.read(this.buf,this.pos,true,23,4);return this.pos+=4,e},readDouble:function(){var e=t.read(this.buf,this.pos,true,52,8);return this.pos+=8,e},readVarint:function(t){var e,r,n=this.buf;return e=127&(r=n[this.pos++]),r<128?e:(e|=(127&(r=n[this.pos++]))<<7,r<128?e:(e|=(127&(r=n[this.pos++]))<<14,r<128?e:(e|=(127&(r=n[this.pos++]))<<21,r<128?e:function(t,e,r){var n,i,s=r.buf;if(n=(112&(i=s[r.pos++]))>>4,i<128)return a(t,n,e);if(n|=(127&(i=s[r.pos++]))<<3,i<128)return a(t,n,e);if(n|=(127&(i=s[r.pos++]))<<10,i<128)return a(t,n,e);if(n|=(127&(i=s[r.pos++]))<<17,i<128)return a(t,n,e);if(n|=(127&(i=s[r.pos++]))<<24,i<128)return a(t,n,e);if(n|=(1&(i=s[r.pos++]))<<31,i<128)return a(t,n,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=n[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(true)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&i?function(t,e,r){return i.decode(t.subarray(e,r))}(this.buf,e,t):function(t,e,r){for(var n="",i=e;i239?4:l>223?3:l>191?2:1;if(i+c>r)break;1===c?l<128&&(u=l):2===c?128==(192&(s=t[i+1]))&&(u=(31&l)<<6|63&s)<=127&&(u=null):3===c?(a=t[i+2],128==(192&(s=t[i+1]))&&128==(192&a)&&((u=(15&l)<<12|(63&s)<<6|63&a)<=2047||u>=55296&&u<=57343)&&(u=null)):4===c&&(a=t[i+2],o=t[i+3],128==(192&(s=t[i+1]))&&128==(192&a)&&128==(192&o)&&((u=(15&l)<<18|(63&s)<<12|(63&a)<<6|63&o)<=65535||u>=1114112)&&(u=null)),null===u?(u=65533,c=1):u>65535&&(u-=65536,n+=String.fromCharCode(u>>>10&1023|55296),u=56320|1023&u),n+=String.fromCharCode(u),i+=c;}return n}(this.buf,e,t)},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,r){if(this.type!==e.Bytes)return t.push(this.readVarint(r));var n=s(this);for(t=t||[];this.pos127;);else if(r===e.Bytes)this.pos=this.readVarint()+this.pos;else if(r===e.Fixed32)this.pos+=4;else {if(r!==e.Fixed64)throw new Error("Unimplemented type: "+r);this.pos+=8;}},writeTag:function(t,e){this.writeVarint(t<<3|e);},realloc:function(t){for(var e=this.length||16;e268435455||t<0?function(t,e){var r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(r=~(-t%4294967296))?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,r.buf[r.pos]=127&(t>>>=7);}(r,0,e),function(t,e){var r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t)))));}(n,e);}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))));},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t);},writeBoolean:function(t){this.writeVarint(Boolean(t));},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,r){for(var n,i,s=0;s55295&&n<57344){if(!i){n>56319||s+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);var r=this.pos-e;r>=128&&o(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;},writeFloat:function(e){this.realloc(4),t.write(this.buf,e,this.pos,true,23,4),this.pos+=4;},writeDouble:function(e){this.realloc(8),t.write(this.buf,e,this.pos,true,52,8),this.pos+=8;},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r=128&&o(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;},writeMessage:function(t,r,n){this.writeTag(t,e.Bytes),this.writeRawMessage(r,n);},writePackedVarint:function(t,e){e.length&&this.writeMessage(t,l,e);},writePackedSVarint:function(t,e){e.length&&this.writeMessage(t,u,e);},writePackedBoolean:function(t,e){e.length&&this.writeMessage(t,p,e);},writePackedFloat:function(t,e){e.length&&this.writeMessage(t,c,e);},writePackedDouble:function(t,e){e.length&&this.writeMessage(t,h,e);},writePackedFixed32:function(t,e){e.length&&this.writeMessage(t,f,e);},writePackedSFixed32:function(t,e){e.length&&this.writeMessage(t,d,e);},writePackedFixed64:function(t,e){e.length&&this.writeMessage(t,y,e);},writePackedSFixed64:function(t,e){e.length&&this.writeMessage(t,m,e);},writeBytesField:function(t,r){this.writeTag(t,e.Bytes),this.writeBytes(r);},writeFixed32Field:function(t,r){this.writeTag(t,e.Fixed32),this.writeFixed32(r);},writeSFixed32Field:function(t,r){this.writeTag(t,e.Fixed32),this.writeSFixed32(r);},writeFixed64Field:function(t,r){this.writeTag(t,e.Fixed64),this.writeFixed64(r);},writeSFixed64Field:function(t,r){this.writeTag(t,e.Fixed64),this.writeSFixed64(r);},writeVarintField:function(t,r){this.writeTag(t,e.Varint),this.writeVarint(r);},writeSVarintField:function(t,r){this.writeTag(t,e.Varint),this.writeSVarint(r);},writeStringField:function(t,r){this.writeTag(t,e.Bytes),this.writeString(r);},writeFloatField:function(t,r){this.writeTag(t,e.Fixed32),this.writeFloat(r);},writeDoubleField:function(t,r){this.writeTag(t,e.Fixed64),this.writeDouble(r);},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e));}},Vu}var Du=r(Lu());const Ou=3;function Ru(t,e,r){1===t&&r.readMessage(ju,e);}function ju(t,e,r){if(3===t){const{id:t,bitmap:n,width:i,height:s,left:a,top:o,advance:l}=r.readMessage(Nu,{});e.push({id:t,bitmap:new Do({width:i+2*Ou,height:s+2*Ou},n),metrics:{width:i,height:s,left:a,top:o,advance:l}});}}function Nu(t,e,r){1===t?e.id=r.readVarint():2===t?e.bitmap=r.readBytes():3===t?e.width=r.readVarint():4===t?e.height=r.readVarint():5===t?e.left=r.readSVarint():6===t?e.top=r.readSVarint():7===t&&(e.advance=r.readVarint());}const Uu=Ou;function qu(t){let e=0,r=0;for(const n of t)e+=n.w*n.h,r=Math.max(r,n.w);t.sort(((t,e)=>e.h-t.h));const n=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(e/.95)),r),h:1/0}];let i=0,s=0;for(const e of t)for(let t=n.length-1;t>=0;t--){const r=n[t];if(!(e.w>r.w||e.h>r.h)){if(e.x=r.x,e.y=r.y,s=Math.max(s,e.y+e.h),i=Math.max(i,e.x+e.w),e.w===r.w&&e.h===r.h){const e=n.pop();t=0&&r>=t&&Qu[this.text.charCodeAt(r)];r--)e--;this.text=this.text.substring(t,e),this.sectionIndex=this.sectionIndex.slice(t,e);}substring(t,e){const r=new Ju;return r.text=this.text.substring(t,e),r.sectionIndex=this.sectionIndex.slice(t,e),r.sections=this.sections,r}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce(((t,e)=>Math.max(t,this.sections[e].scale)),0)}addTextSection(t,e){this.text+=t.text,this.sections.push(Yu.forText(t.scale,t.fontStack||e));const r=this.sections.length-1;for(let e=0;e=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function Wu(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y){const m=Ju.fromFeature(e,s);let g;p===t.ai.vertical&&m.verticalizePunctuation();const{processBidirectionalText:x,processStyledBidirectionalText:v}=us;if(x&&1===m.sections.length){g=[];const t=x(m.toString(),oc(m,c,a,r,i,d));for(const e of t){const t=new Ju;t.text=e,t.sections=m.sections;for(let r=0;r0&&n>_&&(_=n);}else {const t=n[y.fontStack],e=t&&t[g];if(e&&e.rect)S=e.rect,b=e.metrics;else {const t=r[y.fontStack],e=t&&t[g];if(!e)continue;b=e.metrics;}x=(s-y.scale)*Tu;}M?(e.verticalizable=true,w.push({glyph:g,imageName:A,x:f,y:d+x,vertical:M,scale:y.scale,fontStack:y.fontStack,sectionIndex:m,metrics:b,rect:S}),f+=k*y.scale+c):(w.push({glyph:g,imageName:A,x:f,y:d+x,vertical:M,scale:y.scale,fontStack:y.fontStack,sectionIndex:m,metrics:b,rect:S}),f+=b.advance*y.scale+c);}0!==w.length&&(y=Math.max(f-c,y),uc(w,0,w.length-1,g,_)),f=0;const S=a*s+_;b.lineOffset=Math.max(_,l),d+=S,m=Math.max(S,m),++x;}var v;const b=d-Hu,{horizontalAlign:w,verticalAlign:_}=lc(o);(((function(t,e,r,n,i,s,a,o,l){const u=(e-r)*i;let c=0;c=s!==a?-o*n-Hu:(-n*l+.5)*a;for(const e of t)for(const t of e.positionedGlyphs)t.x+=u,t.y+=c;})))(e.positionedLines,g,w,_,y,m,a,b,s.length),e.top+=-_*b,e.bottom=e.top+b,e.left+=-w*y,e.right=e.left+y;}(w,r,n,i,g,o,l,u,p,c,f,y),!function(t){for(const e of t)if(0!==e.positionedGlyphs.length)return false;return true}(b)&&w}const Qu={9:true,10:true,11:true,12:true,13:true,32:true},tc={10:true,32:true,38:true,41:true,43:true,45:true,47:true,173:true,183:true,8203:true,8208:true,8211:true,8231:true},ec={40:true};function rc(t,e,r,n,i,s){if(e.imageName){const t=n[e.imageName];return t?t.displaySize[0]*e.scale*Tu/s+i:0}{const n=r[e.fontStack],s=n&&n[t];return s?s.metrics.advance*e.scale+i:0}}function nc(t,e,r,n){const i=Math.pow(t-e,2);return n?t=0;let u=0;for(let r=0;ru){const t=Math.ceil(s/u);i*=t/a,a=t;}return {x1:n,y1:i,x2:n+s,y2:i+a}}function pc(t,e,r,n,i,s){const a=t.image;let o;if(a.content){const t=a.content,e=a.pixelRatio||1;o=[t[0]/e,t[1]/e,a.displaySize[0]-t[2]/e,a.displaySize[1]-t[3]/e];}const l=e.left*s,u=e.right*s;let c,h,p,f;"width"===r||"both"===r?(f=i[0]+l-n[3],h=i[0]+u+n[1]):(f=i[0]+(l+u-a.displaySize[0])/2,h=f+a.displaySize[0]);const d=e.top*s,y=e.bottom*s;return "height"===r||"both"===r?(c=i[1]+d-n[0],p=i[1]+y+n[2]):(c=i[1]+(d+y-a.displaySize[1])/2,p=c+a.displaySize[1]),{image:a,top:c,right:h,bottom:p,left:f,collisionPadding:o}}const fc=255,dc=128,yc=fc*dc;function mc(t,e){const{expression:r}=e;if("constant"===r.kind)return {kind:"constant",layoutSize:r.evaluate(new cs(t+1))};if("source"===r.kind)return {kind:"source"};{const{zoomStops:e,interpolationType:n}=r;let i=0;for(;it.id)),this.index=e.index,this.pixelRatio=e.pixelRatio,this.sourceLayerIndex=e.sourceLayerIndex,this.hasPattern=false,this.hasRTLText=false,this.sortKeyRanges=[],this.collisionCircleArray=[];const r=this.layers[0]._unevaluatedLayout._values;this.textSizeData=mc(this.zoom,r["text-size"]),this.iconSizeData=mc(this.zoom,r["icon-size"]);const n=this.layers[0].layout,i=n.get("symbol-sort-key"),s=n.get("symbol-z-order");this.canOverlap="never"!==gc(n,"text-overlap","text-allow-overlap")||"never"!==gc(n,"icon-overlap","icon-allow-overlap")||n.get("text-ignore-placement")||n.get("icon-ignore-placement"),this.sortFeaturesByKey="viewport-y"!==s&&!i.isConstant(),this.sortFeaturesByY=("viewport-y"===s||"auto"===s&&!this.sortFeaturesByKey)&&this.canOverlap,"point"===n.get("symbol-placement")&&(this.writingModes=n.get("text-writing-mode").map((e=>t.ai[e]))),this.stateDependentLayerIds=this.layers.filter((t=>t.isStateDependent())).map((t=>t.id)),this.sourceID=e.sourceID;}createArrays(){this.text=new Sc(new ro(this.layers,this.zoom,(t=>/^text/.test(t)))),this.icon=new Sc(new ro(this.layers,this.zoom,(t=>/^icon/.test(t)))),this.glyphOffsetArray=new oa,this.lineVertexArray=new la,this.symbolInstances=new aa,this.textAnchorOffsets=new ca;}calculateGlyphDependencies(t,e,r,n,i){for(let s=0;s0)&&("constant"!==a.value.kind||a.value.value.length>0),c="constant"!==l.value.kind||!!l.value.value||Object.keys(l.parameters).length>0,h=s.get("symbol-sort-key");if(this.features=[],!u&&!c)return;const p=r.iconDependencies,f=r.glyphDependencies,d=r.availableImages,y=new cs(this.zoom);for(const{feature:r,id:o,index:l,sourceLayerIndex:m}of e){const e=i._featureFilter.needGeometry,g=lo(r,e);if(!i._featureFilter.filter(y,g,n))continue;let x,v;if(e||(g.geometry=oo(r)),u){const t=i.getValueAndResolveTokens("text-field",g,n,d),e=xe.factory(t),r=this.hasRTLText=this.hasRTLText||_c(e);(!r||"unavailable"===us.getRTLTextPluginStatus()||r&&us.isParsed())&&(x=Pu(e,i,g));}if(c){const t=i.getValueAndResolveTokens("icon-image",g,n,d);v=t instanceof Se?t:Se.fromString(t);}if(!x&&!v)continue;const b=this.sortFeaturesByKey?h.evaluate(g,{},n):undefined;if(this.features.push({id:o,text:x,icon:v,index:l,sourceLayerIndex:m,geometry:g.geometry,properties:r.properties,type:xc[r.type],sortKey:b}),v&&(p[v.name]=true),x){const e=a.evaluate(g,{},n).join(","),r="viewport"!==s.get("text-rotation-alignment")&&"point"!==s.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(t.ai.vertical)>=0;for(const t of x.sections)if(t.image)p[t.image.name]=true;else {const n=Ji(x.toString()),i=t.fontStack||e,s=f[i]=f[i]||{};this.calculateGlyphDependencies(t.text,s,r,this.allowVerticalPlacement,n);}}}"line"===s.get("symbol-placement")&&(this.features=function(t){const e={},r={},n=[];let i=0;function s(e){n.push(t[e]),i++;}function a(t,e,i){const s=r[t];return delete r[t],r[e]=s,n[s].geometry[0].pop(),n[s].geometry[0]=n[s].geometry[0].concat(i[0]),s}function o(t,r,i){const s=e[r];return delete e[r],e[t]=s,n[s].geometry[0].shift(),n[s].geometry[0]=i[0].concat(n[s].geometry[0]),s}function l(t,e,r){const n=r?e[0][e[0].length-1]:e[0][0];return `${t}:${n.x}:${n.y}`}for(let u=0;ut.geometry))}(this.features)),this.sortFeaturesByKey&&this.features.sort(((t,e)=>t.sortKey-e.sortKey));}update(t,e,r){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(t,e,this.layers,r),this.icon.programConfigurations.updatePaintArrays(t,e,this.layers,r));}isEmpty(){return 0===this.symbolInstances.length&&!this.hasRTLText}uploadPending(){return !this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(t){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(t),this.iconCollisionBox.upload(t)),this.text.upload(t,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(t,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=true;}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy();}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData();}addToLineVertexArray(t,e){const r=this.lineVertexArray.length;if(undefined!==t.segment){let r=t.dist(e[t.segment+1]),n=t.dist(e[t.segment]);const i={};for(let n=t.segment+1;n=0;r--)i[r]={x:e[r].x,y:e[r].y,tileUnitDistanceFromAnchor:n},r>0&&(n+=e[r-1].dist(e[r]));for(let t=0;t0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(t,e){const r=t.placedSymbolArray.get(e),n=r.vertexStartIndex+4*r.numGlyphs;for(let e=r.vertexStartIndex;en[t]-n[e]||i[e]-i[t])),s}addToSortKeyRanges(t,e){const r=this.sortKeyRanges[this.sortKeyRanges.length-1];r&&r.sortKey===e?r.symbolInstanceEnd=t+1:this.sortKeyRanges.push({sortKey:e,symbolInstanceStart:t,symbolInstanceEnd:t+1});}sortFeatures(t){if(this.sortFeaturesByY&&this.sortedAngle!==t&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const t of this.symbolInstanceIndexes){const e=this.symbolInstances.get(t);this.featureSortOrder.push(e.featureIndex),[e.rightJustifiedTextSymbolIndex,e.centerJustifiedTextSymbolIndex,e.leftJustifiedTextSymbolIndex].forEach(((t,e,r)=>{t>=0&&r.indexOf(t)===e&&this.addIndicesForPlacedSymbol(this.text,t);})),e.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,e.verticalPlacedTextSymbolIndex),e.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.placedIconSymbolIndex),e.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,e.verticalPlacedIconSymbolIndex);}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}}}let Mc,Ic;Ui("SymbolBucket",kc,{omit:["layers","collisionBoxArray","features","compareText"]}),kc.MAX_GLYPHS=65535,kc.addDynamicAttributes=wc;var zc={get paint(){return Ic=Ic||new As({"icon-opacity":new bs(ht.paint_symbol["icon-opacity"]),"icon-color":new bs(ht.paint_symbol["icon-color"]),"icon-halo-color":new bs(ht.paint_symbol["icon-halo-color"]),"icon-halo-width":new bs(ht.paint_symbol["icon-halo-width"]),"icon-halo-blur":new bs(ht.paint_symbol["icon-halo-blur"]),"icon-translate":new vs(ht.paint_symbol["icon-translate"]),"icon-translate-anchor":new vs(ht.paint_symbol["icon-translate-anchor"]),"text-opacity":new bs(ht.paint_symbol["text-opacity"]),"text-color":new bs(ht.paint_symbol["text-color"],{runtimeType:Bt,getOverride:t=>t.textColor,hasOverride:t=>!!t.textColor}),"text-halo-color":new bs(ht.paint_symbol["text-halo-color"]),"text-halo-width":new bs(ht.paint_symbol["text-halo-width"]),"text-halo-blur":new bs(ht.paint_symbol["text-halo-blur"]),"text-translate":new vs(ht.paint_symbol["text-translate"]),"text-translate-anchor":new vs(ht.paint_symbol["text-translate-anchor"])})},get layout(){return Mc=Mc||new As({"symbol-placement":new vs(ht.layout_symbol["symbol-placement"]),"symbol-spacing":new vs(ht.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new vs(ht.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new bs(ht.layout_symbol["symbol-sort-key"]),"symbol-z-order":new vs(ht.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new vs(ht.layout_symbol["icon-allow-overlap"]),"icon-overlap":new vs(ht.layout_symbol["icon-overlap"]),"icon-ignore-placement":new vs(ht.layout_symbol["icon-ignore-placement"]),"icon-optional":new vs(ht.layout_symbol["icon-optional"]),"icon-rotation-alignment":new vs(ht.layout_symbol["icon-rotation-alignment"]),"icon-size":new bs(ht.layout_symbol["icon-size"]),"icon-text-fit":new vs(ht.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new vs(ht.layout_symbol["icon-text-fit-padding"]),"icon-image":new bs(ht.layout_symbol["icon-image"]),"icon-rotate":new bs(ht.layout_symbol["icon-rotate"]),"icon-padding":new bs(ht.layout_symbol["icon-padding"]),"icon-keep-upright":new vs(ht.layout_symbol["icon-keep-upright"]),"icon-offset":new bs(ht.layout_symbol["icon-offset"]),"icon-anchor":new bs(ht.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new vs(ht.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new vs(ht.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new vs(ht.layout_symbol["text-rotation-alignment"]),"text-field":new bs(ht.layout_symbol["text-field"]),"text-font":new bs(ht.layout_symbol["text-font"]),"text-size":new bs(ht.layout_symbol["text-size"]),"text-max-width":new bs(ht.layout_symbol["text-max-width"]),"text-line-height":new vs(ht.layout_symbol["text-line-height"]),"text-letter-spacing":new bs(ht.layout_symbol["text-letter-spacing"]),"text-justify":new bs(ht.layout_symbol["text-justify"]),"text-radial-offset":new bs(ht.layout_symbol["text-radial-offset"]),"text-variable-anchor":new vs(ht.layout_symbol["text-variable-anchor"]),"text-variable-anchor-offset":new bs(ht.layout_symbol["text-variable-anchor-offset"]),"text-anchor":new bs(ht.layout_symbol["text-anchor"]),"text-max-angle":new vs(ht.layout_symbol["text-max-angle"]),"text-writing-mode":new vs(ht.layout_symbol["text-writing-mode"]),"text-rotate":new bs(ht.layout_symbol["text-rotate"]),"text-padding":new vs(ht.layout_symbol["text-padding"]),"text-keep-upright":new vs(ht.layout_symbol["text-keep-upright"]),"text-transform":new bs(ht.layout_symbol["text-transform"]),"text-offset":new bs(ht.layout_symbol["text-offset"]),"text-allow-overlap":new vs(ht.layout_symbol["text-allow-overlap"]),"text-overlap":new vs(ht.layout_symbol["text-overlap"]),"text-ignore-placement":new vs(ht.layout_symbol["text-ignore-placement"]),"text-optional":new vs(ht.layout_symbol["text-optional"])})}};class Pc{constructor(t){if(undefined===t.property.overrides)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=t.property.overrides?t.property.overrides.runtimeType:It,this.defaultValue=t;}evaluate(t){if(t.formattedSection){const e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default}eachChild(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression);}outputDefined(){return false}serialize(){return null}}Ui("FormatSectionOverride",Pc,{omit:["defaultValue"]});class Cc extends Ms{constructor(t){super(t,zc);}recalculate(t,e){if(super.recalculate(t,e),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]="map"===this.layout.get("text-rotation-alignment")?"map":"viewport"),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){const t=this.layout.get("text-writing-mode");if(t){const e=[];for(const r of t)e.indexOf(r)<0&&e.push(r);this.layout._values["text-writing-mode"]=e;}else this.layout._values["text-writing-mode"]=["horizontal"];}this._setPaintOverrides();}getValueAndResolveTokens(t,e,r,n){const i=this.layout.get(t).evaluate(e,{},r,n),s=this._unevaluatedLayout._values[t];return s.isDataDriven()||jn(s.value)||!i?i:function(t,e){return e.replace(/{([^{}]+)}/g,((e,r)=>t&&r in t?String(t[r]):""))}(e.properties,i)}createBucket(t){return new kc(t)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(const t of zc.paint.overridableProperties){if(!Cc.hasPaintOverride(this.layout,t))continue;const e=this.paint.get(t),r=new Pc(e),n=new Rn(r,e.property.specification);let i=null;i="constant"===e.value.kind||"source"===e.value.kind?new Un("source",n):new qn("composite",n,e.value.zoomStops),this.paint._values[t]=new gs(e.property,i,e.parameters);}}_handleOverridablePaintPropertyUpdate(t,e,r){return !(!this.layout||e.isDataDriven()||r.isDataDriven())&&Cc.hasPaintOverride(this.layout,t)}static hasPaintOverride(t,e){const r=t.get("text-field"),n=zc.paint.properties[e];let i=false;const s=t=>{for(const e of t)if(n.overrides&&n.overrides.hasOverride(e))return void(i=true)};if("constant"===r.value.kind&&r.value.value instanceof xe)s(r.value.value.sections);else if("source"===r.value.kind){const t=e=>{i||(e instanceof Pe&&Ie(e.value)===$t?s(e.value.sections):e instanceof br?s(e.sections):e.eachChild(t));},e=r.value;e._styleExpression&&t(e._styleExpression.expression);}return i}}let Bc;var Vc={get paint(){return Bc=Bc||new As({"background-color":new vs(ht.paint_background["background-color"]),"background-pattern":new _s(ht.paint_background["background-pattern"]),"background-opacity":new vs(ht.paint_background["background-opacity"])})}};class Ec extends Ms{constructor(t){super(t,Vc);}}let Tc;var Fc={get paint(){return Tc=Tc||new As({"raster-opacity":new vs(ht.paint_raster["raster-opacity"]),"raster-hue-rotate":new vs(ht.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new vs(ht.paint_raster["raster-brightness-min"]),"raster-brightness-max":new vs(ht.paint_raster["raster-brightness-max"]),"raster-saturation":new vs(ht.paint_raster["raster-saturation"]),"raster-contrast":new vs(ht.paint_raster["raster-contrast"]),"raster-resampling":new vs(ht.paint_raster["raster-resampling"]),"raster-fade-duration":new vs(ht.paint_raster["raster-fade-duration"])})}};class $c extends Ms{constructor(t){super(t,Fc);}}class Lc extends Ms{constructor(t){super(t,{}),this.onAdd=t=>{this.implementation.onAdd&&this.implementation.onAdd(t,t.painter.context.gl);},this.onRemove=t=>{this.implementation.onRemove&&this.implementation.onRemove(t,t.painter.context.gl);},this.implementation=t;}is3D(){return "3d"===this.implementation.renderingMode}hasOffscreenPass(){return undefined!==this.implementation.prerender}recalculate(){}updateTransitions(){}hasTransition(){return false}serialize(){throw new Error("Custom layers cannot be serialized")}}class Dc{constructor(t){this._methodToThrottle=t,this._triggered=false,"undefined"!=typeof MessageChannel&&(this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=false,this._methodToThrottle();});}trigger(){this._triggered||(this._triggered=true,this._channel?this._channel.port1.postMessage(true):setTimeout((()=>{this._triggered=false,this._methodToThrottle();}),0));}remove(){delete this._channel,this._methodToThrottle=()=>{};}}const Oc=6371008.8;class Rc{constructor(t,e){if(isNaN(t)||isNaN(e))throw new Error(`Invalid LngLat object: (${t}, ${e})`);if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new Rc(T(this.lng,-180,180),this.lat)}toArray(){return [this.lng,this.lat]}toString(){return `LngLat(${this.lng}, ${this.lat})`}distanceTo(t){const e=Math.PI/180,r=this.lat*e,n=t.lat*e,i=Math.sin(r)*Math.sin(n)+Math.cos(r)*Math.cos(n)*Math.cos((t.lng-this.lng)*e);return Oc*Math.acos(Math.min(i,1))}static convert(t){if(t instanceof Rc)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new Rc(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new Rc(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}const jc=2*Math.PI*Oc;function Nc(t){return jc*Math.cos(t*Math.PI/180)}function Uc(t){return (180+t)/360}function qc(t){return (180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function Gc(t,e){return t/Nc(e)}function Zc(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}function Xc(t,e){return t*Nc(Zc(e))}class Kc{constructor(t,e,r=0){this.x=+t,this.y=+e,this.z=+r;}static fromLngLat(t,e=0){const r=Rc.convert(t);return new Kc(Uc(r.lng),qc(r.lat),Gc(e,r.lat))}toLngLat(){return new Rc(360*this.x-180,Zc(this.y))}toAltitude(){return Xc(this.z,this.y)}meterInMercatorCoordinateUnits(){return 1/jc*(t=Zc(this.y),1/Math.cos(t*Math.PI/180));var t;}}function Hc(t,e,r){var n=2*Math.PI*6378137/256/Math.pow(2,r);return [t*n-2*Math.PI*6378137/2,e*n-2*Math.PI*6378137/2]}class Yc{constructor(t,e,r){if(!function(t,e,r){return !(t<0||t>25||r<0||r>=Math.pow(2,t)||e<0||e>=Math.pow(2,t))}(t,e,r))throw new Error(`x=${e}, y=${r}, z=${t} outside of bounds. 0<=x<${Math.pow(2,t)}, 0<=y<${Math.pow(2,t)} 0<=z<=25 `);this.z=t,this.x=e,this.y=r,this.key=Qc(0,t,t,e,r);}equals(t){return this.z===t.z&&this.x===t.x&&this.y===t.y}url(t,e,r){const n=(s=this.y,a=this.z,o=Hc(256*(i=this.x),256*(s=Math.pow(2,a)-s-1),a),l=Hc(256*(i+1),256*(s+1),a),o[0]+","+o[1]+","+l[0]+","+l[1]);var i,s,a,o,l;const u=function(t,e,r){let n,i="";for(let s=t;s>0;s--)n=1<1?"@2x":"").replace(/{quadkey}/g,u).replace(/{bbox-epsg-3857}/g,n)}isChildOf(t){const e=this.z-t.z;return e>0&&t.x===this.x>>e&&t.y===this.y>>e}getTilePoint(t){const e=Math.pow(2,this.z);return new l((t.x*e-this.x)*M,(t.y*e-this.y)*M)}toString(){return `${this.z}/${this.x}/${this.y}`}}class Jc{constructor(t,e){this.wrap=t,this.canonical=e,this.key=Qc(t,e.z,e.z,e.x,e.y);}}class Wc{constructor(t,e,r,n,i){if(this.terrainRttPosMatrix32f=null,t= z; overscaledZ = ${t}; z = ${r}`);this.overscaledZ=t,this.wrap=e,this.canonical=new Yc(r,+n,+i),this.key=Qc(e,t,r,n,i);}clone(){return new Wc(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(t){return this.overscaledZ===t.overscaledZ&&this.wrap===t.wrap&&this.canonical.equals(t.canonical)}scaledTo(t){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const e=this.canonical.z-t;return t>this.canonical.z?new Wc(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new Wc(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)}calculateScaledKey(t,e){if(t>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${t}; overscaledZ = ${this.overscaledZ}`);const r=this.canonical.z-t;return t>this.canonical.z?Qc(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Qc(this.wrap*+e,t,t,this.canonical.x>>r,this.canonical.y>>r)}isChildOf(t){if(t.wrap!==this.wrap)return false;const e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e}children(t){if(this.overscaledZ>=t)return [new Wc(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return [new Wc(e,this.wrap,e,r,n),new Wc(e,this.wrap,e,r+1,n),new Wc(e,this.wrap,e,r,n+1),new Wc(e,this.wrap,e,r+1,n+1)]}isLessThan(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.ythis.max&&(this.max=r),r=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return (e+1)*this.stride+(t+1)}unpack(t,e,r){return t*this.redFactor+e*this.greenFactor+r*this.blueFactor-this.baseShift}getPixels(){return new Oo({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(t,e,r){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");let n=e*this.dim,i=e*this.dim+this.dim,s=r*this.dim,a=r*this.dim+this.dim;switch(e){case-1:n=i-1;break;case 1:i=n+1;}switch(r){case-1:s=a-1;break;case 1:a=s+1;}const o=-e*this.dim,l=-r*this.dim;for(let e=s;e=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${t} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[t]}}class rh{constructor(t,e,r,n,i){this.type="Feature",this._vectorTileFeature=t,t._z=e,t._x=r,t._y=n,this.properties=t.properties,this.id=i;}get geometry(){return undefined===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry}set geometry(t){this._geometry=t;}toJSON(){const t={geometry:this.geometry};for(const e in this)"_geometry"!==e&&"_vectorTileFeature"!==e&&(t[e]=this[e]);return t}}class nh{constructor(t,e){this.tileID=t,this.x=t.canonical.x,this.y=t.canonical.y,this.z=t.canonical.z,this.grid=new ji(M,16,0),this.grid3D=new ji(M,16,0),this.featureIndexArray=new pa,this.promoteId=e;}insert(t,e,r,n,i,s){const a=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(r,n,i);const o=s?this.grid3D:this.grid;for(let t=0;t=0&&n[3]>=0&&o.insert(a,n[0],n[1],n[2],n[3]);}}loadVTLayers(){return this.vtLayers||(this.vtLayers=new Yl.VectorTile(new Du(this.rawTileData)).layers,this.sourceLayerCoder=new eh(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers}query(t,e,r,n){this.loadVTLayers();const i=t.params,s=M/t.tileSize/t.scale,a=Yn(i.filter),o=t.queryGeometry,u=t.queryPadding*s,c=sh(o),h=this.grid.query(c.minX-u,c.minY-u,c.maxX+u,c.maxY+u),p=sh(t.cameraQueryGeometry),f=this.grid3D.query(p.minX-u,p.minY-u,p.maxX+u,p.maxY+u,((e,r,n,i)=>function(t,e,r,n,i){for(const s of t)if(e<=s.x&&r<=s.y&&n>=s.x&&i>=s.y)return true;const s=[new l(e,r),new l(e,i),new l(n,i),new l(n,r)];if(t.length>2)for(const e of s)if(_o(t,e))return true;for(let e=0;e(p||(p=oo(e)),r.queryIntersectsFeature({queryGeometry:o,feature:e,featureState:n,geometry:p,zoom:this.z,transform:t.transform,pixelsToTileUnits:s,pixelPosMatrix:t.pixelPosMatrix}))));}return d}loadMatchingFeature(t,e,r,n,i,s,a,o,l,u,c){const h=this.bucketLayerIDs[e];if(s&&!h.some((t=>s.has(t))))return;const p=this.sourceLayerCoder.decode(r),f=this.vtLayers[p].feature(n);if(i.needGeometry){const t=lo(f,true);if(!i.filter(new cs(this.tileID.overscaledZ),t,this.tileID.canonical))return}else if(!i.filter(new cs(this.tileID.overscaledZ),f))return;const d=this.getId(f,p);for(let e=0;e{const a=e instanceof xs?e.get(s):null;return a&&a.evaluate?a.evaluate(r,n,i):a}))}function sh(t){let e=1/0,r=1/0,n=-1/0,i=-1/0;for(const s of t)e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);return {minX:e,minY:r,maxX:n,maxY:i}}function ah(t,e){return e-t}function oh(t,e,r,n,i){const s=[];for(let a=0;a=n&&c.x>=n||(a.x>=n?a=new l(n,a.y+(n-a.x)/(c.x-a.x)*(c.y-a.y))._round():c.x>=n&&(c=new l(n,a.y+(n-a.x)/(c.x-a.x)*(c.y-a.y))._round()),a.y>=i&&c.y>=i||(a.y>=i?a=new l(a.x+(i-a.y)/(c.y-a.y)*(c.x-a.x),i)._round():c.y>=i&&(c=new l(a.x+(i-a.y)/(c.y-a.y)*(c.x-a.x),i)._round()),u&&a.equals(u[u.length-1])||(u=[a],s.push(u)),u.push(c)))));}}return s}Ui("FeatureIndex",nh,{omit:["rawTileData","sourceLayerCoder"]});class lh extends l{constructor(t,e,r,n){super(t,e),this.angle=r,undefined!==n&&(this.segment=n);}clone(){return new lh(this.x,this.y,this.angle,this.segment)}}function uh(t,e,r,n,i){if(undefined===e.segment||0===r)return true;let s=e,a=e.segment+1,o=0;for(;o>-r/2;){if(a--,a<0)return false;o-=t[a].dist(s),s=t[a];}o+=t[a].dist(t[a+1]),a++;const l=[];let u=0;for(;on;)u-=l.shift().angleDelta;if(u>i)return false;a++,o+=e.dist(r);}return true}function ch(t){let e=0;for(let r=0;ru){const c=(u-l)/s,h=or.number(n.x,i.x,c),p=or.number(n.y,i.y,c),f=new lh(h,p,i.angleTo(n),r);return f._round(),!a||uh(t,f,o,a,e)?f:undefined}l+=s;}}function dh(t,e,r,n,i,s,a,o,l){const u=hh(n,s,a),c=ph(n,i),h=c*a,p=0===t[0].x||t[0].x===l||0===t[0].y||t[0].y===l;return e-h=0&&g=0&&x=0&&p+u<=c){const r=new lh(g,x,y,e);r._round(),n&&!uh(t,r,s,n,i)||f.push(r);}}h+=d;}return o||f.length||a||(f=yh(t,h/2,r,n,i,s,a,true,l)),f}Ui("Anchor",lh);const mh=Gu;function gh(t,e,r,n){const i=[],s=t.image,a=s.pixelRatio,o=s.paddedRect.w-2*mh,u=s.paddedRect.h-2*mh;let c={x1:t.left,y1:t.top,x2:t.right,y2:t.bottom};const h=s.stretchX||[[0,o]],p=s.stretchY||[[0,u]],f=(t,e)=>t+e[1]-e[0],d=h.reduce(f,0),y=p.reduce(f,0),m=o-d,g=u-y;let x=0,v=d,b=0,w=y,_=0,S=m,A=0,k=g;if(s.content&&n){const e=s.content,r=e[2]-e[0],n=e[3]-e[1];(s.textFitWidth||s.textFitHeight)&&(c=hc(t)),x=xh(h,0,e[0]),b=xh(p,0,e[1]),v=xh(h,e[0],e[2]),w=xh(p,e[1],e[3]),_=e[0]-x,A=e[1]-b,S=r-v,k=n-w;}const M=c.x1,I=c.y1,z=c.x2-M,P=c.y2-I,C=(t,n,i,o)=>{const u=bh(t.stretch-x,v,z,M),c=wh(t.fixed-_,S,t.stretch,d),h=bh(n.stretch-b,w,P,I),p=wh(n.fixed-A,k,n.stretch,y),f=bh(i.stretch-x,v,z,M),m=wh(i.fixed-_,S,i.stretch,d),g=bh(o.stretch-b,w,P,I),C=wh(o.fixed-A,k,o.stretch,y),B=new l(u,h),V=new l(f,h),E=new l(f,g),T=new l(u,g),F=new l(c/a,p/a),$=new l(m/a,C/a),L=e*Math.PI/180;if(L){const t=Math.sin(L),e=Math.cos(L),r=[e,-t,t,e];B._matMult(r),V._matMult(r),T._matMult(r),E._matMult(r);}const D=t.stretch+t.fixed,O=n.stretch+n.fixed;return {tl:B,tr:V,bl:T,br:E,tex:{x:s.paddedRect.x+mh+D,y:s.paddedRect.y+mh+O,w:i.stretch+i.fixed-D,h:o.stretch+o.fixed-O},writingMode:undefined,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:F,pixelOffsetBR:$,minFontScaleX:S/a/z,minFontScaleY:k/a/P,isSDF:r}};if(n&&(s.stretchX||s.stretchY)){const t=vh(h,m,d),e=vh(p,g,y);for(let r=0;r0&&(n=Math.max(10,n),this.circleDiameter=n);}else {const u=(null===(h=s.image)||undefined===h?undefined:h.content)&&(s.image.textFitWidth||s.image.textFitHeight)?hc(s):{x1:s.left,y1:s.top,x2:s.right,y2:s.bottom};u.y1=u.y1*a-o[0],u.y2=u.y2*a+o[2],u.x1=u.x1*a-o[3],u.x2=u.x2*a+o[1];const p=s.collisionPadding;if(p&&(u.x1-=p[0]*a,u.y1-=p[1]*a,u.x2+=p[2]*a,u.y2+=p[3]*a),c){const t=new l(u.x1,u.y1),e=new l(u.x2,u.y1),r=new l(u.x1,u.y2),n=new l(u.x2,u.y2),i=c*Math.PI/180;t._rotate(i),e._rotate(i),r._rotate(i),n._rotate(i),u.x1=Math.min(t.x,e.x,r.x,n.x),u.x2=Math.max(t.x,e.x,r.x,n.x),u.y1=Math.min(t.y,e.y,r.y,n.y),u.y2=Math.max(t.y,e.y,r.y,n.y);}t.emplaceBack(e.x,e.y,u.x1,u.y1,u.x2,u.y2,r,n,i);}this.boxEndIndex=t.length;}}class Sh{constructor(t=[],e=((t,e)=>te?1:0)){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let t=(this.length>>1)-1;t>=0;t--)this._down(t);}push(t){this.data.push(t),this._up(this.length++);}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return --this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:r}=this,n=e[t];for(;t>0;){const i=t-1>>1,s=e[i];if(r(n,s)>=0)break;e[t]=s,t=i;}e[t]=n;}_down(t){const{data:e,compare:r}=this,n=this.length>>1,i=e[t];for(;t=0)break;e[t]=e[n],t=n;}e[t]=i;}}function Ah(t,e=1,r=false){let n=1/0,i=1/0,s=-1/0,a=-1/0;const o=t[0];for(let t=0;ts)&&(s=e.x),(!t||e.y>a)&&(a=e.y);}const u=Math.min(s-n,a-i);let c=u/2;const h=new Sh([],kh);if(0===u)return new l(n,i);for(let e=n;ep.d||!p.d)&&(p=n,r&&console.log("found best %d after %d probes",Math.round(1e4*n.d)/1e4,f)),n.max-p.d<=e||(c=n.h/2,h.push(new Mh(n.p.x-c,n.p.y-c,c,t)),h.push(new Mh(n.p.x+c,n.p.y-c,c,t)),h.push(new Mh(n.p.x-c,n.p.y+c,c,t)),h.push(new Mh(n.p.x+c,n.p.y+c,c,t)),f+=4);}return r&&(console.log(`num probes: ${f}`),console.log(`best distance: ${p.d}`)),p.p}function kh(t,e){return e.max-t.max}function Mh(t,e,r,n){this.p=new l(t,e),this.h=r,this.d=function(t,e){let r=false,n=1/0;for(let i=0;it.y!=o.y>t.y&&t.x<(o.x-i.x)*(t.y-i.y)/(o.y-i.y)+i.x&&(r=!r),n=Math.min(n,bo(t,i,o));}}return (r?1:-1)*Math.sqrt(n)}(this.p,n),this.max=this.d+this.h*Math.SQRT2;}var Ih;t.av=undefined,(Ih=t.av||(t.av={}))[Ih.center=1]="center",Ih[Ih.left=2]="left",Ih[Ih.right=3]="right",Ih[Ih.top=4]="top",Ih[Ih.bottom=5]="bottom",Ih[Ih["top-left"]=6]="top-left",Ih[Ih["top-right"]=7]="top-right",Ih[Ih["bottom-left"]=8]="bottom-left",Ih[Ih["bottom-right"]=9]="bottom-right";const zh=7,Ph=Number.POSITIVE_INFINITY;function Ch(t,e){return e[1]!==Ph?function(t,e,r){let n=0,i=0;switch(e=Math.abs(e),r=Math.abs(r),t){case"top-right":case"top-left":case"top":i=r-zh;break;case"bottom-right":case"bottom-left":case"bottom":i=-r+zh;}switch(t){case"top-right":case"bottom-right":case"right":n=-e;break;case"top-left":case"bottom-left":case"left":n=e;}return [n,i]}(t,e[0],e[1]):function(t,e){let r=0,n=0;e<0&&(e=0);const i=e/Math.SQRT2;switch(t){case"top-right":case"top-left":n=i-zh;break;case"bottom-right":case"bottom-left":n=-i+zh;break;case"bottom":n=-e+zh;break;case"top":n=e-zh;}switch(t){case"top-right":case"bottom-right":r=-i;break;case"top-left":case"bottom-left":r=i;break;case"left":r=e;break;case"right":r=-e;}return [r,n]}(t,e[0])}function Bh(t,e,r){var n;const i=t.layout,s=null===(n=i.get("text-variable-anchor-offset"))||undefined===n?undefined:n.evaluate(e,{},r);if(s){const t=s.values,e=[];for(let r=0;rt*Tu));n.startsWith("top")?i[1]-=zh:n.startsWith("bottom")&&(i[1]+=zh),e[r+1]=i;}return new _e(e)}const a=i.get("text-variable-anchor");if(a){let n;n=undefined!==t._unevaluatedLayout.getValue("text-radial-offset")?[i.get("text-radial-offset").evaluate(e,{},r)*Tu,Ph]:i.get("text-offset").evaluate(e,{},r).map((t=>t*Tu));const s=[];for(const t of a)s.push(t,Ch(t,n));return new _e(s)}return null}function Vh(t){switch(t){case"right":case"top-right":case"bottom-right":return "right";case"left":case"top-left":case"bottom-left":return "left"}return "center"}function Eh(e,r,n,i,s,a,o,l,u,c,h,p){let f=a.textMaxSize.evaluate(r,{});undefined===f&&(f=o);const d=e.layers[0].layout,y=d.get("icon-offset").evaluate(r,{},h),m=Fh(n.horizontal),g=o/24,x=e.tilePixelRatio*g,v=e.tilePixelRatio*f/24,b=e.tilePixelRatio*l,w=e.tilePixelRatio*d.get("symbol-spacing"),_=d.get("text-padding")*e.tilePixelRatio,S=function(t,e,r,n=1){const i=t.get("icon-padding").evaluate(e,{},r),s=i&&i.values;return [s[0]*n,s[1]*n,s[2]*n,s[3]*n]}(d,r,h,e.tilePixelRatio),A=d.get("text-max-angle")/180*Math.PI,k="viewport"!==d.get("text-rotation-alignment")&&"point"!==d.get("symbol-placement"),I="map"===d.get("icon-rotation-alignment")&&"point"!==d.get("symbol-placement"),z=d.get("symbol-placement"),P=w/2,C=d.get("icon-text-fit");let B;i&&"none"!==C&&(e.allowVerticalPlacement&&n.vertical&&(B=pc(i,n.vertical,C,d.get("icon-text-fit-padding"),y,g)),m&&(i=pc(i,m,C,d.get("icon-text-fit-padding"),y,g)));const V=h?p.line.getGranularityForZoomLevel(h.z):1,E=(l,p)=>{p.x<0||p.x>=M||p.y<0||p.y>=M||function(e,r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v,b,w,_,S,A,k){const M=e.addToLineVertexArray(r,n);let I,z,P,C,B=0,V=0,E=0,T=0,F=-1,$=-1;const L={};let D=Oa("");if(e.allowVerticalPlacement&&i.vertical){const t=l.layout.get("text-rotate").evaluate(w,{},A)+90;P=new _h(u,r,c,h,p,i.vertical,f,d,y,t),o&&(C=new _h(u,r,c,h,p,o,g,x,y,t));}if(s){const n=l.layout.get("icon-rotate").evaluate(w,{}),i="none"!==l.layout.get("icon-text-fit"),a=gh(s,n,S,i),f=o?gh(o,n,S,i):undefined;z=new _h(u,r,c,h,p,s,g,x,false,n),B=4*a.length;const d=e.iconSizeData;let y=null;"source"===d.kind?(y=[dc*l.layout.get("icon-size").evaluate(w,{})],y[0]>yc&&j(`${e.layerIds[0]}: Value for "icon-size" is >= ${fc}. Reduce your "icon-size".`)):"composite"===d.kind&&(y=[dc*_.compositeIconSizes[0].evaluate(w,{},A),dc*_.compositeIconSizes[1].evaluate(w,{},A)],(y[0]>yc||y[1]>yc)&&j(`${e.layerIds[0]}: Value for "icon-size" is >= ${fc}. Reduce your "icon-size".`)),e.addSymbols(e.icon,a,y,b,v,w,t.ai.none,r,M.lineStartIndex,M.lineLength,-1,A),F=e.icon.placedSymbolArray.length-1,f&&(V=4*f.length,e.addSymbols(e.icon,f,y,b,v,w,t.ai.vertical,r,M.lineStartIndex,M.lineLength,-1,A),$=e.icon.placedSymbolArray.length-1);}const O=Object.keys(i.horizontal);for(const n of O){const s=i.horizontal[n];if(!I){D=Oa(s.text);const t=l.layout.get("text-rotate").evaluate(w,{},A);I=new _h(u,r,c,h,p,s,f,d,y,t);}const o=1===s.positionedLines.length;if(E+=Th(e,r,s,a,l,y,w,m,M,i.vertical?t.ai.horizontal:t.ai.horizontalOnly,o?O:[n],L,F,_,A),o)break}i.vertical&&(T+=Th(e,r,i.vertical,a,l,y,w,m,M,t.ai.vertical,["vertical"],L,$,_,A));const R=I?I.boxStartIndex:e.collisionBoxArray.length,N=I?I.boxEndIndex:e.collisionBoxArray.length,U=P?P.boxStartIndex:e.collisionBoxArray.length,q=P?P.boxEndIndex:e.collisionBoxArray.length,G=z?z.boxStartIndex:e.collisionBoxArray.length,Z=z?z.boxEndIndex:e.collisionBoxArray.length,X=C?C.boxStartIndex:e.collisionBoxArray.length,K=C?C.boxEndIndex:e.collisionBoxArray.length;let H=-1;const Y=(t,e)=>t&&t.circleDiameter?Math.max(t.circleDiameter,e):e;H=Y(I,H),H=Y(P,H),H=Y(z,H),H=Y(C,H);const J=H>-1?1:0;J&&(H*=k/Tu),e.glyphOffsetArray.length>=kc.MAX_GLYPHS&&j("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),undefined!==w.sortKey&&e.addToSortKeyRanges(e.symbolInstances.length,w.sortKey);const W=Bh(l,w,A),[Q,tt]=function(e,r){const n=e.length,i=null==r?undefined:r.values;if((null==i?undefined:i.length)>0)for(let r=0;r=0?L.right:-1,L.center>=0?L.center:-1,L.left>=0?L.left:-1,L.vertical||-1,F,$,D,R,N,U,q,G,Z,X,K,c,E,T,B,V,J,0,f,H,Q,tt);}(e,p,l,n,i,s,B,e.layers[0],e.collisionBoxArray,r.index,r.sourceLayerIndex,e.index,x,[_,_,_,_],k,u,b,S,I,y,r,a,c,h,o);};if("line"===z)for(const t of oh(r.geometry,0,0,M,M)){const r=Il(t,V),s=dh(r,w,A,n.vertical||m,i,24,v,e.overscaling,M);for(const t of s)m&&$h(e,m.text,P,t)||E(r,t);}else if("line-center"===z){for(const t of r.geometry)if(t.length>1){const e=Il(t,V),r=fh(e,A,n.vertical||m,i,24,v);r&&E(e,r);}}else if("Polygon"===r.type)for(const t of Le(r.geometry,0)){const e=Ah(t,16);E(Il(t[0],V,true),new lh(e.x,e.y,0));}else if("LineString"===r.type)for(const t of r.geometry){const e=Il(t,V);E(e,new lh(e[0].x,e[0].y,0));}else if("Point"===r.type)for(const t of r.geometry)for(const e of t)E([e],new lh(e.x,e.y,0));}function Th(t,e,r,n,i,s,a,o,u,c,h,p,f,d,y){const m=function(t,e,r,n,i,s,a,o){const u=n.layout.get("text-rotate").evaluate(s,{})*Math.PI/180,c=[];for(const t of e.positionedLines)for(const n of t.positionedGlyphs){if(!n.rect)continue;const s=n.rect||{};let h=Uu+1,p=true,f=1,d=0;const y=(i||o)&&n.vertical,m=n.metrics.advance*n.scale/2;if(o&&e.verticalizable&&(d=t.lineOffset/2-(n.imageName?-(Tu-n.metrics.width*n.scale)/2:(n.scale-1)*Tu)),n.imageName){const t=a[n.imageName];p=t.sdf,f=t.pixelRatio,h=Gu/f;}const g=i?[n.x+m,n.y]:[0,0];let x=i?[0,0]:[n.x+m+r[0],n.y+r[1]-d],v=[0,0];y&&(v=x,x=[0,0]);const b=n.metrics.isDoubleResolution?2:1,w=(n.metrics.left-h)*n.scale-m+x[0],_=(-n.metrics.top-h)*n.scale+x[1],S=w+s.w/b*n.scale/f,A=_+s.h/b*n.scale/f,k=new l(w,_),M=new l(S,_),I=new l(w,A),z=new l(S,A);if(y){const t=new l(-m,m-Hu),e=-Math.PI/2,r=Tu/2-m,i=new l(5-Hu-r,-(n.imageName?r:0)),s=new l(...v);k._rotateAround(e,t)._add(i)._add(s),M._rotateAround(e,t)._add(i)._add(s),I._rotateAround(e,t)._add(i)._add(s),z._rotateAround(e,t)._add(i)._add(s);}if(u){const t=Math.sin(u),e=Math.cos(u),r=[e,-t,t,e];k._matMult(r),M._matMult(r),I._matMult(r),z._matMult(r);}const P=new l(0,0),C=new l(0,0);c.push({tl:k,tr:M,bl:I,br:z,tex:s,writingMode:e.writingMode,glyphOffset:g,sectionIndex:n.sectionIndex,isSDF:p,pixelOffsetTL:P,pixelOffsetBR:C,minFontScaleX:0,minFontScaleY:0});}return c}(0,r,o,i,s,a,n,t.allowVerticalPlacement),g=t.textSizeData;let x=null;"source"===g.kind?(x=[dc*i.layout.get("text-size").evaluate(a,{})],x[0]>yc&&j(`${t.layerIds[0]}: Value for "text-size" is >= ${fc}. Reduce your "text-size".`)):"composite"===g.kind&&(x=[dc*d.compositeTextSizes[0].evaluate(a,{},y),dc*d.compositeTextSizes[1].evaluate(a,{},y)],(x[0]>yc||x[1]>yc)&&j(`${t.layerIds[0]}: Value for "text-size" is >= ${fc}. Reduce your "text-size".`)),t.addSymbols(t.text,m,x,o,s,a,c,e,u.lineStartIndex,u.lineLength,f,y);for(const e of h)p[e]=t.text.placedSymbolArray.length-1;return 4*m.length}function Fh(t){for(const e in t)return t[e];return null}function $h(t,e,r,n){const i=t.compareText;if(e in i){const t=i[e];for(let e=t.length-1;e>=0;e--)if(n.dist(t[e])>4;if(1!==n)throw new Error(`Got v${n} data when expected v1.`);const i=Lh[15&r];if(!i)throw new Error("Unrecognized array type.");const[s]=new Uint16Array(t,2,1),[a]=new Uint32Array(t,4,1);return new Dh(a,s,i,t)}constructor(t,e=64,r=Float64Array,n){if(isNaN(t)||t<0)throw new Error(`Unpexpected numItems value: ${t}.`);this.numItems=+t,this.nodeSize=Math.min(Math.max(+e,2),65535),this.ArrayType=r,this.IndexArrayType=t<65536?Uint16Array:Uint32Array;const i=Lh.indexOf(this.ArrayType),s=2*t*this.ArrayType.BYTES_PER_ELEMENT,a=t*this.IndexArrayType.BYTES_PER_ELEMENT,o=(8-a%8)%8;if(i<0)throw new Error(`Unexpected typed array class: ${r}.`);n&&n instanceof ArrayBuffer?(this.data=n,this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=2*t,this._finished=true):(this.data=new ArrayBuffer(8+s+a+o),this.ids=new this.IndexArrayType(this.data,8,t),this.coords=new this.ArrayType(this.data,8+a+o,2*t),this._pos=0,this._finished=false,new Uint8Array(this.data,0,2).set([219,16+i]),new Uint16Array(this.data,2,1)[0]=e,new Uint32Array(this.data,4,1)[0]=t);}add(t,e){const r=this._pos>>1;return this.ids[r]=r,this.coords[this._pos++]=t,this.coords[this._pos++]=e,r}finish(){const t=this._pos>>1;if(t!==this.numItems)throw new Error(`Added ${t} items when expected ${this.numItems}.`);return Oh(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=true,this}range(t,e,r,n){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:i,coords:s,nodeSize:a}=this,o=[0,i.length-1,0],l=[];for(;o.length;){const u=o.pop()||0,c=o.pop()||0,h=o.pop()||0;if(c-h<=a){for(let a=h;a<=c;a++){const o=s[2*a],u=s[2*a+1];o>=t&&o<=r&&u>=e&&u<=n&&l.push(i[a]);}continue}const p=h+c>>1,f=s[2*p],d=s[2*p+1];f>=t&&f<=r&&d>=e&&d<=n&&l.push(i[p]),(0===u?t<=f:e<=d)&&(o.push(h),o.push(p-1),o.push(1-u)),(0===u?r>=f:n>=d)&&(o.push(p+1),o.push(c),o.push(1-u));}return l}within(t,e,r){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:n,coords:i,nodeSize:s}=this,a=[0,n.length-1,0],o=[],l=r*r;for(;a.length;){const u=a.pop()||0,c=a.pop()||0,h=a.pop()||0;if(c-h<=s){for(let r=h;r<=c;r++)Uh(i[2*r],i[2*r+1],t,e)<=l&&o.push(n[r]);continue}const p=h+c>>1,f=i[2*p],d=i[2*p+1];Uh(f,d,t,e)<=l&&o.push(n[p]),(0===u?t-r<=f:e-r<=d)&&(a.push(h),a.push(p-1),a.push(1-u)),(0===u?t+r>=f:e+r>=d)&&(a.push(p+1),a.push(c),a.push(1-u));}return o}}function Oh(t,e,r,n,i,s){if(i-n<=r)return;const a=n+i>>1;Rh(t,e,a,n,i,s),Oh(t,e,r,n,a-1,1-s),Oh(t,e,r,a+1,i,1-s);}function Rh(t,e,r,n,i,s){for(;i>n;){if(i-n>600){const a=i-n+1,o=r-n+1,l=Math.log(a),u=.5*Math.exp(2*l/3),c=.5*Math.sqrt(l*u*(a-u)/a)*(o-a/2<0?-1:1);Rh(t,e,r,Math.max(n,Math.floor(r-o*u/a+c)),Math.min(i,Math.floor(r+(a-o)*u/a+c)),s);}const a=e[2*r+s];let o=n,l=i;for(jh(t,e,n,r),e[2*i+s]>a&&jh(t,e,n,i);oa;)l--;}e[2*n+s]===a?jh(t,e,n,l):(l++,jh(t,e,l,i)),l<=r&&(n=l+1),r<=l&&(i=l-1);}}function jh(t,e,r,n){Nh(t,r,n),Nh(e,2*r,2*n),Nh(e,2*r+1,2*n+1);}function Nh(t,e,r){const n=t[e];t[e]=t[r],t[r]=n;}function Uh(t,e,r,n){const i=t-r,s=e-n;return i*i+s*s}var qh;t.ce=undefined,(qh=t.ce||(t.ce={})).create="create",qh.load="load",qh.fullLoad="fullLoad";let Gh=null,Zh=[];const Xh=1e3/60,Kh="loadTime",Hh="fullLoadTime",Yh={mark(t){performance.mark(t);},frame(t){const e=t;null!=Gh&&Zh.push(e-Gh),Gh=e;},clearMetrics(){Gh=null,Zh=[],performance.clearMeasures(Kh),performance.clearMeasures(Hh);for(const e in t.ce)performance.clearMarks(t.ce[e]);},getPerformanceMetrics(){performance.measure(Kh,t.ce.create,t.ce.load),performance.measure(Hh,t.ce.create,t.ce.fullLoad);const e=performance.getEntriesByName(Kh)[0].duration,r=performance.getEntriesByName(Hh)[0].duration,n=Zh.length,i=1/(Zh.reduce(((t,e)=>t+e),0)/n/1e3),s=Zh.filter((t=>t>Xh)).reduce(((t,e)=>t+(e-Xh)/Xh),0);return {loadTime:e,fullLoadTime:r,fps:i,percentDroppedFrames:s/(n+s)*100,totalFrames:n}}};t.$=St,t.A=g,t.B=Li,t.C=function(t){if(null==q){const e=t.navigator?t.navigator.userAgent:null;q=!!t.safari||!(!e||!(/\b(iPad|iPhone|iPod)\b/.test(e)||e.match("Safari")&&!e.match("Chrome")));}return q},t.D=vs,t.E=ct,t.F=class{constructor(t,e){this.target=t,this.mapId=e,this.resolveRejects={},this.tasks={},this.taskQueue=[],this.abortControllers={},this.messageHandlers={},this.invoker=new Dc((()=>this.process())),this.subscription=function(t,e,r,n){return t.addEventListener(e,r,false),{unsubscribe:()=>{t.removeEventListener(e,r,false);}}}(this.target,"message",(t=>this.receive(t))),this.globalScope=U(self)?t:window;}registerMessageHandler(t,e){this.messageHandlers[t]=e;}sendAsync(t,e){return new Promise(((r,n)=>{const i=Math.round(1e18*Math.random()).toString(36).substring(0,10);this.resolveRejects[i]={resolve:r,reject:n},e&&e.signal.addEventListener("abort",(()=>{delete this.resolveRejects[i];const e={id:i,type:"",origin:location.origin,targetMapId:t.targetMapId,sourceMapId:this.mapId};this.target.postMessage(e);}),{once:true});const s=[],a=Object.assign(Object.assign({},t),{id:i,sourceMapId:this.mapId,origin:location.origin,data:Xi(t.data,s)});this.target.postMessage(a,{transfer:s});}))}receive(t){const e=t.data,r=e.id;if(!("file://"!==e.origin&&"file://"!==location.origin&&"resource://android"!==e.origin&&"resource://android"!==location.origin&&e.origin!==location.origin||e.targetMapId&&this.mapId!==e.targetMapId)){if(""===e.type){delete this.tasks[r];const t=this.abortControllers[r];return delete this.abortControllers[r],void(t&&t.abort())}if(U(self)||e.mustQueue)return this.tasks[r]=e,this.taskQueue.push(r),void this.invoker.trigger();this.processTask(r,e);}}process(){if(0===this.taskQueue.length)return;const t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length>0&&this.invoker.trigger(),e&&this.processTask(t,e);}processTask(t,r){return e(this,undefined,undefined,(function*(){if(""===r.type){const e=this.resolveRejects[t];if(delete this.resolveRejects[t],!e)return;return void(r.error?e.reject(Ki(r.error)):e.resolve(Ki(r.data)))}if(!this.messageHandlers[r.type])return void this.completeTask(t,new Error(`Could not find a registered handler for ${r.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));const e=Ki(r.data),n=new AbortController;this.abortControllers[t]=n;try{const i=yield this.messageHandlers[r.type](r.sourceMapId,e,n);this.completeTask(t,null,i);}catch(e){this.completeTask(t,e);}}))}completeTask(t,e,r){const n=[];delete this.abortControllers[t];const i={id:t,type:"",sourceMapId:this.mapId,origin:location.origin,error:e?Xi(e):null,data:Xi(r,n)};this.target.postMessage(i,{transfer:n});}remove(){this.invoker.remove(),this.subscription.unsubscribe();}},t.G=et,t.H=function(){var t=new g(16);return g!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},t.I=Zu,t.J=function(t,e,r){var n,i,s,a,o,l,u,c,h,p,f,d,y=r[0],m=r[1],g=r[2];return e===t?(t[12]=e[0]*y+e[4]*m+e[8]*g+e[12],t[13]=e[1]*y+e[5]*m+e[9]*g+e[13],t[14]=e[2]*y+e[6]*m+e[10]*g+e[14],t[15]=e[3]*y+e[7]*m+e[11]*g+e[15]):(i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],t[0]=n=e[0],t[1]=i,t[2]=s,t[3]=a,t[4]=o,t[5]=l,t[6]=u,t[7]=c,t[8]=h,t[9]=p,t[10]=f,t[11]=d,t[12]=n*y+o*m+h*g+e[12],t[13]=i*y+l*m+p*g+e[13],t[14]=s*y+u*m+f*g+e[14],t[15]=a*y+c*m+d*g+e[15]),t},t.K=function(t,e,r){var n=r[0],i=r[1],s=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*s,t[9]=e[9]*s,t[10]=e[10]*s,t[11]=e[11]*s,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.L=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=e[3],o=e[4],l=e[5],u=e[6],c=e[7],h=e[8],p=e[9],f=e[10],d=e[11],y=e[12],m=e[13],g=e[14],x=e[15],v=r[0],b=r[1],w=r[2],_=r[3];return t[0]=v*n+b*o+w*h+_*y,t[1]=v*i+b*l+w*p+_*m,t[2]=v*s+b*u+w*f+_*g,t[3]=v*a+b*c+w*d+_*x,t[4]=(v=r[4])*n+(b=r[5])*o+(w=r[6])*h+(_=r[7])*y,t[5]=v*i+b*l+w*p+_*m,t[6]=v*s+b*u+w*f+_*g,t[7]=v*a+b*c+w*d+_*x,t[8]=(v=r[8])*n+(b=r[9])*o+(w=r[10])*h+(_=r[11])*y,t[9]=v*i+b*l+w*p+_*m,t[10]=v*s+b*u+w*f+_*g,t[11]=v*a+b*c+w*d+_*x,t[12]=(v=r[12])*n+(b=r[13])*o+(w=r[14])*h+(_=r[15])*y,t[13]=v*i+b*l+w*p+_*m,t[14]=v*s+b*u+w*f+_*g,t[15]=v*a+b*c+w*d+_*x,t},t.M=function(t,e){const r={};for(let n=0;n{const e=window.document.createElement("video");return e.muted=true,new Promise((r=>{e.onloadstart=()=>{r(e);};for(const r of t){const t=window.document.createElement("source");st(r)||(e.crossOrigin="Anonymous"),t.src=r,e.appendChild(t);}}))},t.a1=function(){return $++},t.a2=ra,t.a3=kc,t.a4=Yn,t.a5=lo,t.a6=rh,t.a7=function(t){const e={};if(t.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,((t,r,n,i)=>{const s=n||i;return e[r]=!s||s.toLowerCase(),""})),e["max-age"]){const t=parseInt(e["max-age"],10);isNaN(t)?delete e["max-age"]:e["max-age"]=t;}return e},t.a8=function(t){return Math.log(t)/Math.LN2},t.a9=function(t){var e=t[0],r=t[1];return e*e+r*r},t.aA=Cs,t.aB=_l,t.aC=fa,t.aD=Pa,t.aE=ka,t.aF=85.051129,t.aG=function(t){return Math.pow(2,t)},t.aH=Gc,t.aI=T,t.aJ=Y,t.aK=Xc,t.aL=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t[2]=e[2]*r,t},t.aM=function(t,e,r){return t[0]=e[0]+r[0],t[1]=e[1]+r[1],t[2]=e[2]+r[2],t},t.aN=function(t){var e=new g(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e},t.aO=function(t,e,r){return t[0]=e[0]*r[0],t[1]=e[1]*r[1],t[2]=e[2]*r[2],t[3]=e[3]*r[3],t},t.aP=function(t,e,r){return t[0]=e[0]-r[0],t[1]=e[1]-r[1],t[2]=e[2]-r[2],t},t.aQ=function(t,e){var r=e[0],n=e[1],i=e[2],s=r*r+n*n+i*i;return s>0&&(s=1/Math.sqrt(s)),t[0]=e[0]*s,t[1]=e[1]*s,t[2]=e[2]*s,t},t.aR=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=r[0],o=r[1],l=r[2];return t[0]=i*l-s*o,t[1]=s*a-n*l,t[2]=n*o-i*a,t},t.aS=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]},t.aT=Jc,t.aU=Qc,t.aV=function(t,e,r,n,i){var s,a=1/Math.tan(e/2);return t[0]=a/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=i&&i!==1/0?(t[10]=(i+n)*(s=1/(n-i)),t[14]=2*i*n*s):(t[10]=-1,t[14]=-2*n),t},t.aW=function(t){var e=new g(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},t.aX=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[4],c=e[5],h=e[6],p=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i+u*n,t[1]=a*i+c*n,t[2]=o*i+h*n,t[3]=l*i+p*n,t[4]=u*i-s*n,t[5]=c*i-a*n,t[6]=h*i-o*n,t[7]=p*i-l*n,t},t.aY=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=s*i+u*n,t[5]=a*i+c*n,t[6]=o*i+h*n,t[7]=l*i+p*n,t[8]=u*i-s*n,t[9]=c*i-a*n,t[10]=h*i-o*n,t[11]=p*i-l*n,t},t.aZ=function(){const t=new Float32Array(16);return v(t),t},t.a_=function(){const t=new Float64Array(16);return v(t),t},t.aa=function(t){return t*Math.PI/180},t.ab=E,t.ac=function(t,e){const r=[];for(const n in t)n in e||r.push(n);return r},t.ad=A,t.ae=function(t){return Math.hypot(t[0],t[1])},t.af=function(t){return t[0]=0,t[1]=0,t},t.ag=function(t,e,r){return t[0]=e[0]*r,t[1]=e[1]*r,t},t.ah=function(t,e){let r=0,n=0;if("constant"===t.kind)n=t.layoutSize;else if("source"!==t.kind){const{interpolationType:i,minZoom:s,maxZoom:a}=t,o=i?E(sr.interpolationFactor(i,e,s,a),0,1):0;"camera"===t.kind?n=or.number(t.minSize,t.maxSize,o):r=o;}return {uSizeT:r,uSize:n}},t.aj=function(t,{uSize:e,uSizeT:r},{lowerSize:n,upperSize:i}){return "source"===t.kind?n/dc:"composite"===t.kind?or.number(n/dc,i/dc,r):e},t.ak=wc,t.al=_,t.am=function(t,e,r,n){const i=e.y-t.y,s=e.x-t.x,a=n.y-r.y,o=n.x-r.x,u=a*s-o*i;if(0===u)return null;const c=(o*(t.y-r.y)-a*(t.x-r.x))/u;return new l(t.x+c*s,t.y+c*i)},t.an=function(t,e){var r=e[0],n=e[1],i=e[2],s=e[3],a=e[4],o=e[5],l=e[6],u=e[7],c=e[8],h=e[9],p=e[10],f=e[11],d=e[12],y=e[13],m=e[14],g=e[15],x=r*o-n*a,v=r*l-i*a,b=r*u-s*a,w=n*l-i*o,_=n*u-s*o,S=i*u-s*l,A=c*y-h*d,k=c*m-p*d,M=c*g-f*d,I=h*m-p*y,z=h*g-f*y,P=p*g-f*m,C=x*P-v*z+b*I+w*M-_*k+S*A;return C?(t[0]=(o*P-l*z+u*I)*(C=1/C),t[1]=(i*z-n*P-s*I)*C,t[2]=(y*S-m*_+g*w)*C,t[3]=(p*_-h*S-f*w)*C,t[4]=(l*M-a*P-u*k)*C,t[5]=(r*P-i*M+s*k)*C,t[6]=(m*b-d*S-g*v)*C,t[7]=(c*S-p*b+f*v)*C,t[8]=(a*z-o*M+u*A)*C,t[9]=(n*M-r*z-s*A)*C,t[10]=(d*_-y*b+g*x)*C,t[11]=(h*b-c*_-f*x)*C,t[12]=(o*k-a*I-l*A)*C,t[13]=(r*I-n*k+i*A)*C,t[14]=(y*v-d*w-m*x)*C,t[15]=(c*w-h*v+p*x)*C,t):null},t.ao=oh,t.ap=po,t.aq=v,t.ar=function(t){let e=1/0,r=1/0,n=-1/0,i=-1/0;for(const s of t)e=Math.min(e,s.x),r=Math.min(r,s.y),n=Math.max(n,s.x),i=Math.max(i,s.y);return [e,r,n,i]},t.as=Tu,t.at=I,t.au=function(t,e,r,n,i=false){if(!r[0]&&!r[1])return [0,0];const s=i?"map"===n?-t.bearingInRadians:0:"viewport"===n?t.bearingInRadians:0;if(s){const t=Math.sin(s),e=Math.cos(s);r=[r[0]*e-r[1]*t,r[0]*t+r[1]*e];}return [i?r[0]:I(e,r[0],t.zoom),i?r[1]:I(e,r[1],t.zoom)]},t.aw=gc,t.ax=Vh,t.ay=lc,t.az=Dh,t.b=G,t.b$=t=>"line"===t.type,t.b0=function(t,e,r){const n=new Float64Array(4);return function(t,e,r,n){var i=.5*Math.PI/180;e*=i,r*=i,n*=i;var s=Math.sin(e),a=Math.cos(e),o=Math.sin(r),l=Math.cos(r),u=Math.sin(n),c=Math.cos(n);t[0]=s*l*c-a*o*u,t[1]=a*o*c+s*l*u,t[2]=a*l*u-s*o*c,t[3]=a*l*c+s*o*u;}(n,t,e-90,r),n},t.b1=function(t,e,r,n){var i,s,a,o,l,u=e[0],c=e[1],h=e[2],p=e[3],f=r[0],d=r[1],y=r[2],g=r[3];return (s=u*f+c*d+h*y+p*g)<0&&(s=-s,f=-f,d=-d,y=-y,g=-g),1-s>m?(i=Math.acos(s),a=Math.sin(i),o=Math.sin((1-n)*i)/a,l=Math.sin(n*i)/a):(o=1-n,l=n),t[0]=o*u+l*f,t[1]=o*c+l*d,t[2]=o*h+l*y,t[3]=o*p+l*g,t},t.b2=function(t){const e=new Float64Array(9);var r,n,i,s,a,o,l,u,c,h,p,f,d,y,m,g,x,v;h=(i=(n=t)[0])*(l=i+i),p=(s=n[1])*l,d=(a=n[2])*l,y=a*(u=s+s),g=(o=n[3])*l,x=o*u,v=o*(c=a+a),(r=e)[0]=1-(f=s*u)-(m=a*c),r[3]=p-v,r[6]=d+x,r[1]=p+v,r[4]=1-h-m,r[7]=y-g,r[2]=d-x,r[5]=y+g,r[8]=1-h-f;const b=Y(-Math.asin(E(e[2],-1,1)));let w,_;return Math.hypot(e[5],e[8])<.001?(w=0,_=-Y(Math.atan2(e[3],e[4]))):(w=Y(0===e[5]&&0===e[8]?0:Math.atan2(e[5],e[8])),_=Y(0===e[1]&&0===e[0]?0:Math.atan2(e[1],e[0]))),{roll:w,pitch:b+90,bearing:_}},t.b3=function(t,e){return t.roll==e.roll&&t.pitch==e.pitch&&t.bearing==e.bearing},t.b4=ye,t.b5=Ga,t.b6=Sl,t.b7=Al,t.b8=wl,t.b9=P,t.bA=L,t.bB=D,t.bC=class extends qa{constructor(t,e){super(t,e),this.current=0;}set(t){this.current!==t&&(this.current=t,this.gl.uniform1i(this.location,t));}},t.bD=class extends qa{constructor(t,e){super(t,e),this.current=Ka;}set(t){if(t[12]!==this.current[12]||t[0]!==this.current[0])return this.current=t,void this.gl.uniformMatrix4fv(this.location,false,t);for(let e=1;e<16;e++)if(t[e]!==this.current[e]){this.current=t,this.gl.uniformMatrix4fv(this.location,false,t);break}}},t.bE=Za,t.bF=Xa,t.bG=class extends qa{constructor(t,e){super(t,e),this.current=[0,0,0];}set(t){t[0]===this.current[0]&&t[1]===this.current[1]&&t[2]===this.current[2]||(this.current=t,this.gl.uniform3f(this.location,t[0],t[1],t[2]));}},t.bH=class extends qa{constructor(t,e){super(t,e),this.current=[0,0];}set(t){t[0]===this.current[0]&&t[1]===this.current[1]||(this.current=t,this.gl.uniform2f(this.location,t[0],t[1]));}},t.bI=x,t.bJ=function(t,e){var r=Math.sin(e),n=Math.cos(e);return t[0]=n,t[1]=r,t[2]=0,t[3]=-r,t[4]=n,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t},t.bK=function(t,e,r){var n=e[0],i=e[1],s=e[2];return t[0]=n*r[0]+i*r[3]+s*r[6],t[1]=n*r[1]+i*r[4]+s*r[7],t[2]=n*r[2]+i*r[5]+s*r[8],t},t.bL=function(t,e,r,n,i,s,a){var o=1/(e-r),l=1/(n-i),u=1/(s-a);return t[0]=-2*o,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*l,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*u,t[11]=0,t[12]=(e+r)*o,t[13]=(i+n)*l,t[14]=(a+s)*u,t[15]=1,t},t.bM=class extends qs{},t.bN=zu,t.bO=class extends Zs{},t.bP=jo,t.bQ=function(t){return t<=1?1:Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))},t.bR=Ro,t.bS=function(t,e,r){var n=e[0],i=e[1],s=e[2],a=r[3]*n+r[7]*i+r[11]*s+r[15];return t[0]=(r[0]*n+r[4]*i+r[8]*s+r[12])/(a=a||1),t[1]=(r[1]*n+r[5]*i+r[9]*s+r[13])/a,t[2]=(r[2]*n+r[6]*i+r[10]*s+r[14])/a,t},t.bT=class extends Ts{},t.bU=class extends Qs{},t.bV=function(t,e){return t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]&&t[4]===e[4]&&t[5]===e[5]&&t[6]===e[6]&&t[7]===e[7]&&t[8]===e[8]&&t[9]===e[9]&&t[10]===e[10]&&t[11]===e[11]&&t[12]===e[12]&&t[13]===e[13]&&t[14]===e[14]&&t[15]===e[15]},t.bW=function(t,e){var r=t[0],n=t[1],i=t[2],s=t[3],a=t[4],o=t[5],l=t[6],u=t[7],c=t[8],h=t[9],p=t[10],f=t[11],d=t[12],y=t[13],g=t[14],x=t[15],v=e[0],b=e[1],w=e[2],_=e[3],S=e[4],A=e[5],k=e[6],M=e[7],I=e[8],z=e[9],P=e[10],C=e[11],B=e[12],V=e[13],E=e[14],T=e[15];return Math.abs(r-v)<=m*Math.max(1,Math.abs(r),Math.abs(v))&&Math.abs(n-b)<=m*Math.max(1,Math.abs(n),Math.abs(b))&&Math.abs(i-w)<=m*Math.max(1,Math.abs(i),Math.abs(w))&&Math.abs(s-_)<=m*Math.max(1,Math.abs(s),Math.abs(_))&&Math.abs(a-S)<=m*Math.max(1,Math.abs(a),Math.abs(S))&&Math.abs(o-A)<=m*Math.max(1,Math.abs(o),Math.abs(A))&&Math.abs(l-k)<=m*Math.max(1,Math.abs(l),Math.abs(k))&&Math.abs(u-M)<=m*Math.max(1,Math.abs(u),Math.abs(M))&&Math.abs(c-I)<=m*Math.max(1,Math.abs(c),Math.abs(I))&&Math.abs(h-z)<=m*Math.max(1,Math.abs(h),Math.abs(z))&&Math.abs(p-P)<=m*Math.max(1,Math.abs(p),Math.abs(P))&&Math.abs(f-C)<=m*Math.max(1,Math.abs(f),Math.abs(C))&&Math.abs(d-B)<=m*Math.max(1,Math.abs(d),Math.abs(B))&&Math.abs(y-V)<=m*Math.max(1,Math.abs(y),Math.abs(V))&&Math.abs(g-E)<=m*Math.max(1,Math.abs(g),Math.abs(E))&&Math.abs(x-T)<=m*Math.max(1,Math.abs(x),Math.abs(T))},t.bX=function(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t},t.bY=t=>"symbol"===t.type,t.bZ=t=>"circle"===t.type,t.b_=t=>"heatmap"===t.type,t.ba=C,t.bb=Ae,t.bc=function(t,e,r,n,i){return P(n,i,E((t-e)/(r-e),0,1))},t.bd=z,t.be=function(){return new Float64Array(4)},t.bf=function(){return new Float64Array(3)},t.bg=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0]*Math.cos(n)-i[1]*Math.sin(n),s[1]=i[0]*Math.sin(n)+i[1]*Math.cos(n),s[2]=i[2],t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bh=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[0],s[1]=i[1]*Math.cos(n)-i[2]*Math.sin(n),s[2]=i[1]*Math.sin(n)+i[2]*Math.cos(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bi=function(t,e,r,n){var i=[],s=[];return i[0]=e[0]-r[0],i[1]=e[1]-r[1],i[2]=e[2]-r[2],s[0]=i[2]*Math.sin(n)+i[0]*Math.cos(n),s[1]=i[1],s[2]=i[2]*Math.cos(n)-i[0]*Math.sin(n),t[0]=s[0]+r[0],t[1]=s[1]+r[1],t[2]=s[2]+r[2],t},t.bj=function(t,e,r){var n=Math.sin(r),i=Math.cos(r),s=e[0],a=e[1],o=e[2],l=e[3],u=e[8],c=e[9],h=e[10],p=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=s*i-u*n,t[1]=a*i-c*n,t[2]=o*i-h*n,t[3]=l*i-p*n,t[8]=s*n+u*i,t[9]=a*n+c*i,t[10]=o*n+h*i,t[11]=l*n+p*i,t},t.bk=function(t,e){const r=z(t,360),n=z(e,360),i=n-r,s=n>r?i-360:i+360;return Math.abs(i)0?a:-a},t.bn=function(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]},t.bo=Oc,t.bp=function(t,e){const r=z(t,2*Math.PI),n=z(e,2*Math.PI);return Math.min(Math.abs(r-n),Math.abs(r-n+2*Math.PI),Math.abs(r-n-2*Math.PI))},t.bq=function(t){return Math.hypot(t[0],t[1],t[2])},t.br=function(){const t={},e=ht.$version;for(const r in ht.$root){const n=ht.$root[r];if(n.required){let i=null;i="version"===r?e:"array"===n.type?[]:{},null!=i&&(t[r]=i);}}return t},t.bs=Hi,t.bt=nt,t.bu=function(t){t=t.slice();const e=Object.create(null);for(let r=0;r{"source"in t&&n[t.source]?r.push({command:"removeLayer",args:[t.id]}):s.push(t);})),r=r.concat(i),function(t,e,r){e=e||[];const n=(t=t||[]).map(wt),i=e.map(wt),s=t.reduce(_t,{}),a=e.reduce(_t,{}),o=n.slice(),l=Object.create(null);let u,c,h,p,f;for(let t=0,e=0;t"fill"===t.type,t.c1=t=>"fill-extrusion"===t.type,t.c2=t=>"hillshade"===t.type,t.c3=t=>"raster"===t.type,t.c4=t=>"background"===t.type,t.c5=t=>"custom"===t.type,t.c6=B,t.c7=function(t,e,r){const n=k(e.x-r.x,e.y-r.y),i=k(t.x-r.x,t.y-r.y);var s,a;return Y(Math.atan2(n[0]*i[1]-n[1]*i[0],(s=n)[0]*(a=i)[0]+s[1]*a[1]))},t.c8=V,t.c9=function(t,e,r){var n=e[0],i=e[1];return t[0]=r[0]*n+r[4]*i+r[12],t[1]=r[1]*n+r[5]*i+r[13],t},t.cA=Lu,t.cB=Nn,t.cC=us,t.ca=function(t,e){const{x:r,y:n}=Kc.fromLngLat(e);return !(t<0||t>25||n<0||n>=1||r<0||r>=1)},t.cb=function(t,e){return t[0]=e[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=e[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},t.cc=class extends Es{},t.cd=Yh,t.cf=function(t){return t.message===J},t.cg=rt,t.ch=function(t,e){Q.REGISTERED_PROTOCOLS[t]=e;},t.ci=function(t){delete Q.REGISTERED_PROTOCOLS[t];},t.cj=function(t,e){const r={};for(let n=0;nt*Tu));}let v=o?"center":n.get("text-justify").evaluate(i,{},e.canonical);const b="point"===n.get("symbol-placement")?n.get("text-max-width").evaluate(i,{},e.canonical)*Tu:1/0,w=()=>{e.bucket.allowVerticalPlacement&&Ji(s)&&(d.vertical=Wu(y,e.glyphMap,e.glyphPositions,e.imagePositions,c,b,a,m,"left",f,g,t.ai.vertical,true,p,h));};if(!o&&x){const r=new Set;if("auto"===v)for(let t=0;te(undefined,undefined,undefined,(function*(){if(0===t.byteLength)return createImageBitmap(new ImageData(1,1));const e=new Blob([new Uint8Array(t)],{type:"image/png"});try{return createImageBitmap(e)}catch(t){throw new Error(`Could not load image because of ${t.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)}})),t.e=F,t.f=t=>new Promise(((e,r)=>{const n=new Image;n.onload=()=>{e(n),URL.revokeObjectURL(n.src),n.onload=null,window.requestAnimationFrame((()=>{n.src=Z;}));},n.onerror=()=>r(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));const i=new Blob([new Uint8Array(t)],{type:"image/png"});n.src=t.byteLength?URL.createObjectURL(i):Z;})),t.g=tt,t.h=(t,e)=>it(F(t,{type:"json"}),e),t.i=U,t.j=ut,t.k=lt,t.l=(t,e)=>it(F(t,{type:"arrayBuffer"}),e),t.m=it,t.n=function(t){return new Du(t).readFields(Ru,[])},t.o=Do,t.p=qu,t.q=As,t.r=$i,t.s=st,t.t=Ri,t.u=Fi,t.v=ht,t.w=j,t.x=function([t,e,r]){return e+=90,e*=Math.PI/180,r*=Math.PI/180,{x:t*Math.cos(e)*Math.sin(r),y:t*Math.sin(e)*Math.sin(r),z:t*Math.cos(r)}},t.y=or,t.z=cs;})); - - define("worker",["./shared"],(function(e){class t{constructor(e){this.keyCache={},e&&this.replace(e);}replace(e){this._layerConfigs={},this._layers={},this.update(e,[]);}update(t,o){for(const o of t){this._layerConfigs[o.id]=o;const t=this._layers[o.id]=e.bv(o);t._featureFilter=e.a4(t.filter),this.keyCache[o.id]&&delete this.keyCache[o.id];}for(const e of o)delete this.keyCache[e],delete this._layerConfigs[e],delete this._layers[e];this.familiesBySource={};const i=e.cj(Object.values(this._layerConfigs),this.keyCache);for(const e of i){const t=e.map((e=>this._layers[e.id])),o=t[0];if("none"===o.visibility)continue;const i=o.source||"";let r=this.familiesBySource[i];r||(r=this.familiesBySource[i]={});const s=o.sourceLayer||"_geojsonTileLayer";let n=r[s];n||(n=r[s]=[]),n.push(t);}}}class o{constructor(t){const o={},i=[];for(const e in t){const r=t[e],s=o[e]={};for(const e in r){const t=r[+e];if(!t||0===t.bitmap.width||0===t.bitmap.height)continue;const o={x:0,y:0,w:t.bitmap.width+2,h:t.bitmap.height+2};i.push(o),s[e]={rect:o,metrics:t.metrics};}}const{w:r,h:s}=e.p(i),n=new e.o({width:r||1,height:s||1});for(const i in t){const r=t[i];for(const t in r){const s=r[+t];if(!s||0===s.bitmap.width||0===s.bitmap.height)continue;const a=o[i][t].rect;e.o.copy(s.bitmap,n,{x:0,y:0},{x:a.x+1,y:a.y+1},s.bitmap);}}this.image=n,this.positions=o;}}e.ck("GlyphAtlas",o);class i{constructor(t){this.tileID=new e.S(t.tileID.overscaledZ,t.tileID.wrap,t.tileID.canonical.z,t.tileID.canonical.x,t.tileID.canonical.y),this.uid=t.uid,this.zoom=t.zoom,this.pixelRatio=t.pixelRatio,this.tileSize=t.tileSize,this.source=t.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=t.showCollisionBoxes,this.collectResourceTiming=!!t.collectResourceTiming,this.returnDependencies=!!t.returnDependencies,this.promoteId=t.promoteId,this.inFlightDependencies=[];}parse(t,i,s,n,a){return e._(this,undefined,undefined,(function*(){this.status="parsing",this.data=t,this.collisionBoxArray=new e.a2;const l=new e.cl(Object.keys(t.layers).sort()),c=new e.cm(this.tileID,this.promoteId);c.bucketLayerIDs=[];const u={},h={featureIndex:c,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:s,subdivisionGranularity:a},d=i.familiesBySource[this.source];for(const o in d){const i=t.layers[o];if(!i)continue;1===i.version&&e.w(`Vector tile source "${this.source}" layer "${o}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const n=l.encode(o),a=[];for(let e=0;e=o.maxzoom||"none"!==o.visibility&&(r(t,this.zoom,s),(u[o.id]=o.createBucket({index:c.bucketLayerIDs.length,layers:t,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:n,sourceID:this.source})).populate(a,h,this.tileID.canonical),c.bucketLayerIDs.push(t.map((e=>e.id))));}}const f=e.bA(h.glyphDependencies,(e=>Object.keys(e).map(Number)));this.inFlightDependencies.forEach((e=>null==e?undefined:e.abort())),this.inFlightDependencies=[];let g=Promise.resolve({});if(Object.keys(f).length){const e=new AbortController;this.inFlightDependencies.push(e),g=n.sendAsync({type:"GG",data:{stacks:f,source:this.source,tileID:this.tileID,type:"glyphs"}},e);}const p=Object.keys(h.iconDependencies);let m=Promise.resolve({});if(p.length){const e=new AbortController;this.inFlightDependencies.push(e),m=n.sendAsync({type:"GI",data:{icons:p,source:this.source,tileID:this.tileID,type:"icons"}},e);}const y=Object.keys(h.patternDependencies);let v=Promise.resolve({});if(y.length){const e=new AbortController;this.inFlightDependencies.push(e),v=n.sendAsync({type:"GI",data:{icons:y,source:this.source,tileID:this.tileID,type:"patterns"}},e);}const[w,x,_]=yield Promise.all([g,m,v]),b=new o(w),M=new e.cn(x,_);for(const t in u){const o=u[t];o instanceof e.a3?(r(o.layers,this.zoom,s),e.co({bucket:o,glyphMap:w,glyphPositions:b.positions,imageMap:x,imagePositions:M.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical,subdivisionGranularity:h.subdivisionGranularity})):o.hasPattern&&(o instanceof e.cp||o instanceof e.cq||o instanceof e.cr)&&(r(o.layers,this.zoom,s),o.addFeatures(h,this.tileID.canonical,M.patternPositions));}return this.status="done",{buckets:Object.values(u).filter((e=>!e.isEmpty())),featureIndex:c,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:b.image,imageAtlas:M,glyphMap:this.returnDependencies?w:null,iconMap:this.returnDependencies?x:null,glyphPositions:this.returnDependencies?b.positions:null}}))}}function r(t,o,i){const r=new e.z(o);for(const e of t)e.recalculate(r,i);}class s{constructor(e,t,o){this.actor=e,this.layerIndex=t,this.availableImages=o,this.fetching={},this.loading={},this.loaded={};}loadVectorTile(t,o){return e._(this,undefined,undefined,(function*(){const i=yield e.l(t.request,o);try{return {vectorTile:new e.cs.VectorTile(new e.ct(i.data)),rawData:i.data,cacheControl:i.cacheControl,expires:i.expires}}catch(e){const o=new Uint8Array(i.data);let r=`Unable to parse the tile at ${t.request.url}, `;throw r+=31===o[0]&&139===o[1]?"please make sure the data is not gzipped and that you have configured the relevant header in the server":`got error: ${e.message}`,new Error(r)}}))}loadTile(t){return e._(this,undefined,undefined,(function*(){const o=t.uid,r=!!(t&&t.request&&t.request.collectResourceTiming)&&new e.cu(t.request),s=new i(t);this.loading[o]=s;const n=new AbortController;s.abort=n;try{const i=yield this.loadVectorTile(t,n);if(delete this.loading[o],!i)return null;const a=i.rawData,l={};i.expires&&(l.expires=i.expires),i.cacheControl&&(l.cacheControl=i.cacheControl);const c={};if(r){const e=r.finish();e&&(c.resourceTiming=JSON.parse(JSON.stringify(e)));}s.vectorTile=i.vectorTile;const u=s.parse(i.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);this.loaded[o]=s,this.fetching[o]={rawTileData:a,cacheControl:l,resourceTiming:c};try{const t=yield u;return e.e({rawTileData:a.slice(0)},t,l,c)}finally{delete this.fetching[o];}}catch(e){throw delete this.loading[o],s.status="done",this.loaded[o]=s,e}}))}reloadTile(t){return e._(this,undefined,undefined,(function*(){const o=t.uid;if(!this.loaded||!this.loaded[o])throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");const i=this.loaded[o];if(i.showCollisionBoxes=t.showCollisionBoxes,"parsing"===i.status){const r=yield i.parse(i.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity);let s;if(this.fetching[o]){const{rawTileData:t,cacheControl:i,resourceTiming:n}=this.fetching[o];delete this.fetching[o],s=e.e({rawTileData:t.slice(0)},r,i,n);}else s=r;return s}if("done"===i.status&&i.vectorTile)return i.parse(i.vectorTile,this.layerIndex,this.availableImages,this.actor,t.subdivisionGranularity)}))}abortTile(t){return e._(this,undefined,undefined,(function*(){const e=this.loading,o=t.uid;e&&e[o]&&e[o].abort&&(e[o].abort.abort(),delete e[o]);}))}removeTile(t){return e._(this,undefined,undefined,(function*(){this.loaded&&this.loaded[t.uid]&&delete this.loaded[t.uid];}))}}class n{constructor(){this.loaded={};}loadTile(t){return e._(this,undefined,undefined,(function*(){const{uid:o,encoding:i,rawImageData:r,redFactor:s,greenFactor:n,blueFactor:a,baseShift:l}=t,c=r.width+2,u=r.height+2,h=e.b(r)?new e.R({width:c,height:u},yield e.cv(r,-1,-1,c,u)):r,d=new e.cw(o,h,i,s,n,a,l);return this.loaded=this.loaded||{},this.loaded[o]=d,d}))}removeTile(e){const t=this.loaded,o=e.uid;t&&t[o]&&delete t[o];}}var a,l,c=function(){if(l)return a;function e(e,o){if(0!==e.length){t(e[0],o);for(var i=1;i=Math.abs(a)?o-l+a:a-l+o,o=l;}o+i>=0!=!!t&&e.reverse();}return l=1,a=function t(o,i){var r,s=o&&o.type;if("FeatureCollection"===s)for(r=0;r>31}function c(e,t){for(var o=e.loadGeometry(),i=e.type,r=0,s=0,n=o.length,c=0;ce},_=Math.fround||(b=new Float32Array(1),e=>(b[0]=+e,b[0]));var b;const M=3,S=5,I=6;class P{constructor(e){this.options=Object.assign(Object.create(x),e),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[];}load(e){const{log:t,minZoom:o,maxZoom:i}=this.options;t&&console.time("total time");const r=`prepare ${e.length} points`;t&&console.time(r),this.points=e;const s=[];for(let t=0;t=o;e--){const o=+Date.now();n=this.trees[e]=this._createTree(this._cluster(n,e)),t&&console.log("z%d: %d clusters in %dms",e,n.numItems,+Date.now()-o);}return t&&console.timeEnd("total time"),this}getClusters(e,t){let o=((e[0]+180)%360+360)%360-180;const i=Math.max(-90,Math.min(90,e[1]));let r=180===e[2]?180:((e[2]+180)%360+360)%360-180;const s=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)o=-180,r=180;else if(o>r){const e=this.getClusters([o,i,180,s],t),n=this.getClusters([-180,i,r,s],t);return e.concat(n)}const n=this.trees[this._limitZoom(t)],a=n.range(D(o),C(s),D(r),C(i)),l=n.data,c=[];for(const e of a){const t=this.stride*e;c.push(l[t+S]>1?k(l,t,this.clusterProps):this.points[l[t+M]]);}return c}getChildren(e){const t=this._getOriginId(e),o=this._getOriginZoom(e),i="No cluster with the specified id.",r=this.trees[o];if(!r)throw new Error(i);const s=r.data;if(t*this.stride>=s.length)throw new Error(i);const n=this.options.radius/(this.options.extent*Math.pow(2,o-1)),a=r.within(s[t*this.stride],s[t*this.stride+1],n),l=[];for(const t of a){const o=t*this.stride;s[o+4]===e&&l.push(s[o+S]>1?k(s,o,this.clusterProps):this.points[s[o+M]]);}if(0===l.length)throw new Error(i);return l}getLeaves(e,t,o){const i=[];return this._appendLeaves(i,e,t=t||10,o=o||0,0),i}getTile(e,t,o){const i=this.trees[this._limitZoom(e)],r=Math.pow(2,e),{extent:s,radius:n}=this.options,a=n/s,l=(o-a)/r,c=(o+1+a)/r,u={features:[]};return this._addTileFeatures(i.range((t-a)/r,l,(t+1+a)/r,c),i.data,t,o,r,u),0===t&&this._addTileFeatures(i.range(1-a/r,l,1,c),i.data,r,o,r,u),t===r-1&&this._addTileFeatures(i.range(0,l,a/r,c),i.data,-1,o,r,u),u.features.length?u:null}getClusterExpansionZoom(e){let t=this._getOriginZoom(e)-1;for(;t<=this.options.maxZoom;){const o=this.getChildren(e);if(t++,1!==o.length)break;e=o[0].properties.cluster_id;}return t}_appendLeaves(e,t,o,i,r){const s=this.getChildren(t);for(const t of s){const s=t.properties;if(s&&s.cluster?r+s.point_count<=i?r+=s.point_count:r=this._appendLeaves(e,s.cluster_id,o,i,r):r1;let l,c,u;if(a)l=T(t,e,this.clusterProps),c=t[e],u=t[e+1];else {const o=this.points[t[e+M]];l=o.properties;const[i,r]=o.geometry.coordinates;c=D(i),u=C(r);}const h={type:1,geometry:[[Math.round(this.options.extent*(c*r-o)),Math.round(this.options.extent*(u*r-i))]],tags:l};let d;d=a||this.options.generateId?t[e+M]:this.points[t[e+M]].id,undefined!==d&&(h.id=d),s.features.push(h);}}_limitZoom(e){return Math.max(this.options.minZoom,Math.min(Math.floor(+e),this.options.maxZoom+1))}_cluster(e,t){const{radius:o,extent:i,reduce:r,minPoints:s}=this.options,n=o/(i*Math.pow(2,t)),a=e.data,l=[],c=this.stride;for(let o=0;ot&&(f+=a[o+S]);}if(f>d&&f>=s){let e,s=i*d,n=u*d,g=-1;const p=((o/c|0)<<5)+(t+1)+this.points.length;for(const i of h){const l=i*c;if(a[l+2]<=t)continue;a[l+2]=t;const u=a[l+S];s+=a[l]*u,n+=a[l+1]*u,a[l+4]=p,r&&(e||(e=this._map(a,o,true),g=this.clusterProps.length,this.clusterProps.push(e)),r(e,this._map(a,l)));}a[o+4]=p,l.push(s/f,n/f,1/0,p,-1,f),r&&l.push(g);}else {for(let e=0;e1)for(const e of h){const o=e*c;if(!(a[o+2]<=t)){a[o+2]=t;for(let e=0;e>5}_getOriginZoom(e){return (e-this.points.length)%32}_map(e,t,o){if(e[t+S]>1){const i=this.clusterProps[e[t+I]];return o?Object.assign({},i):i}const i=this.points[e[t+M]].properties,r=this.options.map(i);return o&&r===i?Object.assign({},r):r}}function k(e,t,o){return {type:"Feature",id:e[t+M],properties:T(e,t,o),geometry:{type:"Point",coordinates:[(i=e[t],360*(i-.5)),O(e[t+1])]}};var i;}function T(e,t,o){const i=e[t+S],r=i>=1e4?`${Math.round(i/1e3)}k`:i>=1e3?Math.round(i/100)/10+"k":i,s=e[t+I],n=-1===s?{}:Object.assign({},o[s]);return Object.assign(n,{cluster:true,cluster_id:e[t+M],point_count:i,point_count_abbreviated:r})}function D(e){return e/360+.5}function C(e){const t=Math.sin(e*Math.PI/180),o=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return o<0?0:o>1?1:o}function O(e){const t=(180-360*e)*Math.PI/180;return 360*Math.atan(Math.exp(t))/Math.PI-90}function L(e,t,o,i){let r=i;const s=t+(o-t>>1);let n,a=o-t;const l=e[t],c=e[t+1],u=e[o],h=e[o+1];for(let i=t+3;ir)n=i,r=t;else if(t===r){const e=Math.abs(i-s);ei&&(n-t>3&&L(e,t,n,i),e[n+2]=r,o-n>3&&L(e,n,o,i));}function F(e,t,o,i,r,s){let n=r-o,a=s-i;if(0!==n||0!==a){const l=((e-o)*n+(t-i)*a)/(n*n+a*a);l>1?(o=r,i=s):l>0&&(o+=n*l,i+=a*l);}return n=e-o,a=t-i,n*n+a*a}function z(e,t,o,i){const r={id:null==e?null:e,type:t,geometry:o,tags:i,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("Point"===t||"MultiPoint"===t||"LineString"===t)G(r,o);else if("Polygon"===t)G(r,o[0]);else if("MultiLineString"===t)for(const e of o)G(r,e);else if("MultiPolygon"===t)for(const e of o)G(r,e[0]);return r}function G(e,t){for(let o=0;o0&&(n+=i?(r*l-a*s)/2:Math.sqrt(Math.pow(a-r,2)+Math.pow(l-s,2))),r=a,s=l;}const a=t.length-3;t[2]=1,L(t,0,a,o),t[a+2]=1,t.size=Math.abs(n),t.start=0,t.end=t.size;}function Z(e,t,o,i){for(let r=0;r1?1:o}function W(e,t,o,i,r,s,n,a){if(i/=t,s>=(o/=t)&&n=i)return null;const l=[];for(const t of e){const e=t.geometry;let s=t.type;const n=0===r?t.minX:t.minY,c=0===r?t.maxX:t.maxY;if(n>=o&&c=i)continue;let u=[];if("Point"===s||"MultiPoint"===s)R(e,u,o,i,r);else if("LineString"===s)Y(e,u,o,i,r,false,a.lineMetrics);else if("MultiLineString"===s)X(e,u,o,i,r,false);else if("Polygon"===s)X(e,u,o,i,r,true);else if("MultiPolygon"===s)for(const t of e){const e=[];X(t,e,o,i,r,true),e.length&&u.push(e);}if(u.length){if(a.lineMetrics&&"LineString"===s){for(const e of u)l.push(z(t.id,s,e,t.tags));continue}"LineString"!==s&&"MultiLineString"!==s||(1===u.length?(s="LineString",u=u[0]):s="MultiLineString"),"Point"!==s&&"MultiPoint"!==s||(s=3===u.length?"Point":"MultiPoint"),l.push(z(t.id,s,u,t.tags));}}return l.length?l:null}function R(e,t,o,i,r){for(let s=0;s=o&&n<=i&&q(t,e[s],e[s+1],e[s+2]);}}function Y(e,t,o,i,r,s,n){let a=V(e);const l=0===r?B:H;let c,u,h=e.start;for(let d=0;do&&(u=l(a,f,g,m,y,o),n&&(a.start=h+c*u)):v>i?w=o&&(u=l(a,f,g,m,y,o),x=true),w>i&&v<=i&&(u=l(a,f,g,m,y,i),x=true),!s&&x&&(n&&(a.end=h+c*u),t.push(a),a=V(e)),n&&(h+=c);}let d=e.length-3;const f=e[d],g=e[d+1],p=0===r?f:g;p>=o&&p<=i&&q(a,f,g,e[d+2]),d=a.length-3,s&&d>=3&&(a[d]!==a[0]||a[d+1]!==a[1])&&q(a,a[0],a[1],a[2]),a.length&&t.push(a);}function V(e){const t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function X(e,t,o,i,r,s){for(const n of e)Y(n,t,o,i,r,s,false);}function q(e,t,o,i){e.push(t,o,i);}function B(e,t,o,i,r,s){const n=(s-t)/(i-t);return q(e,s,o+(r-o)*n,1),n}function H(e,t,o,i,r,s){const n=(s-o)/(r-o);return q(e,t+(i-t)*n,s,1),n}function $(e,t){const o=[];for(let i=0;i0&&t.size<(r?n:i))return void(o.numPoints+=t.length/3);const a=[];for(let e=0;en)&&(o.numSimplified++,a.push(t[e],t[e+1])),o.numPoints++;r&&function(e,t){let o=0;for(let t=0,i=e.length,r=i-2;t0===t)for(let t=0,o=e.length;t24)throw new Error("maxZoom should be in the 0-24 range");if(t.promoteId&&t.generateId)throw new Error("promoteId and generateId cannot be used together.");let i=function(e,t){const o=[];if("FeatureCollection"===e.type)for(let i=0;i1&&console.time("creation"),d=this.tiles[h]=ee(e,t,o,i,l),this.tileCoords.push({z:t,x:o,y:i}),c)){c>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,o,i,d.numFeatures,d.numPoints,d.numSimplified),console.timeEnd("creation"));const e=`z${t}`;this.stats[e]=(this.stats[e]||0)+1,this.total++;}if(d.source=e,null==r){if(t===l.indexMaxZoom||d.numPoints<=l.indexMaxPoints)continue}else {if(t===l.maxZoom||t===r)continue;if(null!=r){const e=r-t;if(o!==s>>e||i!==n>>e)continue}}if(d.source=null,0===e.length)continue;c>1&&console.time("clipping");const f=.5*l.buffer/l.extent,g=.5-f,p=.5+f,m=1+f;let y=null,v=null,w=null,x=null,_=W(e,u,o-f,o+p,0,d.minX,d.maxX,l),b=W(e,u,o+g,o+m,0,d.minX,d.maxX,l);e=null,_&&(y=W(_,u,i-f,i+p,1,d.minY,d.maxY,l),v=W(_,u,i+g,i+m,1,d.minY,d.maxY,l),_=null),b&&(w=W(b,u,i-f,i+p,1,d.minY,d.maxY,l),x=W(b,u,i+g,i+m,1,d.minY,d.maxY,l),b=null),c>1&&console.timeEnd("clipping"),a.push(y||[],t+1,2*o,2*i),a.push(v||[],t+1,2*o,2*i+1),a.push(w||[],t+1,2*o+1,2*i),a.push(x||[],t+1,2*o+1,2*i+1);}}getTile(e,t,o){e=+e,t=+t,o=+o;const i=this.options,{extent:r,debug:s}=i;if(e<0||e>24)return null;const n=1<1&&console.log("drilling down to z%d-%d-%d",e,t,o);let l,c=e,u=t,h=o;for(;!l&&c>0;)c--,u>>=1,h>>=1,l=this.tiles[se(c,u,h)];return l&&l.source?(s>1&&(console.log("found parent tile z%d-%d-%d",c,u,h),console.time("drilling down")),this.splitTile(l.source,c,u,h,e,t,o),s>1&&console.timeEnd("drilling down"),this.tiles[a]?K(this.tiles[a],r):null):null}}function se(e,t,o){return 32*((1<{n.properties=e;const t={};for(const e of a)t[e]=i[e].evaluate(s,n);return t},t.reduce=(e,t)=>{n.properties=t;for(const t of a)s.accumulated=e[t],e[t]=r[t].evaluate(s,n);},t}(t)).load((yield this._pendingData).features):(r=yield this._pendingData,new re(r,t.geojsonVtOptions)),this.loaded={};const o={};if(i){const e=i.finish();e&&(o.resourceTiming={},o.resourceTiming[t.source]=JSON.parse(JSON.stringify(e)));}return o}catch(t){if(delete this._pendingRequest,e.cf(t))return {abandoned:true};throw t}var r;}))}getData(){return e._(this,undefined,undefined,(function*(){return this._pendingData}))}reloadTile(e){const t=this.loaded;return t&&t[e.uid]?super.reloadTile(e):this.loadTile(e)}loadAndProcessGeoJSON(t,o){return e._(this,undefined,undefined,(function*(){let i=yield this.loadGeoJSON(t,o);if(delete this._pendingRequest,"object"!=typeof i)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(u(i,true),t.filter){const o=e.cB(t.filter,{type:"boolean","property-type":"data-driven",overridable:false,transition:false});if("error"===o.result)throw new Error(o.value.map((e=>`${e.key}: ${e.message}`)).join(", "));const r=i.features.filter((e=>o.value.evaluate({zoom:0},e)));i={type:"FeatureCollection",features:r};}return i}))}loadGeoJSON(t,o){return e._(this,undefined,undefined,(function*(){const{promoteId:i}=t;if(t.request){const r=yield e.h(t.request,o);return this._dataUpdateable=ae(r.data,i)?le(r.data,i):undefined,r.data}if("string"==typeof t.data)try{const e=JSON.parse(t.data);return this._dataUpdateable=ae(e,i)?le(e,i):void 0,e}catch(e){throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`)}if(!t.dataDiff)throw new Error(`Input data given to '${t.source}' is not a valid GeoJSON object.`);if(!this._dataUpdateable)throw new Error(`Cannot update existing geojson data in ${t.source}`);return function(e,t,o){var i,r,s,n;if(t.removeAll&&e.clear(),t.remove)for(const o of t.remove)e.delete(o);if(t.add)for(const i of t.add){const t=ne(i,o);null!=t&&e.set(t,i);}if(t.update)for(const o of t.update){let t=e.get(o.id);if(null==t)continue;const a=!o.removeAllProperties&&((null===(i=o.removeProperties)||undefined===i?undefined:i.length)>0||(null===(r=o.addOrUpdateProperties)||undefined===r?undefined:r.length)>0);if((o.newGeometry||o.removeAllProperties||a)&&(t=Object.assign({},t),e.set(o.id,t),a&&(t.properties=Object.assign({},t.properties))),o.newGeometry&&(t.geometry=o.newGeometry),o.removeAllProperties)t.properties={};else if((null===(s=o.removeProperties)||undefined===s?undefined:s.length)>0)for(const e of o.removeProperties)Object.prototype.hasOwnProperty.call(t.properties,e)&&delete t.properties[e];if((null===(n=o.addOrUpdateProperties)||undefined===n?undefined:n.length)>0)for(const{key:e,value:i}of o.addOrUpdateProperties)t.properties[e]=i;}}(this._dataUpdateable,t.dataDiff,i),{type:"FeatureCollection",features:Array.from(this._dataUpdateable.values())}}))}removeSource(t){return e._(this,undefined,undefined,(function*(){this._pendingRequest&&this._pendingRequest.abort();}))}getClusterExpansionZoom(e){return this._geoJSONIndex.getClusterExpansionZoom(e.clusterId)}getClusterChildren(e){return this._geoJSONIndex.getChildren(e.clusterId)}getClusterLeaves(e){return this._geoJSONIndex.getLeaves(e.clusterId,e.limit,e.offset)}}class ue{constructor(t){this.self=t,this.actor=new e.F(t),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.self.registerWorkerSource=(e,t)=>{if(this.externalWorkerSourceTypes[e])throw new Error(`Worker source with name "${e}" already registered.`);this.externalWorkerSourceTypes[e]=t;},this.self.addProtocol=e.ch,this.self.removeProtocol=e.ci,this.self.registerRTLTextPlugin=t=>{e.cC.setMethods(t);},this.actor.registerMessageHandler("LDT",((e,t)=>this._getDEMWorkerSource(e,t.source).loadTile(t))),this.actor.registerMessageHandler("RDT",((t,o)=>e._(this,undefined,undefined,(function*(){this._getDEMWorkerSource(t,o.source).removeTile(o);})))),this.actor.registerMessageHandler("GCEZ",((t,o)=>e._(this,undefined,undefined,(function*(){return this._getWorkerSource(t,o.type,o.source).getClusterExpansionZoom(o)})))),this.actor.registerMessageHandler("GCC",((t,o)=>e._(this,undefined,undefined,(function*(){return this._getWorkerSource(t,o.type,o.source).getClusterChildren(o)})))),this.actor.registerMessageHandler("GCL",((t,o)=>e._(this,undefined,undefined,(function*(){return this._getWorkerSource(t,o.type,o.source).getClusterLeaves(o)})))),this.actor.registerMessageHandler("LD",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadData(t))),this.actor.registerMessageHandler("GD",((e,t)=>this._getWorkerSource(e,t.type,t.source).getData())),this.actor.registerMessageHandler("LT",((e,t)=>this._getWorkerSource(e,t.type,t.source).loadTile(t))),this.actor.registerMessageHandler("RT",((e,t)=>this._getWorkerSource(e,t.type,t.source).reloadTile(t))),this.actor.registerMessageHandler("AT",((e,t)=>this._getWorkerSource(e,t.type,t.source).abortTile(t))),this.actor.registerMessageHandler("RMT",((e,t)=>this._getWorkerSource(e,t.type,t.source).removeTile(t))),this.actor.registerMessageHandler("RS",((t,o)=>e._(this,undefined,undefined,(function*(){if(!this.workerSources[t]||!this.workerSources[t][o.type]||!this.workerSources[t][o.type][o.source])return;const e=this.workerSources[t][o.type][o.source];delete this.workerSources[t][o.type][o.source],undefined!==e.removeSource&&e.removeSource(o);})))),this.actor.registerMessageHandler("RM",(t=>e._(this,undefined,undefined,(function*(){delete this.layerIndexes[t],delete this.availableImages[t],delete this.workerSources[t],delete this.demWorkerSources[t];})))),this.actor.registerMessageHandler("SR",((t,o)=>e._(this,undefined,undefined,(function*(){this.referrer=o;})))),this.actor.registerMessageHandler("SRPS",((e,t)=>this._syncRTLPluginState(e,t))),this.actor.registerMessageHandler("IS",((t,o)=>e._(this,undefined,undefined,(function*(){this.self.importScripts(o);})))),this.actor.registerMessageHandler("SI",((e,t)=>this._setImages(e,t))),this.actor.registerMessageHandler("UL",((t,o)=>e._(this,undefined,undefined,(function*(){this._getLayerIndex(t).update(o.layers,o.removedIds);})))),this.actor.registerMessageHandler("SL",((t,o)=>e._(this,undefined,undefined,(function*(){this._getLayerIndex(t).replace(o);}))));}_setImages(t,o){return e._(this,undefined,undefined,(function*(){this.availableImages[t]=o;for(const e in this.workerSources[t]){const i=this.workerSources[t][e];for(const e in i)i[e].availableImages=o;}}))}_syncRTLPluginState(t,o){return e._(this,undefined,undefined,(function*(){return yield e.cC.syncState(o,this.self.importScripts)}))}_getAvailableImages(e){let t=this.availableImages[e];return t||(t=[]),t}_getLayerIndex(e){let o=this.layerIndexes[e];return o||(o=this.layerIndexes[e]=new t),o}_getWorkerSource(e,t,o){if(this.workerSources[e]||(this.workerSources[e]={}),this.workerSources[e][t]||(this.workerSources[e][t]={}),!this.workerSources[e][t][o]){const i={sendAsync:(t,o)=>(t.targetMapId=e,this.actor.sendAsync(t,o))};switch(t){case"vector":this.workerSources[e][t][o]=new s(i,this._getLayerIndex(e),this._getAvailableImages(e));break;case"geojson":this.workerSources[e][t][o]=new ce(i,this._getLayerIndex(e),this._getAvailableImages(e));break;default:this.workerSources[e][t][o]=new this.externalWorkerSourceTypes[t](i,this._getLayerIndex(e),this._getAvailableImages(e));}}return this.workerSources[e][t][o]}_getDEMWorkerSource(e,t){return this.demWorkerSources[e]||(this.demWorkerSources[e]={}),this.demWorkerSources[e][t]||(this.demWorkerSources[e][t]=new n),this.demWorkerSources[e][t]}}return e.i(self)&&(self.worker=new ue(self)),ue})); - - define("index",["exports","./shared"],(function(e,t){var i="5.0.0";function r(){var e=new t.A(4);return t.A!=Float32Array&&(e[1]=0,e[2]=0),e[0]=1,e[3]=1,e}let o,s;const a={now:"undefined"!=typeof performance&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date),frameAsync:e=>new Promise(((i,r)=>{const o=requestAnimationFrame(i);e.signal.addEventListener("abort",(()=>{cancelAnimationFrame(o),r(t.c());}));})),getImageData(e,t=0){return this.getImageCanvasContext(e).getImageData(-t,-t,e.width+2*t,e.height+2*t)},getImageCanvasContext(e){const t=window.document.createElement("canvas"),i=t.getContext("2d",{willReadFrequently:true});if(!i)throw new Error("failed to create canvas 2d context");return t.width=e.width,t.height=e.height,i.drawImage(e,0,0,e.width,e.height),i},resolveURL:e=>(o||(o=document.createElement("a")),o.href=e,o.href),hardwareConcurrency:"undefined"!=typeof navigator&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return !!matchMedia&&(null==s&&(s=matchMedia("(prefers-reduced-motion: reduce)")),s.matches)}};class n{static testProp(e){if(!n.docStyle)return e[0];for(let t=0;t{window.removeEventListener("click",n.suppressClickInternal,true);}),0);}static getScale(e){const t=e.getBoundingClientRect();return {x:t.width/e.offsetWidth||1,y:t.height/e.offsetHeight||1,boundingClientRect:t}}static getPoint(e,i,r){const o=i.boundingClientRect;return new t.P((r.clientX-o.left)/i.x-e.clientLeft,(r.clientY-o.top)/i.y-e.clientTop)}static mousePos(e,t){const i=n.getScale(e);return n.getPoint(e,i,t)}static touchPos(e,t){const i=[],r=n.getScale(e);for(let o=0;o{c&&_(c),c=null,d=true;},h.onerror=()=>{u=true,c=null;},h.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="),function(e){let i,r,o,s;e.resetRequestQueue=()=>{i=[],r=0,o=0,s={};},e.addThrottleControl=e=>{const t=o++;return s[t]=e,t},e.removeThrottleControl=e=>{delete s[e],n();},e.getImage=(e,r,o=true)=>new Promise(((s,a)=>{l.supported&&(e.headers||(e.headers={}),e.headers.accept="image/webp,*/*"),t.e(e,{type:"image"}),i.push({abortController:r,requestParameters:e,supportImageRefresh:o,state:"queued",onError:e=>{a(e);},onSuccess:e=>{s(e);}}),n();}));const a=e=>t._(this,undefined,undefined,(function*(){e.state="running";const{requestParameters:i,supportImageRefresh:o,onError:s,onSuccess:a,abortController:l}=e,h=false===o&&!t.i(self)&&!t.g(i.url)&&(!i.headers||Object.keys(i.headers).reduce(((e,t)=>e&&"accept"===t),true));r++;const u=h?c(i,l):t.m(i,l);try{const i=yield u;delete e.abortController,e.state="completed",i.data instanceof HTMLImageElement||t.b(i.data)?a(i):i.data&&a({data:yield(d=i.data,"function"==typeof createImageBitmap?t.d(d):t.f(d)),cacheControl:i.cacheControl,expires:i.expires});}catch(t){delete e.abortController,s(t);}finally{r--,n();}var d;})),n=()=>{const e=(()=>{for(const e of Object.keys(s))if(s[e]())return true;return false})()?t.a.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:t.a.MAX_PARALLEL_IMAGE_REQUESTS;for(let t=r;t0;t++){const e=i.shift();e.abortController.signal.aborted?t--:a(e);}},c=(e,i)=>new Promise(((r,o)=>{const s=new Image,a=e.url,n=e.credentials;n&&"include"===n?s.crossOrigin="use-credentials":(n&&"same-origin"===n||!t.s(a))&&(s.crossOrigin="anonymous"),i.signal.addEventListener("abort",(()=>{s.src="",o(t.c());})),s.fetchPriority="high",s.onload=()=>{s.onerror=s.onload=null,r({data:s});},s.onerror=()=>{s.onerror=s.onload=null,i.signal.aborted||o(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));},s.src=a;}));}(p||(p={})),p.resetRequestQueue();class m{constructor(e){this._transformRequestFn=e;}transformRequest(e,t){return this._transformRequestFn&&this._transformRequestFn(e,t)||{url:e}}setTransformRequest(e){this._transformRequestFn=e;}}function f(e){const t=[];if("string"==typeof e)t.push({id:"default",url:e});else if(e&&e.length>0){const i=[];for(const{id:r,url:o}of e){const e=`${r}${o}`;-1===i.indexOf(e)&&(i.push(e),t.push({id:r,url:o}));}}return t}function g(e,t,i){try{const r=new URL(e);return r.pathname+=`${t}${i}`,r.toString()}catch(t){throw new Error(`Invalid sprite URL "${e}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`)}}class v{constructor(e,t,i,r){this.context=e,this.format=i,this.texture=e.gl.createTexture(),this.update(t,r);}update(e,i,r){const{width:o,height:s}=e,a=!(this.size&&this.size[0]===o&&this.size[1]===s||r),{context:n}=this,{gl:l}=n;if(this.useMipmap=Boolean(i&&i.useMipmap),l.bindTexture(l.TEXTURE_2D,this.texture),n.pixelStoreUnpackFlipY.set(false),n.pixelStoreUnpack.set(1),n.pixelStoreUnpackPremultiplyAlpha.set(this.format===l.RGBA&&(!i||false!==i.premultiply)),a)this.size=[o,s],e instanceof HTMLImageElement||e instanceof HTMLCanvasElement||e instanceof HTMLVideoElement||e instanceof ImageData||t.b(e)?l.texImage2D(l.TEXTURE_2D,0,this.format,this.format,l.UNSIGNED_BYTE,e):l.texImage2D(l.TEXTURE_2D,0,this.format,o,s,0,this.format,l.UNSIGNED_BYTE,e.data);else {const{x:i,y:a}=r||{x:0,y:0};e instanceof HTMLImageElement||e instanceof HTMLCanvasElement||e instanceof HTMLVideoElement||e instanceof ImageData||t.b(e)?l.texSubImage2D(l.TEXTURE_2D,0,i,a,l.RGBA,l.UNSIGNED_BYTE,e):l.texSubImage2D(l.TEXTURE_2D,0,i,a,o,s,l.RGBA,l.UNSIGNED_BYTE,e.data);}this.useMipmap&&this.isSizePowerOfTwo()&&l.generateMipmap(l.TEXTURE_2D);}bind(e,t,i){const{context:r}=this,{gl:o}=r;o.bindTexture(o.TEXTURE_2D,this.texture),i!==o.LINEAR_MIPMAP_NEAREST||this.isSizePowerOfTwo()||(i=o.LINEAR),e!==this.filter&&(o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,e),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,i||e),this.filter=e),t!==this.wrap&&(o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,t),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,t),this.wrap=t);}isSizePowerOfTwo(){return this.size[0]===this.size[1]&&Math.log(this.size[0])/Math.LN2%1==0}destroy(){const{gl:e}=this.context;e.deleteTexture(this.texture),this.texture=null;}}function x(e){const{userImage:t}=e;return !!(t&&t.render&&t.render())&&(e.data.replace(new Uint8Array(t.data.buffer)),true)}class b extends t.E{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=false,this.requestors=[],this.patterns={},this.atlasImage=new t.R({width:1,height:1}),this.dirty=true;}isLoaded(){return this.loaded}setLoaded(e){if(this.loaded!==e&&(this.loaded=e,e)){for(const{ids:e,promiseResolve:t}of this.requestors)t(this._getImagesForIds(e));this.requestors=[];}}getImage(e){const i=this.images[e];if(i&&!i.data&&i.spriteData){const e=i.spriteData;i.data=new t.R({width:e.width,height:e.height},e.context.getImageData(e.x,e.y,e.width,e.height).data),i.spriteData=null;}return i}addImage(e,t){if(this.images[e])throw new Error(`Image id ${e} already exist, use updateImage instead`);this._validate(e,t)&&(this.images[e]=t);}_validate(e,i){let r=true;const o=i.data||i.spriteData;return this._validateStretch(i.stretchX,o&&o.width)||(this.fire(new t.j(new Error(`Image "${e}" has invalid "stretchX" value`))),r=false),this._validateStretch(i.stretchY,o&&o.height)||(this.fire(new t.j(new Error(`Image "${e}" has invalid "stretchY" value`))),r=false),this._validateContent(i.content,i)||(this.fire(new t.j(new Error(`Image "${e}" has invalid "content" value`))),r=false),r}_validateStretch(e,t){if(!e)return true;let i=0;for(const r of e){if(r[0]{let r=true;if(!this.isLoaded())for(const t of e)this.images[t]||(r=false);this.isLoaded()||r?t(this._getImagesForIds(e)):this.requestors.push({ids:e,promiseResolve:t});}))}_getImagesForIds(e){const i={};for(const r of e){let e=this.getImage(r);e||(this.fire(new t.k("styleimagemissing",{id:r})),e=this.getImage(r)),e?i[r]={data:e.data.clone(),pixelRatio:e.pixelRatio,sdf:e.sdf,version:e.version,stretchX:e.stretchX,stretchY:e.stretchY,content:e.content,textFitWidth:e.textFitWidth,textFitHeight:e.textFitHeight,hasRenderCallback:Boolean(e.userImage&&e.userImage.render)}:t.w(`Image "${r}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`);}return i}getPixelSize(){const{width:e,height:t}=this.atlasImage;return {width:e,height:t}}getPattern(e){const i=this.patterns[e],r=this.getImage(e);if(!r)return null;if(i&&i.position.version===r.version)return i.position;if(i)i.position.version=r.version;else {const i={w:r.data.width+2,h:r.data.height+2,x:0,y:0},o=new t.I(i,r);this.patterns[e]={bin:i,position:o};}return this._updatePatternAtlas(),this.patterns[e].position}bind(e){const t=e.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=false):this.atlasTexture=new v(e,this.atlasImage,t.RGBA),this.atlasTexture.bind(t.LINEAR,t.CLAMP_TO_EDGE);}_updatePatternAtlas(){const e=[];for(const t in this.patterns)e.push(this.patterns[t].bin);const{w:i,h:r}=t.p(e),o=this.atlasImage;o.resize({width:i||1,height:r||1});for(const e in this.patterns){const{bin:i}=this.patterns[e],r=i.x+1,s=i.y+1,a=this.getImage(e).data,n=a.width,l=a.height;t.R.copy(a,o,{x:0,y:0},{x:r,y:s},{width:n,height:l}),t.R.copy(a,o,{x:0,y:l-1},{x:r,y:s-1},{width:n,height:1}),t.R.copy(a,o,{x:0,y:0},{x:r,y:s+l},{width:n,height:1}),t.R.copy(a,o,{x:n-1,y:0},{x:r-1,y:s},{width:1,height:l}),t.R.copy(a,o,{x:0,y:0},{x:r+n,y:s},{width:1,height:l});}this.dirty=true;}beginFrame(){this.callbackDispatchedThisFrame={};}dispatchRenderCallbacks(e){for(const i of e){if(this.callbackDispatchedThisFrame[i])continue;this.callbackDispatchedThisFrame[i]=true;const e=this.getImage(i);e||t.w(`Image with ID: "${i}" was not found`),x(e)&&this.updateImage(i,e);}}}const y=1e20;function w(e,t,i,r,o,s,a,n,l){for(let c=t;c-1);l++,s[l]=n,a[l]=c,a[l+1]=y;}for(let n=0,l=0;n65535)throw new Error("glyphs > 65535 not supported");if(t.ranges[o])return {stack:e,id:i,glyph:r};if(!this.url)throw new Error("glyphsUrl is not set");if(!t.requests[o]){const i=P.loadGlyphRange(e,o,this.url,this.requestManager);t.requests[o]=i;}const s=yield t.requests[o];for(const e in s)this._doesCharSupportLocalGlyph(+e)||(t.glyphs[+e]=s[+e]);return t.ranges[o]=true,{stack:e,id:i,glyph:s[i]||null}}))}_doesCharSupportLocalGlyph(e){return !!this.localIdeographFontFamily&&/\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(e))}_tinySDF(e,i,r){const o=this.localIdeographFontFamily;if(!o)return;if(!this._doesCharSupportLocalGlyph(r))return;let s=e.tinySDF;if(!s){let t="400";/bold/i.test(i)?t="900":/medium/i.test(i)?t="500":/light/i.test(i)&&(t="200"),s=e.tinySDF=new P.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,fontFamily:o,fontWeight:t});}const a=s.draw(String.fromCharCode(r));return {id:r,bitmap:new t.o({width:a.width||60,height:a.height||60},a.data),metrics:{width:a.glyphWidth/2||24,height:a.glyphHeight/2||24,left:a.glyphLeft/2+.5||0,top:a.glyphTop/2-27.5||-8,advance:a.glyphAdvance/2||24,isDoubleResolution:true}}}}P.loadGlyphRange=function(e,i,r,o){return t._(this,undefined,undefined,(function*(){const s=256*i,a=s+255,n=o.transformRequest(r.replace("{fontstack}",e).replace("{range}",`${s}-${a}`),"Glyphs"),l=yield t.l(n,new AbortController);if(!l||!l.data)throw new Error(`Could not load glyph range. range: ${i}, ${s}-${a}`);const c={};for(const e of t.n(l.data))c[e.id]=e;return c}))},P.TinySDF=class{constructor({fontSize:e=24,buffer:t=3,radius:i=8,cutoff:r=.25,fontFamily:o="sans-serif",fontWeight:s="normal",fontStyle:a="normal"}={}){this.buffer=t,this.cutoff=r,this.radius=i;const n=this.size=e+4*t,l=this._createCanvas(n),c=this.ctx=l.getContext("2d",{willReadFrequently:true});c.font=`${a} ${s} ${e}px ${o}`,c.textBaseline="alphabetic",c.textAlign="left",c.fillStyle="black",this.gridOuter=new Float64Array(n*n),this.gridInner=new Float64Array(n*n),this.f=new Float64Array(n),this.z=new Float64Array(n+1),this.v=new Uint16Array(n);}_createCanvas(e){const t=document.createElement("canvas");return t.width=t.height=e,t}draw(e){const{width:t,actualBoundingBoxAscent:i,actualBoundingBoxDescent:r,actualBoundingBoxLeft:o,actualBoundingBoxRight:s}=this.ctx.measureText(e),a=Math.ceil(i),n=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(s-o))),l=Math.min(this.size-this.buffer,a+Math.ceil(r)),c=n+2*this.buffer,h=l+2*this.buffer,u=Math.max(c*h,0),d=new Uint8ClampedArray(u),_={data:d,width:c,height:h,glyphWidth:n,glyphHeight:l,glyphTop:a,glyphLeft:0,glyphAdvance:t};if(0===n||0===l)return _;const{ctx:p,buffer:m,gridInner:f,gridOuter:g}=this;p.clearRect(m,m,n,l),p.fillText(e,m,m+a);const v=p.getImageData(m,m,n,l);g.fill(y,0,u),f.fill(0,0,u);for(let e=0;e0?e*e:0,f[r]=e<0?e*e:0;}}w(g,0,0,c,h,c,this.f,this.v,this.z),w(f,m,m,n,l,c,this.f,this.v,this.z);for(let e=0;e1&&(a=e[++s]);const l=Math.abs(n-a.left),c=Math.abs(n-a.right),h=Math.min(l,c);let u;const d=t/i*(r+1);if(a.isDash){const e=r-Math.abs(d);u=Math.sqrt(h*h+e*e);}else u=r-Math.sqrt(h*h+d*d);this.data[o+n]=Math.max(0,Math.min(255,u+128));}}}addRegularDash(e){for(let t=e.length-1;t>=0;--t){const i=e[t],r=e[t+1];i.zeroLength?e.splice(t,1):r&&r.isDash===i.isDash&&(r.left=i.left,e.splice(t,1));}const t=e[0],i=e[e.length-1];t.isDash===i.isDash&&(t.left=i.left-this.width,i.right=t.right+this.width);const r=this.width*this.nextRow;let o=0,s=e[o];for(let t=0;t1&&(s=e[++o]);const i=Math.abs(t-s.left),a=Math.abs(t-s.right),n=Math.min(i,a);this.data[r+t]=Math.max(0,Math.min(255,(s.isDash?n:-n)+128));}}addDash(e,i){const r=i?7:0,o=2*r+1;if(this.nextRow+o>this.height)return t.w("LineAtlas out of space"),null;let s=0;for(let t=0;t{e.terminate();})),this.workers=null);}isPreloaded(){return !!this.active[D]}numActive(){return Object.keys(this.active).length}}const A=Math.floor(a.hardwareConcurrency/2);let L,k;function F(){return L||(L=new z),L}z.workerCount=t.C(globalThis)?Math.max(Math.min(A,3),1):1;class B{constructor(e,i){this.workerPool=e,this.actors=[],this.currentActor=0,this.id=i;const r=this.workerPool.acquire(i);for(let e=0;e{e.remove();})),this.actors=[],e&&this.workerPool.release(this.id);}registerMessageHandler(e,t){for(const i of this.actors)i.registerMessageHandler(e,t);}}function j(){return k||(k=new B(F(),t.G),k.registerMessageHandler("GR",((e,i,r)=>t.m(i,r)))),k}function O(e,i){const r=t.H();return t.J(r,r,[1,1,0]),t.K(r,r,[.5*e.width,.5*e.height,1]),e.calculatePosMatrix?t.L(r,r,e.calculatePosMatrix(i.toUnwrapped())):r}function N(e,t,i,r,o,s){var a;const n=function(e,t,i){if(e)for(const r of e){const e=t[r];if(e&&e.source===i&&"fill-extrusion"===e.type)return true}else for(const e in t){const r=t[e];if(r.source===i&&"fill-extrusion"===r.type)return true}return false}(null!==(a=null==o?undefined:o.layers)&&undefined!==a?a:null,t,e.id),l=s.maxPitchScaleFactor(),c=e.tilesIn(r,l,n);c.sort(Z);const h=[];for(const r of c)h.push({wrappedTileID:r.tileID.wrapped().key,queryResults:r.tile.queryRenderedFeatures(t,i,e._state,r.queryGeometry,r.cameraQueryGeometry,r.scale,o,s,l,O(e.transform,r.tileID))});return function(e,t){for(const i in e)for(const r of e[i])G(r,t);return e}(function(e){const t={},i={};for(const r of e){const e=r.queryResults,o=r.wrappedTileID,s=i[o]=i[o]||{};for(const i in e){const r=e[i],o=s[i]=s[i]||{},a=t[i]=t[i]||[];for(const e of r)o[e.featureIndex]||(o[e.featureIndex]=true,a.push(e));}}return t}(h),e)}function Z(e,t){const i=e.tileID,r=t.tileID;return i.overscaledZ-r.overscaledZ||i.canonical.y-r.canonical.y||i.wrap-r.wrap||i.canonical.x-r.canonical.x}function G(e,t){const i=e.feature,r=t.getFeatureState(i.layer["source-layer"],i.id);i.source=i.layer.source,i.layer["source-layer"]&&(i.sourceLayer=i.layer["source-layer"]),i.state=r;}function U(e,i,r){return t._(this,undefined,undefined,(function*(){let o=e;if(e.url?o=(yield t.h(i.transformRequest(e.url,"Source"),r)).data:yield a.frameAsync(r),!o)return null;const s=t.M(t.e(o,e),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return "vector_layers"in o&&o.vector_layers&&(s.vectorLayerIds=o.vector_layers.map((e=>e.id))),s}))}class V{constructor(e,t){e&&(t?this.setSouthWest(e).setNorthEast(t):Array.isArray(e)&&(4===e.length?this.setSouthWest([e[0],e[1]]).setNorthEast([e[2],e[3]]):this.setSouthWest(e[0]).setNorthEast(e[1])));}setNorthEast(e){return this._ne=e instanceof t.N?new t.N(e.lng,e.lat):t.N.convert(e),this}setSouthWest(e){return this._sw=e instanceof t.N?new t.N(e.lng,e.lat):t.N.convert(e),this}extend(e){const i=this._sw,r=this._ne;let o,s;if(e instanceof t.N)o=e,s=e;else {if(!(e instanceof V))return Array.isArray(e)?4===e.length||e.every(Array.isArray)?this.extend(V.convert(e)):this.extend(t.N.convert(e)):e&&("lng"in e||"lon"in e)&&"lat"in e?this.extend(t.N.convert(e)):this;if(o=e._sw,s=e._ne,!o||!s)return this}return i||r?(i.lng=Math.min(o.lng,i.lng),i.lat=Math.min(o.lat,i.lat),r.lng=Math.max(s.lng,r.lng),r.lat=Math.max(s.lat,r.lat)):(this._sw=new t.N(o.lng,o.lat),this._ne=new t.N(s.lng,s.lat)),this}getCenter(){return new t.N((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new t.N(this.getWest(),this.getNorth())}getSouthEast(){return new t.N(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return [this._sw.toArray(),this._ne.toArray()]}toString(){return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return !(this._sw&&this._ne)}contains(e){const{lng:i,lat:r}=t.N.convert(e);let o=this._sw.lng<=i&&i<=this._ne.lng;return this._sw.lng>this._ne.lng&&(o=this._sw.lng>=i&&i>=this._ne.lng),this._sw.lat<=r&&r<=this._ne.lat&&o}static convert(e){return e instanceof V?e:e?new V(e):e}static fromLngLat(e,i=0){const r=360*i/40075017,o=r/Math.cos(Math.PI/180*e.lat);return new V(new t.N(e.lng-o,e.lat-r),new t.N(e.lng+o,e.lat+r))}adjustAntiMeridian(){const e=new t.N(this._sw.lng,this._sw.lat),i=new t.N(this._ne.lng,this._ne.lat);return new V(e,e.lng>i.lng?new t.N(i.lng+360,i.lat):i)}}class q{constructor(e,t,i){this.bounds=V.convert(this.validateBounds(e)),this.minzoom=t||0,this.maxzoom=i||24;}validateBounds(e){return Array.isArray(e)&&4===e.length?[Math.max(-180,e[0]),Math.max(-90,e[1]),Math.min(180,e[2]),Math.min(90,e[3])]:[-180,-90,180,90]}contains(e){const i=Math.pow(2,e.z),r=Math.floor(t.O(this.bounds.getWest())*i),o=Math.floor(t.Q(this.bounds.getNorth())*i),s=Math.ceil(t.O(this.bounds.getEast())*i),a=Math.ceil(t.Q(this.bounds.getSouth())*i);return e.x>=r&&e.x=o&&e.y{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}serialize(){return t.e({},this._options)}loadTile(e){return t._(this,undefined,undefined,(function*(){const t=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),i={request:this.map._requestManager.transformRequest(t,"Tile"),uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,tileSize:this.tileSize*e.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};i.request.collectResourceTiming=this._collectResourceTiming;let r="RT";if(e.actor&&"expired"!==e.state){if("loading"===e.state)return new Promise(((t,i)=>{e.reloadPromise={resolve:t,reject:i};}))}else e.actor=this.dispatcher.getActor(),r="LT";e.abortController=new AbortController;try{const t=yield e.actor.sendAsync({type:r,data:i},e.abortController);if(delete e.abortController,e.aborted)return;this._afterTileLoadWorkerResponse(e,t);}catch(t){if(delete e.abortController,e.aborted)return;if(t&&404!==t.status)throw t;this._afterTileLoadWorkerResponse(e,null);}}))}_afterTileLoadWorkerResponse(e,t){if(t&&t.resourceTiming&&(e.resourceTiming=t.resourceTiming),t&&this.map._refreshExpiredTiles&&e.setExpiryData(t),e.loadVectorData(t,this.map.painter),e.reloadPromise){const t=e.reloadPromise;e.reloadPromise=null,this.loadTile(e).then(t.resolve).catch(t.reject);}}abortTile(e){return t._(this,undefined,undefined,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.actor&&(yield e.actor.sendAsync({type:"AT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}unloadTile(e){return t._(this,undefined,undefined,(function*(){e.unloadVectorData(),e.actor&&(yield e.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}}));}))}hasTransition(){return false}}class W extends t.E{constructor(e,i,r,o){super(),this.id=e,this.dispatcher=r,this.setEventedParent(o),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=true,this.scheme="xyz",this.tileSize=512,this._loaded=false,this._options=t.e({type:"raster"},i),t.e(this,t.M(i,["url","scheme","tileSize"]));}load(){return t._(this,arguments,undefined,(function*(e=false){this._loaded=false,this.fire(new t.k("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{const i=yield U(this._options,this.map._requestManager,this._tileJSONRequest);this._tileJSONRequest=null,this._loaded=!0,i&&(t.e(this,i),i.bounds&&(this.tileBounds=new q(i.bounds,this.minzoom,this.maxzoom)),this.fire(new t.k("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new t.k("data",{dataType:"source",sourceDataType:"content",sourceDataChanged:e})));}catch(e){this._tileJSONRequest=null,this.fire(new t.j(e));}}))}loaded(){return this._loaded}onAdd(e){this.map=e,this.load();}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null);}setSourceProperty(e){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),e(),this.load(true);}setTiles(e){return this.setSourceProperty((()=>{this._options.tiles=e;})),this}setUrl(e){return this.setSourceProperty((()=>{this.url=e,this._options.url=e;})),this}serialize(){return t.e({},this._options)}hasTile(e){return !this.tileBounds||this.tileBounds.contains(e.canonical)}loadTile(e){return t._(this,undefined,undefined,(function*(){const t=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);e.abortController=new AbortController;try{const i=yield p.getImage(this.map._requestManager.transformRequest(t,"Tile"),e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(i&&i.data){this.map._refreshExpiredTiles&&i.cacheControl&&i.expires&&e.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const t=this.map.painter.context,r=t.gl,o=i.data;e.texture=this.map.painter.getTileTexture(o.width),e.texture?e.texture.update(o,{useMipmap:!0}):(e.texture=new v(t,o,r.RGBA,{useMipmap:!0}),e.texture.bind(r.LINEAR,r.CLAMP_TO_EDGE,r.LINEAR_MIPMAP_NEAREST)),e.state="loaded";}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}abortTile(e){return t._(this,undefined,undefined,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController);}))}unloadTile(e){return t._(this,undefined,undefined,(function*(){e.texture&&this.map.painter.saveTileTexture(e.texture);}))}hasTransition(){return false}}class X extends W{constructor(e,i,r,o){super(e,i,r,o),this.type="raster-dem",this.maxzoom=22,this._options=t.e({type:"raster-dem"},i),this.encoding=i.encoding||"mapbox",this.redFactor=i.redFactor,this.greenFactor=i.greenFactor,this.blueFactor=i.blueFactor,this.baseShift=i.baseShift;}loadTile(e){return t._(this,undefined,undefined,(function*(){const i=e.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),r=this.map._requestManager.transformRequest(i,"Tile");e.neighboringTiles=this._getNeighboringTiles(e.tileID),e.abortController=new AbortController;try{const i=yield p.getImage(r,e.abortController,this.map._refreshExpiredTiles);if(delete e.abortController,e.aborted)return void(e.state="unloaded");if(i&&i.data){const r=i.data;this.map._refreshExpiredTiles&&i.cacheControl&&i.expires&&e.setExpiryData({cacheControl:i.cacheControl,expires:i.expires});const o=t.b(r)&&t.U()?r:yield this.readImageNow(r),s={type:this.type,uid:e.uid,source:this.id,rawImageData:o,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(!e.actor||"expired"===e.state){e.actor=this.dispatcher.getActor();const t=yield e.actor.sendAsync({type:"LDT",data:s});e.dem=t,e.needsHillshadePrepare=!0,e.needsTerrainPrepare=!0,e.state="loaded";}}}catch(t){if(delete e.abortController,e.aborted)e.state="unloaded";else if(t)throw e.state="errored",t}}))}readImageNow(e){return t._(this,undefined,undefined,(function*(){if("undefined"!=typeof VideoFrame&&t.V()){const i=e.width+2,r=e.height+2;try{return new t.R({width:i,height:r},yield t.W(e,-1,-1,i,r))}catch(e){}}return a.getImageData(e,1)}))}_getNeighboringTiles(e){const i=e.canonical,r=Math.pow(2,i.z),o=(i.x-1+r)%r,s=0===i.x?e.wrap-1:e.wrap,a=(i.x+1+r)%r,n=i.x+1===r?e.wrap+1:e.wrap,l={};return l[new t.S(e.overscaledZ,s,i.z,o,i.y).key]={backfilled:false},l[new t.S(e.overscaledZ,n,i.z,a,i.y).key]={backfilled:false},i.y>0&&(l[new t.S(e.overscaledZ,s,i.z,o,i.y-1).key]={backfilled:false},l[new t.S(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:false},l[new t.S(e.overscaledZ,n,i.z,a,i.y-1).key]={backfilled:false}),i.y+10&&t.e(o,{resourceTiming:r}),this.fire(new t.k("data",Object.assign(Object.assign({},o),{sourceDataType:"metadata"}))),this.fire(new t.k("data",Object.assign(Object.assign({},o),{sourceDataType:"content"})));}catch(e){if(this._pendingLoads--,this._removed)return void this.fire(new t.k("dataabort",{dataType:"source"}));this.fire(new t.j(e));}}))}loaded(){return 0===this._pendingLoads}loadTile(e){return t._(this,undefined,undefined,(function*(){const t=e.actor?"RT":"LT";e.actor=this.actor;const i={type:this.type,uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};e.abortController=new AbortController;const r=yield this.actor.sendAsync({type:t,data:i},e.abortController);delete e.abortController,e.unloadVectorData(),e.aborted||e.loadVectorData(r,this.map.painter,"RT"===t);}))}abortTile(e){return t._(this,undefined,undefined,(function*(){e.abortController&&(e.abortController.abort(),delete e.abortController),e.aborted=true;}))}unloadTile(e){return t._(this,undefined,undefined,(function*(){e.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:e.uid,type:this.type,source:this.id}});}))}onRemove(){this._removed=true,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}});}serialize(){return t.e({},this._options,{type:this.type,data:this._data})}hasTransition(){return false}}class K extends t.E{constructor(e,t,i,r){super(),this.flippedWindingOrder=false,this.id=e,this.dispatcher=i,this.coordinates=t.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=false,this.setEventedParent(r),this.options=t;}load(e){return t._(this,undefined,undefined,(function*(){this._loaded=false,this.fire(new t.k("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{const t=yield p.getImage(this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,t&&t.data&&(this.image=t.data,e&&(this.coordinates=e),this._finishLoading());}catch(e){this._request=null,this._loaded=true,this.fire(new t.j(e));}}))}loaded(){return this._loaded}updateImage(e){return e.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=e.url,this.load(e.coordinates).finally((()=>{this.texture=null;})),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.k("data",{dataType:"source",sourceDataType:"metadata"})));}onAdd(e){this.map=e,this.load();}onRemove(){this._request&&(this._request.abort(),this._request=null);}setCoordinates(e){this.coordinates=e;const i=e.map(t.Y.fromLngLat);var r;return this.tileID=function(e){let i=1/0,r=1/0,o=-1/0,s=-1/0;for(const t of e)i=Math.min(i,t.x),r=Math.min(r,t.y),o=Math.max(o,t.x),s=Math.max(s,t.y);const a=Math.max(o-i,s-r),n=Math.max(0,Math.floor(-Math.log(a)/Math.LN2)),l=Math.pow(2,n);return new t.Z(n,Math.floor((i+o)/2*l),Math.floor((r+s)/2*l))}(i),this.minzoom=this.maxzoom=this.tileID.z,this.tileCoords=i.map((e=>this.tileID.getTilePoint(e)._round())),this.flippedWindingOrder=((r=this.tileCoords)[1].x-r[0].x)*(r[2].y-r[0].y)-(r[1].y-r[0].y)*(r[2].x-r[0].x)<0,this.fire(new t.k("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(0===Object.keys(this.tiles).length||!this.image)return;const e=this.map.painter.context,i=e.gl;this.texture||(this.texture=new v(e,this.image,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let r=false;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,r=true);}r&&this.fire(new t.k("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}loadTile(e){return t._(this,undefined,undefined,(function*(){this.tileID&&this.tileID.equals(e.tileID.canonical)?(this.tiles[String(e.tileID.wrap)]=e,e.buckets={}):e.state="errored";}))}serialize(){return {type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return false}}class Y extends K{constructor(e,t,i,r){super(e,t,i,r),this.roundZoom=true,this.type="video",this.options=t;}load(){return t._(this,undefined,undefined,(function*(){this._loaded=false;const e=this.options;this.urls=[];for(const t of e.urls)this.urls.push(this.map._requestManager.transformRequest(t,"Source").url);try{const e=yield t.a0(this.urls);if(this._loaded=!0,!e)return;this.video=e,this.video.loop=!0,this.video.addEventListener("playing",(()=>{this.map.triggerRepaint();})),this.map&&this.video.play(),this._finishLoading();}catch(e){this.fire(new t.j(e));}}))}pause(){this.video&&this.video.pause();}play(){this.video&&this.video.play();}seek(e){if(this.video){const i=this.video.seekable;ei.end(0)?this.fire(new t.j(new t.$(`sources.${this.id}`,null,`Playback for this video can be set only between the ${i.start(0)} and ${i.end(0)}-second mark.`))):this.video.currentTime=e;}}getVideo(){return this.video}onAdd(e){this.map||(this.map=e,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));}prepare(){if(0===Object.keys(this.tiles).length||this.video.readyState<2)return;const e=this.map.painter.context,i=e.gl;this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new v(e,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE));let r=false;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,r=true);}r&&this.fire(new t.k("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class J extends K{constructor(e,i,r,o){super(e,i,r,o),i.coordinates?Array.isArray(i.coordinates)&&4===i.coordinates.length&&!i.coordinates.some((e=>!Array.isArray(e)||2!==e.length||e.some((e=>"number"!=typeof e))))||this.fire(new t.j(new t.$(`sources.${e}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.j(new t.$(`sources.${e}`,null,'missing required property "coordinates"'))),i.animate&&"boolean"!=typeof i.animate&&this.fire(new t.j(new t.$(`sources.${e}`,null,'optional "animate" property must be a boolean value'))),i.canvas?"string"==typeof i.canvas||i.canvas instanceof HTMLCanvasElement||this.fire(new t.j(new t.$(`sources.${e}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.j(new t.$(`sources.${e}`,null,'missing required property "canvas"'))),this.options=i,this.animate=undefined===i.animate||i.animate;}load(){return t._(this,undefined,undefined,(function*(){this._loaded=true,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.j(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=true,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=false);},this._finishLoading());}))}getCanvas(){return this.canvas}onAdd(e){this.map=e,this.load(),this.canvas&&this.animate&&this.play();}onRemove(){this.pause();}prepare(){let e=false;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=true),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=true),this._hasInvalidDimensions())return;if(0===Object.keys(this.tiles).length)return;const i=this.map.painter.context,r=i.gl;this.texture?(e||this._playing)&&this.texture.update(this.canvas,{premultiply:true}):this.texture=new v(i,this.canvas,r.RGBA,{premultiply:true});let o=false;for(const e in this.tiles){const t=this.tiles[e];"loaded"!==t.state&&(t.state="loaded",t.texture=this.texture,o=true);}o&&this.fire(new t.k("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}));}serialize(){return {type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const e of [this.canvas.width,this.canvas.height])if(isNaN(e)||e<=0)return true;return false}}const Q={},ee=e=>{switch(e){case"geojson":return $;case"image":return K;case"raster":return W;case"raster-dem":return X;case"vector":return H;case"video":return Y;case"canvas":return J}return Q[e]},te="RTLPluginLoaded";class ie extends t.E{constructor(){super(...arguments),this.status="unavailable",this.url=null,this.dispatcher=j();}_syncState(e){return this.status=e,this.dispatcher.broadcast("SRPS",{pluginStatus:e,pluginURL:this.url}).catch((e=>{throw this.status="error",e}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null;}setRTLTextPlugin(e){return t._(this,arguments,undefined,(function*(e,t=false){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=a.resolveURL(e),!this.url)throw new Error(`requested url ${e} is invalid`);if("unavailable"===this.status){if(!t)return this._requestImport();this.status="deferred",this._syncState(this.status);}else if("requested"===this.status)return this._requestImport()}))}_requestImport(){return t._(this,undefined,undefined,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new t.k(te));}))}lazyLoad(){"unavailable"===this.status?this.status="requested":"deferred"===this.status&&this._requestImport();}}let re=null;function oe(){return re||(re=new ie),re}class se{constructor(e,i){this.timeAdded=0,this.fadeEndTime=0,this.tileID=e,this.uid=t.a1(),this.uses=0,this.tileSize=i,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=false,this.hasRTLText=false,this.dependencies={},this.rtt=[],this.rttCoords={},this.expiredRequestCount=0,this.state="loading";}registerFadeDuration(e){const t=e+this.timeAdded;tt.getLayer(e))).filter(Boolean);if(0!==e.length){r.layers=e,r.stateDependentLayerIds&&(r.stateDependentLayers=r.stateDependentLayerIds.map((t=>e.filter((e=>e.id===t))[0])));for(const t of e)i[t.id]=r;}}return i}(e.buckets,null==i?undefined:i.style),this.hasSymbolBuckets=false;for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a3){if(this.hasSymbolBuckets=true,!r)break;i.justReloaded=true;}}if(this.hasRTLText=false,this.hasSymbolBuckets)for(const e in this.buckets){const i=this.buckets[e];if(i instanceof t.a3&&i.hasRTLText){this.hasRTLText=true,oe().lazyLoad();break}}this.queryPadding=0;for(const e in this.buckets){const t=this.buckets[e];this.queryPadding=Math.max(this.queryPadding,i.style.getLayer(e).queryRadius(t));}e.imageAtlas&&(this.imageAtlas=e.imageAtlas),e.glyphAtlasImage&&(this.glyphAtlasImage=e.glyphAtlasImage);}else this.collisionBoxArray=new t.a2;}unloadVectorData(){for(const e in this.buckets)this.buckets[e].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded";}getBucket(e){return this.buckets[e.id]}upload(e){for(const t in this.buckets){const i=this.buckets[t];i.uploadPending()&&i.upload(e);}const t=e.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new v(e,this.imageAtlas.image,t.RGBA),this.imageAtlas.uploaded=true),this.glyphAtlasImage&&(this.glyphAtlasTexture=new v(e,this.glyphAtlasImage,t.ALPHA),this.glyphAtlasImage=null);}prepare(e){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(e,this.imageAtlasTexture);}queryRenderedFeatures(e,t,i,r,o,s,a,n,l,c){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:r,cameraQueryGeometry:o,scale:s,tileSize:this.tileSize,pixelPosMatrix:c,transform:n,params:a,queryPadding:this.queryPadding*l},e,t,i):{}}querySourceFeatures(e,i){const r=this.latestFeatureIndex;if(!r||!r.rawTileData)return;const o=r.loadVTLayers(),s=i&&i.sourceLayer?i.sourceLayer:"",a=o._geojsonTileLayer||o[s];if(!a)return;const n=t.a4(i&&i.filter),{z:l,x:c,y:h}=this.tileID.canonical,u={z:l,x:c,y:h};for(let i=0;ie)t=false;else if(i)if(this.expirationTime{this.remove(e,o);}),i)),this.data[r].push(o),this.order.push(r),this.order.length>this.max){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}has(e){return e.wrapped().key in this.data}getAndRemove(e){return this.has(e)?this._getAndRemoveByKey(e.wrapped().key):null}_getAndRemoveByKey(e){const t=this.data[e].shift();return t.timeout&&clearTimeout(t.timeout),0===this.data[e].length&&delete this.data[e],this.order.splice(this.order.indexOf(e),1),t.value}getByKey(e){const t=this.data[e];return t?t[0].value:null}get(e){return this.has(e)?this.data[e.wrapped().key][0].value:null}remove(e,t){if(!this.has(e))return this;const i=e.wrapped().key,r=undefined===t?0:this.data[i].indexOf(t),o=this.data[i][r];return this.data[i].splice(r,1),o.timeout&&clearTimeout(o.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(o.value),this.order.splice(this.order.indexOf(i),1),this}setMaxSize(e){for(this.max=e;this.order.length>this.max;){const e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this}filter(e){const t=[];for(const i in this.data)for(const r of this.data[i])e(r.value)||t.push(r);for(const e of t)this.remove(e.value.tileID,e);}}class ne{constructor(){this.state={},this.stateChanges={},this.deletedStates={};}updateState(e,i,r){const o=String(i);if(this.stateChanges[e]=this.stateChanges[e]||{},this.stateChanges[e][o]=this.stateChanges[e][o]||{},t.e(this.stateChanges[e][o],r),null===this.deletedStates[e]){this.deletedStates[e]={};for(const t in this.state[e])t!==o&&(this.deletedStates[e][t]=null);}else if(this.deletedStates[e]&&null===this.deletedStates[e][o]){this.deletedStates[e][o]={};for(const t in this.state[e][o])r[t]||(this.deletedStates[e][o][t]=null);}else for(const t in r)this.deletedStates[e]&&this.deletedStates[e][o]&&null===this.deletedStates[e][o][t]&&delete this.deletedStates[e][o][t];}removeFeatureState(e,t,i){if(null===this.deletedStates[e])return;const r=String(t);if(this.deletedStates[e]=this.deletedStates[e]||{},i&&undefined!==t)null!==this.deletedStates[e][r]&&(this.deletedStates[e][r]=this.deletedStates[e][r]||{},this.deletedStates[e][r][i]=null);else if(undefined!==t)if(this.stateChanges[e]&&this.stateChanges[e][r])for(i in this.deletedStates[e][r]={},this.stateChanges[e][r])this.deletedStates[e][r][i]=null;else this.deletedStates[e][r]=null;else this.deletedStates[e]=null;}getState(e,i){const r=String(i),o=t.e({},(this.state[e]||{})[r],(this.stateChanges[e]||{})[r]);if(null===this.deletedStates[e])return {};if(this.deletedStates[e]){const t=this.deletedStates[e][i];if(null===t)return {};for(const e in t)delete o[e];}return o}initializeTileState(e,t){e.setFeatureState(this.state,t);}coalesceChanges(e,i){const r={};for(const e in this.stateChanges){this.state[e]=this.state[e]||{};const i={};for(const r in this.stateChanges[e])this.state[e][r]||(this.state[e][r]={}),t.e(this.state[e][r],this.stateChanges[e][r]),i[r]=this.state[e][r];r[e]=i;}for(const e in this.deletedStates){this.state[e]=this.state[e]||{};const i={};if(null===this.deletedStates[e])for(const t in this.state[e])i[t]={},this.state[e][t]={};else for(const t in this.deletedStates[e]){if(null===this.deletedStates[e][t])this.state[e][t]={};else for(const i of Object.keys(this.deletedStates[e][t]))delete this.state[e][t][i];i[t]=this.state[e][t];}r[e]=r[e]||{},t.e(r[e],i);}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(r).length)for(const t in e)e[t].setFeatureState(r,i);}}function le(e,t,i){const r=t.intersectsFrustum(e);if(!i)return r;const o=t.intersectsPlane(i);return 0===r||0===o?0:2===r&&2===o?2:1}function ce(e,i,r,o,s){let a=e;const n=Math.atan(i/r),l=Math.hypot(i,r);return a=e+t.a8(o/l/Math.max(.5,Math.cos(t.aa(s/2)))),a+=1*t.a8(Math.cos(n))/2,a+=t.ab(e-a,-0,0),a}function he(e,i){const r=(i.roundZoom?Math.round:Math.floor)(e.zoom+t.a8(e.tileSize/i.tileSize));return Math.max(0,r)}function ue(e,i){const r=e.getCameraFrustum(),o=e.getClippingPlane(),s=e.screenPointToMercatorCoordinate(e.getCameraPoint()),a=t.Y.fromLngLat(e.center,e.elevation);s.z=a.z+Math.cos(e.pitchInRadians)*e.cameraToCenterDistance/e.worldSize;const n=e.getCoveringTilesDetailsProvider(),l=n.allowVariableZoom(e,i),c=he(e,i),h=i.minzoom||0,u=undefined!==i.maxzoom?i.maxzoom:e.maxZoom,d=Math.min(Math.max(0,c),u),_=Math.pow(2,d),p=[_*s.x,_*s.y,0],m=[_*a.x,_*a.y,0],f=Math.hypot(a.x-s.x,a.y-s.y),g=Math.abs(a.z-s.z),v=Math.hypot(f,g),x=e=>({zoom:0,x:0,y:0,wrap:e,fullyVisible:false}),b=[],y=[];if(e.renderWorldCopies&&n.allowWorldCopies())for(let e=1;e<=3;e++)b.push(x(-e)),b.push(x(e));for(b.push(x(0));b.length>0;){const _=b.pop(),f=_.x,x=_.y;let w=_.fullyVisible;const T={x:f,y:x,z:_.zoom},P=n.getTileAABB(T,_.wrap,e.elevation,i);if(!w){const e=le(r,P,o);if(0===e)continue;w=2===e;}const C=n.distanceToTile2d(s.x,s.y,T,P);let I=c;l&&(I=(i.calculateTileZoom||ce)(e.zoom+t.a8(e.tileSize/i.tileSize),C,g,v,e.fov)),I=(i.roundZoom?Math.round:Math.floor)(I),I=Math.max(0,I);const E=Math.min(I,u);if(_.wrap=n.getWrap(a,T,_.wrap),_.zoom>=E){if(_.zoom>1),wrap:_.wrap,fullyVisible:w});}return y.sort(((e,t)=>e.distanceSq-t.distanceSq)).map((e=>e.tileID))}class de extends t.E{constructor(e,t,i){super(),this.id=e,this.dispatcher=i,this.on("data",(e=>this._dataHandler(e))),this.on("dataloading",(()=>{this._sourceErrored=false;})),this.on("error",(()=>{this._sourceErrored=this._source.loaded();})),this._source=((e,t,i,r)=>{const o=new(ee(t.type))(e,t,i,r);if(o.id!==e)throw new Error(`Expected Source id to be ${e} instead of ${o.id}`);return o})(e,t,i,this),this._tiles={},this._cache=new ae(0,(e=>this._unloadTile(e))),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new ne,this._didEmitContent=false,this._updated=false;}onAdd(e){this.map=e,this._maxTileCacheSize=e?e._maxTileCacheSize:null,this._maxTileCacheZoomLevels=e?e._maxTileCacheZoomLevels:null,this._source&&this._source.onAdd&&this._source.onAdd(e);}onRemove(e){this.clearTiles(),this._source&&this._source.onRemove&&this._source.onRemove(e);}loaded(){if(this._sourceErrored)return true;if(!this._sourceLoaded)return false;if(!this._source.loaded())return false;if(!(undefined===this.used&&undefined===this.usedForTerrain||this.used||this.usedForTerrain))return true;if(!this._updated)return false;for(const e in this._tiles){const t=this._tiles[e];if("loaded"!==t.state&&"errored"!==t.state)return false}return true}getSource(){return this._source}pause(){this._paused=true;}resume(){if(!this._paused)return;const e=this._shouldReloadOnResume;this._paused=false,this._shouldReloadOnResume=false,e&&this.reload(),this.transform&&this.update(this.transform,this.terrain);}_loadTile(e,i,r){return t._(this,undefined,undefined,(function*(){try{yield this._source.loadTile(e),this._tileLoaded(e,i,r);}catch(i){e.state="errored",404!==i.status?this._source.fire(new t.j(i,{tile:e})):this.update(this.transform,this.terrain);}}))}_unloadTile(e){this._source.unloadTile&&this._source.unloadTile(e);}_abortTile(e){this._source.abortTile&&this._source.abortTile(e),this._source.fire(new t.k("dataabort",{tile:e,coord:e.tileID,dataType:"source"}));}serialize(){return this._source.serialize()}prepare(e){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const t in this._tiles){const i=this._tiles[t];i.upload(e),i.prepare(this.map.style.imageManager);}}getIds(){return Object.values(this._tiles).map((e=>e.tileID)).sort(_e).map((e=>e.key))}getRenderableIds(e){const i=[];for(const t in this._tiles)this._isIdRenderable(t,e)&&i.push(this._tiles[t]);return e?i.sort(((e,i)=>{const r=e.tileID,o=i.tileID,s=new t.P(r.canonical.x,r.canonical.y)._rotate(-this.transform.bearingInRadians),a=new t.P(o.canonical.x,o.canonical.y)._rotate(-this.transform.bearingInRadians);return r.overscaledZ-o.overscaledZ||a.y-s.y||a.x-s.x})).map((e=>e.tileID.key)):i.map((e=>e.tileID)).sort(_e).map((e=>e.key))}hasRenderableParent(e){const t=this.findLoadedParent(e,0);return !!t&&this._isIdRenderable(t.tileID.key)}_isIdRenderable(e,t){return this._tiles[e]&&this._tiles[e].hasData()&&!this._coveredTiles[e]&&(t||!this._tiles[e].holdingForFade())}reload(e){if(this._paused)this._shouldReloadOnResume=true;else {this._cache.reset();for(const t in this._tiles)(e||"errored"!==this._tiles[t].state)&&this._reloadTile(t,"reloading");}}_reloadTile(e,i){return t._(this,undefined,undefined,(function*(){const t=this._tiles[e];t&&("loading"!==t.state&&(t.state=i),yield this._loadTile(t,e,i));}))}_tileLoaded(e,i,r){e.timeAdded=a.now(),"expired"===r&&(e.refreshedUponExpiration=true),this._setTileReloadTimer(i,e),"raster-dem"===this.getSource().type&&e.dem&&this._backfillDEM(e),this._state.initializeTileState(e,this.map?this.map.painter:null),e.aborted||this._source.fire(new t.k("data",{dataType:"source",tile:e,coord:e.tileID}));}_backfillDEM(e){const t=this.getRenderableIds();for(let r=0;r1||(Math.abs(i)>1&&(1===Math.abs(i+o)?i+=o:1===Math.abs(i-o)&&(i-=o)),t.dem&&e.dem&&(e.dem.backfillBorder(t.dem,i,r),e.neighboringTiles&&e.neighboringTiles[s]&&(e.neighboringTiles[s].backfilled=true)));}}getTile(e){return this.getTileByID(e.key)}getTileByID(e){return this._tiles[e]}_retainLoadedChildren(e,t,i,r){for(const o in this._tiles){let s=this._tiles[o];if(r[o]||!s.hasData()||s.tileID.overscaledZ<=t||s.tileID.overscaledZ>i)continue;let a=s.tileID;for(;s&&s.tileID.overscaledZ>t+1;){const e=s.tileID.scaledTo(s.tileID.overscaledZ-1);s=this._tiles[e.key],s&&s.hasData()&&(a=e);}let n=a;for(;n.overscaledZ>t;)if(n=n.scaledTo(n.overscaledZ-1),e[n.key]||e[n.canonical.key]){r[a.key]=a;break}}}findLoadedParent(e,t){if(e.key in this._loadedParentTiles){const i=this._loadedParentTiles[e.key];return i&&i.tileID.overscaledZ>=t?i:null}for(let i=e.overscaledZ-1;i>=t;i--){const t=e.scaledTo(i),r=this._getLoadedTile(t);if(r)return r}}findLoadedSibling(e){return this._getLoadedTile(e)}_getLoadedTile(e){const t=this._tiles[e.key];return t&&t.hasData()?t:this._cache.getByKey(e.wrapped().key)}updateCacheSize(e){const i=Math.ceil(e.width/this._source.tileSize)+1,r=Math.ceil(e.height/this._source.tileSize)+1,o=Math.floor(i*r*(null===this._maxTileCacheZoomLevels?t.a.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),s="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,o):o;this._cache.setMaxSize(s);}handleWrapJump(e){const t=Math.round((e-(undefined===this._prevLng?e:this._prevLng))/360);if(this._prevLng=e,t){const e={};for(const i in this._tiles){const r=this._tiles[i];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+t),e[r.tileID.key]=r;}this._tiles=e;for(const e in this._timers)clearTimeout(this._timers[e]),delete this._timers[e];for(const e in this._tiles)this._setTileReloadTimer(e,this._tiles[e]);}}_updateCoveredAndRetainedTiles(e,t,i,r,o,s){const n={},l={},c=Object.keys(e),h=a.now();for(const i of c){const r=e[i],o=this._tiles[i];if(!o||0!==o.fadeEndTime&&o.fadeEndTime<=h)continue;const s=this.findLoadedParent(r,t),a=this.findLoadedSibling(r),c=s||a||null;c&&(this._addTile(c.tileID),n[c.tileID.key]=c.tileID),l[i]=r;}this._retainLoadedChildren(l,r,i,e);for(const t in n)e[t]||(this._coveredTiles[t]=true,e[t]=n[t]);if(s){const t={},i={};for(const e of o)this._tiles[e.key].hasData()?t[e.key]=e:i[e.key]=e;for(const r in i){const o=i[r].children(this._source.maxzoom);this._tiles[o[0].key]&&this._tiles[o[1].key]&&this._tiles[o[2].key]&&this._tiles[o[3].key]&&(t[o[0].key]=e[o[0].key]=o[0],t[o[1].key]=e[o[1].key]=o[1],t[o[2].key]=e[o[2].key]=o[2],t[o[3].key]=e[o[3].key]=o[3],delete i[r]);}for(const r in i){const o=i[r],s=this.findLoadedParent(o,this._source.minzoom),a=this.findLoadedSibling(o),n=s||a||null;if(n){t[n.tileID.key]=e[n.tileID.key]=n.tileID;for(const e in t)t[e].isChildOf(n.tileID)&&delete t[e];}}for(const e in this._tiles)t[e]||(this._coveredTiles[e]=true);}}update(e,i){if(!this._sourceLoaded||this._paused)return;let r;this.transform=e,this.terrain=i,this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used||this.usedForTerrain?this._source.tileID?r=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((e=>new t.S(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y))):(r=ue(e,{tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:i,calculateTileZoom:this._source.calculateTileZoom}),this._source.hasTile&&(r=r.filter((e=>this._source.hasTile(e))))):r=[];const o=he(e,this._source),s=Math.max(o-de.maxOverzooming,this._source.minzoom),a=Math.max(o+de.maxUnderzooming,this._source.minzoom);if(this.usedForTerrain){const e={};for(const t of r)if(t.canonical.z>this._source.minzoom){const i=t.scaledTo(t.canonical.z-1);e[i.key]=i;const r=t.scaledTo(Math.max(this._source.minzoom,Math.min(t.canonical.z,5)));e[r.key]=r;}r=r.concat(Object.values(e));}const n=0===r.length&&!this._updated&&this._didEmitContent;this._updated=true,n&&this.fire(new t.k("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));const l=this._updateRetainedTiles(r,o);pe(this._source.type)&&this._updateCoveredAndRetainedTiles(l,s,a,o,r,i);for(const e in l)this._tiles[e].clearFadeHold();const c=t.ac(this._tiles,l);for(const e of c){const t=this._tiles[e];t.hasSymbolBuckets&&!t.holdingForFade()?t.setHoldDuration(this.map._fadeDuration):t.hasSymbolBuckets&&!t.symbolFadeFinished()||this._removeTile(e);}this._updateLoadedParentTileCache(),this._updateLoadedSiblingTileCache();}releaseSymbolFadeTiles(){for(const e in this._tiles)this._tiles[e].holdingForFade()&&this._removeTile(e);}_updateRetainedTiles(e,t){var i;const r={},o={},s=Math.max(t-de.maxOverzooming,this._source.minzoom),a=Math.max(t+de.maxUnderzooming,this._source.minzoom),n={};for(const i of e){const e=this._addTile(i);r[i.key]=i,e.hasData()||tthis._source.maxzoom){const e=a.children(this._source.maxzoom)[0],t=this.getTile(e);if(t&&t.hasData()){r[e.key]=e;continue}}else {const e=a.children(this._source.maxzoom);if(r[e[0].key]&&r[e[1].key]&&r[e[2].key]&&r[e[3].key])continue}let n=e.wasRequested();for(let t=a.overscaledZ-1;t>=s;--t){const s=a.scaledTo(t);if(o[s.key])break;if(o[s.key]=true,e=this.getTile(s),!e&&n&&(e=this._addTile(s)),e){const t=e.hasData();if((t||!(null===(i=this.map)||undefined===i?undefined:i.cancelPendingTileRequestsWhileZooming)||n)&&(r[s.key]=s),n=e.wasRequested(),t)break}}}return r}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const e in this._tiles){const t=[];let i,r=this._tiles[e].tileID;for(;r.overscaledZ>0;){if(r.key in this._loadedParentTiles){i=this._loadedParentTiles[r.key];break}t.push(r.key);const e=r.scaledTo(r.overscaledZ-1);if(i=this._getLoadedTile(e),i)break;r=e;}for(const e of t)this._loadedParentTiles[e]=i;}}_updateLoadedSiblingTileCache(){this._loadedSiblingTiles={};for(const e in this._tiles){const t=this._tiles[e].tileID,i=this._getLoadedTile(t);this._loadedSiblingTiles[t.key]=i;}}_addTile(e){let i=this._tiles[e.key];if(i)return i;i=this._cache.getAndRemove(e),i&&(this._setTileReloadTimer(e.key,i),i.tileID=e,this._state.initializeTileState(i,this.map?this.map.painter:null),this._cacheTimers[e.key]&&(clearTimeout(this._cacheTimers[e.key]),delete this._cacheTimers[e.key],this._setTileReloadTimer(e.key,i)));const r=i;return i||(i=new se(e,this._source.tileSize*e.overscaleFactor()),this._loadTile(i,e.key,i.state)),i.uses++,this._tiles[e.key]=i,r||this._source.fire(new t.k("dataloading",{tile:i,coord:i.tileID,dataType:"source"})),i}_setTileReloadTimer(e,t){e in this._timers&&(clearTimeout(this._timers[e]),delete this._timers[e]);const i=t.getExpiryTimeout();i&&(this._timers[e]=setTimeout((()=>{this._reloadTile(e,"expired"),delete this._timers[e];}),i));}_removeTile(e){const t=this._tiles[e];t&&(t.uses--,delete this._tiles[e],this._timers[e]&&(clearTimeout(this._timers[e]),delete this._timers[e]),t.uses>0||(t.hasData()&&"reloading"!==t.state?this._cache.add(t.tileID,t,t.getExpiryTimeout()):(t.aborted=true,this._abortTile(t),this._unloadTile(t))));}_dataHandler(e){const t=e.sourceDataType;"source"===e.dataType&&"metadata"===t&&(this._sourceLoaded=true),this._sourceLoaded&&!this._paused&&"source"===e.dataType&&"content"===t&&(this.reload(e.sourceDataChanged),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=true);}clearTiles(){this._shouldReloadOnResume=false,this._paused=false;for(const e in this._tiles)this._removeTile(e);this._cache.reset();}tilesIn(e,i,r){const o=[],s=this.transform;if(!s)return o;const a=r?s.getCameraQueryGeometry(e):e,n=e.map((e=>s.screenPointToMercatorCoordinate(e,this.terrain))),l=a.map((e=>s.screenPointToMercatorCoordinate(e,this.terrain))),c=this.getIds();let h=1/0,u=1/0,d=-1/0,_=-1/0;for(const e of l)h=Math.min(h,e.x),u=Math.min(u,e.y),d=Math.max(d,e.x),_=Math.max(_,e.y);for(let e=0;e=0&&f[1].y+m>=0){const e=n.map((e=>a.getTilePoint(e))),t=l.map((e=>a.getTilePoint(e)));o.push({tile:r,tileID:a,queryGeometry:e,cameraQueryGeometry:t,scale:p});}}return o}getVisibleCoordinates(e){const t=this.getRenderableIds(e).map((e=>this._tiles[e].tileID));return this.transform&&this.transform.populateCache(t),t}hasTransition(){if(this._source.hasTransition())return true;if(pe(this._source.type)){const e=a.now();for(const t in this._tiles)if(this._tiles[t].fadeEndTime>=e)return true}return false}setFeatureState(e,t,i){this._state.updateState(e=e||"_geojsonTileLayer",t,i);}removeFeatureState(e,t,i){this._state.removeFeatureState(e=e||"_geojsonTileLayer",t,i);}getFeatureState(e,t){return this._state.getState(e=e||"_geojsonTileLayer",t)}setDependencies(e,t,i){const r=this._tiles[e];r&&r.setDependencies(t,i);}reloadTilesForDependencies(e,t){for(const i in this._tiles)this._tiles[i].hasDependency(e,t)&&this._reloadTile(i,"reloading");this._cache.filter((i=>!i.hasDependency(e,t)));}}function _e(e,t){const i=Math.abs(2*e.wrap)-+(e.wrap<0),r=Math.abs(2*t.wrap)-+(t.wrap<0);return e.overscaledZ-t.overscaledZ||r-i||t.canonical.y-e.canonical.y||t.canonical.x-e.canonical.x}function pe(e){return "raster"===e||"image"===e||"video"===e}de.maxOverzooming=10,de.maxUnderzooming=3;class me{constructor(e,t){this.reset(e,t);}reset(e,t){this.points=e||[],this._distances=[0];for(let e=1;e0?(o-a)/n:0;return this.points[s].mult(1-l).add(this.points[i].mult(l))}}function fe(e,t){let i=true;return "always"===e||"never"!==e&&"never"!==t||(i=false),i}class ge{constructor(e,t,i){const r=this.boxCells=[],o=this.circleCells=[];this.xCellCount=Math.ceil(e/i),this.yCellCount=Math.ceil(t/i);for(let e=0;ethis.width||r<0||t>this.height)return [];const n=[];if(e<=0&&t<=0&&this.width<=i&&this.height<=r){if(o)return [{key:null,x1:e,y1:t,x2:i,y2:r}];for(let e=0;e0}hitTestCircle(e,t,i,r,o){const s=e-i,a=e+i,n=t-i,l=t+i;if(a<0||s>this.width||l<0||n>this.height)return false;const c=[];return this._forEachCell(s,n,a,l,this._queryCellCircle,c,{hitTest:true,overlapMode:r,circle:{x:e,y:t,radius:i},seenUids:{box:{},circle:{}}},o),c.length>0}_queryCell(e,t,i,r,o,s,a,n){const{seenUids:l,hitTest:c,overlapMode:h}=a,u=this.boxCells[o];if(null!==u){const o=this.bboxes;for(const a of u)if(!l.box[a]){l.box[a]=true;const u=4*a,d=this.boxKeys[a];if(e<=o[u+2]&&t<=o[u+3]&&i>=o[u+0]&&r>=o[u+1]&&(!n||n(d))&&(!c||!fe(h,d.overlapMode))&&(s.push({key:d,x1:o[u],y1:o[u+1],x2:o[u+2],y2:o[u+3]}),c))return true}}const d=this.circleCells[o];if(null!==d){const o=this.circles;for(const a of d)if(!l.circle[a]){l.circle[a]=true;const u=3*a,d=this.circleKeys[a];if(this._circleAndRectCollide(o[u],o[u+1],o[u+2],e,t,i,r)&&(!n||n(d))&&(!c||!fe(h,d.overlapMode))){const e=o[u],t=o[u+1],i=o[u+2];if(s.push({key:d,x1:e-i,y1:t-i,x2:e+i,y2:t+i}),c)return true}}}return false}_queryCellCircle(e,t,i,r,o,s,a,n){const{circle:l,seenUids:c,overlapMode:h}=a,u=this.boxCells[o];if(null!==u){const e=this.bboxes;for(const t of u)if(!c.box[t]){c.box[t]=true;const i=4*t,r=this.boxKeys[t];if(this._circleAndRectCollide(l.x,l.y,l.radius,e[i+0],e[i+1],e[i+2],e[i+3])&&(!n||n(r))&&!fe(h,r.overlapMode))return s.push(true),true}}const d=this.circleCells[o];if(null!==d){const e=this.circles;for(const t of d)if(!c.circle[t]){c.circle[t]=true;const i=3*t,r=this.circleKeys[t];if(this._circlesCollide(e[i],e[i+1],e[i+2],l.x,l.y,l.radius)&&(!n||n(r))&&!fe(h,r.overlapMode))return s.push(true),true}}}_forEachCell(e,t,i,r,o,s,a,n){const l=this._convertToXCellCoord(e),c=this._convertToYCellCoord(t),h=this._convertToXCellCoord(i),u=this._convertToYCellCoord(r);for(let d=l;d<=h;d++)for(let l=c;l<=u;l++)if(o.call(this,e,t,i,r,this.xCellCount*l+d,s,a,n))return}_convertToXCellCoord(e){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(e*this.xScale)))}_convertToYCellCoord(e){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(e*this.yScale)))}_circlesCollide(e,t,i,r,o,s){const a=r-e,n=o-t,l=i+s;return l*l>a*a+n*n}_circleAndRectCollide(e,t,i,r,o,s,a){const n=(s-r)/2,l=Math.abs(e-(r+n));if(l>n+i)return false;const c=(a-o)/2,h=Math.abs(t-(o+c));if(h>c+i)return false;if(l<=n||h<=c)return true;const u=l-n,d=h-c;return u*u+d*d<=i*i}}function ve(e,i,o){const s=t.H();if(!e){const{vecSouth:e,vecEast:t}=be(i),o=r();o[0]=t[0],o[1]=t[1],o[2]=e[0],o[3]=e[1],a=o,(d=(l=(n=o)[0])*(u=n[3])-(h=n[2])*(c=n[1]))&&(a[0]=u*(d=1/d),a[1]=-c*d,a[2]=-h*d,a[3]=l*d),s[0]=o[0],s[1]=o[1],s[4]=o[2],s[5]=o[3];}var a,n,l,c,h,u,d;return t.K(s,s,[1/o,1/o,1]),s}function xe(e,i,r,o){if(e){const e=t.H();if(!i){const{vecSouth:t,vecEast:i}=be(r);e[0]=i[0],e[1]=i[1],e[4]=t[0],e[5]=t[1];}return t.K(e,e,[o,o,1]),e}return r.pixelsToClipSpaceMatrix}function be(e){const i=Math.cos(e.rollInRadians),r=Math.sin(e.rollInRadians),o=Math.cos(e.pitchInRadians),s=Math.cos(e.bearingInRadians),a=Math.sin(e.bearingInRadians),n=t.ad();n[0]=-s*o*r-a*i,n[1]=-a*o*r+s*i;const l=t.ae(n);l<1e-9?t.af(n):t.ag(n,n,1/l);const c=t.ad();c[0]=s*o*i-a*r,c[1]=a*o*i+s*r;const h=t.ae(c);return h<1e-9?t.af(c):t.ag(c,c,1/h),{vecEast:c,vecSouth:n}}function ye(e,i,r,o){let s;o?(s=[e,i,o(e,i),1],t.al(s,s,r)):(s=[e,i,0,1],je(s,s,r));const a=s[3];return {point:new t.P(s[0]/a,s[1]/a),signedDistanceFromCamera:a,isOccluded:false}}function we(e,t){return .5+e/t*.5}function Te(e,t){return e.x>=-t[0]&&e.x<=t[0]&&e.y>=-t[1]&&e.y<=t[1]}function Pe(e,i,r,o,s,a,n,l,c,h,u,d,_){const p=r?e.textSizeData:e.iconSizeData,m=t.ah(p,i.transform.zoom),f=[256/i.width*2+1,256/i.height*2+1],g=r?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;g.clear();const v=e.lineVertexArray,x=r?e.text.placedSymbolArray:e.icon.placedSymbolArray,b=i.transform.width/i.transform.height;let y=false;for(let r=0;rMath.abs(r.x-i.x)*o?{useVertical:true}:(e===t.ai.vertical?i.yr.x)?{needsFlipping:true}:null}function Ee(e){const{projectionContext:i,pitchedLabelPlaneMatrixInverse:r,symbol:o,fontSize:s,flip:a,keepUpright:n,glyphOffsetArray:l,dynamicLayoutVertexArray:c,aspectRatio:h,rotateToLine:u}=e,d=s/24,_=o.lineOffsetX*d,p=o.lineOffsetY*d;let m;if(o.numGlyphs>1){const e=o.glyphStartIndex+o.numGlyphs,t=o.lineStartIndex,s=o.lineStartIndex+o.lineLength,c=Ce(d,l,_,p,a,o,u,i);if(!c)return {notEnoughRoom:true};const f=De(c.first.point.x,c.first.point.y,i,r),g=De(c.last.point.x,c.last.point.y,i,r);if(n&&!a){const e=Ie(o.writingMode,f,g,h);if(e)return e}m=[c.first];for(let r=o.glyphStartIndex+1;r0?n.point:Me(i.tileAnchorPoint,a,e,1,i),c=De(e.x,e.y,i,r),u=De(l.x,l.y,i,r),d=Ie(o.writingMode,c,u,h);if(d)return d}const e=ke(d*l.getoffsetX(o.glyphStartIndex),_,p,a,o.segment,o.lineStartIndex,o.lineStartIndex+o.lineLength,i,u);if(!e||i.projectionCache.anyProjectionOccluded)return {notEnoughRoom:true};m=[e];}for(const e of m)t.ak(c,e.point,e.angle);return {}}function Me(e,t,i,r,o){const s=e.add(e.sub(t)._unit()),a=Re(s.x,s.y,o).point,n=i.sub(a);return i.add(n._mult(r/n.mag()))}function Se(e,i,r){const o=i.projectionCache;if(o.projections[e])return o.projections[e];const s=new t.P(i.lineVertexArray.getx(e),i.lineVertexArray.gety(e)),a=Re(s.x,s.y,i);if(a.signedDistanceFromCamera>0)return o.projections[e]=a.point,o.anyProjectionOccluded=o.anyProjectionOccluded||a.isOccluded,a.point;const n=e-r.direction;return Me(0===r.distanceFromAnchor?i.tileAnchorPoint:new t.P(i.lineVertexArray.getx(n),i.lineVertexArray.gety(n)),s,r.previousVertex,r.absOffsetX-r.distanceFromAnchor+1,i)}function Re(e,t,i){const r=e+i.translation[0],o=t+i.translation[1];let s;return i.pitchWithMap?(s=ye(r,o,i.pitchedLabelPlaneMatrix,i.getElevation),s.isOccluded=false):(s=i.transform.projectTileCoordinates(r,o,i.unwrappedTileID,i.getElevation),s.point.x=(.5*s.point.x+.5)*i.width,s.point.y=(.5*-s.point.y+.5)*i.height),s}function De(e,i,r,o){if(r.pitchWithMap){const s=[e,i,0,1];return t.al(s,s,o),r.transform.projectTileCoordinates(s[0]/s[3],s[1]/s[3],r.unwrappedTileID,r.getElevation).point}return {x:e/r.width*2-1,y:i/r.height*2-1}}function ze(e,t,i){return i.transform.projectTileCoordinates(e,t,i.unwrappedTileID,i.getElevation)}function Ae(e,t,i){return e._unit()._perp()._mult(t*i)}function Le(e,i,r,o,s,a,n,l,c){if(l.projectionCache.offsets[e])return l.projectionCache.offsets[e];const h=r.add(i);if(e+c.direction=s)return l.projectionCache.offsets[e]=h,h;const u=Se(e+c.direction,l,c),d=Ae(u.sub(r),n,c.direction),_=r.add(d),p=u.add(d);return l.projectionCache.offsets[e]=t.am(a,h,_,p)||h,l.projectionCache.offsets[e]}function ke(e,t,i,r,o,s,a,n,l){const c=r?e-t:e+t;let h=c>0?1:-1,u=0;r&&(h*=-1,u=Math.PI),h<0&&(u+=Math.PI);let d,_=h>0?s+o:s+o+1;n.projectionCache.cachedAnchorPoint?d=n.projectionCache.cachedAnchorPoint:(d=Re(n.tileAnchorPoint.x,n.tileAnchorPoint.y,n).point,n.projectionCache.cachedAnchorPoint=d);let p,m,f=d,g=d,v=0,x=0;const b=Math.abs(c),y=[];let w;for(;v+x<=b;){if(_+=h,_=a)return null;v+=x,g=f,m=p;const e={absOffsetX:b,direction:h,distanceFromAnchor:v,previousVertex:g};if(f=Se(_,n,e),0===i)y.push(g),w=f.sub(g);else {let t;const r=f.sub(g);t=0===r.mag()?Ae(Se(_+h,n,e).sub(f),i,h):Ae(r,i,h),m||(m=g.add(t)),p=Le(_,t,f,s,a,m,i,n,e),y.push(m),w=p.sub(m);}x=w.mag();}const T=w._mult((b-v)/x)._add(m||g),P=u+Math.atan2(f.y-g.y,f.x-g.x);return y.push(T),{point:T,angle:l?P:0,path:y}}const Fe=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function Be(e,t){for(let i=0;i=1;e--)_.push(a.path[e]);for(let e=1;ee.signedDistanceFromCamera<=0))?[]:e.map((e=>e.point));}let f=[];if(_.length>0){const e=_[0].clone(),i=_[0].clone();for(let t=1;t<_.length;t++)e.x=Math.min(e.x,_[t].x),e.y=Math.min(e.y,_[t].y),i.x=Math.max(i.x,_[t].x),i.y=Math.max(i.y,_[t].y);f=e.x>=r.x&&i.x<=o.x&&e.y>=r.y&&i.y<=o.y?[_]:i.xo.x||i.yo.y?[]:t.ao([_],r.x,r.y,o.x,o.y);}for(const t of f){s.reset(t,.25*i);let r=0;r=s.length<=.5*i?1:Math.ceil(s.paddedLength/p)+1;for(let t=0;t{const t=ye(e.x,e.y,r,i.getElevation),o=i.transform.projectTileCoordinates(t.point.x,t.point.y,i.unwrappedTileID,i.getElevation);return o.point.x=(.5*o.point.x+.5)*i.width,o.point.y=(.5*-o.point.y+.5)*i.height,o}))}(e,i);return function(e){let t=0,i=0,r=0,o=0;for(let s=0;si&&(i=o,t=r));return e.slice(t,t+i)}(r)}queryRenderedSymbols(e){if(0===e.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return {};const i=[];let r=1/0,o=1/0,s=-1/0,a=-1/0;for(const n of e){const e=new t.P(n.x+Oe,n.y+Oe);r=Math.min(r,e.x),o=Math.min(o,e.y),s=Math.max(s,e.x),a=Math.max(a,e.y),i.push(e);}const n=this.grid.query(r,o,s,a).concat(this.ignoredGrid.query(r,o,s,a)),l={},c={};for(const e of n){const r=e.key;if(undefined===l[r.bucketInstanceId]&&(l[r.bucketInstanceId]={}),l[r.bucketInstanceId][r.featureIndex])continue;const o=[new t.P(e.x1,e.y1),new t.P(e.x2,e.y1),new t.P(e.x2,e.y2),new t.P(e.x1,e.y2)];t.ap(i,o)&&(l[r.bucketInstanceId][r.featureIndex]=true,undefined===c[r.bucketInstanceId]&&(c[r.bucketInstanceId]=[]),c[r.bucketInstanceId].push(r.featureIndex));}return c}insertCollisionBox(e,t,i,r,o,s){(i?this.ignoredGrid:this.grid).insert({bucketInstanceId:r,featureIndex:o,collisionGroupID:s,overlapMode:t},e[0],e[1],e[2],e[3]);}insertCollisionCircles(e,t,i,r,o,s){const a=i?this.ignoredGrid:this.grid,n={bucketInstanceId:r,featureIndex:o,collisionGroupID:s,overlapMode:t};for(let t=0;t=this.screenRightBoundary||rthis.screenBottomBoundary}isInsideGrid(e,t,i,r){return i>=0&&e=0&&tthis.projectAndGetPerspectiveRatio(e.x,e.y,o,c,u)));S=e.some((e=>!e.isOccluded)),M=e.map((e=>new t.P(e.x,e.y)));}else S=true;return {box:t.ar(M),allPointsOccluded:!S}}}class Ze{constructor(e,t,i,r){this.opacity=e?Math.max(0,Math.min(1,e.opacity+(e.placed?t:-t))):r&&i?1:0,this.placed=i;}isHidden(){return 0===this.opacity&&!this.placed}}class Ge{constructor(e,t,i,r,o){this.text=new Ze(e?e.text:null,t,i,o),this.icon=new Ze(e?e.icon:null,t,r,o);}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class Ue{constructor(e,t,i){this.text=e,this.icon=t,this.skipFade=i;}}class Ve{constructor(e,t,i,r,o){this.bucketInstanceId=e,this.featureIndex=t,this.sourceLayerIndex=i,this.bucketIndex=r,this.tileID=o;}}class qe{constructor(e){this.crossSourceCollisions=e,this.maxGroupID=0,this.collisionGroups={};}get(e){if(this.crossSourceCollisions)return {ID:0,predicate:null};if(!this.collisionGroups[e]){const t=++this.maxGroupID;this.collisionGroups[e]={ID:t,predicate:e=>e.collisionGroupID===t};}return this.collisionGroups[e]}}function He(e,i,r,o,s){const{horizontalAlign:a,verticalAlign:n}=t.ay(e);return new t.P(-(a-.5)*i+o[0]*s,-(n-.5)*r+o[1]*s)}class We{constructor(e,t,i,r,o){this.transform=e.clone(),this.terrain=t,this.collisionIndex=new Ne(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=false,this.commitTime=0,this.fadeDuration=i,this.retainedQueryData={},this.collisionGroups=new qe(r),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=o,o&&(o.prevPlacement=undefined),this.placedOrientations={};}_getTerrainElevationFunc(e){const t=this.terrain;return t?(i,r)=>t.getElevation(e,i,r):null}getBucketParts(e,i,r,o){const s=r.getBucket(i),a=r.latestFeatureIndex;if(!s||!a||i.id!==s.layerIds[0])return;const n=r.collisionBoxArray,l=s.layers[0].layout,c=s.layers[0].paint,h=Math.pow(2,this.transform.zoom-r.tileID.overscaledZ),u=r.tileSize/t.X,d=r.tileID.toUnwrapped(),_="map"===l.get("text-rotation-alignment"),p=t.at(r,1,this.transform.zoom),m=t.au(this.collisionIndex.transform,r,c.get("text-translate"),c.get("text-translate-anchor")),f=t.au(this.collisionIndex.transform,r,c.get("icon-translate"),c.get("icon-translate-anchor")),g=ve(_,this.transform,p);this.retainedQueryData[s.bucketInstanceId]=new Ve(s.bucketInstanceId,a,s.sourceLayerIndex,s.index,r.tileID);const v={bucket:s,layout:l,translationText:m,translationIcon:f,unwrappedTileID:d,pitchedLabelPlaneMatrix:g,scale:h,textPixelRatio:u,holdingForFade:r.holdingForFade(),collisionBoxArray:n,partiallyEvaluatedTextSize:t.ah(s.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get(s.sourceID)};if(o)for(const t of s.sortKeyRanges){const{sortKey:i,symbolInstanceStart:r,symbolInstanceEnd:o}=t;e.push({sortKey:i,symbolInstanceStart:r,symbolInstanceEnd:o,parameters:v});}else e.push({symbolInstanceStart:0,symbolInstanceEnd:s.symbolInstances.length,parameters:v});}attemptAnchorPlacement(e,i,r,o,s,a,n,l,c,h,u,d,_,p,m,f,g,v,x,b){const y=t.av[e.textAnchor],w=[e.textOffset0,e.textOffset1],T=He(y,r,o,w,s),P=this.collisionIndex.placeCollisionBox(i,d,l,c,h,n,a,f,u.predicate,x,T,b);if((!v||this.collisionIndex.placeCollisionBox(v,d,l,c,h,n,a,g,u.predicate,x,T,b).placeable)&&P.placeable){let e;if(this.prevPlacement&&this.prevPlacement.variableOffsets[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID]&&this.prevPlacement.placements[_.crossTileID].text&&(e=this.prevPlacement.variableOffsets[_.crossTileID].anchor),0===_.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[_.crossTileID]={textOffset:w,width:r,height:o,anchor:y,textBoxScale:s,prevAnchor:e},this.markUsedJustification(p,y,_,m),p.allowVerticalPlacement&&(this.markUsedOrientation(p,m,_),this.placedOrientations[_.crossTileID]=m),{shift:T,placedGlyphBoxes:P}}}placeLayerBucketPart(e,i,r){const{bucket:o,layout:s,translationText:a,translationIcon:n,unwrappedTileID:l,pitchedLabelPlaneMatrix:c,textPixelRatio:h,holdingForFade:u,collisionBoxArray:d,partiallyEvaluatedTextSize:_,collisionGroup:p}=e.parameters,m=s.get("text-optional"),f=s.get("icon-optional"),g=t.aw(s,"text-overlap","text-allow-overlap"),v="always"===g,x=t.aw(s,"icon-overlap","icon-allow-overlap"),b="always"===x,y="map"===s.get("text-rotation-alignment"),w="map"===s.get("text-pitch-alignment"),T="none"!==s.get("icon-text-fit"),P="viewport-y"===s.get("symbol-z-order"),C=v&&(b||!o.hasIconData()||f),I=b&&(v||!o.hasTextData()||m);!o.collisionArrays&&d&&o.deserializeCollisionBoxes(d);const E=this.retainedQueryData[o.bucketInstanceId].tileID,M=this._getTerrainElevationFunc(E),S=this.transform.getFastPathSimpleProjectionMatrix(E),R=(e,d,b)=>{var P,R;if(i[e.crossTileID])return;if(u)return void(this.placements[e.crossTileID]=new Ue(false,false,false));let D=false,z=false,A=true,L=null,k={box:null,placeable:false,offscreen:null,occluded:false},F={box:null,placeable:false,offscreen:null},B=null,j=null,O=null,N=0,Z=0,G=0;d.textFeatureIndex?N=d.textFeatureIndex:e.useRuntimeCollisionCircles&&(N=e.featureIndex),d.verticalTextFeatureIndex&&(Z=d.verticalTextFeatureIndex);const U=d.textBox;if(U){const i=i=>{let r=t.ai.horizontal;if(o.allowVerticalPlacement&&!i&&this.prevPlacement){const t=this.prevPlacement.placedOrientations[e.crossTileID];t&&(this.placedOrientations[e.crossTileID]=t,r=t,this.markUsedOrientation(o,r,e));}return r},s=(i,r)=>{if(o.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&d.verticalTextBox){for(const e of o.writingModes)if(e===t.ai.vertical?(k=r(),F=k):k=i(),k&&k.placeable)break}else k=i();},c=e.textAnchorOffsetStartIndex,u=e.textAnchorOffsetEndIndex;if(u===c){const r=(t,i)=>{const r=this.collisionIndex.placeCollisionBox(t,g,h,E,l,w,y,a,p.predicate,M,undefined,S);return r&&r.placeable&&(this.markUsedOrientation(o,i,e),this.placedOrientations[e.crossTileID]=i),r};s((()=>r(U,t.ai.horizontal)),(()=>{const i=d.verticalTextBox;return o.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&i?r(i,t.ai.vertical):{box:null,offscreen:null}})),i(k&&k.placeable);}else {let _=t.av[null===(R=null===(P=this.prevPlacement)||undefined===P?undefined:P.variableOffsets[e.crossTileID])||undefined===R?undefined:R.anchor];const m=(t,i,s)=>{const d=t.x2-t.x1,m=t.y2-t.y1,f=e.textBoxScale,v=T&&"never"===x?i:null;let b=null,P="never"===g?1:2,C="never";_&&P++;for(let i=0;im(U,d.iconBox,t.ai.horizontal)),(()=>{const i=d.verticalTextBox;return o.allowVerticalPlacement&&(!k||!k.placeable)&&e.numVerticalGlyphVertices>0&&i?m(i,d.verticalIconBox,t.ai.vertical):{box:null,occluded:true,offscreen:null}})),k&&(D=k.placeable,A=k.offscreen);const f=i(k&&k.placeable);if(!D&&this.prevPlacement){const t=this.prevPlacement.variableOffsets[e.crossTileID];t&&(this.variableOffsets[e.crossTileID]=t,this.markUsedJustification(o,t.anchor,e,f));}}}if(B=k,D=B&&B.placeable,A=B&&B.offscreen,e.useRuntimeCollisionCircles){const i=o.text.placedSymbolArray.get(e.centerJustifiedTextSymbolIndex),n=t.aj(o.textSizeData,_,i),h=s.get("text-padding");j=this.collisionIndex.placeCollisionCircles(g,i,o.lineVertexArray,o.glyphOffsetArray,n,l,c,r,w,p.predicate,e.collisionCircleDiameter,h,a,M),j.circles.length&&j.collisionDetected&&!r&&t.w("Collisions detected, but collision boxes are not shown"),D=v||j.circles.length>0&&!j.collisionDetected,A=A&&j.offscreen;}if(d.iconFeatureIndex&&(G=d.iconFeatureIndex),d.iconBox){const e=e=>this.collisionIndex.placeCollisionBox(e,x,h,E,l,w,y,n,p.predicate,M,T&&L?L:undefined,S);F&&F.placeable&&d.verticalIconBox?(O=e(d.verticalIconBox),z=O.placeable):(O=e(d.iconBox),z=O.placeable),A=A&&O.offscreen;}const V=m||0===e.numHorizontalGlyphVertices&&0===e.numVerticalGlyphVertices,q=f||0===e.numIconVertices;V||q?q?V||(z=z&&D):D=z&&D:z=D=z&&D;const H=z&&O.placeable;if(D&&B.placeable&&this.collisionIndex.insertCollisionBox(B.box,g,s.get("text-ignore-placement"),o.bucketInstanceId,F&&F.placeable&&Z?Z:N,p.ID),H&&this.collisionIndex.insertCollisionBox(O.box,x,s.get("icon-ignore-placement"),o.bucketInstanceId,G,p.ID),j&&D&&this.collisionIndex.insertCollisionCircles(j.circles,g,s.get("text-ignore-placement"),o.bucketInstanceId,N,p.ID),r&&this.storeCollisionData(o.bucketInstanceId,b,d,B,O,j),0===e.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");if(0===o.bucketInstanceId)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[e.crossTileID]=new Ue((D||C)&&!(null==B?undefined:B.occluded),(z||I)&&!(null==O?undefined:O.occluded),A||o.justReloaded),i[e.crossTileID]=true;};if(P){if(0!==e.symbolInstanceStart)throw new Error("bucket.bucketInstanceId should be 0");const t=o.getSortedSymbolIndexes(-this.transform.bearingInRadians);for(let e=t.length-1;e>=0;--e){const i=t[e];R(o.symbolInstances.get(i),o.collisionArrays[i],i);}}else for(let t=e.symbolInstanceStart;t=0&&(e.text.placedSymbolArray.get(t).crossTileID=s>=0&&t!==s?0:r.crossTileID);}markUsedOrientation(e,i,r){const o=i===t.ai.horizontal||i===t.ai.horizontalOnly?i:0,s=i===t.ai.vertical?i:0,a=[r.leftJustifiedTextSymbolIndex,r.centerJustifiedTextSymbolIndex,r.rightJustifiedTextSymbolIndex];for(const t of a)e.text.placedSymbolArray.get(t).placedOrientation=o;r.verticalPlacedTextSymbolIndex&&(e.text.placedSymbolArray.get(r.verticalPlacedTextSymbolIndex).placedOrientation=s);}commit(e){this.commitTime=e,this.zoomAtLastRecencyCheck=this.transform.zoom;const t=this.prevPlacement;let i=false;this.prevZoomAdjustment=t?t.zoomAdjustment(this.transform.zoom):0;const r=t?t.symbolFadeChange(e):1,o=t?t.opacities:{},s=t?t.variableOffsets:{},a=t?t.placedOrientations:{};for(const e in this.placements){const t=this.placements[e],s=o[e];s?(this.opacities[e]=new Ge(s,r,t.text,t.icon),i=i||t.text!==s.text.placed||t.icon!==s.icon.placed):(this.opacities[e]=new Ge(null,r,t.text,t.icon,t.skipFade),i=i||t.text||t.icon);}for(const e in o){const t=o[e];if(!this.opacities[e]){const o=new Ge(t,r,false,false);o.isHidden()||(this.opacities[e]=o,i=i||t.text.placed||t.icon.placed);}}for(const e in s)this.variableOffsets[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.variableOffsets[e]=s[e]);for(const e in a)this.placedOrientations[e]||!this.opacities[e]||this.opacities[e].isHidden()||(this.placedOrientations[e]=a[e]);if(t&&undefined===t.lastPlacementChangeTime)throw new Error("Last placement time for previous placement is not defined");i?this.lastPlacementChangeTime=e:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=t?t.lastPlacementChangeTime:e);}updateLayerOpacities(e,t){const i={};for(const r of t){const t=r.getBucket(e);t&&r.latestFeatureIndex&&e.id===t.layerIds[0]&&this.updateBucketOpacities(t,r.tileID,i,r.collisionBoxArray);}}updateBucketOpacities(e,i,r,o){e.hasTextData()&&(e.text.opacityVertexArray.clear(),e.text.hasVisibleVertices=false),e.hasIconData()&&(e.icon.opacityVertexArray.clear(),e.icon.hasVisibleVertices=false),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexArray.clear(),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexArray.clear();const s=e.layers[0],a=s.layout,n=new Ge(null,0,false,false,true),l=a.get("text-allow-overlap"),c=a.get("icon-allow-overlap"),h=s._unevaluatedLayout.hasValue("text-variable-anchor")||s._unevaluatedLayout.hasValue("text-variable-anchor-offset"),u="map"===a.get("text-rotation-alignment"),d="map"===a.get("text-pitch-alignment"),_="none"!==a.get("icon-text-fit"),p=new Ge(null,0,l&&(c||!e.hasIconData()||a.get("icon-optional")),c&&(l||!e.hasTextData()||a.get("text-optional")),true);!e.collisionArrays&&o&&(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData())&&e.deserializeCollisionBoxes(o);const m=(e,t,i)=>{for(let r=0;r0,v=this.placedOrientations[o.crossTileID],x=v===t.ai.vertical,b=v===t.ai.horizontal||v===t.ai.horizontalOnly;if(s>0||a>0){const t=it(c.text);m(e.text,s,x?rt:t),m(e.text,a,b?rt:t);const i=c.text.isHidden();[o.rightJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.leftJustifiedTextSymbolIndex].forEach((t=>{t>=0&&(e.text.placedSymbolArray.get(t).hidden=i||x?1:0);})),o.verticalPlacedTextSymbolIndex>=0&&(e.text.placedSymbolArray.get(o.verticalPlacedTextSymbolIndex).hidden=i||b?1:0);const r=this.variableOffsets[o.crossTileID];r&&this.markUsedJustification(e,r.anchor,o,v);const n=this.placedOrientations[o.crossTileID];n&&(this.markUsedJustification(e,"left",o,n),this.markUsedOrientation(e,n,o));}if(g){const t=it(c.icon),i=!(_&&o.verticalPlacedIconSymbolIndex&&x);o.placedIconSymbolIndex>=0&&(m(e.icon,o.numIconVertices,i?t:rt),e.icon.placedSymbolArray.get(o.placedIconSymbolIndex).hidden=c.icon.isHidden()),o.verticalPlacedIconSymbolIndex>=0&&(m(e.icon,o.numVerticalIconVertices,i?rt:t),e.icon.placedSymbolArray.get(o.verticalPlacedIconSymbolIndex).hidden=c.icon.isHidden());}const y=f&&f.has(i)?f.get(i):{text:null,icon:null};if(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()){const r=e.collisionArrays[i];if(r){let i=new t.P(0,0);if(r.textBox||r.verticalTextBox){let t=true;if(h){const e=this.variableOffsets[l];e?(i=He(e.anchor,e.width,e.height,e.textOffset,e.textBoxScale),u&&i._rotate(d?-this.transform.bearingInRadians:this.transform.bearingInRadians)):t=false;}if(r.textBox||r.verticalTextBox){let o;r.textBox&&(o=x),r.verticalTextBox&&(o=b),Xe(e.textCollisionBox.collisionVertexArray,c.text.placed,!t||o,y.text,i.x,i.y);}}if(r.iconBox||r.verticalIconBox){const t=Boolean(!b&&r.verticalIconBox);let o;r.iconBox&&(o=t),r.verticalIconBox&&(o=!t),Xe(e.iconCollisionBox.collisionVertexArray,c.icon.placed,o,y.icon,_?i.x:0,_?i.y:0);}}}}if(e.sortFeatures(-this.transform.bearingInRadians),this.retainedQueryData[e.bucketInstanceId]&&(this.retainedQueryData[e.bucketInstanceId].featureSortOrder=e.featureSortOrder),e.hasTextData()&&e.text.opacityVertexBuffer&&e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray),e.hasIconData()&&e.icon.opacityVertexBuffer&&e.icon.opacityVertexBuffer.updateData(e.icon.opacityVertexArray),e.hasIconCollisionBoxData()&&e.iconCollisionBox.collisionVertexBuffer&&e.iconCollisionBox.collisionVertexBuffer.updateData(e.iconCollisionBox.collisionVertexArray),e.hasTextCollisionBoxData()&&e.textCollisionBox.collisionVertexBuffer&&e.textCollisionBox.collisionVertexBuffer.updateData(e.textCollisionBox.collisionVertexArray),e.text.opacityVertexArray.length!==e.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${e.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${e.text.layoutVertexArray.length}) / 4`);if(e.icon.opacityVertexArray.length!==e.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${e.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${e.icon.layoutVertexArray.length}) / 4`);e.bucketInstanceId in this.collisionCircleArrays&&(e.collisionCircleArray=this.collisionCircleArrays[e.bucketInstanceId],delete this.collisionCircleArrays[e.bucketInstanceId]);}symbolFadeChange(e){return 0===this.fadeDuration?1:(e-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(e){return Math.max(0,(this.transform.zoom-e)/1.5)}hasTransitions(e){return this.stale||e-this.lastPlacementChangeTimee}setStale(){this.stale=true;}}function Xe(e,t,i,r,o,s){r&&0!==r.length||(r=[0,0,0,0]);const a=r[0]-Oe,n=r[1]-Oe,l=r[2]-Oe,c=r[3]-Oe;e.emplaceBack(t?1:0,i?1:0,o||0,s||0,a,n),e.emplaceBack(t?1:0,i?1:0,o||0,s||0,l,n),e.emplaceBack(t?1:0,i?1:0,o||0,s||0,l,c),e.emplaceBack(t?1:0,i?1:0,o||0,s||0,a,c);}const $e=Math.pow(2,25),Ke=Math.pow(2,24),Ye=Math.pow(2,17),Je=Math.pow(2,16),Qe=Math.pow(2,9),et=Math.pow(2,8),tt=Math.pow(2,1);function it(e){if(0===e.opacity&&!e.placed)return 0;if(1===e.opacity&&e.placed)return 4294967295;const t=e.placed?1:0,i=Math.floor(127*e.opacity);return i*$e+t*Ke+i*Ye+t*Je+i*Qe+t*et+i*tt+t}const rt=0;class ot{constructor(e){this._sortAcrossTiles="viewport-y"!==e.layout.get("symbol-z-order")&&!e.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];}continuePlacement(e,t,i,r,o){const s=this._bucketParts;for(;this._currentTileIndexe.sortKey-t.sortKey)));this._currentPartIndex!this._forceFullPlacement&&a.now()-r>2;for(;this._currentPlacementIndex>=0;){const r=t[e[this._currentPlacementIndex]],s=this.placement.collisionIndex.transform.zoom;if("symbol"===r.type&&(!r.minzoom||r.minzoom<=s)&&(!r.maxzoom||r.maxzoom>s)){if(this._inProgressLayer||(this._inProgressLayer=new ot(r)),this._inProgressLayer.continuePlacement(i[r.source],this.placement,this._showCollisionBoxes,r,o))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=true;}commit(e){return this.placement.commit(e),this.placement}}const at=512/t.X/2;class nt{constructor(e,i,r){this.tileID=e,this.bucketInstanceId=r,this._symbolsByKey={};const o=new Map;for(let e=0;e({x:Math.floor(e.anchorX*at),y:Math.floor(e.anchorY*at)}))),crossTileIDs:i.map((e=>e.crossTileID))};if(r.positions.length>128){const e=new t.az(r.positions.length,16,Uint16Array);for(const{x:t,y:i}of r.positions)e.add(t,i);e.finish(),delete r.positions,r.index=e;}this._symbolsByKey[e]=r;}}getScaledCoordinates(e,i){const{x:r,y:o,z:s}=this.tileID.canonical,{x:a,y:n,z:l}=i.canonical,c=at/Math.pow(2,l-s),h=(n*t.X+e.anchorY)*c,u=o*t.X*at;return {x:Math.floor((a*t.X+e.anchorX)*c-r*t.X*at),y:Math.floor(h-u)}}findMatches(e,t,i){const r=this.tileID.canonical.ze))}}class lt{constructor(){this.maxCrossTileID=0;}generate(){return ++this.maxCrossTileID}}class ct{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0;}handleWrapJump(e){const t=Math.round((e-this.lng)/360);if(0!==t)for(const e in this.indexes){const i=this.indexes[e],r={};for(const e in i){const o=i[e];o.tileID=o.tileID.unwrapTo(o.tileID.wrap+t),r[o.tileID.key]=o;}this.indexes[e]=r;}this.lng=e;}addBucket(e,t,i){if(this.indexes[e.overscaledZ]&&this.indexes[e.overscaledZ][e.key]){if(this.indexes[e.overscaledZ][e.key].bucketInstanceId===t.bucketInstanceId)return false;this.removeBucketCrossTileIDs(e.overscaledZ,this.indexes[e.overscaledZ][e.key]);}for(let e=0;ee.overscaledZ)for(const i in o){const s=o[i];s.tileID.isChildOf(e)&&s.findMatches(t.symbolInstances,e,r);}else {const s=o[e.scaledTo(Number(i)).key];s&&s.findMatches(t.symbolInstances,e,r);}}for(let e=0;e{t[e]=true;}));for(const e in this.layerIndexes)t[e]||delete this.layerIndexes[e];}}var ut="void main() {fragColor=vec4(1.0);}";const dt={prelude:_t("#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nout highp vec4 fragColor;","#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}mat3 rotationMatrixFromAxisAngle(vec3 u,float angle) {float c=cos(angle);float s=sin(angle);float c2=1.0-c;return mat3(u.x*u.x*c2+ c,u.x*u.y*c2-u.z*s,u.x*u.z*c2+u.y*s,u.y*u.x*c2+u.z*s,u.y*u.y*c2+ c,u.y*u.z*c2-u.x*s,u.z*u.x*c2-u.y*s,u.z*u.y*c2+u.x*s,u.z*u.z*c2+ c\n);}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\n#ifdef GLOBE\nif ((pos.y <-32767.5) || (pos.y > 32766.5)) {return 0.0;}\n#endif\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}const float PI=3.141592653589793;uniform mat4 u_projection_matrix;"),projectionMercator:_t("","float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}"),projectionGlobe:_t("","#define GLOBE_RADIUS 6371008.8\nuniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos\n);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float spherical_y=2.0*atan(exp(PI-(mercator_pos_y*PI*2.0)))-PI*0.5;return cos(spherical_y);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY); \nif (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 translatedPos,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*translatedPos;vec2 spherical;spherical.x=mercator_pos.x*PI*2.0+PI;spherical.y=2.0*atan(exp(PI-(mercator_pos.y*PI*2.0)))-PI*0.5;float len=cos(spherical.y);vec3 pos=vec3(sin(spherical.x)*len,sin(spherical.y),cos(spherical.x)*len\n);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeComputeClippingZ(vec3 spherePos) {return (1.0-(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphere(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphere(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphere(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphere(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}"),background:_t("uniform vec4 u_color;uniform float u_opacity;void main() {fragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),backgroundPattern:_t("uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}"),circle:_t("in vec3 v_data;in float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);float antialiased_blur=v_data.z;float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));fragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);const float epsilon=0.5/255.0;if (fragColor.r < epsilon && fragColor.g < epsilon && fragColor.b < epsilon && fragColor.a < epsilon) {discard;}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;uniform vec2 u_translate;in vec2 a_pos;out vec3 v_data;out float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 pos_raw=a_pos+32768.0;vec2 extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);vec2 circle_center=floor(pos_raw/8.0)+u_translate;float ele=get_elevation(circle_center);v_visibility=calculate_visibility(projectTileWithElevation(circle_center,ele));if (u_pitch_with_map) {\n#ifdef GLOBE\nvec3 center_vector=projectToSphere(circle_center);\n#endif\nfloat angle_scale=u_globe_extrude_scale;vec2 corner_position=circle_center;if (u_scale_with_map) {angle_scale*=(radius+stroke_width);corner_position+=extrude*u_extrude_scale*(radius+stroke_width);} else {\n#ifdef GLOBE\nvec4 projected_center=interpolateProjection(circle_center,center_vector,ele);\n#else\nvec4 projected_center=projectTileWithElevation(circle_center,ele);\n#endif\ncorner_position+=extrude*u_extrude_scale*(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);angle_scale*=(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);}\n#ifdef GLOBE\nvec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);\n#else\ngl_Position=projectTileWithElevation(corner_position,ele);\n#endif\n} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),clippingMask:_t(ut,"in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),heatmap:_t("uniform highp float u_intensity;in vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);fragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;uniform highp float u_globe_extrude_scale;in vec2 a_pos;out vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 pos_raw=a_pos+32768.0;vec2 unscaled_extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 circle_center=floor(pos_raw/8.0);\n#ifdef GLOBE\nvec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphere(circle_center);vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);\n#else\ngl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));\n#endif\n}"),heatmapTexture:_t("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(0.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),collisionBox:_t("in float v_placed;in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}","in vec2 a_anchor_pos;in vec2 a_placed;in vec2 a_box_real;uniform vec2 u_pixel_extrude_scale;out float v_placed;out float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}"),collisionCircle:_t("in float v_radius;in vec2 v_extrude;in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);fragColor=color*alpha*opacity_t;}","in vec2 a_pos;in float a_radius;in vec2 a_flags;uniform vec2 u_viewport_size;out float v_radius;out vec2 v_extrude;out float v_collision;void main() {float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),debug:_t("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);fragColor=mix(u_color,overlay_color,overlay_color.a);}","in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}"),depth:_t(ut,"in vec2 a_pos;void main() {\n#ifdef GLOBE\ngl_Position=projectTileFor3D(a_pos,0.0);\n#else\ngl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);\n#endif\n}"),fill:_t("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\nfragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_fill_translate;in vec2 a_pos;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);}"),fillOutline:_t("in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=outline_color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillOutlinePattern:_t("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillPattern:_t("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),fillExtrusion:_t("in vec4 v_color;void main() {fragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\nout vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nfloat colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;vec3 normalForLighting=normal/16384.0;float directional=clamp(dot(normalForLighting,u_lightpos),0.0,1.0);\n#ifdef GLOBE\nmat3 rotMatrix=globeGetRotationMatrix(spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);\n#endif\ndirectional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),fillExtrusionPattern:_t("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;in vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);fragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\n#ifdef GLOBE\nout vec3 v_sphere_pos;\n#endif\nout vec2 v_pos_a;out vec2 v_pos_b;out vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nvec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,elevation*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),hillshadePrepare:_t("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/pow(2.0,exaggeration+(19.2562-u_zoom));fragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;in vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),hillshade:_t("uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\n#define PI 3.141592653589793\nvoid main() {vec4 pixel=texture(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);fragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),line:_t("uniform lowp float u_device_pixel_ratio;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp float v_linesofar;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),lineGradient:_t("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture(u_image,v_uv);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;in float a_uv_x;in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),linePattern:_t("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;in vec2 v_normal;in vec2 v_width2;in float v_linesofar;in float v_gamma_scale;in float v_width;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture(u_image,pos_a),texture(u_image,pos_b),u_fade);fragColor=color*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_linesofar;out float v_gamma_scale;out float v_width;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),lineSDF:_t("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture(u_image,v_tex_a).a;float sdfdist_b=texture(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;out vec2 v_normal;out vec2 v_width2;out vec2 v_tex_a;out vec2 v_tex_b;out float v_gamma_scale;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),raster:_t("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec2 v_pos0;in vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture(u_image0,v_pos0);vec4 color1=texture(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;uniform vec4 u_coords_top;uniform vec4 u_coords_bottom;in vec2 a_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {vec2 fractionalPos=a_pos/8192.0;vec2 position=mix(mix(u_coords_top.xy,u_coords_top.zw,fractionalPos.x),mix(u_coords_bottom.xy,u_coords_bottom.zw,fractionalPos.x),fractionalPos.y);gl_Position=projectTile(position,position);v_pos0=((fractionalPos-0.5)/u_buffer_scale)+0.5;\n#ifdef GLOBE\nif (a_pos.y <-32767.5) {v_pos0.y=0.0;}if (a_pos.y > 32766.5) {v_pos0.y=1.0;}\n#endif\nv_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),symbolIcon:_t("uniform sampler2D u_texture;in vec2 v_tex;in float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;fragColor=texture(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_tex;out float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}"),symbolSDF:_t("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;in vec2 v_data0;in vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_data0;out vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),symbolTextAndIcon:_t("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;in vec4 v_data0;in vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;fragColor=texture(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec4 v_data0;out vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}"),terrain:_t("uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;uniform bool u_is_globe_mode;in vec2 v_texture_pos;in float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);fragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {fragColor=surface_color;}}","in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_texture_pos;out float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,get_elevation(a_pos3d.xy)-ele_delta);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}"),terrainDepth:_t("in float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {fragColor=pack(v_depth);}","in vec3 a_pos3d;uniform float u_ele_delta;out float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}"),terrainCoords:_t("precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;in vec2 v_texture_pos;void main() {vec4 rgba=texture(u_texture,v_texture_pos);fragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}","in vec3 a_pos3d;uniform float u_ele_delta;out vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);}"),projectionErrorMeasurement:_t("in vec4 v_output_error_encoded;void main() {fragColor=v_output_error_encoded;}","in vec2 a_pos;uniform highp float u_input;uniform highp float u_output_expected;out vec4 v_output_error_encoded;void main() {float real_output=2.0*atan(exp(PI-(u_input*PI*2.0)))-PI*0.5;float error=real_output-u_output_expected;float abs_error=abs(error)*128.0;v_output_error_encoded.x=min(floor(abs_error*256.0),255.0)/255.0;abs_error-=v_output_error_encoded.x;v_output_error_encoded.y=min(floor(abs_error*65536.0),255.0)/255.0;abs_error-=v_output_error_encoded.x/255.0;v_output_error_encoded.z=min(floor(abs_error*16777216.0),255.0)/255.0;v_output_error_encoded.w=error >=0.0 ? 1.0 : 0.0;gl_Position=vec4(a_pos,0.0,1.0);}"),atmosphere:_t("in vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) {return vec4(0.0,0.0,0.0,1.0);}if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie)));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758\n);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}","in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}"),sky:_t("uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor=mix(fragColor,vec4(vec3(0.0),0.0),u_sky_blend);}","in vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}")};function _t(e,t){const i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,r=t.match(/in ([\w]+) ([\w]+)/g),o=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),s=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=s?s.concat(o):o,n={};return {fragmentSource:e=e.replace(i,((e,t,i,r,o)=>(n[o]=true,"define"===t?`\n#ifndef HAS_UNIFORM_u_${o}\nin ${i} ${r} ${o};\n#else\nuniform ${i} ${r} u_${o};\n#endif\n`:`\n#ifdef HAS_UNIFORM_u_${o}\n ${i} ${r} ${o} = u_${o};\n#endif\n`))),vertexSource:t=t.replace(i,((e,t,i,r,o)=>{const s="float"===r?"vec2":"vec4",a=o.match(/color/)?"color":s;return n[o]?"define"===t?`\n#ifndef HAS_UNIFORM_u_${o}\nuniform lowp float u_${o}_t;\nin ${i} ${s} a_${o};\nout ${i} ${r} ${o};\n#else\nuniform ${i} ${r} u_${o};\n#endif\n`:"vec4"===a?`\n#ifndef HAS_UNIFORM_u_${o}\n ${o} = a_${o};\n#else\n ${i} ${r} ${o} = u_${o};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${o}\n ${o} = unpack_mix_${a}(a_${o}, u_${o}_t);\n#else\n ${i} ${r} ${o} = u_${o};\n#endif\n`:"define"===t?`\n#ifndef HAS_UNIFORM_u_${o}\nuniform lowp float u_${o}_t;\nin ${i} ${s} a_${o};\n#else\nuniform ${i} ${r} u_${o};\n#endif\n`:"vec4"===a?`\n#ifndef HAS_UNIFORM_u_${o}\n ${i} ${r} ${o} = a_${o};\n#else\n ${i} ${r} ${o} = u_${o};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${o}\n ${i} ${r} ${o} = unpack_mix_${a}(a_${o}, u_${o}_t);\n#else\n ${i} ${r} ${o} = u_${o};\n#endif\n`})),staticAttributes:r,staticUniforms:a}}class pt{constructor(e,t,i){this.vertexBuffer=e,this.indexBuffer=t,this.segments=i;}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.vertexBuffer=null,this.indexBuffer=null,this.segments=null;}}var mt=t.aA([{name:"a_pos",type:"Int16",components:2}]);const ft="#define PROJECTION_MERCATOR",gt="mercator";class vt{constructor(){this._cachedMesh=null;}get name(){return "mercator"}get useSubdivision(){return false}get shaderVariantName(){return gt}get shaderDefine(){return ft}get shaderPreludeCode(){return dt.projectionMercator}get vertexShaderPreludeCode(){return dt.projectionMercator.vertexSource}get subdivisionGranularity(){return t.aB.noSubdivision}get useGlobeControls(){return false}get transitionState(){return 0}get latitudeErrorCorrectionRadians(){return 0}destroy(){}updateGPUdependent(e){}getMeshFromTileID(e,i,r,o,s){if(this._cachedMesh)return this._cachedMesh;const a=new t.aC;a.emplaceBack(0,0),a.emplaceBack(t.X,0),a.emplaceBack(0,t.X),a.emplaceBack(t.X,t.X);const n=e.createVertexBuffer(a,mt.members),l=t.aD.simpleSegment(0,0,4,2),c=new t.aE;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3);const h=e.createIndexBuffer(c);return this._cachedMesh=new pt(n,h,l),this._cachedMesh}recalculate(){}hasTransition(){return false}setErrorQueryLatitudeDegrees(e){}}function xt(e,i){const r=t.ab(i.lat,-t.aF,t.aF);return new t.P(t.O(i.lng)*e,t.Q(r)*e)}function bt(e,i){return new t.Y(i.x/e,i.y/e).toLngLat()}function yt(e){return e.cameraToCenterDistance*Math.min(.85*Math.tan(t.aa(90-e.pitch)),Math.tan(t.aa(89.25-e.pitch)))}function wt(e,i){const r=e.canonical,o=i/t.aG(r.z),s=r.x+Math.pow(2,r.z)*e.wrap,a=t.aq(new Float64Array(16));return t.J(a,a,[s*o,r.y*o,0]),t.K(a,a,[o/t.X,o/t.X,1]),a}function Tt(e,i,r,o,s){const a=t.Y.fromLngLat(e,i),n=s*t.aH(1,e.lat),l=n*Math.cos(t.aa(r)),c=Math.sqrt(n*n-l*l),h=c*Math.sin(t.aa(-o)),u=c*Math.cos(t.aa(-o));return new t.Y(a.x+h,a.y+u,a.z+l)}class Pt{constructor(e=0,t=0,i=0,r=0){if(isNaN(e)||e<0||isNaN(t)||t<0||isNaN(i)||i<0||isNaN(r)||r<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=e,this.bottom=t,this.left=i,this.right=r;}interpolate(e,i,r){return null!=i.top&&null!=e.top&&(this.top=t.y.number(e.top,i.top,r)),null!=i.bottom&&null!=e.bottom&&(this.bottom=t.y.number(e.bottom,i.bottom,r)),null!=i.left&&null!=e.left&&(this.left=t.y.number(e.left,i.left,r)),null!=i.right&&null!=e.right&&(this.right=t.y.number(e.right,i.right,r)),this}getCenter(e,i){const r=t.ab((this.left+e-this.right)/2,0,e),o=t.ab((this.top+i-this.bottom)/2,0,i);return new t.P(r,o)}equals(e){return this.top===e.top&&this.bottom===e.bottom&&this.left===e.left&&this.right===e.right}clone(){return new Pt(this.top,this.bottom,this.left,this.right)}toJSON(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function Ct(e,t){if(!e.renderWorldCopies||e.lngRange)return;const i=t.lng-e.center.lng;t.lng+=i>180?-360:i<-180?360:0;}function It(e){return Math.max(0,Math.floor(e))}class Et{constructor(e,i,r,o,s,a){this._callbacks=e,this._tileSize=512,this._renderWorldCopies=undefined===a||!!a,this._minZoom=i||0,this._maxZoom=r||22,this._minPitch=null==o?0:o,this._maxPitch=null==s?60:s,this.setMaxBounds(),this._width=0,this._height=0,this._center=new t.N(0,0),this._elevation=0,this._zoom=0,this._tileZoom=It(this._zoom),this._scale=t.aG(this._zoom),this._bearingInRadians=0,this._fovInRadians=.6435011087932844,this._pitchInRadians=0,this._rollInRadians=0,this._unmodified=true,this._edgeInsets=new Pt,this._minElevationForCurrentTile=0,this._autoCalculateNearFarZ=true;}apply(e,i,r){this._latRange=e.latRange,this._lngRange=e.lngRange,this._width=e.width,this._height=e.height,this._center=e.center,this._elevation=e.elevation,this._minElevationForCurrentTile=e.minElevationForCurrentTile,this._zoom=e.zoom,this._tileZoom=It(this._zoom),this._scale=t.aG(this._zoom),this._bearingInRadians=e.bearingInRadians,this._fovInRadians=e.fovInRadians,this._pitchInRadians=e.pitchInRadians,this._rollInRadians=e.rollInRadians,this._unmodified=e.unmodified,this._edgeInsets=new Pt(e.padding.top,e.padding.bottom,e.padding.left,e.padding.right),this._minZoom=e.minZoom,this._maxZoom=e.maxZoom,this._minPitch=e.minPitch,this._maxPitch=e.maxPitch,this._renderWorldCopies=e.renderWorldCopies,this._cameraToCenterDistance=e.cameraToCenterDistance,this._nearZ=e.nearZ,this._farZ=e.farZ,this._autoCalculateNearFarZ=!r&&e.autoCalculateNearFarZ,i&&this._constrain(),this._calcMatrices();}get pixelsToClipSpaceMatrix(){return this._pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._clipSpaceToPixelsMatrix}get minElevationForCurrentTile(){return this._minElevationForCurrentTile}setMinElevationForCurrentTile(e){this._minElevationForCurrentTile=e;}get tileSize(){return this._tileSize}get tileZoom(){return this._tileZoom}get scale(){return this._scale}get width(){return this._width}get height(){return this._height}get bearingInRadians(){return this._bearingInRadians}get lngRange(){return this._lngRange}get latRange(){return this._latRange}get pixelsToGLUnits(){return this._pixelsToGLUnits}get minZoom(){return this._minZoom}setMinZoom(e){this._minZoom!==e&&(this._minZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get maxZoom(){return this._maxZoom}setMaxZoom(e){this._maxZoom!==e&&(this._maxZoom=e,this.setZoom(this.getConstrained(this._center,this.zoom).zoom));}get minPitch(){return this._minPitch}setMinPitch(e){this._minPitch!==e&&(this._minPitch=e,this.setPitch(Math.max(this.pitch,e)));}get maxPitch(){return this._maxPitch}setMaxPitch(e){this._maxPitch!==e&&(this._maxPitch=e,this.setPitch(Math.min(this.pitch,e)));}get renderWorldCopies(){return this._renderWorldCopies}setRenderWorldCopies(e){undefined===e?e=true:null===e&&(e=false),this._renderWorldCopies=e;}get worldSize(){return this._tileSize*this._scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new t.P(this._width,this._height)}get bearing(){return this._bearingInRadians/Math.PI*180}setBearing(e){const i=t.aI(e,-180,180)*Math.PI/180;var o,s,a,n,l,c,h,u,d;this._bearingInRadians!==i&&(this._unmodified=false,this._bearingInRadians=i,this._calcMatrices(),this._rotationMatrix=r(),o=this._rotationMatrix,a=-this._bearingInRadians,n=(s=this._rotationMatrix)[0],l=s[1],c=s[2],h=s[3],u=Math.sin(a),d=Math.cos(a),o[0]=n*d+c*u,o[1]=l*d+h*u,o[2]=n*-u+c*d,o[3]=l*-u+h*d);}get rotationMatrix(){return this._rotationMatrix}get pitchInRadians(){return this._pitchInRadians}get pitch(){return this._pitchInRadians/Math.PI*180}setPitch(e){const i=t.ab(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitchInRadians!==i&&(this._unmodified=false,this._pitchInRadians=i,this._calcMatrices());}get rollInRadians(){return this._rollInRadians}get roll(){return this._rollInRadians/Math.PI*180}setRoll(e){const t=e/180*Math.PI;this._rollInRadians!==t&&(this._unmodified=false,this._rollInRadians=t,this._calcMatrices());}get fovInRadians(){return this._fovInRadians}get fov(){return t.aJ(this._fovInRadians)}setFov(e){e=t.ab(e,.1,150),this.fov!==e&&(this._unmodified=false,this._fovInRadians=t.aa(e),this._calcMatrices());}get zoom(){return this._zoom}setZoom(e){const i=this.getConstrained(this._center,e).zoom;this._zoom!==i&&(this._unmodified=false,this._zoom=i,this._tileZoom=Math.max(0,Math.floor(i)),this._scale=t.aG(i),this._constrain(),this._calcMatrices());}get center(){return this._center}setCenter(e){e.lat===this._center.lat&&e.lng===this._center.lng||(this._unmodified=false,this._center=e,this._constrain(),this._calcMatrices());}get elevation(){return this._elevation}setElevation(e){e!==this._elevation&&(this._elevation=e,this._constrain(),this._calcMatrices());}get padding(){return this._edgeInsets.toJSON()}setPadding(e){this._edgeInsets.equals(e)||(this._unmodified=false,this._edgeInsets.interpolate(this._edgeInsets,e,1),this._calcMatrices());}get centerPoint(){return this._edgeInsets.getCenter(this._width,this._height)}get pixelsPerMeter(){return this._pixelPerMeter}get unmodified(){return this._unmodified}get cameraToCenterDistance(){return this._cameraToCenterDistance}get nearZ(){return this._nearZ}get farZ(){return this._farZ}get autoCalculateNearFarZ(){return this._autoCalculateNearFarZ}overrideNearFarZ(e,t){this._autoCalculateNearFarZ=false,this._nearZ=e,this._farZ=t,this._calcMatrices();}clearNearFarZOverride(){this._autoCalculateNearFarZ=true,this._calcMatrices();}isPaddingEqual(e){return this._edgeInsets.equals(e)}interpolatePadding(e,t,i){this._unmodified=false,this._edgeInsets.interpolate(e,t,i),this._constrain(),this._calcMatrices();}resize(e,t,i=true){this._width=e,this._height=t,i&&this._constrain(),this._calcMatrices();}getMaxBounds(){return this._latRange&&2===this._latRange.length&&this._lngRange&&2===this._lngRange.length?new V([this._lngRange[0],this._latRange[0]],[this._lngRange[1],this._latRange[1]]):null}setMaxBounds(e){e?(this._lngRange=[e.getWest(),e.getEast()],this._latRange=[e.getSouth(),e.getNorth()],this._constrain()):(this._lngRange=null,this._latRange=[-t.aF,t.aF]);}getConstrained(e,t){return this._callbacks.getConstrained(e,t)}getCameraQueryGeometry(e,i){if(1===i.length)return [i[0],e];{let r=e.x,o=e.y,s=e.x,a=e.y;for(const e of i)r=Math.min(r,e.x),o=Math.min(o,e.y),s=Math.max(s,e.x),a=Math.max(a,e.y);return [new t.P(r,o),new t.P(s,o),new t.P(s,a),new t.P(r,a),new t.P(r,o)]}}_constrain(){if(!this.center||!this._width||!this._height||this._constraining)return;this._constraining=true;const e=this._unmodified,{center:t,zoom:i}=this.getConstrained(this.center,this.zoom);this.setCenter(t),this.setZoom(i),this._unmodified=e,this._constraining=false;}_calcMatrices(){if(this._width&&this._height){this._pixelsToGLUnits=[2/this._width,-2/this._height];let e=t.aq(new Float64Array(16));t.K(e,e,[this._width/2,-this._height/2,1]),t.J(e,e,[1,-1,0]),this._clipSpaceToPixelsMatrix=e,e=t.aq(new Float64Array(16)),t.K(e,e,[1,-1,1]),t.J(e,e,[-1,-1,0]),t.K(e,e,[2/this._width,2/this._height,1]),this._pixelsToClipSpaceMatrix=e,this._cameraToCenterDistance=.5/Math.tan(this.fovInRadians/2)*this._height;}this._callbacks.calcMatrices();}calculateCenterFromCameraLngLatAlt(e,i,r,o){const s=undefined!==r?r:this.bearing,a=o=undefined!==o?o:this.pitch,n=t.Y.fromLngLat(e,i),l=-Math.cos(t.aa(a)),c=Math.sin(t.aa(a)),h=c*Math.sin(t.aa(s)),u=-c*Math.cos(t.aa(s));let d=this.elevation;const _=i-d;let p;l*_>=0||Math.abs(l)<.1?(p=1e4,d=i+p*l):p=-_/l;let m,f,g=t.aK(1,n.y),v=0;do{if(v+=1,v>10)break;f=p/g,m=new t.Y(n.x+h*f,n.y+u*f),g=1/m.meterInMercatorCoordinateUnits();}while(Math.abs(p-f*g)>1e-12);return {center:m.toLngLat(),elevation:d,zoom:t.a8(this.height/2/Math.tan(this.fovInRadians/2)/f/this.tileSize)}}recalculateZoomAndCenter(e){if(this.elevation-e==0)return;const i=t.aH(1,this.center.lat)*this.worldSize,r=this.cameraToCenterDistance/i,o=t.Y.fromLngLat(this.center,this.elevation),s=Tt(this.center,this.elevation,this.pitch,this.bearing,r);this._elevation=e;const a=this.calculateCenterFromCameraLngLatAlt(s.toLngLat(),t.aK(s.z,o.y),this.bearing,this.pitch);this._elevation=a.elevation,this._center=a.center,this.setZoom(a.zoom);}getCameraPoint(){const e=Math.tan(this.pitchInRadians)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new t.P(e*Math.sin(this.rollInRadians),e*Math.cos(this.rollInRadians)))}getCameraAltitude(){return Math.cos(this.pitchInRadians)*this._cameraToCenterDistance/this._pixelPerMeter+this.elevation}getCameraLngLat(){const e=t.aH(1,this.center.lat)*this.worldSize;return Tt(this.center,this.elevation,this.pitch,this.bearing,this.cameraToCenterDistance/e).toLngLat()}getMercatorTileCoordinates(e){if(!e)return [0,0,1,1];const i=e.canonical.z>=0?1<this.max[0]||e.aabb.min[1]>this.max[1]||e.aabb.min[2]>this.max[2]||e.aabb.max[0]0?(t+=e[r]*this.min[r],i+=e[r]*this.max[r]):(i+=e[r]*this.min[r],t+=e[r]*this.max[r]);return t>=0?2:i<0?0:1}}class St{distanceToTile2d(e,t,i,r){const o=r.distanceX([e,t]),s=r.distanceY([e,t]);return Math.hypot(o,s)}getWrap(e,t,i){return i}getTileAABB(e,i,r,o){var s,a;let n=r,l=r;if(o.terrain){const c=new t.S(e.z,i,e.z,e.x,e.y),h=o.terrain.getMinMaxElevation(c);n=null!==(s=h.minElevation)&&undefined!==s?s:r,l=null!==(a=h.maxElevation)&&undefined!==a?a:r;}const c=1<o||e.padding.top>=.1}allowWorldCopies(){return true}recalculateCache(){}}class Rt{constructor(e,t,i){this.points=e,this.planes=t,this.aabb=i;}static fromInvProjectionMatrix(e,i=1,r=0){const o=Math.pow(2,r),s=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((r=>{const s=1/(r=t.al([],r,e))[3]/i*o;return t.aO(r,r,[s,s,1/r[3],s])})),a=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map((e=>{const i=t.aP([],s[e[0]],s[e[1]]),r=t.aP([],s[e[2]],s[e[1]]),o=t.aQ([],t.aR([],i,r)),a=-t.aS(o,s[e[1]]);return o.concat(a)})),n=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],l=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];for(const e of s)for(let t=0;t<3;t++)n[t]=Math.min(n[t],e[t]),l[t]=Math.max(l[t],e[t]);return new Rt(s,a,new Mt(n,l))}}class Dt{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=true){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}setTransitionState(e,t){}constructor(e,t,i,r,o){this._posMatrixCache=new Map,this._alignedPosMatrixCache=new Map,this._fogMatrixCacheF32=new Map,this._helper=new Et({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)},e,t,i,r,o),this._coveringTilesDetailsProvider=new St;}clone(){const e=new Dt;return e.apply(this),e}apply(e,t,i){this._helper.apply(e,t,i);}get cameraPosition(){return this._cameraPosition}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._viewProjMatrix}get inverseProjectionMatrix(){return this._invProjMatrix}get mercatorMatrix(){return this._mercatorMatrix}getVisibleUnwrappedCoordinates(e){const i=[new t.aT(0,e)];if(this._helper._renderWorldCopies){const r=this.screenPointToMercatorCoordinate(new t.P(0,0)),o=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,0)),s=this.screenPointToMercatorCoordinate(new t.P(this._helper._width,this._helper._height)),a=this.screenPointToMercatorCoordinate(new t.P(0,this._helper._height)),n=Math.floor(Math.min(r.x,o.x,s.x,a.x)),l=Math.floor(Math.max(r.x,o.x,s.x,a.x)),c=1;for(let r=n-c;r<=l+c;r++)0!==r&&i.push(new t.aT(r,e));}return i}getCameraFrustum(){return Rt.fromInvProjectionMatrix(this._invViewProjMatrix,this.worldSize)}getClippingPlane(){return null}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(e){const t=this.screenPointToLocation(this.centerPoint,e),i=e?e.getElevationForLngLatZoom(t,this._helper._tileZoom):0;this._helper.recalculateZoomAndCenter(i);}setLocationAtPoint(e,i){const r=t.aH(this.elevation,this.center.lat),o=this.screenPointToMercatorCoordinateAtZ(i,r),s=this.screenPointToMercatorCoordinateAtZ(this.centerPoint,r),a=t.Y.fromLngLat(e),n=new t.Y(a.x-(o.x-s.x),a.y-(o.y-s.y));this.setCenter(null==n?undefined:n.toLngLat()),this._helper._renderWorldCopies&&this.setCenter(this.center.wrap());}locationToScreenPoint(e,i){return i?this.coordinatePoint(t.Y.fromLngLat(e),i.getElevationForLngLatZoom(e,this._helper._tileZoom),this._pixelMatrix3D):this.coordinatePoint(t.Y.fromLngLat(e))}screenPointToLocation(e,t){var i;return null===(i=this.screenPointToMercatorCoordinate(e,t))||undefined===i?undefined:i.toLngLat()}screenPointToMercatorCoordinate(e,t){if(t){const i=t.pointCoordinate(e);if(null!=i)return i}return this.screenPointToMercatorCoordinateAtZ(e)}screenPointToMercatorCoordinateAtZ(e,i){const r=i||0,o=[e.x,e.y,0,1],s=[e.x,e.y,1,1];t.al(o,o,this._pixelMatrixInverse),t.al(s,s,this._pixelMatrixInverse);const a=o[3],n=s[3],l=o[1]/a,c=s[1]/n,h=o[2]/a,u=s[2]/n,d=h===u?0:(r-h)/(u-h);return new t.Y(t.y.number(o[0]/a,s[0]/n,d)/this.worldSize,t.y.number(l,c,d)/this.worldSize,r)}coordinatePoint(e,i=0,r=this._pixelMatrix){const o=[e.x*this.worldSize,e.y*this.worldSize,i,1];return t.al(o,o,r),new t.P(o[0]/o[3],o[1]/o[3])}getBounds(){const e=Math.max(0,this._helper._height/2-yt(this));return (new V).extend(this.screenPointToLocation(new t.P(0,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,e))).extend(this.screenPointToLocation(new t.P(this._helper._width,this._helper._height))).extend(this.screenPointToLocation(new t.P(0,this._helper._height)))}isPointOnMapSurface(e,t){return t?null!=t.pointCoordinate(e):e.y>this.height/2-yt(this)}calculatePosMatrix(e,i=false,r){var o;const s=null!==(o=e.key)&&undefined!==o?o:t.aU(e.wrap,e.canonical.z,e.canonical.z,e.canonical.x,e.canonical.y),a=i?this._alignedPosMatrixCache:this._posMatrixCache;if(a.has(s)){const e=a.get(s);return r?e.f32:e.f64}const n=wt(e,this.worldSize);t.L(n,i?this._alignedProjMatrix:this._viewProjMatrix,n);const l={f64:n,f32:new Float32Array(n)};return a.set(s,l),r?l.f32:l.f64}calculateFogMatrix(e){const i=e.key,r=this._fogMatrixCacheF32;if(r.has(i))return r.get(i);const o=wt(e,this.worldSize);return t.L(o,this._fogMatrix,o),r.set(i,new Float32Array(o)),r.get(i)}getConstrained(e,i){i=t.ab(+i,this.minZoom,this.maxZoom);const r={center:new t.N(e.lng,e.lat),zoom:i};let o=this._helper._lngRange;if(!this._helper._renderWorldCopies&&null===o){const e=180-1e-10;o=[-179.9999999999,e];}const s=this.tileSize*t.aG(r.zoom);let a=0,n=s,l=0,c=s,h=0,u=0;const{x:d,y:_}=this.size;if(this._helper._latRange){const e=this._helper._latRange;a=t.Q(e[1])*s,n=t.Q(e[0])*s,n-a<_&&(h=_/(n-a));}o&&(l=t.aI(t.O(o[0])*s,0,s),c=t.aI(t.O(o[1])*s,0,s),cn&&(g=n-e);}if(o){const e=(l+c)/2;let i=p;this._helper._renderWorldCopies&&(i=t.aI(p,e-s/2,e+s/2));const r=d/2;i-rc&&(f=c-r);}if(undefined!==f||undefined!==g){const e=new t.P(null!=f?f:p,null!=g?g:m);r.center=bt(s,e).wrap();}return r}calculateCenterFromCameraLngLatAlt(e,t,i,r){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,r)}_calculateNearFarZIfNeeded(e,i,r){if(!this._helper.autoCalculateNearFarZ)return;const o=Math.min(this.elevation,this.minElevationForCurrentTile,this.getCameraAltitude()-100),s=e-o*this._helper._pixelPerMeter/Math.cos(i),a=o<0?s:e,n=Math.PI/2+this.pitchInRadians,l=t.aa(this.fov)*(Math.abs(Math.cos(t.aa(this.roll)))*this.height+Math.abs(Math.sin(t.aa(this.roll)))*this.width)/this.height*(.5+r.y/this.height),c=Math.sin(l)*a/Math.sin(t.ab(Math.PI-n-l,.01,Math.PI-.01)),h=yt(this),u=Math.atan(h/this._helper.cameraToCenterDistance),d=t.aa(.75),_=u>d?2*u*(.5+r.y/(2*h)):d,p=Math.sin(_)*a/Math.sin(t.ab(Math.PI-n-_,.01,Math.PI-.01)),m=Math.min(c,p);this._helper._farZ=1.01*(Math.cos(Math.PI/2-i)*m+a),this._helper._nearZ=this._helper._height/50;}_calcMatrices(){if(!this._helper._height)return;const e=this.centerOffset,i=xt(this.worldSize,this.center),r=i.x,o=i.y;this._helper._pixelPerMeter=t.aH(1,this.center.lat)*this.worldSize;const s=t.aa(Math.min(this.pitch,89.25)),a=Math.max(this._helper.cameraToCenterDistance/2,this._helper.cameraToCenterDistance+this._helper._elevation*this._helper._pixelPerMeter/Math.cos(s));let n;this._calculateNearFarZIfNeeded(a,s,e),n=new Float64Array(16),t.aV(n,this.fovInRadians,this._helper._width/this._helper._height,this._helper._nearZ,this._helper._farZ),this._invProjMatrix=new Float64Array(16),t.an(this._invProjMatrix,n),n[8]=2*-e.x/this._helper._width,n[9]=2*e.y/this._helper._height,this._projectionMatrix=t.aW(n),t.K(n,n,[1,-1,1]),t.J(n,n,[0,0,-this._helper.cameraToCenterDistance]),t.aX(n,n,-this.rollInRadians),t.aY(n,n,this.pitchInRadians),t.aX(n,n,-this.bearingInRadians),t.J(n,n,[-r,-o,0]),this._mercatorMatrix=t.K([],n,[this.worldSize,this.worldSize,this.worldSize]),t.K(n,n,[1,1,this._helper._pixelPerMeter]),this._pixelMatrix=t.L(new Float64Array(16),this.clipSpaceToPixelsMatrix,n),t.J(n,n,[0,0,-this.elevation]),this._viewProjMatrix=n,this._invViewProjMatrix=t.an([],n);const l=[0,0,-1,1];t.al(l,l,this._invViewProjMatrix),this._cameraPosition=[l[0]/l[3],l[1]/l[3],l[2]/l[3]],this._fogMatrix=new Float64Array(16),t.aV(this._fogMatrix,this.fovInRadians,this.width/this.height,a,this._helper._farZ),this._fogMatrix[8]=2*-e.x/this.width,this._fogMatrix[9]=2*e.y/this.height,t.K(this._fogMatrix,this._fogMatrix,[1,-1,1]),t.J(this._fogMatrix,this._fogMatrix,[0,0,-this.cameraToCenterDistance]),t.aX(this._fogMatrix,this._fogMatrix,-this.rollInRadians),t.aY(this._fogMatrix,this._fogMatrix,this.pitchInRadians),t.aX(this._fogMatrix,this._fogMatrix,-this.bearingInRadians),t.J(this._fogMatrix,this._fogMatrix,[-r,-o,0]),t.K(this._fogMatrix,this._fogMatrix,[1,1,this._helper._pixelPerMeter]),t.J(this._fogMatrix,this._fogMatrix,[0,0,-this.elevation]),this._pixelMatrix3D=t.L(new Float64Array(16),this.clipSpaceToPixelsMatrix,n);const c=this._helper._width%2/2,h=this._helper._height%2/2,u=Math.cos(this.bearingInRadians),d=Math.sin(-this.bearingInRadians),_=r-Math.round(r)+u*c+d*h,p=o-Math.round(o)+u*h+d*c,m=new Float64Array(n);if(t.J(m,m,[_>.5?_-1:_,p>.5?p-1:p,0]),this._alignedProjMatrix=m,n=t.an(new Float64Array(16),this._pixelMatrix),!n)throw new Error("failed to invert matrix");this._pixelMatrixInverse=n,this._clearMatrixCaches();}_clearMatrixCaches(){this._posMatrixCache.clear(),this._alignedPosMatrixCache.clear(),this._fogMatrixCacheF32.clear();}maxPitchScaleFactor(){if(!this._pixelMatrixInverse)return 1;const e=this.screenPointToMercatorCoordinate(new t.P(0,0)),i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.al(i,i,this._pixelMatrix)[3]/this._helper.cameraToCenterDistance}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){const e=t.aH(1,this.center.lat)*this.worldSize;return Tt(this.center,this.elevation,this.pitch,this.bearing,this._helper.cameraToCenterDistance/e).toLngLat()}lngLatToCameraDepth(e,i){const r=t.Y.fromLngLat(e),o=[r.x*this.worldSize,r.y*this.worldSize,i,1];return t.al(o,o,this._viewProjMatrix),o[2]/o[3]}getProjectionData(e){const{overscaledTileID:i,aligned:r,applyTerrainMatrix:o}=e,s=this._helper.getMercatorTileCoordinates(i),a=i?this.calculatePosMatrix(i,r,true):null;let n;return n=i&&i.terrainRttPosMatrix32f&&o?i.terrainRttPosMatrix32f:a||t.aZ(),{mainMatrix:n,tileMercatorCoords:s,clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:n}}isLocationOccluded(e){return false}getPixelScale(){return 1}getCircleRadiusCorrection(){return 1}getPitchedTextCorrection(e,t,i){return 1}transformLightDirection(e){return t.aN(e)}getRayDirectionFromPixel(e){throw new Error("Not implemented.")}projectTileCoordinates(e,i,r,o){const s=this.calculatePosMatrix(r);let a;o?(a=[e,i,o(e,i),1],t.al(a,a,s)):(a=[e,i,0,1],je(a,a,s));const n=a[3];return {point:new t.P(a[0]/n,a[1]/n),signedDistanceFromCamera:n,isOccluded:false}}populateCache(e){for(const t of e)this.calculatePosMatrix(t);}getMatrixForModel(e,i){const r=t.Y.fromLngLat(e,i),o=r.meterInMercatorCoordinateUnits(),s=t.a_();return t.J(s,s,[r.x,r.y,r.z]),t.aX(s,s,Math.PI),t.aY(s,s,Math.PI/2),t.K(s,s,[-o,o,o]),s}getProjectionDataForCustomLayer(e=true){const i=new t.S(0,0,0,0,0),r=this.getProjectionData({overscaledTileID:i,applyGlobeMatrix:e}),o=wt(i,this.worldSize);t.L(o,this._viewProjMatrix,o),r.tileMercatorCoords=[0,0,1,1];const s=[t.X,t.X,this.worldSize/this._helper.pixelsPerMeter],a=t.a$();return t.K(a,o,s),r.fallbackMatrix=a,r.mainMatrix=a,r}getFastPathSimpleProjectionMatrix(e){return this.calculatePosMatrix(e)}}function zt(){t.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");}function At(e){if(e.useSlerp)if(e.k<1){const i=t.b0(e.startEulerAngles.roll,e.startEulerAngles.pitch,e.startEulerAngles.bearing),r=t.b0(e.endEulerAngles.roll,e.endEulerAngles.pitch,e.endEulerAngles.bearing),o=new Float64Array(4);t.b1(o,i,r,e.k);const s=t.b2(o);e.tr.setRoll(s.roll),e.tr.setPitch(s.pitch),e.tr.setBearing(s.bearing);}else e.tr.setRoll(e.endEulerAngles.roll),e.tr.setPitch(e.endEulerAngles.pitch),e.tr.setBearing(e.endEulerAngles.bearing);else e.tr.setRoll(t.y.number(e.startEulerAngles.roll,e.endEulerAngles.roll,e.k)),e.tr.setPitch(t.y.number(e.startEulerAngles.pitch,e.endEulerAngles.pitch,e.k)),e.tr.setBearing(t.y.number(e.startEulerAngles.bearing,e.endEulerAngles.bearing,e.k));}function Lt(e,i,r,o,s){const a=s.padding,n=xt(s.worldSize,r.getNorthWest()),l=xt(s.worldSize,r.getNorthEast()),c=xt(s.worldSize,r.getSouthEast()),h=xt(s.worldSize,r.getSouthWest()),u=t.aa(-o),d=n.rotate(u),_=l.rotate(u),p=c.rotate(u),m=h.rotate(u),f=new t.P(Math.max(d.x,_.x,m.x,p.x),Math.max(d.y,_.y,m.y,p.y)),g=new t.P(Math.min(d.x,_.x,m.x,p.x),Math.min(d.y,_.y,m.y,p.y)),v=f.sub(g),x=(s.width-(a.left+a.right+i.left+i.right))/v.x,b=(s.height-(a.top+a.bottom+i.top+i.bottom))/v.y;if(b<0||x<0)return void zt();const y=Math.min(t.a8(s.scale*Math.min(x,b)),e.maxZoom),w=t.P.convert(e.offset),T=new t.P((i.left-i.right)/2,(i.top-i.bottom)/2).rotate(t.aa(o)),P=w.add(T).mult(s.scale/t.aG(y));return {center:bt(s.worldSize,n.add(c).div(2).sub(P)),zoom:y,bearing:o}}class kt{get useGlobeControls(){return false}handlePanInertia(e,t){return {easingOffset:e,easingCenter:t.center}}handleMapControlsRollPitchBearingZoom(e,t){e.bearingDelta&&t.setBearing(t.bearing+e.bearingDelta),e.pitchDelta&&t.setPitch(t.pitch+e.pitchDelta),e.rollDelta&&t.setRoll(t.roll+e.rollDelta),e.zoomDelta&&t.setZoom(t.zoom+e.zoomDelta);}handleMapControlsPan(e,t,i){e.around.distSqr(t.centerPoint)<.01||t.setLocationAtPoint(i,e.around);}cameraForBoxAndBearing(e,t,i,r,o){return Lt(e,t,i,r,o)}handleJumpToCenterZoom(e,i){e.zoom!==(undefined!==i.zoom?+i.zoom:e.zoom)&&e.setZoom(+i.zoom),undefined!==i.center&&e.setCenter(t.N.convert(i.center));}handleEaseTo(e,i){const r=e.zoom,o=e.padding,s={roll:e.roll,pitch:e.pitch,bearing:e.bearing},a={roll:undefined===i.roll?e.roll:i.roll,pitch:undefined===i.pitch?e.pitch:i.pitch,bearing:undefined===i.bearing?e.bearing:i.bearing},n=undefined!==i.zoom,l=!e.isPaddingEqual(i.padding);let c=false;const h=n?+i.zoom:e.zoom;let u=e.centerPoint.add(i.offsetAsPoint);const d=e.screenPointToLocation(u),{center:_,zoom:p}=e.getConstrained(t.N.convert(i.center||d),null!=h?h:r);Ct(e,_);const m=xt(e.worldSize,d),f=xt(e.worldSize,_).sub(m),g=t.aG(p-r);return c=p!==r,{easeFunc:n=>{if(c&&e.setZoom(t.y.number(r,p,n)),t.b3(s,a)||At({startEulerAngles:s,endEulerAngles:a,tr:e,k:n,useSlerp:s.roll!=a.roll}),l&&(e.interpolatePadding(o,i.padding,n),u=e.centerPoint.add(i.offsetAsPoint)),i.around)e.setLocationAtPoint(i.around,i.aroundPoint);else {const i=t.aG(e.zoom-r),o=p>r?Math.min(2,g):Math.max(.5,g),s=Math.pow(o,1-n),a=bt(e.worldSize,m.add(f.mult(n*s)).mult(i));e.setLocationAtPoint(e.renderWorldCopies?a.wrap():a,u);}},isZooming:c,elevationCenter:_}}handleFlyTo(e,i){const r=undefined!==i.zoom,o=e.zoom,s=e.getConstrained(t.N.convert(i.center||i.locationAtOffset),r?+i.zoom:o),a=s.center,n=s.zoom;Ct(e,a);const l=xt(e.worldSize,i.locationAtOffset),c=xt(e.worldSize,a).sub(l),h=c.mag(),u=t.aG(n-o);let d;if(undefined!==i.minZoom){const r=Math.min(+i.minZoom,o,n),s=e.getConstrained(a,r).zoom;d=t.aG(s-o);}return {easeFunc:(i,r,s,h)=>{e.setZoom(1===i?n:o+t.a8(r));const u=1===i?a:bt(e.worldSize,l.add(c.mult(s)).mult(r));e.setLocationAtPoint(e.renderWorldCopies?u.wrap():u,h);},scaleOfZoom:u,targetCenter:a,scaleOfMinZoom:d,pixelPathLength:h}}}class Ft{constructor(e,t,i){this.blendFunction=e,this.blendColor=t,this.mask=i;}}Ft.Replace=[1,0],Ft.disabled=new Ft(Ft.Replace,t.b4.transparent,[false,false,false,false]),Ft.unblended=new Ft(Ft.Replace,t.b4.transparent,[true,true,true,true]),Ft.alphaBlended=new Ft([1,771],t.b4.transparent,[true,true,true,true]);const Bt=2305;class jt{constructor(e,t,i){this.enable=e,this.mode=t,this.frontFace=i;}}jt.disabled=new jt(false,1029,Bt),jt.backCCW=new jt(true,1029,Bt),jt.frontCCW=new jt(true,1028,Bt);class Ot{constructor(e,t,i){this.func=e,this.mask=t,this.range=i;}}Ot.ReadOnly=false,Ot.ReadWrite=true,Ot.disabled=new Ot(519,Ot.ReadOnly,[0,1]);const Nt=7680;class Zt{constructor(e,t,i,r,o,s){this.test=e,this.ref=t,this.mask=i,this.fail=r,this.depthFail=o,this.pass=s;}}Zt.disabled=new Zt({func:519,mask:0},0,0,Nt,Nt,Nt);const Gt=new WeakMap;function Ut(e){var t;if(Gt.has(e))return Gt.get(e);{const i=null===(t=e.getParameter(e.VERSION))||undefined===t?undefined:t.startsWith("WebGL 2.0");return Gt.set(e,i),i}}class Vt{get awaitingQuery(){return !!this._readbackQueue}constructor(e){this._readbackWaitFrames=4,this._measureWaitFrames=6,this._texWidth=1,this._texHeight=1,this._measuredError=0,this._updateCount=0,this._lastReadbackFrame=-1e3,this._readbackQueue=null,this._cachedRenderContext=e;const i=e.context,r=i.gl;this._texFormat=r.RGBA,this._texType=r.UNSIGNED_BYTE;const o=new t.aC;o.emplaceBack(-1,-1),o.emplaceBack(2,-1),o.emplaceBack(-1,2);const s=new t.aE;s.emplaceBack(0,1,2),this._fullscreenTriangle=new pt(i.createVertexBuffer(o,mt.members),i.createIndexBuffer(s),t.aD.simpleSegment(0,0,o.length,s.length)),this._resultBuffer=new Uint8Array(4),i.activeTexture.set(r.TEXTURE1);const a=r.createTexture();r.bindTexture(r.TEXTURE_2D,a),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texImage2D(r.TEXTURE_2D,0,this._texFormat,this._texWidth,this._texHeight,0,this._texFormat,this._texType,null),this._fbo=i.createFramebuffer(this._texWidth,this._texHeight,false,false),this._fbo.colorAttachment.set(a),Ut(r)&&(this._pbo=r.createBuffer(),r.bindBuffer(r.PIXEL_PACK_BUFFER,this._pbo),r.bufferData(r.PIXEL_PACK_BUFFER,4,r.STREAM_READ),r.bindBuffer(r.PIXEL_PACK_BUFFER,null));}destroy(){const e=this._cachedRenderContext.context.gl;this._fullscreenTriangle.destroy(),this._fbo.destroy(),e.deleteBuffer(this._pbo),this._fullscreenTriangle=null,this._fbo=null,this._pbo=null,this._resultBuffer=null;}updateErrorLoop(e,t){const i=this._updateCount;return this._readbackQueue?i>=this._readbackQueue.frameNumberIssued+this._readbackWaitFrames&&this._tryReadback():i>=this._lastReadbackFrame+this._measureWaitFrames&&this._renderErrorTexture(e,t),this._updateCount++,this._measuredError}_bindFramebuffer(){const e=this._cachedRenderContext.context,t=e.gl;e.activeTexture.set(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this._fbo.colorAttachment.get()),e.bindFramebuffer.set(this._fbo.framebuffer);}_renderErrorTexture(e,i){const r=this._cachedRenderContext.context,o=r.gl;if(this._bindFramebuffer(),r.viewport.set([0,0,this._texWidth,this._texHeight]),r.clear({color:t.b4.transparent}),this._cachedRenderContext.useProgram("projectionErrorMeasurement").draw(r,o.TRIANGLES,Ot.disabled,Zt.disabled,Ft.unblended,jt.disabled,((e,t)=>({u_input:e,u_output_expected:t}))(e,i),null,null,"$clipping",this._fullscreenTriangle.vertexBuffer,this._fullscreenTriangle.indexBuffer,this._fullscreenTriangle.segments),this._pbo&&Ut(o)){o.bindBuffer(o.PIXEL_PACK_BUFFER,this._pbo),o.readBuffer(o.COLOR_ATTACHMENT0),o.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);const e=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);o.flush(),this._readbackQueue={frameNumberIssued:this._updateCount,sync:e};}else this._readbackQueue={frameNumberIssued:this._updateCount,sync:null};}_tryReadback(){const e=this._cachedRenderContext.context.gl;if(this._pbo&&this._readbackQueue&&Ut(e)){const i=e.clientWaitSync(this._readbackQueue.sync,0,0);if(i===e.WAIT_FAILED)return t.w("WebGL2 clientWaitSync failed."),this._readbackQueue=null,void(this._lastReadbackFrame=this._updateCount);if(i===e.TIMEOUT_EXPIRED)return;e.bindBuffer(e.PIXEL_PACK_BUFFER,this._pbo),e.getBufferSubData(e.PIXEL_PACK_BUFFER,0,this._resultBuffer,0,4),e.bindBuffer(e.PIXEL_PACK_BUFFER,null);}else this._bindFramebuffer(),e.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,this._resultBuffer);this._readbackQueue=null,this._measuredError=Vt._parseRGBA8float(this._resultBuffer),this._lastReadbackFrame=this._updateCount;}static _parseRGBA8float(e){let t=0;return t+=e[0]/256,t+=e[1]/65536,t+=e[2]/16777216,e[3]<127&&(t=-t),t/128}}const qt=t.X/128;function Ht(e,i){const r=undefined!==e.granularity?Math.max(e.granularity,1):1,o=r+(e.generateBorders?2:0),s=r+(e.extendToNorthPole||e.generateBorders?1:0)+(e.extendToSouthPole||e.generateBorders?1:0),a=o+1,n=s+1,l=e.generateBorders?-1:0,c=e.generateBorders||e.extendToNorthPole?-1:0,h=r+(e.generateBorders?1:0),u=r+(e.generateBorders||e.extendToSouthPole?1:0),d=a*n,_=o*s*6,p=a*n>65536;if(p&&"16bit"===i)throw new Error("Granularity is too large and meshes would not fit inside 16 bit vertex indices.");const m=p||"32bit"===i,f=new Int16Array(2*d);let g=0;for(let i=c;i<=u;i++)for(let o=l;o<=h;o++){let s=o/r*t.X;-1===o&&(s=-qt),o===r+1&&(s=t.X+qt);let a=i/r*t.X;-1===i&&(a=e.extendToNorthPole?t.b6:-qt),i===r+1&&(a=e.extendToSouthPole?t.b7:t.X+qt),f[g++]=s,f[g++]=a;}const v=m?new Uint32Array(_):new Uint16Array(_);let x=0;for(let e=0;e0}get latitudeErrorCorrectionRadians(){return this._verticalPerspectiveProjection.latitudeErrorCorrectionRadians}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return "globe"}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy();}updateGPUdependent(e){this._mercatorProjection.updateGPUdependent(e),this._verticalPerspectiveProjection.updateGPUdependent(e);}getMeshFromTileID(e,t,i,r,o){return this.currentProjection.getMeshFromTileID(e,t,i,r,o)}setProjection(e){this._transitionable.setValue("type",(null==e?undefined:e.type)||"mercator");}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning);}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e);}setErrorQueryLatitudeDegrees(e){this._verticalPerspectiveProjection.setErrorQueryLatitudeDegrees(e),this._mercatorProjection.setErrorQueryLatitudeDegrees(e);}}function Yt(e){const t=ei(e.worldSize,e.center.lat);return 2*Math.PI*t}function Jt(e,i,r,o,s){const a=1/(1<1e-6){const o=e[0]/r,s=Math.acos(e[2]/r),a=(o>0?s:-s)/Math.PI*180;return new t.N(t.aI(a,-180,180),i)}return new t.N(0,i)}function ii(e){return Math.cos(e*Math.PI/180)}function ri(e,i){const r=ii(e),o=ii(i);return t.a8(o/r)}function oi(e,i){const r=e.rotate(i.bearingInRadians),o=i.zoom+ri(i.center.lat,0),s=t.b9(1/ii(i.center.lat),1/ii(Math.min(Math.abs(i.center.lat),60)),t.bc(o,7,3,0,1)),a=360/Yt({worldSize:i.worldSize,center:{lat:i.center.lat}});return new t.N(i.center.lng-r.x*a*s,t.ab(i.center.lat+r.y*a,-t.aF,t.aF))}function si(e){const t=.5*e,i=Math.sin(t),r=Math.cos(t);return Math.log(i+r)-Math.log(r-i)}function ai(e,i,r,o){const s=e.lat+r*o;if(Math.abs(r)>1){const a=(Math.sign(e.lat+r)!==Math.sign(e.lat)?-Math.abs(e.lat):Math.abs(e.lat))*Math.PI/180,n=Math.abs(e.lat+r)*Math.PI/180,l=si(a+o*(n-a)),c=si(a),h=si(n);return new t.N(e.lng+i*((l-c)/(h-c)),s)}return new t.N(e.lng+i*o,s)}class ni{constructor(e){this._cachePrevious=new Map,this._cache=new Map,this._hadAnyChanges=false,this._aabbFactory=e;}recalculateCache(){if(!this._hadAnyChanges)return;const e=this._cachePrevious;this._cachePrevious=this._cache,this._cache=e,this._cache.clear(),this._hadAnyChanges=false;}getTileAABB(e,t,i,r){const o=`${e.z}_${e.x}_${e.y}`,s=this._cache.get(o);if(s)return s;const a=this._cachePrevious.get(o);if(a)return this._cache.set(o,a),a;const n=this._aabbFactory(e,t,i,r);return this._cache.set(o,n),this._hadAnyChanges=true,n}}function li(e,t,i){const r=e-t;return r<0?-r:Math.max(0,r-i)}function ci(e,t,i,r,o){const s=e-i;let a;return a=s<0?Math.min(-s,1+s-o):s>1?Math.min(Math.max(s-o,0),1-s):0,Math.max(a,li(t,r,o))}class hi{constructor(){this._aabbCache=new ni(this._computeTileAABB);}recalculateCache(){this._aabbCache.recalculateCache();}distanceToTile2d(e,t,i,r){const o=1<4}allowWorldCopies(){return false}getTileAABB(e,t,i,r){return this._aabbCache.getTileAABB(e,t,i,r)}_computeTileAABB(e,i,r,o){if(e.z<=0)return new Mt([-1,-1,-1],[1,1,1]);if(1===e.z)return new Mt([0===e.x?-1:0,0===e.y?0:-1,-1],[0===e.x?0:1,0===e.y?1:0,1]);{const i=[Jt(0,0,e.x,e.y,e.z),Jt(t.X,0,e.x,e.y,e.z),Jt(t.X,t.X,e.x,e.y,e.z),Jt(0,t.X,e.x,e.y,e.z)],r=[1,1,1],o=[-1,-1,-1];for(const e of i)for(let t=0;t<3;t++)r[t]=Math.min(r[t],e[t]),o[t]=Math.max(o[t],e[t]);if(0===e.y||e.y===(1<{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._coveringTilesDetailsProvider=new hi;}clone(){const e=new ui;return e.apply(this),e}apply(e,t){this._globeLatitudeErrorCorrectionRadians=t||0,this._helper.apply(e);}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._globeViewProjMatrixNoCorrection}get inverseProjectionMatrix(){return this._globeProjMatrixInverted}get cameraPosition(){const e=t.bf();return e[0]=this._cameraPosition[0],e[1]=this._cameraPosition[1],e[2]=this._cameraPosition[2],e}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}getProjectionData(e){const{overscaledTileID:t,applyGlobeMatrix:i}=e,r=this._helper.getMercatorTileCoordinates(t);return {mainMatrix:this._globeViewProjMatrix32f,tileMercatorCoords:r,clippingPlane:this._cachedClippingPlane,projectionTransition:i?1:0,fallbackMatrix:this._globeViewProjMatrix32f}}_computeClippingPlane(e){const i=this.pitchInRadians,r=this.cameraToCenterDistance/e,o=Math.sin(i)*r,s=Math.cos(i)*r+1,a=1/Math.sqrt(o*o+s*s)*1;let n=-o,l=s;const c=Math.sqrt(n*n+l*l);n/=c,l/=c;const h=[0,n,l];return t.bg(h,h,[0,0,0],-this.bearingInRadians),t.bh(h,h,[0,0,0],-1*this.center.lat*Math.PI/180),t.bi(h,h,[0,0,0],this.center.lng*Math.PI/180),t.aL(h,h,.25),[...h,.25*-a]}isLocationOccluded(e){return !this.isSurfacePointVisible(Qt(e))}transformLightDirection(e){const i=this._helper._center.lng*Math.PI/180,r=this._helper._center.lat*Math.PI/180,o=Math.cos(r),s=[Math.sin(i)*o,Math.sin(r),Math.cos(i)*o],a=[s[2],0,-s[0]],n=[0,0,0];t.aR(n,a,s),t.aQ(a,a),t.aQ(n,n);const l=[0,0,0];return t.aQ(l,[a[0]*e[0]+n[0]*e[1]+s[0]*e[2],a[1]*e[0]+n[1]*e[1]+s[1]*e[2],a[2]*e[0]+n[2]*e[1]+s[2]*e[2]]),l}getPixelScale(){return 1/Math.cos(this._helper._center.lat*Math.PI/180)}getCircleRadiusCorrection(){return Math.cos(this._helper._center.lat*Math.PI/180)}getPitchedTextCorrection(e,i,r){const o=function(e,i,r){const o=1/(1<s&&(s=i),rn&&(n=r);}const h=[c.lng+a,c.lat+l,c.lng+s,c.lat+n];return this.isSurfacePointOnScreen([0,1,0])&&(h[3]=90,h[0]=-180,h[2]=180),this.isSurfacePointOnScreen([0,-1,0])&&(h[1]=-90,h[0]=-180,h[2]=180),new V(h)}getConstrained(e,i){const r=t.ab(e.lat,-t.aF,t.aF),o=t.ab(+i,this.minZoom+ri(0,r),this.maxZoom);return {center:new t.N(e.lng,r),zoom:o}}calculateCenterFromCameraLngLatAlt(e,t,i,r){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,r)}setLocationAtPoint(e,i){const r=Qt(this.unprojectScreenPoint(i)),o=Qt(e),s=t.bf();t.bl(s);const a=t.bf();t.bi(a,r,s,-this.center.lng*Math.PI/180),t.bh(a,a,s,this.center.lat*Math.PI/180);const n=o[0]*o[0]+o[2]*o[2],l=a[0]*a[0];if(n=-g&&p<=g,x=f>=-g&&f<=g;let b,y;if(v&&x){const e=this.center.lng*Math.PI/180,i=this.center.lat*Math.PI/180;t.bp(u,e)+t.bp(p,i)=0}isSurfacePointOnScreen(e){if(!this.isSurfacePointVisible(e))return false;const i=t.be();return t.al(i,[...e,1],this._globeViewProjMatrixNoCorrection),i[0]/=i[3],i[1]/=i[3],i[2]/=i[3],i[0]>-1&&i[0]<1&&i[1]>-1&&i[1]<1&&i[2]>-1&&i[2]<1}rayPlanetIntersection(e,i){const r=t.aS(e,i),o=t.bf(),s=t.bf();t.aL(s,i,r),t.aP(o,e,s);const a=1-t.aS(o,o);if(a<0)return null;const n=t.aS(e,e)-1,l=-r+(r<0?1:-1)*Math.sqrt(a),c=n/l,h=l;return {tMin:Math.min(c,h),tMax:Math.max(c,h)}}unprojectScreenPoint(e){const i=this._cameraPosition,r=this.getRayDirectionFromPixel(e),o=this.rayPlanetIntersection(i,r);if(o){const e=t.bf();t.aM(e,i,[r[0]*o.tMin,r[1]*o.tMin,r[2]*o.tMin]);const s=t.bf();return t.aQ(s,e),ti(s)}const s=this._cachedClippingPlane[0]*r[0]+this._cachedClippingPlane[1]*r[1]+this._cachedClippingPlane[2]*r[2],a=-t.bn(this._cachedClippingPlane,i)/s,n=t.bf();if(a>0)t.aM(n,i,[r[0]*a,r[1]*a,r[2]*a]);else {const e=t.bf();t.aM(e,i,[2*r[0],2*r[1],2*r[2]]);const o=t.bn(this._cachedClippingPlane,e);t.aP(n,e,[this._cachedClippingPlane[0]*o,this._cachedClippingPlane[1]*o,this._cachedClippingPlane[2]*o]);}const l=t.bf();return t.aQ(l,n),ti(l)}getMatrixForModel(e,i){const r=t.N.convert(e),o=1/t.bo,s=t.a_();return t.bj(s,s,r.lng/180*Math.PI),t.aY(s,s,-r.lat/180*Math.PI),t.J(s,s,[0,0,1+i/t.bo]),t.aY(s,s,.5*Math.PI),t.K(s,s,[o,o,o]),s}getProjectionDataForCustomLayer(e=true){const i=this.getProjectionData({overscaledTileID:new t.S(0,0,0,0,0),applyGlobeMatrix:e});return i.tileMercatorCoords=[0,0,1,1],i}getFastPathSimpleProjectionMatrix(e){}}class di{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(e){this._helper.setMinZoom(e);}setMaxZoom(e){this._helper.setMaxZoom(e);}setMinPitch(e){this._helper.setMinPitch(e);}setMaxPitch(e){this._helper.setMaxPitch(e);}setRenderWorldCopies(e){this._helper.setRenderWorldCopies(e);}setBearing(e){this._helper.setBearing(e);}setPitch(e){this._helper.setPitch(e);}setRoll(e){this._helper.setRoll(e);}setFov(e){this._helper.setFov(e);}setZoom(e){this._helper.setZoom(e);}setCenter(e){this._helper.setCenter(e);}setElevation(e){this._helper.setElevation(e);}setMinElevationForCurrentTile(e){this._helper.setMinElevationForCurrentTile(e);}setPadding(e){this._helper.setPadding(e);}interpolatePadding(e,t,i){return this._helper.interpolatePadding(e,t,i)}isPaddingEqual(e){return this._helper.isPaddingEqual(e)}resize(e,t,i=true){this._helper.resize(e,t,i);}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(e){this._helper.setMaxBounds(e);}overrideNearFarZ(e,t){this._helper.overrideNearFarZ(e,t);}clearNearFarZOverride(){this._helper.clearNearFarZOverride();}getCameraQueryGeometry(e){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),e)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}get isGlobeRendering(){return this._globeness>0}setTransitionState(e,t){this._globeness=e,this._globeLatitudeErrorCorrectionRadians=t,this._calcMatrices(),this._verticalPerspectiveTransform.getCoveringTilesDetailsProvider().recalculateCache(),this._mercatorTransform.getCoveringTilesDetailsProvider().recalculateCache();}get currentTransform(){return this.isGlobeRendering?this._verticalPerspectiveTransform:this._mercatorTransform}constructor(){this._globeLatitudeErrorCorrectionRadians=0,this._globeness=1,this._helper=new Et({calcMatrices:()=>{this._calcMatrices();},getConstrained:(e,t)=>this.getConstrained(e,t)}),this._globeness=1,this._mercatorTransform=new Dt,this._verticalPerspectiveTransform=new ui;}clone(){const e=new di;return e._globeness=this._globeness,e._globeLatitudeErrorCorrectionRadians=this._globeLatitudeErrorCorrectionRadians,e.apply(this),e}apply(e){this._helper.apply(e),this._mercatorTransform.apply(this),this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians);}get projectionMatrix(){return this.currentTransform.projectionMatrix}get modelViewProjectionMatrix(){return this.currentTransform.modelViewProjectionMatrix}get inverseProjectionMatrix(){return this.currentTransform.inverseProjectionMatrix}get cameraPosition(){return this.currentTransform.cameraPosition}getProjectionData(e){const t=this._mercatorTransform.getProjectionData(e),i=this._verticalPerspectiveTransform.getProjectionData(e);return {mainMatrix:this.isGlobeRendering?i.mainMatrix:t.mainMatrix,clippingPlane:i.clippingPlane,tileMercatorCoords:i.tileMercatorCoords,projectionTransition:e.applyGlobeMatrix?this._globeness:0,fallbackMatrix:t.fallbackMatrix}}isLocationOccluded(e){return this.currentTransform.isLocationOccluded(e)}transformLightDirection(e){return this.currentTransform.transformLightDirection(e)}getPixelScale(){return t.b9(this._mercatorTransform.getPixelScale(),this._verticalPerspectiveTransform.getPixelScale(),this._globeness)}getCircleRadiusCorrection(){return t.b9(this._mercatorTransform.getCircleRadiusCorrection(),this._verticalPerspectiveTransform.getCircleRadiusCorrection(),this._globeness)}getPitchedTextCorrection(e,i,r){const o=this._mercatorTransform.getPitchedTextCorrection(e,i,r),s=this._verticalPerspectiveTransform.getPitchedTextCorrection(e,i,r);return t.b9(o,s,this._globeness)}projectTileCoordinates(e,t,i,r){return this.currentTransform.projectTileCoordinates(e,t,i,r)}_calcMatrices(){this._helper._width&&this._helper._height&&(this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians),this._helper._nearZ=this._verticalPerspectiveTransform.nearZ,this._helper._farZ=this._verticalPerspectiveTransform.farZ,this._mercatorTransform.apply(this,true,this.isGlobeRendering),this._helper._nearZ=this._mercatorTransform.nearZ,this._helper._farZ=this._mercatorTransform.farZ);}calculateFogMatrix(e){return this.currentTransform.calculateFogMatrix(e)}getVisibleUnwrappedCoordinates(e){return this.currentTransform.getVisibleUnwrappedCoordinates(e)}getCameraFrustum(){return this.currentTransform.getCameraFrustum()}getClippingPlane(){return this.currentTransform.getClippingPlane()}getCoveringTilesDetailsProvider(){return this.currentTransform.getCoveringTilesDetailsProvider()}recalculateZoomAndCenter(e){this._mercatorTransform.recalculateZoomAndCenter(e),this._verticalPerspectiveTransform.recalculateZoomAndCenter(e);}maxPitchScaleFactor(){return this._mercatorTransform.maxPitchScaleFactor()}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){return this._helper.getCameraLngLat()}lngLatToCameraDepth(e,t){return this.currentTransform.lngLatToCameraDepth(e,t)}populateCache(e){this._mercatorTransform.populateCache(e),this._verticalPerspectiveTransform.populateCache(e);}getBounds(){return this.currentTransform.getBounds()}getConstrained(e,t){return this.currentTransform.getConstrained(e,t)}calculateCenterFromCameraLngLatAlt(e,t,i,r){return this._helper.calculateCenterFromCameraLngLatAlt(e,t,i,r)}setLocationAtPoint(e,t){if(!this.isGlobeRendering)return this._mercatorTransform.setLocationAtPoint(e,t),void this.apply(this._mercatorTransform);this._verticalPerspectiveTransform.setLocationAtPoint(e,t),this.apply(this._verticalPerspectiveTransform);}locationToScreenPoint(e,t){return this.currentTransform.locationToScreenPoint(e,t)}screenPointToMercatorCoordinate(e,t){return this.currentTransform.screenPointToMercatorCoordinate(e,t)}screenPointToLocation(e,t){return this.currentTransform.screenPointToLocation(e,t)}isPointOnMapSurface(e,t){return this.currentTransform.isPointOnMapSurface(e,t)}getRayDirectionFromPixel(e){return this._verticalPerspectiveTransform.getRayDirectionFromPixel(e)}getMatrixForModel(e,t){return this.currentTransform.getMatrixForModel(e,t)}getProjectionDataForCustomLayer(e=true){const t=this._mercatorTransform.getProjectionDataForCustomLayer(e);if(!this.isGlobeRendering)return t;const i=this._verticalPerspectiveTransform.getProjectionDataForCustomLayer(e);return i.fallbackMatrix=t.mainMatrix,i}getFastPathSimpleProjectionMatrix(e){return this.currentTransform.getFastPathSimpleProjectionMatrix(e)}}class _i{get useGlobeControls(){return true}handlePanInertia(e,i){const r=oi(e,i);return Math.abs(r.lng-i.center.lng)>180&&(r.lng=i.center.lng+179.5*Math.sign(r.lng-i.center.lng)),{easingCenter:r,easingOffset:new t.P(0,0)}}handleMapControlsRollPitchBearingZoom(e,i){const r=e.around,o=i.screenPointToLocation(r);e.bearingDelta&&i.setBearing(i.bearing+e.bearingDelta),e.pitchDelta&&i.setPitch(i.pitch+e.pitchDelta),e.rollDelta&&i.setRoll(i.roll+e.rollDelta);const s=i.zoom;e.zoomDelta&&i.setZoom(i.zoom+e.zoomDelta);const a=i.zoom-s;if(0===a)return;const n=t.bk(i.center.lng,o.lng),l=n/(Math.abs(n/180)+1),c=t.bk(i.center.lat,o.lat),h=i.getRayDirectionFromPixel(r),u=i.cameraPosition,d=-1*t.aS(u,h),_=t.bf();t.aM(_,u,[h[0]*d,h[1]*d,h[2]*d]);const p=t.bq(_)-1,m=Math.exp(.5*-Math.max(p-.3,0)),f=ei(i.worldSize,i.center.lat)/Math.min(i.width,i.height),g=t.bc(f,.9,.5,1,.25),v=(1-t.aG(-a))*Math.min(m,g),x=i.center.lat,b=i.zoom,y=new t.N(i.center.lng+l*v,t.ab(i.center.lat+c*v,-t.aF,t.aF));i.setLocationAtPoint(o,r);const w=i.center,T=t.bc(Math.abs(n),45,85,0,1),P=t.bc(f,.75,.35,0,1),C=Math.pow(Math.max(T,P),.25),I=t.bk(w.lng,y.lng),E=t.bk(w.lat,y.lat);i.setCenter(new t.N(w.lng+I*C,w.lat+E*C).wrap()),i.setZoom(b+ri(x,i.center.lat));}handleMapControlsPan(e,t,i){if(!e.panDelta)return;const r=t.center.lat,o=t.zoom;t.setCenter(oi(e.panDelta,t).wrap()),t.setZoom(o+ri(r,t.center.lat));}cameraForBoxAndBearing(e,i,r,o,s){const a=Lt(e,i,r,o,s),n=i.left/s.width*2-1,l=(s.width-i.right)/s.width*2-1,c=i.top/s.height*-2+1,h=(s.height-i.bottom)/s.height*-2+1,u=t.bk(r.getWest(),r.getEast())<0,d=u?r.getEast():r.getWest(),_=u?r.getWest():r.getEast(),p=Math.max(r.getNorth(),r.getSouth()),m=Math.min(r.getNorth(),r.getSouth()),f=d+.5*t.bk(d,_),g=p+.5*t.bk(p,m),v=s.clone();v.setCenter(a.center),v.setBearing(a.bearing),v.setPitch(0),v.setRoll(0),v.setZoom(a.zoom);const x=v.modelViewProjectionMatrix,b=[Qt(r.getNorthWest()),Qt(r.getNorthEast()),Qt(r.getSouthWest()),Qt(r.getSouthEast()),Qt(new t.N(_,g)),Qt(new t.N(d,g)),Qt(new t.N(f,p)),Qt(new t.N(f,m))],y=Qt(a.center);let w=Number.POSITIVE_INFINITY;for(const e of b)n<0&&(w=_i.getLesserNonNegativeNonNull(w,_i.solveVectorScale(e,y,x,"x",n))),l>0&&(w=_i.getLesserNonNegativeNonNull(w,_i.solveVectorScale(e,y,x,"x",l))),c>0&&(w=_i.getLesserNonNegativeNonNull(w,_i.solveVectorScale(e,y,x,"y",c))),h<0&&(w=_i.getLesserNonNegativeNonNull(w,_i.solveVectorScale(e,y,x,"y",h)));if(Number.isFinite(w)&&0!==w)return a.zoom=v.zoom+t.a8(w),a;zt();}handleJumpToCenterZoom(e,i){const r=e.center.lat,o=e.getConstrained(i.center?t.N.convert(i.center):e.center,e.zoom).center;e.setCenter(o.wrap());const s=undefined!==i.zoom?+i.zoom:e.zoom+ri(r,o.lat);e.zoom!==s&&e.setZoom(s);}handleEaseTo(e,i){const r=e.zoom,o=e.center,s=e.padding,a={roll:e.roll,pitch:e.pitch,bearing:e.bearing},n={roll:undefined===i.roll?e.roll:i.roll,pitch:undefined===i.pitch?e.pitch:i.pitch,bearing:undefined===i.bearing?e.bearing:i.bearing},l=undefined!==i.zoom,c=!e.isPaddingEqual(i.padding);let h=false;const u=i.center?t.N.convert(i.center):o,d=e.getConstrained(u,r).center;Ct(e,d);const _=e.clone();_.setCenter(d),_.setZoom(l?+i.zoom:r+ri(o.lat,u.lat)),_.setBearing(i.bearing);const p=new t.P(t.ab(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ab(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));_.setLocationAtPoint(d,p);const m=(i.offset&&i.offsetAsPoint.mag())>0?_.center:d,f=l?+i.zoom:r+ri(o.lat,m.lat),g=r+ri(o.lat,0),v=f+ri(m.lat,0),x=t.bk(o.lng,m.lng),b=t.bk(o.lat,m.lat),y=t.aG(v-g);return h=f!==r,{easeFunc:r=>{if(t.b3(a,n)||At({startEulerAngles:a,endEulerAngles:n,tr:e,k:r,useSlerp:a.roll!=n.roll}),c&&e.interpolatePadding(s,i.padding,r),i.around)t.w("Easing around a point is not supported under globe projection."),e.setLocationAtPoint(i.around,i.aroundPoint);else {const t=v>g?Math.min(2,y):Math.max(.5,y),i=Math.pow(t,1-r),s=ai(o,x,b,r*i);e.setCenter(s.wrap());}if(h){const i=t.y.number(g,v,r)+ri(0,e.center.lat);e.setZoom(i);}},isZooming:h,elevationCenter:m}}handleFlyTo(e,i){const r=undefined!==i.zoom,o=e.center,s=e.zoom,a=!e.isPaddingEqual(i.padding),n=e.getConstrained(t.N.convert(i.center||i.locationAtOffset),s).center,l=r?+i.zoom:e.zoom+ri(e.center.lat,n.lat),c=e.clone();c.setCenter(n),a&&c.setPadding(i.padding),c.setZoom(l),c.setBearing(i.bearing);const h=new t.P(t.ab(e.centerPoint.x+i.offsetAsPoint.x,0,e.width),t.ab(e.centerPoint.y+i.offsetAsPoint.y,0,e.height));c.setLocationAtPoint(n,h);const u=c.center;Ct(e,u);const d=function(e,i,r){const o=Qt(i),s=Qt(r),a=t.aS(o,s),n=Math.acos(a),l=Yt(e);return n/(2*Math.PI)*l}(e,o,u),_=s+ri(o.lat,0),p=l+ri(u.lat,0),m=t.aG(p-_);let f;if("number"==typeof i.minZoom){const r=+i.minZoom+ri(u.lat,0),o=Math.min(r,_,p)+ri(0,u.lat),s=e.getConstrained(u,o).zoom+ri(u.lat,0);f=t.aG(s-_);}const g=t.bk(o.lng,u.lng),v=t.bk(o.lat,u.lat);return {easeFunc:(i,r,s,a)=>{const n=ai(o,g,v,s),c=1===i?u:n;e.setCenter(c.wrap());const h=_+t.a8(r);e.setZoom(1===i?l:h+ri(0,c.lat));},scaleOfZoom:m,targetCenter:u,scaleOfMinZoom:f,pixelPathLength:d}}static solveVectorScale(e,t,i,r,o){const s="x"===r?[i[0],i[4],i[8],i[12]]:[i[1],i[5],i[9],i[13]],a=[i[3],i[7],i[11],i[15]],n=e[0]*s[0]+e[1]*s[1]+e[2]*s[2],l=e[0]*a[0]+e[1]*a[1]+e[2]*a[2],c=t[0]*s[0]+t[1]*s[1]+t[2]*s[2],h=t[0]*a[0]+t[1]*a[1]+t[2]*a[2];return c+o*l===n+o*h||a[3]*(n-c)+s[3]*(h-l)+n*h==c*l?null:(c+s[3]-o*h-o*a[3])/(c-n-o*h+o*l)}static getLesserNonNegativeNonNull(e,t){return null!==t&&t>=0&&tt.t(e,i&&i.filter((e=>"source.canvas"!==e.identifier))),fi=t.br();class gi extends t.E{constructor(e,i={}){super(),this._rtlPluginLoaded=()=>{for(const e in this.sourceCaches){const t=this.sourceCaches[e].getSource().type;"vector"!==t&&"geojson"!==t||this.sourceCaches[e].reload();}},this.map=e,this.dispatcher=new B(F(),e._getMapId()),this.dispatcher.registerMessageHandler("GG",((e,t)=>this.getGlyphs(e,t))),this.dispatcher.registerMessageHandler("GI",((e,t)=>this.getImages(e,t))),this.imageManager=new b,this.imageManager.setEventedParent(this),this.glyphManager=new P(e._requestManager,i.localIdeographFontFamily),this.lineAtlas=new R(256,512),this.crossTileSymbolIndex=new ht,this._spritesImagesIds={},this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new t.bs,this._loaded=false,this._availableImages=[],this._resetUpdates(),this.dispatcher.broadcast("SR",t.bt()),oe().on(te,this._rtlPluginLoaded),this.on("data",(e=>{if("source"!==e.dataType||"metadata"!==e.sourceDataType)return;const t=this.sourceCaches[e.sourceId];if(!t)return;const i=t.getSource();if(i&&i.vectorLayerIds)for(const e in this._layers){const t=this._layers[e];t.source===i.id&&this._validateLayer(t);}}));}loadURL(e,i={},r){this.fire(new t.k("dataloading",{dataType:"style"})),i.validate="boolean"!=typeof i.validate||i.validate;const o=this.map._requestManager.transformRequest(e,"Style");this._loadStyleRequest=new AbortController;const s=this._loadStyleRequest;t.h(o,this._loadStyleRequest).then((e=>{this._loadStyleRequest=null,this._load(e.data,i,r);})).catch((e=>{this._loadStyleRequest=null,e&&!s.signal.aborted&&this.fire(new t.j(e));}));}loadJSON(e,i={},r){this.fire(new t.k("dataloading",{dataType:"style"})),this._frameRequest=new AbortController,a.frameAsync(this._frameRequest).then((()=>{this._frameRequest=null,i.validate=false!==i.validate,this._load(e,i,r);})).catch((()=>{}));}loadEmpty(){this.fire(new t.k("dataloading",{dataType:"style"})),this._load(fi,{validate:false});}_load(e,i,r){var o,s;const a=i.transformStyle?i.transformStyle(r,e):e;if(!i.validate||!mi(this,t.u(a))){this._loaded=true,this.stylesheet=a;for(const e in a.sources)this.addSource(e,a.sources[e],{validate:false});a.sprite?this._loadSprite(a.sprite):this.imageManager.setLoaded(true),this.glyphManager.setURL(a.glyphs),this._createLayers(),this.light=new E(this.stylesheet.light),this._setProjectionInternal((null===(o=this.stylesheet.projection)||undefined===o?undefined:o.type)||"mercator"),this.sky=new S(this.stylesheet.sky),this.map.setTerrain(null!==(s=this.stylesheet.terrain)&&undefined!==s?s:null),this.fire(new t.k("data",{dataType:"style"})),this.fire(new t.k("style.load"));}}_createLayers(){const e=t.bu(this.stylesheet.layers);this.dispatcher.broadcast("SL",e),this._order=e.map((e=>e.id)),this._layers={},this._serializedLayers=null;for(const i of e){const e=t.bv(i);e.setEventedParent(this,{layer:{id:i.id}}),this._layers[i.id]=e;}}_loadSprite(e,i=false,r=undefined){let o;this.imageManager.setLoaded(false),this._spriteRequest=new AbortController,function(e,i,r,o){return t._(this,undefined,undefined,(function*(){const s=f(e),n=r>1?"@2x":"",l={},c={};for(const{id:e,url:r}of s){const s=i.transformRequest(g(r,n,".json"),"SpriteJSON");l[e]=t.h(s,o);const a=i.transformRequest(g(r,n,".png"),"SpriteImage");c[e]=p.getImage(a,o);}return yield Promise.all([...Object.values(l),...Object.values(c)]),function(e,i){return t._(this,undefined,undefined,(function*(){const t={};for(const r in e){t[r]={};const o=a.getImageCanvasContext((yield i[r]).data),s=(yield e[r]).data;for(const e in s){const{width:i,height:a,x:n,y:l,sdf:c,pixelRatio:h,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m}=s[e];t[r][e]={data:null,pixelRatio:h,sdf:c,stretchX:u,stretchY:d,content:_,textFitWidth:p,textFitHeight:m,spriteData:{width:i,height:a,x:n,y:l,context:o}};}}return t}))}(l,c)}))}(e,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((e=>{if(this._spriteRequest=null,e)for(const t in e){this._spritesImagesIds[t]=[];const r=this._spritesImagesIds[t]?this._spritesImagesIds[t].filter((t=>!(t in e))):[];for(const e of r)this.imageManager.removeImage(e),this._changedImages[e]=true;for(const r in e[t]){const o="default"===t?r:`${t}:${r}`;this._spritesImagesIds[t].push(o),o in this.imageManager.images?this.imageManager.updateImage(o,e[t][r],false):this.imageManager.addImage(o,e[t][r]),i&&(this._changedImages[o]=true);}}})).catch((e=>{this._spriteRequest=null,o=e,this.fire(new t.j(o));})).finally((()=>{this.imageManager.setLoaded(true),this._availableImages=this.imageManager.listImages(),i&&(this._changed=true),this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.k("data",{dataType:"style"})),r&&r(o);}));}_unloadSprite(){for(const e of Object.values(this._spritesImagesIds).flat())this.imageManager.removeImage(e),this._changedImages[e]=true;this._spritesImagesIds={},this._availableImages=this.imageManager.listImages(),this._changed=true,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.k("data",{dataType:"style"}));}_validateLayer(e){const i=this.sourceCaches[e.source];if(!i)return;const r=e.sourceLayer;if(!r)return;const o=i.getSource();("geojson"===o.type||o.vectorLayerIds&&-1===o.vectorLayerIds.indexOf(r))&&this.fire(new t.j(new Error(`Source layer "${r}" does not exist on source "${o.id}" as specified by style layer "${e.id}".`)));}loaded(){if(!this._loaded)return false;if(Object.keys(this._updatedSources).length)return false;for(const e in this.sourceCaches)if(!this.sourceCaches[e].loaded())return false;return !!this.imageManager.isLoaded()}_serializeByIds(e,i=false){const r=this._serializedAllLayers();if(!e||0===e.length)return Object.values(i?t.bw(r):r);const o=[];for(const s of e)if(r[s]){const e=i?t.bw(r[s]):r[s];o.push(e);}return o}_serializedAllLayers(){let e=this._serializedLayers;if(e)return e;e=this._serializedLayers={};const t=Object.keys(this._layers);for(const i of t){const t=this._layers[i];"custom"!==t.type&&(e[i]=t.serialize());}return e}hasTransitions(){var e,t,i;if(null===(e=this.light)||undefined===e?undefined:e.hasTransition())return true;if(null===(t=this.sky)||undefined===t?undefined:t.hasTransition())return true;if(null===(i=this.projection)||undefined===i?undefined:i.hasTransition())return true;for(const e in this.sourceCaches)if(this.sourceCaches[e].hasTransition())return true;for(const e in this._layers)if(this._layers[e].hasTransition())return true;return false}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading.")}update(e){if(!this._loaded)return;const i=this._changed;if(i){const t=Object.keys(this._updatedLayers),i=Object.keys(this._removedLayers);(t.length||i.length)&&this._updateWorkerLayers(t,i);for(const e in this._updatedSources){const t=this._updatedSources[e];if("reload"===t)this._reloadSource(e);else {if("clear"!==t)throw new Error(`Invalid action ${t}`);this._clearSource(e);}}this._updateTilesForChangedImages(),this._updateTilesForChangedGlyphs();for(const t in this._updatedPaintProps)this._layers[t].updateTransitions(e);this.light.updateTransitions(e),this.sky.updateTransitions(e),this._resetUpdates();}const r={};for(const e in this.sourceCaches){const t=this.sourceCaches[e];r[e]=t.used,t.used=false;}for(const t of this._order){const i=this._layers[t];i.recalculate(e,this._availableImages),!i.isHidden(e.zoom)&&i.source&&(this.sourceCaches[i.source].used=true);}for(const e in r){const i=this.sourceCaches[e];!!r[e]!=!!i.used&&i.fire(new t.k("data",{sourceDataType:"visibility",dataType:"source",sourceId:e}));}this.light.recalculate(e),this.sky.recalculate(e),this.projection.recalculate(e),this.z=e.zoom,i&&this.fire(new t.k("data",{dataType:"style"}));}_updateTilesForChangedImages(){const e=Object.keys(this._changedImages);if(e.length){for(const t in this.sourceCaches)this.sourceCaches[t].reloadTilesForDependencies(["icons","patterns"],e);this._changedImages={};}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const e in this.sourceCaches)this.sourceCaches[e].reloadTilesForDependencies(["glyphs"],[""]);this._glyphsDidChange=false;}}_updateWorkerLayers(e,t){this.dispatcher.broadcast("UL",{layers:this._serializeByIds(e,false),removedIds:t});}_resetUpdates(){this._changed=false,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={},this._glyphsDidChange=false;}setState(e,i={}){var r;this._checkLoaded();const o=this.serialize();if(e=i.transformStyle?i.transformStyle(o,e):e,(null===(r=i.validate)||undefined===r||r)&&mi(this,t.u(e)))return false;(e=t.bw(e)).layers=t.bu(e.layers);const s=t.bx(o,e),a=this._getOperationsToPerform(s);if(a.unimplemented.length>0)throw new Error(`Unimplemented: ${a.unimplemented.join(", ")}.`);if(0===a.operations.length)return false;for(const e of a.operations)e();return this.stylesheet=e,this._serializedLayers=null,true}_getOperationsToPerform(e){const t=[],i=[];for(const r of e)switch(r.command){case"setCenter":case"setZoom":case"setBearing":case"setPitch":case"setRoll":continue;case"addLayer":t.push((()=>this.addLayer.apply(this,r.args)));break;case"removeLayer":t.push((()=>this.removeLayer.apply(this,r.args)));break;case"setPaintProperty":t.push((()=>this.setPaintProperty.apply(this,r.args)));break;case"setLayoutProperty":t.push((()=>this.setLayoutProperty.apply(this,r.args)));break;case"setFilter":t.push((()=>this.setFilter.apply(this,r.args)));break;case"addSource":t.push((()=>this.addSource.apply(this,r.args)));break;case"removeSource":t.push((()=>this.removeSource.apply(this,r.args)));break;case"setLayerZoomRange":t.push((()=>this.setLayerZoomRange.apply(this,r.args)));break;case"setLight":t.push((()=>this.setLight.apply(this,r.args)));break;case"setGeoJSONSourceData":t.push((()=>this.setGeoJSONSourceData.apply(this,r.args)));break;case"setGlyphs":t.push((()=>this.setGlyphs.apply(this,r.args)));break;case"setSprite":t.push((()=>this.setSprite.apply(this,r.args)));break;case"setTerrain":t.push((()=>this.map.setTerrain.apply(this,r.args)));break;case"setSky":t.push((()=>this.setSky.apply(this,r.args)));break;case"setProjection":this.setProjection.apply(this,r.args);break;case"setTransition":t.push((()=>{}));break;default:i.push(r.command);}return {operations:t,unimplemented:i}}addImage(e,i){if(this.getImage(e))return this.fire(new t.j(new Error(`An image named "${e}" already exists.`)));this.imageManager.addImage(e,i),this._afterImageUpdated(e);}updateImage(e,t){this.imageManager.updateImage(e,t);}getImage(e){return this.imageManager.getImage(e)}removeImage(e){if(!this.getImage(e))return this.fire(new t.j(new Error(`An image named "${e}" does not exist.`)));this.imageManager.removeImage(e),this._afterImageUpdated(e);}_afterImageUpdated(e){this._availableImages=this.imageManager.listImages(),this._changedImages[e]=true,this._changed=true,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.k("data",{dataType:"style"}));}listImages(){return this._checkLoaded(),this.imageManager.listImages()}addSource(e,i,r={}){if(this._checkLoaded(),undefined!==this.sourceCaches[e])throw new Error(`Source "${e}" already exists.`);if(!i.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(i).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(i.type)>=0&&this._validate(t.u.source,`sources.${e}`,i,null,r))return;this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=true);const o=this.sourceCaches[e]=new de(e,i,this.dispatcher);o.style=this,o.setEventedParent(this,(()=>({isSourceLoaded:o.loaded(),source:o.serialize(),sourceId:e}))),o.onAdd(this.map),this._changed=true;}removeSource(e){if(this._checkLoaded(),undefined===this.sourceCaches[e])throw new Error("There is no source with this ID");for(const i in this._layers)if(this._layers[i].source===e)return this.fire(new t.j(new Error(`Source "${e}" cannot be removed while layer "${i}" is using it.`)));const i=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],i.fire(new t.k("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),i.setEventedParent(null),i.onRemove(this.map),this._changed=true;}setGeoJSONSourceData(e,t){if(this._checkLoaded(),undefined===this.sourceCaches[e])throw new Error(`There is no source with this ID=${e}`);const i=this.sourceCaches[e].getSource();if("geojson"!==i.type)throw new Error(`geojsonSource.type is ${i.type}, which is !== 'geojson`);i.setData(t),this._changed=true;}getSource(e){return this.sourceCaches[e]&&this.sourceCaches[e].getSource()}addLayer(e,i,r={}){this._checkLoaded();const o=e.id;if(this.getLayer(o))return void this.fire(new t.j(new Error(`Layer "${o}" already exists on this map.`)));let s;if("custom"===e.type){if(mi(this,t.by(e)))return;s=t.bv(e);}else {if("source"in e&&"object"==typeof e.source&&(this.addSource(o,e.source),e=t.bw(e),e=t.e(e,{source:o})),this._validate(t.u.layer,`layers.${o}`,e,{arrayIndex:-1},r))return;s=t.bv(e),this._validateLayer(s),s.setEventedParent(this,{layer:{id:o}});}const a=i?this._order.indexOf(i):this._order.length;if(i&&-1===a)this.fire(new t.j(new Error(`Cannot add layer "${o}" before non-existing layer "${i}".`)));else {if(this._order.splice(a,0,o),this._layerOrderChanged=true,this._layers[o]=s,this._removedLayers[o]&&s.source&&"custom"!==s.type){const e=this._removedLayers[o];delete this._removedLayers[o],e.type!==s.type?this._updatedSources[s.source]="clear":(this._updatedSources[s.source]="reload",this.sourceCaches[s.source].pause());}this._updateLayer(s),s.onAdd&&s.onAdd(this.map);}}moveLayer(e,i){if(this._checkLoaded(),this._changed=true,!this._layers[e])return void this.fire(new t.j(new Error(`The layer '${e}' does not exist in the map's style and cannot be moved.`)));if(e===i)return;const r=this._order.indexOf(e);this._order.splice(r,1);const o=i?this._order.indexOf(i):this._order.length;i&&-1===o?this.fire(new t.j(new Error(`Cannot move layer "${e}" before non-existing layer "${i}".`))):(this._order.splice(o,0,e),this._layerOrderChanged=true);}removeLayer(e){this._checkLoaded();const i=this._layers[e];if(!i)return void this.fire(new t.j(new Error(`Cannot remove non-existing layer "${e}".`)));i.setEventedParent(null);const r=this._order.indexOf(e);this._order.splice(r,1),this._layerOrderChanged=true,this._changed=true,this._removedLayers[e]=i,delete this._layers[e],this._serializedLayers&&delete this._serializedLayers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],i.onRemove&&i.onRemove(this.map);}getLayer(e){return this._layers[e]}getLayersOrder(){return [...this._order]}hasLayer(e){return e in this._layers}setLayerZoomRange(e,i,r){this._checkLoaded();const o=this.getLayer(e);o?o.minzoom===i&&o.maxzoom===r||(null!=i&&(o.minzoom=i),null!=r&&(o.maxzoom=r),this._updateLayer(o)):this.fire(new t.j(new Error(`Cannot set the zoom range of non-existing layer "${e}".`)));}setFilter(e,i,r={}){this._checkLoaded();const o=this.getLayer(e);if(o){if(!t.bz(o.filter,i))return null==i?(o.filter=undefined,void this._updateLayer(o)):void(this._validate(t.u.filter,`layers.${o.id}.filter`,i,null,r)||(o.filter=t.bw(i),this._updateLayer(o)))}else this.fire(new t.j(new Error(`Cannot filter non-existing layer "${e}".`)));}getFilter(e){return t.bw(this.getLayer(e).filter)}setLayoutProperty(e,i,r,o={}){this._checkLoaded();const s=this.getLayer(e);s?t.bz(s.getLayoutProperty(i),r)||(s.setLayoutProperty(i,r,o),this._updateLayer(s)):this.fire(new t.j(new Error(`Cannot style non-existing layer "${e}".`)));}getLayoutProperty(e,i){const r=this.getLayer(e);if(r)return r.getLayoutProperty(i);this.fire(new t.j(new Error(`Cannot get style of non-existing layer "${e}".`)));}setPaintProperty(e,i,r,o={}){this._checkLoaded();const s=this.getLayer(e);s?t.bz(s.getPaintProperty(i),r)||(s.setPaintProperty(i,r,o)&&this._updateLayer(s),this._changed=true,this._updatedPaintProps[e]=true,this._serializedLayers=null):this.fire(new t.j(new Error(`Cannot style non-existing layer "${e}".`)));}getPaintProperty(e,t){return this.getLayer(e).getPaintProperty(t)}setFeatureState(e,i){this._checkLoaded();const r=e.source,o=e.sourceLayer,s=this.sourceCaches[r];if(undefined===s)return void this.fire(new t.j(new Error(`The source '${r}' does not exist in the map's style.`)));const a=s.getSource().type;"geojson"===a&&o?this.fire(new t.j(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==a||o?(undefined===e.id&&this.fire(new t.j(new Error("The feature id parameter must be provided."))),s.setFeatureState(o,e.id,i)):this.fire(new t.j(new Error("The sourceLayer parameter must be provided for vector source types.")));}removeFeatureState(e,i){this._checkLoaded();const r=e.source,o=this.sourceCaches[r];if(undefined===o)return void this.fire(new t.j(new Error(`The source '${r}' does not exist in the map's style.`)));const s=o.getSource().type,a="vector"===s?e.sourceLayer:undefined;"vector"!==s||a?i&&"string"!=typeof e.id&&"number"!=typeof e.id?this.fire(new t.j(new Error("A feature id is required to remove its specific state property."))):o.removeFeatureState(a,e.id,i):this.fire(new t.j(new Error("The sourceLayer parameter must be provided for vector source types.")));}getFeatureState(e){this._checkLoaded();const i=e.source,r=e.sourceLayer,o=this.sourceCaches[i];if(undefined!==o)return "vector"!==o.getSource().type||r?(undefined===e.id&&this.fire(new t.j(new Error("The feature id parameter must be provided."))),o.getFeatureState(r,e.id)):void this.fire(new t.j(new Error("The sourceLayer parameter must be provided for vector source types.")));this.fire(new t.j(new Error(`The source '${i}' does not exist in the map's style.`)));}getTransition(){return t.e({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const e=t.bA(this.sourceCaches,(e=>e.serialize())),i=this._serializeByIds(this._order,true),r=this.map.getTerrain()||undefined,o=this.stylesheet;return t.bB({version:o.version,name:o.name,metadata:o.metadata,light:o.light,sky:o.sky,center:o.center,zoom:o.zoom,bearing:o.bearing,pitch:o.pitch,sprite:o.sprite,glyphs:o.glyphs,transition:o.transition,projection:o.projection,sources:e,layers:i,terrain:r},(e=>undefined!==e))}_updateLayer(e){this._updatedLayers[e.id]=true,e.source&&!this._updatedSources[e.source]&&"raster"!==this.sourceCaches[e.source].getSource().type&&(this._updatedSources[e.source]="reload",this.sourceCaches[e.source].pause()),this._serializedLayers=null,this._changed=true;}_flattenAndSortRenderedFeatures(e){const t=e=>"fill-extrusion"===this._layers[e].type,i={},r=[];for(let o=this._order.length-1;o>=0;o--){const s=this._order[o];if(t(s)){i[s]=o;for(const t of e){const e=t[s];if(e)for(const t of e)r.push(t);}}}r.sort(((e,t)=>t.intersectionZ-e.intersectionZ));const o=[];for(let s=this._order.length-1;s>=0;s--){const a=this._order[s];if(t(a))for(let e=r.length-1;e>=0;e--){const t=r[e].feature;if(i[t.layer.id]{const r=i.featureSortOrder;if(r){const i=r.indexOf(e.featureIndex);return r.indexOf(t.featureIndex)-i}return t.featureIndex-e.featureIndex}));for(const e of o)t.push(e);}}return function(e,t,i){for(const r in e)for(const o of e[r])G(o,i[t[r].source]);return e}(n,e,i)}(this._layers,a,this.sourceCaches,e,l,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures(s)}querySourceFeatures(e,i){i&&i.filter&&this._validate(t.u.filter,"querySourceFeatures.filter",i.filter,null,i);const r=this.sourceCaches[e];return r?function(e,t){const i=e.getRenderableIds().map((t=>e.getTileByID(t))),r=[],o={};for(let e=0;ee.getTileByID(t))).sort(((e,t)=>t.tileID.overscaledZ-e.tileID.overscaledZ||(e.tileID.isLessThan(t.tileID)?-1:1)));}const r=this.crossTileSymbolIndex.addLayer(i,l[i.source],e.center.lng);s=s||r;}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((o=o||this._layerOrderChanged||0===i)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent(a.now(),e.zoom))&&(this.pauseablePlacement=new st(e,this.map.terrain,this._order,o,t,i,r,this.placement),this._layerOrderChanged=false),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,l),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(a.now()),n=true),s&&this.pauseablePlacement.placement.setStale()),n||s)for(const e of this._order){const t=this._layers[e];"symbol"===t.type&&this.placement.updateLayerOpacities(t,l[t.source]);}return !this.pauseablePlacement.isDone()||this.placement.hasTransitions(a.now())}_releaseSymbolFadeTiles(){for(const e in this.sourceCaches)this.sourceCaches[e].releaseSymbolFadeTiles();}getImages(e,i){return t._(this,undefined,undefined,(function*(){const e=yield this.imageManager.getImages(i.icons);this._updateTilesForChangedImages();const t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,i.icons),e}))}getGlyphs(e,i){return t._(this,undefined,undefined,(function*(){const e=yield this.glyphManager.getGlyphs(i.stacks),t=this.sourceCaches[i.source];return t&&t.setDependencies(i.tileID.key,i.type,[""]),e}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(e,i={}){this._checkLoaded(),e&&this._validate(t.u.glyphs,"glyphs",e,null,i)||(this._glyphsDidChange=true,this.stylesheet.glyphs=e,this.glyphManager.entries={},this.glyphManager.setURL(e));}addSprite(e,i,r={},o){this._checkLoaded();const s=[{id:e,url:i}],a=[...f(this.stylesheet.sprite),...s];this._validate(t.u.sprite,"sprite",a,null,r)||(this.stylesheet.sprite=a,this._loadSprite(s,true,o));}removeSprite(e){this._checkLoaded();const i=f(this.stylesheet.sprite);if(i.find((t=>t.id===e))){if(this._spritesImagesIds[e])for(const t of this._spritesImagesIds[e])this.imageManager.removeImage(t),this._changedImages[t]=true;i.splice(i.findIndex((t=>t.id===e)),1),this.stylesheet.sprite=i.length>0?i:undefined,delete this._spritesImagesIds[e],this._availableImages=this.imageManager.listImages(),this._changed=true,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new t.k("data",{dataType:"style"}));}else this.fire(new t.j(new Error(`Sprite "${e}" doesn't exists on this map.`)));}getSprite(){return f(this.stylesheet.sprite)}setSprite(e,i={},r){this._checkLoaded(),e&&this._validate(t.u.sprite,"sprite",e,null,i)||(this.stylesheet.sprite=e,e?this._loadSprite(e,true,r):(this._unloadSprite(),r&&r(null)));}}var vi=t.aA([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]);class xi{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;}bind(e,t,i,r,o,s,a,n,l){this.context=e;let c=this.boundPaintVertexBuffers.length!==r.length;for(let e=0;!c&&e({u_texture:0,u_ele_delta:e,u_fog_matrix:i,u_fog_color:r?r.properties.get("fog-color"):t.b4.white,u_fog_ground_blend:r?r.properties.get("fog-ground-blend"):1,u_fog_ground_blend_opacity:s?0:r?r.calculateFogBlendOpacity(o):0,u_horizon_color:r?r.properties.get("horizon-color"):t.b4.white,u_horizon_fog_blend:r?r.properties.get("horizon-fog-blend"):1,u_is_globe_mode:s?1:0}),yi={mainMatrix:"u_projection_matrix",tileMercatorCoords:"u_projection_tile_mercator_coords",clippingPlane:"u_projection_clipping_plane",projectionTransition:"u_projection_transition",fallbackMatrix:"u_projection_fallback_matrix"};function wi(e){const t=[];for(let i=0;i({u_depth:new t.bC(e,i.u_depth),u_terrain:new t.bC(e,i.u_terrain),u_terrain_dim:new t.b5(e,i.u_terrain_dim),u_terrain_matrix:new t.bD(e,i.u_terrain_matrix),u_terrain_unpack:new t.bE(e,i.u_terrain_unpack),u_terrain_exaggeration:new t.b5(e,i.u_terrain_exaggeration)}))(e,P),this.projectionUniforms=((e,i)=>({u_projection_matrix:new t.bD(e,i.u_projection_matrix),u_projection_tile_mercator_coords:new t.bE(e,i.u_projection_tile_mercator_coords),u_projection_clipping_plane:new t.bE(e,i.u_projection_clipping_plane),u_projection_transition:new t.b5(e,i.u_projection_transition),u_projection_fallback_matrix:new t.bD(e,i.u_projection_fallback_matrix)}))(e,P),this.binderUniforms=r?r.getUniforms(e,P):[];}draw(e,t,i,r,o,s,a,n,l,c,h,u,d,_,p,m,f,g,v){const x=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.setDepthMode(i),e.setStencilMode(r),e.setColorMode(o),e.setCullFace(s),n){e.activeTexture.set(x.TEXTURE2),x.bindTexture(x.TEXTURE_2D,n.depthTexture),e.activeTexture.set(x.TEXTURE3),x.bindTexture(x.TEXTURE_2D,n.texture);for(const e in this.terrainUniforms)this.terrainUniforms[e].set(n[e]);}if(l)for(const e in l)this.projectionUniforms[yi[e]].set(l[e]);if(a)for(const e in this.fixedUniforms)this.fixedUniforms[e].set(a[e]);m&&m.setUniforms(e,this.binderUniforms,_,{zoom:p});let b=0;switch(t){case x.LINES:b=2;break;case x.TRIANGLES:b=3;break;case x.LINE_STRIP:b=1;}for(const i of d.get()){const r=i.vaos||(i.vaos={});(r[c]||(r[c]=new xi)).bind(e,this,h,m?m.getPaintVertexBuffers():[],u,i.vertexOffset,f,g,v),x.drawElements(t,i.primitiveLength*b,x.UNSIGNED_SHORT,i.primitiveOffset*b*2);}}}function Pi(e,i,r){const o=1/t.at(r,1,i.transform.tileZoom),s=Math.pow(2,r.tileID.overscaledZ),a=r.tileSize*Math.pow(2,i.transform.tileZoom)/s,n=a*(r.tileID.canonical.x+r.tileID.wrap*s),l=a*r.tileID.canonical.y;return {u_image:0,u_texsize:r.imageAtlasTexture.size,u_scale:[o,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[n>>16,l>>16],u_pixel_coord_lower:[65535&n,65535&l]}}const Ci=(e,i,r,o)=>{const s=e.style.light,a=s.properties.get("position"),n=[a.x,a.y,a.z],l=t.bI();"viewport"===s.properties.get("anchor")&&t.bJ(l,e.transform.bearingInRadians),t.bK(n,n,l);const c=e.transform.transformLightDirection(n),h=s.properties.get("color");return {u_lightpos:n,u_lightpos_globe:c,u_lightintensity:s.properties.get("intensity"),u_lightcolor:[h.r,h.g,h.b],u_vertical_gradient:+i,u_opacity:r,u_fill_translate:o}},Ii=(e,i,r,o,s,a,n)=>t.e(Ci(e,i,r,o),Pi(a,e,n),{u_height_factor:-Math.pow(2,s.overscaledZ)/n.tileSize/8}),Ei=(e,i,r,o)=>t.e(Pi(i,e,r),{u_fill_translate:o}),Mi=(e,t)=>({u_world:e,u_fill_translate:t}),Si=(e,i,r,o,s)=>t.e(Ei(e,i,r,s),{u_world:o}),Ri=(e,i,r,o,s)=>{const a=e.transform;let n,l,c=0;if("map"===r.paint.get("circle-pitch-alignment")){const e=t.at(i,1,a.zoom);n=true,l=[e,e],c=e/(t.X*Math.pow(2,i.tileID.overscaledZ))*2*Math.PI*s;}else n=false,l=a.pixelsToGLUnits;return {u_camera_to_center_distance:a.cameraToCenterDistance,u_scale_with_map:+("map"===r.paint.get("circle-pitch-scale")),u_pitch_with_map:+n,u_device_pixel_ratio:e.pixelRatio,u_extrude_scale:l,u_globe_extrude_scale:c,u_translate:o}},Di=e=>({u_pixel_extrude_scale:[1/e.width,1/e.height]}),zi=e=>({u_viewport_size:[e.width,e.height]}),Ai=(e,t=1)=>({u_color:e,u_overlay:0,u_overlay_scale:t}),Li=(e,i,r,o)=>{const s=t.at(e,1,i)/(t.X*Math.pow(2,e.tileID.overscaledZ))*2*Math.PI*o;return {u_extrude_scale:t.at(e,1,i),u_intensity:r,u_globe_extrude_scale:s}},ki=(e,i,r,o)=>{const s=t.H();t.bL(s,0,e.width,e.height,0,0,1);const a=e.context.gl;return {u_matrix:s,u_world:[a.drawingBufferWidth,a.drawingBufferHeight],u_image:r,u_color_ramp:o,u_opacity:i.paint.get("heatmap-opacity")}},Fi=(e,t,i)=>{const r=i.paint.get("hillshade-shadow-color"),o=i.paint.get("hillshade-highlight-color"),s=i.paint.get("hillshade-accent-color");let a=i.paint.get("hillshade-illumination-direction")*(Math.PI/180);return "viewport"===i.paint.get("hillshade-illumination-anchor")&&(a+=e.transform.bearingInRadians),{u_image:0,u_latrange:ji(0,t.tileID),u_light:[i.paint.get("hillshade-exaggeration"),a],u_shadow:r,u_highlight:o,u_accent:s}},Bi=(e,i)=>{const r=i.stride,o=t.H();return t.bL(o,0,t.X,-t.X,0,0,1),t.J(o,o,[0,-t.X,0]),{u_matrix:o,u_image:1,u_dimension:[r,r],u_zoom:e.overscaledZ,u_unpack:i.getUnpackVector()}};function ji(e,i){const r=Math.pow(2,i.canonical.z),o=i.canonical.y;return [new t.Y(0,o/r).toLngLat().lat,new t.Y(0,(o+1)/r).toLngLat().lat]}const Oi=(e,i,r,o)=>{const s=e.transform;return {u_translation:Vi(e,i,r),u_ratio:o/t.at(i,1,s.zoom),u_device_pixel_ratio:e.pixelRatio,u_units_to_pixels:[1/s.pixelsToGLUnits[0],1/s.pixelsToGLUnits[1]]}},Ni=(e,i,r,o,s)=>t.e(Oi(e,i,r,o),{u_image:0,u_image_height:s}),Zi=(e,i,r,o,s)=>{const a=e.transform,n=Ui(i,a);return {u_translation:Vi(e,i,r),u_texsize:i.imageAtlasTexture.size,u_ratio:o/t.at(i,1,a.zoom),u_device_pixel_ratio:e.pixelRatio,u_image:0,u_scale:[n,s.fromScale,s.toScale],u_fade:s.t,u_units_to_pixels:[1/a.pixelsToGLUnits[0],1/a.pixelsToGLUnits[1]]}},Gi=(e,i,r,o,s,a)=>{const n=e.lineAtlas,l=Ui(i,e.transform),c="round"===r.layout.get("line-cap"),h=n.getDash(s.from,c),u=n.getDash(s.to,c),d=h.width*a.fromScale,_=u.width*a.toScale;return t.e(Oi(e,i,r,o),{u_patternscale_a:[l/d,-h.height/2],u_patternscale_b:[l/_,-u.height/2],u_sdfgamma:n.width/(256*Math.min(d,_)*e.pixelRatio)/2,u_image:0,u_tex_y_a:h.y,u_tex_y_b:u.y,u_mix:a.t})};function Ui(e,i){return 1/t.at(e,1,i.tileZoom)}function Vi(e,i,r){return t.au(e.transform,i,r.paint.get("line-translate"),r.paint.get("line-translate-anchor"))}const qi=(e,t,i,r,o)=>{return {u_tl_parent:e,u_scale_parent:t,u_buffer_scale:1,u_fade_t:i.mix,u_opacity:i.opacity*r.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:r.paint.get("raster-brightness-min"),u_brightness_high:r.paint.get("raster-brightness-max"),u_saturation_factor:(a=r.paint.get("raster-saturation"),a>0?1-1/(1.001-a):-a),u_contrast_factor:(s=r.paint.get("raster-contrast"),s>0?1/(1-s):1+s),u_spin_weights:Hi(r.paint.get("raster-hue-rotate")),u_coords_top:[o[0].x,o[0].y,o[1].x,o[1].y],u_coords_bottom:[o[3].x,o[3].y,o[2].x,o[2].y]};var s,a;};function Hi(e){e*=Math.PI/180;const t=Math.sin(e),i=Math.cos(e);return [(2*i+1)/3,(-Math.sqrt(3)*t-i+1)/3,(Math.sqrt(3)*t-i+1)/3]}const Wi=(e,t,i,r,o,s,a,n,l,c,h,u,d)=>{const _=a.transform;return {u_is_size_zoom_constant:+("constant"===e||"source"===e),u_is_size_feature_constant:+("constant"===e||"camera"===e),u_size_t:t?t.uSizeT:0,u_size:t?t.uSize:0,u_camera_to_center_distance:_.cameraToCenterDistance,u_pitch:_.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:_.width/_.height,u_fade_change:a.options.fadeDuration?a.symbolFadeChange:1,u_label_plane_matrix:n,u_coord_matrix:l,u_is_text:+h,u_pitch_with_map:+r,u_is_along_line:o,u_is_variable_anchor:s,u_texsize:u,u_texture:0,u_translation:c,u_pitched_scale:d}},Xi=(e,i,r,o,s,a,n,l,c,h,u,d,_,p)=>{const m=n.transform;return t.e(Wi(e,i,r,o,s,a,n,l,c,h,u,d,p),{u_gamma_scale:o?Math.cos(m.pitch*Math.PI/180)*m.cameraToCenterDistance:1,u_device_pixel_ratio:n.pixelRatio,u_is_halo:1})},$i=(e,i,r,o,s,a,n,l,c,h,u,d,_)=>t.e(Xi(e,i,r,o,s,a,n,l,c,h,true,u,true,_),{u_texsize_icon:d,u_texture_icon:1}),Ki=(e,t)=>({u_opacity:e,u_color:t}),Yi=(e,i,r,o,s)=>t.e(function(e,i,r,o){const s=r.imageManager.getPattern(e.from.toString()),a=r.imageManager.getPattern(e.to.toString()),{width:n,height:l}=r.imageManager.getPixelSize(),c=Math.pow(2,o.tileID.overscaledZ),h=o.tileSize*Math.pow(2,r.transform.tileZoom)/c,u=h*(o.tileID.canonical.x+o.tileID.wrap*c),d=h*o.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:s.tl,u_pattern_br_a:s.br,u_pattern_tl_b:a.tl,u_pattern_br_b:a.br,u_texsize:[n,l],u_mix:i.t,u_pattern_size_a:s.displaySize,u_pattern_size_b:a.displaySize,u_scale_a:i.fromScale,u_scale_b:i.toScale,u_tile_units_to_pixels:1/t.at(o,1,r.transform.tileZoom),u_pixel_coord_upper:[u>>16,d>>16],u_pixel_coord_lower:[65535&u,65535&d]}}(r,s,i,o),{u_opacity:e}),Ji=(e,t)=>{},Qi={fillExtrusion:(e,i)=>({u_lightpos:new t.bG(e,i.u_lightpos),u_lightpos_globe:new t.bG(e,i.u_lightpos_globe),u_lightintensity:new t.b5(e,i.u_lightintensity),u_lightcolor:new t.bG(e,i.u_lightcolor),u_vertical_gradient:new t.b5(e,i.u_vertical_gradient),u_opacity:new t.b5(e,i.u_opacity),u_fill_translate:new t.bH(e,i.u_fill_translate)}),fillExtrusionPattern:(e,i)=>({u_lightpos:new t.bG(e,i.u_lightpos),u_lightpos_globe:new t.bG(e,i.u_lightpos_globe),u_lightintensity:new t.b5(e,i.u_lightintensity),u_lightcolor:new t.bG(e,i.u_lightcolor),u_vertical_gradient:new t.b5(e,i.u_vertical_gradient),u_height_factor:new t.b5(e,i.u_height_factor),u_opacity:new t.b5(e,i.u_opacity),u_fill_translate:new t.bH(e,i.u_fill_translate),u_image:new t.bC(e,i.u_image),u_texsize:new t.bH(e,i.u_texsize),u_pixel_coord_upper:new t.bH(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bH(e,i.u_pixel_coord_lower),u_scale:new t.bG(e,i.u_scale),u_fade:new t.b5(e,i.u_fade)}),fill:(e,i)=>({u_fill_translate:new t.bH(e,i.u_fill_translate)}),fillPattern:(e,i)=>({u_image:new t.bC(e,i.u_image),u_texsize:new t.bH(e,i.u_texsize),u_pixel_coord_upper:new t.bH(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bH(e,i.u_pixel_coord_lower),u_scale:new t.bG(e,i.u_scale),u_fade:new t.b5(e,i.u_fade),u_fill_translate:new t.bH(e,i.u_fill_translate)}),fillOutline:(e,i)=>({u_world:new t.bH(e,i.u_world),u_fill_translate:new t.bH(e,i.u_fill_translate)}),fillOutlinePattern:(e,i)=>({u_world:new t.bH(e,i.u_world),u_image:new t.bC(e,i.u_image),u_texsize:new t.bH(e,i.u_texsize),u_pixel_coord_upper:new t.bH(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bH(e,i.u_pixel_coord_lower),u_scale:new t.bG(e,i.u_scale),u_fade:new t.b5(e,i.u_fade),u_fill_translate:new t.bH(e,i.u_fill_translate)}),circle:(e,i)=>({u_camera_to_center_distance:new t.b5(e,i.u_camera_to_center_distance),u_scale_with_map:new t.bC(e,i.u_scale_with_map),u_pitch_with_map:new t.bC(e,i.u_pitch_with_map),u_extrude_scale:new t.bH(e,i.u_extrude_scale),u_device_pixel_ratio:new t.b5(e,i.u_device_pixel_ratio),u_globe_extrude_scale:new t.b5(e,i.u_globe_extrude_scale),u_translate:new t.bH(e,i.u_translate)}),collisionBox:(e,i)=>({u_pixel_extrude_scale:new t.bH(e,i.u_pixel_extrude_scale)}),collisionCircle:(e,i)=>({u_viewport_size:new t.bH(e,i.u_viewport_size)}),debug:(e,i)=>({u_color:new t.bF(e,i.u_color),u_overlay:new t.bC(e,i.u_overlay),u_overlay_scale:new t.b5(e,i.u_overlay_scale)}),depth:Ji,clippingMask:Ji,heatmap:(e,i)=>({u_extrude_scale:new t.b5(e,i.u_extrude_scale),u_intensity:new t.b5(e,i.u_intensity),u_globe_extrude_scale:new t.b5(e,i.u_globe_extrude_scale)}),heatmapTexture:(e,i)=>({u_matrix:new t.bD(e,i.u_matrix),u_world:new t.bH(e,i.u_world),u_image:new t.bC(e,i.u_image),u_color_ramp:new t.bC(e,i.u_color_ramp),u_opacity:new t.b5(e,i.u_opacity)}),hillshade:(e,i)=>({u_image:new t.bC(e,i.u_image),u_latrange:new t.bH(e,i.u_latrange),u_light:new t.bH(e,i.u_light),u_shadow:new t.bF(e,i.u_shadow),u_highlight:new t.bF(e,i.u_highlight),u_accent:new t.bF(e,i.u_accent)}),hillshadePrepare:(e,i)=>({u_matrix:new t.bD(e,i.u_matrix),u_image:new t.bC(e,i.u_image),u_dimension:new t.bH(e,i.u_dimension),u_zoom:new t.b5(e,i.u_zoom),u_unpack:new t.bE(e,i.u_unpack)}),line:(e,i)=>({u_translation:new t.bH(e,i.u_translation),u_ratio:new t.b5(e,i.u_ratio),u_device_pixel_ratio:new t.b5(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bH(e,i.u_units_to_pixels)}),lineGradient:(e,i)=>({u_translation:new t.bH(e,i.u_translation),u_ratio:new t.b5(e,i.u_ratio),u_device_pixel_ratio:new t.b5(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bH(e,i.u_units_to_pixels),u_image:new t.bC(e,i.u_image),u_image_height:new t.b5(e,i.u_image_height)}),linePattern:(e,i)=>({u_translation:new t.bH(e,i.u_translation),u_texsize:new t.bH(e,i.u_texsize),u_ratio:new t.b5(e,i.u_ratio),u_device_pixel_ratio:new t.b5(e,i.u_device_pixel_ratio),u_image:new t.bC(e,i.u_image),u_units_to_pixels:new t.bH(e,i.u_units_to_pixels),u_scale:new t.bG(e,i.u_scale),u_fade:new t.b5(e,i.u_fade)}),lineSDF:(e,i)=>({u_translation:new t.bH(e,i.u_translation),u_ratio:new t.b5(e,i.u_ratio),u_device_pixel_ratio:new t.b5(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.bH(e,i.u_units_to_pixels),u_patternscale_a:new t.bH(e,i.u_patternscale_a),u_patternscale_b:new t.bH(e,i.u_patternscale_b),u_sdfgamma:new t.b5(e,i.u_sdfgamma),u_image:new t.bC(e,i.u_image),u_tex_y_a:new t.b5(e,i.u_tex_y_a),u_tex_y_b:new t.b5(e,i.u_tex_y_b),u_mix:new t.b5(e,i.u_mix)}),raster:(e,i)=>({u_tl_parent:new t.bH(e,i.u_tl_parent),u_scale_parent:new t.b5(e,i.u_scale_parent),u_buffer_scale:new t.b5(e,i.u_buffer_scale),u_fade_t:new t.b5(e,i.u_fade_t),u_opacity:new t.b5(e,i.u_opacity),u_image0:new t.bC(e,i.u_image0),u_image1:new t.bC(e,i.u_image1),u_brightness_low:new t.b5(e,i.u_brightness_low),u_brightness_high:new t.b5(e,i.u_brightness_high),u_saturation_factor:new t.b5(e,i.u_saturation_factor),u_contrast_factor:new t.b5(e,i.u_contrast_factor),u_spin_weights:new t.bG(e,i.u_spin_weights),u_coords_top:new t.bE(e,i.u_coords_top),u_coords_bottom:new t.bE(e,i.u_coords_bottom)}),symbolIcon:(e,i)=>({u_is_size_zoom_constant:new t.bC(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bC(e,i.u_is_size_feature_constant),u_size_t:new t.b5(e,i.u_size_t),u_size:new t.b5(e,i.u_size),u_camera_to_center_distance:new t.b5(e,i.u_camera_to_center_distance),u_pitch:new t.b5(e,i.u_pitch),u_rotate_symbol:new t.bC(e,i.u_rotate_symbol),u_aspect_ratio:new t.b5(e,i.u_aspect_ratio),u_fade_change:new t.b5(e,i.u_fade_change),u_label_plane_matrix:new t.bD(e,i.u_label_plane_matrix),u_coord_matrix:new t.bD(e,i.u_coord_matrix),u_is_text:new t.bC(e,i.u_is_text),u_pitch_with_map:new t.bC(e,i.u_pitch_with_map),u_is_along_line:new t.bC(e,i.u_is_along_line),u_is_variable_anchor:new t.bC(e,i.u_is_variable_anchor),u_texsize:new t.bH(e,i.u_texsize),u_texture:new t.bC(e,i.u_texture),u_translation:new t.bH(e,i.u_translation),u_pitched_scale:new t.b5(e,i.u_pitched_scale)}),symbolSDF:(e,i)=>({u_is_size_zoom_constant:new t.bC(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bC(e,i.u_is_size_feature_constant),u_size_t:new t.b5(e,i.u_size_t),u_size:new t.b5(e,i.u_size),u_camera_to_center_distance:new t.b5(e,i.u_camera_to_center_distance),u_pitch:new t.b5(e,i.u_pitch),u_rotate_symbol:new t.bC(e,i.u_rotate_symbol),u_aspect_ratio:new t.b5(e,i.u_aspect_ratio),u_fade_change:new t.b5(e,i.u_fade_change),u_label_plane_matrix:new t.bD(e,i.u_label_plane_matrix),u_coord_matrix:new t.bD(e,i.u_coord_matrix),u_is_text:new t.bC(e,i.u_is_text),u_pitch_with_map:new t.bC(e,i.u_pitch_with_map),u_is_along_line:new t.bC(e,i.u_is_along_line),u_is_variable_anchor:new t.bC(e,i.u_is_variable_anchor),u_texsize:new t.bH(e,i.u_texsize),u_texture:new t.bC(e,i.u_texture),u_gamma_scale:new t.b5(e,i.u_gamma_scale),u_device_pixel_ratio:new t.b5(e,i.u_device_pixel_ratio),u_is_halo:new t.bC(e,i.u_is_halo),u_translation:new t.bH(e,i.u_translation),u_pitched_scale:new t.b5(e,i.u_pitched_scale)}),symbolTextAndIcon:(e,i)=>({u_is_size_zoom_constant:new t.bC(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.bC(e,i.u_is_size_feature_constant),u_size_t:new t.b5(e,i.u_size_t),u_size:new t.b5(e,i.u_size),u_camera_to_center_distance:new t.b5(e,i.u_camera_to_center_distance),u_pitch:new t.b5(e,i.u_pitch),u_rotate_symbol:new t.bC(e,i.u_rotate_symbol),u_aspect_ratio:new t.b5(e,i.u_aspect_ratio),u_fade_change:new t.b5(e,i.u_fade_change),u_label_plane_matrix:new t.bD(e,i.u_label_plane_matrix),u_coord_matrix:new t.bD(e,i.u_coord_matrix),u_is_text:new t.bC(e,i.u_is_text),u_pitch_with_map:new t.bC(e,i.u_pitch_with_map),u_is_along_line:new t.bC(e,i.u_is_along_line),u_is_variable_anchor:new t.bC(e,i.u_is_variable_anchor),u_texsize:new t.bH(e,i.u_texsize),u_texsize_icon:new t.bH(e,i.u_texsize_icon),u_texture:new t.bC(e,i.u_texture),u_texture_icon:new t.bC(e,i.u_texture_icon),u_gamma_scale:new t.b5(e,i.u_gamma_scale),u_device_pixel_ratio:new t.b5(e,i.u_device_pixel_ratio),u_is_halo:new t.bC(e,i.u_is_halo),u_translation:new t.bH(e,i.u_translation),u_pitched_scale:new t.b5(e,i.u_pitched_scale)}),background:(e,i)=>({u_opacity:new t.b5(e,i.u_opacity),u_color:new t.bF(e,i.u_color)}),backgroundPattern:(e,i)=>({u_opacity:new t.b5(e,i.u_opacity),u_image:new t.bC(e,i.u_image),u_pattern_tl_a:new t.bH(e,i.u_pattern_tl_a),u_pattern_br_a:new t.bH(e,i.u_pattern_br_a),u_pattern_tl_b:new t.bH(e,i.u_pattern_tl_b),u_pattern_br_b:new t.bH(e,i.u_pattern_br_b),u_texsize:new t.bH(e,i.u_texsize),u_mix:new t.b5(e,i.u_mix),u_pattern_size_a:new t.bH(e,i.u_pattern_size_a),u_pattern_size_b:new t.bH(e,i.u_pattern_size_b),u_scale_a:new t.b5(e,i.u_scale_a),u_scale_b:new t.b5(e,i.u_scale_b),u_pixel_coord_upper:new t.bH(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.bH(e,i.u_pixel_coord_lower),u_tile_units_to_pixels:new t.b5(e,i.u_tile_units_to_pixels)}),terrain:(e,i)=>({u_texture:new t.bC(e,i.u_texture),u_ele_delta:new t.b5(e,i.u_ele_delta),u_fog_matrix:new t.bD(e,i.u_fog_matrix),u_fog_color:new t.bF(e,i.u_fog_color),u_fog_ground_blend:new t.b5(e,i.u_fog_ground_blend),u_fog_ground_blend_opacity:new t.b5(e,i.u_fog_ground_blend_opacity),u_horizon_color:new t.bF(e,i.u_horizon_color),u_horizon_fog_blend:new t.b5(e,i.u_horizon_fog_blend),u_is_globe_mode:new t.b5(e,i.u_is_globe_mode)}),terrainDepth:(e,i)=>({u_ele_delta:new t.b5(e,i.u_ele_delta)}),terrainCoords:(e,i)=>({u_texture:new t.bC(e,i.u_texture),u_terrain_coords_id:new t.b5(e,i.u_terrain_coords_id),u_ele_delta:new t.b5(e,i.u_ele_delta)}),projectionErrorMeasurement:(e,i)=>({u_input:new t.b5(e,i.u_input),u_output_expected:new t.b5(e,i.u_output_expected)}),atmosphere:(e,i)=>({u_sun_pos:new t.bG(e,i.u_sun_pos),u_atmosphere_blend:new t.b5(e,i.u_atmosphere_blend),u_globe_position:new t.bG(e,i.u_globe_position),u_globe_radius:new t.b5(e,i.u_globe_radius),u_inv_proj_matrix:new t.bD(e,i.u_inv_proj_matrix)}),sky:(e,i)=>({u_sky_color:new t.bF(e,i.u_sky_color),u_horizon_color:new t.bF(e,i.u_horizon_color),u_horizon:new t.bH(e,i.u_horizon),u_horizon_normal:new t.bH(e,i.u_horizon_normal),u_sky_horizon_blend:new t.b5(e,i.u_sky_horizon_blend),u_sky_blend:new t.b5(e,i.u_sky_blend)})};class er{constructor(e,t,i){this.context=e;const r=e.gl;this.buffer=r.createBuffer(),this.dynamicDraw=Boolean(i),this.context.unbindVAO(),e.bindElementBuffer.set(this.buffer),r.bufferData(r.ELEMENT_ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?r.DYNAMIC_DRAW:r.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindElementBuffer.set(this.buffer);}updateData(e){const t=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO(),this.bind(),t.bufferSubData(t.ELEMENT_ARRAY_BUFFER,0,e.arrayBuffer);}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer);}}const tr={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class ir{constructor(e,t,i,r){this.length=t.length,this.attributes=i,this.itemSize=t.bytesPerElement,this.dynamicDraw=r,this.context=e;const o=e.gl;this.buffer=o.createBuffer(),e.bindVertexBuffer.set(this.buffer),o.bufferData(o.ARRAY_BUFFER,t.arrayBuffer,this.dynamicDraw?o.DYNAMIC_DRAW:o.STATIC_DRAW),this.dynamicDraw||delete t.arrayBuffer;}bind(){this.context.bindVertexBuffer.set(this.buffer);}updateData(e){if(e.length!==this.length)throw new Error(`Length of new data is ${e.length}, which doesn't match current length of ${this.length}`);const t=this.context.gl;this.bind(),t.bufferSubData(t.ARRAY_BUFFER,0,e.arrayBuffer);}enableAttributes(e,t){for(let i=0;i0&&(h.push({circleArray:f,circleOffset:d,coord:_}),u+=f.length/4,d=u),m&&c.draw(a,l.LINES,Ot.disabled,Zt.disabled,e.colorModeForRenderPass(),jt.disabled,Di(e.transform),e.style.map.terrain&&e.style.map.terrain.getTerrainData(_),n.getProjectionData({overscaledTileID:_,applyGlobeMatrix:true,applyTerrainMatrix:true}),r.id,m.layoutVertexBuffer,m.indexBuffer,m.segments,null,e.transform.zoom,null,null,m.collisionVertexBuffer);}if(!s||!h.length)return;const _=e.useProgram("collisionCircle"),p=new t.bM;p.resize(4*u),p._trim();let m=0;for(const e of h)for(let t=0;t=0&&(f[g.associatedIconIndex]={shiftedAnchor:M,angle:S});}else Be(g.numGlyphs,p);}if(c){m.clear();const i=e.icon.placedSymbolArray;for(let e=0;ee.style.map.terrain.getElevation(l,t,i):null,i="map"===r.layout.get("text-rotation-alignment");Pe(c,e,s,j,O,v,h,i,l.toUnwrapped(),f.width,f.height,Z,t);}const q=s&&P||V,H=x||q?Vr:v?j:e.transform.clipSpaceToPixelsMatrix,W=p&&0!==r.paint.get(s?"text-halo-width":"icon-halo-width").constantOr(1);let X;X=p?c.iconsInText?$i(T.kind,S,b,v,x,q,e,H,N,Z,D,k,I):Xi(T.kind,S,b,v,x,q,e,H,N,Z,s,D,true,I):Wi(T.kind,S,b,v,x,q,e,H,N,Z,s,D,I);const $={program:M,buffers:u,uniformValues:X,projectionData:G,atlasTexture:z,atlasTextureIcon:F,atlasInterpolation:A,atlasInterpolationIcon:L,isSDF:p,hasHalo:W};if(y&&c.canOverlap){w=true;const e=u.segments.get();for(const i of e)C.push({segments:new t.aD([i]),sortKey:i.sortKey,state:$,terrainData:R});}else C.push({segments:u.segments,sortKey:0,state:$,terrainData:R});}w&&C.sort(((e,t)=>e.sortKey-t.sortKey));for(const t of C){const i=t.state;if(p.activeTexture.set(m.TEXTURE0),i.atlasTexture.bind(i.atlasInterpolation,m.CLAMP_TO_EDGE),i.atlasTextureIcon&&(p.activeTexture.set(m.TEXTURE1),i.atlasTextureIcon&&i.atlasTextureIcon.bind(i.atlasInterpolationIcon,m.CLAMP_TO_EDGE)),i.isSDF){const o=i.uniformValues;i.hasHalo&&(o.u_is_halo=1,Kr(i.buffers,t.segments,r,e,i.program,T,u,d,o,i.projectionData,t.terrainData)),o.u_is_halo=0;}Kr(i.buffers,t.segments,r,e,i.program,T,u,d,i.uniformValues,i.projectionData,t.terrainData);}}function Kr(e,t,i,r,o,s,a,n,l,c,h){const u=r.context;o.draw(u,u.gl.TRIANGLES,s,a,n,jt.backCCW,l,h,c,i.id,e.layoutVertexBuffer,e.indexBuffer,t,i.paint,r.transform.zoom,e.programConfigurations.get(i.id),e.dynamicLayoutVertexBuffer,e.opacityVertexBuffer);}function Yr(e,i,r,o,s){const a=e.context,n=a.gl,l=Zt.disabled,c=new Ft([n.ONE,n.ONE],t.b4.transparent,[true,true,true,true]),h=i.getBucket(r);if(!h)return;const u=o.key;let d=r.heatmapFbos.get(u);d||(d=Qr(a,i.tileSize,i.tileSize),r.heatmapFbos.set(u,d)),a.bindFramebuffer.set(d.framebuffer),a.viewport.set([0,0,i.tileSize,i.tileSize]),a.clear({color:t.b4.transparent});const _=h.programConfigurations.get(r.id),p=e.useProgram("heatmap",_,!s),m=e.transform.getProjectionData({overscaledTileID:i.tileID,applyGlobeMatrix:true,applyTerrainMatrix:true}),f=e.style.map.terrain.getTerrainData(o);p.draw(a,n.TRIANGLES,Ot.disabled,l,c,jt.disabled,Li(i,e.transform.zoom,r.paint.get("heatmap-intensity"),1),f,m,r.id,h.layoutVertexBuffer,h.indexBuffer,h.segments,r.paint,e.transform.zoom,_);}function Jr(e,t,i,r,o){const s=e.context,a=s.gl,n=e.transform;s.setColorMode(e.colorModeForRenderPass());const l=eo(s,t),c=i.key,h=t.heatmapFbos.get(c);if(!h)return;s.activeTexture.set(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,h.colorAttachment.get()),s.activeTexture.set(a.TEXTURE1),l.bind(a.LINEAR,a.CLAMP_TO_EDGE);const u=n.getProjectionData({overscaledTileID:i,applyTerrainMatrix:o,applyGlobeMatrix:!r});e.useProgram("heatmapTexture").draw(s,a.TRIANGLES,Ot.disabled,Zt.disabled,e.colorModeForRenderPass(),jt.disabled,ki(e,t,0,1),null,u,t.id,e.rasterBoundsBuffer,e.quadTriangleIndexBuffer,e.rasterBoundsSegments,t.paint,n.zoom),h.destroy(),t.heatmapFbos.delete(c);}function Qr(e,t,i){var r,o;const s=e.gl,a=s.createTexture();s.bindTexture(s.TEXTURE_2D,a),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR);const n=null!==(r=e.HALF_FLOAT)&&undefined!==r?r:s.UNSIGNED_BYTE,l=null!==(o=e.RGBA16F)&&undefined!==o?o:s.RGBA;s.texImage2D(s.TEXTURE_2D,0,l,t,i,0,s.RGBA,n,null);const c=e.createFramebuffer(t,i,false,false);return c.colorAttachment.set(a),c}function eo(e,t){return t.colorRampTexture||(t.colorRampTexture=new v(e,t.colorRamp,e.gl.RGBA)),t.colorRampTexture}function to(e,t,i,r,o){if(!i||!r||!r.imageAtlas)return;const s=r.imageAtlas.patternPositions;let a=s[i.to.toString()],n=s[i.from.toString()];if(!a&&n&&(a=n),!n&&a&&(n=a),!a||!n){const e=o.getPaintProperty(t);a=s[e],n=s[e];}a&&n&&e.setConstantPatternPositions(a,n);}function io(e,i,r,o,s,a,n,l){const c=e.context.gl,h="fill-pattern",u=r.paint.get(h),d=u&&u.constantOr(1),_=r.getCrossfadeParameters();let p,m,f,g,v;const x=e.transform,b=r.paint.get("fill-translate"),y=r.paint.get("fill-translate-anchor");n?(m=d&&!r.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",p=c.LINES):(m=d?"fillPattern":"fill",p=c.TRIANGLES);const w=u.constantOr(null);for(const u of o){const T=i.getTile(u);if(d&&!T.patternsLoaded())continue;const P=T.getBucket(r);if(!P)continue;const C=P.programConfigurations.get(r.id),I=e.useProgram(m,C),E=e.style.map.terrain&&e.style.map.terrain.getTerrainData(u);d&&(e.context.activeTexture.set(c.TEXTURE0),T.imageAtlasTexture.bind(c.LINEAR,c.CLAMP_TO_EDGE),C.updatePaintBuffers(_)),to(C,h,w,T,r);const M=x.getProjectionData({overscaledTileID:u,applyGlobeMatrix:!l,applyTerrainMatrix:true}),S=t.au(x,T,b,y);if(n){g=P.indexBuffer2,v=P.segments2;const t=[c.drawingBufferWidth,c.drawingBufferHeight];f="fillOutlinePattern"===m&&d?Si(e,_,T,t,S):Mi(t,S);}else g=P.indexBuffer,v=P.segments,f=d?Ei(e,_,T,S):{u_fill_translate:S};let R;if("translucent"===e.renderPass&&l){const[t]=e.getStencilConfigForOverlapAndUpdateStencilID(o);R=t[u.overscaledZ];}else R=e.stencilModeForClipping(u);I.draw(e.context,p,s,R,a,jt.backCCW,f,E,M,r.id,P.layoutVertexBuffer,g,v,r.paint,e.transform.zoom,C);}}function ro(e,i,r,o,s,a,n,l){const c=e.context,h=c.gl,u="fill-extrusion-pattern",d=r.paint.get(u),_=d.constantOr(1),p=r.getCrossfadeParameters(),m=r.paint.get("fill-extrusion-opacity"),f=d.constantOr(null),g=e.transform;for(const d of o){const o=i.getTile(d),v=o.getBucket(r);if(!v)continue;const x=e.style.map.terrain&&e.style.map.terrain.getTerrainData(d),b=v.programConfigurations.get(r.id),y=e.useProgram(_?"fillExtrusionPattern":"fillExtrusion",b);_&&(e.context.activeTexture.set(h.TEXTURE0),o.imageAtlasTexture.bind(h.LINEAR,h.CLAMP_TO_EDGE),b.updatePaintBuffers(p));const w=g.getProjectionData({overscaledTileID:d,applyGlobeMatrix:!l,applyTerrainMatrix:true});to(b,u,f,o,r);const T=t.au(g,o,r.paint.get("fill-extrusion-translate"),r.paint.get("fill-extrusion-translate-anchor")),P=r.paint.get("fill-extrusion-vertical-gradient"),C=_?Ii(e,P,m,T,d,p,o):Ci(e,P,m,T);y.draw(c,c.gl.TRIANGLES,s,a,n,jt.backCCW,C,x,w,r.id,v.layoutVertexBuffer,v.indexBuffer,v.segments,r.paint,e.transform.zoom,b,e.style.map.terrain&&v.centroidVertexBuffer);}}function oo(e,t,i,r,o,s,a,n,l){var c;const h=e.style.projection,u=e.context,d=e.transform,_=u.gl,p=e.useProgram("hillshade"),m=!e.options.moving;for(const f of r){const r=t.getTile(f),g=r.fbo;if(!g)continue;const v=h.getMeshFromTileID(u,f.canonical,n,true,"raster"),x=null===(c=e.style.map.terrain)||undefined===c?undefined:c.getTerrainData(f);u.activeTexture.set(_.TEXTURE0),_.bindTexture(_.TEXTURE_2D,g.colorAttachment.get());const b=d.getProjectionData({overscaledTileID:f,aligned:m,applyGlobeMatrix:!l,applyTerrainMatrix:true});p.draw(u,_.TRIANGLES,s,o[f.overscaledZ],a,jt.backCCW,Fi(e,r,i),x,b,i.id,v.vertexBuffer,v.indexBuffer,v.segments);}}const so=[new t.P(0,0),new t.P(t.X,0),new t.P(t.X,t.X),new t.P(0,t.X)];function ao(e,t,i,r,o,s,a,n,l=false,c=false){const h=r[r.length-1].overscaledZ,u=e.context,d=u.gl,_=e.useProgram("raster"),p=e.transform,m=e.style.projection,f=e.colorModeForRenderPass(),g=!e.options.moving;for(const v of r){const r=e.getDepthModeForSublayer(v.overscaledZ-h,1===i.paint.get("raster-opacity")?Ot.ReadWrite:Ot.ReadOnly,d.LESS),x=t.getTile(v);x.registerFadeDuration(i.paint.get("raster-fade-duration"));const b=t.findLoadedParent(v,0),y=t.findLoadedSibling(v),w=no(x,b||y||null,t,i,e.transform,e.style.map.terrain);let T,P;const C="nearest"===i.paint.get("raster-resampling")?d.NEAREST:d.LINEAR;u.activeTexture.set(d.TEXTURE0),x.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),u.activeTexture.set(d.TEXTURE1),b?(b.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),T=Math.pow(2,b.tileID.overscaledZ-x.tileID.overscaledZ),P=[x.tileID.canonical.x*T%1,x.tileID.canonical.y*T%1]):x.texture.bind(C,d.CLAMP_TO_EDGE,d.LINEAR_MIPMAP_NEAREST),x.texture.useMipmap&&u.extTextureFilterAnisotropic&&e.transform.pitch>20&&d.texParameterf(d.TEXTURE_2D,u.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,u.extTextureFilterAnisotropicMax);const I=e.style.map.terrain&&e.style.map.terrain.getTerrainData(v),E=p.getProjectionData({overscaledTileID:v,aligned:g,applyGlobeMatrix:!c,applyTerrainMatrix:true}),M=qi(P||[0,0],T||1,w,i,n),S=m.getMeshFromTileID(u,v.canonical,s,a,"raster");_.draw(u,d.TRIANGLES,r,o?o[v.overscaledZ]:Zt.disabled,f,l?jt.frontCCW:jt.backCCW,M,I,E,i.id,S.vertexBuffer,S.indexBuffer,S.segments);}}function no(e,i,r,o,s,n){const l=o.paint.get("raster-fade-duration");if(!n&&l>0){const o=a.now(),n=(o-e.timeAdded)/l,c=i?(o-i.timeAdded)/l:-1,h=r.getSource(),u=he(s,{tileSize:h.tileSize,roundZoom:h.roundZoom}),d=!i||Math.abs(i.tileID.overscaledZ-u)>Math.abs(e.tileID.overscaledZ-u),_=d&&e.refreshedUponExpiration?1:t.ab(d?n:1-c,0,1);return e.refreshedUponExpiration&&n>=1&&(e.refreshedUponExpiration=false),i?{opacity:1,mix:1-_}:{opacity:_,mix:0}}return {opacity:1,mix:0}}const lo=new t.b4(1,0,0,1),co=new t.b4(0,1,0,1),ho=new t.b4(0,0,1,1),uo=new t.b4(1,0,1,1),_o=new t.b4(0,1,1,1);function po(e,t,i,r){fo(e,0,t+i/2,e.transform.width,i,r);}function mo(e,t,i,r){fo(e,t-i/2,0,i,e.transform.height,r);}function fo(e,t,i,r,o,s){const a=e.context,n=a.gl;n.enable(n.SCISSOR_TEST),n.scissor(t*e.pixelRatio,i*e.pixelRatio,r*e.pixelRatio,o*e.pixelRatio),a.clear({color:s}),n.disable(n.SCISSOR_TEST);}function go(e,i,r){const o=e.context,s=o.gl,a=e.useProgram("debug"),n=Ot.disabled,l=Zt.disabled,c=e.colorModeForRenderPass(),h="$debug",u=e.style.map.terrain&&e.style.map.terrain.getTerrainData(r);o.activeTexture.set(s.TEXTURE0);const d=i.getTileByID(r.key).latestRawTileData,_=Math.floor((d&&d.byteLength||0)/1024),p=i.getTile(r).tileSize,m=512/Math.min(p,512)*(r.overscaledZ/e.transform.zoom)*.5;let f=r.canonical.toString();r.overscaledZ!==r.canonical.z&&(f+=` => ${r.overscaledZ}`),function(e,t){e.initDebugOverlayCanvas();const i=e.debugOverlayCanvas,r=e.context.gl,o=e.debugOverlayCanvas.getContext("2d");o.clearRect(0,0,i.width,i.height),o.shadowColor="white",o.shadowBlur=2,o.lineWidth=1.5,o.strokeStyle="white",o.textBaseline="top",o.font="bold 36px Open Sans, sans-serif",o.fillText(t,5,5),o.strokeText(t,5,5),e.debugOverlayTexture.update(i),e.debugOverlayTexture.bind(r.LINEAR,r.CLAMP_TO_EDGE);}(e,`${f} ${_}kB`);const g=e.transform.getProjectionData({overscaledTileID:r,applyGlobeMatrix:true,applyTerrainMatrix:true});a.draw(o,s.TRIANGLES,n,l,Ft.alphaBlended,jt.disabled,Ai(t.b4.transparent,m),null,g,h,e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments),a.draw(o,s.LINE_STRIP,n,l,c,jt.disabled,Ai(t.b4.red),u,g,h,e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments);}function vo(e,t,i,r){const{isRenderingGlobe:o}=r,s=e.context,a=s.gl,n=e.transform,l=e.colorModeForRenderPass(),c=e.getDepthModeFor3D(),h=e.useProgram("terrain");s.bindFramebuffer.set(null),s.viewport.set([0,0,e.width,e.height]);for(const r of i){const i=t.getTerrainMesh(r.tileID),u=e.renderToTexture.getTexture(r),d=t.getTerrainData(r.tileID);s.activeTexture.set(a.TEXTURE0),a.bindTexture(a.TEXTURE_2D,u.texture);const _=t.getMeshFrameDelta(n.zoom),p=n.calculateFogMatrix(r.tileID.toUnwrapped()),m=bi(_,p,e.style.sky,n.pitch,o),f=n.getProjectionData({overscaledTileID:r.tileID,applyTerrainMatrix:false,applyGlobeMatrix:true});h.draw(s,a.TRIANGLES,c,Zt.disabled,l,jt.backCCW,m,d,f,"terrain",i.vertexBuffer,i.indexBuffer,i.segments);}}function xo(e,i){if(!i.mesh){const r=new t.aC;r.emplaceBack(-1,-1),r.emplaceBack(1,-1),r.emplaceBack(1,1),r.emplaceBack(-1,1);const o=new t.aE;o.emplaceBack(0,1,2),o.emplaceBack(0,2,3),i.mesh=new pt(e.createVertexBuffer(r,mt.members),e.createIndexBuffer(o),t.aD.simpleSegment(0,0,r.length,o.length));}return i.mesh}class bo{constructor(e,i){this.context=new Zr(e),this.transform=i,this._tileTextures={},this.terrainFacilitator={dirty:true,matrix:t.aq(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=de.maxUnderzooming+de.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new ht;}resize(e,t,i){if(this.width=Math.floor(e*i),this.height=Math.floor(t*i),this.pixelRatio=i,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const e of this.style._order)this.style._layers[e].resize();}setup(){const e=this.context,i=new t.aC;i.emplaceBack(0,0),i.emplaceBack(t.X,0),i.emplaceBack(0,t.X),i.emplaceBack(t.X,t.X),this.tileExtentBuffer=e.createVertexBuffer(i,mt.members),this.tileExtentSegments=t.aD.simpleSegment(0,0,4,2);const r=new t.aC;r.emplaceBack(0,0),r.emplaceBack(t.X,0),r.emplaceBack(0,t.X),r.emplaceBack(t.X,t.X),this.debugBuffer=e.createVertexBuffer(r,mt.members),this.debugSegments=t.aD.simpleSegment(0,0,4,5);const o=new t.bT;o.emplaceBack(0,0,0,0),o.emplaceBack(t.X,0,t.X,0),o.emplaceBack(0,t.X,0,t.X),o.emplaceBack(t.X,t.X,t.X,t.X),this.rasterBoundsBuffer=e.createVertexBuffer(o,vi.members),this.rasterBoundsSegments=t.aD.simpleSegment(0,0,4,2);const s=new t.aC;s.emplaceBack(0,0),s.emplaceBack(t.X,0),s.emplaceBack(0,t.X),s.emplaceBack(t.X,t.X),this.rasterBoundsBufferPosOnly=e.createVertexBuffer(s,mt.members),this.rasterBoundsSegmentsPosOnly=t.aD.simpleSegment(0,0,4,5);const a=new t.aC;a.emplaceBack(0,0),a.emplaceBack(1,0),a.emplaceBack(0,1),a.emplaceBack(1,1),this.viewportBuffer=e.createVertexBuffer(a,mt.members),this.viewportSegments=t.aD.simpleSegment(0,0,4,2);const n=new t.bU;n.emplaceBack(0),n.emplaceBack(1),n.emplaceBack(3),n.emplaceBack(2),n.emplaceBack(0),this.tileBorderIndexBuffer=e.createIndexBuffer(n);const l=new t.aE;l.emplaceBack(1,0,2),l.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=e.createIndexBuffer(l);const c=this.context.gl;this.stencilClearMode=new Zt({func:c.ALWAYS,mask:0},0,255,c.ZERO,c.ZERO,c.ZERO),this.tileExtentMesh=new pt(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments);}clearStencil(){const e=this.context,i=e.gl;this.nextStencilID=1,this.currentStencilSource=undefined;const r=t.H();t.bL(r,0,this.width,this.height,0,0,1),t.K(r,r,[i.drawingBufferWidth,i.drawingBufferHeight,0]);const o={mainMatrix:r,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:r};this.useProgram("clippingMask",null,true).draw(e,i.TRIANGLES,Ot.disabled,this.stencilClearMode,Ft.disabled,jt.disabled,null,null,o,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments);}_renderTileClippingMasks(e,t,i){if(this.currentStencilSource===e.source||!e.isTileClipped()||!t||!t.length)return;this.currentStencilSource=e.source,this.nextStencilID+t.length>256&&this.clearStencil();const r=this.context;r.setColorMode(Ft.disabled),r.setDepthMode(Ot.disabled);const o={};for(const e of t)o[e.key]=this.nextStencilID++;this._renderTileMasks(o,t,i,true),this._renderTileMasks(o,t,i,false),this._tileClippingMaskIDs=o;}_renderTileMasks(e,t,i,r){const o=this.context,s=o.gl,a=this.style.projection,n=this.transform,l=this.useProgram("clippingMask");for(const c of t){const t=e[c.key],h=this.style.map.terrain&&this.style.map.terrain.getTerrainData(c),u=a.getMeshFromTileID(this.context,c.canonical,r,true,"stencil"),d=n.getProjectionData({overscaledTileID:c,applyGlobeMatrix:true,applyTerrainMatrix:true});l.draw(o,s.TRIANGLES,Ot.disabled,new Zt({func:s.ALWAYS,mask:0},t,255,s.KEEP,s.KEEP,s.REPLACE),Ft.disabled,i?jt.disabled:jt.backCCW,null,h,d,"$clipping",u.vertexBuffer,u.indexBuffer,u.segments);}}_renderTilesDepthBuffer(){const e=this.context,t=e.gl,i=this.style.projection,r=this.transform,o=this.useProgram("depth"),s=this.getDepthModeFor3D(),a=ue(r,{tileSize:r.tileSize});for(const n of a){const a=this.style.map.terrain&&this.style.map.terrain.getTerrainData(n),l=i.getMeshFromTileID(this.context,n.canonical,true,true,"raster"),c=r.getProjectionData({overscaledTileID:n,applyGlobeMatrix:true,applyTerrainMatrix:true});o.draw(e,t.TRIANGLES,s,Zt.disabled,Ft.disabled,jt.backCCW,null,a,c,"$clipping",l.vertexBuffer,l.indexBuffer,l.segments);}}stencilModeFor3D(){this.currentStencilSource=undefined,this.nextStencilID+1>256&&this.clearStencil();const e=this.nextStencilID++,t=this.context.gl;return new Zt({func:t.NOTEQUAL,mask:255},e,255,t.KEEP,t.KEEP,t.REPLACE)}stencilModeForClipping(e){const t=this.context.gl;return new Zt({func:t.EQUAL,mask:255},this._tileClippingMaskIDs[e.key],0,t.KEEP,t.KEEP,t.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(e){const t=this.context.gl,i=e.sort(((e,t)=>t.overscaledZ-e.overscaledZ)),r=i[i.length-1].overscaledZ,o=i[0].overscaledZ-r+1;if(o>1){this.currentStencilSource=undefined,this.nextStencilID+o>256&&this.clearStencil();const e={};for(let i=0;it.overscaledZ-e.overscaledZ)),r=i[i.length-1].overscaledZ,o=i[0].overscaledZ-r+1;if(this.clearStencil(),o>1){const e={},s={};for(let i=0;i0};for(const e in n){const t=n[e];t.used&&t.prepare(this.context),l[e]=t.getVisibleCoordinates(false),c[e]=l[e].slice().reverse(),h[e]=t.getVisibleCoordinates(true).reverse();}this.opaquePassCutoff=1/0;for(let e=0;ethis.useProgram(e)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:i.showOverdrawInspector?t.b4.black:t.b4.transparent,depth:1}),this.clearStencil(),this.style.sky&&function(e,t){const i=e.context,r=i.gl,o=((e,t,i)=>{const r=Math.cos(t.rollInRadians),o=Math.sin(t.rollInRadians),s=yt(t),a=t.getProjectionData({overscaledTileID:null,applyGlobeMatrix:true,applyTerrainMatrix:true}).projectionTransition;return {u_sky_color:e.properties.get("sky-color"),u_horizon_color:e.properties.get("horizon-color"),u_horizon:[(t.width/2-s*o)*i,(t.height/2+s*r)*i],u_horizon_normal:[-o,r],u_sky_horizon_blend:e.properties.get("sky-horizon-blend")*t.height/2*i,u_sky_blend:a}})(t,e.style.map.transform,e.pixelRatio),s=new Ot(r.LEQUAL,Ot.ReadWrite,[0,1]),a=Zt.disabled,n=e.colorModeForRenderPass(),l=e.useProgram("sky"),c=xo(i,t);l.draw(i,r.TRIANGLES,s,a,n,jt.disabled,o,null,undefined,"sky",c.vertexBuffer,c.indexBuffer,c.segments);}(this,this.style.sky),this._showOverdrawInspector=i.showOverdrawInspector,this.depthRangeFor3D=[0,1-(e._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=s.length-1;this.currentLayer>=0;this.currentLayer--){const e=this.style._layers[s[this.currentLayer]],t=n[e.source],i=l[e.source];this._renderTileClippingMasks(e,i,false),this.renderLayer(this,t,e,i,u);}this.renderPass="translucent";let d=false;for(this.currentLayer=0;this.currentLayer({u_sun_pos:e,u_atmosphere_blend:t,u_globe_position:i,u_globe_radius:r,u_inv_proj_matrix:o}))(c,u,[p[0],p[1],p[2]],d,_),f=xo(o,i);a.draw(o,s.TRIANGLES,n,Zt.disabled,Ft.alphaBlended,jt.disabled,m,null,null,"atmosphere",f.vertexBuffer,f.indexBuffer,f.segments);}(this,this.style.sky,this.style.light),this.options.showTileBoundaries){const e=function(e,t){let i=null;const r=Object.values(e._layers).flatMap((i=>i.source&&!i.isHidden(t)?[e.sourceCaches[i.source]]:[])),o=r.filter((e=>"vector"===e.getSource().type)),s=r.filter((e=>"vector"!==e.getSource().type)),a=e=>{(!i||i.getSource().maxzooma(e))),i||s.forEach((e=>a(e))),i}(this.style,this.transform.zoom);e&&function(e,t,i){for(let r=0;ru.getElevation(s,e,t):null;Wr(a,d,_,c,h,f,i,p,g,t.au(h,e,n,l),s.toUnwrapped(),r);}}}(o,e,r,i,r.layout.get("text-rotation-alignment"),r.layout.get("text-pitch-alignment"),r.paint.get("text-translate"),r.paint.get("text-translate-anchor"),s),0!==r.paint.get("icon-opacity").constantOr(1)&&$r(e,i,r,o,false,r.paint.get("icon-translate"),r.paint.get("icon-translate-anchor"),r.layout.get("icon-rotation-alignment"),r.layout.get("icon-pitch-alignment"),r.layout.get("icon-keep-upright"),l,c,n),0!==r.paint.get("text-opacity").constantOr(1)&&$r(e,i,r,o,true,r.paint.get("text-translate"),r.paint.get("text-translate-anchor"),r.layout.get("text-rotation-alignment"),r.layout.get("text-pitch-alignment"),r.layout.get("text-keep-upright"),l,c,n),i.map.showCollisionBoxes&&(Ur(e,i,r,o,true),Ur(e,i,r,o,false));}(e,i,r,o,this.style.placement.variableOffsets,s):t.bZ(r)?function(e,i,r,o,s){if("translucent"!==e.renderPass)return;const{isRenderingToTexture:a}=s,n=r.paint.get("circle-opacity"),l=r.paint.get("circle-stroke-width"),c=r.paint.get("circle-stroke-opacity"),h=!r.layout.get("circle-sort-key").isConstant();if(0===n.constantOr(1)&&(0===l.constantOr(1)||0===c.constantOr(1)))return;const u=e.context,d=u.gl,_=e.transform,p=e.getDepthModeForSublayer(0,Ot.ReadOnly),m=Zt.disabled,f=e.colorModeForRenderPass(),g=[],v=_.getCircleRadiusCorrection();for(let s=0;se.sortKey-t.sortKey));for(const t of g){const{programConfiguration:i,program:o,layoutVertexBuffer:s,indexBuffer:a,uniformValues:n,terrainData:l,projectionData:c}=t.state;o.draw(u,d.TRIANGLES,p,m,f,jt.backCCW,n,l,c,r.id,s,a,t.segments,r.paint,e.transform.zoom,i);}}(e,i,r,o,s):t.b_(r)?function(e,i,r,o,s){if(0===r.paint.get("heatmap-opacity"))return;const a=e.context,{isRenderingToTexture:n,isRenderingGlobe:l}=s;if(e.style.map.terrain){for(const t of o){const o=i.getTile(t);i.hasRenderableParent(t)||("offscreen"===e.renderPass?Yr(e,o,r,t,l):"translucent"===e.renderPass&&Jr(e,r,t,n,l));}a.viewport.set([0,0,e.width,e.height]);}else "offscreen"===e.renderPass?function(e,i,r,o){const s=e.context,a=s.gl,n=e.transform,l=Zt.disabled,c=new Ft([a.ONE,a.ONE],t.b4.transparent,[true,true,true,true]);(((function(e,i,r){const o=e.gl;e.activeTexture.set(o.TEXTURE1),e.viewport.set([0,0,i.width/4,i.height/4]);let s=r.heatmapFbos.get(t.bP);s?(o.bindTexture(o.TEXTURE_2D,s.colorAttachment.get()),e.bindFramebuffer.set(s.framebuffer)):(s=Qr(e,i.width/4,i.height/4),r.heatmapFbos.set(t.bP,s));})))(s,e,r),s.clear({color:t.b4.transparent});for(let t=0;t0?t.pop():null}isPatternMissing(e){if(!e)return false;if(!e.from||!e.to)return true;const t=this.imageManager.getPattern(e.from.toString()),i=this.imageManager.getPattern(e.to.toString());return !t||!i}useProgram(e,t,i=false){this.cache=this.cache||{};const r=!!this.style.map.terrain,o=this.style.projection,s=e+(t?t.cacheKey:"")+`/${i?gt:o.shaderVariantName}`+(this._showOverdrawInspector?"/overdraw":"")+(r?"/terrain":"");return this.cache[s]||(this.cache[s]=new Ti(this.context,dt[e],t,Qi[e],this._showOverdrawInspector,r,i?dt.projectionMercator:o.shaderPreludeCode,i?ft:o.shaderDefine)),this.cache[s]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault();}setBaseState(){const e=this.context.gl;this.context.cullFace.set(false),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(e.FUNC_ADD);}initDebugOverlayCanvas(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new v(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));}destroy(){this.debugOverlayTexture&&this.debugOverlayTexture.destroy();}overLimit(){const{drawingBufferWidth:e,drawingBufferHeight:t}=this.context.gl;return this.width!==e||this.height!==t}}function yo(e,t){let i,r=false,o=null,s=null;const a=()=>{o=null,r&&(e.apply(s,i),o=setTimeout(a,t),r=false);};return (...e)=>(r=true,s=this,i=e,o||a(),o)}class wo{constructor(e){this._getCurrentHash=()=>{const e=window.location.hash.replace("#","");if(this._hashName){let t;return e.split("&").map((e=>e.split("="))).forEach((e=>{e[0]===this._hashName&&(t=e);})),(t&&t[1]||"").split("/")}return e.split("/")},this._onHashChange=()=>{const e=this._getCurrentHash();if(!this._isValidHash(e))return false;const t=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(e[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+e[2],+e[1]],zoom:+e[0],bearing:t,pitch:+(e[4]||0)}),true},this._updateHashUnthrottled=()=>{const e=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,e);},this._removeHash=()=>{const e=this._getCurrentHash();if(0===e.length)return;const t=e.join("/");let i=t;i.split("&").length>0&&(i=i.split("&")[0]),this._hashName&&(i=`${this._hashName}=${t}`);let r=window.location.hash.replace(i,"");r.startsWith("#&")?r=r.slice(0,1)+r.slice(2):"#"===r&&(r="");let o=window.location.href.replace(/(#.+)?$/,r);o=o.replace("&&","&"),window.history.replaceState(window.history.state,null,o);},this._updateHash=yo(this._updateHashUnthrottled,300),this._hashName=e&&encodeURIComponent(e);}addTo(e){return this._map=e,addEventListener("hashchange",this._onHashChange,false),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,false),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(e){const t=this._map.getCenter(),i=Math.round(100*this._map.getZoom())/100,r=Math.ceil((i*Math.LN2+Math.log(512/360/.5))/Math.LN10),o=Math.pow(10,r),s=Math.round(t.lng*o)/o,a=Math.round(t.lat*o)/o,n=this._map.getBearing(),l=this._map.getPitch();let c="";if(c+=e?`/${s}/${a}/${i}`:`${i}/${a}/${s}`,(n||l)&&(c+="/"+Math.round(10*n)/10),l&&(c+=`/${Math.round(l)}`),this._hashName){const e=this._hashName;let t=false;const i=window.location.hash.slice(1).split("&").map((i=>{const r=i.split("=")[0];return r===e?(t=true,`${r}=${c}`):i})).filter((e=>e));return t||i.push(`${e}=${c}`),`#${i.join("&")}`}return `#${c}`}_isValidHash(e){if(e.length<3||e.some(isNaN))return false;try{new t.N(+e[2],+e[1]);}catch(e){return false}const i=+e[0],r=+(e[3]||0),o=+(e[4]||0);return i>=this._map.getMinZoom()&&i<=this._map.getMaxZoom()&&r>=0&&r<=180&&o>=this._map.getMinPitch()&&o<=this._map.getMaxPitch()}}const To={linearity:.3,easing:t.c6(0,0,.3,1)},Po=t.e({deceleration:2500,maxSpeed:1400},To),Co=t.e({deceleration:20,maxSpeed:1400},To),Io=t.e({deceleration:1e3,maxSpeed:360},To),Eo=t.e({deceleration:1e3,maxSpeed:90},To),Mo=t.e({deceleration:1e3,maxSpeed:360},To);class So{constructor(e){this._map=e,this.clear();}clear(){this._inertiaBuffer=[];}record(e){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:a.now(),settings:e});}_drainInertiaBuffer(){const e=this._inertiaBuffer,t=a.now();for(;e.length>0&&t-e[0].time>160;)e.shift();}_onMoveEnd(e){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const i={zoom:0,bearing:0,pitch:0,roll:0,pan:new t.P(0,0),pinchAround:undefined,around:undefined};for(const{settings:e}of this._inertiaBuffer)i.zoom+=e.zoomDelta||0,i.bearing+=e.bearingDelta||0,i.pitch+=e.pitchDelta||0,i.roll+=e.rollDelta||0,e.panDelta&&i.pan._add(e.panDelta),e.around&&(i.around=e.around),e.pinchAround&&(i.pinchAround=e.pinchAround);const r=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,o={};if(i.pan.mag()){const s=Do(i.pan.mag(),r,t.e({},Po,e||{})),a=i.pan.mult(s.amount/i.pan.mag()),n=this._map.cameraHelper.handlePanInertia(a,this._map.transform);o.center=n.easingCenter,o.offset=n.easingOffset,Ro(o,s);}if(i.zoom){const e=Do(i.zoom,r,Co);o.zoom=this._map.transform.zoom+e.amount,Ro(o,e);}if(i.bearing){const e=Do(i.bearing,r,Io);o.bearing=this._map.transform.bearing+t.ab(e.amount,-179,179),Ro(o,e);}if(i.pitch){const e=Do(i.pitch,r,Eo);o.pitch=this._map.transform.pitch+e.amount,Ro(o,e);}if(i.roll){const e=Do(i.roll,r,Mo);o.roll=this._map.transform.roll+t.ab(e.amount,-179,179),Ro(o,e);}if(o.zoom||o.bearing){const e=undefined===i.pinchAround?i.around:i.pinchAround;o.around=e?this._map.unproject(e):this._map.getCenter();}return this.clear(),t.e(o,{noMoveStart:true})}}function Ro(e,t){(!e.duration||e.durationi.unproject(e))),l=s.reduce(((e,t,i,r)=>e.add(t.div(r.length))),new t.P(0,0));super(e,{points:s,point:l,lngLats:a,lngLat:i.unproject(l),originalEvent:r}),this._defaultPrevented=false;}}class Lo extends t.k{preventDefault(){this._defaultPrevented=true;}get defaultPrevented(){return this._defaultPrevented}constructor(e,t,i){super(e,{originalEvent:i}),this._defaultPrevented=false;}}class ko{constructor(e,t){this._map=e,this._clickTolerance=t.clickTolerance;}reset(){delete this._mousedownPos;}wheel(e){return this._firePreventable(new Lo(e.type,this._map,e))}mousedown(e,t){return this._mousedownPos=t,this._firePreventable(new zo(e.type,this._map,e))}mouseup(e){this._map.fire(new zo(e.type,this._map,e));}click(e,t){this._mousedownPos&&this._mousedownPos.dist(t)>=this._clickTolerance||this._map.fire(new zo(e.type,this._map,e));}dblclick(e){return this._firePreventable(new zo(e.type,this._map,e))}mouseover(e){this._map.fire(new zo(e.type,this._map,e));}mouseout(e){this._map.fire(new zo(e.type,this._map,e));}touchstart(e){return this._firePreventable(new Ao(e.type,this._map,e))}touchmove(e){this._map.fire(new Ao(e.type,this._map,e));}touchend(e){this._map.fire(new Ao(e.type,this._map,e));}touchcancel(e){this._map.fire(new Ao(e.type,this._map,e));}_firePreventable(e){if(this._map.fire(e),e.defaultPrevented)return {}}isEnabled(){return true}isActive(){return false}enable(){}disable(){}}class Fo{constructor(e){this._map=e;}reset(){this._delayContextMenu=false,this._ignoreContextMenu=true,delete this._contextMenuEvent;}mousemove(e){this._map.fire(new zo(e.type,this._map,e));}mousedown(){this._delayContextMenu=true,this._ignoreContextMenu=false;}mouseup(){this._delayContextMenu=false,this._contextMenuEvent&&(this._map.fire(new zo("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);}contextmenu(e){this._delayContextMenu?this._contextMenuEvent=e:this._ignoreContextMenu||this._map.fire(new zo(e.type,this._map,e)),this._map.listens("contextmenu")&&e.preventDefault();}isEnabled(){return true}isActive(){return false}enable(){}disable(){}}class Bo{constructor(e){this._map=e;}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return {lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this._map.terrain)}}class jo{constructor(e,t){this._map=e,this._tr=new Bo(e),this._el=e.getCanvasContainer(),this._container=e.getContainer(),this._clickTolerance=t.clickTolerance||1;}isEnabled(){return !!this._enabled}isActive(){return !!this._active}enable(){this.isEnabled()||(this._enabled=true);}disable(){this.isEnabled()&&(this._enabled=false);}mousedown(e,t){this.isEnabled()&&e.shiftKey&&0===e.button&&(n.disableDrag(),this._startPos=this._lastPos=t,this._active=true);}mousemoveWindow(e,t){if(!this._active)return;const i=t;if(this._lastPos.equals(i)||!this._box&&i.dist(this._startPos)e.fitScreenCoordinates(r,o,this._tr.bearing,{linear:true})};this._fireEvent("boxzoomcancel",e);}keydown(e){this._active&&27===e.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",e));}reset(){this._active=false,this._container.classList.remove("maplibregl-crosshair"),this._box&&(n.remove(this._box),this._box=null),n.enableDrag(),delete this._startPos,delete this._lastPos;}_fireEvent(e,i){return this._map.fire(new t.k(e,{originalEvent:i}))}}function Oo(e,t){if(e.length!==t.length)throw new Error(`The number of touches and points are not equal - touches ${e.length}, points ${t.length}`);const i={};for(let r=0;rthis.numTouches)&&(this.aborted=true),this.aborted||(undefined===this.startTime&&(this.startTime=e.timeStamp),r.length===this.numTouches&&(this.centroid=function(e){const i=new t.P(0,0);for(const t of e)i._add(t);return i.div(e.length)}(i),this.touches=Oo(r,i)));}touchmove(e,t,i){if(this.aborted||!this.centroid)return;const r=Oo(i,t);for(const e in this.touches){const t=r[e];(!t||t.dist(this.touches[e])>30)&&(this.aborted=true);}}touchend(e,t,i){if((!this.centroid||e.timeStamp-this.startTime>500)&&(this.aborted=true),0===i.length){const e=!this.aborted&&this.centroid;if(this.reset(),e)return e}}}class Zo{constructor(e){this.singleTap=new No(e),this.numTaps=e.numTaps,this.reset();}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset();}touchstart(e,t,i){this.singleTap.touchstart(e,t,i);}touchmove(e,t,i){this.singleTap.touchmove(e,t,i);}touchend(e,t,i){const r=this.singleTap.touchend(e,t,i);if(r){const t=e.timeStamp-this.lastTime<500,i=!this.lastTap||this.lastTap.dist(r)<30;if(t&&i||this.reset(),this.count++,this.lastTime=e.timeStamp,this.lastTap=r,this.count===this.numTaps)return this.reset(),r}}}class Go{constructor(e){this._tr=new Bo(e),this._zoomIn=new Zo({numTouches:1,numTaps:2}),this._zoomOut=new Zo({numTouches:2,numTaps:1}),this.reset();}reset(){this._active=false,this._zoomIn.reset(),this._zoomOut.reset();}touchstart(e,t,i){this._zoomIn.touchstart(e,t,i),this._zoomOut.touchstart(e,t,i);}touchmove(e,t,i){this._zoomIn.touchmove(e,t,i),this._zoomOut.touchmove(e,t,i);}touchend(e,t,i){const r=this._zoomIn.touchend(e,t,i),o=this._zoomOut.touchend(e,t,i),s=this._tr;return r?(this._active=true,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:s.zoom+1,around:s.unproject(r)},{originalEvent:e})}):o?(this._active=true,e.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:t=>t.easeTo({duration:300,zoom:s.zoom-1,around:s.unproject(o)},{originalEvent:e})}):undefined}touchcancel(){this.reset();}enable(){this._enabled=true;}disable(){this._enabled=false,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class Uo{constructor(e){this._enabled=!!e.enable,this._moveStateManager=e.moveStateManager,this._clickTolerance=e.clickTolerance||1,this._moveFunction=e.move,this._activateOnStart=!!e.activateOnStart,e.assignEvents(this),this.reset();}reset(e){this._active=false,this._moved=false,delete this._lastPoint,this._moveStateManager.endMove(e);}_move(...e){const t=this._moveFunction(...e);if(t.bearingDelta||t.pitchDelta||t.rollDelta||t.around||t.panDelta)return this._active=true,t}dragStart(e,t){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(e)&&(this._moveStateManager.startMove(e),this._lastPoint=Array.isArray(t)?t[0]:t,this._activateOnStart&&this._lastPoint&&(this._active=true));}dragMove(e,t){if(!this.isEnabled())return;const i=this._lastPoint;if(!i)return;if(e.preventDefault(),!this._moveStateManager.isValidMoveEvent(e))return void this.reset(e);const r=Array.isArray(t)?t[0]:t;return !this._moved&&r.dist(i)true}),t=new Ho){this.mouseMoveStateManager=e,this.oneFingerTouchMoveStateManager=t;}_executeRelevantHandler(e,t,i){return e instanceof MouseEvent?t(e):"undefined"!=typeof TouchEvent&&e instanceof TouchEvent?i(e):undefined}startMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.startMove(e)),(e=>this.oneFingerTouchMoveStateManager.startMove(e)));}endMove(e){this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.endMove(e)),(e=>this.oneFingerTouchMoveStateManager.endMove(e)));}isValidStartEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidStartEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidStartEvent(e)))}isValidMoveEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidMoveEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidMoveEvent(e)))}isValidEndEvent(e){return this._executeRelevantHandler(e,(e=>this.mouseMoveStateManager.isValidEndEvent(e)),(e=>this.oneFingerTouchMoveStateManager.isValidEndEvent(e)))}}const Xo=e=>{e.mousedown=e.dragStart,e.mousemoveWindow=e.dragMove,e.mouseup=e.dragEnd,e.contextmenu=e=>{e.preventDefault();};};class $o{constructor(e,t){this._clickTolerance=e.clickTolerance||1,this._map=t,this.reset();}reset(){this._active=false,this._touches={},this._sum=new t.P(0,0);}_shouldBePrevented(e){return e<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(e,t,i){return this._calculateTransform(e,t,i)}touchmove(e,t,i){if(this._active){if(!this._shouldBePrevented(i.length))return e.preventDefault(),this._calculateTransform(e,t,i);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",e);}}touchend(e,t,i){this._calculateTransform(e,t,i),this._active&&this._shouldBePrevented(i.length)&&this.reset();}touchcancel(){this.reset();}_calculateTransform(e,i,r){r.length>0&&(this._active=true);const o=Oo(r,i),s=new t.P(0,0),a=new t.P(0,0);let n=0;for(const e in o){const t=o[e],i=this._touches[e];i&&(s._add(t),a._add(t.sub(i)),n++,o[e]=t);}if(this._touches=o,this._shouldBePrevented(n)||!a.mag())return;const l=a.div(n);return this._sum._add(l),this._sum.mag()Math.abs(e.x)}class rs extends Ko{constructor(e){super(),this._currentTouchCount=0,this._map=e;}reset(){super.reset(),this._valid=undefined,delete this._firstMove,delete this._lastPoints;}touchstart(e,t,i){super.touchstart(e,t,i),this._currentTouchCount=i.length;}_start(e){this._lastPoints=e,is(e[0].sub(e[1]))&&(this._valid=false);}_move(e,t,i){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;const r=e[0].sub(this._lastPoints[0]),o=e[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(r,o,i.timeStamp),this._valid?(this._lastPoints=e,this._active=true,{pitchDelta:(r.y+o.y)/2*-0.5}):undefined}gestureBeginsVertically(e,t,i){if(undefined!==this._valid)return this._valid;const r=e.mag()>=2,o=t.mag()>=2;if(!r&&!o)return;if(!r||!o)return undefined===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&undefined;const s=e.y>0==t.y>0;return is(e)&&is(t)&&s}}const os={panStep:100,bearingStep:15,pitchStep:10};class ss{constructor(e){this._tr=new Bo(e);const t=os;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep,this._rotationDisabled=false;}reset(){this._active=false;}keydown(e){if(e.altKey||e.ctrlKey||e.metaKey)return;let t=0,i=0,r=0,o=0,s=0;switch(e.keyCode){case 61:case 107:case 171:case 187:t=1;break;case 189:case 109:case 173:t=-1;break;case 37:e.shiftKey?i=-1:(e.preventDefault(),o=-1);break;case 39:e.shiftKey?i=1:(e.preventDefault(),o=1);break;case 38:e.shiftKey?r=1:(e.preventDefault(),s=-1);break;case 40:e.shiftKey?r=-1:(e.preventDefault(),s=1);break;default:return}return this._rotationDisabled&&(i=0,r=0),{cameraAnimation:a=>{const n=this._tr;a.easeTo({duration:300,easeId:"keyboardHandler",easing:as,zoom:t?Math.round(n.zoom)+t*(e.shiftKey?2:1):n.zoom,bearing:n.bearing+i*this._bearingStep,pitch:n.pitch+r*this._pitchStep,offset:[-o*this._panStep,-s*this._panStep],center:n.center},{originalEvent:e});}}}enable(){this._enabled=true;}disable(){this._enabled=false,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=true;}enableRotation(){this._rotationDisabled=false;}}function as(e){return e*(2-e)}const ns=4.000244140625;class ls{constructor(e,t){this._onTimeout=e=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(e);},this._map=e,this._tr=new Bo(e),this._triggerRenderFrame=t,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=.0022222222222222222;}setZoomRate(e){this._defaultZoomRate=e;}setWheelZoomRate(e){this._wheelZoomRate=e;}isEnabled(){return !!this._enabled}isActive(){return !!this._active||undefined!==this._finishTimeout}isZooming(){return !!this._zooming}enable(e){this.isEnabled()||(this._enabled=true,this._aroundCenter=!!e&&"center"===e.around);}disable(){this.isEnabled()&&(this._enabled=false);}_shouldBePrevented(e){return !!this._map.cooperativeGestures.isEnabled()&&!(e.ctrlKey||this._map.cooperativeGestures.isBypassed(e))}wheel(e){if(!this.isEnabled())return;if(this._shouldBePrevented(e))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",e);let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY;const i=a.now(),r=i-(this._lastWheelEventTime||0);this._lastWheelEventTime=i,0!==t&&t%ns==0?this._type="wheel":0!==t&&Math.abs(t)<4?this._type="trackpad":r>400?(this._type=null,this._lastValue=t,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(r*t)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,t+=this._lastValue)),e.shiftKey&&t&&(t/=4),this._type&&(this._lastWheelEvent=e,this._delta-=t,this._active||this._start(e)),e.preventDefault();}_start(e){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=true,this.isZooming()||(this._zooming=true),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const i=n.mousePos(this._map.getCanvas(),e),r=this._tr;this._aroundPoint=this._aroundCenter?r.transform.locationToScreenPoint(t.N.convert(r.center)):i,this._frameId||(this._frameId=true,this._triggerRenderFrame());}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const e=this._tr.transform;if("number"==typeof this._lastExpectedZoom){const t=e.zoom-this._lastExpectedZoom;"number"==typeof this._startZoom&&(this._startZoom+=t),"number"==typeof this._targetZoom&&(this._targetZoom+=t);}if(0!==this._delta){const i="wheel"===this._type&&Math.abs(this._delta)>ns?this._wheelZoomRate:this._defaultZoomRate;let r=2/(1+Math.exp(-Math.abs(this._delta*i)));this._delta<0&&0!==r&&(r=1/r);const o="number"!=typeof this._targetZoom?e.scale:t.aG(this._targetZoom);this._targetZoom=Math.min(e.maxZoom,Math.max(e.minZoom,t.a8(o*r))),"wheel"===this._type&&(this._startZoom=e.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}const i="number"!=typeof this._targetZoom?e.zoom:this._targetZoom,r=this._startZoom,o=this._easing;let s,n=false;if("wheel"===this._type&&r&&o){const e=a.now()-this._lastWheelEventTime,l=Math.min((e+5)/200,1),c=o(l);s=t.y.number(r,i,c),l<1?this._frameId||(this._frameId=true):n=true;}else s=i,n=true;return this._active=true,n&&(this._active=false,this._finishTimeout=setTimeout((()=>{this._zooming=false,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout;}),200)),this._lastExpectedZoom=s,{noInertia:true,needsRenderFrame:!n,zoomDelta:s-e.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(e){let i=t.c8;if(this._prevEase){const e=this._prevEase,r=(a.now()-e.start)/e.duration,o=e.easing(r+.01)-e.easing(r),s=.27/Math.sqrt(o*o+1e-4)*.01,n=Math.sqrt(.0729-s*s);i=t.c6(s,n,.25,1);}return this._prevEase={start:a.now(),duration:e,easing:i},i}reset(){this._active=false,this._zooming=false,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);}}class cs{constructor(e,t){this._clickZoom=e,this._tapZoom=t;}enable(){this._clickZoom.enable(),this._tapZoom.enable();}disable(){this._clickZoom.disable(),this._tapZoom.disable();}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class hs{constructor(e){this._tr=new Bo(e),this.reset();}reset(){this._active=false;}dblclick(e,t){return e.preventDefault(),{cameraAnimation:i=>{i.easeTo({duration:300,zoom:this._tr.zoom+(e.shiftKey?-1:1),around:this._tr.unproject(t)},{originalEvent:e});}}}enable(){this._enabled=true;}disable(){this._enabled=false,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class us{constructor(){this._tap=new Zo({numTouches:1,numTaps:1}),this.reset();}reset(){this._active=false,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset();}touchstart(e,t,i){if(!this._swipePoint)if(this._tapTime){const r=t[0],o=e.timeStamp-this._tapTime<500,s=this._tapPoint.dist(r)<30;o&&s?i.length>0&&(this._swipePoint=r,this._swipeTouch=i[0].identifier):this.reset();}else this._tap.touchstart(e,t,i);}touchmove(e,t,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;const r=t[0],o=r.y-this._swipePoint.y;return this._swipePoint=r,e.preventDefault(),this._active=true,{zoomDelta:o/128}}}else this._tap.touchmove(e,t,i);}touchend(e,t,i){if(this._tapTime)this._swipePoint&&0===i.length&&this.reset();else {const r=this._tap.touchend(e,t,i);r&&(this._tapTime=e.timeStamp,this._tapPoint=r);}}touchcancel(){this.reset();}enable(){this._enabled=true;}disable(){this._enabled=false,this.reset();}isEnabled(){return this._enabled}isActive(){return this._active}}class ds{constructor(e,t,i){this._el=e,this._mousePan=t,this._touchPan=i;}enable(e){this._inertiaOptions=e||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("maplibregl-touch-drag-pan");}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("maplibregl-touch-drag-pan");}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class _s{constructor(e,t,i,r){this._pitchWithRotate=e.pitchWithRotate,this._rollEnabled=e.rollEnabled,this._mouseRotate=t,this._mousePitch=i,this._mouseRoll=r;}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable();}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable();}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class ps{constructor(e,t,i,r){this._el=e,this._touchZoom=t,this._touchRotate=i,this._tapDragZoom=r,this._rotationDisabled=false,this._enabled=true;}enable(e){this._touchZoom.enable(e),this._rotationDisabled||this._touchRotate.enable(e),this._tapDragZoom.enable(),this._el.classList.add("maplibregl-touch-zoom-rotate");}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("maplibregl-touch-zoom-rotate");}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=true,this._touchRotate.disable();}enableRotation(){this._rotationDisabled=false,this._touchZoom.isEnabled()&&this._touchRotate.enable();}}class ms{constructor(e,t){this._bypassKey=-1!==navigator.userAgent.indexOf("Mac")?"metaKey":"ctrlKey",this._map=e,this._options=t,this._enabled=false;}isActive(){return false}reset(){}_setupUI(){if(this._container)return;const e=this._map.getCanvasContainer();e.classList.add("maplibregl-cooperative-gestures"),this._container=n.create("div","maplibregl-cooperative-gesture-screen",e);let t=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");"metaKey"===this._bypassKey&&(t=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));const i=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),r=document.createElement("div");r.className="maplibregl-desktop-message",r.textContent=t,this._container.appendChild(r);const o=document.createElement("div");o.className="maplibregl-mobile-message",o.textContent=i,this._container.appendChild(o),this._container.setAttribute("aria-hidden","true");}_destroyUI(){this._container&&(n.remove(this._container),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container;}enable(){this._setupUI(),this._enabled=true;}disable(){this._enabled=false,this._destroyUI();}isEnabled(){return this._enabled}isBypassed(e){return e[this._bypassKey]}notifyGestureBlocked(e,i){this._enabled&&(this._map.fire(new t.k("cooperativegestureprevented",{gestureType:e,originalEvent:i})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show");}),100));}}const fs=e=>e.zoom||e.drag||e.roll||e.pitch||e.rotate;class gs extends t.k{}function vs(e){return e.panDelta&&e.panDelta.mag()||e.zoomDelta||e.bearingDelta||e.pitchDelta||e.rollDelta}class xs{constructor(e,t){this.handleWindowEvent=e=>{this.handleEvent(e,`${e.type}Window`);},this.handleEvent=(e,t)=>{if("blur"===e.type)return void this.stop(true);this._updatingCamera=true;const i="renderFrame"===e.type?undefined:e,r={needsRenderFrame:false},o={},s={},a=e.touches,l=a?this._getMapTouches(a):undefined,c=l?n.touchPos(this._map.getCanvas(),l):n.mousePos(this._map.getCanvas(),e);for(const{handlerName:a,handler:n,allowed:h}of this._handlers){if(!n.isEnabled())continue;let u;this._blockedByActive(s,h,a)?n.reset():n[t||e.type]&&(u=n[t||e.type](e,c,l),this.mergeHandlerResult(r,o,u,a,i),u&&u.needsRenderFrame&&this._triggerRenderFrame()),(u||n.isActive())&&(s[a]=n);}const h={};for(const e in this._previousActiveHandlers)s[e]||(h[e]=i);this._previousActiveHandlers=s,(Object.keys(h).length||vs(r))&&(this._changes.push([r,o,h]),this._triggerRenderFrame()),(Object.keys(s).length||vs(r))&&this._map._stop(true),this._updatingCamera=false;const{cameraAnimation:u}=r;u&&(this._inertia.clear(),this._fireEvents({},{},true),this._changes=[],u(this._map));},this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new So(e),this._bearingSnap=t.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(t);const i=this._el;this._listeners=[[i,"touchstart",{passive:true}],[i,"touchmove",{passive:false}],[i,"touchend",undefined],[i,"touchcancel",undefined],[i,"mousedown",undefined],[i,"mousemove",undefined],[i,"mouseup",undefined],[document,"mousemove",{capture:true}],[document,"mouseup",undefined],[i,"mouseover",undefined],[i,"mouseout",undefined],[i,"dblclick",undefined],[i,"click",undefined],[i,"keydown",{capture:false}],[i,"keyup",undefined],[i,"wheel",{passive:false}],[i,"contextmenu",undefined],[window,"blur",undefined]];for(const[e,t,i]of this._listeners)n.addEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}destroy(){for(const[e,t,i]of this._listeners)n.removeEventListener(e,t,e===document?this.handleWindowEvent:this.handleEvent,i);}_addDefaultHandlers(e){const i=this._map,r=i.getCanvasContainer();this._add("mapEvent",new ko(i,e));const o=i.boxZoom=new jo(i,e);this._add("boxZoom",o),e.interactive&&e.boxZoom&&o.enable();const s=i.cooperativeGestures=new ms(i,e.cooperativeGestures);this._add("cooperativeGestures",s),e.cooperativeGestures&&s.enable();const a=new Go(i),l=new hs(i);i.doubleClickZoom=new cs(l,a),this._add("tapZoom",a),this._add("clickZoom",l),e.interactive&&e.doubleClickZoom&&i.doubleClickZoom.enable();const c=new us;this._add("tapDragZoom",c);const h=i.touchPitch=new rs(i);this._add("touchPitch",h),e.interactive&&e.touchPitch&&i.touchPitch.enable(e.touchPitch);const u=()=>i.project(i.getCenter()),d=function({enable:e,clickTolerance:i,aroundCenter:r=true,minPixelCenterThreshold:o=100,rotateDegreesPerPixelMoved:s=.8},a){const l=new qo({checkCorrectEvent:e=>0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)&&!e.ctrlKey});return new Uo({clickTolerance:i,move:(e,i)=>{const n=a();if(r&&Math.abs(n.y-e.y)>o)return {bearingDelta:t.c7(new t.P(e.x,i.y),i,n)};let l=(i.x-e.x)*s;return r&&i.y0===n.mouseButton(e)&&e.ctrlKey||2===n.mouseButton(e)});return new Uo({clickTolerance:t,move:(e,t)=>({pitchDelta:(t.y-e.y)*i}),moveStateManager:r,enable:e,assignEvents:Xo})}(e),p=function({enable:e,clickTolerance:t,rollDegreesPerPixelMoved:i=.3},r){const o=new qo({checkCorrectEvent:e=>2===n.mouseButton(e)&&e.ctrlKey});return new Uo({clickTolerance:t,move:(e,t)=>{const o=r();let s=(t.x-e.x)*i;return t.y0===n.mouseButton(e)&&!e.ctrlKey});return new Uo({clickTolerance:t,move:(e,t)=>({around:t,panDelta:t.sub(e)}),activateOnStart:true,moveStateManager:i,enable:e,assignEvents:Xo})}(e),f=new $o(e,i);i.dragPan=new ds(r,m,f),this._add("mousePan",m),this._add("touchPan",f,["touchZoom","touchRotate"]),e.interactive&&e.dragPan&&i.dragPan.enable(e.dragPan);const g=new ts,v=new Qo;i.touchZoomRotate=new ps(r,v,g,c),this._add("touchRotate",g,["touchPan","touchZoom"]),this._add("touchZoom",v,["touchPan","touchRotate"]),e.interactive&&e.touchZoomRotate&&i.touchZoomRotate.enable(e.touchZoomRotate);const x=i.scrollZoom=new ls(i,(()=>this._triggerRenderFrame()));this._add("scrollZoom",x,["mousePan"]),e.interactive&&e.scrollZoom&&i.scrollZoom.enable(e.scrollZoom);const b=i.keyboard=new ss(i);this._add("keyboard",b),e.interactive&&e.keyboard&&i.keyboard.enable(),this._add("blockableMapEvent",new Fo(i));}_add(e,t,i){this._handlers.push({handlerName:e,handler:t,allowed:i}),this._handlersById[e]=t;}stop(e){if(!this._updatingCamera){for(const{handler:e}of this._handlers)e.reset();this._inertia.clear(),this._fireEvents({},{},e),this._changes=[];}}isActive(){for(const{handler:e}of this._handlers)if(e.isActive())return true;return false}isZooming(){return !!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return !!this._eventsInProgress.rotate}isMoving(){return Boolean(fs(this._eventsInProgress))||this.isZooming()}_blockedByActive(e,t,i){for(const r in e)if(r!==i&&(!t||t.indexOf(r)<0))return true;return false}_getMapTouches(e){const t=[];for(const i of e)this._el.contains(i.target)&&t.push(i);return t}mergeHandlerResult(e,i,r,o,s){if(!r)return;t.e(e,r);const a={handlerName:o,originalEvent:r.originalEvent||s};undefined!==r.zoomDelta&&(i.zoom=a),undefined!==r.panDelta&&(i.drag=a),undefined!==r.rollDelta&&(i.roll=a),undefined!==r.pitchDelta&&(i.pitch=a),undefined!==r.bearingDelta&&(i.rotate=a);}_applyChanges(){const e={},i={},r={};for(const[o,s,a]of this._changes)o.panDelta&&(e.panDelta=(e.panDelta||new t.P(0,0))._add(o.panDelta)),o.zoomDelta&&(e.zoomDelta=(e.zoomDelta||0)+o.zoomDelta),o.bearingDelta&&(e.bearingDelta=(e.bearingDelta||0)+o.bearingDelta),o.pitchDelta&&(e.pitchDelta=(e.pitchDelta||0)+o.pitchDelta),o.rollDelta&&(e.rollDelta=(e.rollDelta||0)+o.rollDelta),undefined!==o.around&&(e.around=o.around),undefined!==o.pinchAround&&(e.pinchAround=o.pinchAround),o.noInertia&&(e.noInertia=o.noInertia),t.e(i,s),t.e(r,a);this._updateMapTransform(e,i,r),this._changes=[];}_updateMapTransform(e,t,i){const r=this._map,o=r._getTransformForUpdate(),s=r.terrain;if(!(vs(e)||s&&this._terrainMovement))return this._fireEvents(t,i,true);r._stop(true);let{panDelta:a,zoomDelta:n,bearingDelta:l,pitchDelta:c,rollDelta:h,around:u,pinchAround:d}=e;undefined!==d&&(u=d),u=u||r.transform.centerPoint,s&&!o.isPointOnMapSurface(u)&&(u=o.centerPoint);const _={panDelta:a,zoomDelta:n,rollDelta:h,pitchDelta:c,bearingDelta:l,around:u};this._map.cameraHelper.useGlobeControls&&!o.isPointOnMapSurface(u)&&(u=o.centerPoint);const p=u.distSqr(o.centerPoint)<.01?o.center:o.screenPointToLocation(a?u.sub(a):u);s?(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,o),this._terrainMovement||!t.drag&&!t.zoom?t.drag&&this._terrainMovement?o.setCenter(o.screenPointToLocation(o.centerPoint.sub(a))):this._map.cameraHelper.handleMapControlsPan(_,o,p):(this._terrainMovement=true,this._map._elevationFreeze=true,this._map.cameraHelper.handleMapControlsPan(_,o,p))):(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(_,o),this._map.cameraHelper.handleMapControlsPan(_,o,p)),r._applyUpdatedTransform(o),this._map._update(),e.noInertia||this._inertia.record(e),this._fireEvents(t,i,true);}_fireEvents(e,i,r){const o=fs(this._eventsInProgress),s=fs(e),n={};for(const t in e){const{originalEvent:i}=e[t];this._eventsInProgress[t]||(n[`${t}start`]=i),this._eventsInProgress[t]=e[t];}!o&&s&&this._fireEvent("movestart",s.originalEvent);for(const e in n)this._fireEvent(e,n[e]);s&&this._fireEvent("move",s.originalEvent);for(const t in e){const{originalEvent:i}=e[t];this._fireEvent(t,i);}const l={};let c;for(const e in this._eventsInProgress){const{handlerName:t,originalEvent:r}=this._eventsInProgress[e];this._handlersById[t].isActive()||(delete this._eventsInProgress[e],c=i[t]||r,l[`${e}end`]=c);}for(const e in l)this._fireEvent(e,l[e]);const h=fs(this._eventsInProgress),u=(o||s)&&!h;if(u&&this._terrainMovement){this._map._elevationFreeze=false,this._terrainMovement=false;const e=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&e.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(e);}if(r&&u){this._updatingCamera=true;const e=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),i=e=>0!==e&&-this._bearingSnap{delete this._frameId,this.handleEvent(new gs("renderFrame",{timeStamp:e})),this._applyChanges();}))}_triggerRenderFrame(){undefined===this._frameId&&(this._frameId=this._requestFrame());}}class bs extends t.E{constructor(e,t,i){super(),this._renderFrameCallback=()=>{const e=Math.min((a.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},this._moving=false,this._zooming=false,this.transform=e,this._bearingSnap=i.bearingSnap,this.cameraHelper=t,this.on("moveend",(()=>{delete this._requestedCameraState;}));}migrateProjection(e,t){e.apply(this.transform),this.transform=e,this.cameraHelper=t;}getCenter(){return new t.N(this.transform.center.lng,this.transform.center.lat)}setCenter(e,t){return this.jumpTo({center:e},t)}getCenterElevation(){return this.transform.elevation}setCenterElevation(e,t){return this.jumpTo({elevation:e},t),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(e){this._centerClampedToGround=e;}panBy(e,i,r){return e=t.P.convert(e).mult(-1),this.panTo(this.transform.center,t.e({offset:e},i),r)}panTo(e,i,r){return this.easeTo(t.e({center:e},i),r)}getZoom(){return this.transform.zoom}setZoom(e,t){return this.jumpTo({zoom:e},t),this}zoomTo(e,i,r){return this.easeTo(t.e({zoom:e},i),r)}zoomIn(e,t){return this.zoomTo(this.getZoom()+1,e,t),this}zoomOut(e,t){return this.zoomTo(this.getZoom()-1,e,t),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(e,i){return e!=this.transform.fov&&(this.transform.setFov(e),this.fire(new t.k("movestart",i)).fire(new t.k("move",i)).fire(new t.k("moveend",i))),this}getBearing(){return this.transform.bearing}setBearing(e,t){return this.jumpTo({bearing:e},t),this}getPadding(){return this.transform.padding}setPadding(e,t){return this.jumpTo({padding:e},t),this}rotateTo(e,i,r){return this.easeTo(t.e({bearing:e},i),r)}resetNorth(e,i){return this.rotateTo(0,t.e({duration:1e3},e),i),this}resetNorthPitch(e,i){return this.easeTo(t.e({bearing:0,pitch:0,roll:0,duration:1e3},e),i),this}snapToNorth(e,t){return Math.abs(this.getBearing()){f.easeFunc(t),this.terrain&&!e.freezeElevation&&this._updateElevation(t),this._applyUpdatedTransform(r),this._fireMoveEvents(i);}),(t=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i,t);}),e),this}_prepareEase(e,i,r={}){this._moving=true,i||r.moving||this.fire(new t.k("movestart",e)),this._zooming&&!r.zooming&&this.fire(new t.k("zoomstart",e)),this._rotating&&!r.rotating&&this.fire(new t.k("rotatestart",e)),this._pitching&&!r.pitching&&this.fire(new t.k("pitchstart",e)),this._rolling&&!r.rolling&&this.fire(new t.k("rollstart",e));}_prepareElevation(e){this._elevationCenter=e,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(e,this.transform.tileZoom),this._elevationFreeze=true;}_updateElevation(e){this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));const i=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(e<1&&i!==this._elevationTarget){const t=this._elevationTarget-this._elevationStart;this._elevationStart+=e*(t-(i-(t*e+this._elevationStart))/(1-e)),this._elevationTarget=i;}this.transform.setElevation(t.y.number(this._elevationStart,this._elevationTarget,e));}_finalizeElevation(){this._elevationFreeze=false,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain);}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(e){if(!this.terrain&&e.elevation>=0&&e.pitch<=90)return {};const t=e.getCameraLngLat(),i=e.getCameraAltitude(),r=this.terrain?this.terrain.getElevationForLngLatZoom(t,e.zoom):0;if(ithis._elevateCameraIfInsideTerrain(e))),this.transformCameraUpdate&&t.push((e=>this.transformCameraUpdate(e))),!t.length)return;const i=e.clone();for(const e of t){const t=i.clone(),{center:r,zoom:o,roll:s,pitch:a,bearing:n,elevation:l}=e(t);r&&t.setCenter(r),undefined!==l&&t.setElevation(l),undefined!==o&&t.setZoom(o),undefined!==s&&t.setRoll(s),undefined!==a&&t.setPitch(a),undefined!==n&&t.setBearing(n),i.apply(t);}this.transform.apply(i);}_fireMoveEvents(e){this.fire(new t.k("move",e)),this._zooming&&this.fire(new t.k("zoom",e)),this._rotating&&this.fire(new t.k("rotate",e)),this._pitching&&this.fire(new t.k("pitch",e)),this._rolling&&this.fire(new t.k("roll",e));}_afterEase(e,i){if(this._easeId&&i&&this._easeId===i)return;delete this._easeId;const r=this._zooming,o=this._rotating,s=this._pitching,a=this._rolling;this._moving=false,this._zooming=false,this._rotating=false,this._pitching=false,this._rolling=false,this._padding=false,r&&this.fire(new t.k("zoomend",e)),o&&this.fire(new t.k("rotateend",e)),s&&this.fire(new t.k("pitchend",e)),a&&this.fire(new t.k("rollend",e)),this.fire(new t.k("moveend",e));}flyTo(e,i){if(!e.essential&&a.prefersReducedMotion){const r=t.M(e,["center","zoom","bearing","pitch","roll","elevation"]);return this.jumpTo(r,i)}this.stop(),e=t.e({offset:[0,0],speed:1.2,curve:1.42,easing:t.c8},e);const r=this._getTransformForUpdate(),o=r.bearing,s=r.pitch,n=r.roll,l=r.padding,c="bearing"in e?this._normalizeBearing(e.bearing,o):o,h="pitch"in e?+e.pitch:s,u="roll"in e?this._normalizeBearing(e.roll,n):n,d="padding"in e?e.padding:r.padding,_=t.P.convert(e.offset);let p=r.centerPoint.add(_);const m=r.screenPointToLocation(p),f=this.cameraHelper.handleFlyTo(r,{bearing:c,pitch:h,roll:u,padding:d,locationAtOffset:m,offsetAsPoint:_,center:e.center,minZoom:e.minZoom,zoom:e.zoom});let g=e.curve;const v=Math.max(r.width,r.height),x=v/f.scaleOfZoom,b=f.pixelPathLength;"number"==typeof f.scaleOfMinZoom&&(g=Math.sqrt(v/f.scaleOfMinZoom/b*2));const y=g*g;function w(e){const t=(x*x-v*v+(e?-1:1)*y*y*b*b)/(2*(e?x:v)*y*b);return Math.log(Math.sqrt(t*t+1)-t)}function T(e){return (Math.exp(e)-Math.exp(-e))/2}function P(e){return (Math.exp(e)+Math.exp(-e))/2}const C=w(false);let I=function(e){return P(C)/P(C+g*e)},E=function(e){return v*((P(C)*(T(t=C+g*e)/P(t))-T(C))/y)/b;var t;},M=(w(true)-C)/g;if(Math.abs(b)<2e-6||!isFinite(M)){if(Math.abs(v-x)<1e-6)return this.easeTo(e,i);const t=x0,I=e=>Math.exp(t*g*e);}return e.duration="duration"in e?+e.duration:1e3*M/("screenSpeed"in e?+e.screenSpeed/g:+e.speed),e.maxDuration&&e.duration>e.maxDuration&&(e.duration=0),this._zooming=true,this._rotating=o!==c,this._pitching=h!==s,this._rolling=u!==n,this._padding=!r.isPaddingEqual(d),this._prepareEase(i,false),this.terrain&&this._prepareElevation(f.targetCenter),this._ease((a=>{const m=a*M,g=1/I(m),v=E(m);this._rotating&&r.setBearing(t.y.number(o,c,a)),this._pitching&&r.setPitch(t.y.number(s,h,a)),this._rolling&&r.setRoll(t.y.number(n,u,a)),this._padding&&(r.interpolatePadding(l,d,a),p=r.centerPoint.add(_)),f.easeFunc(a,g,v,p),this.terrain&&!e.freezeElevation&&this._updateElevation(a),this._applyUpdatedTransform(r),this._fireMoveEvents(i);}),(()=>{this.terrain&&e.freezeElevation&&this._finalizeElevation(),this._afterEase(i);}),e),this}isEasing(){return !!this._easeFrameId}stop(){return this._stop()}_stop(e,t){var i;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){const e=this._onEaseEnd;delete this._onEaseEnd,e.call(this,t);}return e||null===(i=this.handlers)||undefined===i||i.stop(false),this}_ease(e,t,i){false===i.animate||0===i.duration?(e(1),t()):(this._easeStart=a.now(),this._easeOptions=i,this._onEaseFrame=e,this._onEaseEnd=t,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));}_normalizeBearing(e,i){e=t.aI(e,-180,180);const r=Math.abs(e-i);return Math.abs(e-360-i)MapLibre'};class ws{constructor(e=ys){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")));},this._updateData=e=>{!e||"metadata"!==e.sourceDataType&&"visibility"!==e.sourceDataType&&"style"!==e.dataType&&"terrain"!==e.type||this._updateAttributions();},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?false===this._compact?this._container.setAttribute("open",""):this._container.classList.contains("maplibregl-compact")||this._container.classList.contains("maplibregl-attrib-empty")||(this._container.setAttribute("open",""),this._container.classList.add("maplibregl-compact","maplibregl-compact-show")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"));},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show");},this.options=e;}getDefaultPosition(){return "bottom-right"}onAdd(e){return this._map=e,this._compact=this.options.compact,this._container=n.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=n.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=n.create("div","maplibregl-ctrl-attrib-inner",this._container),this._updateAttributions(),this._updateCompact(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("terrain",this._updateData),this._map.on("resize",this._updateCompact),this._map.on("drag",this._updateCompactMinimize),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("terrain",this._updateData),this._map.off("resize",this._updateCompact),this._map.off("drag",this._updateCompactMinimize),this._map=undefined,this._compact=undefined,this._sanitizedAttributionHTML=undefined;}_setElementTitle(e,t){const i=this._map._getUIString(`AttributionControl.${t}`);e.title=i,e.setAttribute("aria-label",i);}_updateAttributions(){if(!this._map.style)return;let e=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?e=e.concat(this.options.customAttribution.map((e=>"string"!=typeof e?"":e))):"string"==typeof this.options.customAttribution&&e.push(this.options.customAttribution)),this._map.style.stylesheet){const e=this._map.style.stylesheet;this.styleOwner=e.owner,this.styleId=e.id;}const t=this._map.style.sourceCaches;for(const i in t){const r=t[i];if(r.used||r.usedForTerrain){const t=r.getSource();t.attribution&&e.indexOf(t.attribution)<0&&e.push(t.attribution);}}e=e.filter((e=>String(e).trim())),e.sort(((e,t)=>e.length-t.length)),e=e.filter(((t,i)=>{for(let r=i+1;r=0)return false;return true}));const i=e.join(" | ");i!==this._sanitizedAttributionHTML&&(this._sanitizedAttributionHTML=n.sanitize(i),e.length?(this._innerContainer.innerHTML=this._sanitizedAttributionHTML,this._container.classList.remove("maplibregl-attrib-empty")):this._container.classList.add("maplibregl-attrib-empty"),this._updateCompact(),this._editLink=null);}}class Ts{constructor(e={}){this._updateCompact=()=>{const e=this._container.children;if(e.length){const t=e[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?false!==this._compact&&t.classList.add("maplibregl-compact"):t.classList.remove("maplibregl-compact");}},this.options=e;}getDefaultPosition(){return "bottom-left"}onAdd(e){this._map=e,this._compact=this.options&&this.options.compact,this._container=n.create("div","maplibregl-ctrl");const t=n.create("a","maplibregl-ctrl-logo");return t.target="_blank",t.rel="noopener nofollow",t.href="https://maplibre.org/",t.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),t.setAttribute("rel","noopener nofollow"),this._container.appendChild(t),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){n.remove(this._container),this._map.off("resize",this._updateCompact),this._map=undefined,this._compact=undefined;}}class Ps{constructor(){this._queue=[],this._id=0,this._cleared=false,this._currentlyRunning=false;}add(e){const t=++this._id;return this._queue.push({callback:e,id:t,cancelled:false}),t}remove(e){const t=this._currentlyRunning,i=t?this._queue.concat(t):this._queue;for(const t of i)if(t.id===e)return void(t.cancelled=true)}run(e=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const t=this._currentlyRunning=this._queue;this._queue=[];for(const i of t)if(!i.cancelled&&(i.callback(e),this._cleared))break;this._cleared=false,this._currentlyRunning=false;}clear(){this._currentlyRunning&&(this._cleared=true),this._queue=[];}}var Cs=t.aA([{name:"a_pos3d",type:"Int16",components:3}]);class Is extends t.E{constructor(e){super(),this._lastTilesetChange=a.now(),this.sourceCache=e,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=e._source.tileSize*2**this.deltaZoom,e.usedForTerrain=true,e.tileSize=this.tileSize;}destruct(){this.sourceCache.usedForTerrain=false,this.sourceCache.tileSize=null;}update(e,i){this.sourceCache.update(e,i),this._renderableTilesKeys=[];const r={};for(const o of ue(e,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:false,terrain:i,calculateTileZoom:this.sourceCache._source.calculateTileZoom}))r[o.key]=true,this._renderableTilesKeys.push(o.key),this._tiles[o.key]||(o.terrainRttPosMatrix32f=new Float64Array(16),t.bL(o.terrainRttPosMatrix32f,0,t.X,t.X,0,0,1),this._tiles[o.key]=new se(o,this.tileSize),this._lastTilesetChange=a.now());for(const e in this._tiles)r[e]||delete this._tiles[e];}freeRtt(e){for(const t in this._tiles){const i=this._tiles[t];(!e||i.tileID.equals(e)||i.tileID.isChildOf(e)||e.isChildOf(i.tileID))&&(i.rtt=[]);}}getRenderableTiles(){return this._renderableTilesKeys.map((e=>this.getTileByID(e)))}getTileByID(e){return this._tiles[e]}getTerrainCoords(e){const i={};for(const r of this._renderableTilesKeys){const o=this._tiles[r].tileID,s=e.clone(),a=t.a$();if(o.canonical.equals(e.canonical))t.bL(a,0,t.X,t.X,0,0,1);else if(o.canonical.isChildOf(e.canonical)){const i=o.canonical.z-e.canonical.z,r=o.canonical.x-(o.canonical.x>>i<>i<>i;t.bL(a,0,n,n,0,0,1),t.J(a,a,[-r*n,-s*n,0]);}else {if(!e.canonical.isChildOf(o.canonical))continue;{const i=e.canonical.z-o.canonical.z,r=e.canonical.x-(e.canonical.x>>i<>i<>i;t.bL(a,0,t.X,t.X,0,0,1),t.J(a,a,[r*n,s*n,0]),t.K(a,a,[1/2**i,1/2**i,0]);}}s.terrainRttPosMatrix32f=new Float32Array(a),i[r]=s;}return i}getSourceTile(e,t){const i=this.sourceCache._source;let r=e.overscaledZ-this.deltaZoom;if(r>i.maxzoom&&(r=i.maxzoom),r=i.minzoom&&(!o||!o.dem);)o=this.sourceCache.getTileByID(e.scaledTo(r--).key);return o}anyTilesAfterTime(e=Date.now()){return this._lastTilesetChange>=e}}class Es{constructor(e,t,i){this._meshCache={},this.painter=e,this.sourceCache=new Is(t),this.options=i,this.exaggeration="number"==typeof i.exaggeration?i.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024;}getDEMElevation(e,i,r,o=t.X){var s;if(!(i>=0&&i=0&&re.canonical.z&&(e.canonical.z>=r?o=e.canonical.z-r:t.w("cannot calculate elevation if elevation maxzoom > source.maxzoom"));const s=e.canonical.x-(e.canonical.x>>o<>o<>8<<4|e>>8,i[t+3]=0;const r=new t.R({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(i.buffer)),o=new v(e,r,e.gl.RGBA,{premultiply:false});return o.bind(e.gl.NEAREST,e.gl.CLAMP_TO_EDGE),this._coordsTexture=o,o}pointCoordinate(e){this.painter.maybeDrawDepthAndCoords(true);const i=new Uint8Array(4),r=this.painter.context,o=r.gl,s=Math.round(e.x*this.painter.pixelRatio/devicePixelRatio),a=Math.round(e.y*this.painter.pixelRatio/devicePixelRatio),n=Math.round(this.painter.height/devicePixelRatio);r.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),o.readPixels(s,n-a-1,1,1,o.RGBA,o.UNSIGNED_BYTE,i),r.bindFramebuffer.set(null);const l=i[0]+(i[2]>>4<<8),c=i[1]+((15&i[2])<<8),h=this.coordsIndex[255-i[3]],u=h&&this.sourceCache.getTileByID(h);if(!u)return null;const d=this._coordsTextureSize,_=(1<0,o=r&&0===e.canonical.y,s=r&&e.canonical.y===(1<e.id!==t)),this._recentlyUsed.push(e.id);}stampObject(e){e.stamp=++this._stamp;}getOrCreateFreeObject(){for(const e of this._recentlyUsed)if(!this._objects[e].inUse)return this._objects[e];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const e=this._createObject(this._objects.length);return this._objects.push(e),e}freeObject(e){e.inUse=false;}freeAllObjects(){for(const e of this._objects)this.freeObject(e);}isFull(){return !(this._objects.length!e.inUse))}}const Ss={background:true,fill:true,line:true,raster:true,hillshade:true};class Rs{constructor(e,t){this.painter=e,this.terrain=t,this.pool=new Ms(e.context,30,t.sourceCache.tileSize*t.qualityFactor);}destruct(){this.pool.destruct();}getTexture(e){return this.pool.getObjectForId(e.rtt[this._stacks.length-1].id).texture}prepareForRender(e,t){this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.sourceCache.getRenderableTiles(),this._renderableLayerIds=e._order.filter((i=>!e._layers[i].isHidden(t))),this._coordsAscending={};for(const t in e.sourceCaches){this._coordsAscending[t]={};const i=e.sourceCaches[t].getVisibleCoordinates();for(const e of i){const i=this.terrain.sourceCache.getTerrainCoords(e);for(const e in i)this._coordsAscending[t][e]||(this._coordsAscending[t][e]=[]),this._coordsAscending[t][e].push(i[e]);}}this._coordsAscendingStr={};for(const t of e._order){const i=e._layers[t],r=i.source;if(Ss[i.type]&&!this._coordsAscendingStr[r]){this._coordsAscendingStr[r]={};for(const e in this._coordsAscending[r])this._coordsAscendingStr[r][e]=this._coordsAscending[r][e].map((e=>e.key)).sort().join();}}for(const e of this._renderableTiles)for(const t in this._coordsAscendingStr){const i=this._coordsAscendingStr[t][e.tileID.key];i&&i!==e.rttCoords[t]&&(e.rtt=[]);}}renderLayer(e,i){if(e.isHidden(this.painter.transform.zoom))return false;const r=Object.assign(Object.assign({},i),{isRenderingToTexture:true}),o=e.type,s=this.painter,a=this._renderableLayerIds[this._renderableLayerIds.length-1]===e.id;if(Ss[o]&&(this._prevType&&Ss[this._prevType]||this._stacks.push([]),this._prevType=o,this._stacks[this._stacks.length-1].push(e.id),!a))return true;if(Ss[this._prevType]||Ss[o]&&a){this._prevType=o;const e=this._stacks.length-1,i=this._stacks[e]||[];for(const o of this._renderableTiles){if(this.pool.isFull()&&(vo(this.painter,this.terrain,this._rttTiles,r),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(o),o.rtt[e]){const t=this.pool.getObjectForId(o.rtt[e].id);if(t.stamp===o.rtt[e].stamp){this.pool.useObject(t);continue}}const a=this.pool.getOrCreateFreeObject();this.pool.useObject(a),this.pool.stampObject(a),o.rtt[e]={id:a.id,stamp:a.stamp},s.context.bindFramebuffer.set(a.fbo.framebuffer),s.context.clear({color:t.b4.transparent,stencil:0}),s.currentStencilSource=undefined;for(let e=0;e{this.startMove(e,n.mousePos(this.element,e)),n.addEventListener(window,"mousemove",this.mousemove),n.addEventListener(window,"mouseup",this.mouseup);},this.mousemove=e=>{this.move(e,n.mousePos(this.element,e));},this.mouseup=e=>{this._rotatePitchHanlder.dragEnd(e),this.offTemp();},this.touchstart=e=>{1!==e.targetTouches.length?this.reset():(this._startPos=this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.startMove(e,this._startPos),n.addEventListener(window,"touchmove",this.touchmove,{passive:false}),n.addEventListener(window,"touchend",this.touchend));},this.touchmove=e=>{1!==e.targetTouches.length?this.reset():(this._lastPos=n.touchPos(this.element,e.targetTouches)[0],this.move(e,this._lastPos));},this.touchend=e=>{0===e.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this._rotatePitchHanlder.reset(),delete this._startPos,delete this._lastPos,this.offTemp();},this._clickTolerance=10,this.element=i;const o=new Wo;this._rotatePitchHanlder=new Uo({clickTolerance:3,move:(e,o)=>{const s=i.getBoundingClientRect(),a=new t.P((s.bottom-s.top)/2,(s.right-s.left)/2);return {bearingDelta:t.c7(new t.P(e.x,o.y),o,a),pitchDelta:r?-0.5*(o.y-e.y):undefined}},moveStateManager:o,enable:true,assignEvents:()=>{}}),this.map=e,n.addEventListener(i,"mousedown",this.mousedown),n.addEventListener(i,"touchstart",this.touchstart,{passive:false}),n.addEventListener(i,"touchcancel",this.reset);}startMove(e,t){this._rotatePitchHanlder.dragStart(e,t),n.disableDrag();}move(e,t){const i=this.map,{bearingDelta:r,pitchDelta:o}=this._rotatePitchHanlder.dragMove(e,t)||{};r&&i.setBearing(i.getBearing()+r),o&&i.setPitch(i.getPitch()+o);}off(){const e=this.element;n.removeEventListener(e,"mousedown",this.mousedown),n.removeEventListener(e,"touchstart",this.touchstart,{passive:false}),n.removeEventListener(window,"touchmove",this.touchmove,{passive:false}),n.removeEventListener(window,"touchend",this.touchend),n.removeEventListener(e,"touchcancel",this.reset),this.offTemp();}offTemp(){n.enableDrag(),n.removeEventListener(window,"mousemove",this.mousemove),n.removeEventListener(window,"mouseup",this.mouseup),n.removeEventListener(window,"touchmove",this.touchmove,{passive:false}),n.removeEventListener(window,"touchend",this.touchend);}}let Fs;function Bs(e,i,r){const o=new t.N(e.lng,e.lat);if(e=new t.N(e.lng,e.lat),i){const o=new t.N(e.lng-360,e.lat),s=new t.N(e.lng+360,e.lat),a=r.locationToScreenPoint(e).distSqr(i);r.locationToScreenPoint(o).distSqr(i)180;){const t=r.locationToScreenPoint(e);if(t.x>=0&&t.y>=0&&t.x<=r.width&&t.y<=r.height)break;e.lng>r.center.lng?e.lng-=360:e.lng+=360;}return e.lng!==o.lng&&r.isPointOnMapSurface(r.locationToScreenPoint(e))?e:o}const js={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function Os(e,t,i){const r=e.classList;for(const e in js)r.remove(`maplibregl-${i}-anchor-${e}`);r.add(`maplibregl-${i}-anchor-${t}`);}class Ns extends t.E{constructor(e){if(super(),this._onKeyPress=e=>{const t=e.code,i=e.charCode||e.keyCode;"Space"!==t&&"Enter"!==t&&32!==i&&13!==i||this.togglePopup();},this._onMapClick=e=>{const t=e.originalEvent.target,i=this._element;this._popup&&(t===i||i.contains(t))&&this.togglePopup();},this._update=e=>{var t;if(!this._map)return;const i=this._map.loaded()&&!this._map.isMoving();("terrain"===(null==e?undefined:e.type)||"render"===(null==e?undefined:e.type)&&!i)&&this._map.once("render",this._update),this._lngLat=this._map.transform.renderWorldCopies?Bs(this._lngLat,this._flatPos,this._map.transform):null===(t=this._lngLat)||undefined===t?undefined:t.wrap(),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let r="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?r=`rotateZ(${this._rotation}deg)`:"map"===this._rotationAlignment&&(r=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let o="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?o="rotateX(0deg)":"map"===this._pitchAlignment&&(o=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||e&&"moveend"!==e.type||(this._pos=this._pos.round()),n.setTransform(this._element,`${js[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${o} ${r}`),a.frameAsync(new AbortController).then((()=>{this._updateOpacity(e&&"moveend"===e.type);})).catch((()=>{}));},this._onMove=e=>{if(!this._isDragging){const t=this._clickTolerance||this._map._clickTolerance;this._isDragging=e.point.dist(this._pointerdownPos)>=t;}this._isDragging&&(this._pos=e.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new t.k("dragstart"))),this.fire(new t.k("drag")));},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=false,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new t.k("dragend")),this._state="inactive";},this._addDragHandler=e=>{this._element.contains(e.originalEvent.target)&&(e.preventDefault(),this._positionDelta=e.point.sub(this._pos).add(this._offset),this._pointerdownPos=e.point,this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp));},this._anchor=e&&e.anchor||"center",this._color=e&&e.color||"#3FB1CE",this._scale=e&&e.scale||1,this._draggable=e&&e.draggable||false,this._clickTolerance=e&&e.clickTolerance||0,this._subpixelPositioning=e&&e.subpixelPositioning||false,this._isDragging=false,this._state="inactive",this._rotation=e&&e.rotation||0,this._rotationAlignment=e&&e.rotationAlignment||"auto",this._pitchAlignment=e&&e.pitchAlignment&&"auto"!==e.pitchAlignment?e.pitchAlignment:this._rotationAlignment,this.setOpacity(),this.setOpacity(null==e?undefined:e.opacity,null==e?undefined:e.opacityWhenCovered),e&&e.element)this._element=e.element,this._offset=t.P.convert(e&&e.offset||[0,0]);else {this._defaultMarker=true,this._element=n.create("div");const i=n.createNS("http://www.w3.org/2000/svg","svg"),r=41,o=27;i.setAttributeNS(null,"display","block"),i.setAttributeNS(null,"height",`${r}px`),i.setAttributeNS(null,"width",`${o}px`),i.setAttributeNS(null,"viewBox",`0 0 ${o} ${r}`);const s=n.createNS("http://www.w3.org/2000/svg","g");s.setAttributeNS(null,"stroke","none"),s.setAttributeNS(null,"stroke-width","1"),s.setAttributeNS(null,"fill","none"),s.setAttributeNS(null,"fill-rule","evenodd");const a=n.createNS("http://www.w3.org/2000/svg","g");a.setAttributeNS(null,"fill-rule","nonzero");const l=n.createNS("http://www.w3.org/2000/svg","g");l.setAttributeNS(null,"transform","translate(3.0, 29.0)"),l.setAttributeNS(null,"fill","#000000");const c=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(const e of c){const t=n.createNS("http://www.w3.org/2000/svg","ellipse");t.setAttributeNS(null,"opacity","0.04"),t.setAttributeNS(null,"cx","10.5"),t.setAttributeNS(null,"cy","5.80029008"),t.setAttributeNS(null,"rx",e.rx),t.setAttributeNS(null,"ry",e.ry),l.appendChild(t);}const h=n.createNS("http://www.w3.org/2000/svg","g");h.setAttributeNS(null,"fill",this._color);const u=n.createNS("http://www.w3.org/2000/svg","path");u.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),h.appendChild(u);const d=n.createNS("http://www.w3.org/2000/svg","g");d.setAttributeNS(null,"opacity","0.25"),d.setAttributeNS(null,"fill","#000000");const _=n.createNS("http://www.w3.org/2000/svg","path");_.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),d.appendChild(_);const p=n.createNS("http://www.w3.org/2000/svg","g");p.setAttributeNS(null,"transform","translate(6.0, 7.0)"),p.setAttributeNS(null,"fill","#FFFFFF");const m=n.createNS("http://www.w3.org/2000/svg","g");m.setAttributeNS(null,"transform","translate(8.0, 8.0)");const f=n.createNS("http://www.w3.org/2000/svg","circle");f.setAttributeNS(null,"fill","#000000"),f.setAttributeNS(null,"opacity","0.25"),f.setAttributeNS(null,"cx","5.5"),f.setAttributeNS(null,"cy","5.5"),f.setAttributeNS(null,"r","5.4999962");const g=n.createNS("http://www.w3.org/2000/svg","circle");g.setAttributeNS(null,"fill","#FFFFFF"),g.setAttributeNS(null,"cx","5.5"),g.setAttributeNS(null,"cy","5.5"),g.setAttributeNS(null,"r","5.4999962"),m.appendChild(f),m.appendChild(g),a.appendChild(l),a.appendChild(h),a.appendChild(d),a.appendChild(p),a.appendChild(m),i.appendChild(a),i.setAttributeNS(null,"height",r*this._scale+"px"),i.setAttributeNS(null,"width",o*this._scale+"px"),this._element.appendChild(i),this._offset=t.P.convert(e&&e.offset||[0,-14]);}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(e=>{e.preventDefault();})),this._element.addEventListener("mousedown",(e=>{e.preventDefault();})),Os(this._element,this._anchor,"marker"),e&&e.className)for(const t of e.className.split(" "))this._element.classList.add(t);this._popup=null;}addTo(e){return this.remove(),this._map=e,this._element.setAttribute("aria-label",e._getUIString("Marker.Title")),e.getCanvasContainer().appendChild(this._element),e.on("move",this._update),e.on("moveend",this._update),e.on("terrain",this._update),e.on("projectiontransition",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("projectiontransition",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),n.remove(this._element),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.N.convert(e),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(e){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),e){if(!("offset"in e.options)){const t=38.1,i=13.5,r=Math.abs(i)/Math.SQRT2;e.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[r,-1*(t-i+r)],"bottom-right":[-r,-1*(t-i+r)],left:[i,-1*(t-i)],right:[-13.5,-1*(t-i)]}:this._offset;}this._popup=e,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress);}return this}setSubpixelPositioning(e){return this._subpixelPositioning=e,this}getPopup(){return this._popup}togglePopup(){const e=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:e?(e.isOpen()?e.remove():(e.setLngLat(this._lngLat),e.addTo(this._map)),this):this}_updateOpacity(e=false){var i,r;if(!(null===(i=this._map)||undefined===i?undefined:i.terrain)){const e=this._map.transform.isLocationOccluded(this._lngLat)?this._opacityWhenCovered:this._opacity;return void(this._element.style.opacity!==e&&(this._element.style.opacity=e))}if(e)this._opacityTimeout=null;else {if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null;}),100);}const o=this._map,s=o.terrain.depthAtPoint(this._pos),a=o.terrain.getElevationForLngLatZoom(this._lngLat,o.transform.tileZoom);if(o.transform.lngLatToCameraDepth(this._lngLat,a)-s<.006)return void(this._element.style.opacity=this._opacity);const n=-this._offset.y/o.transform.pixelsPerMeter,l=Math.sin(o.getPitch()*Math.PI/180)*n,c=o.terrain.depthAtPoint(new t.P(this._pos.x,this._pos.y-this._offset.y)),h=o.transform.lngLatToCameraDepth(this._lngLat,a+l)-c>.006;(null===(r=this._popup)||undefined===r?undefined:r.isOpen())&&h&&this._popup.remove(),this._element.style.opacity=h?this._opacityWhenCovered:this._opacity;}getOffset(){return this._offset}setOffset(e){return this._offset=t.P.convert(e),this._update(),this}addClassName(e){this._element.classList.add(e);}removeClassName(e){this._element.classList.remove(e);}toggleClassName(e){return this._element.classList.toggle(e)}setDraggable(e){return this._draggable=!!e,this._map&&(e?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(e){return this._rotation=e||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(e){return this._rotationAlignment=e||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(e){return this._pitchAlignment=e&&"auto"!==e?e:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(e,t){return undefined===e&&undefined===t&&(this._opacity="1",this._opacityWhenCovered="0.2"),undefined!==e&&(this._opacity=e),undefined!==t&&(this._opacityWhenCovered=t),this._map&&this._updateOpacity(true),this}}const Zs={positionOptions:{enableHighAccuracy:false,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:false,showAccuracyCircle:true,showUserLocation:true};let Gs=0,Us=false;const Vs={maxWidth:100,unit:"metric"};function qs(e,t,i){const r=i&&i.maxWidth||100,o=e._container.clientHeight/2,s=e._container.clientWidth/2,a=e.unproject([s-r/2,o]),n=e.unproject([s+r/2,o]),l=Math.round(e.project(n).x-e.project(a).x),c=Math.min(r,l,e._container.clientWidth),h=a.distanceTo(n);if(i&&"imperial"===i.unit){const i=3.2808*h;i>5280?Hs(t,c,i/5280,e._getUIString("ScaleControl.Miles")):Hs(t,c,i,e._getUIString("ScaleControl.Feet"));}else i&&"nautical"===i.unit?Hs(t,c,h/1852,e._getUIString("ScaleControl.NauticalMiles")):h>=1e3?Hs(t,c,h/1e3,e._getUIString("ScaleControl.Kilometers")):Hs(t,c,h,e._getUIString("ScaleControl.Meters"));}function Hs(e,t,i,r){const o=function(e){const t=Math.pow(10,`${Math.floor(e)}`.length-1);let i=e/t;return i=i>=10?10:i>=5?5:i>=3?3:i>=2?2:i>=1?1:function(e){const t=Math.pow(10,Math.ceil(-Math.log(e)/Math.LN10));return Math.round(e*t)/t}(i),t*i}(i);e.style.width=t*(o/i)+"px",e.innerHTML=`${o} ${r}`;}const Ws={closeButton:true,closeOnClick:true,focusAfterOpen:true,className:"",maxWidth:"240px",subpixelPositioning:false},Xs=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function $s(e){if(e){if("number"==typeof e){const i=Math.round(Math.abs(e)/Math.SQRT2);return {center:new t.P(0,0),top:new t.P(0,e),"top-left":new t.P(i,i),"top-right":new t.P(-i,i),bottom:new t.P(0,-e),"bottom-left":new t.P(i,-i),"bottom-right":new t.P(-i,-i),left:new t.P(e,0),right:new t.P(-e,0)}}if(e instanceof t.P||Array.isArray(e)){const i=t.P.convert(e);return {center:i,top:i,"top-left":i,"top-right":i,bottom:i,"bottom-left":i,"bottom-right":i,left:i,right:i}}return {center:t.P.convert(e.center||[0,0]),top:t.P.convert(e.top||[0,0]),"top-left":t.P.convert(e["top-left"]||[0,0]),"top-right":t.P.convert(e["top-right"]||[0,0]),bottom:t.P.convert(e.bottom||[0,0]),"bottom-left":t.P.convert(e["bottom-left"]||[0,0]),"bottom-right":t.P.convert(e["bottom-right"]||[0,0]),left:t.P.convert(e.left||[0,0]),right:t.P.convert(e.right||[0,0])}}return $s(new t.P(0,0))}const Ks=i;e.AJAXError=t.cg,e.Event=t.k,e.Evented=t.E,e.LngLat=t.N,e.MercatorCoordinate=t.Y,e.Point=t.P,e.addProtocol=t.ch,e.config=t.a,e.removeProtocol=t.ci,e.AttributionControl=ws,e.BoxZoomHandler=jo,e.CanvasSource=J,e.CooperativeGesturesHandler=ms,e.DoubleClickZoomHandler=cs,e.DragPanHandler=ds,e.DragRotateHandler=_s,e.EdgeInsets=Pt,e.FullscreenControl=class extends t.E{constructor(e={}){super(),this._onFullscreenChange=()=>{var e;let t=window.document.fullscreenElement||window.document.mozFullScreenElement||window.document.webkitFullscreenElement||window.document.msFullscreenElement;for(;null===(e=null==t?undefined:t.shadowRoot)||undefined===e?undefined:e.fullscreenElement;)t=t.shadowRoot.fullscreenElement;t===this._container!==this._fullscreen&&this._handleFullscreenChange();},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen();},this._fullscreen=false,e&&e.container&&(e.container instanceof HTMLElement?this._container=e.container:t.w("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange");}onAdd(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){n.remove(this._controlContainer),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange);}_setupUI(){const e=this._fullscreenButton=n.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);n.create("span","maplibregl-ctrl-icon",e).setAttribute("aria-hidden","true"),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange);}_updateTitle(){const e=this._getTitle();this._fullscreenButton.setAttribute("aria-label",e),this._fullscreenButton.title=e;}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink"),this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen"),this._updateTitle(),this._fullscreen?(this.fire(new t.k("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new t.k("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable());}_exitFullscreen(){window.document.exitFullscreen?window.document.exitFullscreen():window.document.mozCancelFullScreen?window.document.mozCancelFullScreen():window.document.msExitFullscreen?window.document.msExitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen();}_requestFullscreen(){this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen();}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize();}},e.GeoJSONSource=$,e.GeolocateControl=class extends t.E{constructor(e){super(),this._onSuccess=e=>{if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.k("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new t.k("geolocate",e)),this._finish();}},this._updateCamera=e=>{const i=new t.N(e.coords.longitude,e.coords.latitude),r=e.coords.accuracy,o=this._map.getBearing(),s=t.e({bearing:o},this.options.fitBoundsOptions),a=V.fromLngLat(i,r);this._map.fitBounds(a,s,{geolocateSource:true});},this._updateMarker=e=>{if(e){const i=new t.N(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=e.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},this._onZoom=()=>{this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();},this._onError=e=>{if(this._map){if(this.options.trackUserLocation)if(1===e.code){this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=true;const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e),undefined!==this._geolocationWatchID&&this._clearWatch();}else {if(3===e.code&&Us)return;this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new t.k("error",e)),this._finish();}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=undefined;},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this._geolocateButton=n.create("button","maplibregl-ctrl-geolocate",this._container),n.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=true);},this._finishSetupUI=e=>{if(this._map){if(false===e){t.w("Geolocation support is not available so the GeolocateControl will be disabled.");const e=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=true,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}else {const e=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=false,this._geolocateButton.title=e,this._geolocateButton.setAttribute("aria-label",e);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=n.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new Ns({element:this._dotElement}),this._circleElement=n.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Ns({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=true,this.options.trackUserLocation&&this._map.on("movestart",(e=>{e.geolocateSource||"ACTIVE_LOCK"!==this._watchState||e.originalEvent&&"resize"===e.originalEvent.type||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new t.k("trackuserlocationend")),this.fire(new t.k("userlocationlostfocus")));}));}},this.options=t.e({},Zs,e);}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),function(){return t._(this,arguments,undefined,(function*(e=false){if(undefined!==Fs&&!e)return Fs;if(undefined===window.navigator.permissions)return Fs=!!window.navigator.geolocation,Fs;try{const e=yield window.navigator.permissions.query({name:"geolocation"});Fs="denied"!==e.state;}catch(e){Fs=!!window.navigator.geolocation;}return Fs}))}().then((e=>this._finishSetupUI(e))),this._container}onRemove(){undefined!==this._geolocationWatchID&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=undefined),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),n.remove(this._container),this._map.off("zoom",this._onZoom),this._map=undefined,Gs=0,Us=false;}_isOutOfMapMaxBounds(e){const t=this._map.getMaxBounds(),i=e.coords;return t&&(i.longitudet.getEast()||i.latitudet.getNorth())}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"ACTIVE_ERROR":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadius(){const e=this._map.getBounds(),t=e.getSouthEast(),i=e.getNorthEast(),r=t.distanceTo(i),o=Math.ceil(this._accuracy/(r/this._map._container.clientHeight)*2);this._circleElement.style.width=`${o}px`,this._circleElement.style.height=`${o}px`;}trigger(){if(!this._setup)return t.w("Geolocate control triggered before added to a map"),false;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.k("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":Gs--,Us=false,this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this.fire(new t.k("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.k("trackuserlocationstart")),this.fire(new t.k("userlocationfocus"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if("OFF"===this._watchState&&undefined!==this._geolocationWatchID)this._clearWatch();else if(undefined===this._geolocationWatchID){let e;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),Gs++,Gs>1?(e={maximumAge:6e5,timeout:0},Us=true):(e=this.options.positionOptions,Us=false),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e);}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return true}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=undefined,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);}},e.GlobeControl=class{constructor(){this._toggleProjection=()=>{var e;const t=null===(e=this._map.getProjection())||undefined===e?undefined:e.type;this._map.setProjection("mercator"!==t&&t?{type:"mercator"}:{type:"globe"}),this._updateGlobeIcon();},this._updateGlobeIcon=()=>{var e;this._globeButton.classList.remove("maplibregl-ctrl-globe"),this._globeButton.classList.remove("maplibregl-ctrl-globe-enabled"),"globe"===(null===(e=this._map.getProjection())||undefined===e?undefined:e.type)?(this._globeButton.classList.add("maplibregl-ctrl-globe-enabled"),this._globeButton.title=this._map._getUIString("GlobeControl.Disable")):(this._globeButton.classList.add("maplibregl-ctrl-globe"),this._globeButton.title=this._map._getUIString("GlobeControl.Enable"));};}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._globeButton=n.create("button","maplibregl-ctrl-globe",this._container),n.create("span","maplibregl-ctrl-icon",this._globeButton).setAttribute("aria-hidden","true"),this._globeButton.type="button",this._globeButton.addEventListener("click",this._toggleProjection),this._updateGlobeIcon(),this._map.on("styledata",this._updateGlobeIcon),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateGlobeIcon),this._globeButton.removeEventListener("click",this._toggleProjection),this._map=undefined;}},e.Hash=wo,e.ImageSource=K,e.KeyboardHandler=ss,e.LngLatBounds=V,e.LogoControl=Ts,e.Map=class extends bs{constructor(e){var i,r;t.cd.mark(t.ce.create);const o=Object.assign(Object.assign(Object.assign({},As),e),{canvasContextAttributes:Object.assign(Object.assign({},As.canvasContextAttributes),e.canvasContextAttributes)});if(null!=o.minZoom&&null!=o.maxZoom&&o.minZoom>o.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=o.minPitch&&null!=o.maxPitch&&o.minPitch>o.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=o.minPitch&&o.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=o.maxPitch&&o.maxPitch>180)throw new Error("maxPitch must be less than or equal to 180");const s=new Dt,a=new kt;if(undefined!==o.minZoom&&s.setMinZoom(o.minZoom),undefined!==o.maxZoom&&s.setMaxZoom(o.maxZoom),undefined!==o.minPitch&&s.setMinPitch(o.minPitch),undefined!==o.maxPitch&&s.setMaxPitch(o.maxPitch),undefined!==o.renderWorldCopies&&s.setRenderWorldCopies(o.renderWorldCopies),super(s,a,{bearingSnap:o.bearingSnap}),this._idleTriggered=false,this._crossFadingFactor=1,this._renderTaskQueue=new Ps,this._controls=[],this._mapId=t.a1(),this._contextLost=e=>{e.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.fire(new t.k("webglcontextlost",{originalEvent:e}));},this._contextRestored=e=>{this._setupPainter(),this.resize(),this._update(),this.fire(new t.k("webglcontextrestored",{originalEvent:e}));},this._onMapScroll=e=>{if(e.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,false},this._onWindowOnline=()=>{this._update();},this._interactive=o.interactive,this._maxTileCacheSize=o.maxTileCacheSize,this._maxTileCacheZoomLevels=o.maxTileCacheZoomLevels,this._canvasContextAttributes=Object.assign({},o.canvasContextAttributes),this._trackResize=true===o.trackResize,this._bearingSnap=o.bearingSnap,this._centerClampedToGround=o.centerClampedToGround,this._refreshExpiredTiles=true===o.refreshExpiredTiles,this._fadeDuration=o.fadeDuration,this._crossSourceCollisions=true===o.crossSourceCollisions,this._collectResourceTiming=true===o.collectResourceTiming,this._locale=Object.assign(Object.assign({},Ds),o.locale),this._clickTolerance=o.clickTolerance,this._overridePixelRatio=o.pixelRatio,this._maxCanvasSize=o.maxCanvasSize,this.transformCameraUpdate=o.transformCameraUpdate,this.cancelPendingTileRequestsWhileZooming=true===o.cancelPendingTileRequestsWhileZooming,this._imageQueueHandle=p.addThrottleControl((()=>this.isMoving())),this._requestManager=new m(o.transformRequest),"string"==typeof o.container){if(this._container=document.getElementById(o.container),!this._container)throw new Error(`Container '${o.container}' not found.`)}else {if(!(o.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=o.container;}if(o.maxBounds&&this.setMaxBounds(o.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(false))),this.on("moveend",(()=>this._update(false))),this.on("zoom",(()=>this._update(true))),this.on("terrain",(()=>{this.painter.terrainFacilitator.dirty=true,this._update(true);})),this.once("idle",(()=>{this._idleTriggered=true;})),"undefined"!=typeof window){addEventListener("online",this._onWindowOnline,false);let e=false;const t=yo((e=>{this._trackResize&&!this._removed&&(this.resize(e),this.redraw());}),50);this._resizeObserver=new ResizeObserver((i=>{e?t(i):e=true;})),this._resizeObserver.observe(this._container);}this.handlers=new xs(this,o),this._hash=o.hash&&new wo("string"==typeof o.hash&&o.hash||undefined).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:o.center,elevation:o.elevation,zoom:o.zoom,bearing:o.bearing,pitch:o.pitch,roll:o.roll}),o.bounds&&(this.resize(),this.fitBounds(o.bounds,t.e({},o.fitBoundsOptions,{duration:0}))));const n="string"==typeof o.style||!("globe"===(null===(r=null===(i=o.style)||undefined===i?undefined:i.projection)||undefined===r?undefined:r.type));this.resize(null,n),this._localIdeographFontFamily=o.localIdeographFontFamily,this._validateStyle=o.validateStyle,o.style&&this.setStyle(o.style,{localIdeographFontFamily:o.localIdeographFontFamily}),o.attributionControl&&this.addControl(new ws("boolean"==typeof o.attributionControl?undefined:o.attributionControl)),o.maplibreLogo&&this.addControl(new Ts,o.logoPosition),this.on("style.load",(()=>{if(n||this._resizeTransform(),this.transform.unmodified){const e=t.M(this.style.stylesheet,["center","zoom","bearing","pitch","roll"]);this.jumpTo(e);}})),this.on("data",(e=>{this._update("style"===e.dataType),this.fire(new t.k(`${e.dataType}data`,e));})),this.on("dataloading",(e=>{this.fire(new t.k(`${e.dataType}dataloading`,e));})),this.on("dataabort",(e=>{this.fire(new t.k("sourcedataabort",e));}));}_getMapId(){return this._mapId}addControl(e,i){if(undefined===i&&(i=e.getDefaultPosition?e.getDefaultPosition():"top-right"),!e||!e.onAdd)return this.fire(new t.j(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const r=e.onAdd(this);this._controls.push(e);const o=this._controlPositions[i];return -1!==i.indexOf("bottom")?o.insertBefore(r,o.firstChild):o.appendChild(r),this}removeControl(e){if(!e||!e.onRemove)return this.fire(new t.j(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const i=this._controls.indexOf(e);return i>-1&&this._controls.splice(i,1),e.onRemove(this),this}hasControl(e){return this._controls.indexOf(e)>-1}calculateCameraOptionsFromTo(e,t,i,r){return null==r&&this.terrain&&(r=this.terrain.getElevationForLngLatZoom(i,this.transform.tileZoom)),super.calculateCameraOptionsFromTo(e,t,i,r)}resize(e,i=true){const[r,o]=this._containerDimensions(),s=this._getClampedPixelRatio(r,o);if(this._resizeCanvas(r,o,s),this.painter.resize(r,o,s),this.painter.overLimit()){const e=this.painter.context.gl;this._maxCanvasSize=[e.drawingBufferWidth,e.drawingBufferHeight];const t=this._getClampedPixelRatio(r,o);this._resizeCanvas(r,o,t),this.painter.resize(r,o,t);}this._resizeTransform(i);const a=!this._moving;return a&&(this.stop(),this.fire(new t.k("movestart",e)).fire(new t.k("move",e))),this.fire(new t.k("resize",e)),a&&this.fire(new t.k("moveend",e)),this}_resizeTransform(e=true){var t;const[i,r]=this._containerDimensions();this.transform.resize(i,r,e),null===(t=this._requestedCameraState)||undefined===t||t.resize(i,r,e);}_getClampedPixelRatio(e,t){const{0:i,1:r}=this._maxCanvasSize,o=this.getPixelRatio(),s=e*o,a=t*o;return Math.min(s>i?i/s:1,a>r?r/a:1)*o}getPixelRatio(){var e;return null!==(e=this._overridePixelRatio)&&undefined!==e?e:devicePixelRatio}setPixelRatio(e){this._overridePixelRatio=e,this.resize();}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(e){return this.transform.setMaxBounds(V.convert(e)),this._update()}setMinZoom(e){if((e=null==e?-2:e)>=-2&&e<=this.transform.maxZoom)return this.transform.setMinZoom(e),this._update(),this.getZoom()=this.transform.minZoom)return this.transform.setMaxZoom(e),this._update(),this.getZoom()>e&&this.setZoom(e),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(e){if((e=null==e?0:e)<0)throw new Error("minPitch must be greater than or equal to 0");if(e>=0&&e<=this.transform.maxPitch)return this.transform.setMinPitch(e),this._update(),this.getPitch()180)throw new Error("maxPitch must be less than or equal to 180");if(e>=this.transform.minPitch)return this.transform.setMaxPitch(e),this._update(),this.getPitch()>e&&this.setPitch(e),this;throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(e){return this.transform.setRenderWorldCopies(e),this._update()}project(e){return this.transform.locationToScreenPoint(t.N.convert(e),this.style&&this.terrain)}unproject(e){return this.transform.screenPointToLocation(t.P.convert(e),this.terrain)}isMoving(){var e;return this._moving||(null===(e=this.handlers)||undefined===e?undefined:e.isMoving())}isZooming(){var e;return this._zooming||(null===(e=this.handlers)||undefined===e?undefined:e.isZooming())}isRotating(){var e;return this._rotating||(null===(e=this.handlers)||undefined===e?undefined:e.isRotating())}_createDelegatedListener(e,t,i){if("mouseenter"===e||"mouseover"===e){let r=false;const o=o=>{const s=t.filter((e=>this.getLayer(e))),a=0!==s.length?this.queryRenderedFeatures(o.point,{layers:s}):[];a.length?r||(r=true,i.call(this,new zo(e,this,o.originalEvent,{features:a}))):r=false;};return {layers:t,listener:i,delegates:{mousemove:o,mouseout:()=>{r=false;}}}}if("mouseleave"===e||"mouseout"===e){let r=false;const o=o=>{const s=t.filter((e=>this.getLayer(e)));(0!==s.length?this.queryRenderedFeatures(o.point,{layers:s}):[]).length?r=true:r&&(r=false,i.call(this,new zo(e,this,o.originalEvent)));},s=t=>{r&&(r=false,i.call(this,new zo(e,this,t.originalEvent)));};return {layers:t,listener:i,delegates:{mousemove:o,mouseout:s}}}{const r=e=>{const r=t.filter((e=>this.getLayer(e))),o=0!==r.length?this.queryRenderedFeatures(e.point,{layers:r}):[];o.length&&(e.features=o,i.call(this,e),delete e.features);};return {layers:t,listener:i,delegates:{[e]:r}}}}_saveDelegatedListener(e,t){this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[e]=this._delegatedListeners[e]||[],this._delegatedListeners[e].push(t);}_removeDelegatedListener(e,t,i){if(!this._delegatedListeners||!this._delegatedListeners[e])return;const r=this._delegatedListeners[e];for(let e=0;et.includes(e)))){for(const e in o.delegates)this.off(e,o.delegates[e]);return void r.splice(e,1)}}}on(e,t,i){if(undefined===i)return super.on(e,t);const r="string"==typeof t?[t]:t,o=this._createDelegatedListener(e,r,i);this._saveDelegatedListener(e,o);for(const e in o.delegates)this.on(e,o.delegates[e]);return {unsubscribe:()=>{this._removeDelegatedListener(e,r,i);}}}once(e,t,i){if(undefined===i)return super.once(e,t);const r="string"==typeof t?[t]:t,o=this._createDelegatedListener(e,r,i);for(const t in o.delegates){const s=o.delegates[t];o.delegates[t]=(...t)=>{this._removeDelegatedListener(e,r,i),s(...t);};}this._saveDelegatedListener(e,o);for(const e in o.delegates)this.once(e,o.delegates[e]);return this}off(e,t,i){return undefined===i?super.off(e,t):(this._removeDelegatedListener(e,"string"==typeof t?[t]:t,i),this)}queryRenderedFeatures(e,i){if(!this.style)return [];let r;const o=e instanceof t.P||Array.isArray(e),s=o?e:[[0,0],[this.transform.width,this.transform.height]];if(i=i||(o?{}:e)||{},s instanceof t.P||"number"==typeof s[0])r=[t.P.convert(s)];else {const e=t.P.convert(s[0]),i=t.P.convert(s[1]);r=[e,new t.P(i.x,e.y),i,new t.P(e.x,i.y),e];}return this.style.queryRenderedFeatures(r,i,this.transform)}querySourceFeatures(e,t){return this.style.querySourceFeatures(e,t)}setStyle(e,i){return false!==(i=t.e({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},i)).diff&&i.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&e?(this._diffStyle(e,i),this):(this._localIdeographFontFamily=i.localIdeographFontFamily,this._updateStyle(e,i))}setTransformRequest(e){return this._requestManager.setTransformRequest(e),this}_getUIString(e){const t=this._locale[e];if(null==t)throw new Error(`Missing UI string '${e}'`);return t}_updateStyle(e,t){var i,r;if(t.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(e,t)));const o=this.style&&t.transformStyle?this.style.serialize():undefined;return this.style&&(this.style.setEventedParent(null),this.style._remove(!e)),e?(this.style=new gi(this,t||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof e?this.style.loadURL(e,t,o):this.style.loadJSON(e,t,o),this):(null===(r=null===(i=this.style)||undefined===i?undefined:i.projection)||undefined===r||r.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new gi(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty());}_diffStyle(e,i){if("string"==typeof e){const r=this._requestManager.transformRequest(e,"Style");t.h(r,new AbortController).then((e=>{this._updateDiff(e.data,i);})).catch((e=>{e&&this.fire(new t.j(e));}));}else "object"==typeof e&&this._updateDiff(e,i);}_updateDiff(e,i){try{this.style.setState(e,i)&&this._update(!0);}catch(r){t.w(`Unable to perform style diff: ${r.message||r.error||r}. Rebuilding the style from scratch.`),this._updateStyle(e,i);}}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():t.w("There is no style added to the map.")}addSource(e,t){return this._lazyInitEmptyStyle(),this.style.addSource(e,t),this._update(true)}isSourceLoaded(e){const i=this.style&&this.style.sourceCaches[e];if(undefined!==i)return i.loaded();this.fire(new t.j(new Error(`There is no source with ID '${e}'`)));}setTerrain(e){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),e){const i=this.style.sourceCaches[e.source];if(!i)throw new Error(`cannot load terrain, because there exists no source with ID: ${e.source}`);null===this.terrain&&i.reload();for(const i in this.style._layers){const r=this.style._layers[i];"hillshade"===r.type&&r.source===e.source&&t.w("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.");}this.terrain=new Es(this.painter,i,e),this.painter.renderToTexture=new Rs(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=t=>{"style"===t.dataType?this.terrain.sourceCache.freeRtt():"source"===t.dataType&&t.tile&&(t.sourceId!==e.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),this.terrain.sourceCache.freeRtt(t.tile.tileID));},this.style.on("data",this._terrainDataCallback);}else this.terrain&&this.terrain.sourceCache.destruct(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new t.k("terrain",{terrain:e})),this}getTerrain(){var e,t;return null!==(t=null===(e=this.terrain)||undefined===e?undefined:e.options)&&undefined!==t?t:null}areTilesLoaded(){const e=this.style&&this.style.sourceCaches;for(const t in e){const i=e[t]._tiles;for(const e in i){const t=i[e];if("loaded"!==t.state&&"errored"!==t.state)return false}}return true}removeSource(e){return this.style.removeSource(e),this._update(true)}getSource(e){return this.style.getSource(e)}addImage(e,i,r={}){const{pixelRatio:o=1,sdf:s=false,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u}=r;if(this._lazyInitEmptyStyle(),!(i instanceof HTMLImageElement||t.b(i))){if(undefined===i.width||undefined===i.height)return this.fire(new t.j(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{const{width:r,height:a,data:d}=i,_=i;return this.style.addImage(e,{data:new t.R({width:r,height:a},new Uint8Array(d)),pixelRatio:o,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:s,version:0,userImage:_}),_.onAdd&&_.onAdd(this,e),this}}{const{width:r,height:d,data:_}=a.getImageData(i);this.style.addImage(e,{data:new t.R({width:r,height:d},_),pixelRatio:o,stretchX:n,stretchY:l,content:c,textFitWidth:h,textFitHeight:u,sdf:s,version:0});}}updateImage(e,i){const r=this.style.getImage(e);if(!r)return this.fire(new t.j(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const o=i instanceof HTMLImageElement||t.b(i)?a.getImageData(i):i,{width:s,height:n,data:l}=o;if(undefined===s||undefined===n)return this.fire(new t.j(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(s!==r.data.width||n!==r.data.height)return this.fire(new t.j(new Error("The width and height of the updated image must be that same as the previous version of the image")));const c=!(i instanceof HTMLImageElement||t.b(i));return r.data.replace(l,c),this.style.updateImage(e,r),this}getImage(e){return this.style.getImage(e)}hasImage(e){return e?!!this.style.getImage(e):(this.fire(new t.j(new Error("Missing required image id"))),false)}removeImage(e){this.style.removeImage(e);}loadImage(e){return p.getImage(this._requestManager.transformRequest(e,"Image"),new AbortController)}listImages(){return this.style.listImages()}addLayer(e,t){return this._lazyInitEmptyStyle(),this.style.addLayer(e,t),this._update(true)}moveLayer(e,t){return this.style.moveLayer(e,t),this._update(true)}removeLayer(e){return this.style.removeLayer(e),this._update(true)}getLayer(e){return this.style.getLayer(e)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(e,t,i){return this.style.setLayerZoomRange(e,t,i),this._update(true)}setFilter(e,t,i={}){return this.style.setFilter(e,t,i),this._update(true)}getFilter(e){return this.style.getFilter(e)}setPaintProperty(e,t,i,r={}){return this.style.setPaintProperty(e,t,i,r),this._update(true)}getPaintProperty(e,t){return this.style.getPaintProperty(e,t)}setLayoutProperty(e,t,i,r={}){return this.style.setLayoutProperty(e,t,i,r),this._update(true)}getLayoutProperty(e,t){return this.style.getLayoutProperty(e,t)}setGlyphs(e,t={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(e,t),this._update(true)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(e,t,i={}){return this._lazyInitEmptyStyle(),this.style.addSprite(e,t,i,(e=>{e||this._update(true);})),this}removeSprite(e){return this._lazyInitEmptyStyle(),this.style.removeSprite(e),this._update(true)}getSprite(){return this.style.getSprite()}setSprite(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSprite(e,t,(e=>{e||this._update(true);})),this}setLight(e,t={}){return this._lazyInitEmptyStyle(),this.style.setLight(e,t),this._update(true)}getLight(){return this.style.getLight()}setSky(e,t={}){return this._lazyInitEmptyStyle(),this.style.setSky(e,t),this._update(true)}getSky(){return this.style.getSky()}setFeatureState(e,t){return this.style.setFeatureState(e,t),this._update()}removeFeatureState(e,t){return this.style.removeFeatureState(e,t),this._update()}getFeatureState(e){return this.style.getFeatureState(e)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let e=0,t=0;return this._container&&(e=this._container.clientWidth||400,t=this._container.clientHeight||300),[e,t]}_setupContainer(){const e=this._container;e.classList.add("maplibregl-map");const t=this._canvasContainer=n.create("div","maplibregl-canvas-container",e);this._interactive&&t.classList.add("maplibregl-interactive"),this._canvas=n.create("canvas","maplibregl-canvas",t),this._canvas.addEventListener("webglcontextlost",this._contextLost,false),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,false),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");const i=this._containerDimensions(),r=this._getClampedPixelRatio(i[0],i[1]);this._resizeCanvas(i[0],i[1],r);const o=this._controlContainer=n.create("div","maplibregl-control-container",e),s=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((e=>{s[e]=n.create("div",`maplibregl-ctrl-${e} `,o);})),this._container.addEventListener("scroll",this._onMapScroll,false);}_resizeCanvas(e,t,i){this._canvas.width=Math.floor(i*e),this._canvas.height=Math.floor(i*t),this._canvas.style.width=`${e}px`,this._canvas.style.height=`${t}px`;}_setupPainter(){const e=Object.assign(Object.assign({},this._canvasContextAttributes),{alpha:true,depth:true,stencil:true,premultipliedAlpha:true});let t=null;this._canvas.addEventListener("webglcontextcreationerror",(i=>{t={requestedAttributes:e},i&&(t.statusMessage=i.statusMessage,t.type=i.type);}),{once:true});let i=null;if(i=this._canvasContextAttributes.contextType?this._canvas.getContext(this._canvasContextAttributes.contextType,e):this._canvas.getContext("webgl2",e)||this._canvas.getContext("webgl",e),!i){const e="Failed to initialize WebGL";throw t?(t.message=e,new Error(JSON.stringify(t))):new Error(e)}this.painter=new bo(i,this.transform),l.testSupport(i);}migrateProjection(e,i){super.migrateProjection(e,i),this.painter.transform=e,this.fire(new t.k("projectiontransition",{newProjection:this.style.projection.name}));}loaded(){return !this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(e){return this.style&&this.style._loaded?(this._styleDirty=this._styleDirty||e,this._sourcesDirty=true,this.triggerRepaint(),this):this}_requestRenderFrame(e){return this._update(),this._renderTaskQueue.add(e)}_cancelRenderFrame(e){this._renderTaskQueue.remove(e);}_render(e){var i,r,o,s,n;const l=this._idleTriggered?this._fadeDuration:0,c=(null===(i=this.style.projection)||undefined===i?undefined:i.transitionState)>0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(e),this._removed)return;let h=false;if(this.style&&this._styleDirty){this._styleDirty=false;const e=this.transform.zoom,i=a.now();this.style.zoomHistory.update(e,i);const r=new t.z(e,{now:i,fadeDuration:l,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),o=r.crossFadingFactor();1===o&&o===this._crossFadingFactor||(h=true,this._crossFadingFactor=o),this.style.update(r);}const u=(null===(r=this.style.projection)||undefined===r?undefined:r.transitionState)>0!==c;null===(o=this.style.projection)||undefined===o||o.setErrorQueryLatitudeDegrees(this.transform.center.lat),this.transform.setTransitionState(null===(s=this.style.projection)||undefined===s?undefined:s.transitionState,null===(n=this.style.projection)||undefined===n?undefined:n.latitudeErrorCorrectionRadians),this.style&&(this._sourcesDirty||u)&&(this._sourcesDirty=false,this.style._updateSources(this.transform)),this.terrain?(this.terrain.sourceCache.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=this.style&&this.style._updatePlacement(this.transform,this.showCollisionBoxes,l,this._crossSourceCollisions,u),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:l,showPadding:this.showPadding}),this.fire(new t.k("render")),this.loaded()&&!this._loaded&&(this._loaded=true,t.cd.mark(t.ce.load),this.fire(new t.k("load"))),this.style&&(this.style.hasTransitions()||h)&&(this._styleDirty=true),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();const d=this._sourcesDirty||this._styleDirty||this._placementDirty;return d||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new t.k("idle")),!this._loaded||this._fullyLoaded||d||(this._fullyLoaded=true,t.cd.mark(t.ce.fullLoad)),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var e;this._hash&&this._hash.remove();for(const e of this._controls)e.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),"undefined"!=typeof window&&removeEventListener("online",this._onWindowOnline,false),p.removeThrottleControl(this._imageQueueHandle),null===(e=this._resizeObserver)||undefined===e||e.disconnect();const i=this.painter.context.gl.getExtension("WEBGL_lose_context");(null==i?undefined:i.loseContext)&&i.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,false),this._canvas.removeEventListener("webglcontextlost",this._contextLost,false),n.remove(this._canvasContainer),n.remove(this._controlContainer),this._container.removeEventListener("scroll",this._onMapScroll,false),this._container.classList.remove("maplibregl-map"),t.cd.clearMetrics(),this._removed=true,this.fire(new t.k("remove"));}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,a.frameAsync(this._frameRequest).then((e=>{t.cd.frame(e),this._frameRequest=null,this._render(e);})).catch((e=>{if(!t.cf(e)&&!function(e){return e.message===Or}(e))throw e})));}get showTileBoundaries(){return !!this._showTileBoundaries}set showTileBoundaries(e){this._showTileBoundaries!==e&&(this._showTileBoundaries=e,this._update());}get showPadding(){return !!this._showPadding}set showPadding(e){this._showPadding!==e&&(this._showPadding=e,this._update());}get showCollisionBoxes(){return !!this._showCollisionBoxes}set showCollisionBoxes(e){this._showCollisionBoxes!==e&&(this._showCollisionBoxes=e,e?this.style._generateCollisionBoxes():this._update());}get showOverdrawInspector(){return !!this._showOverdrawInspector}set showOverdrawInspector(e){this._showOverdrawInspector!==e&&(this._showOverdrawInspector=e,this._update());}get repaint(){return !!this._repaint}set repaint(e){this._repaint!==e&&(this._repaint=e,this.triggerRepaint());}get vertices(){return !!this._vertices}set vertices(e){this._vertices=e,this._update();}get version(){return zs}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(e){return this._lazyInitEmptyStyle(),this.style.setProjection(e),this._update(true)}},e.MapMouseEvent=zo,e.MapTouchEvent=Ao,e.MapWheelEvent=Lo,e.Marker=Ns,e.NavigationControl=class{constructor(e){this._updateZoomButtons=()=>{const e=this._map.getZoom(),t=e===this._map.getMaxZoom(),i=e===this._map.getMinZoom();this._zoomInButton.disabled=t,this._zoomOutButton.disabled=i,this._zoomInButton.setAttribute("aria-disabled",t.toString()),this._zoomOutButton.setAttribute("aria-disabled",i.toString());},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`;},this._setButtonTitle=(e,t)=>{const i=this._map._getUIString(`NavigationControl.${t}`);e.title=i,e.setAttribute("aria-label",i);},this.options=t.e({},Ls,e),this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(e=>e.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(e=>this._map.zoomIn({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(e=>this._map.zoomOut({},{originalEvent:e}))),n.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(e=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:e}):this._map.resetNorth({},{originalEvent:e});})),this._compassIcon=n.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"));}onAdd(e){return this._map=e,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on("roll",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new ks(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){n.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off("roll",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map;}_createButton(e,t){const i=n.create("button",e,this._container);return i.type="button",i.addEventListener("click",t),i}},e.Popup=class extends t.E{constructor(e){super(),this.remove=()=>(this._content&&n.remove(this._content),this._container&&(n.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._onMouseMove),this._map.off("mouseup",this._onMouseUp),this._map.off("drag",this._onDrag),this._map._canvasContainer.classList.remove("maplibregl-track-pointer"),delete this._map,this.fire(new t.k("close"))),this),this._onMouseUp=e=>{this._update(e.point);},this._onMouseMove=e=>{this._update(e.point);},this._onDrag=e=>{this._update(e.point);},this._update=e=>{var t;if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=n.create("div","maplibregl-popup",this._map.getContainer()),this._tip=n.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(const e of this.options.className.split(" "))this._container.classList.add(e);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),this._trackPointer&&this._container.classList.add("maplibregl-popup-track-pointer");}if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=this._map.transform.renderWorldCopies&&!this._trackPointer?Bs(this._lngLat,this._flatPos,this._map.transform):null===(t=this._lngLat)||undefined===t?undefined:t.wrap(),this._trackPointer&&!e)return;const i=this._flatPos=this._pos=this._trackPointer&&e?e:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&e?e:this._map.transform.locationToScreenPoint(this._lngLat));let r=this.options.anchor;const o=$s(this.options.offset);if(!r){const e=this._container.offsetWidth,t=this._container.offsetHeight;let s;s=i.y+o.bottom.ythis._map.transform.height-t?["bottom"]:[],i.xthis._map.transform.width-e/2&&s.push("right"),r=0===s.length?"bottom":s.join("-");}let s=i.add(o[r]);this.options.subpixelPositioning||(s=s.round()),n.setTransform(this._container,`${js[r]} translate(${s.x}px,${s.y}px)`),Os(this._container,r,"popup");},this._onClose=()=>{this.remove();},this.options=t.e(Object.create(Ws),e);}addTo(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new t.k("open")),this}isOpen(){return !!this._map}getLngLat(){return this._lngLat}setLngLat(e){return this._lngLat=t.N.convert(e),this._pos=null,this._flatPos=null,this._trackPointer=false,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=true,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(e){return this.setDOMContent(document.createTextNode(e))}setHTML(e){const t=document.createDocumentFragment(),i=document.createElement("body");let r;for(i.innerHTML=e;r=i.firstChild,r;)t.appendChild(r);return this.setDOMContent(t)}getMaxWidth(){var e;return null===(e=this._container)||undefined===e?undefined:e.style.maxWidth}setMaxWidth(e){return this.options.maxWidth=e,this._update(),this}setDOMContent(e){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=n.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(e),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(e){return this._container&&this._container.classList.add(e),this}removeClassName(e){return this._container&&this._container.classList.remove(e),this}setOffset(e){return this.options.offset=e,this._update(),this}toggleClassName(e){if(this._container)return this._container.classList.toggle(e)}setSubpixelPositioning(e){this.options.subpixelPositioning=e;}_createCloseButton(){this.options.closeButton&&(this._closeButton=n.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose));}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const e=this._container.querySelector(Xs);e&&e.focus();}},e.RasterDEMTileSource=X,e.RasterTileSource=W,e.ScaleControl=class{constructor(e){this._onMove=()=>{qs(this._map,this._container,this.options);},this.setUnit=e=>{this.options.unit=e,qs(this._map,this._container,this.options);},this.options=Object.assign(Object.assign({},Vs),e);}getDefaultPosition(){return "bottom-left"}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-scale",e.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){n.remove(this._container),this._map.off("move",this._onMove),this._map=undefined;}},e.ScrollZoomHandler=ls,e.Style=gi,e.TerrainControl=class{constructor(e){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon();},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"));},this.options=e;}onAdd(e){return this._map=e,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=n.create("button","maplibregl-ctrl-terrain",this._container),n.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true"),this._terrainButton.type="button",this._terrainButton.addEventListener("click",this._toggleTerrain),this._updateTerrainIcon(),this._map.on("terrain",this._updateTerrainIcon),this._container}onRemove(){n.remove(this._container),this._map.off("terrain",this._updateTerrainIcon),this._map=undefined;}},e.TwoFingersTouchPitchHandler=rs,e.TwoFingersTouchRotateHandler=ts,e.TwoFingersTouchZoomHandler=Qo,e.TwoFingersTouchZoomRotateHandler=ps,e.VectorTileSource=H,e.VideoSource=Y,e.addSourceType=(e,i)=>t._(undefined,undefined,undefined,(function*(){if(ee(e))throw new Error(`A source type called "${e}" already exists.`);((e,t)=>{Q[e]=t;})(e,i);})),e.clearPrewarmedResources=function(){const e=L;e&&(e.isPreloaded()&&1===e.numActive()?(e.release(D),L=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"));},e.createTileMesh=Ht,e.getMaxParallelImageRequests=function(){return t.a.MAX_PARALLEL_IMAGE_REQUESTS},e.getRTLTextPluginStatus=function(){return oe().getRTLTextPluginStatus()},e.getVersion=function(){return Ks},e.getWorkerCount=function(){return z.workerCount},e.getWorkerUrl=function(){return t.a.WORKER_URL},e.importScriptInWorkers=function(e){return j().broadcast("IS",e)},e.prewarm=function(){F().acquire(D);},e.setMaxParallelImageRequests=function(e){t.a.MAX_PARALLEL_IMAGE_REQUESTS=e;},e.setRTLTextPlugin=function(e,t){return oe().setRTLTextPlugin(e,t)},e.setWorkerCount=function(e){z.workerCount=e;},e.setWorkerUrl=function(e){t.a.WORKER_URL=e;};})); - - // - // Our custom intro provides a specialized "define()" function, called by the - // AMD modules below, that sets up the worker blob URL and then executes the - // main module, storing its exported value as 'maplibregl' - - - var maplibregl$1 = maplibregl; - - return maplibregl$1; - - })); - - } (maplibreGl$1)); - return maplibreGl$1.exports; -} - -var maplibreGlExports = requireMaplibreGl(); -var maplibregl = /*@__PURE__*/getDefaultExportFromCjs$1(maplibreGlExports); - -function getDefaultExportFromCjs (x) { - return x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; -} - -function getAugmentedNamespace(n) { - if (n.__esModule) return n; - var f = n.default; - if (typeof f == "function") { - var a = function a () { - if (this instanceof a) { - return Reflect.construct(f, arguments, this.constructor); - } - return f.apply(this, arguments); - }; - a.prototype = f.prototype; - } else a = {}; - Object.defineProperty(a, '__esModule', {value: true}); - Object.keys(n).forEach(function (k) { - var d = Object.getOwnPropertyDescriptor(n, k); - Object.defineProperty(a, k, d.get ? d : { - enumerable: true, - get: function () { - return n[k]; - } - }); - }); - return a; -} - -function objectConverter(columns) { - return new Function("d", "return {" + columns.map(function(name, i) { - return JSON.stringify(name) + ": d[" + i + "]"; - }).join(",") + "}"); -} - -function customConverter(columns, f) { - var object = objectConverter(columns); - return function(row, i) { - return f(object(row), i, columns); - }; -} - -// Compute unique columns in order of discovery. -function inferColumns(rows) { - var columnSet = Object.create(null), - columns = []; - - rows.forEach(function(row) { - for (var column in row) { - if (!(column in columnSet)) { - columns.push(columnSet[column] = column); - } - } - }); - - return columns; -} - -function dsv$1(delimiter) { - var reFormat = new RegExp("[\"" + delimiter + "\n]"), - delimiterCode = delimiter.charCodeAt(0); - - function parse(text, f) { - var convert, columns, rows = parseRows(text, function(row, i) { - if (convert) return convert(row, i - 1); - columns = row, convert = f ? customConverter(row, f) : objectConverter(row); - }); - rows.columns = columns; - return rows; - } - - function parseRows(text, f) { - var EOL = {}, // sentinel value for end-of-line - EOF = {}, // sentinel value for end-of-file - rows = [], // output rows - N = text.length, - I = 0, // current character index - n = 0, // the current line number - t, // the current token - eol; // is the current token followed by EOL? - - function token() { - if (I >= N) return EOF; // special case: end of file - if (eol) return eol = false, EOL; // special case: end of line - - // special case: quotes - var j = I, c; - if (text.charCodeAt(j) === 34) { - var i = j; - while (i++ < N) { - if (text.charCodeAt(i) === 34) { - if (text.charCodeAt(i + 1) !== 34) break; - ++i; - } - } - I = i + 2; - c = text.charCodeAt(i + 1); - if (c === 13) { - eol = true; - if (text.charCodeAt(i + 2) === 10) ++I; - } else if (c === 10) { - eol = true; - } - return text.slice(j + 1, i).replace(/""/g, "\""); - } - - // common case: find next delimiter or newline - while (I < N) { - var k = 1; - c = text.charCodeAt(I++); - if (c === 10) eol = true; // \n - else if (c === 13) { eol = true; if (text.charCodeAt(I) === 10) ++I, ++k; } // \r|\r\n - else if (c !== delimiterCode) continue; - return text.slice(j, I - k); - } - - // special case: last token before EOF - return text.slice(j); - } - - while ((t = token()) !== EOF) { - var a = []; - while (t !== EOL && t !== EOF) { - a.push(t); - t = token(); - } - if (f && (a = f(a, n++)) == null) continue; - rows.push(a); - } - - return rows; - } - - function format(rows, columns) { - if (columns == null) columns = inferColumns(rows); - return [columns.map(formatValue).join(delimiter)].concat(rows.map(function(row) { - return columns.map(function(column) { - return formatValue(row[column]); - }).join(delimiter); - })).join("\n"); - } - - function formatRows(rows) { - return rows.map(formatRow).join("\n"); - } - - function formatRow(row) { - return row.map(formatValue).join(delimiter); - } - - function formatValue(text) { - return text == null ? "" - : reFormat.test(text += "") ? "\"" + text.replace(/\"/g, "\"\"") + "\"" - : text; - } - - return { - parse: parse, - parseRows: parseRows, - format: format, - formatRows: formatRows - }; -} - -var csv = dsv$1(","); - -var csvParse = csv.parse; -var csvParseRows = csv.parseRows; -var csvFormat = csv.format; -var csvFormatRows = csv.formatRows; - -var tsv = dsv$1("\t"); - -var tsvParse = tsv.parse; -var tsvParseRows = tsv.parseRows; -var tsvFormat = tsv.format; -var tsvFormatRows = tsv.formatRows; - -var d3Dsv = /*#__PURE__*/Object.freeze({ - __proto__: null, - csvFormat: csvFormat, - csvFormatRows: csvFormatRows, - csvParse: csvParse, - csvParseRows: csvParseRows, - dsvFormat: dsv$1, - tsvFormat: tsvFormat, - tsvFormatRows: tsvFormatRows, - tsvParse: tsvParse, - tsvParseRows: tsvParseRows -}); - -var require$$0 = /*@__PURE__*/getAugmentedNamespace(d3Dsv); - -var sexagesimal$1 = {exports: {}}; - -sexagesimal$1.exports = element; -sexagesimal$1.exports.pair = pair; -sexagesimal$1.exports.format = format; -sexagesimal$1.exports.formatPair = formatPair; -sexagesimal$1.exports.coordToDMS = coordToDMS; - - -function element(input, dims) { - var result = search(input, dims); - return (result === null) ? null : result.val; -} - - -function formatPair(input) { - return format(input.lat, 'lat') + ' ' + format(input.lon, 'lon'); -} - - -// Is 0 North or South? -function format(input, dim) { - var dms = coordToDMS(input, dim); - return dms.whole + '° ' + - (dms.minutes ? dms.minutes + '\' ' : '') + - (dms.seconds ? dms.seconds + '" ' : '') + dms.dir; -} - - -function coordToDMS(input, dim) { - var dirs = { lat: ['N', 'S'], lon: ['E', 'W'] }[dim] || ''; - var dir = dirs[input >= 0 ? 0 : 1]; - var abs = Math.abs(input); - var whole = Math.floor(abs); - var fraction = abs - whole; - var fractionMinutes = fraction * 60; - var minutes = Math.floor(fractionMinutes); - var seconds = Math.floor((fractionMinutes - minutes) * 60); - - return { - whole: whole, - minutes: minutes, - seconds: seconds, - dir: dir - }; -} - - -function search(input, dims) { - if (!dims) dims = 'NSEW'; - if (typeof input !== 'string') return null; - - input = input.toUpperCase(); - var regex = /^[\s\,]*([NSEW])?\s*([\-|\—|\―]?[0-9.]+)[°º˚]?\s*(?:([0-9.]+)['’′‘]\s*)?(?:([0-9.]+)(?:''|"|”|″)\s*)?([NSEW])?/; - - var m = input.match(regex); - if (!m) return null; // no match - - var matched = m[0]; - - // extract dimension.. m[1] = leading, m[5] = trailing - var dim; - if (m[1] && m[5]) { // if matched both.. - dim = m[1]; // keep leading - matched = matched.slice(0, -1); // remove trailing dimension from match - } else { - dim = m[1] || m[5]; - } - - // if unrecognized dimension - if (dim && dims.indexOf(dim) === -1) return null; - - // extract DMS - var deg = m[2] ? parseFloat(m[2]) : 0; - var min = m[3] ? parseFloat(m[3]) / 60 : 0; - var sec = m[4] ? parseFloat(m[4]) / 3600 : 0; - var sign = (deg < 0) ? -1 : 1; - if (dim === 'S' || dim === 'W') sign *= -1; - - return { - val: (Math.abs(deg) + min + sec) * sign, - dim: dim, - matched: matched, - remain: input.slice(matched.length) - }; -} - - -function pair(input, dims) { - input = input.trim(); - var one = search(input, dims); - if (!one) return null; - - input = one.remain.trim(); - var two = search(input, dims); - if (!two || two.remain) return null; - - if (one.dim) { - return swapdim(one.val, two.val, one.dim); - } else { - return [one.val, two.val]; - } -} - - -function swapdim(a, b, dim) { - if (dim === 'N' || dim === 'S') return [a, b]; - if (dim === 'W' || dim === 'E') return [b, a]; -} - -var sexagesimalExports = sexagesimal$1.exports; - -var dsv = require$$0, - sexagesimal = sexagesimalExports; - -var latRegex = /(Lat)(itude)?/gi, - lonRegex = /(L)(on|ng)(gitude)?/i; - -function guessHeader(row, regexp) { - var name, match, score; - for (var f in row) { - match = f.match(regexp); - if (match && (!name || match[0].length / f.length > score)) { - score = match[0].length / f.length; - name = f; - } - } - return name; -} - -function guessLatHeader(row) { return guessHeader(row, latRegex); } -function guessLonHeader(row) { return guessHeader(row, lonRegex); } - -function isLat(f) { return !!f.match(latRegex); } -function isLon(f) { return !!f.match(lonRegex); } - -function keyCount(o) { - return (typeof o == 'object') ? Object.keys(o).length : 0; -} - -function autoDelimiter(x) { - var delimiters = [',', ';', '\t', '|']; - var results = []; - - delimiters.forEach(function (delimiter) { - var res = dsv.dsvFormat(delimiter).parse(x); - if (res.length >= 1) { - var count = keyCount(res[0]); - for (var i = 0; i < res.length; i++) { - if (keyCount(res[i]) !== count) return; - } - results.push({ - delimiter: delimiter, - arity: Object.keys(res[0]).length, - }); - } - }); - - if (results.length) { - return results.sort(function (a, b) { - return b.arity - a.arity; - })[0].delimiter; - } else { - return null; - } -} - -/** - * Silly stopgap for dsv to d3-dsv upgrade - * - * @param {Array} x dsv output - * @returns {Array} array without columns member - */ -function deleteColumns(x) { - delete x.columns; - return x; -} - -function auto(x) { - var delimiter = autoDelimiter(x); - if (!delimiter) return null; - return deleteColumns(dsv.dsvFormat(delimiter).parse(x)); -} - -function csv2geojson(x, options, callback) { - - if (!callback) { - callback = options; - options = {}; - } - - options.delimiter = options.delimiter || ','; - - var latfield = options.latfield || '', - lonfield = options.lonfield || '', - crs = options.crs || ''; - - var features = [], - featurecollection = {type: 'FeatureCollection', features: features}; - - if (crs !== '') { - featurecollection.crs = {type: 'name', properties: {name: crs}}; - } - - if (options.delimiter === 'auto' && typeof x == 'string') { - options.delimiter = autoDelimiter(x); - if (!options.delimiter) { - callback({ - type: 'Error', - message: 'Could not autodetect delimiter' - }); - return; - } - } - - var numericFields = options.numericFields ? options.numericFields.split(',') : null; - - var parsed = (typeof x == 'string') ? - dsv.dsvFormat(options.delimiter).parse(x, function (d) { - if (numericFields) { - for (var key in d) { - if (numericFields.includes(key)) { - d[key] = +d[key]; - } - } - } - return d; - }) : x; - - if (!parsed.length) { - callback(null, featurecollection); - return; - } - - var errors = []; - var i; - - - if (!latfield) latfield = guessLatHeader(parsed[0]); - if (!lonfield) lonfield = guessLonHeader(parsed[0]); - var noGeometry = (!latfield || !lonfield); - - if (noGeometry) { - for (i = 0; i < parsed.length; i++) { - features.push({ - type: 'Feature', - properties: parsed[i], - geometry: null - }); - } - callback(errors.length ? errors : null, featurecollection); - return; - } - - for (i = 0; i < parsed.length; i++) { - if (parsed[i][lonfield] !== undefined && - parsed[i][latfield] !== undefined) { - - var lonk = parsed[i][lonfield], - latk = parsed[i][latfield], - lonf, latf, - a; - - a = sexagesimal(lonk, 'EW'); - if (a) lonk = a; - a = sexagesimal(latk, 'NS'); - if (a) latk = a; - - lonf = parseFloat(lonk); - latf = parseFloat(latk); - - if (isNaN(lonf) || - isNaN(latf)) { - errors.push({ - message: 'A row contained an invalid value for latitude or longitude', - row: parsed[i], - index: i - }); - } else { - if (!options.includeLatLon) { - delete parsed[i][lonfield]; - delete parsed[i][latfield]; - } - - features.push({ - type: 'Feature', - properties: parsed[i], - geometry: { - type: 'Point', - coordinates: [ - parseFloat(lonf), - parseFloat(latf) - ] - } - }); - } - } - } - - callback(errors.length ? errors : null, featurecollection); -} - -function toLine(gj) { - var features = gj.features; - var line = { - type: 'Feature', - geometry: { - type: 'LineString', - coordinates: [] - } - }; - for (var i = 0; i < features.length; i++) { - line.geometry.coordinates.push(features[i].geometry.coordinates); - } - line.properties = features.reduce(function (aggregatedProperties, newFeature) { - for (var key in newFeature.properties) { - if (!aggregatedProperties[key]) { - aggregatedProperties[key] = []; - } - aggregatedProperties[key].push(newFeature.properties[key]); - } - return aggregatedProperties; - }, {}); - return { - type: 'FeatureCollection', - features: [line] - }; -} - -function toPolygon(gj) { - var features = gj.features; - var poly = { - type: 'Feature', - geometry: { - type: 'Polygon', - coordinates: [[]] - } - }; - for (var i = 0; i < features.length; i++) { - poly.geometry.coordinates[0].push(features[i].geometry.coordinates); - } - poly.properties = features.reduce(function (aggregatedProperties, newFeature) { - for (var key in newFeature.properties) { - if (!aggregatedProperties[key]) { - aggregatedProperties[key] = []; - } - aggregatedProperties[key].push(newFeature.properties[key]); - } - return aggregatedProperties; - }, {}); - return { - type: 'FeatureCollection', - features: [poly] - }; -} - -var csv2geojson_1 = { - isLon: isLon, - isLat: isLat, - guessLatHeader: guessLatHeader, - guessLonHeader: guessLonHeader, - csv: dsv.csvParse, - tsv: dsv.tsvParse, - dsv: dsv, - auto: auto, - csv2geojson: csv2geojson, - toLine: toLine, - toPolygon: toPolygon -}; - -function identity(x) { - return x; -} - -function transform(transform) { - if (transform == null) return identity; - var x0, - y0, - kx = transform.scale[0], - ky = transform.scale[1], - dx = transform.translate[0], - dy = transform.translate[1]; - return function(input, i) { - if (!i) x0 = y0 = 0; - var j = 2, n = input.length, output = new Array(n); - output[0] = (x0 += input[0]) * kx + dx; - output[1] = (y0 += input[1]) * ky + dy; - while (j < n) output[j] = input[j], ++j; - return output; - }; -} - -function reverse(array, n) { - var t, j = array.length, i = j - n; - while (i < --j) t = array[i], array[i++] = array[j], array[j] = t; -} - -function topojsonFeature(topology, o) { - if (typeof o === "string") o = topology.objects[o]; - return o.type === "GeometryCollection" - ? {type: "FeatureCollection", features: o.geometries.map(function(o) { return feature(topology, o); })} - : feature(topology, o); -} - -function feature(topology, o) { - var id = o.id, - bbox = o.bbox, - properties = o.properties == null ? {} : o.properties, - geometry = object(topology, o); - return id == null && bbox == null ? {type: "Feature", properties: properties, geometry: geometry} - : bbox == null ? {type: "Feature", id: id, properties: properties, geometry: geometry} - : {type: "Feature", id: id, bbox: bbox, properties: properties, geometry: geometry}; -} - -function object(topology, o) { - var transformPoint = transform(topology.transform), - arcs = topology.arcs; - - function arc(i, points) { - if (points.length) points.pop(); - for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length; k < n; ++k) { - points.push(transformPoint(a[k], k)); - } - if (i < 0) reverse(points, n); - } - - function point(p) { - return transformPoint(p); - } - - function line(arcs) { - var points = []; - for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points); - if (points.length < 2) points.push(points[0]); // This should never happen per the specification. - return points; - } - - function ring(arcs) { - var points = line(arcs); - while (points.length < 4) points.push(points[0]); // This may happen if an arc has only two points. - return points; - } - - function polygon(arcs) { - return arcs.map(ring); - } - - function geometry(o) { - var type = o.type, coordinates; - switch (type) { - case "GeometryCollection": return {type: type, geometries: o.geometries.map(geometry)}; - case "Point": coordinates = point(o.coordinates); break; - case "MultiPoint": coordinates = o.coordinates.map(point); break; - case "LineString": coordinates = line(o.arcs); break; - case "MultiLineString": coordinates = o.arcs.map(line); break; - case "Polygon": coordinates = polygon(o.arcs); break; - case "MultiPolygon": coordinates = o.arcs.map(polygon); break; - default: return null; - } - return {type: type, coordinates: coordinates}; - } - - return geometry(o); -} - -function $(element, tagName) { - return Array.from(element.getElementsByTagName(tagName)); -} -function normalizeId(id) { - return id[0] === "#" ? id : `#${id}`; -} -function $ns(element, tagName, ns) { - return Array.from(element.getElementsByTagNameNS(ns, tagName)); -} -/** - * get the content of a text node, if any - */ -function nodeVal(node) { - node?.normalize(); - return (node && node.textContent) || ""; -} -/** - * Get one Y child of X, if any, otherwise null - */ -function get1(node, tagName, callback) { - const n = node.getElementsByTagName(tagName); - const result = n.length ? n[0] : null; - if (result && callback) - callback(result); - return result; -} -function get(node, tagName, callback) { - const properties = {}; - if (!node) - return properties; - const n = node.getElementsByTagName(tagName); - const result = n.length ? n[0] : null; - if (result && callback) { - return callback(result, properties); - } - return properties; -} -function val1(node, tagName, callback) { - const val = nodeVal(get1(node, tagName)); - if (val && callback) - return callback(val) || {}; - return {}; -} -function $num(node, tagName, callback) { - const val = parseFloat(nodeVal(get1(node, tagName))); - if (isNaN(val)) - return undefined; - if (val && callback) - return callback(val) || {}; - return {}; -} -function num1(node, tagName, callback) { - const val = parseFloat(nodeVal(get1(node, tagName))); - if (isNaN(val)) - return undefined; - if (callback) - callback(val); - return val; -} -function getMulti(node, propertyNames) { - const properties = {}; - for (const property of propertyNames) { - val1(node, property, (val) => { - properties[property] = val; - }); - } - return properties; -} -function isElement(node) { - return node?.nodeType === 1; -} - -function getLineStyle(node) { - return get(node, "line", (lineStyle) => { - const val = Object.assign({}, val1(lineStyle, "color", (color) => { - return { stroke: `#${color}` }; - }), $num(lineStyle, "opacity", (opacity) => { - return { "stroke-opacity": opacity }; - }), $num(lineStyle, "width", (width) => { - // GPX width is in mm, convert to px with 96 px per inch - return { "stroke-width": (width * 96) / 25.4 }; - })); - return val; - }); -} - -function getExtensions(node) { - let values = []; - if (node === null) - return values; - for (const child of Array.from(node.childNodes)) { - if (!isElement(child)) - continue; - const name = abbreviateName(child.nodeName); - if (name === "gpxtpx:TrackPointExtension") { - // loop again for nested garmin extensions (eg. "gpxtpx:hr") - values = values.concat(getExtensions(child)); - } - else { - // push custom extension (eg. "power") - const val = nodeVal(child); - values.push([name, parseNumeric(val)]); - } - } - return values; -} -function abbreviateName(name) { - return ["heart", "gpxtpx:hr", "hr"].includes(name) ? "heart" : name; -} -function parseNumeric(val) { - const num = parseFloat(val); - return isNaN(num) ? val : num; -} - -function coordPair$1(node) { - const ll = [ - parseFloat(node.getAttribute("lon") || ""), - parseFloat(node.getAttribute("lat") || ""), - ]; - if (isNaN(ll[0]) || isNaN(ll[1])) { - return null; - } - num1(node, "ele", (val) => { - ll.push(val); - }); - const time = get1(node, "time"); - return { - coordinates: ll, - time: time ? nodeVal(time) : null, - extendedValues: getExtensions(get1(node, "extensions")), - }; -} - -function extractProperties(node) { - const properties = getMulti(node, [ - "name", - "cmt", - "desc", - "type", - "time", - "keywords", - ]); - const extensions = Array.from(node.getElementsByTagNameNS("http://www.garmin.com/xmlschemas/GpxExtensions/v3", "*")); - for (const child of extensions) { - if (child.parentNode?.parentNode === node) { - properties[child.tagName.replace(":", "_")] = nodeVal(child); - } - } - const links = $(node, "link"); - if (links.length) { - properties.links = links.map((link) => Object.assign({ href: link.getAttribute("href") }, getMulti(link, ["text", "type"]))); - } - return properties; -} - -/** - * Extract points from a trkseg or rte element. - */ -function getPoints$1(node, pointname) { - const pts = $(node, pointname); - const line = []; - const times = []; - const extendedValues = {}; - for (let i = 0; i < pts.length; i++) { - const c = coordPair$1(pts[i]); - if (!c) { - continue; - } - line.push(c.coordinates); - if (c.time) - times.push(c.time); - for (const [name, val] of c.extendedValues) { - const plural = name === "heart" ? name : name.replace("gpxtpx:", "") + "s"; - if (!extendedValues[plural]) { - extendedValues[plural] = Array(pts.length).fill(null); - } - extendedValues[plural][i] = val; - } - } - if (line.length < 2) - return; // Invalid line in GeoJSON - return { - line: line, - times: times, - extendedValues: extendedValues, - }; -} -/** - * Extract a LineString geometry from a rte - * element. - */ -function getRoute(node) { - const line = getPoints$1(node, "rtept"); - if (!line) - return; - return { - type: "Feature", - properties: Object.assign({ _gpxType: "rte" }, extractProperties(node), getLineStyle(get1(node, "extensions"))), - geometry: { - type: "LineString", - coordinates: line.line, - }, - }; -} -function getTrack(node) { - const segments = $(node, "trkseg"); - const track = []; - const times = []; - const extractedLines = []; - for (const segment of segments) { - const line = getPoints$1(segment, "trkpt"); - if (line) { - extractedLines.push(line); - if (line.times && line.times.length) - times.push(line.times); - } - } - if (extractedLines.length === 0) - return null; - const multi = extractedLines.length > 1; - const properties = Object.assign({ _gpxType: "trk" }, extractProperties(node), getLineStyle(get1(node, "extensions")), times.length - ? { - coordinateProperties: { - times: multi ? times : times[0], - }, - } - : {}); - for (const line of extractedLines) { - track.push(line.line); - if (!properties.coordinateProperties) { - properties.coordinateProperties = {}; - } - const props = properties.coordinateProperties; - const entries = Object.entries(line.extendedValues); - for (let i = 0; i < entries.length; i++) { - const [name, val] = entries[i]; - if (multi) { - if (!props[name]) { - props[name] = extractedLines.map((line) => new Array(line.line.length).fill(null)); - } - props[name][i] = val; - } - else { - props[name] = val; - } - } - } - return { - type: "Feature", - properties: properties, - geometry: multi - ? { - type: "MultiLineString", - coordinates: track, - } - : { - type: "LineString", - coordinates: track[0], - }, - }; -} -/** - * Extract a point, if possible, from a given node, - * which is usually a wpt or trkpt - */ -function getPoint(node) { - const properties = Object.assign(extractProperties(node), getMulti(node, ["sym"])); - const pair = coordPair$1(node); - if (!pair) - return null; - return { - type: "Feature", - properties, - geometry: { - type: "Point", - coordinates: pair.coordinates, - }, - }; -} -/** - * Convert GPX to GeoJSON incrementally, returning - * a [Generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators) - * that yields output feature by feature. - */ -function* gpxGen(node) { - for (const track of $(node, "trk")) { - const feature = getTrack(track); - if (feature) - yield feature; - } - for (const route of $(node, "rte")) { - const feature = getRoute(route); - if (feature) - yield feature; - } - for (const waypoint of $(node, "wpt")) { - const point = getPoint(waypoint); - if (point) - yield point; - } -} -/** - * - * Convert a GPX document to GeoJSON. The first argument, `doc`, must be a GPX - * document as an XML DOM - not as a string. You can get this using jQuery's default - * `.ajax` function or using a bare XMLHttpRequest with the `.response` property - * holding an XML DOM. - * - * The output is a JavaScript object of GeoJSON data, same as `.kml` outputs, with the - * addition of a `_gpxType` property on each `LineString` feature that indicates whether - * the feature was encoded as a route (`rte`) or track (`trk`) in the GPX document. - */ -function gpx(node) { - return { - type: "FeatureCollection", - features: Array.from(gpxGen(node)), - }; -} - -const EXTENSIONS_NS = "http://www.garmin.com/xmlschemas/ActivityExtension/v2"; -const TRACKPOINT_ATTRIBUTES = [ - ["heartRate", "heartRates"], - ["Cadence", "cadences"], - // Extended Trackpoint attributes - ["Speed", "speeds"], - ["Watts", "watts"], -]; -const LAP_ATTRIBUTES = [ - ["TotalTimeSeconds", "totalTimeSeconds"], - ["DistanceMeters", "distanceMeters"], - ["MaximumSpeed", "maxSpeed"], - ["AverageHeartRateBpm", "avgHeartRate"], - ["MaximumHeartRateBpm", "maxHeartRate"], - // Extended Lap attributes - ["AvgSpeed", "avgSpeed"], - ["AvgWatts", "avgWatts"], - ["MaxWatts", "maxWatts"], -]; -function getProperties(node, attributeNames) { - const properties = []; - for (const [tag, alias] of attributeNames) { - let elem = get1(node, tag); - if (!elem) { - const elements = node.getElementsByTagNameNS(EXTENSIONS_NS, tag); - if (elements.length) { - elem = elements[0]; - } - } - const val = parseFloat(nodeVal(elem)); - if (!isNaN(val)) { - properties.push([alias, val]); - } - } - return properties; -} -function coordPair(node) { - const ll = [num1(node, "LongitudeDegrees"), num1(node, "LatitudeDegrees")]; - if (ll[0] === undefined || - isNaN(ll[0]) || - ll[1] === undefined || - isNaN(ll[1])) { - return null; - } - const heartRate = get1(node, "HeartRateBpm"); - const time = nodeVal(get1(node, "Time")); - get1(node, "AltitudeMeters", (alt) => { - const a = parseFloat(nodeVal(alt)); - if (!isNaN(a)) { - ll.push(a); - } - }); - return { - coordinates: ll, - time: time || null, - heartRate: heartRate ? parseFloat(nodeVal(heartRate)) : null, - extensions: getProperties(node, TRACKPOINT_ATTRIBUTES), - }; -} -function getPoints(node) { - const pts = $(node, "Trackpoint"); - const line = []; - const times = []; - const heartRates = []; - if (pts.length < 2) - return null; // Invalid line in GeoJSON - const extendedProperties = {}; - const result = { extendedProperties }; - for (let i = 0; i < pts.length; i++) { - const c = coordPair(pts[i]); - if (c === null) - continue; - line.push(c.coordinates); - const { time, heartRate, extensions } = c; - if (time) - times.push(time); - if (heartRate) - heartRates.push(heartRate); - for (const [alias, value] of extensions) { - if (!extendedProperties[alias]) { - extendedProperties[alias] = Array(pts.length).fill(null); - } - extendedProperties[alias][i] = value; - } - } - if (line.length < 2) - return null; - return Object.assign(result, { - line: line, - times: times, - heartRates: heartRates, - }); -} -function getLap(node) { - const segments = $(node, "Track"); - const track = []; - const times = []; - const heartRates = []; - const allExtendedProperties = []; - let line; - const properties = Object.assign(Object.fromEntries(getProperties(node, LAP_ATTRIBUTES)), get(node, "Name", (nameElement) => { - return { name: nodeVal(nameElement) }; - })); - for (const segment of segments) { - line = getPoints(segment); - if (line) { - track.push(line.line); - if (line.times.length) - times.push(line.times); - if (line.heartRates.length) - heartRates.push(line.heartRates); - allExtendedProperties.push(line.extendedProperties); - } - } - for (let i = 0; i < allExtendedProperties.length; i++) { - const extendedProperties = allExtendedProperties[i]; - for (const property in extendedProperties) { - if (segments.length === 1) { - if (line) { - properties[property] = line.extendedProperties[property]; - } - } - else { - if (!properties[property]) { - properties[property] = track.map((track) => Array(track.length).fill(null)); - } - properties[property][i] = extendedProperties[property]; - } - } - } - if (track.length === 0) - return null; - if (times.length || heartRates.length) { - properties.coordinateProperties = Object.assign(times.length - ? { - times: track.length === 1 ? times[0] : times, - } - : {}, heartRates.length - ? { - heart: track.length === 1 ? heartRates[0] : heartRates, - } - : {}); - } - return { - type: "Feature", - properties: properties, - geometry: track.length === 1 - ? { - type: "LineString", - coordinates: track[0], - } - : { - type: "MultiLineString", - coordinates: track, - }, - }; -} -/** - * Incrementally convert a TCX document to GeoJSON. The - * first argument, `doc`, must be a TCX - * document as an XML DOM - not as a string. - */ -function* tcxGen(node) { - for (const lap of $(node, "Lap")) { - const feature = getLap(lap); - if (feature) - yield feature; - } - for (const course of $(node, "Courses")) { - const feature = getLap(course); - if (feature) - yield feature; - } -} -/** - * Convert a TCX document to GeoJSON. The first argument, `doc`, must be a TCX - * document as an XML DOM - not as a string. - */ -function tcx(node) { - return { - type: "FeatureCollection", - features: Array.from(tcxGen(node)), - }; -} - -function fixColor(v, prefix) { - const properties = {}; - const colorProp = prefix == "stroke" || prefix === "fill" ? prefix : prefix + "-color"; - if (v[0] === "#") { - v = v.substring(1); - } - if (v.length === 6 || v.length === 3) { - properties[colorProp] = "#" + v; - } - else if (v.length === 8) { - properties[prefix + "-opacity"] = parseInt(v.substring(0, 2), 16) / 255; - properties[colorProp] = - "#" + v.substring(6, 8) + v.substring(4, 6) + v.substring(2, 4); - } - return properties; -} - -function numericProperty(node, source, target) { - const properties = {}; - num1(node, source, (val) => { - properties[target] = val; - }); - return properties; -} -function getColor(node, output) { - return get(node, "color", (elem) => fixColor(nodeVal(elem), output)); -} -function extractIconHref(node) { - return get(node, "Icon", (icon, properties) => { - val1(icon, "href", (href) => { - properties.icon = href; - }); - return properties; - }); -} -function extractIcon(node) { - return get(node, "IconStyle", (iconStyle) => { - return Object.assign(getColor(iconStyle, "icon"), numericProperty(iconStyle, "scale", "icon-scale"), numericProperty(iconStyle, "heading", "icon-heading"), get(iconStyle, "hotSpot", (hotspot) => { - const left = parseFloat(hotspot.getAttribute("x") || ""); - const top = parseFloat(hotspot.getAttribute("y") || ""); - const xunits = hotspot.getAttribute("xunits") || ""; - const yunits = hotspot.getAttribute("yunits") || ""; - if (!isNaN(left) && !isNaN(top)) - return { - "icon-offset": [left, top], - "icon-offset-units": [xunits, yunits], - }; - return {}; - }), extractIconHref(iconStyle)); - }); -} -function extractLabel(node) { - return get(node, "LabelStyle", (labelStyle) => { - return Object.assign(getColor(labelStyle, "label"), numericProperty(labelStyle, "scale", "label-scale")); - }); -} -function extractLine(node) { - return get(node, "LineStyle", (lineStyle) => { - return Object.assign(getColor(lineStyle, "stroke"), numericProperty(lineStyle, "width", "stroke-width")); - }); -} -function extractPoly(node) { - return get(node, "PolyStyle", (polyStyle, properties) => { - return Object.assign(properties, get(polyStyle, "color", (elem) => fixColor(nodeVal(elem), "fill")), val1(polyStyle, "fill", (fill) => { - if (fill === "0") - return { "fill-opacity": 0 }; - }), val1(polyStyle, "outline", (outline) => { - if (outline === "0") - return { "stroke-opacity": 0 }; - })); - }); -} -function extractStyle(node) { - return Object.assign({}, extractPoly(node), extractLine(node), extractLabel(node), extractIcon(node)); -} - -const toNumber = (x) => Number(x); -const typeConverters = { - string: (x) => x, - int: toNumber, - uint: toNumber, - short: toNumber, - ushort: toNumber, - float: toNumber, - double: toNumber, - bool: (x) => Boolean(x), -}; -function extractExtendedData(node, schema) { - return get(node, "ExtendedData", (extendedData, properties) => { - for (const data of $(extendedData, "Data")) { - properties[data.getAttribute("name") || ""] = nodeVal(get1(data, "value")); - } - for (const simpleData of $(extendedData, "SimpleData")) { - const name = simpleData.getAttribute("name") || ""; - const typeConverter = schema[name] || typeConverters.string; - properties[name] = typeConverter(nodeVal(simpleData)); - } - return properties; - }); -} -function getMaybeHTMLDescription(node) { - const descriptionNode = get1(node, "description"); - for (const c of Array.from(descriptionNode?.childNodes || [])) { - if (c.nodeType === 4) { - return { - description: { - "@type": "html", - value: nodeVal(c), - }, - }; - } - } - return {}; -} -function extractTimeSpan(node) { - return get(node, "TimeSpan", (timeSpan) => { - return { - timespan: { - begin: nodeVal(get1(timeSpan, "begin")), - end: nodeVal(get1(timeSpan, "end")), - }, - }; - }); -} -function extractTimeStamp(node) { - return get(node, "TimeStamp", (timeStamp) => { - return { timestamp: nodeVal(get1(timeStamp, "when")) }; - }); -} -function extractCascadedStyle(node, styleMap) { - return val1(node, "styleUrl", (styleUrl) => { - styleUrl = normalizeId(styleUrl); - if (styleMap[styleUrl]) { - return Object.assign({ styleUrl }, styleMap[styleUrl]); - } - // For backward-compatibility. Should we still include - // styleUrl even if it's not resolved? - return { styleUrl }; - }); -} - -const removeSpace = /\s*/g; -const trimSpace = /^\s*|\s*$/g; -const splitSpace = /\s+/; -/** - * Get one coordinate from a coordinate array, if any - */ -function coord1(value) { - return value - .replace(removeSpace, "") - .split(",") - .map(parseFloat) - .filter((num) => !isNaN(num)) - .slice(0, 3); -} -/** - * Get all coordinates from a coordinate array as [[],[]] - */ -function coord(value) { - return value - .replace(trimSpace, "") - .split(splitSpace) - .map(coord1) - .filter((coord) => { - return coord.length >= 2; - }); -} -function gxCoords(node) { - let elems = $(node, "coord"); - if (elems.length === 0) { - elems = $ns(node, "coord", "*"); - } - const coordinates = elems.map((elem) => { - return nodeVal(elem).split(" ").map(parseFloat); - }); - if (coordinates.length === 0) { - return null; - } - return { - geometry: coordinates.length > 2 - ? { - type: "LineString", - coordinates, - } - : { - type: "Point", - coordinates: coordinates[0], - }, - times: $(node, "when").map((elem) => nodeVal(elem)), - }; -} -function fixRing(ring) { - if (ring.length === 0) - return ring; - const first = ring[0]; - const last = ring[ring.length - 1]; - let equal = true; - for (let i = 0; i < Math.max(first.length, last.length); i++) { - if (first[i] !== last[i]) { - equal = false; - break; - } - } - if (!equal) { - return ring.concat([ring[0]]); - } - return ring; -} -function getCoordinates(node) { - return nodeVal(get1(node, "coordinates")); -} -function getGeometry(node) { - let geometries = []; - let coordTimes = []; - for (let i = 0; i < node.childNodes.length; i++) { - const child = node.childNodes.item(i); - if (isElement(child)) { - switch (child.tagName) { - case "MultiGeometry": - case "MultiTrack": - case "gx:MultiTrack": { - const childGeometries = getGeometry(child); - geometries = geometries.concat(childGeometries.geometries); - coordTimes = coordTimes.concat(childGeometries.coordTimes); - break; - } - case "Point": { - const coordinates = coord1(getCoordinates(child)); - if (coordinates.length >= 2) { - geometries.push({ - type: "Point", - coordinates, - }); - } - break; - } - case "LinearRing": - case "LineString": { - const coordinates = coord(getCoordinates(child)); - if (coordinates.length >= 2) { - geometries.push({ - type: "LineString", - coordinates, - }); - } - break; - } - case "Polygon": { - const coords = []; - for (const linearRing of $(child, "LinearRing")) { - const ring = fixRing(coord(getCoordinates(linearRing))); - if (ring.length >= 4) { - coords.push(ring); - } - } - if (coords.length) { - geometries.push({ - type: "Polygon", - coordinates: coords, - }); - } - break; - } - case "Track": - case "gx:Track": { - const gx = gxCoords(child); - if (!gx) - break; - const { times, geometry } = gx; - geometries.push(geometry); - if (times.length) - coordTimes.push(times); - break; - } - } - } - } - return { - geometries, - coordTimes, - }; -} - -function geometryListToGeometry(geometries) { - return geometries.length === 0 - ? null - : geometries.length === 1 - ? geometries[0] - : { - type: "GeometryCollection", - geometries, - }; -} -function getPlacemark(node, styleMap, schema, options) { - const { coordTimes, geometries } = getGeometry(node); - const geometry = geometryListToGeometry(geometries); - if (!geometry && options.skipNullGeometry) { - return null; - } - const feature = { - type: "Feature", - geometry, - properties: Object.assign(getMulti(node, [ - "name", - "address", - "visibility", - "open", - "phoneNumber", - "description", - ]), getMaybeHTMLDescription(node), extractCascadedStyle(node, styleMap), extractStyle(node), extractExtendedData(node, schema), extractTimeSpan(node), extractTimeStamp(node), coordTimes.length - ? { - coordinateProperties: { - times: coordTimes.length === 1 ? coordTimes[0] : coordTimes, - }, - } - : {}), - }; - if (feature.properties?.visibility !== undefined) { - feature.properties.visibility = feature.properties.visibility !== "0"; - } - const id = node.getAttribute("id"); - if (id !== null && id !== "") - feature.id = id; - return feature; -} - -function getGroundOverlayBox(node) { - const latLonQuad = get1(node, "gx:LatLonQuad"); - if (latLonQuad) { - const ring = fixRing(coord(getCoordinates(node))); - return { - geometry: { - type: "Polygon", - coordinates: [ring], - }, - }; - } - return getLatLonBox(node); -} -const DEGREES_TO_RADIANS = Math.PI / 180; -function rotateBox(bbox, coordinates, rotation) { - const center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]; - return [ - coordinates[0].map((coordinate) => { - const dy = coordinate[1] - center[1]; - const dx = coordinate[0] - center[0]; - const distance = Math.sqrt(Math.pow(dy, 2) + Math.pow(dx, 2)); - const angle = Math.atan2(dy, dx) + rotation * DEGREES_TO_RADIANS; - return [ - center[0] + Math.cos(angle) * distance, - center[1] + Math.sin(angle) * distance, - ]; - }), - ]; -} -function getLatLonBox(node) { - const latLonBox = get1(node, "LatLonBox"); - if (latLonBox) { - const north = num1(latLonBox, "north"); - const west = num1(latLonBox, "west"); - const east = num1(latLonBox, "east"); - const south = num1(latLonBox, "south"); - const rotation = num1(latLonBox, "rotation"); - if (typeof north === "number" && - typeof south === "number" && - typeof west === "number" && - typeof east === "number") { - const bbox = [west, south, east, north]; - let coordinates = [ - [ - [west, north], - [east, north], - [east, south], - [west, south], - [west, north], // top left (again) - ], - ]; - if (typeof rotation === "number") { - coordinates = rotateBox(bbox, coordinates, rotation); - } - return { - bbox, - geometry: { - type: "Polygon", - coordinates, - }, - }; - } - } - return null; -} -function getGroundOverlay(node, styleMap, schema, options) { - const box = getGroundOverlayBox(node); - const geometry = box?.geometry || null; - if (!geometry && options.skipNullGeometry) { - return null; - } - const feature = { - type: "Feature", - geometry, - properties: Object.assign( - /** - * Related to - * https://gist.github.com/tmcw/037a1cb6660d74a392e9da7446540f46 - */ - { "@geometry-type": "groundoverlay" }, getMulti(node, [ - "name", - "address", - "visibility", - "open", - "phoneNumber", - "description", - ]), getMaybeHTMLDescription(node), extractCascadedStyle(node, styleMap), extractStyle(node), extractIconHref(node), extractExtendedData(node, schema), extractTimeSpan(node), extractTimeStamp(node)), - }; - if (box?.bbox) { - feature.bbox = box.bbox; - } - if (feature.properties?.visibility !== undefined) { - feature.properties.visibility = feature.properties.visibility !== "0"; - } - const id = node.getAttribute("id"); - if (id !== null && id !== "") - feature.id = id; - return feature; -} - -function getStyleId(style) { - let id = style.getAttribute("id"); - const parentNode = style.parentNode; - if (!id && - isElement(parentNode) && - parentNode.localName === "CascadingStyle") { - id = parentNode.getAttribute("kml:id") || parentNode.getAttribute("id"); - } - return normalizeId(id || ""); -} -function buildStyleMap(node) { - const styleMap = {}; - for (const style of $(node, "Style")) { - styleMap[getStyleId(style)] = extractStyle(style); - } - for (const map of $(node, "StyleMap")) { - const id = normalizeId(map.getAttribute("id") || ""); - val1(map, "styleUrl", (styleUrl) => { - styleUrl = normalizeId(styleUrl); - if (styleMap[styleUrl]) { - styleMap[id] = styleMap[styleUrl]; - } - }); - } - return styleMap; -} -function buildSchema(node) { - const schema = {}; - for (const field of $(node, "SimpleField")) { - schema[field.getAttribute("name") || ""] = - typeConverters[field.getAttribute("type") || ""] || - typeConverters["string"]; - } - return schema; -} -const FOLDER_PROPS = [ - "name", - "visibility", - "open", - "address", - "description", - "phoneNumber", - "visibility", -]; -function getFolder(node) { - const meta = {}; - for (const child of Array.from(node.childNodes)) { - if (isElement(child) && FOLDER_PROPS.includes(child.tagName)) { - meta[child.tagName] = nodeVal(child); - } - } - return { - type: "folder", - meta, - children: [], - }; -} -/** - * Yield a nested tree with KML folder structure - * - * This generates a tree with the given structure: - * - * ```js - * { - * "type": "root", - * "children": [ - * { - * "type": "folder", - * "meta": { - * "name": "Test" - * }, - * "children": [ - * // ...features and folders - * ] - * } - * // ...features - * ] - * } - * ``` - * - * ### GroundOverlay - * - * GroundOverlay elements are converted into - * `Feature` objects with `Polygon` geometries, - * a property like: - * - * ```json - * { - * "@geometry-type": "groundoverlay" - * } - * ``` - * - * And the ground overlay's image URL in the `href` - * property. Ground overlays will need to be displayed - * with a separate method to other features, depending - * on which map framework you're using. - */ -function kmlWithFolders(node, options = { - skipNullGeometry: false, -}) { - const styleMap = buildStyleMap(node); - const schema = buildSchema(node); - const tree = { type: "root", children: [] }; - function traverse(node, pointer, options) { - if (isElement(node)) { - switch (node.tagName) { - case "GroundOverlay": { - const placemark = getGroundOverlay(node, styleMap, schema, options); - if (placemark) { - pointer.children.push(placemark); - } - break; - } - case "Placemark": { - const placemark = getPlacemark(node, styleMap, schema, options); - if (placemark) { - pointer.children.push(placemark); - } - break; - } - case "Folder": { - const folder = getFolder(node); - pointer.children.push(folder); - pointer = folder; - break; - } - } - } - if (node.childNodes) { - for (let i = 0; i < node.childNodes.length; i++) { - traverse(node.childNodes[i], pointer, options); - } - } - } - traverse(node, tree, options); - return tree; -} -/** - * Convert KML to GeoJSON incrementally, returning - * a [Generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators) - * that yields output feature by feature. - */ -function* kmlGen(node, options = { - skipNullGeometry: false, -}) { - const styleMap = buildStyleMap(node); - const schema = buildSchema(node); - for (const placemark of $(node, "Placemark")) { - const feature = getPlacemark(placemark, styleMap, schema, options); - if (feature) - yield feature; - } - for (const groundOverlay of $(node, "GroundOverlay")) { - const feature = getGroundOverlay(groundOverlay, styleMap, schema, options); - if (feature) - yield feature; - } -} -/** - * Convert a KML document to GeoJSON. The first argument, `doc`, must be a KML - * document as an XML DOM - not as a string. You can get this using jQuery's default - * `.ajax` function or using a bare XMLHttpRequest with the `.response` property - * holding an XML DOM. - * - * The output is a JavaScript object of GeoJSON data. You can convert it to a string - * with [JSON.stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) - * or use it directly in libraries. - */ -function kml(node, options = { - skipNullGeometry: false, -}) { - return { - type: "FeatureCollection", - features: Array.from(kmlGen(node, options)), - }; -} - -var toGeoJson = /*#__PURE__*/Object.freeze({ - __proto__: null, - gpx: gpx, - gpxGen: gpxGen, - kml: kml, - kmlGen: kmlGen, - kmlWithFolders: kmlWithFolders, - tcx: tcx, - tcxGen: tcxGen -}); - -var polyline = {exports: {}}; - -(function (module) { - - /** - * Based off of [the offical Google document](https://developers.google.com/maps/documentation/utilities/polylinealgorithm) - * - * Some parts from [this implementation](http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/PolylineEncoder.js) - * by [Mark McClure](http://facstaff.unca.edu/mcmcclur/) - * - * @module polyline - */ - - var polyline = {}; - - function py2_round(value) { - // Google's polyline algorithm uses the same rounding strategy as Python 2, which is different from JS for negative values - return Math.floor(Math.abs(value) + 0.5) * (value >= 0 ? 1 : -1); - } - - function encode(current, previous, factor) { - current = py2_round(current * factor); - previous = py2_round(previous * factor); - var coordinate = (current - previous) * 2; - if (coordinate < 0) { - coordinate = -coordinate - 1; - } - var output = ''; - while (coordinate >= 0x20) { - output += String.fromCharCode((0x20 | (coordinate & 0x1f)) + 63); - coordinate /= 32; - } - output += String.fromCharCode((coordinate | 0) + 63); - return output; - } - - /** - * Decodes to a [latitude, longitude] coordinates array. - * - * This is adapted from the implementation in Project-OSRM. - * - * @param {String} str - * @param {Number} precision - * @returns {Array} - * - * @see https://github.com/Project-OSRM/osrm-frontend/blob/master/WebContent/routing/OSRM.RoutingGeometry.js - */ - polyline.decode = function(str, precision) { - var index = 0, - lat = 0, - lng = 0, - coordinates = [], - shift = 0, - result = 0, - byte = null, - latitude_change, - longitude_change, - factor = Math.pow(10, Number.isInteger(precision) ? precision : 5); - - // Coordinates have variable length when encoded, so just keep - // track of whether we've hit the end of the string. In each - // loop iteration, a single coordinate is decoded. - while (index < str.length) { - - // Reset shift, result, and byte - byte = null; - shift = 1; - result = 0; - - do { - byte = str.charCodeAt(index++) - 63; - result += (byte & 0x1f) * shift; - shift *= 32; - } while (byte >= 0x20); - - latitude_change = (result & 1) ? ((-result - 1) / 2) : (result / 2); - - shift = 1; - result = 0; - - do { - byte = str.charCodeAt(index++) - 63; - result += (byte & 0x1f) * shift; - shift *= 32; - } while (byte >= 0x20); - - longitude_change = (result & 1) ? ((-result - 1) / 2) : (result / 2); - - lat += latitude_change; - lng += longitude_change; - - coordinates.push([lat / factor, lng / factor]); - } - - return coordinates; - }; - - /** - * Encodes the given [latitude, longitude] coordinates array. - * - * @param {Array.>} coordinates - * @param {Number} precision - * @returns {String} - */ - polyline.encode = function(coordinates, precision) { - if (!coordinates.length) { return ''; } - - var factor = Math.pow(10, Number.isInteger(precision) ? precision : 5), - output = encode(coordinates[0][0], 0, factor) + encode(coordinates[0][1], 0, factor); - - for (var i = 1; i < coordinates.length; i++) { - var a = coordinates[i], b = coordinates[i - 1]; - output += encode(a[0], b[0], factor); - output += encode(a[1], b[1], factor); - } - - return output; - }; - - function flipped(coords) { - var flipped = []; - for (var i = 0; i < coords.length; i++) { - var coord = coords[i].slice(); - flipped.push([coord[1], coord[0]]); - } - return flipped; - } - - /** - * Encodes a GeoJSON LineString feature/geometry. - * - * @param {Object} geojson - * @param {Number} precision - * @returns {String} - */ - polyline.fromGeoJSON = function(geojson, precision) { - if (geojson && geojson.type === 'Feature') { - geojson = geojson.geometry; - } - if (!geojson || geojson.type !== 'LineString') { - throw new Error('Input must be a GeoJSON LineString'); - } - return polyline.encode(flipped(geojson.coordinates), precision); - }; - - /** - * Decodes to a GeoJSON LineString geometry. - * - * @param {String} str - * @param {Number} precision - * @returns {Object} - */ - polyline.toGeoJSON = function(str, precision) { - var coords = polyline.decode(str, precision); - return { - type: 'LineString', - coordinates: flipped(coords) - }; - }; - - if (module.exports) { - module.exports = polyline; - } -} (polyline)); - -var polylineExports = polyline.exports; - -var utils = (() => { - - const purgeProps = (obj, blacklist) => { - if (obj) { - let rs = Object.assign({}, obj); - if (blacklist) { - for (let prop of blacklist) { - delete rs[prop]; - } - } - return rs; - } - return {}; - }; - - const mergeProps = (obj1, obj2) => { - obj1 = obj1 ? obj1 : {}; - obj2 = obj2 ? obj2 : {}; - return Object.assign(obj1, obj2); - }; - - const first = a => a[0]; - const last = a => a[a.length - 1]; - const coordsToKey = a => a.join(','); - - const addToMap = (m, k, v) => { - let a = m[k]; - if (a) { - a.push(v); - } else { - m[k] = [v]; - } - }; - - const removeFromMap = (m, k, v) => { - let a = m[k]; - let idx = null; - if (a && (idx = a.indexOf(v)) >= 0) { - a.splice(idx, 1); - } - }; - - const getFirstFromMap = (m, k) => { - let a = m[k]; - if (a && a.length > 0) { - return a[0]; - } - return null; - }; - - // need 3+ different points to form a ring, here using > 3 is 'coz a the first and the last points are actually the same - const isRing = a => a.length > 3 && coordsToKey(first(a)) === coordsToKey(last(a)); - - const ringDirection = (a, xIdx, yIdx) => { - xIdx = xIdx || 0, yIdx = yIdx || 1; - // get the index of the point which has the maximum x value - let m = a.reduce((maxxIdx, v, idx) => a[maxxIdx][xIdx] > v[xIdx] ? maxxIdx : idx, 0); - // 'coz the first point is virtually the same one as the last point, - // we need to skip a.length - 1 for left when m = 0, - // and skip 0 for right when m = a.length - 1; - let l = m <= 0 ? a.length - 2 : m - 1, r = m >= a.length - 1 ? 1 : m + 1; - let xa = a[l][xIdx], xb = a[m][xIdx], xc = a[r][xIdx]; - let ya = a[l][yIdx], yb = a[m][yIdx], yc = a[r][yIdx]; - let det = (xb - xa) * (yc - ya) - (xc - xa) * (yb - ya); - return det < 0 ? 'clockwise' : 'counterclockwise'; - }; - - const ptInsidePolygon = (pt, polygon, xIdx, yIdx) => { - xIdx = xIdx || 0, yIdx = yIdx || 1; - let result = false; - for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { - if ((polygon[i][xIdx] <= pt[xIdx] && pt[xIdx] < polygon[j][xIdx] || - polygon[j][xIdx] <= pt[xIdx] && pt[xIdx] < polygon[i][xIdx]) && - pt[yIdx] < (polygon[j][yIdx] - polygon[i][yIdx]) * (pt[xIdx] - polygon[i][xIdx]) / (polygon[j][xIdx] - polygon[i][xIdx]) + polygon[i][yIdx]) { - result = !result; - } - - } - return result; - }; - - const strToFloat = el => el instanceof Array ? el.map(strToFloat) : parseFloat(el); - - class RefElements extends Map { - constructor() { - super(); - this.binders = []; - } - - add(k, v) { - if (!this.has(k)) { - this.set(k, v); - } - // suppress duplcated key error - // else - // throw `Error: adding duplicated key '${k}' to RefElements`; - } - - addBinder(binder) { - this.binders.push(binder); - } - - bindAll() { - this.binders.forEach(binder => binder.bind()); - } - } - - class LateBinder { - constructor(container, valueFunc, ctx, args) { - this.container = container; - this.valueFunc = valueFunc; - this.ctx = ctx; - this.args = args; - } - - bind() { - let v = this.valueFunc.apply(this.ctx, this.args); - if (this.container instanceof Array) { - let idx = this.container.indexOf(this); - if (idx >= 0) { - let args = [idx, 1]; - if (v) { - args.push(v); - } - [].splice.apply(this.container, args); - } - } else if (typeof this.container === 'object') { - let k = Object.keys(this.container).find(v => this.container[v] === this); - if (k) { - if (v) { - this.container[k] = v; - } else { - delete this.container[k]; - } - } - } - } - } - - class WayCollection extends Array { - constructor() { - super(); - this.firstMap = {}; - this.lastMap = {}; - } - - addWay(way) { - way = way.toCoordsArray(); - if (way.length > 0) { - this.push(way); - addToMap(this.firstMap, coordsToKey(first(way)), way); - addToMap(this.lastMap, coordsToKey(last(way)), way); - } - } - - toStrings() { - let strings = [], way = null; - while (way = this.shift()) { - removeFromMap(this.firstMap, coordsToKey(first(way)), way); - removeFromMap(this.lastMap, coordsToKey(last(way)), way); - let current = way, next = null; - do { - let key = coordsToKey(last(current)), shouldReverse = false; - - next = getFirstFromMap(this.firstMap, key); - if (!next) { - next = getFirstFromMap(this.lastMap, key); - shouldReverse = true; - } - - if (next) { - this.splice(this.indexOf(next), 1); - removeFromMap(this.firstMap, coordsToKey(first(next)), next); - removeFromMap(this.lastMap, coordsToKey(last(next)), next); - if (shouldReverse) { - // always reverse shorter one to save time - if (next.length > current.length) { - [current, next] = [next, current]; - } - next.reverse(); - } - - current = current.concat(next.slice(1)); - } - } while (next); - strings.push(strToFloat(current)); - } - - return strings; - } - - toRings(direction) { - let strings = this.toStrings(); - let rings = [], string = null; - while (string = strings.shift()) { - if (isRing(string)) { - if (ringDirection(string) !== direction) { - string.reverse(); - } - rings.push(string); - } - } - return rings; - } - } - - return { - purgeProps, mergeProps, - first, last, coordsToKey, - addToMap, removeFromMap, getFirstFromMap, - isRing, ringDirection, ptInsidePolygon, strToFloat, - RefElements, LateBinder, WayCollection - }; -})(); - -var building = { -}; -var highway = { - whitelist: [ - "services", - "rest_area", - "escape", - "elevator" - ] -}; -var natural = { - blacklist: [ - "coastline", - "cliff", - "ridge", - "arete", - "tree_row" - ] -}; -var landuse = { -}; -var waterway = { - whitelist: [ - "riverbank", - "dock", - "boatyard", - "dam" - ] -}; -var amenity = { -}; -var leisure = { -}; -var barrier = { - whitelist: [ - "city_wall", - "ditch", - "hedge", - "retaining_wall", - "wall", - "spikes" - ] -}; -var railway = { - whitelist: [ - "station", - "turntable", - "roundhouse", - "platform" - ] -}; -var area = { -}; -var boundary = { -}; -var man_made = { - blacklist: [ - "cutline", - "embankment", - "pipeline" - ] -}; -var power = { - whitelist: [ - "plant", - "substation", - "generator", - "transformer" - ] -}; -var place = { -}; -var shop = { -}; -var aeroway = { - blacklist: [ - "taxiway" - ] -}; -var tourism = { -}; -var historic = { -}; -var public_transport = { -}; -var office = { -}; -var military = { -}; -var ruins = { -}; -var craft = { -}; -var golf = { -}; -var indoor = { -}; -var require$$1 = { - building: building, - highway: highway, - natural: natural, - landuse: landuse, - waterway: waterway, - amenity: amenity, - leisure: leisure, - barrier: barrier, - railway: railway, - area: area, - boundary: boundary, - man_made: man_made, - power: power, - place: place, - shop: shop, - aeroway: aeroway, - tourism: tourism, - historic: historic, - public_transport: public_transport, - office: office, - "building:part": { -}, - military: military, - ruins: ruins, - "area:highway": { -}, - craft: craft, - golf: golf, - indoor: indoor -}; - -var osmobjs = (() => { - - const { first, last, coordsToKey, - addToMap, removeFromMap, getFirstFromMap, - isRing, ringDirection, ptInsidePolygon, strToFloat, - LateBinder, WayCollection } = utils, - polygonTags = require$$1; - - class OsmObject { - constructor(type, id, refElems) { - this.type = type; - this.id = id; - this.refElems = refElems; - this.tags = {}; - this.props = { id: this.getCompositeId() }; - this.refCount = 0; - this.hasTag = false; - if (refElems) { - refElems.add(this.getCompositeId(), this); - } - } - - addTags(tags) { - this.tags = Object.assign(this.tags, tags); - this.hasTag = tags ? true : false; - } - - addTag(k, v) { - this.tags[k] = v; - this.hasTag = k ? true : false; - } - - addProp(k, v) { - this.props[k] = v; - } - - addProps(props) { - this.props = Object.assign(this.props, props); - } - - getCompositeId() { - return `${this.type}/${this.id}`; - } - - getProps() { - return Object.assign(this.props, this.tags); - } - - toFeatureArray() { - return []; - } - } - - class Node extends OsmObject { - constructor(id, refElems) { - super('node', id, refElems); - this.latLng = null; - } - - setLatLng(latLng) { - this.latLng = latLng; - } - - toFeatureArray() { - if (this.latLng) { - return [{ - type: 'Feature', - id: this.getCompositeId(), - properties: this.getProps(), - geometry: { - type: 'Point', - coordinates: strToFloat([this.latLng.lon, this.latLng.lat]) - } - }]; - } - - return []; - } - - getLatLng() { - return this.latLng; - } - } - - class Way extends OsmObject { - constructor(id, refElems) { - super('way', id, refElems); - this.latLngArray = []; - this.isPolygon = false; - } - - addLatLng(latLng) { - this.latLngArray.push(latLng); - } - - setLatLngArray(latLngArray) { - this.latLngArray = latLngArray; - } - - addNodeRef(ref) { - let binder = new LateBinder(this.latLngArray, function (id) { - let node = this.refElems.get(`node/${id}`); - if (node) { - node.refCount++; - return node.getLatLng(); - } - }, this, [ref]); - - this.latLngArray.push(binder); - this.refElems.addBinder(binder); - } - - analyzeGeometryType(k, v) { - let o = polygonTags[k]; - if (o) { - this.isPolygon = true; - if (o.whitelist) { - this.isPolygon = o.whitelist.indexOf(v) >= 0 ? true : false; - } else if (o.blacklist) { - this.isPolygon = o.blacklist.indexOf(v) >= 0 ? false : true; - } - } - } - - addTags(tags) { - super.addTags(tags); - for (let [k, v] of Object.entries(tags)) { - this.analyzeGeometryType(k, v); - } - } - - addTag(k, v) { - super.addTag(k, v); - this.analyzeGeometryType(k, v); - } - - toCoordsArray() { - return this.latLngArray.map(latLng => [latLng.lon, latLng.lat]); - } - - toFeatureArray() { - let coordsArray = this.toCoordsArray(); - if (coordsArray.length > 1) { - coordsArray = strToFloat(coordsArray); - let feature = { - type: 'Feature', - id: this.getCompositeId(), - properties: this.getProps(), - geometry: { - type: 'LineString', - coordinates: coordsArray - } - }; - - if (this.isPolygon && isRing(coordsArray)) { - if (ringDirection(coordsArray) !== 'counterclockwise') { - coordsArray.reverse(); - } - - feature.geometry = { - type: 'Polygon', - coordinates: [coordsArray] - }; - - return [feature]; - } - - return [feature]; - } - - return []; - } - } - - class Relation extends OsmObject { - constructor(id, refElems) { - super('relation', id, refElems); - this.relations = []; - this.nodes = []; - this.bounds = null; - } - - setBounds(bounds) { - this.bounds = bounds; - } - - addMember(member) { - switch (member.type) { - // super relation, need to do combination - case 'relation': - let binder = new LateBinder(this.relations, function (id) { - let relation = this.refElems.get(`relation/${id}`); - if (relation) { - relation.refCount++; - return relation; - } - }, this, [member.ref]); - this.relations.push(binder); - this.refElems.addBinder(binder); - break; - - case 'way': - if (!member.role) { - member.role = ''; - } - let ways = this[member.role]; - if (!ways) { - ways = this[member.role] = []; - } - if (member.geometry) { - let way = new Way(member.ref, this.refElems); - way.setLatLngArray(member.geometry); - way.refCount++; - ways.push(way); - } else if (member.nodes) { - let way = new Way(member.ref, this.refElems); - for (let nid of member.nodes) { - way.addNodeRef(nid); - } - way.refCount++; - ways.push(way); - } else { - let binder = new LateBinder(ways, function (id) { - let way = this.refElems.get(`way/${id}`); - if (way) { - way.refCount++; - return way; - } - }, this, [member.ref]); - ways.push(binder); - this.refElems.addBinder(binder); - } - break; - - case 'node': - let node = null; - if (member.lat && member.lon) { - node = new Node(member.ref, this.refElems); - node.setLatLng({ lon: member.lon, lat: member.lat }); - if (member.tags) { - node.addTags(member.tags); - } - for (let [k, v] of Object.entries(member)) { - if (['id', 'type', 'lat', 'lon'].indexOf(k) < 0) { - node.addProp(k, v); - } - } - - node.refCount++; - this.nodes.push(node); - } else { - let binder = new LateBinder(this.nodes, function (id) { - let node = this.refElems.get(`node/${id}`); - if (node) { - node.refCount++; - return node; - } - }, this, [member.ref]); - this.nodes.push(binder); - this.refElems.addBinder(binder); - } - break; - } - } - - toFeatureArray() { - const constructStringGeometry = (ws) => { - let strings = ws ? ws.toStrings() : []; - if (strings.length > 0) { - if (strings.length === 1) return { - type: 'LineString', - coordinates: strings[0] - } - - return { - type: 'MultiLineString', - coordinates: strings - } - } - return null; - }; - - const constructPolygonGeometry = (ows, iws) => { - let outerRings = ows ? ows.toRings('counterclockwise') : [], - innerRings = iws ? iws.toRings('clockwise') : []; - - if (outerRings.length > 0) { - let compositPolyons = []; - - let ring = null; - for (ring of outerRings) - compositPolyons.push([ring]); - - // link inner polygons to outer containers - while (ring = innerRings.shift()) { - for (let idx in outerRings) { - if (ptInsidePolygon(first(ring), outerRings[idx])) { - compositPolyons[idx].push(ring); - break; - } - } - } - - // construct the Polygon/MultiPolygon geometry - if (compositPolyons.length === 1) { - return { - type: 'Polygon', - coordinates: compositPolyons[0] - }; - } - - return { - type: 'MultiPolygon', - coordinates: compositPolyons - } - } - - return null; - }; - - let polygonFeatures = [], stringFeatures = [], pointFeatures = []; - const waysFieldNames = ['outer', 'inner', '']; - // need to do combination when there're nested relations - for (let relation of this.relations) { - if (relation) { - for (let fieldName of waysFieldNames) { - let ways = relation[fieldName]; - if (ways) { - let thisWays = this[fieldName]; - if (thisWays) { - [].splice.apply(thisWays, [thisWays.length, 0].concat(ways)); - } else { - this[fieldName] = ways; - } - } - } - } - } - - for (let fieldName of waysFieldNames) { - let ways = this[fieldName]; - if (ways) { - this[fieldName] = new WayCollection(); - for (let way of ways) { - this[fieldName].addWay(way); - } - } - } - - let geometry = null; - - let feature = { - type: 'Feature', - id: this.getCompositeId(), - bbox: this.bounds, - properties: this.getProps() - }; - - if (!this.bounds) { - delete feature.bbox; - } - - if (this.outer) { - geometry = constructPolygonGeometry(this.outer, this.inner); - if (geometry) { - feature.geometry = geometry; - polygonFeatures.push(feature); - } - } - else if (this['']) { - geometry = constructStringGeometry(this['']); - if (geometry) { - feature.geometry = geometry; - stringFeatures.push(feature); - } - } - - for (let node of this.nodes) { - pointFeatures = pointFeatures.concat(node.toFeatureArray()); - } - - return polygonFeatures.concat(stringFeatures).concat(pointFeatures); - } - } - - return { Node, Way, Relation }; -})(); - -var xmlparser = (() => { - - function conditioned(evt) { - return evt.match(/^(.+?)\[(.+?)\]>$/g) != null; - } - - function parseEvent(evt) { - let match = /^(.+?)\[(.+?)\]>$/g.exec(evt); - if (match) { - return { evt: match[1] + '>', exp: match[2] }; - } - return { evt: evt }; - } - - function genConditionFunc(cond) { - let body = 'return ' + cond.replace(/(\$.+?)(?=[=!.])/g, 'node.$&') + ';'; - return new Function('node', body); - } - - return class { - constructor(opts) { - if (opts) { - this.queryParent = opts.queryParent ? true : false; - this.progressive = opts.progressive; - if (this.queryParent) { - this.parentMap = new WeakMap(); - } - } - this.evtListeners = {}; - } - - parse(xml, parent, dir) { - dir = dir ? dir + '.' : ''; - let nodeRegEx = /<([^ >\/]+)(.*?)>/mg, nodeMatch = null, nodes = []; - while (nodeMatch = nodeRegEx.exec(xml)) { - let tag = nodeMatch[1], node = { $tag: tag }, fullTag = dir + tag; - - let attrText = nodeMatch[2].trim(), closed = false; - if (attrText.endsWith('/') || tag.startsWith('?') || tag.startsWith('!')) { - closed = true; - } - - let attRegEx1 = /([^ ]+?)="(.+?)"/g, attRegEx2 = /([^ ]+?)='(.+?)'/g; - let attMatch = null, hasAttrs = false; - while (attMatch = attRegEx1.exec(attrText)) { - hasAttrs = true; - node[attMatch[1]] = attMatch[2]; - } - if (!hasAttrs) - while (attMatch = attRegEx2.exec(attrText)) { - hasAttrs = true; - node[attMatch[1]] = attMatch[2]; - } - - if (!hasAttrs && attrText !== '') { - node.text = attrText; - } - if (this.progressive) { - this.emit(`<${fullTag}>`, node, parent); - } - - if (!closed) { - let innerRegEx = new RegExp(`([^]+?)<\/${tag}>`, 'g'); - innerRegEx.lastIndex = nodeRegEx.lastIndex; - let innerMatch = innerRegEx.exec(xml); - if (innerMatch && innerMatch[1]) { - nodeRegEx.lastIndex = innerRegEx.lastIndex; - let innerNodes = this.parse(innerMatch[1], node, fullTag); - if (innerNodes.length > 0) { - node.$innerNodes = innerNodes; - } else { - node.$innerText = innerMatch[1]; - } - } - } - if (this.queryParent && parent) { - this.parentMap.set(node, parent); - } - - if (this.progressive) { - this.emit(``, node, parent); - } - - nodes.push(node); - } - - return nodes; - } - - getParent(node) { - if (this.queryParent) { - return this.parentMap.get(node); - } - return null; - } - - #addListener(evt, func) { - let funcs = this.evtListeners[evt]; - if (funcs) { - funcs.push(func); - } else { - this.evtListeners[evt] = [func]; - } - } - - // support javascript condition for the last tag - addListener(evt, func) { - if (conditioned(evt)) { - // func.prototype = evt; - evt = parseEvent(evt); - func.condition = genConditionFunc(evt.exp); - evt = evt.evt; - } - this.#addListener(evt, func); - } - - #removeListener(evt, func) { - let funcs = this.evtListeners[evt]; - let idx = null; - if (funcs && (idx = funcs.indexOf(func)) >= 0) { - funcs.splice(idx, 1); - } - } - - removeListener(evt, func) { - if (conditioned(evt)) { - evt = parseEvent(evt); - evt = evt.evt; - } - this.#removeListener(evt, func); - } - - emit(evt, ...args) { - let funcs = this.evtListeners[evt]; - if (funcs) { - for (let func of funcs) { - if (func.condition) { - if (func.condition.apply(null, args) === true) { - func.apply(null, args); - } - } else { - func.apply(null, args); - } - } - } - } - - on(evt, func) { - this.addListener(evt, func); - } - - off(evt, func) { - this.removeListener(evt, func); - } - }; -})(); - -const { Node, Way, Relation } = osmobjs, - { purgeProps, RefElements } = utils, - XmlParser = xmlparser; - -var lib = (osm, opts) => { - let completeFeature = false, renderTagged = false, excludeWay = true; - - const parseOpts = opts => { - if (opts) { - completeFeature = opts.completeFeature || opts.allFeatures ? true : false; - renderTagged = opts.renderTagged ? true : false; - let wayOpt = opts.suppressWay || opts.excludeWay; - if (wayOpt !== undefined && !wayOpt) { - excludeWay = false; - } - } - }; - - parseOpts(opts); - - const detectFormat = osm => { - if (osm.elements) { - return 'json'; - } - if (osm.indexOf('= 0) { - return 'xml'; - } - if (osm.trim().startsWith('{')) { - return 'json-raw'; - } - return 'invalid'; - }; - - let format = detectFormat(osm); - - let refElements = new RefElements(), featureArray = []; - - const analyzeFeaturesFromJson = osm => { - for (let elem of osm.elements) { - switch (elem.type) { - case 'node': - let node = new Node(elem.id, refElements); - if (elem.tags) { - node.addTags(elem.tags); - } - node.addProps(purgeProps(elem, ['id', 'type', 'tags', 'lat', 'lon'])); - node.setLatLng(elem); - break; - - case 'way': - let way = new Way(elem.id, refElements); - if (elem.tags) { - way.addTags(elem.tags); - } - way.addProps(purgeProps(elem, ['id', 'type', 'tags', 'nodes', 'geometry'])); - if (elem.nodes) { - for (let n of elem.nodes) { - way.addNodeRef(n); - } - } else if (elem.geometry) { - way.setLatLngArray(elem.geometry); - } - break; - - case 'relation': - let relation = new Relation(elem.id, refElements); - if (elem.bounds) { - relation.setBounds([parseFloat(elem.bounds.minlon), parseFloat(elem.bounds.minlat), parseFloat(elem.bounds.maxlon), parseFloat(elem.bounds.maxlat)]); - } - if (elem.tags) { - relation.addTags(elem.tags); - } - relation.addProps(purgeProps(elem, ['id', 'type', 'tags', 'bounds', 'members'])); - if (elem.members) { - for (let member of elem.members) { - relation.addMember(member); - } - } - break; - } - } - }; - - const analyzeFeaturesFromXml = osm => { - const xmlParser = new XmlParser({ progressive: true }); - - xmlParser.on('', node => { - let nd = new Node(node.id, refElements); - for (let [k, v] of Object.entries(node)) - if (!k.startsWith('$') && ['id', 'lon', 'lat'].indexOf(k) < 0) { - nd.addProp(k, v); - } - nd.setLatLng(node); - if (node.$innerNodes) { - for (let ind of node.$innerNodes) { - if (ind.$tag === 'tag') { - nd.addTag(ind.k, ind.v); - } - } - } - }); - - xmlParser.on('', node => { - let way = new Way(node.id, refElements); - for (let [k, v] of Object.entries(node)) { - if (!k.startsWith('$') && ['id'].indexOf(k) < 0) { - way.addProp(k, v); - } - } - if (node.$innerNodes) { - for (let ind of node.$innerNodes) { - if (ind.$tag === 'nd') { - if (ind.lon && ind.lat) { - way.addLatLng(ind); - } else if (ind.ref) { - way.addNodeRef(ind.ref); - } - } else if (ind.$tag === 'tag') - way.addTag(ind.k, ind.v); - } - } - }); - - xmlParser.on('', node => { - new Relation(node.id, refElements); - }); - - xmlParser.on('', (node, parent) => { - let relation = refElements.get(`relation/${parent.id}`); - let member = { - type: node.type, - role: node.role ? node.role : '', - ref: node.ref - }; - if (node.lat && node.lon) { - member.lat = node.lat, member.lon = node.lon, member.tags = {}; - for (let [k, v] of Object.entries(node)) { - if (!k.startsWith('$') && ['type', 'lat', 'lon'].indexOf(k) < 0) { - member[k] = v; - } - } - } - if (node.$innerNodes) { - let geometry = []; - let nodes = []; - for (let ind of node.$innerNodes) { - if (ind.lat && ind.lon) { - geometry.push(ind); - } else { - nodes.push(ind.ref); - } - } - if (geometry.length > 0) { - member.geometry = geometry; - } else if (nodes.length > 0) { - member.nodes = nodes; - } - } - relation.addMember(member); - }); - - xmlParser.on('', (node, parent) => { - refElements.get(`relation/${parent.id}`).setBounds([parseFloat(node.minlon), parseFloat(node.minlat), parseFloat(node.maxlon), parseFloat(node.maxlat)]); - }); - - xmlParser.on('', (node, parent) => { - refElements.get(`relation/${parent.id}`).addTag(node.k, node.v); - }); - - xmlParser.parse(osm); - }; - - if (format === 'json-raw') { - osm = JSON.parse(osm); - if (osm.elements) { - format = 'json'; - } else { - format = 'invalid'; - } - } - - if (format === 'json') { - analyzeFeaturesFromJson(osm); - } else if (format === 'xml') { - analyzeFeaturesFromXml(osm); - } - - refElements.bindAll(); - - for (let v of refElements.values()) { - if (v.refCount <= 0 || (v.hasTag && renderTagged && !(v instanceof Way && excludeWay))) { - let features = v.toFeatureArray(); - // return the first geometry of the first relation element - if (v instanceof Relation && !completeFeature && features.length > 0) { - return features[0].geometry; - } - featureArray = featureArray.concat(features); - } - } - - return { type: 'FeatureCollection', features: featureArray }; -}; - -var osm2geojson = /*@__PURE__*/getDefaultExportFromCjs(lib); - -const supportedFormats = ['topojson', 'osm', 'kml', 'gpx', 'tcx', 'csv', 'tsv', 'polyline']; -class Converter { - constructor(format, data, options = {}) { - /** - * Creates a blank GeoJSON feature collection. - * @returns A new GeoJSON feature collection with no features. - */ - this.blankGeoJSON = () => ({ - type: 'FeatureCollection', - features: [], - }); - this._rawData = data; - this._format = format; - this._options = options; - const converters = { - 'topojson': this.loadTopoJson, - 'osm': this.loadOsm, - 'kml': this.loadXml, - 'gpx': this.loadXml, - 'tcx': this.loadXml, - 'csv': this.loadCsv, - 'tsv': this.loadCsv, - 'polyline': this.loadPolyline - }; - this._conversionFn = converters[format]; - } - async convert() { - if (!this._conversionFn) { - return new Promise((_, rej) => rej(`No converter exists for ${this._format}`)); - } - else { - return this._conversionFn(); - } - } - /** - * Load the XML data as GeoJSON - * @returns A promise resolving to a GeoJSON FeatureCollection - */ - async loadXml() { - // Use the appropriate parser based on the format - const geojson = toGeoJson[this._format](new DOMParser().parseFromString(this._rawData, "text/xml")); - return geojson; - } - /** - * Loads and parses CSV data into a GeoJSON FeatureCollection. - * @returns A Promise that resolves with the GeoJSON FeatureCollection. - */ - async loadCsv() { - // Define options for the csv2geojson library - let options = this._options.csvOptions || {}; // TODO allow CSV options - if (this._format === 'tsv') { - options.delimiter = '\t'; - } - // Use the csv2geojson library to convert the CSV to GeoJSON - const geojson = await new Promise((resolve, reject) => { - csv2geojson_1.csv2geojson(this._rawData, options, (err, data) => { - if (err) { - reject(err); - } - else { - resolve(data); - } - }); - }); - return geojson; - } - /** - * Loads TopoJSON data and converts it into a GeoJSON FeatureCollection - * @returns A Promise that resolves with the GeoJSON FeatureCollection. - */ - async loadTopoJson() { - let topoJsonData = {}; - try { - topoJsonData = JSON.parse(this._rawData); - } - catch (e) { - throw "Invalid TopoJson"; - } - // Convert the data - let result = this.blankGeoJSON(); - if (topoJsonData.type === "Topology" && topoJsonData.objects !== undefined) { - result = { - type: "FeatureCollection", - features: result.features = Object.keys(topoJsonData.objects).map(key => topojsonFeature(topoJsonData, key)).reduce((a, v) => [...a, ...v.features], []) - }; - } - return result; - } - ; - /** - * Loads OSM data and converts it into a GeoJSON FeatureCollection - * @returns A Promise that resolves with the GeoJSON FeatureCollection. - */ - async loadOsm() { - return osm2geojson(this._rawData); - } - /** - * Loads and parses Polyline data into a GeoJSON FeatureCollection. - * @returns A Promise that resolves with the GeoJSON FeatureCollection. - */ - async loadPolyline() { - let options = this._options.polylineOptions || {}; - // Use the @mapbox/polyline library to convert the polyline to GeoJSON - const geojson = await new Promise((resolve, reject) => { - try { - const lineString = polylineExports.toGeoJSON(this._rawData, options.precision); - let geometry = lineString; - if (options.type === 'point') { - if (lineString.coordinates.length === 1) { - // Make it a point - geometry = { - 'type': 'Point', - 'coordinates': lineString.coordinates[0] - }; - } - else { - console.warn('Cannot convert polyline to ' + options.type); - } - } - else if (options.type === 'polygon') { - if (lineString.coordinates[0][0] === lineString.coordinates[lineString.coordinates.length - 1][0] && - lineString.coordinates[0][1] === lineString.coordinates[lineString.coordinates.length - 1][1]) { - // Make it a polygon - geometry = { - 'type': 'Polygon', - 'coordinates': [lineString.coordinates] - }; - } - else { - console.warn('Cannot convert polyline to ' + options.type); - } - } - resolve({ - type: "FeatureCollection", - features: [{ - "type": "Feature", - "geometry": geometry, - "properties": options.properties || {} - }] - }); - } - catch (err) { - reject(err); - } - }); - return geojson; - } -} - -var WorkerClass = null; - -try { - var WorkerThreads = - typeof module !== 'undefined' && typeof module.require === 'function' && module.require('worker_threads') || - typeof __non_webpack_require__ === 'function' && __non_webpack_require__('worker_threads') || - typeof require === 'function' && require('worker_threads'); - WorkerClass = WorkerThreads.Worker; -} catch(e) {} // eslint-disable-line - -function decodeBase64$1(base64, enableUnicode) { - return Buffer.from(base64, 'base64').toString('utf8'); -} - -function createBase64WorkerFactory$2(base64, sourcemapArg, enableUnicodeArg) { - var source = decodeBase64$1(base64); - var start = source.indexOf('\n', 10) + 1; - var body = source.substring(start) + (''); - return function WorkerFactory(options) { - return new WorkerClass(body, Object.assign({}, options, { eval: true })); - }; -} - -function decodeBase64(base64, enableUnicode) { - var binaryString = atob(base64); - return binaryString; -} - -function createURL(base64, sourcemapArg, enableUnicodeArg) { - var source = decodeBase64(base64); - var start = source.indexOf('\n', 10) + 1; - var body = source.substring(start) + (''); - var blob = new Blob([body], { type: 'application/javascript' }); - return URL.createObjectURL(blob); -} - -function createBase64WorkerFactory$1(base64, sourcemapArg, enableUnicodeArg) { - var url; - return function WorkerFactory(options) { - url = url || createURL(base64); - return new Worker(url, options); - }; -} - -var kIsNodeJS = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'; - -function isNodeJS() { - return kIsNodeJS; -} - -function createBase64WorkerFactory(base64, sourcemapArg, enableUnicodeArg) { - if (isNodeJS()) { - return createBase64WorkerFactory$2(base64); - } - return createBase64WorkerFactory$1(base64); -} - -var WorkerFactory = createBase64WorkerFactory('Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewoJJ3VzZSBzdHJpY3QnOwoKCWZ1bmN0aW9uIGdldERlZmF1bHRFeHBvcnRGcm9tQ2pzICh4KSB7CgkJcmV0dXJuIHggJiYgeC5fX2VzTW9kdWxlICYmIE9iamVjdC5wcm90b3R5cGUuaGFzT3duUHJvcGVydHkuY2FsbCh4LCAnZGVmYXVsdCcpID8geFsnZGVmYXVsdCddIDogeDsKCX0KCglmdW5jdGlvbiBnZXRBdWdtZW50ZWROYW1lc3BhY2UobikgewoJICBpZiAobi5fX2VzTW9kdWxlKSByZXR1cm4gbjsKCSAgdmFyIGYgPSBuLmRlZmF1bHQ7CgkJaWYgKHR5cGVvZiBmID09ICJmdW5jdGlvbiIpIHsKCQkJdmFyIGEgPSBmdW5jdGlvbiBhICgpIHsKCQkJCWlmICh0aGlzIGluc3RhbmNlb2YgYSkgewoJICAgICAgICByZXR1cm4gUmVmbGVjdC5jb25zdHJ1Y3QoZiwgYXJndW1lbnRzLCB0aGlzLmNvbnN0cnVjdG9yKTsKCQkJCX0KCQkJCXJldHVybiBmLmFwcGx5KHRoaXMsIGFyZ3VtZW50cyk7CgkJCX07CgkJCWEucHJvdG90eXBlID0gZi5wcm90b3R5cGU7CgkgIH0gZWxzZSBhID0ge307CgkgIE9iamVjdC5kZWZpbmVQcm9wZXJ0eShhLCAnX19lc01vZHVsZScsIHt2YWx1ZTogdHJ1ZX0pOwoJCU9iamVjdC5rZXlzKG4pLmZvckVhY2goZnVuY3Rpb24gKGspIHsKCQkJdmFyIGQgPSBPYmplY3QuZ2V0T3duU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W9mIHggPT0gJ3N0cmluZycpIHsKCSAgICAgICAgb3B0aW9ucy5kZWxpbWl0ZXIgPSBhdXRvRGVsaW1pdGVyKHgpOwoJICAgICAgICBpZiAoIW9wdGlvbnMuZGVsaW1pdGVyKSB7CgkgICAgICAgICAgICBjYWxsYmFjayh7CgkgICAgICAgICAgICAgICAgdHlwZTogJ0Vycm9yJywKCSAgICAgICAgICAgICAgICBtZXNzYWdlOiAnQ291bGQgbm90IGF1dG9kZXRlY3QgZGVsaW1pdGVyJwoJICAgICAgICAgICAgfSk7CgkgICAgICAgICAgICByZXR1cm47CgkgICAgICAgIH0KCSAgICB9CgoJICAgIHZhciBudW1lcmljRmllbGRzID0gb3B0aW9ucy5udW1lcmljRmllbGRzID8gb3B0aW9ucy5udW1lcmljRmllbGRzLnNwbGl0KCcsJykgOiBudWxsOwoKCSAgICB2YXIgcGFyc2VkID0gKHR5cGVvZiB4ID09ICdzdHJpbmcnKSA/CgkgICAgICAgIGRzdi5kc3ZGb3JtYXQob3B0aW9ucy5kZWxpbWl0ZXIpLnBhcnNlKHgsIGZ1bmN0aW9uIChkKSB7CgkgICAgICAgICAgICBpZiAobnVtZXJpY0ZpZWxkcykgewoJICAgICAgICAgICAgICAgIGZvciAodmFyIGtleSBpbiBkKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmIChudW1lcmljRmllbGRzLmluY2x1ZGVzKGtleSkpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGRba2V5XSA9ICtkW2tleV07CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgICAgICByZXR1cm4gZDsKCSAgICAgICAgfSkgOiB4OwoKCSAgICBpZiAoIXBhcnNlZC5sZW5ndGgpIHsKCSAgICAgICAgY2FsbGJhY2sobnVsbCwgZmVhdHVyZWNvbGxlY3Rpb24pOwoJICAgICAgICByZXR1cm47CgkgICAgfQoKCSAgICB2YXIgZXJyb3JzID0gW107CgkgICAgdmFyIGk7CgoKCSAgICBpZiAoIWxhdGZpZWxkKSBsYXRmaWVsZCA9IGd1ZXNzTGF0SGVhZGVyKHBhcnNlZFswXSk7CgkgICAgaWYgKCFsb25maWVsZCkgbG9uZmllbGQgPSBndWVzc0xvbkhlYWRlcihwYXJzZWRbMF0pOwoJICAgIHZhciBub0dlb21ldHJ5ID0gKCFsYXRmaWVsZCB8fCAhbG9uZmllbGQpOwoKCSAgICBpZiAobm9HZW9tZXRyeSkgewoJICAgICAgICBmb3IgKGkgPSAwOyBpIDwgcGFyc2VkLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgICAgICBmZWF0dXJlcy5wdXNoKHsKCSAgICAgICAgICAgICAgICB0eXBlOiAnRmVhdHVyZScsCgkgICAgICAgICAgICAgICAgcHJvcGVydGllczogcGFyc2VkW2ldLAoJICAgICAgICAgICAgICAgIGdlb21ldHJ5OiBudWxsCgkgICAgICAgICAgICB9KTsKCSAgICAgICAgfQoJICAgICAgICBjYWxsYmFjayhlcnJvcnMubGVuZ3RoID8gZXJyb3JzIDogbnVsbCwgZmVhdHVyZWNvbGxlY3Rpb24pOwoJICAgICAgICByZXR1cm47CgkgICAgfQoKCSAgICBmb3IgKGkgPSAwOyBpIDwgcGFyc2VkLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgIGlmIChwYXJzZWRbaV1bbG9uZmllbGRdICE9PSB1bmRlZmluZWQgJiYKCSAgICAgICAgICAgIHBhcnNlZFtpXVtsYXRmaWVsZF0gIT09IHVuZGVmaW5lZCkgewoKCSAgICAgICAgICAgIHZhciBsb25rID0gcGFyc2VkW2ldW2xvbmZpZWxkXSwKCSAgICAgICAgICAgICAgICBsYXRrID0gcGFyc2VkW2ldW2xhdGZpZWxkXSwKCSAgICAgICAgICAgICAgICBsb25mLCBsYXRmLAoJICAgICAgICAgICAgICAgIGE7CgoJICAgICAgICAgICAgYSA9IHNleGFnZXNpbWFsKGxvbmssICdFVycpOwoJICAgICAgICAgICAgaWYgKGEpIGxvbmsgPSBhOwoJICAgICAgICAgICAgYSA9IHNleGFnZXNpbWFsKGxhdGssICdOUycpOwoJICAgICAgICAgICAgaWYgKGEpIGxhdGsgPSBhOwoKCSAgICAgICAgICAgIGxvbmYgPSBwYXJzZUZsb2F0KGxvbmspOwoJICAgICAgICAgICAgbGF0ZiA9IHBhcnNlRmxvYXQobGF0ayk7CgoJICAgICAgICAgICAgaWYgKGlzTmFOKGxvbmYpIHx8CgkgICAgICAgICAgICAgICAgaXNOYU4obGF0ZikpIHsKCSAgICAgICAgICAgICAgICBlcnJvcnMucHVzaCh7CgkgICAgICAgICAgICAgICAgICAgIG1lc3NhZ2U6ICdBIHJvdyBjb250YWluZWQgYW4gaW52YWxpZCB2YWx1ZSBmb3IgbGF0aXR1ZGUgb3IgbG9uZ2l0dWRlJywKCSAgICAgICAgICAgICAgICAgICAgcm93OiBwYXJzZWRbaV0sCgkgICAgICAgICAgICAgICAgICAgIGluZGV4OiBpCgkgICAgICAgICAgICAgICAgfSk7CgkgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgIGlmICghb3B0aW9ucy5pbmNsdWRlTGF0TG9uKSB7CgkgICAgICAgICAgICAgICAgICAgIGRlbGV0ZSBwYXJzZWRbaV1bbG9uZmllbGRdOwoJICAgICAgICAgICAgICAgICAgICBkZWxldGUgcGFyc2VkW2ldW2xhdGZpZWxkXTsKCSAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIGZlYXR1cmVzLnB1c2goewoJICAgICAgICAgICAgICAgICAgICB0eXBlOiAnRmVhdHVyZScsCgkgICAgICAgICAgICAgICAgICAgIHByb3BlcnRpZXM6IHBhcnNlZFtpXSwKCSAgICAgICAgICAgICAgICAgICAgZ2VvbWV0cnk6IHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICdQb2ludCcsCgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogWwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHBhcnNlRmxvYXQobG9uZiksCgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgcGFyc2VGbG9hdChsYXRmKQoJICAgICAgICAgICAgICAgICAgICAgICAgXQoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfSk7CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCSAgICB9CgoJICAgIGNhbGxiYWNrKGVycm9ycy5sZW5ndGggPyBlcnJvcnMgOiBudWxsLCBmZWF0dXJlY29sbGVjdGlvbik7Cgl9CgoJZnVuY3Rpb24gdG9MaW5lKGdqKSB7CgkgICAgdmFyIGZlYXR1cmVzID0gZ2ouZmVhdHVyZXM7CgkgICAgdmFyIGxpbmUgPSB7CgkgICAgICAgIHR5cGU6ICdGZWF0dXJlJywKCSAgICAgICAgZ2VvbWV0cnk6IHsKCSAgICAgICAgICAgIHR5cGU6ICdMaW5lU3RyaW5nJywKCSAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBbXQoJICAgICAgICB9CgkgICAgfTsKCSAgICBmb3IgKHZhciBpID0gMDsgaSA8IGZlYXR1cmVzLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgIGxpbmUuZ2VvbWV0cnkuY29vcmRpbmF0ZXMucHVzaChmZWF0dXJlc1tpXS5nZW9tZXRyeS5jb29yZGluYXRlcyk7CgkgICAgfQoJICAgIGxpbmUucHJvcGVydGllcyA9IGZlYXR1cmVzLnJlZHVjZShmdW5jdGlvbiAoYWdncmVnYXRlZFByb3BlcnRpZXMsIG5ld0ZlYXR1cmUpIHsKCSAgICAgICAgZm9yICh2YXIga2V5IGluIG5ld0ZlYXR1cmUucHJvcGVydGllcykgewoJICAgICAgICAgICAgaWYgKCFhZ2dyZWdhdGVkUHJvcGVydGllc1trZXldKSB7CgkgICAgICAgICAgICAgICAgYWdncmVnYXRlZFByb3BlcnRpZXNba2V5XSA9IFtdOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgYWdncmVnYXRlZFByb3BlcnRpZXNba2V5XS5wdXNoKG5ld0ZlYXR1cmUucHJvcGVydGllc1trZXldKTsKCSAgICAgICAgfQoJICAgICAgICByZXR1cm4gYWdncmVnYXRlZFByb3BlcnRpZXM7CgkgICAgfSwge30pOwoJICAgIHJldHVybiB7CgkgICAgICAgIHR5cGU6ICdGZWF0dXJlQ29sbGVjdGlvbicsCgkgICAgICAgIGZlYXR1cmVzOiBbbGluZV0KCSAgICB9OwoJfQoKCWZ1bmN0aW9uIHRvUG9seWdvbihnaikgewoJICAgIHZhciBmZWF0dXJlcyA9IGdqLmZlYXR1cmVzOwoJICAgIHZhciBwb2x5ID0gewoJICAgICAgICB0eXBlOiAnRmVhdHVyZScsCgkgICAgICAgIGdlb21ldHJ5OiB7CgkgICAgICAgICAgICB0eXBlOiAnUG9seWdvbicsCgkgICAgICAgICAgICBjb29yZGluYXRlczogW1tdXQoJICAgICAgICB9CgkgICAgfTsKCSAgICBmb3IgKHZhciBpID0gMDsgaSA8IGZlYXR1cmVzLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgIHBvbHkuZ2VvbWV0cnkuY29vcmRpbmF0ZXNbMF0ucHVzaChmZWF0dXJlc1tpXS5nZW9tZXRyeS5jb29yZGluYXRlcyk7CgkgICAgfQoJICAgIHBvbHkucHJvcGVydGllcyA9IGZlYXR1cmVzLnJlZHVjZShmdW5jdGlvbiAoYWdncmVnYXRlZFByb3BlcnRpZXMsIG5ld0ZlYXR1cmUpIHsKCSAgICAgICAgZm9yICh2YXIga2V5IGluIG5ld0ZlYXR1cmUucHJvcGVydGllcykgewoJICAgICAgICAgICAgaWYgKCFhZ2dyZWdhdGVkUHJvcGVydGllc1trZXldKSB7CgkgICAgICAgICAgICAgICAgYWdncmVnYXRlZFByb3BlcnRpZXNba2V5XSA9IFtdOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgYWdncmVnYXRlZFByb3BlcnRpZXNba2V5XS5wdXNoKG5ld0ZlYXR1cmUucHJvcGVydGllc1trZXldKTsKCSAgICA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W25hbWVdKSB7CgkgICAgICAgICAgICAgICAgICAgIHByb3BzW25hbWVdID0gZXh0cmFjdGVkTGluZXMubWFwKChsaW5lKSA9PiBuZXcgQXJyYXkobGluZS5saW5lLmxlbmd0aCkuZmlsbChudWxsKSk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIHByb3BzW25hbWVdW2ldID0gdmFsOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgZWxzZSB7CgkgICAgICAgICAgICAgICAgcHJvcHNbbmFtZV0gPSB2YWw7CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCSAgICB9CgkgICAgcmV0dXJuIHsKCSAgICAgICAgdHlwZTogIkZlYXR1cmUiLAoJICAgICAgICBwcm9wZXJ0aWVzOiBwcm9wZXJ0aWVzLAoJICAgICAgICBnZW9tZXRyeTogbXVsdGkKCSAgICAgICAgICAgID8gewoJICAgICAgICAgICAgICAgIHR5cGU6ICJNdWx0aUxpbmVTdHJpbmciLAoJICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiB0cmFjaywKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIDogewoJICAgICAgICAgICAgICAgIHR5cGU6ICJMaW5lU3RyaW5nIiwKCSAgICAgICAgICAgICAgICBjb29yZGluYXRlczogdHJhY2tbMF0sCgkgICAgICAgICAgICB9LAoJICAgIH07Cgl9CgkvKioKCSAqIEV4dHJhY3QgYSBwb2ludCwgaWYgcG9zc2libGUsIGZyb20gYSBnaXZlbiBub2RlLAoJICogd2hpY2ggaXMgdXN1YWxseSBhIHdwdCBvciB0cmtwdAoJICovCglmdW5jdGlvbiBnZXRQb2ludChub2RlKSB7CgkgICAgY29uc3QgcHJvcGVydGllcyA9IE9iamVjdC5hc3NpZ24oZXh0cmFjdFByb3BlcnRpZXMobm9kZSksIGdldE11bHRpKG5vZGUsIFsic3ltIl0pKTsKCSAgICBjb25zdCBwYWlyID0gY29vcmRQYWlyJDEobm9kZSk7CgkgICAgaWYgKCFwY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nbWVudCk7CgkgICAgICAgIGlmIChsaW5lKSB7CgkgICAgICAgICAgICB0cmFjay5wdXNoKGxpbmUubGluZSk7CgkgICAgICAgICAgICBpZiAobGluZS50aW1lcy5sZW5ndGgpCgkgICAgICAgICAgICAgICAgdGltZXMucHVzaChsaW5lLnRpbWVzKTsKCSAgICAgICAgICAgIGlmIChsaW5lLmhlYXJ0UmF0ZXMubGVuZ3RoKQoJICAgICAgICAgICAgICAgIGhlYXJ0UmF0ZXMucHVzaChsaW5lLmhlYXJ0UmF0ZXMpOwoJICAgICAgICAgICAgYWxsRXh0ZW5kZWRQcm9wZXJ0aWVzLnB1c2gobGluZS5leHRlbmRlZFByb3BlcnRpZXMpOwoJICAgICAgICB9CgkgICAgfQoJICAgIGZvciAobGV0IGkgPSAwOyBpIDwgYWxsRXh0ZW5kZWRQcm9wZXJ0aWVzLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgIGNvbnN0IGV4dGVuZGVkUHJvcGVydGllcyA9IGFsbEV4dGVuZGVkUHJvcGVydGllc1tpXTsKCSAgICAgICAgZm9yIChjb25zdCBwcm9wZXJ0eSBpbiBleHRlbmRlZFByb3BlcnRpZXMpIHsKCSAgICAgICAgICAgIGlmIChzZWdtZW50cy5sZW5ndGggPT09IDEpIHsKCSAgICAgICAgICAgICAgICBpZiAobGluZSkgewoJICAgICAgICAgICAgICAgICAgICBwcm9wZXJ0aWVzW3Byb3BlcnR5XSA9IGxpbmUuZXh0ZW5kZWRQcm9wZXJ0aWVzW3Byb3BlcnR5XTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgICAgICBlbHNlIHsKCSAgICAgICAgICAgICAgICBpZiAoIXByb3BlcnRpZXNbcHJvcGVydHldKSB7CgkgICAgICAgICAgICAgICAgICAgIHByb3BlcnRpZXNbcHJvcGVydHldID0gdHJhY2subWFwKCh0cmFjaykgPT4gQXJyYXkodHJhY2subGVuZ3RoKS5maWxsKG51bGwpKTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgcHJvcGVydGllc1twcm9wZXJ0eV1baV0gPSBleHRlbmRlZFByb3BlcnRpZXNbcHJvcGVydHldOwoJICAgICAgICAgICAgfQoJICAgICAgICB9CgkgICAgfQoJICAgIGlmICh0cmFjay5sZW5ndGggPT09IDApCgkgICAgICAgIHJldHVybiBudWxsOwoJICAgIGlmICh0aW1lcy5sZW5ndGggfHwgaGVhcnRSYXRlcy5sZW5ndGgpIHsKCSAgICAgICAgcHJvcGVydGllcy5jb29yZGluYXRlUHJvcGVydGllcyA9IE9iamVjdC5hc3NpZ24odGltZXMubGVuZ3RoCgkgICAgICAgICAgICA/IHsKCSAgICAgICAgICAgICAgICB0aW1lczogdHJhY2subGVuZ3RoID09PSAxID8gdGltZXNbMF0gOiB0aW1lcywKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIDoge30sIGhlYXJ0UmF0ZXMubGVuZ3RoCgkgICAgICAgICAgICA/IHsKCSAgICAgICAgICAgICAgICBoZWFydDogdHJhY2subGVuZ3RoID09PSAxID8gaGVhcnRSYXRlc1swXSA6IGhlYXJ0UmF0ZXMsCgkgICAgICAgICAgICB9CgkgICAgICAgICAgICA6IHt9KTsKCSAgICB9CgkgICAgcmV0dXJuIHsKCSAgICAgICAgdHlwZTogIkZlYXR1cmUiLAoJICAgICAgICBwcm9wZXJ0aWVzOiBwcm9wZXJ0aWVzLAoJICAgICAgICBnZW9tZXRyeTogdHJhY2subGVuZ3RoID09PSAxCgkgICAgICAgICAgICA/IHsKCSAgICAgICAgICAgICAgICB0eXBlOiAiTGluZVN0cmluZyIsCgkgICAgICAgICAgICAgICAgY29vcmRpbmF0ZXM6IHRyYWNrWzBdLAoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgOiB7CgkgICAgICAgICAgICAgICAgdHlwZTogIk11bHRpTGluZVN0cmluZyIsCgkgICAgICAgICAgICAgICAgY29vcmRpbmF0ZXM6IHRyYWNrLAoJICAgICAgICAgICAgfSw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HJldHVybiBnZXQobm9kZSwgIkljb24iLCAoaWNvbiwgcHJvcGVydGllcykgPT4gewoJICAgICAgICB2YWwxKGljb24sICJocmVmIiwgKGhyZWYpID0+IHsKCSAgICAgICAgICAgIHByb3BlcnRpZXMuaWNvbiA9IGhyZWY7CgkgICAgICAgIH0pOwoJICAgICAgICByZXR1cm4gcHJvcGVydGllczsKCSAgICB9KTsKCX0KCWZ1bmN0aW9uIGV4dHJhY3RJY29uKG5vZGUpIHsKCSAgICByZXR1cm4gZ2V0KG5vZGUsICJJY29uU3R5bGUiLCAoaWNvblN0eWxlKSA9PiB7CgkgICAgICAgIHJldHVybiBPYmplY3QuYXNzaWduKGdldENvbG9yKGljb25TdHlsZSwgImljb24iKSwgbnVtZXJpY1Byb3BlcnR5KGljb25TdHlsZSwgInNjYWxlIiwgImljb24tc2NhbGUiKSwgbnVtZXJpY1Byb3BlcnR5KGljb25TdHlsZSwgImhlYWRpbmciLCAiaWNvbi1oZWFkaW5nIiksIGdldChpY29uU3R5bGUsICJob3RTcG90IiwgKGhvdHNwb3QpID0+IHsKCSAgICAgICAgICAgIGNvbnN0IGxlZnQgPSBwYXJzZUZsb2F0KGhvdHNwb3QuZ2V0QXR0cmlidXRlKCJ4IikgfHwgIiIpOwoJICAgICAgICAgICAgY29uc3QgdG9wID0gcGFyc2VGbG9hdChob3RzcG90LmdldEF0dHJpYnV0ZSgieSIpIHx8ICIiKTsKCSAgICAgICAgICAgIGNvbnN0IHh1bml0cyA9IGhvdHNwb3QuZ2V0QXR0cmlidXRlKCJ4dW5pdHMiKSB8fCAiIjsKCSAgICAgICAgICAgIGNvbnN0IHl1bml0cyA9IGhvdHNwb3QuZ2V0QXR0cmlidXRlKCJ5dW5pdHMiKSB8fCAiIjsKCSAgICAgICAgICAgIGlmICghaXNOYU4obGVmdCkgJiYgIWlzTmFOKHRvcCkpCgkgICAgICAgICAgICAgICAgcmV0dXJuIHsKCSAgICAgICAgICAgICAgICAgICAgImljb24tb2Zmc2V0I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2VGbG9hdCk7CgkgICAgfSk7CgkgICAgaWYgKGNvb3JkaW5hdGVzLmxlbmd0aCA9PT0gMCkgewoJICAgICAgICByZXR1cm4gbnVsbDsKCSAgICB9CgkgICAgcmV0dXJuIHsKCSAgICAgICAgZ2VvbWV0cnk6IGNvb3JkaW5hdGVzLmxlbmd0aCA+IDIKCSAgICAgICAgICAgID8gewoJICAgICAgICAgICAgICAgIHR5cGU6ICJMaW5lU3RyaW5nIiwKCSAgICAgICAgICAgICAgICBjb29yZGluYXRlcywKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIDogewoJICAgICAgICAgICAgICAgIHR5cGU6ICJQb2ludCIsCgkgICAgICAgICAgICAgICAgY29vcmRpbmF0ZXM6IGNvb3JkaW5hdGVzWzBdLAoJICAgICAgICAgICAgfSwKCSAgICAgICAgdGltZXM6ICQobm9kZSwgIndoZW4iKS5tYXAoKGVsZW0pID0+IG5vZGVWYWwoZWxlbSkpLAoJICAgIH07Cgl9CglmdW5jdGlvbiBmaXhSaW5nKHJpbmcpIHsKCSAgICBpZiAocmluZy5sZW5ndGggPT09IDApCgkgICAgICAgIHJldHVybiByaW5nOwoJICAgIGNvbnN0IGZpcnN0ID0gcmluZ1swXTsKCSAgICBjb25zdCBsYXN0ID0gcmluZ1tyaW5nLmxlbmd0aCAtIDFdOwoJICAgIGxldCBlcXVhbCA9IHRydWU7CgkgICAgZm9yIChsZXQgaSA9IDA7IGkgPCBNYXRoLm1heChmaXJzdC5sZW5ndGgsIGxhc3QubGVuZ3RoKTsgaSsrKSB7CgkgICAgICAgIGlmIChmaXJzdFtpXSAhPT0gbGFzdFtpXSkgewoJICAgICAgICAgICAgZXF1YWwgPSBmYWxzZTsKCSAgICAgICAgICAgIGJyZWFrOwoJICAgICAgICB9CgkgICAgfQoJICAgIGlmICghZXF1YWwpIHsKCSAgICAgICAgcmV0dXJuIHJpbmcuY29uY2F0KFtyaW5nWzBdXSk7CgkgICAgfQoJICAgIHJldHVybiByaW5nOwoJfQoJZnVuY3Rpb24gZ2V0Q29vcmRpbmF0ZXMobm9kZSkgewoJICAgIHJldHVybiBub2RlVmFsKGdldDEobm9kZSwgImNvb3JkaW5hdGVzIikpOwoJfQoJZnVuY3Rpb24gZ2V0R2VvbWV0cnkobm9kZSkgewoJICAgIGxldCBnZW9tZXRyaWVzID0gW107CgkgICAgbGV0IGNvb3JkVGltZXMgPSBbXTsKCSAgICBmb3IgKGxldCBpID0gMDsgaSA8IG5vZGUuY2hpbGROb2Rlcy5sZW5ndGg7IGkrKykgewoJICAgICAgICBjb25zdCBjaGlsZCA9IG5vZGUuY2hpbGROb2Rlcy5pdGVtKGkpOwoJICAgICAgICBpZiAoaXNFbGVtZW50KGNoaWxkKSkgewoJICAgICAgICAgICAgc3dpdGNoIChjaGlsZC50YWdOYW1lKSB7CgkgICAgICAgICAgICAgICAgY2FzZSAiTXVsdGlHZW9tZXRyeSI6CgkgICAgICAgICAgICAgICAgY2FzZSAiTXVsdGlUcmFjayI6CgkgICAgICAgICAgICAgICAgY2FzZSAiZ3g6TXVsdGlUcmFjayI6IHsKCSAgICAgICAgICAgICAgICAgICAgY29uc3QgY2hpbGRHZW9tZXRyaWVzID0gZ2V0R2VvbWV0cnkoY2hpbGQpOwoJICAgICAgICAgICAgICAgICAgICBnZW9tZXRyaWVzID0gZ2VvbWV0cmllcy5jb25jYXQoY2hpbGRHZW9tZXRyaWVzLmdlb21ldHJpZXMpOwoJICAgICAgICAgICAgICAgICAgICBjb29yZFRpbWVzID0gY29vcmRUaW1lcy5jb25jYXQoY2hpbGRHZW9tZXRyaWVzLmNvb3JkVGltZXMpOwoJICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgY2FzZSAiUG9pbnQiOiB7CgkgICAgICAgICAgICAgICAgICAgIGNvbnN0IGNvb3JkaW5hdGVzID0gY29vcmQxKGdldENvb3JkaW5hdGVzKGNoaWxkKSk7CgkgICAgICAgICAgICAgICAgICAgIGlmIChjb29yZGluYXRlcy5sZW5ndGggPj0gMikgewoJICAgICAgICAgICAgICAgICAgICAgICAgZ2VvbWV0cmllcy5wdXNoKHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAiUG9pbnQiLAoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzLAoJICAgICAgICAgICAgICAgICAgICAgICAgfSk7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIGNhc2UgIkxpbmVhclJpbmciOgoJICAgICAgICAgICAgICAgIGNhc2UgIkxpbmVTdHJpbmciOiB7CgkgICAgICAgICAgICAgICAgICAgIGNvbnN0IGNvb3JkaW5hdGVzID0gY29vcmQoZ2V0Q29vcmRpbmF0ZXMoY2hpbGQpKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGNvb3JkaW5hdGVzLmxlbmd0aCA+PSAyKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBnZW9tZXRyaWVzLnB1c2goewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICJMaW5lU3RyaW5nIiwKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlcywKCSAgICAgICAgICAgICAgICAgICAgICAgIH0pOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGJyZWFrOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICBjYXNlICJQb2x5Z29uIjogewoJICAgICAgICAgICAgICAgICAgICBjb25zdCBjb29yZHMgPSBbXTsKCSAgICAgICAgICAgICAgICAgICAgZm9yIChjb25zdCBsaW5lYXJSaW5nIG9mICQoY2hpbGQsICJMaW5lYXJSaW5nIikpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvbnN0IHJpbmcgPSBmaXhSaW5nKGNvb3JkKGdldENvb3JkaW5hdGVzKGxpbmVhclJpbmcpKSk7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAocmluZy5sZW5ndGggPj0gNCkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGNvb3Jkcy5wdXNoKHJpbmcpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGlmIChjb29yZHMubGVuZ3RoKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBnZW9tZXRyaWVzLnB1c2goewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICJQb2x5Z29uIiwKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogY29vcmRzLAoJICAgICAgICAgICAgICAgICAgICAgICAgfSk7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIGNhc2UgIlRyYWNrIjoKCSAgICAgICAgICAgICAgICBjYXNlICJneDpUcmFjayI6IHsKCSAgICAgICAgICAgICAgICAgICAgY29uc3QgZ3ggPSBneENvb3JkcyhjaGlsZCk7CgkgICAgICAgICAgICAgICAgICAgIGlmICghZ3gpCgkgICAgICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICAgICAgY29uc3QgeyB0aW1lcywgZ2VvbWV0cnkgfSA9IGd4OwoJICAgICAgICAgICAgICAgICAgICBnZW9tZXRyaWVzLnB1c2goZ2VvbWV0cnkpOwoJICAgICAgICAgICAgICAgICAgICBpZiAodGltZXMubGVuZ3RoKQoJICAgICAgICAgICAgICAgICAgICAgICAgY29vcmRUaW1lcy5wdXNoKHRpbWVzKTsKCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICB9CgkgICAgfQoJICAgIHJldHVybiB7CgkgICAgICAgIGdlb21ldHJpZXMsCgkgICAgICAgIGNvb3JkVGltZXMsCgkgICAgfTsKCX0KCglmdW5jdGlvbiBnZW9tZXRyeUxpc3RUb0dlb21ldHJ5KGdlb21ldHJpZXMpIHsKCSAgICByZXR1cm4gZ2VvbWV0cmllcy5sZW5ndGggPT09IDAKCSAgICAgICAgPyBudWxsCgkgICAgICAgIDogZ2VvbWV0cmllcy5sZW5ndGggPT09IDEKCSAgICAgICAgICAgID8gZ2VvbWV0cmllc1swXQoJICAgICAgICAgICAgOiB7CgkgICAgICAgICAgICAgICAgdHlwZTogIkdlb21ldHJ5Q29sbGVjdGlvbiIsCgkgICAgICAgICAgICAgICAgZ2VvbWV0cmllcywKCSAgICAgICAgICAgIH07Cgl9CglmdW5jdGlvbiBnZXRQbGFjZW1hcmsobm9kZSwgc3R5bGVNYXAsIHNjaGVtYSwgb3B0aW9ucykgewoJICAgIGNvbnN0IHsgY29vcmRUaW1lcywgZ2VvbWV0cmllcyB9ID0gZ2V0R2VvbWV0cnkobm9kZSk7CgkgICAgY29uc3QgZ2VvbWV0cnkgPSBnZW9tZXRyeUxpc3RUb0dlb21ldHJ5KGdlb21ldHJpZXMpOwoJICAgIGlmICghZ2VvbWV0cnkgJiYgb3B0aW9ucy5za2lwTnVsbEdlb21ldHJ5KSB7CgkgICAgICAgIHJldHVybiBudWxsOwoJICAgIH0KCSAgICBjb25zdCBmZWF0dXJlID0gewoJICAgICAgICB0eXBlOiAiRmVhdHVyZSIsCgkgICAgICAgIGdlb21ldHJ5LAoJICAgICAgICBwcm9wZXJ0aWVzOiBPYmplY3QuYXNzaWduKGdldE11bHRpKG5vZGUsIFsKCSAgICAgICAgICAgICJuYW1lIiwKCSAgICAgICAgICAgICJhZGRyZXNzIiwKCSAgICAgICAgICAgICJ2aXNpYmlsaXR5IiwKCSAgICAgICAgICAgICJvcGVuIiwKCSAgICAgICAgICAgICJwaG9uZU51bWJlciIsCgkgICAgICAgICAgICAiZGVzY3JpcHRpb24iL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RpbmF0ZXMobm9kZSkpKTsKCSAgICAgICAgcmV0dXJuIHsKCSAgICAgICAgICAgIGdlb21ldHJ5OiB7CgkgICAgICAgICAgICAgICAgdHlwZTogIlBvbHlnb24iLAoJICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBbcmluZ10sCgkgICAgICAgICAgICB9LAoJICAgICAgICB9OwoJICAgIH0KCSAgICByZXR1cm4gZ2V0TGF0TG9uQm94KG5vZGUpOwoJfQoJY29uc3QgREVHUkVFU19UT19SQURJQU5TID0gTWF0aC5QSSAvIDE4MDsKCWZ1bmN0aW9uIHJvdGF0ZUJveChiYm94LCBjb29yZGluYXRlcywgcm90YXRpb24pIHsKCSAgICBjb25zdCBjZW50ZXIgPSBbKGJib3hbMF0gKyBiYm94WzJdKSAvIDIsIChiYm94WzFdICsgYmJveFszXSkgLyAyXTsKCSAgICByZXR1cm4gWwoJICAgICAgICBjb29yZGluYXRlc1swXS5tYXAoKGNvb3JkaW5hdGUpID0+IHsKCSAgICAgICAgICAgIGNvbnN0IGR5ID0gY29vcmRpbmF0ZVsxXSAtIGNlbnRlclsxXTsKCSAgICAgICAgICAgIGNvbnN0IGR4ID0gY29vcmRpbmF0ZVswXSAtIGNlbnRlclswXTsKCSAgICAgICAgICAgIGNvbnN0IGRpc3RhbmNlID0gTWF0aC5zcXJ0KE1hdGgucG93KGR5LCAyKSArIE1hdGgucG93KGR4LCAyKSk7CgkgICAgICAgICAgICBjb25zdCBhbmdsZSA9IE1hdGguYXRhbjIoZHksIGR4KSArIHJvdGF0aW9uICogREVHUkVFU19UT19SQURJQU5TOwoJICAgICAgICAgICAgcmV0dXJuIFsKCSAgICAgICAgICAgICAgICBjZW50ZXJbMF0gKyBNYXRoLmNvcyhhbmdsZSkgKiBkaXN0YW5jZSwKCSAgICAgICAgICAgICAgICBjZW50ZXJbMV0gKyBNYXRoLnNpbihhbmdsZSkgKiBkaXN0YW5jZSwKCSAgICAgICAgICAgIF07CgkgICAgICAgIH0pLAoJICAgIF07Cgl9CglmdW5jdGlvbiBnZXRMYXRMb25Cb3gobm9kZSkgewoJICAgIGNvbnN0IGxhdExvbkJveCA9IGdldDEobm9kZSwgIkxhdExvbkJveCIpOwoJICAgIGlmIChsYXRMb25Cb3gpIHsKCSAgICAgICAgY29uc3Qgbm9ydGggPSBudW0xKGxhdExvbkJveCwgIm5vcnRoIik7CgkgICAgICAgIGNvbnN0IHdlc3QgPSBudW0xKGxhdExvbkJveCwgIndlc3QiKTsKCSAgICAgICAgY29uc3QgZWFzdCA9IG51bTEobGF0TG9uQm94LCAiZWFzdCIpOwoJICAgICAgICBjb25zdCBzb3V0aCA9IG51bTEobGF0TG9uQm94LCAic291dGgiKTsKCSAgICAgICAgY29uc3Qgcm90YXRpb24gPSBudW0xKGxhdExvbkJveCwgInJvdGF0aW9uIik7CgkgICAgICAgIGlmICh0eXBlb2Ygbm9ydGggPT09ICJudW1iZXIiICYmCgkgICAgICAgICAgICB0eXBlb2Ygc291dGggPT09ICJudW1iZXIiICYmCgkgICAgICAgICAgICB0eXBlb2Ygd2VzdCA9PT0gIm51bWJlciIgJiYKCSAgICAgICAgICAgIHR5cGVvZiBlYXN0ID09PSAibnVtYmVyIikgewoJICAgICAgICAgICAgY29uc3QgYmJveCA9IFt3ZXN0LCBzb3V0aCwgZWFzdCwgbm9ydGhdOwoJICAgICAgICAgICAgbGV0IGNvb3JkaW5hdGVzID0gWwoJICAgICAgICAgICAgICAgIFsKCSAgICAgICAgICAgICAgICAgICAgW3dlc3QsIG5vcnRoXSwKCSAgICAgICAgICAgICAgICAgICAgW2Vhc3QsIG5vcnRoXSwKCSAgICAgICAgICAgICAgICAgICAgW2Vhc3QsIHNvdXRoXSwKCSAgICAgICAgICAgICAgICAgICAgW3dlc3QsIHNvdXRoXSwKCSAgICAgICAgICAgICAgICAgICAgW3dlc3QsIG5vcnRoXSwgLy8gdG9wIGxlZnQgKGFnYWluKQoJICAgICAgICAgICAgICAgIF0sCgkgICAgICAgICAgICBdOwoJICAgICAgICAgICAgaWYgKHR5cGVvZiByb3RhdGlvbiA9PT0gIm51bWJlciIpIHsKCSAgICAgICAgICAgICAgICBjb29yZGluYXRlcyA9IHJvdGF0ZUJveChiYm94LCBjb29yZGluYXRlcywgcm90YXRpb24pOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmV0dXJuIHsKCSAgICAgICAgICAgICAgICBiYm94LAoJICAgICAgICAgICAgICAgIGdlb21ldHJ5OiB7CgkgICAgICAgICAgICAgICAgICAgIHR5cGU6ICJQb2x5Z29uIiwKCSAgICAgICAgICAgICAgICAgICAgY29vcmRpbmF0ZXMsCgkgICAgICAgICAgICAgICAgfSwKCSAgICAgICAgICAgIH07CgkgICAgICAgIH0KCSAgICB9CgkgICAgcmV0dXJuIG51bGw7Cgl9CglmdW5jdGlvbiBnZXRHcm91bmRPdmVybGF5KG5vZGUsIHN0eWxlTWFwLCBzY2hlbWEsIG9wdGlvbnMpIHsKCSAgICBjb25zdCBib3ggPSBnZXRHcm91bmRPdmVybGF5Qm94KG5vZGUpOwoJICAgIGNvbnN0IGdlb21ldHJ5ID0gYm94Py5nZW9tZXRyeSB8fCBudWxsOwoJICAgIGlmICghZ2VvbWV0cnkgJiYgb3B0aW9ucy5za2lwTnVsbEdlb21ldHJ5KSB7CgkgICAgICAgIHJldHVybiBudWxsOwoJICAgIH0KCSAgICBjb25zdCBmZWF0dXJlID0gewoJICAgICAgICB0eXBlOiAiRmVhdHVyZSIsCgkgICAgICAgIGdlb21ldHJ5LAoJICAgICAgICBwcm9wZXJ0aWVzOiBPYmplY3QuYXNzaWduKAoJICAgICAgICAvKioKCSAgICAgICAgICogUmVsYXRlZCB0bwoJICAgICAgICAgKiBodHRwczovL2dpc3QuZ2l0aHViLmNvbS90bWN3LzAzN2ExY2I2NjYwZDc0YTM5MmU5ZGE3NDQ2NTQwZjQ2CgkgICAgICAgICAqLwoJICAgICAgICB7ICJAZ2VvbWV0cnktdHlwZSI6ICJncm91bmRvdmVybGF5IiB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3R5bGVNYXAobm9kZSk7CgkgICAgY29uc3Qgc2NoZW1hID0gYnVpbGRTY2hlbWEobm9kZSk7CgkgICAgY29uc3QgdHJlZSA9IHsgdHlwZTogInJvb3QiLCBjaGlsZHJlbjogW10gfTsKCSAgICBmdW5jdGlvbiB0cmF2ZXJzZShub2RlLCBwb2ludGVyLCBvcHRpb25zKSB7CgkgICAgICAgIGlmIChpc0VsZW1lbnQobm9kZSkpIHsKCSAgICAgICAgICAgIHN3aXRjaCAobm9kZS50YWdOYW1lKSB7CgkgICAgICAgICAgICAgICAgY2FzZSAiR3JvdW5kT3ZlcmxheSI6IHsKCSAgICAgICAgICAgICAgICAgICAgY29uc3QgcGxhY2VtYXJrID0gZ2V0R3JvdW5kT3ZlcmxheShub2RlLCBzdHlsZU1hcCwgc2NoZW1hLCBvcHRpb25zKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKHBsYWNlbWFyaykgewoJICAgICAgICAgICAgICAgICAgICAgICAgcG9pbnRlci5jaGlsZHJlbi5wdXNoKHBsYWNlbWFyayk7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIGNhc2UgIlBsYWNlbWFyayI6IHsKCSAgICAgICAgICAgICAgICAgICAgY29uc3QgcGxhY2VtYXJrID0gZ2V0UGxhY2VtYXJrKG5vZGUsIHN0eWxlTWFwLCBzY2hlbWEsIG9wdGlvbnMpOwoJICAgICAgICAgICAgICAgICAgICBpZiAocGxhY2VtYXJrKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBwb2ludGVyLmNoaWxkcmVuLnB1c2gocGxhY2VtYXJrKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgY2FzZSAiRm9sZGVyIjogewoJICAgICAgICAgICAgICAgICAgICBjb25zdCBm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EBwYXJhbSB7TnVtYmVyfSBwcmVjaXNpb24KCQkgKiBAcmV0dXJucyB7T2JqZWN0fQoJCSAqLwoJCXBvbHlsaW5lLnRvR2VvSlNPTiA9IGZ1bmN0aW9uKHN0ciwgcHJlY2lzaW9uKSB7CgkJICAgIHZhciBjb29yZHMgPSBwb2x5bGluZS5kZWNvZGUoc3RyLCBwcmVjaXNpb24pOwoJCSAgICByZXR1cm4gewoJCSAgICAgICAgdHlwZTogJ0xpbmVTdHJpbmcnLAoJCSAgICAgICAgY29vcmRpbmF0ZXM6IGZsaXBwZWQoY29vcmRzKQoJCSAgICB9OwoJCX07CgoJCWlmIChtb2R1bGUuZXhwb3J0cykgewoJCSAgICBtb2R1bGUuZXhwb3J0cyA9IHBvbHlsaW5lOwoJCX0gCgl9IChwb2x5bGluZSkpOwoKCXZhciBwb2x5bGluZUV4cG9ydHMgPSBwb2x5bGluZS5leHBvcnRzOwoKCXZhciB1dGlscyA9ICgoKSA9PiB7CgoJICAgIGNvbnN0IHB1cmdlUHJvcHMgPSAob2JqLCBibGFja2xpc3QpID0+IHsKCSAgICAgICAgaWYgKG9iaikgewoJICAgICAgICAgICAgbGV0IHJzID0gT2JqZWN0LmFzc2lnbih7fSwgb2JqKTsKCSAgICAgICAgICAgIGlmIChibGFja2xpc3QpIHsKCSAgICAgICAgICAgICAgICBmb3IgKGxldCBwcm9wIG9mIGJsYWNrbGlzdCkgewoJICAgICAgICAgICAgICAgICAgICBkZWxldGUgcnNbcHJvcF07CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmV0dXJuIHJzOwoJICAgICAgICB9CgkgICAgICAgIHJldHVybiB7fTsKCSAgICB9OwoKCSAgICBjb25zdCBtZXJnZVByb3BzID0gKG9iajEsIG9iajIpID0+IHsKCSAgICAgICAgb2JqMSA9IG9iajEgPyBvYmoxIDoge307CgkgICAgICAgIG9iajIgPSBvYmoyID8gb2JqMiA6IHt9OwoJICAgICAgICByZXR1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AgIHRoaXMuYmluZGVycyA9IFtdOwoJICAgICAgICB9CgoJICAgICAgICBhZGQoaywgdikgewoJICAgICAgICAgICAgaWYgKCF0aGlzLmhhcyhrKSkgewoJICAgICAgICAgICAgICAgIHRoaXMuc2V0KGssIHYpOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgLy8gc3VwcHJlc3MgZHVwbGNhdGVkIGtleSBlcnJvcgoJICAgICAgICAgICAgLy8gZWxzZQoJICAgICAgICAgICAgLy8gdGhyb3cgYEVycm9yOiBhZGRpbmcgZHVwbGljYXRlZCBrZXkgJyR7a30nIHRvIFJlZkVsZW1lbnRzYDsKCSAgICAgICAgfQoKCSAgICAgICAgYWRkQmluZGVyKGJpbmRlcikgewoJICAgICAgICAgICAgdGhpcy5iaW5kZXJzLnB1c2goYmluZGVyKTsKCSAgICAgICAgfQoKCSAgICAgICAgYmluZEFsbCgpIHsKCSAgICAgICAgICAgIHRoaXMuYmluZGVycy5mb3JFYWNoKGJpbmRlciA9PiBiaW5kZXIuYmluZCgpKTsKCSAgICAgICAgfQoJICAgIH0KCgkgICAgY2xhc3MgTGF0ZUJpbmRlciB7CgkgICAgICAgIGNvbnN0cnVjdG9yKGNvbnRhaW5lciwgdmFsdWVGdW5jLCBjdHgsIGFyZ3MpIHsKCSAgICAgICAgICAgIHRoaXMuY29udGFpbmVyID0gY29udGFpbmVyOwoJICAgICAgICAgICAgdGhpcy52YWx1ZUZ1bmMgPSB2YWx1ZUZ1bmM7CgkgICAgICAgICAgICB0aGlzLmN0eCA9IGN0eDsKCSAgICAgICAgICAgIHRoaXMuYXJncyA9IGFyZ3M7CgkgICAgICAgIH0KCgkgICAgICAgIGJpbmQoKSB7CgkgICAgICAgICAgICBsZXQgdiA9IHRoaXMudmFsdWVGdW5jLmFwcGx5KHRoaXMuY3R4LCB0aGlzLmFyZ3MpOwoJICAgICAgICAgICAgaWYgKHRoaXMuY29udGFpbmVyIGluc3RhbmNlb2YgQXJyYXkpIHsKCSAgICAgICAgICAgICAgICBsZXQgaWR4ID0gdGhpcy5jb250YWluZXIuaW5kZXhPZih0aGlzKTsKCSAgICAgICAgICAgICAgICBpZiAoaWR4ID49IDApIHsKCSAgICAgICAgICAgICAgICAgICAgbGV0IGFyZ3MgPSBbaWR4LCAxXTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKHYpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGFyZ3MucHVzaCh2KTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICBbXS5zcGxpY2UuYXBwbHkodGhpcy5jb250YWluZXIsIGFyZ3MpOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0gZWxzZSBpZiAodHlwZW9mIHRoaXMuY29udGFpbmVyID09PSAnb2JqZWN0JykgewoJICAgICAgICAgICAgICAgIGxldCBrID0gT2JqZWN0LmtleXModGhpcy5jb250YWluZXIpLmZpbmQodiA9PiB0aGlzLmNvbnRhaW5lclt2XSA9PT0gdGhpcyk7CgkgICAgICAgICAgICAgICAgaWYgKGspIHsKCSAgICAgICAgICAgICAgICAgICAgaWYgKHYpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHRoaXMuY29udGFpbmVyW2tdID0gdjsKCSAgICAgICAgICAgICAgICAgICAgfSBlbHNlIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGRlbGV0ZSB0aGlzLmNvbnRhaW5lcltrXTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgfQoJICAgIH0KCgkgICAgY2xhc3MgV2F5Q29sbGVjdGlvbiBleHRlbmRzIEFycmF5IHsKCSAgICAgICAgY29uc3RydWN0b3IoKSB7CgkgICAgICAgICAgICBzdXBlcigpOwoJICAgICAgICAgICAgdGhpcy5maXJzdE1hcCA9IHt9OwoJICAgICAgICAgICAgdGhpcy5sYXN0TWFwID0ge307CgkgICAgICAgIH0KCgkgICAgICAgIGFkZFdheSh3YXkpIHsKCSAgICAgICAgICAgIHdheSA9IHdheS50b0Nvb3Jkc0FycmF5KCk7CgkgICAgICAgICAgICBpZiAod2F5Lmxlbmd0aCA+IDApIHsKCSAgICAgICAgICAgICAgICB0aGlzLnB1c2god2F5KTsKCSAgICAgICAgICAgICAgICBhZGRUb01hcCh0aGlzLmZpcnN0TWFwLCBjb29yZHNUb0tleShmaXJzdCh3YXkpKSwgd2F5KTsKCSAgICAgICAgICAgICAgICBhZGRUb01hcCh0aGlzLmxhc3RNYXAsIGNvb3Jkc1RvS2V5KGxhc3Qod2F5KSksIHdheSk7CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCgkgICAgICAgIHRvU3RyaW5ncygpIHsKCSAgICAgICAgICAgIGxldCBzdHJpbmdzID0gW10sIHdheSA9IG51bGw7CgkgICAgICAgICAgICB3aGlsZSAod2F5ID0gdGhpcy5zaGlmdCgpKSB7CgkgICAgICAgICAgICAgICAgcmVtb3ZlRnJvbU1hcCh0aGlzLmZpcnN0TWFwLCBjb29yZHNUb0tleShmaXJzdCh3YXkpKSwgd2F5KTsKCSAgICAgICAgICAgICAgICByZW1vdmVGcm9tTWFwKHRoaXMubGFzdE1hcCwgY29vcmRzVG9LZXkobGFzdCh3YXkpKSwgd2F5KTsKCSAgICAgICAgICAgICAgICBsZXQgY3VycmVudCA9IHdheSwgbmV4dCA9IG51bGw7CgkgICAgICAgICAgICAgICAgZG8gewoJICAgICAgICAgICAgICAgICAgICBsZXQga2V5ID0gY29vcmRzVG9LZXkobGFzdChjdXJyZW50KSksIHNob3VsZFJldmVyc2UgPSBmYWxzZTsKCgkgICAgICAgICAgICAgICAgICAgIG5leHQgPSBnZXRGaXJzdEZyb21NYXAodGhpcy5maXJzdE1hcCwga2V5KTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKCFuZXh0KSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBuZXh0ID0gZ2V0Rmlyc3RGcm9tTWFwKHRoaXMubGFzdE1hcCwga2V5KTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHNob3VsZFJldmVyc2UgPSB0cnVlOwoJICAgICAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgICAgICBpZiAobmV4dCkgewoJICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5zcGxpY2UodGhpcy5pbmRleE9mKG5leHQpLCAxKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHJlbW92ZUZyb21NYXAodGhpcy5maXJzdE1hcCwgY29vcmRzVG9LZXkoZmlyc3QobmV4dCkpLCBuZXh0KTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHJlbW92ZUZyb21NYXAodGhpcy5sYXN0TWFwLCBjb29yZHNUb0tleShsYXN0KG5leHQpKSwgbmV4dCk7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAoc2hvdWxkUmV2ZXJzZSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIC8vIGFsd2F5cyByZXZlcnNlIHNob3J0ZXIgb25lIHRvIHNhdmUgdGltZQoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGlmIChuZXh0Lmxlbmd0aCA+IGN1cnJlbnQubGVuZ3RoKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFtjdXJyZW50LCBuZXh0XSA9IFtuZXh0LCBjdXJyZW50XTsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgbmV4dC5yZXZlcnNlKCk7CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgICAgICAgICAgY3VycmVudCA9IGN1cnJlbnQuY29uY2F0KG5leHQuc2xpY2UoMSkpOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfSB3aGlsZSAobmV4dCk7CgkgICAgICAgICAgICAgICAgc3RyaW5ncy5wdXNoKHN0clRvRmxvYXQoY3VycmVudCkpOwoJICAgICAgICAgICAgfQoKCSAgICAgICAgICAgIHJldHVybiBzdHJpbmdzOwoJICAgICAgICB9CgoJICAgICAgICB0b1JpbmdzKGRpcmVjdGlvbikgewoJICAgICAgICAgICAgbGV0IHN0cmluZ3MgPSB0aGlzLnRvU3RyaW5ncygpOwoJICAgICAgICAgICAgbGV0IHJpbmdzID0gW10sIHN0cmluZyA9IG51bGw7CgkgICAgICAgICAgICB3aGlsZSAoc3RyaW5nID0gc3RyaW5ncy5zaGlmdCgpKSB7CgkgICAgICAgICAgICAgICAgaWYgKGlzUmluZyhzdHJpbmcpKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmIChyaW5nRGlyZWN0aW9uKHN0cmluZykgIT09IGRpcmVjdGlvbikgewoJICAgICAgICAgICAgICAgICAgICAgICAgc3RyaW5nLnJldmVyc2UoKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICByaW5ncy5wdXNoKHN0cmluZyk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmV0dXJuIHJpbmdzOwoJICAgICAgICB9CgkgICAgfQoKCSAgICByZXR1cm4gewoJICAgICAgICBwdXJnZVByb3BzLCBtZXJnZVByb3BzLAoJICAgICAgICBmaXJzdCwgbGFzdCwgY29vcmRzVG9LZXksCgkgICAgICAgIGFkZFRvTWFwLCByZW1vdmVGcm9tTWFwLCBnZXRGaXJzdEZyb21NYXAsCgkgICAgICAgIGlzUmluZywgcmluZ0RpcmVjdGlvbiwgcHRJbnNpZGVQb2x5Z29uLCBzdHJUb0Zsb2F0LAoJICAgICAgICBSZWZFbGVtZW50cywgTGF0ZUJpbmRlciwgV2F5Q29sbGVjdGlvbgoJICAgIH07Cgl9KSgpOwoKCXZhciBidWlsZGluZyA9IHsKCX07Cgl2YXIgaGlnaHdheSA9IHsKCQl3aGl0ZWxpc3Q6IFsKCQkJInNlcnZpY2VzIiwKCQkJInJlc3RfYXJlYSIsCgkJCSJlc2NhcGUiLAoJCQkiZWxldmF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nba10gPSB2OwoJICAgICAgICAgICAgdGhpcy5oYXNUYWcgPSBrID8gdHJ1ZSA6IGZhbHNlOwoJICAgICAgICB9CgoJICAgICAgICBhZGRQcm9wKGssIHYpIHsKCSAgICAgICAgICAgIHRoaXMucHJvcHNba10gPSB2OwoJICAgICAgICB9CgoJICAgICAgICBhZGRQcm9wcyhwcm9wcykgewoJICAgICAgICAgICAgdGhpcy5wcm9wcyA9IE9iamVjdC5hc3NpZ24odGhpcy5wcm9wcywgcHJvcHMpOwoJICAgICAgICB9CgoJICAgICAgICBnZXRDb21wb3NpdGVJZCgpIHsKCSAgICAgICAgICAgIHJldHVybiBgJHt0aGlzLnR5cGV9LyR7dGhpcy5pZH1gOwoJICAgICAgICB9CgoJICAgICAgICBnZXRQcm9wcygpIHsKCSAgICAgICAgICAgIHJldHVybiBPYmplY3QuYXNzaWduKHRoaXMucHJvcHMsIHRoaXMudGFncyk7CgkgICAgICAgIH0KCgkgICAgICAgIHRvRmVhdHVyZUFycmF5KCkgewoJICAgICAgICAgICAgcmV0dXJuIFtdOwoJICAgICAgICB9CgkgICAgfQoKCSAgICBjbGFzcyBOb2RlIGV4dGVuZHMgT3NtT2JqZWN0IHsKCSAgICAgICAgY29uc3RydWN0b3IoaWQsIHJlZkVsZW1zKSB7CgkgICAgICAgICAgICBzdXBlcignbm9kZScsIGlkLCByZWZFbGVtcyk7CgkgICAgICAgICAgICB0aGlzLmxhdExuZyA9IG51bGw7CgkgICAgICAgIH0KCgkgICAgICAgIHNldExhdExuZyhsYXRMbmcpIHsKCSAgICAgICAgICAgIHRoaXMubGF0TG5nID0gbGF0TG5nOwoJICAgICAgICB9CgoJICAgICAgICB0b0ZlYXR1cmVBcnJheSgpIHsKCSAgICAgICAgICAgIGlmICh0aGlzLmxhdExuZykgewoJICAgICAgICAgICAgICAgIHJldHVybiBbewoJICAgICAgICAgICAgICAgICAgICB0eXBlOiAnRmVhdHVyZScsCgkgICAgICAgICAgICAgICAgICAgIGlkOiB0aGlzLmdldENvbXBvc2l0ZUlkKCksCgkgICAgICAgICAgICAgICAgICAgIHByb3BlcnRpZXM6IHRoaXMuZ2V0UHJvcHMoKSwKCSAgICAgICAgICAgICAgICAgICAgZ2VvbWV0cnk6IHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICdQb2ludCcsCgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogc3RyVG9GbG9hdChbdGhpcy5sYXRMbmcubG9uLCB0aGlzLmxhdExuZy5sYXRdKQoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfV07CgkgICAgICAgICAgICB9CgoJICAgICAgICAgICAgcmV0dXJuIFtdOwoJICAgICAgICB9CgoJICAgICAgICBnZXRMYXRMbmcoKSB7CgkgICAgICAgICAgICByZXR1cm4gdGhpcy5sYXRMbmc7CgkgICAgICAgIH0KCSAgICB9CgoJICAgIGNsYXNzIFdheSBleHRlbmRzIE9zbU9iamVjdCB7CgkgICAgICAgIGNvbnN0cnVjdG9yKGlkLCByZWZFbGVtcykgewoJICAgICAgICAgICAgc3VwZXIoJ3dheScsIGlkLCByZWZFbGVtcyk7CgkgICAgICAgICAgICB0aGlzLmxhdExuZ0FycmF5ID0gW107CgkgICAgICAgICAgICB0aGlzLmlzUG9seWdvbiA9IGZhbHNlOwoJICAgICAgICB9CgoJICAgICAgICBhZGRMYXRMbmcobGF0TG5nKSB7CgkgICAgICAgICAgICB0aGlzLmxhdExuZ0FycmF5LnB1c2gobGF0TG5nKTsKCSAgICAgICAgfQoKCSAgICAgICAgc2V0TGF0TG5nQXJyYXkobGF0TG5nQXJyYXkpIHsKCSAgICAgICAgICAgIHRoaXMubGF0TG5nQXJyYXkgPSBsYXRMbmdBcnJheTsKCSAgICAgICAgfQoKCSAgICAgICAgYWRkTm9kZVJlZihyZWYpIHsKCSAgICAgICAgICAgIGxldCBiaW5kZXIgPSBuZXcgTGF0ZUJpbmRlcih0aGlzLmxhdExuZ0FycmF5LCBmdW5jdGlvbiAoaWQpIHsKCSAgICAgICAgICAgICAgICBsZXQgbm9kZSA9IHRoaXMucmVmRWxlbXMuZ2V0KGBub2RlLyR7aWR9YCk7CgkgICAgICAgICAgICAgICAgaWYgKG5vZGUpIHsKCSAgICAgICAgICAgICAgICAgICAgbm9kZS5yZWZDb3VudCsrOwoJICAgICAgICAgICAgICAgICAgICByZXR1cm4gbm9kZS5nZXRMYXRMbmcoKTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9LCB0aGlzLCBbcmVmXSk7CgoJICAgICAgICAgICAgdGhpcy5sYXRMbmdBcnJheS5wdXNoKGJpbmRlcik7CgkgICAgICAgICAgICB0aGlzLnJlZkVsZW1zLmFkZEJpbmRlcihiaW5kZXIpOwoJICAgICAgICB9CgoJICAgICAgICBhbmFseXplR2VvbWV0cnlUeXBlKGssIHYpIHsKCSAgICAgICAgICAgIGxldCBvID0gcG9seWdvblRhZ3Nba107CgkgICAgICAgICAgICBpZiAobykgewoJICAgICAgICAgICAgICAgIHRoaXMuaXNQb2x5Z29uID0gdHJ1ZTsKCSAgICAgICAgICAgICAgICBpZiAoby53aGl0ZWxpc3QpIHsKCSAgICAgICAgICAgICAgICAgICAgdGhpcy5pc1BvbHlnb24gPSBvLndoaXRlbGlzdC5pbmRleE9mKHYpID49IDAgPyB0cnVlIDogZmFsc2U7CgkgICAgICAgICAgICAgICAgfSBlbHNlIGlmIChvLmJsYWNrbGlzdCkgewoJICAgICAgICAgICAgICAgICAgICB0aGlzLmlzUG9seWdvbiA9IG8uYmxhY2tsaXN0LmluZGV4T2YodikgPj0gMCA/IGZhbHNlIDogdHJ1ZTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCgkgICAgICAgIGFkZFRhZ3ModGFncykgewoJICAgICAgICAgICAgc3VwZXIuYWRkVGFncyh0YWdzKTsKCSAgICAgICAgICAgIGZvciAobGV0IFtrLCB2XSBvZiBPYmplY3QuZW50cmllcyh0YWdzKSkgewoJICAgICAgICAgICAgICAgIHRoaXMuYW5hbHl6ZUdlb21ldHJ5VHlwZShrLCB2KTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgfQoKCSAgICAgICAgYWRkVGFnKGssIHYpIHsKCSAgICAgICAgICAgIHN1cGVyLmFkZFRhZyhrLCB2KTsKCSAgICAgICAgICAgIHRoaXMuYW5hbHl6ZUdlb21ldHJ5VHlwZShrLCB2KTsKCSAgICAgICAgfQoKCSAgICAgICAgdG9Db29yZHNBcnJheSgpIHsKCSAgICAgICAgICAgIHJldHVybiB0aGlzLmxhdExuZ0FycmF5Lm1hcChsYXRMbmcgPT4gW2xhdExuZy5sb24sIGxhdExuZy5sYXRdKTsKCSAgICAgICAgfQoKCSAgICAgICAgdG9GZWF0dXJlQXJyYXkoKSB7CgkgICAgICAgICAgICBsZXQgY29vcmRzQXJyYXkgPSB0aGlzLnRvQ29vcmRzQXJyYXkoKTsKCSAgICAgICAgICAgIGlmIChjb29yZHNBcnJheS5sZW5ndGggPiAxKSB7CgkgICAgICAgICAgICAgICAgY29vcmRzQXJyYXkgPSBzdHJUb0Zsb2F0KGNvb3Jkc0FycmF5KTsKCSAgICAgICAgICAgICAgICBsZXQgZmVhdHVyZSA9IHsKCSAgICAgICAgICAgICAgICAgICAgdHlwZTogJ0ZlYXR1cmUnLAoJICAgICAgICAgICAgICAgICAgICBpZDogdGhpcy5nZXRDb21wb3NpdGVJZCgpLAoJICAgICAgICAgICAgICAgICAgICBwcm9wZXJ0aWVzOiB0aGlzLmdldFByb3BzKCksCgkgICAgICAgICAgICAgICAgICAgIGdlb21ldHJ5OiB7CgkgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAnTGluZVN0cmluZycsCgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogY29vcmRzQXJyYXkKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH07CgoJICAgICAgICAgICAgICAgIGlmICh0aGlzLmlzUG9seWdvbiAmJiBpc1JpbmcoY29vcmRzQXJyYXkpKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmIChyaW5nRGlyZWN0aW9uKGNvb3Jkc0FycmF5KSAhPT0gJ2NvdW50ZXJjbG9ja3dpc2UnKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZHNBcnJheS5yZXZlcnNlKCk7CgkgICAgICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgICAgIGZlYXR1cmUuZ2VvbWV0cnkgPSB7CgkgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAnUG9seWdvbicsCgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogW2Nvb3Jkc0FycmF5XQoJICAgICAgICAgICAgICAgICAgICB9OwoKCSAgICAgICAgICAgICAgICAgICAgcmV0dXJuIFtmZWF0dXJlXTsKCSAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIHJldHVybiBbZmVhdHVyZV07CgkgICAgICAgICAgICB9CgoJICAgICAgICAgICAgcmV0dXJuIFtdOwoJICAgICAgICB9CgkgICAgfQoKCSAgICBjbGFzcyBSZWxhdGlvbiBleHRlbmRzIE9zbU9iamVjdCB7CgkgICAgICAgIGNvbnN0cnVjdG9yKGlkLCByZWZFbGVtcykgewoJICAgICAgICAgICAgc3VwZXIoJ3JlbGF0aW9uJywgaWQsIHJlZkVsZW1zKTsKCSAgICAgICAgICAgIHRoaXMucmVsYXRpb25zID0gW107CgkgICAgICAgICAgICB0aGlzLm5vZGVzID0gW107CgkgICAgICAgICAgICB0aGlzLmJvdW5kcyA9IG51bGw7CgkgICAgICAgIH0KCgkgICAgICAgIHNldEJvdW5kcyhib3VuZHMpIHsKCSAgICAgICAgICAgIHRoaXMuYm91bmRzID0gYm91bmRzOwoJICAgICAgICB9CgoJICAgICAgICBhZGRNZW1iZXIobWVtYmVyKSB7CgkgICAgICAgICAgICBzd2l0Y2ggKG1lbWJlci50eXBlKSB7CgkgICAgICAgICAgICAgICAgLy8gc3VwZXIgcmVsYXRpb24sIG5lZWQgdG8gZG8gY29tYmluYXRpb24KCSAgICAgICAgICAgICAgICBjYXNlICdyZWxhdGlvbic6CgkgICAgICAgICAgICAgICAgICAgIGxldCBiaW5kZXIgPSBuZXcgTGF0ZUJpbmRlcih0aGlzLnJlbGF0aW9ucywgZnVuY3Rpb24gKGlkKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBsZXQgcmVsYXRpb24gPSB0aGlzLnJlZkVsZW1zLmdldChgcmVsYXRpb24vJHtpZH1gKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIGlmIChyZWxhdGlvbikgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJlbGF0aW9uLnJlZkNvdW50Kys7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHJlbGF0aW9uOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB9LCB0aGlzLCBbbWVtYmVyLnJlZl0pOwoJICAgICAgICAgICAgICAgICAgICB0aGlzLnJlbGF0aW9ucy5wdXNoKGJpbmRlcik7CgkgICAgICAgICAgICAgICAgICAgIHRoaXMucmVmRWxlbXMuYWRkQmluZGVyKGJpbmRlcik7CgkgICAgICAgICAgICAgICAgICAgIGJyZWFrOwoKCSAgICAgICAgICAgICAgICBjYXNlICd3YXknOgoJICAgICAgICAgICAgICAgICAgICBpZiAoIW1lbWJlci5yb2xlKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBtZW1iZXIucm9sZSA9ICcnOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGxldCB3YXlzID0gdGhpc1ttZW1iZXIucm9sZV07CgkgICAgICAgICAgICAgICAgICAgIGlmICghd2F5cykgewoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5cyA9IHRoaXNbbWVtYmVyLnJvbGVdID0gW107CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgaWYgKG1lbWJlci5nZW9tZXRyeSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgbGV0IHdheSA9IG5ldyBXYXkobWVtYmVyLnJlZiwgdGhpcy5yZWZFbGVtcyk7CgkgICAgICAgICAgICAgICAgICAgICAgICB3YXkuc2V0TGF0TG5nQXJyYXkobWVtYmVyLmdlb21ldHJ5KTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHdheS5yZWZDb3VudCsrOwoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5cy5wdXNoKHdheSk7CgkgICAgICAgICAgICAgICAgICAgIH0gZWxzZSBpZiAobWVtYmVyLm5vZGVzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBsZXQgd2F5ID0gbmV3IFdheShtZW1iZXIucmVmLCB0aGlzLnJlZkVsZW1zKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIGZvciAobGV0IG5pZCBvZiBtZW1iZXIubm9kZXMpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB3YXkuYWRkTm9kZVJlZihuaWQpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5LnJlZkNvdW50Kys7CgkgICAgICAgICAgICAgICAgICAgICAgICB3YXlzLnB1c2god2F5KTsKCSAgICAgICAgICAgICAgICAgICAgfSBlbHNlIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGxldCBiaW5kZXIgPSBuZXcgTGF0ZUJpbmRlcih3YXlzLCBmdW5jdGlvbiAoaWQpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBsZXQgd2F5ID0gdGhpcy5yZWZFbGVtcy5nZXQoYHdheS8ke2lkfWApOwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGlmICh3YXkpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgd2F5LnJlZkNvdW50Kys7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiB3YXk7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICAgICAgfSwgdGhpcywgW21lbWJlci5yZWZdKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHdheXMucHVzaChiaW5kZXIpOwoJICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5yZWZFbGVtcy5hZGRCaW5kZXIoYmluZGVyKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICBicmVhazsKCgkgICAgICAgICAgICAgICAgY2FzZSAnbm9kZSc6CgkgICAgICAgICAgICAgICAgICAgIGxldCBub2RlID0gbnVsbDsKCSAgICAgICAgICAgICAgICAgICAgaWYgKG1lbWJlci5sYXQgJiYgbWVtYmVyLmxvbikgewoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZSA9IG5ldyBOb2RlKG1lbWJlci5yZWYsIHRoaXMucmVmRWxlbXMpOwoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS5zZXRMYXRMbmcoeyBsb246IG1lbWJlci5sb24sIGxhdDogbWVtYmVyLmxhdCB9KTsKCSAgICAgICAgICAgICAgICAgICAgICAgIGlmIChtZW1iZXIudGFncykgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIG5vZGUuYWRkVGFncyhtZW1iZXIudGFncyk7CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgICAgICBmb3IgKGxldCBbaywgdl0gb2YgT2JqZWN0LmVudHJpZXMobWVtYmVyKSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGlmIChbJ2lkJywgJ3R5cGUnLCAnbGF0JywgJ2xvbiddLmluZGV4T2YoaykgPCAwKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIG5vZGUuYWRkUHJvcChrLCB2KTsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS5yZWZDb3VudCsrOwoJICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5ub2Rlcy5wdXNoKG5vZGUpOwoJICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgbGV0IGJpbmRlciA9IG5ldyBMYXRlQmluZGVyKHRoaXMubm9kZXMsIGZ1bmN0aW9uIChpZCkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGxldCBub2RlID0gdGhpcy5yZWZFbGVtcy5nZXQoYG5vZGUvJHtpZH1gKTsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBpZiAobm9kZSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBub2RlLnJlZkNvdW50Kys7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiBub2RlOwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgICAgIH0sIHRoaXMsIFttZW1iZXIucmVmXSk7CgkgICAgICAgICAgICAgICAgICAgICAgICB0aGlzLm5vZGVzLnB1c2goYmluZGVyKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHRoaXMucmVmRWxlbXMuYWRkQmluZGVyKGJpbmRlcik7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCgkgICAgICAgIHRvRmVhdHVyZUFycmF5KCkgewoJICAgICAgICAgICAgY29uc3QgY29uc3RydWN0U3RyaW5nR2VvbWV0cnkgPSAod3MpID0+IHsKCSAgICAgICAgICAgICAgICBsZXQgc3RyaW5ncyA9IHdzID8gd3MudG9TdHJpbmdzKCkgOiBbXTsKCSAgICAgICAgICAgICAgICBpZiAoc3RyaW5ncy5sZW5ndGggPiAwKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmIChzdHJpbmdzLmxlbmd0aCA9PT0gMSkgcmV0dXJuIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICdMaW5lU3RyaW5nJywKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBzdHJpbmdzWzBdCgkgICAgICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgICAgIHJldHVybiB7CgkgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAnTXVsdGlMaW5lU3RyaW5nJywKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBzdHJpbmdzCgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgcmV0dXJuIG51bGw7CgkgICAgICAgICAgICB9OwoKCSAgICAgICAgICAgIGNvbnN0IGNvbnN0cnVjdFBvbHlnb25HZW9tZXRyeSA9IChvd3MsIGl3cykgPT4gewoJICAgICAgICAgICAgICAgIGxldCBvdXRlclJpbmdzID0gb3dzID8gb3dzLnRvUmluZ3MoJ2NvdW50ZXJjbG9ja3dpc2UnKSA6IFtdLAoJICAgICAgICAgICAgICAgICAgICBpbm5lclJpbmdzID0gaXdzID8gaXdzLnRvUmluZ3MoJ2Nsb2Nrd2lzZScpIDogW107CgoJICAgICAgICAgICAgICAgIGlmIChvdXRlclJpbmdzLmxlbmd0aCA+IDApIHsKCSAgICAgICAgICAgICAgICAgICAgbGV0IGNvbXBvc2l0UG9seW9ucyA9IFtdOwoKCSAgICAgICAgICAgICAgICAgICAgbGV0IHJpbmcgPSBudWxsOwoJICAgICAgICAgICAgICAgICAgICBmb3IgKHJpbmcgb2Ygb3V0ZXJSaW5ncykKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvbXBvc2l0UG9seW9ucy5wdXNoKFtyaW5nXSk7CgoJICAgICAgICAgICAgICAgICAgICAvLyBsaW5rIGlubmVyIHBvbHlnb25zIHRvIG91dGVyIGNvbnRhaW5lcnMKCSAgICAgICAgICAgICAgICAgICAgd2hpbGUgKHJpbmcgPSBpbm5lclJpbmdzLnNoaWZ0KCkpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGZvciAobGV0IGlkeCBpbiBvdXRlclJpbmdzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgaWYgKHB0SW5zaWRlUG9seWdvbihmaXJzdChyaW5nKSwgb3V0ZXJSaW5nc1tpZHhdKSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb21wb3NpdFBvbHlvbnNbaWR4XS5wdXNoKHJpbmcpOwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgICAgIC8vIGNvbnN0cnVjdCB0aGUgUG9seWdvbi9NdWx0aVBvbHlnb24gZ2VvbWV0cnkKCSAgICAgICAgICAgICAgICAgICAgaWYgKGNvbXBvc2l0UG9seW9ucy5sZW5ndGggPT09IDEpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgdHlwZTogJ1BvbHlnb24nLAoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBjb21wb3NpdFBvbHlvbnNbMF0KCSAgICAgICAgICAgICAgICAgICAgICAgIH07CgkgICAgICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgICAgIHJldHVybiB7CgkgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAnTXVsdGlQb2x5Z29uJywKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBjb21wb3NpdFBvbHlvbnMKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgcmV0dXJuIG51bGw7CgkgICAgICAgICAgICB9OwoKCSAgICAgICAgICAgIGxldCBwb2x5Z29uRmVhdHVyZXMgPSBbXSwgc3RyaW5nRmVhdHVyZXMgPSBbXSwgcG9pbnRGZWF0dXJlcyA9IFtdOwoJICAgICAgICAgICAgY29uc3Qgd2F5c0ZpZWxkTmFtZXMgPSBbJ291dGVyJywgJ2lubmVyJywgJyddOwoJICAgICAgICAgICAgLy8gbmVlZCB0byBkbyBjb21iaW5hdGlvbiB3aGVuIHRoZXJlJ3JlIG5lc3RlZCByZWxhdGlvbnMKCSAgICAgICAgICAgIGZvciAobGV0IHJlbGF0aW9uIG9mIHRoaXMucmVsYXRpb25zKSB7CgkgICAgICAgICAgICAgICAgaWYgKHJlbGF0aW9uKSB7CgkgICAgICAgICAgICAgICAgICAgIGZvciAobGV0IGZpZWxkTmFtZSBvZiB3YXlzRmllbGROYW1lcykgewoJICAgICAgICAgICAgICAgICAgICAgICAgbGV0IHdheXMgPSByZWxhdGlvbltmaWVsZE5hbWVdOwoJICAgICAgICAgICAgICAgICAgICAgICAgaWYgKHdheXMpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBsZXQgdGhpc1dheXMgPSB0aGlzW2ZpZWxkTmFtZV07CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgaWYgKHRoaXNXYXlzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFtdLnNwbGljZS5hcHBseSh0aGlzV2F5cywgW3RoaXNXYXlzLmxlbmd0aCwgMF0uY29uY2F0KHdheXMpKTsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB0aGlzW2ZpZWxkTmFtZV0gPSB3YXlzOwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCgkgICAgICAgICAgICBmb3IgKGxldCBmaWVsZE5hbWUgb2Ygd2F5c0ZpZWxkTmFtZXMpIHsKCSAgICAgICAgICAgICAgICBsZXQgd2F5cyA9IHRoaXNbZmllbGROYW1lXTsKCSAgICAgICAgICAgICAgICBpZiAod2F5cykgewoJICAgICAgICAgICAgICAgICAgICB0aGlzW2ZpZWxkTmFtZV0gPSBuZXcgV2F5Q29sbGVjdGlvbigpOwoJICAgICAgICAgICAgICAgICAgICBmb3IgKGxldCB3YXkgb2Ygd2F5cykgewoJICAgICAgICAgICAgICAgICAgICAgICAgdGhpc1tmaWVsZE5hbWVdLmFkZFdheSh3YXkpOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoKCSAgICAgICAgICAgIGxldCBnZW9tZXRyeSA9IG51bGw7CgoJICAgICAgICAgICAgbGV0IGZlYXR1cmUgPSB7CgkgICAgICAgICAgICAgICAgdHlwZTogJ0ZlYXR1cmUnLAoJICAgICAgICAgICAgICAgIGlkOiB0aGlzLmdldENvbXBvc2l0ZUlkKCksCgkgICAgICAgICAgICAgICAgYmJveDogdGhpcy5ib3VuZHMsCgkgICAgICAgICAgICAgICAgcHJvcGVydGllczogdGhpcy5nZXRQcm9wcygpCgkgICAgICAgICAgICB9OwoKCSAgICAgICAgICAgIGlmICghdGhpcy5ib3VuZHMpIHsKCSAgICAgICAgICAgICAgICBkZWxldGUgZmVhdHVyZS5iYm94OwoJICAgICAgICAgICAgfQoKCSAgICAgICAgICAgIGlmICh0aGlzLm91dGVyKSB7CgkgICAgICAgICAgICAgICAgZ2VvbWV0cnkgPSBjb25zdHJ1Y3RQb2x5Z29uR2VvbWV0cnkodGhpcy5vdXRlciwgdGhpcy5pbm5lcik7CgkgICAgICAgICAgICAgICAgaWYgKGdlb21ldHJ5KSB7CgkgICAgICAgICAgICAgICAgICAgIGZlYXR1cmUuZ2VvbWV0cnkgPSBnZW9tZXRyeTsKCSAgICAgICAgICAgICAgICAgICAgcG9seWdvbkZlYXR1cmVzLnB1c2goZmVhdHVyZSk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgZWxzZSBpZiAodGhpc1snJ10pIHsKCSAgICAgICAgICAgICAgICBnZW9tZXRyeSA9IGNvbnN0cnVjdFN0cmluZ0dlb21ldHJ5KHRoaXNbJyddKTsKCSAgICAgICAgICAgICAgICBpZiAoZ2VvbWV0cnkpIHsKCSAgICAgICAgICAgICAgICAgICAgZmVhdHVyZS5nZW9tZXRyeSA9IGdlb21ldHJ5OwoJICAgICAgICAgICAgICAgICAgICBzdHJpbmdGZWF0dXJlcy5wdXNoKGZlYXR1cmUpOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCgkgICAgICAgICAgICBmb3IgKGxldCBub2RlIG9mIHRoaXMubm9kZXMpIHsKCSAgICAgICAgICAgICAgICBwb2ludEZlYXR1cmVzID0gcG9pbnRGZWF0dXJlcy5jb25jYXQobm9kZS50b0ZlYXR1cmVBcnJheSgpKTsKCSAgICAgICAgICAgIH0KCgkgICAgICAgICAgICByZXR1cm4gcG9seWdvbkZlYXR1cmVzLmNvbmNhdChzdHJpbmdGZWF0dXJlcykuY29uY2F0KHBvaW50RmVhdHVyZXMpOwoJICAgICAgICB9CgkgICAgfQoKCSAgICByZXR1cm4geyBOb2RlLCBXYXksIFJlbGF0aW9uIH07Cgl9KSgpOwoKCXZhciB4bWxwYXJzZXIgPSAoKCkgPT4gewoKCSAgICBmdW5jdGlvbiBjb25kaXRpb25lZChldnQpIHsKCSAgICAgICAgcmV0dXJuIGV2dC5tYXRjaCgvXiguKz8pXFsoLis/KVxdPiQvZykgIT0gbnVsbDsKCSAgICB9CgoJICAgIGZ1bmN0aW9uIHBhcnNlRXZlbnQoZXZ0KSB7CgkgICAgICAgIGxldCBtYXRjaCA9IC9eKC4rPylcWyguKz8pXF0+JC9nLmV4ZWMoZXZ0KTsKCSAgICAgICAgaWYgKG1hdGNoKSB7CgkgICAgICAgICAgICByZXR1cm4geyBldnQ6IG1hdGNoWzFdICsgJz4nLCBleHA6IG1hdGNoWzJdIH07CgkgICAgICAgIH0KCSAgICAgICAgcmV0dXJuIHsgZXZ0OiBldnQgfTsKCSAgICB9CgoJICAgIGZ1bmN0aW9uIGdlbkNvbmRpdGlvbkZ1bmMoY29uZCkgewoJICAgICAgICBsZXQgYm9keSA9ICdyZXR1cm4gJyArIGNvbmQucmVwbGFjZSgvKFwkLis/KSg/PVs9IS5dKS9nLCAnbm9kZS4kJicpICsgJzsnOwoJICAgICAgICByZXR1cm4gbmV3IEZ1bmN0aW9uKCdub2RlJywgYm9keSk7CgkgICAgfQoKCSAgICByZXR1cm4gY2xhc3MgewoJICAgICAgICBjb25zdHJ1Y3RvcihvcHRzKSB7CgkgICAgICAgICAgICBpZiAob3B0cykgewoJICAgICAgICAgICAgICAgIHRoaXMucXVlcnlQYXJlbnQgPSBvcHRzLnF1ZXJ5UGFyZW50ID8gdHJ1ZSA6IGZhbHNlOwoJICAgICAgICAgICAgICAgIHRoaXMucHJvZ3Jlc3NpdmUgPSBvcHRzLnByb2dyZXNzaXZlOwoJICAgICAgICAgICAgICAgIGlmICh0aGlzLnF1ZXJ5UGFyZW50KSB7CgkgICAgICAgICAgICAgICAgICAgIHRoaXMucGFyZW50TWFwID0gbmV3IFdlYWtNYXAoKTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgICAgICB0aGlzLmV2dExpc3RlbmVycyA9IHt9OwoJICAgICAgICB9CgoJICAgICAgICBwYXJzZSh4bWwsIHBhcmVudCwgZGlyKSB7CgkgICAgICAgICAgICBkaXIgPSBkaXIgPyBkaXIgKyAnLicgOiAnJzsKCSAgICAgICAgICAgIGxldCBub2RlUmVnRXggPSAvPChbXiA+XC9dKykoLio/KT4vbWcsIG5vZGVNYXRjaCA9IG51bGwsIG5vZGVzID0gW107CgkgICAgICAgICAgICB3aGlsZSAobm9kZU1hdGNoID0gbm9kZVJlZ0V4LmV4ZWMoeG1sKSkgewoJICAgICAgICAgICAgICAgIGxldCB0YWcgPSBub2RlTWF0Y2hbMV0sIG5vZGUgPSB7ICR0YWc6IHRhZyB9LCBmdWxsVGFnID0gZGlyICsgdGFnOwoKCSAgICAgICAgICAgICAgICBsZXQgYXR0clRleHQgPSBub2RlTWF0Y2hbMl0udHJpbSgpLCBjbG9zZWQgPSBmYWxzZTsKCSAgICAgICAgICAgICAgICBpZiAoYXR0clRleHQuZW5kc1dpdGgoJy8nKSB8fCB0YWcuc3RhcnRzV2l0aCgnPycpIHx8IHRhZy5zdGFydHNXaXRoKCchJykpIHsKCSAgICAgICAgICAgICAgICAgICAgY2xvc2VkID0gdHJ1ZTsKCSAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIGxldCBhdHRSZWdFeDEgPSAvKFteIF0rPyk9IiguKz8pIi9nLCBhdHRSZWdFeDIgPSAvKFteIF0rPyk9JyguKz8pJy9nOwoJICAgICAgICAgICAgICAgIGxldCBhdHRNYXRjaCA9IG51bGwsIGhhc0F0dHJzID0gZmFsc2U7CgkgICAgICAgICAgICAgICAgd2hpbGUgKGF0dE1hdGNoID0gYXR0UmVnRXgxLmV4ZWMoYXR0clRleHQpKSB7CgkgICAgICAgICAgICAgICAgICAgIGhhc0F0dHJzID0gdHJ1ZTsKCSAgICAgICAgICAgICAgICAgICAgbm9kZVthdHRNYXRjaFsxXV0gPSBhdHRNYXRjaFsyXTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgaWYgKCFoYXNBdHRycykKCSAgICAgICAgICAgICAgICAgICAgd2hpbGUgKGF0dE1hdGNoID0gYXR0UmVnRXgyLmV4ZWMoYXR0clRleHQpKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBoYXNBdHRycyA9IHRydWU7CgkgICAgICAgICAgICAgICAgICAgICAgICBub2RlW2F0dE1hdGNoWzFdXSA9IGF0dE1hdGNoWzJdOwoJICAgICAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIGlmICghaGFzQXR0cnMgJiYgYXR0clRleHQgIT09ICcnKSB7CgkgICAgICAgICAgICAgICAgICAgIG5vZGUudGV4dCA9IGF0dHJUZXh0OwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICBpZiAodGhpcy5wcm9ncmVzc2l2ZSkgewoJICAgICAgICAgICAgICAgICAgICB0aGlzLmVtaXQoYDwke2Z1bGxUYWd9PmAsIG5vZGUsIHBhcmVudCk7CgkgICAgICAgICAgICAgICAgfQoKCSAgICAgICAgICAgICAgICBpZiAoIWNsb3NlZCkgewoJICAgICAgICAgICAgICAgICAgICBsZXQgaW5uZXJSZWdFeCA9IG5ldyBSZWdFeHAoYChbXl0rPyk8XC8ke3RhZ30+YCwgJ2cnKTsKCSAgICAgICAgICAgICAgICAgICAgaW5uZXJSZWdFeC5sYXN0SW5kZXggPSBub2RlUmVnRXgubGFzdEluZGV4OwoJICAgICAgICAgICAgICAgICAgICBsZXQgaW5uZXJNYXRjaCA9IGlubmVyUmVnRXguZXhlYyh4bWwpOwoJICAgICAgICAgICAgICAgICAgICBpZiAoaW5uZXJNYXRjaCAmJiBpbm5lck1hdGNoWzFdKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBub2RlUmVnRXgubGFzdEluZGV4ID0gaW5uZXJSZWdFeC5sYXN0SW5kZXg7CgkgICAgICAgICAgICAgICAgICAgICAgICBsZXQgaW5uZXJOb2RlcyA9IHRoaXMucGFyc2UoaW5uZXJNYXRjaFsxXSwgbm9kZSwgZnVsbFRhZyk7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAoaW5uZXJOb2Rlcy5sZW5ndGggPiAwKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS4kaW5uZXJOb2RlcyA9IGlubmVyTm9kZXM7CgkgICAgICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIG5vZGUuJGlubmVyVGV4dCA9IGlubmVyTWF0Y2hbMV07CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgaWYgKHRoaXMucXVlcnlQYXJlbnQgJiYgcGFyZW50KSB7CgkgICAgICAgICAgICAgICAgICAgIHRoaXMucGFyZW50TWFwLnNldChub2RlLCBwYXJlbnQpOwoJICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgaWYgKHRoaXMucHJvZ3Jlc3NpdmUpIHsKCSAgICAgICAgICAgICAgICAgICAgdGhpcy5lbWl0KGA8LyR7ZnVsbFRhZ30+YCwgbm9kZSwgcGFyZW50KTsKCSAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIG5vZGVzLnB1c2gobm9kZSk7CgkgICAgICAgICAgICB9CgoJICAgICAgICAgICAgcmV0dXJuIG5vZGVzOwoJICAgICAgICB9CgoJICAgICAgICBnZXRQYXJlbnQobm9kZSkgewoJICAgICAgICAgICAgaWYgKHRoaXMucXVlcnlQYXJlbnQpIHsKCSAgICAgICAgICAgICAgICByZXR1cm4gdGhpcy5wYXJlbnRNYXAuZ2V0KG5vZGUpOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmV0dXJuIG51bGw7CgkgICAgICAgIH0KCgkgICAgICAgICNhZGRMaXN0ZW5lcihldnQsIGZ1bmMpIHsKCSAgICAgICAgICAgIGxldCBmdW5jcyA9IHRoaXMuZXZ0TGlzdGVuZXJzW2V2dF07CgkgICAgICAgICAgICBpZiAoZnVuY3MpIHsKCSAgICAgICAgICAgICAgICBmdW5jcy5wdXNoKGZ1bmMpOwoJICAgICAgICAgICAgfSBlbHNlIHsKCSAgICAgICAgICAgICAgICB0aGlzLmV2dExpc3RlbmVyc1tldnRdID0gW2Z1bmNdOwoJICAgICAgICAgICAgfQoJICAgICAgICB9CgoJICAgICAgICAvLyBzdXBwb3J0IGphdmFzY3JpcHQgY29uZGl0aW9uIGZvciB0aGUgbGFzdCB0YWcKCSAgICAgICAgYWRkTGlzdGVuZXIoZXZ0LCBmdW5jKSB7CgkgICAgICAgICAgICBpZiAoY29uZGl0aW9uZWQoZXZ0KSkgewoJICAgICAgICAgICAgICAgIC8vIGZ1bmMucHJvdG90eXBlID0gZXZ0OwoJICAgICAgICAgICAgICAgIGV2dCA9IHBhcnNlRXZlbnQoZXZ0KTsKCSAgICAgICAgICAgICAgICBmdW5jLmNvbmRpdGlvbiA9IGdlbkNvbmRpdGlvbkZ1bmMoZXZ0LmV4cCk7CgkgICAgICAgICAgICAgICAgZXZ0ID0gZXZ0LmV2dDsKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIHRoaXMuI2FkZExpc3RlbmVyKGV2dCwgZnVuYyk7CgkgICAgICAgIH0KCgkgICAgICAgICNyZW1vdmVMaXN0ZW5lcihldnQsIGZ1bmMpIHsKCSAgICAgICAgICAgIGxldCBmdW5jcyA9IHRoaXMuZXZ0TGlzdGVuZXJzW2V2dF07CgkgICAgICAgICAgICBsZXQgaWR4ID0gbnVsbDsKCSAgICAgICAgICAgIGlmIChmdW5jcyAmJiAoaWR4ID0gZnVuY3MuaW5kZXhPZihmdW5jKSkgPj0gMCkgewoJICAgICAgICAgICAgICAgIGZ1bmNzLnNwbGljZShpZHgsIDEpOwoJICAgICAgICAgICAgfQoJICAgICAgICB9CgoJICAgICAgICByZW1vdmVMaXN0ZW5lcihldnQsIGZ1bmMpIHsKCSAgICAgICAgICAgIGlmIChjb25kaXRpb25lZChldnQpKSB7CgkgICAgICAgICAgICAgICAgZXZ0ID0gcGFyc2VFdmVudChldnQpOwoJICAgICAgICAgICAgICAgIGV2dCA9IGV2dC5ldnQ7CgkgICAgICAgICAgICB9CgkgICAgICAgICAgICB0aGlzLiNyZW1vdmVMaXN0ZW5lcihldnQsIGZ1bmMpOwoJICAgICAgICB9CgoJICAgICAgICBlbWl0KGV2dCwgLi4uYXJncykgewoJICAgICAgICAgICAgbGV0IGZ1bmNzID0gdGhpcy5ldnRMaXN0ZW5lcnNbZXZ0XTsKCSAgICAgICAgICAgIGlmIChmdW5jcykgewoJICAgICAgICAgICAgICAgIGZvciAobGV0IGZ1bmMgb2YgZnVuY3MpIHsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGZ1bmMuY29uZGl0aW9uKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAoZnVuYy5jb25kaXRpb24uYXBwbHkobnVsbCwgYXJncykgPT09IHRydWUpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBmdW5jLmFwcGx5KG51bGwsIGFyZ3MpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgZnVuYy5hcHBseShudWxsLCBhcmdzKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgfQoKCSAgICAgICAgb24oZXZ0LCBmdW5jKSB7CgkgICAgICAgICAgICB0aGlzLmFkZExpc3RlbmVyKGV2dCwgZnVuYyk7CgkgICAgICAgIH0KCgkgICAgICAgIG9mZihldnQsIGZ1bmMpIHsKCSAgICAgICAgICAgIHRoaXMucmVtb3ZlTGlzdGVuZXIoZXZ0LCBmdW5jKTsKCSAgICAgICAgfQoJICAgIH07Cgl9KSgpOwoKCWNvbnN0IHsgTm9kZSwgV2F5LCBSZWxhdGlvbiB9ID0gb3Ntb2JqcywKCSAgICB7IHB1cmdlUHJvcHMsIFJlZkVsZW1lbnRzIH0gPSB1dGlscywKCSAgICBYbWxQYXJzZXIgPSB4bWxwYXJzZXI7CgoJdmFyIGxpYiA9IChvc20sIG9wdHMpID0+IHsKCSAgICBsZXQgY29tcGxldGVGZWF0dXJlID0gZmFsc2UsIHJlbmRlclRhZ2dlZCA9IGZhbHNlLCBleGNsdWRlV2F5ID0gdHJ1ZTsKCgkgICAgY29uc3QgcGFyc2VPcHR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9zbSA9PiB7CgkgICAgICAgIGZvciAobGV0IGVsZW0gb2Ygb3NtLmVsZW1lbnRzKSB7CgkgICAgICAgICAgICBzd2l0Y2ggKGVsZW0udHlwZSkgewoJICAgICAgICAgICAgICAgIGNhc2UgJ25vZGUnOgoJICAgICAgICAgICAgICAgICAgICBsZXQgbm9kZSA9IG5ldyBOb2RlKGVsZW0uaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGVsZW0udGFncykgewoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS5hZGRUYWdzKGVsZW0udGFncyk7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgbm9kZS5hZGRQcm9wcyhwdXJnZVByb3BzKGVsZW0sIFsnaWQnLCAndHlwZScsICd0YWdzJywgJ2xhdCcsICdsb24nXSkpOwoJICAgICAgICAgICAgICAgICAgICBub2RlLnNldExhdExuZyhlbGVtKTsKCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgoJICAgICAgICAgICAgICAgIGNhc2UgJ3dheSc6CgkgICAgICAgICAgICAgICAgICAgIGxldCB3YXkgPSBuZXcgV2F5KGVsZW0uaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGVsZW0udGFncykgewoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5LmFkZFRhZ3MoZWxlbS50YWdzKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB3YXkuYWRkUHJvcHMocHVyZ2VQcm9wcyhlbGVtLCBbJ2lkJywgJ3R5cGUnLCAndGFncycsICdub2RlcycsICdnZW9tZXRyeSddKSk7CgkgICAgICAgICAgICAgICAgICAgIGlmIChlbGVtLm5vZGVzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBmb3IgKGxldCBuIG9mIGVsZW0ubm9kZXMpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB3YXkuYWRkTm9kZVJlZihuKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgfSBlbHNlIGlmIChlbGVtLmdlb21ldHJ5KSB7CgkgICAgICAgICAgICAgICAgICAgICAgICB3YXkuc2V0TGF0TG5nQXJyYXkoZWxlbS5nZW9tZXRyeSk7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgoJICAgICAgICAgICAgICAgIGNhc2UgJ3JlbGF0aW9uJzoKCSAgICAgICAgICAgICAgICAgICAgbGV0IHJlbGF0aW9uID0gbmV3IFJlbGF0aW9uKGVsZW0uaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGVsZW0uYm91bmRzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICByZWxhdGlvbi5zZXRCb3VuZHMoW3BhcnNlRmxvYXQoZWxlbS5ib3VuZHMubWlubG9uKSwgcGFyc2VGbG9hdChlbGVtLmJvdW5kcy5taW5sYXQpLCBwYXJzZUZsb2F0KGVsZW0uYm91bmRzLm1heGxvbiksIHBhcnNlRmxvYXQoZWxlbS5ib3VuZHMubWF4bGF0KV0pOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGlmIChlbGVtLnRhZ3MpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHJlbGF0aW9uLmFkZFRhZ3MoZWxlbS50YWdzKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICByZWxhdGlvbi5hZGRQcm9wcyhwdXJnZVByb3BzKGVsZW0sIFsnaWQnLCAndHlwZScsICd0YWdzJywgJ2JvdW5kcycsICdtZW1iZXJzJ10pKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGVsZW0ubWVtYmVycykgewoJICAgICAgICAgICAgICAgICAgICAgICAgZm9yIChsZXQgbWVtYmVyIG9mIGVsZW0ubWVtYmVycykgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJlbGF0aW9uLmFkZE1lbWJlcihtZW1iZXIpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGJyZWFrOwoJICAgICAgICAgICAgfQoJICAgICAgICB9CgkgICAgfTsKCgkgICAgY29uc3QgYW5hbHl6ZUZlYXR1cmVzRnJvbVhtbCA9IG9zbSA9PiB7CgkgICAgICAgIGNvbnN0IHhtbFBhcnNlciA9IG5ldyBYbWxQYXJzZXIoeyBwcm9ncmVzc2l2ZTogdHJ1ZSB9KTsKCgkgICAgICAgIHhtbFBhcnNlci5vbignPC9vc20ubm9kZT4nLCBub2RlID0+IHsKCSAgICAgICAgICAgIGxldCBuZCA9IG5ldyBOb2RlKG5vZGUuaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgIGZvciAobGV0IFtrLCB2XSBvZiBPYmplY3QuZW50cmllcyhub2RlKSkKCSAgICAgICAgICAgICAgICBpZiAoIWsuc3RhcnRzV2l0aCgnJCcpICYmIFsnaWQnLCAnbG9uJywgJ2xhdCddLmluZGV4T2YoaykgPCAwKSB7CgkgICAgICAgICAgICAgICAgICAgIG5kLmFkZFByb3Aoaywgdik7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgbmQuc2V0TGF0TG5nKG5vZGUpOwoJICAgICAgICAgICAgaWYgKG5vZGUuJGlubmVyTm9kZXMpIHsKCSAgICAgICAgICAgICAgICBmb3IgKGxldCBpbmQgb2Ygbm9kZS4kaW5uZXJOb2RlcykgewoJICAgICAgICAgICAgICAgICAgICBpZiAoaW5kLiR0YWcgPT09ICd0YWcnKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBuZC5hZGRUYWcoaW5kLmssIGluZC52KTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgfSk7CgoJICAgICAgICB4bWxQYXJzZXIub24oJzwvb3NtLndheT4nLCBub2RlID0+IHsKCSAgICAgICAgICAgIGxldCB3YXkgPSBuZXcgV2F5KG5vZGUuaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgIGZvciAobGV0IFtrLCB2XSBvZiBPYmplY3QuZW50cmllcyhub2RlKSkgewoJICAgICAgICAgICAgICAgIGlmICghay5zdGFydHNXaXRoKCckJykgJiYgWydpZCddLmluZGV4T2YoaykgPCAwKSB7CgkgICAgICAgICAgICAgICAgICAgIHdheS5hZGRQcm9wKGssIHYpOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIGlmIChub2RlLiRpbm5lck5vZGVzKSB7CgkgICAgICAgICAgICAgICAgZm9yIChsZXQgaW5kIG9mIG5vZGUuJGlubmVyTm9kZXMpIHsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGluZC4kdGFnID09PSAnbmQnKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAoaW5kLmxvbiAmJiBpbmQubGF0KSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgd2F5LmFkZExhdExuZyhpbmQpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfSBlbHNlIGlmIChpbmQucmVmKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgd2F5LmFkZE5vZGVSZWYoaW5kLnJlZik7CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIH0gZWxzZSBpZiAoaW5kLiR0YWcgPT09ICd0YWcnKQoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5LmFkZFRhZyhpbmQuaywgaW5kLnYpOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgfSk7CgoJICAgICAgICB4bWxQYXJzZXIub24oJzxvc20ucmVsYXRpb24+Jywgbm9kZSA9PiB7CgkgICAgICAgICAgICBuZXcgUmVsYXRpb24obm9kZS5pZCwgcmVmRWxlbWVudHMpOwoJICAgICAgICB9KTsKCgkgICAgICAgIHhtbFBhcnNlci5vbignPC9vc20ucmVsYXRpb24ubWVtYmVyPicsIChub2RlLCBwYXJlbnQpID0+IHsKCSAgICAgICAgICAgIGxldCByZWxhdGlvbiA9IHJlZkVsZW1lbnRzLmdldChgcmVsYXRpb24vJHtwYXJlbnQuaWR9YCk7CgkgICAgICAgICAgICBsZXQgbWVtYmVyID0gewoJICAgICAgICAgICAgICAgIHR5cGU6IG5vZGUudHlwZSwKCSAgICAgICAgICAgICAgICByb2xlOiBub2RlLnJvbGUgPyBub2RlLnJvbGUgOiAnJywKCSAgICAgICAgICAgICAgICByZWY6IG5vZGUucmVmCgkgICAgICAgICAgICB9OwoJICAgICAgICAgICAgaWYgKG5vZGUubGF0ICYmIG5vZGUubG9uKSB7CgkgICAgICAgICAgICAgICAgbWVtYmVyLmxhdCA9IG5vZGUubGF0LCBtZW1iZXIubG9uID0gbm9kZS5sb24sIG1lbWJlci50YWdzID0ge307CgkgICAgICAgICAgICAgICAgZm9yIChsZXQgW2ssIHZdIG9mIE9iamVjdC5lbnRyaWVzKG5vZGUpKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmICghay5zdGFydHNXaXRoKCckJykgJiYgWyd0eXBlJywgJ2xhdCcsICdsb24nXS5pbmRleE9mKGspIDwgMCkgewoJICAgICAgICAgICAgICAgICAgICAgICAgbWVtYmVyW2tdID0gdjsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIGlmIChub2RlLiRpbm5lck5vZGVzKSB7CgkgICAgICAgICAgICAgICAgbGV0IGdlb21ldHJ5ID0gW107CgkgICAgICAgICAgICAgICAgbGV0IG5vZGVzID0gW107CgkgICAgICAgICAgICAgICAgZm9yIChsZXQgaW5kIG9mIG5vZGUuJGlubmVyTm9kZXMpIHsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGluZC5sYXQgJiYgaW5kLmxvbikgewoJICAgICAgICAgICAgICAgICAgICAgICAgZ2VvbWV0cnkucHVzaChpbmQpOwoJICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZXMucHVzaChpbmQucmVmKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICBpZiAoZ2VvbWV0cnkubGVuZ3RoID4gMCkgewoJICAgICAgICAgICAgICAgICAgICBtZW1iZXIuZ2VvbWV0cnkgPSBnZW9tZXRyeTsKCSAgICAgICAgICAgICAgICB9IGVsc2UgaWYgKG5vZGVzLmxlbmd0aCA+IDApIHsKCSAgICAgICAgICAgICAgICAgICAgbWVtYmVyLm5vZGVzID0gbm9kZXM7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmVsYXRpb24uYWRkTWVtYmVyKG1lbWJlcik7CgkgICAgICAgIH0pOwoKCSAgICAgICAgeG1sUGFyc2VyLm9uKCc8L29zbS5yZWxhdGlvbi5ib3VuZHM+JywgKG5vZGUsIHBhcmVudCkgPT4gewoJICAgICAgICAgICAgcmVmRWxlbWVudHMuZ2V0KGByZWxhdGlvbi8ke3BhcmVudC5pZH1gKS5zZXRCb3VuZHMoW3BhcnNlRmxvYXQobm9kZS5taW5sb24pLCBwYXJzZUZsb2F0KG5vZGUubWlubGF0KSwgcGFyc2VGbG9hdChub2RlLm1heGxvbiksIHBhcnNlRmxvYXQobm9kZS5tYXhsYXQpXSk7CgkgICAgICAgIH0pOwoKCSAgICAgICAgeG1sUGFyc2VyLm9uKCc8L29zbS5yZWxhdGlvbi50YWc+JywgKG5vZGUsIHBhcmVudCkgPT4gewoJICAgICAgICAgICAgcmVmRWxlbWVudHMuZ2V0KGByZWxhdGlvbi8ke3BhcmVudC5pZH1gKS5hZGRUYWcobm9kZS5rLCBub2RlLnYpOwoJICAgICAgICB9KTsKCgkgICAgICAgIHhtbFBhcnNlci5wYXJzZShvc20pOwoJICAgIH07CgoJICAgIGlmIChmb3JtYXQgPT09ICdqc29uLXJhdycpIHsKCSAgICAgICAgb3NtID0gSlNPTi5wYXJzZShvc20pOwoJICAgICAgICBpZiAob3NtLmVsZW1lbnRzKSB7CgkgICAgICAgICAgICBmb3JtYXQgPSAnanNvbic7CgkgICAgICAgIH0gZWxzZSB7CgkgICAgICAgICAgICBmb3JtYXQgPSAnaW52YWxpZCc7CgkgICAgICAgIH0KCSAgICB9CgoJICAgIGlmIChmb3JtYXQgPT09ICdqc29uJykgewoJICAgICAgICBhbmFseXplRmVhdHVyZXNGcm9tSnNvbihvc20pOwoJICAgIH0gZWxzZSBpZiAoZm9ybWF0ID09PSAneG1sJykgewoJICAgICAgICBhbmFseXplRmVhdHVyZXNGcm9tWG1sKG9zbSk7CgkgICAgfQoKCSAgICByZWZFbGVtZW50cy5iaW5kQWxsKCk7CgoJICAgIGZvciAobGV0IHYgb2YgcmVmRWxlbWVudHMudmFsdWVzKCkpIHsKCSAgICAgICAgaWYgKHYucmVmQ291bnQgPD0gMCB8fCAodi5oYXNUYWcgJiYgcmVuZGVyVGFnZ2VkICYmICEodiBpbnN0YW5jZW9mIFdheSAmJiBleGNsdWRlV2F5KSkpIHsKCSAgICAgICAgICAgIGxldCBmZWF0dXJlcyA9IHYudG9GZWF0dXJlQXJyYXkoKTsKCSAgICAgICAgICAgIC8vIHJldHVybiB0aGUgZmlyc3QgZ2VvbWV0cnkgb2YgdGhlIGZpcnN0IHJlbGF0aW9uIGVsZW1lbnQKCSAgICAgICAgICAgIGlmICh2IGluc3RhbmNlb2YgUmVsYXRpb24gJiYgIWNvbXBsZXRlRmVhdHVyZSAmJiBmZWF0dXJlcy5sZW5ndGggPiAwKSB7CgkgICAgICAgICAgICAgICAgcmV0dXJuIGZlYXR1cmVzWzBdLmdlb21ldHJ5OwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgZmVhdHVyZUFycmF5ID0gZmV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3RoID09PSAxKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAvLyBNYWtlIGl0IGEgcG9pbnQKCSAgICAgICAgICAgICAgICAgICAgICAgIGdlb21ldHJ5ID0gewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICd0eXBlJzogJ1BvaW50JywKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAnY29vcmRpbmF0ZXMnOiBsaW5lU3RyaW5nLmNvb3JkaW5hdGVzWzBdCgkgICAgICAgICAgICAgICAgICAgICAgICB9OwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgY29uc29sZS53YXJuKCdDYW5ub3QgY29udmVydCBwb2x5bGluZSB0byAnICsgb3B0aW9ucy50eXBlKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICBlbHNlIGlmIChvcHRpb25zLnR5cGUgPT09ICdwb2x5Z29uJykgewoJICAgICAgICAgICAgICAgICAgICBpZiAobGluZVN0cmluZy5jb29yZGluYXRlc1swXVswXSA9PT0gbGluZVN0cmluZy5jb29yZGluYXRlc1tsaW5lU3RyaW5nLmNvb3JkaW5hdGVzLmxlbmd0aCAtIDFdWzBdICYmCgkgICAgICAgICAgICAgICAgICAgICAgICBsaW5lU3RyaW5nLmNvb3JkaW5hdGVzWzBdWzFdID09PSBsaW5lU3RyaW5nLmNvb3JkaW5hdGVzW2xpbmVTdHJpbmcuY29vcmRpbmF0ZXMubGVuZ3RoIC0gMV1bMV0pIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIC8vIE1ha2UgaXQgYSBwb2x5Z29uCgkgICAgICAgICAgICAgICAgICAgICAgICBnZW9tZXRyeSA9IHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAndHlwZSc6ICdQb2x5Z29uJywKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAnY29vcmRpbmF0ZXMnOiBbbGluZVN0cmluZy5jb29yZGluYXRlc10KCSAgICAgICAgICAgICAgICAgICAgICAgIH07CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgZWxzZSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBjb25zb2xlLndhcm4oJ0Nhbm5vdCBjb252ZXJ0IHBvbHlsaW5lIHRvICcgKyBvcHRpb25zLnR5cGUpOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIHJlc29sdmUoewoJICAgICAgICAgICAgICAgICAgICB0eXBlOiAiRmVhdHVyZUNvbGxlY3Rpb24iLAoJICAgICAgICAgICAgICAgICAgICBmZWF0dXJlczogW3sKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAidHlwZSI6ICJGZWF0dXJlIiwKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAiZ2VvbWV0cnkiOiBnZW9tZXRyeSwKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAicHJvcGVydGllcyI6IG9wdGlvbnMucHJvcGVydGllcyB8fCB7fQoJICAgICAgICAgICAgICAgICAgICAgICAgfV0KCSAgICAgICAgICAgICAgICB9KTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIGNhdGNoIChlcnIpIHsKCSAgICAgICAgICAgICAgICByZWplY3QoZXJyKTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgfSk7CgkgICAgICAgIHJldHVybiBnZW9qc29uOwoJICAgIH0KCX0KCgljb25zdCBsaWJyYXJpZXMgPSB7CgkgICAgJ0NvbnZlcnRlcic6IENvbnZlcnRlcgoJfTsKCWxldCBzdWJDbGFzczsKCXNlbGYuYWRkRXZlbnRMaXN0ZW5lcignbWVzc2FnZScsIGUgPT4gewoJICAgIGNvbnN0IGRhdGEgPSAoZS5kYXRhIHx8IGUpOwoJICAgIGNvbnN0IHBvc3QgPSAoaWQsIGVyciwgcmVzLCB0eXBlKSA9PiB7CgkgICAgICAgIHBvc3RNZXNzYWdlKHsKCSAgICAgICAgICAgIHR5cGU6IHR5cGUgPyB0eXBlIDogKGVyciA/ICdlcnJvcicgOiAncmVzcG9uc2UnKSwKCSAgICAgICAgICAgIGlkOiBpZCwKCSAgICAgICAgICAgIG1lc3NhZ2U6IHJlcywKCSAgICAgICAgICAgIGVycm9yOiBlcnIKCSAgICAgICAgfSk7CgkgICAgfTsKCSAgICBjb25zdCBjb21tYW5kcyA9IHsKCSAgICAgICAgJ2luaXQnOiAobXNnKSA9PiB7CgkgICAgICAgICAgICBjb25zdCB7IGlkLCBjb21tYW5kLCBtZXNzYWdlIH0gPSBtc2c7CgkgICAgICAgICAgICBzdWJDbGFzcyA9IG5ldyBsaWJyYXJpZXNbY29tbWFuZF0obWVzc2FnZVswXSwgbWVzc2FnZVsxXSk7CgkgICAgICAgICAgICAvLyByZXR1cm4gdGhlIGNsYXNzJyBtZXRob2RzCgkgICAgICAgICAgICBjb25zdCBmbnMgPSBbCgkgICAgICAgICAgICAgICAgLi4uT2JqZWN0LmdldE93blByb3BlcnR5TmFtZXMobGlicmFyaWVzW2NvbW1hbmRdLnByb3RvdHlwZSksCgkgICAgICAgICAgICAgICAgLi4uT2JqZWN0LmtleXMoc3ViQ2xhc3MpCgkgICAgICAgICAgICBdLm1hcChrZXkgPT4gW2tleSwgdHlwZW9mIGxpYnJhcmllc1tjb21tYW5kXS5wcm90b3R5cGVba2V5XV0pCgkgICAgICAgICAgICAgICAgLnJlZHVjZSgoYSwgYykgPT4gKHsgLi4uYSwgLi4ueyBbY1swXV06IGNbMV0gfSB9KSwge30pOwoJICAgICAgICAgICAgcG9zdChpZCwgdW5kZWZpbmVkLCBmbnMsICdpbml0X3Jlc3BvbnNlJyk7CgkgICAgICAgIH0sCgkgICAgICAgICdnZXQnOiBmdW5jdGlvbiAobXNnKSB7CgkgICAgICAgICAgICBjb25zdCB7IGlkLCBjb21tYW5kIH0gPSBtc2c7CgkgICAgICAgICAgICBpZiAoc3ViQ2xhc3MgJiYgc3ViQ2xhc3NbY29tbWFuZF0pIHsKCSAgICAgICAgICAgICAgICBwb3N0KGlkLCB1bmRlZmluZWQsIHN1YkNsYXNzW2NvbW1hbmRdKTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIGVsc2UgewoJICAgICAgICAgICAgICAgIHBvc3QoaWQsIHVuZGVmaW5lZCwgdW5kZWZpbmVkKTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgfSwKCSAgICAgICAgJ2V4ZWMnOiBmdW5jdGlvbiAobXNnKSB7CgkgICAgICAgICAgICBjb25zdCB7IGlkLCBjb21tYW5kLCBtZXNzYWdlIH0gPSBtc2c7CgkgICAgICAgICAgICBpZiAoc3ViQ2xhc3MgJiYgc3ViQ2xhc3NbY29tbWFuZF0gJiYgdHlwZW9mIHN1YkNsYXNzW2NvbW1hbmRdID09PSAnZnVuY3Rpb24nKSB7CgkgICAgICAgICAgICAgICAgY29uc3QgY21kID0gc3ViQ2xhc3NbY29tbWFuZF0KCSAgICAgICAgICAgICAgICAgICAgLmFwcGx5KHN1YkNsYXNzLCBtZXNzYWdlKTsKCSAgICAgICAgICAgICAgICBpZiAoISFjbWQgJiYgdHlwZW9mIGNtZC50aGVuID09PSAnZnVuY3Rpb24nKSB7CgkgICAgICAgICAgICAgICAgICAgIC8vIEl0J3MgYSBwcm9taXNlLCBzbyB3YWl0IGZvciBpdAoJICAgICAgICAgICAgICAgICAgICBjbWQKCSAgICAgICAgICAgICAgICAgICAgICAgIC50aGVuKHJlcyA9PiBwb3N0KGlkLCB1bmRlZmluZWQsIHJlcykpCgkgICAgICAgICAgICAgICAgICAgICAgICAuY2F0Y2goZSA9PiBwb3N0KGlkLCBlKSk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAvLyBOb3QgYSBwcm9taXNlLCBqdXN0IHJldHVybiBpdAoJICAgICAgICAgICAgICAgICAgICBwb3N0KGlkLCB1bmRlZmluZWQsIGNtZCk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgZWxzZSB7CgkgICAgICAgICAgICAgICAgLy8gRXJyb3IKCSAgICAgICAgICAgICAgICBwb3N0KGlkLCBuZXcgRXJyb3IoYGNvbW1hbmQgIiR7Y29tbWFuZH0iIG5vdCBmb3VuZGApKTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgfQoJICAgIH07CgkgICAgaWYgKGNvbW1hbmRzW2RhdGEudHlwZV0pIHsKCSAgICAgICAgY29tbWFuZHNbZGF0YS50eXBlXShkYXRhKTsKCSAgICB9Cgl9KTsKCn0pKCk7Ci8vIyBzb3VyY2VNYXBwaW5nVVJMPXdvcmtlci5qcy5tYXAKCg=='); -/* eslint-enable */ - -const randomString = () => Math.random().toString(36).substring(2); -class Actor { - /** - * Creates a new instance of the `Actor` class. - * @param subClass - The name of the subclass. - * @param args - The arguments to pass to the subclass constructor. - */ - constructor(subClass, args) { - // Generate a random initialization ID - this.initId = randomString() + '-' + subClass; - // Create a new Web Worker and a new Map for handlers - this.worker = new WorkerFactory(); - this.handlers = new Map(); - // Listen for messages from the worker - this.worker.onmessage = (event) => { - const data = event.data; - const handler = this.handlers.get(data.id); - const that = this; - if (handler) { - // Handle responses from the worker - if (data.type === 'response') { - handler.resolve(data.message); - } - // Handle errors from the worker - if (data.type === 'error') { - const error = data.error || new Error(`Unknown error with ${subClass}`); - handler.reject(error); - } - // Handle initialization responses from the worker - if (data.type === 'init_response') { - this._ = Object.keys(data.message) - .map(key => { - const isFn = typeof data.message[key] === 'function'; - const subFunction = function () { - return isFn ? (that.exec(key))(...arguments) : that.get(key); - }; - return [key, subFunction]; - }) - .reduce((a, c) => ({ ...a, ...{ [c[0]]: c[1] } }), {}); - handler.resolve(this._); - } - } - }; - // Tell the worker to initialize the subclass - this.worker.postMessage({ - type: 'init', - id: this.initId, - command: subClass, - message: args - }); - } - /** - * Waits for the initialization of the object to complete and returns the resulting object. - * @returns A promise that resolves with the initialized object. - */ - onLoad() { - return new Promise((resolve) => { - // If initialization is still in progress, add a new handler for the initialization result - if (this._ === undefined) { - this.handlers.set(this.initId, { resolve, 'reject': resolve }); - } - else { - // Otherwise, immediately resolve the promise with the initialized object - resolve(this._); - } - }); - } - /** - * returns a Promise for a given command that will be executed in a worker. - * @param command - The command to execute. - * @returns A Promise that resolves with the result of the command execution or rejects with an error. - */ - exec(command) { - // Keep track of this class - const that = this; - // Return a function that returns a Promise - return function (...args) { - return new Promise((resolve, reject) => { - const id = randomString() + '-' + command; - // Set up the resolve and reject handlers for the Promise - that.handlers.set(id, { resolve, reject }); - // Tell the worker to run the command with the provided arguments - that.worker.postMessage({ - type: 'exec', - id: id, - command: command, - message: [...args] - }); - }); - }; - } - /** - * Returns a Promise that resolves with the result of a command sent to a Web Worker. - * @param command - The command to send to the Web Worker. - * @returns A Promise that resolves with the result of the command. - */ - get(command) { - return new Promise((resolve, reject) => { - // Generate a unique ID for this request - const id = randomString() + '-' + command; - // Store the resolve and reject functions for later use - this.handlers.set(id, { resolve, reject }); - // Send the command to the worker - this.worker.postMessage({ - type: 'get', - id, - command, - message: [], - }); - }); - } -} - -// Make sure we can support workers in the current browser / runtime -const supportsWorkers = () => { - let supported = false; - try { - supported = typeof (window.Worker) === 'function'; - } - catch (e) { - supported = false; - } - return supported; -}; -// Safari changes https:// to http// for some reason, so this is broken in Safari and iPhone -// So to fix this we add it back -const needsUrlCheck = (new URL('test://http://example.com')).href !== 'test://http://example.com'; -const checkUrl = (url) => { - const safariFixRegex = new RegExp('^(https?)(\/\/)'); - const cleanUrl = url.replace(safariFixRegex, '$1:$2'); - return cleanUrl; -}; -/** - * The processData function accepts a URL, prefix, and an optional controller - * and tries to read and convert the data - * @param url - The URL of the resource. - * @param prefix - The prefix used to process the data - * @param controller - optional controller that can be used to cancel a request - * @returns A geojson FeatureCollection (or undefined) - */ -async function processData(url, prefix, controller) { - const response = await fetch(url, controller ? { signal: controller.signal } : undefined); - let options = {}; - // Parse the URL - const urlObject = new URL(url, window.location.href); - if (urlObject.hash.length) { - // Extract the hash (including the "#" symbol) - const hash = urlObject.hash; - // Remove the "#" symbol from the hash and decode it - const decodedHash = decodeURIComponent(hash.slice(1)); // Remove the "#" symbol - try { - options = JSON.parse(decodedHash); - } - catch (e) { - console.warn('Error parsing or reading URL:', e); - } - } - if (response.status == 200) { - const rawData = await response.text(); - let convertPromise; - const usesDOM = (['kml', 'tcx', 'gpx'].includes(prefix)); - if (usesDOM || !supportsWorkers()) { - // XML uses the DOM, which isn't available to web workers - // It is possible to use xmldom to do this, but that increases the bundle size by 3x - const converter = new Converter(prefix, rawData, options); - convertPromise = converter.convert(); - } - else { - const converter = new Actor('Converter', [prefix, rawData, options]); - convertPromise = converter.exec('convert')(); - } - return await convertPromise; - } - else { - throw (new Error(`Data fetch error: ${response.statusText}`)); - } -} -/** - * Processes the URL and returns the prefix and cleaned URL. - * - * @param url - The URL to process. - * @returns An object with the prefix and cleaned URL. - */ -const processUrl = (url) => { - const prefix = url.split('://')[0]; - const replacedUrl = url.replace(new RegExp(`^${prefix}://`), ''); - // Apply the Safari fix (if needed) to the URL - const cleanUrl = needsUrlCheck ? checkUrl(replacedUrl) : replacedUrl; - return { prefix, url: cleanUrl }; -}; -/** - * Handles the Vector Text Protocol for version 4. - * - * @param requestParameters - The parameters for the request including the URL. - * @param controller - An AbortController instance to manage the request lifecycle. - * @returns A promise resolving to a GetResourceResponse containing a FeatureCollection or undefined. - * @throws Will throw an error if the URL is invalid or if any other error occurs during data processing. - */ -const VectorTextProtocolV4 = async (requestParameters, controller) => { - const { prefix, url } = processUrl(requestParameters.url); - if (url) { - try { - // Process the data and return the response - const data = await processData(url, prefix, controller); - return { data }; - } - catch (e) { - // Catch and rethrow errors with additional context - throw new Error(e || 'Unknown Error'); - } - } - else { - // Handle invalid URL case - throw new Error('Invalid URL: ' + requestParameters.url); - } -}; -/** - * Handles the Vector Text Protocol for version 3. - * - * @param requestParameters - The parameters for the request including the URL. - * @param callback - A callback function to handle the response or error. - * @returns An object with a cancel function to abort the request. - */ -const VectorTextProtocolV3 = (requestParameters, callback) => { - const controller = new AbortController(); - const { prefix, url } = processUrl(requestParameters.url); - if (url) { - processData(url, prefix, controller) - .then(data => callback(null, data)) - .catch(e => callback(e)); - } - // Return an object with a cancel method to abort the request - return { cancel: () => { controller.abort(); } }; -}; -/** - * Selects the appropriate Vector Text Protocol version based on the type of controller provided. - * - * @param requestParameters - The parameters for the request including the URL. - * @param controller - Either an AbortController or a callback function. - * @returns Either a Promise for V4 or an object with a cancel method for V3. - */ -const VectorTextProtocol = (requestParameters, controller) => { - if (controller instanceof AbortController) { - return VectorTextProtocolV4(requestParameters, controller); - } - else { - return VectorTextProtocolV3(requestParameters, controller); - } -}; -/** - * Add the vector text protocol to a map library for each supported format. - * @param mapLibrary - The MapLibrary object to add the protocols to. - */ -const addProtocols = (mapLibrary) => { - supportedFormats.forEach(type => { - mapLibrary.addProtocol(type, VectorTextProtocol); - }); -}; - -loadCSS('https://unpkg.com/maplibre-gl@4.5.2/dist/maplibre-gl.css'); - -/** class: Maplibre */ -const Renderer = class extends defaultExport { - /** fields */ - id = 'maplibre' - pitch = 0 - bearing = 0 - style = 'https://demotiles.maplibre.org/style.json' - link = false - globe = false - /* eslint-disable-next-line no-undef */ - maplibregl = maplibregl - - /** options */ - static validOptions = this.validOptions.concat([ - new MapOption({ - name: 'pitch', - desc: 'Pitch toward the horizon measured in degrees', - example: '60', - exampleDesc: 'Look a little upward', - isValid: value => value <= 90 && value >= 0, - }), - new MapOption({ - name: 'bearing', - desc: "The compass direction that is 'up'", - example: '-30', - exampleDesc: 'Rotate map a little', - isValid: value => value <= 180 && value >= -180, - }), - new MapOption({ - name: 'link', - desc: "Syn map's position with the hash fragment of the page's URL", - example: 'true', - exampleDesc: 'Add hash for page URL', - isValid: value => value === 'true', - }), - new MapOption({ - name: 'style', - desc: 'URL of style document, read https://maplibre.org/maplibre-style-spec/', - example: 'https://tile.openstreetmap.jp/styles/openmaptiles/style.json', - exampleDesc: 'Style form OSM japan!!!', - isValid: value => URL.parse(value), - }), - new MapOption({ - name: 'globe', - desc: 'Display a globe', - example: 'true', - exampleDesc: 'Add globe for lower zoom level', - isValid: value => value === 'true', - }), - ]) - - get steps () { - return [...super.steps, this.setProjection] - } - - /** options: center, zoom, pitch, bearing, link, globe */ - async addMap ({ - maplibregl, - target, - style, - data, - center, - zoom, - pitch, - bearing, - link, - globe, - }) { - const tileData = data.filter(d => d.type === 'tile'); - const maplibreStyle = - tileData.length !== 0 ? { version: 8, sources: {}, layers: [] } : style; - - this.map = new maplibregl.Map({ - container: target, - style: maplibreStyle, - center, - zoom, - pitch, - bearing, - hash: link, - }); - - return new Promise((resolve, _reject) => { - this.map.on('load', () => { - this.map.setProjection({ - type: globe ? 'globe' : 'mercator', // Set projection to globe - }); - resolve(this.map); - }); - }) - } - - /** options: draw */ - getTerraDrawAdapter ({ maplibregl, map, draw }) { - if (!draw) return { state: 'skip' } - - this.terraDrawAdapter = new l({ map, maplibregl }); - return this.terraDrawAdapter - } - - /** options: control */ - setControl ({ maplibregl, map, control }) { - if (!control || Object.values(control).filter(v => v).length === 0) { return { state: 'skip' } } - - if (control.fullscreen === true) { - map.addControl(new maplibregl.FullscreenControl()); - } - if (control.scale === true) { - const scale = new maplibregl.ScaleControl({ - unit: 'metric', - }); - map.addControl(scale); - } - } - - /** options: debug, eval */ - setExtra (config) { - const { map, debug } = config; - if (!debug && !config.eval) return { state: 'skip' } - - if (debug === true) { - map.showTileBoundaries = true; - } - if (config.eval) { - this.evalScript(config.eval, [['map', map]]); - } - } - - /** options: data */ - addTileData ({ map, data }) { - const tileData = data.filter(d => d.type === 'tile'); - if (tileData.length === 0) return { state: 'skip' } - - const style = map.getStyle(); - tileData.forEach((datum, index) => { - const source = datum.name ? datum.name : index.toString(); - style.sources[source] = { - type: 'raster', - tiles: [datum.url], - tileSize: 256, - }; - style.layers.push({ id: source, type: 'raster', source }); - }); - map.setStyle(style); - } - - /** options: data.gpx */ - async addGPXFile ({ maplibregl, map, data }) { - const gpxUrl = data.find(record => record.type === 'gpx'); - if (!gpxUrl) return { state: 'skip' } - - addProtocols(maplibregl); - - const gpxSourceName = 'gpx'; - const gpxLink = 'gpx://' + gpxUrl; - - const source = { - type: 'geojson', - data: gpxLink, - }; - map.addSource(gpxSourceName, source); - map.addLayer({ - id: 'id_' + gpxSourceName, - type: 'line', - source: gpxSourceName, - paint: { - 'line-color': 'red', - 'line-width': 3, - }, - }); - - if (!Object.prototype.hasOwnProperty.call(this, 'center')) { - const data = await map.getSource(gpxSourceName).getData(); - const coordinates = data.features[0].geometry.coordinates; - const bounds = coordinates.reduce( - (bounds, coord) => bounds.extend(coord), - new maplibregl.LngLatBounds(coordinates[0], coordinates[0]), - ); - map.fitBounds(bounds, { - padding: 20, - }); - } - } - - /** actions: marker */ - addMarker (config) { - const options = config.element - ? { - element: config.element, - anchor: config.type === 'pin' ? 'bottom' : 'center', - } - : {}; - const marker = new this.maplibregl.Marker(options) - .setLngLat(config.xy) - .addTo(this.map); - const element = marker.getElement(); - element.classList.add('marker'); - element.remove = () => marker.remove(); - - return element - } - - /** actions: camera */ - async updateCamera ({ bounds, center, zoom, animation, ...others }, useAnimation) { - if (bounds) { - this.map.fitBounds(bounds, { linear: true, ...others }); - } else if (animation || useAnimation) { - this.map.flyTo({ - center: center ?? this.map.getCenter(), - zoom: zoom ?? this.map.getZoom(), - ...others, - }); - } else { - this.map.setCenter(center); - this.map.setZoom(zoom); - } - - return new Promise(resolve => { - this.map.on('zoomend', () => { - resolve('zoomend'); - }); - }) - } - - /** utils: projection */ - project ([lng, lat]) { - return this.map.project([lng, lat]) - } - - unproject ([x, y]) { - const { lng, lat } = this.map.unproject([x, y]); - return [lng, lat] - } -}; - -export { Renderer as default }; + */var Vl=function requireMaplibreGl(){return Rl||(Rl=1,Tl.exports=function(){var M={},et={};function define(Bt,Wt,Nt){if(et[Bt]=Nt,"index"===Bt){var $t="var sharedModule = {}; ("+et.shared+")(sharedModule); ("+et.worker+")(sharedModule);",Gr={};return et.shared(Gr),et.index(M,Gr),"undefined"!=typeof window&&M.setWorkerUrl(window.URL.createObjectURL(new Blob([$t],{type:"text/javascript"}))),M}}define("shared",["exports"],(function(M){function e(M,et,Bt,Wt){return new(Bt||(Bt=Promise))((function(Nt,$t){function a(M){try{l(Wt.next(M))}catch(M){$t(M)}}function o(M){try{l(Wt.throw(M))}catch(M){$t(M)}}function l(M){var et;M.done?Nt(M.value):(et=M.value,et instanceof Bt?et:new Bt((function(M){M(et)}))).then(a,o)}l((Wt=Wt.apply(M,et||[])).next())}))}function r(M){return M&&M.__esModule&&Object.prototype.hasOwnProperty.call(M,"default")?M.default:M}var et,Bt;function s(){if(Bt)return et;function t(M,et){this.x=M,this.y=et}return Bt=1,et=t,t.prototype={clone:function(){return new t(this.x,this.y)},add:function(M){return this.clone()._add(M)},sub:function(M){return this.clone()._sub(M)},multByPoint:function(M){return this.clone()._multByPoint(M)},divByPoint:function(M){return this.clone()._divByPoint(M)},mult:function(M){return this.clone()._mult(M)},div:function(M){return this.clone()._div(M)},rotate:function(M){return this.clone()._rotate(M)},rotateAround:function(M,et){return this.clone()._rotateAround(M,et)},matMult:function(M){return this.clone()._matMult(M)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(M){return this.x===M.x&&this.y===M.y},dist:function(M){return Math.sqrt(this.distSqr(M))},distSqr:function(M){var et=M.x-this.x,Bt=M.y-this.y;return et*et+Bt*Bt},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(M){return Math.atan2(this.y-M.y,this.x-M.x)},angleWith:function(M){return this.angleWithSep(M.x,M.y)},angleWithSep:function(M,et){return Math.atan2(this.x*et-this.y*M,this.x*M+this.y*et)},_matMult:function(M){var et=M[2]*this.x+M[3]*this.y;return this.x=M[0]*this.x+M[1]*this.y,this.y=et,this},_add:function(M){return this.x+=M.x,this.y+=M.y,this},_sub:function(M){return this.x-=M.x,this.y-=M.y,this},_mult:function(M){return this.x*=M,this.y*=M,this},_div:function(M){return this.x/=M,this.y/=M,this},_multByPoint:function(M){return this.x*=M.x,this.y*=M.y,this},_divByPoint:function(M){return this.x/=M.x,this.y/=M.y,this},_unit:function(){return this._div(this.mag()),this},_perp:function(){var M=this.y;return this.y=this.x,this.x=-M,this},_rotate:function(M){var et=Math.cos(M),Bt=Math.sin(M),Wt=Bt*this.x+et*this.y;return this.x=et*this.x-Bt*this.y,this.y=Wt,this},_rotateAround:function(M,et){var Bt=Math.cos(M),Wt=Math.sin(M),Nt=et.y+Wt*(this.x-et.x)+Bt*(this.y-et.y);return this.x=et.x+Bt*(this.x-et.x)-Wt*(this.y-et.y),this.y=Nt,this},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}},t.convert=function(M){return M instanceof t?M:Array.isArray(M)?new t(M[0],M[1]):M},et}"function"==typeof SuppressedError&&SuppressedError;var Wt,Nt,$t=r(s()),Gr=function(){if(Nt)return Wt;function t(M,et,Bt,Wt){this.cx=3*M,this.bx=3*(Bt-M)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*et,this.by=3*(Wt-et)-this.cy,this.ay=1-this.cy-this.by,this.p1x=M,this.p1y=et,this.p2x=Bt,this.p2y=Wt}return Nt=1,Wt=t,t.prototype={sampleCurveX:function(M){return((this.ax*M+this.bx)*M+this.cx)*M},sampleCurveY:function(M){return((this.ay*M+this.by)*M+this.cy)*M},sampleCurveDerivativeX:function(M){return(3*this.ax*M+2*this.bx)*M+this.cx},solveCurveX:function(M,et){if(void 0===et&&(et=1e-6),M<0)return 0;if(M>1)return 1;for(var Bt=M,Wt=0;Wt<8;Wt++){var Nt=this.sampleCurveX(Bt)-M;if(Math.abs(Nt)Nt?Gr=Bt:mn=Bt,Bt=.5*(mn-Gr)+Gr;return Bt},solve:function(M,et){return this.sampleCurveY(this.solveCurveX(M,et))}},Wt}(),mn=r(Gr);let Hn,so;function f(){return null==Hn&&(Hn="undefined"!=typeof OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof createImageBitmap),Hn}function d(){if(null==so&&(so=!1,f())){const M=5,et=new OffscreenCanvas(M,M).getContext("2d",{willReadFrequently:!0});if(et){for(let Bt=0;Bt=1)return 1;const et=M*M,Bt=et*M;return 4*(M<.5?Bt:3*(M-et)+Bt-.75)}function B(M,et,Bt,Wt){const Nt=new mn(M,et,Bt,Wt);return M=>Nt.solve(M)}const Eo=B(.25,.1,.25,1);function E(M,et,Bt){return Math.min(Bt,Math.max(et,M))}function T(M,et,Bt){const Wt=Bt-et,Nt=((M-et)%Wt+Wt)%Wt+et;return Nt===et?Bt:Nt}function F(M,...et){for(const Bt of et)for(const et in Bt)M[et]=Bt[et];return M}let Ia=1;function L(M,et,Bt){const Wt={};for(const Bt in M)Wt[Bt]=et.call(this,M[Bt],Bt,M);return Wt}function D(M,et,Bt){const Wt={};for(const Bt in M)et.call(this,M[Bt],Bt,M)&&(Wt[Bt]=M[Bt]);return Wt}function O(M){return Array.isArray(M)?M.map(O):"object"==typeof M&&M?L(M,O):M}const Ba={};function j(M){Ba[M]||("undefined"!=typeof console&&console.warn(M),Ba[M]=!0)}function N(M,et,Bt){return(Bt.y-M.y)*(et.x-M.x)>(et.y-M.y)*(Bt.x-M.x)}function U(M){return"undefined"!=typeof WorkerGlobalScope&&void 0!==M&&M instanceof WorkerGlobalScope}let Ta=null;function G(M){return"undefined"!=typeof ImageBitmap&&M instanceof ImageBitmap}const Va="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=";function X(M,et,Bt,Wt,Nt){return e(this,void 0,void 0,(function*(){if("undefined"==typeof VideoFrame)throw new Error("VideoFrame not supported");const $t=new VideoFrame(M,{timestamp:0});try{const Gr=null==$t?void 0:$t.format;if(!Gr||!Gr.startsWith("BGR")&&!Gr.startsWith("RGB"))throw new Error(`Unrecognized format ${Gr}`);const mn=Gr.startsWith("BGR"),Hn=new Uint8ClampedArray(Wt*Nt*4);if(yield $t.copyTo(Hn,function(M,et,Bt,Wt,Nt){const $t=4*Math.max(-et,0),Gr=(Math.max(0,Bt)-Bt)*Wt*4+$t,mn=4*Wt,Hn=Math.max(0,et),so=Math.max(0,Bt);return{rect:{x:Hn,y:so,width:Math.min(M.width,et+Wt)-Hn,height:Math.min(M.height,Bt+Nt)-so},layout:[{offset:Gr,stride:mn}]}}(M,et,Bt,Wt,Nt)),mn)for(let M=0;MU(self)?self.worker&&self.worker.referrer:("blob:"===window.location.protocol?window.parent:window).location.href,it=function(M,et){if(/:\/\//.test(M.url)&&!/^https?:|^file:/.test(M.url)){const Bt=tt(M.url);if(Bt)return Bt(M,et);if(U(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:M,targetMapId:Da},et)}if(!(/^file:/.test(Bt=M.url)||/^file:/.test(nt())&&!/^\w+:/.test(Bt))){if(fetch&&Request&&AbortController&&Object.prototype.hasOwnProperty.call(Request.prototype,"signal"))return function(M,et){return e(this,void 0,void 0,(function*(){const Bt=new Request(M.url,{method:M.method||"GET",body:M.body,credentials:M.credentials,headers:M.headers,cache:M.cache,referrer:nt(),signal:et.signal});let Wt,Nt;"json"!==M.type||Bt.headers.has("Accept")||Bt.headers.set("Accept","application/json");try{Wt=yield fetch(Bt)}catch(Bt){throw new rt(0,Bt.message,M.url,new Blob)}if(!Wt.ok){const et=yield Wt.blob();throw new rt(Wt.status,Wt.statusText,M.url,et)}Nt="arrayBuffer"===M.type||"image"===M.type?Wt.arrayBuffer():"json"===M.type?Wt.json():Wt.text();const $t=yield Nt;if(et.signal.aborted)throw W();return{data:$t,cacheControl:Wt.headers.get("Cache-Control"),expires:Wt.headers.get("Expires")}}))}(M,et);if(U(self)&&self.worker&&self.worker.actor)return self.worker.actor.sendAsync({type:"GR",data:M,mustQueue:!0,targetMapId:Da},et)}var Bt;return function(M,et){return new Promise(((Bt,Wt)=>{var Nt;const $t=new XMLHttpRequest;$t.open(M.method||"GET",M.url,!0),"arrayBuffer"!==M.type&&"image"!==M.type||($t.responseType="arraybuffer");for(const et in M.headers)$t.setRequestHeader(et,M.headers[et]);"json"===M.type&&($t.responseType="text",(null===(Nt=M.headers)||void 0===Nt?void 0:Nt.Accept)||$t.setRequestHeader("Accept","application/json")),$t.withCredentials="include"===M.credentials,$t.onerror=()=>{Wt(new Error($t.statusText))},$t.onload=()=>{if(!et.signal.aborted)if(($t.status>=200&&$t.status<300||0===$t.status)&&null!==$t.response){let et=$t.response;if("json"===M.type)try{et=JSON.parse($t.response)}catch(M){return void Wt(M)}Bt({data:et,cacheControl:$t.getResponseHeader("Cache-Control"),expires:$t.getResponseHeader("Expires")})}else{const et=new Blob([$t.response],{type:$t.getResponseHeader("Content-Type")});Wt(new rt($t.status,$t.statusText,M.url,et))}},et.signal.addEventListener("abort",(()=>{$t.abort(),Wt(W())})),$t.send(M.body)}))}(M,et)};function st(M){if(!M||M.indexOf("://")<=0||0===M.indexOf("data:image/")||0===M.indexOf("blob:"))return!0;const et=new URL(M),Bt=window.location;return et.protocol===Bt.protocol&&et.host===Bt.host}function at(M,et,Bt){Bt[M]&&-1!==Bt[M].indexOf(et)||(Bt[M]=Bt[M]||[],Bt[M].push(et))}function ot(M,et,Bt){if(Bt&&Bt[M]){const Wt=Bt[M].indexOf(et);-1!==Wt&&Bt[M].splice(Wt,1)}}class lt{constructor(M,et={}){F(this,et),this.type=M}}class ut extends lt{constructor(M,et={}){super("error",F({error:M},et))}}class ct{on(M,et){return this._listeners=this._listeners||{},at(M,et,this._listeners),{unsubscribe:()=>{this.off(M,et)}}}off(M,et){return ot(M,et,this._listeners),ot(M,et,this._oneTimeListeners),this}once(M,et){return et?(this._oneTimeListeners=this._oneTimeListeners||{},at(M,et,this._oneTimeListeners),this):new Promise((et=>this.once(M,et)))}fire(M,et){"string"==typeof M&&(M=new lt(M,et||{}));const Bt=M.type;if(this.listens(Bt)){M.target=this;const et=this._listeners&&this._listeners[Bt]?this._listeners[Bt].slice():[];for(const Bt of et)Bt.call(this,M);const Wt=this._oneTimeListeners&&this._oneTimeListeners[Bt]?this._oneTimeListeners[Bt].slice():[];for(const et of Wt)ot(Bt,et,this._oneTimeListeners),et.call(this,M);const Nt=this._eventedParent;Nt&&(F(M,"function"==typeof this._eventedParentData?this._eventedParentData():this._eventedParentData),Nt.fire(M))}else M instanceof ut&&console.error(M.error);return this}listens(M){return this._listeners&&this._listeners[M]&&this._listeners[M].length>0||this._oneTimeListeners&&this._oneTimeListeners[M]&&this._oneTimeListeners[M].length>0||this._eventedParent&&this._eventedParent.listens(M)}setEventedParent(M,et){return this._eventedParent=M,this._eventedParentData=et,this}}var Ka={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},centerAltitude:{type:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},roll:{type:"number",default:0,units:"degrees"},light:{type:"light"},sky:{type:"sky"},projection:{type:"projection"},terrain:{type:"terrain"},sources:{required:!0,type:"sources"},sprite:{type:"sprite"},glyphs:{type:"string"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{},custom:{}},default:"mapbox"},redFactor:{type:"number",default:1},blueFactor:{type:"number",default:1},greenFactor:{type:"number",default:1},baseShift:{type:"number",default:0},volatile:{type:"boolean",default:!1},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{required:!0,type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},filter:{type:"*"},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterMinPoints:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image",{"!":"icon-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"padding",default:[2],units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},"viewport-glyph":{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-variable-anchor-offset":{type:"variableAnchorOffsetCollection",requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field",{"!":"text-overlap"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-overlap":{type:"enum",values:{never:{},always:{},cooperative:{}},requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},sky:{"sky-color":{type:"color","property-type":"data-constant",default:"#88C6FC",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-color":{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"fog-ground-blend":{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"horizon-fog-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"sky-horizon-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0},"atmosphere-blend":{type:"number","property-type":"data-constant",default:.8,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},terrain:{source:{type:"string",required:!0},exaggeration:{type:"number",minimum:0,default:1}},projection:{type:{type:"projectionDefinition",default:"mercator","property-type":"data-constant",transition:!1,expression:{interpolated:!0,parameters:["zoom"]}}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}};const Oa=["type","source","source-layer","minzoom","maxzoom","filter","layout"];function ft(M,et){const Bt={};for(const et in M)"ref"!==et&&(Bt[et]=M[et]);return Oa.forEach((M=>{M in et&&(Bt[M]=et[M])})),Bt}function dt(M,et){if(Array.isArray(M)){if(!Array.isArray(et)||M.length!==et.length)return!1;for(let Bt=0;Bt`:"value"===M.itemType.kind?"array":`array<${et}>`}return M.kind}const Nl=[$a,Al,Sl,Zl,Gl,Rl,El,Tl,Rt(Vl),Jl,Ll,Dl];function Ut(M,et){if("error"===et.kind)return null;if("array"===M.kind){if("array"===et.kind&&(0===et.N&&"value"===et.itemType.kind||!Ut(M.itemType,et.itemType))&&("number"!=typeof M.N||M.N===et.N))return null}else{if(M.kind===et.kind)return null;if("value"===M.kind)for(const M of Nl)if(!Ut(M,et))return null}return`Expected ${jt(M)} but found ${jt(et)} instead.`}function qt(M,et){return et.some((et=>et.kind===M.kind))}function Gt(M,et){return et.some((et=>"null"===et?null===M:"array"===et?Array.isArray(M):"object"===et?M&&!Array.isArray(M)&&"object"==typeof M:et===typeof M))}function Zt(M,et){return"array"===M.kind&&"array"===et.kind?M.itemType.kind===et.itemType.kind&&"number"==typeof M.N:M.kind===et.kind}const Yl=.96422,Ol=.82521,jl=4/29,Ul=6/29,ql=3*Ul*Ul,$l=Ul*Ul*Ul,tc=Math.PI/180,ec=180/Math.PI;function ee(M){return(M%=360)<0&&(M+=360),M}function re([M,et,Bt,Wt]){let Nt,$t;const Gr=ie((.2225045*(M=ne(M))+.7168786*(et=ne(et))+.0606169*(Bt=ne(Bt)))/1);M===et&&et===Bt?Nt=$t=Gr:(Nt=ie((.4360747*M+.3850649*et+.1430804*Bt)/Yl),$t=ie((.0139322*M+.0971045*et+.7141733*Bt)/Ol));const mn=116*Gr-16;return[mn<0?0:mn,500*(Nt-Gr),200*(Gr-$t),Wt]}function ne(M){return M<=.04045?M/12.92:Math.pow((M+.055)/1.055,2.4)}function ie(M){return M>$l?Math.pow(M,1/3):M/ql+jl}function se([M,et,Bt,Wt]){let Nt=(M+16)/116,$t=isNaN(et)?Nt:Nt+et/500,Gr=isNaN(Bt)?Nt:Nt-Bt/200;return Nt=1*oe(Nt),$t=Yl*oe($t),Gr=Ol*oe(Gr),[ae(3.1338561*$t-1.6168667*Nt-.4906146*Gr),ae(-.9787684*$t+1.9161415*Nt+.033454*Gr),ae(.0719453*$t-.2289914*Nt+1.4052427*Gr),Wt]}function ae(M){return(M=M<=.00304?12.92*M:1.055*Math.pow(M,1/2.4)-.055)<0?0:M>1?1:M}function oe(M){return M>Ul?M*M*M:ql*(M-jl)}function le(M){return parseInt(M.padEnd(2,M),16)/255}function ue(M,et){return ce(et?M/100:M,0,1)}function ce(M,et,Bt){return Math.min(Math.max(et,M),Bt)}function he(M){return!M.some(Number.isNaN)}const dc={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};function fe(M,et,Bt){return M+Bt*(et-M)}function de(M,et,Bt){return M.map(((M,Wt)=>fe(M,et[Wt],Bt)))}class ye{constructor(M,et,Bt,Wt=1,Nt=!0){this.r=M,this.g=et,this.b=Bt,this.a=Wt,Nt||(this.r*=Wt,this.g*=Wt,this.b*=Wt,Wt||this.overwriteGetter("rgb",[M,et,Bt,Wt]))}static parse(M){if(M instanceof ye)return M;if("string"!=typeof M)return;const et=function(M){if("transparent"===(M=M.toLowerCase().trim()))return[0,0,0,0];const et=dc[M];if(et){const[M,Bt,Wt]=et;return[M/255,Bt/255,Wt/255,1]}if(M.startsWith("#")&&/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(M)){const et=M.length<6?1:2;let Bt=1;return[le(M.slice(Bt,Bt+=et)),le(M.slice(Bt,Bt+=et)),le(M.slice(Bt,Bt+=et)),le(M.slice(Bt,Bt+et)||"ff")]}if(M.startsWith("rgb")){const et=M.match(/^rgba?\(\s*([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s+|\s*(,)\s*)([\de.+-]+)(%)?(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(et){const[M,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po]=et,To=[Nt||" ",mn||" ",uo].join("");if(" "===To||" /"===To||",,"===To||",,,"===To){const M=[Wt,Gr,so].join(""),et="%%%"===M?100:""===M?255:0;if(et){const M=[ce(+Bt/et,0,1),ce(+$t/et,0,1),ce(+Hn/et,0,1),Io?ue(+Io,Po):1];if(he(M))return M}}return}}const Bt=M.match(/^hsla?\(\s*([\de.+-]+)(?:deg)?(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s+|\s*(,)\s*)([\de.+-]+)%(?:\s*([,\/])\s*([\de.+-]+)(%)?)?\s*\)$/);if(Bt){const[M,et,Wt,Nt,$t,Gr,mn,Hn,so]=Bt,uo=[Wt||" ",$t||" ",mn].join("");if(" "===uo||" /"===uo||",,"===uo||",,,"===uo){const M=[+et,ce(+Nt,0,100),ce(+Gr,0,100),Hn?ue(+Hn,so):1];if(he(M))return function([M,et,Bt,Wt]){function i(Wt){const Nt=(Wt+M/30)%12,$t=et*Math.min(Bt,1-Bt);return Bt-$t*Math.max(-1,Math.min(Nt-3,9-Nt,1))}return M=ee(M),et/=100,Bt/=100,[i(0),i(8),i(4),Wt]}(M)}}}(M);return et?new ye(...et,!1):void 0}get rgb(){const{r:M,g:et,b:Bt,a:Wt}=this,Nt=Wt||1/0;return this.overwriteGetter("rgb",[M/Nt,et/Nt,Bt/Nt,Wt])}get hcl(){return this.overwriteGetter("hcl",function(M){const[et,Bt,Wt,Nt]=re(M),$t=Math.sqrt(Bt*Bt+Wt*Wt);return[Math.round(1e4*$t)?ee(Math.atan2(Wt,Bt)*ec):NaN,$t,et,Nt]}(this.rgb))}get lab(){return this.overwriteGetter("lab",re(this.rgb))}overwriteGetter(M,et){return Object.defineProperty(this,M,{value:et}),et}toString(){const[M,et,Bt,Wt]=this.rgb;return`rgba(${[M,et,Bt].map((M=>Math.round(255*M))).join(",")},${Wt})`}static interpolate(M,et,Bt,Wt="rgb"){switch(Wt){case"rgb":{const[Wt,Nt,$t,Gr]=de(M.rgb,et.rgb,Bt);return new ye(Wt,Nt,$t,Gr,!1)}case"hcl":{const[Wt,Nt,$t,Gr]=M.hcl,[mn,Hn,so,uo]=et.hcl;let Io,Po;if(isNaN(Wt)||isNaN(mn))isNaN(Wt)?isNaN(mn)?Io=NaN:(Io=mn,1!==$t&&0!==$t||(Po=Hn)):(Io=Wt,1!==so&&0!==so||(Po=Nt));else{let M=mn-Wt;mn>Wt&&M>180?M-=360:mn180&&(M+=360),Io=Wt+Bt*M}const[To,Eo,Ia,Ba]=function([M,et,Bt,Wt]){return M=isNaN(M)?0:M*tc,se([Bt,Math.cos(M)*et,Math.sin(M)*et,Wt])}([Io,null!=Po?Po:fe(Nt,Hn,Bt),fe($t,so,Bt),fe(Gr,uo,Bt)]);return new ye(To,Eo,Ia,Ba,!1)}case"lab":{const[Wt,Nt,$t,Gr]=se(de(M.lab,et.lab,Bt));return new ye(Wt,Nt,$t,Gr,!1)}}}}ye.black=new ye(0,0,0,1),ye.white=new ye(1,1,1,1),ye.transparent=new ye(0,0,0,0),ye.red=new ye(1,0,0,1);class me{constructor(M,et,Bt){this.sensitivity=M?et?"variant":"case":et?"accent":"base",this.locale=Bt,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(M,et){return this.collator.compare(M,et)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class ge{constructor(M,et,Bt,Wt,Nt){this.text=M,this.image=et,this.scale=Bt,this.fontStack=Wt,this.textColor=Nt}}class xe{constructor(M){this.sections=M}static fromString(M){return new xe([new ge(M,null,null,null,null)])}isEmpty(){return 0===this.sections.length||!this.sections.some((M=>0!==M.text.length||M.image&&0!==M.image.name.length))}static factory(M){return M instanceof xe?M:xe.fromString(M)}toString(){return 0===this.sections.length?"":this.sections.map((M=>M.text)).join("")}}class ve{constructor(M){this.values=M.slice()}static parse(M){if(M instanceof ve)return M;if("number"==typeof M)return new ve([M,M,M,M]);if(Array.isArray(M)&&!(M.length<1||M.length>4)){for(const et of M)if("number"!=typeof et)return;switch(M.length){case 1:M=[M[0],M[0],M[0],M[0]];break;case 2:M=[M[0],M[1],M[0],M[1]];break;case 3:M=[M[0],M[1],M[2],M[1]]}return new ve(M)}}toString(){return JSON.stringify(this.values)}static interpolate(M,et,Bt){return new ve(de(M.values,et.values,Bt))}}class be{constructor(M){this.name="ExpressionEvaluationError",this.message=M}toJSON(){return this.message}}const Ic=new Set(["center","left","right","top","bottom","top-left","top-right","bottom-left","bottom-right"]);class _e{constructor(M){this.values=M.slice()}static parse(M){if(M instanceof _e)return M;if(Array.isArray(M)&&!(M.length<1)&&M.length%2==0){for(let et=0;et=0&&M<=255&&"number"==typeof et&&et>=0&&et<=255&&"number"==typeof Bt&&Bt>=0&&Bt<=255?void 0===Wt||"number"==typeof Wt&&Wt>=0&&Wt<=1?null:`Invalid rgba value [${[M,et,Bt,Wt].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${("number"==typeof Wt?[M,et,Bt,Wt]:[M,et,Bt]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Me(M){if(null===M||"string"==typeof M||"boolean"==typeof M||"number"==typeof M||M instanceof Ae||M instanceof ye||M instanceof me||M instanceof xe||M instanceof ve||M instanceof _e||M instanceof Se)return!0;if(Array.isArray(M)){for(const et of M)if(!Me(et))return!1;return!0}if("object"==typeof M){for(const et in M)if(!Me(M[et]))return!1;return!0}return!1}function Ie(M){if(null===M)return $a;if("string"==typeof M)return Sl;if("boolean"==typeof M)return Zl;if("number"==typeof M)return Al;if(M instanceof ye)return Gl;if(M instanceof Ae)return Rl;if(M instanceof me)return Wl;if(M instanceof xe)return El;if(M instanceof ve)return Jl;if(M instanceof _e)return Dl;if(M instanceof Se)return Ll;if(Array.isArray(M)){const et=M.length;let Bt;for(const et of M){const M=Ie(et);if(Bt){if(Bt===M)continue;Bt=Vl;break}Bt=M}return Rt(Bt||Vl,et)}return Tl}function ze(M){const et=typeof M;return null===M?"":"string"===et||"number"===et||"boolean"===et?String(M):M instanceof ye||M instanceof Ae||M instanceof xe||M instanceof ve||M instanceof _e||M instanceof Se?M.toString():JSON.stringify(M)}class Pe{constructor(M,et){this.type=M,this.value=et}static parse(M,et){if(2!==M.length)return et.error(`'literal' expression requires exactly one argument, but found ${M.length-1} instead.`);if(!Me(M[1]))return et.error("invalid value");const Bt=M[1];let Wt=Ie(Bt);const Nt=et.expectedType;return"array"!==Wt.kind||0!==Wt.N||!Nt||"array"!==Nt.kind||"number"==typeof Nt.N&&0!==Nt.N||(Wt=Nt),new Pe(Wt,Bt)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}}const fc={string:Sl,number:Al,boolean:Zl,object:Tl};class Be{constructor(M,et){this.type=M,this.args=et}static parse(M,et){if(M.length<2)return et.error("Expected at least one argument.");let Bt,Wt=1;const Nt=M[0];if("array"===Nt){let Nt,$t;if(M.length>2){const Bt=M[1];if("string"!=typeof Bt||!(Bt in fc)||"object"===Bt)return et.error('The item type argument of "array" must be one of string, number, boolean',1);Nt=fc[Bt],Wt++}else Nt=Vl;if(M.length>3){if(null!==M[2]&&("number"!=typeof M[2]||M[2]<0||M[2]!==Math.floor(M[2])))return et.error('The length argument to "array" must be a positive integer literal',2);$t=M[2],Wt++}Bt=Rt(Nt,$t)}else{if(!fc[Nt])throw new Error(`Types doesn't contain name = ${Nt}`);Bt=fc[Nt]}const $t=[];for(;WtM.outputDefined()))}}const yc={"to-boolean":Zl,"to-color":Gl,"to-number":Al,"to-string":Sl};class Ee{constructor(M,et){this.type=M,this.args=et}static parse(M,et){if(M.length<2)return et.error("Expected at least one argument.");const Bt=M[0];if(!yc[Bt])throw new Error(`Can't parse ${Bt} as it is not part of the known types`);if(("to-boolean"===Bt||"to-string"===Bt)&&2!==M.length)return et.error("Expected one argument.");const Wt=yc[Bt],Nt=[];for(let Bt=1;Bt4?`Invalid rgba value ${JSON.stringify(et)}: expected an array containing either three or four numeric values.`:ke(et[0],et[1],et[2],et[3]),!Bt))return new ye(et[0]/255,et[1]/255,et[2]/255,et[3])}throw new be(Bt||`Could not parse color from value '${"string"==typeof et?et:JSON.stringify(et)}'`)}case"padding":{let et;for(const Bt of this.args){et=Bt.evaluate(M);const Wt=ve.parse(et);if(Wt)return Wt}throw new be(`Could not parse padding from value '${"string"==typeof et?et:JSON.stringify(et)}'`)}case"variableAnchorOffsetCollection":{let et;for(const Bt of this.args){et=Bt.evaluate(M);const Wt=_e.parse(et);if(Wt)return Wt}throw new be(`Could not parse variableAnchorOffsetCollection from value '${"string"==typeof et?et:JSON.stringify(et)}'`)}case"number":{let et=null;for(const Bt of this.args){if(et=Bt.evaluate(M),null===et)return 0;const Wt=Number(et);if(!isNaN(Wt))return Wt}throw new be(`Could not convert ${JSON.stringify(et)} to number.`)}case"formatted":return xe.fromString(ze(this.args[0].evaluate(M)));case"resolvedImage":return Se.fromString(ze(this.args[0].evaluate(M)));case"projectionDefinition":return this.args[0].evaluate(M);default:return ze(this.args[0].evaluate(M))}}eachChild(M){this.args.forEach(M)}outputDefined(){return this.args.every((M=>M.outputDefined()))}}function Te(M,et,Bt=0,Wt=M.length-1,Nt=$e){for(;Wt>Bt;){if(Wt-Bt>600){const $t=Wt-Bt+1,Gr=et-Bt+1,mn=Math.log($t),Hn=.5*Math.exp(2*mn/3),so=.5*Math.sqrt(mn*Hn*($t-Hn)/$t)*(Gr-$t/2<0?-1:1);Te(M,et,Math.max(Bt,Math.floor(et-Gr*Hn/$t+so)),Math.min(Wt,Math.floor(et+($t-Gr)*Hn/$t+so)),Nt)}const $t=M[et];let Gr=Bt,mn=Wt;for(Fe(M,Bt,et),Nt(M[Wt],$t)>0&&Fe(M,Bt,Wt);Gr0;)mn--}0===Nt(M[Bt],$t)?Fe(M,Bt,mn):(mn++,Fe(M,mn,Wt)),mn<=et&&(Bt=mn+1),et<=mn&&(Wt=mn-1)}}function Fe(M,et,Bt){const Wt=M[et];M[et]=M[Bt],M[Bt]=Wt}function $e(M,et){return Met?1:0}function Le(M,et){if(M.length<=1)return[M];const Bt=[];let Wt,Nt;for(const et of M){const M=Oe(et);0!==M&&(et.area=Math.abs(M),void 0===Nt&&(Nt=M<0),Nt===M<0?(Wt&&Bt.push(Wt),Wt=[et]):Wt.push(et))}if(Wt&&Bt.push(Wt),et>1)for(let M=0;M`[${M}]`)).join(""),this.scope=Nt,this.errors=$t,this.expectedType=Wt,this._isConstant=et}parse(M,et,Bt,Wt,Nt={}){return et?this.concat(et,Bt,Wt)._parse(M,Nt):this._parse(M,Nt)}_parse(M,et){function r(M,et,Bt){return"assert"===Bt?new Be(et,[M]):"coerce"===Bt?new Ee(et,[M]):M}if(null!==M&&"string"!=typeof M&&"boolean"!=typeof M&&"number"!=typeof M||(M=["literal",M]),Array.isArray(M)){if(0===M.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const Bt=M[0];if("string"!=typeof Bt)return this.error(`Expression name must be a string, but found ${typeof Bt} instead. If you wanted a literal array, use ["literal", [...]].`,0),null;const Wt=this.registry[Bt];if(Wt){let Bt=Wt.parse(M,this);if(!Bt)return null;if(this.expectedType){const M=this.expectedType,Wt=Bt.type;if("string"!==M.kind&&"number"!==M.kind&&"boolean"!==M.kind&&"object"!==M.kind&&"array"!==M.kind||"value"!==Wt.kind)if("projectionDefinition"!==M.kind||"string"!==Wt.kind&&"array"!==Wt.kind)if("color"!==M.kind&&"formatted"!==M.kind&&"resolvedImage"!==M.kind||"value"!==Wt.kind&&"string"!==Wt.kind)if("padding"!==M.kind||"value"!==Wt.kind&&"number"!==Wt.kind&&"array"!==Wt.kind)if("variableAnchorOffsetCollection"!==M.kind||"value"!==Wt.kind&&"array"!==Wt.kind){if(this.checkSubtype(M,Wt))return null}else Bt=r(Bt,M,et.typeAnnotation||"coerce");else Bt=r(Bt,M,et.typeAnnotation||"coerce");else Bt=r(Bt,M,et.typeAnnotation||"coerce");else Bt=r(Bt,M,et.typeAnnotation||"coerce");else Bt=r(Bt,M,et.typeAnnotation||"assert")}if(!(Bt instanceof Pe)&&"resolvedImage"!==Bt.type.kind&&this._isConstant(Bt)){const et=new Ne;try{Bt=new Pe(Bt.type,Bt.evaluate(et))}catch(M){return this.error(M.message),null}}return Bt}return this.error(`Unknown expression "${Bt}". If you wanted a literal array, use ["literal", [...]].`,0)}return this.error(void 0===M?"'undefined' value invalid. Use null instead.":"object"==typeof M?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof M} instead.`)}concat(M,et,Bt){const Wt="number"==typeof M?this.path.concat(M):this.path,Nt=Bt?this.scope.concat(Bt):this.scope;return new Ue(this.registry,this._isConstant,Wt,et||null,Nt,this.errors)}error(M,...et){const Bt=`${this.key}${et.map((M=>`[${M}]`)).join("")}`;this.errors.push(new kt(Bt,M))}checkSubtype(M,et){const Bt=Ut(M,et);return Bt&&this.error(Bt),Bt}}class qe{constructor(M,et){this.type=et.type,this.bindings=[].concat(M),this.result=et}evaluate(M){return this.result.evaluate(M)}eachChild(M){for(const et of this.bindings)M(et[1]);M(this.result)}static parse(M,et){if(M.length<4)return et.error(`Expected at least 3 arguments, but found ${M.length-1} instead.`);const Bt=[];for(let Wt=1;Wt=Bt.length)throw new be(`Array index out of bounds: ${et} > ${Bt.length-1}.`);if(et!==Math.floor(et))throw new be(`Array index must be an integer, but found ${et} instead.`);return Bt[et]}eachChild(M){M(this.index),M(this.input)}outputDefined(){return!1}}class Xe{constructor(M,et){this.type=Zl,this.needle=M,this.haystack=et}static parse(M,et){if(3!==M.length)return et.error(`Expected 2 arguments, but found ${M.length-1} instead.`);const Bt=et.parse(M[1],1,Vl),Wt=et.parse(M[2],2,Vl);return Bt&&Wt?qt(Bt.type,[Zl,Sl,Al,$a,Vl])?new Xe(Bt,Wt):et.error(`Expected first argument to be of type boolean, string, number or null, but found ${jt(Bt.type)} instead`):null}evaluate(M){const et=this.needle.evaluate(M),Bt=this.haystack.evaluate(M);if(!Bt)return!1;if(!Gt(et,["boolean","string","number","null"]))throw new be(`Expected first argument to be of type boolean, string, number or null, but found ${jt(Ie(et))} instead.`);if(!Gt(Bt,["string","array"]))throw new be(`Expected second argument to be of type array or string, but found ${jt(Ie(Bt))} instead.`);return Bt.indexOf(et)>=0}eachChild(M){M(this.needle),M(this.haystack)}outputDefined(){return!0}}class Ke{constructor(M,et,Bt){this.type=Al,this.needle=M,this.haystack=et,this.fromIndex=Bt}static parse(M,et){if(M.length<=2||M.length>=5)return et.error(`Expected 3 or 4 arguments, but found ${M.length-1} instead.`);const Bt=et.parse(M[1],1,Vl),Wt=et.parse(M[2],2,Vl);if(!Bt||!Wt)return null;if(!qt(Bt.type,[Zl,Sl,Al,$a,Vl]))return et.error(`Expected first argument to be of type boolean, string, number or null, but found ${jt(Bt.type)} instead`);if(4===M.length){const Nt=et.parse(M[3],3,Al);return Nt?new Ke(Bt,Wt,Nt):null}return new Ke(Bt,Wt)}evaluate(M){const et=this.needle.evaluate(M),Bt=this.haystack.evaluate(M);if(!Gt(et,["boolean","string","number","null"]))throw new be(`Expected first argument to be of type boolean, string, number or null, but found ${jt(Ie(et))} instead.`);let Wt;if(this.fromIndex&&(Wt=this.fromIndex.evaluate(M)),Gt(Bt,["string"])){const M=Bt.indexOf(et,Wt);return-1===M?-1:[...Bt.slice(0,M)].length}if(Gt(Bt,["array"]))return Bt.indexOf(et,Wt);throw new be(`Expected second argument to be of type array or string, but found ${jt(Ie(Bt))} instead.`)}eachChild(M){M(this.needle),M(this.haystack),this.fromIndex&&M(this.fromIndex)}outputDefined(){return!1}}class He{constructor(M,et,Bt,Wt,Nt,$t){this.inputType=M,this.type=et,this.input=Bt,this.cases=Wt,this.outputs=Nt,this.otherwise=$t}static parse(M,et){if(M.length<5)return et.error(`Expected at least 4 arguments, but found only ${M.length-1}.`);if(M.length%2!=1)return et.error("Expected an even number of arguments.");let Bt,Wt;et.expectedType&&"value"!==et.expectedType.kind&&(Wt=et.expectedType);const Nt={},$t=[];for(let Gr=2;GrNumber.MAX_SAFE_INTEGER)return so.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if("number"==typeof M&&Math.floor(M)!==M)return so.error("Numeric branch labels must be integer values.");if(Bt){if(so.checkSubtype(Bt,Ie(M)))return null}else Bt=Ie(M);if(void 0!==Nt[String(M)])return so.error("Branch labels must be unique.");Nt[String(M)]=$t.length}const uo=et.parse(Hn,Gr,Wt);if(!uo)return null;Wt=Wt||uo.type,$t.push(uo)}const Gr=et.parse(M[1],1,Vl);if(!Gr)return null;const mn=et.parse(M[M.length-1],M.length-1,Wt);return mn?"value"!==Gr.type.kind&&et.concat(1).checkSubtype(Bt,Gr.type)?null:new He(Bt,Wt,Gr,Nt,$t,mn):null}evaluate(M){const et=this.input.evaluate(M);return(Ie(et)===this.inputType&&this.outputs[this.cases[et]]||this.otherwise).evaluate(M)}eachChild(M){M(this.input),this.outputs.forEach(M),M(this.otherwise)}outputDefined(){return this.outputs.every((M=>M.outputDefined()))&&this.otherwise.outputDefined()}}class Ye{constructor(M,et,Bt){this.type=M,this.branches=et,this.otherwise=Bt}static parse(M,et){if(M.length<4)return et.error(`Expected at least 3 arguments, but found only ${M.length-1}.`);if(M.length%2!=0)return et.error("Expected an odd number of arguments.");let Bt;et.expectedType&&"value"!==et.expectedType.kind&&(Bt=et.expectedType);const Wt=[];for(let Nt=1;Ntet.outputDefined()))&&this.otherwise.outputDefined()}}class Je{constructor(M,et,Bt,Wt){this.type=M,this.input=et,this.beginIndex=Bt,this.endIndex=Wt}static parse(M,et){if(M.length<=2||M.length>=5)return et.error(`Expected 3 or 4 arguments, but found ${M.length-1} instead.`);const Bt=et.parse(M[1],1,Vl),Wt=et.parse(M[2],2,Al);if(!Bt||!Wt)return null;if(!qt(Bt.type,[Rt(Vl),Sl,Vl]))return et.error(`Expected first argument to be of type array or string, but found ${jt(Bt.type)} instead`);if(4===M.length){const Nt=et.parse(M[3],3,Al);return Nt?new Je(Bt.type,Bt,Wt,Nt):null}return new Je(Bt.type,Bt,Wt)}evaluate(M){const et=this.input.evaluate(M),Bt=this.beginIndex.evaluate(M);let Wt;if(this.endIndex&&(Wt=this.endIndex.evaluate(M)),Gt(et,["string"]))return[...et].slice(Bt,Wt).join("");if(Gt(et,["array"]))return et.slice(Bt,Wt);throw new be(`Expected first argument to be of type array or string, but found ${jt(Ie(et))} instead.`)}eachChild(M){M(this.input),M(this.beginIndex),this.endIndex&&M(this.endIndex)}outputDefined(){return!1}}function We(M,et){const Bt=M.length-1;let Wt,Nt,$t=0,Gr=Bt,mn=0;for(;$t<=Gr;)if(mn=Math.floor(($t+Gr)/2),Wt=M[mn],Nt=M[mn+1],Wt<=et){if(mn===Bt||etet))throw new be("Input is not a number.");Gr=mn-1}return 0}class Qe{constructor(M,et,Bt){this.type=M,this.input=et,this.labels=[],this.outputs=[];for(const[M,et]of Bt)this.labels.push(M),this.outputs.push(et)}static parse(M,et){if(M.length-1<4)return et.error(`Expected at least 4 arguments, but found only ${M.length-1}.`);if((M.length-1)%2!=0)return et.error("Expected an even number of arguments.");const Bt=et.parse(M[1],1,Al);if(!Bt)return null;const Wt=[];let Nt=null;et.expectedType&&"value"!==et.expectedType.kind&&(Nt=et.expectedType);for(let Bt=1;Bt=$t)return et.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',mn);const so=et.parse(Gr,Hn,Nt);if(!so)return null;Nt=Nt||so.type,Wt.push([$t,so])}return new Qe(Nt,Bt,Wt)}evaluate(M){const et=this.labels,Bt=this.outputs;if(1===et.length)return Bt[0].evaluate(M);const Wt=this.input.evaluate(M);if(Wt<=et[0])return Bt[0].evaluate(M);const Nt=et.length;return Wt>=et[Nt-1]?Bt[Nt-1].evaluate(M):Bt[We(et,Wt)].evaluate(M)}eachChild(M){M(this.input);for(const et of this.outputs)M(et)}outputDefined(){return this.outputs.every((M=>M.outputDefined()))}}function tr(M){return M&&M.__esModule&&Object.prototype.hasOwnProperty.call(M,"default")?M.default:M}var Bc,Tc,Mc=function(){if(Tc)return Bc;function t(M,et,Bt,Wt){this.cx=3*M,this.bx=3*(Bt-M)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*et,this.by=3*(Wt-et)-this.cy,this.ay=1-this.cy-this.by,this.p1x=M,this.p1y=et,this.p2x=Bt,this.p2y=Wt}return Tc=1,Bc=t,t.prototype={sampleCurveX:function(M){return((this.ax*M+this.bx)*M+this.cx)*M},sampleCurveY:function(M){return((this.ay*M+this.by)*M+this.cy)*M},sampleCurveDerivativeX:function(M){return(3*this.ax*M+2*this.bx)*M+this.cx},solveCurveX:function(M,et){if(void 0===et&&(et=1e-6),M<0)return 0;if(M>1)return 1;for(var Bt=M,Wt=0;Wt<8;Wt++){var Nt=this.sampleCurveX(Bt)-M;if(Math.abs(Nt)Nt?Gr=Bt:mn=Bt,Bt=.5*(mn-Gr)+Gr;return Bt},solve:function(M,et){return this.sampleCurveY(this.solveCurveX(M,et))}},Bc}(),Vc=tr(Mc);class sr{constructor(M,et,Bt,Wt,Nt){this.type=M,this.operator=et,this.interpolation=Bt,this.input=Wt,this.labels=[],this.outputs=[];for(const[M,et]of Nt)this.labels.push(M),this.outputs.push(et)}static interpolationFactor(M,et,Bt,Wt){let Nt=0;if("exponential"===M.name)Nt=ar(et,M.base,Bt,Wt);else if("linear"===M.name)Nt=ar(et,1,Bt,Wt);else if("cubic-bezier"===M.name){const $t=M.controlPoints;Nt=new Vc($t[0],$t[1],$t[2],$t[3]).solve(ar(et,1,Bt,Wt))}return Nt}static parse(M,et){let[Bt,Wt,Nt,...$t]=M;if(!Array.isArray(Wt)||0===Wt.length)return et.error("Expected an interpolation type expression.",1);if("linear"===Wt[0])Wt={name:"linear"};else if("exponential"===Wt[0]){const M=Wt[1];if("number"!=typeof M)return et.error("Exponential interpolation requires a numeric base.",1,1);Wt={name:"exponential",base:M}}else{if("cubic-bezier"!==Wt[0])return et.error(`Unknown interpolation type ${String(Wt[0])}`,1,0);{const M=Wt.slice(1);if(4!==M.length||M.some((M=>"number"!=typeof M||M<0||M>1)))return et.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);Wt={name:"cubic-bezier",controlPoints:M}}}if(M.length-1<4)return et.error(`Expected at least 4 arguments, but found only ${M.length-1}.`);if((M.length-1)%2!=0)return et.error("Expected an even number of arguments.");if(Nt=et.parse(Nt,2,Al),!Nt)return null;const Gr=[];let mn=null;"interpolate-hcl"===Bt||"interpolate-lab"===Bt?mn=Gl:et.expectedType&&"value"!==et.expectedType.kind&&(mn=et.expectedType);for(let M=0;M<$t.length;M+=2){const Bt=$t[M],Wt=$t[M+1],Nt=M+3,Hn=M+4;if("number"!=typeof Bt)return et.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.',Nt);if(Gr.length&&Gr[Gr.length-1][0]>=Bt)return et.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',Nt);const so=et.parse(Wt,Hn,mn);if(!so)return null;mn=mn||so.type,Gr.push([Bt,so])}return Zt(mn,Al)||Zt(mn,Rl)||Zt(mn,Gl)||Zt(mn,Jl)||Zt(mn,Dl)||Zt(mn,Rt(Al))?new sr(mn,Bt,Wt,Nt,Gr):et.error(`Type ${jt(mn)} is not interpolatable.`)}evaluate(M){const et=this.labels,Bt=this.outputs;if(1===et.length)return Bt[0].evaluate(M);const Wt=this.input.evaluate(M);if(Wt<=et[0])return Bt[0].evaluate(M);const Nt=et.length;if(Wt>=et[Nt-1])return Bt[Nt-1].evaluate(M);const $t=We(et,Wt),Gr=sr.interpolationFactor(this.interpolation,Wt,et[$t],et[$t+1]),mn=Bt[$t].evaluate(M),Hn=Bt[$t+1].evaluate(M);switch(this.operator){case"interpolate":switch(this.type.kind){case"number":return fe(mn,Hn,Gr);case"color":return ye.interpolate(mn,Hn,Gr);case"padding":return ve.interpolate(mn,Hn,Gr);case"variableAnchorOffsetCollection":return _e.interpolate(mn,Hn,Gr);case"array":return de(mn,Hn,Gr);case"projectionDefinition":return Ae.interpolate(mn,Hn,Gr)}case"interpolate-hcl":return ye.interpolate(mn,Hn,Gr,"hcl");case"interpolate-lab":return ye.interpolate(mn,Hn,Gr,"lab")}}eachChild(M){M(this.input);for(const et of this.outputs)M(et)}outputDefined(){return this.outputs.every((M=>M.outputDefined()))}}function ar(M,et,Bt,Wt){const Nt=Wt-Bt,$t=M-Bt;return 0===Nt?0:1===et?$t/Nt:(Math.pow(et,$t)-1)/(Math.pow(et,Nt)-1)}const zc={color:ye.interpolate,number:fe,padding:ve.interpolate,variableAnchorOffsetCollection:_e.interpolate,array:de};class lr{constructor(M,et){this.type=M,this.args=et}static parse(M,et){if(M.length<2)return et.error("Expected at least one argument.");let Bt=null;const Wt=et.expectedType;Wt&&"value"!==Wt.kind&&(Bt=Wt);const Nt=[];for(const Wt of M.slice(1)){const M=et.parse(Wt,1+Nt.length,Bt,void 0,{typeAnnotation:"omit"});if(!M)return null;Bt=Bt||M.type,Nt.push(M)}if(!Bt)throw new Error("No output type");const $t=Wt&&Nt.some((M=>Ut(Wt,M.type)));return new lr($t?Vl:Bt,Nt)}evaluate(M){let et,Bt=null,Wt=0;for(const Nt of this.args)if(Wt++,Bt=Nt.evaluate(M),Bt&&Bt instanceof Se&&!Bt.available&&(et||(et=Bt.name),Bt=null,Wt===this.args.length&&(Bt=et)),null!==Bt)break;return Bt}eachChild(M){this.args.forEach(M)}outputDefined(){return this.args.every((M=>M.outputDefined()))}}function ur(M,et){return"=="===M||"!="===M?"boolean"===et.kind||"string"===et.kind||"number"===et.kind||"null"===et.kind||"value"===et.kind:"string"===et.kind||"number"===et.kind||"value"===et.kind}function cr(M,et,Bt,Wt){return 0===Wt.compare(et,Bt)}function hr(M,et,Bt){const Wt="=="!==M&&"!="!==M;return class i{constructor(M,et,Bt){this.type=Zl,this.lhs=M,this.rhs=et,this.collator=Bt,this.hasUntypedArgument="value"===M.type.kind||"value"===et.type.kind}static parse(M,et){if(3!==M.length&&4!==M.length)return et.error("Expected two or three arguments.");const Bt=M[0];let Nt=et.parse(M[1],1,Vl);if(!Nt)return null;if(!ur(Bt,Nt.type))return et.concat(1).error(`"${Bt}" comparisons are not supported for type '${jt(Nt.type)}'.`);let $t=et.parse(M[2],2,Vl);if(!$t)return null;if(!ur(Bt,$t.type))return et.concat(2).error(`"${Bt}" comparisons are not supported for type '${jt($t.type)}'.`);if(Nt.type.kind!==$t.type.kind&&"value"!==Nt.type.kind&&"value"!==$t.type.kind)return et.error(`Cannot compare types '${jt(Nt.type)}' and '${jt($t.type)}'.`);Wt&&("value"===Nt.type.kind&&"value"!==$t.type.kind?Nt=new Be($t.type,[Nt]):"value"!==Nt.type.kind&&"value"===$t.type.kind&&($t=new Be(Nt.type,[$t])));let Gr=null;if(4===M.length){if("string"!==Nt.type.kind&&"string"!==$t.type.kind&&"value"!==Nt.type.kind&&"value"!==$t.type.kind)return et.error("Cannot use collator to compare non-string types.");if(Gr=et.parse(M[3],3,Wl),!Gr)return null}return new i(Nt,$t,Gr)}evaluate(Nt){const $t=this.lhs.evaluate(Nt),Gr=this.rhs.evaluate(Nt);if(Wt&&this.hasUntypedArgument){const et=Ie($t),Bt=Ie(Gr);if(et.kind!==Bt.kind||"string"!==et.kind&&"number"!==et.kind)throw new be(`Expected arguments for "${M}" to be (string, string) or (number, number), but found (${et.kind}, ${Bt.kind}) instead.`)}if(this.collator&&!Wt&&this.hasUntypedArgument){const M=Ie($t),Bt=Ie(Gr);if("string"!==M.kind||"string"!==Bt.kind)return et(Nt,$t,Gr)}return this.collator?Bt(Nt,$t,Gr,this.collator.evaluate(Nt)):et(Nt,$t,Gr)}eachChild(M){M(this.lhs),M(this.rhs),this.collator&&M(this.collator)}outputDefined(){return!0}}}const Fc=hr("==",(function(M,et,Bt){return et===Bt}),cr),Oc=hr("!=",(function(M,et,Bt){return et!==Bt}),(function(M,et,Bt,Wt){return!cr(0,et,Bt,Wt)})),jc=hr("<",(function(M,et,Bt){return et",(function(M,et,Bt){return et>Bt}),(function(M,et,Bt,Wt){return Wt.compare(et,Bt)>0})),Ih=hr("<=",(function(M,et,Bt){return et<=Bt}),(function(M,et,Bt,Wt){return Wt.compare(et,Bt)<=0})),Zh=hr(">=",(function(M,et,Bt){return et>=Bt}),(function(M,et,Bt,Wt){return Wt.compare(et,Bt)>=0}));class xr{constructor(M,et,Bt){this.type=Wl,this.locale=Bt,this.caseSensitive=M,this.diacriticSensitive=et}static parse(M,et){if(2!==M.length)return et.error("Expected one argument.");const Bt=M[1];if("object"!=typeof Bt||Array.isArray(Bt))return et.error("Collator options argument must be an object.");const Wt=et.parse(void 0!==Bt["case-sensitive"]&&Bt["case-sensitive"],1,Zl);if(!Wt)return null;const Nt=et.parse(void 0!==Bt["diacritic-sensitive"]&&Bt["diacritic-sensitive"],1,Zl);if(!Nt)return null;let $t=null;return Bt.locale&&($t=et.parse(Bt.locale,1,Sl),!$t)?null:new xr(Wt,Nt,$t)}evaluate(M){return new me(this.caseSensitive.evaluate(M),this.diacriticSensitive.evaluate(M),this.locale?this.locale.evaluate(M):null)}eachChild(M){M(this.caseSensitive),M(this.diacriticSensitive),this.locale&&M(this.locale)}outputDefined(){return!1}}class vr{constructor(M,et,Bt,Wt,Nt){this.type=Sl,this.number=M,this.locale=et,this.currency=Bt,this.minFractionDigits=Wt,this.maxFractionDigits=Nt}static parse(M,et){if(3!==M.length)return et.error("Expected two arguments.");const Bt=et.parse(M[1],1,Al);if(!Bt)return null;const Wt=M[2];if("object"!=typeof Wt||Array.isArray(Wt))return et.error("NumberFormat options argument must be an object.");let Nt=null;if(Wt.locale&&(Nt=et.parse(Wt.locale,1,Sl),!Nt))return null;let $t=null;if(Wt.currency&&($t=et.parse(Wt.currency,1,Sl),!$t))return null;let Gr=null;if(Wt["min-fraction-digits"]&&(Gr=et.parse(Wt["min-fraction-digits"],1,Al),!Gr))return null;let mn=null;return Wt["max-fraction-digits"]&&(mn=et.parse(Wt["max-fraction-digits"],1,Al),!mn)?null:new vr(Bt,Nt,$t,Gr,mn)}evaluate(M){return new Intl.NumberFormat(this.locale?this.locale.evaluate(M):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(M):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(M):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(M):void 0}).format(this.number.evaluate(M))}eachChild(M){M(this.number),this.locale&&M(this.locale),this.currency&&M(this.currency),this.minFractionDigits&&M(this.minFractionDigits),this.maxFractionDigits&&M(this.maxFractionDigits)}outputDefined(){return!1}}class br{constructor(M){this.type=El,this.sections=M}static parse(M,et){if(M.length<2)return et.error("Expected at least one argument.");const Bt=M[1];if(!Array.isArray(Bt)&&"object"==typeof Bt)return et.error("First argument must be an image or text section.");const Wt=[];let Nt=!1;for(let Bt=1;Bt<=M.length-1;++Bt){const $t=M[Bt];if(Nt&&"object"==typeof $t&&!Array.isArray($t)){Nt=!1;let M=null;if($t["font-scale"]&&(M=et.parse($t["font-scale"],1,Al),!M))return null;let Bt=null;if($t["text-font"]&&(Bt=et.parse($t["text-font"],1,Rt(Sl)),!Bt))return null;let Gr=null;if($t["text-color"]&&(Gr=et.parse($t["text-color"],1,Gl),!Gr))return null;const mn=Wt[Wt.length-1];mn.scale=M,mn.font=Bt,mn.textColor=Gr}else{const $t=et.parse(M[Bt],1,Vl);if(!$t)return null;const Gr=$t.type.kind;if("string"!==Gr&&"value"!==Gr&&"null"!==Gr&&"resolvedImage"!==Gr)return et.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");Nt=!0,Wt.push({content:$t,scale:null,font:null,textColor:null})}}return new br(Wt)}evaluate(M){return new xe(this.sections.map((et=>{const Bt=et.content.evaluate(M);return Ie(Bt)===Ll?new ge("",Bt,null,null,null):new ge(ze(Bt),null,et.scale?et.scale.evaluate(M):null,et.font?et.font.evaluate(M).join(","):null,et.textColor?et.textColor.evaluate(M):null)})))}eachChild(M){for(const et of this.sections)M(et.content),et.scale&&M(et.scale),et.font&&M(et.font),et.textColor&&M(et.textColor)}outputDefined(){return!1}}class wr{constructor(M){this.type=Ll,this.input=M}static parse(M,et){if(2!==M.length)return et.error("Expected two arguments.");const Bt=et.parse(M[1],1,Sl);return Bt?new wr(Bt):et.error("No image name provided.")}evaluate(M){const et=this.input.evaluate(M),Bt=Se.fromString(et);return Bt&&M.availableImages&&(Bt.available=M.availableImages.indexOf(et)>-1),Bt}eachChild(M){M(this.input)}outputDefined(){return!1}}class _r{constructor(M){this.type=Al,this.input=M}static parse(M,et){if(2!==M.length)return et.error(`Expected 1 argument, but found ${M.length-1} instead.`);const Bt=et.parse(M[1],1);return Bt?"array"!==Bt.type.kind&&"string"!==Bt.type.kind&&"value"!==Bt.type.kind?et.error(`Expected argument of type string or array, but found ${jt(Bt.type)} instead.`):new _r(Bt):null}evaluate(M){const et=this.input.evaluate(M);if("string"==typeof et)return[...et].length;if(Array.isArray(et))return et.length;throw new be(`Expected value to be of type string or array, but found ${jt(Ie(et))} instead.`)}eachChild(M){M(this.input)}outputDefined(){return!1}}const Gh=8192;function Ar(M,et){const Bt=(180+M[0])/360,Wt=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+M[1]*Math.PI/360)))/360,Nt=Math.pow(2,et.z);return[Math.round(Bt*Nt*Gh),Math.round(Wt*Nt*Gh)]}function kr(M,et){const Bt=Math.pow(2,et.z);return[(Nt=(M[0]/Gh+et.x)/Bt,360*Nt-180),(Wt=(M[1]/Gh+et.y)/Bt,360/Math.PI*Math.atan(Math.exp((180-360*Wt)*Math.PI/180))-90)];var Wt,Nt}function Mr(M,et){M[0]=Math.min(M[0],et[0]),M[1]=Math.min(M[1],et[1]),M[2]=Math.max(M[2],et[0]),M[3]=Math.max(M[3],et[1])}function Ir(M,et){return!(M[0]<=et[0]||M[2]>=et[2]||M[1]<=et[1]||M[3]>=et[3])}function zr(M,et,Bt){const Wt=M[0]-et[0],Nt=M[1]-et[1],$t=M[0]-Bt[0],Gr=M[1]-Bt[1];return Wt*Gr-$t*Nt==0&&Wt*$t<=0&&Nt*Gr<=0}function Pr(M,et,Bt,Wt){return 0!=(Nt=[Wt[0]-Bt[0],Wt[1]-Bt[1]])[0]*($t=[et[0]-M[0],et[1]-M[1]])[1]-Nt[1]*$t[0]&&!(!Fr(M,et,Bt,Wt)||!Fr(Bt,Wt,M,et));var Nt,$t}function Cr(M,et,Bt){for(const Wt of Bt)for(let Bt=0;Bt(Nt=M)[1]!=(Gr=mn[et+1])[1]>Nt[1]&&Nt[0]<(Gr[0]-$t[0])*(Nt[1]-$t[1])/(Gr[1]-$t[1])+$t[0]&&(Wt=!Wt)}var Nt,$t,Gr;return Wt}function Vr(M,et){for(const Bt of et)if(Br(M,Bt))return!0;return!1}function Er(M,et){for(const Bt of M)if(!Br(Bt,et))return!1;for(let Bt=0;Bt0&&mn<0||Gr<0&&mn>0}function $r(M,et,Bt){const Wt=[];for(let Nt=0;NtBt[2]){const et=.5*Wt;let Nt=M[0]-Bt[0]>et?-Wt:Bt[0]-M[0]>et?Wt:0;0===Nt&&(Nt=M[0]-Bt[2]>et?-Wt:Bt[2]-M[0]>et?Wt:0),M[0]+=Nt}Mr(et,M)}function Or(M,et,Bt,Wt){const Nt=Math.pow(2,Wt.z)*Gh,$t=[Wt.x*Gh,Wt.y*Gh],Gr=[];for(const Wt of M)for(const M of Wt){const Wt=[M.x+$t[0],M.y+$t[1]];Dr(Wt,et,Bt,Nt),Gr.push(Wt)}return Gr}function Rr(M,et,Bt,Wt){const Nt=Math.pow(2,Wt.z)*Gh,$t=[Wt.x*Gh,Wt.y*Gh],Gr=[];for(const Bt of M){const M=[];for(const Wt of Bt){const Bt=[Wt.x+$t[0],Wt.y+$t[1]];Mr(et,Bt),M.push(Bt)}Gr.push(M)}if(et[2]-et[0]<=Nt/2){(mn=et)[0]=mn[1]=1/0,mn[2]=mn[3]=-1/0;for(const M of Gr)for(const Wt of M)Dr(Wt,et,Bt,Nt)}var mn;return Gr}class jr{constructor(M,et){this.type=Zl,this.geojson=M,this.geometries=et}static parse(M,et){if(2!==M.length)return et.error(`'within' expression requires exactly one argument, but found ${M.length-1} instead.`);if(Me(M[1])){const et=M[1];if("FeatureCollection"===et.type){const M=[];for(const Bt of et.features){const{type:et,coordinates:Wt}=Bt.geometry;"Polygon"===et&&M.push(Wt),"MultiPolygon"===et&&M.push(...Wt)}if(M.length)return new jr(et,{type:"MultiPolygon",coordinates:M})}else if("Feature"===et.type){const M=et.geometry.type;if("Polygon"===M||"MultiPolygon"===M)return new jr(et,et.geometry)}else if("Polygon"===et.type||"MultiPolygon"===et.type)return new jr(et,et)}return et.error("'within' expression requires valid geojson object that contains polygon geometry type.")}evaluate(M){if(null!=M.geometry()&&null!=M.canonicalID()){if("Point"===M.geometryDollarType())return function(M,et){const Bt=[1/0,1/0,-1/0,-1/0],Wt=[1/0,1/0,-1/0,-1/0],Nt=M.canonicalID();if("Polygon"===et.type){const $t=$r(et.coordinates,Wt,Nt),Gr=Or(M.geometry(),Bt,Wt,Nt);if(!Ir(Bt,Wt))return!1;for(const M of Gr)if(!Br(M,$t))return!1}if("MultiPolygon"===et.type){const $t=Lr(et.coordinates,Wt,Nt),Gr=Or(M.geometry(),Bt,Wt,Nt);if(!Ir(Bt,Wt))return!1;for(const M of Gr)if(!Vr(M,$t))return!1}return!0}(M,this.geometries);if("LineString"===M.geometryDollarType())return function(M,et){const Bt=[1/0,1/0,-1/0,-1/0],Wt=[1/0,1/0,-1/0,-1/0],Nt=M.canonicalID();if("Polygon"===et.type){const $t=$r(et.coordinates,Wt,Nt),Gr=Rr(M.geometry(),Bt,Wt,Nt);if(!Ir(Bt,Wt))return!1;for(const M of Gr)if(!Er(M,$t))return!1}if("MultiPolygon"===et.type){const $t=Lr(et.coordinates,Wt,Nt),Gr=Rr(M.geometry(),Bt,Wt,Nt);if(!Ir(Bt,Wt))return!1;for(const M of Gr)if(!Tr(M,$t))return!1}return!0}(M,this.geometries)}return!1}eachChild(){}outputDefined(){return!0}}let Ph=class{constructor(M=[],et=(M,et)=>Met?1:0){if(this.data=M,this.length=this.data.length,this.compare=et,this.length>0)for(let M=(this.length>>1)-1;M>=0;M--)this._down(M)}push(M){this.data.push(M),this._up(this.length++)}pop(){if(0===this.length)return;const M=this.data[0],et=this.data.pop();return--this.length>0&&(this.data[0]=et,this._down(0)),M}peek(){return this.data[0]}_up(M){const{data:et,compare:Bt}=this,Wt=et[M];for(;M>0;){const Nt=M-1>>1,$t=et[Nt];if(Bt(Wt,$t)>=0)break;et[M]=$t,M=Nt}et[M]=Wt}_down(M){const{data:et,compare:Bt}=this,Wt=this.length>>1,Nt=et[M];for(;M=0)break;et[M]=et[Wt],M=Wt}et[M]=Nt}};const Wh=1/298.257223563,zh=Wh*(2-Wh),Jh=Math.PI/180;class Zr{constructor(M){const et=6378.137*Jh*1e3,Bt=Math.cos(M*Jh),Wt=1/(1-zh*(1-Bt*Bt)),Nt=Math.sqrt(Wt);this.kx=et*Nt*Bt,this.ky=et*Nt*Wt*(1-zh)}distance(M,et){const Bt=this.wrap(M[0]-et[0])*this.kx,Wt=(M[1]-et[1])*this.ky;return Math.sqrt(Bt*Bt+Wt*Wt)}pointOnLine(M,et){let Bt,Wt,Nt,$t,Gr=1/0;for(let mn=0;mn1?(Hn=M[mn+1][0],so=M[mn+1][1]):Po>0&&(Hn+=uo/this.kx*Po,so+=Io/this.ky*Po)),uo=this.wrap(et[0]-Hn)*this.kx,Io=(et[1]-so)*this.ky;const To=uo*uo+Io*Io;To180;)M-=360;return M}}function Xr(M,et){return et[0]-M[0]}function Kr(M){return M[1]-M[0]+1}function Hr(M,et){return M[1]>=M[0]&&M[1]M[1])return[null,null];const Bt=Kr(M);if(et){if(2===Bt)return[M,null];const et=Math.floor(Bt/2);return[[M[0],M[0]+et],[M[0]+et,M[1]]]}if(1===Bt)return[M,null];const Wt=Math.floor(Bt/2)-1;return[[M[0],M[0]+Wt],[M[0]+Wt+1,M[1]]]}function Jr(M,et){if(!Hr(et,M.length))return[1/0,1/0,-1/0,-1/0];const Bt=[1/0,1/0,-1/0,-1/0];for(let Wt=et[0];Wt<=et[1];++Wt)Mr(Bt,M[Wt]);return Bt}function Wr(M){const et=[1/0,1/0,-1/0,-1/0];for(const Bt of M)for(const M of Bt)Mr(et,M);return et}function Qr(M){return M[0]!==-1/0&&M[1]!==-1/0&&M[2]!==1/0&&M[3]!==1/0}function tn(M,et,Bt){if(!Qr(M)||!Qr(et))return NaN;let Wt=0,Nt=0;return M[2]et[2]&&(Wt=M[0]-et[2]),M[1]>et[3]&&(Nt=M[1]-et[3]),M[3]=Wt)return Wt;if(Ir(Nt,$t)){if(ln(M,et))return 0}else if(ln(et,M))return 0;let Gr=1/0;for(const Wt of M)for(let M=0,Nt=Wt.length,$t=Nt-1;M0;){const Nt=Gr.pop();if(Nt[0]>=$t)continue;const Hn=Nt[1],so=et?50:100;if(Kr(Hn)<=so){if(!Hr(Hn,M.length))return NaN;if(et){const et=on(M,Hn,Bt,Wt);if(isNaN(et)||0===et)return et;$t=Math.min($t,et)}else for(let et=Hn[0];et<=Hn[1];++et){const Nt=an(M[et],Bt,Wt);if($t=Math.min($t,Nt),0===$t)return 0}}else{const Bt=Yr(Hn,et);cn(Gr,$t,Wt,M,mn,Bt[0]),cn(Gr,$t,Wt,M,mn,Bt[1])}}return $t}function fn(M,et,Bt,Wt,Nt,$t=1/0){let Gr=Math.min($t,Nt.distance(M[0],Bt[0]));if(0===Gr)return Gr;const mn=new Ph([[0,[0,M.length-1],[0,Bt.length-1]]],Xr);for(;mn.length>0;){const $t=mn.pop();if($t[0]>=Gr)continue;const Hn=$t[1],so=$t[2],uo=et?50:100,Io=Wt?50:100;if(Kr(Hn)<=uo&&Kr(so)<=Io){if(!Hr(Hn,M.length)&&Hr(so,Bt.length))return NaN;let $t;if(et&&Wt)$t=nn(M,Hn,Bt,so,Nt),Gr=Math.min(Gr,$t);else if(et&&!Wt){const et=M.slice(Hn[0],Hn[1]+1);for(let M=so[0];M<=so[1];++M)if($t=en(Bt[M],et,Nt),Gr=Math.min(Gr,$t),0===Gr)return Gr}else if(!et&&Wt){const et=Bt.slice(so[0],so[1]+1);for(let Bt=Hn[0];Bt<=Hn[1];++Bt)if($t=en(M[Bt],et,Nt),Gr=Math.min(Gr,$t),0===Gr)return Gr}else $t=sn(M,Hn,Bt,so,Nt),Gr=Math.min(Gr,$t)}else{const $t=Yr(Hn,et),uo=Yr(so,Wt);hn(mn,Gr,Nt,M,Bt,$t[0],uo[0]),hn(mn,Gr,Nt,M,Bt,$t[0],uo[1]),hn(mn,Gr,Nt,M,Bt,$t[1],uo[0]),hn(mn,Gr,Nt,M,Bt,$t[1],uo[1])}}return Gr}function dn(M){return"MultiPolygon"===M.type?M.coordinates.map((M=>({type:"Polygon",coordinates:M}))):"MultiLineString"===M.type?M.coordinates.map((M=>({type:"LineString",coordinates:M}))):"MultiPoint"===M.type?M.coordinates.map((M=>({type:"Point",coordinates:M}))):[M]}class yn{constructor(M,et){this.type=Al,this.geojson=M,this.geometries=et}static parse(M,et){if(2!==M.length)return et.error(`'distance' expression requires exactly one argument, but found ${M.length-1} instead.`);if(Me(M[1])){const et=M[1];if("FeatureCollection"===et.type)return new yn(et,et.features.map((M=>dn(M.geometry))).flat());if("Feature"===et.type)return new yn(et,dn(et.geometry));if("type"in et&&"coordinates"in et)return new yn(et,dn(et))}return et.error("'distance' expression requires valid geojson object that contains polygon geometry type.")}evaluate(M){if(null!=M.geometry()&&null!=M.canonicalID()){if("Point"===M.geometryType())return function(M,et){const Bt=M.geometry(),Wt=Bt.flat().map((et=>kr([et.x,et.y],M.canonical)));if(0===Bt.length)return NaN;const Nt=new Zr(Wt[0][1]);let $t=1/0;for(const M of et){switch(M.type){case"Point":$t=Math.min($t,fn(Wt,!1,[M.coordinates],!1,Nt,$t));break;case"LineString":$t=Math.min($t,fn(Wt,!1,M.coordinates,!0,Nt,$t));break;case"Polygon":$t=Math.min($t,pn(Wt,!1,M.coordinates,Nt,$t))}if(0===$t)return $t}return $t}(M,this.geometries);if("LineString"===M.geometryType())return function(M,et){const Bt=M.geometry(),Wt=Bt.flat().map((et=>kr([et.x,et.y],M.canonical)));if(0===Bt.length)return NaN;const Nt=new Zr(Wt[0][1]);let $t=1/0;for(const M of et){switch(M.type){case"Point":$t=Math.min($t,fn(Wt,!0,[M.coordinates],!1,Nt,$t));break;case"LineString":$t=Math.min($t,fn(Wt,!0,M.coordinates,!0,Nt,$t));break;case"Polygon":$t=Math.min($t,pn(Wt,!0,M.coordinates,Nt,$t))}if(0===$t)return $t}return $t}(M,this.geometries);if("Polygon"===M.geometryType())return function(M,et){const Bt=M.geometry();if(0===Bt.length||0===Bt[0].length)return NaN;const Wt=Le(Bt,0).map((et=>et.map((et=>et.map((et=>kr([et.x,et.y],M.canonical))))))),Nt=new Zr(Wt[0][0][0][1]);let $t=1/0;for(const M of et)for(const et of Wt){switch(M.type){case"Point":$t=Math.min($t,pn([M.coordinates],!1,et,Nt,$t));break;case"LineString":$t=Math.min($t,pn(M.coordinates,!0,et,Nt,$t));break;case"Polygon":$t=Math.min($t,un(et,M.coordinates,Nt,$t))}if(0===$t)return $t}return $t}(M,this.geometries)}return NaN}eachChild(){}outputDefined(){return!0}}const Xh={"==":Fc,"!=":Oc,">":mh,"<":jc,">=":Zh,"<=":Ih,array:Be,at:Ze,boolean:Be,case:Ye,coalesce:lr,collator:xr,format:br,image:wr,in:Xe,"index-of":Ke,interpolate:sr,"interpolate-hcl":sr,"interpolate-lab":sr,length:_r,let:qe,literal:Pe,match:He,number:Be,"number-format":vr,object:Be,slice:Je,step:Qe,string:Be,"to-boolean":Ee,"to-color":Ee,"to-number":Ee,"to-string":Ee,var:Ge,within:jr,distance:yn};class gn{constructor(M,et,Bt,Wt){this.name=M,this.type=et,this._evaluate=Bt,this.args=Wt}evaluate(M){return this._evaluate(M,this.args)}eachChild(M){this.args.forEach(M)}outputDefined(){return!1}static parse(M,et){const Bt=M[0],Wt=gn.definitions[Bt];if(!Wt)return et.error(`Unknown expression "${Bt}". If you wanted a literal array, use ["literal", [...]].`,0);const Nt=Array.isArray(Wt)?Wt[0]:Wt.type,$t=Array.isArray(Wt)?[[Wt[1],Wt[2]]]:Wt.overloads,Gr=$t.filter((([et])=>!Array.isArray(et)||et.length===M.length-1));let mn=null;for(const[Wt,$t]of Gr){mn=new Ue(et.registry,_n,et.path,null,et.scope);const Gr=[];let Hn=!1;for(let et=1;et{return et=M,Array.isArray(et)?`(${et.map(jt).join(", ")})`:`(${jt(et.type)}...)`;var et})).join(" | "),Wt=[];for(let Bt=1;Bt{Bt=et?Bt&&_n(M):Bt&&M instanceof Pe})),!!Bt&&Sn(M)&&kn(M,["zoom","heatmap-density","line-progress","accumulated","is-supported-script"])}function Sn(M){if(M instanceof gn){if("get"===M.name&&1===M.args.length)return!1;if("feature-state"===M.name)return!1;if("has"===M.name&&1===M.args.length)return!1;if("properties"===M.name||"geometry-type"===M.name||"id"===M.name)return!1;if(/^filter-/.test(M.name))return!1}if(M instanceof jr)return!1;if(M instanceof yn)return!1;let et=!0;return M.eachChild((M=>{et&&!Sn(M)&&(et=!1)})),et}function An(M){if(M instanceof gn&&"feature-state"===M.name)return!1;let et=!0;return M.eachChild((M=>{et&&!An(M)&&(et=!1)})),et}function kn(M,et){if(M instanceof gn&&et.indexOf(M.name)>=0)return!1;let Bt=!0;return M.eachChild((M=>{Bt&&!kn(M,et)&&(Bt=!1)})),Bt}function Mn(M){return{result:"success",value:M}}function In(M){return{result:"error",value:M}}function zn(M){return"data-driven"===M["property-type"]||"cross-faded-data-driven"===M["property-type"]}function Pn(M){return!!M.expression&&M.expression.parameters.indexOf("zoom")>-1}function Cn(M){return!!M.expression&&M.expression.interpolated}function Bn(M){return M instanceof Number?"number":M instanceof String?"string":M instanceof Boolean?"boolean":Array.isArray(M)?"array":null===M?"null":typeof M}function Vn(M){return"object"==typeof M&&null!==M&&!Array.isArray(M)}function En(M){return M}function Tn(M,et){const Bt="color"===et.type,Wt=M.stops&&"object"==typeof M.stops[0][0],Nt=Wt||!(Wt||void 0!==M.property),$t=M.type||(Cn(et)?"exponential":"interval");if(Bt||"padding"===et.type){const Wt=Bt?ye.parse:ve.parse;(M=At({},M)).stops&&(M.stops=M.stops.map((M=>[M[0],Wt(M[1])]))),M.default=Wt(M.default?M.default:et.default)}if(M.colorSpace&&"rgb"!==(Gr=M.colorSpace)&&"hcl"!==Gr&&"lab"!==Gr)throw new Error(`Unknown color space: "${M.colorSpace}"`);var Gr;let mn,Hn,so;if("exponential"===$t)mn=Dn;else if("interval"===$t)mn=Ln;else if("categorical"===$t){mn=$n,Hn=Object.create(null);for(const et of M.stops)Hn[et[0]]=et[1];so=typeof M.stops[0][0]}else{if("identity"!==$t)throw new Error(`Unknown function type "${$t}"`);mn=On}if(Wt){const Bt={},Wt=[];for(let et=0;etM[0])),evaluate:({zoom:Bt},Wt)=>Dn({stops:Nt,base:M.base},et,Bt).evaluate(Bt,Wt)}}if(Nt){const Bt="exponential"===$t?{name:"exponential",base:void 0!==M.base?M.base:1}:null;return{kind:"camera",interpolationType:Bt,interpolationFactor:sr.interpolationFactor.bind(void 0,Bt),zoomStops:M.stops.map((M=>M[0])),evaluate:({zoom:Bt})=>mn(M,et,Bt,Hn,so)}}return{kind:"source",evaluate(Bt,Wt){const Nt=Wt&&Wt.properties?Wt.properties[M.property]:void 0;return void 0===Nt?Fn(M.default,et.default):mn(M,et,Nt,Hn,so)}}}function Fn(M,et,Bt){return void 0!==M?M:void 0!==et?et:void 0!==Bt?Bt:void 0}function $n(M,et,Bt,Wt,Nt){return Fn(typeof Bt===Nt?Wt[Bt]:void 0,M.default,et.default)}function Ln(M,et,Bt){if("number"!==Bn(Bt))return Fn(M.default,et.default);const Wt=M.stops.length;if(1===Wt)return M.stops[0][1];if(Bt<=M.stops[0][0])return M.stops[0][1];if(Bt>=M.stops[Wt-1][0])return M.stops[Wt-1][1];const Nt=We(M.stops.map((M=>M[0])),Bt);return M.stops[Nt][1]}function Dn(M,et,Bt){const Wt=void 0!==M.base?M.base:1;if("number"!==Bn(Bt))return Fn(M.default,et.default);const Nt=M.stops.length;if(1===Nt)return M.stops[0][1];if(Bt<=M.stops[0][0])return M.stops[0][1];if(Bt>=M.stops[Nt-1][0])return M.stops[Nt-1][1];const $t=We(M.stops.map((M=>M[0])),Bt),Gr=function(M,et,Bt,Wt){const Nt=Wt-Bt,$t=M-Bt;return 0===Nt?0:1===et?$t/Nt:(Math.pow(et,$t)-1)/(Math.pow(et,Nt)-1)}(Bt,Wt,M.stops[$t][0],M.stops[$t+1][0]),mn=M.stops[$t][1],Hn=M.stops[$t+1][1],so=zc[et.type]||En;return"function"==typeof mn.evaluate?{evaluate(...et){const Bt=mn.evaluate.apply(void 0,et),Wt=Hn.evaluate.apply(void 0,et);if(void 0!==Bt&&void 0!==Wt)return so(Bt,Wt,Gr,M.colorSpace)}}:so(mn,Hn,Gr,M.colorSpace)}function On(M,et,Bt){switch(et.type){case"color":Bt=ye.parse(Bt);break;case"formatted":Bt=xe.fromString(Bt.toString());break;case"resolvedImage":Bt=Se.fromString(Bt.toString());break;case"padding":Bt=ve.parse(Bt);break;default:Bn(Bt)===et.type||"enum"===et.type&&et.values[Bt]||(Bt=void 0)}return Fn(Bt,M.default,et.default)}gn.register(Xh,{error:[{kind:"error"},[Sl],(M,[et])=>{throw new be(et.evaluate(M))}],typeof:[Sl,[Vl],(M,[et])=>jt(Ie(et.evaluate(M)))],"to-rgba":[Rt(Al,4),[Gl],(M,[et])=>{const[Bt,Wt,Nt,$t]=et.evaluate(M).rgb;return[255*Bt,255*Wt,255*Nt,$t]}],rgb:[Gl,[Al,Al,Al],xn],rgba:[Gl,[Al,Al,Al,Al],xn],has:{type:Zl,overloads:[[[Sl],(M,[et])=>vn(et.evaluate(M),M.properties())],[[Sl,Tl],(M,[et,Bt])=>vn(et.evaluate(M),Bt.evaluate(M))]]},get:{type:Vl,overloads:[[[Sl],(M,[et])=>bn(et.evaluate(M),M.properties())],[[Sl,Tl],(M,[et,Bt])=>bn(et.evaluate(M),Bt.evaluate(M))]]},"feature-state":[Vl,[Sl],(M,[et])=>bn(et.evaluate(M),M.featureState||{})],properties:[Tl,[],M=>M.properties()],"geometry-type":[Sl,[],M=>M.geometryType()],id:[Vl,[],M=>M.id()],zoom:[Al,[],M=>M.globals.zoom],"heatmap-density":[Al,[],M=>M.globals.heatmapDensity||0],"line-progress":[Al,[],M=>M.globals.lineProgress||0],accumulated:[Vl,[],M=>void 0===M.globals.accumulated?null:M.globals.accumulated],"+":[Al,wn(Al),(M,et)=>{let Bt=0;for(const Wt of et)Bt+=Wt.evaluate(M);return Bt}],"*":[Al,wn(Al),(M,et)=>{let Bt=1;for(const Wt of et)Bt*=Wt.evaluate(M);return Bt}],"-":{type:Al,overloads:[[[Al,Al],(M,[et,Bt])=>et.evaluate(M)-Bt.evaluate(M)],[[Al],(M,[et])=>-et.evaluate(M)]]},"/":[Al,[Al,Al],(M,[et,Bt])=>et.evaluate(M)/Bt.evaluate(M)],"%":[Al,[Al,Al],(M,[et,Bt])=>et.evaluate(M)%Bt.evaluate(M)],ln2:[Al,[],()=>Math.LN2],pi:[Al,[],()=>Math.PI],e:[Al,[],()=>Math.E],"^":[Al,[Al,Al],(M,[et,Bt])=>Math.pow(et.evaluate(M),Bt.evaluate(M))],sqrt:[Al,[Al],(M,[et])=>Math.sqrt(et.evaluate(M))],log10:[Al,[Al],(M,[et])=>Math.log(et.evaluate(M))/Math.LN10],ln:[Al,[Al],(M,[et])=>Math.log(et.evaluate(M))],log2:[Al,[Al],(M,[et])=>Math.log(et.evaluate(M))/Math.LN2],sin:[Al,[Al],(M,[et])=>Math.sin(et.evaluate(M))],cos:[Al,[Al],(M,[et])=>Math.cos(et.evaluate(M))],tan:[Al,[Al],(M,[et])=>Math.tan(et.evaluate(M))],asin:[Al,[Al],(M,[et])=>Math.asin(et.evaluate(M))],acos:[Al,[Al],(M,[et])=>Math.acos(et.evaluate(M))],atan:[Al,[Al],(M,[et])=>Math.atan(et.evaluate(M))],min:[Al,wn(Al),(M,et)=>Math.min(...et.map((et=>et.evaluate(M))))],max:[Al,wn(Al),(M,et)=>Math.max(...et.map((et=>et.evaluate(M))))],abs:[Al,[Al],(M,[et])=>Math.abs(et.evaluate(M))],round:[Al,[Al],(M,[et])=>{const Bt=et.evaluate(M);return Bt<0?-Math.round(-Bt):Math.round(Bt)}],floor:[Al,[Al],(M,[et])=>Math.floor(et.evaluate(M))],ceil:[Al,[Al],(M,[et])=>Math.ceil(et.evaluate(M))],"filter-==":[Zl,[Sl,Vl],(M,[et,Bt])=>M.properties()[et.value]===Bt.value],"filter-id-==":[Zl,[Vl],(M,[et])=>M.id()===et.value],"filter-type-==":[Zl,[Sl],(M,[et])=>M.geometryDollarType()===et.value],"filter-<":[Zl,[Sl,Vl],(M,[et,Bt])=>{const Wt=M.properties()[et.value],Nt=Bt.value;return typeof Wt==typeof Nt&&Wt{const Bt=M.id(),Wt=et.value;return typeof Bt==typeof Wt&&Bt":[Zl,[Sl,Vl],(M,[et,Bt])=>{const Wt=M.properties()[et.value],Nt=Bt.value;return typeof Wt==typeof Nt&&Wt>Nt}],"filter-id->":[Zl,[Vl],(M,[et])=>{const Bt=M.id(),Wt=et.value;return typeof Bt==typeof Wt&&Bt>Wt}],"filter-<=":[Zl,[Sl,Vl],(M,[et,Bt])=>{const Wt=M.properties()[et.value],Nt=Bt.value;return typeof Wt==typeof Nt&&Wt<=Nt}],"filter-id-<=":[Zl,[Vl],(M,[et])=>{const Bt=M.id(),Wt=et.value;return typeof Bt==typeof Wt&&Bt<=Wt}],"filter->=":[Zl,[Sl,Vl],(M,[et,Bt])=>{const Wt=M.properties()[et.value],Nt=Bt.value;return typeof Wt==typeof Nt&&Wt>=Nt}],"filter-id->=":[Zl,[Vl],(M,[et])=>{const Bt=M.id(),Wt=et.value;return typeof Bt==typeof Wt&&Bt>=Wt}],"filter-has":[Zl,[Vl],(M,[et])=>et.value in M.properties()],"filter-has-id":[Zl,[],M=>null!==M.id()&&void 0!==M.id()],"filter-type-in":[Zl,[Rt(Sl)],(M,[et])=>et.value.indexOf(M.geometryDollarType())>=0],"filter-id-in":[Zl,[Rt(Vl)],(M,[et])=>et.value.indexOf(M.id())>=0],"filter-in-small":[Zl,[Sl,Rt(Vl)],(M,[et,Bt])=>Bt.value.indexOf(M.properties()[et.value])>=0],"filter-in-large":[Zl,[Sl,Rt(Vl)],(M,[et,Bt])=>function(M,et,Bt,Wt){for(;Bt<=Wt;){const Nt=Bt+Wt>>1;if(et[Nt]===M)return!0;et[Nt]>M?Wt=Nt-1:Bt=Nt+1}return!1}(M.properties()[et.value],Bt.value,0,Bt.value.length-1)],all:{type:Zl,overloads:[[[Zl,Zl],(M,[et,Bt])=>et.evaluate(M)&&Bt.evaluate(M)],[wn(Zl),(M,et)=>{for(const Bt of et)if(!Bt.evaluate(M))return!1;return!0}]]},any:{type:Zl,overloads:[[[Zl,Zl],(M,[et,Bt])=>et.evaluate(M)||Bt.evaluate(M)],[wn(Zl),(M,et)=>{for(const Bt of et)if(Bt.evaluate(M))return!0;return!1}]]},"!":[Zl,[Zl],(M,[et])=>!et.evaluate(M)],"is-supported-script":[Zl,[Sl],(M,[et])=>{const Bt=M.globals&&M.globals.isSupportedScript;return!Bt||Bt(et.evaluate(M))}],upcase:[Sl,[Sl],(M,[et])=>et.evaluate(M).toUpperCase()],downcase:[Sl,[Sl],(M,[et])=>et.evaluate(M).toLowerCase()],concat:[Sl,wn(Vl),(M,et)=>et.map((et=>ze(et.evaluate(M)))).join("")],"resolved-locale":[Sl,[Wl],(M,[et])=>et.evaluate(M).resolvedLocale()]});class Rn{constructor(M,et){var Bt;this.expression=M,this._warningHistory={},this._evaluator=new Ne,this._defaultValue=et?"color"===(Bt=et).type&&Vn(Bt.default)?new ye(0,0,0,0):"color"===Bt.type?ye.parse(Bt.default)||null:"padding"===Bt.type?ve.parse(Bt.default)||null:"variableAnchorOffsetCollection"===Bt.type?_e.parse(Bt.default)||null:"projectionDefinition"===Bt.type?Ae.parse(Bt.default)||null:void 0===Bt.default?null:Bt.default:null,this._enumValues=et&&"enum"===et.type?et.values:null}evaluateWithoutErrorHandling(M,et,Bt,Wt,Nt,$t){return this._evaluator.globals=M,this._evaluator.feature=et,this._evaluator.featureState=Bt,this._evaluator.canonical=Wt,this._evaluator.availableImages=Nt||null,this._evaluator.formattedSection=$t,this.expression.evaluate(this._evaluator)}evaluate(M,et,Bt,Wt,Nt,$t){this._evaluator.globals=M,this._evaluator.feature=et||null,this._evaluator.featureState=Bt||null,this._evaluator.canonical=Wt,this._evaluator.availableImages=Nt||null,this._evaluator.formattedSection=$t||null;try{const M=this.expression.evaluate(this._evaluator);if(null==M||"number"==typeof M&&M!=M)return this._defaultValue;if(this._enumValues&&!(M in this._enumValues))throw new be(`Expected value to be one of ${Object.keys(this._enumValues).map((M=>JSON.stringify(M))).join(", ")}, but found ${JSON.stringify(M)} instead.`);return M}catch(M){return this._warningHistory[M.message]||(this._warningHistory[M.message]=!0,"undefined"!=typeof console&&console.warn(M.message)),this._defaultValue}}}function jn(M){return Array.isArray(M)&&M.length>0&&"string"==typeof M[0]&&M[0]in Xh}function Nn(M,et){const Bt=new Ue(Xh,_n,[],et?function(M){const et={color:Gl,string:Sl,number:Al,enum:Sl,boolean:Zl,formatted:El,padding:Jl,projectionDefinition:Rl,resolvedImage:Ll,variableAnchorOffsetCollection:Dl};return"array"===M.type?Rt(et[M.value]||Vl,M.length):et[M.type]}(et):void 0),Wt=Bt.parse(M,void 0,void 0,void 0,et&&"string"===et.type?{typeAnnotation:"coerce"}:void 0);return Wt?Mn(new Rn(Wt,et)):In(Bt.errors)}class Un{constructor(M,et){this.kind=M,this._styleExpression=et,this.isStateDependent="constant"!==M&&!An(et.expression)}evaluateWithoutErrorHandling(M,et,Bt,Wt,Nt,$t){return this._styleExpression.evaluateWithoutErrorHandling(M,et,Bt,Wt,Nt,$t)}evaluate(M,et,Bt,Wt,Nt,$t){return this._styleExpression.evaluate(M,et,Bt,Wt,Nt,$t)}}class qn{constructor(M,et,Bt,Wt){this.kind=M,this.zoomStops=Bt,this._styleExpression=et,this.isStateDependent="camera"!==M&&!An(et.expression),this.interpolationType=Wt}evaluateWithoutErrorHandling(M,et,Bt,Wt,Nt,$t){return this._styleExpression.evaluateWithoutErrorHandling(M,et,Bt,Wt,Nt,$t)}evaluate(M,et,Bt,Wt,Nt,$t){return this._styleExpression.evaluate(M,et,Bt,Wt,Nt,$t)}interpolationFactor(M,et,Bt){return this.interpolationType?sr.interpolationFactor(this.interpolationType,M,et,Bt):0}}function Gn(M,et){const Bt=Nn(M,et);if("error"===Bt.result)return Bt;const Wt=Bt.value.expression,Nt=Sn(Wt);if(!Nt&&!zn(et))return In([new kt("","data expressions not supported")]);const $t=kn(Wt,["zoom"]);if(!$t&&!Pn(et))return In([new kt("","zoom expressions not supported")]);const Gr=Xn(Wt);return Gr||$t?Gr instanceof kt?In([Gr]):Gr instanceof sr&&!Cn(et)?In([new kt("",'"interpolate" expressions cannot be used with this property')]):Mn(Gr?new qn(Nt?"camera":"composite",Bt.value,Gr.labels,Gr instanceof sr?Gr.interpolation:void 0):new Un(Nt?"constant":"source",Bt.value)):In([new kt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')])}class Zn{constructor(M,et){this._parameters=M,this._specification=et,At(this,Tn(this._parameters,this._specification))}static deserialize(M){return new Zn(M._parameters,M._specification)}static serialize(M){return{_parameters:M._parameters,_specification:M._specification}}}function Xn(M){let et=null;if(M instanceof qe)et=Xn(M.result);else if(M instanceof lr){for(const Bt of M.args)if(et=Xn(Bt),et)break}else(M instanceof Qe||M instanceof sr)&&M.input instanceof gn&&"zoom"===M.input.name&&(et=M);return et instanceof kt||M.eachChild((M=>{const Bt=Xn(M);Bt instanceof kt?et=Bt:!et&&Bt?et=new kt("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.'):et&&Bt&&et!==Bt&&(et=new kt("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))})),et}function Kn(M){if(!0===M||!1===M)return!0;if(!Array.isArray(M)||0===M.length)return!1;switch(M[0]){case"has":return M.length>=2&&"$id"!==M[1]&&"$type"!==M[1];case"in":return M.length>=3&&("string"!=typeof M[1]||Array.isArray(M[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3!==M.length||Array.isArray(M[1])||Array.isArray(M[2]);case"any":case"all":for(const et of M.slice(1))if(!Kn(et)&&"boolean"!=typeof et)return!1;return!0;default:return!0}}const Lh={type:"boolean",default:!1,transition:!1,"property-type":"data-driven",expression:{interpolated:!1,parameters:["zoom","feature"]}};function Yn(M){if(null==M)return{filter:()=>!0,needGeometry:!1};Kn(M)||(M=Qn(M));const et=Nn(M,Lh);if("error"===et.result)throw new Error(et.value.map((M=>`${M.key}: ${M.message}`)).join(", "));return{filter:(M,Bt,Wt)=>et.value.evaluate(M,Bt,{},Wt),needGeometry:Wn(M)}}function Jn(M,et){return Met?1:0}function Wn(M){if(!Array.isArray(M))return!1;if("within"===M[0]||"distance"===M[0]||"geometry-type"===M[0])return!0;for(let et=1;et"===et||"<="===et||">="===et?ti(M[1],M[2],et):"any"===et?(Bt=M.slice(1),["any"].concat(Bt.map(Qn))):"all"===et?["all"].concat(M.slice(1).map(Qn)):"none"===et?["all"].concat(M.slice(1).map(Qn).map(ni)):"in"===et?ei(M[1],M.slice(2)):"!in"===et?ni(ei(M[1],M.slice(2))):"has"===et?ri(M[1]):"!has"!==et||ni(ri(M[1]));var Bt}function ti(M,et,Bt){switch(M){case"$type":return[`filter-type-${Bt}`,et];case"$id":return[`filter-id-${Bt}`,et];default:return[`filter-${Bt}`,M,et]}}function ei(M,et){if(0===et.length)return!1;switch(M){case"$type":return["filter-type-in",["literal",et]];case"$id":return["filter-id-in",["literal",et]];default:return et.length>200&&!et.some((M=>typeof M!=typeof et[0]))?["filter-in-large",M,["literal",et.sort(Jn)]]:["filter-in-small",M,["literal",et]]}}function ri(M){switch(M){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",M]}}function ni(M){return["!",M]}function ii(M){const et=typeof M;if("number"===et||"boolean"===et||"string"===et||null==M)return JSON.stringify(M);if(Array.isArray(M)){let et="[";for(const Bt of M)et+=`${ii(Bt)},`;return`${et}]`}const Bt=Object.keys(M).sort();let Wt="{";for(let et=0;etWt.maximum?[new St(et,Bt,`${Bt} is greater than the maximum value ${Wt.maximum}`)]:[]}function pi(M){const et=M.valueSpec,Bt=oi(M.value.type);let Wt,Nt,$t,Gr={};const mn="categorical"!==Bt&&void 0===M.value.property,Hn=!mn,so="array"===Bn(M.value.stops)&&"array"===Bn(M.value.stops[0])&&"object"===Bn(M.value.stops[0][0]),uo=ui({key:M.key,value:M.value,valueSpec:M.styleSpec.function,validateSpec:M.validateSpec,style:M.style,styleSpec:M.styleSpec,objectElementValidators:{stops:function(M){if("identity"===Bt)return[new St(M.key,M.value,'identity function may not have a "stops" property')];let et=[];const Wt=M.value;return et=et.concat(ci({key:M.key,value:Wt,valueSpec:M.valueSpec,validateSpec:M.validateSpec,style:M.style,styleSpec:M.styleSpec,arrayElementValidator:h})),"array"===Bn(Wt)&&0===Wt.length&&et.push(new St(M.key,Wt,"array must have at least one stop")),et},default:function(M){return M.validateSpec({key:M.key,value:M.value,valueSpec:et,validateSpec:M.validateSpec,style:M.style,styleSpec:M.styleSpec})}}});return"identity"===Bt&&mn&&uo.push(new St(M.key,M.value,'missing required property "property"')),"identity"===Bt||M.value.stops||uo.push(new St(M.key,M.value,'missing required property "stops"')),"exponential"===Bt&&M.valueSpec.expression&&!Cn(M.valueSpec)&&uo.push(new St(M.key,M.value,"exponential functions not supported")),M.styleSpec.$version>=8&&(Hn&&!zn(M.valueSpec)?uo.push(new St(M.key,M.value,"property functions not supported")):mn&&!Pn(M.valueSpec)&&uo.push(new St(M.key,M.value,"zoom functions not supported"))),"categorical"!==Bt&&!so||void 0!==M.value.property||uo.push(new St(M.key,M.value,'"property" property is required')),uo;function h(M){let Bt=[];const Wt=M.value,mn=M.key;if("array"!==Bn(Wt))return[new St(mn,Wt,`array expected, ${Bn(Wt)} found`)];if(2!==Wt.length)return[new St(mn,Wt,`array length 2 expected, length ${Wt.length} found`)];if(so){if("object"!==Bn(Wt[0]))return[new St(mn,Wt,`object expected, ${Bn(Wt[0])} found`)];if(void 0===Wt[0].zoom)return[new St(mn,Wt,"object stop key must have zoom")];if(void 0===Wt[0].value)return[new St(mn,Wt,"object stop key must have value")];if($t&&$t>oi(Wt[0].zoom))return[new St(mn,Wt[0].zoom,"stop zoom values must appear in ascending order")];oi(Wt[0].zoom)!==$t&&($t=oi(Wt[0].zoom),Nt=void 0,Gr={}),Bt=Bt.concat(ui({key:`${mn}[0]`,value:Wt[0],valueSpec:{zoom:{}},validateSpec:M.validateSpec,style:M.style,styleSpec:M.styleSpec,objectElementValidators:{zoom:hi,value:p}}))}else Bt=Bt.concat(p({key:`${mn}[0]`,value:Wt[0],valueSpec:{},validateSpec:M.validateSpec,style:M.style,styleSpec:M.styleSpec},Wt));return jn(li(Wt[1]))?Bt.concat([new St(`${mn}[1]`,Wt[1],"expressions are not allowed in function stops.")]):Bt.concat(M.validateSpec({key:`${mn}[1]`,value:Wt[1],valueSpec:et,validateSpec:M.validateSpec,style:M.style,styleSpec:M.styleSpec}))}function p(M,$t){const mn=Bn(M.value),Hn=oi(M.value),so=null!==M.value?M.value:$t;if(Wt){if(mn!==Wt)return[new St(M.key,so,`${mn} stop domain type must match previous stop domain type ${Wt}`)]}else Wt=mn;if("number"!==mn&&"string"!==mn&&"boolean"!==mn)return[new St(M.key,so,"stop domain value must be a number, string, or boolean")];if("number"!==mn&&"categorical"!==Bt){let Wt=`number expected, ${mn} found`;return zn(et)&&void 0===Bt&&(Wt+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new St(M.key,so,Wt)]}return"categorical"!==Bt||"number"!==mn||isFinite(Hn)&&Math.floor(Hn)===Hn?"categorical"!==Bt&&"number"===mn&&void 0!==Nt&&Hnnew St(`${M.key}${et.key}`,M.value,et.message)));const Bt=et.value.expression||et.value._styleExpression.expression;if("property"===M.expressionContext&&"text-font"===M.propertyKey&&!Bt.outputDefined())return[new St(M.key,M.value,`Invalid data expression for "${M.propertyKey}". Output values must be contained as literals within the expression.`)];if("property"===M.expressionContext&&"layout"===M.propertyType&&!An(Bt))return[new St(M.key,M.value,'"feature-state" data expressions are not supported with layout properties.')];if("filter"===M.expressionContext&&!An(Bt))return[new St(M.key,M.value,'"feature-state" data expressions are not supported with filters.')];if(M.expressionContext&&0===M.expressionContext.indexOf("cluster")){if(!kn(Bt,["zoom","feature-state"]))return[new St(M.key,M.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if("cluster-initial"===M.expressionContext&&!Sn(Bt))return[new St(M.key,M.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function di(M){const et=M.key,Bt=M.value,Wt=M.valueSpec,Nt=[];return Array.isArray(Wt.values)?-1===Wt.values.indexOf(oi(Bt))&&Nt.push(new St(et,Bt,`expected one of [${Wt.values.join(", ")}], ${JSON.stringify(Bt)} found`)):-1===Object.keys(Wt.values).indexOf(oi(Bt))&&Nt.push(new St(et,Bt,`expected one of [${Object.keys(Wt.values).join(", ")}], ${JSON.stringify(Bt)} found`)),Nt}function yi(M){return Kn(li(M.value))?fi(At({},M,{expressionContext:"filter",valueSpec:{value:"boolean"}})):mi(M)}function mi(M){const et=M.value,Bt=M.key;if("array"!==Bn(et))return[new St(Bt,et,`array expected, ${Bn(et)} found`)];const Wt=M.styleSpec;let Nt,$t=[];if(et.length<1)return[new St(Bt,et,"filter array must have at least 1 element")];switch($t=$t.concat(di({key:`${Bt}[0]`,value:et[0],valueSpec:Wt.filter_operator,style:M.style,styleSpec:M.styleSpec})),oi(et[0])){case"<":case"<=":case">":case">=":et.length>=2&&"$type"===oi(et[1])&&$t.push(new St(Bt,et,`"$type" cannot be use with operator "${et[0]}"`));case"==":case"!=":3!==et.length&&$t.push(new St(Bt,et,`filter array for operator "${et[0]}" must have 3 elements`));case"in":case"!in":et.length>=2&&(Nt=Bn(et[1]),"string"!==Nt&&$t.push(new St(`${Bt}[1]`,et[1],`string expected, ${Nt} found`)));for(let Gr=2;Gr{M in Bt&&et.push(new St(Wt,Bt[M],`"${M}" is prohibited for ref layers`))})),Nt.layers.forEach((et=>{oi(et.id)===mn&&(M=et)})),M?M.ref?et.push(new St(Wt,Bt.ref,"ref cannot reference another ref layer")):Gr=oi(M.type):et.push(new St(Wt,Bt.ref,`ref layer "${mn}" not found`))}else if("background"!==Gr)if(Bt.source){const M=Nt.sources&&Nt.sources[Bt.source],$t=M&&oi(M.type);M?"vector"===$t&&"raster"===Gr?et.push(new St(Wt,Bt.source,`layer "${Bt.id}" requires a raster source`)):"raster-dem"!==$t&&"hillshade"===Gr?et.push(new St(Wt,Bt.source,`layer "${Bt.id}" requires a raster-dem source`)):"raster"===$t&&"raster"!==Gr?et.push(new St(Wt,Bt.source,`layer "${Bt.id}" requires a vector source`)):"vector"!==$t||Bt["source-layer"]?"raster-dem"===$t&&"hillshade"!==Gr?et.push(new St(Wt,Bt.source,"raster-dem source can only be used with layer type 'hillshade'.")):"line"!==Gr||!Bt.paint||!Bt.paint["line-gradient"]||"geojson"===$t&&M.lineMetrics||et.push(new St(Wt,Bt,`layer "${Bt.id}" specifies a line-gradient, which requires a GeoJSON source with \`lineMetrics\` enabled.`)):et.push(new St(Wt,Bt,`layer "${Bt.id}" must specify a "source-layer"`)):et.push(new St(Wt,Bt.source,`source "${Bt.source}" not found`))}else et.push(new St(Wt,Bt,'missing required property "source"'));return et=et.concat(ui({key:Wt,value:Bt,valueSpec:$t.layer,style:M.style,styleSpec:M.styleSpec,validateSpec:M.validateSpec,objectElementValidators:{"*":()=>[],type:()=>M.validateSpec({key:`${Wt}.type`,value:Bt.type,valueSpec:$t.layer.type,style:M.style,styleSpec:M.styleSpec,validateSpec:M.validateSpec,object:Bt,objectKey:"type"}),filter:yi,layout:M=>ui({layer:Bt,key:M.key,value:M.value,style:M.style,styleSpec:M.styleSpec,validateSpec:M.validateSpec,objectElementValidators:{"*":M=>vi(At({layerType:Gr},M))}}),paint:M=>ui({layer:Bt,key:M.key,value:M.value,style:M.style,styleSpec:M.styleSpec,validateSpec:M.validateSpec,objectElementValidators:{"*":M=>xi(At({layerType:Gr},M))}})}})),et}function wi(M){const et=M.value,Bt=M.key,Wt=Bn(et);return"string"!==Wt?[new St(Bt,et,`string expected, ${Wt} found`)]:[]}const Hh={promoteId:function({key:M,value:et}){if("string"===Bn(et))return wi({key:M,value:et});{const Bt=[];for(const Wt in et)Bt.push(...wi({key:`${M}.${Wt}`,value:et[Wt]}));return Bt}}};function Si(M){const et=M.value,Bt=M.key,Wt=M.styleSpec,Nt=M.style,$t=M.validateSpec;if(!et.type)return[new St(Bt,et,'"type" is required')];const Gr=oi(et.type);let mn;switch(Gr){case"vector":case"raster":return mn=ui({key:Bt,value:et,valueSpec:Wt[`source_${Gr.replace("-","_")}`],style:M.style,styleSpec:Wt,objectElementValidators:Hh,validateSpec:$t}),mn;case"raster-dem":return mn=function(M){var et;const Bt=null!==(et=M.sourceName)&&void 0!==et?et:"",Wt=M.value,Nt=M.styleSpec,$t=Nt.source_raster_dem,Gr=M.style;let mn=[];const Hn=Bn(Wt);if(void 0===Wt)return mn;if("object"!==Hn)return mn.push(new St("source_raster_dem",Wt,`object expected, ${Hn} found`)),mn;const so="custom"===oi(Wt.encoding),uo=["redFactor","greenFactor","blueFactor","baseShift"],Io=M.value.encoding?`"${M.value.encoding}"`:"Default";for(const et in Wt)!so&&uo.includes(et)?mn.push(new St(et,Wt[et],`In "${Bt}": "${et}" is only valid when "encoding" is set to "custom". ${Io} encoding found`)):$t[et]?mn=mn.concat(M.validateSpec({key:et,value:Wt[et],valueSpec:$t[et],validateSpec:M.validateSpec,style:Gr,styleSpec:Nt})):mn.push(new St(et,Wt[et],`unknown property "${et}"`));return mn}({sourceName:Bt,value:et,style:M.style,styleSpec:Wt,validateSpec:$t}),mn;case"geojson":if(mn=ui({key:Bt,value:et,valueSpec:Wt.source_geojson,style:Nt,styleSpec:Wt,validateSpec:$t,objectElementValidators:Hh}),et.cluster)for(const M in et.clusterProperties){const[Wt,Nt]=et.clusterProperties[M],Gr="string"==typeof Wt?[Wt,["accumulated"],["get",M]]:Wt;mn.push(...fi({key:`${Bt}.${M}.map`,value:Nt,validateSpec:$t,expressionContext:"cluster-map"})),mn.push(...fi({key:`${Bt}.${M}.reduce`,value:Gr,validateSpec:$t,expressionContext:"cluster-reduce"}))}return mn;case"video":return ui({key:Bt,value:et,valueSpec:Wt.source_video,style:Nt,validateSpec:$t,styleSpec:Wt});case"image":return ui({key:Bt,value:et,valueSpec:Wt.source_image,style:Nt,validateSpec:$t,styleSpec:Wt});case"canvas":return[new St(Bt,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return di({key:`${Bt}.type`,value:et.type,valueSpec:{values:["vector","raster","raster-dem","geojson","video","image"]},style:Nt,validateSpec:$t,styleSpec:Wt})}}function Ai(M){const et=M.value,Bt=M.styleSpec,Wt=Bt.light,Nt=M.style;let $t=[];const Gr=Bn(et);if(void 0===et)return $t;if("object"!==Gr)return $t=$t.concat([new St("light",et,`object expected, ${Gr} found`)]),$t;for(const Gr in et){const mn=Gr.match(/^(.*)-transition$/);$t=$t.concat(mn&&Wt[mn[1]]&&Wt[mn[1]].transition?M.validateSpec({key:Gr,value:et[Gr],valueSpec:Bt.transition,validateSpec:M.validateSpec,style:Nt,styleSpec:Bt}):Wt[Gr]?M.validateSpec({key:Gr,value:et[Gr],valueSpec:Wt[Gr],validateSpec:M.validateSpec,style:Nt,styleSpec:Bt}):[new St(Gr,et[Gr],`unknown property "${Gr}"`)])}return $t}function ki(M){const et=M.value,Bt=M.styleSpec,Wt=Bt.sky,Nt=M.style,$t=Bn(et);if(void 0===et)return[];if("object"!==$t)return[new St("sky",et,`object expected, ${$t} found`)];let Gr=[];for(const $t in et)Gr=Gr.concat(Wt[$t]?M.validateSpec({key:$t,value:et[$t],valueSpec:Wt[$t],style:Nt,styleSpec:Bt}):[new St($t,et[$t],`unknown property "${$t}"`)]);return Gr}function Mi(M){const et=M.value,Bt=M.styleSpec,Wt=Bt.terrain,Nt=M.style;let $t=[];const Gr=Bn(et);if(void 0===et)return $t;if("object"!==Gr)return $t=$t.concat([new St("terrain",et,`object expected, ${Gr} found`)]),$t;for(const Gr in et)$t=$t.concat(Wt[Gr]?M.validateSpec({key:Gr,value:et[Gr],valueSpec:Wt[Gr],validateSpec:M.validateSpec,style:Nt,styleSpec:Bt}):[new St(Gr,et[Gr],`unknown property "${Gr}"`)]);return $t}function Ii(M){let et=[];const Bt=M.value,Wt=M.key;if(Array.isArray(Bt)){const Nt=[],$t=[];for(const Gr in Bt)Bt[Gr].id&&Nt.includes(Bt[Gr].id)&&et.push(new St(Wt,Bt,`all the sprites' ids must be unique, but ${Bt[Gr].id} is duplicated`)),Nt.push(Bt[Gr].id),Bt[Gr].url&&$t.includes(Bt[Gr].url)&&et.push(new St(Wt,Bt,`all the sprites' URLs must be unique, but ${Bt[Gr].url} is duplicated`)),$t.push(Bt[Gr].url),et=et.concat(ui({key:`${Wt}[${Gr}]`,value:Bt[Gr],valueSpec:{id:{type:"string",required:!0},url:{type:"string",required:!0}},validateSpec:M.validateSpec}));return et}return wi({key:Wt,value:Bt})}const Kh={"*":()=>[],array:ci,boolean:function(M){const et=M.value,Bt=M.key,Wt=Bn(et);return"boolean"!==Wt?[new St(Bt,et,`boolean expected, ${Wt} found`)]:[]},number:hi,color:function(M){const et=M.key,Bt=M.value,Wt=Bn(Bt);return"string"!==Wt?[new St(et,Bt,`color expected, ${Wt} found`)]:ye.parse(String(Bt))?[]:[new St(et,Bt,`color expected, "${Bt}" found`)]},constants:ai,enum:di,filter:yi,function:pi,layer:bi,object:ui,source:Si,light:Ai,sky:ki,terrain:Mi,projection:function(M){const et=M.value,Bt=M.styleSpec,Wt=Bt.projection,Nt=M.style,$t=Bn(et);if(void 0===et)return[];if("object"!==$t)return[new St("projection",et,`object expected, ${$t} found`)];let Gr=[];for(const $t in et)Gr=Gr.concat(Wt[$t]?M.validateSpec({key:$t,value:et[$t],valueSpec:Wt[$t],style:Nt,styleSpec:Bt}):[new St($t,et[$t],`unknown property "${$t}"`)]);return Gr},projectionDefinition:function(M){const et=M.key;let Bt=M.value;Bt=Bt instanceof String?Bt.valueOf():Bt;const Wt=Bn(Bt);return"array"!==Wt||function(M){return Array.isArray(M)&&3===M.length&&"string"==typeof M[0]&&"string"==typeof M[1]&&"number"==typeof M[2]}(Bt)||function(M){return!!["interpolate","step","literal"].includes(M[0])}(Bt)?["array","string"].includes(Wt)?[]:[new St(et,Bt,`projection expected, invalid type "${Wt}" found`)]:[new St(et,Bt,`projection expected, invalid array ${JSON.stringify(Bt)} found`)]},string:wi,formatted:function(M){return 0===wi(M).length?[]:fi(M)},resolvedImage:function(M){return 0===wi(M).length?[]:fi(M)},padding:function(M){const et=M.key,Bt=M.value;if("array"===Bn(Bt)){if(Bt.length<1||Bt.length>4)return[new St(et,Bt,`padding requires 1 to 4 values; ${Bt.length} values found`)];const Wt={type:"number"};let Nt=[];for(let $t=0;$t[]}})),M.constants&&(Bt=Bt.concat(ai({key:"constants",value:M.constants,style:M,styleSpec:et,validateSpec:Pi}))),Ei(Bt)}function Vi(M){return function(et){return M({...et,validateSpec:Pi})}}function Ei(M){return[].concat(M).sort(((M,et)=>M.line-et.line))}function Ti(M){return function(...et){return Ei(M.apply(this,et))}}Bi.source=Ti(Vi(Si)),Bi.sprite=Ti(Vi(Ii)),Bi.glyphs=Ti(Vi(Ci)),Bi.light=Ti(Vi(Ai)),Bi.sky=Ti(Vi(ki)),Bi.terrain=Ti(Vi(Mi)),Bi.layer=Ti(Vi(bi)),Bi.filter=Ti(Vi(yi)),Bi.paintProperty=Ti(Vi(xi)),Bi.layoutProperty=Ti(Vi(vi));const Yh=Bi,Qh=Yh.light,qh=Yh.sky,tg=Yh.paintProperty,eg=Yh.layoutProperty;function Ri(M,et){let Bt=!1;if(et&&et.length)for(const Wt of et)M.fire(new ut(new Error(Wt.message))),Bt=!0;return Bt}class ji{constructor(M,et,Bt){const Wt=this.cells=[];if(M instanceof ArrayBuffer){this.arrayBuffer=M;const Nt=new Int32Array(this.arrayBuffer);M=Nt[0],this.d=(et=Nt[1])+2*(Bt=Nt[2]);for(let M=0;M=so[Hn+0]&&Wt>=so[Hn+1])?(Gr[Io]=!0,$t.push(Nt[Io])):Gr[Io]=!1}}}}_forEachCell(M,et,Bt,Wt,Nt,$t,Gr,mn){const Hn=this._convertToCellCoord(M),so=this._convertToCellCoord(et),uo=this._convertToCellCoord(Bt),Io=this._convertToCellCoord(Wt);for(let Po=Hn;Po<=uo;Po++)for(let Hn=so;Hn<=Io;Hn++){const so=this.d*Hn+Po;if((!mn||mn(this._convertFromCellCoord(Po),this._convertFromCellCoord(Hn),this._convertFromCellCoord(Po+1),this._convertFromCellCoord(Hn+1)))&&Nt.call(this,M,et,Bt,Wt,so,$t,Gr,mn))return}}_convertFromCellCoord(M){return(M-this.padding)/this.scale}_convertToCellCoord(M){return Math.max(0,Math.min(this.d-1,Math.floor(M*this.scale)+this.padding))}toArrayBuffer(){if(this.arrayBuffer)return this.arrayBuffer;const M=this.cells,et=3+this.cells.length+1+1;let Bt=0;for(let M=0;M=0)continue;const $t=M[Wt];Nt[Wt]=ig[Bt].shallow.indexOf(Wt)>=0?$t:Xi($t,et)}M instanceof Error&&(Nt.message=M.message)}if(Nt.$name)throw new Error("$name property is reserved for worker serialization logic.");return"Object"!==Bt&&(Nt.$name=Bt),Nt}function Ki(M){if(Zi(M))return M;if(Array.isArray(M))return M.map(Ki);if("object"!=typeof M)throw new Error("can't deserialize object of type "+typeof M);const et=Gi(M)||"Object";if(!ig[et])throw new Error(`can't deserialize unregistered class ${et}`);const{klass:Bt}=ig[et];if(!Bt)throw new Error(`can't deserialize unregistered class ${et}`);if(Bt.deserialize)return Bt.deserialize(M);const Wt=Object.create(Bt.prototype);for(const Bt of Object.keys(M)){if("$name"===Bt)continue;const Nt=M[Bt];Wt[Bt]=ig[et].shallow.indexOf(Bt)>=0?Nt:Ki(Nt)}return Wt}class Hi{constructor(){this.first=!0}update(M,et){const Bt=Math.floor(M);return this.first?(this.first=!1,this.lastIntegerZoom=Bt,this.lastIntegerZoomTime=0,this.lastZoom=M,this.lastFloorZoom=Bt,!0):(this.lastFloorZoom>Bt?(this.lastIntegerZoom=Bt+1,this.lastIntegerZoomTime=et):this.lastFloorZoomM>=128&&M<=255,"Hangul Jamo":M=>M>=4352&&M<=4607,Khmer:M=>M>=6016&&M<=6143,"General Punctuation":M=>M>=8192&&M<=8303,"Letterlike Symbols":M=>M>=8448&&M<=8527,"Number Forms":M=>M>=8528&&M<=8591,"Miscellaneous Technical":M=>M>=8960&&M<=9215,"Control Pictures":M=>M>=9216&&M<=9279,"Optical Character Recognition":M=>M>=9280&&M<=9311,"Enclosed Alphanumerics":M=>M>=9312&&M<=9471,"Geometric Shapes":M=>M>=9632&&M<=9727,"Miscellaneous Symbols":M=>M>=9728&&M<=9983,"Miscellaneous Symbols and Arrows":M=>M>=11008&&M<=11263,"Ideographic Description Characters":M=>M>=12272&&M<=12287,"CJK Symbols and Punctuation":M=>M>=12288&&M<=12351,Katakana:M=>M>=12448&&M<=12543,Kanbun:M=>M>=12688&&M<=12703,"CJK Strokes":M=>M>=12736&&M<=12783,"Enclosed CJK Letters and Months":M=>M>=12800&&M<=13055,"CJK Compatibility":M=>M>=13056&&M<=13311,"Yijing Hexagram Symbols":M=>M>=19904&&M<=19967,"Private Use Area":M=>M>=57344&&M<=63743,"Vertical Forms":M=>M>=65040&&M<=65055,"CJK Compatibility Forms":M=>M>=65072&&M<=65103,"Small Form Variants":M=>M>=65104&&M<=65135,"Halfwidth and Fullwidth Forms":M=>M>=65280&&M<=65519};function Ji(M){for(const et of M)if(ns(et.charCodeAt(0)))return!0;return!1}function Wi(M){for(const et of M)if(!es(et.charCodeAt(0)))return!1;return!0}function Qi(M){const et=M.map((M=>{try{return new RegExp(`\\p{sc=${M}}`,"u").source}catch(M){return null}})).filter((M=>M));return new RegExp(et.join("|"),"u")}const ng=Qi(["Arab","Dupl","Mong","Ougr","Syrc"]);function es(M){return!ng.test(String.fromCodePoint(M))}const og=Qi(["Bopo","Hani","Hira","Kana","Kits","Nshu","Tang","Yiii"]);function ns(M){return!(746!==M&&747!==M&&(M<4352||!(rg["CJK Compatibility Forms"](M)&&!(M>=65097&&M<=65103)||rg["CJK Compatibility"](M)||rg["CJK Strokes"](M)||!(!rg["CJK Symbols and Punctuation"](M)||M>=12296&&M<=12305||M>=12308&&M<=12319||12336===M)||rg["Enclosed CJK Letters and Months"](M)||rg["Ideographic Description Characters"](M)||rg.Kanbun(M)||rg.Katakana(M)&&12540!==M||!(!rg["Halfwidth and Fullwidth Forms"](M)||65288===M||65289===M||65293===M||M>=65306&&M<=65310||65339===M||65341===M||65343===M||M>=65371&&M<=65503||65507===M||M>=65512&&M<=65519)||!(!rg["Small Form Variants"](M)||M>=65112&&M<=65118||M>=65123&&M<=65126)||rg["Vertical Forms"](M)||rg["Yijing Hexagram Symbols"](M)||/\p{sc=Cans}/u.test(String.fromCodePoint(M))||/\p{sc=Hang}/u.test(String.fromCodePoint(M))||og.test(String.fromCodePoint(M)))))}function is(M){return!(ns(M)||function(M){return!!(rg["Latin-1 Supplement"](M)&&(167===M||169===M||174===M||177===M||188===M||189===M||190===M||215===M||247===M)||rg["General Punctuation"](M)&&(8214===M||8224===M||8225===M||8240===M||8241===M||8251===M||8252===M||8258===M||8263===M||8264===M||8265===M||8273===M)||rg["Letterlike Symbols"](M)||rg["Number Forms"](M)||rg["Miscellaneous Technical"](M)&&(M>=8960&&M<=8967||M>=8972&&M<=8991||M>=8996&&M<=9e3||9003===M||M>=9085&&M<=9114||M>=9150&&M<=9165||9167===M||M>=9169&&M<=9179||M>=9186&&M<=9215)||rg["Control Pictures"](M)&&9251!==M||rg["Optical Character Recognition"](M)||rg["Enclosed Alphanumerics"](M)||rg["Geometric Shapes"](M)||rg["Miscellaneous Symbols"](M)&&!(M>=9754&&M<=9759)||rg["Miscellaneous Symbols and Arrows"](M)&&(M>=11026&&M<=11055||M>=11088&&M<=11097||M>=11192&&M<=11243)||rg["CJK Symbols and Punctuation"](M)||rg.Katakana(M)||rg["Private Use Area"](M)||rg["CJK Compatibility Forms"](M)||rg["Small Form Variants"](M)||rg["Halfwidth and Fullwidth Forms"](M)||8734===M||8756===M||8757===M||M>=9984&&M<=10087||M>=10102&&M<=10131||65532===M||65533===M)}(M))}const sg=Qi(["Adlm","Arab","Armi","Avst","Chrs","Cprt","Egyp","Elym","Gara","Hatr","Hebr","Hung","Khar","Lydi","Mand","Mani","Mend","Merc","Mero","Narb","Nbat","Nkoo","Orkh","Palm","Phli","Phlp","Phnx","Prti","Rohg","Samr","Sarb","Sogo","Syrc","Thaa","Todr","Yezi"]);function as(M){return sg.test(String.fromCodePoint(M))}function os(M,et){return!(!et&&as(M)||M>=2304&&M<=3583||M>=3840&&M<=4255||rg.Khmer(M))}function ls(M){for(const et of M)if(as(et.charCodeAt(0)))return!0;return!1}const ag=new class{constructor(){this.TIMEOUT=5e3,this.applyArabicShaping=null,this.processBidirectionalText=null,this.processStyledBidirectionalText=null,this.pluginStatus="unavailable",this.pluginURL=null,this.loadScriptResolve=()=>{}}setState(M){this.pluginStatus=M.pluginStatus,this.pluginURL=M.pluginURL}getState(){return{pluginStatus:this.pluginStatus,pluginURL:this.pluginURL}}setMethods(M){if(ag.isParsed())throw new Error("RTL text plugin already registered.");this.applyArabicShaping=M.applyArabicShaping,this.processBidirectionalText=M.processBidirectionalText,this.processStyledBidirectionalText=M.processStyledBidirectionalText,this.loadScriptResolve()}isParsed(){return null!=this.applyArabicShaping&&null!=this.processBidirectionalText&&null!=this.processStyledBidirectionalText}getRTLTextPluginStatus(){return this.pluginStatus}syncState(M,et){return e(this,void 0,void 0,(function*(){if(this.isParsed())return this.getState();if("loading"!==M.pluginStatus)return this.setState(M),M;const Bt=M.pluginURL,Wt=new Promise((M=>{this.loadScriptResolve=M}));et(Bt);const Nt=new Promise((M=>setTimeout((()=>M()),this.TIMEOUT)));if(yield Promise.race([Wt,Nt]),this.isParsed()){const M={pluginStatus:"loaded",pluginURL:Bt};return this.setState(M),M}throw this.setState({pluginStatus:"error",pluginURL:""}),new Error(`RTL Text Plugin failed to import scripts from ${Bt}`)}))}};class cs{constructor(M,et){this.zoom=M,et?(this.now=et.now,this.fadeDuration=et.fadeDuration,this.zoomHistory=et.zoomHistory,this.transition=et.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new Hi,this.transition={})}isSupportedScript(M){return function(M,et){for(const Bt of M)if(!os(Bt.charCodeAt(0),et))return!1;return!0}(M,"loaded"===ag.getRTLTextPluginStatus())}crossFadingFactor(){return 0===this.fadeDuration?1:Math.min((this.now-this.zoomHistory.lastIntegerZoomTime)/this.fadeDuration,1)}getCrossfadeParameters(){const M=this.zoom,et=M-Math.floor(M),Bt=this.crossFadingFactor();return M>this.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:et+(1-et)*Bt}:{fromScale:.5,toScale:1,t:1-(1-Bt)*et}}}class hs{constructor(M,et){this.property=M,this.value=et,this.expression=function(M,et){if(Vn(M))return new Zn(M,et);if(jn(M)){const Bt=Gn(M,et);if("error"===Bt.result)throw new Error(Bt.value.map((M=>`${M.key}: ${M.message}`)).join(", "));return Bt.value}{let Bt=M;return"color"===et.type&&"string"==typeof M?Bt=ye.parse(M):"padding"!==et.type||"number"!=typeof M&&!Array.isArray(M)?"variableAnchorOffsetCollection"===et.type&&Array.isArray(M)?Bt=_e.parse(M):"projectionDefinition"===et.type&&"string"==typeof M&&(Bt=Ae.parse(M)):Bt=ve.parse(M),{kind:"constant",evaluate:()=>Bt}}}(void 0===et?M.specification.default:et,M.specification)}isDataDriven(){return"source"===this.expression.kind||"composite"===this.expression.kind}possiblyEvaluate(M,et,Bt){return this.property.possiblyEvaluate(this,M,et,Bt)}}class ps{constructor(M){this.property=M,this.value=new hs(M,void 0)}transitioned(M,et){return new ds(this.property,this.value,et,F({},M.transition,this.transition),M.now)}untransitioned(){return new ds(this.property,this.value,null,{},0)}}class fs{constructor(M){this._properties=M,this._values=Object.create(M.defaultTransitionablePropertyValues)}getValue(M){return O(this._values[M].value.value)}setValue(M,et){Object.prototype.hasOwnProperty.call(this._values,M)||(this._values[M]=new ps(this._values[M].property)),this._values[M].value=new hs(this._values[M].property,null===et?void 0:O(et))}getTransition(M){return O(this._values[M].transition)}setTransition(M,et){Object.prototype.hasOwnProperty.call(this._values,M)||(this._values[M]=new ps(this._values[M].property)),this._values[M].transition=O(et)||void 0}serialize(){const M={};for(const et of Object.keys(this._values)){const Bt=this.getValue(et);void 0!==Bt&&(M[et]=Bt);const Wt=this.getTransition(et);void 0!==Wt&&(M[`${et}-transition`]=Wt)}return M}transitioned(M,et){const Bt=new ys(this._properties);for(const Wt of Object.keys(this._values))Bt._values[Wt]=this._values[Wt].transitioned(M,et._values[Wt]);return Bt}untransitioned(){const M=new ys(this._properties);for(const et of Object.keys(this._values))M._values[et]=this._values[et].untransitioned();return M}}class ds{constructor(M,et,Bt,Wt,Nt){this.property=M,this.value=et,this.begin=Nt+Wt.delay||0,this.end=this.begin+Wt.duration||0,M.specification.transition&&(Wt.delay||Wt.duration)&&(this.prior=Bt)}possiblyEvaluate(M,et,Bt){const Wt=M.now||0,Nt=this.value.possiblyEvaluate(M,et,Bt),$t=this.prior;if($t){if(Wt>this.end)return this.prior=null,Nt;if(this.value.isDataDriven())return this.prior=null,Nt;if(WtWt.zoomHistory.lastIntegerZoom?{from:M,to:et}:{from:Bt,to:et}}interpolate(M){return M}}class _s{constructor(M){this.specification=M}possiblyEvaluate(M,et,Bt,Wt){if(void 0!==M.value){if("constant"===M.expression.kind){const Nt=M.expression.evaluate(et,null,{},Bt,Wt);return this._calculate(Nt,Nt,Nt,et)}return this._calculate(M.expression.evaluate(new cs(Math.floor(et.zoom-1),et)),M.expression.evaluate(new cs(Math.floor(et.zoom),et)),M.expression.evaluate(new cs(Math.floor(et.zoom+1),et)),et)}}_calculate(M,et,Bt,Wt){return Wt.zoom>Wt.zoomHistory.lastIntegerZoom?{from:M,to:et}:{from:Bt,to:et}}interpolate(M){return M}}class Ss{constructor(M){this.specification=M}possiblyEvaluate(M,et,Bt,Wt){return!!M.expression.evaluate(et,null,{},Bt,Wt)}interpolate(){return!1}}class As{constructor(M){this.properties=M,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[];for(const et in M){const Bt=M[et];Bt.specification.overridable&&this.overridableProperties.push(et);const Wt=this.defaultPropertyValues[et]=new hs(Bt,void 0),Nt=this.defaultTransitionablePropertyValues[et]=new ps(Bt);this.defaultTransitioningPropertyValues[et]=Nt.untransitioned(),this.defaultPossiblyEvaluatedValues[et]=Wt.possiblyEvaluate({})}}}Ui("DataDrivenProperty",bs),Ui("DataConstantProperty",vs),Ui("CrossFadedDataDrivenProperty",ws),Ui("CrossFadedProperty",_s),Ui("ColorRampProperty",Ss);const lg="-transition";class Ms extends ct{constructor(M,et){if(super(),this.id=M.id,this.type=M.type,this._featureFilter={filter:()=>!0,needGeometry:!1},"custom"!==M.type&&(this.metadata=M.metadata,this.minzoom=M.minzoom,this.maxzoom=M.maxzoom,"background"!==M.type&&(this.source=M.source,this.sourceLayer=M["source-layer"],this.filter=M.filter),et.layout&&(this._unevaluatedLayout=new ms(et.layout)),et.paint)){this._transitionablePaint=new fs(et.paint);for(const et in M.paint)this.setPaintProperty(et,M.paint[et],{validate:!1});for(const et in M.layout)this.setLayoutProperty(et,M.layout[et],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new xs(et.paint)}}getCrossfadeParameters(){return this._crossfadeParameters}getLayoutProperty(M){return"visibility"===M?this.visibility:this._unevaluatedLayout.getValue(M)}setLayoutProperty(M,et,Bt={}){null!=et&&this._validate(eg,`layers.${this.id}.layout.${M}`,M,et,Bt)||("visibility"!==M?this._unevaluatedLayout.setValue(M,et):this.visibility=et)}getPaintProperty(M){return M.endsWith(lg)?this._transitionablePaint.getTransition(M.slice(0,-11)):this._transitionablePaint.getValue(M)}setPaintProperty(M,et,Bt={}){if(null!=et&&this._validate(tg,`layers.${this.id}.paint.${M}`,M,et,Bt))return!1;if(M.endsWith(lg))return this._transitionablePaint.setTransition(M.slice(0,-11),et||void 0),!1;{const Bt=this._transitionablePaint._values[M],Wt="cross-faded-data-driven"===Bt.property.specification["property-type"],Nt=Bt.value.isDataDriven(),$t=Bt.value;this._transitionablePaint.setValue(M,et),this._handleSpecialPaintPropertyUpdate(M);const Gr=this._transitionablePaint._values[M].value;return Gr.isDataDriven()||Nt||Wt||this._handleOverridablePaintPropertyUpdate(M,$t,Gr)}}_handleSpecialPaintPropertyUpdate(M){}_handleOverridablePaintPropertyUpdate(M,et,Bt){return!1}isHidden(M){return!!(this.minzoom&&M=this.maxzoom)||"none"===this.visibility}updateTransitions(M){this._transitioningPaint=this._transitionablePaint.transitioned(M,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(M,et){M.getCrossfadeParameters&&(this._crossfadeParameters=M.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(M,void 0,et)),this.paint=this._transitioningPaint.possiblyEvaluate(M,void 0,et)}serialize(){const M={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(M.layout=M.layout||{},M.layout.visibility=this.visibility),D(M,((M,et)=>!(void 0===M||"layout"===et&&!Object.keys(M).length||"paint"===et&&!Object.keys(M).length)))}_validate(M,et,Bt,Wt,Nt={}){return(!Nt||!1!==Nt.validate)&&Ri(this,M.call(Yh,{key:et,layerType:this.type,objectKey:Bt,value:Wt,styleSpec:Ka,style:{glyphs:!0,sprite:!0}}))}is3D(){return!1}isTileClipped(){return!1}hasOffscreenPass(){return!1}resize(){}isStateDependent(){for(const M in this.paint._values){const et=this.paint.get(M);if(et instanceof gs&&zn(et.property.specification)&&("source"===et.value.kind||"composite"===et.value.kind)&&et.value.isStateDependent)return!0}return!1}}const cg={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class zs{constructor(M,et){this._structArray=M,this._pos1=et*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}class Ps{constructor(){this.isTransferred=!1,this.capacity=-1,this.resize(0)}static serialize(M,et){return M._trim(),et&&(M.isTransferred=!0,et.push(M.arrayBuffer)),{length:M.length,arrayBuffer:M.arrayBuffer}}static deserialize(M){const et=Object.create(this.prototype);return et.arrayBuffer=M.arrayBuffer,et.length=M.length,et.capacity=M.arrayBuffer.byteLength/et.bytesPerElement,et._refreshViews(),et}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())}clear(){this.length=0}resize(M){this.reserve(M),this.length=M}reserve(M){if(M>this.capacity){this.capacity=Math.max(M,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const et=this.uint8;this._refreshViews(),et&&this.uint8.set(et)}}_refreshViews(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")}}function Cs(M,et=1){let Bt=0,Wt=0;return{members:M.map((M=>{const Nt=cg[M.type].BYTES_PER_ELEMENT,$t=Bt=Bs(Bt,Math.max(et,Nt)),Gr=M.components||1;return Wt=Math.max(Wt,Nt),Bt+=Nt*Gr,{name:M.name,type:M.type,components:Gr,offset:$t}})),size:Bs(Bt,Math.max(Wt,et)),alignment:et}}function Bs(M,et){return Math.ceil(M/et)*et}class Vs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(M,et){const Bt=this.length;return this.resize(Bt+1),this.emplace(Bt,M,et)}emplace(M,et,Bt){const Wt=2*M;return this.int16[Wt+0]=et,this.int16[Wt+1]=Bt,M}}Vs.prototype.bytesPerElement=4,Ui("StructArrayLayout2i4",Vs);class Es extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(M,et,Bt){const Wt=this.length;return this.resize(Wt+1),this.emplace(Wt,M,et,Bt)}emplace(M,et,Bt,Wt){const Nt=3*M;return this.int16[Nt+0]=et,this.int16[Nt+1]=Bt,this.int16[Nt+2]=Wt,M}}Es.prototype.bytesPerElement=6,Ui("StructArrayLayout3i6",Es);class Ts extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt){const Nt=this.length;return this.resize(Nt+1),this.emplace(Nt,M,et,Bt,Wt)}emplace(M,et,Bt,Wt,Nt){const $t=4*M;return this.int16[$t+0]=et,this.int16[$t+1]=Bt,this.int16[$t+2]=Wt,this.int16[$t+3]=Nt,M}}Ts.prototype.bytesPerElement=8,Ui("StructArrayLayout4i8",Ts);class Fs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt,$t){const Gr=this.length;return this.resize(Gr+1),this.emplace(Gr,M,et,Bt,Wt,Nt,$t)}emplace(M,et,Bt,Wt,Nt,$t,Gr){const mn=6*M;return this.int16[mn+0]=et,this.int16[mn+1]=Bt,this.int16[mn+2]=Wt,this.int16[mn+3]=Nt,this.int16[mn+4]=$t,this.int16[mn+5]=Gr,M}}Fs.prototype.bytesPerElement=12,Ui("StructArrayLayout2i4i12",Fs);class $s extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt,$t){const Gr=this.length;return this.resize(Gr+1),this.emplace(Gr,M,et,Bt,Wt,Nt,$t)}emplace(M,et,Bt,Wt,Nt,$t,Gr){const mn=4*M,Hn=8*M;return this.int16[mn+0]=et,this.int16[mn+1]=Bt,this.uint8[Hn+4]=Wt,this.uint8[Hn+5]=Nt,this.uint8[Hn+6]=$t,this.uint8[Hn+7]=Gr,M}}$s.prototype.bytesPerElement=8,Ui("StructArrayLayout2i4ub8",$s);class Ls extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(M,et){const Bt=this.length;return this.resize(Bt+1),this.emplace(Bt,M,et)}emplace(M,et,Bt){const Wt=2*M;return this.float32[Wt+0]=et,this.float32[Wt+1]=Bt,M}}Ls.prototype.bytesPerElement=8,Ui("StructArrayLayout2f8",Ls);class Ds extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so){const uo=this.length;return this.resize(uo+1),this.emplace(uo,M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so)}emplace(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo){const Io=10*M;return this.uint16[Io+0]=et,this.uint16[Io+1]=Bt,this.uint16[Io+2]=Wt,this.uint16[Io+3]=Nt,this.uint16[Io+4]=$t,this.uint16[Io+5]=Gr,this.uint16[Io+6]=mn,this.uint16[Io+7]=Hn,this.uint16[Io+8]=so,this.uint16[Io+9]=uo,M}}Ds.prototype.bytesPerElement=20,Ui("StructArrayLayout10ui20",Ds);class Os extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io){const Po=this.length;return this.resize(Po+1),this.emplace(Po,M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io)}emplace(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po){const To=12*M;return this.int16[To+0]=et,this.int16[To+1]=Bt,this.int16[To+2]=Wt,this.int16[To+3]=Nt,this.uint16[To+4]=$t,this.uint16[To+5]=Gr,this.uint16[To+6]=mn,this.uint16[To+7]=Hn,this.int16[To+8]=so,this.int16[To+9]=uo,this.int16[To+10]=Io,this.int16[To+11]=Po,M}}Os.prototype.bytesPerElement=24,Ui("StructArrayLayout4i4ui4i24",Os);class Rs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(M,et,Bt){const Wt=this.length;return this.resize(Wt+1),this.emplace(Wt,M,et,Bt)}emplace(M,et,Bt,Wt){const Nt=3*M;return this.float32[Nt+0]=et,this.float32[Nt+1]=Bt,this.float32[Nt+2]=Wt,M}}Rs.prototype.bytesPerElement=12,Ui("StructArrayLayout3f12",Rs);class js extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(M){const et=this.length;return this.resize(et+1),this.emplace(et,M)}emplace(M,et){return this.uint32[1*M+0]=et,M}}js.prototype.bytesPerElement=4,Ui("StructArrayLayout1ul4",js);class Ns extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn){const so=this.length;return this.resize(so+1),this.emplace(so,M,et,Bt,Wt,Nt,$t,Gr,mn,Hn)}emplace(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so){const uo=10*M,Io=5*M;return this.int16[uo+0]=et,this.int16[uo+1]=Bt,this.int16[uo+2]=Wt,this.int16[uo+3]=Nt,this.int16[uo+4]=$t,this.int16[uo+5]=Gr,this.uint32[Io+3]=mn,this.uint16[uo+8]=Hn,this.uint16[uo+9]=so,M}}Ns.prototype.bytesPerElement=20,Ui("StructArrayLayout6i1ul2ui20",Ns);class Us extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt,$t){const Gr=this.length;return this.resize(Gr+1),this.emplace(Gr,M,et,Bt,Wt,Nt,$t)}emplace(M,et,Bt,Wt,Nt,$t,Gr){const mn=6*M;return this.int16[mn+0]=et,this.int16[mn+1]=Bt,this.int16[mn+2]=Wt,this.int16[mn+3]=Nt,this.int16[mn+4]=$t,this.int16[mn+5]=Gr,M}}Us.prototype.bytesPerElement=12,Ui("StructArrayLayout2i2i2i12",Us);class qs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt){const $t=this.length;return this.resize($t+1),this.emplace($t,M,et,Bt,Wt,Nt)}emplace(M,et,Bt,Wt,Nt,$t){const Gr=4*M,mn=8*M;return this.float32[Gr+0]=et,this.float32[Gr+1]=Bt,this.float32[Gr+2]=Wt,this.int16[mn+6]=Nt,this.int16[mn+7]=$t,M}}qs.prototype.bytesPerElement=16,Ui("StructArrayLayout2f1f2i16",qs);class Gs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt,$t){const Gr=this.length;return this.resize(Gr+1),this.emplace(Gr,M,et,Bt,Wt,Nt,$t)}emplace(M,et,Bt,Wt,Nt,$t,Gr){const mn=16*M,Hn=4*M,so=8*M;return this.uint8[mn+0]=et,this.uint8[mn+1]=Bt,this.float32[Hn+1]=Wt,this.float32[Hn+2]=Nt,this.int16[so+6]=$t,this.int16[so+7]=Gr,M}}Gs.prototype.bytesPerElement=16,Ui("StructArrayLayout2ub2f2i16",Gs);class Zs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(M,et,Bt){const Wt=this.length;return this.resize(Wt+1),this.emplace(Wt,M,et,Bt)}emplace(M,et,Bt,Wt){const Nt=3*M;return this.uint16[Nt+0]=et,this.uint16[Nt+1]=Bt,this.uint16[Nt+2]=Wt,M}}Zs.prototype.bytesPerElement=6,Ui("StructArrayLayout3ui6",Zs);class Xs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba){const Ta=this.length;return this.resize(Ta+1),this.emplace(Ta,M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba)}emplace(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba,Ta){const Va=24*M,za=12*M,Fa=48*M;return this.int16[Va+0]=et,this.int16[Va+1]=Bt,this.uint16[Va+2]=Wt,this.uint16[Va+3]=Nt,this.uint32[za+2]=$t,this.uint32[za+3]=Gr,this.uint32[za+4]=mn,this.uint16[Va+10]=Hn,this.uint16[Va+11]=so,this.uint16[Va+12]=uo,this.float32[za+7]=Io,this.float32[za+8]=Po,this.uint8[Fa+36]=To,this.uint8[Fa+37]=Eo,this.uint8[Fa+38]=Ia,this.uint32[za+10]=Ba,this.int16[Va+22]=Ta,M}}Xs.prototype.bytesPerElement=48,Ui("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",Xs);class Ks extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba,Ta,Va,za,Fa,Ea,La,Da,Ka,Oa,$a,Al){const Sl=this.length;return this.resize(Sl+1),this.emplace(Sl,M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba,Ta,Va,za,Fa,Ea,La,Da,Ka,Oa,$a,Al)}emplace(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba,Ta,Va,za,Fa,Ea,La,Da,Ka,Oa,$a,Al,Sl){const Zl=32*M,Gl=16*M;return this.int16[Zl+0]=et,this.int16[Zl+1]=Bt,this.int16[Zl+2]=Wt,this.int16[Zl+3]=Nt,this.int16[Zl+4]=$t,this.int16[Zl+5]=Gr,this.int16[Zl+6]=mn,this.int16[Zl+7]=Hn,this.uint16[Zl+8]=so,this.uint16[Zl+9]=uo,this.uint16[Zl+10]=Io,this.uint16[Zl+11]=Po,this.uint16[Zl+12]=To,this.uint16[Zl+13]=Eo,this.uint16[Zl+14]=Ia,this.uint16[Zl+15]=Ba,this.uint16[Zl+16]=Ta,this.uint16[Zl+17]=Va,this.uint16[Zl+18]=za,this.uint16[Zl+19]=Fa,this.uint16[Zl+20]=Ea,this.uint16[Zl+21]=La,this.uint16[Zl+22]=Da,this.uint32[Gl+12]=Ka,this.float32[Gl+13]=Oa,this.float32[Gl+14]=$a,this.uint16[Zl+30]=Al,this.uint16[Zl+31]=Sl,M}}Ks.prototype.bytesPerElement=64,Ui("StructArrayLayout8i15ui1ul2f2ui64",Ks);class Hs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(M){const et=this.length;return this.resize(et+1),this.emplace(et,M)}emplace(M,et){return this.float32[1*M+0]=et,M}}Hs.prototype.bytesPerElement=4,Ui("StructArrayLayout1f4",Hs);class Ys extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(M,et,Bt){const Wt=this.length;return this.resize(Wt+1),this.emplace(Wt,M,et,Bt)}emplace(M,et,Bt,Wt){const Nt=3*M;return this.uint16[6*M+0]=et,this.float32[Nt+1]=Bt,this.float32[Nt+2]=Wt,M}}Ys.prototype.bytesPerElement=12,Ui("StructArrayLayout1ui2f12",Ys);class Js extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(M,et,Bt){const Wt=this.length;return this.resize(Wt+1),this.emplace(Wt,M,et,Bt)}emplace(M,et,Bt,Wt){const Nt=4*M;return this.uint32[2*M+0]=et,this.uint16[Nt+2]=Bt,this.uint16[Nt+3]=Wt,M}}Js.prototype.bytesPerElement=8,Ui("StructArrayLayout1ul2ui8",Js);class Ws extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(M,et){const Bt=this.length;return this.resize(Bt+1),this.emplace(Bt,M,et)}emplace(M,et,Bt){const Wt=2*M;return this.uint16[Wt+0]=et,this.uint16[Wt+1]=Bt,M}}Ws.prototype.bytesPerElement=4,Ui("StructArrayLayout2ui4",Ws);class Qs extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(M){const et=this.length;return this.resize(et+1),this.emplace(et,M)}emplace(M,et){return this.uint16[1*M+0]=et,M}}Qs.prototype.bytesPerElement=2,Ui("StructArrayLayout1ui2",Qs);class ta extends Ps{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(M,et,Bt,Wt){const Nt=this.length;return this.resize(Nt+1),this.emplace(Nt,M,et,Bt,Wt)}emplace(M,et,Bt,Wt,Nt){const $t=4*M;return this.float32[$t+0]=et,this.float32[$t+1]=Bt,this.float32[$t+2]=Wt,this.float32[$t+3]=Nt,M}}ta.prototype.bytesPerElement=16,Ui("StructArrayLayout4f16",ta);class ea extends zs{get anchorPointX(){return this._structArray.int16[this._pos2+0]}get anchorPointY(){return this._structArray.int16[this._pos2+1]}get x1(){return this._structArray.int16[this._pos2+2]}get y1(){return this._structArray.int16[this._pos2+3]}get x2(){return this._structArray.int16[this._pos2+4]}get y2(){return this._structArray.int16[this._pos2+5]}get featureIndex(){return this._structArray.uint32[this._pos4+3]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+8]}get bucketIndex(){return this._structArray.uint16[this._pos2+9]}get anchorPoint(){return new $t(this.anchorPointX,this.anchorPointY)}}ea.prototype.size=20;class ra extends Ns{get(M){return new ea(this,M)}}Ui("CollisionBoxArray",ra);class na extends zs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+2]}get numGlyphs(){return this._structArray.uint16[this._pos2+3]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+2]}get lineStartIndex(){return this._structArray.uint32[this._pos4+3]}get lineLength(){return this._structArray.uint32[this._pos4+4]}get segment(){return this._structArray.uint16[this._pos2+10]}get lowerSize(){return this._structArray.uint16[this._pos2+11]}get upperSize(){return this._structArray.uint16[this._pos2+12]}get lineOffsetX(){return this._structArray.float32[this._pos4+7]}get lineOffsetY(){return this._structArray.float32[this._pos4+8]}get writingMode(){return this._structArray.uint8[this._pos1+36]}get placedOrientation(){return this._structArray.uint8[this._pos1+37]}set placedOrientation(M){this._structArray.uint8[this._pos1+37]=M}get hidden(){return this._structArray.uint8[this._pos1+38]}set hidden(M){this._structArray.uint8[this._pos1+38]=M}get crossTileID(){return this._structArray.uint32[this._pos4+10]}set crossTileID(M){this._structArray.uint32[this._pos4+10]=M}get associatedIconIndex(){return this._structArray.int16[this._pos2+22]}}na.prototype.size=48;class ia extends Xs{get(M){return new na(this,M)}}Ui("PlacedSymbolArray",ia);class sa extends zs{get anchorX(){return this._structArray.int16[this._pos2+0]}get anchorY(){return this._structArray.int16[this._pos2+1]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+2]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+3]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+4]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+5]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+6]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+7]}get key(){return this._structArray.uint16[this._pos2+8]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+9]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+10]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+11]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+12]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+13]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+14]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+15]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+16]}get featureIndex(){return this._structArray.uint16[this._pos2+17]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+18]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+19]}get numIconVertices(){return this._structArray.uint16[this._pos2+20]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+21]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+22]}get crossTileID(){return this._structArray.uint32[this._pos4+12]}set crossTileID(M){this._structArray.uint32[this._pos4+12]=M}get textBoxScale(){return this._structArray.float32[this._pos4+13]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+14]}get textAnchorOffsetStartIndex(){return this._structArray.uint16[this._pos2+30]}get textAnchorOffsetEndIndex(){return this._structArray.uint16[this._pos2+31]}}sa.prototype.size=64;class aa extends Ks{get(M){return new sa(this,M)}}Ui("SymbolInstanceArray",aa);class oa extends Hs{getoffsetX(M){return this.float32[1*M+0]}}Ui("GlyphOffsetArray",oa);class la extends Es{getx(M){return this.int16[3*M+0]}gety(M){return this.int16[3*M+1]}gettileUnitDistanceFromAnchor(M){return this.int16[3*M+2]}}Ui("SymbolLineVertexArray",la);class ua extends zs{get textAnchor(){return this._structArray.uint16[this._pos2+0]}get textOffset0(){return this._structArray.float32[this._pos4+1]}get textOffset1(){return this._structArray.float32[this._pos4+2]}}ua.prototype.size=12;class ca extends Ys{get(M){return new ua(this,M)}}Ui("TextAnchorOffsetArray",ca);class ha extends zs{get featureIndex(){return this._structArray.uint32[this._pos4+0]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+2]}get bucketIndex(){return this._structArray.uint16[this._pos2+3]}}ha.prototype.size=8;class pa extends Js{get(M){return new ha(this,M)}}Ui("FeatureIndexArray",pa);class fa extends Vs{}class da extends Vs{}class ya extends Vs{}class ma extends Fs{}class ga extends $s{}class xa extends Ls{}class va extends Ds{}class ba extends Os{}class wa extends Rs{}class _a extends js{}class Sa extends Us{}class Aa extends Gs{}class ka extends Zs{}class Ma extends Ws{}const hg=Cs([{name:"a_pos",components:2,type:"Int16"}],4),{members:gg}=hg;class Pa{constructor(M=[]){this._forceNewSegmentOnNextPrepare=!1,this.segments=M}prepareSegment(M,et,Bt,Wt){const Nt=this.segments[this.segments.length-1];return M>Pa.MAX_VERTEX_ARRAY_LENGTH&&j(`Max vertices per segment is ${Pa.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${M}. Consider using the \`fillLargeMeshArrays\` function if you require meshes with more than ${Pa.MAX_VERTEX_ARRAY_LENGTH} vertices.`),this._forceNewSegmentOnNextPrepare||!Nt||Nt.vertexLength+M>Pa.MAX_VERTEX_ARRAY_LENGTH||Nt.sortKey!==Wt?this.createNewSegment(et,Bt,Wt):Nt}createNewSegment(M,et,Bt){const Wt={vertexOffset:M.length,primitiveOffset:et.length,vertexLength:0,primitiveLength:0,vaos:{}};return void 0!==Bt&&(Wt.sortKey=Bt),this._forceNewSegmentOnNextPrepare=!1,this.segments.push(Wt),Wt}getOrCreateLatestSegment(M,et,Bt){return this.prepareSegment(0,M,et,Bt)}forceNewSegmentOnNextPrepare(){this._forceNewSegmentOnNextPrepare=!0}get(){return this.segments}destroy(){for(const M of this.segments)for(const et in M.vaos)M.vaos[et].destroy()}static simpleSegment(M,et,Bt,Wt){return new Pa([{vertexOffset:M,primitiveOffset:et,vertexLength:Bt,primitiveLength:Wt,vaos:{},sortKey:0}])}}function Ca(M,et){return 256*(M=E(Math.floor(M),0,255))+E(Math.floor(et),0,255)}Pa.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Ui("SegmentVector",Pa);const ug=Cs([{name:"a_pattern_from",components:4,type:"Uint16"},{name:"a_pattern_to",components:4,type:"Uint16"},{name:"a_pixel_ratio_from",components:1,type:"Uint16"},{name:"a_pixel_ratio_to",components:1,type:"Uint16"}]);var dg,pg,mg,Cg={exports:{}},Ig={exports:{}},fg={exports:{}},yg=function(){if(mg)return Cg.exports;mg=1;var M=(dg||(dg=1,Ig.exports=function(M,et){var Bt,Wt,Nt,$t,Gr,mn,Hn,so;for(Wt=M.length-(Bt=3&M.length),Nt=et,Gr=3432918353,mn=461845907,so=0;so>>16)*Gr&65535)<<16)&4294967295)<<15|Hn>>>17))*mn+(((Hn>>>16)*mn&65535)<<16)&4294967295)<<13|Nt>>>19))+((5*(Nt>>>16)&65535)<<16)&4294967295))+((58964+($t>>>16)&65535)<<16);switch(Hn=0,Bt){case 3:Hn^=(255&M.charCodeAt(so+2))<<16;case 2:Hn^=(255&M.charCodeAt(so+1))<<8;case 1:Nt^=Hn=(65535&(Hn=(Hn=(65535&(Hn^=255&M.charCodeAt(so)))*Gr+(((Hn>>>16)*Gr&65535)<<16)&4294967295)<<15|Hn>>>17))*mn+(((Hn>>>16)*mn&65535)<<16)&4294967295}return Nt^=M.length,Nt=2246822507*(65535&(Nt^=Nt>>>16))+((2246822507*(Nt>>>16)&65535)<<16)&4294967295,Nt=3266489909*(65535&(Nt^=Nt>>>13))+((3266489909*(Nt>>>16)&65535)<<16)&4294967295,(Nt^=Nt>>>16)>>>0}),Ig.exports),et=(pg||(pg=1,fg.exports=function(M,et){for(var Bt,Wt=M.length,Nt=et^Wt,$t=0;Wt>=4;)Bt=1540483477*(65535&(Bt=255&M.charCodeAt($t)|(255&M.charCodeAt(++$t))<<8|(255&M.charCodeAt(++$t))<<16|(255&M.charCodeAt(++$t))<<24))+((1540483477*(Bt>>>16)&65535)<<16),Nt=1540483477*(65535&Nt)+((1540483477*(Nt>>>16)&65535)<<16)^(Bt=1540483477*(65535&(Bt^=Bt>>>24))+((1540483477*(Bt>>>16)&65535)<<16)),Wt-=4,++$t;switch(Wt){case 3:Nt^=(255&M.charCodeAt($t+2))<<16;case 2:Nt^=(255&M.charCodeAt($t+1))<<8;case 1:Nt=1540483477*(65535&(Nt^=255&M.charCodeAt($t)))+((1540483477*(Nt>>>16)&65535)<<16)}return Nt=1540483477*(65535&(Nt^=Nt>>>13))+((1540483477*(Nt>>>16)&65535)<<16),(Nt^=Nt>>>15)>>>0}),fg.exports);return Cg.exports=M,Cg.exports.murmur3=M,Cg.exports.murmur2=et,Cg.exports}(),Ag=r(yg);class Ra{constructor(){this.ids=[],this.positions=[],this.indexed=!1}add(M,et,Bt,Wt){this.ids.push(ja(M)),this.positions.push(et,Bt,Wt)}getPositions(M){if(!this.indexed)throw new Error("Trying to get index, but feature positions are not indexed");const et=ja(M);let Bt=0,Wt=this.ids.length-1;for(;Bt>1;this.ids[M]>=et?Wt=M:Bt=M+1}const Nt=[];for(;this.ids[Bt]===et;)Nt.push({index:this.positions[3*Bt],start:this.positions[3*Bt+1],end:this.positions[3*Bt+2]}),Bt++;return Nt}static serialize(M,et){const Bt=new Float64Array(M.ids),Wt=new Uint32Array(M.positions);return Na(Bt,Wt,0,Bt.length-1),et&&et.push(Bt.buffer,Wt.buffer),{ids:Bt,positions:Wt}}static deserialize(M){const et=new Ra;return et.ids=M.ids,et.positions=M.positions,et.indexed=!0,et}}function ja(M){const et=+M;return!isNaN(et)&&et<=Number.MAX_SAFE_INTEGER?et:Ag(String(M))}function Na(M,et,Bt,Wt){for(;Bt>1];let $t=Bt-1,Gr=Wt+1;for(;;){do{$t++}while(M[$t]Nt);if($t>=Gr)break;Ua(M,$t,Gr),Ua(et,3*$t,3*Gr),Ua(et,3*$t+1,3*Gr+1),Ua(et,3*$t+2,3*Gr+2)}Gr-Bt`u_${M}`)),this.type=Bt}setUniform(M,et,Bt){M.set(Bt.constantOr(this.value))}getBinding(M,et,Bt){return"color"===this.type?new Xa(M,et):new Ga(M,et)}}class Ja{constructor(M,et){this.uniformNames=et.map((M=>`u_${M}`)),this.patternFrom=null,this.patternTo=null,this.pixelRatioFrom=1,this.pixelRatioTo=1}setConstantPatternPositions(M,et){this.pixelRatioFrom=et.pixelRatio,this.pixelRatioTo=M.pixelRatio,this.patternFrom=et.tlbr,this.patternTo=M.tlbr}setUniform(M,et,Bt,Wt){const Nt="u_pattern_to"===Wt?this.patternTo:"u_pattern_from"===Wt?this.patternFrom:"u_pixel_ratio_to"===Wt?this.pixelRatioTo:"u_pixel_ratio_from"===Wt?this.pixelRatioFrom:null;Nt&&M.set(Nt)}getBinding(M,et,Bt){return"u_pattern"===Bt.substr(0,9)?new Za(M,et):new Ga(M,et)}}class Wa{constructor(M,et,Bt,Wt){this.expression=M,this.type=Bt,this.maxValue=0,this.paintVertexAttributes=et.map((M=>({name:`a_${M}`,type:"Float32",components:"color"===Bt?2:1,offset:0}))),this.paintVertexArray=new Wt}populatePaintArray(M,et,Bt,Wt,Nt){const $t=this.paintVertexArray.length,Gr=this.expression.evaluate(new cs(0),et,{},Wt,[],Nt);this.paintVertexArray.resize(M),this._setPaintValue($t,M,Gr)}updatePaintArray(M,et,Bt,Wt){const Nt=this.expression.evaluate({zoom:0},Bt,Wt);this._setPaintValue(M,et,Nt)}_setPaintValue(M,et,Bt){if("color"===this.type){const Wt=Ha(Bt);for(let Bt=M;Bt`u_${M}_t`)),this.type=Bt,this.useIntegerZoom=Wt,this.zoom=Nt,this.maxValue=0,this.paintVertexAttributes=et.map((M=>({name:`a_${M}`,type:"Float32",components:"color"===Bt?4:2,offset:0}))),this.paintVertexArray=new $t}populatePaintArray(M,et,Bt,Wt,Nt){const $t=this.expression.evaluate(new cs(this.zoom),et,{},Wt,[],Nt),Gr=this.expression.evaluate(new cs(this.zoom+1),et,{},Wt,[],Nt),mn=this.paintVertexArray.length;this.paintVertexArray.resize(M),this._setPaintValue(mn,M,$t,Gr)}updatePaintArray(M,et,Bt,Wt){const Nt=this.expression.evaluate({zoom:this.zoom},Bt,Wt),$t=this.expression.evaluate({zoom:this.zoom+1},Bt,Wt);this._setPaintValue(M,et,Nt,$t)}_setPaintValue(M,et,Bt,Wt){if("color"===this.type){const Nt=Ha(Bt),$t=Ha(Wt);for(let Bt=M;Bt`#define HAS_UNIFORM_${M}`)))}return M}getBinderAttributes(){const M=[];for(const et in this.binders){const Bt=this.binders[et];if(Bt instanceof Wa||Bt instanceof Qa)for(let et=0;et!0){this.programConfigurations={};for(const Wt of M)this.programConfigurations[Wt.id]=new eo(Wt,et,Bt);this.needsUpload=!1,this._featureMap=new Ra,this._bufferOffset=0}populatePaintArrays(M,et,Bt,Wt,Nt,$t){for(const Bt in this.programConfigurations)this.programConfigurations[Bt].populatePaintArrays(M,et,Wt,Nt,$t);void 0!==et.id&&this._featureMap.add(et.id,Bt,this._bufferOffset,M),this._bufferOffset=M,this.needsUpload=!0}updatePaintArrays(M,et,Bt,Wt){for(const Nt of Bt)this.needsUpload=this.programConfigurations[Nt.id].updatePaintArrays(M,this._featureMap,et,Nt,Wt)||this.needsUpload}get(M){return this.programConfigurations[M]}upload(M){if(this.needsUpload){for(const et in this.programConfigurations)this.programConfigurations[et].upload(M);this.needsUpload=!1}}destroy(){for(const M in this.programConfigurations)this.programConfigurations[M].destroy()}}function no(M,et){return{"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"line-gap-width":["gapwidth"],"line-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"],"fill-extrusion-pattern":["pattern_to","pattern_from","pixel_ratio_to","pixel_ratio_from"]}[M]||[M.replace(`${et}-`,"").replace(/-/g,"_")]}function io(M,et,Bt){const Wt={color:{source:Ls,composite:ta},number:{source:Hs,composite:Ls}},Nt=function(M){return{"line-pattern":{source:va,composite:va},"fill-pattern":{source:va,composite:va},"fill-extrusion-pattern":{source:va,composite:va}}[M]}(M);return Nt&&Nt[Bt]||Wt[et][Bt]}Ui("ConstantBinder",Ya),Ui("CrossFadedConstantBinder",Ja),Ui("SourceExpressionBinder",Wa),Ui("CrossFadedCompositeBinder",to),Ui("CompositeExpressionBinder",Qa),Ui("ProgramConfiguration",eo,{omit:["_buffers"]}),Ui("ProgramConfigurationSet",ro);const bg=Math.pow(2,14)-1,vg=-bg-1;function oo(M){const et=To/M.extent,Bt=M.loadGeometry();for(let M=0;MBt.x+1||$tBt.y+1)&&j("Geometry exceeds allowed extent, reduce your vector tile buffer size")}}return Bt}function lo(M,et){return{type:M.type,id:M.id,properties:M.properties,geometry:et?oo(M):[]}}const xg=-32768;function co(M,et,Bt,Wt,Nt){M.emplaceBack(xg+8*et+Wt,xg+8*Bt+Nt)}class ho{constructor(M){this.zoom=M.zoom,this.overscaling=M.overscaling,this.layers=M.layers,this.layerIds=this.layers.map((M=>M.id)),this.index=M.index,this.hasPattern=!1,this.layoutVertexArray=new da,this.indexArray=new ka,this.segments=new Pa,this.programConfigurations=new ro(M.layers,M.zoom),this.stateDependentLayerIds=this.layers.filter((M=>M.isStateDependent())).map((M=>M.id))}populate(M,et,Bt){const Wt=this.layers[0],Nt=[];let $t=null,Gr=!1,mn="heatmap"===Wt.type;if("circle"===Wt.type){const M=Wt;$t=M.layout.get("circle-sort-key"),Gr=!$t.isConstant(),mn=mn||"map"===M.paint.get("circle-pitch-alignment")}const Hn=mn?et.subdivisionGranularity.circle:1;for(const{feature:et,id:Wt,index:mn,sourceLayerIndex:Hn}of M){const M=this.layers[0]._featureFilter.needGeometry,so=lo(et,M);if(!this.layers[0]._featureFilter.filter(new cs(this.zoom),so,Bt))continue;const uo=Gr?$t.evaluate(so,{},Bt):void 0,Io={id:Wt,properties:et.properties,type:et.type,sourceLayerIndex:Hn,index:mn,geometry:M?so.geometry:oo(et),patterns:{},sortKey:uo};Nt.push(Io)}Gr&&Nt.sort(((M,et)=>M.sortKey-et.sortKey));for(const Wt of Nt){const{geometry:Nt,index:$t,sourceLayerIndex:Gr}=Wt,mn=M[$t].feature;this.addFeature(Wt,Nt,$t,Bt,Hn),et.featureIndex.insert(mn,Nt,$t,Gr,this.index)}}update(M,et,Bt){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(M,et,this.stateDependentLayers,Bt)}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(M){this.uploaded||(this.layoutVertexBuffer=M.createVertexBuffer(this.layoutVertexArray,gg),this.indexBuffer=M.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(M),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}addFeature(M,et,Bt,Wt,Nt=1){let $t;switch(Nt){case 1:$t=[0,7];break;case 3:$t=[0,2,5,7];break;case 5:$t=[0,1,3,4,6,7];break;case 7:$t=[0,1,2,3,4,5,6,7];break;default:throw new Error(`Invalid circle bucket granularity: ${Nt}; valid values are 1, 3, 5, 7.`)}const Gr=$t.length;for(const Bt of et)for(const et of Bt){const Bt=et.x,Wt=et.y;if(Bt<0||Bt>=To||Wt<0||Wt>=To)continue;const Nt=this.segments.prepareSegment(Gr*Gr,this.layoutVertexArray,this.indexArray,M.sortKey),mn=Nt.vertexLength;for(let M=0;M1){if(go(M,et))return!0;for(let Wt=0;Wt1?Bt:Bt.sub(et)._mult(Nt)._add(et))}function wo(M,et){let Bt,Wt,Nt,$t=!1;for(let Gr=0;Gret.y!=Nt.y>et.y&&et.x<(Nt.x-Wt.x)*(et.y-Wt.y)/(Nt.y-Wt.y)+Wt.x&&($t=!$t)}return $t}function _o(M,et){let Bt=!1;for(let Wt=0,Nt=M.length-1;Wtet.y!=Gr.y>et.y&&et.x<(Gr.x-$t.x)*(et.y-$t.y)/(Gr.y-$t.y)+$t.x&&(Bt=!Bt)}return Bt}function So(M,et,Bt){const Wt=Bt[0],Nt=Bt[2];if(M.xNt.x&&et.x>Nt.x||M.yNt.y&&et.y>Nt.y)return!1;const $t=N(M,et,Bt[0]);return $t!==N(M,et,Bt[1])||$t!==N(M,et,Bt[2])||$t!==N(M,et,Bt[3])}function Ao(M,et,Bt){const Wt=et.paint.get(M).value;return"constant"===Wt.kind?Wt.value:Bt.programConfigurations.get(et.id).getMaxValue(M)}function ko(M){return Math.sqrt(M[0]*M[0]+M[1]*M[1])}function Mo(M,et,Bt,Wt,Nt){if(!et[0]&&!et[1])return M;const Gr=$t.convert(et)._mult(Nt);"viewport"===Bt&&Gr._rotate(-Wt);const mn=[];for(let et=0;etBo(M,et)))}(mn,Gr),Io=so?Hn*$t:Hn;for(const M of Wt)for(const et of M){const M=so?et:Bo(et,Gr);let Bt=Io;const Wt=_([],[et.x,et.y,0,1],Gr);if("viewport"===this.paint.get("circle-pitch-scale")&&"map"===this.paint.get("circle-pitch-alignment")?Bt*=Wt[3]/Nt.cameraToCenterDistance:"map"===this.paint.get("circle-pitch-scale")&&"viewport"===this.paint.get("circle-pitch-alignment")&&(Bt*=Nt.cameraToCenterDistance/Wt[3]),fo(uo,M,Bt))return!0}return!1}}function Bo(M,et){const Bt=_([],[M.x,M.y,0,1],et);return new $t(Bt[0]/Bt[3],Bt[1]/Bt[3])}class Vo extends ho{}let Bg;Ui("HeatmapBucket",Vo,{omit:["layers"]});var Zg={get paint(){return Bg=Bg||new As({"heatmap-radius":new bs(Ka.paint_heatmap["heatmap-radius"]),"heatmap-weight":new bs(Ka.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new vs(Ka.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Ss(Ka.paint_heatmap["heatmap-color"]),"heatmap-opacity":new vs(Ka.paint_heatmap["heatmap-opacity"])})}};function Fo(M,{width:et,height:Bt},Wt,Nt){if(Nt){if(Nt instanceof Uint8ClampedArray)Nt=new Uint8Array(Nt.buffer);else if(Nt.length!==et*Bt*Wt)throw new RangeError(`mismatched image size. expected: ${Nt.length} but got: ${et*Bt*Wt}`)}else Nt=new Uint8Array(et*Bt*Wt);return M.width=et,M.height=Bt,M.data=Nt,M}function $o(M,{width:et,height:Bt},Wt){if(et===M.width&&Bt===M.height)return;const Nt=Fo({},{width:et,height:Bt},Wt);Lo(M,Nt,{x:0,y:0},{x:0,y:0},{width:Math.min(M.width,et),height:Math.min(M.height,Bt)},Wt),M.width=et,M.height=Bt,M.data=Nt.data}function Lo(M,et,Bt,Wt,Nt,$t){if(0===Nt.width||0===Nt.height)return et;if(Nt.width>M.width||Nt.height>M.height||Bt.x>M.width-Nt.width||Bt.y>M.height-Nt.height)throw new RangeError("out of range source coordinates for image copy");if(Nt.width>et.width||Nt.height>et.height||Wt.x>et.width-Nt.width||Wt.y>et.height-Nt.height)throw new RangeError("out of range destination coordinates for image copy");const Gr=M.data,mn=et.data;if(Gr===mn)throw new Error("srcData equals dstData, so image is already copied");for(let Hn=0;Hn{et[M.evaluationKey]=$t;const Gr=M.expression.evaluate(et);Nt.data[Bt+Wt+0]=Math.floor(255*Gr.r/Gr.a),Nt.data[Bt+Wt+1]=Math.floor(255*Gr.g/Gr.a),Nt.data[Bt+Wt+2]=Math.floor(255*Gr.b/Gr.a),Nt.data[Bt+Wt+3]=Math.floor(255*Gr.a)};if(M.clips)for(let et=0,Nt=0;et0)for(let Nt=et;Nt=et;Nt-=Wt)$t=xl(Nt/Wt|0,M[Nt],M[Nt+1],$t);return $t&&pl($t,$t.next)&&(vl($t),$t=$t.next),$t}function Jo(M,et){if(!M)return M;et||(et=M);let Bt,Wt=M;do{if(Bt=!1,Wt.steiner||!pl(Wt,Wt.next)&&0!==hl(Wt.prev,Wt,Wt.next))Wt=Wt.next;else{if(vl(Wt),Wt=et=Wt.prev,Wt===Wt.next)break;Bt=!0}}while(Bt||Wt!==et);return et}function Wo(M,et,Bt,Wt,Nt,$t,Gr){if(!M)return;!Gr&&$t&&function(M,et,Bt,Wt){let Nt=M;do{0===Nt.z&&(Nt.z=al(Nt.x,Nt.y,et,Bt,Wt)),Nt.prevZ=Nt.prev,Nt.nextZ=Nt.next,Nt=Nt.next}while(Nt!==M);Nt.prevZ.nextZ=null,Nt.prevZ=null,function(M){let et,Bt=1;do{let Wt,Nt=M;M=null;let $t=null;for(et=0;Nt;){et++;let Gr=Nt,mn=0;for(let M=0;M0||Hn>0&&Gr;)0!==mn&&(0===Hn||!Gr||Nt.z<=Gr.z)?(Wt=Nt,Nt=Nt.nextZ,mn--):(Wt=Gr,Gr=Gr.nextZ,Hn--),$t?$t.nextZ=Wt:M=Wt,Wt.prevZ=$t,$t=Wt;Nt=Gr}$t.nextZ=null,Bt*=2}while(et>1)}(Nt)}(M,Wt,Nt,$t);let mn=M;for(;M.prev!==M.next;){const Hn=M.prev,so=M.next;if($t?tl(M,Wt,Nt,$t):Qo(M))et.push(Hn.i,M.i,so.i),vl(M),M=so.next,mn=so.next;else if((M=so)===mn){Gr?1===Gr?Wo(M=el(Jo(M),et),et,Bt,Wt,Nt,$t,2):2===Gr&&rl(M,et,Bt,Wt,Nt,$t):Wo(Jo(M),et,Bt,Wt,Nt,$t,1);break}}}function Qo(M){const et=M.prev,Bt=M,Wt=M.next;if(hl(et,Bt,Wt)>=0)return!1;const Nt=et.x,$t=Bt.x,Gr=Wt.x,mn=et.y,Hn=Bt.y,so=Wt.y,uo=Math.min(Nt,$t,Gr),Io=Math.min(mn,Hn,so),Po=Math.max(Nt,$t,Gr),To=Math.max(mn,Hn,so);let Eo=Wt.next;for(;Eo!==et;){if(Eo.x>=uo&&Eo.x<=Po&&Eo.y>=Io&&Eo.y<=To&&ul(Nt,mn,$t,Hn,Gr,so,Eo.x,Eo.y)&&hl(Eo.prev,Eo,Eo.next)>=0)return!1;Eo=Eo.next}return!0}function tl(M,et,Bt,Wt){const Nt=M.prev,$t=M,Gr=M.next;if(hl(Nt,$t,Gr)>=0)return!1;const mn=Nt.x,Hn=$t.x,so=Gr.x,uo=Nt.y,Io=$t.y,Po=Gr.y,To=Math.min(mn,Hn,so),Eo=Math.min(uo,Io,Po),Ia=Math.max(mn,Hn,so),Ba=Math.max(uo,Io,Po),Ta=al(To,Eo,et,Bt,Wt),Va=al(Ia,Ba,et,Bt,Wt);let za=M.prevZ,Fa=M.nextZ;for(;za&&za.z>=Ta&&Fa&&Fa.z<=Va;){if(za.x>=To&&za.x<=Ia&&za.y>=Eo&&za.y<=Ba&&za!==Nt&&za!==Gr&&ul(mn,uo,Hn,Io,so,Po,za.x,za.y)&&hl(za.prev,za,za.next)>=0)return!1;if(za=za.prevZ,Fa.x>=To&&Fa.x<=Ia&&Fa.y>=Eo&&Fa.y<=Ba&&Fa!==Nt&&Fa!==Gr&&ul(mn,uo,Hn,Io,so,Po,Fa.x,Fa.y)&&hl(Fa.prev,Fa,Fa.next)>=0)return!1;Fa=Fa.nextZ}for(;za&&za.z>=Ta;){if(za.x>=To&&za.x<=Ia&&za.y>=Eo&&za.y<=Ba&&za!==Nt&&za!==Gr&&ul(mn,uo,Hn,Io,so,Po,za.x,za.y)&&hl(za.prev,za,za.next)>=0)return!1;za=za.prevZ}for(;Fa&&Fa.z<=Va;){if(Fa.x>=To&&Fa.x<=Ia&&Fa.y>=Eo&&Fa.y<=Ba&&Fa!==Nt&&Fa!==Gr&&ul(mn,uo,Hn,Io,so,Po,Fa.x,Fa.y)&&hl(Fa.prev,Fa,Fa.next)>=0)return!1;Fa=Fa.nextZ}return!0}function el(M,et){let Bt=M;do{const Wt=Bt.prev,Nt=Bt.next.next;!pl(Wt,Nt)&&fl(Wt,Bt,Bt.next,Nt)&&ml(Wt,Nt)&&ml(Nt,Wt)&&(et.push(Wt.i,Bt.i,Nt.i),vl(Bt),vl(Bt.next),Bt=M=Nt),Bt=Bt.next}while(Bt!==M);return Jo(Bt)}function rl(M,et,Bt,Wt,Nt,$t){let Gr=M;do{let M=Gr.next.next;for(;M!==Gr.prev;){if(Gr.i!==M.i&&cl(Gr,M)){let mn=gl(Gr,M);return Gr=Jo(Gr,Gr.next),mn=Jo(mn,mn.next),Wo(Gr,et,Bt,Wt,Nt,$t,0),void Wo(mn,et,Bt,Wt,Nt,$t,0)}M=M.next}Gr=Gr.next}while(Gr!==M)}function nl(M,et){let Bt=M.x-et.x;return 0===Bt&&(Bt=M.y-et.y,0===Bt)&&(Bt=(M.next.y-M.y)/(M.next.x-M.x)-(et.next.y-et.y)/(et.next.x-et.x)),Bt}function il(M,et){const Bt=function(M,et){let Bt=et;const Wt=M.x,Nt=M.y;let $t,Gr=-1/0;if(pl(M,Bt))return Bt;do{if(pl(M,Bt.next))return Bt.next;if(Nt<=Bt.y&&Nt>=Bt.next.y&&Bt.next.y!==Bt.y){const M=Bt.x+(Nt-Bt.y)*(Bt.next.x-Bt.x)/(Bt.next.y-Bt.y);if(M<=Wt&&M>Gr&&(Gr=M,$t=Bt.x=Bt.x&&Bt.x>=Hn&&Wt!==Bt.x&&ll(Nt$t.x||Bt.x===$t.x&&sl($t,Bt)))&&($t=Bt,uo=et)}Bt=Bt.next}while(Bt!==mn);return $t}(M,et);if(!Bt)return et;const Wt=gl(Bt,M);return Jo(Wt,Wt.next),Jo(Bt,Bt.next)}function sl(M,et){return hl(M.prev,M,et.prev)<0&&hl(et.next,M,M.next)<0}function al(M,et,Bt,Wt,Nt){return(M=1431655765&((M=858993459&((M=252645135&((M=16711935&((M=(M-Bt)*Nt|0)|M<<8))|M<<4))|M<<2))|M<<1))|(et=1431655765&((et=858993459&((et=252645135&((et=16711935&((et=(et-Wt)*Nt|0)|et<<8))|et<<4))|et<<2))|et<<1))<<1}function ol(M){let et=M,Bt=M;do{(et.x=(M-Gr)*($t-mn)&&(M-Gr)*(Wt-mn)>=(Bt-Gr)*(et-mn)&&(Bt-Gr)*($t-mn)>=(Nt-Gr)*(Wt-mn)}function ul(M,et,Bt,Wt,Nt,$t,Gr,mn){return!(M===Gr&&et===mn)&&ll(M,et,Bt,Wt,Nt,$t,Gr,mn)}function cl(M,et){return M.next.i!==et.i&&M.prev.i!==et.i&&!function(M,et){let Bt=M;do{if(Bt.i!==M.i&&Bt.next.i!==M.i&&Bt.i!==et.i&&Bt.next.i!==et.i&&fl(Bt,Bt.next,M,et))return!0;Bt=Bt.next}while(Bt!==M);return!1}(M,et)&&(ml(M,et)&&ml(et,M)&&function(M,et){let Bt=M,Wt=!1;const Nt=(M.x+et.x)/2,$t=(M.y+et.y)/2;do{Bt.y>$t!=Bt.next.y>$t&&Bt.next.y!==Bt.y&&Nt<(Bt.next.x-Bt.x)*($t-Bt.y)/(Bt.next.y-Bt.y)+Bt.x&&(Wt=!Wt),Bt=Bt.next}while(Bt!==M);return Wt}(M,et)&&(hl(M.prev,M,et.prev)||hl(M,et.prev,et))||pl(M,et)&&hl(M.prev,M,M.next)>0&&hl(et.prev,et,et.next)>0)}function hl(M,et,Bt){return(et.y-M.y)*(Bt.x-et.x)-(et.x-M.x)*(Bt.y-et.y)}function pl(M,et){return M.x===et.x&&M.y===et.y}function fl(M,et,Bt,Wt){const Nt=yl(hl(M,et,Bt)),$t=yl(hl(M,et,Wt)),Gr=yl(hl(Bt,Wt,M)),mn=yl(hl(Bt,Wt,et));return Nt!==$t&&Gr!==mn||!(0!==Nt||!dl(M,Bt,et))||!(0!==$t||!dl(M,Wt,et))||!(0!==Gr||!dl(Bt,M,Wt))||!(0!==mn||!dl(Bt,et,Wt))}function dl(M,et,Bt){return et.x<=Math.max(M.x,Bt.x)&&et.x>=Math.min(M.x,Bt.x)&&et.y<=Math.max(M.y,Bt.y)&&et.y>=Math.min(M.y,Bt.y)}function yl(M){return M>0?1:M<0?-1:0}function ml(M,et){return hl(M.prev,M,M.next)<0?hl(M,et,M.next)>=0&&hl(M,M.prev,et)>=0:hl(M,et,M.prev)<0||hl(M,M.next,et)<0}function gl(M,et){const Bt=bl(M.i,M.x,M.y),Wt=bl(et.i,et.x,et.y),Nt=M.next,$t=et.prev;return M.next=et,et.prev=M,Bt.next=Nt,Nt.prev=Bt,Wt.next=Bt,Bt.prev=Wt,$t.next=Wt,Wt.prev=$t,Wt}function xl(M,et,Bt,Wt){const Nt=bl(M,et,Bt);return Wt?(Nt.next=Wt.next,Nt.prev=Wt,Wt.next.prev=Nt,Wt.next=Nt):(Nt.prev=Nt,Nt.next=Nt),Nt}function vl(M){M.next.prev=M.prev,M.prev.next=M.next,M.prevZ&&(M.prevZ.nextZ=M.nextZ),M.nextZ&&(M.nextZ.prevZ=M.prevZ)}function bl(M,et,Bt){return{i:M,x:et,y:Bt,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}class wl{constructor(M,et){if(et>M)throw new Error("Min granularity must not be greater than base granularity.");this._baseZoomGranularity=M,this._minGranularity=et}getGranularityForZoomLevel(M){return Math.max(Math.floor(this._baseZoomGranularity/(1<32767||et>32767)throw new Error("Vertex coordinates are out of signed 16 bit integer range.");const Bt=0|Math.round(M),Wt=0|Math.round(et),Nt=this._getKey(Bt,Wt);if(this._vertexDictionary.has(Nt))return this._vertexDictionary.get(Nt);const $t=this._vertexBuffer.length/2;return this._vertexDictionary.set(Nt,$t),this._vertexBuffer.push(Bt,Wt),$t}_subdivideTrianglesScanline(M){if(this._granularity<2)return function(M,et){const Bt=[];for(let Wt=0;Wt0?(Bt.push(Nt),Bt.push(Gr),Bt.push($t)):(Bt.push(Nt),Bt.push($t),Bt.push(Gr))}return Bt}(this._vertexBuffer,M);const et=[],Bt=M.length;for(let Wt=0;Wt=1||za<=0)||Ia&&(mnNt)){so>=Wt&&so<=Nt&&$t.push(Bt[(M+1)%3]);continue}!Ia&&Va>0&&$t.push(this._vertexToIndex(Gr+Po*Va,mn+To*Va));const Fa=Gr+Po*Math.max(Va,0),Ea=Gr+Po*Math.min(za,1);Eo||this._generateIntraEdgeVertices($t,Gr,mn,Hn,so,Fa,Ea),!Ia&&za<1&&$t.push(this._vertexToIndex(Gr+Po*za,mn+To*za)),(Ia||so>=Wt&&so<=Nt)&&$t.push(Bt[(M+1)%3]),!Ia&&(so<=Wt||so>=Nt)&&this._generateInterEdgeVertices($t,Gr,mn,Hn,so,uo,Io,Ea,Wt,Nt)}return $t}_generateIntraEdgeVertices(M,et,Bt,Wt,Nt,$t,Gr){const mn=Wt-et,Hn=Nt-Bt,so=0===Hn,uo=so?Math.min(et,Wt):Math.min($t,Gr),Io=so?Math.max(et,Wt):Math.max($t,Gr),Po=Math.floor(uo/this._granularityCellSize)+1,To=Math.ceil(Io/this._granularityCellSize)-1;if(so?et=Po;Wt--){const Nt=Wt*this._granularityCellSize;M.push(this._vertexToIndex(Nt,Bt+Hn*(Nt-et)/mn))}}_generateInterEdgeVertices(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so){const uo=Nt-Bt,Io=$t-Wt,Po=Gr-Nt,To=(Hn-Nt)/Po,Eo=(so-Nt)/Po,Ia=Math.min(To,Eo),Ba=Math.max(To,Eo),Ta=Wt+Io*Ia;let Va=Math.floor(Math.min(Ta,mn)/this._granularityCellSize)+1,za=Math.ceil(Math.max(Ta,mn)/this._granularityCellSize)-1,Fa=mn=1||Ba<=0){const M=Bt-Gr,Wt=$t+(et-$t)*Math.min((Hn-Gr)/M,(so-Gr)/M);Va=Math.floor(Math.min(Wt,mn)/this._granularityCellSize)+1,za=Math.ceil(Math.max(Wt,mn)/this._granularityCellSize)-1,Fa=mn0?so:Hn;if(Fa)for(let et=Va;et<=za;et++)M.push(this._vertexToIndex(et*this._granularityCellSize,La));else for(let et=za;et>=Va;et--)M.push(this._vertexToIndex(et*this._granularityCellSize,La))}_generateOutline(M){const et=[];for(const Bt of M){const M=Il(Bt,this._granularity,!0),Wt=this._pointArrayToIndices(M),Nt=[];for(let M=1;MNt!=($t===Vg)?(M.push(et),M.push(Bt),M.push(this._vertexToIndex(Wt,$t)),M.push(Bt),M.push(this._vertexToIndex(Nt,$t)),M.push(this._vertexToIndex(Wt,$t))):(M.push(Bt),M.push(et),M.push(this._vertexToIndex(Wt,$t)),M.push(this._vertexToIndex(Nt,$t)),M.push(Bt),M.push(this._vertexToIndex(Wt,$t)))}_fillPoles(M,et,Bt){const Wt=this._vertexBuffer,Nt=To,$t=M.length;for(let Gr=2;Gr<$t;Gr+=3){const $t=M[Gr-2],mn=M[Gr-1],Hn=M[Gr],so=Wt[2*$t],uo=Wt[2*$t+1],Io=Wt[2*mn],Po=Wt[2*mn+1],To=Wt[2*Hn],Eo=Wt[2*Hn+1];et&&(0===uo&&0===Po&&this._generatePoleQuad(M,$t,mn,so,Io,Vg),0===Po&&0===Eo&&this._generatePoleQuad(M,mn,Hn,Io,To,Vg),0===Eo&&0===uo&&this._generatePoleQuad(M,Hn,$t,To,so,Vg)),Bt&&(uo===Nt&&Po===Nt&&this._generatePoleQuad(M,$t,mn,so,Io,Wg),Po===Nt&&Eo===Nt&&this._generatePoleQuad(M,mn,Hn,Io,To,Wg),Eo===Nt&&uo===Nt&&this._generatePoleQuad(M,Hn,$t,To,so,Wg))}}_initializeVertices(M){for(let et=0;et80*Bt){mn=1/0,Hn=1/0;let et=-1/0,Wt=-1/0;for(let $t=Bt;$tet&&(et=Bt),Nt>Wt&&(Wt=Nt)}so=Math.max(et-mn,Wt-Hn),so=0!==so?32767/so:0}return Wo($t,Gr,Bt,mn,Hn,so,0),Gr}(Bt,Wt),et=this._convertIndices(Bt,M);Nt=this._subdivideTrianglesScanline(et)}catch(M){console.error(M)}let $t=[];return et&&($t=this._generateOutline(M)),this._ensureNoPoleVertices(),this._handlePoles(Nt),{verticesFlattened:this._vertexBuffer,indicesTriangles:Nt,indicesLineList:$t}}_convertIndices(M,et){const Bt=[];for(let Wt=0;Wt0?(Math.floor(Va/mn)+1)*mn:(Math.ceil(Va/mn)-1)*mn,et=Ia>0?(Math.floor(za/mn)+1)*mn:(Math.ceil(za/mn)-1)*mn,Bt=Math.abs(Va-M),Wt=Math.abs(za-et),Nt=Math.abs(Va-uo),Gr=Math.abs(za-Io),so=Po?Bt/Ba:Number.POSITIVE_INFINITY,Fa=To?Wt/Ta:Number.POSITIVE_INFINITY;if((Nt<=Bt||!Po)&&(Gr<=Wt||!To))break;if(so=0?Gr-1:$t-1,Nt=(mn+1)%$t,Hn=M[2*et[Wt]],so=M[2*et[Nt]],uo=M[2*et[Gr]],Io=M[2*et[Gr]+1],Po=M[2*et[mn]+1];let To=!1;if(Hnso)To=!1;else{const Bt=Po-Io,$t=-(M[2*et[mn]]-uo),Gr=Io((so-uo)*Bt+(M[2*et[Nt]+1]-Io)*$t)*Gr&&(To=!0)}if(To){const M=et[Wt],Nt=et[Gr],Hn=et[mn];M!==Nt&&M!==Hn&&Nt!==Hn&&Bt.push(Hn,Nt,M),Gr--,Gr<0&&(Gr=$t-1)}else{const M=et[Nt],Wt=et[Gr],Hn=et[mn];M!==Wt&&M!==Hn&&Wt!==Hn&&Bt.push(Hn,Wt,M),mn++,mn>=$t&&(mn=0)}if(Wt===Nt)break}}function Pl(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn){const so=Nt.length/2,uo=Gr&&mn&&Hn;if(soPa.MAX_VERTEX_ARRAY_LENGTH&&(so=M.createNewSegment(et,Bt),Hn=mn.count,Ia=!0,Ba=!0,Ta=!0,uo=0);const Va=Cl(Gr,Wt,$t,mn,Po,Ia,so),za=Cl(Gr,Wt,$t,mn,To,Ba,so),Fa=Cl(Gr,Wt,$t,mn,Eo,Ta,so);Bt.emplaceBack(uo+Va-Hn,uo+za-Hn,uo+Fa-Hn),so.primitiveLength++}}(et,Bt,Wt,Nt,$t,M),uo&&function(M,et,Bt,Wt,Nt,$t){const Gr=[];for(let M=0;MPa.MAX_VERTEX_ARRAY_LENGTH&&(so=M.createNewSegment(et,Bt),Hn=mn.count,Eo=!0,Ia=!0,uo=0);const Ba=Cl(Gr,Wt,$t,mn,Nt,Eo,so),Ta=Cl(Gr,Wt,$t,mn,Io,Ia,so);Bt.emplaceBack(uo+Ba-Hn,uo+Ta-Hn),so.primitiveLength++}}}(Gr,Bt,mn,Nt,Hn,M),et.forceNewSegmentOnNextPrepare(),null==Gr||Gr.forceNewSegmentOnNextPrepare()}function Cl(M,et,Bt,Wt,Nt,$t,Gr){if($t){const $t=Wt.count;return Bt(et[2*Nt],et[2*Nt+1]),M[Nt]=Wt.count,Wt.count++,Gr.vertexLength++,$t}return M[Nt]}class Bl{constructor(M){this.zoom=M.zoom,this.overscaling=M.overscaling,this.layers=M.layers,this.layerIds=this.layers.map((M=>M.id)),this.index=M.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new ya,this.indexArray=new ka,this.indexArray2=new Ma,this.programConfigurations=new ro(M.layers,M.zoom),this.segments=new Pa,this.segments2=new Pa,this.stateDependentLayerIds=this.layers.filter((M=>M.isStateDependent())).map((M=>M.id))}populate(M,et,Bt){this.hasPattern=Ko("fill",this.layers,et);const Wt=this.layers[0].layout.get("fill-sort-key"),Nt=!Wt.isConstant(),$t=[];for(const{feature:Gr,id:mn,index:Hn,sourceLayerIndex:so}of M){const M=this.layers[0]._featureFilter.needGeometry,uo=lo(Gr,M);if(!this.layers[0]._featureFilter.filter(new cs(this.zoom),uo,Bt))continue;const Io=Nt?Wt.evaluate(uo,{},Bt,et.availableImages):void 0,Po={id:mn,properties:Gr.properties,type:Gr.type,sourceLayerIndex:so,index:Hn,geometry:M?uo.geometry:oo(Gr),patterns:{},sortKey:Io};$t.push(Po)}Nt&&$t.sort(((M,et)=>M.sortKey-et.sortKey));for(const Wt of $t){const{geometry:Nt,index:$t,sourceLayerIndex:Gr}=Wt;if(this.hasPattern){const M=Ho("fill",this.layers,Wt,this.zoom,et);this.patternFeatures.push(M)}else this.addFeature(Wt,Nt,$t,Bt,{},et.subdivisionGranularity);et.featureIndex.insert(M[$t].feature,Nt,$t,Gr,this.index)}}update(M,et,Bt){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(M,et,this.stateDependentLayers,Bt)}addFeatures(M,et,Bt){for(const Wt of this.patternFeatures)this.addFeature(Wt,Wt.geometry,Wt.index,et,Bt,M.subdivisionGranularity)}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(M){this.uploaded||(this.layoutVertexBuffer=M.createVertexBuffer(this.layoutVertexArray,Mg),this.indexBuffer=M.createIndexBuffer(this.indexArray),this.indexBuffer2=M.createIndexBuffer(this.indexArray2)),this.programConfigurations.upload(M),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.indexBuffer2.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.segments2.destroy())}addFeature(M,et,Bt,Wt,Nt,$t){for(const M of Le(et,500)){const et=Ml(M,Wt,$t.fill.getGranularityForZoomLevel(Wt.z)),Bt=this.layoutVertexArray;Pl(((M,et)=>{Bt.emplaceBack(M,et)}),this.segments,this.layoutVertexArray,this.indexArray,et.verticesFlattened,et.indicesTriangles,this.segments2,this.indexArray2,et.indicesLineList)}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,M,Bt,Nt,Wt)}}let zg,Fg;Ui("FillBucket",Bl,{omit:["layers","patternFeatures"]});var Eg={get paint(){return Fg=Fg||new As({"fill-antialias":new vs(Ka.paint_fill["fill-antialias"]),"fill-opacity":new bs(Ka.paint_fill["fill-opacity"]),"fill-color":new bs(Ka.paint_fill["fill-color"]),"fill-outline-color":new bs(Ka.paint_fill["fill-outline-color"]),"fill-translate":new vs(Ka.paint_fill["fill-translate"]),"fill-translate-anchor":new vs(Ka.paint_fill["fill-translate-anchor"]),"fill-pattern":new ws(Ka.paint_fill["fill-pattern"])})},get layout(){return zg=zg||new As({"fill-sort-key":new bs(Ka.layout_fill["fill-sort-key"])})}};class Fl extends Ms{constructor(M){super(M,Eg)}recalculate(M,et){super.recalculate(M,et);const Bt=this.paint._values["fill-outline-color"];"constant"===Bt.value.kind&&void 0===Bt.value.value&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"])}createBucket(M){return new Bl(M)}queryRadius(){return ko(this.paint.get("fill-translate"))}queryIntersectsFeature({queryGeometry:M,geometry:et,transform:Bt,pixelsToTileUnits:Wt}){return yo(Mo(M,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),-Bt.bearingInRadians,Wt),et)}isTileClipped(){return!0}}const Jg=Cs([{name:"a_pos",components:2,type:"Int16"},{name:"a_normal_ed",components:4,type:"Int16"}],4),Xg=Cs([{name:"a_centroid",components:2,type:"Int16"}],4),{members:Lg}=Jg;var Dg,Hg,Kg,Ng,Yg,Og,jg,Ug={};function Xl(){if(Hg)return Dg;Hg=1;var M=s();function e(M,et,Bt,Wt,Nt){this.properties={},this.extent=Bt,this.type=0,this._pbf=M,this._geometry=-1,this._keys=Wt,this._values=Nt,M.readFields(r,this,et)}function r(M,et,Bt){1==M?et.id=Bt.readVarint():2==M?function(M,et){for(var Bt=M.readVarint()+M.pos;M.pos>3}if($t--,1===Nt||2===Nt)Gr+=et.readSVarint(),mn+=et.readSVarint(),1===Nt&&(Bt&&Hn.push(Bt),Bt=[]),Bt.push(new M(Gr,mn));else{if(7!==Nt)throw new Error("unknown command "+Nt);Bt&&Bt.push(Bt[0].clone())}}return Bt&&Hn.push(Bt),Hn},e.prototype.bbox=function(){var M=this._pbf;M.pos=this._geometry;for(var et=M.readVarint()+M.pos,Bt=1,Wt=0,Nt=0,$t=0,Gr=1/0,mn=-1/0,Hn=1/0,so=-1/0;M.pos>3}if(Wt--,1===Bt||2===Bt)(Nt+=M.readSVarint())mn&&(mn=Nt),($t+=M.readSVarint())so&&(so=$t);else if(7!==Bt)throw new Error("unknown command "+Bt)}return[Gr,Hn,mn,so]},e.prototype.toGeoJSON=function(M,et,Bt){var Wt,Nt,$t=this.extent*Math.pow(2,Bt),Gr=this.extent*M,mn=this.extent*et,Hn=this.loadGeometry(),so=e.types[this.type];function p(M){for(var et=0;et>3;et=1===Wt?M.readString():2===Wt?M.readFloat():3===Wt?M.readDouble():4===Wt?M.readVarint64():5===Wt?M.readVarint():6===Wt?M.readSVarint():7===Wt?M.readBoolean():null}return et}(Bt))}return Kg=e,e.prototype.feature=function(et){if(et<0||et>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[et];var Bt=this._pbf.readVarint()+this._pbf.pos;return new M(this._pbf,Bt,this.extent,this._keys,this._values)},Kg}function Hl(){return jg||(jg=1,Ug.VectorTile=function(){if(Og)return Yg;Og=1;var M=Kl();function e(et,Bt,Wt){if(3===et){var Nt=new M(Wt,Wt.readVarint()+Wt.pos);Nt.length&&(Bt[Nt.name]=Nt)}}return Yg=function(M,et){this.layers=M.readFields(e,{},et)},Yg}(),Ug.VectorTileFeature=Xl(),Ug.VectorTileLayer=Kl()),Ug}var Qg=r(Hl());const qg=Qg.VectorTileFeature.types,$g=Math.pow(2,13);function Ql(M,et,Bt,Wt,Nt,$t,Gr,mn){M.emplaceBack(et,Bt,2*Math.floor(Wt*$g)+Gr,Nt*$g*2,$t*$g*2,Math.round(mn))}class tu{constructor(M){this.zoom=M.zoom,this.overscaling=M.overscaling,this.layers=M.layers,this.layerIds=this.layers.map((M=>M.id)),this.index=M.index,this.hasPattern=!1,this.layoutVertexArray=new ma,this.centroidVertexArray=new fa,this.indexArray=new ka,this.programConfigurations=new ro(M.layers,M.zoom),this.segments=new Pa,this.stateDependentLayerIds=this.layers.filter((M=>M.isStateDependent())).map((M=>M.id))}populate(M,et,Bt){this.features=[],this.hasPattern=Ko("fill-extrusion",this.layers,et);for(const{feature:Wt,id:Nt,index:$t,sourceLayerIndex:Gr}of M){const M=this.layers[0]._featureFilter.needGeometry,mn=lo(Wt,M);if(!this.layers[0]._featureFilter.filter(new cs(this.zoom),mn,Bt))continue;const Hn={id:Nt,sourceLayerIndex:Gr,index:$t,geometry:M?mn.geometry:oo(Wt),properties:Wt.properties,type:Wt.type,patterns:{}};this.hasPattern?this.features.push(Ho("fill-extrusion",this.layers,Hn,this.zoom,et)):this.addFeature(Hn,Hn.geometry,$t,Bt,{},et.subdivisionGranularity),et.featureIndex.insert(Wt,Hn.geometry,$t,Gr,this.index,!0)}}addFeatures(M,et,Bt){for(const Wt of this.features){const{geometry:Nt}=Wt;this.addFeature(Wt,Nt,Wt.index,et,Bt,M.subdivisionGranularity)}}update(M,et,Bt){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(M,et,this.stateDependentLayers,Bt)}isEmpty(){return 0===this.layoutVertexArray.length&&0===this.centroidVertexArray.length}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(M){this.uploaded||(this.layoutVertexBuffer=M.createVertexBuffer(this.layoutVertexArray,Lg),this.centroidVertexBuffer=M.createVertexBuffer(this.centroidVertexArray,Xg.members,!0),this.indexBuffer=M.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(M),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.centroidVertexBuffer.destroy())}addFeature(M,et,Bt,Wt,Nt,$t){for(const Bt of Le(et,500)){const et={x:0,y:0,sampleCount:0},Nt=this.layoutVertexArray.length;this.processPolygon(et,Wt,M,Bt,$t);const Gr=this.layoutVertexArray.length-Nt,mn=Math.floor(et.x/et.sampleCount),Hn=Math.floor(et.y/et.sampleCount);for(let M=0;M{Ql(so,M,et,0,0,1,1,0)}),this.segments,this.layoutVertexArray,this.indexArray,Hn.verticesFlattened,Hn.indicesTriangles)}_generateSideFaces(M,et){let Bt=0;for(let Wt=1;WtPa.MAX_VERTEX_ARRAY_LENGTH&&(et.segment=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));const Gr=Nt.sub($t)._perp()._unit(),mn=$t.dist(Nt);Bt+mn>32768&&(Bt=0),Ql(this.layoutVertexArray,Nt.x,Nt.y,Gr.x,Gr.y,0,0,Bt),Ql(this.layoutVertexArray,Nt.x,Nt.y,Gr.x,Gr.y,0,1,Bt),Bt+=mn,Ql(this.layoutVertexArray,$t.x,$t.y,Gr.x,Gr.y,0,0,Bt),Ql(this.layoutVertexArray,$t.x,$t.y,Gr.x,Gr.y,0,1,Bt);const Hn=et.segment.vertexLength;this.indexArray.emplaceBack(Hn,Hn+2,Hn+1),this.indexArray.emplaceBack(Hn+1,Hn+2,Hn+3),et.segment.vertexLength+=4,et.segment.primitiveLength+=2}}}function eu(M,et){for(let Bt=0;BtTo)||M.y===et.y&&(M.y<0||M.y>To)}function nu(M){return M.every((M=>M.x<0))||M.every((M=>M.x>To))||M.every((M=>M.y<0))||M.every((M=>M.y>To))}let iu;Ui("FillExtrusionBucket",tu,{omit:["layers","features"]});var su={get paint(){return iu=iu||new As({"fill-extrusion-opacity":new vs(Ka["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new bs(Ka["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new vs(Ka["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new vs(Ka["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new ws(Ka["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-height":new bs(Ka["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new bs(Ka["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-vertical-gradient":new vs(Ka["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"])})}};class au extends Ms{constructor(M){super(M,su)}createBucket(M){return new tu(M)}queryRadius(){return ko(this.paint.get("fill-extrusion-translate"))}is3D(){return!0}queryIntersectsFeature({queryGeometry:M,feature:et,featureState:Bt,geometry:Wt,transform:Nt,pixelsToTileUnits:Gr,pixelPosMatrix:mn}){const Hn=Mo(M,this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),-Nt.bearingInRadians,Gr),so=this.paint.get("fill-extrusion-height").evaluate(et,Bt),uo=this.paint.get("fill-extrusion-base").evaluate(et,Bt),Io=function(M,et){const Bt=[];for(const Wt of M){const M=[Wt.x,Wt.y,0,1];_(M,M,et),Bt.push(new $t(M[0]/M[3],M[1]/M[3]))}return Bt}(Hn,mn),Po=function(M,et,Bt,Wt){const Nt=[],Gr=[],mn=Wt[8]*et,Hn=Wt[9]*et,so=Wt[10]*et,uo=Wt[11]*et,Io=Wt[8]*Bt,Po=Wt[9]*Bt,To=Wt[10]*Bt,Eo=Wt[11]*Bt;for(const et of M){const M=[],Bt=[];for(const Nt of et){const et=Nt.x,Gr=Nt.y,Ia=Wt[0]*et+Wt[4]*Gr+Wt[12],Ba=Wt[1]*et+Wt[5]*Gr+Wt[13],Ta=Wt[2]*et+Wt[6]*Gr+Wt[14],Va=Wt[3]*et+Wt[7]*Gr+Wt[15],za=Ta+so,Fa=Va+uo,Ea=Ia+Io,La=Ba+Po,Da=Ta+To,Ka=Va+Eo,Oa=new $t((Ia+mn)/Fa,(Ba+Hn)/Fa);Oa.z=za/Fa,M.push(Oa);const $a=new $t(Ea/Ka,La/Ka);$a.z=Da/Ka,Bt.push($a)}Nt.push(M),Gr.push(Bt)}return[Nt,Gr]}(Wt,uo,so,mn);return function(M,et,Bt){let Wt=1/0;yo(Bt,et)&&(Wt=lu(Bt,et[0]));for(let Nt=0;NtM.id)),this.index=M.index,this.hasPattern=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach((M=>{this.gradients[M.id]={}})),this.layoutVertexArray=new ga,this.layoutVertexArray2=new xa,this.indexArray=new ka,this.programConfigurations=new ro(M.layers,M.zoom),this.segments=new Pa,this.maxLineLength=0,this.stateDependentLayerIds=this.layers.filter((M=>M.isStateDependent())).map((M=>M.id))}populate(M,et,Bt){this.hasPattern=Ko("line",this.layers,et);const Wt=this.layers[0].layout.get("line-sort-key"),Nt=!Wt.isConstant(),$t=[];for(const{feature:et,id:Gr,index:mn,sourceLayerIndex:Hn}of M){const M=this.layers[0]._featureFilter.needGeometry,so=lo(et,M);if(!this.layers[0]._featureFilter.filter(new cs(this.zoom),so,Bt))continue;const uo=Nt?Wt.evaluate(so,{},Bt):void 0,Io={id:Gr,properties:et.properties,type:et.type,sourceLayerIndex:Hn,index:mn,geometry:M?so.geometry:oo(et),patterns:{},sortKey:uo};$t.push(Io)}Nt&&$t.sort(((M,et)=>M.sortKey-et.sortKey));for(const Wt of $t){const{geometry:Nt,index:$t,sourceLayerIndex:Gr}=Wt;if(this.hasPattern){const M=Ho("line",this.layers,Wt,this.zoom,et);this.patternFeatures.push(M)}else this.addFeature(Wt,Nt,$t,Bt,{},et.subdivisionGranularity);et.featureIndex.insert(M[$t].feature,Nt,$t,Gr,this.index)}}update(M,et,Bt){this.stateDependentLayers.length&&this.programConfigurations.updatePaintArrays(M,et,this.stateDependentLayers,Bt)}addFeatures(M,et,Bt){for(const Wt of this.patternFeatures)this.addFeature(Wt,Wt.geometry,Wt.index,et,Bt,M.subdivisionGranularity)}isEmpty(){return 0===this.layoutVertexArray.length}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(M){this.uploaded||(0!==this.layoutVertexArray2.length&&(this.layoutVertexBuffer2=M.createVertexBuffer(this.layoutVertexArray2,uu)),this.layoutVertexBuffer=M.createVertexBuffer(this.layoutVertexArray,hu),this.indexBuffer=M.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(M),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}lineFeatureClips(M){if(M.properties&&Object.prototype.hasOwnProperty.call(M.properties,"mapbox_clip_start")&&Object.prototype.hasOwnProperty.call(M.properties,"mapbox_clip_end"))return{start:+M.properties.mapbox_clip_start,end:+M.properties.mapbox_clip_end}}addFeature(M,et,Bt,Wt,Nt,$t){const Gr=this.layers[0].layout,mn=Gr.get("line-join").evaluate(M,{}),Hn=Gr.get("line-cap"),so=Gr.get("line-miter-limit"),uo=Gr.get("line-round-limit");this.lineClips=this.lineFeatureClips(M);for(const Bt of et)this.addLine(Bt,M,mn,Hn,so,uo,Wt,$t);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,M,Bt,Nt,Wt)}addLine(M,et,Bt,Wt,Nt,$t,Gr,mn){if(this.distance=0,this.scaledDistance=0,this.totalDistance=0,M=Il(M,Gr?mn.line.getGranularityForZoomLevel(Gr.z):1),this.lineClips){this.lineClipsArray.push(this.lineClips);for(let et=0;et=2&&M[so-1].equals(M[so-2]);)so--;let uo=0;for(;uo0;if(Ea&&et>uo){const M=Eo.dist(Ia);if(M>2*Io){const et=Eo.sub(Eo.sub(Ia)._mult(Io/M)._round());this.updateDistance(Ia,et),this.addCurrentVertex(et,Ta,0,0,Po),Ia=et}}const Da=Ia&&Ba;let Ka=Da?Bt:Hn?"butt":Wt;if(Da&&"round"===Ka&&(za<$t?Ka="miter":za<=2&&(Ka="fakeround")),"miter"===Ka&&za>Nt&&(Ka="bevel"),"bevel"===Ka&&(za>2&&(Ka="flipbevel"),za100)Gr=Va.mult(-1);else{const M=za*Ta.add(Va).mag()/Ta.sub(Va).mag();Gr._perp()._mult(M*(La?-1:1))}this.addCurrentVertex(Eo,Gr,0,0,Po),this.addCurrentVertex(Eo,Gr.mult(-1),0,0,Po)}else if("bevel"===Ka||"fakeround"===Ka){const M=-Math.sqrt(za*za-1),et=La?M:0,Bt=La?0:M;if(Ia&&this.addCurrentVertex(Eo,Ta,et,Bt,Po),"fakeround"===Ka){const M=Math.round(180*Fa/Math.PI/20);for(let et=1;et2*Io){const et=Eo.add(Ba.sub(Eo)._mult(Io/M)._round());this.updateDistance(Eo,et),this.addCurrentVertex(et,Va,0,0,Po),Eo=et}}}}addCurrentVertex(M,et,Bt,Wt,Nt,$t=!1){const Gr=et.y*Wt-et.x,mn=-et.y-et.x*Wt;this.addHalfVertex(M,et.x+et.y*Bt,et.y-et.x*Bt,$t,!1,Bt,Nt),this.addHalfVertex(M,Gr,mn,$t,!0,-Wt,Nt),this.distance>Cu/2&&0===this.totalDistance&&(this.distance=0,this.updateScaledDistance(),this.addCurrentVertex(M,et,Bt,Wt,Nt,$t))}addHalfVertex({x:M,y:et},Bt,Wt,Nt,$t,Gr,mn){const Hn=.5*(this.lineClips?this.scaledDistance*(Cu-1):this.scaledDistance);this.layoutVertexArray.emplaceBack((M<<1)+(Nt?1:0),(et<<1)+($t?1:0),Math.round(63*Bt)+128,Math.round(63*Wt)+128,1+(0===Gr?0:Gr<0?-1:1)|(63&Hn)<<2,Hn>>6),this.lineClips&&this.layoutVertexArray2.emplaceBack((this.scaledDistance-this.lineClips.start)/(this.lineClips.end-this.lineClips.start),this.lineClipsArray.length);const so=mn.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,so,this.e2),mn.primitiveLength++),$t?this.e2=so:this.e1=so}updateScaledDistance(){this.scaledDistance=this.lineClips?this.lineClips.start+(this.lineClips.end-this.lineClips.start)*this.distance/this.totalDistance:this.distance}updateDistance(M,et){this.distance+=M.dist(et),this.updateScaledDistance()}}let Iu,fu;Ui("LineBucket",mu,{omit:["layers","patternFeatures"]});var yu={get paint(){return fu=fu||new As({"line-opacity":new bs(Ka.paint_line["line-opacity"]),"line-color":new bs(Ka.paint_line["line-color"]),"line-translate":new vs(Ka.paint_line["line-translate"]),"line-translate-anchor":new vs(Ka.paint_line["line-translate-anchor"]),"line-width":new bs(Ka.paint_line["line-width"]),"line-gap-width":new bs(Ka.paint_line["line-gap-width"]),"line-offset":new bs(Ka.paint_line["line-offset"]),"line-blur":new bs(Ka.paint_line["line-blur"]),"line-dasharray":new _s(Ka.paint_line["line-dasharray"]),"line-pattern":new ws(Ka.paint_line["line-pattern"]),"line-gradient":new Ss(Ka.paint_line["line-gradient"])})},get layout(){return Iu=Iu||new As({"line-cap":new vs(Ka.layout_line["line-cap"]),"line-join":new bs(Ka.layout_line["line-join"]),"line-miter-limit":new vs(Ka.layout_line["line-miter-limit"]),"line-round-limit":new vs(Ka.layout_line["line-round-limit"]),"line-sort-key":new bs(Ka.layout_line["line-sort-key"])})}};class bu extends bs{possiblyEvaluate(M,et){return et=new cs(Math.floor(et.zoom),{now:et.now,fadeDuration:et.fadeDuration,zoomHistory:et.zoomHistory,transition:et.transition}),super.possiblyEvaluate(M,et)}evaluate(M,et,Bt,Wt){return et=F({},et,{zoom:Math.floor(et.zoom)}),super.evaluate(M,et,Bt,Wt)}}let Au;class _u extends Ms{constructor(M){super(M,yu),this.gradientVersion=0,Au||(Au=new bu(yu.paint.properties["line-width"].specification),Au.useIntegerZoom=!0)}_handleSpecialPaintPropertyUpdate(M){if("line-gradient"===M){const M=this.gradientExpression();this.stepInterpolant=!!function(M){return void 0!==M._styleExpression}(M)&&M._styleExpression.expression instanceof Qe,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER}}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}recalculate(M,et){super.recalculate(M,et),this.paint._values["line-floorwidth"]=Au.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,M)}createBucket(M){return new mu(M)}queryRadius(M){const et=M,Bt=Su(Ao("line-width",this,et),Ao("line-gap-width",this,et)),Wt=Ao("line-offset",this,et);return Bt/2+Math.abs(Wt)+ko(this.paint.get("line-translate"))}queryIntersectsFeature({queryGeometry:M,feature:et,featureState:Bt,geometry:Wt,transform:Nt,pixelsToTileUnits:Gr}){const mn=Mo(M,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),-Nt.bearingInRadians,Gr),Hn=Gr/2*Su(this.paint.get("line-width").evaluate(et,Bt),this.paint.get("line-gap-width").evaluate(et,Bt)),so=this.paint.get("line-offset").evaluate(et,Bt);return so&&(Wt=function(M,et){const Bt=[];for(let Wt=0;Wt=3)for(let et=0;et0?et+2*M:M}const vu=Cs([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),xu=Cs([{name:"a_projected_pos",components:3,type:"Float32"}],4);Cs([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const wu=Cs([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_box_real",components:2,type:"Int16"}]);Cs([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]);const ku=Cs([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),Bu=Cs([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function Pu(M,et,Bt){return M.sections.forEach((M=>{M.text=function(M,et,Bt){const Wt=et.layout.get("text-transform").evaluate(Bt,{});return"uppercase"===Wt?M=M.toLocaleUpperCase():"lowercase"===Wt&&(M=M.toLocaleLowerCase()),ag.applyArabicShaping&&(M=ag.applyArabicShaping(M)),M}(M.text,et,Bt)})),M}Cs([{name:"triangle",components:3,type:"Uint16"}]),Cs([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),Cs([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",name:"collisionCircleDiameter"},{type:"Uint16",name:"textAnchorOffsetStartIndex"},{type:"Uint16",name:"textAnchorOffsetEndIndex"}]),Cs([{type:"Float32",name:"offsetX"}]),Cs([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]),Cs([{type:"Uint16",name:"textAnchor"},{type:"Float32",components:2,name:"textOffset"}]);const Gu={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};var Tu,Mu,Vu,zu=24,Fu={};function $u(){return Tu||(Tu=1,Fu.read=function(M,et,Bt,Wt,Nt){var $t,Gr,mn=8*Nt-Wt-1,Hn=(1<>1,uo=-7,Io=Bt?Nt-1:0,Po=Bt?-1:1,To=M[et+Io];for(Io+=Po,$t=To&(1<<-uo)-1,To>>=-uo,uo+=mn;uo>0;$t=256*$t+M[et+Io],Io+=Po,uo-=8);for(Gr=$t&(1<<-uo)-1,$t>>=-uo,uo+=Wt;uo>0;Gr=256*Gr+M[et+Io],Io+=Po,uo-=8);if(0===$t)$t=1-so;else{if($t===Hn)return Gr?NaN:1/0*(To?-1:1);Gr+=Math.pow(2,Wt),$t-=so}return(To?-1:1)*Gr*Math.pow(2,$t-Wt)},Fu.write=function(M,et,Bt,Wt,Nt,$t){var Gr,mn,Hn,so=8*$t-Nt-1,uo=(1<>1,Po=23===Nt?Math.pow(2,-24)-Math.pow(2,-77):0,To=Wt?0:$t-1,Eo=Wt?1:-1,Ia=et<0||0===et&&1/et<0?1:0;for(et=Math.abs(et),isNaN(et)||et===1/0?(mn=isNaN(et)?1:0,Gr=uo):(Gr=Math.floor(Math.log(et)/Math.LN2),et*(Hn=Math.pow(2,-Gr))<1&&(Gr--,Hn*=2),(et+=Gr+Io>=1?Po/Hn:Po*Math.pow(2,1-Io))*Hn>=2&&(Gr++,Hn/=2),Gr+Io>=uo?(mn=0,Gr=uo):Gr+Io>=1?(mn=(et*Hn-1)*Math.pow(2,Nt),Gr+=Io):(mn=et*Math.pow(2,Io-1)*Math.pow(2,Nt),Gr=0));Nt>=8;M[Bt+To]=255&mn,To+=Eo,mn/=256,Nt-=8);for(Gr=Gr<0;M[Bt+To]=255&Gr,To+=Eo,Gr/=256,so-=8);M[Bt+To-Eo]|=128*Ia}),Fu}function Lu(){if(Vu)return Mu;Vu=1,Mu=e;var M=$u();function e(M){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(M)?M:new Uint8Array(M||0),this.pos=0,this.type=0,this.length=this.buf.length}e.Varint=0,e.Fixed64=1,e.Bytes=2,e.Fixed32=5;var et=4294967296,Bt=1/et,Wt="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");function s(M){return M.type===e.Bytes?M.readVarint()+M.pos:M.pos+1}function a(M,et,Bt){return Bt?4294967296*et+(M>>>0):4294967296*(et>>>0)+(M>>>0)}function o(M,et,Bt){var Wt=et<=16383?1:et<=2097151?2:et<=268435455?3:Math.floor(Math.log(et)/(7*Math.LN2));Bt.realloc(Wt);for(var Nt=Bt.pos-1;Nt>=M;Nt--)Bt.buf[Nt+Wt]=Bt.buf[Nt]}function l(M,et){for(var Bt=0;Bt>>8,M[Bt+2]=et>>>16,M[Bt+3]=et>>>24}function v(M,et){return(M[et]|M[et+1]<<8|M[et+2]<<16)+(M[et+3]<<24)}return e.prototype={destroy:function(){this.buf=null},readFields:function(M,et,Bt){for(Bt=Bt||this.length;this.pos>3,$t=this.pos;this.type=7&Wt,M(Nt,et,this),this.pos===$t&&this.skip(Wt)}return et},readMessage:function(M,et){return this.readFields(M,et,this.readVarint()+this.pos)},readFixed32:function(){var M=g(this.buf,this.pos);return this.pos+=4,M},readSFixed32:function(){var M=v(this.buf,this.pos);return this.pos+=4,M},readFixed64:function(){var M=g(this.buf,this.pos)+g(this.buf,this.pos+4)*et;return this.pos+=8,M},readSFixed64:function(){var M=g(this.buf,this.pos)+v(this.buf,this.pos+4)*et;return this.pos+=8,M},readFloat:function(){var et=M.read(this.buf,this.pos,!0,23,4);return this.pos+=4,et},readDouble:function(){var et=M.read(this.buf,this.pos,!0,52,8);return this.pos+=8,et},readVarint:function(M){var et,Bt,Wt=this.buf;return et=127&(Bt=Wt[this.pos++]),Bt<128?et:(et|=(127&(Bt=Wt[this.pos++]))<<7,Bt<128?et:(et|=(127&(Bt=Wt[this.pos++]))<<14,Bt<128?et:(et|=(127&(Bt=Wt[this.pos++]))<<21,Bt<128?et:function(M,et,Bt){var Wt,Nt,$t=Bt.buf;if(Wt=(112&(Nt=$t[Bt.pos++]))>>4,Nt<128)return a(M,Wt,et);if(Wt|=(127&(Nt=$t[Bt.pos++]))<<3,Nt<128)return a(M,Wt,et);if(Wt|=(127&(Nt=$t[Bt.pos++]))<<10,Nt<128)return a(M,Wt,et);if(Wt|=(127&(Nt=$t[Bt.pos++]))<<17,Nt<128)return a(M,Wt,et);if(Wt|=(127&(Nt=$t[Bt.pos++]))<<24,Nt<128)return a(M,Wt,et);if(Wt|=(1&(Nt=$t[Bt.pos++]))<<31,Nt<128)return a(M,Wt,et);throw new Error("Expected varint not more than 10 bytes")}(et|=(15&(Bt=Wt[this.pos]))<<28,M,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var M=this.readVarint();return M%2==1?(M+1)/-2:M/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var M=this.readVarint()+this.pos,et=this.pos;return this.pos=M,M-et>=12&&Wt?function(M,et,Bt){return Wt.decode(M.subarray(et,Bt))}(this.buf,et,M):function(M,et,Bt){for(var Wt="",Nt=et;Nt239?4:Hn>223?3:Hn>191?2:1;if(Nt+uo>Bt)break;1===uo?Hn<128&&(so=Hn):2===uo?128==(192&($t=M[Nt+1]))&&(so=(31&Hn)<<6|63&$t)<=127&&(so=null):3===uo?(Gr=M[Nt+2],128==(192&($t=M[Nt+1]))&&128==(192&Gr)&&((so=(15&Hn)<<12|(63&$t)<<6|63&Gr)<=2047||so>=55296&&so<=57343)&&(so=null)):4===uo&&(Gr=M[Nt+2],mn=M[Nt+3],128==(192&($t=M[Nt+1]))&&128==(192&Gr)&&128==(192&mn)&&((so=(15&Hn)<<18|(63&$t)<<12|(63&Gr)<<6|63&mn)<=65535||so>=1114112)&&(so=null)),null===so?(so=65533,uo=1):so>65535&&(so-=65536,Wt+=String.fromCharCode(so>>>10&1023|55296),so=56320|1023&so),Wt+=String.fromCharCode(so),Nt+=uo}return Wt}(this.buf,et,M)},readBytes:function(){var M=this.readVarint()+this.pos,et=this.buf.subarray(this.pos,M);return this.pos=M,et},readPackedVarint:function(M,et){if(this.type!==e.Bytes)return M.push(this.readVarint(et));var Bt=s(this);for(M=M||[];this.pos127;);else if(et===e.Bytes)this.pos=this.readVarint()+this.pos;else if(et===e.Fixed32)this.pos+=4;else{if(et!==e.Fixed64)throw new Error("Unimplemented type: "+et);this.pos+=8}},writeTag:function(M,et){this.writeVarint(M<<3|et)},realloc:function(M){for(var et=this.length||16;et268435455||M<0?function(M,et){var Bt,Wt;if(M>=0?(Bt=M%4294967296|0,Wt=M/4294967296|0):(Wt=~(-M/4294967296),4294967295^(Bt=~(-M%4294967296))?Bt=Bt+1|0:(Bt=0,Wt=Wt+1|0)),M>=0x10000000000000000||M<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");et.realloc(10),function(M,et,Bt){Bt.buf[Bt.pos++]=127&M|128,M>>>=7,Bt.buf[Bt.pos++]=127&M|128,M>>>=7,Bt.buf[Bt.pos++]=127&M|128,M>>>=7,Bt.buf[Bt.pos++]=127&M|128,Bt.buf[Bt.pos]=127&(M>>>=7)}(Bt,0,et),function(M,et){var Bt=(7&M)<<4;et.buf[et.pos++]|=Bt|((M>>>=3)?128:0),M&&(et.buf[et.pos++]=127&M|((M>>>=7)?128:0),M&&(et.buf[et.pos++]=127&M|((M>>>=7)?128:0),M&&(et.buf[et.pos++]=127&M|((M>>>=7)?128:0),M&&(et.buf[et.pos++]=127&M|((M>>>=7)?128:0),M&&(et.buf[et.pos++]=127&M)))))}(Wt,et)}(M,this):(this.realloc(4),this.buf[this.pos++]=127&M|(M>127?128:0),M<=127||(this.buf[this.pos++]=127&(M>>>=7)|(M>127?128:0),M<=127||(this.buf[this.pos++]=127&(M>>>=7)|(M>127?128:0),M<=127||(this.buf[this.pos++]=M>>>7&127))))},writeSVarint:function(M){this.writeVarint(M<0?2*-M-1:2*M)},writeBoolean:function(M){this.writeVarint(Boolean(M))},writeString:function(M){M=String(M),this.realloc(4*M.length),this.pos++;var et=this.pos;this.pos=function(M,et,Bt){for(var Wt,Nt,$t=0;$t55295&&Wt<57344){if(!Nt){Wt>56319||$t+1===et.length?(M[Bt++]=239,M[Bt++]=191,M[Bt++]=189):Nt=Wt;continue}if(Wt<56320){M[Bt++]=239,M[Bt++]=191,M[Bt++]=189,Nt=Wt;continue}Wt=Nt-55296<<10|Wt-56320|65536,Nt=null}else Nt&&(M[Bt++]=239,M[Bt++]=191,M[Bt++]=189,Nt=null);Wt<128?M[Bt++]=Wt:(Wt<2048?M[Bt++]=Wt>>6|192:(Wt<65536?M[Bt++]=Wt>>12|224:(M[Bt++]=Wt>>18|240,M[Bt++]=Wt>>12&63|128),M[Bt++]=Wt>>6&63|128),M[Bt++]=63&Wt|128)}return Bt}(this.buf,M,this.pos);var Bt=this.pos-et;Bt>=128&&o(et,Bt,this),this.pos=et-1,this.writeVarint(Bt),this.pos+=Bt},writeFloat:function(et){this.realloc(4),M.write(this.buf,et,this.pos,!0,23,4),this.pos+=4},writeDouble:function(et){this.realloc(8),M.write(this.buf,et,this.pos,!0,52,8),this.pos+=8},writeBytes:function(M){var et=M.length;this.writeVarint(et),this.realloc(et);for(var Bt=0;Bt=128&&o(Bt,Wt,this),this.pos=Bt-1,this.writeVarint(Wt),this.pos+=Wt},writeMessage:function(M,et,Bt){this.writeTag(M,e.Bytes),this.writeRawMessage(et,Bt)},writePackedVarint:function(M,et){et.length&&this.writeMessage(M,l,et)},writePackedSVarint:function(M,et){et.length&&this.writeMessage(M,u,et)},writePackedBoolean:function(M,et){et.length&&this.writeMessage(M,p,et)},writePackedFloat:function(M,et){et.length&&this.writeMessage(M,c,et)},writePackedDouble:function(M,et){et.length&&this.writeMessage(M,h,et)},writePackedFixed32:function(M,et){et.length&&this.writeMessage(M,f,et)},writePackedSFixed32:function(M,et){et.length&&this.writeMessage(M,d,et)},writePackedFixed64:function(M,et){et.length&&this.writeMessage(M,y,et)},writePackedSFixed64:function(M,et){et.length&&this.writeMessage(M,m,et)},writeBytesField:function(M,et){this.writeTag(M,e.Bytes),this.writeBytes(et)},writeFixed32Field:function(M,et){this.writeTag(M,e.Fixed32),this.writeFixed32(et)},writeSFixed32Field:function(M,et){this.writeTag(M,e.Fixed32),this.writeSFixed32(et)},writeFixed64Field:function(M,et){this.writeTag(M,e.Fixed64),this.writeFixed64(et)},writeSFixed64Field:function(M,et){this.writeTag(M,e.Fixed64),this.writeSFixed64(et)},writeVarintField:function(M,et){this.writeTag(M,e.Varint),this.writeVarint(et)},writeSVarintField:function(M,et){this.writeTag(M,e.Varint),this.writeSVarint(et)},writeStringField:function(M,et){this.writeTag(M,e.Bytes),this.writeString(et)},writeFloatField:function(M,et){this.writeTag(M,e.Fixed32),this.writeFloat(et)},writeDoubleField:function(M,et){this.writeTag(M,e.Fixed64),this.writeDouble(et)},writeBooleanField:function(M,et){this.writeVarintField(M,Boolean(et))}},Mu}var Eu=r(Lu());const Du=3;function Ru(M,et,Bt){1===M&&Bt.readMessage(ju,et)}function ju(M,et,Bt){if(3===M){const{id:M,bitmap:Wt,width:Nt,height:$t,left:Gr,top:mn,advance:Hn}=Bt.readMessage(Nu,{});et.push({id:M,bitmap:new Do({width:Nt+2*Du,height:$t+2*Du},Wt),metrics:{width:Nt,height:$t,left:Gr,top:mn,advance:Hn}})}}function Nu(M,et,Bt){1===M?et.id=Bt.readVarint():2===M?et.bitmap=Bt.readBytes():3===M?et.width=Bt.readVarint():4===M?et.height=Bt.readVarint():5===M?et.left=Bt.readSVarint():6===M?et.top=Bt.readSVarint():7===M&&(et.advance=Bt.readVarint())}const Hu=Du;function qu(M){let et=0,Bt=0;for(const Wt of M)et+=Wt.w*Wt.h,Bt=Math.max(Bt,Wt.w);M.sort(((M,et)=>et.h-M.h));const Wt=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(et/.95)),Bt),h:1/0}];let Nt=0,$t=0;for(const et of M)for(let M=Wt.length-1;M>=0;M--){const Bt=Wt[M];if(!(et.w>Bt.w||et.h>Bt.h)){if(et.x=Bt.x,et.y=Bt.y,$t=Math.max($t,et.y+et.h),Nt=Math.max(Nt,et.x+et.w),et.w===Bt.w&&et.h===Bt.h){const et=Wt.pop();M=0&&Bt>=M&&Qu[this.text.charCodeAt(Bt)];Bt--)et--;this.text=this.text.substring(M,et),this.sectionIndex=this.sectionIndex.slice(M,et)}substring(M,et){const Bt=new Ju;return Bt.text=this.text.substring(M,et),Bt.sectionIndex=this.sectionIndex.slice(M,et),Bt.sections=this.sections,Bt}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce(((M,et)=>Math.max(M,this.sections[et].scale)),0)}addTextSection(M,et){this.text+=M.text,this.sections.push(Yu.forText(M.scale,M.fontStack||et));const Bt=this.sections.length-1;for(let et=0;et=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function Wu(et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia){const Ba=Ju.fromFeature(et,$t);let Ta;Po===M.ai.vertical&&Ba.verticalizePunctuation();const{processBidirectionalText:Va,processStyledBidirectionalText:za}=ag;if(Va&&1===Ba.sections.length){Ta=[];const M=Va(Ba.toString(),oc(Ba,uo,Gr,Bt,Nt,Eo));for(const et of M){const M=new Ju;M.text=et,M.sections=Ba.sections;for(let Bt=0;Bt0&&Wt>La&&(La=Wt)}else{const M=Wt[Ia.fontStack],et=M&&M[Ta];if(et&&et.rect)Da=et.rect,Fa=et.metrics;else{const M=Bt[Ia.fontStack],et=M&&M[Ta];if(!et)continue;Fa=et.metrics}Va=($t-Ia.scale)*zu}$a?(et.verticalizable=!0,Ea.push({glyph:Ta,imageName:Ka,x:To,y:Eo+Va,vertical:$a,scale:Ia.scale,fontStack:Ia.fontStack,sectionIndex:Ba,metrics:Fa,rect:Da}),To+=Oa*Ia.scale+uo):(Ea.push({glyph:Ta,imageName:Ka,x:To,y:Eo+Va,vertical:$a,scale:Ia.scale,fontStack:Ia.fontStack,sectionIndex:Ba,metrics:Fa,rect:Da}),To+=Fa.advance*Ia.scale+uo)}0!==Ea.length&&(Ia=Math.max(To-uo,Ia),uc(Ea,0,Ea.length-1,Ta,La)),To=0;const Da=Gr*$t+La;Fa.lineOffset=Math.max(La,Hn),Eo+=Da,Ba=Math.max(Da,Ba),++Va}var za;const Fa=Eo-Uu,{horizontalAlign:Ea,verticalAlign:La}=lc(mn);(function(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn){const so=(et-Bt)*Nt;let uo=0;uo=$t!==Gr?-mn*Wt-Uu:(-Wt*Hn+.5)*Gr;for(const et of M)for(const M of et.positionedGlyphs)M.x+=so,M.y+=uo})(et.positionedLines,Ta,Ea,La,Ia,Ba,Gr,Fa,$t.length),et.top+=-La*Fa,et.bottom=et.top+Fa,et.left+=-Ea*Ia,et.right=et.left+Ia}(Ea,Bt,Wt,Nt,Ta,mn,Hn,so,Po,uo,To,Ia),!function(M){for(const et of M)if(0!==et.positionedGlyphs.length)return!1;return!0}(Fa)&&Ea}const Qu={9:!0,10:!0,11:!0,12:!0,13:!0,32:!0},td={10:!0,32:!0,38:!0,41:!0,43:!0,45:!0,47:!0,173:!0,183:!0,8203:!0,8208:!0,8211:!0,8231:!0},ed={40:!0};function rc(M,et,Bt,Wt,Nt,$t){if(et.imageName){const M=Wt[et.imageName];return M?M.displaySize[0]*et.scale*zu/$t+Nt:0}{const Wt=Bt[et.fontStack],$t=Wt&&Wt[M];return $t?$t.metrics.advance*et.scale+Nt:0}}function nc(M,et,Bt,Wt){const Nt=Math.pow(M-et,2);return Wt?M=0;let so=0;for(let Bt=0;Btso){const M=Math.ceil($t/so);Nt*=M/Gr,Gr=M}return{x1:Wt,y1:Nt,x2:Wt+$t,y2:Nt+Gr}}function pc(M,et,Bt,Wt,Nt,$t){const Gr=M.image;let mn;if(Gr.content){const M=Gr.content,et=Gr.pixelRatio||1;mn=[M[0]/et,M[1]/et,Gr.displaySize[0]-M[2]/et,Gr.displaySize[1]-M[3]/et]}const Hn=et.left*$t,so=et.right*$t;let uo,Io,Po,To;"width"===Bt||"both"===Bt?(To=Nt[0]+Hn-Wt[3],Io=Nt[0]+so+Wt[1]):(To=Nt[0]+(Hn+so-Gr.displaySize[0])/2,Io=To+Gr.displaySize[0]);const Eo=et.top*$t,Ia=et.bottom*$t;return"height"===Bt||"both"===Bt?(uo=Nt[1]+Eo-Wt[0],Po=Nt[1]+Ia+Wt[2]):(uo=Nt[1]+(Eo+Ia-Gr.displaySize[1])/2,Po=uo+Gr.displaySize[1]),{image:Gr,top:uo,right:Io,bottom:Po,left:To,collisionPadding:mn}}const id=255,rd=128,nd=id*rd;function mc(M,et){const{expression:Bt}=et;if("constant"===Bt.kind)return{kind:"constant",layoutSize:Bt.evaluate(new cs(M+1))};if("source"===Bt.kind)return{kind:"source"};{const{zoomStops:et,interpolationType:Wt}=Bt;let Nt=0;for(;NtM.id)),this.index=et.index,this.pixelRatio=et.pixelRatio,this.sourceLayerIndex=et.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.sortKeyRanges=[],this.collisionCircleArray=[];const Bt=this.layers[0]._unevaluatedLayout._values;this.textSizeData=mc(this.zoom,Bt["text-size"]),this.iconSizeData=mc(this.zoom,Bt["icon-size"]);const Wt=this.layers[0].layout,Nt=Wt.get("symbol-sort-key"),$t=Wt.get("symbol-z-order");this.canOverlap="never"!==gc(Wt,"text-overlap","text-allow-overlap")||"never"!==gc(Wt,"icon-overlap","icon-allow-overlap")||Wt.get("text-ignore-placement")||Wt.get("icon-ignore-placement"),this.sortFeaturesByKey="viewport-y"!==$t&&!Nt.isConstant(),this.sortFeaturesByY=("viewport-y"===$t||"auto"===$t&&!this.sortFeaturesByKey)&&this.canOverlap,"point"===Wt.get("symbol-placement")&&(this.writingModes=Wt.get("text-writing-mode").map((et=>M.ai[et]))),this.stateDependentLayerIds=this.layers.filter((M=>M.isStateDependent())).map((M=>M.id)),this.sourceID=et.sourceID}createArrays(){this.text=new Sc(new ro(this.layers,this.zoom,(M=>/^text/.test(M)))),this.icon=new Sc(new ro(this.layers,this.zoom,(M=>/^icon/.test(M)))),this.glyphOffsetArray=new oa,this.lineVertexArray=new la,this.symbolInstances=new aa,this.textAnchorOffsets=new ca}calculateGlyphDependencies(M,et,Bt,Wt,Nt){for(let $t=0;$t0)&&("constant"!==Gr.value.kind||Gr.value.value.length>0),uo="constant"!==Hn.value.kind||!!Hn.value.value||Object.keys(Hn.parameters).length>0,Io=$t.get("symbol-sort-key");if(this.features=[],!so&&!uo)return;const Po=Bt.iconDependencies,To=Bt.glyphDependencies,Eo=Bt.availableImages,Ia=new cs(this.zoom);for(const{feature:Bt,id:mn,index:Hn,sourceLayerIndex:Ba}of et){const et=Nt._featureFilter.needGeometry,Ta=lo(Bt,et);if(!Nt._featureFilter.filter(Ia,Ta,Wt))continue;let Va,za;if(et||(Ta.geometry=oo(Bt)),so){const M=Nt.getValueAndResolveTokens("text-field",Ta,Wt,Eo),et=xe.factory(M),Bt=this.hasRTLText=this.hasRTLText||_c(et);(!Bt||"unavailable"===ag.getRTLTextPluginStatus()||Bt&&ag.isParsed())&&(Va=Pu(et,Nt,Ta))}if(uo){const M=Nt.getValueAndResolveTokens("icon-image",Ta,Wt,Eo);za=M instanceof Se?M:Se.fromString(M)}if(!Va&&!za)continue;const Fa=this.sortFeaturesByKey?Io.evaluate(Ta,{},Wt):void 0;if(this.features.push({id:mn,text:Va,icon:za,index:Hn,sourceLayerIndex:Ba,geometry:Ta.geometry,properties:Bt.properties,type:od[Bt.type],sortKey:Fa}),za&&(Po[za.name]=!0),Va){const et=Gr.evaluate(Ta,{},Wt).join(","),Bt="viewport"!==$t.get("text-rotation-alignment")&&"point"!==$t.get("symbol-placement");this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(M.ai.vertical)>=0;for(const M of Va.sections)if(M.image)Po[M.image.name]=!0;else{const Wt=Ji(Va.toString()),Nt=M.fontStack||et,$t=To[Nt]=To[Nt]||{};this.calculateGlyphDependencies(M.text,$t,Bt,this.allowVerticalPlacement,Wt)}}}"line"===$t.get("symbol-placement")&&(this.features=function(M){const et={},Bt={},Wt=[];let Nt=0;function s(et){Wt.push(M[et]),Nt++}function a(M,et,Nt){const $t=Bt[M];return delete Bt[M],Bt[et]=$t,Wt[$t].geometry[0].pop(),Wt[$t].geometry[0]=Wt[$t].geometry[0].concat(Nt[0]),$t}function o(M,Bt,Nt){const $t=et[Bt];return delete et[Bt],et[M]=$t,Wt[$t].geometry[0].shift(),Wt[$t].geometry[0]=Nt[0].concat(Wt[$t].geometry[0]),$t}function l(M,et,Bt){const Wt=Bt?et[0][et[0].length-1]:et[0][0];return`${M}:${Wt.x}:${Wt.y}`}for(let $t=0;$tM.geometry))}(this.features)),this.sortFeaturesByKey&&this.features.sort(((M,et)=>M.sortKey-et.sortKey))}update(M,et,Bt){this.stateDependentLayers.length&&(this.text.programConfigurations.updatePaintArrays(M,et,this.layers,Bt),this.icon.programConfigurations.updatePaintArrays(M,et,this.layers,Bt))}isEmpty(){return 0===this.symbolInstances.length&&!this.hasRTLText}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(M){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(M),this.iconCollisionBox.upload(M)),this.text.upload(M,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload),this.icon.upload(M,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload),this.uploaded=!0}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(M,et){const Bt=this.lineVertexArray.length;if(void 0!==M.segment){let Bt=M.dist(et[M.segment+1]),Wt=M.dist(et[M.segment]);const Nt={};for(let Wt=M.segment+1;Wt=0;Bt--)Nt[Bt]={x:et[Bt].x,y:et[Bt].y,tileUnitDistanceFromAnchor:Wt},Bt>0&&(Wt+=et[Bt-1].dist(et[Bt]));for(let M=0;M0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}addIndicesForPlacedSymbol(M,et){const Bt=M.placedSymbolArray.get(et),Wt=Bt.vertexStartIndex+4*Bt.numGlyphs;for(let et=Bt.vertexStartIndex;etWt[M]-Wt[et]||Nt[et]-Nt[M])),$t}addToSortKeyRanges(M,et){const Bt=this.sortKeyRanges[this.sortKeyRanges.length-1];Bt&&Bt.sortKey===et?Bt.symbolInstanceEnd=M+1:this.sortKeyRanges.push({sortKey:et,symbolInstanceStart:M,symbolInstanceEnd:M+1})}sortFeatures(M){if(this.sortFeaturesByY&&this.sortedAngle!==M&&!(this.text.segments.get().length>1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(M),this.sortedAngle=M,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const M of this.symbolInstanceIndexes){const et=this.symbolInstances.get(M);this.featureSortOrder.push(et.featureIndex),[et.rightJustifiedTextSymbolIndex,et.centerJustifiedTextSymbolIndex,et.leftJustifiedTextSymbolIndex].forEach(((M,et,Bt)=>{M>=0&&Bt.indexOf(M)===et&&this.addIndicesForPlacedSymbol(this.text,M)})),et.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,et.verticalPlacedTextSymbolIndex),et.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,et.placedIconSymbolIndex),et.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,et.verticalPlacedIconSymbolIndex)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}}let ad,ld;Ui("SymbolBucket",kc,{omit:["layers","collisionBoxArray","features","compareText"]}),kc.MAX_GLYPHS=65535,kc.addDynamicAttributes=wc;var cd={get paint(){return ld=ld||new As({"icon-opacity":new bs(Ka.paint_symbol["icon-opacity"]),"icon-color":new bs(Ka.paint_symbol["icon-color"]),"icon-halo-color":new bs(Ka.paint_symbol["icon-halo-color"]),"icon-halo-width":new bs(Ka.paint_symbol["icon-halo-width"]),"icon-halo-blur":new bs(Ka.paint_symbol["icon-halo-blur"]),"icon-translate":new vs(Ka.paint_symbol["icon-translate"]),"icon-translate-anchor":new vs(Ka.paint_symbol["icon-translate-anchor"]),"text-opacity":new bs(Ka.paint_symbol["text-opacity"]),"text-color":new bs(Ka.paint_symbol["text-color"],{runtimeType:Gl,getOverride:M=>M.textColor,hasOverride:M=>!!M.textColor}),"text-halo-color":new bs(Ka.paint_symbol["text-halo-color"]),"text-halo-width":new bs(Ka.paint_symbol["text-halo-width"]),"text-halo-blur":new bs(Ka.paint_symbol["text-halo-blur"]),"text-translate":new vs(Ka.paint_symbol["text-translate"]),"text-translate-anchor":new vs(Ka.paint_symbol["text-translate-anchor"])})},get layout(){return ad=ad||new As({"symbol-placement":new vs(Ka.layout_symbol["symbol-placement"]),"symbol-spacing":new vs(Ka.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new vs(Ka.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new bs(Ka.layout_symbol["symbol-sort-key"]),"symbol-z-order":new vs(Ka.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new vs(Ka.layout_symbol["icon-allow-overlap"]),"icon-overlap":new vs(Ka.layout_symbol["icon-overlap"]),"icon-ignore-placement":new vs(Ka.layout_symbol["icon-ignore-placement"]),"icon-optional":new vs(Ka.layout_symbol["icon-optional"]),"icon-rotation-alignment":new vs(Ka.layout_symbol["icon-rotation-alignment"]),"icon-size":new bs(Ka.layout_symbol["icon-size"]),"icon-text-fit":new vs(Ka.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new vs(Ka.layout_symbol["icon-text-fit-padding"]),"icon-image":new bs(Ka.layout_symbol["icon-image"]),"icon-rotate":new bs(Ka.layout_symbol["icon-rotate"]),"icon-padding":new bs(Ka.layout_symbol["icon-padding"]),"icon-keep-upright":new vs(Ka.layout_symbol["icon-keep-upright"]),"icon-offset":new bs(Ka.layout_symbol["icon-offset"]),"icon-anchor":new bs(Ka.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new vs(Ka.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new vs(Ka.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new vs(Ka.layout_symbol["text-rotation-alignment"]),"text-field":new bs(Ka.layout_symbol["text-field"]),"text-font":new bs(Ka.layout_symbol["text-font"]),"text-size":new bs(Ka.layout_symbol["text-size"]),"text-max-width":new bs(Ka.layout_symbol["text-max-width"]),"text-line-height":new vs(Ka.layout_symbol["text-line-height"]),"text-letter-spacing":new bs(Ka.layout_symbol["text-letter-spacing"]),"text-justify":new bs(Ka.layout_symbol["text-justify"]),"text-radial-offset":new bs(Ka.layout_symbol["text-radial-offset"]),"text-variable-anchor":new vs(Ka.layout_symbol["text-variable-anchor"]),"text-variable-anchor-offset":new bs(Ka.layout_symbol["text-variable-anchor-offset"]),"text-anchor":new bs(Ka.layout_symbol["text-anchor"]),"text-max-angle":new vs(Ka.layout_symbol["text-max-angle"]),"text-writing-mode":new vs(Ka.layout_symbol["text-writing-mode"]),"text-rotate":new bs(Ka.layout_symbol["text-rotate"]),"text-padding":new vs(Ka.layout_symbol["text-padding"]),"text-keep-upright":new vs(Ka.layout_symbol["text-keep-upright"]),"text-transform":new bs(Ka.layout_symbol["text-transform"]),"text-offset":new bs(Ka.layout_symbol["text-offset"]),"text-allow-overlap":new vs(Ka.layout_symbol["text-allow-overlap"]),"text-overlap":new vs(Ka.layout_symbol["text-overlap"]),"text-ignore-placement":new vs(Ka.layout_symbol["text-ignore-placement"]),"text-optional":new vs(Ka.layout_symbol["text-optional"])})}};class Pc{constructor(M){if(void 0===M.property.overrides)throw new Error("overrides must be provided to instantiate FormatSectionOverride class");this.type=M.property.overrides?M.property.overrides.runtimeType:$a,this.defaultValue=M}evaluate(M){if(M.formattedSection){const et=this.defaultValue.property.overrides;if(et&&et.hasOverride(M.formattedSection))return et.getOverride(M.formattedSection)}return M.feature&&M.featureState?this.defaultValue.evaluate(M.feature,M.featureState):this.defaultValue.property.specification.default}eachChild(M){this.defaultValue.isConstant()||M(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}Ui("FormatSectionOverride",Pc,{omit:["defaultValue"]});class Cc extends Ms{constructor(M){super(M,cd)}recalculate(M,et){if(super.recalculate(M,et),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]="map"===this.layout.get("text-rotation-alignment")?"map":"viewport"),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){const M=this.layout.get("text-writing-mode");if(M){const et=[];for(const Bt of M)et.indexOf(Bt)<0&&et.push(Bt);this.layout._values["text-writing-mode"]=et}else this.layout._values["text-writing-mode"]=["horizontal"]}this._setPaintOverrides()}getValueAndResolveTokens(M,et,Bt,Wt){const Nt=this.layout.get(M).evaluate(et,{},Bt,Wt),$t=this._unevaluatedLayout._values[M];return $t.isDataDriven()||jn($t.value)||!Nt?Nt:function(M,et){return et.replace(/{([^{}]+)}/g,((et,Bt)=>M&&Bt in M?String(M[Bt]):""))}(et.properties,Nt)}createBucket(M){return new kc(M)}queryRadius(){return 0}queryIntersectsFeature(){throw new Error("Should take a different path in FeatureIndex")}_setPaintOverrides(){for(const M of cd.paint.overridableProperties){if(!Cc.hasPaintOverride(this.layout,M))continue;const et=this.paint.get(M),Bt=new Pc(et),Wt=new Rn(Bt,et.property.specification);let Nt=null;Nt="constant"===et.value.kind||"source"===et.value.kind?new Un("source",Wt):new qn("composite",Wt,et.value.zoomStops),this.paint._values[M]=new gs(et.property,Nt,et.parameters)}}_handleOverridablePaintPropertyUpdate(M,et,Bt){return!(!this.layout||et.isDataDriven()||Bt.isDataDriven())&&Cc.hasPaintOverride(this.layout,M)}static hasPaintOverride(M,et){const Bt=M.get("text-field"),Wt=cd.paint.properties[et];let Nt=!1;const s=M=>{for(const et of M)if(Wt.overrides&&Wt.overrides.hasOverride(et))return void(Nt=!0)};if("constant"===Bt.value.kind&&Bt.value.value instanceof xe)s(Bt.value.value.sections);else if("source"===Bt.value.kind){const t=M=>{Nt||(M instanceof Pe&&Ie(M.value)===El?s(M.value.sections):M instanceof br?s(M.sections):M.eachChild(t))},M=Bt.value;M._styleExpression&&t(M._styleExpression.expression)}return Nt}}let hd;var gd={get paint(){return hd=hd||new As({"background-color":new vs(Ka.paint_background["background-color"]),"background-pattern":new _s(Ka.paint_background["background-pattern"]),"background-opacity":new vs(Ka.paint_background["background-opacity"])})}};class Ec extends Ms{constructor(M){super(M,gd)}}let ud;var dd={get paint(){return ud=ud||new As({"raster-opacity":new vs(Ka.paint_raster["raster-opacity"]),"raster-hue-rotate":new vs(Ka.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new vs(Ka.paint_raster["raster-brightness-min"]),"raster-brightness-max":new vs(Ka.paint_raster["raster-brightness-max"]),"raster-saturation":new vs(Ka.paint_raster["raster-saturation"]),"raster-contrast":new vs(Ka.paint_raster["raster-contrast"]),"raster-resampling":new vs(Ka.paint_raster["raster-resampling"]),"raster-fade-duration":new vs(Ka.paint_raster["raster-fade-duration"])})}};class $c extends Ms{constructor(M){super(M,dd)}}class Lc extends Ms{constructor(M){super(M,{}),this.onAdd=M=>{this.implementation.onAdd&&this.implementation.onAdd(M,M.painter.context.gl)},this.onRemove=M=>{this.implementation.onRemove&&this.implementation.onRemove(M,M.painter.context.gl)},this.implementation=M}is3D(){return"3d"===this.implementation.renderingMode}hasOffscreenPass(){return void 0!==this.implementation.prerender}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){throw new Error("Custom layers cannot be serialized")}}class Dc{constructor(M){this._methodToThrottle=M,this._triggered=!1,"undefined"!=typeof MessageChannel&&(this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{this._triggered=!1,this._methodToThrottle()})}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout((()=>{this._triggered=!1,this._methodToThrottle()}),0))}remove(){delete this._channel,this._methodToThrottle=()=>{}}}const pd=6371008.8;class Rc{constructor(M,et){if(isNaN(M)||isNaN(et))throw new Error(`Invalid LngLat object: (${M}, ${et})`);if(this.lng=+M,this.lat=+et,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new Rc(T(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(M){const et=Math.PI/180,Bt=this.lat*et,Wt=M.lat*et,Nt=Math.sin(Bt)*Math.sin(Wt)+Math.cos(Bt)*Math.cos(Wt)*Math.cos((M.lng-this.lng)*et);return pd*Math.acos(Math.min(Nt,1))}static convert(M){if(M instanceof Rc)return M;if(Array.isArray(M)&&(2===M.length||3===M.length))return new Rc(Number(M[0]),Number(M[1]));if(!Array.isArray(M)&&"object"==typeof M&&null!==M)return new Rc(Number("lng"in M?M.lng:M.lon),Number(M.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}const md=2*Math.PI*pd;function Nc(M){return md*Math.cos(M*Math.PI/180)}function Uc(M){return(180+M)/360}function qc(M){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+M*Math.PI/360)))/360}function Gc(M,et){return M/Nc(et)}function Zc(M){return 360/Math.PI*Math.atan(Math.exp((180-360*M)*Math.PI/180))-90}function Xc(M,et){return M*Nc(Zc(et))}class Kc{constructor(M,et,Bt=0){this.x=+M,this.y=+et,this.z=+Bt}static fromLngLat(M,et=0){const Bt=Rc.convert(M);return new Kc(Uc(Bt.lng),qc(Bt.lat),Gc(et,Bt.lat))}toLngLat(){return new Rc(360*this.x-180,Zc(this.y))}toAltitude(){return Xc(this.z,this.y)}meterInMercatorCoordinateUnits(){return 1/md*(M=Zc(this.y),1/Math.cos(M*Math.PI/180));var M}}function Hc(M,et,Bt){var Wt=2*Math.PI*6378137/256/Math.pow(2,Bt);return[M*Wt-2*Math.PI*6378137/2,et*Wt-2*Math.PI*6378137/2]}class Yc{constructor(M,et,Bt){if(!function(M,et,Bt){return!(M<0||M>25||Bt<0||Bt>=Math.pow(2,M)||et<0||et>=Math.pow(2,M))}(M,et,Bt))throw new Error(`x=${et}, y=${Bt}, z=${M} outside of bounds. 0<=x<${Math.pow(2,M)}, 0<=y<${Math.pow(2,M)} 0<=z<=25 `);this.z=M,this.x=et,this.y=Bt,this.key=Qc(0,M,M,et,Bt)}equals(M){return this.z===M.z&&this.x===M.x&&this.y===M.y}url(M,et,Bt){const Wt=($t=this.y,Gr=this.z,mn=Hc(256*(Nt=this.x),256*($t=Math.pow(2,Gr)-$t-1),Gr),Hn=Hc(256*(Nt+1),256*($t+1),Gr),mn[0]+","+mn[1]+","+Hn[0]+","+Hn[1]);var Nt,$t,Gr,mn,Hn;const so=function(M,et,Bt){let Wt,Nt="";for(let $t=M;$t>0;$t--)Wt=1<<$t-1,Nt+=(et&Wt?1:0)+(Bt&Wt?2:0);return Nt}(this.z,this.x,this.y);return M[(this.x+this.y)%M.length].replace(/{prefix}/g,(this.x%16).toString(16)+(this.y%16).toString(16)).replace(/{z}/g,String(this.z)).replace(/{x}/g,String(this.x)).replace(/{y}/g,String("tms"===Bt?Math.pow(2,this.z)-this.y-1:this.y)).replace(/{ratio}/g,et>1?"@2x":"").replace(/{quadkey}/g,so).replace(/{bbox-epsg-3857}/g,Wt)}isChildOf(M){const et=this.z-M.z;return et>0&&M.x===this.x>>et&&M.y===this.y>>et}getTilePoint(M){const et=Math.pow(2,this.z);return new $t((M.x*et-this.x)*To,(M.y*et-this.y)*To)}toString(){return`${this.z}/${this.x}/${this.y}`}}class Jc{constructor(M,et){this.wrap=M,this.canonical=et,this.key=Qc(M,et.z,et.z,et.x,et.y)}}class Wc{constructor(M,et,Bt,Wt,Nt){if(this.terrainRttPosMatrix32f=null,M= z; overscaledZ = ${M}; z = ${Bt}`);this.overscaledZ=M,this.wrap=et,this.canonical=new Yc(Bt,+Wt,+Nt),this.key=Qc(et,M,Bt,Wt,Nt)}clone(){return new Wc(this.overscaledZ,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)}equals(M){return this.overscaledZ===M.overscaledZ&&this.wrap===M.wrap&&this.canonical.equals(M.canonical)}scaledTo(M){if(M>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${M}; overscaledZ = ${this.overscaledZ}`);const et=this.canonical.z-M;return M>this.canonical.z?new Wc(M,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new Wc(M,this.wrap,M,this.canonical.x>>et,this.canonical.y>>et)}calculateScaledKey(M,et){if(M>this.overscaledZ)throw new Error(`targetZ > this.overscaledZ; targetZ = ${M}; overscaledZ = ${this.overscaledZ}`);const Bt=this.canonical.z-M;return M>this.canonical.z?Qc(this.wrap*+et,M,this.canonical.z,this.canonical.x,this.canonical.y):Qc(this.wrap*+et,M,M,this.canonical.x>>Bt,this.canonical.y>>Bt)}isChildOf(M){if(M.wrap!==this.wrap)return!1;const et=this.canonical.z-M.canonical.z;return 0===M.overscaledZ||M.overscaledZ>et&&M.canonical.y===this.canonical.y>>et}children(M){if(this.overscaledZ>=M)return[new Wc(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const et=this.canonical.z+1,Bt=2*this.canonical.x,Wt=2*this.canonical.y;return[new Wc(et,this.wrap,et,Bt,Wt),new Wc(et,this.wrap,et,Bt+1,Wt),new Wc(et,this.wrap,et,Bt,Wt+1),new Wc(et,this.wrap,et,Bt+1,Wt+1)]}isLessThan(M){return this.wrapM.wrap)&&(this.overscaledZM.overscaledZ)&&(this.canonical.xM.canonical.x)&&this.canonical.ythis.max&&(this.max=Bt),Bt=this.dim+1||et<-1||et>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(et+1)*this.stride+(M+1)}unpack(M,et,Bt){return M*this.redFactor+et*this.greenFactor+Bt*this.blueFactor-this.baseShift}getPixels(){return new Oo({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))}backfillBorder(M,et,Bt){if(this.dim!==M.dim)throw new Error("dem dimension mismatch");let Wt=et*this.dim,Nt=et*this.dim+this.dim,$t=Bt*this.dim,Gr=Bt*this.dim+this.dim;switch(et){case-1:Wt=Nt-1;break;case 1:Nt=Wt+1}switch(Bt){case-1:$t=Gr-1;break;case 1:Gr=$t+1}const mn=-et*this.dim,Hn=-Bt*this.dim;for(let et=$t;et=this._numberToString.length)throw new Error(`Out of bounds. Index requested n=${M} can't be >= this._numberToString.length ${this._numberToString.length}`);return this._numberToString[M]}}class rh{constructor(M,et,Bt,Wt,Nt){this.type="Feature",this._vectorTileFeature=M,M._z=et,M._x=Bt,M._y=Wt,this.properties=M.properties,this.id=Nt}get geometry(){return void 0===this._geometry&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x,this._vectorTileFeature._y,this._vectorTileFeature._z).geometry),this._geometry}set geometry(M){this._geometry=M}toJSON(){const M={geometry:this.geometry};for(const et in this)"_geometry"!==et&&"_vectorTileFeature"!==et&&(M[et]=this[et]);return M}}class nh{constructor(M,et){this.tileID=M,this.x=M.canonical.x,this.y=M.canonical.y,this.z=M.canonical.z,this.grid=new ji(To,16,0),this.grid3D=new ji(To,16,0),this.featureIndexArray=new pa,this.promoteId=et}insert(M,et,Bt,Wt,Nt,$t){const Gr=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(Bt,Wt,Nt);const mn=$t?this.grid3D:this.grid;for(let M=0;M=0&&Wt[3]>=0&&mn.insert(Gr,Wt[0],Wt[1],Wt[2],Wt[3])}}loadVTLayers(){return this.vtLayers||(this.vtLayers=new Qg.VectorTile(new Eu(this.rawTileData)).layers,this.sourceLayerCoder=new eh(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers}query(M,et,Bt,Wt){this.loadVTLayers();const Nt=M.params,Gr=To/M.tileSize/M.scale,mn=Yn(Nt.filter),Hn=M.queryGeometry,so=M.queryPadding*Gr,uo=sh(Hn),Io=this.grid.query(uo.minX-so,uo.minY-so,uo.maxX+so,uo.maxY+so),Po=sh(M.cameraQueryGeometry),Eo=this.grid3D.query(Po.minX-so,Po.minY-so,Po.maxX+so,Po.maxY+so,((et,Bt,Wt,Nt)=>function(M,et,Bt,Wt,Nt){for(const $t of M)if(et<=$t.x&&Bt<=$t.y&&Wt>=$t.x&&Nt>=$t.y)return!0;const Gr=[new $t(et,Bt),new $t(et,Nt),new $t(Wt,Nt),new $t(Wt,Bt)];if(M.length>2)for(const et of Gr)if(_o(M,et))return!0;for(let et=0;et(Po||(Po=oo(et)),Bt.queryIntersectsFeature({queryGeometry:Hn,feature:et,featureState:Wt,geometry:Po,zoom:this.z,transform:M.transform,pixelsToTileUnits:Gr,pixelPosMatrix:M.pixelPosMatrix}))))}return Ia}loadMatchingFeature(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo){const Io=this.bucketLayerIDs[et];if($t&&!Io.some((M=>$t.has(M))))return;const Po=this.sourceLayerCoder.decode(Bt),To=this.vtLayers[Po].feature(Wt);if(Nt.needGeometry){const M=lo(To,!0);if(!Nt.filter(new cs(this.tileID.overscaledZ),M,this.tileID.canonical))return}else if(!Nt.filter(new cs(this.tileID.overscaledZ),To))return;const Eo=this.getId(To,Po);for(let et=0;et{const Gr=et instanceof xs?et.get($t):null;return Gr&&Gr.evaluate?Gr.evaluate(Bt,Wt,Nt):Gr}))}function sh(M){let et=1/0,Bt=1/0,Wt=-1/0,Nt=-1/0;for(const $t of M)et=Math.min(et,$t.x),Bt=Math.min(Bt,$t.y),Wt=Math.max(Wt,$t.x),Nt=Math.max(Nt,$t.y);return{minX:et,minY:Bt,maxX:Wt,maxY:Nt}}function ah(M,et){return et-M}function oh(M,et,Bt,Wt,Nt){const Gr=[];for(let mn=0;mn=Wt&&uo.x>=Wt||(mn.x>=Wt?mn=new $t(Wt,mn.y+(Wt-mn.x)/(uo.x-mn.x)*(uo.y-mn.y))._round():uo.x>=Wt&&(uo=new $t(Wt,mn.y+(Wt-mn.x)/(uo.x-mn.x)*(uo.y-mn.y))._round()),mn.y>=Nt&&uo.y>=Nt||(mn.y>=Nt?mn=new $t(mn.x+(Nt-mn.y)/(uo.y-mn.y)*(uo.x-mn.x),Nt)._round():uo.y>=Nt&&(uo=new $t(mn.x+(Nt-mn.y)/(uo.y-mn.y)*(uo.x-mn.x),Nt)._round()),so&&mn.equals(so[so.length-1])||(so=[mn],Gr.push(so)),so.push(uo)))))}}return Gr}Ui("FeatureIndex",nh,{omit:["rawTileData","sourceLayerCoder"]});class lh extends $t{constructor(M,et,Bt,Wt){super(M,et),this.angle=Bt,void 0!==Wt&&(this.segment=Wt)}clone(){return new lh(this.x,this.y,this.angle,this.segment)}}function uh(M,et,Bt,Wt,Nt){if(void 0===et.segment||0===Bt)return!0;let $t=et,Gr=et.segment+1,mn=0;for(;mn>-Bt/2;){if(Gr--,Gr<0)return!1;mn-=M[Gr].dist($t),$t=M[Gr]}mn+=M[Gr].dist(M[Gr+1]),Gr++;const Hn=[];let so=0;for(;mnWt;)so-=Hn.shift().angleDelta;if(so>Nt)return!1;Gr++,mn+=et.dist(Bt)}return!0}function ch(M){let et=0;for(let Bt=0;Btso){const uo=(so-Hn)/$t,Io=zc.number(Wt.x,Nt.x,uo),Po=zc.number(Wt.y,Nt.y,uo),To=new lh(Io,Po,Nt.angleTo(Wt),Bt);return To._round(),!Gr||uh(M,To,mn,Gr,et)?To:void 0}Hn+=$t}}function dh(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn){const so=hh(Wt,$t,Gr),uo=ph(Wt,Nt),Io=uo*Gr,Po=0===M[0].x||M[0].x===Hn||0===M[0].y||M[0].y===Hn;return et-Io=0&&Ta=0&&Va=0&&Po+so<=uo){const Bt=new lh(Ta,Va,Ia,et);Bt._round(),Wt&&!uh(M,Bt,$t,Wt,Nt)||To.push(Bt)}}Io+=Eo}return mn||To.length||Gr||(To=yh(M,Io/2,Bt,Wt,Nt,$t,Gr,!0,Hn)),To}Ui("Anchor",lh);const Cd=Ku;function gh(M,et,Bt,Wt){const Nt=[],Gr=M.image,mn=Gr.pixelRatio,Hn=Gr.paddedRect.w-2*Cd,so=Gr.paddedRect.h-2*Cd;let uo={x1:M.left,y1:M.top,x2:M.right,y2:M.bottom};const Io=Gr.stretchX||[[0,Hn]],Po=Gr.stretchY||[[0,so]],f=(M,et)=>M+et[1]-et[0],To=Io.reduce(f,0),Eo=Po.reduce(f,0),Ia=Hn-To,Ba=so-Eo;let Ta=0,Va=To,za=0,Fa=Eo,Ea=0,La=Ia,Da=0,Ka=Ba;if(Gr.content&&Wt){const et=Gr.content,Bt=et[2]-et[0],Wt=et[3]-et[1];(Gr.textFitWidth||Gr.textFitHeight)&&(uo=hc(M)),Ta=xh(Io,0,et[0]),za=xh(Po,0,et[1]),Va=xh(Io,et[0],et[2]),Fa=xh(Po,et[1],et[3]),Ea=et[0]-Ta,Da=et[1]-za,La=Bt-Va,Ka=Wt-Fa}const Oa=uo.x1,$a=uo.y1,Al=uo.x2-Oa,Sl=uo.y2-$a,C=(M,Wt,Nt,Hn)=>{const so=bh(M.stretch-Ta,Va,Al,Oa),uo=wh(M.fixed-Ea,La,M.stretch,To),Io=bh(Wt.stretch-za,Fa,Sl,$a),Po=wh(Wt.fixed-Da,Ka,Wt.stretch,Eo),Ia=bh(Nt.stretch-Ta,Va,Al,Oa),Ba=wh(Nt.fixed-Ea,La,Nt.stretch,To),Zl=bh(Hn.stretch-za,Fa,Sl,$a),Gl=wh(Hn.fixed-Da,Ka,Hn.stretch,Eo),Rl=new $t(so,Io),Tl=new $t(Ia,Io),Vl=new $t(Ia,Zl),Wl=new $t(so,Zl),El=new $t(uo/mn,Po/mn),Jl=new $t(Ba/mn,Gl/mn),Ll=et*Math.PI/180;if(Ll){const M=Math.sin(Ll),et=Math.cos(Ll),Bt=[et,-M,M,et];Rl._matMult(Bt),Tl._matMult(Bt),Wl._matMult(Bt),Vl._matMult(Bt)}const Dl=M.stretch+M.fixed,Nl=Wt.stretch+Wt.fixed;return{tl:Rl,tr:Tl,bl:Wl,br:Vl,tex:{x:Gr.paddedRect.x+Cd+Dl,y:Gr.paddedRect.y+Cd+Nl,w:Nt.stretch+Nt.fixed-Dl,h:Hn.stretch+Hn.fixed-Nl},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:El,pixelOffsetBR:Jl,minFontScaleX:La/mn/Al,minFontScaleY:Ka/mn/Sl,isSDF:Bt}};if(Wt&&(Gr.stretchX||Gr.stretchY)){const M=vh(Io,Ia,To),et=vh(Po,Ba,Eo);for(let Bt=0;Bt0&&(Wt=Math.max(10,Wt),this.circleDiameter=Wt)}else{const so=(null===(Io=Gr.image)||void 0===Io?void 0:Io.content)&&(Gr.image.textFitWidth||Gr.image.textFitHeight)?hc(Gr):{x1:Gr.left,y1:Gr.top,x2:Gr.right,y2:Gr.bottom};so.y1=so.y1*mn-Hn[0],so.y2=so.y2*mn+Hn[2],so.x1=so.x1*mn-Hn[3],so.x2=so.x2*mn+Hn[1];const Po=Gr.collisionPadding;if(Po&&(so.x1-=Po[0]*mn,so.y1-=Po[1]*mn,so.x2+=Po[2]*mn,so.y2+=Po[3]*mn),uo){const M=new $t(so.x1,so.y1),et=new $t(so.x2,so.y1),Bt=new $t(so.x1,so.y2),Wt=new $t(so.x2,so.y2),Nt=uo*Math.PI/180;M._rotate(Nt),et._rotate(Nt),Bt._rotate(Nt),Wt._rotate(Nt),so.x1=Math.min(M.x,et.x,Bt.x,Wt.x),so.x2=Math.max(M.x,et.x,Bt.x,Wt.x),so.y1=Math.min(M.y,et.y,Bt.y,Wt.y),so.y2=Math.max(M.y,et.y,Bt.y,Wt.y)}M.emplaceBack(et.x,et.y,so.x1,so.y1,so.x2,so.y2,Bt,Wt,Nt)}this.boxEndIndex=M.length}}class Sh{constructor(M=[],et=(M,et)=>Met?1:0){if(this.data=M,this.length=this.data.length,this.compare=et,this.length>0)for(let M=(this.length>>1)-1;M>=0;M--)this._down(M)}push(M){this.data.push(M),this._up(this.length++)}pop(){if(0===this.length)return;const M=this.data[0],et=this.data.pop();return--this.length>0&&(this.data[0]=et,this._down(0)),M}peek(){return this.data[0]}_up(M){const{data:et,compare:Bt}=this,Wt=et[M];for(;M>0;){const Nt=M-1>>1,$t=et[Nt];if(Bt(Wt,$t)>=0)break;et[M]=$t,M=Nt}et[M]=Wt}_down(M){const{data:et,compare:Bt}=this,Wt=this.length>>1,Nt=et[M];for(;M=0)break;et[M]=et[Wt],M=Wt}et[M]=Nt}}function Ah(M,et=1,Bt=!1){let Wt=1/0,Nt=1/0,Gr=-1/0,mn=-1/0;const Hn=M[0];for(let M=0;MGr)&&(Gr=et.x),(!M||et.y>mn)&&(mn=et.y)}const so=Math.min(Gr-Wt,mn-Nt);let uo=so/2;const Io=new Sh([],kh);if(0===so)return new $t(Wt,Nt);for(let et=Wt;etPo.d||!Po.d)&&(Po=Wt,Bt&&console.log("found best %d after %d probes",Math.round(1e4*Wt.d)/1e4,To)),Wt.max-Po.d<=et||(uo=Wt.h/2,Io.push(new Mh(Wt.p.x-uo,Wt.p.y-uo,uo,M)),Io.push(new Mh(Wt.p.x+uo,Wt.p.y-uo,uo,M)),Io.push(new Mh(Wt.p.x-uo,Wt.p.y+uo,uo,M)),Io.push(new Mh(Wt.p.x+uo,Wt.p.y+uo,uo,M)),To+=4)}return Bt&&(console.log(`num probes: ${To}`),console.log(`best distance: ${Po.d}`)),Po.p}function kh(M,et){return et.max-M.max}function Mh(M,et,Bt,Wt){this.p=new $t(M,et),this.h=Bt,this.d=function(M,et){let Bt=!1,Wt=1/0;for(let Nt=0;NtM.y!=mn.y>M.y&&M.x<(mn.x-Nt.x)*(M.y-Nt.y)/(mn.y-Nt.y)+Nt.x&&(Bt=!Bt),Wt=Math.min(Wt,bo(M,Nt,mn))}}return(Bt?1:-1)*Math.sqrt(Wt)}(this.p,Wt),this.max=this.d+this.h*Math.SQRT2}var Id;M.av=void 0,(Id=M.av||(M.av={}))[Id.center=1]="center",Id[Id.left=2]="left",Id[Id.right=3]="right",Id[Id.top=4]="top",Id[Id.bottom=5]="bottom",Id[Id["top-left"]=6]="top-left",Id[Id["top-right"]=7]="top-right",Id[Id["bottom-left"]=8]="bottom-left",Id[Id["bottom-right"]=9]="bottom-right";const fd=7,yd=Number.POSITIVE_INFINITY;function Ch(M,et){return et[1]!==yd?function(M,et,Bt){let Wt=0,Nt=0;switch(et=Math.abs(et),Bt=Math.abs(Bt),M){case"top-right":case"top-left":case"top":Nt=Bt-fd;break;case"bottom-right":case"bottom-left":case"bottom":Nt=-Bt+fd}switch(M){case"top-right":case"bottom-right":case"right":Wt=-et;break;case"top-left":case"bottom-left":case"left":Wt=et}return[Wt,Nt]}(M,et[0],et[1]):function(M,et){let Bt=0,Wt=0;et<0&&(et=0);const Nt=et/Math.SQRT2;switch(M){case"top-right":case"top-left":Wt=Nt-fd;break;case"bottom-right":case"bottom-left":Wt=-Nt+fd;break;case"bottom":Wt=-et+fd;break;case"top":Wt=et-fd}switch(M){case"top-right":case"bottom-right":Bt=-Nt;break;case"top-left":case"bottom-left":Bt=Nt;break;case"left":Bt=et;break;case"right":Bt=-et}return[Bt,Wt]}(M,et[0])}function Bh(M,et,Bt){var Wt;const Nt=M.layout,$t=null===(Wt=Nt.get("text-variable-anchor-offset"))||void 0===Wt?void 0:Wt.evaluate(et,{},Bt);if($t){const M=$t.values,et=[];for(let Bt=0;BtM*zu));Wt.startsWith("top")?Nt[1]-=fd:Wt.startsWith("bottom")&&(Nt[1]+=fd),et[Bt+1]=Nt}return new _e(et)}const Gr=Nt.get("text-variable-anchor");if(Gr){let Wt;Wt=void 0!==M._unevaluatedLayout.getValue("text-radial-offset")?[Nt.get("text-radial-offset").evaluate(et,{},Bt)*zu,yd]:Nt.get("text-offset").evaluate(et,{},Bt).map((M=>M*zu));const $t=[];for(const M of Gr)$t.push(M,Ch(M,Wt));return new _e($t)}return null}function Vh(M){switch(M){case"right":case"top-right":case"bottom-right":return"right";case"left":case"top-left":case"bottom-left":return"left"}return"center"}function Eh(et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po){let Eo=Gr.textMaxSize.evaluate(Bt,{});void 0===Eo&&(Eo=mn);const Ia=et.layers[0].layout,Ba=Ia.get("icon-offset").evaluate(Bt,{},Io),Ta=Fh(Wt.horizontal),Va=mn/24,za=et.tilePixelRatio*Va,Fa=et.tilePixelRatio*Eo/24,Ea=et.tilePixelRatio*Hn,La=et.tilePixelRatio*Ia.get("symbol-spacing"),Da=Ia.get("text-padding")*et.tilePixelRatio,Ka=function(M,et,Bt,Wt=1){const Nt=M.get("icon-padding").evaluate(et,{},Bt),$t=Nt&&Nt.values;return[$t[0]*Wt,$t[1]*Wt,$t[2]*Wt,$t[3]*Wt]}(Ia,Bt,Io,et.tilePixelRatio),Oa=Ia.get("text-max-angle")/180*Math.PI,$a="viewport"!==Ia.get("text-rotation-alignment")&&"point"!==Ia.get("symbol-placement"),Al="map"===Ia.get("icon-rotation-alignment")&&"point"!==Ia.get("symbol-placement"),Sl=Ia.get("symbol-placement"),Zl=La/2,Gl=Ia.get("icon-text-fit");let Rl;Nt&&"none"!==Gl&&(et.allowVerticalPlacement&&Wt.vertical&&(Rl=pc(Nt,Wt.vertical,Gl,Ia.get("icon-text-fit-padding"),Ba,Va)),Ta&&(Nt=pc(Nt,Ta,Gl,Ia.get("icon-text-fit-padding"),Ba,Va)));const Tl=Io?Po.line.getGranularityForZoomLevel(Io.z):1,E=(Hn,Po)=>{Po.x<0||Po.x>=To||Po.y<0||Po.y>=To||function(et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba,Ta,Va,za,Fa,Ea,La,Da,Ka,Oa){const $a=et.addToLineVertexArray(Bt,Wt);let Al,Sl,Zl,Gl,Rl=0,Tl=0,Vl=0,Wl=0,El=-1,Jl=-1;const Ll={};let Dl=Ag("");if(et.allowVerticalPlacement&&Nt.vertical){const M=Hn.layout.get("text-rotate").evaluate(Ea,{},Ka)+90;Zl=new _h(so,Bt,uo,Io,Po,Nt.vertical,To,Eo,Ia,M),mn&&(Gl=new _h(so,Bt,uo,Io,Po,mn,Ta,Va,Ia,M))}if($t){const Wt=Hn.layout.get("icon-rotate").evaluate(Ea,{}),Nt="none"!==Hn.layout.get("icon-text-fit"),Gr=gh($t,Wt,Da,Nt),To=mn?gh(mn,Wt,Da,Nt):void 0;Sl=new _h(so,Bt,uo,Io,Po,$t,Ta,Va,!1,Wt),Rl=4*Gr.length;const Eo=et.iconSizeData;let Ia=null;"source"===Eo.kind?(Ia=[rd*Hn.layout.get("icon-size").evaluate(Ea,{})],Ia[0]>nd&&j(`${et.layerIds[0]}: Value for "icon-size" is >= ${id}. Reduce your "icon-size".`)):"composite"===Eo.kind&&(Ia=[rd*La.compositeIconSizes[0].evaluate(Ea,{},Ka),rd*La.compositeIconSizes[1].evaluate(Ea,{},Ka)],(Ia[0]>nd||Ia[1]>nd)&&j(`${et.layerIds[0]}: Value for "icon-size" is >= ${id}. Reduce your "icon-size".`)),et.addSymbols(et.icon,Gr,Ia,Fa,za,Ea,M.ai.none,Bt,$a.lineStartIndex,$a.lineLength,-1,Ka),El=et.icon.placedSymbolArray.length-1,To&&(Tl=4*To.length,et.addSymbols(et.icon,To,Ia,Fa,za,Ea,M.ai.vertical,Bt,$a.lineStartIndex,$a.lineLength,-1,Ka),Jl=et.icon.placedSymbolArray.length-1)}const Nl=Object.keys(Nt.horizontal);for(const Wt of Nl){const $t=Nt.horizontal[Wt];if(!Al){Dl=Ag($t.text);const M=Hn.layout.get("text-rotate").evaluate(Ea,{},Ka);Al=new _h(so,Bt,uo,Io,Po,$t,To,Eo,Ia,M)}const mn=1===$t.positionedLines.length;if(Vl+=Th(et,Bt,$t,Gr,Hn,Ia,Ea,Ba,$a,Nt.vertical?M.ai.horizontal:M.ai.horizontalOnly,mn?Nl:[Wt],Ll,El,La,Ka),mn)break}Nt.vertical&&(Wl+=Th(et,Bt,Nt.vertical,Gr,Hn,Ia,Ea,Ba,$a,M.ai.vertical,["vertical"],Ll,Jl,La,Ka));const Yl=Al?Al.boxStartIndex:et.collisionBoxArray.length,Ol=Al?Al.boxEndIndex:et.collisionBoxArray.length,jl=Zl?Zl.boxStartIndex:et.collisionBoxArray.length,Ul=Zl?Zl.boxEndIndex:et.collisionBoxArray.length,ql=Sl?Sl.boxStartIndex:et.collisionBoxArray.length,$l=Sl?Sl.boxEndIndex:et.collisionBoxArray.length,tc=Gl?Gl.boxStartIndex:et.collisionBoxArray.length,ec=Gl?Gl.boxEndIndex:et.collisionBoxArray.length;let dc=-1;const Y=(M,et)=>M&&M.circleDiameter?Math.max(M.circleDiameter,et):et;dc=Y(Al,dc),dc=Y(Zl,dc),dc=Y(Sl,dc),dc=Y(Gl,dc);const Ic=dc>-1?1:0;Ic&&(dc*=Oa/zu),et.glyphOffsetArray.length>=kc.MAX_GLYPHS&&j("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),void 0!==Ea.sortKey&&et.addToSortKeyRanges(et.symbolInstances.length,Ea.sortKey);const fc=Bh(Hn,Ea,Ka),[yc,vc]=function(et,Bt){const Wt=et.length,Nt=null==Bt?void 0:Bt.values;if((null==Nt?void 0:Nt.length)>0)for(let Bt=0;Bt=0?Ll.right:-1,Ll.center>=0?Ll.center:-1,Ll.left>=0?Ll.left:-1,Ll.vertical||-1,El,Jl,Dl,Yl,Ol,jl,Ul,ql,$l,tc,ec,uo,Vl,Wl,Rl,Tl,Ic,0,To,dc,yc,vc)}(et,Po,Hn,Wt,Nt,$t,Rl,et.layers[0],et.collisionBoxArray,Bt.index,Bt.sourceLayerIndex,et.index,za,[Da,Da,Da,Da],$a,so,Ea,Ka,Al,Ba,Bt,Gr,uo,Io,mn)};if("line"===Sl)for(const M of oh(Bt.geometry,0,0,To,To)){const Bt=Il(M,Tl),$t=dh(Bt,La,Oa,Wt.vertical||Ta,Nt,24,Fa,et.overscaling,To);for(const M of $t)Ta&&$h(et,Ta.text,Zl,M)||E(Bt,M)}else if("line-center"===Sl){for(const M of Bt.geometry)if(M.length>1){const et=Il(M,Tl),Bt=fh(et,Oa,Wt.vertical||Ta,Nt,24,Fa);Bt&&E(et,Bt)}}else if("Polygon"===Bt.type)for(const M of Le(Bt.geometry,0)){const et=Ah(M,16);E(Il(M[0],Tl,!0),new lh(et.x,et.y,0))}else if("LineString"===Bt.type)for(const M of Bt.geometry){const et=Il(M,Tl);E(et,new lh(et[0].x,et[0].y,0))}else if("Point"===Bt.type)for(const M of Bt.geometry)for(const et of M)E([et],new lh(et.x,et.y,0))}function Th(M,et,Bt,Wt,Nt,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia){const Ba=function(M,et,Bt,Wt,Nt,Gr,mn,Hn){const so=Wt.layout.get("text-rotate").evaluate(Gr,{})*Math.PI/180,uo=[];for(const M of et.positionedLines)for(const Wt of M.positionedGlyphs){if(!Wt.rect)continue;const Gr=Wt.rect||{};let Io=Hu+1,Po=!0,To=1,Eo=0;const Ia=(Nt||Hn)&&Wt.vertical,Ba=Wt.metrics.advance*Wt.scale/2;if(Hn&&et.verticalizable&&(Eo=M.lineOffset/2-(Wt.imageName?-(zu-Wt.metrics.width*Wt.scale)/2:(Wt.scale-1)*zu)),Wt.imageName){const M=mn[Wt.imageName];Po=M.sdf,To=M.pixelRatio,Io=Ku/To}const Ta=Nt?[Wt.x+Ba,Wt.y]:[0,0];let Va=Nt?[0,0]:[Wt.x+Ba+Bt[0],Wt.y+Bt[1]-Eo],za=[0,0];Ia&&(za=Va,Va=[0,0]);const Fa=Wt.metrics.isDoubleResolution?2:1,Ea=(Wt.metrics.left-Io)*Wt.scale-Ba+Va[0],La=(-Wt.metrics.top-Io)*Wt.scale+Va[1],Da=Ea+Gr.w/Fa*Wt.scale/To,Ka=La+Gr.h/Fa*Wt.scale/To,Oa=new $t(Ea,La),$a=new $t(Da,La),Al=new $t(Ea,Ka),Sl=new $t(Da,Ka);if(Ia){const M=new $t(-Ba,Ba-Uu),et=-Math.PI/2,Bt=zu/2-Ba,Nt=new $t(5-Uu-Bt,-(Wt.imageName?Bt:0)),Gr=new $t(...za);Oa._rotateAround(et,M)._add(Nt)._add(Gr),$a._rotateAround(et,M)._add(Nt)._add(Gr),Al._rotateAround(et,M)._add(Nt)._add(Gr),Sl._rotateAround(et,M)._add(Nt)._add(Gr)}if(so){const M=Math.sin(so),et=Math.cos(so),Bt=[et,-M,M,et];Oa._matMult(Bt),$a._matMult(Bt),Al._matMult(Bt),Sl._matMult(Bt)}const Zl=new $t(0,0),Gl=new $t(0,0);uo.push({tl:Oa,tr:$a,bl:Al,br:Sl,tex:Gr,writingMode:et.writingMode,glyphOffset:Ta,sectionIndex:Wt.sectionIndex,isSDF:Po,pixelOffsetTL:Zl,pixelOffsetBR:Gl,minFontScaleX:0,minFontScaleY:0})}return uo}(0,Bt,Hn,Nt,Gr,mn,Wt,M.allowVerticalPlacement),Ta=M.textSizeData;let Va=null;"source"===Ta.kind?(Va=[rd*Nt.layout.get("text-size").evaluate(mn,{})],Va[0]>nd&&j(`${M.layerIds[0]}: Value for "text-size" is >= ${id}. Reduce your "text-size".`)):"composite"===Ta.kind&&(Va=[rd*Eo.compositeTextSizes[0].evaluate(mn,{},Ia),rd*Eo.compositeTextSizes[1].evaluate(mn,{},Ia)],(Va[0]>nd||Va[1]>nd)&&j(`${M.layerIds[0]}: Value for "text-size" is >= ${id}. Reduce your "text-size".`)),M.addSymbols(M.text,Ba,Va,Hn,Gr,mn,uo,et,so.lineStartIndex,so.lineLength,To,Ia);for(const et of Io)Po[et]=M.text.placedSymbolArray.length-1;return 4*Ba.length}function Fh(M){for(const et in M)return M[et];return null}function $h(M,et,Bt,Wt){const Nt=M.compareText;if(et in Nt){const M=Nt[et];for(let et=M.length-1;et>=0;et--)if(Wt.dist(M[et])>4;if(1!==Wt)throw new Error(`Got v${Wt} data when expected v1.`);const Nt=Ad[15&Bt];if(!Nt)throw new Error("Unrecognized array type.");const[$t]=new Uint16Array(M,2,1),[Gr]=new Uint32Array(M,4,1);return new Dh(Gr,$t,Nt,M)}constructor(M,et=64,Bt=Float64Array,Wt){if(isNaN(M)||M<0)throw new Error(`Unpexpected numItems value: ${M}.`);this.numItems=+M,this.nodeSize=Math.min(Math.max(+et,2),65535),this.ArrayType=Bt,this.IndexArrayType=M<65536?Uint16Array:Uint32Array;const Nt=Ad.indexOf(this.ArrayType),$t=2*M*this.ArrayType.BYTES_PER_ELEMENT,Gr=M*this.IndexArrayType.BYTES_PER_ELEMENT,mn=(8-Gr%8)%8;if(Nt<0)throw new Error(`Unexpected typed array class: ${Bt}.`);Wt&&Wt instanceof ArrayBuffer?(this.data=Wt,this.ids=new this.IndexArrayType(this.data,8,M),this.coords=new this.ArrayType(this.data,8+Gr+mn,2*M),this._pos=2*M,this._finished=!0):(this.data=new ArrayBuffer(8+$t+Gr+mn),this.ids=new this.IndexArrayType(this.data,8,M),this.coords=new this.ArrayType(this.data,8+Gr+mn,2*M),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+Nt]),new Uint16Array(this.data,2,1)[0]=et,new Uint32Array(this.data,4,1)[0]=M)}add(M,et){const Bt=this._pos>>1;return this.ids[Bt]=Bt,this.coords[this._pos++]=M,this.coords[this._pos++]=et,Bt}finish(){const M=this._pos>>1;if(M!==this.numItems)throw new Error(`Added ${M} items when expected ${this.numItems}.`);return Oh(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(M,et,Bt,Wt){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:Nt,coords:$t,nodeSize:Gr}=this,mn=[0,Nt.length-1,0],Hn=[];for(;mn.length;){const so=mn.pop()||0,uo=mn.pop()||0,Io=mn.pop()||0;if(uo-Io<=Gr){for(let Gr=Io;Gr<=uo;Gr++){const mn=$t[2*Gr],so=$t[2*Gr+1];mn>=M&&mn<=Bt&&so>=et&&so<=Wt&&Hn.push(Nt[Gr])}continue}const Po=Io+uo>>1,To=$t[2*Po],Eo=$t[2*Po+1];To>=M&&To<=Bt&&Eo>=et&&Eo<=Wt&&Hn.push(Nt[Po]),(0===so?M<=To:et<=Eo)&&(mn.push(Io),mn.push(Po-1),mn.push(1-so)),(0===so?Bt>=To:Wt>=Eo)&&(mn.push(Po+1),mn.push(uo),mn.push(1-so))}return Hn}within(M,et,Bt){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:Wt,coords:Nt,nodeSize:$t}=this,Gr=[0,Wt.length-1,0],mn=[],Hn=Bt*Bt;for(;Gr.length;){const so=Gr.pop()||0,uo=Gr.pop()||0,Io=Gr.pop()||0;if(uo-Io<=$t){for(let Bt=Io;Bt<=uo;Bt++)Uh(Nt[2*Bt],Nt[2*Bt+1],M,et)<=Hn&&mn.push(Wt[Bt]);continue}const Po=Io+uo>>1,To=Nt[2*Po],Eo=Nt[2*Po+1];Uh(To,Eo,M,et)<=Hn&&mn.push(Wt[Po]),(0===so?M-Bt<=To:et-Bt<=Eo)&&(Gr.push(Io),Gr.push(Po-1),Gr.push(1-so)),(0===so?M+Bt>=To:et+Bt>=Eo)&&(Gr.push(Po+1),Gr.push(uo),Gr.push(1-so))}return mn}}function Oh(M,et,Bt,Wt,Nt,$t){if(Nt-Wt<=Bt)return;const Gr=Wt+Nt>>1;Rh(M,et,Gr,Wt,Nt,$t),Oh(M,et,Bt,Wt,Gr-1,1-$t),Oh(M,et,Bt,Gr+1,Nt,1-$t)}function Rh(M,et,Bt,Wt,Nt,$t){for(;Nt>Wt;){if(Nt-Wt>600){const Gr=Nt-Wt+1,mn=Bt-Wt+1,Hn=Math.log(Gr),so=.5*Math.exp(2*Hn/3),uo=.5*Math.sqrt(Hn*so*(Gr-so)/Gr)*(mn-Gr/2<0?-1:1);Rh(M,et,Bt,Math.max(Wt,Math.floor(Bt-mn*so/Gr+uo)),Math.min(Nt,Math.floor(Bt+(Gr-mn)*so/Gr+uo)),$t)}const Gr=et[2*Bt+$t];let mn=Wt,Hn=Nt;for(jh(M,et,Wt,Bt),et[2*Nt+$t]>Gr&&jh(M,et,Wt,Nt);mnGr;)Hn--}et[2*Wt+$t]===Gr?jh(M,et,Wt,Hn):(Hn++,jh(M,et,Hn,Nt)),Hn<=Bt&&(Wt=Hn+1),Bt<=Hn&&(Nt=Hn-1)}}function jh(M,et,Bt,Wt){Nh(M,Bt,Wt),Nh(et,2*Bt,2*Wt),Nh(et,2*Bt+1,2*Wt+1)}function Nh(M,et,Bt){const Wt=M[et];M[et]=M[Bt],M[Bt]=Wt}function Uh(M,et,Bt,Wt){const Nt=M-Bt,$t=et-Wt;return Nt*Nt+$t*$t}var _d;M.ce=void 0,(_d=M.ce||(M.ce={})).create="create",_d.load="load",_d.fullLoad="fullLoad";let bd=null,vd=[];const xd=1e3/60,wd="loadTime",Sd="fullLoadTime",kd={mark(M){performance.mark(M)},frame(M){const et=M;null!=bd&&vd.push(et-bd),bd=et},clearMetrics(){bd=null,vd=[],performance.clearMeasures(wd),performance.clearMeasures(Sd);for(const et in M.ce)performance.clearMarks(M.ce[et])},getPerformanceMetrics(){performance.measure(wd,M.ce.create,M.ce.load),performance.measure(Sd,M.ce.create,M.ce.fullLoad);const et=performance.getEntriesByName(wd)[0].duration,Bt=performance.getEntriesByName(Sd)[0].duration,Wt=vd.length,Nt=1/(vd.reduce(((M,et)=>M+et),0)/Wt/1e3),$t=vd.filter((M=>M>xd)).reduce(((M,et)=>M+(et-xd)/xd),0);return{loadTime:et,fullLoadTime:Bt,fps:Nt,percentDroppedFrames:$t/(Wt+$t)*100,totalFrames:Wt}}};M.$=St,M.A=Po,M.B=qh,M.C=function(M){if(null==Ta){const et=M.navigator?M.navigator.userAgent:null;Ta=!!M.safari||!(!et||!(/\b(iPad|iPhone|iPod)\b/.test(et)||et.match("Safari")&&!et.match("Chrome")))}return Ta},M.D=vs,M.E=ct,M.F=class{constructor(M,et){this.target=M,this.mapId=et,this.resolveRejects={},this.tasks={},this.taskQueue=[],this.abortControllers={},this.messageHandlers={},this.invoker=new Dc((()=>this.process())),this.subscription=function(M,et,Bt){return M.addEventListener(et,Bt,!1),{unsubscribe:()=>{M.removeEventListener(et,Bt,!1)}}}(this.target,"message",(M=>this.receive(M))),this.globalScope=U(self)?M:window}registerMessageHandler(M,et){this.messageHandlers[M]=et}sendAsync(M,et){return new Promise(((Bt,Wt)=>{const Nt=Math.round(1e18*Math.random()).toString(36).substring(0,10);this.resolveRejects[Nt]={resolve:Bt,reject:Wt},et&&et.signal.addEventListener("abort",(()=>{delete this.resolveRejects[Nt];const et={id:Nt,type:"",origin:location.origin,targetMapId:M.targetMapId,sourceMapId:this.mapId};this.target.postMessage(et)}),{once:!0});const $t=[],Gr=Object.assign(Object.assign({},M),{id:Nt,sourceMapId:this.mapId,origin:location.origin,data:Xi(M.data,$t)});this.target.postMessage(Gr,{transfer:$t})}))}receive(M){const et=M.data,Bt=et.id;if(!("file://"!==et.origin&&"file://"!==location.origin&&"resource://android"!==et.origin&&"resource://android"!==location.origin&&et.origin!==location.origin||et.targetMapId&&this.mapId!==et.targetMapId)){if(""===et.type){delete this.tasks[Bt];const M=this.abortControllers[Bt];return delete this.abortControllers[Bt],void(M&&M.abort())}if(U(self)||et.mustQueue)return this.tasks[Bt]=et,this.taskQueue.push(Bt),void this.invoker.trigger();this.processTask(Bt,et)}}process(){if(0===this.taskQueue.length)return;const M=this.taskQueue.shift(),et=this.tasks[M];delete this.tasks[M],this.taskQueue.length>0&&this.invoker.trigger(),et&&this.processTask(M,et)}processTask(M,et){return e(this,void 0,void 0,(function*(){if(""===et.type){const Bt=this.resolveRejects[M];if(delete this.resolveRejects[M],!Bt)return;return void(et.error?Bt.reject(Ki(et.error)):Bt.resolve(Ki(et.data)))}if(!this.messageHandlers[et.type])return void this.completeTask(M,new Error(`Could not find a registered handler for ${et.type}, map ID: ${this.mapId}, available handlers: ${Object.keys(this.messageHandlers).join(", ")}`));const Bt=Ki(et.data),Wt=new AbortController;this.abortControllers[M]=Wt;try{const Nt=yield this.messageHandlers[et.type](et.sourceMapId,Bt,Wt);this.completeTask(M,null,Nt)}catch(Bt){this.completeTask(M,Bt)}}))}completeTask(M,et,Bt){const Wt=[];delete this.abortControllers[M];const Nt={id:M,type:"",sourceMapId:this.mapId,origin:location.origin,error:et?Xi(et):null,data:Xi(Bt,Wt)};this.target.postMessage(Nt,{transfer:Wt})}remove(){this.invoker.remove(),this.subscription.unsubscribe()}},M.G=Da,M.H=function(){var M=new Po(16);return Po!=Float32Array&&(M[1]=0,M[2]=0,M[3]=0,M[4]=0,M[6]=0,M[7]=0,M[8]=0,M[9]=0,M[11]=0,M[12]=0,M[13]=0,M[14]=0),M[0]=1,M[5]=1,M[10]=1,M[15]=1,M},M.I=Zu,M.J=function(M,et,Bt){var Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia=Bt[0],Ba=Bt[1],Ta=Bt[2];return et===M?(M[12]=et[0]*Ia+et[4]*Ba+et[8]*Ta+et[12],M[13]=et[1]*Ia+et[5]*Ba+et[9]*Ta+et[13],M[14]=et[2]*Ia+et[6]*Ba+et[10]*Ta+et[14],M[15]=et[3]*Ia+et[7]*Ba+et[11]*Ta+et[15]):(Nt=et[1],$t=et[2],Gr=et[3],mn=et[4],Hn=et[5],so=et[6],uo=et[7],Io=et[8],Po=et[9],To=et[10],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M[10]=za*$t+Fa*so+Ea*To+La*Ta,M[11]=za*Gr+Fa*uo+Ea*Eo+La*Va,M[12]=(za=Bt[12])*Wt+(Fa=Bt[13])*mn+(Ea=Bt[14])*Io+(La=Bt[15])*Ia,M[13]=za*Nt+Fa*Hn+Ea*Po+La*Ba,M[14]=za*$t+Fa*so+Ea*To+La*Ta,M[15]=za*Gr+Fa*uo+Ea*Eo+La*Va,M},M.M=function(M,et){const Bt={};for(let Wt=0;Wt{const et=window.document.createElement("video");return et.muted=!0,new Promise((Bt=>{et.onloadstart=()=>{Bt(et)};for(const Bt of M){const M=window.document.createElement("source");st(Bt)||(et.crossOrigin="Anonymous"),M.src=Bt,et.appendChild(M)}}))},M.a1=function(){return Ia++},M.a2=ra,M.a3=kc,M.a4=Yn,M.a5=lo,M.a6=rh,M.a7=function(M){const et={};if(M.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,((M,Bt,Wt,Nt)=>{const $t=Wt||Nt;return et[Bt]=!$t||$t.toLowerCase(),""})),et["max-age"]){const M=parseInt(et["max-age"],10);isNaN(M)?delete et["max-age"]:et["max-age"]=M}return et},M.a8=function(M){return Math.log(M)/Math.LN2},M.a9=function(M){var et=M[0],Bt=M[1];return et*et+Bt*Bt},M.aA=Cs,M.aB=_l,M.aC=fa,M.aD=Pa,M.aE=ka,M.aF=85.051129,M.aG=function(M){return Math.pow(2,M)},M.aH=Gc,M.aI=T,M.aJ=Y,M.aK=Xc,M.aL=function(M,et,Bt){return M[0]=et[0]*Bt,M[1]=et[1]*Bt,M[2]=et[2]*Bt,M},M.aM=function(M,et,Bt){return M[0]=et[0]+Bt[0],M[1]=et[1]+Bt[1],M[2]=et[2]+Bt[2],M},M.aN=function(M){var et=new Po(3);return et[0]=M[0],et[1]=M[1],et[2]=M[2],et},M.aO=function(M,et,Bt){return M[0]=et[0]*Bt[0],M[1]=et[1]*Bt[1],M[2]=et[2]*Bt[2],M[3]=et[3]*Bt[3],M},M.aP=function(M,et,Bt){return M[0]=et[0]-Bt[0],M[1]=et[1]-Bt[1],M[2]=et[2]-Bt[2],M},M.aQ=function(M,et){var Bt=et[0],Wt=et[1],Nt=et[2],$t=Bt*Bt+Wt*Wt+Nt*Nt;return $t>0&&($t=1/Math.sqrt($t)),M[0]=et[0]*$t,M[1]=et[1]*$t,M[2]=et[2]*$t,M},M.aR=function(M,et,Bt){var Wt=et[0],Nt=et[1],$t=et[2],Gr=Bt[0],mn=Bt[1],Hn=Bt[2];return M[0]=Nt*Hn-$t*mn,M[1]=$t*Gr-Wt*Hn,M[2]=Wt*mn-Nt*Gr,M},M.aS=function(M,et){return M[0]*et[0]+M[1]*et[1]+M[2]*et[2]},M.aT=Jc,M.aU=Qc,M.aV=function(M,et,Bt,Wt,Nt){var $t,Gr=1/Math.tan(et/2);return M[0]=Gr/Bt,M[1]=0,M[2]=0,M[3]=0,M[4]=0,M[5]=Gr,M[6]=0,M[7]=0,M[8]=0,M[9]=0,M[11]=-1,M[12]=0,M[13]=0,M[15]=0,null!=Nt&&Nt!==1/0?(M[10]=(Nt+Wt)*($t=1/(Wt-Nt)),M[14]=2*Nt*Wt*$t):(M[10]=-1,M[14]=-2*Wt),M},M.aW=function(M){var et=new Po(16);return et[0]=M[0],et[1]=M[1],et[2]=M[2],et[3]=M[3],et[4]=M[4],et[5]=M[5],et[6]=M[6],et[7]=M[7],et[8]=M[8],et[9]=M[9],et[10]=M[10],et[11]=M[11],et[12]=M[12],et[13]=M[13],et[14]=M[14],et[15]=M[15],et},M.aX=function(M,et,Bt){var Wt=Math.sin(Bt),Nt=Math.cos(Bt),$t=et[0],Gr=et[1],mn=et[2],Hn=et[3],so=et[4],uo=et[5],Io=et[6],Po=et[7];return et!==M&&(M[8]=et[8],M[9]=et[9],M[10]=et[10],M[11]=et[11],M[12]=et[12],M[13]=et[13],M[14]=et[14],M[15]=et[15]),M[0]=$t*Nt+so*Wt,M[1]=Gr*Nt+uo*Wt,M[2]=mn*Nt+Io*Wt,M[3]=Hn*Nt+Po*Wt,M[4]=so*Nt-$t*Wt,M[5]=uo*Nt-Gr*Wt,M[6]=Io*Nt-mn*Wt,M[7]=Po*Nt-Hn*Wt,M},M.aY=function(M,et,Bt){var Wt=Math.sin(Bt),Nt=Math.cos(Bt),$t=et[4],Gr=et[5],mn=et[6],Hn=et[7],so=et[8],uo=et[9],Io=et[10],Po=et[11];return et!==M&&(M[0]=et[0],M[1]=et[1],M[2]=et[2],M[3]=et[3],M[12]=et[12],M[13]=et[13],M[14]=et[14],M[15]=et[15]),M[4]=$t*Nt+so*Wt,M[5]=Gr*Nt+uo*Wt,M[6]=mn*Nt+Io*Wt,M[7]=Hn*Nt+Po*Wt,M[8]=so*Nt-$t*Wt,M[9]=uo*Nt-Gr*Wt,M[10]=Io*Nt-mn*Wt,M[11]=Po*Nt-Hn*Wt,M},M.aZ=function(){const M=new Float32Array(16);return v(M),M},M.a_=function(){const M=new Float64Array(16);return v(M),M},M.aa=function(M){return M*Math.PI/180},M.ab=E,M.ac=function(M,et){const Bt=[];for(const Wt in M)Wt in et||Bt.push(Wt);return Bt},M.ad=A,M.ae=function(M){return Math.hypot(M[0],M[1])},M.af=function(M){return M[0]=0,M[1]=0,M},M.ag=function(M,et,Bt){return M[0]=et[0]*Bt,M[1]=et[1]*Bt,M},M.ah=function(M,et){let Bt=0,Wt=0;if("constant"===M.kind)Wt=M.layoutSize;else if("source"!==M.kind){const{interpolationType:Nt,minZoom:$t,maxZoom:Gr}=M,mn=Nt?E(sr.interpolationFactor(Nt,et,$t,Gr),0,1):0;"camera"===M.kind?Wt=zc.number(M.minSize,M.maxSize,mn):Bt=mn}return{uSizeT:Bt,uSize:Wt}},M.aj=function(M,{uSize:et,uSizeT:Bt},{lowerSize:Wt,upperSize:Nt}){return"source"===M.kind?W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Bt*Al-Wt*Oa+Nt*Ka)*Gl,M[14]=(Ia*za-Eo*Ea-Ba*Va)*Gl,M[15]=(uo*Ea-Io*za+Po*Va)*Gl,M):null},M.ao=oh,M.ap=po,M.aq=v,M.ar=function(M){let et=1/0,Bt=1/0,Wt=-1/0,Nt=-1/0;for(const $t of M)et=Math.min(et,$t.x),Bt=Math.min(Bt,$t.y),Wt=Math.max(Wt,$t.x),Nt=Math.max(Nt,$t.y);return[et,Bt,Wt,Nt]},M.as=zu,M.at=I,M.au=function(M,et,Bt,Wt,Nt=!1){if(!Bt[0]&&!Bt[1])return[0,0];const $t=Nt?"map"===Wt?-M.bearingInRadians:0:"viewport"===Wt?M.bearingInRadians:0;if($t){const M=Math.sin($t),et=Math.cos($t);Bt=[Bt[0]*et-Bt[1]*M,Bt[0]*M+Bt[1]*et]}return[Nt?Bt[0]:I(et,Bt[0],M.zoom),Nt?Bt[1]:I(et,Bt[1],M.zoom)]},M.aw=gc,M.ax=Vh,M.ay=lc,M.az=Dh,M.b=G,M.b$=M=>"line"===M.type,M.b0=function(M,et,Bt){const Wt=new Float64Array(4);return function(M,et,Bt,Wt){var Nt=.5*Math.PI/180;et*=Nt,Bt*=Nt,Wt*=Nt;var $t=Math.sin(et),Gr=Math.cos(et),mn=Math.sin(Bt),Hn=Math.cos(Bt),so=Math.sin(Wt),uo=Math.cos(Wt);M[0]=$t*Hn*uo-Gr*mn*so,M[1]=Gr*mn*uo+$t*Hn*so,M[2]=Gr*Hn*so-$t*mn*uo,M[3]=Gr*Hn*uo+$t*mn*so}(Wt,M,et-90,Bt),Wt},M.b1=function(M,et,Bt,Wt){var Nt,$t,Gr,mn,Hn,so=et[0],uo=et[1],Po=et[2],To=et[3],Eo=Bt[0],Ia=Bt[1],Ba=Bt[2],Ta=Bt[3];return($t=so*Eo+uo*Ia+Po*Ba+To*Ta)<0&&($t=-$t,Eo=-Eo,Ia=-Ia,Ba=-Ba,Ta=-Ta),1-$t>Io?(Nt=Math.acos($t),Gr=Math.sin(Nt),mn=Math.sin((1-Wt)*Nt)/Gr,Hn=Math.sin(Wt*Nt)/Gr):(mn=1-Wt,Hn=Wt),M[0]=mn*so+Hn*Eo,M[1]=mn*uo+Hn*Ia,M[2]=mn*Po+Hn*Ba,M[3]=mn*To+Hn*Ta,M},M.b2=function(M){const et=new Float64Array(9);var Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba,Ta,Va,za;Io=(Nt=(Wt=M)[0])*(Hn=Nt+Nt),Po=($t=Wt[1])*Hn,Eo=(Gr=Wt[2])*Hn,Ia=Gr*(so=$t+$t),Ta=(mn=Wt[3])*Hn,Va=mn*so,za=mn*(uo=Gr+Gr),(Bt=et)[0]=1-(To=$t*so)-(Ba=Gr*uo),Bt[3]=Po-za,Bt[6]=Eo+Va,Bt[1]=Po+za,Bt[4]=1-Io-Ba,Bt[7]=Ia-Ta,Bt[2]=Eo-Va,Bt[5]=Ia+Ta,Bt[8]=1-Io-To;const Fa=Y(-Math.asin(E(et[2],-1,1)));let Ea,La;return Math.hypot(et[5],et[8])<.001?(Ea=0,La=-Y(Math.atan2(et[3],et[4]))):(Ea=Y(0===et[5]&&0===et[8]?0:Math.atan2(et[5],et[8])),La=Y(0===et[1]&&0===et[0]?0:Math.atan2(et[1],et[0]))),{roll:Ea,pitch:Fa+90,bearing:La}},M.b3=function(M,et){return M.roll==et.roll&&M.pitch==et.pitch&&M.bearing==et.bearing},M.b4=ye,M.b5=Ga,M.b6=Vg,M.b7=Wg,M.b8=wl,M.b9=P,M.bA=L,M.bB=D,M.bC=class extends qa{constructor(M,et){super(M,et),this.current=0}set(M){this.current!==M&&(this.current=M,this.gl.uniform1i(this.location,M))}},M.bD=class extends qa{constructor(M,et){super(M,et),this.current=_g}set(M){if(M[12]!==this.current[12]||M[0]!==this.current[0])return this.current=M,void this.gl.uniformMatrix4fv(this.location,!1,M);for(let et=1;et<16;et++)if(M[et]!==this.current[et]){this.current=M,this.gl.uniformMatrix4fv(this.location,!1,M);break}}},M.bE=Za,M.bF=Xa,M.bG=class extends qa{constructor(M,et){super(M,et),this.current=[0,0,0]}set(M){M[0]===this.current[0]&&M[1]===this.current[1]&&M[2]===this.current[2]||(this.current=M,this.gl.uniform3f(this.location,M[0],M[1],M[2]))}},M.bH=class extends qa{constructor(M,et){super(M,et),this.current=[0,0]}set(M){M[0]===this.current[0]&&M[1]===this.current[1]||(this.current=M,this.gl.uniform2f(this.location,M[0],M[1]))}},M.bI=x,M.bJ=function(M,et){var Bt=Math.sin(et),Wt=Math.cos(et);return M[0]=Wt,M[1]=Bt,M[2]=0,M[3]=-Bt,M[4]=Wt,M[5]=0,M[6]=0,M[7]=0,M[8]=1,M},M.bK=function(M,et,Bt){var Wt=et[0],Nt=et[1],$t=et[2];return M[0]=Wt*Bt[0]+Nt*Bt[3]+$t*Bt[6],M[1]=Wt*Bt[1]+Nt*Bt[4]+$t*Bt[7],M[2]=Wt*Bt[2]+Nt*Bt[5]+$t*Bt[8],M},M.bL=function(M,et,Bt,Wt,Nt,$t,Gr){var mn=1/(et-Bt),Hn=1/(Wt-Nt),so=1/($t-Gr);return M[0]=-2*mn,M[1]=0,M[2]=0,M[3]=0,M[4]=0,M[5]=-2*Hn,M[6]=0,M[7]=0,M[8]=0,M[9]=0,M[10]=2*so,M[11]=0,M[12]=(et+Bt)*mn,M[13]=(Nt+Wt)*Hn,M[14]=(Gr+$t)*so,M[15]=1,M},M.bM=class extends qs{},M.bN=Bu,M.bO=class extends Zs{},M.bP=Gg,M.bQ=function(M){return M<=1?1:Math.pow(2,Math.ceil(Math.log(M)/Math.LN2))},M.bR=Ro,M.bS=function(M,et,Bt){var Wt=et[0],Nt=et[1],$t=et[2],Gr=Bt[3]*Wt+Bt[7]*Nt+Bt[11]*$t+Bt[15];return M[0]=(Bt[0]*Wt+Bt[4]*Nt+Bt[8]*$t+Bt[12])/(Gr=Gr||1),M[1]=(Bt[1]*Wt+Bt[5]*Nt+Bt[9]*$t+Bt[13])/Gr,M[2]=(Bt[2]*Wt+Bt[6]*Nt+Bt[10]*$t+Bt[14])/Gr,M},M.bT=class extends Ts{},M.bU=class extends Qs{},M.bV=function(M,et){return M[0]===et[0]&&M[1]===et[1]&&M[2]===et[2]&&M[3]===et[3]&&M[4]===et[4]&&M[5]===et[5]&&M[6]===et[6]&&M[7]===et[7]&&M[8]===et[8]&&M[9]===et[9]&&M[10]===et[10]&&M[11]===et[11]&&M[12]===et[12]&&M[13]===et[13]&&M[14]===et[14]&&M[15]===et[15]},M.bW=function(M,et){var Bt=M[0],Wt=M[1],Nt=M[2],$t=M[3],Gr=M[4],mn=M[5],Hn=M[6],so=M[7],uo=M[8],Po=M[9],To=M[10],Eo=M[11],Ia=M[12],Ba=M[13],Ta=M[14],Va=M[15],za=et[0],Fa=et[1],Ea=et[2],La=et[3],Da=et[4],Ka=et[5],Oa=et[6],$a=et[7],Al=et[8],Sl=et[9],Zl=et[10],Gl=et[11],Rl=et[12],Tl=et[13],Vl=et[14],Wl=et[15];return Math.abs(Bt-za)<=Io*Math.max(1,Math.abs(Bt),Math.abs(za))&&Math.abs(Wt-Fa)<=Io*Math.max(1,Math.abs(Wt),Math.abs(Fa))&&Math.abs(Nt-Ea)<=Io*Math.max(1,Math.abs(Nt),Math.abs(Ea))&&Math.abs($t-La)<=Io*Math.max(1,Math.abs($t),Math.abs(La))&&Math.abs(Gr-Da)<=Io*Math.max(1,Math.abs(Gr),Math.abs(Da))&&Math.abs(mn-Ka)<=Io*Math.max(1,Math.abs(mn),Math.abs(Ka))&&Math.abs(Hn-Oa)<=Io*Math.max(1,Math.abs(Hn),Math.abs(Oa))&&Math.abs(so-$a)<=Io*Math.max(1,Math.abs(so),Math.abs($a))&&Math.abs(uo-Al)<=Io*Math.max(1,Math.abs(uo),Math.abs(Al))&&Math.abs(Po-Sl)<=Io*Math.max(1,Math.abs(Po),Math.abs(Sl))&&Math.abs(To-Zl)<=Io*Math.max(1,Math.abs(To),Math.abs(Zl))&&Math.abs(Eo-Gl)<=Io*Math.max(1,Math.abs(Eo),Math.abs(Gl))&&Math.abs(Ia-Rl)<=Io*Math.max(1,Math.abs(Ia),Math.abs(Rl))&&Math.abs(Ba-Tl)<=Io*Math.max(1,Math.abs(Ba),Math.abs(Tl))&&Math.abs(Ta-Vl)<=Io*Math.max(1,Math.abs(Ta),Math.abs(Vl))&&Math.abs(Va-Wl)<=Io*Math.max(1,Math.abs(Va),Math.abs(Wl))},M.bX=function(M,et){return M[0]=et[0],M[1]=et[1],M[2]=et[2],M[3]=et[3],M[4]=et[4],M[5]=et[5],M[6]=et[6],M[7]=et[7],M[8]=et[8],M[9]=et[9],M[10]=et[10],M[11]=et[11],M[12]=et[12],M[13]=et[13],M[14]=et[14],M[15]=et[15],M},M.bY=M=>"symbol"===M.type,M.bZ=M=>"circle"===M.type,M.b_=M=>"heatmap"===M.type,M.ba=C,M.bb=Ae,M.bc=function(M,et,Bt,Wt,Nt){return P(Wt,Nt,E((M-et)/(Bt-et),0,1))},M.bd=z,M.be=function(){return new Float64Array(4)},M.bf=function(){return new Float64Array(3)},M.bg=function(M,et,Bt,Wt){var Nt=[],$t=[];return Nt[0]=et[0]-Bt[0],Nt[1]=et[1]-Bt[1],Nt[2]=et[2]-Bt[2],$t[0]=Nt[0]*Math.cos(Wt)-Nt[1]*Math.sin(Wt),$t[1]=Nt[0]*Math.sin(Wt)+Nt[1]*Math.cos(Wt),$t[2]=Nt[2],M[0]=$t[0]+Bt[0],M[1]=$t[1]+Bt[1],M[2]=$t[2]+Bt[2],M},M.bh=function(M,et,Bt,Wt){var Nt=[],$t=[];return Nt[0]=et[0]-Bt[0],Nt[1]=et[1]-Bt[1],Nt[2]=et[2]-Bt[2],$t[0]=Nt[0],$t[1]=Nt[1]*Math.cos(Wt)-Nt[2]*Math.sin(Wt),$t[2]=Nt[1]*Math.sin(Wt)+Nt[2]*Math.cos(Wt),M[0]=$t[0]+Bt[0],M[1]=$t[1]+Bt[1],M[2]=$t[2]+Bt[2],M},M.bi=function(M,et,Bt,Wt){var Nt=[],$t=[];return Nt[0]=et[0]-Bt[0],Nt[1]=et[1]-Bt[1],Nt[2]=et[2]-Bt[2],$t[0]=Nt[2]*Math.sin(Wt)+Nt[0]*Math.cos(Wt),$t[1]=Nt[1],$t[2]=Nt[2]*Math.cos(Wt)-Nt[0]*Math.sin(Wt),M[0]=$t[0]+Bt[0],M[1]=$t[1]+Bt[1],M[2]=$t[2]+Bt[2],M},M.bj=function(M,et,Bt){var Wt=Math.sin(Bt),Nt=Math.cos(Bt),$t=et[0],Gr=et[1],mn=et[2],Hn=et[3],so=et[8],uo=et[9],Io=et[10],Po=et[11];return et!==M&&(M[4]=et[4],M[5]=et[5],M[6]=et[6],M[7]=et[7],M[12]=et[12],M[13]=et[13],M[14]=et[14],M[15]=et[15]),M[0]=$t*Nt-so*Wt,M[1]=Gr*Nt-uo*Wt,M[2]=mn*Nt-Io*Wt,M[3]=Hn*Nt-Po*Wt,M[8]=$t*Wt+so*Nt,M[9]=Gr*Wt+uo*Nt,M[10]=mn*Wt+Io*Nt,M[11]=Hn*Wt+Po*Nt,M},M.bk=function(M,et){const Bt=z(M,360),Wt=z(et,360),Nt=Wt-Bt,$t=Wt>Bt?Nt-360:Nt+360;return Math.abs(Nt)0?Gr:-Gr},M.bn=function(M,et){return M[0]*et[0]+M[1]*et[1]+M[2]*et[2]+M[3]},M.bo=pd,M.bp=function(M,et){const Bt=z(M,2*Math.PI),Wt=z(et,2*Math.PI);return Math.min(Math.abs(Bt-Wt),Math.abs(Bt-Wt+2*Math.PI),Math.abs(Bt-Wt-2*Math.PI))},M.bq=function(M){return Math.hypot(M[0],M[1],M[2])},M.br=function(){const M={},et=Ka.$version;for(const Bt in Ka.$root){const Wt=Ka.$root[Bt];if(Wt.required){let Nt=null;Nt="version"===Bt?et:"array"===Wt.type?[]:{},null!=Nt&&(M[Bt]=Nt)}}return M},M.bs=Hi,M.bt=nt,M.bu=function(M){M=M.slice();const et=Object.create(null);for(let Bt=0;Bt{"source"in M&&Wt[M.source]?Bt.push({command:"removeLayer",args:[M.id]}):$t.push(M)})),Bt=Bt.concat(Nt),function(M,et,Bt){et=et||[];const Wt=(M=M||[]).map(wt),Nt=et.map(wt),$t=M.reduce(_t,{}),Gr=et.reduce(_t,{}),mn=Wt.slice(),Hn=Object.create(null);let so,uo,Io,Po,To;for(let M=0,et=0;M"fill"===M.type,M.c1=M=>"fill-extrusion"===M.type,M.c2=M=>"hillshade"===M.type,M.c3=M=>"raster"===M.type,M.c4=M=>"background"===M.type,M.c5=M=>"custom"===M.type,M.c6=B,M.c7=function(M,et,Bt){const Wt=k(et.x-Bt.x,et.y-Bt.y),Nt=k(M.x-Bt.x,M.y-Bt.y);var $t,Gr;return Y(Math.atan2(Wt[0]*Nt[1]-Wt[1]*Nt[0],($t=Wt)[0]*(Gr=Nt)[0]+$t[1]*Gr[1]))},M.c8=Eo,M.c9=function(M,et,Bt){var Wt=et[0],Nt=et[1];return M[0]=Bt[0]*Wt+Bt[4]*Nt+Bt[12],M[1]=Bt[1]*Wt+Bt[5]*Nt+Bt[13],M},M.cA=Lu,M.cB=Nn,M.cC=ag,M.ca=function(M,et){const{x:Bt,y:Wt}=Kc.fromLngLat(et);return!(M<0||M>25||Wt<0||Wt>=1||Bt<0||Bt>=1)},M.cb=function(M,et){return M[0]=et[0],M[1]=0,M[2]=0,M[3]=0,M[4]=0,M[5]=et[1],M[6]=0,M[7]=0,M[8]=0,M[9]=0,M[10]=et[2],M[11]=0,M[12]=0,M[13]=0,M[14]=0,M[15]=1,M},M.cc=class extends Es{},M.cd=kd,M.cf=function(M){return M.message===Ea},M.cg=rt,M.ch=function(M,et){La.REGISTERED_PROTOCOLS[M]=et},M.ci=function(M){delete La.REGISTERED_PROTOCOLS[M]},M.cj=function(M,et){const Bt={};for(let Wt=0;WtM*zu))}let za=mn?"center":Wt.get("text-justify").evaluate(Nt,{},et.canonical);const Fa="point"===Wt.get("symbol-placement")?Wt.get("text-max-width").evaluate(Nt,{},et.canonical)*zu:1/0,w=()=>{et.bucket.allowVerticalPlacement&&Ji($t)&&(Eo.vertical=Wu(Ia,et.glyphMap,et.glyphPositions,et.imagePositions,uo,Fa,Gr,Ba,"left",To,Ta,M.ai.vertical,!0,Po,Io))};if(!mn&&Va){const Bt=new Set;if("auto"===za)for(let M=0;Me(void 0,void 0,void 0,(function*(){if(0===M.byteLength)return createImageBitmap(new ImageData(1,1));const et=new Blob([new Uint8Array(M)],{type:"image/png"});try{return createImageBitmap(et)}catch(M){throw new Error(`Could not load image because of ${M.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`)}})),M.e=F,M.f=M=>new Promise(((et,Bt)=>{const Wt=new Image;Wt.onload=()=>{et(Wt),URL.revokeObjectURL(Wt.src),Wt.onload=null,window.requestAnimationFrame((()=>{Wt.src=Va}))},Wt.onerror=()=>Bt(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));const Nt=new Blob([new Uint8Array(M)],{type:"image/png"});Wt.src=M.byteLength?URL.createObjectURL(Nt):Va})),M.g=tt,M.h=(M,et)=>it(F(M,{type:"json"}),et),M.i=U,M.j=ut,M.k=lt,M.l=(M,et)=>it(F(M,{type:"arrayBuffer"}),et),M.m=it,M.n=function(M){return new Eu(M).readFields(Ru,[])},M.o=Do,M.p=qu,M.q=As,M.r=Qh,M.s=st,M.t=Ri,M.u=Yh,M.v=Ka,M.w=j,M.x=function([M,et,Bt]){return et+=90,et*=Math.PI/180,Bt*=Math.PI/180,{x:M*Math.cos(et)*Math.sin(Bt),y:M*Math.sin(et)*Math.sin(Bt),z:M*Math.cos(Bt)}},M.y=zc,M.z=cs})),define("worker",["./shared"],(function(M){class t{constructor(M){this.keyCache={},M&&this.replace(M)}replace(M){this._layerConfigs={},this._layers={},this.update(M,[])}update(et,Bt){for(const Bt of et){this._layerConfigs[Bt.id]=Bt;const et=this._layers[Bt.id]=M.bv(Bt);et._featureFilter=M.a4(et.filter),this.keyCache[Bt.id]&&delete this.keyCache[Bt.id]}for(const M of Bt)delete this.keyCache[M],delete this._layerConfigs[M],delete this._layers[M];this.familiesBySource={};const Wt=M.cj(Object.values(this._layerConfigs),this.keyCache);for(const M of Wt){const et=M.map((M=>this._layers[M.id])),Bt=et[0];if("none"===Bt.visibility)continue;const Wt=Bt.source||"";let Nt=this.familiesBySource[Wt];Nt||(Nt=this.familiesBySource[Wt]={});const $t=Bt.sourceLayer||"_geojsonTileLayer";let Gr=Nt[$t];Gr||(Gr=Nt[$t]=[]),Gr.push(et)}}}class o{constructor(et){const Bt={},Wt=[];for(const M in et){const Nt=et[M],$t=Bt[M]={};for(const M in Nt){const et=Nt[+M];if(!et||0===et.bitmap.width||0===et.bitmap.height)continue;const Bt={x:0,y:0,w:et.bitmap.width+2,h:et.bitmap.height+2};Wt.push(Bt),$t[M]={rect:Bt,metrics:et.metrics}}}const{w:Nt,h:$t}=M.p(Wt),Gr=new M.o({width:Nt||1,height:$t||1});for(const Wt in et){const Nt=et[Wt];for(const et in Nt){const $t=Nt[+et];if(!$t||0===$t.bitmap.width||0===$t.bitmap.height)continue;const mn=Bt[Wt][et].rect;M.o.copy($t.bitmap,Gr,{x:0,y:0},{x:mn.x+1,y:mn.y+1},$t.bitmap)}}this.image=Gr,this.positions=Bt}}M.ck("GlyphAtlas",o);class i{constructor(et){this.tileID=new M.S(et.tileID.overscaledZ,et.tileID.wrap,et.tileID.canonical.z,et.tileID.canonical.x,et.tileID.canonical.y),this.uid=et.uid,this.zoom=et.zoom,this.pixelRatio=et.pixelRatio,this.tileSize=et.tileSize,this.source=et.source,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=et.showCollisionBoxes,this.collectResourceTiming=!!et.collectResourceTiming,this.returnDependencies=!!et.returnDependencies,this.promoteId=et.promoteId,this.inFlightDependencies=[]}parse(et,Bt,Wt,Nt,$t){return M._(this,void 0,void 0,(function*(){this.status="parsing",this.data=et,this.collisionBoxArray=new M.a2;const Gr=new M.cl(Object.keys(et.layers).sort()),mn=new M.cm(this.tileID,this.promoteId);mn.bucketLayerIDs=[];const Hn={},so={featureIndex:mn,iconDependencies:{},patternDependencies:{},glyphDependencies:{},availableImages:Wt,subdivisionGranularity:$t},uo=Bt.familiesBySource[this.source];for(const Bt in uo){const Nt=et.layers[Bt];if(!Nt)continue;1===Nt.version&&M.w(`Vector tile source "${this.source}" layer "${Bt}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const $t=Gr.encode(Bt),Io=[];for(let M=0;M=Bt.maxzoom||"none"!==Bt.visibility&&(r(et,this.zoom,Wt),(Hn[Bt.id]=Bt.createBucket({index:mn.bucketLayerIDs.length,layers:et,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:$t,sourceID:this.source})).populate(Io,so,this.tileID.canonical),mn.bucketLayerIDs.push(et.map((M=>M.id))))}}const Io=M.bA(so.glyphDependencies,(M=>Object.keys(M).map(Number)));this.inFlightDependencies.forEach((M=>null==M?void 0:M.abort())),this.inFlightDependencies=[];let Po=Promise.resolve({});if(Object.keys(Io).length){const M=new AbortController;this.inFlightDependencies.push(M),Po=Nt.sendAsync({type:"GG",data:{stacks:Io,source:this.source,tileID:this.tileID,type:"glyphs"}},M)}const To=Object.keys(so.iconDependencies);let Eo=Promise.resolve({});if(To.length){const M=new AbortController;this.inFlightDependencies.push(M),Eo=Nt.sendAsync({type:"GI",data:{icons:To,source:this.source,tileID:this.tileID,type:"icons"}},M)}const Ia=Object.keys(so.patternDependencies);let Ba=Promise.resolve({});if(Ia.length){const M=new AbortController;this.inFlightDependencies.push(M),Ba=Nt.sendAsync({type:"GI",data:{icons:Ia,source:this.source,tileID:this.tileID,type:"patterns"}},M)}const[Ta,Va,za]=yield Promise.all([Po,Eo,Ba]),Fa=new o(Ta),Ea=new M.cn(Va,za);for(const et in Hn){const Bt=Hn[et];Bt instanceof M.a3?(r(Bt.layers,this.zoom,Wt),M.co({bucket:Bt,glyphMap:Ta,glyphPositions:Fa.positions,imageMap:Va,imagePositions:Ea.iconPositions,showCollisionBoxes:this.showCollisionBoxes,canonical:this.tileID.canonical,subdivisionGranularity:so.subdivisionGranularity})):Bt.hasPattern&&(Bt instanceof M.cp||Bt instanceof M.cq||Bt instanceof M.cr)&&(r(Bt.layers,this.zoom,Wt),Bt.addFeatures(so,this.tileID.canonical,Ea.patternPositions))}return this.status="done",{buckets:Object.values(Hn).filter((M=>!M.isEmpty())),featureIndex:mn,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:Fa.image,imageAtlas:Ea,glyphMap:this.returnDependencies?Ta:null,iconMap:this.returnDependencies?Va:null,glyphPositions:this.returnDependencies?Fa.positions:null}}))}}function r(et,Bt,Wt){const Nt=new M.z(Bt);for(const M of et)M.recalculate(Nt,Wt)}class s{constructor(M,et,Bt){this.actor=M,this.layerIndex=et,this.availableImages=Bt,this.fetching={},this.loading={},this.loaded={}}loadVectorTile(et,Bt){return M._(this,void 0,void 0,(function*(){const Wt=yield M.l(et.request,Bt);try{return{vectorTile:new M.cs.VectorTile(new M.ct(Wt.data)),rawData:Wt.data,cacheControl:Wt.cacheControl,expires:Wt.expires}}catch(M){const Bt=new Uint8Array(Wt.data);let Nt=`Unable to parse the tile at ${et.request.url}, `;throw Nt+=31===Bt[0]&&139===Bt[1]?"please make sure the data is not gzipped and that you have configured the relevant header in the server":`got error: ${M.message}`,new Error(Nt)}}))}loadTile(et){return M._(this,void 0,void 0,(function*(){const Bt=et.uid,Wt=!!(et&&et.request&&et.request.collectResourceTiming)&&new M.cu(et.request),Nt=new i(et);this.loading[Bt]=Nt;const $t=new AbortController;Nt.abort=$t;try{const Gr=yield this.loadVectorTile(et,$t);if(delete this.loading[Bt],!Gr)return null;const mn=Gr.rawData,Hn={};Gr.expires&&(Hn.expires=Gr.expires),Gr.cacheControl&&(Hn.cacheControl=Gr.cacheControl);const so={};if(Wt){const M=Wt.finish();M&&(so.resourceTiming=JSON.parse(JSON.stringify(M)))}Nt.vectorTile=Gr.vectorTile;const uo=Nt.parse(Gr.vectorTile,this.layerIndex,this.availableImages,this.actor,et.subdivisionGranularity);this.loaded[Bt]=Nt,this.fetching[Bt]={rawTileData:mn,cacheControl:Hn,resourceTiming:so};try{const et=yield uo;return M.e({rawTileData:mn.slice(0)},et,Hn,so)}finally{delete this.fetching[Bt]}}catch(M){throw delete this.loading[Bt],Nt.status="done",this.loaded[Bt]=Nt,M}}))}reloadTile(et){return M._(this,void 0,void 0,(function*(){const Bt=et.uid;if(!this.loaded||!this.loaded[Bt])throw new Error("Should not be trying to reload a tile that was never loaded or has been removed");const Wt=this.loaded[Bt];if(Wt.showCollisionBoxes=et.showCollisionBoxes,"parsing"===Wt.status){const Nt=yield Wt.parse(Wt.vectorTile,this.layerIndex,this.availableImages,this.actor,et.subdivisionGranularity);let $t;if(this.fetching[Bt]){const{rawTileData:et,cacheControl:Wt,resourceTiming:Gr}=this.fetching[Bt];delete this.fetching[Bt],$t=M.e({rawTileData:et.slice(0)},Nt,Wt,Gr)}else $t=Nt;return $t}if("done"===Wt.status&&Wt.vectorTile)return Wt.parse(Wt.vectorTile,this.layerIndex,this.availableImages,this.actor,et.subdivisionGranularity)}))}abortTile(et){return M._(this,void 0,void 0,(function*(){const M=this.loading,Bt=et.uid;M&&M[Bt]&&M[Bt].abort&&(M[Bt].abort.abort(),delete M[Bt])}))}removeTile(et){return M._(this,void 0,void 0,(function*(){this.loaded&&this.loaded[et.uid]&&delete this.loaded[et.uid]}))}}class n{constructor(){this.loaded={}}loadTile(et){return M._(this,void 0,void 0,(function*(){const{uid:Bt,encoding:Wt,rawImageData:Nt,redFactor:$t,greenFactor:Gr,blueFactor:mn,baseShift:Hn}=et,so=Nt.width+2,uo=Nt.height+2,Io=M.b(Nt)?new M.R({width:so,height:uo},yield M.cv(Nt,-1,-1,so,uo)):Nt,Po=new M.cw(Bt,Io,Wt,$t,Gr,mn,Hn);return this.loaded=this.loaded||{},this.loaded[Bt]=Po,Po}))}removeTile(M){const et=this.loaded,Bt=M.uid;et&&et[Bt]&&delete et[Bt]}}var et,Bt,Wt=function(){if(Bt)return et;function e(M,et){if(0!==M.length){t(M[0],et);for(var Bt=1;Bt=Math.abs(mn)?Bt-Hn+mn:mn-Hn+Bt,Bt=Hn}Bt+Wt>=0!=!!et&&M.reverse()}return Bt=1,et=function t(M,et){var Bt,Wt=M&&M.type;if("FeatureCollection"===Wt)for(Bt=0;Bt>31}function c(M,et){for(var Bt=M.loadGeometry(),Wt=M.type,Nt=0,$t=0,Gr=Bt.length,mn=0;mnM},To=Math.fround||(Eo=new Float32Array(1),M=>(Eo[0]=+M,Eo[0]));var Eo;const Ia=3,Ba=5,Ta=6;class P{constructor(M){this.options=Object.assign(Object.create(Po),M),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(M){const{log:et,minZoom:Bt,maxZoom:Wt}=this.options;et&&console.time("total time");const Nt=`prepare ${M.length} points`;et&&console.time(Nt),this.points=M;const $t=[];for(let et=0;et=Bt;M--){const Bt=+Date.now();Gr=this.trees[M]=this._createTree(this._cluster(Gr,M)),et&&console.log("z%d: %d clusters in %dms",M,Gr.numItems,+Date.now()-Bt)}return et&&console.timeEnd("total time"),this}getClusters(M,et){let Bt=((M[0]+180)%360+360)%360-180;const Wt=Math.max(-90,Math.min(90,M[1]));let Nt=180===M[2]?180:((M[2]+180)%360+360)%360-180;const $t=Math.max(-90,Math.min(90,M[3]));if(M[2]-M[0]>=360)Bt=-180,Nt=180;else if(Bt>Nt){const M=this.getClusters([Bt,Wt,180,$t],et),Gr=this.getClusters([-180,Wt,Nt,$t],et);return M.concat(Gr)}const Gr=this.trees[this._limitZoom(et)],mn=Gr.range(D(Bt),C($t),D(Nt),C(Wt)),Hn=Gr.data,so=[];for(const M of mn){const et=this.stride*M;so.push(Hn[et+Ba]>1?k(Hn,et,this.clusterProps):this.points[Hn[et+Ia]])}return so}getChildren(M){const et=this._getOriginId(M),Bt=this._getOriginZoom(M),Wt="No cluster with the specified id.",Nt=this.trees[Bt];if(!Nt)throw new Error(Wt);const $t=Nt.data;if(et*this.stride>=$t.length)throw new Error(Wt);const Gr=this.options.radius/(this.options.extent*Math.pow(2,Bt-1)),mn=Nt.within($t[et*this.stride],$t[et*this.stride+1],Gr),Hn=[];for(const et of mn){const Bt=et*this.stride;$t[Bt+4]===M&&Hn.push($t[Bt+Ba]>1?k($t,Bt,this.clusterProps):this.points[$t[Bt+Ia]])}if(0===Hn.length)throw new Error(Wt);return Hn}getLeaves(M,et,Bt){const Wt=[];return this._appendLeaves(Wt,M,et=et||10,Bt=Bt||0,0),Wt}getTile(M,et,Bt){const Wt=this.trees[this._limitZoom(M)],Nt=Math.pow(2,M),{extent:$t,radius:Gr}=this.options,mn=Gr/$t,Hn=(Bt-mn)/Nt,so=(Bt+1+mn)/Nt,uo={features:[]};return this._addTileFeatures(Wt.range((et-mn)/Nt,Hn,(et+1+mn)/Nt,so),Wt.data,et,Bt,Nt,uo),0===et&&this._addTileFeatures(Wt.range(1-mn/Nt,Hn,1,so),Wt.data,Nt,Bt,Nt,uo),et===Nt-1&&this._addTileFeatures(Wt.range(0,Hn,mn/Nt,so),Wt.data,-1,Bt,Nt,uo),uo.features.length?uo:null}getClusterExpansionZoom(M){let et=this._getOriginZoom(M)-1;for(;et<=this.options.maxZoom;){const Bt=this.getChildren(M);if(et++,1!==Bt.length)break;M=Bt[0].properties.cluster_id}return et}_appendLeaves(M,et,Bt,Wt,Nt){const $t=this.getChildren(et);for(const et of $t){const $t=et.properties;if($t&&$t.cluster?Nt+$t.point_count<=Wt?Nt+=$t.point_count:Nt=this._appendLeaves(M,$t.cluster_id,Bt,Wt,Nt):Nt1;let Hn,so,uo;if(mn)Hn=T(et,M,this.clusterProps),so=et[M],uo=et[M+1];else{const Bt=this.points[et[M+Ia]];Hn=Bt.properties;const[Wt,Nt]=Bt.geometry.coordinates;so=D(Wt),uo=C(Nt)}const Io={type:1,geometry:[[Math.round(this.options.extent*(so*Nt-Bt)),Math.round(this.options.extent*(uo*Nt-Wt))]],tags:Hn};let Po;Po=mn||this.options.generateId?et[M+Ia]:this.points[et[M+Ia]].id,void 0!==Po&&(Io.id=Po),$t.features.push(Io)}}_limitZoom(M){return Math.max(this.options.minZoom,Math.min(Math.floor(+M),this.options.maxZoom+1))}_cluster(M,et){const{radius:Bt,extent:Wt,reduce:Nt,minPoints:$t}=this.options,Gr=Bt/(Wt*Math.pow(2,et)),mn=M.data,Hn=[],so=this.stride;for(let Bt=0;Btet&&(To+=mn[Bt+Ba])}if(To>Po&&To>=$t){let M,$t=Wt*Po,Gr=uo*Po,Eo=-1;const Ia=(Bt/so<<5)+(et+1)+this.points.length;for(const Wt of Io){const Hn=Wt*so;if(mn[Hn+2]<=et)continue;mn[Hn+2]=et;const uo=mn[Hn+Ba];$t+=mn[Hn]*uo,Gr+=mn[Hn+1]*uo,mn[Hn+4]=Ia,Nt&&(M||(M=this._map(mn,Bt,!0),Eo=this.clusterProps.length,this.clusterProps.push(M)),Nt(M,this._map(mn,Hn)))}mn[Bt+4]=Ia,Hn.push($t/To,Gr/To,1/0,Ia,-1,To),Nt&&Hn.push(Eo)}else{for(let M=0;M1)for(const M of Io){const Bt=M*so;if(!(mn[Bt+2]<=et)){mn[Bt+2]=et;for(let M=0;M>5}_getOriginZoom(M){return(M-this.points.length)%32}_map(M,et,Bt){if(M[et+Ba]>1){const Wt=this.clusterProps[M[et+Ta]];return Bt?Object.assign({},Wt):Wt}const Wt=this.points[M[et+Ia]].properties,Nt=this.options.map(Wt);return Bt&&Nt===Wt?Object.assign({},Nt):Nt}}function k(M,et,Bt){return{type:"Feature",id:M[et+Ia],properties:T(M,et,Bt),geometry:{type:"Point",coordinates:[(Wt=M[et],360*(Wt-.5)),O(M[et+1])]}};var Wt}function T(M,et,Bt){const Wt=M[et+Ba],Nt=Wt>=1e4?`${Math.round(Wt/1e3)}k`:Wt>=1e3?Math.round(Wt/100)/10+"k":Wt,$t=M[et+Ta],Gr=-1===$t?{}:Object.assign({},Bt[$t]);return Object.assign(Gr,{cluster:!0,cluster_id:M[et+Ia],point_count:Wt,point_count_abbreviated:Nt})}function D(M){return M/360+.5}function C(M){const et=Math.sin(M*Math.PI/180),Bt=.5-.25*Math.log((1+et)/(1-et))/Math.PI;return Bt<0?0:Bt>1?1:Bt}function O(M){const et=(180-360*M)*Math.PI/180;return 360*Math.atan(Math.exp(et))/Math.PI-90}function L(M,et,Bt,Wt){let Nt=Wt;const $t=et+(Bt-et>>1);let Gr,mn=Bt-et;const Hn=M[et],so=M[et+1],uo=M[Bt],Io=M[Bt+1];for(let Wt=et+3;WtNt)Gr=Wt,Nt=et;else if(et===Nt){const M=Math.abs(Wt-$t);MWt&&(Gr-et>3&&L(M,et,Gr,Wt),M[Gr+2]=Nt,Bt-Gr>3&&L(M,Gr,Bt,Wt))}function F(M,et,Bt,Wt,Nt,$t){let Gr=Nt-Bt,mn=$t-Wt;if(0!==Gr||0!==mn){const Hn=((M-Bt)*Gr+(et-Wt)*mn)/(Gr*Gr+mn*mn);Hn>1?(Bt=Nt,Wt=$t):Hn>0&&(Bt+=Gr*Hn,Wt+=mn*Hn)}return Gr=M-Bt,mn=et-Wt,Gr*Gr+mn*mn}function z(M,et,Bt,Wt){const Nt={id:null==M?null:M,type:et,geometry:Bt,tags:Wt,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("Point"===et||"MultiPoint"===et||"LineString"===et)G(Nt,Bt);else if("Polygon"===et)G(Nt,Bt[0]);else if("MultiLineString"===et)for(const M of Bt)G(Nt,M);else if("MultiPolygon"===et)for(const M of Bt)G(Nt,M[0]);return Nt}function G(M,et){for(let Bt=0;Bt0&&(Gr+=Wt?(Nt*Hn-mn*$t)/2:Math.sqrt(Math.pow(mn-Nt,2)+Math.pow(Hn-$t,2))),Nt=mn,$t=Hn}const mn=et.length-3;et[2]=1,L(et,0,mn,Bt),et[mn+2]=1,et.size=Math.abs(Gr),et.start=0,et.end=et.size}function Z(M,et,Bt,Wt){for(let Nt=0;Nt1?1:Bt}function W(M,et,Bt,Wt,Nt,$t,Gr,mn){if(Wt/=et,$t>=(Bt/=et)&&Gr=Wt)return null;const Hn=[];for(const et of M){const M=et.geometry;let $t=et.type;const Gr=0===Nt?et.minX:et.minY,so=0===Nt?et.maxX:et.maxY;if(Gr>=Bt&&so=Wt)continue;let uo=[];if("Point"===$t||"MultiPoint"===$t)R(M,uo,Bt,Wt,Nt);else if("LineString"===$t)Y(M,uo,Bt,Wt,Nt,!1,mn.lineMetrics);else if("MultiLineString"===$t)X(M,uo,Bt,Wt,Nt,!1);else if("Polygon"===$t)X(M,uo,Bt,Wt,Nt,!0);else if("MultiPolygon"===$t)for(const et of M){const M=[];X(et,M,Bt,Wt,Nt,!0),M.length&&uo.push(M)}if(uo.length){if(mn.lineMetrics&&"LineString"===$t){for(const M of uo)Hn.push(z(et.id,$t,M,et.tags));continue}"LineString"!==$t&&"MultiLineString"!==$t||(1===uo.length?($t="LineString",uo=uo[0]):$t="MultiLineString"),"Point"!==$t&&"MultiPoint"!==$t||($t=3===uo.length?"Point":"MultiPoint"),Hn.push(z(et.id,$t,uo,et.tags))}}return Hn.length?Hn:null}function R(M,et,Bt,Wt,Nt){for(let $t=0;$t=Bt&&Gr<=Wt&&q(et,M[$t],M[$t+1],M[$t+2])}}function Y(M,et,Bt,Wt,Nt,$t,Gr){let mn=V(M);const Hn=0===Nt?B:H;let so,uo,Io=M.start;for(let Po=0;PoBt&&(uo=Hn(mn,To,Eo,Ba,Ta,Bt),Gr&&(mn.start=Io+so*uo)):Va>Wt?za=Bt&&(uo=Hn(mn,To,Eo,Ba,Ta,Bt),Fa=!0),za>Wt&&Va<=Wt&&(uo=Hn(mn,To,Eo,Ba,Ta,Wt),Fa=!0),!$t&&Fa&&(Gr&&(mn.end=Io+so*uo),et.push(mn),mn=V(M)),Gr&&(Io+=so)}let Po=M.length-3;const To=M[Po],Eo=M[Po+1],Ia=0===Nt?To:Eo;Ia>=Bt&&Ia<=Wt&&q(mn,To,Eo,M[Po+2]),Po=mn.length-3,$t&&Po>=3&&(mn[Po]!==mn[0]||mn[Po+1]!==mn[1])&&q(mn,mn[0],mn[1],mn[2]),mn.length&&et.push(mn)}function V(M){const et=[];return et.size=M.size,et.start=M.start,et.end=M.end,et}function X(M,et,Bt,Wt,Nt,$t){for(const Gr of M)Y(Gr,et,Bt,Wt,Nt,$t,!1)}function q(M,et,Bt,Wt){M.push(et,Bt,Wt)}function B(M,et,Bt,Wt,Nt,$t){const Gr=($t-et)/(Wt-et);return q(M,$t,Bt+(Nt-Bt)*Gr,1),Gr}function H(M,et,Bt,Wt,Nt,$t){const Gr=($t-Bt)/(Nt-Bt);return q(M,et+(Wt-et)*Gr,$t,1),Gr}function $(M,et){const Bt=[];for(let Wt=0;Wt0&&et.size<(Nt?Gr:Wt))return void(Bt.numPoints+=et.length/3);const mn=[];for(let M=0;MGr)&&(Bt.numSimplified++,mn.push(et[M],et[M+1])),Bt.numPoints++;Nt&&function(M,et){let Bt=0;for(let et=0,Wt=M.length,Nt=Wt-2;et0===et)for(let et=0,Bt=M.length;et24)throw new Error("maxZoom should be in the 0-24 range");if(et.promoteId&&et.generateId)throw new Error("promoteId and generateId cannot be used together.");let Wt=function(M,et){const Bt=[];if("FeatureCollection"===M.type)for(let Wt=0;Wt1&&console.time("creation"),Po=this.tiles[Io]=ee(M,et,Bt,Wt,Hn),this.tileCoords.push({z:et,x:Bt,y:Wt}),so)){so>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",et,Bt,Wt,Po.numFeatures,Po.numPoints,Po.numSimplified),console.timeEnd("creation"));const M=`z${et}`;this.stats[M]=(this.stats[M]||0)+1,this.total++}if(Po.source=M,null==Nt){if(et===Hn.indexMaxZoom||Po.numPoints<=Hn.indexMaxPoints)continue}else{if(et===Hn.maxZoom||et===Nt)continue;if(null!=Nt){const M=Nt-et;if(Bt!==$t>>M||Wt!==Gr>>M)continue}}if(Po.source=null,0===M.length)continue;so>1&&console.time("clipping");const To=.5*Hn.buffer/Hn.extent,Eo=.5-To,Ia=.5+To,Ba=1+To;let Ta=null,Va=null,za=null,Fa=null,Ea=W(M,uo,Bt-To,Bt+Ia,0,Po.minX,Po.maxX,Hn),La=W(M,uo,Bt+Eo,Bt+Ba,0,Po.minX,Po.maxX,Hn);M=null,Ea&&(Ta=W(Ea,uo,Wt-To,Wt+Ia,1,Po.minY,Po.maxY,Hn),Va=W(Ea,uo,Wt+Eo,Wt+Ba,1,Po.minY,Po.maxY,Hn),Ea=null),La&&(za=W(La,uo,Wt-To,Wt+Ia,1,Po.minY,Po.maxY,Hn),Fa=W(La,uo,Wt+Eo,Wt+Ba,1,Po.minY,Po.maxY,Hn),La=null),so>1&&console.timeEnd("clipping"),mn.push(Ta||[],et+1,2*Bt,2*Wt),mn.push(Va||[],et+1,2*Bt,2*Wt+1),mn.push(za||[],et+1,2*Bt+1,2*Wt),mn.push(Fa||[],et+1,2*Bt+1,2*Wt+1)}}getTile(M,et,Bt){M=+M,et=+et,Bt=+Bt;const Wt=this.options,{extent:Nt,debug:$t}=Wt;if(M<0||M>24)return null;const Gr=1<1&&console.log("drilling down to z%d-%d-%d",M,et,Bt);let Hn,so=M,uo=et,Io=Bt;for(;!Hn&&so>0;)so--,uo>>=1,Io>>=1,Hn=this.tiles[se(so,uo,Io)];return Hn&&Hn.source?($t>1&&(console.log("found parent tile z%d-%d-%d",so,uo,Io),console.time("drilling down")),this.splitTile(Hn.source,so,uo,Io,M,et,Bt),$t>1&&console.timeEnd("drilling down"),this.tiles[mn]?K(this.tiles[mn],Nt):null):null}}function se(M,et,Bt){return 32*((1<{Gr.properties=M;const et={};for(const M of mn)et[M]=Wt[M].evaluate($t,Gr);return et},et.reduce=(M,et)=>{Gr.properties=et;for(const et of mn)$t.accumulated=M[et],M[et]=Nt[et].evaluate($t,Gr)},et}(et)).load((yield this._pendingData).features):(Nt=yield this._pendingData,new re(Nt,et.geojsonVtOptions)),this.loaded={};const Bt={};if(Wt){const M=Wt.finish();M&&(Bt.resourceTiming={},Bt.resourceTiming[et.source]=JSON.parse(JSON.stringify(M)))}return Bt}catch(et){if(delete this._pendingRequest,M.cf(et))return{abandoned:!0};throw et}var Nt}))}getData(){return M._(this,void 0,void 0,(function*(){return this._pendingData}))}reloadTile(M){const et=this.loaded;return et&&et[M.uid]?super.reloadTile(M):this.loadTile(M)}loadAndProcessGeoJSON(et,Bt){return M._(this,void 0,void 0,(function*(){let Wt=yield this.loadGeoJSON(et,Bt);if(delete this._pendingRequest,"object"!=typeof Wt)throw new Error(`Input data given to '${et.source}' is not a valid GeoJSON object.`);if(Nt(Wt,!0),et.filter){const Bt=M.cB(et.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if("error"===Bt.result)throw new Error(Bt.value.map((M=>`${M.key}: ${M.message}`)).join(", "));const Nt=Wt.features.filter((M=>Bt.value.evaluate({zoom:0},M)));Wt={type:"FeatureCollection",features:Nt}}return Wt}))}loadGeoJSON(et,Bt){return M._(this,void 0,void 0,(function*(){const{promoteId:Wt}=et;if(et.request){const Nt=yield M.h(et.request,Bt);return this._dataUpdateable=ae(Nt.data,Wt)?le(Nt.data,Wt):void 0,Nt.data}if("string"==typeof et.data)try{const M=JSON.parse(et.data);return this._dataUpdateable=ae(M,Wt)?le(M,Wt):void 0,M}catch(M){throw new Error(`Input data given to '${et.source}' is not a valid GeoJSON object.`)}if(!et.dataDiff)throw new Error(`Input data given to '${et.source}' is not a valid GeoJSON object.`);if(!this._dataUpdateable)throw new Error(`Cannot update existing geojson data in ${et.source}`);return function(M,et,Bt){var Wt,Nt,$t,Gr;if(et.removeAll&&M.clear(),et.remove)for(const Bt of et.remove)M.delete(Bt);if(et.add)for(const Wt of et.add){const et=ne(Wt,Bt);null!=et&&M.set(et,Wt)}if(et.update)for(const Bt of et.update){let et=M.get(Bt.id);if(null==et)continue;const mn=!Bt.removeAllProperties&&((null===(Wt=Bt.removeProperties)||void 0===Wt?void 0:Wt.length)>0||(null===(Nt=Bt.addOrUpdateProperties)||void 0===Nt?void 0:Nt.length)>0);if((Bt.newGeometry||Bt.removeAllProperties||mn)&&(et=Object.assign({},et),M.set(Bt.id,et),mn&&(et.properties=Object.assign({},et.properties))),Bt.newGeometry&&(et.geometry=Bt.newGeometry),Bt.removeAllProperties)et.properties={};else if((null===($t=Bt.removeProperties)||void 0===$t?void 0:$t.length)>0)for(const M of Bt.removeProperties)Object.prototype.hasOwnProperty.call(et.properties,M)&&delete et.properties[M];if((null===(Gr=Bt.addOrUpdateProperties)||void 0===Gr?void 0:Gr.length)>0)for(const{key:M,value:Wt}of Bt.addOrUpdateProperties)et.properties[M]=Wt}}(this._dataUpdateable,et.dataDiff,Wt),{type:"FeatureCollection",features:Array.from(this._dataUpdateable.values())}}))}removeSource(et){return M._(this,void 0,void 0,(function*(){this._pendingRequest&&this._pendingRequest.abort()}))}getClusterExpansionZoom(M){return this._geoJSONIndex.getClusterExpansionZoom(M.clusterId)}getClusterChildren(M){return this._geoJSONIndex.getChildren(M.clusterId)}getClusterLeaves(M){return this._geoJSONIndex.getLeaves(M.clusterId,M.limit,M.offset)}}class ue{constructor(et){this.self=et,this.actor=new M.F(et),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.self.registerWorkerSource=(M,et)=>{if(this.externalWorkerSourceTypes[M])throw new Error(`Worker source with name "${M}" already registered.`);this.externalWorkerSourceTypes[M]=et},this.self.addProtocol=M.ch,this.self.removeProtocol=M.ci,this.self.registerRTLTextPlugin=et=>{M.cC.setMethods(et)},this.actor.registerMessageHandler("LDT",((M,et)=>this._getDEMWorkerSource(M,et.source).loadTile(et))),this.actor.registerMessageHandler("RDT",((et,Bt)=>M._(this,void 0,void 0,(function*(){this._getDEMWorkerSource(et,Bt.source).removeTile(Bt)})))),this.actor.registerMessageHandler("GCEZ",((et,Bt)=>M._(this,void 0,void 0,(function*(){return this._getWorkerSource(et,Bt.type,Bt.source).getClusterExpansionZoom(Bt)})))),this.actor.registerMessageHandler("GCC",((et,Bt)=>M._(this,void 0,void 0,(function*(){return this._getWorkerSource(et,Bt.type,Bt.source).getClusterChildren(Bt)})))),this.actor.registerMessageHandler("GCL",((et,Bt)=>M._(this,void 0,void 0,(function*(){return this._getWorkerSource(et,Bt.type,Bt.source).getClusterLeaves(Bt)})))),this.actor.registerMessageHandler("LD",((M,et)=>this._getWorkerSource(M,et.type,et.source).loadData(et))),this.actor.registerMessageHandler("GD",((M,et)=>this._getWorkerSource(M,et.type,et.source).getData())),this.actor.registerMessageHandler("LT",((M,et)=>this._getWorkerSource(M,et.type,et.source).loadTile(et))),this.actor.registerMessageHandler("RT",((M,et)=>this._getWorkerSource(M,et.type,et.source).reloadTile(et))),this.actor.registerMessageHandler("AT",((M,et)=>this._getWorkerSource(M,et.type,et.source).abortTile(et))),this.actor.registerMessageHandler("RMT",((M,et)=>this._getWorkerSource(M,et.type,et.source).removeTile(et))),this.actor.registerMessageHandler("RS",((et,Bt)=>M._(this,void 0,void 0,(function*(){if(!this.workerSources[et]||!this.workerSources[et][Bt.type]||!this.workerSources[et][Bt.type][Bt.source])return;const M=this.workerSources[et][Bt.type][Bt.source];delete this.workerSources[et][Bt.type][Bt.source],void 0!==M.removeSource&&M.removeSource(Bt)})))),this.actor.registerMessageHandler("RM",(et=>M._(this,void 0,void 0,(function*(){delete this.layerIndexes[et],delete this.availableImages[et],delete this.workerSources[et],delete this.demWorkerSources[et]})))),this.actor.registerMessageHandler("SR",((et,Bt)=>M._(this,void 0,void 0,(function*(){this.referrer=Bt})))),this.actor.registerMessageHandler("SRPS",((M,et)=>this._syncRTLPluginState(M,et))),this.actor.registerMessageHandler("IS",((et,Bt)=>M._(this,void 0,void 0,(function*(){this.self.importScripts(Bt)})))),this.actor.registerMessageHandler("SI",((M,et)=>this._setImages(M,et))),this.actor.registerMessageHandler("UL",((et,Bt)=>M._(this,void 0,void 0,(function*(){this._getLayerIndex(et).update(Bt.layers,Bt.removedIds)})))),this.actor.registerMessageHandler("SL",((et,Bt)=>M._(this,void 0,void 0,(function*(){this._getLayerIndex(et).replace(Bt)}))))}_setImages(et,Bt){return M._(this,void 0,void 0,(function*(){this.availableImages[et]=Bt;for(const M in this.workerSources[et]){const Wt=this.workerSources[et][M];for(const M in Wt)Wt[M].availableImages=Bt}}))}_syncRTLPluginState(et,Bt){return M._(this,void 0,void 0,(function*(){return yield M.cC.syncState(Bt,this.self.importScripts)}))}_getAvailableImages(M){let et=this.availableImages[M];return et||(et=[]),et}_getLayerIndex(M){let et=this.layerIndexes[M];return et||(et=this.layerIndexes[M]=new t),et}_getWorkerSource(M,et,Bt){if(this.workerSources[M]||(this.workerSources[M]={}),this.workerSources[M][et]||(this.workerSources[M][et]={}),!this.workerSources[M][et][Bt]){const Wt={sendAsync:(et,Bt)=>(et.targetMapId=M,this.actor.sendAsync(et,Bt))};switch(et){case"vector":this.workerSources[M][et][Bt]=new s(Wt,this._getLayerIndex(M),this._getAvailableImages(M));break;case"geojson":this.workerSources[M][et][Bt]=new ce(Wt,this._getLayerIndex(M),this._getAvailableImages(M));break;default:this.workerSources[M][et][Bt]=new this.externalWorkerSourceTypes[et](Wt,this._getLayerIndex(M),this._getAvailableImages(M))}}return this.workerSources[M][et][Bt]}_getDEMWorkerSource(M,et){return this.demWorkerSources[M]||(this.demWorkerSources[M]={}),this.demWorkerSources[M][et]||(this.demWorkerSources[M][et]=new n),this.demWorkerSources[M][et]}}return M.i(self)&&(self.worker=new ue(self)),ue})),define("index",["exports","./shared"],(function(M,et){var Bt="5.0.0";function r(){var M=new et.A(4);return et.A!=Float32Array&&(M[1]=0,M[2]=0),M[0]=1,M[3]=1,M}let Wt,Nt;const $t={now:"undefined"!=typeof performance&&performance&&performance.now?performance.now.bind(performance):Date.now.bind(Date),frameAsync:M=>new Promise(((Bt,Wt)=>{const Nt=requestAnimationFrame(Bt);M.signal.addEventListener("abort",(()=>{cancelAnimationFrame(Nt),Wt(et.c())}))})),getImageData(M,et=0){return this.getImageCanvasContext(M).getImageData(-et,-et,M.width+2*et,M.height+2*et)},getImageCanvasContext(M){const et=window.document.createElement("canvas"),Bt=et.getContext("2d",{willReadFrequently:!0});if(!Bt)throw new Error("failed to create canvas 2d context");return et.width=M.width,et.height=M.height,Bt.drawImage(M,0,0,M.width,M.height),Bt},resolveURL:M=>(Wt||(Wt=document.createElement("a")),Wt.href=M,Wt.href),hardwareConcurrency:"undefined"!=typeof navigator&&navigator.hardwareConcurrency||4,get prefersReducedMotion(){return!!matchMedia&&(null==Nt&&(Nt=matchMedia("(prefers-reduced-motion: reduce)")),Nt.matches)}};class n{static testProp(M){if(!n.docStyle)return M[0];for(let et=0;et{window.removeEventListener("click",n.suppressClickInternal,!0)}),0)}static getScale(M){const et=M.getBoundingClientRect();return{x:et.width/M.offsetWidth||1,y:et.height/M.offsetHeight||1,boundingClientRect:et}}static getPoint(M,Bt,Wt){const Nt=Bt.boundingClientRect;return new et.P((Wt.clientX-Nt.left)/Bt.x-M.clientLeft,(Wt.clientY-Nt.top)/Bt.y-M.clientTop)}static mousePos(M,et){const Bt=n.getScale(M);return n.getPoint(M,Bt,et)}static touchPos(M,et){const Bt=[],Wt=n.getScale(M);for(let Nt=0;Nt{mn&&_(mn),mn=null,uo=!0},Hn.onerror=()=>{so=!0,mn=null},Hn.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA="),function(M){let Bt,Wt,Nt,$t;M.resetRequestQueue=()=>{Bt=[],Wt=0,Nt=0,$t={}},M.addThrottleControl=M=>{const et=Nt++;return $t[et]=M,et},M.removeThrottleControl=M=>{delete $t[M],n()},M.getImage=(M,Wt,Nt=!0)=>new Promise((($t,mn)=>{Gr.supported&&(M.headers||(M.headers={}),M.headers.accept="image/webp,*/*"),et.e(M,{type:"image"}),Bt.push({abortController:Wt,requestParameters:M,supportImageRefresh:Nt,state:"queued",onError:M=>{mn(M)},onSuccess:M=>{$t(M)}}),n()}));const a=M=>et._(this,void 0,void 0,(function*(){M.state="running";const{requestParameters:Bt,supportImageRefresh:Nt,onError:$t,onSuccess:Gr,abortController:mn}=M,Hn=!1===Nt&&!et.i(self)&&!et.g(Bt.url)&&(!Bt.headers||Object.keys(Bt.headers).reduce(((M,et)=>M&&"accept"===et),!0));Wt++;const so=Hn?c(Bt,mn):et.m(Bt,mn);try{const Bt=yield so;delete M.abortController,M.state="completed",Bt.data instanceof HTMLImageElement||et.b(Bt.data)?Gr(Bt):Bt.data&&Gr({data:yield(uo=Bt.data,"function"==typeof createImageBitmap?et.d(uo):et.f(uo)),cacheControl:Bt.cacheControl,expires:Bt.expires})}catch(et){delete M.abortController,$t(et)}finally{Wt--,n()}var uo})),n=()=>{const M=(()=>{for(const M of Object.keys($t))if($t[M]())return!0;return!1})()?et.a.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME:et.a.MAX_PARALLEL_IMAGE_REQUESTS;for(let et=Wt;et0;et++){const M=Bt.shift();M.abortController.signal.aborted?et--:a(M)}},c=(M,Bt)=>new Promise(((Wt,Nt)=>{const $t=new Image,Gr=M.url,mn=M.credentials;mn&&"include"===mn?$t.crossOrigin="use-credentials":(mn&&"same-origin"===mn||!et.s(Gr))&&($t.crossOrigin="anonymous"),Bt.signal.addEventListener("abort",(()=>{$t.src="",Nt(et.c())})),$t.fetchPriority="high",$t.onload=()=>{$t.onerror=$t.onload=null,Wt({data:$t})},$t.onerror=()=>{$t.onerror=$t.onload=null,Bt.signal.aborted||Nt(new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."))},$t.src=Gr}))}(Io||(Io={})),Io.resetRequestQueue();class m{constructor(M){this._transformRequestFn=M}transformRequest(M,et){return this._transformRequestFn&&this._transformRequestFn(M,et)||{url:M}}setTransformRequest(M){this._transformRequestFn=M}}function f(M){const et=[];if("string"==typeof M)et.push({id:"default",url:M});else if(M&&M.length>0){const Bt=[];for(const{id:Wt,url:Nt}of M){const M=`${Wt}${Nt}`;-1===Bt.indexOf(M)&&(Bt.push(M),et.push({id:Wt,url:Nt}))}}return et}function g(M,et,Bt){try{const Wt=new URL(M);return Wt.pathname+=`${et}${Bt}`,Wt.toString()}catch(et){throw new Error(`Invalid sprite URL "${M}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`)}}class v{constructor(M,et,Bt,Wt){this.context=M,this.format=Bt,this.texture=M.gl.createTexture(),this.update(et,Wt)}update(M,Bt,Wt){const{width:Nt,height:$t}=M,Gr=!(this.size&&this.size[0]===Nt&&this.size[1]===$t||Wt),{context:mn}=this,{gl:Hn}=mn;if(this.useMipmap=Boolean(Bt&&Bt.useMipmap),Hn.bindTexture(Hn.TEXTURE_2D,this.texture),mn.pixelStoreUnpackFlipY.set(!1),mn.pixelStoreUnpack.set(1),mn.pixelStoreUnpackPremultiplyAlpha.set(this.format===Hn.RGBA&&(!Bt||!1!==Bt.premultiply)),Gr)this.size=[Nt,$t],M instanceof HTMLImageElement||M instanceof HTMLCanvasElement||M instanceof HTMLVideoElement||M instanceof ImageData||et.b(M)?Hn.texImage2D(Hn.TEXTURE_2D,0,this.format,this.format,Hn.UNSIGNED_BYTE,M):Hn.texImage2D(Hn.TEXTURE_2D,0,this.format,Nt,$t,0,this.format,Hn.UNSIGNED_BYTE,M.data);else{const{x:Bt,y:Gr}=Wt||{x:0,y:0};M instanceof HTMLImageElement||M instanceof HTMLCanvasElement||M instanceof HTMLVideoElement||M instanceof ImageData||et.b(M)?Hn.texSubImage2D(Hn.TEXTURE_2D,0,Bt,Gr,Hn.RGBA,Hn.UNSIGNED_BYTE,M):Hn.texSubImage2D(Hn.TEXTURE_2D,0,Bt,Gr,Nt,$t,Hn.RGBA,Hn.UNSIGNED_BYTE,M.data)}this.useMipmap&&this.isSizePowerOfTwo()&&Hn.generateMipmap(Hn.TEXTURE_2D)}bind(M,et,Bt){const{context:Wt}=this,{gl:Nt}=Wt;Nt.bindTexture(Nt.TEXTURE_2D,this.texture),Bt!==Nt.LINEAR_MIPMAP_NEAREST||this.isSizePowerOfTwo()||(Bt=Nt.LINEAR),M!==this.filter&&(Nt.texParameteri(Nt.TEXTURE_2D,Nt.TEXTURE_MAG_FILTER,M),Nt.texParameteri(Nt.TEXTURE_2D,Nt.TEXTURE_MIN_FILTER,Bt||M),this.filter=M),et!==this.wrap&&(Nt.texParameteri(Nt.TEXTURE_2D,Nt.TEXTURE_WRAP_S,et),Nt.texParameteri(Nt.TEXTURE_2D,Nt.TEXTURE_WRAP_T,et),this.wrap=et)}isSizePowerOfTwo(){return this.size[0]===this.size[1]&&Math.log(this.size[0])/Math.LN2%1==0}destroy(){const{gl:M}=this.context;M.deleteTexture(this.texture),this.texture=null}}function x(M){const{userImage:et}=M;return!!(et&&et.render&&et.render())&&(M.data.replace(new Uint8Array(et.data.buffer)),!0)}class b extends et.E{constructor(){super(),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new et.R({width:1,height:1}),this.dirty=!0}isLoaded(){return this.loaded}setLoaded(M){if(this.loaded!==M&&(this.loaded=M,M)){for(const{ids:M,promiseResolve:et}of this.requestors)et(this._getImagesForIds(M));this.requestors=[]}}getImage(M){const Bt=this.images[M];if(Bt&&!Bt.data&&Bt.spriteData){const M=Bt.spriteData;Bt.data=new et.R({width:M.width,height:M.height},M.context.getImageData(M.x,M.y,M.width,M.height).data),Bt.spriteData=null}return Bt}addImage(M,et){if(this.images[M])throw new Error(`Image id ${M} already exist, use updateImage instead`);this._validate(M,et)&&(this.images[M]=et)}_validate(M,Bt){let Wt=!0;const Nt=Bt.data||Bt.spriteData;return this._validateStretch(Bt.stretchX,Nt&&Nt.width)||(this.fire(new et.j(new Error(`Image "${M}" has invalid "stretchX" value`))),Wt=!1),this._validateStretch(Bt.stretchY,Nt&&Nt.height)||(this.fire(new et.j(new Error(`Image "${M}" has invalid "stretchY" value`))),Wt=!1),this._validateContent(Bt.content,Bt)||(this.fire(new et.j(new Error(`Image "${M}" has invalid "content" value`))),Wt=!1),Wt}_validateStretch(M,et){if(!M)return!0;let Bt=0;for(const Wt of M){if(Wt[0]{let Wt=!0;if(!this.isLoaded())for(const et of M)this.images[et]||(Wt=!1);this.isLoaded()||Wt?et(this._getImagesForIds(M)):this.requestors.push({ids:M,promiseResolve:et})}))}_getImagesForIds(M){const Bt={};for(const Wt of M){let M=this.getImage(Wt);M||(this.fire(new et.k("styleimagemissing",{id:Wt})),M=this.getImage(Wt)),M?Bt[Wt]={data:M.data.clone(),pixelRatio:M.pixelRatio,sdf:M.sdf,version:M.version,stretchX:M.stretchX,stretchY:M.stretchY,content:M.content,textFitWidth:M.textFitWidth,textFitHeight:M.textFitHeight,hasRenderCallback:Boolean(M.userImage&&M.userImage.render)}:et.w(`Image "${Wt}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`)}return Bt}getPixelSize(){const{width:M,height:et}=this.atlasImage;return{width:M,height:et}}getPattern(M){const Bt=this.patterns[M],Wt=this.getImage(M);if(!Wt)return null;if(Bt&&Bt.position.version===Wt.version)return Bt.position;if(Bt)Bt.position.version=Wt.version;else{const Bt={w:Wt.data.width+2,h:Wt.data.height+2,x:0,y:0},Nt=new et.I(Bt,Wt);this.patterns[M]={bin:Bt,position:Nt}}return this._updatePatternAtlas(),this.patterns[M].position}bind(M){const et=M.gl;this.atlasTexture?this.dirty&&(this.atlasTexture.update(this.atlasImage),this.dirty=!1):this.atlasTexture=new v(M,this.atlasImage,et.RGBA),this.atlasTexture.bind(et.LINEAR,et.CLAMP_TO_EDGE)}_updatePatternAtlas(){const M=[];for(const et in this.patterns)M.push(this.patterns[et].bin);const{w:Bt,h:Wt}=et.p(M),Nt=this.atlasImage;Nt.resize({width:Bt||1,height:Wt||1});for(const M in this.patterns){const{bin:Bt}=this.patterns[M],Wt=Bt.x+1,$t=Bt.y+1,Gr=this.getImage(M).data,mn=Gr.width,Hn=Gr.height;et.R.copy(Gr,Nt,{x:0,y:0},{x:Wt,y:$t},{width:mn,height:Hn}),et.R.copy(Gr,Nt,{x:0,y:Hn-1},{x:Wt,y:$t-1},{width:mn,height:1}),et.R.copy(Gr,Nt,{x:0,y:0},{x:Wt,y:$t+Hn},{width:mn,height:1}),et.R.copy(Gr,Nt,{x:mn-1,y:0},{x:Wt-1,y:$t},{width:1,height:Hn}),et.R.copy(Gr,Nt,{x:0,y:0},{x:Wt+mn,y:$t},{width:1,height:Hn})}this.dirty=!0}beginFrame(){this.callbackDispatchedThisFrame={}}dispatchRenderCallbacks(M){for(const Bt of M){if(this.callbackDispatchedThisFrame[Bt])continue;this.callbackDispatchedThisFrame[Bt]=!0;const M=this.getImage(Bt);M||et.w(`Image with ID: "${Bt}" was not found`),x(M)&&this.updateImage(Bt,M)}}}const Po=1e20;function w(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn){for(let so=et;so-1);Hn++,$t[Hn]=mn,Gr[Hn]=so,Gr[Hn+1]=Po}for(let mn=0,Hn=0;mn65535)throw new Error("glyphs > 65535 not supported");if(et.ranges[Nt])return{stack:M,id:Bt,glyph:Wt};if(!this.url)throw new Error("glyphsUrl is not set");if(!et.requests[Nt]){const Bt=P.loadGlyphRange(M,Nt,this.url,this.requestManager);et.requests[Nt]=Bt}const $t=yield et.requests[Nt];for(const M in $t)this._doesCharSupportLocalGlyph(+M)||(et.glyphs[+M]=$t[+M]);return et.ranges[Nt]=!0,{stack:M,id:Bt,glyph:$t[Bt]||null}}))}_doesCharSupportLocalGlyph(M){return!!this.localIdeographFontFamily&&/\p{Ideo}|\p{sc=Hang}|\p{sc=Hira}|\p{sc=Kana}/u.test(String.fromCodePoint(M))}_tinySDF(M,Bt,Wt){const Nt=this.localIdeographFontFamily;if(!Nt)return;if(!this._doesCharSupportLocalGlyph(Wt))return;let $t=M.tinySDF;if(!$t){let et="400";/bold/i.test(Bt)?et="900":/medium/i.test(Bt)?et="500":/light/i.test(Bt)&&(et="200"),$t=M.tinySDF=new P.TinySDF({fontSize:48,buffer:6,radius:16,cutoff:.25,fontFamily:Nt,fontWeight:et})}const Gr=$t.draw(String.fromCharCode(Wt));return{id:Wt,bitmap:new et.o({width:Gr.width||60,height:Gr.height||60},Gr.data),metrics:{width:Gr.glyphWidth/2||24,height:Gr.glyphHeight/2||24,left:Gr.glyphLeft/2+.5||0,top:Gr.glyphTop/2-27.5||-8,advance:Gr.glyphAdvance/2||24,isDoubleResolution:!0}}}}P.loadGlyphRange=function(M,Bt,Wt,Nt){return et._(this,void 0,void 0,(function*(){const $t=256*Bt,Gr=$t+255,mn=Nt.transformRequest(Wt.replace("{fontstack}",M).replace("{range}",`${$t}-${Gr}`),"Glyphs"),Hn=yield et.l(mn,new AbortController);if(!Hn||!Hn.data)throw new Error(`Could not load glyph range. range: ${Bt}, ${$t}-${Gr}`);const so={};for(const M of et.n(Hn.data))so[M.id]=M;return so}))},P.TinySDF=class{constructor({fontSize:M=24,buffer:et=3,radius:Bt=8,cutoff:Wt=.25,fontFamily:Nt="sans-serif",fontWeight:$t="normal",fontStyle:Gr="normal"}={}){this.buffer=et,this.cutoff=Wt,this.radius=Bt;const mn=this.size=M+4*et,Hn=this._createCanvas(mn),so=this.ctx=Hn.getContext("2d",{willReadFrequently:!0});so.font=`${Gr} ${$t} ${M}px ${Nt}`,so.textBaseline="alphabetic",so.textAlign="left",so.fillStyle="black",this.gridOuter=new Float64Array(mn*mn),this.gridInner=new Float64Array(mn*mn),this.f=new Float64Array(mn),this.z=new Float64Array(mn+1),this.v=new Uint16Array(mn)}_createCanvas(M){const et=document.createElement("canvas");return et.width=et.height=M,et}draw(M){const{width:et,actualBoundingBoxAscent:Bt,actualBoundingBoxDescent:Wt,actualBoundingBoxLeft:Nt,actualBoundingBoxRight:$t}=this.ctx.measureText(M),Gr=Math.ceil(Bt),mn=Math.max(0,Math.min(this.size-this.buffer,Math.ceil($t-Nt))),Hn=Math.min(this.size-this.buffer,Gr+Math.ceil(Wt)),so=mn+2*this.buffer,uo=Hn+2*this.buffer,Io=Math.max(so*uo,0),To=new Uint8ClampedArray(Io),Eo={data:To,width:so,height:uo,glyphWidth:mn,glyphHeight:Hn,glyphTop:Gr,glyphLeft:0,glyphAdvance:et};if(0===mn||0===Hn)return Eo;const{ctx:Ia,buffer:Ba,gridInner:Ta,gridOuter:Va}=this;Ia.clearRect(Ba,Ba,mn,Hn),Ia.fillText(M,Ba,Ba+Gr);const za=Ia.getImageData(Ba,Ba,mn,Hn);Va.fill(Po,0,Io),Ta.fill(0,0,Io);for(let M=0;M0?M*M:0,Ta[Wt]=M<0?M*M:0}}w(Va,0,0,so,uo,so,this.f,this.v,this.z),w(Ta,Ba,Ba,mn,Hn,so,this.f,this.v,this.z);for(let M=0;M1&&(Gr=M[++$t]);const Hn=Math.abs(mn-Gr.left),so=Math.abs(mn-Gr.right),uo=Math.min(Hn,so);let Io;const Po=et/Bt*(Wt+1);if(Gr.isDash){const M=Wt-Math.abs(Po);Io=Math.sqrt(uo*uo+M*M)}else Io=Wt-Math.sqrt(uo*uo+Po*Po);this.data[Nt+mn]=Math.max(0,Math.min(255,Io+128))}}}addRegularDash(M){for(let et=M.length-1;et>=0;--et){const Bt=M[et],Wt=M[et+1];Bt.zeroLength?M.splice(et,1):Wt&&Wt.isDash===Bt.isDash&&(Wt.left=Bt.left,M.splice(et,1))}const et=M[0],Bt=M[M.length-1];et.isDash===Bt.isDash&&(et.left=Bt.left-this.width,Bt.right=et.right+this.width);const Wt=this.width*this.nextRow;let Nt=0,$t=M[Nt];for(let et=0;et1&&($t=M[++Nt]);const Bt=Math.abs(et-$t.left),Gr=Math.abs(et-$t.right),mn=Math.min(Bt,Gr);this.data[Wt+et]=Math.max(0,Math.min(255,($t.isDash?mn:-mn)+128))}}addDash(M,Bt){const Wt=Bt?7:0,Nt=2*Wt+1;if(this.nextRow+Nt>this.height)return et.w("LineAtlas out of space"),null;let $t=0;for(let et=0;et{M.terminate()})),this.workers=null)}isPreloaded(){return!!this.active[Ia]}numActive(){return Object.keys(this.active).length}}const Ba=Math.floor($t.hardwareConcurrency/2);let Ta,Va;function F(){return Ta||(Ta=new z),Ta}z.workerCount=et.C(globalThis)?Math.max(Math.min(Ba,3),1):1;class B{constructor(M,Bt){this.workerPool=M,this.actors=[],this.currentActor=0,this.id=Bt;const Wt=this.workerPool.acquire(Bt);for(let M=0;M{M.remove()})),this.actors=[],M&&this.workerPool.release(this.id)}registerMessageHandler(M,et){for(const Bt of this.actors)Bt.registerMessageHandler(M,et)}}function j(){return Va||(Va=new B(F(),et.G),Va.registerMessageHandler("GR",((M,Bt,Wt)=>et.m(Bt,Wt)))),Va}function O(M,Bt){const Wt=et.H();return et.J(Wt,Wt,[1,1,0]),et.K(Wt,Wt,[.5*M.width,.5*M.height,1]),M.calculatePosMatrix?et.L(Wt,Wt,M.calculatePosMatrix(Bt.toUnwrapped())):Wt}function N(M,et,Bt,Wt,Nt,$t){var Gr;const mn=function(M,et,Bt){if(M)for(const Wt of M){const M=et[Wt];if(M&&M.source===Bt&&"fill-extrusion"===M.type)return!0}else for(const M in et){const Wt=et[M];if(Wt.source===Bt&&"fill-extrusion"===Wt.type)return!0}return!1}(null!==(Gr=null==Nt?void 0:Nt.layers)&&void 0!==Gr?Gr:null,et,M.id),Hn=$t.maxPitchScaleFactor(),so=M.tilesIn(Wt,Hn,mn);so.sort(Z);const uo=[];for(const Wt of so)uo.push({wrappedTileID:Wt.tileID.wrapped().key,queryResults:Wt.tile.queryRenderedFeatures(et,Bt,M._state,Wt.queryGeometry,Wt.cameraQueryGeometry,Wt.scale,Nt,$t,Hn,O(M.transform,Wt.tileID))});return function(M,et){for(const Bt in M)for(const Wt of M[Bt])G(Wt,et);return M}(function(M){const et={},Bt={};for(const Wt of M){const M=Wt.queryResults,Nt=Wt.wrappedTileID,$t=Bt[Nt]=Bt[Nt]||{};for(const Bt in M){const Wt=M[Bt],Nt=$t[Bt]=$t[Bt]||{},Gr=et[Bt]=et[Bt]||[];for(const M of Wt)Nt[M.featureIndex]||(Nt[M.featureIndex]=!0,Gr.push(M))}}return et}(uo),M)}function Z(M,et){const Bt=M.tileID,Wt=et.tileID;return Bt.overscaledZ-Wt.overscaledZ||Bt.canonical.y-Wt.canonical.y||Bt.wrap-Wt.wrap||Bt.canonical.x-Wt.canonical.x}function G(M,et){const Bt=M.feature,Wt=et.getFeatureState(Bt.layer["source-layer"],Bt.id);Bt.source=Bt.layer.source,Bt.layer["source-layer"]&&(Bt.sourceLayer=Bt.layer["source-layer"]),Bt.state=Wt}function U(M,Bt,Wt){return et._(this,void 0,void 0,(function*(){let Nt=M;if(M.url?Nt=(yield et.h(Bt.transformRequest(M.url,"Source"),Wt)).data:yield $t.frameAsync(Wt),!Nt)return null;const Gr=et.M(et.e(Nt,M),["tiles","minzoom","maxzoom","attribution","bounds","scheme","tileSize","encoding"]);return"vector_layers"in Nt&&Nt.vector_layers&&(Gr.vectorLayerIds=Nt.vector_layers.map((M=>M.id))),Gr}))}class V{constructor(M,et){M&&(et?this.setSouthWest(M).setNorthEast(et):Array.isArray(M)&&(4===M.length?this.setSouthWest([M[0],M[1]]).setNorthEast([M[2],M[3]]):this.setSouthWest(M[0]).setNorthEast(M[1])))}setNorthEast(M){return this._ne=M instanceof et.N?new et.N(M.lng,M.lat):et.N.convert(M),this}setSouthWest(M){return this._sw=M instanceof et.N?new et.N(M.lng,M.lat):et.N.convert(M),this}extend(M){const Bt=this._sw,Wt=this._ne;let Nt,$t;if(M instanceof et.N)Nt=M,$t=M;else{if(!(M instanceof V))return Array.isArray(M)?4===M.length||M.every(Array.isArray)?this.extend(V.convert(M)):this.extend(et.N.convert(M)):M&&("lng"in M||"lon"in M)&&"lat"in M?this.extend(et.N.convert(M)):this;if(Nt=M._sw,$t=M._ne,!Nt||!$t)return this}return Bt||Wt?(Bt.lng=Math.min(Nt.lng,Bt.lng),Bt.lat=Math.min(Nt.lat,Bt.lat),Wt.lng=Math.max($t.lng,Wt.lng),Wt.lat=Math.max($t.lat,Wt.lat)):(this._sw=new et.N(Nt.lng,Nt.lat),this._ne=new et.N($t.lng,$t.lat)),this}getCenter(){return new et.N((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)}getSouthWest(){return this._sw}getNorthEast(){return this._ne}getNorthWest(){return new et.N(this.getWest(),this.getNorth())}getSouthEast(){return new et.N(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return[this._sw.toArray(),this._ne.toArray()]}toString(){return`LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return!(this._sw&&this._ne)}contains(M){const{lng:Bt,lat:Wt}=et.N.convert(M);let Nt=this._sw.lng<=Bt&&Bt<=this._ne.lng;return this._sw.lng>this._ne.lng&&(Nt=this._sw.lng>=Bt&&Bt>=this._ne.lng),this._sw.lat<=Wt&&Wt<=this._ne.lat&&Nt}static convert(M){return M instanceof V?M:M?new V(M):M}static fromLngLat(M,Bt=0){const Wt=360*Bt/40075017,Nt=Wt/Math.cos(Math.PI/180*M.lat);return new V(new et.N(M.lng-Nt,M.lat-Wt),new et.N(M.lng+Nt,M.lat+Wt))}adjustAntiMeridian(){const M=new et.N(this._sw.lng,this._sw.lat),Bt=new et.N(this._ne.lng,this._ne.lat);return new V(M,M.lng>Bt.lng?new et.N(Bt.lng+360,Bt.lat):Bt)}}class q{constructor(M,et,Bt){this.bounds=V.convert(this.validateBounds(M)),this.minzoom=et||0,this.maxzoom=Bt||24}validateBounds(M){return Array.isArray(M)&&4===M.length?[Math.max(-180,M[0]),Math.max(-90,M[1]),Math.min(180,M[2]),Math.min(90,M[3])]:[-180,-90,180,90]}contains(M){const Bt=Math.pow(2,M.z),Wt=Math.floor(et.O(this.bounds.getWest())*Bt),Nt=Math.floor(et.Q(this.bounds.getNorth())*Bt),$t=Math.ceil(et.O(this.bounds.getEast())*Bt),Gr=Math.ceil(et.Q(this.bounds.getSouth())*Bt);return M.x>=Wt&&M.x<$t&&M.y>=Nt&&M.y{this._options.tiles=M})),this}setUrl(M){return this.setSourceProperty((()=>{this.url=M,this._options.url=M})),this}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null)}serialize(){return et.e({},this._options)}loadTile(M){return et._(this,void 0,void 0,(function*(){const et=M.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),Bt={request:this.map._requestManager.transformRequest(et,"Tile"),uid:M.uid,tileID:M.tileID,zoom:M.tileID.overscaledZ,tileSize:this.tileSize*M.tileID.overscaleFactor(),type:this.type,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};Bt.request.collectResourceTiming=this._collectResourceTiming;let Wt="RT";if(M.actor&&"expired"!==M.state){if("loading"===M.state)return new Promise(((et,Bt)=>{M.reloadPromise={resolve:et,reject:Bt}}))}else M.actor=this.dispatcher.getActor(),Wt="LT";M.abortController=new AbortController;try{const et=yield M.actor.sendAsync({type:Wt,data:Bt},M.abortController);if(delete M.abortController,M.aborted)return;this._afterTileLoadWorkerResponse(M,et)}catch(et){if(delete M.abortController,M.aborted)return;if(et&&404!==et.status)throw et;this._afterTileLoadWorkerResponse(M,null)}}))}_afterTileLoadWorkerResponse(M,et){if(et&&et.resourceTiming&&(M.resourceTiming=et.resourceTiming),et&&this.map._refreshExpiredTiles&&M.setExpiryData(et),M.loadVectorData(et,this.map.painter),M.reloadPromise){const et=M.reloadPromise;M.reloadPromise=null,this.loadTile(M).then(et.resolve).catch(et.reject)}}abortTile(M){return et._(this,void 0,void 0,(function*(){M.abortController&&(M.abortController.abort(),delete M.abortController),M.actor&&(yield M.actor.sendAsync({type:"AT",data:{uid:M.uid,type:this.type,source:this.id}}))}))}unloadTile(M){return et._(this,void 0,void 0,(function*(){M.unloadVectorData(),M.actor&&(yield M.actor.sendAsync({type:"RMT",data:{uid:M.uid,type:this.type,source:this.id}}))}))}hasTransition(){return!1}}class W extends et.E{constructor(M,Bt,Wt,Nt){super(),this.id=M,this.dispatcher=Wt,this.setEventedParent(Nt),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=et.e({type:"raster"},Bt),et.e(this,et.M(Bt,["url","scheme","tileSize"]))}load(){return et._(this,arguments,void 0,(function*(M=!1){this._loaded=!1,this.fire(new et.k("dataloading",{dataType:"source"})),this._tileJSONRequest=new AbortController;try{const Bt=yield U(this._options,this.map._requestManager,this._tileJSONRequest);this._tileJSONRequest=null,this._loaded=!0,Bt&&(et.e(this,Bt),Bt.bounds&&(this.tileBounds=new q(Bt.bounds,this.minzoom,this.maxzoom)),this.fire(new et.k("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new et.k("data",{dataType:"source",sourceDataType:"content",sourceDataChanged:M})))}catch(M){this._tileJSONRequest=null,this.fire(new et.j(M))}}))}loaded(){return this._loaded}onAdd(M){this.map=M,this.load()}onRemove(){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null)}setSourceProperty(M){this._tileJSONRequest&&(this._tileJSONRequest.abort(),this._tileJSONRequest=null),M(),this.load(!0)}setTiles(M){return this.setSourceProperty((()=>{this._options.tiles=M})),this}setUrl(M){return this.setSourceProperty((()=>{this.url=M,this._options.url=M})),this}serialize(){return et.e({},this._options)}hasTile(M){return!this.tileBounds||this.tileBounds.contains(M.canonical)}loadTile(M){return et._(this,void 0,void 0,(function*(){const et=M.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme);M.abortController=new AbortController;try{const Bt=yield Io.getImage(this.map._requestManager.transformRequest(et,"Tile"),M.abortController,this.map._refreshExpiredTiles);if(delete M.abortController,M.aborted)return void(M.state="unloaded");if(Bt&&Bt.data){this.map._refreshExpiredTiles&&Bt.cacheControl&&Bt.expires&&M.setExpiryData({cacheControl:Bt.cacheControl,expires:Bt.expires});const et=this.map.painter.context,Wt=et.gl,Nt=Bt.data;M.texture=this.map.painter.getTileTexture(Nt.width),M.texture?M.texture.update(Nt,{useMipmap:!0}):(M.texture=new v(et,Nt,Wt.RGBA,{useMipmap:!0}),M.texture.bind(Wt.LINEAR,Wt.CLAMP_TO_EDGE,Wt.LINEAR_MIPMAP_NEAREST)),M.state="loaded"}}catch(et){if(delete M.abortController,M.aborted)M.state="unloaded";else if(et)throw M.state="errored",et}}))}abortTile(M){return et._(this,void 0,void 0,(function*(){M.abortController&&(M.abortController.abort(),delete M.abortController)}))}unloadTile(M){return et._(this,void 0,void 0,(function*(){M.texture&&this.map.painter.saveTileTexture(M.texture)}))}hasTransition(){return!1}}class X extends W{constructor(M,Bt,Wt,Nt){super(M,Bt,Wt,Nt),this.type="raster-dem",this.maxzoom=22,this._options=et.e({type:"raster-dem"},Bt),this.encoding=Bt.encoding||"mapbox",this.redFactor=Bt.redFactor,this.greenFactor=Bt.greenFactor,this.blueFactor=Bt.blueFactor,this.baseShift=Bt.baseShift}loadTile(M){return et._(this,void 0,void 0,(function*(){const Bt=M.tileID.canonical.url(this.tiles,this.map.getPixelRatio(),this.scheme),Wt=this.map._requestManager.transformRequest(Bt,"Tile");M.neighboringTiles=this._getNeighboringTiles(M.tileID),M.abortController=new AbortController;try{const Bt=yield Io.getImage(Wt,M.abortController,this.map._refreshExpiredTiles);if(delete M.abortController,M.aborted)return void(M.state="unloaded");if(Bt&&Bt.data){const Wt=Bt.data;this.map._refreshExpiredTiles&&Bt.cacheControl&&Bt.expires&&M.setExpiryData({cacheControl:Bt.cacheControl,expires:Bt.expires});const Nt=et.b(Wt)&&et.U()?Wt:yield this.readImageNow(Wt),$t={type:this.type,uid:M.uid,source:this.id,rawImageData:Nt,encoding:this.encoding,redFactor:this.redFactor,greenFactor:this.greenFactor,blueFactor:this.blueFactor,baseShift:this.baseShift};if(!M.actor||"expired"===M.state){M.actor=this.dispatcher.getActor();const et=yield M.actor.sendAsync({type:"LDT",data:$t});M.dem=et,M.needsHillshadePrepare=!0,M.needsTerrainPrepare=!0,M.state="loaded"}}}catch(et){if(delete M.abortController,M.aborted)M.state="unloaded";else if(et)throw M.state="errored",et}}))}readImageNow(M){return et._(this,void 0,void 0,(function*(){if("undefined"!=typeof VideoFrame&&et.V()){const Bt=M.width+2,Wt=M.height+2;try{return new et.R({width:Bt,height:Wt},yield et.W(M,-1,-1,Bt,Wt))}catch(M){}}return $t.getImageData(M,1)}))}_getNeighboringTiles(M){const Bt=M.canonical,Wt=Math.pow(2,Bt.z),Nt=(Bt.x-1+Wt)%Wt,$t=0===Bt.x?M.wrap-1:M.wrap,Gr=(Bt.x+1+Wt)%Wt,mn=Bt.x+1===Wt?M.wrap+1:M.wrap,Hn={};return Hn[new et.S(M.overscaledZ,$t,Bt.z,Nt,Bt.y).key]={backfilled:!1},Hn[new et.S(M.overscaledZ,mn,Bt.z,Gr,Bt.y).key]={backfilled:!1},Bt.y>0&&(Hn[new et.S(M.overscaledZ,$t,Bt.z,Nt,Bt.y-1).key]={backfilled:!1},Hn[new et.S(M.overscaledZ,M.wrap,Bt.z,Bt.x,Bt.y-1).key]={backfilled:!1},Hn[new et.S(M.overscaledZ,mn,Bt.z,Gr,Bt.y-1).key]={backfilled:!1}),Bt.y+10&&et.e(Nt,{resourceTiming:Wt}),this.fire(new et.k("data",Object.assign(Object.assign({},Nt),{sourceDataType:"metadata"}))),this.fire(new et.k("data",Object.assign(Object.assign({},Nt),{sourceDataType:"content"})))}catch(M){if(this._pendingLoads--,this._removed)return void this.fire(new et.k("dataabort",{dataType:"source"}));this.fire(new et.j(M))}}))}loaded(){return 0===this._pendingLoads}loadTile(M){return et._(this,void 0,void 0,(function*(){const et=M.actor?"RT":"LT";M.actor=this.actor;const Bt={type:this.type,uid:M.uid,tileID:M.tileID,zoom:M.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:this.map.getPixelRatio(),showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,subdivisionGranularity:this.map.style.projection.subdivisionGranularity};M.abortController=new AbortController;const Wt=yield this.actor.sendAsync({type:et,data:Bt},M.abortController);delete M.abortController,M.unloadVectorData(),M.aborted||M.loadVectorData(Wt,this.map.painter,"RT"===et)}))}abortTile(M){return et._(this,void 0,void 0,(function*(){M.abortController&&(M.abortController.abort(),delete M.abortController),M.aborted=!0}))}unloadTile(M){return et._(this,void 0,void 0,(function*(){M.unloadVectorData(),yield this.actor.sendAsync({type:"RMT",data:{uid:M.uid,type:this.type,source:this.id}})}))}onRemove(){this._removed=!0,this.actor.sendAsync({type:"RS",data:{type:this.type,source:this.id}})}serialize(){return et.e({},this._options,{type:this.type,data:this._data})}hasTransition(){return!1}}class K extends et.E{constructor(M,et,Bt,Wt){super(),this.flippedWindingOrder=!1,this.id=M,this.dispatcher=Bt,this.coordinates=et.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(Wt),this.options=et}load(M){return et._(this,void 0,void 0,(function*(){this._loaded=!1,this.fire(new et.k("dataloading",{dataType:"source"})),this.url=this.options.url,this._request=new AbortController;try{const et=yield Io.getImage(this.map._requestManager.transformRequest(this.url,"Image"),this._request);this._request=null,this._loaded=!0,et&&et.data&&(this.image=et.data,M&&(this.coordinates=M),this._finishLoading())}catch(M){this._request=null,this._loaded=!0,this.fire(new et.j(M))}}))}loaded(){return this._loaded}updateImage(M){return M.url?(this._request&&(this._request.abort(),this._request=null),this.options.url=M.url,this.load(M.coordinates).finally((()=>{this.texture=null})),this):this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new et.k("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(M){this.map=M,this.load()}onRemove(){this._request&&(this._request.abort(),this._request=null)}setCoordinates(M){this.coordinates=M;const Bt=M.map(et.Y.fromLngLat);var Wt;return this.tileID=function(M){let Bt=1/0,Wt=1/0,Nt=-1/0,$t=-1/0;for(const et of M)Bt=Math.min(Bt,et.x),Wt=Math.min(Wt,et.y),Nt=Math.max(Nt,et.x),$t=Math.max($t,et.y);const Gr=Math.max(Nt-Bt,$t-Wt),mn=Math.max(0,Math.floor(-Math.log(Gr)/Math.LN2)),Hn=Math.pow(2,mn);return new et.Z(mn,Math.floor((Bt+Nt)/2*Hn),Math.floor((Wt+$t)/2*Hn))}(Bt),this.minzoom=this.maxzoom=this.tileID.z,this.tileCoords=Bt.map((M=>this.tileID.getTilePoint(M)._round())),this.flippedWindingOrder=((Wt=this.tileCoords)[1].x-Wt[0].x)*(Wt[2].y-Wt[0].y)-(Wt[1].y-Wt[0].y)*(Wt[2].x-Wt[0].x)<0,this.fire(new et.k("data",{dataType:"source",sourceDataType:"content"})),this}prepare(){if(0===Object.keys(this.tiles).length||!this.image)return;const M=this.map.painter.context,Bt=M.gl;this.texture||(this.texture=new v(M,this.image,Bt.RGBA),this.texture.bind(Bt.LINEAR,Bt.CLAMP_TO_EDGE));let Wt=!1;for(const M in this.tiles){const et=this.tiles[M];"loaded"!==et.state&&(et.state="loaded",et.texture=this.texture,Wt=!0)}Wt&&this.fire(new et.k("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}loadTile(M){return et._(this,void 0,void 0,(function*(){this.tileID&&this.tileID.equals(M.tileID.canonical)?(this.tiles[String(M.tileID.wrap)]=M,M.buckets={}):M.state="errored"}))}serialize(){return{type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return!1}}class Y extends K{constructor(M,et,Bt,Wt){super(M,et,Bt,Wt),this.roundZoom=!0,this.type="video",this.options=et}load(){return et._(this,void 0,void 0,(function*(){this._loaded=!1;const M=this.options;this.urls=[];for(const et of M.urls)this.urls.push(this.map._requestManager.transformRequest(et,"Source").url);try{const M=yield et.a0(this.urls);if(this._loaded=!0,!M)return;this.video=M,this.video.loop=!0,this.video.addEventListener("playing",(()=>{this.map.triggerRepaint()})),this.map&&this.video.play(),this._finishLoading()}catch(M){this.fire(new et.j(M))}}))}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(M){if(this.video){const Bt=this.video.seekable;MBt.end(0)?this.fire(new et.j(new et.$(`sources.${this.id}`,null,`Playback for this video can be set only between the ${Bt.start(0)} and ${Bt.end(0)}-second mark.`))):this.video.currentTime=M}}getVideo(){return this.video}onAdd(M){this.map||(this.map=M,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)))}prepare(){if(0===Object.keys(this.tiles).length||this.video.readyState<2)return;const M=this.map.painter.context,Bt=M.gl;this.texture?this.video.paused||(this.texture.bind(Bt.LINEAR,Bt.CLAMP_TO_EDGE),Bt.texSubImage2D(Bt.TEXTURE_2D,0,0,0,Bt.RGBA,Bt.UNSIGNED_BYTE,this.video)):(this.texture=new v(M,this.video,Bt.RGBA),this.texture.bind(Bt.LINEAR,Bt.CLAMP_TO_EDGE));let Wt=!1;for(const M in this.tiles){const et=this.tiles[M];"loaded"!==et.state&&(et.state="loaded",et.texture=this.texture,Wt=!0)}Wt&&this.fire(new et.k("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}serialize(){return{type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}}class J extends K{constructor(M,Bt,Wt,Nt){super(M,Bt,Wt,Nt),Bt.coordinates?Array.isArray(Bt.coordinates)&&4===Bt.coordinates.length&&!Bt.coordinates.some((M=>!Array.isArray(M)||2!==M.length||M.some((M=>"number"!=typeof M))))||this.fire(new et.j(new et.$(`sources.${M}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new et.j(new et.$(`sources.${M}`,null,'missing required property "coordinates"'))),Bt.animate&&"boolean"!=typeof Bt.animate&&this.fire(new et.j(new et.$(`sources.${M}`,null,'optional "animate" property must be a boolean value'))),Bt.canvas?"string"==typeof Bt.canvas||Bt.canvas instanceof HTMLCanvasElement||this.fire(new et.j(new et.$(`sources.${M}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new et.j(new et.$(`sources.${M}`,null,'missing required property "canvas"'))),this.options=Bt,this.animate=void 0===Bt.animate||Bt.animate}load(){return et._(this,void 0,void 0,(function*(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new et.j(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint()},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1)},this._finishLoading())}))}getCanvas(){return this.canvas}onAdd(M){this.map=M,this.load(),this.canvas&&this.animate&&this.play()}onRemove(){this.pause()}prepare(){let M=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,M=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,M=!0),this._hasInvalidDimensions())return;if(0===Object.keys(this.tiles).length)return;const Bt=this.map.painter.context,Wt=Bt.gl;this.texture?(M||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new v(Bt,this.canvas,Wt.RGBA,{premultiply:!0});let Nt=!1;for(const M in this.tiles){const et=this.tiles[M];"loaded"!==et.state&&(et.state="loaded",et.texture=this.texture,Nt=!0)}Nt&&this.fire(new et.k("data",{dataType:"source",sourceDataType:"idle",sourceId:this.id}))}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const M of[this.canvas.width,this.canvas.height])if(isNaN(M)||M<=0)return!0;return!1}}const za={},ee=M=>{switch(M){case"geojson":return $;case"image":return K;case"raster":return W;case"raster-dem":return X;case"vector":return H;case"video":return Y;case"canvas":return J}return za[M]},Fa="RTLPluginLoaded";class ie extends et.E{constructor(){super(...arguments),this.status="unavailable",this.url=null,this.dispatcher=j()}_syncState(M){return this.status=M,this.dispatcher.broadcast("SRPS",{pluginStatus:M,pluginURL:this.url}).catch((M=>{throw this.status="error",M}))}getRTLTextPluginStatus(){return this.status}clearRTLTextPlugin(){this.status="unavailable",this.url=null}setRTLTextPlugin(M){return et._(this,arguments,void 0,(function*(M,et=!1){if(this.url)throw new Error("setRTLTextPlugin cannot be called multiple times.");if(this.url=$t.resolveURL(M),!this.url)throw new Error(`requested url ${M} is invalid`);if("unavailable"===this.status){if(!et)return this._requestImport();this.status="deferred",this._syncState(this.status)}else if("requested"===this.status)return this._requestImport()}))}_requestImport(){return et._(this,void 0,void 0,(function*(){yield this._syncState("loading"),this.status="loaded",this.fire(new et.k(Fa))}))}lazyLoad(){"unavailable"===this.status?this.status="requested":"deferred"===this.status&&this._requestImport()}}let Ea=null;function oe(){return Ea||(Ea=new ie),Ea}class se{constructor(M,Bt){this.timeAdded=0,this.fadeEndTime=0,this.tileID=M,this.uid=et.a1(),this.uses=0,this.tileSize=Bt,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasRTLText=!1,this.dependencies={},this.rtt=[],this.rttCoords={},this.expiredRequestCount=0,this.state="loading"}registerFadeDuration(M){const et=M+this.timeAdded;etet.getLayer(M))).filter(Boolean);if(0!==M.length){Wt.layers=M,Wt.stateDependentLayerIds&&(Wt.stateDependentLayers=Wt.stateDependentLayerIds.map((et=>M.filter((M=>M.id===et))[0])));for(const et of M)Bt[et.id]=Wt}}return Bt}(M.buckets,null==Bt?void 0:Bt.style),this.hasSymbolBuckets=!1;for(const M in this.buckets){const Bt=this.buckets[M];if(Bt instanceof et.a3){if(this.hasSymbolBuckets=!0,!Wt)break;Bt.justReloaded=!0}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const M in this.buckets){const Bt=this.buckets[M];if(Bt instanceof et.a3&&Bt.hasRTLText){this.hasRTLText=!0,oe().lazyLoad();break}}this.queryPadding=0;for(const M in this.buckets){const et=this.buckets[M];this.queryPadding=Math.max(this.queryPadding,Bt.style.getLayer(M).queryRadius(et))}M.imageAtlas&&(this.imageAtlas=M.imageAtlas),M.glyphAtlasImage&&(this.glyphAtlasImage=M.glyphAtlasImage)}else this.collisionBoxArray=new et.a2}unloadVectorData(){for(const M in this.buckets)this.buckets[M].destroy();this.buckets={},this.imageAtlasTexture&&this.imageAtlasTexture.destroy(),this.imageAtlas&&(this.imageAtlas=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.latestFeatureIndex=null,this.state="unloaded"}getBucket(M){return this.buckets[M.id]}upload(M){for(const et in this.buckets){const Bt=this.buckets[et];Bt.uploadPending()&&Bt.upload(M)}const et=M.gl;this.imageAtlas&&!this.imageAtlas.uploaded&&(this.imageAtlasTexture=new v(M,this.imageAtlas.image,et.RGBA),this.imageAtlas.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new v(M,this.glyphAtlasImage,et.ALPHA),this.glyphAtlasImage=null)}prepare(M){this.imageAtlas&&this.imageAtlas.patchUpdatedImages(M,this.imageAtlasTexture)}queryRenderedFeatures(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so){return this.latestFeatureIndex&&this.latestFeatureIndex.rawTileData?this.latestFeatureIndex.query({queryGeometry:Wt,cameraQueryGeometry:Nt,scale:$t,tileSize:this.tileSize,pixelPosMatrix:so,transform:mn,params:Gr,queryPadding:this.queryPadding*Hn},M,et,Bt):{}}querySourceFeatures(M,Bt){const Wt=this.latestFeatureIndex;if(!Wt||!Wt.rawTileData)return;const Nt=Wt.loadVTLayers(),$t=Bt&&Bt.sourceLayer?Bt.sourceLayer:"",Gr=Nt._geojsonTileLayer||Nt[$t];if(!Gr)return;const mn=et.a4(Bt&&Bt.filter),{z:Hn,x:so,y:uo}=this.tileID.canonical,Io={z:Hn,x:so,y:uo};for(let Bt=0;BtM)et=!1;else if(Bt)if(this.expirationTime{this.remove(M,Nt)}),Bt)),this.data[Wt].push(Nt),this.order.push(Wt),this.order.length>this.max){const M=this._getAndRemoveByKey(this.order[0]);M&&this.onRemove(M)}return this}has(M){return M.wrapped().key in this.data}getAndRemove(M){return this.has(M)?this._getAndRemoveByKey(M.wrapped().key):null}_getAndRemoveByKey(M){const et=this.data[M].shift();return et.timeout&&clearTimeout(et.timeout),0===this.data[M].length&&delete this.data[M],this.order.splice(this.order.indexOf(M),1),et.value}getByKey(M){const et=this.data[M];return et?et[0].value:null}get(M){return this.has(M)?this.data[M.wrapped().key][0].value:null}remove(M,et){if(!this.has(M))return this;const Bt=M.wrapped().key,Wt=void 0===et?0:this.data[Bt].indexOf(et),Nt=this.data[Bt][Wt];return this.data[Bt].splice(Wt,1),Nt.timeout&&clearTimeout(Nt.timeout),0===this.data[Bt].length&&delete this.data[Bt],this.onRemove(Nt.value),this.order.splice(this.order.indexOf(Bt),1),this}setMaxSize(M){for(this.max=M;this.order.length>this.max;){const M=this._getAndRemoveByKey(this.order[0]);M&&this.onRemove(M)}return this}filter(M){const et=[];for(const Bt in this.data)for(const Wt of this.data[Bt])M(Wt.value)||et.push(Wt);for(const M of et)this.remove(M.value.tileID,M)}}class ne{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(M,Bt,Wt){const Nt=String(Bt);if(this.stateChanges[M]=this.stateChanges[M]||{},this.stateChanges[M][Nt]=this.stateChanges[M][Nt]||{},et.e(this.stateChanges[M][Nt],Wt),null===this.deletedStates[M]){this.deletedStates[M]={};for(const et in this.state[M])et!==Nt&&(this.deletedStates[M][et]=null)}else if(this.deletedStates[M]&&null===this.deletedStates[M][Nt]){this.deletedStates[M][Nt]={};for(const et in this.state[M][Nt])Wt[et]||(this.deletedStates[M][Nt][et]=null)}else for(const et in Wt)this.deletedStates[M]&&this.deletedStates[M][Nt]&&null===this.deletedStates[M][Nt][et]&&delete this.deletedStates[M][Nt][et]}removeFeatureState(M,et,Bt){if(null===this.deletedStates[M])return;const Wt=String(et);if(this.deletedStates[M]=this.deletedStates[M]||{},Bt&&void 0!==et)null!==this.deletedStates[M][Wt]&&(this.deletedStates[M][Wt]=this.deletedStates[M][Wt]||{},this.deletedStates[M][Wt][Bt]=null);else if(void 0!==et)if(this.stateChanges[M]&&this.stateChanges[M][Wt])for(Bt in this.deletedStates[M][Wt]={},this.stateChanges[M][Wt])this.deletedStates[M][Wt][Bt]=null;else this.deletedStates[M][Wt]=null;else this.deletedStates[M]=null}getState(M,Bt){const Wt=String(Bt),Nt=et.e({},(this.state[M]||{})[Wt],(this.stateChanges[M]||{})[Wt]);if(null===this.deletedStates[M])return{};if(this.deletedStates[M]){const et=this.deletedStates[M][Bt];if(null===et)return{};for(const M in et)delete Nt[M]}return Nt}initializeTileState(M,et){M.setFeatureState(this.state,et)}coalesceChanges(M,Bt){const Wt={};for(const M in this.stateChanges){this.state[M]=this.state[M]||{};const Bt={};for(const Wt in this.stateChanges[M])this.state[M][Wt]||(this.state[M][Wt]={}),et.e(this.state[M][Wt],this.stateChanges[M][Wt]),Bt[Wt]=this.state[M][Wt];Wt[M]=Bt}for(const M in this.deletedStates){this.state[M]=this.state[M]||{};const Bt={};if(null===this.deletedStates[M])for(const et in this.state[M])Bt[et]={},this.state[M][et]={};else for(const et in this.deletedStates[M]){if(null===this.deletedStates[M][et])this.state[M][et]={};else for(const Bt of Object.keys(this.deletedStates[M][et]))delete this.state[M][et][Bt];Bt[et]=this.state[M][et]}Wt[M]=Wt[M]||{},et.e(Wt[M],Bt)}if(this.stateChanges={},this.deletedStates={},0!==Object.keys(Wt).length)for(const et in M)M[et].setFeatureState(Wt,Bt)}}function le(M,et,Bt){const Wt=et.intersectsFrustum(M);if(!Bt)return Wt;const Nt=et.intersectsPlane(Bt);return 0===Wt||0===Nt?0:2===Wt&&2===Nt?2:1}function ce(M,Bt,Wt,Nt,$t){let Gr=M;const mn=Math.atan(Bt/Wt),Hn=Math.hypot(Bt,Wt);return Gr=M+et.a8(Nt/Hn/Math.max(.5,Math.cos(et.aa($t/2)))),Gr+=1*et.a8(Math.cos(mn))/2,Gr+=et.ab(M-Gr,-0,0),Gr}function he(M,Bt){const Wt=(Bt.roundZoom?Math.round:Math.floor)(M.zoom+et.a8(M.tileSize/Bt.tileSize));return Math.max(0,Wt)}function ue(M,Bt){const Wt=M.getCameraFrustum(),Nt=M.getClippingPlane(),$t=M.screenPointToMercatorCoordinate(M.getCameraPoint()),Gr=et.Y.fromLngLat(M.center,M.elevation);$t.z=Gr.z+Math.cos(M.pitchInRadians)*M.cameraToCenterDistance/M.worldSize;const mn=M.getCoveringTilesDetailsProvider(),Hn=mn.allowVariableZoom(M,Bt),so=he(M,Bt),uo=Bt.minzoom||0,Io=void 0!==Bt.maxzoom?Bt.maxzoom:M.maxZoom,Po=Math.min(Math.max(0,so),Io),To=Math.pow(2,Po),Eo=[To*$t.x,To*$t.y,0],Ia=[To*Gr.x,To*Gr.y,0],Ba=Math.hypot(Gr.x-$t.x,Gr.y-$t.y),Ta=Math.abs(Gr.z-$t.z),Va=Math.hypot(Ba,Ta),x=M=>({zoom:0,x:0,y:0,wrap:M,fullyVisible:!1}),za=[],Fa=[];if(M.renderWorldCopies&&mn.allowWorldCopies())for(let M=1;M<=3;M++)za.push(x(-M)),za.push(x(M));for(za.push(x(0));za.length>0;){const To=za.pop(),Ba=To.x,Ea=To.y;let La=To.fullyVisible;const Da={x:Ba,y:Ea,z:To.zoom},Ka=mn.getTileAABB(Da,To.wrap,M.elevation,Bt);if(!La){const M=le(Wt,Ka,Nt);if(0===M)continue;La=2===M}const Oa=mn.distanceToTile2d($t.x,$t.y,Da,Ka);let $a=so;Hn&&($a=(Bt.calculateTileZoom||ce)(M.zoom+et.a8(M.tileSize/Bt.tileSize),Oa,Ta,Va,M.fov)),$a=(Bt.roundZoom?Math.round:Math.floor)($a),$a=Math.max(0,$a);const Al=Math.min($a,Io);if(To.wrap=mn.getWrap(Gr,Da,To.wrap),To.zoom>=Al){if(To.zoom>1),wrap:To.wrap,fullyVisible:La})}return Fa.sort(((M,et)=>M.distanceSq-et.distanceSq)).map((M=>M.tileID))}class de extends et.E{constructor(M,et,Bt){super(),this.id=M,this.dispatcher=Bt,this.on("data",(M=>this._dataHandler(M))),this.on("dataloading",(()=>{this._sourceErrored=!1})),this.on("error",(()=>{this._sourceErrored=this._source.loaded()})),this._source=((M,et,Bt,Wt)=>{const Nt=new(ee(et.type))(M,et,Bt,Wt);if(Nt.id!==M)throw new Error(`Expected Source id to be ${M} instead of ${Nt.id}`);return Nt})(M,et,Bt,this),this._tiles={},this._cache=new ae(0,(M=>this._unloadTile(M))),this._timers={},this._cacheTimers={},this._maxTileCacheSize=null,this._maxTileCacheZoomLevels=null,this._loadedParentTiles={},this._coveredTiles={},this._state=new ne,this._didEmitContent=!1,this._updated=!1}onAdd(M){this.map=M,this._maxTileCacheSize=M?M._maxTileCacheSize:null,this._maxTileCacheZoomLevels=M?M._maxTileCacheZoomLevels:null,this._source&&this._source.onAdd&&this._source.onAdd(M)}onRemove(M){this.clearTiles(),this._source&&this._source.onRemove&&this._source.onRemove(M)}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded)return!1;if(!this._source.loaded())return!1;if(!(void 0===this.used&&void 0===this.usedForTerrain||this.used||this.usedForTerrain))return!0;if(!this._updated)return!1;for(const M in this._tiles){const et=this._tiles[M];if("loaded"!==et.state&&"errored"!==et.state)return!1}return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const M=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,M&&this.reload(),this.transform&&this.update(this.transform,this.terrain)}_loadTile(M,Bt,Wt){return et._(this,void 0,void 0,(function*(){try{yield this._source.loadTile(M),this._tileLoaded(M,Bt,Wt)}catch(Bt){M.state="errored",404!==Bt.status?this._source.fire(new et.j(Bt,{tile:M})):this.update(this.transform,this.terrain)}}))}_unloadTile(M){this._source.unloadTile&&this._source.unloadTile(M)}_abortTile(M){this._source.abortTile&&this._source.abortTile(M),this._source.fire(new et.k("dataabort",{tile:M,coord:M.tileID,dataType:"source"}))}serialize(){return this._source.serialize()}prepare(M){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const et in this._tiles){const Bt=this._tiles[et];Bt.upload(M),Bt.prepare(this.map.style.imageManager)}}getIds(){return Object.values(this._tiles).map((M=>M.tileID)).sort(_e).map((M=>M.key))}getRenderableIds(M){const Bt=[];for(const et in this._tiles)this._isIdRenderable(et,M)&&Bt.push(this._tiles[et]);return M?Bt.sort(((M,Bt)=>{const Wt=M.tileID,Nt=Bt.tileID,$t=new et.P(Wt.canonical.x,Wt.canonical.y)._rotate(-this.transform.bearingInRadians),Gr=new et.P(Nt.canonical.x,Nt.canonical.y)._rotate(-this.transform.bearingInRadians);return Wt.overscaledZ-Nt.overscaledZ||Gr.y-$t.y||Gr.x-$t.x})).map((M=>M.tileID.key)):Bt.map((M=>M.tileID)).sort(_e).map((M=>M.key))}hasRenderableParent(M){const et=this.findLoadedParent(M,0);return!!et&&this._isIdRenderable(et.tileID.key)}_isIdRenderable(M,et){return this._tiles[M]&&this._tiles[M].hasData()&&!this._coveredTiles[M]&&(et||!this._tiles[M].holdingForFade())}reload(M){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const et in this._tiles)(M||"errored"!==this._tiles[et].state)&&this._reloadTile(et,"reloading")}}_reloadTile(M,Bt){return et._(this,void 0,void 0,(function*(){const et=this._tiles[M];et&&("loading"!==et.state&&(et.state=Bt),yield this._loadTile(et,M,Bt))}))}_tileLoaded(M,Bt,Wt){M.timeAdded=$t.now(),"expired"===Wt&&(M.refreshedUponExpiration=!0),this._setTileReloadTimer(Bt,M),"raster-dem"===this.getSource().type&&M.dem&&this._backfillDEM(M),this._state.initializeTileState(M,this.map?this.map.painter:null),M.aborted||this._source.fire(new et.k("data",{dataType:"source",tile:M,coord:M.tileID}))}_backfillDEM(M){const et=this.getRenderableIds();for(let Bt=0;Bt1||(Math.abs(Bt)>1&&(1===Math.abs(Bt+Nt)?Bt+=Nt:1===Math.abs(Bt-Nt)&&(Bt-=Nt)),et.dem&&M.dem&&(M.dem.backfillBorder(et.dem,Bt,Wt),M.neighboringTiles&&M.neighboringTiles[$t]&&(M.neighboringTiles[$t].backfilled=!0)))}}getTile(M){return this.getTileByID(M.key)}getTileByID(M){return this._tiles[M]}_retainLoadedChildren(M,et,Bt,Wt){for(const Nt in this._tiles){let $t=this._tiles[Nt];if(Wt[Nt]||!$t.hasData()||$t.tileID.overscaledZ<=et||$t.tileID.overscaledZ>Bt)continue;let Gr=$t.tileID;for(;$t&&$t.tileID.overscaledZ>et+1;){const M=$t.tileID.scaledTo($t.tileID.overscaledZ-1);$t=this._tiles[M.key],$t&&$t.hasData()&&(Gr=M)}let mn=Gr;for(;mn.overscaledZ>et;)if(mn=mn.scaledTo(mn.overscaledZ-1),M[mn.key]||M[mn.canonical.key]){Wt[Gr.key]=Gr;break}}}findLoadedParent(M,et){if(M.key in this._loadedParentTiles){const Bt=this._loadedParentTiles[M.key];return Bt&&Bt.tileID.overscaledZ>=et?Bt:null}for(let Bt=M.overscaledZ-1;Bt>=et;Bt--){const et=M.scaledTo(Bt),Wt=this._getLoadedTile(et);if(Wt)return Wt}}findLoadedSibling(M){return this._getLoadedTile(M)}_getLoadedTile(M){const et=this._tiles[M.key];return et&&et.hasData()?et:this._cache.getByKey(M.wrapped().key)}updateCacheSize(M){const Bt=Math.ceil(M.width/this._source.tileSize)+1,Wt=Math.ceil(M.height/this._source.tileSize)+1,Nt=Math.floor(Bt*Wt*(null===this._maxTileCacheZoomLevels?et.a.MAX_TILE_CACHE_ZOOM_LEVELS:this._maxTileCacheZoomLevels)),$t="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,Nt):Nt;this._cache.setMaxSize($t)}handleWrapJump(M){const et=Math.round((M-(void 0===this._prevLng?M:this._prevLng))/360);if(this._prevLng=M,et){const M={};for(const Bt in this._tiles){const Wt=this._tiles[Bt];Wt.tileID=Wt.tileID.unwrapTo(Wt.tileID.wrap+et),M[Wt.tileID.key]=Wt}this._tiles=M;for(const M in this._timers)clearTimeout(this._timers[M]),delete this._timers[M];for(const M in this._tiles)this._setTileReloadTimer(M,this._tiles[M])}}_updateCoveredAndRetainedTiles(M,et,Bt,Wt,Nt,Gr){const mn={},Hn={},so=Object.keys(M),uo=$t.now();for(const Bt of so){const Wt=M[Bt],Nt=this._tiles[Bt];if(!Nt||0!==Nt.fadeEndTime&&Nt.fadeEndTime<=uo)continue;const $t=this.findLoadedParent(Wt,et),Gr=this.findLoadedSibling(Wt),so=$t||Gr||null;so&&(this._addTile(so.tileID),mn[so.tileID.key]=so.tileID),Hn[Bt]=Wt}this._retainLoadedChildren(Hn,Wt,Bt,M);for(const et in mn)M[et]||(this._coveredTiles[et]=!0,M[et]=mn[et]);if(Gr){const et={},Bt={};for(const M of Nt)this._tiles[M.key].hasData()?et[M.key]=M:Bt[M.key]=M;for(const Wt in Bt){const Nt=Bt[Wt].children(this._source.maxzoom);this._tiles[Nt[0].key]&&this._tiles[Nt[1].key]&&this._tiles[Nt[2].key]&&this._tiles[Nt[3].key]&&(et[Nt[0].key]=M[Nt[0].key]=Nt[0],et[Nt[1].key]=M[Nt[1].key]=Nt[1],et[Nt[2].key]=M[Nt[2].key]=Nt[2],et[Nt[3].key]=M[Nt[3].key]=Nt[3],delete Bt[Wt])}for(const Wt in Bt){const Nt=Bt[Wt],$t=this.findLoadedParent(Nt,this._source.minzoom),Gr=this.findLoadedSibling(Nt),mn=$t||Gr||null;if(mn){et[mn.tileID.key]=M[mn.tileID.key]=mn.tileID;for(const M in et)et[M].isChildOf(mn.tileID)&&delete et[M]}}for(const M in this._tiles)et[M]||(this._coveredTiles[M]=!0)}}update(M,Bt){if(!this._sourceLoaded||this._paused)return;let Wt;this.transform=M,this.terrain=Bt,this.updateCacheSize(M),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used||this.usedForTerrain?this._source.tileID?Wt=M.getVisibleUnwrappedCoordinates(this._source.tileID).map((M=>new et.S(M.canonical.z,M.wrap,M.canonical.z,M.canonical.x,M.canonical.y))):(Wt=ue(M,{tileSize:this.usedForTerrain?this.tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:!this.usedForTerrain&&this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled,terrain:Bt,calculateTileZoom:this._source.calculateTileZoom}),this._source.hasTile&&(Wt=Wt.filter((M=>this._source.hasTile(M))))):Wt=[];const Nt=he(M,this._source),$t=Math.max(Nt-de.maxOverzooming,this._source.minzoom),Gr=Math.max(Nt+de.maxUnderzooming,this._source.minzoom);if(this.usedForTerrain){const M={};for(const et of Wt)if(et.canonical.z>this._source.minzoom){const Bt=et.scaledTo(et.canonical.z-1);M[Bt.key]=Bt;const Wt=et.scaledTo(Math.max(this._source.minzoom,Math.min(et.canonical.z,5)));M[Wt.key]=Wt}Wt=Wt.concat(Object.values(M))}const mn=0===Wt.length&&!this._updated&&this._didEmitContent;this._updated=!0,mn&&this.fire(new et.k("data",{sourceDataType:"idle",dataType:"source",sourceId:this.id}));const Hn=this._updateRetainedTiles(Wt,Nt);pe(this._source.type)&&this._updateCoveredAndRetainedTiles(Hn,$t,Gr,Nt,Wt,Bt);for(const M in Hn)this._tiles[M].clearFadeHold();const so=et.ac(this._tiles,Hn);for(const M of so){const et=this._tiles[M];et.hasSymbolBuckets&&!et.holdingForFade()?et.setHoldDuration(this.map._fadeDuration):et.hasSymbolBuckets&&!et.symbolFadeFinished()||this._removeTile(M)}this._updateLoadedParentTileCache(),this._updateLoadedSiblingTileCache()}releaseSymbolFadeTiles(){for(const M in this._tiles)this._tiles[M].holdingForFade()&&this._removeTile(M)}_updateRetainedTiles(M,et){var Bt;const Wt={},Nt={},$t=Math.max(et-de.maxOverzooming,this._source.minzoom),Gr=Math.max(et+de.maxUnderzooming,this._source.minzoom),mn={};for(const Bt of M){const M=this._addTile(Bt);Wt[Bt.key]=Bt,M.hasData()||etthis._source.maxzoom){const M=Gr.children(this._source.maxzoom)[0],et=this.getTile(M);if(et&&et.hasData()){Wt[M.key]=M;continue}}else{const M=Gr.children(this._source.maxzoom);if(Wt[M[0].key]&&Wt[M[1].key]&&Wt[M[2].key]&&Wt[M[3].key])continue}let mn=M.wasRequested();for(let et=Gr.overscaledZ-1;et>=$t;--et){const $t=Gr.scaledTo(et);if(Nt[$t.key])break;if(Nt[$t.key]=!0,M=this.getTile($t),!M&&mn&&(M=this._addTile($t)),M){const et=M.hasData();if((et||!(null===(Bt=this.map)||void 0===Bt?void 0:Bt.cancelPendingTileRequestsWhileZooming)||mn)&&(Wt[$t.key]=$t),mn=M.wasRequested(),et)break}}}return Wt}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const M in this._tiles){const et=[];let Bt,Wt=this._tiles[M].tileID;for(;Wt.overscaledZ>0;){if(Wt.key in this._loadedParentTiles){Bt=this._loadedParentTiles[Wt.key];break}et.push(Wt.key);const M=Wt.scaledTo(Wt.overscaledZ-1);if(Bt=this._getLoadedTile(M),Bt)break;Wt=M}for(const M of et)this._loadedParentTiles[M]=Bt}}_updateLoadedSiblingTileCache(){this._loadedSiblingTiles={};for(const M in this._tiles){const et=this._tiles[M].tileID,Bt=this._getLoadedTile(et);this._loadedSiblingTiles[et.key]=Bt}}_addTile(M){let Bt=this._tiles[M.key];if(Bt)return Bt;Bt=this._cache.getAndRemove(M),Bt&&(this._setTileReloadTimer(M.key,Bt),Bt.tileID=M,this._state.initializeTileState(Bt,this.map?this.map.painter:null),this._cacheTimers[M.key]&&(clearTimeout(this._cacheTimers[M.key]),delete this._cacheTimers[M.key],this._setTileReloadTimer(M.key,Bt)));const Wt=Bt;return Bt||(Bt=new se(M,this._source.tileSize*M.overscaleFactor()),this._loadTile(Bt,M.key,Bt.state)),Bt.uses++,this._tiles[M.key]=Bt,Wt||this._source.fire(new et.k("dataloading",{tile:Bt,coord:Bt.tileID,dataType:"source"})),Bt}_setTileReloadTimer(M,et){M in this._timers&&(clearTimeout(this._timers[M]),delete this._timers[M]);const Bt=et.getExpiryTimeout();Bt&&(this._timers[M]=setTimeout((()=>{this._reloadTile(M,"expired"),delete this._timers[M]}),Bt))}_removeTile(M){const et=this._tiles[M];et&&(et.uses--,delete this._tiles[M],this._timers[M]&&(clearTimeout(this._timers[M]),delete this._timers[M]),et.uses>0||(et.hasData()&&"reloading"!==et.state?this._cache.add(et.tileID,et,et.getExpiryTimeout()):(et.aborted=!0,this._abortTile(et),this._unloadTile(et))))}_dataHandler(M){const et=M.sourceDataType;"source"===M.dataType&&"metadata"===et&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&"source"===M.dataType&&"content"===et&&(this.reload(M.sourceDataChanged),this.transform&&this.update(this.transform,this.terrain),this._didEmitContent=!0)}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const M in this._tiles)this._removeTile(M);this._cache.reset()}tilesIn(M,Bt,Wt){const Nt=[],$t=this.transform;if(!$t)return Nt;const Gr=Wt?$t.getCameraQueryGeometry(M):M,mn=M.map((M=>$t.screenPointToMercatorCoordinate(M,this.terrain))),Hn=Gr.map((M=>$t.screenPointToMercatorCoordinate(M,this.terrain))),so=this.getIds();let uo=1/0,Io=1/0,Po=-1/0,To=-1/0;for(const M of Hn)uo=Math.min(uo,M.x),Io=Math.min(Io,M.y),Po=Math.max(Po,M.x),To=Math.max(To,M.y);for(let M=0;M=0&&Ba[1].y+Ia>=0){const M=mn.map((M=>Gr.getTilePoint(M))),et=Hn.map((M=>Gr.getTilePoint(M)));Nt.push({tile:Wt,tileID:Gr,queryGeometry:M,cameraQueryGeometry:et,scale:Eo})}}return Nt}getVisibleCoordinates(M){const et=this.getRenderableIds(M).map((M=>this._tiles[M].tileID));return this.transform&&this.transform.populateCache(et),et}hasTransition(){if(this._source.hasTransition())return!0;if(pe(this._source.type)){const M=$t.now();for(const et in this._tiles)if(this._tiles[et].fadeEndTime>=M)return!0}return!1}setFeatureState(M,et,Bt){this._state.updateState(M=M||"_geojsonTileLayer",et,Bt)}removeFeatureState(M,et,Bt){this._state.removeFeatureState(M=M||"_geojsonTileLayer",et,Bt)}getFeatureState(M,et){return this._state.getState(M=M||"_geojsonTileLayer",et)}setDependencies(M,et,Bt){const Wt=this._tiles[M];Wt&&Wt.setDependencies(et,Bt)}reloadTilesForDependencies(M,et){for(const Bt in this._tiles)this._tiles[Bt].hasDependency(M,et)&&this._reloadTile(Bt,"reloading");this._cache.filter((Bt=>!Bt.hasDependency(M,et)))}}function _e(M,et){const Bt=Math.abs(2*M.wrap)-+(M.wrap<0),Wt=Math.abs(2*et.wrap)-+(et.wrap<0);return M.overscaledZ-et.overscaledZ||Wt-Bt||et.canonical.y-M.canonical.y||et.canonical.x-M.canonical.x}function pe(M){return"raster"===M||"image"===M||"video"===M}de.maxOverzooming=10,de.maxUnderzooming=3;class me{constructor(M,et){this.reset(M,et)}reset(M,et){this.points=M||[],this._distances=[0];for(let M=1;M0?(Nt-Gr)/mn:0;return this.points[$t].mult(1-Hn).add(this.points[Bt].mult(Hn))}}function fe(M,et){let Bt=!0;return"always"===M||"never"!==M&&"never"!==et||(Bt=!1),Bt}class ge{constructor(M,et,Bt){const Wt=this.boxCells=[],Nt=this.circleCells=[];this.xCellCount=Math.ceil(M/Bt),this.yCellCount=Math.ceil(et/Bt);for(let M=0;Mthis.width||Wt<0||et>this.height)return[];const mn=[];if(M<=0&&et<=0&&this.width<=Bt&&this.height<=Wt){if(Nt)return[{key:null,x1:M,y1:et,x2:Bt,y2:Wt}];for(let M=0;M0}hitTestCircle(M,et,Bt,Wt,Nt){const $t=M-Bt,Gr=M+Bt,mn=et-Bt,Hn=et+Bt;if(Gr<0||$t>this.width||Hn<0||mn>this.height)return!1;const so=[];return this._forEachCell($t,mn,Gr,Hn,this._queryCellCircle,so,{hitTest:!0,overlapMode:Wt,circle:{x:M,y:et,radius:Bt},seenUids:{box:{},circle:{}}},Nt),so.length>0}_queryCell(M,et,Bt,Wt,Nt,$t,Gr,mn){const{seenUids:Hn,hitTest:so,overlapMode:uo}=Gr,Io=this.boxCells[Nt];if(null!==Io){const Nt=this.bboxes;for(const Gr of Io)if(!Hn.box[Gr]){Hn.box[Gr]=!0;const Io=4*Gr,Po=this.boxKeys[Gr];if(M<=Nt[Io+2]&&et<=Nt[Io+3]&&Bt>=Nt[Io+0]&&Wt>=Nt[Io+1]&&(!mn||mn(Po))&&(!so||!fe(uo,Po.overlapMode))&&($t.push({key:Po,x1:Nt[Io],y1:Nt[Io+1],x2:Nt[Io+2],y2:Nt[Io+3]}),so))return!0}}const Po=this.circleCells[Nt];if(null!==Po){const Nt=this.circles;for(const Gr of Po)if(!Hn.circle[Gr]){Hn.circle[Gr]=!0;const Io=3*Gr,Po=this.circleKeys[Gr];if(this._circleAndRectCollide(Nt[Io],Nt[Io+1],Nt[Io+2],M,et,Bt,Wt)&&(!mn||mn(Po))&&(!so||!fe(uo,Po.overlapMode))){const M=Nt[Io],et=Nt[Io+1],Bt=Nt[Io+2];if($t.push({key:Po,x1:M-Bt,y1:et-Bt,x2:M+Bt,y2:et+Bt}),so)return!0}}}return!1}_queryCellCircle(M,et,Bt,Wt,Nt,$t,Gr,mn){const{circle:Hn,seenUids:so,overlapMode:uo}=Gr,Io=this.boxCells[Nt];if(null!==Io){const M=this.bboxes;for(const et of Io)if(!so.box[et]){so.box[et]=!0;const Bt=4*et,Wt=this.boxKeys[et];if(this._circleAndRectCollide(Hn.x,Hn.y,Hn.radius,M[Bt+0],M[Bt+1],M[Bt+2],M[Bt+3])&&(!mn||mn(Wt))&&!fe(uo,Wt.overlapMode))return $t.push(!0),!0}}const Po=this.circleCells[Nt];if(null!==Po){const M=this.circles;for(const et of Po)if(!so.circle[et]){so.circle[et]=!0;const Bt=3*et,Wt=this.circleKeys[et];if(this._circlesCollide(M[Bt],M[Bt+1],M[Bt+2],Hn.x,Hn.y,Hn.radius)&&(!mn||mn(Wt))&&!fe(uo,Wt.overlapMode))return $t.push(!0),!0}}}_forEachCell(M,et,Bt,Wt,Nt,$t,Gr,mn){const Hn=this._convertToXCellCoord(M),so=this._convertToYCellCoord(et),uo=this._convertToXCellCoord(Bt),Io=this._convertToYCellCoord(Wt);for(let Po=Hn;Po<=uo;Po++)for(let Hn=so;Hn<=Io;Hn++)if(Nt.call(this,M,et,Bt,Wt,this.xCellCount*Hn+Po,$t,Gr,mn))return}_convertToXCellCoord(M){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(M*this.xScale)))}_convertToYCellCoord(M){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(M*this.yScale)))}_circlesCollide(M,et,Bt,Wt,Nt,$t){const Gr=Wt-M,mn=Nt-et,Hn=Bt+$t;return Hn*Hn>Gr*Gr+mn*mn}_circleAndRectCollide(M,et,Bt,Wt,Nt,$t,Gr){const mn=($t-Wt)/2,Hn=Math.abs(M-(Wt+mn));if(Hn>mn+Bt)return!1;const so=(Gr-Nt)/2,uo=Math.abs(et-(Nt+so));if(uo>so+Bt)return!1;if(Hn<=mn||uo<=so)return!0;const Io=Hn-mn,Po=uo-so;return Io*Io+Po*Po<=Bt*Bt}}function ve(M,Bt,Wt){const Nt=et.H();if(!M){const{vecSouth:M,vecEast:et}=be(Bt),Wt=r();Wt[0]=et[0],Wt[1]=et[1],Wt[2]=M[0],Wt[3]=M[1],$t=Wt,(Io=(mn=(Gr=Wt)[0])*(uo=Gr[3])-(so=Gr[2])*(Hn=Gr[1]))&&($t[0]=uo*(Io=1/Io),$t[1]=-Hn*Io,$t[2]=-so*Io,$t[3]=mn*Io),Nt[0]=Wt[0],Nt[1]=Wt[1],Nt[4]=Wt[2],Nt[5]=Wt[3]}var $t,Gr,mn,Hn,so,uo,Io;return et.K(Nt,Nt,[1/Wt,1/Wt,1]),Nt}function xe(M,Bt,Wt,Nt){if(M){const M=et.H();if(!Bt){const{vecSouth:et,vecEast:Bt}=be(Wt);M[0]=Bt[0],M[1]=Bt[1],M[4]=et[0],M[5]=et[1]}return et.K(M,M,[Nt,Nt,1]),M}return Wt.pixelsToClipSpaceMatrix}function be(M){const Bt=Math.cos(M.rollInRadians),Wt=Math.sin(M.rollInRadians),Nt=Math.cos(M.pitchInRadians),$t=Math.cos(M.bearingInRadians),Gr=Math.sin(M.bearingInRadians),mn=et.ad();mn[0]=-$t*Nt*Wt-Gr*Bt,mn[1]=-Gr*Nt*Wt+$t*Bt;const Hn=et.ae(mn);Hn<1e-9?et.af(mn):et.ag(mn,mn,1/Hn);const so=et.ad();so[0]=$t*Nt*Bt-Gr*Wt,so[1]=Gr*Nt*Bt+$t*Wt;const uo=et.ae(so);return uo<1e-9?et.af(so):et.ag(so,so,1/uo),{vecEast:so,vecSouth:mn}}function ye(M,Bt,Wt,Nt){let $t;Nt?($t=[M,Bt,Nt(M,Bt),1],et.al($t,$t,Wt)):($t=[M,Bt,0,1],je($t,$t,Wt));const Gr=$t[3];return{point:new et.P($t[0]/Gr,$t[1]/Gr),signedDistanceFromCamera:Gr,isOccluded:!1}}function we(M,et){return.5+M/et*.5}function Te(M,et){return M.x>=-et[0]&&M.x<=et[0]&&M.y>=-et[1]&&M.y<=et[1]}function Pe(M,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To){const Eo=Wt?M.textSizeData:M.iconSizeData,Ia=et.ah(Eo,Bt.transform.zoom),Ba=[256/Bt.width*2+1,256/Bt.height*2+1],Ta=Wt?M.text.dynamicLayoutVertexArray:M.icon.dynamicLayoutVertexArray;Ta.clear();const Va=M.lineVertexArray,za=Wt?M.text.placedSymbolArray:M.icon.placedSymbolArray,Fa=Bt.transform.width/Bt.transform.height;let Ea=!1;for(let Wt=0;WtMath.abs(Wt.x-Bt.x)*Nt?{useVertical:!0}:(M===et.ai.vertical?Bt.yWt.x)?{needsFlipping:!0}:null}function Ee(M){const{projectionContext:Bt,pitchedLabelPlaneMatrixInverse:Wt,symbol:Nt,fontSize:$t,flip:Gr,keepUpright:mn,glyphOffsetArray:Hn,dynamicLayoutVertexArray:so,aspectRatio:uo,rotateToLine:Io}=M,Po=$t/24,To=Nt.lineOffsetX*Po,Eo=Nt.lineOffsetY*Po;let Ia;if(Nt.numGlyphs>1){const M=Nt.glyphStartIndex+Nt.numGlyphs,et=Nt.lineStartIndex,$t=Nt.lineStartIndex+Nt.lineLength,so=Ce(Po,Hn,To,Eo,Gr,Nt,Io,Bt);if(!so)return{notEnoughRoom:!0};const Ba=De(so.first.point.x,so.first.point.y,Bt,Wt),Ta=De(so.last.point.x,so.last.point.y,Bt,Wt);if(mn&&!Gr){const M=Ie(Nt.writingMode,Ba,Ta,uo);if(M)return M}Ia=[so.first];for(let Wt=Nt.glyphStartIndex+1;Wt0?mn.point:Me(Bt.tileAnchorPoint,Gr,M,1,Bt),so=De(M.x,M.y,Bt,Wt),Io=De(Hn.x,Hn.y,Bt,Wt),Po=Ie(Nt.writingMode,so,Io,uo);if(Po)return Po}const M=ke(Po*Hn.getoffsetX(Nt.glyphStartIndex),To,Eo,Gr,Nt.segment,Nt.lineStartIndex,Nt.lineStartIndex+Nt.lineLength,Bt,Io);if(!M||Bt.projectionCache.anyProjectionOccluded)return{notEnoughRoom:!0};Ia=[M]}for(const M of Ia)et.ak(so,M.point,M.angle);return{}}function Me(M,et,Bt,Wt,Nt){const $t=M.add(M.sub(et)._unit()),Gr=Re($t.x,$t.y,Nt).point,mn=Bt.sub(Gr);return Bt.add(mn._mult(Wt/mn.mag()))}function Se(M,Bt,Wt){const Nt=Bt.projectionCache;if(Nt.projections[M])return Nt.projections[M];const $t=new et.P(Bt.lineVertexArray.getx(M),Bt.lineVertexArray.gety(M)),Gr=Re($t.x,$t.y,Bt);if(Gr.signedDistanceFromCamera>0)return Nt.projections[M]=Gr.point,Nt.anyProjectionOccluded=Nt.anyProjectionOccluded||Gr.isOccluded,Gr.point;const mn=M-Wt.direction;return Me(0===Wt.distanceFromAnchor?Bt.tileAnchorPoint:new et.P(Bt.lineVertexArray.getx(mn),Bt.lineVertexArray.gety(mn)),$t,Wt.previousVertex,Wt.absOffsetX-Wt.distanceFromAnchor+1,Bt)}function Re(M,et,Bt){const Wt=M+Bt.translation[0],Nt=et+Bt.translation[1];let $t;return Bt.pitchWithMap?($t=ye(Wt,Nt,Bt.pitchedLabelPlaneMatrix,Bt.getElevation),$t.isOccluded=!1):($t=Bt.transform.projectTileCoordinates(Wt,Nt,Bt.unwrappedTileID,Bt.getElevation),$t.point.x=(.5*$t.point.x+.5)*Bt.width,$t.point.y=(.5*-$t.point.y+.5)*Bt.height),$t}function De(M,Bt,Wt,Nt){if(Wt.pitchWithMap){const $t=[M,Bt,0,1];return et.al($t,$t,Nt),Wt.transform.projectTileCoordinates($t[0]/$t[3],$t[1]/$t[3],Wt.unwrappedTileID,Wt.getElevation).point}return{x:M/Wt.width*2-1,y:Bt/Wt.height*2-1}}function ze(M,et,Bt){return Bt.transform.projectTileCoordinates(M,et,Bt.unwrappedTileID,Bt.getElevation)}function Ae(M,et,Bt){return M._unit()._perp()._mult(et*Bt)}function Le(M,Bt,Wt,Nt,$t,Gr,mn,Hn,so){if(Hn.projectionCache.offsets[M])return Hn.projectionCache.offsets[M];const uo=Wt.add(Bt);if(M+so.direction=$t)return Hn.projectionCache.offsets[M]=uo,uo;const Io=Se(M+so.direction,Hn,so),Po=Ae(Io.sub(Wt),mn,so.direction),To=Wt.add(Po),Eo=Io.add(Po);return Hn.projectionCache.offsets[M]=et.am(Gr,uo,To,Eo)||uo,Hn.projectionCache.offsets[M]}function ke(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn){const so=Wt?M-et:M+et;let uo=so>0?1:-1,Io=0;Wt&&(uo*=-1,Io=Math.PI),uo<0&&(Io+=Math.PI);let Po,To=uo>0?$t+Nt:$t+Nt+1;mn.projectionCache.cachedAnchorPoint?Po=mn.projectionCache.cachedAnchorPoint:(Po=Re(mn.tileAnchorPoint.x,mn.tileAnchorPoint.y,mn).point,mn.projectionCache.cachedAnchorPoint=Po);let Eo,Ia,Ba=Po,Ta=Po,Va=0,za=0;const Fa=Math.abs(so),Ea=[];let La;for(;Va+za<=Fa;){if(To+=uo,To<$t||To>=Gr)return null;Va+=za,Ta=Ba,Ia=Eo;const M={absOffsetX:Fa,direction:uo,distanceFromAnchor:Va,previousVertex:Ta};if(Ba=Se(To,mn,M),0===Bt)Ea.push(Ta),La=Ba.sub(Ta);else{let et;const Wt=Ba.sub(Ta);et=0===Wt.mag()?Ae(Se(To+uo,mn,M).sub(Ba),Bt,uo):Ae(Wt,Bt,uo),Ia||(Ia=Ta.add(et)),Eo=Le(To,et,Ba,$t,Gr,Ia,Bt,mn,M),Ea.push(Ia),La=Eo.sub(Ia)}za=La.mag()}const Da=La._mult((Fa-Va)/za)._add(Ia||Ta),Ka=Io+Math.atan2(Ba.y-Ta.y,Ba.x-Ta.x);return Ea.push(Da),{point:Da,angle:Hn?Ka:0,path:Ea}}const La=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function Be(M,et){for(let Bt=0;Bt=1;M--)To.push(Gr.path[M]);for(let M=1;MM.signedDistanceFromCamera<=0))?[]:M.map((M=>M.point))}let Ba=[];if(To.length>0){const M=To[0].clone(),Bt=To[0].clone();for(let et=1;et=Wt.x&&Bt.x<=Nt.x&&M.y>=Wt.y&&Bt.y<=Nt.y?[To]:Bt.xNt.x||Bt.yNt.y?[]:et.ao([To],Wt.x,Wt.y,Nt.x,Nt.y)}for(const et of Ba){$t.reset(et,.25*Bt);let Wt=0;Wt=$t.length<=.5*Bt?1:Math.ceil($t.paddedLength/Eo)+1;for(let et=0;et{const et=ye(M.x,M.y,Wt,Bt.getElevation),Nt=Bt.transform.projectTileCoordinates(et.point.x,et.point.y,Bt.unwrappedTileID,Bt.getElevation);return Nt.point.x=(.5*Nt.point.x+.5)*Bt.width,Nt.point.y=(.5*-Nt.point.y+.5)*Bt.height,Nt}))}(M,Bt);return function(M){let et=0,Bt=0,Wt=0,Nt=0;for(let $t=0;$tBt&&(Bt=Nt,et=Wt));return M.slice(et,et+Bt)}(Wt)}queryRenderedSymbols(M){if(0===M.length||0===this.grid.keysLength()&&0===this.ignoredGrid.keysLength())return{};const Bt=[];let Wt=1/0,Nt=1/0,$t=-1/0,Gr=-1/0;for(const mn of M){const M=new et.P(mn.x+Da,mn.y+Da);Wt=Math.min(Wt,M.x),Nt=Math.min(Nt,M.y),$t=Math.max($t,M.x),Gr=Math.max(Gr,M.y),Bt.push(M)}const mn=this.grid.query(Wt,Nt,$t,Gr).concat(this.ignoredGrid.query(Wt,Nt,$t,Gr)),Hn={},so={};for(const M of mn){const Wt=M.key;if(void 0===Hn[Wt.bucketInstanceId]&&(Hn[Wt.bucketInstanceId]={}),Hn[Wt.bucketInstanceId][Wt.featureIndex])continue;const Nt=[new et.P(M.x1,M.y1),new et.P(M.x2,M.y1),new et.P(M.x2,M.y2),new et.P(M.x1,M.y2)];et.ap(Bt,Nt)&&(Hn[Wt.bucketInstanceId][Wt.featureIndex]=!0,void 0===so[Wt.bucketInstanceId]&&(so[Wt.bucketInstanceId]=[]),so[Wt.bucketInstanceId].push(Wt.featureIndex))}return so}insertCollisionBox(M,et,Bt,Wt,Nt,$t){(Bt?this.ignoredGrid:this.grid).insert({bucketInstanceId:Wt,featureIndex:Nt,collisionGroupID:$t,overlapMode:et},M[0],M[1],M[2],M[3])}insertCollisionCircles(M,et,Bt,Wt,Nt,$t){const Gr=Bt?this.ignoredGrid:this.grid,mn={bucketInstanceId:Wt,featureIndex:Nt,collisionGroupID:$t,overlapMode:et};for(let et=0;et=this.screenRightBoundary||Wtthis.screenBottomBoundary}isInsideGrid(M,et,Bt,Wt){return Bt>=0&&M=0&&etthis.projectAndGetPerspectiveRatio(M.x,M.y,Nt,so,Io)));Zl=M.some((M=>!M.isOccluded)),Sl=M.map((M=>new et.P(M.x,M.y)))}else Zl=!0;return{box:et.ar(Sl),allPointsOccluded:!Zl}}}class Ze{constructor(M,et,Bt,Wt){this.opacity=M?Math.max(0,Math.min(1,M.opacity+(M.placed?et:-et))):Wt&&Bt?1:0,this.placed=Bt}isHidden(){return 0===this.opacity&&!this.placed}}class Ge{constructor(M,et,Bt,Wt,Nt){this.text=new Ze(M?M.text:null,et,Bt,Nt),this.icon=new Ze(M?M.icon:null,et,Wt,Nt)}isHidden(){return this.text.isHidden()&&this.icon.isHidden()}}class Ue{constructor(M,et,Bt){this.text=M,this.icon=et,this.skipFade=Bt}}class Ve{constructor(M,et,Bt,Wt,Nt){this.bucketInstanceId=M,this.featureIndex=et,this.sourceLayerIndex=Bt,this.bucketIndex=Wt,this.tileID=Nt}}class qe{constructor(M){this.crossSourceCollisions=M,this.maxGroupID=0,this.collisionGroups={}}get(M){if(this.crossSourceCollisions)return{ID:0,predicate:null};if(!this.collisionGroups[M]){const et=++this.maxGroupID;this.collisionGroups[M]={ID:et,predicate:M=>M.collisionGroupID===et}}return this.collisionGroups[M]}}function He(M,Bt,Wt,Nt,$t){const{horizontalAlign:Gr,verticalAlign:mn}=et.ay(M);return new et.P(-(Gr-.5)*Bt+Nt[0]*$t,-(mn-.5)*Wt+Nt[1]*$t)}class We{constructor(M,et,Bt,Wt,Nt){this.transform=M.clone(),this.terrain=et,this.collisionIndex=new Ne(this.transform),this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=Bt,this.retainedQueryData={},this.collisionGroups=new qe(Wt),this.collisionCircleArrays={},this.collisionBoxArrays=new Map,this.prevPlacement=Nt,Nt&&(Nt.prevPlacement=void 0),this.placedOrientations={}}_getTerrainElevationFunc(M){const et=this.terrain;return et?(Bt,Wt)=>et.getElevation(M,Bt,Wt):null}getBucketParts(M,Bt,Wt,Nt){const $t=Wt.getBucket(Bt),Gr=Wt.latestFeatureIndex;if(!$t||!Gr||Bt.id!==$t.layerIds[0])return;const mn=Wt.collisionBoxArray,Hn=$t.layers[0].layout,so=$t.layers[0].paint,uo=Math.pow(2,this.transform.zoom-Wt.tileID.overscaledZ),Io=Wt.tileSize/et.X,Po=Wt.tileID.toUnwrapped(),To="map"===Hn.get("text-rotation-alignment"),Eo=et.at(Wt,1,this.transform.zoom),Ia=et.au(this.collisionIndex.transform,Wt,so.get("text-translate"),so.get("text-translate-anchor")),Ba=et.au(this.collisionIndex.transform,Wt,so.get("icon-translate"),so.get("icon-translate-anchor")),Ta=ve(To,this.transform,Eo);this.retainedQueryData[$t.bucketInstanceId]=new Ve($t.bucketInstanceId,Gr,$t.sourceLayerIndex,$t.index,Wt.tileID);const Va={bucket:$t,layout:Hn,translationText:Ia,translationIcon:Ba,unwrappedTileID:Po,pitchedLabelPlaneMatrix:Ta,scale:uo,textPixelRatio:Io,holdingForFade:Wt.holdingForFade(),collisionBoxArray:mn,partiallyEvaluatedTextSize:et.ah($t.textSizeData,this.transform.zoom),collisionGroup:this.collisionGroups.get($t.sourceID)};if(Nt)for(const et of $t.sortKeyRanges){const{sortKey:Bt,symbolInstanceStart:Wt,symbolInstanceEnd:Nt}=et;M.push({sortKey:Bt,symbolInstanceStart:Wt,symbolInstanceEnd:Nt,parameters:Va})}else M.push({symbolInstanceStart:0,symbolInstanceEnd:$t.symbolInstances.length,parameters:Va})}attemptAnchorPlacement(M,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba,Ta,Va,za,Fa){const Ea=et.av[M.textAnchor],La=[M.textOffset0,M.textOffset1],Da=He(Ea,Wt,Nt,La,$t),Ka=this.collisionIndex.placeCollisionBox(Bt,Po,Hn,so,uo,mn,Gr,Ba,Io.predicate,za,Da,Fa);if((!Va||this.collisionIndex.placeCollisionBox(Va,Po,Hn,so,uo,mn,Gr,Ta,Io.predicate,za,Da,Fa).placeable)&&Ka.placeable){let M;if(this.prevPlacement&&this.prevPlacement.variableOffsets[To.crossTileID]&&this.prevPlacement.placements[To.crossTileID]&&this.prevPlacement.placements[To.crossTileID].text&&(M=this.prevPlacement.variableOffsets[To.crossTileID].anchor),0===To.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");return this.variableOffsets[To.crossTileID]={textOffset:La,width:Wt,height:Nt,anchor:Ea,textBoxScale:$t,prevAnchor:M},this.markUsedJustification(Eo,Ea,To,Ia),Eo.allowVerticalPlacement&&(this.markUsedOrientation(Eo,Ia,To),this.placedOrientations[To.crossTileID]=Ia),{shift:Da,placedGlyphBoxes:Ka}}}placeLayerBucketPart(M,Bt,Wt){const{bucket:Nt,layout:$t,translationText:Gr,translationIcon:mn,unwrappedTileID:Hn,pitchedLabelPlaneMatrix:so,textPixelRatio:uo,holdingForFade:Io,collisionBoxArray:Po,partiallyEvaluatedTextSize:To,collisionGroup:Eo}=M.parameters,Ia=$t.get("text-optional"),Ba=$t.get("icon-optional"),Ta=et.aw($t,"text-overlap","text-allow-overlap"),Va="always"===Ta,za=et.aw($t,"icon-overlap","icon-allow-overlap"),Fa="always"===za,Ea="map"===$t.get("text-rotation-alignment"),La="map"===$t.get("text-pitch-alignment"),Da="none"!==$t.get("icon-text-fit"),Ka="viewport-y"===$t.get("symbol-z-order"),Oa=Va&&(Fa||!Nt.hasIconData()||Ba),$a=Fa&&(Va||!Nt.hasTextData()||Ia);!Nt.collisionArrays&&Po&&Nt.deserializeCollisionBoxes(Po);const Al=this.retainedQueryData[Nt.bucketInstanceId].tileID,Sl=this._getTerrainElevationFunc(Al),Zl=this.transform.getFastPathSimpleProjectionMatrix(Al),R=(M,Po,Fa)=>{var Ka,Gl;if(Bt[M.crossTileID])return;if(Io)return void(this.placements[M.crossTileID]=new Ue(!1,!1,!1));let Rl=!1,Tl=!1,Vl=!0,Wl=null,El={box:null,placeable:!1,offscreen:null,occluded:!1},Jl={box:null,placeable:!1,offscreen:null},Ll=null,Dl=null,Nl=null,Yl=0,Ol=0,jl=0;Po.textFeatureIndex?Yl=Po.textFeatureIndex:M.useRuntimeCollisionCircles&&(Yl=M.featureIndex),Po.verticalTextFeatureIndex&&(Ol=Po.verticalTextFeatureIndex);const Ul=Po.textBox;if(Ul){const i=Bt=>{let Wt=et.ai.horizontal;if(Nt.allowVerticalPlacement&&!Bt&&this.prevPlacement){const et=this.prevPlacement.placedOrientations[M.crossTileID];et&&(this.placedOrientations[M.crossTileID]=et,Wt=et,this.markUsedOrientation(Nt,Wt,M))}return Wt},s=(Bt,Wt)=>{if(Nt.allowVerticalPlacement&&M.numVerticalGlyphVertices>0&&Po.verticalTextBox){for(const M of Nt.writingModes)if(M===et.ai.vertical?(El=Wt(),Jl=El):El=Bt(),El&&El.placeable)break}else El=Bt()},Bt=M.textAnchorOffsetStartIndex,$t=M.textAnchorOffsetEndIndex;if($t===Bt){const r=(et,Bt)=>{const Wt=this.collisionIndex.placeCollisionBox(et,Ta,uo,Al,Hn,La,Ea,Gr,Eo.predicate,Sl,void 0,Zl);return Wt&&Wt.placeable&&(this.markUsedOrientation(Nt,Bt,M),this.placedOrientations[M.crossTileID]=Bt),Wt};s((()=>r(Ul,et.ai.horizontal)),(()=>{const Bt=Po.verticalTextBox;return Nt.allowVerticalPlacement&&M.numVerticalGlyphVertices>0&&Bt?r(Bt,et.ai.vertical):{box:null,offscreen:null}})),i(El&&El.placeable)}else{let so=et.av[null===(Gl=null===(Ka=this.prevPlacement)||void 0===Ka?void 0:Ka.variableOffsets[M.crossTileID])||void 0===Gl?void 0:Gl.anchor];const m=(et,Io,Po)=>{const To=et.x2-et.x1,Ia=et.y2-et.y1,Ba=M.textBoxScale,Va=Da&&"never"===za?Io:null;let Fa=null,Ka="never"===Ta?1:2,Oa="never";so&&Ka++;for(let Wt=0;Wtm(Ul,Po.iconBox,et.ai.horizontal)),(()=>{const Bt=Po.verticalTextBox;return Nt.allowVerticalPlacement&&(!El||!El.placeable)&&M.numVerticalGlyphVertices>0&&Bt?m(Bt,Po.verticalIconBox,et.ai.vertical):{box:null,occluded:!0,offscreen:null}})),El&&(Rl=El.placeable,Vl=El.offscreen);const Io=i(El&&El.placeable);if(!Rl&&this.prevPlacement){const et=this.prevPlacement.variableOffsets[M.crossTileID];et&&(this.variableOffsets[M.crossTileID]=et,this.markUsedJustification(Nt,et.anchor,M,Io))}}}if(Ll=El,Rl=Ll&&Ll.placeable,Vl=Ll&&Ll.offscreen,M.useRuntimeCollisionCircles){const Bt=Nt.text.placedSymbolArray.get(M.centerJustifiedTextSymbolIndex),mn=et.aj(Nt.textSizeData,To,Bt),uo=$t.get("text-padding");Dl=this.collisionIndex.placeCollisionCircles(Ta,Bt,Nt.lineVertexArray,Nt.glyphOffsetArray,mn,Hn,so,Wt,La,Eo.predicate,M.collisionCircleDiameter,uo,Gr,Sl),Dl.circles.length&&Dl.collisionDetected&&!Wt&&et.w("Collisions detected, but collision boxes are not shown"),Rl=Va||Dl.circles.length>0&&!Dl.collisionDetected,Vl=Vl&&Dl.offscreen}if(Po.iconFeatureIndex&&(jl=Po.iconFeatureIndex),Po.iconBox){const e=M=>this.collisionIndex.placeCollisionBox(M,za,uo,Al,Hn,La,Ea,mn,Eo.predicate,Sl,Da&&Wl?Wl:void 0,Zl);Jl&&Jl.placeable&&Po.verticalIconBox?(Nl=e(Po.verticalIconBox),Tl=Nl.placeable):(Nl=e(Po.iconBox),Tl=Nl.placeable),Vl=Vl&&Nl.offscreen}const ql=Ia||0===M.numHorizontalGlyphVertices&&0===M.numVerticalGlyphVertices,$l=Ba||0===M.numIconVertices;ql||$l?$l?ql||(Tl=Tl&&Rl):Rl=Tl&&Rl:Tl=Rl=Tl&&Rl;const tc=Tl&&Nl.placeable;if(Rl&&Ll.placeable&&this.collisionIndex.insertCollisionBox(Ll.box,Ta,$t.get("text-ignore-placement"),Nt.bucketInstanceId,Jl&&Jl.placeable&&Ol?Ol:Yl,Eo.ID),tc&&this.collisionIndex.insertCollisionBox(Nl.box,za,$t.get("icon-ignore-placement"),Nt.bucketInstanceId,jl,Eo.ID),Dl&&Rl&&this.collisionIndex.insertCollisionCircles(Dl.circles,Ta,$t.get("text-ignore-placement"),Nt.bucketInstanceId,Yl,Eo.ID),Wt&&this.storeCollisionData(Nt.bucketInstanceId,Fa,Po,Ll,Nl,Dl),0===M.crossTileID)throw new Error("symbolInstance.crossTileID can't be 0");if(0===Nt.bucketInstanceId)throw new Error("bucket.bucketInstanceId can't be 0");this.placements[M.crossTileID]=new Ue((Rl||Oa)&&!(null==Ll?void 0:Ll.occluded),(Tl||$a)&&!(null==Nl?void 0:Nl.occluded),Vl||Nt.justReloaded),Bt[M.crossTileID]=!0};if(Ka){if(0!==M.symbolInstanceStart)throw new Error("bucket.bucketInstanceId should be 0");const et=Nt.getSortedSymbolIndexes(-this.transform.bearingInRadians);for(let M=et.length-1;M>=0;--M){const Bt=et[M];R(Nt.symbolInstances.get(Bt),Nt.collisionArrays[Bt],Bt)}}else for(let et=M.symbolInstanceStart;et=0&&(M.text.placedSymbolArray.get(et).crossTileID=$t>=0&&et!==$t?0:Wt.crossTileID)}markUsedOrientation(M,Bt,Wt){const Nt=Bt===et.ai.horizontal||Bt===et.ai.horizontalOnly?Bt:0,$t=Bt===et.ai.vertical?Bt:0,Gr=[Wt.leftJustifiedTextSymbolIndex,Wt.centerJustifiedTextSymbolIndex,Wt.rightJustifiedTextSymbolIndex];for(const et of Gr)M.text.placedSymbolArray.get(et).placedOrientation=Nt;Wt.verticalPlacedTextSymbolIndex&&(M.text.placedSymbolArray.get(Wt.verticalPlacedTextSymbolIndex).placedOrientation=$t)}commit(M){this.commitTime=M,this.zoomAtLastRecencyCheck=this.transform.zoom;const et=this.prevPlacement;let Bt=!1;this.prevZoomAdjustment=et?et.zoomAdjustment(this.transform.zoom):0;const Wt=et?et.symbolFadeChange(M):1,Nt=et?et.opacities:{},$t=et?et.variableOffsets:{},Gr=et?et.placedOrientations:{};for(const M in this.placements){const et=this.placements[M],$t=Nt[M];$t?(this.opacities[M]=new Ge($t,Wt,et.text,et.icon),Bt=Bt||et.text!==$t.text.placed||et.icon!==$t.icon.placed):(this.opacities[M]=new Ge(null,Wt,et.text,et.icon,et.skipFade),Bt=Bt||et.text||et.icon)}for(const M in Nt){const et=Nt[M];if(!this.opacities[M]){const Nt=new Ge(et,Wt,!1,!1);Nt.isHidden()||(this.opacities[M]=Nt,Bt=Bt||et.text.placed||et.icon.placed)}}for(const M in $t)this.variableOffsets[M]||!this.opacities[M]||this.opacities[M].isHidden()||(this.variableOffsets[M]=$t[M]);for(const M in Gr)this.placedOrientations[M]||!this.opacities[M]||this.opacities[M].isHidden()||(this.placedOrientations[M]=Gr[M]);if(et&&void 0===et.lastPlacementChangeTime)throw new Error("Last placement time for previous placement is not defined");Bt?this.lastPlacementChangeTime=M:"number"!=typeof this.lastPlacementChangeTime&&(this.lastPlacementChangeTime=et?et.lastPlacementChangeTime:M)}updateLayerOpacities(M,et){const Bt={};for(const Wt of et){const et=Wt.getBucket(M);et&&Wt.latestFeatureIndex&&M.id===et.layerIds[0]&&this.updateBucketOpacities(et,Wt.tileID,Bt,Wt.collisionBoxArray)}}updateBucketOpacities(M,Bt,Wt,Nt){M.hasTextData()&&(M.text.opacityVertexArray.clear(),M.text.hasVisibleVertices=!1),M.hasIconData()&&(M.icon.opacityVertexArray.clear(),M.icon.hasVisibleVertices=!1),M.hasIconCollisionBoxData()&&M.iconCollisionBox.collisionVertexArray.clear(),M.hasTextCollisionBoxData()&&M.textCollisionBox.collisionVertexArray.clear();const $t=M.layers[0],Gr=$t.layout,mn=new Ge(null,0,!1,!1,!0),Hn=Gr.get("text-allow-overlap"),so=Gr.get("icon-allow-overlap"),uo=$t._unevaluatedLayout.hasValue("text-variable-anchor")||$t._unevaluatedLayout.hasValue("text-variable-anchor-offset"),Io="map"===Gr.get("text-rotation-alignment"),Po="map"===Gr.get("text-pitch-alignment"),To="none"!==Gr.get("icon-text-fit"),Eo=new Ge(null,0,Hn&&(so||!M.hasIconData()||Gr.get("icon-optional")),so&&(Hn||!M.hasTextData()||Gr.get("text-optional")),!0);!M.collisionArrays&&Nt&&(M.hasIconCollisionBoxData()||M.hasTextCollisionBoxData())&&M.deserializeCollisionBoxes(Nt);const m=(M,et,Bt)=>{for(let Wt=0;Wt0,Ta=this.placedOrientations[Nt.crossTileID],Va=Ta===et.ai.vertical,za=Ta===et.ai.horizontal||Ta===et.ai.horizontalOnly;if($t>0||Gr>0){const et=it(so.text);m(M.text,$t,Va?Rl:et),m(M.text,Gr,za?Rl:et);const Bt=so.text.isHidden();[Nt.rightJustifiedTextSymbolIndex,Nt.centerJustifiedTextSymbolIndex,Nt.leftJustifiedTextSymbolIndex].forEach((et=>{et>=0&&(M.text.placedSymbolArray.get(et).hidden=Bt||Va?1:0)})),Nt.verticalPlacedTextSymbolIndex>=0&&(M.text.placedSymbolArray.get(Nt.verticalPlacedTextSymbolIndex).hidden=Bt||za?1:0);const Wt=this.variableOffsets[Nt.crossTileID];Wt&&this.markUsedJustification(M,Wt.anchor,Nt,Ta);const mn=this.placedOrientations[Nt.crossTileID];mn&&(this.markUsedJustification(M,"left",Nt,mn),this.markUsedOrientation(M,mn,Nt))}if(Ba){const et=it(so.icon),Bt=!(To&&Nt.verticalPlacedIconSymbolIndex&&Va);Nt.placedIconSymbolIndex>=0&&(m(M.icon,Nt.numIconVertices,Bt?et:Rl),M.icon.placedSymbolArray.get(Nt.placedIconSymbolIndex).hidden=so.icon.isHidden()),Nt.verticalPlacedIconSymbolIndex>=0&&(m(M.icon,Nt.numVerticalIconVertices,Bt?Rl:et),M.icon.placedSymbolArray.get(Nt.verticalPlacedIconSymbolIndex).hidden=so.icon.isHidden())}const Fa=Ia&&Ia.has(Bt)?Ia.get(Bt):{text:null,icon:null};if(M.hasIconCollisionBoxData()||M.hasTextCollisionBoxData()){const Wt=M.collisionArrays[Bt];if(Wt){let Bt=new et.P(0,0);if(Wt.textBox||Wt.verticalTextBox){let et=!0;if(uo){const M=this.variableOffsets[Hn];M?(Bt=He(M.anchor,M.width,M.height,M.textOffset,M.textBoxScale),Io&&Bt._rotate(Po?-this.transform.bearingInRadians:this.transform.bearingInRadians)):et=!1}if(Wt.textBox||Wt.verticalTextBox){let Nt;Wt.textBox&&(Nt=Va),Wt.verticalTextBox&&(Nt=za),Xe(M.textCollisionBox.collisionVertexArray,so.text.placed,!et||Nt,Fa.text,Bt.x,Bt.y)}}if(Wt.iconBox||Wt.verticalIconBox){const et=Boolean(!za&&Wt.verticalIconBox);let Nt;Wt.iconBox&&(Nt=et),Wt.verticalIconBox&&(Nt=!et),Xe(M.iconCollisionBox.collisionVertexArray,so.icon.placed,Nt,Fa.icon,To?Bt.x:0,To?Bt.y:0)}}}}if(M.sortFeatures(-this.transform.bearingInRadians),this.retainedQueryData[M.bucketInstanceId]&&(this.retainedQueryData[M.bucketInstanceId].featureSortOrder=M.featureSortOrder),M.hasTextData()&&M.text.opacityVertexBuffer&&M.text.opacityVertexBuffer.updateData(M.text.opacityVertexArray),M.hasIconData()&&M.icon.opacityVertexBuffer&&M.icon.opacityVertexBuffer.updateData(M.icon.opacityVertexArray),M.hasIconCollisionBoxData()&&M.iconCollisionBox.collisionVertexBuffer&&M.iconCollisionBox.collisionVertexBuffer.updateData(M.iconCollisionBox.collisionVertexArray),M.hasTextCollisionBoxData()&&M.textCollisionBox.collisionVertexBuffer&&M.textCollisionBox.collisionVertexBuffer.updateData(M.textCollisionBox.collisionVertexArray),M.text.opacityVertexArray.length!==M.text.layoutVertexArray.length/4)throw new Error(`bucket.text.opacityVertexArray.length (= ${M.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${M.text.layoutVertexArray.length}) / 4`);if(M.icon.opacityVertexArray.length!==M.icon.layoutVertexArray.length/4)throw new Error(`bucket.icon.opacityVertexArray.length (= ${M.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${M.icon.layoutVertexArray.length}) / 4`);M.bucketInstanceId in this.collisionCircleArrays&&(M.collisionCircleArray=this.collisionCircleArrays[M.bucketInstanceId],delete this.collisionCircleArrays[M.bucketInstanceId])}symbolFadeChange(M){return 0===this.fadeDuration?1:(M-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(M){return Math.max(0,(this.transform.zoom-M)/1.5)}hasTransitions(M){return this.stale||M-this.lastPlacementChangeTimeM}setStale(){this.stale=!0}}function Xe(M,et,Bt,Wt,Nt,$t){Wt&&0!==Wt.length||(Wt=[0,0,0,0]);const Gr=Wt[0]-Da,mn=Wt[1]-Da,Hn=Wt[2]-Da,so=Wt[3]-Da;M.emplaceBack(et?1:0,Bt?1:0,Nt||0,$t||0,Gr,mn),M.emplaceBack(et?1:0,Bt?1:0,Nt||0,$t||0,Hn,mn),M.emplaceBack(et?1:0,Bt?1:0,Nt||0,$t||0,Hn,so),M.emplaceBack(et?1:0,Bt?1:0,Nt||0,$t||0,Gr,so)}const Ka=Math.pow(2,25),Oa=Math.pow(2,24),$a=Math.pow(2,17),Al=Math.pow(2,16),Sl=Math.pow(2,9),Zl=Math.pow(2,8),Gl=Math.pow(2,1);function it(M){if(0===M.opacity&&!M.placed)return 0;if(1===M.opacity&&M.placed)return 4294967295;const et=M.placed?1:0,Bt=Math.floor(127*M.opacity);return Bt*Ka+et*Oa+Bt*$a+et*Al+Bt*Sl+et*Zl+Bt*Gl+et}const Rl=0;class ot{constructor(M){this._sortAcrossTiles="viewport-y"!==M.layout.get("symbol-z-order")&&!M.layout.get("symbol-sort-key").isConstant(),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[]}continuePlacement(M,et,Bt,Wt,Nt){const $t=this._bucketParts;for(;this._currentTileIndexM.sortKey-et.sortKey)));this._currentPartIndex<$t.length;)if(et.placeLayerBucketPart($t[this._currentPartIndex],this._seenCrossTileIDs,Bt),this._currentPartIndex++,Nt())return!0;return!1}}class st{constructor(M,et,Bt,Wt,Nt,$t,Gr,mn){this.placement=new We(M,et,$t,Gr,mn),this._currentPlacementIndex=Bt.length-1,this._forceFullPlacement=Wt,this._showCollisionBoxes=Nt,this._done=!1}isDone(){return this._done}continuePlacement(M,et,Bt){const Wt=$t.now(),o=()=>!this._forceFullPlacement&&$t.now()-Wt>2;for(;this._currentPlacementIndex>=0;){const Wt=et[M[this._currentPlacementIndex]],Nt=this.placement.collisionIndex.transform.zoom;if("symbol"===Wt.type&&(!Wt.minzoom||Wt.minzoom<=Nt)&&(!Wt.maxzoom||Wt.maxzoom>Nt)){if(this._inProgressLayer||(this._inProgressLayer=new ot(Wt)),this._inProgressLayer.continuePlacement(Bt[Wt.source],this.placement,this._showCollisionBoxes,Wt,o))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._done=!0}commit(M){return this.placement.commit(M),this.placement}}const Tl=512/et.X/2;class nt{constructor(M,Bt,Wt){this.tileID=M,this.bucketInstanceId=Wt,this._symbolsByKey={};const Nt=new Map;for(let M=0;M({x:Math.floor(M.anchorX*Tl),y:Math.floor(M.anchorY*Tl)}))),crossTileIDs:Bt.map((M=>M.crossTileID))};if(Wt.positions.length>128){const M=new et.az(Wt.positions.length,16,Uint16Array);for(const{x:et,y:Bt}of Wt.positions)M.add(et,Bt);M.finish(),delete Wt.positions,Wt.index=M}this._symbolsByKey[M]=Wt}}getScaledCoordinates(M,Bt){const{x:Wt,y:Nt,z:$t}=this.tileID.canonical,{x:Gr,y:mn,z:Hn}=Bt.canonical,so=Tl/Math.pow(2,Hn-$t),uo=(mn*et.X+M.anchorY)*so,Io=Nt*et.X*Tl;return{x:Math.floor((Gr*et.X+M.anchorX)*so-Wt*et.X*Tl),y:Math.floor(uo-Io)}}findMatches(M,et,Bt){const Wt=this.tileID.canonical.zM))}}class lt{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class ct{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(M){const et=Math.round((M-this.lng)/360);if(0!==et)for(const M in this.indexes){const Bt=this.indexes[M],Wt={};for(const M in Bt){const Nt=Bt[M];Nt.tileID=Nt.tileID.unwrapTo(Nt.tileID.wrap+et),Wt[Nt.tileID.key]=Nt}this.indexes[M]=Wt}this.lng=M}addBucket(M,et,Bt){if(this.indexes[M.overscaledZ]&&this.indexes[M.overscaledZ][M.key]){if(this.indexes[M.overscaledZ][M.key].bucketInstanceId===et.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(M.overscaledZ,this.indexes[M.overscaledZ][M.key])}for(let M=0;MM.overscaledZ)for(const Bt in Nt){const $t=Nt[Bt];$t.tileID.isChildOf(M)&&$t.findMatches(et.symbolInstances,M,Wt)}else{const $t=Nt[M.scaledTo(Number(Bt)).key];$t&&$t.findMatches(et.symbolInstances,M,Wt)}}for(let M=0;M{et[M]=!0}));for(const M in this.layerIndexes)et[M]||delete this.layerIndexes[M]}}var Vl="void main() {fragColor=vec4(1.0);}";const Wl={prelude:_t("#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nout highp vec4 fragColor;","#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const float packedOpacity) {int intOpacity=int(packedOpacity)/2;return vec2(float(intOpacity)/127.0,mod(packedOpacity,2.0));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}mat3 rotationMatrixFromAxisAngle(vec3 u,float angle) {float c=cos(angle);float s=sin(angle);float c2=1.0-c;return mat3(u.x*u.x*c2+ c,u.x*u.y*c2-u.z*s,u.x*u.z*c2+u.y*s,u.y*u.x*c2+u.z*s,u.y*u.y*c2+ c,u.y*u.z*c2-u.x*s,u.z*u.x*c2-u.y*s,u.z*u.y*c2+u.x*s,u.z*u.z*c2+ c\n);}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(vec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texture(u_terrain,pos)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\n#ifdef GLOBE\nif ((pos.y <-32767.5) || (pos.y > 32766.5)) {return 0.0;}\n#endif\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);vec2 c=(floor(coord)+0.5)/(u_terrain_dim+2.0);float d=1.0/(u_terrain_dim+2.0);float tl=ele(c);float tr=ele(c+vec2(d,0.0));float bl=ele(c+vec2(0.0,d));float br=ele(c+vec2(d,d));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}const float PI=3.141592653589793;uniform mat4 u_projection_matrix;"),projectionMercator:_t("","float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}"),projectionGlobe:_t("","#define GLOBE_RADIUS 6371008.8\nuniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos\n);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float spherical_y=2.0*atan(exp(PI-(mercator_pos_y*PI*2.0)))-PI*0.5;return cos(spherical_y);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY); \nif (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 translatedPos,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*translatedPos;vec2 spherical;spherical.x=mercator_pos.x*PI*2.0+PI;spherical.y=2.0*atan(exp(PI-(mercator_pos.y*PI*2.0)))-PI*0.5;float len=cos(spherical.y);vec3 pos=vec3(sin(spherical.x)*len,sin(spherical.y),cos(spherical.x)*len\n);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeComputeClippingZ(vec3 spherePos) {return (1.0-(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphere(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphere(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphere(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphere(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}"),background:_t("uniform vec4 u_color;uniform float u_opacity;void main() {fragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),backgroundPattern:_t("uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}"),circle:_t("in vec3 v_data;in float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);float antialiased_blur=v_data.z;float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));fragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);const float epsilon=0.5/255.0;if (fragColor.r < epsilon && fragColor.g < epsilon && fragColor.b < epsilon && fragColor.a < epsilon) {discard;}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;uniform vec2 u_translate;in vec2 a_pos;out vec3 v_data;out float v_visibility;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\nvoid main(void) {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize mediump float radius\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize highp vec4 stroke_color\n#pragma mapbox: initialize mediump float stroke_width\n#pragma mapbox: initialize lowp float stroke_opacity\nvec2 pos_raw=a_pos+32768.0;vec2 extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);vec2 circle_center=floor(pos_raw/8.0)+u_translate;float ele=get_elevation(circle_center);v_visibility=calculate_visibility(projectTileWithElevation(circle_center,ele));if (u_pitch_with_map) {\n#ifdef GLOBE\nvec3 center_vector=projectToSphere(circle_center);\n#endif\nfloat angle_scale=u_globe_extrude_scale;vec2 corner_position=circle_center;if (u_scale_with_map) {angle_scale*=(radius+stroke_width);corner_position+=extrude*u_extrude_scale*(radius+stroke_width);} else {\n#ifdef GLOBE\nvec4 projected_center=interpolateProjection(circle_center,center_vector,ele);\n#else\nvec4 projected_center=projectTileWithElevation(circle_center,ele);\n#endif\ncorner_position+=extrude*u_extrude_scale*(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);angle_scale*=(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);}\n#ifdef GLOBE\nvec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);\n#else\ngl_Position=projectTileWithElevation(corner_position,ele);\n#endif\n} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}"),clippingMask:_t(Vl,"in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),heatmap:_t("uniform highp float u_intensity;in vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma mapbox: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);fragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;uniform highp float u_globe_extrude_scale;in vec2 a_pos;out vec2 v_extrude;\n#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma mapbox: initialize highp float weight\n#pragma mapbox: initialize mediump float radius\nvec2 pos_raw=a_pos+32768.0;vec2 unscaled_extrude=vec2(mod(pos_raw,8.0)/7.0*2.0-1.0);float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 circle_center=floor(pos_raw/8.0);\n#ifdef GLOBE\nvec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphere(circle_center);vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);\n#else\ngl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));\n#endif\n}"),heatmapTexture:_t("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(0.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),collisionBox:_t("in float v_placed;in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}","in vec2 a_anchor_pos;in vec2 a_placed;in vec2 a_box_real;uniform vec2 u_pixel_extrude_scale;out float v_placed;out float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}"),collisionCircle:_t("in float v_radius;in vec2 v_extrude;in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);fragColor=color*alpha*opacity_t;}","in vec2 a_pos;in float a_radius;in vec2 a_flags;uniform vec2 u_viewport_size;out float v_radius;out vec2 v_extrude;out float v_collision;void main() {float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),debug:_t("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);fragColor=mix(u_color,overlay_color,overlay_color.a);}","in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}"),depth:_t(Vl,"in vec2 a_pos;void main() {\n#ifdef GLOBE\ngl_Position=projectTileFor3D(a_pos,0.0);\n#else\ngl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);\n#endif\n}"),fill:_t("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\nfragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_fill_translate;in vec2 a_pos;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);}"),fillOutline:_t("in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=outline_color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillOutlinePattern:_t("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),fillPattern:_t("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),fillExtrusion:_t("in vec4 v_color;void main() {fragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\nout vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nfloat colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;vec3 normalForLighting=normal/16384.0;float directional=clamp(dot(normalForLighting,u_lightpos),0.0,1.0);\n#ifdef GLOBE\nmat3 rotMatrix=globeGetRotationMatrix(spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);\n#endif\ndirectional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),fillExtrusionPattern:_t("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;in vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);fragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;in vec2 a_pos;in vec4 a_normal_ed;\n#ifdef TERRAIN3D\nin vec2 a_centroid;\n#endif\n#ifdef GLOBE\nout vec3 v_sphere_pos;\n#endif\nout vec2 v_pos_a;out vec2 v_pos_b;out vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=mod(normal.x,2.0);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nvec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,elevation*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),hillshadePrepare:_t("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/pow(2.0,exaggeration+(19.2562-u_zoom));fragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;in vec2 a_pos;in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),hillshade:_t("uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\n#define PI 3.141592653589793\nvoid main() {vec4 pixel=texture(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);fragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),line:_t("uniform lowp float u_device_pixel_ratio;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp float v_linesofar;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),lineGradient:_t("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture(u_image,v_uv);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nin vec2 a_pos_normal;in vec4 a_data;in float a_uv_x;in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),linePattern:_t("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;in vec2 v_normal;in vec2 v_width2;in float v_linesofar;in float v_gamma_scale;in float v_width;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture(u_image,pos_a),texture(u_image,pos_b),u_fade);fragColor=color*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;out vec2 v_width2;out float v_linesofar;out float v_gamma_scale;out float v_width;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),lineSDF:_t("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture(u_image,v_tex_a).a;float sdfdist_b=texture(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nin vec2 a_pos_normal;in vec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;out vec2 v_normal;out vec2 v_width2;out vec2 v_tex_a;out vec2 v_tex_b;out float v_gamma_scale;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),raster:_t("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec2 v_pos0;in vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture(u_image0,v_pos0);vec4 color1=texture(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;uniform vec4 u_coords_top;uniform vec4 u_coords_bottom;in vec2 a_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {vec2 fractionalPos=a_pos/8192.0;vec2 position=mix(mix(u_coords_top.xy,u_coords_top.zw,fractionalPos.x),mix(u_coords_bottom.xy,u_coords_bottom.zw,fractionalPos.x),fractionalPos.y);gl_Position=projectTile(position,position);v_pos0=((fractionalPos-0.5)/u_buffer_scale)+0.5;\n#ifdef GLOBE\nif (a_pos.y <-32767.5) {v_pos0.y=0.0;}if (a_pos.y > 32766.5) {v_pos0.y=1.0;}\n#endif\nv_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),symbolIcon:_t("uniform sampler2D u_texture;in vec2 v_tex;in float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;fragColor=texture(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_tex;out float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));}"),symbolSDF:_t("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;in vec2 v_data0;in vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);inner_edge=inner_edge+gamma*gamma_scale;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);if (u_is_halo) {lowp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha=min(smoothstep(halo_edge-gamma_scaled,halo_edge+gamma_scaled,dist),1.0-alpha);}fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec4 a_pixeloffset;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;out vec2 v_data0;out vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),symbolTextAndIcon:_t("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;in vec4 v_data0;in vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;fragColor=texture(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);fragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}","in vec4 a_pos_offset;in vec4 a_data;in vec3 a_projected_pos;in float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;out vec4 v_data0;out vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}"),terrain:_t("uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;uniform bool u_is_globe_mode;in vec2 v_texture_pos;in float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);fragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {fragColor=surface_color;}}","in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_texture_pos;out float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,get_elevation(a_pos3d.xy)-ele_delta);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}"),terrainDepth:_t("in float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {fragColor=pack(v_depth);}","in vec3 a_pos3d;uniform float u_ele_delta;out float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}"),terrainCoords:_t("precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;in vec2 v_texture_pos;void main() {vec4 rgba=texture(u_texture,v_texture_pos);fragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}","in vec3 a_pos3d;uniform float u_ele_delta;out vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);}"),projectionErrorMeasurement:_t("in vec4 v_output_error_encoded;void main() {fragColor=v_output_error_encoded;}","in vec2 a_pos;uniform highp float u_input;uniform highp float u_output_expected;out vec4 v_output_error_encoded;void main() {float real_output=2.0*atan(exp(PI-(u_input*PI*2.0)))-PI*0.5;float error=real_output-u_output_expected;float abs_error=abs(error)*128.0;v_output_error_encoded.x=min(floor(abs_error*256.0),255.0)/255.0;abs_error-=v_output_error_encoded.x;v_output_error_encoded.y=min(floor(abs_error*65536.0),255.0)/255.0;abs_error-=v_output_error_encoded.x/255.0;v_output_error_encoded.z=min(floor(abs_error*16777216.0),255.0)/255.0;v_output_error_encoded.w=error >=0.0 ? 1.0 : 0.0;gl_Position=vec4(a_pos,0.0,1.0);}"),atmosphere:_t("in vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) {return vec4(0.0,0.0,0.0,1.0);}if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie)));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758\n);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}","in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}"),sky:_t("uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor=mix(fragColor,vec4(vec3(0.0),0.0),u_sky_blend);}","in vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}")};function _t(M,et){const Bt=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,Wt=et.match(/in ([\w]+) ([\w]+)/g),Nt=M.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),$t=et.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),Gr=$t?$t.concat(Nt):Nt,mn={};return{fragmentSource:M=M.replace(Bt,((M,et,Bt,Wt,Nt)=>(mn[Nt]=!0,"define"===et?`\n#ifndef HAS_UNIFORM_u_${Nt}\nin ${Bt} ${Wt} ${Nt};\n#else\nuniform ${Bt} ${Wt} u_${Nt};\n#endif\n`:`\n#ifdef HAS_UNIFORM_u_${Nt}\n ${Bt} ${Wt} ${Nt} = u_${Nt};\n#endif\n`))),vertexSource:et=et.replace(Bt,((M,et,Bt,Wt,Nt)=>{const $t="float"===Wt?"vec2":"vec4",Gr=Nt.match(/color/)?"color":$t;return mn[Nt]?"define"===et?`\n#ifndef HAS_UNIFORM_u_${Nt}\nuniform lowp float u_${Nt}_t;\nin ${Bt} ${$t} a_${Nt};\nout ${Bt} ${Wt} ${Nt};\n#else\nuniform ${Bt} ${Wt} u_${Nt};\n#endif\n`:"vec4"===Gr?`\n#ifndef HAS_UNIFORM_u_${Nt}\n ${Nt} = a_${Nt};\n#else\n ${Bt} ${Wt} ${Nt} = u_${Nt};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${Nt}\n ${Nt} = unpack_mix_${Gr}(a_${Nt}, u_${Nt}_t);\n#else\n ${Bt} ${Wt} ${Nt} = u_${Nt};\n#endif\n`:"define"===et?`\n#ifndef HAS_UNIFORM_u_${Nt}\nuniform lowp float u_${Nt}_t;\nin ${Bt} ${$t} a_${Nt};\n#else\nuniform ${Bt} ${Wt} u_${Nt};\n#endif\n`:"vec4"===Gr?`\n#ifndef HAS_UNIFORM_u_${Nt}\n ${Bt} ${Wt} ${Nt} = a_${Nt};\n#else\n ${Bt} ${Wt} ${Nt} = u_${Nt};\n#endif\n`:`\n#ifndef HAS_UNIFORM_u_${Nt}\n ${Bt} ${Wt} ${Nt} = unpack_mix_${Gr}(a_${Nt}, u_${Nt}_t);\n#else\n ${Bt} ${Wt} ${Nt} = u_${Nt};\n#endif\n`})),staticAttributes:Wt,staticUniforms:Gr}}class pt{constructor(M,et,Bt){this.vertexBuffer=M,this.indexBuffer=et,this.segments=Bt}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.vertexBuffer=null,this.indexBuffer=null,this.segments=null}}var El=et.aA([{name:"a_pos",type:"Int16",components:2}]);const Jl="#define PROJECTION_MERCATOR",Ll="mercator";class vt{constructor(){this._cachedMesh=null}get name(){return"mercator"}get useSubdivision(){return!1}get shaderVariantName(){return Ll}get shaderDefine(){return Jl}get shaderPreludeCode(){return Wl.projectionMercator}get vertexShaderPreludeCode(){return Wl.projectionMercator.vertexSource}get subdivisionGranularity(){return et.aB.noSubdivision}get useGlobeControls(){return!1}get transitionState(){return 0}get latitudeErrorCorrectionRadians(){return 0}destroy(){}updateGPUdependent(M){}getMeshFromTileID(M,Bt,Wt,Nt,$t){if(this._cachedMesh)return this._cachedMesh;const Gr=new et.aC;Gr.emplaceBack(0,0),Gr.emplaceBack(et.X,0),Gr.emplaceBack(0,et.X),Gr.emplaceBack(et.X,et.X);const mn=M.createVertexBuffer(Gr,El.members),Hn=et.aD.simpleSegment(0,0,4,2),so=new et.aE;so.emplaceBack(1,0,2),so.emplaceBack(1,2,3);const uo=M.createIndexBuffer(so);return this._cachedMesh=new pt(mn,uo,Hn),this._cachedMesh}recalculate(){}hasTransition(){return!1}setErrorQueryLatitudeDegrees(M){}}function xt(M,Bt){const Wt=et.ab(Bt.lat,-et.aF,et.aF);return new et.P(et.O(Bt.lng)*M,et.Q(Wt)*M)}function bt(M,Bt){return new et.Y(Bt.x/M,Bt.y/M).toLngLat()}function yt(M){return M.cameraToCenterDistance*Math.min(.85*Math.tan(et.aa(90-M.pitch)),Math.tan(et.aa(89.25-M.pitch)))}function wt(M,Bt){const Wt=M.canonical,Nt=Bt/et.aG(Wt.z),$t=Wt.x+Math.pow(2,Wt.z)*M.wrap,Gr=et.aq(new Float64Array(16));return et.J(Gr,Gr,[$t*Nt,Wt.y*Nt,0]),et.K(Gr,Gr,[Nt/et.X,Nt/et.X,1]),Gr}function Tt(M,Bt,Wt,Nt,$t){const Gr=et.Y.fromLngLat(M,Bt),mn=$t*et.aH(1,M.lat),Hn=mn*Math.cos(et.aa(Wt)),so=Math.sqrt(mn*mn-Hn*Hn),uo=so*Math.sin(et.aa(-Nt)),Io=so*Math.cos(et.aa(-Nt));return new et.Y(Gr.x+uo,Gr.y+Io,Gr.z+Hn)}class Pt{constructor(M=0,et=0,Bt=0,Wt=0){if(isNaN(M)||M<0||isNaN(et)||et<0||isNaN(Bt)||Bt<0||isNaN(Wt)||Wt<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=M,this.bottom=et,this.left=Bt,this.right=Wt}interpolate(M,Bt,Wt){return null!=Bt.top&&null!=M.top&&(this.top=et.y.number(M.top,Bt.top,Wt)),null!=Bt.bottom&&null!=M.bottom&&(this.bottom=et.y.number(M.bottom,Bt.bottom,Wt)),null!=Bt.left&&null!=M.left&&(this.left=et.y.number(M.left,Bt.left,Wt)),null!=Bt.right&&null!=M.right&&(this.right=et.y.number(M.right,Bt.right,Wt)),this}getCenter(M,Bt){const Wt=et.ab((this.left+M-this.right)/2,0,M),Nt=et.ab((this.top+Bt-this.bottom)/2,0,Bt);return new et.P(Wt,Nt)}equals(M){return this.top===M.top&&this.bottom===M.bottom&&this.left===M.left&&this.right===M.right}clone(){return new Pt(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function Ct(M,et){if(!M.renderWorldCopies||M.lngRange)return;const Bt=et.lng-M.center.lng;et.lng+=Bt>180?-360:Bt<-180?360:0}function It(M){return Math.max(0,Math.floor(M))}class Et{constructor(M,Bt,Wt,Nt,$t,Gr){this._callbacks=M,this._tileSize=512,this._renderWorldCopies=void 0===Gr||!!Gr,this._minZoom=Bt||0,this._maxZoom=Wt||22,this._minPitch=null==Nt?0:Nt,this._maxPitch=null==$t?60:$t,this.setMaxBounds(),this._width=0,this._height=0,this._center=new et.N(0,0),this._elevation=0,this._zoom=0,this._tileZoom=It(this._zoom),this._scale=et.aG(this._zoom),this._bearingInRadians=0,this._fovInRadians=.6435011087932844,this._pitchInRadians=0,this._rollInRadians=0,this._unmodified=!0,this._edgeInsets=new Pt,this._minElevationForCurrentTile=0,this._autoCalculateNearFarZ=!0}apply(M,Bt,Wt){this._latRange=M.latRange,this._lngRange=M.lngRange,this._width=M.width,this._height=M.height,this._center=M.center,this._elevation=M.elevation,this._minElevationForCurrentTile=M.minElevationForCurrentTile,this._zoom=M.zoom,this._tileZoom=It(this._zoom),this._scale=et.aG(this._zoom),this._bearingInRadians=M.bearingInRadians,this._fovInRadians=M.fovInRadians,this._pitchInRadians=M.pitchInRadians,this._rollInRadians=M.rollInRadians,this._unmodified=M.unmodified,this._edgeInsets=new Pt(M.padding.top,M.padding.bottom,M.padding.left,M.padding.right),this._minZoom=M.minZoom,this._maxZoom=M.maxZoom,this._minPitch=M.minPitch,this._maxPitch=M.maxPitch,this._renderWorldCopies=M.renderWorldCopies,this._cameraToCenterDistance=M.cameraToCenterDistance,this._nearZ=M.nearZ,this._farZ=M.farZ,this._autoCalculateNearFarZ=!Wt&&M.autoCalculateNearFarZ,Bt&&this._constrain(),this._calcMatrices()}get pixelsToClipSpaceMatrix(){return this._pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._clipSpaceToPixelsMatrix}get minElevationForCurrentTile(){return this._minElevationForCurrentTile}setMinElevationForCurrentTile(M){this._minElevationForCurrentTile=M}get tileSize(){return this._tileSize}get tileZoom(){return this._tileZoom}get scale(){return this._scale}get width(){return this._width}get height(){return this._height}get bearingInRadians(){return this._bearingInRadians}get lngRange(){return this._lngRange}get latRange(){return this._latRange}get pixelsToGLUnits(){return this._pixelsToGLUnits}get minZoom(){return this._minZoom}setMinZoom(M){this._minZoom!==M&&(this._minZoom=M,this.setZoom(this.getConstrained(this._center,this.zoom).zoom))}get maxZoom(){return this._maxZoom}setMaxZoom(M){this._maxZoom!==M&&(this._maxZoom=M,this.setZoom(this.getConstrained(this._center,this.zoom).zoom))}get minPitch(){return this._minPitch}setMinPitch(M){this._minPitch!==M&&(this._minPitch=M,this.setPitch(Math.max(this.pitch,M)))}get maxPitch(){return this._maxPitch}setMaxPitch(M){this._maxPitch!==M&&(this._maxPitch=M,this.setPitch(Math.min(this.pitch,M)))}get renderWorldCopies(){return this._renderWorldCopies}setRenderWorldCopies(M){void 0===M?M=!0:null===M&&(M=!1),this._renderWorldCopies=M}get worldSize(){return this._tileSize*this._scale}get centerOffset(){return this.centerPoint._sub(this.size._div(2))}get size(){return new et.P(this._width,this._height)}get bearing(){return this._bearingInRadians/Math.PI*180}setBearing(M){const Bt=et.aI(M,-180,180)*Math.PI/180;var Wt,Nt,$t,Gr,mn,Hn,so,uo,Io;this._bearingInRadians!==Bt&&(this._unmodified=!1,this._bearingInRadians=Bt,this._calcMatrices(),this._rotationMatrix=r(),Wt=this._rotationMatrix,$t=-this._bearingInRadians,Gr=(Nt=this._rotationMatrix)[0],mn=Nt[1],Hn=Nt[2],so=Nt[3],uo=Math.sin($t),Io=Math.cos($t),Wt[0]=Gr*Io+Hn*uo,Wt[1]=mn*Io+so*uo,Wt[2]=Gr*-uo+Hn*Io,Wt[3]=mn*-uo+so*Io)}get rotationMatrix(){return this._rotationMatrix}get pitchInRadians(){return this._pitchInRadians}get pitch(){return this._pitchInRadians/Math.PI*180}setPitch(M){const Bt=et.ab(M,this.minPitch,this.maxPitch)/180*Math.PI;this._pitchInRadians!==Bt&&(this._unmodified=!1,this._pitchInRadians=Bt,this._calcMatrices())}get rollInRadians(){return this._rollInRadians}get roll(){return this._rollInRadians/Math.PI*180}setRoll(M){const et=M/180*Math.PI;this._rollInRadians!==et&&(this._unmodified=!1,this._rollInRadians=et,this._calcMatrices())}get fovInRadians(){return this._fovInRadians}get fov(){return et.aJ(this._fovInRadians)}setFov(M){M=et.ab(M,.1,150),this.fov!==M&&(this._unmodified=!1,this._fovInRadians=et.aa(M),this._calcMatrices())}get zoom(){return this._zoom}setZoom(M){const Bt=this.getConstrained(this._center,M).zoom;this._zoom!==Bt&&(this._unmodified=!1,this._zoom=Bt,this._tileZoom=Math.max(0,Math.floor(Bt)),this._scale=et.aG(Bt),this._constrain(),this._calcMatrices())}get center(){return this._center}setCenter(M){M.lat===this._center.lat&&M.lng===this._center.lng||(this._unmodified=!1,this._center=M,this._constrain(),this._calcMatrices())}get elevation(){return this._elevation}setElevation(M){M!==this._elevation&&(this._elevation=M,this._constrain(),this._calcMatrices())}get padding(){return this._edgeInsets.toJSON()}setPadding(M){this._edgeInsets.equals(M)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,M,1),this._calcMatrices())}get centerPoint(){return this._edgeInsets.getCenter(this._width,this._height)}get pixelsPerMeter(){return this._pixelPerMeter}get unmodified(){return this._unmodified}get cameraToCenterDistance(){return this._cameraToCenterDistance}get nearZ(){return this._nearZ}get farZ(){return this._farZ}get autoCalculateNearFarZ(){return this._autoCalculateNearFarZ}overrideNearFarZ(M,et){this._autoCalculateNearFarZ=!1,this._nearZ=M,this._farZ=et,this._calcMatrices()}clearNearFarZOverride(){this._autoCalculateNearFarZ=!0,this._calcMatrices()}isPaddingEqual(M){return this._edgeInsets.equals(M)}interpolatePadding(M,et,Bt){this._unmodified=!1,this._edgeInsets.interpolate(M,et,Bt),this._constrain(),this._calcMatrices()}resize(M,et,Bt=!0){this._width=M,this._height=et,Bt&&this._constrain(),this._calcMatrices()}getMaxBounds(){return this._latRange&&2===this._latRange.length&&this._lngRange&&2===this._lngRange.length?new V([this._lngRange[0],this._latRange[0]],[this._lngRange[1],this._latRange[1]]):null}setMaxBounds(M){M?(this._lngRange=[M.getWest(),M.getEast()],this._latRange=[M.getSouth(),M.getNorth()],this._constrain()):(this._lngRange=null,this._latRange=[-et.aF,et.aF])}getConstrained(M,et){return this._callbacks.getConstrained(M,et)}getCameraQueryGeometry(M,Bt){if(1===Bt.length)return[Bt[0],M];{let Wt=M.x,Nt=M.y,$t=M.x,Gr=M.y;for(const M of Bt)Wt=Math.min(Wt,M.x),Nt=Math.min(Nt,M.y),$t=Math.max($t,M.x),Gr=Math.max(Gr,M.y);return[new et.P(Wt,Nt),new et.P($t,Nt),new et.P($t,Gr),new et.P(Wt,Gr),new et.P(Wt,Nt)]}}_constrain(){if(!this.center||!this._width||!this._height||this._constraining)return;this._constraining=!0;const M=this._unmodified,{center:et,zoom:Bt}=this.getConstrained(this.center,this.zoom);this.setCenter(et),this.setZoom(Bt),this._unmodified=M,this._constraining=!1}_calcMatrices(){if(this._width&&this._height){this._pixelsToGLUnits=[2/this._width,-2/this._height];let M=et.aq(new Float64Array(16));et.K(M,M,[this._width/2,-this._height/2,1]),et.J(M,M,[1,-1,0]),this._clipSpaceToPixelsMatrix=M,M=et.aq(new Float64Array(16)),et.K(M,M,[1,-1,1]),et.J(M,M,[-1,-1,0]),et.K(M,M,[2/this._width,2/this._height,1]),this._pixelsToClipSpaceMatrix=M,this._cameraToCenterDistance=.5/Math.tan(this.fovInRadians/2)*this._height}this._callbacks.calcMatrices()}calculateCenterFromCameraLngLatAlt(M,Bt,Wt,Nt){const $t=void 0!==Wt?Wt:this.bearing,Gr=Nt=void 0!==Nt?Nt:this.pitch,mn=et.Y.fromLngLat(M,Bt),Hn=-Math.cos(et.aa(Gr)),so=Math.sin(et.aa(Gr)),uo=so*Math.sin(et.aa($t)),Io=-so*Math.cos(et.aa($t));let Po=this.elevation;const To=Bt-Po;let Eo;Hn*To>=0||Math.abs(Hn)<.1?(Eo=1e4,Po=Bt+Eo*Hn):Eo=-To/Hn;let Ia,Ba,Ta=et.aK(1,mn.y),Va=0;do{if(Va+=1,Va>10)break;Ba=Eo/Ta,Ia=new et.Y(mn.x+uo*Ba,mn.y+Io*Ba),Ta=1/Ia.meterInMercatorCoordinateUnits()}while(Math.abs(Eo-Ba*Ta)>1e-12);return{center:Ia.toLngLat(),elevation:Po,zoom:et.a8(this.height/2/Math.tan(this.fovInRadians/2)/Ba/this.tileSize)}}recalculateZoomAndCenter(M){if(this.elevation-M==0)return;const Bt=et.aH(1,this.center.lat)*this.worldSize,Wt=this.cameraToCenterDistance/Bt,Nt=et.Y.fromLngLat(this.center,this.elevation),$t=Tt(this.center,this.elevation,this.pitch,this.bearing,Wt);this._elevation=M;const Gr=this.calculateCenterFromCameraLngLatAlt($t.toLngLat(),et.aK($t.z,Nt.y),this.bearing,this.pitch);this._elevation=Gr.elevation,this._center=Gr.center,this.setZoom(Gr.zoom)}getCameraPoint(){const M=Math.tan(this.pitchInRadians)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new et.P(M*Math.sin(this.rollInRadians),M*Math.cos(this.rollInRadians)))}getCameraAltitude(){return Math.cos(this.pitchInRadians)*this._cameraToCenterDistance/this._pixelPerMeter+this.elevation}getCameraLngLat(){const M=et.aH(1,this.center.lat)*this.worldSize;return Tt(this.center,this.elevation,this.pitch,this.bearing,this.cameraToCenterDistance/M).toLngLat()}getMercatorTileCoordinates(M){if(!M)return[0,0,1,1];const Bt=M.canonical.z>=0?1<this.max[0]||M.aabb.min[1]>this.max[1]||M.aabb.min[2]>this.max[2]||M.aabb.max[0]0?(et+=M[Wt]*this.min[Wt],Bt+=M[Wt]*this.max[Wt]):(Bt+=M[Wt]*this.min[Wt],et+=M[Wt]*this.max[Wt]);return et>=0?2:Bt<0?0:1}}class St{distanceToTile2d(M,et,Bt,Wt){const Nt=Wt.distanceX([M,et]),$t=Wt.distanceY([M,et]);return Math.hypot(Nt,$t)}getWrap(M,et,Bt){return Bt}getTileAABB(M,Bt,Wt,Nt){var $t,Gr;let mn=Wt,Hn=Wt;if(Nt.terrain){const so=new et.S(M.z,Bt,M.z,M.x,M.y),uo=Nt.terrain.getMinMaxElevation(so);mn=null!==($t=uo.minElevation)&&void 0!==$t?$t:Wt,Hn=null!==(Gr=uo.maxElevation)&&void 0!==Gr?Gr:Wt}const so=1<Nt||M.padding.top>=.1}allowWorldCopies(){return!0}recalculateCache(){}}class Rt{constructor(M,et,Bt){this.points=M,this.planes=et,this.aabb=Bt}static fromInvProjectionMatrix(M,Bt=1,Wt=0){const Nt=Math.pow(2,Wt),$t=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((Wt=>{const $t=1/(Wt=et.al([],Wt,M))[3]/Bt*Nt;return et.aO(Wt,Wt,[$t,$t,1/Wt[3],$t])})),Gr=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map((M=>{const Bt=et.aP([],$t[M[0]],$t[M[1]]),Wt=et.aP([],$t[M[2]],$t[M[1]]),Nt=et.aQ([],et.aR([],Bt,Wt)),Gr=-et.aS(Nt,$t[M[1]]);return Nt.concat(Gr)})),mn=[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY],Hn=[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY];for(const M of $t)for(let et=0;et<3;et++)mn[et]=Math.min(mn[et],M[et]),Hn[et]=Math.max(Hn[et],M[et]);return new Rt($t,Gr,new Mt(mn,Hn))}}class Dt{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(M){this._helper.setMinZoom(M)}setMaxZoom(M){this._helper.setMaxZoom(M)}setMinPitch(M){this._helper.setMinPitch(M)}setMaxPitch(M){this._helper.setMaxPitch(M)}setRenderWorldCopies(M){this._helper.setRenderWorldCopies(M)}setBearing(M){this._helper.setBearing(M)}setPitch(M){this._helper.setPitch(M)}setRoll(M){this._helper.setRoll(M)}setFov(M){this._helper.setFov(M)}setZoom(M){this._helper.setZoom(M)}setCenter(M){this._helper.setCenter(M)}setElevation(M){this._helper.setElevation(M)}setMinElevationForCurrentTile(M){this._helper.setMinElevationForCurrentTile(M)}setPadding(M){this._helper.setPadding(M)}interpolatePadding(M,et,Bt){return this._helper.interpolatePadding(M,et,Bt)}isPaddingEqual(M){return this._helper.isPaddingEqual(M)}resize(M,et,Bt=!0){this._helper.resize(M,et,Bt)}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(M){this._helper.setMaxBounds(M)}overrideNearFarZ(M,et){this._helper.overrideNearFarZ(M,et)}clearNearFarZOverride(){this._helper.clearNearFarZOverride()}getCameraQueryGeometry(M){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),M)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}setTransitionState(M,et){}constructor(M,et,Bt,Wt,Nt){this._posMatrixCache=new Map,this._alignedPosMatrixCache=new Map,this._fogMatrixCacheF32=new Map,this._helper=new Et({calcMatrices:()=>{this._calcMatrices()},getConstrained:(M,et)=>this.getConstrained(M,et)},M,et,Bt,Wt,Nt),this._coveringTilesDetailsProvider=new St}clone(){const M=new Dt;return M.apply(this),M}apply(M,et,Bt){this._helper.apply(M,et,Bt)}get cameraPosition(){return this._cameraPosition}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._viewProjMatrix}get inverseProjectionMatrix(){return this._invProjMatrix}get mercatorMatrix(){return this._mercatorMatrix}getVisibleUnwrappedCoordinates(M){const Bt=[new et.aT(0,M)];if(this._helper._renderWorldCopies){const Wt=this.screenPointToMercatorCoordinate(new et.P(0,0)),Nt=this.screenPointToMercatorCoordinate(new et.P(this._helper._width,0)),$t=this.screenPointToMercatorCoordinate(new et.P(this._helper._width,this._helper._height)),Gr=this.screenPointToMercatorCoordinate(new et.P(0,this._helper._height)),mn=Math.floor(Math.min(Wt.x,Nt.x,$t.x,Gr.x)),Hn=Math.floor(Math.max(Wt.x,Nt.x,$t.x,Gr.x)),so=1;for(let Wt=mn-so;Wt<=Hn+so;Wt++)0!==Wt&&Bt.push(new et.aT(Wt,M))}return Bt}getCameraFrustum(){return Rt.fromInvProjectionMatrix(this._invViewProjMatrix,this.worldSize)}getClippingPlane(){return null}getCoveringTilesDetailsProvider(){return this._coveringTilesDetailsProvider}recalculateZoomAndCenter(M){const et=this.screenPointToLocation(this.centerPoint,M),Bt=M?M.getElevationForLngLatZoom(et,this._helper._tileZoom):0;this._helper.recalculateZoomAndCenter(Bt)}setLocationAtPoint(M,Bt){const Wt=et.aH(this.elevation,this.center.lat),Nt=this.screenPointToMercatorCoordinateAtZ(Bt,Wt),$t=this.screenPointToMercatorCoordinateAtZ(this.centerPoint,Wt),Gr=et.Y.fromLngLat(M),mn=new et.Y(Gr.x-(Nt.x-$t.x),Gr.y-(Nt.y-$t.y));this.setCenter(null==mn?void 0:mn.toLngLat()),this._helper._renderWorldCopies&&this.setCenter(this.center.wrap())}locationToScreenPoint(M,Bt){return Bt?this.coordinatePoint(et.Y.fromLngLat(M),Bt.getElevationForLngLatZoom(M,this._helper._tileZoom),this._pixelMatrix3D):this.coordinatePoint(et.Y.fromLngLat(M))}screenPointToLocation(M,et){var Bt;return null===(Bt=this.screenPointToMercatorCoordinate(M,et))||void 0===Bt?void 0:Bt.toLngLat()}screenPointToMercatorCoordinate(M,et){if(et){const Bt=et.pointCoordinate(M);if(null!=Bt)return Bt}return this.screenPointToMercatorCoordinateAtZ(M)}screenPointToMercatorCoordinateAtZ(M,Bt){const Wt=Bt||0,Nt=[M.x,M.y,0,1],$t=[M.x,M.y,1,1];et.al(Nt,Nt,this._pixelMatrixInverse),et.al($t,$t,this._pixelMatrixInverse);const Gr=Nt[3],mn=$t[3],Hn=Nt[1]/Gr,so=$t[1]/mn,uo=Nt[2]/Gr,Io=$t[2]/mn,Po=uo===Io?0:(Wt-uo)/(Io-uo);return new et.Y(et.y.number(Nt[0]/Gr,$t[0]/mn,Po)/this.worldSize,et.y.number(Hn,so,Po)/this.worldSize,Wt)}coordinatePoint(M,Bt=0,Wt=this._pixelMatrix){const Nt=[M.x*this.worldSize,M.y*this.worldSize,Bt,1];return et.al(Nt,Nt,Wt),new et.P(Nt[0]/Nt[3],Nt[1]/Nt[3])}getBounds(){const M=Math.max(0,this._helper._height/2-yt(this));return(new V).extend(this.screenPointToLocation(new et.P(0,M))).extend(this.screenPointToLocation(new et.P(this._helper._width,M))).extend(this.screenPointToLocation(new et.P(this._helper._width,this._helper._height))).extend(this.screenPointToLocation(new et.P(0,this._helper._height)))}isPointOnMapSurface(M,et){return et?null!=et.pointCoordinate(M):M.y>this.height/2-yt(this)}calculatePosMatrix(M,Bt=!1,Wt){var Nt;const $t=null!==(Nt=M.key)&&void 0!==Nt?Nt:et.aU(M.wrap,M.canonical.z,M.canonical.z,M.canonical.x,M.canonical.y),Gr=Bt?this._alignedPosMatrixCache:this._posMatrixCache;if(Gr.has($t)){const M=Gr.get($t);return Wt?M.f32:M.f64}const mn=wt(M,this.worldSize);et.L(mn,Bt?this._alignedProjMatrix:this._viewProjMatrix,mn);const Hn={f64:mn,f32:new Float32Array(mn)};return Gr.set($t,Hn),Wt?Hn.f32:Hn.f64}calculateFogMatrix(M){const Bt=M.key,Wt=this._fogMatrixCacheF32;if(Wt.has(Bt))return Wt.get(Bt);const Nt=wt(M,this.worldSize);return et.L(Nt,this._fogMatrix,Nt),Wt.set(Bt,new Float32Array(Nt)),Wt.get(Bt)}getConstrained(M,Bt){Bt=et.ab(+Bt,this.minZoom,this.maxZoom);const Wt={center:new et.N(M.lng,M.lat),zoom:Bt};let Nt=this._helper._lngRange;this._helper._renderWorldCopies||null!==Nt||(Nt=[-179.9999999999,180-1e-10]);const $t=this.tileSize*et.aG(Wt.zoom);let Gr=0,mn=$t,Hn=0,so=$t,uo=0,Io=0;const{x:Po,y:To}=this.size;if(this._helper._latRange){const M=this._helper._latRange;Gr=et.Q(M[1])*$t,mn=et.Q(M[0])*$t,mn-Grmn&&(Ta=mn-M)}if(Nt){const M=(Hn+so)/2;let Bt=Eo;this._helper._renderWorldCopies&&(Bt=et.aI(Eo,M-$t/2,M+$t/2));const Wt=Po/2;Bt-Wtso&&(Ba=so-Wt)}if(void 0!==Ba||void 0!==Ta){const M=new et.P(null!=Ba?Ba:Eo,null!=Ta?Ta:Ia);Wt.center=bt($t,M).wrap()}return Wt}calculateCenterFromCameraLngLatAlt(M,et,Bt,Wt){return this._helper.calculateCenterFromCameraLngLatAlt(M,et,Bt,Wt)}_calculateNearFarZIfNeeded(M,Bt,Wt){if(!this._helper.autoCalculateNearFarZ)return;const Nt=Math.min(this.elevation,this.minElevationForCurrentTile,this.getCameraAltitude()-100),$t=M-Nt*this._helper._pixelPerMeter/Math.cos(Bt),Gr=Nt<0?$t:M,mn=Math.PI/2+this.pitchInRadians,Hn=et.aa(this.fov)*(Math.abs(Math.cos(et.aa(this.roll)))*this.height+Math.abs(Math.sin(et.aa(this.roll)))*this.width)/this.height*(.5+Wt.y/this.height),so=Math.sin(Hn)*Gr/Math.sin(et.ab(Math.PI-mn-Hn,.01,Math.PI-.01)),uo=yt(this),Io=Math.atan(uo/this._helper.cameraToCenterDistance),Po=et.aa(.75),To=Io>Po?2*Io*(.5+Wt.y/(2*uo)):Po,Eo=Math.sin(To)*Gr/Math.sin(et.ab(Math.PI-mn-To,.01,Math.PI-.01)),Ia=Math.min(so,Eo);this._helper._farZ=1.01*(Math.cos(Math.PI/2-Bt)*Ia+Gr),this._helper._nearZ=this._helper._height/50}_calcMatrices(){if(!this._helper._height)return;const M=this.centerOffset,Bt=xt(this.worldSize,this.center),Wt=Bt.x,Nt=Bt.y;this._helper._pixelPerMeter=et.aH(1,this.center.lat)*this.worldSize;const $t=et.aa(Math.min(this.pitch,89.25)),Gr=Math.max(this._helper.cameraToCenterDistance/2,this._helper.cameraToCenterDistance+this._helper._elevation*this._helper._pixelPerMeter/Math.cos($t));let mn;this._calculateNearFarZIfNeeded(Gr,$t,M),mn=new Float64Array(16),et.aV(mn,this.fovInRadians,this._helper._width/this._helper._height,this._helper._nearZ,this._helper._farZ),this._invProjMatrix=new Float64Array(16),et.an(this._invProjMatrix,mn),mn[8]=2*-M.x/this._helper._width,mn[9]=2*M.y/this._helper._height,this._projectionMatrix=et.aW(mn),et.K(mn,mn,[1,-1,1]),et.J(mn,mn,[0,0,-this._helper.cameraToCenterDistance]),et.aX(mn,mn,-this.rollInRadians),et.aY(mn,mn,this.pitchInRadians),et.aX(mn,mn,-this.bearingInRadians),et.J(mn,mn,[-Wt,-Nt,0]),this._mercatorMatrix=et.K([],mn,[this.worldSize,this.worldSize,this.worldSize]),et.K(mn,mn,[1,1,this._helper._pixelPerMeter]),this._pixelMatrix=et.L(new Float64Array(16),this.clipSpaceToPixelsMatrix,mn),et.J(mn,mn,[0,0,-this.elevation]),this._viewProjMatrix=mn,this._invViewProjMatrix=et.an([],mn);const Hn=[0,0,-1,1];et.al(Hn,Hn,this._invViewProjMatrix),this._cameraPosition=[Hn[0]/Hn[3],Hn[1]/Hn[3],Hn[2]/Hn[3]],this._fogMatrix=new Float64Array(16),et.aV(this._fogMatrix,this.fovInRadians,this.width/this.height,Gr,this._helper._farZ),this._fogMatrix[8]=2*-M.x/this.width,this._fogMatrix[9]=2*M.y/this.height,et.K(this._fogMatrix,this._fogMatrix,[1,-1,1]),et.J(this._fogMatrix,this._fogMatrix,[0,0,-this.cameraToCenterDistance]),et.aX(this._fogMatrix,this._fogMatrix,-this.rollInRadians),et.aY(this._fogMatrix,this._fogMatrix,this.pitchInRadians),et.aX(this._fogMatrix,this._fogMatrix,-this.bearingInRadians),et.J(this._fogMatrix,this._fogMatrix,[-Wt,-Nt,0]),et.K(this._fogMatrix,this._fogMatrix,[1,1,this._helper._pixelPerMeter]),et.J(this._fogMatrix,this._fogMatrix,[0,0,-this.elevation]),this._pixelMatrix3D=et.L(new Float64Array(16),this.clipSpaceToPixelsMatrix,mn);const so=this._helper._width%2/2,uo=this._helper._height%2/2,Io=Math.cos(this.bearingInRadians),Po=Math.sin(-this.bearingInRadians),To=Wt-Math.round(Wt)+Io*so+Po*uo,Eo=Nt-Math.round(Nt)+Io*uo+Po*so,Ia=new Float64Array(mn);if(et.J(Ia,Ia,[To>.5?To-1:To,Eo>.5?Eo-1:Eo,0]),this._alignedProjMatrix=Ia,mn=et.an(new Float64Array(16),this._pixelMatrix),!mn)throw new Error("failed to invert matrix");this._pixelMatrixInverse=mn,this._clearMatrixCaches()}_clearMatrixCaches(){this._posMatrixCache.clear(),this._alignedPosMatrixCache.clear(),this._fogMatrixCacheF32.clear()}maxPitchScaleFactor(){if(!this._pixelMatrixInverse)return 1;const M=this.screenPointToMercatorCoordinate(new et.P(0,0)),Bt=[M.x*this.worldSize,M.y*this.worldSize,0,1];return et.al(Bt,Bt,this._pixelMatrix)[3]/this._helper.cameraToCenterDistance}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){const M=et.aH(1,this.center.lat)*this.worldSize;return Tt(this.center,this.elevation,this.pitch,this.bearing,this._helper.cameraToCenterDistance/M).toLngLat()}lngLatToCameraDepth(M,Bt){const Wt=et.Y.fromLngLat(M),Nt=[Wt.x*this.worldSize,Wt.y*this.worldSize,Bt,1];return et.al(Nt,Nt,this._viewProjMatrix),Nt[2]/Nt[3]}getProjectionData(M){const{overscaledTileID:Bt,aligned:Wt,applyTerrainMatrix:Nt}=M,$t=this._helper.getMercatorTileCoordinates(Bt),Gr=Bt?this.calculatePosMatrix(Bt,Wt,!0):null;let mn;return mn=Bt&&Bt.terrainRttPosMatrix32f&&Nt?Bt.terrainRttPosMatrix32f:Gr||et.aZ(),{mainMatrix:mn,tileMercatorCoords:$t,clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:mn}}isLocationOccluded(M){return!1}getPixelScale(){return 1}getCircleRadiusCorrection(){return 1}getPitchedTextCorrection(M,et,Bt){return 1}transformLightDirection(M){return et.aN(M)}getRayDirectionFromPixel(M){throw new Error("Not implemented.")}projectTileCoordinates(M,Bt,Wt,Nt){const $t=this.calculatePosMatrix(Wt);let Gr;Nt?(Gr=[M,Bt,Nt(M,Bt),1],et.al(Gr,Gr,$t)):(Gr=[M,Bt,0,1],je(Gr,Gr,$t));const mn=Gr[3];return{point:new et.P(Gr[0]/mn,Gr[1]/mn),signedDistanceFromCamera:mn,isOccluded:!1}}populateCache(M){for(const et of M)this.calculatePosMatrix(et)}getMatrixForModel(M,Bt){const Wt=et.Y.fromLngLat(M,Bt),Nt=Wt.meterInMercatorCoordinateUnits(),$t=et.a_();return et.J($t,$t,[Wt.x,Wt.y,Wt.z]),et.aX($t,$t,Math.PI),et.aY($t,$t,Math.PI/2),et.K($t,$t,[-Nt,Nt,Nt]),$t}getProjectionDataForCustomLayer(M=!0){const Bt=new et.S(0,0,0,0,0),Wt=this.getProjectionData({overscaledTileID:Bt,applyGlobeMatrix:M}),Nt=wt(Bt,this.worldSize);et.L(Nt,this._viewProjMatrix,Nt),Wt.tileMercatorCoords=[0,0,1,1];const $t=[et.X,et.X,this.worldSize/this._helper.pixelsPerMeter],Gr=et.a$();return et.K(Gr,Nt,$t),Wt.fallbackMatrix=Gr,Wt.mainMatrix=Gr,Wt}getFastPathSimpleProjectionMatrix(M){return this.calculatePosMatrix(M)}}function zt(){et.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.")}function At(M){if(M.useSlerp)if(M.k<1){const Bt=et.b0(M.startEulerAngles.roll,M.startEulerAngles.pitch,M.startEulerAngles.bearing),Wt=et.b0(M.endEulerAngles.roll,M.endEulerAngles.pitch,M.endEulerAngles.bearing),Nt=new Float64Array(4);et.b1(Nt,Bt,Wt,M.k);const $t=et.b2(Nt);M.tr.setRoll($t.roll),M.tr.setPitch($t.pitch),M.tr.setBearing($t.bearing)}else M.tr.setRoll(M.endEulerAngles.roll),M.tr.setPitch(M.endEulerAngles.pitch),M.tr.setBearing(M.endEulerAngles.bearing);else M.tr.setRoll(et.y.number(M.startEulerAngles.roll,M.endEulerAngles.roll,M.k)),M.tr.setPitch(et.y.number(M.startEulerAngles.pitch,M.endEulerAngles.pitch,M.k)),M.tr.setBearing(et.y.number(M.startEulerAngles.bearing,M.endEulerAngles.bearing,M.k))}function Lt(M,Bt,Wt,Nt,$t){const Gr=$t.padding,mn=xt($t.worldSize,Wt.getNorthWest()),Hn=xt($t.worldSize,Wt.getNorthEast()),so=xt($t.worldSize,Wt.getSouthEast()),uo=xt($t.worldSize,Wt.getSouthWest()),Io=et.aa(-Nt),Po=mn.rotate(Io),To=Hn.rotate(Io),Eo=so.rotate(Io),Ia=uo.rotate(Io),Ba=new et.P(Math.max(Po.x,To.x,Ia.x,Eo.x),Math.max(Po.y,To.y,Ia.y,Eo.y)),Ta=new et.P(Math.min(Po.x,To.x,Ia.x,Eo.x),Math.min(Po.y,To.y,Ia.y,Eo.y)),Va=Ba.sub(Ta),za=($t.width-(Gr.left+Gr.right+Bt.left+Bt.right))/Va.x,Fa=($t.height-(Gr.top+Gr.bottom+Bt.top+Bt.bottom))/Va.y;if(Fa<0||za<0)return void zt();const Ea=Math.min(et.a8($t.scale*Math.min(za,Fa)),M.maxZoom),La=et.P.convert(M.offset),Da=new et.P((Bt.left-Bt.right)/2,(Bt.top-Bt.bottom)/2).rotate(et.aa(Nt)),Ka=La.add(Da).mult($t.scale/et.aG(Ea));return{center:bt($t.worldSize,mn.add(so).div(2).sub(Ka)),zoom:Ea,bearing:Nt}}class kt{get useGlobeControls(){return!1}handlePanInertia(M,et){return{easingOffset:M,easingCenter:et.center}}handleMapControlsRollPitchBearingZoom(M,et){M.bearingDelta&&et.setBearing(et.bearing+M.bearingDelta),M.pitchDelta&&et.setPitch(et.pitch+M.pitchDelta),M.rollDelta&&et.setRoll(et.roll+M.rollDelta),M.zoomDelta&&et.setZoom(et.zoom+M.zoomDelta)}handleMapControlsPan(M,et,Bt){M.around.distSqr(et.centerPoint)<.01||et.setLocationAtPoint(Bt,M.around)}cameraForBoxAndBearing(M,et,Bt,Wt,Nt){return Lt(M,et,Bt,Wt,Nt)}handleJumpToCenterZoom(M,Bt){M.zoom!==(void 0!==Bt.zoom?+Bt.zoom:M.zoom)&&M.setZoom(+Bt.zoom),void 0!==Bt.center&&M.setCenter(et.N.convert(Bt.center))}handleEaseTo(M,Bt){const Wt=M.zoom,Nt=M.padding,$t={roll:M.roll,pitch:M.pitch,bearing:M.bearing},Gr={roll:void 0===Bt.roll?M.roll:Bt.roll,pitch:void 0===Bt.pitch?M.pitch:Bt.pitch,bearing:void 0===Bt.bearing?M.bearing:Bt.bearing},mn=void 0!==Bt.zoom,Hn=!M.isPaddingEqual(Bt.padding);let so=!1;const uo=mn?+Bt.zoom:M.zoom;let Io=M.centerPoint.add(Bt.offsetAsPoint);const Po=M.screenPointToLocation(Io),{center:To,zoom:Eo}=M.getConstrained(et.N.convert(Bt.center||Po),null!=uo?uo:Wt);Ct(M,To);const Ia=xt(M.worldSize,Po),Ba=xt(M.worldSize,To).sub(Ia),Ta=et.aG(Eo-Wt);return so=Eo!==Wt,{easeFunc:mn=>{if(so&&M.setZoom(et.y.number(Wt,Eo,mn)),et.b3($t,Gr)||At({startEulerAngles:$t,endEulerAngles:Gr,tr:M,k:mn,useSlerp:$t.roll!=Gr.roll}),Hn&&(M.interpolatePadding(Nt,Bt.padding,mn),Io=M.centerPoint.add(Bt.offsetAsPoint)),Bt.around)M.setLocationAtPoint(Bt.around,Bt.aroundPoint);else{const Bt=et.aG(M.zoom-Wt),Nt=Eo>Wt?Math.min(2,Ta):Math.max(.5,Ta),$t=Math.pow(Nt,1-mn),Gr=bt(M.worldSize,Ia.add(Ba.mult(mn*$t)).mult(Bt));M.setLocationAtPoint(M.renderWorldCopies?Gr.wrap():Gr,Io)}},isZooming:so,elevationCenter:To}}handleFlyTo(M,Bt){const Wt=void 0!==Bt.zoom,Nt=M.zoom,$t=M.getConstrained(et.N.convert(Bt.center||Bt.locationAtOffset),Wt?+Bt.zoom:Nt),Gr=$t.center,mn=$t.zoom;Ct(M,Gr);const Hn=xt(M.worldSize,Bt.locationAtOffset),so=xt(M.worldSize,Gr).sub(Hn),uo=so.mag(),Io=et.aG(mn-Nt);let Po;if(void 0!==Bt.minZoom){const Wt=Math.min(+Bt.minZoom,Nt,mn),$t=M.getConstrained(Gr,Wt).zoom;Po=et.aG($t-Nt)}return{easeFunc:(Bt,Wt,$t,uo)=>{M.setZoom(1===Bt?mn:Nt+et.a8(Wt));const Io=1===Bt?Gr:bt(M.worldSize,Hn.add(so.mult($t)).mult(Wt));M.setLocationAtPoint(M.renderWorldCopies?Io.wrap():Io,uo)},scaleOfZoom:Io,targetCenter:Gr,scaleOfMinZoom:Po,pixelPathLength:uo}}}class Ft{constructor(M,et,Bt){this.blendFunction=M,this.blendColor=et,this.mask=Bt}}Ft.Replace=[1,0],Ft.disabled=new Ft(Ft.Replace,et.b4.transparent,[!1,!1,!1,!1]),Ft.unblended=new Ft(Ft.Replace,et.b4.transparent,[!0,!0,!0,!0]),Ft.alphaBlended=new Ft([1,771],et.b4.transparent,[!0,!0,!0,!0]);const Dl=2305;class jt{constructor(M,et,Bt){this.enable=M,this.mode=et,this.frontFace=Bt}}jt.disabled=new jt(!1,1029,Dl),jt.backCCW=new jt(!0,1029,Dl),jt.frontCCW=new jt(!0,1028,Dl);class Ot{constructor(M,et,Bt){this.func=M,this.mask=et,this.range=Bt}}Ot.ReadOnly=!1,Ot.ReadWrite=!0,Ot.disabled=new Ot(519,Ot.ReadOnly,[0,1]);const Nl=7680;class Zt{constructor(M,et,Bt,Wt,Nt,$t){this.test=M,this.ref=et,this.mask=Bt,this.fail=Wt,this.depthFail=Nt,this.pass=$t}}Zt.disabled=new Zt({func:519,mask:0},0,0,Nl,Nl,Nl);const Yl=new WeakMap;function Ut(M){var et;if(Yl.has(M))return Yl.get(M);{const Bt=null===(et=M.getParameter(M.VERSION))||void 0===et?void 0:et.startsWith("WebGL 2.0");return Yl.set(M,Bt),Bt}}class Vt{get awaitingQuery(){return!!this._readbackQueue}constructor(M){this._readbackWaitFrames=4,this._measureWaitFrames=6,this._texWidth=1,this._texHeight=1,this._measuredError=0,this._updateCount=0,this._lastReadbackFrame=-1e3,this._readbackQueue=null,this._cachedRenderContext=M;const Bt=M.context,Wt=Bt.gl;this._texFormat=Wt.RGBA,this._texType=Wt.UNSIGNED_BYTE;const Nt=new et.aC;Nt.emplaceBack(-1,-1),Nt.emplaceBack(2,-1),Nt.emplaceBack(-1,2);const $t=new et.aE;$t.emplaceBack(0,1,2),this._fullscreenTriangle=new pt(Bt.createVertexBuffer(Nt,El.members),Bt.createIndexBuffer($t),et.aD.simpleSegment(0,0,Nt.length,$t.length)),this._resultBuffer=new Uint8Array(4),Bt.activeTexture.set(Wt.TEXTURE1);const Gr=Wt.createTexture();Wt.bindTexture(Wt.TEXTURE_2D,Gr),Wt.texParameteri(Wt.TEXTURE_2D,Wt.TEXTURE_WRAP_S,Wt.CLAMP_TO_EDGE),Wt.texParameteri(Wt.TEXTURE_2D,Wt.TEXTURE_WRAP_T,Wt.CLAMP_TO_EDGE),Wt.texParameteri(Wt.TEXTURE_2D,Wt.TEXTURE_MIN_FILTER,Wt.NEAREST),Wt.texParameteri(Wt.TEXTURE_2D,Wt.TEXTURE_MAG_FILTER,Wt.NEAREST),Wt.texImage2D(Wt.TEXTURE_2D,0,this._texFormat,this._texWidth,this._texHeight,0,this._texFormat,this._texType,null),this._fbo=Bt.createFramebuffer(this._texWidth,this._texHeight,!1,!1),this._fbo.colorAttachment.set(Gr),Ut(Wt)&&(this._pbo=Wt.createBuffer(),Wt.bindBuffer(Wt.PIXEL_PACK_BUFFER,this._pbo),Wt.bufferData(Wt.PIXEL_PACK_BUFFER,4,Wt.STREAM_READ),Wt.bindBuffer(Wt.PIXEL_PACK_BUFFER,null))}destroy(){const M=this._cachedRenderContext.context.gl;this._fullscreenTriangle.destroy(),this._fbo.destroy(),M.deleteBuffer(this._pbo),this._fullscreenTriangle=null,this._fbo=null,this._pbo=null,this._resultBuffer=null}updateErrorLoop(M,et){const Bt=this._updateCount;return this._readbackQueue?Bt>=this._readbackQueue.frameNumberIssued+this._readbackWaitFrames&&this._tryReadback():Bt>=this._lastReadbackFrame+this._measureWaitFrames&&this._renderErrorTexture(M,et),this._updateCount++,this._measuredError}_bindFramebuffer(){const M=this._cachedRenderContext.context,et=M.gl;M.activeTexture.set(et.TEXTURE1),et.bindTexture(et.TEXTURE_2D,this._fbo.colorAttachment.get()),M.bindFramebuffer.set(this._fbo.framebuffer)}_renderErrorTexture(M,Bt){const Wt=this._cachedRenderContext.context,Nt=Wt.gl;if(this._bindFramebuffer(),Wt.viewport.set([0,0,this._texWidth,this._texHeight]),Wt.clear({color:et.b4.transparent}),this._cachedRenderContext.useProgram("projectionErrorMeasurement").draw(Wt,Nt.TRIANGLES,Ot.disabled,Zt.disabled,Ft.unblended,jt.disabled,((M,et)=>({u_input:M,u_output_expected:et}))(M,Bt),null,null,"$clipping",this._fullscreenTriangle.vertexBuffer,this._fullscreenTriangle.indexBuffer,this._fullscreenTriangle.segments),this._pbo&&Ut(Nt)){Nt.bindBuffer(Nt.PIXEL_PACK_BUFFER,this._pbo),Nt.readBuffer(Nt.COLOR_ATTACHMENT0),Nt.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,0),Nt.bindBuffer(Nt.PIXEL_PACK_BUFFER,null);const M=Nt.fenceSync(Nt.SYNC_GPU_COMMANDS_COMPLETE,0);Nt.flush(),this._readbackQueue={frameNumberIssued:this._updateCount,sync:M}}else this._readbackQueue={frameNumberIssued:this._updateCount,sync:null}}_tryReadback(){const M=this._cachedRenderContext.context.gl;if(this._pbo&&this._readbackQueue&&Ut(M)){const Bt=M.clientWaitSync(this._readbackQueue.sync,0,0);if(Bt===M.WAIT_FAILED)return et.w("WebGL2 clientWaitSync failed."),this._readbackQueue=null,void(this._lastReadbackFrame=this._updateCount);if(Bt===M.TIMEOUT_EXPIRED)return;M.bindBuffer(M.PIXEL_PACK_BUFFER,this._pbo),M.getBufferSubData(M.PIXEL_PACK_BUFFER,0,this._resultBuffer,0,4),M.bindBuffer(M.PIXEL_PACK_BUFFER,null)}else this._bindFramebuffer(),M.readPixels(0,0,this._texWidth,this._texHeight,this._texFormat,this._texType,this._resultBuffer);this._readbackQueue=null,this._measuredError=Vt._parseRGBA8float(this._resultBuffer),this._lastReadbackFrame=this._updateCount}static _parseRGBA8float(M){let et=0;return et+=M[0]/256,et+=M[1]/65536,et+=M[2]/16777216,M[3]<127&&(et=-et),et/128}}const Ol=et.X/128;function Ht(M,Bt){const Wt=void 0!==M.granularity?Math.max(M.granularity,1):1,Nt=Wt+(M.generateBorders?2:0),$t=Wt+(M.extendToNorthPole||M.generateBorders?1:0)+(M.extendToSouthPole||M.generateBorders?1:0),Gr=Nt+1,mn=$t+1,Hn=M.generateBorders?-1:0,so=M.generateBorders||M.extendToNorthPole?-1:0,uo=Wt+(M.generateBorders?1:0),Io=Wt+(M.generateBorders||M.extendToSouthPole?1:0),Po=Gr*mn,To=Nt*$t*6,Eo=Gr*mn>65536;if(Eo&&"16bit"===Bt)throw new Error("Granularity is too large and meshes would not fit inside 16 bit vertex indices.");const Ia=Eo||"32bit"===Bt,Ba=new Int16Array(2*Po);let Ta=0;for(let Bt=so;Bt<=Io;Bt++)for(let Nt=Hn;Nt<=uo;Nt++){let $t=Nt/Wt*et.X;-1===Nt&&($t=-Ol),Nt===Wt+1&&($t=et.X+Ol);let Gr=Bt/Wt*et.X;-1===Bt&&(Gr=M.extendToNorthPole?et.b6:-Ol),Bt===Wt+1&&(Gr=M.extendToSouthPole?et.b7:et.X+Ol),Ba[Ta++]=$t,Ba[Ta++]=Gr}const Va=Ia?new Uint32Array(To):new Uint16Array(To);let za=0;for(let M=0;M<$t;M++)for(let et=0;et0}get latitudeErrorCorrectionRadians(){return this._verticalPerspectiveProjection.latitudeErrorCorrectionRadians}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return"globe"}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy()}updateGPUdependent(M){this._mercatorProjection.updateGPUdependent(M),this._verticalPerspectiveProjection.updateGPUdependent(M)}getMeshFromTileID(M,et,Bt,Wt,Nt){return this.currentProjection.getMeshFromTileID(M,et,Bt,Wt,Nt)}setProjection(M){this._transitionable.setValue("type",(null==M?void 0:M.type)||"mercator")}updateTransitions(M){this._transitioning=this._transitionable.transitioned(M,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(M){this.properties=this._transitioning.possiblyEvaluate(M)}setErrorQueryLatitudeDegrees(M){this._verticalPerspectiveProjection.setErrorQueryLatitudeDegrees(M),this._mercatorProjection.setErrorQueryLatitudeDegrees(M)}}function Yt(M){const et=ei(M.worldSize,M.center.lat);return 2*Math.PI*et}function Jt(M,Bt,Wt,Nt,$t){const Gr=1/(1<<$t),mn=Bt/et.X*Gr+Nt*Gr,Hn=et.bd((M/et.X*Gr+Wt*Gr)*Math.PI*2+Math.PI,2*Math.PI),so=2*Math.atan(Math.exp(Math.PI-mn*Math.PI*2))-.5*Math.PI,uo=Math.cos(so),Io=new Float64Array(3);return Io[0]=Math.sin(Hn)*uo,Io[1]=Math.sin(so),Io[2]=Math.cos(Hn)*uo,Io}function Qt(M){return function(M,et){const Bt=Math.cos(et),Wt=new Float64Array(3);return Wt[0]=Math.sin(M)*Bt,Wt[1]=Math.sin(et),Wt[2]=Math.cos(M)*Bt,Wt}(M.lng*Math.PI/180,M.lat*Math.PI/180)}function ei(M,et){return M/(2*Math.PI)/Math.cos(et*Math.PI/180)}function ti(M){const Bt=Math.asin(M[1])/Math.PI*180,Wt=Math.sqrt(M[0]*M[0]+M[2]*M[2]);if(Wt>1e-6){const Nt=M[0]/Wt,$t=Math.acos(M[2]/Wt),Gr=(Nt>0?$t:-$t)/Math.PI*180;return new et.N(et.aI(Gr,-180,180),Bt)}return new et.N(0,Bt)}function ii(M){return Math.cos(M*Math.PI/180)}function ri(M,Bt){const Wt=ii(M),Nt=ii(Bt);return et.a8(Nt/Wt)}function oi(M,Bt){const Wt=M.rotate(Bt.bearingInRadians),Nt=Bt.zoom+ri(Bt.center.lat,0),$t=et.b9(1/ii(Bt.center.lat),1/ii(Math.min(Math.abs(Bt.center.lat),60)),et.bc(Nt,7,3,0,1)),Gr=360/Yt({worldSize:Bt.worldSize,center:{lat:Bt.center.lat}});return new et.N(Bt.center.lng-Wt.x*Gr*$t,et.ab(Bt.center.lat+Wt.y*Gr,-et.aF,et.aF))}function si(M){const et=.5*M,Bt=Math.sin(et),Wt=Math.cos(et);return Math.log(Bt+Wt)-Math.log(Wt-Bt)}function ai(M,Bt,Wt,Nt){const $t=M.lat+Wt*Nt;if(Math.abs(Wt)>1){const Gr=(Math.sign(M.lat+Wt)!==Math.sign(M.lat)?-Math.abs(M.lat):Math.abs(M.lat))*Math.PI/180,mn=Math.abs(M.lat+Wt)*Math.PI/180,Hn=si(Gr+Nt*(mn-Gr)),so=si(Gr),uo=si(mn);return new et.N(M.lng+Bt*((Hn-so)/(uo-so)),$t)}return new et.N(M.lng+Bt*Nt,$t)}class ni{constructor(M){this._cachePrevious=new Map,this._cache=new Map,this._hadAnyChanges=!1,this._aabbFactory=M}recalculateCache(){if(!this._hadAnyChanges)return;const M=this._cachePrevious;this._cachePrevious=this._cache,this._cache=M,this._cache.clear(),this._hadAnyChanges=!1}getTileAABB(M,et,Bt,Wt){const Nt=`${M.z}_${M.x}_${M.y}`,$t=this._cache.get(Nt);if($t)return $t;const Gr=this._cachePrevious.get(Nt);if(Gr)return this._cache.set(Nt,Gr),Gr;const mn=this._aabbFactory(M,et,Bt,Wt);return this._cache.set(Nt,mn),this._hadAnyChanges=!0,mn}}function li(M,et,Bt){const Wt=M-et;return Wt<0?-Wt:Math.max(0,Wt-Bt)}function ci(M,et,Bt,Wt,Nt){const $t=M-Bt;let Gr;return Gr=$t<0?Math.min(-$t,1+$t-Nt):$t>1?Math.min(Math.max($t-Nt,0),1-$t):0,Math.max(Gr,li(et,Wt,Nt))}class hi{constructor(){this._aabbCache=new ni(this._computeTileAABB)}recalculateCache(){this._aabbCache.recalculateCache()}distanceToTile2d(M,et,Bt,Wt){const Nt=1<4}allowWorldCopies(){return!1}getTileAABB(M,et,Bt,Wt){return this._aabbCache.getTileAABB(M,et,Bt,Wt)}_computeTileAABB(M,Bt,Wt,Nt){if(M.z<=0)return new Mt([-1,-1,-1],[1,1,1]);if(1===M.z)return new Mt([0===M.x?-1:0,0===M.y?0:-1,-1],[0===M.x?0:1,0===M.y?1:0,1]);{const Bt=[Jt(0,0,M.x,M.y,M.z),Jt(et.X,0,M.x,M.y,M.z),Jt(et.X,et.X,M.x,M.y,M.z),Jt(0,et.X,M.x,M.y,M.z)],Wt=[1,1,1],Nt=[-1,-1,-1];for(const M of Bt)for(let et=0;et<3;et++)Wt[et]=Math.min(Wt[et],M[et]),Nt[et]=Math.max(Nt[et],M[et]);if(0===M.y||M.y===(1<{this._calcMatrices()},getConstrained:(M,et)=>this.getConstrained(M,et)}),this._coveringTilesDetailsProvider=new hi}clone(){const M=new ui;return M.apply(this),M}apply(M,et){this._globeLatitudeErrorCorrectionRadians=et||0,this._helper.apply(M)}get projectionMatrix(){return this._projectionMatrix}get modelViewProjectionMatrix(){return this._globeViewProjMatrixNoCorrection}get inverseProjectionMatrix(){return this._globeProjMatrixInverted}get cameraPosition(){const M=et.bf();return M[0]=this._cameraPosition[0],M[1]=this._cameraPosition[1],M[2]=this._cameraPosition[2],M}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}getProjectionData(M){const{overscaledTileID:et,applyGlobeMatrix:Bt}=M,Wt=this._helper.getMercatorTileCoordinates(et);return{mainMatrix:this._globeViewProjMatrix32f,tileMercatorCoords:Wt,clippingPlane:this._cachedClippingPlane,projectionTransition:Bt?1:0,fallbackMatrix:this._globeViewProjMatrix32f}}_computeClippingPlane(M){const Bt=this.pitchInRadians,Wt=this.cameraToCenterDistance/M,Nt=Math.sin(Bt)*Wt,$t=Math.cos(Bt)*Wt+1,Gr=1/Math.sqrt(Nt*Nt+$t*$t)*1;let mn=-Nt,Hn=$t;const so=Math.sqrt(mn*mn+Hn*Hn);mn/=so,Hn/=so;const uo=[0,mn,Hn];return et.bg(uo,uo,[0,0,0],-this.bearingInRadians),et.bh(uo,uo,[0,0,0],-1*this.center.lat*Math.PI/180),et.bi(uo,uo,[0,0,0],this.center.lng*Math.PI/180),et.aL(uo,uo,.25),[...uo,.25*-Gr]}isLocationOccluded(M){return!this.isSurfacePointVisible(Qt(M))}transformLightDirection(M){const Bt=this._helper._center.lng*Math.PI/180,Wt=this._helper._center.lat*Math.PI/180,Nt=Math.cos(Wt),$t=[Math.sin(Bt)*Nt,Math.sin(Wt),Math.cos(Bt)*Nt],Gr=[$t[2],0,-$t[0]],mn=[0,0,0];et.aR(mn,Gr,$t),et.aQ(Gr,Gr),et.aQ(mn,mn);const Hn=[0,0,0];return et.aQ(Hn,[Gr[0]*M[0]+mn[0]*M[1]+$t[0]*M[2],Gr[1]*M[0]+mn[1]*M[1]+$t[1]*M[2],Gr[2]*M[0]+mn[2]*M[1]+$t[2]*M[2]]),Hn}getPixelScale(){return 1/Math.cos(this._helper._center.lat*Math.PI/180)}getCircleRadiusCorrection(){return Math.cos(this._helper._center.lat*Math.PI/180)}getPitchedTextCorrection(M,Bt,Wt){const Nt=function(M,Bt,Wt){const Nt=1/(1<$t&&($t=Bt),Wtmn&&(mn=Wt)}const uo=[so.lng+Gr,so.lat+Hn,so.lng+$t,so.lat+mn];return this.isSurfacePointOnScreen([0,1,0])&&(uo[3]=90,uo[0]=-180,uo[2]=180),this.isSurfacePointOnScreen([0,-1,0])&&(uo[1]=-90,uo[0]=-180,uo[2]=180),new V(uo)}getConstrained(M,Bt){const Wt=et.ab(M.lat,-et.aF,et.aF),Nt=et.ab(+Bt,this.minZoom+ri(0,Wt),this.maxZoom);return{center:new et.N(M.lng,Wt),zoom:Nt}}calculateCenterFromCameraLngLatAlt(M,et,Bt,Wt){return this._helper.calculateCenterFromCameraLngLatAlt(M,et,Bt,Wt)}setLocationAtPoint(M,Bt){const Wt=Qt(this.unprojectScreenPoint(Bt)),Nt=Qt(M),$t=et.bf();et.bl($t);const Gr=et.bf();et.bi(Gr,Wt,$t,-this.center.lng*Math.PI/180),et.bh(Gr,Gr,$t,this.center.lat*Math.PI/180);const mn=Nt[0]*Nt[0]+Nt[2]*Nt[2],Hn=Gr[0]*Gr[0];if(mn=-Ta&&Eo<=Ta,za=Ba>=-Ta&&Ba<=Ta;let Fa,Ea;if(Va&&za){const M=this.center.lng*Math.PI/180,Bt=this.center.lat*Math.PI/180;et.bp(Io,M)+et.bp(Eo,Bt)=0}isSurfacePointOnScreen(M){if(!this.isSurfacePointVisible(M))return!1;const Bt=et.be();return et.al(Bt,[...M,1],this._globeViewProjMatrixNoCorrection),Bt[0]/=Bt[3],Bt[1]/=Bt[3],Bt[2]/=Bt[3],Bt[0]>-1&&Bt[0]<1&&Bt[1]>-1&&Bt[1]<1&&Bt[2]>-1&&Bt[2]<1}rayPlanetIntersection(M,Bt){const Wt=et.aS(M,Bt),Nt=et.bf(),$t=et.bf();et.aL($t,Bt,Wt),et.aP(Nt,M,$t);const Gr=1-et.aS(Nt,Nt);if(Gr<0)return null;const mn=et.aS(M,M)-1,Hn=-Wt+(Wt<0?1:-1)*Math.sqrt(Gr),so=mn/Hn,uo=Hn;return{tMin:Math.min(so,uo),tMax:Math.max(so,uo)}}unprojectScreenPoint(M){const Bt=this._cameraPosition,Wt=this.getRayDirectionFromPixel(M),Nt=this.rayPlanetIntersection(Bt,Wt);if(Nt){const M=et.bf();et.aM(M,Bt,[Wt[0]*Nt.tMin,Wt[1]*Nt.tMin,Wt[2]*Nt.tMin]);const $t=et.bf();return et.aQ($t,M),ti($t)}const $t=this._cachedClippingPlane[0]*Wt[0]+this._cachedClippingPlane[1]*Wt[1]+this._cachedClippingPlane[2]*Wt[2],Gr=-et.bn(this._cachedClippingPlane,Bt)/$t,mn=et.bf();if(Gr>0)et.aM(mn,Bt,[Wt[0]*Gr,Wt[1]*Gr,Wt[2]*Gr]);else{const M=et.bf();et.aM(M,Bt,[2*Wt[0],2*Wt[1],2*Wt[2]]);const Nt=et.bn(this._cachedClippingPlane,M);et.aP(mn,M,[this._cachedClippingPlane[0]*Nt,this._cachedClippingPlane[1]*Nt,this._cachedClippingPlane[2]*Nt])}const Hn=et.bf();return et.aQ(Hn,mn),ti(Hn)}getMatrixForModel(M,Bt){const Wt=et.N.convert(M),Nt=1/et.bo,$t=et.a_();return et.bj($t,$t,Wt.lng/180*Math.PI),et.aY($t,$t,-Wt.lat/180*Math.PI),et.J($t,$t,[0,0,1+Bt/et.bo]),et.aY($t,$t,.5*Math.PI),et.K($t,$t,[Nt,Nt,Nt]),$t}getProjectionDataForCustomLayer(M=!0){const Bt=this.getProjectionData({overscaledTileID:new et.S(0,0,0,0,0),applyGlobeMatrix:M});return Bt.tileMercatorCoords=[0,0,1,1],Bt}getFastPathSimpleProjectionMatrix(M){}}class di{get pixelsToClipSpaceMatrix(){return this._helper.pixelsToClipSpaceMatrix}get clipSpaceToPixelsMatrix(){return this._helper.clipSpaceToPixelsMatrix}get pixelsToGLUnits(){return this._helper.pixelsToGLUnits}get centerOffset(){return this._helper.centerOffset}get size(){return this._helper.size}get rotationMatrix(){return this._helper.rotationMatrix}get centerPoint(){return this._helper.centerPoint}get pixelsPerMeter(){return this._helper.pixelsPerMeter}setMinZoom(M){this._helper.setMinZoom(M)}setMaxZoom(M){this._helper.setMaxZoom(M)}setMinPitch(M){this._helper.setMinPitch(M)}setMaxPitch(M){this._helper.setMaxPitch(M)}setRenderWorldCopies(M){this._helper.setRenderWorldCopies(M)}setBearing(M){this._helper.setBearing(M)}setPitch(M){this._helper.setPitch(M)}setRoll(M){this._helper.setRoll(M)}setFov(M){this._helper.setFov(M)}setZoom(M){this._helper.setZoom(M)}setCenter(M){this._helper.setCenter(M)}setElevation(M){this._helper.setElevation(M)}setMinElevationForCurrentTile(M){this._helper.setMinElevationForCurrentTile(M)}setPadding(M){this._helper.setPadding(M)}interpolatePadding(M,et,Bt){return this._helper.interpolatePadding(M,et,Bt)}isPaddingEqual(M){return this._helper.isPaddingEqual(M)}resize(M,et,Bt=!0){this._helper.resize(M,et,Bt)}getMaxBounds(){return this._helper.getMaxBounds()}setMaxBounds(M){this._helper.setMaxBounds(M)}overrideNearFarZ(M,et){this._helper.overrideNearFarZ(M,et)}clearNearFarZOverride(){this._helper.clearNearFarZOverride()}getCameraQueryGeometry(M){return this._helper.getCameraQueryGeometry(this.getCameraPoint(),M)}get tileSize(){return this._helper.tileSize}get tileZoom(){return this._helper.tileZoom}get scale(){return this._helper.scale}get worldSize(){return this._helper.worldSize}get width(){return this._helper.width}get height(){return this._helper.height}get lngRange(){return this._helper.lngRange}get latRange(){return this._helper.latRange}get minZoom(){return this._helper.minZoom}get maxZoom(){return this._helper.maxZoom}get zoom(){return this._helper.zoom}get center(){return this._helper.center}get minPitch(){return this._helper.minPitch}get maxPitch(){return this._helper.maxPitch}get pitch(){return this._helper.pitch}get pitchInRadians(){return this._helper.pitchInRadians}get roll(){return this._helper.roll}get rollInRadians(){return this._helper.rollInRadians}get bearing(){return this._helper.bearing}get bearingInRadians(){return this._helper.bearingInRadians}get fov(){return this._helper.fov}get fovInRadians(){return this._helper.fovInRadians}get elevation(){return this._helper.elevation}get minElevationForCurrentTile(){return this._helper.minElevationForCurrentTile}get padding(){return this._helper.padding}get unmodified(){return this._helper.unmodified}get renderWorldCopies(){return this._helper.renderWorldCopies}get cameraToCenterDistance(){return this._helper.cameraToCenterDistance}get nearZ(){return this._helper.nearZ}get farZ(){return this._helper.farZ}get autoCalculateNearFarZ(){return this._helper.autoCalculateNearFarZ}get isGlobeRendering(){return this._globeness>0}setTransitionState(M,et){this._globeness=M,this._globeLatitudeErrorCorrectionRadians=et,this._calcMatrices(),this._verticalPerspectiveTransform.getCoveringTilesDetailsProvider().recalculateCache(),this._mercatorTransform.getCoveringTilesDetailsProvider().recalculateCache()}get currentTransform(){return this.isGlobeRendering?this._verticalPerspectiveTransform:this._mercatorTransform}constructor(){this._globeLatitudeErrorCorrectionRadians=0,this._globeness=1,this._helper=new Et({calcMatrices:()=>{this._calcMatrices()},getConstrained:(M,et)=>this.getConstrained(M,et)}),this._globeness=1,this._mercatorTransform=new Dt,this._verticalPerspectiveTransform=new ui}clone(){const M=new di;return M._globeness=this._globeness,M._globeLatitudeErrorCorrectionRadians=this._globeLatitudeErrorCorrectionRadians,M.apply(this),M}apply(M){this._helper.apply(M),this._mercatorTransform.apply(this),this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians)}get projectionMatrix(){return this.currentTransform.projectionMatrix}get modelViewProjectionMatrix(){return this.currentTransform.modelViewProjectionMatrix}get inverseProjectionMatrix(){return this.currentTransform.inverseProjectionMatrix}get cameraPosition(){return this.currentTransform.cameraPosition}getProjectionData(M){const et=this._mercatorTransform.getProjectionData(M),Bt=this._verticalPerspectiveTransform.getProjectionData(M);return{mainMatrix:this.isGlobeRendering?Bt.mainMatrix:et.mainMatrix,clippingPlane:Bt.clippingPlane,tileMercatorCoords:Bt.tileMercatorCoords,projectionTransition:M.applyGlobeMatrix?this._globeness:0,fallbackMatrix:et.fallbackMatrix}}isLocationOccluded(M){return this.currentTransform.isLocationOccluded(M)}transformLightDirection(M){return this.currentTransform.transformLightDirection(M)}getPixelScale(){return et.b9(this._mercatorTransform.getPixelScale(),this._verticalPerspectiveTransform.getPixelScale(),this._globeness)}getCircleRadiusCorrection(){return et.b9(this._mercatorTransform.getCircleRadiusCorrection(),this._verticalPerspectiveTransform.getCircleRadiusCorrection(),this._globeness)}getPitchedTextCorrection(M,Bt,Wt){const Nt=this._mercatorTransform.getPitchedTextCorrection(M,Bt,Wt),$t=this._verticalPerspectiveTransform.getPitchedTextCorrection(M,Bt,Wt);return et.b9(Nt,$t,this._globeness)}projectTileCoordinates(M,et,Bt,Wt){return this.currentTransform.projectTileCoordinates(M,et,Bt,Wt)}_calcMatrices(){this._helper._width&&this._helper._height&&(this._verticalPerspectiveTransform.apply(this,this._globeLatitudeErrorCorrectionRadians),this._helper._nearZ=this._verticalPerspectiveTransform.nearZ,this._helper._farZ=this._verticalPerspectiveTransform.farZ,this._mercatorTransform.apply(this,!0,this.isGlobeRendering),this._helper._nearZ=this._mercatorTransform.nearZ,this._helper._farZ=this._mercatorTransform.farZ)}calculateFogMatrix(M){return this.currentTransform.calculateFogMatrix(M)}getVisibleUnwrappedCoordinates(M){return this.currentTransform.getVisibleUnwrappedCoordinates(M)}getCameraFrustum(){return this.currentTransform.getCameraFrustum()}getClippingPlane(){return this.currentTransform.getClippingPlane()}getCoveringTilesDetailsProvider(){return this.currentTransform.getCoveringTilesDetailsProvider()}recalculateZoomAndCenter(M){this._mercatorTransform.recalculateZoomAndCenter(M),this._verticalPerspectiveTransform.recalculateZoomAndCenter(M)}maxPitchScaleFactor(){return this._mercatorTransform.maxPitchScaleFactor()}getCameraPoint(){return this._helper.getCameraPoint()}getCameraAltitude(){return this._helper.getCameraAltitude()}getCameraLngLat(){return this._helper.getCameraLngLat()}lngLatToCameraDepth(M,et){return this.currentTransform.lngLatToCameraDepth(M,et)}populateCache(M){this._mercatorTransform.populateCache(M),this._verticalPerspectiveTransform.populateCache(M)}getBounds(){return this.currentTransform.getBounds()}getConstrained(M,et){return this.currentTransform.getConstrained(M,et)}calculateCenterFromCameraLngLatAlt(M,et,Bt,Wt){return this._helper.calculateCenterFromCameraLngLatAlt(M,et,Bt,Wt)}setLocationAtPoint(M,et){if(!this.isGlobeRendering)return this._mercatorTransform.setLocationAtPoint(M,et),void this.apply(this._mercatorTransform);this._verticalPerspectiveTransform.setLocationAtPoint(M,et),this.apply(this._verticalPerspectiveTransform)}locationToScreenPoint(M,et){return this.currentTransform.locationToScreenPoint(M,et)}screenPointToMercatorCoordinate(M,et){return this.currentTransform.screenPointToMercatorCoordinate(M,et)}screenPointToLocation(M,et){return this.currentTransform.screenPointToLocation(M,et)}isPointOnMapSurface(M,et){return this.currentTransform.isPointOnMapSurface(M,et)}getRayDirectionFromPixel(M){return this._verticalPerspectiveTransform.getRayDirectionFromPixel(M)}getMatrixForModel(M,et){return this.currentTransform.getMatrixForModel(M,et)}getProjectionDataForCustomLayer(M=!0){const et=this._mercatorTransform.getProjectionDataForCustomLayer(M);if(!this.isGlobeRendering)return et;const Bt=this._verticalPerspectiveTransform.getProjectionDataForCustomLayer(M);return Bt.fallbackMatrix=et.mainMatrix,Bt}getFastPathSimpleProjectionMatrix(M){return this.currentTransform.getFastPathSimpleProjectionMatrix(M)}}class _i{get useGlobeControls(){return!0}handlePanInertia(M,Bt){const Wt=oi(M,Bt);return Math.abs(Wt.lng-Bt.center.lng)>180&&(Wt.lng=Bt.center.lng+179.5*Math.sign(Wt.lng-Bt.center.lng)),{easingCenter:Wt,easingOffset:new et.P(0,0)}}handleMapControlsRollPitchBearingZoom(M,Bt){const Wt=M.around,Nt=Bt.screenPointToLocation(Wt);M.bearingDelta&&Bt.setBearing(Bt.bearing+M.bearingDelta),M.pitchDelta&&Bt.setPitch(Bt.pitch+M.pitchDelta),M.rollDelta&&Bt.setRoll(Bt.roll+M.rollDelta);const $t=Bt.zoom;M.zoomDelta&&Bt.setZoom(Bt.zoom+M.zoomDelta);const Gr=Bt.zoom-$t;if(0===Gr)return;const mn=et.bk(Bt.center.lng,Nt.lng),Hn=mn/(Math.abs(mn/180)+1),so=et.bk(Bt.center.lat,Nt.lat),uo=Bt.getRayDirectionFromPixel(Wt),Io=Bt.cameraPosition,Po=-1*et.aS(Io,uo),To=et.bf();et.aM(To,Io,[uo[0]*Po,uo[1]*Po,uo[2]*Po]);const Eo=et.bq(To)-1,Ia=Math.exp(.5*-Math.max(Eo-.3,0)),Ba=ei(Bt.worldSize,Bt.center.lat)/Math.min(Bt.width,Bt.height),Ta=et.bc(Ba,.9,.5,1,.25),Va=(1-et.aG(-Gr))*Math.min(Ia,Ta),za=Bt.center.lat,Fa=Bt.zoom,Ea=new et.N(Bt.center.lng+Hn*Va,et.ab(Bt.center.lat+so*Va,-et.aF,et.aF));Bt.setLocationAtPoint(Nt,Wt);const La=Bt.center,Da=et.bc(Math.abs(mn),45,85,0,1),Ka=et.bc(Ba,.75,.35,0,1),Oa=Math.pow(Math.max(Da,Ka),.25),$a=et.bk(La.lng,Ea.lng),Al=et.bk(La.lat,Ea.lat);Bt.setCenter(new et.N(La.lng+$a*Oa,La.lat+Al*Oa).wrap()),Bt.setZoom(Fa+ri(za,Bt.center.lat))}handleMapControlsPan(M,et,Bt){if(!M.panDelta)return;const Wt=et.center.lat,Nt=et.zoom;et.setCenter(oi(M.panDelta,et).wrap()),et.setZoom(Nt+ri(Wt,et.center.lat))}cameraForBoxAndBearing(M,Bt,Wt,Nt,$t){const Gr=Lt(M,Bt,Wt,Nt,$t),mn=Bt.left/$t.width*2-1,Hn=($t.width-Bt.right)/$t.width*2-1,so=Bt.top/$t.height*-2+1,uo=($t.height-Bt.bottom)/$t.height*-2+1,Io=et.bk(Wt.getWest(),Wt.getEast())<0,Po=Io?Wt.getEast():Wt.getWest(),To=Io?Wt.getWest():Wt.getEast(),Eo=Math.max(Wt.getNorth(),Wt.getSouth()),Ia=Math.min(Wt.getNorth(),Wt.getSouth()),Ba=Po+.5*et.bk(Po,To),Ta=Eo+.5*et.bk(Eo,Ia),Va=$t.clone();Va.setCenter(Gr.center),Va.setBearing(Gr.bearing),Va.setPitch(0),Va.setRoll(0),Va.setZoom(Gr.zoom);const za=Va.modelViewProjectionMatrix,Fa=[Qt(Wt.getNorthWest()),Qt(Wt.getNorthEast()),Qt(Wt.getSouthWest()),Qt(Wt.getSouthEast()),Qt(new et.N(To,Ta)),Qt(new et.N(Po,Ta)),Qt(new et.N(Ba,Eo)),Qt(new et.N(Ba,Ia))],Ea=Qt(Gr.center);let La=Number.POSITIVE_INFINITY;for(const M of Fa)mn<0&&(La=_i.getLesserNonNegativeNonNull(La,_i.solveVectorScale(M,Ea,za,"x",mn))),Hn>0&&(La=_i.getLesserNonNegativeNonNull(La,_i.solveVectorScale(M,Ea,za,"x",Hn))),so>0&&(La=_i.getLesserNonNegativeNonNull(La,_i.solveVectorScale(M,Ea,za,"y",so))),uo<0&&(La=_i.getLesserNonNegativeNonNull(La,_i.solveVectorScale(M,Ea,za,"y",uo)));if(Number.isFinite(La)&&0!==La)return Gr.zoom=Va.zoom+et.a8(La),Gr;zt()}handleJumpToCenterZoom(M,Bt){const Wt=M.center.lat,Nt=M.getConstrained(Bt.center?et.N.convert(Bt.center):M.center,M.zoom).center;M.setCenter(Nt.wrap());const $t=void 0!==Bt.zoom?+Bt.zoom:M.zoom+ri(Wt,Nt.lat);M.zoom!==$t&&M.setZoom($t)}handleEaseTo(M,Bt){const Wt=M.zoom,Nt=M.center,$t=M.padding,Gr={roll:M.roll,pitch:M.pitch,bearing:M.bearing},mn={roll:void 0===Bt.roll?M.roll:Bt.roll,pitch:void 0===Bt.pitch?M.pitch:Bt.pitch,bearing:void 0===Bt.bearing?M.bearing:Bt.bearing},Hn=void 0!==Bt.zoom,so=!M.isPaddingEqual(Bt.padding);let uo=!1;const Io=Bt.center?et.N.convert(Bt.center):Nt,Po=M.getConstrained(Io,Wt).center;Ct(M,Po);const To=M.clone();To.setCenter(Po),To.setZoom(Hn?+Bt.zoom:Wt+ri(Nt.lat,Io.lat)),To.setBearing(Bt.bearing);const Eo=new et.P(et.ab(M.centerPoint.x+Bt.offsetAsPoint.x,0,M.width),et.ab(M.centerPoint.y+Bt.offsetAsPoint.y,0,M.height));To.setLocationAtPoint(Po,Eo);const Ia=(Bt.offset&&Bt.offsetAsPoint.mag())>0?To.center:Po,Ba=Hn?+Bt.zoom:Wt+ri(Nt.lat,Ia.lat),Ta=Wt+ri(Nt.lat,0),Va=Ba+ri(Ia.lat,0),za=et.bk(Nt.lng,Ia.lng),Fa=et.bk(Nt.lat,Ia.lat),Ea=et.aG(Va-Ta);return uo=Ba!==Wt,{easeFunc:Wt=>{if(et.b3(Gr,mn)||At({startEulerAngles:Gr,endEulerAngles:mn,tr:M,k:Wt,useSlerp:Gr.roll!=mn.roll}),so&&M.interpolatePadding($t,Bt.padding,Wt),Bt.around)et.w("Easing around a point is not supported under globe projection."),M.setLocationAtPoint(Bt.around,Bt.aroundPoint);else{const et=Va>Ta?Math.min(2,Ea):Math.max(.5,Ea),Bt=Math.pow(et,1-Wt),$t=ai(Nt,za,Fa,Wt*Bt);M.setCenter($t.wrap())}if(uo){const Bt=et.y.number(Ta,Va,Wt)+ri(0,M.center.lat);M.setZoom(Bt)}},isZooming:uo,elevationCenter:Ia}}handleFlyTo(M,Bt){const Wt=void 0!==Bt.zoom,Nt=M.center,$t=M.zoom,Gr=!M.isPaddingEqual(Bt.padding),mn=M.getConstrained(et.N.convert(Bt.center||Bt.locationAtOffset),$t).center,Hn=Wt?+Bt.zoom:M.zoom+ri(M.center.lat,mn.lat),so=M.clone();so.setCenter(mn),Gr&&so.setPadding(Bt.padding),so.setZoom(Hn),so.setBearing(Bt.bearing);const uo=new et.P(et.ab(M.centerPoint.x+Bt.offsetAsPoint.x,0,M.width),et.ab(M.centerPoint.y+Bt.offsetAsPoint.y,0,M.height));so.setLocationAtPoint(mn,uo);const Io=so.center;Ct(M,Io);const Po=function(M,Bt,Wt){const Nt=Qt(Bt),$t=Qt(Wt),Gr=et.aS(Nt,$t),mn=Math.acos(Gr),Hn=Yt(M);return mn/(2*Math.PI)*Hn}(M,Nt,Io),To=$t+ri(Nt.lat,0),Eo=Hn+ri(Io.lat,0),Ia=et.aG(Eo-To);let Ba;if("number"==typeof Bt.minZoom){const Wt=+Bt.minZoom+ri(Io.lat,0),Nt=Math.min(Wt,To,Eo)+ri(0,Io.lat),$t=M.getConstrained(Io,Nt).zoom+ri(Io.lat,0);Ba=et.aG($t-To)}const Ta=et.bk(Nt.lng,Io.lng),Va=et.bk(Nt.lat,Io.lat);return{easeFunc:(Bt,Wt,$t,Gr)=>{const mn=ai(Nt,Ta,Va,$t),so=1===Bt?Io:mn;M.setCenter(so.wrap());const uo=To+et.a8(Wt);M.setZoom(1===Bt?Hn:uo+ri(0,so.lat))},scaleOfZoom:Ia,targetCenter:Io,scaleOfMinZoom:Ba,pixelPathLength:Po}}static solveVectorScale(M,et,Bt,Wt,Nt){const $t="x"===Wt?[Bt[0],Bt[4],Bt[8],Bt[12]]:[Bt[1],Bt[5],Bt[9],Bt[13]],Gr=[Bt[3],Bt[7],Bt[11],Bt[15]],mn=M[0]*$t[0]+M[1]*$t[1]+M[2]*$t[2],Hn=M[0]*Gr[0]+M[1]*Gr[1]+M[2]*Gr[2],so=et[0]*$t[0]+et[1]*$t[1]+et[2]*$t[2],uo=et[0]*Gr[0]+et[1]*Gr[1]+et[2]*Gr[2];return so+Nt*Hn===mn+Nt*uo||Gr[3]*(mn-so)+$t[3]*(uo-Hn)+mn*uo==so*Hn?null:(so+$t[3]-Nt*uo-Nt*Gr[3])/(so-mn-Nt*uo+Nt*Hn)}static getLesserNonNegativeNonNull(M,et){return null!==et&&et>=0&&etet.t(M,Bt&&Bt.filter((M=>"source.canvas"!==M.identifier))),ql=et.br();class gi extends et.E{constructor(M,Bt={}){super(),this._rtlPluginLoaded=()=>{for(const M in this.sourceCaches){const et=this.sourceCaches[M].getSource().type;"vector"!==et&&"geojson"!==et||this.sourceCaches[M].reload()}},this.map=M,this.dispatcher=new B(F(),M._getMapId()),this.dispatcher.registerMessageHandler("GG",((M,et)=>this.getGlyphs(M,et))),this.dispatcher.registerMessageHandler("GI",((M,et)=>this.getImages(M,et))),this.imageManager=new b,this.imageManager.setEventedParent(this),this.glyphManager=new P(M._requestManager,Bt.localIdeographFontFamily),this.lineAtlas=new R(256,512),this.crossTileSymbolIndex=new ht,this._spritesImagesIds={},this._layers={},this._order=[],this.sourceCaches={},this.zoomHistory=new et.bs,this._loaded=!1,this._availableImages=[],this._resetUpdates(),this.dispatcher.broadcast("SR",et.bt()),oe().on(Fa,this._rtlPluginLoaded),this.on("data",(M=>{if("source"!==M.dataType||"metadata"!==M.sourceDataType)return;const et=this.sourceCaches[M.sourceId];if(!et)return;const Bt=et.getSource();if(Bt&&Bt.vectorLayerIds)for(const M in this._layers){const et=this._layers[M];et.source===Bt.id&&this._validateLayer(et)}}))}loadURL(M,Bt={},Wt){this.fire(new et.k("dataloading",{dataType:"style"})),Bt.validate="boolean"!=typeof Bt.validate||Bt.validate;const Nt=this.map._requestManager.transformRequest(M,"Style");this._loadStyleRequest=new AbortController;const $t=this._loadStyleRequest;et.h(Nt,this._loadStyleRequest).then((M=>{this._loadStyleRequest=null,this._load(M.data,Bt,Wt)})).catch((M=>{this._loadStyleRequest=null,M&&!$t.signal.aborted&&this.fire(new et.j(M))}))}loadJSON(M,Bt={},Wt){this.fire(new et.k("dataloading",{dataType:"style"})),this._frameRequest=new AbortController,$t.frameAsync(this._frameRequest).then((()=>{this._frameRequest=null,Bt.validate=!1!==Bt.validate,this._load(M,Bt,Wt)})).catch((()=>{}))}loadEmpty(){this.fire(new et.k("dataloading",{dataType:"style"})),this._load(ql,{validate:!1})}_load(M,Bt,Wt){var Nt,$t;const Gr=Bt.transformStyle?Bt.transformStyle(Wt,M):M;if(!Bt.validate||!mi(this,et.u(Gr))){this._loaded=!0,this.stylesheet=Gr;for(const M in Gr.sources)this.addSource(M,Gr.sources[M],{validate:!1});Gr.sprite?this._loadSprite(Gr.sprite):this.imageManager.setLoaded(!0),this.glyphManager.setURL(Gr.glyphs),this._createLayers(),this.light=new E(this.stylesheet.light),this._setProjectionInternal((null===(Nt=this.stylesheet.projection)||void 0===Nt?void 0:Nt.type)||"mercator"),this.sky=new S(this.stylesheet.sky),this.map.setTerrain(null!==($t=this.stylesheet.terrain)&&void 0!==$t?$t:null),this.fire(new et.k("data",{dataType:"style"})),this.fire(new et.k("style.load"))}}_createLayers(){const M=et.bu(this.stylesheet.layers);this.dispatcher.broadcast("SL",M),this._order=M.map((M=>M.id)),this._layers={},this._serializedLayers=null;for(const Bt of M){const M=et.bv(Bt);M.setEventedParent(this,{layer:{id:Bt.id}}),this._layers[Bt.id]=M}}_loadSprite(M,Bt=!1,Wt=void 0){let Nt;this.imageManager.setLoaded(!1),this._spriteRequest=new AbortController,function(M,Bt,Wt,Nt){return et._(this,void 0,void 0,(function*(){const Gr=f(M),mn=Wt>1?"@2x":"",Hn={},so={};for(const{id:M,url:Wt}of Gr){const $t=Bt.transformRequest(g(Wt,mn,".json"),"SpriteJSON");Hn[M]=et.h($t,Nt);const Gr=Bt.transformRequest(g(Wt,mn,".png"),"SpriteImage");so[M]=Io.getImage(Gr,Nt)}return yield Promise.all([...Object.values(Hn),...Object.values(so)]),function(M,Bt){return et._(this,void 0,void 0,(function*(){const et={};for(const Wt in M){et[Wt]={};const Nt=$t.getImageCanvasContext((yield Bt[Wt]).data),Gr=(yield M[Wt]).data;for(const M in Gr){const{width:Bt,height:$t,x:mn,y:Hn,sdf:so,pixelRatio:uo,stretchX:Io,stretchY:Po,content:To,textFitWidth:Eo,textFitHeight:Ia}=Gr[M];et[Wt][M]={data:null,pixelRatio:uo,sdf:so,stretchX:Io,stretchY:Po,content:To,textFitWidth:Eo,textFitHeight:Ia,spriteData:{width:Bt,height:$t,x:mn,y:Hn,context:Nt}}}}return et}))}(Hn,so)}))}(M,this.map._requestManager,this.map.getPixelRatio(),this._spriteRequest).then((M=>{if(this._spriteRequest=null,M)for(const et in M){this._spritesImagesIds[et]=[];const Wt=this._spritesImagesIds[et]?this._spritesImagesIds[et].filter((et=>!(et in M))):[];for(const M of Wt)this.imageManager.removeImage(M),this._changedImages[M]=!0;for(const Wt in M[et]){const Nt="default"===et?Wt:`${et}:${Wt}`;this._spritesImagesIds[et].push(Nt),Nt in this.imageManager.images?this.imageManager.updateImage(Nt,M[et][Wt],!1):this.imageManager.addImage(Nt,M[et][Wt]),Bt&&(this._changedImages[Nt]=!0)}}})).catch((M=>{this._spriteRequest=null,Nt=M,this.fire(new et.j(Nt))})).finally((()=>{this.imageManager.setLoaded(!0),this._availableImages=this.imageManager.listImages(),Bt&&(this._changed=!0),this.dispatcher.broadcast("SI",this._availableImages),this.fire(new et.k("data",{dataType:"style"})),Wt&&Wt(Nt)}))}_unloadSprite(){for(const M of Object.values(this._spritesImagesIds).flat())this.imageManager.removeImage(M),this._changedImages[M]=!0;this._spritesImagesIds={},this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new et.k("data",{dataType:"style"}))}_validateLayer(M){const Bt=this.sourceCaches[M.source];if(!Bt)return;const Wt=M.sourceLayer;if(!Wt)return;const Nt=Bt.getSource();("geojson"===Nt.type||Nt.vectorLayerIds&&-1===Nt.vectorLayerIds.indexOf(Wt))&&this.fire(new et.j(new Error(`Source layer "${Wt}" does not exist on source "${Nt.id}" as specified by style layer "${M.id}".`)))}loaded(){if(!this._loaded)return!1;if(Object.keys(this._updatedSources).length)return!1;for(const M in this.sourceCaches)if(!this.sourceCaches[M].loaded())return!1;return!!this.imageManager.isLoaded()}_serializeByIds(M,Bt=!1){const Wt=this._serializedAllLayers();if(!M||0===M.length)return Object.values(Bt?et.bw(Wt):Wt);const Nt=[];for(const $t of M)if(Wt[$t]){const M=Bt?et.bw(Wt[$t]):Wt[$t];Nt.push(M)}return Nt}_serializedAllLayers(){let M=this._serializedLayers;if(M)return M;M=this._serializedLayers={};const et=Object.keys(this._layers);for(const Bt of et){const et=this._layers[Bt];"custom"!==et.type&&(M[Bt]=et.serialize())}return M}hasTransitions(){var M,et,Bt;if(null===(M=this.light)||void 0===M?void 0:M.hasTransition())return!0;if(null===(et=this.sky)||void 0===et?void 0:et.hasTransition())return!0;if(null===(Bt=this.projection)||void 0===Bt?void 0:Bt.hasTransition())return!0;for(const M in this.sourceCaches)if(this.sourceCaches[M].hasTransition())return!0;for(const M in this._layers)if(this._layers[M].hasTransition())return!0;return!1}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading.")}update(M){if(!this._loaded)return;const Bt=this._changed;if(Bt){const et=Object.keys(this._updatedLayers),Bt=Object.keys(this._removedLayers);(et.length||Bt.length)&&this._updateWorkerLayers(et,Bt);for(const M in this._updatedSources){const et=this._updatedSources[M];if("reload"===et)this._reloadSource(M);else{if("clear"!==et)throw new Error(`Invalid action ${et}`);this._clearSource(M)}}this._updateTilesForChangedImages(),this._updateTilesForChangedGlyphs();for(const et in this._updatedPaintProps)this._layers[et].updateTransitions(M);this.light.updateTransitions(M),this.sky.updateTransitions(M),this._resetUpdates()}const Wt={};for(const M in this.sourceCaches){const et=this.sourceCaches[M];Wt[M]=et.used,et.used=!1}for(const et of this._order){const Bt=this._layers[et];Bt.recalculate(M,this._availableImages),!Bt.isHidden(M.zoom)&&Bt.source&&(this.sourceCaches[Bt.source].used=!0)}for(const M in Wt){const Bt=this.sourceCaches[M];!!Wt[M]!=!!Bt.used&&Bt.fire(new et.k("data",{sourceDataType:"visibility",dataType:"source",sourceId:M}))}this.light.recalculate(M),this.sky.recalculate(M),this.projection.recalculate(M),this.z=M.zoom,Bt&&this.fire(new et.k("data",{dataType:"style"}))}_updateTilesForChangedImages(){const M=Object.keys(this._changedImages);if(M.length){for(const et in this.sourceCaches)this.sourceCaches[et].reloadTilesForDependencies(["icons","patterns"],M);this._changedImages={}}}_updateTilesForChangedGlyphs(){if(this._glyphsDidChange){for(const M in this.sourceCaches)this.sourceCaches[M].reloadTilesForDependencies(["glyphs"],[""]);this._glyphsDidChange=!1}}_updateWorkerLayers(M,et){this.dispatcher.broadcast("UL",{layers:this._serializeByIds(M,!1),removedIds:et})}_resetUpdates(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSources={},this._updatedPaintProps={},this._changedImages={},this._glyphsDidChange=!1}setState(M,Bt={}){var Wt;this._checkLoaded();const Nt=this.serialize();if(M=Bt.transformStyle?Bt.transformStyle(Nt,M):M,(null===(Wt=Bt.validate)||void 0===Wt||Wt)&&mi(this,et.u(M)))return!1;(M=et.bw(M)).layers=et.bu(M.layers);const $t=et.bx(Nt,M),Gr=this._getOperationsToPerform($t);if(Gr.unimplemented.length>0)throw new Error(`Unimplemented: ${Gr.unimplemented.join(", ")}.`);if(0===Gr.operations.length)return!1;for(const M of Gr.operations)M();return this.stylesheet=M,this._serializedLayers=null,!0}_getOperationsToPerform(M){const et=[],Bt=[];for(const Wt of M)switch(Wt.command){case"setCenter":case"setZoom":case"setBearing":case"setPitch":case"setRoll":continue;case"addLayer":et.push((()=>this.addLayer.apply(this,Wt.args)));break;case"removeLayer":et.push((()=>this.removeLayer.apply(this,Wt.args)));break;case"setPaintProperty":et.push((()=>this.setPaintProperty.apply(this,Wt.args)));break;case"setLayoutProperty":et.push((()=>this.setLayoutProperty.apply(this,Wt.args)));break;case"setFilter":et.push((()=>this.setFilter.apply(this,Wt.args)));break;case"addSource":et.push((()=>this.addSource.apply(this,Wt.args)));break;case"removeSource":et.push((()=>this.removeSource.apply(this,Wt.args)));break;case"setLayerZoomRange":et.push((()=>this.setLayerZoomRange.apply(this,Wt.args)));break;case"setLight":et.push((()=>this.setLight.apply(this,Wt.args)));break;case"setGeoJSONSourceData":et.push((()=>this.setGeoJSONSourceData.apply(this,Wt.args)));break;case"setGlyphs":et.push((()=>this.setGlyphs.apply(this,Wt.args)));break;case"setSprite":et.push((()=>this.setSprite.apply(this,Wt.args)));break;case"setTerrain":et.push((()=>this.map.setTerrain.apply(this,Wt.args)));break;case"setSky":et.push((()=>this.setSky.apply(this,Wt.args)));break;case"setProjection":this.setProjection.apply(this,Wt.args);break;case"setTransition":et.push((()=>{}));break;default:Bt.push(Wt.command)}return{operations:et,unimplemented:Bt}}addImage(M,Bt){if(this.getImage(M))return this.fire(new et.j(new Error(`An image named "${M}" already exists.`)));this.imageManager.addImage(M,Bt),this._afterImageUpdated(M)}updateImage(M,et){this.imageManager.updateImage(M,et)}getImage(M){return this.imageManager.getImage(M)}removeImage(M){if(!this.getImage(M))return this.fire(new et.j(new Error(`An image named "${M}" does not exist.`)));this.imageManager.removeImage(M),this._afterImageUpdated(M)}_afterImageUpdated(M){this._availableImages=this.imageManager.listImages(),this._changedImages[M]=!0,this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new et.k("data",{dataType:"style"}))}listImages(){return this._checkLoaded(),this.imageManager.listImages()}addSource(M,Bt,Wt={}){if(this._checkLoaded(),void 0!==this.sourceCaches[M])throw new Error(`Source "${M}" already exists.`);if(!Bt.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(Bt).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(Bt.type)>=0&&this._validate(et.u.source,`sources.${M}`,Bt,null,Wt))return;this.map&&this.map._collectResourceTiming&&(Bt.collectResourceTiming=!0);const Nt=this.sourceCaches[M]=new de(M,Bt,this.dispatcher);Nt.style=this,Nt.setEventedParent(this,(()=>({isSourceLoaded:Nt.loaded(),source:Nt.serialize(),sourceId:M}))),Nt.onAdd(this.map),this._changed=!0}removeSource(M){if(this._checkLoaded(),void 0===this.sourceCaches[M])throw new Error("There is no source with this ID");for(const Bt in this._layers)if(this._layers[Bt].source===M)return this.fire(new et.j(new Error(`Source "${M}" cannot be removed while layer "${Bt}" is using it.`)));const Bt=this.sourceCaches[M];delete this.sourceCaches[M],delete this._updatedSources[M],Bt.fire(new et.k("data",{sourceDataType:"metadata",dataType:"source",sourceId:M})),Bt.setEventedParent(null),Bt.onRemove(this.map),this._changed=!0}setGeoJSONSourceData(M,et){if(this._checkLoaded(),void 0===this.sourceCaches[M])throw new Error(`There is no source with this ID=${M}`);const Bt=this.sourceCaches[M].getSource();if("geojson"!==Bt.type)throw new Error(`geojsonSource.type is ${Bt.type}, which is !== 'geojson`);Bt.setData(et),this._changed=!0}getSource(M){return this.sourceCaches[M]&&this.sourceCaches[M].getSource()}addLayer(M,Bt,Wt={}){this._checkLoaded();const Nt=M.id;if(this.getLayer(Nt))return void this.fire(new et.j(new Error(`Layer "${Nt}" already exists on this map.`)));let $t;if("custom"===M.type){if(mi(this,et.by(M)))return;$t=et.bv(M)}else{if("source"in M&&"object"==typeof M.source&&(this.addSource(Nt,M.source),M=et.bw(M),M=et.e(M,{source:Nt})),this._validate(et.u.layer,`layers.${Nt}`,M,{arrayIndex:-1},Wt))return;$t=et.bv(M),this._validateLayer($t),$t.setEventedParent(this,{layer:{id:Nt}})}const Gr=Bt?this._order.indexOf(Bt):this._order.length;if(Bt&&-1===Gr)this.fire(new et.j(new Error(`Cannot add layer "${Nt}" before non-existing layer "${Bt}".`)));else{if(this._order.splice(Gr,0,Nt),this._layerOrderChanged=!0,this._layers[Nt]=$t,this._removedLayers[Nt]&&$t.source&&"custom"!==$t.type){const M=this._removedLayers[Nt];delete this._removedLayers[Nt],M.type!==$t.type?this._updatedSources[$t.source]="clear":(this._updatedSources[$t.source]="reload",this.sourceCaches[$t.source].pause())}this._updateLayer($t),$t.onAdd&&$t.onAdd(this.map)}}moveLayer(M,Bt){if(this._checkLoaded(),this._changed=!0,!this._layers[M])return void this.fire(new et.j(new Error(`The layer '${M}' does not exist in the map's style and cannot be moved.`)));if(M===Bt)return;const Wt=this._order.indexOf(M);this._order.splice(Wt,1);const Nt=Bt?this._order.indexOf(Bt):this._order.length;Bt&&-1===Nt?this.fire(new et.j(new Error(`Cannot move layer "${M}" before non-existing layer "${Bt}".`))):(this._order.splice(Nt,0,M),this._layerOrderChanged=!0)}removeLayer(M){this._checkLoaded();const Bt=this._layers[M];if(!Bt)return void this.fire(new et.j(new Error(`Cannot remove non-existing layer "${M}".`)));Bt.setEventedParent(null);const Wt=this._order.indexOf(M);this._order.splice(Wt,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[M]=Bt,delete this._layers[M],this._serializedLayers&&delete this._serializedLayers[M],delete this._updatedLayers[M],delete this._updatedPaintProps[M],Bt.onRemove&&Bt.onRemove(this.map)}getLayer(M){return this._layers[M]}getLayersOrder(){return[...this._order]}hasLayer(M){return M in this._layers}setLayerZoomRange(M,Bt,Wt){this._checkLoaded();const Nt=this.getLayer(M);Nt?Nt.minzoom===Bt&&Nt.maxzoom===Wt||(null!=Bt&&(Nt.minzoom=Bt),null!=Wt&&(Nt.maxzoom=Wt),this._updateLayer(Nt)):this.fire(new et.j(new Error(`Cannot set the zoom range of non-existing layer "${M}".`)))}setFilter(M,Bt,Wt={}){this._checkLoaded();const Nt=this.getLayer(M);if(Nt){if(!et.bz(Nt.filter,Bt))return null==Bt?(Nt.filter=void 0,void this._updateLayer(Nt)):void(this._validate(et.u.filter,`layers.${Nt.id}.filter`,Bt,null,Wt)||(Nt.filter=et.bw(Bt),this._updateLayer(Nt)))}else this.fire(new et.j(new Error(`Cannot filter non-existing layer "${M}".`)))}getFilter(M){return et.bw(this.getLayer(M).filter)}setLayoutProperty(M,Bt,Wt,Nt={}){this._checkLoaded();const $t=this.getLayer(M);$t?et.bz($t.getLayoutProperty(Bt),Wt)||($t.setLayoutProperty(Bt,Wt,Nt),this._updateLayer($t)):this.fire(new et.j(new Error(`Cannot style non-existing layer "${M}".`)))}getLayoutProperty(M,Bt){const Wt=this.getLayer(M);if(Wt)return Wt.getLayoutProperty(Bt);this.fire(new et.j(new Error(`Cannot get style of non-existing layer "${M}".`)))}setPaintProperty(M,Bt,Wt,Nt={}){this._checkLoaded();const $t=this.getLayer(M);$t?et.bz($t.getPaintProperty(Bt),Wt)||($t.setPaintProperty(Bt,Wt,Nt)&&this._updateLayer($t),this._changed=!0,this._updatedPaintProps[M]=!0,this._serializedLayers=null):this.fire(new et.j(new Error(`Cannot style non-existing layer "${M}".`)))}getPaintProperty(M,et){return this.getLayer(M).getPaintProperty(et)}setFeatureState(M,Bt){this._checkLoaded();const Wt=M.source,Nt=M.sourceLayer,$t=this.sourceCaches[Wt];if(void 0===$t)return void this.fire(new et.j(new Error(`The source '${Wt}' does not exist in the map's style.`)));const Gr=$t.getSource().type;"geojson"===Gr&&Nt?this.fire(new et.j(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==Gr||Nt?(void 0===M.id&&this.fire(new et.j(new Error("The feature id parameter must be provided."))),$t.setFeatureState(Nt,M.id,Bt)):this.fire(new et.j(new Error("The sourceLayer parameter must be provided for vector source types.")))}removeFeatureState(M,Bt){this._checkLoaded();const Wt=M.source,Nt=this.sourceCaches[Wt];if(void 0===Nt)return void this.fire(new et.j(new Error(`The source '${Wt}' does not exist in the map's style.`)));const $t=Nt.getSource().type,Gr="vector"===$t?M.sourceLayer:void 0;"vector"!==$t||Gr?Bt&&"string"!=typeof M.id&&"number"!=typeof M.id?this.fire(new et.j(new Error("A feature id is required to remove its specific state property."))):Nt.removeFeatureState(Gr,M.id,Bt):this.fire(new et.j(new Error("The sourceLayer parameter must be provided for vector source types.")))}getFeatureState(M){this._checkLoaded();const Bt=M.source,Wt=M.sourceLayer,Nt=this.sourceCaches[Bt];if(void 0!==Nt)return"vector"!==Nt.getSource().type||Wt?(void 0===M.id&&this.fire(new et.j(new Error("The feature id parameter must be provided."))),Nt.getFeatureState(Wt,M.id)):void this.fire(new et.j(new Error("The sourceLayer parameter must be provided for vector source types.")));this.fire(new et.j(new Error(`The source '${Bt}' does not exist in the map's style.`)))}getTransition(){return et.e({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)}serialize(){if(!this._loaded)return;const M=et.bA(this.sourceCaches,(M=>M.serialize())),Bt=this._serializeByIds(this._order,!0),Wt=this.map.getTerrain()||void 0,Nt=this.stylesheet;return et.bB({version:Nt.version,name:Nt.name,metadata:Nt.metadata,light:Nt.light,sky:Nt.sky,center:Nt.center,zoom:Nt.zoom,bearing:Nt.bearing,pitch:Nt.pitch,sprite:Nt.sprite,glyphs:Nt.glyphs,transition:Nt.transition,projection:Nt.projection,sources:M,layers:Bt,terrain:Wt},(M=>void 0!==M))}_updateLayer(M){this._updatedLayers[M.id]=!0,M.source&&!this._updatedSources[M.source]&&"raster"!==this.sourceCaches[M.source].getSource().type&&(this._updatedSources[M.source]="reload",this.sourceCaches[M.source].pause()),this._serializedLayers=null,this._changed=!0}_flattenAndSortRenderedFeatures(M){const t=M=>"fill-extrusion"===this._layers[M].type,et={},Bt=[];for(let Wt=this._order.length-1;Wt>=0;Wt--){const Nt=this._order[Wt];if(t(Nt)){et[Nt]=Wt;for(const et of M){const M=et[Nt];if(M)for(const et of M)Bt.push(et)}}}Bt.sort(((M,et)=>et.intersectionZ-M.intersectionZ));const Wt=[];for(let Nt=this._order.length-1;Nt>=0;Nt--){const $t=this._order[Nt];if(t($t))for(let M=Bt.length-1;M>=0;M--){const $t=Bt[M].feature;if(et[$t.layer.id]{const Wt=Bt.featureSortOrder;if(Wt){const Bt=Wt.indexOf(M.featureIndex);return Wt.indexOf(et.featureIndex)-Bt}return et.featureIndex-M.featureIndex}));for(const M of Nt)et.push(M)}}return function(M,et,Bt){for(const Wt in M)for(const Nt of M[Wt])G(Nt,Bt[et[Wt].source]);return M}(mn,M,Bt)}(this._layers,Gr,this.sourceCaches,M,Hn,this.placement.collisionIndex,this.placement.retainedQueryData)),this._flattenAndSortRenderedFeatures($t)}querySourceFeatures(M,Bt){Bt&&Bt.filter&&this._validate(et.u.filter,"querySourceFeatures.filter",Bt.filter,null,Bt);const Wt=this.sourceCaches[M];return Wt?function(M,et){const Bt=M.getRenderableIds().map((et=>M.getTileByID(et))),Wt=[],Nt={};for(let M=0;MM.getTileByID(et))).sort(((M,et)=>et.tileID.overscaledZ-M.tileID.overscaledZ||(M.tileID.isLessThan(et.tileID)?-1:1)))}const Wt=this.crossTileSymbolIndex.addLayer(Bt,Hn[Bt.source],M.center.lng);Gr=Gr||Wt}if(this.crossTileSymbolIndex.pruneUnusedLayers(this._order),((Nt=Nt||this._layerOrderChanged||0===Bt)||!this.pauseablePlacement||this.pauseablePlacement.isDone()&&!this.placement.stillRecent($t.now(),M.zoom))&&(this.pauseablePlacement=new st(M,this.map.terrain,this._order,Nt,et,Bt,Wt,this.placement),this._layerOrderChanged=!1),this.pauseablePlacement.isDone()?this.placement.setStale():(this.pauseablePlacement.continuePlacement(this._order,this._layers,Hn),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit($t.now()),mn=!0),Gr&&this.pauseablePlacement.placement.setStale()),mn||Gr)for(const M of this._order){const et=this._layers[M];"symbol"===et.type&&this.placement.updateLayerOpacities(et,Hn[et.source])}return!this.pauseablePlacement.isDone()||this.placement.hasTransitions($t.now())}_releaseSymbolFadeTiles(){for(const M in this.sourceCaches)this.sourceCaches[M].releaseSymbolFadeTiles()}getImages(M,Bt){return et._(this,void 0,void 0,(function*(){const M=yield this.imageManager.getImages(Bt.icons);this._updateTilesForChangedImages();const et=this.sourceCaches[Bt.source];return et&&et.setDependencies(Bt.tileID.key,Bt.type,Bt.icons),M}))}getGlyphs(M,Bt){return et._(this,void 0,void 0,(function*(){const M=yield this.glyphManager.getGlyphs(Bt.stacks),et=this.sourceCaches[Bt.source];return et&&et.setDependencies(Bt.tileID.key,Bt.type,[""]),M}))}getGlyphsUrl(){return this.stylesheet.glyphs||null}setGlyphs(M,Bt={}){this._checkLoaded(),M&&this._validate(et.u.glyphs,"glyphs",M,null,Bt)||(this._glyphsDidChange=!0,this.stylesheet.glyphs=M,this.glyphManager.entries={},this.glyphManager.setURL(M))}addSprite(M,Bt,Wt={},Nt){this._checkLoaded();const $t=[{id:M,url:Bt}],Gr=[...f(this.stylesheet.sprite),...$t];this._validate(et.u.sprite,"sprite",Gr,null,Wt)||(this.stylesheet.sprite=Gr,this._loadSprite($t,!0,Nt))}removeSprite(M){this._checkLoaded();const Bt=f(this.stylesheet.sprite);if(Bt.find((et=>et.id===M))){if(this._spritesImagesIds[M])for(const et of this._spritesImagesIds[M])this.imageManager.removeImage(et),this._changedImages[et]=!0;Bt.splice(Bt.findIndex((et=>et.id===M)),1),this.stylesheet.sprite=Bt.length>0?Bt:void 0,delete this._spritesImagesIds[M],this._availableImages=this.imageManager.listImages(),this._changed=!0,this.dispatcher.broadcast("SI",this._availableImages),this.fire(new et.k("data",{dataType:"style"}))}else this.fire(new et.j(new Error(`Sprite "${M}" doesn't exists on this map.`)))}getSprite(){return f(this.stylesheet.sprite)}setSprite(M,Bt={},Wt){this._checkLoaded(),M&&this._validate(et.u.sprite,"sprite",M,null,Bt)||(this.stylesheet.sprite=M,M?this._loadSprite(M,!0,Wt):(this._unloadSprite(),Wt&&Wt(null)))}}var $l=et.aA([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]);class xi{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null}bind(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn){this.context=M;let so=this.boundPaintVertexBuffers.length!==Wt.length;for(let M=0;!so&&M({u_texture:0,u_ele_delta:M,u_fog_matrix:Bt,u_fog_color:Wt?Wt.properties.get("fog-color"):et.b4.white,u_fog_ground_blend:Wt?Wt.properties.get("fog-ground-blend"):1,u_fog_ground_blend_opacity:$t?0:Wt?Wt.calculateFogBlendOpacity(Nt):0,u_horizon_color:Wt?Wt.properties.get("horizon-color"):et.b4.white,u_horizon_fog_blend:Wt?Wt.properties.get("horizon-fog-blend"):1,u_is_globe_mode:$t?1:0}),tc={mainMatrix:"u_projection_matrix",tileMercatorCoords:"u_projection_tile_mercator_coords",clippingPlane:"u_projection_clipping_plane",projectionTransition:"u_projection_transition",fallbackMatrix:"u_projection_fallback_matrix"};function wi(M){const et=[];for(let Bt=0;Bt({u_depth:new et.bC(M,Bt.u_depth),u_terrain:new et.bC(M,Bt.u_terrain),u_terrain_dim:new et.b5(M,Bt.u_terrain_dim),u_terrain_matrix:new et.bD(M,Bt.u_terrain_matrix),u_terrain_unpack:new et.bE(M,Bt.u_terrain_unpack),u_terrain_exaggeration:new et.b5(M,Bt.u_terrain_exaggeration)}))(M,Ka),this.projectionUniforms=((M,Bt)=>({u_projection_matrix:new et.bD(M,Bt.u_projection_matrix),u_projection_tile_mercator_coords:new et.bE(M,Bt.u_projection_tile_mercator_coords),u_projection_clipping_plane:new et.bE(M,Bt.u_projection_clipping_plane),u_projection_transition:new et.b5(M,Bt.u_projection_transition),u_projection_fallback_matrix:new et.bD(M,Bt.u_projection_fallback_matrix)}))(M,Ka),this.binderUniforms=Wt?Wt.getUniforms(M,Ka):[]}draw(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo,Ia,Ba,Ta,Va){const za=M.gl;if(this.failedToCreate)return;if(M.program.set(this.program),M.setDepthMode(Bt),M.setStencilMode(Wt),M.setColorMode(Nt),M.setCullFace($t),mn){M.activeTexture.set(za.TEXTURE2),za.bindTexture(za.TEXTURE_2D,mn.depthTexture),M.activeTexture.set(za.TEXTURE3),za.bindTexture(za.TEXTURE_2D,mn.texture);for(const M in this.terrainUniforms)this.terrainUniforms[M].set(mn[M])}if(Hn)for(const M in Hn)this.projectionUniforms[tc[M]].set(Hn[M]);if(Gr)for(const M in this.fixedUniforms)this.fixedUniforms[M].set(Gr[M]);Ia&&Ia.setUniforms(M,this.binderUniforms,To,{zoom:Eo});let Fa=0;switch(et){case za.LINES:Fa=2;break;case za.TRIANGLES:Fa=3;break;case za.LINE_STRIP:Fa=1}for(const Bt of Po.get()){const Wt=Bt.vaos||(Bt.vaos={});(Wt[so]||(Wt[so]=new xi)).bind(M,this,uo,Ia?Ia.getPaintVertexBuffers():[],Io,Bt.vertexOffset,Ba,Ta,Va),za.drawElements(et,Bt.primitiveLength*Fa,za.UNSIGNED_SHORT,Bt.primitiveOffset*Fa*2)}}}function Pi(M,Bt,Wt){const Nt=1/et.at(Wt,1,Bt.transform.tileZoom),$t=Math.pow(2,Wt.tileID.overscaledZ),Gr=Wt.tileSize*Math.pow(2,Bt.transform.tileZoom)/$t,mn=Gr*(Wt.tileID.canonical.x+Wt.tileID.wrap*$t),Hn=Gr*Wt.tileID.canonical.y;return{u_image:0,u_texsize:Wt.imageAtlasTexture.size,u_scale:[Nt,M.fromScale,M.toScale],u_fade:M.t,u_pixel_coord_upper:[mn>>16,Hn>>16],u_pixel_coord_lower:[65535&mn,65535&Hn]}}const Ci=(M,Bt,Wt,Nt)=>{const $t=M.style.light,Gr=$t.properties.get("position"),mn=[Gr.x,Gr.y,Gr.z],Hn=et.bI();"viewport"===$t.properties.get("anchor")&&et.bJ(Hn,M.transform.bearingInRadians),et.bK(mn,mn,Hn);const so=M.transform.transformLightDirection(mn),uo=$t.properties.get("color");return{u_lightpos:mn,u_lightpos_globe:so,u_lightintensity:$t.properties.get("intensity"),u_lightcolor:[uo.r,uo.g,uo.b],u_vertical_gradient:+Bt,u_opacity:Wt,u_fill_translate:Nt}},Ii=(M,Bt,Wt,Nt,$t,Gr,mn)=>et.e(Ci(M,Bt,Wt,Nt),Pi(Gr,M,mn),{u_height_factor:-Math.pow(2,$t.overscaledZ)/mn.tileSize/8}),Ei=(M,Bt,Wt,Nt)=>et.e(Pi(Bt,M,Wt),{u_fill_translate:Nt}),Mi=(M,et)=>({u_world:M,u_fill_translate:et}),Si=(M,Bt,Wt,Nt,$t)=>et.e(Ei(M,Bt,Wt,$t),{u_world:Nt}),Ri=(M,Bt,Wt,Nt,$t)=>{const Gr=M.transform;let mn,Hn,so=0;if("map"===Wt.paint.get("circle-pitch-alignment")){const M=et.at(Bt,1,Gr.zoom);mn=!0,Hn=[M,M],so=M/(et.X*Math.pow(2,Bt.tileID.overscaledZ))*2*Math.PI*$t}else mn=!1,Hn=Gr.pixelsToGLUnits;return{u_camera_to_center_distance:Gr.cameraToCenterDistance,u_scale_with_map:+("map"===Wt.paint.get("circle-pitch-scale")),u_pitch_with_map:+mn,u_device_pixel_ratio:M.pixelRatio,u_extrude_scale:Hn,u_globe_extrude_scale:so,u_translate:Nt}},Di=M=>({u_pixel_extrude_scale:[1/M.width,1/M.height]}),zi=M=>({u_viewport_size:[M.width,M.height]}),Ai=(M,et=1)=>({u_color:M,u_overlay:0,u_overlay_scale:et}),Li=(M,Bt,Wt,Nt)=>{const $t=et.at(M,1,Bt)/(et.X*Math.pow(2,M.tileID.overscaledZ))*2*Math.PI*Nt;return{u_extrude_scale:et.at(M,1,Bt),u_intensity:Wt,u_globe_extrude_scale:$t}},ki=(M,Bt,Wt,Nt)=>{const $t=et.H();et.bL($t,0,M.width,M.height,0,0,1);const Gr=M.context.gl;return{u_matrix:$t,u_world:[Gr.drawingBufferWidth,Gr.drawingBufferHeight],u_image:Wt,u_color_ramp:Nt,u_opacity:Bt.paint.get("heatmap-opacity")}},Fi=(M,et,Bt)=>{const Wt=Bt.paint.get("hillshade-shadow-color"),Nt=Bt.paint.get("hillshade-highlight-color"),$t=Bt.paint.get("hillshade-accent-color");let Gr=Bt.paint.get("hillshade-illumination-direction")*(Math.PI/180);return"viewport"===Bt.paint.get("hillshade-illumination-anchor")&&(Gr+=M.transform.bearingInRadians),{u_image:0,u_latrange:ji(0,et.tileID),u_light:[Bt.paint.get("hillshade-exaggeration"),Gr],u_shadow:Wt,u_highlight:Nt,u_accent:$t}},Bi=(M,Bt)=>{const Wt=Bt.stride,Nt=et.H();return et.bL(Nt,0,et.X,-et.X,0,0,1),et.J(Nt,Nt,[0,-et.X,0]),{u_matrix:Nt,u_image:1,u_dimension:[Wt,Wt],u_zoom:M.overscaledZ,u_unpack:Bt.getUnpackVector()}};function ji(M,Bt){const Wt=Math.pow(2,Bt.canonical.z),Nt=Bt.canonical.y;return[new et.Y(0,Nt/Wt).toLngLat().lat,new et.Y(0,(Nt+1)/Wt).toLngLat().lat]}const Oi=(M,Bt,Wt,Nt)=>{const $t=M.transform;return{u_translation:Vi(M,Bt,Wt),u_ratio:Nt/et.at(Bt,1,$t.zoom),u_device_pixel_ratio:M.pixelRatio,u_units_to_pixels:[1/$t.pixelsToGLUnits[0],1/$t.pixelsToGLUnits[1]]}},Ni=(M,Bt,Wt,Nt,$t)=>et.e(Oi(M,Bt,Wt,Nt),{u_image:0,u_image_height:$t}),Zi=(M,Bt,Wt,Nt,$t)=>{const Gr=M.transform,mn=Ui(Bt,Gr);return{u_translation:Vi(M,Bt,Wt),u_texsize:Bt.imageAtlasTexture.size,u_ratio:Nt/et.at(Bt,1,Gr.zoom),u_device_pixel_ratio:M.pixelRatio,u_image:0,u_scale:[mn,$t.fromScale,$t.toScale],u_fade:$t.t,u_units_to_pixels:[1/Gr.pixelsToGLUnits[0],1/Gr.pixelsToGLUnits[1]]}},Gi=(M,Bt,Wt,Nt,$t,Gr)=>{const mn=M.lineAtlas,Hn=Ui(Bt,M.transform),so="round"===Wt.layout.get("line-cap"),uo=mn.getDash($t.from,so),Io=mn.getDash($t.to,so),Po=uo.width*Gr.fromScale,To=Io.width*Gr.toScale;return et.e(Oi(M,Bt,Wt,Nt),{u_patternscale_a:[Hn/Po,-uo.height/2],u_patternscale_b:[Hn/To,-Io.height/2],u_sdfgamma:mn.width/(256*Math.min(Po,To)*M.pixelRatio)/2,u_image:0,u_tex_y_a:uo.y,u_tex_y_b:Io.y,u_mix:Gr.t})};function Ui(M,Bt){return 1/et.at(M,1,Bt.tileZoom)}function Vi(M,Bt,Wt){return et.au(M.transform,Bt,Wt.paint.get("line-translate"),Wt.paint.get("line-translate-anchor"))}const qi=(M,et,Bt,Wt,Nt)=>{return{u_tl_parent:M,u_scale_parent:et,u_buffer_scale:1,u_fade_t:Bt.mix,u_opacity:Bt.opacity*Wt.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:Wt.paint.get("raster-brightness-min"),u_brightness_high:Wt.paint.get("raster-brightness-max"),u_saturation_factor:(Gr=Wt.paint.get("raster-saturation"),Gr>0?1-1/(1.001-Gr):-Gr),u_contrast_factor:($t=Wt.paint.get("raster-contrast"),$t>0?1/(1-$t):1+$t),u_spin_weights:Hi(Wt.paint.get("raster-hue-rotate")),u_coords_top:[Nt[0].x,Nt[0].y,Nt[1].x,Nt[1].y],u_coords_bottom:[Nt[3].x,Nt[3].y,Nt[2].x,Nt[2].y]};var $t,Gr};function Hi(M){M*=Math.PI/180;const et=Math.sin(M),Bt=Math.cos(M);return[(2*Bt+1)/3,(-Math.sqrt(3)*et-Bt+1)/3,(Math.sqrt(3)*et-Bt+1)/3]}const Wi=(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po)=>{const To=Gr.transform;return{u_is_size_zoom_constant:+("constant"===M||"source"===M),u_is_size_feature_constant:+("constant"===M||"camera"===M),u_size_t:et?et.uSizeT:0,u_size:et?et.uSize:0,u_camera_to_center_distance:To.cameraToCenterDistance,u_pitch:To.pitch/360*2*Math.PI,u_rotate_symbol:+Bt,u_aspect_ratio:To.width/To.height,u_fade_change:Gr.options.fadeDuration?Gr.symbolFadeChange:1,u_label_plane_matrix:mn,u_coord_matrix:Hn,u_is_text:+uo,u_pitch_with_map:+Wt,u_is_along_line:Nt,u_is_variable_anchor:$t,u_texsize:Io,u_texture:0,u_translation:so,u_pitched_scale:Po}},Xi=(M,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To,Eo)=>{const Ia=mn.transform;return et.e(Wi(M,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,Eo),{u_gamma_scale:Nt?Math.cos(Ia.pitch*Math.PI/180)*Ia.cameraToCenterDistance:1,u_device_pixel_ratio:mn.pixelRatio,u_is_halo:1})},$i=(M,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,Io,Po,To)=>et.e(Xi(M,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo,!0,Io,!0,To),{u_texsize_icon:Po,u_texture_icon:1}),Ki=(M,et)=>({u_opacity:M,u_color:et}),Yi=(M,Bt,Wt,Nt,$t)=>et.e(function(M,Bt,Wt,Nt){const $t=Wt.imageManager.getPattern(M.from.toString()),Gr=Wt.imageManager.getPattern(M.to.toString()),{width:mn,height:Hn}=Wt.imageManager.getPixelSize(),so=Math.pow(2,Nt.tileID.overscaledZ),uo=Nt.tileSize*Math.pow(2,Wt.transform.tileZoom)/so,Io=uo*(Nt.tileID.canonical.x+Nt.tileID.wrap*so),Po=uo*Nt.tileID.canonical.y;return{u_image:0,u_pattern_tl_a:$t.tl,u_pattern_br_a:$t.br,u_pattern_tl_b:Gr.tl,u_pattern_br_b:Gr.br,u_texsize:[mn,Hn],u_mix:Bt.t,u_pattern_size_a:$t.displaySize,u_pattern_size_b:Gr.displaySize,u_scale_a:Bt.fromScale,u_scale_b:Bt.toScale,u_tile_units_to_pixels:1/et.at(Nt,1,Wt.transform.tileZoom),u_pixel_coord_upper:[Io>>16,Po>>16],u_pixel_coord_lower:[65535&Io,65535&Po]}}(Wt,$t,Bt,Nt),{u_opacity:M}),Ji=(M,et)=>{},ec={fillExtrusion:(M,Bt)=>({u_lightpos:new et.bG(M,Bt.u_lightpos),u_lightpos_globe:new et.bG(M,Bt.u_lightpos_globe),u_lightintensity:new et.b5(M,Bt.u_lightintensity),u_lightcolor:new et.bG(M,Bt.u_lightcolor),u_vertical_gradient:new et.b5(M,Bt.u_vertical_gradient),u_opacity:new et.b5(M,Bt.u_opacity),u_fill_translate:new et.bH(M,Bt.u_fill_translate)}),fillExtrusionPattern:(M,Bt)=>({u_lightpos:new et.bG(M,Bt.u_lightpos),u_lightpos_globe:new et.bG(M,Bt.u_lightpos_globe),u_lightintensity:new et.b5(M,Bt.u_lightintensity),u_lightcolor:new et.bG(M,Bt.u_lightcolor),u_vertical_gradient:new et.b5(M,Bt.u_vertical_gradient),u_height_factor:new et.b5(M,Bt.u_height_factor),u_opacity:new et.b5(M,Bt.u_opacity),u_fill_translate:new et.bH(M,Bt.u_fill_translate),u_image:new et.bC(M,Bt.u_image),u_texsize:new et.bH(M,Bt.u_texsize),u_pixel_coord_upper:new et.bH(M,Bt.u_pixel_coord_upper),u_pixel_coord_lower:new et.bH(M,Bt.u_pixel_coord_lower),u_scale:new et.bG(M,Bt.u_scale),u_fade:new et.b5(M,Bt.u_fade)}),fill:(M,Bt)=>({u_fill_translate:new et.bH(M,Bt.u_fill_translate)}),fillPattern:(M,Bt)=>({u_image:new et.bC(M,Bt.u_image),u_texsize:new et.bH(M,Bt.u_texsize),u_pixel_coord_upper:new et.bH(M,Bt.u_pixel_coord_upper),u_pixel_coord_lower:new et.bH(M,Bt.u_pixel_coord_lower),u_scale:new et.bG(M,Bt.u_scale),u_fade:new et.b5(M,Bt.u_fade),u_fill_translate:new et.bH(M,Bt.u_fill_translate)}),fillOutline:(M,Bt)=>({u_world:new et.bH(M,Bt.u_world),u_fill_translate:new et.bH(M,Bt.u_fill_translate)}),fillOutlinePattern:(M,Bt)=>({u_world:new et.bH(M,Bt.u_world),u_image:new et.bC(M,Bt.u_image),u_texsize:new et.bH(M,Bt.u_texsize),u_pixel_coord_upper:new et.bH(M,Bt.u_pixel_coord_upper),u_pixel_coord_lower:new et.bH(M,Bt.u_pixel_coord_lower),u_scale:new et.bG(M,Bt.u_scale),u_fade:new et.b5(M,Bt.u_fade),u_fill_translate:new et.bH(M,Bt.u_fill_translate)}),circle:(M,Bt)=>({u_camera_to_center_distance:new et.b5(M,Bt.u_camera_to_center_distance),u_scale_with_map:new et.bC(M,Bt.u_scale_with_map),u_pitch_with_map:new et.bC(M,Bt.u_pitch_with_map),u_extrude_scale:new et.bH(M,Bt.u_extrude_scale),u_device_pixel_ratio:new et.b5(M,Bt.u_device_pixel_ratio),u_globe_extrude_scale:new et.b5(M,Bt.u_globe_extrude_scale),u_translate:new et.bH(M,Bt.u_translate)}),collisionBox:(M,Bt)=>({u_pixel_extrude_scale:new et.bH(M,Bt.u_pixel_extrude_scale)}),collisionCircle:(M,Bt)=>({u_viewport_size:new et.bH(M,Bt.u_viewport_size)}),debug:(M,Bt)=>({u_color:new et.bF(M,Bt.u_color),u_overlay:new et.bC(M,Bt.u_overlay),u_overlay_scale:new et.b5(M,Bt.u_overlay_scale)}),depth:Ji,clippingMask:Ji,heatmap:(M,Bt)=>({u_extrude_scale:new et.b5(M,Bt.u_extrude_scale),u_intensity:new et.b5(M,Bt.u_intensity),u_globe_extrude_scale:new et.b5(M,Bt.u_globe_extrude_scale)}),heatmapTexture:(M,Bt)=>({u_matrix:new et.bD(M,Bt.u_matrix),u_world:new et.bH(M,Bt.u_world),u_image:new et.bC(M,Bt.u_image),u_color_ramp:new et.bC(M,Bt.u_color_ramp),u_opacity:new et.b5(M,Bt.u_opacity)}),hillshade:(M,Bt)=>({u_image:new et.bC(M,Bt.u_image),u_latrange:new et.bH(M,Bt.u_latrange),u_light:new et.bH(M,Bt.u_light),u_shadow:new et.bF(M,Bt.u_shadow),u_highlight:new et.bF(M,Bt.u_highlight),u_accent:new et.bF(M,Bt.u_accent)}),hillshadePrepare:(M,Bt)=>({u_matrix:new et.bD(M,Bt.u_matrix),u_image:new et.bC(M,Bt.u_image),u_dimension:new et.bH(M,Bt.u_dimension),u_zoom:new et.b5(M,Bt.u_zoom),u_unpack:new et.bE(M,Bt.u_unpack)}),line:(M,Bt)=>({u_translation:new et.bH(M,Bt.u_translation),u_ratio:new et.b5(M,Bt.u_ratio),u_device_pixel_ratio:new et.b5(M,Bt.u_device_pixel_ratio),u_units_to_pixels:new et.bH(M,Bt.u_units_to_pixels)}),lineGradient:(M,Bt)=>({u_translation:new et.bH(M,Bt.u_translation),u_ratio:new et.b5(M,Bt.u_ratio),u_device_pixel_ratio:new et.b5(M,Bt.u_device_pixel_ratio),u_units_to_pixels:new et.bH(M,Bt.u_units_to_pixels),u_image:new et.bC(M,Bt.u_image),u_image_height:new et.b5(M,Bt.u_image_height)}),linePattern:(M,Bt)=>({u_translation:new et.bH(M,Bt.u_translation),u_texsize:new et.bH(M,Bt.u_texsize),u_ratio:new et.b5(M,Bt.u_ratio),u_device_pixel_ratio:new et.b5(M,Bt.u_device_pixel_ratio),u_image:new et.bC(M,Bt.u_image),u_units_to_pixels:new et.bH(M,Bt.u_units_to_pixels),u_scale:new et.bG(M,Bt.u_scale),u_fade:new et.b5(M,Bt.u_fade)}),lineSDF:(M,Bt)=>({u_translation:new et.bH(M,Bt.u_translation),u_ratio:new et.b5(M,Bt.u_ratio),u_device_pixel_ratio:new et.b5(M,Bt.u_device_pixel_ratio),u_units_to_pixels:new et.bH(M,Bt.u_units_to_pixels),u_patternscale_a:new et.bH(M,Bt.u_patternscale_a),u_patternscale_b:new et.bH(M,Bt.u_patternscale_b),u_sdfgamma:new et.b5(M,Bt.u_sdfgamma),u_image:new et.bC(M,Bt.u_image),u_tex_y_a:new et.b5(M,Bt.u_tex_y_a),u_tex_y_b:new et.b5(M,Bt.u_tex_y_b),u_mix:new et.b5(M,Bt.u_mix)}),raster:(M,Bt)=>({u_tl_parent:new et.bH(M,Bt.u_tl_parent),u_scale_parent:new et.b5(M,Bt.u_scale_parent),u_buffer_scale:new et.b5(M,Bt.u_buffer_scale),u_fade_t:new et.b5(M,Bt.u_fade_t),u_opacity:new et.b5(M,Bt.u_opacity),u_image0:new et.bC(M,Bt.u_image0),u_image1:new et.bC(M,Bt.u_image1),u_brightness_low:new et.b5(M,Bt.u_brightness_low),u_brightness_high:new et.b5(M,Bt.u_brightness_high),u_saturation_factor:new et.b5(M,Bt.u_saturation_factor),u_contrast_factor:new et.b5(M,Bt.u_contrast_factor),u_spin_weights:new et.bG(M,Bt.u_spin_weights),u_coords_top:new et.bE(M,Bt.u_coords_top),u_coords_bottom:new et.bE(M,Bt.u_coords_bottom)}),symbolIcon:(M,Bt)=>({u_is_size_zoom_constant:new et.bC(M,Bt.u_is_size_zoom_constant),u_is_size_feature_constant:new et.bC(M,Bt.u_is_size_feature_constant),u_size_t:new et.b5(M,Bt.u_size_t),u_size:new et.b5(M,Bt.u_size),u_camera_to_center_distance:new et.b5(M,Bt.u_camera_to_center_distance),u_pitch:new et.b5(M,Bt.u_pitch),u_rotate_symbol:new et.bC(M,Bt.u_rotate_symbol),u_aspect_ratio:new et.b5(M,Bt.u_aspect_ratio),u_fade_change:new et.b5(M,Bt.u_fade_change),u_label_plane_matrix:new et.bD(M,Bt.u_label_plane_matrix),u_coord_matrix:new et.bD(M,Bt.u_coord_matrix),u_is_text:new et.bC(M,Bt.u_is_text),u_pitch_with_map:new et.bC(M,Bt.u_pitch_with_map),u_is_along_line:new et.bC(M,Bt.u_is_along_line),u_is_variable_anchor:new et.bC(M,Bt.u_is_variable_anchor),u_texsize:new et.bH(M,Bt.u_texsize),u_texture:new et.bC(M,Bt.u_texture),u_translation:new et.bH(M,Bt.u_translation),u_pitched_scale:new et.b5(M,Bt.u_pitched_scale)}),symbolSDF:(M,Bt)=>({u_is_size_zoom_constant:new et.bC(M,Bt.u_is_size_zoom_constant),u_is_size_feature_constant:new et.bC(M,Bt.u_is_size_feature_constant),u_size_t:new et.b5(M,Bt.u_size_t),u_size:new et.b5(M,Bt.u_size),u_camera_to_center_distance:new et.b5(M,Bt.u_camera_to_center_distance),u_pitch:new et.b5(M,Bt.u_pitch),u_rotate_symbol:new et.bC(M,Bt.u_rotate_symbol),u_aspect_ratio:new et.b5(M,Bt.u_aspect_ratio),u_fade_change:new et.b5(M,Bt.u_fade_change),u_label_plane_matrix:new et.bD(M,Bt.u_label_plane_matrix),u_coord_matrix:new et.bD(M,Bt.u_coord_matrix),u_is_text:new et.bC(M,Bt.u_is_text),u_pitch_with_map:new et.bC(M,Bt.u_pitch_with_map),u_is_along_line:new et.bC(M,Bt.u_is_along_line),u_is_variable_anchor:new et.bC(M,Bt.u_is_variable_anchor),u_texsize:new et.bH(M,Bt.u_texsize),u_texture:new et.bC(M,Bt.u_texture),u_gamma_scale:new et.b5(M,Bt.u_gamma_scale),u_device_pixel_ratio:new et.b5(M,Bt.u_device_pixel_ratio),u_is_halo:new et.bC(M,Bt.u_is_halo),u_translation:new et.bH(M,Bt.u_translation),u_pitched_scale:new et.b5(M,Bt.u_pitched_scale)}),symbolTextAndIcon:(M,Bt)=>({u_is_size_zoom_constant:new et.bC(M,Bt.u_is_size_zoom_constant),u_is_size_feature_constant:new et.bC(M,Bt.u_is_size_feature_constant),u_size_t:new et.b5(M,Bt.u_size_t),u_size:new et.b5(M,Bt.u_size),u_camera_to_center_distance:new et.b5(M,Bt.u_camera_to_center_distance),u_pitch:new et.b5(M,Bt.u_pitch),u_rotate_symbol:new et.bC(M,Bt.u_rotate_symbol),u_aspect_ratio:new et.b5(M,Bt.u_aspect_ratio),u_fade_change:new et.b5(M,Bt.u_fade_change),u_label_plane_matrix:new et.bD(M,Bt.u_label_plane_matrix),u_coord_matrix:new et.bD(M,Bt.u_coord_matrix),u_is_text:new et.bC(M,Bt.u_is_text),u_pitch_with_map:new et.bC(M,Bt.u_pitch_with_map),u_is_along_line:new et.bC(M,Bt.u_is_along_line),u_is_variable_anchor:new et.bC(M,Bt.u_is_variable_anchor),u_texsize:new et.bH(M,Bt.u_texsize),u_texsize_icon:new et.bH(M,Bt.u_texsize_icon),u_texture:new et.bC(M,Bt.u_texture),u_texture_icon:new et.bC(M,Bt.u_texture_icon),u_gamma_scale:new et.b5(M,Bt.u_gamma_scale),u_device_pixel_ratio:new et.b5(M,Bt.u_device_pixel_ratio),u_is_halo:new et.bC(M,Bt.u_is_halo),u_translation:new et.bH(M,Bt.u_translation),u_pitched_scale:new et.b5(M,Bt.u_pitched_scale)}),background:(M,Bt)=>({u_opacity:new et.b5(M,Bt.u_opacity),u_color:new et.bF(M,Bt.u_color)}),backgroundPattern:(M,Bt)=>({u_opacity:new et.b5(M,Bt.u_opacity),u_image:new et.bC(M,Bt.u_image),u_pattern_tl_a:new et.bH(M,Bt.u_pattern_tl_a),u_pattern_br_a:new et.bH(M,Bt.u_pattern_br_a),u_pattern_tl_b:new et.bH(M,Bt.u_pattern_tl_b),u_pattern_br_b:new et.bH(M,Bt.u_pattern_br_b),u_texsize:new et.bH(M,Bt.u_texsize),u_mix:new et.b5(M,Bt.u_mix),u_pattern_size_a:new et.bH(M,Bt.u_pattern_size_a),u_pattern_size_b:new et.bH(M,Bt.u_pattern_size_b),u_scale_a:new et.b5(M,Bt.u_scale_a),u_scale_b:new et.b5(M,Bt.u_scale_b),u_pixel_coord_upper:new et.bH(M,Bt.u_pixel_coord_upper),u_pixel_coord_lower:new et.bH(M,Bt.u_pixel_coord_lower),u_tile_units_to_pixels:new et.b5(M,Bt.u_tile_units_to_pixels)}),terrain:(M,Bt)=>({u_texture:new et.bC(M,Bt.u_texture),u_ele_delta:new et.b5(M,Bt.u_ele_delta),u_fog_matrix:new et.bD(M,Bt.u_fog_matrix),u_fog_color:new et.bF(M,Bt.u_fog_color),u_fog_ground_blend:new et.b5(M,Bt.u_fog_ground_blend),u_fog_ground_blend_opacity:new et.b5(M,Bt.u_fog_ground_blend_opacity),u_horizon_color:new et.bF(M,Bt.u_horizon_color),u_horizon_fog_blend:new et.b5(M,Bt.u_horizon_fog_blend),u_is_globe_mode:new et.b5(M,Bt.u_is_globe_mode)}),terrainDepth:(M,Bt)=>({u_ele_delta:new et.b5(M,Bt.u_ele_delta)}),terrainCoords:(M,Bt)=>({u_texture:new et.bC(M,Bt.u_texture),u_terrain_coords_id:new et.b5(M,Bt.u_terrain_coords_id),u_ele_delta:new et.b5(M,Bt.u_ele_delta)}),projectionErrorMeasurement:(M,Bt)=>({u_input:new et.b5(M,Bt.u_input),u_output_expected:new et.b5(M,Bt.u_output_expected)}),atmosphere:(M,Bt)=>({u_sun_pos:new et.bG(M,Bt.u_sun_pos),u_atmosphere_blend:new et.b5(M,Bt.u_atmosphere_blend),u_globe_position:new et.bG(M,Bt.u_globe_position),u_globe_radius:new et.b5(M,Bt.u_globe_radius),u_inv_proj_matrix:new et.bD(M,Bt.u_inv_proj_matrix)}),sky:(M,Bt)=>({u_sky_color:new et.bF(M,Bt.u_sky_color),u_horizon_color:new et.bF(M,Bt.u_horizon_color),u_horizon:new et.bH(M,Bt.u_horizon),u_horizon_normal:new et.bH(M,Bt.u_horizon_normal),u_sky_horizon_blend:new et.b5(M,Bt.u_sky_horizon_blend),u_sky_blend:new et.b5(M,Bt.u_sky_blend)})};class er{constructor(M,et,Bt){this.context=M;const Wt=M.gl;this.buffer=Wt.createBuffer(),this.dynamicDraw=Boolean(Bt),this.context.unbindVAO(),M.bindElementBuffer.set(this.buffer),Wt.bufferData(Wt.ELEMENT_ARRAY_BUFFER,et.arrayBuffer,this.dynamicDraw?Wt.DYNAMIC_DRAW:Wt.STATIC_DRAW),this.dynamicDraw||delete et.arrayBuffer}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(M){const et=this.context.gl;if(!this.dynamicDraw)throw new Error("Attempted to update data while not in dynamic mode.");this.context.unbindVAO(),this.bind(),et.bufferSubData(et.ELEMENT_ARRAY_BUFFER,0,M.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}const dc={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class ir{constructor(M,et,Bt,Wt){this.length=et.length,this.attributes=Bt,this.itemSize=et.bytesPerElement,this.dynamicDraw=Wt,this.context=M;const Nt=M.gl;this.buffer=Nt.createBuffer(),M.bindVertexBuffer.set(this.buffer),Nt.bufferData(Nt.ARRAY_BUFFER,et.arrayBuffer,this.dynamicDraw?Nt.DYNAMIC_DRAW:Nt.STATIC_DRAW),this.dynamicDraw||delete et.arrayBuffer}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(M){if(M.length!==this.length)throw new Error(`Length of new data is ${M.length}, which doesn't match current length of ${this.length}`);const et=this.context.gl;this.bind(),et.bufferSubData(et.ARRAY_BUFFER,0,M.arrayBuffer)}enableAttributes(M,et){for(let Bt=0;Bt0&&(uo.push({circleArray:Ba,circleOffset:Po,coord:To}),Io+=Ba.length/4,Po=Io),Ia&&so.draw(Gr,Hn.LINES,Ot.disabled,Zt.disabled,M.colorModeForRenderPass(),jt.disabled,Di(M.transform),M.style.map.terrain&&M.style.map.terrain.getTerrainData(To),mn.getProjectionData({overscaledTileID:To,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),Wt.id,Ia.layoutVertexBuffer,Ia.indexBuffer,Ia.segments,null,M.transform.zoom,null,null,Ia.collisionVertexBuffer)}if(!$t||!uo.length)return;const To=M.useProgram("collisionCircle"),Eo=new et.bM;Eo.resize(4*Io),Eo._trim();let Ia=0;for(const M of uo)for(let et=0;et=0&&(Ba[Ta.associatedIconIndex]={shiftedAnchor:Sl,angle:Zl})}else Be(Ta.numGlyphs,Eo)}if(so){Ia.clear();const Bt=M.icon.placedSymbolArray;for(let M=0;MM.style.map.terrain.getElevation(Hn,et,Bt):null,Bt="map"===Wt.layout.get("text-rotation-alignment");Pe(so,M,$t,Dl,Nl,Va,uo,Bt,Hn.toUnwrapped(),Ba.width,Ba.height,Ol,et)}const $l=$t&&Ka||ql,tc=za||$l?yc:Va?Dl:M.transform.clipSpaceToPixelsMatrix,ec=Eo&&0!==Wt.paint.get($t?"text-halo-width":"icon-halo-width").constantOr(1);let dc;dc=Eo?so.iconsInText?$i(Da.kind,Zl,Fa,Va,za,$l,M,tc,Yl,Ol,Rl,El,$a):Xi(Da.kind,Zl,Fa,Va,za,$l,M,tc,Yl,Ol,$t,Rl,!0,$a):Wi(Da.kind,Zl,Fa,Va,za,$l,M,tc,Yl,Ol,$t,Rl,$a);const Ic={program:Sl,buffers:Io,uniformValues:dc,projectionData:jl,atlasTexture:Tl,atlasTextureIcon:Jl,atlasInterpolation:Vl,atlasInterpolationIcon:Wl,isSDF:Eo,hasHalo:ec};if(Ea&&so.canOverlap){La=!0;const M=Io.segments.get();for(const Bt of M)Oa.push({segments:new et.aD([Bt]),sortKey:Bt.sortKey,state:Ic,terrainData:Gl})}else Oa.push({segments:Io.segments,sortKey:0,state:Ic,terrainData:Gl})}La&&Oa.sort(((M,et)=>M.sortKey-et.sortKey));for(const et of Oa){const Bt=et.state;if(Eo.activeTexture.set(Ia.TEXTURE0),Bt.atlasTexture.bind(Bt.atlasInterpolation,Ia.CLAMP_TO_EDGE),Bt.atlasTextureIcon&&(Eo.activeTexture.set(Ia.TEXTURE1),Bt.atlasTextureIcon&&Bt.atlasTextureIcon.bind(Bt.atlasInterpolationIcon,Ia.CLAMP_TO_EDGE)),Bt.isSDF){const Nt=Bt.uniformValues;Bt.hasHalo&&(Nt.u_is_halo=1,Kr(Bt.buffers,et.segments,Wt,M,Bt.program,Da,Io,Po,Nt,Bt.projectionData,et.terrainData)),Nt.u_is_halo=0}Kr(Bt.buffers,et.segments,Wt,M,Bt.program,Da,Io,Po,Bt.uniformValues,Bt.projectionData,et.terrainData)}}function Kr(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn,so,uo){const Io=Wt.context;Nt.draw(Io,Io.gl.TRIANGLES,$t,Gr,mn,jt.backCCW,Hn,uo,so,Bt.id,M.layoutVertexBuffer,M.indexBuffer,et,Bt.paint,Wt.transform.zoom,M.programConfigurations.get(Bt.id),M.dynamicLayoutVertexBuffer,M.opacityVertexBuffer)}function Yr(M,Bt,Wt,Nt,$t){const Gr=M.context,mn=Gr.gl,Hn=Zt.disabled,so=new Ft([mn.ONE,mn.ONE],et.b4.transparent,[!0,!0,!0,!0]),uo=Bt.getBucket(Wt);if(!uo)return;const Io=Nt.key;let Po=Wt.heatmapFbos.get(Io);Po||(Po=Qr(Gr,Bt.tileSize,Bt.tileSize),Wt.heatmapFbos.set(Io,Po)),Gr.bindFramebuffer.set(Po.framebuffer),Gr.viewport.set([0,0,Bt.tileSize,Bt.tileSize]),Gr.clear({color:et.b4.transparent});const To=uo.programConfigurations.get(Wt.id),Eo=M.useProgram("heatmap",To,!$t),Ia=M.transform.getProjectionData({overscaledTileID:Bt.tileID,applyGlobeMatrix:!0,applyTerrainMatrix:!0}),Ba=M.style.map.terrain.getTerrainData(Nt);Eo.draw(Gr,mn.TRIANGLES,Ot.disabled,Hn,so,jt.disabled,Li(Bt,M.transform.zoom,Wt.paint.get("heatmap-intensity"),1),Ba,Ia,Wt.id,uo.layoutVertexBuffer,uo.indexBuffer,uo.segments,Wt.paint,M.transform.zoom,To)}function Jr(M,et,Bt,Wt,Nt){const $t=M.context,Gr=$t.gl,mn=M.transform;$t.setColorMode(M.colorModeForRenderPass());const Hn=eo($t,et),so=Bt.key,uo=et.heatmapFbos.get(so);if(!uo)return;$t.activeTexture.set(Gr.TEXTURE0),Gr.bindTexture(Gr.TEXTURE_2D,uo.colorAttachment.get()),$t.activeTexture.set(Gr.TEXTURE1),Hn.bind(Gr.LINEAR,Gr.CLAMP_TO_EDGE);const Io=mn.getProjectionData({overscaledTileID:Bt,applyTerrainMatrix:Nt,applyGlobeMatrix:!Wt});M.useProgram("heatmapTexture").draw($t,Gr.TRIANGLES,Ot.disabled,Zt.disabled,M.colorModeForRenderPass(),jt.disabled,ki(M,et,0,1),null,Io,et.id,M.rasterBoundsBuffer,M.quadTriangleIndexBuffer,M.rasterBoundsSegments,et.paint,mn.zoom),uo.destroy(),et.heatmapFbos.delete(so)}function Qr(M,et,Bt){var Wt,Nt;const $t=M.gl,Gr=$t.createTexture();$t.bindTexture($t.TEXTURE_2D,Gr),$t.texParameteri($t.TEXTURE_2D,$t.TEXTURE_WRAP_S,$t.CLAMP_TO_EDGE),$t.texParameteri($t.TEXTURE_2D,$t.TEXTURE_WRAP_T,$t.CLAMP_TO_EDGE),$t.texParameteri($t.TEXTURE_2D,$t.TEXTURE_MIN_FILTER,$t.LINEAR),$t.texParameteri($t.TEXTURE_2D,$t.TEXTURE_MAG_FILTER,$t.LINEAR);const mn=null!==(Wt=M.HALF_FLOAT)&&void 0!==Wt?Wt:$t.UNSIGNED_BYTE,Hn=null!==(Nt=M.RGBA16F)&&void 0!==Nt?Nt:$t.RGBA;$t.texImage2D($t.TEXTURE_2D,0,Hn,et,Bt,0,$t.RGBA,mn,null);const so=M.createFramebuffer(et,Bt,!1,!1);return so.colorAttachment.set(Gr),so}function eo(M,et){return et.colorRampTexture||(et.colorRampTexture=new v(M,et.colorRamp,M.gl.RGBA)),et.colorRampTexture}function to(M,et,Bt,Wt,Nt){if(!Bt||!Wt||!Wt.imageAtlas)return;const $t=Wt.imageAtlas.patternPositions;let Gr=$t[Bt.to.toString()],mn=$t[Bt.from.toString()];if(!Gr&&mn&&(Gr=mn),!mn&&Gr&&(mn=Gr),!Gr||!mn){const M=Nt.getPaintProperty(et);Gr=$t[M],mn=$t[M]}Gr&&mn&&M.setConstantPatternPositions(Gr,mn)}function io(M,Bt,Wt,Nt,$t,Gr,mn,Hn){const so=M.context.gl,uo="fill-pattern",Io=Wt.paint.get(uo),Po=Io&&Io.constantOr(1),To=Wt.getCrossfadeParameters();let Eo,Ia,Ba,Ta,Va;const za=M.transform,Fa=Wt.paint.get("fill-translate"),Ea=Wt.paint.get("fill-translate-anchor");mn?(Ia=Po&&!Wt.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",Eo=so.LINES):(Ia=Po?"fillPattern":"fill",Eo=so.TRIANGLES);const La=Io.constantOr(null);for(const Io of Nt){const Da=Bt.getTile(Io);if(Po&&!Da.patternsLoaded())continue;const Ka=Da.getBucket(Wt);if(!Ka)continue;const Oa=Ka.programConfigurations.get(Wt.id),$a=M.useProgram(Ia,Oa),Al=M.style.map.terrain&&M.style.map.terrain.getTerrainData(Io);Po&&(M.context.activeTexture.set(so.TEXTURE0),Da.imageAtlasTexture.bind(so.LINEAR,so.CLAMP_TO_EDGE),Oa.updatePaintBuffers(To)),to(Oa,uo,La,Da,Wt);const Sl=za.getProjectionData({overscaledTileID:Io,applyGlobeMatrix:!Hn,applyTerrainMatrix:!0}),Zl=et.au(za,Da,Fa,Ea);if(mn){Ta=Ka.indexBuffer2,Va=Ka.segments2;const et=[so.drawingBufferWidth,so.drawingBufferHeight];Ba="fillOutlinePattern"===Ia&&Po?Si(M,To,Da,et,Zl):Mi(et,Zl)}else Ta=Ka.indexBuffer,Va=Ka.segments,Ba=Po?Ei(M,To,Da,Zl):{u_fill_translate:Zl};let Gl;if("translucent"===M.renderPass&&Hn){const[et]=M.getStencilConfigForOverlapAndUpdateStencilID(Nt);Gl=et[Io.overscaledZ]}else Gl=M.stencilModeForClipping(Io);$a.draw(M.context,Eo,$t,Gl,Gr,jt.backCCW,Ba,Al,Sl,Wt.id,Ka.layoutVertexBuffer,Ta,Va,Wt.paint,M.transform.zoom,Oa)}}function ro(M,Bt,Wt,Nt,$t,Gr,mn,Hn){const so=M.context,uo=so.gl,Io="fill-extrusion-pattern",Po=Wt.paint.get(Io),To=Po.constantOr(1),Eo=Wt.getCrossfadeParameters(),Ia=Wt.paint.get("fill-extrusion-opacity"),Ba=Po.constantOr(null),Ta=M.transform;for(const Po of Nt){const Nt=Bt.getTile(Po),Va=Nt.getBucket(Wt);if(!Va)continue;const za=M.style.map.terrain&&M.style.map.terrain.getTerrainData(Po),Fa=Va.programConfigurations.get(Wt.id),Ea=M.useProgram(To?"fillExtrusionPattern":"fillExtrusion",Fa);To&&(M.context.activeTexture.set(uo.TEXTURE0),Nt.imageAtlasTexture.bind(uo.LINEAR,uo.CLAMP_TO_EDGE),Fa.updatePaintBuffers(Eo));const La=Ta.getProjectionData({overscaledTileID:Po,applyGlobeMatrix:!Hn,applyTerrainMatrix:!0});to(Fa,Io,Ba,Nt,Wt);const Da=et.au(Ta,Nt,Wt.paint.get("fill-extrusion-translate"),Wt.paint.get("fill-extrusion-translate-anchor")),Ka=Wt.paint.get("fill-extrusion-vertical-gradient"),Oa=To?Ii(M,Ka,Ia,Da,Po,Eo,Nt):Ci(M,Ka,Ia,Da);Ea.draw(so,so.gl.TRIANGLES,$t,Gr,mn,jt.backCCW,Oa,za,La,Wt.id,Va.layoutVertexBuffer,Va.indexBuffer,Va.segments,Wt.paint,M.transform.zoom,Fa,M.style.map.terrain&&Va.centroidVertexBuffer)}}function oo(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn){var so;const uo=M.style.projection,Io=M.context,Po=M.transform,To=Io.gl,Eo=M.useProgram("hillshade"),Ia=!M.options.moving;for(const Ba of Wt){const Wt=et.getTile(Ba),Ta=Wt.fbo;if(!Ta)continue;const Va=uo.getMeshFromTileID(Io,Ba.canonical,mn,!0,"raster"),za=null===(so=M.style.map.terrain)||void 0===so?void 0:so.getTerrainData(Ba);Io.activeTexture.set(To.TEXTURE0),To.bindTexture(To.TEXTURE_2D,Ta.colorAttachment.get());const Fa=Po.getProjectionData({overscaledTileID:Ba,aligned:Ia,applyGlobeMatrix:!Hn,applyTerrainMatrix:!0});Eo.draw(Io,To.TRIANGLES,$t,Nt[Ba.overscaledZ],Gr,jt.backCCW,Fi(M,Wt,Bt),za,Fa,Bt.id,Va.vertexBuffer,Va.indexBuffer,Va.segments)}}const vc=[new et.P(0,0),new et.P(et.X,0),new et.P(et.X,et.X),new et.P(0,et.X)];function ao(M,et,Bt,Wt,Nt,$t,Gr,mn,Hn=!1,so=!1){const uo=Wt[Wt.length-1].overscaledZ,Io=M.context,Po=Io.gl,To=M.useProgram("raster"),Eo=M.transform,Ia=M.style.projection,Ba=M.colorModeForRenderPass(),Ta=!M.options.moving;for(const Va of Wt){const Wt=M.getDepthModeForSublayer(Va.overscaledZ-uo,1===Bt.paint.get("raster-opacity")?Ot.ReadWrite:Ot.ReadOnly,Po.LESS),za=et.getTile(Va);za.registerFadeDuration(Bt.paint.get("raster-fade-duration"));const Fa=et.findLoadedParent(Va,0),Ea=et.findLoadedSibling(Va),La=no(za,Fa||Ea||null,et,Bt,M.transform,M.style.map.terrain);let Da,Ka;const Oa="nearest"===Bt.paint.get("raster-resampling")?Po.NEAREST:Po.LINEAR;Io.activeTexture.set(Po.TEXTURE0),za.texture.bind(Oa,Po.CLAMP_TO_EDGE,Po.LINEAR_MIPMAP_NEAREST),Io.activeTexture.set(Po.TEXTURE1),Fa?(Fa.texture.bind(Oa,Po.CLAMP_TO_EDGE,Po.LINEAR_MIPMAP_NEAREST),Da=Math.pow(2,Fa.tileID.overscaledZ-za.tileID.overscaledZ),Ka=[za.tileID.canonical.x*Da%1,za.tileID.canonical.y*Da%1]):za.texture.bind(Oa,Po.CLAMP_TO_EDGE,Po.LINEAR_MIPMAP_NEAREST),za.texture.useMipmap&&Io.extTextureFilterAnisotropic&&M.transform.pitch>20&&Po.texParameterf(Po.TEXTURE_2D,Io.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,Io.extTextureFilterAnisotropicMax);const $a=M.style.map.terrain&&M.style.map.terrain.getTerrainData(Va),Al=Eo.getProjectionData({overscaledTileID:Va,aligned:Ta,applyGlobeMatrix:!so,applyTerrainMatrix:!0}),Sl=qi(Ka||[0,0],Da||1,La,Bt,mn),Zl=Ia.getMeshFromTileID(Io,Va.canonical,$t,Gr,"raster");To.draw(Io,Po.TRIANGLES,Wt,Nt?Nt[Va.overscaledZ]:Zt.disabled,Ba,Hn?jt.frontCCW:jt.backCCW,Sl,$a,Al,Bt.id,Zl.vertexBuffer,Zl.indexBuffer,Zl.segments)}}function no(M,Bt,Wt,Nt,Gr,mn){const Hn=Nt.paint.get("raster-fade-duration");if(!mn&&Hn>0){const Nt=$t.now(),mn=(Nt-M.timeAdded)/Hn,so=Bt?(Nt-Bt.timeAdded)/Hn:-1,uo=Wt.getSource(),Io=he(Gr,{tileSize:uo.tileSize,roundZoom:uo.roundZoom}),Po=!Bt||Math.abs(Bt.tileID.overscaledZ-Io)>Math.abs(M.tileID.overscaledZ-Io),To=Po&&M.refreshedUponExpiration?1:et.ab(Po?mn:1-so,0,1);return M.refreshedUponExpiration&&mn>=1&&(M.refreshedUponExpiration=!1),Bt?{opacity:1,mix:1-To}:{opacity:To,mix:0}}return{opacity:1,mix:0}}const xc=new et.b4(1,0,0,1),Bc=new et.b4(0,1,0,1),Tc=new et.b4(0,0,1,1),Mc=new et.b4(1,0,1,1),Vc=new et.b4(0,1,1,1);function po(M,et,Bt,Wt){fo(M,0,et+Bt/2,M.transform.width,Bt,Wt)}function mo(M,et,Bt,Wt){fo(M,et-Bt/2,0,Bt,M.transform.height,Wt)}function fo(M,et,Bt,Wt,Nt,$t){const Gr=M.context,mn=Gr.gl;mn.enable(mn.SCISSOR_TEST),mn.scissor(et*M.pixelRatio,Bt*M.pixelRatio,Wt*M.pixelRatio,Nt*M.pixelRatio),Gr.clear({color:$t}),mn.disable(mn.SCISSOR_TEST)}function go(M,Bt,Wt){const Nt=M.context,$t=Nt.gl,Gr=M.useProgram("debug"),mn=Ot.disabled,Hn=Zt.disabled,so=M.colorModeForRenderPass(),uo="$debug",Io=M.style.map.terrain&&M.style.map.terrain.getTerrainData(Wt);Nt.activeTexture.set($t.TEXTURE0);const Po=Bt.getTileByID(Wt.key).latestRawTileData,To=Math.floor((Po&&Po.byteLength||0)/1024),Eo=Bt.getTile(Wt).tileSize,Ia=512/Math.min(Eo,512)*(Wt.overscaledZ/M.transform.zoom)*.5;let Ba=Wt.canonical.toString();Wt.overscaledZ!==Wt.canonical.z&&(Ba+=` => ${Wt.overscaledZ}`),function(M,et){M.initDebugOverlayCanvas();const Bt=M.debugOverlayCanvas,Wt=M.context.gl,Nt=M.debugOverlayCanvas.getContext("2d");Nt.clearRect(0,0,Bt.width,Bt.height),Nt.shadowColor="white",Nt.shadowBlur=2,Nt.lineWidth=1.5,Nt.strokeStyle="white",Nt.textBaseline="top",Nt.font="bold 36px Open Sans, sans-serif",Nt.fillText(et,5,5),Nt.strokeText(et,5,5),M.debugOverlayTexture.update(Bt),M.debugOverlayTexture.bind(Wt.LINEAR,Wt.CLAMP_TO_EDGE)}(M,`${Ba} ${To}kB`);const Ta=M.transform.getProjectionData({overscaledTileID:Wt,applyGlobeMatrix:!0,applyTerrainMatrix:!0});Gr.draw(Nt,$t.TRIANGLES,mn,Hn,Ft.alphaBlended,jt.disabled,Ai(et.b4.transparent,Ia),null,Ta,uo,M.debugBuffer,M.quadTriangleIndexBuffer,M.debugSegments),Gr.draw(Nt,$t.LINE_STRIP,mn,Hn,so,jt.disabled,Ai(et.b4.red),Io,Ta,uo,M.debugBuffer,M.tileBorderIndexBuffer,M.debugSegments)}function vo(M,et,Bt,Wt){const{isRenderingGlobe:Nt}=Wt,$t=M.context,Gr=$t.gl,mn=M.transform,Hn=M.colorModeForRenderPass(),so=M.getDepthModeFor3D(),uo=M.useProgram("terrain");$t.bindFramebuffer.set(null),$t.viewport.set([0,0,M.width,M.height]);for(const Wt of Bt){const Bt=et.getTerrainMesh(Wt.tileID),Io=M.renderToTexture.getTexture(Wt),Po=et.getTerrainData(Wt.tileID);$t.activeTexture.set(Gr.TEXTURE0),Gr.bindTexture(Gr.TEXTURE_2D,Io.texture);const To=et.getMeshFrameDelta(mn.zoom),Eo=mn.calculateFogMatrix(Wt.tileID.toUnwrapped()),Ia=bi(To,Eo,M.style.sky,mn.pitch,Nt),Ba=mn.getProjectionData({overscaledTileID:Wt.tileID,applyTerrainMatrix:!1,applyGlobeMatrix:!0});uo.draw($t,Gr.TRIANGLES,so,Zt.disabled,Hn,jt.backCCW,Ia,Po,Ba,"terrain",Bt.vertexBuffer,Bt.indexBuffer,Bt.segments)}}function xo(M,Bt){if(!Bt.mesh){const Wt=new et.aC;Wt.emplaceBack(-1,-1),Wt.emplaceBack(1,-1),Wt.emplaceBack(1,1),Wt.emplaceBack(-1,1);const Nt=new et.aE;Nt.emplaceBack(0,1,2),Nt.emplaceBack(0,2,3),Bt.mesh=new pt(M.createVertexBuffer(Wt,El.members),M.createIndexBuffer(Nt),et.aD.simpleSegment(0,0,Wt.length,Nt.length))}return Bt.mesh}class bo{constructor(M,Bt){this.context=new Zr(M),this.transform=Bt,this._tileTextures={},this.terrainFacilitator={dirty:!0,matrix:et.aq(new Float64Array(16)),renderTime:0},this.setup(),this.numSublayers=de.maxUnderzooming+de.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.crossTileSymbolIndex=new ht}resize(M,et,Bt){if(this.width=Math.floor(M*Bt),this.height=Math.floor(et*Bt),this.pixelRatio=Bt,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const M of this.style._order)this.style._layers[M].resize()}setup(){const M=this.context,Bt=new et.aC;Bt.emplaceBack(0,0),Bt.emplaceBack(et.X,0),Bt.emplaceBack(0,et.X),Bt.emplaceBack(et.X,et.X),this.tileExtentBuffer=M.createVertexBuffer(Bt,El.members),this.tileExtentSegments=et.aD.simpleSegment(0,0,4,2);const Wt=new et.aC;Wt.emplaceBack(0,0),Wt.emplaceBack(et.X,0),Wt.emplaceBack(0,et.X),Wt.emplaceBack(et.X,et.X),this.debugBuffer=M.createVertexBuffer(Wt,El.members),this.debugSegments=et.aD.simpleSegment(0,0,4,5);const Nt=new et.bT;Nt.emplaceBack(0,0,0,0),Nt.emplaceBack(et.X,0,et.X,0),Nt.emplaceBack(0,et.X,0,et.X),Nt.emplaceBack(et.X,et.X,et.X,et.X),this.rasterBoundsBuffer=M.createVertexBuffer(Nt,$l.members),this.rasterBoundsSegments=et.aD.simpleSegment(0,0,4,2);const $t=new et.aC;$t.emplaceBack(0,0),$t.emplaceBack(et.X,0),$t.emplaceBack(0,et.X),$t.emplaceBack(et.X,et.X),this.rasterBoundsBufferPosOnly=M.createVertexBuffer($t,El.members),this.rasterBoundsSegmentsPosOnly=et.aD.simpleSegment(0,0,4,5);const Gr=new et.aC;Gr.emplaceBack(0,0),Gr.emplaceBack(1,0),Gr.emplaceBack(0,1),Gr.emplaceBack(1,1),this.viewportBuffer=M.createVertexBuffer(Gr,El.members),this.viewportSegments=et.aD.simpleSegment(0,0,4,2);const mn=new et.bU;mn.emplaceBack(0),mn.emplaceBack(1),mn.emplaceBack(3),mn.emplaceBack(2),mn.emplaceBack(0),this.tileBorderIndexBuffer=M.createIndexBuffer(mn);const Hn=new et.aE;Hn.emplaceBack(1,0,2),Hn.emplaceBack(1,2,3),this.quadTriangleIndexBuffer=M.createIndexBuffer(Hn);const so=this.context.gl;this.stencilClearMode=new Zt({func:so.ALWAYS,mask:0},0,255,so.ZERO,so.ZERO,so.ZERO),this.tileExtentMesh=new pt(this.tileExtentBuffer,this.quadTriangleIndexBuffer,this.tileExtentSegments)}clearStencil(){const M=this.context,Bt=M.gl;this.nextStencilID=1,this.currentStencilSource=void 0;const Wt=et.H();et.bL(Wt,0,this.width,this.height,0,0,1),et.K(Wt,Wt,[Bt.drawingBufferWidth,Bt.drawingBufferHeight,0]);const Nt={mainMatrix:Wt,tileMercatorCoords:[0,0,1,1],clippingPlane:[0,0,0,0],projectionTransition:0,fallbackMatrix:Wt};this.useProgram("clippingMask",null,!0).draw(M,Bt.TRIANGLES,Ot.disabled,this.stencilClearMode,Ft.disabled,jt.disabled,null,null,Nt,"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}_renderTileClippingMasks(M,et,Bt){if(this.currentStencilSource===M.source||!M.isTileClipped()||!et||!et.length)return;this.currentStencilSource=M.source,this.nextStencilID+et.length>256&&this.clearStencil();const Wt=this.context;Wt.setColorMode(Ft.disabled),Wt.setDepthMode(Ot.disabled);const Nt={};for(const M of et)Nt[M.key]=this.nextStencilID++;this._renderTileMasks(Nt,et,Bt,!0),this._renderTileMasks(Nt,et,Bt,!1),this._tileClippingMaskIDs=Nt}_renderTileMasks(M,et,Bt,Wt){const Nt=this.context,$t=Nt.gl,Gr=this.style.projection,mn=this.transform,Hn=this.useProgram("clippingMask");for(const so of et){const et=M[so.key],uo=this.style.map.terrain&&this.style.map.terrain.getTerrainData(so),Io=Gr.getMeshFromTileID(this.context,so.canonical,Wt,!0,"stencil"),Po=mn.getProjectionData({overscaledTileID:so,applyGlobeMatrix:!0,applyTerrainMatrix:!0});Hn.draw(Nt,$t.TRIANGLES,Ot.disabled,new Zt({func:$t.ALWAYS,mask:0},et,255,$t.KEEP,$t.KEEP,$t.REPLACE),Ft.disabled,Bt?jt.disabled:jt.backCCW,null,uo,Po,"$clipping",Io.vertexBuffer,Io.indexBuffer,Io.segments)}}_renderTilesDepthBuffer(){const M=this.context,et=M.gl,Bt=this.style.projection,Wt=this.transform,Nt=this.useProgram("depth"),$t=this.getDepthModeFor3D(),Gr=ue(Wt,{tileSize:Wt.tileSize});for(const mn of Gr){const Gr=this.style.map.terrain&&this.style.map.terrain.getTerrainData(mn),Hn=Bt.getMeshFromTileID(this.context,mn.canonical,!0,!0,"raster"),so=Wt.getProjectionData({overscaledTileID:mn,applyGlobeMatrix:!0,applyTerrainMatrix:!0});Nt.draw(M,et.TRIANGLES,$t,Zt.disabled,Ft.disabled,jt.backCCW,null,Gr,so,"$clipping",Hn.vertexBuffer,Hn.indexBuffer,Hn.segments)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const M=this.nextStencilID++,et=this.context.gl;return new Zt({func:et.NOTEQUAL,mask:255},M,255,et.KEEP,et.KEEP,et.REPLACE)}stencilModeForClipping(M){const et=this.context.gl;return new Zt({func:et.EQUAL,mask:255},this._tileClippingMaskIDs[M.key],0,et.KEEP,et.KEEP,et.REPLACE)}getStencilConfigForOverlapAndUpdateStencilID(M){const et=this.context.gl,Bt=M.sort(((M,et)=>et.overscaledZ-M.overscaledZ)),Wt=Bt[Bt.length-1].overscaledZ,Nt=Bt[0].overscaledZ-Wt+1;if(Nt>1){this.currentStencilSource=void 0,this.nextStencilID+Nt>256&&this.clearStencil();const M={};for(let Bt=0;Btet.overscaledZ-M.overscaledZ)),Wt=Bt[Bt.length-1].overscaledZ,Nt=Bt[0].overscaledZ-Wt+1;if(this.clearStencil(),Nt>1){const M={},$t={};for(let Bt=0;Bt0};for(const M in mn){const et=mn[M];et.used&&et.prepare(this.context),Hn[M]=et.getVisibleCoordinates(!1),so[M]=Hn[M].slice().reverse(),uo[M]=et.getVisibleCoordinates(!0).reverse()}this.opaquePassCutoff=1/0;for(let M=0;Mthis.useProgram(M)}),this.context.viewport.set([0,0,this.width,this.height]),this.context.bindFramebuffer.set(null),this.context.clear({color:Bt.showOverdrawInspector?et.b4.black:et.b4.transparent,depth:1}),this.clearStencil(),this.style.sky&&function(M,et){const Bt=M.context,Wt=Bt.gl,Nt=((M,et,Bt)=>{const Wt=Math.cos(et.rollInRadians),Nt=Math.sin(et.rollInRadians),$t=yt(et),Gr=et.getProjectionData({overscaledTileID:null,applyGlobeMatrix:!0,applyTerrainMatrix:!0}).projectionTransition;return{u_sky_color:M.properties.get("sky-color"),u_horizon_color:M.properties.get("horizon-color"),u_horizon:[(et.width/2-$t*Nt)*Bt,(et.height/2+$t*Wt)*Bt],u_horizon_normal:[-Nt,Wt],u_sky_horizon_blend:M.properties.get("sky-horizon-blend")*et.height/2*Bt,u_sky_blend:Gr}})(et,M.style.map.transform,M.pixelRatio),$t=new Ot(Wt.LEQUAL,Ot.ReadWrite,[0,1]),Gr=Zt.disabled,mn=M.colorModeForRenderPass(),Hn=M.useProgram("sky"),so=xo(Bt,et);Hn.draw(Bt,Wt.TRIANGLES,$t,Gr,mn,jt.disabled,Nt,null,void 0,"sky",so.vertexBuffer,so.indexBuffer,so.segments)}(this,this.style.sky),this._showOverdrawInspector=Bt.showOverdrawInspector,this.depthRangeFor3D=[0,1-(M._order.length+2)*this.numSublayers*this.depthEpsilon],!this.renderToTexture)for(this.renderPass="opaque",this.currentLayer=Gr.length-1;this.currentLayer>=0;this.currentLayer--){const M=this.style._layers[Gr[this.currentLayer]],et=mn[M.source],Bt=Hn[M.source];this._renderTileClippingMasks(M,Bt,!1),this.renderLayer(this,et,M,Bt,Io)}this.renderPass="translucent";let Po=!1;for(this.currentLayer=0;this.currentLayer({u_sun_pos:M,u_atmosphere_blend:et,u_globe_position:Bt,u_globe_radius:Wt,u_inv_proj_matrix:Nt}))(so,Io,[Eo[0],Eo[1],Eo[2]],Po,To),Ba=xo(Nt,Bt);Gr.draw(Nt,$t.TRIANGLES,mn,Zt.disabled,Ft.alphaBlended,jt.disabled,Ia,null,null,"atmosphere",Ba.vertexBuffer,Ba.indexBuffer,Ba.segments)}(this,this.style.sky,this.style.light),this.options.showTileBoundaries){const M=function(M,et){let Bt=null;const Wt=Object.values(M._layers).flatMap((Bt=>Bt.source&&!Bt.isHidden(et)?[M.sourceCaches[Bt.source]]:[])),Nt=Wt.filter((M=>"vector"===M.getSource().type)),$t=Wt.filter((M=>"vector"!==M.getSource().type)),a=M=>{(!Bt||Bt.getSource().maxzooma(M))),Bt||$t.forEach((M=>a(M))),Bt}(this.style,this.transform.zoom);M&&function(M,et,Bt){for(let Wt=0;WtIo.getElevation($t,M,et):null;Wr(Gr,Po,To,so,uo,Ba,Bt,Eo,Ta,et.au(uo,M,mn,Hn),$t.toUnwrapped(),Wt)}}}(Nt,M,Wt,Bt,Wt.layout.get("text-rotation-alignment"),Wt.layout.get("text-pitch-alignment"),Wt.paint.get("text-translate"),Wt.paint.get("text-translate-anchor"),$t),0!==Wt.paint.get("icon-opacity").constantOr(1)&&$r(M,Bt,Wt,Nt,!1,Wt.paint.get("icon-translate"),Wt.paint.get("icon-translate-anchor"),Wt.layout.get("icon-rotation-alignment"),Wt.layout.get("icon-pitch-alignment"),Wt.layout.get("icon-keep-upright"),Hn,so,mn),0!==Wt.paint.get("text-opacity").constantOr(1)&&$r(M,Bt,Wt,Nt,!0,Wt.paint.get("text-translate"),Wt.paint.get("text-translate-anchor"),Wt.layout.get("text-rotation-alignment"),Wt.layout.get("text-pitch-alignment"),Wt.layout.get("text-keep-upright"),Hn,so,mn),Bt.map.showCollisionBoxes&&(Ur(M,Bt,Wt,Nt,!0),Ur(M,Bt,Wt,Nt,!1))}(M,Bt,Wt,Nt,this.style.placement.variableOffsets,$t):et.bZ(Wt)?function(M,Bt,Wt,Nt,$t){if("translucent"!==M.renderPass)return;const{isRenderingToTexture:Gr}=$t,mn=Wt.paint.get("circle-opacity"),Hn=Wt.paint.get("circle-stroke-width"),so=Wt.paint.get("circle-stroke-opacity"),uo=!Wt.layout.get("circle-sort-key").isConstant();if(0===mn.constantOr(1)&&(0===Hn.constantOr(1)||0===so.constantOr(1)))return;const Io=M.context,Po=Io.gl,To=M.transform,Eo=M.getDepthModeForSublayer(0,Ot.ReadOnly),Ia=Zt.disabled,Ba=M.colorModeForRenderPass(),Ta=[],Va=To.getCircleRadiusCorrection();for(let $t=0;$tM.sortKey-et.sortKey));for(const et of Ta){const{programConfiguration:Bt,program:Nt,layoutVertexBuffer:$t,indexBuffer:Gr,uniformValues:mn,terrainData:Hn,projectionData:so}=et.state;Nt.draw(Io,Po.TRIANGLES,Eo,Ia,Ba,jt.backCCW,mn,Hn,so,Wt.id,$t,Gr,et.segments,Wt.paint,M.transform.zoom,Bt)}}(M,Bt,Wt,Nt,$t):et.b_(Wt)?function(M,Bt,Wt,Nt,$t){if(0===Wt.paint.get("heatmap-opacity"))return;const Gr=M.context,{isRenderingToTexture:mn,isRenderingGlobe:Hn}=$t;if(M.style.map.terrain){for(const et of Nt){const Nt=Bt.getTile(et);Bt.hasRenderableParent(et)||("offscreen"===M.renderPass?Yr(M,Nt,Wt,et,Hn):"translucent"===M.renderPass&&Jr(M,Wt,et,mn,Hn))}Gr.viewport.set([0,0,M.width,M.height])}else"offscreen"===M.renderPass?function(M,Bt,Wt,Nt){const $t=M.context,Gr=$t.gl,mn=M.transform,Hn=Zt.disabled,so=new Ft([Gr.ONE,Gr.ONE],et.b4.transparent,[!0,!0,!0,!0]);(function(M,Bt,Wt){const Nt=M.gl;M.activeTexture.set(Nt.TEXTURE1),M.viewport.set([0,0,Bt.width/4,Bt.height/4]);let $t=Wt.heatmapFbos.get(et.bP);$t?(Nt.bindTexture(Nt.TEXTURE_2D,$t.colorAttachment.get()),M.bindFramebuffer.set($t.framebuffer)):($t=Qr(M,Bt.width/4,Bt.height/4),Wt.heatmapFbos.set(et.bP,$t))})($t,M,Wt),$t.clear({color:et.b4.transparent});for(let et=0;et0?et.pop():null}isPatternMissing(M){if(!M)return!1;if(!M.from||!M.to)return!0;const et=this.imageManager.getPattern(M.from.toString()),Bt=this.imageManager.getPattern(M.to.toString());return!et||!Bt}useProgram(M,et,Bt=!1){this.cache=this.cache||{};const Wt=!!this.style.map.terrain,Nt=this.style.projection,$t=M+(et?et.cacheKey:"")+`/${Bt?Ll:Nt.shaderVariantName}`+(this._showOverdrawInspector?"/overdraw":"")+(Wt?"/terrain":"");return this.cache[$t]||(this.cache[$t]=new Ti(this.context,Wl[M],et,ec[M],this._showOverdrawInspector,Wt,Bt?Wl.projectionMercator:Nt.shaderPreludeCode,Bt?Jl:Nt.shaderDefine)),this.cache[$t]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault()}setBaseState(){const M=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(M.FUNC_ADD)}initDebugOverlayCanvas(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new v(this.context,this.debugOverlayCanvas,this.context.gl.RGBA))}destroy(){this.debugOverlayTexture&&this.debugOverlayTexture.destroy()}overLimit(){const{drawingBufferWidth:M,drawingBufferHeight:et}=this.context.gl;return this.width!==M||this.height!==et}}function yo(M,et){let Bt,Wt=!1,Nt=null,$t=null;const a=()=>{Nt=null,Wt&&(M.apply($t,Bt),Nt=setTimeout(a,et),Wt=!1)};return(...M)=>(Wt=!0,$t=this,Bt=M,Nt||a(),Nt)}class wo{constructor(M){this._getCurrentHash=()=>{const M=window.location.hash.replace("#","");if(this._hashName){let et;return M.split("&").map((M=>M.split("="))).forEach((M=>{M[0]===this._hashName&&(et=M)})),(et&&et[1]||"").split("/")}return M.split("/")},this._onHashChange=()=>{const M=this._getCurrentHash();if(!this._isValidHash(M))return!1;const et=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(M[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+M[2],+M[1]],zoom:+M[0],bearing:et,pitch:+(M[4]||0)}),!0},this._updateHashUnthrottled=()=>{const M=window.location.href.replace(/(#.*)?$/,this.getHashString());window.history.replaceState(window.history.state,null,M)},this._removeHash=()=>{const M=this._getCurrentHash();if(0===M.length)return;const et=M.join("/");let Bt=et;Bt.split("&").length>0&&(Bt=Bt.split("&")[0]),this._hashName&&(Bt=`${this._hashName}=${et}`);let Wt=window.location.hash.replace(Bt,"");Wt.startsWith("#&")?Wt=Wt.slice(0,1)+Wt.slice(2):"#"===Wt&&(Wt="");let Nt=window.location.href.replace(/(#.+)?$/,Wt);Nt=Nt.replace("&&","&"),window.history.replaceState(window.history.state,null,Nt)},this._updateHash=yo(this._updateHashUnthrottled,300),this._hashName=M&&encodeURIComponent(M)}addTo(M){return this._map=M,addEventListener("hashchange",this._onHashChange,!1),this._map.on("moveend",this._updateHash),this}remove(){return removeEventListener("hashchange",this._onHashChange,!1),this._map.off("moveend",this._updateHash),clearTimeout(this._updateHash()),this._removeHash(),delete this._map,this}getHashString(M){const et=this._map.getCenter(),Bt=Math.round(100*this._map.getZoom())/100,Wt=Math.ceil((Bt*Math.LN2+Math.log(512/360/.5))/Math.LN10),Nt=Math.pow(10,Wt),$t=Math.round(et.lng*Nt)/Nt,Gr=Math.round(et.lat*Nt)/Nt,mn=this._map.getBearing(),Hn=this._map.getPitch();let so="";if(so+=M?`/${$t}/${Gr}/${Bt}`:`${Bt}/${Gr}/${$t}`,(mn||Hn)&&(so+="/"+Math.round(10*mn)/10),Hn&&(so+=`/${Math.round(Hn)}`),this._hashName){const M=this._hashName;let et=!1;const Bt=window.location.hash.slice(1).split("&").map((Bt=>{const Wt=Bt.split("=")[0];return Wt===M?(et=!0,`${Wt}=${so}`):Bt})).filter((M=>M));return et||Bt.push(`${M}=${so}`),`#${Bt.join("&")}`}return`#${so}`}_isValidHash(M){if(M.length<3||M.some(isNaN))return!1;try{new et.N(+M[2],+M[1])}catch(M){return!1}const Bt=+M[0],Wt=+(M[3]||0),Nt=+(M[4]||0);return Bt>=this._map.getMinZoom()&&Bt<=this._map.getMaxZoom()&&Wt>=0&&Wt<=180&&Nt>=this._map.getMinPitch()&&Nt<=this._map.getMaxPitch()}}const zc={linearity:.3,easing:et.c6(0,0,.3,1)},Fc=et.e({deceleration:2500,maxSpeed:1400},zc),Oc=et.e({deceleration:20,maxSpeed:1400},zc),jc=et.e({deceleration:1e3,maxSpeed:360},zc),mh=et.e({deceleration:1e3,maxSpeed:90},zc),Ih=et.e({deceleration:1e3,maxSpeed:360},zc);class So{constructor(M){this._map=M,this.clear()}clear(){this._inertiaBuffer=[]}record(M){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:$t.now(),settings:M})}_drainInertiaBuffer(){const M=this._inertiaBuffer,et=$t.now();for(;M.length>0&&et-M[0].time>160;)M.shift()}_onMoveEnd(M){if(this._drainInertiaBuffer(),this._inertiaBuffer.length<2)return;const Bt={zoom:0,bearing:0,pitch:0,roll:0,pan:new et.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:M}of this._inertiaBuffer)Bt.zoom+=M.zoomDelta||0,Bt.bearing+=M.bearingDelta||0,Bt.pitch+=M.pitchDelta||0,Bt.roll+=M.rollDelta||0,M.panDelta&&Bt.pan._add(M.panDelta),M.around&&(Bt.around=M.around),M.pinchAround&&(Bt.pinchAround=M.pinchAround);const Wt=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,Nt={};if(Bt.pan.mag()){const $t=Do(Bt.pan.mag(),Wt,et.e({},Fc,M||{})),Gr=Bt.pan.mult($t.amount/Bt.pan.mag()),mn=this._map.cameraHelper.handlePanInertia(Gr,this._map.transform);Nt.center=mn.easingCenter,Nt.offset=mn.easingOffset,Ro(Nt,$t)}if(Bt.zoom){const M=Do(Bt.zoom,Wt,Oc);Nt.zoom=this._map.transform.zoom+M.amount,Ro(Nt,M)}if(Bt.bearing){const M=Do(Bt.bearing,Wt,jc);Nt.bearing=this._map.transform.bearing+et.ab(M.amount,-179,179),Ro(Nt,M)}if(Bt.pitch){const M=Do(Bt.pitch,Wt,mh);Nt.pitch=this._map.transform.pitch+M.amount,Ro(Nt,M)}if(Bt.roll){const M=Do(Bt.roll,Wt,Ih);Nt.roll=this._map.transform.roll+et.ab(M.amount,-179,179),Ro(Nt,M)}if(Nt.zoom||Nt.bearing){const M=void 0===Bt.pinchAround?Bt.around:Bt.pinchAround;Nt.around=M?this._map.unproject(M):this._map.getCenter()}return this.clear(),et.e(Nt,{noMoveStart:!0})}}function Ro(M,et){(!M.duration||M.durationBt.unproject(M))),mn=$t.reduce(((M,et,Bt,Wt)=>M.add(et.div(Wt.length))),new et.P(0,0));super(M,{points:$t,point:mn,lngLats:Gr,lngLat:Bt.unproject(mn),originalEvent:Wt}),this._defaultPrevented=!1}}class Lo extends et.k{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(M,et,Bt){super(M,{originalEvent:Bt}),this._defaultPrevented=!1}}class ko{constructor(M,et){this._map=M,this._clickTolerance=et.clickTolerance}reset(){delete this._mousedownPos}wheel(M){return this._firePreventable(new Lo(M.type,this._map,M))}mousedown(M,et){return this._mousedownPos=et,this._firePreventable(new zo(M.type,this._map,M))}mouseup(M){this._map.fire(new zo(M.type,this._map,M))}click(M,et){this._mousedownPos&&this._mousedownPos.dist(et)>=this._clickTolerance||this._map.fire(new zo(M.type,this._map,M))}dblclick(M){return this._firePreventable(new zo(M.type,this._map,M))}mouseover(M){this._map.fire(new zo(M.type,this._map,M))}mouseout(M){this._map.fire(new zo(M.type,this._map,M))}touchstart(M){return this._firePreventable(new Ao(M.type,this._map,M))}touchmove(M){this._map.fire(new Ao(M.type,this._map,M))}touchend(M){this._map.fire(new Ao(M.type,this._map,M))}touchcancel(M){this._map.fire(new Ao(M.type,this._map,M))}_firePreventable(M){if(this._map.fire(M),M.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Fo{constructor(M){this._map=M}reset(){this._delayContextMenu=!1,this._ignoreContextMenu=!0,delete this._contextMenuEvent}mousemove(M){this._map.fire(new zo(M.type,this._map,M))}mousedown(){this._delayContextMenu=!0,this._ignoreContextMenu=!1}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new zo("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(M){this._delayContextMenu?this._contextMenuEvent=M:this._ignoreContextMenu||this._map.fire(new zo(M.type,this._map,M)),this._map.listens("contextmenu")&&M.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Bo{constructor(M){this._map=M}get transform(){return this._map._requestedCameraState||this._map.transform}get center(){return{lng:this.transform.center.lng,lat:this.transform.center.lat}}get zoom(){return this.transform.zoom}get pitch(){return this.transform.pitch}get bearing(){return this.transform.bearing}unproject(M){return this.transform.screenPointToLocation(et.P.convert(M),this._map.terrain)}}class jo{constructor(M,et){this._map=M,this._tr=new Bo(M),this._el=M.getCanvasContainer(),this._container=M.getContainer(),this._clickTolerance=et.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(M,et){this.isEnabled()&&M.shiftKey&&0===M.button&&(n.disableDrag(),this._startPos=this._lastPos=et,this._active=!0)}mousemoveWindow(M,et){if(!this._active)return;const Bt=et;if(this._lastPos.equals(Bt)||!this._box&&Bt.dist(this._startPos)M.fitScreenCoordinates(Wt,Nt,this._tr.bearing,{linear:!0})};this._fireEvent("boxzoomcancel",M)}keydown(M){this._active&&27===M.keyCode&&(this.reset(),this._fireEvent("boxzoomcancel",M))}reset(){this._active=!1,this._container.classList.remove("maplibregl-crosshair"),this._box&&(n.remove(this._box),this._box=null),n.enableDrag(),delete this._startPos,delete this._lastPos}_fireEvent(M,Bt){return this._map.fire(new et.k(M,{originalEvent:Bt}))}}function Oo(M,et){if(M.length!==et.length)throw new Error(`The number of touches and points are not equal - touches ${M.length}, points ${et.length}`);const Bt={};for(let Wt=0;Wtthis.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=M.timeStamp),Wt.length===this.numTouches&&(this.centroid=function(M){const Bt=new et.P(0,0);for(const et of M)Bt._add(et);return Bt.div(M.length)}(Bt),this.touches=Oo(Wt,Bt)))}touchmove(M,et,Bt){if(this.aborted||!this.centroid)return;const Wt=Oo(Bt,et);for(const M in this.touches){const et=Wt[M];(!et||et.dist(this.touches[M])>30)&&(this.aborted=!0)}}touchend(M,et,Bt){if((!this.centroid||M.timeStamp-this.startTime>500)&&(this.aborted=!0),0===Bt.length){const M=!this.aborted&&this.centroid;if(this.reset(),M)return M}}}class Zo{constructor(M){this.singleTap=new No(M),this.numTaps=M.numTaps,this.reset()}reset(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset()}touchstart(M,et,Bt){this.singleTap.touchstart(M,et,Bt)}touchmove(M,et,Bt){this.singleTap.touchmove(M,et,Bt)}touchend(M,et,Bt){const Wt=this.singleTap.touchend(M,et,Bt);if(Wt){const et=M.timeStamp-this.lastTime<500,Bt=!this.lastTap||this.lastTap.dist(Wt)<30;if(et&&Bt||this.reset(),this.count++,this.lastTime=M.timeStamp,this.lastTap=Wt,this.count===this.numTaps)return this.reset(),Wt}}}class Go{constructor(M){this._tr=new Bo(M),this._zoomIn=new Zo({numTouches:1,numTaps:2}),this._zoomOut=new Zo({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(M,et,Bt){this._zoomIn.touchstart(M,et,Bt),this._zoomOut.touchstart(M,et,Bt)}touchmove(M,et,Bt){this._zoomIn.touchmove(M,et,Bt),this._zoomOut.touchmove(M,et,Bt)}touchend(M,et,Bt){const Wt=this._zoomIn.touchend(M,et,Bt),Nt=this._zoomOut.touchend(M,et,Bt),$t=this._tr;return Wt?(this._active=!0,M.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:et=>et.easeTo({duration:300,zoom:$t.zoom+1,around:$t.unproject(Wt)},{originalEvent:M})}):Nt?(this._active=!0,M.preventDefault(),setTimeout((()=>this.reset()),0),{cameraAnimation:et=>et.easeTo({duration:300,zoom:$t.zoom-1,around:$t.unproject(Nt)},{originalEvent:M})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class Uo{constructor(M){this._enabled=!!M.enable,this._moveStateManager=M.moveStateManager,this._clickTolerance=M.clickTolerance||1,this._moveFunction=M.move,this._activateOnStart=!!M.activateOnStart,M.assignEvents(this),this.reset()}reset(M){this._active=!1,this._moved=!1,delete this._lastPoint,this._moveStateManager.endMove(M)}_move(...M){const et=this._moveFunction(...M);if(et.bearingDelta||et.pitchDelta||et.rollDelta||et.around||et.panDelta)return this._active=!0,et}dragStart(M,et){this.isEnabled()&&!this._lastPoint&&this._moveStateManager.isValidStartEvent(M)&&(this._moveStateManager.startMove(M),this._lastPoint=Array.isArray(et)?et[0]:et,this._activateOnStart&&this._lastPoint&&(this._active=!0))}dragMove(M,et){if(!this.isEnabled())return;const Bt=this._lastPoint;if(!Bt)return;if(M.preventDefault(),!this._moveStateManager.isValidMoveEvent(M))return void this.reset(M);const Wt=Array.isArray(et)?et[0]:et;return!this._moved&&Wt.dist(Bt)!0}),et=new Ho){this.mouseMoveStateManager=M,this.oneFingerTouchMoveStateManager=et}_executeRelevantHandler(M,et,Bt){return M instanceof MouseEvent?et(M):"undefined"!=typeof TouchEvent&&M instanceof TouchEvent?Bt(M):void 0}startMove(M){this._executeRelevantHandler(M,(M=>this.mouseMoveStateManager.startMove(M)),(M=>this.oneFingerTouchMoveStateManager.startMove(M)))}endMove(M){this._executeRelevantHandler(M,(M=>this.mouseMoveStateManager.endMove(M)),(M=>this.oneFingerTouchMoveStateManager.endMove(M)))}isValidStartEvent(M){return this._executeRelevantHandler(M,(M=>this.mouseMoveStateManager.isValidStartEvent(M)),(M=>this.oneFingerTouchMoveStateManager.isValidStartEvent(M)))}isValidMoveEvent(M){return this._executeRelevantHandler(M,(M=>this.mouseMoveStateManager.isValidMoveEvent(M)),(M=>this.oneFingerTouchMoveStateManager.isValidMoveEvent(M)))}isValidEndEvent(M){return this._executeRelevantHandler(M,(M=>this.mouseMoveStateManager.isValidEndEvent(M)),(M=>this.oneFingerTouchMoveStateManager.isValidEndEvent(M)))}}const Xo=M=>{M.mousedown=M.dragStart,M.mousemoveWindow=M.dragMove,M.mouseup=M.dragEnd,M.contextmenu=M=>{M.preventDefault()}};class $o{constructor(M,et){this._clickTolerance=M.clickTolerance||1,this._map=et,this.reset()}reset(){this._active=!1,this._touches={},this._sum=new et.P(0,0)}_shouldBePrevented(M){return M<(this._map.cooperativeGestures.isEnabled()?2:1)}touchstart(M,et,Bt){return this._calculateTransform(M,et,Bt)}touchmove(M,et,Bt){if(this._active){if(!this._shouldBePrevented(Bt.length))return M.preventDefault(),this._calculateTransform(M,et,Bt);this._map.cooperativeGestures.notifyGestureBlocked("touch_pan",M)}}touchend(M,et,Bt){this._calculateTransform(M,et,Bt),this._active&&this._shouldBePrevented(Bt.length)&&this.reset()}touchcancel(){this.reset()}_calculateTransform(M,Bt,Wt){Wt.length>0&&(this._active=!0);const Nt=Oo(Wt,Bt),$t=new et.P(0,0),Gr=new et.P(0,0);let mn=0;for(const M in Nt){const et=Nt[M],Bt=this._touches[M];Bt&&($t._add(et),Gr._add(et.sub(Bt)),mn++,Nt[M]=et)}if(this._touches=Nt,this._shouldBePrevented(mn)||!Gr.mag())return;const Hn=Gr.div(mn);return this._sum._add(Hn),this._sum.mag()Math.abs(M.x)}class rs extends Ko{constructor(M){super(),this._currentTouchCount=0,this._map=M}reset(){super.reset(),this._valid=void 0,delete this._firstMove,delete this._lastPoints}touchstart(M,et,Bt){super.touchstart(M,et,Bt),this._currentTouchCount=Bt.length}_start(M){this._lastPoints=M,is(M[0].sub(M[1]))&&(this._valid=!1)}_move(M,et,Bt){if(this._map.cooperativeGestures.isEnabled()&&this._currentTouchCount<3)return;const Wt=M[0].sub(this._lastPoints[0]),Nt=M[1].sub(this._lastPoints[1]);return this._valid=this.gestureBeginsVertically(Wt,Nt,Bt.timeStamp),this._valid?(this._lastPoints=M,this._active=!0,{pitchDelta:(Wt.y+Nt.y)/2*-.5}):void 0}gestureBeginsVertically(M,et,Bt){if(void 0!==this._valid)return this._valid;const Wt=M.mag()>=2,Nt=et.mag()>=2;if(!Wt&&!Nt)return;if(!Wt||!Nt)return void 0===this._firstMove&&(this._firstMove=Bt),Bt-this._firstMove<100&&void 0;const $t=M.y>0==et.y>0;return is(M)&&is(et)&&$t}}const Gh={panStep:100,bearingStep:15,pitchStep:10};class ss{constructor(M){this._tr=new Bo(M);const et=Gh;this._panStep=et.panStep,this._bearingStep=et.bearingStep,this._pitchStep=et.pitchStep,this._rotationDisabled=!1}reset(){this._active=!1}keydown(M){if(M.altKey||M.ctrlKey||M.metaKey)return;let et=0,Bt=0,Wt=0,Nt=0,$t=0;switch(M.keyCode){case 61:case 107:case 171:case 187:et=1;break;case 189:case 109:case 173:et=-1;break;case 37:M.shiftKey?Bt=-1:(M.preventDefault(),Nt=-1);break;case 39:M.shiftKey?Bt=1:(M.preventDefault(),Nt=1);break;case 38:M.shiftKey?Wt=1:(M.preventDefault(),$t=-1);break;case 40:M.shiftKey?Wt=-1:(M.preventDefault(),$t=1);break;default:return}return this._rotationDisabled&&(Bt=0,Wt=0),{cameraAnimation:Gr=>{const mn=this._tr;Gr.easeTo({duration:300,easeId:"keyboardHandler",easing:as,zoom:et?Math.round(mn.zoom)+et*(M.shiftKey?2:1):mn.zoom,bearing:mn.bearing+Bt*this._bearingStep,pitch:mn.pitch+Wt*this._pitchStep,offset:[-Nt*this._panStep,-$t*this._panStep],center:mn.center},{originalEvent:M})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}disableRotation(){this._rotationDisabled=!0}enableRotation(){this._rotationDisabled=!1}}function as(M){return M*(2-M)}const Ph=4.000244140625;class ls{constructor(M,et){this._onTimeout=M=>{this._type="wheel",this._delta-=this._lastValue,this._active||this._start(M)},this._map=M,this._tr=new Bo(M),this._triggerRenderFrame=et,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=.0022222222222222222}setZoomRate(M){this._defaultZoomRate=M}setWheelZoomRate(M){this._wheelZoomRate=M}isEnabled(){return!!this._enabled}isActive(){return!!this._active||void 0!==this._finishTimeout}isZooming(){return!!this._zooming}enable(M){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!M&&"center"===M.around)}disable(){this.isEnabled()&&(this._enabled=!1)}_shouldBePrevented(M){return!!this._map.cooperativeGestures.isEnabled()&&!(M.ctrlKey||this._map.cooperativeGestures.isBypassed(M))}wheel(M){if(!this.isEnabled())return;if(this._shouldBePrevented(M))return void this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom",M);let et=M.deltaMode===WheelEvent.DOM_DELTA_LINE?40*M.deltaY:M.deltaY;const Bt=$t.now(),Wt=Bt-(this._lastWheelEventTime||0);this._lastWheelEventTime=Bt,0!==et&&et%Ph==0?this._type="wheel":0!==et&&Math.abs(et)<4?this._type="trackpad":Wt>400?(this._type=null,this._lastValue=et,this._timeout=setTimeout(this._onTimeout,40,M)):this._type||(this._type=Math.abs(Wt*et)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,et+=this._lastValue)),M.shiftKey&&et&&(et/=4),this._type&&(this._lastWheelEvent=M,this._delta-=et,this._active||this._start(M)),M.preventDefault()}_start(M){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const Bt=n.mousePos(this._map.getCanvas(),M),Wt=this._tr;this._aroundPoint=this._aroundCenter?Wt.transform.locationToScreenPoint(et.N.convert(Wt.center)):Bt,this._frameId||(this._frameId=!0,this._triggerRenderFrame())}renderFrame(){if(!this._frameId)return;if(this._frameId=null,!this.isActive())return;const M=this._tr.transform;if("number"==typeof this._lastExpectedZoom){const et=M.zoom-this._lastExpectedZoom;"number"==typeof this._startZoom&&(this._startZoom+=et),"number"==typeof this._targetZoom&&(this._targetZoom+=et)}if(0!==this._delta){const Bt="wheel"===this._type&&Math.abs(this._delta)>Ph?this._wheelZoomRate:this._defaultZoomRate;let Wt=2/(1+Math.exp(-Math.abs(this._delta*Bt)));this._delta<0&&0!==Wt&&(Wt=1/Wt);const Nt="number"!=typeof this._targetZoom?M.scale:et.aG(this._targetZoom);this._targetZoom=Math.min(M.maxZoom,Math.max(M.minZoom,et.a8(Nt*Wt))),"wheel"===this._type&&(this._startZoom=M.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0}const Bt="number"!=typeof this._targetZoom?M.zoom:this._targetZoom,Wt=this._startZoom,Nt=this._easing;let Gr,mn=!1;if("wheel"===this._type&&Wt&&Nt){const M=$t.now()-this._lastWheelEventTime,Hn=Math.min((M+5)/200,1),so=Nt(Hn);Gr=et.y.number(Wt,Bt,so),Hn<1?this._frameId||(this._frameId=!0):mn=!0}else Gr=Bt,mn=!0;return this._active=!0,mn&&(this._active=!1,this._finishTimeout=setTimeout((()=>{this._zooming=!1,this._triggerRenderFrame(),delete this._targetZoom,delete this._lastExpectedZoom,delete this._finishTimeout}),200)),this._lastExpectedZoom=Gr,{noInertia:!0,needsRenderFrame:!mn,zoomDelta:Gr-M.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}_smoothOutEasing(M){let Bt=et.c8;if(this._prevEase){const M=this._prevEase,Wt=($t.now()-M.start)/M.duration,Nt=M.easing(Wt+.01)-M.easing(Wt),Gr=.27/Math.sqrt(Nt*Nt+1e-4)*.01,mn=Math.sqrt(.0729-Gr*Gr);Bt=et.c6(Gr,mn,.25,1)}return this._prevEase={start:$t.now(),duration:M,easing:Bt},Bt}reset(){this._active=!1,this._zooming=!1,delete this._targetZoom,delete this._lastExpectedZoom,this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout)}}class cs{constructor(M,et){this._clickZoom=M,this._tapZoom=et}enable(){this._clickZoom.enable(),this._tapZoom.enable()}disable(){this._clickZoom.disable(),this._tapZoom.disable()}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class hs{constructor(M){this._tr=new Bo(M),this.reset()}reset(){this._active=!1}dblclick(M,et){return M.preventDefault(),{cameraAnimation:Bt=>{Bt.easeTo({duration:300,zoom:this._tr.zoom+(M.shiftKey?-1:1),around:this._tr.unproject(et)},{originalEvent:M})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class us{constructor(){this._tap=new Zo({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,delete this._tapPoint,this._tap.reset()}touchstart(M,et,Bt){if(!this._swipePoint)if(this._tapTime){const Wt=et[0],Nt=M.timeStamp-this._tapTime<500,$t=this._tapPoint.dist(Wt)<30;Nt&&$t?Bt.length>0&&(this._swipePoint=Wt,this._swipeTouch=Bt[0].identifier):this.reset()}else this._tap.touchstart(M,et,Bt)}touchmove(M,et,Bt){if(this._tapTime){if(this._swipePoint){if(Bt[0].identifier!==this._swipeTouch)return;const Wt=et[0],Nt=Wt.y-this._swipePoint.y;return this._swipePoint=Wt,M.preventDefault(),this._active=!0,{zoomDelta:Nt/128}}}else this._tap.touchmove(M,et,Bt)}touchend(M,et,Bt){if(this._tapTime)this._swipePoint&&0===Bt.length&&this.reset();else{const Wt=this._tap.touchend(M,et,Bt);Wt&&(this._tapTime=M.timeStamp,this._tapPoint=Wt)}}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class ds{constructor(M,et,Bt){this._el=M,this._mousePan=et,this._touchPan=Bt}enable(M){this._inertiaOptions=M||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("maplibregl-touch-drag-pan")}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("maplibregl-touch-drag-pan")}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class _s{constructor(M,et,Bt,Wt){this._pitchWithRotate=M.pitchWithRotate,this._rollEnabled=M.rollEnabled,this._mouseRotate=et,this._mousePitch=Bt,this._mouseRoll=Wt}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable(),this._rollEnabled&&this._mouseRoll.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable(),this._mouseRoll.disable()}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())&&(!this._rollEnabled||this._mouseRoll.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()||this._mouseRoll.isActive()}}class ps{constructor(M,et,Bt,Wt){this._el=M,this._touchZoom=et,this._touchRotate=Bt,this._tapDragZoom=Wt,this._rotationDisabled=!1,this._enabled=!0}enable(M){this._touchZoom.enable(M),this._rotationDisabled||this._touchRotate.enable(M),this._tapDragZoom.enable(),this._el.classList.add("maplibregl-touch-zoom-rotate")}disable(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("maplibregl-touch-zoom-rotate")}isEnabled(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()}isActive(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()}disableRotation(){this._rotationDisabled=!0,this._touchRotate.disable()}enableRotation(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable()}}class ms{constructor(M,et){this._bypassKey=-1!==navigator.userAgent.indexOf("Mac")?"metaKey":"ctrlKey",this._map=M,this._options=et,this._enabled=!1}isActive(){return!1}reset(){}_setupUI(){if(this._container)return;const M=this._map.getCanvasContainer();M.classList.add("maplibregl-cooperative-gestures"),this._container=n.create("div","maplibregl-cooperative-gesture-screen",M);let et=this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");"metaKey"===this._bypassKey&&(et=this._map._getUIString("CooperativeGesturesHandler.MacHelpText"));const Bt=this._map._getUIString("CooperativeGesturesHandler.MobileHelpText"),Wt=document.createElement("div");Wt.className="maplibregl-desktop-message",Wt.textContent=et,this._container.appendChild(Wt);const Nt=document.createElement("div");Nt.className="maplibregl-mobile-message",Nt.textContent=Bt,this._container.appendChild(Nt),this._container.setAttribute("aria-hidden","true")}_destroyUI(){this._container&&(n.remove(this._container),this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures")),delete this._container}enable(){this._setupUI(),this._enabled=!0}disable(){this._enabled=!1,this._destroyUI()}isEnabled(){return this._enabled}isBypassed(M){return M[this._bypassKey]}notifyGestureBlocked(M,Bt){this._enabled&&(this._map.fire(new et.k("cooperativegestureprevented",{gestureType:M,originalEvent:Bt})),this._container.classList.add("maplibregl-show"),setTimeout((()=>{this._container.classList.remove("maplibregl-show")}),100))}}const fs=M=>M.zoom||M.drag||M.roll||M.pitch||M.rotate;class gs extends et.k{}function vs(M){return M.panDelta&&M.panDelta.mag()||M.zoomDelta||M.bearingDelta||M.pitchDelta||M.rollDelta}class xs{constructor(M,et){this.handleWindowEvent=M=>{this.handleEvent(M,`${M.type}Window`)},this.handleEvent=(M,et)=>{if("blur"===M.type)return void this.stop(!0);this._updatingCamera=!0;const Bt="renderFrame"===M.type?void 0:M,Wt={needsRenderFrame:!1},Nt={},$t={},Gr=M.touches,mn=Gr?this._getMapTouches(Gr):void 0,Hn=mn?n.touchPos(this._map.getCanvas(),mn):n.mousePos(this._map.getCanvas(),M);for(const{handlerName:Gr,handler:so,allowed:uo}of this._handlers){if(!so.isEnabled())continue;let Io;this._blockedByActive($t,uo,Gr)?so.reset():so[et||M.type]&&(Io=so[et||M.type](M,Hn,mn),this.mergeHandlerResult(Wt,Nt,Io,Gr,Bt),Io&&Io.needsRenderFrame&&this._triggerRenderFrame()),(Io||so.isActive())&&($t[Gr]=so)}const so={};for(const M in this._previousActiveHandlers)$t[M]||(so[M]=Bt);this._previousActiveHandlers=$t,(Object.keys(so).length||vs(Wt))&&(this._changes.push([Wt,Nt,so]),this._triggerRenderFrame()),(Object.keys($t).length||vs(Wt))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:uo}=Wt;uo&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],uo(this._map))},this._map=M,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new So(M),this._bearingSnap=et.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(et);const Bt=this._el;this._listeners=[[Bt,"touchstart",{passive:!0}],[Bt,"touchmove",{passive:!1}],[Bt,"touchend",void 0],[Bt,"touchcancel",void 0],[Bt,"mousedown",void 0],[Bt,"mousemove",void 0],[Bt,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[Bt,"mouseover",void 0],[Bt,"mouseout",void 0],[Bt,"dblclick",void 0],[Bt,"click",void 0],[Bt,"keydown",{capture:!1}],[Bt,"keyup",void 0],[Bt,"wheel",{passive:!1}],[Bt,"contextmenu",void 0],[window,"blur",void 0]];for(const[M,et,Bt]of this._listeners)n.addEventListener(M,et,M===document?this.handleWindowEvent:this.handleEvent,Bt)}destroy(){for(const[M,et,Bt]of this._listeners)n.removeEventListener(M,et,M===document?this.handleWindowEvent:this.handleEvent,Bt)}_addDefaultHandlers(M){const Bt=this._map,Wt=Bt.getCanvasContainer();this._add("mapEvent",new ko(Bt,M));const Nt=Bt.boxZoom=new jo(Bt,M);this._add("boxZoom",Nt),M.interactive&&M.boxZoom&&Nt.enable();const $t=Bt.cooperativeGestures=new ms(Bt,M.cooperativeGestures);this._add("cooperativeGestures",$t),M.cooperativeGestures&&$t.enable();const Gr=new Go(Bt),mn=new hs(Bt);Bt.doubleClickZoom=new cs(mn,Gr),this._add("tapZoom",Gr),this._add("clickZoom",mn),M.interactive&&M.doubleClickZoom&&Bt.doubleClickZoom.enable();const Hn=new us;this._add("tapDragZoom",Hn);const so=Bt.touchPitch=new rs(Bt);this._add("touchPitch",so),M.interactive&&M.touchPitch&&Bt.touchPitch.enable(M.touchPitch);const u=()=>Bt.project(Bt.getCenter()),uo=function({enable:M,clickTolerance:Bt,aroundCenter:Wt=!0,minPixelCenterThreshold:Nt=100,rotateDegreesPerPixelMoved:$t=.8},Gr){const mn=new qo({checkCorrectEvent:M=>0===n.mouseButton(M)&&M.ctrlKey||2===n.mouseButton(M)&&!M.ctrlKey});return new Uo({clickTolerance:Bt,move:(M,Bt)=>{const mn=Gr();if(Wt&&Math.abs(mn.y-M.y)>Nt)return{bearingDelta:et.c7(new et.P(M.x,Bt.y),Bt,mn)};let Hn=(Bt.x-M.x)*$t;return Wt&&Bt.y0===n.mouseButton(M)&&M.ctrlKey||2===n.mouseButton(M)});return new Uo({clickTolerance:et,move:(M,et)=>({pitchDelta:(et.y-M.y)*Bt}),moveStateManager:Wt,enable:M,assignEvents:Xo})}(M),Po=function({enable:M,clickTolerance:et,rollDegreesPerPixelMoved:Bt=.3},Wt){const Nt=new qo({checkCorrectEvent:M=>2===n.mouseButton(M)&&M.ctrlKey});return new Uo({clickTolerance:et,move:(M,et)=>{const Nt=Wt();let $t=(et.x-M.x)*Bt;return et.y0===n.mouseButton(M)&&!M.ctrlKey});return new Uo({clickTolerance:et,move:(M,et)=>({around:et,panDelta:et.sub(M)}),activateOnStart:!0,moveStateManager:Bt,enable:M,assignEvents:Xo})}(M),Eo=new $o(M,Bt);Bt.dragPan=new ds(Wt,To,Eo),this._add("mousePan",To),this._add("touchPan",Eo,["touchZoom","touchRotate"]),M.interactive&&M.dragPan&&Bt.dragPan.enable(M.dragPan);const Ia=new ts,Ba=new Qo;Bt.touchZoomRotate=new ps(Wt,Ba,Ia,Hn),this._add("touchRotate",Ia,["touchPan","touchZoom"]),this._add("touchZoom",Ba,["touchPan","touchRotate"]),M.interactive&&M.touchZoomRotate&&Bt.touchZoomRotate.enable(M.touchZoomRotate);const Ta=Bt.scrollZoom=new ls(Bt,(()=>this._triggerRenderFrame()));this._add("scrollZoom",Ta,["mousePan"]),M.interactive&&M.scrollZoom&&Bt.scrollZoom.enable(M.scrollZoom);const Va=Bt.keyboard=new ss(Bt);this._add("keyboard",Va),M.interactive&&M.keyboard&&Bt.keyboard.enable(),this._add("blockableMapEvent",new Fo(Bt))}_add(M,et,Bt){this._handlers.push({handlerName:M,handler:et,allowed:Bt}),this._handlersById[M]=et}stop(M){if(!this._updatingCamera){for(const{handler:M}of this._handlers)M.reset();this._inertia.clear(),this._fireEvents({},{},M),this._changes=[]}}isActive(){for(const{handler:M}of this._handlers)if(M.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return Boolean(fs(this._eventsInProgress))||this.isZooming()}_blockedByActive(M,et,Bt){for(const Wt in M)if(Wt!==Bt&&(!et||et.indexOf(Wt)<0))return!0;return!1}_getMapTouches(M){const et=[];for(const Bt of M)this._el.contains(Bt.target)&&et.push(Bt);return et}mergeHandlerResult(M,Bt,Wt,Nt,$t){if(!Wt)return;et.e(M,Wt);const Gr={handlerName:Nt,originalEvent:Wt.originalEvent||$t};void 0!==Wt.zoomDelta&&(Bt.zoom=Gr),void 0!==Wt.panDelta&&(Bt.drag=Gr),void 0!==Wt.rollDelta&&(Bt.roll=Gr),void 0!==Wt.pitchDelta&&(Bt.pitch=Gr),void 0!==Wt.bearingDelta&&(Bt.rotate=Gr)}_applyChanges(){const M={},Bt={},Wt={};for(const[Nt,$t,Gr]of this._changes)Nt.panDelta&&(M.panDelta=(M.panDelta||new et.P(0,0))._add(Nt.panDelta)),Nt.zoomDelta&&(M.zoomDelta=(M.zoomDelta||0)+Nt.zoomDelta),Nt.bearingDelta&&(M.bearingDelta=(M.bearingDelta||0)+Nt.bearingDelta),Nt.pitchDelta&&(M.pitchDelta=(M.pitchDelta||0)+Nt.pitchDelta),Nt.rollDelta&&(M.rollDelta=(M.rollDelta||0)+Nt.rollDelta),void 0!==Nt.around&&(M.around=Nt.around),void 0!==Nt.pinchAround&&(M.pinchAround=Nt.pinchAround),Nt.noInertia&&(M.noInertia=Nt.noInertia),et.e(Bt,$t),et.e(Wt,Gr);this._updateMapTransform(M,Bt,Wt),this._changes=[]}_updateMapTransform(M,et,Bt){const Wt=this._map,Nt=Wt._getTransformForUpdate(),$t=Wt.terrain;if(!(vs(M)||$t&&this._terrainMovement))return this._fireEvents(et,Bt,!0);Wt._stop(!0);let{panDelta:Gr,zoomDelta:mn,bearingDelta:Hn,pitchDelta:so,rollDelta:uo,around:Io,pinchAround:Po}=M;void 0!==Po&&(Io=Po),Io=Io||Wt.transform.centerPoint,$t&&!Nt.isPointOnMapSurface(Io)&&(Io=Nt.centerPoint);const To={panDelta:Gr,zoomDelta:mn,rollDelta:uo,pitchDelta:so,bearingDelta:Hn,around:Io};this._map.cameraHelper.useGlobeControls&&!Nt.isPointOnMapSurface(Io)&&(Io=Nt.centerPoint);const Eo=Io.distSqr(Nt.centerPoint)<.01?Nt.center:Nt.screenPointToLocation(Gr?Io.sub(Gr):Io);$t?(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(To,Nt),this._terrainMovement||!et.drag&&!et.zoom?et.drag&&this._terrainMovement?Nt.setCenter(Nt.screenPointToLocation(Nt.centerPoint.sub(Gr))):this._map.cameraHelper.handleMapControlsPan(To,Nt,Eo):(this._terrainMovement=!0,this._map._elevationFreeze=!0,this._map.cameraHelper.handleMapControlsPan(To,Nt,Eo))):(this._map.cameraHelper.handleMapControlsRollPitchBearingZoom(To,Nt),this._map.cameraHelper.handleMapControlsPan(To,Nt,Eo)),Wt._applyUpdatedTransform(Nt),this._map._update(),M.noInertia||this._inertia.record(M),this._fireEvents(et,Bt,!0)}_fireEvents(M,Bt,Wt){const Nt=fs(this._eventsInProgress),Gr=fs(M),mn={};for(const et in M){const{originalEvent:Bt}=M[et];this._eventsInProgress[et]||(mn[`${et}start`]=Bt),this._eventsInProgress[et]=M[et]}!Nt&&Gr&&this._fireEvent("movestart",Gr.originalEvent);for(const M in mn)this._fireEvent(M,mn[M]);Gr&&this._fireEvent("move",Gr.originalEvent);for(const et in M){const{originalEvent:Bt}=M[et];this._fireEvent(et,Bt)}const Hn={};let so;for(const M in this._eventsInProgress){const{handlerName:et,originalEvent:Wt}=this._eventsInProgress[M];this._handlersById[et].isActive()||(delete this._eventsInProgress[M],so=Bt[et]||Wt,Hn[`${M}end`]=so)}for(const M in Hn)this._fireEvent(M,Hn[M]);const uo=fs(this._eventsInProgress),Io=(Nt||Gr)&&!uo;if(Io&&this._terrainMovement){this._map._elevationFreeze=!1,this._terrainMovement=!1;const M=this._map._getTransformForUpdate();this._map.getCenterClampedToGround()&&M.recalculateZoomAndCenter(this._map.terrain),this._map._applyUpdatedTransform(M)}if(Wt&&Io){this._updatingCamera=!0;const M=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),i=M=>0!==M&&-this._bearingSnap{delete this._frameId,this.handleEvent(new gs("renderFrame",{timeStamp:M})),this._applyChanges()}))}_triggerRenderFrame(){void 0===this._frameId&&(this._frameId=this._requestFrame())}}class bs extends et.E{constructor(M,et,Bt){super(),this._renderFrameCallback=()=>{const M=Math.min(($t.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(M)),M<1&&this._easeFrameId?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()},this._moving=!1,this._zooming=!1,this.transform=M,this._bearingSnap=Bt.bearingSnap,this.cameraHelper=et,this.on("moveend",(()=>{delete this._requestedCameraState}))}migrateProjection(M,et){M.apply(this.transform),this.transform=M,this.cameraHelper=et}getCenter(){return new et.N(this.transform.center.lng,this.transform.center.lat)}setCenter(M,et){return this.jumpTo({center:M},et)}getCenterElevation(){return this.transform.elevation}setCenterElevation(M,et){return this.jumpTo({elevation:M},et),this}getCenterClampedToGround(){return this._centerClampedToGround}setCenterClampedToGround(M){this._centerClampedToGround=M}panBy(M,Bt,Wt){return M=et.P.convert(M).mult(-1),this.panTo(this.transform.center,et.e({offset:M},Bt),Wt)}panTo(M,Bt,Wt){return this.easeTo(et.e({center:M},Bt),Wt)}getZoom(){return this.transform.zoom}setZoom(M,et){return this.jumpTo({zoom:M},et),this}zoomTo(M,Bt,Wt){return this.easeTo(et.e({zoom:M},Bt),Wt)}zoomIn(M,et){return this.zoomTo(this.getZoom()+1,M,et),this}zoomOut(M,et){return this.zoomTo(this.getZoom()-1,M,et),this}getVerticalFieldOfView(){return this.transform.fov}setVerticalFieldOfView(M,Bt){return M!=this.transform.fov&&(this.transform.setFov(M),this.fire(new et.k("movestart",Bt)).fire(new et.k("move",Bt)).fire(new et.k("moveend",Bt))),this}getBearing(){return this.transform.bearing}setBearing(M,et){return this.jumpTo({bearing:M},et),this}getPadding(){return this.transform.padding}setPadding(M,et){return this.jumpTo({padding:M},et),this}rotateTo(M,Bt,Wt){return this.easeTo(et.e({bearing:M},Bt),Wt)}resetNorth(M,Bt){return this.rotateTo(0,et.e({duration:1e3},M),Bt),this}resetNorthPitch(M,Bt){return this.easeTo(et.e({bearing:0,pitch:0,roll:0,duration:1e3},M),Bt),this}snapToNorth(M,et){return Math.abs(this.getBearing()){Ba.easeFunc(et),this.terrain&&!M.freezeElevation&&this._updateElevation(et),this._applyUpdatedTransform(Wt),this._fireMoveEvents(Bt)}),(et=>{this.terrain&&M.freezeElevation&&this._finalizeElevation(),this._afterEase(Bt,et)}),M),this}_prepareEase(M,Bt,Wt={}){this._moving=!0,Bt||Wt.moving||this.fire(new et.k("movestart",M)),this._zooming&&!Wt.zooming&&this.fire(new et.k("zoomstart",M)),this._rotating&&!Wt.rotating&&this.fire(new et.k("rotatestart",M)),this._pitching&&!Wt.pitching&&this.fire(new et.k("pitchstart",M)),this._rolling&&!Wt.rolling&&this.fire(new et.k("rollstart",M))}_prepareElevation(M){this._elevationCenter=M,this._elevationStart=this.transform.elevation,this._elevationTarget=this.terrain.getElevationForLngLatZoom(M,this.transform.tileZoom),this._elevationFreeze=!0}_updateElevation(M){this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom));const Bt=this.terrain.getElevationForLngLatZoom(this._elevationCenter,this.transform.tileZoom);if(M<1&&Bt!==this._elevationTarget){const et=this._elevationTarget-this._elevationStart;this._elevationStart+=M*(et-(Bt-(et*M+this._elevationStart))/(1-M)),this._elevationTarget=Bt}this.transform.setElevation(et.y.number(this._elevationStart,this._elevationTarget,M))}_finalizeElevation(){this._elevationFreeze=!1,this.getCenterClampedToGround()&&this.transform.recalculateZoomAndCenter(this.terrain)}_getTransformForUpdate(){return this.transformCameraUpdate||this.terrain?(this._requestedCameraState||(this._requestedCameraState=this.transform.clone()),this._requestedCameraState):this.transform}_elevateCameraIfInsideTerrain(M){if(!this.terrain&&M.elevation>=0&&M.pitch<=90)return{};const et=M.getCameraLngLat(),Bt=M.getCameraAltitude(),Wt=this.terrain?this.terrain.getElevationForLngLatZoom(et,M.zoom):0;if(Btthis._elevateCameraIfInsideTerrain(M))),this.transformCameraUpdate&&et.push((M=>this.transformCameraUpdate(M))),!et.length)return;const Bt=M.clone();for(const M of et){const et=Bt.clone(),{center:Wt,zoom:Nt,roll:$t,pitch:Gr,bearing:mn,elevation:Hn}=M(et);Wt&&et.setCenter(Wt),void 0!==Hn&&et.setElevation(Hn),void 0!==Nt&&et.setZoom(Nt),void 0!==$t&&et.setRoll($t),void 0!==Gr&&et.setPitch(Gr),void 0!==mn&&et.setBearing(mn),Bt.apply(et)}this.transform.apply(Bt)}_fireMoveEvents(M){this.fire(new et.k("move",M)),this._zooming&&this.fire(new et.k("zoom",M)),this._rotating&&this.fire(new et.k("rotate",M)),this._pitching&&this.fire(new et.k("pitch",M)),this._rolling&&this.fire(new et.k("roll",M))}_afterEase(M,Bt){if(this._easeId&&Bt&&this._easeId===Bt)return;delete this._easeId;const Wt=this._zooming,Nt=this._rotating,$t=this._pitching,Gr=this._rolling;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._rolling=!1,this._padding=!1,Wt&&this.fire(new et.k("zoomend",M)),Nt&&this.fire(new et.k("rotateend",M)),$t&&this.fire(new et.k("pitchend",M)),Gr&&this.fire(new et.k("rollend",M)),this.fire(new et.k("moveend",M))}flyTo(M,Bt){if(!M.essential&&$t.prefersReducedMotion){const Wt=et.M(M,["center","zoom","bearing","pitch","roll","elevation"]);return this.jumpTo(Wt,Bt)}this.stop(),M=et.e({offset:[0,0],speed:1.2,curve:1.42,easing:et.c8},M);const Wt=this._getTransformForUpdate(),Nt=Wt.bearing,Gr=Wt.pitch,mn=Wt.roll,Hn=Wt.padding,so="bearing"in M?this._normalizeBearing(M.bearing,Nt):Nt,uo="pitch"in M?+M.pitch:Gr,Io="roll"in M?this._normalizeBearing(M.roll,mn):mn,Po="padding"in M?M.padding:Wt.padding,To=et.P.convert(M.offset);let Eo=Wt.centerPoint.add(To);const Ia=Wt.screenPointToLocation(Eo),Ba=this.cameraHelper.handleFlyTo(Wt,{bearing:so,pitch:uo,roll:Io,padding:Po,locationAtOffset:Ia,offsetAsPoint:To,center:M.center,minZoom:M.minZoom,zoom:M.zoom});let Ta=M.curve;const Va=Math.max(Wt.width,Wt.height),za=Va/Ba.scaleOfZoom,Fa=Ba.pixelPathLength;"number"==typeof Ba.scaleOfMinZoom&&(Ta=Math.sqrt(Va/Ba.scaleOfMinZoom/Fa*2));const Ea=Ta*Ta;function w(M){const et=(za*za-Va*Va+(M?-1:1)*Ea*Ea*Fa*Fa)/(2*(M?za:Va)*Ea*Fa);return Math.log(Math.sqrt(et*et+1)-et)}function T(M){return(Math.exp(M)-Math.exp(-M))/2}function P(M){return(Math.exp(M)+Math.exp(-M))/2}const La=w(!1);let I=function(M){return P(La)/P(La+Ta*M)},E=function(M){return Va*((P(La)*(T(et=La+Ta*M)/P(et))-T(La))/Ea)/Fa;var et},Da=(w(!0)-La)/Ta;if(Math.abs(Fa)<2e-6||!isFinite(Da)){if(Math.abs(Va-za)<1e-6)return this.easeTo(M,Bt);const et=za0,I=M=>Math.exp(et*Ta*M)}return M.duration="duration"in M?+M.duration:1e3*Da/("screenSpeed"in M?+M.screenSpeed/Ta:+M.speed),M.maxDuration&&M.duration>M.maxDuration&&(M.duration=0),this._zooming=!0,this._rotating=Nt!==so,this._pitching=uo!==Gr,this._rolling=Io!==mn,this._padding=!Wt.isPaddingEqual(Po),this._prepareEase(Bt,!1),this.terrain&&this._prepareElevation(Ba.targetCenter),this._ease(($t=>{const Ia=$t*Da,Ta=1/I(Ia),Va=E(Ia);this._rotating&&Wt.setBearing(et.y.number(Nt,so,$t)),this._pitching&&Wt.setPitch(et.y.number(Gr,uo,$t)),this._rolling&&Wt.setRoll(et.y.number(mn,Io,$t)),this._padding&&(Wt.interpolatePadding(Hn,Po,$t),Eo=Wt.centerPoint.add(To)),Ba.easeFunc($t,Ta,Va,Eo),this.terrain&&!M.freezeElevation&&this._updateElevation($t),this._applyUpdatedTransform(Wt),this._fireMoveEvents(Bt)}),(()=>{this.terrain&&M.freezeElevation&&this._finalizeElevation(),this._afterEase(Bt)}),M),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_stop(M,et){var Bt;if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){const M=this._onEaseEnd;delete this._onEaseEnd,M.call(this,et)}return M||null===(Bt=this.handlers)||void 0===Bt||Bt.stop(!1),this}_ease(M,et,Bt){!1===Bt.animate||0===Bt.duration?(M(1),et()):(this._easeStart=$t.now(),this._easeOptions=Bt,this._onEaseFrame=M,this._onEaseEnd=et,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_normalizeBearing(M,Bt){M=et.aI(M,-180,180);const Wt=Math.abs(M-Bt);return Math.abs(M-360-Bt)MapLibre'};class ws{constructor(M=Wh){this._toggleAttribution=()=>{this._container.classList.contains("maplibregl-compact")&&(this._container.classList.contains("maplibregl-compact-show")?(this._container.setAttribute("open",""),this._container.classList.remove("maplibregl-compact-show")):(this._container.classList.add("maplibregl-compact-show"),this._container.removeAttribute("open")))},this._updateData=M=>{!M||"metadata"!==M.sourceDataType&&"visibility"!==M.sourceDataType&&"style"!==M.dataType&&"terrain"!==M.type||this._updateAttributions()},this._updateCompact=()=>{this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1===this._compact?this._container.setAttribute("open",""):this._container.classList.contains("maplibregl-compact")||this._container.classList.contains("maplibregl-attrib-empty")||(this._container.setAttribute("open",""),this._container.classList.add("maplibregl-compact","maplibregl-compact-show")):(this._container.setAttribute("open",""),this._container.classList.contains("maplibregl-compact")&&this._container.classList.remove("maplibregl-compact","maplibregl-compact-show"))},this._updateCompactMinimize=()=>{this._container.classList.contains("maplibregl-compact")&&this._container.classList.contains("maplibregl-compact-show")&&this._container.classList.remove("maplibregl-compact-show")},this.options=M}getDefaultPosition(){return"bottom-right"}onAdd(M){return this._map=M,this._compact=this.options.compact,this._container=n.create("details","maplibregl-ctrl maplibregl-ctrl-attrib"),this._compactButton=n.create("summary","maplibregl-ctrl-attrib-button",this._container),this._compactButton.addEventListener("click",this._toggleAttribution),this._setElementTitle(this._compactButton,"ToggleAttribution"),this._innerContainer=n.create("div","maplibregl-ctrl-attrib-inner",this._container),this._updateAttributions(),this._updateCompact(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("terrain",this._updateData),this._map.on("resize",this._updateCompact),this._map.on("drag",this._updateCompactMinimize),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("terrain",this._updateData),this._map.off("resize",this._updateCompact),this._map.off("drag",this._updateCompactMinimize),this._map=void 0,this._compact=void 0,this._sanitizedAttributionHTML=void 0}_setElementTitle(M,et){const Bt=this._map._getUIString(`AttributionControl.${et}`);M.title=Bt,M.setAttribute("aria-label",Bt)}_updateAttributions(){if(!this._map.style)return;let M=[];if(this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?M=M.concat(this.options.customAttribution.map((M=>"string"!=typeof M?"":M))):"string"==typeof this.options.customAttribution&&M.push(this.options.customAttribution)),this._map.style.stylesheet){const M=this._map.style.stylesheet;this.styleOwner=M.owner,this.styleId=M.id}const et=this._map.style.sourceCaches;for(const Bt in et){const Wt=et[Bt];if(Wt.used||Wt.usedForTerrain){const et=Wt.getSource();et.attribution&&M.indexOf(et.attribution)<0&&M.push(et.attribution)}}M=M.filter((M=>String(M).trim())),M.sort(((M,et)=>M.length-et.length)),M=M.filter(((et,Bt)=>{for(let Wt=Bt+1;Wt=0)return!1;return!0}));const Bt=M.join(" | ");Bt!==this._sanitizedAttributionHTML&&(this._sanitizedAttributionHTML=n.sanitize(Bt),M.length?(this._innerContainer.innerHTML=this._sanitizedAttributionHTML,this._container.classList.remove("maplibregl-attrib-empty")):this._container.classList.add("maplibregl-attrib-empty"),this._updateCompact(),this._editLink=null)}}class Ts{constructor(M={}){this._updateCompact=()=>{const M=this._container.children;if(M.length){const et=M[0];this._map.getCanvasContainer().offsetWidth<=640||this._compact?!1!==this._compact&&et.classList.add("maplibregl-compact"):et.classList.remove("maplibregl-compact")}},this.options=M}getDefaultPosition(){return"bottom-left"}onAdd(M){this._map=M,this._compact=this.options&&this.options.compact,this._container=n.create("div","maplibregl-ctrl");const et=n.create("a","maplibregl-ctrl-logo");return et.target="_blank",et.rel="noopener nofollow",et.href="https://maplibre.org/",et.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),et.setAttribute("rel","noopener nofollow"),this._container.appendChild(et),this._container.style.display="block",this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){n.remove(this._container),this._map.off("resize",this._updateCompact),this._map=void 0,this._compact=void 0}}class Ps{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(M){const et=++this._id;return this._queue.push({callback:M,id:et,cancelled:!1}),et}remove(M){const et=this._currentlyRunning,Bt=et?this._queue.concat(et):this._queue;for(const et of Bt)if(et.id===M)return void(et.cancelled=!0)}run(M=0){if(this._currentlyRunning)throw new Error("Attempting to run(), but is already running.");const et=this._currentlyRunning=this._queue;this._queue=[];for(const Bt of et)if(!Bt.cancelled&&(Bt.callback(M),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}var zh=et.aA([{name:"a_pos3d",type:"Int16",components:3}]);class Is extends et.E{constructor(M){super(),this._lastTilesetChange=$t.now(),this.sourceCache=M,this._tiles={},this._renderableTilesKeys=[],this._sourceTileCache={},this.minzoom=0,this.maxzoom=22,this.deltaZoom=1,this.tileSize=M._source.tileSize*2**this.deltaZoom,M.usedForTerrain=!0,M.tileSize=this.tileSize}destruct(){this.sourceCache.usedForTerrain=!1,this.sourceCache.tileSize=null}update(M,Bt){this.sourceCache.update(M,Bt),this._renderableTilesKeys=[];const Wt={};for(const Nt of ue(M,{tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,reparseOverscaled:!1,terrain:Bt,calculateTileZoom:this.sourceCache._source.calculateTileZoom}))Wt[Nt.key]=!0,this._renderableTilesKeys.push(Nt.key),this._tiles[Nt.key]||(Nt.terrainRttPosMatrix32f=new Float64Array(16),et.bL(Nt.terrainRttPosMatrix32f,0,et.X,et.X,0,0,1),this._tiles[Nt.key]=new se(Nt,this.tileSize),this._lastTilesetChange=$t.now());for(const M in this._tiles)Wt[M]||delete this._tiles[M]}freeRtt(M){for(const et in this._tiles){const Bt=this._tiles[et];(!M||Bt.tileID.equals(M)||Bt.tileID.isChildOf(M)||M.isChildOf(Bt.tileID))&&(Bt.rtt=[])}}getRenderableTiles(){return this._renderableTilesKeys.map((M=>this.getTileByID(M)))}getTileByID(M){return this._tiles[M]}getTerrainCoords(M){const Bt={};for(const Wt of this._renderableTilesKeys){const Nt=this._tiles[Wt].tileID,$t=M.clone(),Gr=et.a$();if(Nt.canonical.equals(M.canonical))et.bL(Gr,0,et.X,et.X,0,0,1);else if(Nt.canonical.isChildOf(M.canonical)){const Bt=Nt.canonical.z-M.canonical.z,Wt=Nt.canonical.x-(Nt.canonical.x>>Bt<>Bt<>Bt;et.bL(Gr,0,mn,mn,0,0,1),et.J(Gr,Gr,[-Wt*mn,-$t*mn,0])}else{if(!M.canonical.isChildOf(Nt.canonical))continue;{const Bt=M.canonical.z-Nt.canonical.z,Wt=M.canonical.x-(M.canonical.x>>Bt<>Bt<>Bt;et.bL(Gr,0,et.X,et.X,0,0,1),et.J(Gr,Gr,[Wt*mn,$t*mn,0]),et.K(Gr,Gr,[1/2**Bt,1/2**Bt,0])}}$t.terrainRttPosMatrix32f=new Float32Array(Gr),Bt[Wt]=$t}return Bt}getSourceTile(M,et){const Bt=this.sourceCache._source;let Wt=M.overscaledZ-this.deltaZoom;if(Wt>Bt.maxzoom&&(Wt=Bt.maxzoom),Wt=Bt.minzoom&&(!Nt||!Nt.dem);)Nt=this.sourceCache.getTileByID(M.scaledTo(Wt--).key);return Nt}anyTilesAfterTime(M=Date.now()){return this._lastTilesetChange>=M}}class Es{constructor(M,et,Bt){this._meshCache={},this.painter=M,this.sourceCache=new Is(et),this.options=Bt,this.exaggeration="number"==typeof Bt.exaggeration?Bt.exaggeration:1,this.qualityFactor=2,this.meshSize=128,this._demMatrixCache={},this.coordsIndex=[],this._coordsTextureSize=1024}getDEMElevation(M,Bt,Wt,Nt=et.X){var $t;if(!(Bt>=0&&Bt=0&&WtM.canonical.z&&(M.canonical.z>=Wt?Nt=M.canonical.z-Wt:et.w("cannot calculate elevation if elevation maxzoom > source.maxzoom"));const $t=M.canonical.x-(M.canonical.x>>Nt<>Nt<>8<<4|M>>8,Bt[et+3]=0;const Wt=new et.R({width:this._coordsTextureSize,height:this._coordsTextureSize},new Uint8Array(Bt.buffer)),Nt=new v(M,Wt,M.gl.RGBA,{premultiply:!1});return Nt.bind(M.gl.NEAREST,M.gl.CLAMP_TO_EDGE),this._coordsTexture=Nt,Nt}pointCoordinate(M){this.painter.maybeDrawDepthAndCoords(!0);const Bt=new Uint8Array(4),Wt=this.painter.context,Nt=Wt.gl,$t=Math.round(M.x*this.painter.pixelRatio/devicePixelRatio),Gr=Math.round(M.y*this.painter.pixelRatio/devicePixelRatio),mn=Math.round(this.painter.height/devicePixelRatio);Wt.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer),Nt.readPixels($t,mn-Gr-1,1,1,Nt.RGBA,Nt.UNSIGNED_BYTE,Bt),Wt.bindFramebuffer.set(null);const Hn=Bt[0]+(Bt[2]>>4<<8),so=Bt[1]+((15&Bt[2])<<8),uo=this.coordsIndex[255-Bt[3]],Io=uo&&this.sourceCache.getTileByID(uo);if(!Io)return null;const Po=this._coordsTextureSize,To=(1<0,Nt=Wt&&0===M.canonical.y,$t=Wt&&M.canonical.y===(1<M.id!==et)),this._recentlyUsed.push(M.id)}stampObject(M){M.stamp=++this._stamp}getOrCreateFreeObject(){for(const M of this._recentlyUsed)if(!this._objects[M].inUse)return this._objects[M];if(this._objects.length>=this._size)throw new Error("No free RenderPool available, call freeAllObjects() required!");const M=this._createObject(this._objects.length);return this._objects.push(M),M}freeObject(M){M.inUse=!1}freeAllObjects(){for(const M of this._objects)this.freeObject(M)}isFull(){return!(this._objects.length!M.inUse))}}const Jh={background:!0,fill:!0,line:!0,raster:!0,hillshade:!0};class Rs{constructor(M,et){this.painter=M,this.terrain=et,this.pool=new Ms(M.context,30,et.sourceCache.tileSize*et.qualityFactor)}destruct(){this.pool.destruct()}getTexture(M){return this.pool.getObjectForId(M.rtt[this._stacks.length-1].id).texture}prepareForRender(M,et){this._stacks=[],this._prevType=null,this._rttTiles=[],this._renderableTiles=this.terrain.sourceCache.getRenderableTiles(),this._renderableLayerIds=M._order.filter((Bt=>!M._layers[Bt].isHidden(et))),this._coordsAscending={};for(const et in M.sourceCaches){this._coordsAscending[et]={};const Bt=M.sourceCaches[et].getVisibleCoordinates();for(const M of Bt){const Bt=this.terrain.sourceCache.getTerrainCoords(M);for(const M in Bt)this._coordsAscending[et][M]||(this._coordsAscending[et][M]=[]),this._coordsAscending[et][M].push(Bt[M])}}this._coordsAscendingStr={};for(const et of M._order){const Bt=M._layers[et],Wt=Bt.source;if(Jh[Bt.type]&&!this._coordsAscendingStr[Wt]){this._coordsAscendingStr[Wt]={};for(const M in this._coordsAscending[Wt])this._coordsAscendingStr[Wt][M]=this._coordsAscending[Wt][M].map((M=>M.key)).sort().join()}}for(const M of this._renderableTiles)for(const et in this._coordsAscendingStr){const Bt=this._coordsAscendingStr[et][M.tileID.key];Bt&&Bt!==M.rttCoords[et]&&(M.rtt=[])}}renderLayer(M,Bt){if(M.isHidden(this.painter.transform.zoom))return!1;const Wt=Object.assign(Object.assign({},Bt),{isRenderingToTexture:!0}),Nt=M.type,$t=this.painter,Gr=this._renderableLayerIds[this._renderableLayerIds.length-1]===M.id;if(Jh[Nt]&&(this._prevType&&Jh[this._prevType]||this._stacks.push([]),this._prevType=Nt,this._stacks[this._stacks.length-1].push(M.id),!Gr))return!0;if(Jh[this._prevType]||Jh[Nt]&&Gr){this._prevType=Nt;const M=this._stacks.length-1,Bt=this._stacks[M]||[];for(const Nt of this._renderableTiles){if(this.pool.isFull()&&(vo(this.painter,this.terrain,this._rttTiles,Wt),this._rttTiles=[],this.pool.freeAllObjects()),this._rttTiles.push(Nt),Nt.rtt[M]){const et=this.pool.getObjectForId(Nt.rtt[M].id);if(et.stamp===Nt.rtt[M].stamp){this.pool.useObject(et);continue}}const Gr=this.pool.getOrCreateFreeObject();this.pool.useObject(Gr),this.pool.stampObject(Gr),Nt.rtt[M]={id:Gr.id,stamp:Gr.stamp},$t.context.bindFramebuffer.set(Gr.fbo.framebuffer),$t.context.clear({color:et.b4.transparent,stencil:0}),$t.currentStencilSource=void 0;for(let M=0;M{this.startMove(M,n.mousePos(this.element,M)),n.addEventListener(window,"mousemove",this.mousemove),n.addEventListener(window,"mouseup",this.mouseup)},this.mousemove=M=>{this.move(M,n.mousePos(this.element,M))},this.mouseup=M=>{this._rotatePitchHanlder.dragEnd(M),this.offTemp()},this.touchstart=M=>{1!==M.targetTouches.length?this.reset():(this._startPos=this._lastPos=n.touchPos(this.element,M.targetTouches)[0],this.startMove(M,this._startPos),n.addEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.addEventListener(window,"touchend",this.touchend))},this.touchmove=M=>{1!==M.targetTouches.length?this.reset():(this._lastPos=n.touchPos(this.element,M.targetTouches)[0],this.move(M,this._lastPos))},this.touchend=M=>{0===M.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos){this._rotatePitchHanlder.reset(),delete this._startPos,delete this._lastPos,this.offTemp()},this._clickTolerance=10,this.element=Bt;const Nt=new Wo;this._rotatePitchHanlder=new Uo({clickTolerance:3,move:(M,Nt)=>{const $t=Bt.getBoundingClientRect(),Gr=new et.P(($t.bottom-$t.top)/2,($t.right-$t.left)/2);return{bearingDelta:et.c7(new et.P(M.x,Nt.y),Nt,Gr),pitchDelta:Wt?-.5*(Nt.y-M.y):void 0}},moveStateManager:Nt,enable:!0,assignEvents:()=>{}}),this.map=M,n.addEventListener(Bt,"mousedown",this.mousedown),n.addEventListener(Bt,"touchstart",this.touchstart,{passive:!1}),n.addEventListener(Bt,"touchcancel",this.reset)}startMove(M,et){this._rotatePitchHanlder.dragStart(M,et),n.disableDrag()}move(M,et){const Bt=this.map,{bearingDelta:Wt,pitchDelta:Nt}=this._rotatePitchHanlder.dragMove(M,et)||{};Wt&&Bt.setBearing(Bt.getBearing()+Wt),Nt&&Bt.setPitch(Bt.getPitch()+Nt)}off(){const M=this.element;n.removeEventListener(M,"mousedown",this.mousedown),n.removeEventListener(M,"touchstart",this.touchstart,{passive:!1}),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend),n.removeEventListener(M,"touchcancel",this.reset),this.offTemp()}offTemp(){n.enableDrag(),n.removeEventListener(window,"mousemove",this.mousemove),n.removeEventListener(window,"mouseup",this.mouseup),n.removeEventListener(window,"touchmove",this.touchmove,{passive:!1}),n.removeEventListener(window,"touchend",this.touchend)}}let Yh;function Bs(M,Bt,Wt){const Nt=new et.N(M.lng,M.lat);if(M=new et.N(M.lng,M.lat),Bt){const Nt=new et.N(M.lng-360,M.lat),$t=new et.N(M.lng+360,M.lat),Gr=Wt.locationToScreenPoint(M).distSqr(Bt);Wt.locationToScreenPoint(Nt).distSqr(Bt)180;){const et=Wt.locationToScreenPoint(M);if(et.x>=0&&et.y>=0&&et.x<=Wt.width&&et.y<=Wt.height)break;M.lng>Wt.center.lng?M.lng-=360:M.lng+=360}return M.lng!==Nt.lng&&Wt.isPointOnMapSurface(Wt.locationToScreenPoint(M))?M:Nt}const Qh={center:"translate(-50%,-50%)",top:"translate(-50%,0)","top-left":"translate(0,0)","top-right":"translate(-100%,0)",bottom:"translate(-50%,-100%)","bottom-left":"translate(0,-100%)","bottom-right":"translate(-100%,-100%)",left:"translate(0,-50%)",right:"translate(-100%,-50%)"};function Os(M,et,Bt){const Wt=M.classList;for(const M in Qh)Wt.remove(`maplibregl-${Bt}-anchor-${M}`);Wt.add(`maplibregl-${Bt}-anchor-${et}`)}class Ns extends et.E{constructor(M){if(super(),this._onKeyPress=M=>{const et=M.code,Bt=M.charCode||M.keyCode;"Space"!==et&&"Enter"!==et&&32!==Bt&&13!==Bt||this.togglePopup()},this._onMapClick=M=>{const et=M.originalEvent.target,Bt=this._element;this._popup&&(et===Bt||Bt.contains(et))&&this.togglePopup()},this._update=M=>{var et;if(!this._map)return;const Bt=this._map.loaded()&&!this._map.isMoving();("terrain"===(null==M?void 0:M.type)||"render"===(null==M?void 0:M.type)&&!Bt)&&this._map.once("render",this._update),this._lngLat=this._map.transform.renderWorldCopies?Bs(this._lngLat,this._flatPos,this._map.transform):null===(et=this._lngLat)||void 0===et?void 0:et.wrap(),this._flatPos=this._pos=this._map.project(this._lngLat)._add(this._offset),this._map.terrain&&(this._flatPos=this._map.transform.locationToScreenPoint(this._lngLat)._add(this._offset));let Wt="";"viewport"===this._rotationAlignment||"auto"===this._rotationAlignment?Wt=`rotateZ(${this._rotation}deg)`:"map"===this._rotationAlignment&&(Wt=`rotateZ(${this._rotation-this._map.getBearing()}deg)`);let Nt="";"viewport"===this._pitchAlignment||"auto"===this._pitchAlignment?Nt="rotateX(0deg)":"map"===this._pitchAlignment&&(Nt=`rotateX(${this._map.getPitch()}deg)`),this._subpixelPositioning||M&&"moveend"!==M.type||(this._pos=this._pos.round()),n.setTransform(this._element,`${Qh[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${Nt} ${Wt}`),$t.frameAsync(new AbortController).then((()=>{this._updateOpacity(M&&"moveend"===M.type)})).catch((()=>{}))},this._onMove=M=>{if(!this._isDragging){const et=this._clickTolerance||this._map._clickTolerance;this._isDragging=M.point.dist(this._pointerdownPos)>=et}this._isDragging&&(this._pos=M.point.sub(this._positionDelta),this._lngLat=this._map.unproject(this._pos),this.setLngLat(this._lngLat),this._element.style.pointerEvents="none","pending"===this._state&&(this._state="active",this.fire(new et.k("dragstart"))),this.fire(new et.k("drag")))},this._onUp=()=>{this._element.style.pointerEvents="auto",this._positionDelta=null,this._pointerdownPos=null,this._isDragging=!1,this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),"active"===this._state&&this.fire(new et.k("dragend")),this._state="inactive"},this._addDragHandler=M=>{this._element.contains(M.originalEvent.target)&&(M.preventDefault(),this._positionDelta=M.point.sub(this._pos).add(this._offset),this._pointerdownPos=M.point,this._state="pending",this._map.on("mousemove",this._onMove),this._map.on("touchmove",this._onMove),this._map.once("mouseup",this._onUp),this._map.once("touchend",this._onUp))},this._anchor=M&&M.anchor||"center",this._color=M&&M.color||"#3FB1CE",this._scale=M&&M.scale||1,this._draggable=M&&M.draggable||!1,this._clickTolerance=M&&M.clickTolerance||0,this._subpixelPositioning=M&&M.subpixelPositioning||!1,this._isDragging=!1,this._state="inactive",this._rotation=M&&M.rotation||0,this._rotationAlignment=M&&M.rotationAlignment||"auto",this._pitchAlignment=M&&M.pitchAlignment&&"auto"!==M.pitchAlignment?M.pitchAlignment:this._rotationAlignment,this.setOpacity(),this.setOpacity(null==M?void 0:M.opacity,null==M?void 0:M.opacityWhenCovered),M&&M.element)this._element=M.element,this._offset=et.P.convert(M&&M.offset||[0,0]);else{this._defaultMarker=!0,this._element=n.create("div");const Bt=n.createNS("http://www.w3.org/2000/svg","svg"),Wt=41,Nt=27;Bt.setAttributeNS(null,"display","block"),Bt.setAttributeNS(null,"height",`${Wt}px`),Bt.setAttributeNS(null,"width",`${Nt}px`),Bt.setAttributeNS(null,"viewBox",`0 0 ${Nt} ${Wt}`);const $t=n.createNS("http://www.w3.org/2000/svg","g");$t.setAttributeNS(null,"stroke","none"),$t.setAttributeNS(null,"stroke-width","1"),$t.setAttributeNS(null,"fill","none"),$t.setAttributeNS(null,"fill-rule","evenodd");const Gr=n.createNS("http://www.w3.org/2000/svg","g");Gr.setAttributeNS(null,"fill-rule","nonzero");const mn=n.createNS("http://www.w3.org/2000/svg","g");mn.setAttributeNS(null,"transform","translate(3.0, 29.0)"),mn.setAttributeNS(null,"fill","#000000");const Hn=[{rx:"10.5",ry:"5.25002273"},{rx:"10.5",ry:"5.25002273"},{rx:"9.5",ry:"4.77275007"},{rx:"8.5",ry:"4.29549936"},{rx:"7.5",ry:"3.81822308"},{rx:"6.5",ry:"3.34094679"},{rx:"5.5",ry:"2.86367051"},{rx:"4.5",ry:"2.38636864"}];for(const M of Hn){const et=n.createNS("http://www.w3.org/2000/svg","ellipse");et.setAttributeNS(null,"opacity","0.04"),et.setAttributeNS(null,"cx","10.5"),et.setAttributeNS(null,"cy","5.80029008"),et.setAttributeNS(null,"rx",M.rx),et.setAttributeNS(null,"ry",M.ry),mn.appendChild(et)}const so=n.createNS("http://www.w3.org/2000/svg","g");so.setAttributeNS(null,"fill",this._color);const uo=n.createNS("http://www.w3.org/2000/svg","path");uo.setAttributeNS(null,"d","M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z"),so.appendChild(uo);const Io=n.createNS("http://www.w3.org/2000/svg","g");Io.setAttributeNS(null,"opacity","0.25"),Io.setAttributeNS(null,"fill","#000000");const Po=n.createNS("http://www.w3.org/2000/svg","path");Po.setAttributeNS(null,"d","M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z"),Io.appendChild(Po);const To=n.createNS("http://www.w3.org/2000/svg","g");To.setAttributeNS(null,"transform","translate(6.0, 7.0)"),To.setAttributeNS(null,"fill","#FFFFFF");const Eo=n.createNS("http://www.w3.org/2000/svg","g");Eo.setAttributeNS(null,"transform","translate(8.0, 8.0)");const Ia=n.createNS("http://www.w3.org/2000/svg","circle");Ia.setAttributeNS(null,"fill","#000000"),Ia.setAttributeNS(null,"opacity","0.25"),Ia.setAttributeNS(null,"cx","5.5"),Ia.setAttributeNS(null,"cy","5.5"),Ia.setAttributeNS(null,"r","5.4999962");const Ba=n.createNS("http://www.w3.org/2000/svg","circle");Ba.setAttributeNS(null,"fill","#FFFFFF"),Ba.setAttributeNS(null,"cx","5.5"),Ba.setAttributeNS(null,"cy","5.5"),Ba.setAttributeNS(null,"r","5.4999962"),Eo.appendChild(Ia),Eo.appendChild(Ba),Gr.appendChild(mn),Gr.appendChild(so),Gr.appendChild(Io),Gr.appendChild(To),Gr.appendChild(Eo),Bt.appendChild(Gr),Bt.setAttributeNS(null,"height",Wt*this._scale+"px"),Bt.setAttributeNS(null,"width",Nt*this._scale+"px"),this._element.appendChild(Bt),this._offset=et.P.convert(M&&M.offset||[0,-14])}if(this._element.classList.add("maplibregl-marker"),this._element.addEventListener("dragstart",(M=>{M.preventDefault()})),this._element.addEventListener("mousedown",(M=>{M.preventDefault()})),Os(this._element,this._anchor,"marker"),M&&M.className)for(const et of M.className.split(" "))this._element.classList.add(et);this._popup=null}addTo(M){return this.remove(),this._map=M,this._element.setAttribute("aria-label",M._getUIString("Marker.Title")),M.getCanvasContainer().appendChild(this._element),M.on("move",this._update),M.on("moveend",this._update),M.on("terrain",this._update),M.on("projectiontransition",this._update),this.setDraggable(this._draggable),this._update(),this._map.on("click",this._onMapClick),this}remove(){return this._opacityTimeout&&(clearTimeout(this._opacityTimeout),delete this._opacityTimeout),this._map&&(this._map.off("click",this._onMapClick),this._map.off("move",this._update),this._map.off("moveend",this._update),this._map.off("terrain",this._update),this._map.off("projectiontransition",this._update),this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler),this._map.off("mouseup",this._onUp),this._map.off("touchend",this._onUp),this._map.off("mousemove",this._onMove),this._map.off("touchmove",this._onMove),delete this._map),n.remove(this._element),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(M){return this._lngLat=et.N.convert(M),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(),this}getElement(){return this._element}setPopup(M){if(this._popup&&(this._popup.remove(),this._popup=null,this._element.removeEventListener("keypress",this._onKeyPress),this._originalTabIndex||this._element.removeAttribute("tabindex")),M){if(!("offset"in M.options)){const et=38.1,Bt=13.5,Wt=Math.abs(Bt)/Math.SQRT2;M.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[Wt,-1*(et-Bt+Wt)],"bottom-right":[-Wt,-1*(et-Bt+Wt)],left:[Bt,-1*(et-Bt)],right:[-13.5,-1*(et-Bt)]}:this._offset}this._popup=M,this._originalTabIndex=this._element.getAttribute("tabindex"),this._originalTabIndex||this._element.setAttribute("tabindex","0"),this._element.addEventListener("keypress",this._onKeyPress)}return this}setSubpixelPositioning(M){return this._subpixelPositioning=M,this}getPopup(){return this._popup}togglePopup(){const M=this._popup;return this._element.style.opacity===this._opacityWhenCovered?this:M?(M.isOpen()?M.remove():(M.setLngLat(this._lngLat),M.addTo(this._map)),this):this}_updateOpacity(M=!1){var Bt,Wt;if(!(null===(Bt=this._map)||void 0===Bt?void 0:Bt.terrain)){const M=this._map.transform.isLocationOccluded(this._lngLat)?this._opacityWhenCovered:this._opacity;return void(this._element.style.opacity!==M&&(this._element.style.opacity=M))}if(M)this._opacityTimeout=null;else{if(this._opacityTimeout)return;this._opacityTimeout=setTimeout((()=>{this._opacityTimeout=null}),100)}const Nt=this._map,$t=Nt.terrain.depthAtPoint(this._pos),Gr=Nt.terrain.getElevationForLngLatZoom(this._lngLat,Nt.transform.tileZoom);if(Nt.transform.lngLatToCameraDepth(this._lngLat,Gr)-$t<.006)return void(this._element.style.opacity=this._opacity);const mn=-this._offset.y/Nt.transform.pixelsPerMeter,Hn=Math.sin(Nt.getPitch()*Math.PI/180)*mn,so=Nt.terrain.depthAtPoint(new et.P(this._pos.x,this._pos.y-this._offset.y)),uo=Nt.transform.lngLatToCameraDepth(this._lngLat,Gr+Hn)-so>.006;(null===(Wt=this._popup)||void 0===Wt?void 0:Wt.isOpen())&&uo&&this._popup.remove(),this._element.style.opacity=uo?this._opacityWhenCovered:this._opacity}getOffset(){return this._offset}setOffset(M){return this._offset=et.P.convert(M),this._update(),this}addClassName(M){this._element.classList.add(M)}removeClassName(M){this._element.classList.remove(M)}toggleClassName(M){return this._element.classList.toggle(M)}setDraggable(M){return this._draggable=!!M,this._map&&(M?(this._map.on("mousedown",this._addDragHandler),this._map.on("touchstart",this._addDragHandler)):(this._map.off("mousedown",this._addDragHandler),this._map.off("touchstart",this._addDragHandler))),this}isDraggable(){return this._draggable}setRotation(M){return this._rotation=M||0,this._update(),this}getRotation(){return this._rotation}setRotationAlignment(M){return this._rotationAlignment=M||"auto",this._update(),this}getRotationAlignment(){return this._rotationAlignment}setPitchAlignment(M){return this._pitchAlignment=M&&"auto"!==M?M:this._rotationAlignment,this._update(),this}getPitchAlignment(){return this._pitchAlignment}setOpacity(M,et){return void 0===M&&void 0===et&&(this._opacity="1",this._opacityWhenCovered="0.2"),void 0!==M&&(this._opacity=M),void 0!==et&&(this._opacityWhenCovered=et),this._map&&this._updateOpacity(!0),this}}const qh={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0};let tg=0,eg=!1;const ig={maxWidth:100,unit:"metric"};function qs(M,et,Bt){const Wt=Bt&&Bt.maxWidth||100,Nt=M._container.clientHeight/2,$t=M._container.clientWidth/2,Gr=M.unproject([$t-Wt/2,Nt]),mn=M.unproject([$t+Wt/2,Nt]),Hn=Math.round(M.project(mn).x-M.project(Gr).x),so=Math.min(Wt,Hn,M._container.clientWidth),uo=Gr.distanceTo(mn);if(Bt&&"imperial"===Bt.unit){const Bt=3.2808*uo;Bt>5280?Hs(et,so,Bt/5280,M._getUIString("ScaleControl.Miles")):Hs(et,so,Bt,M._getUIString("ScaleControl.Feet"))}else Bt&&"nautical"===Bt.unit?Hs(et,so,uo/1852,M._getUIString("ScaleControl.NauticalMiles")):uo>=1e3?Hs(et,so,uo/1e3,M._getUIString("ScaleControl.Kilometers")):Hs(et,so,uo,M._getUIString("ScaleControl.Meters"))}function Hs(M,et,Bt,Wt){const Nt=function(M){const et=Math.pow(10,`${Math.floor(M)}`.length-1);let Bt=M/et;return Bt=Bt>=10?10:Bt>=5?5:Bt>=3?3:Bt>=2?2:Bt>=1?1:function(M){const et=Math.pow(10,Math.ceil(-Math.log(M)/Math.LN10));return Math.round(M*et)/et}(Bt),et*Bt}(Bt);M.style.width=et*(Nt/Bt)+"px",M.innerHTML=`${Nt} ${Wt}`}const rg={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",subpixelPositioning:!1},ng=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function $s(M){if(M){if("number"==typeof M){const Bt=Math.round(Math.abs(M)/Math.SQRT2);return{center:new et.P(0,0),top:new et.P(0,M),"top-left":new et.P(Bt,Bt),"top-right":new et.P(-Bt,Bt),bottom:new et.P(0,-M),"bottom-left":new et.P(Bt,-Bt),"bottom-right":new et.P(-Bt,-Bt),left:new et.P(M,0),right:new et.P(-M,0)}}if(M instanceof et.P||Array.isArray(M)){const Bt=et.P.convert(M);return{center:Bt,top:Bt,"top-left":Bt,"top-right":Bt,bottom:Bt,"bottom-left":Bt,"bottom-right":Bt,left:Bt,right:Bt}}return{center:et.P.convert(M.center||[0,0]),top:et.P.convert(M.top||[0,0]),"top-left":et.P.convert(M["top-left"]||[0,0]),"top-right":et.P.convert(M["top-right"]||[0,0]),bottom:et.P.convert(M.bottom||[0,0]),"bottom-left":et.P.convert(M["bottom-left"]||[0,0]),"bottom-right":et.P.convert(M["bottom-right"]||[0,0]),left:et.P.convert(M.left||[0,0]),right:et.P.convert(M.right||[0,0])}}return $s(new et.P(0,0))}const og=Bt;M.AJAXError=et.cg,M.Event=et.k,M.Evented=et.E,M.LngLat=et.N,M.MercatorCoordinate=et.Y,M.Point=et.P,M.addProtocol=et.ch,M.config=et.a,M.removeProtocol=et.ci,M.AttributionControl=ws,M.BoxZoomHandler=jo,M.CanvasSource=J,M.CooperativeGesturesHandler=ms,M.DoubleClickZoomHandler=cs,M.DragPanHandler=ds,M.DragRotateHandler=_s,M.EdgeInsets=Pt,M.FullscreenControl=class extends et.E{constructor(M={}){super(),this._onFullscreenChange=()=>{var M;let et=window.document.fullscreenElement||window.document.mozFullScreenElement||window.document.webkitFullscreenElement||window.document.msFullscreenElement;for(;null===(M=null==et?void 0:et.shadowRoot)||void 0===M?void 0:M.fullscreenElement;)et=et.shadowRoot.fullscreenElement;et===this._container!==this._fullscreen&&this._handleFullscreenChange()},this._onClickFullscreen=()=>{this._isFullscreen()?this._exitFullscreen():this._requestFullscreen()},this._fullscreen=!1,M&&M.container&&(M.container instanceof HTMLElement?this._container=M.container:et.w("Full screen control 'container' must be a DOM element.")),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in document&&(this._fullscreenchange="MSFullscreenChange")}onAdd(M){return this._map=M,this._container||(this._container=this._map.getContainer()),this._controlContainer=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),this._controlContainer}onRemove(){n.remove(this._controlContainer),this._map=null,window.document.removeEventListener(this._fullscreenchange,this._onFullscreenChange)}_setupUI(){const M=this._fullscreenButton=n.create("button","maplibregl-ctrl-fullscreen",this._controlContainer);n.create("span","maplibregl-ctrl-icon",M).setAttribute("aria-hidden","true"),M.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),window.document.addEventListener(this._fullscreenchange,this._onFullscreenChange)}_updateTitle(){const M=this._getTitle();this._fullscreenButton.setAttribute("aria-label",M),this._fullscreenButton.title=M}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_handleFullscreenChange(){this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink"),this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen"),this._updateTitle(),this._fullscreen?(this.fire(new et.k("fullscreenstart")),this._prevCooperativeGesturesEnabled=this._map.cooperativeGestures.isEnabled(),this._map.cooperativeGestures.disable()):(this.fire(new et.k("fullscreenend")),this._prevCooperativeGesturesEnabled&&this._map.cooperativeGestures.enable())}_exitFullscreen(){window.document.exitFullscreen?window.document.exitFullscreen():window.document.mozCancelFullScreen?window.document.mozCancelFullScreen():window.document.msExitFullscreen?window.document.msExitFullscreen():window.document.webkitCancelFullScreen?window.document.webkitCancelFullScreen():this._togglePseudoFullScreen()}_requestFullscreen(){this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen?this._container.webkitRequestFullscreen():this._togglePseudoFullScreen()}_togglePseudoFullScreen(){this._container.classList.toggle("maplibregl-pseudo-fullscreen"),this._handleFullscreenChange(),this._map.resize()}},M.GeoJSONSource=$,M.GeolocateControl=class extends et.E{constructor(M){super(),this._onSuccess=M=>{if(this._map){if(this._isOutOfMapMaxBounds(M))return this._setErrorState(),this.fire(new et.k("outofmaxbounds",M)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=M,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(M),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(M),this.options.showUserLocation&&this._dotElement.classList.remove("maplibregl-user-location-dot-stale"),this.fire(new et.k("geolocate",M)),this._finish()}},this._updateCamera=M=>{const Bt=new et.N(M.coords.longitude,M.coords.latitude),Wt=M.coords.accuracy,Nt=this._map.getBearing(),$t=et.e({bearing:Nt},this.options.fitBoundsOptions),Gr=V.fromLngLat(Bt,Wt);this._map.fitBounds(Gr,$t,{geolocateSource:!0})},this._updateMarker=M=>{if(M){const Bt=new et.N(M.coords.longitude,M.coords.latitude);this._accuracyCircleMarker.setLngLat(Bt).addTo(this._map),this._userLocationDotMarker.setLngLat(Bt).addTo(this._map),this._accuracy=M.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()},this._onZoom=()=>{this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()},this._onError=M=>{if(this._map){if(this.options.trackUserLocation)if(1===M.code){this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const M=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=M,this._geolocateButton.setAttribute("aria-label",M),void 0!==this._geolocationWatchID&&this._clearWatch()}else{if(3===M.code&&eg)return;this._setErrorState()}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("maplibregl-user-location-dot-stale"),this.fire(new et.k("error",M)),this._finish()}},this._finish=()=>{this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0},this._setupUI=()=>{this._map&&(this._container.addEventListener("contextmenu",(M=>M.preventDefault())),this._geolocateButton=n.create("button","maplibregl-ctrl-geolocate",this._container),n.create("span","maplibregl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",this._geolocateButton.disabled=!0)},this._finishSetupUI=M=>{if(this._map){if(!1===M){et.w("Geolocation support is not available so the GeolocateControl will be disabled.");const M=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=M,this._geolocateButton.setAttribute("aria-label",M)}else{const M=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.disabled=!1,this._geolocateButton.title=M,this._geolocateButton.setAttribute("aria-label",M)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=n.create("div","maplibregl-user-location-dot"),this._userLocationDotMarker=new Ns({element:this._dotElement}),this._circleElement=n.create("div","maplibregl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Ns({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",(()=>this.trigger())),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(M=>{M.geolocateSource||"ACTIVE_LOCK"!==this._watchState||M.originalEvent&&"resize"===M.originalEvent.type||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this.fire(new et.k("trackuserlocationend")),this.fire(new et.k("userlocationlostfocus")))}))}},this.options=et.e({},qh,M)}onAdd(M){return this._map=M,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._setupUI(),function(){return et._(this,arguments,void 0,(function*(M=!1){if(void 0!==Yh&&!M)return Yh;if(void 0===window.navigator.permissions)return Yh=!!window.navigator.geolocation,Yh;try{const M=yield window.navigator.permissions.query({name:"geolocation"});Yh="denied"!==M.state}catch(M){Yh=!!window.navigator.geolocation}return Yh}))}().then((M=>this._finishSetupUI(M))),this._container}onRemove(){void 0!==this._geolocationWatchID&&(window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),n.remove(this._container),this._map.off("zoom",this._onZoom),this._map=void 0,tg=0,eg=!1}_isOutOfMapMaxBounds(M){const et=this._map.getMaxBounds(),Bt=M.coords;return et&&(Bt.longitudeet.getEast()||Bt.latitudeet.getNorth())}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");break;case"ACTIVE_ERROR":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}}_updateCircleRadius(){const M=this._map.getBounds(),et=M.getSouthEast(),Bt=M.getNorthEast(),Wt=et.distanceTo(Bt),Nt=Math.ceil(this._accuracy/(Wt/this._map._container.clientHeight)*2);this._circleElement.style.width=`${Nt}px`,this._circleElement.style.height=`${Nt}px`}trigger(){if(!this._setup)return et.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new et.k("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":tg--,eg=!1,this._watchState="OFF",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error"),this.fire(new et.k("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new et.k("trackuserlocationstart")),this.fire(new et.k("userlocationfocus"));break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");break;case"OFF":break;default:throw new Error(`Unexpected watchState ${this._watchState}`)}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){let M;this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),tg++,tg>1?(M={maximumAge:6e5,timeout:0},eg=!0):(M=this.options.positionOptions,eg=!1),this._geolocationWatchID=window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,M)}}else window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return!0}_clearWatch(){window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}},M.GlobeControl=class{constructor(){this._toggleProjection=()=>{var M;const et=null===(M=this._map.getProjection())||void 0===M?void 0:M.type;this._map.setProjection("mercator"!==et&&et?{type:"mercator"}:{type:"globe"}),this._updateGlobeIcon()},this._updateGlobeIcon=()=>{var M;this._globeButton.classList.remove("maplibregl-ctrl-globe"),this._globeButton.classList.remove("maplibregl-ctrl-globe-enabled"),"globe"===(null===(M=this._map.getProjection())||void 0===M?void 0:M.type)?(this._globeButton.classList.add("maplibregl-ctrl-globe-enabled"),this._globeButton.title=this._map._getUIString("GlobeControl.Disable")):(this._globeButton.classList.add("maplibregl-ctrl-globe"),this._globeButton.title=this._map._getUIString("GlobeControl.Enable"))}}onAdd(M){return this._map=M,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._globeButton=n.create("button","maplibregl-ctrl-globe",this._container),n.create("span","maplibregl-ctrl-icon",this._globeButton).setAttribute("aria-hidden","true"),this._globeButton.type="button",this._globeButton.addEventListener("click",this._toggleProjection),this._updateGlobeIcon(),this._map.on("styledata",this._updateGlobeIcon),this._container}onRemove(){n.remove(this._container),this._map.off("styledata",this._updateGlobeIcon),this._globeButton.removeEventListener("click",this._toggleProjection),this._map=void 0}},M.Hash=wo,M.ImageSource=K,M.KeyboardHandler=ss,M.LngLatBounds=V,M.LogoControl=Ts,M.Map=class extends bs{constructor(M){var Bt,Wt;et.cd.mark(et.ce.create);const Nt=Object.assign(Object.assign(Object.assign({},Hh),M),{canvasContextAttributes:Object.assign(Object.assign({},Hh.canvasContextAttributes),M.canvasContextAttributes)});if(null!=Nt.minZoom&&null!=Nt.maxZoom&&Nt.minZoom>Nt.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=Nt.minPitch&&null!=Nt.maxPitch&&Nt.minPitch>Nt.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=Nt.minPitch&&Nt.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=Nt.maxPitch&&Nt.maxPitch>180)throw new Error("maxPitch must be less than or equal to 180");const $t=new Dt,Gr=new kt;if(void 0!==Nt.minZoom&&$t.setMinZoom(Nt.minZoom),void 0!==Nt.maxZoom&&$t.setMaxZoom(Nt.maxZoom),void 0!==Nt.minPitch&&$t.setMinPitch(Nt.minPitch),void 0!==Nt.maxPitch&&$t.setMaxPitch(Nt.maxPitch),void 0!==Nt.renderWorldCopies&&$t.setRenderWorldCopies(Nt.renderWorldCopies),super($t,Gr,{bearingSnap:Nt.bearingSnap}),this._idleTriggered=!1,this._crossFadingFactor=1,this._renderTaskQueue=new Ps,this._controls=[],this._mapId=et.a1(),this._contextLost=M=>{M.preventDefault(),this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this.fire(new et.k("webglcontextlost",{originalEvent:M}))},this._contextRestored=M=>{this._setupPainter(),this.resize(),this._update(),this.fire(new et.k("webglcontextrestored",{originalEvent:M}))},this._onMapScroll=M=>{if(M.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1},this._onWindowOnline=()=>{this._update()},this._interactive=Nt.interactive,this._maxTileCacheSize=Nt.maxTileCacheSize,this._maxTileCacheZoomLevels=Nt.maxTileCacheZoomLevels,this._canvasContextAttributes=Object.assign({},Nt.canvasContextAttributes),this._trackResize=!0===Nt.trackResize,this._bearingSnap=Nt.bearingSnap,this._centerClampedToGround=Nt.centerClampedToGround,this._refreshExpiredTiles=!0===Nt.refreshExpiredTiles,this._fadeDuration=Nt.fadeDuration,this._crossSourceCollisions=!0===Nt.crossSourceCollisions,this._collectResourceTiming=!0===Nt.collectResourceTiming,this._locale=Object.assign(Object.assign({},Xh),Nt.locale),this._clickTolerance=Nt.clickTolerance,this._overridePixelRatio=Nt.pixelRatio,this._maxCanvasSize=Nt.maxCanvasSize,this.transformCameraUpdate=Nt.transformCameraUpdate,this.cancelPendingTileRequestsWhileZooming=!0===Nt.cancelPendingTileRequestsWhileZooming,this._imageQueueHandle=Io.addThrottleControl((()=>this.isMoving())),this._requestManager=new m(Nt.transformRequest),"string"==typeof Nt.container){if(this._container=document.getElementById(Nt.container),!this._container)throw new Error(`Container '${Nt.container}' not found.`)}else{if(!(Nt.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=Nt.container}if(Nt.maxBounds&&this.setMaxBounds(Nt.maxBounds),this._setupContainer(),this._setupPainter(),this.on("move",(()=>this._update(!1))),this.on("moveend",(()=>this._update(!1))),this.on("zoom",(()=>this._update(!0))),this.on("terrain",(()=>{this.painter.terrainFacilitator.dirty=!0,this._update(!0)})),this.once("idle",(()=>{this._idleTriggered=!0})),"undefined"!=typeof window){addEventListener("online",this._onWindowOnline,!1);let M=!1;const et=yo((M=>{this._trackResize&&!this._removed&&(this.resize(M),this.redraw())}),50);this._resizeObserver=new ResizeObserver((Bt=>{M?et(Bt):M=!0})),this._resizeObserver.observe(this._container)}this.handlers=new xs(this,Nt),this._hash=Nt.hash&&new wo("string"==typeof Nt.hash&&Nt.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:Nt.center,elevation:Nt.elevation,zoom:Nt.zoom,bearing:Nt.bearing,pitch:Nt.pitch,roll:Nt.roll}),Nt.bounds&&(this.resize(),this.fitBounds(Nt.bounds,et.e({},Nt.fitBoundsOptions,{duration:0}))));const mn="string"==typeof Nt.style||!("globe"===(null===(Wt=null===(Bt=Nt.style)||void 0===Bt?void 0:Bt.projection)||void 0===Wt?void 0:Wt.type));this.resize(null,mn),this._localIdeographFontFamily=Nt.localIdeographFontFamily,this._validateStyle=Nt.validateStyle,Nt.style&&this.setStyle(Nt.style,{localIdeographFontFamily:Nt.localIdeographFontFamily}),Nt.attributionControl&&this.addControl(new ws("boolean"==typeof Nt.attributionControl?void 0:Nt.attributionControl)),Nt.maplibreLogo&&this.addControl(new Ts,Nt.logoPosition),this.on("style.load",(()=>{if(mn||this._resizeTransform(),this.transform.unmodified){const M=et.M(this.style.stylesheet,["center","zoom","bearing","pitch","roll"]);this.jumpTo(M)}})),this.on("data",(M=>{this._update("style"===M.dataType),this.fire(new et.k(`${M.dataType}data`,M))})),this.on("dataloading",(M=>{this.fire(new et.k(`${M.dataType}dataloading`,M))})),this.on("dataabort",(M=>{this.fire(new et.k("sourcedataabort",M))}))}_getMapId(){return this._mapId}addControl(M,Bt){if(void 0===Bt&&(Bt=M.getDefaultPosition?M.getDefaultPosition():"top-right"),!M||!M.onAdd)return this.fire(new et.j(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const Wt=M.onAdd(this);this._controls.push(M);const Nt=this._controlPositions[Bt];return-1!==Bt.indexOf("bottom")?Nt.insertBefore(Wt,Nt.firstChild):Nt.appendChild(Wt),this}removeControl(M){if(!M||!M.onRemove)return this.fire(new et.j(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const Bt=this._controls.indexOf(M);return Bt>-1&&this._controls.splice(Bt,1),M.onRemove(this),this}hasControl(M){return this._controls.indexOf(M)>-1}calculateCameraOptionsFromTo(M,et,Bt,Wt){return null==Wt&&this.terrain&&(Wt=this.terrain.getElevationForLngLatZoom(Bt,this.transform.tileZoom)),super.calculateCameraOptionsFromTo(M,et,Bt,Wt)}resize(M,Bt=!0){const[Wt,Nt]=this._containerDimensions(),$t=this._getClampedPixelRatio(Wt,Nt);if(this._resizeCanvas(Wt,Nt,$t),this.painter.resize(Wt,Nt,$t),this.painter.overLimit()){const M=this.painter.context.gl;this._maxCanvasSize=[M.drawingBufferWidth,M.drawingBufferHeight];const et=this._getClampedPixelRatio(Wt,Nt);this._resizeCanvas(Wt,Nt,et),this.painter.resize(Wt,Nt,et)}this._resizeTransform(Bt);const Gr=!this._moving;return Gr&&(this.stop(),this.fire(new et.k("movestart",M)).fire(new et.k("move",M))),this.fire(new et.k("resize",M)),Gr&&this.fire(new et.k("moveend",M)),this}_resizeTransform(M=!0){var et;const[Bt,Wt]=this._containerDimensions();this.transform.resize(Bt,Wt,M),null===(et=this._requestedCameraState)||void 0===et||et.resize(Bt,Wt,M)}_getClampedPixelRatio(M,et){const{0:Bt,1:Wt}=this._maxCanvasSize,Nt=this.getPixelRatio(),$t=M*Nt,Gr=et*Nt;return Math.min($t>Bt?Bt/$t:1,Gr>Wt?Wt/Gr:1)*Nt}getPixelRatio(){var M;return null!==(M=this._overridePixelRatio)&&void 0!==M?M:devicePixelRatio}setPixelRatio(M){this._overridePixelRatio=M,this.resize()}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()}setMaxBounds(M){return this.transform.setMaxBounds(V.convert(M)),this._update()}setMinZoom(M){if((M=null==M?-2:M)>=-2&&M<=this.transform.maxZoom)return this.transform.setMinZoom(M),this._update(),this.getZoom()=this.transform.minZoom)return this.transform.setMaxZoom(M),this._update(),this.getZoom()>M&&this.setZoom(M),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(M){if((M=null==M?0:M)<0)throw new Error("minPitch must be greater than or equal to 0");if(M>=0&&M<=this.transform.maxPitch)return this.transform.setMinPitch(M),this._update(),this.getPitch()180)throw new Error("maxPitch must be less than or equal to 180");if(M>=this.transform.minPitch)return this.transform.setMaxPitch(M),this._update(),this.getPitch()>M&&this.setPitch(M),this;throw new Error("maxPitch must be greater than the current minPitch")}getMaxPitch(){return this.transform.maxPitch}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(M){return this.transform.setRenderWorldCopies(M),this._update()}project(M){return this.transform.locationToScreenPoint(et.N.convert(M),this.style&&this.terrain)}unproject(M){return this.transform.screenPointToLocation(et.P.convert(M),this.terrain)}isMoving(){var M;return this._moving||(null===(M=this.handlers)||void 0===M?void 0:M.isMoving())}isZooming(){var M;return this._zooming||(null===(M=this.handlers)||void 0===M?void 0:M.isZooming())}isRotating(){var M;return this._rotating||(null===(M=this.handlers)||void 0===M?void 0:M.isRotating())}_createDelegatedListener(M,et,Bt){if("mouseenter"===M||"mouseover"===M){let Wt=!1;const o=Nt=>{const $t=et.filter((M=>this.getLayer(M))),Gr=0!==$t.length?this.queryRenderedFeatures(Nt.point,{layers:$t}):[];Gr.length?Wt||(Wt=!0,Bt.call(this,new zo(M,this,Nt.originalEvent,{features:Gr}))):Wt=!1};return{layers:et,listener:Bt,delegates:{mousemove:o,mouseout:()=>{Wt=!1}}}}if("mouseleave"===M||"mouseout"===M){let Wt=!1;const o=Nt=>{const $t=et.filter((M=>this.getLayer(M)));(0!==$t.length?this.queryRenderedFeatures(Nt.point,{layers:$t}):[]).length?Wt=!0:Wt&&(Wt=!1,Bt.call(this,new zo(M,this,Nt.originalEvent)))},s=et=>{Wt&&(Wt=!1,Bt.call(this,new zo(M,this,et.originalEvent)))};return{layers:et,listener:Bt,delegates:{mousemove:o,mouseout:s}}}{const r=M=>{const Wt=et.filter((M=>this.getLayer(M))),Nt=0!==Wt.length?this.queryRenderedFeatures(M.point,{layers:Wt}):[];Nt.length&&(M.features=Nt,Bt.call(this,M),delete M.features)};return{layers:et,listener:Bt,delegates:{[M]:r}}}}_saveDelegatedListener(M,et){this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[M]=this._delegatedListeners[M]||[],this._delegatedListeners[M].push(et)}_removeDelegatedListener(M,et,Bt){if(!this._delegatedListeners||!this._delegatedListeners[M])return;const Wt=this._delegatedListeners[M];for(let M=0;Met.includes(M)))){for(const M in Nt.delegates)this.off(M,Nt.delegates[M]);return void Wt.splice(M,1)}}}on(M,et,Bt){if(void 0===Bt)return super.on(M,et);const Wt="string"==typeof et?[et]:et,Nt=this._createDelegatedListener(M,Wt,Bt);this._saveDelegatedListener(M,Nt);for(const M in Nt.delegates)this.on(M,Nt.delegates[M]);return{unsubscribe:()=>{this._removeDelegatedListener(M,Wt,Bt)}}}once(M,et,Bt){if(void 0===Bt)return super.once(M,et);const Wt="string"==typeof et?[et]:et,Nt=this._createDelegatedListener(M,Wt,Bt);for(const et in Nt.delegates){const $t=Nt.delegates[et];Nt.delegates[et]=(...et)=>{this._removeDelegatedListener(M,Wt,Bt),$t(...et)}}this._saveDelegatedListener(M,Nt);for(const M in Nt.delegates)this.once(M,Nt.delegates[M]);return this}off(M,et,Bt){return void 0===Bt?super.off(M,et):(this._removeDelegatedListener(M,"string"==typeof et?[et]:et,Bt),this)}queryRenderedFeatures(M,Bt){if(!this.style)return[];let Wt;const Nt=M instanceof et.P||Array.isArray(M),$t=Nt?M:[[0,0],[this.transform.width,this.transform.height]];if(Bt=Bt||(Nt?{}:M)||{},$t instanceof et.P||"number"==typeof $t[0])Wt=[et.P.convert($t)];else{const M=et.P.convert($t[0]),Bt=et.P.convert($t[1]);Wt=[M,new et.P(Bt.x,M.y),Bt,new et.P(M.x,Bt.y),M]}return this.style.queryRenderedFeatures(Wt,Bt,this.transform)}querySourceFeatures(M,et){return this.style.querySourceFeatures(M,et)}setStyle(M,Bt){return!1!==(Bt=et.e({},{localIdeographFontFamily:this._localIdeographFontFamily,validate:this._validateStyle},Bt)).diff&&Bt.localIdeographFontFamily===this._localIdeographFontFamily&&this.style&&M?(this._diffStyle(M,Bt),this):(this._localIdeographFontFamily=Bt.localIdeographFontFamily,this._updateStyle(M,Bt))}setTransformRequest(M){return this._requestManager.setTransformRequest(M),this}_getUIString(M){const et=this._locale[M];if(null==et)throw new Error(`Missing UI string '${M}'`);return et}_updateStyle(M,et){var Bt,Wt;if(et.transformStyle&&this.style&&!this.style._loaded)return void this.style.once("style.load",(()=>this._updateStyle(M,et)));const Nt=this.style&&et.transformStyle?this.style.serialize():void 0;return this.style&&(this.style.setEventedParent(null),this.style._remove(!M)),M?(this.style=new gi(this,et||{}),this.style.setEventedParent(this,{style:this.style}),"string"==typeof M?this.style.loadURL(M,et,Nt):this.style.loadJSON(M,et,Nt),this):(null===(Wt=null===(Bt=this.style)||void 0===Bt?void 0:Bt.projection)||void 0===Wt||Wt.destroy(),delete this.style,this)}_lazyInitEmptyStyle(){this.style||(this.style=new gi(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty())}_diffStyle(M,Bt){if("string"==typeof M){const Wt=this._requestManager.transformRequest(M,"Style");et.h(Wt,new AbortController).then((M=>{this._updateDiff(M.data,Bt)})).catch((M=>{M&&this.fire(new et.j(M))}))}else"object"==typeof M&&this._updateDiff(M,Bt)}_updateDiff(M,Bt){try{this.style.setState(M,Bt)&&this._update(!0)}catch(Wt){et.w(`Unable to perform style diff: ${Wt.message||Wt.error||Wt}. Rebuilding the style from scratch.`),this._updateStyle(M,Bt)}}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():et.w("There is no style added to the map.")}addSource(M,et){return this._lazyInitEmptyStyle(),this.style.addSource(M,et),this._update(!0)}isSourceLoaded(M){const Bt=this.style&&this.style.sourceCaches[M];if(void 0!==Bt)return Bt.loaded();this.fire(new et.j(new Error(`There is no source with ID '${M}'`)))}setTerrain(M){if(this.style._checkLoaded(),this._terrainDataCallback&&this.style.off("data",this._terrainDataCallback),M){const Bt=this.style.sourceCaches[M.source];if(!Bt)throw new Error(`cannot load terrain, because there exists no source with ID: ${M.source}`);null===this.terrain&&Bt.reload();for(const Bt in this.style._layers){const Wt=this.style._layers[Bt];"hillshade"===Wt.type&&Wt.source===M.source&&et.w("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.")}this.terrain=new Es(this.painter,Bt,M),this.painter.renderToTexture=new Rs(this.painter,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._terrainDataCallback=et=>{"style"===et.dataType?this.terrain.sourceCache.freeRtt():"source"===et.dataType&&et.tile&&(et.sourceId!==M.source||this._elevationFreeze||(this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))),this.terrain.sourceCache.freeRtt(et.tile.tileID))},this.style.on("data",this._terrainDataCallback)}else this.terrain&&this.terrain.sourceCache.destruct(),this.terrain=null,this.painter.renderToTexture&&this.painter.renderToTexture.destruct(),this.painter.renderToTexture=null,this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0);return this.fire(new et.k("terrain",{terrain:M})),this}getTerrain(){var M,et;return null!==(et=null===(M=this.terrain)||void 0===M?void 0:M.options)&&void 0!==et?et:null}areTilesLoaded(){const M=this.style&&this.style.sourceCaches;for(const et in M){const Bt=M[et]._tiles;for(const M in Bt){const et=Bt[M];if("loaded"!==et.state&&"errored"!==et.state)return!1}}return!0}removeSource(M){return this.style.removeSource(M),this._update(!0)}getSource(M){return this.style.getSource(M)}addImage(M,Bt,Wt={}){const{pixelRatio:Nt=1,sdf:Gr=!1,stretchX:mn,stretchY:Hn,content:so,textFitWidth:uo,textFitHeight:Io}=Wt;if(this._lazyInitEmptyStyle(),!(Bt instanceof HTMLImageElement||et.b(Bt))){if(void 0===Bt.width||void 0===Bt.height)return this.fire(new et.j(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));{const{width:Wt,height:$t,data:Po}=Bt,To=Bt;return this.style.addImage(M,{data:new et.R({width:Wt,height:$t},new Uint8Array(Po)),pixelRatio:Nt,stretchX:mn,stretchY:Hn,content:so,textFitWidth:uo,textFitHeight:Io,sdf:Gr,version:0,userImage:To}),To.onAdd&&To.onAdd(this,M),this}}{const{width:Wt,height:Po,data:To}=$t.getImageData(Bt);this.style.addImage(M,{data:new et.R({width:Wt,height:Po},To),pixelRatio:Nt,stretchX:mn,stretchY:Hn,content:so,textFitWidth:uo,textFitHeight:Io,sdf:Gr,version:0})}}updateImage(M,Bt){const Wt=this.style.getImage(M);if(!Wt)return this.fire(new et.j(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const Nt=Bt instanceof HTMLImageElement||et.b(Bt)?$t.getImageData(Bt):Bt,{width:Gr,height:mn,data:Hn}=Nt;if(void 0===Gr||void 0===mn)return this.fire(new et.j(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(Gr!==Wt.data.width||mn!==Wt.data.height)return this.fire(new et.j(new Error("The width and height of the updated image must be that same as the previous version of the image")));const so=!(Bt instanceof HTMLImageElement||et.b(Bt));return Wt.data.replace(Hn,so),this.style.updateImage(M,Wt),this}getImage(M){return this.style.getImage(M)}hasImage(M){return M?!!this.style.getImage(M):(this.fire(new et.j(new Error("Missing required image id"))),!1)}removeImage(M){this.style.removeImage(M)}loadImage(M){return Io.getImage(this._requestManager.transformRequest(M,"Image"),new AbortController)}listImages(){return this.style.listImages()}addLayer(M,et){return this._lazyInitEmptyStyle(),this.style.addLayer(M,et),this._update(!0)}moveLayer(M,et){return this.style.moveLayer(M,et),this._update(!0)}removeLayer(M){return this.style.removeLayer(M),this._update(!0)}getLayer(M){return this.style.getLayer(M)}getLayersOrder(){return this.style.getLayersOrder()}setLayerZoomRange(M,et,Bt){return this.style.setLayerZoomRange(M,et,Bt),this._update(!0)}setFilter(M,et,Bt={}){return this.style.setFilter(M,et,Bt),this._update(!0)}getFilter(M){return this.style.getFilter(M)}setPaintProperty(M,et,Bt,Wt={}){return this.style.setPaintProperty(M,et,Bt,Wt),this._update(!0)}getPaintProperty(M,et){return this.style.getPaintProperty(M,et)}setLayoutProperty(M,et,Bt,Wt={}){return this.style.setLayoutProperty(M,et,Bt,Wt),this._update(!0)}getLayoutProperty(M,et){return this.style.getLayoutProperty(M,et)}setGlyphs(M,et={}){return this._lazyInitEmptyStyle(),this.style.setGlyphs(M,et),this._update(!0)}getGlyphs(){return this.style.getGlyphsUrl()}addSprite(M,et,Bt={}){return this._lazyInitEmptyStyle(),this.style.addSprite(M,et,Bt,(M=>{M||this._update(!0)})),this}removeSprite(M){return this._lazyInitEmptyStyle(),this.style.removeSprite(M),this._update(!0)}getSprite(){return this.style.getSprite()}setSprite(M,et={}){return this._lazyInitEmptyStyle(),this.style.setSprite(M,et,(M=>{M||this._update(!0)})),this}setLight(M,et={}){return this._lazyInitEmptyStyle(),this.style.setLight(M,et),this._update(!0)}getLight(){return this.style.getLight()}setSky(M,et={}){return this._lazyInitEmptyStyle(),this.style.setSky(M,et),this._update(!0)}getSky(){return this.style.getSky()}setFeatureState(M,et){return this.style.setFeatureState(M,et),this._update()}removeFeatureState(M,et){return this.style.removeFeatureState(M,et),this._update()}getFeatureState(M){return this.style.getFeatureState(M)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}_containerDimensions(){let M=0,et=0;return this._container&&(M=this._container.clientWidth||400,et=this._container.clientHeight||300),[M,et]}_setupContainer(){const M=this._container;M.classList.add("maplibregl-map");const et=this._canvasContainer=n.create("div","maplibregl-canvas-container",M);this._interactive&&et.classList.add("maplibregl-interactive"),this._canvas=n.create("canvas","maplibregl-canvas",et),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("tabindex",this._interactive?"0":"-1"),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region");const Bt=this._containerDimensions(),Wt=this._getClampedPixelRatio(Bt[0],Bt[1]);this._resizeCanvas(Bt[0],Bt[1],Wt);const Nt=this._controlContainer=n.create("div","maplibregl-control-container",M),$t=this._controlPositions={};["top-left","top-right","bottom-left","bottom-right"].forEach((M=>{$t[M]=n.create("div",`maplibregl-ctrl-${M} `,Nt)})),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(M,et,Bt){this._canvas.width=Math.floor(Bt*M),this._canvas.height=Math.floor(Bt*et),this._canvas.style.width=`${M}px`,this._canvas.style.height=`${et}px`}_setupPainter(){const M=Object.assign(Object.assign({},this._canvasContextAttributes),{alpha:!0,depth:!0,stencil:!0,premultipliedAlpha:!0});let et=null;this._canvas.addEventListener("webglcontextcreationerror",(Bt=>{et={requestedAttributes:M},Bt&&(et.statusMessage=Bt.statusMessage,et.type=Bt.type)}),{once:!0});let Bt=null;if(Bt=this._canvasContextAttributes.contextType?this._canvas.getContext(this._canvasContextAttributes.contextType,M):this._canvas.getContext("webgl2",M)||this._canvas.getContext("webgl",M),!Bt){const M="Failed to initialize WebGL";throw et?(et.message=M,new Error(JSON.stringify(et))):new Error(M)}this.painter=new bo(Bt,this.transform),Gr.testSupport(Bt)}migrateProjection(M,Bt){super.migrateProjection(M,Bt),this.painter.transform=M,this.fire(new et.k("projectiontransition",{newProjection:this.style.projection.name}))}loaded(){return!this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}_update(M){return this.style&&this.style._loaded?(this._styleDirty=this._styleDirty||M,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(M){return this._update(),this._renderTaskQueue.add(M)}_cancelRenderFrame(M){this._renderTaskQueue.remove(M)}_render(M){var Bt,Wt,Nt,Gr,mn;const Hn=this._idleTriggered?this._fadeDuration:0,so=(null===(Bt=this.style.projection)||void 0===Bt?void 0:Bt.transitionState)>0;if(this.painter.context.setDirty(),this.painter.setBaseState(),this._renderTaskQueue.run(M),this._removed)return;let uo=!1;if(this.style&&this._styleDirty){this._styleDirty=!1;const M=this.transform.zoom,Bt=$t.now();this.style.zoomHistory.update(M,Bt);const Wt=new et.z(M,{now:Bt,fadeDuration:Hn,zoomHistory:this.style.zoomHistory,transition:this.style.getTransition()}),Nt=Wt.crossFadingFactor();1===Nt&&Nt===this._crossFadingFactor||(uo=!0,this._crossFadingFactor=Nt),this.style.update(Wt)}const Io=(null===(Wt=this.style.projection)||void 0===Wt?void 0:Wt.transitionState)>0!==so;null===(Nt=this.style.projection)||void 0===Nt||Nt.setErrorQueryLatitudeDegrees(this.transform.center.lat),this.transform.setTransitionState(null===(Gr=this.style.projection)||void 0===Gr?void 0:Gr.transitionState,null===(mn=this.style.projection)||void 0===mn?void 0:mn.latitudeErrorCorrectionRadians),this.style&&(this._sourcesDirty||Io)&&(this._sourcesDirty=!1,this.style._updateSources(this.transform)),this.terrain?(this.terrain.sourceCache.update(this.transform,this.terrain),this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this.transform.center,this.transform.tileZoom)),!this._elevationFreeze&&this._centerClampedToGround&&this.transform.setElevation(this.terrain.getElevationForLngLatZoom(this.transform.center,this.transform.tileZoom))):(this.transform.setMinElevationForCurrentTile(0),this._centerClampedToGround&&this.transform.setElevation(0)),this._placementDirty=this.style&&this.style._updatePlacement(this.transform,this.showCollisionBoxes,Hn,this._crossSourceCollisions,Io),this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showOverdrawInspector:this._showOverdrawInspector,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:Hn,showPadding:this.showPadding}),this.fire(new et.k("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,et.cd.mark(et.ce.load),this.fire(new et.k("load"))),this.style&&(this.style.hasTransitions()||uo)&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles();const Po=this._sourcesDirty||this._styleDirty||this._placementDirty;return Po||this._repaint?this.triggerRepaint():!this.isMoving()&&this.loaded()&&this.fire(new et.k("idle")),!this._loaded||this._fullyLoaded||Po||(this._fullyLoaded=!0,et.cd.mark(et.ce.fullLoad)),this}redraw(){return this.style&&(this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._render(0)),this}remove(){var M;this._hash&&this._hash.remove();for(const M of this._controls)M.onRemove(this);this._controls=[],this._frameRequest&&(this._frameRequest.abort(),this._frameRequest=null),this._renderTaskQueue.clear(),this.painter.destroy(),this.handlers.destroy(),delete this.handlers,this.setStyle(null),"undefined"!=typeof window&&removeEventListener("online",this._onWindowOnline,!1),Io.removeThrottleControl(this._imageQueueHandle),null===(M=this._resizeObserver)||void 0===M||M.disconnect();const Bt=this.painter.context.gl.getExtension("WEBGL_lose_context");(null==Bt?void 0:Bt.loseContext)&&Bt.loseContext(),this._canvas.removeEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.removeEventListener("webglcontextlost",this._contextLost,!1),n.remove(this._canvasContainer),n.remove(this._controlContainer),this._container.removeEventListener("scroll",this._onMapScroll,!1),this._container.classList.remove("maplibregl-map"),et.cd.clearMetrics(),this._removed=!0,this.fire(new et.k("remove"))}triggerRepaint(){this.style&&!this._frameRequest&&(this._frameRequest=new AbortController,$t.frameAsync(this._frameRequest).then((M=>{et.cd.frame(M),this._frameRequest=null,this._render(M)})).catch((M=>{if(!et.cf(M)&&!function(M){return M.message===Ic}(M))throw M})))}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(M){this._showTileBoundaries!==M&&(this._showTileBoundaries=M,this._update())}get showPadding(){return!!this._showPadding}set showPadding(M){this._showPadding!==M&&(this._showPadding=M,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(M){this._showCollisionBoxes!==M&&(this._showCollisionBoxes=M,M?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(M){this._showOverdrawInspector!==M&&(this._showOverdrawInspector=M,this._update())}get repaint(){return!!this._repaint}set repaint(M){this._repaint!==M&&(this._repaint=M,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(M){this._vertices=M,this._update()}get version(){return Lh}getCameraTargetElevation(){return this.transform.elevation}getProjection(){return this.style.getProjection()}setProjection(M){return this._lazyInitEmptyStyle(),this.style.setProjection(M),this._update(!0)}},M.MapMouseEvent=zo,M.MapTouchEvent=Ao,M.MapWheelEvent=Lo,M.Marker=Ns,M.NavigationControl=class{constructor(M){this._updateZoomButtons=()=>{const M=this._map.getZoom(),et=M===this._map.getMaxZoom(),Bt=M===this._map.getMinZoom();this._zoomInButton.disabled=et,this._zoomOutButton.disabled=Bt,this._zoomInButton.setAttribute("aria-disabled",et.toString()),this._zoomOutButton.setAttribute("aria-disabled",Bt.toString())},this._rotateCompassArrow=()=>{this._compassIcon.style.transform=this.options.visualizePitch&&this.options.visualizeRoll?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateZ(${-this._map.transform.roll}deg) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(this._map.transform.pitchInRadians),.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${-this._map.transform.bearing}deg)`:this.options.visualizeRoll?`rotate(${-this._map.transform.bearing-this._map.transform.roll}deg)`:`rotate(${-this._map.transform.bearing}deg)`},this._setButtonTitle=(M,et)=>{const Bt=this._map._getUIString(`NavigationControl.${et}`);M.title=Bt,M.setAttribute("aria-label",Bt)},this.options=et.e({},Kh,M),this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._container.addEventListener("contextmenu",(M=>M.preventDefault())),this.options.showZoom&&(this._zoomInButton=this._createButton("maplibregl-ctrl-zoom-in",(M=>this._map.zoomIn({},{originalEvent:M}))),n.create("span","maplibregl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("maplibregl-ctrl-zoom-out",(M=>this._map.zoomOut({},{originalEvent:M}))),n.create("span","maplibregl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(this._compass=this._createButton("maplibregl-ctrl-compass",(M=>{this.options.visualizePitch?this._map.resetNorthPitch({},{originalEvent:M}):this._map.resetNorth({},{originalEvent:M})})),this._compassIcon=n.create("span","maplibregl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}onAdd(M){return this._map=M,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),this._map.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&this._map.on("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.on("roll",this._rotateCompassArrow),this._map.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new ks(this._map,this._compass,this.options.visualizePitch)),this._container}onRemove(){n.remove(this._container),this.options.showZoom&&this._map.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&this._map.off("pitch",this._rotateCompassArrow),this.options.visualizeRoll&&this._map.off("roll",this._rotateCompassArrow),this._map.off("rotate",this._rotateCompassArrow),this._handler.off(),delete this._handler),delete this._map}_createButton(M,et){const Bt=n.create("button",M,this._container);return Bt.type="button",Bt.addEventListener("click",et),Bt}},M.Popup=class extends et.E{constructor(M){super(),this.remove=()=>(this._content&&n.remove(this._content),this._container&&(n.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._onMouseMove),this._map.off("mouseup",this._onMouseUp),this._map.off("drag",this._onDrag),this._map._canvasContainer.classList.remove("maplibregl-track-pointer"),delete this._map,this.fire(new et.k("close"))),this),this._onMouseUp=M=>{this._update(M.point)},this._onMouseMove=M=>{this._update(M.point)},this._onDrag=M=>{this._update(M.point)},this._update=M=>{var et;if(!this._map||!this._lngLat&&!this._trackPointer||!this._content)return;if(!this._container){if(this._container=n.create("div","maplibregl-popup",this._map.getContainer()),this._tip=n.create("div","maplibregl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className)for(const M of this.options.className.split(" "))this._container.classList.add(M);this._closeButton&&this._closeButton.setAttribute("aria-label",this._map._getUIString("Popup.Close")),this._trackPointer&&this._container.classList.add("maplibregl-popup-track-pointer")}if(this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._lngLat=this._map.transform.renderWorldCopies&&!this._trackPointer?Bs(this._lngLat,this._flatPos,this._map.transform):null===(et=this._lngLat)||void 0===et?void 0:et.wrap(),this._trackPointer&&!M)return;const Bt=this._flatPos=this._pos=this._trackPointer&&M?M:this._map.project(this._lngLat);this._map.terrain&&(this._flatPos=this._trackPointer&&M?M:this._map.transform.locationToScreenPoint(this._lngLat));let Wt=this.options.anchor;const Nt=$s(this.options.offset);if(!Wt){const M=this._container.offsetWidth,et=this._container.offsetHeight;let $t;$t=Bt.y+Nt.bottom.ythis._map.transform.height-et?["bottom"]:[],Bt.xthis._map.transform.width-M/2&&$t.push("right"),Wt=0===$t.length?"bottom":$t.join("-")}let $t=Bt.add(Nt[Wt]);this.options.subpixelPositioning||($t=$t.round()),n.setTransform(this._container,`${Qh[Wt]} translate(${$t.x}px,${$t.y}px)`),Os(this._container,Wt,"popup")},this._onClose=()=>{this.remove()},this.options=et.e(Object.create(rg),M)}addTo(M){return this._map&&this.remove(),this._map=M,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._focusFirstElement(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")):this._map.on("move",this._update),this.fire(new et.k("open")),this}isOpen(){return!!this._map}getLngLat(){return this._lngLat}setLngLat(M){return this._lngLat=et.N.convert(M),this._pos=null,this._flatPos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.remove("maplibregl-track-pointer")),this}trackPointer(){return this._trackPointer=!0,this._pos=null,this._flatPos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("maplibregl-popup-track-pointer"),this._map._canvasContainer.classList.add("maplibregl-track-pointer")),this}getElement(){return this._container}setText(M){return this.setDOMContent(document.createTextNode(M))}setHTML(M){const et=document.createDocumentFragment(),Bt=document.createElement("body");let Wt;for(Bt.innerHTML=M;Wt=Bt.firstChild,Wt;)et.appendChild(Wt);return this.setDOMContent(et)}getMaxWidth(){var M;return null===(M=this._container)||void 0===M?void 0:M.style.maxWidth}setMaxWidth(M){return this.options.maxWidth=M,this._update(),this}setDOMContent(M){if(this._content)for(;this._content.hasChildNodes();)this._content.firstChild&&this._content.removeChild(this._content.firstChild);else this._content=n.create("div","maplibregl-popup-content",this._container);return this._content.appendChild(M),this._createCloseButton(),this._update(),this._focusFirstElement(),this}addClassName(M){return this._container&&this._container.classList.add(M),this}removeClassName(M){return this._container&&this._container.classList.remove(M),this}setOffset(M){return this.options.offset=M,this._update(),this}toggleClassName(M){if(this._container)return this._container.classList.toggle(M)}setSubpixelPositioning(M){this.options.subpixelPositioning=M}_createCloseButton(){this.options.closeButton&&(this._closeButton=n.create("button","maplibregl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose))}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const M=this._container.querySelector(ng);M&&M.focus()}},M.RasterDEMTileSource=X,M.RasterTileSource=W,M.ScaleControl=class{constructor(M){this._onMove=()=>{qs(this._map,this._container,this.options)},this.setUnit=M=>{this.options.unit=M,qs(this._map,this._container,this.options)},this.options=Object.assign(Object.assign({},ig),M)}getDefaultPosition(){return"bottom-left"}onAdd(M){return this._map=M,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-scale",M.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container}onRemove(){n.remove(this._container),this._map.off("move",this._onMove),this._map=void 0}},M.ScrollZoomHandler=ls,M.Style=gi,M.TerrainControl=class{constructor(M){this._toggleTerrain=()=>{this._map.getTerrain()?this._map.setTerrain(null):this._map.setTerrain(this.options),this._updateTerrainIcon()},this._updateTerrainIcon=()=>{this._terrainButton.classList.remove("maplibregl-ctrl-terrain"),this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled"),this._map.terrain?(this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled"),this._terrainButton.title=this._map._getUIString("TerrainControl.Disable")):(this._terrainButton.classList.add("maplibregl-ctrl-terrain"),this._terrainButton.title=this._map._getUIString("TerrainControl.Enable"))},this.options=M}onAdd(M){return this._map=M,this._container=n.create("div","maplibregl-ctrl maplibregl-ctrl-group"),this._terrainButton=n.create("button","maplibregl-ctrl-terrain",this._container),n.create("span","maplibregl-ctrl-icon",this._terrainButton).setAttribute("aria-hidden","true"),this._terrainButton.type="button",this._terrainButton.addEventListener("click",this._toggleTerrain),this._updateTerrainIcon(),this._map.on("terrain",this._updateTerrainIcon),this._container}onRemove(){n.remove(this._container),this._map.off("terrain",this._updateTerrainIcon),this._map=void 0}},M.TwoFingersTouchPitchHandler=rs,M.TwoFingersTouchRotateHandler=ts,M.TwoFingersTouchZoomHandler=Qo,M.TwoFingersTouchZoomRotateHandler=ps,M.VectorTileSource=H,M.VideoSource=Y,M.addSourceType=(M,Bt)=>et._(void 0,void 0,void 0,(function*(){if(ee(M))throw new Error(`A source type called "${M}" already exists.`);((M,et)=>{za[M]=et})(M,Bt)})),M.clearPrewarmedResources=function(){const M=Ta;M&&(M.isPreloaded()&&1===M.numActive()?(M.release(Ia),Ta=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"))},M.createTileMesh=Ht,M.getMaxParallelImageRequests=function(){return et.a.MAX_PARALLEL_IMAGE_REQUESTS},M.getRTLTextPluginStatus=function(){return oe().getRTLTextPluginStatus()},M.getVersion=function(){return og},M.getWorkerCount=function(){return z.workerCount},M.getWorkerUrl=function(){return et.a.WORKER_URL},M.importScriptInWorkers=function(M){return j().broadcast("IS",M)},M.prewarm=function(){F().acquire(Ia)},M.setMaxParallelImageRequests=function(M){et.a.MAX_PARALLEL_IMAGE_REQUESTS=M},M.setRTLTextPlugin=function(M,et){return oe().setRTLTextPlugin(M,et)},M.setWorkerCount=function(M){z.workerCount=M},M.setWorkerUrl=function(M){et.a.WORKER_URL=M}}));var Bt=M;return Bt}()),Tl.exports}(),Wl=getDefaultExportFromCjs$1(Vl);function getDefaultExportFromCjs(M){return M.__esModule&&Object.prototype.hasOwnProperty.call(M,"default")?M.default:M}function getAugmentedNamespace(M){if(M.__esModule)return M;var et=M.default;if("function"==typeof et){var Bt=function a(){return this instanceof a?Reflect.construct(et,arguments,this.constructor):et.apply(this,arguments)};Bt.prototype=et.prototype}else Bt={};return Object.defineProperty(Bt,"__esModule",{value:!0}),Object.keys(M).forEach((function(et){var Wt=Object.getOwnPropertyDescriptor(M,et);Object.defineProperty(Bt,et,Wt.get?Wt:{enumerable:!0,get:function(){return M[et]}})})),Bt}function objectConverter(M){return new Function("d","return {"+M.map((function(M,et){return JSON.stringify(M)+": d["+et+"]"})).join(",")+"}")}function dsv$1(M){var et=new RegExp('["'+M+"\n]"),Bt=M.charCodeAt(0);function parseRows(M,et){var Wt,Nt,$t={},Gr={},mn=[],Hn=M.length,so=0,uo=0;function token(){if(so>=Hn)return Gr;if(Nt)return Nt=!1,$t;var et,Wt=so;if(34===M.charCodeAt(Wt)){for(var mn=Wt;mn++=0?0:1],Wt=Math.abs(M),Nt=Math.floor(Wt),$t=60*(Wt-Nt),Gr=Math.floor($t);return{whole:Nt,minutes:Gr,seconds:Math.floor(60*($t-Gr)),dir:Bt}}function search(M,et){if(et||(et="NSEW"),"string"!=typeof M)return null;var Bt=(M=M.toUpperCase()).match(/^[\s\,]*([NSEW])?\s*([\-|—|―]?[0-9.]+)[°º˚]?\s*(?:([0-9.]+)['’′‘]\s*)?(?:([0-9.]+)(?:''|"|”|″)\s*)?([NSEW])?/);if(!Bt)return null;var Wt,Nt=Bt[0];if(Bt[1]&&Bt[5]?(Wt=Bt[1],Nt=Nt.slice(0,-1)):Wt=Bt[1]||Bt[5],Wt&&-1===et.indexOf(Wt))return null;var $t=Bt[2]?parseFloat(Bt[2]):0,Gr=Bt[3]?parseFloat(Bt[3])/60:0,mn=Bt[4]?parseFloat(Bt[4])/3600:0,Hn=$t<0?-1:1;return"S"!==Wt&&"W"!==Wt||(Hn*=-1),{val:(Math.abs($t)+Gr+mn)*Hn,dim:Wt,matched:Nt,remain:M.slice(Nt.length)}}tc.exports=function element(M,et){var Bt=search(M,et);return null===Bt?null:Bt.val},tc.exports.pair=function pair(M,et){var Bt=search(M=M.trim(),et);if(!Bt)return null;var Wt=search(M=Bt.remain.trim(),et);if(!Wt||Wt.remain)return null;return Bt.dim?function swapdim(M,et,Bt){if("N"===Bt||"S"===Bt)return[M,et];if("W"===Bt||"E"===Bt)return[et,M]}(Bt.val,Wt.val,Bt.dim):[Bt.val,Wt.val]},tc.exports.format=format,tc.exports.formatPair=function formatPair(M){return format(M.lat,"lat")+" "+format(M.lon,"lon")},tc.exports.coordToDMS=coordToDMS;var ec=tc.exports,dc=$l,Ic=ec,fc=/(Lat)(itude)?/gi,yc=/(L)(on|ng)(gitude)?/i;function guessHeader(M,et){var Bt,Wt,Nt;for(var $t in M)(Wt=$t.match(et))&&(!Bt||Wt[0].length/$t.length>Nt)&&(Nt=Wt[0].length/$t.length,Bt=$t);return Bt}function guessLatHeader(M){return guessHeader(M,fc)}function guessLonHeader(M){return guessHeader(M,yc)}function keyCount(M){return"object"==typeof M?Object.keys(M).length:0}function autoDelimiter(M){var et=[];return[",",";","\t","|"].forEach((function(Bt){var Wt=dc.dsvFormat(Bt).parse(M);if(Wt.length>=1){for(var Nt=keyCount(Wt[0]),$t=0;$t{Bt[Wt]=M}));return Bt}function isElement(M){return 1===M?.nodeType}function getLineStyle(M){return get(M,"line",(M=>Object.assign({},val1(M,"color",(M=>({stroke:`#${M}`}))),$num(M,"opacity",(M=>({"stroke-opacity":M}))),$num(M,"width",(M=>({"stroke-width":96*M/25.4}))))))}function getExtensions(M){let et=[];if(null===M)return et;for(const Bt of Array.from(M.childNodes)){if(!isElement(Bt))continue;const M=abbreviateName(Bt.nodeName);if("gpxtpx:TrackPointExtension"===M)et=et.concat(getExtensions(Bt));else{const Wt=nodeVal(Bt);et.push([M,parseNumeric(Wt)])}}return et}function abbreviateName(M){return["heart","gpxtpx:hr","hr"].includes(M)?"heart":M}function parseNumeric(M){const et=parseFloat(M);return isNaN(et)?M:et}function coordPair$1(M){const et=[parseFloat(M.getAttribute("lon")||""),parseFloat(M.getAttribute("lat")||"")];if(isNaN(et[0])||isNaN(et[1]))return null;num1(M,"ele",(M=>{et.push(M)}));const Bt=get1(M,"time");return{coordinates:et,time:Bt?nodeVal(Bt):null,extendedValues:getExtensions(get1(M,"extensions"))}}function extractProperties(M){const et=getMulti(M,["name","cmt","desc","type","time","keywords"]),Bt=Array.from(M.getElementsByTagNameNS("http://www.garmin.com/xmlschemas/GpxExtensions/v3","*"));for(const Wt of Bt)Wt.parentNode?.parentNode===M&&(et[Wt.tagName.replace(":","_")]=nodeVal(Wt));const Wt=$(M,"link");return Wt.length&&(et.links=Wt.map((M=>Object.assign({href:M.getAttribute("href")},getMulti(M,["text","type"]))))),et}function getPoints$1(M,et){const Bt=$(M,et),Wt=[],Nt=[],$t={};for(let M=0;M1,Gr=Object.assign({_gpxType:"trk"},extractProperties(M),getLineStyle(get1(M,"extensions")),Wt.length?{coordinateProperties:{times:$t?Wt:Wt[0]}}:{});for(const M of Nt){Bt.push(M.line),Gr.coordinateProperties||(Gr.coordinateProperties={});const et=Gr.coordinateProperties,Wt=Object.entries(M.extendedValues);for(let M=0;Mnew Array(M.line.length).fill(null)))),et[Bt][M]=Gr):et[Bt]=Gr}}return{type:"Feature",properties:Gr,geometry:$t?{type:"MultiLineString",coordinates:Bt}:{type:"LineString",coordinates:Bt[0]}}}function getPoint(M){const et=Object.assign(extractProperties(M),getMulti(M,["sym"])),Bt=coordPair$1(M);return Bt?{type:"Feature",properties:et,geometry:{type:"Point",coordinates:Bt.coordinates}}:null}function*gpxGen(M){for(const et of $(M,"trk")){const M=getTrack(et);M&&(yield M)}for(const et of $(M,"rte")){const M=getRoute(et);M&&(yield M)}for(const et of $(M,"wpt")){const M=getPoint(et);M&&(yield M)}}const xc=[["heartRate","heartRates"],["Cadence","cadences"],["Speed","speeds"],["Watts","watts"]],Bc=[["TotalTimeSeconds","totalTimeSeconds"],["DistanceMeters","distanceMeters"],["MaximumSpeed","maxSpeed"],["AverageHeartRateBpm","avgHeartRate"],["MaximumHeartRateBpm","maxHeartRate"],["AvgSpeed","avgSpeed"],["AvgWatts","avgWatts"],["MaxWatts","maxWatts"]];function getProperties(M,et){const Bt=[];for(const[Wt,Nt]of et){let et=get1(M,Wt);if(!et){const Bt=M.getElementsByTagNameNS("http://www.garmin.com/xmlschemas/ActivityExtension/v2",Wt);Bt.length&&(et=Bt[0])}const $t=parseFloat(nodeVal(et));isNaN($t)||Bt.push([Nt,$t])}return Bt}function coordPair(M){const et=[num1(M,"LongitudeDegrees"),num1(M,"LatitudeDegrees")];if(void 0===et[0]||isNaN(et[0])||void 0===et[1]||isNaN(et[1]))return null;const Bt=get1(M,"HeartRateBpm"),Wt=nodeVal(get1(M,"Time"));return get1(M,"AltitudeMeters",(M=>{const Bt=parseFloat(nodeVal(M));isNaN(Bt)||et.push(Bt)})),{coordinates:et,time:Wt||null,heartRate:Bt?parseFloat(nodeVal(Bt)):null,extensions:getProperties(M,xc)}}function getPoints(M){const et=$(M,"Trackpoint"),Bt=[],Wt=[],Nt=[];if(et.length<2)return null;const $t={},Gr={extendedProperties:$t};for(let M=0;M({name:nodeVal(M)}))));for(const M of et)Gr=getPoints(M),Gr&&(Bt.push(Gr.line),Gr.times.length&&Wt.push(Gr.times),Gr.heartRates.length&&Nt.push(Gr.heartRates),$t.push(Gr.extendedProperties));for(let M=0;M<$t.length;M++){const Wt=$t[M];for(const Nt in Wt)1===et.length?Gr&&(mn[Nt]=Gr.extendedProperties[Nt]):(mn[Nt]||(mn[Nt]=Bt.map((M=>Array(M.length).fill(null)))),mn[Nt][M]=Wt[Nt])}return 0===Bt.length?null:((Wt.length||Nt.length)&&(mn.coordinateProperties=Object.assign(Wt.length?{times:1===Bt.length?Wt[0]:Wt}:{},Nt.length?{heart:1===Bt.length?Nt[0]:Nt}:{})),{type:"Feature",properties:mn,geometry:1===Bt.length?{type:"LineString",coordinates:Bt[0]}:{type:"MultiLineString",coordinates:Bt}})}function*tcxGen(M){for(const et of $(M,"Lap")){const M=getLap(et);M&&(yield M)}for(const et of $(M,"Courses")){const M=getLap(et);M&&(yield M)}}function fixColor(M,et){const Bt={},Wt="stroke"==et||"fill"===et?et:et+"-color";return"#"===M[0]&&(M=M.substring(1)),6===M.length||3===M.length?Bt[Wt]="#"+M:8===M.length&&(Bt[et+"-opacity"]=parseInt(M.substring(0,2),16)/255,Bt[Wt]="#"+M.substring(6,8)+M.substring(4,6)+M.substring(2,4)),Bt}function numericProperty(M,et,Bt){const Wt={};return num1(M,et,(M=>{Wt[Bt]=M})),Wt}function getColor(M,et){return get(M,"color",(M=>fixColor(nodeVal(M),et)))}function extractIconHref(M){return get(M,"Icon",((M,et)=>(val1(M,"href",(M=>{et.icon=M})),et)))}function extractStyle(M){return Object.assign({},function extractPoly(M){return get(M,"PolyStyle",((M,et)=>Object.assign(et,get(M,"color",(M=>fixColor(nodeVal(M),"fill"))),val1(M,"fill",(M=>{if("0"===M)return{"fill-opacity":0}})),val1(M,"outline",(M=>{if("0"===M)return{"stroke-opacity":0}})))))}(M),function extractLine(M){return get(M,"LineStyle",(M=>Object.assign(getColor(M,"stroke"),numericProperty(M,"width","stroke-width"))))}(M),function extractLabel(M){return get(M,"LabelStyle",(M=>Object.assign(getColor(M,"label"),numericProperty(M,"scale","label-scale"))))}(M),function extractIcon(M){return get(M,"IconStyle",(M=>Object.assign(getColor(M,"icon"),numericProperty(M,"scale","icon-scale"),numericProperty(M,"heading","icon-heading"),get(M,"hotSpot",(M=>{const et=parseFloat(M.getAttribute("x")||""),Bt=parseFloat(M.getAttribute("y")||""),Wt=M.getAttribute("xunits")||"",Nt=M.getAttribute("yunits")||"";return isNaN(et)||isNaN(Bt)?{}:{"icon-offset":[et,Bt],"icon-offset-units":[Wt,Nt]}})),extractIconHref(M))))}(M))}const toNumber=M=>Number(M),Tc={string:M=>M,int:toNumber,uint:toNumber,short:toNumber,ushort:toNumber,float:toNumber,double:toNumber,bool:M=>Boolean(M)};function extractExtendedData(M,et){return get(M,"ExtendedData",((M,Bt)=>{for(const et of $(M,"Data"))Bt[et.getAttribute("name")||""]=nodeVal(get1(et,"value"));for(const Wt of $(M,"SimpleData")){const M=Wt.getAttribute("name")||"",Nt=et[M]||Tc.string;Bt[M]=Nt(nodeVal(Wt))}return Bt}))}function getMaybeHTMLDescription(M){const et=get1(M,"description");for(const M of Array.from(et?.childNodes||[]))if(4===M.nodeType)return{description:{"@type":"html",value:nodeVal(M)}};return{}}function extractTimeSpan(M){return get(M,"TimeSpan",(M=>({timespan:{begin:nodeVal(get1(M,"begin")),end:nodeVal(get1(M,"end"))}})))}function extractTimeStamp(M){return get(M,"TimeStamp",(M=>({timestamp:nodeVal(get1(M,"when"))})))}function extractCascadedStyle(M,et){return val1(M,"styleUrl",(M=>(M=normalizeId(M),et[M]?Object.assign({styleUrl:M},et[M]):{styleUrl:M})))}const Mc=/\s*/g,Vc=/^\s*|\s*$/g,zc=/\s+/;function coord1(M){return M.replace(Mc,"").split(",").map(parseFloat).filter((M=>!isNaN(M))).slice(0,3)}function coord(M){return M.replace(Vc,"").split(zc).map(coord1).filter((M=>M.length>=2))}function gxCoords(M){let et=$(M,"coord");0===et.length&&(et=function $ns(M,et,Bt){return Array.from(M.getElementsByTagNameNS(Bt,et))}(M,"coord","*"));const Bt=et.map((M=>nodeVal(M).split(" ").map(parseFloat)));return 0===Bt.length?null:{geometry:Bt.length>2?{type:"LineString",coordinates:Bt}:{type:"Point",coordinates:Bt[0]},times:$(M,"when").map((M=>nodeVal(M)))}}function fixRing(M){if(0===M.length)return M;const et=M[0],Bt=M[M.length-1];let Wt=!0;for(let M=0;M=2&&et.push({type:"Point",coordinates:M});break}case"LinearRing":case"LineString":{const M=coord(getCoordinates(Nt));M.length>=2&&et.push({type:"LineString",coordinates:M});break}case"Polygon":{const M=[];for(const et of $(Nt,"LinearRing")){const Bt=fixRing(coord(getCoordinates(et)));Bt.length>=4&&M.push(Bt)}M.length&&et.push({type:"Polygon",coordinates:M});break}case"Track":case"gx:Track":{const M=gxCoords(Nt);if(!M)break;const{times:Wt,geometry:$t}=M;et.push($t),Wt.length&&Bt.push(Wt);break}}}return{geometries:et,coordTimes:Bt}}function getPlacemark(M,et,Bt,Wt){const{coordTimes:Nt,geometries:$t}=getGeometry(M),Gr=function geometryListToGeometry(M){return 0===M.length?null:1===M.length?M[0]:{type:"GeometryCollection",geometries:M}}($t);if(!Gr&&Wt.skipNullGeometry)return null;const mn={type:"Feature",geometry:Gr,properties:Object.assign(getMulti(M,["name","address","visibility","open","phoneNumber","description"]),getMaybeHTMLDescription(M),extractCascadedStyle(M,et),extractStyle(M),extractExtendedData(M,Bt),extractTimeSpan(M),extractTimeStamp(M),Nt.length?{coordinateProperties:{times:1===Nt.length?Nt[0]:Nt}}:{})};void 0!==mn.properties?.visibility&&(mn.properties.visibility="0"!==mn.properties.visibility);const Hn=M.getAttribute("id");return null!==Hn&&""!==Hn&&(mn.id=Hn),mn}function getGroundOverlayBox(M){if(get1(M,"gx:LatLonQuad")){return{geometry:{type:"Polygon",coordinates:[fixRing(coord(getCoordinates(M)))]}}}return function getLatLonBox(M){const et=get1(M,"LatLonBox");if(et){const M=num1(et,"north"),Bt=num1(et,"west"),Wt=num1(et,"east"),Nt=num1(et,"south"),$t=num1(et,"rotation");if("number"==typeof M&&"number"==typeof Nt&&"number"==typeof Bt&&"number"==typeof Wt){const et=[Bt,Nt,Wt,M];let Gr=[[[Bt,M],[Wt,M],[Wt,Nt],[Bt,Nt],[Bt,M]]];return"number"==typeof $t&&(Gr=function rotateBox(M,et,Bt){const Wt=[(M[0]+M[2])/2,(M[1]+M[3])/2];return[et[0].map((M=>{const et=M[1]-Wt[1],Nt=M[0]-Wt[0],$t=Math.sqrt(Math.pow(et,2)+Math.pow(Nt,2)),Gr=Math.atan2(et,Nt)+Bt*Fc;return[Wt[0]+Math.cos(Gr)*$t,Wt[1]+Math.sin(Gr)*$t]}))]}(et,Gr,$t)),{bbox:et,geometry:{type:"Polygon",coordinates:Gr}}}}return null}(M)}const Fc=Math.PI/180;function getGroundOverlay(M,et,Bt,Wt){const Nt=getGroundOverlayBox(M),$t=Nt?.geometry||null;if(!$t&&Wt.skipNullGeometry)return null;const Gr={type:"Feature",geometry:$t,properties:Object.assign({"@geometry-type":"groundoverlay"},getMulti(M,["name","address","visibility","open","phoneNumber","description"]),getMaybeHTMLDescription(M),extractCascadedStyle(M,et),extractStyle(M),extractIconHref(M),extractExtendedData(M,Bt),extractTimeSpan(M),extractTimeStamp(M))};Nt?.bbox&&(Gr.bbox=Nt.bbox),void 0!==Gr.properties?.visibility&&(Gr.properties.visibility="0"!==Gr.properties.visibility);const mn=M.getAttribute("id");return null!==mn&&""!==mn&&(Gr.id=mn),Gr}function getStyleId(M){let et=M.getAttribute("id");const Bt=M.parentNode;return!et&&isElement(Bt)&&"CascadingStyle"===Bt.localName&&(et=Bt.getAttribute("kml:id")||Bt.getAttribute("id")),normalizeId(et||"")}function buildStyleMap(M){const et={};for(const Bt of $(M,"Style"))et[getStyleId(Bt)]=extractStyle(Bt);for(const Bt of $(M,"StyleMap")){const M=normalizeId(Bt.getAttribute("id")||"");val1(Bt,"styleUrl",(Bt=>{Bt=normalizeId(Bt),et[Bt]&&(et[M]=et[Bt])}))}return et}function buildSchema(M){const et={};for(const Bt of $(M,"SimpleField"))et[Bt.getAttribute("name")||""]=Tc[Bt.getAttribute("type")||""]||Tc.string;return et}const Oc=["name","visibility","open","address","description","phoneNumber","visibility"];function*kmlGen(M,et={skipNullGeometry:!1}){const Bt=buildStyleMap(M),Wt=buildSchema(M);for(const Nt of $(M,"Placemark")){const M=getPlacemark(Nt,Bt,Wt,et);M&&(yield M)}for(const Nt of $(M,"GroundOverlay")){const M=getGroundOverlay(Nt,Bt,Wt,et);M&&(yield M)}}var jc=Object.freeze({__proto__:null,gpx:function gpx(M){return{type:"FeatureCollection",features:Array.from(gpxGen(M))}},gpxGen:gpxGen,kml:function kml(M,et={skipNullGeometry:!1}){return{type:"FeatureCollection",features:Array.from(kmlGen(M,et))}},kmlGen:kmlGen,kmlWithFolders:function kmlWithFolders(M,et={skipNullGeometry:!1}){const Bt=buildStyleMap(M),Wt=buildSchema(M),Nt={type:"root",children:[]};return function traverse(M,et,Nt){if(isElement(M))switch(M.tagName){case"GroundOverlay":{const $t=getGroundOverlay(M,Bt,Wt,Nt);$t&&et.children.push($t);break}case"Placemark":{const $t=getPlacemark(M,Bt,Wt,Nt);$t&&et.children.push($t);break}case"Folder":{const Bt=function getFolder(M){const et={};for(const Bt of Array.from(M.childNodes))isElement(Bt)&&Oc.includes(Bt.tagName)&&(et[Bt.tagName]=nodeVal(Bt));return{type:"folder",meta:et,children:[]}}(M);et.children.push(Bt),et=Bt;break}}if(M.childNodes)for(let Bt=0;Bt=0?1:-1)}function encode(M,et,Bt){var Wt=2*((M=py2_round(M*Bt))-(et=py2_round(et*Bt)));Wt<0&&(Wt=-Wt-1);for(var Nt="";Wt>=32;)Nt+=String.fromCharCode(63+(32|31&Wt)),Wt/=32;return Nt+=String.fromCharCode(63+(0|Wt))}function flipped(M){for(var et=[],Bt=0;Bt=32);Bt=1&Hn?(-Hn-1)/2:Hn/2,mn=1,Hn=0;do{Hn+=(31&(so=M.charCodeAt(Wt++)-63))*mn,mn*=32}while(so>=32);Nt+=Bt,$t+=1&Hn?(-Hn-1)/2:Hn/2,Gr.push([Nt/uo,$t/uo])}return Gr},et.encode=function(M,et){if(!M.length)return"";for(var Bt=Math.pow(10,Number.isInteger(et)?et:5),Wt=encode(M[0][0],0,Bt)+encode(M[0][1],0,Bt),Nt=1;Nt{const first=M=>M[0],last=M=>M[M.length-1],coordsToKey=M=>M.join(","),addToMap=(M,et,Bt)=>{let Wt=M[et];Wt?Wt.push(Bt):M[et]=[Bt]},removeFromMap=(M,et,Bt)=>{let Wt=M[et],Nt=null;Wt&&(Nt=Wt.indexOf(Bt))>=0&&Wt.splice(Nt,1)},getFirstFromMap=(M,et)=>{let Bt=M[et];return Bt&&Bt.length>0?Bt[0]:null},isRing=M=>M.length>3&&coordsToKey(first(M))===coordsToKey(last(M)),ringDirection=(M,et,Bt)=>{et=et||0,Bt=Bt||1;let Wt=M.reduce(((Bt,Wt,Nt)=>M[Bt][et]>Wt[et]?Bt:Nt),0),Nt=Wt<=0?M.length-2:Wt-1,$t=Wt>=M.length-1?1:Wt+1,Gr=M[Nt][et],mn=M[Wt][et],Hn=M[$t][et],so=M[Nt][Bt],uo=M[Wt][Bt];return(mn-Gr)*(M[$t][Bt]-so)-(Hn-Gr)*(uo-so)<0?"clockwise":"counterclockwise"},strToFloat=M=>M instanceof Array?M.map(strToFloat):parseFloat(M);class RefElements extends Map{constructor(){super(),this.binders=[]}add(M,et){this.has(M)||this.set(M,et)}addBinder(M){this.binders.push(M)}bindAll(){this.binders.forEach((M=>M.bind()))}}return{purgeProps:(M,et)=>{if(M){let Bt=Object.assign({},M);if(et)for(let M of et)delete Bt[M];return Bt}return{}},mergeProps:(M,et)=>(M=M||{},et=et||{},Object.assign(M,et)),first:first,last:last,coordsToKey:coordsToKey,addToMap:addToMap,removeFromMap:removeFromMap,getFirstFromMap:getFirstFromMap,isRing:isRing,ringDirection:ringDirection,ptInsidePolygon:(M,et,Bt,Wt)=>{Bt=Bt||0,Wt=Wt||1;let Nt=!1;for(let $t=0,Gr=et.length-1;$t=0){let Bt=[et,1];M&&Bt.push(M),[].splice.apply(this.container,Bt)}}else if("object"==typeof this.container){let et=Object.keys(this.container).find((M=>this.container[M]===this));et&&(M?this.container[et]=M:delete this.container[et])}}},WayCollection:class WayCollection extends Array{constructor(){super(),this.firstMap={},this.lastMap={}}addWay(M){(M=M.toCoordsArray()).length>0&&(this.push(M),addToMap(this.firstMap,coordsToKey(first(M)),M),addToMap(this.lastMap,coordsToKey(last(M)),M))}toStrings(){let M=[],et=null;for(;et=this.shift();){removeFromMap(this.firstMap,coordsToKey(first(et)),et),removeFromMap(this.lastMap,coordsToKey(last(et)),et);let Bt=et,Wt=null;do{let M=coordsToKey(last(Bt)),et=!1;Wt=getFirstFromMap(this.firstMap,M),Wt||(Wt=getFirstFromMap(this.lastMap,M),et=!0),Wt&&(this.splice(this.indexOf(Wt),1),removeFromMap(this.firstMap,coordsToKey(first(Wt)),Wt),removeFromMap(this.lastMap,coordsToKey(last(Wt)),Wt),et&&(Wt.length>Bt.length&&([Bt,Wt]=[Wt,Bt]),Wt.reverse()),Bt=Bt.concat(Wt.slice(1)))}while(Wt);M.push(strToFloat(Bt))}return M}toRings(M){let et=this.toStrings(),Bt=[],Wt=null;for(;Wt=et.shift();)isRing(Wt)&&(ringDirection(Wt)!==M&&Wt.reverse(),Bt.push(Wt));return Bt}}}})(),Gh={building:{},highway:{whitelist:["services","rest_area","escape","elevator"]},natural:{blacklist:["coastline","cliff","ridge","arete","tree_row"]},landuse:{},waterway:{whitelist:["riverbank","dock","boatyard","dam"]},amenity:{},leisure:{},barrier:{whitelist:["city_wall","ditch","hedge","retaining_wall","wall","spikes"]},railway:{whitelist:["station","turntable","roundhouse","platform"]},area:{},boundary:{},man_made:{blacklist:["cutline","embankment","pipeline"]},power:{whitelist:["plant","substation","generator","transformer"]},place:{},shop:{},aeroway:{blacklist:["taxiway"]},tourism:{},historic:{},public_transport:{},office:{},"building:part":{},military:{},ruins:{},"area:highway":{},craft:{},golf:{},indoor:{}},Ph=(()=>{const{first:M,last:et,coordsToKey:Bt,addToMap:Wt,removeFromMap:Nt,getFirstFromMap:$t,isRing:Gr,ringDirection:mn,ptInsidePolygon:Hn,strToFloat:so,LateBinder:uo,WayCollection:Io}=Zh,Po=Gh;class OsmObject{constructor(M,et,Bt){this.type=M,this.id=et,this.refElems=Bt,this.tags={},this.props={id:this.getCompositeId()},this.refCount=0,this.hasTag=!1,Bt&&Bt.add(this.getCompositeId(),this)}addTags(M){this.tags=Object.assign(this.tags,M),this.hasTag=!!M}addTag(M,et){this.tags[M]=et,this.hasTag=!!M}addProp(M,et){this.props[M]=et}addProps(M){this.props=Object.assign(this.props,M)}getCompositeId(){return`${this.type}/${this.id}`}getProps(){return Object.assign(this.props,this.tags)}toFeatureArray(){return[]}}class Node extends OsmObject{constructor(M,et){super("node",M,et),this.latLng=null}setLatLng(M){this.latLng=M}toFeatureArray(){return this.latLng?[{type:"Feature",id:this.getCompositeId(),properties:this.getProps(),geometry:{type:"Point",coordinates:so([this.latLng.lon,this.latLng.lat])}}]:[]}getLatLng(){return this.latLng}}class Way extends OsmObject{constructor(M,et){super("way",M,et),this.latLngArray=[],this.isPolygon=!1}addLatLng(M){this.latLngArray.push(M)}setLatLngArray(M){this.latLngArray=M}addNodeRef(M){let et=new uo(this.latLngArray,(function(M){let et=this.refElems.get(`node/${M}`);if(et)return et.refCount++,et.getLatLng()}),this,[M]);this.latLngArray.push(et),this.refElems.addBinder(et)}analyzeGeometryType(M,et){let Bt=Po[M];Bt&&(this.isPolygon=!0,Bt.whitelist?this.isPolygon=Bt.whitelist.indexOf(et)>=0:Bt.blacklist&&(this.isPolygon=!(Bt.blacklist.indexOf(et)>=0)))}addTags(M){super.addTags(M);for(let[et,Bt]of Object.entries(M))this.analyzeGeometryType(et,Bt)}addTag(M,et){super.addTag(M,et),this.analyzeGeometryType(M,et)}toCoordsArray(){return this.latLngArray.map((M=>[M.lon,M.lat]))}toFeatureArray(){let M=this.toCoordsArray();if(M.length>1){M=so(M);let et={type:"Feature",id:this.getCompositeId(),properties:this.getProps(),geometry:{type:"LineString",coordinates:M}};return this.isPolygon&&Gr(M)?("counterclockwise"!==mn(M)&&M.reverse(),et.geometry={type:"Polygon",coordinates:[M]},[et]):[et]}return[]}}return{Node:Node,Way:Way,Relation:class Relation extends OsmObject{constructor(M,et){super("relation",M,et),this.relations=[],this.nodes=[],this.bounds=null}setBounds(M){this.bounds=M}addMember(M){switch(M.type){case"relation":let et=new uo(this.relations,(function(M){let et=this.refElems.get(`relation/${M}`);if(et)return et.refCount++,et}),this,[M.ref]);this.relations.push(et),this.refElems.addBinder(et);break;case"way":M.role||(M.role="");let Bt=this[M.role];if(Bt||(Bt=this[M.role]=[]),M.geometry){let et=new Way(M.ref,this.refElems);et.setLatLngArray(M.geometry),et.refCount++,Bt.push(et)}else if(M.nodes){let et=new Way(M.ref,this.refElems);for(let Bt of M.nodes)et.addNodeRef(Bt);et.refCount++,Bt.push(et)}else{let et=new uo(Bt,(function(M){let et=this.refElems.get(`way/${M}`);if(et)return et.refCount++,et}),this,[M.ref]);Bt.push(et),this.refElems.addBinder(et)}break;case"node":let Wt=null;if(M.lat&&M.lon){Wt=new Node(M.ref,this.refElems),Wt.setLatLng({lon:M.lon,lat:M.lat}),M.tags&&Wt.addTags(M.tags);for(let[et,Bt]of Object.entries(M))["id","type","lat","lon"].indexOf(et)<0&&Wt.addProp(et,Bt);Wt.refCount++,this.nodes.push(Wt)}else{let et=new uo(this.nodes,(function(M){let et=this.refElems.get(`node/${M}`);if(et)return et.refCount++,et}),this,[M.ref]);this.nodes.push(et),this.refElems.addBinder(et)}}}toFeatureArray(){let et=[],Bt=[],Wt=[];const Nt=["outer","inner",""];for(let M of this.relations)if(M)for(let et of Nt){let Bt=M[et];if(Bt){let M=this[et];M?[].splice.apply(M,[M.length,0].concat(Bt)):this[et]=Bt}}for(let M of Nt){let et=this[M];if(et){this[M]=new Io;for(let Bt of et)this[M].addWay(Bt)}}let $t=null,Gr={type:"Feature",id:this.getCompositeId(),bbox:this.bounds,properties:this.getProps()};this.bounds||delete Gr.bbox,this.outer?($t=((et,Bt)=>{let Wt=et?et.toRings("counterclockwise"):[],Nt=Bt?Bt.toRings("clockwise"):[];if(Wt.length>0){let et=[],Bt=null;for(Bt of Wt)et.push([Bt]);for(;Bt=Nt.shift();)for(let Nt in Wt)if(Hn(M(Bt),Wt[Nt])){et[Nt].push(Bt);break}return 1===et.length?{type:"Polygon",coordinates:et[0]}:{type:"MultiPolygon",coordinates:et}}return null})(this.outer,this.inner),$t&&(Gr.geometry=$t,et.push(Gr))):this[""]&&($t=(M=>{let et=M?M.toStrings():[];return et.length>0?1===et.length?{type:"LineString",coordinates:et[0]}:{type:"MultiLineString",coordinates:et}:null})(this[""]),$t&&(Gr.geometry=$t,Bt.push(Gr)));for(let M of this.nodes)Wt=Wt.concat(M.toFeatureArray());return et.concat(Bt).concat(Wt)}}}})(),Wh=(()=>{function conditioned(M){return null!=M.match(/^(.+?)\[(.+?)\]>$/g)}function parseEvent(M){let et=/^(.+?)\[(.+?)\]>$/g.exec(M);return et?{evt:et[1]+">",exp:et[2]}:{evt:M}}return class{constructor(M){M&&(this.queryParent=!!M.queryParent,this.progressive=M.progressive,this.queryParent&&(this.parentMap=new WeakMap)),this.evtListeners={}}parse(M,et,Bt){Bt=Bt?Bt+".":"";let Wt=/<([^ >\/]+)(.*?)>/gm,Nt=null,$t=[];for(;Nt=Wt.exec(M);){let Gr=Nt[1],mn={$tag:Gr},Hn=Bt+Gr,so=Nt[2].trim(),uo=!1;(so.endsWith("/")||Gr.startsWith("?")||Gr.startsWith("!"))&&(uo=!0);let Io=/([^ ]+?)="(.+?)"/g,Po=/([^ ]+?)='(.+?)'/g,To=null,Eo=!1;for(;To=Io.exec(so);)Eo=!0,mn[To[1]]=To[2];if(!Eo)for(;To=Po.exec(so);)Eo=!0,mn[To[1]]=To[2];if(Eo||""===so||(mn.text=so),this.progressive&&this.emit(`<${Hn}>`,mn,et),!uo){let et=new RegExp(`([^]+?)`,"g");et.lastIndex=Wt.lastIndex;let Bt=et.exec(M);if(Bt&&Bt[1]){Wt.lastIndex=et.lastIndex;let M=this.parse(Bt[1],mn,Hn);M.length>0?mn.$innerNodes=M:mn.$innerText=Bt[1]}}this.queryParent&&et&&this.parentMap.set(mn,et),this.progressive&&this.emit(``,mn,et),$t.push(mn)}return $t}getParent(M){return this.queryParent?this.parentMap.get(M):null}#t(M,et){let Bt=this.evtListeners[M];Bt?Bt.push(et):this.evtListeners[M]=[et]}addListener(M,et){conditioned(M)&&(M=parseEvent(M),et.condition=function genConditionFunc(M){let et="return "+M.replace(/(\$.+?)(?=[=!.])/g,"node.$&")+";";return new Function("node",et)}(M.exp),M=M.evt),this.#t(M,et)}#e(M,et){let Bt=this.evtListeners[M],Wt=null;Bt&&(Wt=Bt.indexOf(et))>=0&&Bt.splice(Wt,1)}removeListener(M,et){conditioned(M)&&(M=(M=parseEvent(M)).evt),this.#e(M,et)}emit(M,...et){let Bt=this.evtListeners[M];if(Bt)for(let M of Bt)M.condition?!0===M.condition.apply(null,et)&&M.apply(null,et):M.apply(null,et)}on(M,et){this.addListener(M,et)}off(M,et){this.removeListener(M,et)}}})();const{Node:zh,Way:Jh,Relation:Xh}=Ph,{purgeProps:Lh,RefElements:Hh}=Zh,Kh=Wh;var lib=(M,et)=>{let Bt=!1,Wt=!1,Nt=!0;(M=>{if(M){Bt=!(!M.completeFeature&&!M.allFeatures),Wt=!!M.renderTagged;let et=M.suppressWay||M.excludeWay;void 0===et||et||(Nt=!1)}})(et);let $t=(M=>M.elements?"json":M.indexOf("=0?"xml":M.trim().startsWith("{")?"json-raw":"invalid")(M),Gr=new Hh,mn=[];"json-raw"===$t&&($t=(M=JSON.parse(M)).elements?"json":"invalid"),"json"===$t?(M=>{for(let et of M.elements)switch(et.type){case"node":let M=new zh(et.id,Gr);et.tags&&M.addTags(et.tags),M.addProps(Lh(et,["id","type","tags","lat","lon"])),M.setLatLng(et);break;case"way":let Bt=new Jh(et.id,Gr);if(et.tags&&Bt.addTags(et.tags),Bt.addProps(Lh(et,["id","type","tags","nodes","geometry"])),et.nodes)for(let M of et.nodes)Bt.addNodeRef(M);else et.geometry&&Bt.setLatLngArray(et.geometry);break;case"relation":let Wt=new Xh(et.id,Gr);if(et.bounds&&Wt.setBounds([parseFloat(et.bounds.minlon),parseFloat(et.bounds.minlat),parseFloat(et.bounds.maxlon),parseFloat(et.bounds.maxlat)]),et.tags&&Wt.addTags(et.tags),Wt.addProps(Lh(et,["id","type","tags","bounds","members"])),et.members)for(let M of et.members)Wt.addMember(M)}})(M):"xml"===$t&&(M=>{const et=new Kh({progressive:!0});et.on("",(M=>{let et=new zh(M.id,Gr);for(let[Bt,Wt]of Object.entries(M))!Bt.startsWith("$")&&["id","lon","lat"].indexOf(Bt)<0&&et.addProp(Bt,Wt);if(et.setLatLng(M),M.$innerNodes)for(let Bt of M.$innerNodes)"tag"===Bt.$tag&&et.addTag(Bt.k,Bt.v)})),et.on("",(M=>{let et=new Jh(M.id,Gr);for(let[Bt,Wt]of Object.entries(M))!Bt.startsWith("$")&&["id"].indexOf(Bt)<0&&et.addProp(Bt,Wt);if(M.$innerNodes)for(let Bt of M.$innerNodes)"nd"===Bt.$tag?Bt.lon&&Bt.lat?et.addLatLng(Bt):Bt.ref&&et.addNodeRef(Bt.ref):"tag"===Bt.$tag&&et.addTag(Bt.k,Bt.v)})),et.on("",(M=>{new Xh(M.id,Gr)})),et.on("",((M,et)=>{let Bt=Gr.get(`relation/${et.id}`),Wt={type:M.type,role:M.role?M.role:"",ref:M.ref};if(M.lat&&M.lon){Wt.lat=M.lat,Wt.lon=M.lon,Wt.tags={};for(let[et,Bt]of Object.entries(M))!et.startsWith("$")&&["type","lat","lon"].indexOf(et)<0&&(Wt[et]=Bt)}if(M.$innerNodes){let et=[],Bt=[];for(let Wt of M.$innerNodes)Wt.lat&&Wt.lon?et.push(Wt):Bt.push(Wt.ref);et.length>0?Wt.geometry=et:Bt.length>0&&(Wt.nodes=Bt)}Bt.addMember(Wt)})),et.on("",((M,et)=>{Gr.get(`relation/${et.id}`).setBounds([parseFloat(M.minlon),parseFloat(M.minlat),parseFloat(M.maxlon),parseFloat(M.maxlat)])})),et.on("",((M,et)=>{Gr.get(`relation/${et.id}`).addTag(M.k,M.v)})),et.parse(M)})(M),Gr.bindAll();for(let M of Gr.values())if(M.refCount<=0||M.hasTag&&Wt&&!(M instanceof Jh&&Nt)){let et=M.toFeatureArray();if(M instanceof Xh&&!Bt&&et.length>0)return et[0].geometry;mn=mn.concat(et)}return{type:"FeatureCollection",features:mn}},Yh=getDefaultExportFromCjs(lib);const Qh=["topojson","osm","kml","gpx","tcx","csv","tsv","polyline"];class Converter{constructor(M,et,Bt={}){this.blankGeoJSON=()=>({type:"FeatureCollection",features:[]}),this._rawData=et,this._format=M,this._options=Bt;const Wt={topojson:this.loadTopoJson,osm:this.loadOsm,kml:this.loadXml,gpx:this.loadXml,tcx:this.loadXml,csv:this.loadCsv,tsv:this.loadCsv,polyline:this.loadPolyline};this._conversionFn=Wt[M]}async convert(){return this._conversionFn?this._conversionFn():new Promise(((M,et)=>et(`No converter exists for ${this._format}`)))}async loadXml(){return jc[this._format]((new DOMParser).parseFromString(this._rawData,"text/xml"))}async loadCsv(){let M=this._options.csvOptions||{};"tsv"===this._format&&(M.delimiter="\t");return await new Promise(((et,Bt)=>{vc.csv2geojson(this._rawData,M,((M,Wt)=>{M?Bt(M):et(Wt)}))}))}async loadTopoJson(){let M={};try{M=JSON.parse(this._rawData)}catch(M){throw"Invalid TopoJson"}let et=this.blankGeoJSON();return"Topology"===M.type&&void 0!==M.objects&&(et={type:"FeatureCollection",features:et.features=Object.keys(M.objects).map((et=>function topojsonFeature(M,et){return"string"==typeof et&&(et=M.objects[et]),"GeometryCollection"===et.type?{type:"FeatureCollection",features:et.geometries.map((function(et){return feature(M,et)}))}:feature(M,et)}(M,et))).reduce(((M,et)=>[...M,...et.features]),[])}),et}async loadOsm(){return Yh(this._rawData)}async loadPolyline(){let M=this._options.polylineOptions||{};return await new Promise(((et,Bt)=>{try{const Bt=Ih.toGeoJSON(this._rawData,M.precision);let Wt=Bt;"point"===M.type?1===Bt.coordinates.length?Wt={type:"Point",coordinates:Bt.coordinates[0]}:console.warn("Cannot convert polyline to "+M.type):"polygon"===M.type&&(Bt.coordinates[0][0]===Bt.coordinates[Bt.coordinates.length-1][0]&&Bt.coordinates[0][1]===Bt.coordinates[Bt.coordinates.length-1][1]?Wt={type:"Polygon",coordinates:[Bt.coordinates]}:console.warn("Cannot convert polyline to "+M.type)),et({type:"FeatureCollection",features:[{type:"Feature",geometry:Wt,properties:M.properties||{}}]})}catch(M){Bt(M)}}))}}var qh=null;try{var tg="undefined"!=typeof module&&"function"==typeof module.require&&module.require("worker_threads")||"function"==typeof __non_webpack_require__&&__non_webpack_require__("worker_threads")||"function"==typeof require&&require("worker_threads");qh=tg.Worker}catch(e){}function createBase64WorkerFactory$2(M,et,Bt){var Wt=function decodeBase64$1(M,et){return Buffer.from(M,"base64").toString("utf8")}(M),Nt=Wt.indexOf("\n",10)+1,$t=Wt.substring(Nt)+"";return function WorkerFactory(M){return new qh($t,Object.assign({},M,{eval:!0}))}}function createURL(M,et,Bt){var Wt=function decodeBase64(M,et){return atob(M)}(M),Nt=Wt.indexOf("\n",10)+1,$t=Wt.substring(Nt)+"",Gr=new Blob([$t],{type:"application/javascript"});return URL.createObjectURL(Gr)}var eg="[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0);var ig=function createBase64WorkerFactory(M,et,Bt){return function isNodeJS(){return eg}()?createBase64WorkerFactory$2(M):function createBase64WorkerFactory$1(M,et,Bt){var Wt;return function WorkerFactory(et){return Wt=Wt||createURL(M),new Worker(Wt,et)}}(M)}("Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24gKCkgewoJJ3VzZSBzdHJpY3QnOwoKCWZ1bmN0aW9uIGdldERlZmF1bHRFeHBvcnRGcm9tQ2pzICh4KSB7CgkJcmV0dXJuIHggJiYgeC5fX2VzTW9kdWxlICYmIE9iamVjdC5wcm90b3R5cGUuaGFzT3duUHJvcGVydHkuY2FsbCh4LCAnZGVmYXVsdCcpID8geFsnZGVmYXVsdCddIDogeDsKCX0KCglmdW5jdGlvbiBnZXRBdWdtZW50ZWROYW1lc3BhY2UobikgewoJICBpZiAobi5fX2VzTW9kdWxlKSByZXR1cm4gbjsKCSAgdmFyIGYgPSBuLmRlZmF1bHQ7CgkJaWYgKHR5cGVvZiBmID09ICJmdW5jdGlvbiIpIHsKCQkJdmFyIGEgPSBmdW5jdGlvbiBhICgpIHsKCQkJCWlmICh0aGlzIGluc3RhbmNlb2YgYSkgewoJICAgICAgICByZXR1cm4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JICAgICAgICAgIGlmICh0ZXh0LmNoYXJDb2RlQXQoaSArIDIpID09PSAxMCkgKytJOwoJICAgICAgICB9IGVsc2UgaWYgKGMgPT09IDEwKSB7CgkgICAgICAgICAgZW9sID0gdHJ1ZTsKCSAgICAgICAgfQoJICAgICAgICByZXR1cm4gdGV4dC5zbGljZShqICsgMSwgaSkucmVwbGFjZSgvIiIvZywgIlwiIik7CgkgICAgICB9CgoJICAgICAgLy8gY29tbW9uIGNhc2U6IGZpbmQgbmV4dCBkZWxpbWl0ZXIgb3IgbmV3bGluZQoJICAgICAgd2hpbGUgKEkgPCBOKSB7CgkgICAgICAgIHZhciBrID0gMTsKCSAgICAgICAgYyA9IHRleHQuY2hhckNvZGVBdChJKyspOwoJICAgICAgICBpZiAoYyA9PT0gMTApIGVvbCA9IHRydWU7IC8vIFxuCgkgICAgICAgIGVsc2UgaWYgKGMgPT09IDEzKSB7IGVvbCA9IHRydWU7IGlmICh0ZXh0LmNoYXJDb2RlQXQoSSkgPT09IDEwKSArK0ksICsrazsgfSAvLyBccnxcclxuCgkgICAgICAgIGVsc2UgaWYgKGMgIT09IGRlbGltaXRlckNvZGUpIGNvbnRpbnVlOwoJICAgICAgICByZXR1cm4gdGV4dC5zbGljZShqLCBJIC0gayk7CgkgICAgICB9CgoJICAgICAgLy8gc3BlY2lhbCBjYXNlOiBsYXN0IHRva2VuIGJlZm9yZSBFT0YKCSAgICAgIHJldHVybiB0ZXh0LnNsaWNlKGopOwoJICAgIH0KCgkgICAgd2hpbGUgKCh0ID0gdG9rZW4oKSkgIT09IEVPRikgewoJICAgICAgdmFyIGEgPSBbXTsKCSAgICAgIHdoaWxlICh0ICE9PSBFT0wgJiYgdCAhPT0gRU9GKSB7CgkgICAgICAgIGEucHVzaCh0KTsKCSAgICAgICAgdCA9IHRva2VuKCk7CgkgICAgICB9CgkgICAgICBpZiAoZiAmJiAoYSA9IGYoYSwgbisrKSkgPT0gbnVsbCkgY29udGludWU7CgkgICAgICByb3dzLnB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IGlmIChudW1lcmljRmllbGRzLmluY2x1ZGVzKGtleSkpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGRba2V5XSA9ICtkW2tleV07CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgICAgICByZXR1cm4gZDsKCSAgICAgICAgfSkgOiB4OwoKCSAgICBpZiAoIXBhcnNlZC5sZW5ndGgpIHsKCSAgICAgICAgY2FsbGJhY2sobnVsbCwgZmVhdHVyZWNvbGxlY3Rpb24pOwoJICAgICAgICByZXR1cm47CgkgICAgfQoKCSAgICB2YXIgZXJyb3JzID0gW107CgkgICAgdmFyIGk7CgoKCSAgICBpZiAoIWxhdGZpZWxkKSBsYXRmaWVsZCA9IGd1ZXNzTGF0SGVhZGVyKHBhcnNlZFswXSk7CgkgICAgaWYgKCFsb25maWVsZCkgbG9uZmllbGQgPSBndWVzc0xvbkhlYWRlcihwYXJzZWRbMF0pOwoJICAgIHZhciBub0dlb21ldHJ5ID0gKCFsYXRmaWVsZCB8fCAhbG9uZmllbGQpOwoKCSAgICBpZiAobm9HZW9tZXRyeSkgewoJICAgICAgICBmb3IgKGkgPSAwOyBpIDwgcGFyc2VkLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgICAgICBmZWF0dXJlcy5wdXNoKHsKCSAgICAgICAgICAgICAgICB0eXBlOiAnRmVhdHVyZScsCgkgICAgICAgICAgICAgICAgcHJvcGVydGllczogcGFyc2VkW2ldLAoJICAgICAgICAgICAgICAgIGdlb21ldHJ5OiBudWxsCgkgICAgICAgICAgICB9KTsKCSAgICAgICAgfQoJICAgICAgICBjYWxsYmFjayhlcnJvcnMubGVuZ3RoID8gZXJyb3JzIDogbnVsbCwgZmVhdHVyZWNvbGxlY3Rpb24pOwoJICAgICAgICByZXR1cm47CgkgICAgfQoKCSAgICBmb3IgKGkgPSAwOyBpIDwgcGFyc2VkLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgIGlmIChwYXJzZWRbaV1bbG9uZmllbGRdICE9PSB1bmRlZmluZWQgJiYKCSAgICAgICAgICAgIHBhcnNlZFtpXVtsYXRmaWVsZF0gIT09IHVuZGVmaW5lZCkgewoKCSAgICAgICAgICAgIHZhciBsb25rID0gcGFyc2VkW2ldW2xvbmZpZWxkXSwKCSAgICAgICAgICAgICAgICBsYXRrID0gcGFyc2VkW2ldW2xhdGZpZWxkXSwKCSAgICAgICAgICAgICAgICBsb25mLCBsYXRmLAoJICAgICAgICAgICAgICAgIGE7CgoJICAgICAgICAgICAgYSA9IHNleGFnZXNpbWFsKGxvbmssICdFVycpOwoJICAgICAgICAgICAgaWYgKGEpIGxvbmsgPSBhOwoJICAgICAgICAgICAgYSA9IHNleGFnZXNpbWFsKGxhdGssICdOUycpOwoJICAgICAgICAgICAgaWYgKGEpIGxhdGsgPSBhOwoKCSAgICAgICAgICAgIGxvbmYgPSBwYXJzZUZsb2F0KGxvbmspOwoJICAgICAgICAgICAgbGF0ZiA9IHBhcnNlRmxvYXQobGF0ayk7CgoJICAgICAgICAgICAgaWYgKGlzTmFOKGxvbmYpIHx8CgkgICAgICAgICAgICAgICAgaXNOYU4obGF0ZikpIHsKCSAgICAgICAgICAgICAgICBlcnJvcnMucHVzaCh7CgkgICAgICAgICAgICAgICAgICAgIG1lc3NhZ2U6ICdBIHJvdyBjb250YWluZWQgYW4gaW52YWxpZCB2YWx1ZSBmb3IgbGF0aXR1ZGUgb3IgbG9uZ2l0dWRlJywKCSAgICAgICAgICAgICAgICAgICAgcm93OiBwYXJzZWRbaV0sCgkgICAgICAgICAgICAgICAgICAgIGluZGV4OiBpCgkgICAgICAgICAgICAgICAgfSk7CgkgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgIGlmICghb3B0aW9ucy5pbmNsdWRlTGF0TG9uKSB7CgkgICAgICAgICAgICAgICAgICAgIGRlbGV0ZSBwYXJzZWRbaV1bbG9uZmllbGRdOwoJICAgICAgICAgICAgICAgICAgICBkZWxldGUgcGFyc2VkW2ldW2xhdGZpZWxkXTsKCSAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIGZlYXR1cmVzLnB1c2goewoJICAgICAgICAgICAgICAgICAgICB0eXBlOiAnRmVhdHVyZScsCgkgICAgICAgICAgICAgICAgICAgIHByb3BlcnRpZXM6IHBhcnNlZFtpXSwKCSAgICAgICAgICAgICAgICAgICAgZ2VvbWV0cnk6IHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICdQb2ludCcsCgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogWwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHBhcnNlRmxvYXQobG9uZiksCgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgcGFyc2VGbG9hdChsYXRmKQoJICAgICAgICAgICAgICAgICAgICAgICAgXQoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfSk7CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCSAgICB9CgoJICAgIGNhbGxiYWNrKGVycm9ycy5sZW5ndGggPyBlcnJvcnMgOiBudWxsLCBmZWF0dXJlY29sbGVjdGlvbik7Cgl9CgoJZnVuY3Rpb24gdG9MaW5lKGdqKSB7CgkgICAgdmFyIGZlYXR1cmVzID0gZ2ouZmVhdHVyZXM7CgkgICAgdmFyIGxpbmUgPSB7CgkgICAgICAgIHR5cGU6ICdGZWF0dXJlJywKCSAgICAgICAgZ2VvbWV0cnk6IHsKCSAgICAgICAgICAgIHR5cGU6ICdMaW5lU3RyaW5nJywKCSAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBbXQoJICAgICAgICB9CgkgICAgfTsKCSAgICBmb3IgKHZhciBpID0gMDsgaSA8IGZlYXR1cmVzLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgIGxpbmUuZ2VvbWV0cnkuY29vcmRpbmF0ZXMucHVzaChmZWF0dXJlc1tpXS5nZW9tZXRyeS5jb29yZGluYXRlcyk7CgkgICAgfQoJICAgIGxpbmUucHJvcGVydGllcyA9IGZlYXR1cmVzLnJlZHVjZShmdW5jdGlvbiAoYWdncmVnYXRlZFByb3BlcnRpZXMsIG5ld0ZlYXR1cmUpIHsKCSAgICAgICAgZm9yICh2YXIga2V5IGluIG5ld0ZlYXR1cmUucHJvcGVydGllcykgewoJICAgICAgICAgICAgaWYgKCFhZ2dyZWdhdGVkUHJvcGVydGllc1trZXldKSB7CgkgICAgICAgICAgICAgICAgYWdncmVnYXRlZFByb3BlcnRpZXNba2V5XSA9IFtdOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgYWdncmVnYXRlZFByb3BlcnRpZXNba2V5XS5wdXNoKG5ld0ZlYXR1cmUucHJvcGVydGllc1trZXldKTsKCSAgICAgICAgfQoJICAgICAgICByZXR1cm4gYWdncmVnYXRlZFByb3BlcnRpZXM7CgkgICAgfSwge30pOwoJICAgIHJldHVybiB7CgkgICAgICAgIHR5cGU6ICdGZWF0dXJlQ29sbGVjdGlvbicsCgkgICAgICAgIGZlYXR1cmVzOiBbbGluZV0KCSAgICB9OwoJfQoKCWZ1bmN0aW9uIHRvUG9seWdvbihnaikgewoJICAgIHZhciBmZWF0dXJlcyA9IGdqLmZlYXR1cmVzOwoJICAgIHZhciBwb2x5ID0gewoJICAgICAgICB0eXBlOiAnRmVhdHVyZScsCgkgICAgICAgIGdlb21ldHJ5OiB7CgkgICAgICAgICAgICB0eXBlOiAnUG9seWdvbicsCgkgICAgICAgICAgICBjb29yZGluYXRlczogW1tdXQoJICAgICAgICB9CgkgICAgfTsKCSAgICBmb3IgKHZhciBpID0gMDsgaSA8IGZlYXR1cmVzLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgIHBvbHkuZ2VvbWV0cnkuY29vcmRpbmF0ZXNbMF0ucHVzaChmZWF0dXJlc1tpXS5nZW9tZXRyeS5jb29yZGluYXRlcyk7CgkgICAgfQoJICAgIHBvbHkucHJvcGVydGllcyA9IGZlYXR1cmVzLnJl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PSB7fTsKCSAgICAgICAgfQoJICAgICAgICBjb25zdCBwcm9wcyA9IHByb3BlcnRpZXMuY29vcmRpbmF0ZVByb3BlcnRpZXM7CgkgICAgICAgIGNvbnN0IGVudHJpZXMgPSBPYmplY3QuZW50cmllcyhsaW5lLmV4dGVuZGVkVmFsdWVzKTsKCSAgICAgICAgZm9yIChsZXQgaSA9IDA7IGkgPCBlbnRyaWVzLmxlbmd0aDsgaSsrKSB7CgkgICAgICAgICAgICBjb25zdCBbbmFtZSwgdmFsXSA9IGVudHJpZXNbaV07CgkgICAgICAgICAgICBpZiAobXVsdGkpIHsKCSAgICAgICAgICAgICAgICBpZiAoIXByb3BzW25hbWVdKSB7CgkgICAgICAgICAgICAgICAgICAgIHByb3BzW25hbWVdID0gZXh0cmFjdGVkTGluZXMubWFwKChsaW5lKSA9PiBuZXcgQXJyYXkobGluZS5saW5lLmxlbmd0aCkuZmlsbChudWxsKSk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIHByb3BzW25hbWVdW2ldID0gdmFsOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgZWxzZSB7CgkgICAgICAgICAgICAgICAgcHJvcHNbbmFtZV0gPSB2YWw7CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCSAgICB9CgkgICAgcmV0dXJuIHsKCSAgICAgICAgdHlwZTogIkZlYXR1cmUiLAoJICAgICAgICBwcm9wZXJ0aWVzOiBwcm9wZXJ0aWVzLAoJICAgICAgICBnZW9tZXRyeTogbXVsdGkKCSAgICAgICAgICAgID8gewoJICAgICAgICAgICAgICAgIHR5cGU6ICJNdWx0aUxpbmVTdHJpbmciLAoJICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiB0cmFjaywKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIDogewoJICAgICAgICAgICAgICAgIHR5cGU6ICJMaW5lU3RyaW5nIiwKCSAgICAgICAgICAgICAgICBjb29yZGluYXRlczogdHJhY2tbMF0sCgkgICA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ICAgICAgICBpZiAoYyA9PT0gbnVsbCkKCSAgICAgICAgICAgIGNvbnRpbnVlOwoJICAgICAgICBsaW5lLnB1c2goYy5jb29yZGluYXRlcyk7CgkgICAgICAgIGNvbnN0IHsgdGltZSwgaGVhcnRSYXRlLCBleHRlbnNpb25zIH0gPSBjOwoJICAgICAgICBpZiAodGltZSkKCSAgICAgICAgICAgIHRpbWVzLnB1c2godGltZSk7CgkgICAgICAgIGlmIChoZWFydFJhdGUpCgkgICAgICAgICAgICBoZWFydFJhdGVzLnB1c2goaGVhcnRSYXRlKTsKCSAgICAgICAgZm9yIChjb25zdCBbYWxpYXMsIHZhbHVlXSBvZiBleHRlbnNpb25zKSB7CgkgICAgICAgICAgICBpZiAoIWV4dGVuZGVkUHJvcGVydGllc1thbGlhc10pIHsKCSAgICAgICAgICAgICAgICBleHRlbmRlZFByb3BlcnRpZXNbYWxpYXNdID0gQXJyYXkocHRzLmxlbmd0aCkuZmlsbChudWxsKTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIGV4dGVuZGVkUHJvcGVydGllc1thbGlhc11baV0gPSB2YWx1ZTsKCSAgICAgICAgfQoJICAgIH0KCSAgICBpZiAobGluZS5sZW5ndGggPCAyKQoJICAgICAgICByZXR1cm4gbnVsbDsKCSAgICByZXR1cm4gT2JqZWN0LmFzc2lnbihyZXN1bHQsIHsKCSAgICAgICAgbGluZTogbGluZSwKCSAgICAgICAgdGltZXM6IHRpbWVzLAoJICAgICAgICBoZWFydFJhdGVzOiBoZWFydFJhdGVzLAoJICAgIH0pOwoJfQoJZnVuY3Rpb24gZ2V0TGFwKG5vZGUpIHsKCSAgICBjb25zdCBzZWdtZW50cyA9ICQobm9kZSwgIlRyYWNrIik7CgkgICAgY29uc3QgdHJhY2sgPSBbXTsKCSAgICBjb25zdCB0aW1lcyA9IFtdOwoJICAgIGNvbnN0IGhlYXJ0UmF0ZXMgPSBbXTsKCSAgICBjb25zdCBhbGxFeHRlbmRlZFByb3BlcnRpZXM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obGluZSkgewoJICAgICAgICAgICAgICAgICAgICBwcm9wZXJ0aWVzW3Byb3BlcnR5XSA9IGxpbmUuZXh0ZW5kZWRQcm9wZXJ0aWVzW3Byb3BlcnR5XTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgICAgICBlbHNlIHsKCSAgICAgICAgICAgICAgICBpZiAoIXByb3BlcnRpZXNbcHJvcGVydHldKSB7CgkgICAgICAgICAgICAgICAgICAgIHByb3BlcnRpZXNbcHJvcGVydHldID0gdHJhY2subWFwKCh0cmFjaykgPT4gQXJyYXkodHJhY2subGVuZ3RoKS5maWxsKG51bGwpKTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgcHJvcGVydGllc1twcm9wZXJ0eV1baV0gPSBleHRlbmRlZFByb3BlcnRpZXNbcHJvcGVydHldOwoJICAgICAgICAgICAgfQoJICAgICAgICB9CgkgICAgfQoJICAgIGlmICh0cmFjay5sZW5ndGggPT09IDApCgkgICAgICAgIHJldHVybiBudWxsOwoJICAgIGlmICh0aW1lcy5sZW5ndGggfHwgaGVhcnRSYXRlcy5sZW5ndGgpIHsKCSAgICAgICAgcHJvcGVydGllcy5jb29yZGluYXRlUHJvcGVydGllcyA9IE9iamVjdC5hc3NpZ24odGltZXMubGVuZ3RoCgkgICAgICAgICAgICA/IHsKCSAgICAgICAgICAgICAgICB0aW1lczogdHJhY2subGVuZ3RoID09PSAxID8gdGltZXNbMF0gOiB0aW1lcywKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIDoge30sIGhlYXJ0UmF0ZXMubGVuZ3RoCgkgICAgICAgICAgICA/IHsKCSAgICAgICAgICAgICAgICBoZWFydDogdHJhY2subGVuZ3RoID09PSAxID8gaGVhcnRSYXRlc1swXSA6IGhlYXJ0UmF0ZXMsCgkgICAgICAgICAgICB9CgkgICAgICAgICAgICA6IHt9KTsKCSAgICB9CgkgICAgcmV0dXJuIHsKCSAgICAgICAgdHlwZTogIkZlYXR1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IHx8IFtdKSkgewoJICAgICAgICBpZiAoYy5ub2RlVHlwZSA9PT0gNCkgewoJICAgICAgICAgICAgcmV0dXJuIHsKCSAgICAgICAgICAgICAgICBkZXNjcmlwdGlvbjogewoJICAgICAgICAgICAgICAgICAgICAiQHR5cGUiOiAiaHRtbCIsCgkgICAgICAgICAgICAgICAgICAgIHZhbHVlOiBub2RlVmFsKGMpLAoJICAgICAgICAgICAgICAgIH0sCgkgICAgICAgICAgICB9OwoJICAgICAgICB9CgkgICAgfQoJICAgIHJldHVybiB7fTsKCX0KCWZ1bmN0aW9uIGV4dHJhY3RUaW1lU3Bhbihub2RlKSB7CgkgICAgcmV0dXJuIGdldChub2RlLCAiVGltZVNwYW4iLCAodGltZVNwYW4pID0+IHsKCSAgICAgICAgcmV0dXJuIHsKCSAgICAgICAgICAgIHRpbWVzcGFuOiB7CgkgICAgICAgICAgICAgICAgYmVnaW46IG5vZGVWYWwoZ2V0MSh0aW1lU3BhbiwgImJlZ2luIikpLAoJICAgICAgICAgICAgICAgIGVuZDogbm9kZVZhbChnZXQxKHRpbWVTcGFuLCAiZW5kIikpLAoJICAgICAgICAgICAgfSwKCSAgICAgICAgfTsKCSAgICB9KTsKCX0KCWZ1bmN0aW9uIGV4dHJhY3RUaW1lU3RhbXAobm9kZSkgewoJICAgIHJldHVybiBnZXQobm9kZSwgIlRpbWVTdGFtcCIsICh0aW1lU3RhbXApID0+IHsKCSAgICAgICAgcmV0dXJuIHsgdGltZXN0YW1wOiBub2RlVmFsKGdldDEodGltZVN0YW1wLCAid2hlbiIpKSB9OwoJICAgIH0pOwoJfQoJZnVuY3Rpb24gZXh0cmFjdENhc2NhZGVkU3R5bGUobm9kZSwgc3R5bGVNYXApIHsKCSAgICByZXR1cm4gdmFsMShub2RlLCAic3R5bGVVcmwiLCAoc3R5bGVVcmwpID0+IHsKCSAgICAgICAgc3R5bGVVcmwgPSBub3JtYWxpemVJZChzdHlsZVVybCk7CgkgICAgICAgIGlmIChzdHlsZU1h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2VvbWV0cmllcy5jb25jYXQoY2hpbGRHZW9tZXRyaWVzLmdlb21ldHJpZXMpOwoJICAgICAgICAgICAgICAgICAgICBjb29yZFRpbWVzID0gY29vcmRUaW1lcy5jb25jYXQoY2hpbGRHZW9tZXRyaWVzLmNvb3JkVGltZXMpOwoJICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgY2FzZSAiUG9pbnQiOiB7CgkgICAgICAgICAgICAgICAgICAgIGNvbnN0IGNvb3JkaW5hdGVzID0gY29vcmQxKGdldENvb3JkaW5hdGVzKGNoaWxkKSk7CgkgICAgICAgICAgICAgICAgICAgIGlmIChjb29yZGluYXRlcy5sZW5ndGggPj0gMikgewoJICAgICAgICAgICAgICAgICAgICAgICAgZ2VvbWV0cmllcy5wdXNoKHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAiUG9pbnQiLAoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzLAoJICAgICAgICAgICAgICAgICAgICAgICAgfSk7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIGNhc2UgIkxpbmVhclJpbmciOgoJICAgICAgICAgICAgICAgIGNhc2UgIkxpbmVTdHJpbmciOiB7CgkgICAgICAgICAgICAgICAgICAgIGNvbnN0IGNvb3JkaW5hdGVzID0gY29vcmQoZ2V0Q29vcmRpbmF0ZXMoY2hpbGQpKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGNvb3JkaW5hdGVzLmxlbmd0aCA+PSAyKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBnZW9tZXRyaWVzLnB1c2goewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICJMaW5lU3RyaW5nIiwKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlcywKCSAgICAgICAgICAgICAgICAgICAgICAgIH0pOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGJyZWFrOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICBjYXNlICJQb2x5Z29uIjogewoJICAgICAgICAgICAgICAgICAgICBjb25zdCBjb29yZHMgPSBbXTsKCSAgICAgICAgICAgICAgICAgICAgZm9yIChjb25zdCBsaW5lYXJSaW5nIG9mICQoY2hpbGQsICJMaW5lYXJSaW5nIikpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvbnN0IHJpbmcgPSBmaXhSaW5nKGNvb3JkKGdldENvb3JkaW5hdGVzKGxpbmVhclJpbmcpKSk7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAocmluZy5sZW5ndGggPj0gNCkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGNvb3Jkcy5wdXNoKHJpbmcpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGlmIChjb29yZHMubGVuZ3RoKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBnZW9tZXRyaWVzLnB1c2goewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICJQb2x5Z29uIiwKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogY29vcmRzLAoJICAgICAgICAgICAgICAgICAgICAgICAgfSk7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIGNhc2UgIlRyYWNrIjoKCSAgICAgICAgICAgICAgICBjYXNlICJneDpUcmFjayI6IHsKCSAgICAgICAgICAgICAgICAgICAgY29uc3QgZ3ggPSBneENvb3JkcyhjaGlsZCk7CgkgICAgICAgICAgICAgICAgICAgIGlmICghZ3gpCgkgICAgICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICAgICAgY29uc3QgeyB0aW1lcywgZ2VvbWV0cnkgfSA9IGd4OwoJICAgICAgICAgICAgICAgICAgICBnZW9tZXRyaWVzLnB1c2goZ2VvbWV0cnkpOwoJICAgICAgICAgICAgICAgICAgICBpZiAodGltZXMubGVuZ3RoKQoJICAgICAgICAgICAgICAgICAgICAgICAgY29vcmRUaW1lcy5wdXNoKHRpbWVzKTsKCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICB9CgkgICAgfQoJICAgIHJldHVybiB7CgkgICAgICAgIGdlb21ldHJpZXMsCgkgICAgICAgIGNvb3JkVGltZXMsCgkgICAgfTsKCX0KCglmdW5jdGlvbiBnZW9tZXRyeUxpc3RUb0dlb21ldHJ5KGdlb21ldHJpZXMpIHsKCSAgICByZXR1cm4gZ2VvbWV0cmllcy5sZW5ndGggPT09IDAKCSAgICAgICAgPyBudWxsCgkgICAgICAgIDogZ2VvbWV0cmllcy5sZW5ndGggPT09IDEKCSAgICAgICAgICAgID8gZ2VvbWV0cmllc1swXQoJICAgICAgICAgICAgOiB7CgkgICAgICAgICAgICAgICAgdHlwZTogIkdlb21ldHJ5Q29sbGVjdGlvbiIsCgkgICAgICAgICAgICAgICAgZ2VvbWV0cmllcywKCSAgICAgICAgICAgIH07Cgl9CglmdW5jdGlvbiBnZXRQbGFjZW1hcmsobm9kZSwgc3R5bGVNYXAsIHNjaGVtYSwgb3B0aW9ucykgewoJICAgIGNvbnN0IHsgY29vcmRUaW1lcywgZ2VvbWV0cmllcyB9ID0gZ2V0R2VvbWV0cnkobm9kZSk7CgkgICAgY29uc3QgZ2VvbWV0cnkgPSBnZW9tZXRyeUxpc3RUb0dlb21ldHJ5KGdlb21ldHJpZXMpOwoJICAgIGlmICghZ2VvbWV0cnkgJiYgb3B0aW9ucy5za2lwTnVsbEdlb21ldHJ5KSB7CgkgICAgICAgIHJldHVybiBudWxsOwoJICAgIH0KCSAgICBjb25zdCBmZWF0dXJlID0gewoJICAgICAgICB0eXBlOiAiRmVhdHVyZSIsCgkgICAgICAgIGdlb21ldHJ5LAoJICAgICAgICBwcm9wZXJ0aWVzOiBPYmplY3QuYXNzaWduKGdldE11bHRpKG5vZGUsIFsKCSAgICAgICAgICAgICJuYW1lIiwKCSAgICAgICAgICAgICJhZGRyZXNzIiwKCSAgICAgICAgICAgICJ2aXNpYmlsaXR5IiwKCSAgICAgICAgICAgICJvcGVuIiwKCSAgICAgICAgICAgICJwaG9uZU51bWJlciIsCgkgICAgICAgICAgICAiZGVzY3JpcHRpb24iLAoJICAgICAgICBdKSwgZ2V0TWF5YmVIVE1MRGVzY3JpcHRpb24obm9kZSksIGV4dHJhY3RDYXNjYWRlZFN0eWxlKG5vZGUsIHN0eWxlTWFwKSwgZXh0cmFjdFN0eWxlKG5vZGUpLCBleHRyYWN0RXh0ZW5kZWREYXRhKG5vZGUsIHNjaGVtYSksIGV4dHJhY3RUaW1lU3Bhbihub2RlKSwgZXh0cmFjdFRpbWVTdGFtcChub2RlKSwgY29vcmRUaW1lcy5sZW5ndGgKCSAgICAgICAgICAgID8gewoJICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVQcm9wZXJ0aWVzOiB7CgkgICAgICAgICAgICAgICAgICAgIHRpbWVzOiBjb29yZFRpbWVzLmxlbmd0aCA9PT0gMSA/IGNvb3JkVGltZXNbMF0gOiBjb29yZFRpbWVzLAoJICAgICAgICAgICAgICAgIH0sCgkgICAgICAgICAgICB9CgkgICAgICAgICAgICA6IHt9KSwKCSAgICB9OwoJICAgIGlmIChmZWF0dXJlLnByb3BlcnRpZXM/LnZpc2liaWxpdHkgIT09IHVuZGVmaW5lZCkgewoJICAgICAgICBmZWF0dXJlLnByb3BlcnRpZXMudmlzaWJpbGl0eSA9IGZlYXR1cmUucHJvcGVydGllcy52aXNpYmlsaXR5ICE9PSAiMCI7CgkgICAgfQoJICAg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C5zcXJ0KE1hdGgucG93KGR5LCAyKSArIE1hdGgucG93KGR4LCAyKSk7CgkgICAgICAgICAgICBjb25zdCBhbmdsZSA9IE1hdGguYXRhbjIoZHksIGR4KSArIHJvdGF0aW9uICogREVHUkVFU19UT19SQURJQU5TOwoJICAgICAgICAgICAgcmV0dXJuIFsKCSAgICAgICAgICAgICAgICBjZW50ZXJbMF0gKyBNYXRoLmNvcyhhbmdsZSkgKiBkaXN0YW5jZSwKCSAgICAgICAgICAgICAgICBjZW50ZXJbMV0gKyBNYXRoLnNpbihhbmdsZSkgKiBkaXN0YW5jZSwKCSAgICAgICAgICAgIF07CgkgICAgICAgIH0pLAoJICAgIF07Cgl9CglmdW5jdGlvbiBnZXRMYXRMb25Cb3gobm9kZSkgewoJICAgIGNvbnN0IGxhdExvbkJveCA9IGdldDEobm9kZSwgIkxhdExvbkJveCIpOwoJICAgIGlmIChsYXRMb25Cb3gpIHsKCSAgICAgICAgY29uc3Qgbm9ydGggPSBudW0xKGxhdExvbkJveCwgIm5vcnRoIik7CgkgICAgICAgIGNvbnN0IHdlc3QgPSBudW0xKGxhdExvbkJveCwgIndlc3QiKTsKCSAgICAgICAgY29uc3QgZWFzdCA9IG51bTEobGF0TG9uQm94LCAiZWFzdCIpOwoJICAgICAgICBjb25zdCBzb3V0aCA9IG51bTEobGF0TG9uQm94LCAic291dGgiKTsKCSAgICAgICAgY29uc3Qgcm90YXRpb24gPSBudW0xKGxhdExvbkJveCwgInJvdGF0aW9uIik7CgkgICAgICAgIGlmICh0eXBlb2Ygbm9ydGggPT09ICJudW1iZXIiICYmCgkgICAgICAgICAgICB0eXBlb2Ygc291dGggPT09ICJudW1iZXIiICYmCgkgICAgICAgICAgICB0eXBlb2Ygd2VzdCA9PT0gIm51bWJlciIgJiYKCSAgICAgICAgICAgIHR5cGVvZiBlYXN0ID09PSAibnVtYmVyIikgewoJICAgICAgICAgICAgY29uc3QgYmJveCA9IFt3ZXN0LCBzb3V0aCwgZWFzdCwgbm9ydGhdOwoJICAgICAgICAgICAgbGV0IGNvb3JkaW5hdGVzID0gWwoJICAgICAgICAgICAgICAgIFsKCSAgICAgICAgICAgICAgICAgICAgW3dlc3QsIG5vcnRoXSwKCSAgICAgICAgICAgICAgICAgICAgW2Vhc3QsIG5vcnRoXSwKCSAgICAgICAgICAgICAgICAgICAgW2Vhc3QsIHNvdXRoXSwKCSAgICAgICAgICAgICAgICAgICAgW3dlc3QsIHNvdXRoXSwKCSAgICAgICAgICAgICAgICAgICAgW3dlc3QsIG5vcnRoXSwgLy8gdG9wIGxlZnQgKGFnYWluKQoJICAgICAgICAgICAgICAgIF0sCgkgICAgICAgICAgICBdOwoJICAgICAgICAgICAgaWYgKHR5cGVvZiByb3RhdGlvbiA9PT0gIm51bWJlciIpIHsKCSAgICAgICAgICAgICAgICBjb29yZGluYXRlcyA9IHJvdGF0ZUJveChiYm94LCBjb29yZGluYXRlcywgcm90YXRpb24pOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmV0dXJuIHsKCSAgICAgICAgICAgICAgICBiYm94LAoJICAgICAgICAgICAgICAgIGdlb21ldHJ5OiB7CgkgICAgICAgICAgICAgICAgICAgIHR5cGU6ICJQb2x5Z29uIiwKCSAgICAgICAgICAgICAgICAgICAgY29vcmRpbmF0ZXMsCgkgICAgICAgICAgICAgICAgfSwKCSAgICAgICAgICAgIH07CgkgICAgICAgIH0KCSAgICB9CgkgICAgcmV0dXJuIG51bGw7Cgl9CglmdW5jdGlvbiBnZXRHcm91bmRPdmVybGF5KG5vZGUsIHN0eWxlTWFwLCBzY2hlbWEsIG9wdGlvbnMpIHsKCSAgICBjb25zdCBib3ggPSBnZXRHcm91bmRPdmVybGF5Qm94KG5vZGUpOwoJICAgIGNvbnN0IGdlb21ldHJ5ID0gYm94Py5nZW9tZXRyeSB8fCBudWxsOwoJICAgIGlmICghZ2VvbWV0cnkgJiYgb3B0aW9ucy5za2lwTnVsbEdlb21ldHJ5KSB7CgkgICAgICAgIHJldHVybi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gICAgICAgY29uc3QgcGxhY2VtYXJrID0gZ2V0UGxhY2VtYXJrKG5vZGUsIHN0eWxlTWFwLCBzY2hlbWEsIG9wdGlvbnMpOwoJICAgICAgICAgICAgICAgICAgICBpZiAocGxhY2VtYXJrKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBwb2ludGVyLmNoaWxkcmVuLnB1c2gocGxhY2VtYXJrKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgY2FzZSAiRm9sZGVyIjogewoJICAgICAgICAgICAgICAgICAgICBjb25zdCBmb2xkZXIgPSBnZXRGb2xkZXIobm9kZSk7CgkgICAgICAgICAgICAgICAgICAgIHBvaW50ZXIuY2hpbGRyZW4ucHVzaChmb2xkZXIpOwoJICAgICAgICAgICAgICAgICAgICBwb2ludGVyID0gZm9sZGVyOwoJICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCSAgICAgICAgaWYgKG5vZGUuY2hpbGROb2RlcykgewoJICAgICAgICAgICAgZm9yIChsZXQgaSA9IDA7IGkgPCBub2RlLmNoaWxkTm9kZXMubGVuZ3RoOyBpKyspIHsKCSAgICAgICAgICAgICAgICB0cmF2ZXJzZShub2RlLmNoaWxkTm9kZXNbaV0sIHBvaW50ZXIsIG9wdGlvbnMpOwoJICAgICAgICAgICAgfQoJICAgICAgICB9CgkgICAgfQoJICAgIHRyYXZlcnNlKG5vZGUsIHRyZWUsIG9wdGlvbnMpOwoJICAgIHJldHVybiB0cmVlOwoJfQoJLyoqCgkgKiBDb252ZXJ0IEtNTCB0byBHZW9KU09OIGluY3JlbWVudGFsbHksIHJldHVybmluZwoJICogYSBbR2VuZXJhdG9yXShodHRwczovL2RldmVsb3Blci5tb3ppbGxhLm9yZy9lbi1VUy9kb2NzL1dlYi9KYXZhU2NyaXB0L0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AgICAgICAgICAgICBmb3IgKGxldCBwcm9wIG9mIGJsYWNrbGlzdCkgewoJICAgICAgICAgICAgICAgICAgICBkZWxldGUgcnNbcHJvcF07CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmV0dXJuIHJzOwoJICAgICAgICB9CgkgICAgICAgIHJldHVybiB7fTsKCSAgICB9OwoKCSAgICBjb25zdCBtZXJnZVByb3BzID0gKG9iajEsIG9iajIpID0+IHsKCSAgICAgICAgb2JqMSA9IG9iajEgPyBvYmoxIDoge307CgkgICAgICAgIG9iajIgPSBvYmoyID8gb2JqMiA6IHt9OwoJICAgICAgICByZXR1cm4gT2JqZWN0LmFzc2lnbihvYmoxLCBvYmoyKTsKCSAgICB9OwoKCSAgICBjb25zdCBmaXJzdCA9IGEgPT4gYVswXTsKCSAgICBjb25zdCBsYXN0ID0gYSA9PiBhW2EubGVuZ3RoIC0gMV07CgkgICAgY29uc3QgY29vcmRzVG9LZXkgPSBhID0+IGEuam9pbignLCcpOwoKCSAgICBjb25zdCBhZGRUb01hcCA9IChtLCBrLCB2KSA9PiB7CgkgICAgICAgIGxldCBhID0gbVtrXTsKCSAgICAgICAgaWYgKGEpIHsKCSAgICAgICAgICAgIGEucHVzaCh2KTsKCSAgICAgICAgfSBlbHNlIHsKCSAgICAgICAgICAgIG1ba10gPSBbdl07CgkgICAgICAgIH0KCSAgICB9OwoKCSAgICBjb25zdCByZW1vdmVGcm9tTWFwID0gKG0sIGssIHYpID0+IHsKCSAgICAgICAgbGV0IGEgPSBtW2tdOwoJICAgICAgICBsZXQgaWR4ID0gbnVsbDsKCSAgICAgICAgaWYgKGEgJiYgKGlkeCA9IGEuaW5kZXhPZih2KSkgPj0gMCkgewoJICAgICAgICAgICAgYS5zcGxpY2UoaWR4LCAxKTsKCSAgICAgICAgfQoJICAgIH07CgoJICAgIGNvbnN0IGdldEZpcnN0RnJvbU1hcCA9IChtLCBrKSA9PiB7CgkgICAgICAgIGxldCB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gkgICAgICAgICAgICAgICAgcmVzdWx0ID0gIXJlc3VsdDsKCSAgICAgICAgICAgIH0KCgkgICAgICAgIH0KCSAgICAgICAgcmV0dXJuIHJlc3VsdDsKCSAgICB9OwoKCSAgICBjb25zdCBzdHJUb0Zsb2F0ID0gZWwgPT4gZWwgaW5zdGFuY2VvZiBBcnJheSA/IGVsLm1hcChzdHJUb0Zsb2F0KSA6IHBhcnNlRmxvYXQoZWwpOwoKCSAgICBjbGFzcyBSZWZFbGVtZW50cyBleHRlbmRzIE1hcCB7CgkgICAgICAgIGNvbnN0cnVjdG9yKCkgewoJICAgICAgICAgICAgc3VwZXIoKTsKCSAgICAgICAgICAgIHRoaXMuYmluZGVycyA9IFtdOwoJICAgICAgICB9CgoJICAgICAgICBhZGQoaywgdikgewoJICAgICAgICAgICAgaWYgKCF0aGlzLmhhcyhrKSkgewoJICAgICAgICAgICAgICAgIHRoaXMuc2V0KGssIHYpOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgLy8gc3VwcHJlc3MgZHVwbGNhdGVkIGtleSBlcnJvcgoJICAgICAgICAgICAgLy8gZWxzZQoJICAgICAgICAgICAgLy8gdGhyb3cgYEVycm9yOiBhZGRpbmcgZHVwbGljYXRlZCBrZXkgJyR7a30nIHRvIFJlZkVsZW1lbnRzYDsKCSAgICAgICAgfQoKCSAgICAgICAgYWRkQmluZGVyKGJpbmRlcikgewoJICAgICAgICAgICAgdGhpcy5iaW5kZXJzLnB1c2goYmluZGVyKTsKCSAgICAgICAgfQoKCSAgICAgICAgYmluZEFsbCgpIHsKCSAgICAgICAgICAgIHRoaXMuYmluZGVycy5mb3JFYWNoKGJpbmRlciA9PiBiaW5kZXIuYmluZCgpKTsKCSAgICAgICAgfQoJICAgIH0KCgkgICAgY2xhc3MgTGF0ZUJpbmRlciB7CgkgICAgICAgIGNvbnN0cnVjdG9yKGNvbnRhaW5lciwgdmFsdWVGdW5jLCBjdHgsIGFyZ3MpIHsKCSAgICAgICAgICAgIHRoaXMuY29udGFpbmVyID0gY29udGFpbmVyOwoJICAgICAgICAgICAgdGhpcy52YWx1ZUZ1bmMgPSB2YWx1ZUZ1bmM7CgkgICAgICAgICAgICB0aGlzLmN0eCA9IGN0eDsKCSAgICAgICAgICAgIHRoaXMuYXJncyA9IGFyZ3M7CgkgICAgICAgIH0KCgkgICAgICAgIGJpbmQoKSB7CgkgICAgICAgICAgICBsZXQgdiA9IHRoaXMudmFsdWVGdW5jLmFwcGx5KHRoaXMuY3R4LCB0aGlzLmFyZ3MpOwoJICAgICAgICAgICAgaWYgKHRoaXMuY29udGFpbmVyIGluc3RhbmNlb2YgQXJyYXkpIHsKCSAgICAgICAgICAgICAgICBsZXQgaWR4ID0gdGhpcy5jb250YWluZXIuaW5kZXhPZih0aGlzKTsKCSAgICAgICAgICAgICAgICBpZiAoaWR4ID49IDApIHsKCSAgICAgICAgICAgICAgICAgICAgbGV0IGFyZ3MgPSBbaWR4LCAxXTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKHYpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGFyZ3MucHVzaCh2KTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICBbXS5zcGxpY2UuYXBwbHkodGhpcy5jb250YWluZXIsIGFyZ3MpOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0gZWxzZSBpZiAodHlwZW9mIHRoaXMuY29udGFpbmVyID09PSAnb2JqZWN0JykgewoJICAgICAgICAgICAgICAgIGxldCBrID0gT2JqZWN0LmtleXModGhpcy5jb250YWluZXIpLmZpbmQodiA9PiB0aGlzLmNvbnRhaW5lclt2XSA9PT0gdGhpcyk7CgkgICAgICAgICAgICAgICAgaWYgKGspIHsKCSAgICAgICAgICAgICAgICAgICAgaWYgKHYpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHRoaXMuY29udGFpbmVyW2tdID0gdjsKCSAgICAgICAgICAgICAgICAgICAgfSBlbHNlIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGRlbGV0ZSB0aGlzLmNvbnRhaW5lcltrXTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgfQoJICAgIH0KCgkgICAgY2xhc3MgV2F5Q29sbGVjdGlvbiBleHRlbmRzIEFycmF5IHsKCSAgICAgICAgY29uc3RydWN0b3IoKSB7CgkgICAgICAgICAgICBzdXBlcigpOwoJICAgICAgICAgICAgdGhpcy5maXJzdE1hcCA9IHt9OwoJICAgICAgICAgICAgdGhpcy5sYXN0TWFwID0ge307CgkgICAgICAgIH0KCgkgICAgICAgIGFkZFdheSh3YXkpIHsKCSAgICAgICAgICAgIHdheSA9IHdheS50b0Nvb3Jkc0FycmF5KCk7CgkgICAgICAgICAgICBpZiAod2F5Lmxlbmd0aCA+IDApIHsKCSAgICAgICAgICAgICAgICB0aGlzLnB1c2god2F5KTsKCSAgICAgICAgICAgICAgICBhZGRUb01hcCh0aGlzLmZpcnN0TWFwLCBjb29yZHNUb0tleShmaXJzdCh3YXkpKSwgd2F5KTsKCSAgICAgICAgICAgICAgICBhZGRUb01hcCh0aGlzLmxhc3RNYXAsIGNvb3Jkc1RvS2V5KGxhc3Qod2F5KSksIHdheSk7CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCgkgICAgICAgIHRvU3RyaW5ncygpIHsKCSAgICAgICAgICAgIGxldCBzdHJpbmdzID0gW10sIHdheSA9IG51bGw7CgkgICAgICAgICAgICB3aGlsZSAod2F5ID0gdGhpcy5zaGlmdCgpKSB7CgkgICAgICAgICAgICAgICAgcmVtb3ZlRnJvbU1hcCh0aGlzLmZpcnN0TWFwLCBjb29yZHNUb0tleShmaXJzdCh3YXkpKSwgd2F5KTsKCSAgICAgICAgICAgICAgICByZW1vdmVGcm9tTWFwKHRoaXMubGFzdE1hcCwgY29vcmRzVG9LZXkobGFzdCh3YXkpKSwgd2F5KTsKCSAgICAgICAgICAgICAgICBsZXQgY3VycmVudCA9IHdheSwgbmV4dCA9IG51bGw7CgkgICAgICAgICAgICAgICAgZG8gewoJICAgICAgICAgICAgICAgICAgICBsZXQga2V5ID0gY29vcmRzVG9LZXkobGFzdChjdXJyZW50KSksIHNob3VsZFJldmVyc2UgPSBmYWxzZTsKCgkgICAgICAgICAgICAgICAgICAgIG5leHQgPSBnZXRGaXJzdEZyb21NYXAodGhpcy5maXJzdE1hcCwga2V5KTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKCFuZXh0KSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBuZXh0ID0gZ2V0Rmlyc3RGcm9tTWFwKHRoaXMubGFzdE1hcCwga2V5KTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHNob3VsZFJldmVyc2UgPSB0cnVlOwoJICAgICAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgICAgICBpZiAobmV4dCkgewoJICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5zcGxpY2UodGhpcy5pbmRleE9mKG5leHQpLCAxKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHJlbW92ZUZyb21NYXAodGhpcy5maXJzdE1hcCwgY29vcmRzVG9LZXkoZmlyc3QobmV4dCkpLCBuZXh0KTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHJlbW92ZUZyb21NYXAodGhpcy5sYXN0TWFwLCBjb29yZHNUb0tleShsYXN0KG5leHQpKSwgbmV4dCk7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAoc2hvdWxkUmV2ZXJzZSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIC8vIGFsd2F5cyByZXZlcnNlIHNob3J0ZXIgb25lIHRvIHNhdmUgdGltZQoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGlmIChuZXh0Lmxlbmd0aCA+IGN1cnJlbnQubGVuZ3RoKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFtjdXJyZW50LCBuZXh0XSA9IFtuZXh0LCBjdXJyZW50XTsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgbmV4dC5yZXZlcnNlKCk7CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgICAgICAgICAgY3VycmVudCA9IGN1cnJlbnQuY29uY2F0KG5leHQuc2xpY2UoMSkpOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfSB3aGlsZSAobmV4dCk7CgkgICAgICAgICAgICAgICAgc3RyaW5ncy5wdXNoKHN0clRvRmxvYXQoY3VycmVudCkpOwoJICAgICAgICAgICAgfQoKCSAgICAgICAgICAgIHJldHVybiBzdHJpbmdzOwoJICAgICAgICB9CgoJICAgICAgICB0b1JpbmdzKGRpcmVjdGlvbikgewoJICAgICAgICAgICAgbGV0IHN0cmluZ3MgPSB0aGlzLnRvU3RyaW5ncygpOwoJICAgICAgICAgICAgbGV0IHJpbmdzID0gW10sIHN0cmluZyA9IG51bGw7CgkgICAgICAgICAgICB3aGlsZSAoc3RyaW5nID0gc3RyaW5ncy5zaGlmdCgpKSB7CgkgICAgICAgICAgICAgICAgaWYgKGlzUmluZyhzdHJpbmcpKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmIChyaW5nRGlyZWN0aW9uKHN0cmluZykgIT09IGRpcmVjdGlvbikgewoJICAgICAgICAgICAgICAgICAgICAgICAgc3RyaW5nLnJldmVyc2UoKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICByaW5ncy5wdXNoKHN0cmluZyk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmV0dXJuIHJpbmdzOwoJICAgICAgICB9CgkgICAgfQoKCSAgICByZXR1cm4gewoJICAgICAgICBwdXJnZVByb3BzLCBtZXJnZVByb3BzLAoJICAgICAgICBmaXJzdCwgbGFzdCwgY29vcmRzVG9LZXksCgkgICAgICAgIGFkZF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VmRWxlbXMpIHsKCSAgICAgICAgICAgICAgICByZWZFbGVtcy5hZGQodGhpcy5nZXRDb21wb3NpdGVJZCgpLCB0aGlzKTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgfQoKCSAgICAgICAgYWRkVGFncyh0YWdzKSB7CgkgICAgICAgICAgICB0aGlzLnRhZ3MgPSBPYmplY3QuYXNzaWduKHRoaXMudGFncywgdGFncyk7CgkgICAgICAgICAgICB0aGlzLmhhc1RhZyA9IHRhZ3MgPyB0cnVlIDogZmFsc2U7CgkgICAgICAgIH0KCgkgICAgICAgIGFkZFRhZyhrLCB2KSB7CgkgICAgICAgICAgICB0aGlzLnRhZ3Nba10gPSB2OwoJICAgICAgICAgICAgdGhpcy5oYXNUYWcgPSBrID8gdHJ1ZSA6IGZhbHNlOwoJICAgICAgICB9CgoJICAgICAgICBhZGRQcm9wKGssIHYpIHsKCSAgICAgICAgICAgIHRoaXMucHJvcHNba10gPSB2OwoJICAgICAgICB9CgoJICAgICAgICBhZGRQcm9wcyhwcm9wcykgewoJICAgICAgICAgICAgdGhpcy5wcm9wcyA9IE9iamVjdC5hc3NpZ24odGhpcy5wcm9wcywgcHJvcHMpOwoJICAgICAgICB9CgoJICAgICAgICBnZXRDb21wb3NpdGVJZCgpIHsKCSAgICAgICAgICAgIHJldHVybiBgJHt0aGlzLnR5cGV9LyR7dGhpcy5pZH1gOwoJICAgICAgICB9CgoJICAgICAgICBnZXRQcm9wcygpIHsKCSAgICAgICAgICAgIHJldHVybiBPYmplY3QuYXNzaWduKHRoaXMucHJvcHMsIHRoaXMudGFncyk7CgkgICAgICAgIH0KCgkgICAgICAgIHRvRmVhdHVyZUFycmF5KCkgewoJICAgICAgICAgICAgcmV0dXJuIFtdOwoJICAgICAgICB9CgkgICAgfQoKCSAgICBjbGFzcyBOb2RlIGV4dGVuZHMgT3NtT2JqZWN0IHsKCSAgICAgICAgY29uc3RydWN0b3IoaWQsIHJlZkVsZW1zKSB7CgkgICAgICAgICAgICBzdXBlcignbm9kZScsIGlkLCByZWZFbGVtcyk7CgkgICAgICAgICAgICB0aGlzLmxhdExuZyA9IG51bGw7CgkgICAgICAgIH0KCgkgICAgICAgIHNldExhdExuZyhsYXRMbmcpIHsKCSAgICAgICAgICAgIHRoaXMubGF0TG5nID0gbGF0TG5nOwoJICAgICAgICB9CgoJICAgICAgICB0b0ZlYXR1cmVBcnJheSgpIHsKCSAgICAgICAgICAgIGlmICh0aGlzLmxhdExuZykgewoJICAgICAgICAgICAgICAgIHJldHVybiBbewoJICAgICAgICAgICAgICAgICAgICB0eXBlOiAnRmVhdHVyZScsCgkgICAgICAgICAgICAgICAgICAgIGlkOiB0aGlzLmdldENvbXBvc2l0ZUlkKCksCgkgICAgICAgICAgICAgICAgICAgIHByb3BlcnRpZXM6IHRoaXMuZ2V0UHJvcHMoKSwKCSAgICAgICAgICAgICAgICAgICAgZ2VvbWV0cnk6IHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICdQb2ludCcsCgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogc3RyVG9GbG9hdChbdGhpcy5sYXRMbmcubG9uLCB0aGlzLmxhdExuZy5sYXRdKQoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfV07CgkgICAgICAgICAgICB9CgoJICAgICAgICAgICAgcmV0dXJuIFtdOwoJICAgICAgICB9CgoJICAgICAgICBnZXRMYXRMbmcoKSB7CgkgICAgICAgICAgICByZXR1cm4gdGhpcy5sYXRMbmc7CgkgICAgICAgIH0KCSAgICB9CgoJICAgIGNsYXNzIFdheSBleHRlbmRzIE9zbU9iamVjdCB7CgkgICAgICAgIGNvbnN0cnVjdG9yKGlkLCByZWZFbGVtcykgewoJICAgICAgICAgICAgc3VwZXIoJ3dheScsIGlkLCByZWZFbGVtcyk7CgkgICAgICAgICAgICB0aGlzLmxhdExuZ0FycmF5ID0gW107CgkgICAgICAgICAgICB0aGlzLmlzUG9seWdvbiA9IGZhbHNlOwoJICAgICAgICB9CgoJICAgICAgICBhZGRMYXRMbmcobGF0TG5nKSB7CgkgICAgICAgICAgICB0aGlzLmxhdExuZ0FycmF5LnB1c2gobGF0TG5nKTsKCSAgICAgICAgfQoKCSAgICAgICAgc2V0TGF0TG5nQXJyYXkobGF0TG5nQXJyYXkpIHsKCSAgICAgICAgICAgIHRoaXMubGF0TG5nQXJyYXkgPSBsYXRMbmdBcnJheTsKCSAgICAgICAgfQoKCSAgICAgICAgYWRkTm9kZVJlZihyZWYpIHsKCSAgICAgICAgICAgIGxldCBiaW5kZXIgPSBuZXcgTGF0ZUJpbmRlcih0aGlzLmxhdExuZ0FycmF5LCBmdW5jdGlvbiAoaWQpIHsKCSAgICAgICAgICAgICAgICBsZXQgbm9kZSA9IHRoaXMucmVmRWxlbXMuZ2V0KGBub2RlLyR7aWR9YCk7CgkgICAgICAgICAgICAgICAgaWYgKG5vZGUpIHsKCSAgICAgICAgICAgICAgICAgICAgbm9kZS5yZWZDb3VudCsrOwoJICAgICAgICAgICAgICAgICAgICByZXR1cm4gbm9kZS5nZXRMYXRMbmcoKTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9LCB0aGlzLCBbcmVmXSk7CgoJICAgICAgICAgICAgdGhpcy5sYXRMbmdBcnJheS5wdXNoKGJpbmRlcik7CgkgICAgICAgICAgICB0aGlzLnJlZkVsZW1zLmFkZEJpbmRlcihiaW5kZXIpOwoJICAgICAgICB9CgoJICAgICAgICBhbmFseXplR2VvbWV0cnlUeXBlKGssIHYpIHsKCSAgICAgICAgICAgIGxldCBvID0gcG9seWdvblRhZ3Nba107CgkgICAgICAgICAgICBpZiAobykgewoJICAgICAgICAgICAgICAgIHRoaXMuaXNQb2x5Z29uID0gdHJ1ZTsKCSAgICAgICAgICAgICAgICBpZiAoby53aGl0ZWxpc3QpIHsKCSAgICAgICAgICAgICAgICAgICAgdGhpcy5pc1BvbHlnb24gPSBvLndoaXRlbGlzdC5pbmRleE9mKHYpID49IDAgPyB0cnVlIDogZmFsc2U7CgkgICAgICAgICAgICAgICAgfSBlbHNlIGlmIChvLmJsYWNrbGlzdCkgewoJICAgICAgICAgICAgICAgICAgICB0aGlzLmlzUG9seWdvbiA9IG8uYmxhY2tsaXN0LmluZGV4T2YodikgPj0gMCA/IGZhbHNlIDogdHJ1ZTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCgkgICAgICAgIGFkZFRhZ3ModGFncykgewoJICAgICAgICAgICAgc3VwZXIuYWRkVGFncyh0YWdzKTsKCSAgICAgICAgICAgIGZvciAobGV0IFtrLCB2XSBvZiBPYmplY3QuZW50cmllcyh0YWdzKSkgewoJICAgICAgICAgICAgICAgIHRoaXMuYW5hbHl6ZUdlb21ldHJ5VHlwZShrLCB2KTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgfQoKCSAgICAgICAgYWRkVGFnKGssIHYpIHsKCSAgICAgICAgICAgIHN1cGVyLmFkZFRhZyhrLCB2KTsKCSAgICAgICAgICAgIHRoaXMuYW5hbHl6ZUdlb21ldHJ5VHlwZShrLCB2KTsKCSAgICAgICAgfQoKCSAgICAgICAgdG9Db29yZHNBcnJheSgpIHsKCSAgICAgICAgICAgIHJldHVybiB0aGlzLmxhdExuZ0FycmF5Lm1hcChsYXRMbmcgPT4gW2xhdExuZy5sb24sIGxhdExuZy5sYXRdKTsKCSAgICAgICAgfQoKCSAgICAgICAgdG9GZWF0dXJlQXJyYXkoKSB7CgkgICAgICAgICAgICBsZXQgY29vcmRzQXJyYXkgPSB0aGlzLnRvQ29vcmRzQXJyYXkoKTsKCSAgICAgICAgICAgIGlmIChjb29yZHNBcnJheS5sZW5ndGggPiAxKSB7CgkgICAgICAgICAgICAgICAgY29vcmRzQXJyYXkgPSBzdHJUb0Zsb2F0KGNvb3Jkc0FycmF5KTsKCSAgICAgICAgICAgICAgICBsZXQgZmVhdHVyZSA9IHsKCSAgICAgICAgICAgICAgICAgICAgdHlwZTogJ0ZlYXR1cmUnLAoJICAgICAgICAgICAgICAgICAgICBpZDogdGhpcy5nZXRDb21wb3NpdGVJZCgpLAoJICAgICAgICAgICAgICAgICAgICBwcm9wZXJ0aWVzOiB0aGlzLmdldFByb3BzKCksCgkgICAgICAgICAgICAgICAgICAgIGdlb21ldHJ5OiB7CgkgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAnTGluZVN0cmluZycsCgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogY29vcmRzQXJyYXkKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH07CgoJICAgICAgICAgICAgICAgIGlmICh0aGlzLmlzUG9seWdvbiAmJiBpc1JpbmcoY29vcmRzQXJyYXkpKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmIChyaW5nRGlyZWN0aW9uKGNvb3Jkc0FycmF5KSAhPT0gJ2NvdW50ZXJjbG9ja3dpc2UnKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZHNBcnJheS5yZXZlcnNlKCk7CgkgICAgICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgICAgIGZlYXR1cmUuZ2VvbWV0cnkgPSB7CgkgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAnUG9seWdvbicsCgkgICAgICAgICAgICAgICAgICAgICAgICBjb29yZGluYXRlczogW2Nvb3Jkc0FycmF5XQoJICAgICAgICAgICAgICAgICAgICB9OwoKCSAgICAgICAgICAgICAgICAgICAgcmV0dXJuIFtmZWF0dXJlXTsKCSAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIHJldHVybiBbZmVhdHVyZV07CgkgICAgICAgICAgICB9CgoJICAgICAgICAgICAgcmV0dXJuIFtdOwoJICAgICAgICB9CgkgICAgfQoKCSAgICBjbGFzcyBSZWxhdGlvbiBleHRlbmRzIE9zbU9iamVjdCB7CgkgICAgICAgIGNvbnN0cnVjdG9yKGlkLCByZWZFbGVtcykgewoJICAgICAgICAgICAgc3VwZXIoJ3JlbGF0aW9uJywgaWQsIHJlZkVsZW1zKTsKCSAgICAgICAgICAgIHRoaXMucmVsYXRpb25zID0gW107CgkgICAgICAgICAgICB0aGlzLm5vZGVzID0gW107CgkgICAgICAgICAgICB0aGlzLmJvdW5kcyA9IG51bGw7CgkgICAgICAgIH0KCgkgICAgICAgIHNldEJvdW5kcyhib3VuZHMpIHsKCSAgICAgICAgICAgIHRoaXMuYm91bmRzID0gYm91bmRzOwoJICAgICAgICB9CgoJICAgICAgICBhZGRNZW1iZXIobWVtYmVyKSB7CgkgICAgICAgICAgICBzd2l0Y2ggKG1lbWJlci50eXBlKSB7CgkgICAgICAgICAgICAgICAgLy8gc3VwZXIgcmVsYXRpb24sIG5lZWQgdG8gZG8gY29tYmluYXRpb24KCSAgICAgICAgICAgICAgICBjYXNlICdyZWxhdGlvbic6CgkgICAgICAgICAgICAgICAgICAgIGxldCBiaW5kZXIgPSBuZXcgTGF0ZUJpbmRlcih0aGlzLnJlbGF0aW9ucywgZnVuY3Rpb24gKGlkKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBsZXQgcmVsYXRpb24gPSB0aGlzLnJlZkVsZW1zLmdldChgcmVsYXRpb24vJHtpZH1gKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIGlmIChyZWxhdGlvbikgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJlbGF0aW9uLnJlZkNvdW50Kys7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgcmV0dXJuIHJlbGF0aW9uOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB9LCB0aGlzLCBbbWVtYmVyLnJlZl0pOwoJICAgICAgICAgICAgICAgICAgICB0aGlzLnJlbGF0aW9ucy5wdXNoKGJpbmRlcik7CgkgICAgICAgICAgICAgICAgICAgIHRoaXMucmVmRWxlbXMuYWRkQmluZGVyKGJpbmRlcik7CgkgICAgICAgICAgICAgICAgICAgIGJyZWFrOwoKCSAgICAgICAgICAgICAgICBjYXNlICd3YXknOgoJICAgICAgICAgICAgICAgICAgICBpZiAoIW1lbWJlci5yb2xlKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBtZW1iZXIucm9sZSA9ICcnOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGxldCB3YXlzID0gdGhpc1ttZW1iZXIucm9sZV07CgkgICAgICAgICAgICAgICAgICAgIGlmICghd2F5cykgewoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5cyA9IHRoaXNbbWVtYmVyLnJvbGVdID0gW107CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgaWYgKG1lbWJlci5nZW9tZXRyeSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgbGV0IHdheSA9IG5ldyBXYXkobWVtYmVyLnJlZiwgdGhpcy5yZWZFbGVtcyk7CgkgICAgICAgICAgICAgICAgICAgICAgICB3YXkuc2V0TGF0TG5nQXJyYXkobWVtYmVyLmdlb21ldHJ5KTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHdheS5yZWZDb3VudCsrOwoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5cy5wdXNoKHdheSk7CgkgICAgICAgICAgICAgICAgICAgIH0gZWxzZSBpZiAobWVtYmVyLm5vZGVzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBsZXQgd2F5ID0gbmV3IFdheShtZW1iZXIucmVmLCB0aGlzLnJlZkVsZW1zKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIGZvciAobGV0IG5pZCBvZiBtZW1iZXIubm9kZXMpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB3YXkuYWRkTm9kZVJlZihuaWQpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5LnJlZkNvdW50Kys7CgkgICAgICAgICAgICAgICAgICAgICAgICB3YXlzLnB1c2god2F5KTsKCSAgICAgICAgICAgICAgICAgICAgfSBlbHNlIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGxldCBiaW5kZXIgPSBuZXcgTGF0ZUJpbmRlcih3YXlzLCBmdW5jdGlvbiAoaWQpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBsZXQgd2F5ID0gdGhpcy5yZWZFbGVtcy5nZXQoYHdheS8ke2lkfWApOwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGlmICh3YXkpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgd2F5LnJlZkNvdW50Kys7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiB3YXk7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICAgICAgfSwgdGhpcywgW21lbWJlci5yZWZdKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHdheXMucHVzaChiaW5kZXIpOwoJICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5yZWZFbGVtcy5hZGRCaW5kZXIoYmluZGVyKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICBicmVhazsKCgkgICAgICAgICAgICAgICAgY2FzZSAnbm9kZSc6CgkgICAgICAgICAgICAgICAgICAgIGxldCBub2RlID0gbnVsbDsKCSAgICAgICAgICAgICAgICAgICAgaWYgKG1lbWJlci5sYXQgJiYgbWVtYmVyLmxvbikgewoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZSA9IG5ldyBOb2RlKG1lbWJlci5yZWYsIHRoaXMucmVmRWxlbXMpOwoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS5zZXRMYXRMbmcoeyBsb246IG1lbWJlci5sb24sIGxhdDogbWVtYmVyLmxhdCB9KTsKCSAgICAgICAgICAgICAgICAgICAgICAgIGlmIChtZW1iZXIudGFncykgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIG5vZGUuYWRkVGFncyhtZW1iZXIudGFncyk7CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgICAgICBmb3IgKGxldCBbaywgdl0gb2YgT2JqZWN0LmVudHJpZXMobWVtYmVyKSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGlmIChbJ2lkJywgJ3R5cGUnLCAnbGF0JywgJ2xvbiddLmluZGV4T2YoaykgPCAwKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIG5vZGUuYWRkUHJvcChrLCB2KTsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS5yZWZDb3VudCsrOwoJICAgICAgICAgICAgICAgICAgICAgICAgdGhpcy5ub2Rlcy5wdXNoKG5vZGUpOwoJICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgbGV0IGJpbmRlciA9IG5ldyBMYXRlQmluZGVyKHRoaXMubm9kZXMsIGZ1bmN0aW9uIChpZCkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGxldCBub2RlID0gdGhpcy5yZWZFbGVtcy5nZXQoYG5vZGUvJHtpZH1gKTsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBpZiAobm9kZSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBub2RlLnJlZkNvdW50Kys7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiBub2RlOwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgICAgIH0sIHRoaXMsIFttZW1iZXIucmVmXSk7CgkgICAgICAgICAgICAgICAgICAgICAgICB0aGlzLm5vZGVzLnB1c2goYmluZGVyKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIHRoaXMucmVmRWxlbXMuYWRkQmluZGVyKGJpbmRlcik7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgkgICAgICAgICAgICB9CgkgICAgICAgIH0KCgkgICAgICAgIHRvRmVhdHVyZUFycmF5KCkgewoJICAgICAgICAgICAgY29uc3QgY29uc3RydWN0U3RyaW5nR2VvbWV0cnkgPSAod3MpID0+IHsKCSAgICAgICAgICAgICAgICBsZXQgc3RyaW5ncyA9IHdzID8gd3MudG9TdHJpbmdzKCkgOiBbXTsKCSAgICAgICAgICAgICAgICBpZiAoc3RyaW5ncy5sZW5ndGggPiAwKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmIChzdHJpbmdzLmxlbmd0aCA9PT0gMSkgcmV0dXJuIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHR5cGU6ICdMaW5lU3RyaW5nJywKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBzdHJpbmdzWzBdCgkgICAgICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgICAgIHJldHVybiB7CgkgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAnTXVsdGlMaW5lU3RyaW5nJywKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBzdHJpbmdzCgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgcmV0dXJuIG51bGw7CgkgICAgICAgICAgICB9OwoKCSAgICAgICAgICAgIGNvbnN0IGNvbnN0cnVjdFBvbHlnb25HZW9tZXRyeSA9IChvd3MsIGl3cykgPT4gewoJICAgICAgICAgICAgICAgIGxldCBvdXRlclJpbmdzID0gb3dzID8gb3dzLnRvUmluZ3MoJ2NvdW50ZXJjbG9ja3dpc2UnKSA6IFtdLAoJICAgICAgICAgICAgICAgICAgICBpbm5lclJpbmdzID0gaXdzID8gaXdzLnRvUmluZ3MoJ2Nsb2Nrd2lzZScpIDogW107CgoJICAgICAgICAgICAgICAgIGlmIChvdXRlclJpbmdzLmxlbmd0aCA+IDApIHsKCSAgICAgICAgICAgICAgICAgICAgbGV0IGNvbXBvc2l0UG9seW9ucyA9IFtdOwoKCSAgICAgICAgICAgICAgICAgICAgbGV0IHJpbmcgPSBudWxsOwoJICAgICAgICAgICAgICAgICAgICBmb3IgKHJpbmcgb2Ygb3V0ZXJSaW5ncykKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvbXBvc2l0UG9seW9ucy5wdXNoKFtyaW5nXSk7CgoJICAgICAgICAgICAgICAgICAgICAvLyBsaW5rIGlubmVyIHBvbHlnb25zIHRvIG91dGVyIGNvbnRhaW5lcnMKCSAgICAgICAgICAgICAgICAgICAgd2hpbGUgKHJpbmcgPSBpbm5lclJpbmdzLnNoaWZ0KCkpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIGZvciAobGV0IGlkeCBpbiBvdXRlclJpbmdzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgaWYgKHB0SW5zaWRlUG9seWdvbihmaXJzdChyaW5nKSwgb3V0ZXJSaW5nc1tpZHhdKSkgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb21wb3NpdFBvbHlvbnNbaWR4XS5wdXNoKHJpbmcpOwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBicmVhazsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgICAgIC8vIGNvbnN0cnVjdCB0aGUgUG9seWdvbi9NdWx0aVBvbHlnb24gZ2VvbWV0cnkKCSAgICAgICAgICAgICAgICAgICAgaWYgKGNvbXBvc2l0UG9seW9ucy5sZW5ndGggPT09IDEpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgdHlwZTogJ1BvbHlnb24nLAoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBjb21wb3NpdFBvbHlvbnNbMF0KCSAgICAgICAgICAgICAgICAgICAgICAgIH07CgkgICAgICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgICAgIHJldHVybiB7CgkgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiAnTXVsdGlQb2x5Z29uJywKCSAgICAgICAgICAgICAgICAgICAgICAgIGNvb3JkaW5hdGVzOiBjb21wb3NpdFBvbHlvbnMKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgcmV0dXJuIG51bGw7CgkgICAgICAgICAgICB9OwoKCSAgICAgICAgICAgIGxldCBwb2x5Z29uRmVhdHVyZXMgPSBbXSwgc3RyaW5nRmVhdHVyZXMgPSBbXSwgcG9pbnRGZWF0dXJlcyA9IFtdOwoJICAgICAgICAgICAgY29uc3Qgd2F5c0ZpZWxkTmFtZXMgPSBbJ291dGVyJywgJ2lubmVyJywgJyddOwoJICAgICAgICAgICAgLy8gbmVlZCB0byBkbyBjb21iaW5hdGlvbiB3aGVuIHRoZXJlJ3JlIG5lc3RlZCByZWxhdGlvbnMKCSAgICAgICAgICAgIGZvciAobGV0IHJlbGF0aW9uIG9mIHRoaXMucmVsYXRpb25zKSB7CgkgICAgICAgICAgICAgICAgaWYgKHJlbGF0aW9uKSB7CgkgICAgICAgICAgICAgICAgICAgIGZvciAobGV0IGZpZWxkTmFtZSBvZiB3YXlzRmllbGROYW1lcykgewoJICAgICAgICAgICAgICAgICAgICAgICAgbGV0IHdheXMgPSByZWxhdGlvbltmaWVsZE5hbWVdOwoJICAgICAgICAgICAgICAgICAgICAgICAgaWYgKHdheXMpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBsZXQgdGhpc1dheXMgPSB0aGlzW2ZpZWxkTmFtZV07CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgaWYgKHRoaXNXYXlzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFtdLnNwbGljZS5hcHBseSh0aGlzV2F5cywgW3RoaXNXYXlzLmxlbmd0aCwgMF0uY29uY2F0KHdheXMpKTsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB0aGlzW2ZpZWxkTmFtZV0gPSB3YXlzOwoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCgkgICAgICAgICAgICBmb3IgKGxldCBmaWVsZE5hbWUgb2Ygd2F5c0ZpZWxkTmFtZXMpIHsKCSAgICAgICAgICAgICAgICBsZXQgd2F5cyA9IHRoaXNbZmllbGROYW1lXTsKCSAgICAgICAgICAgICAgICBpZiAod2F5cykgewoJICAgICAgICAgICAgICAgICAgICB0aGlzW2ZpZWxkTmFtZV0gPSBuZXcgV2F5Q29sbGVjdGlvbigpOwoJICAgICAgICAgICAgICAgICAgICBmb3IgKGxldCB3YXkgb2Ygd2F5cykgewoJICAgICAgICAgICAgICAgICAgICAgICAgdGhpc1tmaWVsZE5hbWVdLmFkZFdheSh3YXkpOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoKCSAgICAgICAgICAgIGxldCBnZW9tZXRyeSA9IG51bGw7CgoJICAgICAgICAgICAgbGV0IGZlYXR1cmUgPSB7CgkgICAgICAgICAgICAgICAgdHlwZTogJ0ZlYXR1cmUnLAoJICAgICAgICAgICAgICAgIGlkOiB0aGlzLmdldENvbXBvc2l0ZUlkKCksCgkgICAgICAgICAgICAgICAgYmJveDogdGhpcy5ib3VuZHMsCgkgICAgICAgICAgICAgICAgcHJvcGVydGllczogdGhpcy5nZXRQcm9wcygpCgkgICAgICAgICAgICB9OwoKCSAgICAgICAgICAgIGlmICghdGhpcy5ib3VuZHMpIHsKCSAgICAgICAgICAgICAgICBkZWxldGUgZmVhdHVyZS5iYm94OwoJICAgICAgICAgICAgfQoKCSAgICAgICAgICAgIGlmICh0aGlzLm91dGVyKSB7CgkgICAgICAgICAgICAgICAgZ2VvbWV0cnkgPSBjb25zdHJ1Y3RQb2x5Z29uR2VvbWV0cnkodGhpcy5vdXRlciwgdGhpcy5pbm5lcik7CgkgICAgICAgICAgICAgICAgaWYgKGdlb21ldHJ5KSB7CgkgICAgICAgICAgICAgICAgICAgIGZlYXR1cmUuZ2VvbWV0cnkgPSBnZW9tZXRyeTsKCSAgICAgICAgICAgICAgICAgICAgcG9seWdvbkZlYXR1cmVzLnB1c2goZmVhdHVyZSk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgZWxzZSBpZiAodGhpc1snJ10pIHsKCSAgICAgICAgICAgICAgICBnZW9tZXRyeSA9IGNvbnN0cnVjdFN0cmluZ0dlb21ldHJ5KHRoaXNbJyddKTsKCSAgICAgICAgICAgICAgICBpZiAoZ2VvbWV0cnkpIHsKCSAgICAgICAgICAgICAgICAgICAgZmVhdHVyZS5nZW9tZXRyeSA9IGdlb21ldHJ5OwoJICAgICAgICAgICAgICAgICAgICBzdHJpbmdGZWF0dXJlcy5wdXNoKGZlYXR1cmUpOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCgkgICAgICAgICAgICBmb3IgKGxldCBub2RlIG9mIHRoaXMubm9kZXMpIHsKCSAgICAgICAgICAgICAgICBwb2ludEZlYXR1cmVzID0gcG9pbnRGZWF0dXJlcy5jb25jYXQobm9kZS50b0ZlYXR1cmVBcnJheSgpKTsKCSAgICAgICAgICAgIH0KCgkgICAgICAgICAgICByZXR1cm4gcG9seWdvbkZlYXR1cmVzLmNvbmNhdChzdHJpbmdGZWF0dXJlcykuY29uY2F0KHBvaW50RmVhdHVyZXMpOwoJICAgICAgICB9CgkgICAgfQoKCSAgICByZXR1cm4geyBOb2RlLC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sKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9CgkgICAgICAgICAgICB0aGlzLmV2dExpc3RlbmVycyA9IHt9OwoJICAgICAgICB9CgoJICAgICAgICBwYXJzZSh4bWwsIHBhcmVudCwgZGlyKSB7CgkgICAgICAgICAgICBkaXIgPSBkaXIgPyBkaXIgKyAnLicgOiAnJzsKCSAgICAgICAgICAgIGxldCBub2RlUmVnRXggPSAvPChbXiA+XC9dKykoLio/KT4vbWcsIG5vZGVNYXRjaCA9IG51bGwsIG5vZGVzID0gW107CgkgICAgICAgICAgICB3aGlsZSAobm9kZU1hdGNoID0gbm9kZVJlZ0V4LmV4ZWMoeG1sKSkgewoJICAgICAgICAgICAgICAgIGxldCB0YWcgPSBub2RlTWF0Y2hbMV0sIG5vZGUgPSB7ICR0YWc6IHRhZyB9LCBmdWxsVGFnID0gZGlyICsgdGFnOwoKCSAgICAgICAgICAgICAgICBsZXQgYXR0clRleHQgPSBub2RlTWF0Y2hbMl0udHJpbSgpLCBjbG9zZWQgPSBmYWxzZTsKCSAgICAgICAgICAgICAgICBpZiAoYXR0clRleHQuZW5kc1dpdGgoJy8nKSB8fCB0YWcuc3RhcnRzV2l0aCgnPycpIHx8IHRhZy5zdGFydHNXaXRoKCchJykpIHsKCSAgICAgICAgICAgICAgICAgICAgY2xvc2VkID0gdHJ1ZTsKCSAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIGxldCBhdHRSZWdFeDEgPSAvKFteIF0rPyk9IiguKz8pIi9nLCBhdHRSZWdFeDIgPSAvKFteIF0rPyk9JyguKz8pJy9nOwoJICAgICAgICAgICAgICAgIGxldCBhdHRNYXRjaCA9IG51bGwsIGhhc0F0dHJzID0gZmFsc2U7CgkgICAgICAgICAgICAgICAgd2hpbGUgKGF0dE1hdGNoID0gYXR0UmVnRXgxLmV4ZWMoYXR0clRleHQpKSB7CgkgICAgICAgICAgICAgICAgICAgIGhhc0F0dHJzID0gdHJ1ZTsKCSAgICAgICAgICAgICAgICAgICAgbm9kZVthdHRNYXRjaFsxXV0gPSBhdHRNYXRjaFsyXTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgaWYgKCFoYXNBdHRycykKCSAgICAgICAgICAgICAgICAgICAgd2hpbGUgKGF0dE1hdGNoID0gYXR0UmVnRXgyLmV4ZWMoYXR0clRleHQpKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBoYXNBdHRycyA9IHRydWU7CgkgICAgICAgICAgICAgICAgICAgICAgICBub2RlW2F0dE1hdGNoWzFdXSA9IGF0dE1hdGNoWzJdOwoJICAgICAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIGlmICghaGFzQXR0cnMgJiYgYXR0clRleHQgIT09ICcnKSB7CgkgICAgICAgICAgICAgICAgICAgIG5vZGUudGV4dCA9IGF0dHJUZXh0OwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICBpZiAodGhpcy5wcm9ncmVzc2l2ZSkgewoJICAgICAgICAgICAgICAgICAgICB0aGlzLmVtaXQoYDwke2Z1bGxUYWd9PmAsIG5vZGUsIHBhcmVudCk7CgkgICAgICAgICAgICAgICAgfQoKCSAgICAgICAgICAgICAgICBpZiAoIWNsb3NlZCkgewoJICAgICAgICAgICAgICAgICAgICBsZXQgaW5uZXJSZWdFeCA9IG5ldyBSZWdFeHAoYChbXl0rPyk8XC8ke3RhZ30+YCwgJ2cnKTsKCSAgICAgICAgICAgICAgICAgICAgaW5uZXJSZWdFeC5sYXN0SW5kZXggPSBub2RlUmVnRXgubGFzdEluZGV4OwoJICAgICAgICAgICAgICAgICAgICBsZXQgaW5uZXJNYXRjaCA9IGlubmVyUmVnRXguZXhlYyh4bWwpOwoJICAgICAgICAgICAgICAgICAgICBpZiAoaW5uZXJNYXRjaCAmJiBpbm5lck1hdGNoWzFdKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBub2RlUmVnRXgubGFzdEluZGV4ID0gaW5uZXJSZWdFeC5sYXN0SW5kZXg7CgkgICAgICAgICAgICAgICAgICAgICAgICBsZXQgaW5uZXJOb2RlcyA9IHRoaXMucGFyc2UoaW5uZXJNYXRjaFsxXSwgbm9kZSwgZnVsbFRhZyk7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAoaW5uZXJOb2Rlcy5sZW5ndGggPiAwKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS4kaW5uZXJOb2RlcyA9IGlubmVyTm9kZXM7CgkgICAgICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIG5vZGUuJGlubmVyVGV4dCA9IGlubmVyTWF0Y2hbMV07CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgaWYgKHRoaXMucXVlcnlQYXJlbnQgJiYgcGFyZW50KSB7CgkgICAgICAgICAgICAgICAgICAgIHRoaXMucGFyZW50TWFwLnNldChub2RlLCBwYXJlbnQpOwoJICAgICAgICAgICAgICAgIH0KCgkgICAgICAgICAgICAgICAgaWYgKHRoaXMucHJvZ3Jlc3NpdmUpIHsKCSAgICAgICAgICAgICAgICAgICAgdGhpcy5lbWl0KGA8LyR7ZnVsbFRhZ30+YCwgbm9kZSwgcGFyZW50KTsKCSAgICAgICAgICAgICAgICB9CgoJICAgICAgICAgICAgICAgIG5vZGVzLnB1c2gobm9kZSk7CgkgICAgICAgICAgICB9CgoJICAgICAgICAgICAgcmV0dXJuIG5vZGVzOwoJICAgICAgICB9CgoJICAgICAgICBnZXRQYXJlbnQobm9kZSkgewoJICAgICAgICAgICAgaWYgKHRoaXMucXVlcnlQYXJlbnQpIHsKCSAgICAgICAgICAgICAgICByZXR1cm4gdGhpcy5wYXJlbnRNYXAuZ2V0KG5vZGUpOwoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmV0dXJuIG51bGw7CgkgICAgICAgIH0KCg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ICAgICAgICAgfQoJICAgICAgICB9CgoJICAgICAgICByZW1vdmVMaXN0ZW5lcihldnQsIGZ1bmMpIHsKCSAgICAgICAgICAgIGlmIChjb25kaXRpb25lZChldnQpKSB7CgkgICAgICAgICAgICAgICAgZXZ0ID0gcGFyc2VFdmVudChldnQpOwoJICAgICAgICAgICAgICAgIGV2dCA9IGV2dC5ldnQ7CgkgICAgICAgICAgICB9CgkgICAgICAgICAgICB0aGlzLiNyZW1vdmVMaXN0ZW5lcihldnQsIGZ1bmMpOwoJICAgICAgICB9CgoJICAgICAgICBlbWl0KGV2dCwgLi4uYXJncykgewoJICAgICAgICAgICAgbGV0IGZ1bmNzID0gdGhpcy5ldnRMaXN0ZW5lcnNbZXZ0XTsKCSAgICAgICAgICAgIGlmIChmdW5jcykgewoJICAgICAgICAgICAgICAgIGZvciAobGV0IGZ1bmMgb2YgZnVuY3MpIHsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGZ1bmMuY29uZGl0aW9uKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAoZnVuYy5jb25kaXRpb24uYXBwbHkobnVsbCwgYXJncykgPT09IHRydWUpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICBmdW5jLmFwcGx5KG51bGwsIGFyZ3MpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgZnVuYy5hcHBseShudWxsLCBhcmdzKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgfQoKCSAgICAgICAgb24oZXZ0LCBmdW5jKSB7CgkgICAgICAgICAgICB0aGlzLmFkZExpc3RlbmVyKGV2dCwgZnVuYyk7CgkgICAgICAgIH0KCgkgICAgICAgIG9mZihldnQsIGZ1bmMpIHsKCSAgICAgICAgICAgIHRoaXMucmVtb3ZlTGlzdGVuZXIoZXZ0LCB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XR1cm4gJ3htbCc7CgkgICAgICAgIH0KCSAgICAgICAgaWYgKG9zbS50cmltKCkuc3RhcnRzV2l0aCgneycpKSB7CgkgICAgICAgICAgICByZXR1cm4gJ2pzb24tcmF3JzsKCSAgICAgICAgfQoJICAgICAgICByZXR1cm4gJ2ludmFsaWQnOwoJICAgIH07CgoJICAgIGxldCBmb3JtYXQgPSBkZXRlY3RGb3JtYXQob3NtKTsKCgkgICAgbGV0IHJlZkVsZW1lbnRzID0gbmV3IFJlZkVsZW1lbnRzKCksIGZlYXR1cmVBcnJheSA9IFtdOwoKCSAgICBjb25zdCBhbmFseXplRmVhdHVyZXNGcm9tSnNvbiA9IG9zbSA9PiB7CgkgICAgICAgIGZvciAobGV0IGVsZW0gb2Ygb3NtLmVsZW1lbnRzKSB7CgkgICAgICAgICAgICBzd2l0Y2ggKGVsZW0udHlwZSkgewoJICAgICAgICAgICAgICAgIGNhc2UgJ25vZGUnOgoJICAgICAgICAgICAgICAgICAgICBsZXQgbm9kZSA9IG5ldyBOb2RlKGVsZW0uaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGVsZW0udGFncykgewoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZS5hZGRUYWdzKGVsZW0udGFncyk7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgbm9kZS5hZGRQcm9wcyhwdXJnZVByb3BzKGVsZW0sIFsnaWQnLCAndHlwZScsICd0YWdzJywgJ2xhdCcsICdsb24nXSkpOwoJICAgICAgICAgICAgICAgICAgICBub2RlLnNldExhdExuZyhlbGVtKTsKCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgoJICAgICAgICAgICAgICAgIGNhc2UgJ3dheSc6CgkgICAgICAgICAgICAgICAgICAgIGxldCB3YXkgPSBuZXcgV2F5KGVsZW0uaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGVsZW0udGFncykgewoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5LmFkZFRhZ3MoZWxlbS50YWdzKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB3YXkuYWRkUHJvcHMocHVyZ2VQcm9wcyhlbGVtLCBbJ2lkJywgJ3R5cGUnLCAndGFncycsICdub2RlcycsICdnZW9tZXRyeSddKSk7CgkgICAgICAgICAgICAgICAgICAgIGlmIChlbGVtLm5vZGVzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBmb3IgKGxldCBuIG9mIGVsZW0ubm9kZXMpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICB3YXkuYWRkTm9kZVJlZihuKTsKCSAgICAgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgfSBlbHNlIGlmIChlbGVtLmdlb21ldHJ5KSB7CgkgICAgICAgICAgICAgICAgICAgICAgICB3YXkuc2V0TGF0TG5nQXJyYXkoZWxlbS5nZW9tZXRyeSk7CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgYnJlYWs7CgoJICAgICAgICAgICAgICAgIGNhc2UgJ3JlbGF0aW9uJzoKCSAgICAgICAgICAgICAgICAgICAgbGV0IHJlbGF0aW9uID0gbmV3IFJlbGF0aW9uKGVsZW0uaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGVsZW0uYm91bmRzKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICByZWxhdGlvbi5zZXRCb3VuZHMoW3BhcnNlRmxvYXQoZWxlbS5ib3VuZHMubWlubG9uKSwgcGFyc2VGbG9hdChlbGVtLmJvdW5kcy5taW5sYXQpLCBwYXJzZUZsb2F0KGVsZW0uYm91bmRzLm1heGxvbiksIHBhcnNlRmxvYXQoZWxlbS5ib3VuZHMubWF4bGF0KV0pOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGlmIChlbGVtLnRhZ3MpIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIHJlbGF0aW9uLmFkZFRhZ3MoZWxlbS50YWdzKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICByZWxhdGlvbi5hZGRQcm9wcyhwdXJnZVByb3BzKGVsZW0sIFsnaWQnLCAndHlwZScsICd0YWdzJywgJ2JvdW5kcycsICdtZW1iZXJzJ10pKTsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGVsZW0ubWVtYmVycykgewoJICAgICAgICAgICAgICAgICAgICAgICAgZm9yIChsZXQgbWVtYmVyIG9mIGVsZW0ubWVtYmVycykgewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJlbGF0aW9uLmFkZE1lbWJlcihtZW1iZXIpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGJyZWFrOwoJICAgICAgICAgICAgfQoJICAgICAgICB9CgkgICAgfTsKCgkgICAgY29uc3QgYW5hbHl6ZUZlYXR1cmVzRnJvbVhtbCA9IG9zbSA9PiB7CgkgICAgICAgIGNvbnN0IHhtbFBhcnNlciA9IG5ldyBYbWxQYXJzZXIoeyBwcm9ncmVzc2l2ZTogdHJ1ZSB9KTsKCgkgICAgICAgIHhtbFBhcnNlci5vbignPC9vc20ubm9kZT4nLCBub2RlID0+IHsKCSAgICAgICAgICAgIGxldCBuZCA9IG5ldyBOb2RlKG5vZGUuaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgIGZvciAobGV0IFtrLCB2XSBvZiBPYmplY3QuZW50cmllcyhub2RlKSkKCSAgICAgICAgICAgICAgICBpZiAoIWsuc3RhcnRzV2l0aCgnJCcpICYmIFsnaWQnLCAnbG9uJywgJ2xhdCddLmluZGV4T2YoaykgPCAwKSB7CgkgICAgICAgICAgICAgICAgICAgIG5kLmFkZFByb3Aoaywgdik7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgbmQuc2V0TGF0TG5nKG5vZGUpOwoJICAgICAgICAgICAgaWYgKG5vZGUuJGlubmVyTm9kZXMpIHsKCSAgICAgICAgICAgICAgICBmb3IgKGxldCBpbmQgb2Ygbm9kZS4kaW5uZXJOb2RlcykgewoJICAgICAgICAgICAgICAgICAgICBpZiAoaW5kLiR0YWcgPT09ICd0YWcnKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBuZC5hZGRUYWcoaW5kLmssIGluZC52KTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgfSk7CgoJICAgICAgICB4bWxQYXJzZXIub24oJzwvb3NtLndheT4nLCBub2RlID0+IHsKCSAgICAgICAgICAgIGxldCB3YXkgPSBuZXcgV2F5KG5vZGUuaWQsIHJlZkVsZW1lbnRzKTsKCSAgICAgICAgICAgIGZvciAobGV0IFtrLCB2XSBvZiBPYmplY3QuZW50cmllcyhub2RlKSkgewoJICAgICAgICAgICAgICAgIGlmICghay5zdGFydHNXaXRoKCckJykgJiYgWydpZCddLmluZGV4T2YoaykgPCAwKSB7CgkgICAgICAgICAgICAgICAgICAgIHdheS5hZGRQcm9wKGssIHYpOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIGlmIChub2RlLiRpbm5lck5vZGVzKSB7CgkgICAgICAgICAgICAgICAgZm9yIChsZXQgaW5kIG9mIG5vZGUuJGlubmVyTm9kZXMpIHsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGluZC4kdGFnID09PSAnbmQnKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBpZiAoaW5kLmxvbiAmJiBpbmQubGF0KSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgd2F5LmFkZExhdExuZyhpbmQpOwoJICAgICAgICAgICAgICAgICAgICAgICAgfSBlbHNlIGlmIChpbmQucmVmKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAgICAgd2F5LmFkZE5vZGVSZWYoaW5kLnJlZik7CgkgICAgICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIH0gZWxzZSBpZiAoaW5kLiR0YWcgPT09ICd0YWcnKQoJICAgICAgICAgICAgICAgICAgICAgICAgd2F5LmFkZFRhZyhpbmQuaywgaW5kLnYpOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgfSk7CgoJICAgICAgICB4bWxQYXJzZXIub24oJzxvc20ucmVsYXRpb24+Jywgbm9kZSA9PiB7CgkgICAgICAgICAgICBuZXcgUmVsYXRpb24obm9kZS5pZCwgcmVmRWxlbWVudHMpOwoJICAgICAgICB9KTsKCgkgICAgICAgIHhtbFBhcnNlci5vbignPC9vc20ucmVsYXRpb24ubWVtYmVyPicsIChub2RlLCBwYXJlbnQpID0+IHsKCSAgICAgICAgICAgIGxldCByZWxhdGlvbiA9IHJlZkVsZW1lbnRzLmdldChgcmVsYXRpb24vJHtwYXJlbnQuaWR9YCk7CgkgICAgICAgICAgICBsZXQgbWVtYmVyID0gewoJICAgICAgICAgICAgICAgIHR5cGU6IG5vZGUudHlwZSwKCSAgICAgICAgICAgICAgICByb2xlOiBub2RlLnJvbGUgPyBub2RlLnJvbGUgOiAnJywKCSAgICAgICAgICAgICAgICByZWY6IG5vZGUucmVmCgkgICAgICAgICAgICB9OwoJICAgICAgICAgICAgaWYgKG5vZGUubGF0ICYmIG5vZGUubG9uKSB7CgkgICAgICAgICAgICAgICAgbWVtYmVyLmxhdCA9IG5vZGUubGF0LCBtZW1iZXIubG9uID0gbm9kZS5sb24sIG1lbWJlci50YWdzID0ge307CgkgICAgICAgICAgICAgICAgZm9yIChsZXQgW2ssIHZdIG9mIE9iamVjdC5lbnRyaWVzKG5vZGUpKSB7CgkgICAgICAgICAgICAgICAgICAgIGlmICghay5zdGFydHNXaXRoKCckJykgJiYgWyd0eXBlJywgJ2xhdCcsICdsb24nXS5pbmRleE9mKGspIDwgMCkgewoJICAgICAgICAgICAgICAgICAgICAgICAgbWVtYmVyW2tdID0gdjsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIGlmIChub2RlLiRpbm5lck5vZGVzKSB7CgkgICAgICAgICAgICAgICAgbGV0IGdlb21ldHJ5ID0gW107CgkgICAgICAgICAgICAgICAgbGV0IG5vZGVzID0gW107CgkgICAgICAgICAgICAgICAgZm9yIChsZXQgaW5kIG9mIG5vZGUuJGlubmVyTm9kZXMpIHsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGluZC5sYXQgJiYgaW5kLmxvbikgewoJICAgICAgICAgICAgICAgICAgICAgICAgZ2VvbWV0cnkucHVzaChpbmQpOwoJICAgICAgICAgICAgICAgICAgICB9IGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgbm9kZXMucHVzaChpbmQucmVmKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICBpZiAoZ2VvbWV0cnkubGVuZ3RoID4gMCkgewoJICAgICAgICAgICAgICAgICAgICBtZW1iZXIuZ2VvbWV0cnkgPSBnZW9tZXRyeTsKCSAgICAgICAgICAgICAgICB9IGVsc2UgaWYgKG5vZGVzLmxlbmd0aCA+IDApIHsKCSAgICAgICAgICAgICAgICAgICAgbWVtYmVyLm5vZGVzID0gbm9kZXM7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgcmVsYXRpb24uYWRkTWVtYmVyKG1lbWJlcik7CgkgICAgICAgIH0pOwoKCSAgICAgICAgeG1sUGFyc2VyLm9uKCc8L29zbS5yZWxhdGlvbi5ib3VuZHM+JywgKG5vZGUsIHBhcmVudCkgPT4gewoJICAgICAgICAgICAgcmVmRWxlbWVudHMuZ2V0KGByZWxhdGlvbi8ke3BhcmVudC5pZH1gKS5zZXRCb3VuZHMoW3BhcnNlRmxvYXQobm9kZS5taW5sb24pLCBwYXJzZUZsb2F0KG5vZGUubWlubGF0KSwgcGFyc2VGbG9hdChub2RlLm1heGxvbiksIHBhcnNlRmxvYXQobm9kZS5tYXhsYXQpXSk7CgkgICAgICAgIH0pOwoKCSAgICAgICAgeG1sUGFyc2VyLm9uKCc8L29zbS5yZWxhdGlvbi50YWc+JywgKG5vZGUsIHBhcmVudCkgPT4gewoJICAgICAgICAgICAgcmVmRWxlbWVudHMuZ2V0KGByZWxhdGlvbi8ke3BhcmVudC5pZH1gKS5hZGRUYWcobm9kZS5rLCBub2RlLnYpOwoJICAgICAgICB9KTsKCgkgICAgICAgIHhtbFBhcnNlci5wYXJzZShvc20pOwoJICAgIH07CgoJICAgIGlmIChmb3JtYXQgPT09ICdqc29uLXJhdycpIHsKCSAgICAgICAgb3NtID0gSlNPTi5wYXJzZShvc20pOwoJICAgICAgICBpZiAob3NtLmVsZW1lbnRzKSB7CgkgICAgICAgICAgICBmb3JtYXQgPSAnanNvbic7CgkgICAgICAgIH0gZWxzZSB7CgkgICAgICAgICAgICBmb3JtYXQgPSAnaW52YWxpZCc7CgkgICAgICAgIH0KCSAgICB9CgoJICAgIGlmIChmb3JtYXQgPT09ICdqc29uJykgewoJICAgICAgICBhbmFseXplRmVhdHVyZXNGcm9tSnNvbihvc20pOwoJICAgIH0gZWxzZSBpZiAoZm9ybWF0ID09PSAneG1sJykgewoJICAgICAgICBhbmFseXplRmVhdHVyZXNGcm9tWG1sKG9zbSk7CgkgICAgfQoKCSAgICByZWZFbGVtZW50cy5iaW5kQWxsKCk7CgoJICAgIGZvciAobGV0IHYgb2YgcmVmRWxlbWVudHMudmFsdWVzKCkpIHsKCSAgICAgICAgaWYgKHYucmVmQ291bnQgPD0gMCB8fCAodi5oYXNUYWcgJiYgcmVuZGVyVGFnZ2VkICYmICEodiBpbnN0YW5jZW9mIFdheSAmJiBleGNsdWRlV2F5KSkpIHsKCSAgICAgICAgICAgIGxldCBm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RhOwoJICAgICAgICB0aGlzLl9mb3JtYXQgPSBmb3JtYXQ7CgkgICAgICAgIHRoaXMuX29wdGlvbnMgPSBvcHRpb25zOwoJICAgICAgICBjb25zdCBjb252ZXJ0ZXJzID0gewoJICAgICAgICAgICAgJ3RvcG9qc29uJzogdGhpcy5sb2FkVG9wb0pzb24sCgkgICAgICAgICAgICAnb3NtJzogdGhpcy5sb2FkT3NtLAoJICAgICAgICAgICAgJ2ttbCc6IHRoaXMubG9hZFhtbCwKCSAgICAgICAgICAgICdncHgnOiB0aGlzLmxvYWRYbWwsCgkgICAgICAgICAgICAndGN4JzogdGhpcy5sb2FkWG1sLAoJICAgICAgICAgICAgJ2Nzdic6IHRoaXMubG9hZENzdiwKCSAgICAgICAgICAgICd0c3YnOiB0aGlzLmxvYWRDc3YsCgkgICAgICAgICAgICAncG9seWxpbmUnOiB0aGlzLmxvYWRQb2x5bGluZQoJICAgICAgICB9OwoJICAgICAgICB0aGlzLl9jb252ZXJzaW9uRm4gPSBjb252ZXJ0ZXJzW2Zvcm1hdF07CgkgICAgfQoJICAgIGFzeW5jIGNvbnZlcnQoKSB7CgkgICAgICAgIGlmICghdGhpcy5fY29udmVyc2lvbkZuKSB7CgkgICAgICAgICAgICByZXR1cm4gbmV3IFByb21pc2UoKF8sIHJlaikgPT4gcmVqKGBObyBjb252ZXJ0ZXIgZXhpc3RzIGZvciAke3RoaXMuX2Zvcm1hdH1gKSk7CgkgICAgICAgIH0KCSAgICAgICAgZWxzZSB7CgkgICAgICAgICAgICByZXR1cm4gdGhpcy5fY29udmVyc2lvbkZuKCk7CgkgICAgICAgIH0KCSAgICB9CgkgICAgLyoqCgkgICAgICogTG9hZCB0aGUgWE1MIGRhdGEgYXMgR2VvSlNPTgoJICAgICAqIEByZXR1cm5zIEEgcHJvbWlzZSByZXNvbHZpbmcgdG8gYSBHZW9KU09OIEZlYXR1cmVDb2xsZWN0aW9uCgkgICAgICovCgkgICAgYXN5bmMgbG9hZFhtbCgpIHsKC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sKCSAgICAgICAgICAgICAgICBpZiAoZXJyKSB7CgkgICAgICAgICAgICAgICAgICAgIHJlamVjdChlcnIpOwoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICBlbHNlIHsKCSAgICAgICAgICAgICAgICAgICAgcmVzb2x2ZShkYXRhKTsKCSAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICB9KTsKCSAgICAgICAgfSk7CgkgICAgICAgIHJldHVybiBnZW9qc29uOwoJICAgIH0KCSAgICAvKioKCSAgICAgKiBMb2FkcyBUb3BvSlNPTiBkYXRhIGFuZCBjb252ZXJ0cyBpdCBpbnRvIGEgR2VvSlNPTiBGZWF0dXJlQ29sbGVjdGlvbgoJICAgICAqIEByZXR1cm5zIEEgUHJvbWlzZSB0aGF0IHJlc29sdmVzIHdpdGggdGhlIEdlb0pTT04gRmVhdHVyZUNvbGxlY3Rpb24uCgkgICAgICovCgkgICAgYXN5bmMgbG9hZFRvcG9Kc29uKCkgewoJICAgICAgICBsZXQgdG9wb0pzb25EYXRhID0ge307CgkgICAgICAgIHRyeSB7CgkgICAgICAgICAgICB0b3BvSnNvbkRhdGEgPSBKU09OLnBhcnNlKHRoaXMuX3Jhd0RhdGEpOwoJICAgICAgICB9CgkgICAgICAgIGNhdGNoIChlKSB7CgkgICAgICAgICAgICB0aHJvdyAiSW52YWxpZCBUb3BvSnNvbiI7CgkgICAgICAgIH0KCSAgICAgICAgLy8gQ29udmVydCB0aGUgZGF0YQoJICAgICAgICBsZXQgcmVzdWx0ID0gdGhpcy5ibGFua0dlb0pTT04oKTsKCSAgICAgICAgaWYgKHRvcG9Kc29uRGF0YS50eXBlID09PSAiVG9wb2xvZ3kiICYmIHRvcG9Kc29uRGF0YS5vYmplY3RzICE9PSB1bmRlZmluZWQpIHsKCSAgICAgICAgICAgIHJlc3VsdCA9IHsKCSAgICAgICAgICAgICAgICB0eXBlOiAiRmVhdHVyZUNvbGxlY3Rpb24iLAoJICAgICAgICAgICAgICAgIGZlYX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mVzb2x2ZSwgcmVqZWN0KSA9PiB7CgkgICAgICAgICAgICB0cnkgewoJICAgICAgICAgICAgICAgIGNvbnN0IGxpbmVTdHJpbmcgPSBwb2x5bGluZUV4cG9ydHMudG9HZW9KU09OKHRoaXMuX3Jhd0RhdGEsIG9wdGlvbnMucHJlY2lzaW9uKTsKCSAgICAgICAgICAgICAgICBsZXQgZ2VvbWV0cnkgPSBsaW5lU3RyaW5nOwoJICAgICAgICAgICAgICAgIGlmIChvcHRpb25zLnR5cGUgPT09ICdwb2ludCcpIHsKCSAgICAgICAgICAgICAgICAgICAgaWYgKGxpbmVTdHJpbmcuY29vcmRpbmF0ZXMubGVuZ3RoID09PSAxKSB7CgkgICAgICAgICAgICAgICAgICAgICAgICAvLyBNYWtlIGl0IGEgcG9pbnQKCSAgICAgICAgICAgICAgICAgICAgICAgIGdlb21ldHJ5ID0gewoJICAgICAgICAgICAgICAgICAgICAgICAgICAgICd0eXBlJzogJ1BvaW50JywKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAnY29vcmRpbmF0ZXMnOiBsaW5lU3RyaW5nLmNvb3JkaW5hdGVzWzBdCgkgICAgICAgICAgICAgICAgICAgICAgICB9OwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgICAgIGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAgICAgY29uc29sZS53YXJuKCdDYW5ub3QgY29udmVydCBwb2x5bGluZSB0byAnICsgb3B0aW9ucy50eXBlKTsKCSAgICAgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICBlbHNlIGlmIChvcHRpb25zLnR5cGUgPT09ICdwb2x5Z29uJykgewoJICAgICAgICAgICAgICAgICAgICBpZiAobGluZVN0cmluZy5jb29yZGluYXRlc1swXVswXSA9PT0gbGluZVN0cmluZy5jb29yZGluYXRlc1tsaW5lU3RyaW5nLmNvb3JkaW5hdGVzLmxlbmd0aCAtIDFdWzBdICYmCgkgICAgICAgICAgICAgICAgICAgICAgICBsaW5lU3RyaW5nLmNvb3JkaW5hdGVzWzBdWzFdID09PSBsaW5lU3RyaW5nLmNvb3JkaW5hdGVzW2xpbmVTdHJpbmcuY29vcmRpbmF0ZXMubGVuZ3RoIC0gMV1bMV0pIHsKCSAgICAgICAgICAgICAgICAgICAgICAgIC8vIE1ha2UgaXQgYSBwb2x5Z29uCgkgICAgICAgICAgICAgICAgICAgICAgICBnZW9tZXRyeSA9IHsKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAndHlwZSc6ICdQb2x5Z29uJywKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAnY29vcmRpbmF0ZXMnOiBbbGluZVN0cmluZy5jb29yZGluYXRlc10KCSAgICAgICAgICAgICAgICAgICAgICAgIH07CgkgICAgICAgICAgICAgICAgICAgIH0KCSAgICAgICAgICAgICAgICAgICAgZWxzZSB7CgkgICAgICAgICAgICAgICAgICAgICAgICBjb25zb2xlLndhcm4oJ0Nhbm5vdCBjb252ZXJ0IHBvbHlsaW5lIHRvICcgKyBvcHRpb25zLnR5cGUpOwoJICAgICAgICAgICAgICAgICAgICB9CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIHJlc29sdmUoewoJICAgICAgICAgICAgICAgICAgICB0eXBlOiAiRmVhdHVyZUNvbGxlY3Rpb24iLAoJICAgICAgICAgICAgICAgICAgICBmZWF0dXJlczogW3sKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAidHlwZSI6ICJGZWF0dXJlIiwKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAiZ2VvbWV0cnkiOiBnZW9tZXRyeSwKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAicHJvcGVydGllcyI6IG9wdGlvbnMucHJvcGVydGllcyB8fCB7fQoJICAgICAgICAgICAgICAgICAgICAgICAgfV0KCSAgICAgICAgICAgICAgICB9KTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgICAgIGNhdGNoIChlcnIpIHsKCSAgICAgICAgICAgICAgICByZWplY3QoZXJyKTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgfSk7CgkgICAgICAgIHJldHVybiBnZW9qc29uOwoJICAgIH0KCX0KCgljb25zdCBsaWJyYXJpZXMgPSB7CgkgICAgJ0NvbnZlcnRlcic6IENvbnZlcnRlcgoJfTsKCWxldCBzdWJDbGFzczsKCXNlbGYuYWRkRXZlbnRMaXN0ZW5lcignbWVzc2FnZScsIGUgPT4gewoJICAgIGNvbnN0IGRhdGEgPSAoZS5kYXRhIHx8IGUpOwoJICAgIGNvbnN0IHBvc3QgPSAoaWQsIGVyciwgcmVzLCB0eXBlKSA9PiB7CgkgICAgICAgIHBvc3RNZXNzYWdlKHsKCSAgICAgICAgICAgIHR5cGU6IHR5cGUgPyB0eXBlIDogKGVyciA/ICdlcnJvcicgOiAncmVzcG9uc2UnKSwKCSAgICAgICAgICAgIGlkOiBpZCwKCSAgICAgICAgICAgIG1lc3NhZ2U6IHJlcywKCSAgICAgICAgICAgIGVycm9yOiBlcnIKCSAgICAgICAgfSk7CgkgICAgfTsKCSAgICBjb25zdCBjb21tYW5kcyA9IHsKCSAgICAgICAgJ2luaXQnOiAobXNnKSA9PiB7CgkgICAgICAgICAgICBjb25zdCB7IGlkLCBjb21tYW5kLCBtZXNzYWdlIH0gPSBtc2c7CgkgICAgICAgICAgICBzdWJDbGFzcyA9IG5ldyBsaWJyYXJpZXNbY29tbWFuZF0obWVzc2FnZVswXSwgbWVzc2FnZVsxXSk7CgkgICAgICAgICAgICAvLyByZXR1cm4gdGhlIGNsYXNzJyBtZXRob2RzCgkgICAgICAgICAgICBjb25zdCBmbnMgPSBbCgkgICAgICAgICAgICAgICAgLi4uT2JqZWN0LmdldE93blByb3BlcnR5TmFtZXMobGlicmFyaWVzW2NvbW1hbmRdLnByb3RvdHlwZSksCgkgICAgICAgICAgICAgICAgLi4uT2JqZWN0LmtleXMoc3ViQ2xhc3MpCgkgICAgICAgICAgICBdLm1hcChrZXkgPT4g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IEl0J3MgYSBwcm9taXNlLCBzbyB3YWl0IGZvciBpdAoJICAgICAgICAgICAgICAgICAgICBjbWQKCSAgICAgICAgICAgICAgICAgICAgICAgIC50aGVuKHJlcyA9PiBwb3N0KGlkLCB1bmRlZmluZWQsIHJlcykpCgkgICAgICAgICAgICAgICAgICAgICAgICAuY2F0Y2goZSA9PiBwb3N0KGlkLCBlKSk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgICAgIGVsc2UgewoJICAgICAgICAgICAgICAgICAgICAvLyBOb3QgYSBwcm9taXNlLCBqdXN0IHJldHVybiBpdAoJICAgICAgICAgICAgICAgICAgICBwb3N0KGlkLCB1bmRlZmluZWQsIGNtZCk7CgkgICAgICAgICAgICAgICAgfQoJICAgICAgICAgICAgfQoJICAgICAgICAgICAgZWxzZSB7CgkgICAgICAgICAgICAgICAgLy8gRXJyb3IKCSAgICAgICAgICAgICAgICBwb3N0KGlkLCBuZXcgRXJyb3IoYGNvbW1hbmQgIiR7Y29tbWFuZH0iIG5vdCBmb3VuZGApKTsKCSAgICAgICAgICAgIH0KCSAgICAgICAgfQoJICAgIH07CgkgICAgaWYgKGNvbW1hbmRzW2RhdGEudHlwZV0pIHsKCSAgICAgICAgY29tbWFuZHNbZGF0YS50eXBlXShkYXRhKTsKCSAgICB9Cgl9KTsKCn0pKCk7Ci8vIyBzb3VyY2VNYXBwaW5nVVJMPXdvcmtlci5qcy5tYXAKCg==");const randomString=()=>Math.random().toString(36).substring(2);class Actor{constructor(M,et){this.initId=randomString()+"-"+M,this.worker=new ig,this.handlers=new Map,this.worker.onmessage=et=>{const Bt=et.data,Wt=this.handlers.get(Bt.id),Nt=this;if(Wt){if("response"===Bt.type&&Wt.resolve(Bt.message),"error"===Bt.type){const et=Bt.error||new Error(`Unknown error with ${M}`);Wt.reject(et)}"init_response"===Bt.type&&(this._=Object.keys(Bt.message).map((M=>{const et="function"==typeof Bt.message[M];return[M,function(){return et?Nt.exec(M)(...arguments):Nt.get(M)}]})).reduce(((M,et)=>({...M,[et[0]]:et[1]})),{}),Wt.resolve(this._))}},this.worker.postMessage({type:"init",id:this.initId,command:M,message:et})}onLoad(){return new Promise((M=>{void 0===this._?this.handlers.set(this.initId,{resolve:M,reject:M}):M(this._)}))}exec(M){const et=this;return function(...Bt){return new Promise(((Wt,Nt)=>{const $t=randomString()+"-"+M;et.handlers.set($t,{resolve:Wt,reject:Nt}),et.worker.postMessage({type:"exec",id:$t,command:M,message:[...Bt]})}))}}get(M){return new Promise(((et,Bt)=>{const Wt=randomString()+"-"+M;this.handlers.set(Wt,{resolve:et,reject:Bt}),this.worker.postMessage({type:"get",id:Wt,command:M,message:[]})}))}}const rg="test://http://example.com"!==new URL("test://http://example.com").href;async function processData(M,et,Bt){const Wt=await fetch(M,Bt?{signal:Bt.signal}:void 0);let Nt={};const $t=new URL(M,window.location.href);if($t.hash.length){const M=$t.hash,et=decodeURIComponent(M.slice(1));try{Nt=JSON.parse(et)}catch(M){console.warn("Error parsing or reading URL:",M)}}if(200==Wt.status){const M=await Wt.text();let Bt;if(["kml","tcx","gpx"].includes(et)||!(()=>{let M=!1;try{M="function"==typeof window.Worker}catch(et){M=!1}return M})()){Bt=new Converter(et,M,Nt).convert()}else{Bt=new Actor("Converter",[et,M,Nt]).exec("convert")()}return await Bt}throw new Error(`Data fetch error: ${Wt.statusText}`)}const processUrl=M=>{const et=M.split("://")[0],Bt=M.replace(new RegExp(`^${et}://`),""),Wt=rg?(M=>{const et=new RegExp("^(https?)(//)");return M.replace(et,"$1:$2")})(Bt):Bt;return{prefix:et,url:Wt}},VectorTextProtocol=(M,et)=>et instanceof AbortController?(async(M,et)=>{const{prefix:Bt,url:Wt}=processUrl(M.url);if(!Wt)throw new Error("Invalid URL: "+M.url);try{return{data:await processData(Wt,Bt,et)}}catch(M){throw new Error(M||"Unknown Error")}})(M,et):((M,et)=>{const Bt=new AbortController,{prefix:Wt,url:Nt}=processUrl(M.url);return Nt&&processData(Nt,Wt,Bt).then((M=>et(null,M))).catch((M=>et(M))),{cancel:()=>{Bt.abort()}}})(M,et);(M=>{if(document.head.querySelector(`link[href="${M}"]`))return;const et=document.createElement("link");Object.assign(et,{rel:"stylesheet",href:M,onerror:()=>console.warn("Fail to load stylesheet:",M)}),document.head.appendChild(et)})("https://unpkg.com/maplibre-gl@4.5.2/dist/maplibre-gl.css");const ng=class extends defaultExport{id="maplibre";pitch=0;bearing=0;style="https://demotiles.maplibre.org/style.json";link=!1;globe=!1;maplibregl=Wl;static validOptions=this.validOptions.concat([new MapOption({name:"pitch",desc:"Pitch toward the horizon measured in degrees",example:"60",exampleDesc:"Look a little upward",isValid:M=>M<=90&&M>=0}),new MapOption({name:"bearing",desc:"The compass direction that is 'up'",example:"-30",exampleDesc:"Rotate map a little",isValid:M=>M<=180&&M>=-180}),new MapOption({name:"link",desc:"Syn map's position with the hash fragment of the page's URL",example:"true",exampleDesc:"Add hash for page URL",isValid:M=>"true"===M}),new MapOption({name:"style",desc:"URL of style document, read https://maplibre.org/maplibre-style-spec/",example:"https://tile.openstreetmap.jp/styles/openmaptiles/style.json",exampleDesc:"Style form OSM japan!!!",isValid:M=>URL.parse(M)}),new MapOption({name:"globe",desc:"Display a globe",example:"true",exampleDesc:"Add globe for lower zoom level",isValid:M=>"true"===M})]);async addMap({maplibregl:M,target:et,style:Bt,data:Wt,center:Nt,zoom:$t,pitch:Gr,bearing:mn,link:Hn,globe:so}){const uo=0!==Wt.filter((M=>"tile"===M.type)).length?{version:8,sources:{},layers:[]}:Bt;return this.map=new M.Map({container:et,style:uo,center:Nt,zoom:$t,pitch:Gr,bearing:mn,hash:Hn}),new Promise(((M,et)=>{this.map.on("load",(()=>{this.map.setProjection({type:so?"globe":"mercator"}),M(this.map)}))}))}getTerraDrawAdapter({maplibregl:M,map:et,draw:Bt}){return Bt?(this.terraDrawAdapter=new l({map:et,maplibregl:M}),this.terraDrawAdapter):{state:"skip"}}setControl({maplibregl:M,map:et,control:Bt}){if(!Bt||0===Object.values(Bt).filter((M=>M)).length)return{state:"skip"};if(!0===Bt.fullscreen&&et.addControl(new M.FullscreenControl),!0===Bt.scale){const Bt=new M.ScaleControl({unit:"metric"});et.addControl(Bt)}}setExtra(M){const{map:et,debug:Bt}=M;if(!Bt&&!M.eval)return{state:"skip"};!0===Bt&&(et.showTileBoundaries=!0),M.eval&&this.evalScript(M.eval,[["map",et]])}addTileData({map:M,data:et}){const Bt=et.filter((M=>"tile"===M.type));if(0===Bt.length)return{state:"skip"};const Wt=M.getStyle();Bt.forEach(((M,et)=>{const Bt=M.name?M.name:et.toString();Wt.sources[Bt]={type:"raster",tiles:[M.url],tileSize:256},Wt.layers.push({id:Bt,type:"raster",source:Bt})})),M.setStyle(Wt)}async addGPXFile({maplibregl:M,map:et,data:Bt}){const Wt=Bt.find((M=>"gpx"===M.type));if(!Wt)return{state:"skip"};var Nt;Nt=M,Qh.forEach((M=>{Nt.addProtocol(M,VectorTextProtocol)}));const $t="gpx",Gr={type:"geojson",data:"gpx://"+Wt};if(et.addSource($t,Gr),et.addLayer({id:"id_"+$t,type:"line",source:$t,paint:{"line-color":"red","line-width":3}}),!Object.prototype.hasOwnProperty.call(this,"center")){const Bt=(await et.getSource($t).getData()).features[0].geometry.coordinates,Wt=Bt.reduce(((M,et)=>M.extend(et)),new M.LngLatBounds(Bt[0],Bt[0]));et.fitBounds(Wt,{padding:20})}}addMarker(M){const et=M.element?{element:M.element,anchor:"pin"===M.type?"bottom":"center"}:{},Bt=new this.maplibregl.Marker(et).setLngLat(M.xy).addTo(this.map),Wt=Bt.getElement();return Wt.classList.add("marker"),Wt.remove=()=>Bt.remove(),Wt}async updateCamera({bounds:M,center:et,zoom:Bt,animation:Wt,...Nt},$t){return M?this.map.fitBounds(M,{linear:!0,...Nt}):Wt||$t?this.map.flyTo({center:et??this.map.getCenter(),zoom:Bt??this.map.getZoom(),...Nt}):(this.map.setCenter(et),this.map.setZoom(Bt)),new Promise((M=>{this.map.on("zoomend",(()=>{M("zoomend")}))}))}project([M,et]){return this.map.project([M,et])}unproject([M,et]){const{lng:Bt,lat:Wt}=this.map.unproject([M,et]);return[Bt,Wt]}};export{ng as default};