ofs-object 0.1.6 → 0.1.7

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.
@@ -23,7 +23,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
23
23
  `}[t]}}class Ce{static isRing(t){return!(t.length<4||!t[0].equals2D(t[t.length-1]))}static ptNotInList(t,e){for(let n=0;n<t.length;n++){const r=t[n];if(Ce.indexOf(r,e)<0)return r}return null}static scroll(t,e){const n=Ce.indexOf(e,t);if(n<0)return null;const r=new Array(t.length).fill(null);pi.arraycopy(t,n,r,0,t.length-n),pi.arraycopy(t,0,r,t.length-n,n),pi.arraycopy(r,0,t,0,t.length)}static equals(){if(arguments.length===2){const t=arguments[0],e=arguments[1];if(t===e)return!0;if(t===null||e===null||t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(!t[n].equals(e[n]))return!1;return!0}else if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2];if(t===e)return!0;if(t===null||e===null||t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(n.compare(t[r],e[r])!==0)return!1;return!0}}static intersection(t,e){const n=new or;for(let r=0;r<t.length;r++)e.intersects(t[r])&&n.add(t[r],!0);return n.toCoordinateArray()}static measures(t){if(t===null||t.length===0)return 0;let e=0;for(const n of t)e=Math.max(e,yl.measures(n));return e}static hasRepeatedPoints(t){for(let e=1;e<t.length;e++)if(t[e-1].equals(t[e]))return!0;return!1}static removeRepeatedPoints(t){return Ce.hasRepeatedPoints(t)?new or(t,!1).toCoordinateArray():t}static reverse(t){const e=t.length-1,n=Math.trunc(e/2);for(let r=0;r<=n;r++){const s=t[r];t[r]=t[e-r],t[e-r]=s}}static removeNull(t){let e=0;for(let s=0;s<t.length;s++)t[s]!==null&&e++;const n=new Array(e).fill(null);if(e===0)return n;let r=0;for(let s=0;s<t.length;s++)t[s]!==null&&(n[r++]=t[s]);return n}static copyDeep(){if(arguments.length===1){const t=arguments[0],e=new Array(t.length).fill(null);for(let n=0;n<t.length;n++)e[n]=t[n].copy();return e}else if(arguments.length===5){const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3],s=arguments[4];for(let o=0;o<s;o++)n[r+o]=t[e+o].copy()}}static isEqualReversed(t,e){for(let n=0;n<t.length;n++){const r=t[n],s=e[t.length-n-1];if(r.compareTo(s)!==0)return!1}return!0}static envelope(t){const e=new ne;for(let n=0;n<t.length;n++)e.expandToInclude(t[n]);return e}static toCoordinateArray(t){return t.toArray(Ce.coordArrayType)}static dimension(t){if(t===null||t.length===0)return 3;let e=0;for(const n of t)e=Math.max(e,yl.dimension(n));return e}static atLeastNCoordinatesOrNothing(t,e){return e.length>=t?e:[]}static indexOf(t,e){for(let n=0;n<e.length;n++)if(t.equals(e[n]))return n;return-1}static increasingDirection(t){for(let e=0;e<Math.trunc(t.length/2);e++){const n=t.length-1-e,r=t[e].compareTo(t[n]);if(r!==0)return r}return 1}static compare(t,e){let n=0;for(;n<t.length&&n<e.length;){const r=t[n].compareTo(e[n]);if(r!==0)return r;n++}return n<e.length?-1:n<t.length?1:0}static minCoordinate(t){let e=null;for(let n=0;n<t.length;n++)(e===null||e.compareTo(t[n])>0)&&(e=t[n]);return e}static extract(t,e,n){e=Vo.clamp(e,0,t.length),n=Vo.clamp(n,-1,t.length);let r=n-e+1;n<0&&(r=0),e>=t.length&&(r=0),n<e&&(r=0);const s=new Array(r).fill(null);if(r===0)return s;let o=0;for(let a=e;a<=n;a++)s[o++]=t[a];return s}}class GO{compare(t,e){const n=t,r=e;return Ce.compare(n,r)}get interfaces_(){return[lo]}}class BO{compare(t,e){const n=t,r=e;if(n.length<r.length)return-1;if(n.length>r.length)return 1;if(n.length===0)return 0;const s=Ce.compare(n,r);return Ce.isEqualReversed(n,r)?0:s}OLDcompare(t,e){const n=t,r=e;if(n.length<r.length)return-1;if(n.length>r.length)return 1;if(n.length===0)return 0;const s=Ce.increasingDirection(n),o=Ce.increasingDirection(r);let a=s>0?0:n.length-1,l=o>0?0:n.length-1;for(let h=0;h<n.length;h++){const f=n[a].compareTo(r[l]);if(f!==0)return f;a+=s,l+=o}return 0}get interfaces_(){return[lo]}}Ce.ForwardComparator=GO;Ce.BidirectionalComparator=BO;Ce.coordArrayType=new Array(0).fill(null);class yd{constructor(t){this.str=t}append(t){this.str+=t}setCharAt(t,e){this.str=this.str.substr(0,t)+e+this.str.substr(t+1)}toString(){return this.str}}class Sr{constructor(){Sr.constructor_.apply(this,arguments)}static constructor_(){if(this._dimension=3,this._measures=0,this._coordinates=null,arguments.length===1){if(arguments[0]instanceof Array){const t=arguments[0];Sr.constructor_.call(this,t,Ce.dimension(t),Ce.measures(t))}else if(Number.isInteger(arguments[0])){const t=arguments[0];this._coordinates=new Array(t).fill(null);for(let e=0;e<t;e++)this._coordinates[e]=new Q}else if(At(arguments[0],de)){const t=arguments[0];if(t===null)return this._coordinates=new Array(0).fill(null),null;this._dimension=t.getDimension(),this._measures=t.getMeasures(),this._coordinates=new Array(t.size()).fill(null);for(let e=0;e<this._coordinates.length;e++)this._coordinates[e]=t.getCoordinateCopy(e)}}else if(arguments.length===2){if(arguments[0]instanceof Array&&Number.isInteger(arguments[1])){const t=arguments[0],e=arguments[1];Sr.constructor_.call(this,t,e,Ce.measures(t))}else if(Number.isInteger(arguments[0])&&Number.isInteger(arguments[1])){const t=arguments[0],e=arguments[1];this._coordinates=new Array(t).fill(null),this._dimension=e;for(let n=0;n<t;n++)this._coordinates[n]=yl.create(e)}}else if(arguments.length===3){if(Number.isInteger(arguments[2])&&arguments[0]instanceof Array&&Number.isInteger(arguments[1])){const t=arguments[0],e=arguments[1],n=arguments[2];this._dimension=e,this._measures=n,t===null?this._coordinates=new Array(0).fill(null):this._coordinates=t}else if(Number.isInteger(arguments[2])&&Number.isInteger(arguments[0])&&Number.isInteger(arguments[1])){const t=arguments[0],e=arguments[1],n=arguments[2];this._coordinates=new Array(t).fill(null),this._dimension=e,this._measures=n;for(let r=0;r<t;r++)this._coordinates[r]=this.createCoordinate()}}}getM(t){return this.hasM()?this._coordinates[t].getM():Tt.NaN}setOrdinate(t,e,n){switch(e){case de.X:this._coordinates[t].x=n;break;case de.Y:this._coordinates[t].y=n;break;default:this._coordinates[t].setOrdinate(e,n)}}getZ(t){return this.hasZ()?this._coordinates[t].getZ():Tt.NaN}size(){return this._coordinates.length}getOrdinate(t,e){switch(e){case de.X:return this._coordinates[t].x;case de.Y:return this._coordinates[t].y;default:return this._coordinates[t].getOrdinate(e)}}getCoordinate(){if(arguments.length===1){const t=arguments[0];return this._coordinates[t]}else if(arguments.length===2){const t=arguments[0];arguments[1].setCoordinate(this._coordinates[t])}}getCoordinateCopy(t){const e=this.createCoordinate();return e.setCoordinate(this._coordinates[t]),e}createCoordinate(){return yl.create(this.getDimension(),this.getMeasures())}getDimension(){return this._dimension}getX(t){return this._coordinates[t].x}getMeasures(){return this._measures}expandEnvelope(t){for(let e=0;e<this._coordinates.length;e++)t.expandToInclude(this._coordinates[e]);return t}copy(){const t=new Array(this.size()).fill(null);for(let e=0;e<this._coordinates.length;e++){const n=this.createCoordinate();n.setCoordinate(this._coordinates[e]),t[e]=n}return new Sr(t,this._dimension,this._measures)}toString(){if(this._coordinates.length>0){const t=new yd(17*this._coordinates.length);t.append("("),t.append(this._coordinates[0]);for(let e=1;e<this._coordinates.length;e++)t.append(", "),t.append(this._coordinates[e]);return t.append(")"),t.toString()}else return"()"}getY(t){return this._coordinates[t].y}toCoordinateArray(){return this._coordinates}get interfaces_(){return[de,wi]}}class _l{static instance(){return _l.instanceObject}readResolve(){return _l.instance()}create(){if(arguments.length===1){if(arguments[0]instanceof Array){const t=arguments[0];return new Sr(t)}else if(At(arguments[0],de)){const t=arguments[0];return new Sr(t)}}else if(arguments.length===2){let t=arguments[0],e=arguments[1];return e>3&&(e=3),e<2&&(e=2),new Sr(t,e)}else if(arguments.length===3){let t=arguments[0],e=arguments[1],n=arguments[2],r=e-n;return n>1&&(n=1),r>3&&(r=3),r<2&&(r=2),new Sr(t,r+n,n)}}get interfaces_(){return[Ax,wi]}}_l.instanceObject=new _l;class yi extends _e{constructor(){super(),yi.constructor_.apply(this,arguments)}static constructor_(){const t=arguments[0],e=arguments[1];_e.constructor_.call(this,t,e)}copyInternal(){const t=new Array(this._geometries.length).fill(null);for(let e=0;e<t.length;e++)t[e]=this._geometries[e].copy();return new yi(t,this._factory)}equalsExact(){if(arguments.length===2&&typeof arguments[1]=="number"&&arguments[0]instanceof dt){const t=arguments[0],e=arguments[1];return this.isEquivalentClass(t)?super.equalsExact.call(this,t,e):!1}else return super.equalsExact.apply(this,arguments)}getBoundaryDimension(){return 1}getTypeCode(){return dt.TYPECODE_MULTIPOLYGON}getDimension(){return 2}getBoundary(){if(this.isEmpty())return this.getFactory().createMultiLineString();const t=new wt;for(let n=0;n<this._geometries.length;n++){const s=this._geometries[n].getBoundary();for(let o=0;o<s.getNumGeometries();o++)t.add(s.getGeometryN(o))}const e=new Array(t.size()).fill(null);return this.getFactory().createMultiLineString(t.toArray(e))}getGeometryType(){return dt.TYPENAME_MULTIPOLYGON}get interfaces_(){return[co]}}let Gx=class{get(){}put(){}size(){}values(){}entrySet(){}};class Rc extends Dx{constructor(t){super(),this.map=new Map,t instanceof on&&this.addAll(t)}contains(t){const e=t.hashCode?t.hashCode():t;return!!this.map.has(e)}add(t){const e=t.hashCode?t.hashCode():t;return this.map.has(e)?!1:!!this.map.set(e,t)}addAll(t){for(const e of t)this.add(e);return!0}remove(){throw new cr}size(){return this.map.size}isEmpty(){return this.map.size===0}toArray(){return Array.from(this.map.values())}iterator(){return new qO(this.map)}[Symbol.iterator](){return this.map}}let qO=class{constructor(t){this.iterator=t.values();const{done:e,value:n}=this.iterator.next();this.done=e,this.value=n}next(){if(this.done)throw new Ol;const t=this.value,{done:e,value:n}=this.iterator.next();return this.done=e,this.value=n,t}hasNext(){return!this.done}remove(){throw new cr}};class Bx extends Gx{constructor(){super(),this.map=new Map}get(t){return this.map.get(t)||null}put(t,e){return this.map.set(t,e),e}values(){const t=new wt,e=this.map.values();let n=e.next();for(;!n.done;)t.add(n.value),n=e.next();return t}entrySet(){const t=new Rc;return this.map.entries().forEach(e=>t.add(e)),t}size(){return this.map.size()}}class we{constructor(){we.constructor_.apply(this,arguments)}static constructor_(){if(this._modelType=null,this._scale=null,arguments.length===0)this._modelType=we.FLOATING;else if(arguments.length===1){if(arguments[0]instanceof Zr){const t=arguments[0];this._modelType=t,t===we.FIXED&&this.setScale(1)}else if(typeof arguments[0]=="number"){const t=arguments[0];this._modelType=we.FIXED,this.setScale(t)}else if(arguments[0]instanceof we){const t=arguments[0];this._modelType=t._modelType,this._scale=t._scale}}}static mostPrecise(t,e){return t.compareTo(e)>=0?t:e}equals(t){if(!(t instanceof we))return!1;const e=t;return this._modelType===e._modelType&&this._scale===e._scale}compareTo(t){const e=t,n=this.getMaximumSignificantDigits(),r=e.getMaximumSignificantDigits();return pl.compare(n,r)}getScale(){return this._scale}isFloating(){return this._modelType===we.FLOATING||this._modelType===we.FLOATING_SINGLE}getType(){return this._modelType}toString(){let t="UNKNOWN";return this._modelType===we.FLOATING?t="Floating":this._modelType===we.FLOATING_SINGLE?t="Floating-Single":this._modelType===we.FIXED&&(t="Fixed (Scale="+this.getScale()+")"),t}makePrecise(){if(typeof arguments[0]=="number"){const t=arguments[0];return Tt.isNaN(t)||this._modelType===we.FLOATING_SINGLE?t:this._modelType===we.FIXED?Math.round(t*this._scale)/this._scale:t}else if(arguments[0]instanceof Q){const t=arguments[0];if(this._modelType===we.FLOATING)return null;t.x=this.makePrecise(t.x),t.y=this.makePrecise(t.y)}}getMaximumSignificantDigits(){let t=16;return this._modelType===we.FLOATING?t=16:this._modelType===we.FLOATING_SINGLE?t=6:this._modelType===we.FIXED&&(t=1+Math.trunc(Math.ceil(Math.log(this.getScale())/Math.log(10)))),t}setScale(t){this._scale=Math.abs(t)}get interfaces_(){return[wi,Ei]}}class Zr{constructor(){Zr.constructor_.apply(this,arguments)}static constructor_(){this._name=null;const t=arguments[0];this._name=t,Zr.nameToTypeMap.put(t,this)}readResolve(){return Zr.nameToTypeMap.get(this._name)}toString(){return this._name}get interfaces_(){return[wi]}}Zr.nameToTypeMap=new Bx;we.Type=Zr;we.FIXED=new Zr("FIXED");we.FLOATING=new Zr("FLOATING");we.FLOATING_SINGLE=new Zr("FLOATING SINGLE");we.maximumPreciseValue=9007199254740992;class ur extends _e{constructor(){super(),ur.constructor_.apply(this,arguments)}static constructor_(){const t=arguments[0],e=arguments[1];_e.constructor_.call(this,t,e)}copyInternal(){const t=new Array(this._geometries.length).fill(null);for(let e=0;e<t.length;e++)t[e]=this._geometries[e].copy();return new ur(t,this._factory)}equalsExact(){if(arguments.length===2&&typeof arguments[1]=="number"&&arguments[0]instanceof dt){const t=arguments[0],e=arguments[1];return this.isEquivalentClass(t)?super.equalsExact.call(this,t,e):!1}else return super.equalsExact.apply(this,arguments)}getBoundaryDimension(){return this.isClosed()?yt.FALSE:0}isClosed(){if(this.isEmpty())return!1;for(let t=0;t<this._geometries.length;t++)if(!this._geometries[t].isClosed())return!1;return!0}getTypeCode(){return dt.TYPECODE_MULTILINESTRING}getDimension(){return 1}getBoundary(){throw new cr}getGeometryType(){return dt.TYPENAME_MULTILINESTRING}get interfaces_(){return[Fx]}}class qe{constructor(){qe.constructor_.apply(this,arguments)}static constructor_(){if(this._precisionModel=null,this._coordinateSequenceFactory=null,this._SRID=null,arguments.length===0)qe.constructor_.call(this,new we,0);else if(arguments.length===1){if(At(arguments[0],Ax)){const t=arguments[0];qe.constructor_.call(this,new we,0,t)}else if(arguments[0]instanceof we){const t=arguments[0];qe.constructor_.call(this,t,0,qe.getDefaultCoordinateSequenceFactory())}}else if(arguments.length===2){const t=arguments[0],e=arguments[1];qe.constructor_.call(this,t,e,qe.getDefaultCoordinateSequenceFactory())}else if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2];this._precisionModel=t,this._coordinateSequenceFactory=n,this._SRID=e}}static toMultiPolygonArray(t){const e=new Array(t.size()).fill(null);return t.toArray(e)}static toGeometryArray(t){if(t===null)return null;const e=new Array(t.size()).fill(null);return t.toArray(e)}static getDefaultCoordinateSequenceFactory(){return _l.instance()}static toMultiLineStringArray(t){const e=new Array(t.size()).fill(null);return t.toArray(e)}static toLineStringArray(t){const e=new Array(t.size()).fill(null);return t.toArray(e)}static toMultiPointArray(t){const e=new Array(t.size()).fill(null);return t.toArray(e)}static toLinearRingArray(t){const e=new Array(t.size()).fill(null);return t.toArray(e)}static toPointArray(t){const e=new Array(t.size()).fill(null);return t.toArray(e)}static toPolygonArray(t){const e=new Array(t.size()).fill(null);return t.toArray(e)}static createPointFromInternalCoord(t,e){return e.getPrecisionModel().makePrecise(t),e.getFactory().createPoint(t)}createEmpty(t){switch(t){case-1:return this.createGeometryCollection();case 0:return this.createPoint();case 1:return this.createLineString();case 2:return this.createPolygon();default:throw new te("Invalid dimension: "+t)}}toGeometry(t){return t.isNull()?this.createPoint():t.getMinX()===t.getMaxX()&&t.getMinY()===t.getMaxY()?this.createPoint(new Q(t.getMinX(),t.getMinY())):t.getMinX()===t.getMaxX()||t.getMinY()===t.getMaxY()?this.createLineString([new Q(t.getMinX(),t.getMinY()),new Q(t.getMaxX(),t.getMaxY())]):this.createPolygon(this.createLinearRing([new Q(t.getMinX(),t.getMinY()),new Q(t.getMinX(),t.getMaxY()),new Q(t.getMaxX(),t.getMaxY()),new Q(t.getMaxX(),t.getMinY()),new Q(t.getMinX(),t.getMinY())]),null)}createLineString(){if(arguments.length===0)return this.createLineString(this.getCoordinateSequenceFactory().create([]));if(arguments.length===1){if(arguments[0]instanceof Array){const t=arguments[0];return this.createLineString(t!==null?this.getCoordinateSequenceFactory().create(t):null)}else if(At(arguments[0],de)){const t=arguments[0];return new he(t,this)}}}createMultiLineString(){if(arguments.length===0)return new ur(null,this);if(arguments.length===1){const t=arguments[0];return new ur(t,this)}}buildGeometry(t){let e=null,n=!1,r=!1;for(let a=t.iterator();a.hasNext();){const l=a.next(),h=l.getTypeCode();e===null&&(e=h),h!==e&&(n=!0),l instanceof _e&&(r=!0)}if(e===null)return this.createGeometryCollection();if(n||r)return this.createGeometryCollection(qe.toGeometryArray(t));const s=t.iterator().next();if(t.size()>1){if(s instanceof Te)return this.createMultiPolygon(qe.toPolygonArray(t));if(s instanceof he)return this.createMultiLineString(qe.toLineStringArray(t));if(s instanceof De)return this.createMultiPoint(qe.toPointArray(t));Yt.shouldNeverReachHere("Unhandled geometry type: "+s.getGeometryType())}return s}createMultiPointFromCoords(t){return this.createMultiPoint(t!==null?this.getCoordinateSequenceFactory().create(t):null)}createPoint(){if(arguments.length===0)return this.createPoint(this.getCoordinateSequenceFactory().create([]));if(arguments.length===1){if(arguments[0]instanceof Q){const t=arguments[0];return this.createPoint(t!==null?this.getCoordinateSequenceFactory().create([t]):null)}else if(At(arguments[0],de)){const t=arguments[0];return new De(t,this)}}}getCoordinateSequenceFactory(){return this._coordinateSequenceFactory}createPolygon(){if(arguments.length===0)return this.createPolygon(null,null);if(arguments.length===1){if(At(arguments[0],de)){const t=arguments[0];return this.createPolygon(this.createLinearRing(t))}else if(arguments[0]instanceof Array){const t=arguments[0];return this.createPolygon(this.createLinearRing(t))}else if(arguments[0]instanceof gn){const t=arguments[0];return this.createPolygon(t,null)}}else if(arguments.length===2){const t=arguments[0],e=arguments[1];return new Te(t,e,this)}}getSRID(){return this._SRID}createGeometryCollection(){if(arguments.length===0)return new _e(null,this);if(arguments.length===1){const t=arguments[0];return new _e(t,this)}}getPrecisionModel(){return this._precisionModel}createLinearRing(){if(arguments.length===0)return this.createLinearRing(this.getCoordinateSequenceFactory().create([]));if(arguments.length===1){if(arguments[0]instanceof Array){const t=arguments[0];return this.createLinearRing(t!==null?this.getCoordinateSequenceFactory().create(t):null)}else if(At(arguments[0],de)){const t=arguments[0];return new gn(t,this)}}}createMultiPolygon(){if(arguments.length===0)return new yi(null,this);if(arguments.length===1){const t=arguments[0];return new yi(t,this)}}createMultiPoint(){if(arguments.length===0)return new Rr(null,this);if(arguments.length===1){if(arguments[0]instanceof Array){const t=arguments[0];return new Rr(t,this)}else if(At(arguments[0],de)){const t=arguments[0];if(t===null)return this.createMultiPoint(new Array(0).fill(null));const e=new Array(t.size()).fill(null);for(let n=0;n<t.size();n++){const r=this.getCoordinateSequenceFactory().create(1,t.getDimension(),t.getMeasures());nn.copy(t,n,r,0,1),e[n]=this.createPoint(r)}return this.createMultiPoint(e)}}}get interfaces_(){return[wi]}}const zO=["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon"];class qx{constructor(t){this.geometryFactory=t||new qe}read(t){let e;typeof t=="string"?e=JSON.parse(t):e=t;const n=e.type;if(!Ki[n])throw new Error("Unknown GeoJSON type: "+e.type);return zO.indexOf(n)!==-1?Ki[n].call(this,e.coordinates):n==="GeometryCollection"?Ki[n].call(this,e.geometries):Ki[n].call(this,e)}write(t){const e=t.getGeometryType();if(!qr[e])throw new Error("Geometry is not supported");return qr[e].call(this,t)}}const Ki={Feature:function(i){const t={};for(const e in i)t[e]=i[e];if(i.geometry){const e=i.geometry.type;if(!Ki[e])throw new Error("Unknown GeoJSON type: "+i.type);t.geometry=this.read(i.geometry)}return i.bbox&&(t.bbox=Ki.bbox.call(this,i.bbox)),t},FeatureCollection:function(i){const t={};if(i.features){t.features=[];for(let e=0;e<i.features.length;++e)t.features.push(this.read(i.features[e]))}return i.bbox&&(t.bbox=this.parse.bbox.call(this,i.bbox)),t},coordinates:function(i){const t=[];for(let e=0;e<i.length;++e){const n=i[e];t.push(new Q(...n))}return t},bbox:function(i){return this.geometryFactory.createLinearRing([new Q(i[0],i[1]),new Q(i[2],i[1]),new Q(i[2],i[3]),new Q(i[0],i[3]),new Q(i[0],i[1])])},Point:function(i){const t=new Q(...i);return this.geometryFactory.createPoint(t)},MultiPoint:function(i){const t=[];for(let e=0;e<i.length;++e)t.push(Ki.Point.call(this,i[e]));return this.geometryFactory.createMultiPoint(t)},LineString:function(i){const t=Ki.coordinates.call(this,i);return this.geometryFactory.createLineString(t)},MultiLineString:function(i){const t=[];for(let e=0;e<i.length;++e)t.push(Ki.LineString.call(this,i[e]));return this.geometryFactory.createMultiLineString(t)},Polygon:function(i){const t=Ki.coordinates.call(this,i[0]),e=this.geometryFactory.createLinearRing(t),n=[];for(let r=1;r<i.length;++r){const s=i[r],o=Ki.coordinates.call(this,s),a=this.geometryFactory.createLinearRing(o);n.push(a)}return this.geometryFactory.createPolygon(e,n)},MultiPolygon:function(i){const t=[];for(let e=0;e<i.length;++e){const n=i[e];t.push(Ki.Polygon.call(this,n))}return this.geometryFactory.createMultiPolygon(t)},GeometryCollection:function(i){const t=[];for(let e=0;e<i.length;++e){const n=i[e];t.push(this.read(n))}return this.geometryFactory.createGeometryCollection(t)}},qr={coordinate:function(i){const t=[i.x,i.y];return i.z&&t.push(i.z),i.m&&t.push(i.m),t},Point:function(i){return{type:"Point",coordinates:qr.coordinate.call(this,i.getCoordinate())}},MultiPoint:function(i){const t=[];for(let e=0;e<i._geometries.length;++e){const n=i._geometries[e],r=qr.Point.call(this,n);t.push(r.coordinates)}return{type:"MultiPoint",coordinates:t}},LineString:function(i){const t=[],e=i.getCoordinates();for(let n=0;n<e.length;++n){const r=e[n];t.push(qr.coordinate.call(this,r))}return{type:"LineString",coordinates:t}},MultiLineString:function(i){const t=[];for(let e=0;e<i._geometries.length;++e){const n=i._geometries[e],r=qr.LineString.call(this,n);t.push(r.coordinates)}return{type:"MultiLineString",coordinates:t}},Polygon:function(i){const t=[],e=qr.LineString.call(this,i._shell);t.push(e.coordinates);for(let n=0;n<i._holes.length;++n){const r=i._holes[n],s=qr.LineString.call(this,r);t.push(s.coordinates)}return{type:"Polygon",coordinates:t}},MultiPolygon:function(i){const t=[];for(let e=0;e<i._geometries.length;++e){const n=i._geometries[e],r=qr.Polygon.call(this,n);t.push(r.coordinates)}return{type:"MultiPolygon",coordinates:t}},GeometryCollection:function(i){const t=[];for(let e=0;e<i._geometries.length;++e){const n=i._geometries[e],r=n.getGeometryType();t.push(qr[r].call(this,n))}return{type:"GeometryCollection",geometries:t}}};class _d{constructor(t){this.parser=new qx(t||new qe)}read(t){return this.parser.read(t)}}class zx{constructor(){this.parser=new qx(this.geometryFactory)}write(t){return this.parser.write(t)}}const ya={XY:"XY",XYZ:"XYZ",XYM:"XYM",XYZM:"XYZM"},pv={POINT:"Point",LINE_STRING:"LineString",LINEAR_RING:"LinearRing",POLYGON:"Polygon",MULTI_POINT:"MultiPoint",MULTI_LINE_STRING:"MultiLineString",MULTI_POLYGON:"MultiPolygon",GEOMETRY_COLLECTION:"GeometryCollection",CIRCLE:"Circle"},Ux="EMPTY",Yx="Z",jx="M",UO="ZM",be={TEXT:1,LEFT_PAREN:2,RIGHT_PAREN:3,NUMBER:4,COMMA:5,EOF:6};for(const i in pv)pv[i].toUpperCase();class YO{constructor(t){this.wkt=t,this.index_=-1}isAlpha_(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"}isNumeric_(t,e){const n=e!==void 0?e:!1;return t>="0"&&t<="9"||t=="."&&!n}isWhiteSpace_(t){return t==" "||t==" "||t=="\r"||t==`
24
24
  `}nextChar_(){return this.wkt.charAt(++this.index_)}nextToken(){const t=this.nextChar_(),e=this.index_;let n=t,r;if(t=="(")r=be.LEFT_PAREN;else if(t==",")r=be.COMMA;else if(t==")")r=be.RIGHT_PAREN;else if(this.isNumeric_(t)||t=="-")r=be.NUMBER,n=this.readNumber_();else if(this.isAlpha_(t))r=be.TEXT,n=this.readText_();else{if(this.isWhiteSpace_(t))return this.nextToken();if(t==="")r=be.EOF;else throw new Error("Unexpected character: "+t)}return{position:e,value:n,type:r}}readNumber_(){let t;const e=this.index_;let n=!1,r=!1;do t=="."?n=!0:(t=="e"||t=="E")&&(r=!0),t=this.nextChar_();while(this.isNumeric_(t,n)||!r&&(t=="e"||t=="E")||r&&(t=="-"||t=="+"));return parseFloat(this.wkt.substring(e,this.index_--))}readText_(){let t;const e=this.index_;do t=this.nextChar_();while(this.isAlpha_(t));return this.wkt.substring(e,this.index_--).toUpperCase()}}let jO=class{constructor(t,e){this.lexer_=t,this.token_,this.layout_=ya.XY,this.factory=e}consume_(){this.token_=this.lexer_.nextToken()}isTokenType(t){return this.token_.type==t}match(t){const e=this.isTokenType(t);return e&&this.consume_(),e}parse(){return this.consume_(),this.parseGeometry_()}parseGeometryLayout_(){let t=ya.XY;const e=this.token_;if(this.isTokenType(be.TEXT)){const n=e.value;n===Yx?t=ya.XYZ:n===jx?t=ya.XYM:n===UO&&(t=ya.XYZM),t!==ya.XY&&this.consume_()}return t}parseGeometryCollectionText_(){if(this.match(be.LEFT_PAREN)){const t=[];do t.push(this.parseGeometry_());while(this.match(be.COMMA));if(this.match(be.RIGHT_PAREN))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}parsePointText_(){if(this.match(be.LEFT_PAREN)){const t=this.parsePoint_();if(this.match(be.RIGHT_PAREN))return t}else if(this.isEmptyGeometry_())return null;throw new Error(this.formatErrorMessage_())}parseLineStringText_(){if(this.match(be.LEFT_PAREN)){const t=this.parsePointList_();if(this.match(be.RIGHT_PAREN))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}parsePolygonText_(){if(this.match(be.LEFT_PAREN)){const t=this.parseLineStringTextList_();if(this.match(be.RIGHT_PAREN))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}parseMultiPointText_(){if(this.match(be.LEFT_PAREN)){let t;if(this.token_.type==be.LEFT_PAREN?t=this.parsePointTextList_():t=this.parsePointList_(),this.match(be.RIGHT_PAREN))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}parseMultiLineStringText_(){if(this.match(be.LEFT_PAREN)){const t=this.parseLineStringTextList_();if(this.match(be.RIGHT_PAREN))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}parseMultiPolygonText_(){if(this.match(be.LEFT_PAREN)){const t=this.parsePolygonTextList_();if(this.match(be.RIGHT_PAREN))return t}else if(this.isEmptyGeometry_())return[];throw new Error(this.formatErrorMessage_())}parsePoint_(){const t=[],e=this.layout_.length;for(let n=0;n<e;++n){const r=this.token_;if(this.match(be.NUMBER))t.push(r.value);else break}if(t.length==e)return t;throw new Error(this.formatErrorMessage_())}parsePointList_(){const t=[this.parsePoint_()];for(;this.match(be.COMMA);)t.push(this.parsePoint_());return t}parsePointTextList_(){const t=[this.parsePointText_()];for(;this.match(be.COMMA);)t.push(this.parsePointText_());return t}parseLineStringTextList_(){const t=[this.parseLineStringText_()];for(;this.match(be.COMMA);)t.push(this.parseLineStringText_());return t}parsePolygonTextList_(){const t=[this.parsePolygonText_()];for(;this.match(be.COMMA);)t.push(this.parsePolygonText_());return t}isEmptyGeometry_(){const t=this.isTokenType(be.TEXT)&&this.token_.value==Ux;return t&&this.consume_(),t}formatErrorMessage_(){return"Unexpected `"+this.token_.value+"` at position "+this.token_.position+" in `"+this.lexer_.wkt+"`"}parseGeometry_(){const t=this.factory,e=s=>new Q(...s),n=s=>{const o=s.map(a=>t.createLinearRing(a.map(e)));return o.length>1?t.createPolygon(o[0],o.slice(1)):t.createPolygon(o[0])},r=this.token_;if(this.match(be.TEXT)){const s=r.value;if(this.layout_=this.parseGeometryLayout_(),s=="GEOMETRYCOLLECTION"){const o=this.parseGeometryCollectionText_();return t.createGeometryCollection(o)}else switch(s){case"POINT":{const o=this.parsePointText_();return o?t.createPoint(new Q(...o)):t.createPoint()}case"LINESTRING":{const a=this.parseLineStringText_().map(e);return t.createLineString(a)}case"LINEARRING":{const a=this.parseLineStringText_().map(e);return t.createLinearRing(a)}case"POLYGON":{const o=this.parsePolygonText_();return!o||o.length===0?t.createPolygon():n(o)}case"MULTIPOINT":{const o=this.parseMultiPointText_();if(!o||o.length===0)return t.createMultiPoint();const a=o.map(e).map(l=>t.createPoint(l));return t.createMultiPoint(a)}case"MULTILINESTRING":{const a=this.parseMultiLineStringText_().map(l=>t.createLineString(l.map(e)));return t.createMultiLineString(a)}case"MULTIPOLYGON":{const o=this.parseMultiPolygonText_();if(!o||o.length===0)return t.createMultiPolygon();const a=o.map(n);return t.createMultiPolygon(a)}default:throw new Error("Invalid geometry type: "+s)}}throw new Error(this.formatErrorMessage_())}};function Xx(i){if(i.isEmpty())return"";const t=i.getCoordinate(),e=[t.x,t.y];return t.z!==void 0&&!Number.isNaN(t.z)&&e.push(t.z),t.m!==void 0&&!Number.isNaN(t.m)&&e.push(t.m),e.join(" ")}function XO(i){const t=[];for(let e=0,n=i.getNumGeometries();e<n;++e)t.push("("+Xx(i.getGeometryN(e))+")");return t.join(", ")}function VO(i){const t=[];for(let e=0,n=i.getNumGeometries();e<n;++e)t.push(Wx(i.getGeometryN(e)));return t.join(", ")}function Ju(i){const t=i.getCoordinates().map(n=>{const r=[n.x,n.y];return n.z!==void 0&&!Number.isNaN(n.z)&&r.push(n.z),n.m!==void 0&&!Number.isNaN(n.m)&&r.push(n.m),r}),e=[];for(let n=0,r=t.length;n<r;++n)e.push(t[n].join(" "));return e.join(", ")}function WO(i){const t=[];for(let e=0,n=i.getNumGeometries();e<n;++e)t.push("("+Ju(i.getGeometryN(e))+")");return t.join(", ")}function Vx(i){const t=[];t.push("("+Ju(i.getExteriorRing())+")");for(let e=0,n=i.getNumInteriorRing();e<n;++e)t.push("("+Ju(i.getInteriorRingN(e))+")");return t.join(", ")}function HO(i){const t=[];for(let e=0,n=i.getNumGeometries();e<n;++e)t.push("("+Vx(i.getGeometryN(e))+")");return t.join(", ")}function KO(i){let t="";if(i.isEmpty())return t;const e=i.getCoordinate();return e.z!==void 0&&!Number.isNaN(e.z)&&(t+=Yx),e.m!==void 0&&!Number.isNaN(e.m)&&(t+=jx),t}const ZO={Point:Xx,LineString:Ju,LinearRing:Ju,Polygon:Vx,MultiPoint:XO,MultiLineString:WO,MultiPolygon:HO,GeometryCollection:VO};function Wx(i){let t=i.getGeometryType();const e=ZO[t];t=t.toUpperCase();const n=KO(i);if(n.length>0&&(t+=" "+n),i.isEmpty())return t+" "+Ux;const r=e(i);return t+" ("+r+")"}class JO{constructor(t){this.geometryFactory=t||new qe,this.precisionModel=this.geometryFactory.getPrecisionModel()}read(t){const e=new YO(t);return new jO(e,this.geometryFactory).parse()}write(t){return Wx(t)}}class rs{constructor(t){this.parser=new JO(t)}write(t){return this.parser.write(t)}static toLineString(t,e){if(arguments.length!==2)throw new Error("Not implemented");return"LINESTRING ( "+t.x+" "+t.y+", "+e.x+" "+e.y+" )"}}class re{constructor(){re.constructor_.apply(this,arguments)}static constructor_(){if(this._quadrantSegments=re.DEFAULT_QUADRANT_SEGMENTS,this._endCapStyle=re.CAP_ROUND,this._joinStyle=re.JOIN_ROUND,this._mitreLimit=re.DEFAULT_MITRE_LIMIT,this._isSingleSided=!1,this._simplifyFactor=re.DEFAULT_SIMPLIFY_FACTOR,arguments.length!==0){if(arguments.length===1){const t=arguments[0];this.setQuadrantSegments(t)}else if(arguments.length===2){const t=arguments[0],e=arguments[1];this.setQuadrantSegments(t),this.setEndCapStyle(e)}else if(arguments.length===4){const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];this.setQuadrantSegments(t),this.setEndCapStyle(e),this.setJoinStyle(n),this.setMitreLimit(r)}}}static bufferDistanceError(t){const e=Math.PI/2/t;return 1-Math.cos(e/2)}getEndCapStyle(){return this._endCapStyle}isSingleSided(){return this._isSingleSided}setQuadrantSegments(t){this._quadrantSegments=t,this._quadrantSegments===0&&(this._joinStyle=re.JOIN_BEVEL),this._quadrantSegments<0&&(this._joinStyle=re.JOIN_MITRE,this._mitreLimit=Math.abs(this._quadrantSegments)),t<=0&&(this._quadrantSegments=1),this._joinStyle!==re.JOIN_ROUND&&(this._quadrantSegments=re.DEFAULT_QUADRANT_SEGMENTS)}getJoinStyle(){return this._joinStyle}setJoinStyle(t){this._joinStyle=t}setSimplifyFactor(t){this._simplifyFactor=t<0?0:t}getSimplifyFactor(){return this._simplifyFactor}getQuadrantSegments(){return this._quadrantSegments}setEndCapStyle(t){this._endCapStyle=t}getMitreLimit(){return this._mitreLimit}setMitreLimit(t){this._mitreLimit=t}setSingleSided(t){this._isSingleSided=t}}re.CAP_ROUND=1;re.CAP_FLAT=2;re.CAP_SQUARE=3;re.JOIN_ROUND=1;re.JOIN_MITRE=2;re.JOIN_BEVEL=3;re.DEFAULT_QUADRANT_SEGMENTS=8;re.DEFAULT_MITRE_LIMIT=5;re.DEFAULT_SIMPLIFY_FACTOR=.01;class z{static toLocationSymbol(t){switch(t){case z.EXTERIOR:return"e";case z.BOUNDARY:return"b";case z.INTERIOR:return"i";case z.NONE:return"-"}throw new te("Unknown location value: "+t)}}z.INTERIOR=0;z.BOUNDARY=1;z.EXTERIOR=2;z.NONE=-1;class _t{static opposite(t){return t===_t.LEFT?_t.RIGHT:t===_t.RIGHT?_t.LEFT:t}}_t.ON=0;_t.LEFT=1;_t.RIGHT=2;class Lf extends Tr{constructor(t){super(t),this.name=Object.keys({EmptyStackException:Lf})[0]}}class Hx extends Oi{constructor(){super(),this.array=[]}add(t){return this.array.push(t),!0}get(t){if(t<0||t>=this.size())throw new pd;return this.array[t]}push(t){return this.array.push(t),t}pop(){if(this.array.length===0)throw new Lf;return this.array.pop()}peek(){if(this.array.length===0)throw new Lf;return this.array[this.array.length-1]}empty(){return this.array.length===0}isEmpty(){return this.empty()}search(t){return this.array.indexOf(t)}size(){return this.array.length}toArray(){return this.array.slice()}}class Up{constructor(){Up.constructor_.apply(this,arguments)}static constructor_(){this._minIndex=-1,this._minCoord=null,this._minDe=null,this._orientedDe=null}getCoordinate(){return this._minCoord}getRightmostSide(t,e){let n=this.getRightmostSideOfSegment(t,e);return n<0&&(n=this.getRightmostSideOfSegment(t,e-1)),n<0&&(this._minCoord=null,this.checkForRightmostCoordinate(t)),n}findRightmostEdgeAtVertex(){const t=this._minDe.getEdge().getCoordinates();Yt.isTrue(this._minIndex>0&&this._minIndex<t.length,"rightmost point expected to be interior vertex of edge");const e=t[this._minIndex-1],n=t[this._minIndex+1],r=$t.index(this._minCoord,n,e);let s=!1;(e.y<this._minCoord.y&&n.y<this._minCoord.y&&r===$t.COUNTERCLOCKWISE||e.y>this._minCoord.y&&n.y>this._minCoord.y&&r===$t.CLOCKWISE)&&(s=!0),s&&(this._minIndex=this._minIndex-1)}getRightmostSideOfSegment(t,e){const r=t.getEdge().getCoordinates();if(e<0||e+1>=r.length||r[e].y===r[e+1].y)return-1;let s=_t.LEFT;return r[e].y<r[e+1].y&&(s=_t.RIGHT),s}getEdge(){return this._orientedDe}checkForRightmostCoordinate(t){const e=t.getEdge().getCoordinates();for(let n=0;n<e.length-1;n++)(this._minCoord===null||e[n].x>this._minCoord.x)&&(this._minDe=t,this._minIndex=n,this._minCoord=e[n])}findRightmostEdgeAtNode(){const e=this._minDe.getNode().getEdges();this._minDe=e.getRightmostEdge(),this._minDe.isForward()||(this._minDe=this._minDe.getSym(),this._minIndex=this._minDe.getEdge().getCoordinates().length-1)}findEdge(t){for(let n=t.iterator();n.hasNext();){const r=n.next();r.isForward()&&this.checkForRightmostCoordinate(r)}Yt.isTrue(this._minIndex!==0||this._minCoord.equals(this._minDe.getCoordinate()),"inconsistency in rightmost processing"),this._minIndex===0?this.findRightmostEdgeAtNode():this.findRightmostEdgeAtVertex(),this._orientedDe=this._minDe,this.getRightmostSide(this._minDe,this._minIndex)===_t.LEFT&&(this._orientedDe=this._minDe.getSym())}}class Fi extends mi{constructor(t,e){super(e?t+" [ "+e+" ]":t),this.pt=e?new Q(e):void 0,this.name=Object.keys({TopologyException:Fi})[0]}getCoordinate(){return this.pt}}class QO{constructor(){this.array=[]}addLast(t){this.array.push(t)}removeFirst(){return this.array.shift()}isEmpty(){return this.array.length===0}}class Yp{constructor(){Yp.constructor_.apply(this,arguments)}static constructor_(){this._finder=null,this._dirEdgeList=new wt,this._nodes=new wt,this._rightMostCoord=null,this._env=null,this._finder=new Up}clearVisitedEdges(){for(let t=this._dirEdgeList.iterator();t.hasNext();)t.next().setVisited(!1)}getRightmostCoordinate(){return this._rightMostCoord}computeNodeDepth(t){let e=null;for(let n=t.getEdges().iterator();n.hasNext();){const r=n.next();if(r.isVisited()||r.getSym().isVisited()){e=r;break}}if(e===null)throw new Fi("unable to find edge to compute depths at "+t.getCoordinate());t.getEdges().computeDepths(e);for(let n=t.getEdges().iterator();n.hasNext();){const r=n.next();r.setVisited(!0),this.copySymDepths(r)}}computeDepth(t){this.clearVisitedEdges();const e=this._finder.getEdge();e.getNode(),e.getLabel(),e.setEdgeDepths(_t.RIGHT,t),this.copySymDepths(e),this.computeDepths(e)}create(t){this.addReachable(t),this._finder.findEdge(this._dirEdgeList),this._rightMostCoord=this._finder.getCoordinate()}findResultEdges(){for(let t=this._dirEdgeList.iterator();t.hasNext();){const e=t.next();e.getDepth(_t.RIGHT)>=1&&e.getDepth(_t.LEFT)<=0&&!e.isInteriorAreaEdge()&&e.setInResult(!0)}}computeDepths(t){const e=new Rc,n=new QO,r=t.getNode();for(n.addLast(r),e.add(r),t.setVisited(!0);!n.isEmpty();){const s=n.removeFirst();e.add(s),this.computeNodeDepth(s);for(let o=s.getEdges().iterator();o.hasNext();){const l=o.next().getSym();if(l.isVisited())continue;const h=l.getNode();e.contains(h)||(n.addLast(h),e.add(h))}}}compareTo(t){const e=t;return this._rightMostCoord.x<e._rightMostCoord.x?-1:this._rightMostCoord.x>e._rightMostCoord.x?1:0}getEnvelope(){if(this._env===null){const t=new ne;for(let e=this._dirEdgeList.iterator();e.hasNext();){const r=e.next().getEdge().getCoordinates();for(let s=0;s<r.length-1;s++)t.expandToInclude(r[s])}this._env=t}return this._env}addReachable(t){const e=new Hx;for(e.add(t);!e.empty();){const n=e.pop();this.add(n,e)}}copySymDepths(t){const e=t.getSym();e.setDepth(_t.LEFT,t.getDepth(_t.RIGHT)),e.setDepth(_t.RIGHT,t.getDepth(_t.LEFT))}add(t,e){t.setVisited(!0),this._nodes.add(t);for(let n=t.getEdges().iterator();n.hasNext();){const r=n.next();this._dirEdgeList.add(r);const o=r.getSym().getNode();o.isVisited()||e.push(o)}}getNodes(){return this._nodes}getDirectedEdges(){return this._dirEdgeList}get interfaces_(){return[Ei]}}class jp{static intersection(t,e,n,r){const s=t.x<e.x?t.x:e.x,o=t.y<e.y?t.y:e.y,a=t.x>e.x?t.x:e.x,l=t.y>e.y?t.y:e.y,h=n.x<r.x?n.x:r.x,f=n.y<r.y?n.y:r.y,d=n.x>r.x?n.x:r.x,p=n.y>r.y?n.y:r.y,y=s>h?s:h,_=a<d?a:d,E=o>f?o:f,w=l<p?l:p,L=(y+_)/2,b=(E+w)/2,S=t.x-L,P=t.y-b,N=e.x-L,C=e.y-b,T=n.x-L,I=n.y-b,M=r.x-L,R=r.y-b,A=P-C,F=N-S,$=S*C-N*P,U=I-R,D=M-T,B=T*R-M*I,Y=F*B-D*$,X=U*$-A*B,K=A*D-U*F,H=Y/K,et=X/K;return Tt.isNaN(H)||Tt.isInfinite(H)||Tt.isNaN(et)||Tt.isInfinite(et)?null:new Q(H+L,et+b)}}class dn{static segmentToSegment(t,e,n,r){if(t.equals(e))return dn.pointToSegment(t,n,r);if(n.equals(r))return dn.pointToSegment(r,t,e);let s=!1;if(!ne.intersects(t,e,n,r))s=!0;else{const o=(e.x-t.x)*(r.y-n.y)-(e.y-t.y)*(r.x-n.x);if(o===0)s=!0;else{const a=(t.y-n.y)*(r.x-n.x)-(t.x-n.x)*(r.y-n.y),h=((t.y-n.y)*(e.x-t.x)-(t.x-n.x)*(e.y-t.y))/o,f=a/o;(f<0||f>1||h<0||h>1)&&(s=!0)}}return s?Vo.min(dn.pointToSegment(t,n,r),dn.pointToSegment(e,n,r),dn.pointToSegment(n,t,e),dn.pointToSegment(r,t,e)):0}static pointToSegment(t,e,n){if(e.x===n.x&&e.y===n.y)return t.distance(e);const r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),s=((t.x-e.x)*(n.x-e.x)+(t.y-e.y)*(n.y-e.y))/r;if(s<=0)return t.distance(e);if(s>=1)return t.distance(n);const o=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(o)*Math.sqrt(r)}static pointToLinePerpendicular(t,e,n){const r=(n.x-e.x)*(n.x-e.x)+(n.y-e.y)*(n.y-e.y),s=((e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y))/r;return Math.abs(s)*Math.sqrt(r)}static pointToSegmentString(t,e){if(e.length===0)throw new te("Line array must contain at least one vertex");let n=t.distance(e[0]);for(let r=0;r<e.length-1;r++){const s=dn.pointToSegment(t,e[r],e[r+1]);s<n&&(n=s)}return n}}class Ne{constructor(){Ne.constructor_.apply(this,arguments)}static constructor_(){this._result=null,this._inputLines=Array(2).fill().map(()=>Array(2)),this._intPt=new Array(2).fill(null),this._intLineIndex=null,this._isProper=null,this._pa=null,this._pb=null,this._precisionModel=null,this._intPt[0]=new Q,this._intPt[1]=new Q,this._pa=this._intPt[0],this._pb=this._intPt[1],this._result=0}static computeEdgeDistance(t,e,n){const r=Math.abs(n.x-e.x),s=Math.abs(n.y-e.y);let o=-1;if(t.equals(e))o=0;else if(t.equals(n))r>s?o=r:o=s;else{const a=Math.abs(t.x-e.x),l=Math.abs(t.y-e.y);r>s?o=a:o=l,o===0&&!t.equals(e)&&(o=Math.max(a,l))}return Yt.isTrue(!(o===0&&!t.equals(e)),"Bad distance calculation"),o}static nonRobustComputeEdgeDistance(t,e,n){const r=t.x-e.x,s=t.y-e.y,o=Math.sqrt(r*r+s*s);return Yt.isTrue(!(o===0&&!t.equals(e)),"Invalid distance calculation"),o}getIndexAlongSegment(t,e){return this.computeIntLineIndex(),this._intLineIndex[t][e]}getTopologySummary(){const t=new yd;return this.isEndPoint()&&t.append(" endpoint"),this._isProper&&t.append(" proper"),this.isCollinear()&&t.append(" collinear"),t.toString()}computeIntersection(t,e,n,r){this._inputLines[0][0]=t,this._inputLines[0][1]=e,this._inputLines[1][0]=n,this._inputLines[1][1]=r,this._result=this.computeIntersect(t,e,n,r)}getIntersectionNum(){return this._result}computeIntLineIndex(){if(arguments.length===0)this._intLineIndex===null&&(this._intLineIndex=Array(2).fill().map(()=>Array(2)),this.computeIntLineIndex(0),this.computeIntLineIndex(1));else if(arguments.length===1){const t=arguments[0],e=this.getEdgeDistance(t,0),n=this.getEdgeDistance(t,1);e>n?(this._intLineIndex[t][0]=0,this._intLineIndex[t][1]=1):(this._intLineIndex[t][0]=1,this._intLineIndex[t][1]=0)}}isProper(){return this.hasIntersection()&&this._isProper}setPrecisionModel(t){this._precisionModel=t}isInteriorIntersection(){if(arguments.length===0)return!!(this.isInteriorIntersection(0)||this.isInteriorIntersection(1));if(arguments.length===1){const t=arguments[0];for(let e=0;e<this._result;e++)if(!(this._intPt[e].equals2D(this._inputLines[t][0])||this._intPt[e].equals2D(this._inputLines[t][1])))return!0;return!1}}getIntersection(t){return this._intPt[t]}isEndPoint(){return this.hasIntersection()&&!this._isProper}hasIntersection(){return this._result!==Ne.NO_INTERSECTION}getEdgeDistance(t,e){return Ne.computeEdgeDistance(this._intPt[e],this._inputLines[t][0],this._inputLines[t][1])}isCollinear(){return this._result===Ne.COLLINEAR_INTERSECTION}toString(){return rs.toLineString(this._inputLines[0][0],this._inputLines[0][1])+" - "+rs.toLineString(this._inputLines[1][0],this._inputLines[1][1])+this.getTopologySummary()}getEndpoint(t,e){return this._inputLines[t][e]}isIntersection(t){for(let e=0;e<this._result;e++)if(this._intPt[e].equals2D(t))return!0;return!1}getIntersectionAlongSegment(t,e){return this.computeIntLineIndex(),this._intPt[this._intLineIndex[t][e]]}}Ne.DONT_INTERSECT=0;Ne.DO_INTERSECT=1;Ne.COLLINEAR=2;Ne.NO_INTERSECTION=0;Ne.POINT_INTERSECTION=1;Ne.COLLINEAR_INTERSECTION=2;class Pn extends Ne{constructor(){super()}static nearestEndpoint(t,e,n,r){let s=t,o=dn.pointToSegment(t,n,r),a=dn.pointToSegment(e,n,r);return a<o&&(o=a,s=e),a=dn.pointToSegment(n,t,e),a<o&&(o=a,s=n),a=dn.pointToSegment(r,t,e),a<o&&(o=a,s=r),s}isInSegmentEnvelopes(t){const e=new ne(this._inputLines[0][0],this._inputLines[0][1]),n=new ne(this._inputLines[1][0],this._inputLines[1][1]);return e.contains(t)&&n.contains(t)}computeIntersection(){if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2];if(this._isProper=!1,ne.intersects(e,n,t)&&$t.index(e,n,t)===0&&$t.index(n,e,t)===0)return this._isProper=!0,(t.equals(e)||t.equals(n))&&(this._isProper=!1),this._result=Ne.POINT_INTERSECTION,null;this._result=Ne.NO_INTERSECTION}else return super.computeIntersection.apply(this,arguments)}intersection(t,e,n,r){let s=this.intersectionSafe(t,e,n,r);return this.isInSegmentEnvelopes(s)||(s=new Q(Pn.nearestEndpoint(t,e,n,r))),this._precisionModel!==null&&this._precisionModel.makePrecise(s),s}checkDD(t,e,n,r,s){const o=jr.intersection(t,e,n,r),a=this.isInSegmentEnvelopes(o);pi.out.println("DD in env = "+a+" --------------------- "+o),s.distance(o)>1e-4&&pi.out.println("Distance = "+s.distance(o))}intersectionSafe(t,e,n,r){let s=jp.intersection(t,e,n,r);return s===null&&(s=Pn.nearestEndpoint(t,e,n,r)),s}computeCollinearIntersection(t,e,n,r){const s=ne.intersects(t,e,n),o=ne.intersects(t,e,r),a=ne.intersects(n,r,t),l=ne.intersects(n,r,e);return s&&o?(this._intPt[0]=n,this._intPt[1]=r,Ne.COLLINEAR_INTERSECTION):a&&l?(this._intPt[0]=t,this._intPt[1]=e,Ne.COLLINEAR_INTERSECTION):s&&a?(this._intPt[0]=n,this._intPt[1]=t,n.equals(t)&&!o&&!l?Ne.POINT_INTERSECTION:Ne.COLLINEAR_INTERSECTION):s&&l?(this._intPt[0]=n,this._intPt[1]=e,n.equals(e)&&!o&&!a?Ne.POINT_INTERSECTION:Ne.COLLINEAR_INTERSECTION):o&&a?(this._intPt[0]=r,this._intPt[1]=t,r.equals(t)&&!s&&!l?Ne.POINT_INTERSECTION:Ne.COLLINEAR_INTERSECTION):o&&l?(this._intPt[0]=r,this._intPt[1]=e,r.equals(e)&&!s&&!a?Ne.POINT_INTERSECTION:Ne.COLLINEAR_INTERSECTION):Ne.NO_INTERSECTION}computeIntersect(t,e,n,r){if(this._isProper=!1,!ne.intersects(t,e,n,r))return Ne.NO_INTERSECTION;const s=$t.index(t,e,n),o=$t.index(t,e,r);if(s>0&&o>0||s<0&&o<0)return Ne.NO_INTERSECTION;const a=$t.index(n,r,t),l=$t.index(n,r,e);return a>0&&l>0||a<0&&l<0?Ne.NO_INTERSECTION:s===0&&o===0&&a===0&&l===0?this.computeCollinearIntersection(t,e,n,r):(s===0||o===0||a===0||l===0?(this._isProper=!1,t.equals2D(n)||t.equals2D(r)?this._intPt[0]=t:e.equals2D(n)||e.equals2D(r)?this._intPt[0]=e:s===0?this._intPt[0]=new Q(n):o===0?this._intPt[0]=new Q(r):a===0?this._intPt[0]=new Q(t):l===0&&(this._intPt[0]=new Q(e))):(this._isProper=!0,this._intPt[0]=this.intersection(t,e,n,r)),Ne.POINT_INTERSECTION)}}class Xa{constructor(){Xa.constructor_.apply(this,arguments)}static constructor_(){this._p=null,this._crossingCount=0,this._isPointOnSegment=!1;const t=arguments[0];this._p=t}static locatePointInRing(){if(arguments[0]instanceof Q&&At(arguments[1],de)){const t=arguments[0],e=arguments[1],n=new Xa(t),r=new Q,s=new Q;for(let o=1;o<e.size();o++)if(e.getCoordinate(o,r),e.getCoordinate(o-1,s),n.countSegment(r,s),n.isOnSegment())return n.getLocation();return n.getLocation()}else if(arguments[0]instanceof Q&&arguments[1]instanceof Array){const t=arguments[0],e=arguments[1],n=new Xa(t);for(let r=1;r<e.length;r++){const s=e[r],o=e[r-1];if(n.countSegment(s,o),n.isOnSegment())return n.getLocation()}return n.getLocation()}}countSegment(t,e){if(t.x<this._p.x&&e.x<this._p.x)return null;if(this._p.x===e.x&&this._p.y===e.y)return this._isPointOnSegment=!0,null;if(t.y===this._p.y&&e.y===this._p.y){let n=t.x,r=e.x;return n>r&&(n=e.x,r=t.x),this._p.x>=n&&this._p.x<=r&&(this._isPointOnSegment=!0),null}if(t.y>this._p.y&&e.y<=this._p.y||e.y>this._p.y&&t.y<=this._p.y){let n=$t.index(t,e,this._p);if(n===$t.COLLINEAR)return this._isPointOnSegment=!0,null;e.y<t.y&&(n=-n),n===$t.LEFT&&this._crossingCount++}}isPointInPolygon(){return this.getLocation()!==z.EXTERIOR}getLocation(){return this._isPointOnSegment?z.BOUNDARY:this._crossingCount%2===1?z.INTERIOR:z.EXTERIOR}isOnSegment(){return this._isPointOnSegment}}class ar{static isOnLine(){if(arguments[0]instanceof Q&&At(arguments[1],de)){const t=arguments[0],e=arguments[1],n=new Pn,r=new Q,s=new Q,o=e.size();for(let a=1;a<o;a++)if(e.getCoordinate(a-1,r),e.getCoordinate(a,s),n.computeIntersection(t,r,s),n.hasIntersection())return!0;return!1}else if(arguments[0]instanceof Q&&arguments[1]instanceof Array){const t=arguments[0],e=arguments[1],n=new Pn;for(let r=1;r<e.length;r++){const s=e[r-1],o=e[r];if(n.computeIntersection(t,s,o),n.hasIntersection())return!0}return!1}}static locateInRing(t,e){return Xa.locatePointInRing(t,e)}static isInRing(t,e){return ar.locateInRing(t,e)!==z.EXTERIOR}}class Vn{constructor(){Vn.constructor_.apply(this,arguments)}static constructor_(){if(this.location=null,arguments.length===1){if(arguments[0]instanceof Array){const t=arguments[0];this.init(t.length)}else if(Number.isInteger(arguments[0])){const t=arguments[0];this.init(1),this.location[_t.ON]=t}else if(arguments[0]instanceof Vn){const t=arguments[0];if(this.init(t.location.length),t!==null)for(let e=0;e<this.location.length;e++)this.location[e]=t.location[e]}}else if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2];this.init(3),this.location[_t.ON]=t,this.location[_t.LEFT]=e,this.location[_t.RIGHT]=n}}setAllLocations(t){for(let e=0;e<this.location.length;e++)this.location[e]=t}isNull(){for(let t=0;t<this.location.length;t++)if(this.location[t]!==z.NONE)return!1;return!0}setAllLocationsIfNull(t){for(let e=0;e<this.location.length;e++)this.location[e]===z.NONE&&(this.location[e]=t)}isLine(){return this.location.length===1}merge(t){if(t.location.length>this.location.length){const e=new Array(3).fill(null);e[_t.ON]=this.location[_t.ON],e[_t.LEFT]=z.NONE,e[_t.RIGHT]=z.NONE,this.location=e}for(let e=0;e<this.location.length;e++)this.location[e]===z.NONE&&e<t.location.length&&(this.location[e]=t.location[e])}getLocations(){return this.location}flip(){if(this.location.length<=1)return null;const t=this.location[_t.LEFT];this.location[_t.LEFT]=this.location[_t.RIGHT],this.location[_t.RIGHT]=t}toString(){const t=new Zu;return this.location.length>1&&t.append(z.toLocationSymbol(this.location[_t.LEFT])),t.append(z.toLocationSymbol(this.location[_t.ON])),this.location.length>1&&t.append(z.toLocationSymbol(this.location[_t.RIGHT])),t.toString()}setLocations(t,e,n){this.location[_t.ON]=t,this.location[_t.LEFT]=e,this.location[_t.RIGHT]=n}get(t){return t<this.location.length?this.location[t]:z.NONE}isArea(){return this.location.length>1}isAnyNull(){for(let t=0;t<this.location.length;t++)if(this.location[t]===z.NONE)return!0;return!1}setLocation(){if(arguments.length===1){const t=arguments[0];this.setLocation(_t.ON,t)}else if(arguments.length===2){const t=arguments[0],e=arguments[1];this.location[t]=e}}init(t){this.location=new Array(t).fill(null),this.setAllLocations(z.NONE)}isEqualOnSide(t,e){return this.location[e]===t.location[e]}allPositionsEqual(t){for(let e=0;e<this.location.length;e++)if(this.location[e]!==t)return!1;return!0}}class Ge{constructor(){Ge.constructor_.apply(this,arguments)}static constructor_(){if(this.elt=new Array(2).fill(null),arguments.length===1){if(Number.isInteger(arguments[0])){const t=arguments[0];this.elt[0]=new Vn(t),this.elt[1]=new Vn(t)}else if(arguments[0]instanceof Ge){const t=arguments[0];this.elt[0]=new Vn(t.elt[0]),this.elt[1]=new Vn(t.elt[1])}}else if(arguments.length===2){const t=arguments[0],e=arguments[1];this.elt[0]=new Vn(z.NONE),this.elt[1]=new Vn(z.NONE),this.elt[t].setLocation(e)}else if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2];this.elt[0]=new Vn(t,e,n),this.elt[1]=new Vn(t,e,n)}else if(arguments.length===4){const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];this.elt[0]=new Vn(z.NONE,z.NONE,z.NONE),this.elt[1]=new Vn(z.NONE,z.NONE,z.NONE),this.elt[t].setLocations(e,n,r)}}static toLineLabel(t){const e=new Ge(z.NONE);for(let n=0;n<2;n++)e.setLocation(n,t.getLocation(n));return e}getGeometryCount(){let t=0;return this.elt[0].isNull()||t++,this.elt[1].isNull()||t++,t}setAllLocations(t,e){this.elt[t].setAllLocations(e)}isNull(t){return this.elt[t].isNull()}setAllLocationsIfNull(){if(arguments.length===1){const t=arguments[0];this.setAllLocationsIfNull(0,t),this.setAllLocationsIfNull(1,t)}else if(arguments.length===2){const t=arguments[0],e=arguments[1];this.elt[t].setAllLocationsIfNull(e)}}isLine(t){return this.elt[t].isLine()}merge(t){for(let e=0;e<2;e++)this.elt[e]===null&&t.elt[e]!==null?this.elt[e]=new Vn(t.elt[e]):this.elt[e].merge(t.elt[e])}flip(){this.elt[0].flip(),this.elt[1].flip()}getLocation(){if(arguments.length===1){const t=arguments[0];return this.elt[t].get(_t.ON)}else if(arguments.length===2){const t=arguments[0],e=arguments[1];return this.elt[t].get(e)}}toString(){const t=new Zu;return this.elt[0]!==null&&(t.append("A:"),t.append(this.elt[0].toString())),this.elt[1]!==null&&(t.append(" B:"),t.append(this.elt[1].toString())),t.toString()}isArea(){if(arguments.length===0)return this.elt[0].isArea()||this.elt[1].isArea();if(arguments.length===1){const t=arguments[0];return this.elt[t].isArea()}}isAnyNull(t){return this.elt[t].isAnyNull()}setLocation(){if(arguments.length===2){const t=arguments[0],e=arguments[1];this.elt[t].setLocation(_t.ON,e)}else if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2];this.elt[t].setLocation(e,n)}}isEqualOnSide(t,e){return this.elt[0].isEqualOnSide(t.elt[0],e)&&this.elt[1].isEqualOnSide(t.elt[1],e)}allPositionsEqual(t,e){return this.elt[t].allPositionsEqual(e)}toLine(t){this.elt[t].isArea()&&(this.elt[t]=new Vn(this.elt[t].location[0]))}}class vl{constructor(){vl.constructor_.apply(this,arguments)}static constructor_(){if(this._startDe=null,this._maxNodeDegree=-1,this._edges=new wt,this._pts=new wt,this._label=new Ge(z.NONE),this._ring=null,this._isHole=null,this._shell=null,this._holes=new wt,this._geometryFactory=null,arguments.length!==0){if(arguments.length===2){const t=arguments[0],e=arguments[1];this._geometryFactory=e,this.computePoints(t),this.computeRing()}}}computeRing(){if(this._ring!==null)return null;const t=new Array(this._pts.size()).fill(null);for(let e=0;e<this._pts.size();e++)t[e]=this._pts.get(e);this._ring=this._geometryFactory.createLinearRing(t),this._isHole=$t.isCCW(this._ring.getCoordinates())}isIsolated(){return this._label.getGeometryCount()===1}computePoints(t){this._startDe=t;let e=t,n=!0;do{if(e===null)throw new Fi("Found null DirectedEdge");if(e.getEdgeRing()===this)throw new Fi("Directed Edge visited twice during ring-building at "+e.getCoordinate());this._edges.add(e);const r=e.getLabel();Yt.isTrue(r.isArea()),this.mergeLabel(r),this.addPoints(e.getEdge(),e.isForward(),n),n=!1,this.setEdgeRing(e,this),e=this.getNext(e)}while(e!==this._startDe)}getLinearRing(){return this._ring}getCoordinate(t){return this._pts.get(t)}computeMaxNodeDegree(){this._maxNodeDegree=0;let t=this._startDe;do{const n=t.getNode().getEdges().getOutgoingDegree(this);n>this._maxNodeDegree&&(this._maxNodeDegree=n),t=this.getNext(t)}while(t!==this._startDe);this._maxNodeDegree*=2}addPoints(t,e,n){const r=t.getCoordinates();if(e){let s=1;n&&(s=0);for(let o=s;o<r.length;o++)this._pts.add(r[o])}else{let s=r.length-2;n&&(s=r.length-1);for(let o=s;o>=0;o--)this._pts.add(r[o])}}isHole(){return this._isHole}setInResult(){let t=this._startDe;do t.getEdge().setInResult(!0),t=t.getNext();while(t!==this._startDe)}containsPoint(t){const e=this.getLinearRing();if(!e.getEnvelopeInternal().contains(t)||!ar.isInRing(t,e.getCoordinates()))return!1;for(let r=this._holes.iterator();r.hasNext();)if(r.next().containsPoint(t))return!1;return!0}addHole(t){this._holes.add(t)}isShell(){return this._shell===null}getLabel(){return this._label}getEdges(){return this._edges}getMaxNodeDegree(){return this._maxNodeDegree<0&&this.computeMaxNodeDegree(),this._maxNodeDegree}getShell(){return this._shell}mergeLabel(){if(arguments.length===1){const t=arguments[0];this.mergeLabel(t,0),this.mergeLabel(t,1)}else if(arguments.length===2){const t=arguments[0],e=arguments[1],n=t.getLocation(e,_t.RIGHT);if(n===z.NONE)return null;if(this._label.getLocation(e)===z.NONE)return this._label.setLocation(e,n),null}}setShell(t){this._shell=t,t!==null&&t.addHole(this)}toPolygon(t){const e=new Array(this._holes.size()).fill(null);for(let r=0;r<this._holes.size();r++)e[r]=this._holes.get(r).getLinearRing();return t.createPolygon(this.getLinearRing(),e)}}class Xp extends vl{constructor(){super(),Xp.constructor_.apply(this,arguments)}static constructor_(){const t=arguments[0],e=arguments[1];vl.constructor_.call(this,t,e)}setEdgeRing(t,e){t.setMinEdgeRing(e)}getNext(t){return t.getNextMin()}}class vd extends vl{constructor(){super(),vd.constructor_.apply(this,arguments)}static constructor_(){const t=arguments[0],e=arguments[1];vl.constructor_.call(this,t,e)}buildMinimalRings(){const t=new wt;let e=this._startDe;do{if(e.getMinEdgeRing()===null){const n=new Xp(e,this._geometryFactory);t.add(n)}e=e.getNext()}while(e!==this._startDe);return t}setEdgeRing(t,e){t.setEdgeRing(e)}linkDirectedEdgesForMinimalEdgeRings(){let t=this._startDe;do t.getNode().getEdges().linkMinimalDirectedEdges(this),t=t.getNext();while(t!==this._startDe)}getNext(t){return t.getNext()}}class Ed{constructor(){Ed.constructor_.apply(this,arguments)}static constructor_(){if(this._label=null,this._isInResult=!1,this._isCovered=!1,this._isCoveredSet=!1,this._isVisited=!1,arguments.length!==0){if(arguments.length===1){const t=arguments[0];this._label=t}}}setVisited(t){this._isVisited=t}setInResult(t){this._isInResult=t}isCovered(){return this._isCovered}isCoveredSet(){return this._isCoveredSet}setLabel(t){this._label=t}getLabel(){return this._label}setCovered(t){this._isCovered=t,this._isCoveredSet=!0}updateIM(t){Yt.isTrue(this._label.getGeometryCount()>=2,"found partial label"),this.computeIM(t)}isInResult(){return this._isInResult}isVisited(){return this._isVisited}}class bs extends Ed{constructor(){super(),bs.constructor_.apply(this,arguments)}static constructor_(){this._coord=null,this._edges=null;const t=arguments[0],e=arguments[1];this._coord=t,this._edges=e,this._label=new Ge(0,z.NONE)}isIncidentEdgeInResult(){for(let t=this.getEdges().getEdges().iterator();t.hasNext();)if(t.next().getEdge().isInResult())return!0;return!1}isIsolated(){return this._label.getGeometryCount()===1}getCoordinate(){return this._coord}print(t){t.println("node "+this._coord+" lbl: "+this._label)}computeIM(t){}computeMergedLocation(t,e){let n=z.NONE;if(n=this._label.getLocation(e),!t.isNull(e)){const r=t.getLocation(e);n!==z.BOUNDARY&&(n=r)}return n}setLabel(){if(arguments.length===2&&Number.isInteger(arguments[1])&&Number.isInteger(arguments[0])){const t=arguments[0],e=arguments[1];this._label===null?this._label=new Ge(t,e):this._label.setLocation(t,e)}else return super.setLabel.apply(this,arguments)}getEdges(){return this._edges}mergeLabel(){if(arguments[0]instanceof bs){const t=arguments[0];this.mergeLabel(t._label)}else if(arguments[0]instanceof Ge){const t=arguments[0];for(let e=0;e<2;e++){const n=this.computeMergedLocation(t,e);this._label.getLocation(e)===z.NONE&&this._label.setLocation(e,n)}}}add(t){this._edges.insert(t),t.setNode(this)}setLabelBoundary(t){if(this._label===null)return null;let e=z.NONE;this._label!==null&&(e=this._label.getLocation(t));let n=null;switch(e){case z.BOUNDARY:n=z.INTERIOR;break;case z.INTERIOR:n=z.BOUNDARY;break;default:n=z.BOUNDARY;break}this._label.setLocation(t,n)}}class t8 extends Gx{}const Gr=0,Rs=1;function yv(i){return i==null?Gr:i.color}function Ee(i){return i==null?null:i.parent}function Dr(i,t){i!==null&&(i.color=t)}function Vg(i){return i==null?null:i.left}function _v(i){return i==null?null:i.right}class ss extends t8{constructor(){super(),this.root_=null,this.size_=0}get(t){let e=this.root_;for(;e!==null;){const n=t.compareTo(e.key);if(n<0)e=e.left;else if(n>0)e=e.right;else return e.value}return null}put(t,e){if(this.root_===null)return this.root_={key:t,value:e,left:null,right:null,parent:null,color:Gr,getValue(){return this.value},getKey(){return this.key}},this.size_=1,null;let n=this.root_,r,s;do if(r=n,s=t.compareTo(n.key),s<0)n=n.left;else if(s>0)n=n.right;else{const a=n.value;return n.value=e,a}while(n!==null);const o={key:t,left:null,right:null,value:e,parent:r,color:Gr,getValue(){return this.value},getKey(){return this.key}};return s<0?r.left=o:r.right=o,this.fixAfterInsertion(o),this.size_++,null}fixAfterInsertion(t){let e;for(t.color=Rs;t!=null&&t!==this.root_&&t.parent.color===Rs;)Ee(t)===Vg(Ee(Ee(t)))?(e=_v(Ee(Ee(t))),yv(e)===Rs?(Dr(Ee(t),Gr),Dr(e,Gr),Dr(Ee(Ee(t)),Rs),t=Ee(Ee(t))):(t===_v(Ee(t))&&(t=Ee(t),this.rotateLeft(t)),Dr(Ee(t),Gr),Dr(Ee(Ee(t)),Rs),this.rotateRight(Ee(Ee(t))))):(e=Vg(Ee(Ee(t))),yv(e)===Rs?(Dr(Ee(t),Gr),Dr(e,Gr),Dr(Ee(Ee(t)),Rs),t=Ee(Ee(t))):(t===Vg(Ee(t))&&(t=Ee(t),this.rotateRight(t)),Dr(Ee(t),Gr),Dr(Ee(Ee(t)),Rs),this.rotateLeft(Ee(Ee(t)))));this.root_.color=Gr}values(){const t=new wt;let e=this.getFirstEntry();if(e!==null)for(t.add(e.value);(e=ss.successor(e))!==null;)t.add(e.value);return t}entrySet(){const t=new Rc;let e=this.getFirstEntry();if(e!==null)for(t.add(e);(e=ss.successor(e))!==null;)t.add(e);return t}rotateLeft(t){if(t!=null){const e=t.right;t.right=e.left,e.left!=null&&(e.left.parent=t),e.parent=t.parent,t.parent==null?this.root_=e:t.parent.left===t?t.parent.left=e:t.parent.right=e,e.left=t,t.parent=e}}rotateRight(t){if(t!=null){const e=t.left;t.left=e.right,e.right!=null&&(e.right.parent=t),e.parent=t.parent,t.parent==null?this.root_=e:t.parent.right===t?t.parent.right=e:t.parent.left=e,e.right=t,t.parent=e}}getFirstEntry(){let t=this.root_;if(t!=null)for(;t.left!=null;)t=t.left;return t}static successor(t){let e;if(t===null)return null;if(t.right!==null){for(e=t.right;e.left!==null;)e=e.left;return e}else{e=t.parent;let n=t;for(;e!==null&&n===e.right;)n=e,e=e.parent;return e}}size(){return this.size_}containsKey(t){let e=this.root_;for(;e!==null;){const n=t.compareTo(e.key);if(n<0)e=e.left;else if(n>0)e=e.right;else return!0}return!1}}class El{constructor(){El.constructor_.apply(this,arguments)}static constructor_(){this.nodeMap=new ss,this.nodeFact=null;const t=arguments[0];this.nodeFact=t}find(t){return this.nodeMap.get(t)}addNode(){if(arguments[0]instanceof Q){const t=arguments[0];let e=this.nodeMap.get(t);return e===null&&(e=this.nodeFact.createNode(t),this.nodeMap.put(t,e)),e}else if(arguments[0]instanceof bs){const t=arguments[0],e=this.nodeMap.get(t.getCoordinate());return e===null?(this.nodeMap.put(t.getCoordinate(),t),t):(e.mergeLabel(t),e)}}print(t){for(let e=this.iterator();e.hasNext();)e.next().print(t)}iterator(){return this.nodeMap.values().iterator()}values(){return this.nodeMap.values()}getBoundaryNodes(t){const e=new wt;for(let n=this.iterator();n.hasNext();){const r=n.next();r.getLabel().getLocation(t)===z.BOUNDARY&&e.add(r)}return e}add(t){const e=t.getCoordinate();this.addNode(e).add(t)}}class Le{static isNorthern(t){return t===Le.NE||t===Le.NW}static isOpposite(t,e){return t===e?!1:(t-e+4)%4===2}static commonHalfPlane(t,e){if(t===e)return t;if((t-e+4)%4===2)return-1;const r=t<e?t:e,s=t>e?t:e;return r===0&&s===3?3:r}static isInHalfPlane(t,e){return e===Le.SE?t===Le.SE||t===Le.SW:t===e||t===e+1}static quadrant(){if(typeof arguments[0]=="number"&&typeof arguments[1]=="number"){const t=arguments[0],e=arguments[1];if(t===0&&e===0)throw new te("Cannot compute the quadrant for point ( "+t+", "+e+" )");return t>=0?e>=0?Le.NE:Le.SE:e>=0?Le.NW:Le.SW}else if(arguments[0]instanceof Q&&arguments[1]instanceof Q){const t=arguments[0],e=arguments[1];if(e.x===t.x&&e.y===t.y)throw new te("Cannot compute the quadrant for two identical points "+t);return e.x>=t.x?e.y>=t.y?Le.NE:Le.SE:e.y>=t.y?Le.NW:Le.SW}}}Le.NE=0;Le.NW=1;Le.SW=2;Le.SE=3;class Jr{constructor(){Jr.constructor_.apply(this,arguments)}static constructor_(){if(this._edge=null,this._label=null,this._node=null,this._p0=null,this._p1=null,this._dx=null,this._dy=null,this._quadrant=null,arguments.length===1){const t=arguments[0];this._edge=t}else if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2];Jr.constructor_.call(this,t,e,n,null)}else if(arguments.length===4){const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];Jr.constructor_.call(this,t),this.init(e,n),this._label=r}}compareDirection(t){return this._dx===t._dx&&this._dy===t._dy?0:this._quadrant>t._quadrant?1:this._quadrant<t._quadrant?-1:$t.index(t._p0,t._p1,this._p1)}getDy(){return this._dy}getCoordinate(){return this._p0}setNode(t){this._node=t}print(t){const e=Math.atan2(this._dy,this._dx),n=this.getClass().getName(),r=n.lastIndexOf("."),s=n.substring(r+1);t.print(" "+s+": "+this._p0+" - "+this._p1+" "+this._quadrant+":"+e+" "+this._label)}compareTo(t){const e=t;return this.compareDirection(e)}getDirectedCoordinate(){return this._p1}getDx(){return this._dx}getLabel(){return this._label}getEdge(){return this._edge}getQuadrant(){return this._quadrant}getNode(){return this._node}toString(){const t=Math.atan2(this._dy,this._dx),e=this.getClass().getName(),n=e.lastIndexOf(".");return" "+e.substring(n+1)+": "+this._p0+" - "+this._p1+" "+this._quadrant+":"+t+" "+this._label}computeLabel(t){}init(t,e){this._p0=t,this._p1=e,this._dx=e.x-t.x,this._dy=e.y-t.y,this._quadrant=Le.quadrant(this._dx,this._dy),Yt.isTrue(!(this._dx===0&&this._dy===0),"EdgeEnd with identical endpoints found")}get interfaces_(){return[Ei]}}class Qu extends Jr{constructor(){super(),Qu.constructor_.apply(this,arguments)}static constructor_(){this._isForward=null,this._isInResult=!1,this._isVisited=!1,this._sym=null,this._next=null,this._nextMin=null,this._edgeRing=null,this._minEdgeRing=null,this._depth=[0,-999,-999];const t=arguments[0],e=arguments[1];if(Jr.constructor_.call(this,t),this._isForward=e,e)this.init(t.getCoordinate(0),t.getCoordinate(1));else{const n=t.getNumPoints()-1;this.init(t.getCoordinate(n),t.getCoordinate(n-1))}this.computeDirectedLabel()}static depthFactor(t,e){return t===z.EXTERIOR&&e===z.INTERIOR?1:t===z.INTERIOR&&e===z.EXTERIOR?-1:0}getNextMin(){return this._nextMin}getDepth(t){return this._depth[t]}setVisited(t){this._isVisited=t}computeDirectedLabel(){this._label=new Ge(this._edge.getLabel()),this._isForward||this._label.flip()}getNext(){return this._next}setDepth(t,e){if(this._depth[t]!==-999&&this._depth[t]!==e)throw new Fi("assigned depths do not match",this.getCoordinate());this._depth[t]=e}isInteriorAreaEdge(){let t=!0;for(let e=0;e<2;e++)this._label.isArea(e)&&this._label.getLocation(e,_t.LEFT)===z.INTERIOR&&this._label.getLocation(e,_t.RIGHT)===z.INTERIOR||(t=!1);return t}setNextMin(t){this._nextMin=t}print(t){super.print.call(this,t),t.print(" "+this._depth[_t.LEFT]+"/"+this._depth[_t.RIGHT]),t.print(" ("+this.getDepthDelta()+")"),this._isInResult&&t.print(" inResult")}setMinEdgeRing(t){this._minEdgeRing=t}isLineEdge(){const t=this._label.isLine(0)||this._label.isLine(1),e=!this._label.isArea(0)||this._label.allPositionsEqual(0,z.EXTERIOR),n=!this._label.isArea(1)||this._label.allPositionsEqual(1,z.EXTERIOR);return t&&e&&n}setEdgeRing(t){this._edgeRing=t}getMinEdgeRing(){return this._minEdgeRing}getDepthDelta(){let t=this._edge.getDepthDelta();return this._isForward||(t=-t),t}setInResult(t){this._isInResult=t}getSym(){return this._sym}isForward(){return this._isForward}getEdge(){return this._edge}printEdge(t){this.print(t),t.print(" "),this._isForward?this._edge.print(t):this._edge.printReverse(t)}setSym(t){this._sym=t}setVisitedEdge(t){this.setVisited(t),this._sym.setVisited(t)}setEdgeDepths(t,e){let n=this.getEdge().getDepthDelta();this._isForward||(n=-n);let r=1;t===_t.LEFT&&(r=-1);const s=_t.opposite(t),o=n*r,a=e+o;this.setDepth(t,e),this.setDepth(s,a)}getEdgeRing(){return this._edgeRing}isInResult(){return this._isInResult}setNext(t){this._next=t}isVisited(){return this._isVisited}}class Vp{createNode(t){return new bs(t,null)}}class Jo{constructor(){Jo.constructor_.apply(this,arguments)}static constructor_(){if(this._edges=new wt,this._nodes=null,this._edgeEndList=new wt,arguments.length===0)this._nodes=new El(new Vp);else if(arguments.length===1){const t=arguments[0];this._nodes=new El(t)}}static linkResultDirectedEdges(t){for(let e=t.iterator();e.hasNext();)e.next().getEdges().linkResultDirectedEdges()}printEdges(t){t.println("Edges:");for(let e=0;e<this._edges.size();e++){t.println("edge "+e+":");const n=this._edges.get(e);n.print(t),n.eiList.print(t)}}find(t){return this._nodes.find(t)}addNode(){if(arguments[0]instanceof bs){const t=arguments[0];return this._nodes.addNode(t)}else if(arguments[0]instanceof Q){const t=arguments[0];return this._nodes.addNode(t)}}getNodeIterator(){return this._nodes.iterator()}linkResultDirectedEdges(){for(let t=this._nodes.iterator();t.hasNext();)t.next().getEdges().linkResultDirectedEdges()}debugPrintln(t){pi.out.println(t)}isBoundaryNode(t,e){const n=this._nodes.find(e);if(n===null)return!1;const r=n.getLabel();return r!==null&&r.getLocation(t)===z.BOUNDARY}linkAllDirectedEdges(){for(let t=this._nodes.iterator();t.hasNext();)t.next().getEdges().linkAllDirectedEdges()}matchInSameDirection(t,e,n,r){return t.equals(n)?$t.index(t,e,r)===$t.COLLINEAR&&Le.quadrant(t,e)===Le.quadrant(n,r):!1}getEdgeEnds(){return this._edgeEndList}debugPrint(t){pi.out.print(t)}getEdgeIterator(){return this._edges.iterator()}findEdgeInSameDirection(t,e){for(let n=0;n<this._edges.size();n++){const r=this._edges.get(n),s=r.getCoordinates();if(this.matchInSameDirection(t,e,s[0],s[1])||this.matchInSameDirection(t,e,s[s.length-1],s[s.length-2]))return r}return null}insertEdge(t){this._edges.add(t)}findEdgeEnd(t){for(let e=this.getEdgeEnds().iterator();e.hasNext();){const n=e.next();if(n.getEdge()===t)return n}return null}addEdges(t){for(let e=t.iterator();e.hasNext();){const n=e.next();this._edges.add(n);const r=new Qu(n,!0),s=new Qu(n,!1);r.setSym(s),s.setSym(r),this.add(r),this.add(s)}}add(t){this._nodes.add(t),this._edgeEndList.add(t)}getNodes(){return this._nodes.values()}findEdge(t,e){for(let n=0;n<this._edges.size();n++){const r=this._edges.get(n),s=r.getCoordinates();if(t.equals(s[0])&&e.equals(s[1]))return r}return null}}class tc{constructor(){tc.constructor_.apply(this,arguments)}static constructor_(){this._geometryFactory=null,this._shellList=new wt;const t=arguments[0];this._geometryFactory=t}static findEdgeRingContaining(t,e){const n=t.getLinearRing(),r=n.getEnvelopeInternal();let s=n.getCoordinateN(0),o=null,a=null;for(let l=e.iterator();l.hasNext();){const h=l.next(),f=h.getLinearRing(),d=f.getEnvelopeInternal();if(d.equals(r)||!d.contains(r))continue;s=Ce.ptNotInList(n.getCoordinates(),f.getCoordinates());let p=!1;ar.isInRing(s,f.getCoordinates())&&(p=!0),p&&(o===null||a.contains(d))&&(o=h,a=o.getLinearRing().getEnvelopeInternal())}return o}sortShellsAndHoles(t,e,n){for(let r=t.iterator();r.hasNext();){const s=r.next();s.isHole()?n.add(s):e.add(s)}}computePolygons(t){const e=new wt;for(let n=t.iterator();n.hasNext();){const s=n.next().toPolygon(this._geometryFactory);e.add(s)}return e}placeFreeHoles(t,e){for(let n=e.iterator();n.hasNext();){const r=n.next();if(r.getShell()===null){const s=tc.findEdgeRingContaining(r,t);if(s===null)throw new Fi("unable to assign hole to a shell",r.getCoordinate(0));r.setShell(s)}}}buildMinimalEdgeRings(t,e,n){const r=new wt;for(let s=t.iterator();s.hasNext();){const o=s.next();if(o.getMaxNodeDegree()>2){o.linkDirectedEdgesForMinimalEdgeRings();const a=o.buildMinimalRings(),l=this.findShell(a);l!==null?(this.placePolygonHoles(l,a),e.add(l)):n.addAll(a)}else r.add(o)}return r}buildMaximalEdgeRings(t){const e=new wt;for(let n=t.iterator();n.hasNext();){const r=n.next();if(r.isInResult()&&r.getLabel().isArea()&&r.getEdgeRing()===null){const s=new vd(r,this._geometryFactory);e.add(s),s.setInResult()}}return e}placePolygonHoles(t,e){for(let n=e.iterator();n.hasNext();){const r=n.next();r.isHole()&&r.setShell(t)}}getPolygons(){return this.computePolygons(this._shellList)}findShell(t){let e=0,n=null;for(let r=t.iterator();r.hasNext();){const s=r.next();s.isHole()||(n=s,e++)}return Yt.isTrue(e<=1,"found two shells in MinimalEdgeRing list"),n}add(){if(arguments.length===1){const t=arguments[0];this.add(t.getEdgeEnds(),t.getNodes())}else if(arguments.length===2){const t=arguments[0],e=arguments[1];Jo.linkResultDirectedEdges(e);const n=this.buildMaximalEdgeRings(t),r=new wt,s=this.buildMinimalEdgeRings(n,this._shellList,r);this.sortShellsAndHoles(s,this._shellList,r),this.placeFreeHoles(this._shellList,r)}}}class Kx{getBounds(){}}class vr{constructor(){vr.constructor_.apply(this,arguments)}static constructor_(){this._bounds=null,this._item=null;const t=arguments[0],e=arguments[1];this._bounds=t,this._item=e}getItem(){return this._item}getBounds(){return this._bounds}get interfaces_(){return[Kx,wi]}}class $a{constructor(){$a.constructor_.apply(this,arguments)}static constructor_(){this._size=null,this._items=null,this._size=0,this._items=new wt,this._items.add(null)}poll(){if(this.isEmpty())return null;const t=this._items.get(1);return this._items.set(1,this._items.get(this._size)),this._size-=1,this.reorder(1),t}size(){return this._size}reorder(t){let e=null;const n=this._items.get(t);for(;t*2<=this._size&&(e=t*2,e!==this._size&&this._items.get(e+1).compareTo(this._items.get(e))<0&&e++,this._items.get(e).compareTo(n)<0);t=e)this._items.set(t,this._items.get(e));this._items.set(t,n)}clear(){this._size=0,this._items.clear()}peek(){return this.isEmpty()?null:this._items.get(1)}isEmpty(){return this._size===0}add(t){this._items.add(null),this._size+=1;let e=this._size;for(this._items.set(0,t);t.compareTo(this._items.get(Math.trunc(e/2)))<0;e/=2)this._items.set(e,this._items.get(Math.trunc(e/2)));this._items.set(e,t)}}class e8{insert(t,e){}remove(t,e){}query(){}}class ui{constructor(){ui.constructor_.apply(this,arguments)}static constructor_(){if(this._childBoundables=new wt,this._bounds=null,this._level=null,arguments.length!==0){if(arguments.length===1){const t=arguments[0];this._level=t}}}getLevel(){return this._level}size(){return this._childBoundables.size()}getChildBoundables(){return this._childBoundables}addChildBoundable(t){Yt.isTrue(this._bounds===null),this._childBoundables.add(t)}isEmpty(){return this._childBoundables.isEmpty()}getBounds(){return this._bounds===null&&(this._bounds=this.computeBounds()),this._bounds}get interfaces_(){return[Kx,wi]}}const Is={reverseOrder:function(){return{compare(i,t){return t.compareTo(i)}}},min:function(i){return Is.sort(i),i.get(0)},sort:function(i,t){const e=i.toArray();t?Ys.sort(e,t):Ys.sort(e);const n=i.iterator();for(let r=0,s=e.length;r<s;r++)n.next(),n.set(e[r])},singletonList:function(i){const t=new wt;return t.add(i),t}};class We{static maxDistance(t,e,n,r,s,o,a,l){let h=We.distance(t,e,s,o);return h=Math.max(h,We.distance(t,e,a,l)),h=Math.max(h,We.distance(n,r,s,o)),h=Math.max(h,We.distance(n,r,a,l)),h}static distance(t,e,n,r){const s=n-t,o=r-e;return Math.sqrt(s*s+o*o)}static maximumDistance(t,e){const n=Math.min(t.getMinX(),e.getMinX()),r=Math.min(t.getMinY(),e.getMinY()),s=Math.max(t.getMaxX(),e.getMaxX()),o=Math.max(t.getMaxY(),e.getMaxY());return We.distance(n,r,s,o)}static minMaxDistance(t,e){const n=t.getMinX(),r=t.getMinY(),s=t.getMaxX(),o=t.getMaxY(),a=e.getMinX(),l=e.getMinY(),h=e.getMaxX(),f=e.getMaxY();let d=We.maxDistance(n,r,n,o,a,l,a,f);return d=Math.min(d,We.maxDistance(n,r,n,o,a,l,h,l)),d=Math.min(d,We.maxDistance(n,r,n,o,h,f,a,f)),d=Math.min(d,We.maxDistance(n,r,n,o,h,f,h,l)),d=Math.min(d,We.maxDistance(n,r,s,r,a,l,a,f)),d=Math.min(d,We.maxDistance(n,r,s,r,a,l,h,l)),d=Math.min(d,We.maxDistance(n,r,s,r,h,f,a,f)),d=Math.min(d,We.maxDistance(n,r,s,r,h,f,h,l)),d=Math.min(d,We.maxDistance(s,o,n,o,a,l,a,f)),d=Math.min(d,We.maxDistance(s,o,n,o,a,l,h,l)),d=Math.min(d,We.maxDistance(s,o,n,o,h,f,a,f)),d=Math.min(d,We.maxDistance(s,o,n,o,h,f,h,l)),d=Math.min(d,We.maxDistance(s,o,s,r,a,l,a,f)),d=Math.min(d,We.maxDistance(s,o,s,r,a,l,h,l)),d=Math.min(d,We.maxDistance(s,o,s,r,h,f,a,f)),d=Math.min(d,We.maxDistance(s,o,s,r,h,f,h,l)),d}}class Fn{constructor(){Fn.constructor_.apply(this,arguments)}static constructor_(){this._boundable1=null,this._boundable2=null,this._distance=null,this._itemDistance=null;const t=arguments[0],e=arguments[1],n=arguments[2];this._boundable1=t,this._boundable2=e,this._itemDistance=n,this._distance=this.distance()}static area(t){return t.getBounds().getArea()}static isComposite(t){return t instanceof ui}maximumDistance(){return We.maximumDistance(this._boundable1.getBounds(),this._boundable2.getBounds())}expandToQueue(t,e){const n=Fn.isComposite(this._boundable1),r=Fn.isComposite(this._boundable2);if(n&&r)return Fn.area(this._boundable1)>Fn.area(this._boundable2)?(this.expand(this._boundable1,this._boundable2,!1,t,e),null):(this.expand(this._boundable2,this._boundable1,!0,t,e),null);if(n)return this.expand(this._boundable1,this._boundable2,!1,t,e),null;if(r)return this.expand(this._boundable2,this._boundable1,!0,t,e),null;throw new te("neither boundable is composite")}isLeaves(){return!(Fn.isComposite(this._boundable1)||Fn.isComposite(this._boundable2))}compareTo(t){const e=t;return this._distance<e._distance?-1:this._distance>e._distance?1:0}expand(t,e,n,r,s){const o=t.getChildBoundables();for(let a=o.iterator();a.hasNext();){const l=a.next();let h=null;n?h=new Fn(e,l,this._itemDistance):h=new Fn(l,e,this._itemDistance),h.getDistance()<s&&r.add(h)}}getBoundable(t){return t===0?this._boundable1:this._boundable2}getDistance(){return this._distance}distance(){return this.isLeaves()?this._itemDistance.distance(this._boundable1,this._boundable2):this._boundable1.getBounds().distance(this._boundable2.getBounds())}get interfaces_(){return[Ei]}}class wd{visitItem(t){}}class Qr{constructor(){Qr.constructor_.apply(this,arguments)}static constructor_(){if(this._root=null,this._built=!1,this._itemBoundables=new wt,this._nodeCapacity=null,arguments.length===0)Qr.constructor_.call(this,Qr.DEFAULT_NODE_CAPACITY);else if(arguments.length===1){const t=arguments[0];Yt.isTrue(t>1,"Node capacity must be greater than 1"),this._nodeCapacity=t}}static compareDoubles(t,e){return t>e?1:t<e?-1:0}queryInternal(){if(At(arguments[2],wd)&&arguments[0]instanceof Object&&arguments[1]instanceof ui){const t=arguments[0],e=arguments[1],n=arguments[2],r=e.getChildBoundables();for(let s=0;s<r.size();s++){const o=r.get(s);this.getIntersectsOp().intersects(o.getBounds(),t)&&(o instanceof ui?this.queryInternal(t,o,n):o instanceof vr?n.visitItem(o.getItem()):Yt.shouldNeverReachHere())}}else if(At(arguments[2],Oi)&&arguments[0]instanceof Object&&arguments[1]instanceof ui){const t=arguments[0],e=arguments[1],n=arguments[2],r=e.getChildBoundables();for(let s=0;s<r.size();s++){const o=r.get(s);this.getIntersectsOp().intersects(o.getBounds(),t)&&(o instanceof ui?this.queryInternal(t,o,n):o instanceof vr?n.add(o.getItem()):Yt.shouldNeverReachHere())}}}getNodeCapacity(){return this._nodeCapacity}lastNode(t){return t.get(t.size()-1)}size(){if(arguments.length===0)return this.isEmpty()?0:(this.build(),this.size(this._root));if(arguments.length===1){const t=arguments[0];let e=0;for(let n=t.getChildBoundables().iterator();n.hasNext();){const r=n.next();r instanceof ui?e+=this.size(r):r instanceof vr&&(e+=1)}return e}}removeItem(t,e){let n=null;for(let r=t.getChildBoundables().iterator();r.hasNext();){const s=r.next();s instanceof vr&&s.getItem()===e&&(n=s)}return n!==null?(t.getChildBoundables().remove(n),!0):!1}itemsTree(){if(arguments.length===0){this.build();const t=this.itemsTree(this._root);return t===null?new wt:t}else if(arguments.length===1){const t=arguments[0],e=new wt;for(let n=t.getChildBoundables().iterator();n.hasNext();){const r=n.next();if(r instanceof ui){const s=this.itemsTree(r);s!==null&&e.add(s)}else r instanceof vr?e.add(r.getItem()):Yt.shouldNeverReachHere()}return e.size()<=0?null:e}}insert(t,e){Yt.isTrue(!this._built,"Cannot insert items into an STR packed R-tree after it has been built."),this._itemBoundables.add(new vr(t,e))}boundablesAtLevel(){if(arguments.length===1){const t=arguments[0],e=new wt;return this.boundablesAtLevel(t,this._root,e),e}else if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2];if(Yt.isTrue(t>-2),e.getLevel()===t)return n.add(e),null;for(let r=e.getChildBoundables().iterator();r.hasNext();){const s=r.next();s instanceof ui?this.boundablesAtLevel(t,s,n):(Yt.isTrue(s instanceof vr),t===-1&&n.add(s))}return null}}query(){if(arguments.length===1){const t=arguments[0];this.build();const e=new wt;return this.isEmpty()||this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.queryInternal(t,this._root,e),e}else if(arguments.length===2){const t=arguments[0],e=arguments[1];if(this.build(),this.isEmpty())return null;this.getIntersectsOp().intersects(this._root.getBounds(),t)&&this.queryInternal(t,this._root,e)}}build(){if(this._built)return null;this._root=this._itemBoundables.isEmpty()?this.createNode(0):this.createHigherLevels(this._itemBoundables,-1),this._itemBoundables=null,this._built=!0}getRoot(){return this.build(),this._root}remove(){if(arguments.length===2){const t=arguments[0],e=arguments[1];return this.build(),this.getIntersectsOp().intersects(this._root.getBounds(),t)?this.remove(t,this._root,e):!1}else if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2];let r=this.removeItem(e,n);if(r)return!0;let s=null;for(let o=e.getChildBoundables().iterator();o.hasNext();){const a=o.next();if(this.getIntersectsOp().intersects(a.getBounds(),t)&&a instanceof ui&&(r=this.remove(t,a,n),r)){s=a;break}}return s!==null&&s.getChildBoundables().isEmpty()&&e.getChildBoundables().remove(s),r}}createHigherLevels(t,e){Yt.isTrue(!t.isEmpty());const n=this.createParentBoundables(t,e+1);return n.size()===1?n.get(0):this.createHigherLevels(n,e+1)}depth(){if(arguments.length===0)return this.isEmpty()?0:(this.build(),this.depth(this._root));if(arguments.length===1){const t=arguments[0];let e=0;for(let n=t.getChildBoundables().iterator();n.hasNext();){const r=n.next();if(r instanceof ui){const s=this.depth(r);s>e&&(e=s)}}return e+1}}createParentBoundables(t,e){Yt.isTrue(!t.isEmpty());const n=new wt;n.add(this.createNode(e));const r=new wt(t);Is.sort(r,this.getComparator());for(let s=r.iterator();s.hasNext();){const o=s.next();this.lastNode(n).getChildBoundables().size()===this.getNodeCapacity()&&n.add(this.createNode(e)),this.lastNode(n).addChildBoundable(o)}return n}isEmpty(){return this._built?this._root.isEmpty():this._itemBoundables.isEmpty()}get interfaces_(){return[wi]}}function n8(){}Qr.IntersectsOp=n8;Qr.DEFAULT_NODE_CAPACITY=10;class i8{distance(t,e){}}class Je extends Qr{constructor(){super(),Je.constructor_.apply(this,arguments)}static constructor_(){if(arguments.length===0)Je.constructor_.call(this,Je.DEFAULT_NODE_CAPACITY);else if(arguments.length===1){const t=arguments[0];Qr.constructor_.call(this,t)}}static centreX(t){return Je.avg(t.getMinX(),t.getMaxX())}static avg(t,e){return(t+e)/2}static getItems(t){const e=new Array(t.size()).fill(null);let n=0;for(;!t.isEmpty();){const r=t.poll();e[n]=r.getBoundable(0).getItem(),n++}return e}static centreY(t){return Je.avg(t.getMinY(),t.getMaxY())}createParentBoundablesFromVerticalSlices(t,e){Yt.isTrue(t.length>0);const n=new wt;for(let r=0;r<t.length;r++)n.addAll(this.createParentBoundablesFromVerticalSlice(t[r],e));return n}nearestNeighbourK(){if(arguments.length===2){const t=arguments[0],e=arguments[1];return this.nearestNeighbourK(t,Tt.POSITIVE_INFINITY,e)}else if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2];let r=e;const s=new $a;s.add(t);const o=new $a;for(;!s.isEmpty()&&r>=0;){const a=s.poll(),l=a.getDistance();if(l>=r)break;a.isLeaves()?o.size()<n?o.add(a):(o.peek().getDistance()>l&&(o.poll(),o.add(a)),r=o.peek().getDistance()):a.expandToQueue(s,r)}return Je.getItems(o)}}createNode(t){return new xd(t)}size(){return arguments.length===0?super.size.call(this):super.size.apply(this,arguments)}insert(){if(arguments.length===2&&arguments[1]instanceof Object&&arguments[0]instanceof ne){const t=arguments[0],e=arguments[1];if(t.isNull())return null;super.insert.call(this,t,e)}else return super.insert.apply(this,arguments)}getIntersectsOp(){return Je.intersectsOp}verticalSlices(t,e){const n=Math.trunc(Math.ceil(t.size()/e)),r=new Array(e).fill(null),s=t.iterator();for(let o=0;o<e;o++){r[o]=new wt;let a=0;for(;s.hasNext()&&a<n;){const l=s.next();r[o].add(l),a++}}return r}query(){if(arguments.length===1){const t=arguments[0];return super.query.call(this,t)}else if(arguments.length===2){const t=arguments[0],e=arguments[1];super.query.call(this,t,e)}}getComparator(){return Je.yComparator}createParentBoundablesFromVerticalSlice(t,e){return super.createParentBoundables.call(this,t,e)}remove(){if(arguments.length===2&&arguments[1]instanceof Object&&arguments[0]instanceof ne){const t=arguments[0],e=arguments[1];return super.remove.call(this,t,e)}else return super.remove.apply(this,arguments)}depth(){return arguments.length===0?super.depth.call(this):super.depth.apply(this,arguments)}createParentBoundables(t,e){Yt.isTrue(!t.isEmpty());const n=Math.trunc(Math.ceil(t.size()/this.getNodeCapacity())),r=new wt(t);Is.sort(r,Je.xComparator);const s=this.verticalSlices(r,Math.trunc(Math.ceil(Math.sqrt(n))));return this.createParentBoundablesFromVerticalSlices(s,e)}nearestNeighbour(){if(arguments.length===1){if(At(arguments[0],i8)){const t=arguments[0];if(this.isEmpty())return null;const e=new Fn(this.getRoot(),this.getRoot(),t);return this.nearestNeighbour(e)}else if(arguments[0]instanceof Fn){const t=arguments[0];let e=Tt.POSITIVE_INFINITY,n=null;const r=new $a;for(r.add(t);!r.isEmpty()&&e>0;){const s=r.poll(),o=s.getDistance();if(o>=e)break;s.isLeaves()?(e=o,n=s):s.expandToQueue(r,e)}return n===null?null:[n.getBoundable(0).getItem(),n.getBoundable(1).getItem()]}}else if(arguments.length===2){const t=arguments[0],e=arguments[1];if(this.isEmpty()||t.isEmpty())return null;const n=new Fn(this.getRoot(),t.getRoot(),e);return this.nearestNeighbour(n)}else if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2],r=new vr(t,e),s=new Fn(this.getRoot(),r,n);return this.nearestNeighbour(s)[0]}else if(arguments.length===4){const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3],s=new vr(t,e),o=new Fn(this.getRoot(),s,n);return this.nearestNeighbourK(o,r)}}isWithinDistance(){if(arguments.length===2){const t=arguments[0],e=arguments[1];let n=Tt.POSITIVE_INFINITY;const r=new $a;for(r.add(t);!r.isEmpty();){const s=r.poll(),o=s.getDistance();if(o>e)return!1;if(s.maximumDistance()<=e)return!0;if(s.isLeaves()){if(n=o,n<=e)return!0}else s.expandToQueue(r,n)}return!1}else if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2],r=new Fn(this.getRoot(),t.getRoot(),e);return this.isWithinDistance(r,n)}}get interfaces_(){return[e8,wi]}}class xd extends ui{constructor(){super(),xd.constructor_.apply(this,arguments)}static constructor_(){const t=arguments[0];ui.constructor_.call(this,t)}computeBounds(){let t=null;for(let e=this.getChildBoundables().iterator();e.hasNext();){const n=e.next();t===null?t=new ne(n.getBounds()):t.expandToInclude(n.getBounds())}return t}}Je.STRtreeNode=xd;Je.xComparator=new class{get interfaces_(){return[lo]}compare(i,t){return Qr.compareDoubles(Je.centreX(i.getBounds()),Je.centreX(t.getBounds()))}};Je.yComparator=new class{get interfaces_(){return[lo]}compare(i,t){return Qr.compareDoubles(Je.centreY(i.getBounds()),Je.centreY(t.getBounds()))}};Je.intersectsOp=new class{get interfaces_(){return[IntersectsOp]}intersects(i,t){return i.intersects(t)}};Je.DEFAULT_NODE_CAPACITY=10;class Wi{static relativeSign(t,e){return t<e?-1:t>e?1:0}static compare(t,e,n){if(e.equals2D(n))return 0;const r=Wi.relativeSign(e.x,n.x),s=Wi.relativeSign(e.y,n.y);switch(t){case 0:return Wi.compareValue(r,s);case 1:return Wi.compareValue(s,r);case 2:return Wi.compareValue(s,-r);case 3:return Wi.compareValue(-r,s);case 4:return Wi.compareValue(-r,-s);case 5:return Wi.compareValue(-s,-r);case 6:return Wi.compareValue(-s,r);case 7:return Wi.compareValue(r,-s)}return Yt.shouldNeverReachHere("invalid octant value"),0}static compareValue(t,e){return t<0?-1:t>0?1:e<0?-1:e>0?1:0}}class Wp{constructor(){Wp.constructor_.apply(this,arguments)}static constructor_(){this._segString=null,this.coord=null,this.segmentIndex=null,this._segmentOctant=null,this._isInterior=null;const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];this._segString=t,this.coord=new Q(e),this.segmentIndex=n,this._segmentOctant=r,this._isInterior=!e.equals2D(t.getCoordinate(n))}getCoordinate(){return this.coord}print(t){t.print(this.coord),t.print(" seg # = "+this.segmentIndex)}compareTo(t){const e=t;return this.segmentIndex<e.segmentIndex?-1:this.segmentIndex>e.segmentIndex?1:this.coord.equals2D(e.coord)?0:this._isInterior?e._isInterior?Wi.compare(this._segmentOctant,this.coord,e.coord):1:-1}isEndPoint(t){return this.segmentIndex===0&&!this._isInterior||this.segmentIndex===t}toString(){return this.segmentIndex+":"+this.coord.toString()}isInterior(){return this._isInterior}get interfaces_(){return[Ei]}}class r8{hasNext(){}next(){}remove(){}}class Hp{constructor(){Hp.constructor_.apply(this,arguments)}static constructor_(){this._nodeMap=new ss,this._edge=null;const t=arguments[0];this._edge=t}getSplitCoordinates(){const t=new or;this.addEndpoints();const e=this.iterator();let n=e.next();for(;e.hasNext();){const r=e.next();this.addEdgeCoordinates(n,r,t),n=r}return t.toCoordinateArray()}addCollapsedNodes(){const t=new wt;this.findCollapsesFromInsertedNodes(t),this.findCollapsesFromExistingVertices(t);for(let e=t.iterator();e.hasNext();){const n=e.next().intValue();this.add(this._edge.getCoordinate(n),n)}}createSplitEdgePts(t,e){let n=e.segmentIndex-t.segmentIndex+2;if(n===2)return[new Q(t.coord),new Q(e.coord)];const r=this._edge.getCoordinate(e.segmentIndex),s=e.isInterior()||!e.coord.equals2D(r);s||n--;const o=new Array(n).fill(null);let a=0;o[a++]=new Q(t.coord);for(let l=t.segmentIndex+1;l<=e.segmentIndex;l++)o[a++]=this._edge.getCoordinate(l);return s&&(o[a]=new Q(e.coord)),o}print(t){t.println("Intersections:");for(let e=this.iterator();e.hasNext();)e.next().print(t)}findCollapsesFromExistingVertices(t){for(let e=0;e<this._edge.size()-2;e++){const n=this._edge.getCoordinate(e);this._edge.getCoordinate(e+1);const r=this._edge.getCoordinate(e+2);n.equals2D(r)&&t.add(pl.valueOf(e+1))}}addEdgeCoordinates(t,e,n){const r=this.createSplitEdgePts(t,e);n.add(r,!1)}iterator(){return this._nodeMap.values().iterator()}addSplitEdges(t){this.addEndpoints(),this.addCollapsedNodes();const e=this.iterator();let n=e.next();for(;e.hasNext();){const r=e.next(),s=this.createSplitEdge(n,r);t.add(s),n=r}}findCollapseIndex(t,e,n){if(!t.coord.equals2D(e.coord))return!1;let r=e.segmentIndex-t.segmentIndex;return e.isInterior()||r--,r===1?(n[0]=t.segmentIndex+1,!0):!1}findCollapsesFromInsertedNodes(t){const e=new Array(1).fill(null),n=this.iterator();let r=n.next();for(;n.hasNext();){const s=n.next();this.findCollapseIndex(r,s,e)&&t.add(pl.valueOf(e[0])),r=s}}getEdge(){return this._edge}addEndpoints(){const t=this._edge.size()-1;this.add(this._edge.getCoordinate(0),0),this.add(this._edge.getCoordinate(t),t)}createSplitEdge(t,e){const n=this.createSplitEdgePts(t,e);return new ts(n,this._edge.getData())}add(t,e){const n=new Wp(this._edge,t,e,this._edge.getSegmentOctant(e)),r=this._nodeMap.get(n);return r!==null?(Yt.isTrue(r.coord.equals2D(t),"Found equal nodes with different coordinates"),r):(this._nodeMap.put(n,n),n)}checkSplitEdgesCorrectness(t){const e=this._edge.getCoordinates(),r=t.get(0).getCoordinate(0);if(!r.equals2D(e[0]))throw new mi("bad split edge start point at "+r);const o=t.get(t.size()-1).getCoordinates(),a=o[o.length-1];if(!a.equals2D(e[e.length-1]))throw new mi("bad split edge end point at "+a)}}class bd{static octant(){if(typeof arguments[0]=="number"&&typeof arguments[1]=="number"){const t=arguments[0],e=arguments[1];if(t===0&&e===0)throw new te("Cannot compute the octant for point ( "+t+", "+e+" )");const n=Math.abs(t),r=Math.abs(e);return t>=0?e>=0?n>=r?0:1:n>=r?7:6:e>=0?n>=r?3:2:n>=r?4:5}else if(arguments[0]instanceof Q&&arguments[1]instanceof Q){const t=arguments[0],e=arguments[1],n=e.x-t.x,r=e.y-t.y;if(n===0&&r===0)throw new te("Cannot compute the octant for two identical points "+t);return bd.octant(n,r)}}}class Zx{getCoordinates(){}size(){}getCoordinate(t){}isClosed(){}setData(t){}getData(){}}class s8{addIntersection(t,e){}get interfaces_(){return[Zx]}}class ts{constructor(){ts.constructor_.apply(this,arguments)}static constructor_(){this._nodeList=new Hp(this),this._pts=null,this._data=null;const t=arguments[0],e=arguments[1];this._pts=t,this._data=e}static getNodedSubstrings(){if(arguments.length===1){const t=arguments[0],e=new wt;return ts.getNodedSubstrings(t,e),e}else if(arguments.length===2){const t=arguments[0],e=arguments[1];for(let n=t.iterator();n.hasNext();)n.next().getNodeList().addSplitEdges(e)}}getCoordinates(){return this._pts}size(){return this._pts.length}getCoordinate(t){return this._pts[t]}isClosed(){return this._pts[0].equals(this._pts[this._pts.length-1])}getSegmentOctant(t){return t===this._pts.length-1?-1:this.safeOctant(this.getCoordinate(t),this.getCoordinate(t+1))}setData(t){this._data=t}safeOctant(t,e){return t.equals2D(e)?0:bd.octant(t,e)}getData(){return this._data}addIntersection(){if(arguments.length===2){const t=arguments[0],e=arguments[1];this.addIntersectionNode(t,e)}else if(arguments.length===4){const t=arguments[0],e=arguments[1],n=arguments[3],r=new Q(t.getIntersection(n));this.addIntersection(r,e)}}toString(){return rs.toLineString(new Sr(this._pts))}getNodeList(){return this._nodeList}addIntersectionNode(t,e){let n=e;const r=n+1;if(r<this._pts.length){const o=this._pts[r];t.equals2D(o)&&(n=r)}return this._nodeList.add(t,n)}addIntersections(t,e,n){for(let r=0;r<t.getIntersectionNum();r++)this.addIntersection(t,e,n,r)}get interfaces_(){return[s8]}}class Me{constructor(){Me.constructor_.apply(this,arguments)}static constructor_(){if(this.p0=null,this.p1=null,arguments.length===0)Me.constructor_.call(this,new Q,new Q);else if(arguments.length===1){const t=arguments[0];Me.constructor_.call(this,t.p0,t.p1)}else if(arguments.length===2){const t=arguments[0],e=arguments[1];this.p0=t,this.p1=e}else if(arguments.length===4){const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];Me.constructor_.call(this,new Q(t,e),new Q(n,r))}}static midPoint(t,e){return new Q((t.x+e.x)/2,(t.y+e.y)/2)}minX(){return Math.min(this.p0.x,this.p1.x)}orientationIndex(){if(arguments[0]instanceof Me){const t=arguments[0],e=$t.index(this.p0,this.p1,t.p0),n=$t.index(this.p0,this.p1,t.p1);return e>=0&&n>=0||e<=0&&n<=0?Math.max(e,n):0}else if(arguments[0]instanceof Q){const t=arguments[0];return $t.index(this.p0,this.p1,t)}}toGeometry(t){return t.createLineString([this.p0,this.p1])}isVertical(){return this.p0.x===this.p1.x}equals(t){if(!(t instanceof Me))return!1;const e=t;return this.p0.equals(e.p0)&&this.p1.equals(e.p1)}intersection(t){const e=new Pn;return e.computeIntersection(this.p0,this.p1,t.p0,t.p1),e.hasIntersection()?e.getIntersection(0):null}project(){if(arguments[0]instanceof Q){const t=arguments[0];if(t.equals(this.p0)||t.equals(this.p1))return new Q(t);const e=this.projectionFactor(t),n=new Q;return n.x=this.p0.x+e*(this.p1.x-this.p0.x),n.y=this.p0.y+e*(this.p1.y-this.p0.y),n}else if(arguments[0]instanceof Me){const t=arguments[0],e=this.projectionFactor(t.p0),n=this.projectionFactor(t.p1);if(e>=1&&n>=1||e<=0&&n<=0)return null;let r=this.project(t.p0);e<0&&(r=this.p0),e>1&&(r=this.p1);let s=this.project(t.p1);return n<0&&(s=this.p0),n>1&&(s=this.p1),new Me(r,s)}}normalize(){this.p1.compareTo(this.p0)<0&&this.reverse()}angle(){return Math.atan2(this.p1.y-this.p0.y,this.p1.x-this.p0.x)}getCoordinate(t){return t===0?this.p0:this.p1}distancePerpendicular(t){return dn.pointToLinePerpendicular(t,this.p0,this.p1)}minY(){return Math.min(this.p0.y,this.p1.y)}midPoint(){return Me.midPoint(this.p0,this.p1)}projectionFactor(t){if(t.equals(this.p0))return 0;if(t.equals(this.p1))return 1;const e=this.p1.x-this.p0.x,n=this.p1.y-this.p0.y,r=e*e+n*n;return r<=0?Tt.NaN:((t.x-this.p0.x)*e+(t.y-this.p0.y)*n)/r}closestPoints(t){const e=this.intersection(t);if(e!==null)return[e,e];const n=new Array(2).fill(null);let r=Tt.MAX_VALUE,s=null;const o=this.closestPoint(t.p0);r=o.distance(t.p0),n[0]=o,n[1]=t.p0;const a=this.closestPoint(t.p1);s=a.distance(t.p1),s<r&&(r=s,n[0]=a,n[1]=t.p1);const l=t.closestPoint(this.p0);s=l.distance(this.p0),s<r&&(r=s,n[0]=this.p0,n[1]=l);const h=t.closestPoint(this.p1);return s=h.distance(this.p1),s<r&&(r=s,n[0]=this.p1,n[1]=h),n}closestPoint(t){const e=this.projectionFactor(t);if(e>0&&e<1)return this.project(t);const n=this.p0.distance(t),r=this.p1.distance(t);return n<r?this.p0:this.p1}maxX(){return Math.max(this.p0.x,this.p1.x)}getLength(){return this.p0.distance(this.p1)}compareTo(t){const e=t,n=this.p0.compareTo(e.p0);return n!==0?n:this.p1.compareTo(e.p1)}reverse(){const t=this.p0;this.p0=this.p1,this.p1=t}equalsTopo(t){return this.p0.equals(t.p0)&&this.p1.equals(t.p1)||this.p0.equals(t.p1)&&this.p1.equals(t.p0)}lineIntersection(t){return jp.intersection(this.p0,this.p1,t.p0,t.p1)}maxY(){return Math.max(this.p0.y,this.p1.y)}pointAlongOffset(t,e){const n=this.p0.x+t*(this.p1.x-this.p0.x),r=this.p0.y+t*(this.p1.y-this.p0.y),s=this.p1.x-this.p0.x,o=this.p1.y-this.p0.y,a=Math.sqrt(s*s+o*o);let l=0,h=0;if(e!==0){if(a<=0)throw new IllegalStateException("Cannot compute offset from zero-length line segment");l=e*s/a,h=e*o/a}const f=n-h,d=r+l;return new Q(f,d)}setCoordinates(){if(arguments.length===1){const t=arguments[0];this.setCoordinates(t.p0,t.p1)}else if(arguments.length===2){const t=arguments[0],e=arguments[1];this.p0.x=t.x,this.p0.y=t.y,this.p1.x=e.x,this.p1.y=e.y}}segmentFraction(t){let e=this.projectionFactor(t);return e<0?e=0:(e>1||Tt.isNaN(e))&&(e=1),e}toString(){return"LINESTRING( "+this.p0.x+" "+this.p0.y+", "+this.p1.x+" "+this.p1.y+")"}isHorizontal(){return this.p0.y===this.p1.y}reflect(t){const e=this.p1.getY()-this.p0.getY(),n=this.p0.getX()-this.p1.getX(),r=this.p0.getY()*(this.p1.getX()-this.p0.getX())-this.p0.getX()*(this.p1.getY()-this.p0.getY()),s=e*e+n*n,o=e*e-n*n,a=t.getX(),l=t.getY(),h=(-o*a-2*e*n*l-2*e*r)/s,f=(o*l-2*e*n*a-2*n*r)/s;return new Q(h,f)}distance(){if(arguments[0]instanceof Me){const t=arguments[0];return dn.segmentToSegment(this.p0,this.p1,t.p0,t.p1)}else if(arguments[0]instanceof Q){const t=arguments[0];return dn.pointToSegment(t,this.p0,this.p1)}}pointAlong(t){const e=new Q;return e.x=this.p0.x+t*(this.p1.x-this.p0.x),e.y=this.p0.y+t*(this.p1.y-this.p0.y),e}hashCode(){let t=Tt.doubleToLongBits(this.p0.x);t^=Tt.doubleToLongBits(this.p0.y)*31;const e=Math.trunc(t)^Math.trunc(t>>32);let n=Tt.doubleToLongBits(this.p1.x);n^=Tt.doubleToLongBits(this.p1.y)*31;const r=Math.trunc(n)^Math.trunc(n>>32);return e^r}get interfaces_(){return[Ei,wi]}}class Kp{constructor(){Kp.constructor_.apply(this,arguments)}static constructor_(){this._overlapSeg1=new Me,this._overlapSeg2=new Me}overlap(){if(arguments.length!==2){if(arguments.length===4){const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];t.getLineSegment(e,this._overlapSeg1),n.getLineSegment(r,this._overlapSeg2),this.overlap(this._overlapSeg1,this._overlapSeg2)}}}}let Jx=class Qx{constructor(){Qx.constructor_.apply(this,arguments)}static constructor_(){this._pts=null,this._start=null,this._end=null,this._env=null,this._context=null,this._id=null;const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];this._pts=t,this._start=e,this._end=n,this._context=r}getLineSegment(t,e){e.p0=this._pts[t],e.p1=this._pts[t+1]}computeSelect(t,e,n,r){const s=this._pts[e],o=this._pts[n];if(n-e===1)return r.select(this,e),null;if(!t.intersects(s,o))return null;const a=Math.trunc((e+n)/2);e<a&&this.computeSelect(t,e,a,r),a<n&&this.computeSelect(t,a,n,r)}getCoordinates(){const t=new Array(this._end-this._start+1).fill(null);let e=0;for(let n=this._start;n<=this._end;n++)t[e++]=this._pts[n];return t}computeOverlaps(){if(arguments.length===2){const t=arguments[0],e=arguments[1];this.computeOverlaps(this._start,this._end,t,t._start,t._end,e)}else if(arguments.length===6){const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3],s=arguments[4],o=arguments[5];if(e-t===1&&s-r===1)return o.overlap(this,t,n,r),null;if(!this.overlaps(t,e,n,r,s))return null;const a=Math.trunc((t+e)/2),l=Math.trunc((r+s)/2);t<a&&(r<l&&this.computeOverlaps(t,a,n,r,l,o),l<s&&this.computeOverlaps(t,a,n,l,s,o)),a<e&&(r<l&&this.computeOverlaps(a,e,n,r,l,o),l<s&&this.computeOverlaps(a,e,n,l,s,o))}}setId(t){this._id=t}select(t,e){this.computeSelect(t,this._start,this._end,e)}getEnvelope(){if(this._env===null){const t=this._pts[this._start],e=this._pts[this._end];this._env=new ne(t,e)}return this._env}overlaps(t,e,n,r,s){return ne.intersects(this._pts[t],this._pts[e],n._pts[r],n._pts[s])}getEndIndex(){return this._end}getStartIndex(){return this._start}getContext(){return this._context}getId(){return this._id}};class Cf{static findChainEnd(t,e){let n=e;for(;n<t.length-1&&t[n].equals2D(t[n+1]);)n++;if(n>=t.length-1)return t.length-1;const r=Le.quadrant(t[n],t[n+1]);let s=e+1;for(;s<t.length&&!(!t[s-1].equals2D(t[s])&&Le.quadrant(t[s-1],t[s])!==r);)s++;return s-1}static getChains(){if(arguments.length===1){const t=arguments[0];return Cf.getChains(t,null)}else if(arguments.length===2){const t=arguments[0],e=arguments[1],n=new wt;let r=0;do{const s=Cf.findChainEnd(t,r),o=new Jx(t,r,s,e);n.add(o),r=s}while(r<t.length-1);return n}}}class Zp{computeNodes(t){}getNodedSubstrings(){}}class Pf{constructor(){Pf.constructor_.apply(this,arguments)}static constructor_(){if(this._segInt=null,arguments.length!==0){if(arguments.length===1){const t=arguments[0];this.setSegmentIntersector(t)}}}setSegmentIntersector(t){this._segInt=t}get interfaces_(){return[Zp]}}class Fl extends Pf{constructor(){super(),Fl.constructor_.apply(this,arguments)}static constructor_(){if(this._monoChains=new wt,this._index=new Je,this._idCounter=0,this._nodedSegStrings=null,this._nOverlaps=0,arguments.length!==0){if(arguments.length===1){const t=arguments[0];Pf.constructor_.call(this,t)}}}getMonotoneChains(){return this._monoChains}getNodedSubstrings(){return ts.getNodedSubstrings(this._nodedSegStrings)}getIndex(){return this._index}add(t){const e=Cf.getChains(t.getCoordinates(),t);for(let n=e.iterator();n.hasNext();){const r=n.next();r.setId(this._idCounter++),this._index.insert(r.getEnvelope(),r),this._monoChains.add(r)}}computeNodes(t){this._nodedSegStrings=t;for(let e=t.iterator();e.hasNext();)this.add(e.next());this.intersectChains()}intersectChains(){const t=new Id(this._segInt);for(let e=this._monoChains.iterator();e.hasNext();){const n=e.next(),r=this._index.query(n.getEnvelope());for(let s=r.iterator();s.hasNext();){const o=s.next();if(o.getId()>n.getId()&&(n.computeOverlaps(o,t),this._nOverlaps++),this._segInt.isDone())return null}}}}class Id extends Kp{constructor(){super(),Id.constructor_.apply(this,arguments)}static constructor_(){this._si=null;const t=arguments[0];this._si=t}overlap(){if(arguments.length===4){const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3],s=t.getContext(),o=n.getContext();this._si.processIntersections(s,e,o,r)}else return super.overlap.apply(this,arguments)}}Fl.SegmentOverlapAction=Id;class En{constructor(){En.constructor_.apply(this,arguments)}static constructor_(){this._inputLine=null,this._distanceTol=null,this._isDeleted=null,this._angleOrientation=$t.COUNTERCLOCKWISE;const t=arguments[0];this._inputLine=t}static simplify(t,e){return new En(t).simplify(e)}isDeletable(t,e,n,r){const s=this._inputLine[t],o=this._inputLine[e],a=this._inputLine[n];return!this.isConcave(s,o,a)||!this.isShallow(s,o,a,r)?!1:this.isShallowSampled(s,o,t,n,r)}deleteShallowConcavities(){let t=1,e=this.findNextNonDeletedIndex(t),n=this.findNextNonDeletedIndex(e),r=!1;for(;n<this._inputLine.length;){let s=!1;this.isDeletable(t,e,n,this._distanceTol)&&(this._isDeleted[e]=En.DELETE,s=!0,r=!0),s?t=n:t=e,e=this.findNextNonDeletedIndex(t),n=this.findNextNonDeletedIndex(e)}return r}isShallowConcavity(t,e,n,r){return $t.index(t,e,n)===this._angleOrientation?dn.pointToSegment(e,t,n)<r:!1}isShallowSampled(t,e,n,r,s){let o=Math.trunc((r-n)/En.NUM_PTS_TO_CHECK);o<=0&&(o=1);for(let a=n;a<r;a+=o)if(!this.isShallow(t,e,this._inputLine[a],s))return!1;return!0}isConcave(t,e,n){return $t.index(t,e,n)===this._angleOrientation}simplify(t){this._distanceTol=Math.abs(t),t<0&&(this._angleOrientation=$t.CLOCKWISE),this._isDeleted=new Array(this._inputLine.length).fill(null);let e=!1;do e=this.deleteShallowConcavities();while(e);return this.collapseLine()}findNextNonDeletedIndex(t){let e=t+1;for(;e<this._inputLine.length&&this._isDeleted[e]===En.DELETE;)e++;return e}isShallow(t,e,n,r){return dn.pointToSegment(e,t,n)<r}collapseLine(){const t=new or;for(let e=0;e<this._inputLine.length;e++)this._isDeleted[e]!==En.DELETE&&t.add(this._inputLine[e]);return t.toCoordinateArray()}}En.INIT=0;En.DELETE=1;En.KEEP=1;En.NUM_PTS_TO_CHECK=10;class ec{constructor(){ec.constructor_.apply(this,arguments)}static constructor_(){this._ptList=null,this._precisionModel=null,this._minimimVertexDistance=0,this._ptList=new wt}getCoordinates(){return this._ptList.toArray(ec.COORDINATE_ARRAY_TYPE)}setPrecisionModel(t){this._precisionModel=t}addPt(t){const e=new Q(t);if(this._precisionModel.makePrecise(e),this.isRedundant(e))return null;this._ptList.add(e)}reverse(){}addPts(t,e){if(e)for(let n=0;n<t.length;n++)this.addPt(t[n]);else for(let n=t.length-1;n>=0;n--)this.addPt(t[n])}isRedundant(t){if(this._ptList.size()<1)return!1;const e=this._ptList.get(this._ptList.size()-1);return t.distance(e)<this._minimimVertexDistance}toString(){return new qe().createLineString(this.getCoordinates()).toString()}closeRing(){if(this._ptList.size()<1)return null;const t=new Q(this._ptList.get(0)),e=this._ptList.get(this._ptList.size()-1);if(t.equals(e))return null;this._ptList.add(t)}setMinimumVertexDistance(t){this._minimimVertexDistance=t}}ec.COORDINATE_ARRAY_TYPE=new Array(0).fill(null);class ye{static toDegrees(t){return t*180/Math.PI}static normalize(t){for(;t>Math.PI;)t-=ye.PI_TIMES_2;for(;t<=-Math.PI;)t+=ye.PI_TIMES_2;return t}static angle(){if(arguments.length===1){const t=arguments[0];return Math.atan2(t.y,t.x)}else if(arguments.length===2){const t=arguments[0],e=arguments[1],n=e.x-t.x,r=e.y-t.y;return Math.atan2(r,n)}}static isAcute(t,e,n){const r=t.x-e.x,s=t.y-e.y,o=n.x-e.x,a=n.y-e.y;return r*o+s*a>0}static isObtuse(t,e,n){const r=t.x-e.x,s=t.y-e.y,o=n.x-e.x,a=n.y-e.y;return r*o+s*a<0}static interiorAngle(t,e,n){const r=ye.angle(e,t),s=ye.angle(e,n);return Math.abs(s-r)}static normalizePositive(t){if(t<0){for(;t<0;)t+=ye.PI_TIMES_2;t>=ye.PI_TIMES_2&&(t=0)}else{for(;t>=ye.PI_TIMES_2;)t-=ye.PI_TIMES_2;t<0&&(t=0)}return t}static angleBetween(t,e,n){const r=ye.angle(e,t),s=ye.angle(e,n);return ye.diff(r,s)}static diff(t,e){let n=null;return t<e?n=e-t:n=t-e,n>Math.PI&&(n=2*Math.PI-n),n}static toRadians(t){return t*Math.PI/180}static getTurn(t,e){const n=Math.sin(e-t);return n>0?ye.COUNTERCLOCKWISE:n<0?ye.CLOCKWISE:ye.NONE}static angleBetweenOriented(t,e,n){const r=ye.angle(e,t),o=ye.angle(e,n)-r;return o<=-Math.PI?o+ye.PI_TIMES_2:o>Math.PI?o-ye.PI_TIMES_2:o}}ye.PI_TIMES_2=2*Math.PI;ye.PI_OVER_2=Math.PI/2;ye.PI_OVER_4=Math.PI/4;ye.COUNTERCLOCKWISE=$t.COUNTERCLOCKWISE;ye.CLOCKWISE=$t.CLOCKWISE;ye.NONE=$t.COLLINEAR;class wr{constructor(){wr.constructor_.apply(this,arguments)}static constructor_(){this._maxCurveSegmentError=0,this._filletAngleQuantum=null,this._closingSegLengthFactor=1,this._segList=null,this._distance=0,this._precisionModel=null,this._bufParams=null,this._li=null,this._s0=null,this._s1=null,this._s2=null,this._seg0=new Me,this._seg1=new Me,this._offset0=new Me,this._offset1=new Me,this._side=0,this._hasNarrowConcaveAngle=!1;const t=arguments[0],e=arguments[1],n=arguments[2];this._precisionModel=t,this._bufParams=e,this._li=new Pn,this._filletAngleQuantum=Math.PI/2/e.getQuadrantSegments(),e.getQuadrantSegments()>=8&&e.getJoinStyle()===re.JOIN_ROUND&&(this._closingSegLengthFactor=wr.MAX_CLOSING_SEG_LEN_FACTOR),this.init(n)}addNextSegment(t,e){if(this._s0=this._s1,this._s1=this._s2,this._s2=t,this._seg0.setCoordinates(this._s0,this._s1),this.computeOffsetSegment(this._seg0,this._side,this._distance,this._offset0),this._seg1.setCoordinates(this._s1,this._s2),this.computeOffsetSegment(this._seg1,this._side,this._distance,this._offset1),this._s1.equals(this._s2))return null;const n=$t.index(this._s0,this._s1,this._s2),r=n===$t.CLOCKWISE&&this._side===_t.LEFT||n===$t.COUNTERCLOCKWISE&&this._side===_t.RIGHT;n===0?this.addCollinear(e):r?this.addOutsideTurn(n,e):this.addInsideTurn(n,e)}addLineEndCap(t,e){const n=new Me(t,e),r=new Me;this.computeOffsetSegment(n,_t.LEFT,this._distance,r);const s=new Me;this.computeOffsetSegment(n,_t.RIGHT,this._distance,s);const o=e.x-t.x,a=e.y-t.y,l=Math.atan2(a,o);switch(this._bufParams.getEndCapStyle()){case re.CAP_ROUND:this._segList.addPt(r.p1),this.addDirectedFillet(e,l+Math.PI/2,l-Math.PI/2,$t.CLOCKWISE,this._distance),this._segList.addPt(s.p1);break;case re.CAP_FLAT:this._segList.addPt(r.p1),this._segList.addPt(s.p1);break;case re.CAP_SQUARE:const h=new Q;h.x=Math.abs(this._distance)*Math.cos(l),h.y=Math.abs(this._distance)*Math.sin(l);const f=new Q(r.p1.x+h.x,r.p1.y+h.y),d=new Q(s.p1.x+h.x,s.p1.y+h.y);this._segList.addPt(f),this._segList.addPt(d);break}}getCoordinates(){return this._segList.getCoordinates()}addMitreJoin(t,e,n,r){const s=jp.intersection(e.p0,e.p1,n.p0,n.p1);if(s!==null&&(r<=0?1:s.distance(t)/Math.abs(r))<=this._bufParams.getMitreLimit())return this._segList.addPt(s),null;this.addLimitedMitreJoin(e,n,r,this._bufParams.getMitreLimit())}addOutsideTurn(t,e){if(this._offset0.p1.distance(this._offset1.p0)<this._distance*wr.OFFSET_SEGMENT_SEPARATION_FACTOR)return this._segList.addPt(this._offset0.p1),null;this._bufParams.getJoinStyle()===re.JOIN_MITRE?this.addMitreJoin(this._s1,this._offset0,this._offset1,this._distance):this._bufParams.getJoinStyle()===re.JOIN_BEVEL?this.addBevelJoin(this._offset0,this._offset1):(e&&this._segList.addPt(this._offset0.p1),this.addCornerFillet(this._s1,this._offset0.p1,this._offset1.p0,t,this._distance),this._segList.addPt(this._offset1.p0))}createSquare(t){this._segList.addPt(new Q(t.x+this._distance,t.y+this._distance)),this._segList.addPt(new Q(t.x+this._distance,t.y-this._distance)),this._segList.addPt(new Q(t.x-this._distance,t.y-this._distance)),this._segList.addPt(new Q(t.x-this._distance,t.y+this._distance)),this._segList.closeRing()}addSegments(t,e){this._segList.addPts(t,e)}addFirstSegment(){this._segList.addPt(this._offset1.p0)}addCornerFillet(t,e,n,r,s){const o=e.x-t.x,a=e.y-t.y;let l=Math.atan2(a,o);const h=n.x-t.x,f=n.y-t.y,d=Math.atan2(f,h);r===$t.CLOCKWISE?l<=d&&(l+=2*Math.PI):l>=d&&(l-=2*Math.PI),this._segList.addPt(e),this.addDirectedFillet(t,l,d,r,s),this._segList.addPt(n)}addLastSegment(){this._segList.addPt(this._offset1.p1)}initSideSegments(t,e,n){this._s1=t,this._s2=e,this._side=n,this._seg1.setCoordinates(t,e),this.computeOffsetSegment(this._seg1,n,this._distance,this._offset1)}addLimitedMitreJoin(t,e,n,r){const s=this._seg0.p1,o=ye.angle(s,this._seg0.p0),l=ye.angleBetweenOriented(this._seg0.p0,s,this._seg1.p1)/2,h=ye.normalize(o+l),f=ye.normalize(h+Math.PI),d=r*n,p=d*Math.abs(Math.sin(l)),y=n-p,_=s.x+d*Math.cos(f),E=s.y+d*Math.sin(f),w=new Q(_,E),L=new Me(s,w),b=L.pointAlongOffset(1,y),S=L.pointAlongOffset(1,-y);this._side===_t.LEFT?(this._segList.addPt(b),this._segList.addPt(S)):(this._segList.addPt(S),this._segList.addPt(b))}addDirectedFillet(t,e,n,r,s){const o=r===$t.CLOCKWISE?-1:1,a=Math.abs(e-n),l=Math.trunc(a/this._filletAngleQuantum+.5);if(l<1)return null;const h=a/l,f=new Q;for(let d=0;d<l;d++){const p=e+o*d*h;f.x=t.x+s*Math.cos(p),f.y=t.y+s*Math.sin(p),this._segList.addPt(f)}}computeOffsetSegment(t,e,n,r){const s=e===_t.LEFT?1:-1,o=t.p1.x-t.p0.x,a=t.p1.y-t.p0.y,l=Math.sqrt(o*o+a*a),h=s*n*o/l,f=s*n*a/l;r.p0.x=t.p0.x-f,r.p0.y=t.p0.y+h,r.p1.x=t.p1.x-f,r.p1.y=t.p1.y+h}addInsideTurn(t,e){if(this._li.computeIntersection(this._offset0.p0,this._offset0.p1,this._offset1.p0,this._offset1.p1),this._li.hasIntersection())this._segList.addPt(this._li.getIntersection(0));else if(this._hasNarrowConcaveAngle=!0,this._offset0.p1.distance(this._offset1.p0)<this._distance*wr.INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR)this._segList.addPt(this._offset0.p1);else{if(this._segList.addPt(this._offset0.p1),this._closingSegLengthFactor>0){const n=new Q((this._closingSegLengthFactor*this._offset0.p1.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset0.p1.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(n);const r=new Q((this._closingSegLengthFactor*this._offset1.p0.x+this._s1.x)/(this._closingSegLengthFactor+1),(this._closingSegLengthFactor*this._offset1.p0.y+this._s1.y)/(this._closingSegLengthFactor+1));this._segList.addPt(r)}else this._segList.addPt(this._s1);this._segList.addPt(this._offset1.p0)}}createCircle(t){const e=new Q(t.x+this._distance,t.y);this._segList.addPt(e),this.addDirectedFillet(t,0,2*Math.PI,-1,this._distance),this._segList.closeRing()}addBevelJoin(t,e){this._segList.addPt(t.p1),this._segList.addPt(e.p0)}init(t){this._distance=t,this._maxCurveSegmentError=t*(1-Math.cos(this._filletAngleQuantum/2)),this._segList=new ec,this._segList.setPrecisionModel(this._precisionModel),this._segList.setMinimumVertexDistance(t*wr.CURVE_VERTEX_SNAP_DISTANCE_FACTOR)}addCollinear(t){this._li.computeIntersection(this._s0,this._s1,this._s1,this._s2),this._li.getIntersectionNum()>=2&&(this._bufParams.getJoinStyle()===re.JOIN_BEVEL||this._bufParams.getJoinStyle()===re.JOIN_MITRE?(t&&this._segList.addPt(this._offset0.p1),this._segList.addPt(this._offset1.p0)):this.addCornerFillet(this._s1,this._offset0.p1,this._offset1.p0,$t.CLOCKWISE,this._distance))}closeRing(){this._segList.closeRing()}hasNarrowConcaveAngle(){return this._hasNarrowConcaveAngle}}wr.OFFSET_SEGMENT_SEPARATION_FACTOR=.001;wr.INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR=.001;wr.CURVE_VERTEX_SNAP_DISTANCE_FACTOR=1e-6;wr.MAX_CLOSING_SEG_LEN_FACTOR=80;class kf{constructor(){kf.constructor_.apply(this,arguments)}static constructor_(){this._distance=0,this._precisionModel=null,this._bufParams=null;const t=arguments[0],e=arguments[1];this._precisionModel=t,this._bufParams=e}static copyCoordinates(t){const e=new Array(t.length).fill(null);for(let n=0;n<e.length;n++)e[n]=new Q(t[n]);return e}getOffsetCurve(t,e){if(this._distance=e,e===0)return null;const n=e<0,r=Math.abs(e),s=this.getSegGen(r);t.length<=1?this.computePointCurve(t[0],s):this.computeOffsetCurve(t,n,s);const o=s.getCoordinates();return n&&Ce.reverse(o),o}computeSingleSidedBufferCurve(t,e,n){const r=this.simplifyTolerance(this._distance);if(e){n.addSegments(t,!0);const s=En.simplify(t,-r),o=s.length-1;n.initSideSegments(s[o],s[o-1],_t.LEFT),n.addFirstSegment();for(let a=o-2;a>=0;a--)n.addNextSegment(s[a],!0)}else{n.addSegments(t,!1);const s=En.simplify(t,r),o=s.length-1;n.initSideSegments(s[0],s[1],_t.LEFT),n.addFirstSegment();for(let a=2;a<=o;a++)n.addNextSegment(s[a],!0)}n.addLastSegment(),n.closeRing()}computeRingBufferCurve(t,e,n){let r=this.simplifyTolerance(this._distance);e===_t.RIGHT&&(r=-r);const s=En.simplify(t,r),o=s.length-1;n.initSideSegments(s[o-1],s[0],e);for(let a=1;a<=o;a++){const l=a!==1;n.addNextSegment(s[a],l)}n.closeRing()}computeLineBufferCurve(t,e){const n=this.simplifyTolerance(this._distance),r=En.simplify(t,n),s=r.length-1;e.initSideSegments(r[0],r[1],_t.LEFT);for(let l=2;l<=s;l++)e.addNextSegment(r[l],!0);e.addLastSegment(),e.addLineEndCap(r[s-1],r[s]);const o=En.simplify(t,-n),a=o.length-1;e.initSideSegments(o[a],o[a-1],_t.LEFT);for(let l=a-2;l>=0;l--)e.addNextSegment(o[l],!0);e.addLastSegment(),e.addLineEndCap(o[1],o[0]),e.closeRing()}computePointCurve(t,e){switch(this._bufParams.getEndCapStyle()){case re.CAP_ROUND:e.createCircle(t);break;case re.CAP_SQUARE:e.createSquare(t);break}}getLineCurve(t,e){if(this._distance=e,this.isLineOffsetEmpty(e))return null;const n=Math.abs(e),r=this.getSegGen(n);if(t.length<=1)this.computePointCurve(t[0],r);else if(this._bufParams.isSingleSided()){const o=e<0;this.computeSingleSidedBufferCurve(t,o,r)}else this.computeLineBufferCurve(t,r);return r.getCoordinates()}getBufferParameters(){return this._bufParams}simplifyTolerance(t){return t*this._bufParams.getSimplifyFactor()}getRingCurve(t,e,n){if(this._distance=n,t.length<=2)return this.getLineCurve(t,n);if(n===0)return kf.copyCoordinates(t);const r=this.getSegGen(n);return this.computeRingBufferCurve(t,e,r),r.getCoordinates()}computeOffsetCurve(t,e,n){const r=this.simplifyTolerance(this._distance);if(e){const s=En.simplify(t,-r),o=s.length-1;n.initSideSegments(s[o],s[o-1],_t.LEFT),n.addFirstSegment();for(let a=o-2;a>=0;a--)n.addNextSegment(s[a],!0)}else{const s=En.simplify(t,r),o=s.length-1;n.initSideSegments(s[0],s[1],_t.LEFT),n.addFirstSegment();for(let a=2;a<=o;a++)n.addNextSegment(s[a],!0)}n.addLastSegment()}isLineOffsetEmpty(t){return t===0||t<0&&!this._bufParams.isSingleSided()}getSegGen(t){return new wr(this._precisionModel,this._bufParams,t)}}class Sd{constructor(){Sd.constructor_.apply(this,arguments)}static constructor_(){this._subgraphs=null,this._seg=new Me;const t=arguments[0];this._subgraphs=t}findStabbedSegments(){if(arguments.length===1){const t=arguments[0],e=new wt;for(let n=this._subgraphs.iterator();n.hasNext();){const r=n.next(),s=r.getEnvelope();t.y<s.getMinY()||t.y>s.getMaxY()||this.findStabbedSegments(t,r.getDirectedEdges(),e)}return e}else if(arguments.length===3){if(At(arguments[2],Oi)&&arguments[0]instanceof Q&&arguments[1]instanceof Qu){const t=arguments[0],e=arguments[1],n=arguments[2],r=e.getEdge().getCoordinates();for(let s=0;s<r.length-1;s++){if(this._seg.p0=r[s],this._seg.p1=r[s+1],this._seg.p0.y>this._seg.p1.y&&this._seg.reverse(),Math.max(this._seg.p0.x,this._seg.p1.x)<t.x||this._seg.isHorizontal()||t.y<this._seg.p0.y||t.y>this._seg.p1.y||$t.index(this._seg.p0,this._seg.p1,t)===$t.RIGHT)continue;let a=e.getDepth(_t.LEFT);this._seg.p0.equals(r[s])||(a=e.getDepth(_t.RIGHT));const l=new Md(this._seg,a);n.add(l)}}else if(At(arguments[2],Oi)&&arguments[0]instanceof Q&&At(arguments[1],Oi)){const t=arguments[0],e=arguments[1],n=arguments[2];for(let r=e.iterator();r.hasNext();){const s=r.next();s.isForward()&&this.findStabbedSegments(t,s,n)}}}}getDepth(t){const e=this.findStabbedSegments(t);return e.size()===0?0:Is.min(e)._leftDepth}}class Md{constructor(){Md.constructor_.apply(this,arguments)}static constructor_(){this._upwardSeg=null,this._leftDepth=null;const t=arguments[0],e=arguments[1];this._upwardSeg=new Me(t),this._leftDepth=e}compareTo(t){const e=t;if(this._upwardSeg.minX()>=e._upwardSeg.maxX())return 1;if(this._upwardSeg.maxX()<=e._upwardSeg.minX())return-1;let n=this._upwardSeg.orientationIndex(e._upwardSeg);return n!==0||(n=-1*e._upwardSeg.orientationIndex(this._upwardSeg),n!==0)?n:this._upwardSeg.compareTo(e._upwardSeg)}compareX(t,e){const n=t.p0.compareTo(e.p0);return n!==0?n:t.p1.compareTo(e.p1)}toString(){return this._upwardSeg.toString()}get interfaces_(){return[Ei]}}Sd.DepthSegment=Md;class Tf extends Tr{constructor(){super(),Tf.constructor_.apply(this,arguments)}static constructor_(){Tr.constructor_.call(this,"Projective point not representable on the Cartesian plane.")}}class Do{constructor(){Do.constructor_.apply(this,arguments)}static constructor_(){if(this.x=null,this.y=null,this.w=null,arguments.length===0)this.x=0,this.y=0,this.w=1;else if(arguments.length===1){const t=arguments[0];this.x=t.x,this.y=t.y,this.w=1}else if(arguments.length===2){if(typeof arguments[0]=="number"&&typeof arguments[1]=="number"){const t=arguments[0],e=arguments[1];this.x=t,this.y=e,this.w=1}else if(arguments[0]instanceof Do&&arguments[1]instanceof Do){const t=arguments[0],e=arguments[1];this.x=t.y*e.w-e.y*t.w,this.y=e.x*t.w-t.x*e.w,this.w=t.x*e.y-e.x*t.y}else if(arguments[0]instanceof Q&&arguments[1]instanceof Q){const t=arguments[0],e=arguments[1];this.x=t.y-e.y,this.y=e.x-t.x,this.w=t.x*e.y-e.x*t.y}}else if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2];this.x=t,this.y=e,this.w=n}else if(arguments.length===4){const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3],s=t.y-e.y,o=e.x-t.x,a=t.x*e.y-e.x*t.y,l=n.y-r.y,h=r.x-n.x,f=n.x*r.y-r.x*n.y;this.x=o*f-h*a,this.y=l*a-s*f,this.w=s*h-l*o}}getY(){const t=this.y/this.w;if(Tt.isNaN(t)||Tt.isInfinite(t))throw new Tf;return t}getX(){const t=this.x/this.w;if(Tt.isNaN(t)||Tt.isInfinite(t))throw new Tf;return t}getCoordinate(){const t=new Q;return t.x=this.getX(),t.y=this.getY(),t}}class jn{constructor(){jn.constructor_.apply(this,arguments)}static constructor_(){this.p0=null,this.p1=null,this.p2=null;const t=arguments[0],e=arguments[1],n=arguments[2];this.p0=t,this.p1=e,this.p2=n}static area(t,e,n){return Math.abs(((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2)}static signedArea(t,e,n){return((n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y))/2}static det(t,e,n,r){return t*r-e*n}static interpolateZ(t,e,n,r){const s=e.x,o=e.y,a=n.x-s,l=r.x-s,h=n.y-o,f=r.y-o,d=a*f-l*h,p=t.x-s,y=t.y-o,_=(f*p-l*y)/d,E=(-h*p+a*y)/d;return e.getZ()+_*(n.getZ()-e.getZ())+E*(r.getZ()-e.getZ())}static longestSideLength(t,e,n){const r=t.distance(e),s=e.distance(n),o=n.distance(t);let a=r;return s>a&&(a=s),o>a&&(a=o),a}static circumcentreDD(t,e,n){const r=ht.valueOf(t.x).subtract(n.x),s=ht.valueOf(t.y).subtract(n.y),o=ht.valueOf(e.x).subtract(n.x),a=ht.valueOf(e.y).subtract(n.y),l=ht.determinant(r,s,o,a).multiply(2),h=r.sqr().add(s.sqr()),f=o.sqr().add(a.sqr()),d=ht.determinant(s,h,a,f),p=ht.determinant(r,h,o,f),y=ht.valueOf(n.x).subtract(d.divide(l)).doubleValue(),_=ht.valueOf(n.y).add(p.divide(l)).doubleValue();return new Q(y,_)}static isAcute(t,e,n){return!(!ye.isAcute(t,e,n)||!ye.isAcute(e,n,t)||!ye.isAcute(n,t,e))}static circumcentre(t,e,n){const r=n.x,s=n.y,o=t.x-r,a=t.y-s,l=e.x-r,h=e.y-s,f=2*jn.det(o,a,l,h),d=jn.det(a,o*o+a*a,h,l*l+h*h),p=jn.det(o,o*o+a*a,l,l*l+h*h),y=r-d/f,_=s+p/f;return new Q(y,_)}static perpendicularBisector(t,e){const n=e.x-t.x,r=e.y-t.y,s=new Do(t.x+n/2,t.y+r/2,1),o=new Do(t.x-r+n/2,t.y+n+r/2,1);return new Do(s,o)}static angleBisector(t,e,n){const r=e.distance(t),s=e.distance(n),o=r/(r+s),a=n.x-t.x,l=n.y-t.y;return new Q(t.x+o*a,t.y+o*l)}static area3D(t,e,n){const r=e.x-t.x,s=e.y-t.y,o=e.getZ()-t.getZ(),a=n.x-t.x,l=n.y-t.y,h=n.getZ()-t.getZ(),f=s*h-o*l,d=o*a-r*h,p=r*l-s*a,y=f*f+d*d+p*p;return Math.sqrt(y)/2}static centroid(t,e,n){const r=(t.x+e.x+n.x)/3,s=(t.y+e.y+n.y)/3;return new Q(r,s)}static inCentre(t,e,n){const r=e.distance(n),s=t.distance(n),o=t.distance(e),a=r+s+o,l=(r*t.x+s*e.x+o*n.x)/a,h=(r*t.y+s*e.y+o*n.y)/a;return new Q(l,h)}area(){return jn.area(this.p0,this.p1,this.p2)}signedArea(){return jn.signedArea(this.p0,this.p1,this.p2)}interpolateZ(t){if(t===null)throw new te("Supplied point is null.");return jn.interpolateZ(t,this.p0,this.p1,this.p2)}longestSideLength(){return jn.longestSideLength(this.p0,this.p1,this.p2)}isAcute(){return jn.isAcute(this.p0,this.p1,this.p2)}circumcentre(){return jn.circumcentre(this.p0,this.p1,this.p2)}area3D(){return jn.area3D(this.p0,this.p1,this.p2)}centroid(){return jn.centroid(this.p0,this.p1,this.p2)}inCentre(){return jn.inCentre(this.p0,this.p1,this.p2)}}class Jp{constructor(){Jp.constructor_.apply(this,arguments)}static constructor_(){this._inputGeom=null,this._distance=null,this._curveBuilder=null,this._curveList=new wt;const t=arguments[0],e=arguments[1],n=arguments[2];this._inputGeom=t,this._distance=e,this._curveBuilder=n}addRingSide(t,e,n,r,s){if(e===0&&t.length<gn.MINIMUM_VALID_SIZE)return null;let o=r,a=s;t.length>=gn.MINIMUM_VALID_SIZE&&$t.isCCW(t)&&(o=s,a=r,n=_t.opposite(n));const l=this._curveBuilder.getRingCurve(t,n,e);this.addCurve(l,o,a)}addRingBothSides(t,e){this.addRingSide(t,e,_t.LEFT,z.EXTERIOR,z.INTERIOR),this.addRingSide(t,e,_t.RIGHT,z.INTERIOR,z.EXTERIOR)}addPoint(t){if(this._distance<=0)return null;const e=t.getCoordinates(),n=this._curveBuilder.getLineCurve(e,this._distance);this.addCurve(n,z.EXTERIOR,z.INTERIOR)}addPolygon(t){let e=this._distance,n=_t.LEFT;this._distance<0&&(e=-this._distance,n=_t.RIGHT);const r=t.getExteriorRing(),s=Ce.removeRepeatedPoints(r.getCoordinates());if(this._distance<0&&this.isErodedCompletely(r,this._distance)||this._distance<=0&&s.length<3)return null;this.addRingSide(s,e,n,z.EXTERIOR,z.INTERIOR);for(let o=0;o<t.getNumInteriorRing();o++){const a=t.getInteriorRingN(o),l=Ce.removeRepeatedPoints(a.getCoordinates());this._distance>0&&this.isErodedCompletely(a,-this._distance)||this.addRingSide(l,e,_t.opposite(n),z.INTERIOR,z.EXTERIOR)}}isTriangleErodedCompletely(t,e){const n=new jn(t[0],t[1],t[2]),r=n.inCentre();return dn.pointToSegment(r,n.p0,n.p1)<Math.abs(e)}addLineString(t){if(this._curveBuilder.isLineOffsetEmpty(this._distance))return null;const e=Ce.removeRepeatedPoints(t.getCoordinates());if(Ce.isRing(e)&&!this._curveBuilder.getBufferParameters().isSingleSided())this.addRingBothSides(e,this._distance);else{const n=this._curveBuilder.getLineCurve(e,this._distance);this.addCurve(n,z.EXTERIOR,z.INTERIOR)}}addCurve(t,e,n){if(t===null||t.length<2)return null;const r=new ts(t,new Ge(0,z.BOUNDARY,e,n));this._curveList.add(r)}getCurves(){return this.add(this._inputGeom),this._curveList}add(t){if(t.isEmpty())return null;if(t instanceof Te)this.addPolygon(t);else if(t instanceof he)this.addLineString(t);else if(t instanceof De)this.addPoint(t);else if(t instanceof Rr)this.addCollection(t);else if(t instanceof ur)this.addCollection(t);else if(t instanceof yi)this.addCollection(t);else if(t instanceof _e)this.addCollection(t);else throw new cr(t.getGeometryType())}isErodedCompletely(t,e){const n=t.getCoordinates();if(n.length<4)return e<0;if(n.length===4)return this.isTriangleErodedCompletely(n,e);const r=t.getEnvelopeInternal(),s=Math.min(r.getHeight(),r.getWidth());return e<0&&2*Math.abs(e)>s}addCollection(t){for(let e=0;e<t.getNumGeometries();e++){const n=t.getGeometryN(e);this.add(n)}}}class tb{locate(t){}}class Va{constructor(){Va.constructor_.apply(this,arguments)}static constructor_(){this._parent=null,this._atStart=null,this._max=null,this._index=null,this._subcollectionIterator=null;const t=arguments[0];this._parent=t,this._atStart=!0,this._index=0,this._max=t.getNumGeometries()}static isAtomic(t){return!(t instanceof _e)}next(){if(this._atStart)return this._atStart=!1,Va.isAtomic(this._parent)&&this._index++,this._parent;if(this._subcollectionIterator!==null){if(this._subcollectionIterator.hasNext())return this._subcollectionIterator.next();this._subcollectionIterator=null}if(this._index>=this._max)throw new Ol;const t=this._parent.getGeometryN(this._index++);return t instanceof _e?(this._subcollectionIterator=new Va(t),this._subcollectionIterator.next()):t}remove(){throw new cr(this.getClass().getName())}hasNext(){if(this._atStart)return!0;if(this._subcollectionIterator!==null){if(this._subcollectionIterator.hasNext())return!0;this._subcollectionIterator=null}return!(this._index>=this._max)}get interfaces_(){return[r8]}}class Hi{constructor(){Hi.constructor_.apply(this,arguments)}static constructor_(){this._geom=null;const t=arguments[0];this._geom=t}static locatePointInPolygon(t,e){if(e.isEmpty())return z.EXTERIOR;const n=e.getExteriorRing(),r=Hi.locatePointInRing(t,n);if(r!==z.INTERIOR)return r;for(let s=0;s<e.getNumInteriorRing();s++){const o=e.getInteriorRingN(s),a=Hi.locatePointInRing(t,o);if(a===z.BOUNDARY)return z.BOUNDARY;if(a===z.INTERIOR)return z.EXTERIOR}return z.INTERIOR}static locatePointInRing(t,e){return e.getEnvelopeInternal().intersects(t)?ar.locateInRing(t,e.getCoordinates()):z.EXTERIOR}static containsPointInPolygon(t,e){return z.EXTERIOR!==Hi.locatePointInPolygon(t,e)}static locateInGeometry(t,e){if(e instanceof Te)return Hi.locatePointInPolygon(t,e);if(e instanceof _e){const n=new Va(e);for(;n.hasNext();){const r=n.next();if(r!==e){const s=Hi.locateInGeometry(t,r);if(s!==z.EXTERIOR)return s}}}return z.EXTERIOR}static isContained(t,e){return z.EXTERIOR!==Hi.locate(t,e)}static locate(t,e){return e.isEmpty()||!e.getEnvelopeInternal().intersects(t)?z.EXTERIOR:Hi.locateInGeometry(t,e)}locate(t){return Hi.locate(t,this._geom)}get interfaces_(){return[tb]}}class Nd{constructor(){Nd.constructor_.apply(this,arguments)}static constructor_(){this._edgeMap=new ss,this._edgeList=null,this._ptInAreaLocation=[z.NONE,z.NONE]}getNextCW(t){this.getEdges();const e=this._edgeList.indexOf(t);let n=e-1;return e===0&&(n=this._edgeList.size()-1),this._edgeList.get(n)}propagateSideLabels(t){let e=z.NONE;for(let r=this.iterator();r.hasNext();){const o=r.next().getLabel();o.isArea(t)&&o.getLocation(t,_t.LEFT)!==z.NONE&&(e=o.getLocation(t,_t.LEFT))}if(e===z.NONE)return null;let n=e;for(let r=this.iterator();r.hasNext();){const s=r.next(),o=s.getLabel();if(o.getLocation(t,_t.ON)===z.NONE&&o.setLocation(t,_t.ON,n),o.isArea(t)){const a=o.getLocation(t,_t.LEFT),l=o.getLocation(t,_t.RIGHT);if(l!==z.NONE){if(l!==n)throw new Fi("side location conflict",s.getCoordinate());a===z.NONE&&Yt.shouldNeverReachHere("found single null side (at "+s.getCoordinate()+")"),n=a}else Yt.isTrue(o.getLocation(t,_t.LEFT)===z.NONE,"found single null side"),o.setLocation(t,_t.RIGHT,n),o.setLocation(t,_t.LEFT,n)}}}getCoordinate(){const t=this.iterator();return t.hasNext()?t.next().getCoordinate():null}print(t){pi.out.println("EdgeEndStar: "+this.getCoordinate());for(let e=this.iterator();e.hasNext();)e.next().print(t)}isAreaLabelsConsistent(t){return this.computeEdgeEndLabels(t.getBoundaryNodeRule()),this.checkAreaLabelsConsistent(0)}checkAreaLabelsConsistent(t){const e=this.getEdges();if(e.size()<=0)return!0;const n=e.size()-1,s=e.get(n).getLabel().getLocation(t,_t.LEFT);Yt.isTrue(s!==z.NONE,"Found unlabelled area edge");let o=s;for(let a=this.iterator();a.hasNext();){const h=a.next().getLabel();Yt.isTrue(h.isArea(t),"Found non-area edge");const f=h.getLocation(t,_t.LEFT),d=h.getLocation(t,_t.RIGHT);if(f===d||d!==o)return!1;o=f}return!0}findIndex(t){this.iterator();for(let e=0;e<this._edgeList.size();e++)if(this._edgeList.get(e)===t)return e;return-1}iterator(){return this.getEdges().iterator()}getEdges(){return this._edgeList===null&&(this._edgeList=new wt(this._edgeMap.values())),this._edgeList}getLocation(t,e,n){return this._ptInAreaLocation[t]===z.NONE&&(this._ptInAreaLocation[t]=Hi.locate(e,n[t].getGeometry())),this._ptInAreaLocation[t]}toString(){const t=new Zu;t.append("EdgeEndStar: "+this.getCoordinate()),t.append(`
25
25
  `);for(let e=this.iterator();e.hasNext();){const n=e.next();t.append(n),t.append(`
26
- `)}return t.toString()}computeEdgeEndLabels(t){for(let e=this.iterator();e.hasNext();)e.next().computeLabel(t)}computeLabelling(t){this.computeEdgeEndLabels(t[0].getBoundaryNodeRule()),this.propagateSideLabels(0),this.propagateSideLabels(1);const e=[!1,!1];for(let n=this.iterator();n.hasNext();){const s=n.next().getLabel();for(let o=0;o<2;o++)s.isLine(o)&&s.getLocation(o)===z.BOUNDARY&&(e[o]=!0)}for(let n=this.iterator();n.hasNext();){const r=n.next(),s=r.getLabel();for(let o=0;o<2;o++)if(s.isAnyNull(o)){let a=z.NONE;if(e[o])a=z.EXTERIOR;else{const l=r.getCoordinate();a=this.getLocation(o,l,t)}s.setAllLocationsIfNull(o,a)}}}getDegree(){return this._edgeMap.size()}insertEdgeEnd(t,e){this._edgeMap.put(t,e),this._edgeList=null}}class Qp extends Nd{constructor(){super(),Qp.constructor_.apply(this,arguments)}static constructor_(){this._resultAreaEdgeList=null,this._label=null,this._SCANNING_FOR_INCOMING=1,this._LINKING_TO_OUTGOING=2}linkResultDirectedEdges(){this.getResultAreaEdges();let t=null,e=null,n=this._SCANNING_FOR_INCOMING;for(let r=0;r<this._resultAreaEdgeList.size();r++){const s=this._resultAreaEdgeList.get(r),o=s.getSym();if(s.getLabel().isArea())switch(t===null&&s.isInResult()&&(t=s),n){case this._SCANNING_FOR_INCOMING:if(!o.isInResult())continue;e=o,n=this._LINKING_TO_OUTGOING;break;case this._LINKING_TO_OUTGOING:if(!s.isInResult())continue;e.setNext(s),n=this._SCANNING_FOR_INCOMING;break}}if(n===this._LINKING_TO_OUTGOING){if(t===null)throw new Fi("no outgoing dirEdge found",this.getCoordinate());Yt.isTrue(t.isInResult(),"unable to link last incoming dirEdge"),e.setNext(t)}}insert(t){const e=t;this.insertEdgeEnd(e,e)}getRightmostEdge(){const t=this.getEdges(),e=t.size();if(e<1)return null;const n=t.get(0);if(e===1)return n;const r=t.get(e-1),s=n.getQuadrant(),o=r.getQuadrant();return Le.isNorthern(s)&&Le.isNorthern(o)?n:!Le.isNorthern(s)&&!Le.isNorthern(o)?r:n.getDy()!==0?n:r.getDy()!==0?r:(Yt.shouldNeverReachHere("found two horizontal edges incident on node"),null)}print(t){pi.out.println("DirectedEdgeStar: "+this.getCoordinate());for(let e=this.iterator();e.hasNext();){const n=e.next();t.print("out "),n.print(t),t.println(),t.print("in "),n.getSym().print(t),t.println()}}getResultAreaEdges(){if(this._resultAreaEdgeList!==null)return this._resultAreaEdgeList;this._resultAreaEdgeList=new wt;for(let t=this.iterator();t.hasNext();){const e=t.next();(e.isInResult()||e.getSym().isInResult())&&this._resultAreaEdgeList.add(e)}return this._resultAreaEdgeList}updateLabelling(t){for(let e=this.iterator();e.hasNext();){const r=e.next().getLabel();r.setAllLocationsIfNull(0,t.getLocation(0)),r.setAllLocationsIfNull(1,t.getLocation(1))}}linkAllDirectedEdges(){this.getEdges();let t=null,e=null;for(let n=this._edgeList.size()-1;n>=0;n--){const r=this._edgeList.get(n),s=r.getSym();e===null&&(e=s),t!==null&&s.setNext(t),t=r}e.setNext(t)}computeDepths(){if(arguments.length===1){const t=arguments[0],e=this.findIndex(t),n=t.getDepth(_t.LEFT),r=t.getDepth(_t.RIGHT),s=this.computeDepths(e+1,this._edgeList.size(),n);if(this.computeDepths(0,e,s)!==r)throw new Fi("depth mismatch at "+t.getCoordinate())}else if(arguments.length===3){const t=arguments[0],e=arguments[1];let r=arguments[2];for(let s=t;s<e;s++){const o=this._edgeList.get(s);o.setEdgeDepths(_t.RIGHT,r),r=o.getDepth(_t.LEFT)}return r}}mergeSymLabels(){for(let t=this.iterator();t.hasNext();){const e=t.next();e.getLabel().merge(e.getSym().getLabel())}}linkMinimalDirectedEdges(t){let e=null,n=null,r=this._SCANNING_FOR_INCOMING;for(let s=this._resultAreaEdgeList.size()-1;s>=0;s--){const o=this._resultAreaEdgeList.get(s),a=o.getSym();switch(e===null&&o.getEdgeRing()===t&&(e=o),r){case this._SCANNING_FOR_INCOMING:if(a.getEdgeRing()!==t)continue;n=a,r=this._LINKING_TO_OUTGOING;break;case this._LINKING_TO_OUTGOING:if(o.getEdgeRing()!==t)continue;n.setNextMin(o),r=this._SCANNING_FOR_INCOMING;break}}r===this._LINKING_TO_OUTGOING&&(Yt.isTrue(e!==null,"found null for first outgoing dirEdge"),Yt.isTrue(e.getEdgeRing()===t,"unable to link last incoming dirEdge"),n.setNextMin(e))}getOutgoingDegree(){if(arguments.length===0){let t=0;for(let e=this.iterator();e.hasNext();)e.next().isInResult()&&t++;return t}else if(arguments.length===1){const t=arguments[0];let e=0;for(let n=this.iterator();n.hasNext();)n.next().getEdgeRing()===t&&e++;return e}}getLabel(){return this._label}findCoveredLineEdges(){let t=z.NONE;for(let n=this.iterator();n.hasNext();){const r=n.next(),s=r.getSym();if(!r.isLineEdge()){if(r.isInResult()){t=z.INTERIOR;break}if(s.isInResult()){t=z.EXTERIOR;break}}}if(t===z.NONE)return null;let e=t;for(let n=this.iterator();n.hasNext();){const r=n.next(),s=r.getSym();r.isLineEdge()?r.getEdge().setCovered(e===z.INTERIOR):(r.isInResult()&&(e=z.EXTERIOR),s.isInResult()&&(e=z.INTERIOR))}}computeLabelling(t){super.computeLabelling.call(this,t),this._label=new Ge(z.NONE);for(let e=this.iterator();e.hasNext();){const s=e.next().getEdge().getLabel();for(let o=0;o<2;o++){const a=s.getLocation(o);(a===z.INTERIOR||a===z.BOUNDARY)&&this._label.setLocation(o,z.INTERIOR)}}}}class t0 extends Vp{constructor(){super()}createNode(t){return new bs(t,new Qp)}}class Wa{constructor(){Wa.constructor_.apply(this,arguments)}static constructor_(){this._pts=null,this._orientation=null;const t=arguments[0];this._pts=t,this._orientation=Wa.orientation(t)}static orientation(t){return Ce.increasingDirection(t)===1}static compareOriented(t,e,n,r){const s=e?1:-1,o=r?1:-1,a=e?t.length:-1,l=r?n.length:-1;let h=e?0:t.length-1,f=r?0:n.length-1;for(;;){const d=t[h].compareTo(n[f]);if(d!==0)return d;h+=s,f+=o;const p=h===a,y=f===l;if(p&&!y)return-1;if(!p&&y)return 1;if(p&&y)return 0}}compareTo(t){const e=t;return Wa.compareOriented(this._pts,this._orientation,e._pts,e._orientation)}get interfaces_(){return[Ei]}}class Ld{constructor(){Ld.constructor_.apply(this,arguments)}static constructor_(){this._edges=new wt,this._ocaMap=new ss}print(t){t.print("MULTILINESTRING ( ");for(let e=0;e<this._edges.size();e++){const n=this._edges.get(e);e>0&&t.print(","),t.print("(");const r=n.getCoordinates();for(let s=0;s<r.length;s++)s>0&&t.print(","),t.print(r[s].x+" "+r[s].y);t.println(")")}t.print(") ")}addAll(t){for(let e=t.iterator();e.hasNext();)this.add(e.next())}findEdgeIndex(t){for(let e=0;e<this._edges.size();e++)if(this._edges.get(e).equals(t))return e;return-1}iterator(){return this._edges.iterator()}getEdges(){return this._edges}get(t){return this._edges.get(t)}findEqualEdge(t){const e=new Wa(t.getCoordinates());return this._ocaMap.get(e)}add(t){this._edges.add(t);const e=new Wa(t.getCoordinates());this._ocaMap.put(e,t)}}let e0=class{processIntersections(t,e,n,r){}isDone(){}};class Rf{constructor(){Rf.constructor_.apply(this,arguments)}static constructor_(){this._hasIntersection=!1,this._hasProper=!1,this._hasProperInterior=!1,this._hasInterior=!1,this._properIntersectionPoint=null,this._li=null,this._isSelfIntersection=null,this.numIntersections=0,this.numInteriorIntersections=0,this.numProperIntersections=0,this.numTests=0;const t=arguments[0];this._li=t}static isAdjacentSegments(t,e){return Math.abs(t-e)===1}isTrivialIntersection(t,e,n,r){if(t===n&&this._li.getIntersectionNum()===1){if(Rf.isAdjacentSegments(e,r))return!0;if(t.isClosed()){const s=t.size()-1;if(e===0&&r===s||r===0&&e===s)return!0}}return!1}getProperIntersectionPoint(){return this._properIntersectionPoint}hasProperInteriorIntersection(){return this._hasProperInterior}getLineIntersector(){return this._li}hasProperIntersection(){return this._hasProper}processIntersections(t,e,n,r){if(t===n&&e===r)return null;this.numTests++;const s=t.getCoordinates()[e],o=t.getCoordinates()[e+1],a=n.getCoordinates()[r],l=n.getCoordinates()[r+1];this._li.computeIntersection(s,o,a,l),this._li.hasIntersection()&&(this.numIntersections++,this._li.isInteriorIntersection()&&(this.numInteriorIntersections++,this._hasInterior=!0),this.isTrivialIntersection(t,e,n,r)||(this._hasIntersection=!0,t.addIntersections(this._li,e,0),n.addIntersections(this._li,r,1),this._li.isProper()&&(this.numProperIntersections++,this._hasProper=!0,this._hasProperInterior=!0)))}hasIntersection(){return this._hasIntersection}isDone(){return!1}hasInteriorIntersection(){return this._hasInterior}get interfaces_(){return[e0]}}class n0{constructor(){n0.constructor_.apply(this,arguments)}static constructor_(){this.coord=null,this.segmentIndex=null,this.dist=null;const t=arguments[0],e=arguments[1],n=arguments[2];this.coord=new Q(t),this.segmentIndex=e,this.dist=n}getSegmentIndex(){return this.segmentIndex}getCoordinate(){return this.coord}print(t){t.print(this.coord),t.print(" seg # = "+this.segmentIndex),t.println(" dist = "+this.dist)}compareTo(t){const e=t;return this.compare(e.segmentIndex,e.dist)}isEndPoint(t){return this.segmentIndex===0&&this.dist===0||this.segmentIndex===t}toString(){return this.coord+" seg # = "+this.segmentIndex+" dist = "+this.dist}getDistance(){return this.dist}compare(t,e){return this.segmentIndex<t?-1:this.segmentIndex>t?1:this.dist<e?-1:this.dist>e?1:0}get interfaces_(){return[Ei]}}class i0{constructor(){i0.constructor_.apply(this,arguments)}static constructor_(){this._nodeMap=new ss,this.edge=null;const t=arguments[0];this.edge=t}print(t){t.println("Intersections:");for(let e=this.iterator();e.hasNext();)e.next().print(t)}iterator(){return this._nodeMap.values().iterator()}addSplitEdges(t){this.addEndpoints();const e=this.iterator();let n=e.next();for(;e.hasNext();){const r=e.next(),s=this.createSplitEdge(n,r);t.add(s),n=r}}addEndpoints(){const t=this.edge.pts.length-1;this.add(this.edge.pts[0],0,0),this.add(this.edge.pts[t],t,0)}createSplitEdge(t,e){let n=e.segmentIndex-t.segmentIndex+2;const r=this.edge.pts[e.segmentIndex],s=e.dist>0||!e.coord.equals2D(r);s||n--;const o=new Array(n).fill(null);let a=0;o[a++]=new Q(t.coord);for(let l=t.segmentIndex+1;l<=e.segmentIndex;l++)o[a++]=this.edge.pts[l];return s&&(o[a]=e.coord),new xr(o,new Ge(this.edge._label))}add(t,e,n){const r=new n0(t,e,n),s=this._nodeMap.get(r);return s!==null?s:(this._nodeMap.put(r,r),r)}isIntersection(t){for(let e=this.iterator();e.hasNext();)if(e.next().coord.equals(t))return!0;return!1}}class pe{constructor(){pe.constructor_.apply(this,arguments)}static constructor_(){if(this._matrix=null,arguments.length===0)this._matrix=Array(3).fill().map(()=>Array(3)),this.setAll(yt.FALSE);else if(arguments.length===1){if(typeof arguments[0]=="string"){const t=arguments[0];pe.constructor_.call(this),this.set(t)}else if(arguments[0]instanceof pe){const t=arguments[0];pe.constructor_.call(this),this._matrix[z.INTERIOR][z.INTERIOR]=t._matrix[z.INTERIOR][z.INTERIOR],this._matrix[z.INTERIOR][z.BOUNDARY]=t._matrix[z.INTERIOR][z.BOUNDARY],this._matrix[z.INTERIOR][z.EXTERIOR]=t._matrix[z.INTERIOR][z.EXTERIOR],this._matrix[z.BOUNDARY][z.INTERIOR]=t._matrix[z.BOUNDARY][z.INTERIOR],this._matrix[z.BOUNDARY][z.BOUNDARY]=t._matrix[z.BOUNDARY][z.BOUNDARY],this._matrix[z.BOUNDARY][z.EXTERIOR]=t._matrix[z.BOUNDARY][z.EXTERIOR],this._matrix[z.EXTERIOR][z.INTERIOR]=t._matrix[z.EXTERIOR][z.INTERIOR],this._matrix[z.EXTERIOR][z.BOUNDARY]=t._matrix[z.EXTERIOR][z.BOUNDARY],this._matrix[z.EXTERIOR][z.EXTERIOR]=t._matrix[z.EXTERIOR][z.EXTERIOR]}}}static matches(){if(Number.isInteger(arguments[0])&&typeof arguments[1]=="string"){const t=arguments[0],e=arguments[1];return e===yt.SYM_DONTCARE||e===yt.SYM_TRUE&&(t>=0||t===yt.TRUE)||e===yt.SYM_FALSE&&t===yt.FALSE||e===yt.SYM_P&&t===yt.P||e===yt.SYM_L&&t===yt.L||e===yt.SYM_A&&t===yt.A}else if(typeof arguments[0]=="string"&&typeof arguments[1]=="string"){const t=arguments[0],e=arguments[1];return new pe(t).matches(e)}}static isTrue(t){return t>=0||t===yt.TRUE}isIntersects(){return!this.isDisjoint()}isCovers(){return(pe.isTrue(this._matrix[z.INTERIOR][z.INTERIOR])||pe.isTrue(this._matrix[z.INTERIOR][z.BOUNDARY])||pe.isTrue(this._matrix[z.BOUNDARY][z.INTERIOR])||pe.isTrue(this._matrix[z.BOUNDARY][z.BOUNDARY]))&&this._matrix[z.EXTERIOR][z.INTERIOR]===yt.FALSE&&this._matrix[z.EXTERIOR][z.BOUNDARY]===yt.FALSE}isCoveredBy(){return(pe.isTrue(this._matrix[z.INTERIOR][z.INTERIOR])||pe.isTrue(this._matrix[z.INTERIOR][z.BOUNDARY])||pe.isTrue(this._matrix[z.BOUNDARY][z.INTERIOR])||pe.isTrue(this._matrix[z.BOUNDARY][z.BOUNDARY]))&&this._matrix[z.INTERIOR][z.EXTERIOR]===yt.FALSE&&this._matrix[z.BOUNDARY][z.EXTERIOR]===yt.FALSE}set(){if(arguments.length===1){const t=arguments[0];for(let e=0;e<t.length;e++){const n=Math.trunc(e/3),r=e%3;this._matrix[n][r]=yt.toDimensionValue(t.charAt(e))}}else if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2];this._matrix[t][e]=n}}isContains(){return pe.isTrue(this._matrix[z.INTERIOR][z.INTERIOR])&&this._matrix[z.EXTERIOR][z.INTERIOR]===yt.FALSE&&this._matrix[z.EXTERIOR][z.BOUNDARY]===yt.FALSE}setAtLeast(){if(arguments.length===1){const t=arguments[0];for(let e=0;e<t.length;e++){const n=Math.trunc(e/3),r=e%3;this.setAtLeast(n,r,yt.toDimensionValue(t.charAt(e)))}}else if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2];this._matrix[t][e]<n&&(this._matrix[t][e]=n)}}setAtLeastIfValid(t,e,n){t>=0&&e>=0&&this.setAtLeast(t,e,n)}isWithin(){return pe.isTrue(this._matrix[z.INTERIOR][z.INTERIOR])&&this._matrix[z.INTERIOR][z.EXTERIOR]===yt.FALSE&&this._matrix[z.BOUNDARY][z.EXTERIOR]===yt.FALSE}isTouches(t,e){return t>e?this.isTouches(e,t):t===yt.A&&e===yt.A||t===yt.L&&e===yt.L||t===yt.L&&e===yt.A||t===yt.P&&e===yt.A||t===yt.P&&e===yt.L?this._matrix[z.INTERIOR][z.INTERIOR]===yt.FALSE&&(pe.isTrue(this._matrix[z.INTERIOR][z.BOUNDARY])||pe.isTrue(this._matrix[z.BOUNDARY][z.INTERIOR])||pe.isTrue(this._matrix[z.BOUNDARY][z.BOUNDARY])):!1}isOverlaps(t,e){return t===yt.P&&e===yt.P||t===yt.A&&e===yt.A?pe.isTrue(this._matrix[z.INTERIOR][z.INTERIOR])&&pe.isTrue(this._matrix[z.INTERIOR][z.EXTERIOR])&&pe.isTrue(this._matrix[z.EXTERIOR][z.INTERIOR]):t===yt.L&&e===yt.L?this._matrix[z.INTERIOR][z.INTERIOR]===1&&pe.isTrue(this._matrix[z.INTERIOR][z.EXTERIOR])&&pe.isTrue(this._matrix[z.EXTERIOR][z.INTERIOR]):!1}isEquals(t,e){return t!==e?!1:pe.isTrue(this._matrix[z.INTERIOR][z.INTERIOR])&&this._matrix[z.INTERIOR][z.EXTERIOR]===yt.FALSE&&this._matrix[z.BOUNDARY][z.EXTERIOR]===yt.FALSE&&this._matrix[z.EXTERIOR][z.INTERIOR]===yt.FALSE&&this._matrix[z.EXTERIOR][z.BOUNDARY]===yt.FALSE}toString(){const t=new yd("123456789");for(let e=0;e<3;e++)for(let n=0;n<3;n++)t.setCharAt(3*e+n,yt.toDimensionSymbol(this._matrix[e][n]));return t.toString()}setAll(t){for(let e=0;e<3;e++)for(let n=0;n<3;n++)this._matrix[e][n]=t}get(t,e){return this._matrix[t][e]}transpose(){let t=this._matrix[1][0];return this._matrix[1][0]=this._matrix[0][1],this._matrix[0][1]=t,t=this._matrix[2][0],this._matrix[2][0]=this._matrix[0][2],this._matrix[0][2]=t,t=this._matrix[2][1],this._matrix[2][1]=this._matrix[1][2],this._matrix[1][2]=t,this}matches(t){if(t.length!==9)throw new te("Should be length 9: "+t);for(let e=0;e<3;e++)for(let n=0;n<3;n++)if(!pe.matches(this._matrix[e][n],t.charAt(3*e+n)))return!1;return!0}add(t){for(let e=0;e<3;e++)for(let n=0;n<3;n++)this.setAtLeast(e,n,t.get(e,n))}isDisjoint(){return this._matrix[z.INTERIOR][z.INTERIOR]===yt.FALSE&&this._matrix[z.INTERIOR][z.BOUNDARY]===yt.FALSE&&this._matrix[z.BOUNDARY][z.INTERIOR]===yt.FALSE&&this._matrix[z.BOUNDARY][z.BOUNDARY]===yt.FALSE}isCrosses(t,e){return t===yt.P&&e===yt.L||t===yt.P&&e===yt.A||t===yt.L&&e===yt.A?pe.isTrue(this._matrix[z.INTERIOR][z.INTERIOR])&&pe.isTrue(this._matrix[z.INTERIOR][z.EXTERIOR]):t===yt.L&&e===yt.P||t===yt.A&&e===yt.P||t===yt.A&&e===yt.L?pe.isTrue(this._matrix[z.INTERIOR][z.INTERIOR])&&pe.isTrue(this._matrix[z.EXTERIOR][z.INTERIOR]):t===yt.L&&e===yt.L?this._matrix[z.INTERIOR][z.INTERIOR]===0:!1}get interfaces_(){return[Tc]}}class Af{constructor(){Af.constructor_.apply(this,arguments)}static constructor_(){if(this._data=null,this._size=0,arguments.length===0)Af.constructor_.call(this,10);else if(arguments.length===1){const t=arguments[0];this._data=new Array(t).fill(null)}}size(){return this._size}addAll(t){if(t===null||t.length===0)return null;this.ensureCapacity(this._size+t.length),pi.arraycopy(t,0,this._data,this._size,t.length),this._size+=t.length}ensureCapacity(t){if(t<=this._data.length)return null;const e=Math.max(t,this._data.length*2);this._data=Ys.copyOf(this._data,e)}toArray(){const t=new Array(this._size).fill(null);return pi.arraycopy(this._data,0,t,0,this._size),t}add(t){this.ensureCapacity(this._size+1),this._data[this._size]=t,++this._size}}class r0{static toIntArray(t){const e=new Array(t.size()).fill(null);for(let n=0;n<e.length;n++)e[n]=t.get(n).intValue();return e}getChainStartIndices(t){let e=0;const n=new Af(Math.trunc(t.length/2));n.add(e);do{const r=this.findChainEnd(t,e);n.add(r),e=r}while(e<t.length-1);return n.toArray()}findChainEnd(t,e){const n=Le.quadrant(t[e],t[e+1]);let r=e+1;for(;r<t.length&&Le.quadrant(t[r-1],t[r])===n;)r++;return r-1}OLDgetChainStartIndices(t){let e=0;const n=new wt;n.add(e);do{const s=this.findChainEnd(t,e);n.add(s),e=s}while(e<t.length-1);return r0.toIntArray(n)}}class s0{constructor(){s0.constructor_.apply(this,arguments)}static constructor_(){this.e=null,this.pts=null,this.startIndex=null;const t=arguments[0];this.e=t,this.pts=t.getCoordinates();const e=new r0;this.startIndex=e.getChainStartIndices(this.pts)}getCoordinates(){return this.pts}getMaxX(t){const e=this.pts[this.startIndex[t]].x,n=this.pts[this.startIndex[t+1]].x;return e>n?e:n}getMinX(t){const e=this.pts[this.startIndex[t]].x,n=this.pts[this.startIndex[t+1]].x;return e<n?e:n}computeIntersectsForChain(){if(arguments.length===4){const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];this.computeIntersectsForChain(this.startIndex[t],this.startIndex[t+1],e,e.startIndex[n],e.startIndex[n+1],r)}else if(arguments.length===6){const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3],s=arguments[4],o=arguments[5];if(e-t===1&&s-r===1)return o.addIntersections(this.e,t,n.e,r),null;if(!this.overlaps(t,e,n,r,s))return null;const a=Math.trunc((t+e)/2),l=Math.trunc((r+s)/2);t<a&&(r<l&&this.computeIntersectsForChain(t,a,n,r,l,o),l<s&&this.computeIntersectsForChain(t,a,n,l,s,o)),a<e&&(r<l&&this.computeIntersectsForChain(a,e,n,r,l,o),l<s&&this.computeIntersectsForChain(a,e,n,l,s,o))}}overlaps(t,e,n,r,s){return ne.intersects(this.pts[t],this.pts[e],n.pts[r],n.pts[s])}getStartIndexes(){return this.startIndex}computeIntersects(t,e){for(let n=0;n<this.startIndex.length-1;n++)for(let r=0;r<t.startIndex.length-1;r++)this.computeIntersectsForChain(n,t,r,e)}}class yr{constructor(){yr.constructor_.apply(this,arguments)}static constructor_(){this._depth=Array(2).fill().map(()=>Array(3));for(let t=0;t<2;t++)for(let e=0;e<3;e++)this._depth[t][e]=yr.NULL_VALUE}static depthAtLocation(t){return t===z.EXTERIOR?0:t===z.INTERIOR?1:yr.NULL_VALUE}getDepth(t,e){return this._depth[t][e]}setDepth(t,e,n){this._depth[t][e]=n}isNull(){if(arguments.length===0){for(let t=0;t<2;t++)for(let e=0;e<3;e++)if(this._depth[t][e]!==yr.NULL_VALUE)return!1;return!0}else if(arguments.length===1){const t=arguments[0];return this._depth[t][1]===yr.NULL_VALUE}else if(arguments.length===2){const t=arguments[0],e=arguments[1];return this._depth[t][e]===yr.NULL_VALUE}}normalize(){for(let t=0;t<2;t++)if(!this.isNull(t)){let e=this._depth[t][1];this._depth[t][2]<e&&(e=this._depth[t][2]),e<0&&(e=0);for(let n=1;n<3;n++){let r=0;this._depth[t][n]>e&&(r=1),this._depth[t][n]=r}}}getDelta(t){return this._depth[t][_t.RIGHT]-this._depth[t][_t.LEFT]}getLocation(t,e){return this._depth[t][e]<=0?z.EXTERIOR:z.INTERIOR}toString(){return"A: "+this._depth[0][1]+","+this._depth[0][2]+" B: "+this._depth[1][1]+","+this._depth[1][2]}add(){if(arguments.length===1){const t=arguments[0];for(let e=0;e<2;e++)for(let n=1;n<3;n++){const r=t.getLocation(e,n);(r===z.EXTERIOR||r===z.INTERIOR)&&(this.isNull(e,n)?this._depth[e][n]=yr.depthAtLocation(r):this._depth[e][n]+=yr.depthAtLocation(r))}}else if(arguments.length===3){const t=arguments[0],e=arguments[1];arguments[2]===z.INTERIOR&&this._depth[t][e]++}}}yr.NULL_VALUE=-1;class xr extends Ed{constructor(){super(),xr.constructor_.apply(this,arguments)}static constructor_(){if(this.pts=null,this._env=null,this.eiList=new i0(this),this._name=null,this._mce=null,this._isIsolated=!0,this._depth=new yr,this._depthDelta=0,arguments.length===1){const t=arguments[0];xr.constructor_.call(this,t,null)}else if(arguments.length===2){const t=arguments[0],e=arguments[1];this.pts=t,this._label=e}}static updateIM(){if(arguments.length===2&&arguments[1]instanceof pe&&arguments[0]instanceof Ge){const t=arguments[0],e=arguments[1];e.setAtLeastIfValid(t.getLocation(0,_t.ON),t.getLocation(1,_t.ON),1),t.isArea()&&(e.setAtLeastIfValid(t.getLocation(0,_t.LEFT),t.getLocation(1,_t.LEFT),2),e.setAtLeastIfValid(t.getLocation(0,_t.RIGHT),t.getLocation(1,_t.RIGHT),2))}else return super.updateIM.apply(this,arguments)}getDepth(){return this._depth}getCollapsedEdge(){const t=new Array(2).fill(null);return t[0]=this.pts[0],t[1]=this.pts[1],new xr(t,Ge.toLineLabel(this._label))}isIsolated(){return this._isIsolated}getCoordinates(){return this.pts}setIsolated(t){this._isIsolated=t}setName(t){this._name=t}equals(t){if(!(t instanceof xr))return!1;const e=t;if(this.pts.length!==e.pts.length)return!1;let n=!0,r=!0,s=this.pts.length;for(let o=0;o<this.pts.length;o++)if(this.pts[o].equals2D(e.pts[o])||(n=!1),this.pts[o].equals2D(e.pts[--s])||(r=!1),!n&&!r)return!1;return!0}getCoordinate(){if(arguments.length===0)return this.pts.length>0?this.pts[0]:null;if(arguments.length===1){const t=arguments[0];return this.pts[t]}}print(t){t.print("edge "+this._name+": "),t.print("LINESTRING (");for(let e=0;e<this.pts.length;e++)e>0&&t.print(","),t.print(this.pts[e].x+" "+this.pts[e].y);t.print(") "+this._label+" "+this._depthDelta)}computeIM(t){xr.updateIM(this._label,t)}isCollapsed(){return!this._label.isArea()||this.pts.length!==3?!1:!!this.pts[0].equals(this.pts[2])}isClosed(){return this.pts[0].equals(this.pts[this.pts.length-1])}getMaximumSegmentIndex(){return this.pts.length-1}getDepthDelta(){return this._depthDelta}getNumPoints(){return this.pts.length}printReverse(t){t.print("edge "+this._name+": ");for(let e=this.pts.length-1;e>=0;e--)t.print(this.pts[e]+" ");t.println("")}getMonotoneChainEdge(){return this._mce===null&&(this._mce=new s0(this)),this._mce}getEnvelope(){if(this._env===null){this._env=new ne;for(let t=0;t<this.pts.length;t++)this._env.expandToInclude(this.pts[t])}return this._env}addIntersection(t,e,n,r){const s=new Q(t.getIntersection(r));let o=e,a=t.getEdgeDistance(n,r);const l=o+1;if(l<this.pts.length){const h=this.pts[l];s.equals2D(h)&&(o=l,a=0)}this.eiList.add(s,o,a)}toString(){const t=new yd;t.append("edge "+this._name+": "),t.append("LINESTRING (");for(let e=0;e<this.pts.length;e++)e>0&&t.append(","),t.append(this.pts[e].x+" "+this.pts[e].y);return t.append(") "+this._label+" "+this._depthDelta),t.toString()}isPointwiseEqual(t){if(this.pts.length!==t.pts.length)return!1;for(let e=0;e<this.pts.length;e++)if(!this.pts[e].equals2D(t.pts[e]))return!1;return!0}setDepthDelta(t){this._depthDelta=t}getEdgeIntersectionList(){return this.eiList}addIntersections(t,e,n){for(let r=0;r<t.getIntersectionNum();r++)this.addIntersection(t,e,n,r)}}class Ha{constructor(){Ha.constructor_.apply(this,arguments)}static constructor_(){this._bufParams=null,this._workingPrecisionModel=null,this._workingNoder=null,this._geomFact=null,this._graph=null,this._edgeList=new Ld;const t=arguments[0];this._bufParams=t}static depthDelta(t){const e=t.getLocation(0,_t.LEFT),n=t.getLocation(0,_t.RIGHT);return e===z.INTERIOR&&n===z.EXTERIOR?1:e===z.EXTERIOR&&n===z.INTERIOR?-1:0}static convertSegStrings(t){const e=new qe,n=new wt;for(;t.hasNext();){const r=t.next(),s=e.createLineString(r.getCoordinates());n.add(s)}return e.buildGeometry(n)}setWorkingPrecisionModel(t){this._workingPrecisionModel=t}insertUniqueEdge(t){const e=this._edgeList.findEqualEdge(t);if(e!==null){const n=e.getLabel();let r=t.getLabel();e.isPointwiseEqual(t)||(r=new Ge(t.getLabel()),r.flip()),n.merge(r);const s=Ha.depthDelta(r),a=e.getDepthDelta()+s;e.setDepthDelta(a)}else this._edgeList.add(t),t.setDepthDelta(Ha.depthDelta(t.getLabel()))}buildSubgraphs(t,e){const n=new wt;for(let r=t.iterator();r.hasNext();){const s=r.next(),o=s.getRightmostCoordinate(),l=new Sd(n).getDepth(o);s.computeDepth(l),s.findResultEdges(),n.add(s),e.add(s.getDirectedEdges(),s.getNodes())}}createSubgraphs(t){const e=new wt;for(let n=t.getNodes().iterator();n.hasNext();){const r=n.next();if(!r.isVisited()){const s=new Yp;s.create(r),e.add(s)}}return Is.sort(e,Is.reverseOrder()),e}createEmptyResultGeometry(){return this._geomFact.createPolygon()}getNoder(t){if(this._workingNoder!==null)return this._workingNoder;const e=new Fl,n=new Pn;return n.setPrecisionModel(t),e.setSegmentIntersector(new Rf(n)),e}buffer(t,e){let n=this._workingPrecisionModel;n===null&&(n=t.getPrecisionModel()),this._geomFact=t.getFactory();const r=new kf(n,this._bufParams),o=new Jp(t,e,r).getCurves();if(o.size()<=0)return this.createEmptyResultGeometry();this.computeNodedEdges(o,n),this._graph=new Jo(new t0),this._graph.addEdges(this._edgeList.getEdges());const a=this.createSubgraphs(this._graph),l=new tc(this._geomFact);this.buildSubgraphs(a,l);const h=l.getPolygons();return h.size()<=0?this.createEmptyResultGeometry():this._geomFact.buildGeometry(h)}computeNodedEdges(t,e){const n=this.getNoder(e);n.computeNodes(t);const r=n.getNodedSubstrings();for(let s=r.iterator();s.hasNext();){const o=s.next(),a=o.getCoordinates();if(a.length===2&&a[0].equals2D(a[1]))continue;const l=o.getData(),h=new xr(o.getCoordinates(),new Ge(l));this.insertUniqueEdge(h)}}setNoder(t){this._workingNoder=t}}class Of{constructor(){Of.constructor_.apply(this,arguments)}static constructor_(){if(this._noder=null,this._scaleFactor=null,this._offsetX=null,this._offsetY=null,this._isScaled=!1,arguments.length===2){const t=arguments[0],e=arguments[1];Of.constructor_.call(this,t,e,0,0)}else if(arguments.length===4){const t=arguments[0],e=arguments[1];this._noder=t,this._scaleFactor=e,this._isScaled=!this.isIntegerPrecision()}}rescale(){if(At(arguments[0],on)){const t=arguments[0];for(let e=t.iterator();e.hasNext();){const n=e.next();this.rescale(n.getCoordinates())}}else if(arguments[0]instanceof Array){const t=arguments[0];for(let e=0;e<t.length;e++)t[e].x=t[e].x/this._scaleFactor+this._offsetX,t[e].y=t[e].y/this._scaleFactor+this._offsetY;t.length===2&&t[0].equals2D(t[1])&&pi.out.println(t)}}scale(){if(At(arguments[0],on)){const t=arguments[0],e=new wt(t.size());for(let n=t.iterator();n.hasNext();){const r=n.next();e.add(new ts(this.scale(r.getCoordinates()),r.getData()))}return e}else if(arguments[0]instanceof Array){const t=arguments[0],e=new Array(t.length).fill(null);for(let r=0;r<t.length;r++)e[r]=new Q(Math.round((t[r].x-this._offsetX)*this._scaleFactor),Math.round((t[r].y-this._offsetY)*this._scaleFactor),t[r].getZ());return Ce.removeRepeatedPoints(e)}}isIntegerPrecision(){return this._scaleFactor===1}getNodedSubstrings(){const t=this._noder.getNodedSubstrings();return this._isScaled&&this.rescale(t),t}computeNodes(t){let e=t;this._isScaled&&(e=this.scale(t)),this._noder.computeNodes(e)}get interfaces_(){return[Zp]}}class nc{constructor(){nc.constructor_.apply(this,arguments)}static constructor_(){this._li=new Pn,this._segStrings=null;const t=arguments[0];this._segStrings=t}checkEndPtVertexIntersections(){if(arguments.length===0)for(let t=this._segStrings.iterator();t.hasNext();){const n=t.next().getCoordinates();this.checkEndPtVertexIntersections(n[0],this._segStrings),this.checkEndPtVertexIntersections(n[n.length-1],this._segStrings)}else if(arguments.length===2){const t=arguments[0],e=arguments[1];for(let n=e.iterator();n.hasNext();){const s=n.next().getCoordinates();for(let o=1;o<s.length-1;o++)if(s[o].equals(t))throw new mi("found endpt/interior pt intersection at index "+o+" :pt "+t)}}}checkInteriorIntersections(){if(arguments.length===0)for(let t=this._segStrings.iterator();t.hasNext();){const e=t.next();for(let n=this._segStrings.iterator();n.hasNext();){const r=n.next();this.checkInteriorIntersections(e,r)}}else if(arguments.length===2){const t=arguments[0],e=arguments[1],n=t.getCoordinates(),r=e.getCoordinates();for(let s=0;s<n.length-1;s++)for(let o=0;o<r.length-1;o++)this.checkInteriorIntersections(t,s,e,o)}else if(arguments.length===4){const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];if(t===n&&e===r)return null;const s=t.getCoordinates()[e],o=t.getCoordinates()[e+1],a=n.getCoordinates()[r],l=n.getCoordinates()[r+1];if(this._li.computeIntersection(s,o,a,l),this._li.hasIntersection()&&(this._li.isProper()||this.hasInteriorIntersection(this._li,s,o)||this.hasInteriorIntersection(this._li,a,l)))throw new mi("found non-noded intersection at "+s+"-"+o+" and "+a+"-"+l)}}checkValid(){this.checkEndPtVertexIntersections(),this.checkInteriorIntersections(),this.checkCollapses()}checkCollapses(){if(arguments.length===0)for(let t=this._segStrings.iterator();t.hasNext();){const e=t.next();this.checkCollapses(e)}else if(arguments.length===1){const e=arguments[0].getCoordinates();for(let n=0;n<e.length-2;n++)this.checkCollapse(e[n],e[n+1],e[n+2])}}hasInteriorIntersection(t,e,n){for(let r=0;r<t.getIntersectionNum();r++){const s=t.getIntersection(r);if(!(s.equals(e)||s.equals(n)))return!0}return!1}checkCollapse(t,e,n){if(t.equals(n))throw new mi("found non-noded collapse at "+nc.fact.createLineString([t,e,n]))}}nc.fact=new qe;class wl{constructor(){wl.constructor_.apply(this,arguments)}static constructor_(){this._li=null,this._pt=null,this._originalPt=null,this._ptScaled=null,this._p0Scaled=null,this._p1Scaled=null,this._scaleFactor=null,this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,this._corner=new Array(4).fill(null),this._safeEnv=null;const t=arguments[0],e=arguments[1],n=arguments[2];if(this._originalPt=t,this._pt=t,this._scaleFactor=e,this._li=n,e<=0)throw new te("Scale factor must be non-zero");e!==1&&(this._pt=new Q(this.scale(t.x),this.scale(t.y)),this._p0Scaled=new Q,this._p1Scaled=new Q),this.initCorners(this._pt)}intersectsScaled(t,e){const n=Math.min(t.x,e.x),r=Math.max(t.x,e.x),s=Math.min(t.y,e.y),o=Math.max(t.y,e.y),a=this._maxx<n||this._minx>r||this._maxy<s||this._miny>o;if(a)return!1;const l=this.intersectsToleranceSquare(t,e);return Yt.isTrue(!(a&&l),"Found bad envelope test"),l}initCorners(t){this._minx=t.x-.5,this._maxx=t.x+.5,this._miny=t.y-.5,this._maxy=t.y+.5,this._corner[0]=new Q(this._maxx,this._maxy),this._corner[1]=new Q(this._minx,this._maxy),this._corner[2]=new Q(this._minx,this._miny),this._corner[3]=new Q(this._maxx,this._miny)}intersects(t,e){return this._scaleFactor===1?this.intersectsScaled(t,e):(this.copyScaled(t,this._p0Scaled),this.copyScaled(e,this._p1Scaled),this.intersectsScaled(this._p0Scaled,this._p1Scaled))}scale(t){return Math.round(t*this._scaleFactor)}getCoordinate(){return this._originalPt}copyScaled(t,e){e.x=this.scale(t.x),e.y=this.scale(t.y)}getSafeEnvelope(){if(this._safeEnv===null){const t=wl.SAFE_ENV_EXPANSION_FACTOR/this._scaleFactor;this._safeEnv=new ne(this._originalPt.x-t,this._originalPt.x+t,this._originalPt.y-t,this._originalPt.y+t)}return this._safeEnv}intersectsPixelClosure(t,e){return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.hasIntersection())||(this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.hasIntersection())||(this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.hasIntersection()))}intersectsToleranceSquare(t,e){let n=!1,r=!1;return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.isProper()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.isProper())||(this._li.hasIntersection()&&(n=!0),this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.isProper())||(this._li.hasIntersection()&&(r=!0),this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.isProper())||n&&r||t.equals(this._pt)||e.equals(this._pt))}addSnappedNode(t,e){const n=t.getCoordinate(e),r=t.getCoordinate(e+1);return this.intersects(n,r)?(t.addIntersection(this.getCoordinate(),e),!0):!1}}wl.SAFE_ENV_EXPANSION_FACTOR=.75;class o0{constructor(){o0.constructor_.apply(this,arguments)}static constructor_(){this.selectedSegment=new Me}select(){if(arguments.length!==1){if(arguments.length===2){const t=arguments[0],e=arguments[1];t.getLineSegment(e,this.selectedSegment),this.select(this.selectedSegment)}}}}class Cd{constructor(){Cd.constructor_.apply(this,arguments)}static constructor_(){this._index=null;const t=arguments[0];this._index=t}snap(){if(arguments.length===1){const t=arguments[0];return this.snap(t,null,-1)}else if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2],r=t.getSafeEnvelope(),s=new Pd(t,e,n);return this._index.query(r,new class{get interfaces_(){return[wd]}visitItem(o){o.select(r,s)}}),s.isNodeAdded()}}}class Pd extends o0{constructor(){super(),Pd.constructor_.apply(this,arguments)}static constructor_(){this._hotPixel=null,this._parentEdge=null,this._hotPixelVertexIndex=null,this._isNodeAdded=!1;const t=arguments[0],e=arguments[1],n=arguments[2];this._hotPixel=t,this._parentEdge=e,this._hotPixelVertexIndex=n}isNodeAdded(){return this._isNodeAdded}select(){if(arguments.length===2&&Number.isInteger(arguments[1])&&arguments[0]instanceof Jx){const t=arguments[0],e=arguments[1],n=t.getContext();if(this._parentEdge===n&&(e===this._hotPixelVertexIndex||e+1===this._hotPixelVertexIndex))return null;this._isNodeAdded|=this._hotPixel.addSnappedNode(n,e)}else return super.select.apply(this,arguments)}}Cd.HotPixelSnapAction=Pd;class a0{constructor(){a0.constructor_.apply(this,arguments)}static constructor_(){this._li=null,this._interiorIntersections=null;const t=arguments[0];this._li=t,this._interiorIntersections=new wt}processIntersections(t,e,n,r){if(t===n&&e===r)return null;const s=t.getCoordinates()[e],o=t.getCoordinates()[e+1],a=n.getCoordinates()[r],l=n.getCoordinates()[r+1];if(this._li.computeIntersection(s,o,a,l),this._li.hasIntersection()&&this._li.isInteriorIntersection()){for(let h=0;h<this._li.getIntersectionNum();h++)this._interiorIntersections.add(this._li.getIntersection(h));t.addIntersections(this._li,e,0),n.addIntersections(this._li,r,1)}}isDone(){return!1}getInteriorIntersections(){return this._interiorIntersections}get interfaces_(){return[e0]}}class l0{constructor(){l0.constructor_.apply(this,arguments)}static constructor_(){this._pm=null,this._li=null,this._scaleFactor=null,this._noder=null,this._pointSnapper=null,this._nodedSegStrings=null;const t=arguments[0];this._pm=t,this._li=new Pn,this._li.setPrecisionModel(t),this._scaleFactor=t.getScale()}checkCorrectness(t){const e=ts.getNodedSubstrings(t),n=new nc(e);try{n.checkValid()}catch(r){if(r instanceof Tr)r.printStackTrace();else throw r}finally{}}getNodedSubstrings(){return ts.getNodedSubstrings(this._nodedSegStrings)}snapRound(t,e){const n=this.findInteriorIntersections(t,e);this.computeIntersectionSnaps(n),this.computeVertexSnaps(t)}findInteriorIntersections(t,e){const n=new a0(e);return this._noder.setSegmentIntersector(n),this._noder.computeNodes(t),n.getInteriorIntersections()}computeVertexSnaps(){if(At(arguments[0],on)){const t=arguments[0];for(let e=t.iterator();e.hasNext();){const n=e.next();this.computeVertexSnaps(n)}}else if(arguments[0]instanceof ts){const t=arguments[0],e=t.getCoordinates();for(let n=0;n<e.length;n++){const r=new wl(e[n],this._scaleFactor,this._li);this._pointSnapper.snap(r,t,n)&&t.addIntersection(e[n],n)}}}computeNodes(t){this._nodedSegStrings=t,this._noder=new Fl,this._pointSnapper=new Cd(this._noder.getIndex()),this.snapRound(t,this._li)}computeIntersectionSnaps(t){for(let e=t.iterator();e.hasNext();){const n=e.next(),r=new wl(n,this._scaleFactor,this._li);this._pointSnapper.snap(r)}}get interfaces_(){return[Zp]}}class wn{constructor(){wn.constructor_.apply(this,arguments)}static constructor_(){if(this._argGeom=null,this._distance=null,this._bufParams=new re,this._resultGeometry=null,this._saveException=null,arguments.length===1){const t=arguments[0];this._argGeom=t}else if(arguments.length===2){const t=arguments[0],e=arguments[1];this._argGeom=t,this._bufParams=e}}static bufferOp(){if(arguments.length===2){const t=arguments[0],e=arguments[1];return new wn(t).getResultGeometry(e)}else if(arguments.length===3){if(Number.isInteger(arguments[2])&&arguments[0]instanceof dt&&typeof arguments[1]=="number"){const t=arguments[0],e=arguments[1],n=arguments[2],r=new wn(t);return r.setQuadrantSegments(n),r.getResultGeometry(e)}else if(arguments[2]instanceof re&&arguments[0]instanceof dt&&typeof arguments[1]=="number"){const t=arguments[0],e=arguments[1],n=arguments[2];return new wn(t,n).getResultGeometry(e)}}else if(arguments.length===4){const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3],s=new wn(t);return s.setQuadrantSegments(n),s.setEndCapStyle(r),s.getResultGeometry(e)}}static precisionScaleFactor(t,e,n){const r=t.getEnvelopeInternal(),s=Vo.max(Math.abs(r.getMaxX()),Math.abs(r.getMaxY()),Math.abs(r.getMinX()),Math.abs(r.getMinY())),o=e>0?e:0,a=s+2*o,l=Math.trunc(Math.log(a)/Math.log(10)+1),h=n-l;return Math.pow(10,h)}bufferFixedPrecision(t){const e=new Of(new l0(new we(1)),t.getScale()),n=new Ha(this._bufParams);n.setWorkingPrecisionModel(t),n.setNoder(e),this._resultGeometry=n.buffer(this._argGeom,this._distance)}bufferReducedPrecision(){if(arguments.length===0){for(let t=wn.MAX_PRECISION_DIGITS;t>=0;t--){try{this.bufferReducedPrecision(t)}catch(e){if(e instanceof Fi)this._saveException=e;else throw e}finally{}if(this._resultGeometry!==null)return null}throw this._saveException}else if(arguments.length===1){const t=arguments[0],e=wn.precisionScaleFactor(this._argGeom,this._distance,t),n=new we(e);this.bufferFixedPrecision(n)}}computeGeometry(){if(this.bufferOriginalPrecision(),this._resultGeometry!==null)return null;const t=this._argGeom.getFactory().getPrecisionModel();t.getType()===we.FIXED?this.bufferFixedPrecision(t):this.bufferReducedPrecision()}setQuadrantSegments(t){this._bufParams.setQuadrantSegments(t)}bufferOriginalPrecision(){try{const t=new Ha(this._bufParams);this._resultGeometry=t.buffer(this._argGeom,this._distance)}catch(t){if(t instanceof mi)this._saveException=t;else throw t}finally{}}getResultGeometry(t){return this._distance=t,this.computeGeometry(),this._resultGeometry}setEndCapStyle(t){this._bufParams.setEndCapStyle(t)}}wn.CAP_ROUND=re.CAP_ROUND;wn.CAP_BUTT=re.CAP_FLAT;wn.CAP_FLAT=re.CAP_FLAT;wn.CAP_SQUARE=re.CAP_SQUARE;wn.MAX_PRECISION_DIGITS=12;const ps=1e-9,eb=10;function ir(i,t){return[i[0]-t[0],i[1]-t[1]]}function Ss(i){return Math.hypot(i[0],i[1])}function Ka(i){const t=Ss(i);return t<ps?[0,0]:[i[0]/t,i[1]/t]}function o8(i,t,e,n){const r=t[0]*n[1]-t[1]*n[0];if(Math.abs(r)<ps)return null;const s=((e[0]-i[0])*n[1]-(e[1]-i[1])*n[0])/r;return[i[0]+s*t[0],i[1]+s*t[1]]}function vv(i){return i.filter((t,e)=>e===0||Ss(ir(t,i[e-1]))>ps)}function a8(i,t,e=eb){const n=vv(i);if(n.length<2)return n;const r=[];for(let o=0;o<n.length-1;o++){const a=Ka(ir(n[o+1],n[o])),l=[a[1],-a[0]],h=[l[0]*t,l[1]*t];r.push({dir:a,start:[n[o][0]+h[0],n[o][1]+h[1]],end:[n[o+1][0]+h[0],n[o+1][1]+h[1]]})}const s=[r[0].start];for(let o=0;o<r.length-1;o++){const a=r[o],l=r[o+1],h=o8(a.start,a.dir,l.start,l.dir);h?Ss(ir(h,n[o+1]))>Math.abs(t)*e?s.push(a.end,l.start):s.push(h):s.push(a.end)}return s.push(r[r.length-1].end),vv(s)}function nb(i,t,e=eb){const n=new _d,r=new zx,s=new re;s.setJoinStyle(re.JOIN_MITRE),s.setMitreLimit(e);const o=wn.bufferOp(n.read(i),t,s);if(!o||o.isEmpty())return null;const a=r.write(o);return a.type!=="Polygon"&&a.type!=="MultiPolygon"?null:a}function ib(i,t,e,n,r=5){const s=ir(i,t),o=ir(e,t),a=Ss(s),l=Ss(o);if(n<=0||a<ps||l<ps)return null;const h=Ka(s),f=Ka(o),d=Math.max(-1,Math.min(1,h[0]*f[0]+h[1]*f[1])),p=Math.acos(d);if(p<1e-6||Math.PI-p<1e-6)return null;const y=n/Math.tan(p/2);if(y>a+ps||y>l+ps)return null;const _=[t[0]+h[0]*y,t[1]+h[1]*y],E=[t[0]+f[0]*y,t[1]+f[1]*y],w=Ka([h[0]+f[0],h[1]+f[1]]),L=n/Math.sin(p/2),b=[t[0]+w[0]*L,t[1]+w[1]*L],S=Math.atan2(_[1]-b[1],_[0]-b[0]);let N=Math.atan2(E[1]-b[1],E[0]-b[0])-S;for(;N>Math.PI;)N-=2*Math.PI;for(;N<-Math.PI;)N+=2*Math.PI;const C=Math.max(2,Math.ceil(Math.abs(N)/(r*Math.PI/180))),T=[_];for(let I=1;I<C;I++){const M=S+N*I/C;T.push([b[0]+n*Math.cos(M),b[1]+n*Math.sin(M)])}return T.push(E),{tangentStart:_,tangentEnd:E,center:b,points:T}}function l8(i,t,e){const n=Ss(ir(i,t)),r=Ss(ir(e,t)),s=Ka(ir(i,t)),o=Ka(ir(e,t)),a=Math.acos(Math.max(-1,Math.min(1,s[0]*o[0]+s[1]*o[1])));return a<1e-6||Math.PI-a<1e-6?0:Math.min(n,r)*Math.tan(a/2)}function u8(i,t,e){const n=-e*Math.PI/180,r=Math.cos(n),s=Math.sin(n),o=i[0]-t[0],a=i[1]-t[1];return[t[0]+o*r-a*s,t[1]+o*s+a*r]}function c8(i,t,e){return[t[0]+(i[0]-t[0])*e,t[1]+(i[1]-t[1])*e]}function h8(i,t,e){const n=ir(e,t),r=Ss(n);return r<ps?Ss(ir(i,t)):Math.abs(n[0]*(t[1]-i[1])-n[1]*(t[0]-i[0]))/r}function f8(i,t,e){const n=ir(e,t),r=n[0]*n[0]+n[1]*n[1];return r<ps?0:((i[0]-t[0])*n[0]+(i[1]-t[1])*n[1])/r}const Fm=.001;function ou(i,t,e){const n=Ue(i);return Cn(n,r=>{const s=t.toGeographic(e(t.toPlanar(r)));r[0]=s[0],r[1]=s[1]}),n}class ce{static splitSinglePolygonByLine(t,e){try{const n=ll(t);if(n){const r=Zo(e,n);if(r.features.length>=2){const s=[];for(const o of r.features){const a=o.geometry.coordinates;s.some(h=>{const f=h.geometry.coordinates;return Math.hypot(a[0]-f[0],a[1]-f[1])<1e-7})||s.push(o)}if(s.length>=2){let o=wh(n).features;for(const h of s){const f=[];for(const d of o){const p=_u(d,h);p&&p.features.length>0?f.push(...p.features):f.push(d)}o=f}let a=[e];for(const h of s){const f=[];for(const d of a){const p=_u(d,h);p&&p.features.length>0?f.push(...p.features):f.push(d)}a=f}const l=a.filter(h=>{const f=h.geometry.coordinates;if(f.length<2)return!1;const d=eT(h,dl(h)/2),p=r4(Lt(f[0]),Lt(f[f.length-1]));return Zt(d,t)||Zt(p,t)});if(l.length>0){const h=[...o,...l].filter(p=>dl(p,{units:"meters"})>=1e-4),f=le(h),d=E4(f);if(d.features.length>=2){const p=d.features.filter(y=>{ja(y);const _=h4(y);return(Zt(_,t)||Zt(Us(y),t))&&Xu(y)>.01});if(p.length>=2)return p}}}}}}catch{}try{const n=Gw(e,5e-5,{units:"meters"});if(!n)return null;const r=Oa(le([t,n]));if(!r)return null;const s=wh(r);return s.features.length<=1?null:s.features.map(o=>(ja(o),o))}catch{return null}}static splitPolygonByLine(t,e){try{if(e.geometry.coordinates.length<2)return null;const n=e;let r=[];t.geometry.type==="MultiPolygon"?r=wh(t).features:r=[t];const s=[];for(const o of r){const a=this.splitSinglePolygonByLine(o,n);a&&a.length>1?s.push(...a):s.push(o)}return s.length<=r.length?null:s.map(o=>this.cleanCollinearVertices(o))}catch(n){return console.error("splitPolygonByLine error:",n),null}}static connectLines(t,e=5,n=!0){if(t.length===0)return null;if(t.length===1)return t[0];const r=[...t],s=r.shift();let o=[...s.geometry.coordinates];for(;r.length>0;){const l=o[0],h=o[o.length-1];let f=-1,d=!1,p=!1;for(let E=0;E<r.length;E++){const w=r[E].geometry.coordinates,L=w[0],b=w[w.length-1];if(sn(Lt(h),Lt(L),{units:"meters"})<=e){f=E,d=!1,p=!1;break}if(sn(Lt(h),Lt(b),{units:"meters"})<=e){f=E,d=!0,p=!1;break}}if(f===-1)for(let E=0;E<r.length;E++){const w=r[E].geometry.coordinates,L=w[0],b=w[w.length-1];if(sn(Lt(b),Lt(l),{units:"meters"})<=e){f=E,d=!1,p=!0;break}if(sn(Lt(L),Lt(l),{units:"meters"})<=e){f=E,d=!0,p=!0;break}}if(f===-1)break;let _=[...r.splice(f,1)[0].geometry.coordinates];if(d&&_.reverse(),p){const E=_[_.length-1];sn(Lt(E),Lt(l),{units:"meters"})<=e&&_.pop(),o=[..._,...o]}else{const E=_[0];sn(Lt(h),Lt(E),{units:"meters"})<=e&&_.shift(),o=[...o,..._]}}return ae(o,s.properties)}static smoothLineBezier(t,e=32){const n=t.geometry.coordinates;if(n.length<3)return t;const r=TE(n,e);return ae(r,t.properties)}static extendLine(t,e=.05){const n=t.geometry.coordinates;if(n.length<2)return t;const r=n[0],s=n[n.length-1],o=al(Lt(n[n.length-2]),Lt(s)),a=al(Lt(n[1]),Lt(r)),l=ju(Lt(r),e,a).geometry.coordinates,h=ju(Lt(s),e,o).geometry.coordinates;return ae([l,...n,h])}static offset(t,e){if(!Number.isFinite(e)||e===0)return null;const n=me.forGeometries([t.geometry]);if(t.geometry.type==="LineString"){const r=t.geometry.coordinates.map(o=>n.toPlanar(o)),s=a8(r,e);return s.length<2?null:ae(s.map(o=>n.toGeographic(o)),t.properties)}if(t.geometry.type==="Polygon"){const r=nb(n.projectGeometry(t.geometry),e);return r?xn(n.unprojectGeometry(r),t.properties):null}return null}static rotate(t,e,n){const r=n||Us(t).geometry.coordinates,s=me.forCoordinate(r),o=s.toPlanar(r);return ou(t,s,a=>u8(a,o,e))}static scale(t,e,n){const r=n||Us(t).geometry.coordinates,s=me.forCoordinate(r),o=s.toPlanar(r);return ou(t,s,a=>c8(a,o,e))}static explode(t){const e=[];return t.geometry.type==="Polygon"?t.geometry.coordinates.forEach((n,r)=>{var s;e.push(ae(n,{...t.properties,ringIndex:r,name:`${((s=t.properties)==null?void 0:s.name)||"Polygon"} Ring ${r+1}`}))}):t.geometry.type==="MultiPolygon"&&t.geometry.coordinates.forEach((n,r)=>{n.forEach((s,o)=>{var a;e.push(ae(s,{...t.properties,polygonIndex:r,ringIndex:o,name:`${((a=t.properties)==null?void 0:a.name)||"Polygon"} ${r+1}.${o+1}`}))})}),e}static fillet(t,e,n=5){const r=this.getFilletCorner(t,e);if(!r)return null;const{coords:s,prev:o,curr:a,next:l,isPolygon:h,projection:f}=r,d=ib(f.toPlanar(o),f.toPlanar(a),f.toPlanar(l),n);if(!d)return null;const p=d.points.map(_=>f.toGeographic(_));if(h){const _=s.slice(0,-1);_.splice(e,1,...p),_.push(_[0]);const E=t.geometry.coordinates.slice(1);return Pe([_,...E],t.properties)}const y=[...s];return y.splice(e,1,...p),ae(y,t.properties)}static maxFilletRadius(t,e){const n=this.getFilletCorner(t,e);if(!n)return 0;const{prev:r,curr:s,next:o,projection:a}=n;return l8(a.toPlanar(r),a.toPlanar(s),a.toPlanar(o))}static getFilletCorner(t,e){const n=t.geometry.type==="Polygon";if(!n&&t.geometry.type!=="LineString")return null;const r=n?[...t.geometry.coordinates[0]]:[...t.geometry.coordinates],s=n?r.length-1:r.length;if(s<3||!Number.isInteger(e)||(n?e<0||e>=s:e<1||e>s-2))return null;const o=r[n?(e-1+s)%s:e-1],a=r[e],l=r[n?(e+1)%s:e+1],h=me.forCoordinate(a);return{coords:r,prev:o,curr:a,next:l,isPolygon:n,projection:h}}static translate(t,e,n){const r=n*Math.PI/180;return this.translateByMeters(t,e*Math.sin(r),e*Math.cos(r))}static translateByMeters(t,e,n){const r=me.forGeometries([t.geometry]);return ou(t,r,s=>[s[0]+e,s[1]+n])}static translateByVector(t,e,n){const r=me.forCoordinate(e),s=me.forCoordinate(n),o=r.toPlanar(e),a=s.toPlanar(n),l=Ue(t);return Cn(l,h=>{const f=r.toPlanar(h),d=s.toGeographic([a[0]+(f[0]-o[0]),a[1]+(f[1]-o[1])]);h[0]=d[0],h[1]=d[1]}),l}static align(t,e,n,r,s,o=!1){const a=me.forCoordinate(n),l=a.toPlanar(e),h=a.toPlanar(n);let f=0,d=1;if(r&&s){const _=a.toPlanar(r),E=a.toPlanar(s),w=Math.hypot(_[0]-l[0],_[1]-l[1]),L=Math.hypot(E[0]-h[0],E[1]-h[1]);if(w<1e-9||L<1e-9)throw new Error("Alignment points must be different.");f=Math.atan2(E[1]-h[1],E[0]-h[0])-Math.atan2(_[1]-l[1],_[0]-l[0]),o&&(d=L/w)}const p=Math.cos(f)*d,y=Math.sin(f)*d;return ou(t,a,_=>{const E=_[0]-l[0],w=_[1]-l[1];return[h[0]+E*p-w*y,h[1]+E*y+w*p]})}static mirror(t,e,n){const r=me.forCoordinate(e),s=r.toPlanar(e),o=r.toPlanar(n),a=o[0]-s[0],l=o[1]-s[1],h=a*a+l*l;if(h<1e-12)throw new Error("Mirror line needs two different points");const f=ou(t,r,y=>{const _=((y[0]-s[0])*a+(y[1]-s[1])*l)/h,E=s[0]+_*a,w=s[1]+_*l;return[2*E-y[0],2*w-y[1]]}),d=y=>y.forEach(_=>_.reverse()),p=f.geometry;return p.type==="Polygon"&&d(p.coordinates),p.type==="MultiPolygon"&&p.coordinates.forEach(d),f}static translateByOffset(t,e,n){const r=Ue(t);return Cn(r,s=>{s[0]+=e,s[1]+=n}),r}static difference(t,e){try{return Oa(le([t,e]))}catch(n){return console.error("CADOperations.difference error:",n),null}}static intersect(t,e){try{return xf(le([t,e]))}catch(n){return console.error("CADOperations.intersect error:",n),null}}static simplify(t,e=1e-4){return S4(t,{tolerance:e,highQuality:!0,mutate:!1})}static reverse(t){const e=Ue(t);return e.geometry.type==="LineString"?e.geometry.coordinates.reverse():e.geometry.type==="Polygon"&&e.geometry.coordinates.forEach(r=>{const s=r.slice(0,-1).reverse();s.push(s[0]);for(let o=0;o<r.length;o++)r[o]=s[o]}),e}static cloneFeature(t,e){const n=Ue(t);return e!==void 0&&(n.id=e),n}static snapVertices(t,e=Fm){if(t.length<2||!(e>0))return t.map(o=>Ue(o));const n=me.forGeometries(t.map(o=>o.geometry)),r=(o,a)=>`${Math.floor(o/e)}:${Math.floor(a/e)}`,s=new Map;return t.map(o=>{const a=Ue(o),l=[];return Cn(a,h=>{const f=n.toPlanar(h),d=Math.floor(f[0]/e),p=Math.floor(f[1]/e);let y=null,_=e;for(let E=-1;E<=1;E++)for(let w=-1;w<=1;w++)for(const L of s.get(`${d+E}:${p+w}`)||[]){const b=Math.hypot(L.planar[0]-f[0],L.planar[1]-f[1]);b<=_&&(_=b,y=L.coord)}y?(h[0]=y[0],h[1]=y[1]):l.push({planar:f,coord:[h[0],h[1]]})}),l.forEach(h=>{const f=r(h.planar[0],h.planar[1]),d=s.get(f);d?d.push(h):s.set(f,[h])}),a})}static cleanCollinearVertices(t,e=Fm){const n=Ue(t),r=me.forGeometries([t.geometry]),s=o=>{if(o.length<=4)return o;const a=o.slice(0,-1).map(f=>({coord:f,planar:r.toPlanar(f)}));let l=!0;for(;l&&a.length>3;){l=!1;for(let f=0;f<a.length&&a.length>3;f++){const d=a[(f-1+a.length)%a.length].planar,p=a[f].planar,y=a[(f+1)%a.length].planar,_=f8(p,d,y);_>0&&_<1&&h8(p,d,y)<=e&&(a.splice(f,1),f--,l=!0)}}const h=a.map(f=>f.coord);return h.push(h[0]),h};if(n.geometry.type==="Polygon"){const o=n.geometry.coordinates;n.geometry.coordinates=o.map(s)}else if(n.geometry.type==="MultiPolygon"){const o=n.geometry.coordinates;n.geometry.coordinates=o.map(a=>a.map(s))}return n}static splitOverlappingPolygons(t,e){try{if(!Yo(t,e))return null;const r=xf(le([t,e]));if(!r)return null;const s=Oa(le([t,e])),o=Oa(le([e,t])),a=d=>{if(!d)return[];const p=wh(d),y=[];for(const _ of p.features)ja(_),_.geometry&&_.geometry.type==="Polygon"&&y.push(_);return y},l=a(s),h=a(r),f=a(o);return{pieceA:l,overlap:h,pieceB:f}}catch(n){return console.error("splitOverlappingPolygons error:",n),null}}static splitLine(t,e){try{let n;if(Array.isArray(e)?n=Lt(e):n=e,n.geometry.type==="Point"){const r=vw(t,n),s=t.geometry.coordinates,o=s[0],a=s[s.length-1],l=sn(Lt(o),r,{units:"meters"}),h=sn(Lt(a),r,{units:"meters"});if(l<.5||h<.5)return null;const f=_u(t,r);if(f&&f.features.length>1)return f.features}else if(n.geometry.type==="LineString"){const r=_u(t,n);if(r&&r.features.length>1)return r.features}return null}catch(n){return console.error("splitLine error:",n),null}}}class rb extends no{constructor(){super();q(this,"layers",new Map);q(this,"tileLayers",new Map);q(this,"groups",new Map);q(this,"activeLayerId",null);q(this,"selectionStore",new Map);q(this,"transactions",new ix(50));q(this,"pendingChangedLayers",null)}emit(e,n){if(e==="features:changed"&&this.pendingChangedLayers){this.pendingChangedLayers.add(n.layerId);return}super.emit(e,n)}runTransaction(e,n){return this.withCoalescedEvents(()=>{this.transactions.beginGroup(e);try{const r=n();return this.transactions.commitGroup(),r}catch(r){throw this.transactions.rollbackGroup(),r}})}withCoalescedEvents(e){const n=this.pendingChangedLayers===null;n&&(this.pendingChangedLayers=new Set);try{return e()}finally{if(n){const r=this.pendingChangedLayers;this.pendingChangedLayers=null,r.forEach(s=>this.emit("features:changed",{layerId:s}))}}}addLayer(e,n=[]){if(e.color!==void 0&&!Vt.valid(e.color))throw new Xt(`Layer "${e.id}": "${e.color}" is not a colour.`);this.layers.has(e.id)&&(console.warn(`Layer with id "${e.id}" already exists. Replacing it.`),this.detachLayer(e.id,!0));const r=new dd(e,n);return this.layers.set(r.id,r),this.activeLayerId===null&&this.setActiveLayer(r.id),this.emit("layer:added",{layer:r}),r}removeLayer(e){return this.detachLayer(e,!1)}detachLayer(e,n){const r=this.layers.get(e);if(!r)return!1;if(r.pinned)return console.warn(`Layer "${e}" is pinned and cannot be removed.`),!1;if(this.layers.delete(e),this.selectionStore.delete(e),this.activeLayerId===e){const s=Array.from(this.layers.keys());this.setActiveLayer(s.length>0?s[0]:null)}return this.emit("layer:removed",{layerId:e,replaced:n}),!0}getLayer(e){return this.layers.get(e)}hasLayer(e){return this.layers.has(e)}getAllLayers(){return Array.from(this.layers.values()).sort((e,n)=>e.zIndex-n.zIndex)}addTileLayer(e){if(this.layers.has(e.id))throw new Xt(`"${e.id}" is already a feature layer. Tile layers and feature layers share one set of ids.`);this.tileLayers.has(e.id)&&(console.warn(`Tile layer with id "${e.id}" already exists. Replacing it.`),this.removeTileLayer(e.id));const n=new km(e);return this.tileLayers.set(n.id,n),this.emit("tile-layer:added",{layer:n}),n}getTileLayer(e){return this.tileLayers.get(e)}getTileLayers(){return Array.from(this.tileLayers.values()).sort((e,n)=>e.zIndex-n.zIndex)}removeTileLayer(e){const n=this.tileLayers.get(e);return n?n.pinned?(console.warn(`Tile layer "${e}" is pinned and cannot be removed.`),!1):(this.tileLayers.delete(e),this.emit("tile-layer:removed",{layerId:e}),!0):!1}setTileLayerStyles(e,n){const r=this.tileLayers.get(e);if(!r)throw new Xt(`Tile layer "${e}" not found`);if(r.kind!=="vector")throw new Xt(`"${e}" is a raster tile layer; only vector tiles are styled this way.`);r.styles=[...n],this.emit("tile-layer:updated",{layer:r})}getDisplayLayers(){return[...this.layers.values(),...this.tileLayers.values()].sort((e,n)=>e.zIndex-n.zIndex)}findAnyLayer(e){return this.layers.get(e)??this.tileLayers.get(e)}emitLayerChanged(e){e instanceof km?this.emit("tile-layer:updated",{layer:e}):this.emit("layer:updated",{layer:e})}setLayerVisibility(e,n){const r=this.findAnyLayer(e)??this.getLayerOrThrow(e);r.visible!==n&&(r.visible=n,this.emitLayerChanged(r))}setLayerOpacity(e,n){const r=this.findAnyLayer(e)??this.getLayerOrThrow(e),s=Math.max(0,Math.min(1,n));r.opacity!==s&&(r.opacity=s,this.emitLayerChanged(r))}setLayerZIndex(e,n){const r=this.findAnyLayer(e)??this.getLayerOrThrow(e);r.zIndex!==n&&(r.zIndex=n,this.emitLayerChanged(r))}reorderLayers(e){e.forEach((n,r)=>{const s=this.findAnyLayer(n);s&&(s.zIndex=r)}),this.getDisplayLayers().forEach(n=>this.emitLayerChanged(n))}setLayerPinned(e,n){const r=this.findAnyLayer(e)??this.getLayerOrThrow(e);r.pinned!==n&&(r.pinned=n,this.emitLayerChanged(r))}addLayerGroup(e){if(this.groups.has(e.id))throw new Error(`Layer group "${e.id}" already exists`);const n=e.parentId??null;if(n!==null&&!this.groups.has(n))throw new Error(`Layer group "${n}" not found`);const r={id:e.id,name:e.name??e.id,parentId:n,visible:e.visible??!0,expanded:e.expanded??!0};return this.groups.set(r.id,r),this.emit("group:added",{group:r}),r}getLayerGroup(e){return this.groups.get(e)}getLayerGroups(){return Array.from(this.groups.values())}removeLayerGroup(e){const n=this.groups.get(e);n&&(this.layers.forEach(r=>{r.groupId===e&&(r.groupId=n.parentId??void 0)}),this.groups.forEach(r=>{r.parentId===e&&(r.parentId=n.parentId)}),this.groups.delete(e),this.emit("group:removed",{groupId:e}),this.getAllLayers().forEach(r=>this.emit("layer:updated",{layer:r})))}updateLayerGroup(e,n){var o;const r=this.groups.get(e);if(!r)throw new Error(`Layer group "${e}" not found`);if(n.parentId!==void 0&&n.parentId!==null){if(!this.groups.has(n.parentId))throw new Error(`Layer group "${n.parentId}" not found`);for(let a=n.parentId;a;a=((o=this.groups.get(a))==null?void 0:o.parentId)??null)if(a===e)throw new Error(`Layer group "${e}" cannot be moved into itself`)}const s=n.visible!==void 0&&n.visible!==r.visible;Object.assign(r,Object.fromEntries(Object.entries(n).filter(([,a])=>a!==void 0))),this.emit("group:updated",{group:r}),(s||n.parentId!==void 0)&&this.getAllLayers().filter(a=>this.isLayerInGroup(a.id,e)).forEach(a=>this.emit("layer:updated",{layer:a}))}setLayerGroupVisibility(e,n){this.updateLayerGroup(e,{visible:n})}moveLayerToGroup(e,n){const r=this.findAnyLayer(e)??this.getLayerOrThrow(e);if(n!==null&&!this.groups.has(n))throw new Error(`Layer group "${n}" not found`);const s=n??void 0;r.groupId!==s&&(r.groupId=s,this.emitLayerChanged(r))}isLayerInGroup(e,n){var s,o;let r=((s=this.findAnyLayer(e))==null?void 0:s.groupId)??null;for(;r;){if(r===n)return!0;r=((o=this.groups.get(r))==null?void 0:o.parentId)??null}return!1}isLayerRendered(e){const n=this.findAnyLayer(e);if(!n||!n.visible)return!1;let r=n.groupId??null;for(;r;){const s=this.groups.get(r);if(!s)break;if(!s.visible)return!1;r=s.parentId}return!0}setActiveLayer(e){if(e!==null&&!this.layers.has(e))throw new um(e);this.activeLayerId!==e&&(this.activeLayerId=e,this.emit("active-layer:changed",{layerId:e}))}getActiveLayerId(){return this.activeLayerId}getActiveLayer(){return this.activeLayerId&&this.layers.get(this.activeLayerId)||null}selectFeature(e,n,r=!1){this.selectionStore.has(e)||this.selectionStore.set(e,new Set);const s=this.selectionStore.get(e);if(!r){for(const[o,a]of this.selectionStore.entries())o!==e&&a.size>0&&(a.clear(),this.emit("selection:changed",{layerId:o,featureIds:[]}));s.clear()}s.add(n),this.emit("selection:changed",{layerId:e,featureIds:Array.from(s)})}deselectFeature(e,n){const r=this.selectionStore.get(e);r&&r.delete(n)&&this.emit("selection:changed",{layerId:e,featureIds:Array.from(r)})}toggleFeatureSelection(e,n){const r=this.selectionStore.get(e);return r&&r.has(n)?(this.deselectFeature(e,n),!1):(this.selectFeature(e,n,!0),!0)}selectFeatures(e,n,r=!1){this.selectionStore.has(e)||this.selectionStore.set(e,new Set);const s=this.selectionStore.get(e);if(!r){for(const[o,a]of this.selectionStore.entries())o!==e&&a.size>0&&(a.clear(),this.emit("selection:changed",{layerId:o,featureIds:[]}));s.clear()}n.forEach(o=>s.add(o)),this.emit("selection:changed",{layerId:e,featureIds:Array.from(s)})}getSelectedCount(){let e=0;for(const n of this.selectionStore.values())e+=n.size;return e}clearSelection(e){if(e){const n=this.selectionStore.get(e);n&&n.size>0&&(n.clear(),this.emit("selection:changed",{layerId:e,featureIds:[]}))}else for(const[n,r]of this.selectionStore.entries())r.size>0&&(r.clear(),this.emit("selection:changed",{layerId:n,featureIds:[]}))}deselectAll(e){this.clearSelection(e)}getSelectedFeatureIds(e){return Array.from(this.selectionStore.get(e)||[])}getSelectedFeatures(e){const n=this.layers.get(e);if(!n)return[];const r=this.selectionStore.get(e);return!r||r.size===0?[]:Array.from(r).map(s=>n.getFeature(s)).filter(s=>!!s)}getAnySelectedFeature(){if(this.activeLayerId){const e=this.getSelectedFeatureIds(this.activeLayerId);if(e.length>0)return{layerId:this.activeLayerId,featureId:e[0]}}for(const[e,n]of this.selectionStore.entries())if(n.size>0){const r=n.values().next().value;if(r!==void 0)return{layerId:e,featureId:r}}return null}getAnySelectedFeatures(){if(this.activeLayerId){const e=this.getSelectedFeatureIds(this.activeLayerId);if(e.length>0)return{layerId:this.activeLayerId,featureIds:e}}for(const[e,n]of this.selectionStore.entries())if(n.size>0)return{layerId:e,featureIds:Array.from(n)};return null}addFeature(e,n,r=!0){const s=this.getLayerOrThrow(e),o=s.addFeature(n);if(r&&o.id!==void 0){const a=o.id;this.transactions.record({description:`Add feature to ${s.name}`,undo:()=>{this.removeFeature(e,a,!1)},redo:()=>{this.addFeature(e,o,!1)}})}return this.emit("feature:added",{layerId:e,feature:o}),this.emit("features:changed",{layerId:e}),o}addFeatures(e,n,r=!0){const s=this.getLayerOrThrow(e),o=s.addFeatures(n);if(r){const a=o.map(l=>l.id).filter(l=>l!==void 0);this.transactions.record({description:`Add ${o.length} features to ${s.name}`,undo:()=>{a.forEach(l=>s.removeFeature(l)),this.emit("features:changed",{layerId:e})},redo:()=>{s.addFeatures(o),this.emit("features:changed",{layerId:e})}})}return o.forEach(a=>this.emit("feature:added",{layerId:e,feature:a})),this.emit("features:changed",{layerId:e}),o}updateFeature(e,n,r=!0){const s=this.getLayerOrThrow(e);if(n.id===void 0||n.id===null)return!1;const o=s.getFeature(n.id);if(!o)return!1;const a=Ue(o),l=s.updateFeature(n);return l&&(r&&this.transactions.record({description:`Update feature ${n.id} in ${s.name}`,undo:()=>{this.updateFeature(e,a,!1)},redo:()=>{this.updateFeature(e,n,!1)}}),this.emit("feature:updated",{layerId:e,feature:n}),this.emit("features:changed",{layerId:e})),l}updateFeatureProperties(e,n,r,s=!0){const o=this.getLayerOrThrow(e),a=this.propertiesBefore(o,n,r);if(!a)return!1;const l=o.updateProperties(n,r);return l?(s&&this.transactions.record({description:`Edit attributes of feature ${n} in ${o.name}`,undo:()=>{this.updateFeatureProperties(e,n,a,!1)},redo:()=>{this.updateFeatureProperties(e,n,r,!1)}}),this.emit("feature:updated",{layerId:e,feature:l}),this.emit("features:changed",{layerId:e}),!0):!1}updateFeaturePropertiesBatch(e,n,r=!0,s){const o=this.getLayerOrThrow(e),a=[],l=[];return this.withCoalescedEvents(()=>{for(const{featureId:h,patch:f}of n){const d=this.propertiesBefore(o,h,f);d&&o.updateProperties(h,f)&&(a.push({featureId:h,patch:d}),l.push({featureId:h,patch:f}),this.emit("feature:updated",{layerId:e,feature:o.getFeature(h)}))}l.length&&this.emit("features:changed",{layerId:e})}),r&&l.length&&this.transactions.record({description:s??`Edit attributes of ${l.length} features in ${o.name}`,undo:()=>{this.updateFeaturePropertiesBatch(e,a,!1)},redo:()=>{this.updateFeaturePropertiesBatch(e,l,!1)}}),l.length}propertiesBefore(e,n,r){const s=e.getFeature(n);if(!s)return null;const o={};let a=!1;for(const[l,h]of Object.entries(r)){const f=!!s.properties&&Object.prototype.hasOwnProperty.call(s.properties,l),d=f?s.properties[l]:void 0;f&&d===h||!f&&h===void 0||(o[l]=d,a=!0)}return a?o:null}removeFeature(e,n,r=!0){const s=this.getLayerOrThrow(e),o=s.getFeature(n);if(!o)return!1;const a=Ue(o),l=s.removeFeature(n);return l&&(this.deselectFeature(e,n),r&&this.transactions.record({description:`Delete feature ${n} from ${s.name}`,undo:()=>{this.addFeature(e,a,!1)},redo:()=>{this.removeFeature(e,n,!1)}}),this.emit("feature:removed",{layerId:e,featureId:n}),this.emit("features:changed",{layerId:e})),l}getAvailableFeatureId(e,n){return this.getLayerOrThrow(e).getAvailableId(n)}getFeature(e,n){var r;return(r=this.layers.get(e))==null?void 0:r.getFeature(n)}buffer(e,n,r,s="meters",o){const a=this.getLayerOrThrow(e),l=a.getFeature(n);if(!l)throw new cm(n,e);const h=Gw(l,r,{units:s});h.properties={...l.properties,_bufferDistance:r,_bufferUnit:s};let f=o;if(f){const d=this.getLayerOrThrow(f);if(d.type!=="polygon")throw new Xt(`A buffer is a polygon; layer "${d.name}" is a ${d.type} layer and would not draw it.`)}else f=a.type==="polygon"?e:this.bufferLayerFor(a).id;return this.addFeature(f,h)}bufferLayerFor(e){let n=`${e.id}_buffer`;for(let r=2;this.layers.has(n)&&this.layers.get(n).type!=="polygon";r++)n=`${e.id}_buffer_${r}`;return this.layers.get(n)??this.addLayer({id:n,name:`${e.name} (buffer)`,type:"polygon",groupId:e.groupId})}calculateArea(e,n,r="sqm"){const s=this.getFeatureOrThrow(e,n),o=Xu(s);return r==="hectares"?o/1e4:r==="rai"?o/1600:o}calculateLength(e,n,r="meters"){const s=this.getFeatureOrThrow(e,n);return dl(s,{units:r})}union(e,n,r={}){const s=this.getLayerOrThrow(e),o=n.map(f=>s.getFeature(f)).filter(f=>!!(f&&(f.geometry.type==="Polygon"||f.geometry.type==="MultiPolygon")));if(o.length<2)throw new Rh("Union requires at least 2 polygon features");const a=ce.snapVertices(o,r.snapToleranceMeters),l=nx(le(a));if(!l)throw new Rh("Union produced an empty geometry");const h=ce.cleanCollinearVertices(l);return h.properties={...o[0].properties||{}},delete h.id,this.runTransaction(`Union ${o.length} polygons in ${s.name}`,()=>{o.forEach(d=>this.removeFeature(e,d.id));const f=this.addFeature(e,h);return f.id!==void 0&&this.selectFeature(e,f.id,!1),f})}splitOverlapping(e,n,r){const s=this.getLayerOrThrow(e),o=s.getFeature(n),a=s.getFeature(r);if(!o||!a)return null;const l=ce.splitOverlappingPolygons(o,a);return l?(this.runTransaction(`Split overlapping polygons ${n} and ${r} in ${s.name}`,()=>{this.removeFeature(e,n),this.removeFeature(e,r),l.pieceA.forEach((h,f)=>{h.id=this.getAvailableFeatureId(e,`${n}_part_${f+1}`),h.properties={...o.properties||{},_split:"A_minus_B"},this.addFeature(e,h)}),l.overlap.forEach((h,f)=>{var d,p;h.id=this.getAvailableFeatureId(e,`overlap_${n}_${r}_${f+1}`),h.properties={name:`Overlap (${((d=o.properties)==null?void 0:d.name)||n} & ${((p=a.properties)==null?void 0:p.name)||r})`,_split:"overlap"},this.addFeature(e,h)}),l.pieceB.forEach((h,f)=>{h.id=this.getAvailableFeatureId(e,`${r}_part_${f+1}`),h.properties={...a.properties||{},_split:"B_minus_A"},this.addFeature(e,h)})}),l):null}difference(e,n,r){const s=this.getLayerOrThrow(e),o=s.getFeature(n),a=s.getFeature(r);if(!o||!a)throw new Rh("Base and cut polygon features required");const l=Oa(le([o,a]));return l&&(l.id=n,l.properties={...o.properties},this.updateFeature(e,l)),l}getBoundingBox(e){if(e)return this.getLayerOrThrow(e).getBoundingBox();const n=this.getAllLayers();if(n.length===0)return[0,0,0,0];const r={type:"FeatureCollection",features:n.flatMap(s=>s.getFeatures())};return r.features.length===0?[0,0,0,0]:je(r)}undo(){const e=this.withCoalescedEvents(()=>this.transactions.undo());return e&&this.emit("transaction:undo",{description:e}),e}redo(){const e=this.withCoalescedEvents(()=>this.transactions.redo());return e&&this.emit("transaction:redo",{description:e}),e}canUndo(){return this.transactions.canUndo()}canRedo(){return this.transactions.canRedo()}getLayerOrThrow(e){const n=this.layers.get(e);if(!n)throw new um(e);return n}getFeatureOrThrow(e,n){const s=this.getLayerOrThrow(e).getFeature(n);if(!s)throw new cm(n,e);return s}}const tn=1e-9,Qi=Math.PI*2,Ms=.05,sb=2048,d8=1e-7,g8=1e3;function Qn(i,t){return[i[0]-t[0],i[1]-t[1]]}function ti(i){return Math.hypot(i[0],i[1])}function u0(i){const t=ti(i);return t<tn?[0,0]:[i[0]/t,i[1]/t]}function m8(i,t){return i[0]*t[0]+i[1]*t[1]}function $m(i,t){return i[0]*t[1]-i[1]*t[0]}function c0(i){return[-i[1],i[0]]}function h0(i,t,e){return[i[0]+t*Math.cos(e),i[1]+t*Math.sin(e)]}function p8(i,t){let e=(t-i)%Qi;return e>Math.PI&&(e-=Qi),e<=-Math.PI&&(e+=Qi),e}function ic(i,t,e){let n=(t-i)%Qi;return n<0&&(n+=Qi),e?n<tn&&(n=Qi):n=n===0?Qi:Qi-n,n}function ob(i){return h0(i.center,i.radius,i.startAngle)}function ab(i){return h0(i.center,i.radius,i.startAngle+i.sweep)}function kd(i,t){return h0(i.center,i.radius,i.startAngle+i.sweep*t)}function f0(i){return kd(i,.5)}function lb(i){return Math.abs(i.sweep)*i.radius}function y8(i){return 2*i.radius*Math.abs(Math.sin(i.sweep/2))}function ub(i,t){const e=i.startAngle+i.sweep*t,n=i.sweep>=0?1:-1;return[-Math.sin(e)*n,Math.cos(e)*n]}function _8(i){return i.sweep>0}function Td(i){return Math.tan(i.sweep/4)}function d0(i,t,e){if(!Number.isFinite(e)||Math.abs(e)<tn)return null;const n=4*Math.atan(e);return Rd(i,t,n)}function cb(i,t,e){const n=Qn(t,i),r=Qn(e,t),s=ti(n),o=ti(r);if(s<tn||o<tn)return null;const a=$m(n,r)/(s*o);if(Math.abs(a)<d8)return null;const l=2*$m(n,r),h=i[0]*i[0]+i[1]*i[1],f=t[0]*t[0]+t[1]*t[1],d=e[0]*e[0]+e[1]*e[1],p=[(h*(t[1]-e[1])+f*(e[1]-i[1])+d*(i[1]-t[1]))/l,(h*(e[0]-t[0])+f*(i[0]-e[0])+d*(t[0]-i[0]))/l],y=ti(Qn(i,p));if(!Number.isFinite(y)||y<tn)return null;const _=Math.atan2(i[1]-p[1],i[0]-p[0]),E=Math.atan2(t[1]-p[1],t[0]-p[0]),w=Math.atan2(e[1]-p[1],e[0]-p[0]),L=a>0,b=ic(_,E,L),S=ic(_,w,L);return S<b?null:{center:p,radius:y,startAngle:_,sweep:L?S:-S}}function v8(i,t,e,n=!0){const r=ti(Qn(i,t)),s=Qn(e,t);if(r<tn||ti(s)<tn)return null;const o=Math.atan2(i[1]-t[1],i[0]-t[0]),a=Math.atan2(s[1],s[0]),l=ic(o,a,n);return{center:t,radius:r,startAngle:o,sweep:n?l:-l}}function E8(i,t,e){const n=ti(Qn(i,t));if(n<tn||!Number.isFinite(e)||Math.abs(e)<tn)return null;const r=Math.sign(e)*Math.min(Math.abs(e),Qi);return{center:t,radius:n,startAngle:Math.atan2(i[1]-t[1],i[0]-t[0]),sweep:r}}function w8(i,t,e,n=!0){const r=ti(Qn(i,t));if(r<tn||!(e>tn)||e>2*r+tn)return null;const o=2*Math.asin(Math.min(1,e/(2*r)));return{center:t,radius:r,startAngle:Math.atan2(i[1]-t[1],i[0]-t[0]),sweep:n?o:-o}}function Rd(i,t,e){const n=Qn(t,i),r=ti(n);if(r<tn||!Number.isFinite(e))return null;const s=Math.sign(e)*Math.min(Math.abs(e),Qi-tn),o=s/2;if(Math.abs(Math.sin(o))<tn)return null;const a=Math.abs(r/(2*Math.sin(o))),l=r/2/Math.tan(o),h=c0(u0(n)),f=[(i[0]+t[0])/2+h[0]*l,(i[1]+t[1])/2+h[1]*l];return{center:f,radius:a,startAngle:Math.atan2(i[1]-f[1],i[0]-f[0]),sweep:s}}function x8(i,t,e,n={}){const{ccw:r=!0,major:s=!1}=n,o=Qn(t,i),a=ti(o);if(a<tn||!(e>0)||e<a/2-tn)return null;const l=Math.min(e,a/2),h=Math.sqrt(Math.max(0,e*e-l*l)),f=c0(u0(o)),d=r!==s?1:-1,p=[(i[0]+t[0])/2+f[0]*h*d,(i[1]+t[1])/2+f[1]*h*d],y=Math.atan2(i[1]-p[1],i[0]-p[0]),_=Math.atan2(t[1]-p[1],t[0]-p[0]),E=ic(y,_,r);return{center:p,radius:e,startAngle:y,sweep:r?E:-E}}function hb(i,t,e){const n=Qn(t,i),r=ti(n),s=u0(e);if(r<tn||ti(s)<tn)return null;let o=c0(s),a=m8(o,n);if(a<0&&(o=[-o[0],-o[1]],a=-a),a<r/(2*g8))return null;const l=r*r/(2*a);if(!Number.isFinite(l)||l<tn)return null;const h=[i[0]+o[0]*l,i[1]+o[1]*l],f=Math.atan2(i[1]-h[1],i[0]-h[0]),d=Math.atan2(t[1]-h[1],t[0]-h[0]),p=$m(s,Qn(h,i))>0,y=ic(f,d,p);return{center:h,radius:l,startAngle:f,sweep:p?y:-y}}function fb(i,t=Ms,e=sb){const n=Math.abs(i.sweep),r=Math.max(t,tn);let s;if(r>=i.radius)s=1;else{const a=2*Math.acos(1-r/i.radius);s=Math.max(1,Math.ceil(n/a))}s=Math.min(s,Math.max(1,e-1));const o=[];for(let a=0;a<=s;a++)o.push(kd(i,a/s));return o}function Ff(i,t){const e=Qn(t,i.center),n=Math.atan2(e[1],e[0]),r=p8(i.startAngle,n);let s=i.sweep===0?0:r/i.sweep;if(s<0||s>1){const a=(r>0?r-Qi:r+Qi)/i.sweep;if(a>=0&&a<=1)s=a;else{const l=ti(Qn(t,ob(i))),h=ti(Qn(t,ab(i)));s=l<=h?0:1}}const o=kd(i,s);return{point:o,t:s,distance:ti(Qn(t,o))}}function b8(i){return{center:i.center,radius:i.radius,startAngle:i.startAngle+i.sweep,sweep:-i.sweep}}const $f="ofsCurve";function db(i,t){return i*Math.abs(t)/2}function Ad(i,t,e=ei(i.vertices)){const n=i.vertices[t],r=i.vertices[t+1],s=i.bulges[t];if(!n||!r||!Number.isFinite(s)||s===0)return!1;const o=e.toPlanar(n),a=e.toPlanar(r),l=Math.hypot(a[0]-o[0],a[1]-o[1]);return db(l,s)>i.sagToleranceMeters}function I8(i,t=ei(i.vertices)){return i.bulges.some((e,n)=>Ad(i,n,t))}function ei(i){if(i.length===0)return me.forCoordinate([0,0]);let t=1/0,e=1/0,n=-1/0,r=-1/0;return i.forEach(([s,o])=>{s<t&&(t=s),o<e&&(e=o),s>n&&(n=s),o>r&&(r=o)}),me.forBBox([t,e,n,r])}function $l(i,t,e=ei(i.vertices)){return Ad(i,t,e)?d0(e.toPlanar(i.vertices[t]),e.toPlanar(i.vertices[t+1]),i.bulges[t]):null}function Pu(i,t=ei(i.vertices)){if(i.vertices.length===0)return[];const e=i.sagToleranceMeters??Ms,n=[i.vertices[0]];for(let r=0;r<i.vertices.length-1;r++){const s=$l(i,r,t);if(!s){n.push(i.vertices[r+1]);continue}fb(s,e).slice(1,-1).forEach(o=>n.push(t.toGeographic(o))),n.push(i.vertices[r+1])}return n}function To(i){var s;const t=(s=i==null?void 0:i.properties)==null?void 0:s[$f];if(!t||typeof t!="object"||t.version!==1)return null;const e=t.vertices,n=t.bulges;if(!Array.isArray(e)||!Array.isArray(n)||e.length<2||n.length!==e.length-1||!e.every(o=>Array.isArray(o)&&o.length>=2&&Number.isFinite(o[0])&&Number.isFinite(o[1]))||!n.every(o=>Number.isFinite(o)))return null;const r=Number(t.sagToleranceMeters);return{version:1,vertices:e.map(o=>[o[0],o[1]]),bulges:n.map(Number),sagToleranceMeters:r>0?r:Ms}}function ku(i,t,e=Ms){if(i.length<2)return null;const n={version:1,vertices:i.map(o=>[o[0],o[1]]),bulges:i.slice(0,-1).map((o,a)=>Number.isFinite(t[a])?t[a]:0),sagToleranceMeters:e>0?e:Ms},r=ei(n.vertices);let s=!1;return n.bulges=n.bulges.map((o,a)=>Ad(n,a,r)?(s=!0,o):0),s?n:null}function Df(i,t){if(!t){const{[$f]:e,...n}=i;return n}return{...i,[$f]:t}}function gb(i,t,e,n=ei([i,t,e])){const r=cb(n.toPlanar(i),n.toPlanar(t),n.toPlanar(e));return r?Td(r):0}function Od(i){if(!i)return null;const t=To(i);if(t)return{vertices:[...t.vertices],bulges:[...t.bulges],sagToleranceMeters:t.sagToleranceMeters};const e=i.geometry.type==="LineString"?i.geometry.coordinates:i.geometry.type==="Polygon"&&i.geometry.coordinates.length===1?i.geometry.coordinates[0]:null;return!e||e.length<2?null:{vertices:e.map(n=>[n[0],n[1]]),bulges:new Array(e.length-1).fill(0),sagToleranceMeters:Ms}}function Gf(i,t){const e=ku(t.vertices,t.bulges,t.sagToleranceMeters),n=e?Pu(e):t.vertices,r=i.geometry.type==="Polygon"?{type:"Polygon",coordinates:[n]}:i.geometry.type==="LineString"?{type:"LineString",coordinates:n}:null;return r?{...i,geometry:r,properties:Df({...i.properties||{}},e)}:null}function g0(i,t,e){const n=Od(i);if(!n||t<0||t>=n.bulges.length||!Number.isFinite(e))return null;if(e===0)return n.bulges[t]=0,Gf(i,n);const r=ei(n.vertices),s=Rd(r.toPlanar(n.vertices[t]),r.toPlanar(n.vertices[t+1]),e*Math.PI/180);return s?(n.bulges[t]=Td(s),Gf(i,n)):null}function Bf(i,t,e=Ms,n=ei(i)){const r={vertices:i,bulges:t,sagToleranceMeters:e},s=[];for(let o=0;o<i.length-1;o++){const a=$l(r,o,n);s.push({segmentIndex:o,curved:a!==null,coordinate:a?n.toGeographic(f0(a)):[(i[o][0]+i[o+1][0])/2,(i[o][1]+i[o+1][1])/2]})}return s}function S8(i,t,e=ei(i.vertices)){if(i.vertices.length<2)return null;const n=e.toPlanar(t);let r=null;for(let s=0;s<i.vertices.length-1;s++){const o=$l(i,s,e),a=o?Ff(o,n):M8(n,e.toPlanar(i.vertices[s]),e.toPlanar(i.vertices[s+1]));(!r||a.distance<r.distanceMeters)&&(r={coordinate:e.toGeographic(a.point),segmentIndex:s,distanceMeters:a.distance})}return r}function M8(i,t,e){const n=e[0]-t[0],r=e[1]-t[1],s=n*n+r*r,o=s<1e-18?0:Math.max(0,Math.min(1,((i[0]-t[0])*n+(i[1]-t[1])*r)/s)),a=[t[0]+n*o,t[1]+r*o];return{point:a,distance:Math.hypot(i[0]-a[0],i[1]-a[1])}}const N8=["vertex","intersection","midpoint","center","perpendicular","edge"];class rc{constructor(t,e){q(this,"dataSource");q(this,"mapAdapter");q(this,"enabled",!0);q(this,"tolerancePixels",18);q(this,"modes",{vertex:!0,intersection:!0,midpoint:!0,center:!0,perpendicular:!0,edge:!0});this.dataSource=t,this.mapAdapter=e}setModes(t){this.modes={...this.modes,...t}}toggleMode(t){return this.modes[t]=!this.modes[t],this.modes[t]}getSnap(t,e=[],n){var E;if(!this.enabled||!this.mapAdapter.isReady)return null;let r;try{r=this.mapAdapter.getRawMap()}catch{return null}if(!t||!Array.isArray(t)||t.length<2||!r||typeof r.project!="function")return null;const s=r.project([t[0],t[1]]),o=this.tolerancePixels,a=new Map,l=(w,L,b,S)=>{if(!this.modes[w])return;const P=b||r.project([L[0],L[1]]),N=Math.hypot(P.x-s.x,P.y-s.y),C=a.get(w);N<=o&&(!C||N<C.distPx)&&a.set(w,{coord:L,distPx:N,segment:S})},h=[],f=(n==null?void 0:n.fromPoint)??null,d=(w,L)=>{if(!w||!L||w.length<2||L.length<2)return;const b=r.project([w[0],w[1]]),S=r.project([L[0],L[1]]),P=S.x-b.x,N=S.y-b.y,C=P*P+N*N;if(C<1)return;l("midpoint",[(w[0]+L[0])/2,(w[1]+L[1])/2],{x:(b.x+S.x)/2,y:(b.y+S.y)/2});const T=((s.x-b.x)*P+(s.y-b.y)*N)/C,I=Math.max(0,Math.min(1,T));if(Math.hypot(s.x-(b.x+I*P),s.y-(b.y+I*N))<=o&&h.push({a:w,b:L}),this.modes.edge&&T>=.08&&T<=.92&&l("edge",[w[0]+T*(L[0]-w[0]),w[1]+T*(L[1]-w[1])],{x:b.x+T*P,y:b.y+T*N},{a:w,b:L}),this.modes.perpendicular&&f){const R=rc.perpendicularFoot(f,w,L);R&&l("perpendicular",R,void 0,{a:w,b:L})}},p=w=>{for(let L=0;L<w.length-1;L++)d(w[L],w[L+1])};Array.isArray(e)&&e.length>0&&(e.forEach(w=>w&&l("vertex",w)),(n==null?void 0:n.connectAdditional)!==!1&&p(e));const y=this.dataSource.getAllLayers().filter(w=>w.visible),_=this.getSearchBBox(r,s);for(const w of y){const L=_?w.queryBBox(_):w.getFeatures();for(const b of L){if(!b.geometry)continue;const S=n==null?void 0:n.excludeFeatureId;if(S!=null&&b.id===S)continue;const P=To(b);if(P){this.considerCurve(P,t,l,d,f);continue}rT(b).forEach(C=>l("vertex",C));const N=b.geometry;if(N.type==="LineString"?p(N.coordinates):N.type==="MultiLineString"||N.type==="Polygon"?N.coordinates.forEach(p):N.type==="MultiPolygon"&&N.coordinates.forEach(C=>C.forEach(p)),this.modes.center&&((E=b.properties)==null?void 0:E.shape)==="circle"&&N.type==="Polygon"){const C=N.coordinates[0].slice(0,-1),T=C.reduce((M,R)=>M+R[0],0)/C.length,I=C.reduce((M,R)=>M+R[1],0)/C.length;l("center",[T,I])}}}if(this.modes.intersection&&h.length>=2)for(let w=0;w<h.length;w++)for(let L=w+1;L<h.length;L++){const b=rc.segmentIntersection(h[w],h[L]);b&&l("intersection",b)}for(const w of N8){const L=a.get(w);if(L)return{coordinate:L.coord,type:w,distanceMeters:Co(t,L.coord),segment:L.segment}}return null}considerCurve(t,e,n,r,s){const o=ei(t.vertices);t.vertices.forEach(a=>n("vertex",a));for(let a=0;a<t.vertices.length-1;a++){const l=$l(t,a,o);if(!l){r(t.vertices[a],t.vertices[a+1]);continue}n("center",o.toGeographic(l.center)),n("midpoint",o.toGeographic(f0(l)));const h=Ff(l,o.toPlanar(e));if(h.t>.08&&h.t<.92&&n("edge",o.toGeographic(h.point)),s){const f=Ff(l,o.toPlanar(s));f.t>0&&f.t<1&&n("perpendicular",o.toGeographic(f.point))}}}static segmentIntersection(t,e){const[n,r]=t.a,[s,o]=t.b,[a,l]=e.a,[h,f]=e.b,d=(s-n)*(f-l)-(o-r)*(h-a);if(Math.abs(d)<1e-18)return null;const p=((a-n)*(f-l)-(l-r)*(h-a))/d,y=((a-n)*(o-r)-(l-r)*(s-n))/d,_=1e-9;return p<=_||p>=1-_||y<=_||y>=1-_?null:[n+p*(s-n),r+p*(o-r)]}static perpendicularFoot(t,e,n){const r=Math.cos(t[1]*Math.PI/180),s=e[0]*r,o=n[0]*r,a=t[0]*r,l=o-s,h=n[1]-e[1],f=l*l+h*h;if(f<1e-24)return null;const d=((a-s)*l+(t[1]-e[1])*h)/f;return d<=0||d>=1?null:[e[0]+d*(n[0]-e[0]),e[1]+d*(n[1]-e[1])]}getSearchBBox(t,e){if(typeof t.unproject!="function")return null;const n=this.tolerancePixels,r=[[e.x-n,e.y-n],[e.x+n,e.y-n],[e.x+n,e.y+n],[e.x-n,e.y+n]].map(([h,f])=>t.unproject([h,f]));let s=1/0,o=1/0,a=-1/0,l=-1/0;for(const h of r){const f=Array.isArray(h)?h[0]:h==null?void 0:h.lng,d=Array.isArray(h)?h[1]:h==null?void 0:h.lat;if(!Number.isFinite(f)||!Number.isFinite(d))return null;s=Math.min(s,f),o=Math.min(o,d),a=Math.max(a,f),l=Math.max(l,d)}return[s,o,a,l]}}const Js={convention:"bearing",ucsRotationDeg:0},m0={enabled:!1,incrementDeg:45,toleranceDeg:4},xl=Math.PI/180;function Dm(i){const t=i%360;return t<0?t+360:t}function sc(i,t){return((t.convention==="bearing"?90-i:i)+t.ucsRotationDeg)*xl}function bl(i,t){const e=i/xl-t.ucsRotationDeg;return Dm(t.convention==="bearing"?90-e:e)}function Gm(i,t){return(t.convention==="bearing"?-i:i)*xl}function p0(i,t){const e=me.forCoordinate(i),n=e.toPlanar(i),r=e.toPlanar(t);return{projection:e,origin:n,dx:r[0]-n[0],dy:r[1]-n[1]}}function es(i,t,e){const n=me.forCoordinate(i),r=n.toPlanar(i);return n.toGeographic([r[0]+t*Math.cos(e),r[1]+t*Math.sin(e)])}function Qe(i,t,e=Js){const{dx:n,dy:r}=p0(i,t);return{distance:Math.hypot(n,r),angle:bl(Math.atan2(r,n),e)}}const oc=String.raw`[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?`,L8=new RegExp(String.raw`^@\s*(${oc})\s*[,\s]\s*(${oc})$`,"i"),C8=new RegExp(String.raw`^@\s*(${oc})\s*<\s*(${oc})$`,"i"),P8=new RegExp(String.raw`^(${oc})$`,"i");function y0(i,t={}){const e=i.trim();if(!e)return null;const n=t.frame??Js,r=t.basePoint??null,s=e.match(C8);if(s){if(!r)return{kind:"error",message:"Relative input needs a base point. Specify the first point first."};const h=Number(s[1]),f=Number(s[2]);return{kind:"point",coordinate:es(r,h,sc(f,n)),description:`@${h}<${f}`}}const o=e.match(L8);if(o){if(!r)return{kind:"error",message:"Relative input needs a base point. Specify the first point first."};const h=Number(o[1]),f=Number(o[2]),d=n.ucsRotationDeg*xl,p=h*Math.cos(d)-f*Math.sin(d),y=h*Math.sin(d)+f*Math.cos(d),_=Math.hypot(p,y);return{kind:"point",coordinate:_===0?[r[0],r[1]]:es(r,_,Math.atan2(y,p)),description:`@${h},${f}`}}const a=e.match(P8);if(a){const h=Number(a[1]);if(!r)return{kind:"error",message:"Distance input needs a base point. Specify the first point first."};if(!t.cursor)return{kind:"error",message:"Move the cursor to show the direction, then type the distance."};const{dx:f,dy:d}=p0(r,t.cursor);return Math.hypot(f,d)<1e-6?{kind:"error",message:"Move the cursor away from the base point to show the direction."}:{kind:"point",coordinate:es(r,h,Math.atan2(d,f)),description:`${h} m toward cursor`}}if(e.startsWith("@"))return{kind:"error",message:`Invalid relative input "${e}". Use @dx,dy or @distance<angle.`};const l=dp(e);return l?{kind:"point",coordinate:l,description:`${l[0]}, ${l[1]}`}:gp(e)?{kind:"error",message:rf(e)}:null}function _0(i,t,e){const{ortho:n,polar:r,frame:s}=e;if(!n&&!r.enabled)return{coordinate:t,lockedAngle:null,mode:null};const{projection:o,origin:a,dx:l,dy:h}=p0(i,t);if(Math.hypot(l,h)<1e-9)return{coordinate:t,lockedAngle:null,mode:null};const d=Dm(Math.atan2(h,l)/xl-s.ucsRotationDeg);let p=null,y=null;if(n)p=Math.round(d/90)*90,y="ortho";else if(r.enabled&&r.incrementDeg>0){const L=Math.round(d/r.incrementDeg)*r.incrementDeg;Math.abs(d-L)<=r.toleranceDeg&&(p=L,y="polar")}if(p===null)return{coordinate:t,lockedAngle:null,mode:null};const _=(p+s.ucsRotationDeg)*xl,E=l*Math.cos(_)+h*Math.sin(_);let w=o.toGeographic([a[0]+E*Math.cos(_),a[1]+E*Math.sin(_)]);if(s.ucsRotationDeg%360===0){const L=Dm(p)%180;L===0?w=[t[0],i[1]]:L===90&&(w=[i[0],t[1]])}return{coordinate:w,lockedAngle:bl(_,s),mode:y}}class k8{static calculateOrtho(t,e,n=Js){const r=_0(t,e,{ortho:!0,polar:m0,frame:n}),{distance:s}=Qe(t,r.coordinate),o=Qe(t,r.coordinate,Js).angle,a=((o-(90-n.ucsRotationDeg))%180+180)%180;return{coordinate:r.coordinate,distanceMeters:s,bearingDegrees:s>.1?Math.round(o*10)/10:0,axis:a<45||a>135?"horizontal":"vertical"}}}function xe(i){if(!i||typeof i.getRawMap!="function")return null;try{return i.getRawMap()??null}catch{return null}}class mb extends no{constructor(e,n,r){super();q(this,"dataSource");q(this,"mapAdapter");q(this,"snapping",null);q(this,"currentSnapResult",null);q(this,"sourceId","_ofs_grips_temp");q(this,"activeFeatureId",null);q(this,"activeLayerId",null);q(this,"activeGrip",null);q(this,"isDragging",!1);q(this,"dragHasMoved",!1);q(this,"isEnabled",!1);q(this,"activationTimestamp",0);q(this,"initialFeatureSnapshot",null);q(this,"unsubClick",null);q(this,"unsubMouseDown",null);q(this,"unsubMouseUp",null);q(this,"unsubMove",null);q(this,"unsubContextMenu",null);q(this,"handleKeyDown",e=>{if(!(!this.isEnabled||this.activeFeatureId===null||!this.activeLayerId)){if(e.key==="Delete"||e.key==="Backspace")this.activeGrip&&this.activeGrip.type==="vertex"&&(e.preventDefault(),this.deleteVertex(this.activeGrip.index,this.activeGrip.ringIndex,this.activeGrip.partIndex??0)&&(this.activeGrip=null,this.isDragging=!1,this.dragHasMoved=!1));else if(e.key==="Escape")if(this.isDragging&&this.initialFeatureSnapshot){this.dataSource.updateFeature(this.activeLayerId,this.initialFeatureSnapshot,!1),this.isDragging=!1,this.dragHasMoved=!1,this.activeGrip=null,this.initialFeatureSnapshot=null,this.renderGrips();try{const n=xe(this.mapAdapter);n&&n.dragPan&&n.dragPan.enable(),n&&n.getCanvas()&&(n.getCanvas().style.cursor="default")}catch(n){Ht("OFSGripsEditor.handleKeyDown",n)}}else this.clear()}});this.dataSource=e,this.mapAdapter=n,this.snapping=r||null,typeof window<"u"&&window.addEventListener("keydown",this.handleKeyDown),this.dataSource.on("feature:updated",({layerId:s,feature:o})=>{this.isEnabled&&this.activeLayerId===s&&this.activeFeatureId===o.id&&!this.isDragging&&this.renderGrips()})}setSnappingEngine(e){this.snapping=e}getSnappingEngine(){return this.snapping}editFeature(e,n){if(this.isEnabled&&this.activeLayerId===e&&this.activeFeatureId===n)return;const r=this.dataSource.getFeature(e,n);!r||!["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon"].includes(r.geometry.type)||(this.activeLayerId=e,this.activeFeatureId=n,this.isEnabled=!0,this.activeGrip=null,this.isDragging=!1,this.dragHasMoved=!1,this.initialFeatureSnapshot=null,this.activationTimestamp=Date.now(),this.setupLayers(),this.renderGrips(),this.bindEvents())}clear(){try{const e=xe(this.mapAdapter);e&&e.dragPan&&e.dragPan.enable(),e&&e.getCanvas()&&(e.getCanvas().style.cursor="default")}catch(e){Ht("OFSGripsEditor.clear",e)}this.isEnabled=!1,this.activeFeatureId=null,this.activeLayerId=null,this.activeGrip=null,this.isDragging=!1,this.dragHasMoved=!1,this.initialFeatureSnapshot=null,this.currentSnapResult=null,this.unsubClick&&(this.unsubClick(),this.unsubClick=null),this.unsubMouseDown&&(this.unsubMouseDown(),this.unsubMouseDown=null),this.unsubMouseUp&&(this.unsubMouseUp(),this.unsubMouseUp=null),this.unsubMove&&(this.unsubMove(),this.unsubMove=null),this.unsubContextMenu&&(this.unsubContextMenu(),this.unsubContextMenu=null),this.clearSource(),this.emit("grip:clear",void 0)}getActiveFeature(){return!this.activeLayerId||this.activeFeatureId===null?null:this.dataSource.getFeature(this.activeLayerId,this.activeFeatureId)||null}getActiveLayerId(){return this.activeLayerId}getActiveFeatureId(){return this.activeFeatureId}getIsEditing(){return this.isEnabled&&this.activeFeatureId!==null}hasHandleAt(e,n=18){return this.findNearestHandle(e,n)!==null}curveStateOf(e){return Od(e)}writeCurveState(e,n){if(!this.activeLayerId||this.activeFeatureId===null)return!1;const r=Gf(e,n);return r?(r.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,r,!1),!0):!1}getCurveSegments(){const e=this.getActiveFeature();if(!e)return[];const n=this.curveStateOf(e);if(!n)return[];const r=ei(n.vertices);return Bf(n.vertices,n.bulges,n.sagToleranceMeters,r).map(s=>({index:s.segmentIndex,curved:s.curved,coordinate:s.coordinate,sagMeters:s.curved?r.distance(n.vertices[s.segmentIndex],n.vertices[s.segmentIndex+1])*Math.abs(n.bulges[s.segmentIndex])/2:0}))}convertSegmentToArc(e,n){const r=this.getActiveFeature();if(!r||!this.activeLayerId||this.activeFeatureId===null||!n)return!1;const s=g0(r,e,n);return s?(s.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,s,!1),!0):!1}setSegmentBulge(e,n){const r=this.getActiveFeature();if(!r)return!1;const s=this.curveStateOf(r);return!s||e<0||e>=s.bulges.length||!Number.isFinite(n)?!1:(s.bulges[e]=n,this.writeCurveState(r,s))}straightenSegment(e){return this.setSegmentBulge(e,0)}curveHandles(e){if(!To(e))return null;const n=this.curveStateOf(e);if(!n)return null;const r=e.geometry.type==="Polygon",s=[],o=r?n.vertices.length-1:n.vertices.length;for(let a=0;a<o;a++)s.push({id:r?`v_0_${a}`:`v_${a}`,coordinate:n.vertices[a],type:"vertex",index:a,ringIndex:0,partIndex:0});Bf(n.vertices,n.bulges,n.sagToleranceMeters).forEach(a=>{s.push({id:`${a.curved?"s":"m"}_${a.segmentIndex}`,coordinate:a.coordinate,type:a.curved?"curve":"midpoint",index:a.segmentIndex,ringIndex:0,partIndex:0})});try{s.push({id:"c_center",coordinate:Us(e).geometry.coordinates,type:"center",index:0,ringIndex:0,partIndex:0})}catch(a){Ht("OFSGripsEditor.curveHandles",a)}return s}getHandles(){const e=this.getActiveFeature();if(!e)return[];const n=this.curveHandles(e);if(n)return n;const r=[],s=e.geometry.type,o=()=>{try{const a=Us(e).geometry.coordinates;r.push({id:"c_center",coordinate:a,type:"center",index:0,ringIndex:0,partIndex:0})}catch(a){Ht("OFSGripsEditor.getHandles",a)}};if(s==="Point"){const a=e.geometry.coordinates;r.push({id:"v_0",coordinate:a,type:"vertex",index:0,ringIndex:0,partIndex:0})}else if(s==="MultiPoint")e.geometry.coordinates.forEach((l,h)=>{r.push({id:`v_${h}`,coordinate:l,type:"vertex",index:h,ringIndex:0,partIndex:0})}),o();else if(s==="LineString"){const a=e.geometry.coordinates;a.forEach((l,h)=>{if(r.push({id:`v_${h}`,coordinate:l,type:"vertex",index:h,ringIndex:0,partIndex:0}),h<a.length-1){const f=a[h+1];r.push({id:`m_${h}`,coordinate:[(l[0]+f[0])/2,(l[1]+f[1])/2],type:"midpoint",index:h,ringIndex:0,partIndex:0})}}),o()}else s==="MultiLineString"?(e.geometry.coordinates.forEach((l,h)=>{l.forEach((f,d)=>{if(r.push({id:`v_${h}_${d}`,coordinate:f,type:"vertex",index:d,ringIndex:0,partIndex:h}),d<l.length-1){const p=l[d+1];r.push({id:`m_${h}_${d}`,coordinate:[(f[0]+p[0])/2,(f[1]+p[1])/2],type:"midpoint",index:d,ringIndex:0,partIndex:h})}})}),o()):s==="Polygon"?(e.geometry.coordinates.forEach((l,h)=>{const f=l.length-1;for(let d=0;d<f;d++){const p=l[d],y=l[(d+1)%f];r.push({id:`v_${h}_${d}`,coordinate:p,type:"vertex",index:d,ringIndex:h,partIndex:0}),r.push({id:`m_${h}_${d}`,coordinate:[(p[0]+y[0])/2,(p[1]+y[1])/2],type:"midpoint",index:d,ringIndex:h,partIndex:0})}}),o()):s==="MultiPolygon"&&(e.geometry.coordinates.forEach((l,h)=>{l.forEach((f,d)=>{const p=f.length-1;for(let y=0;y<p;y++){const _=f[y],E=f[(y+1)%p];r.push({id:`v_${h}_${d}_${y}`,coordinate:_,type:"vertex",index:y,ringIndex:d,partIndex:h}),r.push({id:`m_${h}_${d}_${y}`,coordinate:[(_[0]+E[0])/2,(_[1]+E[1])/2],type:"midpoint",index:y,ringIndex:d,partIndex:h})}})}),o());return r}setupLayers(){if(this.mapAdapter.isReady)try{const e=xe(this.mapAdapter);if(!e||typeof e.getSource!="function")return;if(!e.getSource(this.sourceId))e.addSource(this.sourceId,{type:"geojson",data:{type:"FeatureCollection",features:[]}}),e.addLayer({id:`${this.sourceId}_shape_fill`,source:this.sourceId,type:"fill",filter:["all",["==","$type","Polygon"],["==","gripType","active_shape"]],paint:{"fill-color":"#818cf8","fill-opacity":.25}}),e.addLayer({id:`${this.sourceId}_shape_line`,source:this.sourceId,type:"line",filter:["all",["in","$type","LineString","Polygon"],["==","gripType","active_shape"]],paint:{"line-color":"#2e2b6b","line-width":2.5}}),e.addLayer({id:`${this.sourceId}_center`,source:this.sourceId,type:"circle",filter:["==",["get","gripType"],"center"],paint:{"circle-radius":8,"circle-color":"#10b981","circle-stroke-width":2.5,"circle-stroke-color":"#ffffff"}}),e.addLayer({id:`${this.sourceId}_curves`,source:this.sourceId,type:"circle",filter:["==",["get","gripType"],"curve"],paint:{"circle-radius":6,"circle-color":"#f59e0b","circle-stroke-width":2,"circle-stroke-color":"#ffffff"}}),e.addLayer({id:`${this.sourceId}_midpoints`,source:this.sourceId,type:"circle",filter:["==",["get","gripType"],"midpoint"],paint:{"circle-radius":4.5,"circle-color":"#f43f5e","circle-stroke-width":1.5,"circle-stroke-color":"#ffffff"}}),e.addLayer({id:`${this.sourceId}_vertices`,source:this.sourceId,type:"circle",filter:["==",["get","gripType"],"vertex"],paint:{"circle-radius":6.5,"circle-color":"#f43f5e","circle-stroke-width":2.5,"circle-stroke-color":"#ffffff"}}),e.addLayer({id:`${this.sourceId}_direction_arrows`,source:this.sourceId,type:"symbol",filter:["==",["get","gripType"],"direction_arrow"],layout:{"text-field":"▲","text-size":14,"text-rotate":["get","bearing"],"text-rotation-alignment":"map","text-pitch-alignment":"map","text-keep-upright":!1,"text-allow-overlap":!0,"text-ignore-placement":!0},paint:{"text-color":"#0284c7","text-halo-color":"#ffffff","text-halo-width":2}}),e.addLayer({id:`${this.sourceId}_active`,source:this.sourceId,type:"circle",filter:["==",["get","isActive"],!0],paint:{"circle-radius":11,"circle-color":"#fbbf24","circle-opacity":.45,"circle-stroke-width":2.5,"circle-stroke-color":"#f59e0b"}}),e.addLayer({id:`${this.sourceId}_snap_halo`,source:this.sourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":22,"circle-color":["match",["get","snapType"],"midpoint","#38bdf8","edge","#a855f7","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#3b82f6"],"circle-blur":.85,"circle-opacity":.7}}),e.addLayer({id:`${this.sourceId}_snap_glow`,source:this.sourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":11,"circle-color":["match",["get","snapType"],"midpoint","#0ea5e9","edge","#8b5cf6","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#2563eb"],"circle-blur":.35,"circle-opacity":.55}}),e.addLayer({id:`${this.sourceId}_snap_core`,source:this.sourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":5.5,"circle-color":["match",["get","snapType"],"midpoint","#0284c7","edge","#7c3aed","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#1d4ed8"],"circle-stroke-width":2,"circle-stroke-color":"#ffffff","circle-stroke-opacity":1}});else try{e.getLayer(`${this.sourceId}_shape_fill`)&&e.setFilter(`${this.sourceId}_shape_fill`,["all",["==","$type","Polygon"],["==","gripType","active_shape"]]),e.getLayer(`${this.sourceId}_shape_line`)&&e.setFilter(`${this.sourceId}_shape_line`,["all",["in","$type","LineString","Polygon"],["==","gripType","active_shape"]]),e.getLayer(`${this.sourceId}_snap_halo`)||e.addLayer({id:`${this.sourceId}_snap_halo`,source:this.sourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":22,"circle-color":["match",["get","snapType"],"midpoint","#38bdf8","edge","#a855f7","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#3b82f6"],"circle-blur":.85,"circle-opacity":.7}}),e.getLayer(`${this.sourceId}_snap_glow`)||e.addLayer({id:`${this.sourceId}_snap_glow`,source:this.sourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":11,"circle-color":["match",["get","snapType"],"midpoint","#0ea5e9","edge","#8b5cf6","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#2563eb"],"circle-blur":.35,"circle-opacity":.55}}),e.getLayer(`${this.sourceId}_snap_core`)||e.addLayer({id:`${this.sourceId}_snap_core`,source:this.sourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":5.5,"circle-color":["match",["get","snapType"],"midpoint","#0284c7","edge","#7c3aed","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#1d4ed8"],"circle-stroke-width":2,"circle-stroke-color":"#ffffff","circle-stroke-opacity":1}})}catch(n){Ht("OFSGripsEditor.setupLayers",n)}}catch(e){Ht("OFSGripsEditor.setupLayers",e)}}renderGrips(){if(this.mapAdapter.isReady)try{const e=xe(this.mapAdapter);if(!e||typeof e.getSource!="function")return;const n=e.getSource(this.sourceId);if(!n||typeof n.setData!="function")return;const r=this.getActiveFeature(),s=[];if(r&&r.geometry&&s.push({type:"Feature",geometry:r.geometry,properties:{gripType:"active_shape"}}),this.getHandles().forEach(l=>{var h;s.push(Lt(l.coordinate,{gripId:l.id,gripType:l.type,index:l.index,ringIndex:l.ringIndex,partIndex:l.partIndex??0,isActive:((h=this.activeGrip)==null?void 0:h.id)===l.id,isSnap:!1}))}),r&&r.geometry&&r.geometry.type==="LineString"){const l=r.geometry.coordinates;for(let h=0;h<l.length-1;h++){const f=l[h],d=l[h+1],p=[(f[0]+d[0])/2,(f[1]+d[1])/2],y=al(Lt(f),Lt(d));s.push(Lt(p,{gripId:`arrow_${h}`,gripType:"direction_arrow",bearing:y,isSnap:!1}))}}this.currentSnapResult&&this.currentSnapResult.coordinate&&s.push(Lt(this.currentSnapResult.coordinate,{gripId:"snap_indicator",gripType:"snap_guide",isSnap:!0,snapType:this.currentSnapResult.type})),n.setData({type:"FeatureCollection",features:s}),[`${this.sourceId}_shape_fill`,`${this.sourceId}_shape_line`,`${this.sourceId}_direction_arrows`,`${this.sourceId}_center`,`${this.sourceId}_curves`,`${this.sourceId}_midpoints`,`${this.sourceId}_vertices`,`${this.sourceId}_active`,`${this.sourceId}_snap_halo`,`${this.sourceId}_snap_glow`,`${this.sourceId}_snap_core`].forEach(l=>{try{e.getLayer(l)&&e.moveLayer(l)}catch(h){Ht("OFSGripsEditor.renderGrips",h)}})}catch(e){Ht("OFSGripsEditor.renderGrips",e)}}clearSource(){try{const e=xe(this.mapAdapter);if(!e||typeof e.getSource!="function")return;const n=e.getSource(this.sourceId);n&&typeof n.setData=="function"&&n.setData({type:"FeatureCollection",features:[]})}catch(e){Ht("OFSGripsEditor.clearSource",e)}}bindEvents(){this.unsubClick&&this.unsubClick(),this.unsubMouseDown&&this.unsubMouseDown(),this.unsubMouseUp&&this.unsubMouseUp(),this.unsubMove&&this.unsubMove(),this.unsubContextMenu&&this.unsubContextMenu(),this.unsubMouseDown=typeof this.mapAdapter.onMouseDown=="function"?this.mapAdapter.onMouseDown(e=>this.handleMouseDown(e.coordinate)):()=>{},this.unsubMouseUp=typeof this.mapAdapter.onMouseUp=="function"?this.mapAdapter.onMouseUp(e=>this.handleMouseUp(e.coordinate)):()=>{},this.unsubClick=typeof this.mapAdapter.onMapClick=="function"?this.mapAdapter.onMapClick(e=>this.handleClick(e.coordinate)):()=>{},this.unsubMove=typeof this.mapAdapter.onMouseMove=="function"?this.mapAdapter.onMouseMove(e=>this.handleMove(e.coordinate)):()=>{},this.unsubContextMenu=typeof this.mapAdapter.onContextMenu=="function"?this.mapAdapter.onContextMenu(e=>this.handleContextMenu(e.coordinate,e.originalEvent)):()=>{}}findNearestHandle(e,n=18){let r;try{r=xe(this.mapAdapter)}catch{return null}if(!r||typeof r.project!="function"){const h=this.getHandles();let f=null,d=.001;for(const p of h){const y=Math.hypot(e[0]-p.coordinate[0],e[1]-p.coordinate[1]),_=p.type==="center"?d*.7:d;y<=_&&(d=y,f=p)}return f}const s=r.project([e[0],e[1]]),o=this.getHandles();let a=null,l=n;for(const h of o){const f=r.project([h.coordinate[0],h.coordinate[1]]),d=Math.hypot(s.x-f.x,s.y-f.y),p=h.type==="center"?Math.min(n,14):n;d<=p&&(a&&h.type!=="center"&&a.type==="center"&&d<=l+4||!a||d<l)&&(a=h,l=d)}return a}handleMouseDown(e){if(!this.isEnabled||!this.activeLayerId||this.activeFeatureId===null||Date.now()-this.activationTimestamp<250)return;const n=this.findNearestHandle(e,18);if(!n)return;const r=this.getActiveFeature();r&&(this.initialFeatureSnapshot=Ue(r)),n.type==="midpoint"?this.insertVertexAtMidpoint(n):(this.activeGrip=n,this.isDragging=!0,this.emit("grip:select",{handle:n}),this.renderGrips()),this.dragHasMoved=!1;try{const s=xe(this.mapAdapter);s&&s.dragPan&&typeof s.dragPan.disable=="function"&&s.dragPan.disable(),s&&typeof s.getCanvas=="function"&&s.getCanvas()&&(s.getCanvas().style.cursor="crosshair")}catch(s){Ht("OFSGripsEditor.handleMouseDown",s)}}handleMouseUp(e){var n;if(this.isEnabled){try{const r=xe(this.mapAdapter);r&&r.dragPan&&typeof r.dragPan.enable=="function"&&r.dragPan.enable(),r&&typeof r.getCanvas=="function"&&r.getCanvas()&&(r.getCanvas().style.cursor="default")}catch(r){Ht("OFSGripsEditor.handleMouseUp",r)}if(this.isDragging){if(this.dragHasMoved){if(this.activeGrip&&this.activeLayerId&&this.activeFeatureId!==null){const r=this.activeFeatureId,s=this.activeLayerId,o=this.initialFeatureSnapshot,a=this.getActiveFeature();if(o&&a){const l=Ue(a);this.dataSource.transactions.record({description:`Edit geometry of feature ${r}`,undo:()=>{this.dataSource.updateFeature(s,o,!1),this.renderGrips()},redo:()=>{this.dataSource.updateFeature(s,l,!1),this.renderGrips()}})}this.initialFeatureSnapshot=null,this.activeGrip=null,this.isDragging=!1,this.dragHasMoved=!1,this.currentSnapResult=null,this.renderGrips(),this.emit("grip:commit",{featureId:r,layerId:s})}}else if(((n=this.activeGrip)==null?void 0:n.type)==="center"){this.isDragging=!1,this.activeGrip=null,this.initialFeatureSnapshot=null,this.renderGrips();return}}}}handleClick(e){if(!(!this.isEnabled||!this.activeLayerId||this.activeFeatureId===null)&&!(Date.now()-this.activationTimestamp<250)){if(this.dragHasMoved){this.dragHasMoved=!1;return}if(this.isDragging){this.isDragging=!1,this.dragHasMoved=!1;const n=this.activeFeatureId,r=this.activeLayerId,s=this.initialFeatureSnapshot,o=this.getActiveFeature();if(s&&o){const a=Ue(o);this.dataSource.transactions.record({description:`Edit geometry of feature ${n}`,undo:()=>{this.dataSource.updateFeature(r,s,!1),this.renderGrips()},redo:()=>{this.dataSource.updateFeature(r,a,!1),this.renderGrips()}})}this.initialFeatureSnapshot=null,this.activeGrip=null,this.currentSnapResult=null,this.renderGrips(),this.emit("grip:commit",{featureId:n,layerId:r})}else{const n=this.findNearestHandle(e,18);if(n){if(n.type==="center")return;const r=this.getActiveFeature();r&&(this.initialFeatureSnapshot=Ue(r)),n.type==="midpoint"?this.insertVertexAtMidpoint(n):(this.activeGrip=n,this.isDragging=!0,this.emit("grip:select",{handle:n}),this.renderGrips())}}}}handleContextMenu(e,n){if(!this.isEnabled||!this.activeLayerId||this.activeFeatureId===null)return;const r=this.findNearestHandle(e,18);r&&r.type==="vertex"&&(n&&n.preventDefault(),this.deleteVertex(r.index,r.ringIndex,r.partIndex??0),this.activeGrip=null,this.isDragging=!1,this.dragHasMoved=!1)}handleMove(e){if(this.isEnabled){if(this.isDragging&&this.activeGrip&&this.activeLayerId&&this.activeFeatureId!==null){this.dragHasMoved=!0;let n=e,r=null;if(this.snapping&&this.snapping.enabled&&["vertex","midpoint","curve"].includes(this.activeGrip.type)){const s=this.activeGrip.type==="curve"?[]:this.getHandles().filter(o=>o.id!==this.activeGrip.id&&o.type==="vertex").map(o=>o.coordinate);r=this.snapping.getSnap(e,s,{excludeFeatureId:this.activeFeatureId,connectAdditional:!To(this.getActiveFeature())}),r&&(n=r.coordinate)}this.currentSnapResult=r,this.applyCoordinateChange(n);return}try{const n=xe(this.mapAdapter);if(n&&typeof n.getCanvas=="function"&&n.getCanvas()){const r=this.findNearestHandle(e,18);r?n.getCanvas().style.cursor=r.type==="center"?"move":"pointer":n.getCanvas().style.cursor="default"}}catch(n){Ht("OFSGripsEditor.handleMove",n)}}}applyCoordinateChange(e){if(!this.activeGrip||!this.activeLayerId||this.activeFeatureId===null)return;const n=this.getActiveFeature();if(n){if(this.activeGrip.type==="center"){const r=e[0]-this.activeGrip.coordinate[0],s=e[1]-this.activeGrip.coordinate[1],o=ce.translateByOffset(n,r,s);o.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,o,!1),this.activeGrip.coordinate=e,this.renderGrips(),this.emit("grip:move",{handle:this.activeGrip,coordinate:e});return}if(To(n)&&this.applyCurveChange(n,e)){this.activeGrip.coordinate=e,this.renderGrips(),this.emit("grip:move",{handle:this.activeGrip,coordinate:e});return}if(n.geometry.type==="Point"){const r=Lt(e,n.properties);r.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,r,!1)}else if(n.geometry.type==="MultiPoint"){const r=[...n.geometry.coordinates];r[this.activeGrip.index]=e;const s=fw(r,n.properties);s.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,s,!1)}else if(n.geometry.type==="LineString"){const r=[...n.geometry.coordinates];r[this.activeGrip.index]=e;const s=ae(r,n.properties);s.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,s,!1)}else if(n.geometry.type==="MultiLineString"){const r=n.geometry.coordinates.map(a=>[...a]),s=this.activeGrip.partIndex??0;r[s][this.activeGrip.index]=e;const o=hw(r,n.properties);o.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,o,!1)}else if(n.geometry.type==="Polygon"){const r=n.geometry.coordinates.map(l=>[...l]),s=this.activeGrip.ringIndex,o=this.activeGrip.index;r[s][o]=e,o===0&&(r[s][r[s].length-1]=e);const a=Pe(r,n.properties);a.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,a,!1)}else if(n.geometry.type==="MultiPolygon"){const r=n.geometry.coordinates.map(h=>h.map(f=>[...f])),s=this.activeGrip.partIndex??0,o=this.activeGrip.ringIndex,a=this.activeGrip.index;r[s][o][a]=e,a===0&&(r[s][o][r[s][o].length-1]=e);const l=Oo(r,n.properties);l.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,l,!1)}this.activeGrip.coordinate=e,this.renderGrips(),this.emit("grip:move",{handle:this.activeGrip,coordinate:e})}}applyCurveChange(e,n){if(!this.activeGrip)return!1;const r=this.curveStateOf(e);if(!r)return!1;const s=this.activeGrip.index;if(this.activeGrip.type==="curve"){if(s<0||s>=r.bulges.length)return!1;r.bulges[s]=gb(r.vertices[s],n,r.vertices[s+1])}else if(this.activeGrip.type==="vertex"){if(s<0||s>=r.vertices.length)return!1;r.vertices[s]=n,e.geometry.type==="Polygon"&&s===0&&(r.vertices[r.vertices.length-1]=n)}else return!1;return this.writeCurveState(e,r)}insertVertexAtMidpoint(e){const n=this.getActiveFeature();if(n&&To(n)){const r=this.curveStateOf(n);r&&e.index>=0&&e.index<r.bulges.length&&(r.vertices.splice(e.index+1,0,e.coordinate),r.bulges.splice(e.index,1,0,0),this.writeCurveState(n,r)&&(this.activeGrip={id:`v_${e.index+1}`,coordinate:e.coordinate,type:"vertex",index:e.index+1,ringIndex:e.ringIndex,partIndex:0},this.isDragging=!0,this.renderGrips()));return}this.insertVertexIntoGeometry(e)}insertVertexIntoGeometry(e){if(!this.activeLayerId||this.activeFeatureId===null)return;const n=this.getActiveFeature();if(n){if(n.geometry.type==="LineString"){const r=[...n.geometry.coordinates],s=e.index+1;r.splice(s,0,e.coordinate);const o=ae(r,n.properties);o.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,o,!1),this.activeGrip={id:`v_${s}`,coordinate:e.coordinate,type:"vertex",index:s,ringIndex:0,partIndex:0},this.isDragging=!0,this.renderGrips()}else if(n.geometry.type==="Polygon"){const r=n.geometry.coordinates.map(l=>[...l]),s=e.ringIndex,o=e.index+1;r[s].splice(o,0,e.coordinate);const a=Pe(r,n.properties);a.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,a,!1),this.activeGrip={id:`v_${s}_${o}`,coordinate:e.coordinate,type:"vertex",index:o,ringIndex:s,partIndex:0},this.isDragging=!0,this.renderGrips()}else if(n.geometry.type==="MultiPolygon"){const r=n.geometry.coordinates.map(h=>h.map(f=>[...f])),s=e.partIndex??0,o=e.ringIndex,a=e.index+1;r[s][o].splice(a,0,e.coordinate);const l=Oo(r,n.properties);l.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,l,!1),this.activeGrip={id:`v_${s}_${o}_${a}`,coordinate:e.coordinate,type:"vertex",index:a,ringIndex:o,partIndex:s},this.isDragging=!0,this.renderGrips()}}}deleteVertex(e,n=0,r=0){if(!this.activeLayerId||this.activeFeatureId===null)return!1;const s=this.getActiveFeature();if(!s)return!1;if(s.geometry.type==="LineString"){const o=[...s.geometry.coordinates];if(o.length<=2)return!1;o.splice(e,1);const a=ae(o,s.properties);return a.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,a,!0),this.renderGrips(),this.emit("grip:delete-vertex",{featureId:this.activeFeatureId,index:e}),!0}else if(s.geometry.type==="Polygon"){const o=s.geometry.coordinates.map(l=>[...l]);if(o[n].length<=4)return!1;o[n].splice(e,1),e===0&&(o[n][o[n].length-1]=o[n][0]);const a=Pe(o,s.properties);return a.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,a,!0),this.renderGrips(),this.emit("grip:delete-vertex",{featureId:this.activeFeatureId,index:e}),!0}else if(s.geometry.type==="MultiPolygon"){const o=s.geometry.coordinates.map(l=>l.map(h=>[...h]));if(o[r][n].length<=4)return!1;o[r][n].splice(e,1),e===0&&(o[r][n][o[r][n].length-1]=o[r][n][0]);const a=Oo(o,s.properties);return a.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,a,!0),this.renderGrips(),this.emit("grip:delete-vertex",{featureId:this.activeFeatureId,index:e}),!0}return!1}destroy(){typeof window<"u"&&window.removeEventListener("keydown",this.handleKeyDown),this.clear(),this.removeAllListeners()}}const pb={pointColor:"#22d3ee",pointRadius:4,pointStrokeColor:"#0e7490",pointStrokeWidth:1,lineColor:"#22d3ee",lineWidth:1.5,lineDash:[2,2],fillColor:"#22d3ee",fillOpacity:.15,opacity:.9},Wg={type:"FeatureCollection",features:[]};function hn(i,t){return["coalesce",["get",i],t]}class yb{constructor(t){q(this,"mapAdapter");q(this,"sourceId","_ofs_preview_source");q(this,"style",{...pb});q(this,"current",Wg);this.mapAdapter=t}get layerIds(){return[`${this.sourceId}_fill`,`${this.sourceId}_line`,`${this.sourceId}_points`]}raw(){var t;if(!((t=this.mapAdapter)!=null&&t.isReady))return null;try{return xe(this.mapAdapter)}catch{return null}}setupLayers(){const t=this.raw();if(!(!t||typeof t.addSource!="function"))try{if(t.getSource(this.sourceId))return;t.addSource(this.sourceId,{type:"geojson",data:this.current}),t.addLayer({id:`${this.sourceId}_fill`,source:this.sourceId,type:"fill",filter:["in","$type","Polygon"],paint:{"fill-color":hn("color",this.style.fillColor),"fill-opacity":hn("fillOpacity",this.style.fillOpacity)}}),t.addLayer({id:`${this.sourceId}_line`,source:this.sourceId,type:"line",filter:["in","$type","LineString","Polygon"],layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":hn("color",this.style.lineColor),"line-width":hn("width",this.style.lineWidth),"line-opacity":hn("opacity",this.style.opacity),...this.style.lineDash.length>0?{"line-dasharray":this.style.lineDash}:{}}}),t.addLayer({id:`${this.sourceId}_points`,source:this.sourceId,type:"circle",filter:["==","$type","Point"],paint:{"circle-color":hn("color",this.style.pointColor),"circle-radius":hn("radius",this.style.pointRadius),"circle-opacity":hn("opacity",this.style.opacity),"circle-stroke-color":hn("strokeColor",this.style.pointStrokeColor),"circle-stroke-width":hn("strokeWidth",this.style.pointStrokeWidth)}})}catch(e){Ht("OFSDrawPreview.setupLayers",e)}}set(t){const e=t?Array.isArray(t)?{type:"FeatureCollection",features:t}:t:Wg;this.current=e,this.setupLayers();const n=this.raw();if(!(!n||typeof n.getSource!="function"))try{const r=n.getSource(this.sourceId);r&&typeof r.setData=="function"&&r.setData(e)}catch(r){Ht("OFSDrawPreview.set",r)}}clear(){this.set(null)}getFeatures(){return[...this.current.features]}isEmpty(){return this.current.features.length===0}setStyle(t){this.style={...this.style,...t};const e=this.raw();if(!(!e||typeof e.setPaintProperty!="function")&&!(typeof e.getLayer=="function"&&!e.getLayer(`${this.sourceId}_points`)))try{const n=`${this.sourceId}_fill`,r=`${this.sourceId}_line`,s=`${this.sourceId}_points`;e.setPaintProperty(n,"fill-color",hn("color",this.style.fillColor)),e.setPaintProperty(n,"fill-opacity",hn("fillOpacity",this.style.fillOpacity)),e.setPaintProperty(r,"line-color",hn("color",this.style.lineColor)),e.setPaintProperty(r,"line-width",hn("width",this.style.lineWidth)),e.setPaintProperty(r,"line-opacity",hn("opacity",this.style.opacity)),e.setPaintProperty(r,"line-dasharray",this.style.lineDash.length>0?this.style.lineDash:void 0),e.setPaintProperty(s,"circle-color",hn("color",this.style.pointColor)),e.setPaintProperty(s,"circle-radius",hn("radius",this.style.pointRadius)),e.setPaintProperty(s,"circle-opacity",hn("opacity",this.style.opacity)),e.setPaintProperty(s,"circle-stroke-color",hn("strokeColor",this.style.pointStrokeColor)),e.setPaintProperty(s,"circle-stroke-width",hn("strokeWidth",this.style.pointStrokeWidth))}catch(n){Ht("OFSDrawPreview.setStyle",n)}}getStyle(){return{...this.style}}bringToFront(){const t=this.raw();if(!(!t||typeof t.moveLayer!="function"||typeof t.getLayer!="function"))try{this.layerIds.forEach(e=>{t.getLayer(e)&&t.moveLayer(e)})}catch(e){Ht("OFSDrawPreview.bringToFront",e)}}destroy(){const t=this.raw();if(this.current=Wg,!!t)try{this.layerIds.forEach(e=>{typeof t.getLayer=="function"&&t.getLayer(e)&&typeof t.removeLayer=="function"&&t.removeLayer(e)}),typeof t.getSource=="function"&&t.getSource(this.sourceId)&&typeof t.removeSource=="function"&&t.removeSource(this.sourceId)}catch(e){Ht("OFSDrawPreview.destroy",e)}}}const Ev=1e-12;function Fd(i,t,e){return[i[0]+(t[0]-i[0])*e,i[1]+(t[1]-i[1])*e]}function Zn(i){return i.segmentIndex+i.t}function _b(i){const t=[],e=n=>{for(let r=0;r<n.length-1;r++)(n[r][0]!==n[r+1][0]||n[r][1]!==n[r+1][1])&&t.push({a:n[r],b:n[r+1]})};switch(i.type){case"LineString":e(i.coordinates);break;case"MultiLineString":case"Polygon":i.coordinates.forEach(e);break;case"MultiPolygon":i.coordinates.forEach(n=>n.forEach(e));break;case"GeometryCollection":i.geometries.forEach(n=>t.push(..._b(n)));break}return t}function qf(i,t,e){const n=t[0]-i[0],r=t[1]-i[1],s=e.b[0]-e.a[0],o=e.b[1]-e.a[1],a=n*o-r*s,l=Math.hypot(n,r)*Math.hypot(s,o);if(l===0||Math.abs(a)<=l*1e-12)return null;const h=e.a[0]-i[0],f=e.a[1]-i[1];return{s:(h*o-f*s)/a,u:(h*r-f*n)/a}}function js(i,t){const e=Math.cos(t[1]*Math.PI/180);let n={segmentIndex:0,t:0,coordinate:i[0],distance:1/0};for(let r=0;r<i.length-1;r++){const s=i[r],o=i[r+1],a=(o[0]-s[0])*e,l=o[1]-s[1],h=a*a+l*l,f=h<Ev*Ev?0:Math.max(0,Math.min(1,((t[0]-s[0])*e*a+(t[1]-s[1])*l)/h)),d=Fd(s,o,f),p=Math.hypot((t[0]-d[0])*e,t[1]-d[1]);p<n.distance&&(n={segmentIndex:r,t:f,coordinate:d,distance:p})}return n}function T8(i,t){const e=[];for(let n=0;n<i.length-1;n++){const r=i[n],s=i[n+1];for(const o of t){const a=qf(r,s,o);if(!a||a.s<-1e-9||a.s>1+1e-9||a.u<-1e-9||a.u>1+1e-9)continue;const l=Math.max(0,Math.min(1,a.s)),h=a.u<=1e-9?o.a:a.u>=1-1e-9?o.b:Fd(r,s,l);e.push({segmentIndex:n,t:l,coordinate:h})}}return e.sort((n,r)=>Zn(n)-Zn(r)),e.filter((n,r)=>r===0||Zn(n)-Zn(e[r-1])>1e-9)}function zf(i,t,e){const n=[t.coordinate];for(let r=t.segmentIndex+1;r<=e.segmentIndex;r++)n.push(i[r]);return n.push(e.coordinate),n.filter((r,s)=>s===0||r[0]!==n[s-1][0]||r[1]!==n[s-1][1])}function R8(i,t,e){const n=i.length,r={segmentIndex:0,coordinate:i[0]},s={segmentIndex:n-2,t:1,coordinate:i[n-1]},o=T8(i,t).filter(d=>Zn(d)>1e-9&&Zn(d)<Zn(s)-1e-9);if(o.length===0)return null;const a=Zn(js(i,e)),l=[...o].reverse().find(d=>Zn(d)<a)??null,h=o.find(d=>Zn(d)>a)??null,f=[];return l&&f.push(zf(i,r,l)),h&&f.push(zf(i,h,s)),f.filter(d=>d.length>=2)}function A8(i,t,e){const n=i.length;if(n<2)return null;const r=Math.cos(e[1]*Math.PI/180),s=p=>Math.hypot((p[0]-e[0])*r,p[1]-e[1]),o=s(i[n-1])<=s(i[0]),a=o?i[n-2]:i[1],l=o?i[n-1]:i[0];let h=1/0,f=null;for(const p of t){const y=qf(a,l,p);!y||y.u<-1e-9||y.u>1+1e-9||y.s<=1+1e-9||y.s<h&&(h=y.s,f=y.u<=1e-9?p.a:y.u>=1-1e-9?p.b:Fd(a,l,y.s))}if(!f)return null;const d=[...i];return o?d[n-1]=f:d[0]=f,d}function O8(i,t,e,n,r){const s=js(i,t),o=js(e,n),a=i[s.segmentIndex],l=i[s.segmentIndex+1],h={a:e[o.segmentIndex],b:e[o.segmentIndex+1]},f=qf(a,l,h);if(!f)return null;const d=Fd(a,l,f.s),p=qf(h.a,h.b,{a,b:l}),y=f.s>=s.t,_=p.s>=o.t,E=y?a:l,w=_?h.a:h.b;let L=d,b=d,S=null;if(r>0){const N=me.forCoordinate(d),C=ib(N.toPlanar(E),N.toPlanar(d),N.toPlanar(w),r);if(!C)return null;S=C.points.map(T=>N.toGeographic(T)),L=S[0],b=S[S.length-1]}const P=(N,C,T,I)=>T?[...N.slice(0,C+1),I]:[I,...N.slice(C+1)];return{line1:P(i,s.segmentIndex,y,L),line2:P(e,o.segmentIndex,_,b),arc:S}}function vb(i,t,e,n){const r=me.forCoordinate(e),s=r.toPlanar(e),o=r.toPlanar(n),a=o[0]-s[0],l=o[1]-s[1];let h=0;const f=y=>y[0]>=t[0]&&y[0]<=t[2]&&y[1]>=t[1]&&y[1]<=t[3],d=y=>{if(!f(y))return y;h++;const _=r.toPlanar(y),E=r.toGeographic([_[0]+a,_[1]+l]);return y.length>2?[E[0],E[1],...y.slice(2)]:E},p=y=>typeof y[0]=="number"?d(y):y.map(p);if(i.type==="GeometryCollection"){const y=i.geometries.map(_=>vb(_,t,e,n));return{geometry:{...i,geometries:y.map(_=>_.geometry)},moved:y.reduce((_,E)=>_+E.moved,0)}}return{geometry:{...i,coordinates:p(i.coordinates)},moved:h}}function F8(i,t,e){const n=i.length,r={segmentIndex:0,coordinate:i[0]},s={segmentIndex:n-2,t:1,coordinate:i[n-1]};let o=js(i,t),a=js(i,e);Zn(a)<Zn(o)&&([o,a]=[a,o]);const l=[];return Zn(o)>1e-9&&l.push(zf(i,r,o)),Zn(a)<Zn(s)-1e-9&&l.push(zf(i,a,s)),l.filter(h=>h.length>=2)}function Eb(i){let t=0;for(let e=0;e<i.length-1;e++)t+=Qe(i[e],i[e+1]).distance;return t}function $8(i,t,e){const n=i.length;if(n<2)return null;const r=Math.cos(t[1]*Math.PI/180),s=l=>Math.hypot((l[0]-t[0])*r,l[1]-t[1]),o=s(i[n-1])<=s(i[0]),a=o?[...i]:[...i].reverse();if(e>=0){const l=a[a.length-1],h=Qe(a[a.length-2],l,{convention:"cad",ucsRotationDeg:0}).angle;a[a.length-1]=es(l,e,h*Math.PI/180)}else{let l=-e;for(;a.length>=2;){const h=a[a.length-1],f=a[a.length-2],d=Qe(f,h).distance;if(l<d-1e-9){const p=Qe(h,f,{convention:"cad",ucsRotationDeg:0}).angle;a[a.length-1]=es(h,l,p*Math.PI/180);break}if(l-=d,a.pop(),a.length<2)return null}}return o?a:a.reverse()}const D8={enabled:!0,acquireDelayMs:400,tolerancePixels:8,maxPoints:5};function wv(i,t,e){const n=t.toPlanar(i.origin),r=[Math.cos(i.angleRad),Math.sin(i.angleRad)],s=Math.abs((e[0]-n[0])*r[1]-(e[1]-n[1])*r[0]);return{line:i,point:n,dir:r,distance:s}}function xv(i,t){const e=i.dir[0]*t.dir[1]-i.dir[1]*t.dir[0];if(Math.abs(e)<1e-9)return null;const n=((t.point[0]-i.point[0])*t.dir[1]-(t.point[1]-i.point[1])*t.dir[0])/e;return[i.point[0]+n*i.dir[0],i.point[1]+n*i.dir[1]]}function G8(i,t){const e=(t[0]-i.point[0])*i.dir[0]+(t[1]-i.point[1])*i.dir[1];return[i.point[0]+e*i.dir[0],i.point[1]+e*i.dir[1]]}function B8(i,t){const{anchor:e,ortho:n,polar:r,frame:s,trackPoints:o,toleranceMeters:a}=t,l=me.forCoordinate(i),h=l.toPlanar(i);let f=null,d=null;if(e){const E=_0(e,i,{ortho:n,polar:r,frame:s});if(E.mode&&E.lockedAngle!==null){const w={origin:e,angleRad:sc(E.lockedAngle,s),source:"anchor"};f=wv(w,l,h),d={coordinate:E.coordinate,mode:E.mode,lines:[w]}}}const p=[0,90];if(r.enabled&&r.incrementDeg>0)for(let E=r.incrementDeg;E<180-1e-9;E+=r.incrementDeg)E!==90&&p.push(E);const y=[];for(const E of o)for(const w of p){const L={origin:E,angleRad:(w+s.ucsRotationDeg)*Math.PI/180,source:"track"},b=wv(L,l,h);b.distance<=a&&y.push(b)}y.sort((E,w)=>E.distance-w.distance);const _=(E,w)=>({coordinate:l.toGeographic(E),mode:"tracking",lines:w});if(f&&y.length>0)for(const E of y){const w=xv(f,E);if(w&&Math.hypot(w[0]-h[0],w[1]-h[1])<=f.distance+a*2)return _(w,[f.line,E.line])}for(let E=0;E<y.length;E++)for(let w=E+1;w<y.length;w++){const L=xv(y[E],y[w]);if(L&&Math.hypot(L[0]-h[0],L[1]-h[1])<=a*2)return _(L,[y[E].line,y[w].line])}return d||(y.length>0?_(G8(y[0],h),[y[0].line]):null)}class q8{constructor(t,e){q(this,"dataSource");q(this,"mapAdapter");q(this,"selectionSourceId","_ofs_selection_source");q(this,"hoverSourceId","_ofs_hover_source");q(this,"flashSourceId","_ofs_flash_source");q(this,"unsubSelection",null);q(this,"currentHoveredFeatureId",null);q(this,"flashTimer",null);this.dataSource=t,this.mapAdapter=e,this.unsubSelection=this.dataSource.on("selection:changed",()=>{this.syncSelectionOverlay()})}setupLayers(){if(this.mapAdapter.isReady)try{const t=xe(this.mapAdapter);if(!t||typeof t.addSource!="function")return;t.getSource(this.selectionSourceId)||(t.addSource(this.selectionSourceId,{type:"geojson",data:{type:"FeatureCollection",features:[]}}),t.addLayer({id:`${this.selectionSourceId}_fill`,source:this.selectionSourceId,type:"fill",filter:["all",["in","$type","Polygon"],["!=","isBbox",!0]],paint:{"fill-color":"#00e5ff","fill-opacity":.22}}),t.addLayer({id:`${this.selectionSourceId}_glow`,source:this.selectionSourceId,type:"line",filter:["all",["in","$type","Polygon","LineString"],["!=","isBbox",!0]],paint:{"line-color":"#00b4d8","line-width":7,"line-blur":3.5,"line-opacity":.85}}),t.addLayer({id:`${this.selectionSourceId}_line`,source:this.selectionSourceId,type:"line",filter:["all",["in","$type","Polygon","LineString"],["!=","isBbox",!0]],paint:{"line-color":"#ffffff","line-width":3,"line-dasharray":[3,2],"line-opacity":1}}),t.addLayer({id:`${this.selectionSourceId}_points`,source:this.selectionSourceId,type:"circle",filter:["all",["in","$type","Point"],["!=","isBbox",!0]],paint:{"circle-radius":9,"circle-color":"#00e5ff","circle-stroke-width":2.5,"circle-stroke-color":"#ffffff","circle-stroke-opacity":1}}),t.addLayer({id:`${this.selectionSourceId}_bbox`,source:this.selectionSourceId,type:"line",filter:["all",["==","$type","Polygon"],["==","isBbox",!0]],paint:{"line-color":"#38bdf8","line-width":1.5,"line-dasharray":[4,4],"line-opacity":.75}})),t.getSource(this.hoverSourceId)||(t.addSource(this.hoverSourceId,{type:"geojson",data:{type:"FeatureCollection",features:[]}}),t.addLayer({id:`${this.hoverSourceId}_fill`,source:this.hoverSourceId,type:"fill",filter:["in","$type","Polygon"],paint:{"fill-color":"#38bdf8","fill-opacity":.15}}),t.addLayer({id:`${this.hoverSourceId}_line`,source:this.hoverSourceId,type:"line",filter:["in","$type","Polygon","LineString"],paint:{"line-color":"#38bdf8","line-width":3.5,"line-opacity":.9,"line-blur":1}}),t.addLayer({id:`${this.hoverSourceId}_point`,source:this.hoverSourceId,type:"circle",filter:["in","$type","Point"],paint:{"circle-radius":8,"circle-color":"#38bdf8","circle-stroke-width":2,"circle-stroke-color":"#ffffff","circle-opacity":.8}})),t.getSource(this.flashSourceId)||(t.addSource(this.flashSourceId,{type:"geojson",data:{type:"FeatureCollection",features:[]}}),t.addLayer({id:`${this.flashSourceId}_fill`,source:this.flashSourceId,type:"fill",filter:["in","$type","Polygon"],paint:{"fill-color":"#22c55e","fill-opacity":.35}}),t.addLayer({id:`${this.flashSourceId}_line`,source:this.flashSourceId,type:"line",filter:["in","$type","Polygon","LineString"],paint:{"line-color":"#4ade80","line-width":5,"line-blur":2,"line-opacity":.95}})),this.bringToFront()}catch{}}bringToFront(){if(this.mapAdapter.isReady)try{const t=xe(this.mapAdapter);if(!t||typeof t.moveLayer!="function")return;const e=[`${this.selectionSourceId}_fill`,`${this.selectionSourceId}_glow`,`${this.selectionSourceId}_line`,`${this.selectionSourceId}_points`,`${this.selectionSourceId}_bbox`,`${this.hoverSourceId}_fill`,`${this.hoverSourceId}_line`,`${this.hoverSourceId}_point`,`${this.flashSourceId}_fill`,`${this.flashSourceId}_line`];for(const n of e)t.getLayer(n)&&t.moveLayer(n)}catch(t){Ht("OFSSelectionOverlay.bringToFront",t)}}syncSelectionOverlay(){const t=xe(this.mapAdapter);if(!t||typeof t.getSource!="function")return;const e=t.getSource(this.selectionSourceId);if(!e||typeof e.setData!="function")return;const n=[],r=this.dataSource.getAllLayers();for(const o of r){const a=this.dataSource.getSelectedFeatureIds(o.id);a.length>0&&a.forEach(l=>{const h=o.getFeature(l);h&&n.push(Ue(h))})}const s=[...n];if(n.length>=2)try{const o=le(n),a=je(o),l=Mp(a,{properties:{isBbox:!0}});s.push(l)}catch(o){Ht("OFSSelectionOverlay.syncSelectionOverlay",o)}e.setData({type:"FeatureCollection",features:s})}previewSelection(t){const e=xe(this.mapAdapter);if(!e||typeof e.getSource!="function")return;const n=e.getSource(this.selectionSourceId);!n||typeof n.setData!="function"||n.setData({type:"FeatureCollection",features:t.map(r=>Ue(r))})}setHoverFeature(t){if(!this.mapAdapter.isReady)return;const e=xe(this.mapAdapter);if(!e||typeof e.getSource!="function")return;const n=e.getSource(this.hoverSourceId);if(!(!n||typeof n.setData!="function")){if(!t){this.currentHoveredFeatureId=null,n.setData({type:"FeatureCollection",features:[]});return}this.currentHoveredFeatureId!==t.id&&(this.currentHoveredFeatureId=t.id??null,n.setData({type:"FeatureCollection",features:[Ue(t)]}))}}flashFeatures(t,e=750){const n=Array.isArray(t)?t:[t];if(!this.mapAdapter.isReady||n.length===0)return;const r=xe(this.mapAdapter);if(!r||typeof r.getSource!="function")return;const s=r.getSource(this.flashSourceId);!s||typeof s.setData!="function"||(this.flashTimer&&clearTimeout(this.flashTimer),s.setData({type:"FeatureCollection",features:n.map(o=>Ue(o))}),this.flashTimer=setTimeout(()=>{try{s.setData({type:"FeatureCollection",features:[]})}catch(o){Ht("OFSSelectionOverlay.flashFeatures",o)}this.flashTimer=null},e))}destroy(){this.unsubSelection&&this.unsubSelection(),this.flashTimer&&clearTimeout(this.flashTimer);try{const t=xe(this.mapAdapter);t&&([`${this.selectionSourceId}_fill`,`${this.selectionSourceId}_glow`,`${this.selectionSourceId}_line`,`${this.selectionSourceId}_points`,`${this.selectionSourceId}_bbox`,`${this.hoverSourceId}_fill`,`${this.hoverSourceId}_line`,`${this.hoverSourceId}_point`,`${this.flashSourceId}_fill`,`${this.flashSourceId}_line`].forEach(n=>{t.getLayer(n)&&t.removeLayer(n)}),t.getSource(this.selectionSourceId)&&t.removeSource(this.selectionSourceId),t.getSource(this.hoverSourceId)&&t.removeSource(this.hoverSourceId),t.getSource(this.flashSourceId)&&t.removeSource(this.flashSourceId))}catch(t){Ht("OFSSelectionOverlay.destroy",t)}}}const z8=["Open Sans Regular","Arial Unicode MS Regular"],U8=["_dim_labels","_labels"],wb={crosshair:!1,dimensions:!0,segmentLabels:!1,areaLabel:!0,anchor:"cursor",crosshairColor:"#ffffff",crosshairWidth:.75,angles:!0,dimensionOffsetPixels:26,font:null},bv=["all",["in","$type","LineString","Polygon"],["!=","isTracking",!0],["!=","isGuide",!0],["!=","isDim",!0],["!=","isDimExt",!0],["!=","isAngle",!0]],Iv=["all",["==","$type","Point"],["!=","isSnap",!0],["!=","isLabel",!0],["!=","isTrackPoint",!0]],Y8={point:"crosshair",line:"crosshair",polygon:"crosshair",circle:"crosshair",rectangle:"crosshair","select-box":"crosshair","select-polygon":"crosshair",select:"default",modify:"default"};class xb extends no{constructor(e,n){super();q(this,"dataSource");q(this,"mapAdapter");q(this,"snapping");q(this,"grips");q(this,"selectionOverlay");q(this,"preview");q(this,"orthoEnabled",!1);q(this,"polarTracking",{...m0});q(this,"inputFrame",{convention:"bearing",ucsRotationDeg:0});q(this,"lastCursorCoord",null);q(this,"lastConstraint",null);q(this,"objectTracking",{...D8});q(this,"trackingPoints",[]);q(this,"trackingHover",null);q(this,"now",()=>Date.now());q(this,"pointPick",null);q(this,"currentMode",null);q(this,"activeCoordinates",[]);q(this,"activeBulges",[]);q(this,"arcSegment",!1);q(this,"arcSweepRadians",null);q(this,"sagToleranceMeters",Ms);q(this,"targetLayerId",null);q(this,"tempSourceId","_ofs_draw_temp");q(this,"unsubClick",null);q(this,"unsubDblClick",null);q(this,"unsubContextMenu",null);q(this,"unsubMove",null);q(this,"unsubMouseDown",null);q(this,"unsubMouseUp",null);q(this,"isDrawing",!1);q(this,"guides",{...wb});q(this,"dragSelectStart",null);q(this,"isDragSelecting",!1);q(this,"justFinishedDrag",!1);q(this,"handleKeyDown",e=>{var r;const n=(r=e.target)==null?void 0:r.tagName;if(!(n==="INPUT"||n==="TEXTAREA")){if(e.key==="F8"){e.preventDefault(),this.toggleOrtho();return}if(e.key==="F10"){e.preventDefault(),this.togglePolarTracking();return}if(e.key==="F11"){e.preventDefault(),this.setObjectTracking({enabled:!this.objectTracking.enabled});return}if(e.key==="F3"){e.preventDefault(),this.snapping.enabled=!this.snapping.enabled;return}if(e.key==="Enter"){(this.isDrawing||this.grips.getIsEditing()||this.currentMode==="modify"||this.currentMode==="select")&&(e.preventDefault(),this.finishDrawing());return}if(e.key==="Escape"){(this.isDrawing||this.grips.getIsEditing()||this.currentMode)&&(e.preventDefault(),this.cancel());return}if((this.currentMode==="line"||this.currentMode==="polygon")&&!e.ctrlKey&&!e.metaKey&&!e.altKey){const s=e.key.toLowerCase();(s==="a"||s==="l")&&(e.preventDefault(),this.setArcSegment(s==="a"))}}});this.dataSource=e,this.mapAdapter=n,this.snapping=new rc(e,n),this.grips=new mb(e,n,this.snapping),this.selectionOverlay=new q8(e,n),this.preview=new yb(n),this.bindMapEvents()}setOrtho(e){this.orthoEnabled=e,this.emit("draw:ortho-change",{enabled:e})}toggleOrtho(){return this.orthoEnabled=!this.orthoEnabled,this.emit("draw:ortho-change",{enabled:this.orthoEnabled}),this.orthoEnabled}setPolarTracking(e){this.polarTracking={...this.polarTracking,...e},this.emit("draw:polar-change",{enabled:this.polarTracking.enabled,incrementDeg:this.polarTracking.incrementDeg})}togglePolarTracking(){return this.setPolarTracking({enabled:!this.polarTracking.enabled}),this.polarTracking.enabled}setUcsRotation(e){this.inputFrame={...this.inputFrame,ucsRotationDeg:(e%360+360)%360},this.emit("draw:ucs-change",{...this.inputFrame})}setAngleConvention(e){this.inputFrame={...this.inputFrame,convention:e},this.emit("draw:ucs-change",{...this.inputFrame})}setArcSegment(e,n={}){this.arcSegment=e;const r=n.sweepDegrees;r!==void 0&&(this.arcSweepRadians=r===null||!Number.isFinite(r)||r===0?null:r*Math.PI/180),this.emit("draw:arc-segment",{enabled:e,sweepDegrees:this.arcSweepRadians===null?null:this.arcSweepRadians*180/Math.PI,ready:!e||this.arcSweepRadians!==null||this.activeCoordinates.length>=2}),this.lastCursorCoord&&this.updateTempFeatures(this.lastCursorCoord,null)}toggleArcSegment(){return this.setArcSegment(!this.arcSegment),this.arcSegment}isArcSegment(){return this.arcSegment}getActiveBulges(){return[...this.activeBulges]}setSagTolerance(e){Number.isFinite(e)&&e>0&&(this.sagToleranceMeters=e)}getSagTolerance(){return this.sagToleranceMeters}headingAtLastVertex(e){const n=this.activeCoordinates.length;if(n<2)return null;const r=e.toPlanar(this.activeCoordinates[n-2]),s=e.toPlanar(this.activeCoordinates[n-1]),o=this.activeBulges[n-2]??0;if(o){const a=d0(r,s,o);if(a)return ub(a,1)}return[s[0]-r[0],s[1]-r[1]]}bulgeForSegmentTo(e){if(!this.arcSegment||this.activeCoordinates.length===0)return 0;const n=this.activeCoordinates[this.activeCoordinates.length-1],r=ei([...this.activeCoordinates,e]),s=r.toPlanar(n),o=r.toPlanar(e),a=this.arcSweepRadians!==null?Rd(s,o,this.arcSweepRadians):(()=>{const l=this.headingAtLastVertex(r);return l?hb(s,o,l):null})();return a?Td(a):0}curveLengthMeters(e,n){if(!e)return dl(ae(n),{units:"meters"});const r=ei(e.vertices);let s=0;for(let o=0;o<e.vertices.length-1;o++){const a=$l(e,o,r);s+=a?lb(a):r.distance(e.vertices[o],e.vertices[o+1])}return s}previewCoordinates(e){const n=[...this.activeCoordinates,e];if(n.length<2)return n;const r=ku(n,[...this.activeBulges,this.bulgeForSegmentTo(e)],this.sagToleranceMeters);return r?Pu(r):n}getMapAdapter(){return this.mapAdapter}getCursorCoordinate(){return this.lastCursorCoord}isDrawModeActive(){return["point","line","polygon","circle","rectangle","select-polygon"].includes(this.currentMode)}getReferencePoint(){return this.pointPick?this.pointPick.basePoint??null:this.isDrawing&&this.activeCoordinates.length>0?this.activeCoordinates[this.activeCoordinates.length-1]:null}resolveCursor(e,n,r=[]){const s=this.snapping.getSnap(e,r,{fromPoint:n});if(s)return{coordinate:s.coordinate,snap:s,constraint:null};const o=this.objectTracking.enabled&&this.snapping.enabled?this.trackingPoints:[],a=B8(e,{anchor:n,ortho:this.orthoEnabled,polar:this.polarTracking,frame:this.inputFrame,trackPoints:o,toleranceMeters:this.objectTracking.tolerancePixels*this.metersPerPixel(e)});return a?{coordinate:a.coordinate,snap:null,constraint:a}:{coordinate:e,snap:null,constraint:null}}metersPerPixel(e){const n=xe(this.mapAdapter);if(!n||typeof n.project!="function"||typeof n.unproject!="function")return 1;try{const r=n.project(e),s=n.unproject([r.x+1,r.y]),o=Array.isArray(s)?[s[0],s[1]]:[s.lng,s.lat],a=Qe(e,o).distance;return Number.isFinite(a)&&a>0?a:1}catch(r){return Ht("OFSDrawTools.metersPerPixel",r),1}}setObjectTracking(e){this.objectTracking={...this.objectTracking,...e},this.objectTracking.enabled||this.clearTrackingPoints(),this.emit("draw:otrack-change",{enabled:this.objectTracking.enabled})}getTrackingPoints(){return[...this.trackingPoints]}clearTrackingPoints(){this.trackingHover=null,this.trackingPoints.length!==0&&(this.trackingPoints=[],this.emit("draw:tracking-points",{points:[]}))}updateTrackingAcquisition(e){if(!this.objectTracking.enabled||!this.snapping.enabled||!e||e.type==="edge"){this.trackingHover=null;return}const n=`${e.coordinate[0]},${e.coordinate[1]}`,r=this.now();if((!this.trackingHover||this.trackingHover.key!==n)&&(this.trackingHover={key:n,coord:e.coordinate,since:r,handled:!1}),this.trackingHover.handled||r-this.trackingHover.since<this.objectTracking.acquireDelayMs)return;this.trackingHover.handled=!0;const s=this.trackingPoints.findIndex(o=>o[0]===e.coordinate[0]&&o[1]===e.coordinate[1]);s>=0?this.trackingPoints.splice(s,1):(this.trackingPoints.push(e.coordinate),this.trackingPoints.length>this.objectTracking.maxPoints&&this.trackingPoints.shift()),this.emit("draw:tracking-points",{points:[...this.trackingPoints]})}getInProgressSnapCoords(){return!this.isDrawing||this.activeCoordinates.length===0?[]:(this.currentMode==="polygon"||this.currentMode==="select-polygon")&&this.activeCoordinates.length>=3?[this.activeCoordinates[0]]:this.currentMode==="line"&&this.activeCoordinates.length>=2?this.activeCoordinates.slice(0,-1):[]}submitInput(e){const n=["point","line","polygon","circle","rectangle","select-polygon"];if(!this.currentMode||!n.includes(this.currentMode))return{handled:!1};const r=e.trim(),s=r.toLowerCase();if(r==="")return this.isDrawing?this.finishDrawing()?{handled:!0,message:`${this.currentMode??"Drawing"} finished.`}:{handled:!0,error:"Not enough points to finish."}:{handled:!1};if(this.isDrawing&&(s==="u"||s==="undo"))return this.undoLastVertex()?{handled:!0,message:"Last point removed."}:{handled:!0,error:"Nothing to undo."};if((this.currentMode==="line"||this.currentMode==="polygon")&&["a","arc","l","line"].includes(s)){const a=s==="a"||s==="arc";return this.setArcSegment(a),a&&this.arcSweepRadians===null&&this.activeCoordinates.length<2?{handled:!0,message:"Arc mode on. The first segment stays straight until there is one to curve from."}:{handled:!0,message:a?"Arc segments.":"Straight segments."}}if(this.isDrawing&&(s==="c"||s==="close"))return(this.currentMode==="polygon"||this.currentMode==="select-polygon")&&this.activeCoordinates.length>=3?(this.finishDrawing(),{handled:!0,message:"Polygon closed."}):this.currentMode==="line"&&this.activeCoordinates.length>=3?(this.commitDrawPoint(this.activeCoordinates[0],null),this.finishDrawing(),{handled:!0,message:"Line closed."}):{handled:!0,error:"Close needs at least 3 points."};const o=y0(r,{basePoint:this.getReferencePoint(),cursor:this.lastCursorCoord,frame:this.inputFrame});return o?o.kind==="error"?{handled:!0,error:o.message}:(this.commitDrawPoint(o.coordinate,null),{handled:!0,message:`Point: ${o.description}`}):{handled:!1}}undoLastVertex(){return!this.isDrawing||this.activeCoordinates.length===0?!1:(this.activeCoordinates.pop(),this.activeBulges.pop(),this.activeCoordinates.length===0&&(this.isDrawing=!1),this.emit("draw:vertex-removed",{mode:this.currentMode,coordinates:[...this.activeCoordinates]}),this.updateTempFeatures(this.lastCursorCoord??this.activeCoordinates[this.activeCoordinates.length-1]??[0,0],null),!0)}beginPointPick(e,n){const r={...e,onPick:n};return this.pointPick=r,this.applyCursor(),()=>{this.pointPick===r&&(this.pointPick=null,this.applyCursor(),this.clearTrackingPoints(),this.lastConstraint=null,this.clearTempFeatures())}}isPickingPoint(){return this.pointPick!==null}setupTempDrawingLayer(){if(this.mapAdapter.isReady){this.preview.setupLayers();try{const e=this.mapAdapter.getRawMap();if(!e)return;if(!e.getSource(this.tempSourceId))e.addSource(this.tempSourceId,{type:"geojson",data:{type:"FeatureCollection",features:[]}}),e.addLayer({id:`${this.tempSourceId}_fill`,source:this.tempSourceId,type:"fill",filter:["==","$type","Polygon"],paint:{"fill-color":"#3b82f6","fill-opacity":.25}}),e.addLayer({id:`${this.tempSourceId}_crosshair_shadow`,source:this.tempSourceId,type:"line",filter:["all",["==","$type","LineString"],["==","isGuide",!0]],paint:{"line-color":"#0f172a","line-width":2,"line-opacity":.25,"line-dasharray":[5,5]}}),e.addLayer({id:`${this.tempSourceId}_crosshair`,source:this.tempSourceId,type:"line",filter:["all",["==","$type","LineString"],["==","isGuide",!0]],paint:{"line-color":this.guides.crosshairColor,"line-width":this.guides.crosshairWidth,"line-opacity":.95,"line-dasharray":[5,5]}}),e.addLayer({id:`${this.tempSourceId}_line`,source:this.tempSourceId,type:"line",filter:bv,paint:{"line-color":"#2563eb","line-width":2.5,"line-dasharray":[2,1]}}),e.addLayer({id:`${this.tempSourceId}_dim_ext`,source:this.tempSourceId,type:"line",filter:["all",["==","$type","LineString"],["==","isDimExt",!0]],paint:{"line-color":"#334155","line-width":.75,"line-opacity":.7}}),e.addLayer({id:`${this.tempSourceId}_dim`,source:this.tempSourceId,type:"line",filter:["all",["==","$type","LineString"],["==","isDim",!0]],paint:{"line-color":["case",["==",["get","isLive"],!0],"#1d4ed8","#334155"],"line-width":1}}),e.addLayer({id:`${this.tempSourceId}_dim_labels`,source:this.tempSourceId,type:"symbol",filter:["all",["==","$type","LineString"],["==","isDim",!0]],layout:{"text-field":["get","label"],"text-font":this.guideFont(),"text-size":["case",["==",["get","isLive"],!0],13,11],"symbol-placement":"line-center","text-rotation-alignment":"map","text-offset":[0,-.7],"text-allow-overlap":!1},paint:{"text-color":["case",["==",["get","isLive"],!0],"#1d4ed8","#334155"],"text-halo-color":"#ffffff","text-halo-width":1.6}}),e.addLayer({id:`${this.tempSourceId}_angle_arc`,source:this.tempSourceId,type:"line",filter:["all",["==","$type","LineString"],["==","isAngle",!0]],paint:{"line-color":["case",["==",["get","isLive"],!0],"#16a34a","#64748b"],"line-width":1.25}}),e.addLayer({id:`${this.tempSourceId}_labels`,source:this.tempSourceId,type:"symbol",filter:["all",["==","$type","Point"],["==","isLabel",!0]],layout:{"text-field":["get","label"],"text-font":this.guideFont(),"text-size":["case",["==",["get","isLive"],!0],13,11],"text-offset":[0,-.8],"text-anchor":"bottom","text-allow-overlap":!1,"text-ignore-placement":!1,"symbol-z-order":"source"},paint:{"text-color":["case",["==",["get","isLive"],!0],"#1d4ed8","#334155"],"text-halo-color":"#ffffff","text-halo-width":1.6}}),e.addLayer({id:`${this.tempSourceId}_points`,source:this.tempSourceId,type:"circle",filter:Iv,paint:{"circle-radius":5,"circle-color":"#1d4ed8","circle-stroke-width":2,"circle-stroke-color":"#ffffff"}}),e.addLayer({id:`${this.tempSourceId}_snap_halo`,source:this.tempSourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":22,"circle-color":["match",["get","snapType"],"midpoint","#38bdf8","edge","#a855f7","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#3b82f6"],"circle-blur":.85,"circle-opacity":.7}}),e.addLayer({id:`${this.tempSourceId}_snap_glow`,source:this.tempSourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":11,"circle-color":["match",["get","snapType"],"midpoint","#0ea5e9","edge","#8b5cf6","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#2563eb"],"circle-blur":.35,"circle-opacity":.55}}),e.addLayer({id:`${this.tempSourceId}_snap_core`,source:this.tempSourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":5.5,"circle-color":["match",["get","snapType"],"midpoint","#0284c7","edge","#7c3aed","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#1d4ed8"],"circle-stroke-width":2,"circle-stroke-color":"#ffffff","circle-stroke-opacity":1}});else{e.getLayer(`${this.tempSourceId}_snap_halo`)||e.addLayer({id:`${this.tempSourceId}_snap_halo`,source:this.tempSourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":22,"circle-color":["match",["get","snapType"],"midpoint","#38bdf8","edge","#a855f7","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#3b82f6"],"circle-blur":.85,"circle-opacity":.7}});try{e.getLayer(`${this.tempSourceId}_points`)&&e.setFilter(`${this.tempSourceId}_points`,["all",["==","$type","Point"],["!=","isSnap",!0]]),e.getLayer(`${this.tempSourceId}_snap_halo`)&&e.setFilter(`${this.tempSourceId}_snap_halo`,["all",["==","$type","Point"],["==","isSnap",!0]]),e.getLayer(`${this.tempSourceId}_snap_glow`)&&e.setFilter(`${this.tempSourceId}_snap_glow`,["all",["==","$type","Point"],["==","isSnap",!0]]),e.getLayer(`${this.tempSourceId}_snap_core`)&&e.setFilter(`${this.tempSourceId}_snap_core`,["all",["==","$type","Point"],["==","isSnap",!0]])}catch(n){Ht("OFSDrawTools.setupTempDrawingLayer",n)}}this.ensureTrackingLayer(e),this.selectionOverlay.setupLayers(),this.selectionOverlay.syncSelectionOverlay(),this.bringTempLayersToFront()}catch{}}}ensureTrackingLayer(e){try{e.getLayer(`${this.tempSourceId}_line`)&&e.setFilter(`${this.tempSourceId}_line`,bv),e.getLayer(`${this.tempSourceId}_points`)&&e.setFilter(`${this.tempSourceId}_points`,Iv),e.getLayer(`${this.tempSourceId}_trackpoints`)||e.addLayer({id:`${this.tempSourceId}_trackpoints`,source:this.tempSourceId,type:"circle",filter:["==","isTrackPoint",!0],paint:{"circle-radius":5,"circle-color":"rgba(0,0,0,0)","circle-stroke-color":"#f59e0b","circle-stroke-width":2}}),e.getLayer(`${this.tempSourceId}_tracking`)||e.addLayer({id:`${this.tempSourceId}_tracking`,source:this.tempSourceId,type:"line",filter:["==","isTracking",!0],paint:{"line-color":"#f59e0b","line-width":1.25,"line-dasharray":[4,3],"line-opacity":.9}})}catch(n){Ht("OFSDrawTools.ensureTrackingLayer",n)}}trackingFeatures(e){const r=this.objectTracking.enabled&&this.snapping.enabled?this.trackingPoints.map(o=>Lt(o,{isTrackPoint:!0})):[],s=this.lastConstraint;if(!s||e!==this.lastCursorCoord)return r;for(const o of s.lines){const{distance:a}=Qe(o.origin,e),l=Math.max(a*4,a+200),h=o.source==="track"?es(o.origin,-l,o.angleRad):o.origin,f=a>1e-6?Qe(o.origin,e,{convention:"cad",ucsRotationDeg:0}).angle*Math.PI/180:o.angleRad,d=es(o.origin,l,f);r.push(ae([h,d],{isTracking:!0}))}return r}bringTempLayersToFront(){var e;if((e=this.mapAdapter)!=null&&e.isReady)try{const n=xe(this.mapAdapter);if(!n||typeof n.getLayer!="function"||typeof n.moveLayer!="function")return;this.preview.bringToFront();const r=[`${this.tempSourceId}_fill`,`${this.tempSourceId}_crosshair_shadow`,`${this.tempSourceId}_crosshair`,`${this.tempSourceId}_tracking`,`${this.tempSourceId}_trackpoints`,`${this.tempSourceId}_line`,`${this.tempSourceId}_dim_ext`,`${this.tempSourceId}_dim`,`${this.tempSourceId}_dim_labels`,`${this.tempSourceId}_angle_arc`,`${this.tempSourceId}_points`,`${this.tempSourceId}_snap_halo`,`${this.tempSourceId}_snap_glow`,`${this.tempSourceId}_snap_core`];for(const s of r)n.getLayer(s)&&n.moveLayer(s);this.selectionOverlay.bringToFront()}catch(n){Ht("OFSDrawTools.bringTempLayersToFront",n)}}bindMapEvents(){this.unsubClick=typeof this.mapAdapter.onMapClick=="function"?this.mapAdapter.onMapClick(e=>this.handleMapClick(e)):()=>{},this.unsubDblClick=typeof this.mapAdapter.onMapDblClick=="function"?this.mapAdapter.onMapDblClick(e=>this.handleMapDblClick(e)):()=>{},this.unsubContextMenu=typeof this.mapAdapter.onContextMenu=="function"?this.mapAdapter.onContextMenu(e=>this.handleContextMenu(e)):()=>{},this.unsubMove=typeof this.mapAdapter.onMouseMove=="function"?this.mapAdapter.onMouseMove(e=>this.handleMouseMove(e)):()=>{},this.unsubMouseDown=typeof this.mapAdapter.onMouseDown=="function"?this.mapAdapter.onMouseDown(e=>this.handleMouseDown(e)):()=>{},this.unsubMouseUp=typeof this.mapAdapter.onMouseUp=="function"?this.mapAdapter.onMouseUp(e=>this.handleMouseUp(e)):()=>{},typeof window<"u"&&window.addEventListener("keydown",this.handleKeyDown)}getRequiredGeometryType(e){return e==="point"?"point":e==="line"?"line":"polygon"}resolveTargetLayerId(e,n){const r=this.getRequiredGeometryType(e);if(n){const f=this.dataSource.getLayer(n);if(f&&f.type===r)return f.id}const s=this.dataSource.getActiveLayer();if(s&&s.type===r)return s.id;const o=this.dataSource.getAllLayers().find(f=>f.type===r&&f.visible);if(o)return this.dataSource.setActiveLayer(o.id),o.id;const a=this.dataSource.getAllLayers().find(f=>f.type===r);if(a)return this.dataSource.setActiveLayer(a.id),a.id;const l=r.charAt(0).toUpperCase()+r.slice(1),h=this.dataSource.addLayer({id:`draw_${r}_layer`,name:`${l}s Layer (Drawn)`,type:r,zIndex:10});return this.dataSource.setActiveLayer(h.id),h.id}getTargetLayerId(){return this.targetLayerId}setMode(e,n){var r;if(this.currentMode!==e){this.isDrawing&&this.cancel(),this.currentMode=e,e!=="modify"&&this.grips.getIsEditing()&&this.grips.clear(),e==="select"||e==="modify"||e==="select-box"||e==="select-polygon"?this.targetLayerId=n||null:e?this.targetLayerId=this.resolveTargetLayerId(e,n):(this.targetLayerId=null,this.grips.clear()),this.setupTempDrawingLayer(),this.emit("draw:mode-change",{mode:e});try{if((r=this.mapAdapter)!=null&&r.isReady){typeof this.mapAdapter.setDoubleClickZoom=="function"&&this.mapAdapter.setDoubleClickZoom(e===null||e==="select"||e==="modify");const s=xe(this.mapAdapter);s&&(s.boxZoom&&(e==="select"||e==="select-box"||e==="select-polygon"?s.boxZoom.disable():s.boxZoom.enable()),this.applyCursor())}}catch(s){Ht("OFSDrawTools.setMode",s)}}}getMode(){return this.currentMode}getIsDrawing(){return this.isDrawing}getActiveCoordinates(){return[...this.activeCoordinates]}handleMouseDown(e){if(this.currentMode&&(this.currentMode==="select"||this.currentMode==="select-box")){if(this.grips.getIsEditing()&&this.grips.hasHandleAt(e.coordinate,18))return;this.dragSelectStart={coord:e.coordinate,point:{x:e.point.x,y:e.point.y}},this.isDragSelecting=!1}}handleMouseUp(e){var r;const n=xe(this.mapAdapter);if(n&&n.dragPan&&!n.dragPan.isEnabled()&&n.dragPan.enable(),this.isDragSelecting&&this.dragSelectStart){const s=this.dragSelectStart.coord,o=e.coordinate,a=Math.min(s[0],o[0]),l=Math.max(s[0],o[0]),h=Math.min(s[1],o[1]),f=Math.max(s[1],o[1]),d=Pe([[[a,h],[l,h],[l,f],[a,f],[a,h]]]),p=!!((r=e.originalEvent)!=null&&r.shiftKey);this.executeDrawSelection("select-box",d,p),this.justFinishedDrag=!0,setTimeout(()=>{this.justFinishedDrag=!1},150),this.isDragSelecting=!1,this.dragSelectStart=null,this.clearTempFeatures();return}this.dragSelectStart=null,this.isDragSelecting=!1}handleMapClick(e){var o,a,l;if(this.pointPick){const h=this.pointPick,{coordinate:f}=this.resolveCursor(e.coordinate,h.basePoint??null);this.pointPick=null,this.applyCursor(),this.clearTrackingPoints(),this.lastConstraint=null,this.clearTempFeatures(),h.onPick(f);return}if(!this.currentMode||this.justFinishedDrag)return;if(this.currentMode==="select"){this.grips.getIsEditing()&&this.grips.clear();const h=!!((o=e.originalEvent)!=null&&o.shiftKey);if(e.features&&e.features.length>0){const f=e.features[0];if(f.id!==void 0&&f.layerId){h?this.dataSource.toggleFeatureSelection(f.layerId,f.id):this.dataSource.selectFeature(f.layerId,f.id,!1);return}}else{h||this.dataSource.clearSelection();return}return}if(this.currentMode==="modify"){if(this.grips.getIsEditing()&&this.grips.hasHandleAt(e.coordinate,18))return;const h=!!((a=e.originalEvent)!=null&&a.shiftKey);if(e.features&&e.features.length>0){const f=e.features[0];if(f.id!==void 0&&f.layerId){this.dataSource.selectFeature(f.layerId,f.id,!1),this.grips.editFeature(f.layerId,f.id);return}}else{h||this.stopEdit();return}return}if(this.currentMode==="select-box"){const h=e.coordinate,f=!!((l=e.originalEvent)!=null&&l.shiftKey);if(!this.isDrawing)this.isDrawing=!0,this.activeCoordinates=[h],this.emit("draw:start",{mode:"select-box",coordinate:h}),this.updateTempFeatures(h,null);else{const d=this.activeCoordinates[0],p=h,y=Math.min(d[0],p[0]),_=Math.max(d[0],p[0]),E=Math.min(d[1],p[1]),w=Math.max(d[1],p[1]),L=Pe([[[y,E],[_,E],[_,w],[y,w],[y,E]]]);this.executeDrawSelection("select-box",L,f),this.resetDrawingState(!0)}return}const n=this.isDrawing&&this.activeCoordinates.length>0?this.activeCoordinates[this.activeCoordinates.length-1]:null,{coordinate:r,snap:s}=this.resolveCursor(e.coordinate,n,this.getInProgressSnapCoords());this.commitDrawPoint(r,s,!0)}commitDrawPoint(e,n,r=!1){if(this.currentMode){if(this.isDrawing){if((this.currentMode==="polygon"||this.currentMode==="select-polygon")&&this.activeCoordinates.length>=3){const o=this.activeCoordinates[0];let a=!1;if(n&&n.coordinate[0]===o[0]&&n.coordinate[1]===o[1])a=!0;else if(e[0]===o[0]&&e[1]===o[1])a=!0;else if(r)try{const l=xe(this.mapAdapter);if(l&&typeof l.project=="function"){const h=l.project([o[0],o[1]]),f=l.project([e[0],e[1]]);h&&f&&Math.hypot(h.x-f.x,h.y-f.y)<=12&&(a=!0)}else Co(e,o)<.5&&(a=!0)}catch(l){Ht("OFSDrawTools.commitDrawPoint",l),Co(e,o)<.5&&(a=!0)}if(a){this.finishDrawing();return}}const s=this.activeCoordinates[this.activeCoordinates.length-1];if(s[0]===e[0]&&s[1]===e[1]&&(this.currentMode==="line"&&this.activeCoordinates.length>=2||(this.currentMode==="polygon"||this.currentMode==="select-polygon")&&this.activeCoordinates.length>=3)){this.finishDrawing();return}if(this.activeBulges.push(this.bulgeForSegmentTo(e)),this.activeCoordinates.push(e),this.emit("draw:vertex-added",{mode:this.currentMode,coordinate:e,coordinates:[...this.activeCoordinates]}),(this.currentMode==="circle"||this.currentMode==="rectangle")&&this.activeCoordinates.length>=2){this.finishDrawing();return}}else if(this.isDrawing=!0,this.activeCoordinates=[e],this.emit("draw:start",{mode:this.currentMode,coordinate:e}),this.currentMode==="point"){this.finishDrawing();return}this.updateTempFeatures(e,n)}}handleMapDblClick(e){if(this.currentMode){if(this.currentMode==="select"&&e.features&&e.features.length>0){const n=e.features[0];if(n.id!==void 0&&n.layerId){this.startEdit(n.layerId,n.id);return}}if(this.isDrawing&&(this.currentMode==="line"||this.currentMode==="polygon"||this.currentMode==="select-polygon")){if(this.activeCoordinates.length>1){const n=this.activeCoordinates[this.activeCoordinates.length-1],r=this.activeCoordinates[this.activeCoordinates.length-2];n[0]===r[0]&&n[1]===r[1]&&this.activeCoordinates.pop()}this.finishDrawing()}}}handleContextMenu(e){this.currentMode&&(e.originalEvent&&e.originalEvent.preventDefault(),this.isDrawing&&((this.currentMode==="polygon"||this.currentMode==="select-polygon")&&this.activeCoordinates.length>=3||this.currentMode==="line"&&this.activeCoordinates.length>=2?this.finishDrawing():this.cancel()))}handleMouseMove(e){if(this.pointPick){const a=this.pointPick.basePoint??null,{coordinate:l,snap:h,constraint:f}=this.resolveCursor(e.coordinate,a);this.updateTrackingAcquisition(h),this.lastCursorCoord=l,this.lastConstraint=f,a&&this.emitMeasure(a,l,f),this.emit("draw:move",{coordinate:l,isSnapped:!!h,snapResult:h||void 0}),this.updatePickPreview(l,h);return}if(this.dragSelectStart&&Math.hypot(e.point.x-this.dragSelectStart.point.x,e.point.y-this.dragSelectStart.point.y)>4){this.isDragSelecting=!0;const l=xe(this.mapAdapter);l&&l.dragPan&&l.dragPan.isEnabled()&&l.dragPan.disable(),this.updateDragBoxPreview(this.dragSelectStart.coord,e.coordinate);const h=Math.min(this.dragSelectStart.coord[0],e.coordinate[0]),f=Math.max(this.dragSelectStart.coord[0],e.coordinate[0]),d=Math.min(this.dragSelectStart.coord[1],e.coordinate[1]),p=Math.max(this.dragSelectStart.coord[1],e.coordinate[1]),y=Pe([[[h,d],[f,d],[f,p],[h,p],[h,d]]]),_=this.queryFeaturesInGeometry(y);this.selectionOverlay.previewSelection(_.map(L=>L.feature));const E=Co([h,d],[f,d]),w=Co([h,d],[h,p]);this.emit("selection:drag-progress",{widthMeters:Math.round(E*10)/10,heightMeters:Math.round(w*10)/10,count:_.length,coordinate:e.coordinate});return}if(this.currentMode==="select"||this.currentMode==="modify"){const a=e.features&&e.features.length>0?e.features[0]:null,l=xe(this.mapAdapter),h=l&&typeof l.getCanvas=="function"?l.getCanvas():null;if(a&&a.id!==void 0&&a.layerId){const f=this.dataSource.getLayer(a.layerId),d=f==null?void 0:f.getFeature(a.id);this.selectionOverlay.setHoverFeature(d||a),h&&(h.style.cursor="pointer")}else this.selectionOverlay.setHoverFeature(null),h&&(h.style.cursor="default");return}if(!this.currentMode)return;const n=this.isDrawing&&this.activeCoordinates.length>0?this.activeCoordinates[this.activeCoordinates.length-1]:null,{coordinate:r,snap:s,constraint:o}=this.resolveCursor(e.coordinate,n,this.getInProgressSnapCoords());this.isDrawModeActive()&&this.updateTrackingAcquisition(s),this.lastCursorCoord=r,this.lastConstraint=o,n&&this.emitMeasure(n,r,o),this.emit("draw:move",{coordinate:r,isSnapped:!!s,snapResult:s||void 0}),this.updateTempFeatures(r,s)}emitMeasure(e,n,r){const s=Qe(e,n,this.inputFrame),o=Qe(e,n,{convention:"bearing",ucsRotationDeg:0});this.emit("draw:measure",{distanceMeters:Math.round(s.distance*1e3)/1e3,bearingDegrees:Math.round(o.angle*100)/100,angle:Math.round(s.angle*100)/100,constraint:(r==null?void 0:r.mode)??null,coordinate:n})}updatePickPreview(e,n){var l;const r=xe(this.mapAdapter),s=r&&typeof r.getSource=="function"?r.getSource(this.tempSourceId):null;if(!s||typeof s.setData!="function")return;const o=[];n&&o.push(Lt(n.coordinate,{isSnap:!0,snapType:n.type}));const a=(l=this.pointPick)==null?void 0:l.basePoint;a&&(o.push(Lt(a,{isSnap:!1})),o.push(ae([a,e])),o.push(...this.trackingFeatures(e))),s.setData({type:"FeatureCollection",features:o})}finishDrawing(){if(this.grips.getIsEditing()||this.currentMode==="modify"){const r=this.grips.getActiveFeature(),s=this.grips.activeLayerId||this.targetLayerId||this.dataSource.getActiveLayerId()||"";return this.stopEdit(),(this.currentMode==="modify"||this.currentMode==="select")&&this.resetDrawingState(!1),r&&this.emit("draw:complete",{mode:"modify",layerId:s,feature:r}),r||null}if(!this.currentMode||this.activeCoordinates.length===0)return null;let e=null;const n=[...this.activeCoordinates];if(this.currentMode==="line"&&n.length<2||(this.currentMode==="polygon"||this.currentMode==="select-polygon")&&n.length<3||(this.currentMode==="circle"||this.currentMode==="rectangle"||this.currentMode==="select-box")&&n.length<2)return null;if(this.currentMode==="point")e=Lt(n[0],{name:`Point ${new Date().toLocaleTimeString()}`,createdAt:new Date().toISOString()});else if(this.currentMode==="line"){const r=ku(n,this.activeBulges,this.sagToleranceMeters),s=r?Pu(r):n;e=ae(s,Df({name:`Line ${new Date().toLocaleTimeString()}`,lengthMeters:this.curveLengthMeters(r,s),createdAt:new Date().toISOString()},r))}else if(this.currentMode==="polygon"){const r=[...n],s=r[0],o=r[r.length-1];(s[0]!==o[0]||s[1]!==o[1])&&r.push(s);const a=ku(r,[...this.activeBulges,0],this.sagToleranceMeters),l=a?Pu(a):r;e=Pe([l],Df({name:`Polygon ${new Date().toLocaleTimeString()}`,areaM2:Xu(Pe([l])),createdAt:new Date().toISOString()},a))}else if(this.currentMode==="circle"){const r=n[0],s=sn(Lt(r),Lt(n[1]),{units:"meters"});e=G_(r,s,{units:"meters",steps:64,properties:{name:`Circle ${new Date().toLocaleTimeString()}`,shape:"circle",radiusMeters:s,createdAt:new Date().toISOString()}})}else if(this.currentMode==="rectangle"){const r=n[0],s=n[1],o=Math.min(r[0],s[0]),a=Math.max(r[0],s[0]),l=Math.min(r[1],s[1]),h=Math.max(r[1],s[1]);e=Pe([[[o,l],[a,l],[a,h],[o,h],[o,l]]],{name:`Rectangle ${new Date().toLocaleTimeString()}`,shape:"rectangle",createdAt:new Date().toISOString()})}else if(this.currentMode==="select-box"){const r=n[0],s=n[1],o=Math.min(r[0],s[0]),a=Math.max(r[0],s[0]),l=Math.min(r[1],s[1]),h=Math.max(r[1],s[1]),f=Pe([[[o,l],[a,l],[a,h],[o,h],[o,l]]]);return this.executeDrawSelection("select-box",f,!1),this.resetDrawingState(!0),null}else if(this.currentMode==="select-polygon"){const r=[...n],s=r[0],o=r[r.length-1];(s[0]!==o[0]||s[1]!==o[1])&&r.push(s);const a=Pe([r]);return this.executeDrawSelection("select-polygon",a,!1),this.resetDrawingState(!0),null}if(e){const r=this.currentMode,s=this.resolveTargetLayerId(r,this.targetLayerId||void 0),o=this.dataSource.addFeature(s,e);return this.resetDrawingState(!0),this.emit("draw:complete",{mode:r,feature:o,layerId:s}),o}return this.resetDrawingState(!0),null}resetDrawingState(e=!0){var n;if(this.isDrawing=!1,this.clearTrackingPoints(),this.lastConstraint=null,this.activeCoordinates=[],this.activeBulges=[],this.arcSegment=!1,this.arcSweepRadians=null,this.clearTempFeatures(),this.selectionOverlay.setHoverFeature(null),this.selectionOverlay.syncSelectionOverlay(),e&&this.currentMode!==null){this.currentMode=null,this.targetLayerId=null;try{(n=this.mapAdapter)!=null&&n.isReady&&(typeof this.mapAdapter.setDoubleClickZoom=="function"&&this.mapAdapter.setDoubleClickZoom(!0),this.applyCursor())}catch(r){Ht("OFSDrawTools.resetDrawingState",r)}this.emit("draw:mode-change",{mode:null})}}cancel(){this.pointPick=null;const e=this.grips.getIsEditing()||this.currentMode==="modify";if(e){this.stopEdit(),this.resetDrawingState(!1),this.emit("draw:cancel",{mode:"modify"});return}const n=this.currentMode,r=this.isDrawing;this.resetDrawingState(!0),(e||n||r)&&this.emit("draw:cancel",{mode:n||"modify"})}drawPointByCoords(e,n,r={}){const s=Lt(e,r),o=n||this.dataSource.getActiveLayerId()||"points";return this.dataSource.hasLayer(o)||this.dataSource.addLayer({id:o,name:"Points",type:"point"}),this.dataSource.addFeature(o,s)}drawLineByCoords(e,n,r={}){const s=ae(e,r),o=n||this.dataSource.getActiveLayerId()||"lines";return this.dataSource.hasLayer(o)||this.dataSource.addLayer({id:o,name:"Lines",type:"line"}),this.dataSource.addFeature(o,s)}drawPolygonByCoords(e,n,r={}){const s=[...e],o=s[0],a=s[s.length-1];(o[0]!==a[0]||o[1]!==a[1])&&s.push(o);const l=Pe([s],r),h=n||this.dataSource.getActiveLayerId()||"polygons";return this.dataSource.hasLayer(h)||this.dataSource.addLayer({id:h,name:"Polygons",type:"polygon"}),this.dataSource.addFeature(h,l)}splitPolygon(e,n,r){const s=this.dataSource.getFeature(e,n);if(!s)return null;let o=null;if(r!==void 0){if(o=this.dataSource.getFeature(e,r),!o)for(const l of this.dataSource.getAllLayers()){const h=l.getFeature(r);if(h&&(h.geometry.type==="LineString"||h.geometry.type==="MultiLineString")){o=h;break}}}else{const l=je(s);for(const h of this.dataSource.getAllLayers())if(o=h.queryBBox(l).find(f=>f.id!==n&&f.geometry.type==="LineString"&&Yo(s,f))||null,o)break}if(!o)return null;const a=ce.splitPolygonByLine(s,o);return a&&a.length>1?(this.dataSource.runTransaction(`Split polygon ${n} into ${a.length} parts`,()=>{this.dataSource.removeFeature(e,n),a.forEach((l,h)=>{l.id=this.dataSource.getAvailableFeatureId(e,`${n}_part_${h+1}`),l.properties={...s.properties||{},_split:h+1},this.dataSource.addFeature(e,l)})}),a):null}splitOverlappingPolygons(e,n,r){return this.dataSource.splitOverlapping(e,n,r)}splitLine(e,n,r){const s=this.dataSource.getFeature(e,n);if(!s||s.geometry.type!=="LineString")return null;let o=r;if(typeof r=="string"||typeof r=="number"){let l=this.dataSource.getFeature(e,r)||null;if(!l)for(const h of this.dataSource.getAllLayers()){const f=h.getFeature(r);if(f){l=f;break}}if(!l)return null;o=l}const a=ce.splitLine(s,o);return a&&a.length>1?(this.dataSource.runTransaction(`Split line ${n} into ${a.length} segments`,()=>{this.dataSource.removeFeature(e,n),a.forEach((l,h)=>{l.id=this.dataSource.getAvailableFeatureId(e,`${n}_seg_${h+1}`),l.properties={...s.properties||{},_split:h+1},this.dataSource.addFeature(e,l)})}),a):null}joinLines(e,n,r,s=15){var h;const o=this.dataSource.getFeature(e,n);let a=this.dataSource.getFeature(e,r);if(!a)for(const f of this.dataSource.getAllLayers()){const d=f.getFeature(r);if(d&&d.geometry.type==="LineString"){a=d;break}}if(!o||!a||o.geometry.type!=="LineString"||a.geometry.type!=="LineString")return null;const l=ce.connectLines([o,a],s,!0);return l?(l.id=n,this.dataSource.runTransaction(`Join lines ${n} and ${r}`,()=>{this.dataSource.updateFeature(e,l),this.dataSource.removeFeature(e,r)}),this.grips.getIsEditing()&&((h=this.grips.getActiveFeature())==null?void 0:h.id)===n&&this.grips.editFeature(e,n),l):null}offsetFeature(e,n,r,s=!1){var l;const o=this.dataSource.getFeature(e,n);if(!o)return null;const a=ce.offset(o,r);if(a)if(s){const h=this.dataSource.getAvailableFeatureId(e);return a.id=h,a.properties&&(a.properties={...a.properties,name:`${a.properties.name||"Feature"} (Offset ${r>0?"+":""}${r}m)`}),this.dataSource.addFeature(e,a)}else return a.id=n,this.dataSource.updateFeature(e,a),this.grips.getIsEditing()&&((l=this.grips.getActiveFeature())==null?void 0:l.id)===n&&this.grips.editFeature(e,n),a;return null}rotateFeature(e,n,r,s){const o=this.dataSource.getFeature(e,n);if(!o)return null;const a=ce.rotate(o,r,s);return a.id=n,this.dataSource.updateFeature(e,a),a}scaleFeature(e,n,r,s){const o=this.dataSource.getFeature(e,n);if(!o)return null;const a=ce.scale(o,r,s);return a.id=n,this.dataSource.updateFeature(e,a),a}explodeFeature(e,n){const r=this.dataSource.getFeature(e,n);if(!r||r.geometry.type!=="Polygon"&&r.geometry.type!=="MultiPolygon")return null;const s=ce.explode(r);return s.length>0?(this.dataSource.runTransaction(`Explode polygon ${n} into ${s.length} lines`,()=>{this.dataSource.removeFeature(e,n),s.forEach(o=>this.dataSource.addFeature(e,o))}),s):null}filletFeature(e,n,r,s=5){const o=this.dataSource.getFeature(e,n);if(!o)return null;const a=ce.fillet(o,r,s);return a?(a.id=n,this.dataSource.updateFeature(e,a),a):null}curveFeatureSegment(e,n,r,s){const o=this.dataSource.getFeature(e,n);if(!o)return null;const a=g0(o,r,s);return a?(a.id=n,this.dataSource.updateFeature(e,a),a):null}getFeatureCurveSegments(e,n){const r=Od(this.dataSource.getFeature(e,n));if(!r)return[];const s=ei(r.vertices);return Bf(r.vertices,r.bulges,r.sagToleranceMeters,s).map(o=>({index:o.segmentIndex,curved:o.curved,coordinate:o.coordinate,sagMeters:o.curved?s.distance(r.vertices[o.segmentIndex],r.vertices[o.segmentIndex+1])*Math.abs(r.bulges[o.segmentIndex])/2:0}))}startEdit(e,n){return this.dataSource.getFeature(e,n)?(this.dataSource.selectFeature(e,n),this.grips.editFeature(e,n),this.currentMode!=="modify"&&(this.currentMode="modify",this.emit("draw:mode-change",{mode:"modify"})),!0):!1}stopEdit(){this.grips.clear(),this.currentMode==="modify"&&(this.currentMode="select",this.emit("draw:mode-change",{mode:"select"}))}isEditing(){return this.grips.getIsEditing()}getActiveEditingFeature(){return this.grips.getActiveFeature()}getActiveEditingLayerId(){return this.grips.getActiveLayerId()}getActiveEditingFeatureId(){return this.grips.getActiveFeatureId()}updateGeometry(e,n,r){var l;const s=this.dataSource.getFeature(e,n);if(!s)return!1;const o={...s,geometry:r},a=this.dataSource.updateFeature(e,o);return a&&this.grips.getIsEditing()&&((l=this.grips.getActiveFeature())==null?void 0:l.id)===n&&this.grips.editFeature(e,n),a}moveFeature(e,n,r,s){var l;const o=this.dataSource.getFeature(e,n);if(!o)return null;const a=ce.translate(o,r,s);return a.id=n,this.dataSource.updateFeature(e,a),this.grips.getIsEditing()&&((l=this.grips.getActiveFeature())==null?void 0:l.id)===n&&this.grips.editFeature(e,n),a}moveFeatureByOffset(e,n,r,s){var l;const o=this.dataSource.getFeature(e,n);if(!o)return null;const a=ce.translateByOffset(o,r,s);return a.id=n,this.dataSource.updateFeature(e,a),this.grips.getIsEditing()&&((l=this.grips.getActiveFeature())==null?void 0:l.id)===n&&this.grips.editFeature(e,n),a}copyFeature(e,n,r,s){const o=this.dataSource.getFeature(e,n);if(!o)return null;const a=ce.translateByOffset(o,r,s),l=this.dataSource.getAvailableFeatureId(e,`${n}_copy`);return a.id=l,a.properties&&(a.properties={...a.properties,name:`${a.properties.name||"Feature"} (Copy)`}),this.dataSource.addFeature(e,a)}copyFeatureByDistance(e,n,r,s){var l;const o=this.dataSource.getFeature(e,n);if(!o)return null;const a=ce.translate(o,r,s);return a.id=this.dataSource.getAvailableFeatureId(e,`${n}_copy`),a.properties={...a.properties||{},name:`${((l=a.properties)==null?void 0:l.name)||"Feature"} (Copy)`},this.dataSource.addFeature(e,a)}transformFeatures(e,n,r,s=!1){const o=[];this.dataSource.runTransaction(n,()=>{for(const{layerId:h,featureId:f}of e){const d=this.dataSource.getFeature(h,f);if(!d)continue;const p=r(d);s?(p.id=this.dataSource.getAvailableFeatureId(h,`${f}_copy`),o.push(this.dataSource.addFeature(h,p))):(p.id=d.id,this.dataSource.updateFeature(h,p),o.push(this.dataSource.getFeature(h,d.id)))}});const a=this.grips.getIsEditing()?this.grips.getActiveFeature():null,l=this.grips.getActiveLayerId();return!s&&a&&l&&e.some(h=>h.layerId===l&&h.featureId===a.id)&&this.grips.editFeature(l,a.id),o}findLineAt(e,n=12){return this.findFeatureAt(e,{tolerancePixels:n,types:["LineString"]})}findFeatureAt(e,n={}){var d;const r=n.tolerancePixels??12,s=n.types??["LineString","Polygon"],o=xe(this.mapAdapter),a=o&&typeof o.project=="function";let l=2/111320/Math.max(.1,Math.cos(e[1]*Math.PI/180));if(a&&typeof o.unproject=="function"){const p=o.project(e),y=o.unproject([p.x+r,p.y+r]),_=Array.isArray(y)?y[0]:y.lng,E=Array.isArray(y)?y[1]:y.lat;l=Math.max(Math.abs(_-e[0]),Math.abs(E-e[1]))}const h=p=>{let y=null;for(const _ of p){if(_.length<2)continue;const E=js(_,e);let w;if(a){const L=o.project(e),b=o.project(E.coordinate);if(w=Math.hypot(L.x-b.x,L.y-b.y),w>r)continue}else if(w=Co(e,E.coordinate),w>2)continue;(y===null||w<y)&&(y=w)}return y};let f=null;for(const p of this.dataSource.getAllLayers().filter(y=>y.visible))for(const y of p.queryNear(e,l)){const _=(d=y.geometry)==null?void 0:d.type;let E=null;_==="LineString"&&s.includes("LineString")?E=h([y.geometry.coordinates]):_==="Polygon"&&s.includes("Polygon")&&(E=h(y.geometry.coordinates),E===null&&Zt(e,y)&&(E=r+1)),E!==null&&(!f||E<f.distance)&&(f={layerId:p.id,feature:y,distance:E})}return f}breakLineAt(e,n){const r=this.findLineAt(e);if(!r)return null;const{layerId:s,feature:o}=r,a=F8(o.geometry.coordinates,e,n);return this.replaceLineWithPieces(s,o,a,`Break line ${o.id}`)}lengthenLineAt(e,n,r){const s=this.findLineAt(e);if(!s)return null;const o=s.feature.geometry.coordinates,a=Eb(o),l=n==="delta"?r:n==="total"?r-a:a*r/100-a;if(n!=="delta"&&r<=0)throw new Error("Length must be greater than 0.");const h=$8(o,e,l);if(!h)throw new Error(`Cannot shorten by ${Math.abs(l).toFixed(3)} m: the line is only ${a.toFixed(3)} m long.`);return this.dataSource.updateFeature(s.layerId,{...s.feature,geometry:{type:"LineString",coordinates:h}}),this.dataSource.getFeature(s.layerId,s.feature.id)}offsetAt(e,n,r){const s=this.findFeatureAt(e);if(!s)throw new Error("No line or polygon under the pick point.");const{layerId:o,feature:a}=s,l=a.geometry;let h;if(l.type==="LineString"){const p=l.coordinates,y=js(p,n),_={convention:"cad",ucsRotationDeg:0},E=Qe(p[y.segmentIndex],p[y.segmentIndex+1],_).angle,w=Qe(y.coordinate,n,_),L=r==="through"?w.distance:Math.abs(r),b=((w.angle-E)%360+360)%360;h=b>0&&b<180?-L:L}else{const p=l.coordinates,y=Math.min(...p.map(E=>Qe(js(E,n).coordinate,n).distance)),_=r==="through"?y:Math.abs(r);h=Zt(n,a)?-_:_}if(!(Math.abs(h)>0))throw new Error("Offset distance must be greater than 0.");const f=ce.offset(a,h);if(!f)throw new Error(`Offset of ${Math.abs(h).toFixed(3)} m collapses the shape.`);f.id=this.dataSource.getAvailableFeatureId(o,`${a.id}_offset`),f.properties={...a.properties||{}};const d=this.dataSource.addFeature(o,f);return{layerId:o,source:a,result:d}}replaceLineWithPieces(e,n,r,s){const o=[];return this.dataSource.runTransaction(s,()=>{if(r.length===0){this.dataSource.removeFeature(e,n.id);return}this.dataSource.updateFeature(e,{...n,geometry:{type:"LineString",coordinates:r[0]}}),o.push(this.dataSource.getFeature(e,n.id)),r.slice(1).forEach(a=>{o.push(this.dataSource.addFeature(e,{type:"Feature",id:this.dataSource.getAvailableFeatureId(e,`${n.id}_seg`),properties:{...n.properties||{}},geometry:{type:"LineString",coordinates:a}}))})}),{layerId:e,featureId:n.id,pieces:o}}boundarySegments(e,n){const r=[];for(const s of this.dataSource.getAllLayers().filter(o=>o.visible)){const o=n?s.queryBBox(n):s.getFeatures();for(const a of o)e&&s.id===e.layerId&&a.id===e.featureId||a.geometry&&r.push(..._b(a.geometry))}return r}trimLineAt(e){const n=this.findLineAt(e);if(!n)return null;const{layerId:r,feature:s}=n,o=s.geometry.coordinates,a=je(s),l=R8(o,this.boundarySegments({layerId:r,featureId:s.id},a),e);return l?this.replaceLineWithPieces(r,s,l,`Trim line ${s.id}`):null}extendLineAt(e){const n=this.findLineAt(e);if(!n)return null;const{layerId:r,feature:s}=n,o=A8(s.geometry.coordinates,this.boundarySegments({layerId:r,featureId:s.id}),e);return o?(this.dataSource.updateFeature(r,{...s,geometry:{type:"LineString",coordinates:o}}),{layerId:r,feature:this.dataSource.getFeature(r,s.id)}):null}filletLinesAt(e,n,r){const s=this.findLineAt(e),o=this.findLineAt(n);if(!s||!o)throw new Error("Pick two lines.");if(s.layerId===o.layerId&&s.feature.id===o.feature.id)throw new Error("Pick two different lines.");const a=O8(s.feature.geometry.coordinates,e,o.feature.geometry.coordinates,n,r);if(!a)throw new Error(r>0?`Cannot fillet with radius ${r} m: the lines are parallel or too short for this radius.`:"Cannot fillet: the picked segments are parallel.");let l=null;return this.dataSource.runTransaction(`Fillet lines ${s.feature.id} and ${o.feature.id}`,()=>{this.dataSource.updateFeature(s.layerId,{...s.feature,geometry:{type:"LineString",coordinates:a.line1}}),this.dataSource.updateFeature(o.layerId,{...o.feature,geometry:{type:"LineString",coordinates:a.line2}}),a.arc&&(l=this.dataSource.addFeature(s.layerId,{type:"Feature",id:this.dataSource.getAvailableFeatureId(s.layerId,`${s.feature.id}_fillet`),properties:{name:`Fillet R${r}m`,shape:"arc",radiusMeters:r},geometry:{type:"LineString",coordinates:a.arc}}))}),{lines:[this.dataSource.getFeature(s.layerId,s.feature.id),this.dataSource.getFeature(o.layerId,o.feature.id)],arc:l}}stretch(e,n,r,s,o){const a=[Math.min(e[0],n[0]),Math.min(e[1],n[1]),Math.max(e[0],n[0]),Math.max(e[1],n[1])],l=o??this.dataSource.getAllLayers().filter(d=>d.visible).flatMap(d=>d.queryBBox(a).map(p=>({layerId:d.id,featureId:p.id}))),h=[];let f=0;return this.dataSource.runTransaction("Stretch",()=>{for(const{layerId:d,featureId:p}of l){const y=this.dataSource.getFeature(d,p);if(!(y!=null&&y.geometry))continue;const{geometry:_,moved:E}=vb(y.geometry,a,r,s);E!==0&&(f+=E,this.dataSource.updateFeature(d,{...y,geometry:_}),h.push(this.dataSource.getFeature(d,p)))}}),{features:h,movedVertices:f}}deleteFeature(e,n){var r;return this.grips.getIsEditing()&&((r=this.grips.getActiveFeature())==null?void 0:r.id)===n&&this.grips.clear(),this.dataSource.removeFeature(e,n)}updateVertex(e,n,r,s,o=0){const a=this.dataSource.getFeature(e,n);if(!a)return!1;if(a.geometry.type==="Point"){const l=Lt(s,a.properties);return l.id=n,this.dataSource.updateFeature(e,l)}else if(a.geometry.type==="LineString"){const l=[...a.geometry.coordinates];if(r<0||r>=l.length)return!1;l[r]=s;const h=ae(l,a.properties);return h.id=n,this.dataSource.updateFeature(e,h)}else if(a.geometry.type==="Polygon"){const l=a.geometry.coordinates.map(d=>[...d]);if(o<0||o>=l.length)return!1;const h=l[o];if(r<0||r>=h.length)return!1;h[r]=s,r===0&&(h[h.length-1]=s);const f=Pe(l,a.properties);return f.id=n,this.dataSource.updateFeature(e,f)}return!1}insertVertex(e,n,r,s,o=0){const a=this.dataSource.getFeature(e,n);if(!a)return!1;if(a.geometry.type==="LineString"){const l=[...a.geometry.coordinates],h=s!==void 0?Math.min(Math.max(0,s),l.length):l.length;l.splice(h,0,r);const f=ae(l,a.properties);return f.id=n,this.dataSource.updateFeature(e,f)}else if(a.geometry.type==="Polygon"){const l=a.geometry.coordinates.map(p=>[...p]);if(o<0||o>=l.length)return!1;const h=l[o],f=s!==void 0?Math.min(Math.max(0,s),h.length-1):h.length-1;h.splice(f,0,r);const d=Pe(l,a.properties);return d.id=n,this.dataSource.updateFeature(e,d)}return!1}deleteVertex(e,n,r,s=0){var a;if(this.grips.getIsEditing()&&((a=this.grips.getActiveFeature())==null?void 0:a.id)===n)return this.grips.deleteVertex(r,s);const o=this.dataSource.getFeature(e,n);if(!o)return!1;if(o.geometry.type==="LineString"){const l=[...o.geometry.coordinates];if(l.length<=2||r<0||r>=l.length)return!1;l.splice(r,1);const h=ae(l,o.properties);return h.id=n,this.dataSource.updateFeature(e,h)}else if(o.geometry.type==="Polygon"){const l=o.geometry.coordinates.map(d=>[...d]);if(s<0||s>=l.length)return!1;const h=l[s];if(h.length<=4||r<0||r>=h.length-1)return!1;h.splice(r,1),r===0&&(h[h.length-1]=h[0]);const f=Pe(l,o.properties);return f.id=n,this.dataSource.updateFeature(e,f)}return!1}simplifyFeature(e,n,r=1e-4){var a;const s=this.dataSource.getFeature(e,n);if(!s)return null;const o=ce.simplify(s,r);return o.id=n,this.dataSource.updateFeature(e,o),this.grips.getIsEditing()&&((a=this.grips.getActiveFeature())==null?void 0:a.id)===n&&this.grips.editFeature(e,n),o}smoothFeature(e,n,r=32){var a;const s=this.dataSource.getFeature(e,n);if(!s||s.geometry.type!=="LineString")return null;const o=ce.smoothLineBezier(s,r);return o.id=n,this.dataSource.updateFeature(e,o),this.grips.getIsEditing()&&((a=this.grips.getActiveFeature())==null?void 0:a.id)===n&&this.grips.editFeature(e,n),o}reverseLine(e,n){var o;const r=this.dataSource.getFeature(e,n);if(!r||r.geometry.type!=="LineString")return null;const s=ce.reverse(r);return s.id=n,this.dataSource.updateFeature(e,s),this.grips.getIsEditing()&&((o=this.grips.getActiveFeature())==null?void 0:o.id)===n&&this.grips.editFeature(e,n),s}differenceFeature(e,n,r){const s=this.dataSource.getFeature(e,n),o=this.dataSource.getFeature(e,r);if(!s||!o)return null;const a=ce.difference(s,o);return a?(a.id=n,this.dataSource.updateFeature(e,a),a):null}intersectFeatures(e,n,r){const s=this.dataSource.getFeature(e,n),o=this.dataSource.getFeature(e,r);if(!s||!o)return null;const a=ce.intersect(s,o);if(a){const l=this.dataSource.getAvailableFeatureId(e,"intersect");return a.id=l,this.dataSource.addFeature(e,a),a}return null}applyCursor(){if(typeof this.mapAdapter.getRawMap=="function")try{const e=this.mapAdapter.getRawMap();if(!e||typeof e.getCanvas!="function"||!e.getCanvas())return;const n=this.pointPick?"crosshair":this.currentMode?Y8[this.currentMode]??"crosshair":"";e.getCanvas().style.cursor=n}catch(e){Ht("OFSDrawTools.applyCursor",e)}}guideFont(){var e,n;return this.guides.font??((n=(e=this.mapAdapter).getStyleFont)==null?void 0:n.call(e))??z8}getGuides(){return{...this.guides}}setGuides(e){if(this.guides={...this.guides,...e},"font"in e){const n=xe(this.mapAdapter);U8.forEach(r=>{var o;const s=`${this.tempSourceId}${r}`;try{(o=n==null?void 0:n.getLayer)!=null&&o.call(n,s)&&n.setLayoutProperty(s,"text-font",this.guideFont())}catch(a){Ht("OFSDrawTools.setGuides",a)}})}return this.lastCursorCoord&&this.updateTempFeatures(this.lastCursorCoord,null),this.getGuides()}crosshairFeatures(e){if(!this.guides.crosshair||typeof this.mapAdapter.getBounds!="function")return[];let n;try{n=this.mapAdapter.getBounds()}catch(f){return Ht("OFSDrawTools.crosshair",f),[]}const[r,s,o,a]=n;if(![r,s,o,a].every(f=>Number.isFinite(f)))return[];const l=(o-r)*.1,h=(a-s)*.1;return[ae([[r-l,e[1]],[o+l,e[1]]],{isGuide:!0}),ae([[e[0],s-h],[e[0],a+h]],{isGuide:!0})]}formatLength(e){return e>=1e3?`${(e/1e3).toFixed(2)} km`:`${e.toFixed(e<10?2:1)} m`}projector(){const e=xe(this.mapAdapter);return e&&typeof e.project=="function"&&typeof e.unproject=="function"?e:null}dimensionFeatures(e,n,r){const s=sn(Lt(e),Lt(n),{units:"meters"});if(s<=0)return[];const o=this.formatLength(s),a=this.projector();if(!a)return[Lt([(e[0]+n[0])/2,(e[1]+n[1])/2],{isLabel:!0,isLive:r,label:o})];try{const l=a.project(e),h=a.project(n),f=h.x-l.x,d=h.y-l.y,p=Math.hypot(f,d);if(p<1)return[];const y=d/p,_=-f/p,E=this.guides.dimensionOffsetPixels,w=(S,P)=>{const N=a.unproject([S.x+y*P,S.y+_*P]);return[N.lng,N.lat]},L=w(l,E),b=w(h,E);return[ae([e,w(l,E+6)],{isDimExt:!0}),ae([n,w(h,E+6)],{isDimExt:!0}),ae([L,b],{isDim:!0,isLive:r,label:o})]}catch(l){return Ht("OFSDrawTools.dimension",l),[Lt([(e[0]+n[0])/2,(e[1]+n[1])/2],{isLabel:!0,isLive:r,label:o})]}}angleFeatures(e,n,r,s){if(!this.guides.angles)return[];const o=this.projector();if(!o)return[];try{const a=o.project(n),l=o.project(e),h=o.project(r);if(Math.hypot(l.x-a.x,l.y-a.y)<4||Math.hypot(h.x-a.x,h.y-a.y)<4)return[];const f=Math.atan2(l.y-a.y,l.x-a.x);let p=Math.atan2(h.y-a.y,h.x-a.x)-f;for(;p>Math.PI;)p-=Math.PI*2;for(;p<=-Math.PI;)p+=Math.PI*2;const y=Math.abs(p*180/Math.PI);if(y<.05)return[];const _=30,E=18,w=[];for(let S=0;S<=E;S++){const P=f+p*S/E,N=o.unproject([a.x+Math.cos(P)*_,a.y+Math.sin(P)*_]);w.push([N.lng,N.lat])}const L=f+p/2,b=o.unproject([a.x+Math.cos(L)*(_+16),a.y+Math.sin(L)*(_+16)]);return[ae(w,{isAngle:!0,isLive:s}),Lt([b.lng,b.lat],{isLabel:!0,isLive:s,label:`${y.toFixed(1)}°`})]}catch(a){return Ht("OFSDrawTools.angleGuide",a),[]}}measurementFeatures(e,n){const r=[];if(e.length<2)return r;const s=n&&e.length>=3?[...e,e[0]]:e,o=s.length-2;if(this.guides.dimensions)for(let a=0;a<s.length-1;a++)!this.guides.segmentLabels&&a!==o||r.push(...this.dimensionFeatures(s[a],s[a+1],a===o));for(let a=1;a<s.length-1;a++){const l=a===s.length-2;!this.guides.segmentLabels&&!l||r.push(...this.angleFeatures(s[a-1],s[a],s[a+1],l))}if(n&&s.length>=4&&this.guides.segmentLabels&&r.push(...this.angleFeatures(s[s.length-2],s[0],s[1],!1)),this.guides.areaLabel&&n&&e.length>=3){const a=Pe([[...e,e[0]]]),l=Xu(a);if(l>0){const h=Uw(a).geometry.coordinates;r.push(Lt(h,{isLabel:!0,isLive:!0,label:`${l.toFixed(1)} m²`}))}}return r}updateTempFeatures(e,n){const r=xe(this.mapAdapter);if(!r||typeof r.getSource!="function")return;const s=r.getSource(this.tempSourceId);if(!s||typeof s.setData!="function")return;const o=[];if(n&&n.coordinate&&o.push(Lt(n.coordinate,{isSnap:!0,snapType:n.type})),this.isDrawing&&this.activeCoordinates.length>0){const a=[...this.activeCoordinates,e];if(this.activeCoordinates.forEach(h=>{o.push(Lt(h,{isSnap:!1}))}),n||o.push(Lt(e,{isSnap:!1})),this.currentMode==="line"&&a.length>=2)o.push(ae(this.previewCoordinates(e)));else if((this.currentMode==="polygon"||this.currentMode==="select-polygon")&&a.length>=2){const h=this.previewCoordinates(e);o.push(ae(h)),a.length>=3&&o.push(Pe([[...h,h[0]]]))}else if(this.currentMode==="circle"&&a.length>=2){const h=sn(Lt(a[0]),Lt(e),{units:"meters"});o.push(G_(a[0],h,{units:"meters"}))}else if((this.currentMode==="rectangle"||this.currentMode==="select-box")&&a.length>=2){const h=a[0],f=e,d=Math.min(h[0],f[0]),p=Math.max(h[0],f[0]),y=Math.min(h[1],f[1]),_=Math.max(h[1],f[1]);o.push(Pe([[[d,y],[p,y],[p,_],[d,_],[d,y]]]))}o.push(...this.trackingFeatures(e));const l=this.currentMode==="polygon"||this.currentMode==="select-polygon";if(this.currentMode!=="circle"&&this.currentMode!=="rectangle"&&this.currentMode!=="select-box")o.push(...this.measurementFeatures(a,l));else if(this.currentMode==="circle"){const h=sn(Lt(a[0]),Lt(e),{units:"meters"});this.guides.dimensions&&h>0&&o.push(Lt([(a[0][0]+e[0])/2,(a[0][1]+e[1])/2],{isLabel:!0,isLive:!0,label:`r ${this.formatLength(h)}`}))}else{const h=[a[0],[e[0],a[0][1]],e,[a[0][0],e[1]]];o.push(...this.measurementFeatures(h,!0))}o.push(...this.crosshairFeatures(this.guides.anchor==="vertex"?this.activeCoordinates[this.activeCoordinates.length-1]:e))}else this.currentMode==="point"&&o.push(Lt(e,{isSnap:!1})),o.push(...this.trackingFeatures(e)),o.push(...this.crosshairFeatures(e));s.setData({type:"FeatureCollection",features:o})}updateDragBoxPreview(e,n){const r=xe(this.mapAdapter);if(!r||typeof r.getSource!="function")return;const s=r.getSource(this.tempSourceId);if(!s||typeof s.setData!="function")return;const o=Math.min(e[0],n[0]),a=Math.max(e[0],n[0]),l=Math.min(e[1],n[1]),h=Math.max(e[1],n[1]),f=Pe([[[o,l],[a,l],[a,h],[o,h],[o,l]]]);s.setData({type:"FeatureCollection",features:[f]})}queryFeaturesInGeometry(e){const n=[],r=this.dataSource.getAllLayers().filter(s=>s.visible);for(const s of r)if(!(this.targetLayerId&&s.id!==this.targetLayerId))for(const o of jo.queryGeometry(s,e))o.id!==void 0&&n.push({layerId:s.id,feature:o});return n}executeDrawSelection(e,n,r=!1){const s=this.queryFeaturesInGeometry(n);r||this.dataSource.clearSelection();const o=new Map;for(const a of s)if(a.feature.id!==void 0){const l=o.get(a.layerId)||[];l.push(a.feature.id),o.set(a.layerId,l)}for(const[a,l]of o.entries())this.dataSource.selectFeatures(a,l,!0);this.dataSource.getSelectedCount()===1&&s.length===1?this.grips.editFeature(s[0].layerId,s[0].feature.id):this.grips.clear(),this.selectionOverlay.syncSelectionOverlay(),this.emit("selection:draw-complete",{mode:e,selectionPolygon:n,selectedFeatures:s.map(a=>a.feature),count:s.length})}flashFeatures(e,n=750){this.selectionOverlay.flashFeatures(e,n)}clearTempFeatures(){if(this.mapAdapter.isReady)try{const e=xe(this.mapAdapter);if(!e||typeof e.getSource!="function")return;const n=e.getSource(this.tempSourceId);n&&typeof n.setData=="function"&&n.setData({type:"FeatureCollection",features:[]})}catch(e){Ht("OFSDrawTools.clearTempFeatures",e)}}destroy(){this.unsubClick&&this.unsubClick(),this.unsubDblClick&&this.unsubDblClick(),this.unsubContextMenu&&this.unsubContextMenu(),this.unsubMove&&this.unsubMove(),this.unsubMouseDown&&this.unsubMouseDown(),this.unsubMouseUp&&this.unsubMouseUp(),typeof window<"u"&&window.removeEventListener("keydown",this.handleKeyDown),this.cancel(),this.grips.clear(),this.preview.destroy(),this.selectionOverlay.destroy(),this.removeAllListeners()}}const Bm={viridis:["#440154","#3b528b","#21918c","#5ec962","#fde725"],magma:["#000004","#51127c","#b73779","#fb8861","#fcfdbf"],blues:["#eff3ff","#bdd7e7","#6baed6","#3182bd","#08519c"],greens:["#edf8e9","#bae4b3","#74c476","#31a354","#006d2c"],oranges:["#feedde","#fdbe85","#fd8d3c","#e6550d","#a63603"],purples:["#f2f0f7","#cbc9e2","#9e9ac8","#756bb1","#54278f"],ylgnbu:["#ffffd9","#c7e9b4","#41b6c4","#225ea8","#081d58"],ylorrd:["#ffffb2","#fecc5c","#fd8d3c","#f03b20","#bd0026"],spectral:["#d7191c","#fdae61","#ffffbf","#abdda4","#2b83ba"],rdylgn:["#d73027","#fc8d59","#fee08b","#d9ef8b","#91cf60","#1a9850"],rdbu:["#ca0020","#f4a582","#f7f7f7","#92c5de","#0571b0"],category10:["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],set1:["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628","#f781bf"],set2:["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f","#e5c494","#b3b3b3"],pastel:["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd","#fddaec"]},j8={viridis:"sequential",magma:"sequential",blues:"sequential",greens:"sequential",oranges:"sequential",purples:"sequential",ylgnbu:"sequential",ylorrd:"sequential",spectral:"diverging",rdylgn:"diverging",rdbu:"diverging",category10:"qualitative",set1:"qualitative",set2:"qualitative",pastel:"qualitative"},X8=i=>i.split(" ").map(t=>`#${t.toLowerCase()}`),V8={Blues:"f7fbff deebf7 c6dbef 9ecae1 6baed6 4292c6 2171b5 08519c 08306b",BuGn:"f7fcfd e5f5f9 ccece6 99d8c9 66c2a4 41ae76 238b45 006d2c 00441b",BuPu:"f7fcfd e0ecf4 bfd3e6 9ebcda 8c96c6 8c6bb1 88419d 810f7c 4d004b",GnBu:"f7fcf0 e0f3db ccebc5 a8ddb5 7bccc4 4eb3d3 2b8cbe 0868ac 084081",Greens:"f7fcf5 e5f5e0 c7e9c0 a1d99b 74c476 41ab5d 238b45 006d2c 00441b",Greys:"ffffff f0f0f0 d9d9d9 bdbdbd 969696 737373 525252 252525 000000",Oranges:"fff5eb fee6ce fdd0a2 fdae6b fd8d3c f16913 d94801 a63603 7f2704",OrRd:"fff7ec fee8c8 fdd49e fdbb84 fc8d59 ef6548 d7301f b30000 7f0000",PuBu:"fff7fb ece7f2 d0d1e6 a6bddb 74a9cf 3690c0 0570b0 045a8d 023858",PuBuGn:"fff7fb ece2f0 d0d1e6 a6bddb 67a9cf 3690c0 02818a 016c59 014636",PuRd:"f7f4f9 e7e1ef d4b9da c994c7 df65b0 e7298a ce1256 980043 67001f",Purples:"fcfbfd efedf5 dadaeb bcbddc 9e9ac8 807dba 6a51a3 54278f 3f007d",RdPu:"fff7f3 fde0dd fcc5c0 fa9fb5 f768a1 dd3497 ae017e 7a0177 49006a",Reds:"fff5f0 fee0d2 fcbba1 fc9272 fb6a4a ef3b2c cb181d a50f15 67000d",YlGn:"ffffe5 f7fcb9 d9f0a3 addd8e 78c679 41ab5d 238443 006837 004529",YlGnBu:"ffffd9 edf8b1 c7e9b4 7fcdbb 41b6c4 1d91c0 225ea8 253494 081d58",YlOrBr:"ffffe5 fff7bc fee391 fec44f fe9929 ec7014 cc4c02 993404 662506",YlOrRd:"ffffcc ffeda0 fed976 feb24c fd8d3c fc4e2a e31a1c bd0026 800026"},W8={BrBG:"543005 8c510a bf812d dfc27d f6e8c3 f5f5f5 c7eae5 80cdc1 35978f 01665e 003c30",PiYG:"8e0152 c51b7d de77ae f1b6da fde0ef f7f7f7 e6f5d0 b8e186 7fbc41 4d9221 276419",PRGn:"40004b 762a83 9970ab c2a5cf e7d4e8 f7f7f7 d9f0d3 a6dba0 5aae61 1b7837 00441b",PuOr:"7f3b08 b35806 e08214 fdb863 fee0b6 f7f7f7 d8daeb b2abd2 8073ac 542788 2d004b",RdBu:"67001f b2182b d6604d f4a582 fddbc7 f7f7f7 d1e5f0 92c5de 4393c3 2166ac 053061",RdGy:"67001f b2182b d6604d f4a582 fddbc7 ffffff e0e0e0 bababa 878787 4d4d4d 1a1a1a",RdYlBu:"a50026 d73027 f46d43 fdae61 fee090 ffffbf e0f3f8 abd9e9 74add1 4575b4 313695",RdYlGn:"a50026 d73027 f46d43 fdae61 fee08b ffffbf d9ef8b a6d96a 66bd63 1a9850 006837",Spectral:"9e0142 d53e4f f46d43 fdae61 fee08b ffffbf e6f598 abdda4 66c2a5 3288bd 5e4fa2"},H8={Accent:"7fc97f beaed4 fdc086 ffff99 386cb0 f0027f bf5b17 666666",Dark2:"1b9e77 d95f02 7570b3 e7298a 66a61e e6ab02 a6761d 666666",Paired:"a6cee3 1f78b4 b2df8a 33a02c fb9a99 e31a1c fdbf6f ff7f00 cab2d6 6a3d9a ffff99 b15928",Pastel1:"fbb4ae b3cde3 ccebc5 decbe4 fed9a6 ffffcc e5d8bd fddaec f2f2f2",Pastel2:"b3e2cd fdcdac cbd5e8 f4cae4 e6f5c9 fff2ae f1e2cc cccccc",Set3:"8dd3c7 ffffb3 bebada fb8072 80b1d3 fdb462 b3de69 fccde5 d9d9d9 bc80bd ccebc5 ffed6f"},K8={Burg:"ffc6c4 f4a3a8 e38191 cc607d ad466c 8b3058 672044",BurgYl:"fbe6c5 f5ba98 ee8a82 dc7176 c8586c 9c3f5d 70284a",RedOr:"f6d2a9 f5b78e f19c7c ea8171 dd686c ca5268 b13f64",OrYel:"ecda9a efc47e f3ad6a f7945d f97b57 f66356 ee4d5a",Peach:"fde0c5 facba6 f8b58b f59e72 f2855d ef6a4c eb4a40",PinkYl:"fef6b5 ffdd9a ffc285 ffa679 fa8a76 f16d7a e15383",Mint:"e4f1e1 b4d9cc 89c0b6 63a6a0 448c8a 287274 0d585f",BluGrn:"c4e6c3 96d2a4 6dbc90 4da284 36877a 266b6e 1d4f60",DarkMint:"d2fbd4 a5dbc2 7bbcb0 559c9e 3a7c89 235d72 123f5a",Emrld:"d3f2a3 97e196 6cc08b 4c9b82 217a79 105965 074050",ag_GrnYl:"245668 0f7279 0d8f81 39ab7e 6ec574 a9dc67 edef5d",BluYl:"f7feae b7e6a5 7ccba2 46aea0 089099 00718b 045275",Teal:"d1eeea a8dbd9 85c4c9 68abb8 4f90a6 3b738f 2a5674",TealGrn:"b0f2bc 89e8ac 67dba5 4cc8a3 38b2a3 2c98a0 257d98",Purp:"f3e0f7 e4c7f1 d1afe8 b998dd 9f82ce 826dba 63589f",PurpOr:"f9ddda f2b9c4 e597b9 ce78b3 ad5fad 834ba0 573b88",Sunset:"f3e79b fac484 f8a07e eb7f86 ce6693 a059a0 5c53a5",Magenta:"f3cbd3 eaa9bd dd88ac ca699d b14d8e 91357d 6c2167",SunsetDark:"fcde9c faa476 f0746e e34f6f dc3977 b9257a 7c1d6f",ag_Sunset:"4b2991 872ca2 c0369d ea4f88 fa7876 f6a97a edd9a3",BrwnYl:"ede5cf e0c2a2 d39c83 c1766f a65461 813753 541f3f"},Z8={ArmyRose:"798234 a3ad62 d0d3a2 fdfbe4 f0c6c3 df91a3 d46780",Fall:"3d5941 778868 b5b991 f6edbd edbb8a de8a5a ca562c",Geyser:"008080 70a494 b4c8a8 f6edbd edbb8a de8a5a ca562c",Temps:"009392 39b185 9ccb86 e9e29c eeb479 e88471 cf597e",TealRose:"009392 72aaa1 b1c7b3 f1eac8 e5b9ad d98994 d0587e",Tropic:"009b9e 42b7b9 a7d3d4 f1f1f1 e4c1d9 d691c1 c75dab",Earth:"a16928 bd925a d6bd8d edeac2 b5c8b8 79a7ac 2887a1"},J8={Antique:"855c75 d9af6b af6458 736f4c 526a83 625377 68855c 9c9c5e a06177 8c785d 467378 7c7c7c",Bold:"7f3c8d 11a579 3969ac f2b701 e73f74 80ba5a e68310 008695 cf1c90 f97b72 4b4b8f a5aa99",CartoPastel:"66c5cc f6cf71 f89c74 dcb0f2 87c55f 9eb9f3 fe88b1 c9db74 8be0a4 b497e7 d3b484 b3b3b3",Prism:"5f4690 1d6996 38a6a5 0f8554 73af48 edad08 e17c05 cc503e 94346e 6f4070 994e95 666666",Safe:"88ccee cc6677 ddcc77 117733 332288 aa4499 44aa99 999933 882255 661100 6699cc 888888",Vivid:"e58606 5d69b1 52bca3 99c945 cc61b0 24796c daa51b 2f8ac4 764e9f ed645a cc3a8e a5aa99"},Q8={Cividis:"00224e 123570 3b496c 575d6d 707173 8a8678 a59c74 c3b369 e1cc55 fee838",Inferno:"000004 1b0c41 4a0c6b 781c6d a52c60 cf4446 ed6925 fb9b06 f7d13d fcffa4",Plasma:"0d0887 46039f 7201a8 9c179e bd3786 d8576b ed7953 fb9f3a fdca26 f0f921"};function tF(){const i=new Map,t=n=>i.set(n.name.toLowerCase(),n);Object.keys(Bm).forEach(n=>t({name:n,type:j8[n],source:"ofs",colors:[...Bm[n]]}));const e=(n,r,s)=>Object.entries(n).forEach(([o,a])=>{i.has(o.toLowerCase())||t({name:o,type:r,source:s,colors:X8(a)})});return e(V8,"sequential","colorbrewer"),e(W8,"diverging","colorbrewer"),e(H8,"qualitative","colorbrewer"),e(K8,"sequential","carto"),e(Z8,"diverging","carto"),e(J8,"qualitative","carto"),e(Q8,"sequential","matplotlib"),i}const v0=tF();function eF(i){if(i.colors.length===0)throw new Error(`Color ramp "${i.name}" has no colors`);i.colors.forEach(t=>{if(!Vt.valid(t))throw new Error(`Color ramp "${i.name}" has an invalid color: ${t}`)}),v0.set(i.name.toLowerCase(),{...i,colors:[...i.colors]})}function ac(i){return v0.get(i.toLowerCase())}function E0(i){return Array.from(v0.values()).filter(t=>!i||t.type===i)}function nF(i,t){const e=[];for(let n=0;n<i;n++){const r=(t+n)*137.508%360,s=55+(t+n)%3*10;e.push(Vt.lch(s,60,r).hex())}return e}function Ac(i,t,e=!1){if(t<=0)return[];let n,r;if(Array.isArray(i))n=[...i],r="sequential";else{const s=ac(i)??ac("viridis");n=[...s.colors],r=s.type}return e&&n.reverse(),r==="qualitative"?t<=n.length?n.slice(0,t):[...n,...nF(t-n.length,n.length)]:t===1?[n[Math.floor((n.length-1)/2)]]:t===n.length?n:Vt.scale(n).mode("lab").colors(t)}function bb(i,t=!1){return`linear-gradient(90deg, ${Ac(i,9,t).join(", ")})`}const Oc="#3b82f6",Za={kind:"lines",color:Oc,spacing:8,angleDeg:45,lineWidth:1};function Ib(i=Oc){return{fill:{color:i,opacity:.65,style:"solid",outlineColor:"#ffffff",outlineWidth:1.5,outlineOpacity:1},line:{color:i,width:3,opacity:1,cap:"round",join:"round"},marker:{shape:"circle",size:12,color:i,opacity:1,strokeColor:"#ffffff",strokeWidth:1.5,allowOverlap:!0}}}function Da(i){return i===void 0?i:JSON.parse(JSON.stringify(i))}function Sb(i,t){const e=Da(i);return t&&(t.fill&&Object.assign(e.fill,Da(t.fill)),t.line&&Object.assign(e.line,Da(t.line)),t.marker&&Object.assign(e.marker,Da(t.marker))),e}function Qs(i){const t=i.simpleStyle||{},n=t.fillColor??t.circleColor??(i.type==="simple"?i.defaultColor:void 0)??Oc,r=Ib(n);t.circleColor&&(r.marker.color=t.circleColor),t.fillOpacity!==void 0&&(r.fill.opacity=t.fillOpacity),t.strokeColor&&(r.fill.outlineColor=t.strokeColor,r.marker.strokeColor=t.strokeColor),t.strokeWidth!==void 0&&(r.line.width=t.strokeWidth,r.marker.strokeWidth=t.strokeWidth),t.strokeOpacity!==void 0&&(r.line.opacity=t.strokeOpacity),t.circleRadius!==void 0&&(r.marker.size=t.circleRadius*2);const s=Sb(r,i.baseSymbol);return s.fill.style==="pattern"&&!s.fill.pattern&&(s.fill.pattern={...Za,color:s.fill.color}),s}function jh(i,t,e,n){const r=Da(i),s=(n==null?void 0:n.color)??t;s&&(r.fill.color=s,r.line.color=s,r.marker.color=s),r.fill.style==="pattern"&&r.fill.pattern&&(s&&(r.fill.pattern={...r.fill.pattern,color:s}),r.fill.patternBackground&&(r.fill.color=i.fill.color));const o=(n==null?void 0:n.size)??e;return o!==void 0&&(r.line.width=o,r.marker.size=o),n&&(n.opacity!==void 0&&(r.fill.opacity=n.opacity,r.line.opacity=n.opacity,r.marker.opacity=n.opacity),n.strokeColor!==void 0&&(r.fill.outlineColor=n.strokeColor,r.marker.strokeColor=n.strokeColor),n.strokeWidth!==void 0&&(r.fill.outlineWidth=n.strokeWidth,r.marker.strokeWidth=n.strokeWidth),n.pattern===null?(r.fill.style==="pattern"&&(r.fill.style="solid"),delete r.fill.pattern):n.pattern&&(r.fill.style="pattern",r.fill.pattern=Da(n.pattern)),n.shape!==void 0&&(r.marker.shape=n.shape),n.icon!==void 0&&(r.marker.icon=n.icon),n.rotationDeg!==void 0&&(r.marker.rotationDeg=n.rotationDeg)),r}function iF(i,t,e,n){if(i.type!=="graduated"||i.graduatedMode!=="size")return t.map(()=>{});const r=n==="line"?[1,e.line.width*3]:[4,e.marker.size*2],[s,o]=i.sizeRange??r,a=t.length;return t.map((l,h)=>l.size??(a===1?o:s+(o-s)*h/(a-1)))}function w0(i,t){const e=Qs(i),n=[];if(i.type==="graduated"&&i.fieldName&&i.breaks&&i.breaks.length>0){const r=iF(i,i.breaks,e,t),s=i.graduatedMode==="size";i.breaks.forEach((o,a)=>{n.push({index:a,label:o.label,visible:o.visible!==!1,symbol:jh(e,s?void 0:o.color,r[a],o.symbol),min:o.min,max:o.max,count:o.count})})}else if(i.type==="categorical"&&i.fieldName&&i.categories&&i.categories.length>0)i.categories.forEach((r,s)=>{n.push({index:s,label:r.label,visible:r.visible!==!1,symbol:jh(e,r.color,void 0,r.symbol),value:r.value,count:r.count})});else return[{index:0,label:"",visible:!0,symbol:e}];return n.push({index:-1,label:i.otherLabel??"Other values",visible:i.showOther!==!1,symbol:jh(e,i.defaultColor,void 0)}),n}function Mb(i,t){return t==="line"?i.line:t==="polygon"?i.fill:i.marker}const qm=["#2563eb","#65a30d","#ea580c","#f472b6","#115e59","#9d174d","#2dd4bf","#3f6212","#f59e0b","#c026d3","#9a3412"],Nb=["#FFFD3D","#94a3b8","#ffffff","#000000"],x0=20,rF=64;function zm(i={}){const t=i.random??Math.random,e=Ga(i.visible),n=Ga(i.hidden),r=(l,h)=>h.every(f=>Vt.deltaE(l,f)>=x0);for(const l of[[...e,...n],e]){const h=qm.filter(f=>r(f,l));if(h.length>0)return h[Math.floor(t()*h.length)]}const s=[...qm];for(let l=0;l<rF;l++){const h=sF(t);r(h,[...Nb])&&s.push(h)}let o=s[0],a=[-1/0,-1/0];for(const l of s){const h=[Sv(l,e),Sv(l,n)];(h[0]>a[0]||h[0]===a[0]&&h[1]>a[1])&&(o=l,a=h)}return o}function Lb(i,t){if(i.type==="categorical"||i.type==="graduated"){const n=(i.type==="categorical"?i.categories:i.breaks)??[];return Ga(n.filter(r=>r.visible!==!1).map(r=>{var s;return((s=r.symbol)==null?void 0:s.color)??r.color}))}const e=Qs(i);switch(t){case"line":return Ga([e.line.color]);case"point":case"circle":case"symbol":return Ga([e.marker.color]);default:return Ga([e.fill.style==="none"?e.fill.outlineColor:e.fill.color])}}function Ga(i=[]){return i.filter(t=>typeof t=="string"&&Vt.valid(t))}function Sv(i,t){let e=1/0;for(const n of t)e=Math.min(e,Vt.deltaE(i,n));return e}function sF(i){const t=i()*360,e=50+i()*35,n=40+i()*30;return Vt.hcl(t,e,n).hex()}const Xh=3e3;function b0(i,t){if(typeof t!="number"||!Number.isFinite(t))return-1;for(let e=0;e<i.length;e++){const n=i[e];if((e===0?t>=n.min:t>n.min)&&t<=n.max)return e}return-1}function Cb(i,t){for(let e=0;e<i.length;e++)if(i[e].value===t)return e;return-1}function I0(i){const t=i.flatMap(r=>[r.min,r.max]);if(t.every(r=>Number.isInteger(r)))return 0;const e=i.map(r=>r.max-r.min).filter(r=>r>0),n=e.length>0?Math.min(...e):Math.abs(t[0]||1);return Math.max(0,Math.min(6,2-Math.floor(Math.log10(n))))}function S0(i,t,e){return i===t?i.toFixed(e):`${i.toFixed(e)} - ${t.toFixed(e)}`}function Ns(i,t,e,n,r=!1){const s=[];e.forEach(h=>{(s.length===0?h>=t:h>s[s.length-1])&&s.push(h)}),s.length===0&&s.push(t);const o=Ac(n,s.length,r),a=s.map((h,f)=>({min:f===0?t:s[f-1],max:h,color:o[f],label:"",count:0}));i.forEach(h=>{const f=b0(a,h);f>=0&&(a[f].count+=1)});const l=I0(a);return a.forEach(h=>h.label=S0(h.min,h.max,l)),a}function Fc(i){return i.filter(t=>typeof t=="number"&&Number.isFinite(t)).sort((t,e)=>t-e)}function Pb(i,t,e="viridis",n=!1){const r=Fc(i);if(r.length===0||t<=0)return[];const s=r[0],o=r[r.length-1];if(s===o)return Ns(r,s,[o],e,n);const a=(o-s)/t,l=Array.from({length:t},(h,f)=>f===t-1?o:s+(f+1)*a);return Ns(r,s,l,e,n)}function kb(i,t,e="viridis",n=!1){const r=Fc(i);if(r.length===0||t<=0)return[];const s=r.length,o=Array.from({length:t},(a,l)=>l===t-1?r[s-1]:r[Math.max(0,Math.ceil((l+1)*s/t)-1)]);return Ns(r,r[0],o,e,n)}function Tb(i,t,e="viridis",n=!1){const r=Fc(i);if(r.length===0||t<=0)return[];let s=r;if(r.length>Xh){const p=(r.length-1)/(Xh-1);s=Array.from({length:Xh},(y,_)=>r[Math.round(_*p)])}const o=s.length,a=Math.min(t,o);if(a<=1)return Ns(r,r[0],[r[r.length-1]],e,n);const l=Array.from({length:o+1},()=>Array(a+1).fill(0)),h=Array.from({length:o+1},()=>Array(a+1).fill(0));for(let p=1;p<=a;p++){l[1][p]=1;for(let y=2;y<=o;y++)h[y][p]=1/0}for(let p=2;p<=o;p++){let y=0,_=0,E=0,w=0;for(let L=1;L<=p;L++){const b=p-L+1,S=s[b-1];E++,y+=S,_+=S*S,w=_-y*y/E;const P=b-1;if(P!==0)for(let N=2;N<=a;N++)h[p][N]>=w+h[P][N-1]&&(l[p][N]=b,h[p][N]=w+h[P][N-1])}l[p][1]=1,h[p][1]=w}const f=Array(a+1).fill(0);f[a]=o;for(let p=a;p>=2;p--)f[p-1]=l[f[p]][p]-1;const d=Array.from({length:a},(p,y)=>y===a-1?r[r.length-1]:s[f[y+1]-1]);return Ns(r,r[0],d,e,n)}function oF(i){const t=Math.floor(Math.log10(i)),e=i/Math.pow(10,t);return(e<=1?1:e<=2?2:e<=5?5:10)*Math.pow(10,t)}function Rb(i,t,e="viridis",n=!1){const r=Fc(i);if(r.length===0||t<=0)return[];const s=r[0],o=r[r.length-1];if(s===o)return Ns(r,s,[o],e,n);const a=oF((o-s)/t),l=Math.max(0,-Math.floor(Math.log10(a))+1),h=d=>Number(d.toFixed(l)),f=[];for(let d=h((Math.floor(s/a)+1)*a);d<o;d=h(d+a))d>s&&f.push(d);return f.push(o),Ns(r,s,f,e,n)}function Ab(i,t,e="viridis",n,r=!1){const s=Fc(i),o=n??s[0]??t[0];return o===void 0?[]:Ns(s,o,[...t].sort((a,l)=>a-l),e,r)}function Um(i,t,e,n="viridis",r=!1){switch(i){case"equal_interval":return Pb(t,e,n,r);case"natural_breaks":return Tb(t,e,n,r);case"pretty_breaks":return Rb(t,e,n,r);case"manual":case"quantile":default:return kb(t,e,n,r)}}function M0(i,t){const e=s=>typeof s=="number"?0:typeof s=="boolean"?1:2,n=e(i),r=e(t);return n!==r?n-r:typeof i=="number"&&typeof t=="number"?i-t:String(i).localeCompare(String(t),void 0,{numeric:!0})}function Ym(i,t="category10",e=!1){const n=new Map;i.forEach(o=>{o!=null&&(typeof o=="number"&&!Number.isFinite(o)||n.set(o,(n.get(o)||0)+1))});const r=Array.from(n.keys()).sort(M0),s=Ac(t,r.length,e);return r.map((o,a)=>({value:o,color:s[a],label:String(o),count:n.get(o)}))}function Mv(i,t=0){return Array.from({length:i},(e,n)=>{const r=(t+360*n/i-90)*Math.PI/180;return[Math.cos(r),Math.sin(r)]})}function aF(i,t){return Array.from({length:i*2},(e,n)=>{const r=n%2===0?1:t,s=(180*n/i-90)*(Math.PI/180);return[r*Math.cos(s),r*Math.sin(s)]})}function Nv(i){const t=i;return[[-t,-1],[t,-1],[t,-t],[1,-t],[1,t],[t,t],[t,1],[-t,1],[-t,t],[-1,t],[-1,-t],[-t,-t]]}function lF(i,t){const e=t*Math.PI/180,n=Math.cos(e),r=Math.sin(e);return i.map(([s,o])=>[s*n-o*r,s*r+o*n])}const uF={square:[[-.8,-.8],[.8,-.8],[.8,.8],[-.8,.8]],diamond:[[0,-1],[1,0],[0,1],[-1,0]],triangle:[[0,-1],[.95,.72],[-.95,.72]],star:aF(5,.45),pentagon:Mv(5),hexagon:Mv(6,30),cross:Nv(.28),x:lF(Nv(.24),45)},lc=["circle","square","diamond","triangle","star","pentagon","hexagon","cross","x"];function N0(i){return i==="circle"||i==="icon"?null:uF[i]??null}function Ob(i,t,e,n){const r=N0(i);return r?r.map(([s,o],a)=>`${a===0?"M":"L"} ${(t+s*n).toFixed(2)} ${(e+o*n).toFixed(2)}`).join(" ")+" Z":`M ${t-n} ${e} a ${n} ${n} 0 1 0 ${n*2} 0 a ${n} ${n} 0 1 0 ${-n*2} 0 Z`}const L0=new Map,jm=new Set;function cF(i,t,e={}){if(!i.trim())throw new Error("Marker icon name must not be empty");L0.set(i,{source:t,sdf:e.sdf??!0}),jm.forEach(n=>n(i))}function C0(i){return L0.get(i)}function P0(){return Array.from(L0.keys())}function Fb(i){return jm.add(i),()=>jm.delete(i)}function k0(i){return i.trimStart().startsWith("<svg")||i.trimStart().startsWith("<?xml")}const Hg=8,Lv=1024;function hF(i,t){for(i=Math.abs(i),t=Math.abs(t);t;)[i,t]=[t,i%t];return i}function $b(i,t,e){const n=(i%180+180)%180;let r={a:1,b:0,error:Math.min(n,180-n)};for(let s=-Hg;s<=Hg;s++)for(let o=0;o<=Hg;o++){if(s===0&&o===0||hF(s,o)!==1||e*Math.hypot(s,o)>t)continue;const a=(Math.atan2(o,s)*180/Math.PI+180)%180,l=Math.abs(a-n),h=Math.min(l,180-l),f=Math.hypot(s,o)<Math.hypot(r.a,r.b);(h<r.error-1e-9||Math.abs(h-r.error)<=1e-9&&f)&&(r={a:s,b:o,error:h})}return{a:r.a,b:r.b}}function Db(i,t=1){const e=Math.max(1,t),n=Math.max(i.spacing,1),{a:r,b:s}=$b(i.angleDeg,Lv/e/2,n),o=Math.hypot(r,s),a=Math.max(1,Math.round(n*o*e)),l=a/o,h=[r/o,-s/o],f=[s/o,r/o];let d=null,p=1;const y=(i.dash??[]).map(N=>N*e).filter(N=>N>0);if(i.kind!=="dots"&&y.length>0){const N=y.reduce((I,M)=>I+M,0)*(y.length%2===1?2:1),C=y.length%2===1?[...y,...y]:y;let T;N<=l?T=l/Math.max(1,Math.round(l/N)):(p=Math.max(1,Math.round(N/l)),T=l*p),a*p<=Lv?d=C.map(I=>I*T/N):p=1}const _=a*p,E=Math.max(i.lineWidth,.1)*e,w=[],L=[],b=[[-_,-_],[_*2,-_],[-_,_*2],[_*2,_*2]],S=_*4+E,P=(N,C)=>{const T=b.map(([$,U])=>$*C[0]+U*C[1]),I=Math.floor((Math.min(...T)-E)/l)-1,M=Math.ceil((Math.max(...T)+E)/l)+1,R=d?d.reduce(($,U)=>$+U,0):1,A=-Math.ceil(S/R)*R,F=Math.ceil(S/R)*R;for(let $=I;$<=M;$++){const U=$*l*C[0],D=$*l*C[1];w.push([U+A*N[0],D+A*N[1],U+F*N[0],D+F*N[1]])}};if(i.kind==="dots"){const N=E/2,C=Math.ceil(_*3/l)+1;for(let T=-C;T<=C;T++)for(let I=-C;I<=C;I++){const M=T*l*h[0]+I*l*f[0],R=T*l*h[1]+I*l*f[1];M>=-_-N&&M<=_*2+N&&R>=-_-N&&R<=_*2+N&&L.push([M,R])}}else P(h,f),i.kind==="cross"&&P(f,[-h[0],-h[1]]);return{size:_,pixelRatio:e,color:i.color,lineWidth:E,segments:w,dots:L,dash:d,effectiveAngleDeg:(Math.atan2(s,r)*180/Math.PI+180)%180,effectiveSpacing:l/e}}function Gb(i){let t=2166136261;for(let e=0;e<i.length;e++)t^=i.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function Bb(i){const t=JSON.stringify([i.kind,i.color,i.spacing,i.angleDeg,i.lineWidth,i.dash??[]]);return`ofs-hatch-${Gb(t)}`}const Tu=1e20;function Cv(i,t,e,n,r,s,o){s[0]=0,o[0]=-Tu,o[1]=Tu,r[0]=i[t];for(let a=1,l=0,h=0;a<n;a++){r[a]=i[t+a*e];const f=a*a;do{const d=s[l];h=(r[a]-r[d]+f-d*d)/(a-d)/2}while(h<=o[l]&&--l>-1);l++,s[l]=a,o[l]=h,o[l+1]=Tu}for(let a=0,l=0;a<n;a++){for(;o[l+1]<a;)l++;const h=s[l],f=a-h;i[t+a*e]=r[h]+f*f}}function Pv(i,t,e){const n=Math.max(t,e),r=new Float64Array(n),s=new Float64Array(n+1),o=new Uint16Array(n);for(let a=0;a<t;a++)Cv(i,a,t,e,r,o,s);for(let a=0;a<e;a++)Cv(i,a*t,1,t,r,o,s)}function qb(i,t,e,n=8,r=.25){const s=t*e,o=new Float64Array(s),a=new Float64Array(s);for(let h=0;h<s;h++){const f=i[h]/255;if(f>=1)o[h]=0,a[h]=Tu;else if(f<=0)o[h]=Tu,a[h]=0;else{const d=.5-f;o[h]=d>0?d*d:0,a[h]=d<0?d*d:0}}Pv(o,t,e),Pv(a,t,e);const l=new Uint8ClampedArray(s);for(let h=0;h<s;h++){const f=Math.sqrt(o[h])-Math.sqrt(a[h]);l[h]=Math.round(255-255*(f/n+r))}return l}const Uf="_ofs_label",$c=24,uc=8,Wo=2;function zb(i,t){return i==="icon"?`ofs-icon-${t??""}`:`ofs-marker-${i}`}const Xm={polygon:["match",["geometry-type"],["Polygon","MultiPolygon"],!0,!1],line:["match",["geometry-type"],["LineString","MultiLineString"],!0,!1],point:["match",["geometry-type"],["Point","MultiPoint"],!0,!1]},fF={center:[0,0],left:[-1,0],right:[1,0],top:[0,-1],bottom:[0,1],"top-left":[-1,-1],"top-right":[1,-1],"bottom-left":[-1,1],"bottom-right":[1,1]};function dF(i){return Number.isInteger(i)&&Math.abs(i)<=Number.MAX_SAFE_INTEGER}function Ub(i){const t=i.fieldName;if(!t)return null;const e=["get",t];if(i.type==="graduated"&&i.breaks&&i.breaks.length>0){const n=["to-number",e],r=[];return i.breaks.forEach((s,o)=>{r.push(["all",[o===0?">=":">",n,s.min],["<=",n,s.max]],o)}),["case",["!=",["typeof",e],"number"],-1,...r,-1]}if(i.type==="categorical"&&i.categories&&i.categories.length>0){const n=[],r=[],s=[],o=[],a=new Set;i.categories.forEach((h,f)=>{const d=`${typeof h.value}:${String(h.value)}`;h.value===null||h.value===void 0||a.has(d)||(a.add(d),typeof h.value=="string"?n.push(h.value,f):typeof h.value=="boolean"?o.push(["==",["to-boolean",e],h.value],f):typeof h.value=="number"&&dF(h.value)?r.push(h.value,f):typeof h.value=="number"&&Number.isFinite(h.value)&&s.push(["==",["to-number",e],h.value],f))});const l=[];if(n.length>0&&l.push(["==",["typeof",e],"string"],["match",["to-string",e],...n,-1]),r.length>0||s.length>0){const h=[];r.length>0&&h.push(["match",["to-number",e],...r,-1]);const f=s.length>0?["case",...s,r.length>0?h[0]:-1]:h[0];l.push(["==",["typeof",e],"number"],f)}return o.length>0&&l.push(["==",["typeof",e],"boolean"],["case",...o,-1]),l.length===0?null:["case",...l,-1]}return null}function Ve(i,t,e){const n=t.map(e),r=JSON.stringify(n[0]);if(!i||n.every(a=>JSON.stringify(a)===r))return n[0];const s=t.find(a=>a.index===-1),o=[];return t.forEach((a,l)=>{a.index>=0&&o.push(a.index,n[l])}),["match",i,...o,s?e(s):n[0]]}function bo(i,t){return t===1?i:typeof i=="number"?i*t:["*",t,i]}function kv(i,t,e){const n=t.filter(e).map(r=>r.index);return i?n.length===t.length?null:n.length===0?["boolean",!1]:["match",i,n,!0,!1]:n.length>0?null:["boolean",!1]}function Tv(...i){const t=i.filter(e=>e!==null);return t.length===1?t[0]:["all",...t]}function Rv(i,t){const e=(i??[]).filter(n=>Number.isFinite(n)&&n>=0);if(!(e.length<2||e.every(n=>n===0)))return e.map(n=>n/Math.max(t,.01))}class Yb{static compile(t,e,n={}){const r=n.layerId??t.layerId,s=Math.max(0,Math.min(1,n.opacity??1)),o=t.highlightColor||"#FFFD3D",a=t.enableSelectionHighlight??!0,l=["boolean",["feature-state","selected"],!1],h=S=>a?["case",l,o,S]:S,f=w0(t,e),d=f.length>1?Ub(t):null,p=kv(d,f,S=>S.visible),y=e==="line"?"line":e==="polygon"?"polygon":"point",_=Tv(Xm[y],p),E=f.find(S=>S.index===0)??f[0],w=[],L=new Map;if(y==="polygon"){const S=E.symbol.fill,P=S.offset??[0,0],N=A=>{const F=A.symbol.fill;return F.style==="none"||F.style==="pattern"&&!F.patternBackground?0:F.opacity},C=bo(Ve(d,f,N),s),T=bo(Ve(d,f,A=>Math.max(N(A),.35)),s);w.push({id:r,role:"fill",type:"fill",filter:_,paint:{"fill-color":h(Ve(d,f,A=>A.symbol.fill.color)),"fill-opacity":a?["case",l,T,C]:C,"fill-translate":P},layout:{visibility:"visible"}});const I=A=>A.symbol.fill.style==="pattern"&&!!A.symbol.fill.pattern;if(f.some(I)){const A=$=>{if(!I($))return null;const U=Bb($.symbol.fill.pattern);return L.set(U,{id:U,kind:"hatch",pattern:$.symbol.fill.pattern}),U},F=f.map(A).find($=>!!$);w.push({id:`${r}_pattern`,role:"pattern",type:"fill",filter:Tv(Xm.polygon,kv(d,f,$=>$.visible&&I($))),paint:{"fill-pattern":Ve(d,f,$=>A($)??F),"fill-opacity":bo(Ve(d,f,$=>$.symbol.fill.opacity),s),"fill-translate":P},layout:{visibility:"visible"}})}const M={"line-color":Ve(d,f,A=>A.symbol.fill.outlineColor),"line-width":Ve(d,f,A=>A.symbol.fill.outlineWidth),"line-opacity":bo(Ve(d,f,A=>A.symbol.fill.outlineOpacity),s),"line-translate":P},R=Rv(S.outlineDash,S.outlineWidth);R&&(M["line-dasharray"]=R),w.push({id:`${r}_stroke`,role:"stroke",type:"line",filter:_,paint:M,layout:{visibility:"visible","line-join":"round"}})}else if(y==="line"){const S=E.symbol.line,P={"line-color":h(Ve(d,f,C=>C.symbol.line.color)),"line-width":Ve(d,f,C=>C.symbol.line.width),"line-opacity":bo(Ve(d,f,C=>C.symbol.line.opacity),s)},N=Rv(S.dash,S.width);N&&(P["line-dasharray"]=N),S.offset&&(P["line-offset"]=S.offset),w.push({id:r,role:"line",type:"line",filter:_,paint:P,layout:{visibility:"visible","line-cap":S.cap??"round","line-join":S.join??"round"}})}else{const S=E.symbol.marker,P=S.offset??[0,0];if(f.some(C=>C.symbol.marker.shape!=="circle")){const C=R=>{const A=R.symbol.marker,F=zb(A.shape,A.icon);return A.shape==="icon"?L.set(F,{id:F,kind:"icon",icon:A.icon??""}):L.set(F,{id:F,kind:"marker",shape:A.shape}),F},T=S.anchor??"center",I=fF[T],M=S.allowOverlap??!0;w.push({id:r,role:"marker",type:"symbol",filter:_,paint:{"icon-color":h(Ve(d,f,R=>R.symbol.marker.color)),"icon-opacity":bo(Ve(d,f,R=>R.symbol.marker.opacity),s),"icon-halo-color":Ve(d,f,R=>R.symbol.marker.strokeColor),"icon-halo-width":Ve(d,f,R=>R.symbol.marker.strokeWidth),"icon-translate":P},layout:{visibility:"visible","icon-image":Ve(d,f,C),"icon-size":Ve(d,f,R=>R.symbol.marker.size/$c),"icon-rotate":Ve(d,f,R=>R.symbol.marker.rotationDeg??0),"icon-anchor":T,"icon-offset":[I[0]*uc,I[1]*uc],"icon-allow-overlap":M,"icon-ignore-placement":M}})}else{const C=bo(Ve(d,f,T=>T.symbol.marker.opacity),s);w.push({id:r,role:"circle",type:"circle",filter:_,paint:{"circle-color":h(Ve(d,f,T=>T.symbol.marker.color)),"circle-radius":Ve(d,f,T=>T.symbol.marker.size/2),"circle-opacity":C,"circle-stroke-color":Ve(d,f,T=>T.symbol.marker.strokeColor),"circle-stroke-width":Ve(d,f,T=>T.symbol.marker.strokeWidth),"circle-stroke-opacity":C,"circle-translate":P},layout:{visibility:"visible"}})}}const b=Vb(t.label,r,y,s);return b&&w.push(b),{paint:w[0].paint,layout:{visibility:"visible"},layers:w,images:Array.from(L.values())}}}function jb(i){return!!i&&i.enabled!==!1&&!!i.expression}function Xb(i){return!!i&&i.enabled!==!1&&!!(i.field||i.expression)}function Vb(i,t,e,n=1){if(!Xb(i))return null;const r=i,s=r.size??12,o=r.allowOverlap??!1,l={visibility:"visible","text-field":r.expression?["coalesce",["get",Uf],""]:r.decimals!==void 0?["case",["==",["typeof",["get",r.field]],"number"],["number-format",["get",r.field],{"min-fraction-digits":r.decimals,"max-fraction-digits":r.decimals}],["to-string",["coalesce",["get",r.field],""]]]:["to-string",["coalesce",["get",r.field],""]],"text-size":s,"text-anchor":r.anchor??"center","text-max-width":r.maxWidth??10,"text-allow-overlap":o,"text-ignore-placement":o,"symbol-placement":r.placement==="line"&&e!=="point"?"line":"point"};r.font&&(l["text-font"]=r.font),r.offset&&(l["text-offset"]=r.offset),r.rotationDeg&&(l["text-rotate"]=r.rotationDeg),r.transform&&r.transform!=="none"&&(l["text-transform"]=r.transform),r.priorityField&&(l["symbol-sort-key"]=["-",0,["to-number",["coalesce",["get",r.priorityField],0]]]);const h={"text-color":r.color??"#1f2937","text-halo-color":r.haloColor??"#ffffff","text-halo-width":r.haloWidth??1.2,"text-opacity":Math.max(0,Math.min(1,(r.opacity??1)*n))},f={id:`${t}_label`,role:"label",type:"symbol",filter:Xm[e],paint:h,layout:l};return r.minZoom!==void 0&&(f.minzoom=r.minZoom),r.maxZoom!==void 0&&(f.maxzoom=r.maxZoom),f}const Av="#94a3b8";function oi(i){return i===void 0?i:JSON.parse(JSON.stringify(i))}function gF(i,t){const e=oi(i)??{};return["fill","line","marker"].forEach(n=>{t[n]&&(e[n]={...e[n],...oi(t[n])})}),e}function Vh(i,t){var n;const e=[];for(const r of i.getFeatures()){const s=(n=r.properties)==null?void 0:n[t];typeof s=="number"&&Number.isFinite(s)&&e.push(s)}return e}function Wb(i,t){var s,o,a;const e=new Map,n=i.fieldName,r=n&&(i.type==="graduated"&&((s=i.breaks)==null?void 0:s.length)||i.type==="categorical"&&((o=i.categories)==null?void 0:o.length));for(const l of t.getFeatures()){let h=0;if(r){const f=(a=l.properties)==null?void 0:a[n];h=i.type==="graduated"?b0(i.breaks,f):Cb(i.categories,f)}e.set(h,(e.get(h)??0)+1)}return e}class cc extends no{constructor(e={}){super();q(this,"themes",new Map);q(this,"random");q(this,"dataSource",null);q(this,"unbindDataSource",[]);this.random=e.random??Math.random}bindDataSource(e){this.dataSource!==e&&(this.unbindDataSource.forEach(n=>n()),this.dataSource=e,this.unbindDataSource=[e.on("layer:added",({layer:n})=>this.styleNewLayer(n)),e.on("layer:removed",({layerId:n,replaced:r})=>{r||this.removeTheme(n)})])}styleNewLayer(e){if(e.color){this.createSimpleTheme(e.id,{},e.color);return}this.getEffectiveTheme(e.id)}getTheme(e){return this.themes.get(e)}setTheme(e){this.themes.set(e.layerId,e),this.emit("theme:changed",{layerId:e.layerId,theme:e})}removeTheme(e){this.themes.delete(e)}exportThemes(){return Array.from(this.themes.values()).map(e=>oi(e))}importThemes(e){e.forEach(n=>this.setTheme(oi(n)))}carriedLayerSettings(e){const n=this.themes.get(e);if(!n)return{};const r={};return n.label&&(r.label=oi(n.label)),n.highlightColor!==void 0&&(r.highlightColor=n.highlightColor),n.enableSelectionHighlight!==void 0&&(r.enableSelectionHighlight=n.enableSelectionHighlight),r}carriedSymbol(e,n){var r;return oi(n??((r=this.themes.get(e))==null?void 0:r.baseSymbol))}createSimpleTheme(e,n={},r="#3b82f6"){const s=n.fillColor??n.circleColor??r,o=this.carriedSymbol(e);o!=null&&o.fill&&(delete o.fill.color,o.fill.pattern&&(o.fill.pattern.color=s)),o!=null&&o.line&&delete o.line.color,o!=null&&o.marker&&delete o.marker.color;const a={type:"simple",layerId:e,defaultColor:r,simpleStyle:{fillColor:r,strokeColor:"#ffffff",strokeWidth:2,fillOpacity:.65,circleColor:r,circleRadius:6,...n},baseSymbol:o,...this.carriedLayerSettings(e)};return this.setTheme(a),a}createCategoricalTheme(e,n,r="category10",s=Av,o={}){var h;const a=[];for(const f of e.getFeatures()){const d=(h=f.properties)==null?void 0:h[n];d!=null&&a.push(d)}const l={type:"categorical",layerId:e.id,fieldName:n,paletteName:r,defaultColor:s,categories:Ym(a,r,o.reverse),baseSymbol:this.carriedSymbol(e.id,o.baseSymbol),...this.carriedLayerSettings(e.id),...o.keepEmptyCategories?{keepEmptyCategories:!0}:{}};return this.setTheme(l),l}createGraduatedTheme(e,n,r="quantile",s=5,o="viridis",a=Av,l={}){const h=Um(r,Vh(e,n),s,o,l.reverse),f={type:"graduated",layerId:e.id,fieldName:n,classificationMethod:r,classCount:s,paletteName:o,defaultColor:a,breaks:h,graduatedMode:l.mode??"color",sizeRange:l.sizeRange,baseSymbol:this.carriedSymbol(e.id,l.baseSymbol),...this.carriedLayerSettings(e.id)};return this.setTheme(f),f}setManualBreaks(e,n,r){const s=this.requireTheme(e.id);if(s.type!=="graduated"||!s.fieldName)throw new Error(`Layer "${e.id}" does not have a graduated theme`);const o={...oi(s),classificationMethod:"manual",classCount:n.length,breaks:Ab(Vh(e,s.fieldName),n,s.paletteName??"viridis",r)};return this.setTheme(o),o}reclassify(e){var s;const n=this.themes.get(e.id);if(!n||!n.fieldName||n.type==="simple")return n;const r=oi(n);if(n.type==="categorical"){const o=this.createCategoricalThemeData(e,n),a=o.map(d=>{var p;return(p=n.categories)==null?void 0:p.find(y=>y.value===d.value)}),l=n.keepEmptyCategories?(n.categories??[]).filter(d=>!o.some(p=>p.value===d.value)).map(d=>({...d,count:0})):[],h=[...a.flatMap(d=>d?[d.color]:[]),...l.map(d=>d.color)],f=o.map((d,p)=>{const y=a[p];if(y)return{...d,color:y.color,label:y.label,visible:y.visible,symbol:y.symbol};const _=this.unusedClassColor(n.paletteName??"category10",o.length+h.length,h);return h.push(_),{...d,color:_}});r.categories=[...f,...l].sort((d,p)=>M0(d.value,p.value))}else if(n.classificationMethod!=="manual"){const o=Um(n.classificationMethod??"quantile",Vh(e,n.fieldName),n.classCount??((s=n.breaks)==null?void 0:s.length)??5,n.paletteName??"viridis");r.breaks=o.map((a,l)=>{var f;const h=(f=n.breaks)==null?void 0:f[l];return h?{...a,visible:h.visible,symbol:h.symbol,size:h.size}:a})}return this.setTheme(r),r}unusedClassColor(e,n,r){return Ac(e,Math.max(n,1)).find(a=>r.every(l=>!Vt.valid(l)||Vt.deltaE(a,l)>=x0))??zm({visible:r,random:this.random})}createCategoricalThemeData(e,n){var s;const r=[];for(const o of e.getFeatures()){const a=(s=o.properties)==null?void 0:s[n.fieldName];a!=null&&r.push(a)}return Ym(r,n.paletteName??"category10")}updateBaseSymbol(e,n){const r=oi(this.themes.get(e))??this.defaultTheme(e);return r.baseSymbol=gF(r.baseSymbol,n),this.setTheme(r),r}setLabel(e,n){const r=oi(this.themes.get(e))??this.defaultTheme(e);if(!n)delete r.label;else{const s={...r.label??{},...n};if(n.field!==void 0&&n.expression===void 0&&delete s.expression,n.expression!==void 0&&n.field===void 0&&delete s.field,!s.field&&!s.expression)throw new Error("Labels need a field or an expression");r.label=s}return this.setTheme(r),r}getLabel(e){var n;return(n=this.themes.get(e))==null?void 0:n.label}setClassVisible(e,n,r){const s=oi(this.requireTheme(e));if(n===-1)s.showOther=r;else{const o=this.classList(s)[n];if(!o)throw new Error(`Layer "${e}" has no class ${n}`);o.visible=r}this.setTheme(s)}setAllClassesVisible(e,n){const r=oi(this.requireTheme(e));this.classList(r).forEach(s=>s.visible=n),r.showOther=n,this.setTheme(r)}updateClass(e,n,r){const s=oi(this.requireTheme(e)),a=this.classList(s)[n];if(!a)throw new Error(`Layer "${e}" has no class ${n}`);if(r.color!==void 0&&(a.color=r.color),r.visible!==void 0&&(a.visible=r.visible),r.size!==void 0&&(a.size=r.size),r.symbol===null?delete a.symbol:r.symbol&&(a.symbol={...a.symbol,...oi(r.symbol)}),s.type==="graduated"&&(r.min!==void 0||r.max!==void 0)){const l=s.breaks,h=l[n];if(r.max!==void 0){const f=l[n+1];f&&f.min===h.max&&(f.min=r.max),h.max=r.max}if(r.min!==void 0){const f=l[n-1];f&&f.max===h.min&&(f.max=r.min),h.min=r.min}if(s.classificationMethod="manual",r.label===void 0){const f=I0(l);l.forEach(d=>d.label=S0(d.min,d.max,f))}}r.label!==void 0&&(a.label=r.label),this.setTheme(s)}classList(e){return e.type==="graduated"?e.breaks??[]:e.type==="categorical"?e.categories??[]:[]}requireTheme(e){const n=this.themes.get(e);if(!n)throw new Error(`Layer "${e}" has no theme`);return n}defaultTheme(e){const n=this.defaultColorFor(e);return{type:"simple",layerId:e,defaultColor:n,simpleStyle:{fillColor:n,strokeColor:"#ffffff",strokeWidth:2,fillOpacity:.65,circleColor:n,circleRadius:6}}}defaultColorFor(e){const n=this.dataSource,r=n==null?void 0:n.getLayer(e);if(r!=null&&r.color)return r.color;if(!n)return Oc;const s=[],o=[];for(const a of n.getAllLayers()){if(a.id===e)continue;const l=this.themes.get(a.id);if((l==null?void 0:l.type)!=="simple")continue;const h=Lb(l,a.type);(n.isLayerRendered(a.id)?s:o).push(...h)}return zm({visible:s,hidden:o,random:this.random})}getEffectiveTheme(e){let n=this.themes.get(e);return n||(n=this.defaultTheme(e),this.themes.set(e,n)),n}compile(e){return Yb.compile(this.getEffectiveTheme(e.id),e.type,{layerId:e.id,opacity:e.opacity??1})}}class Hb extends no{constructor(e,n){super();q(this,"dataSource");q(this,"thematicEngine");q(this,"unsubscribers",[]);q(this,"groupCounter",0);this.dataSource=e,this.thematicEngine=n||new cc,this.thematicEngine.bindDataSource(e),this.bindDataSourceEvents()}bindDataSourceEvents(){if(["layer:added","layer:removed","layer:updated","features:changed","active-layer:changed","group:added","group:removed","group:updated","tile-layer:added","tile-layer:removed","tile-layer:updated"].forEach(n=>{const r=this.dataSource.on(n,()=>{this.notifyUpdate()});this.unsubscribers.push(r)}),this.thematicEngine){const n=this.thematicEngine.on("theme:changed",()=>{this.notifyUpdate()});this.unsubscribers.push(n)}}getSnapshot(){const e=this.dataSource.getAllLayers().sort((a,l)=>l.zIndex-a.zIndex),n=this.dataSource.getTileLayers().map(a=>({id:a.id,name:a.name,type:a.kind,visible:a.visible,rendered:this.dataSource.isLayerRendered(a.id),opacity:a.opacity,zIndex:a.zIndex,pinned:a.pinned,groupId:a.groupId&&this.dataSource.getLayerGroup(a.groupId)?a.groupId:null,featureCount:0,thematicType:"simple",items:[]})),r=e.map(a=>{const l=this.thematicEngine.getEffectiveTheme(a.id),h=Wb(l,a),f=[];return w0(l,a.type).forEach(d=>{const p=Mb(d.symbol,a.type),y="style"in p&&p.style==="pattern"&&p.pattern?p.pattern.color:p.color;if(l.type==="simple"||d.index>=0){f.push({label:l.type==="simple"?a.name:d.label,color:y,count:l.type==="simple"?a.count:h.get(d.index)??0,min:d.min,max:d.max,value:d.value,index:d.index,visible:d.visible,symbol:d.symbol});return}const _=h.get(-1)??0;(l.type==="categorical"||_>0)&&f.push({label:d.label,color:y,count:_,index:-1,visible:d.visible,symbol:d.symbol})}),{id:a.id,name:a.name,type:a.type,visible:a.visible,rendered:this.dataSource.isLayerRendered(a.id),opacity:a.opacity,zIndex:a.zIndex,pinned:a.pinned,groupId:a.groupId&&this.dataSource.getLayerGroup(a.groupId)?a.groupId:null,featureCount:a.count,thematicType:l.type,fieldName:l.fieldName,classificationMethod:l.classificationMethod,graduatedMode:l.type==="graduated"?l.graduatedMode??"color":void 0,paletteName:l.paletteName,items:f}}),s=this.dataSource.getLayerGroups().map(a=>({...a,rendered:this.isGroupRendered(a.id)})),o=[...r,...n].sort((a,l)=>l.zIndex-a.zIndex);return{layers:o,tree:this.buildTree(o,s),groups:s,activeLayerId:this.dataSource.getActiveLayerId(),totalLayers:o.length}}isGroupRendered(e){for(let n=this.dataSource.getLayerGroup(e);n;n=n.parentId?this.dataSource.getLayerGroup(n.parentId):void 0)if(!n.visible)return!1;return!0}buildTree(e,n){const r=new Map,s=a=>{if(r.has(a))return r.get(a);r.set(a,-1/0);let l=-1/0;return e.forEach(h=>h.groupId===a&&(l=Math.max(l,h.zIndex))),n.forEach(h=>h.parentId===a&&(l=Math.max(l,s(h.id)))),r.set(a,l),l},o=a=>{const l=[];return n.filter(h=>h.parentId===a).forEach(h=>l.push({z:s(h.id),node:{kind:"group",group:h,children:o(h.id)}})),e.filter(h=>h.groupId===a).forEach(h=>l.push({z:h.zIndex,node:{kind:"layer",layer:h}})),l.sort((h,f)=>f.z-h.z).map(h=>h.node)};return o(null)}notifyUpdate(){this.emit("legend:updated",{snapshot:this.getSnapshot()})}findRow(e){return this.dataSource.getLayer(e)??this.dataSource.getTileLayer(e)}toggleLayerVisibility(e){const n=this.findRow(e);n&&this.dataSource.setLayerVisibility(e,!n.visible)}setLayerOpacity(e,n){this.dataSource.setLayerOpacity(e,n)}setActiveLayer(e){!this.dataSource.hasLayer(e)&&this.dataSource.getTileLayer(e)||this.dataSource.setActiveLayer(e)}toggleLayerPinned(e){const n=this.findRow(e);n&&this.dataSource.setLayerPinned(e,!n.pinned)}moveLayerUp(e){this.moveNode({kind:"layer",id:e},-1)}moveLayerDown(e){this.moveNode({kind:"layer",id:e},1)}moveGroupUp(e){this.moveNode({kind:"group",id:e},-1)}moveGroupDown(e){this.moveNode({kind:"group",id:e},1)}nodeLayers(e){return e.kind==="layer"?[e.layer.id]:e.children.flatMap(n=>this.nodeLayers(n))}findSiblings(e,n){const r=e.findIndex(s=>(s.kind==="layer"?s.layer.id:s.group.id)===n.id&&s.kind===n.kind);if(r>=0)return{siblings:e,index:r};for(const s of e)if(s.kind==="group"){const o=this.findSiblings(s.children,n);if(o)return o}return null}moveNode(e,n){const r=this.getSnapshot().tree,s=this.findSiblings(r,e);if(!s)return;const o=this.nodeLayers(s.siblings[s.index]);if(o.length===0)return;let a=[];for(let f=s.index+n;f>=0&&f<s.siblings.length&&(a=this.nodeLayers(s.siblings[f]),!(a.length>0));f+=n);if(a.length===0)return;const l=r.flatMap(f=>this.nodeLayers(f)).filter(f=>!o.includes(f)),h=n===-1?l.indexOf(a[0]):l.indexOf(a[a.length-1])+1;l.splice(h,0,...o),this.dataSource.reorderLayers([...l].reverse())}addGroup(e,n=null,r){let s=r;for(;!s||this.dataSource.getLayerGroup(s);)s=`group_${++this.groupCounter}`;return this.dataSource.addLayerGroup({id:s,name:e,parentId:n}),s}removeGroup(e){this.dataSource.removeLayerGroup(e)}renameGroup(e,n){this.dataSource.updateLayerGroup(e,{name:n})}toggleGroupVisibility(e){const n=this.dataSource.getLayerGroup(e);n&&this.dataSource.updateLayerGroup(e,{visible:!n.visible})}toggleGroupExpanded(e){const n=this.dataSource.getLayerGroup(e);n&&this.dataSource.updateLayerGroup(e,{expanded:!n.expanded})}moveLayerToGroup(e,n){const r=this.findRow(e);if(!r)return;const s=this.dataSource.getDisplayLayers().filter(a=>a.id!==e&&(n===null?!0:this.dataSource.isLayerInGroup(a.id,n))).reduce((a,l)=>Math.max(a,l.zIndex),-1/0);this.dataSource.moveLayerToGroup(e,n),Number.isFinite(s)&&(r.zIndex=s+.5);const o=this.getSnapshot().tree.flatMap(a=>this.nodeLayers(a));this.dataSource.reorderLayers(o.reverse())}setThematicSimple(e,n){this.thematicEngine.createSimpleTheme(e,{fillColor:n,circleColor:n})}setThematicCategorical(e,n,r="category10",s={}){const o=this.dataSource.getLayer(e);o&&this.thematicEngine.createCategoricalTheme(o,n,r,void 0,s)}setThematicGraduated(e,n,r="quantile",s=5,o="viridis",a={}){const l=this.dataSource.getLayer(e);l&&this.thematicEngine.createGraduatedTheme(l,n,r,s,o,void 0,a)}reclassify(e){const n=this.dataSource.getLayer(e);n&&this.thematicEngine.reclassify(n)}updateBaseSymbol(e,n){this.thematicEngine.updateBaseSymbol(e,n)}setLabel(e,n){this.thematicEngine.setLabel(e,n)}getLabel(e){return this.thematicEngine.getLabel(e)}setClassVisible(e,n,r){this.thematicEngine.setClassVisible(e,n,r)}toggleClassVisible(e,n){var s;const r=(s=this.getSnapshot().layers.find(o=>o.id===e))==null?void 0:s.items.find(o=>o.index===n);r&&this.setClassVisible(e,n,!r.visible)}setAllClassesVisible(e,n){this.thematicEngine.setAllClassesVisible(e,n)}updateClass(e,n,r){this.thematicEngine.updateClass(e,n,r)}getThematicEngine(){return this.thematicEngine}getDataSource(){return this.dataSource}destroy(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[],this.removeAllListeners()}}let mF=0;function Rt(i){return String(i).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Yn(i,t=2){return Number.isFinite(i)?String(Number(i.toFixed(t))):"0"}function Ov(i){const t=(i??[]).filter(e=>Number.isFinite(e)&&e>=0);return t.length>=2?` stroke-dasharray="${t.map(e=>Yn(e)).join(" ")}"`:""}function Yf(i,t,e=18){const n=e,r=`<svg xmlns="http://www.w3.org/2000/svg" width="${n}" height="${n}" viewBox="0 0 ${n} ${n}" class="ofs-swatch-svg">`;if(t==="line"){const d=i.line,p=Math.min(Math.max(d.width,.5),n/2);return`${r}<line x1="2" y1="${n/2}" x2="${n-2}" y2="${n/2}" stroke="${Rt(d.color)}" stroke-width="${Yn(p)}" stroke-opacity="${Yn(d.opacity)}" stroke-linecap="${Rt(d.cap??"round")}"${Ov(d.dash)}/></svg>`}if(t==="polygon"){const d=i.fill,p=1.5,y=(L,b="")=>`<rect x="${p}" y="${p}" width="${n-p*2}" height="${n-p*2}" rx="2" fill="${L}"${b}/>`;let _="",E="";if((d.style==="solid"||d.style==="pattern"&&d.patternBackground)&&(_+=y(Rt(d.color),` fill-opacity="${Yn(d.opacity)}"`)),d.style==="pattern"&&d.pattern){const L=d.pattern,b=`ofs-swatch-hatch-${++mF}`,S=Math.max(3,Math.min(L.spacing*.6,n/3)),P=Math.max(.75,Math.min(L.lineWidth,S/2)),N=Rt(L.color);let C="";L.kind==="dots"?C=`<circle cx="${S/2}" cy="${S/2}" r="${Yn(P/2+.25)}" fill="${N}"/>`:(C=`<line x1="0" y1="${S/2}" x2="${S}" y2="${S/2}" stroke="${N}" stroke-width="${Yn(P)}"/>`,L.kind==="cross"&&(C+=`<line x1="${S/2}" y1="0" x2="${S/2}" y2="${S}" stroke="${N}" stroke-width="${Yn(P)}"/>`)),E=`<defs><pattern id="${b}" patternUnits="userSpaceOnUse" width="${S}" height="${S}" patternTransform="rotate(${Yn(-L.angleDeg)})">${C}</pattern></defs>`,_+=y(`url(#${b})`,` fill-opacity="${Yn(d.opacity)}"`)}const w=Math.min(d.outlineWidth,3);return w>0&&(_+=y("none",` stroke="${Rt(d.outlineColor)}" stroke-width="${Yn(w)}" stroke-opacity="${Yn(d.outlineOpacity)}"${Ov(d.outlineDash)}`)),`${r}${E}${_}</svg>`}const s=i.marker,o=Math.min(s.strokeWidth,3),a=Math.max(2,Math.min(s.size,n-2)/2-o/2),l=n/2,h=s.rotationDeg?` transform="rotate(${Yn(s.rotationDeg)} ${l} ${l})"`:"";if(s.shape==="icon"){const d=s.icon?C0(s.icon):void 0;if(d){const p=k0(d.source)?`data:image/svg+xml;charset=utf-8,${encodeURIComponent(d.source)}`:d.source;return`${r}<image href="${Rt(p)}" x="${l-a}" y="${l-a}" width="${a*2}" height="${a*2}" opacity="${Yn(s.opacity)}"${h}/></svg>`}}const f=s.shape==="icon"?"circle":s.shape;return`${r}<path d="${Ob(f,l,l,a)}" fill="${Rt(s.color)}" fill-opacity="${Yn(s.opacity)}" stroke="${Rt(s.strokeColor)}" stroke-width="${Yn(o)}"${h}/></svg>`}class pF{constructor(t,e={}){q(this,"legendTools");q(this,"container",null);q(this,"unsubscriber",null);q(this,"options");q(this,"handleClick",t=>{var h,f,d,p,y,_;const e=t.target,n=e.closest("[data-action]"),r=n==null?void 0:n.dataset.action,s=(n==null?void 0:n.dataset.id)??"",o=this.legendTools;switch(r){case"add-group":{const E=typeof prompt=="function"?prompt("Group name:","New group"):"New group";E&&o.addGroup(E);return}case"group-expand":o.toggleGroupExpanded(s);return;case"group-up":o.moveGroupUp(s);return;case"group-down":o.moveGroupDown(s);return;case"group-remove":o.removeGroup(s);return;case"layer-pin":t.stopPropagation(),o.toggleLayerPinned(s);return;case"import":(f=(h=this.options).onImport)==null||f.call(h);return;case"layer-export":t.stopPropagation(),(p=(d=this.options).onExportLayer)==null||p.call(d,s);return;case"layer-style":t.stopPropagation(),(_=(y=this.options).onEditSymbology)==null||_.call(y,s);return;case"layer-up":t.stopPropagation(),o.moveLayerUp(s);return;case"layer-down":t.stopPropagation(),o.moveLayerDown(s);return}if(e.closest("input, select, button, label"))return;const a=e.closest(".ofs-legend-layer"),l=a==null?void 0:a.dataset.layerId;l&&o.setActiveLayer(l)});q(this,"handleChange",t=>{const e=t.target,n=e.dataset.id??"";switch(e.dataset.action){case"layer-visible":this.legendTools.toggleLayerVisibility(n);return;case"group-visible":this.legendTools.toggleGroupVisibility(n);return;case"class-visible":this.legendTools.setClassVisible(n,Number(e.dataset.index),e.checked);return;case"layer-group":this.legendTools.moveLayerToGroup(n,e.value||null);return;case"layer-opacity":e.blur(),this.legendTools.notifyUpdate();return}});q(this,"handleDoubleClick",t=>{const e=t.target.closest('[data-action="group-rename"]'),n=e==null?void 0:e.dataset.id;if(!n||typeof prompt!="function")return;const r=this.legendTools.getDataSource().getLayerGroup(n),s=prompt("Group name:",(r==null?void 0:r.name)??"");s&&this.legendTools.renameGroup(n,s)});q(this,"handleInput",t=>{const e=t.target;e.dataset.action==="layer-opacity"&&e.dataset.id&&this.legendTools.setLayerOpacity(e.dataset.id,parseFloat(e.value))});this.legendTools=t,this.options=e}mount(t){const e=typeof t=="string"?document.getElementById(t):t;if(!e)throw new Error(`Target container for LegendWidget not found: ${t}`);this.container=e,this.container.classList.add("ofs-legend-container"),this.container.addEventListener("click",this.handleClick),this.container.addEventListener("change",this.handleChange),this.container.addEventListener("input",this.handleInput),this.container.addEventListener("dblclick",this.handleDoubleClick),this.unsubscriber=this.legendTools.on("legend:updated",({snapshot:n})=>{this.render(n)}),this.render(this.legendTools.getSnapshot())}unmount(){this.unsubscriber&&(this.unsubscriber(),this.unsubscriber=null),this.container&&(this.container.removeEventListener("click",this.handleClick),this.container.removeEventListener("change",this.handleChange),this.container.removeEventListener("input",this.handleInput),this.container.removeEventListener("dblclick",this.handleDoubleClick),this.container.innerHTML="",this.container=null)}render(t){var n;if(!this.container)return;const e=document.activeElement;if(e&&this.container.contains(e)&&e.classList.contains("ofs-opacity-slider")){const r=(n=e.parentElement)==null?void 0:n.querySelector(".ofs-opacity-val");r&&(r.textContent=`${Math.round(Number(e.value)*100)}%`);return}if(t.layers.length===0&&t.groups.length===0){this.container.innerHTML=`
26
+ `)}return t.toString()}computeEdgeEndLabels(t){for(let e=this.iterator();e.hasNext();)e.next().computeLabel(t)}computeLabelling(t){this.computeEdgeEndLabels(t[0].getBoundaryNodeRule()),this.propagateSideLabels(0),this.propagateSideLabels(1);const e=[!1,!1];for(let n=this.iterator();n.hasNext();){const s=n.next().getLabel();for(let o=0;o<2;o++)s.isLine(o)&&s.getLocation(o)===z.BOUNDARY&&(e[o]=!0)}for(let n=this.iterator();n.hasNext();){const r=n.next(),s=r.getLabel();for(let o=0;o<2;o++)if(s.isAnyNull(o)){let a=z.NONE;if(e[o])a=z.EXTERIOR;else{const l=r.getCoordinate();a=this.getLocation(o,l,t)}s.setAllLocationsIfNull(o,a)}}}getDegree(){return this._edgeMap.size()}insertEdgeEnd(t,e){this._edgeMap.put(t,e),this._edgeList=null}}class Qp extends Nd{constructor(){super(),Qp.constructor_.apply(this,arguments)}static constructor_(){this._resultAreaEdgeList=null,this._label=null,this._SCANNING_FOR_INCOMING=1,this._LINKING_TO_OUTGOING=2}linkResultDirectedEdges(){this.getResultAreaEdges();let t=null,e=null,n=this._SCANNING_FOR_INCOMING;for(let r=0;r<this._resultAreaEdgeList.size();r++){const s=this._resultAreaEdgeList.get(r),o=s.getSym();if(s.getLabel().isArea())switch(t===null&&s.isInResult()&&(t=s),n){case this._SCANNING_FOR_INCOMING:if(!o.isInResult())continue;e=o,n=this._LINKING_TO_OUTGOING;break;case this._LINKING_TO_OUTGOING:if(!s.isInResult())continue;e.setNext(s),n=this._SCANNING_FOR_INCOMING;break}}if(n===this._LINKING_TO_OUTGOING){if(t===null)throw new Fi("no outgoing dirEdge found",this.getCoordinate());Yt.isTrue(t.isInResult(),"unable to link last incoming dirEdge"),e.setNext(t)}}insert(t){const e=t;this.insertEdgeEnd(e,e)}getRightmostEdge(){const t=this.getEdges(),e=t.size();if(e<1)return null;const n=t.get(0);if(e===1)return n;const r=t.get(e-1),s=n.getQuadrant(),o=r.getQuadrant();return Le.isNorthern(s)&&Le.isNorthern(o)?n:!Le.isNorthern(s)&&!Le.isNorthern(o)?r:n.getDy()!==0?n:r.getDy()!==0?r:(Yt.shouldNeverReachHere("found two horizontal edges incident on node"),null)}print(t){pi.out.println("DirectedEdgeStar: "+this.getCoordinate());for(let e=this.iterator();e.hasNext();){const n=e.next();t.print("out "),n.print(t),t.println(),t.print("in "),n.getSym().print(t),t.println()}}getResultAreaEdges(){if(this._resultAreaEdgeList!==null)return this._resultAreaEdgeList;this._resultAreaEdgeList=new wt;for(let t=this.iterator();t.hasNext();){const e=t.next();(e.isInResult()||e.getSym().isInResult())&&this._resultAreaEdgeList.add(e)}return this._resultAreaEdgeList}updateLabelling(t){for(let e=this.iterator();e.hasNext();){const r=e.next().getLabel();r.setAllLocationsIfNull(0,t.getLocation(0)),r.setAllLocationsIfNull(1,t.getLocation(1))}}linkAllDirectedEdges(){this.getEdges();let t=null,e=null;for(let n=this._edgeList.size()-1;n>=0;n--){const r=this._edgeList.get(n),s=r.getSym();e===null&&(e=s),t!==null&&s.setNext(t),t=r}e.setNext(t)}computeDepths(){if(arguments.length===1){const t=arguments[0],e=this.findIndex(t),n=t.getDepth(_t.LEFT),r=t.getDepth(_t.RIGHT),s=this.computeDepths(e+1,this._edgeList.size(),n);if(this.computeDepths(0,e,s)!==r)throw new Fi("depth mismatch at "+t.getCoordinate())}else if(arguments.length===3){const t=arguments[0],e=arguments[1];let r=arguments[2];for(let s=t;s<e;s++){const o=this._edgeList.get(s);o.setEdgeDepths(_t.RIGHT,r),r=o.getDepth(_t.LEFT)}return r}}mergeSymLabels(){for(let t=this.iterator();t.hasNext();){const e=t.next();e.getLabel().merge(e.getSym().getLabel())}}linkMinimalDirectedEdges(t){let e=null,n=null,r=this._SCANNING_FOR_INCOMING;for(let s=this._resultAreaEdgeList.size()-1;s>=0;s--){const o=this._resultAreaEdgeList.get(s),a=o.getSym();switch(e===null&&o.getEdgeRing()===t&&(e=o),r){case this._SCANNING_FOR_INCOMING:if(a.getEdgeRing()!==t)continue;n=a,r=this._LINKING_TO_OUTGOING;break;case this._LINKING_TO_OUTGOING:if(o.getEdgeRing()!==t)continue;n.setNextMin(o),r=this._SCANNING_FOR_INCOMING;break}}r===this._LINKING_TO_OUTGOING&&(Yt.isTrue(e!==null,"found null for first outgoing dirEdge"),Yt.isTrue(e.getEdgeRing()===t,"unable to link last incoming dirEdge"),n.setNextMin(e))}getOutgoingDegree(){if(arguments.length===0){let t=0;for(let e=this.iterator();e.hasNext();)e.next().isInResult()&&t++;return t}else if(arguments.length===1){const t=arguments[0];let e=0;for(let n=this.iterator();n.hasNext();)n.next().getEdgeRing()===t&&e++;return e}}getLabel(){return this._label}findCoveredLineEdges(){let t=z.NONE;for(let n=this.iterator();n.hasNext();){const r=n.next(),s=r.getSym();if(!r.isLineEdge()){if(r.isInResult()){t=z.INTERIOR;break}if(s.isInResult()){t=z.EXTERIOR;break}}}if(t===z.NONE)return null;let e=t;for(let n=this.iterator();n.hasNext();){const r=n.next(),s=r.getSym();r.isLineEdge()?r.getEdge().setCovered(e===z.INTERIOR):(r.isInResult()&&(e=z.EXTERIOR),s.isInResult()&&(e=z.INTERIOR))}}computeLabelling(t){super.computeLabelling.call(this,t),this._label=new Ge(z.NONE);for(let e=this.iterator();e.hasNext();){const s=e.next().getEdge().getLabel();for(let o=0;o<2;o++){const a=s.getLocation(o);(a===z.INTERIOR||a===z.BOUNDARY)&&this._label.setLocation(o,z.INTERIOR)}}}}class t0 extends Vp{constructor(){super()}createNode(t){return new bs(t,new Qp)}}class Wa{constructor(){Wa.constructor_.apply(this,arguments)}static constructor_(){this._pts=null,this._orientation=null;const t=arguments[0];this._pts=t,this._orientation=Wa.orientation(t)}static orientation(t){return Ce.increasingDirection(t)===1}static compareOriented(t,e,n,r){const s=e?1:-1,o=r?1:-1,a=e?t.length:-1,l=r?n.length:-1;let h=e?0:t.length-1,f=r?0:n.length-1;for(;;){const d=t[h].compareTo(n[f]);if(d!==0)return d;h+=s,f+=o;const p=h===a,y=f===l;if(p&&!y)return-1;if(!p&&y)return 1;if(p&&y)return 0}}compareTo(t){const e=t;return Wa.compareOriented(this._pts,this._orientation,e._pts,e._orientation)}get interfaces_(){return[Ei]}}class Ld{constructor(){Ld.constructor_.apply(this,arguments)}static constructor_(){this._edges=new wt,this._ocaMap=new ss}print(t){t.print("MULTILINESTRING ( ");for(let e=0;e<this._edges.size();e++){const n=this._edges.get(e);e>0&&t.print(","),t.print("(");const r=n.getCoordinates();for(let s=0;s<r.length;s++)s>0&&t.print(","),t.print(r[s].x+" "+r[s].y);t.println(")")}t.print(") ")}addAll(t){for(let e=t.iterator();e.hasNext();)this.add(e.next())}findEdgeIndex(t){for(let e=0;e<this._edges.size();e++)if(this._edges.get(e).equals(t))return e;return-1}iterator(){return this._edges.iterator()}getEdges(){return this._edges}get(t){return this._edges.get(t)}findEqualEdge(t){const e=new Wa(t.getCoordinates());return this._ocaMap.get(e)}add(t){this._edges.add(t);const e=new Wa(t.getCoordinates());this._ocaMap.put(e,t)}}let e0=class{processIntersections(t,e,n,r){}isDone(){}};class Rf{constructor(){Rf.constructor_.apply(this,arguments)}static constructor_(){this._hasIntersection=!1,this._hasProper=!1,this._hasProperInterior=!1,this._hasInterior=!1,this._properIntersectionPoint=null,this._li=null,this._isSelfIntersection=null,this.numIntersections=0,this.numInteriorIntersections=0,this.numProperIntersections=0,this.numTests=0;const t=arguments[0];this._li=t}static isAdjacentSegments(t,e){return Math.abs(t-e)===1}isTrivialIntersection(t,e,n,r){if(t===n&&this._li.getIntersectionNum()===1){if(Rf.isAdjacentSegments(e,r))return!0;if(t.isClosed()){const s=t.size()-1;if(e===0&&r===s||r===0&&e===s)return!0}}return!1}getProperIntersectionPoint(){return this._properIntersectionPoint}hasProperInteriorIntersection(){return this._hasProperInterior}getLineIntersector(){return this._li}hasProperIntersection(){return this._hasProper}processIntersections(t,e,n,r){if(t===n&&e===r)return null;this.numTests++;const s=t.getCoordinates()[e],o=t.getCoordinates()[e+1],a=n.getCoordinates()[r],l=n.getCoordinates()[r+1];this._li.computeIntersection(s,o,a,l),this._li.hasIntersection()&&(this.numIntersections++,this._li.isInteriorIntersection()&&(this.numInteriorIntersections++,this._hasInterior=!0),this.isTrivialIntersection(t,e,n,r)||(this._hasIntersection=!0,t.addIntersections(this._li,e,0),n.addIntersections(this._li,r,1),this._li.isProper()&&(this.numProperIntersections++,this._hasProper=!0,this._hasProperInterior=!0)))}hasIntersection(){return this._hasIntersection}isDone(){return!1}hasInteriorIntersection(){return this._hasInterior}get interfaces_(){return[e0]}}class n0{constructor(){n0.constructor_.apply(this,arguments)}static constructor_(){this.coord=null,this.segmentIndex=null,this.dist=null;const t=arguments[0],e=arguments[1],n=arguments[2];this.coord=new Q(t),this.segmentIndex=e,this.dist=n}getSegmentIndex(){return this.segmentIndex}getCoordinate(){return this.coord}print(t){t.print(this.coord),t.print(" seg # = "+this.segmentIndex),t.println(" dist = "+this.dist)}compareTo(t){const e=t;return this.compare(e.segmentIndex,e.dist)}isEndPoint(t){return this.segmentIndex===0&&this.dist===0||this.segmentIndex===t}toString(){return this.coord+" seg # = "+this.segmentIndex+" dist = "+this.dist}getDistance(){return this.dist}compare(t,e){return this.segmentIndex<t?-1:this.segmentIndex>t?1:this.dist<e?-1:this.dist>e?1:0}get interfaces_(){return[Ei]}}class i0{constructor(){i0.constructor_.apply(this,arguments)}static constructor_(){this._nodeMap=new ss,this.edge=null;const t=arguments[0];this.edge=t}print(t){t.println("Intersections:");for(let e=this.iterator();e.hasNext();)e.next().print(t)}iterator(){return this._nodeMap.values().iterator()}addSplitEdges(t){this.addEndpoints();const e=this.iterator();let n=e.next();for(;e.hasNext();){const r=e.next(),s=this.createSplitEdge(n,r);t.add(s),n=r}}addEndpoints(){const t=this.edge.pts.length-1;this.add(this.edge.pts[0],0,0),this.add(this.edge.pts[t],t,0)}createSplitEdge(t,e){let n=e.segmentIndex-t.segmentIndex+2;const r=this.edge.pts[e.segmentIndex],s=e.dist>0||!e.coord.equals2D(r);s||n--;const o=new Array(n).fill(null);let a=0;o[a++]=new Q(t.coord);for(let l=t.segmentIndex+1;l<=e.segmentIndex;l++)o[a++]=this.edge.pts[l];return s&&(o[a]=e.coord),new xr(o,new Ge(this.edge._label))}add(t,e,n){const r=new n0(t,e,n),s=this._nodeMap.get(r);return s!==null?s:(this._nodeMap.put(r,r),r)}isIntersection(t){for(let e=this.iterator();e.hasNext();)if(e.next().coord.equals(t))return!0;return!1}}class pe{constructor(){pe.constructor_.apply(this,arguments)}static constructor_(){if(this._matrix=null,arguments.length===0)this._matrix=Array(3).fill().map(()=>Array(3)),this.setAll(yt.FALSE);else if(arguments.length===1){if(typeof arguments[0]=="string"){const t=arguments[0];pe.constructor_.call(this),this.set(t)}else if(arguments[0]instanceof pe){const t=arguments[0];pe.constructor_.call(this),this._matrix[z.INTERIOR][z.INTERIOR]=t._matrix[z.INTERIOR][z.INTERIOR],this._matrix[z.INTERIOR][z.BOUNDARY]=t._matrix[z.INTERIOR][z.BOUNDARY],this._matrix[z.INTERIOR][z.EXTERIOR]=t._matrix[z.INTERIOR][z.EXTERIOR],this._matrix[z.BOUNDARY][z.INTERIOR]=t._matrix[z.BOUNDARY][z.INTERIOR],this._matrix[z.BOUNDARY][z.BOUNDARY]=t._matrix[z.BOUNDARY][z.BOUNDARY],this._matrix[z.BOUNDARY][z.EXTERIOR]=t._matrix[z.BOUNDARY][z.EXTERIOR],this._matrix[z.EXTERIOR][z.INTERIOR]=t._matrix[z.EXTERIOR][z.INTERIOR],this._matrix[z.EXTERIOR][z.BOUNDARY]=t._matrix[z.EXTERIOR][z.BOUNDARY],this._matrix[z.EXTERIOR][z.EXTERIOR]=t._matrix[z.EXTERIOR][z.EXTERIOR]}}}static matches(){if(Number.isInteger(arguments[0])&&typeof arguments[1]=="string"){const t=arguments[0],e=arguments[1];return e===yt.SYM_DONTCARE||e===yt.SYM_TRUE&&(t>=0||t===yt.TRUE)||e===yt.SYM_FALSE&&t===yt.FALSE||e===yt.SYM_P&&t===yt.P||e===yt.SYM_L&&t===yt.L||e===yt.SYM_A&&t===yt.A}else if(typeof arguments[0]=="string"&&typeof arguments[1]=="string"){const t=arguments[0],e=arguments[1];return new pe(t).matches(e)}}static isTrue(t){return t>=0||t===yt.TRUE}isIntersects(){return!this.isDisjoint()}isCovers(){return(pe.isTrue(this._matrix[z.INTERIOR][z.INTERIOR])||pe.isTrue(this._matrix[z.INTERIOR][z.BOUNDARY])||pe.isTrue(this._matrix[z.BOUNDARY][z.INTERIOR])||pe.isTrue(this._matrix[z.BOUNDARY][z.BOUNDARY]))&&this._matrix[z.EXTERIOR][z.INTERIOR]===yt.FALSE&&this._matrix[z.EXTERIOR][z.BOUNDARY]===yt.FALSE}isCoveredBy(){return(pe.isTrue(this._matrix[z.INTERIOR][z.INTERIOR])||pe.isTrue(this._matrix[z.INTERIOR][z.BOUNDARY])||pe.isTrue(this._matrix[z.BOUNDARY][z.INTERIOR])||pe.isTrue(this._matrix[z.BOUNDARY][z.BOUNDARY]))&&this._matrix[z.INTERIOR][z.EXTERIOR]===yt.FALSE&&this._matrix[z.BOUNDARY][z.EXTERIOR]===yt.FALSE}set(){if(arguments.length===1){const t=arguments[0];for(let e=0;e<t.length;e++){const n=Math.trunc(e/3),r=e%3;this._matrix[n][r]=yt.toDimensionValue(t.charAt(e))}}else if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2];this._matrix[t][e]=n}}isContains(){return pe.isTrue(this._matrix[z.INTERIOR][z.INTERIOR])&&this._matrix[z.EXTERIOR][z.INTERIOR]===yt.FALSE&&this._matrix[z.EXTERIOR][z.BOUNDARY]===yt.FALSE}setAtLeast(){if(arguments.length===1){const t=arguments[0];for(let e=0;e<t.length;e++){const n=Math.trunc(e/3),r=e%3;this.setAtLeast(n,r,yt.toDimensionValue(t.charAt(e)))}}else if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2];this._matrix[t][e]<n&&(this._matrix[t][e]=n)}}setAtLeastIfValid(t,e,n){t>=0&&e>=0&&this.setAtLeast(t,e,n)}isWithin(){return pe.isTrue(this._matrix[z.INTERIOR][z.INTERIOR])&&this._matrix[z.INTERIOR][z.EXTERIOR]===yt.FALSE&&this._matrix[z.BOUNDARY][z.EXTERIOR]===yt.FALSE}isTouches(t,e){return t>e?this.isTouches(e,t):t===yt.A&&e===yt.A||t===yt.L&&e===yt.L||t===yt.L&&e===yt.A||t===yt.P&&e===yt.A||t===yt.P&&e===yt.L?this._matrix[z.INTERIOR][z.INTERIOR]===yt.FALSE&&(pe.isTrue(this._matrix[z.INTERIOR][z.BOUNDARY])||pe.isTrue(this._matrix[z.BOUNDARY][z.INTERIOR])||pe.isTrue(this._matrix[z.BOUNDARY][z.BOUNDARY])):!1}isOverlaps(t,e){return t===yt.P&&e===yt.P||t===yt.A&&e===yt.A?pe.isTrue(this._matrix[z.INTERIOR][z.INTERIOR])&&pe.isTrue(this._matrix[z.INTERIOR][z.EXTERIOR])&&pe.isTrue(this._matrix[z.EXTERIOR][z.INTERIOR]):t===yt.L&&e===yt.L?this._matrix[z.INTERIOR][z.INTERIOR]===1&&pe.isTrue(this._matrix[z.INTERIOR][z.EXTERIOR])&&pe.isTrue(this._matrix[z.EXTERIOR][z.INTERIOR]):!1}isEquals(t,e){return t!==e?!1:pe.isTrue(this._matrix[z.INTERIOR][z.INTERIOR])&&this._matrix[z.INTERIOR][z.EXTERIOR]===yt.FALSE&&this._matrix[z.BOUNDARY][z.EXTERIOR]===yt.FALSE&&this._matrix[z.EXTERIOR][z.INTERIOR]===yt.FALSE&&this._matrix[z.EXTERIOR][z.BOUNDARY]===yt.FALSE}toString(){const t=new yd("123456789");for(let e=0;e<3;e++)for(let n=0;n<3;n++)t.setCharAt(3*e+n,yt.toDimensionSymbol(this._matrix[e][n]));return t.toString()}setAll(t){for(let e=0;e<3;e++)for(let n=0;n<3;n++)this._matrix[e][n]=t}get(t,e){return this._matrix[t][e]}transpose(){let t=this._matrix[1][0];return this._matrix[1][0]=this._matrix[0][1],this._matrix[0][1]=t,t=this._matrix[2][0],this._matrix[2][0]=this._matrix[0][2],this._matrix[0][2]=t,t=this._matrix[2][1],this._matrix[2][1]=this._matrix[1][2],this._matrix[1][2]=t,this}matches(t){if(t.length!==9)throw new te("Should be length 9: "+t);for(let e=0;e<3;e++)for(let n=0;n<3;n++)if(!pe.matches(this._matrix[e][n],t.charAt(3*e+n)))return!1;return!0}add(t){for(let e=0;e<3;e++)for(let n=0;n<3;n++)this.setAtLeast(e,n,t.get(e,n))}isDisjoint(){return this._matrix[z.INTERIOR][z.INTERIOR]===yt.FALSE&&this._matrix[z.INTERIOR][z.BOUNDARY]===yt.FALSE&&this._matrix[z.BOUNDARY][z.INTERIOR]===yt.FALSE&&this._matrix[z.BOUNDARY][z.BOUNDARY]===yt.FALSE}isCrosses(t,e){return t===yt.P&&e===yt.L||t===yt.P&&e===yt.A||t===yt.L&&e===yt.A?pe.isTrue(this._matrix[z.INTERIOR][z.INTERIOR])&&pe.isTrue(this._matrix[z.INTERIOR][z.EXTERIOR]):t===yt.L&&e===yt.P||t===yt.A&&e===yt.P||t===yt.A&&e===yt.L?pe.isTrue(this._matrix[z.INTERIOR][z.INTERIOR])&&pe.isTrue(this._matrix[z.EXTERIOR][z.INTERIOR]):t===yt.L&&e===yt.L?this._matrix[z.INTERIOR][z.INTERIOR]===0:!1}get interfaces_(){return[Tc]}}class Af{constructor(){Af.constructor_.apply(this,arguments)}static constructor_(){if(this._data=null,this._size=0,arguments.length===0)Af.constructor_.call(this,10);else if(arguments.length===1){const t=arguments[0];this._data=new Array(t).fill(null)}}size(){return this._size}addAll(t){if(t===null||t.length===0)return null;this.ensureCapacity(this._size+t.length),pi.arraycopy(t,0,this._data,this._size,t.length),this._size+=t.length}ensureCapacity(t){if(t<=this._data.length)return null;const e=Math.max(t,this._data.length*2);this._data=Ys.copyOf(this._data,e)}toArray(){const t=new Array(this._size).fill(null);return pi.arraycopy(this._data,0,t,0,this._size),t}add(t){this.ensureCapacity(this._size+1),this._data[this._size]=t,++this._size}}class r0{static toIntArray(t){const e=new Array(t.size()).fill(null);for(let n=0;n<e.length;n++)e[n]=t.get(n).intValue();return e}getChainStartIndices(t){let e=0;const n=new Af(Math.trunc(t.length/2));n.add(e);do{const r=this.findChainEnd(t,e);n.add(r),e=r}while(e<t.length-1);return n.toArray()}findChainEnd(t,e){const n=Le.quadrant(t[e],t[e+1]);let r=e+1;for(;r<t.length&&Le.quadrant(t[r-1],t[r])===n;)r++;return r-1}OLDgetChainStartIndices(t){let e=0;const n=new wt;n.add(e);do{const s=this.findChainEnd(t,e);n.add(s),e=s}while(e<t.length-1);return r0.toIntArray(n)}}class s0{constructor(){s0.constructor_.apply(this,arguments)}static constructor_(){this.e=null,this.pts=null,this.startIndex=null;const t=arguments[0];this.e=t,this.pts=t.getCoordinates();const e=new r0;this.startIndex=e.getChainStartIndices(this.pts)}getCoordinates(){return this.pts}getMaxX(t){const e=this.pts[this.startIndex[t]].x,n=this.pts[this.startIndex[t+1]].x;return e>n?e:n}getMinX(t){const e=this.pts[this.startIndex[t]].x,n=this.pts[this.startIndex[t+1]].x;return e<n?e:n}computeIntersectsForChain(){if(arguments.length===4){const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];this.computeIntersectsForChain(this.startIndex[t],this.startIndex[t+1],e,e.startIndex[n],e.startIndex[n+1],r)}else if(arguments.length===6){const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3],s=arguments[4],o=arguments[5];if(e-t===1&&s-r===1)return o.addIntersections(this.e,t,n.e,r),null;if(!this.overlaps(t,e,n,r,s))return null;const a=Math.trunc((t+e)/2),l=Math.trunc((r+s)/2);t<a&&(r<l&&this.computeIntersectsForChain(t,a,n,r,l,o),l<s&&this.computeIntersectsForChain(t,a,n,l,s,o)),a<e&&(r<l&&this.computeIntersectsForChain(a,e,n,r,l,o),l<s&&this.computeIntersectsForChain(a,e,n,l,s,o))}}overlaps(t,e,n,r,s){return ne.intersects(this.pts[t],this.pts[e],n.pts[r],n.pts[s])}getStartIndexes(){return this.startIndex}computeIntersects(t,e){for(let n=0;n<this.startIndex.length-1;n++)for(let r=0;r<t.startIndex.length-1;r++)this.computeIntersectsForChain(n,t,r,e)}}class yr{constructor(){yr.constructor_.apply(this,arguments)}static constructor_(){this._depth=Array(2).fill().map(()=>Array(3));for(let t=0;t<2;t++)for(let e=0;e<3;e++)this._depth[t][e]=yr.NULL_VALUE}static depthAtLocation(t){return t===z.EXTERIOR?0:t===z.INTERIOR?1:yr.NULL_VALUE}getDepth(t,e){return this._depth[t][e]}setDepth(t,e,n){this._depth[t][e]=n}isNull(){if(arguments.length===0){for(let t=0;t<2;t++)for(let e=0;e<3;e++)if(this._depth[t][e]!==yr.NULL_VALUE)return!1;return!0}else if(arguments.length===1){const t=arguments[0];return this._depth[t][1]===yr.NULL_VALUE}else if(arguments.length===2){const t=arguments[0],e=arguments[1];return this._depth[t][e]===yr.NULL_VALUE}}normalize(){for(let t=0;t<2;t++)if(!this.isNull(t)){let e=this._depth[t][1];this._depth[t][2]<e&&(e=this._depth[t][2]),e<0&&(e=0);for(let n=1;n<3;n++){let r=0;this._depth[t][n]>e&&(r=1),this._depth[t][n]=r}}}getDelta(t){return this._depth[t][_t.RIGHT]-this._depth[t][_t.LEFT]}getLocation(t,e){return this._depth[t][e]<=0?z.EXTERIOR:z.INTERIOR}toString(){return"A: "+this._depth[0][1]+","+this._depth[0][2]+" B: "+this._depth[1][1]+","+this._depth[1][2]}add(){if(arguments.length===1){const t=arguments[0];for(let e=0;e<2;e++)for(let n=1;n<3;n++){const r=t.getLocation(e,n);(r===z.EXTERIOR||r===z.INTERIOR)&&(this.isNull(e,n)?this._depth[e][n]=yr.depthAtLocation(r):this._depth[e][n]+=yr.depthAtLocation(r))}}else if(arguments.length===3){const t=arguments[0],e=arguments[1];arguments[2]===z.INTERIOR&&this._depth[t][e]++}}}yr.NULL_VALUE=-1;class xr extends Ed{constructor(){super(),xr.constructor_.apply(this,arguments)}static constructor_(){if(this.pts=null,this._env=null,this.eiList=new i0(this),this._name=null,this._mce=null,this._isIsolated=!0,this._depth=new yr,this._depthDelta=0,arguments.length===1){const t=arguments[0];xr.constructor_.call(this,t,null)}else if(arguments.length===2){const t=arguments[0],e=arguments[1];this.pts=t,this._label=e}}static updateIM(){if(arguments.length===2&&arguments[1]instanceof pe&&arguments[0]instanceof Ge){const t=arguments[0],e=arguments[1];e.setAtLeastIfValid(t.getLocation(0,_t.ON),t.getLocation(1,_t.ON),1),t.isArea()&&(e.setAtLeastIfValid(t.getLocation(0,_t.LEFT),t.getLocation(1,_t.LEFT),2),e.setAtLeastIfValid(t.getLocation(0,_t.RIGHT),t.getLocation(1,_t.RIGHT),2))}else return super.updateIM.apply(this,arguments)}getDepth(){return this._depth}getCollapsedEdge(){const t=new Array(2).fill(null);return t[0]=this.pts[0],t[1]=this.pts[1],new xr(t,Ge.toLineLabel(this._label))}isIsolated(){return this._isIsolated}getCoordinates(){return this.pts}setIsolated(t){this._isIsolated=t}setName(t){this._name=t}equals(t){if(!(t instanceof xr))return!1;const e=t;if(this.pts.length!==e.pts.length)return!1;let n=!0,r=!0,s=this.pts.length;for(let o=0;o<this.pts.length;o++)if(this.pts[o].equals2D(e.pts[o])||(n=!1),this.pts[o].equals2D(e.pts[--s])||(r=!1),!n&&!r)return!1;return!0}getCoordinate(){if(arguments.length===0)return this.pts.length>0?this.pts[0]:null;if(arguments.length===1){const t=arguments[0];return this.pts[t]}}print(t){t.print("edge "+this._name+": "),t.print("LINESTRING (");for(let e=0;e<this.pts.length;e++)e>0&&t.print(","),t.print(this.pts[e].x+" "+this.pts[e].y);t.print(") "+this._label+" "+this._depthDelta)}computeIM(t){xr.updateIM(this._label,t)}isCollapsed(){return!this._label.isArea()||this.pts.length!==3?!1:!!this.pts[0].equals(this.pts[2])}isClosed(){return this.pts[0].equals(this.pts[this.pts.length-1])}getMaximumSegmentIndex(){return this.pts.length-1}getDepthDelta(){return this._depthDelta}getNumPoints(){return this.pts.length}printReverse(t){t.print("edge "+this._name+": ");for(let e=this.pts.length-1;e>=0;e--)t.print(this.pts[e]+" ");t.println("")}getMonotoneChainEdge(){return this._mce===null&&(this._mce=new s0(this)),this._mce}getEnvelope(){if(this._env===null){this._env=new ne;for(let t=0;t<this.pts.length;t++)this._env.expandToInclude(this.pts[t])}return this._env}addIntersection(t,e,n,r){const s=new Q(t.getIntersection(r));let o=e,a=t.getEdgeDistance(n,r);const l=o+1;if(l<this.pts.length){const h=this.pts[l];s.equals2D(h)&&(o=l,a=0)}this.eiList.add(s,o,a)}toString(){const t=new yd;t.append("edge "+this._name+": "),t.append("LINESTRING (");for(let e=0;e<this.pts.length;e++)e>0&&t.append(","),t.append(this.pts[e].x+" "+this.pts[e].y);return t.append(") "+this._label+" "+this._depthDelta),t.toString()}isPointwiseEqual(t){if(this.pts.length!==t.pts.length)return!1;for(let e=0;e<this.pts.length;e++)if(!this.pts[e].equals2D(t.pts[e]))return!1;return!0}setDepthDelta(t){this._depthDelta=t}getEdgeIntersectionList(){return this.eiList}addIntersections(t,e,n){for(let r=0;r<t.getIntersectionNum();r++)this.addIntersection(t,e,n,r)}}class Ha{constructor(){Ha.constructor_.apply(this,arguments)}static constructor_(){this._bufParams=null,this._workingPrecisionModel=null,this._workingNoder=null,this._geomFact=null,this._graph=null,this._edgeList=new Ld;const t=arguments[0];this._bufParams=t}static depthDelta(t){const e=t.getLocation(0,_t.LEFT),n=t.getLocation(0,_t.RIGHT);return e===z.INTERIOR&&n===z.EXTERIOR?1:e===z.EXTERIOR&&n===z.INTERIOR?-1:0}static convertSegStrings(t){const e=new qe,n=new wt;for(;t.hasNext();){const r=t.next(),s=e.createLineString(r.getCoordinates());n.add(s)}return e.buildGeometry(n)}setWorkingPrecisionModel(t){this._workingPrecisionModel=t}insertUniqueEdge(t){const e=this._edgeList.findEqualEdge(t);if(e!==null){const n=e.getLabel();let r=t.getLabel();e.isPointwiseEqual(t)||(r=new Ge(t.getLabel()),r.flip()),n.merge(r);const s=Ha.depthDelta(r),a=e.getDepthDelta()+s;e.setDepthDelta(a)}else this._edgeList.add(t),t.setDepthDelta(Ha.depthDelta(t.getLabel()))}buildSubgraphs(t,e){const n=new wt;for(let r=t.iterator();r.hasNext();){const s=r.next(),o=s.getRightmostCoordinate(),l=new Sd(n).getDepth(o);s.computeDepth(l),s.findResultEdges(),n.add(s),e.add(s.getDirectedEdges(),s.getNodes())}}createSubgraphs(t){const e=new wt;for(let n=t.getNodes().iterator();n.hasNext();){const r=n.next();if(!r.isVisited()){const s=new Yp;s.create(r),e.add(s)}}return Is.sort(e,Is.reverseOrder()),e}createEmptyResultGeometry(){return this._geomFact.createPolygon()}getNoder(t){if(this._workingNoder!==null)return this._workingNoder;const e=new Fl,n=new Pn;return n.setPrecisionModel(t),e.setSegmentIntersector(new Rf(n)),e}buffer(t,e){let n=this._workingPrecisionModel;n===null&&(n=t.getPrecisionModel()),this._geomFact=t.getFactory();const r=new kf(n,this._bufParams),o=new Jp(t,e,r).getCurves();if(o.size()<=0)return this.createEmptyResultGeometry();this.computeNodedEdges(o,n),this._graph=new Jo(new t0),this._graph.addEdges(this._edgeList.getEdges());const a=this.createSubgraphs(this._graph),l=new tc(this._geomFact);this.buildSubgraphs(a,l);const h=l.getPolygons();return h.size()<=0?this.createEmptyResultGeometry():this._geomFact.buildGeometry(h)}computeNodedEdges(t,e){const n=this.getNoder(e);n.computeNodes(t);const r=n.getNodedSubstrings();for(let s=r.iterator();s.hasNext();){const o=s.next(),a=o.getCoordinates();if(a.length===2&&a[0].equals2D(a[1]))continue;const l=o.getData(),h=new xr(o.getCoordinates(),new Ge(l));this.insertUniqueEdge(h)}}setNoder(t){this._workingNoder=t}}class Of{constructor(){Of.constructor_.apply(this,arguments)}static constructor_(){if(this._noder=null,this._scaleFactor=null,this._offsetX=null,this._offsetY=null,this._isScaled=!1,arguments.length===2){const t=arguments[0],e=arguments[1];Of.constructor_.call(this,t,e,0,0)}else if(arguments.length===4){const t=arguments[0],e=arguments[1];this._noder=t,this._scaleFactor=e,this._isScaled=!this.isIntegerPrecision()}}rescale(){if(At(arguments[0],on)){const t=arguments[0];for(let e=t.iterator();e.hasNext();){const n=e.next();this.rescale(n.getCoordinates())}}else if(arguments[0]instanceof Array){const t=arguments[0];for(let e=0;e<t.length;e++)t[e].x=t[e].x/this._scaleFactor+this._offsetX,t[e].y=t[e].y/this._scaleFactor+this._offsetY;t.length===2&&t[0].equals2D(t[1])&&pi.out.println(t)}}scale(){if(At(arguments[0],on)){const t=arguments[0],e=new wt(t.size());for(let n=t.iterator();n.hasNext();){const r=n.next();e.add(new ts(this.scale(r.getCoordinates()),r.getData()))}return e}else if(arguments[0]instanceof Array){const t=arguments[0],e=new Array(t.length).fill(null);for(let r=0;r<t.length;r++)e[r]=new Q(Math.round((t[r].x-this._offsetX)*this._scaleFactor),Math.round((t[r].y-this._offsetY)*this._scaleFactor),t[r].getZ());return Ce.removeRepeatedPoints(e)}}isIntegerPrecision(){return this._scaleFactor===1}getNodedSubstrings(){const t=this._noder.getNodedSubstrings();return this._isScaled&&this.rescale(t),t}computeNodes(t){let e=t;this._isScaled&&(e=this.scale(t)),this._noder.computeNodes(e)}get interfaces_(){return[Zp]}}class nc{constructor(){nc.constructor_.apply(this,arguments)}static constructor_(){this._li=new Pn,this._segStrings=null;const t=arguments[0];this._segStrings=t}checkEndPtVertexIntersections(){if(arguments.length===0)for(let t=this._segStrings.iterator();t.hasNext();){const n=t.next().getCoordinates();this.checkEndPtVertexIntersections(n[0],this._segStrings),this.checkEndPtVertexIntersections(n[n.length-1],this._segStrings)}else if(arguments.length===2){const t=arguments[0],e=arguments[1];for(let n=e.iterator();n.hasNext();){const s=n.next().getCoordinates();for(let o=1;o<s.length-1;o++)if(s[o].equals(t))throw new mi("found endpt/interior pt intersection at index "+o+" :pt "+t)}}}checkInteriorIntersections(){if(arguments.length===0)for(let t=this._segStrings.iterator();t.hasNext();){const e=t.next();for(let n=this._segStrings.iterator();n.hasNext();){const r=n.next();this.checkInteriorIntersections(e,r)}}else if(arguments.length===2){const t=arguments[0],e=arguments[1],n=t.getCoordinates(),r=e.getCoordinates();for(let s=0;s<n.length-1;s++)for(let o=0;o<r.length-1;o++)this.checkInteriorIntersections(t,s,e,o)}else if(arguments.length===4){const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3];if(t===n&&e===r)return null;const s=t.getCoordinates()[e],o=t.getCoordinates()[e+1],a=n.getCoordinates()[r],l=n.getCoordinates()[r+1];if(this._li.computeIntersection(s,o,a,l),this._li.hasIntersection()&&(this._li.isProper()||this.hasInteriorIntersection(this._li,s,o)||this.hasInteriorIntersection(this._li,a,l)))throw new mi("found non-noded intersection at "+s+"-"+o+" and "+a+"-"+l)}}checkValid(){this.checkEndPtVertexIntersections(),this.checkInteriorIntersections(),this.checkCollapses()}checkCollapses(){if(arguments.length===0)for(let t=this._segStrings.iterator();t.hasNext();){const e=t.next();this.checkCollapses(e)}else if(arguments.length===1){const e=arguments[0].getCoordinates();for(let n=0;n<e.length-2;n++)this.checkCollapse(e[n],e[n+1],e[n+2])}}hasInteriorIntersection(t,e,n){for(let r=0;r<t.getIntersectionNum();r++){const s=t.getIntersection(r);if(!(s.equals(e)||s.equals(n)))return!0}return!1}checkCollapse(t,e,n){if(t.equals(n))throw new mi("found non-noded collapse at "+nc.fact.createLineString([t,e,n]))}}nc.fact=new qe;class wl{constructor(){wl.constructor_.apply(this,arguments)}static constructor_(){this._li=null,this._pt=null,this._originalPt=null,this._ptScaled=null,this._p0Scaled=null,this._p1Scaled=null,this._scaleFactor=null,this._minx=null,this._maxx=null,this._miny=null,this._maxy=null,this._corner=new Array(4).fill(null),this._safeEnv=null;const t=arguments[0],e=arguments[1],n=arguments[2];if(this._originalPt=t,this._pt=t,this._scaleFactor=e,this._li=n,e<=0)throw new te("Scale factor must be non-zero");e!==1&&(this._pt=new Q(this.scale(t.x),this.scale(t.y)),this._p0Scaled=new Q,this._p1Scaled=new Q),this.initCorners(this._pt)}intersectsScaled(t,e){const n=Math.min(t.x,e.x),r=Math.max(t.x,e.x),s=Math.min(t.y,e.y),o=Math.max(t.y,e.y),a=this._maxx<n||this._minx>r||this._maxy<s||this._miny>o;if(a)return!1;const l=this.intersectsToleranceSquare(t,e);return Yt.isTrue(!(a&&l),"Found bad envelope test"),l}initCorners(t){this._minx=t.x-.5,this._maxx=t.x+.5,this._miny=t.y-.5,this._maxy=t.y+.5,this._corner[0]=new Q(this._maxx,this._maxy),this._corner[1]=new Q(this._minx,this._maxy),this._corner[2]=new Q(this._minx,this._miny),this._corner[3]=new Q(this._maxx,this._miny)}intersects(t,e){return this._scaleFactor===1?this.intersectsScaled(t,e):(this.copyScaled(t,this._p0Scaled),this.copyScaled(e,this._p1Scaled),this.intersectsScaled(this._p0Scaled,this._p1Scaled))}scale(t){return Math.round(t*this._scaleFactor)}getCoordinate(){return this._originalPt}copyScaled(t,e){e.x=this.scale(t.x),e.y=this.scale(t.y)}getSafeEnvelope(){if(this._safeEnv===null){const t=wl.SAFE_ENV_EXPANSION_FACTOR/this._scaleFactor;this._safeEnv=new ne(this._originalPt.x-t,this._originalPt.x+t,this._originalPt.y-t,this._originalPt.y+t)}return this._safeEnv}intersectsPixelClosure(t,e){return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.hasIntersection()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.hasIntersection())||(this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.hasIntersection())||(this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.hasIntersection()))}intersectsToleranceSquare(t,e){let n=!1,r=!1;return this._li.computeIntersection(t,e,this._corner[0],this._corner[1]),!!(this._li.isProper()||(this._li.computeIntersection(t,e,this._corner[1],this._corner[2]),this._li.isProper())||(this._li.hasIntersection()&&(n=!0),this._li.computeIntersection(t,e,this._corner[2],this._corner[3]),this._li.isProper())||(this._li.hasIntersection()&&(r=!0),this._li.computeIntersection(t,e,this._corner[3],this._corner[0]),this._li.isProper())||n&&r||t.equals(this._pt)||e.equals(this._pt))}addSnappedNode(t,e){const n=t.getCoordinate(e),r=t.getCoordinate(e+1);return this.intersects(n,r)?(t.addIntersection(this.getCoordinate(),e),!0):!1}}wl.SAFE_ENV_EXPANSION_FACTOR=.75;class o0{constructor(){o0.constructor_.apply(this,arguments)}static constructor_(){this.selectedSegment=new Me}select(){if(arguments.length!==1){if(arguments.length===2){const t=arguments[0],e=arguments[1];t.getLineSegment(e,this.selectedSegment),this.select(this.selectedSegment)}}}}class Cd{constructor(){Cd.constructor_.apply(this,arguments)}static constructor_(){this._index=null;const t=arguments[0];this._index=t}snap(){if(arguments.length===1){const t=arguments[0];return this.snap(t,null,-1)}else if(arguments.length===3){const t=arguments[0],e=arguments[1],n=arguments[2],r=t.getSafeEnvelope(),s=new Pd(t,e,n);return this._index.query(r,new class{get interfaces_(){return[wd]}visitItem(o){o.select(r,s)}}),s.isNodeAdded()}}}class Pd extends o0{constructor(){super(),Pd.constructor_.apply(this,arguments)}static constructor_(){this._hotPixel=null,this._parentEdge=null,this._hotPixelVertexIndex=null,this._isNodeAdded=!1;const t=arguments[0],e=arguments[1],n=arguments[2];this._hotPixel=t,this._parentEdge=e,this._hotPixelVertexIndex=n}isNodeAdded(){return this._isNodeAdded}select(){if(arguments.length===2&&Number.isInteger(arguments[1])&&arguments[0]instanceof Jx){const t=arguments[0],e=arguments[1],n=t.getContext();if(this._parentEdge===n&&(e===this._hotPixelVertexIndex||e+1===this._hotPixelVertexIndex))return null;this._isNodeAdded|=this._hotPixel.addSnappedNode(n,e)}else return super.select.apply(this,arguments)}}Cd.HotPixelSnapAction=Pd;class a0{constructor(){a0.constructor_.apply(this,arguments)}static constructor_(){this._li=null,this._interiorIntersections=null;const t=arguments[0];this._li=t,this._interiorIntersections=new wt}processIntersections(t,e,n,r){if(t===n&&e===r)return null;const s=t.getCoordinates()[e],o=t.getCoordinates()[e+1],a=n.getCoordinates()[r],l=n.getCoordinates()[r+1];if(this._li.computeIntersection(s,o,a,l),this._li.hasIntersection()&&this._li.isInteriorIntersection()){for(let h=0;h<this._li.getIntersectionNum();h++)this._interiorIntersections.add(this._li.getIntersection(h));t.addIntersections(this._li,e,0),n.addIntersections(this._li,r,1)}}isDone(){return!1}getInteriorIntersections(){return this._interiorIntersections}get interfaces_(){return[e0]}}class l0{constructor(){l0.constructor_.apply(this,arguments)}static constructor_(){this._pm=null,this._li=null,this._scaleFactor=null,this._noder=null,this._pointSnapper=null,this._nodedSegStrings=null;const t=arguments[0];this._pm=t,this._li=new Pn,this._li.setPrecisionModel(t),this._scaleFactor=t.getScale()}checkCorrectness(t){const e=ts.getNodedSubstrings(t),n=new nc(e);try{n.checkValid()}catch(r){if(r instanceof Tr)r.printStackTrace();else throw r}finally{}}getNodedSubstrings(){return ts.getNodedSubstrings(this._nodedSegStrings)}snapRound(t,e){const n=this.findInteriorIntersections(t,e);this.computeIntersectionSnaps(n),this.computeVertexSnaps(t)}findInteriorIntersections(t,e){const n=new a0(e);return this._noder.setSegmentIntersector(n),this._noder.computeNodes(t),n.getInteriorIntersections()}computeVertexSnaps(){if(At(arguments[0],on)){const t=arguments[0];for(let e=t.iterator();e.hasNext();){const n=e.next();this.computeVertexSnaps(n)}}else if(arguments[0]instanceof ts){const t=arguments[0],e=t.getCoordinates();for(let n=0;n<e.length;n++){const r=new wl(e[n],this._scaleFactor,this._li);this._pointSnapper.snap(r,t,n)&&t.addIntersection(e[n],n)}}}computeNodes(t){this._nodedSegStrings=t,this._noder=new Fl,this._pointSnapper=new Cd(this._noder.getIndex()),this.snapRound(t,this._li)}computeIntersectionSnaps(t){for(let e=t.iterator();e.hasNext();){const n=e.next(),r=new wl(n,this._scaleFactor,this._li);this._pointSnapper.snap(r)}}get interfaces_(){return[Zp]}}class wn{constructor(){wn.constructor_.apply(this,arguments)}static constructor_(){if(this._argGeom=null,this._distance=null,this._bufParams=new re,this._resultGeometry=null,this._saveException=null,arguments.length===1){const t=arguments[0];this._argGeom=t}else if(arguments.length===2){const t=arguments[0],e=arguments[1];this._argGeom=t,this._bufParams=e}}static bufferOp(){if(arguments.length===2){const t=arguments[0],e=arguments[1];return new wn(t).getResultGeometry(e)}else if(arguments.length===3){if(Number.isInteger(arguments[2])&&arguments[0]instanceof dt&&typeof arguments[1]=="number"){const t=arguments[0],e=arguments[1],n=arguments[2],r=new wn(t);return r.setQuadrantSegments(n),r.getResultGeometry(e)}else if(arguments[2]instanceof re&&arguments[0]instanceof dt&&typeof arguments[1]=="number"){const t=arguments[0],e=arguments[1],n=arguments[2];return new wn(t,n).getResultGeometry(e)}}else if(arguments.length===4){const t=arguments[0],e=arguments[1],n=arguments[2],r=arguments[3],s=new wn(t);return s.setQuadrantSegments(n),s.setEndCapStyle(r),s.getResultGeometry(e)}}static precisionScaleFactor(t,e,n){const r=t.getEnvelopeInternal(),s=Vo.max(Math.abs(r.getMaxX()),Math.abs(r.getMaxY()),Math.abs(r.getMinX()),Math.abs(r.getMinY())),o=e>0?e:0,a=s+2*o,l=Math.trunc(Math.log(a)/Math.log(10)+1),h=n-l;return Math.pow(10,h)}bufferFixedPrecision(t){const e=new Of(new l0(new we(1)),t.getScale()),n=new Ha(this._bufParams);n.setWorkingPrecisionModel(t),n.setNoder(e),this._resultGeometry=n.buffer(this._argGeom,this._distance)}bufferReducedPrecision(){if(arguments.length===0){for(let t=wn.MAX_PRECISION_DIGITS;t>=0;t--){try{this.bufferReducedPrecision(t)}catch(e){if(e instanceof Fi)this._saveException=e;else throw e}finally{}if(this._resultGeometry!==null)return null}throw this._saveException}else if(arguments.length===1){const t=arguments[0],e=wn.precisionScaleFactor(this._argGeom,this._distance,t),n=new we(e);this.bufferFixedPrecision(n)}}computeGeometry(){if(this.bufferOriginalPrecision(),this._resultGeometry!==null)return null;const t=this._argGeom.getFactory().getPrecisionModel();t.getType()===we.FIXED?this.bufferFixedPrecision(t):this.bufferReducedPrecision()}setQuadrantSegments(t){this._bufParams.setQuadrantSegments(t)}bufferOriginalPrecision(){try{const t=new Ha(this._bufParams);this._resultGeometry=t.buffer(this._argGeom,this._distance)}catch(t){if(t instanceof mi)this._saveException=t;else throw t}finally{}}getResultGeometry(t){return this._distance=t,this.computeGeometry(),this._resultGeometry}setEndCapStyle(t){this._bufParams.setEndCapStyle(t)}}wn.CAP_ROUND=re.CAP_ROUND;wn.CAP_BUTT=re.CAP_FLAT;wn.CAP_FLAT=re.CAP_FLAT;wn.CAP_SQUARE=re.CAP_SQUARE;wn.MAX_PRECISION_DIGITS=12;const ps=1e-9,eb=10;function ir(i,t){return[i[0]-t[0],i[1]-t[1]]}function Ss(i){return Math.hypot(i[0],i[1])}function Ka(i){const t=Ss(i);return t<ps?[0,0]:[i[0]/t,i[1]/t]}function o8(i,t,e,n){const r=t[0]*n[1]-t[1]*n[0];if(Math.abs(r)<ps)return null;const s=((e[0]-i[0])*n[1]-(e[1]-i[1])*n[0])/r;return[i[0]+s*t[0],i[1]+s*t[1]]}function vv(i){return i.filter((t,e)=>e===0||Ss(ir(t,i[e-1]))>ps)}function a8(i,t,e=eb){const n=vv(i);if(n.length<2)return n;const r=[];for(let o=0;o<n.length-1;o++){const a=Ka(ir(n[o+1],n[o])),l=[a[1],-a[0]],h=[l[0]*t,l[1]*t];r.push({dir:a,start:[n[o][0]+h[0],n[o][1]+h[1]],end:[n[o+1][0]+h[0],n[o+1][1]+h[1]]})}const s=[r[0].start];for(let o=0;o<r.length-1;o++){const a=r[o],l=r[o+1],h=o8(a.start,a.dir,l.start,l.dir);h?Ss(ir(h,n[o+1]))>Math.abs(t)*e?s.push(a.end,l.start):s.push(h):s.push(a.end)}return s.push(r[r.length-1].end),vv(s)}function nb(i,t,e=eb){const n=new _d,r=new zx,s=new re;s.setJoinStyle(re.JOIN_MITRE),s.setMitreLimit(e);const o=wn.bufferOp(n.read(i),t,s);if(!o||o.isEmpty())return null;const a=r.write(o);return a.type!=="Polygon"&&a.type!=="MultiPolygon"?null:a}function ib(i,t,e,n,r=5){const s=ir(i,t),o=ir(e,t),a=Ss(s),l=Ss(o);if(n<=0||a<ps||l<ps)return null;const h=Ka(s),f=Ka(o),d=Math.max(-1,Math.min(1,h[0]*f[0]+h[1]*f[1])),p=Math.acos(d);if(p<1e-6||Math.PI-p<1e-6)return null;const y=n/Math.tan(p/2);if(y>a+ps||y>l+ps)return null;const _=[t[0]+h[0]*y,t[1]+h[1]*y],E=[t[0]+f[0]*y,t[1]+f[1]*y],w=Ka([h[0]+f[0],h[1]+f[1]]),L=n/Math.sin(p/2),b=[t[0]+w[0]*L,t[1]+w[1]*L],S=Math.atan2(_[1]-b[1],_[0]-b[0]);let N=Math.atan2(E[1]-b[1],E[0]-b[0])-S;for(;N>Math.PI;)N-=2*Math.PI;for(;N<-Math.PI;)N+=2*Math.PI;const C=Math.max(2,Math.ceil(Math.abs(N)/(r*Math.PI/180))),T=[_];for(let I=1;I<C;I++){const M=S+N*I/C;T.push([b[0]+n*Math.cos(M),b[1]+n*Math.sin(M)])}return T.push(E),{tangentStart:_,tangentEnd:E,center:b,points:T}}function l8(i,t,e){const n=Ss(ir(i,t)),r=Ss(ir(e,t)),s=Ka(ir(i,t)),o=Ka(ir(e,t)),a=Math.acos(Math.max(-1,Math.min(1,s[0]*o[0]+s[1]*o[1])));return a<1e-6||Math.PI-a<1e-6?0:Math.min(n,r)*Math.tan(a/2)}function u8(i,t,e){const n=-e*Math.PI/180,r=Math.cos(n),s=Math.sin(n),o=i[0]-t[0],a=i[1]-t[1];return[t[0]+o*r-a*s,t[1]+o*s+a*r]}function c8(i,t,e){return[t[0]+(i[0]-t[0])*e,t[1]+(i[1]-t[1])*e]}function h8(i,t,e){const n=ir(e,t),r=Ss(n);return r<ps?Ss(ir(i,t)):Math.abs(n[0]*(t[1]-i[1])-n[1]*(t[0]-i[0]))/r}function f8(i,t,e){const n=ir(e,t),r=n[0]*n[0]+n[1]*n[1];return r<ps?0:((i[0]-t[0])*n[0]+(i[1]-t[1])*n[1])/r}const Fm=.001;function ou(i,t,e){const n=Ue(i);return Cn(n,r=>{const s=t.toGeographic(e(t.toPlanar(r)));r[0]=s[0],r[1]=s[1]}),n}class ce{static splitSinglePolygonByLine(t,e){try{const n=ll(t);if(n){const r=Zo(e,n);if(r.features.length>=2){const s=[];for(const o of r.features){const a=o.geometry.coordinates;s.some(h=>{const f=h.geometry.coordinates;return Math.hypot(a[0]-f[0],a[1]-f[1])<1e-7})||s.push(o)}if(s.length>=2){let o=wh(n).features;for(const h of s){const f=[];for(const d of o){const p=_u(d,h);p&&p.features.length>0?f.push(...p.features):f.push(d)}o=f}let a=[e];for(const h of s){const f=[];for(const d of a){const p=_u(d,h);p&&p.features.length>0?f.push(...p.features):f.push(d)}a=f}const l=a.filter(h=>{const f=h.geometry.coordinates;if(f.length<2)return!1;const d=eT(h,dl(h)/2),p=r4(Lt(f[0]),Lt(f[f.length-1]));return Zt(d,t)||Zt(p,t)});if(l.length>0){const h=[...o,...l].filter(p=>dl(p,{units:"meters"})>=1e-4),f=le(h),d=E4(f);if(d.features.length>=2){const p=d.features.filter(y=>{ja(y);const _=h4(y);return(Zt(_,t)||Zt(Us(y),t))&&Xu(y)>.01});if(p.length>=2)return p}}}}}}catch{}try{const n=Gw(e,5e-5,{units:"meters"});if(!n)return null;const r=Oa(le([t,n]));if(!r)return null;const s=wh(r);return s.features.length<=1?null:s.features.map(o=>(ja(o),o))}catch{return null}}static splitPolygonByLine(t,e){try{if(e.geometry.coordinates.length<2)return null;const n=e;let r=[];t.geometry.type==="MultiPolygon"?r=wh(t).features:r=[t];const s=[];for(const o of r){const a=this.splitSinglePolygonByLine(o,n);a&&a.length>1?s.push(...a):s.push(o)}return s.length<=r.length?null:s.map(o=>this.cleanCollinearVertices(o))}catch(n){return console.error("splitPolygonByLine error:",n),null}}static connectLines(t,e=5,n=!0){if(t.length===0)return null;if(t.length===1)return t[0];const r=[...t],s=r.shift();let o=[...s.geometry.coordinates];for(;r.length>0;){const l=o[0],h=o[o.length-1];let f=-1,d=!1,p=!1;for(let E=0;E<r.length;E++){const w=r[E].geometry.coordinates,L=w[0],b=w[w.length-1];if(sn(Lt(h),Lt(L),{units:"meters"})<=e){f=E,d=!1,p=!1;break}if(sn(Lt(h),Lt(b),{units:"meters"})<=e){f=E,d=!0,p=!1;break}}if(f===-1)for(let E=0;E<r.length;E++){const w=r[E].geometry.coordinates,L=w[0],b=w[w.length-1];if(sn(Lt(b),Lt(l),{units:"meters"})<=e){f=E,d=!1,p=!0;break}if(sn(Lt(L),Lt(l),{units:"meters"})<=e){f=E,d=!0,p=!0;break}}if(f===-1)break;let _=[...r.splice(f,1)[0].geometry.coordinates];if(d&&_.reverse(),p){const E=_[_.length-1];sn(Lt(E),Lt(l),{units:"meters"})<=e&&_.pop(),o=[..._,...o]}else{const E=_[0];sn(Lt(h),Lt(E),{units:"meters"})<=e&&_.shift(),o=[...o,..._]}}return ae(o,s.properties)}static smoothLineBezier(t,e=32){const n=t.geometry.coordinates;if(n.length<3)return t;const r=TE(n,e);return ae(r,t.properties)}static extendLine(t,e=.05){const n=t.geometry.coordinates;if(n.length<2)return t;const r=n[0],s=n[n.length-1],o=al(Lt(n[n.length-2]),Lt(s)),a=al(Lt(n[1]),Lt(r)),l=ju(Lt(r),e,a).geometry.coordinates,h=ju(Lt(s),e,o).geometry.coordinates;return ae([l,...n,h])}static offset(t,e){if(!Number.isFinite(e)||e===0)return null;const n=me.forGeometries([t.geometry]);if(t.geometry.type==="LineString"){const r=t.geometry.coordinates.map(o=>n.toPlanar(o)),s=a8(r,e);return s.length<2?null:ae(s.map(o=>n.toGeographic(o)),t.properties)}if(t.geometry.type==="Polygon"){const r=nb(n.projectGeometry(t.geometry),e);return r?xn(n.unprojectGeometry(r),t.properties):null}return null}static rotate(t,e,n){const r=n||Us(t).geometry.coordinates,s=me.forCoordinate(r),o=s.toPlanar(r);return ou(t,s,a=>u8(a,o,e))}static scale(t,e,n){const r=n||Us(t).geometry.coordinates,s=me.forCoordinate(r),o=s.toPlanar(r);return ou(t,s,a=>c8(a,o,e))}static explode(t){const e=[];return t.geometry.type==="Polygon"?t.geometry.coordinates.forEach((n,r)=>{var s;e.push(ae(n,{...t.properties,ringIndex:r,name:`${((s=t.properties)==null?void 0:s.name)||"Polygon"} Ring ${r+1}`}))}):t.geometry.type==="MultiPolygon"&&t.geometry.coordinates.forEach((n,r)=>{n.forEach((s,o)=>{var a;e.push(ae(s,{...t.properties,polygonIndex:r,ringIndex:o,name:`${((a=t.properties)==null?void 0:a.name)||"Polygon"} ${r+1}.${o+1}`}))})}),e}static fillet(t,e,n=5){const r=this.getFilletCorner(t,e);if(!r)return null;const{coords:s,prev:o,curr:a,next:l,isPolygon:h,projection:f}=r,d=ib(f.toPlanar(o),f.toPlanar(a),f.toPlanar(l),n);if(!d)return null;const p=d.points.map(_=>f.toGeographic(_));if(h){const _=s.slice(0,-1);_.splice(e,1,...p),_.push(_[0]);const E=t.geometry.coordinates.slice(1);return Pe([_,...E],t.properties)}const y=[...s];return y.splice(e,1,...p),ae(y,t.properties)}static maxFilletRadius(t,e){const n=this.getFilletCorner(t,e);if(!n)return 0;const{prev:r,curr:s,next:o,projection:a}=n;return l8(a.toPlanar(r),a.toPlanar(s),a.toPlanar(o))}static getFilletCorner(t,e){const n=t.geometry.type==="Polygon";if(!n&&t.geometry.type!=="LineString")return null;const r=n?[...t.geometry.coordinates[0]]:[...t.geometry.coordinates],s=n?r.length-1:r.length;if(s<3||!Number.isInteger(e)||(n?e<0||e>=s:e<1||e>s-2))return null;const o=r[n?(e-1+s)%s:e-1],a=r[e],l=r[n?(e+1)%s:e+1],h=me.forCoordinate(a);return{coords:r,prev:o,curr:a,next:l,isPolygon:n,projection:h}}static translate(t,e,n){const r=n*Math.PI/180;return this.translateByMeters(t,e*Math.sin(r),e*Math.cos(r))}static translateByMeters(t,e,n){const r=me.forGeometries([t.geometry]);return ou(t,r,s=>[s[0]+e,s[1]+n])}static translateByVector(t,e,n){const r=me.forCoordinate(e),s=me.forCoordinate(n),o=r.toPlanar(e),a=s.toPlanar(n),l=Ue(t);return Cn(l,h=>{const f=r.toPlanar(h),d=s.toGeographic([a[0]+(f[0]-o[0]),a[1]+(f[1]-o[1])]);h[0]=d[0],h[1]=d[1]}),l}static align(t,e,n,r,s,o=!1){const a=me.forCoordinate(n),l=a.toPlanar(e),h=a.toPlanar(n);let f=0,d=1;if(r&&s){const _=a.toPlanar(r),E=a.toPlanar(s),w=Math.hypot(_[0]-l[0],_[1]-l[1]),L=Math.hypot(E[0]-h[0],E[1]-h[1]);if(w<1e-9||L<1e-9)throw new Error("Alignment points must be different.");f=Math.atan2(E[1]-h[1],E[0]-h[0])-Math.atan2(_[1]-l[1],_[0]-l[0]),o&&(d=L/w)}const p=Math.cos(f)*d,y=Math.sin(f)*d;return ou(t,a,_=>{const E=_[0]-l[0],w=_[1]-l[1];return[h[0]+E*p-w*y,h[1]+E*y+w*p]})}static mirror(t,e,n){const r=me.forCoordinate(e),s=r.toPlanar(e),o=r.toPlanar(n),a=o[0]-s[0],l=o[1]-s[1],h=a*a+l*l;if(h<1e-12)throw new Error("Mirror line needs two different points");const f=ou(t,r,y=>{const _=((y[0]-s[0])*a+(y[1]-s[1])*l)/h,E=s[0]+_*a,w=s[1]+_*l;return[2*E-y[0],2*w-y[1]]}),d=y=>y.forEach(_=>_.reverse()),p=f.geometry;return p.type==="Polygon"&&d(p.coordinates),p.type==="MultiPolygon"&&p.coordinates.forEach(d),f}static translateByOffset(t,e,n){const r=Ue(t);return Cn(r,s=>{s[0]+=e,s[1]+=n}),r}static difference(t,e){try{return Oa(le([t,e]))}catch(n){return console.error("CADOperations.difference error:",n),null}}static intersect(t,e){try{return xf(le([t,e]))}catch(n){return console.error("CADOperations.intersect error:",n),null}}static simplify(t,e=1e-4){return S4(t,{tolerance:e,highQuality:!0,mutate:!1})}static reverse(t){const e=Ue(t);return e.geometry.type==="LineString"?e.geometry.coordinates.reverse():e.geometry.type==="Polygon"&&e.geometry.coordinates.forEach(r=>{const s=r.slice(0,-1).reverse();s.push(s[0]);for(let o=0;o<r.length;o++)r[o]=s[o]}),e}static cloneFeature(t,e){const n=Ue(t);return e!==void 0&&(n.id=e),n}static snapVertices(t,e=Fm){if(t.length<2||!(e>0))return t.map(o=>Ue(o));const n=me.forGeometries(t.map(o=>o.geometry)),r=(o,a)=>`${Math.floor(o/e)}:${Math.floor(a/e)}`,s=new Map;return t.map(o=>{const a=Ue(o),l=[];return Cn(a,h=>{const f=n.toPlanar(h),d=Math.floor(f[0]/e),p=Math.floor(f[1]/e);let y=null,_=e;for(let E=-1;E<=1;E++)for(let w=-1;w<=1;w++)for(const L of s.get(`${d+E}:${p+w}`)||[]){const b=Math.hypot(L.planar[0]-f[0],L.planar[1]-f[1]);b<=_&&(_=b,y=L.coord)}y?(h[0]=y[0],h[1]=y[1]):l.push({planar:f,coord:[h[0],h[1]]})}),l.forEach(h=>{const f=r(h.planar[0],h.planar[1]),d=s.get(f);d?d.push(h):s.set(f,[h])}),a})}static cleanCollinearVertices(t,e=Fm){const n=Ue(t),r=me.forGeometries([t.geometry]),s=o=>{if(o.length<=4)return o;const a=o.slice(0,-1).map(f=>({coord:f,planar:r.toPlanar(f)}));let l=!0;for(;l&&a.length>3;){l=!1;for(let f=0;f<a.length&&a.length>3;f++){const d=a[(f-1+a.length)%a.length].planar,p=a[f].planar,y=a[(f+1)%a.length].planar,_=f8(p,d,y);_>0&&_<1&&h8(p,d,y)<=e&&(a.splice(f,1),f--,l=!0)}}const h=a.map(f=>f.coord);return h.push(h[0]),h};if(n.geometry.type==="Polygon"){const o=n.geometry.coordinates;n.geometry.coordinates=o.map(s)}else if(n.geometry.type==="MultiPolygon"){const o=n.geometry.coordinates;n.geometry.coordinates=o.map(a=>a.map(s))}return n}static splitOverlappingPolygons(t,e){try{if(!Yo(t,e))return null;const r=xf(le([t,e]));if(!r)return null;const s=Oa(le([t,e])),o=Oa(le([e,t])),a=d=>{if(!d)return[];const p=wh(d),y=[];for(const _ of p.features)ja(_),_.geometry&&_.geometry.type==="Polygon"&&y.push(_);return y},l=a(s),h=a(r),f=a(o);return{pieceA:l,overlap:h,pieceB:f}}catch(n){return console.error("splitOverlappingPolygons error:",n),null}}static splitLine(t,e){try{let n;if(Array.isArray(e)?n=Lt(e):n=e,n.geometry.type==="Point"){const r=vw(t,n),s=t.geometry.coordinates,o=s[0],a=s[s.length-1],l=sn(Lt(o),r,{units:"meters"}),h=sn(Lt(a),r,{units:"meters"});if(l<.5||h<.5)return null;const f=_u(t,r);if(f&&f.features.length>1)return f.features}else if(n.geometry.type==="LineString"){const r=_u(t,n);if(r&&r.features.length>1)return r.features}return null}catch(n){return console.error("splitLine error:",n),null}}}class rb extends no{constructor(){super();q(this,"layers",new Map);q(this,"tileLayers",new Map);q(this,"groups",new Map);q(this,"activeLayerId",null);q(this,"selectionStore",new Map);q(this,"transactions",new ix(50));q(this,"pendingChangedLayers",null)}emit(e,n){if(e==="features:changed"&&this.pendingChangedLayers){this.pendingChangedLayers.add(n.layerId);return}super.emit(e,n)}runTransaction(e,n){return this.withCoalescedEvents(()=>{this.transactions.beginGroup(e);try{const r=n();return this.transactions.commitGroup(),r}catch(r){throw this.transactions.rollbackGroup(),r}})}withCoalescedEvents(e){const n=this.pendingChangedLayers===null;n&&(this.pendingChangedLayers=new Set);try{return e()}finally{if(n){const r=this.pendingChangedLayers;this.pendingChangedLayers=null,r.forEach(s=>this.emit("features:changed",{layerId:s}))}}}addLayer(e,n=[]){if(e.color!==void 0&&!Vt.valid(e.color))throw new Xt(`Layer "${e.id}": "${e.color}" is not a colour.`);this.layers.has(e.id)&&(console.warn(`Layer with id "${e.id}" already exists. Replacing it.`),this.detachLayer(e.id,!0));const r=new dd(e,n);return this.layers.set(r.id,r),this.activeLayerId===null&&this.setActiveLayer(r.id),this.emit("layer:added",{layer:r}),r}removeLayer(e){return this.detachLayer(e,!1)}detachLayer(e,n){const r=this.layers.get(e);if(!r)return!1;if(r.pinned)return console.warn(`Layer "${e}" is pinned and cannot be removed.`),!1;if(this.layers.delete(e),this.selectionStore.delete(e),this.activeLayerId===e){const s=Array.from(this.layers.keys());this.setActiveLayer(s.length>0?s[0]:null)}return this.emit("layer:removed",{layerId:e,replaced:n}),!0}getLayer(e){return this.layers.get(e)}hasLayer(e){return this.layers.has(e)}getAllLayers(){return Array.from(this.layers.values()).sort((e,n)=>e.zIndex-n.zIndex)}addTileLayer(e){if(this.layers.has(e.id))throw new Xt(`"${e.id}" is already a feature layer. Tile layers and feature layers share one set of ids.`);this.tileLayers.has(e.id)&&(console.warn(`Tile layer with id "${e.id}" already exists. Replacing it.`),this.removeTileLayer(e.id));const n=new km(e);return this.tileLayers.set(n.id,n),this.emit("tile-layer:added",{layer:n}),n}getTileLayer(e){return this.tileLayers.get(e)}getTileLayers(){return Array.from(this.tileLayers.values()).sort((e,n)=>e.zIndex-n.zIndex)}removeTileLayer(e){const n=this.tileLayers.get(e);return n?n.pinned?(console.warn(`Tile layer "${e}" is pinned and cannot be removed.`),!1):(this.tileLayers.delete(e),this.emit("tile-layer:removed",{layerId:e}),!0):!1}setTileLayerStyles(e,n){const r=this.tileLayers.get(e);if(!r)throw new Xt(`Tile layer "${e}" not found`);if(r.kind!=="vector")throw new Xt(`"${e}" is a raster tile layer; only vector tiles are styled this way.`);r.styles=[...n],this.emit("tile-layer:updated",{layer:r})}getDisplayLayers(){return[...this.layers.values(),...this.tileLayers.values()].sort((e,n)=>e.zIndex-n.zIndex)}findAnyLayer(e){return this.layers.get(e)??this.tileLayers.get(e)}emitLayerChanged(e){e instanceof km?this.emit("tile-layer:updated",{layer:e}):this.emit("layer:updated",{layer:e})}setLayerVisibility(e,n){const r=this.findAnyLayer(e)??this.getLayerOrThrow(e);r.visible!==n&&(r.visible=n,this.emitLayerChanged(r))}setLayerOpacity(e,n){const r=this.findAnyLayer(e)??this.getLayerOrThrow(e),s=Math.max(0,Math.min(1,n));r.opacity!==s&&(r.opacity=s,this.emitLayerChanged(r))}setLayerZIndex(e,n){const r=this.findAnyLayer(e)??this.getLayerOrThrow(e);r.zIndex!==n&&(r.zIndex=n,this.emitLayerChanged(r))}reorderLayers(e){e.forEach((n,r)=>{const s=this.findAnyLayer(n);s&&(s.zIndex=r)}),this.getDisplayLayers().forEach(n=>this.emitLayerChanged(n))}setLayerPinned(e,n){const r=this.findAnyLayer(e)??this.getLayerOrThrow(e);r.pinned!==n&&(r.pinned=n,this.emitLayerChanged(r))}addLayerGroup(e){if(this.groups.has(e.id))throw new Error(`Layer group "${e.id}" already exists`);const n=e.parentId??null;if(n!==null&&!this.groups.has(n))throw new Error(`Layer group "${n}" not found`);const r={id:e.id,name:e.name??e.id,parentId:n,visible:e.visible??!0,expanded:e.expanded??!0};return this.groups.set(r.id,r),this.emit("group:added",{group:r}),r}getLayerGroup(e){return this.groups.get(e)}getLayerGroups(){return Array.from(this.groups.values())}removeLayerGroup(e){const n=this.groups.get(e);n&&(this.layers.forEach(r=>{r.groupId===e&&(r.groupId=n.parentId??void 0)}),this.groups.forEach(r=>{r.parentId===e&&(r.parentId=n.parentId)}),this.groups.delete(e),this.emit("group:removed",{groupId:e}),this.getAllLayers().forEach(r=>this.emit("layer:updated",{layer:r})))}updateLayerGroup(e,n){var o;const r=this.groups.get(e);if(!r)throw new Error(`Layer group "${e}" not found`);if(n.parentId!==void 0&&n.parentId!==null){if(!this.groups.has(n.parentId))throw new Error(`Layer group "${n.parentId}" not found`);for(let a=n.parentId;a;a=((o=this.groups.get(a))==null?void 0:o.parentId)??null)if(a===e)throw new Error(`Layer group "${e}" cannot be moved into itself`)}const s=n.visible!==void 0&&n.visible!==r.visible;Object.assign(r,Object.fromEntries(Object.entries(n).filter(([,a])=>a!==void 0))),this.emit("group:updated",{group:r}),(s||n.parentId!==void 0)&&this.getAllLayers().filter(a=>this.isLayerInGroup(a.id,e)).forEach(a=>this.emit("layer:updated",{layer:a}))}setLayerGroupVisibility(e,n){this.updateLayerGroup(e,{visible:n})}moveLayerToGroup(e,n){const r=this.findAnyLayer(e)??this.getLayerOrThrow(e);if(n!==null&&!this.groups.has(n))throw new Error(`Layer group "${n}" not found`);const s=n??void 0;r.groupId!==s&&(r.groupId=s,this.emitLayerChanged(r))}isLayerInGroup(e,n){var s,o;let r=((s=this.findAnyLayer(e))==null?void 0:s.groupId)??null;for(;r;){if(r===n)return!0;r=((o=this.groups.get(r))==null?void 0:o.parentId)??null}return!1}isLayerRendered(e){const n=this.findAnyLayer(e);if(!n||!n.visible)return!1;let r=n.groupId??null;for(;r;){const s=this.groups.get(r);if(!s)break;if(!s.visible)return!1;r=s.parentId}return!0}setActiveLayer(e){if(e!==null&&!this.layers.has(e))throw new um(e);this.activeLayerId!==e&&(this.activeLayerId=e,this.emit("active-layer:changed",{layerId:e}))}getActiveLayerId(){return this.activeLayerId}getActiveLayer(){return this.activeLayerId&&this.layers.get(this.activeLayerId)||null}selectFeature(e,n,r=!1){this.selectionStore.has(e)||this.selectionStore.set(e,new Set);const s=this.selectionStore.get(e);if(!r){for(const[o,a]of this.selectionStore.entries())o!==e&&a.size>0&&(a.clear(),this.emit("selection:changed",{layerId:o,featureIds:[]}));s.clear()}s.add(n),this.emit("selection:changed",{layerId:e,featureIds:Array.from(s)})}deselectFeature(e,n){const r=this.selectionStore.get(e);r&&r.delete(n)&&this.emit("selection:changed",{layerId:e,featureIds:Array.from(r)})}toggleFeatureSelection(e,n){const r=this.selectionStore.get(e);return r&&r.has(n)?(this.deselectFeature(e,n),!1):(this.selectFeature(e,n,!0),!0)}selectFeatures(e,n,r=!1){this.selectionStore.has(e)||this.selectionStore.set(e,new Set);const s=this.selectionStore.get(e);if(!r){for(const[o,a]of this.selectionStore.entries())o!==e&&a.size>0&&(a.clear(),this.emit("selection:changed",{layerId:o,featureIds:[]}));s.clear()}n.forEach(o=>s.add(o)),this.emit("selection:changed",{layerId:e,featureIds:Array.from(s)})}getSelectedCount(){let e=0;for(const n of this.selectionStore.values())e+=n.size;return e}clearSelection(e){if(e){const n=this.selectionStore.get(e);n&&n.size>0&&(n.clear(),this.emit("selection:changed",{layerId:e,featureIds:[]}))}else for(const[n,r]of this.selectionStore.entries())r.size>0&&(r.clear(),this.emit("selection:changed",{layerId:n,featureIds:[]}))}deselectAll(e){this.clearSelection(e)}getSelectedFeatureIds(e){return Array.from(this.selectionStore.get(e)||[])}getSelectedFeatures(e){const n=this.layers.get(e);if(!n)return[];const r=this.selectionStore.get(e);return!r||r.size===0?[]:Array.from(r).map(s=>n.getFeature(s)).filter(s=>!!s)}getAnySelectedFeature(){if(this.activeLayerId){const e=this.getSelectedFeatureIds(this.activeLayerId);if(e.length>0)return{layerId:this.activeLayerId,featureId:e[0]}}for(const[e,n]of this.selectionStore.entries())if(n.size>0){const r=n.values().next().value;if(r!==void 0)return{layerId:e,featureId:r}}return null}getAnySelectedFeatures(){if(this.activeLayerId){const e=this.getSelectedFeatureIds(this.activeLayerId);if(e.length>0)return{layerId:this.activeLayerId,featureIds:e}}for(const[e,n]of this.selectionStore.entries())if(n.size>0)return{layerId:e,featureIds:Array.from(n)};return null}addFeature(e,n,r=!0){const s=this.getLayerOrThrow(e),o=s.addFeature(n);if(r&&o.id!==void 0){const a=o.id;this.transactions.record({description:`Add feature to ${s.name}`,undo:()=>{this.removeFeature(e,a,!1)},redo:()=>{this.addFeature(e,o,!1)}})}return this.emit("feature:added",{layerId:e,feature:o}),this.emit("features:changed",{layerId:e}),o}addFeatures(e,n,r=!0){const s=this.getLayerOrThrow(e),o=s.addFeatures(n);if(r){const a=o.map(l=>l.id).filter(l=>l!==void 0);this.transactions.record({description:`Add ${o.length} features to ${s.name}`,undo:()=>{a.forEach(l=>s.removeFeature(l)),this.emit("features:changed",{layerId:e})},redo:()=>{s.addFeatures(o),this.emit("features:changed",{layerId:e})}})}return o.forEach(a=>this.emit("feature:added",{layerId:e,feature:a})),this.emit("features:changed",{layerId:e}),o}updateFeature(e,n,r=!0){const s=this.getLayerOrThrow(e);if(n.id===void 0||n.id===null)return!1;const o=s.getFeature(n.id);if(!o)return!1;const a=Ue(o),l=s.updateFeature(n);return l&&(r&&this.transactions.record({description:`Update feature ${n.id} in ${s.name}`,undo:()=>{this.updateFeature(e,a,!1)},redo:()=>{this.updateFeature(e,n,!1)}}),this.emit("feature:updated",{layerId:e,feature:n}),this.emit("features:changed",{layerId:e})),l}updateFeatureProperties(e,n,r,s=!0){const o=this.getLayerOrThrow(e),a=this.propertiesBefore(o,n,r);if(!a)return!1;const l=o.updateProperties(n,r);return l?(s&&this.transactions.record({description:`Edit attributes of feature ${n} in ${o.name}`,undo:()=>{this.updateFeatureProperties(e,n,a,!1)},redo:()=>{this.updateFeatureProperties(e,n,r,!1)}}),this.emit("feature:updated",{layerId:e,feature:l}),this.emit("features:changed",{layerId:e}),!0):!1}updateFeaturePropertiesBatch(e,n,r=!0,s){const o=this.getLayerOrThrow(e),a=[],l=[];return this.withCoalescedEvents(()=>{for(const{featureId:h,patch:f}of n){const d=this.propertiesBefore(o,h,f);d&&o.updateProperties(h,f)&&(a.push({featureId:h,patch:d}),l.push({featureId:h,patch:f}),this.emit("feature:updated",{layerId:e,feature:o.getFeature(h)}))}l.length&&this.emit("features:changed",{layerId:e})}),r&&l.length&&this.transactions.record({description:s??`Edit attributes of ${l.length} features in ${o.name}`,undo:()=>{this.updateFeaturePropertiesBatch(e,a,!1)},redo:()=>{this.updateFeaturePropertiesBatch(e,l,!1)}}),l.length}propertiesBefore(e,n,r){const s=e.getFeature(n);if(!s)return null;const o={};let a=!1;for(const[l,h]of Object.entries(r)){const f=!!s.properties&&Object.prototype.hasOwnProperty.call(s.properties,l),d=f?s.properties[l]:void 0;f&&d===h||!f&&h===void 0||(o[l]=d,a=!0)}return a?o:null}removeFeature(e,n,r=!0){const s=this.getLayerOrThrow(e),o=s.getFeature(n);if(!o)return!1;const a=Ue(o),l=s.removeFeature(n);return l&&(this.deselectFeature(e,n),r&&this.transactions.record({description:`Delete feature ${n} from ${s.name}`,undo:()=>{this.addFeature(e,a,!1)},redo:()=>{this.removeFeature(e,n,!1)}}),this.emit("feature:removed",{layerId:e,featureId:n}),this.emit("features:changed",{layerId:e})),l}getAvailableFeatureId(e,n){return this.getLayerOrThrow(e).getAvailableId(n)}getFeature(e,n){var r;return(r=this.layers.get(e))==null?void 0:r.getFeature(n)}buffer(e,n,r,s="meters",o){const a=this.getLayerOrThrow(e),l=a.getFeature(n);if(!l)throw new cm(n,e);const h=Gw(l,r,{units:s});h.properties={...l.properties,_bufferDistance:r,_bufferUnit:s};let f=o;if(f){const d=this.getLayerOrThrow(f);if(d.type!=="polygon")throw new Xt(`A buffer is a polygon; layer "${d.name}" is a ${d.type} layer and would not draw it.`)}else f=a.type==="polygon"?e:this.bufferLayerFor(a).id;return this.addFeature(f,h)}bufferLayerFor(e){let n=`${e.id}_buffer`;for(let r=2;this.layers.has(n)&&this.layers.get(n).type!=="polygon";r++)n=`${e.id}_buffer_${r}`;return this.layers.get(n)??this.addLayer({id:n,name:`${e.name} (buffer)`,type:"polygon",groupId:e.groupId})}calculateArea(e,n,r="sqm"){const s=this.getFeatureOrThrow(e,n),o=Xu(s);return r==="hectares"?o/1e4:r==="rai"?o/1600:o}calculateLength(e,n,r="meters"){const s=this.getFeatureOrThrow(e,n);return dl(s,{units:r})}union(e,n,r={}){const s=this.getLayerOrThrow(e),o=n.map(f=>s.getFeature(f)).filter(f=>!!(f&&(f.geometry.type==="Polygon"||f.geometry.type==="MultiPolygon")));if(o.length<2)throw new Rh("Union requires at least 2 polygon features");const a=ce.snapVertices(o,r.snapToleranceMeters),l=nx(le(a));if(!l)throw new Rh("Union produced an empty geometry");const h=ce.cleanCollinearVertices(l);return h.properties={...o[0].properties||{}},delete h.id,this.runTransaction(`Union ${o.length} polygons in ${s.name}`,()=>{o.forEach(d=>this.removeFeature(e,d.id));const f=this.addFeature(e,h);return f.id!==void 0&&this.selectFeature(e,f.id,!1),f})}splitOverlapping(e,n,r){const s=this.getLayerOrThrow(e),o=s.getFeature(n),a=s.getFeature(r);if(!o||!a)return null;const l=ce.splitOverlappingPolygons(o,a);return l?(this.runTransaction(`Split overlapping polygons ${n} and ${r} in ${s.name}`,()=>{this.removeFeature(e,n),this.removeFeature(e,r),l.pieceA.forEach((h,f)=>{h.id=this.getAvailableFeatureId(e,`${n}_part_${f+1}`),h.properties={...o.properties||{},_split:"A_minus_B"},this.addFeature(e,h)}),l.overlap.forEach((h,f)=>{var d,p;h.id=this.getAvailableFeatureId(e,`overlap_${n}_${r}_${f+1}`),h.properties={name:`Overlap (${((d=o.properties)==null?void 0:d.name)||n} & ${((p=a.properties)==null?void 0:p.name)||r})`,_split:"overlap"},this.addFeature(e,h)}),l.pieceB.forEach((h,f)=>{h.id=this.getAvailableFeatureId(e,`${r}_part_${f+1}`),h.properties={...a.properties||{},_split:"B_minus_A"},this.addFeature(e,h)})}),l):null}difference(e,n,r){const s=this.getLayerOrThrow(e),o=s.getFeature(n),a=s.getFeature(r);if(!o||!a)throw new Rh("Base and cut polygon features required");const l=Oa(le([o,a]));return l&&(l.id=n,l.properties={...o.properties},this.updateFeature(e,l)),l}getBoundingBox(e){if(e)return this.getLayerOrThrow(e).getBoundingBox();const n=this.getAllLayers();if(n.length===0)return[0,0,0,0];const r={type:"FeatureCollection",features:n.flatMap(s=>s.getFeatures())};return r.features.length===0?[0,0,0,0]:je(r)}undo(){const e=this.withCoalescedEvents(()=>this.transactions.undo());return e&&this.emit("transaction:undo",{description:e}),e}redo(){const e=this.withCoalescedEvents(()=>this.transactions.redo());return e&&this.emit("transaction:redo",{description:e}),e}canUndo(){return this.transactions.canUndo()}canRedo(){return this.transactions.canRedo()}getLayerOrThrow(e){const n=this.layers.get(e);if(!n)throw new um(e);return n}getFeatureOrThrow(e,n){const s=this.getLayerOrThrow(e).getFeature(n);if(!s)throw new cm(n,e);return s}}const tn=1e-9,Qi=Math.PI*2,Ms=.05,sb=2048,d8=1e-7,g8=1e3;function Qn(i,t){return[i[0]-t[0],i[1]-t[1]]}function ti(i){return Math.hypot(i[0],i[1])}function u0(i){const t=ti(i);return t<tn?[0,0]:[i[0]/t,i[1]/t]}function m8(i,t){return i[0]*t[0]+i[1]*t[1]}function $m(i,t){return i[0]*t[1]-i[1]*t[0]}function c0(i){return[-i[1],i[0]]}function h0(i,t,e){return[i[0]+t*Math.cos(e),i[1]+t*Math.sin(e)]}function p8(i,t){let e=(t-i)%Qi;return e>Math.PI&&(e-=Qi),e<=-Math.PI&&(e+=Qi),e}function ic(i,t,e){let n=(t-i)%Qi;return n<0&&(n+=Qi),e?n<tn&&(n=Qi):n=n===0?Qi:Qi-n,n}function ob(i){return h0(i.center,i.radius,i.startAngle)}function ab(i){return h0(i.center,i.radius,i.startAngle+i.sweep)}function kd(i,t){return h0(i.center,i.radius,i.startAngle+i.sweep*t)}function f0(i){return kd(i,.5)}function lb(i){return Math.abs(i.sweep)*i.radius}function y8(i){return 2*i.radius*Math.abs(Math.sin(i.sweep/2))}function ub(i,t){const e=i.startAngle+i.sweep*t,n=i.sweep>=0?1:-1;return[-Math.sin(e)*n,Math.cos(e)*n]}function _8(i){return i.sweep>0}function Td(i){return Math.tan(i.sweep/4)}function d0(i,t,e){if(!Number.isFinite(e)||Math.abs(e)<tn)return null;const n=4*Math.atan(e);return Rd(i,t,n)}function cb(i,t,e){const n=Qn(t,i),r=Qn(e,t),s=ti(n),o=ti(r);if(s<tn||o<tn)return null;const a=$m(n,r)/(s*o);if(Math.abs(a)<d8)return null;const l=2*$m(n,r),h=i[0]*i[0]+i[1]*i[1],f=t[0]*t[0]+t[1]*t[1],d=e[0]*e[0]+e[1]*e[1],p=[(h*(t[1]-e[1])+f*(e[1]-i[1])+d*(i[1]-t[1]))/l,(h*(e[0]-t[0])+f*(i[0]-e[0])+d*(t[0]-i[0]))/l],y=ti(Qn(i,p));if(!Number.isFinite(y)||y<tn)return null;const _=Math.atan2(i[1]-p[1],i[0]-p[0]),E=Math.atan2(t[1]-p[1],t[0]-p[0]),w=Math.atan2(e[1]-p[1],e[0]-p[0]),L=a>0,b=ic(_,E,L),S=ic(_,w,L);return S<b?null:{center:p,radius:y,startAngle:_,sweep:L?S:-S}}function v8(i,t,e,n=!0){const r=ti(Qn(i,t)),s=Qn(e,t);if(r<tn||ti(s)<tn)return null;const o=Math.atan2(i[1]-t[1],i[0]-t[0]),a=Math.atan2(s[1],s[0]),l=ic(o,a,n);return{center:t,radius:r,startAngle:o,sweep:n?l:-l}}function E8(i,t,e){const n=ti(Qn(i,t));if(n<tn||!Number.isFinite(e)||Math.abs(e)<tn)return null;const r=Math.sign(e)*Math.min(Math.abs(e),Qi);return{center:t,radius:n,startAngle:Math.atan2(i[1]-t[1],i[0]-t[0]),sweep:r}}function w8(i,t,e,n=!0){const r=ti(Qn(i,t));if(r<tn||!(e>tn)||e>2*r+tn)return null;const o=2*Math.asin(Math.min(1,e/(2*r)));return{center:t,radius:r,startAngle:Math.atan2(i[1]-t[1],i[0]-t[0]),sweep:n?o:-o}}function Rd(i,t,e){const n=Qn(t,i),r=ti(n);if(r<tn||!Number.isFinite(e))return null;const s=Math.sign(e)*Math.min(Math.abs(e),Qi-tn),o=s/2;if(Math.abs(Math.sin(o))<tn)return null;const a=Math.abs(r/(2*Math.sin(o))),l=r/2/Math.tan(o),h=c0(u0(n)),f=[(i[0]+t[0])/2+h[0]*l,(i[1]+t[1])/2+h[1]*l];return{center:f,radius:a,startAngle:Math.atan2(i[1]-f[1],i[0]-f[0]),sweep:s}}function x8(i,t,e,n={}){const{ccw:r=!0,major:s=!1}=n,o=Qn(t,i),a=ti(o);if(a<tn||!(e>0)||e<a/2-tn)return null;const l=Math.min(e,a/2),h=Math.sqrt(Math.max(0,e*e-l*l)),f=c0(u0(o)),d=r!==s?1:-1,p=[(i[0]+t[0])/2+f[0]*h*d,(i[1]+t[1])/2+f[1]*h*d],y=Math.atan2(i[1]-p[1],i[0]-p[0]),_=Math.atan2(t[1]-p[1],t[0]-p[0]),E=ic(y,_,r);return{center:p,radius:e,startAngle:y,sweep:r?E:-E}}function hb(i,t,e){const n=Qn(t,i),r=ti(n),s=u0(e);if(r<tn||ti(s)<tn)return null;let o=c0(s),a=m8(o,n);if(a<0&&(o=[-o[0],-o[1]],a=-a),a<r/(2*g8))return null;const l=r*r/(2*a);if(!Number.isFinite(l)||l<tn)return null;const h=[i[0]+o[0]*l,i[1]+o[1]*l],f=Math.atan2(i[1]-h[1],i[0]-h[0]),d=Math.atan2(t[1]-h[1],t[0]-h[0]),p=$m(s,Qn(h,i))>0,y=ic(f,d,p);return{center:h,radius:l,startAngle:f,sweep:p?y:-y}}function fb(i,t=Ms,e=sb){const n=Math.abs(i.sweep),r=Math.max(t,tn);let s;if(r>=i.radius)s=1;else{const a=2*Math.acos(1-r/i.radius);s=Math.max(1,Math.ceil(n/a))}s=Math.min(s,Math.max(1,e-1));const o=[];for(let a=0;a<=s;a++)o.push(kd(i,a/s));return o}function Ff(i,t){const e=Qn(t,i.center),n=Math.atan2(e[1],e[0]),r=p8(i.startAngle,n);let s=i.sweep===0?0:r/i.sweep;if(s<0||s>1){const a=(r>0?r-Qi:r+Qi)/i.sweep;if(a>=0&&a<=1)s=a;else{const l=ti(Qn(t,ob(i))),h=ti(Qn(t,ab(i)));s=l<=h?0:1}}const o=kd(i,s);return{point:o,t:s,distance:ti(Qn(t,o))}}function b8(i){return{center:i.center,radius:i.radius,startAngle:i.startAngle+i.sweep,sweep:-i.sweep}}const $f="ofsCurve";function db(i,t){return i*Math.abs(t)/2}function Ad(i,t,e=ei(i.vertices)){const n=i.vertices[t],r=i.vertices[t+1],s=i.bulges[t];if(!n||!r||!Number.isFinite(s)||s===0)return!1;const o=e.toPlanar(n),a=e.toPlanar(r),l=Math.hypot(a[0]-o[0],a[1]-o[1]);return db(l,s)>i.sagToleranceMeters}function I8(i,t=ei(i.vertices)){return i.bulges.some((e,n)=>Ad(i,n,t))}function ei(i){if(i.length===0)return me.forCoordinate([0,0]);let t=1/0,e=1/0,n=-1/0,r=-1/0;return i.forEach(([s,o])=>{s<t&&(t=s),o<e&&(e=o),s>n&&(n=s),o>r&&(r=o)}),me.forBBox([t,e,n,r])}function $l(i,t,e=ei(i.vertices)){return Ad(i,t,e)?d0(e.toPlanar(i.vertices[t]),e.toPlanar(i.vertices[t+1]),i.bulges[t]):null}function Pu(i,t=ei(i.vertices)){if(i.vertices.length===0)return[];const e=i.sagToleranceMeters??Ms,n=[i.vertices[0]];for(let r=0;r<i.vertices.length-1;r++){const s=$l(i,r,t);if(!s){n.push(i.vertices[r+1]);continue}fb(s,e).slice(1,-1).forEach(o=>n.push(t.toGeographic(o))),n.push(i.vertices[r+1])}return n}function To(i){var s;const t=(s=i==null?void 0:i.properties)==null?void 0:s[$f];if(!t||typeof t!="object"||t.version!==1)return null;const e=t.vertices,n=t.bulges;if(!Array.isArray(e)||!Array.isArray(n)||e.length<2||n.length!==e.length-1||!e.every(o=>Array.isArray(o)&&o.length>=2&&Number.isFinite(o[0])&&Number.isFinite(o[1]))||!n.every(o=>Number.isFinite(o)))return null;const r=Number(t.sagToleranceMeters);return{version:1,vertices:e.map(o=>[o[0],o[1]]),bulges:n.map(Number),sagToleranceMeters:r>0?r:Ms}}function ku(i,t,e=Ms){if(i.length<2)return null;const n={version:1,vertices:i.map(o=>[o[0],o[1]]),bulges:i.slice(0,-1).map((o,a)=>Number.isFinite(t[a])?t[a]:0),sagToleranceMeters:e>0?e:Ms},r=ei(n.vertices);let s=!1;return n.bulges=n.bulges.map((o,a)=>Ad(n,a,r)?(s=!0,o):0),s?n:null}function Df(i,t){if(!t){const{[$f]:e,...n}=i;return n}return{...i,[$f]:t}}function gb(i,t,e,n=ei([i,t,e])){const r=cb(n.toPlanar(i),n.toPlanar(t),n.toPlanar(e));return r?Td(r):0}function Od(i){if(!i)return null;const t=To(i);if(t)return{vertices:[...t.vertices],bulges:[...t.bulges],sagToleranceMeters:t.sagToleranceMeters};const e=i.geometry.type==="LineString"?i.geometry.coordinates:i.geometry.type==="Polygon"&&i.geometry.coordinates.length===1?i.geometry.coordinates[0]:null;return!e||e.length<2?null:{vertices:e.map(n=>[n[0],n[1]]),bulges:new Array(e.length-1).fill(0),sagToleranceMeters:Ms}}function Gf(i,t){const e=ku(t.vertices,t.bulges,t.sagToleranceMeters),n=e?Pu(e):t.vertices,r=i.geometry.type==="Polygon"?{type:"Polygon",coordinates:[n]}:i.geometry.type==="LineString"?{type:"LineString",coordinates:n}:null;return r?{...i,geometry:r,properties:Df({...i.properties||{}},e)}:null}function g0(i,t,e){const n=Od(i);if(!n||t<0||t>=n.bulges.length||!Number.isFinite(e))return null;if(e===0)return n.bulges[t]=0,Gf(i,n);const r=ei(n.vertices),s=Rd(r.toPlanar(n.vertices[t]),r.toPlanar(n.vertices[t+1]),e*Math.PI/180);return s?(n.bulges[t]=Td(s),Gf(i,n)):null}function Bf(i,t,e=Ms,n=ei(i)){const r={vertices:i,bulges:t,sagToleranceMeters:e},s=[];for(let o=0;o<i.length-1;o++){const a=$l(r,o,n);s.push({segmentIndex:o,curved:a!==null,coordinate:a?n.toGeographic(f0(a)):[(i[o][0]+i[o+1][0])/2,(i[o][1]+i[o+1][1])/2]})}return s}function S8(i,t,e=ei(i.vertices)){if(i.vertices.length<2)return null;const n=e.toPlanar(t);let r=null;for(let s=0;s<i.vertices.length-1;s++){const o=$l(i,s,e),a=o?Ff(o,n):M8(n,e.toPlanar(i.vertices[s]),e.toPlanar(i.vertices[s+1]));(!r||a.distance<r.distanceMeters)&&(r={coordinate:e.toGeographic(a.point),segmentIndex:s,distanceMeters:a.distance})}return r}function M8(i,t,e){const n=e[0]-t[0],r=e[1]-t[1],s=n*n+r*r,o=s<1e-18?0:Math.max(0,Math.min(1,((i[0]-t[0])*n+(i[1]-t[1])*r)/s)),a=[t[0]+n*o,t[1]+r*o];return{point:a,distance:Math.hypot(i[0]-a[0],i[1]-a[1])}}const N8=["vertex","intersection","midpoint","center","perpendicular","edge"];class rc{constructor(t,e){q(this,"dataSource");q(this,"mapAdapter");q(this,"enabled",!0);q(this,"tolerancePixels",18);q(this,"modes",{vertex:!0,intersection:!0,midpoint:!0,center:!0,perpendicular:!0,edge:!0});this.dataSource=t,this.mapAdapter=e}setModes(t){this.modes={...this.modes,...t}}toggleMode(t){return this.modes[t]=!this.modes[t],this.modes[t]}getSnap(t,e=[],n){var E;if(!this.enabled||!this.mapAdapter.isReady)return null;let r;try{r=this.mapAdapter.getRawMap()}catch{return null}if(!t||!Array.isArray(t)||t.length<2||!r||typeof r.project!="function")return null;const s=r.project([t[0],t[1]]),o=this.tolerancePixels,a=new Map,l=(w,L,b,S)=>{if(!this.modes[w])return;const P=b||r.project([L[0],L[1]]),N=Math.hypot(P.x-s.x,P.y-s.y),C=a.get(w);N<=o&&(!C||N<C.distPx)&&a.set(w,{coord:L,distPx:N,segment:S})},h=[],f=(n==null?void 0:n.fromPoint)??null,d=(w,L)=>{if(!w||!L||w.length<2||L.length<2)return;const b=r.project([w[0],w[1]]),S=r.project([L[0],L[1]]),P=S.x-b.x,N=S.y-b.y,C=P*P+N*N;if(C<1)return;l("midpoint",[(w[0]+L[0])/2,(w[1]+L[1])/2],{x:(b.x+S.x)/2,y:(b.y+S.y)/2});const T=((s.x-b.x)*P+(s.y-b.y)*N)/C,I=Math.max(0,Math.min(1,T));if(Math.hypot(s.x-(b.x+I*P),s.y-(b.y+I*N))<=o&&h.push({a:w,b:L}),this.modes.edge&&T>=.08&&T<=.92&&l("edge",[w[0]+T*(L[0]-w[0]),w[1]+T*(L[1]-w[1])],{x:b.x+T*P,y:b.y+T*N},{a:w,b:L}),this.modes.perpendicular&&f){const R=rc.perpendicularFoot(f,w,L);R&&l("perpendicular",R,void 0,{a:w,b:L})}},p=w=>{for(let L=0;L<w.length-1;L++)d(w[L],w[L+1])};Array.isArray(e)&&e.length>0&&(e.forEach(w=>w&&l("vertex",w)),(n==null?void 0:n.connectAdditional)!==!1&&p(e));const y=this.dataSource.getAllLayers().filter(w=>w.visible),_=this.getSearchBBox(r,s);for(const w of y){const L=_?w.queryBBox(_):w.getFeatures();for(const b of L){if(!b.geometry)continue;const S=n==null?void 0:n.excludeFeatureId;if(S!=null&&b.id===S)continue;const P=To(b);if(P){this.considerCurve(P,t,l,d,f);continue}rT(b).forEach(C=>l("vertex",C));const N=b.geometry;if(N.type==="LineString"?p(N.coordinates):N.type==="MultiLineString"||N.type==="Polygon"?N.coordinates.forEach(p):N.type==="MultiPolygon"&&N.coordinates.forEach(C=>C.forEach(p)),this.modes.center&&((E=b.properties)==null?void 0:E.shape)==="circle"&&N.type==="Polygon"){const C=N.coordinates[0].slice(0,-1),T=C.reduce((M,R)=>M+R[0],0)/C.length,I=C.reduce((M,R)=>M+R[1],0)/C.length;l("center",[T,I])}}}if(this.modes.intersection&&h.length>=2)for(let w=0;w<h.length;w++)for(let L=w+1;L<h.length;L++){const b=rc.segmentIntersection(h[w],h[L]);b&&l("intersection",b)}for(const w of N8){const L=a.get(w);if(L)return{coordinate:L.coord,type:w,distanceMeters:Co(t,L.coord),segment:L.segment}}return null}considerCurve(t,e,n,r,s){const o=ei(t.vertices);t.vertices.forEach(a=>n("vertex",a));for(let a=0;a<t.vertices.length-1;a++){const l=$l(t,a,o);if(!l){r(t.vertices[a],t.vertices[a+1]);continue}n("center",o.toGeographic(l.center)),n("midpoint",o.toGeographic(f0(l)));const h=Ff(l,o.toPlanar(e));if(h.t>.08&&h.t<.92&&n("edge",o.toGeographic(h.point)),s){const f=Ff(l,o.toPlanar(s));f.t>0&&f.t<1&&n("perpendicular",o.toGeographic(f.point))}}}static segmentIntersection(t,e){const[n,r]=t.a,[s,o]=t.b,[a,l]=e.a,[h,f]=e.b,d=(s-n)*(f-l)-(o-r)*(h-a);if(Math.abs(d)<1e-18)return null;const p=((a-n)*(f-l)-(l-r)*(h-a))/d,y=((a-n)*(o-r)-(l-r)*(s-n))/d,_=1e-9;return p<=_||p>=1-_||y<=_||y>=1-_?null:[n+p*(s-n),r+p*(o-r)]}static perpendicularFoot(t,e,n){const r=Math.cos(t[1]*Math.PI/180),s=e[0]*r,o=n[0]*r,a=t[0]*r,l=o-s,h=n[1]-e[1],f=l*l+h*h;if(f<1e-24)return null;const d=((a-s)*l+(t[1]-e[1])*h)/f;return d<=0||d>=1?null:[e[0]+d*(n[0]-e[0]),e[1]+d*(n[1]-e[1])]}getSearchBBox(t,e){if(typeof t.unproject!="function")return null;const n=this.tolerancePixels,r=[[e.x-n,e.y-n],[e.x+n,e.y-n],[e.x+n,e.y+n],[e.x-n,e.y+n]].map(([h,f])=>t.unproject([h,f]));let s=1/0,o=1/0,a=-1/0,l=-1/0;for(const h of r){const f=Array.isArray(h)?h[0]:h==null?void 0:h.lng,d=Array.isArray(h)?h[1]:h==null?void 0:h.lat;if(!Number.isFinite(f)||!Number.isFinite(d))return null;s=Math.min(s,f),o=Math.min(o,d),a=Math.max(a,f),l=Math.max(l,d)}return[s,o,a,l]}}const Js={convention:"bearing",ucsRotationDeg:0},m0={enabled:!1,incrementDeg:45,toleranceDeg:4},xl=Math.PI/180;function Dm(i){const t=i%360;return t<0?t+360:t}function sc(i,t){return((t.convention==="bearing"?90-i:i)+t.ucsRotationDeg)*xl}function bl(i,t){const e=i/xl-t.ucsRotationDeg;return Dm(t.convention==="bearing"?90-e:e)}function Gm(i,t){return(t.convention==="bearing"?-i:i)*xl}function p0(i,t){const e=me.forCoordinate(i),n=e.toPlanar(i),r=e.toPlanar(t);return{projection:e,origin:n,dx:r[0]-n[0],dy:r[1]-n[1]}}function es(i,t,e){const n=me.forCoordinate(i),r=n.toPlanar(i);return n.toGeographic([r[0]+t*Math.cos(e),r[1]+t*Math.sin(e)])}function Qe(i,t,e=Js){const{dx:n,dy:r}=p0(i,t);return{distance:Math.hypot(n,r),angle:bl(Math.atan2(r,n),e)}}const oc=String.raw`[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?`,L8=new RegExp(String.raw`^@\s*(${oc})\s*[,\s]\s*(${oc})$`,"i"),C8=new RegExp(String.raw`^@\s*(${oc})\s*<\s*(${oc})$`,"i"),P8=new RegExp(String.raw`^(${oc})$`,"i");function y0(i,t={}){const e=i.trim();if(!e)return null;const n=t.frame??Js,r=t.basePoint??null,s=e.match(C8);if(s){if(!r)return{kind:"error",message:"Relative input needs a base point. Specify the first point first."};const h=Number(s[1]),f=Number(s[2]);return{kind:"point",coordinate:es(r,h,sc(f,n)),description:`@${h}<${f}`}}const o=e.match(L8);if(o){if(!r)return{kind:"error",message:"Relative input needs a base point. Specify the first point first."};const h=Number(o[1]),f=Number(o[2]),d=n.ucsRotationDeg*xl,p=h*Math.cos(d)-f*Math.sin(d),y=h*Math.sin(d)+f*Math.cos(d),_=Math.hypot(p,y);return{kind:"point",coordinate:_===0?[r[0],r[1]]:es(r,_,Math.atan2(y,p)),description:`@${h},${f}`}}const a=e.match(P8);if(a){const h=Number(a[1]);if(!r)return{kind:"error",message:"Distance input needs a base point. Specify the first point first."};if(!t.cursor)return{kind:"error",message:"Move the cursor to show the direction, then type the distance."};const{dx:f,dy:d}=p0(r,t.cursor);return Math.hypot(f,d)<1e-6?{kind:"error",message:"Move the cursor away from the base point to show the direction."}:{kind:"point",coordinate:es(r,h,Math.atan2(d,f)),description:`${h} m toward cursor`}}if(e.startsWith("@"))return{kind:"error",message:`Invalid relative input "${e}". Use @dx,dy or @distance<angle.`};const l=dp(e);return l?{kind:"point",coordinate:l,description:`${l[0]}, ${l[1]}`}:gp(e)?{kind:"error",message:rf(e)}:null}function _0(i,t,e){const{ortho:n,polar:r,frame:s}=e;if(!n&&!r.enabled)return{coordinate:t,lockedAngle:null,mode:null};const{projection:o,origin:a,dx:l,dy:h}=p0(i,t);if(Math.hypot(l,h)<1e-9)return{coordinate:t,lockedAngle:null,mode:null};const d=Dm(Math.atan2(h,l)/xl-s.ucsRotationDeg);let p=null,y=null;if(n)p=Math.round(d/90)*90,y="ortho";else if(r.enabled&&r.incrementDeg>0){const L=Math.round(d/r.incrementDeg)*r.incrementDeg;Math.abs(d-L)<=r.toleranceDeg&&(p=L,y="polar")}if(p===null)return{coordinate:t,lockedAngle:null,mode:null};const _=(p+s.ucsRotationDeg)*xl,E=l*Math.cos(_)+h*Math.sin(_);let w=o.toGeographic([a[0]+E*Math.cos(_),a[1]+E*Math.sin(_)]);if(s.ucsRotationDeg%360===0){const L=Dm(p)%180;L===0?w=[t[0],i[1]]:L===90&&(w=[i[0],t[1]])}return{coordinate:w,lockedAngle:bl(_,s),mode:y}}class k8{static calculateOrtho(t,e,n=Js){const r=_0(t,e,{ortho:!0,polar:m0,frame:n}),{distance:s}=Qe(t,r.coordinate),o=Qe(t,r.coordinate,Js).angle,a=((o-(90-n.ucsRotationDeg))%180+180)%180;return{coordinate:r.coordinate,distanceMeters:s,bearingDegrees:s>.1?Math.round(o*10)/10:0,axis:a<45||a>135?"horizontal":"vertical"}}}function xe(i){if(!i||typeof i.getRawMap!="function")return null;try{return i.getRawMap()??null}catch{return null}}class mb extends no{constructor(e,n,r){super();q(this,"dataSource");q(this,"mapAdapter");q(this,"snapping",null);q(this,"currentSnapResult",null);q(this,"sourceId","_ofs_grips_temp");q(this,"activeFeatureId",null);q(this,"activeLayerId",null);q(this,"activeGrip",null);q(this,"isDragging",!1);q(this,"dragHasMoved",!1);q(this,"isEnabled",!1);q(this,"activationTimestamp",0);q(this,"initialFeatureSnapshot",null);q(this,"unsubClick",null);q(this,"unsubMouseDown",null);q(this,"unsubMouseUp",null);q(this,"unsubMove",null);q(this,"unsubContextMenu",null);q(this,"handleKeyDown",e=>{if(!(!this.isEnabled||this.activeFeatureId===null||!this.activeLayerId)){if(e.key==="Delete"||e.key==="Backspace")this.activeGrip&&this.activeGrip.type==="vertex"&&(e.preventDefault(),this.deleteVertex(this.activeGrip.index,this.activeGrip.ringIndex,this.activeGrip.partIndex??0)&&(this.activeGrip=null,this.isDragging=!1,this.dragHasMoved=!1));else if(e.key==="Escape")if(this.isDragging&&this.initialFeatureSnapshot){this.dataSource.updateFeature(this.activeLayerId,this.initialFeatureSnapshot,!1),this.isDragging=!1,this.dragHasMoved=!1,this.activeGrip=null,this.initialFeatureSnapshot=null,this.renderGrips();try{const n=xe(this.mapAdapter);n&&n.dragPan&&n.dragPan.enable(),n&&n.getCanvas()&&(n.getCanvas().style.cursor="default")}catch(n){Ht("OFSGripsEditor.handleKeyDown",n)}}else this.clear()}});this.dataSource=e,this.mapAdapter=n,this.snapping=r||null,typeof window<"u"&&window.addEventListener("keydown",this.handleKeyDown),this.dataSource.on("feature:updated",({layerId:s,feature:o})=>{this.isEnabled&&this.activeLayerId===s&&this.activeFeatureId===o.id&&!this.isDragging&&this.renderGrips()})}setSnappingEngine(e){this.snapping=e}getSnappingEngine(){return this.snapping}editFeature(e,n){if(this.isEnabled&&this.activeLayerId===e&&this.activeFeatureId===n)return;const r=this.dataSource.getFeature(e,n);!r||!["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon"].includes(r.geometry.type)||(this.activeLayerId=e,this.activeFeatureId=n,this.isEnabled=!0,this.activeGrip=null,this.isDragging=!1,this.dragHasMoved=!1,this.initialFeatureSnapshot=null,this.activationTimestamp=Date.now(),this.setupLayers(),this.renderGrips(),this.bindEvents())}clear(){try{const e=xe(this.mapAdapter);e&&e.dragPan&&e.dragPan.enable(),e&&e.getCanvas()&&(e.getCanvas().style.cursor="default")}catch(e){Ht("OFSGripsEditor.clear",e)}this.isEnabled=!1,this.activeFeatureId=null,this.activeLayerId=null,this.activeGrip=null,this.isDragging=!1,this.dragHasMoved=!1,this.initialFeatureSnapshot=null,this.currentSnapResult=null,this.unsubClick&&(this.unsubClick(),this.unsubClick=null),this.unsubMouseDown&&(this.unsubMouseDown(),this.unsubMouseDown=null),this.unsubMouseUp&&(this.unsubMouseUp(),this.unsubMouseUp=null),this.unsubMove&&(this.unsubMove(),this.unsubMove=null),this.unsubContextMenu&&(this.unsubContextMenu(),this.unsubContextMenu=null),this.clearSource(),this.emit("grip:clear",void 0)}getActiveFeature(){return!this.activeLayerId||this.activeFeatureId===null?null:this.dataSource.getFeature(this.activeLayerId,this.activeFeatureId)||null}getActiveLayerId(){return this.activeLayerId}getActiveFeatureId(){return this.activeFeatureId}getIsEditing(){return this.isEnabled&&this.activeFeatureId!==null}hasHandleAt(e,n=18){return this.findNearestHandle(e,n)!==null}curveStateOf(e){return Od(e)}writeCurveState(e,n){if(!this.activeLayerId||this.activeFeatureId===null)return!1;const r=Gf(e,n);return r?(r.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,r,!1),!0):!1}getCurveSegments(){const e=this.getActiveFeature();if(!e)return[];const n=this.curveStateOf(e);if(!n)return[];const r=ei(n.vertices);return Bf(n.vertices,n.bulges,n.sagToleranceMeters,r).map(s=>({index:s.segmentIndex,curved:s.curved,coordinate:s.coordinate,sagMeters:s.curved?r.distance(n.vertices[s.segmentIndex],n.vertices[s.segmentIndex+1])*Math.abs(n.bulges[s.segmentIndex])/2:0}))}convertSegmentToArc(e,n){const r=this.getActiveFeature();if(!r||!this.activeLayerId||this.activeFeatureId===null||!n)return!1;const s=g0(r,e,n);return s?(s.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,s,!1),!0):!1}setSegmentBulge(e,n){const r=this.getActiveFeature();if(!r)return!1;const s=this.curveStateOf(r);return!s||e<0||e>=s.bulges.length||!Number.isFinite(n)?!1:(s.bulges[e]=n,this.writeCurveState(r,s))}straightenSegment(e){return this.setSegmentBulge(e,0)}curveHandles(e){if(!To(e))return null;const n=this.curveStateOf(e);if(!n)return null;const r=e.geometry.type==="Polygon",s=[],o=r?n.vertices.length-1:n.vertices.length;for(let a=0;a<o;a++)s.push({id:r?`v_0_${a}`:`v_${a}`,coordinate:n.vertices[a],type:"vertex",index:a,ringIndex:0,partIndex:0});Bf(n.vertices,n.bulges,n.sagToleranceMeters).forEach(a=>{s.push({id:`${a.curved?"s":"m"}_${a.segmentIndex}`,coordinate:a.coordinate,type:a.curved?"curve":"midpoint",index:a.segmentIndex,ringIndex:0,partIndex:0})});try{s.push({id:"c_center",coordinate:Us(e).geometry.coordinates,type:"center",index:0,ringIndex:0,partIndex:0})}catch(a){Ht("OFSGripsEditor.curveHandles",a)}return s}getHandles(){const e=this.getActiveFeature();if(!e)return[];const n=this.curveHandles(e);if(n)return n;const r=[],s=e.geometry.type,o=()=>{try{const a=Us(e).geometry.coordinates;r.push({id:"c_center",coordinate:a,type:"center",index:0,ringIndex:0,partIndex:0})}catch(a){Ht("OFSGripsEditor.getHandles",a)}};if(s==="Point"){const a=e.geometry.coordinates;r.push({id:"v_0",coordinate:a,type:"vertex",index:0,ringIndex:0,partIndex:0})}else if(s==="MultiPoint")e.geometry.coordinates.forEach((l,h)=>{r.push({id:`v_${h}`,coordinate:l,type:"vertex",index:h,ringIndex:0,partIndex:0})}),o();else if(s==="LineString"){const a=e.geometry.coordinates;a.forEach((l,h)=>{if(r.push({id:`v_${h}`,coordinate:l,type:"vertex",index:h,ringIndex:0,partIndex:0}),h<a.length-1){const f=a[h+1];r.push({id:`m_${h}`,coordinate:[(l[0]+f[0])/2,(l[1]+f[1])/2],type:"midpoint",index:h,ringIndex:0,partIndex:0})}}),o()}else s==="MultiLineString"?(e.geometry.coordinates.forEach((l,h)=>{l.forEach((f,d)=>{if(r.push({id:`v_${h}_${d}`,coordinate:f,type:"vertex",index:d,ringIndex:0,partIndex:h}),d<l.length-1){const p=l[d+1];r.push({id:`m_${h}_${d}`,coordinate:[(f[0]+p[0])/2,(f[1]+p[1])/2],type:"midpoint",index:d,ringIndex:0,partIndex:h})}})}),o()):s==="Polygon"?(e.geometry.coordinates.forEach((l,h)=>{const f=l.length-1;for(let d=0;d<f;d++){const p=l[d],y=l[(d+1)%f];r.push({id:`v_${h}_${d}`,coordinate:p,type:"vertex",index:d,ringIndex:h,partIndex:0}),r.push({id:`m_${h}_${d}`,coordinate:[(p[0]+y[0])/2,(p[1]+y[1])/2],type:"midpoint",index:d,ringIndex:h,partIndex:0})}}),o()):s==="MultiPolygon"&&(e.geometry.coordinates.forEach((l,h)=>{l.forEach((f,d)=>{const p=f.length-1;for(let y=0;y<p;y++){const _=f[y],E=f[(y+1)%p];r.push({id:`v_${h}_${d}_${y}`,coordinate:_,type:"vertex",index:y,ringIndex:d,partIndex:h}),r.push({id:`m_${h}_${d}_${y}`,coordinate:[(_[0]+E[0])/2,(_[1]+E[1])/2],type:"midpoint",index:y,ringIndex:d,partIndex:h})}})}),o());return r}setupLayers(){if(this.mapAdapter.isReady)try{const e=xe(this.mapAdapter);if(!e||typeof e.getSource!="function")return;if(!e.getSource(this.sourceId))e.addSource(this.sourceId,{type:"geojson",data:{type:"FeatureCollection",features:[]}}),e.addLayer({id:`${this.sourceId}_shape_fill`,source:this.sourceId,type:"fill",filter:["all",["==","$type","Polygon"],["==","gripType","active_shape"]],paint:{"fill-color":"#818cf8","fill-opacity":.25}}),e.addLayer({id:`${this.sourceId}_shape_line`,source:this.sourceId,type:"line",filter:["all",["in","$type","LineString","Polygon"],["==","gripType","active_shape"]],paint:{"line-color":"#2e2b6b","line-width":2.5}}),e.addLayer({id:`${this.sourceId}_center`,source:this.sourceId,type:"circle",filter:["==",["get","gripType"],"center"],paint:{"circle-radius":8,"circle-color":"#10b981","circle-stroke-width":2.5,"circle-stroke-color":"#ffffff"}}),e.addLayer({id:`${this.sourceId}_curves`,source:this.sourceId,type:"circle",filter:["==",["get","gripType"],"curve"],paint:{"circle-radius":6,"circle-color":"#f59e0b","circle-stroke-width":2,"circle-stroke-color":"#ffffff"}}),e.addLayer({id:`${this.sourceId}_midpoints`,source:this.sourceId,type:"circle",filter:["==",["get","gripType"],"midpoint"],paint:{"circle-radius":4.5,"circle-color":"#f43f5e","circle-stroke-width":1.5,"circle-stroke-color":"#ffffff"}}),e.addLayer({id:`${this.sourceId}_vertices`,source:this.sourceId,type:"circle",filter:["==",["get","gripType"],"vertex"],paint:{"circle-radius":6.5,"circle-color":"#f43f5e","circle-stroke-width":2.5,"circle-stroke-color":"#ffffff"}}),e.addLayer({id:`${this.sourceId}_direction_arrows`,source:this.sourceId,type:"symbol",filter:["==",["get","gripType"],"direction_arrow"],layout:{"text-field":"▲","text-size":14,"text-rotate":["get","bearing"],"text-rotation-alignment":"map","text-pitch-alignment":"map","text-keep-upright":!1,"text-allow-overlap":!0,"text-ignore-placement":!0},paint:{"text-color":"#0284c7","text-halo-color":"#ffffff","text-halo-width":2}}),e.addLayer({id:`${this.sourceId}_active`,source:this.sourceId,type:"circle",filter:["==",["get","isActive"],!0],paint:{"circle-radius":11,"circle-color":"#fbbf24","circle-opacity":.45,"circle-stroke-width":2.5,"circle-stroke-color":"#f59e0b"}}),e.addLayer({id:`${this.sourceId}_snap_halo`,source:this.sourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":22,"circle-color":["match",["get","snapType"],"midpoint","#38bdf8","edge","#a855f7","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#3b82f6"],"circle-blur":.85,"circle-opacity":.7}}),e.addLayer({id:`${this.sourceId}_snap_glow`,source:this.sourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":11,"circle-color":["match",["get","snapType"],"midpoint","#0ea5e9","edge","#8b5cf6","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#2563eb"],"circle-blur":.35,"circle-opacity":.55}}),e.addLayer({id:`${this.sourceId}_snap_core`,source:this.sourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":5.5,"circle-color":["match",["get","snapType"],"midpoint","#0284c7","edge","#7c3aed","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#1d4ed8"],"circle-stroke-width":2,"circle-stroke-color":"#ffffff","circle-stroke-opacity":1}});else try{e.getLayer(`${this.sourceId}_shape_fill`)&&e.setFilter(`${this.sourceId}_shape_fill`,["all",["==","$type","Polygon"],["==","gripType","active_shape"]]),e.getLayer(`${this.sourceId}_shape_line`)&&e.setFilter(`${this.sourceId}_shape_line`,["all",["in","$type","LineString","Polygon"],["==","gripType","active_shape"]]),e.getLayer(`${this.sourceId}_snap_halo`)||e.addLayer({id:`${this.sourceId}_snap_halo`,source:this.sourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":22,"circle-color":["match",["get","snapType"],"midpoint","#38bdf8","edge","#a855f7","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#3b82f6"],"circle-blur":.85,"circle-opacity":.7}}),e.getLayer(`${this.sourceId}_snap_glow`)||e.addLayer({id:`${this.sourceId}_snap_glow`,source:this.sourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":11,"circle-color":["match",["get","snapType"],"midpoint","#0ea5e9","edge","#8b5cf6","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#2563eb"],"circle-blur":.35,"circle-opacity":.55}}),e.getLayer(`${this.sourceId}_snap_core`)||e.addLayer({id:`${this.sourceId}_snap_core`,source:this.sourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":5.5,"circle-color":["match",["get","snapType"],"midpoint","#0284c7","edge","#7c3aed","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#1d4ed8"],"circle-stroke-width":2,"circle-stroke-color":"#ffffff","circle-stroke-opacity":1}})}catch(n){Ht("OFSGripsEditor.setupLayers",n)}}catch(e){Ht("OFSGripsEditor.setupLayers",e)}}renderGrips(){if(this.mapAdapter.isReady)try{const e=xe(this.mapAdapter);if(!e||typeof e.getSource!="function")return;const n=e.getSource(this.sourceId);if(!n||typeof n.setData!="function")return;const r=this.getActiveFeature(),s=[];if(r&&r.geometry&&s.push({type:"Feature",geometry:r.geometry,properties:{gripType:"active_shape"}}),this.getHandles().forEach(l=>{var h;s.push(Lt(l.coordinate,{gripId:l.id,gripType:l.type,index:l.index,ringIndex:l.ringIndex,partIndex:l.partIndex??0,isActive:((h=this.activeGrip)==null?void 0:h.id)===l.id,isSnap:!1}))}),r&&r.geometry&&r.geometry.type==="LineString"){const l=r.geometry.coordinates;for(let h=0;h<l.length-1;h++){const f=l[h],d=l[h+1],p=[(f[0]+d[0])/2,(f[1]+d[1])/2],y=al(Lt(f),Lt(d));s.push(Lt(p,{gripId:`arrow_${h}`,gripType:"direction_arrow",bearing:y,isSnap:!1}))}}this.currentSnapResult&&this.currentSnapResult.coordinate&&s.push(Lt(this.currentSnapResult.coordinate,{gripId:"snap_indicator",gripType:"snap_guide",isSnap:!0,snapType:this.currentSnapResult.type})),n.setData({type:"FeatureCollection",features:s}),[`${this.sourceId}_shape_fill`,`${this.sourceId}_shape_line`,`${this.sourceId}_direction_arrows`,`${this.sourceId}_center`,`${this.sourceId}_curves`,`${this.sourceId}_midpoints`,`${this.sourceId}_vertices`,`${this.sourceId}_active`,`${this.sourceId}_snap_halo`,`${this.sourceId}_snap_glow`,`${this.sourceId}_snap_core`].forEach(l=>{try{e.getLayer(l)&&e.moveLayer(l)}catch(h){Ht("OFSGripsEditor.renderGrips",h)}})}catch(e){Ht("OFSGripsEditor.renderGrips",e)}}clearSource(){try{const e=xe(this.mapAdapter);if(!e||typeof e.getSource!="function")return;const n=e.getSource(this.sourceId);n&&typeof n.setData=="function"&&n.setData({type:"FeatureCollection",features:[]})}catch(e){Ht("OFSGripsEditor.clearSource",e)}}bindEvents(){this.unsubClick&&this.unsubClick(),this.unsubMouseDown&&this.unsubMouseDown(),this.unsubMouseUp&&this.unsubMouseUp(),this.unsubMove&&this.unsubMove(),this.unsubContextMenu&&this.unsubContextMenu(),this.unsubMouseDown=typeof this.mapAdapter.onMouseDown=="function"?this.mapAdapter.onMouseDown(e=>this.handleMouseDown(e.coordinate)):()=>{},this.unsubMouseUp=typeof this.mapAdapter.onMouseUp=="function"?this.mapAdapter.onMouseUp(e=>this.handleMouseUp(e.coordinate)):()=>{},this.unsubClick=typeof this.mapAdapter.onMapClick=="function"?this.mapAdapter.onMapClick(e=>this.handleClick(e.coordinate)):()=>{},this.unsubMove=typeof this.mapAdapter.onMouseMove=="function"?this.mapAdapter.onMouseMove(e=>this.handleMove(e.coordinate)):()=>{},this.unsubContextMenu=typeof this.mapAdapter.onContextMenu=="function"?this.mapAdapter.onContextMenu(e=>this.handleContextMenu(e.coordinate,e.originalEvent)):()=>{}}findNearestHandle(e,n=18){let r;try{r=xe(this.mapAdapter)}catch{return null}if(!r||typeof r.project!="function"){const h=this.getHandles();let f=null,d=.001;for(const p of h){const y=Math.hypot(e[0]-p.coordinate[0],e[1]-p.coordinate[1]),_=p.type==="center"?d*.7:d;y<=_&&(d=y,f=p)}return f}const s=r.project([e[0],e[1]]),o=this.getHandles();let a=null,l=n;for(const h of o){const f=r.project([h.coordinate[0],h.coordinate[1]]),d=Math.hypot(s.x-f.x,s.y-f.y),p=h.type==="center"?Math.min(n,14):n;d<=p&&(a&&h.type!=="center"&&a.type==="center"&&d<=l+4||!a||d<l)&&(a=h,l=d)}return a}handleMouseDown(e){if(!this.isEnabled||!this.activeLayerId||this.activeFeatureId===null||Date.now()-this.activationTimestamp<250)return;const n=this.findNearestHandle(e,18);if(!n)return;const r=this.getActiveFeature();r&&(this.initialFeatureSnapshot=Ue(r)),n.type==="midpoint"?this.insertVertexAtMidpoint(n):(this.activeGrip=n,this.isDragging=!0,this.emit("grip:select",{handle:n}),this.renderGrips()),this.dragHasMoved=!1;try{const s=xe(this.mapAdapter);s&&s.dragPan&&typeof s.dragPan.disable=="function"&&s.dragPan.disable(),s&&typeof s.getCanvas=="function"&&s.getCanvas()&&(s.getCanvas().style.cursor="crosshair")}catch(s){Ht("OFSGripsEditor.handleMouseDown",s)}}handleMouseUp(e){var n;if(this.isEnabled){try{const r=xe(this.mapAdapter);r&&r.dragPan&&typeof r.dragPan.enable=="function"&&r.dragPan.enable(),r&&typeof r.getCanvas=="function"&&r.getCanvas()&&(r.getCanvas().style.cursor="default")}catch(r){Ht("OFSGripsEditor.handleMouseUp",r)}if(this.isDragging){if(this.dragHasMoved){if(this.activeGrip&&this.activeLayerId&&this.activeFeatureId!==null){const r=this.activeFeatureId,s=this.activeLayerId,o=this.initialFeatureSnapshot,a=this.getActiveFeature();if(o&&a){const l=Ue(a);this.dataSource.transactions.record({description:`Edit geometry of feature ${r}`,undo:()=>{this.dataSource.updateFeature(s,o,!1),this.renderGrips()},redo:()=>{this.dataSource.updateFeature(s,l,!1),this.renderGrips()}})}this.initialFeatureSnapshot=null,this.activeGrip=null,this.isDragging=!1,this.dragHasMoved=!1,this.currentSnapResult=null,this.renderGrips(),this.emit("grip:commit",{featureId:r,layerId:s})}}else if(((n=this.activeGrip)==null?void 0:n.type)==="center"){this.isDragging=!1,this.activeGrip=null,this.initialFeatureSnapshot=null,this.renderGrips();return}}}}handleClick(e){if(!(!this.isEnabled||!this.activeLayerId||this.activeFeatureId===null)&&!(Date.now()-this.activationTimestamp<250)){if(this.dragHasMoved){this.dragHasMoved=!1;return}if(this.isDragging){this.isDragging=!1,this.dragHasMoved=!1;const n=this.activeFeatureId,r=this.activeLayerId,s=this.initialFeatureSnapshot,o=this.getActiveFeature();if(s&&o){const a=Ue(o);this.dataSource.transactions.record({description:`Edit geometry of feature ${n}`,undo:()=>{this.dataSource.updateFeature(r,s,!1),this.renderGrips()},redo:()=>{this.dataSource.updateFeature(r,a,!1),this.renderGrips()}})}this.initialFeatureSnapshot=null,this.activeGrip=null,this.currentSnapResult=null,this.renderGrips(),this.emit("grip:commit",{featureId:n,layerId:r})}else{const n=this.findNearestHandle(e,18);if(n){if(n.type==="center")return;const r=this.getActiveFeature();r&&(this.initialFeatureSnapshot=Ue(r)),n.type==="midpoint"?this.insertVertexAtMidpoint(n):(this.activeGrip=n,this.isDragging=!0,this.emit("grip:select",{handle:n}),this.renderGrips())}}}}handleContextMenu(e,n){if(!this.isEnabled||!this.activeLayerId||this.activeFeatureId===null)return;const r=this.findNearestHandle(e,18);r&&r.type==="vertex"&&(n&&n.preventDefault(),this.deleteVertex(r.index,r.ringIndex,r.partIndex??0),this.activeGrip=null,this.isDragging=!1,this.dragHasMoved=!1)}handleMove(e){if(this.isEnabled){if(this.isDragging&&this.activeGrip&&this.activeLayerId&&this.activeFeatureId!==null){this.dragHasMoved=!0;let n=e,r=null;if(this.snapping&&this.snapping.enabled&&["vertex","midpoint","curve"].includes(this.activeGrip.type)){const s=this.activeGrip.type==="curve"?[]:this.getHandles().filter(o=>o.id!==this.activeGrip.id&&o.type==="vertex").map(o=>o.coordinate);r=this.snapping.getSnap(e,s,{excludeFeatureId:this.activeFeatureId,connectAdditional:!To(this.getActiveFeature())}),r&&(n=r.coordinate)}this.currentSnapResult=r,this.applyCoordinateChange(n);return}try{const n=xe(this.mapAdapter);if(n&&typeof n.getCanvas=="function"&&n.getCanvas()){const r=this.findNearestHandle(e,18);r?n.getCanvas().style.cursor=r.type==="center"?"move":"pointer":n.getCanvas().style.cursor="default"}}catch(n){Ht("OFSGripsEditor.handleMove",n)}}}applyCoordinateChange(e){if(!this.activeGrip||!this.activeLayerId||this.activeFeatureId===null)return;const n=this.getActiveFeature();if(n){if(this.activeGrip.type==="center"){const r=e[0]-this.activeGrip.coordinate[0],s=e[1]-this.activeGrip.coordinate[1],o=ce.translateByOffset(n,r,s);o.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,o,!1),this.activeGrip.coordinate=e,this.renderGrips(),this.emit("grip:move",{handle:this.activeGrip,coordinate:e});return}if(To(n)&&this.applyCurveChange(n,e)){this.activeGrip.coordinate=e,this.renderGrips(),this.emit("grip:move",{handle:this.activeGrip,coordinate:e});return}if(n.geometry.type==="Point"){const r=Lt(e,n.properties);r.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,r,!1)}else if(n.geometry.type==="MultiPoint"){const r=[...n.geometry.coordinates];r[this.activeGrip.index]=e;const s=fw(r,n.properties);s.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,s,!1)}else if(n.geometry.type==="LineString"){const r=[...n.geometry.coordinates];r[this.activeGrip.index]=e;const s=ae(r,n.properties);s.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,s,!1)}else if(n.geometry.type==="MultiLineString"){const r=n.geometry.coordinates.map(a=>[...a]),s=this.activeGrip.partIndex??0;r[s][this.activeGrip.index]=e;const o=hw(r,n.properties);o.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,o,!1)}else if(n.geometry.type==="Polygon"){const r=n.geometry.coordinates.map(l=>[...l]),s=this.activeGrip.ringIndex,o=this.activeGrip.index;r[s][o]=e,o===0&&(r[s][r[s].length-1]=e);const a=Pe(r,n.properties);a.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,a,!1)}else if(n.geometry.type==="MultiPolygon"){const r=n.geometry.coordinates.map(h=>h.map(f=>[...f])),s=this.activeGrip.partIndex??0,o=this.activeGrip.ringIndex,a=this.activeGrip.index;r[s][o][a]=e,a===0&&(r[s][o][r[s][o].length-1]=e);const l=Oo(r,n.properties);l.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,l,!1)}this.activeGrip.coordinate=e,this.renderGrips(),this.emit("grip:move",{handle:this.activeGrip,coordinate:e})}}applyCurveChange(e,n){if(!this.activeGrip)return!1;const r=this.curveStateOf(e);if(!r)return!1;const s=this.activeGrip.index;if(this.activeGrip.type==="curve"){if(s<0||s>=r.bulges.length)return!1;r.bulges[s]=gb(r.vertices[s],n,r.vertices[s+1])}else if(this.activeGrip.type==="vertex"){if(s<0||s>=r.vertices.length)return!1;r.vertices[s]=n,e.geometry.type==="Polygon"&&s===0&&(r.vertices[r.vertices.length-1]=n)}else return!1;return this.writeCurveState(e,r)}insertVertexAtMidpoint(e){const n=this.getActiveFeature();if(n&&To(n)){const r=this.curveStateOf(n);r&&e.index>=0&&e.index<r.bulges.length&&(r.vertices.splice(e.index+1,0,e.coordinate),r.bulges.splice(e.index,1,0,0),this.writeCurveState(n,r)&&(this.activeGrip={id:`v_${e.index+1}`,coordinate:e.coordinate,type:"vertex",index:e.index+1,ringIndex:e.ringIndex,partIndex:0},this.isDragging=!0,this.renderGrips()));return}this.insertVertexIntoGeometry(e)}insertVertexIntoGeometry(e){if(!this.activeLayerId||this.activeFeatureId===null)return;const n=this.getActiveFeature();if(n){if(n.geometry.type==="LineString"){const r=[...n.geometry.coordinates],s=e.index+1;r.splice(s,0,e.coordinate);const o=ae(r,n.properties);o.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,o,!1),this.activeGrip={id:`v_${s}`,coordinate:e.coordinate,type:"vertex",index:s,ringIndex:0,partIndex:0},this.isDragging=!0,this.renderGrips()}else if(n.geometry.type==="Polygon"){const r=n.geometry.coordinates.map(l=>[...l]),s=e.ringIndex,o=e.index+1;r[s].splice(o,0,e.coordinate);const a=Pe(r,n.properties);a.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,a,!1),this.activeGrip={id:`v_${s}_${o}`,coordinate:e.coordinate,type:"vertex",index:o,ringIndex:s,partIndex:0},this.isDragging=!0,this.renderGrips()}else if(n.geometry.type==="MultiPolygon"){const r=n.geometry.coordinates.map(h=>h.map(f=>[...f])),s=e.partIndex??0,o=e.ringIndex,a=e.index+1;r[s][o].splice(a,0,e.coordinate);const l=Oo(r,n.properties);l.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,l,!1),this.activeGrip={id:`v_${s}_${o}_${a}`,coordinate:e.coordinate,type:"vertex",index:a,ringIndex:o,partIndex:s},this.isDragging=!0,this.renderGrips()}}}deleteVertex(e,n=0,r=0){if(!this.activeLayerId||this.activeFeatureId===null)return!1;const s=this.getActiveFeature();if(!s)return!1;if(s.geometry.type==="LineString"){const o=[...s.geometry.coordinates];if(o.length<=2)return!1;o.splice(e,1);const a=ae(o,s.properties);return a.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,a,!0),this.renderGrips(),this.emit("grip:delete-vertex",{featureId:this.activeFeatureId,index:e}),!0}else if(s.geometry.type==="Polygon"){const o=s.geometry.coordinates.map(l=>[...l]);if(o[n].length<=4)return!1;o[n].splice(e,1),e===0&&(o[n][o[n].length-1]=o[n][0]);const a=Pe(o,s.properties);return a.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,a,!0),this.renderGrips(),this.emit("grip:delete-vertex",{featureId:this.activeFeatureId,index:e}),!0}else if(s.geometry.type==="MultiPolygon"){const o=s.geometry.coordinates.map(l=>l.map(h=>[...h]));if(o[r][n].length<=4)return!1;o[r][n].splice(e,1),e===0&&(o[r][n][o[r][n].length-1]=o[r][n][0]);const a=Oo(o,s.properties);return a.id=this.activeFeatureId,this.dataSource.updateFeature(this.activeLayerId,a,!0),this.renderGrips(),this.emit("grip:delete-vertex",{featureId:this.activeFeatureId,index:e}),!0}return!1}destroy(){typeof window<"u"&&window.removeEventListener("keydown",this.handleKeyDown),this.clear(),this.removeAllListeners()}}const pb={pointColor:"#22d3ee",pointRadius:4,pointStrokeColor:"#0e7490",pointStrokeWidth:1,lineColor:"#22d3ee",lineWidth:1.5,lineDash:[2,2],fillColor:"#22d3ee",fillOpacity:.15,opacity:.9},Wg={type:"FeatureCollection",features:[]};function hn(i,t){return["coalesce",["get",i],t]}class yb{constructor(t){q(this,"mapAdapter");q(this,"sourceId","_ofs_preview_source");q(this,"style",{...pb});q(this,"current",Wg);this.mapAdapter=t}get layerIds(){return[`${this.sourceId}_fill`,`${this.sourceId}_line`,`${this.sourceId}_points`]}raw(){var t;if(!((t=this.mapAdapter)!=null&&t.isReady))return null;try{return xe(this.mapAdapter)}catch{return null}}setupLayers(){const t=this.raw();if(!(!t||typeof t.addSource!="function"))try{if(t.getSource(this.sourceId))return;t.addSource(this.sourceId,{type:"geojson",data:this.current}),t.addLayer({id:`${this.sourceId}_fill`,source:this.sourceId,type:"fill",filter:["in","$type","Polygon"],paint:{"fill-color":hn("color",this.style.fillColor),"fill-opacity":hn("fillOpacity",this.style.fillOpacity)}}),t.addLayer({id:`${this.sourceId}_line`,source:this.sourceId,type:"line",filter:["in","$type","LineString","Polygon"],layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":hn("color",this.style.lineColor),"line-width":hn("width",this.style.lineWidth),"line-opacity":hn("opacity",this.style.opacity),...this.style.lineDash.length>0?{"line-dasharray":this.style.lineDash}:{}}}),t.addLayer({id:`${this.sourceId}_points`,source:this.sourceId,type:"circle",filter:["==","$type","Point"],paint:{"circle-color":hn("color",this.style.pointColor),"circle-radius":hn("radius",this.style.pointRadius),"circle-opacity":hn("opacity",this.style.opacity),"circle-stroke-color":hn("strokeColor",this.style.pointStrokeColor),"circle-stroke-width":hn("strokeWidth",this.style.pointStrokeWidth)}})}catch(e){Ht("OFSDrawPreview.setupLayers",e)}}set(t){const e=t?Array.isArray(t)?{type:"FeatureCollection",features:t}:t:Wg;this.current=e,this.setupLayers();const n=this.raw();if(!(!n||typeof n.getSource!="function"))try{const r=n.getSource(this.sourceId);r&&typeof r.setData=="function"&&r.setData(e)}catch(r){Ht("OFSDrawPreview.set",r)}}clear(){this.set(null)}getFeatures(){return[...this.current.features]}isEmpty(){return this.current.features.length===0}setStyle(t){this.style={...this.style,...t};const e=this.raw();if(!(!e||typeof e.setPaintProperty!="function")&&!(typeof e.getLayer=="function"&&!e.getLayer(`${this.sourceId}_points`)))try{const n=`${this.sourceId}_fill`,r=`${this.sourceId}_line`,s=`${this.sourceId}_points`;e.setPaintProperty(n,"fill-color",hn("color",this.style.fillColor)),e.setPaintProperty(n,"fill-opacity",hn("fillOpacity",this.style.fillOpacity)),e.setPaintProperty(r,"line-color",hn("color",this.style.lineColor)),e.setPaintProperty(r,"line-width",hn("width",this.style.lineWidth)),e.setPaintProperty(r,"line-opacity",hn("opacity",this.style.opacity)),e.setPaintProperty(r,"line-dasharray",this.style.lineDash.length>0?this.style.lineDash:void 0),e.setPaintProperty(s,"circle-color",hn("color",this.style.pointColor)),e.setPaintProperty(s,"circle-radius",hn("radius",this.style.pointRadius)),e.setPaintProperty(s,"circle-opacity",hn("opacity",this.style.opacity)),e.setPaintProperty(s,"circle-stroke-color",hn("strokeColor",this.style.pointStrokeColor)),e.setPaintProperty(s,"circle-stroke-width",hn("strokeWidth",this.style.pointStrokeWidth))}catch(n){Ht("OFSDrawPreview.setStyle",n)}}getStyle(){return{...this.style}}bringToFront(){const t=this.raw();if(!(!t||typeof t.moveLayer!="function"||typeof t.getLayer!="function"))try{this.layerIds.forEach(e=>{t.getLayer(e)&&t.moveLayer(e)})}catch(e){Ht("OFSDrawPreview.bringToFront",e)}}destroy(){const t=this.raw();if(this.current=Wg,!!t)try{this.layerIds.forEach(e=>{typeof t.getLayer=="function"&&t.getLayer(e)&&typeof t.removeLayer=="function"&&t.removeLayer(e)}),typeof t.getSource=="function"&&t.getSource(this.sourceId)&&typeof t.removeSource=="function"&&t.removeSource(this.sourceId)}catch(e){Ht("OFSDrawPreview.destroy",e)}}}const Ev=1e-12;function Fd(i,t,e){return[i[0]+(t[0]-i[0])*e,i[1]+(t[1]-i[1])*e]}function Zn(i){return i.segmentIndex+i.t}function _b(i){const t=[],e=n=>{for(let r=0;r<n.length-1;r++)(n[r][0]!==n[r+1][0]||n[r][1]!==n[r+1][1])&&t.push({a:n[r],b:n[r+1]})};switch(i.type){case"LineString":e(i.coordinates);break;case"MultiLineString":case"Polygon":i.coordinates.forEach(e);break;case"MultiPolygon":i.coordinates.forEach(n=>n.forEach(e));break;case"GeometryCollection":i.geometries.forEach(n=>t.push(..._b(n)));break}return t}function qf(i,t,e){const n=t[0]-i[0],r=t[1]-i[1],s=e.b[0]-e.a[0],o=e.b[1]-e.a[1],a=n*o-r*s,l=Math.hypot(n,r)*Math.hypot(s,o);if(l===0||Math.abs(a)<=l*1e-12)return null;const h=e.a[0]-i[0],f=e.a[1]-i[1];return{s:(h*o-f*s)/a,u:(h*r-f*n)/a}}function js(i,t){const e=Math.cos(t[1]*Math.PI/180);let n={segmentIndex:0,t:0,coordinate:i[0],distance:1/0};for(let r=0;r<i.length-1;r++){const s=i[r],o=i[r+1],a=(o[0]-s[0])*e,l=o[1]-s[1],h=a*a+l*l,f=h<Ev*Ev?0:Math.max(0,Math.min(1,((t[0]-s[0])*e*a+(t[1]-s[1])*l)/h)),d=Fd(s,o,f),p=Math.hypot((t[0]-d[0])*e,t[1]-d[1]);p<n.distance&&(n={segmentIndex:r,t:f,coordinate:d,distance:p})}return n}function T8(i,t){const e=[];for(let n=0;n<i.length-1;n++){const r=i[n],s=i[n+1];for(const o of t){const a=qf(r,s,o);if(!a||a.s<-1e-9||a.s>1+1e-9||a.u<-1e-9||a.u>1+1e-9)continue;const l=Math.max(0,Math.min(1,a.s)),h=a.u<=1e-9?o.a:a.u>=1-1e-9?o.b:Fd(r,s,l);e.push({segmentIndex:n,t:l,coordinate:h})}}return e.sort((n,r)=>Zn(n)-Zn(r)),e.filter((n,r)=>r===0||Zn(n)-Zn(e[r-1])>1e-9)}function zf(i,t,e){const n=[t.coordinate];for(let r=t.segmentIndex+1;r<=e.segmentIndex;r++)n.push(i[r]);return n.push(e.coordinate),n.filter((r,s)=>s===0||r[0]!==n[s-1][0]||r[1]!==n[s-1][1])}function R8(i,t,e){const n=i.length,r={segmentIndex:0,coordinate:i[0]},s={segmentIndex:n-2,t:1,coordinate:i[n-1]},o=T8(i,t).filter(d=>Zn(d)>1e-9&&Zn(d)<Zn(s)-1e-9);if(o.length===0)return null;const a=Zn(js(i,e)),l=[...o].reverse().find(d=>Zn(d)<a)??null,h=o.find(d=>Zn(d)>a)??null,f=[];return l&&f.push(zf(i,r,l)),h&&f.push(zf(i,h,s)),f.filter(d=>d.length>=2)}function A8(i,t,e){const n=i.length;if(n<2)return null;const r=Math.cos(e[1]*Math.PI/180),s=p=>Math.hypot((p[0]-e[0])*r,p[1]-e[1]),o=s(i[n-1])<=s(i[0]),a=o?i[n-2]:i[1],l=o?i[n-1]:i[0];let h=1/0,f=null;for(const p of t){const y=qf(a,l,p);!y||y.u<-1e-9||y.u>1+1e-9||y.s<=1+1e-9||y.s<h&&(h=y.s,f=y.u<=1e-9?p.a:y.u>=1-1e-9?p.b:Fd(a,l,y.s))}if(!f)return null;const d=[...i];return o?d[n-1]=f:d[0]=f,d}function O8(i,t,e,n,r){const s=js(i,t),o=js(e,n),a=i[s.segmentIndex],l=i[s.segmentIndex+1],h={a:e[o.segmentIndex],b:e[o.segmentIndex+1]},f=qf(a,l,h);if(!f)return null;const d=Fd(a,l,f.s),p=qf(h.a,h.b,{a,b:l}),y=f.s>=s.t,_=p.s>=o.t,E=y?a:l,w=_?h.a:h.b;let L=d,b=d,S=null;if(r>0){const N=me.forCoordinate(d),C=ib(N.toPlanar(E),N.toPlanar(d),N.toPlanar(w),r);if(!C)return null;S=C.points.map(T=>N.toGeographic(T)),L=S[0],b=S[S.length-1]}const P=(N,C,T,I)=>T?[...N.slice(0,C+1),I]:[I,...N.slice(C+1)];return{line1:P(i,s.segmentIndex,y,L),line2:P(e,o.segmentIndex,_,b),arc:S}}function vb(i,t,e,n){const r=me.forCoordinate(e),s=r.toPlanar(e),o=r.toPlanar(n),a=o[0]-s[0],l=o[1]-s[1];let h=0;const f=y=>y[0]>=t[0]&&y[0]<=t[2]&&y[1]>=t[1]&&y[1]<=t[3],d=y=>{if(!f(y))return y;h++;const _=r.toPlanar(y),E=r.toGeographic([_[0]+a,_[1]+l]);return y.length>2?[E[0],E[1],...y.slice(2)]:E},p=y=>typeof y[0]=="number"?d(y):y.map(p);if(i.type==="GeometryCollection"){const y=i.geometries.map(_=>vb(_,t,e,n));return{geometry:{...i,geometries:y.map(_=>_.geometry)},moved:y.reduce((_,E)=>_+E.moved,0)}}return{geometry:{...i,coordinates:p(i.coordinates)},moved:h}}function F8(i,t,e){const n=i.length,r={segmentIndex:0,coordinate:i[0]},s={segmentIndex:n-2,t:1,coordinate:i[n-1]};let o=js(i,t),a=js(i,e);Zn(a)<Zn(o)&&([o,a]=[a,o]);const l=[];return Zn(o)>1e-9&&l.push(zf(i,r,o)),Zn(a)<Zn(s)-1e-9&&l.push(zf(i,a,s)),l.filter(h=>h.length>=2)}function Eb(i){let t=0;for(let e=0;e<i.length-1;e++)t+=Qe(i[e],i[e+1]).distance;return t}function $8(i,t,e){const n=i.length;if(n<2)return null;const r=Math.cos(t[1]*Math.PI/180),s=l=>Math.hypot((l[0]-t[0])*r,l[1]-t[1]),o=s(i[n-1])<=s(i[0]),a=o?[...i]:[...i].reverse();if(e>=0){const l=a[a.length-1],h=Qe(a[a.length-2],l,{convention:"cad",ucsRotationDeg:0}).angle;a[a.length-1]=es(l,e,h*Math.PI/180)}else{let l=-e;for(;a.length>=2;){const h=a[a.length-1],f=a[a.length-2],d=Qe(f,h).distance;if(l<d-1e-9){const p=Qe(h,f,{convention:"cad",ucsRotationDeg:0}).angle;a[a.length-1]=es(h,l,p*Math.PI/180);break}if(l-=d,a.pop(),a.length<2)return null}}return o?a:a.reverse()}const D8={enabled:!0,acquireDelayMs:400,tolerancePixels:8,maxPoints:5};function wv(i,t,e){const n=t.toPlanar(i.origin),r=[Math.cos(i.angleRad),Math.sin(i.angleRad)],s=Math.abs((e[0]-n[0])*r[1]-(e[1]-n[1])*r[0]);return{line:i,point:n,dir:r,distance:s}}function xv(i,t){const e=i.dir[0]*t.dir[1]-i.dir[1]*t.dir[0];if(Math.abs(e)<1e-9)return null;const n=((t.point[0]-i.point[0])*t.dir[1]-(t.point[1]-i.point[1])*t.dir[0])/e;return[i.point[0]+n*i.dir[0],i.point[1]+n*i.dir[1]]}function G8(i,t){const e=(t[0]-i.point[0])*i.dir[0]+(t[1]-i.point[1])*i.dir[1];return[i.point[0]+e*i.dir[0],i.point[1]+e*i.dir[1]]}function B8(i,t){const{anchor:e,ortho:n,polar:r,frame:s,trackPoints:o,toleranceMeters:a}=t,l=me.forCoordinate(i),h=l.toPlanar(i);let f=null,d=null;if(e){const E=_0(e,i,{ortho:n,polar:r,frame:s});if(E.mode&&E.lockedAngle!==null){const w={origin:e,angleRad:sc(E.lockedAngle,s),source:"anchor"};f=wv(w,l,h),d={coordinate:E.coordinate,mode:E.mode,lines:[w]}}}const p=[0,90];if(r.enabled&&r.incrementDeg>0)for(let E=r.incrementDeg;E<180-1e-9;E+=r.incrementDeg)E!==90&&p.push(E);const y=[];for(const E of o)for(const w of p){const L={origin:E,angleRad:(w+s.ucsRotationDeg)*Math.PI/180,source:"track"},b=wv(L,l,h);b.distance<=a&&y.push(b)}y.sort((E,w)=>E.distance-w.distance);const _=(E,w)=>({coordinate:l.toGeographic(E),mode:"tracking",lines:w});if(f&&y.length>0)for(const E of y){const w=xv(f,E);if(w&&Math.hypot(w[0]-h[0],w[1]-h[1])<=f.distance+a*2)return _(w,[f.line,E.line])}for(let E=0;E<y.length;E++)for(let w=E+1;w<y.length;w++){const L=xv(y[E],y[w]);if(L&&Math.hypot(L[0]-h[0],L[1]-h[1])<=a*2)return _(L,[y[E].line,y[w].line])}return d||(y.length>0?_(G8(y[0],h),[y[0].line]):null)}class q8{constructor(t,e){q(this,"dataSource");q(this,"mapAdapter");q(this,"selectionSourceId","_ofs_selection_source");q(this,"hoverSourceId","_ofs_hover_source");q(this,"flashSourceId","_ofs_flash_source");q(this,"unsubSelection",null);q(this,"currentHoveredFeatureId",null);q(this,"flashTimer",null);this.dataSource=t,this.mapAdapter=e,this.unsubSelection=this.dataSource.on("selection:changed",()=>{this.syncSelectionOverlay()})}setupLayers(){if(this.mapAdapter.isReady)try{const t=xe(this.mapAdapter);if(!t||typeof t.addSource!="function")return;t.getSource(this.selectionSourceId)||(t.addSource(this.selectionSourceId,{type:"geojson",data:{type:"FeatureCollection",features:[]}}),t.addLayer({id:`${this.selectionSourceId}_fill`,source:this.selectionSourceId,type:"fill",filter:["all",["in","$type","Polygon"],["!=","isBbox",!0]],paint:{"fill-color":"#00e5ff","fill-opacity":.22}}),t.addLayer({id:`${this.selectionSourceId}_glow`,source:this.selectionSourceId,type:"line",filter:["all",["in","$type","Polygon","LineString"],["!=","isBbox",!0]],paint:{"line-color":"#00b4d8","line-width":7,"line-blur":3.5,"line-opacity":.85}}),t.addLayer({id:`${this.selectionSourceId}_line`,source:this.selectionSourceId,type:"line",filter:["all",["in","$type","Polygon","LineString"],["!=","isBbox",!0]],paint:{"line-color":"#ffffff","line-width":3,"line-dasharray":[3,2],"line-opacity":1}}),t.addLayer({id:`${this.selectionSourceId}_points`,source:this.selectionSourceId,type:"circle",filter:["all",["in","$type","Point"],["!=","isBbox",!0]],paint:{"circle-radius":9,"circle-color":"#00e5ff","circle-stroke-width":2.5,"circle-stroke-color":"#ffffff","circle-stroke-opacity":1}}),t.addLayer({id:`${this.selectionSourceId}_bbox`,source:this.selectionSourceId,type:"line",filter:["all",["==","$type","Polygon"],["==","isBbox",!0]],paint:{"line-color":"#38bdf8","line-width":1.5,"line-dasharray":[4,4],"line-opacity":.75}})),t.getSource(this.hoverSourceId)||(t.addSource(this.hoverSourceId,{type:"geojson",data:{type:"FeatureCollection",features:[]}}),t.addLayer({id:`${this.hoverSourceId}_fill`,source:this.hoverSourceId,type:"fill",filter:["in","$type","Polygon"],paint:{"fill-color":"#38bdf8","fill-opacity":.15}}),t.addLayer({id:`${this.hoverSourceId}_line`,source:this.hoverSourceId,type:"line",filter:["in","$type","Polygon","LineString"],paint:{"line-color":"#38bdf8","line-width":3.5,"line-opacity":.9,"line-blur":1}}),t.addLayer({id:`${this.hoverSourceId}_point`,source:this.hoverSourceId,type:"circle",filter:["in","$type","Point"],paint:{"circle-radius":8,"circle-color":"#38bdf8","circle-stroke-width":2,"circle-stroke-color":"#ffffff","circle-opacity":.8}})),t.getSource(this.flashSourceId)||(t.addSource(this.flashSourceId,{type:"geojson",data:{type:"FeatureCollection",features:[]}}),t.addLayer({id:`${this.flashSourceId}_fill`,source:this.flashSourceId,type:"fill",filter:["in","$type","Polygon"],paint:{"fill-color":"#22c55e","fill-opacity":.35}}),t.addLayer({id:`${this.flashSourceId}_line`,source:this.flashSourceId,type:"line",filter:["in","$type","Polygon","LineString"],paint:{"line-color":"#4ade80","line-width":5,"line-blur":2,"line-opacity":.95}})),this.bringToFront()}catch{}}bringToFront(){if(this.mapAdapter.isReady)try{const t=xe(this.mapAdapter);if(!t||typeof t.moveLayer!="function")return;const e=[`${this.selectionSourceId}_fill`,`${this.selectionSourceId}_glow`,`${this.selectionSourceId}_line`,`${this.selectionSourceId}_points`,`${this.selectionSourceId}_bbox`,`${this.hoverSourceId}_fill`,`${this.hoverSourceId}_line`,`${this.hoverSourceId}_point`,`${this.flashSourceId}_fill`,`${this.flashSourceId}_line`];for(const n of e)t.getLayer(n)&&t.moveLayer(n)}catch(t){Ht("OFSSelectionOverlay.bringToFront",t)}}syncSelectionOverlay(){const t=xe(this.mapAdapter);if(!t||typeof t.getSource!="function")return;const e=t.getSource(this.selectionSourceId);if(!e||typeof e.setData!="function")return;const n=[],r=this.dataSource.getAllLayers();for(const o of r){const a=this.dataSource.getSelectedFeatureIds(o.id);a.length>0&&a.forEach(l=>{const h=o.getFeature(l);h&&n.push(Ue(h))})}const s=[...n];if(n.length>=2)try{const o=le(n),a=je(o),l=Mp(a,{properties:{isBbox:!0}});s.push(l)}catch(o){Ht("OFSSelectionOverlay.syncSelectionOverlay",o)}e.setData({type:"FeatureCollection",features:s})}previewSelection(t){const e=xe(this.mapAdapter);if(!e||typeof e.getSource!="function")return;const n=e.getSource(this.selectionSourceId);!n||typeof n.setData!="function"||n.setData({type:"FeatureCollection",features:t.map(r=>Ue(r))})}setHoverFeature(t){if(!this.mapAdapter.isReady)return;const e=xe(this.mapAdapter);if(!e||typeof e.getSource!="function")return;const n=e.getSource(this.hoverSourceId);if(!(!n||typeof n.setData!="function")){if(!t){this.currentHoveredFeatureId=null,n.setData({type:"FeatureCollection",features:[]});return}this.currentHoveredFeatureId!==t.id&&(this.currentHoveredFeatureId=t.id??null,n.setData({type:"FeatureCollection",features:[Ue(t)]}))}}flashFeatures(t,e=750){const n=Array.isArray(t)?t:[t];if(!this.mapAdapter.isReady||n.length===0)return;const r=xe(this.mapAdapter);if(!r||typeof r.getSource!="function")return;const s=r.getSource(this.flashSourceId);!s||typeof s.setData!="function"||(this.flashTimer&&clearTimeout(this.flashTimer),s.setData({type:"FeatureCollection",features:n.map(o=>Ue(o))}),this.flashTimer=setTimeout(()=>{try{s.setData({type:"FeatureCollection",features:[]})}catch(o){Ht("OFSSelectionOverlay.flashFeatures",o)}this.flashTimer=null},e))}destroy(){this.unsubSelection&&this.unsubSelection(),this.flashTimer&&clearTimeout(this.flashTimer);try{const t=xe(this.mapAdapter);t&&([`${this.selectionSourceId}_fill`,`${this.selectionSourceId}_glow`,`${this.selectionSourceId}_line`,`${this.selectionSourceId}_points`,`${this.selectionSourceId}_bbox`,`${this.hoverSourceId}_fill`,`${this.hoverSourceId}_line`,`${this.hoverSourceId}_point`,`${this.flashSourceId}_fill`,`${this.flashSourceId}_line`].forEach(n=>{t.getLayer(n)&&t.removeLayer(n)}),t.getSource(this.selectionSourceId)&&t.removeSource(this.selectionSourceId),t.getSource(this.hoverSourceId)&&t.removeSource(this.hoverSourceId),t.getSource(this.flashSourceId)&&t.removeSource(this.flashSourceId))}catch(t){Ht("OFSSelectionOverlay.destroy",t)}}}const z8=["Open Sans Regular","Arial Unicode MS Regular"],U8=["_dim_labels","_labels"],wb={crosshair:!1,dimensions:!0,segmentLabels:!1,areaLabel:!0,anchor:"cursor",crosshairColor:"#ffffff",crosshairWidth:.75,angles:!0,dimensionOffsetPixels:26,font:null},bv=["all",["in","$type","LineString","Polygon"],["!=","isTracking",!0],["!=","isGuide",!0],["!=","isDim",!0],["!=","isDimExt",!0],["!=","isAngle",!0]],Iv=["all",["==","$type","Point"],["!=","isSnap",!0],["!=","isLabel",!0],["!=","isTrackPoint",!0]],Y8={point:"crosshair",line:"crosshair",polygon:"crosshair",circle:"crosshair",rectangle:"crosshair","select-box":"crosshair","select-polygon":"crosshair",select:"default",modify:"default"};class xb extends no{constructor(e,n){super();q(this,"dataSource");q(this,"mapAdapter");q(this,"snapping");q(this,"grips");q(this,"selectionOverlay");q(this,"preview");q(this,"orthoEnabled",!1);q(this,"polarTracking",{...m0});q(this,"inputFrame",{convention:"bearing",ucsRotationDeg:0});q(this,"lastCursorCoord",null);q(this,"lastConstraint",null);q(this,"objectTracking",{...D8});q(this,"trackingPoints",[]);q(this,"trackingHover",null);q(this,"now",()=>Date.now());q(this,"pointPick",null);q(this,"currentMode",null);q(this,"activeCoordinates",[]);q(this,"activeBulges",[]);q(this,"arcSegment",!1);q(this,"arcSweepRadians",null);q(this,"sagToleranceMeters",Ms);q(this,"targetLayerId",null);q(this,"tempSourceId","_ofs_draw_temp");q(this,"unsubClick",null);q(this,"unsubDblClick",null);q(this,"unsubContextMenu",null);q(this,"unsubMove",null);q(this,"unsubMouseDown",null);q(this,"unsubMouseUp",null);q(this,"isDrawing",!1);q(this,"guides",{...wb});q(this,"dragSelectStart",null);q(this,"isDragSelecting",!1);q(this,"justFinishedDrag",!1);q(this,"handleKeyDown",e=>{var r;const n=(r=e.target)==null?void 0:r.tagName;if(!(n==="INPUT"||n==="TEXTAREA")){if(e.key==="F8"){e.preventDefault(),this.toggleOrtho();return}if(e.key==="F10"){e.preventDefault(),this.togglePolarTracking();return}if(e.key==="F11"){e.preventDefault(),this.setObjectTracking({enabled:!this.objectTracking.enabled});return}if(e.key==="F3"){e.preventDefault(),this.snapping.enabled=!this.snapping.enabled;return}if(e.key==="Enter"){(this.isDrawing||this.grips.getIsEditing()||this.currentMode==="modify"||this.currentMode==="select")&&(e.preventDefault(),this.finishDrawing());return}if(e.key==="Escape"){(this.isDrawing||this.grips.getIsEditing()||this.currentMode)&&(e.preventDefault(),this.cancel());return}if((this.currentMode==="line"||this.currentMode==="polygon")&&!e.ctrlKey&&!e.metaKey&&!e.altKey){const s=e.key.toLowerCase();(s==="a"||s==="l")&&(e.preventDefault(),this.setArcSegment(s==="a"))}}});this.dataSource=e,this.mapAdapter=n,this.snapping=new rc(e,n),this.grips=new mb(e,n,this.snapping),this.selectionOverlay=new q8(e,n),this.preview=new yb(n),this.bindMapEvents()}setOrtho(e){this.orthoEnabled=e,this.emit("draw:ortho-change",{enabled:e})}toggleOrtho(){return this.orthoEnabled=!this.orthoEnabled,this.emit("draw:ortho-change",{enabled:this.orthoEnabled}),this.orthoEnabled}setPolarTracking(e){this.polarTracking={...this.polarTracking,...e},this.emit("draw:polar-change",{enabled:this.polarTracking.enabled,incrementDeg:this.polarTracking.incrementDeg})}togglePolarTracking(){return this.setPolarTracking({enabled:!this.polarTracking.enabled}),this.polarTracking.enabled}setUcsRotation(e){this.inputFrame={...this.inputFrame,ucsRotationDeg:(e%360+360)%360},this.emit("draw:ucs-change",{...this.inputFrame})}setAngleConvention(e){this.inputFrame={...this.inputFrame,convention:e},this.emit("draw:ucs-change",{...this.inputFrame})}setArcSegment(e,n={}){this.arcSegment=e;const r=n.sweepDegrees;r!==void 0&&(this.arcSweepRadians=r===null||!Number.isFinite(r)||r===0?null:r*Math.PI/180),this.emit("draw:arc-segment",{enabled:e,sweepDegrees:this.arcSweepRadians===null?null:this.arcSweepRadians*180/Math.PI,ready:!e||this.arcSweepRadians!==null||this.activeCoordinates.length>=2}),this.lastCursorCoord&&this.updateTempFeatures(this.lastCursorCoord,null)}toggleArcSegment(){return this.setArcSegment(!this.arcSegment),this.arcSegment}isArcSegment(){return this.arcSegment}getActiveBulges(){return[...this.activeBulges]}setSagTolerance(e){Number.isFinite(e)&&e>0&&(this.sagToleranceMeters=e)}getSagTolerance(){return this.sagToleranceMeters}headingAtLastVertex(e){const n=this.activeCoordinates.length;if(n<2)return null;const r=e.toPlanar(this.activeCoordinates[n-2]),s=e.toPlanar(this.activeCoordinates[n-1]),o=this.activeBulges[n-2]??0;if(o){const a=d0(r,s,o);if(a)return ub(a,1)}return[s[0]-r[0],s[1]-r[1]]}bulgeForSegmentTo(e){if(!this.arcSegment||this.activeCoordinates.length===0)return 0;const n=this.activeCoordinates[this.activeCoordinates.length-1],r=ei([...this.activeCoordinates,e]),s=r.toPlanar(n),o=r.toPlanar(e),a=this.arcSweepRadians!==null?Rd(s,o,this.arcSweepRadians):(()=>{const l=this.headingAtLastVertex(r);return l?hb(s,o,l):null})();return a?Td(a):0}curveLengthMeters(e,n){if(!e)return dl(ae(n),{units:"meters"});const r=ei(e.vertices);let s=0;for(let o=0;o<e.vertices.length-1;o++){const a=$l(e,o,r);s+=a?lb(a):r.distance(e.vertices[o],e.vertices[o+1])}return s}previewCoordinates(e){const n=[...this.activeCoordinates,e];if(n.length<2)return n;const r=ku(n,[...this.activeBulges,this.bulgeForSegmentTo(e)],this.sagToleranceMeters);return r?Pu(r):n}getMapAdapter(){return this.mapAdapter}getCursorCoordinate(){return this.lastCursorCoord}isDrawModeActive(){return["point","line","polygon","circle","rectangle","select-polygon"].includes(this.currentMode)}getReferencePoint(){return this.pointPick?this.pointPick.basePoint??null:this.isDrawing&&this.activeCoordinates.length>0?this.activeCoordinates[this.activeCoordinates.length-1]:null}resolveCursor(e,n,r=[]){const s=this.snapping.getSnap(e,r,{fromPoint:n});if(s)return{coordinate:s.coordinate,snap:s,constraint:null};const o=this.objectTracking.enabled&&this.snapping.enabled?this.trackingPoints:[],a=B8(e,{anchor:n,ortho:this.orthoEnabled,polar:this.polarTracking,frame:this.inputFrame,trackPoints:o,toleranceMeters:this.objectTracking.tolerancePixels*this.metersPerPixel(e)});return a?{coordinate:a.coordinate,snap:null,constraint:a}:{coordinate:e,snap:null,constraint:null}}metersPerPixel(e){const n=xe(this.mapAdapter);if(!n||typeof n.project!="function"||typeof n.unproject!="function")return 1;try{const r=n.project(e),s=n.unproject([r.x+1,r.y]),o=Array.isArray(s)?[s[0],s[1]]:[s.lng,s.lat],a=Qe(e,o).distance;return Number.isFinite(a)&&a>0?a:1}catch(r){return Ht("OFSDrawTools.metersPerPixel",r),1}}setObjectTracking(e){this.objectTracking={...this.objectTracking,...e},this.objectTracking.enabled||this.clearTrackingPoints(),this.emit("draw:otrack-change",{enabled:this.objectTracking.enabled})}getTrackingPoints(){return[...this.trackingPoints]}clearTrackingPoints(){this.trackingHover=null,this.trackingPoints.length!==0&&(this.trackingPoints=[],this.emit("draw:tracking-points",{points:[]}))}updateTrackingAcquisition(e){if(!this.objectTracking.enabled||!this.snapping.enabled||!e||e.type==="edge"){this.trackingHover=null;return}const n=`${e.coordinate[0]},${e.coordinate[1]}`,r=this.now();if((!this.trackingHover||this.trackingHover.key!==n)&&(this.trackingHover={key:n,coord:e.coordinate,since:r,handled:!1}),this.trackingHover.handled||r-this.trackingHover.since<this.objectTracking.acquireDelayMs)return;this.trackingHover.handled=!0;const s=this.trackingPoints.findIndex(o=>o[0]===e.coordinate[0]&&o[1]===e.coordinate[1]);s>=0?this.trackingPoints.splice(s,1):(this.trackingPoints.push(e.coordinate),this.trackingPoints.length>this.objectTracking.maxPoints&&this.trackingPoints.shift()),this.emit("draw:tracking-points",{points:[...this.trackingPoints]})}getInProgressSnapCoords(){return!this.isDrawing||this.activeCoordinates.length===0?[]:(this.currentMode==="polygon"||this.currentMode==="select-polygon")&&this.activeCoordinates.length>=3?[this.activeCoordinates[0]]:this.currentMode==="line"&&this.activeCoordinates.length>=2?this.activeCoordinates.slice(0,-1):[]}submitInput(e){const n=["point","line","polygon","circle","rectangle","select-polygon"];if(!this.currentMode||!n.includes(this.currentMode))return{handled:!1};const r=e.trim(),s=r.toLowerCase();if(r==="")return this.isDrawing?this.finishDrawing()?{handled:!0,message:`${this.currentMode??"Drawing"} finished.`}:{handled:!0,error:"Not enough points to finish."}:{handled:!1};if(this.isDrawing&&(s==="u"||s==="undo"))return this.undoLastVertex()?{handled:!0,message:"Last point removed."}:{handled:!0,error:"Nothing to undo."};if((this.currentMode==="line"||this.currentMode==="polygon")&&["a","arc","l","line"].includes(s)){const a=s==="a"||s==="arc";return this.setArcSegment(a),a&&this.arcSweepRadians===null&&this.activeCoordinates.length<2?{handled:!0,message:"Arc mode on. The first segment stays straight until there is one to curve from."}:{handled:!0,message:a?"Arc segments.":"Straight segments."}}if(this.isDrawing&&(s==="c"||s==="close"))return(this.currentMode==="polygon"||this.currentMode==="select-polygon")&&this.activeCoordinates.length>=3?(this.finishDrawing(),{handled:!0,message:"Polygon closed."}):this.currentMode==="line"&&this.activeCoordinates.length>=3?(this.commitDrawPoint(this.activeCoordinates[0],null),this.finishDrawing(),{handled:!0,message:"Line closed."}):{handled:!0,error:"Close needs at least 3 points."};const o=y0(r,{basePoint:this.getReferencePoint(),cursor:this.lastCursorCoord,frame:this.inputFrame});return o?o.kind==="error"?{handled:!0,error:o.message}:(this.commitDrawPoint(o.coordinate,null),{handled:!0,message:`Point: ${o.description}`}):{handled:!1}}undoLastVertex(){return!this.isDrawing||this.activeCoordinates.length===0?!1:(this.activeCoordinates.pop(),this.activeBulges.pop(),this.activeCoordinates.length===0&&(this.isDrawing=!1),this.emit("draw:vertex-removed",{mode:this.currentMode,coordinates:[...this.activeCoordinates]}),this.updateTempFeatures(this.lastCursorCoord??this.activeCoordinates[this.activeCoordinates.length-1]??[0,0],null),!0)}beginPointPick(e,n){const r={...e,onPick:n};return this.pointPick=r,this.applyCursor(),()=>{this.pointPick===r&&(this.pointPick=null,this.applyCursor(),this.clearTrackingPoints(),this.lastConstraint=null,this.clearTempFeatures())}}isPickingPoint(){return this.pointPick!==null}setupTempDrawingLayer(){if(this.mapAdapter.isReady){this.preview.setupLayers();try{const e=this.mapAdapter.getRawMap();if(!e)return;if(!e.getSource(this.tempSourceId))e.addSource(this.tempSourceId,{type:"geojson",data:{type:"FeatureCollection",features:[]}}),e.addLayer({id:`${this.tempSourceId}_fill`,source:this.tempSourceId,type:"fill",filter:["==","$type","Polygon"],paint:{"fill-color":"#3b82f6","fill-opacity":.25}}),e.addLayer({id:`${this.tempSourceId}_crosshair_shadow`,source:this.tempSourceId,type:"line",filter:["all",["==","$type","LineString"],["==","isGuide",!0]],paint:{"line-color":"#0f172a","line-width":2,"line-opacity":.25,"line-dasharray":[5,5]}}),e.addLayer({id:`${this.tempSourceId}_crosshair`,source:this.tempSourceId,type:"line",filter:["all",["==","$type","LineString"],["==","isGuide",!0]],paint:{"line-color":this.guides.crosshairColor,"line-width":this.guides.crosshairWidth,"line-opacity":.95,"line-dasharray":[5,5]}}),e.addLayer({id:`${this.tempSourceId}_line`,source:this.tempSourceId,type:"line",filter:bv,paint:{"line-color":"#2563eb","line-width":2.5,"line-dasharray":[2,1]}}),e.addLayer({id:`${this.tempSourceId}_dim_ext`,source:this.tempSourceId,type:"line",filter:["all",["==","$type","LineString"],["==","isDimExt",!0]],paint:{"line-color":"#334155","line-width":.75,"line-opacity":.7}}),e.addLayer({id:`${this.tempSourceId}_dim`,source:this.tempSourceId,type:"line",filter:["all",["==","$type","LineString"],["==","isDim",!0]],paint:{"line-color":["case",["==",["get","isLive"],!0],"#1d4ed8","#334155"],"line-width":1}}),e.addLayer({id:`${this.tempSourceId}_dim_labels`,source:this.tempSourceId,type:"symbol",filter:["all",["==","$type","LineString"],["==","isDim",!0]],layout:{"text-field":["get","label"],"text-font":this.guideFont(),"text-size":["case",["==",["get","isLive"],!0],13,11],"symbol-placement":"line-center","text-rotation-alignment":"map","text-offset":[0,-.7],"text-allow-overlap":!1},paint:{"text-color":["case",["==",["get","isLive"],!0],"#1d4ed8","#334155"],"text-halo-color":"#ffffff","text-halo-width":1.6}}),e.addLayer({id:`${this.tempSourceId}_angle_arc`,source:this.tempSourceId,type:"line",filter:["all",["==","$type","LineString"],["==","isAngle",!0]],paint:{"line-color":["case",["==",["get","isLive"],!0],"#16a34a","#64748b"],"line-width":1.25}}),e.addLayer({id:`${this.tempSourceId}_labels`,source:this.tempSourceId,type:"symbol",filter:["all",["==","$type","Point"],["==","isLabel",!0]],layout:{"text-field":["get","label"],"text-font":this.guideFont(),"text-size":["case",["==",["get","isLive"],!0],13,11],"text-offset":[0,-.8],"text-anchor":"bottom","text-allow-overlap":!1,"text-ignore-placement":!1,"symbol-z-order":"source"},paint:{"text-color":["case",["==",["get","isLive"],!0],"#1d4ed8","#334155"],"text-halo-color":"#ffffff","text-halo-width":1.6}}),e.addLayer({id:`${this.tempSourceId}_points`,source:this.tempSourceId,type:"circle",filter:Iv,paint:{"circle-radius":5,"circle-color":"#1d4ed8","circle-stroke-width":2,"circle-stroke-color":"#ffffff"}}),e.addLayer({id:`${this.tempSourceId}_snap_halo`,source:this.tempSourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":22,"circle-color":["match",["get","snapType"],"midpoint","#38bdf8","edge","#a855f7","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#3b82f6"],"circle-blur":.85,"circle-opacity":.7}}),e.addLayer({id:`${this.tempSourceId}_snap_glow`,source:this.tempSourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":11,"circle-color":["match",["get","snapType"],"midpoint","#0ea5e9","edge","#8b5cf6","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#2563eb"],"circle-blur":.35,"circle-opacity":.55}}),e.addLayer({id:`${this.tempSourceId}_snap_core`,source:this.tempSourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":5.5,"circle-color":["match",["get","snapType"],"midpoint","#0284c7","edge","#7c3aed","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#1d4ed8"],"circle-stroke-width":2,"circle-stroke-color":"#ffffff","circle-stroke-opacity":1}});else{e.getLayer(`${this.tempSourceId}_snap_halo`)||e.addLayer({id:`${this.tempSourceId}_snap_halo`,source:this.tempSourceId,type:"circle",filter:["all",["==","$type","Point"],["==","isSnap",!0]],paint:{"circle-radius":22,"circle-color":["match",["get","snapType"],"midpoint","#38bdf8","edge","#a855f7","intersection","#f97316","perpendicular","#22c55e","center","#eab308","#3b82f6"],"circle-blur":.85,"circle-opacity":.7}});try{e.getLayer(`${this.tempSourceId}_points`)&&e.setFilter(`${this.tempSourceId}_points`,["all",["==","$type","Point"],["!=","isSnap",!0]]),e.getLayer(`${this.tempSourceId}_snap_halo`)&&e.setFilter(`${this.tempSourceId}_snap_halo`,["all",["==","$type","Point"],["==","isSnap",!0]]),e.getLayer(`${this.tempSourceId}_snap_glow`)&&e.setFilter(`${this.tempSourceId}_snap_glow`,["all",["==","$type","Point"],["==","isSnap",!0]]),e.getLayer(`${this.tempSourceId}_snap_core`)&&e.setFilter(`${this.tempSourceId}_snap_core`,["all",["==","$type","Point"],["==","isSnap",!0]])}catch(n){Ht("OFSDrawTools.setupTempDrawingLayer",n)}}this.ensureTrackingLayer(e),this.selectionOverlay.setupLayers(),this.selectionOverlay.syncSelectionOverlay(),this.bringTempLayersToFront()}catch{}}}ensureTrackingLayer(e){try{e.getLayer(`${this.tempSourceId}_line`)&&e.setFilter(`${this.tempSourceId}_line`,bv),e.getLayer(`${this.tempSourceId}_points`)&&e.setFilter(`${this.tempSourceId}_points`,Iv),e.getLayer(`${this.tempSourceId}_trackpoints`)||e.addLayer({id:`${this.tempSourceId}_trackpoints`,source:this.tempSourceId,type:"circle",filter:["==","isTrackPoint",!0],paint:{"circle-radius":5,"circle-color":"rgba(0,0,0,0)","circle-stroke-color":"#f59e0b","circle-stroke-width":2}}),e.getLayer(`${this.tempSourceId}_tracking`)||e.addLayer({id:`${this.tempSourceId}_tracking`,source:this.tempSourceId,type:"line",filter:["==","isTracking",!0],paint:{"line-color":"#f59e0b","line-width":1.25,"line-dasharray":[4,3],"line-opacity":.9}})}catch(n){Ht("OFSDrawTools.ensureTrackingLayer",n)}}trackingFeatures(e){const r=this.objectTracking.enabled&&this.snapping.enabled?this.trackingPoints.map(o=>Lt(o,{isTrackPoint:!0})):[],s=this.lastConstraint;if(!s||e!==this.lastCursorCoord)return r;for(const o of s.lines){const{distance:a}=Qe(o.origin,e),l=Math.max(a*4,a+200),h=o.source==="track"?es(o.origin,-l,o.angleRad):o.origin,f=a>1e-6?Qe(o.origin,e,{convention:"cad",ucsRotationDeg:0}).angle*Math.PI/180:o.angleRad,d=es(o.origin,l,f);r.push(ae([h,d],{isTracking:!0}))}return r}bringTempLayersToFront(){var e;if((e=this.mapAdapter)!=null&&e.isReady)try{const n=xe(this.mapAdapter);if(!n||typeof n.getLayer!="function"||typeof n.moveLayer!="function")return;this.preview.bringToFront();const r=[`${this.tempSourceId}_fill`,`${this.tempSourceId}_crosshair_shadow`,`${this.tempSourceId}_crosshair`,`${this.tempSourceId}_tracking`,`${this.tempSourceId}_trackpoints`,`${this.tempSourceId}_line`,`${this.tempSourceId}_dim_ext`,`${this.tempSourceId}_dim`,`${this.tempSourceId}_dim_labels`,`${this.tempSourceId}_angle_arc`,`${this.tempSourceId}_points`,`${this.tempSourceId}_snap_halo`,`${this.tempSourceId}_snap_glow`,`${this.tempSourceId}_snap_core`];for(const s of r)n.getLayer(s)&&n.moveLayer(s);this.selectionOverlay.bringToFront()}catch(n){Ht("OFSDrawTools.bringTempLayersToFront",n)}}bindMapEvents(){this.unsubClick=typeof this.mapAdapter.onMapClick=="function"?this.mapAdapter.onMapClick(e=>this.handleMapClick(e)):()=>{},this.unsubDblClick=typeof this.mapAdapter.onMapDblClick=="function"?this.mapAdapter.onMapDblClick(e=>this.handleMapDblClick(e)):()=>{},this.unsubContextMenu=typeof this.mapAdapter.onContextMenu=="function"?this.mapAdapter.onContextMenu(e=>this.handleContextMenu(e)):()=>{},this.unsubMove=typeof this.mapAdapter.onMouseMove=="function"?this.mapAdapter.onMouseMove(e=>this.handleMouseMove(e)):()=>{},this.unsubMouseDown=typeof this.mapAdapter.onMouseDown=="function"?this.mapAdapter.onMouseDown(e=>this.handleMouseDown(e)):()=>{},this.unsubMouseUp=typeof this.mapAdapter.onMouseUp=="function"?this.mapAdapter.onMouseUp(e=>this.handleMouseUp(e)):()=>{},typeof window<"u"&&window.addEventListener("keydown",this.handleKeyDown)}getRequiredGeometryType(e){return e==="point"?"point":e==="line"?"line":"polygon"}resolveTargetLayerId(e,n){const r=this.getRequiredGeometryType(e);if(n){const f=this.dataSource.getLayer(n);if(f&&f.type===r)return f.id}const s=this.dataSource.getActiveLayer();if(s&&s.type===r)return s.id;const o=this.dataSource.getAllLayers().find(f=>f.type===r&&f.visible);if(o)return this.dataSource.setActiveLayer(o.id),o.id;const a=this.dataSource.getAllLayers().find(f=>f.type===r);if(a)return this.dataSource.setActiveLayer(a.id),a.id;const l=r.charAt(0).toUpperCase()+r.slice(1),h=this.dataSource.addLayer({id:`draw_${r}_layer`,name:`${l}s Layer (Drawn)`,type:r,zIndex:10});return this.dataSource.setActiveLayer(h.id),h.id}getTargetLayerId(){return this.targetLayerId}setMode(e,n){var r;if(this.currentMode!==e){this.isDrawing&&this.cancel(),this.currentMode=e,e!=="modify"&&this.grips.getIsEditing()&&this.grips.clear(),e==="select"||e==="modify"||e==="select-box"||e==="select-polygon"?this.targetLayerId=n||null:e?this.targetLayerId=this.resolveTargetLayerId(e,n):(this.targetLayerId=null,this.grips.clear()),this.setupTempDrawingLayer(),this.emit("draw:mode-change",{mode:e});try{if((r=this.mapAdapter)!=null&&r.isReady){typeof this.mapAdapter.setDoubleClickZoom=="function"&&this.mapAdapter.setDoubleClickZoom(e===null||e==="select"||e==="modify");const s=xe(this.mapAdapter);s&&(s.boxZoom&&(e==="select"||e==="select-box"||e==="select-polygon"?s.boxZoom.disable():s.boxZoom.enable()),this.applyCursor())}}catch(s){Ht("OFSDrawTools.setMode",s)}}}getMode(){return this.currentMode}getIsDrawing(){return this.isDrawing}getActiveCoordinates(){return[...this.activeCoordinates]}handleMouseDown(e){if(this.currentMode&&(this.currentMode==="select"||this.currentMode==="select-box")){if(this.grips.getIsEditing()&&this.grips.hasHandleAt(e.coordinate,18))return;this.dragSelectStart={coord:e.coordinate,point:{x:e.point.x,y:e.point.y}},this.isDragSelecting=!1}}handleMouseUp(e){var r;const n=xe(this.mapAdapter);if(n&&n.dragPan&&!n.dragPan.isEnabled()&&n.dragPan.enable(),this.isDragSelecting&&this.dragSelectStart){const s=this.dragSelectStart.coord,o=e.coordinate,a=Math.min(s[0],o[0]),l=Math.max(s[0],o[0]),h=Math.min(s[1],o[1]),f=Math.max(s[1],o[1]),d=Pe([[[a,h],[l,h],[l,f],[a,f],[a,h]]]),p=!!((r=e.originalEvent)!=null&&r.shiftKey);this.executeDrawSelection("select-box",d,p),this.justFinishedDrag=!0,setTimeout(()=>{this.justFinishedDrag=!1},150),this.isDragSelecting=!1,this.dragSelectStart=null,this.clearTempFeatures();return}this.dragSelectStart=null,this.isDragSelecting=!1}handleMapClick(e){var o,a,l;if(this.pointPick){const h=this.pointPick,{coordinate:f}=this.resolveCursor(e.coordinate,h.basePoint??null);this.pointPick=null,this.applyCursor(),this.clearTrackingPoints(),this.lastConstraint=null,this.clearTempFeatures(),h.onPick(f);return}if(!this.currentMode||this.justFinishedDrag)return;if(this.currentMode==="select"){this.grips.getIsEditing()&&this.grips.clear();const h=!!((o=e.originalEvent)!=null&&o.shiftKey),f=this.pickable(e.features);if(f.length>0){const d=f[0];if(d.id!==void 0&&d.layerId){h?this.dataSource.toggleFeatureSelection(d.layerId,d.id):this.dataSource.selectFeature(d.layerId,d.id,!1);return}}else{h||this.dataSource.clearSelection();return}return}if(this.currentMode==="modify"){if(this.grips.getIsEditing()&&this.grips.hasHandleAt(e.coordinate,18))return;const h=!!((a=e.originalEvent)!=null&&a.shiftKey);if(e.features&&e.features.length>0){const f=e.features[0];if(f.id!==void 0&&f.layerId){this.dataSource.selectFeature(f.layerId,f.id,!1),this.grips.editFeature(f.layerId,f.id);return}}else{h||this.stopEdit();return}return}if(this.currentMode==="select-box"){const h=e.coordinate,f=!!((l=e.originalEvent)!=null&&l.shiftKey);if(!this.isDrawing)this.isDrawing=!0,this.activeCoordinates=[h],this.emit("draw:start",{mode:"select-box",coordinate:h}),this.updateTempFeatures(h,null);else{const d=this.activeCoordinates[0],p=h,y=Math.min(d[0],p[0]),_=Math.max(d[0],p[0]),E=Math.min(d[1],p[1]),w=Math.max(d[1],p[1]),L=Pe([[[y,E],[_,E],[_,w],[y,w],[y,E]]]);this.executeDrawSelection("select-box",L,f),this.resetDrawingState(!0)}return}const n=this.isDrawing&&this.activeCoordinates.length>0?this.activeCoordinates[this.activeCoordinates.length-1]:null,{coordinate:r,snap:s}=this.resolveCursor(e.coordinate,n,this.getInProgressSnapCoords());this.commitDrawPoint(r,s,!0)}commitDrawPoint(e,n,r=!1){if(this.currentMode){if(this.isDrawing){if((this.currentMode==="polygon"||this.currentMode==="select-polygon")&&this.activeCoordinates.length>=3){const o=this.activeCoordinates[0];let a=!1;if(n&&n.coordinate[0]===o[0]&&n.coordinate[1]===o[1])a=!0;else if(e[0]===o[0]&&e[1]===o[1])a=!0;else if(r)try{const l=xe(this.mapAdapter);if(l&&typeof l.project=="function"){const h=l.project([o[0],o[1]]),f=l.project([e[0],e[1]]);h&&f&&Math.hypot(h.x-f.x,h.y-f.y)<=12&&(a=!0)}else Co(e,o)<.5&&(a=!0)}catch(l){Ht("OFSDrawTools.commitDrawPoint",l),Co(e,o)<.5&&(a=!0)}if(a){this.finishDrawing();return}}const s=this.activeCoordinates[this.activeCoordinates.length-1];if(s[0]===e[0]&&s[1]===e[1]&&(this.currentMode==="line"&&this.activeCoordinates.length>=2||(this.currentMode==="polygon"||this.currentMode==="select-polygon")&&this.activeCoordinates.length>=3)){this.finishDrawing();return}if(this.activeBulges.push(this.bulgeForSegmentTo(e)),this.activeCoordinates.push(e),this.emit("draw:vertex-added",{mode:this.currentMode,coordinate:e,coordinates:[...this.activeCoordinates]}),(this.currentMode==="circle"||this.currentMode==="rectangle")&&this.activeCoordinates.length>=2){this.finishDrawing();return}}else if(this.isDrawing=!0,this.activeCoordinates=[e],this.emit("draw:start",{mode:this.currentMode,coordinate:e}),this.currentMode==="point"){this.finishDrawing();return}this.updateTempFeatures(e,n)}}handleMapDblClick(e){if(!this.currentMode)return;const n=this.currentMode==="select"?this.pickable(e.features):[];if(n.length>0){const r=n[0];if(r.id!==void 0&&r.layerId){this.startEdit(r.layerId,r.id);return}}if(this.isDrawing&&(this.currentMode==="line"||this.currentMode==="polygon"||this.currentMode==="select-polygon")){if(this.activeCoordinates.length>1){const r=this.activeCoordinates[this.activeCoordinates.length-1],s=this.activeCoordinates[this.activeCoordinates.length-2];r[0]===s[0]&&r[1]===s[1]&&this.activeCoordinates.pop()}this.finishDrawing()}}handleContextMenu(e){this.currentMode&&(e.originalEvent&&e.originalEvent.preventDefault(),this.isDrawing&&((this.currentMode==="polygon"||this.currentMode==="select-polygon")&&this.activeCoordinates.length>=3||this.currentMode==="line"&&this.activeCoordinates.length>=2?this.finishDrawing():this.cancel()))}handleMouseMove(e){if(this.pointPick){const a=this.pointPick.basePoint??null,{coordinate:l,snap:h,constraint:f}=this.resolveCursor(e.coordinate,a);this.updateTrackingAcquisition(h),this.lastCursorCoord=l,this.lastConstraint=f,a&&this.emitMeasure(a,l,f),this.emit("draw:move",{coordinate:l,isSnapped:!!h,snapResult:h||void 0}),this.updatePickPreview(l,h);return}if(this.dragSelectStart&&Math.hypot(e.point.x-this.dragSelectStart.point.x,e.point.y-this.dragSelectStart.point.y)>4){this.isDragSelecting=!0;const l=xe(this.mapAdapter);l&&l.dragPan&&l.dragPan.isEnabled()&&l.dragPan.disable(),this.updateDragBoxPreview(this.dragSelectStart.coord,e.coordinate);const h=Math.min(this.dragSelectStart.coord[0],e.coordinate[0]),f=Math.max(this.dragSelectStart.coord[0],e.coordinate[0]),d=Math.min(this.dragSelectStart.coord[1],e.coordinate[1]),p=Math.max(this.dragSelectStart.coord[1],e.coordinate[1]),y=Pe([[[h,d],[f,d],[f,p],[h,p],[h,d]]]),_=this.queryFeaturesInGeometry(y);this.selectionOverlay.previewSelection(_.map(L=>L.feature));const E=Co([h,d],[f,d]),w=Co([h,d],[h,p]);this.emit("selection:drag-progress",{widthMeters:Math.round(E*10)/10,heightMeters:Math.round(w*10)/10,count:_.length,coordinate:e.coordinate});return}if(this.currentMode==="select"||this.currentMode==="modify"){const a=this.pickable(e.features)[0]??null,l=xe(this.mapAdapter),h=l&&typeof l.getCanvas=="function"?l.getCanvas():null;if(a&&a.id!==void 0&&a.layerId){const f=this.dataSource.getLayer(a.layerId),d=f==null?void 0:f.getFeature(a.id);this.selectionOverlay.setHoverFeature(d||a),h&&(h.style.cursor="pointer")}else this.selectionOverlay.setHoverFeature(null),h&&(h.style.cursor="default");return}if(!this.currentMode)return;const n=this.isDrawing&&this.activeCoordinates.length>0?this.activeCoordinates[this.activeCoordinates.length-1]:null,{coordinate:r,snap:s,constraint:o}=this.resolveCursor(e.coordinate,n,this.getInProgressSnapCoords());this.isDrawModeActive()&&this.updateTrackingAcquisition(s),this.lastCursorCoord=r,this.lastConstraint=o,n&&this.emitMeasure(n,r,o),this.emit("draw:move",{coordinate:r,isSnapped:!!s,snapResult:s||void 0}),this.updateTempFeatures(r,s)}emitMeasure(e,n,r){const s=Qe(e,n,this.inputFrame),o=Qe(e,n,{convention:"bearing",ucsRotationDeg:0});this.emit("draw:measure",{distanceMeters:Math.round(s.distance*1e3)/1e3,bearingDegrees:Math.round(o.angle*100)/100,angle:Math.round(s.angle*100)/100,constraint:(r==null?void 0:r.mode)??null,coordinate:n})}updatePickPreview(e,n){var l;const r=xe(this.mapAdapter),s=r&&typeof r.getSource=="function"?r.getSource(this.tempSourceId):null;if(!s||typeof s.setData!="function")return;const o=[];n&&o.push(Lt(n.coordinate,{isSnap:!0,snapType:n.type}));const a=(l=this.pointPick)==null?void 0:l.basePoint;a&&(o.push(Lt(a,{isSnap:!1})),o.push(ae([a,e])),o.push(...this.trackingFeatures(e))),s.setData({type:"FeatureCollection",features:o})}finishDrawing(){if(this.grips.getIsEditing()||this.currentMode==="modify"){const r=this.grips.getActiveFeature(),s=this.grips.activeLayerId||this.targetLayerId||this.dataSource.getActiveLayerId()||"";return this.stopEdit(),(this.currentMode==="modify"||this.currentMode==="select")&&this.resetDrawingState(!1),r&&this.emit("draw:complete",{mode:"modify",layerId:s,feature:r}),r||null}if(!this.currentMode||this.activeCoordinates.length===0)return null;let e=null;const n=[...this.activeCoordinates];if(this.currentMode==="line"&&n.length<2||(this.currentMode==="polygon"||this.currentMode==="select-polygon")&&n.length<3||(this.currentMode==="circle"||this.currentMode==="rectangle"||this.currentMode==="select-box")&&n.length<2)return null;if(this.currentMode==="point")e=Lt(n[0],{name:`Point ${new Date().toLocaleTimeString()}`,createdAt:new Date().toISOString()});else if(this.currentMode==="line"){const r=ku(n,this.activeBulges,this.sagToleranceMeters),s=r?Pu(r):n;e=ae(s,Df({name:`Line ${new Date().toLocaleTimeString()}`,lengthMeters:this.curveLengthMeters(r,s),createdAt:new Date().toISOString()},r))}else if(this.currentMode==="polygon"){const r=[...n],s=r[0],o=r[r.length-1];(s[0]!==o[0]||s[1]!==o[1])&&r.push(s);const a=ku(r,[...this.activeBulges,0],this.sagToleranceMeters),l=a?Pu(a):r;e=Pe([l],Df({name:`Polygon ${new Date().toLocaleTimeString()}`,areaM2:Xu(Pe([l])),createdAt:new Date().toISOString()},a))}else if(this.currentMode==="circle"){const r=n[0],s=sn(Lt(r),Lt(n[1]),{units:"meters"});e=G_(r,s,{units:"meters",steps:64,properties:{name:`Circle ${new Date().toLocaleTimeString()}`,shape:"circle",radiusMeters:s,createdAt:new Date().toISOString()}})}else if(this.currentMode==="rectangle"){const r=n[0],s=n[1],o=Math.min(r[0],s[0]),a=Math.max(r[0],s[0]),l=Math.min(r[1],s[1]),h=Math.max(r[1],s[1]);e=Pe([[[o,l],[a,l],[a,h],[o,h],[o,l]]],{name:`Rectangle ${new Date().toLocaleTimeString()}`,shape:"rectangle",createdAt:new Date().toISOString()})}else if(this.currentMode==="select-box"){const r=n[0],s=n[1],o=Math.min(r[0],s[0]),a=Math.max(r[0],s[0]),l=Math.min(r[1],s[1]),h=Math.max(r[1],s[1]),f=Pe([[[o,l],[a,l],[a,h],[o,h],[o,l]]]);return this.executeDrawSelection("select-box",f,!1),this.resetDrawingState(!0),null}else if(this.currentMode==="select-polygon"){const r=[...n],s=r[0],o=r[r.length-1];(s[0]!==o[0]||s[1]!==o[1])&&r.push(s);const a=Pe([r]);return this.executeDrawSelection("select-polygon",a,!1),this.resetDrawingState(!0),null}if(e){const r=this.currentMode,s=this.resolveTargetLayerId(r,this.targetLayerId||void 0),o=this.dataSource.addFeature(s,e);return this.resetDrawingState(!0),this.emit("draw:complete",{mode:r,feature:o,layerId:s}),o}return this.resetDrawingState(!0),null}resetDrawingState(e=!0){var n;if(this.isDrawing=!1,this.clearTrackingPoints(),this.lastConstraint=null,this.activeCoordinates=[],this.activeBulges=[],this.arcSegment=!1,this.arcSweepRadians=null,this.clearTempFeatures(),this.selectionOverlay.setHoverFeature(null),this.selectionOverlay.syncSelectionOverlay(),e&&this.currentMode!==null){this.currentMode=null,this.targetLayerId=null;try{(n=this.mapAdapter)!=null&&n.isReady&&(typeof this.mapAdapter.setDoubleClickZoom=="function"&&this.mapAdapter.setDoubleClickZoom(!0),this.applyCursor())}catch(r){Ht("OFSDrawTools.resetDrawingState",r)}this.emit("draw:mode-change",{mode:null})}}cancel(){this.pointPick=null;const e=this.grips.getIsEditing()||this.currentMode==="modify";if(e){this.stopEdit(),this.resetDrawingState(!1),this.emit("draw:cancel",{mode:"modify"});return}const n=this.currentMode,r=this.isDrawing;this.resetDrawingState(!0),(e||n||r)&&this.emit("draw:cancel",{mode:n||"modify"})}drawPointByCoords(e,n,r={}){const s=Lt(e,r),o=n||this.dataSource.getActiveLayerId()||"points";return this.dataSource.hasLayer(o)||this.dataSource.addLayer({id:o,name:"Points",type:"point"}),this.dataSource.addFeature(o,s)}drawLineByCoords(e,n,r={}){const s=ae(e,r),o=n||this.dataSource.getActiveLayerId()||"lines";return this.dataSource.hasLayer(o)||this.dataSource.addLayer({id:o,name:"Lines",type:"line"}),this.dataSource.addFeature(o,s)}drawPolygonByCoords(e,n,r={}){const s=[...e],o=s[0],a=s[s.length-1];(o[0]!==a[0]||o[1]!==a[1])&&s.push(o);const l=Pe([s],r),h=n||this.dataSource.getActiveLayerId()||"polygons";return this.dataSource.hasLayer(h)||this.dataSource.addLayer({id:h,name:"Polygons",type:"polygon"}),this.dataSource.addFeature(h,l)}splitPolygon(e,n,r){const s=this.dataSource.getFeature(e,n);if(!s)return null;let o=null;if(r!==void 0){if(o=this.dataSource.getFeature(e,r),!o)for(const l of this.dataSource.getAllLayers()){const h=l.getFeature(r);if(h&&(h.geometry.type==="LineString"||h.geometry.type==="MultiLineString")){o=h;break}}}else{const l=je(s);for(const h of this.dataSource.getAllLayers())if(o=h.queryBBox(l).find(f=>f.id!==n&&f.geometry.type==="LineString"&&Yo(s,f))||null,o)break}if(!o)return null;const a=ce.splitPolygonByLine(s,o);return a&&a.length>1?(this.dataSource.runTransaction(`Split polygon ${n} into ${a.length} parts`,()=>{this.dataSource.removeFeature(e,n),a.forEach((l,h)=>{l.id=this.dataSource.getAvailableFeatureId(e,`${n}_part_${h+1}`),l.properties={...s.properties||{},_split:h+1},this.dataSource.addFeature(e,l)})}),a):null}splitOverlappingPolygons(e,n,r){return this.dataSource.splitOverlapping(e,n,r)}splitLine(e,n,r){const s=this.dataSource.getFeature(e,n);if(!s||s.geometry.type!=="LineString")return null;let o=r;if(typeof r=="string"||typeof r=="number"){let l=this.dataSource.getFeature(e,r)||null;if(!l)for(const h of this.dataSource.getAllLayers()){const f=h.getFeature(r);if(f){l=f;break}}if(!l)return null;o=l}const a=ce.splitLine(s,o);return a&&a.length>1?(this.dataSource.runTransaction(`Split line ${n} into ${a.length} segments`,()=>{this.dataSource.removeFeature(e,n),a.forEach((l,h)=>{l.id=this.dataSource.getAvailableFeatureId(e,`${n}_seg_${h+1}`),l.properties={...s.properties||{},_split:h+1},this.dataSource.addFeature(e,l)})}),a):null}joinLines(e,n,r,s=15){var h;const o=this.dataSource.getFeature(e,n);let a=this.dataSource.getFeature(e,r);if(!a)for(const f of this.dataSource.getAllLayers()){const d=f.getFeature(r);if(d&&d.geometry.type==="LineString"){a=d;break}}if(!o||!a||o.geometry.type!=="LineString"||a.geometry.type!=="LineString")return null;const l=ce.connectLines([o,a],s,!0);return l?(l.id=n,this.dataSource.runTransaction(`Join lines ${n} and ${r}`,()=>{this.dataSource.updateFeature(e,l),this.dataSource.removeFeature(e,r)}),this.grips.getIsEditing()&&((h=this.grips.getActiveFeature())==null?void 0:h.id)===n&&this.grips.editFeature(e,n),l):null}offsetFeature(e,n,r,s=!1){var l;const o=this.dataSource.getFeature(e,n);if(!o)return null;const a=ce.offset(o,r);if(a)if(s){const h=this.dataSource.getAvailableFeatureId(e);return a.id=h,a.properties&&(a.properties={...a.properties,name:`${a.properties.name||"Feature"} (Offset ${r>0?"+":""}${r}m)`}),this.dataSource.addFeature(e,a)}else return a.id=n,this.dataSource.updateFeature(e,a),this.grips.getIsEditing()&&((l=this.grips.getActiveFeature())==null?void 0:l.id)===n&&this.grips.editFeature(e,n),a;return null}rotateFeature(e,n,r,s){const o=this.dataSource.getFeature(e,n);if(!o)return null;const a=ce.rotate(o,r,s);return a.id=n,this.dataSource.updateFeature(e,a),a}scaleFeature(e,n,r,s){const o=this.dataSource.getFeature(e,n);if(!o)return null;const a=ce.scale(o,r,s);return a.id=n,this.dataSource.updateFeature(e,a),a}explodeFeature(e,n){const r=this.dataSource.getFeature(e,n);if(!r||r.geometry.type!=="Polygon"&&r.geometry.type!=="MultiPolygon")return null;const s=ce.explode(r);return s.length>0?(this.dataSource.runTransaction(`Explode polygon ${n} into ${s.length} lines`,()=>{this.dataSource.removeFeature(e,n),s.forEach(o=>this.dataSource.addFeature(e,o))}),s):null}filletFeature(e,n,r,s=5){const o=this.dataSource.getFeature(e,n);if(!o)return null;const a=ce.fillet(o,r,s);return a?(a.id=n,this.dataSource.updateFeature(e,a),a):null}curveFeatureSegment(e,n,r,s){const o=this.dataSource.getFeature(e,n);if(!o)return null;const a=g0(o,r,s);return a?(a.id=n,this.dataSource.updateFeature(e,a),a):null}getFeatureCurveSegments(e,n){const r=Od(this.dataSource.getFeature(e,n));if(!r)return[];const s=ei(r.vertices);return Bf(r.vertices,r.bulges,r.sagToleranceMeters,s).map(o=>({index:o.segmentIndex,curved:o.curved,coordinate:o.coordinate,sagMeters:o.curved?s.distance(r.vertices[o.segmentIndex],r.vertices[o.segmentIndex+1])*Math.abs(r.bulges[o.segmentIndex])/2:0}))}startEdit(e,n){return this.dataSource.getFeature(e,n)?(this.dataSource.selectFeature(e,n),this.grips.editFeature(e,n),this.currentMode!=="modify"&&(this.currentMode="modify",this.emit("draw:mode-change",{mode:"modify"})),!0):!1}stopEdit(){this.grips.clear(),this.currentMode==="modify"&&(this.currentMode="select",this.emit("draw:mode-change",{mode:"select"}))}isEditing(){return this.grips.getIsEditing()}getActiveEditingFeature(){return this.grips.getActiveFeature()}getActiveEditingLayerId(){return this.grips.getActiveLayerId()}getActiveEditingFeatureId(){return this.grips.getActiveFeatureId()}updateGeometry(e,n,r){var l;const s=this.dataSource.getFeature(e,n);if(!s)return!1;const o={...s,geometry:r},a=this.dataSource.updateFeature(e,o);return a&&this.grips.getIsEditing()&&((l=this.grips.getActiveFeature())==null?void 0:l.id)===n&&this.grips.editFeature(e,n),a}moveFeature(e,n,r,s){var l;const o=this.dataSource.getFeature(e,n);if(!o)return null;const a=ce.translate(o,r,s);return a.id=n,this.dataSource.updateFeature(e,a),this.grips.getIsEditing()&&((l=this.grips.getActiveFeature())==null?void 0:l.id)===n&&this.grips.editFeature(e,n),a}moveFeatureByOffset(e,n,r,s){var l;const o=this.dataSource.getFeature(e,n);if(!o)return null;const a=ce.translateByOffset(o,r,s);return a.id=n,this.dataSource.updateFeature(e,a),this.grips.getIsEditing()&&((l=this.grips.getActiveFeature())==null?void 0:l.id)===n&&this.grips.editFeature(e,n),a}copyFeature(e,n,r,s){const o=this.dataSource.getFeature(e,n);if(!o)return null;const a=ce.translateByOffset(o,r,s),l=this.dataSource.getAvailableFeatureId(e,`${n}_copy`);return a.id=l,a.properties&&(a.properties={...a.properties,name:`${a.properties.name||"Feature"} (Copy)`}),this.dataSource.addFeature(e,a)}copyFeatureByDistance(e,n,r,s){var l;const o=this.dataSource.getFeature(e,n);if(!o)return null;const a=ce.translate(o,r,s);return a.id=this.dataSource.getAvailableFeatureId(e,`${n}_copy`),a.properties={...a.properties||{},name:`${((l=a.properties)==null?void 0:l.name)||"Feature"} (Copy)`},this.dataSource.addFeature(e,a)}transformFeatures(e,n,r,s=!1){const o=[];this.dataSource.runTransaction(n,()=>{for(const{layerId:h,featureId:f}of e){const d=this.dataSource.getFeature(h,f);if(!d)continue;const p=r(d);s?(p.id=this.dataSource.getAvailableFeatureId(h,`${f}_copy`),o.push(this.dataSource.addFeature(h,p))):(p.id=d.id,this.dataSource.updateFeature(h,p),o.push(this.dataSource.getFeature(h,d.id)))}});const a=this.grips.getIsEditing()?this.grips.getActiveFeature():null,l=this.grips.getActiveLayerId();return!s&&a&&l&&e.some(h=>h.layerId===l&&h.featureId===a.id)&&this.grips.editFeature(l,a.id),o}findLineAt(e,n=12){return this.findFeatureAt(e,{tolerancePixels:n,types:["LineString"]})}findFeatureAt(e,n={}){var d;const r=n.tolerancePixels??12,s=n.types??["LineString","Polygon"],o=xe(this.mapAdapter),a=o&&typeof o.project=="function";let l=2/111320/Math.max(.1,Math.cos(e[1]*Math.PI/180));if(a&&typeof o.unproject=="function"){const p=o.project(e),y=o.unproject([p.x+r,p.y+r]),_=Array.isArray(y)?y[0]:y.lng,E=Array.isArray(y)?y[1]:y.lat;l=Math.max(Math.abs(_-e[0]),Math.abs(E-e[1]))}const h=p=>{let y=null;for(const _ of p){if(_.length<2)continue;const E=js(_,e);let w;if(a){const L=o.project(e),b=o.project(E.coordinate);if(w=Math.hypot(L.x-b.x,L.y-b.y),w>r)continue}else if(w=Co(e,E.coordinate),w>2)continue;(y===null||w<y)&&(y=w)}return y};let f=null;for(const p of this.dataSource.getAllLayers().filter(y=>y.visible))for(const y of p.queryNear(e,l)){const _=(d=y.geometry)==null?void 0:d.type;let E=null;_==="LineString"&&s.includes("LineString")?E=h([y.geometry.coordinates]):_==="Polygon"&&s.includes("Polygon")&&(E=h(y.geometry.coordinates),E===null&&Zt(e,y)&&(E=r+1)),E!==null&&(!f||E<f.distance)&&(f={layerId:p.id,feature:y,distance:E})}return f}breakLineAt(e,n){const r=this.findLineAt(e);if(!r)return null;const{layerId:s,feature:o}=r,a=F8(o.geometry.coordinates,e,n);return this.replaceLineWithPieces(s,o,a,`Break line ${o.id}`)}lengthenLineAt(e,n,r){const s=this.findLineAt(e);if(!s)return null;const o=s.feature.geometry.coordinates,a=Eb(o),l=n==="delta"?r:n==="total"?r-a:a*r/100-a;if(n!=="delta"&&r<=0)throw new Error("Length must be greater than 0.");const h=$8(o,e,l);if(!h)throw new Error(`Cannot shorten by ${Math.abs(l).toFixed(3)} m: the line is only ${a.toFixed(3)} m long.`);return this.dataSource.updateFeature(s.layerId,{...s.feature,geometry:{type:"LineString",coordinates:h}}),this.dataSource.getFeature(s.layerId,s.feature.id)}offsetAt(e,n,r){const s=this.findFeatureAt(e);if(!s)throw new Error("No line or polygon under the pick point.");const{layerId:o,feature:a}=s,l=a.geometry;let h;if(l.type==="LineString"){const p=l.coordinates,y=js(p,n),_={convention:"cad",ucsRotationDeg:0},E=Qe(p[y.segmentIndex],p[y.segmentIndex+1],_).angle,w=Qe(y.coordinate,n,_),L=r==="through"?w.distance:Math.abs(r),b=((w.angle-E)%360+360)%360;h=b>0&&b<180?-L:L}else{const p=l.coordinates,y=Math.min(...p.map(E=>Qe(js(E,n).coordinate,n).distance)),_=r==="through"?y:Math.abs(r);h=Zt(n,a)?-_:_}if(!(Math.abs(h)>0))throw new Error("Offset distance must be greater than 0.");const f=ce.offset(a,h);if(!f)throw new Error(`Offset of ${Math.abs(h).toFixed(3)} m collapses the shape.`);f.id=this.dataSource.getAvailableFeatureId(o,`${a.id}_offset`),f.properties={...a.properties||{}};const d=this.dataSource.addFeature(o,f);return{layerId:o,source:a,result:d}}replaceLineWithPieces(e,n,r,s){const o=[];return this.dataSource.runTransaction(s,()=>{if(r.length===0){this.dataSource.removeFeature(e,n.id);return}this.dataSource.updateFeature(e,{...n,geometry:{type:"LineString",coordinates:r[0]}}),o.push(this.dataSource.getFeature(e,n.id)),r.slice(1).forEach(a=>{o.push(this.dataSource.addFeature(e,{type:"Feature",id:this.dataSource.getAvailableFeatureId(e,`${n.id}_seg`),properties:{...n.properties||{}},geometry:{type:"LineString",coordinates:a}}))})}),{layerId:e,featureId:n.id,pieces:o}}boundarySegments(e,n){const r=[];for(const s of this.dataSource.getAllLayers().filter(o=>o.visible)){const o=n?s.queryBBox(n):s.getFeatures();for(const a of o)e&&s.id===e.layerId&&a.id===e.featureId||a.geometry&&r.push(..._b(a.geometry))}return r}trimLineAt(e){const n=this.findLineAt(e);if(!n)return null;const{layerId:r,feature:s}=n,o=s.geometry.coordinates,a=je(s),l=R8(o,this.boundarySegments({layerId:r,featureId:s.id},a),e);return l?this.replaceLineWithPieces(r,s,l,`Trim line ${s.id}`):null}extendLineAt(e){const n=this.findLineAt(e);if(!n)return null;const{layerId:r,feature:s}=n,o=A8(s.geometry.coordinates,this.boundarySegments({layerId:r,featureId:s.id}),e);return o?(this.dataSource.updateFeature(r,{...s,geometry:{type:"LineString",coordinates:o}}),{layerId:r,feature:this.dataSource.getFeature(r,s.id)}):null}filletLinesAt(e,n,r){const s=this.findLineAt(e),o=this.findLineAt(n);if(!s||!o)throw new Error("Pick two lines.");if(s.layerId===o.layerId&&s.feature.id===o.feature.id)throw new Error("Pick two different lines.");const a=O8(s.feature.geometry.coordinates,e,o.feature.geometry.coordinates,n,r);if(!a)throw new Error(r>0?`Cannot fillet with radius ${r} m: the lines are parallel or too short for this radius.`:"Cannot fillet: the picked segments are parallel.");let l=null;return this.dataSource.runTransaction(`Fillet lines ${s.feature.id} and ${o.feature.id}`,()=>{this.dataSource.updateFeature(s.layerId,{...s.feature,geometry:{type:"LineString",coordinates:a.line1}}),this.dataSource.updateFeature(o.layerId,{...o.feature,geometry:{type:"LineString",coordinates:a.line2}}),a.arc&&(l=this.dataSource.addFeature(s.layerId,{type:"Feature",id:this.dataSource.getAvailableFeatureId(s.layerId,`${s.feature.id}_fillet`),properties:{name:`Fillet R${r}m`,shape:"arc",radiusMeters:r},geometry:{type:"LineString",coordinates:a.arc}}))}),{lines:[this.dataSource.getFeature(s.layerId,s.feature.id),this.dataSource.getFeature(o.layerId,o.feature.id)],arc:l}}stretch(e,n,r,s,o){const a=[Math.min(e[0],n[0]),Math.min(e[1],n[1]),Math.max(e[0],n[0]),Math.max(e[1],n[1])],l=o??this.dataSource.getAllLayers().filter(d=>d.visible).flatMap(d=>d.queryBBox(a).map(p=>({layerId:d.id,featureId:p.id}))),h=[];let f=0;return this.dataSource.runTransaction("Stretch",()=>{for(const{layerId:d,featureId:p}of l){const y=this.dataSource.getFeature(d,p);if(!(y!=null&&y.geometry))continue;const{geometry:_,moved:E}=vb(y.geometry,a,r,s);E!==0&&(f+=E,this.dataSource.updateFeature(d,{...y,geometry:_}),h.push(this.dataSource.getFeature(d,p)))}}),{features:h,movedVertices:f}}deleteFeature(e,n){var r;return this.grips.getIsEditing()&&((r=this.grips.getActiveFeature())==null?void 0:r.id)===n&&this.grips.clear(),this.dataSource.removeFeature(e,n)}updateVertex(e,n,r,s,o=0){const a=this.dataSource.getFeature(e,n);if(!a)return!1;if(a.geometry.type==="Point"){const l=Lt(s,a.properties);return l.id=n,this.dataSource.updateFeature(e,l)}else if(a.geometry.type==="LineString"){const l=[...a.geometry.coordinates];if(r<0||r>=l.length)return!1;l[r]=s;const h=ae(l,a.properties);return h.id=n,this.dataSource.updateFeature(e,h)}else if(a.geometry.type==="Polygon"){const l=a.geometry.coordinates.map(d=>[...d]);if(o<0||o>=l.length)return!1;const h=l[o];if(r<0||r>=h.length)return!1;h[r]=s,r===0&&(h[h.length-1]=s);const f=Pe(l,a.properties);return f.id=n,this.dataSource.updateFeature(e,f)}return!1}insertVertex(e,n,r,s,o=0){const a=this.dataSource.getFeature(e,n);if(!a)return!1;if(a.geometry.type==="LineString"){const l=[...a.geometry.coordinates],h=s!==void 0?Math.min(Math.max(0,s),l.length):l.length;l.splice(h,0,r);const f=ae(l,a.properties);return f.id=n,this.dataSource.updateFeature(e,f)}else if(a.geometry.type==="Polygon"){const l=a.geometry.coordinates.map(p=>[...p]);if(o<0||o>=l.length)return!1;const h=l[o],f=s!==void 0?Math.min(Math.max(0,s),h.length-1):h.length-1;h.splice(f,0,r);const d=Pe(l,a.properties);return d.id=n,this.dataSource.updateFeature(e,d)}return!1}deleteVertex(e,n,r,s=0){var a;if(this.grips.getIsEditing()&&((a=this.grips.getActiveFeature())==null?void 0:a.id)===n)return this.grips.deleteVertex(r,s);const o=this.dataSource.getFeature(e,n);if(!o)return!1;if(o.geometry.type==="LineString"){const l=[...o.geometry.coordinates];if(l.length<=2||r<0||r>=l.length)return!1;l.splice(r,1);const h=ae(l,o.properties);return h.id=n,this.dataSource.updateFeature(e,h)}else if(o.geometry.type==="Polygon"){const l=o.geometry.coordinates.map(d=>[...d]);if(s<0||s>=l.length)return!1;const h=l[s];if(h.length<=4||r<0||r>=h.length-1)return!1;h.splice(r,1),r===0&&(h[h.length-1]=h[0]);const f=Pe(l,o.properties);return f.id=n,this.dataSource.updateFeature(e,f)}return!1}simplifyFeature(e,n,r=1e-4){var a;const s=this.dataSource.getFeature(e,n);if(!s)return null;const o=ce.simplify(s,r);return o.id=n,this.dataSource.updateFeature(e,o),this.grips.getIsEditing()&&((a=this.grips.getActiveFeature())==null?void 0:a.id)===n&&this.grips.editFeature(e,n),o}smoothFeature(e,n,r=32){var a;const s=this.dataSource.getFeature(e,n);if(!s||s.geometry.type!=="LineString")return null;const o=ce.smoothLineBezier(s,r);return o.id=n,this.dataSource.updateFeature(e,o),this.grips.getIsEditing()&&((a=this.grips.getActiveFeature())==null?void 0:a.id)===n&&this.grips.editFeature(e,n),o}reverseLine(e,n){var o;const r=this.dataSource.getFeature(e,n);if(!r||r.geometry.type!=="LineString")return null;const s=ce.reverse(r);return s.id=n,this.dataSource.updateFeature(e,s),this.grips.getIsEditing()&&((o=this.grips.getActiveFeature())==null?void 0:o.id)===n&&this.grips.editFeature(e,n),s}differenceFeature(e,n,r){const s=this.dataSource.getFeature(e,n),o=this.dataSource.getFeature(e,r);if(!s||!o)return null;const a=ce.difference(s,o);return a?(a.id=n,this.dataSource.updateFeature(e,a),a):null}intersectFeatures(e,n,r){const s=this.dataSource.getFeature(e,n),o=this.dataSource.getFeature(e,r);if(!s||!o)return null;const a=ce.intersect(s,o);if(a){const l=this.dataSource.getAvailableFeatureId(e,"intersect");return a.id=l,this.dataSource.addFeature(e,a),a}return null}applyCursor(){if(typeof this.mapAdapter.getRawMap=="function")try{const e=this.mapAdapter.getRawMap();if(!e||typeof e.getCanvas!="function"||!e.getCanvas())return;const n=this.pointPick?"crosshair":this.currentMode?Y8[this.currentMode]??"crosshair":"";e.getCanvas().style.cursor=n}catch(e){Ht("OFSDrawTools.applyCursor",e)}}guideFont(){var e,n;return this.guides.font??((n=(e=this.mapAdapter).getStyleFont)==null?void 0:n.call(e))??z8}getGuides(){return{...this.guides}}setGuides(e){if(this.guides={...this.guides,...e},"font"in e){const n=xe(this.mapAdapter);U8.forEach(r=>{var o;const s=`${this.tempSourceId}${r}`;try{(o=n==null?void 0:n.getLayer)!=null&&o.call(n,s)&&n.setLayoutProperty(s,"text-font",this.guideFont())}catch(a){Ht("OFSDrawTools.setGuides",a)}})}return this.lastCursorCoord&&this.updateTempFeatures(this.lastCursorCoord,null),this.getGuides()}crosshairFeatures(e){if(!this.guides.crosshair||typeof this.mapAdapter.getBounds!="function")return[];let n;try{n=this.mapAdapter.getBounds()}catch(f){return Ht("OFSDrawTools.crosshair",f),[]}const[r,s,o,a]=n;if(![r,s,o,a].every(f=>Number.isFinite(f)))return[];const l=(o-r)*.1,h=(a-s)*.1;return[ae([[r-l,e[1]],[o+l,e[1]]],{isGuide:!0}),ae([[e[0],s-h],[e[0],a+h]],{isGuide:!0})]}formatLength(e){return e>=1e3?`${(e/1e3).toFixed(2)} km`:`${e.toFixed(e<10?2:1)} m`}projector(){const e=xe(this.mapAdapter);return e&&typeof e.project=="function"&&typeof e.unproject=="function"?e:null}dimensionFeatures(e,n,r){const s=sn(Lt(e),Lt(n),{units:"meters"});if(s<=0)return[];const o=this.formatLength(s),a=this.projector();if(!a)return[Lt([(e[0]+n[0])/2,(e[1]+n[1])/2],{isLabel:!0,isLive:r,label:o})];try{const l=a.project(e),h=a.project(n),f=h.x-l.x,d=h.y-l.y,p=Math.hypot(f,d);if(p<1)return[];const y=d/p,_=-f/p,E=this.guides.dimensionOffsetPixels,w=(S,P)=>{const N=a.unproject([S.x+y*P,S.y+_*P]);return[N.lng,N.lat]},L=w(l,E),b=w(h,E);return[ae([e,w(l,E+6)],{isDimExt:!0}),ae([n,w(h,E+6)],{isDimExt:!0}),ae([L,b],{isDim:!0,isLive:r,label:o})]}catch(l){return Ht("OFSDrawTools.dimension",l),[Lt([(e[0]+n[0])/2,(e[1]+n[1])/2],{isLabel:!0,isLive:r,label:o})]}}angleFeatures(e,n,r,s){if(!this.guides.angles)return[];const o=this.projector();if(!o)return[];try{const a=o.project(n),l=o.project(e),h=o.project(r);if(Math.hypot(l.x-a.x,l.y-a.y)<4||Math.hypot(h.x-a.x,h.y-a.y)<4)return[];const f=Math.atan2(l.y-a.y,l.x-a.x);let p=Math.atan2(h.y-a.y,h.x-a.x)-f;for(;p>Math.PI;)p-=Math.PI*2;for(;p<=-Math.PI;)p+=Math.PI*2;const y=Math.abs(p*180/Math.PI);if(y<.05)return[];const _=30,E=18,w=[];for(let S=0;S<=E;S++){const P=f+p*S/E,N=o.unproject([a.x+Math.cos(P)*_,a.y+Math.sin(P)*_]);w.push([N.lng,N.lat])}const L=f+p/2,b=o.unproject([a.x+Math.cos(L)*(_+16),a.y+Math.sin(L)*(_+16)]);return[ae(w,{isAngle:!0,isLive:s}),Lt([b.lng,b.lat],{isLabel:!0,isLive:s,label:`${y.toFixed(1)}°`})]}catch(a){return Ht("OFSDrawTools.angleGuide",a),[]}}measurementFeatures(e,n){const r=[];if(e.length<2)return r;const s=n&&e.length>=3?[...e,e[0]]:e,o=s.length-2;if(this.guides.dimensions)for(let a=0;a<s.length-1;a++)!this.guides.segmentLabels&&a!==o||r.push(...this.dimensionFeatures(s[a],s[a+1],a===o));for(let a=1;a<s.length-1;a++){const l=a===s.length-2;!this.guides.segmentLabels&&!l||r.push(...this.angleFeatures(s[a-1],s[a],s[a+1],l))}if(n&&s.length>=4&&this.guides.segmentLabels&&r.push(...this.angleFeatures(s[s.length-2],s[0],s[1],!1)),this.guides.areaLabel&&n&&e.length>=3){const a=Pe([[...e,e[0]]]),l=Xu(a);if(l>0){const h=Uw(a).geometry.coordinates;r.push(Lt(h,{isLabel:!0,isLive:!0,label:`${l.toFixed(1)} m²`}))}}return r}updateTempFeatures(e,n){const r=xe(this.mapAdapter);if(!r||typeof r.getSource!="function")return;const s=r.getSource(this.tempSourceId);if(!s||typeof s.setData!="function")return;const o=[];if(n&&n.coordinate&&o.push(Lt(n.coordinate,{isSnap:!0,snapType:n.type})),this.isDrawing&&this.activeCoordinates.length>0){const a=[...this.activeCoordinates,e];if(this.activeCoordinates.forEach(h=>{o.push(Lt(h,{isSnap:!1}))}),n||o.push(Lt(e,{isSnap:!1})),this.currentMode==="line"&&a.length>=2)o.push(ae(this.previewCoordinates(e)));else if((this.currentMode==="polygon"||this.currentMode==="select-polygon")&&a.length>=2){const h=this.previewCoordinates(e);o.push(ae(h)),a.length>=3&&o.push(Pe([[...h,h[0]]]))}else if(this.currentMode==="circle"&&a.length>=2){const h=sn(Lt(a[0]),Lt(e),{units:"meters"});o.push(G_(a[0],h,{units:"meters"}))}else if((this.currentMode==="rectangle"||this.currentMode==="select-box")&&a.length>=2){const h=a[0],f=e,d=Math.min(h[0],f[0]),p=Math.max(h[0],f[0]),y=Math.min(h[1],f[1]),_=Math.max(h[1],f[1]);o.push(Pe([[[d,y],[p,y],[p,_],[d,_],[d,y]]]))}o.push(...this.trackingFeatures(e));const l=this.currentMode==="polygon"||this.currentMode==="select-polygon";if(this.currentMode!=="circle"&&this.currentMode!=="rectangle"&&this.currentMode!=="select-box")o.push(...this.measurementFeatures(a,l));else if(this.currentMode==="circle"){const h=sn(Lt(a[0]),Lt(e),{units:"meters"});this.guides.dimensions&&h>0&&o.push(Lt([(a[0][0]+e[0])/2,(a[0][1]+e[1])/2],{isLabel:!0,isLive:!0,label:`r ${this.formatLength(h)}`}))}else{const h=[a[0],[e[0],a[0][1]],e,[a[0][0],e[1]]];o.push(...this.measurementFeatures(h,!0))}o.push(...this.crosshairFeatures(this.guides.anchor==="vertex"?this.activeCoordinates[this.activeCoordinates.length-1]:e))}else this.currentMode==="point"&&o.push(Lt(e,{isSnap:!1})),o.push(...this.trackingFeatures(e)),o.push(...this.crosshairFeatures(e));s.setData({type:"FeatureCollection",features:o})}updateDragBoxPreview(e,n){const r=xe(this.mapAdapter);if(!r||typeof r.getSource!="function")return;const s=r.getSource(this.tempSourceId);if(!s||typeof s.setData!="function")return;const o=Math.min(e[0],n[0]),a=Math.max(e[0],n[0]),l=Math.min(e[1],n[1]),h=Math.max(e[1],n[1]),f=Pe([[[o,l],[a,l],[a,h],[o,h],[o,l]]]);s.setData({type:"FeatureCollection",features:[f]})}pickable(e){return e!=null&&e.length?this.targetLayerId?e.filter(n=>n.layerId===this.targetLayerId):e:[]}queryFeaturesInGeometry(e){const n=[],r=this.dataSource.getAllLayers().filter(s=>s.visible);for(const s of r)if(!(this.targetLayerId&&s.id!==this.targetLayerId))for(const o of jo.queryGeometry(s,e))o.id!==void 0&&n.push({layerId:s.id,feature:o});return n}executeDrawSelection(e,n,r=!1){const s=this.queryFeaturesInGeometry(n);r||this.dataSource.clearSelection();const o=new Map;for(const a of s)if(a.feature.id!==void 0){const l=o.get(a.layerId)||[];l.push(a.feature.id),o.set(a.layerId,l)}for(const[a,l]of o.entries())this.dataSource.selectFeatures(a,l,!0);this.dataSource.getSelectedCount()===1&&s.length===1?this.grips.editFeature(s[0].layerId,s[0].feature.id):this.grips.clear(),this.selectionOverlay.syncSelectionOverlay(),this.emit("selection:draw-complete",{mode:e,selectionPolygon:n,selectedFeatures:s.map(a=>a.feature),count:s.length})}flashFeatures(e,n=750){this.selectionOverlay.flashFeatures(e,n)}clearTempFeatures(){if(this.mapAdapter.isReady)try{const e=xe(this.mapAdapter);if(!e||typeof e.getSource!="function")return;const n=e.getSource(this.tempSourceId);n&&typeof n.setData=="function"&&n.setData({type:"FeatureCollection",features:[]})}catch(e){Ht("OFSDrawTools.clearTempFeatures",e)}}destroy(){this.unsubClick&&this.unsubClick(),this.unsubDblClick&&this.unsubDblClick(),this.unsubContextMenu&&this.unsubContextMenu(),this.unsubMove&&this.unsubMove(),this.unsubMouseDown&&this.unsubMouseDown(),this.unsubMouseUp&&this.unsubMouseUp(),typeof window<"u"&&window.removeEventListener("keydown",this.handleKeyDown),this.cancel(),this.grips.clear(),this.preview.destroy(),this.selectionOverlay.destroy(),this.removeAllListeners()}}const Bm={viridis:["#440154","#3b528b","#21918c","#5ec962","#fde725"],magma:["#000004","#51127c","#b73779","#fb8861","#fcfdbf"],blues:["#eff3ff","#bdd7e7","#6baed6","#3182bd","#08519c"],greens:["#edf8e9","#bae4b3","#74c476","#31a354","#006d2c"],oranges:["#feedde","#fdbe85","#fd8d3c","#e6550d","#a63603"],purples:["#f2f0f7","#cbc9e2","#9e9ac8","#756bb1","#54278f"],ylgnbu:["#ffffd9","#c7e9b4","#41b6c4","#225ea8","#081d58"],ylorrd:["#ffffb2","#fecc5c","#fd8d3c","#f03b20","#bd0026"],spectral:["#d7191c","#fdae61","#ffffbf","#abdda4","#2b83ba"],rdylgn:["#d73027","#fc8d59","#fee08b","#d9ef8b","#91cf60","#1a9850"],rdbu:["#ca0020","#f4a582","#f7f7f7","#92c5de","#0571b0"],category10:["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],set1:["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#ffff33","#a65628","#f781bf"],set2:["#66c2a5","#fc8d62","#8da0cb","#e78ac3","#a6d854","#ffd92f","#e5c494","#b3b3b3"],pastel:["#fbb4ae","#b3cde3","#ccebc5","#decbe4","#fed9a6","#ffffcc","#e5d8bd","#fddaec"]},j8={viridis:"sequential",magma:"sequential",blues:"sequential",greens:"sequential",oranges:"sequential",purples:"sequential",ylgnbu:"sequential",ylorrd:"sequential",spectral:"diverging",rdylgn:"diverging",rdbu:"diverging",category10:"qualitative",set1:"qualitative",set2:"qualitative",pastel:"qualitative"},X8=i=>i.split(" ").map(t=>`#${t.toLowerCase()}`),V8={Blues:"f7fbff deebf7 c6dbef 9ecae1 6baed6 4292c6 2171b5 08519c 08306b",BuGn:"f7fcfd e5f5f9 ccece6 99d8c9 66c2a4 41ae76 238b45 006d2c 00441b",BuPu:"f7fcfd e0ecf4 bfd3e6 9ebcda 8c96c6 8c6bb1 88419d 810f7c 4d004b",GnBu:"f7fcf0 e0f3db ccebc5 a8ddb5 7bccc4 4eb3d3 2b8cbe 0868ac 084081",Greens:"f7fcf5 e5f5e0 c7e9c0 a1d99b 74c476 41ab5d 238b45 006d2c 00441b",Greys:"ffffff f0f0f0 d9d9d9 bdbdbd 969696 737373 525252 252525 000000",Oranges:"fff5eb fee6ce fdd0a2 fdae6b fd8d3c f16913 d94801 a63603 7f2704",OrRd:"fff7ec fee8c8 fdd49e fdbb84 fc8d59 ef6548 d7301f b30000 7f0000",PuBu:"fff7fb ece7f2 d0d1e6 a6bddb 74a9cf 3690c0 0570b0 045a8d 023858",PuBuGn:"fff7fb ece2f0 d0d1e6 a6bddb 67a9cf 3690c0 02818a 016c59 014636",PuRd:"f7f4f9 e7e1ef d4b9da c994c7 df65b0 e7298a ce1256 980043 67001f",Purples:"fcfbfd efedf5 dadaeb bcbddc 9e9ac8 807dba 6a51a3 54278f 3f007d",RdPu:"fff7f3 fde0dd fcc5c0 fa9fb5 f768a1 dd3497 ae017e 7a0177 49006a",Reds:"fff5f0 fee0d2 fcbba1 fc9272 fb6a4a ef3b2c cb181d a50f15 67000d",YlGn:"ffffe5 f7fcb9 d9f0a3 addd8e 78c679 41ab5d 238443 006837 004529",YlGnBu:"ffffd9 edf8b1 c7e9b4 7fcdbb 41b6c4 1d91c0 225ea8 253494 081d58",YlOrBr:"ffffe5 fff7bc fee391 fec44f fe9929 ec7014 cc4c02 993404 662506",YlOrRd:"ffffcc ffeda0 fed976 feb24c fd8d3c fc4e2a e31a1c bd0026 800026"},W8={BrBG:"543005 8c510a bf812d dfc27d f6e8c3 f5f5f5 c7eae5 80cdc1 35978f 01665e 003c30",PiYG:"8e0152 c51b7d de77ae f1b6da fde0ef f7f7f7 e6f5d0 b8e186 7fbc41 4d9221 276419",PRGn:"40004b 762a83 9970ab c2a5cf e7d4e8 f7f7f7 d9f0d3 a6dba0 5aae61 1b7837 00441b",PuOr:"7f3b08 b35806 e08214 fdb863 fee0b6 f7f7f7 d8daeb b2abd2 8073ac 542788 2d004b",RdBu:"67001f b2182b d6604d f4a582 fddbc7 f7f7f7 d1e5f0 92c5de 4393c3 2166ac 053061",RdGy:"67001f b2182b d6604d f4a582 fddbc7 ffffff e0e0e0 bababa 878787 4d4d4d 1a1a1a",RdYlBu:"a50026 d73027 f46d43 fdae61 fee090 ffffbf e0f3f8 abd9e9 74add1 4575b4 313695",RdYlGn:"a50026 d73027 f46d43 fdae61 fee08b ffffbf d9ef8b a6d96a 66bd63 1a9850 006837",Spectral:"9e0142 d53e4f f46d43 fdae61 fee08b ffffbf e6f598 abdda4 66c2a5 3288bd 5e4fa2"},H8={Accent:"7fc97f beaed4 fdc086 ffff99 386cb0 f0027f bf5b17 666666",Dark2:"1b9e77 d95f02 7570b3 e7298a 66a61e e6ab02 a6761d 666666",Paired:"a6cee3 1f78b4 b2df8a 33a02c fb9a99 e31a1c fdbf6f ff7f00 cab2d6 6a3d9a ffff99 b15928",Pastel1:"fbb4ae b3cde3 ccebc5 decbe4 fed9a6 ffffcc e5d8bd fddaec f2f2f2",Pastel2:"b3e2cd fdcdac cbd5e8 f4cae4 e6f5c9 fff2ae f1e2cc cccccc",Set3:"8dd3c7 ffffb3 bebada fb8072 80b1d3 fdb462 b3de69 fccde5 d9d9d9 bc80bd ccebc5 ffed6f"},K8={Burg:"ffc6c4 f4a3a8 e38191 cc607d ad466c 8b3058 672044",BurgYl:"fbe6c5 f5ba98 ee8a82 dc7176 c8586c 9c3f5d 70284a",RedOr:"f6d2a9 f5b78e f19c7c ea8171 dd686c ca5268 b13f64",OrYel:"ecda9a efc47e f3ad6a f7945d f97b57 f66356 ee4d5a",Peach:"fde0c5 facba6 f8b58b f59e72 f2855d ef6a4c eb4a40",PinkYl:"fef6b5 ffdd9a ffc285 ffa679 fa8a76 f16d7a e15383",Mint:"e4f1e1 b4d9cc 89c0b6 63a6a0 448c8a 287274 0d585f",BluGrn:"c4e6c3 96d2a4 6dbc90 4da284 36877a 266b6e 1d4f60",DarkMint:"d2fbd4 a5dbc2 7bbcb0 559c9e 3a7c89 235d72 123f5a",Emrld:"d3f2a3 97e196 6cc08b 4c9b82 217a79 105965 074050",ag_GrnYl:"245668 0f7279 0d8f81 39ab7e 6ec574 a9dc67 edef5d",BluYl:"f7feae b7e6a5 7ccba2 46aea0 089099 00718b 045275",Teal:"d1eeea a8dbd9 85c4c9 68abb8 4f90a6 3b738f 2a5674",TealGrn:"b0f2bc 89e8ac 67dba5 4cc8a3 38b2a3 2c98a0 257d98",Purp:"f3e0f7 e4c7f1 d1afe8 b998dd 9f82ce 826dba 63589f",PurpOr:"f9ddda f2b9c4 e597b9 ce78b3 ad5fad 834ba0 573b88",Sunset:"f3e79b fac484 f8a07e eb7f86 ce6693 a059a0 5c53a5",Magenta:"f3cbd3 eaa9bd dd88ac ca699d b14d8e 91357d 6c2167",SunsetDark:"fcde9c faa476 f0746e e34f6f dc3977 b9257a 7c1d6f",ag_Sunset:"4b2991 872ca2 c0369d ea4f88 fa7876 f6a97a edd9a3",BrwnYl:"ede5cf e0c2a2 d39c83 c1766f a65461 813753 541f3f"},Z8={ArmyRose:"798234 a3ad62 d0d3a2 fdfbe4 f0c6c3 df91a3 d46780",Fall:"3d5941 778868 b5b991 f6edbd edbb8a de8a5a ca562c",Geyser:"008080 70a494 b4c8a8 f6edbd edbb8a de8a5a ca562c",Temps:"009392 39b185 9ccb86 e9e29c eeb479 e88471 cf597e",TealRose:"009392 72aaa1 b1c7b3 f1eac8 e5b9ad d98994 d0587e",Tropic:"009b9e 42b7b9 a7d3d4 f1f1f1 e4c1d9 d691c1 c75dab",Earth:"a16928 bd925a d6bd8d edeac2 b5c8b8 79a7ac 2887a1"},J8={Antique:"855c75 d9af6b af6458 736f4c 526a83 625377 68855c 9c9c5e a06177 8c785d 467378 7c7c7c",Bold:"7f3c8d 11a579 3969ac f2b701 e73f74 80ba5a e68310 008695 cf1c90 f97b72 4b4b8f a5aa99",CartoPastel:"66c5cc f6cf71 f89c74 dcb0f2 87c55f 9eb9f3 fe88b1 c9db74 8be0a4 b497e7 d3b484 b3b3b3",Prism:"5f4690 1d6996 38a6a5 0f8554 73af48 edad08 e17c05 cc503e 94346e 6f4070 994e95 666666",Safe:"88ccee cc6677 ddcc77 117733 332288 aa4499 44aa99 999933 882255 661100 6699cc 888888",Vivid:"e58606 5d69b1 52bca3 99c945 cc61b0 24796c daa51b 2f8ac4 764e9f ed645a cc3a8e a5aa99"},Q8={Cividis:"00224e 123570 3b496c 575d6d 707173 8a8678 a59c74 c3b369 e1cc55 fee838",Inferno:"000004 1b0c41 4a0c6b 781c6d a52c60 cf4446 ed6925 fb9b06 f7d13d fcffa4",Plasma:"0d0887 46039f 7201a8 9c179e bd3786 d8576b ed7953 fb9f3a fdca26 f0f921"};function tF(){const i=new Map,t=n=>i.set(n.name.toLowerCase(),n);Object.keys(Bm).forEach(n=>t({name:n,type:j8[n],source:"ofs",colors:[...Bm[n]]}));const e=(n,r,s)=>Object.entries(n).forEach(([o,a])=>{i.has(o.toLowerCase())||t({name:o,type:r,source:s,colors:X8(a)})});return e(V8,"sequential","colorbrewer"),e(W8,"diverging","colorbrewer"),e(H8,"qualitative","colorbrewer"),e(K8,"sequential","carto"),e(Z8,"diverging","carto"),e(J8,"qualitative","carto"),e(Q8,"sequential","matplotlib"),i}const v0=tF();function eF(i){if(i.colors.length===0)throw new Error(`Color ramp "${i.name}" has no colors`);i.colors.forEach(t=>{if(!Vt.valid(t))throw new Error(`Color ramp "${i.name}" has an invalid color: ${t}`)}),v0.set(i.name.toLowerCase(),{...i,colors:[...i.colors]})}function ac(i){return v0.get(i.toLowerCase())}function E0(i){return Array.from(v0.values()).filter(t=>!i||t.type===i)}function nF(i,t){const e=[];for(let n=0;n<i;n++){const r=(t+n)*137.508%360,s=55+(t+n)%3*10;e.push(Vt.lch(s,60,r).hex())}return e}function Ac(i,t,e=!1){if(t<=0)return[];let n,r;if(Array.isArray(i))n=[...i],r="sequential";else{const s=ac(i)??ac("viridis");n=[...s.colors],r=s.type}return e&&n.reverse(),r==="qualitative"?t<=n.length?n.slice(0,t):[...n,...nF(t-n.length,n.length)]:t===1?[n[Math.floor((n.length-1)/2)]]:t===n.length?n:Vt.scale(n).mode("lab").colors(t)}function bb(i,t=!1){return`linear-gradient(90deg, ${Ac(i,9,t).join(", ")})`}const Oc="#3b82f6",Za={kind:"lines",color:Oc,spacing:8,angleDeg:45,lineWidth:1};function Ib(i=Oc){return{fill:{color:i,opacity:.65,style:"solid",outlineColor:"#ffffff",outlineWidth:1.5,outlineOpacity:1},line:{color:i,width:3,opacity:1,cap:"round",join:"round"},marker:{shape:"circle",size:12,color:i,opacity:1,strokeColor:"#ffffff",strokeWidth:1.5,allowOverlap:!0}}}function Da(i){return i===void 0?i:JSON.parse(JSON.stringify(i))}function Sb(i,t){const e=Da(i);return t&&(t.fill&&Object.assign(e.fill,Da(t.fill)),t.line&&Object.assign(e.line,Da(t.line)),t.marker&&Object.assign(e.marker,Da(t.marker))),e}function Qs(i){const t=i.simpleStyle||{},n=t.fillColor??t.circleColor??(i.type==="simple"?i.defaultColor:void 0)??Oc,r=Ib(n);t.circleColor&&(r.marker.color=t.circleColor),t.fillOpacity!==void 0&&(r.fill.opacity=t.fillOpacity),t.strokeColor&&(r.fill.outlineColor=t.strokeColor,r.marker.strokeColor=t.strokeColor),t.strokeWidth!==void 0&&(r.line.width=t.strokeWidth,r.marker.strokeWidth=t.strokeWidth),t.strokeOpacity!==void 0&&(r.line.opacity=t.strokeOpacity),t.circleRadius!==void 0&&(r.marker.size=t.circleRadius*2);const s=Sb(r,i.baseSymbol);return s.fill.style==="pattern"&&!s.fill.pattern&&(s.fill.pattern={...Za,color:s.fill.color}),s}function jh(i,t,e,n){const r=Da(i),s=(n==null?void 0:n.color)??t;s&&(r.fill.color=s,r.line.color=s,r.marker.color=s),r.fill.style==="pattern"&&r.fill.pattern&&(s&&(r.fill.pattern={...r.fill.pattern,color:s}),r.fill.patternBackground&&(r.fill.color=i.fill.color));const o=(n==null?void 0:n.size)??e;return o!==void 0&&(r.line.width=o,r.marker.size=o),n&&(n.opacity!==void 0&&(r.fill.opacity=n.opacity,r.line.opacity=n.opacity,r.marker.opacity=n.opacity),n.strokeColor!==void 0&&(r.fill.outlineColor=n.strokeColor,r.marker.strokeColor=n.strokeColor),n.strokeWidth!==void 0&&(r.fill.outlineWidth=n.strokeWidth,r.marker.strokeWidth=n.strokeWidth),n.pattern===null?(r.fill.style==="pattern"&&(r.fill.style="solid"),delete r.fill.pattern):n.pattern&&(r.fill.style="pattern",r.fill.pattern=Da(n.pattern)),n.shape!==void 0&&(r.marker.shape=n.shape),n.icon!==void 0&&(r.marker.icon=n.icon),n.rotationDeg!==void 0&&(r.marker.rotationDeg=n.rotationDeg)),r}function iF(i,t,e,n){if(i.type!=="graduated"||i.graduatedMode!=="size")return t.map(()=>{});const r=n==="line"?[1,e.line.width*3]:[4,e.marker.size*2],[s,o]=i.sizeRange??r,a=t.length;return t.map((l,h)=>l.size??(a===1?o:s+(o-s)*h/(a-1)))}function w0(i,t){const e=Qs(i),n=[];if(i.type==="graduated"&&i.fieldName&&i.breaks&&i.breaks.length>0){const r=iF(i,i.breaks,e,t),s=i.graduatedMode==="size";i.breaks.forEach((o,a)=>{n.push({index:a,label:o.label,visible:o.visible!==!1,symbol:jh(e,s?void 0:o.color,r[a],o.symbol),min:o.min,max:o.max,count:o.count})})}else if(i.type==="categorical"&&i.fieldName&&i.categories&&i.categories.length>0)i.categories.forEach((r,s)=>{n.push({index:s,label:r.label,visible:r.visible!==!1,symbol:jh(e,r.color,void 0,r.symbol),value:r.value,count:r.count})});else return[{index:0,label:"",visible:!0,symbol:e}];return n.push({index:-1,label:i.otherLabel??"Other values",visible:i.showOther!==!1,symbol:jh(e,i.defaultColor,void 0)}),n}function Mb(i,t){return t==="line"?i.line:t==="polygon"?i.fill:i.marker}const qm=["#2563eb","#65a30d","#ea580c","#f472b6","#115e59","#9d174d","#2dd4bf","#3f6212","#f59e0b","#c026d3","#9a3412"],Nb=["#FFFD3D","#94a3b8","#ffffff","#000000"],x0=20,rF=64;function zm(i={}){const t=i.random??Math.random,e=Ga(i.visible),n=Ga(i.hidden),r=(l,h)=>h.every(f=>Vt.deltaE(l,f)>=x0);for(const l of[[...e,...n],e]){const h=qm.filter(f=>r(f,l));if(h.length>0)return h[Math.floor(t()*h.length)]}const s=[...qm];for(let l=0;l<rF;l++){const h=sF(t);r(h,[...Nb])&&s.push(h)}let o=s[0],a=[-1/0,-1/0];for(const l of s){const h=[Sv(l,e),Sv(l,n)];(h[0]>a[0]||h[0]===a[0]&&h[1]>a[1])&&(o=l,a=h)}return o}function Lb(i,t){if(i.type==="categorical"||i.type==="graduated"){const n=(i.type==="categorical"?i.categories:i.breaks)??[];return Ga(n.filter(r=>r.visible!==!1).map(r=>{var s;return((s=r.symbol)==null?void 0:s.color)??r.color}))}const e=Qs(i);switch(t){case"line":return Ga([e.line.color]);case"point":case"circle":case"symbol":return Ga([e.marker.color]);default:return Ga([e.fill.style==="none"?e.fill.outlineColor:e.fill.color])}}function Ga(i=[]){return i.filter(t=>typeof t=="string"&&Vt.valid(t))}function Sv(i,t){let e=1/0;for(const n of t)e=Math.min(e,Vt.deltaE(i,n));return e}function sF(i){const t=i()*360,e=50+i()*35,n=40+i()*30;return Vt.hcl(t,e,n).hex()}const Xh=3e3;function b0(i,t){if(typeof t!="number"||!Number.isFinite(t))return-1;for(let e=0;e<i.length;e++){const n=i[e];if((e===0?t>=n.min:t>n.min)&&t<=n.max)return e}return-1}function Cb(i,t){for(let e=0;e<i.length;e++)if(i[e].value===t)return e;return-1}function I0(i){const t=i.flatMap(r=>[r.min,r.max]);if(t.every(r=>Number.isInteger(r)))return 0;const e=i.map(r=>r.max-r.min).filter(r=>r>0),n=e.length>0?Math.min(...e):Math.abs(t[0]||1);return Math.max(0,Math.min(6,2-Math.floor(Math.log10(n))))}function S0(i,t,e){return i===t?i.toFixed(e):`${i.toFixed(e)} - ${t.toFixed(e)}`}function Ns(i,t,e,n,r=!1){const s=[];e.forEach(h=>{(s.length===0?h>=t:h>s[s.length-1])&&s.push(h)}),s.length===0&&s.push(t);const o=Ac(n,s.length,r),a=s.map((h,f)=>({min:f===0?t:s[f-1],max:h,color:o[f],label:"",count:0}));i.forEach(h=>{const f=b0(a,h);f>=0&&(a[f].count+=1)});const l=I0(a);return a.forEach(h=>h.label=S0(h.min,h.max,l)),a}function Fc(i){return i.filter(t=>typeof t=="number"&&Number.isFinite(t)).sort((t,e)=>t-e)}function Pb(i,t,e="viridis",n=!1){const r=Fc(i);if(r.length===0||t<=0)return[];const s=r[0],o=r[r.length-1];if(s===o)return Ns(r,s,[o],e,n);const a=(o-s)/t,l=Array.from({length:t},(h,f)=>f===t-1?o:s+(f+1)*a);return Ns(r,s,l,e,n)}function kb(i,t,e="viridis",n=!1){const r=Fc(i);if(r.length===0||t<=0)return[];const s=r.length,o=Array.from({length:t},(a,l)=>l===t-1?r[s-1]:r[Math.max(0,Math.ceil((l+1)*s/t)-1)]);return Ns(r,r[0],o,e,n)}function Tb(i,t,e="viridis",n=!1){const r=Fc(i);if(r.length===0||t<=0)return[];let s=r;if(r.length>Xh){const p=(r.length-1)/(Xh-1);s=Array.from({length:Xh},(y,_)=>r[Math.round(_*p)])}const o=s.length,a=Math.min(t,o);if(a<=1)return Ns(r,r[0],[r[r.length-1]],e,n);const l=Array.from({length:o+1},()=>Array(a+1).fill(0)),h=Array.from({length:o+1},()=>Array(a+1).fill(0));for(let p=1;p<=a;p++){l[1][p]=1;for(let y=2;y<=o;y++)h[y][p]=1/0}for(let p=2;p<=o;p++){let y=0,_=0,E=0,w=0;for(let L=1;L<=p;L++){const b=p-L+1,S=s[b-1];E++,y+=S,_+=S*S,w=_-y*y/E;const P=b-1;if(P!==0)for(let N=2;N<=a;N++)h[p][N]>=w+h[P][N-1]&&(l[p][N]=b,h[p][N]=w+h[P][N-1])}l[p][1]=1,h[p][1]=w}const f=Array(a+1).fill(0);f[a]=o;for(let p=a;p>=2;p--)f[p-1]=l[f[p]][p]-1;const d=Array.from({length:a},(p,y)=>y===a-1?r[r.length-1]:s[f[y+1]-1]);return Ns(r,r[0],d,e,n)}function oF(i){const t=Math.floor(Math.log10(i)),e=i/Math.pow(10,t);return(e<=1?1:e<=2?2:e<=5?5:10)*Math.pow(10,t)}function Rb(i,t,e="viridis",n=!1){const r=Fc(i);if(r.length===0||t<=0)return[];const s=r[0],o=r[r.length-1];if(s===o)return Ns(r,s,[o],e,n);const a=oF((o-s)/t),l=Math.max(0,-Math.floor(Math.log10(a))+1),h=d=>Number(d.toFixed(l)),f=[];for(let d=h((Math.floor(s/a)+1)*a);d<o;d=h(d+a))d>s&&f.push(d);return f.push(o),Ns(r,s,f,e,n)}function Ab(i,t,e="viridis",n,r=!1){const s=Fc(i),o=n??s[0]??t[0];return o===void 0?[]:Ns(s,o,[...t].sort((a,l)=>a-l),e,r)}function Um(i,t,e,n="viridis",r=!1){switch(i){case"equal_interval":return Pb(t,e,n,r);case"natural_breaks":return Tb(t,e,n,r);case"pretty_breaks":return Rb(t,e,n,r);case"manual":case"quantile":default:return kb(t,e,n,r)}}function M0(i,t){const e=s=>typeof s=="number"?0:typeof s=="boolean"?1:2,n=e(i),r=e(t);return n!==r?n-r:typeof i=="number"&&typeof t=="number"?i-t:String(i).localeCompare(String(t),void 0,{numeric:!0})}function Ym(i,t="category10",e=!1){const n=new Map;i.forEach(o=>{o!=null&&(typeof o=="number"&&!Number.isFinite(o)||n.set(o,(n.get(o)||0)+1))});const r=Array.from(n.keys()).sort(M0),s=Ac(t,r.length,e);return r.map((o,a)=>({value:o,color:s[a],label:String(o),count:n.get(o)}))}function Mv(i,t=0){return Array.from({length:i},(e,n)=>{const r=(t+360*n/i-90)*Math.PI/180;return[Math.cos(r),Math.sin(r)]})}function aF(i,t){return Array.from({length:i*2},(e,n)=>{const r=n%2===0?1:t,s=(180*n/i-90)*(Math.PI/180);return[r*Math.cos(s),r*Math.sin(s)]})}function Nv(i){const t=i;return[[-t,-1],[t,-1],[t,-t],[1,-t],[1,t],[t,t],[t,1],[-t,1],[-t,t],[-1,t],[-1,-t],[-t,-t]]}function lF(i,t){const e=t*Math.PI/180,n=Math.cos(e),r=Math.sin(e);return i.map(([s,o])=>[s*n-o*r,s*r+o*n])}const uF={square:[[-.8,-.8],[.8,-.8],[.8,.8],[-.8,.8]],diamond:[[0,-1],[1,0],[0,1],[-1,0]],triangle:[[0,-1],[.95,.72],[-.95,.72]],star:aF(5,.45),pentagon:Mv(5),hexagon:Mv(6,30),cross:Nv(.28),x:lF(Nv(.24),45)},lc=["circle","square","diamond","triangle","star","pentagon","hexagon","cross","x"];function N0(i){return i==="circle"||i==="icon"?null:uF[i]??null}function Ob(i,t,e,n){const r=N0(i);return r?r.map(([s,o],a)=>`${a===0?"M":"L"} ${(t+s*n).toFixed(2)} ${(e+o*n).toFixed(2)}`).join(" ")+" Z":`M ${t-n} ${e} a ${n} ${n} 0 1 0 ${n*2} 0 a ${n} ${n} 0 1 0 ${-n*2} 0 Z`}const L0=new Map,jm=new Set;function cF(i,t,e={}){if(!i.trim())throw new Error("Marker icon name must not be empty");L0.set(i,{source:t,sdf:e.sdf??!0}),jm.forEach(n=>n(i))}function C0(i){return L0.get(i)}function P0(){return Array.from(L0.keys())}function Fb(i){return jm.add(i),()=>jm.delete(i)}function k0(i){return i.trimStart().startsWith("<svg")||i.trimStart().startsWith("<?xml")}const Hg=8,Lv=1024;function hF(i,t){for(i=Math.abs(i),t=Math.abs(t);t;)[i,t]=[t,i%t];return i}function $b(i,t,e){const n=(i%180+180)%180;let r={a:1,b:0,error:Math.min(n,180-n)};for(let s=-Hg;s<=Hg;s++)for(let o=0;o<=Hg;o++){if(s===0&&o===0||hF(s,o)!==1||e*Math.hypot(s,o)>t)continue;const a=(Math.atan2(o,s)*180/Math.PI+180)%180,l=Math.abs(a-n),h=Math.min(l,180-l),f=Math.hypot(s,o)<Math.hypot(r.a,r.b);(h<r.error-1e-9||Math.abs(h-r.error)<=1e-9&&f)&&(r={a:s,b:o,error:h})}return{a:r.a,b:r.b}}function Db(i,t=1){const e=Math.max(1,t),n=Math.max(i.spacing,1),{a:r,b:s}=$b(i.angleDeg,Lv/e/2,n),o=Math.hypot(r,s),a=Math.max(1,Math.round(n*o*e)),l=a/o,h=[r/o,-s/o],f=[s/o,r/o];let d=null,p=1;const y=(i.dash??[]).map(N=>N*e).filter(N=>N>0);if(i.kind!=="dots"&&y.length>0){const N=y.reduce((I,M)=>I+M,0)*(y.length%2===1?2:1),C=y.length%2===1?[...y,...y]:y;let T;N<=l?T=l/Math.max(1,Math.round(l/N)):(p=Math.max(1,Math.round(N/l)),T=l*p),a*p<=Lv?d=C.map(I=>I*T/N):p=1}const _=a*p,E=Math.max(i.lineWidth,.1)*e,w=[],L=[],b=[[-_,-_],[_*2,-_],[-_,_*2],[_*2,_*2]],S=_*4+E,P=(N,C)=>{const T=b.map(([$,U])=>$*C[0]+U*C[1]),I=Math.floor((Math.min(...T)-E)/l)-1,M=Math.ceil((Math.max(...T)+E)/l)+1,R=d?d.reduce(($,U)=>$+U,0):1,A=-Math.ceil(S/R)*R,F=Math.ceil(S/R)*R;for(let $=I;$<=M;$++){const U=$*l*C[0],D=$*l*C[1];w.push([U+A*N[0],D+A*N[1],U+F*N[0],D+F*N[1]])}};if(i.kind==="dots"){const N=E/2,C=Math.ceil(_*3/l)+1;for(let T=-C;T<=C;T++)for(let I=-C;I<=C;I++){const M=T*l*h[0]+I*l*f[0],R=T*l*h[1]+I*l*f[1];M>=-_-N&&M<=_*2+N&&R>=-_-N&&R<=_*2+N&&L.push([M,R])}}else P(h,f),i.kind==="cross"&&P(f,[-h[0],-h[1]]);return{size:_,pixelRatio:e,color:i.color,lineWidth:E,segments:w,dots:L,dash:d,effectiveAngleDeg:(Math.atan2(s,r)*180/Math.PI+180)%180,effectiveSpacing:l/e}}function Gb(i){let t=2166136261;for(let e=0;e<i.length;e++)t^=i.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function Bb(i){const t=JSON.stringify([i.kind,i.color,i.spacing,i.angleDeg,i.lineWidth,i.dash??[]]);return`ofs-hatch-${Gb(t)}`}const Tu=1e20;function Cv(i,t,e,n,r,s,o){s[0]=0,o[0]=-Tu,o[1]=Tu,r[0]=i[t];for(let a=1,l=0,h=0;a<n;a++){r[a]=i[t+a*e];const f=a*a;do{const d=s[l];h=(r[a]-r[d]+f-d*d)/(a-d)/2}while(h<=o[l]&&--l>-1);l++,s[l]=a,o[l]=h,o[l+1]=Tu}for(let a=0,l=0;a<n;a++){for(;o[l+1]<a;)l++;const h=s[l],f=a-h;i[t+a*e]=r[h]+f*f}}function Pv(i,t,e){const n=Math.max(t,e),r=new Float64Array(n),s=new Float64Array(n+1),o=new Uint16Array(n);for(let a=0;a<t;a++)Cv(i,a,t,e,r,o,s);for(let a=0;a<e;a++)Cv(i,a*t,1,t,r,o,s)}function qb(i,t,e,n=8,r=.25){const s=t*e,o=new Float64Array(s),a=new Float64Array(s);for(let h=0;h<s;h++){const f=i[h]/255;if(f>=1)o[h]=0,a[h]=Tu;else if(f<=0)o[h]=Tu,a[h]=0;else{const d=.5-f;o[h]=d>0?d*d:0,a[h]=d<0?d*d:0}}Pv(o,t,e),Pv(a,t,e);const l=new Uint8ClampedArray(s);for(let h=0;h<s;h++){const f=Math.sqrt(o[h])-Math.sqrt(a[h]);l[h]=Math.round(255-255*(f/n+r))}return l}const Uf="_ofs_label",$c=24,uc=8,Wo=2;function zb(i,t){return i==="icon"?`ofs-icon-${t??""}`:`ofs-marker-${i}`}const Xm={polygon:["match",["geometry-type"],["Polygon","MultiPolygon"],!0,!1],line:["match",["geometry-type"],["LineString","MultiLineString"],!0,!1],point:["match",["geometry-type"],["Point","MultiPoint"],!0,!1]},fF={center:[0,0],left:[-1,0],right:[1,0],top:[0,-1],bottom:[0,1],"top-left":[-1,-1],"top-right":[1,-1],"bottom-left":[-1,1],"bottom-right":[1,1]};function dF(i){return Number.isInteger(i)&&Math.abs(i)<=Number.MAX_SAFE_INTEGER}function Ub(i){const t=i.fieldName;if(!t)return null;const e=["get",t];if(i.type==="graduated"&&i.breaks&&i.breaks.length>0){const n=["to-number",e],r=[];return i.breaks.forEach((s,o)=>{r.push(["all",[o===0?">=":">",n,s.min],["<=",n,s.max]],o)}),["case",["!=",["typeof",e],"number"],-1,...r,-1]}if(i.type==="categorical"&&i.categories&&i.categories.length>0){const n=[],r=[],s=[],o=[],a=new Set;i.categories.forEach((h,f)=>{const d=`${typeof h.value}:${String(h.value)}`;h.value===null||h.value===void 0||a.has(d)||(a.add(d),typeof h.value=="string"?n.push(h.value,f):typeof h.value=="boolean"?o.push(["==",["to-boolean",e],h.value],f):typeof h.value=="number"&&dF(h.value)?r.push(h.value,f):typeof h.value=="number"&&Number.isFinite(h.value)&&s.push(["==",["to-number",e],h.value],f))});const l=[];if(n.length>0&&l.push(["==",["typeof",e],"string"],["match",["to-string",e],...n,-1]),r.length>0||s.length>0){const h=[];r.length>0&&h.push(["match",["to-number",e],...r,-1]);const f=s.length>0?["case",...s,r.length>0?h[0]:-1]:h[0];l.push(["==",["typeof",e],"number"],f)}return o.length>0&&l.push(["==",["typeof",e],"boolean"],["case",...o,-1]),l.length===0?null:["case",...l,-1]}return null}function Ve(i,t,e){const n=t.map(e),r=JSON.stringify(n[0]);if(!i||n.every(a=>JSON.stringify(a)===r))return n[0];const s=t.find(a=>a.index===-1),o=[];return t.forEach((a,l)=>{a.index>=0&&o.push(a.index,n[l])}),["match",i,...o,s?e(s):n[0]]}function bo(i,t){return t===1?i:typeof i=="number"?i*t:["*",t,i]}function kv(i,t,e){const n=t.filter(e).map(r=>r.index);return i?n.length===t.length?null:n.length===0?["boolean",!1]:["match",i,n,!0,!1]:n.length>0?null:["boolean",!1]}function Tv(...i){const t=i.filter(e=>e!==null);return t.length===1?t[0]:["all",...t]}function Rv(i,t){const e=(i??[]).filter(n=>Number.isFinite(n)&&n>=0);if(!(e.length<2||e.every(n=>n===0)))return e.map(n=>n/Math.max(t,.01))}class Yb{static compile(t,e,n={}){const r=n.layerId??t.layerId,s=Math.max(0,Math.min(1,n.opacity??1)),o=t.highlightColor||"#FFFD3D",a=t.enableSelectionHighlight??!0,l=["boolean",["feature-state","selected"],!1],h=S=>a?["case",l,o,S]:S,f=w0(t,e),d=f.length>1?Ub(t):null,p=kv(d,f,S=>S.visible),y=e==="line"?"line":e==="polygon"?"polygon":"point",_=Tv(Xm[y],p),E=f.find(S=>S.index===0)??f[0],w=[],L=new Map;if(y==="polygon"){const S=E.symbol.fill,P=S.offset??[0,0],N=A=>{const F=A.symbol.fill;return F.style==="none"||F.style==="pattern"&&!F.patternBackground?0:F.opacity},C=bo(Ve(d,f,N),s),T=bo(Ve(d,f,A=>Math.max(N(A),.35)),s);w.push({id:r,role:"fill",type:"fill",filter:_,paint:{"fill-color":h(Ve(d,f,A=>A.symbol.fill.color)),"fill-opacity":a?["case",l,T,C]:C,"fill-translate":P},layout:{visibility:"visible"}});const I=A=>A.symbol.fill.style==="pattern"&&!!A.symbol.fill.pattern;if(f.some(I)){const A=$=>{if(!I($))return null;const U=Bb($.symbol.fill.pattern);return L.set(U,{id:U,kind:"hatch",pattern:$.symbol.fill.pattern}),U},F=f.map(A).find($=>!!$);w.push({id:`${r}_pattern`,role:"pattern",type:"fill",filter:Tv(Xm.polygon,kv(d,f,$=>$.visible&&I($))),paint:{"fill-pattern":Ve(d,f,$=>A($)??F),"fill-opacity":bo(Ve(d,f,$=>$.symbol.fill.opacity),s),"fill-translate":P},layout:{visibility:"visible"}})}const M={"line-color":Ve(d,f,A=>A.symbol.fill.outlineColor),"line-width":Ve(d,f,A=>A.symbol.fill.outlineWidth),"line-opacity":bo(Ve(d,f,A=>A.symbol.fill.outlineOpacity),s),"line-translate":P},R=Rv(S.outlineDash,S.outlineWidth);R&&(M["line-dasharray"]=R),w.push({id:`${r}_stroke`,role:"stroke",type:"line",filter:_,paint:M,layout:{visibility:"visible","line-join":"round"}})}else if(y==="line"){const S=E.symbol.line,P={"line-color":h(Ve(d,f,C=>C.symbol.line.color)),"line-width":Ve(d,f,C=>C.symbol.line.width),"line-opacity":bo(Ve(d,f,C=>C.symbol.line.opacity),s)},N=Rv(S.dash,S.width);N&&(P["line-dasharray"]=N),S.offset&&(P["line-offset"]=S.offset),w.push({id:r,role:"line",type:"line",filter:_,paint:P,layout:{visibility:"visible","line-cap":S.cap??"round","line-join":S.join??"round"}})}else{const S=E.symbol.marker,P=S.offset??[0,0];if(f.some(C=>C.symbol.marker.shape!=="circle")){const C=R=>{const A=R.symbol.marker,F=zb(A.shape,A.icon);return A.shape==="icon"?L.set(F,{id:F,kind:"icon",icon:A.icon??""}):L.set(F,{id:F,kind:"marker",shape:A.shape}),F},T=S.anchor??"center",I=fF[T],M=S.allowOverlap??!0;w.push({id:r,role:"marker",type:"symbol",filter:_,paint:{"icon-color":h(Ve(d,f,R=>R.symbol.marker.color)),"icon-opacity":bo(Ve(d,f,R=>R.symbol.marker.opacity),s),"icon-halo-color":Ve(d,f,R=>R.symbol.marker.strokeColor),"icon-halo-width":Ve(d,f,R=>R.symbol.marker.strokeWidth),"icon-translate":P},layout:{visibility:"visible","icon-image":Ve(d,f,C),"icon-size":Ve(d,f,R=>R.symbol.marker.size/$c),"icon-rotate":Ve(d,f,R=>R.symbol.marker.rotationDeg??0),"icon-anchor":T,"icon-offset":[I[0]*uc,I[1]*uc],"icon-allow-overlap":M,"icon-ignore-placement":M}})}else{const C=bo(Ve(d,f,T=>T.symbol.marker.opacity),s);w.push({id:r,role:"circle",type:"circle",filter:_,paint:{"circle-color":h(Ve(d,f,T=>T.symbol.marker.color)),"circle-radius":Ve(d,f,T=>T.symbol.marker.size/2),"circle-opacity":C,"circle-stroke-color":Ve(d,f,T=>T.symbol.marker.strokeColor),"circle-stroke-width":Ve(d,f,T=>T.symbol.marker.strokeWidth),"circle-stroke-opacity":C,"circle-translate":P},layout:{visibility:"visible"}})}}const b=Vb(t.label,r,y,s);return b&&w.push(b),{paint:w[0].paint,layout:{visibility:"visible"},layers:w,images:Array.from(L.values())}}}function jb(i){return!!i&&i.enabled!==!1&&!!i.expression}function Xb(i){return!!i&&i.enabled!==!1&&!!(i.field||i.expression)}function Vb(i,t,e,n=1){if(!Xb(i))return null;const r=i,s=r.size??12,o=r.allowOverlap??!1,l={visibility:"visible","text-field":r.expression?["coalesce",["get",Uf],""]:r.decimals!==void 0?["case",["==",["typeof",["get",r.field]],"number"],["number-format",["get",r.field],{"min-fraction-digits":r.decimals,"max-fraction-digits":r.decimals}],["to-string",["coalesce",["get",r.field],""]]]:["to-string",["coalesce",["get",r.field],""]],"text-size":s,"text-anchor":r.anchor??"center","text-max-width":r.maxWidth??10,"text-allow-overlap":o,"text-ignore-placement":o,"symbol-placement":r.placement==="line"&&e!=="point"?"line":"point"};r.font&&(l["text-font"]=r.font),r.offset&&(l["text-offset"]=r.offset),r.rotationDeg&&(l["text-rotate"]=r.rotationDeg),r.transform&&r.transform!=="none"&&(l["text-transform"]=r.transform),r.priorityField&&(l["symbol-sort-key"]=["-",0,["to-number",["coalesce",["get",r.priorityField],0]]]);const h={"text-color":r.color??"#1f2937","text-halo-color":r.haloColor??"#ffffff","text-halo-width":r.haloWidth??1.2,"text-opacity":Math.max(0,Math.min(1,(r.opacity??1)*n))},f={id:`${t}_label`,role:"label",type:"symbol",filter:Xm[e],paint:h,layout:l};return r.minZoom!==void 0&&(f.minzoom=r.minZoom),r.maxZoom!==void 0&&(f.maxzoom=r.maxZoom),f}const Av="#94a3b8";function oi(i){return i===void 0?i:JSON.parse(JSON.stringify(i))}function gF(i,t){const e=oi(i)??{};return["fill","line","marker"].forEach(n=>{t[n]&&(e[n]={...e[n],...oi(t[n])})}),e}function Vh(i,t){var n;const e=[];for(const r of i.getFeatures()){const s=(n=r.properties)==null?void 0:n[t];typeof s=="number"&&Number.isFinite(s)&&e.push(s)}return e}function Wb(i,t){var s,o,a;const e=new Map,n=i.fieldName,r=n&&(i.type==="graduated"&&((s=i.breaks)==null?void 0:s.length)||i.type==="categorical"&&((o=i.categories)==null?void 0:o.length));for(const l of t.getFeatures()){let h=0;if(r){const f=(a=l.properties)==null?void 0:a[n];h=i.type==="graduated"?b0(i.breaks,f):Cb(i.categories,f)}e.set(h,(e.get(h)??0)+1)}return e}class cc extends no{constructor(e={}){super();q(this,"themes",new Map);q(this,"random");q(this,"dataSource",null);q(this,"unbindDataSource",[]);this.random=e.random??Math.random}bindDataSource(e){this.dataSource!==e&&(this.unbindDataSource.forEach(n=>n()),this.dataSource=e,this.unbindDataSource=[e.on("layer:added",({layer:n})=>this.styleNewLayer(n)),e.on("layer:removed",({layerId:n,replaced:r})=>{r||this.removeTheme(n)})])}styleNewLayer(e){if(e.color){this.createSimpleTheme(e.id,{},e.color);return}this.getEffectiveTheme(e.id)}getTheme(e){return this.themes.get(e)}setTheme(e){this.themes.set(e.layerId,e),this.emit("theme:changed",{layerId:e.layerId,theme:e})}removeTheme(e){this.themes.delete(e)}exportThemes(){return Array.from(this.themes.values()).map(e=>oi(e))}importThemes(e){e.forEach(n=>this.setTheme(oi(n)))}carriedLayerSettings(e){const n=this.themes.get(e);if(!n)return{};const r={};return n.label&&(r.label=oi(n.label)),n.highlightColor!==void 0&&(r.highlightColor=n.highlightColor),n.enableSelectionHighlight!==void 0&&(r.enableSelectionHighlight=n.enableSelectionHighlight),r}carriedSymbol(e,n){var r;return oi(n??((r=this.themes.get(e))==null?void 0:r.baseSymbol))}createSimpleTheme(e,n={},r="#3b82f6"){const s=n.fillColor??n.circleColor??r,o=this.carriedSymbol(e);o!=null&&o.fill&&(delete o.fill.color,o.fill.pattern&&(o.fill.pattern.color=s)),o!=null&&o.line&&delete o.line.color,o!=null&&o.marker&&delete o.marker.color;const a={type:"simple",layerId:e,defaultColor:r,simpleStyle:{fillColor:r,strokeColor:"#ffffff",strokeWidth:2,fillOpacity:.65,circleColor:r,circleRadius:6,...n},baseSymbol:o,...this.carriedLayerSettings(e)};return this.setTheme(a),a}createCategoricalTheme(e,n,r="category10",s=Av,o={}){var h;const a=[];for(const f of e.getFeatures()){const d=(h=f.properties)==null?void 0:h[n];d!=null&&a.push(d)}const l={type:"categorical",layerId:e.id,fieldName:n,paletteName:r,defaultColor:s,categories:Ym(a,r,o.reverse),baseSymbol:this.carriedSymbol(e.id,o.baseSymbol),...this.carriedLayerSettings(e.id),...o.keepEmptyCategories?{keepEmptyCategories:!0}:{}};return this.setTheme(l),l}createGraduatedTheme(e,n,r="quantile",s=5,o="viridis",a=Av,l={}){const h=Um(r,Vh(e,n),s,o,l.reverse),f={type:"graduated",layerId:e.id,fieldName:n,classificationMethod:r,classCount:s,paletteName:o,defaultColor:a,breaks:h,graduatedMode:l.mode??"color",sizeRange:l.sizeRange,baseSymbol:this.carriedSymbol(e.id,l.baseSymbol),...this.carriedLayerSettings(e.id)};return this.setTheme(f),f}setManualBreaks(e,n,r){const s=this.requireTheme(e.id);if(s.type!=="graduated"||!s.fieldName)throw new Error(`Layer "${e.id}" does not have a graduated theme`);const o={...oi(s),classificationMethod:"manual",classCount:n.length,breaks:Ab(Vh(e,s.fieldName),n,s.paletteName??"viridis",r)};return this.setTheme(o),o}reclassify(e){var s;const n=this.themes.get(e.id);if(!n||!n.fieldName||n.type==="simple")return n;const r=oi(n);if(n.type==="categorical"){const o=this.createCategoricalThemeData(e,n),a=o.map(d=>{var p;return(p=n.categories)==null?void 0:p.find(y=>y.value===d.value)}),l=n.keepEmptyCategories?(n.categories??[]).filter(d=>!o.some(p=>p.value===d.value)).map(d=>({...d,count:0})):[],h=[...a.flatMap(d=>d?[d.color]:[]),...l.map(d=>d.color)],f=o.map((d,p)=>{const y=a[p];if(y)return{...d,color:y.color,label:y.label,visible:y.visible,symbol:y.symbol};const _=this.unusedClassColor(n.paletteName??"category10",o.length+h.length,h);return h.push(_),{...d,color:_}});r.categories=[...f,...l].sort((d,p)=>M0(d.value,p.value))}else if(n.classificationMethod!=="manual"){const o=Um(n.classificationMethod??"quantile",Vh(e,n.fieldName),n.classCount??((s=n.breaks)==null?void 0:s.length)??5,n.paletteName??"viridis");r.breaks=o.map((a,l)=>{var f;const h=(f=n.breaks)==null?void 0:f[l];return h?{...a,visible:h.visible,symbol:h.symbol,size:h.size}:a})}return this.setTheme(r),r}unusedClassColor(e,n,r){return Ac(e,Math.max(n,1)).find(a=>r.every(l=>!Vt.valid(l)||Vt.deltaE(a,l)>=x0))??zm({visible:r,random:this.random})}createCategoricalThemeData(e,n){var s;const r=[];for(const o of e.getFeatures()){const a=(s=o.properties)==null?void 0:s[n.fieldName];a!=null&&r.push(a)}return Ym(r,n.paletteName??"category10")}updateBaseSymbol(e,n){const r=oi(this.themes.get(e))??this.defaultTheme(e);return r.baseSymbol=gF(r.baseSymbol,n),this.setTheme(r),r}setLabel(e,n){const r=oi(this.themes.get(e))??this.defaultTheme(e);if(!n)delete r.label;else{const s={...r.label??{},...n};if(n.field!==void 0&&n.expression===void 0&&delete s.expression,n.expression!==void 0&&n.field===void 0&&delete s.field,!s.field&&!s.expression)throw new Error("Labels need a field or an expression");r.label=s}return this.setTheme(r),r}getLabel(e){var n;return(n=this.themes.get(e))==null?void 0:n.label}setClassVisible(e,n,r){const s=oi(this.requireTheme(e));if(n===-1)s.showOther=r;else{const o=this.classList(s)[n];if(!o)throw new Error(`Layer "${e}" has no class ${n}`);o.visible=r}this.setTheme(s)}setAllClassesVisible(e,n){const r=oi(this.requireTheme(e));this.classList(r).forEach(s=>s.visible=n),r.showOther=n,this.setTheme(r)}updateClass(e,n,r){const s=oi(this.requireTheme(e)),a=this.classList(s)[n];if(!a)throw new Error(`Layer "${e}" has no class ${n}`);if(r.color!==void 0&&(a.color=r.color),r.visible!==void 0&&(a.visible=r.visible),r.size!==void 0&&(a.size=r.size),r.symbol===null?delete a.symbol:r.symbol&&(a.symbol={...a.symbol,...oi(r.symbol)}),s.type==="graduated"&&(r.min!==void 0||r.max!==void 0)){const l=s.breaks,h=l[n];if(r.max!==void 0){const f=l[n+1];f&&f.min===h.max&&(f.min=r.max),h.max=r.max}if(r.min!==void 0){const f=l[n-1];f&&f.max===h.min&&(f.max=r.min),h.min=r.min}if(s.classificationMethod="manual",r.label===void 0){const f=I0(l);l.forEach(d=>d.label=S0(d.min,d.max,f))}}r.label!==void 0&&(a.label=r.label),this.setTheme(s)}classList(e){return e.type==="graduated"?e.breaks??[]:e.type==="categorical"?e.categories??[]:[]}requireTheme(e){const n=this.themes.get(e);if(!n)throw new Error(`Layer "${e}" has no theme`);return n}defaultTheme(e){const n=this.defaultColorFor(e);return{type:"simple",layerId:e,defaultColor:n,simpleStyle:{fillColor:n,strokeColor:"#ffffff",strokeWidth:2,fillOpacity:.65,circleColor:n,circleRadius:6}}}defaultColorFor(e){const n=this.dataSource,r=n==null?void 0:n.getLayer(e);if(r!=null&&r.color)return r.color;if(!n)return Oc;const s=[],o=[];for(const a of n.getAllLayers()){if(a.id===e)continue;const l=this.themes.get(a.id);if((l==null?void 0:l.type)!=="simple")continue;const h=Lb(l,a.type);(n.isLayerRendered(a.id)?s:o).push(...h)}return zm({visible:s,hidden:o,random:this.random})}getEffectiveTheme(e){let n=this.themes.get(e);return n||(n=this.defaultTheme(e),this.themes.set(e,n)),n}compile(e){return Yb.compile(this.getEffectiveTheme(e.id),e.type,{layerId:e.id,opacity:e.opacity??1})}}class Hb extends no{constructor(e,n){super();q(this,"dataSource");q(this,"thematicEngine");q(this,"unsubscribers",[]);q(this,"groupCounter",0);this.dataSource=e,this.thematicEngine=n||new cc,this.thematicEngine.bindDataSource(e),this.bindDataSourceEvents()}bindDataSourceEvents(){if(["layer:added","layer:removed","layer:updated","features:changed","active-layer:changed","group:added","group:removed","group:updated","tile-layer:added","tile-layer:removed","tile-layer:updated"].forEach(n=>{const r=this.dataSource.on(n,()=>{this.notifyUpdate()});this.unsubscribers.push(r)}),this.thematicEngine){const n=this.thematicEngine.on("theme:changed",()=>{this.notifyUpdate()});this.unsubscribers.push(n)}}getSnapshot(){const e=this.dataSource.getAllLayers().sort((a,l)=>l.zIndex-a.zIndex),n=this.dataSource.getTileLayers().map(a=>({id:a.id,name:a.name,type:a.kind,visible:a.visible,rendered:this.dataSource.isLayerRendered(a.id),opacity:a.opacity,zIndex:a.zIndex,pinned:a.pinned,groupId:a.groupId&&this.dataSource.getLayerGroup(a.groupId)?a.groupId:null,featureCount:0,thematicType:"simple",items:[]})),r=e.map(a=>{const l=this.thematicEngine.getEffectiveTheme(a.id),h=Wb(l,a),f=[];return w0(l,a.type).forEach(d=>{const p=Mb(d.symbol,a.type),y="style"in p&&p.style==="pattern"&&p.pattern?p.pattern.color:p.color;if(l.type==="simple"||d.index>=0){f.push({label:l.type==="simple"?a.name:d.label,color:y,count:l.type==="simple"?a.count:h.get(d.index)??0,min:d.min,max:d.max,value:d.value,index:d.index,visible:d.visible,symbol:d.symbol});return}const _=h.get(-1)??0;(l.type==="categorical"||_>0)&&f.push({label:d.label,color:y,count:_,index:-1,visible:d.visible,symbol:d.symbol})}),{id:a.id,name:a.name,type:a.type,visible:a.visible,rendered:this.dataSource.isLayerRendered(a.id),opacity:a.opacity,zIndex:a.zIndex,pinned:a.pinned,groupId:a.groupId&&this.dataSource.getLayerGroup(a.groupId)?a.groupId:null,featureCount:a.count,thematicType:l.type,fieldName:l.fieldName,classificationMethod:l.classificationMethod,graduatedMode:l.type==="graduated"?l.graduatedMode??"color":void 0,paletteName:l.paletteName,items:f}}),s=this.dataSource.getLayerGroups().map(a=>({...a,rendered:this.isGroupRendered(a.id)})),o=[...r,...n].sort((a,l)=>l.zIndex-a.zIndex);return{layers:o,tree:this.buildTree(o,s),groups:s,activeLayerId:this.dataSource.getActiveLayerId(),totalLayers:o.length}}isGroupRendered(e){for(let n=this.dataSource.getLayerGroup(e);n;n=n.parentId?this.dataSource.getLayerGroup(n.parentId):void 0)if(!n.visible)return!1;return!0}buildTree(e,n){const r=new Map,s=a=>{if(r.has(a))return r.get(a);r.set(a,-1/0);let l=-1/0;return e.forEach(h=>h.groupId===a&&(l=Math.max(l,h.zIndex))),n.forEach(h=>h.parentId===a&&(l=Math.max(l,s(h.id)))),r.set(a,l),l},o=a=>{const l=[];return n.filter(h=>h.parentId===a).forEach(h=>l.push({z:s(h.id),node:{kind:"group",group:h,children:o(h.id)}})),e.filter(h=>h.groupId===a).forEach(h=>l.push({z:h.zIndex,node:{kind:"layer",layer:h}})),l.sort((h,f)=>f.z-h.z).map(h=>h.node)};return o(null)}notifyUpdate(){this.emit("legend:updated",{snapshot:this.getSnapshot()})}findRow(e){return this.dataSource.getLayer(e)??this.dataSource.getTileLayer(e)}toggleLayerVisibility(e){const n=this.findRow(e);n&&this.dataSource.setLayerVisibility(e,!n.visible)}setLayerOpacity(e,n){this.dataSource.setLayerOpacity(e,n)}setActiveLayer(e){!this.dataSource.hasLayer(e)&&this.dataSource.getTileLayer(e)||this.dataSource.setActiveLayer(e)}toggleLayerPinned(e){const n=this.findRow(e);n&&this.dataSource.setLayerPinned(e,!n.pinned)}moveLayerUp(e){this.moveNode({kind:"layer",id:e},-1)}moveLayerDown(e){this.moveNode({kind:"layer",id:e},1)}moveGroupUp(e){this.moveNode({kind:"group",id:e},-1)}moveGroupDown(e){this.moveNode({kind:"group",id:e},1)}nodeLayers(e){return e.kind==="layer"?[e.layer.id]:e.children.flatMap(n=>this.nodeLayers(n))}findSiblings(e,n){const r=e.findIndex(s=>(s.kind==="layer"?s.layer.id:s.group.id)===n.id&&s.kind===n.kind);if(r>=0)return{siblings:e,index:r};for(const s of e)if(s.kind==="group"){const o=this.findSiblings(s.children,n);if(o)return o}return null}moveNode(e,n){const r=this.getSnapshot().tree,s=this.findSiblings(r,e);if(!s)return;const o=this.nodeLayers(s.siblings[s.index]);if(o.length===0)return;let a=[];for(let f=s.index+n;f>=0&&f<s.siblings.length&&(a=this.nodeLayers(s.siblings[f]),!(a.length>0));f+=n);if(a.length===0)return;const l=r.flatMap(f=>this.nodeLayers(f)).filter(f=>!o.includes(f)),h=n===-1?l.indexOf(a[0]):l.indexOf(a[a.length-1])+1;l.splice(h,0,...o),this.dataSource.reorderLayers([...l].reverse())}addGroup(e,n=null,r){let s=r;for(;!s||this.dataSource.getLayerGroup(s);)s=`group_${++this.groupCounter}`;return this.dataSource.addLayerGroup({id:s,name:e,parentId:n}),s}removeGroup(e){this.dataSource.removeLayerGroup(e)}renameGroup(e,n){this.dataSource.updateLayerGroup(e,{name:n})}toggleGroupVisibility(e){const n=this.dataSource.getLayerGroup(e);n&&this.dataSource.updateLayerGroup(e,{visible:!n.visible})}toggleGroupExpanded(e){const n=this.dataSource.getLayerGroup(e);n&&this.dataSource.updateLayerGroup(e,{expanded:!n.expanded})}moveLayerToGroup(e,n){const r=this.findRow(e);if(!r)return;const s=this.dataSource.getDisplayLayers().filter(a=>a.id!==e&&(n===null?!0:this.dataSource.isLayerInGroup(a.id,n))).reduce((a,l)=>Math.max(a,l.zIndex),-1/0);this.dataSource.moveLayerToGroup(e,n),Number.isFinite(s)&&(r.zIndex=s+.5);const o=this.getSnapshot().tree.flatMap(a=>this.nodeLayers(a));this.dataSource.reorderLayers(o.reverse())}setThematicSimple(e,n){this.thematicEngine.createSimpleTheme(e,{fillColor:n,circleColor:n})}setThematicCategorical(e,n,r="category10",s={}){const o=this.dataSource.getLayer(e);o&&this.thematicEngine.createCategoricalTheme(o,n,r,void 0,s)}setThematicGraduated(e,n,r="quantile",s=5,o="viridis",a={}){const l=this.dataSource.getLayer(e);l&&this.thematicEngine.createGraduatedTheme(l,n,r,s,o,void 0,a)}reclassify(e){const n=this.dataSource.getLayer(e);n&&this.thematicEngine.reclassify(n)}updateBaseSymbol(e,n){this.thematicEngine.updateBaseSymbol(e,n)}setLabel(e,n){this.thematicEngine.setLabel(e,n)}getLabel(e){return this.thematicEngine.getLabel(e)}setClassVisible(e,n,r){this.thematicEngine.setClassVisible(e,n,r)}toggleClassVisible(e,n){var s;const r=(s=this.getSnapshot().layers.find(o=>o.id===e))==null?void 0:s.items.find(o=>o.index===n);r&&this.setClassVisible(e,n,!r.visible)}setAllClassesVisible(e,n){this.thematicEngine.setAllClassesVisible(e,n)}updateClass(e,n,r){this.thematicEngine.updateClass(e,n,r)}getThematicEngine(){return this.thematicEngine}getDataSource(){return this.dataSource}destroy(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[],this.removeAllListeners()}}let mF=0;function Rt(i){return String(i).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Yn(i,t=2){return Number.isFinite(i)?String(Number(i.toFixed(t))):"0"}function Ov(i){const t=(i??[]).filter(e=>Number.isFinite(e)&&e>=0);return t.length>=2?` stroke-dasharray="${t.map(e=>Yn(e)).join(" ")}"`:""}function Yf(i,t,e=18){const n=e,r=`<svg xmlns="http://www.w3.org/2000/svg" width="${n}" height="${n}" viewBox="0 0 ${n} ${n}" class="ofs-swatch-svg">`;if(t==="line"){const d=i.line,p=Math.min(Math.max(d.width,.5),n/2);return`${r}<line x1="2" y1="${n/2}" x2="${n-2}" y2="${n/2}" stroke="${Rt(d.color)}" stroke-width="${Yn(p)}" stroke-opacity="${Yn(d.opacity)}" stroke-linecap="${Rt(d.cap??"round")}"${Ov(d.dash)}/></svg>`}if(t==="polygon"){const d=i.fill,p=1.5,y=(L,b="")=>`<rect x="${p}" y="${p}" width="${n-p*2}" height="${n-p*2}" rx="2" fill="${L}"${b}/>`;let _="",E="";if((d.style==="solid"||d.style==="pattern"&&d.patternBackground)&&(_+=y(Rt(d.color),` fill-opacity="${Yn(d.opacity)}"`)),d.style==="pattern"&&d.pattern){const L=d.pattern,b=`ofs-swatch-hatch-${++mF}`,S=Math.max(3,Math.min(L.spacing*.6,n/3)),P=Math.max(.75,Math.min(L.lineWidth,S/2)),N=Rt(L.color);let C="";L.kind==="dots"?C=`<circle cx="${S/2}" cy="${S/2}" r="${Yn(P/2+.25)}" fill="${N}"/>`:(C=`<line x1="0" y1="${S/2}" x2="${S}" y2="${S/2}" stroke="${N}" stroke-width="${Yn(P)}"/>`,L.kind==="cross"&&(C+=`<line x1="${S/2}" y1="0" x2="${S/2}" y2="${S}" stroke="${N}" stroke-width="${Yn(P)}"/>`)),E=`<defs><pattern id="${b}" patternUnits="userSpaceOnUse" width="${S}" height="${S}" patternTransform="rotate(${Yn(-L.angleDeg)})">${C}</pattern></defs>`,_+=y(`url(#${b})`,` fill-opacity="${Yn(d.opacity)}"`)}const w=Math.min(d.outlineWidth,3);return w>0&&(_+=y("none",` stroke="${Rt(d.outlineColor)}" stroke-width="${Yn(w)}" stroke-opacity="${Yn(d.outlineOpacity)}"${Ov(d.outlineDash)}`)),`${r}${E}${_}</svg>`}const s=i.marker,o=Math.min(s.strokeWidth,3),a=Math.max(2,Math.min(s.size,n-2)/2-o/2),l=n/2,h=s.rotationDeg?` transform="rotate(${Yn(s.rotationDeg)} ${l} ${l})"`:"";if(s.shape==="icon"){const d=s.icon?C0(s.icon):void 0;if(d){const p=k0(d.source)?`data:image/svg+xml;charset=utf-8,${encodeURIComponent(d.source)}`:d.source;return`${r}<image href="${Rt(p)}" x="${l-a}" y="${l-a}" width="${a*2}" height="${a*2}" opacity="${Yn(s.opacity)}"${h}/></svg>`}}const f=s.shape==="icon"?"circle":s.shape;return`${r}<path d="${Ob(f,l,l,a)}" fill="${Rt(s.color)}" fill-opacity="${Yn(s.opacity)}" stroke="${Rt(s.strokeColor)}" stroke-width="${Yn(o)}"${h}/></svg>`}class pF{constructor(t,e={}){q(this,"legendTools");q(this,"container",null);q(this,"unsubscriber",null);q(this,"options");q(this,"handleClick",t=>{var h,f,d,p,y,_;const e=t.target,n=e.closest("[data-action]"),r=n==null?void 0:n.dataset.action,s=(n==null?void 0:n.dataset.id)??"",o=this.legendTools;switch(r){case"add-group":{const E=typeof prompt=="function"?prompt("Group name:","New group"):"New group";E&&o.addGroup(E);return}case"group-expand":o.toggleGroupExpanded(s);return;case"group-up":o.moveGroupUp(s);return;case"group-down":o.moveGroupDown(s);return;case"group-remove":o.removeGroup(s);return;case"layer-pin":t.stopPropagation(),o.toggleLayerPinned(s);return;case"import":(f=(h=this.options).onImport)==null||f.call(h);return;case"layer-export":t.stopPropagation(),(p=(d=this.options).onExportLayer)==null||p.call(d,s);return;case"layer-style":t.stopPropagation(),(_=(y=this.options).onEditSymbology)==null||_.call(y,s);return;case"layer-up":t.stopPropagation(),o.moveLayerUp(s);return;case"layer-down":t.stopPropagation(),o.moveLayerDown(s);return}if(e.closest("input, select, button, label"))return;const a=e.closest(".ofs-legend-layer"),l=a==null?void 0:a.dataset.layerId;l&&o.setActiveLayer(l)});q(this,"handleChange",t=>{const e=t.target,n=e.dataset.id??"";switch(e.dataset.action){case"layer-visible":this.legendTools.toggleLayerVisibility(n);return;case"group-visible":this.legendTools.toggleGroupVisibility(n);return;case"class-visible":this.legendTools.setClassVisible(n,Number(e.dataset.index),e.checked);return;case"layer-group":this.legendTools.moveLayerToGroup(n,e.value||null);return;case"layer-opacity":e.blur(),this.legendTools.notifyUpdate();return}});q(this,"handleDoubleClick",t=>{const e=t.target.closest('[data-action="group-rename"]'),n=e==null?void 0:e.dataset.id;if(!n||typeof prompt!="function")return;const r=this.legendTools.getDataSource().getLayerGroup(n),s=prompt("Group name:",(r==null?void 0:r.name)??"");s&&this.legendTools.renameGroup(n,s)});q(this,"handleInput",t=>{const e=t.target;e.dataset.action==="layer-opacity"&&e.dataset.id&&this.legendTools.setLayerOpacity(e.dataset.id,parseFloat(e.value))});this.legendTools=t,this.options=e}mount(t){const e=typeof t=="string"?document.getElementById(t):t;if(!e)throw new Error(`Target container for LegendWidget not found: ${t}`);this.container=e,this.container.classList.add("ofs-legend-container"),this.container.addEventListener("click",this.handleClick),this.container.addEventListener("change",this.handleChange),this.container.addEventListener("input",this.handleInput),this.container.addEventListener("dblclick",this.handleDoubleClick),this.unsubscriber=this.legendTools.on("legend:updated",({snapshot:n})=>{this.render(n)}),this.render(this.legendTools.getSnapshot())}unmount(){this.unsubscriber&&(this.unsubscriber(),this.unsubscriber=null),this.container&&(this.container.removeEventListener("click",this.handleClick),this.container.removeEventListener("change",this.handleChange),this.container.removeEventListener("input",this.handleInput),this.container.removeEventListener("dblclick",this.handleDoubleClick),this.container.innerHTML="",this.container=null)}render(t){var n;if(!this.container)return;const e=document.activeElement;if(e&&this.container.contains(e)&&e.classList.contains("ofs-opacity-slider")){const r=(n=e.parentElement)==null?void 0:n.querySelector(".ofs-opacity-val");r&&(r.textContent=`${Math.round(Number(e.value)*100)}%`);return}if(t.layers.length===0&&t.groups.length===0){this.container.innerHTML=`
27
27
  <div class="ofs-legend-empty">
28
28
  <div class="ofs-empty-icon">🗺️</div>
29
29
  <div class="ofs-empty-text">No layers loaded</div>