leaflet-polydraw 2.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("leaflet")):"function"==typeof define&&define.amd?define(["exports","leaflet"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LeafletPolydraw={},e.L)}(this,function(e,t){"use strict";var r,o,n=Object.defineProperty,i=(e,t,r)=>((e,t,r)=>t in e?n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);function a(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const r in e)if("default"!==r){const o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,o.get?o:{enumerable:!0,get:()=>e[r]})}return t.default=e,Object.freeze(t)}const s=a(t);var l=(e=>(e.V1="1.x",e.V2="2.x",e))(l||{}),c=(e=>(e[e.Off=0]="Off",e[e.Add=1]="Add",e[e.Edit=2]="Edit",e[e.Subtract=4]="Subtract",e[e.AppendMarker=8]="AppendMarker",e[e.LoadPredefined=16]="LoadPredefined",e[e.PointToPoint=32]="PointToPoint",e[e.PointToPointSubtract=64]="PointToPointSubtract",e[e.Clone=128]="Clone",e))(c||{}),u=(e=>(e[e.SouthWest=0]="SouthWest",e[e.South=1]="South",e[e.SouthEast=2]="SouthEast",e[e.East=3]="East",e[e.NorthEast=4]="NorthEast",e[e.North=5]="North",e[e.NorthWest=6]="NorthWest",e[e.West=7]="West",e[e.Hole=8]="Hole",e))(u||{}),h=(e=>(e.Both="both",e.Inward="inward",e))(h||{});const g={mergePolygons:!0,kinks:!1,tools:{default:c.Off,draw:!0,subtract:!0,p2p:!0,p2pSubtract:!0,clone:!0,erase:!0,eraseScope:"all"},modes:{attachElbow:!0,dragElbow:!0,dragPolygons:!0,edgeDeletion:!0},modifierSubtractMode:!0,interaction:{drag:{opacity:.7,dragCursor:"move",hoverCursor:"grab",markerBehavior:"hide",markerAnimationDuration:200,modifierSubtract:{keys:{windows:"ctrlKey",mac:"metaKey",linux:"ctrlKey"},hideMarkersOnDrag:!0}},edgeDeletion:{keys:{windows:"ctrlKey",mac:"metaKey",linux:"ctrlKey"},minVertices:3}},markers:{deleteMarker:!0,infoMarker:!0,menuMarker:!0,coordsTitle:!0,zIndexOffset:0,markerIcon:{styleClasses:["polygon-marker"],zIndexOffset:null},holeIcon:{styleClasses:["polygon-marker","hole"],zIndexOffset:null},markerInfoIcon:{position:u.East,showArea:!0,showPerimeter:!0,useMetrics:!0,usePerimeterMinValue:!1,areaLabel:"Area",perimeterLabel:"Perimeter",values:{min:{metric:"50",imperial:"100"},unknown:{metric:"-",imperial:"-"}},units:{unknownUnit:"",metric:{onlyMetrics:!0,perimeter:{m:"m",km:"km"},area:{m2:"m²",km2:"km²",daa:"daa",ha:"ha"}},imperial:{perimeter:{feet:"ft",yards:"yd",miles:"mi"},area:{feet2:"ft²",yards2:"yd²",acres:"ac",miles2:"mi²"}}},styleClasses:["polygon-marker","info"],zIndexOffset:1e4},markerMenuIcon:{position:u.South,styleClasses:["polygon-marker","menu"],zIndexOffset:1e4},markerDeleteIcon:{position:u.North,styleClasses:["polygon-marker","delete"],zIndexOffset:1e4},holeMarkers:{menuMarker:!1,deleteMarker:!0,infoMarker:!1},visualOptimization:{toleranceMin:5e-6,toleranceMax:.005,curve:1.35}},styles:{polyline:{weight:2,opacity:1,color:"#50622b"},subtractLine:{weight:2,opacity:1,color:"#D9460F"},polygon:{weight:2,opacity:1,fillOpacity:.2,smoothFactor:.3,noClip:!0,color:"#50622b",fillColor:"#b4cd8a"},hole:{weight:2,opacity:1,fillOpacity:.5,color:"#aa0000",fillColor:"#ffcccc"},ui:{controlButton:{backgroundColor:"#fff",color:"#000"},controlButtonHover:{backgroundColor:"#f4f4f4"},controlButtonActive:{backgroundColor:"rgb(128, 218, 255)",color:"#fff"},indicatorActive:{backgroundColor:"#ffcc00"},p2pMarker:{backgroundColor:"#fff",borderColor:"#50622b"},p2pClosingMarker:{color:"#4CAF50"},edgeHover:{color:"#7a9441"},edgeDeletion:{color:"#D9460F"},dragSubtract:{color:"#D9460F"}}},polygonCreation:{algorithm:"concaveman"},simplification:{strategy:"simple",simple:{tolerance:1e-4,highQuality:!1},dynamic:{baseTolerance:1e-4,highQuality:!1,fractionGuard:.9,multiplier:2}},polygonTools:{simplify:{enabled:!0,processHoles:!0},doubleElbows:{enabled:!0,processHoles:!0},bbox:{enabled:!0,processHoles:!0,addMidPointMarkers:!0},bezier:{enabled:!0,resolution:1e4,sharpness:.75,resampleMultiplier:10,maxNodes:1e3,visualOptimizationLevel:10,ghostMarkers:!1},scale:{enabled:!0},rotate:{enabled:!0},donut:{enabled:!0,direction:h.Both},visualOptimizationToggle:{enabled:!0}},tooltips:{enabled:!0,delayMs:500,direction:"left",backgroundColor:"#645d5d",color:"#ffffff"},history:{capture:{batch:!0,freehand:!0,pointToPoint:!0,addPredefinedPolygon:!0,eraseAll:!0,markerDrag:!0,polygonDrag:!0,polygonClone:!0,addVertex:!0,removeVertex:!0,removeHole:!0,modifierSubtract:!0,deletePolygon:!0,layerDelete:!0,layerReorder:!0,polygonActions:{simplify:!0,doubleElbows:!0,bbox:!0,bezier:!0,scale:!0,rotate:!0,donut:!0,toggleOptimization:!0,polygonMenuAction:!0}},maxSize:50}},d=6371e3,p=6371,f=3959,y=Math.PI/180,m=180/Math.PI;Math.PI;function v(e,t={}){return{type:"Feature",geometry:{type:"Point",coordinates:e},properties:t}}function M(e,t={}){return{type:"Feature",geometry:{type:"LineString",coordinates:e},properties:t}}function b(e,t={}){return{type:"Feature",geometry:{type:"Polygon",coordinates:e},properties:t}}function w(e,t={}){return{type:"Feature",geometry:{type:"MultiPolygon",coordinates:e},properties:t}}function P(e){return{type:"FeatureCollection",features:e}}function L(e){if("Polygon"===e.geometry.type)return[e.geometry.coordinates];if("MultiPolygon"===e.geometry.type)return e.geometry.coordinates;throw new Error("Feature must be a Polygon or MultiPolygon")}function k(e){let t=1/0,r=1/0,o=-1/0,n=-1/0;const i=e=>{if(Array.isArray(e[0]))e.forEach(e=>i(e));else{const[i,a]=e;t=Math.min(t,i),r=Math.min(r,a),o=Math.max(o,i),n=Math.max(n,a)}},a=e=>{if("GeometryCollection"===e.type){return void e.geometries.forEach(a)}i(e.coordinates)};return a(e.geometry),[t,r,o,n]}function E(e,t,r="kilometers"){const o=Array.isArray(e)?e:e.geometry.coordinates,n=Array.isArray(t)?t:t.geometry.coordinates,[i,a]=o,[s,l]=n,c="miles"===r?f:"meters"===r?d:p,u=D(l-a),h=D(s-i),g=Math.sin(u/2)*Math.sin(u/2)+Math.cos(D(a))*Math.cos(D(l))*Math.sin(h/2)*Math.sin(h/2);return c*(2*Math.atan2(Math.sqrt(g),Math.sqrt(1-g)))}function x(e,t){const r=Array.isArray(e)?e:e.geometry.coordinates,o=Array.isArray(t)?t:t.geometry.coordinates,[n,i]=r,[a,s]=o;return v([(n+a)/2,(i+s)/2])}function S(e){const t=L(e);let r=0,o=0,n=0;for(const i of t)for(const e of i)for(const t of e)r+=t[0],o+=t[1],n++;return v([r/n,o/n])}function D(e){return e*y}var C=6371008.8,I={centimeters:637100880,centimetres:637100880,degrees:360/(2*Math.PI),feet:20902260.511392,inches:39.37*C,kilometers:6371.0088,kilometres:6371.0088,meters:C,metres:C,miles:3958.761333810546,millimeters:6371008800,millimetres:6371008800,nauticalmiles:C/1852,radians:1,yards:6967335.223679999};function A(e,t,r={}){const o={type:"Feature"};return(0===r.id||r.id)&&(o.id=r.id),r.bbox&&(o.bbox=r.bbox),o.properties=t||{},o.geometry=e,o}function F(e,t,r={}){if(!e)throw new Error("coordinates is required");if(!Array.isArray(e))throw new Error("coordinates must be an Array");if(e.length<2)throw new Error("coordinates must be at least 2 numbers long");if(!z(e[0])||!z(e[1]))throw new Error("coordinates must contain numbers");return A({type:"Point",coordinates:e},t,r)}function O(e,t,r={}){for(const o of e){if(o.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(o[o.length-1].length!==o[0].length)throw new Error("First and last Position are not equivalent.");for(let e=0;e<o[o.length-1].length;e++)if(o[o.length-1][e]!==o[0][e])throw new Error("First and last Position are not equivalent.")}return A({type:"Polygon",coordinates:e},t,r)}function T(e,t,r={}){if(e.length<2)throw new Error("coordinates must be an array of two or more positions");return A({type:"LineString",coordinates:e},t,r)}function _(e,t={}){const r={type:"FeatureCollection"};return t.id&&(r.id=t.id),t.bbox&&(r.bbox=t.bbox),r.features=e,r}function G(e,t,r={}){return A({type:"MultiPolygon",coordinates:e},t,r)}function H(e){return 180*(e%(2*Math.PI))/Math.PI}function B(e){return e%360*Math.PI/180}function z(e){return!isNaN(e)&&null!==e&&!Array.isArray(e)}function N(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function U(e,t,r){var o=r;return function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,function(e,n,i,a,s){o=0===n&&void 0===r?e:t(o,e,n,i,a,s)}),o}function R(e){return U(e,(e,t)=>e+function(e){let t,r=0;switch(e.type){case"Polygon":return X(e.coordinates);case"MultiPolygon":for(t=0;t<e.coordinates.length;t++)r+=X(e.coordinates[t]);return r;case"Point":case"MultiPoint":case"LineString":case"MultiLineString":return 0}return 0}(t),0)}function X(e){let t=0;if(e&&e.length>0){t+=Math.abs(q(e[0]));for(let r=1;r<e.length;r++)t-=Math.abs(q(e[r]))}return t}var Y=20294876564838.72,V=Math.PI/180;function q(e){const t=e.length-1;if(t<=2)return 0;let r=0,o=0;for(;o<t;){const n=e[o],i=e[o+1===t?0:o+1],a=e[o+2>=t?(o+2)%t:o+2],s=n[0]*V,l=i[1]*V;r+=(a[0]*V-s)*Math.sin(l),o++}return r*Y}var j=R;function W(e,t,r){if(null!==e)for(var o,n,i,a,s,l,c,u,h=0,g=0,d=e.type,p="FeatureCollection"===d,f="Feature"===d,y=p?e.features.length:1,m=0;m<y;m++){s=(u=!!(c=p?e.features[m].geometry:f?e.geometry:e)&&"GeometryCollection"===c.type)?c.geometries.length:1;for(var v=0;v<s;v++){var M=0,b=0;if(null!==(a=u?c.geometries[v]:c)){l=a.coordinates;var w=a.type;switch(h=0,w){case null:break;case"Point":if(!1===t(l,g,m,M,b))return!1;g++,M++;break;case"LineString":case"MultiPoint":for(o=0;o<l.length;o++){if(!1===t(l[o],g,m,M,b))return!1;g++,"MultiPoint"===w&&M++}"LineString"===w&&M++;break;case"Polygon":case"MultiLineString":for(o=0;o<l.length;o++){for(n=0;n<l[o].length-h;n++){if(!1===t(l[o][n],g,m,M,b))return!1;g++}"MultiLineString"===w&&M++,"Polygon"===w&&b++}"Polygon"===w&&M++;break;case"MultiPolygon":for(o=0;o<l.length;o++){for(b=0,n=0;n<l[o].length;n++){for(i=0;i<l[o][n].length-h;i++){if(!1===t(l[o][n][i],g,m,M,b))return!1;g++}b++}M++}break;case"GeometryCollection":for(o=0;o<a.geometries.length;o++)if(!1===W(a.geometries[o],t))return!1;break;default:throw new Error("Unknown Geometry Type")}}}}}function $(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function K(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var o=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,o.get?o:{enumerable:!0,get:function(){return e[t]}})}),r}var J,Z={exports:{}},Q={exports:{}};function ee(){return J||(J=1,Q.exports=function(){function e(e,o,n,i,a){!function e(r,o,n,i,a){for(;i>n;){if(i-n>600){var s=i-n+1,l=o-n+1,c=Math.log(s),u=.5*Math.exp(2*c/3),h=.5*Math.sqrt(c*u*(s-u)/s)*(l-s/2<0?-1:1);e(r,o,Math.max(n,Math.floor(o-l*u/s+h)),Math.min(i,Math.floor(o+(s-l)*u/s+h)),a)}var g=r[o],d=n,p=i;for(t(r,n,o),a(r[i],g)>0&&t(r,n,i);d<p;){for(t(r,d,p),d++,p--;a(r[d],g)<0;)d++;for(;a(r[p],g)>0;)p--}0===a(r[n],g)?t(r,n,p):t(r,++p,i),p<=o&&(n=p+1),o<=p&&(i=p-1)}}(e,o,n||0,i||e.length-1,a||r)}function t(e,t,r){var o=e[t];e[t]=e[r],e[r]=o}function r(e,t){return e<t?-1:e>t?1:0}var o=function(e){void 0===e&&(e=9),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function n(e,t,r){if(!r)return t.indexOf(e);for(var o=0;o<t.length;o++)if(r(e,t[o]))return o;return-1}function i(e,t){a(e,0,e.children.length,t,e)}function a(e,t,r,o,n){n||(n=p(null)),n.minX=1/0,n.minY=1/0,n.maxX=-1/0,n.maxY=-1/0;for(var i=t;i<r;i++){var a=e.children[i];s(n,e.leaf?o(a):a)}return n}function s(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function l(e,t){return e.minX-t.minX}function c(e,t){return e.minY-t.minY}function u(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function h(e){return e.maxX-e.minX+(e.maxY-e.minY)}function g(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function d(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function p(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function f(t,r,o,n,i){for(var a=[r,o];a.length;)if(!((o=a.pop())-(r=a.pop())<=n)){var s=r+Math.ceil((o-r)/n/2)*n;e(t,s,r,o,i),a.push(r,s,s,o)}}return o.prototype.all=function(){return this._all(this.data,[])},o.prototype.search=function(e){var t=this.data,r=[];if(!d(e,t))return r;for(var o=this.toBBox,n=[];t;){for(var i=0;i<t.children.length;i++){var a=t.children[i],s=t.leaf?o(a):a;d(e,s)&&(t.leaf?r.push(a):g(e,s)?this._all(a,r):n.push(a))}t=n.pop()}return r},o.prototype.collides=function(e){var t=this.data;if(!d(e,t))return!1;for(var r=[];t;){for(var o=0;o<t.children.length;o++){var n=t.children[o],i=t.leaf?this.toBBox(n):n;if(d(e,i)){if(t.leaf||g(e,i))return!0;r.push(n)}}t=r.pop()}return!1},o.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(var t=0;t<e.length;t++)this.insert(e[t]);return this}var r=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===r.height)this._splitRoot(this.data,r);else{if(this.data.height<r.height){var o=this.data;this.data=r,r=o}this._insert(r,this.data.height-r.height-1,!0)}else this.data=r;return this},o.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},o.prototype.clear=function(){return this.data=p([]),this},o.prototype.remove=function(e,t){if(!e)return this;for(var r,o,i,a=this.data,s=this.toBBox(e),l=[],c=[];a||l.length;){if(a||(a=l.pop(),o=l[l.length-1],r=c.pop(),i=!0),a.leaf){var u=n(e,a.children,t);if(-1!==u)return a.children.splice(u,1),l.push(a),this._condense(l),this}i||a.leaf||!g(a,s)?o?(r++,a=o.children[r],i=!1):a=null:(l.push(a),c.push(r),r=0,o=a,a=a.children[0])}return this},o.prototype.toBBox=function(e){return e},o.prototype.compareMinX=function(e,t){return e.minX-t.minX},o.prototype.compareMinY=function(e,t){return e.minY-t.minY},o.prototype.toJSON=function(){return this.data},o.prototype.fromJSON=function(e){return this.data=e,this},o.prototype._all=function(e,t){for(var r=[];e;)e.leaf?t.push.apply(t,e.children):r.push.apply(r,e.children),e=r.pop();return t},o.prototype._build=function(e,t,r,o){var n,a=r-t+1,s=this._maxEntries;if(a<=s)return i(n=p(e.slice(t,r+1)),this.toBBox),n;o||(o=Math.ceil(Math.log(a)/Math.log(s)),s=Math.ceil(a/Math.pow(s,o-1))),(n=p([])).leaf=!1,n.height=o;var l=Math.ceil(a/s),c=l*Math.ceil(Math.sqrt(s));f(e,t,r,c,this.compareMinX);for(var u=t;u<=r;u+=c){var h=Math.min(u+c-1,r);f(e,u,h,l,this.compareMinY);for(var g=u;g<=h;g+=l){var d=Math.min(g+l-1,h);n.children.push(this._build(e,g,d,o-1))}}return i(n,this.toBBox),n},o.prototype._chooseSubtree=function(e,t,r,o){for(;o.push(t),!t.leaf&&o.length-1!==r;){for(var n=1/0,i=1/0,a=void 0,s=0;s<t.children.length;s++){var l=t.children[s],c=u(l),h=(g=e,d=l,(Math.max(d.maxX,g.maxX)-Math.min(d.minX,g.minX))*(Math.max(d.maxY,g.maxY)-Math.min(d.minY,g.minY))-c);h<i?(i=h,n=c<n?c:n,a=l):h===i&&c<n&&(n=c,a=l)}t=a||t.children[0]}var g,d;return t},o.prototype._insert=function(e,t,r){var o=r?e:this.toBBox(e),n=[],i=this._chooseSubtree(o,this.data,t,n);for(i.children.push(e),s(i,o);t>=0&&n[t].children.length>this._maxEntries;)this._split(n,t),t--;this._adjustParentBBoxes(o,n,t)},o.prototype._split=function(e,t){var r=e[t],o=r.children.length,n=this._minEntries;this._chooseSplitAxis(r,n,o);var a=this._chooseSplitIndex(r,n,o),s=p(r.children.splice(a,r.children.length-a));s.height=r.height,s.leaf=r.leaf,i(r,this.toBBox),i(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(r,s)},o.prototype._splitRoot=function(e,t){this.data=p([e,t]),this.data.height=e.height+1,this.data.leaf=!1,i(this.data,this.toBBox)},o.prototype._chooseSplitIndex=function(e,t,r){for(var o,n,i,s,l,c,h,g=1/0,d=1/0,p=t;p<=r-t;p++){var f=a(e,0,p,this.toBBox),y=a(e,p,r,this.toBBox),m=(n=f,i=y,s=void 0,l=void 0,c=void 0,h=void 0,s=Math.max(n.minX,i.minX),l=Math.max(n.minY,i.minY),c=Math.min(n.maxX,i.maxX),h=Math.min(n.maxY,i.maxY),Math.max(0,c-s)*Math.max(0,h-l)),v=u(f)+u(y);m<g?(g=m,o=p,d=v<d?v:d):m===g&&v<d&&(d=v,o=p)}return o||r-t},o.prototype._chooseSplitAxis=function(e,t,r){var o=e.leaf?this.compareMinX:l,n=e.leaf?this.compareMinY:c;this._allDistMargin(e,t,r,o)<this._allDistMargin(e,t,r,n)&&e.children.sort(o)},o.prototype._allDistMargin=function(e,t,r,o){e.children.sort(o);for(var n=this.toBBox,i=a(e,0,t,n),l=a(e,r-t,r,n),c=h(i)+h(l),u=t;u<r-t;u++){var g=e.children[u];s(i,e.leaf?n(g):g),c+=h(i)}for(var d=r-t-1;d>=t;d--){var p=e.children[d];s(l,e.leaf?n(p):p),c+=h(l)}return c},o.prototype._adjustParentBBoxes=function(e,t,r){for(var o=r;o>=0;o--)s(t[o],e)},o.prototype._condense=function(e){for(var t=e.length-1,r=void 0;t>=0;t--)0===e[t].children.length?t>0?(r=e[t-1].children).splice(r.indexOf(e[t]),1):this.clear():i(e[t],this.toBBox)},o}()),Q.exports}function te(e,t){return e<t?-1:e>t?1:0}const re=K(Object.freeze(Object.defineProperty({__proto__:null,default:class{constructor(e=[],t=te){if(this.data=e,this.length=this.data.length,this.compare=t,this.length>0)for(let r=(this.length>>1)-1;r>=0;r--)this._down(r)}push(e){this.data.push(e),this.length++,this._up(this.length-1)}pop(){if(0===this.length)return;const e=this.data[0],t=this.data.pop();return this.length--,this.length>0&&(this.data[0]=t,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:t,compare:r}=this,o=t[e];for(;e>0;){const n=e-1>>1,i=t[n];if(r(o,i)>=0)break;t[e]=i,e=n}t[e]=o}_down(e){const{data:t,compare:r}=this,o=this.length>>1,n=t[e];for(;e<o;){let o=1+(e<<1),i=t[o];const a=o+1;if(a<this.length&&r(t[a],i)<0&&(o=a,i=t[a]),r(i,n)>=0)break;t[e]=i,e=o}t[e]=n}}},Symbol.toStringTag,{value:"Module"})));var oe,ne,ie,ae,se,le={exports:{}};function ce(){if(se)return le.exports;se=1;var e=ne?oe:(ne=1,oe=function(e,t,r,o){var n=e[0],i=e[1],a=!1;void 0===r&&(r=0),void 0===o&&(o=t.length);for(var s=(o-r)/2,l=0,c=s-1;l<s;c=l++){var u=t[r+2*l+0],h=t[r+2*l+1],g=t[r+2*c+0],d=t[r+2*c+1];h>i!=d>i&&n<(g-u)*(i-h)/(d-h)+u&&(a=!a)}return a}),t=ae?ie:(ae=1,ie=function(e,t,r,o){var n=e[0],i=e[1],a=!1;void 0===r&&(r=0),void 0===o&&(o=t.length);for(var s=o-r,l=0,c=s-1;l<s;c=l++){var u=t[l+r][0],h=t[l+r][1],g=t[c+r][0],d=t[c+r][1];h>i!=d>i&&n<(g-u)*(i-h)/(d-h)+u&&(a=!a)}return a});return le.exports=function(r,o,n,i){return o.length>0&&Array.isArray(o[0])?t(r,o,n,i):e(r,o,n,i)},le.exports.nested=t,le.exports.flat=e,le.exports}var ue,he,ge={exports:{}};function de(){return ue||(ue=1,function(e){const t=134217729,r=33306690738754706e-32;function o(e,t,r,o,n){let i,a,s,l,c=t[0],u=o[0],h=0,g=0;u>c==u>-c?(i=c,c=t[++h]):(i=u,u=o[++g]);let d=0;if(h<e&&g<r)for(u>c==u>-c?(s=i-((a=c+i)-c),c=t[++h]):(s=i-((a=u+i)-u),u=o[++g]),i=a,0!==s&&(n[d++]=s);h<e&&g<r;)u>c==u>-c?(s=i-((a=i+c)-(l=a-i))+(c-l),c=t[++h]):(s=i-((a=i+u)-(l=a-i))+(u-l),u=o[++g]),i=a,0!==s&&(n[d++]=s);for(;h<e;)s=i-((a=i+c)-(l=a-i))+(c-l),c=t[++h],i=a,0!==s&&(n[d++]=s);for(;g<r;)s=i-((a=i+u)-(l=a-i))+(u-l),u=o[++g],i=a,0!==s&&(n[d++]=s);return 0===i&&0!==d||(n[d++]=i),d}function n(e){return new Float64Array(e)}const i=33306690738754716e-32,a=22204460492503146e-32,s=11093356479670487e-47,l=n(4),c=n(8),u=n(12),h=n(16),g=n(4);e.orient2d=function(e,n,d,p,f,y){const m=(n-y)*(d-f),v=(e-f)*(p-y),M=m-v;if(0===m||0===v||m>0!=v>0)return M;const b=Math.abs(m+v);return Math.abs(M)>=i*b?M:-function(e,n,i,d,p,f,y){let m,v,M,b,w,P,L,k,E,x,S,D,C,I,A,F,O,T;const _=e-p,G=i-p,H=n-f,B=d-f;w=(A=(k=_-(L=(P=t*_)-(P-_)))*(x=B-(E=(P=t*B)-(P-B)))-((I=_*B)-L*E-k*E-L*x))-(S=A-(O=(k=H-(L=(P=t*H)-(P-H)))*(x=G-(E=(P=t*G)-(P-G)))-((F=H*G)-L*E-k*E-L*x))),l[0]=A-(S+w)+(w-O),w=(C=I-((D=I+S)-(w=D-I))+(S-w))-(S=C-F),l[1]=C-(S+w)+(w-F),w=(T=D+S)-D,l[2]=D-(T-w)+(S-w),l[3]=T;let z=function(e,t){let r=t[0];for(let o=1;o<e;o++)r+=t[o];return r}(4,l),N=a*y;if(z>=N||-z>=N)return z;if(m=e-(_+(w=e-_))+(w-p),M=i-(G+(w=i-G))+(w-p),v=n-(H+(w=n-H))+(w-f),b=d-(B+(w=d-B))+(w-f),0===m&&0===v&&0===M&&0===b)return z;if(N=s*y+r*Math.abs(z),(z+=_*b+B*m-(H*M+G*v))>=N||-z>=N)return z;w=(A=(k=m-(L=(P=t*m)-(P-m)))*(x=B-(E=(P=t*B)-(P-B)))-((I=m*B)-L*E-k*E-L*x))-(S=A-(O=(k=v-(L=(P=t*v)-(P-v)))*(x=G-(E=(P=t*G)-(P-G)))-((F=v*G)-L*E-k*E-L*x))),g[0]=A-(S+w)+(w-O),w=(C=I-((D=I+S)-(w=D-I))+(S-w))-(S=C-F),g[1]=C-(S+w)+(w-F),w=(T=D+S)-D,g[2]=D-(T-w)+(S-w),g[3]=T;const U=o(4,l,4,g,c);w=(A=(k=_-(L=(P=t*_)-(P-_)))*(x=b-(E=(P=t*b)-(P-b)))-((I=_*b)-L*E-k*E-L*x))-(S=A-(O=(k=H-(L=(P=t*H)-(P-H)))*(x=M-(E=(P=t*M)-(P-M)))-((F=H*M)-L*E-k*E-L*x))),g[0]=A-(S+w)+(w-O),w=(C=I-((D=I+S)-(w=D-I))+(S-w))-(S=C-F),g[1]=C-(S+w)+(w-F),w=(T=D+S)-D,g[2]=D-(T-w)+(S-w),g[3]=T;const R=o(U,c,4,g,u);w=(A=(k=m-(L=(P=t*m)-(P-m)))*(x=b-(E=(P=t*b)-(P-b)))-((I=m*b)-L*E-k*E-L*x))-(S=A-(O=(k=v-(L=(P=t*v)-(P-v)))*(x=M-(E=(P=t*M)-(P-M)))-((F=v*M)-L*E-k*E-L*x))),g[0]=A-(S+w)+(w-O),w=(C=I-((D=I+S)-(w=D-I))+(S-w))-(S=C-F),g[1]=C-(S+w)+(w-F),w=(T=D+S)-D,g[2]=D-(T-w)+(S-w),g[3]=T;const X=o(R,u,4,g,h);return h[X-1]}(e,n,d,p,f,y,b)},e.orient2dfast=function(e,t,r,o,n,i){return(t-i)*(r-n)-(e-n)*(o-i)},Object.defineProperty(e,"__esModule",{value:!0})}(ge.exports)),ge.exports}const pe=$(function(){if(he)return Z.exports;he=1;var e=ee(),t=re,r=ce(),o=de().orient2d;function n(t,o,n){o=Math.max(0,void 0===o?2:o),n=n||0;var a=function(e){for(var t=e[0],o=e[0],n=e[0],i=e[0],a=0;a<e.length;a++){var s=e[a];s[0]<t[0]&&(t=s),s[0]>n[0]&&(n=s),s[1]<o[1]&&(o=s),s[1]>i[1]&&(i=s)}var l=[t,o,n,i],c=l.slice();for(a=0;a<e.length;a++)r(e[a],l)||c.push(e[a]);return function(e){e.sort(m);for(var t=[],r=0;r<e.length;r++){for(;t.length>=2&&u(t[t.length-2],t[t.length-1],e[r])<=0;)t.pop();t.push(e[r])}for(var o=[],n=e.length-1;n>=0;n--){for(;o.length>=2&&u(o[o.length-2],o[o.length-1],e[n])<=0;)o.pop();o.push(e[n])}return o.pop(),t.pop(),t.concat(o)}(c)}(t),s=new e(16);s.toBBox=function(e){return{minX:e[0],minY:e[1],maxX:e[0],maxY:e[1]}},s.compareMinX=function(e,t){return e[0]-t[0]},s.compareMinY=function(e,t){return e[1]-t[1]},s.load(t);for(var l,c=[],h=0;h<a.length;h++){var f=a[h];s.remove(f),l=d(f,l),c.push(l)}var y=new e(16);for(h=0;h<c.length;h++)y.insert(g(c[h]));for(var v=o*o,M=n*n;c.length;){var b=c.shift(),w=b.p,P=b.next.p,L=p(w,P);if(!(L<M)){var k=L/v;(f=i(s,b.prev.p,w,P,b.next.next.p,k,y))&&Math.min(p(f,w),p(f,P))<=k&&(c.push(b),c.push(d(f,b)),s.remove(f),y.remove(b),y.insert(g(b)),y.insert(g(b.next)))}}b=l;var E=[];do{E.push(b.p),b=b.next}while(b!==l);return E.push(b.p),E}function i(e,r,o,n,i,l,u){for(var h=new t([],a),g=e.data;g;){for(var d=0;d<g.children.length;d++){var p=g.children[d],y=g.leaf?f(p,o,n):s(o,n,p);y>l||h.push({node:p,dist:y})}for(;h.length&&!h.peek().node.children;){var m=h.pop(),v=m.node,M=f(v,r,o),b=f(v,n,i);if(m.dist<M&&m.dist<b&&c(o,v,u)&&c(n,v,u))return v}(g=h.pop())&&(g=g.node)}return null}function a(e,t){return e.dist-t.dist}function s(e,t,r){if(l(e,r)||l(t,r))return 0;var o=y(e[0],e[1],t[0],t[1],r.minX,r.minY,r.maxX,r.minY);if(0===o)return 0;var n=y(e[0],e[1],t[0],t[1],r.minX,r.minY,r.minX,r.maxY);if(0===n)return 0;var i=y(e[0],e[1],t[0],t[1],r.maxX,r.minY,r.maxX,r.maxY);if(0===i)return 0;var a=y(e[0],e[1],t[0],t[1],r.minX,r.maxY,r.maxX,r.maxY);return 0===a?0:Math.min(o,n,i,a)}function l(e,t){return e[0]>=t.minX&&e[0]<=t.maxX&&e[1]>=t.minY&&e[1]<=t.maxY}function c(e,t,r){for(var o=Math.min(e[0],t[0]),n=Math.min(e[1],t[1]),i=Math.max(e[0],t[0]),a=Math.max(e[1],t[1]),s=r.search({minX:o,minY:n,maxX:i,maxY:a}),l=0;l<s.length;l++)if(h(s[l].p,s[l].next.p,e,t))return!1;return!0}function u(e,t,r){return o(e[0],e[1],t[0],t[1],r[0],r[1])}function h(e,t,r,o){return e!==o&&t!==r&&u(e,t,r)>0!=u(e,t,o)>0&&u(r,o,e)>0!=u(r,o,t)>0}function g(e){var t=e.p,r=e.next.p;return e.minX=Math.min(t[0],r[0]),e.minY=Math.min(t[1],r[1]),e.maxX=Math.max(t[0],r[0]),e.maxY=Math.max(t[1],r[1]),e}function d(e,t){var r={p:e,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return t?(r.next=t.next,r.prev=t,t.next.prev=r,t.next=r):(r.prev=r,r.next=r),r}function p(e,t){var r=e[0]-t[0],o=e[1]-t[1];return r*r+o*o}function f(e,t,r){var o=t[0],n=t[1],i=r[0]-o,a=r[1]-n;if(0!==i||0!==a){var s=((e[0]-o)*i+(e[1]-n)*a)/(i*i+a*a);s>1?(o=r[0],n=r[1]):s>0&&(o+=i*s,n+=a*s)}return(i=e[0]-o)*i+(a=e[1]-n)*a}function y(e,t,r,o,n,i,a,s){var l,c,u,h,g=r-e,d=o-t,p=a-n,f=s-i,y=e-n,m=t-i,v=g*g+d*d,M=g*p+d*f,b=p*p+f*f,w=g*y+d*m,P=p*y+f*m,L=v*b-M*M,k=L,E=L;0===L?(c=0,k=1,h=P,E=b):(h=v*P-M*w,(c=M*P-b*w)<0?(c=0,h=P,E=b):c>k&&(c=k,h=P+M,E=b)),h<0?(h=0,-w<0?c=0:-w>v?c=k:(c=-w,k=v)):h>E&&(h=E,-w+M<0?c=0:-w+M>v?c=k:(c=-w+M,k=v));var x=(1-(u=0===h?0:h/E))*n+u*a-((1-(l=0===c?0:c/k))*e+l*r),S=(1-u)*i+u*s-((1-l)*t+l*o);return x*x+S*S}function m(e,t){return e[0]===t[0]?e[1]-t[1]:e[0]-t[0]}return t.default&&(t=t.default),Z.exports=n,Z.exports.default=n,Z.exports}());function fe(e,t={}){t.concavity=t.concavity||1/0;const r=[];if(W(e,e=>{r.push([e[0],e[1]])}),!r.length)return null;const o=pe(r,t.concavity);return o.length>3?O([o]):null}var ye=fe;function me(e,t,r){if(null!==e)for(var o,n,i,a,s,l,c,u,h=0,g=0,d=e.type,p="FeatureCollection"===d,f="Feature"===d,y=p?e.features.length:1,m=0;m<y;m++){s=(u=!!(c=p?e.features[m].geometry:f?e.geometry:e)&&"GeometryCollection"===c.type)?c.geometries.length:1;for(var v=0;v<s;v++){var M=0,b=0;if(null!==(a=u?c.geometries[v]:c)){l=a.coordinates;var w=a.type;switch(h="Polygon"===w||"MultiPolygon"===w?1:0,w){case null:break;case"Point":if(!1===t(l,g,m,M,b))return!1;g++,M++;break;case"LineString":case"MultiPoint":for(o=0;o<l.length;o++){if(!1===t(l[o],g,m,M,b))return!1;g++,"MultiPoint"===w&&M++}"LineString"===w&&M++;break;case"Polygon":case"MultiLineString":for(o=0;o<l.length;o++){for(n=0;n<l[o].length-h;n++){if(!1===t(l[o][n],g,m,M,b))return!1;g++}"MultiLineString"===w&&M++,"Polygon"===w&&b++}"Polygon"===w&&M++;break;case"MultiPolygon":for(o=0;o<l.length;o++){for(b=0,n=0;n<l[o].length;n++){for(i=0;i<l[o][n].length-h;i++){if(!1===t(l[o][n][i],g,m,M,b))return!1;g++}b++}M++}break;case"GeometryCollection":for(o=0;o<a.geometries.length;o++)if(!1===me(a.geometries[o],t))return!1;break;default:throw new Error("Unknown Geometry Type")}}}}}function ve(e,t={}){let r=0,o=0,n=0;return me(e,function(e){r+=e[0],o+=e[1],n++}),F([r/n,o/n],t.properties)}function Me(e){if(!e)throw new Error("coord is required");if(!Array.isArray(e)){if("Feature"===e.type&&null!==e.geometry&&"Point"===e.geometry.type)return[...e.geometry.coordinates];if("Point"===e.type)return[...e.coordinates]}if(Array.isArray(e)&&e.length>=2&&!Array.isArray(e[0])&&!Array.isArray(e[1]))return[...e];throw new Error("coord must be GeoJSON Point or an Array of numbers")}function be(e){if(Array.isArray(e))return e;if("Feature"===e.type){if(null!==e.geometry)return e.geometry.coordinates}else if(e.coordinates)return e.coordinates;throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array")}function we(e){return"Feature"===e.type?e.geometry:e}function Pe(e,t){return"FeatureCollection"===e.type?"FeatureCollection":"GeometryCollection"===e.type?"GeometryCollection":"Feature"===e.type&&null!==e.geometry?e.geometry.type:e.type}function Le(e,t,r){if(null!==e)for(var o,n,i,a,s,l,c,u,h=0,g=0,d=e.type,p="FeatureCollection"===d,f="Feature"===d,y=p?e.features.length:1,m=0;m<y;m++){s=(u=!!(c=p?e.features[m].geometry:f?e.geometry:e)&&"GeometryCollection"===c.type)?c.geometries.length:1;for(var v=0;v<s;v++){var M=0,b=0;if(null!==(a=u?c.geometries[v]:c)){l=a.coordinates;var w=a.type;switch(h=0,w){case null:break;case"Point":if(!1===t(l,g,m,M,b))return!1;g++,M++;break;case"LineString":case"MultiPoint":for(o=0;o<l.length;o++){if(!1===t(l[o],g,m,M,b))return!1;g++,"MultiPoint"===w&&M++}"LineString"===w&&M++;break;case"Polygon":case"MultiLineString":for(o=0;o<l.length;o++){for(n=0;n<l[o].length-h;n++){if(!1===t(l[o][n],g,m,M,b))return!1;g++}"MultiLineString"===w&&M++,"Polygon"===w&&b++}"Polygon"===w&&M++;break;case"MultiPolygon":for(o=0;o<l.length;o++){for(b=0,n=0;n<l[o].length;n++){for(i=0;i<l[o][n].length-h;i++){if(!1===t(l[o][n][i],g,m,M,b))return!1;g++}b++}M++}break;case"GeometryCollection":for(o=0;o<a.geometries.length;o++)if(!1===Le(a.geometries[o],t))return!1;break;default:throw new Error("Unknown Geometry Type")}}}}}var ke=function e(t,r={}){switch(Pe(t)){case"Point":return F(Me(t),r.properties);case"Polygon":var o=[];Le(t,function(e){o.push(e)});var n,i,a,s,l,c,u,h,g=ve(t,{properties:r.properties}),d=g.geometry.coordinates,p=0,f=0,y=0,m=o.map(function(e){return[e[0]-d[0],e[1]-d[1]]});for(n=0;n<o.length-1;n++)s=(i=m[n])[0],c=i[1],l=(a=m[n+1])[0],y+=h=s*(u=a[1])-l*c,p+=(s+l)*h,f+=(c+u)*h;if(0===y)return g;var v=1/(6*(.5*y));return F([d[0]+v*p,d[1]+v*f],r.properties);default:var M=fe(t);return M?e(M,{properties:r.properties}):ve(t,{properties:r.properties})}};let Ee=class{constructor(e=[],t=xe){if(this.data=e,this.length=this.data.length,this.compare=t,this.length>0)for(let r=(this.length>>1)-1;r>=0;r--)this._down(r)}push(e){this.data.push(e),this.length++,this._up(this.length-1)}pop(){if(0===this.length)return;const e=this.data[0],t=this.data.pop();return this.length--,this.length>0&&(this.data[0]=t,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:t,compare:r}=this,o=t[e];for(;e>0;){const n=e-1>>1,i=t[n];if(r(o,i)>=0)break;t[e]=i,e=n}t[e]=o}_down(e){const{data:t,compare:r}=this,o=this.length>>1,n=t[e];for(;e<o;){let o=1+(e<<1),i=t[o];const a=o+1;if(a<this.length&&r(t[a],i)<0&&(o=a,i=t[a]),r(i,n)>=0)break;t[e]=i,e=o}t[e]=n}};function xe(e,t){return e<t?-1:e>t?1:0}function Se(e,t){return e.p.x>t.p.x?1:e.p.x<t.p.x?-1:e.p.y!==t.p.y?e.p.y>t.p.y?1:-1:1}function De(e,t){return e.rightSweepEvent.p.x>t.rightSweepEvent.p.x?1:e.rightSweepEvent.p.x<t.rightSweepEvent.p.x?-1:e.rightSweepEvent.p.y!==t.rightSweepEvent.p.y?e.rightSweepEvent.p.y<t.rightSweepEvent.p.y?1:-1:1}let Ce=class{constructor(e,t,r,o){this.p={x:e[0],y:e[1]},this.featureId=t,this.ringId=r,this.eventId=o,this.otherEvent=null,this.isLeftEndpoint=null}isSamePoint(e){return this.p.x===e.p.x&&this.p.y===e.p.y}};let Ie=0,Ae=0,Fe=0;function Oe(e,t){const r="Feature"===e.type?e.geometry:e;let o=r.coordinates;"Polygon"!==r.type&&"MultiLineString"!==r.type||(o=[o]),"LineString"===r.type&&(o=[[o]]);for(let n=0;n<o.length;n++)for(let e=0;e<o[n].length;e++){let r=o[n][e][0],i=null;Ae+=1;for(let a=0;a<o[n][e].length-1;a++){i=o[n][e][a+1];const s=new Ce(r,Ie,Ae,Fe),l=new Ce(i,Ie,Ae,Fe+1);s.otherEvent=l,l.otherEvent=s,Se(s,l)>0?(l.isLeftEndpoint=!0,s.isLeftEndpoint=!1):(s.isLeftEndpoint=!0,l.isLeftEndpoint=!1),t.push(s),t.push(l),r=i,Fe+=1}}Ie+=1}let Te=class{constructor(e){this.leftSweepEvent=e,this.rightSweepEvent=e.otherEvent}};function _e(e,t){if(null===e||null===t)return!1;if(e.leftSweepEvent.ringId===t.leftSweepEvent.ringId&&(e.rightSweepEvent.isSamePoint(t.leftSweepEvent)||e.rightSweepEvent.isSamePoint(t.leftSweepEvent)||e.rightSweepEvent.isSamePoint(t.rightSweepEvent)||e.leftSweepEvent.isSamePoint(t.leftSweepEvent)||e.leftSweepEvent.isSamePoint(t.rightSweepEvent)))return!1;const r=e.leftSweepEvent.p.x,o=e.leftSweepEvent.p.y,n=e.rightSweepEvent.p.x,i=e.rightSweepEvent.p.y,a=t.leftSweepEvent.p.x,s=t.leftSweepEvent.p.y,l=t.rightSweepEvent.p.x,c=t.rightSweepEvent.p.y,u=(c-s)*(n-r)-(l-a)*(i-o),h=(l-a)*(o-s)-(c-s)*(r-a),g=(n-r)*(o-s)-(i-o)*(r-a);if(0===u)return!1;const d=h/u,p=g/u;if(d>=0&&d<=1&&p>=0&&p<=1){return[r+d*(n-r),o+d*(i-o)]}return!1}var Ge=function(e,t){const r=new Ee([],Se);return function(e,t){if("FeatureCollection"===e.type){const r=e.features;for(let e=0;e<r.length;e++)Oe(r[e],t)}else Oe(e,t)}(e,r),function(e,t){t=t||!1;const r=[],o=new Ee([],De);for(;e.length;){const n=e.pop();if(n.isLeftEndpoint){const e=new Te(n);for(let i=0;i<o.data.length;i++){const a=o.data[i];if(t&&a.leftSweepEvent.featureId===n.featureId)continue;const s=_e(e,a);!1!==s&&r.push(s)}o.push(e)}else!1===n.isLeftEndpoint&&o.pop()}return r}(r,t)};function He(e,t,r={}){const{removeDuplicates:o=!0,ignoreSelfIntersections:n=!0}=r;let i=[];"FeatureCollection"===e.type?i=i.concat(e.features):"Feature"===e.type?i.push(e):"LineString"!==e.type&&"Polygon"!==e.type&&"MultiLineString"!==e.type&&"MultiPolygon"!==e.type||i.push(A(e)),"FeatureCollection"===t.type?i=i.concat(t.features):"Feature"===t.type?i.push(t):"LineString"!==t.type&&"Polygon"!==t.type&&"MultiLineString"!==t.type&&"MultiPolygon"!==t.type||i.push(A(t));const a=Ge(_(i),n);let s=[];if(o){const e={};a.forEach(t=>{const r=t.join(",");e[r]||(e[r]=!0,s.push(t))})}else s=a;return _(s.map(e=>F(e)))}var Be=He,ze=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Ne=Math.ceil,Ue=Math.floor,Re="[BigNumber Error] ",Xe=Re+"Number primitive has more than 15 significant digits: ",Ye=1e14,Ve=14,qe=9007199254740991,je=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],We=1e7,$e=1e9;function Ke(e){var t=0|e;return e>0||e===t?t:t-1}function Je(e){for(var t,r,o=1,n=e.length,i=e[0]+"";o<n;){for(t=e[o++]+"",r=Ve-t.length;r--;t="0"+t);i+=t}for(n=i.length;48===i.charCodeAt(--n););return i.slice(0,n+1||1)}function Ze(e,t){var r,o,n=e.c,i=t.c,a=e.s,s=t.s,l=e.e,c=t.e;if(!a||!s)return null;if(r=n&&!n[0],o=i&&!i[0],r||o)return r?o?0:-s:a;if(a!=s)return a;if(r=a<0,o=l==c,!n||!i)return o?0:!n^r?1:-1;if(!o)return l>c^r?1:-1;for(s=(l=n.length)<(c=i.length)?l:c,a=0;a<s;a++)if(n[a]!=i[a])return n[a]>i[a]^r?1:-1;return l==c?0:l>c^r?1:-1}function Qe(e,t,r,o){if(e<t||e>r||e!==Ue(e))throw Error(Re+(o||"Argument")+("number"==typeof e?e<t||e>r?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function et(e){var t=e.c.length-1;return Ke(e.e/Ve)==t&&e.c[t]%2!=0}function tt(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function rt(e,t,r){var o,n;if(t<0){for(n=r+".";++t;n+=r);e=n+e}else if(++t>(o=e.length)){for(n=r,t-=o;--t;n+=r);e+=n}else t<o&&(e=e.slice(0,t)+"."+e.slice(t));return e}var ot=function e(t){var r,o,n,i,a,s=w.prototype={constructor:w,toString:null,valueOf:null},l=new w(1),c=20,u=4,h=-7,g=21,d=-1e7,p=1e7,f=!1,y=1,m=0,v={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:" ",suffix:""},M="0123456789abcdefghijklmnopqrstuvwxyz",b=!0;function w(e,t){var r,i,a,s,l,h,g,f,y=this;if(!(y instanceof w))return new w(e,t);if(null==t){if(e&&!0===e._isBigNumber)return y.s=e.s,void(!e.c||e.e>p?y.c=y.e=null:e.e<d?y.c=[y.e=0]:(y.e=e.e,y.c=e.c.slice()));if((h="number"==typeof e)&&0*e==0){if(y.s=1/e<0?(e=-e,-1):1,e===~~e){for(s=0,l=e;l>=10;l/=10,s++);return void(s>p?y.c=y.e=null:(y.e=s,y.c=[e]))}f=String(e)}else{if(!ze.test(f=String(e)))return n(y,f,h);y.s=45==f.charCodeAt(0)?(f=f.slice(1),-1):1}(s=f.indexOf("."))>-1&&(f=f.replace(".","")),(l=f.search(/e/i))>0?(s<0&&(s=l),s+=+f.slice(l+1),f=f.substring(0,l)):s<0&&(s=f.length)}else{if(Qe(t,2,M.length,"Base"),10==t&&b)return E(y=new w(e),c+y.e+1,u);if(f=String(e),h="number"==typeof e){if(0*e!=0)return n(y,f,h,t);if(y.s=1/e<0?(f=f.slice(1),-1):1,w.DEBUG&&f.replace(/^0\.0*|\./,"").length>15)throw Error(Xe+e)}else y.s=45===f.charCodeAt(0)?(f=f.slice(1),-1):1;for(r=M.slice(0,t),s=l=0,g=f.length;l<g;l++)if(r.indexOf(i=f.charAt(l))<0){if("."==i){if(l>s){s=g;continue}}else if(!a&&(f==f.toUpperCase()&&(f=f.toLowerCase())||f==f.toLowerCase()&&(f=f.toUpperCase()))){a=!0,l=-1,s=0;continue}return n(y,String(e),h,t)}h=!1,(s=(f=o(f,t,10,y.s)).indexOf("."))>-1?f=f.replace(".",""):s=f.length}for(l=0;48===f.charCodeAt(l);l++);for(g=f.length;48===f.charCodeAt(--g););if(f=f.slice(l,++g)){if(g-=l,h&&w.DEBUG&&g>15&&(e>qe||e!==Ue(e)))throw Error(Xe+y.s*e);if((s=s-l-1)>p)y.c=y.e=null;else if(s<d)y.c=[y.e=0];else{if(y.e=s,y.c=[],l=(s+1)%Ve,s<0&&(l+=Ve),l<g){for(l&&y.c.push(+f.slice(0,l)),g-=Ve;l<g;)y.c.push(+f.slice(l,l+=Ve));l=Ve-(f=f.slice(l)).length}else l-=g;for(;l--;f+="0");y.c.push(+f)}}else y.c=[y.e=0]}function P(e,t,r,o){var n,i,a,s,l;if(null==r?r=u:Qe(r,0,8),!e.c)return e.toString();if(n=e.c[0],a=e.e,null==t)l=Je(e.c),l=1==o||2==o&&(a<=h||a>=g)?tt(l,a):rt(l,a,"0");else if(i=(e=E(new w(e),t,r)).e,s=(l=Je(e.c)).length,1==o||2==o&&(t<=i||i<=h)){for(;s<t;l+="0",s++);l=tt(l,i)}else if(t-=a+(2===o&&i>a),l=rt(l,i,"0"),i+1>s){if(--t>0)for(l+=".";t--;l+="0");}else if((t+=i-s)>0)for(i+1==s&&(l+=".");t--;l+="0");return e.s<0&&n?"-"+l:l}function L(e,t){for(var r,o,n=1,i=new w(e[0]);n<e.length;n++)(!(o=new w(e[n])).s||(r=Ze(i,o))===t||0===r&&i.s===t)&&(i=o);return i}function k(e,t,r){for(var o=1,n=t.length;!t[--n];t.pop());for(n=t[0];n>=10;n/=10,o++);return(r=o+r*Ve-1)>p?e.c=e.e=null:r<d?e.c=[e.e=0]:(e.e=r,e.c=t),e}function E(e,t,r,o){var n,i,a,s,l,c,u,h=e.c,g=je;if(h){e:{for(n=1,s=h[0];s>=10;s/=10,n++);if((i=t-n)<0)i+=Ve,a=t,l=h[c=0],u=Ue(l/g[n-a-1]%10);else if((c=Ne((i+1)/Ve))>=h.length){if(!o)break e;for(;h.length<=c;h.push(0));l=u=0,n=1,a=(i%=Ve)-Ve+1}else{for(l=s=h[c],n=1;s>=10;s/=10,n++);u=(a=(i%=Ve)-Ve+n)<0?0:Ue(l/g[n-a-1]%10)}if(o=o||t<0||null!=h[c+1]||(a<0?l:l%g[n-a-1]),o=r<4?(u||o)&&(0==r||r==(e.s<0?3:2)):u>5||5==u&&(4==r||o||6==r&&(i>0?a>0?l/g[n-a]:0:h[c-1])%10&1||r==(e.s<0?8:7)),t<1||!h[0])return h.length=0,o?(t-=e.e+1,h[0]=g[(Ve-t%Ve)%Ve],e.e=-t||0):h[0]=e.e=0,e;if(0==i?(h.length=c,s=1,c--):(h.length=c+1,s=g[Ve-i],h[c]=a>0?Ue(l/g[n-a]%g[a])*s:0),o)for(;;){if(0==c){for(i=1,a=h[0];a>=10;a/=10,i++);for(a=h[0]+=s,s=1;a>=10;a/=10,s++);i!=s&&(e.e++,h[0]==Ye&&(h[0]=1));break}if(h[c]+=s,h[c]!=Ye)break;h[c--]=0,s=1}for(i=h.length;0===h[--i];h.pop());}e.e>p?e.c=e.e=null:e.e<d&&(e.c=[e.e=0])}return e}function x(e){var t,r=e.e;return null===r?e.toString():(t=Je(e.c),t=r<=h||r>=g?tt(t,r):rt(t,r,"0"),e.s<0?"-"+t:t)}return w.clone=e,w.ROUND_UP=0,w.ROUND_DOWN=1,w.ROUND_CEIL=2,w.ROUND_FLOOR=3,w.ROUND_HALF_UP=4,w.ROUND_HALF_DOWN=5,w.ROUND_HALF_EVEN=6,w.ROUND_HALF_CEIL=7,w.ROUND_HALF_FLOOR=8,w.EUCLID=9,w.config=w.set=function(e){var t,r;if(null!=e){if("object"!=typeof e)throw Error(Re+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(Qe(r=e[t],0,$e,t),c=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(Qe(r=e[t],0,8,t),u=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((r=e[t])&&r.pop?(Qe(r[0],-$e,0,t),Qe(r[1],0,$e,t),h=r[0],g=r[1]):(Qe(r,-$e,$e,t),h=-(g=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if((r=e[t])&&r.pop)Qe(r[0],-$e,-1,t),Qe(r[1],1,$e,t),d=r[0],p=r[1];else{if(Qe(r,-$e,$e,t),!r)throw Error(Re+t+" cannot be zero: "+r);d=-(p=r<0?-r:r)}if(e.hasOwnProperty(t="CRYPTO")){if((r=e[t])!==!!r)throw Error(Re+t+" not true or false: "+r);if(r){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw f=!r,Error(Re+"crypto unavailable");f=r}else f=r}if(e.hasOwnProperty(t="MODULO_MODE")&&(Qe(r=e[t],0,9,t),y=r),e.hasOwnProperty(t="POW_PRECISION")&&(Qe(r=e[t],0,$e,t),m=r),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(r=e[t]))throw Error(Re+t+" not an object: "+r);v=r}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(r))throw Error(Re+t+" invalid: "+r);b="0123456789"==r.slice(0,10),M=r}}return{DECIMAL_PLACES:c,ROUNDING_MODE:u,EXPONENTIAL_AT:[h,g],RANGE:[d,p],CRYPTO:f,MODULO_MODE:y,POW_PRECISION:m,FORMAT:v,ALPHABET:M}},w.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!w.DEBUG)return!0;var t,r,o=e.c,n=e.e,i=e.s;e:if("[object Array]"=={}.toString.call(o)){if((1===i||-1===i)&&n>=-$e&&n<=$e&&n===Ue(n)){if(0===o[0]){if(0===n&&1===o.length)return!0;break e}if((t=(n+1)%Ve)<1&&(t+=Ve),String(o[0]).length==t){for(t=0;t<o.length;t++)if((r=o[t])<0||r>=Ye||r!==Ue(r))break e;if(0!==r)return!0}}}else if(null===o&&null===n&&(null===i||1===i||-1===i))return!0;throw Error(Re+"Invalid BigNumber: "+e)},w.maximum=w.max=function(){return L(arguments,-1)},w.minimum=w.min=function(){return L(arguments,1)},w.random=(i=9007199254740992,a=Math.random()*i&2097151?function(){return Ue(Math.random()*i)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,r,o,n,i,s=0,u=[],h=new w(l);if(null==e?e=c:Qe(e,0,$e),n=Ne(e/Ve),f)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(n*=2));s<n;)(i=131072*t[s]+(t[s+1]>>>11))>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),t[s]=r[0],t[s+1]=r[1]):(u.push(i%1e14),s+=2);s=n/2}else{if(!crypto.randomBytes)throw f=!1,Error(Re+"crypto unavailable");for(t=crypto.randomBytes(n*=7);s<n;)(i=281474976710656*(31&t[s])+1099511627776*t[s+1]+4294967296*t[s+2]+16777216*t[s+3]+(t[s+4]<<16)+(t[s+5]<<8)+t[s+6])>=9e15?crypto.randomBytes(7).copy(t,s):(u.push(i%1e14),s+=7);s=n/7}if(!f)for(;s<n;)(i=a())<9e15&&(u[s++]=i%1e14);for(n=u[--s],e%=Ve,n&&e&&(i=je[Ve-e],u[s]=Ue(n/i)*i);0===u[s];u.pop(),s--);if(s<0)u=[o=0];else{for(o=-1;0===u[0];u.splice(0,1),o-=Ve);for(s=1,i=u[0];i>=10;i/=10,s++);s<Ve&&(o-=Ve-s)}return h.e=o,h.c=u,h}),w.sum=function(){for(var e=1,t=arguments,r=new w(t[0]);e<t.length;)r=r.plus(t[e++]);return r},o=function(){var e="0123456789";function t(e,t,r,o){for(var n,i,a=[0],s=0,l=e.length;s<l;){for(i=a.length;i--;a[i]*=t);for(a[0]+=o.indexOf(e.charAt(s++)),n=0;n<a.length;n++)a[n]>r-1&&(null==a[n+1]&&(a[n+1]=0),a[n+1]+=a[n]/r|0,a[n]%=r)}return a.reverse()}return function(o,n,i,a,s){var l,h,g,d,p,f,y,v,b=o.indexOf("."),P=c,L=u;for(b>=0&&(d=m,m=0,o=o.replace(".",""),f=(v=new w(n)).pow(o.length-b),m=d,v.c=t(rt(Je(f.c),f.e,"0"),10,i,e),v.e=v.c.length),g=d=(y=t(o,n,i,s?(l=M,e):(l=e,M))).length;0==y[--d];y.pop());if(!y[0])return l.charAt(0);if(b<0?--g:(f.c=y,f.e=g,f.s=a,y=(f=r(f,v,P,L,i)).c,p=f.r,g=f.e),b=y[h=g+P+1],d=i/2,p=p||h<0||null!=y[h+1],p=L<4?(null!=b||p)&&(0==L||L==(f.s<0?3:2)):b>d||b==d&&(4==L||p||6==L&&1&y[h-1]||L==(f.s<0?8:7)),h<1||!y[0])o=p?rt(l.charAt(1),-P,l.charAt(0)):l.charAt(0);else{if(y.length=h,p)for(--i;++y[--h]>i;)y[h]=0,h||(++g,y=[1].concat(y));for(d=y.length;!y[--d];);for(b=0,o="";b<=d;o+=l.charAt(y[b++]));o=rt(o,g,l.charAt(0))}return o}}(),r=function(){function e(e,t,r){var o,n,i,a,s=0,l=e.length,c=t%We,u=t/We|0;for(e=e.slice();l--;)s=((n=c*(i=e[l]%We)+(o=u*i+(a=e[l]/We|0)*c)%We*We+s)/r|0)+(o/We|0)+u*a,e[l]=n%r;return s&&(e=[s].concat(e)),e}function t(e,t,r,o){var n,i;if(r!=o)i=r>o?1:-1;else for(n=i=0;n<r;n++)if(e[n]!=t[n]){i=e[n]>t[n]?1:-1;break}return i}function r(e,t,r,o){for(var n=0;r--;)e[r]-=n,n=e[r]<t[r]?1:0,e[r]=n*o+e[r]-t[r];for(;!e[0]&&e.length>1;e.splice(0,1));}return function(o,n,i,a,s){var l,c,u,h,g,d,p,f,y,m,v,M,b,P,L,k,x,S=o.s==n.s?1:-1,D=o.c,C=n.c;if(!(D&&D[0]&&C&&C[0]))return new w(o.s&&n.s&&(D?!C||D[0]!=C[0]:C)?D&&0==D[0]||!C?0*S:S/0:NaN);for(y=(f=new w(S)).c=[],S=i+(c=o.e-n.e)+1,s||(s=Ye,c=Ke(o.e/Ve)-Ke(n.e/Ve),S=S/Ve|0),u=0;C[u]==(D[u]||0);u++);if(C[u]>(D[u]||0)&&c--,S<0)y.push(1),h=!0;else{for(P=D.length,k=C.length,u=0,S+=2,(g=Ue(s/(C[0]+1)))>1&&(C=e(C,g,s),D=e(D,g,s),k=C.length,P=D.length),b=k,v=(m=D.slice(0,k)).length;v<k;m[v++]=0);x=C.slice(),x=[0].concat(x),L=C[0],C[1]>=s/2&&L++;do{if(g=0,(l=t(C,m,k,v))<0){if(M=m[0],k!=v&&(M=M*s+(m[1]||0)),(g=Ue(M/L))>1)for(g>=s&&(g=s-1),p=(d=e(C,g,s)).length,v=m.length;1==t(d,m,p,v);)g--,r(d,k<p?x:C,p,s),p=d.length,l=1;else 0==g&&(l=g=1),p=(d=C.slice()).length;if(p<v&&(d=[0].concat(d)),r(m,d,v,s),v=m.length,-1==l)for(;t(C,m,k,v)<1;)g++,r(m,k<v?x:C,v,s),v=m.length}else 0===l&&(g++,m=[0]);y[u++]=g,m[0]?m[v++]=D[b]||0:(m=[D[b]],v=1)}while((b++<P||null!=m[0])&&S--);h=null!=m[0],y[0]||y.splice(0,1)}if(s==Ye){for(u=1,S=y[0];S>=10;S/=10,u++);E(f,i+(f.e=u+c*Ve-1)+1,a,h)}else f.e=c,f.r=+h;return f}}(),n=function(){var e=/^(-?)0([xbo])(?=\w[\w.]*$)/i,t=/^([^.]+)\.$/,r=/^\.([^.]+)$/,o=/^-?(Infinity|NaN)$/,n=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(i,a,s,l){var c,u=s?a:a.replace(n,"");if(o.test(u))i.s=isNaN(u)?null:u<0?-1:1;else{if(!s&&(u=u.replace(e,function(e,t,r){return c="x"==(r=r.toLowerCase())?16:"b"==r?2:8,l&&l!=c?e:t}),l&&(c=l,u=u.replace(t,"$1").replace(r,"0.$1")),a!=u))return new w(u,c);if(w.DEBUG)throw Error(Re+"Not a"+(l?" base "+l:"")+" number: "+a);i.s=null}i.c=i.e=null}}(),s.absoluteValue=s.abs=function(){var e=new w(this);return e.s<0&&(e.s=1),e},s.comparedTo=function(e,t){return Ze(this,new w(e,t))},s.decimalPlaces=s.dp=function(e,t){var r,o,n,i=this;if(null!=e)return Qe(e,0,$e),null==t?t=u:Qe(t,0,8),E(new w(i),e+i.e+1,t);if(!(r=i.c))return null;if(o=((n=r.length-1)-Ke(this.e/Ve))*Ve,n=r[n])for(;n%10==0;n/=10,o--);return o<0&&(o=0),o},s.dividedBy=s.div=function(e,t){return r(this,new w(e,t),c,u)},s.dividedToIntegerBy=s.idiv=function(e,t){return r(this,new w(e,t),0,1)},s.exponentiatedBy=s.pow=function(e,t){var r,o,n,i,a,s,c,h,g=this;if((e=new w(e)).c&&!e.isInteger())throw Error(Re+"Exponent not an integer: "+x(e));if(null!=t&&(t=new w(t)),a=e.e>14,!g.c||!g.c[0]||1==g.c[0]&&!g.e&&1==g.c.length||!e.c||!e.c[0])return h=new w(Math.pow(+x(g),a?e.s*(2-et(e)):+x(e))),t?h.mod(t):h;if(s=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new w(NaN);(o=!s&&g.isInteger()&&t.isInteger())&&(g=g.mod(t))}else{if(e.e>9&&(g.e>0||g.e<-1||(0==g.e?g.c[0]>1||a&&g.c[1]>=24e7:g.c[0]<8e13||a&&g.c[0]<=9999975e7)))return i=g.s<0&&et(e)?-0:0,g.e>-1&&(i=1/i),new w(s?1/i:i);m&&(i=Ne(m/Ve+2))}for(a?(r=new w(.5),s&&(e.s=1),c=et(e)):c=(n=Math.abs(+x(e)))%2,h=new w(l);;){if(c){if(!(h=h.times(g)).c)break;i?h.c.length>i&&(h.c.length=i):o&&(h=h.mod(t))}if(n){if(0===(n=Ue(n/2)))break;c=n%2}else if(E(e=e.times(r),e.e+1,1),e.e>14)c=et(e);else{if(0===(n=+x(e)))break;c=n%2}g=g.times(g),i?g.c&&g.c.length>i&&(g.c.length=i):o&&(g=g.mod(t))}return o?h:(s&&(h=l.div(h)),t?h.mod(t):i?E(h,m,u,void 0):h)},s.integerValue=function(e){var t=new w(this);return null==e?e=u:Qe(e,0,8),E(t,t.e+1,e)},s.isEqualTo=s.eq=function(e,t){return 0===Ze(this,new w(e,t))},s.isFinite=function(){return!!this.c},s.isGreaterThan=s.gt=function(e,t){return Ze(this,new w(e,t))>0},s.isGreaterThanOrEqualTo=s.gte=function(e,t){return 1===(t=Ze(this,new w(e,t)))||0===t},s.isInteger=function(){return!!this.c&&Ke(this.e/Ve)>this.c.length-2},s.isLessThan=s.lt=function(e,t){return Ze(this,new w(e,t))<0},s.isLessThanOrEqualTo=s.lte=function(e,t){return-1===(t=Ze(this,new w(e,t)))||0===t},s.isNaN=function(){return!this.s},s.isNegative=function(){return this.s<0},s.isPositive=function(){return this.s>0},s.isZero=function(){return!!this.c&&0==this.c[0]},s.minus=function(e,t){var r,o,n,i,a=this,s=a.s;if(t=(e=new w(e,t)).s,!s||!t)return new w(NaN);if(s!=t)return e.s=-t,a.plus(e);var l=a.e/Ve,c=e.e/Ve,h=a.c,g=e.c;if(!l||!c){if(!h||!g)return h?(e.s=-t,e):new w(g?a:NaN);if(!h[0]||!g[0])return g[0]?(e.s=-t,e):new w(h[0]?a:3==u?-0:0)}if(l=Ke(l),c=Ke(c),h=h.slice(),s=l-c){for((i=s<0)?(s=-s,n=h):(c=l,n=g),n.reverse(),t=s;t--;n.push(0));n.reverse()}else for(o=(i=(s=h.length)<(t=g.length))?s:t,s=t=0;t<o;t++)if(h[t]!=g[t]){i=h[t]<g[t];break}if(i&&(n=h,h=g,g=n,e.s=-e.s),(t=(o=g.length)-(r=h.length))>0)for(;t--;h[r++]=0);for(t=Ye-1;o>s;){if(h[--o]<g[o]){for(r=o;r&&!h[--r];h[r]=t);--h[r],h[o]+=Ye}h[o]-=g[o]}for(;0==h[0];h.splice(0,1),--c);return h[0]?k(e,h,c):(e.s=3==u?-1:1,e.c=[e.e=0],e)},s.modulo=s.mod=function(e,t){var o,n,i=this;return e=new w(e,t),!i.c||!e.s||e.c&&!e.c[0]?new w(NaN):!e.c||i.c&&!i.c[0]?new w(i):(9==y?(n=e.s,e.s=1,o=r(i,e,0,3),e.s=n,o.s*=n):o=r(i,e,0,y),(e=i.minus(o.times(e))).c[0]||1!=y||(e.s=i.s),e)},s.multipliedBy=s.times=function(e,t){var r,o,n,i,a,s,l,c,u,h,g,d,p,f,y,m=this,v=m.c,M=(e=new w(e,t)).c;if(!(v&&M&&v[0]&&M[0]))return!m.s||!e.s||v&&!v[0]&&!M||M&&!M[0]&&!v?e.c=e.e=e.s=null:(e.s*=m.s,v&&M?(e.c=[0],e.e=0):e.c=e.e=null),e;for(o=Ke(m.e/Ve)+Ke(e.e/Ve),e.s*=m.s,(l=v.length)<(h=M.length)&&(p=v,v=M,M=p,n=l,l=h,h=n),n=l+h,p=[];n--;p.push(0));for(f=Ye,y=We,n=h;--n>=0;){for(r=0,g=M[n]%y,d=M[n]/y|0,i=n+(a=l);i>n;)r=((c=g*(c=v[--a]%y)+(s=d*c+(u=v[a]/y|0)*g)%y*y+p[i]+r)/f|0)+(s/y|0)+d*u,p[i--]=c%f;p[i]=r}return r?++o:p.splice(0,1),k(e,p,o)},s.negated=function(){var e=new w(this);return e.s=-e.s||null,e},s.plus=function(e,t){var r,o=this,n=o.s;if(t=(e=new w(e,t)).s,!n||!t)return new w(NaN);if(n!=t)return e.s=-t,o.minus(e);var i=o.e/Ve,a=e.e/Ve,s=o.c,l=e.c;if(!i||!a){if(!s||!l)return new w(n/0);if(!s[0]||!l[0])return l[0]?e:new w(s[0]?o:0*n)}if(i=Ke(i),a=Ke(a),s=s.slice(),n=i-a){for(n>0?(a=i,r=l):(n=-n,r=s),r.reverse();n--;r.push(0));r.reverse()}for((n=s.length)-(t=l.length)<0&&(r=l,l=s,s=r,t=n),n=0;t;)n=(s[--t]=s[t]+l[t]+n)/Ye|0,s[t]=Ye===s[t]?0:s[t]%Ye;return n&&(s=[n].concat(s),++a),k(e,s,a)},s.precision=s.sd=function(e,t){var r,o,n,i=this;if(null!=e&&e!==!!e)return Qe(e,1,$e),null==t?t=u:Qe(t,0,8),E(new w(i),e,t);if(!(r=i.c))return null;if(o=(n=r.length-1)*Ve+1,n=r[n]){for(;n%10==0;n/=10,o--);for(n=r[0];n>=10;n/=10,o++);}return e&&i.e+1>o&&(o=i.e+1),o},s.shiftedBy=function(e){return Qe(e,-9007199254740991,qe),this.times("1e"+e)},s.squareRoot=s.sqrt=function(){var e,t,o,n,i,a=this,s=a.c,l=a.s,h=a.e,g=c+4,d=new w("0.5");if(1!==l||!s||!s[0])return new w(!l||l<0&&(!s||s[0])?NaN:s?a:1/0);if(0==(l=Math.sqrt(+x(a)))||l==1/0?(((t=Je(s)).length+h)%2==0&&(t+="0"),l=Math.sqrt(+t),h=Ke((h+1)/2)-(h<0||h%2),o=new w(t=l==1/0?"5e"+h:(t=l.toExponential()).slice(0,t.indexOf("e")+1)+h)):o=new w(l+""),o.c[0])for((l=(h=o.e)+g)<3&&(l=0);;)if(i=o,o=d.times(i.plus(r(a,i,g,1))),Je(i.c).slice(0,l)===(t=Je(o.c)).slice(0,l)){if(o.e<h&&--l,"9999"!=(t=t.slice(l-3,l+1))&&(n||"4999"!=t)){+t&&(+t.slice(1)||"5"!=t.charAt(0))||(E(o,o.e+c+2,1),e=!o.times(o).eq(a));break}if(!n&&(E(i,i.e+c+2,0),i.times(i).eq(a))){o=i;break}g+=4,l+=4,n=1}return E(o,o.e+c+1,u,e)},s.toExponential=function(e,t){return null!=e&&(Qe(e,0,$e),e++),P(this,e,t,1)},s.toFixed=function(e,t){return null!=e&&(Qe(e,0,$e),e=e+this.e+1),P(this,e,t)},s.toFormat=function(e,t,r){var o,n=this;if(null==r)null!=e&&t&&"object"==typeof t?(r=t,t=null):e&&"object"==typeof e?(r=e,e=t=null):r=v;else if("object"!=typeof r)throw Error(Re+"Argument not an object: "+r);if(o=n.toFixed(e,t),n.c){var i,a=o.split("."),s=+r.groupSize,l=+r.secondaryGroupSize,c=r.groupSeparator||"",u=a[0],h=a[1],g=n.s<0,d=g?u.slice(1):u,p=d.length;if(l&&(i=s,s=l,l=i,p-=i),s>0&&p>0){for(i=p%s||s,u=d.substr(0,i);i<p;i+=s)u+=c+d.substr(i,s);l>0&&(u+=c+d.slice(i)),g&&(u="-"+u)}o=h?u+(r.decimalSeparator||"")+((l=+r.fractionGroupSize)?h.replace(new RegExp("\\d{"+l+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):h):u}return(r.prefix||"")+o+(r.suffix||"")},s.toFraction=function(e){var t,o,n,i,a,s,c,h,g,d,f,y,m=this,v=m.c;if(null!=e&&(!(c=new w(e)).isInteger()&&(c.c||1!==c.s)||c.lt(l)))throw Error(Re+"Argument "+(c.isInteger()?"out of range: ":"not an integer: ")+x(c));if(!v)return new w(m);for(t=new w(l),g=o=new w(l),n=h=new w(l),y=Je(v),a=t.e=y.length-m.e-1,t.c[0]=je[(s=a%Ve)<0?Ve+s:s],e=!e||c.comparedTo(t)>0?a>0?t:g:c,s=p,p=1/0,c=new w(y),h.c[0]=0;d=r(c,t,0,1),1!=(i=o.plus(d.times(n))).comparedTo(e);)o=n,n=i,g=h.plus(d.times(i=g)),h=i,t=c.minus(d.times(i=t)),c=i;return i=r(e.minus(o),n,0,1),h=h.plus(i.times(g)),o=o.plus(i.times(n)),h.s=g.s=m.s,f=r(g,n,a*=2,u).minus(m).abs().comparedTo(r(h,o,a,u).minus(m).abs())<1?[g,n]:[h,o],p=s,f},s.toNumber=function(){return+x(this)},s.toPrecision=function(e,t){return null!=e&&Qe(e,1,$e),P(this,e,t,2)},s.toString=function(e){var t,r=this,n=r.s,i=r.e;return null===i?n?(t="Infinity",n<0&&(t="-"+t)):t="NaN":(null==e?t=i<=h||i>=g?tt(Je(r.c),i):rt(Je(r.c),i,"0"):10===e&&b?t=rt(Je((r=E(new w(r),c+i+1,u)).c),r.e,"0"):(Qe(e,2,M.length,"Base"),t=o(rt(Je(r.c),i,"0"),10,e,n,!0)),n<0&&r.c[0]&&(t="-"+t)),t},s.valueOf=s.toJSON=function(){return x(this)},s._isBigNumber=!0,s[Symbol.toStringTag]="BigNumber",s[Symbol.for("nodejs.util.inspect.custom")]=s.valueOf,null!=t&&w.set(t),w}(),nt=class{constructor(e){i(this,"key"),i(this,"left",null),i(this,"right",null),this.key=e}},it=class extends nt{constructor(e){super(e)}},at=class{constructor(){i(this,"size",0),i(this,"modificationCount",0),i(this,"splayCount",0)}splay(e){const t=this.root;if(null==t)return this.compare(e,e),-1;let r=null,o=null,n=null,i=null,a=t;const s=this.compare;let l;for(;;)if(l=s(a.key,e),l>0){let t=a.left;if(null==t)break;if(l=s(t.key,e),l>0&&(a.left=t.right,t.right=a,a=t,t=a.left,null==t))break;null==r?o=a:r.left=a,r=a,a=t}else{if(!(l<0))break;{let t=a.right;if(null==t)break;if(l=s(t.key,e),l<0&&(a.right=t.left,t.left=a,a=t,t=a.right,null==t))break;null==n?i=a:n.right=a,n=a,a=t}}return null!=n&&(n.right=a.left,a.left=i),null!=r&&(r.left=a.right,a.right=o),this.root!==a&&(this.root=a,this.splayCount++),l}splayMin(e){let t=e,r=t.left;for(;null!=r;){const e=r;t.left=e.right,e.right=t,t=e,r=t.left}return t}splayMax(e){let t=e,r=t.right;for(;null!=r;){const e=r;t.right=e.left,e.left=t,t=e,r=t.right}return t}_delete(e){if(null==this.root)return null;if(0!=this.splay(e))return null;let t=this.root;const r=t,o=t.left;if(this.size--,null==o)this.root=t.right;else{const e=t.right;t=this.splayMax(o),t.right=e,this.root=t}return this.modificationCount++,r}addNewRoot(e,t){this.size++,this.modificationCount++;const r=this.root;null!=r?(t<0?(e.left=r,e.right=r.right,r.right=null):(e.right=r,e.left=r.left,r.left=null),this.root=e):this.root=e}_first(){const e=this.root;return null==e?null:(this.root=this.splayMin(e),this.root)}_last(){const e=this.root;return null==e?null:(this.root=this.splayMax(e),this.root)}clear(){this.root=null,this.size=0,this.modificationCount++}has(e){return this.validKey(e)&&0==this.splay(e)}defaultCompare(){return(e,t)=>e<t?-1:e>t?1:0}wrap(){return{getRoot:()=>this.root,setRoot:e=>{this.root=e},getSize:()=>this.size,getModificationCount:()=>this.modificationCount,getSplayCount:()=>this.splayCount,setSplayCount:e=>{this.splayCount=e},splay:e=>this.splay(e),has:e=>this.has(e)}}},st=class e extends at{constructor(e,t){super(),i(this,"root",null),i(this,"compare"),i(this,"validKey"),i(this,r,"[object Set]"),this.compare=e??this.defaultCompare(),this.validKey=t??(e=>null!=e&&null!=e)}delete(e){return!!this.validKey(e)&&null!=this._delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){const t=this[Symbol.iterator]();let r;for(;r=t.next(),!r.done;)e(r.value,r.value,this)}add(e){const t=this.splay(e);return 0!=t&&this.addNewRoot(new it(e),t),this}addAndReturn(e){const t=this.splay(e);return 0!=t&&this.addNewRoot(new it(e),t),this.root.key}addAll(e){for(const t of e)this.add(t)}isEmpty(){return null==this.root}isNotEmpty(){return null!=this.root}single(){if(0==this.size)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}first(){if(0==this.size)throw"Bad state: No element";return this._first().key}last(){if(0==this.size)throw"Bad state: No element";return this._last().key}lastBefore(e){if(null==e)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(e)<0)return this.root.key;let t=this.root.left;if(null==t)return null;let r=t.right;for(;null!=r;)t=r,r=t.right;return t.key}firstAfter(e){if(null==e)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(e)>0)return this.root.key;let t=this.root.right;if(null==t)return null;let r=t.left;for(;null!=r;)t=r,r=t.left;return t.key}retainAll(t){const r=new e(this.compare,this.validKey),o=this.modificationCount;for(const e of t){if(o!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(e)&&0==this.splay(e)&&r.add(this.root.key)}r.size!=this.size&&(this.root=r.root,this.size=r.size,this.modificationCount++)}lookup(e){if(!this.validKey(e))return null;return 0!=this.splay(e)?null:this.root.key}intersection(t){const r=new e(this.compare,this.validKey);for(const e of this)t.has(e)&&r.add(e);return r}difference(t){const r=new e(this.compare,this.validKey);for(const e of this)t.has(e)||r.add(e);return r}union(e){const t=this.clone();return t.addAll(e),t}clone(){const t=new e(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}copyNode(e){if(null==e)return null;const t=new it(e.key);return function e(t,r){let o,n;do{if(o=t.left,n=t.right,null!=o){const t=new it(o.key);r.left=t,e(o,t)}if(null!=n){const e=new it(n.key);r.right=e,t=n,r=e}}while(null!=n)}(e,t),t}toSet(){return this.clone()}entries(){return new ut(this.wrap())}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}[(o=Symbol.iterator,r=Symbol.toStringTag,o)](){return new ct(this.wrap())}},lt=class{constructor(e){i(this,"tree"),i(this,"path",new Array),i(this,"modificationCount",null),i(this,"splayCount"),this.tree=e,this.splayCount=e.getSplayCount()}[Symbol.iterator](){return this}next(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}current(){if(!this.path.length)return null;const e=this.path[this.path.length-1];return this.getValue(e)}rebuildPath(e){this.path.splice(0,this.path.length),this.tree.splay(e),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}findLeftMostDescendent(e){for(;null!=e;)this.path.push(e),e=e.left}moveNext(){if(this.modificationCount!=this.tree.getModificationCount()){if(null==this.modificationCount){this.modificationCount=this.tree.getModificationCount();let e=this.tree.getRoot();for(;null!=e;)this.path.push(e),e=e.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);let e=this.path[this.path.length-1],t=e.right;if(null!=t){for(;null!=t;)this.path.push(t),t=t.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===e;)e=this.path.pop();return this.path.length>0}},ct=class extends lt{getValue(e){return e.key}},ut=class extends lt{getValue(e){return[e.key,e.key]}},ht=e=>()=>e,gt=e=>{const t=e?(t,r)=>r.minus(t).abs().isLessThanOrEqualTo(e):ht(!1);return(e,r)=>t(e,r)?0:e.comparedTo(r)};function dt(e){const t=e?(t,r,o,n,i)=>t.exponentiatedBy(2).isLessThanOrEqualTo(n.minus(r).exponentiatedBy(2).plus(i.minus(o).exponentiatedBy(2)).times(e)):ht(!1);return(e,r,o)=>{const n=e.x,i=e.y,a=o.x,s=o.y,l=i.minus(s).times(r.x.minus(a)).minus(n.minus(a).times(r.y.minus(s)));return t(l,n,i,a,s)?0:l.comparedTo(0)}}var pt=e=>e,ft=e=>{if(e){const t=new st(gt(e)),r=new st(gt(e)),o=(e,t)=>t.addAndReturn(e),n=e=>({x:o(e.x,t),y:o(e.y,r)});return n({x:new ot(0),y:new ot(0)}),n}return pt},yt=e=>({set:e=>{mt=yt(e)},reset:()=>yt(e),compare:gt(e),snap:ft(e),orient:dt(e)}),mt=yt(),vt=(e,t)=>e.ll.x.isLessThanOrEqualTo(t.x)&&t.x.isLessThanOrEqualTo(e.ur.x)&&e.ll.y.isLessThanOrEqualTo(t.y)&&t.y.isLessThanOrEqualTo(e.ur.y),Mt=(e,t)=>{if(t.ur.x.isLessThan(e.ll.x)||e.ur.x.isLessThan(t.ll.x)||t.ur.y.isLessThan(e.ll.y)||e.ur.y.isLessThan(t.ll.y))return null;const r=e.ll.x.isLessThan(t.ll.x)?t.ll.x:e.ll.x,o=e.ur.x.isLessThan(t.ur.x)?e.ur.x:t.ur.x;return{ll:{x:r,y:e.ll.y.isLessThan(t.ll.y)?t.ll.y:e.ll.y},ur:{x:o,y:e.ur.y.isLessThan(t.ur.y)?e.ur.y:t.ur.y}}},bt=(e,t)=>e.x.times(t.y).minus(e.y.times(t.x)),wt=(e,t)=>e.x.times(t.x).plus(e.y.times(t.y)),Pt=e=>wt(e,e).sqrt(),Lt=(e,t,r)=>{const o={x:t.x.minus(e.x),y:t.y.minus(e.y)},n={x:r.x.minus(e.x),y:r.y.minus(e.y)};return bt(n,o).div(Pt(n)).div(Pt(o))},kt=(e,t,r)=>{const o={x:t.x.minus(e.x),y:t.y.minus(e.y)},n={x:r.x.minus(e.x),y:r.y.minus(e.y)};return wt(n,o).div(Pt(n)).div(Pt(o))},Et=(e,t,r)=>t.y.isZero()?null:{x:e.x.plus(t.x.div(t.y).times(r.minus(e.y))),y:r},xt=(e,t,r)=>t.x.isZero()?null:{x:r,y:e.y.plus(t.y.div(t.x).times(r.minus(e.x)))},St=class e{constructor(e,t){i(this,"point"),i(this,"isLeft"),i(this,"segment"),i(this,"otherSE"),i(this,"consumedBy"),void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=t}static compare(t,r){const o=e.comparePoints(t.point,r.point);return 0!==o?o:(t.point!==r.point&&t.link(r),t.isLeft!==r.isLeft?t.isLeft?1:-1:_t.compare(t.segment,r.segment))}static comparePoints(e,t){return e.x.isLessThan(t.x)?-1:e.x.isGreaterThan(t.x)?1:e.y.isLessThan(t.y)?-1:e.y.isGreaterThan(t.y)?1:0}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const t=e.point.events;for(let r=0,o=t.length;r<o;r++){const e=t[r];this.point.events.push(e),e.point=this.point}this.checkForConsuming()}checkForConsuming(){const e=this.point.events.length;for(let t=0;t<e;t++){const r=this.point.events[t];if(void 0===r.segment.consumedBy)for(let o=t+1;o<e;o++){const e=this.point.events[o];void 0===e.consumedBy&&(r.otherSE.point.events===e.otherSE.point.events&&r.segment.consume(e.segment))}}}getAvailableLinkedEvents(){const e=[];for(let t=0,r=this.point.events.length;t<r;t++){const r=this.point.events[t];r!==this&&!r.segment.ringOut&&r.segment.isInResult()&&e.push(r)}return e}getLeftmostComparator(e){const t=new Map,r=r=>{const o=r.otherSE;t.set(r,{sine:Lt(this.point,e.point,o.point),cosine:kt(this.point,e.point,o.point)})};return(e,o)=>{t.has(e)||r(e),t.has(o)||r(o);const{sine:n,cosine:i}=t.get(e),{sine:a,cosine:s}=t.get(o);return n.isGreaterThanOrEqualTo(0)&&a.isGreaterThanOrEqualTo(0)?i.isLessThan(s)?1:i.isGreaterThan(s)?-1:0:n.isLessThan(0)&&a.isLessThan(0)?i.isLessThan(s)?-1:i.isGreaterThan(s)?1:0:a.isLessThan(n)?-1:a.isGreaterThan(n)?1:0}}},Dt=class e{constructor(e){i(this,"events"),i(this,"poly"),i(this,"_isExteriorRing"),i(this,"_enclosingRing"),this.events=e;for(let t=0,r=e.length;t<r;t++)e[t].segment.ringOut=this;this.poly=null}static factory(t){const r=[];for(let o=0,n=t.length;o<n;o++){const n=t[o];if(!n.isInResult()||n.ringOut)continue;let i=null,a=n.leftSE,s=n.rightSE;const l=[a],c=a.point,u=[];for(;i=a,a=s,l.push(a),a.point!==c;)for(;;){const t=a.getAvailableLinkedEvents();if(0===t.length){const e=l[0].point,t=l[l.length-1].point;throw new Error(`Unable to complete output ring starting at [${e.x}, ${e.y}]. Last matching segment found ends at [${t.x}, ${t.y}].`)}if(1===t.length){s=t[0].otherSE;break}let o=null;for(let e=0,r=u.length;e<r;e++)if(u[e].point===a.point){o=e;break}if(null!==o){const t=u.splice(o)[0],n=l.splice(t.index);n.unshift(n[0].otherSE),r.push(new e(n.reverse()));continue}u.push({index:l.length,point:a.point});const n=a.getLeftmostComparator(i);s=t.sort(n)[0].otherSE;break}r.push(new e(l))}return r}getGeom(){let e=this.events[0].point;const t=[e];for(let l=1,c=this.events.length-1;l<c;l++){const r=this.events[l].point,o=this.events[l+1].point;0!==mt.orient(r,e,o)&&(t.push(r),e=r)}if(1===t.length)return null;const r=t[0],o=t[1];0===mt.orient(r,e,o)&&t.shift(),t.push(t[0]);const n=this.isExteriorRing()?1:-1,i=this.isExteriorRing()?0:t.length-1,a=this.isExteriorRing()?t.length:-1,s=[];for(let l=i;l!=a;l+=n)s.push([t[l].x.toNumber(),t[l].y.toNumber()]);return s}isExteriorRing(){if(void 0===this._isExteriorRing){const e=this.enclosingRing();this._isExteriorRing=!e||!e.isExteriorRing()}return this._isExteriorRing}enclosingRing(){return void 0===this._enclosingRing&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){var e,t;let r=this.events[0];for(let i=1,a=this.events.length;i<a;i++){const e=this.events[i];St.compare(r,e)>0&&(r=e)}let o=r.segment.prevInResult(),n=o?o.prevInResult():null;for(;;){if(!o)return null;if(!n)return o.ringOut;if(n.ringOut!==o.ringOut)return(null==(e=n.ringOut)?void 0:e.enclosingRing())!==o.ringOut?o.ringOut:null==(t=o.ringOut)?void 0:t.enclosingRing();o=n.prevInResult(),n=o?o.prevInResult():null}}},Ct=class{constructor(e){i(this,"exteriorRing"),i(this,"interiorRings"),this.exteriorRing=e,e.poly=this,this.interiorRings=[]}addInterior(e){this.interiorRings.push(e),e.poly=this}getGeom(){const e=this.exteriorRing.getGeom();if(null===e)return null;const t=[e];for(let r=0,o=this.interiorRings.length;r<o;r++){const e=this.interiorRings[r].getGeom();null!==e&&t.push(e)}return t}},It=class{constructor(e){i(this,"rings"),i(this,"polys"),this.rings=e,this.polys=this._composePolys(e)}getGeom(){const e=[];for(let t=0,r=this.polys.length;t<r;t++){const r=this.polys[t].getGeom();null!==r&&e.push(r)}return e}_composePolys(e){var t;const r=[];for(let o=0,n=e.length;o<n;o++){const n=e[o];if(!n.poly)if(n.isExteriorRing())r.push(new Ct(n));else{const e=n.enclosingRing();(null==e?void 0:e.poly)||r.push(new Ct(e)),null==(t=null==e?void 0:e.poly)||t.addInterior(n)}}return r}},At=class{constructor(e,t=_t.compare){i(this,"queue"),i(this,"tree"),i(this,"segments"),this.queue=e,this.tree=new st(t),this.segments=[]}process(e){const t=e.segment,r=[];if(e.consumedBy)return e.isLeft?this.queue.delete(e.otherSE):this.tree.delete(t),r;e.isLeft&&this.tree.add(t);let o=t,n=t;do{o=this.tree.lastBefore(o)}while(null!=o&&null!=o.consumedBy);do{n=this.tree.firstAfter(n)}while(null!=n&&null!=n.consumedBy);if(e.isLeft){let i=null;if(o){const e=o.getIntersection(t);if(null!==e&&(t.isAnEndpoint(e)||(i=e),!o.isAnEndpoint(e))){const t=this._splitSafely(o,e);for(let e=0,o=t.length;e<o;e++)r.push(t[e])}}let a=null;if(n){const e=n.getIntersection(t);if(null!==e&&(t.isAnEndpoint(e)||(a=e),!n.isAnEndpoint(e))){const t=this._splitSafely(n,e);for(let e=0,o=t.length;e<o;e++)r.push(t[e])}}if(null!==i||null!==a){let e=null;if(null===i)e=a;else if(null===a)e=i;else{e=St.comparePoints(i,a)<=0?i:a}this.queue.delete(t.rightSE),r.push(t.rightSE);const o=t.split(e);for(let t=0,n=o.length;t<n;t++)r.push(o[t])}r.length>0?(this.tree.delete(t),r.push(e)):(this.segments.push(t),t.prev=o)}else{if(o&&n){const e=o.getIntersection(n);if(null!==e){if(!o.isAnEndpoint(e)){const t=this._splitSafely(o,e);for(let e=0,o=t.length;e<o;e++)r.push(t[e])}if(!n.isAnEndpoint(e)){const t=this._splitSafely(n,e);for(let e=0,o=t.length;e<o;e++)r.push(t[e])}}}this.tree.delete(t)}return r}_splitSafely(e,t){this.tree.delete(e);const r=e.rightSE;this.queue.delete(r);const o=e.split(t);return o.push(r),void 0===e.consumedBy&&this.tree.add(e),o}},Ft=new class{constructor(){i(this,"type"),i(this,"numMultiPolys")}run(e,t,r){Ft.type=e;const o=[new Bt(t,!0)];for(let l=0,c=r.length;l<c;l++)o.push(new Bt(r[l],!1));if(Ft.numMultiPolys=o.length,"difference"===Ft.type){const e=o[0];let t=1;for(;t<o.length;)null!==Mt(o[t].bbox,e.bbox)?t++:o.splice(t,1)}if("intersection"===Ft.type)for(let l=0,c=o.length;l<c;l++){const e=o[l];for(let t=l+1,r=o.length;t<r;t++)if(null===Mt(e.bbox,o[t].bbox))return[]}const n=new st(St.compare);for(let l=0,c=o.length;l<c;l++){const e=o[l].getSweepEvents();for(let t=0,r=e.length;t<r;t++)n.add(e[t])}const i=new At(n);let a=null;for(0!=n.size&&(a=n.first(),n.delete(a));a;){const e=i.process(a);for(let t=0,r=e.length;t<r;t++){const r=e[t];void 0===r.consumedBy&&n.add(r)}0!=n.size?(a=n.first(),n.delete(a)):a=null}mt.reset();const s=Dt.factory(i.segments);return new It(s).getGeom()}},Ot=Ft,Tt=0,_t=class e{constructor(e,t,r,o){i(this,"id"),i(this,"leftSE"),i(this,"rightSE"),i(this,"rings"),i(this,"windings"),i(this,"ringOut"),i(this,"consumedBy"),i(this,"prev"),i(this,"_prevInResult"),i(this,"_beforeState"),i(this,"_afterState"),i(this,"_isInResult"),this.id=++Tt,this.leftSE=e,e.segment=this,e.otherSE=t,this.rightSE=t,t.segment=this,t.otherSE=e,this.rings=r,this.windings=o}static compare(e,t){const r=e.leftSE.point.x,o=t.leftSE.point.x,n=e.rightSE.point.x,i=t.rightSE.point.x;if(i.isLessThan(r))return 1;if(n.isLessThan(o))return-1;const a=e.leftSE.point.y,s=t.leftSE.point.y,l=e.rightSE.point.y,c=t.rightSE.point.y;if(r.isLessThan(o)){if(s.isLessThan(a)&&s.isLessThan(l))return 1;if(s.isGreaterThan(a)&&s.isGreaterThan(l))return-1;const r=e.comparePoint(t.leftSE.point);if(r<0)return 1;if(r>0)return-1;const o=t.comparePoint(e.rightSE.point);return 0!==o?o:-1}if(r.isGreaterThan(o)){if(a.isLessThan(s)&&a.isLessThan(c))return-1;if(a.isGreaterThan(s)&&a.isGreaterThan(c))return 1;const r=t.comparePoint(e.leftSE.point);if(0!==r)return r;const o=e.comparePoint(t.rightSE.point);return o<0?1:o>0?-1:1}if(a.isLessThan(s))return-1;if(a.isGreaterThan(s))return 1;if(n.isLessThan(i)){const r=t.comparePoint(e.rightSE.point);if(0!==r)return r}if(n.isGreaterThan(i)){const r=e.comparePoint(t.rightSE.point);if(r<0)return 1;if(r>0)return-1}if(!n.eq(i)){const e=l.minus(a),t=n.minus(r),u=c.minus(s),h=i.minus(o);if(e.isGreaterThan(t)&&u.isLessThan(h))return 1;if(e.isLessThan(t)&&u.isGreaterThan(h))return-1}return n.isGreaterThan(i)?1:n.isLessThan(i)||l.isLessThan(c)?-1:l.isGreaterThan(c)?1:e.id<t.id?-1:e.id>t.id?1:0}static fromRing(t,r,o){let n,i,a;const s=St.comparePoints(t,r);if(s<0)n=t,i=r,a=1;else{if(!(s>0))throw new Error(`Tried to create degenerate segment at [${t.x}, ${t.y}]`);n=r,i=t,a=-1}const l=new St(n,!0),c=new St(i,!1);return new e(l,c,[o],[a])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,t=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e.isLessThan(t)?e:t},ur:{x:this.rightSE.point.x,y:e.isGreaterThan(t)?e:t}}}vector(){return{x:this.rightSE.point.x.minus(this.leftSE.point.x),y:this.rightSE.point.y.minus(this.leftSE.point.y)}}isAnEndpoint(e){return e.x.eq(this.leftSE.point.x)&&e.y.eq(this.leftSE.point.y)||e.x.eq(this.rightSE.point.x)&&e.y.eq(this.rightSE.point.y)}comparePoint(e){return mt.orient(this.leftSE.point,e,this.rightSE.point)}getIntersection(e){const t=this.bbox(),r=e.bbox(),o=Mt(t,r);if(null===o)return null;const n=this.leftSE.point,i=this.rightSE.point,a=e.leftSE.point,s=e.rightSE.point,l=vt(t,a)&&0===this.comparePoint(a),c=vt(r,n)&&0===e.comparePoint(n),u=vt(t,s)&&0===this.comparePoint(s),h=vt(r,i)&&0===e.comparePoint(i);if(c&&l)return h&&!u?i:!h&&u?s:null;if(c)return u&&n.x.eq(s.x)&&n.y.eq(s.y)?null:n;if(l)return h&&i.x.eq(a.x)&&i.y.eq(a.y)?null:a;if(h&&u)return null;if(h)return i;if(u)return s;const g=((e,t,r,o)=>{if(t.x.isZero())return xt(r,o,e.x);if(o.x.isZero())return xt(e,t,r.x);if(t.y.isZero())return Et(r,o,e.y);if(o.y.isZero())return Et(e,t,r.y);const n=bt(t,o);if(n.isZero())return null;const i={x:r.x.minus(e.x),y:r.y.minus(e.y)},a=bt(i,t).div(n),s=bt(i,o).div(n),l=e.x.plus(s.times(t.x)),c=r.x.plus(a.times(o.x)),u=e.y.plus(s.times(t.y)),h=r.y.plus(a.times(o.y));return{x:l.plus(c).div(2),y:u.plus(h).div(2)}})(n,this.vector(),a,e.vector());return null===g?null:vt(o,g)?mt.snap(g):null}split(t){const r=[],o=void 0!==t.events,n=new St(t,!0),i=new St(t,!1),a=this.rightSE;this.replaceRightSE(i),r.push(i),r.push(n);const s=new e(n,a,this.rings.slice(),this.windings.slice());return St.comparePoints(s.leftSE.point,s.rightSE.point)>0&&s.swapEvents(),St.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),o&&(n.checkForConsuming(),i.checkForConsuming()),r}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let t=0,r=this.windings.length;t<r;t++)this.windings[t]*=-1}consume(t){let r=this,o=t;for(;r.consumedBy;)r=r.consumedBy;for(;o.consumedBy;)o=o.consumedBy;const n=e.compare(r,o);if(0!==n){if(n>0){const e=r;r=o,o=e}if(r.prev===o){const e=r;r=o,o=e}for(let e=0,t=o.rings.length;e<t;e++){const t=o.rings[e],n=o.windings[e],i=r.rings.indexOf(t);-1===i?(r.rings.push(t),r.windings.push(n)):r.windings[i]+=n}o.rings=null,o.windings=null,o.consumedBy=r,o.leftSE.consumedBy=r.leftSE,o.rightSE.consumedBy=r.rightSE}}prevInResult(){return void 0!==this._prevInResult||(this.prev?this.prev.isInResult()?this._prevInResult=this.prev:this._prevInResult=this.prev.prevInResult():this._prevInResult=null),this._prevInResult}beforeState(){if(void 0!==this._beforeState)return this._beforeState;if(this.prev){const e=this.prev.consumedBy||this.prev;this._beforeState=e.afterState()}else this._beforeState={rings:[],windings:[],multiPolys:[]};return this._beforeState}afterState(){if(void 0!==this._afterState)return this._afterState;const e=this.beforeState();this._afterState={rings:e.rings.slice(0),windings:e.windings.slice(0),multiPolys:[]};const t=this._afterState.rings,r=this._afterState.windings,o=this._afterState.multiPolys;for(let a=0,s=this.rings.length;a<s;a++){const e=this.rings[a],o=this.windings[a],n=t.indexOf(e);-1===n?(t.push(e),r.push(o)):r[n]+=o}const n=[],i=[];for(let a=0,s=t.length;a<s;a++){if(0===r[a])continue;const e=t[a],o=e.poly;if(-1===i.indexOf(o))if(e.isExterior)n.push(o);else{-1===i.indexOf(o)&&i.push(o);const t=n.indexOf(e.poly);-1!==t&&n.splice(t,1)}}for(let a=0,s=n.length;a<s;a++){const e=n[a].multiPoly;-1===o.indexOf(e)&&o.push(e)}return this._afterState}isInResult(){if(this.consumedBy)return!1;if(void 0!==this._isInResult)return this._isInResult;const e=this.beforeState().multiPolys,t=this.afterState().multiPolys;switch(Ot.type){case"union":{const r=0===e.length,o=0===t.length;this._isInResult=r!==o;break}case"intersection":{let r,o;e.length<t.length?(r=e.length,o=t.length):(r=t.length,o=e.length),this._isInResult=o===Ot.numMultiPolys&&r<o;break}case"xor":{const r=Math.abs(e.length-t.length);this._isInResult=r%2==1;break}case"difference":{const r=e=>1===e.length&&e[0].isSubject;this._isInResult=r(e)!==r(t);break}}return this._isInResult}},Gt=class{constructor(e,t,r){if(i(this,"poly"),i(this,"isExterior"),i(this,"segments"),i(this,"bbox"),!Array.isArray(e)||0===e.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=t,this.isExterior=r,this.segments=[],"number"!=typeof e[0][0]||"number"!=typeof e[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const o=mt.snap({x:new ot(e[0][0]),y:new ot(e[0][1])});this.bbox={ll:{x:o.x,y:o.y},ur:{x:o.x,y:o.y}};let n=o;for(let i=1,a=e.length;i<a;i++){if("number"!=typeof e[i][0]||"number"!=typeof e[i][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const t=mt.snap({x:new ot(e[i][0]),y:new ot(e[i][1])});t.x.eq(n.x)&&t.y.eq(n.y)||(this.segments.push(_t.fromRing(n,t,this)),t.x.isLessThan(this.bbox.ll.x)&&(this.bbox.ll.x=t.x),t.y.isLessThan(this.bbox.ll.y)&&(this.bbox.ll.y=t.y),t.x.isGreaterThan(this.bbox.ur.x)&&(this.bbox.ur.x=t.x),t.y.isGreaterThan(this.bbox.ur.y)&&(this.bbox.ur.y=t.y),n=t)}o.x.eq(n.x)&&o.y.eq(n.y)||this.segments.push(_t.fromRing(n,o,this))}getSweepEvents(){const e=[];for(let t=0,r=this.segments.length;t<r;t++){const r=this.segments[t];e.push(r.leftSE),e.push(r.rightSE)}return e}},Ht=class{constructor(e,t){if(i(this,"multiPoly"),i(this,"exteriorRing"),i(this,"interiorRings"),i(this,"bbox"),!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new Gt(e[0],this,!0),this.bbox={ll:{x:this.exteriorRing.bbox.ll.x,y:this.exteriorRing.bbox.ll.y},ur:{x:this.exteriorRing.bbox.ur.x,y:this.exteriorRing.bbox.ur.y}},this.interiorRings=[];for(let r=1,o=e.length;r<o;r++){const t=new Gt(e[r],this,!1);t.bbox.ll.x.isLessThan(this.bbox.ll.x)&&(this.bbox.ll.x=t.bbox.ll.x),t.bbox.ll.y.isLessThan(this.bbox.ll.y)&&(this.bbox.ll.y=t.bbox.ll.y),t.bbox.ur.x.isGreaterThan(this.bbox.ur.x)&&(this.bbox.ur.x=t.bbox.ur.x),t.bbox.ur.y.isGreaterThan(this.bbox.ur.y)&&(this.bbox.ur.y=t.bbox.ur.y),this.interiorRings.push(t)}this.multiPoly=t}getSweepEvents(){const e=this.exteriorRing.getSweepEvents();for(let t=0,r=this.interiorRings.length;t<r;t++){const r=this.interiorRings[t].getSweepEvents();for(let t=0,o=r.length;t<o;t++)e.push(r[t])}return e}},Bt=class{constructor(e,t){if(i(this,"isSubject"),i(this,"polys"),i(this,"bbox"),!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{"number"==typeof e[0][0][0]&&(e=[e])}catch(r){}this.polys=[],this.bbox={ll:{x:new ot(Number.POSITIVE_INFINITY),y:new ot(Number.POSITIVE_INFINITY)},ur:{x:new ot(Number.NEGATIVE_INFINITY),y:new ot(Number.NEGATIVE_INFINITY)}};for(let o=0,n=e.length;o<n;o++){const t=new Ht(e[o],this);t.bbox.ll.x.isLessThan(this.bbox.ll.x)&&(this.bbox.ll.x=t.bbox.ll.x),t.bbox.ll.y.isLessThan(this.bbox.ll.y)&&(this.bbox.ll.y=t.bbox.ll.y),t.bbox.ur.x.isGreaterThan(this.bbox.ur.x)&&(this.bbox.ur.x=t.bbox.ur.x),t.bbox.ur.y.isGreaterThan(this.bbox.ur.y)&&(this.bbox.ur.y=t.bbox.ur.y),this.polys.push(t)}this.isSubject=t}getSweepEvents(){const e=[];for(let t=0,r=this.polys.length;t<r;t++){const r=this.polys[t].getSweepEvents();for(let t=0,o=r.length;t<o;t++)e.push(r[t])}return e}};mt.set;var zt=function(e,t={}){const r=[];if(function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,e=>{r.push(e.coordinates)}),r.length<2)throw new Error("Must have at least 2 geometries");const o=((e,...t)=>Ot.run("union",e,t))(r[0],...r.slice(1));return 0===o.length?null:1===o.length?O(o[0],t.properties):G(o,t.properties)};function Nt(e,t,r={}){const o={type:"Feature"};return(0===r.id||r.id)&&(o.id=r.id),r.bbox&&(o.bbox=r.bbox),o.properties=t||{},o.geometry=e,o}function Ut(e,t){if("Feature"===e.type)t(e,0);else if("FeatureCollection"===e.type)for(var r=0;r<e.features.length&&!1!==t(e.features[r],r);r++);}var Rt=function(e,t={}){const r=[];if(function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,e=>{r.push(e.coordinates)}),r.length<2)throw new Error("Must specify at least 2 geometries");const o=((e,...t)=>Ot.run("intersection",e,t))(r[0],...r.slice(1));return 0===o.length?null:1===o.length?function(e,t,r={}){for(const o of e){if(o.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(o[o.length-1].length!==o[0].length)throw new Error("First and last Position are not equivalent.");for(let e=0;e<o[o.length-1].length;e++)if(o[o.length-1][e]!==o[0][e])throw new Error("First and last Position are not equivalent.")}return Nt({type:"Polygon",coordinates:e},t,r)}(o[0],t.properties):function(e,t,r={}){return Nt({type:"MultiPolygon",coordinates:e},t,r)}(o,t.properties)};var Xt=function(e){const t=[];if(function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,e=>{t.push(e.coordinates)}),t.length<2)throw new Error("Must have at least two features");const r=e.features[0].properties||{},o=((e,...t)=>Ot.run("difference",e,t))(t[0],...t.slice(1));return 0===o.length?null:1===o.length?O(o[0],r):G(o,r)};function Yt(e,t,r){if(null!==e)for(var o,n,i,a,s,l,c,u,h=0,g=0,d=e.type,p="FeatureCollection"===d,f="Feature"===d,y=p?e.features.length:1,m=0;m<y;m++){s=(u=!!(c=p?e.features[m].geometry:f?e.geometry:e)&&"GeometryCollection"===c.type)?c.geometries.length:1;for(var v=0;v<s;v++){var M=0,b=0;if(null!==(a=u?c.geometries[v]:c)){l=a.coordinates;var w=a.type;switch(h=0,w){case null:break;case"Point":if(!1===t(l,g,m,M,b))return!1;g++,M++;break;case"LineString":case"MultiPoint":for(o=0;o<l.length;o++){if(!1===t(l[o],g,m,M,b))return!1;g++,"MultiPoint"===w&&M++}"LineString"===w&&M++;break;case"Polygon":case"MultiLineString":for(o=0;o<l.length;o++){for(n=0;n<l[o].length-h;n++){if(!1===t(l[o][n],g,m,M,b))return!1;g++}"MultiLineString"===w&&M++,"Polygon"===w&&b++}"Polygon"===w&&M++;break;case"MultiPolygon":for(o=0;o<l.length;o++){for(b=0,n=0;n<l[o].length;n++){for(i=0;i<l[o][n].length-h;i++){if(!1===t(l[o][n][i],g,m,M,b))return!1;g++}b++}M++}break;case"GeometryCollection":for(o=0;o<a.geometries.length;o++)if(!1===Yt(a.geometries[o],t))return!1;break;default:throw new Error("Unknown Geometry Type")}}}}}var Vt=function(e){const t=[];return"FeatureCollection"===e.type?function(e,t){if("Feature"===e.type)t(e,0);else if("FeatureCollection"===e.type)for(var r=0;r<e.features.length&&!1!==t(e.features[r],r);r++);}(e,function(e){Yt(e,function(r){t.push(F(r,e.properties))})}):"Feature"===e.type?Yt(e,function(r){t.push(F(r,e.properties))}):Yt(e,function(e){t.push(F(e))}),_(t)};function qt(e,t,r={}){const o=Me(e),n=be(t);for(let i=0;i<n.length-1;i++){let e=!1;if(r.ignoreEndVertices&&(0===i&&(e="start"),i===n.length-2&&(e="end"),0===i&&i+1===n.length-1&&(e="both")),jt(n[i],n[i+1],o,e,void 0===r.epsilon?null:r.epsilon))return!0}return!1}function jt(e,t,r,o,n){const i=r[0],a=r[1],s=e[0],l=e[1],c=t[0],u=t[1],h=c-s,g=u-l,d=(r[0]-s)*g-(r[1]-l)*h;if(null!==n){if(Math.abs(d)>n)return!1}else if(0!==d)return!1;return Math.abs(h)===Math.abs(g)&&0===Math.abs(h)?!o&&(r[0]===e[0]&&r[1]===e[1]):o?"start"===o?Math.abs(h)>=Math.abs(g)?h>0?s<i&&i<=c:c<=i&&i<s:g>0?l<a&&a<=u:u<=a&&a<l:"end"===o?Math.abs(h)>=Math.abs(g)?h>0?s<=i&&i<c:c<i&&i<=s:g>0?l<=a&&a<u:u<a&&a<=l:"both"===o&&(Math.abs(h)>=Math.abs(g)?h>0?s<i&&i<c:c<i&&i<s:g>0?l<a&&a<u:u<a&&a<l):Math.abs(h)>=Math.abs(g)?h>0?s<=i&&i<=c:c<=i&&i<=s:g>0?l<=a&&a<=u:u<=a&&a<=l}function Wt(e,t={}){var r="object"==typeof t?t.mutate:t;if(!e)throw new Error("geojson is required");var o=Pe(e),n=[];switch(o){case"LineString":n=$t(e,o);break;case"MultiLineString":case"Polygon":be(e).forEach(function(e){n.push($t(e,o))});break;case"MultiPolygon":be(e).forEach(function(e){var t=[];e.forEach(function(e){t.push($t(e,o))}),n.push(t)});break;case"Point":return e;case"MultiPoint":var i={};be(e).forEach(function(e){var t=e.join("-");Object.prototype.hasOwnProperty.call(i,t)||(n.push(e),i[t]=!0)});break;default:throw new Error(o+" geometry not supported")}return e.coordinates?!0===r?(e.coordinates=n,e):{type:o,coordinates:n}:!0===r?(e.geometry.coordinates=n,e):A({type:o,coordinates:n},e.properties,{bbox:e.bbox,id:e.id})}function $t(e,t){const r=be(e);if(2===r.length&&!Kt(r[0],r[1]))return r;const o=[];let n=0,i=1,a=2;for(o.push(r[n]);a<r.length;)qt(r[i],T([r[n],r[a]]))?i=a:(o.push(r[i]),n=i,i++,a=i),a++;if(o.push(r[i]),"Polygon"===t||"MultiPolygon"===t){if(qt(o[0],T([o[1],o[o.length-2]]))&&(o.shift(),o.pop(),o.push(o[0])),o.length<4)throw new Error("invalid polygon, fewer than 4 points");if(!Kt(o[0],o[o.length-1]))throw new Error("invalid polygon, first and last points not equal")}return o}function Kt(e,t){return e[0]===t[0]&&e[1]===t[1]}function Jt(e){if(!e)throw new Error("geojson is required");switch(e.type){case"Feature":return Zt(e);case"FeatureCollection":return function(e){const t={type:"FeatureCollection"};return Object.keys(e).forEach(r=>{switch(r){case"type":case"features":return;default:t[r]=e[r]}}),t.features=e.features.map(e=>Zt(e)),t}(e);case"Point":case"LineString":case"Polygon":case"MultiPoint":case"MultiLineString":case"MultiPolygon":case"GeometryCollection":return er(e);default:throw new Error("unknown GeoJSON type")}}function Zt(e){const t={type:"Feature"};return Object.keys(e).forEach(r=>{switch(r){case"type":case"properties":case"geometry":return;default:t[r]=e[r]}}),t.properties=Qt(e.properties),null==e.geometry?t.geometry=null:t.geometry=er(e.geometry),t}function Qt(e){const t={};return e?(Object.keys(e).forEach(r=>{const o=e[r];"object"==typeof o?null===o?t[r]=null:Array.isArray(o)?t[r]=o.map(e=>e):t[r]=Qt(o):t[r]=o}),t):t}function er(e){const t={type:e.type};return e.bbox&&(t.bbox=e.bbox),"GeometryCollection"===e.type?(t.geometries=e.geometries.map(e=>er(e)),t):(t.coordinates=tr(e.coordinates),t)}function tr(e){const t=e;return"object"!=typeof t[0]?t.slice():t.map(e=>tr(e))}function rr(e,t){var r=e[0]-t[0],o=e[1]-t[1];return r*r+o*o}function or(e,t,r){var o=t[0],n=t[1],i=r[0]-o,a=r[1]-n;if(0!==i||0!==a){var s=((e[0]-o)*i+(e[1]-n)*a)/(i*i+a*a);s>1?(o=r[0],n=r[1]):s>0&&(o+=i*s,n+=a*s)}return(i=e[0]-o)*i+(a=e[1]-n)*a}function nr(e,t,r,o,n){for(var i,a=o,s=t+1;s<r;s++){var l=or(e[s],e[t],e[r]);l>a&&(i=s,a=l)}a>o&&(i-t>1&&nr(e,t,i,o,n),n.push(e[i]),r-i>1&&nr(e,i,r,o,n))}function ir(e,t){var r=e.length-1,o=[e[0]];return nr(e,0,r,t,o),o.push(e[r]),o}function ar(e,t,r){if(e.length<=2)return e;var o=void 0!==t?t*t:1;return e=r?e:function(e,t){for(var r,o=e[0],n=[o],i=1,a=e.length;i<a;i++)rr(r=e[i],o)>t&&(n.push(r),o=r);return o!==r&&n.push(r),n}(e,o),e=ir(e,o)}function sr(e,t,r){return e.map(function(e){if(e.length<4)throw new Error("invalid polygon");let o=t,n=ar(e,o,r);for(;!lr(n)&&o>=Number.EPSILON;)o-=.01*o,n=ar(e,o,r);return lr(n)?(n[n.length-1][0]===n[0][0]&&n[n.length-1][1]===n[0][1]||n.push(n[0]),n):e})}function lr(e){return!(e.length<3)&&!(3===e.length&&e[2][0]===e[0][0]&&e[2][1]===e[0][1])}var cr=function(e,t={}){var r,o,n;if(!N(t=null!=t?t:{}))throw new Error("options is invalid");const i=null!=(r=t.tolerance)?r:1,a=null!=(o=t.highQuality)&&o,s=null!=(n=t.mutate)&&n;if(!e)throw new Error("geojson is required");if(i&&i<0)throw new Error("invalid tolerance");return!0!==s&&(e=Jt(e)),function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,function(e){!function(e,t,r){const o=e.type;if("Point"===o||"MultiPoint"===o)return e;if(Wt(e,{mutate:!0}),"GeometryCollection"!==o)switch(o){case"LineString":e.coordinates=ar(e.coordinates,t,r);break;case"MultiLineString":e.coordinates=e.coordinates.map(e=>ar(e,t,r));break;case"Polygon":e.coordinates=sr(e.coordinates,t,r);break;case"MultiPolygon":e.coordinates=e.coordinates.map(e=>sr(e,t,r))}}(e,i,a)}),e};function ur(e,t,r,o,n,i,a,s){let l,c,u,h,g;const d={x:null,y:null,onLine1:!1,onLine2:!1};return l=(s-i)*(r-e)-(a-n)*(o-t),0===l?null!==d.x&&null!==d.y&&d:(c=t-i,u=e-n,h=(a-n)*c-(s-i)*u,g=(r-e)*c-(o-t)*u,c=h/l,u=g/l,d.x=e+c*(r-e),d.y=t+c*(o-t),c>=0&&c<=1&&(d.onLine1=!0),u>=0&&u<=1&&(d.onLine2=!0),!(!d.onLine1||!d.onLine2)&&[d.x,d.y])}var hr=function(e){let t,r;const o={type:"FeatureCollection",features:[]};if(r="Feature"===e.type?e.geometry:e,"LineString"===r.type)t=[r.coordinates];else if("MultiLineString"===r.type)t=r.coordinates;else if("MultiPolygon"===r.type)t=[].concat(...r.coordinates);else{if("Polygon"!==r.type)throw new Error("Input must be a LineString, MultiLineString, Polygon, or MultiPolygon Feature or Geometry");t=r.coordinates}return t.forEach(e=>{t.forEach(t=>{for(let r=0;r<e.length-1;r++)for(let n=r;n<t.length-1;n++){if(e===t){if(1===Math.abs(r-n))continue;if(0===r&&n===e.length-2&&e[r][0]===e[e.length-1][0]&&e[r][1]===e[e.length-1][1])continue}const i=ur(e[r][0],e[r][1],e[r+1][0],e[r+1][1],t[n][0],t[n][1],t[n+1][0],t[n+1][1]);i&&o.features.push(F([i[0],i[1]]))}})}),o};function gr(e,t){!function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,function(e,r,o,n,i){var a,s=null===e?null:e.type;switch(s){case null:case"Point":case"LineString":case"Polygon":return!1!==t(A(e,o,{bbox:n,id:i}),r,0)&&void 0}switch(s){case"MultiPoint":a="Point";break;case"MultiLineString":a="LineString";break;case"MultiPolygon":a="Polygon"}for(var l=0;l<e.coordinates.length;l++){var c=e.coordinates[l];if(!1===t(A({type:a,coordinates:c},o),r,l))return!1}})}function dr(e,t,r,o,n){pr(e,t,r||0,o||e.length-1,n||yr)}function pr(e,t,r,o,n){for(;o>r;){if(o-r>600){var i=o-r+1,a=t-r+1,s=Math.log(i),l=.5*Math.exp(2*s/3),c=.5*Math.sqrt(s*l*(i-l)/i)*(a-i/2<0?-1:1);pr(e,t,Math.max(r,Math.floor(t-a*l/i+c)),Math.min(o,Math.floor(t+(i-a)*l/i+c)),n)}var u=e[t],h=r,g=o;for(fr(e,r,t),n(e[o],u)>0&&fr(e,r,o);h<g;){for(fr(e,h,g),h++,g--;n(e[h],u)<0;)h++;for(;n(e[g],u)>0;)g--}0===n(e[r],u)?fr(e,r,g):fr(e,++g,o),g<=t&&(r=g+1),t<=g&&(o=g-1)}}function fr(e,t,r){var o=e[t];e[t]=e[r],e[r]=o}function yr(e,t){return e<t?-1:e>t?1:0}let mr=class{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data;const r=[];if(!Cr(e,t))return r;const o=this.toBBox,n=[];for(;t;){for(let i=0;i<t.children.length;i++){const a=t.children[i],s=t.leaf?o(a):a;Cr(e,s)&&(t.leaf?r.push(a):Dr(e,s)?this._all(a,r):n.push(a))}t=n.pop()}return r}collides(e){let t=this.data;if(!Cr(e,t))return!1;const r=[];for(;t;){for(let o=0;o<t.children.length;o++){const n=t.children[o],i=t.leaf?this.toBBox(n):n;if(Cr(e,i)){if(t.leaf||Dr(e,i))return!0;r.push(n)}}t=r.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let t=0;t<e.length;t++)this.insert(e[t]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){const e=this.data;this.data=t,t=e}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=Ir([]),this}remove(e,t){if(!e)return this;let r=this.data;const o=this.toBBox(e),n=[],i=[];let a,s,l;for(;r||n.length;){if(r||(r=n.pop(),s=n[n.length-1],a=i.pop(),l=!0),r.leaf){const o=vr(e,r.children,t);if(-1!==o)return r.children.splice(o,1),n.push(r),this._condense(n),this}l||r.leaf||!Dr(r,o)?s?(a++,r=s.children[a],l=!1):r=null:(n.push(r),i.push(a),a=0,s=r,r=r.children[0])}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){const r=[];for(;e;)e.leaf?t.push(...e.children):r.push(...e.children),e=r.pop();return t}_build(e,t,r,o){const n=r-t+1;let i,a=this._maxEntries;if(n<=a)return i=Ir(e.slice(t,r+1)),Mr(i,this.toBBox),i;o||(o=Math.ceil(Math.log(n)/Math.log(a)),a=Math.ceil(n/Math.pow(a,o-1))),i=Ir([]),i.leaf=!1,i.height=o;const s=Math.ceil(n/a),l=s*Math.ceil(Math.sqrt(a));Ar(e,t,r,l,this.compareMinX);for(let c=t;c<=r;c+=l){const t=Math.min(c+l-1,r);Ar(e,c,t,s,this.compareMinY);for(let r=c;r<=t;r+=s){const n=Math.min(r+s-1,t);i.children.push(this._build(e,r,n,o-1))}}return Mr(i,this.toBBox),i}_chooseSubtree(e,t,r,o){for(;o.push(t),!t.leaf&&o.length-1!==r;){let r,o=1/0,n=1/0;for(let i=0;i<t.children.length;i++){const a=t.children[i],s=kr(a),l=xr(e,a)-s;l<n?(n=l,o=s<o?s:o,r=a):l===n&&s<o&&(o=s,r=a)}t=r||t.children[0]}return t}_insert(e,t,r){const o=r?e:this.toBBox(e),n=[],i=this._chooseSubtree(o,this.data,t,n);for(i.children.push(e),wr(i,o);t>=0&&n[t].children.length>this._maxEntries;)this._split(n,t),t--;this._adjustParentBBoxes(o,n,t)}_split(e,t){const r=e[t],o=r.children.length,n=this._minEntries;this._chooseSplitAxis(r,n,o);const i=this._chooseSplitIndex(r,n,o),a=Ir(r.children.splice(i,r.children.length-i));a.height=r.height,a.leaf=r.leaf,Mr(r,this.toBBox),Mr(a,this.toBBox),t?e[t-1].children.push(a):this._splitRoot(r,a)}_splitRoot(e,t){this.data=Ir([e,t]),this.data.height=e.height+1,this.data.leaf=!1,Mr(this.data,this.toBBox)}_chooseSplitIndex(e,t,r){let o,n=1/0,i=1/0;for(let a=t;a<=r-t;a++){const t=br(e,0,a,this.toBBox),s=br(e,a,r,this.toBBox),l=Sr(t,s),c=kr(t)+kr(s);l<n?(n=l,o=a,i=c<i?c:i):l===n&&c<i&&(i=c,o=a)}return o||r-t}_chooseSplitAxis(e,t,r){const o=e.leaf?this.compareMinX:Pr,n=e.leaf?this.compareMinY:Lr;this._allDistMargin(e,t,r,o)<this._allDistMargin(e,t,r,n)&&e.children.sort(o)}_allDistMargin(e,t,r,o){e.children.sort(o);const n=this.toBBox,i=br(e,0,t,n),a=br(e,r-t,r,n);let s=Er(i)+Er(a);for(let l=t;l<r-t;l++){const t=e.children[l];wr(i,e.leaf?n(t):t),s+=Er(i)}for(let l=r-t-1;l>=t;l--){const t=e.children[l];wr(a,e.leaf?n(t):t),s+=Er(a)}return s}_adjustParentBBoxes(e,t,r){for(let o=r;o>=0;o--)wr(t[o],e)}_condense(e){for(let t,r=e.length-1;r>=0;r--)0===e[r].children.length?r>0?(t=e[r-1].children,t.splice(t.indexOf(e[r]),1)):this.clear():Mr(e[r],this.toBBox)}};function vr(e,t,r){if(!r)return t.indexOf(e);for(let o=0;o<t.length;o++)if(r(e,t[o]))return o;return-1}function Mr(e,t){br(e,0,e.children.length,t,e)}function br(e,t,r,o,n){n||(n=Ir(null)),n.minX=1/0,n.minY=1/0,n.maxX=-1/0,n.maxY=-1/0;for(let i=t;i<r;i++){const t=e.children[i];wr(n,e.leaf?o(t):t)}return n}function wr(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function Pr(e,t){return e.minX-t.minX}function Lr(e,t){return e.minY-t.minY}function kr(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function Er(e){return e.maxX-e.minX+(e.maxY-e.minY)}function xr(e,t){return(Math.max(t.maxX,e.maxX)-Math.min(t.minX,e.minX))*(Math.max(t.maxY,e.maxY)-Math.min(t.minY,e.minY))}function Sr(e,t){const r=Math.max(e.minX,t.minX),o=Math.max(e.minY,t.minY),n=Math.min(e.maxX,t.maxX),i=Math.min(e.maxY,t.maxY);return Math.max(0,n-r)*Math.max(0,i-o)}function Dr(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function Cr(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function Ir(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function Ar(e,t,r,o,n){const i=[t,r];for(;i.length;){if((r=i.pop())-(t=i.pop())<=o)continue;const a=t+Math.ceil((r-t)/o/2)*o;dr(e,a,t,r,n),i.push(t,a,a,r)}}const Fr=11102230246251565e-32,Or=134217729,Tr=(3+8*Fr)*Fr;function _r(e,t,r,o,n){let i,a,s,l,c=t[0],u=o[0],h=0,g=0;u>c==u>-c?(i=c,c=t[++h]):(i=u,u=o[++g]);let d=0;if(h<e&&g<r)for(u>c==u>-c?(a=c+i,s=i-(a-c),c=t[++h]):(a=u+i,s=i-(a-u),u=o[++g]),i=a,0!==s&&(n[d++]=s);h<e&&g<r;)u>c==u>-c?(a=i+c,l=a-i,s=i-(a-l)+(c-l),c=t[++h]):(a=i+u,l=a-i,s=i-(a-l)+(u-l),u=o[++g]),i=a,0!==s&&(n[d++]=s);for(;h<e;)a=i+c,l=a-i,s=i-(a-l)+(c-l),c=t[++h],i=a,0!==s&&(n[d++]=s);for(;g<r;)a=i+u,l=a-i,s=i-(a-l)+(u-l),u=o[++g],i=a,0!==s&&(n[d++]=s);return 0===i&&0!==d||(n[d++]=i),d}function Gr(e){return new Float64Array(e)}const Hr=Gr(4),Br=Gr(8),zr=Gr(12),Nr=Gr(16),Ur=Gr(4);function Rr(e,t,r,o,n,i){const a=(t-i)*(r-n),s=(e-n)*(o-i),l=a-s,c=Math.abs(a+s);return Math.abs(l)>=33306690738754716e-32*c?l:-function(e,t,r,o,n,i,a){let s,l,c,u,h,g,d,p,f,y,m,v,M,b,w,P,L,k;const E=e-n,x=r-n,S=t-i,D=o-i;b=E*D,g=Or*E,d=g-(g-E),p=E-d,g=Or*D,f=g-(g-D),y=D-f,w=p*y-(b-d*f-p*f-d*y),P=S*x,g=Or*S,d=g-(g-S),p=S-d,g=Or*x,f=g-(g-x),y=x-f,L=p*y-(P-d*f-p*f-d*y),m=w-L,h=w-m,Hr[0]=w-(m+h)+(h-L),v=b+m,h=v-b,M=b-(v-h)+(m-h),m=M-P,h=M-m,Hr[1]=M-(m+h)+(h-P),k=v+m,h=k-v,Hr[2]=v-(k-h)+(m-h),Hr[3]=k;let C=function(e,t){let r=t[0];for(let o=1;o<e;o++)r+=t[o];return r}(4,Hr),I=22204460492503146e-32*a;if(C>=I||-C>=I)return C;if(h=e-E,s=e-(E+h)+(h-n),h=r-x,c=r-(x+h)+(h-n),h=t-S,l=t-(S+h)+(h-i),h=o-D,u=o-(D+h)+(h-i),0===s&&0===l&&0===c&&0===u)return C;if(I=11093356479670487e-47*a+Tr*Math.abs(C),C+=E*u+D*s-(S*c+x*l),C>=I||-C>=I)return C;b=s*D,g=Or*s,d=g-(g-s),p=s-d,g=Or*D,f=g-(g-D),y=D-f,w=p*y-(b-d*f-p*f-d*y),P=l*x,g=Or*l,d=g-(g-l),p=l-d,g=Or*x,f=g-(g-x),y=x-f,L=p*y-(P-d*f-p*f-d*y),m=w-L,h=w-m,Ur[0]=w-(m+h)+(h-L),v=b+m,h=v-b,M=b-(v-h)+(m-h),m=M-P,h=M-m,Ur[1]=M-(m+h)+(h-P),k=v+m,h=k-v,Ur[2]=v-(k-h)+(m-h),Ur[3]=k;const A=_r(4,Hr,4,Ur,Br);b=E*u,g=Or*E,d=g-(g-E),p=E-d,g=Or*u,f=g-(g-u),y=u-f,w=p*y-(b-d*f-p*f-d*y),P=S*c,g=Or*S,d=g-(g-S),p=S-d,g=Or*c,f=g-(g-c),y=c-f,L=p*y-(P-d*f-p*f-d*y),m=w-L,h=w-m,Ur[0]=w-(m+h)+(h-L),v=b+m,h=v-b,M=b-(v-h)+(m-h),m=M-P,h=M-m,Ur[1]=M-(m+h)+(h-P),k=v+m,h=k-v,Ur[2]=v-(k-h)+(m-h),Ur[3]=k;const F=_r(A,Br,4,Ur,zr);b=s*u,g=Or*s,d=g-(g-s),p=s-d,g=Or*u,f=g-(g-u),y=u-f,w=p*y-(b-d*f-p*f-d*y),P=l*c,g=Or*l,d=g-(g-l),p=l-d,g=Or*c,f=g-(g-c),y=c-f,L=p*y-(P-d*f-p*f-d*y),m=w-L,h=w-m,Ur[0]=w-(m+h)+(h-L),v=b+m,h=v-b,M=b-(v-h)+(m-h),m=M-P,h=M-m,Ur[1]=M-(m+h)+(h-P),k=v+m,h=k-v,Ur[2]=v-(k-h)+(m-h),Ur[3]=k;const O=_r(F,zr,4,Ur,Nr);return Nr[O-1]}(e,t,r,o,n,i,c)}function Xr(e,t){var r,o,n,i,a,s,l,c,u,h=0,g=e[0],d=e[1],p=t.length;for(r=0;r<p;r++){o=0;var f=t[r],y=f.length-1;if((c=f[0])[0]!==f[y][0]&&c[1]!==f[y][1])throw new Error("First and last coordinates in a ring must be the same");for(i=c[0]-g,a=c[1]-d;o<y;o++){if(s=(u=f[o+1])[0]-g,l=u[1]-d,0===a&&0===l){if(s<=0&&i>=0||i<=0&&s>=0)return 0}else if(l>=0&&a<=0||l<=0&&a>=0){if(0===(n=Rr(i,s,a,l,0,0)))return 0;(n>0&&l>0&&a<=0||n<0&&l<=0&&a>0)&&h++}c=u,a=l,i=s}}return h%2!=0}function Yr(e,t,r={}){if(!e)throw new Error("point is required");if(!t)throw new Error("polygon is required");const o=Me(e),n=we(t),i=n.type,a=t.bbox;let s=n.coordinates;if(a&&!1===function(e,t){return t[0]<=e[0]&&t[1]<=e[1]&&t[2]>=e[0]&&t[3]>=e[1]}(o,a))return!1;"Polygon"===i&&(s=[s]);let l=!1;for(var c=0;c<s.length;++c){const e=Xr(o,s[c]);if(0===e)return!r.ignoreBoundary;e&&(l=!0)}return l}var Vr=Yr;function qr(e,t){if("Polygon"!==e.geometry.type)throw new Error("The input feature must be a Polygon");for(var r=e.geometry.coordinates,o=[],n={},i=[],a=0;a<r.length;a++)for(var s=0;s<r[a].length-1;s++)i.push(g(a,s));var l=new mr;l.load(i);for(var c=0;c<r.length;c++)for(var u=0;u<r[c].length-1;u++){l.search(g(c,u)).forEach(function(e){var t=e.ring,r=e.edge;h(c,u,t,r)})}return o;function h(e,i,a,s){var l,c,u=r[e][i],h=r[e][i+1],g=r[a][s],d=r[a][s+1],p=function(e,t,r,o){if(jr(e,r)||jr(e,o)||jr(t,r)||jr(o,r))return null;var n=e[0],i=e[1],a=t[0],s=t[1],l=r[0],c=r[1],u=o[0],h=o[1],g=(n-a)*(c-h)-(i-s)*(l-u);return 0===g?null:[((n*s-i*a)*(l-u)-(n-a)*(l*h-c*u))/g,((n*s-i*a)*(c-h)-(i-s)*(l*h-c*u))/g]}(u,h,g,d);if(null!==p&&(l=h[0]!==u[0]?(p[0]-u[0])/(h[0]-u[0]):(p[1]-u[1])/(h[1]-u[1]),c=d[0]!==g[0]?(p[0]-g[0])/(d[0]-g[0]):(p[1]-g[1])/(d[1]-g[1]),!(l>=1||l<=0||c>=1||c<=0))){var f=p,y=!n[f.toString()];y&&(n[f.toString()]=!0),t&&o.push(t(p,e,i,u,h,l,a,s,g,d,c,y))}}function g(e,t){var o,n,i,a,s=r[e][t],l=r[e][t+1];return s[0]<l[0]?(o=s[0],n=l[0]):(o=l[0],n=s[0]),s[1]<l[1]?(i=s[1],a=l[1]):(i=l[1],a=s[1]),{minX:o,minY:i,maxX:n,maxY:a,ring:e,edge:t}}}function jr(e,t){if(!e||!t)return!1;if(e.length!==t.length)return!1;for(var r=0,o=e.length;r<o;r++)if(e[r]instanceof Array&&t[r]instanceof Array){if(!jr(e[r],t[r]))return!1}else if(e[r]!==t[r])return!1;return!0}function Wr(e){if("Feature"!=e.type)throw new Error("The input must a geojson object of type Feature");if(void 0===e.geometry||null==e.geometry)throw new Error("The input must a geojson object with a non-empty geometry");if("Polygon"!=e.geometry.type)throw new Error("The input must be a geojson Polygon");for(var t=e.geometry.coordinates.length,r=[],o=0;o<t;o++){var n=e.geometry.coordinates[o];Qr(n[0],n[n.length-1])||n.push(n[0]);for(var i=0;i<n.length-1;i++)r.push(n[i])}if(!function(e){for(var t={},r=1,o=0,n=e.length;o<n;++o){if(Object.prototype.hasOwnProperty.call(t,e[o].toString())){r=0;break}t[e[o].toString()]=1}return r}(r))throw new Error("The input polygon may not have duplicate vertices (except for the first and last vertex of each ring)");var a=r.length,s=qr(e,function(e,t,r,o,n,i,a,s,l,c,u,h){return[e,t,r,o,n,i,a,s,l,c,u,h]}),l=s.length;if(0==l){var c=[];for(o=0;o<t;o++)c.push(O([e.geometry.coordinates[o]],{parent:-1,winding:Zr(e.geometry.coordinates[o])}));let r=_(c);return H(r),B(r),r}var u=[],h=[];for(o=0;o<t;o++){u.push([]);for(i=0;i<e.geometry.coordinates[o].length-1;i++)u[o].push([new $r(e.geometry.coordinates[o][eo(i+1,e.geometry.coordinates[o].length-1)],1,[o,i],[o,eo(i+1,e.geometry.coordinates[o].length-1)],void 0)]),h.push(new Kr(e.geometry.coordinates[o][i],[o,eo(i-1,e.geometry.coordinates[o].length-1)],[o,i],void 0,void 0,!1,!0))}for(o=0;o<l;o++)u[s[o][1]][s[o][2]].push(new $r(s[o][0],s[o][5],[s[o][1],s[o][2]],[s[o][6],s[o][7]],void 0)),s[o][11]&&h.push(new Kr(s[o][0],[s[o][1],s[o][2]],[s[o][6],s[o][7]],void 0,void 0,!0,!0));var g=h.length;for(o=0;o<u.length;o++)for(i=0;i<u[o].length;i++)u[o][i].sort(function(e,t){return e.param<t.param?-1:1});var d=[];for(o=0;o<g;o++)d.push({minX:h[o].coord[0],minY:h[o].coord[1],maxX:h[o].coord[0],maxY:h[o].coord[1],index:o});var p=new mr;p.load(d);for(o=0;o<u.length;o++)for(i=0;i<u[o].length;i++)for(var f=0;f<u[o][i].length;f++){let t;t=f==u[o][i].length-1?u[o][eo(i+1,e.geometry.coordinates[o].length-1)][0].coord:u[o][i][f+1].coord;var y=p.search({minX:t[0],minY:t[1],maxX:t[0],maxY:t[1]})[0];u[o][i][f].nxtIsectAlongEdgeIn=y.index}for(o=0;o<u.length;o++)for(i=0;i<u[o].length;i++)for(f=0;f<u[o][i].length;f++){let e=u[o][i][f].coord;var m=(y=p.search({minX:e[0],minY:e[1],maxX:e[0],maxY:e[1]})[0]).index;m<a?h[m].nxtIsectAlongRingAndEdge2=u[o][i][f].nxtIsectAlongEdgeIn:Qr(h[m].ringAndEdge1,u[o][i][f].ringAndEdgeIn)?h[m].nxtIsectAlongRingAndEdge1=u[o][i][f].nxtIsectAlongEdgeIn:h[m].nxtIsectAlongRingAndEdge2=u[o][i][f].nxtIsectAlongEdgeIn}var v=[];for(o=0,i=0;i<t;i++){var M=o;for(f=0;f<e.geometry.coordinates[i].length-1;f++)h[o].coord[0]<h[M].coord[0]&&(M=o),o++;var b=h[M].nxtIsectAlongRingAndEdge2;for(f=0;f<h.length;f++)if(h[f].nxtIsectAlongRingAndEdge1==M||h[f].nxtIsectAlongRingAndEdge2==M){var w=f;break}var P=Jr([h[w].coord,h[M].coord,h[b].coord],!0)?1:-1;v.push({isect:M,parent:-1,winding:P})}v.sort(function(e,t){return h[e.isect].coord>h[t.isect].coord?-1:1});for(c=[];v.length>0;){var L=v.pop(),k=L.isect,E=L.parent,x=L.winding,S=c.length,D=[h[k].coord],C=k;if(h[k].ringAndEdge1Walkable)var I=h[k].ringAndEdge1,A=h[k].nxtIsectAlongRingAndEdge1;else I=h[k].ringAndEdge2,A=h[k].nxtIsectAlongRingAndEdge2;for(;!Qr(h[k].coord,h[A].coord);){D.push(h[A].coord);var F=void 0;for(o=0;o<v.length;o++)if(v[o].isect==A){F=o;break}if(null!=F&&v.splice(F,1),Qr(I,h[A].ringAndEdge1)){if(I=h[A].ringAndEdge2,h[A].ringAndEdge2Walkable=!1,h[A].ringAndEdge1Walkable){var T={isect:A};Jr([h[C].coord,h[A].coord,h[h[A].nxtIsectAlongRingAndEdge2].coord],1==x)?(T.parent=E,T.winding=-x):(T.parent=S,T.winding=x),v.push(T)}C=A,A=h[A].nxtIsectAlongRingAndEdge2}else{if(I=h[A].ringAndEdge1,h[A].ringAndEdge1Walkable=!1,h[A].ringAndEdge2Walkable){T={isect:A};Jr([h[C].coord,h[A].coord,h[h[A].nxtIsectAlongRingAndEdge1].coord],1==x)?(T.parent=E,T.winding=-x):(T.parent=S,T.winding=x),v.push(T)}C=A,A=h[A].nxtIsectAlongRingAndEdge1}}D.push(h[A].coord),c.push(O([D],{index:S,parent:E,winding:x,netWinding:void 0}))}let G=_(c);function H(e){for(var t=[],r=0;r<e.features.length;r++)-1==e.features[r].properties.parent&&t.push(r);if(t.length>1)for(r=0;r<t.length;r++){for(var o=-1,n=1/0,i=0;i<e.features.length;i++)t[r]!=i&&Yr(e.features[t[r]].geometry.coordinates[0][0],e.features[i],{ignoreBoundary:!0})&&R(e.features[i])<n&&(o=i);e.features[t[r]].properties.parent=o}}function B(e){for(var t=0;t<e.features.length;t++)if(-1==e.features[t].properties.parent){var r=e.features[t].properties.winding;e.features[t].properties.netWinding=r,z(e,t,r)}}function z(e,t,r){for(var o=0;o<e.features.length;o++)if(e.features[o].properties.parent==t){var n=r+e.features[o].properties.winding;e.features[o].properties.netWinding=n,z(e,o,n)}}return H(G),B(G),G}var $r=class{constructor(e,t,r,o,n){this.coord=e,this.param=t,this.ringAndEdgeIn=r,this.ringAndEdgeOut=o,this.nxtIsectAlongEdgeIn=n}},Kr=class{constructor(e,t,r,o,n,i,a){this.coord=e,this.ringAndEdge1=t,this.ringAndEdge2=r,this.nxtIsectAlongRingAndEdge1=o,this.nxtIsectAlongRingAndEdge2=n,this.ringAndEdge1Walkable=i,this.ringAndEdge2Walkable=a}};function Jr(e,t){if(void 0===t&&(t=!0),3!=e.length)throw new Error("This function requires an array of three points [x,y]");return(e[1][0]-e[0][0])*(e[2][1]-e[0][1])-(e[1][1]-e[0][1])*(e[2][0]-e[0][0])>=0==t}function Zr(e){for(var t=0,r=0;r<e.length-1;r++)e[r][0]<e[t][0]&&(t=r);if(Jr([e[eo(t-1,e.length-1)],e[t],e[eo(t+1,e.length-1)]],!0))var o=1;else o=-1;return o}function Qr(e,t){if(!e||!t)return!1;if(e.length!=t.length)return!1;for(var r=0,o=e.length;r<o;r++)if(e[r]instanceof Array&&t[r]instanceof Array){if(!Qr(e[r],t[r]))return!1}else if(e[r]!=t[r])return!1;return!0}function eo(e,t){return(e%t+t)%t}var to=function(e){var t=[];return gr(e,function(e){"Polygon"===e.geometry.type&&function(e,t){if("Feature"===e.type)t(e,0);else if("FeatureCollection"===e.type)for(var r=0;r<e.features.length&&!1!==t(e.features[r],r);r++);}(Wr(e),function(r){t.push(O(r.geometry.coordinates,e.properties))})}),_(t)};function ro(e,t,r){if(null!==e)for(var o,n,i,a,s,l,c,u,h=0,g=0,d=e.type,p="FeatureCollection"===d,f="Feature"===d,y=p?e.features.length:1,m=0;m<y;m++){s=(u=!!(c=p?e.features[m].geometry:f?e.geometry:e)&&"GeometryCollection"===c.type)?c.geometries.length:1;for(var v=0;v<s;v++){var M=0,b=0;if(null!==(a=u?c.geometries[v]:c)){l=a.coordinates;var w=a.type;switch(h=0,w){case null:break;case"Point":if(!1===t(l,g,m,M,b))return!1;g++,M++;break;case"LineString":case"MultiPoint":for(o=0;o<l.length;o++){if(!1===t(l[o],g,m,M,b))return!1;g++,"MultiPoint"===w&&M++}"LineString"===w&&M++;break;case"Polygon":case"MultiLineString":for(o=0;o<l.length;o++){for(n=0;n<l[o].length-h;n++){if(!1===t(l[o][n],g,m,M,b))return!1;g++}"MultiLineString"===w&&M++,"Polygon"===w&&b++}"Polygon"===w&&M++;break;case"MultiPolygon":for(o=0;o<l.length;o++){for(b=0,n=0;n<l[o].length;n++){for(i=0;i<l[o][n].length-h;i++){if(!1===t(l[o][n][i],g,m,M,b))return!1;g++}b++}M++}break;case"GeometryCollection":for(o=0;o<a.geometries.length;o++)if(!1===ro(a.geometries[o],t))return!1;break;default:throw new Error("Unknown Geometry Type")}}}}}function oo(e,t={}){if(null!=e.bbox&&!0!==t.recompute)return e.bbox;const r=[1/0,1/0,-1/0,-1/0];return ro(e,e=>{r[0]>e[0]&&(r[0]=e[0]),r[1]>e[1]&&(r[1]=e[1]),r[2]<e[0]&&(r[2]=e[0]),r[3]<e[1]&&(r[3]=e[1])}),r}function no(e){var t;if(e.bbox)t=e.bbox;else if(Array.isArray(e)&&4===e.length)t=e;else if(Array.isArray(e)&&6===e.length)t=[e[0],e[1],e[3],e[4]];else if("Feature"===e.type)t=oo(e);else{if("FeatureCollection"!==e.type)throw new Error("invalid geojson");t=oo(e)}return{minX:t[0],minY:t[1],maxX:t[2],maxY:t[3]}}var io=class{constructor(e=9){this.tree=new mr(e),this.tree.toBBox=no}insert(e){if("Feature"!==e.type)throw new Error("invalid feature");return e.bbox=e.bbox?e.bbox:oo(e),this.tree.insert(e),this}load(e){var t=[];return Array.isArray(e)?e.forEach(function(e){if("Feature"!==e.type)throw new Error("invalid features");e.bbox=e.bbox?e.bbox:oo(e),t.push(e)}):function(e,t){if("Feature"===e.type)t(e,0);else if("FeatureCollection"===e.type)for(var r=0;r<e.features.length&&!1!==t(e.features[r],r);r++);}(e,function(e){if("Feature"!==e.type)throw new Error("invalid features");e.bbox=e.bbox?e.bbox:oo(e),t.push(e)}),this.tree.load(t),this}remove(e,t){if("Feature"!==e.type)throw new Error("invalid feature");return e.bbox=e.bbox?e.bbox:oo(e),this.tree.remove(e,t),this}clear(){return this.tree.clear(),this}search(e){return _(this.tree.search(no(e)))}collides(e){return this.tree.collides(no(e))}all(){return _(this.tree.all())}toJSON(){return this.tree.toJSON()}fromJSON(e){return this.tree.fromJSON(e),this}};function ao(e){return new io(e)}function so(e,t,r){if(null!==e)for(var o,n,i,a,s,l,c,u,h=0,g=0,d=e.type,p="FeatureCollection"===d,f="Feature"===d,y=p?e.features.length:1,m=0;m<y;m++){s=(u=!!(c=p?e.features[m].geometry:f?e.geometry:e)&&"GeometryCollection"===c.type)?c.geometries.length:1;for(var v=0;v<s;v++){var M=0,b=0;if(null!==(a=u?c.geometries[v]:c)){l=a.coordinates;var w=a.type;switch(h=0,w){case null:break;case"Point":if(!1===t(l,g,m,M,b))return!1;g++,M++;break;case"LineString":case"MultiPoint":for(o=0;o<l.length;o++){if(!1===t(l[o],g,m,M,b))return!1;g++,"MultiPoint"===w&&M++}"LineString"===w&&M++;break;case"Polygon":case"MultiLineString":for(o=0;o<l.length;o++){for(n=0;n<l[o].length-h;n++){if(!1===t(l[o][n],g,m,M,b))return!1;g++}"MultiLineString"===w&&M++,"Polygon"===w&&b++}"Polygon"===w&&M++;break;case"MultiPolygon":for(o=0;o<l.length;o++){for(b=0,n=0;n<l[o].length;n++){for(i=0;i<l[o][n].length-h;i++){if(!1===t(l[o][n][i],g,m,M,b))return!1;g++}b++}M++}break;case"GeometryCollection":for(o=0;o<a.geometries.length;o++)if(!1===so(a.geometries[o],t))return!1;break;default:throw new Error("Unknown Geometry Type")}}}}}function lo(e,t){if(!N(t=null!=t?t:{}))throw new Error("options is invalid");var r=t.precision,o=t.coordinates,n=t.mutate;if(r=null==r||isNaN(r)?6:r,o=null==o||isNaN(o)?3:o,!e)throw new Error("<geojson> is required");if("number"!=typeof r)throw new Error("<precision> must be a number");if("number"!=typeof o)throw new Error("<coordinates> must be a number");!1!==n&&void 0!==n||(e=JSON.parse(JSON.stringify(e)));var i=Math.pow(10,r);return so(e,function(e){!function(e,t,r){e.length>r&&e.splice(r,e.length);for(var o=0;o<e.length;o++)e[o]=Math.round(e[o]*t)/t}(e,i,o)}),e}function co(e,t){!function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,function(e,r,o,n,i){var a,s=null===e?null:e.type;switch(s){case null:case"Point":case"LineString":case"Polygon":return!1!==t(A(e,o,{bbox:n,id:i}),r,0)&&void 0}switch(s){case"MultiPoint":a="Point";break;case"MultiLineString":a="LineString";break;case"MultiPolygon":a="Polygon"}for(var l=0;l<e.coordinates.length;l++){var c=e.coordinates[l];if(!1===t(A({type:a,coordinates:c},o),r,l))return!1}})}function uo(e){if(!e)throw new Error("geojson is required");const t=[];return co(e,e=>{!function(e,t){let r=[];const o=e.geometry;if(null!==o){switch(o.type){case"Polygon":r=be(o);break;case"LineString":r=[be(o)]}r.forEach(r=>{const o=function(e,t){const r=[];return e.reduce((e,o)=>{const n=T([e,o],t);return n.bbox=function(e,t){const r=e[0],o=e[1],n=t[0],i=t[1];return[r<n?r:n,o<i?o:i,r>n?r:n,o>i?o:i]}(e,o),r.push(n),o}),r}(r,e.properties);o.forEach(e=>{e.id=t.length,t.push(e)})})}}(e,t)}),_(t)}function ho(e,t,r={}){var o=Me(e),n=Me(t),i=B(n[1]-o[1]),a=B(n[0]-o[0]),s=B(o[1]),l=B(n[1]),c=Math.pow(Math.sin(i/2),2)+Math.pow(Math.sin(a/2),2)*Math.cos(s)*Math.cos(l);return function(e,t="kilometers"){const r=I[t];if(!r)throw new Error(t+" units is invalid");return e*r}(2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c)),r.units)}function go(e,t){!function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,function(e,r,o,n,i){var a,s=null===e?null:e.type;switch(s){case null:case"Point":case"LineString":case"Polygon":return!1!==t(A(e,o,{bbox:n,id:i}),r,0)&&void 0}switch(s){case"MultiPoint":a="Point";break;case"MultiLineString":a="LineString";break;case"MultiPolygon":a="Polygon"}for(var l=0;l<e.coordinates.length;l++){var c=e.coordinates[l];if(!1===t(A({type:a,coordinates:c},o),r,l))return!1}})}var po=Object.defineProperty,fo=Object.defineProperties,yo=Object.getOwnPropertyDescriptors,mo=Object.getOwnPropertySymbols,vo=Object.prototype.hasOwnProperty,Mo=Object.prototype.propertyIsEnumerable,bo=(e,t,r)=>t in e?po(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,wo=(e,t)=>{for(var r in t||(t={}))vo.call(t,r)&&bo(e,r,t[r]);if(mo)for(var r of mo(t))Mo.call(t,r)&&bo(e,r,t[r]);return e},Po=(e,t)=>fo(e,yo(t));function Lo(e,t){const[r,o,n]=e,[i,a,s]=t;return r*i+o*a+n*s}function ko(e,t){const[r,o,n]=e,[i,a,s]=t;return[o*s-n*a,n*i-r*s,r*a-o*i]}function Eo(e){const t=function(e){return Math.sqrt(Math.pow(e[0],2)+Math.pow(e[1],2)+Math.pow(e[2],2))}(e);return[e[0]/t,e[1]/t,e[2]/t]}function xo(e){const t=B(e[1]),r=B(e[0]);return[Math.cos(t)*Math.cos(r),Math.cos(t)*Math.sin(r),Math.sin(t)]}function So(e){const[t,r,o]=e,n=Math.min(Math.max(o,-1),1),i=H(Math.asin(n));return[H(Math.atan2(r,t)),i]}function Do(e,t,r){const o=xo(e),n=xo(t),i=xo(r),a=ko(o,n);if(0===a[0]&&0===a[1]&&0===a[2])return Lo(o,n)>0?[[...t],!0]:[[...r],!1];const s=ko(a,i);if(0===s[0]&&0===s[1]&&0===s[2])return[[...t],!0];const l=Eo(ko(s,a)),c=[-l[0],-l[1],-l[2]],u=Lo(i,l)>Lo(i,c)?l:c,h=Eo(a),g=Lo(ko(o,u),h),d=Lo(ko(u,n),h);return g>=0&&d>=0?[So(u),!1]:Lo(o,i)>Lo(n,i)?[[...e],!1]:[[...t],!0]}function Co(e,t){if("Feature"===e.type)t(e,0);else if("FeatureCollection"===e.type)for(var r=0;r<e.features.length&&!1!==t(e.features[r],r);r++);}function Io(e,t){!function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,function(e,r,o,n,i){var a,s=null===e?null:e.type;switch(s){case null:case"Point":case"LineString":case"Polygon":return!1!==t(A(e,o,{bbox:n,id:i}),r,0)&&void 0}switch(s){case"MultiPoint":a="Point";break;case"MultiLineString":a="LineString";break;case"MultiPolygon":a="Polygon"}for(var l=0;l<e.coordinates.length;l++){var c=e.coordinates[l];if(!1===t(A({type:a,coordinates:c},o),r,l))return!1}})}function Ao(e,t){if(!e)throw new Error("line is required");if(!t)throw new Error("splitter is required");const r=Pe(e),o=Pe(t);if("LineString"!==r)throw new Error("line must be LineString");if("FeatureCollection"===o)throw new Error("splitter cannot be a FeatureCollection");if("GeometryCollection"===o)throw new Error("splitter cannot be a GeometryCollection");var n=lo(t,{precision:7});switch("Feature"!==e.type&&(e=A(e)),o){case"Point":return Oo(e,n);case"MultiPoint":return Fo(e,n);case"LineString":case"MultiLineString":case"Polygon":case"MultiPolygon":return Fo(e,He(e,n,{ignoreSelfIntersections:!0}))}}function Fo(e,t){var r=[],o=ao();return Io(t,function(t){if(r.forEach(function(e,t){e.id=t}),r.length){var n=o.search(t);if(n.features.length){var i=To(t,n);r=r.filter(function(e){return e.id!==i.id}),o.remove(i),Co(Oo(i,t),function(e){r.push(e),o.insert(e)})}}else r=Oo(e,t).features,o.load(_(r))}),_(r)}function Oo(e,t){var r=[],o=be(e)[0],n=be(e)[e.geometry.coordinates.length-1];if(_o(o,Me(t))||_o(n,Me(t)))return _([e]);var i=ao(),a=uo(e);i.load(a);var s=i.search(t);if(!s.features.length)return _([e]);var l=To(t,s),c=function(e,t,r){var o=r;return Co(e,function(e,n){o=0===n&&void 0===r?e:t(o,e,n)}),o}(a,function(e,o,n){var i=be(o)[1],a=Me(t);return n===l.id?(e.push(a),r.push(T(e)),_o(a,i)?[a]:[a,i]):(e.push(i),e)},[o]);return c.length>1&&r.push(T(c)),_(r)}function To(e,t){if(!t.features.length)throw new Error("lines must contain features");if(1===t.features.length)return t.features[0];var r,o=1/0;return Co(t,function(t){var n=function(e,t,r={}){if(!e||!t)throw new Error("lines and inputPoint are required arguments");const o=Me(t);let n=F([1/0,1/0],{lineStringIndex:-1,segmentIndex:-1,totalDistance:-1,lineDistance:-1,segmentDistance:-1,pointDistance:1/0,multiFeatureIndex:-1,index:-1,location:-1,dist:1/0}),i=0,a=0,s=-1;return go(e,function(e,l,c){s!==c&&(s=c,a=0);const u=be(e);for(let s=0;s<u.length-1;s++){const e=F(u[s]),l=Me(e),h=F(u[s+1]),g=Me(h),d=ho(e,h,r);let p,f;g[0]===o[0]&&g[1]===o[1]?[p,f]=[g,!0]:l[0]===o[0]&&l[1]===o[1]?[p,f]=[l,!1]:[p,f]=Do(l,g,o);const y=ho(t,p,r);if(y<n.properties.pointDistance){const t=ho(e,p,r);n=F(p,{lineStringIndex:c,segmentIndex:f?s+1:s,totalDistance:i+t,lineDistance:a+t,segmentDistance:t,pointDistance:y,multiFeatureIndex:-1,index:-1,location:-1,dist:1/0}),n.properties=Po(wo({},n.properties),{multiFeatureIndex:n.properties.lineStringIndex,index:n.properties.segmentIndex,location:n.properties.totalDistance,dist:n.properties.pointDistance})}i+=d,a+=d}}),n}(t,e),i=n.properties.dist;i<o&&(r=t,o=i)}),r}function _o(e,t){return e[0]===t[0]&&e[1]===t[1]}function Go(e,t){return!(e[0]>t[0])&&(!(e[2]<t[2])&&(!(e[1]>t[1])&&!(e[3]<t[3])))}function Ho(e,t){return e[0]===t[0]&&e[1]===t[1]}function Bo(e,t){return[(e[0]+t[0])/2,(e[1]+t[1])/2]}var zo=function(e,t){var r=we(e),o=we(t),n=r.type,i=o.type;switch(n){case"Point":switch(i){case"MultiPoint":return function(e,t){var r,o=!1;for(r=0;r<t.coordinates.length;r++)if(Ho(t.coordinates[r],e.coordinates)){o=!0;break}return o}(r,o);case"LineString":return qt(r,o,{ignoreEndVertices:!0});case"Polygon":case"MultiPolygon":return Yr(r,o,{ignoreBoundary:!0});default:throw new Error("feature2 "+i+" geometry not supported")}case"MultiPoint":switch(i){case"MultiPoint":return function(e,t){for(var r=0;r<e.coordinates.length;r++){for(var o=!1,n=0;n<t.coordinates.length;n++)Ho(e.coordinates[r],t.coordinates[n])&&(o=!0);if(!o)return!1}return!0}(r,o);case"LineString":return function(e,t){for(var r=!1,o=0;o<e.coordinates.length;o++){if(!qt(e.coordinates[o],t))return!1;r||(r=qt(e.coordinates[o],t,{ignoreEndVertices:!0}))}return r}(r,o);case"Polygon":case"MultiPolygon":return function(e,t){for(var r=!0,o=!1,n=0;n<e.coordinates.length;n++){if(!(o=Yr(e.coordinates[n],t))){r=!1;break}o=Yr(e.coordinates[n],t,{ignoreBoundary:!0})}return r&&o}(r,o);default:throw new Error("feature2 "+i+" geometry not supported")}case"LineString":switch(i){case"LineString":return function(e,t){for(var r=0;r<e.coordinates.length;r++)if(!qt(e.coordinates[r],t))return!1;return!0}(r,o);case"Polygon":case"MultiPolygon":return function(e,t){const r=oo(t),o=oo(e);if(!Go(r,o))return!1;for(const a of e.coordinates)if(!Yr(a,t))return!1;let n=!1;const i=function(e,t){const r=e.coordinates,o=[];for(let n=0;n<r.length-1;n++){const e=T([r[n],r[n+1]]),i=Ao(e,A(t));0===i.features.length?o.push(e):o.push(...i.features)}return _(o)}(e,t);for(const a of i.features){const e=Bo(a.geometry.coordinates[0],a.geometry.coordinates[1]);if(!Yr(e,t))return!1;!n&&Yr(e,t,{ignoreBoundary:!0})&&(n=!0)}return n}(r,o);default:throw new Error("feature2 "+i+" geometry not supported")}case"Polygon":switch(i){case"Polygon":case"MultiPolygon":return function(e,t){var r=oo(e);if(!Go(oo(t),r))return!1;for(var o=0;o<e.coordinates[0].length;o++)if(!Yr(e.coordinates[0][o],t))return!1;return!0}(r,o);default:throw new Error("feature2 "+i+" geometry not supported")}default:throw new Error("feature1 "+n+" geometry not supported")}},No=Object.defineProperty,Uo=(e,t)=>No(e,"name",{value:t,configurable:!0}),Ro=class{constructor(e){var t,r,o;this.direction=!1,this.compareProperties=!0,this.precision=10**-(null!=(t=null==e?void 0:e.precision)?t:17),this.direction=null!=(r=null==e?void 0:e.direction)&&r,this.compareProperties=null==(o=null==e?void 0:e.compareProperties)||o}compare(e,t){if(e.type!==t.type)return!1;if(!Yo(e,t))return!1;switch(e.type){case"Point":return this.compareCoord(e.coordinates,t.coordinates);case"LineString":return this.compareLine(e.coordinates,t.coordinates);case"Polygon":return this.comparePolygon(e,t);case"GeometryCollection":return this.compareGeometryCollection(e,t);case"Feature":return this.compareFeature(e,t);case"FeatureCollection":return this.compareFeatureCollection(e,t);default:if(e.type.startsWith("Multi")){const r=Vo(e),o=Vo(t);return r.every(e=>o.some(t=>this.compare(e,t)))}}return!1}compareCoord(e,t){return e.length===t.length&&e.every((e,r)=>Math.abs(e-t[r])<this.precision)}compareLine(e,t,r=0,o=!1){if(!Yo(e,t))return!1;const n=e;let i=t;if(o&&!this.compareCoord(n[0],i[0])){const e=this.fixStartIndex(i,n);if(!e)return!1;i=e}const a=this.compareCoord(n[r],i[r]);return this.direction||a?this.comparePath(n,i):!!this.compareCoord(n[r],i[i.length-(1+r)])&&this.comparePath(n.slice().reverse(),i)}fixStartIndex(e,t){let r,o=-1;for(let n=0;n<e.length;n++)if(this.compareCoord(e[n],t[0])){o=n;break}return o>=0&&(r=[].concat(e.slice(o,e.length),e.slice(1,o+1))),r}comparePath(e,t){return e.every((e,r)=>this.compareCoord(e,t[r]))}comparePolygon(e,t){if(this.compareLine(e.coordinates[0],t.coordinates[0],1,!0)){const r=e.coordinates.slice(1,e.coordinates.length),o=t.coordinates.slice(1,t.coordinates.length);return r.every(e=>o.some(t=>this.compareLine(e,t,1,!0)))}return!1}compareGeometryCollection(e,t){return Yo(e.geometries,t.geometries)&&this.compareBBox(e,t)&&e.geometries.every((e,r)=>this.compare(e,t.geometries[r]))}compareFeature(e,t){return e.id===t.id&&(!this.compareProperties||jo(e.properties,t.properties))&&this.compareBBox(e,t)&&this.compare(e.geometry,t.geometry)}compareFeatureCollection(e,t){return Yo(e.features,t.features)&&this.compareBBox(e,t)&&e.features.every((e,r)=>this.compare(e,t.features[r]))}compareBBox(e,t){return Boolean(!e.bbox&&!t.bbox)||!(!e.bbox||!t.bbox)&&this.compareCoord(e.bbox,t.bbox)}};Uo(Ro,"GeojsonEquality");var Xo=Ro;function Yo(e,t){return e.coordinates?e.coordinates.length===t.coordinates.length:e.length===t.length}function Vo(e){return e.coordinates.map(t=>({type:e.type.replace("Multi",""),coordinates:t}))}function qo(e,t,r){return new Xo(r).compare(e,t)}function jo(e,t){if(null===e&&null===t)return!0;if(null===e||null===t)return!1;const r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(var n of r){const r=e[n],o=t[n],i=Wo(r)&&Wo(o);if(i&&!jo(r,o)||!i&&r!==o)return!1}return!0}Uo(Yo,"sameLength"),Uo(Vo,"explode"),Uo(qo,"geojsonEquality"),Uo(jo,"equal");var Wo=Uo(e=>null!=e&&"object"==typeof e,"isObject");var $o=function(e,t,r={}){let o=r.precision;if(o=null==o||isNaN(o)?6:o,"number"!=typeof o||!(o>=0))throw new Error("precision must be a positive number");return we(e).type===we(t).type&&qo(Wt(e),Wt(t),{precision:o})};var Ko=Object.defineProperty,Jo=Object.defineProperties,Zo=Object.getOwnPropertyDescriptors,Qo=Object.getOwnPropertySymbols,en=Object.prototype.hasOwnProperty,tn=Object.prototype.propertyIsEnumerable,rn=(e,t,r)=>t in e?Ko(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,on=(e,t)=>{for(var r in t||(t={}))en.call(t,r)&&rn(e,r,t[r]);if(Qo)for(var r of Qo(t))tn.call(t,r)&&rn(e,r,t[r]);return e},nn=(e,t)=>Jo(e,Zo(t));var an=function(e,t,r={}){if(!e)throw new Error("targetPoint is required");if(!t)throw new Error("points is required");let o=1/0,n=0;!function(e,t){if("Feature"===e.type)t(e,0);else if("FeatureCollection"===e.type)for(var r=0;r<e.features.length&&!1!==t(e.features[r],r);r++);}(t,(t,i)=>{const a=ho(e,t,r);a<o&&(n=i,o=a)});const i=Jt(t.features[n]);return nn(on({},i),{properties:nn(on({},i.properties),{featureIndex:n,distanceToPoint:o})})},sn=class{constructor(e){this.points=e.points||[],this.duration=e.duration||1e4,this.sharpness=e.sharpness||.85,this.centers=[],this.controls=[],this.stepLength=e.stepLength||60,this.length=this.points.length,this.delay=0;for(let t=0;t<this.length;t++)this.points[t].z=this.points[t].z||0;for(let t=0;t<this.length-1;t++){const e=this.points[t],r=this.points[t+1];this.centers.push({x:(e.x+r.x)/2,y:(e.y+r.y)/2,z:(e.z+r.z)/2})}this.controls.push([this.points[0],this.points[0]]);for(let t=0;t<this.centers.length-1;t++){const e=this.points[t+1].x-(this.centers[t].x+this.centers[t+1].x)/2,r=this.points[t+1].y-(this.centers[t].y+this.centers[t+1].y)/2,o=this.points[t+1].z-(this.centers[t].y+this.centers[t+1].z)/2;this.controls.push([{x:(1-this.sharpness)*this.points[t+1].x+this.sharpness*(this.centers[t].x+e),y:(1-this.sharpness)*this.points[t+1].y+this.sharpness*(this.centers[t].y+r),z:(1-this.sharpness)*this.points[t+1].z+this.sharpness*(this.centers[t].z+o)},{x:(1-this.sharpness)*this.points[t+1].x+this.sharpness*(this.centers[t+1].x+e),y:(1-this.sharpness)*this.points[t+1].y+this.sharpness*(this.centers[t+1].y+r),z:(1-this.sharpness)*this.points[t+1].z+this.sharpness*(this.centers[t+1].z+o)}])}return this.controls.push([this.points[this.length-1],this.points[this.length-1]]),this.steps=this.cacheSteps(this.stepLength),this}cacheSteps(e){const t=[];let r=this.pos(0);t.push(0);for(let o=0;o<this.duration;o+=10){const n=this.pos(o);Math.sqrt((n.x-r.x)*(n.x-r.x)+(n.y-r.y)*(n.y-r.y)+(n.z-r.z)*(n.z-r.z))>e&&(t.push(o),r=n)}return t}vector(e){const t=this.pos(e+10),r=this.pos(e-10);return{angle:180*Math.atan2(t.y-r.y,t.x-r.x)/3.14,speed:Math.sqrt((r.x-t.x)*(r.x-t.x)+(r.y-t.y)*(r.y-t.y)+(r.z-t.z)*(r.z-t.z))}}pos(e){let t=e-this.delay;t<0&&(t=0),t>this.duration&&(t=this.duration-1);const r=t/this.duration;if(r>=1)return this.points[this.length-1];const o=Math.floor((this.points.length-1)*r);return function(e,t,r,o,n){const i=function(e){const t=e*e,r=t*e;return[r,3*t*(1-e),3*e*(1-e)*(1-e),(1-e)*(1-e)*(1-e)]}(e);return{x:n.x*i[0]+o.x*i[1]+r.x*i[2]+t.x*i[3],y:n.y*i[0]+o.y*i[1]+r.y*i[2]+t.y*i[3],z:n.z*i[0]+o.z*i[1]+r.z*i[2]+t.z*i[3]}}((this.length-1)*r-o,this.points[o],this.controls[o][1],this.controls[o+1][0],this.points[o+1])}};var ln=function(e,t={}){const r=t.resolution||1e4,o=t.sharpness||.85,n=[],i=we(e).coordinates.map(e=>({x:e[0],y:e[1]})),a=new sn({duration:r,points:i,sharpness:o}),s=e=>{var t=a.pos(e);Math.floor(e/100)%2==0&&n.push([t.x,t.y])};for(var l=0;l<a.duration;l+=10)s(l);return s(a.duration),T(n,t.properties)};function cn(e,t,r){if(null!==e)for(var o,n,i,a,s,l,c,u,h=0,g=0,d=e.type,p="FeatureCollection"===d,f="Feature"===d,y=p?e.features.length:1,m=0;m<y;m++){s=(u=!!(c=p?e.features[m].geometry:f?e.geometry:e)&&"GeometryCollection"===c.type)?c.geometries.length:1;for(var v=0;v<s;v++){var M=0,b=0;if(null!==(a=u?c.geometries[v]:c)){l=a.coordinates;var w=a.type;switch(h=0,w){case null:break;case"Point":if(!1===t(l,g,m,M,b))return!1;g++,M++;break;case"LineString":case"MultiPoint":for(o=0;o<l.length;o++){if(!1===t(l[o],g,m,M,b))return!1;g++,"MultiPoint"===w&&M++}"LineString"===w&&M++;break;case"Polygon":case"MultiLineString":for(o=0;o<l.length;o++){for(n=0;n<l[o].length-h;n++){if(!1===t(l[o][n],g,m,M,b))return!1;g++}"MultiLineString"===w&&M++,"Polygon"===w&&b++}"Polygon"===w&&M++;break;case"MultiPolygon":for(o=0;o<l.length;o++){for(b=0,n=0;n<l[o].length;n++){for(i=0;i<l[o][n].length-h;i++){if(!1===t(l[o][n][i],g,m,M,b))return!1;g++}b++}M++}break;case"GeometryCollection":for(o=0;o<a.geometries.length;o++)if(!1===cn(a.geometries[o],t))return!1;break;default:throw new Error("Unknown Geometry Type")}}}}}function un(e,t){!function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,function(e,r,o,n,i){var a,s=null===e?null:e.type;switch(s){case null:case"Point":case"LineString":case"Polygon":return!1!==t(A(e,o,{bbox:n,id:i}),r,0)&&void 0}switch(s){case"MultiPoint":a="Point";break;case"MultiLineString":a="LineString";break;case"MultiPolygon":a="Polygon"}for(var l=0;l<e.coordinates.length;l++){var c=e.coordinates[l];if(!1===t(A({type:a,coordinates:c},o),r,l))return!1}})}function hn(e,t){un(e,function(e,r,o){var n=0;if(e.geometry){var i=e.geometry.type;if("Point"!==i&&"MultiPoint"!==i){var a,s=0,l=0,c=0;return!1!==cn(e,function(i,u,h,g,d){if(void 0===a||r>s||g>l||d>c)return a=i,s=r,l=g,c=d,void(n=0);var p=T([a,i],e.properties);if(!1===t(p,r,o,d,n))return!1;n++,a=i})&&void 0}}})}var gn=function(e,t={}){return function(e,t,r){var o=r,n=!1;return hn(e,function(e,i,a,s,l){o=!1===n&&void 0===r?e:t(o,e,i,a,s,l),n=!0}),o}(e,(e,r)=>{const o=r.geometry.coordinates;return e+ho(o[0],o[1],t)},0)};function dn(e,t,r=0,o=e.length-1,n=fn){for(;o>r;){if(o-r>600){const i=o-r+1,a=t-r+1,s=Math.log(i),l=.5*Math.exp(2*s/3),c=.5*Math.sqrt(s*l*(i-l)/i)*(a-i/2<0?-1:1);dn(e,t,Math.max(r,Math.floor(t-a*l/i+c)),Math.min(o,Math.floor(t+(i-a)*l/i+c)),n)}const i=e[t];let a=r,s=o;for(pn(e,r,t),n(e[o],i)>0&&pn(e,r,o);a<s;){for(pn(e,a,s),a++,s--;n(e[a],i)<0;)a++;for(;n(e[s],i)>0;)s--}0===n(e[r],i)?pn(e,r,s):(s++,pn(e,s,o)),s<=t&&(r=s+1),t<=s&&(o=s-1)}}function pn(e,t,r){const o=e[t];e[t]=e[r],e[r]=o}function fn(e,t){return e<t?-1:e>t?1:0}class yn{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data;const r=[];if(!Dn(e,t))return r;const o=this.toBBox,n=[];for(;t;){for(let i=0;i<t.children.length;i++){const a=t.children[i],s=t.leaf?o(a):a;Dn(e,s)&&(t.leaf?r.push(a):Sn(e,s)?this._all(a,r):n.push(a))}t=n.pop()}return r}collides(e){let t=this.data;if(!Dn(e,t))return!1;const r=[];for(;t;){for(let o=0;o<t.children.length;o++){const n=t.children[o],i=t.leaf?this.toBBox(n):n;if(Dn(e,i)){if(t.leaf||Sn(e,i))return!0;r.push(n)}}t=r.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let t=0;t<e.length;t++)this.insert(e[t]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){const e=this.data;this.data=t,t=e}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=Cn([]),this}remove(e,t){if(!e)return this;let r=this.data;const o=this.toBBox(e),n=[],i=[];let a,s,l;for(;r||n.length;){if(r||(r=n.pop(),s=n[n.length-1],a=i.pop(),l=!0),r.leaf){const o=mn(e,r.children,t);if(-1!==o)return r.children.splice(o,1),n.push(r),this._condense(n),this}l||r.leaf||!Sn(r,o)?s?(a++,r=s.children[a],l=!1):r=null:(n.push(r),i.push(a),a=0,s=r,r=r.children[0])}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){const r=[];for(;e;)e.leaf?t.push(...e.children):r.push(...e.children),e=r.pop();return t}_build(e,t,r,o){const n=r-t+1;let i,a=this._maxEntries;if(n<=a)return i=Cn(e.slice(t,r+1)),vn(i,this.toBBox),i;o||(o=Math.ceil(Math.log(n)/Math.log(a)),a=Math.ceil(n/Math.pow(a,o-1))),i=Cn([]),i.leaf=!1,i.height=o;const s=Math.ceil(n/a),l=s*Math.ceil(Math.sqrt(a));In(e,t,r,l,this.compareMinX);for(let c=t;c<=r;c+=l){const t=Math.min(c+l-1,r);In(e,c,t,s,this.compareMinY);for(let r=c;r<=t;r+=s){const n=Math.min(r+s-1,t);i.children.push(this._build(e,r,n,o-1))}}return vn(i,this.toBBox),i}_chooseSubtree(e,t,r,o){for(;o.push(t),!t.leaf&&o.length-1!==r;){let r,o=1/0,n=1/0;for(let i=0;i<t.children.length;i++){const a=t.children[i],s=Ln(a),l=En(e,a)-s;l<n?(n=l,o=s<o?s:o,r=a):l===n&&s<o&&(o=s,r=a)}t=r||t.children[0]}return t}_insert(e,t,r){const o=r?e:this.toBBox(e),n=[],i=this._chooseSubtree(o,this.data,t,n);for(i.children.push(e),bn(i,o);t>=0&&n[t].children.length>this._maxEntries;)this._split(n,t),t--;this._adjustParentBBoxes(o,n,t)}_split(e,t){const r=e[t],o=r.children.length,n=this._minEntries;this._chooseSplitAxis(r,n,o);const i=this._chooseSplitIndex(r,n,o),a=Cn(r.children.splice(i,r.children.length-i));a.height=r.height,a.leaf=r.leaf,vn(r,this.toBBox),vn(a,this.toBBox),t?e[t-1].children.push(a):this._splitRoot(r,a)}_splitRoot(e,t){this.data=Cn([e,t]),this.data.height=e.height+1,this.data.leaf=!1,vn(this.data,this.toBBox)}_chooseSplitIndex(e,t,r){let o,n=1/0,i=1/0;for(let a=t;a<=r-t;a++){const t=Mn(e,0,a,this.toBBox),s=Mn(e,a,r,this.toBBox),l=xn(t,s),c=Ln(t)+Ln(s);l<n?(n=l,o=a,i=c<i?c:i):l===n&&c<i&&(i=c,o=a)}return o||r-t}_chooseSplitAxis(e,t,r){const o=e.leaf?this.compareMinX:wn,n=e.leaf?this.compareMinY:Pn;this._allDistMargin(e,t,r,o)<this._allDistMargin(e,t,r,n)&&e.children.sort(o)}_allDistMargin(e,t,r,o){e.children.sort(o);const n=this.toBBox,i=Mn(e,0,t,n),a=Mn(e,r-t,r,n);let s=kn(i)+kn(a);for(let l=t;l<r-t;l++){const t=e.children[l];bn(i,e.leaf?n(t):t),s+=kn(i)}for(let l=r-t-1;l>=t;l--){const t=e.children[l];bn(a,e.leaf?n(t):t),s+=kn(a)}return s}_adjustParentBBoxes(e,t,r){for(let o=r;o>=0;o--)bn(t[o],e)}_condense(e){for(let t,r=e.length-1;r>=0;r--)0===e[r].children.length?r>0?(t=e[r-1].children,t.splice(t.indexOf(e[r]),1)):this.clear():vn(e[r],this.toBBox)}}function mn(e,t,r){if(!r)return t.indexOf(e);for(let o=0;o<t.length;o++)if(r(e,t[o]))return o;return-1}function vn(e,t){Mn(e,0,e.children.length,t,e)}function Mn(e,t,r,o,n){n||(n=Cn(null)),n.minX=1/0,n.minY=1/0,n.maxX=-1/0,n.maxY=-1/0;for(let i=t;i<r;i++){const t=e.children[i];bn(n,e.leaf?o(t):t)}return n}function bn(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function wn(e,t){return e.minX-t.minX}function Pn(e,t){return e.minY-t.minY}function Ln(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function kn(e){return e.maxX-e.minX+(e.maxY-e.minY)}function En(e,t){return(Math.max(t.maxX,e.maxX)-Math.min(t.minX,e.minX))*(Math.max(t.maxY,e.maxY)-Math.min(t.minY,e.minY))}function xn(e,t){const r=Math.max(e.minX,t.minX),o=Math.max(e.minY,t.minY),n=Math.min(e.maxX,t.maxX),i=Math.min(e.maxY,t.maxY);return Math.max(0,n-r)*Math.max(0,i-o)}function Sn(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function Dn(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function Cn(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function In(e,t,r,o,n){const i=[t,r];for(;i.length;){if((r=i.pop())-(t=i.pop())<=o)continue;const a=t+Math.ceil((r-t)/o/2)*o;dn(e,a,t,r,n),i.push(t,a,a,r)}}class An{constructor(e=[],t=(e,t)=>e<t?-1:e>t?1:0){if(this.data=e,this.length=this.data.length,this.compare=t,this.length>0)for(let r=(this.length>>1)-1;r>=0;r--)this._down(r)}push(e){this.data.push(e),this._up(this.length++)}pop(){if(0===this.length)return;const e=this.data[0],t=this.data.pop();return--this.length>0&&(this.data[0]=t,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:t,compare:r}=this,o=t[e];for(;e>0;){const n=e-1>>1,i=t[n];if(r(o,i)>=0)break;t[e]=i,e=n}t[e]=o}_down(e){const{data:t,compare:r}=this,o=this.length>>1,n=t[e];for(;e<o;){let o=1+(e<<1);const i=o+1;if(i<this.length&&r(t[i],t[o])<0&&(o=i),r(t[o],n)>=0)break;t[e]=t[o],e=o}t[e]=n}}const Fn=$(ce());function On(e,t,r){t=Math.max(0,void 0===t?2:t),r=r||0;const o=function(e){let t=e[0],r=e[0],o=e[0],n=e[0];for(let s=0;s<e.length;s++){const i=e[s];i[0]<t[0]&&(t=i),i[0]>o[0]&&(o=i),i[1]<r[1]&&(r=i),i[1]>n[1]&&(n=i)}const i=[t,r,o,n],a=i.slice();for(let s=0;s<e.length;s++)Fn(e[s],i)||a.push(e[s]);return function(e){e.sort(qn);const t=[];for(let o=0;o<e.length;o++){for(;t.length>=2&&zn(t[t.length-2],t[t.length-1],e[o])<=0;)t.pop();t.push(e[o])}const r=[];for(let o=e.length-1;o>=0;o--){for(;r.length>=2&&zn(r[r.length-2],r[r.length-1],e[o])<=0;)r.pop();r.push(e[o])}return r.pop(),t.pop(),t.concat(r)}(a)}(e),n=new yn(16);n.toBBox=function(e){return{minX:e[0],minY:e[1],maxX:e[0],maxY:e[1]}},n.compareMinX=function(e,t){return e[0]-t[0]},n.compareMinY=function(e,t){return e[1]-t[1]},n.load(e);const i=[];let a;for(let g=0;g<o.length;g++){const e=o[g];n.remove(e),a=Rn(e,a),i.push(a)}const s=new yn(16);for(let g=0;g<i.length;g++)s.insert(Un(i[g]));const l=t*t,c=r*r;for(;i.length;){const e=i.shift(),t=e.p,r=e.next.p,o=Xn(t,r);if(o<c)continue;const a=o/l,u=Tn(n,e.prev.p,t,r,e.next.next.p,a,s);u&&Math.min(Xn(u,t),Xn(u,r))<=a&&(i.push(e),i.push(Rn(u,e)),n.remove(u),s.remove(e),s.insert(Un(e)),s.insert(Un(e.next)))}let u=a;const h=[];do{h.push(u.p),u=u.next}while(u!==a);return h.push(u.p),h}function Tn(e,t,r,o,n,i,a){const s=new An([],_n);let l=e.data;for(;l;){for(let e=0;e<l.children.length;e++){const t=l.children[e],n=l.leaf?Yn(t,r,o):Gn(r,o,t);n>i||s.push({node:t,dist:n})}for(;s.length&&!s.peek().node.children;){const e=s.pop(),i=e.node,l=Yn(i,t,r),c=Yn(i,o,n);if(e.dist<l&&e.dist<c&&Bn(r,i,a)&&Bn(o,i,a))return i}l=s.pop(),l&&(l=l.node)}return null}function _n(e,t){return e.dist-t.dist}function Gn(e,t,r){if(Hn(e,r)||Hn(t,r))return 0;const o=Vn(e[0],e[1],t[0],t[1],r.minX,r.minY,r.maxX,r.minY);if(0===o)return 0;const n=Vn(e[0],e[1],t[0],t[1],r.minX,r.minY,r.minX,r.maxY);if(0===n)return 0;const i=Vn(e[0],e[1],t[0],t[1],r.maxX,r.minY,r.maxX,r.maxY);if(0===i)return 0;const a=Vn(e[0],e[1],t[0],t[1],r.minX,r.maxY,r.maxX,r.maxY);return 0===a?0:Math.min(o,n,i,a)}function Hn(e,t){return e[0]>=t.minX&&e[0]<=t.maxX&&e[1]>=t.minY&&e[1]<=t.maxY}function Bn(e,t,r){const o=Math.min(e[0],t[0]),n=Math.min(e[1],t[1]),i=Math.max(e[0],t[0]),a=Math.max(e[1],t[1]),s=r.search({minX:o,minY:n,maxX:i,maxY:a});for(let l=0;l<s.length;l++)if(Nn(s[l].p,s[l].next.p,e,t))return!1;return!0}function zn(e,t,r){return Rr(e[0],e[1],t[0],t[1],r[0],r[1])}function Nn(e,t,r,o){return e!==o&&t!==r&&zn(e,t,r)>0!=zn(e,t,o)>0&&zn(r,o,e)>0!=zn(r,o,t)>0}function Un(e){const t=e.p,r=e.next.p;return e.minX=Math.min(t[0],r[0]),e.minY=Math.min(t[1],r[1]),e.maxX=Math.max(t[0],r[0]),e.maxY=Math.max(t[1],r[1]),e}function Rn(e,t){const r={p:e,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return t?(r.next=t.next,r.prev=t,t.next.prev=r,t.next=r):(r.prev=r,r.next=r),r}function Xn(e,t){const r=e[0]-t[0],o=e[1]-t[1];return r*r+o*o}function Yn(e,t,r){let o=t[0],n=t[1],i=r[0]-o,a=r[1]-n;if(0!==i||0!==a){const t=((e[0]-o)*i+(e[1]-n)*a)/(i*i+a*a);t>1?(o=r[0],n=r[1]):t>0&&(o+=i*t,n+=a*t)}return i=e[0]-o,a=e[1]-n,i*i+a*a}function Vn(e,t,r,o,n,i,a,s){const l=r-e,c=o-t,u=a-n,h=s-i,g=e-n,d=t-i,p=l*l+c*c,f=l*u+c*h,y=u*u+h*h,m=l*g+c*d,v=u*g+h*d,M=p*y-f*f;let b,w,P=M,L=M;0===M?(b=0,P=1,w=v,L=y):(b=f*v-y*m,w=p*v-f*m,b<0?(b=0,w=v,L=y):b>P&&(b=P,w=v+f,L=y)),w<0?(w=0,-m<0?b=0:-m>p?b=P:(b=-m,P=p)):w>L&&(w=L,-m+f<0?b=0:-m+f>p?b=P:(b=-m+f,P=p));const k=0===b?0:b/P,E=0===w?0:w/L,x=(1-E)*n+E*a-((1-k)*e+k*r),S=(1-E)*i+E*s-((1-k)*t+k*o);return x*x+S*S}function qn(e,t){return e[0]===t[0]?e[1]-t[1]:e[0]-t[0]}const jn=()=>"ontouchstart"in window||navigator.maxTouchPoints>0;function Wn(){return"undefined"!=typeof vitest}class $n{static getBounds(e,t=0){const r=[];e.forEach(e=>{isNaN(e.lat)||isNaN(e.lng),r.push(e)});const o=new s.Polyline(r).getBounds();return 0!==t?o.pad(t):o}}class Kn{constructor(e=0,t=0,r=0,o=0){i(this,"direction",{East:new s.LatLng(0,0),North:new s.LatLng(0,0),NorthEast:new s.LatLng(0,0),NorthWest:new s.LatLng(0,0),South:new s.LatLng(0,0),SouthEast:new s.LatLng(0,0),SouthWest:new s.LatLng(0,0),West:new s.LatLng(0,0)}),this.direction.North=new s.LatLng(r,(t+o)/2),this.direction.NorthEast=new s.LatLng(r,o),this.direction.East=new s.LatLng((e+r)/2,o),this.direction.SouthEast=new s.LatLng(e,o),this.direction.South=new s.LatLng(e,(t+o)/2),this.direction.SouthWest=new s.LatLng(e,t),this.direction.West=new s.LatLng((e+r)/2,t),this.direction.NorthWest=new s.LatLng(r,t)}getDirection(e){switch(e){case u.SouthWest:return this.direction.SouthWest;case u.West:return this.direction.West;case u.NorthWest:return this.direction.NorthWest;case u.North:return this.direction.North;case u.NorthEast:return this.direction.NorthEast;case u.East:return this.direction.East;case u.SouthEast:return this.direction.SouthEast;case u.South:return this.direction.South;default:throw new Error}}getPositions(e=u.SouthWest,t=!1,r=!0){const o=[],n=this.getPositionAsArray(e,t);return n.forEach(e=>{o.push([e.lng,e.lat])}),r&&o.push([n[0].lng,n[0].lat]),o}getPositionAsArray(e=u.NorthEast,t=!1){const r=[];if(t?(r.push(this.direction.SouthWest),r.push(this.direction.West),r.push(this.direction.NorthWest),r.push(this.direction.North),r.push(this.direction.NorthEast),r.push(this.direction.East),r.push(this.direction.SouthEast),r.push(this.direction.South)):(r.push(this.direction.SouthWest),r.push(this.direction.South),r.push(this.direction.SouthEast),r.push(this.direction.East),r.push(this.direction.NorthEast),r.push(this.direction.North),r.push(this.direction.NorthWest),r.push(this.direction.West)),e!==u.SouthWest){r.splice(0,e).forEach((t,o)=>{r.splice(e+o,0,t)})}return r}}class Jn{constructor(e,t){if(i(this,"metricLength",""),i(this,"metricUnit",""),i(this,"imperialLength",""),i(this,"imperialUnit",""),null!==e||void 0!==e){0===e?t.markers.markerInfoIcon.usePerimeterMinValue?(this.metricLength=t.markers.markerInfoIcon.values.min.metric,this.metricUnit=t.markers.markerInfoIcon.units.metric.perimeter.m,this.imperialLength=t.markers.markerInfoIcon.values.min.imperial,this.imperialUnit=t.markers.markerInfoIcon.units.imperial.perimeter.feet):(this.metricLength=t.markers.markerInfoIcon.values.unknown.metric,this.metricUnit=t.markers.markerInfoIcon.units.unknownUnit,this.imperialLength=t.markers.markerInfoIcon.values.unknown.imperial,this.imperialUnit=t.markers.markerInfoIcon.units.unknownUnit):e<100?(this.metricLength=(10*Math.ceil(e/10)).toString(),this.metricUnit=t.markers.markerInfoIcon.units.metric.perimeter.m):e<500?(this.metricLength=(50*Math.ceil(e/50)).toString(),this.metricUnit=t.markers.markerInfoIcon.units.metric.perimeter.m):e<1e3?(this.metricLength=(100*Math.ceil(e/100)).toString(),this.metricUnit=t.markers.markerInfoIcon.units.metric.perimeter.m):e<1e4?(this.metricLength=(100*Math.ceil(e/100)/1e3).toFixed(1),this.metricUnit=t.markers.markerInfoIcon.units.metric.perimeter.km):(this.metricLength=(1e3*Math.ceil(e/1e3)/1e3).toString(),this.metricUnit=t.markers.markerInfoIcon.units.metric.perimeter.km);const r=e/.0254/12,o=r/3,n=o/1760;e<1e3/2.54?(this.imperialLength=(10*Math.ceil(r/10)).toString(),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.perimeter.feet):e<1e3/2.54*3?(this.imperialLength=(10*Math.ceil(o/10)).toString(),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.perimeter.yards):e<1609?(this.imperialLength=n.toFixed(2),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.perimeter.miles):e<16093?(this.imperialLength=n.toFixed(1),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.perimeter.miles):(this.imperialLength=n.toFixed(0),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.perimeter.miles)}}}class Zn{constructor(e,t){i(this,"metricArea",""),i(this,"metricUnit",""),i(this,"imperialArea",""),i(this,"imperialUnit","");const r=e,o=t.markers.markerInfoIcon.units.metric.onlyMetrics;if(null!==r||void 0!==r){0===r?(this.metricArea="-",this.metricUnit=t.markers.markerInfoIcon.units.unknownUnit,this.imperialArea="-",this.imperialUnit=t.markers.markerInfoIcon.units.unknownUnit):r<1e4?(this.metricArea=Math.round(r).toString(),this.metricUnit=t.markers.markerInfoIcon.units.metric.area.m2):r<1e5?o?(this.metricArea=(r/1e6).toFixed(2),this.metricUnit=t.markers.markerInfoIcon.units.metric.area.km2):(this.metricArea=(r/1e3).toFixed(1),this.metricUnit=t.markers.markerInfoIcon.units.metric.area.daa):r<1e7?o?(this.metricArea=(r/1e6).toFixed(2),this.metricUnit=t.markers.markerInfoIcon.units.metric.area.km2):(this.metricArea=Math.round(r/1e3).toString(),this.metricUnit=t.markers.markerInfoIcon.units.metric.area.daa):r<1e8?o?(this.metricArea=(r/1e6).toFixed(1),this.metricUnit=t.markers.markerInfoIcon.units.metric.area.km2):(this.metricArea=Math.round(r/1e4).toString(),this.metricUnit=t.markers.markerInfoIcon.units.metric.area.ha):(this.metricArea=Math.round(r/1e6).toString(),this.metricUnit=t.markers.markerInfoIcon.units.metric.area.km2);const e=.0069444*(1550*r),n=.11111*e,i=20661e-8*n,a=3.2283e-7*n;r<92.9?(this.imperialArea=Math.round(e).toString(),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.area.feet2):r<836.14?(this.imperialArea=n.toFixed(0),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.area.yards2):r<40469.6?(this.imperialArea=i.toFixed(2),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.area.acres):r<404696?(this.imperialArea=i.toFixed(1),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.area.acres):r<4046960?(this.imperialArea=i.toFixed(0),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.area.acres):r<25900404?(this.imperialArea=a.toFixed(2),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.area.miles2):r<259004040?(this.imperialArea=a.toFixed(1),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.area.miles2):(this.imperialArea=a.toFixed(0),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.area.miles2)}}}function Qn(e,...t){if(!t.length)return e;for(const r of t)if(r)for(const t in r){const o=r[t],n=e[t];if(o&&"object"==typeof o&&!Array.isArray(o)){const r=n&&"object"==typeof n&&!Array.isArray(n)?n:{};e[t]=Qn(r,o)}else void 0!==o&&(e[t]=o)}return e}class ei{constructor(e){i(this,"config",g),i(this,"fallbackWarnings",new Set),this.config=Qn(structuredClone(g),e)}warnFallbackOnce(e,t){Wn()||this.fallbackWarnings.has(e)||(this.fallbackWarnings.add(e),console.warn(t))}toProjectedTolerance(e,t){if(e<=0)return 0;try{const r=d*y,o=e*r,n=Math.cos(t.lat*y);return 0===n?e:o/(r*n)}catch{return e}}getFeatureDiagonal(e){try{const[t,r,o,n]=k(e);return Math.hypot(o-t,n-r)}catch{return 0}}getRingDiagonal(e){if(!e||0===e.length)return 0;let t=e[0].lat,r=e[0].lat,o=e[0].lng,n=e[0].lng;for(const i of e)t=Math.min(t,i.lat),r=Math.max(r,i.lat),o=Math.min(o,i.lng),n=Math.max(n,i.lng);return Math.hypot(n-o,r-t)}getAdaptiveTolerance(e,t){if(e<=0)return 0;if(t<=0)return e;const r=.02*t;return Math.min(e,r)}union(e,t){try{const r=P([e,t]),o=zt(r);return o?this.getTurfPolygon(o):null}catch(r){return Wn()||console.warn("Error in union:",r instanceof Error?r.message:String(r)),null}}createPolygonFromTrace(e){var t;const r=null==(t=this.config.polygonCreation)?void 0:t.algorithm;void 0!==r&&"string"!=typeof r&&this.warnFallbackOnce("polygonCreation.algorithm.type",'[Leaflet.Polydraw] Invalid `polygonCreation.algorithm` type. Using "concaveman" as fallback.');const o="string"==typeof r?r:"concaveman";switch(o){case"concaveman":return this.turfConcaveman(e);case"convex":return this.createConvexPolygon(e);case"direct":return this.createDirectPolygon(e);case"buffer":return this.warnFallbackOnce("polygonCreation.algorithm.buffer",'[Leaflet.Polydraw] `polygonCreation.algorithm: "buffer"` is deprecated. Using "concaveman" as fallback.'),this.turfConcaveman(e);default:return this.warnFallbackOnce(`polygonCreation.algorithm.unknown:${o}`,`[Leaflet.Polydraw] Unknown polygon creation algorithm "${o}". Using "concaveman" as fallback.`),this.turfConcaveman(e)}}turfConcaveman(e){return w([[On(Vt(e).features.map(e=>e.geometry.coordinates))]])}createConvexPolygon(e){const t=Vt(e),r=ye(t);return r?this.getTurfPolygon(r):(this.warnFallbackOnce("polygonCreation.algorithm.convex.noHull",'[Leaflet.Polydraw] Convex hull generation failed. Using "direct" polygon creation as fallback.'),this.createDirectPolygon(e))}createDirectPolygon(e){let t;if("LineString"===e.geometry.type)t=e.geometry.coordinates;else if("Polygon"===e.geometry.type)t=e.geometry.coordinates[0];else{t=Vt(e).features.map(e=>e.geometry.coordinates)}if(t.length>0){const e=t[0],r=t[t.length-1];e[0]===r[0]&&e[1]===r[1]||t.push([e[0],e[1]])}return t.length<4?(Wn()||console.warn("Not enough points for direct polygon, falling back to concaveman"),this.turfConcaveman(e)):w([[t]])}getSimplified(e,t=!1){const r=this.resolveSimplificationConfig();if("none"===r.strategy)return e;if("simple"===r.strategy){const t=this.getAdaptiveTolerance(r.simple.tolerance,this.getFeatureDiagonal(e));return cr(e,{tolerance:this.toProjectedTolerance(t,this.getReferenceLatLng(e)),highQuality:r.simple.highQuality,mutate:!1})}const o=e.geometry.coordinates[0][0].length,n=r.dynamic.fractionGuard,i=r.dynamic.multiplier,a=this.getAdaptiveTolerance(r.dynamic.baseTolerance,this.getFeatureDiagonal(e)),s={highQuality:r.dynamic.highQuality,mutate:!1},l=t=>cr(e,{...s,tolerance:this.toProjectedTolerance(t,this.getReferenceLatLng(e))});if(!t)return l(a);let c=a,u=l(c);for(;u.geometry.coordinates[0][0].length>4&&u.geometry.coordinates[0][0].length/(o+2)>n;)c*=i,u=l(c);return u}simplifyLatLngRing(e,t,r=!0){var o,n;if(!e||0===e.length||t<=0)return e?[...e]:[];const i=[...e],a=i[0],s=i[i.length-1];s&&a&&s.lat===a.lat&&s.lng===a.lng||i.push({lat:a.lat,lng:a.lng});const l=i.map(e=>[e.lng,e.lat]),c=this.getAdaptiveTolerance(t,this.getRingDiagonal(i));try{const t=b([l]),i=cr(t,{tolerance:this.toProjectedTolerance(c,e[0]),highQuality:r,mutate:!1}),a=null==(n=null==(o=null==i?void 0:i.geometry)?void 0:o.coordinates)?void 0:n[0];return a&&0!==a.length?a.map(e=>({lat:e[1],lng:e[0]})):[...e]}catch(u){return Wn()||console.warn("Error simplifying ring:",u instanceof Error?u.message:String(u)),[...e]}}resolveSimplificationConfig(){const e=this.config.simplification,t=null==e?void 0:e.simple,r=null==e?void 0:e.dynamic,o=null==e?void 0:e.strategy,n=(e,t)=>"number"!=typeof e||!Number.isFinite(e)||e<0?(void 0!==e&&this.warnFallbackOnce(`simplification.invalidNumber:${String(e)}`,"[Leaflet.Polydraw] Invalid simplification numeric value. Using fallback default."),t):e,i=(e,t)=>"boolean"!=typeof e?(void 0!==e&&this.warnFallbackOnce(`simplification.invalidBoolean:${String(e)}`,"[Leaflet.Polydraw] Invalid simplification boolean value. Using fallback default."),t):e;let a="simple";"simple"===o||"dynamic"===o||"none"===o?a=o:void 0!==o&&this.warnFallbackOnce(`simplification.invalidStrategy:${String(o)}`,'[Leaflet.Polydraw] Invalid `simplification.strategy`. Using "simple" as fallback.');return{strategy:a,simple:{tolerance:n(null==t?void 0:t.tolerance,1e-4),highQuality:i(null==t?void 0:t.highQuality,!1)},dynamic:{baseTolerance:n(null==r?void 0:r.baseTolerance,1e-4),highQuality:i(null==r?void 0:r.highQuality,!1),fractionGuard:((e,t)=>"number"==typeof e&&Number.isFinite(e)?((e<0||e>1)&&this.warnFallbackOnce(`simplification.outOfRangeFraction:${e}`,"[Leaflet.Polydraw] `simplification.dynamic.fractionGuard` is out of range [0, 1]. Clamping to nearest valid value."),Math.max(0,Math.min(1,e))):(void 0!==e&&this.warnFallbackOnce(`simplification.invalidFraction:${String(e)}`,"[Leaflet.Polydraw] Invalid `simplification.dynamic.fractionGuard`. Using fallback default."),t))(null==r?void 0:r.fractionGuard,.9),multiplier:((e,t)=>"number"!=typeof e||!Number.isFinite(e)||e<=1?(void 0!==e&&this.warnFallbackOnce(`simplification.invalidMultiplier:${String(e)}`,"[Leaflet.Polydraw] Invalid `simplification.dynamic.multiplier` (must be > 1). Using fallback default."),t):e)(null==r?void 0:r.multiplier,2)}}}getTurfPolygon(e){let t;return t="Polygon"===e.geometry.type?w([e.geometry.coordinates]):w(e.geometry.coordinates),t}getMultiPolygon(e){return w(e)}getKinks(e){try{if(!e||!e.geometry||!e.geometry.coordinates)return[e];const t=this.removeDuplicateVertices(e);if(!t||!t.geometry||!t.geometry.coordinates)return Wn()||console.warn("Feature became invalid after cleaning in getKinks"),[e];if(this.polygonHasHoles(t))return this.getKinksWithHolePreservation(t);{const e=to(t),r=[];return Ut(e,e=>{r.push(e)}),r}}catch(t){return Wn()||console.warn("Error processing kinks:",t instanceof Error?t.message:String(t)),[e]}}getCoords(e){return L(e)}getReferenceLatLng(e){var t,r;try{const o=L(e),n=null==(r=null==(t=null==o?void 0:o[0])?void 0:t[0])?void 0:r[0];if(n&&Array.isArray(n)&&n.length>=2)return{lat:n[1],lng:n[0]}}catch{}return{lat:0,lng:0}}hasKinks(e){return hr(e).features.length>0}getConvexHull(e){try{const t=P([e]);return ye(t)}catch(t){return Wn()||console.warn("Error in getConvexHull:",t instanceof Error?t.message:String(t)),null}}getMidpoint(e,t){const r=x(v([e.lng,e.lat]),v([t.lng,t.lat]));return{lat:r.geometry.coordinates[1],lng:r.geometry.coordinates[0]}}polygonIntersect(e,t){try{if(!(e&&e.geometry&&e.geometry.coordinates&&t&&t.geometry&&t.geometry.coordinates))return Wn()||console.warn("Invalid features passed to polygonIntersect"),!1;const r=e=>{var t,r;return Array.isArray(null==(r=null==(t=e[0])?void 0:t[0])?void 0:r[0])},o=e=>{if(!Array.isArray(e))return!1;const t=r(e)?e.flat():e;for(const r of t){if(!Array.isArray(r))return!1;for(const e of r){if(!Array.isArray(e)||e.length<2)return!1;if(e.some(e=>null==e||!isFinite(e)))return!1}}return!0};if(!o(e.geometry.coordinates)||!o(t.geometry.coordinates))return!1;try{const r=P([e,t]),o=Rt(r);if(o&&o.geometry&&("Polygon"===o.geometry.type||"MultiPolygon"===o.geometry.type)){if(j(o)>1e-6)return!0}}catch{}try{const r=Vt(e),o=Vt(t);for(const t of o.features)if(Vr(t,e))return!0;for(const e of r.features)if(Vr(e,t))return!0}catch{}try{const r=L(e),o=L(t);for(const e of r){const t=e[0];if(t&&!(t.length<2))for(let e=0;e<t.length-1;e++){const r=t[e],n=t[e+1];if(!r||!n||!Array.isArray(r)||!Array.isArray(n)||r.length<2||n.length<2||r.some(e=>null==e||!isFinite(e))||n.some(e=>null==e||!isFinite(e)))continue;const i=M([r,n]);for(const e of o){const t=e[0];if(t&&!(t.length<2))for(let e=0;e<t.length-1;e++){const r=t[e],o=t[e+1];if(!r||!o||!Array.isArray(r)||!Array.isArray(o)||r.length<2||o.length<2||r.some(e=>null==e||!isFinite(e))||o.some(e=>null==e||!isFinite(e)))continue;const n=M([r,o]);try{const e=Be(i,n);if(e&&e.features&&e.features.length>0)return!0}catch{}}}}}}catch{}return!1}catch(r){return Wn()||console.warn("Error in polygonIntersect:",r instanceof Error?r.message:String(r)),!1}}getIntersection(e,t){try{const r=P([e,t]),o=Rt(r);return o&&o.geometry&&("Polygon"===o.geometry.type||"MultiPolygon"===o.geometry.type)?o:null}catch(r){return Wn()||console.warn("Error in getIntersection:",r instanceof Error?r.message:String(r)),null}}getDistance(e,t){return E(e,t)}isWithin(e,t){return zo(b([e]),b([t]))}isPolygonCompletelyWithin(e,t){try{return zo(e,t)}catch{const r=L(e),o=L(t);for(const e of r)for(const t of e)for(const e of t){const t=v(e);let r=!1;for(const e of o){for(const o of e){const e=b([o]);if(Vr(t,e)){r=!0;break}}if(r)break}if(!r)return!1}return!0}}toPointFeature(e){if((e=>{var t;if(!e||"object"!=typeof e)return!1;const r=e;return"Feature"===r.type&&"Point"===(null==(t=r.geometry)?void 0:t.type)})(e))return e;if(Array.isArray(e)&&e.length>=2&&"number"==typeof e[0]&&"number"==typeof e[1])return v(e);if((t=e)&&"object"==typeof t&&"number"==typeof t.lat&&"number"==typeof t.lng){const t=e;return v([t.lng,t.lat])}var t;if((e=>{if(!e||"object"!=typeof e)return!1;const t=e.geometry;return!!t&&Array.isArray(t.coordinates)})(e))return v(e.geometry.coordinates);throw new Error("Unsupported point format provided to toPointFeature")}isPointInsidePolygon(e,t){try{const r=this.toPointFeature(e);return Vr(r,t)}catch{return!1}}equalPolygons(e,t){return $o(e,t)}convertToBoundingBoxPolygon(e){const t=function(e){const[t,r,o,n]=e;return b([[[t,r],[o,r],[o,n],[t,n],[t,r]]])}(k(e));return t}polygonToMultiPolygon(e){return w([e.geometry.coordinates])}injectPointToPolygon(e,t,r){const o=JSON.parse(JSON.stringify(e));let n;if("MultiPolygon"===o.geometry.type)n=o.geometry.coordinates[0][r];else{if("Polygon"!==o.geometry.type)return o;n=o.geometry.coordinates[r]}if(!n)return o;let i=1/0,a=0;for(let s=0;s<n.length-1;s++){const e=n[s],r=n[s+1],o=this.distanceToLineSegment(t,e,r);o<i&&(i=o,a=s+1)}return n.splice(a,0,t),o}distanceToLineSegment(e,t,r){const o=e[0]-t[0],n=e[1]-t[1],i=r[0]-t[0],a=r[1]-t[1],s=o*i+n*a,l=i*i+a*a;if(0===l)return Math.sqrt(o*o+n*n);const c=s/l;let u,h;c<0?(u=t[0],h=t[1]):c>1?(u=r[0],h=r[1]):(u=t[0]+c*i,h=t[1]+c*a);const g=e[0]-u,d=e[1]-h;return Math.sqrt(g*g+d*d)}polygonDifference(e,t){try{const r=P([e,t]),o=Xt(r);return o?this.getTurfPolygon(o):null}catch(r){return Wn()||console.warn("Error in polygonDifference:",r instanceof Error?r.message:String(r)),null}}getBoundingBoxCompassPosition(e,t,r,o){return null}getNearestPointIndex(e,t){return an(e,t).properties.featureIndex??0}getCoord(e){return[e.lng,e.lat]}createPolygon(e){return b(e)}getFeaturePointCollection(e){const t=[];e.forEach(e=>{const r=v([e.lng,e.lat],{});t.push(r)});return P(t)}getPolygonArea(e){return j(e)}getPolygonPerimeter(e){return gn(e,{units:"kilometers"})}getCenterOfMass(e){return ke(e)}getDoubleElbowLatLngs(e){const t=[],r=e.length,o=e[0].lat===e[r-1].lat&&e[0].lng===e[r-1].lng?r-1:r;for(let n=0;n<o;n++){const r=e[n],i=e[(n+1)%o];t.push(new s.LatLng(r.lat,r.lng));const a=x(v([r.lng,r.lat]),v([i.lng,i.lat]));t.push(new s.LatLng(a.geometry.coordinates[1],a.geometry.coordinates[0]))}return t}getBezierMultiPolygon(e){const t=e=>{if(!e||0===e.length)return e;const t=e[0],r=e[e.length-1];return t[0]===r[0]&&t[1]===r[1]?e:[...e,[t[0],t[1]]]},r=e.map(e=>e.map(e=>{const r=t(e);try{const e=M(r),o=ln(e,{resolution:this.config.polygonTools.bezier.resolution,sharpness:this.config.polygonTools.bezier.sharpness}).geometry.coordinates??r,n=Math.max(2,r.length-1),i=Math.max(1,this.config.polygonTools.bezier.resampleMultiplier??10),a=Math.max(4,this.config.polygonTools.bezier.maxNodes??o.length),s=((e,r)=>{const o=t(e);if(!o||o.length<2)return o;const n=(e,t)=>{const r=e[0]-t[0],o=e[1]-t[1];return Math.sqrt(r*r+o*o)};let i=0;for(let t=1;t<o.length;t++)i+=n(o[t-1],o[t]);if(!Number.isFinite(i)||i<=0)return o;const a=i/Math.max(r,4),s=[o[0]];let l=0;for(let t=1;t<o.length;t++){let e=o[t-1];const r=o[t];let i=n(e,r);for(;l+i>=a&&i>0;){const t=(a-l)/i,o=[e[0]+(r[0]-e[0])*t,e[1]+(r[1]-e[1])*t];s.push(o),e=o,i=n(e,r),l=0}l+=i}return t(s)})(o,Math.max(4,Math.min(a,n*i))),l=(e=>{if(!e||0===e.length)return e;const r=1e-6,o=new Set,n=[];for(let t=0;t<e.length;t++){const i=e[t];if(!Array.isArray(i)||i.length<2)continue;const a=`${Math.round(i[0]/r)}:${Math.round(i[1]/r)}`;o.has(a)||(o.add(a),n.push(i))}return t(n)})(s);return l.length>=4?l:r}catch(o){return Wn()||console.warn("Bezier smoothing failed for ring, falling back to original:",o),r}}));return this.getMultiPolygon(r)}polygonHasHoles(e){try{return"Polygon"===e.geometry.type?e.geometry.coordinates.length>1:"MultiPolygon"===e.geometry.type&&e.geometry.coordinates.some(e=>e.length>1)}catch(t){return Wn()||console.warn("Error checking for holes:",t instanceof Error?t.message:String(t)),!1}}getKinksWithHolePreservation(e){try{if("Polygon"===e.geometry.type){const t=e.geometry.coordinates,r=t[0],o=t.slice(1),n={type:"Feature",geometry:{type:"Polygon",coordinates:[r]},properties:e.properties||{}},i=this.hasKinks(n),a=this.checkOuterRingHoleIntersection(r,o);if(i||a){if(this.checkIfDragCompletelyThroughHole(r,o))return this.handleCompleteHoleTraversal(n,o);const e=to(n),t=[];return Ut(e,e=>{const r=this.subtractIntersectingHoles(e,o);t.push(r)}),t}return[e]}if("MultiPolygon"===e.geometry.type){const t=[];for(const r of e.geometry.coordinates){const o={type:"Feature",geometry:{type:"Polygon",coordinates:r},properties:e.properties||{}},n=this.getKinksWithHolePreservation(o);t.push(...n)}return t}return[e]}catch(t){return Wn()||console.warn("Error in getKinksWithHolePreservation:",t instanceof Error?t.message:String(t)),[e]}}checkIfDragCompletelyThroughHole(e,t){try{if(this.findDuplicatePoints(e).length>0)return!0;const r=this.findSelfIntersectionLine(e);if(r&&t.length>0)for(const e of t)if(this.lineCompletelyTraversesHole(r,e))return!0;if(this.hasKinks({type:"Feature",geometry:{type:"Polygon",coordinates:[e]},properties:{}}))for(const o of t)if(this.holeIsCutByKinks(e,o))return!0;return!1}catch(r){return Wn()||console.warn("Error checking complete hole traversal:",r instanceof Error?r.message:String(r)),!1}}findSelfIntersectionLine(e){try{const t=new Map;for(let r=0;r<e.length-1;r++){const o=e[r],n=`${o[0]},${o[1]}`;t.has(n)?t.get(n).indices.push(r):t.set(n,{point:o,indices:[r]})}for(const[,r]of t)if(r.indices.length>=2){const t=r.indices[0],o=r.indices[1],n=[];for(let r=t;r<=o;r++)n.push(e[r]);return n}return null}catch(t){return Wn()||console.warn("Error finding self-intersection line:",t instanceof Error?t.message:String(t)),null}}lineCompletelyTraversesHole(e,t){try{if(e.length<2)return!1;const r=e[0],o=e[e.length-1],n=b([t]),i=Vr(v(r),n);return i!==Vr(v(o),n)}catch(r){return Wn()||console.warn("Error checking line hole traversal:",r instanceof Error?r.message:String(r)),!1}}holeIsCutByKinks(e,t){try{const r=b([e]),o=b([t]),n=hr(r);if(0===n.features.length)return!1;for(const e of n.features){const t=e.geometry.coordinates;try{if(E(v(t),S(o))<.01)return!0;if(Vr(v(t),o))return!0}catch{if(Vr(v(t),o))return!0}}return!1}catch(r){return Wn()||console.warn("Error checking hole cut by kinks:",r.message),!1}}findDuplicatePoints(e){const t=[],r=new Set;for(let o=0;o<e.length-1;o++){const n=e[o],i=`${n[0]},${n[1]}`;r.has(i)?t.push(n):r.add(i)}return t}checkOuterRingHoleIntersection(e,t){try{if(0===t.length)return!1;const r=b([e]);for(const o of t){const t=b([o]);if(this.getIntersection(r,t))return!0;for(let r=0;r<e.length-1;r++){const o=e[r];if(Vr(v(o),t))return!0}}return!1}catch{return!1}}handleCompleteHoleTraversal(e,t){try{const t={type:"Feature",geometry:{type:"Polygon",coordinates:[e.geometry.coordinates[0]]},properties:e.properties||{}},r=to(t),o=[];return Ut(r,e=>{e._polydrawHoleTraversalOccurred=!0,o.push(e)}),o}catch(r){Wn()||console.warn("Error handling complete hole traversal:",r instanceof Error?r.message:String(r));try{const t={...e,geometry:{...e.geometry,coordinates:[e.geometry.coordinates[0]]}};return t._polydrawHoleTraversalOccurred=!0,[t]}catch{return[e]}}}subtractIntersectingHoles(e,t){try{let r=e;for(const e of t){const t=b([e]);if(this.getIntersection(t,r)){const e=this.polygonDifference(r,t);if(e)if("Polygon"===e.geometry.type)r=e;else if("MultiPolygon"===e.geometry.type){const t=e;let o=0,n=null;for(const e of t.geometry.coordinates){const t={type:"Feature",geometry:{type:"Polygon",coordinates:e},properties:{}},r=j(t);r>o&&(o=r,n=t)}n&&(r=n)}}}return r}catch(r){return Wn()||console.warn("Error subtracting intersecting holes:",r instanceof Error?r.message:String(r)),e}}removeDuplicateVertices(e){if(!e||!e.geometry||!e.geometry.coordinates)return Wn()||console.warn("Invalid feature passed to removeDuplicateVertices"),e;const t=e=>{if(!e||e.length<3)return Wn()||console.warn("Invalid coordinates array - need at least 3 points for a polygon"),e||[];const t=[],r=1e-6,o=new Set;for(let n=0;n<e.length;n++){const i=e[n],a=e[(n+1)%e.length];if(!i||!Array.isArray(i)||i.length<2||!a||!Array.isArray(a)||a.length<2)continue;const s=Math.abs(i[1]-a[1]),l=Math.abs(i[0]-a[0]),c=`${Math.round(i[0]/r)}:${Math.round(i[1]/r)}`,u=o.has(c);(s>r||l>r)&&!u&&(t.push(i),o.add(c))}if(t.length<3)return Wn()||console.warn("After cleaning, polygon has less than 3 points"),e;if(t.length>0){const e=t[0],o=t[t.length-1],n=Math.abs(e[1]-o[1]),i=Math.abs(e[0]-o[0]);(n>r||i>r)&&t.push([e[0],e[1]])}return t};try{if("Polygon"===e.geometry.type){const r=e.geometry.coordinates.map(e=>t(e));return r.some(e=>e.length<4)?(Wn()||console.warn("Cleaned polygon has invalid ring with less than 4 coordinates"),e):{...e,geometry:{...e.geometry,coordinates:r}}}if("MultiPolygon"===e.geometry.type){const r=e.geometry.coordinates.map(e=>e.map(e=>t(e)));return r.some(e=>e.some(e=>e.length<4))?(Wn()||console.warn("Cleaned multipolygon has invalid ring with less than 4 coordinates"),e):{...e,geometry:{...e.geometry,coordinates:r}}}}catch(r){return Wn()||console.warn("Error in removeDuplicateVertices:",r instanceof Error?r.message:String(r)),e}return e}}const ti=()=>{if("undefined"!=typeof globalThis)return globalThis.L};class ri{static getVersion(){if(this._detectedVersion)return this._detectedVersion;const e=ti();return e?(this._detectedVersion=this.detectVersion(e),this._detectedVersion):l.V2}static detectVersion(e){const t=e??ti();if(!t)return l.V2;if(t.version){if(t.version.startsWith("2."))return l.V2;if(t.version.startsWith("1."))return l.V1}return"function"!=typeof t.marker?l.V2:"function"==typeof t.marker&&"function"==typeof t.polyline&&"function"==typeof t.polygon?l.V1:t.Marker&&"function"==typeof t.Marker&&t.Polyline&&"function"==typeof t.Polyline?l.V2:l.V1}static isV1(){return this.getVersion()===l.V1}static isV2(){return this.getVersion()===l.V2}static reset(){this._detectedVersion=null}static getVersionInfo(){const e=this.getVersion(),t=ti();return{version:e,leafletVersion:null==t?void 0:t.version,hasFactoryMethods:"function"==typeof(null==t?void 0:t.marker),hasConstructors:!!(null==t?void 0:t.Marker)&&"function"==typeof t.Marker,globalLAvailable:!!t}}}i(ri,"_detectedVersion",null);const oi=new class{constructor(){i(this,"domUtil",{create:(e,t,r)=>{if(void 0!==s&&s.DomUtil)return s.DomUtil.create(e,t,r);{const o=document.createElement(e);return t&&(o.className=t),r&&r.appendChild(o),o}},addClass:(e,t)=>{this.version===l.V1?s.DomUtil.addClass(e,t):e.classList.add(t)},removeClass:(e,t)=>{this.version===l.V1?s.DomUtil.removeClass(e,t):e.classList.remove(t)},hasClass:(e,t)=>this.version===l.V1?s.DomUtil.hasClass(e,t):e.classList.contains(t),setPosition:(e,t)=>{s.DomUtil.setPosition(e,t)},getPosition:e=>s.DomUtil.getPosition(e)}),i(this,"domEvent",{on:(e,t,r,o)=>(s.DomEvent.on(e,t,r,o),this),off:(e,t,r,o)=>(s.DomEvent.off(e,t,r,o),this),stopPropagation:e=>(s.DomEvent.stopPropagation(e),this),preventDefault:e=>(s.DomEvent.preventDefault(e),this),stop:e=>(s.DomEvent.stop(e),this),disableClickPropagation:e=>(s.DomEvent.disableClickPropagation(e),this),disableScrollPropagation:e=>(s.DomEvent.disableScrollPropagation(e),this),getMousePosition:(e,t)=>{if(this.version===l.V1)return s.DomEvent.getMousePosition(e,t);{const r=s.DomEvent;return r.getPointerPosition?r.getPointerPosition(e,t):s.DomEvent.getMousePosition(e,t)}}}),i(this,"util",{extend:(e,...t)=>this.version===l.V1?s.Util.extend(e,...t):Object.assign(e,...t),bind:(e,t)=>this.version===l.V1?s.Util.bind(e,t):e.bind(t),stamp:e=>s.Util.stamp(e),throttle:(e,t,r)=>s.Util.throttle(e,t,r),wrapNum:(e,t,r)=>s.Util.wrapNum(e,t,r),falseFn:()=>s.Util.falseFn(),formatNum:(e,t)=>s.Util.formatNum(e,t),trim:e=>this.version===l.V1?s.Util.trim(e):e.trim(),splitWords:e=>s.Util.splitWords(e),setOptions:(e,t)=>s.Util.setOptions(e,t),getParamString:(e,t,r)=>{if(this.version===l.V1)return s.Util.getParamString(e,t,r);{const o=new URLSearchParams;for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){const n=r?t.toUpperCase():t;o.set(n,String(e[t]))}const n=o.toString();if(t){const e=-1===t.indexOf("?")?"?":"&";return t+e+n}return n?"?"+n:""}},template:(e,t)=>s.Util.template(e,t),isArray:e=>this.version===l.V1?s.Util.isArray(e):Array.isArray(e),indexOf:(e,t)=>s.Util.indexOf(e,t),requestAnimFrame:(e,t,r)=>this.version===l.V1?s.Util.requestAnimFrame(e,t,r):requestAnimationFrame(t?e.bind(t):e),cancelAnimFrame:e=>{this.version===l.V1?s.Util.cancelAnimFrame(e):cancelAnimationFrame(e)}})}get version(){return ri.getVersion()}createTileLayer(e,t){return new s.TileLayer(e,t)}createMap(e,t){return new s.Map(e,t)}createMarker(e,t){return new s.Marker(e,t)}createPolyline(e,t){return new s.Polyline(e,t)}createPolygon(e,t){return new s.Polygon(e,t)}createDivIcon(e){return new s.DivIcon(e)}createLatLng(e,t,r){return new s.LatLng(e,t,r)}createLatLngBounds(e,t){return e&&t?new s.LatLngBounds(e,t):e?new s.LatLngBounds(e,e):new s.LatLngBounds([])}createPoint(e,t,r){return new s.Point(e,t,r)}createPopup(e,t){return new s.Popup(e,t)}createFeatureGroup(e){return new s.FeatureGroup(e)}createLayerGroup(e){return new s.LayerGroup(e)}getBrowser(){const e=this,t=s.Browser;return{get ie(){return e.version===l.V1&&s.Browser.ie},get ielt9(){return e.version===l.V1&&s.Browser.ielt9},get edge(){return e.version===l.V1&&s.Browser.edge},get webkit(){return e.version===l.V1&&s.Browser.webkit},get android(){return e.version===l.V1?s.Browser.android:/Android/.test(navigator.userAgent)},get android23(){return e.version===l.V1&&s.Browser.android23},get androidStock(){return e.version===l.V1&&s.Browser.androidStock},get opera(){return e.version===l.V1&&s.Browser.opera},get chrome(){return e.version===l.V1?s.Browser.chrome:/Chrome/.test(navigator.userAgent)},get gecko(){return e.version===l.V1&&s.Browser.gecko},get safari(){return e.version===l.V1?s.Browser.safari:/Safari/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)},get phantom(){return e.version===l.V1&&(t.phantom??!1)},get opera12(){return e.version===l.V1&&s.Browser.opera12},get win(){return e.version===l.V1?s.Browser.win:/Win/.test(navigator.platform)},get ie3d(){return e.version===l.V1&&s.Browser.ie3d},get webkit3d(){return e.version===l.V1&&s.Browser.webkit3d},get gecko3d(){return e.version===l.V1&&s.Browser.gecko3d},get any3d(){return e.version!==l.V1||s.Browser.any3d},get mobile(){return s.Browser.mobile},get mobileWebkit(){return e.version===l.V1&&s.Browser.mobileWebkit},get mobileWebkit3d(){return e.version===l.V1&&s.Browser.mobileWebkit3d},get msPointer(){return e.version===l.V1&&s.Browser.msPointer},get pointer(){return s.Browser.pointer||!0},get touch(){return s.Browser.touch},get touchNative(){return e.version===l.V1&&(t.touchNative??!1)},get mobileOpera(){return e.version===l.V1&&s.Browser.mobileOpera},get mobileGecko(){return e.version===l.V1&&s.Browser.mobileGecko},get retina(){return s.Browser.retina},get passiveEvents(){return e.version!==l.V1||(t.passiveEvents??!0)},get canvas(){return e.version!==l.V1||s.Browser.canvas},get svg(){return e.version!==l.V1||s.Browser.svg},get vml(){return e.version===l.V1&&s.Browser.vml},get inlineSvg(){return e.version!==l.V1||(t.inlineSvg??!0)}}}getVersion(){return this.version}isV1(){return this.version===l.V1}isV2(){return this.version===l.V2}};function ni(e,t){e.innerHTML=t;const r=e.querySelector("svg");r&&(!function(e){if(e.hasAttribute("viewBox"))return;const t=e.getAttribute("width"),r=e.getAttribute("height"),o=t?parseFloat(t):NaN,n=r?parseFloat(r):NaN;Number.isFinite(o)&&Number.isFinite(n)&&o>0&&n>0&&e.setAttribute("viewBox",`0 0 ${o} ${n}`)}(r),function(e){const t=Array.from(e.querySelectorAll("style"));if(0===t.length)return;const r=new Set;if(t.forEach(t=>{const o=t.textContent;if(!o)return void t.remove();const n=/([^{]+)\{([^}]*)\}/g;let i;for(;null!==(i=n.exec(o));){const t=i[1].split(",").map(e=>e.trim()).filter(Boolean),o=i[2];t.forEach(t=>{if(!t.startsWith("."))return;const n=t.slice(1);r.add(n),e.querySelectorAll(`.${n}`).forEach(e=>{o.split(";").forEach(t=>{const[r,o]=t.split(":");r&&o&&e.style.setProperty(r.trim(),o.trim())})})})}t.remove()}),0===r.size)return;e.querySelectorAll("[class]").forEach(e=>{const t=Array.from(e.classList).filter(e=>!r.has(e));t.length>0?e.setAttribute("class",t.join(" ")):e.removeAttribute("class")})}(r),r.setAttribute("width","24"),r.setAttribute("height","24"),r.style.pointerEvents="none",r.querySelectorAll("*").forEach(e=>{e.style.pointerEvents="none"}))}const ii='<?xml version="1.0" encoding="utf-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" id="Layer_1" x="0" y="0" style="enable-background:new 0 0 48 48" version="1.1" viewBox="0 0 48 48">\n <style>\n .st0{fill:#000}\n </style>\n <path d="M0 0h48v48H0z" style="fill:#333;fill-opacity:0"/>\n <path d="M26.6 10V7.8h-5.2V10h-8.8v2.8h22.8V10zM35.4 15.4H12.6v4.3h1.8V37c0 1.1.9 2 2 2h15.2c1.1 0 2-.9 2-2V19.7h1.8v-4.3zM19.7 34.2c0 .5-.4 1-1 1-.5 0-1-.4-1-1V22.6c0-.5.4-1 1-1 .5 0 1 .4 1 1v11.6zm5.6-.4c0 .7-.6 1.3-1.3 1.3-.7 0-1.3-.6-1.3-1.3V23c0-.7.6-1.3 1.3-1.3.7 0 1.3.6 1.3 1.3v10.8zm5 .4c0 .5-.4 1-1 1-.5 0-1-.4-1-1V22.6c0-.5.4-1 1-1 .5 0 1 .4 1 1v11.6z" class="st0"/>\n</svg>',ai={activate:'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" id="svg1" width="512" height="512" version="1.1">\n <path id="Shape" fill="#000" fill-rule="evenodd" stroke="none" d="M73.574 425.687c-1.14.188-4.099-.592-6.574-1.735-2.475-1.142-5.513-3.027-6.75-4.188C58 417.65 58 417.65 58 348.144c0-69.506 0-69.506 6.152-80.075a1599.57 1599.57 0 0 1 12.84-21.569c3.677-6.05 12.679-21.125 20.004-33.5 7.324-12.375 15.666-26.325 18.538-31 2.87-4.675 13.163-21.88 22.872-38.233a33686.921 33686.921 0 0 1 34.229-57.5c9.117-15.272 18.261-30.022 20.322-32.777 2.298-3.074 5.78-6.117 9.008-7.874 3.583-1.95 7.22-3.017 11.399-3.342 4.972-.388 7.445.018 13.04 2.137 3.799 1.439 10.999 4.919 16 7.733 5.003 2.814 13.371 7.613 18.596 10.663s13.775 8.134 19 11.297c5.225 3.163 12.061 7.246 15.192 9.073 3.13 1.828 9.402 5.521 13.936 8.208 4.535 2.686 10.397 6.897 13.027 9.357 3.265 3.054 5.457 6.261 6.912 10.115 1.672 4.43 2.036 7.161 1.694 12.704-.324 5.244-1.186 8.511-3.349 12.695-1.601 3.098-9.388 16.57-17.303 29.939-7.915 13.368-16.24 27.326-18.5 31.019a3087.099 3087.099 0 0 0-9.697 16c-3.073 5.107-11.2 18.736-18.061 30.286-6.86 11.55-16.45 27.75-21.312 36-4.86 8.25-11.179 18.825-14.04 23.5-2.862 4.675-8.308 13.83-12.101 20.343-3.794 6.513-10.508 17.762-14.92 24.997-7.721 12.664-8.263 13.29-14.5 16.77-3.563 1.987-15.357 8.416-26.21 14.286-10.851 5.87-28.851 15.66-40 21.756-11.147 6.096-25.86 14.032-32.694 17.638-6.834 3.605-13.359 6.709-14.5 6.897ZM116 376.754c2.096-.21 12.525-5.28 26-12.636 12.375-6.757 23.394-13.153 24.486-14.215 1.495-1.453 1.734-2.331.966-3.548-.56-.889-7.304-5.352-14.986-9.918-7.681-4.565-17.116-10.268-20.966-12.672-3.85-2.405-15.046-9.073-24.88-14.818-9.834-5.746-19.087-10.976-20.561-11.623-1.641-.72-3.24-.831-4.12-.287-.981.606-1.598 3.444-1.939 8.924-.275 4.42-.347 17.312-.16 28.65.341 20.616.341 20.616 3.5 23.908 1.738 1.81 9.01 6.733 16.16 10.94 10.754 6.327 13.605 7.587 16.5 7.295ZM184.98 329c.9 0 2.342-.563 3.204-1.25.86-.688 3.803-4.85 6.537-9.25 2.735-4.4 17.476-28.925 32.759-54.5 15.283-25.575 29.64-49.497 31.904-53.16 2.264-3.662 6.141-10.152 8.616-14.422 2.475-4.27 5.957-10.274 7.738-13.341 1.785-3.075 3.244-7.005 3.25-8.759.011-2.982-.694-3.614-11.238-10.077A2882.894 2882.894 0 0 0 249 152.847c-4.125-2.475-13.245-7.94-20.267-12.145a9841.507 9841.507 0 0 1-20.5-12.309 1566.199 1566.199 0 0 0-14.685-8.73c-3.823-2.238-8.13-4.242-9.57-4.453-1.998-.293-3.333.43-5.64 3.057-1.661 1.893-5.368 7.444-8.237 12.337a2040.256 2040.256 0 0 1-11.477 19.251 5775.594 5775.594 0 0 0-12.325 20.5A7048.542 7048.542 0 0 1 131.47 195c-4.823 7.975-10.898 18.1-13.501 22.5-2.604 4.4-8.45 14.075-12.991 21.5-4.542 7.425-10.268 16.988-12.725 21.252-3.26 5.657-4.304 8.405-3.861 10.168.454 1.81 4.239 4.57 15.1 11.01 7.973 4.726 20.686 12.257 28.252 16.735 7.566 4.477 17.582 10.485 22.257 13.351 4.675 2.866 13.19 7.973 18.921 11.348 5.732 3.375 11.158 6.136 12.059 6.136Zm100.681-194.022c2.318.016 3.852-.798 5.75-3.055 1.497-1.78 2.589-4.313 2.589-6.01 0-2.269-.848-3.508-3.75-5.478-2.063-1.4-6.53-4.29-9.927-6.421-3.398-2.132-9.923-6.015-14.5-8.63-4.578-2.614-10.798-6.408-13.823-8.43-3.025-2.022-7.75-4.873-10.5-6.334-2.75-1.462-8.15-4.689-12-7.171-5.023-3.24-7.838-4.434-9.968-4.232-2.1.2-3.65 1.298-5.297 3.75-1.437 2.14-2.215 4.588-2.032 6.391.254 2.498 1.604 3.72 9.297 8.412 4.95 3.02 15.525 9.427 23.5 14.238a3631.896 3631.896 0 0 1 26 15.848c7.807 4.82 12.515 7.107 14.661 7.122Z"/>\n <path id="path1" fill="#000" fill-rule="evenodd" stroke="none" d="M479.5 119.5c0 34 0 34-7 34.262-3.85.144-11.275.947-16.5 1.785s-12.533 2.42-16.24 3.514c-3.708 1.095-9.416 3.559-12.686 5.475-3.269 1.916-7.401 4.71-9.183 6.209-1.781 1.499-4.926 5.336-6.988 8.526-2.395 3.706-4.41 8.588-5.576 13.515-1.346 5.684-1.817 11.548-1.79 22.282.023 8.902.749 19.208 1.866 26.5 1.006 6.563 2.964 17.107 4.352 23.432 1.388 6.325 3.152 14.2 3.92 17.5.768 3.3 3.14 14.55 5.272 25s4.816 24.901 5.965 32.114c1.57 9.86 2.088 17.705 2.088 31.622 0 16.395-.284 19.635-2.485 28.386-1.367 5.433-4.299 13.56-6.515 18.061-2.832 5.75-6.265 10.559-11.545 16.172-5.308 5.642-10.516 9.846-17.735 14.316-5.62 3.481-13.145 7.611-16.72 9.179-3.575 1.567-10.739 4.4-15.92 6.293-5.181 1.894-13.506 4.308-18.5 5.365-4.994 1.056-13.58 2.637-19.08 3.513-6.633 1.057-18.754 1.716-36 1.958-14.3.201-30.5.01-36-.424s-15.625-1.537-22.5-2.45c-6.875-.912-16.575-2.328-21.557-3.146-4.98-.817-12.406-2.176-16.5-3.02-4.093-.843-9.693-2.157-12.443-2.92-2.75-.763-7.7-2.083-11-2.932-3.3-.85-10.5-2.648-16-3.996-5.5-1.348-15.85-4.3-23-6.56-7.15-2.261-14.912-4.805-17.25-5.653-2.904-1.055-4.25-2.127-4.25-3.386 0-1.228 3.252-3.97 9.75-8.22 5.363-3.507 13.202-8.277 17.421-10.6 7.671-4.225 7.671-4.225 18.5-1.287 5.956 1.616 19.154 4.998 29.329 7.515 10.175 2.517 23.45 5.465 29.5 6.55 6.05 1.087 15.05 2.427 20 2.98 4.95.552 14.85 1.53 22 2.175 8.107.73 21.657.955 36 .598 13.264-.33 27.021-1.234 32.5-2.135 5.225-.86 14-2.963 19.5-4.673s12.925-4.443 16.5-6.073a870.93 870.93 0 0 0 11.5-5.354c2.75-1.314 7.94-4.836 11.535-7.826 3.888-3.234 7.591-7.403 9.142-10.29 1.433-2.668 3.653-8.143 4.932-12.166 1.934-6.082 2.319-9.415 2.283-19.794-.024-7.149-.774-16.627-1.756-22.186-.943-5.339-2.407-13.531-3.253-18.206-.847-4.675-2.454-12.775-3.572-18-1.118-5.225-3.15-14-4.514-19.5-1.365-5.5-3.5-14.725-4.746-20.5-1.246-5.775-2.995-15-3.886-20.5-.892-5.5-2.081-14.08-2.643-19.068-.562-4.987-1.014-13.987-1.005-20 .01-6.012.652-14.799 1.427-19.525.775-4.726 2.12-11.026 2.988-14 .869-2.974 3.04-8.224 4.824-11.668 1.784-3.443 5.256-9.004 7.715-12.356 2.46-3.353 8.084-8.988 12.5-12.523 4.416-3.534 11.629-8.164 16.029-10.287 4.4-2.124 12.05-5.194 17-6.823 4.95-1.63 14.625-3.757 21.5-4.729s16.1-1.824 20.5-1.894l8-.127Z"/>\n <path id="path2" fill="#B6BCC4" fill-rule="evenodd" stroke="none" d="M116 375.743c-2.73.236-5.372-.8-12-4.708-4.675-2.756-11.133-6.704-14.35-8.773-3.218-2.07-6.48-4.977-7.25-6.462-1.094-2.111-1.4-8.348-1.4-28.56 0-21.125.267-26.213 1.461-27.799 1.43-1.9 1.574-1.879 6.75.986 2.909 1.61 8.214 4.584 11.789 6.61 3.575 2.026 9.1 5.209 12.28 7.073 3.179 1.865 10.253 6.09 15.722 9.39 5.468 3.3 13.836 8.245 18.596 10.989 4.76 2.744 10.736 6.348 13.279 8.01 2.568 1.678 4.753 3.927 4.917 5.062.246 1.716-3.42 4.101-23 14.96-14.766 8.189-24.575 13.03-26.794 13.222Z"/>\n <path id="path3" fill="#fff" fill-rule="evenodd" stroke="none" d="M185.256 329c-1.012 0-5.646-2.194-10.298-4.875-4.652-2.68-22.633-13.322-39.958-23.648-17.325-10.325-34.65-20.844-38.5-23.375-6.25-4.109-7.029-4.977-7.268-8.102-.202-2.632.816-5.36 4.106-11 2.407-4.125 21.576-36.075 42.6-71 21.022-34.925 39.47-65.075 40.994-67 2.195-2.772 3.589-3.562 6.699-3.797 3.477-.262 6.271 1.103 24.398 11.925 11.259 6.722 30.146 18.027 41.971 25.123 11.825 7.095 23.075 14.15 25 15.675 2.099 1.664 3.627 3.836 3.816 5.425.19 1.592-1.021 5.145-3.035 8.9-1.844 3.437-21.525 36.528-43.737 73.537-22.211 37.008-41.411 68.395-42.666 69.75-1.256 1.354-3.11 2.462-4.122 2.462Z"/>\n</svg>'.trim(),draw:'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" id="svg1" width="512" height="512" version="1.1">\n <path id="Shape" fill="#000" fill-rule="evenodd" stroke="none" d="M73.574 425.687c-1.14.188-4.099-.592-6.574-1.735-2.475-1.142-5.513-3.027-6.75-4.188C58 417.65 58 417.65 58 348.144c0-69.506 0-69.506 6.152-80.075a1599.57 1599.57 0 0 1 12.84-21.569c3.677-6.05 12.679-21.125 20.004-33.5 7.324-12.375 15.666-26.325 18.538-31 2.87-4.675 13.163-21.88 22.872-38.233a33686.921 33686.921 0 0 1 34.229-57.5c9.117-15.272 18.261-30.022 20.322-32.777 2.298-3.074 5.78-6.117 9.008-7.874 3.583-1.95 7.22-3.017 11.399-3.342 4.972-.388 7.445.018 13.04 2.137 3.799 1.439 10.999 4.919 16 7.733 5.003 2.814 13.371 7.613 18.596 10.663s13.775 8.134 19 11.297c5.225 3.163 12.061 7.246 15.192 9.073 3.13 1.828 9.402 5.521 13.936 8.208 4.535 2.686 10.397 6.897 13.027 9.357 3.265 3.054 5.457 6.261 6.912 10.115 1.672 4.43 2.036 7.161 1.694 12.704-.324 5.244-1.186 8.511-3.349 12.695-1.601 3.098-9.388 16.57-17.303 29.939-7.915 13.368-16.24 27.326-18.5 31.019a3087.099 3087.099 0 0 0-9.697 16c-3.073 5.107-11.2 18.736-18.061 30.286-6.86 11.55-16.45 27.75-21.312 36-4.86 8.25-11.179 18.825-14.04 23.5-2.862 4.675-8.308 13.83-12.101 20.343-3.794 6.513-10.508 17.762-14.92 24.997-7.721 12.664-8.263 13.29-14.5 16.77-3.563 1.987-15.357 8.416-26.21 14.286-10.851 5.87-28.851 15.66-40 21.756-11.147 6.096-25.86 14.032-32.694 17.638-6.834 3.605-13.359 6.709-14.5 6.897ZM116 376.754c2.096-.21 12.525-5.28 26-12.636 12.375-6.757 23.394-13.153 24.486-14.215 1.495-1.453 1.734-2.331.966-3.548-.56-.889-7.304-5.352-14.986-9.918-7.681-4.565-17.116-10.268-20.966-12.672-3.85-2.405-15.046-9.073-24.88-14.818-9.834-5.746-19.087-10.976-20.561-11.623-1.641-.72-3.24-.831-4.12-.287-.981.606-1.598 3.444-1.939 8.924-.275 4.42-.347 17.312-.16 28.65.341 20.616.341 20.616 3.5 23.908 1.738 1.81 9.01 6.733 16.16 10.94 10.754 6.327 13.605 7.587 16.5 7.295ZM184.98 329c.9 0 2.342-.563 3.204-1.25.86-.688 3.803-4.85 6.537-9.25 2.735-4.4 17.476-28.925 32.759-54.5 15.283-25.575 29.64-49.497 31.904-53.16 2.264-3.662 6.141-10.152 8.616-14.422 2.475-4.27 5.957-10.274 7.738-13.341 1.785-3.075 3.244-7.005 3.25-8.759.011-2.982-.694-3.614-11.238-10.077A2882.894 2882.894 0 0 0 249 152.847c-4.125-2.475-13.245-7.94-20.267-12.145a9841.507 9841.507 0 0 1-20.5-12.309 1566.199 1566.199 0 0 0-14.685-8.73c-3.823-2.238-8.13-4.242-9.57-4.453-1.998-.293-3.333.43-5.64 3.057-1.661 1.893-5.368 7.444-8.237 12.337a2040.256 2040.256 0 0 1-11.477 19.251 5775.594 5775.594 0 0 0-12.325 20.5A7048.542 7048.542 0 0 1 131.47 195c-4.823 7.975-10.898 18.1-13.501 22.5-2.604 4.4-8.45 14.075-12.991 21.5-4.542 7.425-10.268 16.988-12.725 21.252-3.26 5.657-4.304 8.405-3.861 10.168.454 1.81 4.239 4.57 15.1 11.01 7.973 4.726 20.686 12.257 28.252 16.735 7.566 4.477 17.582 10.485 22.257 13.351 4.675 2.866 13.19 7.973 18.921 11.348 5.732 3.375 11.158 6.136 12.059 6.136Zm100.681-194.022c2.318.016 3.852-.798 5.75-3.055 1.497-1.78 2.589-4.313 2.589-6.01 0-2.269-.848-3.508-3.75-5.478-2.063-1.4-6.53-4.29-9.927-6.421-3.398-2.132-9.923-6.015-14.5-8.63-4.578-2.614-10.798-6.408-13.823-8.43-3.025-2.022-7.75-4.873-10.5-6.334-2.75-1.462-8.15-4.689-12-7.171-5.023-3.24-7.838-4.434-9.968-4.232-2.1.2-3.65 1.298-5.297 3.75-1.437 2.14-2.215 4.588-2.032 6.391.254 2.498 1.604 3.72 9.297 8.412 4.95 3.02 15.525 9.427 23.5 14.238a3631.896 3631.896 0 0 1 26 15.848c7.807 4.82 12.515 7.107 14.661 7.122Z" style="stroke:#000;stroke-opacity:1;stroke-width:20;stroke-dasharray:none"/>\n <path id="path1" fill="#000" fill-rule="evenodd" stroke="none" d="M479.5 119.5c0 34 0 34-7 34.262-3.85.144-11.275.947-16.5 1.785s-12.533 2.42-16.24 3.514c-3.708 1.095-9.416 3.559-12.686 5.475-3.269 1.916-7.401 4.71-9.183 6.209-1.781 1.499-4.926 5.336-6.988 8.526-2.395 3.706-4.41 8.588-5.576 13.515-1.346 5.684-1.817 11.548-1.79 22.282.023 8.902.749 19.208 1.866 26.5 1.006 6.563 2.964 17.107 4.352 23.432 1.388 6.325 3.152 14.2 3.92 17.5.768 3.3 3.14 14.55 5.272 25s4.816 24.901 5.965 32.114c1.57 9.86 2.088 17.705 2.088 31.622 0 16.395-.284 19.635-2.485 28.386-1.367 5.433-4.299 13.56-6.515 18.061-2.832 5.75-6.265 10.559-11.545 16.172-5.308 5.642-10.516 9.846-17.735 14.316-5.62 3.481-13.145 7.611-16.72 9.179-3.575 1.567-10.739 4.4-15.92 6.293-5.181 1.894-13.506 4.308-18.5 5.365-4.994 1.056-13.58 2.637-19.08 3.513-6.633 1.057-18.754 1.716-36 1.958-14.3.201-30.5.01-36-.424s-15.625-1.537-22.5-2.45c-6.875-.912-16.575-2.328-21.557-3.146-4.98-.817-12.406-2.176-16.5-3.02-4.093-.843-9.693-2.157-12.443-2.92-2.75-.763-7.7-2.083-11-2.932-3.3-.85-10.5-2.648-16-3.996-5.5-1.348-15.85-4.3-23-6.56-7.15-2.261-14.912-4.805-17.25-5.653-2.904-1.055-4.25-2.127-4.25-3.386 0-1.228 3.252-3.97 9.75-8.22 5.363-3.507 13.202-8.277 17.421-10.6 7.671-4.225 7.671-4.225 18.5-1.287 5.956 1.616 19.154 4.998 29.329 7.515 10.175 2.517 23.45 5.465 29.5 6.55 6.05 1.087 15.05 2.427 20 2.98 4.95.552 14.85 1.53 22 2.175 8.107.73 21.657.955 36 .598 13.264-.33 27.021-1.234 32.5-2.135 5.225-.86 14-2.963 19.5-4.673s12.925-4.443 16.5-6.073a870.93 870.93 0 0 0 11.5-5.354c2.75-1.314 7.94-4.836 11.535-7.826 3.888-3.234 7.591-7.403 9.142-10.29 1.433-2.668 3.653-8.143 4.932-12.166 1.934-6.082 2.319-9.415 2.283-19.794-.024-7.149-.774-16.627-1.756-22.186-.943-5.339-2.407-13.531-3.253-18.206-.847-4.675-2.454-12.775-3.572-18-1.118-5.225-3.15-14-4.514-19.5-1.365-5.5-3.5-14.725-4.746-20.5-1.246-5.775-2.995-15-3.886-20.5-.892-5.5-2.081-14.08-2.643-19.068-.562-4.987-1.014-13.987-1.005-20 .01-6.012.652-14.799 1.427-19.525.775-4.726 2.12-11.026 2.988-14 .869-2.974 3.04-8.224 4.824-11.668 1.784-3.443 5.256-9.004 7.715-12.356 2.46-3.353 8.084-8.988 12.5-12.523 4.416-3.534 11.629-8.164 16.029-10.287 4.4-2.124 12.05-5.194 17-6.823 4.95-1.63 14.625-3.757 21.5-4.729s16.1-1.824 20.5-1.894l8-.127Z"/>\n <path id="path2" fill="#B6BCC4" fill-rule="evenodd" stroke="none" d="M116 375.743c-2.73.236-5.372-.8-12-4.708-4.675-2.756-11.133-6.704-14.35-8.773-3.218-2.07-6.48-4.977-7.25-6.462-1.094-2.111-1.4-8.348-1.4-28.56 0-21.125.267-26.213 1.461-27.799 1.43-1.9 1.574-1.879 6.75.986 2.909 1.61 8.214 4.584 11.789 6.61 3.575 2.026 9.1 5.209 12.28 7.073 3.179 1.865 10.253 6.09 15.722 9.39 5.468 3.3 13.836 8.245 18.596 10.989 4.76 2.744 10.736 6.348 13.279 8.01 2.568 1.678 4.753 3.927 4.917 5.062.246 1.716-3.42 4.101-23 14.96-14.766 8.189-24.575 13.03-26.794 13.222Z"/>\n</svg>'.trim(),subtract:'<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path fill-rule="evenodd" clip-rule="evenodd" d="M15.0722 3.9967L20.7508 9.83395L17.0544 13.5304L13.0758 17.5H21.0041V19H7.93503L4.00195 15.0669L15.0722 3.9967ZM10.952 17.5L15.4628 12.9994L11.8268 9.3634L6.12327 15.0669L8.55635 17.5H10.952Z" fill="#1F2328"></path> </g></svg>\n'.trim(),clone:'<?xml version="1.0" encoding="UTF-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">\n <rect x="88" y="88" width="252" height="252" fill="none" stroke="#000" stroke-width="42"/>\n <rect x="172" y="172" width="252" height="252" fill="none" stroke="#000" stroke-width="42"/>\n</svg>'.trim(),p2p:'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" id="svg1" width="512" height="512" version="1.1">\n <path id="path7" d="m155.327 480.616 323.962-.033V45.207L32.68 44.87l.24 35.605 411.103-.882-.338 365.995-169.126-.577Z" style="fill:#000;fill-opacity:1;stroke:none;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n <circle id="path8" cx="460.396" cy="461.547" r="39.134" style="fill:#000;fill-opacity:1;stroke:none;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n <circle id="path8-8" cx="460.775" cy="65.834" r="39.134" style="fill:#000;fill-opacity:1;stroke:none;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n <circle id="path8-8-0" cx="67.176" cy="62.815" r="39.134" style="fill:#000;fill-opacity:1;stroke:none;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n <path id="path2" fill="#000" fill-rule="evenodd" stroke="none" d="M78.983 469.63c-2.155.594-4.661-.186-6.416-1.995-1.755-1.81-2.512-4.396-1.937-6.616.52-2.005 2.036-7.54 3.369-12.298 1.333-4.76 4.302-15.274 6.598-23.365 2.295-8.09 6.159-21.33 8.585-29.421a5326.7 5326.7 0 0 0 9.458-32.018c2.775-9.519 6.848-23.538 9.05-31.153a3424.585 3424.585 0 0 1 8.424-28.556c2.432-8.09 5.74-19.445 7.35-25.23 1.61-5.786 4.963-13.271 7.45-16.634 3.196-4.319 8.828-8.134 19.19-12.998 8.067-3.787 22.221-10.287 31.454-14.445 9.232-4.158 20.186-9.16 24.34-11.116a766.22 766.22 0 0 1 15.108-6.874c4.154-1.824 8.5-4.181 9.657-5.238 1.675-1.53 1.537-3.405-.681-9.226-2.27-5.96-2.436-8.498-.898-13.779 1.221-4.19 5.936-10.614 13.373-18.217 6.772-6.923 13.882-12.502 17.322-13.59 4.562-1.444 7.103-1.28 11.648.752 3.426 1.532 23.389 20.759 48.618 46.826 23.543 24.325 45.072 47.061 47.841 50.525 3.873 4.843 5.036 8.022 5.036 13.76 0 6.664-.988 8.548-9.232 17.594-5.078 5.572-11.81 12.267-14.959 14.876-4.16 3.448-7.614 4.745-12.635 4.745-3.801 0-8.653-1.259-10.783-2.797-2.18-1.574-4.506-2.141-5.322-1.298-.797.824-5.186 10.455-9.754 21.402a5146.966 5146.966 0 0 1-15.335 36.316c-3.866 9.027-10.026 22.886-13.689 30.798-4.617 9.975-8.217 15.361-11.743 17.572-2.796 1.753-10.879 5.156-17.961 7.562-7.083 2.406-20.431 6.749-29.664 9.65-9.232 2.902-25.661 8.033-36.509 11.403-10.847 3.37-31.242 9.76-45.323 14.201-14.08 4.44-32.777 10.286-41.547 12.99-8.771 2.704-17.539 5.355-19.483 5.892zm33.106-25.66c3.124-.525 14.558-3.756 25.407-7.18 10.85-3.424 33.511-10.53 50.36-15.791a27689.101 27689.101 0 0 1 50.776-15.803c14.114-4.37 21.467-7.596 24.568-10.778 2.433-2.497 8.003-13.108 12.378-23.578 4.374-10.471 10.397-24.88 13.384-32.018 2.987-7.14 8.327-19.6 11.866-27.691 3.54-8.091 6.71-17.047 7.046-19.903.555-4.717-2.161-8.042-29.692-36.345-16.667-17.133-31.78-31.396-33.584-31.694-1.804-.298-24.636 9.269-50.737 21.259-26.102 11.99-49.09 23.383-51.087 25.316-1.997 1.934-4.862 7.745-6.369 12.914a7969.157 7969.157 0 0 0-7.086 24.55 5161.998 5161.998 0 0 1-9.204 31.594c-2.67 9.043-9.076 30.85-14.234 48.46-5.158 17.609-10.028 34.72-10.822 38.026-.794 3.304-1.129 6.334-.743 6.731.385.397 3.176-1.24 6.202-3.637 3.026-2.397 17.965-17.532 33.199-33.633 15.233-16.1 31.64-33.573 36.46-38.83 8.522-9.292 8.717-9.73 7.063-15.905-1.163-4.344-1.143-8.487.066-13.114 1.094-4.191 4.275-9.1 8.364-12.909 3.648-3.398 9.265-6.662 12.561-7.3 4.51-.872 7.9-.158 13.92 2.932 4.845 2.486 9.223 6.36 11.188 9.9 1.776 3.2 3.3 9.202 3.385 13.339.09 4.285-1.167 10.058-2.921 13.416-1.693 3.242-6.11 7.651-9.814 9.798-5.669 3.285-8.24 3.73-16.226 2.804-9.49-1.099-9.49-1.099-49.778 40.478-22.158 22.867-40.577 42.47-40.932 43.56-.438 1.349 1.175 1.679 5.036 1.031zm90.33-98.225c3.355 0 6.06-1.502 8.524-4.733 2.602-3.409 3.338-6.138 2.634-9.765-.537-2.768-2.295-6.065-3.908-7.327-1.612-1.262-5.138-2.32-7.835-2.35-2.697-.03-6.285 1.234-7.974 2.81-1.808 1.687-3.07 5.242-3.07 8.653 0 3.481 1.339 7.169 3.358 9.25 1.846 1.904 5.568 3.462 8.271 3.462zm133.61-53.652c1.976 0 7.955-4.72 14.175-11.19 10.066-10.471 10.62-11.455 8.624-15.3-1.174-2.262-22.067-24.651-46.43-49.755-28.883-29.764-45.482-45.645-47.707-45.645-1.918 0-7.85 4.523-13.542 10.323-7.359 7.498-9.997 11.39-9.645 14.229.303 2.438 17.518 21.468 45.796 50.622 29.62 30.538 46.495 46.716 48.73 46.716z" style="stroke:#010101;stroke-width:17.0446;stroke-dasharray:none;stroke-opacity:1"/>\n <path id="path3" d="m243.547 189.376 16.458-15.442 96.745 96.717-16.459 16.256z" style="fill:green;fill-opacity:1;stroke:none;stroke-width:18.6862;stroke-dasharray:none;stroke-opacity:1"/>\n <circle id="path9" cx="201.178" cy="332.215" r="13.593" style="fill:#fff;fill-opacity:1;stroke:none;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n</svg>'.trim(),p2pSubtract:'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" id="svg1" width="512" height="512" version="1.1">\n <path id="path2" fill="#000" fill-rule="evenodd" stroke="none" d="M193.812 478.594c-90.053.005-55.415-.21-62.995-.883-3.109-.277-27.11-21.644-46.82-41.478-19.71-19.834-38.405-39.3-41.545-43.255-3.14-3.957-6.62-10.716-7.734-15.02-1.731-6.696-1.64-9.153.633-17.007 2.63-9.085 3.646-10.163 97.355-103.187 67.82-67.324 96.742-95.006 101.9-97.53 4.693-2.298 10.024-3.498 15.308-3.447 5.932.057 10.337 1.334 16.417 4.757 5.373 3.027 23.906 20.087 52.456 48.29 24.281 23.987 46.739 47.413 49.906 52.058 4.533 6.648 5.893 10.36 6.393 17.444.536 7.598-.072 10.288-3.907 17.275-3.191 5.814-24.3 28.163-70.958 75.126-36.529 36.767-66.373 67.623-66.926 68.174-19.83 19.71-39.71 38.183-39.483 38.683zm84.581-137.331c-68.043-67.49-88.703-86.892-89.81-86.657-1.106.234-27.946 26.117-59.643 57.517-31.698 31.4-57.439 57.94-57.202 58.977.236 1.037 15.757 17.272 34.492 36.078 34.062 34.193 34.062 34.193 53.6 34.193 19.536 0 19.536 0 55.274-35.285 19.656-19.407 41.937-41.932 49.514-50.054zm60.94-60.024c-66.9-66.62-87.289-86.356-88.469-86.837-1.29-.527-8.787 5.684-18.813 15.585l-16.668 16.46 44.408 44.028c24.425 24.215 44.787 44.027 45.249 44.027.461 0 8.366-7.484 17.566-16.632z" style="stroke-width:1.5931"/>\n <path id="path3" d="m214.604 225.766 35.345-32.835 89.308 87.873-34.083 33.773z" style="fill:maroon;fill-opacity:1;stroke:#010101;stroke-width:7.48758"/>\n <path id="path7" d="m238.705 480.616 240.584-.033V45.207L32.68 44.87l.24 35.605 411.103-.882-.338 365.995-169.126-.577Z" style="fill:#000;fill-opacity:1;stroke:none;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n <circle id="path8" cx="460.396" cy="461.547" r="39.134" style="fill:#000;fill-opacity:1;stroke:none;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n <circle id="path8-8" cx="460.775" cy="65.834" r="39.134" style="fill:#000;fill-opacity:1;stroke:none;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n <circle id="path8-8-0" cx="67.176" cy="62.815" r="39.134" style="fill:#000;fill-opacity:1;stroke:none;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n</svg>'.trim(),erase:ii.trim(),collapse:'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512">\n <path d="m80.033 292.15 175.755-174.592 175.755 174.591" style="fill:none;stroke:#000;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n <path d="M80.105 394.539 255.86 219.947 431.615 394.54" style="fill:none;stroke:#000;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n</svg>'.trim(),undo:'<?xml version="1.0" encoding="utf-8"?>\n<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 48 48" xml:space="preserve">\n<style type="text/css">\n\t.st0{fill:none;stroke:#000000;stroke-width:3;stroke-linecap:round;stroke-linejoin:round;}\n</style>\n<g>\n\t<path class="st0" d="M14,18h10c6.6,0,12,5.4,12,12s-5.4,12-12,12s-12-5.4-12-12"/>\n\t<polyline class="st0" points="18,14 14,18 18,22"/>\n</g>\n</svg>\n'.trim(),redo:'<?xml version="1.0" encoding="utf-8"?>\n<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 48 48" xml:space="preserve">\n<style type="text/css">\n\t.st0{fill:none;stroke:#000000;stroke-width:3;stroke-linecap:round;stroke-linejoin:round;}\n</style>\n<g>\n\t<path class="st0" d="M34,18H24C17.4,18,12,23.4,12,30s5.4,12,12,12s12-5.4,12-12"/>\n\t<polyline class="st0" points="30,14 34,18 30,22"/>\n</g>\n</svg>\n'.trim()},si=(e,t)=>{ni(e,t)},li=(e,t)=>{e.setAttribute("data-tooltip",t),e.setAttribute("aria-label",t)};class ci{static getCenter(e){let t=0,r=0,o=0;e.forEach(e=>{let n=e.lat,i=e.lng;n*=y,i*=y,t+=Math.cos(n)*Math.cos(i),r+=Math.cos(n)*Math.sin(i),o+=Math.sin(n)});let n=Math.atan2(r,t);const i=Math.sqrt(t*t+r*r);let a=Math.atan2(o,i);a*=m,n*=m;return{lat:a,lng:n}}static getSouthWest(e){return this.getBounds(e).getSouthWest()}static getNorthEast(e){return this.getBounds(e).getNorthEast()}static getNorthWest(e){return this.getBounds(e).getNorthWest()}static getSouthEast(e){return this.getBounds(e).getSouthEast()}static getNorth(e){return this.getBounds(e).getNorth()}static getSouth(e){return this.getBounds(e).getSouth()}static getWest(e){return this.getBounds(e).getWest()}static getEast(e){return this.getBounds(e).getEast()}static getSqmArea(e){const t=new s.Polygon(e).toGeoJSON();return this.turfHelper.getPolygonArea(t)}static getPerimeter(e){const t=new s.Polygon(e).toGeoJSON();return 1e3*this.turfHelper.getPolygonPerimeter(t)}static getPolygonChecksum(e){const t=e.filter((e,t,r)=>{const o=r.find(t=>t.lat===e.lat&&t.lng===e.lng);return!!o&&r.indexOf(o)===t});return t.reduce((e,t)=>+e+ +t.lat,0)*t.reduce((e,t)=>+e+ +t.lng,0)}static getMidPoint(e,t){const r=this.turfHelper.getMidpoint(e,t);return{lat:r.lat,lng:r.lng}}static getBounds(e){const t=[];e.forEach(e=>{isNaN(e.lat)||isNaN(e.lng),t.push(e)});return new s.Polyline(t).getBounds()}static getCenterOfMass(e){const t=this.turfHelper.getCenterOfMass(e);return{lat:t.geometry.coordinates[1],lng:t.geometry.coordinates[0]}}static getCenterOfPolygonByIndexWithOffsetFromCenterOfMass(e,t){const r=this.turfHelper.getCenterOfMass(e),o={lat:r.geometry.coordinates[1],lng:r.geometry.coordinates[0]},n=this.getPolygonLatLngAtIndex(e,t)??o,i=n.lat-o.lat,a=n.lng-o.lng,s={geometry:{coordinates:[o.lng+.5*a,o.lat+.5*i]}};return{lat:s.geometry.coordinates[1],lng:s.geometry.coordinates[0]}}static getPolygonLatLngAtIndex(e,t){const r=e.geometry;if(!r)return null;let o;if("Polygon"===r.type)o=r.coordinates[0];else{if("MultiPolygon"!==r.type)return null;o=r.coordinates[0][0]}if(!o||0===o.length)return null;if(o.length>1){const e=o[0],t=o[o.length-1];e[0]===t[0]&&e[1]===t[1]&&(o=o.slice(0,o.length-1))}if(0===o.length)return null;const n=o[(t%o.length+o.length)%o.length];return{lat:n[1],lng:n[0]}}}i(ci,"turfHelper",new ei(g));class ui{constructor(e){if(i(this,"polygon",[]),i(this,"trashcanPoint",[]),i(this,"sqmArea",[]),i(this,"perimeter",[]),!Array.isArray(e))return;if(e.length>0&&Array.isArray(e[0])&&e[0].length>0&&"object"==typeof e[0][0]&&"lat"in e[0][0]){const t=e[0];return this.trashcanPoint[0]=this.getTrashcanPoint(t),this.sqmArea[0]=this.calculatePolygonArea(t),this.perimeter[0]=this.calculatePolygonPerimeter(t),void(this.polygon[0]=[t])}if(e.length>0&&e[0]&&"object"==typeof e[0]&&"lat"in e[0]){const t=e,r=[[t]];return this.trashcanPoint[0]=this.getTrashcanPoint(t),this.sqmArea[0]=this.calculatePolygonArea(t),this.perimeter[0]=this.calculatePolygonPerimeter(t),void(this.polygon[0]=r[0])}e.forEach((e,t)=>{e&&Array.isArray(e)&&e[0]&&Array.isArray(e[0])&&(this.trashcanPoint[t]=this.getTrashcanPoint(e[0]),this.sqmArea[t]=this.calculatePolygonArea(e[0]),this.perimeter[t]=this.calculatePolygonPerimeter(e[0]),this.polygon[t]=e)})}setSqmArea(e){this.sqmArea[0]=e}getTrashcanPoint(e){if(!Array.isArray(e)||0===e.length)return console.warn("getTrashcanPoint: Invalid polygon array:",e),{lat:0,lng:0};const t=e.filter(e=>e&&"object"==typeof e&&"number"==typeof e.lat&&"number"==typeof e.lng&&!isNaN(e.lat)&&!isNaN(e.lng));if(0===t.length)return console.warn("getTrashcanPoint: No valid coordinates found:",e),{lat:0,lng:0};const r=Math.max(...t.map(e=>e.lat)),o=t.findIndex(e=>e.lat===r);if(-1===o)return console.warn("getTrashcanPoint: Could not find max lat coordinate"),{lat:0,lng:0};let n,i;if(o>0?(n=t[o-1],i=o<t.length-1?t[o+1]:t[0]):(n=t[t.length-1],i=t[o+1]),!n||!i)return console.warn("getTrashcanPoint: Could not determine previous/next points"),t[o]||{lat:0,lng:0};const a=n.lng<i.lng?n:i;return ci.getMidPoint(t[o],a)}calculatePolygonArea(e){return ci.getSqmArea(e)}calculatePolygonPerimeter(e){return ci.getPerimeter(e)}}class hi{constructor(e){i(this,"polygonInfoListeners",[]),i(this,"polygonDrawStateListeners",[]),i(this,"polygonInformationStorage",[]),this.mapStateService=e}onPolygonInfoUpdated(e){this.polygonInfoListeners.push(e)}emitPolygonInfoUpdated(){for(const e of this.polygonInfoListeners)e(this.polygonInformationStorage)}onPolygonDrawStateUpdated(e){this.polygonDrawStateListeners.push(e)}updatePolygons(){const e=[];this.polygonInformationStorage.length>0&&this.polygonInformationStorage.forEach(t=>{const r=[];t.polygon.forEach(e=>{e.forEach(e=>{const t=[...e];e.length>0&&e[0].toString()!==e[e.length-1].toString()&&t.push(e[0]),r.push(t)})}),e.push(r)}),this.mapStateService.updatePolygons(e),this.saveCurrentState()}saveCurrentState(){this.emitPolygonInfoUpdated()}deleteTrashcan(e){const t=this.polygonInformationStorage.findIndex(t=>t.polygon[0]===e);-1!==t&&(this.polygonInformationStorage.splice(t,1),this.updatePolygons())}deleteTrashCanOnMulti(e){let t=0;this.polygonInformationStorage.forEach((r,o)=>{const n=r.polygon.findIndex(t=>t.toString()===e.toString());n>=0&&(t=o,r.trashcanPoint.splice(n,1),r.sqmArea.splice(n,1),r.perimeter.splice(n,1),r.polygon.splice(n,1))}),this.updatePolygons(),this.polygonInformationStorage.length>1&&this.polygonInformationStorage.splice(t,1)}deletePolygonInformationStorage(){this.polygonInformationStorage=[]}createPolygonInformationStorage(e){e.length>0&&(e.forEach(e=>{var t;const r=null==(t=e.getLayers)?void 0:t.call(e);if(null==r?void 0:r[0]){const e=r[0].getLatLngs(),t=new ui(e);this.polygonInformationStorage.push(t)}}),this.updatePolygons())}}class gi{constructor(){i(this,"map",null),i(this,"mapListeners",[])}onMapUpdated(e){this.map&&e(this.map),this.mapListeners.push(e)}emitMapUpdated(){if(this.map)for(const e of this.mapListeners)e(this.map)}updateMapState(e){this.map=e,this.emitMapUpdated()}updatePolygons(e){}}class di{constructor(){i(this,"eventListeners",new Map)}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t)}off(e,t){const r=this.eventListeners.get(e);if(r){const e=r.indexOf(t);e>-1&&r.splice(e,1)}}emit(e,t){var r;this.eventListeners.has(e)&&(null==(r=this.eventListeners.get(e))||r.forEach(e=>{e(t)}))}}class pi{constructor(e,t){i(this,"state"),i(this,"config"),i(this,"eventManager"),this.config=e,this.eventManager=t,this.state=this.createInitialState()}createInitialState(){return{polygonDragging:this.config.modes.dragPolygons??!1,markerDragging:this.config.modes.dragElbow??!1,edgeClicking:!0,polygonClicking:!0,canStartDrawing:!0,canCompletePolygon:!1,mapDragging:!0,mapZooming:!0,mapDoubleClickZoom:!0,currentMode:c.Off,isDrawingActive:!1,isModifierKeyHeld:!1,showCrosshairCursor:!1,showDragCursor:!1}}updateStateForMode(e){switch(this.state.currentMode=e,e){case c.Off:this.setOffModeState();break;case c.Add:case c.Subtract:this.setDrawingModeState();break;case c.PointToPoint:case c.PointToPointSubtract:this.setPointToPointModeState();break;case c.Clone:this.setCloneModeState()}this.state.isDrawingActive=e!==c.Off&&e!==c.Clone,this.eventManager.emit("polydraw:mode:change",{mode:e})}setOffModeState(){this.state.polygonDragging=this.config.modes.dragPolygons??!1,this.state.markerDragging=this.config.modes.dragElbow??!1,this.state.edgeClicking=!0,this.state.polygonClicking=!0,this.state.canStartDrawing=!0,this.state.canCompletePolygon=!1,this.state.mapDragging=!0,this.state.mapZooming=!0,this.state.mapDoubleClickZoom=!0,this.state.showCrosshairCursor=!1,this.state.showDragCursor=!1}setDrawingModeState(){this.state.polygonDragging=!1,this.state.markerDragging=!1,this.state.edgeClicking=!1,this.state.polygonClicking=!1,this.state.canStartDrawing=!0,this.state.canCompletePolygon=!0,this.state.mapDragging=!1,this.state.mapZooming=!1,this.state.mapDoubleClickZoom=!1,this.state.showCrosshairCursor=!0,this.state.showDragCursor=!1}setPointToPointModeState(){this.state.polygonDragging=!1,this.state.markerDragging=!1,this.state.edgeClicking=!1,this.state.polygonClicking=!1,this.state.canStartDrawing=!0,this.state.canCompletePolygon=!0,this.state.mapDragging=!1,this.state.mapZooming=!1,this.state.mapDoubleClickZoom=!1,this.state.showCrosshairCursor=!0,this.state.showDragCursor=!1}setCloneModeState(){this.state.polygonDragging=this.config.tools.clone??!1,this.state.markerDragging=!1,this.state.edgeClicking=!1,this.state.polygonClicking=!1,this.state.canStartDrawing=!1,this.state.canCompletePolygon=!1,this.state.mapDragging=!0,this.state.mapZooming=!0,this.state.mapDoubleClickZoom=!0,this.state.showCrosshairCursor=!1,this.state.showDragCursor=!0}setModifierKeyState(e){this.state.isModifierKeyHeld=e,this.state.currentMode,c.Off}canPerformAction(e){switch(e){case"polygonDrag":return this.state.polygonDragging;case"markerDrag":return this.state.markerDragging;case"edgeClick":return this.state.edgeClicking;case"polygonClick":return this.state.polygonClicking;case"startDrawing":return this.state.canStartDrawing;case"completePolygon":return this.state.canCompletePolygon;case"mapDrag":return this.state.mapDragging;case"mapZoom":return this.state.mapZooming;case"mapDoubleClickZoom":return this.state.mapDoubleClickZoom;default:return!1}}isInDrawingMode(){return this.state.isDrawingActive}isInOffMode(){return this.state.currentMode===c.Off}getCurrentMode(){return this.state.currentMode}getState(){return{...this.state}}shouldShowCrosshairCursor(){return this.state.showCrosshairCursor}shouldShowDragCursor(){return this.state.showDragCursor}updateConfig(e){this.config=e,this.updateStateForMode(this.state.currentMode)}}class fi{constructor(e){i(this,"turfHelper"),i(this,"map"),i(this,"config"),i(this,"modeManager"),i(this,"eventManager"),i(this,"tracer"),i(this,"p2pMarkers",[]),i(this,"isModifierKeyHeld",!1),i(this,"markerModifierHandlers",new WeakMap),this.turfHelper=e.turfHelper,this.map=e.map,this.config=e.config,this.modeManager=e.modeManager,this.eventManager=e.eventManager,this.tracer=e.tracer}mouseMove(e){if("latlng"in e&&e.latlng)this.tracer.addLatLng(e.latlng);else if("touches"in e&&e.touches&&e.touches.length>0){const t=this.map.getContainer().getBoundingClientRect(),r=this.map.containerPointToLatLng([e.touches[0].clientX-t.x,e.touches[0].clientY-t.y]);this.tracer.addLatLng(r)}}async mouseUpLeave(e){const t=this.tracer.toGeoJSON();if(!t||!t.geometry||!t.geometry.coordinates||t.geometry.coordinates.length<3)return{success:!1,error:"Not enough points to form a valid polygon. Event: "+JSON.stringify(e)};let r;try{r=this.turfHelper.createPolygonFromTrace(t)}catch(o){return{success:!1,error:(o instanceof Error?o.message:"Failed to create polygon from trace")+". Event: "+JSON.stringify(e)}}return r&&r.geometry&&r.geometry.coordinates&&0!==r.geometry.coordinates.length?(this.eventManager.emit("polydraw:polygon:created",{polygon:r,mode:this.modeManager.getCurrentMode()}),{success:!0,polygon:r}):{success:!1,error:"Invalid polygon created from trace. Event: "+JSON.stringify(e)}}setModifierKey(e){this.isModifierKeyHeld=e}shouldAllowP2PMarkerDeletion(){if(!this.isModifierKeyHeld||!this.config.modes.edgeDeletion)return!1;if(this.config.modifierSubtractMode){const e=this.modeManager.getCurrentMode();if(e===c.PointToPoint||e===c.PointToPointSubtract)return!1}return!0}handlePointToPointClick(e){if(e){if(this.p2pMarkers.length>=3){const t=this.p2pMarkers[0].getLatLng();if(this.isClickingFirstPoint(e,t))return void this.completePointToPointPolygon()}try{const t=this.isTouchDevice(),r=0===this.p2pMarkers.length,o=r?"leaflet-polydraw-p2p-marker leaflet-polydraw-p2p-first-marker":"leaflet-polydraw-p2p-marker",n=r?t?[24,24]:[20,20]:t?[18,18]:[16,16],i=new s.Marker(e,{icon:oi.createDivIcon({className:o,iconSize:n}),draggable:this.config.modes.dragElbow});i.on("add",()=>this.applyP2PMarkerMode(i)),i.addTo(this.map),this.applyP2PMarkerMode(i),i.on("mousedown",e=>{s.DomEvent.stopPropagation(e)}),i.on("drag",()=>{this.updateP2PTracer()}),i.on("click",e=>{this.shouldAllowP2PMarkerDeletion()&&(this.deleteP2PMarker(i),s.DomEvent.stopPropagation(e))}),i.on("mouseover",()=>this.onMarkerHoverForEdgeDeletion(i,!0)),i.on("mouseout",()=>this.onMarkerHoverForEdgeDeletion(i,!1)),r&&(i.on("mouseover",()=>{if(this.p2pMarkers.length>=3){const e=i.getElement();if(e){const t=this.modeManager.getCurrentMode()===c.PointToPointSubtract?this.config.styles.ui.dragSubtract.color:this.config.styles.ui.p2pClosingMarker.color;e.style.backgroundColor=t,e.style.borderColor=t,e.style.cursor="pointer",e.title="Click to close polygon"}}}),i.on("mouseout",()=>{const e=i.getElement();e&&(e.style.backgroundColor="",e.style.borderColor="",e.style.cursor="",e.title="")}),i.on("click",e=>{if(this.shouldAllowP2PMarkerDeletion())return this.deleteP2PMarker(i),void s.DomEvent.stopPropagation(e);this.p2pMarkers.length>=3&&(s.DomEvent.stopPropagation(e),this.completePointToPointPolygon())})),this.p2pMarkers.push(i),this.updateP2PTracer(),this.updateP2PMarkerModes(),this.updateFirstMarkerReadyState()}catch{}}}handleDoubleClick(e){this.modeManager.getCurrentMode()!==c.PointToPoint&&this.modeManager.getCurrentMode()!==c.PointToPointSubtract||this.p2pMarkers.length>=3&&this.completePointToPointPolygon()}handleDoubleTap(e){this.modeManager.getCurrentMode()!==c.PointToPoint&&this.modeManager.getCurrentMode()!==c.PointToPointSubtract||this.p2pMarkers.length>=3&&this.completePointToPointPolygon()}completePointToPointPolygon(){const e=this.p2pMarkers.map(e=>e.getLatLng());if(e.length<3)return;const t=[...e],r=e[0],o=e[e.length-1];r.lat===o.lat&&r.lng===o.lng||t.push(r);try{const e=t.map(e=>[e.lng,e.lat]),r=this.turfHelper.getMultiPolygon([[e]]);this.clearP2pMarkers(),this.resetTracer(),this.eventManager.emit("polydraw:polygon:created",{polygon:r,mode:this.modeManager.getCurrentMode(),isPointToPoint:!0})}catch(n){Wn()||console.warn("Error completing point-to-point polygon:",n),this.clearP2pMarkers(),this.resetTracer()}}cancelPointToPointDrawing(){this.clearP2pMarkers(),this.resetTracer(),this.eventManager.emit("polydraw:draw:cancel",{mode:c.PointToPoint})}clearP2pMarkers(){this.p2pMarkers.forEach(e=>{this.detachMarkerModifierHandler(e);try{this.map.removeLayer(e)}catch{}}),this.p2pMarkers=[]}resetTracer(){this.tracer.setLatLngs([]);try{this.tracer.setStyle({dashArray:void 0})}catch{}}isClickingFirstPoint(e,t){if(!t)return!1;const r=this.map.latLngToLayerPoint(e),o=this.map.latLngToLayerPoint(t);return r.distanceTo(o)<=(this.isTouchDevice()?36:12)}isTouchDevice(){return jn()}updateP2PTracer(){const e=this.p2pMarkers.map(e=>e.getLatLng());if(this.tracer.setLatLngs(e),this.p2pMarkers.length>=2)try{const e=this.modeManager.getCurrentMode()===c.PointToPointSubtract?this.config.styles.subtractLine.color:this.config.styles.polyline.color;this.tracer.setStyle({color:e,dashArray:"5, 5"})}catch{}else try{this.tracer.setStyle({dashArray:void 0})}catch{}}deleteP2PMarker(e){const t=this.p2pMarkers.findIndex(t=>t===e);if(t>-1){this.p2pMarkers.splice(t,1),this.detachMarkerModifierHandler(e);try{this.map.removeLayer(e)}catch{}this.updateP2PTracer(),0===t&&this.p2pMarkers.length>0&&this.setupFirstMarker(),this.updateFirstMarkerReadyState()}}getP2pMarkers(){return[...this.p2pMarkers]}isInPointToPointMode(){const e=this.modeManager.getCurrentMode();return e===c.PointToPoint||e===c.PointToPointSubtract}getTracerPointsCount(){return this.tracer.getLatLngs().length}setupFirstMarker(){if(0===this.p2pMarkers.length)return;const e=this.p2pMarkers[0],t=e.getElement();t&&(t.classList.add("leaflet-polydraw-p2p-first-marker"),t.classList.remove("leaflet-polydraw-p2p-first-marker-ready"),e.setIcon(oi.createDivIcon({className:"leaflet-polydraw-p2p-marker leaflet-polydraw-p2p-first-marker",iconSize:[20,20]})),this.applyP2PMarkerMode(e)),e.off("mouseover"),e.off("mouseout"),e.off("click"),e.on("mouseover",()=>{if(this.p2pMarkers.length>=3){const t=e.getElement();t&&(t.style.cursor="pointer",t.title="Click to close polygon")}}),e.on("mouseout",()=>{const t=e.getElement();t&&(t.style.backgroundColor="",t.style.borderColor="",t.style.cursor="",t.title="")}),e.on("click",t=>{if(this.shouldAllowP2PMarkerDeletion())return this.deleteP2PMarker(e),void s.DomEvent.stopPropagation(t);this.p2pMarkers.length>=3&&(s.DomEvent.stopPropagation(t),this.completePointToPointPolygon())})}updateFirstMarkerReadyState(){if(0===this.p2pMarkers.length)return;this.updateP2PMarkerModes();const e=this.p2pMarkers[0].getElement();e&&(this.p2pMarkers.length>=3?(e.classList.add("leaflet-polydraw-p2p-first-marker-ready"),e.setAttribute("data-p2p-mode",this.modeManager.getCurrentMode()===c.PointToPointSubtract?"subtract":"add"),e.style.cursor="pointer",e.title="Click to close polygon"):(e.classList.remove("leaflet-polydraw-p2p-first-marker-ready"),e.style.cursor="",e.removeAttribute("title")))}refreshP2PMarkerState(){0!==this.p2pMarkers.length&&(this.updateP2PMarkerModes(),this.updateFirstMarkerReadyState())}applyP2PMarkerMode(e){const t=e.getElement();if(!t)return;const r=this.modeManager.getCurrentMode();r===c.PointToPointSubtract?t.setAttribute("data-p2p-mode","subtract"):r===c.PointToPoint?t.setAttribute("data-p2p-mode","add"):t.removeAttribute("data-p2p-mode")}updateP2PMarkerModes(){this.p2pMarkers.forEach(e=>this.applyP2PMarkerMode(e))}onMarkerHoverForEdgeDeletion(e,t){const r=e.getElement();if(r)if(t){this.detachMarkerModifierHandler(e);const t=e=>{if(this.shouldAllowP2PMarkerDeletion()){r.classList.add("edge-deletion-hover");try{this.map.getContainer().style.cursor="pointer"}catch{}}else{r.classList.remove("edge-deletion-hover");try{this.map.getContainer().style.cursor=""}catch{}}};this.markerModifierHandlers.set(e,t),document.addEventListener("keydown",t),document.addEventListener("keyup",t),r.addEventListener("mousemove",t)}else{r.classList.remove("edge-deletion-hover");try{this.map.getContainer().style.cursor=""}catch{}this.detachMarkerModifierHandler(e)}}detachMarkerModifierHandler(e){const t=this.markerModifierHandlers.get(e);if(!t)return;document.removeEventListener("keydown",t),document.removeEventListener("keyup",t);const r=e.getElement();r&&(r.removeEventListener("mousemove",t),r.classList.remove("edge-deletion-hover")),this.markerModifierHandlers.delete(e)}}function yi(e){if(null==e)return e;try{return structuredClone(e)}catch{return mi(e)}}function mi(e,t=new WeakMap){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e))return e.map(e=>mi(e,t));if(t.has(e))return t.get(e);const r={};return t.set(e,r),Object.entries(e).forEach(([e,o])=>{r[e]=mi(o,t)}),r}class vi{constructor(e){i(this,"turfHelper"),i(this,"config"),this.turfHelper=e.turfHelper,this.config=e.config}checkPolygonIntersection(e,t){if(this.isPolygonInsideHole(e,t)||this.isPolygonInsideHole(t,e))return!1;try{const r=this.turfHelper.isPolygonCompletelyWithin(e,t),o=this.turfHelper.isPolygonCompletelyWithin(t,e);if(r||o)return!0}catch{}try{if(this.turfHelper.polygonIntersect(e,t))return!0}catch{}try{const r=this.turfHelper.getIntersection(e,t);if(r&&r.geometry&&("Polygon"===r.geometry.type||"MultiPolygon"===r.geometry.type)){if(this.turfHelper.getPolygonArea(r)>1e-6)return!0}}catch{}try{const r=this.turfHelper.getCoords(e),o=this.turfHelper.getCoords(t);for(const t of o)for(const r of t[0]){const t={type:"Feature",geometry:{type:"Point",coordinates:r},properties:{}};if(this.turfHelper.isPointInsidePolygon(t,e))return!0}for(const e of r)for(const r of e[0]){const e={type:"Feature",geometry:{type:"Point",coordinates:r},properties:{}};if(this.turfHelper.isPointInsidePolygon(e,t))return!0}}catch{}return!1}isPolygonInsideHole(e,t){try{const r=this.turfHelper.getCoords(t);for(const t of r){if(!t||t.length<=1)continue;const r=t.slice(1);for(const t of r)try{const r=this.turfHelper.createPolygon([t]);if(this.turfHelper.isPolygonCompletelyWithin(e,r))return!0}catch{continue}}}catch{}return!1}unionPolygons(e,t){try{let r=t;for(const t of e){const e=this.turfHelper.union(r,t);e&&(r=e)}return{success:!0,result:r}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Unknown error in unionPolygons"}}}subtractPolygon(e,t){try{const r=this.turfHelper.polygonDifference(e,t);if(r){const e=this.turfHelper.getCoords(r),t=[];for(const r of e)t.push(this.turfHelper.getMultiPolygon([r]));return{success:!0,results:t}}return{success:!0,results:[]}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Unknown error in subtractPolygon"}}}simplifyPolygon(e){var t,r;try{const o=this.turfHelper.getCoords(e);if(!o||0===o.length)return{success:!1,error:"Invalid polygon coordinates"};const n=(null==(r=null==(t=this.config.polygonTools)?void 0:t.simplify)?void 0:r.processHoles)??!0,i=o.map(e=>{const t=[];for(let r=0;r<e.length;r++){const o=e[r];if(0===r||n){if(o.length<=4){t.push(o);continue}const e=[];for(let t=0;t<o.length;t+=2)e.push(o[t]);const r=e[0],n=e[e.length-1];r[0]===n[0]&&r[1]===n[1]||e.push(r),e.length<4?t.push(o):t.push(e)}else t.push(o)}return t}),a=this.turfHelper.getMultiPolygon(i);return{success:!0,result:this.turfHelper.getTurfPolygon(a)}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error in simplifyPolygon"}}}convertToBoundingBox(e){var t,r,o,n;try{const i=this.turfHelper.getCoords(e);if(!i||0===i.length)return{success:!1,error:"Invalid polygon coordinates"};if(!((null==(r=null==(t=this.config.polygonTools)?void 0:t.bbox)?void 0:r.processHoles)??!0)){const t=this.turfHelper.convertToBoundingBoxPolygon(e);return{success:!0,result:this.turfHelper.getTurfPolygon(t)}}const a=i.map(e=>{const t=[];for(let r=0;r<e.length;r++){const o=e[r];let n=1/0,i=-1/0,a=1/0,s=-1/0;for(const e of o)if(Array.isArray(e)&&e.length>=2){const t=e[0],r=e[1];"number"!=typeof t||"number"!=typeof r||isNaN(t)||isNaN(r)||(a=Math.min(a,t),s=Math.max(s,t),n=Math.min(n,r),i=Math.max(i,r))}if(n!==1/0&&i!==-1/0&&a!==1/0&&s!==-1/0){const e=[[a,n],[a,i],[s,i],[s,n],[a,n]];t.push(e)}else t.push(o)}return t}),s=this.turfHelper.getMultiPolygon(a);let l=this.turfHelper.getTurfPolygon(s);if(null==(n=null==(o=this.config.polygonTools)?void 0:o.bbox)?void 0:n.addMidPointMarkers){const e=this.doubleElbowsPolygon(l);e.success&&e.result&&(l=e.result)}return{success:!0,result:l}}catch(i){return{success:!1,error:i instanceof Error?i.message:"Unknown error in convertToBoundingBox"}}}bezierifyPolygon(e){try{const t=this.turfHelper.getCoords(e),r=this.turfHelper.getBezierMultiPolygon(t);return{success:!0,result:this.turfHelper.getTurfPolygon(r)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error in bezierifyPolygon"}}}doubleElbowsPolygon(e){var t,r;try{const o=this.turfHelper.getCoords(e);if(!o||0===o.length)return{success:!1,error:"Invalid polygon coordinates"};const n=(null==(r=null==(t=this.config.polygonTools)?void 0:t.doubleElbows)?void 0:r.processHoles)??!0,i=o.map(e=>{const t=[];for(let r=0;r<e.length;r++){const o=e[r];if(0===r||n){const e=o.map(e=>({lat:e[1],lng:e[0]})),r=this.turfHelper.getDoubleElbowLatLngs(e).map(e=>[e.lng,e.lat]);t.push(r)}else t.push(o)}return t}),a=this.turfHelper.getMultiPolygon(i);return{success:!0,result:this.turfHelper.getTurfPolygon(a)}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error in doubleElbowsPolygon"}}}}class Mi{static createDivIcon(e){const t=e.join(" ");return oi.createDivIcon({className:t})}}class bi{static normalizeEvent(e){return ri.getVersion()===l.V2&&(e.layer&&!e.propagatedFrom&&(e.propagatedFrom=e.layer),"mousedown"!==e.type&&"touchstart"!==e.type||(e._isPointerEvent=!0)),e}static getEventName(e){if(ri.getVersion()===l.V2)switch(e){case"mousedown":case"touchstart":return"pointerdown";case"mouseup":case"touchend":return"pointerup";case"mousemove":case"touchmove":return"pointermove";default:return e}return e}static shouldUsePointerEvents(){return ri.getVersion()===l.V2&&"PointerEvent"in window}static extractCoordinates(e,t){if(e.latlng)return e.latlng;if(e.touches&&e.touches.length>0){const r=t.getContainer().getBoundingClientRect();return t.containerPointToLatLng([e.touches[0].clientX-r.x,e.touches[0].clientY-r.y])}if(e.pointerType&&void 0!==e.clientX&&void 0!==e.clientY){const r=t.getContainer().getBoundingClientRect();return t.containerPointToLatLng([e.clientX-r.x,e.clientY-r.y])}if(void 0!==e.clientX&&void 0!==e.clientY){const r=t.getContainer().getBoundingClientRect();return t.containerPointToLatLng([e.clientX-r.x,e.clientY-r.y])}return null}static shouldPreventDefault(e){return!(!e.type||!e.type.startsWith("touch"))||(!e.pointerType||!1!==e.isPrimary)&&!(!("cancelable"in e)||!e.cancelable)}static getEventNames(){return ri.getVersion()===l.V2&&this.shouldUsePointerEvents()?{start:["pointerdown"],move:["pointermove"],end:["pointerup"]}:{start:["mousedown","touchstart"],move:["mousemove","touchmove"],end:["mouseup","touchend"]}}}var wi=(e=>(e.TopLeft="top-left",e.Top="top",e.TopRight="top-right",e.Right="right",e.BottomRight="bottom-right",e.Bottom="bottom",e.BottomLeft="bottom-left",e.Left="left",e.Rotate="rotate",e.Pivot="pivot",e))(wi||{});class Pi{constructor(e,t,r,o,n){var a;i(this,"map"),i(this,"pane"),i(this,"root"),i(this,"draggingHandle",null),i(this,"documentMoveHandler",null),i(this,"documentUpHandler",null),i(this,"pointerCaptureTarget",null),i(this,"activePointerId",null),i(this,"callbacks"),i(this,"rafId",null),i(this,"mode"),i(this,"onCancel"),i(this,"onConfirm"),i(this,"cancelBtn",null),i(this,"confirmBtn",null),i(this,"statusLabel",null),i(this,"currentBBox",null),i(this,"currentRotation",0),i(this,"buttonsHidden",!1),i(this,"destroyed",!1),i(this,"donutValidation",null),i(this,"donutWarningVisible",!1),i(this,"supportsPointerEvents","undefined"!=typeof window&&"PointerEvent"in window),this.map=e,this.callbacks=t,this.mode=r,this.onCancel=o,this.onConfirm=n;const s="polydraw-transform",l=this.map;let c=null==(a=l.getPane)?void 0:a.call(l,s);c||(c=this.map.createPane(s)),c.style.zIndex="650",c.style.pointerEvents="auto",this.pane=c,this.root=document.createElement("div"),this.root.className="polydraw-transform-root",this.root.style.position="absolute",this.root.style.left="0px",this.root.style.top="0px",this.root.style.pointerEvents="none",this.pane.appendChild(this.root)}destroy(){this.destroyed||(this.destroyed=!0,null!=this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.draggingHandle=null,this.detachDocumentDragHandlers(),this.root.remove())}setDonutValidation(e,t=e.warning){this.donutValidation=e,this.donutWarningVisible=t}update(e,t,r=0){this.destroyed||null==this.rafId&&(this.rafId=requestAnimationFrame(()=>{if(this.rafId=null,!this.destroyed&&(this.render(e,t,r),this.cancelBtn||this.confirmBtn)){this.draggingHandle===wi.Rotate&&"rotate"===this.mode||this.updateButtonPositions(e,r)}}))}render(e,t,r=0){const o=this.cancelBtn,n=this.confirmBtn,i=this.statusLabel;this.root.innerHTML="",this.currentBBox=e,this.currentRotation=r,this.cancelBtn=o,this.confirmBtn=n,this.statusLabel=i;const a=e.maxX-e.minX,l=e.maxY-e.minY,c=e.minX+a/2,u=e.minY+l/2,h=this.getAccentPalette(),g=document.createElement("div");g.className="polydraw-transform-box","donut"===this.mode&&this.donutWarningVisible&&g.classList.add("is-invalid"),Object.assign(g.style,{position:"absolute",left:`${c}px`,top:`${u}px`,width:`${a}px`,height:`${l}px`,marginLeft:-a/2+"px",marginTop:-l/2+"px",border:`1px dashed ${h.boxBorder}`,pointerEvents:"none",transformOrigin:"center center",transform:`rotate(${180*r/Math.PI}deg)`}),this.root.appendChild(g);const d=(e,t,o)=>{const n=t-c,i=o-u,a=Math.cos(r),l=Math.sin(r),g=c+n*a-i*l,d=u+n*l+i*a,p=document.createElement("div");p.className=`polydraw-transform-handle handle-${e}`,Object.assign(p.style,{position:"absolute",left:g-5+"px",top:d-5+"px",width:"10px",height:"10px",borderRadius:"2px",background:h.handleFill,boxShadow:`0 0 0 1px ${h.handleOutline}`,cursor:this.cursorForHandle(e),pointerEvents:"auto",touchAction:"none"}),"donut"===this.mode&&this.donutWarningVisible&&p.classList.add("is-invalid"),this.supportsPointerEvents?s.DomEvent.on(p,"pointerdown",t=>this.startDrag(e,{x:g,y:d},t),this):(s.DomEvent.on(p,"mousedown",t=>this.startDrag(e,{x:g,y:d},t),this),s.DomEvent.on(p,"touchstart",t=>this.startDrag(e,{x:g,y:d},t),this)),this.root.appendChild(p)};"scale"===this.mode||"donut"===this.mode?(d(wi.TopLeft,e.minX,e.minY),d(wi.TopRight,e.maxX,e.minY),d(wi.BottomRight,e.maxX,e.maxY),d(wi.BottomLeft,e.minX,e.maxY),d(wi.Top,c,e.minY),d(wi.Right,e.maxX,u),d(wi.Bottom,c,e.maxY),d(wi.Left,e.minX,u)):(d(wi.Rotate,e.minX,e.minY),d(wi.Rotate,e.maxX,e.minY),d(wi.Rotate,e.maxX,e.maxY),d(wi.Rotate,e.minX,e.maxY)),this.cancelBtn||this.confirmBtn?(this.updateButtonPositions(e,r),this.cancelBtn&&this.root.appendChild(this.cancelBtn),this.confirmBtn&&this.root.appendChild(this.confirmBtn)):this.updateButtonPositions(e,r)}cursorForHandle(e){switch(e){case wi.Top:case wi.Bottom:return"ns-resize";case wi.Left:case wi.Right:return"ew-resize";case wi.TopLeft:case wi.BottomRight:return"nwse-resize";case wi.TopRight:case wi.BottomLeft:return"nesw-resize";case wi.Rotate:return"grab";case wi.Pivot:return"move";default:return"default"}}startDrag(e,t,r){var o,n;if(this.destroyed)return;s.DomEvent.stop(r),this.draggingHandle=e,this.hideButtons(),this.documentMoveHandler=e=>this.onDrag(e),this.documentUpHandler=e=>this.endDrag(e);const i=document,a=this.documentMoveHandler,l=this.documentUpHandler;if(this.supportsPointerEvents&&r instanceof PointerEvent){this.activePointerId=r.pointerId,this.pointerCaptureTarget=this.map.getContainer();try{null==(n=null==(o=this.pointerCaptureTarget)?void 0:o.setPointerCapture)||n.call(o,r.pointerId)}catch{}s.DomEvent.on(i,"pointermove",a),s.DomEvent.on(i,"pointerup",l),s.DomEvent.on(i,"pointercancel",l)}else s.DomEvent.on(i,"mousemove",a),s.DomEvent.on(i,"mouseup",l),s.DomEvent.on(i,"touchmove",a),s.DomEvent.on(i,"touchend",l),s.DomEvent.on(i,"touchcancel",l);this.callbacks.onStartHandleDrag(e,t,r)}onDrag(e){if(null==this.draggingHandle)return;const t=this.getMouseLayerPoint(e);this.callbacks.onDragHandle(this.draggingHandle,t,e)}endDrag(e){if(null==this.draggingHandle)return;const t=this.draggingHandle;this.draggingHandle=null;try{const r=this.getMouseLayerPoint(e);this.callbacks.onEndHandleDrag(t,r,e),this.currentBBox&&this.updateButtonPositions(this.currentBBox,this.currentRotation),this.showButtons()}finally{this.detachDocumentDragHandlers()}}detachDocumentDragHandlers(){var e,t;if(!this.documentMoveHandler&&!this.documentUpHandler&&!this.pointerCaptureTarget)return;const r=document;if(this.supportsPointerEvents&&this.pointerCaptureTarget){if(null!=this.activePointerId)try{null==(t=(e=this.pointerCaptureTarget).releasePointerCapture)||t.call(e,this.activePointerId)}catch{}if(this.documentMoveHandler){const e=this.documentMoveHandler;s.DomEvent.off(r,"pointermove",e)}if(this.documentUpHandler){const e=this.documentUpHandler;s.DomEvent.off(r,"pointerup",e),s.DomEvent.off(r,"pointercancel",e)}this.pointerCaptureTarget=null,this.activePointerId=null}else{if(this.documentMoveHandler){const e=this.documentMoveHandler;s.DomEvent.off(r,"mousemove",e),s.DomEvent.off(r,"touchmove",e)}if(this.documentUpHandler){const e=this.documentUpHandler;s.DomEvent.off(r,"mouseup",e),s.DomEvent.off(r,"touchend",e),s.DomEvent.off(r,"touchcancel",e)}}this.documentMoveHandler=null,this.documentUpHandler=null}getMouseLayerPoint(e){const t=this.map.getContainer();let r=null,o=null;if(e.touches&&e.touches.length>0){const t=e.touches[0];r=t.clientX,o=t.clientY}else if(e.changedTouches&&e.changedTouches.length>0){const t=e.changedTouches[0];r=t.clientX,o=t.clientY}else null!=e.clientX&&(r=e.clientX,o=e.clientY);null!=r&&null!=o||(r=0,o=0);const n=t.getBoundingClientRect(),i=r-n.left,a=o-n.top,s=oi.createPoint(i,a),l=this.map.containerPointToLayerPoint(s);return{x:l.x,y:l.y}}updateButtonPositions(e,t){var r,o;const n=e.maxX-e.minX,i=e.maxY-e.minY,a=e.minX+n/2,l=e.minY+i/2,c=[{x:e.minX,y:e.minY},{x:e.maxX,y:e.minY},{x:e.maxX,y:e.maxY},{x:e.minX,y:e.maxY}],u=Math.cos(t),h=Math.sin(t);let g={x:0,y:1/0},d=1/0;for(const s of c){const e=s.x-a,t=s.y-l,r=a+e*u-t*h,o=l+e*h+t*u,n=o<d,i=Math.abs(o-d)<1,c=r>g.x;(n||i&&c)&&(d=o,g={x:r,y:o})}const p=g.x,f=g.y-28,y=p+5,m=p-29,v=m-12,M=f+4;if(this.onCancel&&!this.cancelBtn&&(this.cancelBtn=document.createElement("div"),this.cancelBtn.className="polydraw-transform-cancel",this.cancelBtn.innerHTML='<?xml version="1.0" encoding="UTF-8"?>\n<svg width="512" height="512" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">\n <circle cx="256" cy="256" r="236" fill="#212A32"/>\n <circle cx="256" cy="256" r="190" fill="#ffffff"/>\n <path id="path2" fill="#800000" fill-rule="evenodd" stroke="none"\n d="M 156 373.906311 C 140.875 373.871002 127.9375 373.615112 127.25 373.337708 C 126.5625 373.060303 126 372.072937 126 371.143555 C 126 370.214203 146.628433 343.53772 171.840973 311.862488 C 197.053513 280.187286 217.991867 253.463562 218.370667 252.47644 C 218.806335 251.341125 218.221786 249.464233 216.779678 247.368073 C 215.525864 245.545563 196.612503 221.361847 174.75 193.626465 C 152.887497 165.891052 135 142.531311 135 141.715881 C 135 140.900421 136.012497 139.961914 137.25 139.63028 C 138.487503 139.298645 152.408203 139.021179 168.184906 139.013641 C 184.588272 139.005859 197.976456 139.420746 199.454529 139.982727 C 201.182831 140.639801 210.486664 152.319733 227.533463 175.232727 C 241.555283 194.079712 253.994949 210.166199 255.177185 210.980438 C 257.208252 212.379272 257.562622 212.186401 261.607452 207.480438 C 263.961853 204.74118 276.052643 189 288.47583 172.5 C 300.899048 156 312.286682 141.714874 313.781738 140.75528 C 316.198669 139.203949 319.554993 139.009949 344.058868 139.00528 C 366.27774 139.001007 371.993561 139.274811 373.557343 140.418274 C 375.458923 141.808746 375.448914 141.90155 373.046875 145.150452 C 371.699341 146.973114 352.828827 170.746307 331.112396 197.979767 C 309.395966 225.213257 291.465973 248.396271 291.267914 249.497589 C 291.012512 250.91803 304.435944 268.61731 337.453918 310.395416 C 363.05426 342.787903 384 370.077271 384 371.038422 C 384 371.999603 383.288208 373.059174 382.418213 373.393005 C 381.548218 373.726868 367.485718 373.993347 351.168213 373.98526 C 329.591888 373.974548 320.854309 373.633606 319.132629 372.73526 C 317.830597 372.055847 302.980591 353.049988 286.132629 330.5 C 260.059052 295.602051 255.12793 289.5 253 289.5 C 250.878326 289.5 245.808807 295.701355 219.5 330.479431 C 202.449997 353.018127 187.375 372.023987 186 372.714691 C 184.165009 373.636475 176.184906 373.95343 156 373.906311 Z"/>\n</svg>',s.DomEvent.on(this.cancelBtn,"mousedown",e=>{e.stopPropagation(),e.preventDefault(),this.onCancel&&this.onCancel()}),s.DomEvent.on(this.cancelBtn,"touchstart",e=>{e.stopPropagation(),e.preventDefault(),this.onCancel&&this.onCancel()}),s.DomEvent.on(this.cancelBtn,"pointerdown",e=>{e.stopPropagation(),e.preventDefault(),this.onCancel&&this.onCancel()}),this.root.appendChild(this.cancelBtn)),this.onConfirm&&!this.confirmBtn&&(this.confirmBtn=document.createElement("div"),this.confirmBtn.className="polydraw-transform-confirm",this.confirmBtn.innerHTML='<?xml version="1.0" encoding="UTF-8"?>\n<svg width="512" height="512" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">\n <circle cx="256" cy="256" r="236" fill="#212A32"/>\n <circle cx="256" cy="256" r="190" fill="#ffffff"/>\n <path id="check" fill="#008000" fill-rule="evenodd" stroke="none"\n d="M 223.844696 360 C 222.79425 360 204.506973 341.170593 178.987274 313.812744 \n C 144.992401 277.369232 135.966232 267.145691 136.201645 265.351257 \n C 136.396179 263.868408 143.092361 257.073425 155.444672 245.824249 \n C 166.363129 235.880859 175.214264 228.571442 176.336426 228.571442 \n C 177.515594 228.571442 181.716553 232.304138 186.987961 238.035706 \n C 191.775406 243.241058 201.629044 254.024994 208.884933 262 \n C 216.140823 269.975006 222.682266 276.635315 223.421478 276.80072 \n C 224.16246 276.966553 247.742722 250.494751 275.976837 217.800751 \n C 304.143097 185.185333 328.050385 157.879608 329.104156 157.121368 \n C 330.785767 155.911316 331.44046 156.0336 334.457672 158.121368 \n C 336.348328 159.429626 345.368622 167.190216 354.502747 175.367126 \n C 367.688812 187.171356 371.047394 190.689819 370.805115 192.445557 \n C 370.635864 193.67218 338.242889 231.469543 298.059082 277.32843 \n C 253.148834 328.581238 224.944153 360 223.844696 360 Z"/>\n</svg>',s.DomEvent.on(this.confirmBtn,"mousedown",e=>{e.stopPropagation(),e.preventDefault(),this.onConfirm&&this.isConfirmEnabled()&&this.onConfirm()}),s.DomEvent.on(this.confirmBtn,"touchstart",e=>{e.stopPropagation(),e.preventDefault(),this.onConfirm&&this.isConfirmEnabled()&&this.onConfirm()}),s.DomEvent.on(this.confirmBtn,"pointerdown",e=>{e.stopPropagation(),e.preventDefault(),this.onConfirm&&this.isConfirmEnabled()&&this.onConfirm()}),this.root.appendChild(this.confirmBtn)),"donut"!==this.mode||this.statusLabel||(this.statusLabel=document.createElement("div"),this.statusLabel.className="polydraw-transform-status",this.root.appendChild(this.statusLabel)),this.cancelBtn){Object.assign(this.cancelBtn.style,{position:"absolute",left:`${m}px`,top:`${f}px`,display:"grid",placeItems:"center",pointerEvents:"auto",width:"28px",height:"28px"});const e=this.cancelBtn.querySelector("svg");e&&(e.setAttribute("width","24"),e.setAttribute("height","24")),this.cancelBtn.style.display=this.buttonsHidden?"none":"grid"}if(this.confirmBtn){const e=this.isConfirmEnabled();Object.assign(this.confirmBtn.style,{position:"absolute",left:`${y}px`,top:`${f}px`,display:"grid",placeItems:"center",pointerEvents:e?"auto":"none",width:"28px",height:"28px"});const t=this.confirmBtn.querySelector("svg");t&&(t.setAttribute("width","24"),t.setAttribute("height","24")),this.confirmBtn.classList.toggle("is-disabled",!e),this.confirmBtn.setAttribute("aria-disabled",String(!e)),this.confirmBtn.style.display=this.buttonsHidden?"none":"grid"}if(this.statusLabel){const e="donut"===this.mode&&this.donutWarningVisible;this.statusLabel.innerHTML=e?'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512.055 512.055">\n <g transform="translate(-1)">\n <path\n fill="#facc15"\n d="M56.879,469.361L257.028,69.064l200.149,400.297H56.879z"\n />\n <path\n fill="#7f1d1d"\n fill-rule="evenodd"\n clip-rule="evenodd"\n d="M510.775,481.154L276.109,11.82c-7.862-15.724-30.3-15.724-38.162,0L3.28,481.154 c-7.092,14.185,3.222,30.874,19.081,30.874h469.333C507.553,512.028,517.868,495.338,510.775,481.154z M56.879,469.361 L257.028,69.064l200.149,400.297H56.879z"\n />\n <path\n fill="#7f1d1d"\n d="M235.694,192.028v149.333c0,11.782,9.551,21.333,21.333,21.333s21.333-9.551,21.333-21.333V192.028 c0-11.782-9.551-21.333-21.333-21.333S235.694,180.245,235.694,192.028z"\n />\n <path\n fill="#7f1d1d"\n d="M257.028,384.028c-11.776,0-21.333,9.557-21.333,21.333s9.557,21.333,21.333,21.333s21.333-9.557,21.333-21.333 S268.804,384.028,257.028,384.028z"\n />\n </g>\n</svg>\n':"",this.statusLabel.classList.toggle("is-invalid",e),this.statusLabel.setAttribute("data-donut-validity",(null==(r=this.donutValidation)?void 0:r.validity)??"invalid"),this.statusLabel.title=e?(null==(o=this.donutValidation)?void 0:o.statusText)??"":"",Object.assign(this.statusLabel.style,{position:"absolute",left:`${v}px`,top:`${M}px`,transform:"translateX(-100%)",pointerEvents:"none",display:e?"grid":"none"}),e&&this.root.appendChild(this.statusLabel)}}hideButtons(){this.buttonsHidden=!0,this.cancelBtn&&(this.cancelBtn.style.display="none"),this.confirmBtn&&(this.confirmBtn.style.display="none")}showButtons(){this.buttonsHidden=!1,this.cancelBtn&&(this.cancelBtn.style.display="grid"),this.confirmBtn&&(this.confirmBtn.style.display="grid",this.isConfirmEnabled()||(this.confirmBtn.style.display="grid"))}getAccentPalette(){return"donut"===this.mode&&this.donutWarningVisible?{boxBorder:"#d97706",handleFill:"#f59e0b",handleOutline:"#fff7ed"}:{boxBorder:"#2b90d9",handleFill:"#2b90d9",handleOutline:"#fff"}}isConfirmEnabled(){var e;return"donut"!==this.mode||!0===(null==(e=this.donutValidation)?void 0:e.submitEnabled)}}function Li(e,t){const r=e.latLngToLayerPoint(t);return{x:r.x,y:r.y}}function ki(e,t){const r=e.layerPointToLatLng(oi.createPoint(t.x,t.y));return{lat:r.lat,lng:r.lng}}function Ei(e){let t=1/0,r=1/0,o=-1/0,n=-1/0;for(const i of e)for(const e of i)for(const i of e)i.x<t&&(t=i.x),i.y<r&&(r=i.y),i.x>o&&(o=i.x),i.y>n&&(n=i.y);return{minX:t,minY:r,maxX:o,maxY:n}}function xi(e){return{x:(e.minX+e.maxX)/2,y:(e.minY+e.maxY)/2}}function Si(e,t,r,o){const n=e.x-t.x,i=e.y-t.y;return{x:t.x+n*r,y:t.y+i*o}}function Di(e,t,r,o,n){return e.map(e=>e.map(e=>e.map(e=>function(e,t,r){const o=Math.cos(r),n=Math.sin(r),i=e.x-t.x,a=e.y-t.y;return{x:t.x+i*o-a*n,y:t.y+i*n+a*o}}(Si(e,t,r,o),t,n))))}function Ci(e){if(0===e.length)return e;const t=e[0],r=e[e.length-1];return t.lat===r.lat&&t.lng===r.lng?e:[...e,{lat:t.lat,lng:t.lng}]}function Ii(e){if(!Array.isArray(e))return[[e]];const t=e;return 0===t.length?[]:Array.isArray(t[0])?Array.isArray(t[0][0])?e:[e]:[[e]]}function Ai(e,t,r){const o=[];for(let n=0;n<t.length;n++){const i=[];for(let o=0;o<t[n].length;o++){const a=t[n][o].map(t=>ki(e,t)),s=r[n][o],l=s.length>2&&s[0].lat===s[s.length-1].lat&&s[0].lng===s[s.length-1].lng;i.push(l?Ci(a):a)}o.push(i)}return o}function Fi(e){const t=e.map(e=>[e.lng,e.lat]);if(0===t.length)return t;const[r,o]=t[0],[n,i]=t[t.length-1];return r===n&&o===i||t.push([r,o]),t}function Oi(e){return{type:"Feature",geometry:{type:"Polygon",coordinates:[e]},properties:{}}}function Ti(e,t){return{validity:"invalid",reason:e,submitEnabled:!1,warning:!0,statusText:t}}class _i{constructor(e,t,r="scale",o=h.Both,n){var a,l;i(this,"map"),i(this,"polygon"),i(this,"overlay"),i(this,"state"),i(this,"normalizedLatLngs"),i(this,"wasMapDraggingEnabled",!1),i(this,"mode"),i(this,"onExit"),i(this,"rotateStartAngle",null),i(this,"rotateBaseRotation",0),i(this,"originalTouchAction",null),i(this,"mapDraggingHandler"),i(this,"originalPolygonStyle"),i(this,"donutDirection"),i(this,"onKeyDown",e=>{"Escape"===e.key&&this.handleCancel()}),i(this,"updateOverlay",()=>{const e=Ei(this.state.originalPixelRings.map(e=>e.map(e=>e.map(e=>Si(e,this.state.pivot,this.state.scaleX,this.state.scaleY)))));this.overlay.update(e,this.state.pivot,this.state.rotation)}),this.map=e,this.mode=r,this.donutDirection=o,this.onExit=n;const c=t.getLayers().find(e=>e instanceof s.Polygon);if(!c)throw new Error("FeatureGroup does not contain a polygon");this.polygon=c,this.originalPolygonStyle={color:this.polygon.options.color,fillColor:this.polygon.options.fillColor,opacity:this.polygon.options.opacity,fillOpacity:this.polygon.options.fillOpacity};const u=this.polygon.getLatLngs();this.normalizedLatLngs=Ii(u);const g=function(e,t){const r=[],o=[];for(const n of t){const t=[],i=[];for(const r of n){const o=r.map(t=>Li(e,{lat:t.lat,lng:t.lng}));t.push(o),i.push(r.length)}r.push(t),o.push(i)}return{rings:r,ringLengths:o}}(this.map,this.normalizedLatLngs),d=xi(Ei(g.rings));this.state={isActive:!0,originalLatLngs:u,originalPixelRings:g.rings,pivot:d,scaleX:1,scaleY:1,rotation:0,uniformScale:!1,snapRotation:!1,scaleFromPivot:!1},this.overlay=new Pi(this.map,{onStartHandleDrag:(e,t,r)=>this.onStartDrag(e,t,r),onDragHandle:(e,t)=>this.onDrag(e,t),onEndHandleDrag:()=>{}},this.mode,()=>this.handleCancel(),()=>this.handleConfirm()),this.updateOverlay(),this.syncDonutValidation(),this.map.on("zoom viewreset move",this.updateOverlay,this),this.mapDraggingHandler=this.map.dragging,this.mapDraggingHandler&&("function"==typeof this.mapDraggingHandler.enabled&&(this.wasMapDraggingEnabled=this.mapDraggingHandler.enabled()),null==(l=(a=this.mapDraggingHandler).disable)||l.call(a));const p=this.map.getContainer();this.originalTouchAction=p.style.touchAction||null,p.style.touchAction="none",document.addEventListener("keydown",this.onKeyDown)}destroy(){document.removeEventListener("keydown",this.onKeyDown),this.map.off("zoom viewreset move",this.updateOverlay,this),this.restorePolygonStyle(),this.overlay.destroy(),this.state.isActive=!1,this.mapDraggingHandler&&this.wasMapDraggingEnabled&&"function"==typeof this.mapDraggingHandler.enable&&this.mapDraggingHandler.enable();const e=this.map.getContainer();null!==this.originalTouchAction?e.style.touchAction=this.originalTouchAction:e.style.touchAction=""}onStartDrag(e,t,r){const o=navigator.userAgent.toLowerCase().includes("mac")?r.metaKey:r.ctrlKey;if(this.state.uniformScale=!!r.shiftKey,this.state.scaleFromPivot=!!r.altKey,this.state.snapRotation=!!o,e===wi.Rotate){const e=this.state.scaleFromPivot?this.state.pivot:xi(Ei(this.state.originalPixelRings)),r=Math.atan2(t.y-e.y,t.x-e.x);this.rotateStartAngle=r,this.rotateBaseRotation=this.state.rotation||0}}onDrag(e,t){const r=Ei(this.state.originalPixelRings);switch(e){case wi.Rotate:{const e=this.state.scaleFromPivot?this.state.pivot:xi(r);this.handleRotateDrag(t,e);break}case wi.Pivot:this.handlePivotDrag(t);break;default:{const o=this.state.scaleFromPivot?this.state.pivot:xi(r);this.handleScaleDrag(e,t,r,o);break}}this.preview()}handleRotateDrag(e,t){if("rotate"!==this.mode)return;const r=Math.atan2(e.y-t.y,e.x-t.x);let o;if(null!=this.rotateStartAngle){const e=r-this.rotateStartAngle;o=this.rotateBaseRotation+e}else o=r;this.state.rotation=this.state.snapRotation?function(e,t=15){const r=t*Math.PI/180;return Math.round(e/r)*r}(o,15):o}handlePivotDrag(e){this.state.pivot=e}handleScaleDrag(e,t,r,o){if("rotate"===this.mode)return;const n=r.maxX-r.minX,i=r.maxY-r.minY;let a=this.state.scaleX,s=this.state.scaleY;switch(e){case wi.Left:case wi.TopLeft:case wi.BottomLeft:a=(o.x-t.x)/(o.x-r.minX||1);break;case wi.Right:case wi.TopRight:case wi.BottomRight:a=(t.x-o.x)/(r.maxX-o.x||1)}switch(e){case wi.Top:case wi.TopLeft:case wi.TopRight:s=(o.y-t.y)/(o.y-r.minY||1);break;case wi.Bottom:case wi.BottomLeft:case wi.BottomRight:s=(t.y-o.y)/(r.maxY-o.y||1)}if(e!==wi.Left&&e!==wi.Right||(s=this.state.scaleY),e!==wi.Top&&e!==wi.Bottom||(a=this.state.scaleX),this.state.uniformScale){const e=Math.abs(n)>Math.abs(i)?Math.sign(a)*Math.abs(a):Math.sign(s)*Math.abs(s);a=e,s=e}const l=Number.isFinite(a)&&Math.abs(a)>.001,c=Number.isFinite(s)&&Math.abs(s)>.001;l&&(this.state.scaleX=a),c&&(this.state.scaleY=s)}preview(){var e,t;const r=Di(this.state.originalPixelRings,this.state.pivot,this.state.scaleX,this.state.scaleY,this.state.rotation),o=Ai(this.map,r,this.normalizedLatLngs);if("donut"===this.mode){const r=(null==(e=this.normalizedLatLngs[0])?void 0:e[0])??[],n=(null==(t=o[0])?void 0:t[0])??[];this.polygon.setLatLngs([[r,n]]),this.syncDonutValidation()}else this.polygon.setLatLngs(o);this.updateOverlay()}apply(){return Ii(this.polygon.getLatLngs())}cancel(){this.restorePolygonStyle(),this.polygon.setLatLngs(this.state.originalLatLngs)}getMode(){return this.mode}getOriginalOuterLatLngs(){var e;return(null==(e=this.normalizedLatLngs[0])?void 0:e[0])??[]}getScaledOuterLatLngs(){var e;const t=Di(this.state.originalPixelRings,this.state.pivot,this.state.scaleX,this.state.scaleY,this.state.rotation);return(null==(e=Ai(this.map,t,this.normalizedLatLngs)[0])?void 0:e[0])??[]}getDonutValidation(){return function(e,t,r,o,n=h.Both){if(e.length<3||t.length<3)return Ti("invalid-rings","Scale to create a donut");if(Math.abs(r-1)<.01&&Math.abs(o-1)<.01)return Ti("scale-required","Scale to create a donut");const i=Fi(e),a=Fi(t);if(i.length<4||a.length<4)return Ti("invalid-rings","Scale to create a donut");const s=Oi(i),l=Oi(a);let c=!1,u=!1;try{c=zo(l,s),u=zo(s,l)}catch{return Ti("partial-overlap","Donut requires one shape to fully contain the other")}return c||u?u&&n===h.Inward?Ti("direction-restricted","Only inward donuts allowed"):{validity:u?"valid-outward":"valid-inward",reason:u?"nested-outward":"nested-inward",submitEnabled:!0,warning:!1,statusText:"Valid donut",allowMerge:u,polygon:{type:"Feature",geometry:{type:"Polygon",coordinates:[u?a:i,u?i:a]},properties:{}}}:Ti("partial-overlap","Donut requires one shape to fully contain the other")}(this.getOriginalOuterLatLngs(),this.getScaledOuterLatLngs(),this.state.scaleX,this.state.scaleY,this.donutDirection)}syncDonutValidation(){if("donut"!==this.mode)return;const e=this.getDonutValidation(),t=e.warning&&"scale-required"!==e.reason;this.overlay.setDonutValidation(e,t),t?this.polygon.setStyle({color:"#d97706",fillColor:"#f59e0b",opacity:Math.max(this.originalPolygonStyle.opacity??0,.95),fillOpacity:Math.max(this.originalPolygonStyle.fillOpacity??0,.2)}):this.restorePolygonStyle()}restorePolygonStyle(){"donut"===this.mode&&this.polygon.setStyle({color:this.originalPolygonStyle.color,fillColor:this.originalPolygonStyle.fillColor,opacity:this.originalPolygonStyle.opacity,fillOpacity:this.originalPolygonStyle.fillOpacity})}handleCancel(){this.cancel(),this.onExit&&this.onExit(!1),this.destroy()}handleConfirm(){this.onExit&&this.onExit(!0),this.destroy()}}class Gi{static createMenuButton(e,t,r){const o=document.createElement("div");return o.classList.add("marker-menu-button",...r),o.title=t,o.setAttribute("aria-label",t),o.setAttribute("data-action-id",e),o}static buildMenuPopup(e){const t=document.createElement("div");t.classList.add("alter-marker-outer-wrapper");const r=document.createElement("div");r.classList.add("alter-marker-wrapper");const o=document.createElement("button");o.type="button",o.className="marker-menu-close",o.setAttribute("aria-label","Close menu"),o.innerHTML="&times;",r.appendChild(o);const n=document.createElement("div");n.classList.add("content");const i=document.createElement("div");return i.classList.add("marker-menu-content"),e.forEach(e=>{i.appendChild(e)}),n.appendChild(i),r.appendChild(n),t.appendChild(r),t}static buildInfoPopup(e){const t=document.createElement("div");t.classList.add("info-marker-outer-wrapper");const r=document.createElement("div");r.classList.add("info-marker-wrapper");const o=document.createElement("div");return o.classList.add("content"),o.appendChild(e),r.appendChild(o),t.appendChild(r),t}}const Hi=new Set(["simplify","doubleElbows","bbox","bezier","scale","rotate","donut","toggleOptimization"]);class Bi{constructor(e,t){i(this,"markerFeatureGroupMap",new WeakMap),i(this,"polygonFeatureGroupMap",new WeakMap),i(this,"markerModifierHandlers",new WeakMap),i(this,"markerTouchListeners",new WeakMap),i(this,"markerEdgeDeletionListeners",new WeakMap),i(this,"_activeMarker",null),i(this,"isDraggingMarker",!1),i(this,"turfHelper"),i(this,"polygonInformation"),i(this,"map"),i(this,"config"),i(this,"modeManager"),i(this,"eventManager"),i(this,"saveHistoryState"),i(this,"layerManager"),i(this,"currentDragPolygon",null),i(this,"currentDragIsClone",!1),i(this,"currentModifierDragMode",!1),i(this,"isModifierKeyHeld",!1),i(this,"currentCloneGhost",null),i(this,"dragCancelHandlersAttached",!1),i(this,"_boundDragTouchMove",null),i(this,"_boundDragTouchEnd",null),i(this,"_boundDragMoveListener",null),i(this,"_boundDragEndListener",null),i(this,"dragUsesPointerEvents",!1),i(this,"polygonTouchStartListeners",new WeakMap),i(this,"_openMenuPopup",null),i(this,"transformModeActive",!1),i(this,"transformControllers",new WeakMap),i(this,"deleteMarkerSuppressUntil",0),i(this,"onModeChange",()=>{(this.currentCloneGhost||this.isPolygonDragActive())&&this.cancelActivePolygonDrag()}),i(this,"getFeatureGroups"),i(this,"removeFeatureGroup"),i(this,"onPolygonMouseMove",e=>{if(!this.currentDragPolygon||!this.currentDragPolygon._polydrawDragData||!this.currentDragPolygon._polydrawDragData.isDragging)return;const t=this.currentDragPolygon,r=t._polydrawDragData;if(!this.currentDragIsClone){const t=e.originalEvent&&"metaKey"in e.originalEvent?e.originalEvent:e;this.detectDragSubtractModifierKey(t)!==this.currentModifierDragMode&&this.handleModifierToggleDuringDrag(t)}const o=r.startPosition,n=e.latlng,i=n.lat-o.lat,a=n.lng-o.lng,s=this.offsetPolygonCoordinates(r.startLatLngs,i,a);t.setLatLngs(s),this.updateMarkersAndHoleLinesDuringDrag(t,i,a)}),i(this,"onPolygonMouseUp",e=>{if(!this.currentDragPolygon||!this.currentDragPolygon._polydrawDragData||!this.currentDragPolygon._polydrawDragData.isDragging)return;const t=this.currentDragPolygon,r=t._polydrawDragData;r.isDragging=!1,this.map.dragging&&this.map.dragging.enable(),t._polydrawDragData&&null!=t._polydrawDragData.originalOpacity&&t.setStyle({fillOpacity:t._polydrawDragData.originalOpacity}),this.setMarkerVisibility(t,!0);try{this.map.getContainer().style.cursor=""}catch{}this.clearCloneGhost(),this.detachDragTouchListeners(),this.detachDragDocumentListeners(),this.detachDragCancelHandlers();const o=this.currentDragIsClone;this.currentDragIsClone=!1,o?this.updatePolygonAfterCloneDrag(t,r):this.updatePolygonAfterDrag(t),t._polydrawOriginalMarkerPositions&&(t._polydrawOriginalMarkerPositions.clear(),delete t._polydrawOriginalMarkerPositions),t._polydrawOriginalHoleLinePositions&&(t._polydrawOriginalHoleLinePositions.clear(),delete t._polydrawOriginalHoleLinePositions),t._polydrawCurrentDragSession&&delete t._polydrawCurrentDragSession,this.currentDragPolygon=null}),i(this,"onPolygonDragCancel",()=>{this.cancelActivePolygonDrag()}),i(this,"onPolygonDragKeyDown",e=>{"Escape"===e.key&&this.cancelActivePolygonDrag()}),i(this,"onDragTouchMove",e=>{e.preventDefault();const t=bi.extractCoordinates(e,this.map);t&&this.onPolygonMouseMove({latlng:t})}),i(this,"onDragTouchEnd",e=>{e.preventDefault(),this.onPolygonMouseUp({latlng:null})}),i(this,"onDragDocumentMove",e=>{const t=bi.extractCoordinates(e,this.map);t&&this.onPolygonMouseMove({latlng:t,originalEvent:e})}),i(this,"onDragDocumentEnd",e=>{const t=bi.extractCoordinates(e,this.map)??null;this.onPolygonMouseUp({latlng:t,originalEvent:e})}),i(this,"onMarkerHoverForEdgeDeletionEvent",e=>{if(!this.isModifierKeyHeld)return;const t=e.target;t&&(t.style.backgroundColor=this.config.styles.ui.edgeDeletion.color,t.style.borderColor=this.config.styles.ui.edgeDeletion.color,t.classList.add("edge-deletion-hover"))}),i(this,"onMarkerLeaveForEdgeDeletionEvent",e=>{const t=e.target;t&&(t.style.backgroundColor="",t.style.borderColor="",t.classList.remove("edge-deletion-hover"))}),this.turfHelper=e.turfHelper,this.polygonInformation=e.polygonInformation,this.map=e.map,this.config=e.config,this.modeManager=e.modeManager,this.eventManager=e.eventManager,this.saveHistoryState=e.saveHistoryState,this.layerManager=e.layerManager,this.getFeatureGroups=t.getFeatureGroups,this.removeFeatureGroup=t.removeFeatureGroup,this.eventManager.on("polydraw:mode:change",this.onModeChange)}emitPolygonUpdated(e){const t=this.getHistoryActionForOperation(e.operation);t&&this.saveHistoryState&&this.saveHistoryState(t),this.eventManager.emit("polydraw:polygon:updated",e)}getHistoryActionForOperation(e){switch(e){case"addVertex":case"removeVertex":case"removeHole":case"toggleOptimization":return e;case"modifierSubtract":case"modifierSubtractFallback":return"modifierSubtract";default:return null}}donutTargetHasHoles(e){const t=e.getLayers().find(e=>e instanceof s.Polygon);if(!t)return!0;const r=t.getLatLngs();if(!Array.isArray(r)||0===r.length)return!0;if(!Array.isArray(r[0]))return!1;const o=r;return!!Array.isArray(o[0][0])||o.length>1}handleDonutCommit(e,t,r,o,n){const i=e.getOriginalOuterLatLngs(),a=e.getDonutValidation(),s=()=>{r.setLatLngs([i]),this.setMarkerVisibility(r,!0)};a.submitEnabled&&a.polygon?(r.setLatLngs([i]),this.saveHistoryState&&this.saveHistoryState("donut"),this.cleanupFeatureGroup(t),this.removeFeatureGroup(t),this.emitPolygonUpdated({operation:"donut",polygon:a.polygon,allowMerge:a.allowMerge,optimizationLevel:o,originalOptimizationLevel:n})):s()}dispose(){this.eventManager.off("polydraw:mode:change",this.onModeChange),this.cancelActivePolygonDrag()}getTimestamp(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}shouldSuppressDeleteMarkerClick(){return this.getTimestamp()<this.deleteMarkerSuppressUntil}suppressDeleteMarkerClicks(e){this.deleteMarkerSuppressUntil=this.getTimestamp()+Math.max(0,e)}addMarkers(e,t,r={}){this.registerPolygonLayerMappings(t);let o=this.getMarkerIndex(e,this.config.markers.markerMenuIcon.position),n=this.getMarkerIndex(e,this.config.markers.markerDeleteIcon.position),i=this.getMarkerIndex(e,this.config.markers.markerInfoIcon.position);const a=this.ensureMarkerSeparation(e.length,{menu:{index:o,enabled:this.config.markers.menuMarker},delete:{index:n,enabled:this.config.markers.deleteMarker},info:{index:i,enabled:this.config.markers.infoMarker}});o=a.menu,n=a.delete,i=a.info;const l=r.optimizationLevel??0,c=this.deriveImportantMarkerIndices(e,{menuIndex:o,deleteIndex:n,infoIndex:i,optimizationLevel:l}),u=e.length>2&&this.latLngEquals(e[0],e[e.length-1]);e.forEach((r,a)=>{let h=this.config.markers.markerIcon.styleClasses;a===o&&this.config.markers.menuMarker&&(h=this.config.markers.markerMenuIcon.styleClasses),a===n&&this.config.markers.deleteMarker&&(h=this.config.markers.markerDeleteIcon.styleClasses),a===i&&this.config.markers.infoMarker&&(h=this.config.markers.markerInfoIcon.styleClasses);const g=Array.isArray(h)?h:[h],d=a===o&&this.config.markers.menuMarker||a===n&&this.config.markers.deleteMarker||a===i&&this.config.markers.infoMarker,p=this.normalizeMarkerIndex(a,e.length,u),f=[...g];l<=0||null===p||c.has(p)||d||f.push("polygon-marker-faded");const y=new s.Marker(r,{icon:this.createDivIcon(f),draggable:this.config.modes.dragElbow,title:this.config.markers.coordsTitle?this.getLatLngInfoString(r):"",zIndexOffset:this.config.markers.markerIcon.zIndexOffset??this.config.markers.zIndexOffset});t.addLayer(y),this.markerFeatureGroupMap.set(y,t),y.on("add",()=>{const e=y.getElement();e&&(e.style.pointerEvents="auto")}),y.on("click",e=>{var t,r;this.isDraggingMarker&&(null==(r=null==(t=e.originalEvent)?void 0:t.stopPropagation)||r.call(t),s.DomEvent.stopPropagation(e))}),y.on("dragstart",()=>{const e=this.markerFeatureGroupMap.get(y);!e||this.isFeatureGroupInActiveLayer(e)?(this.saveHistoryState&&this.saveHistoryState("markerDrag"),this.isDraggingMarker=!0,this._activeMarker=y):y.dragging&&y.dragging.disable()}),y.on("dragend",e=>{const t=this.markerFeatureGroupMap.get(y);if(t&&!this.isFeatureGroupInActiveLayer(t))return this._activeMarker=null,void(this.isDraggingMarker=!1);this.modeManager.canPerformAction("markerDrag")&&t&&this.markerDragEnd(t),this._activeMarker=null,s.DomEvent.stopPropagation(e),setTimeout(()=>{this.isDraggingMarker=!1},10)});const m=y.getElement();if(m){const e=e=>{e.stopPropagation()},t=e=>{if(e.preventDefault(),e.stopPropagation(),y.fire("click"),this.isDraggingMarker&&!d){const e=this.markerFeatureGroupMap.get(y);this.modeManager.canPerformAction("markerDrag")&&e&&this.isFeatureGroupInActiveLayer(e)&&this.markerDragEnd(e)}this._activeMarker=null};m.addEventListener("touchstart",e,{passive:!0}),m.addEventListener("touchend",t),this.markerTouchListeners.set(y,{touchstart:e,touchend:t})}if(a===o||a===n||a===i){const e=y.getElement();e&&(e.style.zIndex="10000")}if(this.config.modes.dragElbow){const e=e=>()=>{this.modeManager.canPerformAction("markerDrag")&&this.isFeatureGroupInActiveLayer(e)&&this.markerDrag(e)};y.on("drag",e(t))}if(a===o&&this.config.markers.menuMarker&&(y.options.zIndexOffset=this.config.markers.markerMenuIcon.zIndexOffset??this.config.markers.zIndexOffset,y.on("click",()=>{if(!this.isFeatureGroupInActiveLayer(t))return;const r=this.getPolygonGeoJSONFromFeatureGroup(t),n=ci.getCenterOfPolygonByIndexWithOffsetFromCenterOfMass(r,o);this.generateMenuMarkerPopup(e,t).setLatLng(n).openOn(this.map)}),y.on("popupopen",e=>{const t=e.popup.getElement();if(!t)return;setTimeout(()=>{const e=this.map.getContainer(),r=t.getBoundingClientRect(),o=e.getBoundingClientRect();let n=0,i=0;r.left<o.left?n=o.left-r.left:r.right>o.right&&(n=o.right-r.right),r.top<o.top?i=o.top-r.top:r.bottom>o.bottom&&(i=o.bottom-r.bottom),0===n&&0===i||(t.style.transform=`translate(${n}px, ${i}px)`)},0);const r=this.map.getContainer();r&&(r.style.touchAction="manipulation")}),y.on("popupclose",()=>{const e=this.map.getContainer();e&&(e.style.touchAction="")})),a===i&&this.config.markers.infoMarker){const e=this.getPolygonGeoJSONFromFeatureGroup(t),r=this.turfHelper.getPolygonArea(e),o=this.getTotalPolygonPerimeter(e);y.options.zIndexOffset=this.config.markers.markerInfoIcon.zIndexOffset??this.config.markers.zIndexOffset,y.on("click",()=>{if(!this.isFeatureGroupInActiveLayer(t))return;const n=this.generateInfoMarkerPopup(r,o),a=ci.getCenterOfPolygonByIndexWithOffsetFromCenterOfMass(e,i);n.setLatLng(a).openOn(this.map)}),y.on("popupopen",e=>{const t=e.popup.getElement();if(!t)return;setTimeout(()=>{const e=this.map.getContainer().getBoundingClientRect(),r=t.getBoundingClientRect();r.left<e.left?t.style.transform=`translateX(${e.left-r.left}px)`:r.right>e.right&&(t.style.transform=`translateX(${e.right-r.right}px)`)},0);const r=this.map.getContainer();r&&(r.style.touchAction="manipulation")}),y.on("popupclose",()=>{const e=this.map.getContainer();e&&(e.style.touchAction="")})}y.on("mousedown",e=>{this.modeManager.isInOffMode()||(s.DomEvent.stopPropagation(e),this.map.fire("mousedown",e)),this._activeMarker=y}),y.on("click",e=>{var r,o;if(this.isFeatureGroupInActiveLayer(t)&&this.modeManager.isInOffMode())if(this.isEdgeDeletionModifierKeyPressed(e.originalEvent)){const r=t.getLayers().find(e=>e instanceof s.Polygon);r&&this.elbowClicked(e,r,y.getLatLng())}else if(a===n&&this.config.markers.deleteMarker){if(this.shouldSuppressDeleteMarkerClick()){const t=e.originalEvent;return null==(r=null==t?void 0:t.preventDefault)||r.call(t),void(null==(o=null==t?void 0:t.stopPropagation)||o.call(t))}this.map.closePopup(),this.saveHistoryState&&this.saveHistoryState("deletePolygon"),this.cleanupFeatureGroup(t),this.removeFeatureGroup(t),this.polygonInformation.createPolygonInformationStorage(this.getFeatureGroups()),this.eventManager.emit("polydraw:polygon:deleted",void 0)}}),y.on("mouseover",()=>{this.isFeatureGroupInActiveLayer(t)&&this.onMarkerHoverForEdgeDeletion(y,!0)}),y.on("mouseout",()=>{this.onMarkerHoverForEdgeDeletion(y,!1)})});const h=this.map.getContainer();h&&(h.style.touchAction="manipulation")}addHoleMarkers(e,t){var r,o,n;this.registerPolygonLayerMappings(t);const i=(null==(r=this.config.markers.holeMarkers)?void 0:r.menuMarker)??!1,a=(null==(o=this.config.markers.holeMarkers)?void 0:o.deleteMarker)??!1,l=(null==(n=this.config.markers.holeMarkers)?void 0:n.infoMarker)??!1;let c=this.getMarkerIndex(e,this.config.markers.markerMenuIcon.position),u=this.getMarkerIndex(e,this.config.markers.markerDeleteIcon.position),h=this.getMarkerIndex(e,this.config.markers.markerInfoIcon.position);const g=this.ensureMarkerSeparation(e.length,{menu:{index:c,enabled:i},delete:{index:u,enabled:a},info:{index:h,enabled:l}});c=g.menu,u=g.delete,h=g.info,e.forEach((r,o)=>{let n=this.config.markers.holeIcon.styleClasses;o===c&&i&&(n=this.config.markers.markerMenuIcon.styleClasses),o===u&&a&&(n=this.config.markers.markerDeleteIcon.styleClasses),o===h&&l&&(n=this.config.markers.markerInfoIcon.styleClasses);const g=Array.isArray(n)?n:[n],d=o===c&&i||o===u&&a||o===h&&l,p=new s.Marker(r,{icon:this.createDivIcon(g),draggable:this.config.modes.dragElbow,title:this.config.markers.coordsTitle?this.getLatLngInfoString(r):"",zIndexOffset:this.config.markers.holeIcon.zIndexOffset??this.config.markers.zIndexOffset});t.addLayer(p),this.markerFeatureGroupMap.set(p,t),p.on("add",()=>{const e=p.getElement();e&&(e.style.pointerEvents="auto")}),p.on("click",e=>{var t,r;this.isDraggingMarker&&(null==(r=null==(t=e.originalEvent)?void 0:t.stopPropagation)||r.call(t),s.DomEvent.stopPropagation(e))}),p.on("dragstart",()=>{const e=this.markerFeatureGroupMap.get(p);!e||this.isFeatureGroupInActiveLayer(e)?(this.saveHistoryState&&this.saveHistoryState("markerDrag"),this.isDraggingMarker=!0,this._activeMarker=p):p.dragging&&p.dragging.disable()}),p.on("dragend",e=>{const t=this.markerFeatureGroupMap.get(p);if(t&&!this.isFeatureGroupInActiveLayer(t))return this._activeMarker=null,void(this.isDraggingMarker=!1);this.modeManager.canPerformAction("markerDrag")&&t&&this.markerDragEnd(t),this._activeMarker=null,s.DomEvent.stopPropagation(e),setTimeout(()=>{this.isDraggingMarker=!1},10)});const f=p.getElement();if(f){const e=e=>{e.stopPropagation()},t=e=>{if(e.preventDefault(),e.stopPropagation(),p.fire("click"),this.isDraggingMarker&&!d){const e=this.markerFeatureGroupMap.get(p);this.modeManager.canPerformAction("markerDrag")&&e&&this.isFeatureGroupInActiveLayer(e)&&this.markerDragEnd(e)}this._activeMarker=null};f.addEventListener("touchstart",e,{passive:!0}),f.addEventListener("touchend",t),this.markerTouchListeners.set(p,{touchstart:e,touchend:t})}if(o===c||o===u||o===h){const e=p.getElement();e&&(e.style.zIndex="10000")}if(this.config.modes.dragElbow){const e=e=>()=>{this.modeManager.canPerformAction("markerDrag")&&this.isFeatureGroupInActiveLayer(e)&&this.markerDrag(e)};p.on("drag",e(t))}if(o===c&&i&&(p.options.zIndexOffset=this.config.markers.markerMenuIcon.zIndexOffset??this.config.markers.zIndexOffset,p.on("click",()=>{const r=e.map(e=>[e.lng,e.lat]);r.push(r[0]);const o={type:"Feature",properties:{},geometry:{type:"Polygon",coordinates:[r]}},n=ci.getCenterOfMass(o);this.generateMenuMarkerPopup(e,t).setLatLng(n).openOn(this.map)}),p.on("popupopen",e=>{const t=e.popup.getElement();if(!t)return;setTimeout(()=>{const e=this.map.getContainer().getBoundingClientRect(),r=t.getBoundingClientRect();r.left<e.left?t.style.transform=`translateX(${e.left-r.left}px)`:r.right>e.right&&(t.style.transform=`translateX(${e.right-r.right}px)`)},0);const r=this.map.getContainer();r&&(r.style.touchAction="manipulation")}),p.on("popupclose",()=>{const e=this.map.getContainer();e&&(e.style.touchAction="")})),o===h&&l){const o=e.map(e=>[e.lng,e.lat]);o.push(o[0]);const n={type:"Feature",properties:{},geometry:{type:"Polygon",coordinates:[o]}},i=this.turfHelper.getPolygonArea(n),a=1e3*this.turfHelper.getPolygonPerimeter(n);p.options.zIndexOffset=this.config.markers.markerInfoIcon.zIndexOffset??this.config.markers.zIndexOffset,p.on("click",()=>{if(!this.isFeatureGroupInActiveLayer(t))return;this.generateInfoMarkerPopup(i,a).setLatLng(r).openOn(this.map)})}p.on("mousedown",e=>{this.modeManager.isInOffMode()||(s.DomEvent.stopPropagation(e),this.map.fire("mousedown",e)),this._activeMarker=p}),p.on("click",e=>{if(this.isFeatureGroupInActiveLayer(t)&&this.modeManager.isInOffMode())if(this.isEdgeDeletionModifierKeyPressed(e.originalEvent)){const r=t.getLayers().find(e=>e instanceof s.Polygon);r&&this.elbowClicked(e,r,p.getLatLng())}else if(o===u&&a){this.map.closePopup();const e=t.getLayers().find(e=>e instanceof s.Polygon);if(e){const r=e.getLatLngs();let o=[];if(Array.isArray(r)&&r.length>0)if(Array.isArray(r[0])){const e=r[0];o=Array.isArray(e)&&Array.isArray(e[0])?r[0]:r}else o=[r];const n=p.getLatLng();let i=-1;for(let e=1;e<o.length;e++)if(o[e].some(e=>e.lat===n.lat&&e.lng===n.lng)){i=e;break}if(i>0){const e=o.filter((e,t)=>t!==i).map(e=>{const t=e.map(e=>[e.lng,e.lat]);if(t.length>0){const e=t[0],r=t[t.length-1];e[0]===r[0]&&e[1]===r[1]||t.push([e[0],e[1]])}return t}),{level:r,original:n}=this.getOptimizationMetadataFromFeatureGroup(t),a=this.getFeatureMetadataState(t),s=this.turfHelper.getMultiPolygon([e]);this.cleanupFeatureGroup(t),this.removeFeatureGroup(t),this.emitPolygonUpdated({operation:"removeHole",polygon:s,optimizationLevel:r,originalOptimizationLevel:n,featureId:a.featureId,featureMetadata:a.metadata,sourceFeatureIds:a.sourceFeatureIds,featureInteractionOverride:a.interactionOverride,featureStyleOverrides:a.styleOverrides,featureCreatedAt:a.createdAt})}}}}),p.on("mouseover",()=>{this.isFeatureGroupInActiveLayer(t)&&this.onMarkerHoverForEdgeDeletion(p,!0)}),p.on("mouseout",()=>{this.onMarkerHoverForEdgeDeletion(p,!1)})})}addEdgeClickListeners(e,t){const r=e.getLatLngs();let o;if(Array.isArray(r)&&r.length>0){if(Array.isArray(r[0]))if(Array.isArray(r[0][0])&&r[0][0].length>0){r[0][0][0];o=r[0]}else o=r[0][0]&&"object"==typeof r[0][0]&&"lat"in r[0][0]?r:r[0];else o=(r[0]&&"object"==typeof r[0]&&r[0],[r]);o.forEach((r,o)=>{for(let n=0;n<r.length;n++){const i=r[n],a=r[(n+1)%r.length];if(i.lat===a.lat&&i.lng===a.lng)continue;const s=oi.createPolyline([i,a],{color:"transparent",weight:10,opacity:0,interactive:!0});s._polydrawEdgeInfo={ringIndex:o,edgeIndex:n,startPoint:i,endPoint:a,parentPolygon:e,parentFeatureGroup:t},s.on("click",e=>{this.onEdgeClick(e,s)}),s.on("mouseover",()=>{this.highlightEdgeOnHover(s,!0)}),s.on("mouseout",()=>{this.highlightEdgeOnHover(s,!1)}),t.addLayer(s)}})}}isPolygonDragModeActive(){const e=this.modeManager.getCurrentMode();return e===c.Off||e===c.Clone}isPolygonDragActive(){return!!(this.currentDragPolygon&&this.currentDragPolygon._polydrawDragData&&this.currentDragPolygon._polydrawDragData.isDragging)}isPolygonInActiveLayer(e){if(!this.layerManager)return!0;const t=this.polygonFeatureGroupMap.get(e);if(t)return this.layerManager.isInActiveLayer(t)&&this.layerManager.isFeatureGroupEditable(t);const r=this.findFeatureGroupForPolygon(e);return!r||(this.polygonFeatureGroupMap.set(e,r),this.layerManager.isInActiveLayer(r)&&this.layerManager.isFeatureGroupEditable(r))}isFeatureGroupInActiveLayer(e){return!this.layerManager||this.layerManager.isInActiveLayer(e)&&this.layerManager.isFeatureGroupEditable(e)}enablePolygonDragging(e,t){if(this.config.modes.dragPolygons||this.config.tools.clone){if(e._polydrawOriginalLatLngs=t,e._polydrawDragData={isDragging:!1,startPosition:null,startLatLngs:null,originalOpacity:e.options.fillOpacity},e.on("mousedown",t=>{if(this.transformModeActive)return;if(!this.isPolygonInActiveLayer(e))return;if(!this.isPolygonDragModeActive())return s.DomEvent.stopPropagation(t),void this.map.fire("mousedown",t);if(!this.modeManager.canPerformAction("polygonDrag"))return;s.DomEvent.stopPropagation(t.originalEvent),s.DomEvent.preventDefault(t.originalEvent);const r=this.modeManager.getCurrentMode()===c.Clone,o=!r&&this.detectDragSubtractModifierKey(t.originalEvent);this.currentDragIsClone=r,this.currentModifierDragMode=o,this.isModifierKeyHeld=o,this.saveHistoryState&&this.saveHistoryState(r?"polygonClone":"polygonDrag"),e._polydrawDragData.isDragging=!0,e._polydrawDragData.startPosition=t.latlng,e._polydrawDragData.startLatLngs=e.getLatLngs(),e.setStyle({fillOpacity:this.config.interaction.drag.opacity}),r?this.showCloneGhost(e._polydrawDragData.startLatLngs):this.clearCloneGhost(),this.map.dragging&&this.map.dragging.disable(),this.setSubtractVisualMode(e,o),this.setMarkerVisibility(e,!1);try{this.map.getContainer().style.cursor=this.config.interaction.drag.dragCursor||"move"}catch{}this.attachDragDocumentListeners(),this.attachDragCancelHandlers(),this.currentDragPolygon=e}),e.on("pointerdown",t=>{const r=t;if(this.transformModeActive)return;if(!this.isPolygonInActiveLayer(e))return;if(!this.isPolygonDragModeActive()){const e=r.originalEvent??r;return s.DomEvent.stopPropagation(e),void this.map.fire("pointerdown",r)}if(!this.modeManager.canPerformAction("polygonDrag"))return;const o=r.originalEvent??r;s.DomEvent.stopPropagation(o),s.DomEvent.preventDefault(o);const n=this.modeManager.getCurrentMode()===c.Clone,i=!n&&this.detectDragSubtractModifierKey(o);this.currentDragIsClone=n,this.currentModifierDragMode=i,this.isModifierKeyHeld=i,this.saveHistoryState&&this.saveHistoryState(n?"polygonClone":"polygonDrag"),e._polydrawDragData.isDragging=!0,e._polydrawDragData.startPosition=r.latlng,e._polydrawDragData.startLatLngs=e.getLatLngs(),e.setStyle({fillOpacity:this.config.interaction.drag.opacity}),n?this.showCloneGhost(e._polydrawDragData.startLatLngs):this.clearCloneGhost(),this.map.dragging&&this.map.dragging.disable(),this.setSubtractVisualMode(e,i),this.setMarkerVisibility(e,!1);try{this.map.getContainer().style.cursor=this.config.interaction.drag.dragCursor||"move"}catch{}this.attachDragDocumentListeners(),this.attachDragCancelHandlers(),this.currentDragPolygon=e}),ri.isV1()){const t=t=>{if(this.transformModeActive)return;if(!this.isPolygonInActiveLayer(e))return;if(!this.isPolygonDragModeActive())return;if(!this.modeManager.canPerformAction("polygonDrag"))return;t.stopPropagation(),t.preventDefault();const r=bi.extractCoordinates(t,this.map);if(!r)return;const o=this.modeManager.getCurrentMode()===c.Clone;this.currentDragIsClone=o,this.currentModifierDragMode=!1,this.isModifierKeyHeld=!1,this.saveHistoryState&&this.saveHistoryState(o?"polygonClone":"polygonDrag"),e._polydrawDragData.isDragging=!0,e._polydrawDragData.startPosition=r,e._polydrawDragData.startLatLngs=e.getLatLngs(),e.setStyle({fillOpacity:this.config.interaction.drag.opacity}),o?this.showCloneGhost(e._polydrawDragData.startLatLngs):this.clearCloneGhost(),this.map.dragging&&this.map.dragging.disable(),this.setSubtractVisualMode(e,!1),this.setMarkerVisibility(e,!1);try{this.map.getContainer().style.cursor=this.config.interaction.drag.dragCursor||"move"}catch{}this.attachDragTouchListeners(),this.attachDragDocumentListeners(),this.attachDragCancelHandlers(),this.currentDragPolygon=e};this.polygonTouchStartListeners.set(e,t);const r=()=>{const r=e._path;r&&r.addEventListener("touchstart",t,{passive:!1})};e._path?r():e.once("add",r)}e.on("mouseover",()=>{if(this.isPolygonInActiveLayer(e)&&(!e._polydrawDragData||!e._polydrawDragData.isDragging))try{this.map.getContainer().style.cursor=this.config.interaction.drag.hoverCursor||"grab"}catch{}}),e.on("mouseout",()=>{if(!e._polydrawDragData||!e._polydrawDragData.isDragging)try{this.map.getContainer().style.cursor=""}catch{}})}}updateMarkerDraggableState(){const e=this.modeManager.canPerformAction("markerDrag");this.getFeatureGroups().forEach(t=>{const r=this.isFeatureGroupInActiveLayer(t),o=e&&r;t.eachLayer(e=>{if(e instanceof s.Marker){const t=e;try{t.options.draggable=o,t.dragging&&(o?t.dragging.enable():t.dragging.disable())}catch{}}})})}updateAllMarkersForEdgeDeletion(e){this.getFeatureGroups().forEach(t=>{t.eachLayer(t=>{t instanceof s.Marker&&this.updateMarkerForEdgeDeletion(t,e)})})}updateMarkerForEdgeDeletion(e,t){const r=e.getElement();r&&(t?(r.addEventListener("mouseenter",this.onMarkerHoverForEdgeDeletionEvent),r.addEventListener("mouseleave",this.onMarkerLeaveForEdgeDeletionEvent),this.markerEdgeDeletionListeners.set(e,{mouseenter:this.onMarkerHoverForEdgeDeletionEvent,mouseleave:this.onMarkerLeaveForEdgeDeletionEvent})):(r.removeEventListener("mouseenter",this.onMarkerHoverForEdgeDeletionEvent),r.removeEventListener("mouseleave",this.onMarkerLeaveForEdgeDeletionEvent),r.style.backgroundColor="",r.style.borderColor="",this.markerEdgeDeletionListeners.delete(e)))}setModifierKeyHeld(e){this.isModifierKeyHeld=e}cleanupMarker(e){const t=e.getElement(),r=this.markerModifierHandlers.get(e);r&&(document.removeEventListener("keydown",r),document.removeEventListener("keyup",r),t&&t.removeEventListener("mousemove",r),this.markerModifierHandlers.delete(e));const o=this.markerTouchListeners.get(e);o&&(t&&(t.removeEventListener("touchstart",o.touchstart),t.removeEventListener("touchend",o.touchend)),this.markerTouchListeners.delete(e));const n=this.markerEdgeDeletionListeners.get(e);n&&(t&&(t.removeEventListener("mouseenter",n.mouseenter),t.removeEventListener("mouseleave",n.mouseleave)),this.markerEdgeDeletionListeners.delete(e)),this.markerFeatureGroupMap.delete(e)}cleanupFeatureGroup(e){e.eachLayer(e=>{e instanceof s.Marker?this.cleanupMarker(e):e instanceof s.Polygon&&(this.detachPolygonTouchStart(e),this.polygonFeatureGroupMap.delete(e))}),this.destroyTransformController(e)}destroyTransformController(e){const t=this.transformControllers.get(e);t&&(t.destroy(),this.transformControllers.delete(e),this.transformModeActive=!1)}onEdgeClick(e,t){if(!this.config.modes.attachElbow)return;if(!this.modeManager.isInOffMode())return;const r=t._polydrawEdgeInfo;if(!r)return;if(r.parentFeatureGroup&&!this.isFeatureGroupInActiveLayer(r.parentFeatureGroup))return;const o=e.latlng,n=r.parentPolygon,i=r.parentFeatureGroup;if(n&&i)try{if("function"!=typeof n.toGeoJSON)return;const e=n.toGeoJSON();if("MultiPolygon"===e.geometry.type||"Polygon"===e.geometry.type){const t=this.turfHelper.injectPointToPolygon(e,[o.lng,o.lat],r.ringIndex);if(t){const e=n,r=e._polydrawOptimizationLevel||0,o=e._polydrawOptimizationOriginalLevel||r,a=this.getFeatureMetadataState(i);this.cleanupFeatureGroup(i),this.removeFeatureGroup(i),this.emitPolygonUpdated({operation:"addVertex",polygon:t,optimizationLevel:r,originalOptimizationLevel:o,featureId:a.featureId,featureMetadata:a.metadata,sourceFeatureIds:a.sourceFeatureIds,featureInteractionOverride:a.interactionOverride,featureStyleOverrides:a.styleOverrides,featureCreatedAt:a.createdAt})}}}catch{}s.DomEvent.stopPropagation(e)}highlightEdgeOnHover(e,t){t?e.setStyle({color:this.config.styles.ui.edgeHover.color,weight:4,opacity:1}):e.setStyle({color:"transparent",weight:10,opacity:0})}deriveImportantMarkerIndices(e,t){const r=new Set;if(!e||0===e.length)return r;const o=Math.min(Math.max(t.optimizationLevel??0,0),10),n=e.length>2&&this.latLngEquals(e[0],e[e.length-1]),i=n?e.slice(0,-1):[...e],a=i.length,s=t=>{if(null==t||t<0)return;let o=t;n&&t===e.length-1&&(o=0),o>=a&&(o=a>0?o%a:0),o>=0&&o<a&&r.add(o)};if(s(0),s(t.menuIndex),s(t.deleteIndex),s(t.infoIndex),0===a||o<=0||a<=3){for(let e=0;e<a;e++)r.add(e);return r}const l=this.getToleranceForOptimizationLevel(o);let c=l>0?this.turfHelper.simplifyLatLngRing(i,l,!0):[...i];if(c.length>1&&this.latLngEquals(c[0],c[c.length-1])&&(c=c.slice(0,-1)),!c||0===c.length){for(let e=0;e<a;e++)r.add(e);return r}if(c.forEach(e=>{const t=this.findClosestVertexIndex(e,i);null!==t&&r.add(t)}),0===r.size)for(let u=0;u<a;u++)r.add(u);return r}normalizeMarkerIndex(e,t,r){if(null==e||e<0)return null;if(r){const r=Math.max(1,t-1);return e===t-1?0:e>=r?e%r:e}return e>=t?t>0?t-1:null:e}latLngEquals(e,t){return!(!e||!t)&&(Math.abs(e.lat-t.lat)<1e-9&&Math.abs(e.lng-t.lng)<1e-9)}isLatLngLiteral(e){return!!e&&"object"==typeof e&&"lat"in e&&"lng"in e&&"number"==typeof e.lat&&"number"==typeof e.lng}getOrderedMarkers(e){const t=[];return e.eachLayer(e=>{e instanceof s.Marker&&t.push(e)}),t.sort((e,t)=>oi.util.stamp(e)-oi.util.stamp(t))}countLatLngNodes(e){return Array.isArray(e)?0===e.length?0:this.isLatLngLiteral(e[0])?e.length:e.reduce((e,t)=>e+this.countLatLngNodes(t),0):0}rebuildLatLngStructure(e,t,r){if(!Array.isArray(e))return e;if(e.length>0&&this.isLatLngLiteral(e[0])){const o=e,n=o.length>1&&this.latLngEquals(o[0],o[o.length-1]),i=o.map((e,n)=>{const i=t[r.value]??o[n];return r.value+=1,oi.createLatLng(i.lat,i.lng)});return n&&i.length>1&&(i[i.length-1]=i[0]),i}return e.map(e=>this.rebuildLatLngStructure(e,t,r))}getOptimizationMetadataFromFeatureGroup(e){let t=0,r=0;return e.eachLayer(e=>{if(e instanceof s.Polygon){const o=e;"number"==typeof o._polydrawOptimizationLevel&&(t=o._polydrawOptimizationLevel||0),"number"==typeof o._polydrawOptimizationOriginalLevel&&(r=o._polydrawOptimizationOriginalLevel||0)}}),!r&&t>0&&(r=t),{level:t,original:r}}getFeatureMetadataState(e){if(!e)return{};const t=e._polydrawMetadata,r=(null==t?void 0:t.createdAt)instanceof Date&&!Number.isNaN(t.createdAt.getTime())?t.createdAt.toISOString():void 0;return{featureId:null==t?void 0:t.id,metadata:(null==t?void 0:t.metadata)?{...t.metadata}:void 0,sourceFeatureIds:Array.isArray(null==t?void 0:t.sourceFeatureIds)?[...t.sourceFeatureIds]:(null==t?void 0:t.id)?[t.id]:void 0,interactionOverride:null==t?void 0:t.interactionOverride,styleOverrides:(null==t?void 0:t.styleOverrides)?{...t.styleOverrides}:void 0,createdAt:r}}getOptimizationMetadataFromPolygonLayer(e){if(!e)return{level:0,original:0};const t=e,r=t._polydrawOptimizationLevel||0;return{level:r,original:t._polydrawOptimizationOriginalLevel||(r>0?r:0)}}getDistanceMeters(e,t){try{const r=oi.createLatLng(e.lat,e.lng),o=oi.createLatLng(t.lat,t.lng);if("function"==typeof r.distanceTo)return r.distanceTo(o)}catch{}const r=e=>e*Math.PI/180,o=r(t.lat-e.lat),n=r(t.lng-e.lng),i=r(e.lat),a=r(t.lat),s=Math.sin(o/2)*Math.sin(o/2)+Math.sin(n/2)*Math.sin(n/2)*Math.cos(i)*Math.cos(a);return 6371e3*(2*Math.atan2(Math.sqrt(s),Math.sqrt(1-s)))}findClosestVertexIndex(e,t){if(!t||0===t.length)return null;let r=0,o=Number.POSITIVE_INFINITY;for(let n=0;n<t.length;n++){const i=this.getDistanceMeters(e,t[n]);if(i<o&&(o=i,r=n,0===i))break}return r}getToleranceForOptimizationLevel(e){const t=Math.min(Math.max(e,0),10)/10,r=this.config.markers.visualOptimization??{},o=Math.max(r.toleranceMin??5e-6,0),n=Math.max(r.toleranceMax??.005,o),i=r.curve??1.35;return o+(n-o)*Math.pow(t,i)}elbowClicked(e,t,r){if(!this.config.modes.edgeDeletion)return;if(!this.isEdgeDeletionModifierKeyPressed(e.originalEvent))return;const o=r??e.latlng,n=t.getLatLngs();let i=[];if(!(Array.isArray(n)&&n.length>0))return;if(Array.isArray(n[0])){const e=n[0];i=Array.isArray(e)&&Array.isArray(e[0])?n[0]:n}else i=[n];let a=-1,s=-1;for(let f=0;f<i.length;f++){const e=i[f];for(let t=0;t<e.length;t++){const r=e[t];if(r.lat===o.lat&&r.lng===o.lng){a=f,s=t;break}}if(-1!==a)break}if(-1===a||-1===s)return;if(i[a].length<=this.config.interaction.edgeDeletion.minVertices)return;const l=i.map((e,t)=>{if(t!==a)return e.slice();const r=e.slice();return r.splice(s,1),r}).map(e=>{const t=e.map(e=>[e.lng,e.lat]);if(t.length>0){const e=t[0],r=t[t.length-1];e[0]===r[0]&&e[1]===r[1]||t.push([e[0],e[1]])}return t});let c=null;for(const f of this.getFeatureGroups()){let e=!1;if(f.eachLayer(r=>{r===t&&(e=!0)}),e){c=f;break}}const u=c?this.getOptimizationMetadataFromFeatureGroup(c):this.getOptimizationMetadataFromPolygonLayer(t),h=this.getFeatureMetadataState(c??void 0),{level:g,original:d}=u;c&&this.removeFeatureGroup(c);const p=this.turfHelper.getMultiPolygon([l]);this.emitPolygonUpdated({operation:"removeVertex",polygon:p,optimizationLevel:g,originalOptimizationLevel:d,featureId:h.featureId,featureMetadata:h.metadata,sourceFeatureIds:h.sourceFeatureIds,featureInteractionOverride:h.interactionOverride,featureStyleOverrides:h.styleOverrides,featureCreatedAt:h.createdAt})}markerDrag(e){if(!this._activeMarker)return void(Wn()||console.warn("No active marker set for dragging."));const t=e.getLayers().find(e=>e instanceof s.Polygon);if(!t)return void(Wn()||console.warn("No polygon found in feature group for marker drag."));const r=this.getOrderedMarkers(e);if(0===r.length)return;const o=r.map(e=>e.getLatLng()),n=this.countLatLngNodes(t.getLatLngs());if(o.length<n)return void(Wn()||console.warn("Not enough markers to rebuild polygon during drag. Expected:",n,"got:",o.length));const i=this.rebuildLatLngStructure(t.getLatLngs(),o,{value:0});t.setLatLngs(i)}async markerDragEnd(e){var t;this.polygonInformation.deletePolygonInformationStorage();const r=e.toGeoJSON();if(!r.features||0===r.features.length)return;const{level:o,original:n}=this.getOptimizationMetadataFromFeatureGroup(e),i=this.getFeatureMetadataState(e),a=null==(t=this.layerManager)?void 0:t.getLayerForFeatureGroup(e);this.cleanupFeatureGroup(e),this.removeFeatureGroup(e);const s=(e,t,r)=>{const o=this.turfHelper.removeDuplicateVertices(e),n=[];if(!this.config.kinks)try{const e=this.turfHelper.getKinks(o);e&&e.length>0&&n.push(...e)}catch{}0===n.length&&("MultiPolygon"===o.geometry.type?o.geometry.coordinates.forEach(e=>n.push(this.turfHelper.getMultiPolygon([e]))):n.push(o)),n.forEach(e=>{this.emitPolygonUpdated({operation:"markerDrag",polygon:e,allowMerge:t,optimizationLevel:r.optimizationLevel,originalOptimizationLevel:r.originalOptimizationLevel,featureId:i.featureId,featureMetadata:i.metadata,sourceFeatureIds:i.sourceFeatureIds,featureInteractionOverride:i.interactionOverride,featureStyleOverrides:i.styleOverrides,targetLayerId:a,featureCreatedAt:i.createdAt})})};if("MultiPolygon"===r.features[0].geometry.type)for(const l of r.features[0].geometry.coordinates){s(this.turfHelper.getMultiPolygon([l]),!0,{optimizationLevel:o,originalOptimizationLevel:n})}else{s(this.turfHelper.getMultiPolygon([r.features[0].geometry.coordinates]),!0,{optimizationLevel:o,originalOptimizationLevel:n})}this.polygonInformation.createPolygonInformationStorage(this.getFeatureGroups())}attachDragDocumentListeners(){if(this.detachDragDocumentListeners(),this.dragUsesPointerEvents=bi.shouldUsePointerEvents(),this._boundDragMoveListener=this.onDragDocumentMove,this._boundDragEndListener=this.onDragDocumentEnd,this.dragUsesPointerEvents)return document.addEventListener("pointermove",this._boundDragMoveListener),void document.addEventListener("pointerup",this._boundDragEndListener);document.addEventListener("mousemove",this._boundDragMoveListener),document.addEventListener("mouseup",this._boundDragEndListener)}detachDragDocumentListeners(){this._boundDragMoveListener&&(this.dragUsesPointerEvents?document.removeEventListener("pointermove",this._boundDragMoveListener):document.removeEventListener("mousemove",this._boundDragMoveListener),this._boundDragMoveListener=null),this._boundDragEndListener&&(this.dragUsesPointerEvents?document.removeEventListener("pointerup",this._boundDragEndListener):document.removeEventListener("mouseup",this._boundDragEndListener),this._boundDragEndListener=null),this.dragUsesPointerEvents=!1}attachDragTouchListeners(){this.detachDragTouchListeners(),this._boundDragTouchMove=this.onDragTouchMove,this._boundDragTouchEnd=this.onDragTouchEnd;const e=this.map.getContainer();e.addEventListener("touchmove",this._boundDragTouchMove,{passive:!1}),e.addEventListener("touchend",this._boundDragTouchEnd,{passive:!1})}detachDragTouchListeners(){const e=this.map.getContainer();this._boundDragTouchMove&&(e.removeEventListener("touchmove",this._boundDragTouchMove),this._boundDragTouchMove=null),this._boundDragTouchEnd&&(e.removeEventListener("touchend",this._boundDragTouchEnd),this._boundDragTouchEnd=null)}detachPolygonTouchStart(e){const t=this.polygonTouchStartListeners.get(e);if(!t)return;const r=e._path;r&&r.removeEventListener("touchstart",t),this.polygonTouchStartListeners.delete(e)}attachDragCancelHandlers(){this.dragCancelHandlersAttached||(this.dragCancelHandlersAttached=!0,document.addEventListener("keydown",this.onPolygonDragKeyDown),this.map.on("pointercancel",this.onPolygonDragCancel,this),this.map.on("touchcancel",this.onPolygonDragCancel,this))}detachDragCancelHandlers(){this.dragCancelHandlersAttached&&(this.dragCancelHandlersAttached=!1,document.removeEventListener("keydown",this.onPolygonDragKeyDown),this.map.off("pointercancel",this.onPolygonDragCancel,this),this.map.off("touchcancel",this.onPolygonDragCancel,this))}cancelActivePolygonDrag(){if(!this.currentDragPolygon||!this.currentDragPolygon._polydrawDragData)return this.clearCloneGhost(),void this.detachDragDocumentListeners();const e=this.currentDragPolygon,t=e._polydrawDragData;if(!t)return this.clearCloneGhost(),void this.detachDragDocumentListeners();if(!t.isDragging)return this.clearCloneGhost(),void this.detachDragDocumentListeners();t.isDragging=!1,this.map.dragging&&this.map.dragging.enable(),t.startLatLngs&&e.setLatLngs(t.startLatLngs),e._polydrawOriginalMarkerPositions&&(e._polydrawOriginalMarkerPositions.forEach((e,t)=>{t.setLatLng(e)}),e._polydrawOriginalMarkerPositions.clear(),delete e._polydrawOriginalMarkerPositions),e._polydrawOriginalHoleLinePositions&&(e._polydrawOriginalHoleLinePositions.forEach((e,t)=>{t.setLatLngs(e)}),e._polydrawOriginalHoleLinePositions.clear(),delete e._polydrawOriginalHoleLinePositions),e._polydrawCurrentDragSession&&delete e._polydrawCurrentDragSession,null!=t.originalOpacity&&e.setStyle({fillOpacity:t.originalOpacity}),this.setSubtractVisualMode(e,!1),this.setMarkerVisibility(e,!0);try{this.map.getContainer().style.cursor=""}catch{}this.clearCloneGhost(),this.detachDragTouchListeners(),this.detachDragDocumentListeners(),this.detachDragCancelHandlers(),this.currentDragIsClone=!1,this.currentModifierDragMode=!1,this.isModifierKeyHeld=!1,this.currentDragPolygon=null}offsetPolygonCoordinates(e,t,r){return e?Array.isArray(e[0])?e.map(e=>this.offsetPolygonCoordinates(e,t,r)):e.map(e=>oi.createLatLng(e.lat+t,e.lng+r)):e}updateMarkersAndHoleLinesDuringDrag(e,t,r){try{let o=null;for(const t of this.getFeatureGroups()){let r=!1;if(t.eachLayer(t=>{t===e&&(r=!0)}),r){o=t;break}}if(!o)return;const n="_polydrawDragSession_"+Date.now()+"_"+oi.util.stamp(e);e._polydrawCurrentDragSession||(e._polydrawCurrentDragSession=n,e._polydrawOriginalMarkerPositions=new Map,e._polydrawOriginalHoleLinePositions=new Map,o.eachLayer(t=>{if(t instanceof s.Marker)e._polydrawOriginalMarkerPositions.set(t,t.getLatLng());else if(t instanceof s.Polyline&&!(t instanceof s.Polygon)){const r=t.getLatLngs();e._polydrawOriginalHoleLinePositions.set(t,r)}})),o.eachLayer(o=>{if(o instanceof s.Marker){const n=e._polydrawOriginalMarkerPositions.get(o);if(n){const e={lat:n.lat+t,lng:n.lng+r};o.setLatLng(e)}}else if(o instanceof s.Polyline&&!(o instanceof s.Polygon)){const n=e._polydrawOriginalHoleLinePositions.get(o);if(n){let e;e=Array.isArray(n[0])?n.map(e=>e.map(e=>oi.createLatLng(e.lat+t,e.lng+r))):n.map(e=>oi.createLatLng(e.lat+t,e.lng+r)),o.setLatLngs(e)}}})}catch(o){console.warn("Error updating markers during drag:",o)}}async updatePolygonAfterDrag(e){try{let t=null;for(const s of this.getFeatureGroups())if(s.eachLayer(r=>{r===e&&(t=s)}),t)break;if(!t)return;const r=e.toGeoJSON();if(this.isModifierDragActive())return this.performModifierSubtract(r,t),this.currentModifierDragMode=!1,void(this.isModifierKeyHeld=!1);const{level:o,original:n}=this.getOptimizationMetadataFromFeatureGroup(t),i=this.getFeatureMetadataState(t);this.cleanupFeatureGroup(t),this.removeFeatureGroup(t);const a=this.turfHelper.getTurfPolygon(r);this.emitPolygonUpdated({operation:"polygonDrag",polygon:a,allowMerge:!0,optimizationLevel:o,originalOptimizationLevel:n,featureId:i.featureId,featureMetadata:i.metadata,sourceFeatureIds:i.sourceFeatureIds,featureInteractionOverride:i.interactionOverride,featureStyleOverrides:i.styleOverrides,featureCreatedAt:i.createdAt}),this.polygonInformation.createPolygonInformationStorage(this.getFeatureGroups())}catch{}}updatePolygonAfterCloneDrag(e,t){try{let r=null;for(const t of this.getFeatureGroups())if(t.eachLayer(o=>{o===e&&(r=t)}),r)break;if(!r)return;const o=e.toGeoJSON(),n=(null==t?void 0:t.startLatLngs)??null,i=n?this.createPolygonFeatureFromLatLngs(n):null,{level:a,original:s}=this.getOptimizationMetadataFromFeatureGroup(r),l=this.getFeatureMetadataState(r);this.cleanupFeatureGroup(r),this.removeFeatureGroup(r);const c=this.turfHelper.getTurfPolygon(o);if(this.emitPolygonUpdated({operation:"polygonDrag",polygon:c,allowMerge:!0,optimizationLevel:a,originalOptimizationLevel:s,featureId:l.featureId,featureMetadata:l.metadata,sourceFeatureIds:l.sourceFeatureIds,featureInteractionOverride:l.interactionOverride,featureStyleOverrides:l.styleOverrides,featureCreatedAt:l.createdAt}),i){const e=this.turfHelper.getTurfPolygon(i);this.emitPolygonUpdated({operation:"polygonClone",polygon:e,allowMerge:!0,optimizationLevel:a,originalOptimizationLevel:s,featureId:l.featureId,featureMetadata:l.metadata,sourceFeatureIds:l.sourceFeatureIds,featureInteractionOverride:l.interactionOverride,featureStyleOverrides:l.styleOverrides,featureCreatedAt:l.createdAt})}this.polygonInformation.createPolygonInformationStorage(this.getFeatureGroups())}catch{}finally{this.currentModifierDragMode=!1,this.isModifierKeyHeld=!1}}showCloneGhost(e){if(this.clearCloneGhost(),e)try{const t=oi.createPolygon(e,{color:this.config.styles.polygon.color,weight:this.config.styles.polygon.weight,opacity:.9,fill:!1,fillOpacity:0,dashArray:"4,6",interactive:!1});t.addTo(this.map),this.currentCloneGhost=t}catch{}}clearCloneGhost(){if(this.currentCloneGhost){try{this.map.removeLayer(this.currentCloneGhost)}catch{}this.currentCloneGhost=null}}createPolygonFeatureFromLatLngs(e){try{return oi.createPolygon(e).toGeoJSON()}catch{return null}}getDragSubtractModifierKey(){const{keys:e}=this.config.interaction.drag.modifierSubtract,t=navigator.userAgent.toLowerCase(),r=t.includes("mac"),o=t.includes("windows");return r&&e.mac?e.mac:o&&e.windows?e.windows:e.linux?e.linux:r?"metaKey":"ctrlKey"}detectDragSubtractModifierKey(e){if(jn())return!1;return e[this.getDragSubtractModifierKey()]||!1}setSubtractVisualMode(e,t){if(e&&e.setStyle)try{t?e.setStyle({color:this.config.styles.ui.dragSubtract.color}):e.setStyle({color:this.config.styles.polygon.color}),this.updateMarkerColorsForSubtractMode(e,t)}catch{}}updateMarkerColorsForSubtractMode(e,t){try{let r=null;for(const t of this.getFeatureGroups())if(t.eachLayer(o=>{o===e&&(r=t)}),r)break;if(!r)return;const o=r,n=this.config.interaction.drag.modifierSubtract.hideMarkersOnDrag;o.eachLayer(e=>{if(e instanceof s.Marker){const r=e.getElement();r&&(t?n?(r.style.display="none",r.classList.add("subtract-mode-hidden")):(r.style.backgroundColor=this.config.styles.ui.dragSubtract.color,r.style.borderColor=this.config.styles.ui.dragSubtract.color,r.classList.add("subtract-mode")):n?(r.style.display="",r.classList.remove("subtract-mode-hidden")):(r.style.backgroundColor="",r.style.borderColor="",r.classList.remove("subtract-mode")))}})}catch{}}handleModifierToggleDuringDrag(e){const t=this.detectDragSubtractModifierKey(e);this.currentModifierDragMode=t,this.isModifierKeyHeld=t,this.currentDragPolygon&&this.setSubtractVisualMode(this.currentDragPolygon,t)}isModifierDragActive(){return this.currentModifierDragMode}performModifierSubtract(e,t){var r;try{const o=this.turfHelper.getTurfPolygon(e),n=[],i=null==(r=this.layerManager)?void 0:r.getLayerForFeatureGroup(t);this.getFeatureGroups().forEach(e=>{if(e!==t){if(i&&this.layerManager){if(this.layerManager.getLayerForFeatureGroup(e)!==i)return}try{const t=e.toGeoJSON();if(!t||!t.features||!t.features[0])return;const r=t.features[0];if(!r.geometry||!r.geometry.coordinates)return;const i=this.turfHelper.getTurfPolygon(r);try{const t=this.turfHelper.getIntersection(i,o);if(t&&t.geometry&&"coordinates"in t.geometry){t.geometry.coordinates.length>0&&n.push(e)}}catch{try{this.turfHelper.polygonIntersect(i,o)&&n.push(e)}catch{}}}catch{}}}),this.removeFeatureGroup(t),n.forEach(e=>{try{const r=e.toGeoJSON(),n=this.turfHelper.getTurfPolygon(r.features[0]),{level:i,original:a}=this.getOptimizationMetadataFromFeatureGroup(e),s=this.getFeatureMetadataState(e);this.cleanupFeatureGroup(e),this.removeFeatureGroup(e);try{const e=this.turfHelper.polygonDifference(n,o);if(e&&e.geometry){const t=this.turfHelper.getCoords(e);for(const e of t){const t=this.turfHelper.getMultiPolygon([e]);this.emitPolygonUpdated({operation:"modifierSubtract",polygon:this.turfHelper.getTurfPolygon(t),allowMerge:!1,optimizationLevel:i,originalOptimizationLevel:a,featureId:s.featureId,featureMetadata:s.metadata,sourceFeatureIds:s.sourceFeatureIds,featureInteractionOverride:s.interactionOverride,featureStyleOverrides:s.styleOverrides,featureCreatedAt:s.createdAt})}}}catch(t){Wn()||console.warn("Failed to perform difference operation:",t),this.emitPolygonUpdated({operation:"modifierSubtractFallback",polygon:n,allowMerge:!1,optimizationLevel:i,originalOptimizationLevel:a,featureId:s.featureId,featureMetadata:s.metadata,sourceFeatureIds:s.sourceFeatureIds,featureInteractionOverride:s.interactionOverride,featureStyleOverrides:s.styleOverrides,featureCreatedAt:s.createdAt})}}catch(r){Wn()||console.warn("Error in modifier subtract operation:",r)}}),this.polygonInformation.createPolygonInformationStorage(this.getFeatureGroups())}catch(o){Wn()||console.warn("Error in performModifierSubtract:",o)}}getEdgeDeletionModifierKey(){const{keys:e}=this.config.interaction.edgeDeletion,t=navigator.userAgent.toLowerCase(),r=t.includes("mac"),o=t.includes("windows");return r&&e.mac?e.mac:o&&e.windows?e.windows:e.linux?e.linux:r?"metaKey":"ctrlKey"}isEdgeDeletionModifierKeyPressed(e){if(jn())return!1;return!!e[this.getEdgeDeletionModifierKey()]}registerPolygonLayerMappings(e){e.eachLayer(t=>{t instanceof s.Polygon&&this.polygonFeatureGroupMap.set(t,e)})}findFeatureGroupForPolygon(e){for(const t of this.getFeatureGroups()){let r=!1;if(t.eachLayer(t=>{r||t!==e||(r=!0)}),r)return t}}onMarkerHoverForEdgeDeletion(e,t){const r=e.getElement();if(r)if(t){const t=e=>{if(this.isEdgeDeletionModifierKeyPressed(e)){r.style.backgroundColor=this.config.styles.ui.edgeDeletion.color,r.style.borderColor=this.config.styles.ui.edgeDeletion.color,r.classList.add("edge-deletion-hover");try{this.map.getContainer().style.cursor="pointer"}catch{}}else{r.style.backgroundColor="",r.style.borderColor="",r.classList.remove("edge-deletion-hover");try{this.map.getContainer().style.cursor=""}catch{}}};t(new MouseEvent("mouseover")),this.markerModifierHandlers.set(e,t),document.addEventListener("keydown",t),document.addEventListener("keyup",t),r.addEventListener("mousemove",t)}else{r.style.backgroundColor="",r.style.borderColor="",r.classList.remove("edge-deletion-hover");try{this.map.getContainer().style.cursor=""}catch{}const t=this.markerModifierHandlers.get(e);t&&(document.removeEventListener("keydown",t),document.removeEventListener("keyup",t),r.removeEventListener("mousemove",t),this.markerModifierHandlers.delete(e))}}getMarkerIndex(e,t){const r=$n.getBounds(e,Math.sqrt(2)/2),o=new Kn(r.getSouth(),r.getWest(),r.getNorth(),r.getEast()).getDirection(t),n={lat:o.lat,lng:o.lng},i=this.turfHelper.getCoord(n),a=this.turfHelper.getFeaturePointCollection(e);return this.turfHelper.getNearestPointIndex(i,a)}ensureMarkerSeparation(e,t){const r=[];if(t.menu.enabled&&r.push({type:"menu",index:t.menu.index}),t.delete.enabled&&r.push({type:"delete",index:t.delete.index}),t.info.enabled&&r.push({type:"info",index:t.info.index}),r.length<2)return{menu:t.menu.index,delete:t.delete.index,info:t.info.index};const o={...t},n=new Set,i=["info","delete","menu"];for(const a of i){const t=o[a];if(t.enabled)if(n.has(t.index)){const r=this.findAlternativeMarkerPosition(e,t.index,n);o[a].index=r,n.add(r)}else n.add(t.index)}return{menu:o.menu.index,delete:o.delete.index,info:o.info.index}}findAlternativeMarkerPosition(e,t,r){const o=e,n=Math.max(1,Math.floor(e/8));for(let i=1;i<o;i++){const o=[(t+i*n)%e,(t-i*n+e)%e];for(const e of o)if(!r.has(e))return e}for(let i=0;i<e;i++)if(!r.has(i))return i;return t}createDivIcon(e){return Mi.createDivIcon(e)}getLatLngInfoString(e){return"Latitude: "+e.lat+" Longitude: "+e.lng}setMarkerVisibility(e,t){const r=this.getFeatureGroups().find(t=>t.hasLayer(e));r&&r.eachLayer(e=>{if(e instanceof s.Marker){const r=e.getElement();if(r){const e=this.config.interaction.drag.markerBehavior,o=this.config.interaction.drag.markerAnimationDuration;"hide"===e?r.style.display=t?"":"none":"fade"===e&&(r.style.transition=`opacity ${o}ms ease`,r.style.opacity=t?"1":"0")}}})}getBuiltInMenuButtonConfigs(){const e=this.config.polygonTools;return[{enabled:e.simplify.enabled,id:"simplify",label:"Simplify",classNames:["simplify"]},{enabled:e.doubleElbows.enabled,id:"doubleElbows",label:"DoubleElbows",classNames:["double-elbows"]},{enabled:e.bbox.enabled,id:"bbox",label:"Bounding box",classNames:["bbox"]},{enabled:e.bezier.enabled,id:"bezier",label:"Curve",classNames:["bezier"]},{enabled:e.scale.enabled,id:"scale",label:"Scale",classNames:["transform-scale"]},{enabled:e.rotate.enabled,id:"rotate",label:"Rotate",classNames:["transform-rotate"]}]}getBuiltInMenuButtons(e){var t;const r=this.getBuiltInMenuButtonConfigs().filter(({enabled:e})=>e).map(({id:e,label:t,classNames:r})=>Gi.createMenuButton(e,t,r));(null==(t=this.config.polygonTools.donut)?void 0:t.enabled)&&!this.donutTargetHasHoles(e)&&r.push(Gi.createMenuButton("donut","Donut",["transform-donut"]));const o=this.getVisualOptimizationToggleButton(e);return o&&r.push(o),r}getVisualOptimizationToggleButton(e){var t;if(!(null==(t=this.config.polygonTools.visualOptimizationToggle)?void 0:t.enabled))return null;const{level:r,original:o}=this.getOptimizationMetadataFromFeatureGroup(e);if(!(o>0||r>0))return null;const n="number"==typeof r&&r>0,i=n?"visual-optimization-state-hidden":"visual-optimization-state-visible",a=n?"Show all markers":"Hide extra markers";return Gi.createMenuButton("toggleOptimization",a,["toggle-visual-optimization",i])}getPolygonMenuActionButtons(e){const{menuActions:t}=this.config.polygonTools;return Array.isArray(t)?t.filter(t=>this.shouldShowPolygonMenuActionButton(t,e)).map(e=>Gi.createMenuButton(e.id,e.label,this.getPolygonMenuActionClassNames(e))):[]}shouldShowPolygonMenuActionButton(e,t){if(!e.id||Hi.has(e.id))return!1;if(!e.visible)return!0;try{return e.visible(this.getMenuActionContext(t))}catch{return!1}}getPolygonMenuActionClassNames(e){return Array.isArray(e.className)?e.className:e.className?[e.className]:["menu-action-default"]}closeOpenMenuPopup(){this._openMenuPopup&&(this.map.closePopup(this._openMenuPopup),this._openMenuPopup=null)}attachMenuPopupCloseHandler(e){const t=e.querySelector(".marker-menu-close");if(!t)return;const r=e=>{e.stopPropagation(),e.preventDefault(),this._openMenuPopup?this.closeOpenMenuPopup():this.map.closePopup()};t.addEventListener("click",r),t.addEventListener("touchend",r,{passive:!1})}emitBuiltInPolygonMenuAction(e,t,r){this.eventManager.emit("polydraw:menu:action",{action:e,latLngs:t,featureGroup:r}),this.closeOpenMenuPopup()}attachBuiltInMenuActionHandler(e,t,r,o){const n=e=>{e.preventDefault(),e.stopPropagation(),this.emitBuiltInPolygonMenuAction(t,r,o)};e.addEventListener("touchend",n,{passive:!1}),e.onclick=n}attachTransformHandler(e,t,r){const o=e=>{e.preventDefault(),e.stopPropagation(),this.startPolygonTransform(r,t),this.closeOpenMenuPopup()};e.addEventListener("touchend",o,{passive:!1}),e.onclick=o}attachOptimizationToggleHandler(e,t){const r=e=>{e.preventDefault(),e.stopPropagation(),this.toggleOptimizationVisibility(t),this.closeOpenMenuPopup()};e.addEventListener("touchend",r,{passive:!1}),e.onclick=r}attachCustomPolygonMenuActionHandler(e,t,r,o){var n;if(!(null==(n=this.config.polygonTools.menuActions)?void 0:n.find(({id:e})=>e===t)))return;const i=e=>{e.preventDefault(),e.stopPropagation(),this.eventManager.emit("polydraw:menu:action",{action:"polygonMenuAction",menuActionId:t,latLngs:r,featureGroup:o}),this.closeOpenMenuPopup()};e.addEventListener("touchend",i,{passive:!1}),e.onclick=i}attachMenuButtonHandler(e,t,r){const o=e.dataset.actionId;switch(o){case"simplify":case"doubleElbows":case"bbox":case"bezier":return void this.attachBuiltInMenuActionHandler(e,o,t,r);case"scale":case"rotate":case"donut":return void this.attachTransformHandler(e,o,r);case"toggleOptimization":return void this.attachOptimizationToggleHandler(e,r);default:o&&this.attachCustomPolygonMenuActionHandler(e,o,t,r)}}startPolygonTransform(e,t){const r=this.transformControllers.get(e);if(r&&(r.cancel(),r.destroy(),this.transformControllers.delete(e)),"donut"!==t||!this.donutTargetHasHoles(e))try{const r=new _i(this.map,e,t,this.config.polygonTools.donut.direction,o=>this.handleTransformControllerResult(r,e,t,o));this.transformControllers.set(e,r);const o=this.getPolygonLayer(e);o&&this.setMarkerVisibility(o,!1),this.transformModeActive=!0}catch{}}handleTransformControllerResult(e,t,r,o){this.transformControllers.get(t)===e&&this.transformControllers.delete(t),this.transformModeActive=!1;const n=this.getPolygonLayer(t);if(!n)return;if(!o)return void this.setMarkerVisibility(n,!0);const{level:i,original:a}=this.getOptimizationMetadataFromFeatureGroup(t);if("donut"===r)return void this.handleDonutCommit(e,t,n,i,a);this.saveHistoryState&&this.saveHistoryState(r);const s=n.toGeoJSON(),l=this.getFeatureMetadataState(t);this.cleanupFeatureGroup(t),this.removeFeatureGroup(t),this.emitPolygonUpdated({operation:"transform",polygon:this.turfHelper.getTurfPolygon(s),allowMerge:!0,optimizationLevel:i,originalOptimizationLevel:a,featureId:l.featureId,featureMetadata:l.metadata,sourceFeatureIds:l.sourceFeatureIds,featureInteractionOverride:l.interactionOverride,featureStyleOverrides:l.styleOverrides,featureCreatedAt:l.createdAt})}getPolygonLayer(e){return e.getLayers().find(e=>e instanceof s.Polygon)}attachMenuButtonHandlers(e,t,r){e.forEach(e=>this.attachMenuButtonHandler(e,t,r))}enableMenuButtonPointerEvents(e){e.querySelectorAll(".marker-menu-button").forEach(e=>{e.style.pointerEvents="auto",e.addEventListener("click",e=>e.stopPropagation())})}generateMenuMarkerPopup(e,t){const r=[...this.getBuiltInMenuButtons(t),...this.getPolygonMenuActionButtons(t)],o=Gi.buildMenuPopup(r);this.attachMenuPopupCloseHandler(o),this.attachMenuButtonHandlers(r,e,t),s.DomEvent.disableClickPropagation(o),o.style.pointerEvents="auto",this.enableMenuButtonPointerEvents(o);const n=globalThis.innerWidth<=600,i=ri.isV1()?" leaflet-v1":" leaflet-v2",a=oi.createPopup({closeButton:!1,autoClose:!0,className:`menu-popup${n?" mobile-popup":""}${i}`}).setContent(o);return this._openMenuPopup=a,a}getMenuActionContext(e){const t=this.getPolygonGeoJSONFromFeatureGroup(e),r=e.getLayers().find(e=>e instanceof s.Polygon);return{polygon:this.turfHelper.getTurfPolygon(t),featureGroup:e,bounds:r?r.getBounds():oi.createLatLngBounds()}}toggleOptimizationVisibility(e){const t=e.getLayers().find(e=>e instanceof s.Polygon);if(!t)return;const r=this.getOptimizationMetadataFromFeatureGroup(e);if(!r.original&&!r.level)return;const o=r.level>0?0:r.original>0?r.original:r.level;if(o===r.level)return;const n=t.toGeoJSON(),i=this.getFeatureMetadataState(e);this.cleanupFeatureGroup(e),this.removeFeatureGroup(e),this.emitPolygonUpdated({operation:"toggleOptimization",polygon:this.turfHelper.getTurfPolygon(n),allowMerge:!0,optimizationLevel:o,originalOptimizationLevel:r.original||o,featureId:i.featureId,featureMetadata:i.metadata,sourceFeatureIds:i.sourceFeatureIds,featureInteractionOverride:i.interactionOverride,featureStyleOverrides:i.styleOverrides,featureCreatedAt:i.createdAt})}getPolygonGeoJSONFromFeatureGroup(e){try{const t=e.getLayers().find(e=>e instanceof s.Polygon);if(!t)throw new Error("No polygon found in feature group");return t.toGeoJSON()}catch(t){return Wn()||(t instanceof Error?console.warn("Error getting polygon GeoJSON from feature group:",t.message):console.warn("Error getting polygon GeoJSON from feature group:",t)),{type:"Feature",geometry:{type:"Polygon",coordinates:[[[0,0],[0,1],[1,1],[1,0],[0,0]]]},properties:{}}}}getTotalPolygonPerimeter(e){try{if(!e||!e.geometry)return 0;let t=0;if("Polygon"===e.geometry.type){const r=e.geometry.coordinates;for(const e of r){const r={type:"Feature",geometry:{type:"Polygon",coordinates:[e]},properties:{}};t+=this.turfHelper.getPolygonPerimeter(r)}}else if("MultiPolygon"===e.geometry.type){const r=e.geometry.coordinates;for(const e of r)for(const r of e){const e={type:"Feature",geometry:{type:"Polygon",coordinates:[r]},properties:{}};t+=this.turfHelper.getPolygonPerimeter(e)}}return 1e3*t}catch(t){return Wn()||(t instanceof Error?console.warn("Error calculating total polygon perimeter:",t.message):console.warn("Error calculating total polygon perimeter:",t)),1e3*this.turfHelper.getPolygonPerimeter(e)}}generateInfoMarkerPopup(e,t){var r,o;const n=new Jn(t,this.config),i=new Zn(e,this.config),a=this.config.markers.markerInfoIcon??{},l=!1!==a.showArea,c=!1!==a.showPerimeter,u=!1!==a.useMetrics,h=null==(r=a.areaLabel)?void 0:r.trim(),g=null==(o=a.perimeterLabel)?void 0:o.trim(),d=document.createElement("div");d.classList.add("info-marker-outer-wrapper");const p=document.createElement("div");p.classList.add("info-marker-wrapper");const f=document.createElement("div");f.classList.add("content");const y=document.createElement("div");if(y.classList.add("info-marker-content"),l){const e=u?`${i.metricArea} ${i.metricUnit}`:`${i.imperialArea} ${i.imperialUnit}`,t=document.createElement("div");t.classList.add("info-item","area"),t.innerHTML=h&&h.length>0?`<strong>${h}:</strong> ${e}`:e,y.appendChild(t)}if(c){const e=u?`${n.metricLength} ${n.metricUnit}`:`${n.imperialLength} ${n.imperialUnit}`,t=document.createElement("div");t.classList.add("info-item","perimeter"),t.innerHTML=g&&g.length>0?`<strong>${g}:</strong> ${e}`:e,y.appendChild(t)}f.appendChild(y),d.appendChild(p),p.appendChild(f),s.DomEvent.disableClickPropagation(d),d.style.pointerEvents="auto",d.querySelectorAll("button").forEach(e=>{e.style.pointerEvents="auto",e.addEventListener("click",e=>e.stopPropagation())});const m=window.innerWidth<=600;return oi.createPopup({closeButton:!0,autoClose:!0,className:"info-popup"+(m?" mobile-popup":"")}).setContent(d)}}class zi{constructor(e){i(this,"turfHelper"),i(this,"map"),i(this,"config"),i(this,"eventManager"),i(this,"getFeatureGroups"),i(this,"saveHistoryState"),i(this,"layerManager"),i(this,"geometryManager"),i(this,"interactionManager"),i(this,"onDrawCancel",e=>{this.emit("drawCancelled",e)}),i(this,"onPolygonUpdated",e=>{this.handlePolygonModified(e)}),i(this,"onMenuAction",e=>{this.handleMenuAction(e).catch(e=>{if(!Wn()){const t=e instanceof Error?e.message:String(e);console.warn(`Menu action failed: ${t}`)}})}),i(this,"onCheckIntersection",e=>{const t=this.geometryManager.checkPolygonIntersection(e.polygon1,e.polygon2);e.callback(t)}),i(this,"onSubtract",e=>{this.subtractPolygon(e.subtractPolygon)}),i(this,"onPolygonDeleted",()=>{this.emit("polygonDeleted",void 0)}),this.turfHelper=e.turfHelper,this.map=e.map,this.config=e.config,this.eventManager=e.eventManager,this.getFeatureGroups=e.getFeatureGroups,this.saveHistoryState=e.saveHistoryState,this.layerManager=e.layerManager,this.initializeSpecializedManagers(e)}initializeSpecializedManagers(e){this.geometryManager=new vi({turfHelper:e.turfHelper,config:e.config}),this.interactionManager=new Bi({turfHelper:e.turfHelper,polygonInformation:e.polygonInformation,map:e.map,config:e.config,modeManager:e.modeManager,eventManager:this.eventManager,saveHistoryState:e.saveHistoryState,layerManager:e.layerManager},{getFeatureGroups:this.getFeatureGroups,addFeatureGroup:e=>this.addFeatureGroupInternal(e),removeFeatureGroup:e=>this.removeFeatureGroupInternal(e)}),this.setupEventForwarding()}setupEventForwarding(){this.eventManager.on("polydraw:draw:cancel",this.onDrawCancel),this.eventManager.on("polydraw:polygon:updated",this.onPolygonUpdated),this.eventManager.on("polydraw:menu:action",this.onMenuAction),this.eventManager.on("polydraw:check:intersection",this.onCheckIntersection),this.eventManager.on("polydraw:subtract",this.onSubtract),this.eventManager.on("polydraw:polygon:deleted",this.onPolygonDeleted)}dispose(){this.eventManager.off("polydraw:draw:cancel",this.onDrawCancel),this.eventManager.off("polydraw:polygon:updated",this.onPolygonUpdated),this.eventManager.off("polydraw:menu:action",this.onMenuAction),this.eventManager.off("polydraw:check:intersection",this.onCheckIntersection),this.eventManager.off("polydraw:subtract",this.onSubtract),this.eventManager.off("polydraw:polygon:deleted",this.onPolygonDeleted),this.interactionManager.dispose()}async handlePolygonModified(e){const t=new Set(["addVertex","markerDrag","polygonDrag","polygonClone","toggleOptimization","donut"]),r=!e.operation||!t.has(e.operation);let o=e.allowMerge;e.intelligentMerge&&"markerDrag"===e.operation&&(o=this.shouldAllowIntelligentMerge(e.polygon));const n={simplify:r,noMerge:!o,visualOptimizationLevel:e.optimizationLevel||0,originalOptimizationLevel:e.originalOptimizationLevel,skipKinkProcessing:"markerDrag"===e.operation,featureId:e.featureId,featureMetadata:e.featureMetadata,sourceFeatureIds:e.sourceFeatureIds,featureInteractionOverride:e.featureInteractionOverride,featureStyleOverrides:e.featureStyleOverrides,targetLayerId:e.targetLayerId,featureCreatedAt:e.featureCreatedAt,featureLastModified:e.featureLastModified};await this.addPolygon(e.polygon,n)}async handleMenuAction(e){var t,r,o,n;if(!(null==e?void 0:e.featureGroup))return;if(this.layerManager&&!this.layerManager.isFeatureGroupEditable(e.featureGroup))return;let i;try{i=this.getCompletePolygonFromFeatureGroup(e.featureGroup)}catch(g){if(!Wn()){const e=g instanceof Error?g.message:String(g);console.warn(`Menu action skipped: unable to resolve polygon geometry (${e}).`)}return}const{level:a,original:l}=this.getOptimizationMetadataFromFeatureGroup(e.featureGroup),c=this.getFeatureMetadataStateFromFeatureGroup(e.featureGroup);let u,h=!0;switch(e.action){case"simplify":u=this.geometryManager.simplifyPolygon(i);break;case"bbox":u=this.geometryManager.convertToBoundingBox(i);break;case"doubleElbows":u=this.geometryManager.doubleElbowsPolygon(i);break;case"bezier":u=this.geometryManager.bezierifyPolygon(i);break;case"polygonMenuAction":{u=await this.executePolygonMenuAction(e.menuActionId,i,e.featureGroup);const t=e.menuActionId&&this.config.polygonTools.menuActions?this.config.polygonTools.menuActions.find(t=>t.id===e.menuActionId):void 0;h=!1!==(null==t?void 0:t.history);break}default:return}if(u.success&&u.result){this.saveHistoryState&&h&&this.saveHistoryState(e.action),this.removeFeatureGroupInternal(e.featureGroup);const i="bezier"===e.action?(null==(t=this.config.polygonTools.bezier)?void 0:t.visualOptimizationLevel)??10:a,g="bezier"===e.action?(null==(r=this.config.polygonTools.bezier)?void 0:r.visualOptimizationLevel)??10:l,d=!1===u.allowMerge,p=!0===u.simplify,f=u.metadata??c.metadata,y=await this.addPolygon(u.result,{simplify:p,noMerge:d,visualOptimizationLevel:i,originalOptimizationLevel:g,featureId:c.featureId,featureMetadata:f,sourceFeatureIds:c.sourceFeatureIds,featureInteractionOverride:c.interactionOverride,featureStyleOverrides:c.styleOverrides,featureCreatedAt:c.createdAt});if("bezier"===e.action&&(null==(o=this.config.polygonTools.bezier)?void 0:o.ghostMarkers)){const e=.001;null==(n=y.featureGroups)||n.forEach(t=>{t.eachLayer(t=>{if(t instanceof s.Polygon){const r=t;r.setStyle({opacity:e,fillOpacity:e}),r._polydrawDragData&&(r._polydrawDragData.originalOpacity=e)}})})}}}async executePolygonMenuAction(e,t,r){if(!e||!this.config.polygonTools.menuActions)return{success:!1,error:"Polygon menu action not found"};const o=this.config.polygonTools.menuActions.find(t=>t.id===e);if(!o)return{success:!1,error:"Polygon menu action not found"};try{const e=await o.apply({polygon:t,featureGroup:r,bounds:this.getBoundsForMenuAction(r,t)}),n=this.normalizeMenuActionResult(e);return n?this.isPolygonFeature(n.polygon)?{success:!0,result:n.polygon,allowMerge:n.allowMerge,simplify:n.simplify,metadata:n.metadata}:{success:!1,error:"Invalid polygon geometry"}:{success:!1,error:"No change"}}catch(n){if(!Wn()){const e=n instanceof Error?n.message:String(n);console.warn(`Polygon menu action failed: ${e}`)}return{success:!1,error:"Polygon menu action execution failed"}}}normalizeMenuActionResult(e){if(null!=e&&"object"==typeof e)return this.isPolygonFeature(e)?{polygon:e}:"polygon"in e&&this.isPolygonFeature(e.polygon)?{polygon:e.polygon,allowMerge:e.allowMerge,simplify:e.simplify,metadata:e.metadata}:void 0}isPolygonFeature(e){if(!e||"object"!=typeof e)return!1;const t=e;return"Feature"===t.type&&!!t.geometry&&("Polygon"===t.geometry.type||"MultiPolygon"===t.geometry.type)}getBoundsForMenuAction(e,t){const r=e.getLayers().find(e=>e instanceof s.Polygon);if(r)return r.getBounds();const o=oi.createLatLngBounds(),n=e=>{"number"==typeof e[0]&&"number"==typeof e[1]&&o.extend(oi.createLatLng(e[1],e[0]))};return"Polygon"===t.geometry.type?t.geometry.coordinates.forEach(e=>e.forEach(n)):t.geometry.coordinates.forEach(e=>e.forEach(e=>e.forEach(n))),o}get polygonInteractionManager(){return this.interactionManager}on(e,t){this.eventManager.on(e,t)}emit(e,t){this.eventManager.emit(e,t)}async addPolygon(e,t={}){if(this.layerManager&&t.targetLayerId){if(!this.layerManager.getLayer(t.targetLayerId))return{success:!1,error:`Layer "${t.targetLayerId}" does not exist`}}const{polygons:r,skipMerge:o}=this.preparePolygonsForAddition(e,t),n=[];for(const i of r){const e=await this.addPolygonWithMergeHandling(i,t,o);if(!e.success)return e;e.featureGroups&&e.featureGroups.length>0&&n.push(...e.featureGroups)}return{success:!0,featureGroups:n.length>0?n:void 0}}async addPolygonWithMergeHandling(e,t,r){const{noMerge:o=!1}=t;try{return this.isPolygonInsideExistingHole(e)?await this.addPolygonLayer(e,t):this.config.mergePolygons&&!o&&this.getFeatureGroups().length>0&&!r?await this.mergePolygon(e,t):await this.addPolygonLayer(e,t)}catch(n){return{success:!1,error:n instanceof Error?n.message:"Unknown error in addPolygon"}}}preparePolygonsForAddition(e,t={}){let r=!1;try{r=this.turfHelper.hasKinks(e)}catch(o){Wn()||console.warn("Error detecting polygon kinks:",o instanceof Error?o.message:String(o))}if(!(!0===t.skipKinkProcessing)&&!this.config.kinks&&r)try{const t=this.turfHelper.getKinks(e);if(t.length>0)return{polygons:t,skipMerge:!1}}catch(o){Wn()||console.warn("Error splitting polygon kinks:",o instanceof Error?o.message:String(o))}return{polygons:[e],skipMerge:this.config.kinks&&r}}async subtractPolygon(e,t={}){const{simplify:r=!0,visualOptimizationLevel:o,originalOptimizationLevel:n}=t;try{const a=[],s=this.layerManager;(s?s.getFeatureGroupsForLayer(t.targetLayerId||s.getActiveLayerId()).filter(e=>s.isFeatureGroupEditable(e)):this.getFeatureGroups()).forEach(t=>{try{const r=t.toGeoJSON();if(!r||!r.features||!r.features[0])return;const o=r.features[0];if(!o.geometry||!o.geometry.coordinates)return;const n=this.turfHelper.getTurfPolygon(o);this.geometryManager.checkPolygonIntersection(n,e)&&a.push(t)}catch(r){Wn()||console.warn("Skipping feature group during intersection check:",r)}});const l=[];for(const t of a)try{const i=this.getFeatureMetadataStateFromFeatureGroup(t),a=t.toGeoJSON(),s=this.turfHelper.getTurfPolygon(a.features[0]),c=this.geometryManager.subtractPolygon(s,e);if(this.removeFeatureGroupInternal(t),c.success&&c.results)for(const e of c.results){const t=await this.addPolygonLayer(e,{simplify:r,visualOptimizationLevel:o,originalOptimizationLevel:n,featureMetadata:i.metadata,sourceFeatureIds:i.sourceFeatureIds,featureInteractionOverride:i.interactionOverride,featureStyleOverrides:i.styleOverrides,featureCreatedAt:i.createdAt});t.success&&t.featureGroups&&l.push(...t.featureGroups)}}catch(i){Wn()||console.warn("Failed subtract operation for one feature group:",i)}return this.emit("polygonSubtracted",{subtractedPolygon:e,affectedFeatureGroups:a,resultFeatureGroups:l}),this.emit("polygonOperationComplete",{operation:"subtract",polygon:e,resultFeatureGroups:l}),{success:!0,featureGroups:l}}catch(i){return{success:!1,error:i instanceof Error?i.message:"Unknown error in subtractPolygon"}}}async addPolygonLayer(e,t={}){const{simplify:r=!0,dynamicTolerance:o=!1,visualOptimizationLevel:n=0,originalOptimizationLevel:i,targetLayerId:a,layerColor:l,featureId:c,featureMetadata:u,sourceFeatureIds:h,featureInteractionOverride:g,featureStyleOverrides:d,featureCreatedAt:p,featureLastModified:f}=t;try{if(!e||!e.geometry||!e.geometry.coordinates)return{success:!1,error:"Invalid polygon data"};const t=this.layerManager?a||this.layerManager.getActiveLayerId():void 0,y=!this.layerManager||!t||this.layerManager.isLayerEditable(t),m=void 0===g?y:"editable"===g;let v=l;if(!v&&this.layerManager&&t){const e=this.layerManager.getLayer(t);e&&(v=e.color)}else if(!v&&this.layerManager){const e=this.layerManager.getActiveLayer();e&&this.layerManager.getLayerCount()>1&&(v=e.color)}const M=new s.FeatureGroup,b=r?this.turfHelper.getSimplified(e,o):e,w=this.normalizeSinglePolygonFeature(b);let P,L,k=n;try{if(P=this.getPolygon(w,v,{enableDragging:m,styleOverrides:d}),!P)return{success:!1,error:"Failed to create polygon"};P._polydrawOptimizationLevel=n,k=i??P._polydrawOptimizationOriginalLevel??n,P._polydrawOptimizationOriginalLevel=k||0,M.addLayer(P),this.interactionManager.suppressDeleteMarkerClicks(250)}catch{return{success:!1,error:"Failed to create polygon layer"}}this.setFeatureGroupMetadata(M,{featureId:c,metadata:u,sourceFeatureIds:h,interactionOverride:g,styleOverrides:d,optimizationLevel:n,originalOptimizationLevel:k,hasHoles:this.featureHasHoles(w),layerId:t,createdAt:p,lastModified:f});try{const e=P.getLatLngs();L=this.normalizePolygonCoordinates(e)}catch{L=[]}if(m){try{L.forEach((e,t)=>{if(!e||!Array.isArray(e))return;const r=[];if(e.forEach(e=>{Array.isArray(e)&&e.length>=2?r.push({lat:e[1],lng:e[0]}):"object"==typeof e&&null!==e&&"lat"in e&&"lng"in e&&r.push(e)}),0!==r.length)try{if(0===t)this.interactionManager.addMarkers(r,M,{optimizationLevel:n,originalOptimizationLevel:k});else{const e=oi.createPolyline(r,{color:this.config.styles.hole.color,weight:this.config.styles.hole.weight||2,opacity:this.config.styles.hole.opacity||1,fillColor:this.config.styles.hole.fillColor,fillOpacity:this.config.styles.hole.fillOpacity||.5});M.addLayer(e),this.interactionManager.addHoleMarkers(r,M)}}catch{}})}catch{}try{this.interactionManager.addEdgeClickListeners(P,M)}catch{}}if(this.getFeatureGroups().push(M),this.layerManager){const e=t||this.layerManager.getActiveLayerId();if(!this.layerManager.assignFeatureGroupToLayer(M,e))return this.removeFeatureGroupInternal(M),{success:!1,error:`Failed to assign polygon to layer "${e}"`}}try{M.addTo(this.map)}catch{}return this.interactionManager.updateMarkerDraggableState(),this.emit("polygonAdded",{polygon:w,featureGroup:M}),this.emit("polygonOperationComplete",{operation:"add",polygon:w,featureGroup:M}),{success:!0,featureGroups:[M]}}catch(y){return{success:!1,error:y instanceof Error?y.message:"Unknown error in addPolygonLayer"}}}async mergePolygon(e,t={}){try{const r=[],o=[];let n=!1;const i=!1!==t.mergeEditableOnly,a=this.layerManager;return(a?a.getFeatureGroupsForLayer(t.targetLayerId||a.getActiveLayerId()).filter(e=>!i||a.isFeatureGroupEditable(e)):this.getFeatureGroups()).forEach(t=>{try{const i=t.toGeoJSON();if(!i||!i.features||!i.features[0])return;const a=i.features[0];if(!a.geometry||!a.geometry.coordinates)return;if(this.isPositionArrayofArrays(a.geometry.coordinates))a.geometry.coordinates.forEach(i=>{try{const a=this.turfHelper.getMultiPolygon([i]);n=this.geometryManager.checkPolygonIntersection(a,e),n&&(o.push(t),r.push(a))}catch{}});else try{const i=this.turfHelper.getTurfPolygon(a);n=this.geometryManager.checkPolygonIntersection(i,e),n&&(o.push(t),r.push(i))}catch{}}catch{}}),o.length>0?await this.unionPolygons(o,e,r,t):await this.addPolygonLayer(e,t)}catch(r){return{success:!1,error:r instanceof Error?r.message:"Unknown error in mergePolygon"}}}async unionPolygons(e,t,r,o={}){try{const n=this.collectSourceFeatureIds(e,o.sourceFeatureIds),i=o.featureMetadata??this.resolvePrimaryFeatureMetadata(e),a=o.featureInteractionOverride??this.resolvePrimaryFeatureInteractionOverride(e),s=o.featureStyleOverrides??this.resolvePrimaryFeatureStyleOverrides(e);e.forEach(e=>{this.removeFeatureGroupInternal(e)});const l=this.geometryManager.unionPolygons(r,t);if(l.success&&l.result){const e=await this.addPolygonLayer(l.result,{...o,featureMetadata:i,sourceFeatureIds:n,featureInteractionOverride:a,featureStyleOverrides:s});return this.emit("polygonsUnioned",{originalPolygons:r,resultPolygon:l.result,featureGroups:e.featureGroups}),e}return{success:!1,error:l.error||"Failed to union polygons"}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Unknown error in unionPolygons"}}}shouldAllowIntelligentMerge(e){try{const t=this.layerManager,r=t?t.getFeatureGroupsForLayer(t.getActiveLayerId()).filter(e=>t.isFeatureGroupEditable(e)):this.getFeatureGroups();for(const o of r)try{const t=o.toGeoJSON();if(!t||!t.features||!t.features[0])continue;const r=t.features[0];if(!r.geometry||!r.geometry.coordinates)continue;const n=this.turfHelper.getTurfPolygon(r);if(this.geometryManager.checkPolygonIntersection(n,e))return!0}catch{continue}return!1}catch{return!1}}isPolygonInsideExistingHole(e){try{const t=this.layerManager,r=t?t.getFeatureGroupsForLayer(t.getActiveLayerId()).filter(e=>t.isFeatureGroupEditable(e)):this.getFeatureGroups();for(const o of r)try{const t=o.toGeoJSON();if(!t||!t.features||!t.features[0])continue;const r=t.features[0];if(!r.geometry||!r.geometry.coordinates)continue;let n=!1,i=[];if("Polygon"===r.geometry.type)n=r.geometry.coordinates.length>1,n&&(i=r.geometry.coordinates.slice(1));else if("MultiPolygon"===r.geometry.type)for(const e of r.geometry.coordinates)e.length>1&&(n=!0,i.push(...e.slice(1)));if(n&&i.length>0)for(const o of i)try{const t=this.turfHelper.createPolygon([o]);if(this.turfHelper.isPolygonCompletelyWithin(e,t))return!0}catch{continue}}catch{continue}return!1}catch{return!1}}normalizePolygonCoordinates(e){if(!Array.isArray(e)||0===e.length)return[];const t=e=>null!==e&&"object"==typeof e&&"lat"in e&&"lng"in e&&"number"==typeof e.lat&&"number"==typeof e.lng,r=e=>{if(!Array.isArray(e))return[];if(e.length>0&&t(e[0]))return[e];const o=[];for(const n of e)if(Array.isArray(n))if(n.length>0&&t(n[0]))o.push(n);else{const e=r(n);o.push(...e)}return o};try{return r(e)}catch{return[]}}isPositionArrayofArrays(e){if(!Array.isArray(e)||0===e.length)return!1;const t=e[0];if(!Array.isArray(t)||0===t.length)return!1;const r=t[0];if(!Array.isArray(r)||0===r.length)return!1;const o=r[0];return this.isPosition(o)}isPosition(e){return Array.isArray(e)&&e.length>=2&&e.every(e=>"number"==typeof e)}getPolygon(e,t,r={}){const o=s.GeoJSON.geometryToLayer(e),n=t||this.config.styles.polygon.color,i=this.config.styles.polygon.fillColor,{styleOverrides:a}=r,l={...this.config.styles.polygon,color:(null==a?void 0:a.color)??n,fillColor:(null==a?void 0:a.fillColor)??i,weight:(null==a?void 0:a.weight)??this.config.styles.polygon.weight??2,opacity:this.config.styles.polygon.opacity||1,fillOpacity:(null==a?void 0:a.fillOpacity)??this.config.styles.polygon.fillOpacity??.2};o.setStyle(l),o._polydrawUniqueId=oi.util.stamp(o)+"_"+Date.now(),delete o._polydrawDragData,delete o._polydrawOriginalLatLngs,delete o._polydrawCurrentDragSession,delete o._polydrawOriginalMarkerPositions,delete o._polydrawOriginalHoleLinePositions;return!1!==r.enableDragging&&(this.config.modes.dragPolygons||this.config.tools.clone)&&this.interactionManager.enablePolygonDragging(o,e),o}normalizeSinglePolygonFeature(e){if("MultiPolygon"===e.geometry.type&&1===e.geometry.coordinates.length){const[t]=e.geometry.coordinates;try{return this.turfHelper.createPolygon(t)}catch{return e}}return e}addFeatureGroupInternal(e){this.getFeatureGroups().push(e)}removeFeatureGroupInternal(e){this.cleanupFeatureGroup(e),this.layerManager&&this.layerManager.removeFeatureGroupFromLayer(e);try{e.clearLayers()}catch(o){Wn()||console.warn("Error clearing layers from feature group:",o)}const t=this.getFeatureGroups(),r=t.indexOf(e);r>-1&&t.splice(r,1);try{this.map.removeLayer(e)}catch(o){Wn()||console.warn("Error removing feature group layer from map:",o)}}getCompletePolygonFromFeatureGroup(e){try{let t=null;if(e.eachLayer(e=>{e instanceof s.Polygon&&(t=e)}),t)return t.toGeoJSON();const r=e.toGeoJSON().features.find(e=>{var t,r;return"Polygon"===(null==(t=e.geometry)?void 0:t.type)||"MultiPolygon"===(null==(r=e.geometry)?void 0:r.type)});if(r)return r;throw new Error("No polygon geometry found in feature group")}catch(t){throw Wn()||t instanceof Error&&console.warn("Error getting complete polygon GeoJSON from feature group:",t.message),t instanceof Error?t:new Error("Failed to resolve polygon geometry from feature group")}}getOptimizationMetadataFromFeatureGroup(e){if(!e)return{level:0,original:0};let t=0,r=0;return e.eachLayer(e=>{if(e instanceof s.Polygon){const o=e;"number"==typeof o._polydrawOptimizationLevel&&(t=o._polydrawOptimizationLevel||0),"number"==typeof o._polydrawOptimizationOriginalLevel&&(r=o._polydrawOptimizationOriginalLevel||0)}}),!r&&t>0&&(r=t),{level:t,original:r}}getFeatureMetadataStateFromFeatureGroup(e){if(!e)return{metadata:{},sourceFeatureIds:[]};const t=e._polydrawMetadata,r=null==t?void 0:t.id,o=Array.isArray(null==t?void 0:t.sourceFeatureIds)?[...t.sourceFeatureIds]:r?[r]:[],n=(null==t?void 0:t.createdAt)instanceof Date&&!Number.isNaN(t.createdAt.getTime())?t.createdAt.toISOString():void 0;return{featureId:r,metadata:this.cloneFeatureMetadata(null==t?void 0:t.metadata),sourceFeatureIds:o,interactionOverride:null==t?void 0:t.interactionOverride,styleOverrides:this.cloneStyleOverrides(null==t?void 0:t.styleOverrides),createdAt:n}}collectSourceFeatureIds(e,t){const r=[],o=new Set,n=e=>{e&&!o.has(e)&&(o.add(e),r.push(e))};return e.forEach(e=>{const t=e._polydrawMetadata;Array.isArray(null==t?void 0:t.sourceFeatureIds)&&t.sourceFeatureIds.length>0?t.sourceFeatureIds.forEach(e=>n(e)):n(null==t?void 0:t.id)}),Array.isArray(t)&&t.forEach(e=>n(e)),r}resolvePrimaryFeatureMetadata(e){var t;for(const r of e){const e=null==(t=r._polydrawMetadata)?void 0:t.metadata;if(e&&Object.keys(e).length>0)return this.cloneFeatureMetadata(e)}return{}}resolvePrimaryFeatureInteractionOverride(e){var t;for(const r of e){const e=null==(t=r._polydrawMetadata)?void 0:t.interactionOverride;if(e)return e}}resolvePrimaryFeatureStyleOverrides(e){var t;for(const r of e){const e=null==(t=r._polydrawMetadata)?void 0:t.styleOverrides;if(e)return this.cloneStyleOverrides(e)}}cloneFeatureMetadata(e){return e?yi(e):{}}cloneStyleOverrides(e){if(e)return yi(e)}featureHasHoles(e){return!!(null==e?void 0:e.geometry)&&("Polygon"===e.geometry.type?e.geometry.coordinates.length>1:"MultiPolygon"===e.geometry.type&&e.geometry.coordinates.some(e=>e.length>1))}setFeatureGroupMetadata(e,t){const r=new Date,o=t.createdAt?new Date(t.createdAt):r,n=t.lastModified?new Date(t.lastModified):r,i=Number.isNaN(o.getTime())?r:o,a=Number.isNaN(n.getTime())?r:n,s=t.featureId||`fg-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l=t.sourceFeatureIds&&t.sourceFeatureIds.length>0?[...new Set(t.sourceFeatureIds)]:[s];e._polydrawMetadata={id:s,optimizationLevel:t.optimizationLevel,originalOptimizationLevel:t.originalOptimizationLevel,hasHoles:t.hasHoles,createdAt:i,lastModified:a,layerId:t.layerId,metadata:this.cloneFeatureMetadata(t.metadata),sourceFeatureIds:l,interactionOverride:t.interactionOverride,styleOverrides:this.cloneStyleOverrides(t.styleOverrides)}}updateMarkerDraggableState(){this.interactionManager.updateMarkerDraggableState()}updateAllMarkersForEdgeDeletion(e){this.interactionManager.updateAllMarkersForEdgeDeletion(e)}setModifierKeyHeld(e){this.interactionManager.setModifierKeyHeld(e)}checkPolygonIntersection(e,t){return this.geometryManager.checkPolygonIntersection(e,t)}getPolygonCenter(e){try{if(!e||!e.geometry||!e.geometry.coordinates)return null;let t;if("Polygon"===e.geometry.type)t=e.geometry.coordinates[0];else{if("MultiPolygon"!==e.geometry.type)return null;t=e.geometry.coordinates[0][0]}if(!Array.isArray(t)||0===t.length)return null;let r=0,o=0,n=0;for(const e of t)if(Array.isArray(e)&&e.length>=2){const t=e[0],i=e[1];"number"!=typeof t||"number"!=typeof i||isNaN(t)||isNaN(i)||(o+=t,r+=i,n++)}return 0===n?null:{lat:r/n,lng:o/n}}catch{return null}}getBoundingBox(e){try{if(!e||!e.geometry||!e.geometry.coordinates)return null;let t;if("Polygon"===e.geometry.type)t=e.geometry.coordinates[0];else{if("MultiPolygon"!==e.geometry.type)return null;t=e.geometry.coordinates[0][0]}if(!Array.isArray(t)||0===t.length)return null;let r=1/0,o=-1/0,n=1/0,i=-1/0;for(const e of t)if(Array.isArray(e)&&e.length>=2){const t=e[0],a=e[1];"number"!=typeof t||"number"!=typeof a||isNaN(t)||isNaN(a)||(n=Math.min(n,t),i=Math.max(i,t),r=Math.min(r,a),o=Math.max(o,a))}return r===1/0||o===-1/0||n===1/0||i===-1/0?null:{minLat:r,maxLat:o,minLng:n,maxLng:i}}catch{return null}}addMarker(e,t,r){this.interactionManager.addMarkers(e,t,r)}addHoleMarker(e,t){this.interactionManager.addHoleMarkers(e,t)}addEdgeClickListeners(e,t){this.interactionManager.addEdgeClickListeners(e,t)}enablePolygonDragging(e,t){this.interactionManager.enablePolygonDragging(e,t)}getMarkerIndex(e,t){return 0}ensureMarkerSeparation(e,t){var r,o,n;return{menu:(null==(r=t.menu)?void 0:r.index)??0,delete:(null==(o=t.delete)?void 0:o.index)??1,info:(null==(n=t.info)?void 0:n.index)??2}}findAlternativeMarkerPosition(e,t,r){return(t+1)%e}createDivIcon(e){return oi.createDivIcon({className:e.join(" ")})}getLatLngInfoString(e){return"Latitude: "+e.lat+" Longitude: "+e.lng}generateMenuMarkerPopup(e,t){const r=document.createElement("div");return r.innerHTML="Menu",r}getPolygonGeoJSONFromFeatureGroup(e){return{type:"Feature",geometry:{type:"Polygon",coordinates:[[[0,0],[0,1],[1,1],[1,0],[0,0]]]},properties:{}}}getTotalPolygonPerimeter(e){return 1e3}generateInfoMarkerPopup(e,t){const r=document.createElement("div");return r.innerHTML=`Area: ${e}, Perimeter: ${t}`,r}onMarkerHoverForEdgeDeletion(e,t){}highlightEdgeOnHover(e,t){}onEdgeClick(e,t){}removeFeatureGroup(e){this.removeFeatureGroupInternal(e)}cleanupFeatureGroup(e){this.interactionManager.cleanupFeatureGroup(e)}onPolygonMouseMove(e){}onPolygonMouseUp(e){}updatePolygonAfterDrag(e){}setSubtractVisualMode(e,t){}performModifierSubtract(e,t){try{const r=this.turfHelper.getTurfPolygon(e),o=[];this.getFeatureGroups().forEach(e=>{if(e!==t)try{const t=e.toGeoJSON();if(!t||!t.features||!t.features[0])return;const n=t.features[0];if(!n.geometry||!n.geometry.coordinates)return;const i=this.turfHelper.getTurfPolygon(n);this.geometryManager.checkPolygonIntersection(i,r)&&o.push(e)}catch{}}),this.removeFeatureGroupInternal(t),o.forEach(e=>{try{const t=e.toGeoJSON(),o=this.turfHelper.getTurfPolygon(t.features[0]);this.removeFeatureGroupInternal(e);const n=this.geometryManager.subtractPolygon(o,r);if(n.success&&n.results)for(const e of n.results)this.addPolygonLayer(e,{simplify:!0})}catch{}})}catch{}}}class Ni{constructor(e,t=50){i(this,"undoStack",[]),i(this,"redoStack",[]),i(this,"maxHistorySize",50),i(this,"maxSnapshotSize",5e5),i(this,"maxTotalMemory",5e6),i(this,"currentMemoryUsage",0),i(this,"eventManager"),i(this,"isRestoring",!1),this.eventManager=e,this.maxHistorySize=t}setMaxHistorySize(e){!Number.isFinite(e)||e<=0||(this.maxHistorySize=Math.floor(e),this.enforceMemoryBudget(),this.enforceRedoMemoryBudget())}saveState(e,t,r){if(this.isRestoring)return;const o=this.createSnapshot(e,t,r),n=this.calculateSnapshotSize(o);o.size=n,n>this.maxSnapshotSize?console.warn(`History snapshot too large (${n} bytes, limit ${this.maxSnapshotSize} bytes). Skipping save.`):(this.redoStack=[],this.undoStack.push(o),this.currentMemoryUsage+=n,this.enforceMemoryBudget(),this.eventManager.emit("polydraw:history:changed",{canUndo:this.canUndo(),canRedo:this.canRedo()}))}calculateSnapshotSize(e){try{return 2*JSON.stringify(e).length}catch(t){return console.warn("Error calculating snapshot size:",t),0}}enforceMemoryBudget(){for(;this.undoStack.length>this.maxHistorySize;){const e=this.undoStack.shift();e&&(this.currentMemoryUsage-=this.getSnapshotSize(e))}for(;this.currentMemoryUsage>this.maxTotalMemory&&this.undoStack.length>0;){const e=this.undoStack.shift();e&&(this.currentMemoryUsage-=this.getSnapshotSize(e))}}enforceRedoMemoryBudget(){const e=Math.floor(this.maxHistorySize/2);for(;this.redoStack.length>e;)this.redoStack.shift()}undo(e,t){if(!this.canUndo())return null;const r=this.createSnapshot(e,"redo-point",t),o=this.calculateSnapshotSize(r);r.size=o,o<=this.maxSnapshotSize?(this.redoStack.push(r),this.enforceRedoMemoryBudget()):console.warn(`Current state too large (${o} bytes) to save to redo stack.`);const n=this.undoStack.pop();return this.currentMemoryUsage-=this.getSnapshotSize(n),this.eventManager.emit("polydraw:history:undo",{canUndo:this.canUndo(),canRedo:this.canRedo(),action:n.action}),n}redo(e,t){if(!this.canRedo())return null;const r=this.createSnapshot(e,"undo-point",t),o=this.calculateSnapshotSize(r);r.size=o,o<=this.maxSnapshotSize?(this.undoStack.push(r),this.currentMemoryUsage+=o,this.enforceMemoryBudget()):console.warn(`Current state too large (${o} bytes) to save to undo stack.`),this.enforceRedoMemoryBudget();const n=this.redoStack.pop();return this.eventManager.emit("polydraw:history:redo",{canUndo:this.canUndo(),canRedo:this.canRedo(),action:n.action}),n}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}clear(){this.undoStack=[],this.redoStack=[],this.currentMemoryUsage=0,this.eventManager.emit("polydraw:history:changed",{canUndo:this.canUndo(),canRedo:this.canRedo()})}setRestoring(e){this.isRestoring=e}createSnapshot(e,t,r){const o=[],n=[];e.forEach(e=>{e.eachLayer(t=>{var r;const i=t;if(null==i?void 0:i.toGeoJSON)try{const a=i.toGeoJSON();if(!a)return;const s=null==(r=null==a?void 0:a.geometry)?void 0:r.type;"Polygon"!==s&&"MultiPolygon"!==s||(o.push(a),n.push(this.captureFeatureMetadataSnapshot(e,t)))}catch(a){console.warn("Error converting polygon to GeoJSON:",a)}})});const i={features:o,timestamp:Date.now(),action:t};return r&&(i.layerSnapshot=r.captureLayerSnapshot(e)),n.length>0&&(i.featureMetadataSnapshot=n),i}captureFeatureMetadataSnapshot(e,t){const r={},o=e._polydrawMetadata;if((null==o?void 0:o.id)&&(r.id=o.id),(null==o?void 0:o.metadata)&&(r.metadata=yi(o.metadata)),Array.isArray(null==o?void 0:o.sourceFeatureIds)&&(r.sourceFeatureIds=[...o.sourceFeatureIds]),(null==o?void 0:o.interactionOverride)&&(r.interactionOverride=o.interactionOverride),(null==o?void 0:o.styleOverrides)&&(r.styleOverrides=yi(o.styleOverrides)),"boolean"==typeof(null==o?void 0:o.hasHoles)&&(r.hasHoles=o.hasHoles),"string"==typeof(null==o?void 0:o.layerId)&&(r.layerId=o.layerId),(null==o?void 0:o.createdAt)instanceof Date&&!Number.isNaN(o.createdAt.getTime())&&(r.createdAt=o.createdAt.toISOString()),(null==o?void 0:o.lastModified)instanceof Date&&!Number.isNaN(o.lastModified.getTime())&&(r.lastModified=o.lastModified.toISOString()),t instanceof s.Polygon){const e=t;"number"==typeof e._polydrawOptimizationLevel&&(r.optimizationLevel=e._polydrawOptimizationLevel),"number"==typeof e._polydrawOptimizationOriginalLevel&&(r.originalOptimizationLevel=e._polydrawOptimizationOriginalLevel)}return r}getSnapshotSize(e){if("number"==typeof e.size)return e.size;const t=this.calculateSnapshotSize(e);return e.size=t,t}}class Ui{constructor(e,t){i(this,"eventManager"),i(this,"layers",new Map),i(this,"featureGroupToLayer",new WeakMap),i(this,"activeLayerId","default"),i(this,"defaultColor"),this.eventManager=e,this.defaultColor=Ui.normalizeColor(t),this.ensureDefaultLayer()}getLayerCount(){return this.layers.size}getAllLayers(){return Array.from(this.layers.values()).map(e=>this.cloneLayerState(e))}getPanelLayers(){return this.getAllLayers().filter(e=>"hidden"!==e.panel)}getPanelLayerCount(){let e=0;for(const t of this.layers.values())"hidden"!==t.panel&&(e+=1);return e}getLayer(e){const t=this.layers.get(this.normalizeLayerId(e));return t?this.cloneLayerState(t):void 0}getActiveLayerId(){return this.activeLayerId}getActiveLayer(){return this.getLayer(this.activeLayerId)}getOrCreateLayer(e,t){const r=this.normalizeLayerId(e);if(this.layers.get(r))return this.cloneLayerState(this.layers.get(r));const o="string"==typeof t?{color:t}:t||{},n={id:r,label:o.label,color:o.color?Ui.normalizeColor(o.color,this.defaultColor):this.defaultColor,visible:!1!==o.visible,interaction:this.normalizeInteraction(o.interaction),panel:this.normalizePanel(o.panel),metadata:this.cloneMetadata(o.metadata),featureGroups:[]};return this.layers.set(r,n),this.eventManager.emit("polydraw:layer:created",{layerId:n.id,color:n.color}),this.cloneLayerState(n)}setActiveLayer(e){return"activated"===this.setActiveLayerWithResult(e)}setActiveLayerWithResult(e){const t=this.normalizeLayerId(e),r=this.layers.get(t);if(!r)return"not-found";if(t===this.activeLayerId)return"already-active";if(!r.visible)return"not-visible";const o=this.activeLayerId;return this.activeLayerId=t,this.eventManager.emit("polydraw:layer:activated",{layerId:t,previousLayerId:o}),"activated"}setLayerVisibility(e,t){const r=this.layers.get(this.normalizeLayerId(e));if(!r||r.visible===t)return!1;if(!t&&r.id===this.activeLayerId){const e=this.getFirstVisibleLayerId(r.id);if(!e)return!1;this.setActiveLayer(e)}return r.visible=t,this.eventManager.emit("polydraw:layer:visibility",{layerId:r.id,visible:t}),!0}setLayerColor(e,t){const r=this.layers.get(this.normalizeLayerId(e)),o=Ui.normalizeColor(t,(null==r?void 0:r.color)??this.defaultColor);return!(!r||r.color===o)&&(r.color=o,r.featureGroups.forEach(e=>{var t,r;const n=null==(r=null==(t=e._polydrawMetadata)?void 0:t.styleOverrides)?void 0:r.color;e.eachLayer(e=>{e instanceof s.Polygon&&!(e instanceof s.Rectangle)&&e.setStyle({color:n??o})})}),this.eventManager.emit("polydraw:layer:colorChanged",{layerId:r.id,color:r.color}),!0)}setLayerLabel(e,t){const r=this.layers.get(this.normalizeLayerId(e));if(!r)return!1;const o="string"==typeof t?t.trim():void 0,n=o&&o.length>0?o:void 0;return r.label!==n&&(r.label=n,!0)}setLayerInteraction(e,t){const r=this.layers.get(this.normalizeLayerId(e));if(!r)return!1;const o=this.normalizeInteraction(t);return r.interaction!==o&&(r.interaction=o,!0)}setLayerPanelVisibility(e,t){const r=this.layers.get(this.normalizeLayerId(e));if(!r)return!1;const o=this.normalizePanel(t);return r.panel!==o&&(r.panel=o,!0)}setLayerMetadata(e,t){const r=this.layers.get(this.normalizeLayerId(e));return!!r&&(r.metadata=this.cloneMetadata(t),!0)}isLayerEditable(e){const t=this.layers.get(this.normalizeLayerId(e));return!t||"editable"===t.interaction}isFeatureGroupEditable(e){var t;const r=null==(t=e._polydrawMetadata)?void 0:t.interactionOverride;if(r)return"editable"===r;const o=this.getLayerForFeatureGroup(e);return!o||this.isLayerEditable(o)}moveLayer(e,t){const r=this.normalizeLayerId(e),o=this.normalizeLayerId(t);if(r===o)return!1;if("default"===r||"default"===o)return!1;if(!this.layers.has(r)||!this.layers.has(o))return!1;const n=Array.from(this.layers.keys()),i=n.indexOf(r),a=n.indexOf(o);if(i<0||a<0)return!1;const[s]=n.splice(i,1);n.splice(a,0,s);const l=new Map;for(const c of n){const e=this.layers.get(c);e&&l.set(c,e)}return this.layers=l,this.eventManager.emit("polydraw:layer:reordered",{layerId:r,targetLayerId:o,orderedLayerIds:n}),!0}assignFeatureGroupToLayer(e,t){const r=this.normalizeLayerId(t);if(!this.layers.has(r))return!1;const o=this.getLayerForFeatureGroup(e);if(o===r)return!1;if(o){const t=this.layers.get(o);t&&(t.featureGroups=t.featureGroups.filter(t=>t!==e))}const n=this.layers.get(r);n.featureGroups.includes(e)||n.featureGroups.push(e),this.featureGroupToLayer.set(e,r);const i=e._polydrawMetadata;return i&&(i.layerId=r),!0}removeFeatureGroupFromLayer(e){const t=this.getLayerForFeatureGroup(e);if(!t)return;const r=this.layers.get(t);r&&(r.featureGroups=r.featureGroups.filter(t=>t!==e)),this.featureGroupToLayer.delete(e);const o=e._polydrawMetadata;o&&delete o.layerId}getLayerForFeatureGroup(e){const t=this.featureGroupToLayer.get(e);if(t)return t;for(const[r,o]of this.layers.entries())if(o.featureGroups.includes(e))return this.featureGroupToLayer.set(e,r),r}getFeatureGroupsForLayer(e){const t=this.layers.get(this.normalizeLayerId(e));return t?[...t.featureGroups]:[]}isInActiveLayer(e){const t=this.getLayerForFeatureGroup(e);return!t||t===this.activeLayerId}deleteLayer(e){const t=this.normalizeLayerId(e);if("default"===t)return[];const r=this.layers.get(t);if(!r)return[];const o=[...r.featureGroups];if(o.forEach(e=>{this.featureGroupToLayer.delete(e)}),this.layers.delete(t),this.activeLayerId===t){const e=this.getFirstVisibleLayerId(t);e?this.setActiveLayer(e):this.activeLayerId="default"}return this.eventManager.emit("polydraw:layer:deleted",{layerId:t,removedFeatureGroups:o}),o}moveLayerToIndex(e,t){const r=this.normalizeLayerId(e);if("default"===r||!this.layers.has(r)||!Number.isFinite(t))return!1;const o=Array.from(this.layers.keys()),n=o.indexOf(r),i=Math.trunc(t),a=Math.max(1,Math.min(i,o.length-1));if(n===a)return!1;o.splice(n,1),o.splice(a,0,r);const s=new Map;for(const l of o){const e=this.layers.get(l);e&&s.set(l,e)}return this.layers=s,this.eventManager.emit("polydraw:layer:reordered",{layerId:r,targetLayerId:o[a]??r,orderedLayerIds:o}),!0}setLayerOrder(e){if(!e||0===e.length)return!1;const t=e.map(e=>this.normalizeLayerId(e));if(new Set(t).size!==t.length)return!1;for(const s of t)if("default"===s||!this.layers.has(s))return!1;const r=Array.from(this.layers.keys()),o=new Set(t),n=Array.from(this.layers.keys()).filter(e=>"default"!==e&&!o.has(e)),i=["default",...t,...n];if(r.length===i.length&&r.every((e,t)=>e===i[t]))return!1;const a=new Map;for(const s of i){const e=this.layers.get(s);e&&a.set(s,e)}return this.layers=a,this.eventManager.emit("polydraw:layer:reordered",{layerId:t[0],targetLayerId:t[t.length-1],orderedLayerIds:i}),!0}clear(e){e&&(this.defaultColor=Ui.normalizeColor(e,this.defaultColor)),this.layers=new Map,this.featureGroupToLayer=new WeakMap,this.activeLayerId="default",this.ensureDefaultLayer()}captureLayerSnapshot(e){const t=new Map;return e.forEach((e,r)=>{t.set(e,r)}),{layers:this.getAllLayers().map(e=>({id:e.id,label:e.label,color:e.color,visible:e.visible,interaction:e.interaction,panel:e.panel,metadata:this.cloneMetadata(e.metadata),featureIndices:e.featureGroups.map(e=>t.get(e)).filter(e=>"number"==typeof e)})),activeLayerId:this.activeLayerId}}restoreFromLayerSnapshot(e,t){if(this.clear(),!e||!Array.isArray(e.layers))return;e.layers.forEach(e=>{const t=this.normalizeLayerId(e.id),r=this.layers.get(t);r?(r.label="string"==typeof e.label?e.label:void 0,r.color=e.color?Ui.normalizeColor(e.color):r.color,r.visible=!1!==e.visible,r.interaction=this.normalizeInteraction(e.interaction),r.panel=this.normalizePanel(e.panel),r.metadata=this.cloneMetadata(e.metadata)):this.layers.set(t,{id:t,label:"string"==typeof e.label?e.label:void 0,color:e.color?Ui.normalizeColor(e.color):this.defaultColor,visible:!1!==e.visible,interaction:this.normalizeInteraction(e.interaction),panel:this.normalizePanel(e.panel),metadata:this.cloneMetadata(e.metadata),featureGroups:[]})}),this.ensureDefaultLayer(),e.layers.forEach(e=>{const r=this.normalizeLayerId(e.id),o=this.layers.get(r);o&&e.featureIndices.forEach(e=>{const n=t[e];n&&(o.featureGroups.includes(n)||o.featureGroups.push(n),this.featureGroupToLayer.set(n,r))})});const r=this.normalizeLayerId(e.activeLayerId||"default"),o=this.layers.get(r);if(null==o?void 0:o.visible)return void(this.activeLayerId=r);const n=this.getFirstVisibleLayerId();if(n)return void(this.activeLayerId=n);const i=this.layers.get("default");i&&(i.visible=!0),this.activeLayerId="default"}ensureDefaultLayer(){this.layers.has("default")||this.layers.set("default",{id:"default",color:this.defaultColor,visible:!0,interaction:"editable",panel:"visible",metadata:{},featureGroups:[]})}getFirstVisibleLayerId(e){for(const t of this.layers.values())if(t.id!==e&&t.visible)return t.id}normalizeLayerId(e){const t=(e||"").trim();return t.length>0?t:"default"}cloneLayerState(e){return{id:e.id,label:e.label,color:e.color,visible:e.visible,interaction:e.interaction,panel:e.panel,metadata:this.cloneMetadata(e.metadata),featureGroups:[...e.featureGroups]}}normalizeInteraction(e){return"readonly"===e||"static"===e?e:"editable"}normalizePanel(e){return"hidden"===e?"hidden":"visible"}cloneMetadata(e){return e?yi(e):{}}static normalizeColor(e,t="#50622b"){let r=(e||"").trim().replace(/^#/,"");return 3===r.length&&(r=`${r[0]}${r[0]}${r[1]}${r[1]}${r[2]}${r[2]}`),/^[0-9a-fA-F]{6}$/.test(r)?`#${r.toLowerCase()}`:t}}const Ri=e=>e.replace(/#(?:fff|ffffff)/gi,"currentColor"),Xi={grip:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">\n <circle cx="9" cy="5" r="1" />\n <circle cx="9" cy="12" r="1" />\n <circle cx="9" cy="19" r="1" />\n <circle cx="15" cy="5" r="1" />\n <circle cx="15" cy="12" r="1" />\n <circle cx="15" cy="19" r="1" />\n</svg>\n'.trim(),eyeVisible:Ri('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">\n <defs>\n <mask id="pupil-hole-hide">\n <rect width="512" height="512" fill="white"/>\n <circle cx="256" cy="220" r="60" fill="black"/>\n </mask>\n </defs>\n <g fill="none" stroke="#fff" stroke-linecap="round" stroke-linejoin="round">\n \x3c!-- Upper eye contour --\x3e\n <path d="M24 256 C 120 93 392 93 488 256" stroke-width="48"/>\n \x3c!-- Lower eye contour --\x3e\n <path d="M24 256 C 120 419 392 419 488 256" stroke-width="48"/>\n \x3c!-- Iris highlight --\x3e\n <circle cx="256" cy="234" r="108" fill="#fff" stroke="none" mask="url(#pupil-hole-hide)"/>\n </g>\n</svg>\n'.trim()),eyeHidden:Ri('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">\n <g fill="none" stroke="#fff" stroke-linecap="round" stroke-linejoin="round">\n \x3c!-- Upper eye contour --\x3e\n <path d="M24 256 C 120 93 392 93 488 256" stroke-width="48"/>\n \x3c!-- Lower eye contour --\x3e\n <path d="M24 256 C 120 419 392 419 488 256" stroke-width="48"/>\n \x3c!-- Diagonal hide slash --\x3e\n <path d="M48 408 L464 104" stroke-width="48"/>\n </g>\n</svg>\n'.trim()),delete:ii.trim(),toggle:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor">\n <path d="M3 7.5 12 3l9 4.5L12 12 3 7.5Z" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />\n <path d="M3 12.5 12 17l9-4.5" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />\n <path d="M3 17 12 21l9-4" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />\n <polyline points="14 9.5 17 12 14 14.5" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />\n</svg>\n'.trim()};class Yi{static calculateAngle(e,t,r){const o=e.lng-t.lng,n=e.lat-t.lat,i=r.lng-t.lng,a=r.lat-t.lat,s=o*i+n*a,l=Math.sqrt(o*o+n*n),c=Math.sqrt(i*i+a*a);if(0===l||0===c)return 0;const u=s/(l*c);return Math.acos(Math.max(-1,Math.min(1,u)))}static calculateDistanceFromLine(e,t,r){const o=t.lng-e.lng,n=t.lat-e.lat,i=r.lng-e.lng,a=r.lat-e.lat,s=o*i+n*a,l=i*i+a*a;if(0===l)return Math.sqrt(o*o+n*n);const c=s/l;let u,h;c<0?(u=e.lng,h=e.lat):c>1?(u=r.lng,h=r.lat):(u=e.lng+c*i,h=e.lat+c*a);const g=t.lng-u,d=t.lat-h;return Math.sqrt(g*g+d*d)}static calculateCentroid(e){return ci.getCenter(e)}static calculateDistance(e,t){const r=e.lng-t.lng,o=e.lat-t.lat;return Math.sqrt(r*r+o*o)}static offsetPolygonCoordinates(e,t,r){return e?Array.isArray(e[0])?e.map(e=>Yi.offsetPolygonCoordinates(e,t,r)):void 0!==e.lat&&void 0!==e.lng?{lat:e.lat+t,lng:e.lng+r}:e.map(e=>Yi.offsetPolygonCoordinates(e,t,r)):e}}class Vi{static convertToCoords(e,t){const r=[];if(e.length>1&&e.length<3){const o=[];t.isWithin(s.GeoJSON.latLngsToCoords(e[e.length-1]),s.GeoJSON.latLngsToCoords(e[0]))?e.forEach(e=>{o.push(s.GeoJSON.latLngsToCoords(e))}):e.forEach(e=>{r.push([s.GeoJSON.latLngsToCoords(e)])}),o.length>=1&&r.push(o)}else if(e.length>2){const o=[];for(let n=1;n<e.length-1;n++){t.isWithin(s.GeoJSON.latLngsToCoords(e[n]),s.GeoJSON.latLngsToCoords(e[0]))?(e.forEach(e=>{o.push(s.GeoJSON.latLngsToCoords(e))}),r.push(o)):e.forEach(e=>{r.push([s.GeoJSON.latLngsToCoords(e)])})}}else r.push([s.GeoJSON.latLngsToCoords(e[0])]);return r}static offsetPolygonCoordinates(e,t,r){return Yi.offsetPolygonCoordinates(e,t,r)}static getLatLngInfoString(e){return"Latitude: "+e.lat+" Longitude: "+e.lng}static convertToLatLng(e){if("object"==typeof e&&null!==e){if("lat"in e&&"lng"in e)return oi.createLatLng(e.lat,e.lng);if("latitude"in e&&"longitude"in e)return oi.createLatLng(e.latitude,e.longitude);if("longitude"in e&&"latitude"in e)return oi.createLatLng(e.latitude,e.longitude);if("lng"in e&&"lat"in e)return oi.createLatLng(e.lat,e.lng)}if(Array.isArray(e)&&e.length>=2){const[t,r]=e;if("number"==typeof t&&"number"==typeof r){const e=Math.abs(t),o=Math.abs(r);return e>90&&o<=90?oi.createLatLng(r,t):o>90&&e<=90?oi.createLatLng(t,r):e>90||o>90?oi.createLatLng(r,t):oi.createLatLng(t,r)}}if("string"==typeof e){const t=e.trim(),r=t.match(/(\d+)°(\d+)'(?:(\d+(?:\.\d+)?)")?([NS])\s*,?\s*(\d+)°(\d+)'(?:(\d+(?:\.\d+)?)")?([EW])/i);if(r){const[,e,t,o,n,i,a,s,l]=r,c=parseFloat(e)+parseFloat(t)/60+parseFloat(o||"0")/3600,u=parseFloat(i)+parseFloat(a)/60+parseFloat(s||"0")/3600,h="S"===n.toUpperCase()?-c:c,g="W"===l.toUpperCase()?-u:u;return oi.createLatLng(h,g)}const o=t.match(/(\d+)°(\d+(?:\.\d+)?)'([NS])\s*,?\s*(\d+)°(\d+(?:\.\d+)?)'([EW])/i);if(o){const[,e,t,r,n,i,a]=o,s=parseFloat(e)+parseFloat(t)/60,l=parseFloat(n)+parseFloat(i)/60,c="S"===r.toUpperCase()?-s:s,u="W"===a.toUpperCase()?-l:l;return oi.createLatLng(c,u)}const n=t.match(/([+-]?(?:\d+(?:\.\d+)?|\.\d+))°?\s*([NS])(?:\s*,\s*|\s+)([+-]?(?:\d+(?:\.\d+)?|\.\d+))°?\s*([EW])/i);if(n){const[,e,t,r,o]=n,i=Math.abs(parseFloat(e)),a=Math.abs(parseFloat(r)),s="S"===t.toUpperCase()?-i:i,l="W"===o.toUpperCase()?-a:a;return oi.createLatLng(s,l)}const i=t.match(/([NS])\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s+([EW])\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))/i);if(i){const[,e,t,r,o]=i,n=Math.abs(parseFloat(t)),a=Math.abs(parseFloat(o)),s="S"===e.toUpperCase()?-n:n,l="W"===r.toUpperCase()?-a:a;return oi.createLatLng(s,l)}const a=t.match(/^\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*$/);if(a){const[,e,t]=a;return this.convertToLatLng([parseFloat(e),parseFloat(t)])}if(t.match(/(?:UTM\s+)?(\d+)([NS])\s+(\d+(?:\.\d+)?)\s+(\d+(?:\.\d+)?)/i))throw new Error(`UTM coordinates detected: ${t}. UTM conversion requires specialized libraries like proj4js. Please convert to decimal degrees first.`);if(t.match(/(\d+)([A-Z])\s+([A-Z]{2})\s+(\d+)\s+(\d+)/i))throw new Error(`MGRS coordinates detected: ${t}. MGRS conversion requires specialized libraries. Please convert to decimal degrees first.`);if(t.match(/^[23456789CFGHJMPQRVWX]{2,3}[23456789CFGHJMPQRVWX]{3,7}\+[23456789CFGHJMPQRVWX]{2,3}$/i))throw new Error(`Plus Code detected: ${t}. Plus Code conversion requires specialized libraries. Please convert to decimal degrees first.`)}throw new Error(`Unable to convert coordinate: ${JSON.stringify(e)}`)}static convertToLatLngArray(e){return e.map(e=>e.map(e=>e.map(e=>this.convertToLatLng(e))))}}const qi={draw:"draw",subtract:"subtract",p2p:"p2p",p2pSubtract:"p2pSubtract",deleteAll:"erase",clonePolygons:"clone"};const ji=new Set([u.SouthWest,u.South,u.SouthEast,u.East,u.NorthEast,u.North,u.NorthWest,u.West]);function Wi(e,t,r){return"number"==typeof e&&Number.isFinite(e)&&ji.has(e)?e:(console.warn(`[Leaflet.Polydraw] Invalid \`${r}\` value "${String(e)}". Using "${u[t]}" (${t}) as fallback.`),t)}function $i(e){e.markers.markerInfoIcon.position=Wi(e.markers.markerInfoIcon.position,g.markers.markerInfoIcon.position,"markers.markerInfoIcon.position"),e.markers.markerMenuIcon.position=Wi(e.markers.markerMenuIcon.position,g.markers.markerMenuIcon.position,"markers.markerMenuIcon.position"),e.markers.markerDeleteIcon.position=Wi(e.markers.markerDeleteIcon.position,g.markers.markerDeleteIcon.position,"markers.markerDeleteIcon.position")}function Ki(e){const t=Qn({},e??{});return function(e){var t,r,o,n;if(!e)return;const i=e,a=e.modes;if(a){const t=Object.keys(qi).filter(e=>void 0!==a[e]);if(t.length>0){console.warn("[Leaflet.Polydraw] `config.modes.*` tool toggles are deprecated in v2. Use `config.tools.*` (draw/subtract/p2p/clone/erase) instead."),e.tools||(e.tools={});for(const r of t){const t=qi[r];void 0===e.tools[t]&&(e.tools[t]=a[r])}}}const s=(null==(t=e.markers)?void 0:t.visualOptimization)??{};(Object.prototype.hasOwnProperty.call(s,"useAngles")||Object.prototype.hasOwnProperty.call(s,"useBoundingBox")||Object.prototype.hasOwnProperty.call(s,"useDistance")||Object.prototype.hasOwnProperty.call(s,"thresholdBoundingBox")||Object.prototype.hasOwnProperty.call(s,"thresholdDistance")||Object.prototype.hasOwnProperty.call(s,"sharpAngleThreshold"))&&console.warn("[Leaflet.Polydraw] `markers.visualOptimization` is deprecated. Prefer `visualOptimizationLevel` when adding predefined polygons.");const l=e.maxHistorySize;"number"==typeof l&&(console.warn("[Leaflet.Polydraw] `config.maxHistorySize` is deprecated in v2. Use `config.history.maxSize` instead."),e.history||(e.history={}),void 0===e.history.maxSize&&(e.history.maxSize=l));const c=e.boundingBox;c&&"boolean"==typeof c.addMidPointMarkers&&(console.warn("[Leaflet.Polydraw] `config.boundingBox` is deprecated in v2. Use `config.polygonTools.bbox` instead."),e.polygonTools||(e.polygonTools={}),e.polygonTools.bbox||(e.polygonTools.bbox={}),void 0===e.polygonTools.bbox.addMidPointMarkers&&(e.polygonTools.bbox.addMidPointMarkers=c.addMidPointMarkers));const u=e.bezier;if(u&&(void 0!==u.resolution||void 0!==u.sharpness||void 0!==u.resampleMultiplier||void 0!==u.maxNodes||void 0!==u.visualOptimizationLevel||void 0!==u.ghostMarkers)){console.warn("[Leaflet.Polydraw] `config.bezier` is deprecated in v2. Use `config.polygonTools.bezier` instead."),e.polygonTools||(e.polygonTools={}),e.polygonTools.bezier||(e.polygonTools.bezier={});const t=e.polygonTools.bezier;for(const e of Object.keys(u))void 0!==u[e]&&void 0===t[e]&&(t[e]=u[e])}const h=e.polygonCreation,g=i.polygonCreation;if(void 0!==(null==g?void 0:g.method)){console.warn("[Leaflet.Polydraw] `config.polygonCreation.method` is deprecated in v2. Use `config.polygonCreation.algorithm` instead."),e.polygonCreation||(e.polygonCreation={});const t=e.polygonCreation;void 0===t.algorithm&&(t.algorithm=g.method)}const d=i.simplification;if(void 0!==(null==d?void 0:d.mode)){console.warn("[Leaflet.Polydraw] `config.simplification.mode` is deprecated in v2. Use `config.simplification.strategy` instead."),e.simplification||(e.simplification={});const t=e.simplification;void 0===t.strategy&&(t.strategy=d.mode)}"buffer"===(null==h?void 0:h.algorithm)&&console.warn('[Leaflet.Polydraw] `polygonCreation.algorithm: "buffer"` is deprecated and no longer supported. Falling back to "concaveman". Use "concaveman" or "direct" instead.');const p=void 0!==i.polyLineOptions,f=void 0!==i.subtractLineOptions,y=void 0!==i.polygonOptions,m=void 0!==i.holeOptions,v=void 0!==i.colors;if(p||f||y||m||v){console.warn("[Leaflet.Polydraw] `polyLineOptions`, `subtractLineOptions`, `polygonOptions`, `holeOptions`, and `colors` are deprecated in v2. Use the unified `config.styles` block instead."),e.styles||(e.styles={});const t=e.styles;if(p){t.polyline||(t.polyline={});const e=i.polyLineOptions;void 0!==e.weight&&void 0===t.polyline.weight&&(t.polyline.weight=e.weight),void 0!==e.opacity&&void 0===t.polyline.opacity&&(t.polyline.opacity=e.opacity)}if(f){t.subtractLine||(t.subtractLine={});const e=i.subtractLineOptions;void 0!==e.weight&&void 0===t.subtractLine.weight&&(t.subtractLine.weight=e.weight),void 0!==e.opacity&&void 0===t.subtractLine.opacity&&(t.subtractLine.opacity=e.opacity)}if(y){t.polygon||(t.polygon={});const e=i.polygonOptions;void 0!==e.weight&&void 0===t.polygon.weight&&(t.polygon.weight=e.weight),void 0!==e.opacity&&void 0===t.polygon.opacity&&(t.polygon.opacity=e.opacity),void 0!==e.fillOpacity&&void 0===t.polygon.fillOpacity&&(t.polygon.fillOpacity=e.fillOpacity),void 0!==e.smoothFactor&&void 0===t.polygon.smoothFactor&&(t.polygon.smoothFactor=e.smoothFactor),void 0!==e.noClip&&void 0===t.polygon.noClip&&(t.polygon.noClip=e.noClip)}if(m){t.hole||(t.hole={});const e=i.holeOptions;void 0!==e.weight&&void 0===t.hole.weight&&(t.hole.weight=e.weight),void 0!==e.opacity&&void 0===t.hole.opacity&&(t.hole.opacity=e.opacity),void 0!==e.fillOpacity&&void 0===t.hole.fillOpacity&&(t.hole.fillOpacity=e.fillOpacity)}if(v){const e=i.colors;if(void 0!==e.polyline&&(t.polyline||(t.polyline={}),void 0===t.polyline.color&&(t.polyline.color=e.polyline)),void 0!==e.subtractLine&&(t.subtractLine||(t.subtractLine={}),void 0===t.subtractLine.color&&(t.subtractLine.color=e.subtractLine)),e.polygon&&(t.polygon||(t.polygon={}),void 0!==e.polygon.border&&void 0===t.polygon.color&&(t.polygon.color=e.polygon.border),void 0!==e.polygon.fill&&void 0===t.polygon.fillColor&&(t.polygon.fillColor=e.polygon.fill)),e.hole&&(t.hole||(t.hole={}),void 0!==e.hole.border&&void 0===t.hole.color&&(t.hole.color=e.hole.border),void 0!==e.hole.fill&&void 0===t.hole.fillColor&&(t.hole.fillColor=e.hole.fill)),e.styles){t.ui||(t.ui={});const r=e.styles,o=t.ui;r.controlButton&&!o.controlButton&&(o.controlButton=r.controlButton),r.controlButtonHover&&!o.controlButtonHover&&(o.controlButtonHover=r.controlButtonHover),r.controlButtonActive&&!o.controlButtonActive&&(o.controlButtonActive=r.controlButtonActive),r.indicatorActive&&!o.indicatorActive&&(o.indicatorActive=r.indicatorActive),r.p2pMarker&&!o.p2pMarker&&(o.p2pMarker=r.p2pMarker)}void 0!==(null==(r=e.p2p)?void 0:r.closingMarker)&&(t.ui||(t.ui={}),t.ui.p2pClosingMarker||(t.ui.p2pClosingMarker={color:e.p2p.closingMarker})),void 0!==e.edgeHover&&(t.ui||(t.ui={}),t.ui.edgeHover||(t.ui.edgeHover={color:e.edgeHover})),void 0!==(null==(o=e.edgeDeletion)?void 0:o.hover)&&(t.ui||(t.ui={}),t.ui.edgeDeletion||(t.ui.edgeDeletion={color:e.edgeDeletion.hover})),void 0!==(null==(n=e.dragPolygons)?void 0:n.subtract)&&(t.ui||(t.ui={}),t.ui.dragSubtract||(t.ui.dragSubtract={color:e.dragPolygons.subtract}))}}void 0!==i.defaultMode&&(console.warn("[Leaflet.Polydraw] `config.defaultMode` is deprecated in v2. Use `config.tools.default` instead."),e.tools||(e.tools={}),void 0===e.tools.default&&(e.tools.default=i.defaultMode)),void 0!==i.dragPolygons&&(console.warn("[Leaflet.Polydraw] `config.dragPolygons` is deprecated in v2. Use `config.interaction.drag` instead."),e.interaction||(e.interaction={}),e.interaction.drag||(e.interaction.drag=i.dragPolygons)),void 0!==i.edgeDeletion&&(console.warn("[Leaflet.Polydraw] `config.edgeDeletion` is deprecated in v2. Use `config.interaction.edgeDeletion` instead."),e.interaction||(e.interaction={}),e.interaction.edgeDeletion||(e.interaction.edgeDeletion=i.edgeDeletion)),void 0!==i.menuOperations&&(console.warn("[Leaflet.Polydraw] `config.menuOperations` is deprecated in v2. Use `config.polygonTools` instead."),e.polygonTools||(e.polygonTools=i.menuOperations))}(t),t}class Ji extends s.Control{constructor(e){super(e),i(this,"map"),i(this,"tracer",null),i(this,"turfHelper"),i(this,"subContainer"),i(this,"config"),i(this,"mapStateService"),i(this,"eventManager"),i(this,"polygonInformation"),i(this,"modeManager"),i(this,"polygonDrawManager"),i(this,"polygonMutationManager"),i(this,"historyManager"),i(this,"layerManager"),i(this,"layerPanel",null),i(this,"arrayOfFeatureGroups",[]),i(this,"drawMode",c.Off),i(this,"drawModeListeners",[]),i(this,"_boundKeyDownHandler"),i(this,"_boundKeyUpHandler"),i(this,"isModifierKeyHeld",!1),i(this,"modifierModeOverride",null),i(this,"isDrawingInProgress",!1),i(this,"mapEventsAttached",!1),i(this,"drawEventsAttached",!1),i(this,"controlEvents",new WeakSet),i(this,"lastControlPointerDown",null),i(this,"_boundTouchMove"),i(this,"_boundTouchEnd"),i(this,"_boundTouchStart"),i(this,"_boundPointerDown"),i(this,"_boundPointerMove"),i(this,"_boundPointerUp"),i(this,"_lastTapTime",0),i(this,"_lastTapLatLng",null),i(this,"_tapTimeout",null),i(this,"pointerEventsHandled","undefined"!=typeof window&&"PointerEvent"in window&&ri.isV2()),i(this,"_configReady",null),i(this,"_componentsInitialized",!1),i(this,"_isControlMounted",!1),i(this,"_isRestoringSnapshot",!1),i(this,"_coreEventListenersAttached",!1),i(this,"_coreEventSubscriptions",[]),i(this,"_initRequestId",0),i(this,"_historySuppressionDepth",0),i(this,"_lastAppliedVisibleMapOrder",[]),i(this,"_handleActivateToggle",()=>{const e=this.getContainer();if(!e)return;const t=e.querySelector(".icon-activate");if(oi.domUtil.hasClass(t,"active"))oi.domUtil.removeClass(t,"active"),this.subContainer&&(this.subContainer.style.maxHeight="0px",this.subContainer.style.overflow="hidden");else if(oi.domUtil.addClass(t,"active"),this.subContainer){const e=this.subContainer.scrollHeight;this.subContainer.style.maxHeight=`${e||250}px`,this.subContainer.style.overflow="visible"}this.updateActivateButtonIndicator()}),i(this,"_handleDrawClick",e=>{e&&(e.preventDefault(),e.stopPropagation()),this.modeManager.getCurrentMode()!==c.Add?(this.setDrawMode(c.Add),this.polygonInformation.saveCurrentState()):this.setDrawMode(c.Off)}),i(this,"_handleSubtractClick",e=>{e&&(e.preventDefault(),e.stopPropagation()),this.modeManager.getCurrentMode()!==c.Subtract?(this.setDrawMode(c.Subtract),this.polygonInformation.saveCurrentState()):this.setDrawMode(c.Off)}),i(this,"_handleCloneClick",e=>{e&&(e.preventDefault(),e.stopPropagation()),0!==this.arrayOfFeatureGroups.length&&(this.modeManager.getCurrentMode()!==c.Clone?(this.setDrawMode(c.Clone),this.polygonInformation.saveCurrentState()):this.setDrawMode(c.Off))}),i(this,"_handleEraseClick",e=>{e&&(e.preventDefault(),e.stopPropagation());const t=this.config.tools.eraseScope??"all";0!==("defaultLayer"===t?this.layerManager.getFeatureGroupsForLayer("default"):this.arrayOfFeatureGroups).length&&(this.map.closePopup(),this.saveHistory("eraseAll"),"defaultLayer"!==t?this.removeAllFeatureGroups():this.removeDefaultLayerFeatureGroups())}),i(this,"_handlePointToPointClick",e=>{e&&(e.preventDefault(),e.stopPropagation()),this.modeManager.getCurrentMode()!==c.PointToPoint?(this.setDrawMode(c.PointToPoint),this.polygonInformation.saveCurrentState()):this.setDrawMode(c.Off)}),i(this,"_handlePointToPointSubtractClick",e=>{e&&(e.preventDefault(),e.stopPropagation()),this.modeManager.getCurrentMode()!==c.PointToPointSubtract?(this.setDrawMode(c.PointToPointSubtract),this.polygonInformation.saveCurrentState()):this.setDrawMode(c.Off)}),i(this,"_handleUndoClick",e=>{e&&(e.preventDefault(),e.stopPropagation()),this.undo()}),i(this,"_handleRedoClick",e=>{e&&(e.preventDefault(),e.stopPropagation()),this.redo()}),i(this,"onMarkerHoverForEdgeDeletionEvent",e=>{if(!this.isModifierKeyHeld)return;const t=e.target;t&&(t.style.backgroundColor=this.config.styles.ui.edgeDeletion.color,t.style.borderColor=this.config.styles.ui.edgeDeletion.color,t.classList.add("edge-deletion-hover"))}),i(this,"onMarkerLeaveForEdgeDeletionEvent",e=>{const t=e.target;t&&(t.style.backgroundColor="",t.style.borderColor="",t.classList.remove("edge-deletion-hover"))});const t=structuredClone(g),r=Ki(null==e?void 0:e.config);this.config=Qn(t,r),$i(this.config),(null==e?void 0:e.configPath)?this._configReady=this.loadExternalConfig(e.configPath,r):(this.initializeComponents(),this._configReady=Promise.resolve())}onAdd(e){const t=e,r=s.Browser;t._onResize=()=>{},r.touch&&r.mobile&&(t.tap=!1),this.map=e,this._isControlMounted=!0;const o=++this._initRequestId;this.setupKeyboardHandlers();const n=oi.domUtil.create("div","leaflet-control leaflet-bar");return this.initializeUI(n),this.createTracer(),this.completeInitialization(o),n}completeInitialization(e){var t;const r=()=>{this._isControlMounted&&e===this._initRequestId&&(this.initializeManagers(),this.setDrawMode(this.config.tools.default),this.setupEventListeners())};this._componentsInitialized?r():null==(t=this._configReady)||t.then(()=>{r()}).catch(()=>{})}onRemove(e){this._isControlMounted=!1,this._initRequestId+=1,this.comprehensiveCleanup()}comprehensiveCleanup(){if(this.events(!1),this.drawStartedEvents(!1),this.removeKeyboardHandlers(),this.tracer){try{this.map.hasLayer(this.tracer)?this.map.removeLayer(this.tracer):this.tracer.remove()}catch{}this.tracer=null}if(this.arrayOfFeatureGroups.forEach(e=>{try{this.polygonMutationManager&&this.polygonMutationManager.cleanupFeatureGroup(e),this.map.removeLayer(e)}catch(t){console.warn("Error cleaning up feature group:",t)}}),this.arrayOfFeatureGroups.length=0,this._lastAppliedVisibleMapOrder=[],this.polygonMutationManager&&this.polygonMutationManager.dispose(),this.removeCoreEventListeners(),this.polygonInformation&&this.polygonInformation.deletePolygonInformationStorage(),this.drawModeListeners.length=0,this._boundKeyDownHandler&&(this._boundKeyDownHandler=void 0),this._boundKeyUpHandler&&(this._boundKeyUpHandler=void 0),this._boundTouchMove&&(this._boundTouchMove=void 0),this._boundTouchEnd&&(this._boundTouchEnd=void 0),this._boundTouchStart&&(this._boundTouchStart=void 0),this._boundPointerDown&&(this._boundPointerDown=void 0),this._boundPointerMove&&(this._boundPointerMove=void 0),this._boundPointerUp&&(this._boundPointerUp=void 0),this._tapTimeout&&(clearTimeout(this._tapTimeout),this._tapTimeout=null),this.drawMode=c.Off,this.isModifierKeyHeld=!1,this._lastTapTime=0,this.layerPanel){try{this.layerPanel.remove()}catch{}this.layerPanel=null}this.subContainer=void 0,this._componentsInitialized=!1}addTo(e){return super.addTo(e),this}getFeatureGroups(){return this.arrayOfFeatureGroups}async undo(){if(!this.historyManager.canUndo())return;const e=this.historyManager.undo(this.arrayOfFeatureGroups,this.layerManager);e&&await this.restoreFromSnapshot(e)}isPolygonAction(e){return"simplify"===e||"doubleElbows"===e||"bbox"===e||"bezier"===e||"scale"===e||"rotate"===e||"donut"===e||"toggleOptimization"===e||"polygonMenuAction"===e}shouldCaptureHistory(e){var t,r;const o=null==(t=this.config.history)?void 0:t.capture;return!o||(this.isPolygonAction(e)?!1!==(null==(r=o.polygonActions)?void 0:r[e]):!1!==o[e])}saveHistory(e){this.isHistorySuppressed()||this.shouldCaptureHistory(e)&&this.historyManager.saveState(this.arrayOfFeatureGroups,e,this.layerManager)}isHistorySuppressed(){return this._historySuppressionDepth>0}startHistoryBatch(e){this.isHistorySuppressed()||this.saveHistory(e),this._historySuppressionDepth+=1}endHistoryBatch(){this._historySuppressionDepth>0&&(this._historySuppressionDepth-=1)}async redo(){if(!this.historyManager.canRedo())return;const e=this.historyManager.redo(this.arrayOfFeatureGroups,this.layerManager);e&&await this.restoreFromSnapshot(e)}resolvePredefinedLayerDescriptor(e,t){if(!e)return null;if("string"==typeof e){const r=e.trim();if(!r)throw new Error("Layer id cannot be empty");return{id:r,color:t}}const r=(e.id||"").trim();if(!r)throw new Error("Layer descriptor must include a non-empty id");const o={...e,id:r,color:t??e.color};return"static"===o.interaction&&void 0===o.panel&&(o.panel="hidden"),o}ensureLayerFromDescriptor(e){const t=e.id.trim(),r=this.layerManager.getOrCreateLayer(t,{label:e.label,color:e.color,visible:e.visibility,interaction:e.interaction,panel:e.panel??("static"===e.interaction?"hidden":void 0),metadata:e.metadata});return void 0!==e.label&&this.layerManager.setLayerLabel(t,e.label),e.color&&this.layerManager.setLayerColor(t,e.color),void 0!==e.visibility&&this.layerManager.setLayerVisibility(t,e.visibility),void 0!==e.interaction&&this.layerManager.setLayerInteraction(t,e.interaction),void 0===e.panel&&"static"!==e.interaction||this.layerManager.setLayerPanelVisibility(t,e.panel??("static"===e.interaction?"hidden":"visible")),void 0!==e.metadata&&this.layerManager.setLayerMetadata(t,e.metadata),this.layerManager.getLayer(t)??r}getInteractionTargetLayerId(){if(!this.layerManager)return;const e=this.layerManager.getActiveLayerId();if(this.layerManager.isLayerEditable(e))return e;if(this.layerManager.isLayerEditable("default"))return"default";const t=this.layerManager.getAllLayers().find(e=>"editable"===e.interaction);return null==t?void 0:t.id}ensureFeatureGroupMetadata(e){const t=e;if(t._polydrawMetadata)return t._polydrawMetadata;let r=0,o=0;e.eachLayer(e=>{if(e instanceof s.Polygon&&!(e instanceof s.Rectangle)){const t=e;"number"==typeof t._polydrawOptimizationLevel&&(r=t._polydrawOptimizationLevel),"number"==typeof t._polydrawOptimizationOriginalLevel&&(o=t._polydrawOptimizationOriginalLevel)}});const n=new Date,i=`fg-${oi.util.stamp(e)}`;return t._polydrawMetadata={id:i,optimizationLevel:r,originalOptimizationLevel:o,hasHoles:!1,createdAt:n,lastModified:n,metadata:{},sourceFeatureIds:[i]},t._polydrawMetadata}async addPredefinedPolygon(e,t){var r,o,n;const i=Vi.convertToLatLngArray(e);if(!i||0===i.length)throw new Error("Cannot add empty polygon array");if(!this.map)throw new Error("Map not initialized");if(!this.polygonMutationManager)throw new Error("PolygonMutationManager not initialized");if(!this.layerManager)throw new Error("LayerManager not initialized");for(const[p,f]of i.entries())if(!f||!f[0]||f[0].length<4)throw new Error(`Invalid polygon data at index ${p}: A polygon must have at least 3 unique vertices.`);const a=(null==t?void 0:t.visualOptimizationLevel)??0,s=(null==(r=null==t?void 0:t.overrides)?void 0:r.interaction)&&"inherit"!==t.overrides.interaction?t.overrides.interaction:void 0,l=(null==(o=null==t?void 0:t.overrides)?void 0:o.style)?{...t.overrides.style}:void 0,c=(null==(n=null==t?void 0:t.overrides)?void 0:n.merge)??"inherit";let u,h,g=!1;if(null==t?void 0:t.layer){const e=this.resolvePredefinedLayerDescriptor(t.layer,t.layerColor);if(e){const t=this.ensureLayerFromDescriptor(e);u=t.id,h=t.color,g="editable"!==t.interaction}this.updateLayerPanel()}else(null==t?void 0:t.layerColor)&&(h=t.layerColor);this.startHistoryBatch("addPredefinedPolygon");try{for(const e of i)try{const r=e.map(e=>e.map(e=>[e.lng,e.lat])),o=this.turfHelper.getMultiPolygon([r]),n="allow"!==c&&("block"===c||g),i=await this.polygonMutationManager.addPolygon(o,{simplify:!1,noMerge:n,mergeEditableOnly:"allow"!==c,visualOptimizationLevel:a,targetLayerId:u,layerColor:h,featureMetadata:null==t?void 0:t.metadata,featureInteractionOverride:s,featureStyleOverrides:l});if(!i.success)throw console.error("Error adding polygon via manager:",i.error),new Error(i.error||"Failed to add polygon");this.polygonInformation.createPolygonInformationStorage(this.arrayOfFeatureGroups)}catch(d){throw console.error("Error adding auto polygon:",d),d}}finally{this.endHistoryBatch()}}async addPredefinedGeoJSONs(e,t){if(!Array.isArray(e)||0===e.length)throw new Error("Cannot add empty GeoJSON feature array");this.startHistoryBatch("addPredefinedPolygon");try{for(const r of e){const{type:e,coordinates:o}=r.geometry,n=(null==t?void 0:t.metadata)??(r.properties?{...r.properties}:void 0),i={...t,metadata:n};if("MultiPolygon"===e)for(const t of o){const e=t.map(e=>e.map(e=>oi.createLatLng(e[1],e[0])));await this.addPredefinedPolygon([e],i)}else if("Polygon"===e){const e=o.map(e=>e.map(e=>oi.createLatLng(e[1],e[0])));await this.addPredefinedPolygon([e],i)}}}finally{this.endHistoryBatch()}}async addPredefinedPolygonGroups(e){if(!Array.isArray(e)||0===e.length)throw new Error("Cannot add empty polygon group array");if(!this.layerManager)throw new Error("LayerManager not initialized");this.startHistoryBatch("addPredefinedPolygon");try{const t=e.map(e=>{const t=this.resolvePredefinedLayerDescriptor(e.layer);if(!t)throw new Error("Polygon group layer descriptor is missing");return{descriptor:t,polygons:e.polygons,options:e.options}});for(const e of t)this.ensureLayerFromDescriptor(e.descriptor);for(const e of t)for(const t of e.polygons)await this.addPredefinedPolygon(t,{layer:e.descriptor,...e.options})}finally{this.endHistoryBatch()}this.updateLayerPanel()}getLayerManager(){return this.layerManager}getAllLayers(){return this.layerManager.getAllLayers()}getLayerById(e){return this.layerManager.getLayer(e)}hasLayer(e){return!!this.layerManager.getLayer(e)}getActiveLayer(){return this.layerManager.getActiveLayer()}getFeatureGroupsByLayer(e){return this.layerManager.getFeatureGroupsForLayer(e)}createLayer(e){const t=(e.id||"").trim();if(!t)throw new Error("Layer id cannot be empty");if(this.layerManager.getLayer(t))throw new Error(`Layer "${t}" already exists`);return this.ensureLayer(e)}ensureLayer(e){const t=this.ensureLayerFromDescriptor(e);return this.updateLayerPanel(),this.updateMarkerDraggableState(),t}updateLayer(e,t){if(!this.layerManager.getLayer(e))return;let r=!1;return"label"in t&&(r=this.layerManager.setLayerLabel(e,t.label)||r),"string"==typeof t.color&&(r=this.layerManager.setLayerColor(e,t.color)||r),"boolean"==typeof t.visibility&&(r=this.layerManager.setLayerVisibility(e,t.visibility)||r),void 0!==t.interaction&&(r=this.layerManager.setLayerInteraction(e,t.interaction)||r,"static"===t.interaction&&void 0===t.panel&&(r=this.layerManager.setLayerPanelVisibility(e,"hidden")||r)),void 0!==t.panel&&(r=this.layerManager.setLayerPanelVisibility(e,t.panel)||r),void 0!==t.metadata&&(r=this.layerManager.setLayerMetadata(e,t.metadata)||r),r&&(this.updateLayerPanel(),this.updateMarkerDraggableState(),this.syncFeatureGroupOrderWithLayers()),this.layerManager.getLayer(e)}deleteLayer(e){const t=(e||"").trim();if(!t||!this.layerManager.getLayer(t))return{success:!1,layerId:t,removedFeatureGroups:0,reason:"not-found"};if("default"===t)return{success:!1,layerId:t,removedFeatureGroups:0,reason:"default-layer"};this.saveHistory("layerDelete");return{success:!0,layerId:t,removedFeatureGroups:this.layerManager.deleteLayer(t).length}}setActiveLayer(e){return this.layerManager.setActiveLayer(e)}setLayerVisibility(e,t){return this.layerManager.setLayerVisibility(e,t)}showLayer(e){return this.setLayerVisibility(e,!0)}hideLayer(e){return this.setLayerVisibility(e,!1)}setLayerColor(e,t){return this.layerManager.setLayerColor(e,t)}setLayerInteraction(e,t){const r=this.layerManager.setLayerInteraction(e,t);return r&&(this.updateMarkerDraggableState(),this.updateLayerPanel()),r}setLayerPanelVisibility(e,t){const r=this.layerManager.setLayerPanelVisibility(e,t);return r&&this.updateLayerPanel(),r}setLayerMetadata(e,t){return this.layerManager.setLayerMetadata(e,t)}patchLayerMetadata(e,t){const r=this.layerManager.getLayer(e);return!!r&&this.layerManager.setLayerMetadata(e,{...r.metadata,...t})}getFeatureMetadata(e){const t=e._polydrawMetadata;if(null==t?void 0:t.metadata)return yi(t.metadata)}setFeatureMetadata(e,t){if(!e)return!1;const r=this.ensureFeatureGroupMetadata(e);return r.metadata=yi(t),r.lastModified=new Date,!0}patchFeatureMetadata(e,t){if(!e)return!1;const r=this.getFeatureMetadata(e)??{};return this.setFeatureMetadata(e,{...r,...t})}reorderLayer(e,t){if("default"===e||"default"===t)return!1;const r=this.layerManager.getAllLayers().map(e=>e.id),o=r.indexOf(e),n=r.indexOf(t);return!(o<0||n<0||o===n)&&(this.saveHistory("layerReorder"),this.layerManager.moveLayer(e,t))}getActiveLayerId(){return this.layerManager.getActiveLayerId()}getLayerForFeatureGroup(e){return this.layerManager.getLayerForFeatureGroup(e)}assignFeatureGroupToLayer(e,t){const r=(t||"").trim();if(!e||!r)return!1;if(!this.layerManager.getLayer(r))return!1;if(this.layerManager.getLayerForFeatureGroup(e)===r)return!1;this.saveHistory("layerReorder");const o=this.layerManager.assignFeatureGroupToLayer(e,r);return o&&this.refreshAfterLayerStructureChange(),o}moveFeatureGroupToLayer(e,t){return this.assignFeatureGroupToLayer(e,t)}removeFeatureGroupFromLayer(e){e&&this.layerManager.getLayerForFeatureGroup(e)&&(this.saveHistory("layerReorder"),this.layerManager.removeFeatureGroupFromLayer(e),this.refreshAfterLayerStructureChange())}clearLayers(){const e=this.layerManager.getAllLayers().filter(e=>"default"!==e.id).map(e=>e.id);if(0===e.length)return;this.saveHistory("layerDelete");const t=[];for(const r of e)t.push(...this.layerManager.deleteLayer(r));t.length>0?this.removeFeatureGroupsFromMap(t):this.updateLayerPanel()}moveLayerToIndex(e,t){const r=(e||"").trim();if("default"===r||!Number.isFinite(t))return!1;const o=this.layerManager.getAllLayers().map(e=>e.id),n=o.indexOf(r);if(n<0)return!1;return n!==Math.max(1,Math.min(Math.trunc(t),o.length-1))&&(this.saveHistory("layerReorder"),this.layerManager.moveLayerToIndex(r,t))}setLayerOrder(e){if(!e||0===e.length)return!1;const t=this.layerManager.getAllLayers().map(e=>e.id),r=e.map(e=>(e||"").trim());if(r.some(e=>0===e.length||"default"===e))return!1;if(new Set(r).size!==r.length)return!1;if(r.some(e=>!t.includes(e)))return!1;const o=new Set(r),n=["default",...r,...t.filter(e=>"default"!==e&&!o.has(e))];return(t.length!==n.length||!t.every((e,t)=>e===n[t]))&&(this.saveHistory("layerReorder"),this.layerManager.setLayerOrder(r))}refreshAfterLayerStructureChange(){this.syncFeatureGroupOrderWithLayers(),this.polygonInformation.deletePolygonInformationStorage(),this.polygonInformation.createPolygonInformationStorage(this.arrayOfFeatureGroups),this.updateMarkerDraggableState(),this.updateLayerPanel()}beginBatch(e="batch"){this.startHistoryBatch(e)}endBatch(){this.endHistoryBatch()}setDrawMode(e,t){const r=this.drawMode;this._updateDrawModeState(e);if(!((null==t?void 0:t.preserveActiveDraw)&&this.isDrawingInProgress&&(r===c.Add&&e===c.Subtract||r===c.Subtract&&e===c.Add))){(e===c.PointToPoint||e===c.PointToPointSubtract)&&r!==c.PointToPoint&&r!==c.PointToPointSubtract&&this.isDrawingInProgress&&this.stopDraw(),r!==c.PointToPoint&&r!==c.PointToPointSubtract||e===c.PointToPoint||e===c.PointToPointSubtract?(e===c.Off||e!==c.PointToPoint&&e!==c.PointToPointSubtract)&&this.stopDraw():(this.polygonDrawManager.clearP2pMarkers(),this.stopDraw())}this.map&&(this._updateUIAfterDrawModeChange(e),this._updateMapInteractions())}getDrawMode(){return this.modeManager.getCurrentMode()}on(e,t){this.eventManager.on(e,t)}off(e,t){this.eventManager.off(e,t)}removeAllFeatureGroups(){this.removeFeatureGroupsFromMap([...this.arrayOfFeatureGroups],{clearLayerState:!0})}removeDefaultLayerFeatureGroups(){this.removeFeatureGroupsFromMap(this.layerManager.getFeatureGroupsForLayer("default"))}removeFeatureGroupsFromMap(e,t={}){0!==e.length&&(e.forEach(e=>{var t;try{this.polygonMutationManager&&this.polygonMutationManager.cleanupFeatureGroup(e),this.map.removeLayer(e)}catch{}const r=this.arrayOfFeatureGroups.indexOf(e);-1!==r&&this.arrayOfFeatureGroups.splice(r,1),null==(t=this.layerManager)||t.removeFeatureGroupFromLayer(e)}),this._lastAppliedVisibleMapOrder=[],t.clearLayerState&&this.layerManager&&this.layerManager.clear(this.config.styles.polygon.color),this.polygonInformation.deletePolygonInformationStorage(),this.polygonInformation.updatePolygons(),this.updateActivateButtonIndicator(),this.updateLayerPanel(),this.eventManager.emit("polydraw:polygon:deleted",void 0))}cleanup(){this.map&&this.comprehensiveCleanup()}initializeUI(e){!function(e){const t=document.createElement("style");t.innerHTML=`\n .leaflet-control a { background-color: ${e.styles.ui.controlButton.backgroundColor}; color: ${e.styles.ui.controlButton.color}; display: flex; align-items: center; justify-content: center; }\n .leaflet-control a:hover { background-color: ${e.styles.ui.controlButtonHover.backgroundColor}; }\n .leaflet-control a.active { background-color: ${e.styles.ui.controlButtonActive.backgroundColor}; color: ${e.styles.ui.controlButtonActive.color}; }\n .polydraw-indicator-active { background-color: ${e.styles.ui.indicatorActive.backgroundColor} !important; }\n .crosshair-cursor-enabled { cursor: crosshair !important; }\n .crosshair-cursor-enabled * { cursor: crosshair !important; }\n .leaflet-polydraw-p2p-marker { background-color: ${e.styles.ui.p2pMarker.backgroundColor}; border: 2px solid ${e.styles.ui.p2pMarker.borderColor}; border-radius: 50%; box-sizing: border-box; }\n .leaflet-polydraw-p2p-marker[data-p2p-mode="subtract"] { background-color: ${e.styles.ui.dragSubtract.color}; border-color: ${e.styles.ui.dragSubtract.color}; }\n .leaflet-polydraw-p2p-first-marker { position: relative; }\n .leaflet-polydraw-p2p-first-marker:hover { transform: scale(1.5); transition: all 0.2s ease; }\n .leaflet-polydraw-p2p-first-marker-ready[data-p2p-mode="add"]:hover { background-color: ${e.styles.ui.p2pClosingMarker.color}; border-color: ${e.styles.ui.p2pClosingMarker.color}; cursor: pointer; }\n .leaflet-polydraw-p2p-first-marker-ready[data-p2p-mode="subtract"]:hover { background-color: ${e.styles.ui.dragSubtract.color}; border-color: ${e.styles.ui.dragSubtract.color}; cursor: pointer; }\n `,document.head.appendChild(t)}(this.config),s.DomEvent.disableClickPropagation(e),s.DomEvent.on(e,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(e,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(e,"pointerdown",s.DomEvent.stopPropagation),s.DomEvent.on(e,"pointerup",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stopPropagation);const t=e=>{this.controlEvents.add(e),this.markControlPointerDown(e)},r=e=>{this.clearControlPointerDown(e)};this.pointerEventsHandled?(e.addEventListener("pointerdown",t,{capture:!0,passive:!0}),e.addEventListener("pointerup",r,{capture:!0,passive:!0}),e.addEventListener("pointercancel",r,{capture:!0,passive:!0})):(e.addEventListener("mousedown",t,{capture:!0,passive:!0}),e.addEventListener("mouseup",r,{capture:!0,passive:!0}),e.addEventListener("touchstart",t,{capture:!0,passive:!0}),e.addEventListener("touchend",r,{capture:!0,passive:!0}),e.addEventListener("touchcancel",r,{capture:!0,passive:!0})),e.style.display="flex",e.style.flexDirection="column-reverse",e.style.pointerEvents="auto",e.style.position="relative",e.style.zIndex="1000";const o=this.config.tooltips;if(o){const t=Math.max(0,o.delayMs);e.setAttribute("data-tooltip-enabled",o.enabled?"true":"false"),e.setAttribute("data-tooltip-direction",o.direction),e.style.setProperty("--polydraw-tooltip-bg",o.backgroundColor),e.style.setProperty("--polydraw-tooltip-color",o.color),e.style.setProperty("--polydraw-tooltip-delay",`${t}ms`)}this.subContainer=oi.domUtil.create("div","sub-buttons",e),this.subContainer.setAttribute("data-polydraw","sub-buttons"),this.subContainer.style.maxHeight="0px",this.subContainer.style.overflow="hidden",this.subContainer.style.transition="max-height 0.3s ease",this.subContainer.style.pointerEvents="auto",this.subContainer.style.position="relative",this.eventManager||(this.eventManager=new di),this.historyManager||(this.historyManager=new Ni(this.eventManager,this.config.history.maxSize)),function(e,t,r,o,n,i,a,l,c,u,h,g,d,p){const f=oi.domUtil.create("a","icon-activate",e);if(f.href="#",li(f,"Activate"),f.setAttribute("data-polydraw","activate-button"),si(f,ai.activate),f.dataset.activeIcon=ai.activate,f.dataset.collapsedIcon=ai.collapse,s.DomEvent.on(f,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(f,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(f,"click",s.DomEvent.stop).on(f,"click",o),r.tools.draw){const e=oi.domUtil.create("a","icon-draw",t);e.href="#",li(e,"Draw"),e.setAttribute("data-polydraw","draw-button"),si(e,ai.draw),s.DomEvent.on(e,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(e,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stop),s.DomEvent.on(e,"click",n)}if(r.tools.subtract){const e=oi.domUtil.create("a","icon-subtract",t);e.href="#",li(e,"Subtract"),e.setAttribute("data-polydraw","subtract-button"),si(e,ai.subtract),s.DomEvent.on(e,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(e,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stop),s.DomEvent.on(e,"click",i)}if(r.tools.p2p){const e=oi.domUtil.create("a","icon-p2p",t);e.href="#",li(e,"Point to Point"),e.setAttribute("data-polydraw","p2p-button"),si(e,ai.p2p),s.DomEvent.on(e,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(e,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stop),s.DomEvent.on(e,"click",c)}if(r.tools.p2pSubtract){const e=oi.domUtil.create("a","icon-p2p-subtract",t);e.href="#",li(e,"Point to Point Subtract"),e.setAttribute("data-polydraw","p2p-subtract-button"),si(e,ai.p2pSubtract),s.DomEvent.on(e,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(e,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stop),s.DomEvent.on(e,"click",u)}if(r.tools.clone){const e=oi.domUtil.create("a","icon-clone",t);e.href="#",li(e,"Clone"),e.setAttribute("data-polydraw","clone-button"),si(e,ai.clone),s.DomEvent.on(e,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(e,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stop),s.DomEvent.on(e,"click",a)}if(r.tools.erase){const e=oi.domUtil.create("a","icon-erase",t);e.href="#",li(e,"Erase All"),e.setAttribute("data-polydraw","erase-button"),si(e,ai.erase),s.DomEvent.on(e,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(e,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stop),s.DomEvent.on(e,"click",l)}const y=oi.domUtil.create("a","icon-undo",t);y.href="#",li(y,"Undo (Ctrl+Z / Cmd+Z)"),si(y,ai.undo),s.DomEvent.on(y,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(y,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(y,"click",s.DomEvent.stopPropagation),s.DomEvent.on(y,"click",s.DomEvent.stop),s.DomEvent.on(y,"click",h);const m=oi.domUtil.create("a","icon-redo",t);m.href="#",li(m,"Redo (Ctrl+Y / Cmd+Shift+Z)"),si(m,ai.redo),s.DomEvent.on(m,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(m,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(m,"click",s.DomEvent.stopPropagation),s.DomEvent.on(m,"click",s.DomEvent.stop),s.DomEvent.on(m,"click",g);const v=(e,t)=>{e?(y.style.opacity="1",y.style.pointerEvents="auto"):(y.style.opacity="0.3",y.style.pointerEvents="none"),t?(m.style.opacity="1",m.style.pointerEvents="auto"):(m.style.opacity="0.3",m.style.pointerEvents="none")};d.on("polydraw:history:changed",e=>{v(e.canUndo,e.canRedo)}),d.on("polydraw:history:undo",e=>{v(e.canUndo,e.canRedo)}),d.on("polydraw:history:redo",e=>{v(e.canUndo,e.canRedo)}),v(p.canUndo(),p.canRedo())}(e,this.subContainer,this.config,this._handleActivateToggle,this._handleDrawClick,this._handleSubtractClick,this._handleCloneClick,this._handleEraseClick,this._handlePointToPointClick,this._handlePointToPointSubtractClick,this._handleUndoClick,this._handleRedoClick,this.eventManager,this.historyManager),this.ensureButtonTouchResponsiveness(e),this.updateActivateButtonIndicator();this.drawModeListeners.push(t=>{const r=e.querySelector(".icon-draw"),o=e.querySelector(".icon-subtract"),n=e.querySelector(".icon-p2p"),i=e.querySelector(".icon-p2p-subtract"),a=e.querySelector(".icon-clone");r&&r.classList.toggle("active",t===c.Add),o&&o.classList.toggle("active",t===c.Subtract),n&&n.classList.toggle("active",t===c.PointToPoint),i&&i.classList.toggle("active",t===c.PointToPointSubtract),a&&a.classList.toggle("active",t===c.Clone)})}addCoreEventListener(e,t){this.eventManager.on(e,t),this._coreEventSubscriptions.push({event:e,callback:t})}removeCoreEventListeners(){if(this.eventManager){for(const e of this._coreEventSubscriptions)this.eventManager.off(e.event,e.callback);this._coreEventSubscriptions.length=0,this._coreEventListenersAttached=!1}else this._coreEventListenersAttached=!1}setupEventListeners(){this._coreEventListenersAttached||(this._coreEventListenersAttached=!0,this.addCoreEventListener("polygonOperationComplete",()=>{this.updateActivateButtonIndicator(),this.modeManager.updateStateForMode(c.Off),this.drawMode=c.Off,this.emitDrawModeChanged(),this.updateMarkerDraggableState();const e=this.modeManager.shouldShowCrosshairCursor(),t=this.modeManager.canPerformAction("mapDrag"),r=this.modeManager.canPerformAction("mapZoom"),o=this.modeManager.canPerformAction("mapDoubleClickZoom");e?oi.domUtil.addClass(this.map.getContainer(),"crosshair-cursor-enabled"):oi.domUtil.removeClass(this.map.getContainer(),"crosshair-cursor-enabled"),this.events(!1),this.setLeafletMapEvents(t,o,r),this.applyTracerStyle(c.Off),this.syncFeatureGroupOrderWithLayers(),this.cleanupEmptyLayers()}),this.addCoreEventListener("polygonDeleted",()=>{this.updateActivateButtonIndicator(),this.cleanupEmptyLayers()}),this.addCoreEventListener("polydraw:polygon:created",async e=>{this.stopDraw();const t=this.getInteractionTargetLayerId();e.isPointToPoint?(this.saveHistory("pointToPoint"),e.mode===c.PointToPointSubtract?await this.polygonMutationManager.subtractPolygon(e.polygon,{simplify:!1,targetLayerId:t}):await this.polygonMutationManager.addPolygon(e.polygon,{simplify:!1,noMerge:!1,targetLayerId:t})):await this.handleFreehandDrawCompletion(e.polygon),this.polygonInformation.createPolygonInformationStorage(this.arrayOfFeatureGroups)}),this.addCoreEventListener("polydraw:draw:cancel",()=>{this.stopDraw(),this.setDrawMode(this.config.tools.default)}),this.addCoreEventListener("polydraw:layer:visibility",e=>{const t=this.layerManager.getLayer(e.layerId);if(t){for(const r of t.featureGroups)try{e.visible?r.addTo(this.map):this.map.removeLayer(r)}catch{}this.syncFeatureGroupOrderWithLayers(),this.updateLayerPanel()}}),this.addCoreEventListener("polydraw:layer:activated",()=>{this.updateMarkerDraggableState(),this.updateLayerPanel()}),this.addCoreEventListener("polydraw:layer:colorChanged",()=>{this.updateLayerPanel()}),this.addCoreEventListener("polydraw:layer:created",()=>{this.updateLayerPanel()}),this.addCoreEventListener("polydraw:layer:delete-requested",e=>{this.saveHistory("layerDelete"),this.layerManager.deleteLayer(e.layerId)}),this.addCoreEventListener("polydraw:layer:reorder-requested",e=>{this.reorderLayer(e.layerId,e.targetLayerId)}),this.addCoreEventListener("polydraw:layer:reordered",()=>{this.syncFeatureGroupOrderWithLayers(),this.polygonInformation.deletePolygonInformationStorage(),this.polygonInformation.createPolygonInformationStorage(this.arrayOfFeatureGroups),this.updateLayerPanel()}),this.addCoreEventListener("polydraw:layer:deleted",e=>{for(const t of e.removedFeatureGroups){try{this.polygonMutationManager&&this.polygonMutationManager.cleanupFeatureGroup(t),t.clearLayers(),this.map.removeLayer(t)}catch{}const e=this.arrayOfFeatureGroups.indexOf(t);e>-1&&this.arrayOfFeatureGroups.splice(e,1)}this.syncFeatureGroupOrderWithLayers(),this.polygonInformation.updatePolygons(),this.updateActivateButtonIndicator(),this.updateMarkerDraggableState(),this.updateLayerPanel()}))}createTracer(){this.tracer=oi.createPolyline([],{...this.config.styles.polyline});try{this.tracer.addTo(this.map)}catch{}}applyTracerStyle(e){if(this.tracer)try{const t=e===c.Subtract||e===c.PointToPointSubtract,r=this.getTracerBaseStyle(t);let o,n="";switch(e){case c.Add:n=this.config.styles.polyline.color,o=void 0;break;case c.Subtract:n=this.config.styles.subtractLine.color,o=void 0;break;case c.PointToPoint:n=this.config.styles.polyline.color,o="5, 5";break;case c.PointToPointSubtract:n=this.config.styles.subtractLine.color,o="5, 5";break;case c.Off:default:n="",o=void 0}this.tracer.setStyle({...r,color:n,dashArray:o})}catch{}}getTracerBaseStyle(e){const t=e?this.config.styles.subtractLine:this.config.styles.polyline;return{weight:t.weight,opacity:t.opacity}}initializeManagers(){this.polygonDrawManager=new fi({turfHelper:this.turfHelper,map:this.map,config:this.config,modeManager:this.modeManager,eventManager:this.eventManager,tracer:this.tracer}),this.polygonMutationManager=new zi({turfHelper:this.turfHelper,polygonInformation:this.polygonInformation,map:this.map,config:this.config,modeManager:this.modeManager,eventManager:this.eventManager,getFeatureGroups:()=>this.arrayOfFeatureGroups,saveHistoryState:e=>{this.saveHistory(e)},layerManager:this.layerManager})}async loadExternalConfig(e,t){try{const r=await fetch(e);if(!r.ok)throw new Error(`Failed to load config from ${e}: ${r.status} ${r.statusText}`);const o=Ki(await r.json());this.config=Qn(structuredClone(g),o,t??{}),$i(this.config),this.initializeComponents()}catch(r){console.warn("Failed to load external config, falling back to default + inline config:",r),this.config=Qn(structuredClone(g),t??{}),$i(this.config),this.initializeComponents()}}_updateDrawModeState(e){var t;this.drawMode=e,this.modeManager.updateStateForMode(e),this.emitDrawModeChanged(),this.updateMarkerDraggableState(),(null==(t=this.polygonDrawManager)?void 0:t.refreshP2PMarkerState)&&this.polygonDrawManager.refreshP2PMarkerState()}_updateUIAfterDrawModeChange(e){this.modeManager.shouldShowCrosshairCursor()?oi.domUtil.addClass(this.map.getContainer(),"crosshair-cursor-enabled"):oi.domUtil.removeClass(this.map.getContainer(),"crosshair-cursor-enabled"),this.applyTracerStyle(e)}shouldEnableDrawEvents(e){return e===c.Add||e===c.Subtract||e===c.PointToPoint||e===c.PointToPointSubtract}_updateMapInteractions(){const e=this.modeManager.canPerformAction("mapDrag"),t=this.modeManager.canPerformAction("mapZoom"),r=this.modeManager.canPerformAction("mapDoubleClickZoom");this.events(this.shouldEnableDrawEvents(this.drawMode)),this.setLeafletMapEvents(e,r,t)}async restoreFromSnapshot(e){var t,r,o;if(e&&Array.isArray(e.features)){this.historyManager.setRestoring(!0),this._isRestoringSnapshot=!0;try{this.removeAllFeatureGroups();for(const[o,n]of e.features.entries()){const i=null==(t=e.featureMetadataSnapshot)?void 0:t[o],a=(null==i?void 0:i.layerId)&&(null==(r=this.layerManager)?void 0:r.getLayer(i.layerId))?i.layerId:void 0;await this.polygonMutationManager.addPolygon(n,{noMerge:!0,simplify:!1,skipKinkProcessing:!0,targetLayerId:a,visualOptimizationLevel:(null==i?void 0:i.optimizationLevel)??0,originalOptimizationLevel:null==i?void 0:i.originalOptimizationLevel,featureId:null==i?void 0:i.id,featureMetadata:null==i?void 0:i.metadata,sourceFeatureIds:null==i?void 0:i.sourceFeatureIds,featureInteractionOverride:null==i?void 0:i.interactionOverride,featureStyleOverrides:null==i?void 0:i.styleOverrides,featureCreatedAt:null==i?void 0:i.createdAt,featureLastModified:null==i?void 0:i.lastModified})}if(e.layerSnapshot&&this.layerManager){this.layerManager.restoreFromLayerSnapshot(e.layerSnapshot,this.arrayOfFeatureGroups);for(const e of this.layerManager.getAllLayers()){for(const t of e.featureGroups){const r=null==(o=t._polydrawMetadata)?void 0:o.styleOverrides;t.eachLayer(t=>{t instanceof s.Polygon&&!(t instanceof s.Rectangle)&&t.setStyle({color:(null==r?void 0:r.color)??e.color,fillColor:(null==r?void 0:r.fillColor)??this.config.styles.polygon.fillColor,fillOpacity:(null==r?void 0:r.fillOpacity)??this.config.styles.polygon.fillOpacity,weight:(null==r?void 0:r.weight)??this.config.styles.polygon.weight})})}if(!e.visible)for(const t of e.featureGroups)try{this.map.removeLayer(t)}catch{}}this.updateLayerPanel()}this.layerManager&&this.syncFeatureGroupOrderWithLayers(),this.polygonInformation.updatePolygons(),this.updateMarkerDraggableState()}finally{this._isRestoringSnapshot=!1,this.historyManager.setRestoring(!1)}}else console.warn("Invalid history snapshot provided for restore; skipping restore operation.")}initializeComponents(){this._componentsInitialized||(this._componentsInitialized=!0,this.turfHelper=new ei(this.config),this.mapStateService=new gi,this.eventManager=this.eventManager??new di,this.polygonInformation=new hi(this.mapStateService),this.modeManager=new pi(this.config,this.eventManager),this.historyManager?this.historyManager.setMaxHistorySize(this.config.history.maxSize):this.historyManager=new Ni(this.eventManager,this.config.history.maxSize),this.layerManager=new Ui(this.eventManager,this.config.styles.polygon.color),this.polygonInformation.onPolygonInfoUpdated(e=>{this.updateActivateButtonIndicator()}),this._boundKeyDownHandler=this.handleKeyDown.bind(this))}emitDrawModeChanged(){this.eventManager.emit("polydraw:mode:change",{mode:this.modeManager.getCurrentMode()});for(const e of this.drawModeListeners)e(this.modeManager.getCurrentMode())}updateMarkerDraggableState(){this.polygonMutationManager&&this.polygonMutationManager.updateMarkerDraggableState()}updateLayerPanel(){if(!this.map||!this.layerManager)return;if(this.layerManager.getPanelLayerCount()>1){if(!this.layerPanel){const e=function(e,t){let r=!1,o=null,n=null,i=!1;const a=()=>{if(!o)return;if(n)return void(i=!0);o.innerHTML="";const l=e.getPanelLayers(),c=e.getActiveLayerId();n&&!l.some(e=>e.id===n)&&(n=null),o.classList.toggle("polydraw-layer-panel-collapsed",r);const u=s.DomUtil.create("div","polydraw-layer-header",o);s.DomUtil.create("span","polydraw-layer-header-title",u).textContent="Layers",s.DomUtil.create("span","polydraw-layer-header-count",u).textContent=String(l.length);const h=s.DomUtil.create("button","polydraw-layer-header-toggle",u);if(h.setAttribute("type","button"),h.setAttribute("aria-label",r?"Expand layer panel":"Collapse layer panel"),h.setAttribute("title",r?"Expand layers":"Collapse layers"),ni(h,Xi.toggle),h.classList.toggle("is-collapsed",r),h.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),r=!r,a()}),r)return;const g=()=>{o&&o.querySelectorAll(".polydraw-layer-row").forEach(e=>{e.classList.remove("polydraw-layer-row-dragging"),e.classList.remove("polydraw-layer-row-drag-over")})},d=()=>{i&&(i=!1,a())},p=e=>{var t,r;return(null==(r=null==(t=null==e?void 0:e.dataTransfer)?void 0:t.getData("text/plain"))?void 0:r.trim())||n};l.forEach(r=>{var i;const a=(null==(i=r.label)?void 0:i.trim())?r.label:r.id,l=s.DomUtil.create("div","polydraw-layer-row",o??void 0);if(l.setAttribute("tabindex","0"),l.setAttribute("role","button"),l.setAttribute("draggable","default"===r.id?"false":"true"),l.setAttribute("aria-label",`Activate layer ${a}`),l.setAttribute("data-layer-id",r.id),r.id===c&&l.classList.add("polydraw-layer-row-active"),r.visible||l.classList.add("polydraw-layer-hidden"),"default"!==r.id){const e=s.DomUtil.create("span","polydraw-layer-grip",l);e.setAttribute("aria-hidden","true"),ni(e,Xi.grip)}else s.DomUtil.create("span","polydraw-layer-grip-spacer",l).setAttribute("aria-hidden","true");s.DomUtil.create("span","polydraw-layer-color-indicator",l).style.backgroundColor=r.color;const u=s.DomUtil.create("span","polydraw-layer-name",l);u.textContent=a,u.setAttribute("title",a);const h=s.DomUtil.create("button","polydraw-layer-btn polydraw-layer-visibility",l);if(h.setAttribute("type","button"),h.setAttribute("title",r.visible?"Hide layer":"Show layer"),h.setAttribute("aria-label",r.visible?`Hide layer ${a}`:`Show layer ${a}`),ni(h,r.visible?Xi.eyeVisible:Xi.eyeHidden),r.visible||h.classList.add("polydraw-layer-visibility-hidden"),h.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),e.setLayerVisibility(r.id,!r.visible)}),"default"!==r.id){const e=s.DomUtil.create("button","polydraw-layer-btn polydraw-layer-delete",l);e.setAttribute("type","button"),e.setAttribute("title","Delete layer"),e.setAttribute("aria-label",`Delete layer ${a}`),ni(e,Xi.delete),e.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),t.emit("polydraw:layer:delete-requested",{layerId:r.id})})}else s.DomUtil.create("span","polydraw-layer-btn-spacer",l).setAttribute("aria-hidden","true");l.addEventListener("click",()=>{e.setActiveLayer(r.id)}),l.addEventListener("keydown",t=>{"Enter"!==t.key&&" "!==t.key||(t.preventDefault(),e.setActiveLayer(r.id))}),"default"!==r.id&&(l.addEventListener("dragstart",e=>{n=r.id,l.classList.add("polydraw-layer-row-dragging"),e.dataTransfer&&(e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",r.id))}),l.addEventListener("dragend",()=>{n=null,g(),d()})),l.addEventListener("dragover",e=>{const t=p(e);t&&t!==r.id&&"default"!==r.id&&(e.preventDefault(),l.classList.add("polydraw-layer-row-drag-over"),e.dataTransfer&&(e.dataTransfer.dropEffect="move"))}),l.addEventListener("dragleave",()=>{l.classList.remove("polydraw-layer-row-drag-over")}),l.addEventListener("drop",e=>{const o=p(e);o&&o!==r.id&&"default"!==r.id&&(e.preventDefault(),e.stopPropagation(),t.emit("polydraw:layer:reorder-requested",{layerId:o,targetLayerId:r.id}),n=null,g(),d())})})},l=new(s.Control.extend({options:{position:"topright"},onAdd:()=>(o=s.DomUtil.create("div","leaflet-bar polydraw-layer-panel"),o.setAttribute("data-polydraw","layer-panel"),s.DomEvent.disableClickPropagation(o),s.DomEvent.disableScrollPropagation(o),s.DomEvent.on(o,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(o,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(o,"dragstart",s.DomEvent.stopPropagation),s.DomEvent.on(o,"dragover",s.DomEvent.stopPropagation),s.DomEvent.on(o,"drop",s.DomEvent.stopPropagation),a(),o),onRemove(){o&&(s.DomEvent.off(o,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.off(o,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.off(o,"dragstart",s.DomEvent.stopPropagation),s.DomEvent.off(o,"dragover",s.DomEvent.stopPropagation),s.DomEvent.off(o,"drop",s.DomEvent.stopPropagation),o=null,n=null,i=!1)}}));return l.refresh=()=>{a()},l}(this.layerManager,this.eventManager);return this.layerPanel=e,void e.addTo(this.map)}this.layerPanel.refresh()}else if(this.layerPanel){try{this.layerPanel.remove()}catch{}this.layerPanel=null}}syncFeatureGroupOrderWithLayers(){if(!this.layerManager)return;const e=this.arrayOfFeatureGroups;if(0===e.length)return;const t=new Set(e),r=new Set,o=[];for(const n of this.layerManager.getAllLayers())for(const e of n.featureGroups)t.has(e)&&!r.has(e)&&(r.add(e),o.push(e));for(const n of e)r.has(n)||o.push(n);this.isSameFeatureGroupOrder(e,o)||e.splice(0,e.length,...o),this.reapplyFeatureGroupMapOrder()}isSameFeatureGroupOrder(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}reapplyFeatureGroupMapOrder(){if(!this.map||!this.layerManager)return;const e=this.arrayOfFeatureGroups.filter(e=>{const t=this.layerManager.getLayerForFeatureGroup(e),r=t?this.layerManager.getLayer(t):void 0;return!r||!1!==r.visible}),t=new Map;this.layerManager.getAllLayers().forEach((e,r)=>{t.set(e.id,r)});const r=[...e].sort((e,r)=>{var o,n;const i=null==(o=this.layerManager)?void 0:o.getLayerForFeatureGroup(e),a=null==(n=this.layerManager)?void 0:n.getLayerForFeatureGroup(r),s=i?t.get(i)??t.size:t.size;return(a?t.get(a)??t.size:t.size)-s}),o=new Set(e);if(!this.arrayOfFeatureGroups.every(e=>{const t=o.has(e);return this.map.hasLayer(e)===t})||!this.isSameFeatureGroupOrder(this._lastAppliedVisibleMapOrder,r)){for(const e of this.arrayOfFeatureGroups)if(!o.has(e)&&this.map.hasLayer(e))try{this.map.removeLayer(e)}catch{}for(const e of r)try{this.map.hasLayer(e)&&this.map.removeLayer(e),e.addTo(this.map)}catch{}this._lastAppliedVisibleMapOrder=[...r]}}cleanupEmptyLayers(){if(!this.layerManager||this._isRestoringSnapshot)return;const e=[];for(const t of this.layerManager.getAllLayers())"default"!==t.id&&0===t.featureGroups.length&&e.push(t.id);for(const t of e)this.layerManager.deleteLayer(t);e.length>0&&this.updateLayerPanel()}stopDraw(){this.isDrawingInProgress=!1,this.resetTracker(),this.drawStartedEvents(!1)}setLeafletMapEvents(e,t,r){e?this.map.dragging.enable():this.map.dragging.disable(),t?this.map.doubleClickZoom.enable():this.map.doubleClickZoom.disable(),r?this.map.scrollWheelZoom.enable():this.map.scrollWheelZoom.disable()}resetTracker(){var e;null==(e=this.tracer)||e.setLatLngs([])}drawStartedEvents(e){if(this.drawEventsAttached===e)return;this.drawEventsAttached=e;const t=this.pointerEventsHandled,r=e?"on":"off";t||(this.map[r]("mousemove",this.mouseMove,this),this.map[r]("mouseup",this.mouseUpLeave,this)),e?(t||(this._boundTouchMove||(this._boundTouchMove=e=>this.mouseMove(e)),this._boundTouchEnd||(this._boundTouchEnd=e=>this.mouseUpLeave(e)),this.map.getContainer().addEventListener("touchmove",this._boundTouchMove,{passive:!1}),this.map.getContainer().addEventListener("touchend",this._boundTouchEnd,{passive:!1})),t&&(this._boundPointerMove||(this._boundPointerMove=e=>this.mouseMove(e)),this._boundPointerUp||(this._boundPointerUp=e=>this.mouseUpLeave(e)),this.map.getContainer().addEventListener("pointermove",this._boundPointerMove,{passive:!1}),this.map.getContainer().addEventListener("pointerup",this._boundPointerUp,{passive:!1}))):(this._boundTouchMove&&this.map.getContainer().removeEventListener("touchmove",this._boundTouchMove),this._boundTouchEnd&&this.map.getContainer().removeEventListener("touchend",this._boundTouchEnd),this._boundPointerMove&&this.map.getContainer().removeEventListener("pointermove",this._boundPointerMove),this._boundPointerUp&&this.map.getContainer().removeEventListener("pointerup",this._boundPointerUp))}events(e){if(this.mapEventsAttached===e)return;this.mapEventsAttached=e;const t=this.pointerEventsHandled,r=e?"on":"off";t||this.map[r]("mousedown",this.mouseDown,this),this.map[r]("dblclick",this.handleDoubleClick,this),e?(t||(this._boundTouchStart||(this._boundTouchStart=e=>this.handleTouchStart(e)),this.map.getContainer().addEventListener("touchstart",this._boundTouchStart,{passive:!1})),t&&(this._boundPointerDown||(this._boundPointerDown=e=>this.mouseDown(e)),this.map.getContainer().addEventListener("pointerdown",this._boundPointerDown,{passive:!1}))):(this._boundTouchStart&&this.map.getContainer().removeEventListener("touchstart",this._boundTouchStart),this._boundPointerDown&&this.map.getContainer().removeEventListener("pointerdown",this._boundPointerDown))}handleTouchStart(e){const t=Date.now(),r=t-this._lastTapTime;if(this.modeManager.getCurrentMode()===c.PointToPoint||this.modeManager.getCurrentMode()===c.PointToPointSubtract){this._tapTimeout&&(clearTimeout(this._tapTimeout),this._tapTimeout=null);const o=bi.extractCoordinates(e,this.map);return this.isP2PDoubleTapClose(o,r)?(this.handleDoubleTap(e),this._lastTapTime=0,void(this._lastTapLatLng=null)):(this._lastTapTime=t,this._lastTapLatLng=o,void this.mouseDown(e))}this._tapTimeout&&(clearTimeout(this._tapTimeout),this._tapTimeout=null),r<300&&r>0?(this.handleDoubleTap(e),this._lastTapTime=0):(this._lastTapTime=t,this._lastTapLatLng=bi.extractCoordinates(e,this.map),this.pointerEventsHandled||(this._tapTimeout=window.setTimeout(()=>{this.mouseDown(e),this._tapTimeout=null},300)))}isP2PDoubleTapClose(e,t){if(!e||!this._lastTapLatLng)return!1;if(t<=0||t>300)return!1;const r=this.map.latLngToLayerPoint(this._lastTapLatLng),o=this.map.latLngToLayerPoint(e);return r.distanceTo(o)<=36}handleDoubleTap(e){this.modeManager.getCurrentMode()!==c.PointToPoint&&this.modeManager.getCurrentMode()!==c.PointToPointSubtract||this.polygonDrawManager.handleDoubleTap(e)}mouseDown(e){var t;const r=bi.normalizeEvent(e);if(this.isEventFromControl(r))return;if(bi.shouldPreventDefault(r)&&(null==(t=r.preventDefault)||t.call(r)),this.modeManager.isInOffMode())return;const o=bi.extractCoordinates(r,this.map);if(!o)return;const n=this.modeManager.getCurrentMode()===c.PointToPoint||this.modeManager.getCurrentMode()===c.PointToPointSubtract;if(n&&"touch"===r.pointerType){const t=Date.now(),r=t-this._lastTapTime;if(this.isP2PDoubleTapClose(o,r))return this.handleDoubleTap(e),this._lastTapTime=0,void(this._lastTapLatLng=null);this._lastTapTime=t,this._lastTapLatLng=o}n?this.polygonDrawManager.handlePointToPointClick(o):this.tracer&&(this.isDrawingInProgress||(this.tracer.setLatLngs([o]),this.startDraw()))}isEventFromControl(e){var t,r;const o=this.getContainer();if(!o)return!1;const n=null==e?void 0:e.originalEvent;if(n&&this.controlEvents.has(n))return!0;if(e instanceof Event&&this.controlEvents.has(e))return!0;if(this.isRecentControlPointer(e))return!0;const i=(null==(t=null==n?void 0:n.composedPath)?void 0:t.call(n))??(null==(r=null==e?void 0:e.composedPath)?void 0:r.call(e));if(i&&i.some(e=>e instanceof Node&&o.contains(e)))return!0;const a=(null==n?void 0:n.target)??(null==e?void 0:e.target);if(a instanceof Node&&o.contains(a))return!0;const s=e=>{if(!e||"object"!=typeof e)return null;const t=e;if(t.touches&&t.touches.length>0)return{x:t.touches[0].clientX,y:t.touches[0].clientY};const r=e;if("number"==typeof r.clientX&&"number"==typeof r.clientY)return{x:r.clientX,y:r.clientY};const o=e;if(o.containerPoint&&this.map){const e=this.map.getContainer().getBoundingClientRect();return{x:e.left+o.containerPoint.x,y:e.top+o.containerPoint.y}}const n=e;if(n.latlng&&this.map){const e=this.map.latLngToContainerPoint(n.latlng),t=this.map.getContainer().getBoundingClientRect();return{x:t.left+e.x,y:t.top+e.y}}return null},l=s(null==e?void 0:e.originalEvent)??s(e);if(!l)return!1;const c=o.getBoundingClientRect();if(l.x>=c.left&&l.x<=c.right&&l.y>=c.top&&l.y<=c.bottom)return!0;const u=document.elementFromPoint(l.x,l.y);return!(!u||!o.contains(u))}extractPointerInfo(e){if(!e||"object"!=typeof e)return null;const t=e;if("number"==typeof t.pointerId)return{id:t.pointerId,pointerType:"string"==typeof t.pointerType?t.pointerType:"unknown"};if("string"==typeof t.type){if(t.type.startsWith("touch"))return{id:-2,pointerType:"touch"};if(t.type.startsWith("mouse"))return{id:-1,pointerType:"mouse"}}return null}markControlPointerDown(e){const t=this.extractPointerInfo(e);t&&(this.lastControlPointerDown={...t,time:Date.now()})}clearControlPointerDown(e){if(!this.lastControlPointerDown)return;const t=this.extractPointerInfo(e);t&&t.id===this.lastControlPointerDown.id&&(this.lastControlPointerDown=null)}isRecentControlPointer(e){if(!this.lastControlPointerDown)return!1;const t=null==e?void 0:e.originalEvent,r=this.extractPointerInfo(t)??this.extractPointerInfo(e);if(!r)return!1;const o="touch"===this.lastControlPointerDown.pointerType?450:80;return!(Date.now()-this.lastControlPointerDown.time>o)&&(r.pointerType===this.lastControlPointerDown.pointerType&&("mouse"===r.pointerType||r.id===this.lastControlPointerDown.id))}mouseMove(e){var t;if(!this.isDrawingInProgress)return;const r=bi.normalizeEvent(e);bi.shouldPreventDefault(r)&&(null==(t=r.preventDefault)||t.call(r));const o=bi.extractCoordinates(r,this.map);o&&this.tracer&&this.tracer.addLatLng(o)}async mouseUpLeave(e){var t;if(!this.isDrawingInProgress)return;const r=bi.normalizeEvent(e);if(bi.shouldPreventDefault(r)&&(null==(t=r.preventDefault)||t.call(r)),this.polygonInformation.deletePolygonInformationStorage(),!this.tracer)return void this.stopDraw();const o=this.tracer.toGeoJSON();if(!o||!o.geometry||!o.geometry.coordinates||o.geometry.coordinates.length<3)return void this.stopDraw();let n;try{n=this.turfHelper.createPolygonFromTrace(o)}catch{return void this.stopDraw()}if(n&&n.geometry&&n.geometry.coordinates&&0!==n.geometry.coordinates.length){this.stopDraw();try{const e=this.getInteractionTargetLayerId();switch(this.modeManager.getCurrentMode()){case c.Add:{const t=await this.polygonMutationManager.addPolygon(n,{simplify:!0,noMerge:!1,targetLayerId:e});t.success||console.error("Error adding polygon via manager:",t.error);break}case c.Subtract:{const t=await this.polygonMutationManager.subtractPolygon(n,{targetLayerId:e});t.success||console.error("Error subtracting polygon via manager:",t.error);break}}}catch(i){console.error("Error in mouseUpLeave polygon operation:",i)}this.polygonInformation.createPolygonInformationStorage(this.arrayOfFeatureGroups)}else this.stopDraw()}async handleFreehandDrawCompletion(e){try{this.saveHistory("freehand");const t=this.getInteractionTargetLayerId();switch(this.modeManager.getCurrentMode()){case c.Add:{const r=await this.polygonMutationManager.addPolygon(e,{simplify:!0,noMerge:!1,targetLayerId:t});r.success||console.error("Error adding polygon via manager:",r.error);break}case c.Subtract:{const r=await this.polygonMutationManager.subtractPolygon(e,{targetLayerId:t});r.success||console.error("Error subtracting polygon via manager:",r.error);break}}}catch(t){console.error("Error in mouseUpLeave polygon operation:",t)}}startDraw(){this.isDrawingInProgress||(this.isDrawingInProgress=!0,this.drawStartedEvents(!0))}setupKeyboardHandlers(){this._boundKeyDownHandler||(this._boundKeyDownHandler=this.handleKeyDown.bind(this)),this._boundKeyUpHandler||(this._boundKeyUpHandler=this.handleKeyUp.bind(this)),document.addEventListener("keydown",this._boundKeyDownHandler),document.addEventListener("keyup",this._boundKeyUpHandler)}removeKeyboardHandlers(){this._boundKeyDownHandler&&document.removeEventListener("keydown",this._boundKeyDownHandler),this._boundKeyUpHandler&&document.removeEventListener("keyup",this._boundKeyUpHandler)}handleKeyDown(e){const t=e.ctrlKey||e.metaKey;if(t&&"z"===e.key&&!e.shiftKey)return e.preventDefault(),void this.undo();if(t&&("y"===e.key||"z"===e.key&&e.shiftKey))return e.preventDefault(),void this.redo();"Escape"===e.key&&(this.modeManager.getCurrentMode()!==c.PointToPoint&&this.modeManager.getCurrentMode()!==c.PointToPointSubtract||this.polygonDrawManager.cancelPointToPointDrawing());this.isModifierKeyPressed(e)&&!this.isModifierKeyHeld&&(this.isModifierKeyHeld=!0,this.polygonDrawManager.setModifierKey(!0),this.updateAllMarkersForEdgeDeletion(!0),this.applyModifierModeOverride(!0))}handleKeyUp(e){!this.isModifierKeyPressed(e)&&this.isModifierKeyHeld&&(this.isModifierKeyHeld=!1,this.polygonDrawManager.setModifierKey(!1),this.updateAllMarkersForEdgeDeletion(!1),this.applyModifierModeOverride(!1))}applyModifierModeOverride(e){if(e){if(this.modifierModeOverride)return;if(!this.config.modifierSubtractMode)return;const e=this.modeManager.getCurrentMode();return void(e===c.Add?(this.modifierModeOverride={from:e,to:c.Subtract},this.setDrawMode(c.Subtract,{preserveActiveDraw:!0})):e===c.PointToPoint&&(this.modifierModeOverride={from:e,to:c.PointToPointSubtract},this.setDrawMode(c.PointToPointSubtract,{preserveActiveDraw:!0})))}if(!this.modifierModeOverride)return;const{from:t,to:r}=this.modifierModeOverride;this.modifierModeOverride=null,this.modeManager.getCurrentMode()===r&&this.setDrawMode(t,{preserveActiveDraw:!0})}updateAllMarkersForEdgeDeletion(e){this.arrayOfFeatureGroups.forEach(t=>{t.eachLayer(t=>{t instanceof s.Marker&&this.updateMarkerForEdgeDeletion(t,e)})})}updateMarkerForEdgeDeletion(e,t){const r=e.getElement();r&&(t?(r.addEventListener("mouseenter",this.onMarkerHoverForEdgeDeletionEvent),r.addEventListener("mouseleave",this.onMarkerLeaveForEdgeDeletionEvent)):(r.removeEventListener("mouseenter",this.onMarkerHoverForEdgeDeletionEvent),r.removeEventListener("mouseleave",this.onMarkerLeaveForEdgeDeletionEvent),r.style.backgroundColor="",r.style.borderColor=""))}handleDoubleClick(e){this.modeManager.getCurrentMode()!==c.PointToPoint&&this.modeManager.getCurrentMode()!==c.PointToPointSubtract||(s.DomEvent.stop(e),this.polygonDrawManager.handleDoubleClick(e))}isModifierKeyPressed(e){return navigator.userAgent.toLowerCase().includes("mac")?e.metaKey:e.ctrlKey}ensureButtonTouchResponsiveness(e){e.querySelectorAll("a").forEach(e=>{e.style.pointerEvents="auto",e.style.touchAction="manipulation",e.style.position="relative",e.style.zIndex="1";const t=e=>{e.stopPropagation(),e.target.style.pointerEvents="auto"};e.addEventListener("touchstart",t,{passive:!0}),e.addEventListener("touchend",t,{passive:!0})})}updateActivateButtonIndicator(){if("function"!=typeof this.getContainer)return;const e=this.getContainer();if(!e)return;const t=e.querySelector(".icon-activate");if(!t)return;const r=this.arrayOfFeatureGroups.length>0,o=!oi.domUtil.hasClass(t,"active"),n=oi.domUtil.hasClass(t,"active")?t.dataset.collapsedIcon:t.dataset.activeIcon;n&&this.applyActivateButtonIcon(t,n);const i=r&&o;i?oi.domUtil.addClass(t,"polydraw-indicator-active"):oi.domUtil.removeClass(t,"polydraw-indicator-active");const a=this.config.styles.ui.controlButton.backgroundColor,s=this.config.styles.ui.controlButton.color,l=this.config.styles.ui.indicatorActive.backgroundColor;t.style.backgroundColor=i?l:a,t.style.color=s;const u=(e,t)=>{e&&(t?(e.style.opacity="1",e.style.pointerEvents="auto",e.setAttribute("aria-disabled","false"),e.tabIndex=0):(e.style.opacity="0.3",e.style.pointerEvents="none",e.setAttribute("aria-disabled","true"),e.tabIndex=-1))};u(e.querySelector(".icon-clone"),r),r||this.modeManager.getCurrentMode()!==c.Clone||this.setDrawMode(c.Off);u(e.querySelector(".icon-erase"),"defaultLayer"===(this.config.tools.eraseScope??"all")?this.layerManager.getFeatureGroupsForLayer("default").length>0:r)}applyActivateButtonIcon(e,t){ni(e,t)}}const Zi=e=>{if(e){if("undefined"!=typeof globalThis){globalThis.L||(globalThis.L=e)}e.control&&(e.control.polydraw=function(e){return new Ji(e)}),ri.reset()}};if("undefined"!=typeof globalThis){const e=globalThis.L;e&&Zi(e)}e.default=Ji,e.defaultConfig=g,e.leafletAdapter=oi,e.registerWithLeaflet=Zi,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("leaflet")):"function"==typeof define&&define.amd?define(["exports","leaflet"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LeafletPolydraw={},e.L)}(this,function(e,t){"use strict";var r,o,n=Object.defineProperty,i=(e,t,r)=>((e,t,r)=>t in e?n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);function a(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const r in e)if("default"!==r){const o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,o.get?o:{enumerable:!0,get:()=>e[r]})}return t.default=e,Object.freeze(t)}const s=a(t);var l=(e=>(e.V1="1.x",e.V2="2.x",e))(l||{}),c=(e=>(e[e.Off=0]="Off",e[e.Add=1]="Add",e[e.Edit=2]="Edit",e[e.Subtract=4]="Subtract",e[e.AppendMarker=8]="AppendMarker",e[e.LoadPredefined=16]="LoadPredefined",e[e.PointToPoint=32]="PointToPoint",e[e.PointToPointSubtract=64]="PointToPointSubtract",e[e.Clone=128]="Clone",e))(c||{}),u=(e=>(e[e.SouthWest=0]="SouthWest",e[e.South=1]="South",e[e.SouthEast=2]="SouthEast",e[e.East=3]="East",e[e.NorthEast=4]="NorthEast",e[e.North=5]="North",e[e.NorthWest=6]="NorthWest",e[e.West=7]="West",e[e.Hole=8]="Hole",e))(u||{}),h=(e=>(e.Both="both",e.Inward="inward",e))(h||{});const g={mergePolygons:!0,kinks:!1,tools:{default:c.Off,draw:!0,subtract:!0,p2p:!0,p2pSubtract:!0,clone:!0,erase:!0,eraseScope:"all"},modes:{attachElbow:!0,dragElbow:!0,dragPolygons:!0,edgeDeletion:!0},modifierSubtractMode:!0,interaction:{drag:{opacity:.7,dragCursor:"move",hoverCursor:"grab",markerBehavior:"hide",markerAnimationDuration:200,modifierSubtract:{keys:{windows:"ctrlKey",mac:"metaKey",linux:"ctrlKey"},hideMarkersOnDrag:!0}},edgeDeletion:{keys:{windows:"ctrlKey",mac:"metaKey",linux:"ctrlKey"},minVertices:3}},markers:{deleteMarker:!0,infoMarker:!0,menuMarker:!0,coordsTitle:!0,zIndexOffset:0,markerIcon:{styleClasses:["polygon-marker"],zIndexOffset:null},holeIcon:{styleClasses:["polygon-marker","hole"],zIndexOffset:null},markerInfoIcon:{position:u.East,showArea:!0,showPerimeter:!0,useMetrics:!0,usePerimeterMinValue:!1,areaLabel:"Area",perimeterLabel:"Perimeter",values:{min:{metric:"50",imperial:"100"},unknown:{metric:"-",imperial:"-"}},units:{unknownUnit:"",metric:{onlyMetrics:!0,perimeter:{m:"m",km:"km"},area:{m2:"m²",km2:"km²",daa:"daa",ha:"ha"}},imperial:{perimeter:{feet:"ft",yards:"yd",miles:"mi"},area:{feet2:"ft²",yards2:"yd²",acres:"ac",miles2:"mi²"}}},styleClasses:["polygon-marker","info"],zIndexOffset:1e4},markerMenuIcon:{position:u.South,styleClasses:["polygon-marker","menu"],zIndexOffset:1e4},markerDeleteIcon:{position:u.North,styleClasses:["polygon-marker","delete"],zIndexOffset:1e4},holeMarkers:{menuMarker:!1,deleteMarker:!0,infoMarker:!1},visualOptimization:{toleranceMin:5e-6,toleranceMax:.005,curve:1.35}},styles:{polyline:{weight:2,opacity:1,color:"#50622b"},subtractLine:{weight:2,opacity:1,color:"#D9460F"},polygon:{weight:2,opacity:1,fillOpacity:.2,smoothFactor:.3,noClip:!0,color:"#50622b",fillColor:"#b4cd8a"},hole:{weight:2,opacity:1,fillOpacity:.5,color:"#aa0000",fillColor:"#ffcccc"},ui:{controlButton:{backgroundColor:"#fff",color:"#000"},controlButtonHover:{backgroundColor:"#f4f4f4"},controlButtonActive:{backgroundColor:"rgb(128, 218, 255)",color:"#fff"},indicatorActive:{backgroundColor:"#ffcc00"},p2pMarker:{backgroundColor:"#fff",borderColor:"#50622b"},p2pClosingMarker:{color:"#4CAF50"},edgeHover:{color:"#7a9441"},edgeDeletion:{color:"#D9460F"},dragSubtract:{color:"#D9460F"}}},polygonCreation:{algorithm:"concaveman"},simplification:{strategy:"simple",simple:{tolerance:1e-4,highQuality:!1},dynamic:{baseTolerance:1e-4,highQuality:!1,fractionGuard:.9,multiplier:2}},polygonTools:{simplify:{enabled:!0,processHoles:!0},doubleElbows:{enabled:!0,processHoles:!0},bbox:{enabled:!0,processHoles:!0,addMidPointMarkers:!0},bezier:{enabled:!0,resolution:1e4,sharpness:.75,resampleMultiplier:10,maxNodes:1e3,visualOptimizationLevel:10,ghostMarkers:!1},scale:{enabled:!0},rotate:{enabled:!0},donut:{enabled:!0,direction:h.Both},visualOptimizationToggle:{enabled:!0}},tooltips:{enabled:!0,delayMs:500,direction:"left",backgroundColor:"#645d5d",color:"#ffffff"},history:{capture:{batch:!0,freehand:!0,pointToPoint:!0,addPredefinedPolygon:!0,eraseAll:!0,markerDrag:!0,polygonDrag:!0,polygonClone:!0,addVertex:!0,removeVertex:!0,removeHole:!0,modifierSubtract:!0,deletePolygon:!0,layerDelete:!0,layerReorder:!0,polygonActions:{simplify:!0,doubleElbows:!0,bbox:!0,bezier:!0,scale:!0,rotate:!0,donut:!0,toggleOptimization:!0,polygonMenuAction:!0}},maxSize:50}},d=6371e3,p=6371,f=3959,y=Math.PI/180,m=180/Math.PI;Math.PI;function v(e,t={}){return{type:"Feature",geometry:{type:"Point",coordinates:e},properties:t}}function M(e,t={}){return{type:"Feature",geometry:{type:"LineString",coordinates:e},properties:t}}function b(e,t={}){return{type:"Feature",geometry:{type:"Polygon",coordinates:e},properties:t}}function w(e,t={}){return{type:"Feature",geometry:{type:"MultiPolygon",coordinates:e},properties:t}}function P(e){return{type:"FeatureCollection",features:e}}function L(e){if("Polygon"===e.geometry.type)return[e.geometry.coordinates];if("MultiPolygon"===e.geometry.type)return e.geometry.coordinates;throw new Error("Feature must be a Polygon or MultiPolygon")}function k(e){let t=1/0,r=1/0,o=-1/0,n=-1/0;const i=e=>{if(Array.isArray(e[0]))e.forEach(e=>i(e));else{const[i,a]=e;t=Math.min(t,i),r=Math.min(r,a),o=Math.max(o,i),n=Math.max(n,a)}},a=e=>{if("GeometryCollection"===e.type){return void e.geometries.forEach(a)}i(e.coordinates)};return a(e.geometry),[t,r,o,n]}function x(e,t,r="kilometers"){const o=Array.isArray(e)?e:e.geometry.coordinates,n=Array.isArray(t)?t:t.geometry.coordinates,[i,a]=o,[s,l]=n,c="miles"===r?f:"meters"===r?d:p,u=D(l-a),h=D(s-i),g=Math.sin(u/2)*Math.sin(u/2)+Math.cos(D(a))*Math.cos(D(l))*Math.sin(h/2)*Math.sin(h/2);return c*(2*Math.atan2(Math.sqrt(g),Math.sqrt(1-g)))}function E(e,t){const r=Array.isArray(e)?e:e.geometry.coordinates,o=Array.isArray(t)?t:t.geometry.coordinates,[n,i]=r,[a,s]=o;return v([(n+a)/2,(i+s)/2])}function S(e){const t=L(e);let r=0,o=0,n=0;for(const i of t)for(const e of i)for(const t of e)r+=t[0],o+=t[1],n++;return v([r/n,o/n])}function D(e){return e*y}var C=6371008.8,I={centimeters:637100880,centimetres:637100880,degrees:360/(2*Math.PI),feet:20902260.511392,inches:39.37*C,kilometers:6371.0088,kilometres:6371.0088,meters:C,metres:C,miles:3958.761333810546,millimeters:6371008800,millimetres:6371008800,nauticalmiles:C/1852,radians:1,yards:6967335.223679999};function A(e,t,r={}){const o={type:"Feature"};return(0===r.id||r.id)&&(o.id=r.id),r.bbox&&(o.bbox=r.bbox),o.properties=t||{},o.geometry=e,o}function F(e,t,r={}){if(!e)throw new Error("coordinates is required");if(!Array.isArray(e))throw new Error("coordinates must be an Array");if(e.length<2)throw new Error("coordinates must be at least 2 numbers long");if(!z(e[0])||!z(e[1]))throw new Error("coordinates must contain numbers");return A({type:"Point",coordinates:e},t,r)}function O(e,t,r={}){for(const o of e){if(o.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(o[o.length-1].length!==o[0].length)throw new Error("First and last Position are not equivalent.");for(let e=0;e<o[o.length-1].length;e++)if(o[o.length-1][e]!==o[0][e])throw new Error("First and last Position are not equivalent.")}return A({type:"Polygon",coordinates:e},t,r)}function T(e,t,r={}){if(e.length<2)throw new Error("coordinates must be an array of two or more positions");return A({type:"LineString",coordinates:e},t,r)}function _(e,t={}){const r={type:"FeatureCollection"};return t.id&&(r.id=t.id),t.bbox&&(r.bbox=t.bbox),r.features=e,r}function G(e,t,r={}){return A({type:"MultiPolygon",coordinates:e},t,r)}function H(e){return 180*(e%(2*Math.PI))/Math.PI}function B(e){return e%360*Math.PI/180}function z(e){return!isNaN(e)&&null!==e&&!Array.isArray(e)}function U(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function N(e,t,r){var o=r;return function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,function(e,n,i,a,s){o=0===n&&void 0===r?e:t(o,e,n,i,a,s)}),o}function R(e){return N(e,(e,t)=>e+function(e){let t,r=0;switch(e.type){case"Polygon":return X(e.coordinates);case"MultiPolygon":for(t=0;t<e.coordinates.length;t++)r+=X(e.coordinates[t]);return r;case"Point":case"MultiPoint":case"LineString":case"MultiLineString":return 0}return 0}(t),0)}function X(e){let t=0;if(e&&e.length>0){t+=Math.abs(q(e[0]));for(let r=1;r<e.length;r++)t-=Math.abs(q(e[r]))}return t}var Y=20294876564838.72,V=Math.PI/180;function q(e){const t=e.length-1;if(t<=2)return 0;let r=0,o=0;for(;o<t;){const n=e[o],i=e[o+1===t?0:o+1],a=e[o+2>=t?(o+2)%t:o+2],s=n[0]*V,l=i[1]*V;r+=(a[0]*V-s)*Math.sin(l),o++}return r*Y}var j=R;function W(e,t,r){if(null!==e)for(var o,n,i,a,s,l,c,u,h=0,g=0,d=e.type,p="FeatureCollection"===d,f="Feature"===d,y=p?e.features.length:1,m=0;m<y;m++){s=(u=!!(c=p?e.features[m].geometry:f?e.geometry:e)&&"GeometryCollection"===c.type)?c.geometries.length:1;for(var v=0;v<s;v++){var M=0,b=0;if(null!==(a=u?c.geometries[v]:c)){l=a.coordinates;var w=a.type;switch(h=0,w){case null:break;case"Point":if(!1===t(l,g,m,M,b))return!1;g++,M++;break;case"LineString":case"MultiPoint":for(o=0;o<l.length;o++){if(!1===t(l[o],g,m,M,b))return!1;g++,"MultiPoint"===w&&M++}"LineString"===w&&M++;break;case"Polygon":case"MultiLineString":for(o=0;o<l.length;o++){for(n=0;n<l[o].length-h;n++){if(!1===t(l[o][n],g,m,M,b))return!1;g++}"MultiLineString"===w&&M++,"Polygon"===w&&b++}"Polygon"===w&&M++;break;case"MultiPolygon":for(o=0;o<l.length;o++){for(b=0,n=0;n<l[o].length;n++){for(i=0;i<l[o][n].length-h;i++){if(!1===t(l[o][n][i],g,m,M,b))return!1;g++}b++}M++}break;case"GeometryCollection":for(o=0;o<a.geometries.length;o++)if(!1===W(a.geometries[o],t))return!1;break;default:throw new Error("Unknown Geometry Type")}}}}}function $(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function K(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var o=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,o.get?o:{enumerable:!0,get:function(){return e[t]}})}),r}var J,Z={exports:{}},Q={exports:{}};function ee(){return J||(J=1,Q.exports=function(){function e(e,o,n,i,a){!function e(r,o,n,i,a){for(;i>n;){if(i-n>600){var s=i-n+1,l=o-n+1,c=Math.log(s),u=.5*Math.exp(2*c/3),h=.5*Math.sqrt(c*u*(s-u)/s)*(l-s/2<0?-1:1);e(r,o,Math.max(n,Math.floor(o-l*u/s+h)),Math.min(i,Math.floor(o+(s-l)*u/s+h)),a)}var g=r[o],d=n,p=i;for(t(r,n,o),a(r[i],g)>0&&t(r,n,i);d<p;){for(t(r,d,p),d++,p--;a(r[d],g)<0;)d++;for(;a(r[p],g)>0;)p--}0===a(r[n],g)?t(r,n,p):t(r,++p,i),p<=o&&(n=p+1),o<=p&&(i=p-1)}}(e,o,n||0,i||e.length-1,a||r)}function t(e,t,r){var o=e[t];e[t]=e[r],e[r]=o}function r(e,t){return e<t?-1:e>t?1:0}var o=function(e){void 0===e&&(e=9),this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function n(e,t,r){if(!r)return t.indexOf(e);for(var o=0;o<t.length;o++)if(r(e,t[o]))return o;return-1}function i(e,t){a(e,0,e.children.length,t,e)}function a(e,t,r,o,n){n||(n=p(null)),n.minX=1/0,n.minY=1/0,n.maxX=-1/0,n.maxY=-1/0;for(var i=t;i<r;i++){var a=e.children[i];s(n,e.leaf?o(a):a)}return n}function s(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function l(e,t){return e.minX-t.minX}function c(e,t){return e.minY-t.minY}function u(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function h(e){return e.maxX-e.minX+(e.maxY-e.minY)}function g(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function d(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function p(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function f(t,r,o,n,i){for(var a=[r,o];a.length;)if(!((o=a.pop())-(r=a.pop())<=n)){var s=r+Math.ceil((o-r)/n/2)*n;e(t,s,r,o,i),a.push(r,s,s,o)}}return o.prototype.all=function(){return this._all(this.data,[])},o.prototype.search=function(e){var t=this.data,r=[];if(!d(e,t))return r;for(var o=this.toBBox,n=[];t;){for(var i=0;i<t.children.length;i++){var a=t.children[i],s=t.leaf?o(a):a;d(e,s)&&(t.leaf?r.push(a):g(e,s)?this._all(a,r):n.push(a))}t=n.pop()}return r},o.prototype.collides=function(e){var t=this.data;if(!d(e,t))return!1;for(var r=[];t;){for(var o=0;o<t.children.length;o++){var n=t.children[o],i=t.leaf?this.toBBox(n):n;if(d(e,i)){if(t.leaf||g(e,i))return!0;r.push(n)}}t=r.pop()}return!1},o.prototype.load=function(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(var t=0;t<e.length;t++)this.insert(e[t]);return this}var r=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===r.height)this._splitRoot(this.data,r);else{if(this.data.height<r.height){var o=this.data;this.data=r,r=o}this._insert(r,this.data.height-r.height-1,!0)}else this.data=r;return this},o.prototype.insert=function(e){return e&&this._insert(e,this.data.height-1),this},o.prototype.clear=function(){return this.data=p([]),this},o.prototype.remove=function(e,t){if(!e)return this;for(var r,o,i,a=this.data,s=this.toBBox(e),l=[],c=[];a||l.length;){if(a||(a=l.pop(),o=l[l.length-1],r=c.pop(),i=!0),a.leaf){var u=n(e,a.children,t);if(-1!==u)return a.children.splice(u,1),l.push(a),this._condense(l),this}i||a.leaf||!g(a,s)?o?(r++,a=o.children[r],i=!1):a=null:(l.push(a),c.push(r),r=0,o=a,a=a.children[0])}return this},o.prototype.toBBox=function(e){return e},o.prototype.compareMinX=function(e,t){return e.minX-t.minX},o.prototype.compareMinY=function(e,t){return e.minY-t.minY},o.prototype.toJSON=function(){return this.data},o.prototype.fromJSON=function(e){return this.data=e,this},o.prototype._all=function(e,t){for(var r=[];e;)e.leaf?t.push.apply(t,e.children):r.push.apply(r,e.children),e=r.pop();return t},o.prototype._build=function(e,t,r,o){var n,a=r-t+1,s=this._maxEntries;if(a<=s)return i(n=p(e.slice(t,r+1)),this.toBBox),n;o||(o=Math.ceil(Math.log(a)/Math.log(s)),s=Math.ceil(a/Math.pow(s,o-1))),(n=p([])).leaf=!1,n.height=o;var l=Math.ceil(a/s),c=l*Math.ceil(Math.sqrt(s));f(e,t,r,c,this.compareMinX);for(var u=t;u<=r;u+=c){var h=Math.min(u+c-1,r);f(e,u,h,l,this.compareMinY);for(var g=u;g<=h;g+=l){var d=Math.min(g+l-1,h);n.children.push(this._build(e,g,d,o-1))}}return i(n,this.toBBox),n},o.prototype._chooseSubtree=function(e,t,r,o){for(;o.push(t),!t.leaf&&o.length-1!==r;){for(var n=1/0,i=1/0,a=void 0,s=0;s<t.children.length;s++){var l=t.children[s],c=u(l),h=(g=e,d=l,(Math.max(d.maxX,g.maxX)-Math.min(d.minX,g.minX))*(Math.max(d.maxY,g.maxY)-Math.min(d.minY,g.minY))-c);h<i?(i=h,n=c<n?c:n,a=l):h===i&&c<n&&(n=c,a=l)}t=a||t.children[0]}var g,d;return t},o.prototype._insert=function(e,t,r){var o=r?e:this.toBBox(e),n=[],i=this._chooseSubtree(o,this.data,t,n);for(i.children.push(e),s(i,o);t>=0&&n[t].children.length>this._maxEntries;)this._split(n,t),t--;this._adjustParentBBoxes(o,n,t)},o.prototype._split=function(e,t){var r=e[t],o=r.children.length,n=this._minEntries;this._chooseSplitAxis(r,n,o);var a=this._chooseSplitIndex(r,n,o),s=p(r.children.splice(a,r.children.length-a));s.height=r.height,s.leaf=r.leaf,i(r,this.toBBox),i(s,this.toBBox),t?e[t-1].children.push(s):this._splitRoot(r,s)},o.prototype._splitRoot=function(e,t){this.data=p([e,t]),this.data.height=e.height+1,this.data.leaf=!1,i(this.data,this.toBBox)},o.prototype._chooseSplitIndex=function(e,t,r){for(var o,n,i,s,l,c,h,g=1/0,d=1/0,p=t;p<=r-t;p++){var f=a(e,0,p,this.toBBox),y=a(e,p,r,this.toBBox),m=(n=f,i=y,s=void 0,l=void 0,c=void 0,h=void 0,s=Math.max(n.minX,i.minX),l=Math.max(n.minY,i.minY),c=Math.min(n.maxX,i.maxX),h=Math.min(n.maxY,i.maxY),Math.max(0,c-s)*Math.max(0,h-l)),v=u(f)+u(y);m<g?(g=m,o=p,d=v<d?v:d):m===g&&v<d&&(d=v,o=p)}return o||r-t},o.prototype._chooseSplitAxis=function(e,t,r){var o=e.leaf?this.compareMinX:l,n=e.leaf?this.compareMinY:c;this._allDistMargin(e,t,r,o)<this._allDistMargin(e,t,r,n)&&e.children.sort(o)},o.prototype._allDistMargin=function(e,t,r,o){e.children.sort(o);for(var n=this.toBBox,i=a(e,0,t,n),l=a(e,r-t,r,n),c=h(i)+h(l),u=t;u<r-t;u++){var g=e.children[u];s(i,e.leaf?n(g):g),c+=h(i)}for(var d=r-t-1;d>=t;d--){var p=e.children[d];s(l,e.leaf?n(p):p),c+=h(l)}return c},o.prototype._adjustParentBBoxes=function(e,t,r){for(var o=r;o>=0;o--)s(t[o],e)},o.prototype._condense=function(e){for(var t=e.length-1,r=void 0;t>=0;t--)0===e[t].children.length?t>0?(r=e[t-1].children).splice(r.indexOf(e[t]),1):this.clear():i(e[t],this.toBBox)},o}()),Q.exports}function te(e,t){return e<t?-1:e>t?1:0}const re=K(Object.freeze(Object.defineProperty({__proto__:null,default:class{constructor(e=[],t=te){if(this.data=e,this.length=this.data.length,this.compare=t,this.length>0)for(let r=(this.length>>1)-1;r>=0;r--)this._down(r)}push(e){this.data.push(e),this.length++,this._up(this.length-1)}pop(){if(0===this.length)return;const e=this.data[0],t=this.data.pop();return this.length--,this.length>0&&(this.data[0]=t,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:t,compare:r}=this,o=t[e];for(;e>0;){const n=e-1>>1,i=t[n];if(r(o,i)>=0)break;t[e]=i,e=n}t[e]=o}_down(e){const{data:t,compare:r}=this,o=this.length>>1,n=t[e];for(;e<o;){let o=1+(e<<1),i=t[o];const a=o+1;if(a<this.length&&r(t[a],i)<0&&(o=a,i=t[a]),r(i,n)>=0)break;t[e]=i,e=o}t[e]=n}}},Symbol.toStringTag,{value:"Module"})));var oe,ne,ie,ae,se,le={exports:{}};function ce(){if(se)return le.exports;se=1;var e=ne?oe:(ne=1,oe=function(e,t,r,o){var n=e[0],i=e[1],a=!1;void 0===r&&(r=0),void 0===o&&(o=t.length);for(var s=(o-r)/2,l=0,c=s-1;l<s;c=l++){var u=t[r+2*l+0],h=t[r+2*l+1],g=t[r+2*c+0],d=t[r+2*c+1];h>i!=d>i&&n<(g-u)*(i-h)/(d-h)+u&&(a=!a)}return a}),t=ae?ie:(ae=1,ie=function(e,t,r,o){var n=e[0],i=e[1],a=!1;void 0===r&&(r=0),void 0===o&&(o=t.length);for(var s=o-r,l=0,c=s-1;l<s;c=l++){var u=t[l+r][0],h=t[l+r][1],g=t[c+r][0],d=t[c+r][1];h>i!=d>i&&n<(g-u)*(i-h)/(d-h)+u&&(a=!a)}return a});return le.exports=function(r,o,n,i){return o.length>0&&Array.isArray(o[0])?t(r,o,n,i):e(r,o,n,i)},le.exports.nested=t,le.exports.flat=e,le.exports}var ue,he,ge={exports:{}};function de(){return ue||(ue=1,function(e){const t=134217729,r=33306690738754706e-32;function o(e,t,r,o,n){let i,a,s,l,c=t[0],u=o[0],h=0,g=0;u>c==u>-c?(i=c,c=t[++h]):(i=u,u=o[++g]);let d=0;if(h<e&&g<r)for(u>c==u>-c?(s=i-((a=c+i)-c),c=t[++h]):(s=i-((a=u+i)-u),u=o[++g]),i=a,0!==s&&(n[d++]=s);h<e&&g<r;)u>c==u>-c?(s=i-((a=i+c)-(l=a-i))+(c-l),c=t[++h]):(s=i-((a=i+u)-(l=a-i))+(u-l),u=o[++g]),i=a,0!==s&&(n[d++]=s);for(;h<e;)s=i-((a=i+c)-(l=a-i))+(c-l),c=t[++h],i=a,0!==s&&(n[d++]=s);for(;g<r;)s=i-((a=i+u)-(l=a-i))+(u-l),u=o[++g],i=a,0!==s&&(n[d++]=s);return 0===i&&0!==d||(n[d++]=i),d}function n(e){return new Float64Array(e)}const i=33306690738754716e-32,a=22204460492503146e-32,s=11093356479670487e-47,l=n(4),c=n(8),u=n(12),h=n(16),g=n(4);e.orient2d=function(e,n,d,p,f,y){const m=(n-y)*(d-f),v=(e-f)*(p-y),M=m-v;if(0===m||0===v||m>0!=v>0)return M;const b=Math.abs(m+v);return Math.abs(M)>=i*b?M:-function(e,n,i,d,p,f,y){let m,v,M,b,w,P,L,k,x,E,S,D,C,I,A,F,O,T;const _=e-p,G=i-p,H=n-f,B=d-f;w=(A=(k=_-(L=(P=t*_)-(P-_)))*(E=B-(x=(P=t*B)-(P-B)))-((I=_*B)-L*x-k*x-L*E))-(S=A-(O=(k=H-(L=(P=t*H)-(P-H)))*(E=G-(x=(P=t*G)-(P-G)))-((F=H*G)-L*x-k*x-L*E))),l[0]=A-(S+w)+(w-O),w=(C=I-((D=I+S)-(w=D-I))+(S-w))-(S=C-F),l[1]=C-(S+w)+(w-F),w=(T=D+S)-D,l[2]=D-(T-w)+(S-w),l[3]=T;let z=function(e,t){let r=t[0];for(let o=1;o<e;o++)r+=t[o];return r}(4,l),U=a*y;if(z>=U||-z>=U)return z;if(m=e-(_+(w=e-_))+(w-p),M=i-(G+(w=i-G))+(w-p),v=n-(H+(w=n-H))+(w-f),b=d-(B+(w=d-B))+(w-f),0===m&&0===v&&0===M&&0===b)return z;if(U=s*y+r*Math.abs(z),(z+=_*b+B*m-(H*M+G*v))>=U||-z>=U)return z;w=(A=(k=m-(L=(P=t*m)-(P-m)))*(E=B-(x=(P=t*B)-(P-B)))-((I=m*B)-L*x-k*x-L*E))-(S=A-(O=(k=v-(L=(P=t*v)-(P-v)))*(E=G-(x=(P=t*G)-(P-G)))-((F=v*G)-L*x-k*x-L*E))),g[0]=A-(S+w)+(w-O),w=(C=I-((D=I+S)-(w=D-I))+(S-w))-(S=C-F),g[1]=C-(S+w)+(w-F),w=(T=D+S)-D,g[2]=D-(T-w)+(S-w),g[3]=T;const N=o(4,l,4,g,c);w=(A=(k=_-(L=(P=t*_)-(P-_)))*(E=b-(x=(P=t*b)-(P-b)))-((I=_*b)-L*x-k*x-L*E))-(S=A-(O=(k=H-(L=(P=t*H)-(P-H)))*(E=M-(x=(P=t*M)-(P-M)))-((F=H*M)-L*x-k*x-L*E))),g[0]=A-(S+w)+(w-O),w=(C=I-((D=I+S)-(w=D-I))+(S-w))-(S=C-F),g[1]=C-(S+w)+(w-F),w=(T=D+S)-D,g[2]=D-(T-w)+(S-w),g[3]=T;const R=o(N,c,4,g,u);w=(A=(k=m-(L=(P=t*m)-(P-m)))*(E=b-(x=(P=t*b)-(P-b)))-((I=m*b)-L*x-k*x-L*E))-(S=A-(O=(k=v-(L=(P=t*v)-(P-v)))*(E=M-(x=(P=t*M)-(P-M)))-((F=v*M)-L*x-k*x-L*E))),g[0]=A-(S+w)+(w-O),w=(C=I-((D=I+S)-(w=D-I))+(S-w))-(S=C-F),g[1]=C-(S+w)+(w-F),w=(T=D+S)-D,g[2]=D-(T-w)+(S-w),g[3]=T;const X=o(R,u,4,g,h);return h[X-1]}(e,n,d,p,f,y,b)},e.orient2dfast=function(e,t,r,o,n,i){return(t-i)*(r-n)-(e-n)*(o-i)},Object.defineProperty(e,"__esModule",{value:!0})}(ge.exports)),ge.exports}const pe=$(function(){if(he)return Z.exports;he=1;var e=ee(),t=re,r=ce(),o=de().orient2d;function n(t,o,n){o=Math.max(0,void 0===o?2:o),n=n||0;var a=function(e){for(var t=e[0],o=e[0],n=e[0],i=e[0],a=0;a<e.length;a++){var s=e[a];s[0]<t[0]&&(t=s),s[0]>n[0]&&(n=s),s[1]<o[1]&&(o=s),s[1]>i[1]&&(i=s)}var l=[t,o,n,i],c=l.slice();for(a=0;a<e.length;a++)r(e[a],l)||c.push(e[a]);return function(e){e.sort(m);for(var t=[],r=0;r<e.length;r++){for(;t.length>=2&&u(t[t.length-2],t[t.length-1],e[r])<=0;)t.pop();t.push(e[r])}for(var o=[],n=e.length-1;n>=0;n--){for(;o.length>=2&&u(o[o.length-2],o[o.length-1],e[n])<=0;)o.pop();o.push(e[n])}return o.pop(),t.pop(),t.concat(o)}(c)}(t),s=new e(16);s.toBBox=function(e){return{minX:e[0],minY:e[1],maxX:e[0],maxY:e[1]}},s.compareMinX=function(e,t){return e[0]-t[0]},s.compareMinY=function(e,t){return e[1]-t[1]},s.load(t);for(var l,c=[],h=0;h<a.length;h++){var f=a[h];s.remove(f),l=d(f,l),c.push(l)}var y=new e(16);for(h=0;h<c.length;h++)y.insert(g(c[h]));for(var v=o*o,M=n*n;c.length;){var b=c.shift(),w=b.p,P=b.next.p,L=p(w,P);if(!(L<M)){var k=L/v;(f=i(s,b.prev.p,w,P,b.next.next.p,k,y))&&Math.min(p(f,w),p(f,P))<=k&&(c.push(b),c.push(d(f,b)),s.remove(f),y.remove(b),y.insert(g(b)),y.insert(g(b.next)))}}b=l;var x=[];do{x.push(b.p),b=b.next}while(b!==l);return x.push(b.p),x}function i(e,r,o,n,i,l,u){for(var h=new t([],a),g=e.data;g;){for(var d=0;d<g.children.length;d++){var p=g.children[d],y=g.leaf?f(p,o,n):s(o,n,p);y>l||h.push({node:p,dist:y})}for(;h.length&&!h.peek().node.children;){var m=h.pop(),v=m.node,M=f(v,r,o),b=f(v,n,i);if(m.dist<M&&m.dist<b&&c(o,v,u)&&c(n,v,u))return v}(g=h.pop())&&(g=g.node)}return null}function a(e,t){return e.dist-t.dist}function s(e,t,r){if(l(e,r)||l(t,r))return 0;var o=y(e[0],e[1],t[0],t[1],r.minX,r.minY,r.maxX,r.minY);if(0===o)return 0;var n=y(e[0],e[1],t[0],t[1],r.minX,r.minY,r.minX,r.maxY);if(0===n)return 0;var i=y(e[0],e[1],t[0],t[1],r.maxX,r.minY,r.maxX,r.maxY);if(0===i)return 0;var a=y(e[0],e[1],t[0],t[1],r.minX,r.maxY,r.maxX,r.maxY);return 0===a?0:Math.min(o,n,i,a)}function l(e,t){return e[0]>=t.minX&&e[0]<=t.maxX&&e[1]>=t.minY&&e[1]<=t.maxY}function c(e,t,r){for(var o=Math.min(e[0],t[0]),n=Math.min(e[1],t[1]),i=Math.max(e[0],t[0]),a=Math.max(e[1],t[1]),s=r.search({minX:o,minY:n,maxX:i,maxY:a}),l=0;l<s.length;l++)if(h(s[l].p,s[l].next.p,e,t))return!1;return!0}function u(e,t,r){return o(e[0],e[1],t[0],t[1],r[0],r[1])}function h(e,t,r,o){return e!==o&&t!==r&&u(e,t,r)>0!=u(e,t,o)>0&&u(r,o,e)>0!=u(r,o,t)>0}function g(e){var t=e.p,r=e.next.p;return e.minX=Math.min(t[0],r[0]),e.minY=Math.min(t[1],r[1]),e.maxX=Math.max(t[0],r[0]),e.maxY=Math.max(t[1],r[1]),e}function d(e,t){var r={p:e,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return t?(r.next=t.next,r.prev=t,t.next.prev=r,t.next=r):(r.prev=r,r.next=r),r}function p(e,t){var r=e[0]-t[0],o=e[1]-t[1];return r*r+o*o}function f(e,t,r){var o=t[0],n=t[1],i=r[0]-o,a=r[1]-n;if(0!==i||0!==a){var s=((e[0]-o)*i+(e[1]-n)*a)/(i*i+a*a);s>1?(o=r[0],n=r[1]):s>0&&(o+=i*s,n+=a*s)}return(i=e[0]-o)*i+(a=e[1]-n)*a}function y(e,t,r,o,n,i,a,s){var l,c,u,h,g=r-e,d=o-t,p=a-n,f=s-i,y=e-n,m=t-i,v=g*g+d*d,M=g*p+d*f,b=p*p+f*f,w=g*y+d*m,P=p*y+f*m,L=v*b-M*M,k=L,x=L;0===L?(c=0,k=1,h=P,x=b):(h=v*P-M*w,(c=M*P-b*w)<0?(c=0,h=P,x=b):c>k&&(c=k,h=P+M,x=b)),h<0?(h=0,-w<0?c=0:-w>v?c=k:(c=-w,k=v)):h>x&&(h=x,-w+M<0?c=0:-w+M>v?c=k:(c=-w+M,k=v));var E=(1-(u=0===h?0:h/x))*n+u*a-((1-(l=0===c?0:c/k))*e+l*r),S=(1-u)*i+u*s-((1-l)*t+l*o);return E*E+S*S}function m(e,t){return e[0]===t[0]?e[1]-t[1]:e[0]-t[0]}return t.default&&(t=t.default),Z.exports=n,Z.exports.default=n,Z.exports}());function fe(e,t={}){t.concavity=t.concavity||1/0;const r=[];if(W(e,e=>{r.push([e[0],e[1]])}),!r.length)return null;const o=pe(r,t.concavity);return o.length>3?O([o]):null}var ye=fe;function me(e,t,r){if(null!==e)for(var o,n,i,a,s,l,c,u,h=0,g=0,d=e.type,p="FeatureCollection"===d,f="Feature"===d,y=p?e.features.length:1,m=0;m<y;m++){s=(u=!!(c=p?e.features[m].geometry:f?e.geometry:e)&&"GeometryCollection"===c.type)?c.geometries.length:1;for(var v=0;v<s;v++){var M=0,b=0;if(null!==(a=u?c.geometries[v]:c)){l=a.coordinates;var w=a.type;switch(h="Polygon"===w||"MultiPolygon"===w?1:0,w){case null:break;case"Point":if(!1===t(l,g,m,M,b))return!1;g++,M++;break;case"LineString":case"MultiPoint":for(o=0;o<l.length;o++){if(!1===t(l[o],g,m,M,b))return!1;g++,"MultiPoint"===w&&M++}"LineString"===w&&M++;break;case"Polygon":case"MultiLineString":for(o=0;o<l.length;o++){for(n=0;n<l[o].length-h;n++){if(!1===t(l[o][n],g,m,M,b))return!1;g++}"MultiLineString"===w&&M++,"Polygon"===w&&b++}"Polygon"===w&&M++;break;case"MultiPolygon":for(o=0;o<l.length;o++){for(b=0,n=0;n<l[o].length;n++){for(i=0;i<l[o][n].length-h;i++){if(!1===t(l[o][n][i],g,m,M,b))return!1;g++}b++}M++}break;case"GeometryCollection":for(o=0;o<a.geometries.length;o++)if(!1===me(a.geometries[o],t))return!1;break;default:throw new Error("Unknown Geometry Type")}}}}}function ve(e,t={}){let r=0,o=0,n=0;return me(e,function(e){r+=e[0],o+=e[1],n++}),F([r/n,o/n],t.properties)}function Me(e){if(!e)throw new Error("coord is required");if(!Array.isArray(e)){if("Feature"===e.type&&null!==e.geometry&&"Point"===e.geometry.type)return[...e.geometry.coordinates];if("Point"===e.type)return[...e.coordinates]}if(Array.isArray(e)&&e.length>=2&&!Array.isArray(e[0])&&!Array.isArray(e[1]))return[...e];throw new Error("coord must be GeoJSON Point or an Array of numbers")}function be(e){if(Array.isArray(e))return e;if("Feature"===e.type){if(null!==e.geometry)return e.geometry.coordinates}else if(e.coordinates)return e.coordinates;throw new Error("coords must be GeoJSON Feature, Geometry Object or an Array")}function we(e){return"Feature"===e.type?e.geometry:e}function Pe(e,t){return"FeatureCollection"===e.type?"FeatureCollection":"GeometryCollection"===e.type?"GeometryCollection":"Feature"===e.type&&null!==e.geometry?e.geometry.type:e.type}function Le(e,t,r){if(null!==e)for(var o,n,i,a,s,l,c,u,h=0,g=0,d=e.type,p="FeatureCollection"===d,f="Feature"===d,y=p?e.features.length:1,m=0;m<y;m++){s=(u=!!(c=p?e.features[m].geometry:f?e.geometry:e)&&"GeometryCollection"===c.type)?c.geometries.length:1;for(var v=0;v<s;v++){var M=0,b=0;if(null!==(a=u?c.geometries[v]:c)){l=a.coordinates;var w=a.type;switch(h=0,w){case null:break;case"Point":if(!1===t(l,g,m,M,b))return!1;g++,M++;break;case"LineString":case"MultiPoint":for(o=0;o<l.length;o++){if(!1===t(l[o],g,m,M,b))return!1;g++,"MultiPoint"===w&&M++}"LineString"===w&&M++;break;case"Polygon":case"MultiLineString":for(o=0;o<l.length;o++){for(n=0;n<l[o].length-h;n++){if(!1===t(l[o][n],g,m,M,b))return!1;g++}"MultiLineString"===w&&M++,"Polygon"===w&&b++}"Polygon"===w&&M++;break;case"MultiPolygon":for(o=0;o<l.length;o++){for(b=0,n=0;n<l[o].length;n++){for(i=0;i<l[o][n].length-h;i++){if(!1===t(l[o][n][i],g,m,M,b))return!1;g++}b++}M++}break;case"GeometryCollection":for(o=0;o<a.geometries.length;o++)if(!1===Le(a.geometries[o],t))return!1;break;default:throw new Error("Unknown Geometry Type")}}}}}var ke=function e(t,r={}){switch(Pe(t)){case"Point":return F(Me(t),r.properties);case"Polygon":var o=[];Le(t,function(e){o.push(e)});var n,i,a,s,l,c,u,h,g=ve(t,{properties:r.properties}),d=g.geometry.coordinates,p=0,f=0,y=0,m=o.map(function(e){return[e[0]-d[0],e[1]-d[1]]});for(n=0;n<o.length-1;n++)s=(i=m[n])[0],c=i[1],l=(a=m[n+1])[0],y+=h=s*(u=a[1])-l*c,p+=(s+l)*h,f+=(c+u)*h;if(0===y)return g;var v=1/(6*(.5*y));return F([d[0]+v*p,d[1]+v*f],r.properties);default:var M=fe(t);return M?e(M,{properties:r.properties}):ve(t,{properties:r.properties})}};let xe=class{constructor(e=[],t=Ee){if(this.data=e,this.length=this.data.length,this.compare=t,this.length>0)for(let r=(this.length>>1)-1;r>=0;r--)this._down(r)}push(e){this.data.push(e),this.length++,this._up(this.length-1)}pop(){if(0===this.length)return;const e=this.data[0],t=this.data.pop();return this.length--,this.length>0&&(this.data[0]=t,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:t,compare:r}=this,o=t[e];for(;e>0;){const n=e-1>>1,i=t[n];if(r(o,i)>=0)break;t[e]=i,e=n}t[e]=o}_down(e){const{data:t,compare:r}=this,o=this.length>>1,n=t[e];for(;e<o;){let o=1+(e<<1),i=t[o];const a=o+1;if(a<this.length&&r(t[a],i)<0&&(o=a,i=t[a]),r(i,n)>=0)break;t[e]=i,e=o}t[e]=n}};function Ee(e,t){return e<t?-1:e>t?1:0}function Se(e,t){return e.p.x>t.p.x?1:e.p.x<t.p.x?-1:e.p.y!==t.p.y?e.p.y>t.p.y?1:-1:1}function De(e,t){return e.rightSweepEvent.p.x>t.rightSweepEvent.p.x?1:e.rightSweepEvent.p.x<t.rightSweepEvent.p.x?-1:e.rightSweepEvent.p.y!==t.rightSweepEvent.p.y?e.rightSweepEvent.p.y<t.rightSweepEvent.p.y?1:-1:1}let Ce=class{constructor(e,t,r,o){this.p={x:e[0],y:e[1]},this.featureId=t,this.ringId=r,this.eventId=o,this.otherEvent=null,this.isLeftEndpoint=null}isSamePoint(e){return this.p.x===e.p.x&&this.p.y===e.p.y}};let Ie=0,Ae=0,Fe=0;function Oe(e,t){const r="Feature"===e.type?e.geometry:e;let o=r.coordinates;"Polygon"!==r.type&&"MultiLineString"!==r.type||(o=[o]),"LineString"===r.type&&(o=[[o]]);for(let n=0;n<o.length;n++)for(let e=0;e<o[n].length;e++){let r=o[n][e][0],i=null;Ae+=1;for(let a=0;a<o[n][e].length-1;a++){i=o[n][e][a+1];const s=new Ce(r,Ie,Ae,Fe),l=new Ce(i,Ie,Ae,Fe+1);s.otherEvent=l,l.otherEvent=s,Se(s,l)>0?(l.isLeftEndpoint=!0,s.isLeftEndpoint=!1):(s.isLeftEndpoint=!0,l.isLeftEndpoint=!1),t.push(s),t.push(l),r=i,Fe+=1}}Ie+=1}let Te=class{constructor(e){this.leftSweepEvent=e,this.rightSweepEvent=e.otherEvent}};function _e(e,t){if(null===e||null===t)return!1;if(e.leftSweepEvent.ringId===t.leftSweepEvent.ringId&&(e.rightSweepEvent.isSamePoint(t.leftSweepEvent)||e.rightSweepEvent.isSamePoint(t.leftSweepEvent)||e.rightSweepEvent.isSamePoint(t.rightSweepEvent)||e.leftSweepEvent.isSamePoint(t.leftSweepEvent)||e.leftSweepEvent.isSamePoint(t.rightSweepEvent)))return!1;const r=e.leftSweepEvent.p.x,o=e.leftSweepEvent.p.y,n=e.rightSweepEvent.p.x,i=e.rightSweepEvent.p.y,a=t.leftSweepEvent.p.x,s=t.leftSweepEvent.p.y,l=t.rightSweepEvent.p.x,c=t.rightSweepEvent.p.y,u=(c-s)*(n-r)-(l-a)*(i-o),h=(l-a)*(o-s)-(c-s)*(r-a),g=(n-r)*(o-s)-(i-o)*(r-a);if(0===u)return!1;const d=h/u,p=g/u;if(d>=0&&d<=1&&p>=0&&p<=1){return[r+d*(n-r),o+d*(i-o)]}return!1}var Ge=function(e,t){const r=new xe([],Se);return function(e,t){if("FeatureCollection"===e.type){const r=e.features;for(let e=0;e<r.length;e++)Oe(r[e],t)}else Oe(e,t)}(e,r),function(e,t){t=t||!1;const r=[],o=new xe([],De);for(;e.length;){const n=e.pop();if(n.isLeftEndpoint){const e=new Te(n);for(let i=0;i<o.data.length;i++){const a=o.data[i];if(t&&a.leftSweepEvent.featureId===n.featureId)continue;const s=_e(e,a);!1!==s&&r.push(s)}o.push(e)}else!1===n.isLeftEndpoint&&o.pop()}return r}(r,t)};function He(e,t,r={}){const{removeDuplicates:o=!0,ignoreSelfIntersections:n=!0}=r;let i=[];"FeatureCollection"===e.type?i=i.concat(e.features):"Feature"===e.type?i.push(e):"LineString"!==e.type&&"Polygon"!==e.type&&"MultiLineString"!==e.type&&"MultiPolygon"!==e.type||i.push(A(e)),"FeatureCollection"===t.type?i=i.concat(t.features):"Feature"===t.type?i.push(t):"LineString"!==t.type&&"Polygon"!==t.type&&"MultiLineString"!==t.type&&"MultiPolygon"!==t.type||i.push(A(t));const a=Ge(_(i),n);let s=[];if(o){const e={};a.forEach(t=>{const r=t.join(",");e[r]||(e[r]=!0,s.push(t))})}else s=a;return _(s.map(e=>F(e)))}var Be=He,ze=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Ue=Math.ceil,Ne=Math.floor,Re="[BigNumber Error] ",Xe=Re+"Number primitive has more than 15 significant digits: ",Ye=1e14,Ve=14,qe=9007199254740991,je=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],We=1e7,$e=1e9;function Ke(e){var t=0|e;return e>0||e===t?t:t-1}function Je(e){for(var t,r,o=1,n=e.length,i=e[0]+"";o<n;){for(t=e[o++]+"",r=Ve-t.length;r--;t="0"+t);i+=t}for(n=i.length;48===i.charCodeAt(--n););return i.slice(0,n+1||1)}function Ze(e,t){var r,o,n=e.c,i=t.c,a=e.s,s=t.s,l=e.e,c=t.e;if(!a||!s)return null;if(r=n&&!n[0],o=i&&!i[0],r||o)return r?o?0:-s:a;if(a!=s)return a;if(r=a<0,o=l==c,!n||!i)return o?0:!n^r?1:-1;if(!o)return l>c^r?1:-1;for(s=(l=n.length)<(c=i.length)?l:c,a=0;a<s;a++)if(n[a]!=i[a])return n[a]>i[a]^r?1:-1;return l==c?0:l>c^r?1:-1}function Qe(e,t,r,o){if(e<t||e>r||e!==Ne(e))throw Error(Re+(o||"Argument")+("number"==typeof e?e<t||e>r?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function et(e){var t=e.c.length-1;return Ke(e.e/Ve)==t&&e.c[t]%2!=0}function tt(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function rt(e,t,r){var o,n;if(t<0){for(n=r+".";++t;n+=r);e=n+e}else if(++t>(o=e.length)){for(n=r,t-=o;--t;n+=r);e+=n}else t<o&&(e=e.slice(0,t)+"."+e.slice(t));return e}var ot=function e(t){var r,o,n,i,a,s=w.prototype={constructor:w,toString:null,valueOf:null},l=new w(1),c=20,u=4,h=-7,g=21,d=-1e7,p=1e7,f=!1,y=1,m=0,v={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:" ",suffix:""},M="0123456789abcdefghijklmnopqrstuvwxyz",b=!0;function w(e,t){var r,i,a,s,l,h,g,f,y=this;if(!(y instanceof w))return new w(e,t);if(null==t){if(e&&!0===e._isBigNumber)return y.s=e.s,void(!e.c||e.e>p?y.c=y.e=null:e.e<d?y.c=[y.e=0]:(y.e=e.e,y.c=e.c.slice()));if((h="number"==typeof e)&&0*e==0){if(y.s=1/e<0?(e=-e,-1):1,e===~~e){for(s=0,l=e;l>=10;l/=10,s++);return void(s>p?y.c=y.e=null:(y.e=s,y.c=[e]))}f=String(e)}else{if(!ze.test(f=String(e)))return n(y,f,h);y.s=45==f.charCodeAt(0)?(f=f.slice(1),-1):1}(s=f.indexOf("."))>-1&&(f=f.replace(".","")),(l=f.search(/e/i))>0?(s<0&&(s=l),s+=+f.slice(l+1),f=f.substring(0,l)):s<0&&(s=f.length)}else{if(Qe(t,2,M.length,"Base"),10==t&&b)return x(y=new w(e),c+y.e+1,u);if(f=String(e),h="number"==typeof e){if(0*e!=0)return n(y,f,h,t);if(y.s=1/e<0?(f=f.slice(1),-1):1,w.DEBUG&&f.replace(/^0\.0*|\./,"").length>15)throw Error(Xe+e)}else y.s=45===f.charCodeAt(0)?(f=f.slice(1),-1):1;for(r=M.slice(0,t),s=l=0,g=f.length;l<g;l++)if(r.indexOf(i=f.charAt(l))<0){if("."==i){if(l>s){s=g;continue}}else if(!a&&(f==f.toUpperCase()&&(f=f.toLowerCase())||f==f.toLowerCase()&&(f=f.toUpperCase()))){a=!0,l=-1,s=0;continue}return n(y,String(e),h,t)}h=!1,(s=(f=o(f,t,10,y.s)).indexOf("."))>-1?f=f.replace(".",""):s=f.length}for(l=0;48===f.charCodeAt(l);l++);for(g=f.length;48===f.charCodeAt(--g););if(f=f.slice(l,++g)){if(g-=l,h&&w.DEBUG&&g>15&&(e>qe||e!==Ne(e)))throw Error(Xe+y.s*e);if((s=s-l-1)>p)y.c=y.e=null;else if(s<d)y.c=[y.e=0];else{if(y.e=s,y.c=[],l=(s+1)%Ve,s<0&&(l+=Ve),l<g){for(l&&y.c.push(+f.slice(0,l)),g-=Ve;l<g;)y.c.push(+f.slice(l,l+=Ve));l=Ve-(f=f.slice(l)).length}else l-=g;for(;l--;f+="0");y.c.push(+f)}}else y.c=[y.e=0]}function P(e,t,r,o){var n,i,a,s,l;if(null==r?r=u:Qe(r,0,8),!e.c)return e.toString();if(n=e.c[0],a=e.e,null==t)l=Je(e.c),l=1==o||2==o&&(a<=h||a>=g)?tt(l,a):rt(l,a,"0");else if(i=(e=x(new w(e),t,r)).e,s=(l=Je(e.c)).length,1==o||2==o&&(t<=i||i<=h)){for(;s<t;l+="0",s++);l=tt(l,i)}else if(t-=a+(2===o&&i>a),l=rt(l,i,"0"),i+1>s){if(--t>0)for(l+=".";t--;l+="0");}else if((t+=i-s)>0)for(i+1==s&&(l+=".");t--;l+="0");return e.s<0&&n?"-"+l:l}function L(e,t){for(var r,o,n=1,i=new w(e[0]);n<e.length;n++)(!(o=new w(e[n])).s||(r=Ze(i,o))===t||0===r&&i.s===t)&&(i=o);return i}function k(e,t,r){for(var o=1,n=t.length;!t[--n];t.pop());for(n=t[0];n>=10;n/=10,o++);return(r=o+r*Ve-1)>p?e.c=e.e=null:r<d?e.c=[e.e=0]:(e.e=r,e.c=t),e}function x(e,t,r,o){var n,i,a,s,l,c,u,h=e.c,g=je;if(h){e:{for(n=1,s=h[0];s>=10;s/=10,n++);if((i=t-n)<0)i+=Ve,a=t,l=h[c=0],u=Ne(l/g[n-a-1]%10);else if((c=Ue((i+1)/Ve))>=h.length){if(!o)break e;for(;h.length<=c;h.push(0));l=u=0,n=1,a=(i%=Ve)-Ve+1}else{for(l=s=h[c],n=1;s>=10;s/=10,n++);u=(a=(i%=Ve)-Ve+n)<0?0:Ne(l/g[n-a-1]%10)}if(o=o||t<0||null!=h[c+1]||(a<0?l:l%g[n-a-1]),o=r<4?(u||o)&&(0==r||r==(e.s<0?3:2)):u>5||5==u&&(4==r||o||6==r&&(i>0?a>0?l/g[n-a]:0:h[c-1])%10&1||r==(e.s<0?8:7)),t<1||!h[0])return h.length=0,o?(t-=e.e+1,h[0]=g[(Ve-t%Ve)%Ve],e.e=-t||0):h[0]=e.e=0,e;if(0==i?(h.length=c,s=1,c--):(h.length=c+1,s=g[Ve-i],h[c]=a>0?Ne(l/g[n-a]%g[a])*s:0),o)for(;;){if(0==c){for(i=1,a=h[0];a>=10;a/=10,i++);for(a=h[0]+=s,s=1;a>=10;a/=10,s++);i!=s&&(e.e++,h[0]==Ye&&(h[0]=1));break}if(h[c]+=s,h[c]!=Ye)break;h[c--]=0,s=1}for(i=h.length;0===h[--i];h.pop());}e.e>p?e.c=e.e=null:e.e<d&&(e.c=[e.e=0])}return e}function E(e){var t,r=e.e;return null===r?e.toString():(t=Je(e.c),t=r<=h||r>=g?tt(t,r):rt(t,r,"0"),e.s<0?"-"+t:t)}return w.clone=e,w.ROUND_UP=0,w.ROUND_DOWN=1,w.ROUND_CEIL=2,w.ROUND_FLOOR=3,w.ROUND_HALF_UP=4,w.ROUND_HALF_DOWN=5,w.ROUND_HALF_EVEN=6,w.ROUND_HALF_CEIL=7,w.ROUND_HALF_FLOOR=8,w.EUCLID=9,w.config=w.set=function(e){var t,r;if(null!=e){if("object"!=typeof e)throw Error(Re+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(Qe(r=e[t],0,$e,t),c=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(Qe(r=e[t],0,8,t),u=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((r=e[t])&&r.pop?(Qe(r[0],-$e,0,t),Qe(r[1],0,$e,t),h=r[0],g=r[1]):(Qe(r,-$e,$e,t),h=-(g=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if((r=e[t])&&r.pop)Qe(r[0],-$e,-1,t),Qe(r[1],1,$e,t),d=r[0],p=r[1];else{if(Qe(r,-$e,$e,t),!r)throw Error(Re+t+" cannot be zero: "+r);d=-(p=r<0?-r:r)}if(e.hasOwnProperty(t="CRYPTO")){if((r=e[t])!==!!r)throw Error(Re+t+" not true or false: "+r);if(r){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw f=!r,Error(Re+"crypto unavailable");f=r}else f=r}if(e.hasOwnProperty(t="MODULO_MODE")&&(Qe(r=e[t],0,9,t),y=r),e.hasOwnProperty(t="POW_PRECISION")&&(Qe(r=e[t],0,$e,t),m=r),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(r=e[t]))throw Error(Re+t+" not an object: "+r);v=r}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(r))throw Error(Re+t+" invalid: "+r);b="0123456789"==r.slice(0,10),M=r}}return{DECIMAL_PLACES:c,ROUNDING_MODE:u,EXPONENTIAL_AT:[h,g],RANGE:[d,p],CRYPTO:f,MODULO_MODE:y,POW_PRECISION:m,FORMAT:v,ALPHABET:M}},w.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!w.DEBUG)return!0;var t,r,o=e.c,n=e.e,i=e.s;e:if("[object Array]"=={}.toString.call(o)){if((1===i||-1===i)&&n>=-$e&&n<=$e&&n===Ne(n)){if(0===o[0]){if(0===n&&1===o.length)return!0;break e}if((t=(n+1)%Ve)<1&&(t+=Ve),String(o[0]).length==t){for(t=0;t<o.length;t++)if((r=o[t])<0||r>=Ye||r!==Ne(r))break e;if(0!==r)return!0}}}else if(null===o&&null===n&&(null===i||1===i||-1===i))return!0;throw Error(Re+"Invalid BigNumber: "+e)},w.maximum=w.max=function(){return L(arguments,-1)},w.minimum=w.min=function(){return L(arguments,1)},w.random=(i=9007199254740992,a=Math.random()*i&2097151?function(){return Ne(Math.random()*i)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,r,o,n,i,s=0,u=[],h=new w(l);if(null==e?e=c:Qe(e,0,$e),n=Ue(e/Ve),f)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(n*=2));s<n;)(i=131072*t[s]+(t[s+1]>>>11))>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),t[s]=r[0],t[s+1]=r[1]):(u.push(i%1e14),s+=2);s=n/2}else{if(!crypto.randomBytes)throw f=!1,Error(Re+"crypto unavailable");for(t=crypto.randomBytes(n*=7);s<n;)(i=281474976710656*(31&t[s])+1099511627776*t[s+1]+4294967296*t[s+2]+16777216*t[s+3]+(t[s+4]<<16)+(t[s+5]<<8)+t[s+6])>=9e15?crypto.randomBytes(7).copy(t,s):(u.push(i%1e14),s+=7);s=n/7}if(!f)for(;s<n;)(i=a())<9e15&&(u[s++]=i%1e14);for(n=u[--s],e%=Ve,n&&e&&(i=je[Ve-e],u[s]=Ne(n/i)*i);0===u[s];u.pop(),s--);if(s<0)u=[o=0];else{for(o=-1;0===u[0];u.splice(0,1),o-=Ve);for(s=1,i=u[0];i>=10;i/=10,s++);s<Ve&&(o-=Ve-s)}return h.e=o,h.c=u,h}),w.sum=function(){for(var e=1,t=arguments,r=new w(t[0]);e<t.length;)r=r.plus(t[e++]);return r},o=function(){var e="0123456789";function t(e,t,r,o){for(var n,i,a=[0],s=0,l=e.length;s<l;){for(i=a.length;i--;a[i]*=t);for(a[0]+=o.indexOf(e.charAt(s++)),n=0;n<a.length;n++)a[n]>r-1&&(null==a[n+1]&&(a[n+1]=0),a[n+1]+=a[n]/r|0,a[n]%=r)}return a.reverse()}return function(o,n,i,a,s){var l,h,g,d,p,f,y,v,b=o.indexOf("."),P=c,L=u;for(b>=0&&(d=m,m=0,o=o.replace(".",""),f=(v=new w(n)).pow(o.length-b),m=d,v.c=t(rt(Je(f.c),f.e,"0"),10,i,e),v.e=v.c.length),g=d=(y=t(o,n,i,s?(l=M,e):(l=e,M))).length;0==y[--d];y.pop());if(!y[0])return l.charAt(0);if(b<0?--g:(f.c=y,f.e=g,f.s=a,y=(f=r(f,v,P,L,i)).c,p=f.r,g=f.e),b=y[h=g+P+1],d=i/2,p=p||h<0||null!=y[h+1],p=L<4?(null!=b||p)&&(0==L||L==(f.s<0?3:2)):b>d||b==d&&(4==L||p||6==L&&1&y[h-1]||L==(f.s<0?8:7)),h<1||!y[0])o=p?rt(l.charAt(1),-P,l.charAt(0)):l.charAt(0);else{if(y.length=h,p)for(--i;++y[--h]>i;)y[h]=0,h||(++g,y=[1].concat(y));for(d=y.length;!y[--d];);for(b=0,o="";b<=d;o+=l.charAt(y[b++]));o=rt(o,g,l.charAt(0))}return o}}(),r=function(){function e(e,t,r){var o,n,i,a,s=0,l=e.length,c=t%We,u=t/We|0;for(e=e.slice();l--;)s=((n=c*(i=e[l]%We)+(o=u*i+(a=e[l]/We|0)*c)%We*We+s)/r|0)+(o/We|0)+u*a,e[l]=n%r;return s&&(e=[s].concat(e)),e}function t(e,t,r,o){var n,i;if(r!=o)i=r>o?1:-1;else for(n=i=0;n<r;n++)if(e[n]!=t[n]){i=e[n]>t[n]?1:-1;break}return i}function r(e,t,r,o){for(var n=0;r--;)e[r]-=n,n=e[r]<t[r]?1:0,e[r]=n*o+e[r]-t[r];for(;!e[0]&&e.length>1;e.splice(0,1));}return function(o,n,i,a,s){var l,c,u,h,g,d,p,f,y,m,v,M,b,P,L,k,E,S=o.s==n.s?1:-1,D=o.c,C=n.c;if(!(D&&D[0]&&C&&C[0]))return new w(o.s&&n.s&&(D?!C||D[0]!=C[0]:C)?D&&0==D[0]||!C?0*S:S/0:NaN);for(y=(f=new w(S)).c=[],S=i+(c=o.e-n.e)+1,s||(s=Ye,c=Ke(o.e/Ve)-Ke(n.e/Ve),S=S/Ve|0),u=0;C[u]==(D[u]||0);u++);if(C[u]>(D[u]||0)&&c--,S<0)y.push(1),h=!0;else{for(P=D.length,k=C.length,u=0,S+=2,(g=Ne(s/(C[0]+1)))>1&&(C=e(C,g,s),D=e(D,g,s),k=C.length,P=D.length),b=k,v=(m=D.slice(0,k)).length;v<k;m[v++]=0);E=C.slice(),E=[0].concat(E),L=C[0],C[1]>=s/2&&L++;do{if(g=0,(l=t(C,m,k,v))<0){if(M=m[0],k!=v&&(M=M*s+(m[1]||0)),(g=Ne(M/L))>1)for(g>=s&&(g=s-1),p=(d=e(C,g,s)).length,v=m.length;1==t(d,m,p,v);)g--,r(d,k<p?E:C,p,s),p=d.length,l=1;else 0==g&&(l=g=1),p=(d=C.slice()).length;if(p<v&&(d=[0].concat(d)),r(m,d,v,s),v=m.length,-1==l)for(;t(C,m,k,v)<1;)g++,r(m,k<v?E:C,v,s),v=m.length}else 0===l&&(g++,m=[0]);y[u++]=g,m[0]?m[v++]=D[b]||0:(m=[D[b]],v=1)}while((b++<P||null!=m[0])&&S--);h=null!=m[0],y[0]||y.splice(0,1)}if(s==Ye){for(u=1,S=y[0];S>=10;S/=10,u++);x(f,i+(f.e=u+c*Ve-1)+1,a,h)}else f.e=c,f.r=+h;return f}}(),n=function(){var e=/^(-?)0([xbo])(?=\w[\w.]*$)/i,t=/^([^.]+)\.$/,r=/^\.([^.]+)$/,o=/^-?(Infinity|NaN)$/,n=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(i,a,s,l){var c,u=s?a:a.replace(n,"");if(o.test(u))i.s=isNaN(u)?null:u<0?-1:1;else{if(!s&&(u=u.replace(e,function(e,t,r){return c="x"==(r=r.toLowerCase())?16:"b"==r?2:8,l&&l!=c?e:t}),l&&(c=l,u=u.replace(t,"$1").replace(r,"0.$1")),a!=u))return new w(u,c);if(w.DEBUG)throw Error(Re+"Not a"+(l?" base "+l:"")+" number: "+a);i.s=null}i.c=i.e=null}}(),s.absoluteValue=s.abs=function(){var e=new w(this);return e.s<0&&(e.s=1),e},s.comparedTo=function(e,t){return Ze(this,new w(e,t))},s.decimalPlaces=s.dp=function(e,t){var r,o,n,i=this;if(null!=e)return Qe(e,0,$e),null==t?t=u:Qe(t,0,8),x(new w(i),e+i.e+1,t);if(!(r=i.c))return null;if(o=((n=r.length-1)-Ke(this.e/Ve))*Ve,n=r[n])for(;n%10==0;n/=10,o--);return o<0&&(o=0),o},s.dividedBy=s.div=function(e,t){return r(this,new w(e,t),c,u)},s.dividedToIntegerBy=s.idiv=function(e,t){return r(this,new w(e,t),0,1)},s.exponentiatedBy=s.pow=function(e,t){var r,o,n,i,a,s,c,h,g=this;if((e=new w(e)).c&&!e.isInteger())throw Error(Re+"Exponent not an integer: "+E(e));if(null!=t&&(t=new w(t)),a=e.e>14,!g.c||!g.c[0]||1==g.c[0]&&!g.e&&1==g.c.length||!e.c||!e.c[0])return h=new w(Math.pow(+E(g),a?e.s*(2-et(e)):+E(e))),t?h.mod(t):h;if(s=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new w(NaN);(o=!s&&g.isInteger()&&t.isInteger())&&(g=g.mod(t))}else{if(e.e>9&&(g.e>0||g.e<-1||(0==g.e?g.c[0]>1||a&&g.c[1]>=24e7:g.c[0]<8e13||a&&g.c[0]<=9999975e7)))return i=g.s<0&&et(e)?-0:0,g.e>-1&&(i=1/i),new w(s?1/i:i);m&&(i=Ue(m/Ve+2))}for(a?(r=new w(.5),s&&(e.s=1),c=et(e)):c=(n=Math.abs(+E(e)))%2,h=new w(l);;){if(c){if(!(h=h.times(g)).c)break;i?h.c.length>i&&(h.c.length=i):o&&(h=h.mod(t))}if(n){if(0===(n=Ne(n/2)))break;c=n%2}else if(x(e=e.times(r),e.e+1,1),e.e>14)c=et(e);else{if(0===(n=+E(e)))break;c=n%2}g=g.times(g),i?g.c&&g.c.length>i&&(g.c.length=i):o&&(g=g.mod(t))}return o?h:(s&&(h=l.div(h)),t?h.mod(t):i?x(h,m,u,void 0):h)},s.integerValue=function(e){var t=new w(this);return null==e?e=u:Qe(e,0,8),x(t,t.e+1,e)},s.isEqualTo=s.eq=function(e,t){return 0===Ze(this,new w(e,t))},s.isFinite=function(){return!!this.c},s.isGreaterThan=s.gt=function(e,t){return Ze(this,new w(e,t))>0},s.isGreaterThanOrEqualTo=s.gte=function(e,t){return 1===(t=Ze(this,new w(e,t)))||0===t},s.isInteger=function(){return!!this.c&&Ke(this.e/Ve)>this.c.length-2},s.isLessThan=s.lt=function(e,t){return Ze(this,new w(e,t))<0},s.isLessThanOrEqualTo=s.lte=function(e,t){return-1===(t=Ze(this,new w(e,t)))||0===t},s.isNaN=function(){return!this.s},s.isNegative=function(){return this.s<0},s.isPositive=function(){return this.s>0},s.isZero=function(){return!!this.c&&0==this.c[0]},s.minus=function(e,t){var r,o,n,i,a=this,s=a.s;if(t=(e=new w(e,t)).s,!s||!t)return new w(NaN);if(s!=t)return e.s=-t,a.plus(e);var l=a.e/Ve,c=e.e/Ve,h=a.c,g=e.c;if(!l||!c){if(!h||!g)return h?(e.s=-t,e):new w(g?a:NaN);if(!h[0]||!g[0])return g[0]?(e.s=-t,e):new w(h[0]?a:3==u?-0:0)}if(l=Ke(l),c=Ke(c),h=h.slice(),s=l-c){for((i=s<0)?(s=-s,n=h):(c=l,n=g),n.reverse(),t=s;t--;n.push(0));n.reverse()}else for(o=(i=(s=h.length)<(t=g.length))?s:t,s=t=0;t<o;t++)if(h[t]!=g[t]){i=h[t]<g[t];break}if(i&&(n=h,h=g,g=n,e.s=-e.s),(t=(o=g.length)-(r=h.length))>0)for(;t--;h[r++]=0);for(t=Ye-1;o>s;){if(h[--o]<g[o]){for(r=o;r&&!h[--r];h[r]=t);--h[r],h[o]+=Ye}h[o]-=g[o]}for(;0==h[0];h.splice(0,1),--c);return h[0]?k(e,h,c):(e.s=3==u?-1:1,e.c=[e.e=0],e)},s.modulo=s.mod=function(e,t){var o,n,i=this;return e=new w(e,t),!i.c||!e.s||e.c&&!e.c[0]?new w(NaN):!e.c||i.c&&!i.c[0]?new w(i):(9==y?(n=e.s,e.s=1,o=r(i,e,0,3),e.s=n,o.s*=n):o=r(i,e,0,y),(e=i.minus(o.times(e))).c[0]||1!=y||(e.s=i.s),e)},s.multipliedBy=s.times=function(e,t){var r,o,n,i,a,s,l,c,u,h,g,d,p,f,y,m=this,v=m.c,M=(e=new w(e,t)).c;if(!(v&&M&&v[0]&&M[0]))return!m.s||!e.s||v&&!v[0]&&!M||M&&!M[0]&&!v?e.c=e.e=e.s=null:(e.s*=m.s,v&&M?(e.c=[0],e.e=0):e.c=e.e=null),e;for(o=Ke(m.e/Ve)+Ke(e.e/Ve),e.s*=m.s,(l=v.length)<(h=M.length)&&(p=v,v=M,M=p,n=l,l=h,h=n),n=l+h,p=[];n--;p.push(0));for(f=Ye,y=We,n=h;--n>=0;){for(r=0,g=M[n]%y,d=M[n]/y|0,i=n+(a=l);i>n;)r=((c=g*(c=v[--a]%y)+(s=d*c+(u=v[a]/y|0)*g)%y*y+p[i]+r)/f|0)+(s/y|0)+d*u,p[i--]=c%f;p[i]=r}return r?++o:p.splice(0,1),k(e,p,o)},s.negated=function(){var e=new w(this);return e.s=-e.s||null,e},s.plus=function(e,t){var r,o=this,n=o.s;if(t=(e=new w(e,t)).s,!n||!t)return new w(NaN);if(n!=t)return e.s=-t,o.minus(e);var i=o.e/Ve,a=e.e/Ve,s=o.c,l=e.c;if(!i||!a){if(!s||!l)return new w(n/0);if(!s[0]||!l[0])return l[0]?e:new w(s[0]?o:0*n)}if(i=Ke(i),a=Ke(a),s=s.slice(),n=i-a){for(n>0?(a=i,r=l):(n=-n,r=s),r.reverse();n--;r.push(0));r.reverse()}for((n=s.length)-(t=l.length)<0&&(r=l,l=s,s=r,t=n),n=0;t;)n=(s[--t]=s[t]+l[t]+n)/Ye|0,s[t]=Ye===s[t]?0:s[t]%Ye;return n&&(s=[n].concat(s),++a),k(e,s,a)},s.precision=s.sd=function(e,t){var r,o,n,i=this;if(null!=e&&e!==!!e)return Qe(e,1,$e),null==t?t=u:Qe(t,0,8),x(new w(i),e,t);if(!(r=i.c))return null;if(o=(n=r.length-1)*Ve+1,n=r[n]){for(;n%10==0;n/=10,o--);for(n=r[0];n>=10;n/=10,o++);}return e&&i.e+1>o&&(o=i.e+1),o},s.shiftedBy=function(e){return Qe(e,-9007199254740991,qe),this.times("1e"+e)},s.squareRoot=s.sqrt=function(){var e,t,o,n,i,a=this,s=a.c,l=a.s,h=a.e,g=c+4,d=new w("0.5");if(1!==l||!s||!s[0])return new w(!l||l<0&&(!s||s[0])?NaN:s?a:1/0);if(0==(l=Math.sqrt(+E(a)))||l==1/0?(((t=Je(s)).length+h)%2==0&&(t+="0"),l=Math.sqrt(+t),h=Ke((h+1)/2)-(h<0||h%2),o=new w(t=l==1/0?"5e"+h:(t=l.toExponential()).slice(0,t.indexOf("e")+1)+h)):o=new w(l+""),o.c[0])for((l=(h=o.e)+g)<3&&(l=0);;)if(i=o,o=d.times(i.plus(r(a,i,g,1))),Je(i.c).slice(0,l)===(t=Je(o.c)).slice(0,l)){if(o.e<h&&--l,"9999"!=(t=t.slice(l-3,l+1))&&(n||"4999"!=t)){+t&&(+t.slice(1)||"5"!=t.charAt(0))||(x(o,o.e+c+2,1),e=!o.times(o).eq(a));break}if(!n&&(x(i,i.e+c+2,0),i.times(i).eq(a))){o=i;break}g+=4,l+=4,n=1}return x(o,o.e+c+1,u,e)},s.toExponential=function(e,t){return null!=e&&(Qe(e,0,$e),e++),P(this,e,t,1)},s.toFixed=function(e,t){return null!=e&&(Qe(e,0,$e),e=e+this.e+1),P(this,e,t)},s.toFormat=function(e,t,r){var o,n=this;if(null==r)null!=e&&t&&"object"==typeof t?(r=t,t=null):e&&"object"==typeof e?(r=e,e=t=null):r=v;else if("object"!=typeof r)throw Error(Re+"Argument not an object: "+r);if(o=n.toFixed(e,t),n.c){var i,a=o.split("."),s=+r.groupSize,l=+r.secondaryGroupSize,c=r.groupSeparator||"",u=a[0],h=a[1],g=n.s<0,d=g?u.slice(1):u,p=d.length;if(l&&(i=s,s=l,l=i,p-=i),s>0&&p>0){for(i=p%s||s,u=d.substr(0,i);i<p;i+=s)u+=c+d.substr(i,s);l>0&&(u+=c+d.slice(i)),g&&(u="-"+u)}o=h?u+(r.decimalSeparator||"")+((l=+r.fractionGroupSize)?h.replace(new RegExp("\\d{"+l+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):h):u}return(r.prefix||"")+o+(r.suffix||"")},s.toFraction=function(e){var t,o,n,i,a,s,c,h,g,d,f,y,m=this,v=m.c;if(null!=e&&(!(c=new w(e)).isInteger()&&(c.c||1!==c.s)||c.lt(l)))throw Error(Re+"Argument "+(c.isInteger()?"out of range: ":"not an integer: ")+E(c));if(!v)return new w(m);for(t=new w(l),g=o=new w(l),n=h=new w(l),y=Je(v),a=t.e=y.length-m.e-1,t.c[0]=je[(s=a%Ve)<0?Ve+s:s],e=!e||c.comparedTo(t)>0?a>0?t:g:c,s=p,p=1/0,c=new w(y),h.c[0]=0;d=r(c,t,0,1),1!=(i=o.plus(d.times(n))).comparedTo(e);)o=n,n=i,g=h.plus(d.times(i=g)),h=i,t=c.minus(d.times(i=t)),c=i;return i=r(e.minus(o),n,0,1),h=h.plus(i.times(g)),o=o.plus(i.times(n)),h.s=g.s=m.s,f=r(g,n,a*=2,u).minus(m).abs().comparedTo(r(h,o,a,u).minus(m).abs())<1?[g,n]:[h,o],p=s,f},s.toNumber=function(){return+E(this)},s.toPrecision=function(e,t){return null!=e&&Qe(e,1,$e),P(this,e,t,2)},s.toString=function(e){var t,r=this,n=r.s,i=r.e;return null===i?n?(t="Infinity",n<0&&(t="-"+t)):t="NaN":(null==e?t=i<=h||i>=g?tt(Je(r.c),i):rt(Je(r.c),i,"0"):10===e&&b?t=rt(Je((r=x(new w(r),c+i+1,u)).c),r.e,"0"):(Qe(e,2,M.length,"Base"),t=o(rt(Je(r.c),i,"0"),10,e,n,!0)),n<0&&r.c[0]&&(t="-"+t)),t},s.valueOf=s.toJSON=function(){return E(this)},s._isBigNumber=!0,s[Symbol.toStringTag]="BigNumber",s[Symbol.for("nodejs.util.inspect.custom")]=s.valueOf,null!=t&&w.set(t),w}(),nt=class{constructor(e){i(this,"key"),i(this,"left",null),i(this,"right",null),this.key=e}},it=class extends nt{constructor(e){super(e)}},at=class{constructor(){i(this,"size",0),i(this,"modificationCount",0),i(this,"splayCount",0)}splay(e){const t=this.root;if(null==t)return this.compare(e,e),-1;let r=null,o=null,n=null,i=null,a=t;const s=this.compare;let l;for(;;)if(l=s(a.key,e),l>0){let t=a.left;if(null==t)break;if(l=s(t.key,e),l>0&&(a.left=t.right,t.right=a,a=t,t=a.left,null==t))break;null==r?o=a:r.left=a,r=a,a=t}else{if(!(l<0))break;{let t=a.right;if(null==t)break;if(l=s(t.key,e),l<0&&(a.right=t.left,t.left=a,a=t,t=a.right,null==t))break;null==n?i=a:n.right=a,n=a,a=t}}return null!=n&&(n.right=a.left,a.left=i),null!=r&&(r.left=a.right,a.right=o),this.root!==a&&(this.root=a,this.splayCount++),l}splayMin(e){let t=e,r=t.left;for(;null!=r;){const e=r;t.left=e.right,e.right=t,t=e,r=t.left}return t}splayMax(e){let t=e,r=t.right;for(;null!=r;){const e=r;t.right=e.left,e.left=t,t=e,r=t.right}return t}_delete(e){if(null==this.root)return null;if(0!=this.splay(e))return null;let t=this.root;const r=t,o=t.left;if(this.size--,null==o)this.root=t.right;else{const e=t.right;t=this.splayMax(o),t.right=e,this.root=t}return this.modificationCount++,r}addNewRoot(e,t){this.size++,this.modificationCount++;const r=this.root;null!=r?(t<0?(e.left=r,e.right=r.right,r.right=null):(e.right=r,e.left=r.left,r.left=null),this.root=e):this.root=e}_first(){const e=this.root;return null==e?null:(this.root=this.splayMin(e),this.root)}_last(){const e=this.root;return null==e?null:(this.root=this.splayMax(e),this.root)}clear(){this.root=null,this.size=0,this.modificationCount++}has(e){return this.validKey(e)&&0==this.splay(e)}defaultCompare(){return(e,t)=>e<t?-1:e>t?1:0}wrap(){return{getRoot:()=>this.root,setRoot:e=>{this.root=e},getSize:()=>this.size,getModificationCount:()=>this.modificationCount,getSplayCount:()=>this.splayCount,setSplayCount:e=>{this.splayCount=e},splay:e=>this.splay(e),has:e=>this.has(e)}}},st=class e extends at{constructor(e,t){super(),i(this,"root",null),i(this,"compare"),i(this,"validKey"),i(this,r,"[object Set]"),this.compare=e??this.defaultCompare(),this.validKey=t??(e=>null!=e&&null!=e)}delete(e){return!!this.validKey(e)&&null!=this._delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){const t=this[Symbol.iterator]();let r;for(;r=t.next(),!r.done;)e(r.value,r.value,this)}add(e){const t=this.splay(e);return 0!=t&&this.addNewRoot(new it(e),t),this}addAndReturn(e){const t=this.splay(e);return 0!=t&&this.addNewRoot(new it(e),t),this.root.key}addAll(e){for(const t of e)this.add(t)}isEmpty(){return null==this.root}isNotEmpty(){return null!=this.root}single(){if(0==this.size)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}first(){if(0==this.size)throw"Bad state: No element";return this._first().key}last(){if(0==this.size)throw"Bad state: No element";return this._last().key}lastBefore(e){if(null==e)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(e)<0)return this.root.key;let t=this.root.left;if(null==t)return null;let r=t.right;for(;null!=r;)t=r,r=t.right;return t.key}firstAfter(e){if(null==e)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(e)>0)return this.root.key;let t=this.root.right;if(null==t)return null;let r=t.left;for(;null!=r;)t=r,r=t.left;return t.key}retainAll(t){const r=new e(this.compare,this.validKey),o=this.modificationCount;for(const e of t){if(o!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(e)&&0==this.splay(e)&&r.add(this.root.key)}r.size!=this.size&&(this.root=r.root,this.size=r.size,this.modificationCount++)}lookup(e){if(!this.validKey(e))return null;return 0!=this.splay(e)?null:this.root.key}intersection(t){const r=new e(this.compare,this.validKey);for(const e of this)t.has(e)&&r.add(e);return r}difference(t){const r=new e(this.compare,this.validKey);for(const e of this)t.has(e)||r.add(e);return r}union(e){const t=this.clone();return t.addAll(e),t}clone(){const t=new e(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}copyNode(e){if(null==e)return null;const t=new it(e.key);return function e(t,r){let o,n;do{if(o=t.left,n=t.right,null!=o){const t=new it(o.key);r.left=t,e(o,t)}if(null!=n){const e=new it(n.key);r.right=e,t=n,r=e}}while(null!=n)}(e,t),t}toSet(){return this.clone()}entries(){return new ut(this.wrap())}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}[(o=Symbol.iterator,r=Symbol.toStringTag,o)](){return new ct(this.wrap())}},lt=class{constructor(e){i(this,"tree"),i(this,"path",new Array),i(this,"modificationCount",null),i(this,"splayCount"),this.tree=e,this.splayCount=e.getSplayCount()}[Symbol.iterator](){return this}next(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}current(){if(!this.path.length)return null;const e=this.path[this.path.length-1];return this.getValue(e)}rebuildPath(e){this.path.splice(0,this.path.length),this.tree.splay(e),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}findLeftMostDescendent(e){for(;null!=e;)this.path.push(e),e=e.left}moveNext(){if(this.modificationCount!=this.tree.getModificationCount()){if(null==this.modificationCount){this.modificationCount=this.tree.getModificationCount();let e=this.tree.getRoot();for(;null!=e;)this.path.push(e),e=e.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);let e=this.path[this.path.length-1],t=e.right;if(null!=t){for(;null!=t;)this.path.push(t),t=t.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===e;)e=this.path.pop();return this.path.length>0}},ct=class extends lt{getValue(e){return e.key}},ut=class extends lt{getValue(e){return[e.key,e.key]}},ht=e=>()=>e,gt=e=>{const t=e?(t,r)=>r.minus(t).abs().isLessThanOrEqualTo(e):ht(!1);return(e,r)=>t(e,r)?0:e.comparedTo(r)};function dt(e){const t=e?(t,r,o,n,i)=>t.exponentiatedBy(2).isLessThanOrEqualTo(n.minus(r).exponentiatedBy(2).plus(i.minus(o).exponentiatedBy(2)).times(e)):ht(!1);return(e,r,o)=>{const n=e.x,i=e.y,a=o.x,s=o.y,l=i.minus(s).times(r.x.minus(a)).minus(n.minus(a).times(r.y.minus(s)));return t(l,n,i,a,s)?0:l.comparedTo(0)}}var pt=e=>e,ft=e=>{if(e){const t=new st(gt(e)),r=new st(gt(e)),o=(e,t)=>t.addAndReturn(e),n=e=>({x:o(e.x,t),y:o(e.y,r)});return n({x:new ot(0),y:new ot(0)}),n}return pt},yt=e=>({set:e=>{mt=yt(e)},reset:()=>yt(e),compare:gt(e),snap:ft(e),orient:dt(e)}),mt=yt(),vt=(e,t)=>e.ll.x.isLessThanOrEqualTo(t.x)&&t.x.isLessThanOrEqualTo(e.ur.x)&&e.ll.y.isLessThanOrEqualTo(t.y)&&t.y.isLessThanOrEqualTo(e.ur.y),Mt=(e,t)=>{if(t.ur.x.isLessThan(e.ll.x)||e.ur.x.isLessThan(t.ll.x)||t.ur.y.isLessThan(e.ll.y)||e.ur.y.isLessThan(t.ll.y))return null;const r=e.ll.x.isLessThan(t.ll.x)?t.ll.x:e.ll.x,o=e.ur.x.isLessThan(t.ur.x)?e.ur.x:t.ur.x;return{ll:{x:r,y:e.ll.y.isLessThan(t.ll.y)?t.ll.y:e.ll.y},ur:{x:o,y:e.ur.y.isLessThan(t.ur.y)?e.ur.y:t.ur.y}}},bt=(e,t)=>e.x.times(t.y).minus(e.y.times(t.x)),wt=(e,t)=>e.x.times(t.x).plus(e.y.times(t.y)),Pt=e=>wt(e,e).sqrt(),Lt=(e,t,r)=>{const o={x:t.x.minus(e.x),y:t.y.minus(e.y)},n={x:r.x.minus(e.x),y:r.y.minus(e.y)};return bt(n,o).div(Pt(n)).div(Pt(o))},kt=(e,t,r)=>{const o={x:t.x.minus(e.x),y:t.y.minus(e.y)},n={x:r.x.minus(e.x),y:r.y.minus(e.y)};return wt(n,o).div(Pt(n)).div(Pt(o))},xt=(e,t,r)=>t.y.isZero()?null:{x:e.x.plus(t.x.div(t.y).times(r.minus(e.y))),y:r},Et=(e,t,r)=>t.x.isZero()?null:{x:r,y:e.y.plus(t.y.div(t.x).times(r.minus(e.x)))},St=class e{constructor(e,t){i(this,"point"),i(this,"isLeft"),i(this,"segment"),i(this,"otherSE"),i(this,"consumedBy"),void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=t}static compare(t,r){const o=e.comparePoints(t.point,r.point);return 0!==o?o:(t.point!==r.point&&t.link(r),t.isLeft!==r.isLeft?t.isLeft?1:-1:_t.compare(t.segment,r.segment))}static comparePoints(e,t){return e.x.isLessThan(t.x)?-1:e.x.isGreaterThan(t.x)?1:e.y.isLessThan(t.y)?-1:e.y.isGreaterThan(t.y)?1:0}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const t=e.point.events;for(let r=0,o=t.length;r<o;r++){const e=t[r];this.point.events.push(e),e.point=this.point}this.checkForConsuming()}checkForConsuming(){const e=this.point.events.length;for(let t=0;t<e;t++){const r=this.point.events[t];if(void 0===r.segment.consumedBy)for(let o=t+1;o<e;o++){const e=this.point.events[o];void 0===e.consumedBy&&(r.otherSE.point.events===e.otherSE.point.events&&r.segment.consume(e.segment))}}}getAvailableLinkedEvents(){const e=[];for(let t=0,r=this.point.events.length;t<r;t++){const r=this.point.events[t];r!==this&&!r.segment.ringOut&&r.segment.isInResult()&&e.push(r)}return e}getLeftmostComparator(e){const t=new Map,r=r=>{const o=r.otherSE;t.set(r,{sine:Lt(this.point,e.point,o.point),cosine:kt(this.point,e.point,o.point)})};return(e,o)=>{t.has(e)||r(e),t.has(o)||r(o);const{sine:n,cosine:i}=t.get(e),{sine:a,cosine:s}=t.get(o);return n.isGreaterThanOrEqualTo(0)&&a.isGreaterThanOrEqualTo(0)?i.isLessThan(s)?1:i.isGreaterThan(s)?-1:0:n.isLessThan(0)&&a.isLessThan(0)?i.isLessThan(s)?-1:i.isGreaterThan(s)?1:0:a.isLessThan(n)?-1:a.isGreaterThan(n)?1:0}}},Dt=class e{constructor(e){i(this,"events"),i(this,"poly"),i(this,"_isExteriorRing"),i(this,"_enclosingRing"),this.events=e;for(let t=0,r=e.length;t<r;t++)e[t].segment.ringOut=this;this.poly=null}static factory(t){const r=[];for(let o=0,n=t.length;o<n;o++){const n=t[o];if(!n.isInResult()||n.ringOut)continue;let i=null,a=n.leftSE,s=n.rightSE;const l=[a],c=a.point,u=[];for(;i=a,a=s,l.push(a),a.point!==c;)for(;;){const t=a.getAvailableLinkedEvents();if(0===t.length){const e=l[0].point,t=l[l.length-1].point;throw new Error(`Unable to complete output ring starting at [${e.x}, ${e.y}]. Last matching segment found ends at [${t.x}, ${t.y}].`)}if(1===t.length){s=t[0].otherSE;break}let o=null;for(let e=0,r=u.length;e<r;e++)if(u[e].point===a.point){o=e;break}if(null!==o){const t=u.splice(o)[0],n=l.splice(t.index);n.unshift(n[0].otherSE),r.push(new e(n.reverse()));continue}u.push({index:l.length,point:a.point});const n=a.getLeftmostComparator(i);s=t.sort(n)[0].otherSE;break}r.push(new e(l))}return r}getGeom(){let e=this.events[0].point;const t=[e];for(let l=1,c=this.events.length-1;l<c;l++){const r=this.events[l].point,o=this.events[l+1].point;0!==mt.orient(r,e,o)&&(t.push(r),e=r)}if(1===t.length)return null;const r=t[0],o=t[1];0===mt.orient(r,e,o)&&t.shift(),t.push(t[0]);const n=this.isExteriorRing()?1:-1,i=this.isExteriorRing()?0:t.length-1,a=this.isExteriorRing()?t.length:-1,s=[];for(let l=i;l!=a;l+=n)s.push([t[l].x.toNumber(),t[l].y.toNumber()]);return s}isExteriorRing(){if(void 0===this._isExteriorRing){const e=this.enclosingRing();this._isExteriorRing=!e||!e.isExteriorRing()}return this._isExteriorRing}enclosingRing(){return void 0===this._enclosingRing&&(this._enclosingRing=this._calcEnclosingRing()),this._enclosingRing}_calcEnclosingRing(){var e,t;let r=this.events[0];for(let i=1,a=this.events.length;i<a;i++){const e=this.events[i];St.compare(r,e)>0&&(r=e)}let o=r.segment.prevInResult(),n=o?o.prevInResult():null;for(;;){if(!o)return null;if(!n)return o.ringOut;if(n.ringOut!==o.ringOut)return(null==(e=n.ringOut)?void 0:e.enclosingRing())!==o.ringOut?o.ringOut:null==(t=o.ringOut)?void 0:t.enclosingRing();o=n.prevInResult(),n=o?o.prevInResult():null}}},Ct=class{constructor(e){i(this,"exteriorRing"),i(this,"interiorRings"),this.exteriorRing=e,e.poly=this,this.interiorRings=[]}addInterior(e){this.interiorRings.push(e),e.poly=this}getGeom(){const e=this.exteriorRing.getGeom();if(null===e)return null;const t=[e];for(let r=0,o=this.interiorRings.length;r<o;r++){const e=this.interiorRings[r].getGeom();null!==e&&t.push(e)}return t}},It=class{constructor(e){i(this,"rings"),i(this,"polys"),this.rings=e,this.polys=this._composePolys(e)}getGeom(){const e=[];for(let t=0,r=this.polys.length;t<r;t++){const r=this.polys[t].getGeom();null!==r&&e.push(r)}return e}_composePolys(e){var t;const r=[];for(let o=0,n=e.length;o<n;o++){const n=e[o];if(!n.poly)if(n.isExteriorRing())r.push(new Ct(n));else{const e=n.enclosingRing();(null==e?void 0:e.poly)||r.push(new Ct(e)),null==(t=null==e?void 0:e.poly)||t.addInterior(n)}}return r}},At=class{constructor(e,t=_t.compare){i(this,"queue"),i(this,"tree"),i(this,"segments"),this.queue=e,this.tree=new st(t),this.segments=[]}process(e){const t=e.segment,r=[];if(e.consumedBy)return e.isLeft?this.queue.delete(e.otherSE):this.tree.delete(t),r;e.isLeft&&this.tree.add(t);let o=t,n=t;do{o=this.tree.lastBefore(o)}while(null!=o&&null!=o.consumedBy);do{n=this.tree.firstAfter(n)}while(null!=n&&null!=n.consumedBy);if(e.isLeft){let i=null;if(o){const e=o.getIntersection(t);if(null!==e&&(t.isAnEndpoint(e)||(i=e),!o.isAnEndpoint(e))){const t=this._splitSafely(o,e);for(let e=0,o=t.length;e<o;e++)r.push(t[e])}}let a=null;if(n){const e=n.getIntersection(t);if(null!==e&&(t.isAnEndpoint(e)||(a=e),!n.isAnEndpoint(e))){const t=this._splitSafely(n,e);for(let e=0,o=t.length;e<o;e++)r.push(t[e])}}if(null!==i||null!==a){let e=null;if(null===i)e=a;else if(null===a)e=i;else{e=St.comparePoints(i,a)<=0?i:a}this.queue.delete(t.rightSE),r.push(t.rightSE);const o=t.split(e);for(let t=0,n=o.length;t<n;t++)r.push(o[t])}r.length>0?(this.tree.delete(t),r.push(e)):(this.segments.push(t),t.prev=o)}else{if(o&&n){const e=o.getIntersection(n);if(null!==e){if(!o.isAnEndpoint(e)){const t=this._splitSafely(o,e);for(let e=0,o=t.length;e<o;e++)r.push(t[e])}if(!n.isAnEndpoint(e)){const t=this._splitSafely(n,e);for(let e=0,o=t.length;e<o;e++)r.push(t[e])}}}this.tree.delete(t)}return r}_splitSafely(e,t){this.tree.delete(e);const r=e.rightSE;this.queue.delete(r);const o=e.split(t);return o.push(r),void 0===e.consumedBy&&this.tree.add(e),o}},Ft=new class{constructor(){i(this,"type"),i(this,"numMultiPolys")}run(e,t,r){Ft.type=e;const o=[new Bt(t,!0)];for(let l=0,c=r.length;l<c;l++)o.push(new Bt(r[l],!1));if(Ft.numMultiPolys=o.length,"difference"===Ft.type){const e=o[0];let t=1;for(;t<o.length;)null!==Mt(o[t].bbox,e.bbox)?t++:o.splice(t,1)}if("intersection"===Ft.type)for(let l=0,c=o.length;l<c;l++){const e=o[l];for(let t=l+1,r=o.length;t<r;t++)if(null===Mt(e.bbox,o[t].bbox))return[]}const n=new st(St.compare);for(let l=0,c=o.length;l<c;l++){const e=o[l].getSweepEvents();for(let t=0,r=e.length;t<r;t++)n.add(e[t])}const i=new At(n);let a=null;for(0!=n.size&&(a=n.first(),n.delete(a));a;){const e=i.process(a);for(let t=0,r=e.length;t<r;t++){const r=e[t];void 0===r.consumedBy&&n.add(r)}0!=n.size?(a=n.first(),n.delete(a)):a=null}mt.reset();const s=Dt.factory(i.segments);return new It(s).getGeom()}},Ot=Ft,Tt=0,_t=class e{constructor(e,t,r,o){i(this,"id"),i(this,"leftSE"),i(this,"rightSE"),i(this,"rings"),i(this,"windings"),i(this,"ringOut"),i(this,"consumedBy"),i(this,"prev"),i(this,"_prevInResult"),i(this,"_beforeState"),i(this,"_afterState"),i(this,"_isInResult"),this.id=++Tt,this.leftSE=e,e.segment=this,e.otherSE=t,this.rightSE=t,t.segment=this,t.otherSE=e,this.rings=r,this.windings=o}static compare(e,t){const r=e.leftSE.point.x,o=t.leftSE.point.x,n=e.rightSE.point.x,i=t.rightSE.point.x;if(i.isLessThan(r))return 1;if(n.isLessThan(o))return-1;const a=e.leftSE.point.y,s=t.leftSE.point.y,l=e.rightSE.point.y,c=t.rightSE.point.y;if(r.isLessThan(o)){if(s.isLessThan(a)&&s.isLessThan(l))return 1;if(s.isGreaterThan(a)&&s.isGreaterThan(l))return-1;const r=e.comparePoint(t.leftSE.point);if(r<0)return 1;if(r>0)return-1;const o=t.comparePoint(e.rightSE.point);return 0!==o?o:-1}if(r.isGreaterThan(o)){if(a.isLessThan(s)&&a.isLessThan(c))return-1;if(a.isGreaterThan(s)&&a.isGreaterThan(c))return 1;const r=t.comparePoint(e.leftSE.point);if(0!==r)return r;const o=e.comparePoint(t.rightSE.point);return o<0?1:o>0?-1:1}if(a.isLessThan(s))return-1;if(a.isGreaterThan(s))return 1;if(n.isLessThan(i)){const r=t.comparePoint(e.rightSE.point);if(0!==r)return r}if(n.isGreaterThan(i)){const r=e.comparePoint(t.rightSE.point);if(r<0)return 1;if(r>0)return-1}if(!n.eq(i)){const e=l.minus(a),t=n.minus(r),u=c.minus(s),h=i.minus(o);if(e.isGreaterThan(t)&&u.isLessThan(h))return 1;if(e.isLessThan(t)&&u.isGreaterThan(h))return-1}return n.isGreaterThan(i)?1:n.isLessThan(i)||l.isLessThan(c)?-1:l.isGreaterThan(c)?1:e.id<t.id?-1:e.id>t.id?1:0}static fromRing(t,r,o){let n,i,a;const s=St.comparePoints(t,r);if(s<0)n=t,i=r,a=1;else{if(!(s>0))throw new Error(`Tried to create degenerate segment at [${t.x}, ${t.y}]`);n=r,i=t,a=-1}const l=new St(n,!0),c=new St(i,!1);return new e(l,c,[o],[a])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,t=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e.isLessThan(t)?e:t},ur:{x:this.rightSE.point.x,y:e.isGreaterThan(t)?e:t}}}vector(){return{x:this.rightSE.point.x.minus(this.leftSE.point.x),y:this.rightSE.point.y.minus(this.leftSE.point.y)}}isAnEndpoint(e){return e.x.eq(this.leftSE.point.x)&&e.y.eq(this.leftSE.point.y)||e.x.eq(this.rightSE.point.x)&&e.y.eq(this.rightSE.point.y)}comparePoint(e){return mt.orient(this.leftSE.point,e,this.rightSE.point)}getIntersection(e){const t=this.bbox(),r=e.bbox(),o=Mt(t,r);if(null===o)return null;const n=this.leftSE.point,i=this.rightSE.point,a=e.leftSE.point,s=e.rightSE.point,l=vt(t,a)&&0===this.comparePoint(a),c=vt(r,n)&&0===e.comparePoint(n),u=vt(t,s)&&0===this.comparePoint(s),h=vt(r,i)&&0===e.comparePoint(i);if(c&&l)return h&&!u?i:!h&&u?s:null;if(c)return u&&n.x.eq(s.x)&&n.y.eq(s.y)?null:n;if(l)return h&&i.x.eq(a.x)&&i.y.eq(a.y)?null:a;if(h&&u)return null;if(h)return i;if(u)return s;const g=((e,t,r,o)=>{if(t.x.isZero())return Et(r,o,e.x);if(o.x.isZero())return Et(e,t,r.x);if(t.y.isZero())return xt(r,o,e.y);if(o.y.isZero())return xt(e,t,r.y);const n=bt(t,o);if(n.isZero())return null;const i={x:r.x.minus(e.x),y:r.y.minus(e.y)},a=bt(i,t).div(n),s=bt(i,o).div(n),l=e.x.plus(s.times(t.x)),c=r.x.plus(a.times(o.x)),u=e.y.plus(s.times(t.y)),h=r.y.plus(a.times(o.y));return{x:l.plus(c).div(2),y:u.plus(h).div(2)}})(n,this.vector(),a,e.vector());return null===g?null:vt(o,g)?mt.snap(g):null}split(t){const r=[],o=void 0!==t.events,n=new St(t,!0),i=new St(t,!1),a=this.rightSE;this.replaceRightSE(i),r.push(i),r.push(n);const s=new e(n,a,this.rings.slice(),this.windings.slice());return St.comparePoints(s.leftSE.point,s.rightSE.point)>0&&s.swapEvents(),St.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),o&&(n.checkForConsuming(),i.checkForConsuming()),r}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let t=0,r=this.windings.length;t<r;t++)this.windings[t]*=-1}consume(t){let r=this,o=t;for(;r.consumedBy;)r=r.consumedBy;for(;o.consumedBy;)o=o.consumedBy;const n=e.compare(r,o);if(0!==n){if(n>0){const e=r;r=o,o=e}if(r.prev===o){const e=r;r=o,o=e}for(let e=0,t=o.rings.length;e<t;e++){const t=o.rings[e],n=o.windings[e],i=r.rings.indexOf(t);-1===i?(r.rings.push(t),r.windings.push(n)):r.windings[i]+=n}o.rings=null,o.windings=null,o.consumedBy=r,o.leftSE.consumedBy=r.leftSE,o.rightSE.consumedBy=r.rightSE}}prevInResult(){return void 0!==this._prevInResult||(this.prev?this.prev.isInResult()?this._prevInResult=this.prev:this._prevInResult=this.prev.prevInResult():this._prevInResult=null),this._prevInResult}beforeState(){if(void 0!==this._beforeState)return this._beforeState;if(this.prev){const e=this.prev.consumedBy||this.prev;this._beforeState=e.afterState()}else this._beforeState={rings:[],windings:[],multiPolys:[]};return this._beforeState}afterState(){if(void 0!==this._afterState)return this._afterState;const e=this.beforeState();this._afterState={rings:e.rings.slice(0),windings:e.windings.slice(0),multiPolys:[]};const t=this._afterState.rings,r=this._afterState.windings,o=this._afterState.multiPolys;for(let a=0,s=this.rings.length;a<s;a++){const e=this.rings[a],o=this.windings[a],n=t.indexOf(e);-1===n?(t.push(e),r.push(o)):r[n]+=o}const n=[],i=[];for(let a=0,s=t.length;a<s;a++){if(0===r[a])continue;const e=t[a],o=e.poly;if(-1===i.indexOf(o))if(e.isExterior)n.push(o);else{-1===i.indexOf(o)&&i.push(o);const t=n.indexOf(e.poly);-1!==t&&n.splice(t,1)}}for(let a=0,s=n.length;a<s;a++){const e=n[a].multiPoly;-1===o.indexOf(e)&&o.push(e)}return this._afterState}isInResult(){if(this.consumedBy)return!1;if(void 0!==this._isInResult)return this._isInResult;const e=this.beforeState().multiPolys,t=this.afterState().multiPolys;switch(Ot.type){case"union":{const r=0===e.length,o=0===t.length;this._isInResult=r!==o;break}case"intersection":{let r,o;e.length<t.length?(r=e.length,o=t.length):(r=t.length,o=e.length),this._isInResult=o===Ot.numMultiPolys&&r<o;break}case"xor":{const r=Math.abs(e.length-t.length);this._isInResult=r%2==1;break}case"difference":{const r=e=>1===e.length&&e[0].isSubject;this._isInResult=r(e)!==r(t);break}}return this._isInResult}},Gt=class{constructor(e,t,r){if(i(this,"poly"),i(this,"isExterior"),i(this,"segments"),i(this,"bbox"),!Array.isArray(e)||0===e.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=t,this.isExterior=r,this.segments=[],"number"!=typeof e[0][0]||"number"!=typeof e[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const o=mt.snap({x:new ot(e[0][0]),y:new ot(e[0][1])});this.bbox={ll:{x:o.x,y:o.y},ur:{x:o.x,y:o.y}};let n=o;for(let i=1,a=e.length;i<a;i++){if("number"!=typeof e[i][0]||"number"!=typeof e[i][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const t=mt.snap({x:new ot(e[i][0]),y:new ot(e[i][1])});t.x.eq(n.x)&&t.y.eq(n.y)||(this.segments.push(_t.fromRing(n,t,this)),t.x.isLessThan(this.bbox.ll.x)&&(this.bbox.ll.x=t.x),t.y.isLessThan(this.bbox.ll.y)&&(this.bbox.ll.y=t.y),t.x.isGreaterThan(this.bbox.ur.x)&&(this.bbox.ur.x=t.x),t.y.isGreaterThan(this.bbox.ur.y)&&(this.bbox.ur.y=t.y),n=t)}o.x.eq(n.x)&&o.y.eq(n.y)||this.segments.push(_t.fromRing(n,o,this))}getSweepEvents(){const e=[];for(let t=0,r=this.segments.length;t<r;t++){const r=this.segments[t];e.push(r.leftSE),e.push(r.rightSE)}return e}},Ht=class{constructor(e,t){if(i(this,"multiPoly"),i(this,"exteriorRing"),i(this,"interiorRings"),i(this,"bbox"),!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");this.exteriorRing=new Gt(e[0],this,!0),this.bbox={ll:{x:this.exteriorRing.bbox.ll.x,y:this.exteriorRing.bbox.ll.y},ur:{x:this.exteriorRing.bbox.ur.x,y:this.exteriorRing.bbox.ur.y}},this.interiorRings=[];for(let r=1,o=e.length;r<o;r++){const t=new Gt(e[r],this,!1);t.bbox.ll.x.isLessThan(this.bbox.ll.x)&&(this.bbox.ll.x=t.bbox.ll.x),t.bbox.ll.y.isLessThan(this.bbox.ll.y)&&(this.bbox.ll.y=t.bbox.ll.y),t.bbox.ur.x.isGreaterThan(this.bbox.ur.x)&&(this.bbox.ur.x=t.bbox.ur.x),t.bbox.ur.y.isGreaterThan(this.bbox.ur.y)&&(this.bbox.ur.y=t.bbox.ur.y),this.interiorRings.push(t)}this.multiPoly=t}getSweepEvents(){const e=this.exteriorRing.getSweepEvents();for(let t=0,r=this.interiorRings.length;t<r;t++){const r=this.interiorRings[t].getSweepEvents();for(let t=0,o=r.length;t<o;t++)e.push(r[t])}return e}},Bt=class{constructor(e,t){if(i(this,"isSubject"),i(this,"polys"),i(this,"bbox"),!Array.isArray(e))throw new Error("Input geometry is not a valid Polygon or MultiPolygon");try{"number"==typeof e[0][0][0]&&(e=[e])}catch(r){}this.polys=[],this.bbox={ll:{x:new ot(Number.POSITIVE_INFINITY),y:new ot(Number.POSITIVE_INFINITY)},ur:{x:new ot(Number.NEGATIVE_INFINITY),y:new ot(Number.NEGATIVE_INFINITY)}};for(let o=0,n=e.length;o<n;o++){const t=new Ht(e[o],this);t.bbox.ll.x.isLessThan(this.bbox.ll.x)&&(this.bbox.ll.x=t.bbox.ll.x),t.bbox.ll.y.isLessThan(this.bbox.ll.y)&&(this.bbox.ll.y=t.bbox.ll.y),t.bbox.ur.x.isGreaterThan(this.bbox.ur.x)&&(this.bbox.ur.x=t.bbox.ur.x),t.bbox.ur.y.isGreaterThan(this.bbox.ur.y)&&(this.bbox.ur.y=t.bbox.ur.y),this.polys.push(t)}this.isSubject=t}getSweepEvents(){const e=[];for(let t=0,r=this.polys.length;t<r;t++){const r=this.polys[t].getSweepEvents();for(let t=0,o=r.length;t<o;t++)e.push(r[t])}return e}};mt.set;var zt=function(e,t={}){const r=[];if(function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,e=>{r.push(e.coordinates)}),r.length<2)throw new Error("Must have at least 2 geometries");const o=((e,...t)=>Ot.run("union",e,t))(r[0],...r.slice(1));return 0===o.length?null:1===o.length?O(o[0],t.properties):G(o,t.properties)};function Ut(e,t,r={}){const o={type:"Feature"};return(0===r.id||r.id)&&(o.id=r.id),r.bbox&&(o.bbox=r.bbox),o.properties=t||{},o.geometry=e,o}function Nt(e,t){if("Feature"===e.type)t(e,0);else if("FeatureCollection"===e.type)for(var r=0;r<e.features.length&&!1!==t(e.features[r],r);r++);}var Rt=function(e,t={}){const r=[];if(function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,e=>{r.push(e.coordinates)}),r.length<2)throw new Error("Must specify at least 2 geometries");const o=((e,...t)=>Ot.run("intersection",e,t))(r[0],...r.slice(1));return 0===o.length?null:1===o.length?function(e,t,r={}){for(const o of e){if(o.length<4)throw new Error("Each LinearRing of a Polygon must have 4 or more Positions.");if(o[o.length-1].length!==o[0].length)throw new Error("First and last Position are not equivalent.");for(let e=0;e<o[o.length-1].length;e++)if(o[o.length-1][e]!==o[0][e])throw new Error("First and last Position are not equivalent.")}return Ut({type:"Polygon",coordinates:e},t,r)}(o[0],t.properties):function(e,t,r={}){return Ut({type:"MultiPolygon",coordinates:e},t,r)}(o,t.properties)};var Xt=function(e){const t=[];if(function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,e=>{t.push(e.coordinates)}),t.length<2)throw new Error("Must have at least two features");const r=e.features[0].properties||{},o=((e,...t)=>Ot.run("difference",e,t))(t[0],...t.slice(1));return 0===o.length?null:1===o.length?O(o[0],r):G(o,r)};function Yt(e,t,r){if(null!==e)for(var o,n,i,a,s,l,c,u,h=0,g=0,d=e.type,p="FeatureCollection"===d,f="Feature"===d,y=p?e.features.length:1,m=0;m<y;m++){s=(u=!!(c=p?e.features[m].geometry:f?e.geometry:e)&&"GeometryCollection"===c.type)?c.geometries.length:1;for(var v=0;v<s;v++){var M=0,b=0;if(null!==(a=u?c.geometries[v]:c)){l=a.coordinates;var w=a.type;switch(h=0,w){case null:break;case"Point":if(!1===t(l,g,m,M,b))return!1;g++,M++;break;case"LineString":case"MultiPoint":for(o=0;o<l.length;o++){if(!1===t(l[o],g,m,M,b))return!1;g++,"MultiPoint"===w&&M++}"LineString"===w&&M++;break;case"Polygon":case"MultiLineString":for(o=0;o<l.length;o++){for(n=0;n<l[o].length-h;n++){if(!1===t(l[o][n],g,m,M,b))return!1;g++}"MultiLineString"===w&&M++,"Polygon"===w&&b++}"Polygon"===w&&M++;break;case"MultiPolygon":for(o=0;o<l.length;o++){for(b=0,n=0;n<l[o].length;n++){for(i=0;i<l[o][n].length-h;i++){if(!1===t(l[o][n][i],g,m,M,b))return!1;g++}b++}M++}break;case"GeometryCollection":for(o=0;o<a.geometries.length;o++)if(!1===Yt(a.geometries[o],t))return!1;break;default:throw new Error("Unknown Geometry Type")}}}}}var Vt=function(e){const t=[];return"FeatureCollection"===e.type?function(e,t){if("Feature"===e.type)t(e,0);else if("FeatureCollection"===e.type)for(var r=0;r<e.features.length&&!1!==t(e.features[r],r);r++);}(e,function(e){Yt(e,function(r){t.push(F(r,e.properties))})}):"Feature"===e.type?Yt(e,function(r){t.push(F(r,e.properties))}):Yt(e,function(e){t.push(F(e))}),_(t)};function qt(e,t,r={}){const o=Me(e),n=be(t);for(let i=0;i<n.length-1;i++){let e=!1;if(r.ignoreEndVertices&&(0===i&&(e="start"),i===n.length-2&&(e="end"),0===i&&i+1===n.length-1&&(e="both")),jt(n[i],n[i+1],o,e,void 0===r.epsilon?null:r.epsilon))return!0}return!1}function jt(e,t,r,o,n){const i=r[0],a=r[1],s=e[0],l=e[1],c=t[0],u=t[1],h=c-s,g=u-l,d=(r[0]-s)*g-(r[1]-l)*h;if(null!==n){if(Math.abs(d)>n)return!1}else if(0!==d)return!1;return Math.abs(h)===Math.abs(g)&&0===Math.abs(h)?!o&&(r[0]===e[0]&&r[1]===e[1]):o?"start"===o?Math.abs(h)>=Math.abs(g)?h>0?s<i&&i<=c:c<=i&&i<s:g>0?l<a&&a<=u:u<=a&&a<l:"end"===o?Math.abs(h)>=Math.abs(g)?h>0?s<=i&&i<c:c<i&&i<=s:g>0?l<=a&&a<u:u<a&&a<=l:"both"===o&&(Math.abs(h)>=Math.abs(g)?h>0?s<i&&i<c:c<i&&i<s:g>0?l<a&&a<u:u<a&&a<l):Math.abs(h)>=Math.abs(g)?h>0?s<=i&&i<=c:c<=i&&i<=s:g>0?l<=a&&a<=u:u<=a&&a<=l}function Wt(e,t={}){var r="object"==typeof t?t.mutate:t;if(!e)throw new Error("geojson is required");var o=Pe(e),n=[];switch(o){case"LineString":n=$t(e,o);break;case"MultiLineString":case"Polygon":be(e).forEach(function(e){n.push($t(e,o))});break;case"MultiPolygon":be(e).forEach(function(e){var t=[];e.forEach(function(e){t.push($t(e,o))}),n.push(t)});break;case"Point":return e;case"MultiPoint":var i={};be(e).forEach(function(e){var t=e.join("-");Object.prototype.hasOwnProperty.call(i,t)||(n.push(e),i[t]=!0)});break;default:throw new Error(o+" geometry not supported")}return e.coordinates?!0===r?(e.coordinates=n,e):{type:o,coordinates:n}:!0===r?(e.geometry.coordinates=n,e):A({type:o,coordinates:n},e.properties,{bbox:e.bbox,id:e.id})}function $t(e,t){const r=be(e);if(2===r.length&&!Kt(r[0],r[1]))return r;const o=[];let n=0,i=1,a=2;for(o.push(r[n]);a<r.length;)qt(r[i],T([r[n],r[a]]))?i=a:(o.push(r[i]),n=i,i++,a=i),a++;if(o.push(r[i]),"Polygon"===t||"MultiPolygon"===t){if(qt(o[0],T([o[1],o[o.length-2]]))&&(o.shift(),o.pop(),o.push(o[0])),o.length<4)throw new Error("invalid polygon, fewer than 4 points");if(!Kt(o[0],o[o.length-1]))throw new Error("invalid polygon, first and last points not equal")}return o}function Kt(e,t){return e[0]===t[0]&&e[1]===t[1]}function Jt(e){if(!e)throw new Error("geojson is required");switch(e.type){case"Feature":return Zt(e);case"FeatureCollection":return function(e){const t={type:"FeatureCollection"};return Object.keys(e).forEach(r=>{switch(r){case"type":case"features":return;default:t[r]=e[r]}}),t.features=e.features.map(e=>Zt(e)),t}(e);case"Point":case"LineString":case"Polygon":case"MultiPoint":case"MultiLineString":case"MultiPolygon":case"GeometryCollection":return er(e);default:throw new Error("unknown GeoJSON type")}}function Zt(e){const t={type:"Feature"};return Object.keys(e).forEach(r=>{switch(r){case"type":case"properties":case"geometry":return;default:t[r]=e[r]}}),t.properties=Qt(e.properties),null==e.geometry?t.geometry=null:t.geometry=er(e.geometry),t}function Qt(e){const t={};return e?(Object.keys(e).forEach(r=>{const o=e[r];"object"==typeof o?null===o?t[r]=null:Array.isArray(o)?t[r]=o.map(e=>e):t[r]=Qt(o):t[r]=o}),t):t}function er(e){const t={type:e.type};return e.bbox&&(t.bbox=e.bbox),"GeometryCollection"===e.type?(t.geometries=e.geometries.map(e=>er(e)),t):(t.coordinates=tr(e.coordinates),t)}function tr(e){const t=e;return"object"!=typeof t[0]?t.slice():t.map(e=>tr(e))}function rr(e,t){var r=e[0]-t[0],o=e[1]-t[1];return r*r+o*o}function or(e,t,r){var o=t[0],n=t[1],i=r[0]-o,a=r[1]-n;if(0!==i||0!==a){var s=((e[0]-o)*i+(e[1]-n)*a)/(i*i+a*a);s>1?(o=r[0],n=r[1]):s>0&&(o+=i*s,n+=a*s)}return(i=e[0]-o)*i+(a=e[1]-n)*a}function nr(e,t,r,o,n){for(var i,a=o,s=t+1;s<r;s++){var l=or(e[s],e[t],e[r]);l>a&&(i=s,a=l)}a>o&&(i-t>1&&nr(e,t,i,o,n),n.push(e[i]),r-i>1&&nr(e,i,r,o,n))}function ir(e,t){var r=e.length-1,o=[e[0]];return nr(e,0,r,t,o),o.push(e[r]),o}function ar(e,t,r){if(e.length<=2)return e;var o=void 0!==t?t*t:1;return e=r?e:function(e,t){for(var r,o=e[0],n=[o],i=1,a=e.length;i<a;i++)rr(r=e[i],o)>t&&(n.push(r),o=r);return o!==r&&n.push(r),n}(e,o),e=ir(e,o)}function sr(e,t,r){return e.map(function(e){if(e.length<4)throw new Error("invalid polygon");let o=t,n=ar(e,o,r);for(;!lr(n)&&o>=Number.EPSILON;)o-=.01*o,n=ar(e,o,r);return lr(n)?(n[n.length-1][0]===n[0][0]&&n[n.length-1][1]===n[0][1]||n.push(n[0]),n):e})}function lr(e){return!(e.length<3)&&!(3===e.length&&e[2][0]===e[0][0]&&e[2][1]===e[0][1])}var cr=function(e,t={}){var r,o,n;if(!U(t=null!=t?t:{}))throw new Error("options is invalid");const i=null!=(r=t.tolerance)?r:1,a=null!=(o=t.highQuality)&&o,s=null!=(n=t.mutate)&&n;if(!e)throw new Error("geojson is required");if(i&&i<0)throw new Error("invalid tolerance");return!0!==s&&(e=Jt(e)),function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,function(e){!function(e,t,r){const o=e.type;if("Point"===o||"MultiPoint"===o)return e;if(Wt(e,{mutate:!0}),"GeometryCollection"!==o)switch(o){case"LineString":e.coordinates=ar(e.coordinates,t,r);break;case"MultiLineString":e.coordinates=e.coordinates.map(e=>ar(e,t,r));break;case"Polygon":e.coordinates=sr(e.coordinates,t,r);break;case"MultiPolygon":e.coordinates=e.coordinates.map(e=>sr(e,t,r))}}(e,i,a)}),e};function ur(e,t,r,o,n,i,a,s){let l,c,u,h,g;const d={x:null,y:null,onLine1:!1,onLine2:!1};return l=(s-i)*(r-e)-(a-n)*(o-t),0===l?null!==d.x&&null!==d.y&&d:(c=t-i,u=e-n,h=(a-n)*c-(s-i)*u,g=(r-e)*c-(o-t)*u,c=h/l,u=g/l,d.x=e+c*(r-e),d.y=t+c*(o-t),c>=0&&c<=1&&(d.onLine1=!0),u>=0&&u<=1&&(d.onLine2=!0),!(!d.onLine1||!d.onLine2)&&[d.x,d.y])}var hr=function(e){let t,r;const o={type:"FeatureCollection",features:[]};if(r="Feature"===e.type?e.geometry:e,"LineString"===r.type)t=[r.coordinates];else if("MultiLineString"===r.type)t=r.coordinates;else if("MultiPolygon"===r.type)t=[].concat(...r.coordinates);else{if("Polygon"!==r.type)throw new Error("Input must be a LineString, MultiLineString, Polygon, or MultiPolygon Feature or Geometry");t=r.coordinates}return t.forEach(e=>{t.forEach(t=>{for(let r=0;r<e.length-1;r++)for(let n=r;n<t.length-1;n++){if(e===t){if(1===Math.abs(r-n))continue;if(0===r&&n===e.length-2&&e[r][0]===e[e.length-1][0]&&e[r][1]===e[e.length-1][1])continue}const i=ur(e[r][0],e[r][1],e[r+1][0],e[r+1][1],t[n][0],t[n][1],t[n+1][0],t[n+1][1]);i&&o.features.push(F([i[0],i[1]]))}})}),o};function gr(e,t){!function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,function(e,r,o,n,i){var a,s=null===e?null:e.type;switch(s){case null:case"Point":case"LineString":case"Polygon":return!1!==t(A(e,o,{bbox:n,id:i}),r,0)&&void 0}switch(s){case"MultiPoint":a="Point";break;case"MultiLineString":a="LineString";break;case"MultiPolygon":a="Polygon"}for(var l=0;l<e.coordinates.length;l++){var c=e.coordinates[l];if(!1===t(A({type:a,coordinates:c},o),r,l))return!1}})}function dr(e,t,r,o,n){pr(e,t,r||0,o||e.length-1,n||yr)}function pr(e,t,r,o,n){for(;o>r;){if(o-r>600){var i=o-r+1,a=t-r+1,s=Math.log(i),l=.5*Math.exp(2*s/3),c=.5*Math.sqrt(s*l*(i-l)/i)*(a-i/2<0?-1:1);pr(e,t,Math.max(r,Math.floor(t-a*l/i+c)),Math.min(o,Math.floor(t+(i-a)*l/i+c)),n)}var u=e[t],h=r,g=o;for(fr(e,r,t),n(e[o],u)>0&&fr(e,r,o);h<g;){for(fr(e,h,g),h++,g--;n(e[h],u)<0;)h++;for(;n(e[g],u)>0;)g--}0===n(e[r],u)?fr(e,r,g):fr(e,++g,o),g<=t&&(r=g+1),t<=g&&(o=g-1)}}function fr(e,t,r){var o=e[t];e[t]=e[r],e[r]=o}function yr(e,t){return e<t?-1:e>t?1:0}let mr=class{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data;const r=[];if(!Cr(e,t))return r;const o=this.toBBox,n=[];for(;t;){for(let i=0;i<t.children.length;i++){const a=t.children[i],s=t.leaf?o(a):a;Cr(e,s)&&(t.leaf?r.push(a):Dr(e,s)?this._all(a,r):n.push(a))}t=n.pop()}return r}collides(e){let t=this.data;if(!Cr(e,t))return!1;const r=[];for(;t;){for(let o=0;o<t.children.length;o++){const n=t.children[o],i=t.leaf?this.toBBox(n):n;if(Cr(e,i)){if(t.leaf||Dr(e,i))return!0;r.push(n)}}t=r.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let t=0;t<e.length;t++)this.insert(e[t]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){const e=this.data;this.data=t,t=e}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=Ir([]),this}remove(e,t){if(!e)return this;let r=this.data;const o=this.toBBox(e),n=[],i=[];let a,s,l;for(;r||n.length;){if(r||(r=n.pop(),s=n[n.length-1],a=i.pop(),l=!0),r.leaf){const o=vr(e,r.children,t);if(-1!==o)return r.children.splice(o,1),n.push(r),this._condense(n),this}l||r.leaf||!Dr(r,o)?s?(a++,r=s.children[a],l=!1):r=null:(n.push(r),i.push(a),a=0,s=r,r=r.children[0])}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){const r=[];for(;e;)e.leaf?t.push(...e.children):r.push(...e.children),e=r.pop();return t}_build(e,t,r,o){const n=r-t+1;let i,a=this._maxEntries;if(n<=a)return i=Ir(e.slice(t,r+1)),Mr(i,this.toBBox),i;o||(o=Math.ceil(Math.log(n)/Math.log(a)),a=Math.ceil(n/Math.pow(a,o-1))),i=Ir([]),i.leaf=!1,i.height=o;const s=Math.ceil(n/a),l=s*Math.ceil(Math.sqrt(a));Ar(e,t,r,l,this.compareMinX);for(let c=t;c<=r;c+=l){const t=Math.min(c+l-1,r);Ar(e,c,t,s,this.compareMinY);for(let r=c;r<=t;r+=s){const n=Math.min(r+s-1,t);i.children.push(this._build(e,r,n,o-1))}}return Mr(i,this.toBBox),i}_chooseSubtree(e,t,r,o){for(;o.push(t),!t.leaf&&o.length-1!==r;){let r,o=1/0,n=1/0;for(let i=0;i<t.children.length;i++){const a=t.children[i],s=kr(a),l=Er(e,a)-s;l<n?(n=l,o=s<o?s:o,r=a):l===n&&s<o&&(o=s,r=a)}t=r||t.children[0]}return t}_insert(e,t,r){const o=r?e:this.toBBox(e),n=[],i=this._chooseSubtree(o,this.data,t,n);for(i.children.push(e),wr(i,o);t>=0&&n[t].children.length>this._maxEntries;)this._split(n,t),t--;this._adjustParentBBoxes(o,n,t)}_split(e,t){const r=e[t],o=r.children.length,n=this._minEntries;this._chooseSplitAxis(r,n,o);const i=this._chooseSplitIndex(r,n,o),a=Ir(r.children.splice(i,r.children.length-i));a.height=r.height,a.leaf=r.leaf,Mr(r,this.toBBox),Mr(a,this.toBBox),t?e[t-1].children.push(a):this._splitRoot(r,a)}_splitRoot(e,t){this.data=Ir([e,t]),this.data.height=e.height+1,this.data.leaf=!1,Mr(this.data,this.toBBox)}_chooseSplitIndex(e,t,r){let o,n=1/0,i=1/0;for(let a=t;a<=r-t;a++){const t=br(e,0,a,this.toBBox),s=br(e,a,r,this.toBBox),l=Sr(t,s),c=kr(t)+kr(s);l<n?(n=l,o=a,i=c<i?c:i):l===n&&c<i&&(i=c,o=a)}return o||r-t}_chooseSplitAxis(e,t,r){const o=e.leaf?this.compareMinX:Pr,n=e.leaf?this.compareMinY:Lr;this._allDistMargin(e,t,r,o)<this._allDistMargin(e,t,r,n)&&e.children.sort(o)}_allDistMargin(e,t,r,o){e.children.sort(o);const n=this.toBBox,i=br(e,0,t,n),a=br(e,r-t,r,n);let s=xr(i)+xr(a);for(let l=t;l<r-t;l++){const t=e.children[l];wr(i,e.leaf?n(t):t),s+=xr(i)}for(let l=r-t-1;l>=t;l--){const t=e.children[l];wr(a,e.leaf?n(t):t),s+=xr(a)}return s}_adjustParentBBoxes(e,t,r){for(let o=r;o>=0;o--)wr(t[o],e)}_condense(e){for(let t,r=e.length-1;r>=0;r--)0===e[r].children.length?r>0?(t=e[r-1].children,t.splice(t.indexOf(e[r]),1)):this.clear():Mr(e[r],this.toBBox)}};function vr(e,t,r){if(!r)return t.indexOf(e);for(let o=0;o<t.length;o++)if(r(e,t[o]))return o;return-1}function Mr(e,t){br(e,0,e.children.length,t,e)}function br(e,t,r,o,n){n||(n=Ir(null)),n.minX=1/0,n.minY=1/0,n.maxX=-1/0,n.maxY=-1/0;for(let i=t;i<r;i++){const t=e.children[i];wr(n,e.leaf?o(t):t)}return n}function wr(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function Pr(e,t){return e.minX-t.minX}function Lr(e,t){return e.minY-t.minY}function kr(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function xr(e){return e.maxX-e.minX+(e.maxY-e.minY)}function Er(e,t){return(Math.max(t.maxX,e.maxX)-Math.min(t.minX,e.minX))*(Math.max(t.maxY,e.maxY)-Math.min(t.minY,e.minY))}function Sr(e,t){const r=Math.max(e.minX,t.minX),o=Math.max(e.minY,t.minY),n=Math.min(e.maxX,t.maxX),i=Math.min(e.maxY,t.maxY);return Math.max(0,n-r)*Math.max(0,i-o)}function Dr(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function Cr(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function Ir(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function Ar(e,t,r,o,n){const i=[t,r];for(;i.length;){if((r=i.pop())-(t=i.pop())<=o)continue;const a=t+Math.ceil((r-t)/o/2)*o;dr(e,a,t,r,n),i.push(t,a,a,r)}}const Fr=11102230246251565e-32,Or=134217729,Tr=(3+8*Fr)*Fr;function _r(e,t,r,o,n){let i,a,s,l,c=t[0],u=o[0],h=0,g=0;u>c==u>-c?(i=c,c=t[++h]):(i=u,u=o[++g]);let d=0;if(h<e&&g<r)for(u>c==u>-c?(a=c+i,s=i-(a-c),c=t[++h]):(a=u+i,s=i-(a-u),u=o[++g]),i=a,0!==s&&(n[d++]=s);h<e&&g<r;)u>c==u>-c?(a=i+c,l=a-i,s=i-(a-l)+(c-l),c=t[++h]):(a=i+u,l=a-i,s=i-(a-l)+(u-l),u=o[++g]),i=a,0!==s&&(n[d++]=s);for(;h<e;)a=i+c,l=a-i,s=i-(a-l)+(c-l),c=t[++h],i=a,0!==s&&(n[d++]=s);for(;g<r;)a=i+u,l=a-i,s=i-(a-l)+(u-l),u=o[++g],i=a,0!==s&&(n[d++]=s);return 0===i&&0!==d||(n[d++]=i),d}function Gr(e){return new Float64Array(e)}const Hr=Gr(4),Br=Gr(8),zr=Gr(12),Ur=Gr(16),Nr=Gr(4);function Rr(e,t,r,o,n,i){const a=(t-i)*(r-n),s=(e-n)*(o-i),l=a-s,c=Math.abs(a+s);return Math.abs(l)>=33306690738754716e-32*c?l:-function(e,t,r,o,n,i,a){let s,l,c,u,h,g,d,p,f,y,m,v,M,b,w,P,L,k;const x=e-n,E=r-n,S=t-i,D=o-i;b=x*D,g=Or*x,d=g-(g-x),p=x-d,g=Or*D,f=g-(g-D),y=D-f,w=p*y-(b-d*f-p*f-d*y),P=S*E,g=Or*S,d=g-(g-S),p=S-d,g=Or*E,f=g-(g-E),y=E-f,L=p*y-(P-d*f-p*f-d*y),m=w-L,h=w-m,Hr[0]=w-(m+h)+(h-L),v=b+m,h=v-b,M=b-(v-h)+(m-h),m=M-P,h=M-m,Hr[1]=M-(m+h)+(h-P),k=v+m,h=k-v,Hr[2]=v-(k-h)+(m-h),Hr[3]=k;let C=function(e,t){let r=t[0];for(let o=1;o<e;o++)r+=t[o];return r}(4,Hr),I=22204460492503146e-32*a;if(C>=I||-C>=I)return C;if(h=e-x,s=e-(x+h)+(h-n),h=r-E,c=r-(E+h)+(h-n),h=t-S,l=t-(S+h)+(h-i),h=o-D,u=o-(D+h)+(h-i),0===s&&0===l&&0===c&&0===u)return C;if(I=11093356479670487e-47*a+Tr*Math.abs(C),C+=x*u+D*s-(S*c+E*l),C>=I||-C>=I)return C;b=s*D,g=Or*s,d=g-(g-s),p=s-d,g=Or*D,f=g-(g-D),y=D-f,w=p*y-(b-d*f-p*f-d*y),P=l*E,g=Or*l,d=g-(g-l),p=l-d,g=Or*E,f=g-(g-E),y=E-f,L=p*y-(P-d*f-p*f-d*y),m=w-L,h=w-m,Nr[0]=w-(m+h)+(h-L),v=b+m,h=v-b,M=b-(v-h)+(m-h),m=M-P,h=M-m,Nr[1]=M-(m+h)+(h-P),k=v+m,h=k-v,Nr[2]=v-(k-h)+(m-h),Nr[3]=k;const A=_r(4,Hr,4,Nr,Br);b=x*u,g=Or*x,d=g-(g-x),p=x-d,g=Or*u,f=g-(g-u),y=u-f,w=p*y-(b-d*f-p*f-d*y),P=S*c,g=Or*S,d=g-(g-S),p=S-d,g=Or*c,f=g-(g-c),y=c-f,L=p*y-(P-d*f-p*f-d*y),m=w-L,h=w-m,Nr[0]=w-(m+h)+(h-L),v=b+m,h=v-b,M=b-(v-h)+(m-h),m=M-P,h=M-m,Nr[1]=M-(m+h)+(h-P),k=v+m,h=k-v,Nr[2]=v-(k-h)+(m-h),Nr[3]=k;const F=_r(A,Br,4,Nr,zr);b=s*u,g=Or*s,d=g-(g-s),p=s-d,g=Or*u,f=g-(g-u),y=u-f,w=p*y-(b-d*f-p*f-d*y),P=l*c,g=Or*l,d=g-(g-l),p=l-d,g=Or*c,f=g-(g-c),y=c-f,L=p*y-(P-d*f-p*f-d*y),m=w-L,h=w-m,Nr[0]=w-(m+h)+(h-L),v=b+m,h=v-b,M=b-(v-h)+(m-h),m=M-P,h=M-m,Nr[1]=M-(m+h)+(h-P),k=v+m,h=k-v,Nr[2]=v-(k-h)+(m-h),Nr[3]=k;const O=_r(F,zr,4,Nr,Ur);return Ur[O-1]}(e,t,r,o,n,i,c)}function Xr(e,t){var r,o,n,i,a,s,l,c,u,h=0,g=e[0],d=e[1],p=t.length;for(r=0;r<p;r++){o=0;var f=t[r],y=f.length-1;if((c=f[0])[0]!==f[y][0]&&c[1]!==f[y][1])throw new Error("First and last coordinates in a ring must be the same");for(i=c[0]-g,a=c[1]-d;o<y;o++){if(s=(u=f[o+1])[0]-g,l=u[1]-d,0===a&&0===l){if(s<=0&&i>=0||i<=0&&s>=0)return 0}else if(l>=0&&a<=0||l<=0&&a>=0){if(0===(n=Rr(i,s,a,l,0,0)))return 0;(n>0&&l>0&&a<=0||n<0&&l<=0&&a>0)&&h++}c=u,a=l,i=s}}return h%2!=0}function Yr(e,t,r={}){if(!e)throw new Error("point is required");if(!t)throw new Error("polygon is required");const o=Me(e),n=we(t),i=n.type,a=t.bbox;let s=n.coordinates;if(a&&!1===function(e,t){return t[0]<=e[0]&&t[1]<=e[1]&&t[2]>=e[0]&&t[3]>=e[1]}(o,a))return!1;"Polygon"===i&&(s=[s]);let l=!1;for(var c=0;c<s.length;++c){const e=Xr(o,s[c]);if(0===e)return!r.ignoreBoundary;e&&(l=!0)}return l}var Vr=Yr;function qr(e,t){if("Polygon"!==e.geometry.type)throw new Error("The input feature must be a Polygon");for(var r=e.geometry.coordinates,o=[],n={},i=[],a=0;a<r.length;a++)for(var s=0;s<r[a].length-1;s++)i.push(g(a,s));var l=new mr;l.load(i);for(var c=0;c<r.length;c++)for(var u=0;u<r[c].length-1;u++){l.search(g(c,u)).forEach(function(e){var t=e.ring,r=e.edge;h(c,u,t,r)})}return o;function h(e,i,a,s){var l,c,u=r[e][i],h=r[e][i+1],g=r[a][s],d=r[a][s+1],p=function(e,t,r,o){if(jr(e,r)||jr(e,o)||jr(t,r)||jr(o,r))return null;var n=e[0],i=e[1],a=t[0],s=t[1],l=r[0],c=r[1],u=o[0],h=o[1],g=(n-a)*(c-h)-(i-s)*(l-u);return 0===g?null:[((n*s-i*a)*(l-u)-(n-a)*(l*h-c*u))/g,((n*s-i*a)*(c-h)-(i-s)*(l*h-c*u))/g]}(u,h,g,d);if(null!==p&&(l=h[0]!==u[0]?(p[0]-u[0])/(h[0]-u[0]):(p[1]-u[1])/(h[1]-u[1]),c=d[0]!==g[0]?(p[0]-g[0])/(d[0]-g[0]):(p[1]-g[1])/(d[1]-g[1]),!(l>=1||l<=0||c>=1||c<=0))){var f=p,y=!n[f.toString()];y&&(n[f.toString()]=!0),t&&o.push(t(p,e,i,u,h,l,a,s,g,d,c,y))}}function g(e,t){var o,n,i,a,s=r[e][t],l=r[e][t+1];return s[0]<l[0]?(o=s[0],n=l[0]):(o=l[0],n=s[0]),s[1]<l[1]?(i=s[1],a=l[1]):(i=l[1],a=s[1]),{minX:o,minY:i,maxX:n,maxY:a,ring:e,edge:t}}}function jr(e,t){if(!e||!t)return!1;if(e.length!==t.length)return!1;for(var r=0,o=e.length;r<o;r++)if(e[r]instanceof Array&&t[r]instanceof Array){if(!jr(e[r],t[r]))return!1}else if(e[r]!==t[r])return!1;return!0}function Wr(e){if("Feature"!=e.type)throw new Error("The input must a geojson object of type Feature");if(void 0===e.geometry||null==e.geometry)throw new Error("The input must a geojson object with a non-empty geometry");if("Polygon"!=e.geometry.type)throw new Error("The input must be a geojson Polygon");for(var t=e.geometry.coordinates.length,r=[],o=0;o<t;o++){var n=e.geometry.coordinates[o];Qr(n[0],n[n.length-1])||n.push(n[0]);for(var i=0;i<n.length-1;i++)r.push(n[i])}if(!function(e){for(var t={},r=1,o=0,n=e.length;o<n;++o){if(Object.prototype.hasOwnProperty.call(t,e[o].toString())){r=0;break}t[e[o].toString()]=1}return r}(r))throw new Error("The input polygon may not have duplicate vertices (except for the first and last vertex of each ring)");var a=r.length,s=qr(e,function(e,t,r,o,n,i,a,s,l,c,u,h){return[e,t,r,o,n,i,a,s,l,c,u,h]}),l=s.length;if(0==l){var c=[];for(o=0;o<t;o++)c.push(O([e.geometry.coordinates[o]],{parent:-1,winding:Zr(e.geometry.coordinates[o])}));let r=_(c);return H(r),B(r),r}var u=[],h=[];for(o=0;o<t;o++){u.push([]);for(i=0;i<e.geometry.coordinates[o].length-1;i++)u[o].push([new $r(e.geometry.coordinates[o][eo(i+1,e.geometry.coordinates[o].length-1)],1,[o,i],[o,eo(i+1,e.geometry.coordinates[o].length-1)],void 0)]),h.push(new Kr(e.geometry.coordinates[o][i],[o,eo(i-1,e.geometry.coordinates[o].length-1)],[o,i],void 0,void 0,!1,!0))}for(o=0;o<l;o++)u[s[o][1]][s[o][2]].push(new $r(s[o][0],s[o][5],[s[o][1],s[o][2]],[s[o][6],s[o][7]],void 0)),s[o][11]&&h.push(new Kr(s[o][0],[s[o][1],s[o][2]],[s[o][6],s[o][7]],void 0,void 0,!0,!0));var g=h.length;for(o=0;o<u.length;o++)for(i=0;i<u[o].length;i++)u[o][i].sort(function(e,t){return e.param<t.param?-1:1});var d=[];for(o=0;o<g;o++)d.push({minX:h[o].coord[0],minY:h[o].coord[1],maxX:h[o].coord[0],maxY:h[o].coord[1],index:o});var p=new mr;p.load(d);for(o=0;o<u.length;o++)for(i=0;i<u[o].length;i++)for(var f=0;f<u[o][i].length;f++){let t;t=f==u[o][i].length-1?u[o][eo(i+1,e.geometry.coordinates[o].length-1)][0].coord:u[o][i][f+1].coord;var y=p.search({minX:t[0],minY:t[1],maxX:t[0],maxY:t[1]})[0];u[o][i][f].nxtIsectAlongEdgeIn=y.index}for(o=0;o<u.length;o++)for(i=0;i<u[o].length;i++)for(f=0;f<u[o][i].length;f++){let e=u[o][i][f].coord;var m=(y=p.search({minX:e[0],minY:e[1],maxX:e[0],maxY:e[1]})[0]).index;m<a?h[m].nxtIsectAlongRingAndEdge2=u[o][i][f].nxtIsectAlongEdgeIn:Qr(h[m].ringAndEdge1,u[o][i][f].ringAndEdgeIn)?h[m].nxtIsectAlongRingAndEdge1=u[o][i][f].nxtIsectAlongEdgeIn:h[m].nxtIsectAlongRingAndEdge2=u[o][i][f].nxtIsectAlongEdgeIn}var v=[];for(o=0,i=0;i<t;i++){var M=o;for(f=0;f<e.geometry.coordinates[i].length-1;f++)h[o].coord[0]<h[M].coord[0]&&(M=o),o++;var b=h[M].nxtIsectAlongRingAndEdge2;for(f=0;f<h.length;f++)if(h[f].nxtIsectAlongRingAndEdge1==M||h[f].nxtIsectAlongRingAndEdge2==M){var w=f;break}var P=Jr([h[w].coord,h[M].coord,h[b].coord],!0)?1:-1;v.push({isect:M,parent:-1,winding:P})}v.sort(function(e,t){return h[e.isect].coord>h[t.isect].coord?-1:1});for(c=[];v.length>0;){var L=v.pop(),k=L.isect,x=L.parent,E=L.winding,S=c.length,D=[h[k].coord],C=k;if(h[k].ringAndEdge1Walkable)var I=h[k].ringAndEdge1,A=h[k].nxtIsectAlongRingAndEdge1;else I=h[k].ringAndEdge2,A=h[k].nxtIsectAlongRingAndEdge2;for(;!Qr(h[k].coord,h[A].coord);){D.push(h[A].coord);var F=void 0;for(o=0;o<v.length;o++)if(v[o].isect==A){F=o;break}if(null!=F&&v.splice(F,1),Qr(I,h[A].ringAndEdge1)){if(I=h[A].ringAndEdge2,h[A].ringAndEdge2Walkable=!1,h[A].ringAndEdge1Walkable){var T={isect:A};Jr([h[C].coord,h[A].coord,h[h[A].nxtIsectAlongRingAndEdge2].coord],1==E)?(T.parent=x,T.winding=-E):(T.parent=S,T.winding=E),v.push(T)}C=A,A=h[A].nxtIsectAlongRingAndEdge2}else{if(I=h[A].ringAndEdge1,h[A].ringAndEdge1Walkable=!1,h[A].ringAndEdge2Walkable){T={isect:A};Jr([h[C].coord,h[A].coord,h[h[A].nxtIsectAlongRingAndEdge1].coord],1==E)?(T.parent=x,T.winding=-E):(T.parent=S,T.winding=E),v.push(T)}C=A,A=h[A].nxtIsectAlongRingAndEdge1}}D.push(h[A].coord),c.push(O([D],{index:S,parent:x,winding:E,netWinding:void 0}))}let G=_(c);function H(e){for(var t=[],r=0;r<e.features.length;r++)-1==e.features[r].properties.parent&&t.push(r);if(t.length>1)for(r=0;r<t.length;r++){for(var o=-1,n=1/0,i=0;i<e.features.length;i++)t[r]!=i&&Yr(e.features[t[r]].geometry.coordinates[0][0],e.features[i],{ignoreBoundary:!0})&&R(e.features[i])<n&&(o=i);e.features[t[r]].properties.parent=o}}function B(e){for(var t=0;t<e.features.length;t++)if(-1==e.features[t].properties.parent){var r=e.features[t].properties.winding;e.features[t].properties.netWinding=r,z(e,t,r)}}function z(e,t,r){for(var o=0;o<e.features.length;o++)if(e.features[o].properties.parent==t){var n=r+e.features[o].properties.winding;e.features[o].properties.netWinding=n,z(e,o,n)}}return H(G),B(G),G}var $r=class{constructor(e,t,r,o,n){this.coord=e,this.param=t,this.ringAndEdgeIn=r,this.ringAndEdgeOut=o,this.nxtIsectAlongEdgeIn=n}},Kr=class{constructor(e,t,r,o,n,i,a){this.coord=e,this.ringAndEdge1=t,this.ringAndEdge2=r,this.nxtIsectAlongRingAndEdge1=o,this.nxtIsectAlongRingAndEdge2=n,this.ringAndEdge1Walkable=i,this.ringAndEdge2Walkable=a}};function Jr(e,t){if(void 0===t&&(t=!0),3!=e.length)throw new Error("This function requires an array of three points [x,y]");return(e[1][0]-e[0][0])*(e[2][1]-e[0][1])-(e[1][1]-e[0][1])*(e[2][0]-e[0][0])>=0==t}function Zr(e){for(var t=0,r=0;r<e.length-1;r++)e[r][0]<e[t][0]&&(t=r);if(Jr([e[eo(t-1,e.length-1)],e[t],e[eo(t+1,e.length-1)]],!0))var o=1;else o=-1;return o}function Qr(e,t){if(!e||!t)return!1;if(e.length!=t.length)return!1;for(var r=0,o=e.length;r<o;r++)if(e[r]instanceof Array&&t[r]instanceof Array){if(!Qr(e[r],t[r]))return!1}else if(e[r]!=t[r])return!1;return!0}function eo(e,t){return(e%t+t)%t}var to=function(e){var t=[];return gr(e,function(e){"Polygon"===e.geometry.type&&function(e,t){if("Feature"===e.type)t(e,0);else if("FeatureCollection"===e.type)for(var r=0;r<e.features.length&&!1!==t(e.features[r],r);r++);}(Wr(e),function(r){t.push(O(r.geometry.coordinates,e.properties))})}),_(t)};function ro(e,t,r){if(null!==e)for(var o,n,i,a,s,l,c,u,h=0,g=0,d=e.type,p="FeatureCollection"===d,f="Feature"===d,y=p?e.features.length:1,m=0;m<y;m++){s=(u=!!(c=p?e.features[m].geometry:f?e.geometry:e)&&"GeometryCollection"===c.type)?c.geometries.length:1;for(var v=0;v<s;v++){var M=0,b=0;if(null!==(a=u?c.geometries[v]:c)){l=a.coordinates;var w=a.type;switch(h=0,w){case null:break;case"Point":if(!1===t(l,g,m,M,b))return!1;g++,M++;break;case"LineString":case"MultiPoint":for(o=0;o<l.length;o++){if(!1===t(l[o],g,m,M,b))return!1;g++,"MultiPoint"===w&&M++}"LineString"===w&&M++;break;case"Polygon":case"MultiLineString":for(o=0;o<l.length;o++){for(n=0;n<l[o].length-h;n++){if(!1===t(l[o][n],g,m,M,b))return!1;g++}"MultiLineString"===w&&M++,"Polygon"===w&&b++}"Polygon"===w&&M++;break;case"MultiPolygon":for(o=0;o<l.length;o++){for(b=0,n=0;n<l[o].length;n++){for(i=0;i<l[o][n].length-h;i++){if(!1===t(l[o][n][i],g,m,M,b))return!1;g++}b++}M++}break;case"GeometryCollection":for(o=0;o<a.geometries.length;o++)if(!1===ro(a.geometries[o],t))return!1;break;default:throw new Error("Unknown Geometry Type")}}}}}function oo(e,t={}){if(null!=e.bbox&&!0!==t.recompute)return e.bbox;const r=[1/0,1/0,-1/0,-1/0];return ro(e,e=>{r[0]>e[0]&&(r[0]=e[0]),r[1]>e[1]&&(r[1]=e[1]),r[2]<e[0]&&(r[2]=e[0]),r[3]<e[1]&&(r[3]=e[1])}),r}function no(e){var t;if(e.bbox)t=e.bbox;else if(Array.isArray(e)&&4===e.length)t=e;else if(Array.isArray(e)&&6===e.length)t=[e[0],e[1],e[3],e[4]];else if("Feature"===e.type)t=oo(e);else{if("FeatureCollection"!==e.type)throw new Error("invalid geojson");t=oo(e)}return{minX:t[0],minY:t[1],maxX:t[2],maxY:t[3]}}var io=class{constructor(e=9){this.tree=new mr(e),this.tree.toBBox=no}insert(e){if("Feature"!==e.type)throw new Error("invalid feature");return e.bbox=e.bbox?e.bbox:oo(e),this.tree.insert(e),this}load(e){var t=[];return Array.isArray(e)?e.forEach(function(e){if("Feature"!==e.type)throw new Error("invalid features");e.bbox=e.bbox?e.bbox:oo(e),t.push(e)}):function(e,t){if("Feature"===e.type)t(e,0);else if("FeatureCollection"===e.type)for(var r=0;r<e.features.length&&!1!==t(e.features[r],r);r++);}(e,function(e){if("Feature"!==e.type)throw new Error("invalid features");e.bbox=e.bbox?e.bbox:oo(e),t.push(e)}),this.tree.load(t),this}remove(e,t){if("Feature"!==e.type)throw new Error("invalid feature");return e.bbox=e.bbox?e.bbox:oo(e),this.tree.remove(e,t),this}clear(){return this.tree.clear(),this}search(e){return _(this.tree.search(no(e)))}collides(e){return this.tree.collides(no(e))}all(){return _(this.tree.all())}toJSON(){return this.tree.toJSON()}fromJSON(e){return this.tree.fromJSON(e),this}};function ao(e){return new io(e)}function so(e,t,r){if(null!==e)for(var o,n,i,a,s,l,c,u,h=0,g=0,d=e.type,p="FeatureCollection"===d,f="Feature"===d,y=p?e.features.length:1,m=0;m<y;m++){s=(u=!!(c=p?e.features[m].geometry:f?e.geometry:e)&&"GeometryCollection"===c.type)?c.geometries.length:1;for(var v=0;v<s;v++){var M=0,b=0;if(null!==(a=u?c.geometries[v]:c)){l=a.coordinates;var w=a.type;switch(h=0,w){case null:break;case"Point":if(!1===t(l,g,m,M,b))return!1;g++,M++;break;case"LineString":case"MultiPoint":for(o=0;o<l.length;o++){if(!1===t(l[o],g,m,M,b))return!1;g++,"MultiPoint"===w&&M++}"LineString"===w&&M++;break;case"Polygon":case"MultiLineString":for(o=0;o<l.length;o++){for(n=0;n<l[o].length-h;n++){if(!1===t(l[o][n],g,m,M,b))return!1;g++}"MultiLineString"===w&&M++,"Polygon"===w&&b++}"Polygon"===w&&M++;break;case"MultiPolygon":for(o=0;o<l.length;o++){for(b=0,n=0;n<l[o].length;n++){for(i=0;i<l[o][n].length-h;i++){if(!1===t(l[o][n][i],g,m,M,b))return!1;g++}b++}M++}break;case"GeometryCollection":for(o=0;o<a.geometries.length;o++)if(!1===so(a.geometries[o],t))return!1;break;default:throw new Error("Unknown Geometry Type")}}}}}function lo(e,t){if(!U(t=null!=t?t:{}))throw new Error("options is invalid");var r=t.precision,o=t.coordinates,n=t.mutate;if(r=null==r||isNaN(r)?6:r,o=null==o||isNaN(o)?3:o,!e)throw new Error("<geojson> is required");if("number"!=typeof r)throw new Error("<precision> must be a number");if("number"!=typeof o)throw new Error("<coordinates> must be a number");!1!==n&&void 0!==n||(e=JSON.parse(JSON.stringify(e)));var i=Math.pow(10,r);return so(e,function(e){!function(e,t,r){e.length>r&&e.splice(r,e.length);for(var o=0;o<e.length;o++)e[o]=Math.round(e[o]*t)/t}(e,i,o)}),e}function co(e,t){!function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,function(e,r,o,n,i){var a,s=null===e?null:e.type;switch(s){case null:case"Point":case"LineString":case"Polygon":return!1!==t(A(e,o,{bbox:n,id:i}),r,0)&&void 0}switch(s){case"MultiPoint":a="Point";break;case"MultiLineString":a="LineString";break;case"MultiPolygon":a="Polygon"}for(var l=0;l<e.coordinates.length;l++){var c=e.coordinates[l];if(!1===t(A({type:a,coordinates:c},o),r,l))return!1}})}function uo(e){if(!e)throw new Error("geojson is required");const t=[];return co(e,e=>{!function(e,t){let r=[];const o=e.geometry;if(null!==o){switch(o.type){case"Polygon":r=be(o);break;case"LineString":r=[be(o)]}r.forEach(r=>{const o=function(e,t){const r=[];return e.reduce((e,o)=>{const n=T([e,o],t);return n.bbox=function(e,t){const r=e[0],o=e[1],n=t[0],i=t[1];return[r<n?r:n,o<i?o:i,r>n?r:n,o>i?o:i]}(e,o),r.push(n),o}),r}(r,e.properties);o.forEach(e=>{e.id=t.length,t.push(e)})})}}(e,t)}),_(t)}function ho(e,t,r={}){var o=Me(e),n=Me(t),i=B(n[1]-o[1]),a=B(n[0]-o[0]),s=B(o[1]),l=B(n[1]),c=Math.pow(Math.sin(i/2),2)+Math.pow(Math.sin(a/2),2)*Math.cos(s)*Math.cos(l);return function(e,t="kilometers"){const r=I[t];if(!r)throw new Error(t+" units is invalid");return e*r}(2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c)),r.units)}function go(e,t){!function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,function(e,r,o,n,i){var a,s=null===e?null:e.type;switch(s){case null:case"Point":case"LineString":case"Polygon":return!1!==t(A(e,o,{bbox:n,id:i}),r,0)&&void 0}switch(s){case"MultiPoint":a="Point";break;case"MultiLineString":a="LineString";break;case"MultiPolygon":a="Polygon"}for(var l=0;l<e.coordinates.length;l++){var c=e.coordinates[l];if(!1===t(A({type:a,coordinates:c},o),r,l))return!1}})}var po=Object.defineProperty,fo=Object.defineProperties,yo=Object.getOwnPropertyDescriptors,mo=Object.getOwnPropertySymbols,vo=Object.prototype.hasOwnProperty,Mo=Object.prototype.propertyIsEnumerable,bo=(e,t,r)=>t in e?po(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,wo=(e,t)=>{for(var r in t||(t={}))vo.call(t,r)&&bo(e,r,t[r]);if(mo)for(var r of mo(t))Mo.call(t,r)&&bo(e,r,t[r]);return e},Po=(e,t)=>fo(e,yo(t));function Lo(e,t){const[r,o,n]=e,[i,a,s]=t;return r*i+o*a+n*s}function ko(e,t){const[r,o,n]=e,[i,a,s]=t;return[o*s-n*a,n*i-r*s,r*a-o*i]}function xo(e){const t=function(e){return Math.sqrt(Math.pow(e[0],2)+Math.pow(e[1],2)+Math.pow(e[2],2))}(e);return[e[0]/t,e[1]/t,e[2]/t]}function Eo(e){const t=B(e[1]),r=B(e[0]);return[Math.cos(t)*Math.cos(r),Math.cos(t)*Math.sin(r),Math.sin(t)]}function So(e){const[t,r,o]=e,n=Math.min(Math.max(o,-1),1),i=H(Math.asin(n));return[H(Math.atan2(r,t)),i]}function Do(e,t,r){const o=Eo(e),n=Eo(t),i=Eo(r),a=ko(o,n);if(0===a[0]&&0===a[1]&&0===a[2])return Lo(o,n)>0?[[...t],!0]:[[...r],!1];const s=ko(a,i);if(0===s[0]&&0===s[1]&&0===s[2])return[[...t],!0];const l=xo(ko(s,a)),c=[-l[0],-l[1],-l[2]],u=Lo(i,l)>Lo(i,c)?l:c,h=xo(a),g=Lo(ko(o,u),h),d=Lo(ko(u,n),h);return g>=0&&d>=0?[So(u),!1]:Lo(o,i)>Lo(n,i)?[[...e],!1]:[[...t],!0]}function Co(e,t){if("Feature"===e.type)t(e,0);else if("FeatureCollection"===e.type)for(var r=0;r<e.features.length&&!1!==t(e.features[r],r);r++);}function Io(e,t){!function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,function(e,r,o,n,i){var a,s=null===e?null:e.type;switch(s){case null:case"Point":case"LineString":case"Polygon":return!1!==t(A(e,o,{bbox:n,id:i}),r,0)&&void 0}switch(s){case"MultiPoint":a="Point";break;case"MultiLineString":a="LineString";break;case"MultiPolygon":a="Polygon"}for(var l=0;l<e.coordinates.length;l++){var c=e.coordinates[l];if(!1===t(A({type:a,coordinates:c},o),r,l))return!1}})}function Ao(e,t){if(!e)throw new Error("line is required");if(!t)throw new Error("splitter is required");const r=Pe(e),o=Pe(t);if("LineString"!==r)throw new Error("line must be LineString");if("FeatureCollection"===o)throw new Error("splitter cannot be a FeatureCollection");if("GeometryCollection"===o)throw new Error("splitter cannot be a GeometryCollection");var n=lo(t,{precision:7});switch("Feature"!==e.type&&(e=A(e)),o){case"Point":return Oo(e,n);case"MultiPoint":return Fo(e,n);case"LineString":case"MultiLineString":case"Polygon":case"MultiPolygon":return Fo(e,He(e,n,{ignoreSelfIntersections:!0}))}}function Fo(e,t){var r=[],o=ao();return Io(t,function(t){if(r.forEach(function(e,t){e.id=t}),r.length){var n=o.search(t);if(n.features.length){var i=To(t,n);r=r.filter(function(e){return e.id!==i.id}),o.remove(i),Co(Oo(i,t),function(e){r.push(e),o.insert(e)})}}else r=Oo(e,t).features,o.load(_(r))}),_(r)}function Oo(e,t){var r=[],o=be(e)[0],n=be(e)[e.geometry.coordinates.length-1];if(_o(o,Me(t))||_o(n,Me(t)))return _([e]);var i=ao(),a=uo(e);i.load(a);var s=i.search(t);if(!s.features.length)return _([e]);var l=To(t,s),c=function(e,t,r){var o=r;return Co(e,function(e,n){o=0===n&&void 0===r?e:t(o,e,n)}),o}(a,function(e,o,n){var i=be(o)[1],a=Me(t);return n===l.id?(e.push(a),r.push(T(e)),_o(a,i)?[a]:[a,i]):(e.push(i),e)},[o]);return c.length>1&&r.push(T(c)),_(r)}function To(e,t){if(!t.features.length)throw new Error("lines must contain features");if(1===t.features.length)return t.features[0];var r,o=1/0;return Co(t,function(t){var n=function(e,t,r={}){if(!e||!t)throw new Error("lines and inputPoint are required arguments");const o=Me(t);let n=F([1/0,1/0],{lineStringIndex:-1,segmentIndex:-1,totalDistance:-1,lineDistance:-1,segmentDistance:-1,pointDistance:1/0,multiFeatureIndex:-1,index:-1,location:-1,dist:1/0}),i=0,a=0,s=-1;return go(e,function(e,l,c){s!==c&&(s=c,a=0);const u=be(e);for(let s=0;s<u.length-1;s++){const e=F(u[s]),l=Me(e),h=F(u[s+1]),g=Me(h),d=ho(e,h,r);let p,f;g[0]===o[0]&&g[1]===o[1]?[p,f]=[g,!0]:l[0]===o[0]&&l[1]===o[1]?[p,f]=[l,!1]:[p,f]=Do(l,g,o);const y=ho(t,p,r);if(y<n.properties.pointDistance){const t=ho(e,p,r);n=F(p,{lineStringIndex:c,segmentIndex:f?s+1:s,totalDistance:i+t,lineDistance:a+t,segmentDistance:t,pointDistance:y,multiFeatureIndex:-1,index:-1,location:-1,dist:1/0}),n.properties=Po(wo({},n.properties),{multiFeatureIndex:n.properties.lineStringIndex,index:n.properties.segmentIndex,location:n.properties.totalDistance,dist:n.properties.pointDistance})}i+=d,a+=d}}),n}(t,e),i=n.properties.dist;i<o&&(r=t,o=i)}),r}function _o(e,t){return e[0]===t[0]&&e[1]===t[1]}function Go(e,t){return!(e[0]>t[0])&&(!(e[2]<t[2])&&(!(e[1]>t[1])&&!(e[3]<t[3])))}function Ho(e,t){return e[0]===t[0]&&e[1]===t[1]}function Bo(e,t){return[(e[0]+t[0])/2,(e[1]+t[1])/2]}var zo=function(e,t){var r=we(e),o=we(t),n=r.type,i=o.type;switch(n){case"Point":switch(i){case"MultiPoint":return function(e,t){var r,o=!1;for(r=0;r<t.coordinates.length;r++)if(Ho(t.coordinates[r],e.coordinates)){o=!0;break}return o}(r,o);case"LineString":return qt(r,o,{ignoreEndVertices:!0});case"Polygon":case"MultiPolygon":return Yr(r,o,{ignoreBoundary:!0});default:throw new Error("feature2 "+i+" geometry not supported")}case"MultiPoint":switch(i){case"MultiPoint":return function(e,t){for(var r=0;r<e.coordinates.length;r++){for(var o=!1,n=0;n<t.coordinates.length;n++)Ho(e.coordinates[r],t.coordinates[n])&&(o=!0);if(!o)return!1}return!0}(r,o);case"LineString":return function(e,t){for(var r=!1,o=0;o<e.coordinates.length;o++){if(!qt(e.coordinates[o],t))return!1;r||(r=qt(e.coordinates[o],t,{ignoreEndVertices:!0}))}return r}(r,o);case"Polygon":case"MultiPolygon":return function(e,t){for(var r=!0,o=!1,n=0;n<e.coordinates.length;n++){if(!(o=Yr(e.coordinates[n],t))){r=!1;break}o=Yr(e.coordinates[n],t,{ignoreBoundary:!0})}return r&&o}(r,o);default:throw new Error("feature2 "+i+" geometry not supported")}case"LineString":switch(i){case"LineString":return function(e,t){for(var r=0;r<e.coordinates.length;r++)if(!qt(e.coordinates[r],t))return!1;return!0}(r,o);case"Polygon":case"MultiPolygon":return function(e,t){const r=oo(t),o=oo(e);if(!Go(r,o))return!1;for(const a of e.coordinates)if(!Yr(a,t))return!1;let n=!1;const i=function(e,t){const r=e.coordinates,o=[];for(let n=0;n<r.length-1;n++){const e=T([r[n],r[n+1]]),i=Ao(e,A(t));0===i.features.length?o.push(e):o.push(...i.features)}return _(o)}(e,t);for(const a of i.features){const e=Bo(a.geometry.coordinates[0],a.geometry.coordinates[1]);if(!Yr(e,t))return!1;!n&&Yr(e,t,{ignoreBoundary:!0})&&(n=!0)}return n}(r,o);default:throw new Error("feature2 "+i+" geometry not supported")}case"Polygon":switch(i){case"Polygon":case"MultiPolygon":return function(e,t){var r=oo(e);if(!Go(oo(t),r))return!1;for(var o=0;o<e.coordinates[0].length;o++)if(!Yr(e.coordinates[0][o],t))return!1;return!0}(r,o);default:throw new Error("feature2 "+i+" geometry not supported")}default:throw new Error("feature1 "+n+" geometry not supported")}},Uo=Object.defineProperty,No=(e,t)=>Uo(e,"name",{value:t,configurable:!0}),Ro=class{constructor(e){var t,r,o;this.direction=!1,this.compareProperties=!0,this.precision=10**-(null!=(t=null==e?void 0:e.precision)?t:17),this.direction=null!=(r=null==e?void 0:e.direction)&&r,this.compareProperties=null==(o=null==e?void 0:e.compareProperties)||o}compare(e,t){if(e.type!==t.type)return!1;if(!Yo(e,t))return!1;switch(e.type){case"Point":return this.compareCoord(e.coordinates,t.coordinates);case"LineString":return this.compareLine(e.coordinates,t.coordinates);case"Polygon":return this.comparePolygon(e,t);case"GeometryCollection":return this.compareGeometryCollection(e,t);case"Feature":return this.compareFeature(e,t);case"FeatureCollection":return this.compareFeatureCollection(e,t);default:if(e.type.startsWith("Multi")){const r=Vo(e),o=Vo(t);return r.every(e=>o.some(t=>this.compare(e,t)))}}return!1}compareCoord(e,t){return e.length===t.length&&e.every((e,r)=>Math.abs(e-t[r])<this.precision)}compareLine(e,t,r=0,o=!1){if(!Yo(e,t))return!1;const n=e;let i=t;if(o&&!this.compareCoord(n[0],i[0])){const e=this.fixStartIndex(i,n);if(!e)return!1;i=e}const a=this.compareCoord(n[r],i[r]);return this.direction||a?this.comparePath(n,i):!!this.compareCoord(n[r],i[i.length-(1+r)])&&this.comparePath(n.slice().reverse(),i)}fixStartIndex(e,t){let r,o=-1;for(let n=0;n<e.length;n++)if(this.compareCoord(e[n],t[0])){o=n;break}return o>=0&&(r=[].concat(e.slice(o,e.length),e.slice(1,o+1))),r}comparePath(e,t){return e.every((e,r)=>this.compareCoord(e,t[r]))}comparePolygon(e,t){if(this.compareLine(e.coordinates[0],t.coordinates[0],1,!0)){const r=e.coordinates.slice(1,e.coordinates.length),o=t.coordinates.slice(1,t.coordinates.length);return r.every(e=>o.some(t=>this.compareLine(e,t,1,!0)))}return!1}compareGeometryCollection(e,t){return Yo(e.geometries,t.geometries)&&this.compareBBox(e,t)&&e.geometries.every((e,r)=>this.compare(e,t.geometries[r]))}compareFeature(e,t){return e.id===t.id&&(!this.compareProperties||jo(e.properties,t.properties))&&this.compareBBox(e,t)&&this.compare(e.geometry,t.geometry)}compareFeatureCollection(e,t){return Yo(e.features,t.features)&&this.compareBBox(e,t)&&e.features.every((e,r)=>this.compare(e,t.features[r]))}compareBBox(e,t){return Boolean(!e.bbox&&!t.bbox)||!(!e.bbox||!t.bbox)&&this.compareCoord(e.bbox,t.bbox)}};No(Ro,"GeojsonEquality");var Xo=Ro;function Yo(e,t){return e.coordinates?e.coordinates.length===t.coordinates.length:e.length===t.length}function Vo(e){return e.coordinates.map(t=>({type:e.type.replace("Multi",""),coordinates:t}))}function qo(e,t,r){return new Xo(r).compare(e,t)}function jo(e,t){if(null===e&&null===t)return!0;if(null===e||null===t)return!1;const r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(var n of r){const r=e[n],o=t[n],i=Wo(r)&&Wo(o);if(i&&!jo(r,o)||!i&&r!==o)return!1}return!0}No(Yo,"sameLength"),No(Vo,"explode"),No(qo,"geojsonEquality"),No(jo,"equal");var Wo=No(e=>null!=e&&"object"==typeof e,"isObject");var $o=function(e,t,r={}){let o=r.precision;if(o=null==o||isNaN(o)?6:o,"number"!=typeof o||!(o>=0))throw new Error("precision must be a positive number");return we(e).type===we(t).type&&qo(Wt(e),Wt(t),{precision:o})};var Ko=Object.defineProperty,Jo=Object.defineProperties,Zo=Object.getOwnPropertyDescriptors,Qo=Object.getOwnPropertySymbols,en=Object.prototype.hasOwnProperty,tn=Object.prototype.propertyIsEnumerable,rn=(e,t,r)=>t in e?Ko(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,on=(e,t)=>{for(var r in t||(t={}))en.call(t,r)&&rn(e,r,t[r]);if(Qo)for(var r of Qo(t))tn.call(t,r)&&rn(e,r,t[r]);return e},nn=(e,t)=>Jo(e,Zo(t));var an=function(e,t,r={}){if(!e)throw new Error("targetPoint is required");if(!t)throw new Error("points is required");let o=1/0,n=0;!function(e,t){if("Feature"===e.type)t(e,0);else if("FeatureCollection"===e.type)for(var r=0;r<e.features.length&&!1!==t(e.features[r],r);r++);}(t,(t,i)=>{const a=ho(e,t,r);a<o&&(n=i,o=a)});const i=Jt(t.features[n]);return nn(on({},i),{properties:nn(on({},i.properties),{featureIndex:n,distanceToPoint:o})})},sn=class{constructor(e){this.points=e.points||[],this.duration=e.duration||1e4,this.sharpness=e.sharpness||.85,this.centers=[],this.controls=[],this.stepLength=e.stepLength||60,this.length=this.points.length,this.delay=0;for(let t=0;t<this.length;t++)this.points[t].z=this.points[t].z||0;for(let t=0;t<this.length-1;t++){const e=this.points[t],r=this.points[t+1];this.centers.push({x:(e.x+r.x)/2,y:(e.y+r.y)/2,z:(e.z+r.z)/2})}this.controls.push([this.points[0],this.points[0]]);for(let t=0;t<this.centers.length-1;t++){const e=this.points[t+1].x-(this.centers[t].x+this.centers[t+1].x)/2,r=this.points[t+1].y-(this.centers[t].y+this.centers[t+1].y)/2,o=this.points[t+1].z-(this.centers[t].y+this.centers[t+1].z)/2;this.controls.push([{x:(1-this.sharpness)*this.points[t+1].x+this.sharpness*(this.centers[t].x+e),y:(1-this.sharpness)*this.points[t+1].y+this.sharpness*(this.centers[t].y+r),z:(1-this.sharpness)*this.points[t+1].z+this.sharpness*(this.centers[t].z+o)},{x:(1-this.sharpness)*this.points[t+1].x+this.sharpness*(this.centers[t+1].x+e),y:(1-this.sharpness)*this.points[t+1].y+this.sharpness*(this.centers[t+1].y+r),z:(1-this.sharpness)*this.points[t+1].z+this.sharpness*(this.centers[t+1].z+o)}])}return this.controls.push([this.points[this.length-1],this.points[this.length-1]]),this.steps=this.cacheSteps(this.stepLength),this}cacheSteps(e){const t=[];let r=this.pos(0);t.push(0);for(let o=0;o<this.duration;o+=10){const n=this.pos(o);Math.sqrt((n.x-r.x)*(n.x-r.x)+(n.y-r.y)*(n.y-r.y)+(n.z-r.z)*(n.z-r.z))>e&&(t.push(o),r=n)}return t}vector(e){const t=this.pos(e+10),r=this.pos(e-10);return{angle:180*Math.atan2(t.y-r.y,t.x-r.x)/3.14,speed:Math.sqrt((r.x-t.x)*(r.x-t.x)+(r.y-t.y)*(r.y-t.y)+(r.z-t.z)*(r.z-t.z))}}pos(e){let t=e-this.delay;t<0&&(t=0),t>this.duration&&(t=this.duration-1);const r=t/this.duration;if(r>=1)return this.points[this.length-1];const o=Math.floor((this.points.length-1)*r);return function(e,t,r,o,n){const i=function(e){const t=e*e,r=t*e;return[r,3*t*(1-e),3*e*(1-e)*(1-e),(1-e)*(1-e)*(1-e)]}(e);return{x:n.x*i[0]+o.x*i[1]+r.x*i[2]+t.x*i[3],y:n.y*i[0]+o.y*i[1]+r.y*i[2]+t.y*i[3],z:n.z*i[0]+o.z*i[1]+r.z*i[2]+t.z*i[3]}}((this.length-1)*r-o,this.points[o],this.controls[o][1],this.controls[o+1][0],this.points[o+1])}};var ln=function(e,t={}){const r=t.resolution||1e4,o=t.sharpness||.85,n=[],i=we(e).coordinates.map(e=>({x:e[0],y:e[1]})),a=new sn({duration:r,points:i,sharpness:o}),s=e=>{var t=a.pos(e);Math.floor(e/100)%2==0&&n.push([t.x,t.y])};for(var l=0;l<a.duration;l+=10)s(l);return s(a.duration),T(n,t.properties)};function cn(e,t,r){if(null!==e)for(var o,n,i,a,s,l,c,u,h=0,g=0,d=e.type,p="FeatureCollection"===d,f="Feature"===d,y=p?e.features.length:1,m=0;m<y;m++){s=(u=!!(c=p?e.features[m].geometry:f?e.geometry:e)&&"GeometryCollection"===c.type)?c.geometries.length:1;for(var v=0;v<s;v++){var M=0,b=0;if(null!==(a=u?c.geometries[v]:c)){l=a.coordinates;var w=a.type;switch(h=0,w){case null:break;case"Point":if(!1===t(l,g,m,M,b))return!1;g++,M++;break;case"LineString":case"MultiPoint":for(o=0;o<l.length;o++){if(!1===t(l[o],g,m,M,b))return!1;g++,"MultiPoint"===w&&M++}"LineString"===w&&M++;break;case"Polygon":case"MultiLineString":for(o=0;o<l.length;o++){for(n=0;n<l[o].length-h;n++){if(!1===t(l[o][n],g,m,M,b))return!1;g++}"MultiLineString"===w&&M++,"Polygon"===w&&b++}"Polygon"===w&&M++;break;case"MultiPolygon":for(o=0;o<l.length;o++){for(b=0,n=0;n<l[o].length;n++){for(i=0;i<l[o][n].length-h;i++){if(!1===t(l[o][n][i],g,m,M,b))return!1;g++}b++}M++}break;case"GeometryCollection":for(o=0;o<a.geometries.length;o++)if(!1===cn(a.geometries[o],t))return!1;break;default:throw new Error("Unknown Geometry Type")}}}}}function un(e,t){!function(e,t){var r,o,n,i,a,s,l,c,u,h,g=0,d="FeatureCollection"===e.type,p="Feature"===e.type,f=d?e.features.length:1;for(r=0;r<f;r++){for(s=d?e.features[r].geometry:p?e.geometry:e,c=d?e.features[r].properties:p?e.properties:{},u=d?e.features[r].bbox:p?e.bbox:void 0,h=d?e.features[r].id:p?e.id:void 0,a=(l=!!s&&"GeometryCollection"===s.type)?s.geometries.length:1,n=0;n<a;n++)if(null!==(i=l?s.geometries[n]:s))switch(i.type){case"Point":case"LineString":case"MultiPoint":case"Polygon":case"MultiLineString":case"MultiPolygon":if(!1===t(i,g,c,u,h))return!1;break;case"GeometryCollection":for(o=0;o<i.geometries.length;o++)if(!1===t(i.geometries[o],g,c,u,h))return!1;break;default:throw new Error("Unknown Geometry Type")}else if(!1===t(null,g,c,u,h))return!1;g++}}(e,function(e,r,o,n,i){var a,s=null===e?null:e.type;switch(s){case null:case"Point":case"LineString":case"Polygon":return!1!==t(A(e,o,{bbox:n,id:i}),r,0)&&void 0}switch(s){case"MultiPoint":a="Point";break;case"MultiLineString":a="LineString";break;case"MultiPolygon":a="Polygon"}for(var l=0;l<e.coordinates.length;l++){var c=e.coordinates[l];if(!1===t(A({type:a,coordinates:c},o),r,l))return!1}})}function hn(e,t){un(e,function(e,r,o){var n=0;if(e.geometry){var i=e.geometry.type;if("Point"!==i&&"MultiPoint"!==i){var a,s=0,l=0,c=0;return!1!==cn(e,function(i,u,h,g,d){if(void 0===a||r>s||g>l||d>c)return a=i,s=r,l=g,c=d,void(n=0);var p=T([a,i],e.properties);if(!1===t(p,r,o,d,n))return!1;n++,a=i})&&void 0}}})}var gn=function(e,t={}){return function(e,t,r){var o=r,n=!1;return hn(e,function(e,i,a,s,l){o=!1===n&&void 0===r?e:t(o,e,i,a,s,l),n=!0}),o}(e,(e,r)=>{const o=r.geometry.coordinates;return e+ho(o[0],o[1],t)},0)};function dn(e,t,r=0,o=e.length-1,n=fn){for(;o>r;){if(o-r>600){const i=o-r+1,a=t-r+1,s=Math.log(i),l=.5*Math.exp(2*s/3),c=.5*Math.sqrt(s*l*(i-l)/i)*(a-i/2<0?-1:1);dn(e,t,Math.max(r,Math.floor(t-a*l/i+c)),Math.min(o,Math.floor(t+(i-a)*l/i+c)),n)}const i=e[t];let a=r,s=o;for(pn(e,r,t),n(e[o],i)>0&&pn(e,r,o);a<s;){for(pn(e,a,s),a++,s--;n(e[a],i)<0;)a++;for(;n(e[s],i)>0;)s--}0===n(e[r],i)?pn(e,r,s):(s++,pn(e,s,o)),s<=t&&(r=s+1),t<=s&&(o=s-1)}}function pn(e,t,r){const o=e[t];e[t]=e[r],e[r]=o}function fn(e,t){return e<t?-1:e>t?1:0}class yn{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let t=this.data;const r=[];if(!Dn(e,t))return r;const o=this.toBBox,n=[];for(;t;){for(let i=0;i<t.children.length;i++){const a=t.children[i],s=t.leaf?o(a):a;Dn(e,s)&&(t.leaf?r.push(a):Sn(e,s)?this._all(a,r):n.push(a))}t=n.pop()}return r}collides(e){let t=this.data;if(!Dn(e,t))return!1;const r=[];for(;t;){for(let o=0;o<t.children.length;o++){const n=t.children[o],i=t.leaf?this.toBBox(n):n;if(Dn(e,i)){if(t.leaf||Sn(e,i))return!0;r.push(n)}}t=r.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let t=0;t<e.length;t++)this.insert(e[t]);return this}let t=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===t.height)this._splitRoot(this.data,t);else{if(this.data.height<t.height){const e=this.data;this.data=t,t=e}this._insert(t,this.data.height-t.height-1,!0)}else this.data=t;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=Cn([]),this}remove(e,t){if(!e)return this;let r=this.data;const o=this.toBBox(e),n=[],i=[];let a,s,l;for(;r||n.length;){if(r||(r=n.pop(),s=n[n.length-1],a=i.pop(),l=!0),r.leaf){const o=mn(e,r.children,t);if(-1!==o)return r.children.splice(o,1),n.push(r),this._condense(n),this}l||r.leaf||!Sn(r,o)?s?(a++,r=s.children[a],l=!1):r=null:(n.push(r),i.push(a),a=0,s=r,r=r.children[0])}return this}toBBox(e){return e}compareMinX(e,t){return e.minX-t.minX}compareMinY(e,t){return e.minY-t.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,t){const r=[];for(;e;)e.leaf?t.push(...e.children):r.push(...e.children),e=r.pop();return t}_build(e,t,r,o){const n=r-t+1;let i,a=this._maxEntries;if(n<=a)return i=Cn(e.slice(t,r+1)),vn(i,this.toBBox),i;o||(o=Math.ceil(Math.log(n)/Math.log(a)),a=Math.ceil(n/Math.pow(a,o-1))),i=Cn([]),i.leaf=!1,i.height=o;const s=Math.ceil(n/a),l=s*Math.ceil(Math.sqrt(a));In(e,t,r,l,this.compareMinX);for(let c=t;c<=r;c+=l){const t=Math.min(c+l-1,r);In(e,c,t,s,this.compareMinY);for(let r=c;r<=t;r+=s){const n=Math.min(r+s-1,t);i.children.push(this._build(e,r,n,o-1))}}return vn(i,this.toBBox),i}_chooseSubtree(e,t,r,o){for(;o.push(t),!t.leaf&&o.length-1!==r;){let r,o=1/0,n=1/0;for(let i=0;i<t.children.length;i++){const a=t.children[i],s=Ln(a),l=xn(e,a)-s;l<n?(n=l,o=s<o?s:o,r=a):l===n&&s<o&&(o=s,r=a)}t=r||t.children[0]}return t}_insert(e,t,r){const o=r?e:this.toBBox(e),n=[],i=this._chooseSubtree(o,this.data,t,n);for(i.children.push(e),bn(i,o);t>=0&&n[t].children.length>this._maxEntries;)this._split(n,t),t--;this._adjustParentBBoxes(o,n,t)}_split(e,t){const r=e[t],o=r.children.length,n=this._minEntries;this._chooseSplitAxis(r,n,o);const i=this._chooseSplitIndex(r,n,o),a=Cn(r.children.splice(i,r.children.length-i));a.height=r.height,a.leaf=r.leaf,vn(r,this.toBBox),vn(a,this.toBBox),t?e[t-1].children.push(a):this._splitRoot(r,a)}_splitRoot(e,t){this.data=Cn([e,t]),this.data.height=e.height+1,this.data.leaf=!1,vn(this.data,this.toBBox)}_chooseSplitIndex(e,t,r){let o,n=1/0,i=1/0;for(let a=t;a<=r-t;a++){const t=Mn(e,0,a,this.toBBox),s=Mn(e,a,r,this.toBBox),l=En(t,s),c=Ln(t)+Ln(s);l<n?(n=l,o=a,i=c<i?c:i):l===n&&c<i&&(i=c,o=a)}return o||r-t}_chooseSplitAxis(e,t,r){const o=e.leaf?this.compareMinX:wn,n=e.leaf?this.compareMinY:Pn;this._allDistMargin(e,t,r,o)<this._allDistMargin(e,t,r,n)&&e.children.sort(o)}_allDistMargin(e,t,r,o){e.children.sort(o);const n=this.toBBox,i=Mn(e,0,t,n),a=Mn(e,r-t,r,n);let s=kn(i)+kn(a);for(let l=t;l<r-t;l++){const t=e.children[l];bn(i,e.leaf?n(t):t),s+=kn(i)}for(let l=r-t-1;l>=t;l--){const t=e.children[l];bn(a,e.leaf?n(t):t),s+=kn(a)}return s}_adjustParentBBoxes(e,t,r){for(let o=r;o>=0;o--)bn(t[o],e)}_condense(e){for(let t,r=e.length-1;r>=0;r--)0===e[r].children.length?r>0?(t=e[r-1].children,t.splice(t.indexOf(e[r]),1)):this.clear():vn(e[r],this.toBBox)}}function mn(e,t,r){if(!r)return t.indexOf(e);for(let o=0;o<t.length;o++)if(r(e,t[o]))return o;return-1}function vn(e,t){Mn(e,0,e.children.length,t,e)}function Mn(e,t,r,o,n){n||(n=Cn(null)),n.minX=1/0,n.minY=1/0,n.maxX=-1/0,n.maxY=-1/0;for(let i=t;i<r;i++){const t=e.children[i];bn(n,e.leaf?o(t):t)}return n}function bn(e,t){return e.minX=Math.min(e.minX,t.minX),e.minY=Math.min(e.minY,t.minY),e.maxX=Math.max(e.maxX,t.maxX),e.maxY=Math.max(e.maxY,t.maxY),e}function wn(e,t){return e.minX-t.minX}function Pn(e,t){return e.minY-t.minY}function Ln(e){return(e.maxX-e.minX)*(e.maxY-e.minY)}function kn(e){return e.maxX-e.minX+(e.maxY-e.minY)}function xn(e,t){return(Math.max(t.maxX,e.maxX)-Math.min(t.minX,e.minX))*(Math.max(t.maxY,e.maxY)-Math.min(t.minY,e.minY))}function En(e,t){const r=Math.max(e.minX,t.minX),o=Math.max(e.minY,t.minY),n=Math.min(e.maxX,t.maxX),i=Math.min(e.maxY,t.maxY);return Math.max(0,n-r)*Math.max(0,i-o)}function Sn(e,t){return e.minX<=t.minX&&e.minY<=t.minY&&t.maxX<=e.maxX&&t.maxY<=e.maxY}function Dn(e,t){return t.minX<=e.maxX&&t.minY<=e.maxY&&t.maxX>=e.minX&&t.maxY>=e.minY}function Cn(e){return{children:e,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function In(e,t,r,o,n){const i=[t,r];for(;i.length;){if((r=i.pop())-(t=i.pop())<=o)continue;const a=t+Math.ceil((r-t)/o/2)*o;dn(e,a,t,r,n),i.push(t,a,a,r)}}class An{constructor(e=[],t=(e,t)=>e<t?-1:e>t?1:0){if(this.data=e,this.length=this.data.length,this.compare=t,this.length>0)for(let r=(this.length>>1)-1;r>=0;r--)this._down(r)}push(e){this.data.push(e),this._up(this.length++)}pop(){if(0===this.length)return;const e=this.data[0],t=this.data.pop();return--this.length>0&&(this.data[0]=t,this._down(0)),e}peek(){return this.data[0]}_up(e){const{data:t,compare:r}=this,o=t[e];for(;e>0;){const n=e-1>>1,i=t[n];if(r(o,i)>=0)break;t[e]=i,e=n}t[e]=o}_down(e){const{data:t,compare:r}=this,o=this.length>>1,n=t[e];for(;e<o;){let o=1+(e<<1);const i=o+1;if(i<this.length&&r(t[i],t[o])<0&&(o=i),r(t[o],n)>=0)break;t[e]=t[o],e=o}t[e]=n}}const Fn=$(ce());function On(e,t,r){t=Math.max(0,void 0===t?2:t),r=r||0;const o=function(e){let t=e[0],r=e[0],o=e[0],n=e[0];for(let s=0;s<e.length;s++){const i=e[s];i[0]<t[0]&&(t=i),i[0]>o[0]&&(o=i),i[1]<r[1]&&(r=i),i[1]>n[1]&&(n=i)}const i=[t,r,o,n],a=i.slice();for(let s=0;s<e.length;s++)Fn(e[s],i)||a.push(e[s]);return function(e){e.sort(qn);const t=[];for(let o=0;o<e.length;o++){for(;t.length>=2&&zn(t[t.length-2],t[t.length-1],e[o])<=0;)t.pop();t.push(e[o])}const r=[];for(let o=e.length-1;o>=0;o--){for(;r.length>=2&&zn(r[r.length-2],r[r.length-1],e[o])<=0;)r.pop();r.push(e[o])}return r.pop(),t.pop(),t.concat(r)}(a)}(e),n=new yn(16);n.toBBox=function(e){return{minX:e[0],minY:e[1],maxX:e[0],maxY:e[1]}},n.compareMinX=function(e,t){return e[0]-t[0]},n.compareMinY=function(e,t){return e[1]-t[1]},n.load(e);const i=[];let a;for(let g=0;g<o.length;g++){const e=o[g];n.remove(e),a=Rn(e,a),i.push(a)}const s=new yn(16);for(let g=0;g<i.length;g++)s.insert(Nn(i[g]));const l=t*t,c=r*r;for(;i.length;){const e=i.shift(),t=e.p,r=e.next.p,o=Xn(t,r);if(o<c)continue;const a=o/l,u=Tn(n,e.prev.p,t,r,e.next.next.p,a,s);u&&Math.min(Xn(u,t),Xn(u,r))<=a&&(i.push(e),i.push(Rn(u,e)),n.remove(u),s.remove(e),s.insert(Nn(e)),s.insert(Nn(e.next)))}let u=a;const h=[];do{h.push(u.p),u=u.next}while(u!==a);return h.push(u.p),h}function Tn(e,t,r,o,n,i,a){const s=new An([],_n);let l=e.data;for(;l;){for(let e=0;e<l.children.length;e++){const t=l.children[e],n=l.leaf?Yn(t,r,o):Gn(r,o,t);n>i||s.push({node:t,dist:n})}for(;s.length&&!s.peek().node.children;){const e=s.pop(),i=e.node,l=Yn(i,t,r),c=Yn(i,o,n);if(e.dist<l&&e.dist<c&&Bn(r,i,a)&&Bn(o,i,a))return i}l=s.pop(),l&&(l=l.node)}return null}function _n(e,t){return e.dist-t.dist}function Gn(e,t,r){if(Hn(e,r)||Hn(t,r))return 0;const o=Vn(e[0],e[1],t[0],t[1],r.minX,r.minY,r.maxX,r.minY);if(0===o)return 0;const n=Vn(e[0],e[1],t[0],t[1],r.minX,r.minY,r.minX,r.maxY);if(0===n)return 0;const i=Vn(e[0],e[1],t[0],t[1],r.maxX,r.minY,r.maxX,r.maxY);if(0===i)return 0;const a=Vn(e[0],e[1],t[0],t[1],r.minX,r.maxY,r.maxX,r.maxY);return 0===a?0:Math.min(o,n,i,a)}function Hn(e,t){return e[0]>=t.minX&&e[0]<=t.maxX&&e[1]>=t.minY&&e[1]<=t.maxY}function Bn(e,t,r){const o=Math.min(e[0],t[0]),n=Math.min(e[1],t[1]),i=Math.max(e[0],t[0]),a=Math.max(e[1],t[1]),s=r.search({minX:o,minY:n,maxX:i,maxY:a});for(let l=0;l<s.length;l++)if(Un(s[l].p,s[l].next.p,e,t))return!1;return!0}function zn(e,t,r){return Rr(e[0],e[1],t[0],t[1],r[0],r[1])}function Un(e,t,r,o){return e!==o&&t!==r&&zn(e,t,r)>0!=zn(e,t,o)>0&&zn(r,o,e)>0!=zn(r,o,t)>0}function Nn(e){const t=e.p,r=e.next.p;return e.minX=Math.min(t[0],r[0]),e.minY=Math.min(t[1],r[1]),e.maxX=Math.max(t[0],r[0]),e.maxY=Math.max(t[1],r[1]),e}function Rn(e,t){const r={p:e,prev:null,next:null,minX:0,minY:0,maxX:0,maxY:0};return t?(r.next=t.next,r.prev=t,t.next.prev=r,t.next=r):(r.prev=r,r.next=r),r}function Xn(e,t){const r=e[0]-t[0],o=e[1]-t[1];return r*r+o*o}function Yn(e,t,r){let o=t[0],n=t[1],i=r[0]-o,a=r[1]-n;if(0!==i||0!==a){const t=((e[0]-o)*i+(e[1]-n)*a)/(i*i+a*a);t>1?(o=r[0],n=r[1]):t>0&&(o+=i*t,n+=a*t)}return i=e[0]-o,a=e[1]-n,i*i+a*a}function Vn(e,t,r,o,n,i,a,s){const l=r-e,c=o-t,u=a-n,h=s-i,g=e-n,d=t-i,p=l*l+c*c,f=l*u+c*h,y=u*u+h*h,m=l*g+c*d,v=u*g+h*d,M=p*y-f*f;let b,w,P=M,L=M;0===M?(b=0,P=1,w=v,L=y):(b=f*v-y*m,w=p*v-f*m,b<0?(b=0,w=v,L=y):b>P&&(b=P,w=v+f,L=y)),w<0?(w=0,-m<0?b=0:-m>p?b=P:(b=-m,P=p)):w>L&&(w=L,-m+f<0?b=0:-m+f>p?b=P:(b=-m+f,P=p));const k=0===b?0:b/P,x=0===w?0:w/L,E=(1-x)*n+x*a-((1-k)*e+k*r),S=(1-x)*i+x*s-((1-k)*t+k*o);return E*E+S*S}function qn(e,t){return e[0]===t[0]?e[1]-t[1]:e[0]-t[0]}const jn=()=>"ontouchstart"in window||navigator.maxTouchPoints>0;function Wn(){return"undefined"!=typeof vitest}class $n{static getBounds(e,t=0){const r=[];e.forEach(e=>{isNaN(e.lat)||isNaN(e.lng),r.push(e)});const o=new s.Polyline(r).getBounds();return 0!==t?o.pad(t):o}}class Kn{constructor(e=0,t=0,r=0,o=0){i(this,"direction",{East:new s.LatLng(0,0),North:new s.LatLng(0,0),NorthEast:new s.LatLng(0,0),NorthWest:new s.LatLng(0,0),South:new s.LatLng(0,0),SouthEast:new s.LatLng(0,0),SouthWest:new s.LatLng(0,0),West:new s.LatLng(0,0)}),this.direction.North=new s.LatLng(r,(t+o)/2),this.direction.NorthEast=new s.LatLng(r,o),this.direction.East=new s.LatLng((e+r)/2,o),this.direction.SouthEast=new s.LatLng(e,o),this.direction.South=new s.LatLng(e,(t+o)/2),this.direction.SouthWest=new s.LatLng(e,t),this.direction.West=new s.LatLng((e+r)/2,t),this.direction.NorthWest=new s.LatLng(r,t)}getDirection(e){switch(e){case u.SouthWest:return this.direction.SouthWest;case u.West:return this.direction.West;case u.NorthWest:return this.direction.NorthWest;case u.North:return this.direction.North;case u.NorthEast:return this.direction.NorthEast;case u.East:return this.direction.East;case u.SouthEast:return this.direction.SouthEast;case u.South:return this.direction.South;default:throw new Error}}getPositions(e=u.SouthWest,t=!1,r=!0){const o=[],n=this.getPositionAsArray(e,t);return n.forEach(e=>{o.push([e.lng,e.lat])}),r&&o.push([n[0].lng,n[0].lat]),o}getPositionAsArray(e=u.NorthEast,t=!1){const r=[];if(t?(r.push(this.direction.SouthWest),r.push(this.direction.West),r.push(this.direction.NorthWest),r.push(this.direction.North),r.push(this.direction.NorthEast),r.push(this.direction.East),r.push(this.direction.SouthEast),r.push(this.direction.South)):(r.push(this.direction.SouthWest),r.push(this.direction.South),r.push(this.direction.SouthEast),r.push(this.direction.East),r.push(this.direction.NorthEast),r.push(this.direction.North),r.push(this.direction.NorthWest),r.push(this.direction.West)),e!==u.SouthWest){r.splice(0,e).forEach((t,o)=>{r.splice(e+o,0,t)})}return r}}class Jn{constructor(e,t){if(i(this,"metricLength",""),i(this,"metricUnit",""),i(this,"imperialLength",""),i(this,"imperialUnit",""),null!==e||void 0!==e){0===e?t.markers.markerInfoIcon.usePerimeterMinValue?(this.metricLength=t.markers.markerInfoIcon.values.min.metric,this.metricUnit=t.markers.markerInfoIcon.units.metric.perimeter.m,this.imperialLength=t.markers.markerInfoIcon.values.min.imperial,this.imperialUnit=t.markers.markerInfoIcon.units.imperial.perimeter.feet):(this.metricLength=t.markers.markerInfoIcon.values.unknown.metric,this.metricUnit=t.markers.markerInfoIcon.units.unknownUnit,this.imperialLength=t.markers.markerInfoIcon.values.unknown.imperial,this.imperialUnit=t.markers.markerInfoIcon.units.unknownUnit):e<100?(this.metricLength=(10*Math.ceil(e/10)).toString(),this.metricUnit=t.markers.markerInfoIcon.units.metric.perimeter.m):e<500?(this.metricLength=(50*Math.ceil(e/50)).toString(),this.metricUnit=t.markers.markerInfoIcon.units.metric.perimeter.m):e<1e3?(this.metricLength=(100*Math.ceil(e/100)).toString(),this.metricUnit=t.markers.markerInfoIcon.units.metric.perimeter.m):e<1e4?(this.metricLength=(100*Math.ceil(e/100)/1e3).toFixed(1),this.metricUnit=t.markers.markerInfoIcon.units.metric.perimeter.km):(this.metricLength=(1e3*Math.ceil(e/1e3)/1e3).toString(),this.metricUnit=t.markers.markerInfoIcon.units.metric.perimeter.km);const r=e/.0254/12,o=r/3,n=o/1760;e<1e3/2.54?(this.imperialLength=(10*Math.ceil(r/10)).toString(),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.perimeter.feet):e<1e3/2.54*3?(this.imperialLength=(10*Math.ceil(o/10)).toString(),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.perimeter.yards):e<1609?(this.imperialLength=n.toFixed(2),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.perimeter.miles):e<16093?(this.imperialLength=n.toFixed(1),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.perimeter.miles):(this.imperialLength=n.toFixed(0),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.perimeter.miles)}}}class Zn{constructor(e,t){i(this,"metricArea",""),i(this,"metricUnit",""),i(this,"imperialArea",""),i(this,"imperialUnit","");const r=e,o=t.markers.markerInfoIcon.units.metric.onlyMetrics;if(null!==r||void 0!==r){0===r?(this.metricArea="-",this.metricUnit=t.markers.markerInfoIcon.units.unknownUnit,this.imperialArea="-",this.imperialUnit=t.markers.markerInfoIcon.units.unknownUnit):r<1e4?(this.metricArea=Math.round(r).toString(),this.metricUnit=t.markers.markerInfoIcon.units.metric.area.m2):r<1e5?o?(this.metricArea=(r/1e6).toFixed(2),this.metricUnit=t.markers.markerInfoIcon.units.metric.area.km2):(this.metricArea=(r/1e3).toFixed(1),this.metricUnit=t.markers.markerInfoIcon.units.metric.area.daa):r<1e7?o?(this.metricArea=(r/1e6).toFixed(2),this.metricUnit=t.markers.markerInfoIcon.units.metric.area.km2):(this.metricArea=Math.round(r/1e3).toString(),this.metricUnit=t.markers.markerInfoIcon.units.metric.area.daa):r<1e8?o?(this.metricArea=(r/1e6).toFixed(1),this.metricUnit=t.markers.markerInfoIcon.units.metric.area.km2):(this.metricArea=Math.round(r/1e4).toString(),this.metricUnit=t.markers.markerInfoIcon.units.metric.area.ha):(this.metricArea=Math.round(r/1e6).toString(),this.metricUnit=t.markers.markerInfoIcon.units.metric.area.km2);const e=.0069444*(1550*r),n=.11111*e,i=20661e-8*n,a=3.2283e-7*n;r<92.9?(this.imperialArea=Math.round(e).toString(),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.area.feet2):r<836.14?(this.imperialArea=n.toFixed(0),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.area.yards2):r<40469.6?(this.imperialArea=i.toFixed(2),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.area.acres):r<404696?(this.imperialArea=i.toFixed(1),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.area.acres):r<4046960?(this.imperialArea=i.toFixed(0),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.area.acres):r<25900404?(this.imperialArea=a.toFixed(2),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.area.miles2):r<259004040?(this.imperialArea=a.toFixed(1),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.area.miles2):(this.imperialArea=a.toFixed(0),this.imperialUnit=t.markers.markerInfoIcon.units.imperial.area.miles2)}}}function Qn(e,...t){if(!t.length)return e;for(const r of t)if(r)for(const t in r){const o=r[t],n=e[t];if(o&&"object"==typeof o&&!Array.isArray(o)){const r=n&&"object"==typeof n&&!Array.isArray(n)?n:{};e[t]=Qn(r,o)}else void 0!==o&&(e[t]=o)}return e}class ei{constructor(e){i(this,"config",g),i(this,"fallbackWarnings",new Set),this.config=Qn(structuredClone(g),e)}warnFallbackOnce(e,t){Wn()||this.fallbackWarnings.has(e)||(this.fallbackWarnings.add(e),console.warn(t))}toProjectedTolerance(e,t){if(e<=0)return 0;try{const r=d*y,o=e*r,n=Math.cos(t.lat*y);return 0===n?e:o/(r*n)}catch{return e}}getFeatureDiagonal(e){try{const[t,r,o,n]=k(e);return Math.hypot(o-t,n-r)}catch{return 0}}getRingDiagonal(e){if(!e||0===e.length)return 0;let t=e[0].lat,r=e[0].lat,o=e[0].lng,n=e[0].lng;for(const i of e)t=Math.min(t,i.lat),r=Math.max(r,i.lat),o=Math.min(o,i.lng),n=Math.max(n,i.lng);return Math.hypot(n-o,r-t)}getAdaptiveTolerance(e,t){if(e<=0)return 0;if(t<=0)return e;const r=.02*t;return Math.min(e,r)}union(e,t){try{const r=P([e,t]),o=zt(r);return o?this.getTurfPolygon(o):null}catch(r){return Wn()||console.warn("Error in union:",r instanceof Error?r.message:String(r)),null}}createPolygonFromTrace(e){var t;const r=null==(t=this.config.polygonCreation)?void 0:t.algorithm;void 0!==r&&"string"!=typeof r&&this.warnFallbackOnce("polygonCreation.algorithm.type",'[Leaflet.Polydraw] Invalid `polygonCreation.algorithm` type. Using "concaveman" as fallback.');const o="string"==typeof r?r:"concaveman";switch(o){case"concaveman":return this.turfConcaveman(e);case"convex":return this.createConvexPolygon(e);case"direct":return this.createDirectPolygon(e);case"buffer":return this.warnFallbackOnce("polygonCreation.algorithm.buffer",'[Leaflet.Polydraw] `polygonCreation.algorithm: "buffer"` is deprecated. Using "concaveman" as fallback.'),this.turfConcaveman(e);default:return this.warnFallbackOnce(`polygonCreation.algorithm.unknown:${o}`,`[Leaflet.Polydraw] Unknown polygon creation algorithm "${o}". Using "concaveman" as fallback.`),this.turfConcaveman(e)}}turfConcaveman(e){return w([[On(Vt(e).features.map(e=>e.geometry.coordinates))]])}createConvexPolygon(e){const t=Vt(e),r=ye(t);return r?this.getTurfPolygon(r):(this.warnFallbackOnce("polygonCreation.algorithm.convex.noHull",'[Leaflet.Polydraw] Convex hull generation failed. Using "direct" polygon creation as fallback.'),this.createDirectPolygon(e))}createDirectPolygon(e){let t;if("LineString"===e.geometry.type)t=e.geometry.coordinates;else if("Polygon"===e.geometry.type)t=e.geometry.coordinates[0];else{t=Vt(e).features.map(e=>e.geometry.coordinates)}if(t.length>0){const e=t[0],r=t[t.length-1];e[0]===r[0]&&e[1]===r[1]||t.push([e[0],e[1]])}return t.length<4?(Wn()||console.warn("Not enough points for direct polygon, falling back to concaveman"),this.turfConcaveman(e)):w([[t]])}getSimplified(e,t=!1){const r=this.resolveSimplificationConfig();if("none"===r.strategy)return e;if("simple"===r.strategy){const t=this.getAdaptiveTolerance(r.simple.tolerance,this.getFeatureDiagonal(e));return cr(e,{tolerance:this.toProjectedTolerance(t,this.getReferenceLatLng(e)),highQuality:r.simple.highQuality,mutate:!1})}const o=e.geometry.coordinates[0][0].length,n=r.dynamic.fractionGuard,i=r.dynamic.multiplier,a=this.getAdaptiveTolerance(r.dynamic.baseTolerance,this.getFeatureDiagonal(e)),s={highQuality:r.dynamic.highQuality,mutate:!1},l=t=>cr(e,{...s,tolerance:this.toProjectedTolerance(t,this.getReferenceLatLng(e))});if(!t)return l(a);let c=a,u=l(c);for(;u.geometry.coordinates[0][0].length>4&&u.geometry.coordinates[0][0].length/(o+2)>n;)c*=i,u=l(c);return u}simplifyLatLngRing(e,t,r=!0){var o,n;if(!e||0===e.length||t<=0)return e?[...e]:[];const i=[...e],a=i[0],s=i[i.length-1];s&&a&&s.lat===a.lat&&s.lng===a.lng||i.push({lat:a.lat,lng:a.lng});const l=i.map(e=>[e.lng,e.lat]),c=this.getAdaptiveTolerance(t,this.getRingDiagonal(i));try{const t=b([l]),i=cr(t,{tolerance:this.toProjectedTolerance(c,e[0]),highQuality:r,mutate:!1}),a=null==(n=null==(o=null==i?void 0:i.geometry)?void 0:o.coordinates)?void 0:n[0];return a&&0!==a.length?a.map(e=>({lat:e[1],lng:e[0]})):[...e]}catch(u){return Wn()||console.warn("Error simplifying ring:",u instanceof Error?u.message:String(u)),[...e]}}resolveSimplificationConfig(){const e=this.config.simplification,t=null==e?void 0:e.simple,r=null==e?void 0:e.dynamic,o=null==e?void 0:e.strategy,n=(e,t)=>"number"!=typeof e||!Number.isFinite(e)||e<0?(void 0!==e&&this.warnFallbackOnce(`simplification.invalidNumber:${String(e)}`,"[Leaflet.Polydraw] Invalid simplification numeric value. Using fallback default."),t):e,i=(e,t)=>"boolean"!=typeof e?(void 0!==e&&this.warnFallbackOnce(`simplification.invalidBoolean:${String(e)}`,"[Leaflet.Polydraw] Invalid simplification boolean value. Using fallback default."),t):e;let a="simple";"simple"===o||"dynamic"===o||"none"===o?a=o:void 0!==o&&this.warnFallbackOnce(`simplification.invalidStrategy:${String(o)}`,'[Leaflet.Polydraw] Invalid `simplification.strategy`. Using "simple" as fallback.');return{strategy:a,simple:{tolerance:n(null==t?void 0:t.tolerance,1e-4),highQuality:i(null==t?void 0:t.highQuality,!1)},dynamic:{baseTolerance:n(null==r?void 0:r.baseTolerance,1e-4),highQuality:i(null==r?void 0:r.highQuality,!1),fractionGuard:((e,t)=>"number"==typeof e&&Number.isFinite(e)?((e<0||e>1)&&this.warnFallbackOnce(`simplification.outOfRangeFraction:${e}`,"[Leaflet.Polydraw] `simplification.dynamic.fractionGuard` is out of range [0, 1]. Clamping to nearest valid value."),Math.max(0,Math.min(1,e))):(void 0!==e&&this.warnFallbackOnce(`simplification.invalidFraction:${String(e)}`,"[Leaflet.Polydraw] Invalid `simplification.dynamic.fractionGuard`. Using fallback default."),t))(null==r?void 0:r.fractionGuard,.9),multiplier:((e,t)=>"number"!=typeof e||!Number.isFinite(e)||e<=1?(void 0!==e&&this.warnFallbackOnce(`simplification.invalidMultiplier:${String(e)}`,"[Leaflet.Polydraw] Invalid `simplification.dynamic.multiplier` (must be > 1). Using fallback default."),t):e)(null==r?void 0:r.multiplier,2)}}}getTurfPolygon(e){let t;return t="Polygon"===e.geometry.type?w([e.geometry.coordinates]):w(e.geometry.coordinates),t}getMultiPolygon(e){return w(e)}getKinks(e){try{if(!e||!e.geometry||!e.geometry.coordinates)return[e];const t=this.removeDuplicateVertices(e);if(!t||!t.geometry||!t.geometry.coordinates)return Wn()||console.warn("Feature became invalid after cleaning in getKinks"),[e];if(this.polygonHasHoles(t))return this.getKinksWithHolePreservation(t);{const e=to(t),r=[];return Nt(e,e=>{r.push(e)}),r}}catch(t){return Wn()||console.warn("Error processing kinks:",t instanceof Error?t.message:String(t)),[e]}}getCoords(e){return L(e)}getReferenceLatLng(e){var t,r;try{const o=L(e),n=null==(r=null==(t=null==o?void 0:o[0])?void 0:t[0])?void 0:r[0];if(n&&Array.isArray(n)&&n.length>=2)return{lat:n[1],lng:n[0]}}catch{}return{lat:0,lng:0}}hasKinks(e){return hr(e).features.length>0}getConvexHull(e){try{const t=P([e]);return ye(t)}catch(t){return Wn()||console.warn("Error in getConvexHull:",t instanceof Error?t.message:String(t)),null}}getMidpoint(e,t){const r=E(v([e.lng,e.lat]),v([t.lng,t.lat]));return{lat:r.geometry.coordinates[1],lng:r.geometry.coordinates[0]}}polygonIntersect(e,t){try{if(!(e&&e.geometry&&e.geometry.coordinates&&t&&t.geometry&&t.geometry.coordinates))return Wn()||console.warn("Invalid features passed to polygonIntersect"),!1;const r=e=>{var t,r;return Array.isArray(null==(r=null==(t=e[0])?void 0:t[0])?void 0:r[0])},o=e=>{if(!Array.isArray(e))return!1;const t=r(e)?e.flat():e;for(const r of t){if(!Array.isArray(r))return!1;for(const e of r){if(!Array.isArray(e)||e.length<2)return!1;if(e.some(e=>null==e||!isFinite(e)))return!1}}return!0};if(!o(e.geometry.coordinates)||!o(t.geometry.coordinates))return!1;try{const r=P([e,t]),o=Rt(r);if(o&&o.geometry&&("Polygon"===o.geometry.type||"MultiPolygon"===o.geometry.type)){if(j(o)>1e-6)return!0}}catch{}try{const r=Vt(e),o=Vt(t);for(const t of o.features)if(Vr(t,e))return!0;for(const e of r.features)if(Vr(e,t))return!0}catch{}try{const r=L(e),o=L(t);for(const e of r){const t=e[0];if(t&&!(t.length<2))for(let e=0;e<t.length-1;e++){const r=t[e],n=t[e+1];if(!r||!n||!Array.isArray(r)||!Array.isArray(n)||r.length<2||n.length<2||r.some(e=>null==e||!isFinite(e))||n.some(e=>null==e||!isFinite(e)))continue;const i=M([r,n]);for(const e of o){const t=e[0];if(t&&!(t.length<2))for(let e=0;e<t.length-1;e++){const r=t[e],o=t[e+1];if(!r||!o||!Array.isArray(r)||!Array.isArray(o)||r.length<2||o.length<2||r.some(e=>null==e||!isFinite(e))||o.some(e=>null==e||!isFinite(e)))continue;const n=M([r,o]);try{const e=Be(i,n);if(e&&e.features&&e.features.length>0)return!0}catch{}}}}}}catch{}return!1}catch(r){return Wn()||console.warn("Error in polygonIntersect:",r instanceof Error?r.message:String(r)),!1}}getIntersection(e,t){try{const r=P([e,t]),o=Rt(r);return o&&o.geometry&&("Polygon"===o.geometry.type||"MultiPolygon"===o.geometry.type)?o:null}catch(r){return Wn()||console.warn("Error in getIntersection:",r instanceof Error?r.message:String(r)),null}}getDistance(e,t){return x(e,t)}isWithin(e,t){return zo(b([e]),b([t]))}isPolygonCompletelyWithin(e,t){try{return zo(e,t)}catch{const r=L(e),o=L(t);for(const e of r)for(const t of e)for(const e of t){const t=v(e);let r=!1;for(const e of o){for(const o of e){const e=b([o]);if(Vr(t,e)){r=!0;break}}if(r)break}if(!r)return!1}return!0}}toPointFeature(e){if((e=>{var t;if(!e||"object"!=typeof e)return!1;const r=e;return"Feature"===r.type&&"Point"===(null==(t=r.geometry)?void 0:t.type)})(e))return e;if(Array.isArray(e)&&e.length>=2&&"number"==typeof e[0]&&"number"==typeof e[1])return v(e);if((t=e)&&"object"==typeof t&&"number"==typeof t.lat&&"number"==typeof t.lng){const t=e;return v([t.lng,t.lat])}var t;if((e=>{if(!e||"object"!=typeof e)return!1;const t=e.geometry;return!!t&&Array.isArray(t.coordinates)})(e))return v(e.geometry.coordinates);throw new Error("Unsupported point format provided to toPointFeature")}isPointInsidePolygon(e,t){try{const r=this.toPointFeature(e);return Vr(r,t)}catch{return!1}}equalPolygons(e,t){return $o(e,t)}convertToBoundingBoxPolygon(e){const t=function(e){const[t,r,o,n]=e;return b([[[t,r],[o,r],[o,n],[t,n],[t,r]]])}(k(e));return t}polygonToMultiPolygon(e){return w([e.geometry.coordinates])}injectPointToPolygon(e,t,r){const o=JSON.parse(JSON.stringify(e));let n;if("MultiPolygon"===o.geometry.type)n=o.geometry.coordinates[0][r];else{if("Polygon"!==o.geometry.type)return o;n=o.geometry.coordinates[r]}if(!n)return o;let i=1/0,a=0;for(let s=0;s<n.length-1;s++){const e=n[s],r=n[s+1],o=this.distanceToLineSegment(t,e,r);o<i&&(i=o,a=s+1)}return n.splice(a,0,t),o}distanceToLineSegment(e,t,r){const o=e[0]-t[0],n=e[1]-t[1],i=r[0]-t[0],a=r[1]-t[1],s=o*i+n*a,l=i*i+a*a;if(0===l)return Math.sqrt(o*o+n*n);const c=s/l;let u,h;c<0?(u=t[0],h=t[1]):c>1?(u=r[0],h=r[1]):(u=t[0]+c*i,h=t[1]+c*a);const g=e[0]-u,d=e[1]-h;return Math.sqrt(g*g+d*d)}polygonDifference(e,t){try{const r=P([e,t]),o=Xt(r);return o?this.getTurfPolygon(o):null}catch(r){return Wn()||console.warn("Error in polygonDifference:",r instanceof Error?r.message:String(r)),null}}getBoundingBoxCompassPosition(e,t,r,o){return null}getNearestPointIndex(e,t){return an(e,t).properties.featureIndex??0}getCoord(e){return[e.lng,e.lat]}createPolygon(e){return b(e)}getFeaturePointCollection(e){const t=[];e.forEach(e=>{const r=v([e.lng,e.lat],{});t.push(r)});return P(t)}getPolygonArea(e){return j(e)}getPolygonPerimeter(e){return gn(e,{units:"kilometers"})}getCenterOfMass(e){return ke(e)}getDoubleElbowLatLngs(e){const t=[],r=e.length,o=e[0].lat===e[r-1].lat&&e[0].lng===e[r-1].lng?r-1:r;for(let n=0;n<o;n++){const r=e[n],i=e[(n+1)%o];t.push(new s.LatLng(r.lat,r.lng));const a=E(v([r.lng,r.lat]),v([i.lng,i.lat]));t.push(new s.LatLng(a.geometry.coordinates[1],a.geometry.coordinates[0]))}return t}getBezierMultiPolygon(e){const t=e=>{if(!e||0===e.length)return e;const t=e[0],r=e[e.length-1];return t[0]===r[0]&&t[1]===r[1]?e:[...e,[t[0],t[1]]]},r=e.map(e=>e.map(e=>{const r=t(e);try{const e=M(r),o=ln(e,{resolution:this.config.polygonTools.bezier.resolution,sharpness:this.config.polygonTools.bezier.sharpness}).geometry.coordinates??r,n=Math.max(2,r.length-1),i=Math.max(1,this.config.polygonTools.bezier.resampleMultiplier??10),a=Math.max(4,this.config.polygonTools.bezier.maxNodes??o.length),s=((e,r)=>{const o=t(e);if(!o||o.length<2)return o;const n=(e,t)=>{const r=e[0]-t[0],o=e[1]-t[1];return Math.sqrt(r*r+o*o)};let i=0;for(let t=1;t<o.length;t++)i+=n(o[t-1],o[t]);if(!Number.isFinite(i)||i<=0)return o;const a=i/Math.max(r,4),s=[o[0]];let l=0;for(let t=1;t<o.length;t++){let e=o[t-1];const r=o[t];let i=n(e,r);for(;l+i>=a&&i>0;){const t=(a-l)/i,o=[e[0]+(r[0]-e[0])*t,e[1]+(r[1]-e[1])*t];s.push(o),e=o,i=n(e,r),l=0}l+=i}return t(s)})(o,Math.max(4,Math.min(a,n*i))),l=(e=>{if(!e||0===e.length)return e;const r=1e-6,o=new Set,n=[];for(let t=0;t<e.length;t++){const i=e[t];if(!Array.isArray(i)||i.length<2)continue;const a=`${Math.round(i[0]/r)}:${Math.round(i[1]/r)}`;o.has(a)||(o.add(a),n.push(i))}return t(n)})(s);return l.length>=4?l:r}catch(o){return Wn()||console.warn("Bezier smoothing failed for ring, falling back to original:",o),r}}));return this.getMultiPolygon(r)}polygonHasHoles(e){try{return"Polygon"===e.geometry.type?e.geometry.coordinates.length>1:"MultiPolygon"===e.geometry.type&&e.geometry.coordinates.some(e=>e.length>1)}catch(t){return Wn()||console.warn("Error checking for holes:",t instanceof Error?t.message:String(t)),!1}}getKinksWithHolePreservation(e){try{if("Polygon"===e.geometry.type){const t=e.geometry.coordinates,r=t[0],o=t.slice(1),n={type:"Feature",geometry:{type:"Polygon",coordinates:[r]},properties:e.properties||{}},i=this.hasKinks(n),a=this.checkOuterRingHoleIntersection(r,o);if(i||a){if(this.checkIfDragCompletelyThroughHole(r,o))return this.handleCompleteHoleTraversal(n,o);const e=to(n),t=[];return Nt(e,e=>{const r=this.subtractIntersectingHoles(e,o);t.push(r)}),t}return[e]}if("MultiPolygon"===e.geometry.type){const t=[];for(const r of e.geometry.coordinates){const o={type:"Feature",geometry:{type:"Polygon",coordinates:r},properties:e.properties||{}},n=this.getKinksWithHolePreservation(o);t.push(...n)}return t}return[e]}catch(t){return Wn()||console.warn("Error in getKinksWithHolePreservation:",t instanceof Error?t.message:String(t)),[e]}}checkIfDragCompletelyThroughHole(e,t){try{if(this.findDuplicatePoints(e).length>0)return!0;const r=this.findSelfIntersectionLine(e);if(r&&t.length>0)for(const e of t)if(this.lineCompletelyTraversesHole(r,e))return!0;if(this.hasKinks({type:"Feature",geometry:{type:"Polygon",coordinates:[e]},properties:{}}))for(const o of t)if(this.holeIsCutByKinks(e,o))return!0;return!1}catch(r){return Wn()||console.warn("Error checking complete hole traversal:",r instanceof Error?r.message:String(r)),!1}}findSelfIntersectionLine(e){try{const t=new Map;for(let r=0;r<e.length-1;r++){const o=e[r],n=`${o[0]},${o[1]}`;t.has(n)?t.get(n).indices.push(r):t.set(n,{point:o,indices:[r]})}for(const[,r]of t)if(r.indices.length>=2){const t=r.indices[0],o=r.indices[1],n=[];for(let r=t;r<=o;r++)n.push(e[r]);return n}return null}catch(t){return Wn()||console.warn("Error finding self-intersection line:",t instanceof Error?t.message:String(t)),null}}lineCompletelyTraversesHole(e,t){try{if(e.length<2)return!1;const r=e[0],o=e[e.length-1],n=b([t]),i=Vr(v(r),n);return i!==Vr(v(o),n)}catch(r){return Wn()||console.warn("Error checking line hole traversal:",r instanceof Error?r.message:String(r)),!1}}holeIsCutByKinks(e,t){try{const r=b([e]),o=b([t]),n=hr(r);if(0===n.features.length)return!1;for(const e of n.features){const t=e.geometry.coordinates;try{if(x(v(t),S(o))<.01)return!0;if(Vr(v(t),o))return!0}catch{if(Vr(v(t),o))return!0}}return!1}catch(r){return Wn()||console.warn("Error checking hole cut by kinks:",r.message),!1}}findDuplicatePoints(e){const t=[],r=new Set;for(let o=0;o<e.length-1;o++){const n=e[o],i=`${n[0]},${n[1]}`;r.has(i)?t.push(n):r.add(i)}return t}checkOuterRingHoleIntersection(e,t){try{if(0===t.length)return!1;const r=b([e]);for(const o of t){const t=b([o]);if(this.getIntersection(r,t))return!0;for(let r=0;r<e.length-1;r++){const o=e[r];if(Vr(v(o),t))return!0}}return!1}catch{return!1}}handleCompleteHoleTraversal(e,t){try{const t={type:"Feature",geometry:{type:"Polygon",coordinates:[e.geometry.coordinates[0]]},properties:e.properties||{}},r=to(t),o=[];return Nt(r,e=>{e._polydrawHoleTraversalOccurred=!0,o.push(e)}),o}catch(r){Wn()||console.warn("Error handling complete hole traversal:",r instanceof Error?r.message:String(r));try{const t={...e,geometry:{...e.geometry,coordinates:[e.geometry.coordinates[0]]}};return t._polydrawHoleTraversalOccurred=!0,[t]}catch{return[e]}}}subtractIntersectingHoles(e,t){try{let r=e;for(const e of t){const t=b([e]);if(this.getIntersection(t,r)){const e=this.polygonDifference(r,t);if(e)if("Polygon"===e.geometry.type)r=e;else if("MultiPolygon"===e.geometry.type){const t=e;let o=0,n=null;for(const e of t.geometry.coordinates){const t={type:"Feature",geometry:{type:"Polygon",coordinates:e},properties:{}},r=j(t);r>o&&(o=r,n=t)}n&&(r=n)}}}return r}catch(r){return Wn()||console.warn("Error subtracting intersecting holes:",r instanceof Error?r.message:String(r)),e}}removeDuplicateVertices(e){if(!e||!e.geometry||!e.geometry.coordinates)return Wn()||console.warn("Invalid feature passed to removeDuplicateVertices"),e;const t=e=>{if(!e||e.length<3)return Wn()||console.warn("Invalid coordinates array - need at least 3 points for a polygon"),e||[];const t=[],r=1e-6,o=new Set;for(let n=0;n<e.length;n++){const i=e[n],a=e[(n+1)%e.length];if(!i||!Array.isArray(i)||i.length<2||!a||!Array.isArray(a)||a.length<2)continue;const s=Math.abs(i[1]-a[1]),l=Math.abs(i[0]-a[0]),c=`${Math.round(i[0]/r)}:${Math.round(i[1]/r)}`,u=o.has(c);(s>r||l>r)&&!u&&(t.push(i),o.add(c))}if(t.length<3)return Wn()||console.warn("After cleaning, polygon has less than 3 points"),e;if(t.length>0){const e=t[0],o=t[t.length-1],n=Math.abs(e[1]-o[1]),i=Math.abs(e[0]-o[0]);(n>r||i>r)&&t.push([e[0],e[1]])}return t};try{if("Polygon"===e.geometry.type){const r=e.geometry.coordinates.map(e=>t(e));return r.some(e=>e.length<4)?(Wn()||console.warn("Cleaned polygon has invalid ring with less than 4 coordinates"),e):{...e,geometry:{...e.geometry,coordinates:r}}}if("MultiPolygon"===e.geometry.type){const r=e.geometry.coordinates.map(e=>e.map(e=>t(e)));return r.some(e=>e.some(e=>e.length<4))?(Wn()||console.warn("Cleaned multipolygon has invalid ring with less than 4 coordinates"),e):{...e,geometry:{...e.geometry,coordinates:r}}}}catch(r){return Wn()||console.warn("Error in removeDuplicateVertices:",r instanceof Error?r.message:String(r)),e}return e}}const ti=()=>{if("undefined"!=typeof globalThis)return globalThis.L};class ri{static getVersion(){if(this._detectedVersion)return this._detectedVersion;const e=ti();return e?(this._detectedVersion=this.detectVersion(e),this._detectedVersion):l.V2}static detectVersion(e){const t=e??ti();if(!t)return l.V2;if(t.version){if(t.version.startsWith("2."))return l.V2;if(t.version.startsWith("1."))return l.V1}return"function"!=typeof t.marker?l.V2:"function"==typeof t.marker&&"function"==typeof t.polyline&&"function"==typeof t.polygon?l.V1:t.Marker&&"function"==typeof t.Marker&&t.Polyline&&"function"==typeof t.Polyline?l.V2:l.V1}static isV1(){return this.getVersion()===l.V1}static isV2(){return this.getVersion()===l.V2}static reset(){this._detectedVersion=null}static getVersionInfo(){const e=this.getVersion(),t=ti();return{version:e,leafletVersion:null==t?void 0:t.version,hasFactoryMethods:"function"==typeof(null==t?void 0:t.marker),hasConstructors:!!(null==t?void 0:t.Marker)&&"function"==typeof t.Marker,globalLAvailable:!!t}}}i(ri,"_detectedVersion",null);const oi=new class{constructor(){i(this,"domUtil",{create:(e,t,r)=>{if(void 0!==s&&s.DomUtil)return s.DomUtil.create(e,t,r);{const o=document.createElement(e);return t&&(o.className=t),r&&r.appendChild(o),o}},addClass:(e,t)=>{this.version===l.V1?s.DomUtil.addClass(e,t):e.classList.add(t)},removeClass:(e,t)=>{this.version===l.V1?s.DomUtil.removeClass(e,t):e.classList.remove(t)},hasClass:(e,t)=>this.version===l.V1?s.DomUtil.hasClass(e,t):e.classList.contains(t),setPosition:(e,t)=>{s.DomUtil.setPosition(e,t)},getPosition:e=>s.DomUtil.getPosition(e)}),i(this,"domEvent",{on:(e,t,r,o)=>(s.DomEvent.on(e,t,r,o),this),off:(e,t,r,o)=>(s.DomEvent.off(e,t,r,o),this),stopPropagation:e=>(s.DomEvent.stopPropagation(e),this),preventDefault:e=>(s.DomEvent.preventDefault(e),this),stop:e=>(s.DomEvent.stop(e),this),disableClickPropagation:e=>(s.DomEvent.disableClickPropagation(e),this),disableScrollPropagation:e=>(s.DomEvent.disableScrollPropagation(e),this),getMousePosition:(e,t)=>{if(this.version===l.V1)return s.DomEvent.getMousePosition(e,t);{const r=s.DomEvent;return r.getPointerPosition?r.getPointerPosition(e,t):s.DomEvent.getMousePosition(e,t)}}}),i(this,"util",{extend:(e,...t)=>this.version===l.V1?s.Util.extend(e,...t):Object.assign(e,...t),bind:(e,t)=>this.version===l.V1?s.Util.bind(e,t):e.bind(t),stamp:e=>s.Util.stamp(e),throttle:(e,t,r)=>s.Util.throttle(e,t,r),wrapNum:(e,t,r)=>s.Util.wrapNum(e,t,r),falseFn:()=>s.Util.falseFn(),formatNum:(e,t)=>s.Util.formatNum(e,t),trim:e=>this.version===l.V1?s.Util.trim(e):e.trim(),splitWords:e=>s.Util.splitWords(e),setOptions:(e,t)=>s.Util.setOptions(e,t),getParamString:(e,t,r)=>{if(this.version===l.V1)return s.Util.getParamString(e,t,r);{const o=new URLSearchParams;for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){const n=r?t.toUpperCase():t;o.set(n,String(e[t]))}const n=o.toString();if(t){const e=-1===t.indexOf("?")?"?":"&";return t+e+n}return n?"?"+n:""}},template:(e,t)=>s.Util.template(e,t),isArray:e=>this.version===l.V1?s.Util.isArray(e):Array.isArray(e),indexOf:(e,t)=>s.Util.indexOf(e,t),requestAnimFrame:(e,t,r)=>this.version===l.V1?s.Util.requestAnimFrame(e,t,r):requestAnimationFrame(t?e.bind(t):e),cancelAnimFrame:e=>{this.version===l.V1?s.Util.cancelAnimFrame(e):cancelAnimationFrame(e)}})}get version(){return ri.getVersion()}createTileLayer(e,t){return new s.TileLayer(e,t)}createMap(e,t){return new s.Map(e,t)}createMarker(e,t){return new s.Marker(e,t)}createPolyline(e,t){return new s.Polyline(e,t)}createPolygon(e,t){return new s.Polygon(e,t)}createDivIcon(e){return new s.DivIcon(e)}createLatLng(e,t,r){return new s.LatLng(e,t,r)}createLatLngBounds(e,t){return e&&t?new s.LatLngBounds(e,t):e?new s.LatLngBounds(e,e):new s.LatLngBounds([])}createPoint(e,t,r){return new s.Point(e,t,r)}createPopup(e,t){return new s.Popup(e,t)}createFeatureGroup(e){return new s.FeatureGroup(e)}createLayerGroup(e){return new s.LayerGroup(e)}getBrowser(){const e=this,t=s.Browser;return{get ie(){return e.version===l.V1&&s.Browser.ie},get ielt9(){return e.version===l.V1&&s.Browser.ielt9},get edge(){return e.version===l.V1&&s.Browser.edge},get webkit(){return e.version===l.V1&&s.Browser.webkit},get android(){return e.version===l.V1?s.Browser.android:/Android/.test(navigator.userAgent)},get android23(){return e.version===l.V1&&s.Browser.android23},get androidStock(){return e.version===l.V1&&s.Browser.androidStock},get opera(){return e.version===l.V1&&s.Browser.opera},get chrome(){return e.version===l.V1?s.Browser.chrome:/Chrome/.test(navigator.userAgent)},get gecko(){return e.version===l.V1&&s.Browser.gecko},get safari(){return e.version===l.V1?s.Browser.safari:/Safari/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)},get phantom(){return e.version===l.V1&&(t.phantom??!1)},get opera12(){return e.version===l.V1&&s.Browser.opera12},get win(){return e.version===l.V1?s.Browser.win:/Win/.test(navigator.platform)},get ie3d(){return e.version===l.V1&&s.Browser.ie3d},get webkit3d(){return e.version===l.V1&&s.Browser.webkit3d},get gecko3d(){return e.version===l.V1&&s.Browser.gecko3d},get any3d(){return e.version!==l.V1||s.Browser.any3d},get mobile(){return s.Browser.mobile},get mobileWebkit(){return e.version===l.V1&&s.Browser.mobileWebkit},get mobileWebkit3d(){return e.version===l.V1&&s.Browser.mobileWebkit3d},get msPointer(){return e.version===l.V1&&s.Browser.msPointer},get pointer(){return s.Browser.pointer||!0},get touch(){return s.Browser.touch},get touchNative(){return e.version===l.V1&&(t.touchNative??!1)},get mobileOpera(){return e.version===l.V1&&s.Browser.mobileOpera},get mobileGecko(){return e.version===l.V1&&s.Browser.mobileGecko},get retina(){return s.Browser.retina},get passiveEvents(){return e.version!==l.V1||(t.passiveEvents??!0)},get canvas(){return e.version!==l.V1||s.Browser.canvas},get svg(){return e.version!==l.V1||s.Browser.svg},get vml(){return e.version===l.V1&&s.Browser.vml},get inlineSvg(){return e.version!==l.V1||(t.inlineSvg??!0)}}}getVersion(){return this.version}isV1(){return this.version===l.V1}isV2(){return this.version===l.V2}};function ni(e,t){e.innerHTML=t;const r=e.querySelector("svg");r&&(!function(e){if(e.hasAttribute("viewBox"))return;const t=e.getAttribute("width"),r=e.getAttribute("height"),o=t?parseFloat(t):NaN,n=r?parseFloat(r):NaN;Number.isFinite(o)&&Number.isFinite(n)&&o>0&&n>0&&e.setAttribute("viewBox",`0 0 ${o} ${n}`)}(r),function(e){const t=Array.from(e.querySelectorAll("style"));if(0===t.length)return;const r=new Set;if(t.forEach(t=>{const o=t.textContent;if(!o)return void t.remove();const n=/([^{]+)\{([^}]*)\}/g;let i;for(;null!==(i=n.exec(o));){const t=i[1].split(",").map(e=>e.trim()).filter(Boolean),o=i[2];t.forEach(t=>{if(!t.startsWith("."))return;const n=t.slice(1);r.add(n),e.querySelectorAll(`.${n}`).forEach(e=>{o.split(";").forEach(t=>{const[r,o]=t.split(":");r&&o&&e.style.setProperty(r.trim(),o.trim())})})})}t.remove()}),0===r.size)return;e.querySelectorAll("[class]").forEach(e=>{const t=Array.from(e.classList).filter(e=>!r.has(e));t.length>0?e.setAttribute("class",t.join(" ")):e.removeAttribute("class")})}(r),r.setAttribute("width","24"),r.setAttribute("height","24"),r.style.pointerEvents="none",r.querySelectorAll("*").forEach(e=>{e.style.pointerEvents="none"}))}const ii='<?xml version="1.0" encoding="utf-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" id="Layer_1" x="0" y="0" style="enable-background:new 0 0 48 48" version="1.1" viewBox="0 0 48 48">\n <style>\n .st0{fill:#000}\n </style>\n <path d="M0 0h48v48H0z" style="fill:#333;fill-opacity:0"/>\n <path d="M26.6 10V7.8h-5.2V10h-8.8v2.8h22.8V10zM35.4 15.4H12.6v4.3h1.8V37c0 1.1.9 2 2 2h15.2c1.1 0 2-.9 2-2V19.7h1.8v-4.3zM19.7 34.2c0 .5-.4 1-1 1-.5 0-1-.4-1-1V22.6c0-.5.4-1 1-1 .5 0 1 .4 1 1v11.6zm5.6-.4c0 .7-.6 1.3-1.3 1.3-.7 0-1.3-.6-1.3-1.3V23c0-.7.6-1.3 1.3-1.3.7 0 1.3.6 1.3 1.3v10.8zm5 .4c0 .5-.4 1-1 1-.5 0-1-.4-1-1V22.6c0-.5.4-1 1-1 .5 0 1 .4 1 1v11.6z" class="st0"/>\n</svg>',ai={activate:'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" id="svg1" width="512" height="512" version="1.1">\n <path id="Shape" fill="#000" fill-rule="evenodd" stroke="none" d="M73.574 425.687c-1.14.188-4.099-.592-6.574-1.735-2.475-1.142-5.513-3.027-6.75-4.188C58 417.65 58 417.65 58 348.144c0-69.506 0-69.506 6.152-80.075a1599.57 1599.57 0 0 1 12.84-21.569c3.677-6.05 12.679-21.125 20.004-33.5 7.324-12.375 15.666-26.325 18.538-31 2.87-4.675 13.163-21.88 22.872-38.233a33686.921 33686.921 0 0 1 34.229-57.5c9.117-15.272 18.261-30.022 20.322-32.777 2.298-3.074 5.78-6.117 9.008-7.874 3.583-1.95 7.22-3.017 11.399-3.342 4.972-.388 7.445.018 13.04 2.137 3.799 1.439 10.999 4.919 16 7.733 5.003 2.814 13.371 7.613 18.596 10.663s13.775 8.134 19 11.297c5.225 3.163 12.061 7.246 15.192 9.073 3.13 1.828 9.402 5.521 13.936 8.208 4.535 2.686 10.397 6.897 13.027 9.357 3.265 3.054 5.457 6.261 6.912 10.115 1.672 4.43 2.036 7.161 1.694 12.704-.324 5.244-1.186 8.511-3.349 12.695-1.601 3.098-9.388 16.57-17.303 29.939-7.915 13.368-16.24 27.326-18.5 31.019a3087.099 3087.099 0 0 0-9.697 16c-3.073 5.107-11.2 18.736-18.061 30.286-6.86 11.55-16.45 27.75-21.312 36-4.86 8.25-11.179 18.825-14.04 23.5-2.862 4.675-8.308 13.83-12.101 20.343-3.794 6.513-10.508 17.762-14.92 24.997-7.721 12.664-8.263 13.29-14.5 16.77-3.563 1.987-15.357 8.416-26.21 14.286-10.851 5.87-28.851 15.66-40 21.756-11.147 6.096-25.86 14.032-32.694 17.638-6.834 3.605-13.359 6.709-14.5 6.897ZM116 376.754c2.096-.21 12.525-5.28 26-12.636 12.375-6.757 23.394-13.153 24.486-14.215 1.495-1.453 1.734-2.331.966-3.548-.56-.889-7.304-5.352-14.986-9.918-7.681-4.565-17.116-10.268-20.966-12.672-3.85-2.405-15.046-9.073-24.88-14.818-9.834-5.746-19.087-10.976-20.561-11.623-1.641-.72-3.24-.831-4.12-.287-.981.606-1.598 3.444-1.939 8.924-.275 4.42-.347 17.312-.16 28.65.341 20.616.341 20.616 3.5 23.908 1.738 1.81 9.01 6.733 16.16 10.94 10.754 6.327 13.605 7.587 16.5 7.295ZM184.98 329c.9 0 2.342-.563 3.204-1.25.86-.688 3.803-4.85 6.537-9.25 2.735-4.4 17.476-28.925 32.759-54.5 15.283-25.575 29.64-49.497 31.904-53.16 2.264-3.662 6.141-10.152 8.616-14.422 2.475-4.27 5.957-10.274 7.738-13.341 1.785-3.075 3.244-7.005 3.25-8.759.011-2.982-.694-3.614-11.238-10.077A2882.894 2882.894 0 0 0 249 152.847c-4.125-2.475-13.245-7.94-20.267-12.145a9841.507 9841.507 0 0 1-20.5-12.309 1566.199 1566.199 0 0 0-14.685-8.73c-3.823-2.238-8.13-4.242-9.57-4.453-1.998-.293-3.333.43-5.64 3.057-1.661 1.893-5.368 7.444-8.237 12.337a2040.256 2040.256 0 0 1-11.477 19.251 5775.594 5775.594 0 0 0-12.325 20.5A7048.542 7048.542 0 0 1 131.47 195c-4.823 7.975-10.898 18.1-13.501 22.5-2.604 4.4-8.45 14.075-12.991 21.5-4.542 7.425-10.268 16.988-12.725 21.252-3.26 5.657-4.304 8.405-3.861 10.168.454 1.81 4.239 4.57 15.1 11.01 7.973 4.726 20.686 12.257 28.252 16.735 7.566 4.477 17.582 10.485 22.257 13.351 4.675 2.866 13.19 7.973 18.921 11.348 5.732 3.375 11.158 6.136 12.059 6.136Zm100.681-194.022c2.318.016 3.852-.798 5.75-3.055 1.497-1.78 2.589-4.313 2.589-6.01 0-2.269-.848-3.508-3.75-5.478-2.063-1.4-6.53-4.29-9.927-6.421-3.398-2.132-9.923-6.015-14.5-8.63-4.578-2.614-10.798-6.408-13.823-8.43-3.025-2.022-7.75-4.873-10.5-6.334-2.75-1.462-8.15-4.689-12-7.171-5.023-3.24-7.838-4.434-9.968-4.232-2.1.2-3.65 1.298-5.297 3.75-1.437 2.14-2.215 4.588-2.032 6.391.254 2.498 1.604 3.72 9.297 8.412 4.95 3.02 15.525 9.427 23.5 14.238a3631.896 3631.896 0 0 1 26 15.848c7.807 4.82 12.515 7.107 14.661 7.122Z"/>\n <path id="path1" fill="#000" fill-rule="evenodd" stroke="none" d="M479.5 119.5c0 34 0 34-7 34.262-3.85.144-11.275.947-16.5 1.785s-12.533 2.42-16.24 3.514c-3.708 1.095-9.416 3.559-12.686 5.475-3.269 1.916-7.401 4.71-9.183 6.209-1.781 1.499-4.926 5.336-6.988 8.526-2.395 3.706-4.41 8.588-5.576 13.515-1.346 5.684-1.817 11.548-1.79 22.282.023 8.902.749 19.208 1.866 26.5 1.006 6.563 2.964 17.107 4.352 23.432 1.388 6.325 3.152 14.2 3.92 17.5.768 3.3 3.14 14.55 5.272 25s4.816 24.901 5.965 32.114c1.57 9.86 2.088 17.705 2.088 31.622 0 16.395-.284 19.635-2.485 28.386-1.367 5.433-4.299 13.56-6.515 18.061-2.832 5.75-6.265 10.559-11.545 16.172-5.308 5.642-10.516 9.846-17.735 14.316-5.62 3.481-13.145 7.611-16.72 9.179-3.575 1.567-10.739 4.4-15.92 6.293-5.181 1.894-13.506 4.308-18.5 5.365-4.994 1.056-13.58 2.637-19.08 3.513-6.633 1.057-18.754 1.716-36 1.958-14.3.201-30.5.01-36-.424s-15.625-1.537-22.5-2.45c-6.875-.912-16.575-2.328-21.557-3.146-4.98-.817-12.406-2.176-16.5-3.02-4.093-.843-9.693-2.157-12.443-2.92-2.75-.763-7.7-2.083-11-2.932-3.3-.85-10.5-2.648-16-3.996-5.5-1.348-15.85-4.3-23-6.56-7.15-2.261-14.912-4.805-17.25-5.653-2.904-1.055-4.25-2.127-4.25-3.386 0-1.228 3.252-3.97 9.75-8.22 5.363-3.507 13.202-8.277 17.421-10.6 7.671-4.225 7.671-4.225 18.5-1.287 5.956 1.616 19.154 4.998 29.329 7.515 10.175 2.517 23.45 5.465 29.5 6.55 6.05 1.087 15.05 2.427 20 2.98 4.95.552 14.85 1.53 22 2.175 8.107.73 21.657.955 36 .598 13.264-.33 27.021-1.234 32.5-2.135 5.225-.86 14-2.963 19.5-4.673s12.925-4.443 16.5-6.073a870.93 870.93 0 0 0 11.5-5.354c2.75-1.314 7.94-4.836 11.535-7.826 3.888-3.234 7.591-7.403 9.142-10.29 1.433-2.668 3.653-8.143 4.932-12.166 1.934-6.082 2.319-9.415 2.283-19.794-.024-7.149-.774-16.627-1.756-22.186-.943-5.339-2.407-13.531-3.253-18.206-.847-4.675-2.454-12.775-3.572-18-1.118-5.225-3.15-14-4.514-19.5-1.365-5.5-3.5-14.725-4.746-20.5-1.246-5.775-2.995-15-3.886-20.5-.892-5.5-2.081-14.08-2.643-19.068-.562-4.987-1.014-13.987-1.005-20 .01-6.012.652-14.799 1.427-19.525.775-4.726 2.12-11.026 2.988-14 .869-2.974 3.04-8.224 4.824-11.668 1.784-3.443 5.256-9.004 7.715-12.356 2.46-3.353 8.084-8.988 12.5-12.523 4.416-3.534 11.629-8.164 16.029-10.287 4.4-2.124 12.05-5.194 17-6.823 4.95-1.63 14.625-3.757 21.5-4.729s16.1-1.824 20.5-1.894l8-.127Z"/>\n <path id="path2" fill="#B6BCC4" fill-rule="evenodd" stroke="none" d="M116 375.743c-2.73.236-5.372-.8-12-4.708-4.675-2.756-11.133-6.704-14.35-8.773-3.218-2.07-6.48-4.977-7.25-6.462-1.094-2.111-1.4-8.348-1.4-28.56 0-21.125.267-26.213 1.461-27.799 1.43-1.9 1.574-1.879 6.75.986 2.909 1.61 8.214 4.584 11.789 6.61 3.575 2.026 9.1 5.209 12.28 7.073 3.179 1.865 10.253 6.09 15.722 9.39 5.468 3.3 13.836 8.245 18.596 10.989 4.76 2.744 10.736 6.348 13.279 8.01 2.568 1.678 4.753 3.927 4.917 5.062.246 1.716-3.42 4.101-23 14.96-14.766 8.189-24.575 13.03-26.794 13.222Z"/>\n <path id="path3" fill="#fff" fill-rule="evenodd" stroke="none" d="M185.256 329c-1.012 0-5.646-2.194-10.298-4.875-4.652-2.68-22.633-13.322-39.958-23.648-17.325-10.325-34.65-20.844-38.5-23.375-6.25-4.109-7.029-4.977-7.268-8.102-.202-2.632.816-5.36 4.106-11 2.407-4.125 21.576-36.075 42.6-71 21.022-34.925 39.47-65.075 40.994-67 2.195-2.772 3.589-3.562 6.699-3.797 3.477-.262 6.271 1.103 24.398 11.925 11.259 6.722 30.146 18.027 41.971 25.123 11.825 7.095 23.075 14.15 25 15.675 2.099 1.664 3.627 3.836 3.816 5.425.19 1.592-1.021 5.145-3.035 8.9-1.844 3.437-21.525 36.528-43.737 73.537-22.211 37.008-41.411 68.395-42.666 69.75-1.256 1.354-3.11 2.462-4.122 2.462Z"/>\n</svg>'.trim(),draw:'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" id="svg1" width="512" height="512" version="1.1">\n <path id="Shape" fill="#000" fill-rule="evenodd" stroke="none" d="M73.574 425.687c-1.14.188-4.099-.592-6.574-1.735-2.475-1.142-5.513-3.027-6.75-4.188C58 417.65 58 417.65 58 348.144c0-69.506 0-69.506 6.152-80.075a1599.57 1599.57 0 0 1 12.84-21.569c3.677-6.05 12.679-21.125 20.004-33.5 7.324-12.375 15.666-26.325 18.538-31 2.87-4.675 13.163-21.88 22.872-38.233a33686.921 33686.921 0 0 1 34.229-57.5c9.117-15.272 18.261-30.022 20.322-32.777 2.298-3.074 5.78-6.117 9.008-7.874 3.583-1.95 7.22-3.017 11.399-3.342 4.972-.388 7.445.018 13.04 2.137 3.799 1.439 10.999 4.919 16 7.733 5.003 2.814 13.371 7.613 18.596 10.663s13.775 8.134 19 11.297c5.225 3.163 12.061 7.246 15.192 9.073 3.13 1.828 9.402 5.521 13.936 8.208 4.535 2.686 10.397 6.897 13.027 9.357 3.265 3.054 5.457 6.261 6.912 10.115 1.672 4.43 2.036 7.161 1.694 12.704-.324 5.244-1.186 8.511-3.349 12.695-1.601 3.098-9.388 16.57-17.303 29.939-7.915 13.368-16.24 27.326-18.5 31.019a3087.099 3087.099 0 0 0-9.697 16c-3.073 5.107-11.2 18.736-18.061 30.286-6.86 11.55-16.45 27.75-21.312 36-4.86 8.25-11.179 18.825-14.04 23.5-2.862 4.675-8.308 13.83-12.101 20.343-3.794 6.513-10.508 17.762-14.92 24.997-7.721 12.664-8.263 13.29-14.5 16.77-3.563 1.987-15.357 8.416-26.21 14.286-10.851 5.87-28.851 15.66-40 21.756-11.147 6.096-25.86 14.032-32.694 17.638-6.834 3.605-13.359 6.709-14.5 6.897ZM116 376.754c2.096-.21 12.525-5.28 26-12.636 12.375-6.757 23.394-13.153 24.486-14.215 1.495-1.453 1.734-2.331.966-3.548-.56-.889-7.304-5.352-14.986-9.918-7.681-4.565-17.116-10.268-20.966-12.672-3.85-2.405-15.046-9.073-24.88-14.818-9.834-5.746-19.087-10.976-20.561-11.623-1.641-.72-3.24-.831-4.12-.287-.981.606-1.598 3.444-1.939 8.924-.275 4.42-.347 17.312-.16 28.65.341 20.616.341 20.616 3.5 23.908 1.738 1.81 9.01 6.733 16.16 10.94 10.754 6.327 13.605 7.587 16.5 7.295ZM184.98 329c.9 0 2.342-.563 3.204-1.25.86-.688 3.803-4.85 6.537-9.25 2.735-4.4 17.476-28.925 32.759-54.5 15.283-25.575 29.64-49.497 31.904-53.16 2.264-3.662 6.141-10.152 8.616-14.422 2.475-4.27 5.957-10.274 7.738-13.341 1.785-3.075 3.244-7.005 3.25-8.759.011-2.982-.694-3.614-11.238-10.077A2882.894 2882.894 0 0 0 249 152.847c-4.125-2.475-13.245-7.94-20.267-12.145a9841.507 9841.507 0 0 1-20.5-12.309 1566.199 1566.199 0 0 0-14.685-8.73c-3.823-2.238-8.13-4.242-9.57-4.453-1.998-.293-3.333.43-5.64 3.057-1.661 1.893-5.368 7.444-8.237 12.337a2040.256 2040.256 0 0 1-11.477 19.251 5775.594 5775.594 0 0 0-12.325 20.5A7048.542 7048.542 0 0 1 131.47 195c-4.823 7.975-10.898 18.1-13.501 22.5-2.604 4.4-8.45 14.075-12.991 21.5-4.542 7.425-10.268 16.988-12.725 21.252-3.26 5.657-4.304 8.405-3.861 10.168.454 1.81 4.239 4.57 15.1 11.01 7.973 4.726 20.686 12.257 28.252 16.735 7.566 4.477 17.582 10.485 22.257 13.351 4.675 2.866 13.19 7.973 18.921 11.348 5.732 3.375 11.158 6.136 12.059 6.136Zm100.681-194.022c2.318.016 3.852-.798 5.75-3.055 1.497-1.78 2.589-4.313 2.589-6.01 0-2.269-.848-3.508-3.75-5.478-2.063-1.4-6.53-4.29-9.927-6.421-3.398-2.132-9.923-6.015-14.5-8.63-4.578-2.614-10.798-6.408-13.823-8.43-3.025-2.022-7.75-4.873-10.5-6.334-2.75-1.462-8.15-4.689-12-7.171-5.023-3.24-7.838-4.434-9.968-4.232-2.1.2-3.65 1.298-5.297 3.75-1.437 2.14-2.215 4.588-2.032 6.391.254 2.498 1.604 3.72 9.297 8.412 4.95 3.02 15.525 9.427 23.5 14.238a3631.896 3631.896 0 0 1 26 15.848c7.807 4.82 12.515 7.107 14.661 7.122Z" style="stroke:#000;stroke-opacity:1;stroke-width:20;stroke-dasharray:none"/>\n <path id="path1" fill="#000" fill-rule="evenodd" stroke="none" d="M479.5 119.5c0 34 0 34-7 34.262-3.85.144-11.275.947-16.5 1.785s-12.533 2.42-16.24 3.514c-3.708 1.095-9.416 3.559-12.686 5.475-3.269 1.916-7.401 4.71-9.183 6.209-1.781 1.499-4.926 5.336-6.988 8.526-2.395 3.706-4.41 8.588-5.576 13.515-1.346 5.684-1.817 11.548-1.79 22.282.023 8.902.749 19.208 1.866 26.5 1.006 6.563 2.964 17.107 4.352 23.432 1.388 6.325 3.152 14.2 3.92 17.5.768 3.3 3.14 14.55 5.272 25s4.816 24.901 5.965 32.114c1.57 9.86 2.088 17.705 2.088 31.622 0 16.395-.284 19.635-2.485 28.386-1.367 5.433-4.299 13.56-6.515 18.061-2.832 5.75-6.265 10.559-11.545 16.172-5.308 5.642-10.516 9.846-17.735 14.316-5.62 3.481-13.145 7.611-16.72 9.179-3.575 1.567-10.739 4.4-15.92 6.293-5.181 1.894-13.506 4.308-18.5 5.365-4.994 1.056-13.58 2.637-19.08 3.513-6.633 1.057-18.754 1.716-36 1.958-14.3.201-30.5.01-36-.424s-15.625-1.537-22.5-2.45c-6.875-.912-16.575-2.328-21.557-3.146-4.98-.817-12.406-2.176-16.5-3.02-4.093-.843-9.693-2.157-12.443-2.92-2.75-.763-7.7-2.083-11-2.932-3.3-.85-10.5-2.648-16-3.996-5.5-1.348-15.85-4.3-23-6.56-7.15-2.261-14.912-4.805-17.25-5.653-2.904-1.055-4.25-2.127-4.25-3.386 0-1.228 3.252-3.97 9.75-8.22 5.363-3.507 13.202-8.277 17.421-10.6 7.671-4.225 7.671-4.225 18.5-1.287 5.956 1.616 19.154 4.998 29.329 7.515 10.175 2.517 23.45 5.465 29.5 6.55 6.05 1.087 15.05 2.427 20 2.98 4.95.552 14.85 1.53 22 2.175 8.107.73 21.657.955 36 .598 13.264-.33 27.021-1.234 32.5-2.135 5.225-.86 14-2.963 19.5-4.673s12.925-4.443 16.5-6.073a870.93 870.93 0 0 0 11.5-5.354c2.75-1.314 7.94-4.836 11.535-7.826 3.888-3.234 7.591-7.403 9.142-10.29 1.433-2.668 3.653-8.143 4.932-12.166 1.934-6.082 2.319-9.415 2.283-19.794-.024-7.149-.774-16.627-1.756-22.186-.943-5.339-2.407-13.531-3.253-18.206-.847-4.675-2.454-12.775-3.572-18-1.118-5.225-3.15-14-4.514-19.5-1.365-5.5-3.5-14.725-4.746-20.5-1.246-5.775-2.995-15-3.886-20.5-.892-5.5-2.081-14.08-2.643-19.068-.562-4.987-1.014-13.987-1.005-20 .01-6.012.652-14.799 1.427-19.525.775-4.726 2.12-11.026 2.988-14 .869-2.974 3.04-8.224 4.824-11.668 1.784-3.443 5.256-9.004 7.715-12.356 2.46-3.353 8.084-8.988 12.5-12.523 4.416-3.534 11.629-8.164 16.029-10.287 4.4-2.124 12.05-5.194 17-6.823 4.95-1.63 14.625-3.757 21.5-4.729s16.1-1.824 20.5-1.894l8-.127Z"/>\n <path id="path2" fill="#B6BCC4" fill-rule="evenodd" stroke="none" d="M116 375.743c-2.73.236-5.372-.8-12-4.708-4.675-2.756-11.133-6.704-14.35-8.773-3.218-2.07-6.48-4.977-7.25-6.462-1.094-2.111-1.4-8.348-1.4-28.56 0-21.125.267-26.213 1.461-27.799 1.43-1.9 1.574-1.879 6.75.986 2.909 1.61 8.214 4.584 11.789 6.61 3.575 2.026 9.1 5.209 12.28 7.073 3.179 1.865 10.253 6.09 15.722 9.39 5.468 3.3 13.836 8.245 18.596 10.989 4.76 2.744 10.736 6.348 13.279 8.01 2.568 1.678 4.753 3.927 4.917 5.062.246 1.716-3.42 4.101-23 14.96-14.766 8.189-24.575 13.03-26.794 13.222Z"/>\n</svg>'.trim(),subtract:'<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path fill-rule="evenodd" clip-rule="evenodd" d="M15.0722 3.9967L20.7508 9.83395L17.0544 13.5304L13.0758 17.5H21.0041V19H7.93503L4.00195 15.0669L15.0722 3.9967ZM10.952 17.5L15.4628 12.9994L11.8268 9.3634L6.12327 15.0669L8.55635 17.5H10.952Z" fill="#1F2328"></path> </g></svg>\n'.trim(),clone:'<?xml version="1.0" encoding="UTF-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">\n <rect x="88" y="88" width="252" height="252" fill="none" stroke="#000" stroke-width="42"/>\n <rect x="172" y="172" width="252" height="252" fill="none" stroke="#000" stroke-width="42"/>\n</svg>'.trim(),p2p:'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" id="svg1" width="512" height="512" version="1.1">\n <path id="path7" d="m155.327 480.616 323.962-.033V45.207L32.68 44.87l.24 35.605 411.103-.882-.338 365.995-169.126-.577Z" style="fill:#000;fill-opacity:1;stroke:none;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n <circle id="path8" cx="460.396" cy="461.547" r="39.134" style="fill:#000;fill-opacity:1;stroke:none;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n <circle id="path8-8" cx="460.775" cy="65.834" r="39.134" style="fill:#000;fill-opacity:1;stroke:none;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n <circle id="path8-8-0" cx="67.176" cy="62.815" r="39.134" style="fill:#000;fill-opacity:1;stroke:none;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n <path id="path2" fill="#000" fill-rule="evenodd" stroke="none" d="M78.983 469.63c-2.155.594-4.661-.186-6.416-1.995-1.755-1.81-2.512-4.396-1.937-6.616.52-2.005 2.036-7.54 3.369-12.298 1.333-4.76 4.302-15.274 6.598-23.365 2.295-8.09 6.159-21.33 8.585-29.421a5326.7 5326.7 0 0 0 9.458-32.018c2.775-9.519 6.848-23.538 9.05-31.153a3424.585 3424.585 0 0 1 8.424-28.556c2.432-8.09 5.74-19.445 7.35-25.23 1.61-5.786 4.963-13.271 7.45-16.634 3.196-4.319 8.828-8.134 19.19-12.998 8.067-3.787 22.221-10.287 31.454-14.445 9.232-4.158 20.186-9.16 24.34-11.116a766.22 766.22 0 0 1 15.108-6.874c4.154-1.824 8.5-4.181 9.657-5.238 1.675-1.53 1.537-3.405-.681-9.226-2.27-5.96-2.436-8.498-.898-13.779 1.221-4.19 5.936-10.614 13.373-18.217 6.772-6.923 13.882-12.502 17.322-13.59 4.562-1.444 7.103-1.28 11.648.752 3.426 1.532 23.389 20.759 48.618 46.826 23.543 24.325 45.072 47.061 47.841 50.525 3.873 4.843 5.036 8.022 5.036 13.76 0 6.664-.988 8.548-9.232 17.594-5.078 5.572-11.81 12.267-14.959 14.876-4.16 3.448-7.614 4.745-12.635 4.745-3.801 0-8.653-1.259-10.783-2.797-2.18-1.574-4.506-2.141-5.322-1.298-.797.824-5.186 10.455-9.754 21.402a5146.966 5146.966 0 0 1-15.335 36.316c-3.866 9.027-10.026 22.886-13.689 30.798-4.617 9.975-8.217 15.361-11.743 17.572-2.796 1.753-10.879 5.156-17.961 7.562-7.083 2.406-20.431 6.749-29.664 9.65-9.232 2.902-25.661 8.033-36.509 11.403-10.847 3.37-31.242 9.76-45.323 14.201-14.08 4.44-32.777 10.286-41.547 12.99-8.771 2.704-17.539 5.355-19.483 5.892zm33.106-25.66c3.124-.525 14.558-3.756 25.407-7.18 10.85-3.424 33.511-10.53 50.36-15.791a27689.101 27689.101 0 0 1 50.776-15.803c14.114-4.37 21.467-7.596 24.568-10.778 2.433-2.497 8.003-13.108 12.378-23.578 4.374-10.471 10.397-24.88 13.384-32.018 2.987-7.14 8.327-19.6 11.866-27.691 3.54-8.091 6.71-17.047 7.046-19.903.555-4.717-2.161-8.042-29.692-36.345-16.667-17.133-31.78-31.396-33.584-31.694-1.804-.298-24.636 9.269-50.737 21.259-26.102 11.99-49.09 23.383-51.087 25.316-1.997 1.934-4.862 7.745-6.369 12.914a7969.157 7969.157 0 0 0-7.086 24.55 5161.998 5161.998 0 0 1-9.204 31.594c-2.67 9.043-9.076 30.85-14.234 48.46-5.158 17.609-10.028 34.72-10.822 38.026-.794 3.304-1.129 6.334-.743 6.731.385.397 3.176-1.24 6.202-3.637 3.026-2.397 17.965-17.532 33.199-33.633 15.233-16.1 31.64-33.573 36.46-38.83 8.522-9.292 8.717-9.73 7.063-15.905-1.163-4.344-1.143-8.487.066-13.114 1.094-4.191 4.275-9.1 8.364-12.909 3.648-3.398 9.265-6.662 12.561-7.3 4.51-.872 7.9-.158 13.92 2.932 4.845 2.486 9.223 6.36 11.188 9.9 1.776 3.2 3.3 9.202 3.385 13.339.09 4.285-1.167 10.058-2.921 13.416-1.693 3.242-6.11 7.651-9.814 9.798-5.669 3.285-8.24 3.73-16.226 2.804-9.49-1.099-9.49-1.099-49.778 40.478-22.158 22.867-40.577 42.47-40.932 43.56-.438 1.349 1.175 1.679 5.036 1.031zm90.33-98.225c3.355 0 6.06-1.502 8.524-4.733 2.602-3.409 3.338-6.138 2.634-9.765-.537-2.768-2.295-6.065-3.908-7.327-1.612-1.262-5.138-2.32-7.835-2.35-2.697-.03-6.285 1.234-7.974 2.81-1.808 1.687-3.07 5.242-3.07 8.653 0 3.481 1.339 7.169 3.358 9.25 1.846 1.904 5.568 3.462 8.271 3.462zm133.61-53.652c1.976 0 7.955-4.72 14.175-11.19 10.066-10.471 10.62-11.455 8.624-15.3-1.174-2.262-22.067-24.651-46.43-49.755-28.883-29.764-45.482-45.645-47.707-45.645-1.918 0-7.85 4.523-13.542 10.323-7.359 7.498-9.997 11.39-9.645 14.229.303 2.438 17.518 21.468 45.796 50.622 29.62 30.538 46.495 46.716 48.73 46.716z" style="stroke:#010101;stroke-width:17.0446;stroke-dasharray:none;stroke-opacity:1"/>\n <path id="path3" d="m243.547 189.376 16.458-15.442 96.745 96.717-16.459 16.256z" style="fill:green;fill-opacity:1;stroke:none;stroke-width:18.6862;stroke-dasharray:none;stroke-opacity:1"/>\n <circle id="path9" cx="201.178" cy="332.215" r="13.593" style="fill:#fff;fill-opacity:1;stroke:none;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n</svg>'.trim(),p2pSubtract:'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" id="svg1" width="512" height="512" version="1.1">\n <path id="path2" fill="#000" fill-rule="evenodd" stroke="none" d="M193.812 478.594c-90.053.005-55.415-.21-62.995-.883-3.109-.277-27.11-21.644-46.82-41.478-19.71-19.834-38.405-39.3-41.545-43.255-3.14-3.957-6.62-10.716-7.734-15.02-1.731-6.696-1.64-9.153.633-17.007 2.63-9.085 3.646-10.163 97.355-103.187 67.82-67.324 96.742-95.006 101.9-97.53 4.693-2.298 10.024-3.498 15.308-3.447 5.932.057 10.337 1.334 16.417 4.757 5.373 3.027 23.906 20.087 52.456 48.29 24.281 23.987 46.739 47.413 49.906 52.058 4.533 6.648 5.893 10.36 6.393 17.444.536 7.598-.072 10.288-3.907 17.275-3.191 5.814-24.3 28.163-70.958 75.126-36.529 36.767-66.373 67.623-66.926 68.174-19.83 19.71-39.71 38.183-39.483 38.683zm84.581-137.331c-68.043-67.49-88.703-86.892-89.81-86.657-1.106.234-27.946 26.117-59.643 57.517-31.698 31.4-57.439 57.94-57.202 58.977.236 1.037 15.757 17.272 34.492 36.078 34.062 34.193 34.062 34.193 53.6 34.193 19.536 0 19.536 0 55.274-35.285 19.656-19.407 41.937-41.932 49.514-50.054zm60.94-60.024c-66.9-66.62-87.289-86.356-88.469-86.837-1.29-.527-8.787 5.684-18.813 15.585l-16.668 16.46 44.408 44.028c24.425 24.215 44.787 44.027 45.249 44.027.461 0 8.366-7.484 17.566-16.632z" style="stroke-width:1.5931"/>\n <path id="path3" d="m214.604 225.766 35.345-32.835 89.308 87.873-34.083 33.773z" style="fill:maroon;fill-opacity:1;stroke:#010101;stroke-width:7.48758"/>\n <path id="path7" d="m238.705 480.616 240.584-.033V45.207L32.68 44.87l.24 35.605 411.103-.882-.338 365.995-169.126-.577Z" style="fill:#000;fill-opacity:1;stroke:none;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n <circle id="path8" cx="460.396" cy="461.547" r="39.134" style="fill:#000;fill-opacity:1;stroke:none;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n <circle id="path8-8" cx="460.775" cy="65.834" r="39.134" style="fill:#000;fill-opacity:1;stroke:none;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n <circle id="path8-8-0" cx="67.176" cy="62.815" r="39.134" style="fill:#000;fill-opacity:1;stroke:none;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n</svg>'.trim(),erase:ii.trim(),collapse:'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512">\n <path d="m80.033 292.15 175.755-174.592 175.755 174.591" style="fill:none;stroke:#000;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n <path d="M80.105 394.539 255.86 219.947 431.615 394.54" style="fill:none;stroke:#000;stroke-width:35;stroke-dasharray:none;stroke-opacity:1"/>\n</svg>'.trim(),undo:'<?xml version="1.0" encoding="utf-8"?>\n<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 48 48" xml:space="preserve">\n<style type="text/css">\n\t.st0{fill:none;stroke:#000000;stroke-width:3;stroke-linecap:round;stroke-linejoin:round;}\n</style>\n<g>\n\t<path class="st0" d="M14,18h10c6.6,0,12,5.4,12,12s-5.4,12-12,12s-12-5.4-12-12"/>\n\t<polyline class="st0" points="18,14 14,18 18,22"/>\n</g>\n</svg>\n'.trim(),redo:'<?xml version="1.0" encoding="utf-8"?>\n<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 48 48" xml:space="preserve">\n<style type="text/css">\n\t.st0{fill:none;stroke:#000000;stroke-width:3;stroke-linecap:round;stroke-linejoin:round;}\n</style>\n<g>\n\t<path class="st0" d="M34,18H24C17.4,18,12,23.4,12,30s5.4,12,12,12s12-5.4,12-12"/>\n\t<polyline class="st0" points="30,14 34,18 30,22"/>\n</g>\n</svg>\n'.trim()},si=(e,t)=>{ni(e,t)},li=(e,t)=>{e.setAttribute("data-tooltip",t),e.setAttribute("aria-label",t)};class ci{static getCenter(e){let t=0,r=0,o=0;e.forEach(e=>{let n=e.lat,i=e.lng;n*=y,i*=y,t+=Math.cos(n)*Math.cos(i),r+=Math.cos(n)*Math.sin(i),o+=Math.sin(n)});let n=Math.atan2(r,t);const i=Math.sqrt(t*t+r*r);let a=Math.atan2(o,i);a*=m,n*=m;return{lat:a,lng:n}}static getSouthWest(e){return this.getBounds(e).getSouthWest()}static getNorthEast(e){return this.getBounds(e).getNorthEast()}static getNorthWest(e){return this.getBounds(e).getNorthWest()}static getSouthEast(e){return this.getBounds(e).getSouthEast()}static getNorth(e){return this.getBounds(e).getNorth()}static getSouth(e){return this.getBounds(e).getSouth()}static getWest(e){return this.getBounds(e).getWest()}static getEast(e){return this.getBounds(e).getEast()}static getSqmArea(e){const t=new s.Polygon(e).toGeoJSON();return this.turfHelper.getPolygonArea(t)}static getPerimeter(e){const t=new s.Polygon(e).toGeoJSON();return 1e3*this.turfHelper.getPolygonPerimeter(t)}static getPolygonChecksum(e){const t=e.filter((e,t,r)=>{const o=r.find(t=>t.lat===e.lat&&t.lng===e.lng);return!!o&&r.indexOf(o)===t});return t.reduce((e,t)=>+e+ +t.lat,0)*t.reduce((e,t)=>+e+ +t.lng,0)}static getMidPoint(e,t){const r=this.turfHelper.getMidpoint(e,t);return{lat:r.lat,lng:r.lng}}static getBounds(e){const t=[];e.forEach(e=>{isNaN(e.lat)||isNaN(e.lng),t.push(e)});return new s.Polyline(t).getBounds()}static getCenterOfMass(e){const t=this.turfHelper.getCenterOfMass(e);return{lat:t.geometry.coordinates[1],lng:t.geometry.coordinates[0]}}static getCenterOfPolygonByIndexWithOffsetFromCenterOfMass(e,t){const r=this.turfHelper.getCenterOfMass(e),o={lat:r.geometry.coordinates[1],lng:r.geometry.coordinates[0]},n=this.getPolygonLatLngAtIndex(e,t)??o,i=n.lat-o.lat,a=n.lng-o.lng,s={geometry:{coordinates:[o.lng+.5*a,o.lat+.5*i]}};return{lat:s.geometry.coordinates[1],lng:s.geometry.coordinates[0]}}static getPolygonLatLngAtIndex(e,t){const r=e.geometry;if(!r)return null;let o;if("Polygon"===r.type)o=r.coordinates[0];else{if("MultiPolygon"!==r.type)return null;o=r.coordinates[0][0]}if(!o||0===o.length)return null;if(o.length>1){const e=o[0],t=o[o.length-1];e[0]===t[0]&&e[1]===t[1]&&(o=o.slice(0,o.length-1))}if(0===o.length)return null;const n=o[(t%o.length+o.length)%o.length];return{lat:n[1],lng:n[0]}}}i(ci,"turfHelper",new ei(g));class ui{constructor(e){if(i(this,"polygon",[]),i(this,"trashcanPoint",[]),i(this,"sqmArea",[]),i(this,"perimeter",[]),!Array.isArray(e))return;if(e.length>0&&Array.isArray(e[0])&&e[0].length>0&&"object"==typeof e[0][0]&&"lat"in e[0][0]){const t=e[0];return this.trashcanPoint[0]=this.getTrashcanPoint(t),this.sqmArea[0]=this.calculatePolygonArea(t),this.perimeter[0]=this.calculatePolygonPerimeter(t),void(this.polygon[0]=[t])}if(e.length>0&&e[0]&&"object"==typeof e[0]&&"lat"in e[0]){const t=e,r=[[t]];return this.trashcanPoint[0]=this.getTrashcanPoint(t),this.sqmArea[0]=this.calculatePolygonArea(t),this.perimeter[0]=this.calculatePolygonPerimeter(t),void(this.polygon[0]=r[0])}e.forEach((e,t)=>{e&&Array.isArray(e)&&e[0]&&Array.isArray(e[0])&&(this.trashcanPoint[t]=this.getTrashcanPoint(e[0]),this.sqmArea[t]=this.calculatePolygonArea(e[0]),this.perimeter[t]=this.calculatePolygonPerimeter(e[0]),this.polygon[t]=e)})}setSqmArea(e){this.sqmArea[0]=e}getTrashcanPoint(e){if(!Array.isArray(e)||0===e.length)return console.warn("getTrashcanPoint: Invalid polygon array:",e),{lat:0,lng:0};const t=e.filter(e=>e&&"object"==typeof e&&"number"==typeof e.lat&&"number"==typeof e.lng&&!isNaN(e.lat)&&!isNaN(e.lng));if(0===t.length)return console.warn("getTrashcanPoint: No valid coordinates found:",e),{lat:0,lng:0};const r=Math.max(...t.map(e=>e.lat)),o=t.findIndex(e=>e.lat===r);if(-1===o)return console.warn("getTrashcanPoint: Could not find max lat coordinate"),{lat:0,lng:0};let n,i;if(o>0?(n=t[o-1],i=o<t.length-1?t[o+1]:t[0]):(n=t[t.length-1],i=t[o+1]),!n||!i)return console.warn("getTrashcanPoint: Could not determine previous/next points"),t[o]||{lat:0,lng:0};const a=n.lng<i.lng?n:i;return ci.getMidPoint(t[o],a)}calculatePolygonArea(e){return ci.getSqmArea(e)}calculatePolygonPerimeter(e){return ci.getPerimeter(e)}}class hi{constructor(e){i(this,"polygonInfoListeners",[]),i(this,"polygonDrawStateListeners",[]),i(this,"polygonInformationStorage",[]),this.mapStateService=e}onPolygonInfoUpdated(e){this.polygonInfoListeners.push(e)}emitPolygonInfoUpdated(){for(const e of this.polygonInfoListeners)e(this.polygonInformationStorage)}onPolygonDrawStateUpdated(e){this.polygonDrawStateListeners.push(e)}updatePolygons(){const e=[];this.polygonInformationStorage.length>0&&this.polygonInformationStorage.forEach(t=>{const r=[];t.polygon.forEach(e=>{e.forEach(e=>{const t=[...e];e.length>0&&e[0].toString()!==e[e.length-1].toString()&&t.push(e[0]),r.push(t)})}),e.push(r)}),this.mapStateService.updatePolygons(e),this.saveCurrentState()}saveCurrentState(){this.emitPolygonInfoUpdated()}deleteTrashcan(e){const t=this.polygonInformationStorage.findIndex(t=>t.polygon[0]===e);-1!==t&&(this.polygonInformationStorage.splice(t,1),this.updatePolygons())}deleteTrashCanOnMulti(e){let t=0;this.polygonInformationStorage.forEach((r,o)=>{const n=r.polygon.findIndex(t=>t.toString()===e.toString());n>=0&&(t=o,r.trashcanPoint.splice(n,1),r.sqmArea.splice(n,1),r.perimeter.splice(n,1),r.polygon.splice(n,1))}),this.updatePolygons(),this.polygonInformationStorage.length>1&&this.polygonInformationStorage.splice(t,1)}deletePolygonInformationStorage(){this.polygonInformationStorage=[]}createPolygonInformationStorage(e){e.length>0&&(e.forEach(e=>{var t;const r=null==(t=e.getLayers)?void 0:t.call(e);if(null==r?void 0:r[0]){const e=r[0].getLatLngs(),t=new ui(e);this.polygonInformationStorage.push(t)}}),this.updatePolygons())}}class gi{constructor(){i(this,"map",null),i(this,"mapListeners",[])}onMapUpdated(e){this.map&&e(this.map),this.mapListeners.push(e)}emitMapUpdated(){if(this.map)for(const e of this.mapListeners)e(this.map)}updateMapState(e){this.map=e,this.emitMapUpdated()}updatePolygons(e){}}class di{constructor(){i(this,"eventListeners",new Map)}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t)}off(e,t){const r=this.eventListeners.get(e);if(r){const e=r.indexOf(t);e>-1&&r.splice(e,1)}}emit(e,t){var r;this.eventListeners.has(e)&&(null==(r=this.eventListeners.get(e))||r.forEach(e=>{e(t)}))}}class pi{constructor(e,t){i(this,"state"),i(this,"config"),i(this,"eventManager"),this.config=e,this.eventManager=t,this.state=this.createInitialState()}createInitialState(){return{polygonDragging:this.config.modes.dragPolygons??!1,markerDragging:this.config.modes.dragElbow??!1,edgeClicking:!0,polygonClicking:!0,canStartDrawing:!0,canCompletePolygon:!1,mapDragging:!0,mapZooming:!0,mapDoubleClickZoom:!0,currentMode:c.Off,isDrawingActive:!1,isModifierKeyHeld:!1,showCrosshairCursor:!1,showDragCursor:!1}}updateStateForMode(e){switch(this.state.currentMode=e,e){case c.Off:this.setOffModeState();break;case c.Add:case c.Subtract:this.setDrawingModeState();break;case c.PointToPoint:case c.PointToPointSubtract:this.setPointToPointModeState();break;case c.Clone:this.setCloneModeState()}this.state.isDrawingActive=e!==c.Off&&e!==c.Clone,this.eventManager.emit("polydraw:mode:change",{mode:e})}setOffModeState(){this.state.polygonDragging=this.config.modes.dragPolygons??!1,this.state.markerDragging=this.config.modes.dragElbow??!1,this.state.edgeClicking=!0,this.state.polygonClicking=!0,this.state.canStartDrawing=!0,this.state.canCompletePolygon=!1,this.state.mapDragging=!0,this.state.mapZooming=!0,this.state.mapDoubleClickZoom=!0,this.state.showCrosshairCursor=!1,this.state.showDragCursor=!1}setDrawingModeState(){this.state.polygonDragging=!1,this.state.markerDragging=!1,this.state.edgeClicking=!1,this.state.polygonClicking=!1,this.state.canStartDrawing=!0,this.state.canCompletePolygon=!0,this.state.mapDragging=!1,this.state.mapZooming=!1,this.state.mapDoubleClickZoom=!1,this.state.showCrosshairCursor=!0,this.state.showDragCursor=!1}setPointToPointModeState(){this.state.polygonDragging=!1,this.state.markerDragging=!1,this.state.edgeClicking=!1,this.state.polygonClicking=!1,this.state.canStartDrawing=!0,this.state.canCompletePolygon=!0,this.state.mapDragging=!1,this.state.mapZooming=!1,this.state.mapDoubleClickZoom=!1,this.state.showCrosshairCursor=!0,this.state.showDragCursor=!1}setCloneModeState(){this.state.polygonDragging=this.config.tools.clone??!1,this.state.markerDragging=!1,this.state.edgeClicking=!1,this.state.polygonClicking=!1,this.state.canStartDrawing=!1,this.state.canCompletePolygon=!1,this.state.mapDragging=!0,this.state.mapZooming=!0,this.state.mapDoubleClickZoom=!0,this.state.showCrosshairCursor=!1,this.state.showDragCursor=!0}setModifierKeyState(e){this.state.isModifierKeyHeld=e,this.state.currentMode,c.Off}canPerformAction(e){switch(e){case"polygonDrag":return this.state.polygonDragging;case"markerDrag":return this.state.markerDragging;case"edgeClick":return this.state.edgeClicking;case"polygonClick":return this.state.polygonClicking;case"startDrawing":return this.state.canStartDrawing;case"completePolygon":return this.state.canCompletePolygon;case"mapDrag":return this.state.mapDragging;case"mapZoom":return this.state.mapZooming;case"mapDoubleClickZoom":return this.state.mapDoubleClickZoom;default:return!1}}isInDrawingMode(){return this.state.isDrawingActive}isInOffMode(){return this.state.currentMode===c.Off}getCurrentMode(){return this.state.currentMode}getState(){return{...this.state}}shouldShowCrosshairCursor(){return this.state.showCrosshairCursor}shouldShowDragCursor(){return this.state.showDragCursor}updateConfig(e){this.config=e,this.updateStateForMode(this.state.currentMode)}}class fi{constructor(e){i(this,"turfHelper"),i(this,"map"),i(this,"config"),i(this,"modeManager"),i(this,"eventManager"),i(this,"tracer"),i(this,"p2pMarkers",[]),i(this,"isModifierKeyHeld",!1),i(this,"markerModifierHandlers",new WeakMap),this.turfHelper=e.turfHelper,this.map=e.map,this.config=e.config,this.modeManager=e.modeManager,this.eventManager=e.eventManager,this.tracer=e.tracer}mouseMove(e){if("latlng"in e&&e.latlng)this.tracer.addLatLng(e.latlng);else if("touches"in e&&e.touches&&e.touches.length>0){const t=this.map.getContainer().getBoundingClientRect(),r=this.map.containerPointToLatLng([e.touches[0].clientX-t.x,e.touches[0].clientY-t.y]);this.tracer.addLatLng(r)}}async mouseUpLeave(e){const t=this.tracer.toGeoJSON();if(!t||!t.geometry||!t.geometry.coordinates||t.geometry.coordinates.length<3)return{success:!1,error:"Not enough points to form a valid polygon. Event: "+JSON.stringify(e)};let r;try{r=this.turfHelper.createPolygonFromTrace(t)}catch(o){return{success:!1,error:(o instanceof Error?o.message:"Failed to create polygon from trace")+". Event: "+JSON.stringify(e)}}return r&&r.geometry&&r.geometry.coordinates&&0!==r.geometry.coordinates.length?(this.eventManager.emit("polydraw:polygon:created",{polygon:r,mode:this.modeManager.getCurrentMode()}),{success:!0,polygon:r}):{success:!1,error:"Invalid polygon created from trace. Event: "+JSON.stringify(e)}}setModifierKey(e){this.isModifierKeyHeld=e}shouldAllowP2PMarkerDeletion(){if(!this.isModifierKeyHeld||!this.config.modes.edgeDeletion)return!1;if(this.config.modifierSubtractMode){const e=this.modeManager.getCurrentMode();if(e===c.PointToPoint||e===c.PointToPointSubtract)return!1}return!0}handlePointToPointClick(e){if(e){if(this.p2pMarkers.length>=3){const t=this.p2pMarkers[0].getLatLng();if(this.isClickingFirstPoint(e,t))return void this.completePointToPointPolygon()}try{const t=this.isTouchDevice(),r=0===this.p2pMarkers.length,o=r?"leaflet-polydraw-p2p-marker leaflet-polydraw-p2p-first-marker":"leaflet-polydraw-p2p-marker",n=r?t?[24,24]:[20,20]:t?[18,18]:[16,16],i=new s.Marker(e,{icon:oi.createDivIcon({className:o,iconSize:n}),draggable:this.config.modes.dragElbow});i.on("add",()=>this.applyP2PMarkerMode(i)),i.addTo(this.map),this.applyP2PMarkerMode(i),i.on("mousedown",e=>{s.DomEvent.stopPropagation(e)}),i.on("drag",()=>{this.updateP2PTracer()}),i.on("click",e=>{this.shouldAllowP2PMarkerDeletion()&&(this.deleteP2PMarker(i),s.DomEvent.stopPropagation(e))}),i.on("mouseover",()=>this.onMarkerHoverForEdgeDeletion(i,!0)),i.on("mouseout",()=>this.onMarkerHoverForEdgeDeletion(i,!1)),r&&(i.on("mouseover",()=>{if(this.p2pMarkers.length>=3){const e=i.getElement();if(e){const t=this.modeManager.getCurrentMode()===c.PointToPointSubtract?this.config.styles.ui.dragSubtract.color:this.config.styles.ui.p2pClosingMarker.color;e.style.backgroundColor=t,e.style.borderColor=t,e.style.cursor="pointer",e.title="Click to close polygon"}}}),i.on("mouseout",()=>{const e=i.getElement();e&&(e.style.backgroundColor="",e.style.borderColor="",e.style.cursor="",e.title="")}),i.on("click",e=>{if(this.shouldAllowP2PMarkerDeletion())return this.deleteP2PMarker(i),void s.DomEvent.stopPropagation(e);this.p2pMarkers.length>=3&&(s.DomEvent.stopPropagation(e),this.completePointToPointPolygon())})),this.p2pMarkers.push(i),this.updateP2PTracer(),this.updateP2PMarkerModes(),this.updateFirstMarkerReadyState()}catch{}}}handleDoubleClick(e){this.modeManager.getCurrentMode()!==c.PointToPoint&&this.modeManager.getCurrentMode()!==c.PointToPointSubtract||this.p2pMarkers.length>=3&&this.completePointToPointPolygon()}handleDoubleTap(e){this.modeManager.getCurrentMode()!==c.PointToPoint&&this.modeManager.getCurrentMode()!==c.PointToPointSubtract||this.p2pMarkers.length>=3&&this.completePointToPointPolygon()}completePointToPointPolygon(){const e=this.p2pMarkers.map(e=>e.getLatLng());if(e.length<3)return;const t=[...e],r=e[0],o=e[e.length-1];r.lat===o.lat&&r.lng===o.lng||t.push(r);try{const e=t.map(e=>[e.lng,e.lat]),r=this.turfHelper.getMultiPolygon([[e]]);this.clearP2pMarkers(),this.resetTracer(),this.eventManager.emit("polydraw:polygon:created",{polygon:r,mode:this.modeManager.getCurrentMode(),isPointToPoint:!0})}catch(n){Wn()||console.warn("Error completing point-to-point polygon:",n),this.clearP2pMarkers(),this.resetTracer()}}cancelPointToPointDrawing(){this.clearP2pMarkers(),this.resetTracer(),this.eventManager.emit("polydraw:draw:cancel",{mode:c.PointToPoint})}clearP2pMarkers(){this.p2pMarkers.forEach(e=>{this.detachMarkerModifierHandler(e);try{this.map.removeLayer(e)}catch{}}),this.p2pMarkers=[]}resetTracer(){this.tracer.setLatLngs([]);try{this.tracer.setStyle({dashArray:void 0})}catch{}}isClickingFirstPoint(e,t){if(!t)return!1;const r=this.map.latLngToLayerPoint(e),o=this.map.latLngToLayerPoint(t);return r.distanceTo(o)<=(this.isTouchDevice()?36:12)}isTouchDevice(){return jn()}updateP2PTracer(){const e=this.p2pMarkers.map(e=>e.getLatLng());if(this.tracer.setLatLngs(e),this.p2pMarkers.length>=2)try{const e=this.modeManager.getCurrentMode()===c.PointToPointSubtract?this.config.styles.subtractLine.color:this.config.styles.polyline.color;this.tracer.setStyle({color:e,dashArray:"5, 5"})}catch{}else try{this.tracer.setStyle({dashArray:void 0})}catch{}}deleteP2PMarker(e){const t=this.p2pMarkers.findIndex(t=>t===e);if(t>-1){this.p2pMarkers.splice(t,1),this.detachMarkerModifierHandler(e);try{this.map.removeLayer(e)}catch{}this.updateP2PTracer(),0===t&&this.p2pMarkers.length>0&&this.setupFirstMarker(),this.updateFirstMarkerReadyState()}}getP2pMarkers(){return[...this.p2pMarkers]}isInPointToPointMode(){const e=this.modeManager.getCurrentMode();return e===c.PointToPoint||e===c.PointToPointSubtract}getTracerPointsCount(){return this.tracer.getLatLngs().length}setupFirstMarker(){if(0===this.p2pMarkers.length)return;const e=this.p2pMarkers[0],t=e.getElement();t&&(t.classList.add("leaflet-polydraw-p2p-first-marker"),t.classList.remove("leaflet-polydraw-p2p-first-marker-ready"),e.setIcon(oi.createDivIcon({className:"leaflet-polydraw-p2p-marker leaflet-polydraw-p2p-first-marker",iconSize:[20,20]})),this.applyP2PMarkerMode(e)),e.off("mouseover"),e.off("mouseout"),e.off("click"),e.on("mouseover",()=>{if(this.p2pMarkers.length>=3){const t=e.getElement();t&&(t.style.cursor="pointer",t.title="Click to close polygon")}}),e.on("mouseout",()=>{const t=e.getElement();t&&(t.style.backgroundColor="",t.style.borderColor="",t.style.cursor="",t.title="")}),e.on("click",t=>{if(this.shouldAllowP2PMarkerDeletion())return this.deleteP2PMarker(e),void s.DomEvent.stopPropagation(t);this.p2pMarkers.length>=3&&(s.DomEvent.stopPropagation(t),this.completePointToPointPolygon())})}updateFirstMarkerReadyState(){if(0===this.p2pMarkers.length)return;this.updateP2PMarkerModes();const e=this.p2pMarkers[0].getElement();e&&(this.p2pMarkers.length>=3?(e.classList.add("leaflet-polydraw-p2p-first-marker-ready"),e.setAttribute("data-p2p-mode",this.modeManager.getCurrentMode()===c.PointToPointSubtract?"subtract":"add"),e.style.cursor="pointer",e.title="Click to close polygon"):(e.classList.remove("leaflet-polydraw-p2p-first-marker-ready"),e.style.cursor="",e.removeAttribute("title")))}refreshP2PMarkerState(){0!==this.p2pMarkers.length&&(this.updateP2PMarkerModes(),this.updateFirstMarkerReadyState())}applyP2PMarkerMode(e){const t=e.getElement();if(!t)return;const r=this.modeManager.getCurrentMode();r===c.PointToPointSubtract?t.setAttribute("data-p2p-mode","subtract"):r===c.PointToPoint?t.setAttribute("data-p2p-mode","add"):t.removeAttribute("data-p2p-mode")}updateP2PMarkerModes(){this.p2pMarkers.forEach(e=>this.applyP2PMarkerMode(e))}onMarkerHoverForEdgeDeletion(e,t){const r=e.getElement();if(r)if(t){this.detachMarkerModifierHandler(e);const t=e=>{if(this.shouldAllowP2PMarkerDeletion()){r.classList.add("edge-deletion-hover");try{this.map.getContainer().style.cursor="pointer"}catch{}}else{r.classList.remove("edge-deletion-hover");try{this.map.getContainer().style.cursor=""}catch{}}};this.markerModifierHandlers.set(e,t),document.addEventListener("keydown",t),document.addEventListener("keyup",t),r.addEventListener("mousemove",t)}else{r.classList.remove("edge-deletion-hover");try{this.map.getContainer().style.cursor=""}catch{}this.detachMarkerModifierHandler(e)}}detachMarkerModifierHandler(e){const t=this.markerModifierHandlers.get(e);if(!t)return;document.removeEventListener("keydown",t),document.removeEventListener("keyup",t);const r=e.getElement();r&&(r.removeEventListener("mousemove",t),r.classList.remove("edge-deletion-hover")),this.markerModifierHandlers.delete(e)}}function yi(e){if(null==e)return e;try{return structuredClone(e)}catch{return mi(e)}}function mi(e,t=new WeakMap){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(Array.isArray(e))return e.map(e=>mi(e,t));if(t.has(e))return t.get(e);const r={};return t.set(e,r),Object.entries(e).forEach(([e,o])=>{r[e]=mi(o,t)}),r}class vi{constructor(e){i(this,"turfHelper"),i(this,"config"),this.turfHelper=e.turfHelper,this.config=e.config}checkPolygonIntersection(e,t){if(this.isPolygonInsideHole(e,t)||this.isPolygonInsideHole(t,e))return!1;try{const r=this.turfHelper.isPolygonCompletelyWithin(e,t),o=this.turfHelper.isPolygonCompletelyWithin(t,e);if(r||o)return!0}catch{}try{if(this.turfHelper.polygonIntersect(e,t))return!0}catch{}try{const r=this.turfHelper.getIntersection(e,t);if(r&&r.geometry&&("Polygon"===r.geometry.type||"MultiPolygon"===r.geometry.type)){if(this.turfHelper.getPolygonArea(r)>1e-6)return!0}}catch{}try{const r=this.turfHelper.getCoords(e),o=this.turfHelper.getCoords(t);for(const t of o)for(const r of t[0]){const t={type:"Feature",geometry:{type:"Point",coordinates:r},properties:{}};if(this.turfHelper.isPointInsidePolygon(t,e))return!0}for(const e of r)for(const r of e[0]){const e={type:"Feature",geometry:{type:"Point",coordinates:r},properties:{}};if(this.turfHelper.isPointInsidePolygon(e,t))return!0}}catch{}return!1}isPolygonInsideHole(e,t){try{const r=this.turfHelper.getCoords(t);for(const t of r){if(!t||t.length<=1)continue;const r=t.slice(1);for(const t of r)try{const r=this.turfHelper.createPolygon([t]);if(this.turfHelper.isPolygonCompletelyWithin(e,r))return!0}catch{continue}}}catch{}return!1}unionPolygons(e,t){try{let r=t;for(const t of e){const e=this.turfHelper.union(r,t);e&&(r=e)}return{success:!0,result:r}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Unknown error in unionPolygons"}}}subtractPolygon(e,t){try{const r=this.turfHelper.polygonDifference(e,t);if(r){const e=this.turfHelper.getCoords(r),t=[];for(const r of e)t.push(this.turfHelper.getMultiPolygon([r]));return{success:!0,results:t}}return{success:!0,results:[]}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Unknown error in subtractPolygon"}}}simplifyPolygon(e){var t,r;try{const o=this.turfHelper.getCoords(e);if(!o||0===o.length)return{success:!1,error:"Invalid polygon coordinates"};const n=(null==(r=null==(t=this.config.polygonTools)?void 0:t.simplify)?void 0:r.processHoles)??!0,i=o.map(e=>{const t=[];for(let r=0;r<e.length;r++){const o=e[r];if(0===r||n){if(o.length<=4){t.push(o);continue}const e=[];for(let t=0;t<o.length;t+=2)e.push(o[t]);const r=e[0],n=e[e.length-1];r[0]===n[0]&&r[1]===n[1]||e.push(r),e.length<4?t.push(o):t.push(e)}else t.push(o)}return t}),a=this.turfHelper.getMultiPolygon(i);return{success:!0,result:this.turfHelper.getTurfPolygon(a)}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error in simplifyPolygon"}}}convertToBoundingBox(e){var t,r,o,n;try{const i=this.turfHelper.getCoords(e);if(!i||0===i.length)return{success:!1,error:"Invalid polygon coordinates"};if(!((null==(r=null==(t=this.config.polygonTools)?void 0:t.bbox)?void 0:r.processHoles)??!0)){const t=this.turfHelper.convertToBoundingBoxPolygon(e);return{success:!0,result:this.turfHelper.getTurfPolygon(t)}}const a=i.map(e=>{const t=[];for(let r=0;r<e.length;r++){const o=e[r];let n=1/0,i=-1/0,a=1/0,s=-1/0;for(const e of o)if(Array.isArray(e)&&e.length>=2){const t=e[0],r=e[1];"number"!=typeof t||"number"!=typeof r||isNaN(t)||isNaN(r)||(a=Math.min(a,t),s=Math.max(s,t),n=Math.min(n,r),i=Math.max(i,r))}if(n!==1/0&&i!==-1/0&&a!==1/0&&s!==-1/0){const e=[[a,n],[a,i],[s,i],[s,n],[a,n]];t.push(e)}else t.push(o)}return t}),s=this.turfHelper.getMultiPolygon(a);let l=this.turfHelper.getTurfPolygon(s);if(null==(n=null==(o=this.config.polygonTools)?void 0:o.bbox)?void 0:n.addMidPointMarkers){const e=this.doubleElbowsPolygon(l);e.success&&e.result&&(l=e.result)}return{success:!0,result:l}}catch(i){return{success:!1,error:i instanceof Error?i.message:"Unknown error in convertToBoundingBox"}}}bezierifyPolygon(e){try{const t=this.turfHelper.getCoords(e),r=this.turfHelper.getBezierMultiPolygon(t);return{success:!0,result:this.turfHelper.getTurfPolygon(r)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error in bezierifyPolygon"}}}doubleElbowsPolygon(e){var t,r;try{const o=this.turfHelper.getCoords(e);if(!o||0===o.length)return{success:!1,error:"Invalid polygon coordinates"};const n=(null==(r=null==(t=this.config.polygonTools)?void 0:t.doubleElbows)?void 0:r.processHoles)??!0,i=o.map(e=>{const t=[];for(let r=0;r<e.length;r++){const o=e[r];if(0===r||n){const e=o.map(e=>({lat:e[1],lng:e[0]})),r=this.turfHelper.getDoubleElbowLatLngs(e).map(e=>[e.lng,e.lat]);t.push(r)}else t.push(o)}return t}),a=this.turfHelper.getMultiPolygon(i);return{success:!0,result:this.turfHelper.getTurfPolygon(a)}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error in doubleElbowsPolygon"}}}}class Mi{static createDivIcon(e){const t=e.join(" ");return oi.createDivIcon({className:t})}}class bi{static normalizeEvent(e){return ri.getVersion()===l.V2&&(e.layer&&!e.propagatedFrom&&(e.propagatedFrom=e.layer),"mousedown"!==e.type&&"touchstart"!==e.type||(e._isPointerEvent=!0)),e}static getEventName(e){if(ri.getVersion()===l.V2)switch(e){case"mousedown":case"touchstart":return"pointerdown";case"mouseup":case"touchend":return"pointerup";case"mousemove":case"touchmove":return"pointermove";default:return e}return e}static shouldUsePointerEvents(){return ri.getVersion()===l.V2&&"PointerEvent"in window}static extractCoordinates(e,t){if(e.latlng)return e.latlng;if(e.touches&&e.touches.length>0){const r=t.getContainer().getBoundingClientRect();return t.containerPointToLatLng([e.touches[0].clientX-r.x,e.touches[0].clientY-r.y])}if(e.pointerType&&void 0!==e.clientX&&void 0!==e.clientY){const r=t.getContainer().getBoundingClientRect();return t.containerPointToLatLng([e.clientX-r.x,e.clientY-r.y])}if(void 0!==e.clientX&&void 0!==e.clientY){const r=t.getContainer().getBoundingClientRect();return t.containerPointToLatLng([e.clientX-r.x,e.clientY-r.y])}return null}static shouldPreventDefault(e){return!(!e.type||!e.type.startsWith("touch"))||(!e.pointerType||!1!==e.isPrimary)&&!(!("cancelable"in e)||!e.cancelable)}static getEventNames(){return ri.getVersion()===l.V2&&this.shouldUsePointerEvents()?{start:["pointerdown"],move:["pointermove"],end:["pointerup"]}:{start:["mousedown","touchstart"],move:["mousemove","touchmove"],end:["mouseup","touchend"]}}}var wi=(e=>(e.TopLeft="top-left",e.Top="top",e.TopRight="top-right",e.Right="right",e.BottomRight="bottom-right",e.Bottom="bottom",e.BottomLeft="bottom-left",e.Left="left",e.Rotate="rotate",e.Pivot="pivot",e))(wi||{});class Pi{constructor(e,t,r,o,n){var a;i(this,"map"),i(this,"pane"),i(this,"root"),i(this,"draggingHandle",null),i(this,"documentMoveHandler",null),i(this,"documentUpHandler",null),i(this,"pointerCaptureTarget",null),i(this,"activePointerId",null),i(this,"callbacks"),i(this,"rafId",null),i(this,"mode"),i(this,"onCancel"),i(this,"onConfirm"),i(this,"cancelBtn",null),i(this,"confirmBtn",null),i(this,"statusLabel",null),i(this,"currentBBox",null),i(this,"currentRotation",0),i(this,"buttonsHidden",!1),i(this,"destroyed",!1),i(this,"donutValidation",null),i(this,"donutWarningVisible",!1),i(this,"supportsPointerEvents","undefined"!=typeof window&&"PointerEvent"in window),this.map=e,this.callbacks=t,this.mode=r,this.onCancel=o,this.onConfirm=n;const s="polydraw-transform",l=this.map;let c=null==(a=l.getPane)?void 0:a.call(l,s);c||(c=this.map.createPane(s)),c.style.zIndex="650",c.style.pointerEvents="auto",this.pane=c,this.root=document.createElement("div"),this.root.className="polydraw-transform-root",this.root.style.position="absolute",this.root.style.left="0px",this.root.style.top="0px",this.root.style.pointerEvents="none",this.pane.appendChild(this.root)}destroy(){this.destroyed||(this.destroyed=!0,null!=this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.draggingHandle=null,this.detachDocumentDragHandlers(),this.root.remove())}setDonutValidation(e,t=e.warning){this.donutValidation=e,this.donutWarningVisible=t}update(e,t,r=0){this.destroyed||null==this.rafId&&(this.rafId=requestAnimationFrame(()=>{if(this.rafId=null,!this.destroyed&&(this.render(e,t,r),this.cancelBtn||this.confirmBtn)){this.draggingHandle===wi.Rotate&&"rotate"===this.mode||this.updateButtonPositions(e,r)}}))}render(e,t,r=0){const o=this.cancelBtn,n=this.confirmBtn,i=this.statusLabel;this.root.innerHTML="",this.currentBBox=e,this.currentRotation=r,this.cancelBtn=o,this.confirmBtn=n,this.statusLabel=i;const a=e.maxX-e.minX,l=e.maxY-e.minY,c=e.minX+a/2,u=e.minY+l/2,h=this.getAccentPalette(),g=document.createElement("div");g.className="polydraw-transform-box","donut"===this.mode&&this.donutWarningVisible&&g.classList.add("is-invalid"),Object.assign(g.style,{position:"absolute",left:`${c}px`,top:`${u}px`,width:`${a}px`,height:`${l}px`,marginLeft:-a/2+"px",marginTop:-l/2+"px",border:`1px dashed ${h.boxBorder}`,pointerEvents:"none",transformOrigin:"center center",transform:`rotate(${180*r/Math.PI}deg)`}),this.root.appendChild(g);const d=(e,t,o)=>{const n=t-c,i=o-u,a=Math.cos(r),l=Math.sin(r),g=c+n*a-i*l,d=u+n*l+i*a,p=document.createElement("div");p.className=`polydraw-transform-handle handle-${e}`,Object.assign(p.style,{position:"absolute",left:g-5+"px",top:d-5+"px",width:"10px",height:"10px",borderRadius:"2px",background:h.handleFill,boxShadow:`0 0 0 1px ${h.handleOutline}`,cursor:this.cursorForHandle(e),pointerEvents:"auto",touchAction:"none"}),"donut"===this.mode&&this.donutWarningVisible&&p.classList.add("is-invalid"),this.supportsPointerEvents?s.DomEvent.on(p,"pointerdown",t=>this.startDrag(e,{x:g,y:d},t),this):(s.DomEvent.on(p,"mousedown",t=>this.startDrag(e,{x:g,y:d},t),this),s.DomEvent.on(p,"touchstart",t=>this.startDrag(e,{x:g,y:d},t),this)),this.root.appendChild(p)};"scale"===this.mode||"donut"===this.mode?(d(wi.TopLeft,e.minX,e.minY),d(wi.TopRight,e.maxX,e.minY),d(wi.BottomRight,e.maxX,e.maxY),d(wi.BottomLeft,e.minX,e.maxY),d(wi.Top,c,e.minY),d(wi.Right,e.maxX,u),d(wi.Bottom,c,e.maxY),d(wi.Left,e.minX,u)):(d(wi.Rotate,e.minX,e.minY),d(wi.Rotate,e.maxX,e.minY),d(wi.Rotate,e.maxX,e.maxY),d(wi.Rotate,e.minX,e.maxY)),this.cancelBtn||this.confirmBtn?(this.updateButtonPositions(e,r),this.cancelBtn&&this.root.appendChild(this.cancelBtn),this.confirmBtn&&this.root.appendChild(this.confirmBtn)):this.updateButtonPositions(e,r)}cursorForHandle(e){switch(e){case wi.Top:case wi.Bottom:return"ns-resize";case wi.Left:case wi.Right:return"ew-resize";case wi.TopLeft:case wi.BottomRight:return"nwse-resize";case wi.TopRight:case wi.BottomLeft:return"nesw-resize";case wi.Rotate:return"grab";case wi.Pivot:return"move";default:return"default"}}startDrag(e,t,r){var o,n;if(this.destroyed)return;s.DomEvent.stop(r),this.draggingHandle=e,this.hideButtons(),this.documentMoveHandler=e=>this.onDrag(e),this.documentUpHandler=e=>this.endDrag(e);const i=document,a=this.documentMoveHandler,l=this.documentUpHandler;if(this.supportsPointerEvents&&r instanceof PointerEvent){this.activePointerId=r.pointerId,this.pointerCaptureTarget=this.map.getContainer();try{null==(n=null==(o=this.pointerCaptureTarget)?void 0:o.setPointerCapture)||n.call(o,r.pointerId)}catch{}s.DomEvent.on(i,"pointermove",a),s.DomEvent.on(i,"pointerup",l),s.DomEvent.on(i,"pointercancel",l)}else s.DomEvent.on(i,"mousemove",a),s.DomEvent.on(i,"mouseup",l),s.DomEvent.on(i,"touchmove",a),s.DomEvent.on(i,"touchend",l),s.DomEvent.on(i,"touchcancel",l);this.callbacks.onStartHandleDrag(e,t,r)}onDrag(e){if(null==this.draggingHandle)return;const t=this.getMouseLayerPoint(e);this.callbacks.onDragHandle(this.draggingHandle,t,e)}endDrag(e){if(null==this.draggingHandle)return;const t=this.draggingHandle;this.draggingHandle=null;try{const r=this.getMouseLayerPoint(e);this.callbacks.onEndHandleDrag(t,r,e),this.currentBBox&&this.updateButtonPositions(this.currentBBox,this.currentRotation),this.showButtons()}finally{this.detachDocumentDragHandlers()}}detachDocumentDragHandlers(){var e,t;if(!this.documentMoveHandler&&!this.documentUpHandler&&!this.pointerCaptureTarget)return;const r=document;if(this.supportsPointerEvents&&this.pointerCaptureTarget){if(null!=this.activePointerId)try{null==(t=(e=this.pointerCaptureTarget).releasePointerCapture)||t.call(e,this.activePointerId)}catch{}if(this.documentMoveHandler){const e=this.documentMoveHandler;s.DomEvent.off(r,"pointermove",e)}if(this.documentUpHandler){const e=this.documentUpHandler;s.DomEvent.off(r,"pointerup",e),s.DomEvent.off(r,"pointercancel",e)}this.pointerCaptureTarget=null,this.activePointerId=null}else{if(this.documentMoveHandler){const e=this.documentMoveHandler;s.DomEvent.off(r,"mousemove",e),s.DomEvent.off(r,"touchmove",e)}if(this.documentUpHandler){const e=this.documentUpHandler;s.DomEvent.off(r,"mouseup",e),s.DomEvent.off(r,"touchend",e),s.DomEvent.off(r,"touchcancel",e)}}this.documentMoveHandler=null,this.documentUpHandler=null}getMouseLayerPoint(e){const t=this.map.getContainer();let r=null,o=null;if(e.touches&&e.touches.length>0){const t=e.touches[0];r=t.clientX,o=t.clientY}else if(e.changedTouches&&e.changedTouches.length>0){const t=e.changedTouches[0];r=t.clientX,o=t.clientY}else null!=e.clientX&&(r=e.clientX,o=e.clientY);null!=r&&null!=o||(r=0,o=0);const n=t.getBoundingClientRect(),i=r-n.left,a=o-n.top,s=oi.createPoint(i,a),l=this.map.containerPointToLayerPoint(s);return{x:l.x,y:l.y}}updateButtonPositions(e,t){var r,o;const n=e.maxX-e.minX,i=e.maxY-e.minY,a=e.minX+n/2,l=e.minY+i/2,c=[{x:e.minX,y:e.minY},{x:e.maxX,y:e.minY},{x:e.maxX,y:e.maxY},{x:e.minX,y:e.maxY}],u=Math.cos(t),h=Math.sin(t);let g={x:0,y:1/0},d=1/0;for(const s of c){const e=s.x-a,t=s.y-l,r=a+e*u-t*h,o=l+e*h+t*u,n=o<d,i=Math.abs(o-d)<1,c=r>g.x;(n||i&&c)&&(d=o,g={x:r,y:o})}const p=g.x,f=g.y-28,y=p+5,m=p-29,v=m-12,M=f+4;if(this.onCancel&&!this.cancelBtn&&(this.cancelBtn=document.createElement("div"),this.cancelBtn.className="polydraw-transform-cancel",this.cancelBtn.innerHTML='<?xml version="1.0" encoding="UTF-8"?>\n<svg width="512" height="512" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">\n <circle cx="256" cy="256" r="236" fill="#212A32"/>\n <circle cx="256" cy="256" r="190" fill="#ffffff"/>\n <path id="path2" fill="#800000" fill-rule="evenodd" stroke="none"\n d="M 156 373.906311 C 140.875 373.871002 127.9375 373.615112 127.25 373.337708 C 126.5625 373.060303 126 372.072937 126 371.143555 C 126 370.214203 146.628433 343.53772 171.840973 311.862488 C 197.053513 280.187286 217.991867 253.463562 218.370667 252.47644 C 218.806335 251.341125 218.221786 249.464233 216.779678 247.368073 C 215.525864 245.545563 196.612503 221.361847 174.75 193.626465 C 152.887497 165.891052 135 142.531311 135 141.715881 C 135 140.900421 136.012497 139.961914 137.25 139.63028 C 138.487503 139.298645 152.408203 139.021179 168.184906 139.013641 C 184.588272 139.005859 197.976456 139.420746 199.454529 139.982727 C 201.182831 140.639801 210.486664 152.319733 227.533463 175.232727 C 241.555283 194.079712 253.994949 210.166199 255.177185 210.980438 C 257.208252 212.379272 257.562622 212.186401 261.607452 207.480438 C 263.961853 204.74118 276.052643 189 288.47583 172.5 C 300.899048 156 312.286682 141.714874 313.781738 140.75528 C 316.198669 139.203949 319.554993 139.009949 344.058868 139.00528 C 366.27774 139.001007 371.993561 139.274811 373.557343 140.418274 C 375.458923 141.808746 375.448914 141.90155 373.046875 145.150452 C 371.699341 146.973114 352.828827 170.746307 331.112396 197.979767 C 309.395966 225.213257 291.465973 248.396271 291.267914 249.497589 C 291.012512 250.91803 304.435944 268.61731 337.453918 310.395416 C 363.05426 342.787903 384 370.077271 384 371.038422 C 384 371.999603 383.288208 373.059174 382.418213 373.393005 C 381.548218 373.726868 367.485718 373.993347 351.168213 373.98526 C 329.591888 373.974548 320.854309 373.633606 319.132629 372.73526 C 317.830597 372.055847 302.980591 353.049988 286.132629 330.5 C 260.059052 295.602051 255.12793 289.5 253 289.5 C 250.878326 289.5 245.808807 295.701355 219.5 330.479431 C 202.449997 353.018127 187.375 372.023987 186 372.714691 C 184.165009 373.636475 176.184906 373.95343 156 373.906311 Z"/>\n</svg>',s.DomEvent.on(this.cancelBtn,"mousedown",e=>{e.stopPropagation(),e.preventDefault(),this.onCancel&&this.onCancel()}),s.DomEvent.on(this.cancelBtn,"touchstart",e=>{e.stopPropagation(),e.preventDefault(),this.onCancel&&this.onCancel()}),s.DomEvent.on(this.cancelBtn,"pointerdown",e=>{e.stopPropagation(),e.preventDefault(),this.onCancel&&this.onCancel()}),this.root.appendChild(this.cancelBtn)),this.onConfirm&&!this.confirmBtn&&(this.confirmBtn=document.createElement("div"),this.confirmBtn.className="polydraw-transform-confirm",this.confirmBtn.innerHTML='<?xml version="1.0" encoding="UTF-8"?>\n<svg width="512" height="512" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">\n <circle cx="256" cy="256" r="236" fill="#212A32"/>\n <circle cx="256" cy="256" r="190" fill="#ffffff"/>\n <path id="check" fill="#008000" fill-rule="evenodd" stroke="none"\n d="M 223.844696 360 C 222.79425 360 204.506973 341.170593 178.987274 313.812744 \n C 144.992401 277.369232 135.966232 267.145691 136.201645 265.351257 \n C 136.396179 263.868408 143.092361 257.073425 155.444672 245.824249 \n C 166.363129 235.880859 175.214264 228.571442 176.336426 228.571442 \n C 177.515594 228.571442 181.716553 232.304138 186.987961 238.035706 \n C 191.775406 243.241058 201.629044 254.024994 208.884933 262 \n C 216.140823 269.975006 222.682266 276.635315 223.421478 276.80072 \n C 224.16246 276.966553 247.742722 250.494751 275.976837 217.800751 \n C 304.143097 185.185333 328.050385 157.879608 329.104156 157.121368 \n C 330.785767 155.911316 331.44046 156.0336 334.457672 158.121368 \n C 336.348328 159.429626 345.368622 167.190216 354.502747 175.367126 \n C 367.688812 187.171356 371.047394 190.689819 370.805115 192.445557 \n C 370.635864 193.67218 338.242889 231.469543 298.059082 277.32843 \n C 253.148834 328.581238 224.944153 360 223.844696 360 Z"/>\n</svg>',s.DomEvent.on(this.confirmBtn,"mousedown",e=>{e.stopPropagation(),e.preventDefault(),this.onConfirm&&this.isConfirmEnabled()&&this.onConfirm()}),s.DomEvent.on(this.confirmBtn,"touchstart",e=>{e.stopPropagation(),e.preventDefault(),this.onConfirm&&this.isConfirmEnabled()&&this.onConfirm()}),s.DomEvent.on(this.confirmBtn,"pointerdown",e=>{e.stopPropagation(),e.preventDefault(),this.onConfirm&&this.isConfirmEnabled()&&this.onConfirm()}),this.root.appendChild(this.confirmBtn)),"donut"!==this.mode||this.statusLabel||(this.statusLabel=document.createElement("div"),this.statusLabel.className="polydraw-transform-status",this.root.appendChild(this.statusLabel)),this.cancelBtn){Object.assign(this.cancelBtn.style,{position:"absolute",left:`${m}px`,top:`${f}px`,display:"grid",placeItems:"center",pointerEvents:"auto",width:"28px",height:"28px"});const e=this.cancelBtn.querySelector("svg");e&&(e.setAttribute("width","24"),e.setAttribute("height","24")),this.cancelBtn.style.display=this.buttonsHidden?"none":"grid"}if(this.confirmBtn){const e=this.isConfirmEnabled();Object.assign(this.confirmBtn.style,{position:"absolute",left:`${y}px`,top:`${f}px`,display:"grid",placeItems:"center",pointerEvents:e?"auto":"none",width:"28px",height:"28px"});const t=this.confirmBtn.querySelector("svg");t&&(t.setAttribute("width","24"),t.setAttribute("height","24")),this.confirmBtn.classList.toggle("is-disabled",!e),this.confirmBtn.setAttribute("aria-disabled",String(!e)),this.confirmBtn.style.display=this.buttonsHidden?"none":"grid"}if(this.statusLabel){const e="donut"===this.mode&&this.donutWarningVisible;this.statusLabel.innerHTML=e?'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512.055 512.055">\n <g transform="translate(-1)">\n <path\n fill="#facc15"\n d="M56.879,469.361L257.028,69.064l200.149,400.297H56.879z"\n />\n <path\n fill="#7f1d1d"\n fill-rule="evenodd"\n clip-rule="evenodd"\n d="M510.775,481.154L276.109,11.82c-7.862-15.724-30.3-15.724-38.162,0L3.28,481.154 c-7.092,14.185,3.222,30.874,19.081,30.874h469.333C507.553,512.028,517.868,495.338,510.775,481.154z M56.879,469.361 L257.028,69.064l200.149,400.297H56.879z"\n />\n <path\n fill="#7f1d1d"\n d="M235.694,192.028v149.333c0,11.782,9.551,21.333,21.333,21.333s21.333-9.551,21.333-21.333V192.028 c0-11.782-9.551-21.333-21.333-21.333S235.694,180.245,235.694,192.028z"\n />\n <path\n fill="#7f1d1d"\n d="M257.028,384.028c-11.776,0-21.333,9.557-21.333,21.333s9.557,21.333,21.333,21.333s21.333-9.557,21.333-21.333 S268.804,384.028,257.028,384.028z"\n />\n </g>\n</svg>\n':"",this.statusLabel.classList.toggle("is-invalid",e),this.statusLabel.setAttribute("data-donut-validity",(null==(r=this.donutValidation)?void 0:r.validity)??"invalid"),this.statusLabel.title=e?(null==(o=this.donutValidation)?void 0:o.statusText)??"":"",Object.assign(this.statusLabel.style,{position:"absolute",left:`${v}px`,top:`${M}px`,transform:"translateX(-100%)",pointerEvents:"none",display:e?"grid":"none"}),e&&this.root.appendChild(this.statusLabel)}}hideButtons(){this.buttonsHidden=!0,this.cancelBtn&&(this.cancelBtn.style.display="none"),this.confirmBtn&&(this.confirmBtn.style.display="none")}showButtons(){this.buttonsHidden=!1,this.cancelBtn&&(this.cancelBtn.style.display="grid"),this.confirmBtn&&(this.confirmBtn.style.display="grid",this.isConfirmEnabled()||(this.confirmBtn.style.display="grid"))}getAccentPalette(){return"donut"===this.mode&&this.donutWarningVisible?{boxBorder:"#d97706",handleFill:"#f59e0b",handleOutline:"#fff7ed"}:{boxBorder:"#2b90d9",handleFill:"#2b90d9",handleOutline:"#fff"}}isConfirmEnabled(){var e;return"donut"!==this.mode||!0===(null==(e=this.donutValidation)?void 0:e.submitEnabled)}}function Li(e,t){const r=e.latLngToLayerPoint(t);return{x:r.x,y:r.y}}function ki(e,t){const r=e.layerPointToLatLng(oi.createPoint(t.x,t.y));return{lat:r.lat,lng:r.lng}}function xi(e){let t=1/0,r=1/0,o=-1/0,n=-1/0;for(const i of e)for(const e of i)for(const i of e)i.x<t&&(t=i.x),i.y<r&&(r=i.y),i.x>o&&(o=i.x),i.y>n&&(n=i.y);return{minX:t,minY:r,maxX:o,maxY:n}}function Ei(e){return{x:(e.minX+e.maxX)/2,y:(e.minY+e.maxY)/2}}function Si(e,t,r,o){const n=e.x-t.x,i=e.y-t.y;return{x:t.x+n*r,y:t.y+i*o}}function Di(e,t,r,o,n){return e.map(e=>e.map(e=>e.map(e=>function(e,t,r){const o=Math.cos(r),n=Math.sin(r),i=e.x-t.x,a=e.y-t.y;return{x:t.x+i*o-a*n,y:t.y+i*n+a*o}}(Si(e,t,r,o),t,n))))}function Ci(e){if(0===e.length)return e;const t=e[0],r=e[e.length-1];return t.lat===r.lat&&t.lng===r.lng?e:[...e,{lat:t.lat,lng:t.lng}]}function Ii(e){if(!Array.isArray(e))return[[e]];const t=e;return 0===t.length?[]:Array.isArray(t[0])?Array.isArray(t[0][0])?e:[e]:[[e]]}function Ai(e,t,r){const o=[];for(let n=0;n<t.length;n++){const i=[];for(let o=0;o<t[n].length;o++){const a=t[n][o].map(t=>ki(e,t)),s=r[n][o],l=s.length>2&&s[0].lat===s[s.length-1].lat&&s[0].lng===s[s.length-1].lng;i.push(l?Ci(a):a)}o.push(i)}return o}function Fi(e){const t=e.map(e=>[e.lng,e.lat]);if(0===t.length)return t;const[r,o]=t[0],[n,i]=t[t.length-1];return r===n&&o===i||t.push([r,o]),t}function Oi(e){return{type:"Feature",geometry:{type:"Polygon",coordinates:[e]},properties:{}}}function Ti(e,t){return{validity:"invalid",reason:e,submitEnabled:!1,warning:!0,statusText:t}}class _i{constructor(e,t,r="scale",o=h.Both,n){var a,l;i(this,"map"),i(this,"polygon"),i(this,"overlay"),i(this,"state"),i(this,"normalizedLatLngs"),i(this,"wasMapDraggingEnabled",!1),i(this,"mode"),i(this,"onExit"),i(this,"rotateStartAngle",null),i(this,"rotateBaseRotation",0),i(this,"originalTouchAction",null),i(this,"mapDraggingHandler"),i(this,"originalPolygonStyle"),i(this,"donutDirection"),i(this,"onKeyDown",e=>{"Escape"===e.key&&this.handleCancel()}),i(this,"updateOverlay",()=>{const e=xi(this.state.originalPixelRings.map(e=>e.map(e=>e.map(e=>Si(e,this.state.pivot,this.state.scaleX,this.state.scaleY)))));this.overlay.update(e,this.state.pivot,this.state.rotation)}),this.map=e,this.mode=r,this.donutDirection=o,this.onExit=n;const c=t.getLayers().find(e=>e instanceof s.Polygon);if(!c)throw new Error("FeatureGroup does not contain a polygon");this.polygon=c,this.originalPolygonStyle={color:this.polygon.options.color,fillColor:this.polygon.options.fillColor,opacity:this.polygon.options.opacity,fillOpacity:this.polygon.options.fillOpacity};const u=this.polygon.getLatLngs();this.normalizedLatLngs=Ii(u);const g=function(e,t){const r=[],o=[];for(const n of t){const t=[],i=[];for(const r of n){const o=r.map(t=>Li(e,{lat:t.lat,lng:t.lng}));t.push(o),i.push(r.length)}r.push(t),o.push(i)}return{rings:r,ringLengths:o}}(this.map,this.normalizedLatLngs),d=Ei(xi(g.rings));this.state={isActive:!0,originalLatLngs:u,originalPixelRings:g.rings,pivot:d,scaleX:1,scaleY:1,rotation:0,uniformScale:!1,snapRotation:!1,scaleFromPivot:!1},this.overlay=new Pi(this.map,{onStartHandleDrag:(e,t,r)=>this.onStartDrag(e,t,r),onDragHandle:(e,t)=>this.onDrag(e,t),onEndHandleDrag:()=>{}},this.mode,()=>this.handleCancel(),()=>this.handleConfirm()),this.updateOverlay(),this.syncDonutValidation(),this.map.on("zoom viewreset move",this.updateOverlay,this),this.mapDraggingHandler=this.map.dragging,this.mapDraggingHandler&&("function"==typeof this.mapDraggingHandler.enabled&&(this.wasMapDraggingEnabled=this.mapDraggingHandler.enabled()),null==(l=(a=this.mapDraggingHandler).disable)||l.call(a));const p=this.map.getContainer();this.originalTouchAction=p.style.touchAction||null,p.style.touchAction="none",document.addEventListener("keydown",this.onKeyDown)}destroy(){document.removeEventListener("keydown",this.onKeyDown),this.map.off("zoom viewreset move",this.updateOverlay,this),this.restorePolygonStyle(),this.overlay.destroy(),this.state.isActive=!1,this.mapDraggingHandler&&this.wasMapDraggingEnabled&&"function"==typeof this.mapDraggingHandler.enable&&this.mapDraggingHandler.enable();const e=this.map.getContainer();null!==this.originalTouchAction?e.style.touchAction=this.originalTouchAction:e.style.touchAction=""}onStartDrag(e,t,r){const o=navigator.userAgent.toLowerCase().includes("mac")?r.metaKey:r.ctrlKey;if(this.state.uniformScale=!!r.shiftKey,this.state.scaleFromPivot=!!r.altKey,this.state.snapRotation=!!o,e===wi.Rotate){const e=this.state.scaleFromPivot?this.state.pivot:Ei(xi(this.state.originalPixelRings)),r=Math.atan2(t.y-e.y,t.x-e.x);this.rotateStartAngle=r,this.rotateBaseRotation=this.state.rotation||0}}onDrag(e,t){const r=xi(this.state.originalPixelRings);switch(e){case wi.Rotate:{const e=this.state.scaleFromPivot?this.state.pivot:Ei(r);this.handleRotateDrag(t,e);break}case wi.Pivot:this.handlePivotDrag(t);break;default:{const o=this.state.scaleFromPivot?this.state.pivot:Ei(r);this.handleScaleDrag(e,t,r,o);break}}this.preview()}handleRotateDrag(e,t){if("rotate"!==this.mode)return;const r=Math.atan2(e.y-t.y,e.x-t.x);let o;if(null!=this.rotateStartAngle){const e=r-this.rotateStartAngle;o=this.rotateBaseRotation+e}else o=r;this.state.rotation=this.state.snapRotation?function(e,t=15){const r=t*Math.PI/180;return Math.round(e/r)*r}(o,15):o}handlePivotDrag(e){this.state.pivot=e}handleScaleDrag(e,t,r,o){if("rotate"===this.mode)return;const n=r.maxX-r.minX,i=r.maxY-r.minY;let a=this.state.scaleX,s=this.state.scaleY;switch(e){case wi.Left:case wi.TopLeft:case wi.BottomLeft:a=(o.x-t.x)/(o.x-r.minX||1);break;case wi.Right:case wi.TopRight:case wi.BottomRight:a=(t.x-o.x)/(r.maxX-o.x||1)}switch(e){case wi.Top:case wi.TopLeft:case wi.TopRight:s=(o.y-t.y)/(o.y-r.minY||1);break;case wi.Bottom:case wi.BottomLeft:case wi.BottomRight:s=(t.y-o.y)/(r.maxY-o.y||1)}if(e!==wi.Left&&e!==wi.Right||(s=this.state.scaleY),e!==wi.Top&&e!==wi.Bottom||(a=this.state.scaleX),this.state.uniformScale){const e=Math.abs(n)>Math.abs(i)?Math.sign(a)*Math.abs(a):Math.sign(s)*Math.abs(s);a=e,s=e}const l=Number.isFinite(a)&&Math.abs(a)>.001,c=Number.isFinite(s)&&Math.abs(s)>.001;l&&(this.state.scaleX=a),c&&(this.state.scaleY=s)}preview(){var e,t;const r=Di(this.state.originalPixelRings,this.state.pivot,this.state.scaleX,this.state.scaleY,this.state.rotation),o=Ai(this.map,r,this.normalizedLatLngs);if("donut"===this.mode){const r=(null==(e=this.normalizedLatLngs[0])?void 0:e[0])??[],n=(null==(t=o[0])?void 0:t[0])??[];this.polygon.setLatLngs([[r,n]]),this.syncDonutValidation()}else this.polygon.setLatLngs(o);this.updateOverlay()}apply(){return Ii(this.polygon.getLatLngs())}cancel(){this.restorePolygonStyle(),this.polygon.setLatLngs(this.state.originalLatLngs)}getMode(){return this.mode}getOriginalOuterLatLngs(){var e;return(null==(e=this.normalizedLatLngs[0])?void 0:e[0])??[]}getScaledOuterLatLngs(){var e;const t=Di(this.state.originalPixelRings,this.state.pivot,this.state.scaleX,this.state.scaleY,this.state.rotation);return(null==(e=Ai(this.map,t,this.normalizedLatLngs)[0])?void 0:e[0])??[]}getDonutValidation(){return function(e,t,r,o,n=h.Both){if(e.length<3||t.length<3)return Ti("invalid-rings","Scale to create a donut");if(Math.abs(r-1)<.01&&Math.abs(o-1)<.01)return Ti("scale-required","Scale to create a donut");const i=Fi(e),a=Fi(t);if(i.length<4||a.length<4)return Ti("invalid-rings","Scale to create a donut");const s=Oi(i),l=Oi(a);let c=!1,u=!1;try{c=zo(l,s),u=zo(s,l)}catch{return Ti("partial-overlap","Donut requires one shape to fully contain the other")}return c||u?u&&n===h.Inward?Ti("direction-restricted","Only inward donuts allowed"):{validity:u?"valid-outward":"valid-inward",reason:u?"nested-outward":"nested-inward",submitEnabled:!0,warning:!1,statusText:"Valid donut",allowMerge:u,polygon:{type:"Feature",geometry:{type:"Polygon",coordinates:[u?a:i,u?i:a]},properties:{}}}:Ti("partial-overlap","Donut requires one shape to fully contain the other")}(this.getOriginalOuterLatLngs(),this.getScaledOuterLatLngs(),this.state.scaleX,this.state.scaleY,this.donutDirection)}syncDonutValidation(){if("donut"!==this.mode)return;const e=this.getDonutValidation(),t=e.warning&&"scale-required"!==e.reason;this.overlay.setDonutValidation(e,t),t?this.polygon.setStyle({color:"#d97706",fillColor:"#f59e0b",opacity:Math.max(this.originalPolygonStyle.opacity??0,.95),fillOpacity:Math.max(this.originalPolygonStyle.fillOpacity??0,.2)}):this.restorePolygonStyle()}restorePolygonStyle(){"donut"===this.mode&&this.polygon.setStyle({color:this.originalPolygonStyle.color,fillColor:this.originalPolygonStyle.fillColor,opacity:this.originalPolygonStyle.opacity,fillOpacity:this.originalPolygonStyle.fillOpacity})}handleCancel(){this.cancel(),this.onExit&&this.onExit(!1),this.destroy()}handleConfirm(){this.onExit&&this.onExit(!0),this.destroy()}}class Gi{static createMenuButton(e,t,r){const o=document.createElement("div");return o.classList.add("marker-menu-button",...r),o.title=t,o.setAttribute("aria-label",t),o.setAttribute("data-action-id",e),o}static buildMenuPopup(e){const t=document.createElement("div");t.classList.add("alter-marker-outer-wrapper");const r=document.createElement("div");r.classList.add("alter-marker-wrapper");const o=document.createElement("button");o.type="button",o.className="marker-menu-close",o.setAttribute("aria-label","Close menu"),o.innerHTML="&times;",r.appendChild(o);const n=document.createElement("div");n.classList.add("content");const i=document.createElement("div");return i.classList.add("marker-menu-content"),e.forEach(e=>{i.appendChild(e)}),n.appendChild(i),r.appendChild(n),t.appendChild(r),t}static buildInfoPopup(e){const t=document.createElement("div");t.classList.add("info-marker-outer-wrapper");const r=document.createElement("div");r.classList.add("info-marker-wrapper");const o=document.createElement("div");return o.classList.add("content"),o.appendChild(e),r.appendChild(o),t.appendChild(r),t}}const Hi=new Set(["simplify","doubleElbows","bbox","bezier","scale","rotate","donut","toggleOptimization"]);class Bi{constructor(e,t){i(this,"markerFeatureGroupMap",new WeakMap),i(this,"polygonFeatureGroupMap",new WeakMap),i(this,"markerModifierHandlers",new WeakMap),i(this,"markerTouchListeners",new WeakMap),i(this,"markerEdgeDeletionListeners",new WeakMap),i(this,"_activeMarker",null),i(this,"isDraggingMarker",!1),i(this,"turfHelper"),i(this,"polygonInformation"),i(this,"map"),i(this,"config"),i(this,"modeManager"),i(this,"eventManager"),i(this,"saveHistoryState"),i(this,"layerManager"),i(this,"currentDragPolygon",null),i(this,"currentDragIsClone",!1),i(this,"currentModifierDragMode",!1),i(this,"isModifierKeyHeld",!1),i(this,"currentCloneGhost",null),i(this,"dragCancelHandlersAttached",!1),i(this,"_boundDragTouchMove",null),i(this,"_boundDragTouchEnd",null),i(this,"_boundDragMoveListener",null),i(this,"_boundDragEndListener",null),i(this,"dragUsesPointerEvents",!1),i(this,"polygonTouchStartListeners",new WeakMap),i(this,"_openMenuPopup",null),i(this,"transformModeActive",!1),i(this,"transformControllers",new WeakMap),i(this,"transformAuxiliaryDisplayValues",new WeakMap),i(this,"deleteMarkerSuppressUntil",0),i(this,"onModeChange",()=>{(this.currentCloneGhost||this.isPolygonDragActive())&&this.cancelActivePolygonDrag()}),i(this,"getFeatureGroups"),i(this,"removeFeatureGroup"),i(this,"onPolygonMouseMove",e=>{if(!this.currentDragPolygon||!this.currentDragPolygon._polydrawDragData||!this.currentDragPolygon._polydrawDragData.isDragging)return;const t=this.currentDragPolygon,r=t._polydrawDragData;if(!this.currentDragIsClone){const t=e.originalEvent&&"metaKey"in e.originalEvent?e.originalEvent:e;this.detectDragSubtractModifierKey(t)!==this.currentModifierDragMode&&this.handleModifierToggleDuringDrag(t)}const o=r.startPosition,n=e.latlng,i=n.lat-o.lat,a=n.lng-o.lng,s=this.offsetPolygonCoordinates(r.startLatLngs,i,a);t.setLatLngs(s),this.updateMarkersAndHoleLinesDuringDrag(t,i,a)}),i(this,"onPolygonMouseUp",e=>{if(!this.currentDragPolygon||!this.currentDragPolygon._polydrawDragData||!this.currentDragPolygon._polydrawDragData.isDragging)return;const t=this.currentDragPolygon,r=t._polydrawDragData;r.isDragging=!1,this.map.dragging&&this.map.dragging.enable(),t._polydrawDragData&&null!=t._polydrawDragData.originalOpacity&&t.setStyle({fillOpacity:t._polydrawDragData.originalOpacity}),this.setMarkerVisibility(t,!0);try{this.map.getContainer().style.cursor=""}catch{}this.clearCloneGhost(),this.detachDragTouchListeners(),this.detachDragDocumentListeners(),this.detachDragCancelHandlers();const o=this.currentDragIsClone;this.currentDragIsClone=!1,o?this.updatePolygonAfterCloneDrag(t,r):this.updatePolygonAfterDrag(t),t._polydrawOriginalMarkerPositions&&(t._polydrawOriginalMarkerPositions.clear(),delete t._polydrawOriginalMarkerPositions),t._polydrawOriginalHoleLinePositions&&(t._polydrawOriginalHoleLinePositions.clear(),delete t._polydrawOriginalHoleLinePositions),t._polydrawCurrentDragSession&&delete t._polydrawCurrentDragSession,this.currentDragPolygon=null}),i(this,"onPolygonDragCancel",()=>{this.cancelActivePolygonDrag()}),i(this,"onPolygonDragKeyDown",e=>{"Escape"===e.key&&this.cancelActivePolygonDrag()}),i(this,"onDragTouchMove",e=>{e.preventDefault();const t=bi.extractCoordinates(e,this.map);t&&this.onPolygonMouseMove({latlng:t})}),i(this,"onDragTouchEnd",e=>{e.preventDefault(),this.onPolygonMouseUp({latlng:null})}),i(this,"onDragDocumentMove",e=>{const t=bi.extractCoordinates(e,this.map);t&&this.onPolygonMouseMove({latlng:t,originalEvent:e})}),i(this,"onDragDocumentEnd",e=>{const t=bi.extractCoordinates(e,this.map)??null;this.onPolygonMouseUp({latlng:t,originalEvent:e})}),i(this,"onMarkerHoverForEdgeDeletionEvent",e=>{if(!this.isModifierKeyHeld)return;const t=e.target;t&&(t.style.backgroundColor=this.config.styles.ui.edgeDeletion.color,t.style.borderColor=this.config.styles.ui.edgeDeletion.color,t.classList.add("edge-deletion-hover"))}),i(this,"onMarkerLeaveForEdgeDeletionEvent",e=>{const t=e.target;t&&(t.style.backgroundColor="",t.style.borderColor="",t.classList.remove("edge-deletion-hover"))}),this.turfHelper=e.turfHelper,this.polygonInformation=e.polygonInformation,this.map=e.map,this.config=e.config,this.modeManager=e.modeManager,this.eventManager=e.eventManager,this.saveHistoryState=e.saveHistoryState,this.layerManager=e.layerManager,this.getFeatureGroups=t.getFeatureGroups,this.removeFeatureGroup=t.removeFeatureGroup,this.eventManager.on("polydraw:mode:change",this.onModeChange)}emitPolygonUpdated(e){const t=this.getHistoryActionForOperation(e.operation);t&&this.saveHistoryState&&this.saveHistoryState(t),this.eventManager.emit("polydraw:polygon:updated",e)}getHistoryActionForOperation(e){switch(e){case"addVertex":case"removeVertex":case"removeHole":case"toggleOptimization":return e;case"modifierSubtract":case"modifierSubtractFallback":return"modifierSubtract";default:return null}}donutTargetHasHoles(e){const t=e.getLayers().find(e=>e instanceof s.Polygon);if(!t)return!0;const r=t.getLatLngs();if(!Array.isArray(r)||0===r.length)return!0;if(!Array.isArray(r[0]))return!1;const o=r;return!!Array.isArray(o[0][0])||o.length>1}handleDonutCommit(e,t,r,o,n){const i=e.getOriginalOuterLatLngs(),a=e.getDonutValidation(),s=()=>{r.setLatLngs([i]),this.setMarkerVisibility(r,!0)};a.submitEnabled&&a.polygon?(r.setLatLngs([i]),this.saveHistoryState&&this.saveHistoryState("donut"),this.cleanupFeatureGroup(t),this.removeFeatureGroup(t),this.emitPolygonUpdated({operation:"donut",polygon:a.polygon,allowMerge:a.allowMerge,optimizationLevel:o,originalOptimizationLevel:n})):s()}dispose(){this.eventManager.off("polydraw:mode:change",this.onModeChange),this.cancelActivePolygonDrag()}getTimestamp(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}shouldSuppressDeleteMarkerClick(){return this.getTimestamp()<this.deleteMarkerSuppressUntil}suppressDeleteMarkerClicks(e){this.deleteMarkerSuppressUntil=this.getTimestamp()+Math.max(0,e)}addMarkers(e,t,r={}){this.registerPolygonLayerMappings(t);let o=this.getMarkerIndex(e,this.config.markers.markerMenuIcon.position),n=this.getMarkerIndex(e,this.config.markers.markerDeleteIcon.position),i=this.getMarkerIndex(e,this.config.markers.markerInfoIcon.position);const a=this.ensureMarkerSeparation(e.length,{menu:{index:o,enabled:this.config.markers.menuMarker},delete:{index:n,enabled:this.config.markers.deleteMarker},info:{index:i,enabled:this.config.markers.infoMarker}});o=a.menu,n=a.delete,i=a.info;const l=r.optimizationLevel??0,c=this.deriveImportantMarkerIndices(e,{menuIndex:o,deleteIndex:n,infoIndex:i,optimizationLevel:l}),u=e.length>2&&this.latLngEquals(e[0],e[e.length-1]);e.forEach((r,a)=>{let h=this.config.markers.markerIcon.styleClasses;a===o&&this.config.markers.menuMarker&&(h=this.config.markers.markerMenuIcon.styleClasses),a===n&&this.config.markers.deleteMarker&&(h=this.config.markers.markerDeleteIcon.styleClasses),a===i&&this.config.markers.infoMarker&&(h=this.config.markers.markerInfoIcon.styleClasses);const g=Array.isArray(h)?h:[h],d=a===o&&this.config.markers.menuMarker||a===n&&this.config.markers.deleteMarker||a===i&&this.config.markers.infoMarker,p=this.normalizeMarkerIndex(a,e.length,u),f=[...g];l<=0||null===p||c.has(p)||d||f.push("polygon-marker-faded");const y=new s.Marker(r,{icon:this.createDivIcon(f),draggable:this.config.modes.dragElbow,title:this.config.markers.coordsTitle?this.getLatLngInfoString(r):"",zIndexOffset:this.config.markers.markerIcon.zIndexOffset??this.config.markers.zIndexOffset});t.addLayer(y),this.markerFeatureGroupMap.set(y,t),y.on("add",()=>{const e=y.getElement();e&&(e.style.pointerEvents="auto")}),y.on("click",e=>{var t,r;this.isDraggingMarker&&(null==(r=null==(t=e.originalEvent)?void 0:t.stopPropagation)||r.call(t),s.DomEvent.stopPropagation(e))}),y.on("dragstart",()=>{const e=this.markerFeatureGroupMap.get(y);!e||this.isFeatureGroupInActiveLayer(e)?(this.saveHistoryState&&this.saveHistoryState("markerDrag"),this.isDraggingMarker=!0,this._activeMarker=y):y.dragging&&y.dragging.disable()}),y.on("dragend",e=>{const t=this.markerFeatureGroupMap.get(y);if(t&&!this.isFeatureGroupInActiveLayer(t))return this._activeMarker=null,void(this.isDraggingMarker=!1);this.modeManager.canPerformAction("markerDrag")&&t&&this.markerDragEnd(t),this._activeMarker=null,s.DomEvent.stopPropagation(e),setTimeout(()=>{this.isDraggingMarker=!1},10)});const m=y.getElement();if(m){const e=e=>{e.stopPropagation()},t=e=>{if(e.preventDefault(),e.stopPropagation(),y.fire("click"),this.isDraggingMarker&&!d){const e=this.markerFeatureGroupMap.get(y);this.modeManager.canPerformAction("markerDrag")&&e&&this.isFeatureGroupInActiveLayer(e)&&this.markerDragEnd(e)}this._activeMarker=null};m.addEventListener("touchstart",e,{passive:!0}),m.addEventListener("touchend",t),this.markerTouchListeners.set(y,{touchstart:e,touchend:t})}if(a===o||a===n||a===i){const e=y.getElement();e&&(e.style.zIndex="10000")}if(this.config.modes.dragElbow){const e=e=>()=>{this.modeManager.canPerformAction("markerDrag")&&this.isFeatureGroupInActiveLayer(e)&&this.markerDrag(e)};y.on("drag",e(t))}if(a===o&&this.config.markers.menuMarker&&(y.options.zIndexOffset=this.config.markers.markerMenuIcon.zIndexOffset??this.config.markers.zIndexOffset,y.on("click",()=>{if(!this.isFeatureGroupInActiveLayer(t))return;const r=this.getPolygonGeoJSONFromFeatureGroup(t),n=ci.getCenterOfPolygonByIndexWithOffsetFromCenterOfMass(r,o);this.generateMenuMarkerPopup(e,t).setLatLng(n).openOn(this.map)}),y.on("popupopen",e=>{const t=e.popup.getElement();if(!t)return;setTimeout(()=>{const e=this.map.getContainer(),r=t.getBoundingClientRect(),o=e.getBoundingClientRect();let n=0,i=0;r.left<o.left?n=o.left-r.left:r.right>o.right&&(n=o.right-r.right),r.top<o.top?i=o.top-r.top:r.bottom>o.bottom&&(i=o.bottom-r.bottom),0===n&&0===i||(t.style.transform=`translate(${n}px, ${i}px)`)},0);const r=this.map.getContainer();r&&(r.style.touchAction="manipulation")}),y.on("popupclose",()=>{const e=this.map.getContainer();e&&(e.style.touchAction="")})),a===i&&this.config.markers.infoMarker){const e=this.getPolygonGeoJSONFromFeatureGroup(t),r=this.turfHelper.getPolygonArea(e),o=this.getTotalPolygonPerimeter(e);y.options.zIndexOffset=this.config.markers.markerInfoIcon.zIndexOffset??this.config.markers.zIndexOffset,y.on("click",()=>{if(!this.isFeatureGroupInActiveLayer(t))return;const n=this.generateInfoMarkerPopup(r,o),a=ci.getCenterOfPolygonByIndexWithOffsetFromCenterOfMass(e,i);n.setLatLng(a).openOn(this.map)}),y.on("popupopen",e=>{const t=e.popup.getElement();if(!t)return;setTimeout(()=>{const e=this.map.getContainer().getBoundingClientRect(),r=t.getBoundingClientRect();r.left<e.left?t.style.transform=`translateX(${e.left-r.left}px)`:r.right>e.right&&(t.style.transform=`translateX(${e.right-r.right}px)`)},0);const r=this.map.getContainer();r&&(r.style.touchAction="manipulation")}),y.on("popupclose",()=>{const e=this.map.getContainer();e&&(e.style.touchAction="")})}y.on("mousedown",e=>{this.modeManager.isInOffMode()||(s.DomEvent.stopPropagation(e),this.map.fire("mousedown",e)),this._activeMarker=y}),y.on("click",e=>{var r,o;if(this.isFeatureGroupInActiveLayer(t)&&this.modeManager.isInOffMode())if(this.isEdgeDeletionModifierKeyPressed(e.originalEvent)){const r=t.getLayers().find(e=>e instanceof s.Polygon);r&&this.elbowClicked(e,r,y.getLatLng())}else if(a===n&&this.config.markers.deleteMarker){if(this.shouldSuppressDeleteMarkerClick()){const t=e.originalEvent;return null==(r=null==t?void 0:t.preventDefault)||r.call(t),void(null==(o=null==t?void 0:t.stopPropagation)||o.call(t))}this.map.closePopup(),this.saveHistoryState&&this.saveHistoryState("deletePolygon"),this.cleanupFeatureGroup(t),this.removeFeatureGroup(t),this.polygonInformation.createPolygonInformationStorage(this.getFeatureGroups()),this.eventManager.emit("polydraw:polygon:deleted",void 0)}}),y.on("mouseover",()=>{this.isFeatureGroupInActiveLayer(t)&&this.onMarkerHoverForEdgeDeletion(y,!0)}),y.on("mouseout",()=>{this.onMarkerHoverForEdgeDeletion(y,!1)})});const h=this.map.getContainer();h&&(h.style.touchAction="manipulation")}addHoleMarkers(e,t){var r,o,n;this.registerPolygonLayerMappings(t);const i=(null==(r=this.config.markers.holeMarkers)?void 0:r.menuMarker)??!1,a=(null==(o=this.config.markers.holeMarkers)?void 0:o.deleteMarker)??!1,l=(null==(n=this.config.markers.holeMarkers)?void 0:n.infoMarker)??!1;let c=this.getMarkerIndex(e,this.config.markers.markerMenuIcon.position),u=this.getMarkerIndex(e,this.config.markers.markerDeleteIcon.position),h=this.getMarkerIndex(e,this.config.markers.markerInfoIcon.position);const g=this.ensureMarkerSeparation(e.length,{menu:{index:c,enabled:i},delete:{index:u,enabled:a},info:{index:h,enabled:l}});c=g.menu,u=g.delete,h=g.info,e.forEach((r,o)=>{let n=this.config.markers.holeIcon.styleClasses;o===c&&i&&(n=this.config.markers.markerMenuIcon.styleClasses),o===u&&a&&(n=this.config.markers.markerDeleteIcon.styleClasses),o===h&&l&&(n=this.config.markers.markerInfoIcon.styleClasses);const g=Array.isArray(n)?n:[n],d=o===c&&i||o===u&&a||o===h&&l,p=new s.Marker(r,{icon:this.createDivIcon(g),draggable:this.config.modes.dragElbow,title:this.config.markers.coordsTitle?this.getLatLngInfoString(r):"",zIndexOffset:this.config.markers.holeIcon.zIndexOffset??this.config.markers.zIndexOffset});t.addLayer(p),this.markerFeatureGroupMap.set(p,t),p.on("add",()=>{const e=p.getElement();e&&(e.style.pointerEvents="auto")}),p.on("click",e=>{var t,r;this.isDraggingMarker&&(null==(r=null==(t=e.originalEvent)?void 0:t.stopPropagation)||r.call(t),s.DomEvent.stopPropagation(e))}),p.on("dragstart",()=>{const e=this.markerFeatureGroupMap.get(p);!e||this.isFeatureGroupInActiveLayer(e)?(this.saveHistoryState&&this.saveHistoryState("markerDrag"),this.isDraggingMarker=!0,this._activeMarker=p):p.dragging&&p.dragging.disable()}),p.on("dragend",e=>{const t=this.markerFeatureGroupMap.get(p);if(t&&!this.isFeatureGroupInActiveLayer(t))return this._activeMarker=null,void(this.isDraggingMarker=!1);this.modeManager.canPerformAction("markerDrag")&&t&&this.markerDragEnd(t),this._activeMarker=null,s.DomEvent.stopPropagation(e),setTimeout(()=>{this.isDraggingMarker=!1},10)});const f=p.getElement();if(f){const e=e=>{e.stopPropagation()},t=e=>{if(e.preventDefault(),e.stopPropagation(),p.fire("click"),this.isDraggingMarker&&!d){const e=this.markerFeatureGroupMap.get(p);this.modeManager.canPerformAction("markerDrag")&&e&&this.isFeatureGroupInActiveLayer(e)&&this.markerDragEnd(e)}this._activeMarker=null};f.addEventListener("touchstart",e,{passive:!0}),f.addEventListener("touchend",t),this.markerTouchListeners.set(p,{touchstart:e,touchend:t})}if(o===c||o===u||o===h){const e=p.getElement();e&&(e.style.zIndex="10000")}if(this.config.modes.dragElbow){const e=e=>()=>{this.modeManager.canPerformAction("markerDrag")&&this.isFeatureGroupInActiveLayer(e)&&this.markerDrag(e)};p.on("drag",e(t))}if(o===c&&i&&(p.options.zIndexOffset=this.config.markers.markerMenuIcon.zIndexOffset??this.config.markers.zIndexOffset,p.on("click",()=>{const r=e.map(e=>[e.lng,e.lat]);r.push(r[0]);const o={type:"Feature",properties:{},geometry:{type:"Polygon",coordinates:[r]}},n=ci.getCenterOfMass(o);this.generateMenuMarkerPopup(e,t).setLatLng(n).openOn(this.map)}),p.on("popupopen",e=>{const t=e.popup.getElement();if(!t)return;setTimeout(()=>{const e=this.map.getContainer().getBoundingClientRect(),r=t.getBoundingClientRect();r.left<e.left?t.style.transform=`translateX(${e.left-r.left}px)`:r.right>e.right&&(t.style.transform=`translateX(${e.right-r.right}px)`)},0);const r=this.map.getContainer();r&&(r.style.touchAction="manipulation")}),p.on("popupclose",()=>{const e=this.map.getContainer();e&&(e.style.touchAction="")})),o===h&&l){const o=e.map(e=>[e.lng,e.lat]);o.push(o[0]);const n={type:"Feature",properties:{},geometry:{type:"Polygon",coordinates:[o]}},i=this.turfHelper.getPolygonArea(n),a=1e3*this.turfHelper.getPolygonPerimeter(n);p.options.zIndexOffset=this.config.markers.markerInfoIcon.zIndexOffset??this.config.markers.zIndexOffset,p.on("click",()=>{if(!this.isFeatureGroupInActiveLayer(t))return;this.generateInfoMarkerPopup(i,a).setLatLng(r).openOn(this.map)})}p.on("mousedown",e=>{this.modeManager.isInOffMode()||(s.DomEvent.stopPropagation(e),this.map.fire("mousedown",e)),this._activeMarker=p}),p.on("click",e=>{if(this.isFeatureGroupInActiveLayer(t)&&this.modeManager.isInOffMode())if(this.isEdgeDeletionModifierKeyPressed(e.originalEvent)){const r=t.getLayers().find(e=>e instanceof s.Polygon);r&&this.elbowClicked(e,r,p.getLatLng())}else if(o===u&&a){this.map.closePopup();const e=t.getLayers().find(e=>e instanceof s.Polygon);if(e){const r=e.getLatLngs();let o=[];if(Array.isArray(r)&&r.length>0)if(Array.isArray(r[0])){const e=r[0];o=Array.isArray(e)&&Array.isArray(e[0])?r[0]:r}else o=[r];const n=p.getLatLng();let i=-1;for(let e=1;e<o.length;e++)if(o[e].some(e=>e.lat===n.lat&&e.lng===n.lng)){i=e;break}if(i>0){const e=o.filter((e,t)=>t!==i).map(e=>{const t=e.map(e=>[e.lng,e.lat]);if(t.length>0){const e=t[0],r=t[t.length-1];e[0]===r[0]&&e[1]===r[1]||t.push([e[0],e[1]])}return t}),{level:r,original:n}=this.getOptimizationMetadataFromFeatureGroup(t),a=this.getFeatureMetadataState(t),s=this.turfHelper.getMultiPolygon([e]);this.cleanupFeatureGroup(t),this.removeFeatureGroup(t),this.emitPolygonUpdated({operation:"removeHole",polygon:s,optimizationLevel:r,originalOptimizationLevel:n,featureId:a.featureId,featureMetadata:a.metadata,sourceFeatureIds:a.sourceFeatureIds,featureInteractionOverride:a.interactionOverride,featureStyleOverrides:a.styleOverrides,featureCreatedAt:a.createdAt})}}}}),p.on("mouseover",()=>{this.isFeatureGroupInActiveLayer(t)&&this.onMarkerHoverForEdgeDeletion(p,!0)}),p.on("mouseout",()=>{this.onMarkerHoverForEdgeDeletion(p,!1)})})}addEdgeClickListeners(e,t){const r=e.getLatLngs();let o;if(Array.isArray(r)&&r.length>0){if(Array.isArray(r[0]))if(Array.isArray(r[0][0])&&r[0][0].length>0){r[0][0][0];o=r[0]}else o=r[0][0]&&"object"==typeof r[0][0]&&"lat"in r[0][0]?r:r[0];else o=(r[0]&&"object"==typeof r[0]&&r[0],[r]);o.forEach((r,o)=>{for(let n=0;n<r.length;n++){const i=r[n],a=r[(n+1)%r.length];if(i.lat===a.lat&&i.lng===a.lng)continue;const s=oi.createPolyline([i,a],{color:"transparent",weight:10,opacity:0,interactive:!0});s._polydrawAuxiliaryLayer=!0,s._polydrawEdgeInfo={ringIndex:o,edgeIndex:n,startPoint:i,endPoint:a,parentPolygon:e,parentFeatureGroup:t},s.on("click",e=>{this.onEdgeClick(e,s)}),s.on("mouseover",()=>{this.highlightEdgeOnHover(s,!0)}),s.on("mouseout",()=>{this.highlightEdgeOnHover(s,!1)}),t.addLayer(s)}})}}isPolygonDragModeActive(){const e=this.modeManager.getCurrentMode();return e===c.Off||e===c.Clone}isPolygonDragActive(){return!!(this.currentDragPolygon&&this.currentDragPolygon._polydrawDragData&&this.currentDragPolygon._polydrawDragData.isDragging)}isPolygonInActiveLayer(e){if(!this.layerManager)return!0;const t=this.polygonFeatureGroupMap.get(e);if(t)return this.layerManager.isInActiveLayer(t)&&this.layerManager.isFeatureGroupEditable(t);const r=this.findFeatureGroupForPolygon(e);return!r||(this.polygonFeatureGroupMap.set(e,r),this.layerManager.isInActiveLayer(r)&&this.layerManager.isFeatureGroupEditable(r))}isFeatureGroupInActiveLayer(e){return!this.layerManager||this.layerManager.isInActiveLayer(e)&&this.layerManager.isFeatureGroupEditable(e)}enablePolygonDragging(e,t){if(this.config.modes.dragPolygons||this.config.tools.clone){if(e._polydrawOriginalLatLngs=t,e._polydrawDragData={isDragging:!1,startPosition:null,startLatLngs:null,originalOpacity:e.options.fillOpacity},e.on("mousedown",t=>{if(this.transformModeActive)return;if(!this.isPolygonInActiveLayer(e))return;if(!this.isPolygonDragModeActive())return s.DomEvent.stopPropagation(t),void this.map.fire("mousedown",t);if(!this.modeManager.canPerformAction("polygonDrag"))return;s.DomEvent.stopPropagation(t.originalEvent),s.DomEvent.preventDefault(t.originalEvent);const r=this.modeManager.getCurrentMode()===c.Clone,o=!r&&this.detectDragSubtractModifierKey(t.originalEvent);this.currentDragIsClone=r,this.currentModifierDragMode=o,this.isModifierKeyHeld=o,this.saveHistoryState&&this.saveHistoryState(r?"polygonClone":"polygonDrag"),e._polydrawDragData.isDragging=!0,e._polydrawDragData.startPosition=t.latlng,e._polydrawDragData.startLatLngs=e.getLatLngs(),e.setStyle({fillOpacity:this.config.interaction.drag.opacity}),r?this.showCloneGhost(e._polydrawDragData.startLatLngs):this.clearCloneGhost(),this.map.dragging&&this.map.dragging.disable(),this.setSubtractVisualMode(e,o),this.setMarkerVisibility(e,!1);try{this.map.getContainer().style.cursor=this.config.interaction.drag.dragCursor||"move"}catch{}this.attachDragDocumentListeners(),this.attachDragCancelHandlers(),this.currentDragPolygon=e}),e.on("pointerdown",t=>{const r=t;if(this.transformModeActive)return;if(!this.isPolygonInActiveLayer(e))return;if(!this.isPolygonDragModeActive()){const e=r.originalEvent??r;return s.DomEvent.stopPropagation(e),void this.map.fire("pointerdown",r)}if(!this.modeManager.canPerformAction("polygonDrag"))return;const o=r.originalEvent??r;s.DomEvent.stopPropagation(o),s.DomEvent.preventDefault(o);const n=this.modeManager.getCurrentMode()===c.Clone,i=!n&&this.detectDragSubtractModifierKey(o);this.currentDragIsClone=n,this.currentModifierDragMode=i,this.isModifierKeyHeld=i,this.saveHistoryState&&this.saveHistoryState(n?"polygonClone":"polygonDrag"),e._polydrawDragData.isDragging=!0,e._polydrawDragData.startPosition=r.latlng,e._polydrawDragData.startLatLngs=e.getLatLngs(),e.setStyle({fillOpacity:this.config.interaction.drag.opacity}),n?this.showCloneGhost(e._polydrawDragData.startLatLngs):this.clearCloneGhost(),this.map.dragging&&this.map.dragging.disable(),this.setSubtractVisualMode(e,i),this.setMarkerVisibility(e,!1);try{this.map.getContainer().style.cursor=this.config.interaction.drag.dragCursor||"move"}catch{}this.attachDragDocumentListeners(),this.attachDragCancelHandlers(),this.currentDragPolygon=e}),ri.isV1()){const t=t=>{if(this.transformModeActive)return;if(!this.isPolygonInActiveLayer(e))return;if(!this.isPolygonDragModeActive())return;if(!this.modeManager.canPerformAction("polygonDrag"))return;t.stopPropagation(),t.preventDefault();const r=bi.extractCoordinates(t,this.map);if(!r)return;const o=this.modeManager.getCurrentMode()===c.Clone;this.currentDragIsClone=o,this.currentModifierDragMode=!1,this.isModifierKeyHeld=!1,this.saveHistoryState&&this.saveHistoryState(o?"polygonClone":"polygonDrag"),e._polydrawDragData.isDragging=!0,e._polydrawDragData.startPosition=r,e._polydrawDragData.startLatLngs=e.getLatLngs(),e.setStyle({fillOpacity:this.config.interaction.drag.opacity}),o?this.showCloneGhost(e._polydrawDragData.startLatLngs):this.clearCloneGhost(),this.map.dragging&&this.map.dragging.disable(),this.setSubtractVisualMode(e,!1),this.setMarkerVisibility(e,!1);try{this.map.getContainer().style.cursor=this.config.interaction.drag.dragCursor||"move"}catch{}this.attachDragTouchListeners(),this.attachDragDocumentListeners(),this.attachDragCancelHandlers(),this.currentDragPolygon=e};this.polygonTouchStartListeners.set(e,t);const r=()=>{const r=e._path;r&&r.addEventListener("touchstart",t,{passive:!1})};e._path?r():e.once("add",r)}e.on("mouseover",()=>{if(this.isPolygonInActiveLayer(e)&&(!e._polydrawDragData||!e._polydrawDragData.isDragging))try{this.map.getContainer().style.cursor=this.config.interaction.drag.hoverCursor||"grab"}catch{}}),e.on("mouseout",()=>{if(!e._polydrawDragData||!e._polydrawDragData.isDragging)try{this.map.getContainer().style.cursor=""}catch{}})}}updateMarkerDraggableState(){const e=this.modeManager.canPerformAction("markerDrag");this.getFeatureGroups().forEach(t=>{const r=this.isFeatureGroupInActiveLayer(t),o=e&&r;t.eachLayer(e=>{if(e instanceof s.Marker){const t=e;try{t.options.draggable=o,t.dragging&&(o?t.dragging.enable():t.dragging.disable())}catch{}}})})}updateAllMarkersForEdgeDeletion(e){this.getFeatureGroups().forEach(t=>{t.eachLayer(t=>{t instanceof s.Marker&&this.updateMarkerForEdgeDeletion(t,e)})})}updateMarkerForEdgeDeletion(e,t){const r=e.getElement();r&&(t?(r.addEventListener("mouseenter",this.onMarkerHoverForEdgeDeletionEvent),r.addEventListener("mouseleave",this.onMarkerLeaveForEdgeDeletionEvent),this.markerEdgeDeletionListeners.set(e,{mouseenter:this.onMarkerHoverForEdgeDeletionEvent,mouseleave:this.onMarkerLeaveForEdgeDeletionEvent})):(r.removeEventListener("mouseenter",this.onMarkerHoverForEdgeDeletionEvent),r.removeEventListener("mouseleave",this.onMarkerLeaveForEdgeDeletionEvent),r.style.backgroundColor="",r.style.borderColor="",this.markerEdgeDeletionListeners.delete(e)))}setModifierKeyHeld(e){this.isModifierKeyHeld=e}cleanupMarker(e){const t=e.getElement(),r=this.markerModifierHandlers.get(e);r&&(document.removeEventListener("keydown",r),document.removeEventListener("keyup",r),t&&t.removeEventListener("mousemove",r),this.markerModifierHandlers.delete(e));const o=this.markerTouchListeners.get(e);o&&(t&&(t.removeEventListener("touchstart",o.touchstart),t.removeEventListener("touchend",o.touchend)),this.markerTouchListeners.delete(e));const n=this.markerEdgeDeletionListeners.get(e);n&&(t&&(t.removeEventListener("mouseenter",n.mouseenter),t.removeEventListener("mouseleave",n.mouseleave)),this.markerEdgeDeletionListeners.delete(e)),this.markerFeatureGroupMap.delete(e)}cleanupFeatureGroup(e){e.eachLayer(e=>{e instanceof s.Marker?this.cleanupMarker(e):e instanceof s.Polygon&&(this.detachPolygonTouchStart(e),this.polygonFeatureGroupMap.delete(e))}),this.destroyTransformController(e)}destroyTransformController(e){const t=this.transformControllers.get(e);t&&(t.destroy(),this.transformControllers.delete(e),this.transformModeActive=!1)}onEdgeClick(e,t){if(!this.config.modes.attachElbow)return;if(!this.modeManager.isInOffMode())return;const r=t._polydrawEdgeInfo;if(!r)return;if(r.parentFeatureGroup&&!this.isFeatureGroupInActiveLayer(r.parentFeatureGroup))return;const o=e.latlng,n=r.parentPolygon,i=r.parentFeatureGroup;if(n&&i)try{if("function"!=typeof n.toGeoJSON)return;const e=n.toGeoJSON();if("MultiPolygon"===e.geometry.type||"Polygon"===e.geometry.type){const t=this.turfHelper.injectPointToPolygon(e,[o.lng,o.lat],r.ringIndex);if(t){const e=n,r=e._polydrawOptimizationLevel||0,o=e._polydrawOptimizationOriginalLevel||r,a=this.getFeatureMetadataState(i);this.cleanupFeatureGroup(i),this.removeFeatureGroup(i),this.emitPolygonUpdated({operation:"addVertex",polygon:t,optimizationLevel:r,originalOptimizationLevel:o,featureId:a.featureId,featureMetadata:a.metadata,sourceFeatureIds:a.sourceFeatureIds,featureInteractionOverride:a.interactionOverride,featureStyleOverrides:a.styleOverrides,featureCreatedAt:a.createdAt})}}}catch{}s.DomEvent.stopPropagation(e)}highlightEdgeOnHover(e,t){t?e.setStyle({color:this.config.styles.ui.edgeHover.color,weight:4,opacity:1}):e.setStyle({color:"transparent",weight:10,opacity:0})}deriveImportantMarkerIndices(e,t){const r=new Set;if(!e||0===e.length)return r;const o=Math.min(Math.max(t.optimizationLevel??0,0),10),n=e.length>2&&this.latLngEquals(e[0],e[e.length-1]),i=n?e.slice(0,-1):[...e],a=i.length,s=t=>{if(null==t||t<0)return;let o=t;n&&t===e.length-1&&(o=0),o>=a&&(o=a>0?o%a:0),o>=0&&o<a&&r.add(o)};if(s(0),s(t.menuIndex),s(t.deleteIndex),s(t.infoIndex),0===a||o<=0||a<=3){for(let e=0;e<a;e++)r.add(e);return r}const l=this.getToleranceForOptimizationLevel(o);let c=l>0?this.turfHelper.simplifyLatLngRing(i,l,!0):[...i];if(c.length>1&&this.latLngEquals(c[0],c[c.length-1])&&(c=c.slice(0,-1)),!c||0===c.length){for(let e=0;e<a;e++)r.add(e);return r}if(c.forEach(e=>{const t=this.findClosestVertexIndex(e,i);null!==t&&r.add(t)}),0===r.size)for(let u=0;u<a;u++)r.add(u);return r}normalizeMarkerIndex(e,t,r){if(null==e||e<0)return null;if(r){const r=Math.max(1,t-1);return e===t-1?0:e>=r?e%r:e}return e>=t?t>0?t-1:null:e}latLngEquals(e,t){return!(!e||!t)&&(Math.abs(e.lat-t.lat)<1e-9&&Math.abs(e.lng-t.lng)<1e-9)}isLatLngLiteral(e){return!!e&&"object"==typeof e&&"lat"in e&&"lng"in e&&"number"==typeof e.lat&&"number"==typeof e.lng}getOrderedMarkers(e){const t=[];return e.eachLayer(e=>{e instanceof s.Marker&&t.push(e)}),t.sort((e,t)=>oi.util.stamp(e)-oi.util.stamp(t))}countLatLngNodes(e){return Array.isArray(e)?0===e.length?0:this.isLatLngLiteral(e[0])?e.length:e.reduce((e,t)=>e+this.countLatLngNodes(t),0):0}rebuildLatLngStructure(e,t,r){if(!Array.isArray(e))return e;if(e.length>0&&this.isLatLngLiteral(e[0])){const o=e,n=o.length>1&&this.latLngEquals(o[0],o[o.length-1]),i=o.map((e,n)=>{const i=t[r.value]??o[n];return r.value+=1,oi.createLatLng(i.lat,i.lng)});return n&&i.length>1&&(i[i.length-1]=i[0]),i}return e.map(e=>this.rebuildLatLngStructure(e,t,r))}getOptimizationMetadataFromFeatureGroup(e){let t=0,r=0;return e.eachLayer(e=>{if(e instanceof s.Polygon){const o=e;"number"==typeof o._polydrawOptimizationLevel&&(t=o._polydrawOptimizationLevel||0),"number"==typeof o._polydrawOptimizationOriginalLevel&&(r=o._polydrawOptimizationOriginalLevel||0)}}),!r&&t>0&&(r=t),{level:t,original:r}}getFeatureMetadataState(e){if(!e)return{};const t=e._polydrawMetadata,r=(null==t?void 0:t.createdAt)instanceof Date&&!Number.isNaN(t.createdAt.getTime())?t.createdAt.toISOString():void 0;return{featureId:null==t?void 0:t.id,metadata:(null==t?void 0:t.metadata)?{...t.metadata}:void 0,sourceFeatureIds:Array.isArray(null==t?void 0:t.sourceFeatureIds)?[...t.sourceFeatureIds]:(null==t?void 0:t.id)?[t.id]:void 0,interactionOverride:null==t?void 0:t.interactionOverride,styleOverrides:(null==t?void 0:t.styleOverrides)?{...t.styleOverrides}:void 0,createdAt:r}}getOptimizationMetadataFromPolygonLayer(e){if(!e)return{level:0,original:0};const t=e,r=t._polydrawOptimizationLevel||0;return{level:r,original:t._polydrawOptimizationOriginalLevel||(r>0?r:0)}}getDistanceMeters(e,t){try{const r=oi.createLatLng(e.lat,e.lng),o=oi.createLatLng(t.lat,t.lng);if("function"==typeof r.distanceTo)return r.distanceTo(o)}catch{}const r=e=>e*Math.PI/180,o=r(t.lat-e.lat),n=r(t.lng-e.lng),i=r(e.lat),a=r(t.lat),s=Math.sin(o/2)*Math.sin(o/2)+Math.sin(n/2)*Math.sin(n/2)*Math.cos(i)*Math.cos(a);return 6371e3*(2*Math.atan2(Math.sqrt(s),Math.sqrt(1-s)))}findClosestVertexIndex(e,t){if(!t||0===t.length)return null;let r=0,o=Number.POSITIVE_INFINITY;for(let n=0;n<t.length;n++){const i=this.getDistanceMeters(e,t[n]);if(i<o&&(o=i,r=n,0===i))break}return r}getToleranceForOptimizationLevel(e){const t=Math.min(Math.max(e,0),10)/10,r=this.config.markers.visualOptimization??{},o=Math.max(r.toleranceMin??5e-6,0),n=Math.max(r.toleranceMax??.005,o),i=r.curve??1.35;return o+(n-o)*Math.pow(t,i)}elbowClicked(e,t,r){if(!this.config.modes.edgeDeletion)return;if(!this.isEdgeDeletionModifierKeyPressed(e.originalEvent))return;const o=r??e.latlng,n=t.getLatLngs();let i=[];if(!(Array.isArray(n)&&n.length>0))return;if(Array.isArray(n[0])){const e=n[0];i=Array.isArray(e)&&Array.isArray(e[0])?n[0]:n}else i=[n];let a=-1,s=-1;for(let f=0;f<i.length;f++){const e=i[f];for(let t=0;t<e.length;t++){const r=e[t];if(r.lat===o.lat&&r.lng===o.lng){a=f,s=t;break}}if(-1!==a)break}if(-1===a||-1===s)return;if(i[a].length<=this.config.interaction.edgeDeletion.minVertices)return;const l=i.map((e,t)=>{if(t!==a)return e.slice();const r=e.slice();return r.splice(s,1),r}).map(e=>{const t=e.map(e=>[e.lng,e.lat]);if(t.length>0){const e=t[0],r=t[t.length-1];e[0]===r[0]&&e[1]===r[1]||t.push([e[0],e[1]])}return t});let c=null;for(const f of this.getFeatureGroups()){let e=!1;if(f.eachLayer(r=>{r===t&&(e=!0)}),e){c=f;break}}const u=c?this.getOptimizationMetadataFromFeatureGroup(c):this.getOptimizationMetadataFromPolygonLayer(t),h=this.getFeatureMetadataState(c??void 0),{level:g,original:d}=u;c&&this.removeFeatureGroup(c);const p=this.turfHelper.getMultiPolygon([l]);this.emitPolygonUpdated({operation:"removeVertex",polygon:p,optimizationLevel:g,originalOptimizationLevel:d,featureId:h.featureId,featureMetadata:h.metadata,sourceFeatureIds:h.sourceFeatureIds,featureInteractionOverride:h.interactionOverride,featureStyleOverrides:h.styleOverrides,featureCreatedAt:h.createdAt})}markerDrag(e){if(!this._activeMarker)return void(Wn()||console.warn("No active marker set for dragging."));const t=e.getLayers().find(e=>e instanceof s.Polygon);if(!t)return void(Wn()||console.warn("No polygon found in feature group for marker drag."));const r=this.getOrderedMarkers(e);if(0===r.length)return;const o=r.map(e=>e.getLatLng()),n=this.countLatLngNodes(t.getLatLngs());if(o.length<n)return void(Wn()||console.warn("Not enough markers to rebuild polygon during drag. Expected:",n,"got:",o.length));const i=this.rebuildLatLngStructure(t.getLatLngs(),o,{value:0});t.setLatLngs(i)}async markerDragEnd(e){var t;this.polygonInformation.deletePolygonInformationStorage();const r=e.toGeoJSON();if(!r.features||0===r.features.length)return;const{level:o,original:n}=this.getOptimizationMetadataFromFeatureGroup(e),i=this.getFeatureMetadataState(e),a=null==(t=this.layerManager)?void 0:t.getLayerForFeatureGroup(e);this.cleanupFeatureGroup(e),this.removeFeatureGroup(e);const s=(e,t,r)=>{const o=this.turfHelper.removeDuplicateVertices(e),n=[];if(!this.config.kinks)try{const e=this.turfHelper.getKinks(o);e&&e.length>0&&n.push(...e)}catch{}0===n.length&&("MultiPolygon"===o.geometry.type?o.geometry.coordinates.forEach(e=>n.push(this.turfHelper.getMultiPolygon([e]))):n.push(o)),n.forEach(e=>{this.emitPolygonUpdated({operation:"markerDrag",polygon:e,allowMerge:t,optimizationLevel:r.optimizationLevel,originalOptimizationLevel:r.originalOptimizationLevel,featureId:i.featureId,featureMetadata:i.metadata,sourceFeatureIds:i.sourceFeatureIds,featureInteractionOverride:i.interactionOverride,featureStyleOverrides:i.styleOverrides,targetLayerId:a,featureCreatedAt:i.createdAt})})};if("MultiPolygon"===r.features[0].geometry.type)for(const l of r.features[0].geometry.coordinates){s(this.turfHelper.getMultiPolygon([l]),!0,{optimizationLevel:o,originalOptimizationLevel:n})}else{s(this.turfHelper.getMultiPolygon([r.features[0].geometry.coordinates]),!0,{optimizationLevel:o,originalOptimizationLevel:n})}this.polygonInformation.createPolygonInformationStorage(this.getFeatureGroups())}attachDragDocumentListeners(){if(this.detachDragDocumentListeners(),this.dragUsesPointerEvents=bi.shouldUsePointerEvents(),this._boundDragMoveListener=this.onDragDocumentMove,this._boundDragEndListener=this.onDragDocumentEnd,this.dragUsesPointerEvents)return document.addEventListener("pointermove",this._boundDragMoveListener),void document.addEventListener("pointerup",this._boundDragEndListener);document.addEventListener("mousemove",this._boundDragMoveListener),document.addEventListener("mouseup",this._boundDragEndListener)}detachDragDocumentListeners(){this._boundDragMoveListener&&(this.dragUsesPointerEvents?document.removeEventListener("pointermove",this._boundDragMoveListener):document.removeEventListener("mousemove",this._boundDragMoveListener),this._boundDragMoveListener=null),this._boundDragEndListener&&(this.dragUsesPointerEvents?document.removeEventListener("pointerup",this._boundDragEndListener):document.removeEventListener("mouseup",this._boundDragEndListener),this._boundDragEndListener=null),this.dragUsesPointerEvents=!1}attachDragTouchListeners(){this.detachDragTouchListeners(),this._boundDragTouchMove=this.onDragTouchMove,this._boundDragTouchEnd=this.onDragTouchEnd;const e=this.map.getContainer();e.addEventListener("touchmove",this._boundDragTouchMove,{passive:!1}),e.addEventListener("touchend",this._boundDragTouchEnd,{passive:!1})}detachDragTouchListeners(){const e=this.map.getContainer();this._boundDragTouchMove&&(e.removeEventListener("touchmove",this._boundDragTouchMove),this._boundDragTouchMove=null),this._boundDragTouchEnd&&(e.removeEventListener("touchend",this._boundDragTouchEnd),this._boundDragTouchEnd=null)}detachPolygonTouchStart(e){const t=this.polygonTouchStartListeners.get(e);if(!t)return;const r=e._path;r&&r.removeEventListener("touchstart",t),this.polygonTouchStartListeners.delete(e)}attachDragCancelHandlers(){this.dragCancelHandlersAttached||(this.dragCancelHandlersAttached=!0,document.addEventListener("keydown",this.onPolygonDragKeyDown),this.map.on("pointercancel",this.onPolygonDragCancel,this),this.map.on("touchcancel",this.onPolygonDragCancel,this))}detachDragCancelHandlers(){this.dragCancelHandlersAttached&&(this.dragCancelHandlersAttached=!1,document.removeEventListener("keydown",this.onPolygonDragKeyDown),this.map.off("pointercancel",this.onPolygonDragCancel,this),this.map.off("touchcancel",this.onPolygonDragCancel,this))}cancelActivePolygonDrag(){if(!this.currentDragPolygon||!this.currentDragPolygon._polydrawDragData)return this.clearCloneGhost(),void this.detachDragDocumentListeners();const e=this.currentDragPolygon,t=e._polydrawDragData;if(!t)return this.clearCloneGhost(),void this.detachDragDocumentListeners();if(!t.isDragging)return this.clearCloneGhost(),void this.detachDragDocumentListeners();t.isDragging=!1,this.map.dragging&&this.map.dragging.enable(),t.startLatLngs&&e.setLatLngs(t.startLatLngs),e._polydrawOriginalMarkerPositions&&(e._polydrawOriginalMarkerPositions.forEach((e,t)=>{t.setLatLng(e)}),e._polydrawOriginalMarkerPositions.clear(),delete e._polydrawOriginalMarkerPositions),e._polydrawOriginalHoleLinePositions&&(e._polydrawOriginalHoleLinePositions.forEach((e,t)=>{t.setLatLngs(e)}),e._polydrawOriginalHoleLinePositions.clear(),delete e._polydrawOriginalHoleLinePositions),e._polydrawCurrentDragSession&&delete e._polydrawCurrentDragSession,null!=t.originalOpacity&&e.setStyle({fillOpacity:t.originalOpacity}),this.setSubtractVisualMode(e,!1),this.setMarkerVisibility(e,!0);try{this.map.getContainer().style.cursor=""}catch{}this.clearCloneGhost(),this.detachDragTouchListeners(),this.detachDragDocumentListeners(),this.detachDragCancelHandlers(),this.currentDragIsClone=!1,this.currentModifierDragMode=!1,this.isModifierKeyHeld=!1,this.currentDragPolygon=null}offsetPolygonCoordinates(e,t,r){return e?Array.isArray(e[0])?e.map(e=>this.offsetPolygonCoordinates(e,t,r)):e.map(e=>oi.createLatLng(e.lat+t,e.lng+r)):e}updateMarkersAndHoleLinesDuringDrag(e,t,r){try{let o=null;for(const t of this.getFeatureGroups()){let r=!1;if(t.eachLayer(t=>{t===e&&(r=!0)}),r){o=t;break}}if(!o)return;const n="_polydrawDragSession_"+Date.now()+"_"+oi.util.stamp(e);e._polydrawCurrentDragSession||(e._polydrawCurrentDragSession=n,e._polydrawOriginalMarkerPositions=new Map,e._polydrawOriginalHoleLinePositions=new Map,o.eachLayer(t=>{if(t instanceof s.Marker)e._polydrawOriginalMarkerPositions.set(t,t.getLatLng());else if(t instanceof s.Polyline&&!(t instanceof s.Polygon)){const r=t.getLatLngs();e._polydrawOriginalHoleLinePositions.set(t,r)}})),o.eachLayer(o=>{if(o instanceof s.Marker){const n=e._polydrawOriginalMarkerPositions.get(o);if(n){const e={lat:n.lat+t,lng:n.lng+r};o.setLatLng(e)}}else if(o instanceof s.Polyline&&!(o instanceof s.Polygon)){const n=e._polydrawOriginalHoleLinePositions.get(o);if(n){let e;e=Array.isArray(n[0])?n.map(e=>e.map(e=>oi.createLatLng(e.lat+t,e.lng+r))):n.map(e=>oi.createLatLng(e.lat+t,e.lng+r)),o.setLatLngs(e)}}})}catch(o){console.warn("Error updating markers during drag:",o)}}async updatePolygonAfterDrag(e){try{let t=null;for(const s of this.getFeatureGroups())if(s.eachLayer(r=>{r===e&&(t=s)}),t)break;if(!t)return;const r=e.toGeoJSON();if(this.isModifierDragActive())return this.performModifierSubtract(r,t),this.currentModifierDragMode=!1,void(this.isModifierKeyHeld=!1);const{level:o,original:n}=this.getOptimizationMetadataFromFeatureGroup(t),i=this.getFeatureMetadataState(t);this.cleanupFeatureGroup(t),this.removeFeatureGroup(t);const a=this.turfHelper.getTurfPolygon(r);this.emitPolygonUpdated({operation:"polygonDrag",polygon:a,allowMerge:!0,optimizationLevel:o,originalOptimizationLevel:n,featureId:i.featureId,featureMetadata:i.metadata,sourceFeatureIds:i.sourceFeatureIds,featureInteractionOverride:i.interactionOverride,featureStyleOverrides:i.styleOverrides,featureCreatedAt:i.createdAt}),this.polygonInformation.createPolygonInformationStorage(this.getFeatureGroups())}catch{}}updatePolygonAfterCloneDrag(e,t){try{let r=null;for(const t of this.getFeatureGroups())if(t.eachLayer(o=>{o===e&&(r=t)}),r)break;if(!r)return;const o=e.toGeoJSON(),n=(null==t?void 0:t.startLatLngs)??null,i=n?this.createPolygonFeatureFromLatLngs(n):null,{level:a,original:s}=this.getOptimizationMetadataFromFeatureGroup(r),l=this.getFeatureMetadataState(r);this.cleanupFeatureGroup(r),this.removeFeatureGroup(r);const c=this.turfHelper.getTurfPolygon(o);if(this.emitPolygonUpdated({operation:"polygonDrag",polygon:c,allowMerge:!0,optimizationLevel:a,originalOptimizationLevel:s,featureId:l.featureId,featureMetadata:l.metadata,sourceFeatureIds:l.sourceFeatureIds,featureInteractionOverride:l.interactionOverride,featureStyleOverrides:l.styleOverrides,featureCreatedAt:l.createdAt}),i){const e=this.turfHelper.getTurfPolygon(i);this.emitPolygonUpdated({operation:"polygonClone",polygon:e,allowMerge:!0,optimizationLevel:a,originalOptimizationLevel:s,featureId:l.featureId,featureMetadata:l.metadata,sourceFeatureIds:l.sourceFeatureIds,featureInteractionOverride:l.interactionOverride,featureStyleOverrides:l.styleOverrides,featureCreatedAt:l.createdAt})}this.polygonInformation.createPolygonInformationStorage(this.getFeatureGroups())}catch{}finally{this.currentModifierDragMode=!1,this.isModifierKeyHeld=!1}}showCloneGhost(e){if(this.clearCloneGhost(),e)try{const t=oi.createPolygon(e,{color:this.config.styles.polygon.color,weight:this.config.styles.polygon.weight,opacity:.9,fill:!1,fillOpacity:0,dashArray:"4,6",interactive:!1});t.addTo(this.map),this.currentCloneGhost=t}catch{}}clearCloneGhost(){if(this.currentCloneGhost){try{this.map.removeLayer(this.currentCloneGhost)}catch{}this.currentCloneGhost=null}}createPolygonFeatureFromLatLngs(e){try{return oi.createPolygon(e).toGeoJSON()}catch{return null}}getDragSubtractModifierKey(){const{keys:e}=this.config.interaction.drag.modifierSubtract,t=navigator.userAgent.toLowerCase(),r=t.includes("mac"),o=t.includes("windows");return r&&e.mac?e.mac:o&&e.windows?e.windows:e.linux?e.linux:r?"metaKey":"ctrlKey"}detectDragSubtractModifierKey(e){if(jn())return!1;return e[this.getDragSubtractModifierKey()]||!1}setSubtractVisualMode(e,t){if(e&&e.setStyle)try{t?e.setStyle({color:this.config.styles.ui.dragSubtract.color}):e.setStyle({color:this.config.styles.polygon.color}),this.updateMarkerColorsForSubtractMode(e,t)}catch{}}updateMarkerColorsForSubtractMode(e,t){try{let r=null;for(const t of this.getFeatureGroups())if(t.eachLayer(o=>{o===e&&(r=t)}),r)break;if(!r)return;const o=r,n=this.config.interaction.drag.modifierSubtract.hideMarkersOnDrag;o.eachLayer(e=>{if(e instanceof s.Marker){const r=e.getElement();r&&(t?n?(r.style.display="none",r.classList.add("subtract-mode-hidden")):(r.style.backgroundColor=this.config.styles.ui.dragSubtract.color,r.style.borderColor=this.config.styles.ui.dragSubtract.color,r.classList.add("subtract-mode")):n?(r.style.display="",r.classList.remove("subtract-mode-hidden")):(r.style.backgroundColor="",r.style.borderColor="",r.classList.remove("subtract-mode")))}})}catch{}}handleModifierToggleDuringDrag(e){const t=this.detectDragSubtractModifierKey(e);this.currentModifierDragMode=t,this.isModifierKeyHeld=t,this.currentDragPolygon&&this.setSubtractVisualMode(this.currentDragPolygon,t)}isModifierDragActive(){return this.currentModifierDragMode}performModifierSubtract(e,t){var r;try{const o=this.turfHelper.getTurfPolygon(e),n=[],i=null==(r=this.layerManager)?void 0:r.getLayerForFeatureGroup(t);this.getFeatureGroups().forEach(e=>{if(e!==t){if(i&&this.layerManager){if(this.layerManager.getLayerForFeatureGroup(e)!==i)return}try{const t=e.toGeoJSON();if(!t||!t.features||!t.features[0])return;const r=t.features[0];if(!r.geometry||!r.geometry.coordinates)return;const i=this.turfHelper.getTurfPolygon(r);try{const t=this.turfHelper.getIntersection(i,o);if(t&&t.geometry&&"coordinates"in t.geometry){t.geometry.coordinates.length>0&&n.push(e)}}catch{try{this.turfHelper.polygonIntersect(i,o)&&n.push(e)}catch{}}}catch{}}}),this.removeFeatureGroup(t),n.forEach(e=>{try{const r=e.toGeoJSON(),n=this.turfHelper.getTurfPolygon(r.features[0]),{level:i,original:a}=this.getOptimizationMetadataFromFeatureGroup(e),s=this.getFeatureMetadataState(e);this.cleanupFeatureGroup(e),this.removeFeatureGroup(e);try{const e=this.turfHelper.polygonDifference(n,o);if(e&&e.geometry){const t=this.turfHelper.getCoords(e);for(const e of t){const t=this.turfHelper.getMultiPolygon([e]);this.emitPolygonUpdated({operation:"modifierSubtract",polygon:this.turfHelper.getTurfPolygon(t),allowMerge:!1,optimizationLevel:i,originalOptimizationLevel:a,featureId:s.featureId,featureMetadata:s.metadata,sourceFeatureIds:s.sourceFeatureIds,featureInteractionOverride:s.interactionOverride,featureStyleOverrides:s.styleOverrides,featureCreatedAt:s.createdAt})}}}catch(t){Wn()||console.warn("Failed to perform difference operation:",t),this.emitPolygonUpdated({operation:"modifierSubtractFallback",polygon:n,allowMerge:!1,optimizationLevel:i,originalOptimizationLevel:a,featureId:s.featureId,featureMetadata:s.metadata,sourceFeatureIds:s.sourceFeatureIds,featureInteractionOverride:s.interactionOverride,featureStyleOverrides:s.styleOverrides,featureCreatedAt:s.createdAt})}}catch(r){Wn()||console.warn("Error in modifier subtract operation:",r)}}),this.polygonInformation.createPolygonInformationStorage(this.getFeatureGroups())}catch(o){Wn()||console.warn("Error in performModifierSubtract:",o)}}getEdgeDeletionModifierKey(){const{keys:e}=this.config.interaction.edgeDeletion,t=navigator.userAgent.toLowerCase(),r=t.includes("mac"),o=t.includes("windows");return r&&e.mac?e.mac:o&&e.windows?e.windows:e.linux?e.linux:r?"metaKey":"ctrlKey"}isEdgeDeletionModifierKeyPressed(e){if(jn())return!1;return!!e[this.getEdgeDeletionModifierKey()]}registerPolygonLayerMappings(e){e.eachLayer(t=>{t instanceof s.Polygon&&this.polygonFeatureGroupMap.set(t,e)})}findFeatureGroupForPolygon(e){for(const t of this.getFeatureGroups()){let r=!1;if(t.eachLayer(t=>{r||t!==e||(r=!0)}),r)return t}}onMarkerHoverForEdgeDeletion(e,t){const r=e.getElement();if(r)if(t){const t=e=>{if(this.isEdgeDeletionModifierKeyPressed(e)){r.style.backgroundColor=this.config.styles.ui.edgeDeletion.color,r.style.borderColor=this.config.styles.ui.edgeDeletion.color,r.classList.add("edge-deletion-hover");try{this.map.getContainer().style.cursor="pointer"}catch{}}else{r.style.backgroundColor="",r.style.borderColor="",r.classList.remove("edge-deletion-hover");try{this.map.getContainer().style.cursor=""}catch{}}};t(new MouseEvent("mouseover")),this.markerModifierHandlers.set(e,t),document.addEventListener("keydown",t),document.addEventListener("keyup",t),r.addEventListener("mousemove",t)}else{r.style.backgroundColor="",r.style.borderColor="",r.classList.remove("edge-deletion-hover");try{this.map.getContainer().style.cursor=""}catch{}const t=this.markerModifierHandlers.get(e);t&&(document.removeEventListener("keydown",t),document.removeEventListener("keyup",t),r.removeEventListener("mousemove",t),this.markerModifierHandlers.delete(e))}}getMarkerIndex(e,t){const r=$n.getBounds(e,Math.sqrt(2)/2),o=new Kn(r.getSouth(),r.getWest(),r.getNorth(),r.getEast()).getDirection(t),n={lat:o.lat,lng:o.lng},i=this.turfHelper.getCoord(n),a=this.turfHelper.getFeaturePointCollection(e);return this.turfHelper.getNearestPointIndex(i,a)}ensureMarkerSeparation(e,t){const r=[];if(t.menu.enabled&&r.push({type:"menu",index:t.menu.index}),t.delete.enabled&&r.push({type:"delete",index:t.delete.index}),t.info.enabled&&r.push({type:"info",index:t.info.index}),r.length<2)return{menu:t.menu.index,delete:t.delete.index,info:t.info.index};const o={...t},n=new Set,i=["info","delete","menu"];for(const a of i){const t=o[a];if(t.enabled)if(n.has(t.index)){const r=this.findAlternativeMarkerPosition(e,t.index,n);o[a].index=r,n.add(r)}else n.add(t.index)}return{menu:o.menu.index,delete:o.delete.index,info:o.info.index}}findAlternativeMarkerPosition(e,t,r){const o=e,n=Math.max(1,Math.floor(e/8));for(let i=1;i<o;i++){const o=[(t+i*n)%e,(t-i*n+e)%e];for(const e of o)if(!r.has(e))return e}for(let i=0;i<e;i++)if(!r.has(i))return i;return t}createDivIcon(e){return Mi.createDivIcon(e)}getLatLngInfoString(e){return"Latitude: "+e.lat+" Longitude: "+e.lng}setMarkerVisibility(e,t){const r=this.getFeatureGroups().find(t=>t.hasLayer(e));r&&r.eachLayer(e=>{if(e instanceof s.Marker){const r=e.getElement();if(r){const e=this.config.interaction.drag.markerBehavior,o=this.config.interaction.drag.markerAnimationDuration;"hide"===e?r.style.display=t?"":"none":"fade"===e&&(r.style.transition=`opacity ${o}ms ease`,r.style.opacity=t?"1":"0")}}})}setTransformAuxiliaryVisibility(e,t){const r=this.getPolygonLayer(e);r&&this.setMarkerVisibility(r,t),e.eachLayer(e=>{var r;if(!this.isPolydrawAuxiliaryPolyline(e))return;const o=null==(r=e.getElement)?void 0:r.call(e);return o?t?void(this.transformAuxiliaryDisplayValues.has(e)&&(o.style.display=this.transformAuxiliaryDisplayValues.get(e)??"",this.transformAuxiliaryDisplayValues.delete(e))):(this.transformAuxiliaryDisplayValues.has(e)||this.transformAuxiliaryDisplayValues.set(e,o.style.display),void(o.style.display="none")):void 0})}isPolydrawAuxiliaryPolyline(e){return e instanceof s.Polyline&&!(e instanceof s.Polygon)&&!0===e._polydrawAuxiliaryLayer}getBuiltInMenuButtonConfigs(){const e=this.config.polygonTools;return[{enabled:e.simplify.enabled,id:"simplify",label:"Simplify",classNames:["simplify"]},{enabled:e.doubleElbows.enabled,id:"doubleElbows",label:"DoubleElbows",classNames:["double-elbows"]},{enabled:e.bbox.enabled,id:"bbox",label:"Bounding box",classNames:["bbox"]},{enabled:e.bezier.enabled,id:"bezier",label:"Curve",classNames:["bezier"]},{enabled:e.scale.enabled,id:"scale",label:"Scale",classNames:["transform-scale"]},{enabled:e.rotate.enabled,id:"rotate",label:"Rotate",classNames:["transform-rotate"]}]}getBuiltInMenuButtons(e){var t;const r=this.getBuiltInMenuButtonConfigs().filter(({enabled:e})=>e).map(({id:e,label:t,classNames:r})=>Gi.createMenuButton(e,t,r));(null==(t=this.config.polygonTools.donut)?void 0:t.enabled)&&!this.donutTargetHasHoles(e)&&r.push(Gi.createMenuButton("donut","Donut",["transform-donut"]));const o=this.getVisualOptimizationToggleButton(e);return o&&r.push(o),r}getVisualOptimizationToggleButton(e){var t;if(!(null==(t=this.config.polygonTools.visualOptimizationToggle)?void 0:t.enabled))return null;const{level:r,original:o}=this.getOptimizationMetadataFromFeatureGroup(e);if(!(o>0||r>0))return null;const n="number"==typeof r&&r>0,i=n?"visual-optimization-state-hidden":"visual-optimization-state-visible",a=n?"Show all markers":"Hide extra markers";return Gi.createMenuButton("toggleOptimization",a,["toggle-visual-optimization",i])}getPolygonMenuActionButtons(e){const{menuActions:t}=this.config.polygonTools;return Array.isArray(t)?t.filter(t=>this.shouldShowPolygonMenuActionButton(t,e)).map(e=>Gi.createMenuButton(e.id,e.label,this.getPolygonMenuActionClassNames(e))):[]}shouldShowPolygonMenuActionButton(e,t){if(!e.id||Hi.has(e.id))return!1;if(!e.visible)return!0;try{return e.visible(this.getMenuActionContext(t))}catch{return!1}}getPolygonMenuActionClassNames(e){return Array.isArray(e.className)?e.className:e.className?[e.className]:["menu-action-default"]}closeOpenMenuPopup(){this._openMenuPopup&&(this.map.closePopup(this._openMenuPopup),this._openMenuPopup=null)}attachMenuPopupCloseHandler(e){const t=e.querySelector(".marker-menu-close");if(!t)return;const r=e=>{e.stopPropagation(),e.preventDefault(),this._openMenuPopup?this.closeOpenMenuPopup():this.map.closePopup()};t.addEventListener("click",r),t.addEventListener("touchend",r,{passive:!1})}emitBuiltInPolygonMenuAction(e,t,r){this.eventManager.emit("polydraw:menu:action",{action:e,latLngs:t,featureGroup:r}),this.closeOpenMenuPopup()}attachBuiltInMenuActionHandler(e,t,r,o){const n=e=>{e.preventDefault(),e.stopPropagation(),this.emitBuiltInPolygonMenuAction(t,r,o)};e.addEventListener("touchend",n,{passive:!1}),e.onclick=n}attachTransformHandler(e,t,r){const o=e=>{e.preventDefault(),e.stopPropagation(),this.startPolygonTransform(r,t),this.closeOpenMenuPopup()};e.addEventListener("touchend",o,{passive:!1}),e.onclick=o}attachOptimizationToggleHandler(e,t){const r=e=>{e.preventDefault(),e.stopPropagation(),this.toggleOptimizationVisibility(t),this.closeOpenMenuPopup()};e.addEventListener("touchend",r,{passive:!1}),e.onclick=r}attachCustomPolygonMenuActionHandler(e,t,r,o){var n;if(!(null==(n=this.config.polygonTools.menuActions)?void 0:n.find(({id:e})=>e===t)))return;const i=e=>{e.preventDefault(),e.stopPropagation(),this.eventManager.emit("polydraw:menu:action",{action:"polygonMenuAction",menuActionId:t,latLngs:r,featureGroup:o}),this.closeOpenMenuPopup()};e.addEventListener("touchend",i,{passive:!1}),e.onclick=i}attachMenuButtonHandler(e,t,r){const o=e.dataset.actionId;switch(o){case"simplify":case"doubleElbows":case"bbox":case"bezier":return void this.attachBuiltInMenuActionHandler(e,o,t,r);case"scale":case"rotate":case"donut":return void this.attachTransformHandler(e,o,r);case"toggleOptimization":return void this.attachOptimizationToggleHandler(e,r);default:o&&this.attachCustomPolygonMenuActionHandler(e,o,t,r)}}startPolygonTransform(e,t){const r=this.transformControllers.get(e);if(r&&(r.cancel(),r.destroy(),this.transformControllers.delete(e)),"donut"!==t||!this.donutTargetHasHoles(e))try{const r=new _i(this.map,e,t,this.config.polygonTools.donut.direction,o=>this.handleTransformControllerResult(r,e,t,o));this.transformControllers.set(e,r),this.setTransformAuxiliaryVisibility(e,!1),this.transformModeActive=!0}catch{}}handleTransformControllerResult(e,t,r,o){this.transformControllers.get(t)===e&&this.transformControllers.delete(t),this.transformModeActive=!1;const n=this.getPolygonLayer(t);if(!n)return;if(!o)return void this.setTransformAuxiliaryVisibility(t,!0);const{level:i,original:a}=this.getOptimizationMetadataFromFeatureGroup(t);if("donut"===r)return void this.handleDonutCommit(e,t,n,i,a);this.saveHistoryState&&this.saveHistoryState(r);const s=n.toGeoJSON(),l=this.getFeatureMetadataState(t);this.cleanupFeatureGroup(t),this.removeFeatureGroup(t),this.emitPolygonUpdated({operation:"transform",polygon:this.turfHelper.getTurfPolygon(s),allowMerge:!0,optimizationLevel:i,originalOptimizationLevel:a,featureId:l.featureId,featureMetadata:l.metadata,sourceFeatureIds:l.sourceFeatureIds,featureInteractionOverride:l.interactionOverride,featureStyleOverrides:l.styleOverrides,featureCreatedAt:l.createdAt})}getPolygonLayer(e){return e.getLayers().find(e=>e instanceof s.Polygon)}attachMenuButtonHandlers(e,t,r){e.forEach(e=>this.attachMenuButtonHandler(e,t,r))}enableMenuButtonPointerEvents(e){e.querySelectorAll(".marker-menu-button").forEach(e=>{e.style.pointerEvents="auto",e.addEventListener("click",e=>e.stopPropagation())})}generateMenuMarkerPopup(e,t){const r=[...this.getBuiltInMenuButtons(t),...this.getPolygonMenuActionButtons(t)],o=Gi.buildMenuPopup(r);this.attachMenuPopupCloseHandler(o),this.attachMenuButtonHandlers(r,e,t),s.DomEvent.disableClickPropagation(o),o.style.pointerEvents="auto",this.enableMenuButtonPointerEvents(o);const n=globalThis.innerWidth<=600,i=ri.isV1()?" leaflet-v1":" leaflet-v2",a=oi.createPopup({closeButton:!1,autoClose:!0,className:`menu-popup${n?" mobile-popup":""}${i}`}).setContent(o);return this._openMenuPopup=a,a}getMenuActionContext(e){const t=this.getPolygonGeoJSONFromFeatureGroup(e),r=e.getLayers().find(e=>e instanceof s.Polygon);return{polygon:this.turfHelper.getTurfPolygon(t),featureGroup:e,bounds:r?r.getBounds():oi.createLatLngBounds()}}toggleOptimizationVisibility(e){const t=e.getLayers().find(e=>e instanceof s.Polygon);if(!t)return;const r=this.getOptimizationMetadataFromFeatureGroup(e);if(!r.original&&!r.level)return;const o=r.level>0?0:r.original>0?r.original:r.level;if(o===r.level)return;const n=t.toGeoJSON(),i=this.getFeatureMetadataState(e);this.cleanupFeatureGroup(e),this.removeFeatureGroup(e),this.emitPolygonUpdated({operation:"toggleOptimization",polygon:this.turfHelper.getTurfPolygon(n),allowMerge:!0,optimizationLevel:o,originalOptimizationLevel:r.original||o,featureId:i.featureId,featureMetadata:i.metadata,sourceFeatureIds:i.sourceFeatureIds,featureInteractionOverride:i.interactionOverride,featureStyleOverrides:i.styleOverrides,featureCreatedAt:i.createdAt})}getPolygonGeoJSONFromFeatureGroup(e){try{const t=e.getLayers().find(e=>e instanceof s.Polygon);if(!t)throw new Error("No polygon found in feature group");return t.toGeoJSON()}catch(t){return Wn()||(t instanceof Error?console.warn("Error getting polygon GeoJSON from feature group:",t.message):console.warn("Error getting polygon GeoJSON from feature group:",t)),{type:"Feature",geometry:{type:"Polygon",coordinates:[[[0,0],[0,1],[1,1],[1,0],[0,0]]]},properties:{}}}}getTotalPolygonPerimeter(e){try{if(!e||!e.geometry)return 0;let t=0;if("Polygon"===e.geometry.type){const r=e.geometry.coordinates;for(const e of r){const r={type:"Feature",geometry:{type:"Polygon",coordinates:[e]},properties:{}};t+=this.turfHelper.getPolygonPerimeter(r)}}else if("MultiPolygon"===e.geometry.type){const r=e.geometry.coordinates;for(const e of r)for(const r of e){const e={type:"Feature",geometry:{type:"Polygon",coordinates:[r]},properties:{}};t+=this.turfHelper.getPolygonPerimeter(e)}}return 1e3*t}catch(t){return Wn()||(t instanceof Error?console.warn("Error calculating total polygon perimeter:",t.message):console.warn("Error calculating total polygon perimeter:",t)),1e3*this.turfHelper.getPolygonPerimeter(e)}}generateInfoMarkerPopup(e,t){var r,o;const n=new Jn(t,this.config),i=new Zn(e,this.config),a=this.config.markers.markerInfoIcon??{},l=!1!==a.showArea,c=!1!==a.showPerimeter,u=!1!==a.useMetrics,h=null==(r=a.areaLabel)?void 0:r.trim(),g=null==(o=a.perimeterLabel)?void 0:o.trim(),d=document.createElement("div");d.classList.add("info-marker-outer-wrapper");const p=document.createElement("div");p.classList.add("info-marker-wrapper");const f=document.createElement("div");f.classList.add("content");const y=document.createElement("div");if(y.classList.add("info-marker-content"),l){const e=u?`${i.metricArea} ${i.metricUnit}`:`${i.imperialArea} ${i.imperialUnit}`,t=document.createElement("div");t.classList.add("info-item","area"),t.innerHTML=h&&h.length>0?`<strong>${h}:</strong> ${e}`:e,y.appendChild(t)}if(c){const e=u?`${n.metricLength} ${n.metricUnit}`:`${n.imperialLength} ${n.imperialUnit}`,t=document.createElement("div");t.classList.add("info-item","perimeter"),t.innerHTML=g&&g.length>0?`<strong>${g}:</strong> ${e}`:e,y.appendChild(t)}f.appendChild(y),d.appendChild(p),p.appendChild(f),s.DomEvent.disableClickPropagation(d),d.style.pointerEvents="auto",d.querySelectorAll("button").forEach(e=>{e.style.pointerEvents="auto",e.addEventListener("click",e=>e.stopPropagation())});const m=window.innerWidth<=600;return oi.createPopup({closeButton:!0,autoClose:!0,className:"info-popup"+(m?" mobile-popup":"")}).setContent(d)}}class zi{constructor(e){i(this,"turfHelper"),i(this,"map"),i(this,"config"),i(this,"eventManager"),i(this,"getFeatureGroups"),i(this,"saveHistoryState"),i(this,"layerManager"),i(this,"geometryManager"),i(this,"interactionManager"),i(this,"onDrawCancel",e=>{this.emit("drawCancelled",e)}),i(this,"onPolygonUpdated",e=>{this.handlePolygonModified(e)}),i(this,"onMenuAction",e=>{this.handleMenuAction(e).catch(e=>{if(!Wn()){const t=e instanceof Error?e.message:String(e);console.warn(`Menu action failed: ${t}`)}})}),i(this,"onCheckIntersection",e=>{const t=this.geometryManager.checkPolygonIntersection(e.polygon1,e.polygon2);e.callback(t)}),i(this,"onSubtract",e=>{this.subtractPolygon(e.subtractPolygon)}),i(this,"onPolygonDeleted",()=>{this.emit("polygonDeleted",void 0)}),this.turfHelper=e.turfHelper,this.map=e.map,this.config=e.config,this.eventManager=e.eventManager,this.getFeatureGroups=e.getFeatureGroups,this.saveHistoryState=e.saveHistoryState,this.layerManager=e.layerManager,this.initializeSpecializedManagers(e)}initializeSpecializedManagers(e){this.geometryManager=new vi({turfHelper:e.turfHelper,config:e.config}),this.interactionManager=new Bi({turfHelper:e.turfHelper,polygonInformation:e.polygonInformation,map:e.map,config:e.config,modeManager:e.modeManager,eventManager:this.eventManager,saveHistoryState:e.saveHistoryState,layerManager:e.layerManager},{getFeatureGroups:this.getFeatureGroups,addFeatureGroup:e=>this.addFeatureGroupInternal(e),removeFeatureGroup:e=>this.removeFeatureGroupInternal(e)}),this.setupEventForwarding()}setupEventForwarding(){this.eventManager.on("polydraw:draw:cancel",this.onDrawCancel),this.eventManager.on("polydraw:polygon:updated",this.onPolygonUpdated),this.eventManager.on("polydraw:menu:action",this.onMenuAction),this.eventManager.on("polydraw:check:intersection",this.onCheckIntersection),this.eventManager.on("polydraw:subtract",this.onSubtract),this.eventManager.on("polydraw:polygon:deleted",this.onPolygonDeleted)}dispose(){this.eventManager.off("polydraw:draw:cancel",this.onDrawCancel),this.eventManager.off("polydraw:polygon:updated",this.onPolygonUpdated),this.eventManager.off("polydraw:menu:action",this.onMenuAction),this.eventManager.off("polydraw:check:intersection",this.onCheckIntersection),this.eventManager.off("polydraw:subtract",this.onSubtract),this.eventManager.off("polydraw:polygon:deleted",this.onPolygonDeleted),this.interactionManager.dispose()}async handlePolygonModified(e){const t=new Set(["addVertex","markerDrag","polygonDrag","polygonClone","toggleOptimization","donut"]),r=!e.operation||!t.has(e.operation);let o=e.allowMerge;e.intelligentMerge&&"markerDrag"===e.operation&&(o=this.shouldAllowIntelligentMerge(e.polygon));const n={simplify:r,noMerge:!o,visualOptimizationLevel:e.optimizationLevel||0,originalOptimizationLevel:e.originalOptimizationLevel,skipKinkProcessing:"markerDrag"===e.operation,featureId:e.featureId,featureMetadata:e.featureMetadata,sourceFeatureIds:e.sourceFeatureIds,featureInteractionOverride:e.featureInteractionOverride,featureStyleOverrides:e.featureStyleOverrides,targetLayerId:e.targetLayerId,featureCreatedAt:e.featureCreatedAt,featureLastModified:e.featureLastModified};await this.addPolygon(e.polygon,n)}async handleMenuAction(e){var t,r,o,n;if(!(null==e?void 0:e.featureGroup))return;if(this.layerManager&&!this.layerManager.isFeatureGroupEditable(e.featureGroup))return;let i;try{i=this.getCompletePolygonFromFeatureGroup(e.featureGroup)}catch(g){if(!Wn()){const e=g instanceof Error?g.message:String(g);console.warn(`Menu action skipped: unable to resolve polygon geometry (${e}).`)}return}const{level:a,original:l}=this.getOptimizationMetadataFromFeatureGroup(e.featureGroup),c=this.getFeatureMetadataStateFromFeatureGroup(e.featureGroup);let u,h=!0;switch(e.action){case"simplify":u=this.geometryManager.simplifyPolygon(i);break;case"bbox":u=this.geometryManager.convertToBoundingBox(i);break;case"doubleElbows":u=this.geometryManager.doubleElbowsPolygon(i);break;case"bezier":u=this.geometryManager.bezierifyPolygon(i);break;case"polygonMenuAction":{u=await this.executePolygonMenuAction(e.menuActionId,i,e.featureGroup);const t=e.menuActionId&&this.config.polygonTools.menuActions?this.config.polygonTools.menuActions.find(t=>t.id===e.menuActionId):void 0;h=!1!==(null==t?void 0:t.history);break}default:return}if(u.success&&u.result){this.saveHistoryState&&h&&this.saveHistoryState(e.action),this.removeFeatureGroupInternal(e.featureGroup);const i="bezier"===e.action?(null==(t=this.config.polygonTools.bezier)?void 0:t.visualOptimizationLevel)??10:a,g="bezier"===e.action?(null==(r=this.config.polygonTools.bezier)?void 0:r.visualOptimizationLevel)??10:l,d=!1===u.allowMerge,p=!0===u.simplify,f=u.metadata??c.metadata,y=await this.addPolygon(u.result,{simplify:p,noMerge:d,visualOptimizationLevel:i,originalOptimizationLevel:g,featureId:c.featureId,featureMetadata:f,sourceFeatureIds:c.sourceFeatureIds,featureInteractionOverride:c.interactionOverride,featureStyleOverrides:c.styleOverrides,featureCreatedAt:c.createdAt});if("bezier"===e.action&&(null==(o=this.config.polygonTools.bezier)?void 0:o.ghostMarkers)){const e=.001;null==(n=y.featureGroups)||n.forEach(t=>{t.eachLayer(t=>{if(t instanceof s.Polygon){const r=t;r.setStyle({opacity:e,fillOpacity:e}),r._polydrawDragData&&(r._polydrawDragData.originalOpacity=e)}})})}}}async executePolygonMenuAction(e,t,r){if(!e||!this.config.polygonTools.menuActions)return{success:!1,error:"Polygon menu action not found"};const o=this.config.polygonTools.menuActions.find(t=>t.id===e);if(!o)return{success:!1,error:"Polygon menu action not found"};try{const e=await o.apply({polygon:t,featureGroup:r,bounds:this.getBoundsForMenuAction(r,t)}),n=this.normalizeMenuActionResult(e);return n?this.isPolygonFeature(n.polygon)?{success:!0,result:n.polygon,allowMerge:n.allowMerge,simplify:n.simplify,metadata:n.metadata}:{success:!1,error:"Invalid polygon geometry"}:{success:!1,error:"No change"}}catch(n){if(!Wn()){const e=n instanceof Error?n.message:String(n);console.warn(`Polygon menu action failed: ${e}`)}return{success:!1,error:"Polygon menu action execution failed"}}}normalizeMenuActionResult(e){if(null!=e&&"object"==typeof e)return this.isPolygonFeature(e)?{polygon:e}:"polygon"in e&&this.isPolygonFeature(e.polygon)?{polygon:e.polygon,allowMerge:e.allowMerge,simplify:e.simplify,metadata:e.metadata}:void 0}isPolygonFeature(e){if(!e||"object"!=typeof e)return!1;const t=e;return"Feature"===t.type&&!!t.geometry&&("Polygon"===t.geometry.type||"MultiPolygon"===t.geometry.type)}getBoundsForMenuAction(e,t){const r=e.getLayers().find(e=>e instanceof s.Polygon);if(r)return r.getBounds();const o=oi.createLatLngBounds(),n=e=>{"number"==typeof e[0]&&"number"==typeof e[1]&&o.extend(oi.createLatLng(e[1],e[0]))};return"Polygon"===t.geometry.type?t.geometry.coordinates.forEach(e=>e.forEach(n)):t.geometry.coordinates.forEach(e=>e.forEach(e=>e.forEach(n))),o}get polygonInteractionManager(){return this.interactionManager}on(e,t){this.eventManager.on(e,t)}emit(e,t){this.eventManager.emit(e,t)}async addPolygon(e,t={}){if(this.layerManager&&t.targetLayerId){if(!this.layerManager.getLayer(t.targetLayerId))return{success:!1,error:`Layer "${t.targetLayerId}" does not exist`}}const{polygons:r,skipMerge:o}=this.preparePolygonsForAddition(e,t),n=[];for(const i of r){const e=await this.addPolygonWithMergeHandling(i,t,o);if(!e.success)return e;e.featureGroups&&e.featureGroups.length>0&&n.push(...e.featureGroups)}return{success:!0,featureGroups:n.length>0?n:void 0}}async addPolygonWithMergeHandling(e,t,r){const{noMerge:o=!1}=t;try{return this.isPolygonInsideExistingHole(e)?await this.addPolygonLayer(e,t):this.config.mergePolygons&&!o&&this.getFeatureGroups().length>0&&!r?await this.mergePolygon(e,t):await this.addPolygonLayer(e,t)}catch(n){return{success:!1,error:n instanceof Error?n.message:"Unknown error in addPolygon"}}}preparePolygonsForAddition(e,t={}){let r=!1;try{r=this.turfHelper.hasKinks(e)}catch(o){Wn()||console.warn("Error detecting polygon kinks:",o instanceof Error?o.message:String(o))}if(!(!0===t.skipKinkProcessing)&&!this.config.kinks&&r)try{const t=this.turfHelper.getKinks(e);if(t.length>0)return{polygons:t,skipMerge:!1}}catch(o){Wn()||console.warn("Error splitting polygon kinks:",o instanceof Error?o.message:String(o))}return{polygons:[e],skipMerge:this.config.kinks&&r}}async subtractPolygon(e,t={}){const{simplify:r=!0,visualOptimizationLevel:o,originalOptimizationLevel:n}=t;try{const a=[],s=this.layerManager;(s?s.getFeatureGroupsForLayer(t.targetLayerId||s.getActiveLayerId()).filter(e=>s.isFeatureGroupEditable(e)):this.getFeatureGroups()).forEach(t=>{try{const r=t.toGeoJSON();if(!r||!r.features||!r.features[0])return;const o=r.features[0];if(!o.geometry||!o.geometry.coordinates)return;const n=this.turfHelper.getTurfPolygon(o);this.geometryManager.checkPolygonIntersection(n,e)&&a.push(t)}catch(r){Wn()||console.warn("Skipping feature group during intersection check:",r)}});const l=[];for(const t of a)try{const i=this.getFeatureMetadataStateFromFeatureGroup(t),a=t.toGeoJSON(),s=this.turfHelper.getTurfPolygon(a.features[0]),c=this.geometryManager.subtractPolygon(s,e);if(this.removeFeatureGroupInternal(t),c.success&&c.results)for(const e of c.results){const t=await this.addPolygonLayer(e,{simplify:r,visualOptimizationLevel:o,originalOptimizationLevel:n,featureMetadata:i.metadata,sourceFeatureIds:i.sourceFeatureIds,featureInteractionOverride:i.interactionOverride,featureStyleOverrides:i.styleOverrides,featureCreatedAt:i.createdAt});t.success&&t.featureGroups&&l.push(...t.featureGroups)}}catch(i){Wn()||console.warn("Failed subtract operation for one feature group:",i)}return this.emit("polygonSubtracted",{subtractedPolygon:e,affectedFeatureGroups:a,resultFeatureGroups:l}),this.emit("polygonOperationComplete",{operation:"subtract",polygon:e,resultFeatureGroups:l}),{success:!0,featureGroups:l}}catch(i){return{success:!1,error:i instanceof Error?i.message:"Unknown error in subtractPolygon"}}}async addPolygonLayer(e,t={}){const{simplify:r=!0,dynamicTolerance:o=!1,visualOptimizationLevel:n=0,originalOptimizationLevel:i,targetLayerId:a,layerColor:l,featureId:c,featureMetadata:u,sourceFeatureIds:h,featureInteractionOverride:g,featureStyleOverrides:d,featureCreatedAt:p,featureLastModified:f}=t;try{if(!e||!e.geometry||!e.geometry.coordinates)return{success:!1,error:"Invalid polygon data"};const t=this.layerManager?a||this.layerManager.getActiveLayerId():void 0,y=!this.layerManager||!t||this.layerManager.isLayerEditable(t),m=void 0===g?y:"editable"===g;let v=l;if(!v&&this.layerManager&&t){const e=this.layerManager.getLayer(t);e&&(v=e.color)}else if(!v&&this.layerManager){const e=this.layerManager.getActiveLayer();e&&this.layerManager.getLayerCount()>1&&(v=e.color)}const M=new s.FeatureGroup,b=r?this.turfHelper.getSimplified(e,o):e,w=this.normalizeSinglePolygonFeature(b);let P,L,k=n;try{if(P=this.getPolygon(w,v,{enableDragging:m,styleOverrides:d}),!P)return{success:!1,error:"Failed to create polygon"};P._polydrawOptimizationLevel=n,k=i??P._polydrawOptimizationOriginalLevel??n,P._polydrawOptimizationOriginalLevel=k||0,M.addLayer(P),this.interactionManager.suppressDeleteMarkerClicks(250)}catch{return{success:!1,error:"Failed to create polygon layer"}}this.setFeatureGroupMetadata(M,{featureId:c,metadata:u,sourceFeatureIds:h,interactionOverride:g,styleOverrides:d,optimizationLevel:n,originalOptimizationLevel:k,hasHoles:this.featureHasHoles(w),layerId:t,createdAt:p,lastModified:f});try{const e=P.getLatLngs();L=this.normalizePolygonCoordinates(e)}catch{L=[]}if(m){try{L.forEach((e,t)=>{if(!e||!Array.isArray(e))return;const r=[];if(e.forEach(e=>{Array.isArray(e)&&e.length>=2?r.push({lat:e[1],lng:e[0]}):"object"==typeof e&&null!==e&&"lat"in e&&"lng"in e&&r.push(e)}),0!==r.length)try{if(0===t)this.interactionManager.addMarkers(r,M,{optimizationLevel:n,originalOptimizationLevel:k});else{const e=oi.createPolyline(r,{color:this.config.styles.hole.color,weight:this.config.styles.hole.weight||2,opacity:this.config.styles.hole.opacity||1,fillColor:this.config.styles.hole.fillColor,fillOpacity:this.config.styles.hole.fillOpacity||.5});e._polydrawAuxiliaryLayer=!0,M.addLayer(e),this.interactionManager.addHoleMarkers(r,M)}}catch{}})}catch{}try{this.interactionManager.addEdgeClickListeners(P,M)}catch{}}if(this.getFeatureGroups().push(M),this.layerManager){const e=t||this.layerManager.getActiveLayerId();if(!this.layerManager.assignFeatureGroupToLayer(M,e))return this.removeFeatureGroupInternal(M),{success:!1,error:`Failed to assign polygon to layer "${e}"`}}try{M.addTo(this.map)}catch{}return this.interactionManager.updateMarkerDraggableState(),this.emit("polygonAdded",{polygon:w,featureGroup:M}),this.emit("polygonOperationComplete",{operation:"add",polygon:w,featureGroup:M}),{success:!0,featureGroups:[M]}}catch(y){return{success:!1,error:y instanceof Error?y.message:"Unknown error in addPolygonLayer"}}}async mergePolygon(e,t={}){try{const r=[],o=[];let n=!1;const i=!1!==t.mergeEditableOnly,a=this.layerManager;return(a?a.getFeatureGroupsForLayer(t.targetLayerId||a.getActiveLayerId()).filter(e=>!i||a.isFeatureGroupEditable(e)):this.getFeatureGroups()).forEach(t=>{try{const i=t.toGeoJSON();if(!i||!i.features||!i.features[0])return;const a=i.features[0];if(!a.geometry||!a.geometry.coordinates)return;if(this.isPositionArrayofArrays(a.geometry.coordinates))a.geometry.coordinates.forEach(i=>{try{const a=this.turfHelper.getMultiPolygon([i]);n=this.geometryManager.checkPolygonIntersection(a,e),n&&(o.push(t),r.push(a))}catch{}});else try{const i=this.turfHelper.getTurfPolygon(a);n=this.geometryManager.checkPolygonIntersection(i,e),n&&(o.push(t),r.push(i))}catch{}}catch{}}),o.length>0?await this.unionPolygons(o,e,r,t):await this.addPolygonLayer(e,t)}catch(r){return{success:!1,error:r instanceof Error?r.message:"Unknown error in mergePolygon"}}}async unionPolygons(e,t,r,o={}){try{const n=this.collectSourceFeatureIds(e,o.sourceFeatureIds),i=o.featureMetadata??this.resolvePrimaryFeatureMetadata(e),a=o.featureInteractionOverride??this.resolvePrimaryFeatureInteractionOverride(e),s=o.featureStyleOverrides??this.resolvePrimaryFeatureStyleOverrides(e);e.forEach(e=>{this.removeFeatureGroupInternal(e)});const l=this.geometryManager.unionPolygons(r,t);if(l.success&&l.result){const e=await this.addPolygonLayer(l.result,{...o,featureMetadata:i,sourceFeatureIds:n,featureInteractionOverride:a,featureStyleOverrides:s});return this.emit("polygonsUnioned",{originalPolygons:r,resultPolygon:l.result,featureGroups:e.featureGroups}),e}return{success:!1,error:l.error||"Failed to union polygons"}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Unknown error in unionPolygons"}}}shouldAllowIntelligentMerge(e){try{const t=this.layerManager,r=t?t.getFeatureGroupsForLayer(t.getActiveLayerId()).filter(e=>t.isFeatureGroupEditable(e)):this.getFeatureGroups();for(const o of r)try{const t=o.toGeoJSON();if(!t||!t.features||!t.features[0])continue;const r=t.features[0];if(!r.geometry||!r.geometry.coordinates)continue;const n=this.turfHelper.getTurfPolygon(r);if(this.geometryManager.checkPolygonIntersection(n,e))return!0}catch{continue}return!1}catch{return!1}}isPolygonInsideExistingHole(e){try{const t=this.layerManager,r=t?t.getFeatureGroupsForLayer(t.getActiveLayerId()).filter(e=>t.isFeatureGroupEditable(e)):this.getFeatureGroups();for(const o of r)try{const t=o.toGeoJSON();if(!t||!t.features||!t.features[0])continue;const r=t.features[0];if(!r.geometry||!r.geometry.coordinates)continue;let n=!1,i=[];if("Polygon"===r.geometry.type)n=r.geometry.coordinates.length>1,n&&(i=r.geometry.coordinates.slice(1));else if("MultiPolygon"===r.geometry.type)for(const e of r.geometry.coordinates)e.length>1&&(n=!0,i.push(...e.slice(1)));if(n&&i.length>0)for(const o of i)try{const t=this.turfHelper.createPolygon([o]);if(this.turfHelper.isPolygonCompletelyWithin(e,t))return!0}catch{continue}}catch{continue}return!1}catch{return!1}}normalizePolygonCoordinates(e){if(!Array.isArray(e)||0===e.length)return[];const t=e=>null!==e&&"object"==typeof e&&"lat"in e&&"lng"in e&&"number"==typeof e.lat&&"number"==typeof e.lng,r=e=>{if(!Array.isArray(e))return[];if(e.length>0&&t(e[0]))return[e];const o=[];for(const n of e)if(Array.isArray(n))if(n.length>0&&t(n[0]))o.push(n);else{const e=r(n);o.push(...e)}return o};try{return r(e)}catch{return[]}}isPositionArrayofArrays(e){if(!Array.isArray(e)||0===e.length)return!1;const t=e[0];if(!Array.isArray(t)||0===t.length)return!1;const r=t[0];if(!Array.isArray(r)||0===r.length)return!1;const o=r[0];return this.isPosition(o)}isPosition(e){return Array.isArray(e)&&e.length>=2&&e.every(e=>"number"==typeof e)}getPolygon(e,t,r={}){const o=s.GeoJSON.geometryToLayer(e),n=t||this.config.styles.polygon.color,i=this.config.styles.polygon.fillColor,{styleOverrides:a}=r,l={...this.config.styles.polygon,color:(null==a?void 0:a.color)??n,fillColor:(null==a?void 0:a.fillColor)??i,weight:(null==a?void 0:a.weight)??this.config.styles.polygon.weight??2,opacity:this.config.styles.polygon.opacity||1,fillOpacity:(null==a?void 0:a.fillOpacity)??this.config.styles.polygon.fillOpacity??.2};o.setStyle(l),o._polydrawUniqueId=oi.util.stamp(o)+"_"+Date.now(),delete o._polydrawDragData,delete o._polydrawOriginalLatLngs,delete o._polydrawCurrentDragSession,delete o._polydrawOriginalMarkerPositions,delete o._polydrawOriginalHoleLinePositions;return!1!==r.enableDragging&&(this.config.modes.dragPolygons||this.config.tools.clone)&&this.interactionManager.enablePolygonDragging(o,e),o}normalizeSinglePolygonFeature(e){if("MultiPolygon"===e.geometry.type&&1===e.geometry.coordinates.length){const[t]=e.geometry.coordinates;try{return this.turfHelper.createPolygon(t)}catch{return e}}return e}addFeatureGroupInternal(e){this.getFeatureGroups().push(e)}removeFeatureGroupInternal(e){this.cleanupFeatureGroup(e),this.layerManager&&this.layerManager.removeFeatureGroupFromLayer(e);try{e.clearLayers()}catch(o){Wn()||console.warn("Error clearing layers from feature group:",o)}const t=this.getFeatureGroups(),r=t.indexOf(e);r>-1&&t.splice(r,1);try{this.map.removeLayer(e)}catch(o){Wn()||console.warn("Error removing feature group layer from map:",o)}}getCompletePolygonFromFeatureGroup(e){try{let t=null;if(e.eachLayer(e=>{e instanceof s.Polygon&&(t=e)}),t)return t.toGeoJSON();const r=e.toGeoJSON().features.find(e=>{var t,r;return"Polygon"===(null==(t=e.geometry)?void 0:t.type)||"MultiPolygon"===(null==(r=e.geometry)?void 0:r.type)});if(r)return r;throw new Error("No polygon geometry found in feature group")}catch(t){throw Wn()||t instanceof Error&&console.warn("Error getting complete polygon GeoJSON from feature group:",t.message),t instanceof Error?t:new Error("Failed to resolve polygon geometry from feature group")}}getOptimizationMetadataFromFeatureGroup(e){if(!e)return{level:0,original:0};let t=0,r=0;return e.eachLayer(e=>{if(e instanceof s.Polygon){const o=e;"number"==typeof o._polydrawOptimizationLevel&&(t=o._polydrawOptimizationLevel||0),"number"==typeof o._polydrawOptimizationOriginalLevel&&(r=o._polydrawOptimizationOriginalLevel||0)}}),!r&&t>0&&(r=t),{level:t,original:r}}getFeatureMetadataStateFromFeatureGroup(e){if(!e)return{metadata:{},sourceFeatureIds:[]};const t=e._polydrawMetadata,r=null==t?void 0:t.id,o=Array.isArray(null==t?void 0:t.sourceFeatureIds)?[...t.sourceFeatureIds]:r?[r]:[],n=(null==t?void 0:t.createdAt)instanceof Date&&!Number.isNaN(t.createdAt.getTime())?t.createdAt.toISOString():void 0;return{featureId:r,metadata:this.cloneFeatureMetadata(null==t?void 0:t.metadata),sourceFeatureIds:o,interactionOverride:null==t?void 0:t.interactionOverride,styleOverrides:this.cloneStyleOverrides(null==t?void 0:t.styleOverrides),createdAt:n}}collectSourceFeatureIds(e,t){const r=[],o=new Set,n=e=>{e&&!o.has(e)&&(o.add(e),r.push(e))};return e.forEach(e=>{const t=e._polydrawMetadata;Array.isArray(null==t?void 0:t.sourceFeatureIds)&&t.sourceFeatureIds.length>0?t.sourceFeatureIds.forEach(e=>n(e)):n(null==t?void 0:t.id)}),Array.isArray(t)&&t.forEach(e=>n(e)),r}resolvePrimaryFeatureMetadata(e){var t;for(const r of e){const e=null==(t=r._polydrawMetadata)?void 0:t.metadata;if(e&&Object.keys(e).length>0)return this.cloneFeatureMetadata(e)}return{}}resolvePrimaryFeatureInteractionOverride(e){var t;for(const r of e){const e=null==(t=r._polydrawMetadata)?void 0:t.interactionOverride;if(e)return e}}resolvePrimaryFeatureStyleOverrides(e){var t;for(const r of e){const e=null==(t=r._polydrawMetadata)?void 0:t.styleOverrides;if(e)return this.cloneStyleOverrides(e)}}cloneFeatureMetadata(e){return e?yi(e):{}}cloneStyleOverrides(e){if(e)return yi(e)}featureHasHoles(e){return!!(null==e?void 0:e.geometry)&&("Polygon"===e.geometry.type?e.geometry.coordinates.length>1:"MultiPolygon"===e.geometry.type&&e.geometry.coordinates.some(e=>e.length>1))}setFeatureGroupMetadata(e,t){const r=new Date,o=t.createdAt?new Date(t.createdAt):r,n=t.lastModified?new Date(t.lastModified):r,i=Number.isNaN(o.getTime())?r:o,a=Number.isNaN(n.getTime())?r:n,s=t.featureId||`fg-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l=t.sourceFeatureIds&&t.sourceFeatureIds.length>0?[...new Set(t.sourceFeatureIds)]:[s];e._polydrawMetadata={id:s,optimizationLevel:t.optimizationLevel,originalOptimizationLevel:t.originalOptimizationLevel,hasHoles:t.hasHoles,createdAt:i,lastModified:a,layerId:t.layerId,metadata:this.cloneFeatureMetadata(t.metadata),sourceFeatureIds:l,interactionOverride:t.interactionOverride,styleOverrides:this.cloneStyleOverrides(t.styleOverrides)}}updateMarkerDraggableState(){this.interactionManager.updateMarkerDraggableState()}updateAllMarkersForEdgeDeletion(e){this.interactionManager.updateAllMarkersForEdgeDeletion(e)}setModifierKeyHeld(e){this.interactionManager.setModifierKeyHeld(e)}checkPolygonIntersection(e,t){return this.geometryManager.checkPolygonIntersection(e,t)}getPolygonCenter(e){try{if(!e||!e.geometry||!e.geometry.coordinates)return null;let t;if("Polygon"===e.geometry.type)t=e.geometry.coordinates[0];else{if("MultiPolygon"!==e.geometry.type)return null;t=e.geometry.coordinates[0][0]}if(!Array.isArray(t)||0===t.length)return null;let r=0,o=0,n=0;for(const e of t)if(Array.isArray(e)&&e.length>=2){const t=e[0],i=e[1];"number"!=typeof t||"number"!=typeof i||isNaN(t)||isNaN(i)||(o+=t,r+=i,n++)}return 0===n?null:{lat:r/n,lng:o/n}}catch{return null}}getBoundingBox(e){try{if(!e||!e.geometry||!e.geometry.coordinates)return null;let t;if("Polygon"===e.geometry.type)t=e.geometry.coordinates[0];else{if("MultiPolygon"!==e.geometry.type)return null;t=e.geometry.coordinates[0][0]}if(!Array.isArray(t)||0===t.length)return null;let r=1/0,o=-1/0,n=1/0,i=-1/0;for(const e of t)if(Array.isArray(e)&&e.length>=2){const t=e[0],a=e[1];"number"!=typeof t||"number"!=typeof a||isNaN(t)||isNaN(a)||(n=Math.min(n,t),i=Math.max(i,t),r=Math.min(r,a),o=Math.max(o,a))}return r===1/0||o===-1/0||n===1/0||i===-1/0?null:{minLat:r,maxLat:o,minLng:n,maxLng:i}}catch{return null}}addMarker(e,t,r){this.interactionManager.addMarkers(e,t,r)}addHoleMarker(e,t){this.interactionManager.addHoleMarkers(e,t)}addEdgeClickListeners(e,t){this.interactionManager.addEdgeClickListeners(e,t)}enablePolygonDragging(e,t){this.interactionManager.enablePolygonDragging(e,t)}getMarkerIndex(e,t){return 0}ensureMarkerSeparation(e,t){var r,o,n;return{menu:(null==(r=t.menu)?void 0:r.index)??0,delete:(null==(o=t.delete)?void 0:o.index)??1,info:(null==(n=t.info)?void 0:n.index)??2}}findAlternativeMarkerPosition(e,t,r){return(t+1)%e}createDivIcon(e){return oi.createDivIcon({className:e.join(" ")})}getLatLngInfoString(e){return"Latitude: "+e.lat+" Longitude: "+e.lng}generateMenuMarkerPopup(e,t){const r=document.createElement("div");return r.innerHTML="Menu",r}getPolygonGeoJSONFromFeatureGroup(e){return{type:"Feature",geometry:{type:"Polygon",coordinates:[[[0,0],[0,1],[1,1],[1,0],[0,0]]]},properties:{}}}getTotalPolygonPerimeter(e){return 1e3}generateInfoMarkerPopup(e,t){const r=document.createElement("div");return r.innerHTML=`Area: ${e}, Perimeter: ${t}`,r}onMarkerHoverForEdgeDeletion(e,t){}highlightEdgeOnHover(e,t){}onEdgeClick(e,t){}removeFeatureGroup(e){this.removeFeatureGroupInternal(e)}cleanupFeatureGroup(e){this.interactionManager.cleanupFeatureGroup(e)}onPolygonMouseMove(e){}onPolygonMouseUp(e){}updatePolygonAfterDrag(e){}setSubtractVisualMode(e,t){}performModifierSubtract(e,t){try{const r=this.turfHelper.getTurfPolygon(e),o=[];this.getFeatureGroups().forEach(e=>{if(e!==t)try{const t=e.toGeoJSON();if(!t||!t.features||!t.features[0])return;const n=t.features[0];if(!n.geometry||!n.geometry.coordinates)return;const i=this.turfHelper.getTurfPolygon(n);this.geometryManager.checkPolygonIntersection(i,r)&&o.push(e)}catch{}}),this.removeFeatureGroupInternal(t),o.forEach(e=>{try{const t=e.toGeoJSON(),o=this.turfHelper.getTurfPolygon(t.features[0]);this.removeFeatureGroupInternal(e);const n=this.geometryManager.subtractPolygon(o,r);if(n.success&&n.results)for(const e of n.results)this.addPolygonLayer(e,{simplify:!0})}catch{}})}catch{}}}class Ui{constructor(e,t=50){i(this,"undoStack",[]),i(this,"redoStack",[]),i(this,"maxHistorySize",50),i(this,"maxSnapshotSize",5e5),i(this,"maxTotalMemory",5e6),i(this,"currentMemoryUsage",0),i(this,"eventManager"),i(this,"isRestoring",!1),this.eventManager=e,this.maxHistorySize=t}setMaxHistorySize(e){!Number.isFinite(e)||e<=0||(this.maxHistorySize=Math.floor(e),this.enforceMemoryBudget(),this.enforceRedoMemoryBudget())}saveState(e,t,r){if(this.isRestoring)return;const o=this.createSnapshot(e,t,r),n=this.calculateSnapshotSize(o);o.size=n,n>this.maxSnapshotSize?console.warn(`History snapshot too large (${n} bytes, limit ${this.maxSnapshotSize} bytes). Skipping save.`):(this.redoStack=[],this.undoStack.push(o),this.currentMemoryUsage+=n,this.enforceMemoryBudget(),this.eventManager.emit("polydraw:history:changed",{canUndo:this.canUndo(),canRedo:this.canRedo()}))}calculateSnapshotSize(e){try{return 2*JSON.stringify(e).length}catch(t){return console.warn("Error calculating snapshot size:",t),0}}enforceMemoryBudget(){for(;this.undoStack.length>this.maxHistorySize;){const e=this.undoStack.shift();e&&(this.currentMemoryUsage-=this.getSnapshotSize(e))}for(;this.currentMemoryUsage>this.maxTotalMemory&&this.undoStack.length>0;){const e=this.undoStack.shift();e&&(this.currentMemoryUsage-=this.getSnapshotSize(e))}}enforceRedoMemoryBudget(){const e=Math.floor(this.maxHistorySize/2);for(;this.redoStack.length>e;)this.redoStack.shift()}undo(e,t){if(!this.canUndo())return null;const r=this.createSnapshot(e,"redo-point",t),o=this.calculateSnapshotSize(r);r.size=o,o<=this.maxSnapshotSize?(this.redoStack.push(r),this.enforceRedoMemoryBudget()):console.warn(`Current state too large (${o} bytes) to save to redo stack.`);const n=this.undoStack.pop();return this.currentMemoryUsage-=this.getSnapshotSize(n),this.eventManager.emit("polydraw:history:undo",{canUndo:this.canUndo(),canRedo:this.canRedo(),action:n.action}),n}redo(e,t){if(!this.canRedo())return null;const r=this.createSnapshot(e,"undo-point",t),o=this.calculateSnapshotSize(r);r.size=o,o<=this.maxSnapshotSize?(this.undoStack.push(r),this.currentMemoryUsage+=o,this.enforceMemoryBudget()):console.warn(`Current state too large (${o} bytes) to save to undo stack.`),this.enforceRedoMemoryBudget();const n=this.redoStack.pop();return this.eventManager.emit("polydraw:history:redo",{canUndo:this.canUndo(),canRedo:this.canRedo(),action:n.action}),n}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}clear(){this.undoStack=[],this.redoStack=[],this.currentMemoryUsage=0,this.eventManager.emit("polydraw:history:changed",{canUndo:this.canUndo(),canRedo:this.canRedo()})}setRestoring(e){this.isRestoring=e}createSnapshot(e,t,r){const o=[],n=[];e.forEach(e=>{e.eachLayer(t=>{var r;const i=t;if(null==i?void 0:i.toGeoJSON)try{const a=i.toGeoJSON();if(!a)return;const s=null==(r=null==a?void 0:a.geometry)?void 0:r.type;"Polygon"!==s&&"MultiPolygon"!==s||(o.push(a),n.push(this.captureFeatureMetadataSnapshot(e,t)))}catch(a){console.warn("Error converting polygon to GeoJSON:",a)}})});const i={features:o,timestamp:Date.now(),action:t};return r&&(i.layerSnapshot=r.captureLayerSnapshot(e)),n.length>0&&(i.featureMetadataSnapshot=n),i}captureFeatureMetadataSnapshot(e,t){const r={},o=e._polydrawMetadata;if((null==o?void 0:o.id)&&(r.id=o.id),(null==o?void 0:o.metadata)&&(r.metadata=yi(o.metadata)),Array.isArray(null==o?void 0:o.sourceFeatureIds)&&(r.sourceFeatureIds=[...o.sourceFeatureIds]),(null==o?void 0:o.interactionOverride)&&(r.interactionOverride=o.interactionOverride),(null==o?void 0:o.styleOverrides)&&(r.styleOverrides=yi(o.styleOverrides)),"boolean"==typeof(null==o?void 0:o.hasHoles)&&(r.hasHoles=o.hasHoles),"string"==typeof(null==o?void 0:o.layerId)&&(r.layerId=o.layerId),(null==o?void 0:o.createdAt)instanceof Date&&!Number.isNaN(o.createdAt.getTime())&&(r.createdAt=o.createdAt.toISOString()),(null==o?void 0:o.lastModified)instanceof Date&&!Number.isNaN(o.lastModified.getTime())&&(r.lastModified=o.lastModified.toISOString()),t instanceof s.Polygon){const e=t;"number"==typeof e._polydrawOptimizationLevel&&(r.optimizationLevel=e._polydrawOptimizationLevel),"number"==typeof e._polydrawOptimizationOriginalLevel&&(r.originalOptimizationLevel=e._polydrawOptimizationOriginalLevel)}return r}getSnapshotSize(e){if("number"==typeof e.size)return e.size;const t=this.calculateSnapshotSize(e);return e.size=t,t}}class Ni{constructor(e,t){i(this,"eventManager"),i(this,"layers",new Map),i(this,"featureGroupToLayer",new WeakMap),i(this,"activeLayerId","default"),i(this,"defaultColor"),this.eventManager=e,this.defaultColor=Ni.normalizeColor(t),this.ensureDefaultLayer()}getLayerCount(){return this.layers.size}getAllLayers(){return Array.from(this.layers.values()).map(e=>this.cloneLayerState(e))}getPanelLayers(){return this.getAllLayers().filter(e=>"hidden"!==e.panel)}getPanelLayerCount(){let e=0;for(const t of this.layers.values())"hidden"!==t.panel&&(e+=1);return e}getLayer(e){const t=this.layers.get(this.normalizeLayerId(e));return t?this.cloneLayerState(t):void 0}getActiveLayerId(){return this.activeLayerId}getActiveLayer(){return this.getLayer(this.activeLayerId)}getOrCreateLayer(e,t){const r=this.normalizeLayerId(e);if(this.layers.get(r))return this.cloneLayerState(this.layers.get(r));const o="string"==typeof t?{color:t}:t||{},n={id:r,label:o.label,color:o.color?Ni.normalizeColor(o.color,this.defaultColor):this.defaultColor,visible:!1!==o.visible,interaction:this.normalizeInteraction(o.interaction),panel:this.normalizePanel(o.panel),metadata:this.cloneMetadata(o.metadata),featureGroups:[]};return this.layers.set(r,n),this.eventManager.emit("polydraw:layer:created",{layerId:n.id,color:n.color}),this.cloneLayerState(n)}setActiveLayer(e){return"activated"===this.setActiveLayerWithResult(e)}setActiveLayerWithResult(e){const t=this.normalizeLayerId(e),r=this.layers.get(t);if(!r)return"not-found";if(t===this.activeLayerId)return"already-active";if(!r.visible)return"not-visible";const o=this.activeLayerId;return this.activeLayerId=t,this.eventManager.emit("polydraw:layer:activated",{layerId:t,previousLayerId:o}),"activated"}setLayerVisibility(e,t){const r=this.layers.get(this.normalizeLayerId(e));if(!r||r.visible===t)return!1;if(!t&&r.id===this.activeLayerId){const e=this.getFirstVisibleLayerId(r.id);if(!e)return!1;this.setActiveLayer(e)}return r.visible=t,this.eventManager.emit("polydraw:layer:visibility",{layerId:r.id,visible:t}),!0}setLayerColor(e,t){const r=this.layers.get(this.normalizeLayerId(e)),o=Ni.normalizeColor(t,(null==r?void 0:r.color)??this.defaultColor);return!(!r||r.color===o)&&(r.color=o,r.featureGroups.forEach(e=>{var t,r;const n=null==(r=null==(t=e._polydrawMetadata)?void 0:t.styleOverrides)?void 0:r.color;e.eachLayer(e=>{e instanceof s.Polygon&&!(e instanceof s.Rectangle)&&e.setStyle({color:n??o})})}),this.eventManager.emit("polydraw:layer:colorChanged",{layerId:r.id,color:r.color}),!0)}setLayerLabel(e,t){const r=this.layers.get(this.normalizeLayerId(e));if(!r)return!1;const o="string"==typeof t?t.trim():void 0,n=o&&o.length>0?o:void 0;return r.label!==n&&(r.label=n,!0)}setLayerInteraction(e,t){const r=this.layers.get(this.normalizeLayerId(e));if(!r)return!1;const o=this.normalizeInteraction(t);return r.interaction!==o&&(r.interaction=o,!0)}setLayerPanelVisibility(e,t){const r=this.layers.get(this.normalizeLayerId(e));if(!r)return!1;const o=this.normalizePanel(t);return r.panel!==o&&(r.panel=o,!0)}setLayerMetadata(e,t){const r=this.layers.get(this.normalizeLayerId(e));return!!r&&(r.metadata=this.cloneMetadata(t),!0)}isLayerEditable(e){const t=this.layers.get(this.normalizeLayerId(e));return!t||"editable"===t.interaction}isFeatureGroupEditable(e){var t;const r=null==(t=e._polydrawMetadata)?void 0:t.interactionOverride;if(r)return"editable"===r;const o=this.getLayerForFeatureGroup(e);return!o||this.isLayerEditable(o)}moveLayer(e,t){const r=this.normalizeLayerId(e),o=this.normalizeLayerId(t);if(r===o)return!1;if("default"===r||"default"===o)return!1;if(!this.layers.has(r)||!this.layers.has(o))return!1;const n=Array.from(this.layers.keys()),i=n.indexOf(r),a=n.indexOf(o);if(i<0||a<0)return!1;const[s]=n.splice(i,1);n.splice(a,0,s);const l=new Map;for(const c of n){const e=this.layers.get(c);e&&l.set(c,e)}return this.layers=l,this.eventManager.emit("polydraw:layer:reordered",{layerId:r,targetLayerId:o,orderedLayerIds:n}),!0}assignFeatureGroupToLayer(e,t){const r=this.normalizeLayerId(t);if(!this.layers.has(r))return!1;const o=this.getLayerForFeatureGroup(e);if(o===r)return!1;if(o){const t=this.layers.get(o);t&&(t.featureGroups=t.featureGroups.filter(t=>t!==e))}const n=this.layers.get(r);n.featureGroups.includes(e)||n.featureGroups.push(e),this.featureGroupToLayer.set(e,r);const i=e._polydrawMetadata;return i&&(i.layerId=r),!0}removeFeatureGroupFromLayer(e){const t=this.getLayerForFeatureGroup(e);if(!t)return;const r=this.layers.get(t);r&&(r.featureGroups=r.featureGroups.filter(t=>t!==e)),this.featureGroupToLayer.delete(e);const o=e._polydrawMetadata;o&&delete o.layerId}getLayerForFeatureGroup(e){const t=this.featureGroupToLayer.get(e);if(t)return t;for(const[r,o]of this.layers.entries())if(o.featureGroups.includes(e))return this.featureGroupToLayer.set(e,r),r}getFeatureGroupsForLayer(e){const t=this.layers.get(this.normalizeLayerId(e));return t?[...t.featureGroups]:[]}isInActiveLayer(e){const t=this.getLayerForFeatureGroup(e);return!t||t===this.activeLayerId}deleteLayer(e){const t=this.normalizeLayerId(e);if("default"===t)return[];const r=this.layers.get(t);if(!r)return[];const o=[...r.featureGroups];if(o.forEach(e=>{this.featureGroupToLayer.delete(e)}),this.layers.delete(t),this.activeLayerId===t){const e=this.getFirstVisibleLayerId(t);e?this.setActiveLayer(e):this.activeLayerId="default"}return this.eventManager.emit("polydraw:layer:deleted",{layerId:t,removedFeatureGroups:o}),o}moveLayerToIndex(e,t){const r=this.normalizeLayerId(e);if("default"===r||!this.layers.has(r)||!Number.isFinite(t))return!1;const o=Array.from(this.layers.keys()),n=o.indexOf(r),i=Math.trunc(t),a=Math.max(1,Math.min(i,o.length-1));if(n===a)return!1;o.splice(n,1),o.splice(a,0,r);const s=new Map;for(const l of o){const e=this.layers.get(l);e&&s.set(l,e)}return this.layers=s,this.eventManager.emit("polydraw:layer:reordered",{layerId:r,targetLayerId:o[a]??r,orderedLayerIds:o}),!0}setLayerOrder(e){if(!e||0===e.length)return!1;const t=e.map(e=>this.normalizeLayerId(e));if(new Set(t).size!==t.length)return!1;for(const s of t)if("default"===s||!this.layers.has(s))return!1;const r=Array.from(this.layers.keys()),o=new Set(t),n=Array.from(this.layers.keys()).filter(e=>"default"!==e&&!o.has(e)),i=["default",...t,...n];if(r.length===i.length&&r.every((e,t)=>e===i[t]))return!1;const a=new Map;for(const s of i){const e=this.layers.get(s);e&&a.set(s,e)}return this.layers=a,this.eventManager.emit("polydraw:layer:reordered",{layerId:t[0],targetLayerId:t[t.length-1],orderedLayerIds:i}),!0}clear(e){e&&(this.defaultColor=Ni.normalizeColor(e,this.defaultColor)),this.layers=new Map,this.featureGroupToLayer=new WeakMap,this.activeLayerId="default",this.ensureDefaultLayer()}captureLayerSnapshot(e){const t=new Map;return e.forEach((e,r)=>{t.set(e,r)}),{layers:this.getAllLayers().map(e=>({id:e.id,label:e.label,color:e.color,visible:e.visible,interaction:e.interaction,panel:e.panel,metadata:this.cloneMetadata(e.metadata),featureIndices:e.featureGroups.map(e=>t.get(e)).filter(e=>"number"==typeof e)})),activeLayerId:this.activeLayerId}}restoreFromLayerSnapshot(e,t){if(this.clear(),!e||!Array.isArray(e.layers))return;e.layers.forEach(e=>{const t=this.normalizeLayerId(e.id),r=this.layers.get(t);r?(r.label="string"==typeof e.label?e.label:void 0,r.color=e.color?Ni.normalizeColor(e.color):r.color,r.visible=!1!==e.visible,r.interaction=this.normalizeInteraction(e.interaction),r.panel=this.normalizePanel(e.panel),r.metadata=this.cloneMetadata(e.metadata)):this.layers.set(t,{id:t,label:"string"==typeof e.label?e.label:void 0,color:e.color?Ni.normalizeColor(e.color):this.defaultColor,visible:!1!==e.visible,interaction:this.normalizeInteraction(e.interaction),panel:this.normalizePanel(e.panel),metadata:this.cloneMetadata(e.metadata),featureGroups:[]})}),this.ensureDefaultLayer(),e.layers.forEach(e=>{const r=this.normalizeLayerId(e.id),o=this.layers.get(r);o&&e.featureIndices.forEach(e=>{const n=t[e];n&&(o.featureGroups.includes(n)||o.featureGroups.push(n),this.featureGroupToLayer.set(n,r))})});const r=this.normalizeLayerId(e.activeLayerId||"default"),o=this.layers.get(r);if(null==o?void 0:o.visible)return void(this.activeLayerId=r);const n=this.getFirstVisibleLayerId();if(n)return void(this.activeLayerId=n);const i=this.layers.get("default");i&&(i.visible=!0),this.activeLayerId="default"}ensureDefaultLayer(){this.layers.has("default")||this.layers.set("default",{id:"default",color:this.defaultColor,visible:!0,interaction:"editable",panel:"visible",metadata:{},featureGroups:[]})}getFirstVisibleLayerId(e){for(const t of this.layers.values())if(t.id!==e&&t.visible)return t.id}normalizeLayerId(e){const t=(e||"").trim();return t.length>0?t:"default"}cloneLayerState(e){return{id:e.id,label:e.label,color:e.color,visible:e.visible,interaction:e.interaction,panel:e.panel,metadata:this.cloneMetadata(e.metadata),featureGroups:[...e.featureGroups]}}normalizeInteraction(e){return"readonly"===e||"static"===e?e:"editable"}normalizePanel(e){return"hidden"===e?"hidden":"visible"}cloneMetadata(e){return e?yi(e):{}}static normalizeColor(e,t="#50622b"){let r=(e||"").trim().replace(/^#/,"");return 3===r.length&&(r=`${r[0]}${r[0]}${r[1]}${r[1]}${r[2]}${r[2]}`),/^[0-9a-fA-F]{6}$/.test(r)?`#${r.toLowerCase()}`:t}}const Ri=e=>e.replace(/#(?:fff|ffffff)/gi,"currentColor"),Xi={grip:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">\n <circle cx="9" cy="5" r="1" />\n <circle cx="9" cy="12" r="1" />\n <circle cx="9" cy="19" r="1" />\n <circle cx="15" cy="5" r="1" />\n <circle cx="15" cy="12" r="1" />\n <circle cx="15" cy="19" r="1" />\n</svg>\n'.trim(),eyeVisible:Ri('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">\n <defs>\n <mask id="pupil-hole-hide">\n <rect width="512" height="512" fill="white"/>\n <circle cx="256" cy="220" r="60" fill="black"/>\n </mask>\n </defs>\n <g fill="none" stroke="#fff" stroke-linecap="round" stroke-linejoin="round">\n \x3c!-- Upper eye contour --\x3e\n <path d="M24 256 C 120 93 392 93 488 256" stroke-width="48"/>\n \x3c!-- Lower eye contour --\x3e\n <path d="M24 256 C 120 419 392 419 488 256" stroke-width="48"/>\n \x3c!-- Iris highlight --\x3e\n <circle cx="256" cy="234" r="108" fill="#fff" stroke="none" mask="url(#pupil-hole-hide)"/>\n </g>\n</svg>\n'.trim()),eyeHidden:Ri('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">\n <g fill="none" stroke="#fff" stroke-linecap="round" stroke-linejoin="round">\n \x3c!-- Upper eye contour --\x3e\n <path d="M24 256 C 120 93 392 93 488 256" stroke-width="48"/>\n \x3c!-- Lower eye contour --\x3e\n <path d="M24 256 C 120 419 392 419 488 256" stroke-width="48"/>\n \x3c!-- Diagonal hide slash --\x3e\n <path d="M48 408 L464 104" stroke-width="48"/>\n </g>\n</svg>\n'.trim()),delete:ii.trim(),toggle:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor">\n <path d="M3 7.5 12 3l9 4.5L12 12 3 7.5Z" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />\n <path d="M3 12.5 12 17l9-4.5" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />\n <path d="M3 17 12 21l9-4" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />\n <polyline points="14 9.5 17 12 14 14.5" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />\n</svg>\n'.trim()};class Yi{static calculateAngle(e,t,r){const o=e.lng-t.lng,n=e.lat-t.lat,i=r.lng-t.lng,a=r.lat-t.lat,s=o*i+n*a,l=Math.sqrt(o*o+n*n),c=Math.sqrt(i*i+a*a);if(0===l||0===c)return 0;const u=s/(l*c);return Math.acos(Math.max(-1,Math.min(1,u)))}static calculateDistanceFromLine(e,t,r){const o=t.lng-e.lng,n=t.lat-e.lat,i=r.lng-e.lng,a=r.lat-e.lat,s=o*i+n*a,l=i*i+a*a;if(0===l)return Math.sqrt(o*o+n*n);const c=s/l;let u,h;c<0?(u=e.lng,h=e.lat):c>1?(u=r.lng,h=r.lat):(u=e.lng+c*i,h=e.lat+c*a);const g=t.lng-u,d=t.lat-h;return Math.sqrt(g*g+d*d)}static calculateCentroid(e){return ci.getCenter(e)}static calculateDistance(e,t){const r=e.lng-t.lng,o=e.lat-t.lat;return Math.sqrt(r*r+o*o)}static offsetPolygonCoordinates(e,t,r){return e?Array.isArray(e[0])?e.map(e=>Yi.offsetPolygonCoordinates(e,t,r)):void 0!==e.lat&&void 0!==e.lng?{lat:e.lat+t,lng:e.lng+r}:e.map(e=>Yi.offsetPolygonCoordinates(e,t,r)):e}}class Vi{static convertToCoords(e,t){const r=[];if(e.length>1&&e.length<3){const o=[];t.isWithin(s.GeoJSON.latLngsToCoords(e[e.length-1]),s.GeoJSON.latLngsToCoords(e[0]))?e.forEach(e=>{o.push(s.GeoJSON.latLngsToCoords(e))}):e.forEach(e=>{r.push([s.GeoJSON.latLngsToCoords(e)])}),o.length>=1&&r.push(o)}else if(e.length>2){const o=[];for(let n=1;n<e.length-1;n++){t.isWithin(s.GeoJSON.latLngsToCoords(e[n]),s.GeoJSON.latLngsToCoords(e[0]))?(e.forEach(e=>{o.push(s.GeoJSON.latLngsToCoords(e))}),r.push(o)):e.forEach(e=>{r.push([s.GeoJSON.latLngsToCoords(e)])})}}else r.push([s.GeoJSON.latLngsToCoords(e[0])]);return r}static offsetPolygonCoordinates(e,t,r){return Yi.offsetPolygonCoordinates(e,t,r)}static getLatLngInfoString(e){return"Latitude: "+e.lat+" Longitude: "+e.lng}static convertToLatLng(e){if("object"==typeof e&&null!==e){if("lat"in e&&"lng"in e)return oi.createLatLng(e.lat,e.lng);if("latitude"in e&&"longitude"in e)return oi.createLatLng(e.latitude,e.longitude);if("longitude"in e&&"latitude"in e)return oi.createLatLng(e.latitude,e.longitude);if("lng"in e&&"lat"in e)return oi.createLatLng(e.lat,e.lng)}if(Array.isArray(e)&&e.length>=2){const[t,r]=e;if("number"==typeof t&&"number"==typeof r){const e=Math.abs(t),o=Math.abs(r);return e>90&&o<=90?oi.createLatLng(r,t):o>90&&e<=90?oi.createLatLng(t,r):e>90||o>90?oi.createLatLng(r,t):oi.createLatLng(t,r)}}if("string"==typeof e){const t=e.trim(),r=t.match(/(\d+)°(\d+)'(?:(\d+(?:\.\d+)?)")?([NS])\s*,?\s*(\d+)°(\d+)'(?:(\d+(?:\.\d+)?)")?([EW])/i);if(r){const[,e,t,o,n,i,a,s,l]=r,c=parseFloat(e)+parseFloat(t)/60+parseFloat(o||"0")/3600,u=parseFloat(i)+parseFloat(a)/60+parseFloat(s||"0")/3600,h="S"===n.toUpperCase()?-c:c,g="W"===l.toUpperCase()?-u:u;return oi.createLatLng(h,g)}const o=t.match(/(\d+)°(\d+(?:\.\d+)?)'([NS])\s*,?\s*(\d+)°(\d+(?:\.\d+)?)'([EW])/i);if(o){const[,e,t,r,n,i,a]=o,s=parseFloat(e)+parseFloat(t)/60,l=parseFloat(n)+parseFloat(i)/60,c="S"===r.toUpperCase()?-s:s,u="W"===a.toUpperCase()?-l:l;return oi.createLatLng(c,u)}const n=t.match(/([+-]?(?:\d+(?:\.\d+)?|\.\d+))°?\s*([NS])(?:\s*,\s*|\s+)([+-]?(?:\d+(?:\.\d+)?|\.\d+))°?\s*([EW])/i);if(n){const[,e,t,r,o]=n,i=Math.abs(parseFloat(e)),a=Math.abs(parseFloat(r)),s="S"===t.toUpperCase()?-i:i,l="W"===o.toUpperCase()?-a:a;return oi.createLatLng(s,l)}const i=t.match(/([NS])\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s+([EW])\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))/i);if(i){const[,e,t,r,o]=i,n=Math.abs(parseFloat(t)),a=Math.abs(parseFloat(o)),s="S"===e.toUpperCase()?-n:n,l="W"===r.toUpperCase()?-a:a;return oi.createLatLng(s,l)}const a=t.match(/^\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*,\s*([+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*$/);if(a){const[,e,t]=a;return this.convertToLatLng([parseFloat(e),parseFloat(t)])}if(t.match(/(?:UTM\s+)?(\d+)([NS])\s+(\d+(?:\.\d+)?)\s+(\d+(?:\.\d+)?)/i))throw new Error(`UTM coordinates detected: ${t}. UTM conversion requires specialized libraries like proj4js. Please convert to decimal degrees first.`);if(t.match(/(\d+)([A-Z])\s+([A-Z]{2})\s+(\d+)\s+(\d+)/i))throw new Error(`MGRS coordinates detected: ${t}. MGRS conversion requires specialized libraries. Please convert to decimal degrees first.`);if(t.match(/^[23456789CFGHJMPQRVWX]{2,3}[23456789CFGHJMPQRVWX]{3,7}\+[23456789CFGHJMPQRVWX]{2,3}$/i))throw new Error(`Plus Code detected: ${t}. Plus Code conversion requires specialized libraries. Please convert to decimal degrees first.`)}throw new Error(`Unable to convert coordinate: ${JSON.stringify(e)}`)}static convertToLatLngArray(e){return e.map(e=>e.map(e=>e.map(e=>this.convertToLatLng(e))))}}const qi={draw:"draw",subtract:"subtract",p2p:"p2p",p2pSubtract:"p2pSubtract",deleteAll:"erase",clonePolygons:"clone"};const ji=new Set([u.SouthWest,u.South,u.SouthEast,u.East,u.NorthEast,u.North,u.NorthWest,u.West]);function Wi(e,t,r){return"number"==typeof e&&Number.isFinite(e)&&ji.has(e)?e:(console.warn(`[Leaflet.Polydraw] Invalid \`${r}\` value "${String(e)}". Using "${u[t]}" (${t}) as fallback.`),t)}function $i(e){e.markers.markerInfoIcon.position=Wi(e.markers.markerInfoIcon.position,g.markers.markerInfoIcon.position,"markers.markerInfoIcon.position"),e.markers.markerMenuIcon.position=Wi(e.markers.markerMenuIcon.position,g.markers.markerMenuIcon.position,"markers.markerMenuIcon.position"),e.markers.markerDeleteIcon.position=Wi(e.markers.markerDeleteIcon.position,g.markers.markerDeleteIcon.position,"markers.markerDeleteIcon.position")}function Ki(e){const t=Qn({},e??{});return function(e){var t,r,o,n;if(!e)return;const i=e,a=e.modes;if(a){const t=Object.keys(qi).filter(e=>void 0!==a[e]);if(t.length>0){console.warn("[Leaflet.Polydraw] `config.modes.*` tool toggles are deprecated in v2. Use `config.tools.*` (draw/subtract/p2p/clone/erase) instead."),e.tools||(e.tools={});for(const r of t){const t=qi[r];void 0===e.tools[t]&&(e.tools[t]=a[r])}}}const s=(null==(t=e.markers)?void 0:t.visualOptimization)??{};(Object.prototype.hasOwnProperty.call(s,"useAngles")||Object.prototype.hasOwnProperty.call(s,"useBoundingBox")||Object.prototype.hasOwnProperty.call(s,"useDistance")||Object.prototype.hasOwnProperty.call(s,"thresholdBoundingBox")||Object.prototype.hasOwnProperty.call(s,"thresholdDistance")||Object.prototype.hasOwnProperty.call(s,"sharpAngleThreshold"))&&console.warn("[Leaflet.Polydraw] `markers.visualOptimization` is deprecated. Prefer `visualOptimizationLevel` when adding predefined polygons.");const l=e.maxHistorySize;"number"==typeof l&&(console.warn("[Leaflet.Polydraw] `config.maxHistorySize` is deprecated in v2. Use `config.history.maxSize` instead."),e.history||(e.history={}),void 0===e.history.maxSize&&(e.history.maxSize=l));const c=e.boundingBox;c&&"boolean"==typeof c.addMidPointMarkers&&(console.warn("[Leaflet.Polydraw] `config.boundingBox` is deprecated in v2. Use `config.polygonTools.bbox` instead."),e.polygonTools||(e.polygonTools={}),e.polygonTools.bbox||(e.polygonTools.bbox={}),void 0===e.polygonTools.bbox.addMidPointMarkers&&(e.polygonTools.bbox.addMidPointMarkers=c.addMidPointMarkers));const u=e.bezier;if(u&&(void 0!==u.resolution||void 0!==u.sharpness||void 0!==u.resampleMultiplier||void 0!==u.maxNodes||void 0!==u.visualOptimizationLevel||void 0!==u.ghostMarkers)){console.warn("[Leaflet.Polydraw] `config.bezier` is deprecated in v2. Use `config.polygonTools.bezier` instead."),e.polygonTools||(e.polygonTools={}),e.polygonTools.bezier||(e.polygonTools.bezier={});const t=e.polygonTools.bezier;for(const e of Object.keys(u))void 0!==u[e]&&void 0===t[e]&&(t[e]=u[e])}const h=e.polygonCreation,g=i.polygonCreation;if(void 0!==(null==g?void 0:g.method)){console.warn("[Leaflet.Polydraw] `config.polygonCreation.method` is deprecated in v2. Use `config.polygonCreation.algorithm` instead."),e.polygonCreation||(e.polygonCreation={});const t=e.polygonCreation;void 0===t.algorithm&&(t.algorithm=g.method)}const d=i.simplification;if(void 0!==(null==d?void 0:d.mode)){console.warn("[Leaflet.Polydraw] `config.simplification.mode` is deprecated in v2. Use `config.simplification.strategy` instead."),e.simplification||(e.simplification={});const t=e.simplification;void 0===t.strategy&&(t.strategy=d.mode)}"buffer"===(null==h?void 0:h.algorithm)&&console.warn('[Leaflet.Polydraw] `polygonCreation.algorithm: "buffer"` is deprecated and no longer supported. Falling back to "concaveman". Use "concaveman" or "direct" instead.');const p=void 0!==i.polyLineOptions,f=void 0!==i.subtractLineOptions,y=void 0!==i.polygonOptions,m=void 0!==i.holeOptions,v=void 0!==i.colors;if(p||f||y||m||v){console.warn("[Leaflet.Polydraw] `polyLineOptions`, `subtractLineOptions`, `polygonOptions`, `holeOptions`, and `colors` are deprecated in v2. Use the unified `config.styles` block instead."),e.styles||(e.styles={});const t=e.styles;if(p){t.polyline||(t.polyline={});const e=i.polyLineOptions;void 0!==e.weight&&void 0===t.polyline.weight&&(t.polyline.weight=e.weight),void 0!==e.opacity&&void 0===t.polyline.opacity&&(t.polyline.opacity=e.opacity)}if(f){t.subtractLine||(t.subtractLine={});const e=i.subtractLineOptions;void 0!==e.weight&&void 0===t.subtractLine.weight&&(t.subtractLine.weight=e.weight),void 0!==e.opacity&&void 0===t.subtractLine.opacity&&(t.subtractLine.opacity=e.opacity)}if(y){t.polygon||(t.polygon={});const e=i.polygonOptions;void 0!==e.weight&&void 0===t.polygon.weight&&(t.polygon.weight=e.weight),void 0!==e.opacity&&void 0===t.polygon.opacity&&(t.polygon.opacity=e.opacity),void 0!==e.fillOpacity&&void 0===t.polygon.fillOpacity&&(t.polygon.fillOpacity=e.fillOpacity),void 0!==e.smoothFactor&&void 0===t.polygon.smoothFactor&&(t.polygon.smoothFactor=e.smoothFactor),void 0!==e.noClip&&void 0===t.polygon.noClip&&(t.polygon.noClip=e.noClip)}if(m){t.hole||(t.hole={});const e=i.holeOptions;void 0!==e.weight&&void 0===t.hole.weight&&(t.hole.weight=e.weight),void 0!==e.opacity&&void 0===t.hole.opacity&&(t.hole.opacity=e.opacity),void 0!==e.fillOpacity&&void 0===t.hole.fillOpacity&&(t.hole.fillOpacity=e.fillOpacity)}if(v){const e=i.colors;if(void 0!==e.polyline&&(t.polyline||(t.polyline={}),void 0===t.polyline.color&&(t.polyline.color=e.polyline)),void 0!==e.subtractLine&&(t.subtractLine||(t.subtractLine={}),void 0===t.subtractLine.color&&(t.subtractLine.color=e.subtractLine)),e.polygon&&(t.polygon||(t.polygon={}),void 0!==e.polygon.border&&void 0===t.polygon.color&&(t.polygon.color=e.polygon.border),void 0!==e.polygon.fill&&void 0===t.polygon.fillColor&&(t.polygon.fillColor=e.polygon.fill)),e.hole&&(t.hole||(t.hole={}),void 0!==e.hole.border&&void 0===t.hole.color&&(t.hole.color=e.hole.border),void 0!==e.hole.fill&&void 0===t.hole.fillColor&&(t.hole.fillColor=e.hole.fill)),e.styles){t.ui||(t.ui={});const r=e.styles,o=t.ui;r.controlButton&&!o.controlButton&&(o.controlButton=r.controlButton),r.controlButtonHover&&!o.controlButtonHover&&(o.controlButtonHover=r.controlButtonHover),r.controlButtonActive&&!o.controlButtonActive&&(o.controlButtonActive=r.controlButtonActive),r.indicatorActive&&!o.indicatorActive&&(o.indicatorActive=r.indicatorActive),r.p2pMarker&&!o.p2pMarker&&(o.p2pMarker=r.p2pMarker)}void 0!==(null==(r=e.p2p)?void 0:r.closingMarker)&&(t.ui||(t.ui={}),t.ui.p2pClosingMarker||(t.ui.p2pClosingMarker={color:e.p2p.closingMarker})),void 0!==e.edgeHover&&(t.ui||(t.ui={}),t.ui.edgeHover||(t.ui.edgeHover={color:e.edgeHover})),void 0!==(null==(o=e.edgeDeletion)?void 0:o.hover)&&(t.ui||(t.ui={}),t.ui.edgeDeletion||(t.ui.edgeDeletion={color:e.edgeDeletion.hover})),void 0!==(null==(n=e.dragPolygons)?void 0:n.subtract)&&(t.ui||(t.ui={}),t.ui.dragSubtract||(t.ui.dragSubtract={color:e.dragPolygons.subtract}))}}void 0!==i.defaultMode&&(console.warn("[Leaflet.Polydraw] `config.defaultMode` is deprecated in v2. Use `config.tools.default` instead."),e.tools||(e.tools={}),void 0===e.tools.default&&(e.tools.default=i.defaultMode)),void 0!==i.dragPolygons&&(console.warn("[Leaflet.Polydraw] `config.dragPolygons` is deprecated in v2. Use `config.interaction.drag` instead."),e.interaction||(e.interaction={}),e.interaction.drag||(e.interaction.drag=i.dragPolygons)),void 0!==i.edgeDeletion&&(console.warn("[Leaflet.Polydraw] `config.edgeDeletion` is deprecated in v2. Use `config.interaction.edgeDeletion` instead."),e.interaction||(e.interaction={}),e.interaction.edgeDeletion||(e.interaction.edgeDeletion=i.edgeDeletion)),void 0!==i.menuOperations&&(console.warn("[Leaflet.Polydraw] `config.menuOperations` is deprecated in v2. Use `config.polygonTools` instead."),e.polygonTools||(e.polygonTools=i.menuOperations))}(t),t}class Ji extends s.Control{constructor(e){super(e),i(this,"map"),i(this,"tracer",null),i(this,"turfHelper"),i(this,"subContainer"),i(this,"config"),i(this,"mapStateService"),i(this,"eventManager"),i(this,"polygonInformation"),i(this,"modeManager"),i(this,"polygonDrawManager"),i(this,"polygonMutationManager"),i(this,"historyManager"),i(this,"layerManager"),i(this,"layerPanel",null),i(this,"arrayOfFeatureGroups",[]),i(this,"drawMode",c.Off),i(this,"drawModeListeners",[]),i(this,"_boundKeyDownHandler"),i(this,"_boundKeyUpHandler"),i(this,"isModifierKeyHeld",!1),i(this,"modifierModeOverride",null),i(this,"isDrawingInProgress",!1),i(this,"mapEventsAttached",!1),i(this,"drawEventsAttached",!1),i(this,"controlEvents",new WeakSet),i(this,"lastControlPointerDown",null),i(this,"_boundMouseMove"),i(this,"_boundMouseUp"),i(this,"_boundTouchMove"),i(this,"_boundTouchEnd"),i(this,"_boundTouchCancel"),i(this,"_boundTouchStart"),i(this,"_boundPointerDown"),i(this,"_boundPointerMove"),i(this,"_boundPointerUp"),i(this,"_boundPointerCancel"),i(this,"_boundContextMenu"),i(this,"_lastTapTime",0),i(this,"_lastTapLatLng",null),i(this,"_tapTimeout",null),i(this,"pointerEventsHandled","undefined"!=typeof window&&"PointerEvent"in window&&ri.isV2()),i(this,"_configReady",null),i(this,"_componentsInitialized",!1),i(this,"_isControlMounted",!1),i(this,"_isRestoringSnapshot",!1),i(this,"_coreEventListenersAttached",!1),i(this,"_coreEventSubscriptions",[]),i(this,"_initRequestId",0),i(this,"_historySuppressionDepth",0),i(this,"_lastAppliedVisibleMapOrder",[]),i(this,"originalMapTouchAction",null),i(this,"_handleActivateToggle",()=>{const e=this.getContainer();if(!e)return;const t=e.querySelector(".icon-activate");if(oi.domUtil.hasClass(t,"active"))oi.domUtil.removeClass(t,"active"),this.subContainer&&(this.subContainer.style.maxHeight="0px",this.subContainer.style.overflow="hidden");else if(oi.domUtil.addClass(t,"active"),this.subContainer){const e=this.subContainer.scrollHeight;this.subContainer.style.maxHeight=`${e||250}px`,this.subContainer.style.overflow="visible"}this.updateActivateButtonIndicator()}),i(this,"_handleDrawClick",e=>{e&&(e.preventDefault(),e.stopPropagation()),this.modeManager.getCurrentMode()!==c.Add?(this.setDrawMode(c.Add),this.polygonInformation.saveCurrentState()):this.setDrawMode(c.Off)}),i(this,"_handleSubtractClick",e=>{e&&(e.preventDefault(),e.stopPropagation()),this.modeManager.getCurrentMode()!==c.Subtract?(this.setDrawMode(c.Subtract),this.polygonInformation.saveCurrentState()):this.setDrawMode(c.Off)}),i(this,"_handleCloneClick",e=>{e&&(e.preventDefault(),e.stopPropagation()),0!==this.arrayOfFeatureGroups.length&&(this.modeManager.getCurrentMode()!==c.Clone?(this.setDrawMode(c.Clone),this.polygonInformation.saveCurrentState()):this.setDrawMode(c.Off))}),i(this,"_handleEraseClick",e=>{e&&(e.preventDefault(),e.stopPropagation());const t=this.config.tools.eraseScope??"all";0!==("defaultLayer"===t?this.layerManager.getFeatureGroupsForLayer("default"):this.arrayOfFeatureGroups).length&&(this.map.closePopup(),this.saveHistory("eraseAll"),"defaultLayer"!==t?this.removeAllFeatureGroups():this.removeDefaultLayerFeatureGroups())}),i(this,"_handlePointToPointClick",e=>{e&&(e.preventDefault(),e.stopPropagation()),this.modeManager.getCurrentMode()!==c.PointToPoint?(this.setDrawMode(c.PointToPoint),this.polygonInformation.saveCurrentState()):this.setDrawMode(c.Off)}),i(this,"_handlePointToPointSubtractClick",e=>{e&&(e.preventDefault(),e.stopPropagation()),this.modeManager.getCurrentMode()!==c.PointToPointSubtract?(this.setDrawMode(c.PointToPointSubtract),this.polygonInformation.saveCurrentState()):this.setDrawMode(c.Off)}),i(this,"_handleUndoClick",e=>{e&&(e.preventDefault(),e.stopPropagation()),this.undo()}),i(this,"_handleRedoClick",e=>{e&&(e.preventDefault(),e.stopPropagation()),this.redo()}),i(this,"onMarkerHoverForEdgeDeletionEvent",e=>{if(!this.isModifierKeyHeld)return;const t=e.target;t&&(t.style.backgroundColor=this.config.styles.ui.edgeDeletion.color,t.style.borderColor=this.config.styles.ui.edgeDeletion.color,t.classList.add("edge-deletion-hover"))}),i(this,"onMarkerLeaveForEdgeDeletionEvent",e=>{const t=e.target;t&&(t.style.backgroundColor="",t.style.borderColor="",t.classList.remove("edge-deletion-hover"))});const t=structuredClone(g),r=Ki(null==e?void 0:e.config);this.config=Qn(t,r),$i(this.config),(null==e?void 0:e.configPath)?this._configReady=this.loadExternalConfig(e.configPath,r):(this.initializeComponents(),this._configReady=Promise.resolve())}onAdd(e){const t=e,r=s.Browser;t._onResize=()=>{},r.touch&&r.mobile&&(t.tap=!1),this.map=e,this._isControlMounted=!0;const o=++this._initRequestId;this.setupKeyboardHandlers();const n=oi.domUtil.create("div","leaflet-control leaflet-bar");return this.initializeUI(n),this.createTracer(),this.completeInitialization(o),n}completeInitialization(e){var t;const r=()=>{this._isControlMounted&&e===this._initRequestId&&(this.initializeManagers(),this.setDrawMode(this.config.tools.default),this.setupEventListeners())};this._componentsInitialized?r():null==(t=this._configReady)||t.then(()=>{r()}).catch(()=>{})}onRemove(e){this._isControlMounted=!1,this._initRequestId+=1,this.comprehensiveCleanup()}comprehensiveCleanup(){if(this.events(!1),this.drawStartedEvents(!1),this.setMapDrawingTouchLock(!1),this.removeKeyboardHandlers(),this.tracer){try{this.map.hasLayer(this.tracer)?this.map.removeLayer(this.tracer):this.tracer.remove()}catch{}this.tracer=null}if(this.arrayOfFeatureGroups.forEach(e=>{try{this.polygonMutationManager&&this.polygonMutationManager.cleanupFeatureGroup(e),this.map.removeLayer(e)}catch(t){console.warn("Error cleaning up feature group:",t)}}),this.arrayOfFeatureGroups.length=0,this._lastAppliedVisibleMapOrder=[],this.polygonMutationManager&&this.polygonMutationManager.dispose(),this.removeCoreEventListeners(),this.polygonInformation&&this.polygonInformation.deletePolygonInformationStorage(),this.drawModeListeners.length=0,this._boundKeyDownHandler&&(this._boundKeyDownHandler=void 0),this._boundKeyUpHandler&&(this._boundKeyUpHandler=void 0),this._boundMouseMove&&(this._boundMouseMove=void 0),this._boundMouseUp&&(this._boundMouseUp=void 0),this._boundTouchMove&&(this._boundTouchMove=void 0),this._boundTouchEnd&&(this._boundTouchEnd=void 0),this._boundTouchCancel&&(this._boundTouchCancel=void 0),this._boundTouchStart&&(this._boundTouchStart=void 0),this._boundPointerDown&&(this._boundPointerDown=void 0),this._boundPointerMove&&(this._boundPointerMove=void 0),this._boundPointerUp&&(this._boundPointerUp=void 0),this._boundPointerCancel&&(this._boundPointerCancel=void 0),this._boundContextMenu&&(this._boundContextMenu=void 0),this._tapTimeout&&(clearTimeout(this._tapTimeout),this._tapTimeout=null),this.drawMode=c.Off,this.isModifierKeyHeld=!1,this._lastTapTime=0,this.layerPanel){try{this.layerPanel.remove()}catch{}this.layerPanel=null}this.subContainer=void 0,this._componentsInitialized=!1}addTo(e){return super.addTo(e),this}getFeatureGroups(){return this.arrayOfFeatureGroups}async undo(){if(!this.historyManager.canUndo())return;const e=this.historyManager.undo(this.arrayOfFeatureGroups,this.layerManager);e&&await this.restoreFromSnapshot(e)}isPolygonAction(e){return"simplify"===e||"doubleElbows"===e||"bbox"===e||"bezier"===e||"scale"===e||"rotate"===e||"donut"===e||"toggleOptimization"===e||"polygonMenuAction"===e}shouldCaptureHistory(e){var t,r;const o=null==(t=this.config.history)?void 0:t.capture;return!o||(this.isPolygonAction(e)?!1!==(null==(r=o.polygonActions)?void 0:r[e]):!1!==o[e])}saveHistory(e){this.isHistorySuppressed()||this.shouldCaptureHistory(e)&&this.historyManager.saveState(this.arrayOfFeatureGroups,e,this.layerManager)}isHistorySuppressed(){return this._historySuppressionDepth>0}startHistoryBatch(e){this.isHistorySuppressed()||this.saveHistory(e),this._historySuppressionDepth+=1}endHistoryBatch(){this._historySuppressionDepth>0&&(this._historySuppressionDepth-=1)}async redo(){if(!this.historyManager.canRedo())return;const e=this.historyManager.redo(this.arrayOfFeatureGroups,this.layerManager);e&&await this.restoreFromSnapshot(e)}resolvePredefinedLayerDescriptor(e,t){if(!e)return null;if("string"==typeof e){const r=e.trim();if(!r)throw new Error("Layer id cannot be empty");return{id:r,color:t}}const r=(e.id||"").trim();if(!r)throw new Error("Layer descriptor must include a non-empty id");const o={...e,id:r,color:t??e.color};return"static"===o.interaction&&void 0===o.panel&&(o.panel="hidden"),o}ensureLayerFromDescriptor(e){const t=e.id.trim(),r=this.layerManager.getOrCreateLayer(t,{label:e.label,color:e.color,visible:e.visibility,interaction:e.interaction,panel:e.panel??("static"===e.interaction?"hidden":void 0),metadata:e.metadata});return void 0!==e.label&&this.layerManager.setLayerLabel(t,e.label),e.color&&this.layerManager.setLayerColor(t,e.color),void 0!==e.visibility&&this.layerManager.setLayerVisibility(t,e.visibility),void 0!==e.interaction&&this.layerManager.setLayerInteraction(t,e.interaction),void 0===e.panel&&"static"!==e.interaction||this.layerManager.setLayerPanelVisibility(t,e.panel??("static"===e.interaction?"hidden":"visible")),void 0!==e.metadata&&this.layerManager.setLayerMetadata(t,e.metadata),this.layerManager.getLayer(t)??r}getInteractionTargetLayerId(){if(!this.layerManager)return;const e=this.layerManager.getActiveLayerId();if(this.layerManager.isLayerEditable(e))return e;if(this.layerManager.isLayerEditable("default"))return"default";const t=this.layerManager.getAllLayers().find(e=>"editable"===e.interaction);return null==t?void 0:t.id}ensureFeatureGroupMetadata(e){const t=e;if(t._polydrawMetadata)return t._polydrawMetadata;let r=0,o=0;e.eachLayer(e=>{if(e instanceof s.Polygon&&!(e instanceof s.Rectangle)){const t=e;"number"==typeof t._polydrawOptimizationLevel&&(r=t._polydrawOptimizationLevel),"number"==typeof t._polydrawOptimizationOriginalLevel&&(o=t._polydrawOptimizationOriginalLevel)}});const n=new Date,i=`fg-${oi.util.stamp(e)}`;return t._polydrawMetadata={id:i,optimizationLevel:r,originalOptimizationLevel:o,hasHoles:!1,createdAt:n,lastModified:n,metadata:{},sourceFeatureIds:[i]},t._polydrawMetadata}async addPredefinedPolygon(e,t){var r,o,n;const i=Vi.convertToLatLngArray(e);if(!i||0===i.length)throw new Error("Cannot add empty polygon array");if(!this.map)throw new Error("Map not initialized");if(!this.polygonMutationManager)throw new Error("PolygonMutationManager not initialized");if(!this.layerManager)throw new Error("LayerManager not initialized");for(const[p,f]of i.entries())if(!f||!f[0]||f[0].length<4)throw new Error(`Invalid polygon data at index ${p}: A polygon must have at least 3 unique vertices.`);const a=(null==t?void 0:t.visualOptimizationLevel)??0,s=(null==(r=null==t?void 0:t.overrides)?void 0:r.interaction)&&"inherit"!==t.overrides.interaction?t.overrides.interaction:void 0,l=(null==(o=null==t?void 0:t.overrides)?void 0:o.style)?{...t.overrides.style}:void 0,c=(null==(n=null==t?void 0:t.overrides)?void 0:n.merge)??"inherit";let u,h,g=!1;if(null==t?void 0:t.layer){const e=this.resolvePredefinedLayerDescriptor(t.layer,t.layerColor);if(e){const t=this.ensureLayerFromDescriptor(e);u=t.id,h=t.color,g="editable"!==t.interaction}this.updateLayerPanel()}else(null==t?void 0:t.layerColor)&&(h=t.layerColor);this.startHistoryBatch("addPredefinedPolygon");try{for(const e of i)try{const r=e.map(e=>e.map(e=>[e.lng,e.lat])),o=this.turfHelper.getMultiPolygon([r]),n="allow"!==c&&("block"===c||g),i=await this.polygonMutationManager.addPolygon(o,{simplify:!1,noMerge:n,mergeEditableOnly:"allow"!==c,visualOptimizationLevel:a,targetLayerId:u,layerColor:h,featureMetadata:null==t?void 0:t.metadata,featureInteractionOverride:s,featureStyleOverrides:l});if(!i.success)throw console.error("Error adding polygon via manager:",i.error),new Error(i.error||"Failed to add polygon");this.polygonInformation.createPolygonInformationStorage(this.arrayOfFeatureGroups)}catch(d){throw console.error("Error adding auto polygon:",d),d}}finally{this.endHistoryBatch()}}async addPredefinedGeoJSONs(e,t){if(!Array.isArray(e)||0===e.length)throw new Error("Cannot add empty GeoJSON feature array");this.startHistoryBatch("addPredefinedPolygon");try{for(const r of e){const{type:e,coordinates:o}=r.geometry,n=(null==t?void 0:t.metadata)??(r.properties?{...r.properties}:void 0),i={...t,metadata:n};if("MultiPolygon"===e)for(const t of o){const e=t.map(e=>e.map(e=>oi.createLatLng(e[1],e[0])));await this.addPredefinedPolygon([e],i)}else if("Polygon"===e){const e=o.map(e=>e.map(e=>oi.createLatLng(e[1],e[0])));await this.addPredefinedPolygon([e],i)}}}finally{this.endHistoryBatch()}}async addPredefinedPolygonGroups(e){if(!Array.isArray(e)||0===e.length)throw new Error("Cannot add empty polygon group array");if(!this.layerManager)throw new Error("LayerManager not initialized");this.startHistoryBatch("addPredefinedPolygon");try{const t=e.map(e=>{const t=this.resolvePredefinedLayerDescriptor(e.layer);if(!t)throw new Error("Polygon group layer descriptor is missing");return{descriptor:t,polygons:e.polygons,options:e.options}});for(const e of t)this.ensureLayerFromDescriptor(e.descriptor);for(const e of t)for(const t of e.polygons)await this.addPredefinedPolygon(t,{layer:e.descriptor,...e.options})}finally{this.endHistoryBatch()}this.updateLayerPanel()}getLayerManager(){return this.layerManager}getAllLayers(){return this.layerManager.getAllLayers()}getLayerById(e){return this.layerManager.getLayer(e)}hasLayer(e){return!!this.layerManager.getLayer(e)}getActiveLayer(){return this.layerManager.getActiveLayer()}getFeatureGroupsByLayer(e){return this.layerManager.getFeatureGroupsForLayer(e)}createLayer(e){const t=(e.id||"").trim();if(!t)throw new Error("Layer id cannot be empty");if(this.layerManager.getLayer(t))throw new Error(`Layer "${t}" already exists`);return this.ensureLayer(e)}ensureLayer(e){const t=this.ensureLayerFromDescriptor(e);return this.updateLayerPanel(),this.updateMarkerDraggableState(),t}updateLayer(e,t){if(!this.layerManager.getLayer(e))return;let r=!1;return"label"in t&&(r=this.layerManager.setLayerLabel(e,t.label)||r),"string"==typeof t.color&&(r=this.layerManager.setLayerColor(e,t.color)||r),"boolean"==typeof t.visibility&&(r=this.layerManager.setLayerVisibility(e,t.visibility)||r),void 0!==t.interaction&&(r=this.layerManager.setLayerInteraction(e,t.interaction)||r,"static"===t.interaction&&void 0===t.panel&&(r=this.layerManager.setLayerPanelVisibility(e,"hidden")||r)),void 0!==t.panel&&(r=this.layerManager.setLayerPanelVisibility(e,t.panel)||r),void 0!==t.metadata&&(r=this.layerManager.setLayerMetadata(e,t.metadata)||r),r&&(this.updateLayerPanel(),this.updateMarkerDraggableState(),this.syncFeatureGroupOrderWithLayers()),this.layerManager.getLayer(e)}deleteLayer(e){const t=(e||"").trim();if(!t||!this.layerManager.getLayer(t))return{success:!1,layerId:t,removedFeatureGroups:0,reason:"not-found"};if("default"===t)return{success:!1,layerId:t,removedFeatureGroups:0,reason:"default-layer"};this.saveHistory("layerDelete");return{success:!0,layerId:t,removedFeatureGroups:this.layerManager.deleteLayer(t).length}}setActiveLayer(e){return this.layerManager.setActiveLayer(e)}setLayerVisibility(e,t){return this.layerManager.setLayerVisibility(e,t)}showLayer(e){return this.setLayerVisibility(e,!0)}hideLayer(e){return this.setLayerVisibility(e,!1)}setLayerColor(e,t){return this.layerManager.setLayerColor(e,t)}setLayerInteraction(e,t){const r=this.layerManager.setLayerInteraction(e,t);return r&&(this.updateMarkerDraggableState(),this.updateLayerPanel()),r}setLayerPanelVisibility(e,t){const r=this.layerManager.setLayerPanelVisibility(e,t);return r&&this.updateLayerPanel(),r}setLayerMetadata(e,t){return this.layerManager.setLayerMetadata(e,t)}patchLayerMetadata(e,t){const r=this.layerManager.getLayer(e);return!!r&&this.layerManager.setLayerMetadata(e,{...r.metadata,...t})}getFeatureMetadata(e){const t=e._polydrawMetadata;if(null==t?void 0:t.metadata)return yi(t.metadata)}setFeatureMetadata(e,t){if(!e)return!1;const r=this.ensureFeatureGroupMetadata(e);return r.metadata=yi(t),r.lastModified=new Date,!0}patchFeatureMetadata(e,t){if(!e)return!1;const r=this.getFeatureMetadata(e)??{};return this.setFeatureMetadata(e,{...r,...t})}reorderLayer(e,t){if("default"===e||"default"===t)return!1;const r=this.layerManager.getAllLayers().map(e=>e.id),o=r.indexOf(e),n=r.indexOf(t);return!(o<0||n<0||o===n)&&(this.saveHistory("layerReorder"),this.layerManager.moveLayer(e,t))}getActiveLayerId(){return this.layerManager.getActiveLayerId()}getLayerForFeatureGroup(e){return this.layerManager.getLayerForFeatureGroup(e)}assignFeatureGroupToLayer(e,t){const r=(t||"").trim();if(!e||!r)return!1;if(!this.layerManager.getLayer(r))return!1;if(this.layerManager.getLayerForFeatureGroup(e)===r)return!1;this.saveHistory("layerReorder");const o=this.layerManager.assignFeatureGroupToLayer(e,r);return o&&this.refreshAfterLayerStructureChange(),o}moveFeatureGroupToLayer(e,t){return this.assignFeatureGroupToLayer(e,t)}removeFeatureGroupFromLayer(e){e&&this.layerManager.getLayerForFeatureGroup(e)&&(this.saveHistory("layerReorder"),this.layerManager.removeFeatureGroupFromLayer(e),this.refreshAfterLayerStructureChange())}clearLayers(){const e=this.layerManager.getAllLayers().filter(e=>"default"!==e.id).map(e=>e.id);if(0===e.length)return;this.saveHistory("layerDelete");const t=[];for(const r of e)t.push(...this.layerManager.deleteLayer(r));t.length>0?this.removeFeatureGroupsFromMap(t):this.updateLayerPanel()}moveLayerToIndex(e,t){const r=(e||"").trim();if("default"===r||!Number.isFinite(t))return!1;const o=this.layerManager.getAllLayers().map(e=>e.id),n=o.indexOf(r);if(n<0)return!1;return n!==Math.max(1,Math.min(Math.trunc(t),o.length-1))&&(this.saveHistory("layerReorder"),this.layerManager.moveLayerToIndex(r,t))}setLayerOrder(e){if(!e||0===e.length)return!1;const t=this.layerManager.getAllLayers().map(e=>e.id),r=e.map(e=>(e||"").trim());if(r.some(e=>0===e.length||"default"===e))return!1;if(new Set(r).size!==r.length)return!1;if(r.some(e=>!t.includes(e)))return!1;const o=new Set(r),n=["default",...r,...t.filter(e=>"default"!==e&&!o.has(e))];return(t.length!==n.length||!t.every((e,t)=>e===n[t]))&&(this.saveHistory("layerReorder"),this.layerManager.setLayerOrder(r))}refreshAfterLayerStructureChange(){this.syncFeatureGroupOrderWithLayers(),this.polygonInformation.deletePolygonInformationStorage(),this.polygonInformation.createPolygonInformationStorage(this.arrayOfFeatureGroups),this.updateMarkerDraggableState(),this.updateLayerPanel()}beginBatch(e="batch"){this.startHistoryBatch(e)}endBatch(){this.endHistoryBatch()}setDrawMode(e,t){const r=this.drawMode;this._updateDrawModeState(e);if(!((null==t?void 0:t.preserveActiveDraw)&&this.isDrawingInProgress&&(r===c.Add&&e===c.Subtract||r===c.Subtract&&e===c.Add))){(e===c.PointToPoint||e===c.PointToPointSubtract)&&r!==c.PointToPoint&&r!==c.PointToPointSubtract&&this.isDrawingInProgress&&this.stopDraw(),r!==c.PointToPoint&&r!==c.PointToPointSubtract||e===c.PointToPoint||e===c.PointToPointSubtract?(e===c.Off||e!==c.PointToPoint&&e!==c.PointToPointSubtract)&&this.stopDraw():(this.polygonDrawManager.clearP2pMarkers(),this.stopDraw())}this.map&&(this._updateUIAfterDrawModeChange(e),this._updateMapInteractions())}getDrawMode(){return this.modeManager.getCurrentMode()}on(e,t){this.eventManager.on(e,t)}off(e,t){this.eventManager.off(e,t)}removeAllFeatureGroups(){this.removeFeatureGroupsFromMap([...this.arrayOfFeatureGroups],{clearLayerState:!0})}removeDefaultLayerFeatureGroups(){this.removeFeatureGroupsFromMap(this.layerManager.getFeatureGroupsForLayer("default"))}removeFeatureGroupsFromMap(e,t={}){0!==e.length&&(e.forEach(e=>{var t;try{this.polygonMutationManager&&this.polygonMutationManager.cleanupFeatureGroup(e),this.map.removeLayer(e)}catch{}const r=this.arrayOfFeatureGroups.indexOf(e);-1!==r&&this.arrayOfFeatureGroups.splice(r,1),null==(t=this.layerManager)||t.removeFeatureGroupFromLayer(e)}),this._lastAppliedVisibleMapOrder=[],t.clearLayerState&&this.layerManager&&this.layerManager.clear(this.config.styles.polygon.color),this.polygonInformation.deletePolygonInformationStorage(),this.polygonInformation.updatePolygons(),this.updateActivateButtonIndicator(),this.updateLayerPanel(),this.eventManager.emit("polydraw:polygon:deleted",void 0))}cleanup(){this.map&&this.comprehensiveCleanup()}initializeUI(e){!function(e){const t=document.createElement("style");t.innerHTML=`\n .leaflet-control a { background-color: ${e.styles.ui.controlButton.backgroundColor}; color: ${e.styles.ui.controlButton.color}; display: flex; align-items: center; justify-content: center; }\n .leaflet-control a:hover { background-color: ${e.styles.ui.controlButtonHover.backgroundColor}; }\n .leaflet-control a.active { background-color: ${e.styles.ui.controlButtonActive.backgroundColor}; color: ${e.styles.ui.controlButtonActive.color}; }\n .polydraw-indicator-active { background-color: ${e.styles.ui.indicatorActive.backgroundColor} !important; }\n .crosshair-cursor-enabled { cursor: crosshair !important; }\n .crosshair-cursor-enabled * { cursor: crosshair !important; }\n .leaflet-polydraw-p2p-marker { background-color: ${e.styles.ui.p2pMarker.backgroundColor}; border: 2px solid ${e.styles.ui.p2pMarker.borderColor}; border-radius: 50%; box-sizing: border-box; }\n .leaflet-polydraw-p2p-marker[data-p2p-mode="subtract"] { background-color: ${e.styles.ui.dragSubtract.color}; border-color: ${e.styles.ui.dragSubtract.color}; }\n .leaflet-polydraw-p2p-first-marker { position: relative; }\n .leaflet-polydraw-p2p-first-marker:hover { transform: scale(1.5); transition: all 0.2s ease; }\n .leaflet-polydraw-p2p-first-marker-ready[data-p2p-mode="add"]:hover { background-color: ${e.styles.ui.p2pClosingMarker.color}; border-color: ${e.styles.ui.p2pClosingMarker.color}; cursor: pointer; }\n .leaflet-polydraw-p2p-first-marker-ready[data-p2p-mode="subtract"]:hover { background-color: ${e.styles.ui.dragSubtract.color}; border-color: ${e.styles.ui.dragSubtract.color}; cursor: pointer; }\n `,document.head.appendChild(t)}(this.config),s.DomEvent.disableClickPropagation(e),s.DomEvent.on(e,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(e,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(e,"pointerdown",s.DomEvent.stopPropagation),s.DomEvent.on(e,"pointerup",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stopPropagation);const t=e=>{this.controlEvents.add(e),this.markControlPointerDown(e)},r=e=>{this.clearControlPointerDown(e)};this.pointerEventsHandled?(e.addEventListener("pointerdown",t,{capture:!0,passive:!0}),e.addEventListener("pointerup",r,{capture:!0,passive:!0}),e.addEventListener("pointercancel",r,{capture:!0,passive:!0})):(e.addEventListener("mousedown",t,{capture:!0,passive:!0}),e.addEventListener("mouseup",r,{capture:!0,passive:!0}),e.addEventListener("touchstart",t,{capture:!0,passive:!0}),e.addEventListener("touchend",r,{capture:!0,passive:!0}),e.addEventListener("touchcancel",r,{capture:!0,passive:!0})),e.style.display="flex",e.style.flexDirection="column-reverse",e.style.pointerEvents="auto",e.style.position="relative",e.style.zIndex="1000";const o=this.config.tooltips;if(o){const t=Math.max(0,o.delayMs);e.setAttribute("data-tooltip-enabled",o.enabled?"true":"false"),e.setAttribute("data-tooltip-direction",o.direction),e.style.setProperty("--polydraw-tooltip-bg",o.backgroundColor),e.style.setProperty("--polydraw-tooltip-color",o.color),e.style.setProperty("--polydraw-tooltip-delay",`${t}ms`)}this.subContainer=oi.domUtil.create("div","sub-buttons",e),this.subContainer.setAttribute("data-polydraw","sub-buttons"),this.subContainer.style.maxHeight="0px",this.subContainer.style.overflow="hidden",this.subContainer.style.transition="max-height 0.3s ease",this.subContainer.style.pointerEvents="auto",this.subContainer.style.position="relative",this.eventManager||(this.eventManager=new di),this.historyManager||(this.historyManager=new Ui(this.eventManager,this.config.history.maxSize)),function(e,t,r,o,n,i,a,l,c,u,h,g,d,p){const f=oi.domUtil.create("a","icon-activate",e);if(f.href="#",li(f,"Activate"),f.setAttribute("data-polydraw","activate-button"),si(f,ai.activate),f.dataset.activeIcon=ai.activate,f.dataset.collapsedIcon=ai.collapse,s.DomEvent.on(f,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(f,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(f,"click",s.DomEvent.stop).on(f,"click",o),r.tools.draw){const e=oi.domUtil.create("a","icon-draw",t);e.href="#",li(e,"Draw"),e.setAttribute("data-polydraw","draw-button"),si(e,ai.draw),s.DomEvent.on(e,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(e,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stop),s.DomEvent.on(e,"click",n)}if(r.tools.subtract){const e=oi.domUtil.create("a","icon-subtract",t);e.href="#",li(e,"Subtract"),e.setAttribute("data-polydraw","subtract-button"),si(e,ai.subtract),s.DomEvent.on(e,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(e,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stop),s.DomEvent.on(e,"click",i)}if(r.tools.p2p){const e=oi.domUtil.create("a","icon-p2p",t);e.href="#",li(e,"Point to Point"),e.setAttribute("data-polydraw","p2p-button"),si(e,ai.p2p),s.DomEvent.on(e,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(e,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stop),s.DomEvent.on(e,"click",c)}if(r.tools.p2pSubtract){const e=oi.domUtil.create("a","icon-p2p-subtract",t);e.href="#",li(e,"Point to Point Subtract"),e.setAttribute("data-polydraw","p2p-subtract-button"),si(e,ai.p2pSubtract),s.DomEvent.on(e,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(e,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stop),s.DomEvent.on(e,"click",u)}if(r.tools.clone){const e=oi.domUtil.create("a","icon-clone",t);e.href="#",li(e,"Clone"),e.setAttribute("data-polydraw","clone-button"),si(e,ai.clone),s.DomEvent.on(e,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(e,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stop),s.DomEvent.on(e,"click",a)}if(r.tools.erase){const e=oi.domUtil.create("a","icon-erase",t);e.href="#",li(e,"Erase All"),e.setAttribute("data-polydraw","erase-button"),si(e,ai.erase),s.DomEvent.on(e,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(e,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stopPropagation),s.DomEvent.on(e,"click",s.DomEvent.stop),s.DomEvent.on(e,"click",l)}const y=oi.domUtil.create("a","icon-undo",t);y.href="#",li(y,"Undo (Ctrl+Z / Cmd+Z)"),si(y,ai.undo),s.DomEvent.on(y,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(y,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(y,"click",s.DomEvent.stopPropagation),s.DomEvent.on(y,"click",s.DomEvent.stop),s.DomEvent.on(y,"click",h);const m=oi.domUtil.create("a","icon-redo",t);m.href="#",li(m,"Redo (Ctrl+Y / Cmd+Shift+Z)"),si(m,ai.redo),s.DomEvent.on(m,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(m,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(m,"click",s.DomEvent.stopPropagation),s.DomEvent.on(m,"click",s.DomEvent.stop),s.DomEvent.on(m,"click",g);const v=(e,t)=>{e?(y.style.opacity="1",y.style.pointerEvents="auto"):(y.style.opacity="0.3",y.style.pointerEvents="none"),t?(m.style.opacity="1",m.style.pointerEvents="auto"):(m.style.opacity="0.3",m.style.pointerEvents="none")};d.on("polydraw:history:changed",e=>{v(e.canUndo,e.canRedo)}),d.on("polydraw:history:undo",e=>{v(e.canUndo,e.canRedo)}),d.on("polydraw:history:redo",e=>{v(e.canUndo,e.canRedo)}),v(p.canUndo(),p.canRedo())}(e,this.subContainer,this.config,this._handleActivateToggle,this._handleDrawClick,this._handleSubtractClick,this._handleCloneClick,this._handleEraseClick,this._handlePointToPointClick,this._handlePointToPointSubtractClick,this._handleUndoClick,this._handleRedoClick,this.eventManager,this.historyManager),this.ensureButtonTouchResponsiveness(e),this.updateActivateButtonIndicator();this.drawModeListeners.push(t=>{const r=e.querySelector(".icon-draw"),o=e.querySelector(".icon-subtract"),n=e.querySelector(".icon-p2p"),i=e.querySelector(".icon-p2p-subtract"),a=e.querySelector(".icon-clone");r&&r.classList.toggle("active",t===c.Add),o&&o.classList.toggle("active",t===c.Subtract),n&&n.classList.toggle("active",t===c.PointToPoint),i&&i.classList.toggle("active",t===c.PointToPointSubtract),a&&a.classList.toggle("active",t===c.Clone)})}addCoreEventListener(e,t){this.eventManager.on(e,t),this._coreEventSubscriptions.push({event:e,callback:t})}removeCoreEventListeners(){if(this.eventManager){for(const e of this._coreEventSubscriptions)this.eventManager.off(e.event,e.callback);this._coreEventSubscriptions.length=0,this._coreEventListenersAttached=!1}else this._coreEventListenersAttached=!1}setupEventListeners(){this._coreEventListenersAttached||(this._coreEventListenersAttached=!0,this.addCoreEventListener("polygonOperationComplete",()=>{this.updateActivateButtonIndicator(),this.modeManager.updateStateForMode(c.Off),this.drawMode=c.Off,this.emitDrawModeChanged(),this.updateMarkerDraggableState();const e=this.modeManager.shouldShowCrosshairCursor(),t=this.modeManager.canPerformAction("mapDrag"),r=this.modeManager.canPerformAction("mapZoom"),o=this.modeManager.canPerformAction("mapDoubleClickZoom");e?oi.domUtil.addClass(this.map.getContainer(),"crosshair-cursor-enabled"):oi.domUtil.removeClass(this.map.getContainer(),"crosshair-cursor-enabled"),this.events(!1),this.setLeafletMapEvents(t,o,r),this.applyTracerStyle(c.Off),this.syncFeatureGroupOrderWithLayers(),this.cleanupEmptyLayers()}),this.addCoreEventListener("polygonDeleted",()=>{this.updateActivateButtonIndicator(),this.cleanupEmptyLayers()}),this.addCoreEventListener("polydraw:polygon:created",async e=>{this.stopDraw();const t=this.getInteractionTargetLayerId();e.isPointToPoint?(this.saveHistory("pointToPoint"),e.mode===c.PointToPointSubtract?await this.polygonMutationManager.subtractPolygon(e.polygon,{simplify:!1,targetLayerId:t}):await this.polygonMutationManager.addPolygon(e.polygon,{simplify:!1,noMerge:!1,targetLayerId:t})):await this.handleFreehandDrawCompletion(e.polygon),this.polygonInformation.createPolygonInformationStorage(this.arrayOfFeatureGroups)}),this.addCoreEventListener("polydraw:draw:cancel",()=>{this.stopDraw(),this.setDrawMode(this.config.tools.default)}),this.addCoreEventListener("polydraw:layer:visibility",e=>{const t=this.layerManager.getLayer(e.layerId);if(t){for(const r of t.featureGroups)try{e.visible?r.addTo(this.map):this.map.removeLayer(r)}catch{}this.syncFeatureGroupOrderWithLayers(),this.updateLayerPanel()}}),this.addCoreEventListener("polydraw:layer:activated",()=>{this.updateMarkerDraggableState(),this.updateLayerPanel()}),this.addCoreEventListener("polydraw:layer:colorChanged",()=>{this.updateLayerPanel()}),this.addCoreEventListener("polydraw:layer:created",()=>{this.updateLayerPanel()}),this.addCoreEventListener("polydraw:layer:delete-requested",e=>{this.saveHistory("layerDelete"),this.layerManager.deleteLayer(e.layerId)}),this.addCoreEventListener("polydraw:layer:reorder-requested",e=>{this.reorderLayer(e.layerId,e.targetLayerId)}),this.addCoreEventListener("polydraw:layer:reordered",()=>{this.syncFeatureGroupOrderWithLayers(),this.polygonInformation.deletePolygonInformationStorage(),this.polygonInformation.createPolygonInformationStorage(this.arrayOfFeatureGroups),this.updateLayerPanel()}),this.addCoreEventListener("polydraw:layer:deleted",e=>{for(const t of e.removedFeatureGroups){try{this.polygonMutationManager&&this.polygonMutationManager.cleanupFeatureGroup(t),t.clearLayers(),this.map.removeLayer(t)}catch{}const e=this.arrayOfFeatureGroups.indexOf(t);e>-1&&this.arrayOfFeatureGroups.splice(e,1)}this.syncFeatureGroupOrderWithLayers(),this.polygonInformation.updatePolygons(),this.updateActivateButtonIndicator(),this.updateMarkerDraggableState(),this.updateLayerPanel()}))}createTracer(){this.tracer=oi.createPolyline([],{...this.config.styles.polyline});try{this.tracer.addTo(this.map)}catch{}}applyTracerStyle(e){if(this.tracer)try{const t=e===c.Subtract||e===c.PointToPointSubtract,r=this.getTracerBaseStyle(t);let o,n="";switch(e){case c.Add:n=this.config.styles.polyline.color,o=void 0;break;case c.Subtract:n=this.config.styles.subtractLine.color,o=void 0;break;case c.PointToPoint:n=this.config.styles.polyline.color,o="5, 5";break;case c.PointToPointSubtract:n=this.config.styles.subtractLine.color,o="5, 5";break;case c.Off:default:n="",o=void 0}this.tracer.setStyle({...r,color:n,dashArray:o})}catch{}}getTracerBaseStyle(e){const t=e?this.config.styles.subtractLine:this.config.styles.polyline;return{weight:t.weight,opacity:t.opacity}}initializeManagers(){this.polygonDrawManager=new fi({turfHelper:this.turfHelper,map:this.map,config:this.config,modeManager:this.modeManager,eventManager:this.eventManager,tracer:this.tracer}),this.polygonMutationManager=new zi({turfHelper:this.turfHelper,polygonInformation:this.polygonInformation,map:this.map,config:this.config,modeManager:this.modeManager,eventManager:this.eventManager,getFeatureGroups:()=>this.arrayOfFeatureGroups,saveHistoryState:e=>{this.saveHistory(e)},layerManager:this.layerManager})}async loadExternalConfig(e,t){try{const r=await fetch(e);if(!r.ok)throw new Error(`Failed to load config from ${e}: ${r.status} ${r.statusText}`);const o=Ki(await r.json());this.config=Qn(structuredClone(g),o,t??{}),$i(this.config),this.initializeComponents()}catch(r){console.warn("Failed to load external config, falling back to default + inline config:",r),this.config=Qn(structuredClone(g),t??{}),$i(this.config),this.initializeComponents()}}_updateDrawModeState(e){var t;this.drawMode=e,this.modeManager.updateStateForMode(e),this.emitDrawModeChanged(),this.updateMarkerDraggableState(),(null==(t=this.polygonDrawManager)?void 0:t.refreshP2PMarkerState)&&this.polygonDrawManager.refreshP2PMarkerState()}_updateUIAfterDrawModeChange(e){this.modeManager.shouldShowCrosshairCursor()?oi.domUtil.addClass(this.map.getContainer(),"crosshair-cursor-enabled"):oi.domUtil.removeClass(this.map.getContainer(),"crosshair-cursor-enabled"),this.applyTracerStyle(e)}shouldEnableDrawEvents(e){return e===c.Add||e===c.Subtract||e===c.PointToPoint||e===c.PointToPointSubtract}_updateMapInteractions(){const e=this.modeManager.canPerformAction("mapDrag"),t=this.modeManager.canPerformAction("mapZoom"),r=this.modeManager.canPerformAction("mapDoubleClickZoom"),o=this.shouldEnableDrawEvents(this.drawMode);this.events(o),this.setMapDrawingTouchLock(o),this.setLeafletMapEvents(e,r,t)}setMapDrawingTouchLock(e){if(!this.map)return;const t=this.map.getContainer();if(e)return null===this.originalMapTouchAction&&(this.originalMapTouchAction=t.style.touchAction||""),void(t.style.touchAction="none");null!==this.originalMapTouchAction&&(t.style.touchAction=this.originalMapTouchAction,this.originalMapTouchAction=null)}async restoreFromSnapshot(e){var t,r,o;if(e&&Array.isArray(e.features)){this.historyManager.setRestoring(!0),this._isRestoringSnapshot=!0;try{this.removeAllFeatureGroups();for(const[o,n]of e.features.entries()){const i=null==(t=e.featureMetadataSnapshot)?void 0:t[o],a=(null==i?void 0:i.layerId)&&(null==(r=this.layerManager)?void 0:r.getLayer(i.layerId))?i.layerId:void 0;await this.polygonMutationManager.addPolygon(n,{noMerge:!0,simplify:!1,skipKinkProcessing:!0,targetLayerId:a,visualOptimizationLevel:(null==i?void 0:i.optimizationLevel)??0,originalOptimizationLevel:null==i?void 0:i.originalOptimizationLevel,featureId:null==i?void 0:i.id,featureMetadata:null==i?void 0:i.metadata,sourceFeatureIds:null==i?void 0:i.sourceFeatureIds,featureInteractionOverride:null==i?void 0:i.interactionOverride,featureStyleOverrides:null==i?void 0:i.styleOverrides,featureCreatedAt:null==i?void 0:i.createdAt,featureLastModified:null==i?void 0:i.lastModified})}if(e.layerSnapshot&&this.layerManager){this.layerManager.restoreFromLayerSnapshot(e.layerSnapshot,this.arrayOfFeatureGroups);for(const e of this.layerManager.getAllLayers()){for(const t of e.featureGroups){const r=null==(o=t._polydrawMetadata)?void 0:o.styleOverrides;t.eachLayer(t=>{t instanceof s.Polygon&&!(t instanceof s.Rectangle)&&t.setStyle({color:(null==r?void 0:r.color)??e.color,fillColor:(null==r?void 0:r.fillColor)??this.config.styles.polygon.fillColor,fillOpacity:(null==r?void 0:r.fillOpacity)??this.config.styles.polygon.fillOpacity,weight:(null==r?void 0:r.weight)??this.config.styles.polygon.weight})})}if(!e.visible)for(const t of e.featureGroups)try{this.map.removeLayer(t)}catch{}}this.updateLayerPanel()}this.layerManager&&this.syncFeatureGroupOrderWithLayers(),this.polygonInformation.updatePolygons(),this.updateMarkerDraggableState()}finally{this._isRestoringSnapshot=!1,this.historyManager.setRestoring(!1)}}else console.warn("Invalid history snapshot provided for restore; skipping restore operation.")}initializeComponents(){this._componentsInitialized||(this._componentsInitialized=!0,this.turfHelper=new ei(this.config),this.mapStateService=new gi,this.eventManager=this.eventManager??new di,this.polygonInformation=new hi(this.mapStateService),this.modeManager=new pi(this.config,this.eventManager),this.historyManager?this.historyManager.setMaxHistorySize(this.config.history.maxSize):this.historyManager=new Ui(this.eventManager,this.config.history.maxSize),this.layerManager=new Ni(this.eventManager,this.config.styles.polygon.color),this.polygonInformation.onPolygonInfoUpdated(e=>{this.updateActivateButtonIndicator()}),this._boundKeyDownHandler=this.handleKeyDown.bind(this))}emitDrawModeChanged(){this.eventManager.emit("polydraw:mode:change",{mode:this.modeManager.getCurrentMode()});for(const e of this.drawModeListeners)e(this.modeManager.getCurrentMode())}updateMarkerDraggableState(){this.polygonMutationManager&&this.polygonMutationManager.updateMarkerDraggableState()}updateLayerPanel(){if(!this.map||!this.layerManager)return;if(this.layerManager.getPanelLayerCount()>1){if(!this.layerPanel){const e=function(e,t){let r=!1,o=null,n=null,i=!1;const a=()=>{if(!o)return;if(n)return void(i=!0);o.innerHTML="";const l=e.getPanelLayers(),c=e.getActiveLayerId();n&&!l.some(e=>e.id===n)&&(n=null),o.classList.toggle("polydraw-layer-panel-collapsed",r);const u=s.DomUtil.create("div","polydraw-layer-header",o);s.DomUtil.create("span","polydraw-layer-header-title",u).textContent="Layers",s.DomUtil.create("span","polydraw-layer-header-count",u).textContent=String(l.length);const h=s.DomUtil.create("button","polydraw-layer-header-toggle",u);if(h.setAttribute("type","button"),h.setAttribute("aria-label",r?"Expand layer panel":"Collapse layer panel"),h.setAttribute("title",r?"Expand layers":"Collapse layers"),ni(h,Xi.toggle),h.classList.toggle("is-collapsed",r),h.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),r=!r,a()}),r)return;const g=()=>{o&&o.querySelectorAll(".polydraw-layer-row").forEach(e=>{e.classList.remove("polydraw-layer-row-dragging"),e.classList.remove("polydraw-layer-row-drag-over")})},d=()=>{i&&(i=!1,a())},p=e=>{var t,r;return(null==(r=null==(t=null==e?void 0:e.dataTransfer)?void 0:t.getData("text/plain"))?void 0:r.trim())||n};l.forEach(r=>{var i;const a=(null==(i=r.label)?void 0:i.trim())?r.label:r.id,l=s.DomUtil.create("div","polydraw-layer-row",o??void 0);if(l.setAttribute("tabindex","0"),l.setAttribute("role","button"),l.setAttribute("draggable","default"===r.id?"false":"true"),l.setAttribute("aria-label",`Activate layer ${a}`),l.setAttribute("data-layer-id",r.id),r.id===c&&l.classList.add("polydraw-layer-row-active"),r.visible||l.classList.add("polydraw-layer-hidden"),"default"!==r.id){const e=s.DomUtil.create("span","polydraw-layer-grip",l);e.setAttribute("aria-hidden","true"),ni(e,Xi.grip)}else s.DomUtil.create("span","polydraw-layer-grip-spacer",l).setAttribute("aria-hidden","true");s.DomUtil.create("span","polydraw-layer-color-indicator",l).style.backgroundColor=r.color;const u=s.DomUtil.create("span","polydraw-layer-name",l);u.textContent=a,u.setAttribute("title",a);const h=s.DomUtil.create("button","polydraw-layer-btn polydraw-layer-visibility",l);if(h.setAttribute("type","button"),h.setAttribute("title",r.visible?"Hide layer":"Show layer"),h.setAttribute("aria-label",r.visible?`Hide layer ${a}`:`Show layer ${a}`),ni(h,r.visible?Xi.eyeVisible:Xi.eyeHidden),r.visible||h.classList.add("polydraw-layer-visibility-hidden"),h.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),e.setLayerVisibility(r.id,!r.visible)}),"default"!==r.id){const e=s.DomUtil.create("button","polydraw-layer-btn polydraw-layer-delete",l);e.setAttribute("type","button"),e.setAttribute("title","Delete layer"),e.setAttribute("aria-label",`Delete layer ${a}`),ni(e,Xi.delete),e.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),t.emit("polydraw:layer:delete-requested",{layerId:r.id})})}else s.DomUtil.create("span","polydraw-layer-btn-spacer",l).setAttribute("aria-hidden","true");l.addEventListener("click",()=>{e.setActiveLayer(r.id)}),l.addEventListener("keydown",t=>{"Enter"!==t.key&&" "!==t.key||(t.preventDefault(),e.setActiveLayer(r.id))}),"default"!==r.id&&(l.addEventListener("dragstart",e=>{n=r.id,l.classList.add("polydraw-layer-row-dragging"),e.dataTransfer&&(e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",r.id))}),l.addEventListener("dragend",()=>{n=null,g(),d()})),l.addEventListener("dragover",e=>{const t=p(e);t&&t!==r.id&&"default"!==r.id&&(e.preventDefault(),l.classList.add("polydraw-layer-row-drag-over"),e.dataTransfer&&(e.dataTransfer.dropEffect="move"))}),l.addEventListener("dragleave",()=>{l.classList.remove("polydraw-layer-row-drag-over")}),l.addEventListener("drop",e=>{const o=p(e);o&&o!==r.id&&"default"!==r.id&&(e.preventDefault(),e.stopPropagation(),t.emit("polydraw:layer:reorder-requested",{layerId:o,targetLayerId:r.id}),n=null,g(),d())})})},l=new(s.Control.extend({options:{position:"topright"},onAdd:()=>(o=s.DomUtil.create("div","leaflet-bar polydraw-layer-panel"),o.setAttribute("data-polydraw","layer-panel"),s.DomEvent.disableClickPropagation(o),s.DomEvent.disableScrollPropagation(o),s.DomEvent.on(o,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.on(o,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.on(o,"dragstart",s.DomEvent.stopPropagation),s.DomEvent.on(o,"dragover",s.DomEvent.stopPropagation),s.DomEvent.on(o,"drop",s.DomEvent.stopPropagation),a(),o),onRemove(){o&&(s.DomEvent.off(o,"mousedown",s.DomEvent.stopPropagation),s.DomEvent.off(o,"touchstart",s.DomEvent.stopPropagation),s.DomEvent.off(o,"dragstart",s.DomEvent.stopPropagation),s.DomEvent.off(o,"dragover",s.DomEvent.stopPropagation),s.DomEvent.off(o,"drop",s.DomEvent.stopPropagation),o=null,n=null,i=!1)}}));return l.refresh=()=>{a()},l}(this.layerManager,this.eventManager);return this.layerPanel=e,void e.addTo(this.map)}this.layerPanel.refresh()}else if(this.layerPanel){try{this.layerPanel.remove()}catch{}this.layerPanel=null}}syncFeatureGroupOrderWithLayers(){if(!this.layerManager)return;const e=this.arrayOfFeatureGroups;if(0===e.length)return;const t=new Set(e),r=new Set,o=[];for(const n of this.layerManager.getAllLayers())for(const e of n.featureGroups)t.has(e)&&!r.has(e)&&(r.add(e),o.push(e));for(const n of e)r.has(n)||o.push(n);this.isSameFeatureGroupOrder(e,o)||e.splice(0,e.length,...o),this.reapplyFeatureGroupMapOrder()}isSameFeatureGroupOrder(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}reapplyFeatureGroupMapOrder(){if(!this.map||!this.layerManager)return;const e=this.arrayOfFeatureGroups.filter(e=>{const t=this.layerManager.getLayerForFeatureGroup(e),r=t?this.layerManager.getLayer(t):void 0;return!r||!1!==r.visible}),t=new Map;this.layerManager.getAllLayers().forEach((e,r)=>{t.set(e.id,r)});const r=[...e].sort((e,r)=>{var o,n;const i=null==(o=this.layerManager)?void 0:o.getLayerForFeatureGroup(e),a=null==(n=this.layerManager)?void 0:n.getLayerForFeatureGroup(r),s=i?t.get(i)??t.size:t.size;return(a?t.get(a)??t.size:t.size)-s}),o=new Set(e);if(!this.arrayOfFeatureGroups.every(e=>{const t=o.has(e);return this.map.hasLayer(e)===t})||!this.isSameFeatureGroupOrder(this._lastAppliedVisibleMapOrder,r)){for(const e of this.arrayOfFeatureGroups)if(!o.has(e)&&this.map.hasLayer(e))try{this.map.removeLayer(e)}catch{}for(const e of r)try{this.map.hasLayer(e)&&this.map.removeLayer(e),e.addTo(this.map)}catch{}this._lastAppliedVisibleMapOrder=[...r]}}cleanupEmptyLayers(){if(!this.layerManager||this._isRestoringSnapshot)return;const e=[];for(const t of this.layerManager.getAllLayers())"default"!==t.id&&0===t.featureGroups.length&&e.push(t.id);for(const t of e)this.layerManager.deleteLayer(t);e.length>0&&this.updateLayerPanel()}stopDraw(){this.isDrawingInProgress=!1,this.resetTracker(),this.drawStartedEvents(!1)}setLeafletMapEvents(e,t,r){e?this.map.dragging.enable():this.map.dragging.disable(),t?this.map.doubleClickZoom.enable():this.map.doubleClickZoom.disable(),r?this.map.scrollWheelZoom.enable():this.map.scrollWheelZoom.disable()}resetTracker(){var e;null==(e=this.tracer)||e.setLatLngs([])}drawStartedEvents(e){if(this.drawEventsAttached===e)return;this.drawEventsAttached=e;const t=this.pointerEventsHandled,r=e?"on":"off";t||(this.map[r]("mousemove",this.mouseMove,this),this.map[r]("mouseup",this.mouseUpLeave,this)),e?(this._boundMouseMove||(this._boundMouseMove=e=>this.mouseMove(e)),this._boundMouseUp||(this._boundMouseUp=e=>this.mouseUpLeave(e)),document.addEventListener("mousemove",this._boundMouseMove),document.addEventListener("mouseup",this._boundMouseUp),t||(this._boundTouchMove||(this._boundTouchMove=e=>this.mouseMove(e)),this._boundTouchEnd||(this._boundTouchEnd=e=>this.mouseUpLeave(e)),this._boundTouchCancel||(this._boundTouchCancel=e=>this.mouseUpLeave(e)),document.addEventListener("touchmove",this._boundTouchMove,{passive:!1}),document.addEventListener("touchend",this._boundTouchEnd,{passive:!1}),document.addEventListener("touchcancel",this._boundTouchCancel,{passive:!1})),t&&(this._boundPointerMove||(this._boundPointerMove=e=>this.mouseMove(e)),this._boundPointerUp||(this._boundPointerUp=e=>this.mouseUpLeave(e)),this._boundPointerCancel||(this._boundPointerCancel=e=>this.mouseUpLeave(e)),document.addEventListener("pointermove",this._boundPointerMove,{passive:!1}),document.addEventListener("pointerup",this._boundPointerUp,{passive:!1}),document.addEventListener("pointercancel",this._boundPointerCancel,{passive:!1}))):(this._boundMouseMove&&document.removeEventListener("mousemove",this._boundMouseMove),this._boundMouseUp&&document.removeEventListener("mouseup",this._boundMouseUp),this._boundTouchMove&&document.removeEventListener("touchmove",this._boundTouchMove),this._boundTouchEnd&&document.removeEventListener("touchend",this._boundTouchEnd),this._boundTouchCancel&&document.removeEventListener("touchcancel",this._boundTouchCancel),this._boundPointerMove&&document.removeEventListener("pointermove",this._boundPointerMove),this._boundPointerUp&&document.removeEventListener("pointerup",this._boundPointerUp),this._boundPointerCancel&&document.removeEventListener("pointercancel",this._boundPointerCancel))}events(e){if(this.mapEventsAttached===e)return;this.mapEventsAttached=e;const t=this.pointerEventsHandled,r=e?"on":"off";t||this.map[r]("mousedown",this.mouseDown,this),this.map[r]("dblclick",this.handleDoubleClick,this),e?(this._boundContextMenu||(this._boundContextMenu=e=>e.preventDefault()),this.map.getContainer().addEventListener("contextmenu",this._boundContextMenu),t||(this._boundTouchStart||(this._boundTouchStart=e=>this.handleTouchStart(e)),this.map.getContainer().addEventListener("touchstart",this._boundTouchStart,{passive:!1})),t&&(this._boundPointerDown||(this._boundPointerDown=e=>this.mouseDown(e)),this.map.getContainer().addEventListener("pointerdown",this._boundPointerDown,{passive:!1}))):(this._boundContextMenu&&this.map.getContainer().removeEventListener("contextmenu",this._boundContextMenu),this._boundTouchStart&&this.map.getContainer().removeEventListener("touchstart",this._boundTouchStart),this._boundPointerDown&&this.map.getContainer().removeEventListener("pointerdown",this._boundPointerDown))}handleTouchStart(e){bi.shouldPreventDefault(e)&&e.preventDefault();const t=Date.now(),r=t-this._lastTapTime;if(this.modeManager.getCurrentMode()===c.PointToPoint||this.modeManager.getCurrentMode()===c.PointToPointSubtract){this._tapTimeout&&(clearTimeout(this._tapTimeout),this._tapTimeout=null);const o=bi.extractCoordinates(e,this.map);return this.isP2PDoubleTapClose(o,r)?(this.handleDoubleTap(e),this._lastTapTime=0,void(this._lastTapLatLng=null)):(this._lastTapTime=t,this._lastTapLatLng=o,void this.mouseDown(e))}this._tapTimeout&&(clearTimeout(this._tapTimeout),this._tapTimeout=null),this._lastTapTime=t,this._lastTapLatLng=bi.extractCoordinates(e,this.map),this.mouseDown(e)}isP2PDoubleTapClose(e,t){if(!this.map)return!1;if(!e||!this._lastTapLatLng)return!1;if(t<=0||t>300)return!1;const r=this.map.latLngToLayerPoint(this._lastTapLatLng),o=this.map.latLngToLayerPoint(e);return r.distanceTo(o)<=36}handleDoubleTap(e){this.modeManager.getCurrentMode()!==c.PointToPoint&&this.modeManager.getCurrentMode()!==c.PointToPointSubtract||this.polygonDrawManager.handleDoubleTap(e)}mouseDown(e){var t;const r=bi.normalizeEvent(e);if(this.isEventFromControl(r))return;if(bi.shouldPreventDefault(r)&&(null==(t=r.preventDefault)||t.call(r)),this.modeManager.isInOffMode())return;const o=bi.extractCoordinates(r,this.map);if(!o)return;const n=this.modeManager.getCurrentMode()===c.PointToPoint||this.modeManager.getCurrentMode()===c.PointToPointSubtract;if(n&&"touch"===r.pointerType){const t=Date.now(),r=t-this._lastTapTime;if(this.isP2PDoubleTapClose(o,r))return this.handleDoubleTap(e),this._lastTapTime=0,void(this._lastTapLatLng=null);this._lastTapTime=t,this._lastTapLatLng=o}n?this.polygonDrawManager.handlePointToPointClick(o):this.tracer&&(this.isDrawingInProgress||(this.tracer.setLatLngs([o]),this.startDraw()))}isEventFromControl(e){var t,r;const o=this.getContainer();if(!o)return!1;const n=null==e?void 0:e.originalEvent;if(n&&this.controlEvents.has(n))return!0;if(e instanceof Event&&this.controlEvents.has(e))return!0;if(this.isRecentControlPointer(e))return!0;const i=(null==(t=null==n?void 0:n.composedPath)?void 0:t.call(n))??(null==(r=null==e?void 0:e.composedPath)?void 0:r.call(e));if(i&&i.some(e=>e instanceof Node&&o.contains(e)))return!0;const a=(null==n?void 0:n.target)??(null==e?void 0:e.target);if(a instanceof Node&&o.contains(a))return!0;const s=e=>{if(!e||"object"!=typeof e)return null;const t=e;if(t.touches&&t.touches.length>0)return{x:t.touches[0].clientX,y:t.touches[0].clientY};const r=e;if("number"==typeof r.clientX&&"number"==typeof r.clientY)return{x:r.clientX,y:r.clientY};const o=e;if(o.containerPoint&&this.map){const e=this.map.getContainer().getBoundingClientRect();return{x:e.left+o.containerPoint.x,y:e.top+o.containerPoint.y}}const n=e;if(n.latlng&&this.map){const e=this.map.latLngToContainerPoint(n.latlng),t=this.map.getContainer().getBoundingClientRect();return{x:t.left+e.x,y:t.top+e.y}}return null},l=s(null==e?void 0:e.originalEvent)??s(e);if(!l)return!1;const c=o.getBoundingClientRect();if(l.x>=c.left&&l.x<=c.right&&l.y>=c.top&&l.y<=c.bottom)return!0;const u=document.elementFromPoint(l.x,l.y);return!(!u||!o.contains(u))}extractPointerInfo(e){if(!e||"object"!=typeof e)return null;const t=e;if("number"==typeof t.pointerId)return{id:t.pointerId,pointerType:"string"==typeof t.pointerType?t.pointerType:"unknown"};if("string"==typeof t.type){if(t.type.startsWith("touch"))return{id:-2,pointerType:"touch"};if(t.type.startsWith("mouse"))return{id:-1,pointerType:"mouse"}}return null}markControlPointerDown(e){const t=this.extractPointerInfo(e);t&&(this.lastControlPointerDown={...t,time:Date.now()})}clearControlPointerDown(e){if(!this.lastControlPointerDown)return;const t=this.extractPointerInfo(e);t&&t.id===this.lastControlPointerDown.id&&(this.lastControlPointerDown=null)}isRecentControlPointer(e){if(!this.lastControlPointerDown)return!1;const t=null==e?void 0:e.originalEvent,r=this.extractPointerInfo(t)??this.extractPointerInfo(e);if(!r)return!1;const o="touch"===this.lastControlPointerDown.pointerType?450:80;return!(Date.now()-this.lastControlPointerDown.time>o)&&(r.pointerType===this.lastControlPointerDown.pointerType&&("mouse"===r.pointerType||r.id===this.lastControlPointerDown.id))}mouseMove(e){var t;if(!this.map||!this.isDrawingInProgress)return;const r=bi.normalizeEvent(e);bi.shouldPreventDefault(r)&&(null==(t=r.preventDefault)||t.call(r));const o=bi.extractCoordinates(r,this.map);o&&this.tracer&&this.tracer.addLatLng(o)}async mouseUpLeave(e){var t;if(!this.map||!this.isDrawingInProgress)return;const r=bi.normalizeEvent(e);if(bi.shouldPreventDefault(r)&&(null==(t=r.preventDefault)||t.call(r)),this.polygonInformation.deletePolygonInformationStorage(),!this.tracer)return void this.stopDraw();const o=this.tracer.toGeoJSON();if(!o||!o.geometry||!o.geometry.coordinates||o.geometry.coordinates.length<3)return void this.stopDraw();let n;try{n=this.turfHelper.createPolygonFromTrace(o)}catch{return void this.stopDraw()}if(n&&n.geometry&&n.geometry.coordinates&&0!==n.geometry.coordinates.length){this.stopDraw();try{const e=this.getInteractionTargetLayerId();switch(this.modeManager.getCurrentMode()){case c.Add:{const t=await this.polygonMutationManager.addPolygon(n,{simplify:!0,noMerge:!1,targetLayerId:e});t.success||console.error("Error adding polygon via manager:",t.error);break}case c.Subtract:{const t=await this.polygonMutationManager.subtractPolygon(n,{targetLayerId:e});t.success||console.error("Error subtracting polygon via manager:",t.error);break}}}catch(i){console.error("Error in mouseUpLeave polygon operation:",i)}this.polygonInformation.createPolygonInformationStorage(this.arrayOfFeatureGroups)}else this.stopDraw()}async handleFreehandDrawCompletion(e){try{this.saveHistory("freehand");const t=this.getInteractionTargetLayerId();switch(this.modeManager.getCurrentMode()){case c.Add:{const r=await this.polygonMutationManager.addPolygon(e,{simplify:!0,noMerge:!1,targetLayerId:t});r.success||console.error("Error adding polygon via manager:",r.error);break}case c.Subtract:{const r=await this.polygonMutationManager.subtractPolygon(e,{targetLayerId:t});r.success||console.error("Error subtracting polygon via manager:",r.error);break}}}catch(t){console.error("Error in mouseUpLeave polygon operation:",t)}}startDraw(){this.isDrawingInProgress||(this.isDrawingInProgress=!0,this.drawStartedEvents(!0))}setupKeyboardHandlers(){this._boundKeyDownHandler||(this._boundKeyDownHandler=this.handleKeyDown.bind(this)),this._boundKeyUpHandler||(this._boundKeyUpHandler=this.handleKeyUp.bind(this)),document.addEventListener("keydown",this._boundKeyDownHandler),document.addEventListener("keyup",this._boundKeyUpHandler)}removeKeyboardHandlers(){this._boundKeyDownHandler&&document.removeEventListener("keydown",this._boundKeyDownHandler),this._boundKeyUpHandler&&document.removeEventListener("keyup",this._boundKeyUpHandler)}handleKeyDown(e){const t=e.ctrlKey||e.metaKey;if(t&&"z"===e.key&&!e.shiftKey)return e.preventDefault(),void this.undo();if(t&&("y"===e.key||"z"===e.key&&e.shiftKey))return e.preventDefault(),void this.redo();"Escape"===e.key&&(this.modeManager.getCurrentMode()!==c.PointToPoint&&this.modeManager.getCurrentMode()!==c.PointToPointSubtract||this.polygonDrawManager.cancelPointToPointDrawing());this.isModifierKeyPressed(e)&&!this.isModifierKeyHeld&&(this.isModifierKeyHeld=!0,this.polygonDrawManager.setModifierKey(!0),this.updateAllMarkersForEdgeDeletion(!0),this.applyModifierModeOverride(!0))}handleKeyUp(e){!this.isModifierKeyPressed(e)&&this.isModifierKeyHeld&&(this.isModifierKeyHeld=!1,this.polygonDrawManager.setModifierKey(!1),this.updateAllMarkersForEdgeDeletion(!1),this.applyModifierModeOverride(!1))}applyModifierModeOverride(e){if(e){if(this.modifierModeOverride)return;if(!this.config.modifierSubtractMode)return;const e=this.modeManager.getCurrentMode();return void(e===c.Add?(this.modifierModeOverride={from:e,to:c.Subtract},this.setDrawMode(c.Subtract,{preserveActiveDraw:!0})):e===c.PointToPoint&&(this.modifierModeOverride={from:e,to:c.PointToPointSubtract},this.setDrawMode(c.PointToPointSubtract,{preserveActiveDraw:!0})))}if(!this.modifierModeOverride)return;const{from:t,to:r}=this.modifierModeOverride;this.modifierModeOverride=null,this.modeManager.getCurrentMode()===r&&this.setDrawMode(t,{preserveActiveDraw:!0})}updateAllMarkersForEdgeDeletion(e){this.arrayOfFeatureGroups.forEach(t=>{t.eachLayer(t=>{t instanceof s.Marker&&this.updateMarkerForEdgeDeletion(t,e)})})}updateMarkerForEdgeDeletion(e,t){const r=e.getElement();r&&(t?(r.addEventListener("mouseenter",this.onMarkerHoverForEdgeDeletionEvent),r.addEventListener("mouseleave",this.onMarkerLeaveForEdgeDeletionEvent)):(r.removeEventListener("mouseenter",this.onMarkerHoverForEdgeDeletionEvent),r.removeEventListener("mouseleave",this.onMarkerLeaveForEdgeDeletionEvent),r.style.backgroundColor="",r.style.borderColor=""))}handleDoubleClick(e){this.modeManager.getCurrentMode()!==c.PointToPoint&&this.modeManager.getCurrentMode()!==c.PointToPointSubtract||(s.DomEvent.stop(e),this.polygonDrawManager.handleDoubleClick(e))}isModifierKeyPressed(e){return navigator.userAgent.toLowerCase().includes("mac")?e.metaKey:e.ctrlKey}ensureButtonTouchResponsiveness(e){e.querySelectorAll("a").forEach(e=>{e.style.pointerEvents="auto",e.style.touchAction="manipulation",e.style.position="relative",e.style.zIndex="1";const t=e=>{e.stopPropagation(),e.target.style.pointerEvents="auto"};e.addEventListener("touchstart",t,{passive:!0}),e.addEventListener("touchend",t,{passive:!0})})}updateActivateButtonIndicator(){if("function"!=typeof this.getContainer)return;const e=this.getContainer();if(!e)return;const t=e.querySelector(".icon-activate");if(!t)return;const r=this.arrayOfFeatureGroups.length>0,o=!oi.domUtil.hasClass(t,"active"),n=oi.domUtil.hasClass(t,"active")?t.dataset.collapsedIcon:t.dataset.activeIcon;n&&this.applyActivateButtonIcon(t,n);const i=r&&o;i?oi.domUtil.addClass(t,"polydraw-indicator-active"):oi.domUtil.removeClass(t,"polydraw-indicator-active");const a=this.config.styles.ui.controlButton.backgroundColor,s=this.config.styles.ui.controlButton.color,l=this.config.styles.ui.indicatorActive.backgroundColor;t.style.backgroundColor=i?l:a,t.style.color=s;const u=(e,t)=>{e&&(t?(e.style.opacity="1",e.style.pointerEvents="auto",e.setAttribute("aria-disabled","false"),e.tabIndex=0):(e.style.opacity="0.3",e.style.pointerEvents="none",e.setAttribute("aria-disabled","true"),e.tabIndex=-1))};u(e.querySelector(".icon-clone"),r),r||this.modeManager.getCurrentMode()!==c.Clone||this.setDrawMode(c.Off);u(e.querySelector(".icon-erase"),"defaultLayer"===(this.config.tools.eraseScope??"all")?this.layerManager.getFeatureGroupsForLayer("default").length>0:r)}applyActivateButtonIcon(e,t){ni(e,t)}}const Zi=e=>{if(e){if("undefined"!=typeof globalThis){globalThis.L||(globalThis.L=e)}e.control&&(e.control.polydraw=function(e){return new Ji(e)}),ri.reset()}};if("undefined"!=typeof globalThis){const e=globalThis.L;e&&Zi(e)}e.default=Ji,e.defaultConfig=g,e.leafletAdapter=oi,e.registerWithLeaflet=Zi,Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
2
2
  //# sourceMappingURL=polydraw.umd.min.js.map