@florasync/leaflet-geokit 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,95 @@
1
+ import * as y from "leaflet";
2
+ import { maplibreGL as h } from "@maplibre/maplibre-gl-leaflet";
3
+ import { addProtocol as w, removeProtocol as b } from "maplibre-gl";
4
+ import { Protocol as v } from "pmtiles";
5
+ function L(e) {
6
+ var o, i;
7
+ return {
8
+ attribution: e.attribution,
9
+ provider: {
10
+ kind: "vector",
11
+ capabilities: {
12
+ attributionRequired: !0,
13
+ offline: (o = e.offline) != null ? o : "unknown",
14
+ apiKey: (i = e.apiKey) != null ? i : "host-defined"
15
+ },
16
+ createLayer: e.createLayer
17
+ }
18
+ };
19
+ }
20
+ let r, l = 0;
21
+ function g() {
22
+ if (!r) {
23
+ const o = new v();
24
+ w("pmtiles", o.tile), r = { protocol: o, owners: 0 };
25
+ }
26
+ r.owners++;
27
+ let e = !1;
28
+ return () => {
29
+ if (!e) {
30
+ if ((r == null ? void 0 : r.owners) === 1 && l > 0)
31
+ throw new Error("Remove PMTiles basemaps before releasing the protocol");
32
+ e = !0, r && --r.owners === 0 && (b("pmtiles"), r = void 0);
33
+ }
34
+ };
35
+ }
36
+ function A(e) {
37
+ if (!e.attribution.trim())
38
+ throw new Error("PMTiles attribution is required");
39
+ const { style: o, attribution: i, onMap: s } = e;
40
+ return L({
41
+ attribution: i,
42
+ offline: "unknown",
43
+ apiKey: "host-defined",
44
+ createLayer(m) {
45
+ if (m.Layer !== y.Layer)
46
+ throw new Error(
47
+ "PMTiles requires /external with one shared Leaflet instance"
48
+ );
49
+ const t = h({
50
+ style: o,
51
+ interactive: !1,
52
+ attributionControl: !1
53
+ }), p = t.onAdd, c = t.onRemove;
54
+ let n = !1;
55
+ return t.onAdd = function(a) {
56
+ var u, d;
57
+ try {
58
+ p.call(this, a);
59
+ } catch (f) {
60
+ try {
61
+ (u = t.getMaplibreMap()) == null || u.remove();
62
+ } finally {
63
+ (d = t.getContainer()) == null || d.remove();
64
+ }
65
+ throw f;
66
+ }
67
+ n = !0, l++;
68
+ try {
69
+ s == null || s(t.getMaplibreMap());
70
+ } catch (f) {
71
+ try {
72
+ c.call(this, a);
73
+ } finally {
74
+ n = !1, l--;
75
+ }
76
+ throw f;
77
+ }
78
+ return this;
79
+ }, t.onRemove = function(a) {
80
+ if (n)
81
+ try {
82
+ c.call(this, a);
83
+ } finally {
84
+ n = !1, l--;
85
+ }
86
+ return this;
87
+ }, t;
88
+ }
89
+ });
90
+ }
91
+ export {
92
+ A as createPMTilesBasemapAdapter,
93
+ g as registerPMTilesProtocol
94
+ };
95
+ //# sourceMappingURL=leaflet-geokit.pmtiles.es.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"leaflet-geokit.pmtiles.es.js","sources":["../src/lib/providers.ts","../src/pmtiles.ts"],"sourcesContent":["import type * as Leaflet from \"leaflet\";\nimport { buildTileURL } from \"./TileProviderFactory.js\";\nimport type {\n TileProviderConfig,\n TileURLTemplate,\n} from \"./TileProviderFactory.js\";\n\n/** Technical potential is not a license to cache a vendor's data. */\nexport type OfflineSupport = \"unsupported\" | \"host-managed\" | \"unknown\";\nexport type ApiKeyRequirement = \"none\" | \"required\" | \"host-defined\";\n\nexport interface ProviderCapabilities {\n attributionRequired: boolean;\n offline: OfflineSupport;\n apiKey: ApiKeyRequirement;\n}\n\n/** Raster resolution does not own the map or drawing engine. */\nexport interface RasterTileProvider {\n kind: \"raster\";\n capabilities: ProviderCapabilities;\n resolve(): TileURLTemplate;\n}\n\n/** An optional renderer bridge must return a fresh, unmounted Leaflet layer.\n * The layer owns renderer/event cleanup in onRemove. Global protocols are host-owned.\n */\nexport interface VectorBasemapProvider {\n kind: \"vector\";\n capabilities: ProviderCapabilities;\n createLayer(leaflet: typeof Leaflet): Leaflet.Layer;\n}\n\nexport type BasemapProvider = RasterTileProvider | VectorBasemapProvider;\n\n/** Drawing is independent of basemap vendors; native renderer replacements\n * must implement this separate port before claiming drawing parity.\n */\nexport interface DrawEngineAdapter<TContext, TDocument, TCommand> {\n attach(context: TContext): void;\n read(): TDocument;\n write(document: TDocument): void;\n execute(command: TCommand): boolean;\n dispose(): void;\n}\n\nexport interface ProviderDiagnostics {\n kind: \"raster\" | \"vector\";\n attribution: \"present\" | \"missing\";\n attributionRequired: boolean;\n offline: OfflineSupport;\n apiKey: ApiKeyRequirement;\n drawing: \"leaflet-draw\";\n /** Static capability report, not a network/credentials/renderer health probe. */\n scope: \"configuration\";\n}\n\n/** Explicit field selection: never return URL, style, key, or arbitrary provider metadata. */\nexport function getProviderDiagnostics(\n provider: BasemapProvider,\n attribution: string,\n): ProviderDiagnostics {\n return {\n kind: provider.kind,\n attribution: attribution.trim() ? \"present\" : \"missing\",\n attributionRequired: provider.capabilities.attributionRequired,\n offline: provider.capabilities.offline,\n apiKey: provider.capabilities.apiKey,\n drawing: \"leaflet-draw\",\n scope: \"configuration\",\n };\n}\n\nexport function createRasterProvider(\n config: TileProviderConfig,\n): RasterTileProvider {\n const name = config.provider.trim().toLowerCase();\n // Snapshot the config so later caller mutation cannot silently change a provider.\n const snapshot = { ...config };\n return {\n kind: \"raster\",\n capabilities: {\n attributionRequired: true,\n offline: name === \"osm\" || name === \"here\" ? \"unsupported\" : \"unknown\",\n apiKey: name === \"here\" ? \"required\" : \"none\",\n },\n resolve: () => buildTileURL(snapshot),\n };\n}\n\n/** Existing custom tile-url behavior, without guessing licensing or authentication. */\nexport function createCustomRasterProvider(\n config: TileURLTemplate,\n): RasterTileProvider {\n const snapshot = { ...config, subdomains: config.subdomains?.slice() };\n return {\n kind: \"raster\",\n capabilities: {\n attributionRequired: true,\n offline: \"unknown\",\n apiKey: \"host-defined\",\n },\n resolve: () => ({ ...snapshot, subdomains: snapshot.subdomains?.slice() }),\n };\n}\n\nexport interface BasemapAdapter {\n provider: BasemapProvider;\n /** Trusted host-supplied attribution HTML, never unsanitized remote input. */\n attribution: string;\n}\n\n/** Feasibility shim: host injects a MapLibre-to-Leaflet bridge and owns PMTiles\n * protocol registration. No MapLibre, PMTiles, Google SDK, or keys in core.\n */\nexport function createMapLibreBasemapAdapter(options: {\n createLayer: (leaflet: typeof Leaflet) => Leaflet.Layer;\n attribution: string;\n offline?: OfflineSupport;\n apiKey?: ApiKeyRequirement;\n}): BasemapAdapter {\n return {\n attribution: options.attribution,\n provider: {\n kind: \"vector\",\n capabilities: {\n attributionRequired: true,\n offline: options.offline ?? \"unknown\",\n apiKey: options.apiKey ?? \"host-defined\",\n },\n createLayer: options.createLayer,\n },\n };\n}\n","import * as L from \"leaflet\";\nimport { maplibreGL } from \"@maplibre/maplibre-gl-leaflet\";\nimport { addProtocol, removeProtocol } from \"maplibre-gl\";\nimport type { StyleSpecification } from \"@maplibre/maplibre-gl-style-spec\";\nimport { Protocol } from \"pmtiles\";\nimport { createMapLibreBasemapAdapter } from \"./lib/providers.js\";\nimport type { BasemapAdapter } from \"./lib/providers.js\";\n\nlet registration: { protocol: Protocol; owners: number } | undefined;\nlet mountedLayers = 0;\n\n/** Register once per application; leases share a cache. Do not also register the\n * `pmtiles` scheme yourself. Release all leases after removing all adapter maps.\n * Hosts already managing the scheme may omit this helper entirely.\n */\nexport function registerPMTilesProtocol(): () => void {\n if (!registration) {\n const protocol = new Protocol();\n addProtocol(\"pmtiles\", protocol.tile);\n registration = { protocol, owners: 0 };\n }\n registration.owners++;\n let released = false;\n return () => {\n if (released) return;\n if (registration?.owners === 1 && mountedLayers > 0) {\n throw new Error(\"Remove PMTiles basemaps before releasing the protocol\");\n }\n released = true;\n if (registration && --registration.owners === 0) {\n removeProtocol(\"pmtiles\");\n registration = undefined;\n }\n };\n}\n\n/** Stable event surface of the renderer, without importing its private worker\n * declarations into strict NodeNext consumers. The runtime value is a MapLibre\n * Map; hosts needing its full API may narrow it using their own renderer types.\n */\nexport interface PMTilesMap {\n on(type: \"error\", listener: (event: { error: Error }) => void): unknown;\n on(type: \"load\" | \"remove\", listener: () => void): unknown;\n off(type: \"error\", listener: (event: { error: Error }) => void): unknown;\n off(type: \"load\" | \"remove\", listener: () => void): unknown;\n}\n\nexport interface PMTilesBasemapOptions {\n /** Trusted MapLibre style; use pmtiles://https://... vector source URLs.\n * Source-layer names must match the archive. No vendor schema is assumed.\n */\n style: StyleSpecification | string;\n /** Trusted HTML required by your data license; shown by Leaflet. */\n attribution: string;\n /** Called on mount, before asynchronous load/error events. Attach listeners\n * here for readiness and explicit host fallback. Never implies offline support.\n */\n onMap?: (map: PMTilesMap) => void;\n}\n\n/** Optional concrete MapLibre bridge. Use /external and the same Leaflet module.\n * Leaflet retains interaction, drawing, and view ownership (no pitch/rotation).\n * Protocol registration is explicit and application-owned.\n */\nexport function createPMTilesBasemapAdapter(\n options: PMTilesBasemapOptions,\n): BasemapAdapter {\n if (!options.attribution.trim())\n throw new Error(\"PMTiles attribution is required\");\n const { style, attribution, onMap } = options;\n return createMapLibreBasemapAdapter({\n attribution,\n offline: \"unknown\",\n apiKey: \"host-defined\",\n createLayer(leaflet) {\n if (leaflet.Layer !== L.Layer) {\n throw new Error(\n \"PMTiles requires /external with one shared Leaflet instance\",\n );\n }\n const layer = maplibreGL({\n style,\n interactive: false,\n attributionControl: false,\n });\n const add = layer.onAdd;\n const remove = layer.onRemove;\n let mounted = false;\n layer.onAdd = function (map) {\n try {\n add.call(this, map);\n } catch (error) {\n // The upstream bridge appends its container before constructing WebGL.\n // A constructor failure must not leave a dead canvas in the tile pane.\n try {\n layer.getMaplibreMap()?.remove();\n } finally {\n layer.getContainer()?.remove();\n }\n throw error;\n }\n mounted = true;\n mountedLayers++;\n try {\n onMap?.(layer.getMaplibreMap());\n } catch (error) {\n try {\n remove.call(this, map);\n } finally {\n mounted = false;\n mountedLayers--;\n }\n throw error;\n }\n return this;\n };\n layer.onRemove = function (map) {\n if (mounted) {\n try {\n remove.call(this, map);\n } finally {\n mounted = false;\n mountedLayers--;\n }\n }\n return this;\n };\n return layer;\n },\n });\n}\n"],"names":["createMapLibreBasemapAdapter","options","_a","_b","registration","mountedLayers","registerPMTilesProtocol","protocol","Protocol","addProtocol","released","removeProtocol","createPMTilesBasemapAdapter","style","attribution","onMap","leaflet","L","layer","maplibreGL","add","remove","mounted","map","error"],"mappings":";;;;AAmHO,SAASA,EAA6BC,GAK1B;;AACjB,SAAO;AAAA,IACL,aAAaA,EAAQ;AAAA,IACrB,UAAU;AAAA,MACR,MAAM;AAAA,MACN,cAAc;AAAA,QACZ,qBAAqB;AAAA,QACrB,UAASC,IAAAD,EAAQ,YAAR,OAAAC,IAAmB;AAAA,QAC5B,SAAQC,IAAAF,EAAQ,WAAR,OAAAE,IAAkB;AAAA,MAAA;AAAA,MAE5B,aAAaF,EAAQ;AAAA,IAAA;AAAA,EACvB;AAEJ;AC7HA,IAAIG,GACAC,IAAgB;AAMb,SAASC,IAAsC;AACpD,MAAI,CAACF,GAAc;AACjB,UAAMG,IAAW,IAAIC,EAAA;AACrB,IAAAC,EAAY,WAAWF,EAAS,IAAI,GACpCH,IAAe,EAAE,UAAAG,GAAU,QAAQ,EAAA;AAAA,EACrC;AACA,EAAAH,EAAa;AACb,MAAIM,IAAW;AACf,SAAO,MAAM;AACX,QAAI,CAAAA,GACJ;AAAA,WAAIN,KAAA,gBAAAA,EAAc,YAAW,KAAKC,IAAgB;AAChD,cAAM,IAAI,MAAM,uDAAuD;AAEzE,MAAAK,IAAW,IACPN,KAAgB,EAAEA,EAAa,WAAW,MAC5CO,EAAe,SAAS,GACxBP,IAAe;AAAA;AAAA,EAEnB;AACF;AA8BO,SAASQ,EACdX,GACgB;AAChB,MAAI,CAACA,EAAQ,YAAY,KAAA;AACvB,UAAM,IAAI,MAAM,iCAAiC;AACnD,QAAM,EAAE,OAAAY,GAAO,aAAAC,GAAa,OAAAC,EAAA,IAAUd;AACtC,SAAOD,EAA6B;AAAA,IAClC,aAAAc;AAAA,IACA,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,YAAYE,GAAS;AACnB,UAAIA,EAAQ,UAAUC,EAAE;AACtB,cAAM,IAAI;AAAA,UACR;AAAA,QAAA;AAGJ,YAAMC,IAAQC,EAAW;AAAA,QACvB,OAAAN;AAAA,QACA,aAAa;AAAA,QACb,oBAAoB;AAAA,MAAA,CACrB,GACKO,IAAMF,EAAM,OACZG,IAASH,EAAM;AACrB,UAAII,IAAU;AACd,aAAAJ,EAAM,QAAQ,SAAUK,GAAK;;AAC3B,YAAI;AACF,UAAAH,EAAI,KAAK,MAAMG,CAAG;AAAA,QACpB,SAASC,GAAO;AAGd,cAAI;AACF,aAAAtB,IAAAgB,EAAM,eAAA,MAAN,QAAAhB,EAAwB;AAAA,UAC1B,UAAA;AACE,aAAAC,IAAAe,EAAM,aAAA,MAAN,QAAAf,EAAsB;AAAA,UACxB;AACA,gBAAMqB;AAAA,QACR;AACA,QAAAF,IAAU,IACVjB;AACA,YAAI;AACF,UAAAU,KAAA,QAAAA,EAAQG,EAAM;QAChB,SAASM,GAAO;AACd,cAAI;AACF,YAAAH,EAAO,KAAK,MAAME,CAAG;AAAA,UACvB,UAAA;AACE,YAAAD,IAAU,IACVjB;AAAA,UACF;AACA,gBAAMmB;AAAA,QACR;AACA,eAAO;AAAA,MACT,GACAN,EAAM,WAAW,SAAUK,GAAK;AAC9B,YAAID;AACF,cAAI;AACF,YAAAD,EAAO,KAAK,MAAME,CAAG;AAAA,UACvB,UAAA;AACE,YAAAD,IAAU,IACVjB;AAAA,UACF;AAEF,eAAO;AAAA,MACT,GACOa;AAAA,IACT;AAAA,EAAA,CACD;AACH;"}
@@ -499,5 +499,5 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
499
499
  }
500
500
  </style>
501
501
  <div class="map-container" part="host map"></div>
502
- `;const i=this._root.querySelector(".map-container");if(!(i instanceof HTMLDivElement))throw new Error("Failed to initialize map container");this._container=i;const s=this.getAttribute("log-level");s&&(this._logLevel=s,this._logger.setLevel(s))}_controlsFromAttributes(){return{polygon:this.hasAttribute("draw-polygon"),polyline:this.hasAttribute("draw-polyline"),rectangle:this.hasAttribute("draw-rectangle"),circle:this.hasAttribute("draw-circle"),cake:this.hasAttribute("draw-layer-cake"),marker:this.hasAttribute("draw-marker"),move:this.hasAttribute("draw-move"),edit:this.hasAttribute("edit-features"),delete:this.hasAttribute("delete-features"),ruler:this.hasAttribute("draw-ruler")}}_mapConfig(){return{latitude:this._latitude,longitude:this._longitude,zoom:this._zoom,minZoom:this._minZoom,maxZoom:this._maxZoom,tileUrl:this._tileUrl,tileAttribution:this._tileAttribution,readOnly:this._readOnly,fitToDataOnLoad:!1,logLevel:this._logLevel,devOverlay:this._devOverlay,polygonAllowIntersection:this._polygonAllowIntersection,preferCanvas:this._preferCanvas,useExternalLeaflet:this._useExternalLeaflet,skipLeafletStyles:this._skipLeafletStyles}}async connectedCallback(){var i,s,r;this._logger.debug("connectedCallback",this._currentConfig()),this._setStatus({state:"initializing",ready:!1,busy:!0,featureCount:0,lastEvent:"connected",lastError:null}),Lc({root:this._root,skipStyles:this._skipLeafletStyles}),this._applyThemeStyles(),this._controller=new sm({container:this._container,map:this._mapConfig(),controls:this._controlsFromAttributes(),readOnly:this._readOnly,logger:this._logger.child("controller"),callbacks:{onToolCapabilitiesChanged:()=>this._emitToolCapabilities(),onReady:h=>{this.dispatchEvent(new CustomEvent(ie.Ready,{detail:h})),this._syncStatusFromController({state:"ready",ready:!0,busy:!1,lastEvent:ie.Ready,clearLastError:!0})},onCreated:h=>{this.dispatchEvent(new CustomEvent(ie.Created,{detail:h})),this._setStatus({state:"ready",ready:!0,busy:!1,featureCount:this._status.featureCount+1,lastEvent:ie.Created,lastError:null})},onEdited:h=>{this.dispatchEvent(new CustomEvent(ie.Edited,{detail:h})),this._setStatus({state:"ready",ready:!0,busy:!1,featureCount:h.geoJSON.features.length,lastEvent:ie.Edited,lastError:null})},onDeleted:h=>{this.dispatchEvent(new CustomEvent(ie.Deleted,{detail:h})),this._setStatus({state:"ready",ready:!0,busy:!1,featureCount:h.geoJSON.features.length,lastEvent:ie.Deleted,lastError:null})},onError:h=>{this._emitError(h,{state:h.recoverable?this._status.ready?"ready":this._status.state:"error",lastEvent:ie.Error})},onTileError:h=>{if(this._tileProvider)return;const f=this._describeTileLayerError(h,"tile-url");this._handleTileProviderError("tile_load_failed",f,"tile-url")},onToolTrigger:h=>{this._emitToolTriggerResult(h)},onToolEvent:(h,f)=>{this._emitToolLifecycleEvent(h,f)},onLayerEvent:(h,f)=>{this.dispatchEvent(new CustomEvent(h,{detail:f,bubbles:!0,composed:!0}))},onLayerStyleRequested:h=>!this.dispatchEvent(new CustomEvent("leaflet-geokit:layer-style-request",{detail:h,cancelable:!0,bubbles:!0,composed:!0})),onSaved:h=>{this.dispatchEvent(new CustomEvent(ie.Export,{detail:{geoJSON:h.geoJSON,featureCount:h.featureCount,adapter:"editing"}})),this._setStatus({state:"ready",ready:!0,busy:!1,featureCount:h.featureCount,lastEvent:ie.Export,lastError:null})}},leaflet:(i=this._leafletInstance)!=null?i:void 0,useExternalLeaflet:this._useExternalLeaflet,toolHooks:this._toolHooks,toolEventEmitter:this._toolEventEmitter,markerIconConfig:this._effectiveMarkerIconConfig(),toolButtonConfig:this._effectiveToolButtonConfig(),toolbarGroups:this._effectiveToolbarGroups(),snapping:(s=this._snapping)!=null?s:null,measurementOverlay:(r=this._measurementOverlay)!=null?r:null}),this.addEventListener(_i.ToolCommand,this._externalToolCommandListener),this.addEventListener("leaflet-geokit:trigger-tool",this._externalToolTriggerListener),this.addEventListener("leaflet-geokit:activate-tool",this._externalToolTriggerListener),this.addEventListener("leaflet-geokit:deactivate-tool",this._externalToolDeactivateListener),await this._controller.init(),this._status.state!=="error"&&this._tileProvider&&this._updateTileLayer()}async disconnectedCallback(){this._logger.debug("disconnectedCallback"),this._activeTileProvider="tile-url",this._providerCapabilityError=null,this._controller&&(await this._controller.destroy(),this._controller=null),this._activeTool=null,this.removeEventListener(_i.ToolCommand,this._externalToolCommandListener),this.removeEventListener("leaflet-geokit:trigger-tool",this._externalToolTriggerListener),this.removeEventListener("leaflet-geokit:activate-tool",this._externalToolTriggerListener),this.removeEventListener("leaflet-geokit:deactivate-tool",this._externalToolDeactivateListener),this._setStatus({state:"uninitialized",ready:!1,busy:!1,featureCount:0,lastEvent:"disconnected",lastError:null})}static get observedAttributes(){return["latitude","longitude","zoom","min-zoom","max-zoom","tile-url","tile-attribution","tile-provider","tile-style","api-key","here-api-key","read-only","log-level","dev-overlay","prefer-canvas","use-external-leaflet","skip-leaflet-styles","marker-icon-url","marker-icon-retina-url","marker-shadow-url","marker-icon-size","marker-icon-anchor","marker-popup-anchor","tool-button-config","toolbar-groups","theme-url","draw-polygon","draw-polyline","draw-rectangle","draw-circle","draw-layer-cake","draw-marker","draw-move","draw-ruler","edit-features","delete-features","polygon-allow-intersection"]}attributeChangedCallback(i,s,r){var h;switch(this._logger.debug("attributeChanged",{name:i,value:r}),i){case"latitude":this._latitude=this._coerceNumber(r,0);break;case"longitude":this._longitude=this._coerceNumber(r,0);break;case"zoom":this._zoom=this._coerceNumber(r,2);break;case"min-zoom":this._minZoom=r!=null?this._coerceNumber(r):void 0;break;case"max-zoom":this._maxZoom=r!=null?this._coerceNumber(r):void 0;break;case"tile-url":this._tileUrl=r!=null?r:"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",this._controller&&this._updateTileLayer();break;case"tile-attribution":this._tileAttribution=r!=null?r:void 0,this._controller&&this._updateTileLayer();break;case"tile-provider":this._tileProvider=this._normalizeText(r,{lowercase:!0}),this._controller&&this._updateTileLayer();break;case"tile-style":this._tileStyle=this._normalizeText(r),this._controller&&this._updateTileLayer();break;case"api-key":case"here-api-key":this._syncApiKeyFromAttributes(),this._controller&&this._updateTileLayer();break;case"theme-url":this._themeUrl=r!=null?r:void 0,this.isConnected&&this._applyThemeStyles();break;case"read-only":this._readOnly=r!==null;break;case"log-level":this._logLevel=r!=null?r:this._logLevel,this._logger.setLevel(this._logLevel);break;case"dev-overlay":this._devOverlay=r!==null;break;case"polygon-allow-intersection":this._polygonAllowIntersection=r!==null;break;case"prefer-canvas":this._preferCanvas=r!==null;break;case"use-external-leaflet":this._useExternalLeaflet=r!==null;break;case"skip-leaflet-styles":this._skipLeafletStyles=r!==null;break}if(this._controller){if(i==="latitude"||i==="longitude"||i==="zoom")this._controller.setView(this._latitude,this._longitude,this._zoom);else if(this._isMarkerIconAttribute(i))this._syncMarkerIconConfig();else if(i==="tool-button-config")this._syncToolButtonConfig();else if(i==="toolbar-groups")this._syncToolbarGroups();else if(i==="min-zoom"||i==="max-zoom"||i==="read-only"||i==="dev-overlay"||i==="log-level"||i==="prefer-canvas"||i==="use-external-leaflet"||i==="skip-leaflet-styles"||i.startsWith("draw-")||i==="edit-features"||i==="delete-features"){const f=this._controller;(h=f.configure)==null||h.call(f,this._mapConfig(),this._controlsFromAttributes()),this._configurationUpdate=this._configurationUpdate.then(async()=>{var d;this._controller!==f||!this.isConnected||((d=f.configure)==null||d.call(f,this._mapConfig(),this._controlsFromAttributes()),await f.init(),this._tileProvider&&this._updateTileLayer())})}}}_updateTileLayer(){var s,r,h,f,d,m;if(!this._controller)return;const i=this._controller;if(typeof i.setTileLayer!="function"){this._logger.warn("setTileLayer is not available on MapController yet");return}this._providerCapabilityError=null;try{if(this._tileProvider){const _=this._tileProvider,x={provider:_,style:this._tileStyle,apiKey:this._apiKey,attribution:this._tileAttribution},b=Zf(x);if(!b.valid){const S=(s=b.error)!=null&&s.toLowerCase().includes("api key")?"missing_api_key":"tile_load_failed";this._handleTileProviderError(S,(r=b.error)!=null?r:"Invalid tile provider configuration",_);return}const E=da(x),C=this._activeTileProvider;i.setTileLayer(E,{onTileError:S=>{if(this._tileProvider!==_)return;const O=this._describeTileLayerError(S,_),N=_==="here"?this._resolveHereTileLayerErrorCode(O):"tile_load_failed";this._handleTileProviderError(N,O,_)}}),this._activeTileProvider=_,this._emitTileProviderChanged(_,this._tileStyle,C);return}i.setTileLayer({urlTemplate:this._tileUrl,attribution:(h=this._tileAttribution)!=null?h:"",maxZoom:this._maxZoom,subdomains:["a","b","c"]},{onTileError:_=>{const x=this._describeTileLayerError(_,"tile-url");this._handleTileProviderError("tile_load_failed",x,"tile-url")}}),this._activeTileProvider="tile-url"}catch(_){const x=this._resolveTileProviderErrorCode(_);this._logger.error("Failed to update tile layer",{error:_,code:x}),this._handleTileProviderError(x,_ instanceof Error?_.message:"Unknown tile layer error",(f=this._tileProvider)!=null?f:"unknown")}finally{(m=(d=this._controller)==null?void 0:d.setToolProvider)==null||m.call(d,this._toolProviderCapability()),this._emitToolCapabilities()}}_handleTileProviderError(i,s,r){var d,m;this._logger.error(`Tile provider error (${i}): ${s}`);const h=Date.now();this._providerCapabilityError={code:i==="missing_api_key"?"missing_api_key":i==="unknown_provider"?"missing_provider":"runtime_error",message:i==="missing_api_key"?"Requested provider requires an API key":i==="unknown_provider"?"Requested provider is unavailable":"Requested provider failed; using fallback tiles"},this.dispatchEvent(new CustomEvent("tile-provider-error",{bubbles:!0,detail:{code:i,message:s,provider:r,timestamp:h}})),this._emitDiagnostic({code:i,message:s,recoverable:!0,severity:"warn",timestamp:h},{state:this._status.ready?"ready":this._status.state,lastEvent:"tile-provider-error"});const f=this._controller;typeof f.setTileLayer=="function"&&(f.setTileLayer({urlTemplate:"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",attribution:'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',maxZoom:19,subdomains:["a","b","c"]}),this._activeTileProvider="osm"),(m=(d=this._controller)==null?void 0:d.setToolProvider)==null||m.call(d,this._toolProviderCapability()),this._emitToolCapabilities()}_emitTileProviderChanged(i,s,r){this.dispatchEvent(new CustomEvent("tile-provider-changed",{bubbles:!0,detail:{provider:i,style:s,previousProvider:r,timestamp:Date.now()}}))}_toolProviderCapability(){var r,h;const i=this._activeTileProvider==="adapter"?"adapter":(r=this._tileProvider)!=null?r:"tile-url";let s=this._providerCapabilityError;return i!=="adapter"&&i!=="tile-url"&&i!=="osm"&&i!=="here"?s={code:"missing_provider",message:"Requested provider is unavailable"}:i==="here"&&!((h=this._apiKey)!=null&&h.trim())&&(s={code:"missing_api_key",message:"Requested provider requires an API key"}),{requested:i,active:this._activeTileProvider,state:s?"unavailable":"enabled",reason:s?{...s}:null}}setBasemapAdapter(i){var r,h;if(!this._status.ready||!this._controller)throw new Error("Map is not ready");if(!i){this._updateTileLayer();return}this._controller.setBasemapAdapter(i);const s=this._activeTileProvider;this._activeTileProvider="adapter",this._providerCapabilityError=null,this._emitTileProviderChanged("adapter",void 0,s),(h=(r=this._controller).setToolProvider)==null||h.call(r,this._toolProviderCapability()),this._emitToolCapabilities()}getProviderDiagnostics(){var r,h,f;const i=(f=(h=(r=this._controller)==null?void 0:r.getProviderDiagnostics)==null?void 0:h.call(r))!=null?f:null;if(!i||this._activeTileProvider==="adapter")return i;const s=this._activeTileProvider==="tile-url"&&this._tileUrl===da({provider:"osm"}).urlTemplate?"osm":this._activeTileProvider;if(s==="osm"||s==="here"){const d=eu({provider:s});return{...i,...d.capabilities}}return i}getToolCapabilities(){var s,r,h;return{...(h=(r=(s=this._controller)==null?void 0:s.getToolCapabilities)==null?void 0:r.call(s))!=null?h:nu({ready:!1,readOnly:this._readOnly,controls:this._controlsFromAttributes(),available:{},layerCount:0,selectedFeatureIds:[],activeTool:null,config:this._effectiveToolButtonConfig(),groups:this._effectiveToolbarGroups(),provider:this._toolProviderCapability()}),provider:this._toolProviderCapability()}}setToolSelection(i){var s;(s=this._controller)==null||s.setToolSelection(i)}_emitToolCapabilities(){const i=this.getToolCapabilities(),s=JSON.stringify(i);s!==this._lastCapabilities&&(this._lastCapabilities=s,this.dispatchEvent(new CustomEvent(_i.ToolCapabilitiesChanged,{detail:i,bubbles:!0,composed:!0})))}_isMarkerIconAttribute(i){return i==="marker-icon-url"||i==="marker-icon-retina-url"||i==="marker-shadow-url"||i==="marker-icon-size"||i==="marker-icon-anchor"||i==="marker-popup-anchor"}_effectiveMarkerIconConfig(){const i=(r,h)=>{this._emitError({code:"invalid_marker_icon_config",message:r,recoverable:!0,cause:h},{state:this._status.ready?"ready":this._status.state})};if(this._markerIconConfig===null)return null;if(this._markerIconConfig!==void 0)return am(this._markerIconConfig,{reportError:i});const s=this.getAttribute("marker-icon-url");return s==null?null:lm({iconUrl:s,iconRetinaUrl:this.getAttribute("marker-icon-retina-url"),shadowUrl:this.getAttribute("marker-shadow-url"),iconSize:this.getAttribute("marker-icon-size"),iconAnchor:this.getAttribute("marker-icon-anchor"),popupAnchor:this.getAttribute("marker-popup-anchor")},{reportError:i})}_syncMarkerIconConfig(){const i=this._controller;typeof(i==null?void 0:i.setMarkerIconConfig)=="function"&&i.setMarkerIconConfig(this._effectiveMarkerIconConfig())}_effectiveToolButtonConfig(){if(this._toolButtonConfig!==void 0)return this._toolButtonConfig;const i=this.getAttribute("tool-button-config");if(i==null||i.trim()==="")return null;try{const s=JSON.parse(i);if(!s||typeof s!="object"||Array.isArray(s))throw new Error("tool-button-config must be a JSON object");return s}catch(s){return this._emitError({code:"invalid_tool_button_config",message:"Failed to parse tool-button-config",recoverable:!0,cause:s},{state:this._status.ready?"ready":this._status.state}),null}}_syncToolButtonConfig(){const i=this._controller;typeof(i==null?void 0:i.setToolButtonConfig)=="function"&&i.setToolButtonConfig(this._effectiveToolButtonConfig())}_effectiveToolbarGroups(){if(this._toolbarGroups!==void 0)return this._toolbarGroups;const i=this.getAttribute("toolbar-groups");if(i==null||i.trim()==="")return null;try{const s=JSON.parse(i);if(!Array.isArray(s))throw new Error("toolbar-groups must be a JSON array");return s}catch(s){return this._emitError({code:"invalid_toolbar_groups",message:"Failed to parse toolbar-groups",recoverable:!0,cause:s},{state:this._status.ready?"ready":this._status.state}),null}}_syncToolbarGroups(){const i=this._controller;typeof(i==null?void 0:i.setToolbarGroups)=="function"&&i.setToolbarGroups(this._effectiveToolbarGroups())}get latitude(){return this._latitude}set latitude(i){this._latitude=Number(i),this._reflect("latitude",String(this._latitude))}get longitude(){return this._longitude}set longitude(i){this._longitude=Number(i),this._reflect("longitude",String(this._longitude))}get zoom(){return this._zoom}set zoom(i){this._zoom=Number(i),this._reflect("zoom",String(this._zoom))}get minZoom(){return this._minZoom}set minZoom(i){this._minZoom=i,this._reflect("min-zoom",i!=null?String(i):null)}get maxZoom(){return this._maxZoom}set maxZoom(i){this._maxZoom=i,this._reflect("max-zoom",i!=null?String(i):null)}get tileUrl(){return this._tileUrl}set tileUrl(i){this._tileUrl=i,this._reflect("tile-url",i),this._controller&&this._updateTileLayer()}get tileProvider(){return this._tileProvider}set tileProvider(i){var s;this._tileProvider=this._normalizeText(i!=null?i:null,{lowercase:!0}),this._reflect("tile-provider",(s=this._tileProvider)!=null?s:null),this._controller&&this._updateTileLayer()}get tileStyle(){return this._tileStyle}set tileStyle(i){var s;this._tileStyle=this._normalizeText(i!=null?i:null),this._reflect("tile-style",(s=this._tileStyle)!=null?s:null),this._controller&&this._updateTileLayer()}get apiKey(){return this._apiKey}set apiKey(i){var s;this._apiKey=this._normalizeText(i!=null?i:null),this._reflect("api-key",(s=this._apiKey)!=null?s:null),this.hasAttribute("here-api-key")&&this.removeAttribute("here-api-key"),this._controller&&this._updateTileLayer()}get status(){return this._cloneStatus(this._status)}get tileAttribution(){return this._tileAttribution}set tileAttribution(i){this._tileAttribution=i,this._reflect("tile-attribution",i!=null?i:null),this._controller&&this._updateTileLayer()}get readOnly(){return this._readOnly}set readOnly(i){this._readOnly=!!i,this._booleanReflect("read-only",this._readOnly)}get logLevel(){return this._logLevel}set logLevel(i){this._logLevel=i,this._logger.setLevel(i),this._reflect("log-level",i)}get devOverlay(){return this._devOverlay}set devOverlay(i){this._devOverlay=!!i,this._booleanReflect("dev-overlay",this._devOverlay)}get preferCanvas(){return this._preferCanvas}set preferCanvas(i){this._preferCanvas=!!i,this._booleanReflect("prefer-canvas",this._preferCanvas)}get useExternalLeaflet(){return this._useExternalLeaflet}set useExternalLeaflet(i){this._useExternalLeaflet=!!i,this._booleanReflect("use-external-leaflet",this._useExternalLeaflet)}get skipLeafletStyles(){return this._skipLeafletStyles}set skipLeafletStyles(i){this._skipLeafletStyles=!!i,this._booleanReflect("skip-leaflet-styles",this._skipLeafletStyles)}get markerIconConfig(){return this._markerIconConfig}set markerIconConfig(i){this._markerIconConfig=i,this._syncMarkerIconConfig()}get toolButtonConfig(){return this._toolButtonConfig}set toolButtonConfig(i){this._toolButtonConfig=i,this._syncToolButtonConfig()}get toolbarGroups(){return this._toolbarGroups}set toolbarGroups(i){this._toolbarGroups=i,this._syncToolbarGroups()}get snapping(){return this._snapping}set snapping(i){var r;const s=this._snapping;this._snapping=i;try{(r=this._controller)==null||r.setSnappingOptions(i)}catch(h){throw this._snapping=s,h}}get measurementOverlay(){return this._measurementOverlay}set measurementOverlay(i){var r;const s=this._measurementOverlay;this._measurementOverlay=i;try{(r=this._controller)==null||r.setMeasurementOverlayOptions(i)}catch(h){throw this._measurementOverlay=s,h}}get leafletInstance(){return this._leafletInstance}set leafletInstance(i){this._leafletInstance=i}get toolHooks(){return this._toolHooks}set toolHooks(i){this._toolHooks=i;const s=this._controller;typeof(s==null?void 0:s.setToolObservers)=="function"&&s.setToolObservers({toolHooks:this._toolHooks,toolEventEmitter:this._toolEventEmitter})}get toolEventEmitter(){return this._toolEventEmitter}set toolEventEmitter(i){this._toolEventEmitter=i;const s=this._controller;typeof(s==null?void 0:s.setToolObservers)=="function"&&s.setToolObservers({toolHooks:this._toolHooks,toolEventEmitter:this._toolEventEmitter})}get themeCss(){return this._themeCss}set themeCss(i){this._themeCss=typeof i=="string"?i:"",this.isConnected&&this._applyThemeStyles()}async getGeoJSON(){return this._logger.debug("getGeoJSON"),this._controller?this._controller.getGeoJSON():{type:"FeatureCollection",features:[]}}async importGeoJSON(i,s={}){var f,d,m,_;const r=(f=s.behavior)!=null?f:"replace";if(this._logger.debug("importGeoJSON",{behavior:r,fitToData:(d=s.fitToData)!=null?d:!1,features:(_=(m=i==null?void 0:i.features)==null?void 0:m.length)!=null?_:0}),!this._controller)return[];const h=this.status;return this._setImportLoadingStatus(h),this._performImport(i,s,h,r==="add"?"Failed to add GeoJSON features to the map":"Failed to load GeoJSON into the map")}async loadGeoJSON(i){var s,r;this._logger.debug("loadGeoJSON",{features:(r=(s=i==null?void 0:i.features)==null?void 0:s.length)!=null?r:0}),await this.importGeoJSON(i,{behavior:"replace"})}async clearLayers(){this._logger.debug("clearLayers"),this._controller&&(await this._controller.clearLayers(),this._setStatus({state:"ready",ready:!0,busy:!1,featureCount:0,lastEvent:"clearLayers",lastError:null}))}async addFeatures(i){var s,r;return this._logger.debug("addFeatures",{count:(r=(s=i==null?void 0:i.features)==null?void 0:s.length)!=null?r:0}),this.importGeoJSON(i,{behavior:"add"})}async updateFeature(i,s){this._logger.debug("updateFeature",{id:i}),this._controller&&await this._controller.updateFeature(i,s)}async removeFeature(i){this._logger.debug("removeFeature",{id:i}),this._controller&&(await this._controller.removeFeature(i),await this._syncStatusFromController({state:"ready",ready:!0,busy:!1,lastEvent:"removeFeature",clearLastError:!0}))}async fitBoundsToData(i){this._logger.debug("fitBoundsToData",{padding:i}),this._controller&&await this._controller.fitBoundsToData(typeof i=="number"?i:.05)}async fitBounds(i,s){this._logger.debug("fitBounds",{bounds:i,padding:s}),this._controller&&await this._controller.fitBounds(i,typeof s=="number"?s:.05)}async setView(i,s,r){this._logger.debug("setView",{lat:i,lng:s,zoom:r}),this.latitude=i,this.longitude=s,typeof r=="number"&&(this.zoom=r),this._controller&&await this._controller.setView(i,s,r)}async exportGeoJSON(i={}){var f;const s=(f=i.adapter)!=null?f:"editing";if(this._logger.debug("exportGeoJSON",{adapter:s}),!this._controller)return{type:"FeatureCollection",features:[]};const r=await this._exportWithController(i),h={geoJSON:r,featureCount:r.features.length,adapter:s};return this.dispatchEvent(new CustomEvent(ie.Export,{detail:h})),r}async mergePolygons(i){if(this._logger.debug("mergePolygons"),!this._controller)return null;const r=(await this._controller.getGeoJSON()).features.length,h=await this._controller.mergeVisiblePolygons(i);if(h){const f=await this._controller.getGeoJSON(),d={id:h,mergedFeatureCount:r-f.features.length+1,geoJSON:f};this.dispatchEvent(new CustomEvent("leaflet-draw:merged",{detail:d})),this._setStatus({state:"ready",ready:!0,busy:!1,featureCount:f.features.length,lastEvent:"leaflet-draw:merged",lastError:null})}return h}async setMeasurementUnits(i){this._logger.debug("setMeasurementUnits",{system:i}),this._controller&&this._controller.setRulerUnits(i)}getSnappingOptions(){var i,s;return(s=(i=this._controller)==null?void 0:i.getSnappingOptions())!=null?s:this._snapping?{...this._snapping}:null}getMeasurementOverlayOptions(){var i,s;return(s=(i=this._controller)==null?void 0:i.getMeasurementOverlayOptions())!=null?s:this._measurementOverlay?{...this._measurementOverlay}:null}_nextToolCommandId(){return this._toolCommandSequence+=1,`tool-${Date.now().toString(36)}-element-${this._toolCommandSequence.toString(36)}`}_emitToolTriggerRequested(i,s){this.dispatchEvent(new CustomEvent("leaflet-geokit:tool-trigger-requested",{bubbles:!0,composed:!0,detail:{tool:i,source:s.source,groupId:s.groupId,commandId:s.commandId,handled:!1,timestamp:Date.now()}}))}_baseToolEventDetail(i,s,r){return{tool:i,action:s,source:r.source,groupId:r.groupId,commandId:r.commandId,previousTool:null,activeTool:null,featureIds:[],timestamp:Date.now()}}_emitStandaloneToolFailure(i,s,r,h,f=!0){const d=this._baseToolEventDetail(i,s,r);f&&this._emitToolLifecycleEvent(_i.ToolCommand,d),this._emitToolLifecycleEvent(_i.ToolFailed,{...d,reason:h,timestamp:Date.now()}),this._emitToolTriggerResult({tool:i,source:r.source,groupId:r.groupId,commandId:r.commandId,handled:!1,timestamp:Date.now(),error:h})}async activateTool(i,s={}){var _,x,b;const r=(_=s.source)!=null?_:"api",h=((x=s.commandId)==null?void 0:x.trim())||this._nextToolCommandId(),f={source:r,groupId:s.groupId,commandId:h};if(this._emitToolTriggerRequested(i,f),!this._controller)return this._emitStandaloneToolFailure(i,i==="select"?"deactivate":"activate",f,"Map controller is not initialized"),!1;const d=this._controller,m=typeof d.activateTool=="function"?d.activateTool.bind(d):(b=d.triggerTool)==null?void 0:b.bind(d);return m?m(i,f):(this._emitStandaloneToolFailure(i,i==="select"?"deactivate":"activate",f,"Map controller cannot activate tools"),!1)}async triggerTool(i,s={}){return this.activateTool(i,s)}async deactivateTool(i={}){var m,_,x;const s=(m=i.source)!=null?m:"api",r=((_=i.commandId)==null?void 0:_.trim())||this._nextToolCommandId(),h={source:s,groupId:i.groupId,commandId:r};if(this._emitToolTriggerRequested("select",h),!this._controller)return this._emitStandaloneToolFailure("select","deactivate",h,"Map controller is not initialized"),!1;const f=this._controller;if(typeof f.deactivateTool=="function")return f.deactivateTool(h);const d=typeof f.activateTool=="function"?f.activateTool.bind(f):(x=f.triggerTool)==null?void 0:x.bind(f);return d?d("select",h):(this._emitStandaloneToolFailure("select","deactivate",h,"Map controller cannot deactivate tools"),!1)}async loadGeoJSONFromUrl(i,s={}){var m,_,x;const r=(m=s.behavior)!=null?m:"replace";if(this._logger.debug("loadGeoJSONFromUrl",{url:i,behavior:r,fitToData:(_=s.fitToData)!=null?_:!0}),!this._controller)return;const h=this.status;this._setImportLoadingStatus(h);let f;try{f=await fetch(i,{headers:{Accept:"application/json"}})}catch(b){const E=new Error(`Failed to fetch GeoJSON from ${i}`);throw this._emitError({code:"data_fetch_failed",message:E.message,recoverable:!0,cause:b},{state:h.ready?"ready":h.state,featureCount:h.featureCount}),E}if(!f.ok){const b=new Error(`Failed to fetch GeoJSON from ${i}: ${f.status} ${f.statusText}`);throw this._emitError({code:"data_fetch_failed",message:b.message,recoverable:!0,cause:b},{state:h.ready?"ready":h.state,featureCount:h.featureCount}),b}let d;try{d=await f.json()}catch(b){const E=new Error(`Failed to parse GeoJSON from ${i}`);throw this._emitError({code:"data_parse_failed",message:E.message,recoverable:!0,cause:b},{state:h.ready?"ready":h.state,featureCount:h.featureCount}),E}await this._performImport(d,{behavior:r,fitToData:(x=s.fitToData)!=null?x:!0},h,r==="add"?`Failed to add GeoJSON from ${i}`:`Failed to load GeoJSON from ${i}`)}async loadGeoJSONFromText(i,s={}){var d,m,_,x;const r=(d=s.behavior)!=null?d:"replace";if(this._logger.debug("loadGeoJSONFromText",{behavior:r,fitToData:(m=s.fitToData)!=null?m:!0,length:(_=i==null?void 0:i.length)!=null?_:0}),!this._controller)return;const h=this.status;this._setImportLoadingStatus(h);let f;try{f=JSON.parse(i)}catch(b){const E=new Error("Failed to parse GeoJSON text");throw this._emitError({code:"data_parse_failed",message:E.message,recoverable:!0,cause:b},{state:h.ready?"ready":h.state,featureCount:h.featureCount}),E}await this._performImport(f,{behavior:r,fitToData:(x=s.fitToData)!=null?x:!0},h,r==="add"?"Failed to add parsed GeoJSON into the map":"Failed to load parsed GeoJSON into the map")}_setImportLoadingStatus(i){this._setStatus({state:"loading",ready:i.ready,busy:!0,featureCount:i.featureCount,lastEvent:ie.Ingest,lastError:null})}async _performImport(i,s,r,h){var _,x;const f=(_=s.behavior)!=null?_:"replace",d={fc:i,mode:f==="add"?"add":"load"};this.dispatchEvent(new CustomEvent(ie.Ingest,{detail:d}));const m=d.fc&&d.fc.type==="FeatureCollection"?d.fc:i;try{const b=await this._importWithController(m,{...s,behavior:f,fitToData:(x=s.fitToData)!=null?x:!1});return await this._syncStatusFromController({state:"ready",ready:!0,busy:!1,lastEvent:ie.Ingest,clearLastError:!0}),b}catch(b){throw this._emitError({code:f==="add"?"data_add_failed":"data_load_failed",message:h,recoverable:!0,cause:b},{state:r.ready?"ready":r.state,featureCount:r.featureCount}),b}}getLayers(){var i,s;return(s=(i=this._controller)==null?void 0:i.getLayers())!=null?s:[]}async setLayerVisibility(i,s){var r;(r=this._controller)==null||r.setLayerVisibility(i,s)}async setLayerStyle(i,s){var r;(r=this._controller)==null||r.setLayerStyle(i,s)}async reorderLayers(i){var s;(s=this._controller)==null||s.reorderLayers(i)}async focusLayer(i){var s;await((s=this._controller)==null?void 0:s.focusLayer(i))}async removeLayer(i){var s;await((s=this._controller)==null?void 0:s.removeLayer(i))}getLayerCakeSession(){var i,s;return(s=(i=this._controller)==null?void 0:i.getLayerCakeSession())!=null?s:null}async updateLayerCakeSession(i){var s;(s=this._controller)==null||s.updateLayerCakeSession(i)}async saveLayerCakeSession(){var i;(i=this._controller)==null||i.saveLayerCakeSession()}async cancelLayerCakeSession(){var i;(i=this._controller)==null||i.cancelLayerCakeSession()}async _importWithController(i,s){var d,m;if(!this._controller)return[];const r=(d=s.behavior)!=null?d:"replace",h=(m=s.fitToData)!=null?m:!1,f=this._controller;return typeof f.importGeoJSON=="function"?f.importGeoJSON(i,{...s,behavior:r,fitToData:h}):r==="add"?f.addFeatures(i):(await f.loadGeoJSON(i,h),[])}async _exportWithController(i){if(!this._controller)return{type:"FeatureCollection",features:[]};const s=this._controller;return typeof s.exportGeoJSON=="function"?s.exportGeoJSON(i):s.getGeoJSON()}_currentConfig(){return{latitude:this._latitude,longitude:this._longitude,zoom:this._zoom,minZoom:this._minZoom,maxZoom:this._maxZoom,tileUrl:this._tileUrl,tileAttribution:this._tileAttribution,readOnly:this._readOnly,fitToDataOnLoad:!1,logLevel:this._logLevel,devOverlay:this._devOverlay,polygonAllowIntersection:this._polygonAllowIntersection,preferCanvas:this._preferCanvas,useExternalLeaflet:this._useExternalLeaflet,skipLeafletStyles:this._skipLeafletStyles}}_applyThemeStyles(){var r;const i=(r=this._themeUrl)==null?void 0:r.trim();if(i){if(!this._themeLinkEl){const h=document.createElement("link");h.setAttribute("rel","stylesheet"),h.setAttribute("data-geokit-theme-url","true"),this._root.appendChild(h),this._themeLinkEl=h}this._themeLinkEl.getAttribute("href")!==i&&this._themeLinkEl.setAttribute("href",i)}else this._themeLinkEl&&(this._themeLinkEl.remove(),this._themeLinkEl=null);const s=this._themeCss;if(s.trim().length>0){if(!this._themeStyleEl){const h=document.createElement("style");h.setAttribute("data-geokit-theme-css","true"),this._root.appendChild(h),this._themeStyleEl=h}this._themeStyleEl.textContent!==s&&(this._themeStyleEl.textContent=s)}else this._themeStyleEl&&(this._themeStyleEl.remove(),this._themeStyleEl=null)}_emitToolLifecycleEvent(i,s){i===_i.ToolStateChanged&&(this._activeTool=s.activeTool);const r=new CustomEvent(i,{bubbles:!0,composed:!0,detail:s});this._internalToolEvents.add(r),this.dispatchEvent(r)}_emitToolTriggerResult(i){this.dispatchEvent(new CustomEvent(i.handled?"leaflet-geokit:tool-triggered":"leaflet-geokit:tool-trigger-failed",{bubbles:!0,composed:!0,detail:i}))}_syncStatusFromController(i){const s=this._controller;return!s||typeof s.getGeoJSON!="function"?(this._setStatus({state:i.state,ready:i.ready,busy:i.busy,featureCount:this._status.featureCount,lastEvent:i.lastEvent,lastError:i.clearLastError?null:void 0}),Promise.resolve()):s.getGeoJSON().then(r=>{this._setStatus({state:i.state,ready:i.ready,busy:i.busy,featureCount:r.features.length,lastEvent:i.lastEvent,lastError:i.clearLastError?null:void 0})}).catch(()=>{this._setStatus({state:i.state,ready:i.ready,busy:i.busy,lastEvent:i.lastEvent,lastError:i.clearLastError?null:void 0})})}_emitError(i,s){var h;const r={...i,timestamp:Date.now()};return this.dispatchEvent(new CustomEvent(ie.Error,{detail:r})),this._emitDiagnostic({code:r.code,message:r.message,recoverable:r.recoverable,severity:r.recoverable?"warn":"error",cause:r.cause,timestamp:r.timestamp},{state:s.state,featureCount:s.featureCount,lastEvent:(h=s.lastEvent)!=null?h:ie.Error}),r}_emitDiagnostic(i,s){var h,f;const r={...i,state:s.state};return this.dispatchEvent(new CustomEvent(_i.Diagnostic,{detail:r})),this._setStatus({state:s.state,ready:s.state==="ready",busy:s.state==="initializing"||s.state==="loading",featureCount:(h=s.featureCount)!=null?h:this._status.featureCount,lastEvent:(f=s.lastEvent)!=null?f:_i.Diagnostic,lastError:{code:r.code,message:r.message,recoverable:r.recoverable,timestamp:r.timestamp}}),r}_setStatus(i){const s={...this._status,...i,lastError:i.lastError===null?void 0:i.lastError!==void 0?{...i.lastError}:this._status.lastError?{...this._status.lastError}:void 0,timestamp:Date.now()};this._status=s,this.dispatchEvent(new CustomEvent(_i.Status,{detail:this._cloneStatus(s)}))}_cloneStatus(i){return{...i,lastError:i.lastError?{...i.lastError}:void 0}}_syncApiKeyFromAttributes(){const i=this._normalizeText(this.getAttribute("api-key")),s=this._normalizeText(this.getAttribute("here-api-key"));this._apiKey=i!=null?i:s}_normalizeText(i,s){if(typeof i!="string")return;const r=i.trim();if(r)return s!=null&&s.lowercase?r.toLowerCase():r}_resolveTileProviderErrorCode(i){return i instanceof Error&&i.message.toLowerCase().includes("unknown tile provider")?"unknown_provider":"tile_load_failed"}_resolveHereTileLayerErrorCode(i){const s=i.toLowerCase();return s.includes("permission")||s.includes("forbidden")||s.includes("403")||s.includes("unauthorized")||s.includes("not authorized")||s.includes("not authorised")||s.includes("access denied")?"permission_denied":"invalid_api_key"}_describeTileLayerError(i,s){if(i&&typeof i=="object"&&"error"in i&&i.error instanceof Error)return i.error.message;if(i instanceof Error&&i.message)return i.message;if(i&&typeof i=="object"&&"message"in i&&typeof i.message=="string"){const r=i.message.trim();if(r.length>0)return r}return s==="here"?`Failed to load HERE tiles; verify API key, project permissions, and allowed localhost origin/referrer.${this._tileStyle==="satellite.day"?" If satellite.day fails, try lite.day.":""}`:"Failed to load tile layer"}_reflect(i,s){s===null?this.removeAttribute(i):this.getAttribute(i)!==s&&this.setAttribute(i,s)}_booleanReflect(i,s){s?this.hasAttribute(i)||this.setAttribute(i,""):this.hasAttribute(i)&&this.removeAttribute(i)}_coerceNumber(i,s){if(i==null)return s!=null?s:NaN;const r=Number(i);return Number.isFinite(r)?r:s!=null?s:NaN}}const Xh="leaflet-geokit";customElements.get(Xh)||customElements.define(Xh,sl);const Jh="leaflet-draw-map";if(!customElements.get(Jh)){class a extends sl{}customElements.define(Jh,a)}Nt.DrawEvent=ie,Nt.GROWER_PRESETS=Gp,Nt.GeoJSONValidationError=Br,Nt.GeoKitEvent=_i,Nt.LAYER_STYLE_PRESETS=zn,Nt.LeafletDrawMapElement=sl,Nt.applyGeoJSONPatch=Bf,Nt.boundingBoxGeoJSON=em,Nt.bufferGeoJSON=jp,Nt.centroidGeoJSON=tm,Nt.createBedWidthGuides=im,Nt.createCustomRasterProvider=iu,Nt.createIrrigationZones=rm,Nt.createMapLibreBasemapAdapter=Hf,Nt.createRasterProvider=eu,Nt.createRowSpacingGuides=nm,Nt.diffGeoJSON=Df,Nt.exportGeoJSONData=Of,Nt.findSnap=lu,Nt.formatMeasurements=qh,Nt.getProviderDiagnostics=ga,Nt.importGeoJSONData=Kl,Nt.importGeoJSONText=Ql,Nt.importGeoJSONURL=Rf,Nt.measureGeoJSON=Uh,Nt.mergeGeoJSON=Qp,Nt.normalizeGeoJSON=qo,Nt.simplifyGeoJSON=$p,Nt.splitGeoJSON=Kp,Nt.validateGeoJSON=Ji,Object.defineProperty(Nt,Symbol.toStringTag,{value:"Module"})}));
502
+ `;const i=this._root.querySelector(".map-container");if(!(i instanceof HTMLDivElement))throw new Error("Failed to initialize map container");this._container=i;const s=this.getAttribute("log-level");s&&(this._logLevel=s,this._logger.setLevel(s))}_controlsFromAttributes(){return{polygon:this.hasAttribute("draw-polygon"),polyline:this.hasAttribute("draw-polyline"),rectangle:this.hasAttribute("draw-rectangle"),circle:this.hasAttribute("draw-circle"),cake:this.hasAttribute("draw-layer-cake"),marker:this.hasAttribute("draw-marker"),move:this.hasAttribute("draw-move"),edit:this.hasAttribute("edit-features"),delete:this.hasAttribute("delete-features"),ruler:this.hasAttribute("draw-ruler")}}_mapConfig(){return{latitude:this._latitude,longitude:this._longitude,zoom:this._zoom,minZoom:this._minZoom,maxZoom:this._maxZoom,tileUrl:this._tileUrl,tileAttribution:this._tileAttribution,readOnly:this._readOnly,fitToDataOnLoad:!1,logLevel:this._logLevel,devOverlay:this._devOverlay,polygonAllowIntersection:this._polygonAllowIntersection,preferCanvas:this._preferCanvas,useExternalLeaflet:this._useExternalLeaflet,skipLeafletStyles:this._skipLeafletStyles}}async connectedCallback(){var i,s,r;this._logger.debug("connectedCallback",this._currentConfig()),this._setStatus({state:"initializing",ready:!1,busy:!0,featureCount:0,lastEvent:"connected",lastError:null}),Lc({root:this._root,skipStyles:this._skipLeafletStyles}),this._applyThemeStyles(),this._controller=new sm({container:this._container,map:this._mapConfig(),controls:this._controlsFromAttributes(),readOnly:this._readOnly,logger:this._logger.child("controller"),callbacks:{onToolCapabilitiesChanged:()=>this._emitToolCapabilities(),onReady:h=>{this._setStatus({state:"ready",ready:!0,busy:!1}),this.dispatchEvent(new CustomEvent(ie.Ready,{detail:h})),this._syncStatusFromController({state:"ready",ready:!0,busy:!1,lastEvent:ie.Ready,clearLastError:!0})},onCreated:h=>{this.dispatchEvent(new CustomEvent(ie.Created,{detail:h})),this._setStatus({state:"ready",ready:!0,busy:!1,featureCount:this._status.featureCount+1,lastEvent:ie.Created,lastError:null})},onEdited:h=>{this.dispatchEvent(new CustomEvent(ie.Edited,{detail:h})),this._setStatus({state:"ready",ready:!0,busy:!1,featureCount:h.geoJSON.features.length,lastEvent:ie.Edited,lastError:null})},onDeleted:h=>{this.dispatchEvent(new CustomEvent(ie.Deleted,{detail:h})),this._setStatus({state:"ready",ready:!0,busy:!1,featureCount:h.geoJSON.features.length,lastEvent:ie.Deleted,lastError:null})},onError:h=>{this._emitError(h,{state:h.recoverable?this._status.ready?"ready":this._status.state:"error",lastEvent:ie.Error})},onTileError:h=>{if(this._tileProvider)return;const f=this._describeTileLayerError(h,"tile-url");this._handleTileProviderError("tile_load_failed",f,"tile-url")},onToolTrigger:h=>{this._emitToolTriggerResult(h)},onToolEvent:(h,f)=>{this._emitToolLifecycleEvent(h,f)},onLayerEvent:(h,f)=>{this.dispatchEvent(new CustomEvent(h,{detail:f,bubbles:!0,composed:!0}))},onLayerStyleRequested:h=>!this.dispatchEvent(new CustomEvent("leaflet-geokit:layer-style-request",{detail:h,cancelable:!0,bubbles:!0,composed:!0})),onSaved:h=>{this.dispatchEvent(new CustomEvent(ie.Export,{detail:{geoJSON:h.geoJSON,featureCount:h.featureCount,adapter:"editing"}})),this._setStatus({state:"ready",ready:!0,busy:!1,featureCount:h.featureCount,lastEvent:ie.Export,lastError:null})}},leaflet:(i=this._leafletInstance)!=null?i:void 0,useExternalLeaflet:this._useExternalLeaflet,toolHooks:this._toolHooks,toolEventEmitter:this._toolEventEmitter,markerIconConfig:this._effectiveMarkerIconConfig(),toolButtonConfig:this._effectiveToolButtonConfig(),toolbarGroups:this._effectiveToolbarGroups(),snapping:(s=this._snapping)!=null?s:null,measurementOverlay:(r=this._measurementOverlay)!=null?r:null}),this.addEventListener(_i.ToolCommand,this._externalToolCommandListener),this.addEventListener("leaflet-geokit:trigger-tool",this._externalToolTriggerListener),this.addEventListener("leaflet-geokit:activate-tool",this._externalToolTriggerListener),this.addEventListener("leaflet-geokit:deactivate-tool",this._externalToolDeactivateListener),await this._controller.init(),this._status.state!=="error"&&this._tileProvider&&this._updateTileLayer()}async disconnectedCallback(){this._logger.debug("disconnectedCallback"),this._activeTileProvider="tile-url",this._providerCapabilityError=null,this._controller&&(await this._controller.destroy(),this._controller=null),this._activeTool=null,this.removeEventListener(_i.ToolCommand,this._externalToolCommandListener),this.removeEventListener("leaflet-geokit:trigger-tool",this._externalToolTriggerListener),this.removeEventListener("leaflet-geokit:activate-tool",this._externalToolTriggerListener),this.removeEventListener("leaflet-geokit:deactivate-tool",this._externalToolDeactivateListener),this._setStatus({state:"uninitialized",ready:!1,busy:!1,featureCount:0,lastEvent:"disconnected",lastError:null})}static get observedAttributes(){return["latitude","longitude","zoom","min-zoom","max-zoom","tile-url","tile-attribution","tile-provider","tile-style","api-key","here-api-key","read-only","log-level","dev-overlay","prefer-canvas","use-external-leaflet","skip-leaflet-styles","marker-icon-url","marker-icon-retina-url","marker-shadow-url","marker-icon-size","marker-icon-anchor","marker-popup-anchor","tool-button-config","toolbar-groups","theme-url","draw-polygon","draw-polyline","draw-rectangle","draw-circle","draw-layer-cake","draw-marker","draw-move","draw-ruler","edit-features","delete-features","polygon-allow-intersection"]}attributeChangedCallback(i,s,r){var h;switch(this._logger.debug("attributeChanged",{name:i,value:r}),i){case"latitude":this._latitude=this._coerceNumber(r,0);break;case"longitude":this._longitude=this._coerceNumber(r,0);break;case"zoom":this._zoom=this._coerceNumber(r,2);break;case"min-zoom":this._minZoom=r!=null?this._coerceNumber(r):void 0;break;case"max-zoom":this._maxZoom=r!=null?this._coerceNumber(r):void 0;break;case"tile-url":this._tileUrl=r!=null?r:"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",this._controller&&this._updateTileLayer();break;case"tile-attribution":this._tileAttribution=r!=null?r:void 0,this._controller&&this._updateTileLayer();break;case"tile-provider":this._tileProvider=this._normalizeText(r,{lowercase:!0}),this._controller&&this._updateTileLayer();break;case"tile-style":this._tileStyle=this._normalizeText(r),this._controller&&this._updateTileLayer();break;case"api-key":case"here-api-key":this._syncApiKeyFromAttributes(),this._controller&&this._updateTileLayer();break;case"theme-url":this._themeUrl=r!=null?r:void 0,this.isConnected&&this._applyThemeStyles();break;case"read-only":this._readOnly=r!==null;break;case"log-level":this._logLevel=r!=null?r:this._logLevel,this._logger.setLevel(this._logLevel);break;case"dev-overlay":this._devOverlay=r!==null;break;case"polygon-allow-intersection":this._polygonAllowIntersection=r!==null;break;case"prefer-canvas":this._preferCanvas=r!==null;break;case"use-external-leaflet":this._useExternalLeaflet=r!==null;break;case"skip-leaflet-styles":this._skipLeafletStyles=r!==null;break}if(this._controller){if(i==="latitude"||i==="longitude"||i==="zoom")this._controller.setView(this._latitude,this._longitude,this._zoom);else if(this._isMarkerIconAttribute(i))this._syncMarkerIconConfig();else if(i==="tool-button-config")this._syncToolButtonConfig();else if(i==="toolbar-groups")this._syncToolbarGroups();else if(i==="min-zoom"||i==="max-zoom"||i==="read-only"||i==="dev-overlay"||i==="log-level"||i==="prefer-canvas"||i==="use-external-leaflet"||i==="skip-leaflet-styles"||i.startsWith("draw-")||i==="edit-features"||i==="delete-features"){const f=this._controller;(h=f.configure)==null||h.call(f,this._mapConfig(),this._controlsFromAttributes()),this._configurationUpdate=this._configurationUpdate.then(async()=>{var d;this._controller!==f||!this.isConnected||((d=f.configure)==null||d.call(f,this._mapConfig(),this._controlsFromAttributes()),await f.init(),this._tileProvider&&this._updateTileLayer())})}}}_updateTileLayer(){var s,r,h,f,d,m;if(!this._controller)return;const i=this._controller;if(typeof i.setTileLayer!="function"){this._logger.warn("setTileLayer is not available on MapController yet");return}this._providerCapabilityError=null;try{if(this._tileProvider){const _=this._tileProvider,x={provider:_,style:this._tileStyle,apiKey:this._apiKey,attribution:this._tileAttribution},b=Zf(x);if(!b.valid){const S=(s=b.error)!=null&&s.toLowerCase().includes("api key")?"missing_api_key":"tile_load_failed";this._handleTileProviderError(S,(r=b.error)!=null?r:"Invalid tile provider configuration",_);return}const E=da(x),C=this._activeTileProvider;i.setTileLayer(E,{onTileError:S=>{if(this._tileProvider!==_)return;const O=this._describeTileLayerError(S,_),N=_==="here"?this._resolveHereTileLayerErrorCode(O):"tile_load_failed";this._handleTileProviderError(N,O,_)}}),this._activeTileProvider=_,this._emitTileProviderChanged(_,this._tileStyle,C);return}i.setTileLayer({urlTemplate:this._tileUrl,attribution:(h=this._tileAttribution)!=null?h:"",maxZoom:this._maxZoom,subdomains:["a","b","c"]},{onTileError:_=>{const x=this._describeTileLayerError(_,"tile-url");this._handleTileProviderError("tile_load_failed",x,"tile-url")}}),this._activeTileProvider="tile-url"}catch(_){const x=this._resolveTileProviderErrorCode(_);this._logger.error("Failed to update tile layer",{error:_,code:x}),this._handleTileProviderError(x,_ instanceof Error?_.message:"Unknown tile layer error",(f=this._tileProvider)!=null?f:"unknown")}finally{(m=(d=this._controller)==null?void 0:d.setToolProvider)==null||m.call(d,this._toolProviderCapability()),this._emitToolCapabilities()}}_handleTileProviderError(i,s,r){var d,m;this._logger.error(`Tile provider error (${i}): ${s}`);const h=Date.now();this._providerCapabilityError={code:i==="missing_api_key"?"missing_api_key":i==="unknown_provider"?"missing_provider":"runtime_error",message:i==="missing_api_key"?"Requested provider requires an API key":i==="unknown_provider"?"Requested provider is unavailable":"Requested provider failed; using fallback tiles"},this.dispatchEvent(new CustomEvent("tile-provider-error",{bubbles:!0,detail:{code:i,message:s,provider:r,timestamp:h}})),this._emitDiagnostic({code:i,message:s,recoverable:!0,severity:"warn",timestamp:h},{state:this._status.ready?"ready":this._status.state,lastEvent:"tile-provider-error"});const f=this._controller;typeof f.setTileLayer=="function"&&(f.setTileLayer({urlTemplate:"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",attribution:'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',maxZoom:19,subdomains:["a","b","c"]}),this._activeTileProvider="osm"),(m=(d=this._controller)==null?void 0:d.setToolProvider)==null||m.call(d,this._toolProviderCapability()),this._emitToolCapabilities()}_emitTileProviderChanged(i,s,r){this.dispatchEvent(new CustomEvent("tile-provider-changed",{bubbles:!0,detail:{provider:i,style:s,previousProvider:r,timestamp:Date.now()}}))}_toolProviderCapability(){var r,h;const i=this._activeTileProvider==="adapter"?"adapter":(r=this._tileProvider)!=null?r:"tile-url";let s=this._providerCapabilityError;return i!=="adapter"&&i!=="tile-url"&&i!=="osm"&&i!=="here"?s={code:"missing_provider",message:"Requested provider is unavailable"}:i==="here"&&!((h=this._apiKey)!=null&&h.trim())&&(s={code:"missing_api_key",message:"Requested provider requires an API key"}),{requested:i,active:this._activeTileProvider,state:s?"unavailable":"enabled",reason:s?{...s}:null}}setBasemapAdapter(i){var r,h;if(!this._status.ready||!this._controller)throw new Error("Map is not ready");if(!i){this._updateTileLayer();return}this._controller.setBasemapAdapter(i);const s=this._activeTileProvider;this._activeTileProvider="adapter",this._providerCapabilityError=null,this._emitTileProviderChanged("adapter",void 0,s),(h=(r=this._controller).setToolProvider)==null||h.call(r,this._toolProviderCapability()),this._emitToolCapabilities()}getProviderDiagnostics(){var r,h,f;const i=(f=(h=(r=this._controller)==null?void 0:r.getProviderDiagnostics)==null?void 0:h.call(r))!=null?f:null;if(!i||this._activeTileProvider==="adapter")return i;const s=this._activeTileProvider==="tile-url"&&this._tileUrl===da({provider:"osm"}).urlTemplate?"osm":this._activeTileProvider;if(s==="osm"||s==="here"){const d=eu({provider:s});return{...i,...d.capabilities}}return i}getToolCapabilities(){var s,r,h;return{...(h=(r=(s=this._controller)==null?void 0:s.getToolCapabilities)==null?void 0:r.call(s))!=null?h:nu({ready:!1,readOnly:this._readOnly,controls:this._controlsFromAttributes(),available:{},layerCount:0,selectedFeatureIds:[],activeTool:null,config:this._effectiveToolButtonConfig(),groups:this._effectiveToolbarGroups(),provider:this._toolProviderCapability()}),provider:this._toolProviderCapability()}}setToolSelection(i){var s;(s=this._controller)==null||s.setToolSelection(i)}_emitToolCapabilities(){const i=this.getToolCapabilities(),s=JSON.stringify(i);s!==this._lastCapabilities&&(this._lastCapabilities=s,this.dispatchEvent(new CustomEvent(_i.ToolCapabilitiesChanged,{detail:i,bubbles:!0,composed:!0})))}_isMarkerIconAttribute(i){return i==="marker-icon-url"||i==="marker-icon-retina-url"||i==="marker-shadow-url"||i==="marker-icon-size"||i==="marker-icon-anchor"||i==="marker-popup-anchor"}_effectiveMarkerIconConfig(){const i=(r,h)=>{this._emitError({code:"invalid_marker_icon_config",message:r,recoverable:!0,cause:h},{state:this._status.ready?"ready":this._status.state})};if(this._markerIconConfig===null)return null;if(this._markerIconConfig!==void 0)return am(this._markerIconConfig,{reportError:i});const s=this.getAttribute("marker-icon-url");return s==null?null:lm({iconUrl:s,iconRetinaUrl:this.getAttribute("marker-icon-retina-url"),shadowUrl:this.getAttribute("marker-shadow-url"),iconSize:this.getAttribute("marker-icon-size"),iconAnchor:this.getAttribute("marker-icon-anchor"),popupAnchor:this.getAttribute("marker-popup-anchor")},{reportError:i})}_syncMarkerIconConfig(){const i=this._controller;typeof(i==null?void 0:i.setMarkerIconConfig)=="function"&&i.setMarkerIconConfig(this._effectiveMarkerIconConfig())}_effectiveToolButtonConfig(){if(this._toolButtonConfig!==void 0)return this._toolButtonConfig;const i=this.getAttribute("tool-button-config");if(i==null||i.trim()==="")return null;try{const s=JSON.parse(i);if(!s||typeof s!="object"||Array.isArray(s))throw new Error("tool-button-config must be a JSON object");return s}catch(s){return this._emitError({code:"invalid_tool_button_config",message:"Failed to parse tool-button-config",recoverable:!0,cause:s},{state:this._status.ready?"ready":this._status.state}),null}}_syncToolButtonConfig(){const i=this._controller;typeof(i==null?void 0:i.setToolButtonConfig)=="function"&&i.setToolButtonConfig(this._effectiveToolButtonConfig())}_effectiveToolbarGroups(){if(this._toolbarGroups!==void 0)return this._toolbarGroups;const i=this.getAttribute("toolbar-groups");if(i==null||i.trim()==="")return null;try{const s=JSON.parse(i);if(!Array.isArray(s))throw new Error("toolbar-groups must be a JSON array");return s}catch(s){return this._emitError({code:"invalid_toolbar_groups",message:"Failed to parse toolbar-groups",recoverable:!0,cause:s},{state:this._status.ready?"ready":this._status.state}),null}}_syncToolbarGroups(){const i=this._controller;typeof(i==null?void 0:i.setToolbarGroups)=="function"&&i.setToolbarGroups(this._effectiveToolbarGroups())}get latitude(){return this._latitude}set latitude(i){this._latitude=Number(i),this._reflect("latitude",String(this._latitude))}get longitude(){return this._longitude}set longitude(i){this._longitude=Number(i),this._reflect("longitude",String(this._longitude))}get zoom(){return this._zoom}set zoom(i){this._zoom=Number(i),this._reflect("zoom",String(this._zoom))}get minZoom(){return this._minZoom}set minZoom(i){this._minZoom=i,this._reflect("min-zoom",i!=null?String(i):null)}get maxZoom(){return this._maxZoom}set maxZoom(i){this._maxZoom=i,this._reflect("max-zoom",i!=null?String(i):null)}get tileUrl(){return this._tileUrl}set tileUrl(i){this._tileUrl=i,this._reflect("tile-url",i),this._controller&&this._updateTileLayer()}get tileProvider(){return this._tileProvider}set tileProvider(i){var s;this._tileProvider=this._normalizeText(i!=null?i:null,{lowercase:!0}),this._reflect("tile-provider",(s=this._tileProvider)!=null?s:null),this._controller&&this._updateTileLayer()}get tileStyle(){return this._tileStyle}set tileStyle(i){var s;this._tileStyle=this._normalizeText(i!=null?i:null),this._reflect("tile-style",(s=this._tileStyle)!=null?s:null),this._controller&&this._updateTileLayer()}get apiKey(){return this._apiKey}set apiKey(i){var s;this._apiKey=this._normalizeText(i!=null?i:null),this._reflect("api-key",(s=this._apiKey)!=null?s:null),this.hasAttribute("here-api-key")&&this.removeAttribute("here-api-key"),this._controller&&this._updateTileLayer()}get status(){return this._cloneStatus(this._status)}get tileAttribution(){return this._tileAttribution}set tileAttribution(i){this._tileAttribution=i,this._reflect("tile-attribution",i!=null?i:null),this._controller&&this._updateTileLayer()}get readOnly(){return this._readOnly}set readOnly(i){this._readOnly=!!i,this._booleanReflect("read-only",this._readOnly)}get logLevel(){return this._logLevel}set logLevel(i){this._logLevel=i,this._logger.setLevel(i),this._reflect("log-level",i)}get devOverlay(){return this._devOverlay}set devOverlay(i){this._devOverlay=!!i,this._booleanReflect("dev-overlay",this._devOverlay)}get preferCanvas(){return this._preferCanvas}set preferCanvas(i){this._preferCanvas=!!i,this._booleanReflect("prefer-canvas",this._preferCanvas)}get useExternalLeaflet(){return this._useExternalLeaflet}set useExternalLeaflet(i){this._useExternalLeaflet=!!i,this._booleanReflect("use-external-leaflet",this._useExternalLeaflet)}get skipLeafletStyles(){return this._skipLeafletStyles}set skipLeafletStyles(i){this._skipLeafletStyles=!!i,this._booleanReflect("skip-leaflet-styles",this._skipLeafletStyles)}get markerIconConfig(){return this._markerIconConfig}set markerIconConfig(i){this._markerIconConfig=i,this._syncMarkerIconConfig()}get toolButtonConfig(){return this._toolButtonConfig}set toolButtonConfig(i){this._toolButtonConfig=i,this._syncToolButtonConfig()}get toolbarGroups(){return this._toolbarGroups}set toolbarGroups(i){this._toolbarGroups=i,this._syncToolbarGroups()}get snapping(){return this._snapping}set snapping(i){var r;const s=this._snapping;this._snapping=i;try{(r=this._controller)==null||r.setSnappingOptions(i)}catch(h){throw this._snapping=s,h}}get measurementOverlay(){return this._measurementOverlay}set measurementOverlay(i){var r;const s=this._measurementOverlay;this._measurementOverlay=i;try{(r=this._controller)==null||r.setMeasurementOverlayOptions(i)}catch(h){throw this._measurementOverlay=s,h}}get leafletInstance(){return this._leafletInstance}set leafletInstance(i){this._leafletInstance=i}get toolHooks(){return this._toolHooks}set toolHooks(i){this._toolHooks=i;const s=this._controller;typeof(s==null?void 0:s.setToolObservers)=="function"&&s.setToolObservers({toolHooks:this._toolHooks,toolEventEmitter:this._toolEventEmitter})}get toolEventEmitter(){return this._toolEventEmitter}set toolEventEmitter(i){this._toolEventEmitter=i;const s=this._controller;typeof(s==null?void 0:s.setToolObservers)=="function"&&s.setToolObservers({toolHooks:this._toolHooks,toolEventEmitter:this._toolEventEmitter})}get themeCss(){return this._themeCss}set themeCss(i){this._themeCss=typeof i=="string"?i:"",this.isConnected&&this._applyThemeStyles()}async getGeoJSON(){return this._logger.debug("getGeoJSON"),this._controller?this._controller.getGeoJSON():{type:"FeatureCollection",features:[]}}async importGeoJSON(i,s={}){var f,d,m,_;const r=(f=s.behavior)!=null?f:"replace";if(this._logger.debug("importGeoJSON",{behavior:r,fitToData:(d=s.fitToData)!=null?d:!1,features:(_=(m=i==null?void 0:i.features)==null?void 0:m.length)!=null?_:0}),!this._controller)return[];const h=this.status;return this._setImportLoadingStatus(h),this._performImport(i,s,h,r==="add"?"Failed to add GeoJSON features to the map":"Failed to load GeoJSON into the map")}async loadGeoJSON(i){var s,r;this._logger.debug("loadGeoJSON",{features:(r=(s=i==null?void 0:i.features)==null?void 0:s.length)!=null?r:0}),await this.importGeoJSON(i,{behavior:"replace"})}async clearLayers(){this._logger.debug("clearLayers"),this._controller&&(await this._controller.clearLayers(),this._setStatus({state:"ready",ready:!0,busy:!1,featureCount:0,lastEvent:"clearLayers",lastError:null}))}async addFeatures(i){var s,r;return this._logger.debug("addFeatures",{count:(r=(s=i==null?void 0:i.features)==null?void 0:s.length)!=null?r:0}),this.importGeoJSON(i,{behavior:"add"})}async updateFeature(i,s){this._logger.debug("updateFeature",{id:i}),this._controller&&await this._controller.updateFeature(i,s)}async removeFeature(i){this._logger.debug("removeFeature",{id:i}),this._controller&&(await this._controller.removeFeature(i),await this._syncStatusFromController({state:"ready",ready:!0,busy:!1,lastEvent:"removeFeature",clearLastError:!0}))}async fitBoundsToData(i){this._logger.debug("fitBoundsToData",{padding:i}),this._controller&&await this._controller.fitBoundsToData(typeof i=="number"?i:.05)}async fitBounds(i,s){this._logger.debug("fitBounds",{bounds:i,padding:s}),this._controller&&await this._controller.fitBounds(i,typeof s=="number"?s:.05)}async setView(i,s,r){this._logger.debug("setView",{lat:i,lng:s,zoom:r}),this.latitude=i,this.longitude=s,typeof r=="number"&&(this.zoom=r),this._controller&&await this._controller.setView(i,s,r)}async exportGeoJSON(i={}){var f;const s=(f=i.adapter)!=null?f:"editing";if(this._logger.debug("exportGeoJSON",{adapter:s}),!this._controller)return{type:"FeatureCollection",features:[]};const r=await this._exportWithController(i),h={geoJSON:r,featureCount:r.features.length,adapter:s};return this.dispatchEvent(new CustomEvent(ie.Export,{detail:h})),r}async mergePolygons(i){if(this._logger.debug("mergePolygons"),!this._controller)return null;const r=(await this._controller.getGeoJSON()).features.length,h=await this._controller.mergeVisiblePolygons(i);if(h){const f=await this._controller.getGeoJSON(),d={id:h,mergedFeatureCount:r-f.features.length+1,geoJSON:f};this.dispatchEvent(new CustomEvent("leaflet-draw:merged",{detail:d})),this._setStatus({state:"ready",ready:!0,busy:!1,featureCount:f.features.length,lastEvent:"leaflet-draw:merged",lastError:null})}return h}async setMeasurementUnits(i){this._logger.debug("setMeasurementUnits",{system:i}),this._controller&&this._controller.setRulerUnits(i)}getSnappingOptions(){var i,s;return(s=(i=this._controller)==null?void 0:i.getSnappingOptions())!=null?s:this._snapping?{...this._snapping}:null}getMeasurementOverlayOptions(){var i,s;return(s=(i=this._controller)==null?void 0:i.getMeasurementOverlayOptions())!=null?s:this._measurementOverlay?{...this._measurementOverlay}:null}_nextToolCommandId(){return this._toolCommandSequence+=1,`tool-${Date.now().toString(36)}-element-${this._toolCommandSequence.toString(36)}`}_emitToolTriggerRequested(i,s){this.dispatchEvent(new CustomEvent("leaflet-geokit:tool-trigger-requested",{bubbles:!0,composed:!0,detail:{tool:i,source:s.source,groupId:s.groupId,commandId:s.commandId,handled:!1,timestamp:Date.now()}}))}_baseToolEventDetail(i,s,r){return{tool:i,action:s,source:r.source,groupId:r.groupId,commandId:r.commandId,previousTool:null,activeTool:null,featureIds:[],timestamp:Date.now()}}_emitStandaloneToolFailure(i,s,r,h,f=!0){const d=this._baseToolEventDetail(i,s,r);f&&this._emitToolLifecycleEvent(_i.ToolCommand,d),this._emitToolLifecycleEvent(_i.ToolFailed,{...d,reason:h,timestamp:Date.now()}),this._emitToolTriggerResult({tool:i,source:r.source,groupId:r.groupId,commandId:r.commandId,handled:!1,timestamp:Date.now(),error:h})}async activateTool(i,s={}){var _,x,b;const r=(_=s.source)!=null?_:"api",h=((x=s.commandId)==null?void 0:x.trim())||this._nextToolCommandId(),f={source:r,groupId:s.groupId,commandId:h};if(this._emitToolTriggerRequested(i,f),!this._controller)return this._emitStandaloneToolFailure(i,i==="select"?"deactivate":"activate",f,"Map controller is not initialized"),!1;const d=this._controller,m=typeof d.activateTool=="function"?d.activateTool.bind(d):(b=d.triggerTool)==null?void 0:b.bind(d);return m?m(i,f):(this._emitStandaloneToolFailure(i,i==="select"?"deactivate":"activate",f,"Map controller cannot activate tools"),!1)}async triggerTool(i,s={}){return this.activateTool(i,s)}async deactivateTool(i={}){var m,_,x;const s=(m=i.source)!=null?m:"api",r=((_=i.commandId)==null?void 0:_.trim())||this._nextToolCommandId(),h={source:s,groupId:i.groupId,commandId:r};if(this._emitToolTriggerRequested("select",h),!this._controller)return this._emitStandaloneToolFailure("select","deactivate",h,"Map controller is not initialized"),!1;const f=this._controller;if(typeof f.deactivateTool=="function")return f.deactivateTool(h);const d=typeof f.activateTool=="function"?f.activateTool.bind(f):(x=f.triggerTool)==null?void 0:x.bind(f);return d?d("select",h):(this._emitStandaloneToolFailure("select","deactivate",h,"Map controller cannot deactivate tools"),!1)}async loadGeoJSONFromUrl(i,s={}){var m,_,x;const r=(m=s.behavior)!=null?m:"replace";if(this._logger.debug("loadGeoJSONFromUrl",{url:i,behavior:r,fitToData:(_=s.fitToData)!=null?_:!0}),!this._controller)return;const h=this.status;this._setImportLoadingStatus(h);let f;try{f=await fetch(i,{headers:{Accept:"application/json"}})}catch(b){const E=new Error(`Failed to fetch GeoJSON from ${i}`);throw this._emitError({code:"data_fetch_failed",message:E.message,recoverable:!0,cause:b},{state:h.ready?"ready":h.state,featureCount:h.featureCount}),E}if(!f.ok){const b=new Error(`Failed to fetch GeoJSON from ${i}: ${f.status} ${f.statusText}`);throw this._emitError({code:"data_fetch_failed",message:b.message,recoverable:!0,cause:b},{state:h.ready?"ready":h.state,featureCount:h.featureCount}),b}let d;try{d=await f.json()}catch(b){const E=new Error(`Failed to parse GeoJSON from ${i}`);throw this._emitError({code:"data_parse_failed",message:E.message,recoverable:!0,cause:b},{state:h.ready?"ready":h.state,featureCount:h.featureCount}),E}await this._performImport(d,{behavior:r,fitToData:(x=s.fitToData)!=null?x:!0},h,r==="add"?`Failed to add GeoJSON from ${i}`:`Failed to load GeoJSON from ${i}`)}async loadGeoJSONFromText(i,s={}){var d,m,_,x;const r=(d=s.behavior)!=null?d:"replace";if(this._logger.debug("loadGeoJSONFromText",{behavior:r,fitToData:(m=s.fitToData)!=null?m:!0,length:(_=i==null?void 0:i.length)!=null?_:0}),!this._controller)return;const h=this.status;this._setImportLoadingStatus(h);let f;try{f=JSON.parse(i)}catch(b){const E=new Error("Failed to parse GeoJSON text");throw this._emitError({code:"data_parse_failed",message:E.message,recoverable:!0,cause:b},{state:h.ready?"ready":h.state,featureCount:h.featureCount}),E}await this._performImport(f,{behavior:r,fitToData:(x=s.fitToData)!=null?x:!0},h,r==="add"?"Failed to add parsed GeoJSON into the map":"Failed to load parsed GeoJSON into the map")}_setImportLoadingStatus(i){this._setStatus({state:"loading",ready:i.ready,busy:!0,featureCount:i.featureCount,lastEvent:ie.Ingest,lastError:null})}async _performImport(i,s,r,h){var _,x;const f=(_=s.behavior)!=null?_:"replace",d={fc:i,mode:f==="add"?"add":"load"};this.dispatchEvent(new CustomEvent(ie.Ingest,{detail:d}));const m=d.fc&&d.fc.type==="FeatureCollection"?d.fc:i;try{const b=await this._importWithController(m,{...s,behavior:f,fitToData:(x=s.fitToData)!=null?x:!1});return await this._syncStatusFromController({state:"ready",ready:!0,busy:!1,lastEvent:ie.Ingest,clearLastError:!0}),b}catch(b){throw this._emitError({code:f==="add"?"data_add_failed":"data_load_failed",message:h,recoverable:!0,cause:b},{state:r.ready?"ready":r.state,featureCount:r.featureCount}),b}}getLayers(){var i,s;return(s=(i=this._controller)==null?void 0:i.getLayers())!=null?s:[]}async setLayerVisibility(i,s){var r;(r=this._controller)==null||r.setLayerVisibility(i,s)}async setLayerStyle(i,s){var r;(r=this._controller)==null||r.setLayerStyle(i,s)}async reorderLayers(i){var s;(s=this._controller)==null||s.reorderLayers(i)}async focusLayer(i){var s;await((s=this._controller)==null?void 0:s.focusLayer(i))}async removeLayer(i){var s;await((s=this._controller)==null?void 0:s.removeLayer(i))}getLayerCakeSession(){var i,s;return(s=(i=this._controller)==null?void 0:i.getLayerCakeSession())!=null?s:null}async updateLayerCakeSession(i){var s;(s=this._controller)==null||s.updateLayerCakeSession(i)}async saveLayerCakeSession(){var i;(i=this._controller)==null||i.saveLayerCakeSession()}async cancelLayerCakeSession(){var i;(i=this._controller)==null||i.cancelLayerCakeSession()}async _importWithController(i,s){var d,m;if(!this._controller)return[];const r=(d=s.behavior)!=null?d:"replace",h=(m=s.fitToData)!=null?m:!1,f=this._controller;return typeof f.importGeoJSON=="function"?f.importGeoJSON(i,{...s,behavior:r,fitToData:h}):r==="add"?f.addFeatures(i):(await f.loadGeoJSON(i,h),[])}async _exportWithController(i){if(!this._controller)return{type:"FeatureCollection",features:[]};const s=this._controller;return typeof s.exportGeoJSON=="function"?s.exportGeoJSON(i):s.getGeoJSON()}_currentConfig(){return{latitude:this._latitude,longitude:this._longitude,zoom:this._zoom,minZoom:this._minZoom,maxZoom:this._maxZoom,tileUrl:this._tileUrl,tileAttribution:this._tileAttribution,readOnly:this._readOnly,fitToDataOnLoad:!1,logLevel:this._logLevel,devOverlay:this._devOverlay,polygonAllowIntersection:this._polygonAllowIntersection,preferCanvas:this._preferCanvas,useExternalLeaflet:this._useExternalLeaflet,skipLeafletStyles:this._skipLeafletStyles}}_applyThemeStyles(){var r;const i=(r=this._themeUrl)==null?void 0:r.trim();if(i){if(!this._themeLinkEl){const h=document.createElement("link");h.setAttribute("rel","stylesheet"),h.setAttribute("data-geokit-theme-url","true"),this._root.appendChild(h),this._themeLinkEl=h}this._themeLinkEl.getAttribute("href")!==i&&this._themeLinkEl.setAttribute("href",i)}else this._themeLinkEl&&(this._themeLinkEl.remove(),this._themeLinkEl=null);const s=this._themeCss;if(s.trim().length>0){if(!this._themeStyleEl){const h=document.createElement("style");h.setAttribute("data-geokit-theme-css","true"),this._root.appendChild(h),this._themeStyleEl=h}this._themeStyleEl.textContent!==s&&(this._themeStyleEl.textContent=s)}else this._themeStyleEl&&(this._themeStyleEl.remove(),this._themeStyleEl=null)}_emitToolLifecycleEvent(i,s){i===_i.ToolStateChanged&&(this._activeTool=s.activeTool);const r=new CustomEvent(i,{bubbles:!0,composed:!0,detail:s});this._internalToolEvents.add(r),this.dispatchEvent(r)}_emitToolTriggerResult(i){this.dispatchEvent(new CustomEvent(i.handled?"leaflet-geokit:tool-triggered":"leaflet-geokit:tool-trigger-failed",{bubbles:!0,composed:!0,detail:i}))}_syncStatusFromController(i){const s=this._controller;return!s||typeof s.getGeoJSON!="function"?(this._setStatus({state:i.state,ready:i.ready,busy:i.busy,featureCount:this._status.featureCount,lastEvent:i.lastEvent,lastError:i.clearLastError?null:void 0}),Promise.resolve()):s.getGeoJSON().then(r=>{this._setStatus({state:i.state,ready:i.ready,busy:i.busy,featureCount:r.features.length,lastEvent:i.lastEvent,lastError:i.clearLastError?null:void 0})}).catch(()=>{this._setStatus({state:i.state,ready:i.ready,busy:i.busy,lastEvent:i.lastEvent,lastError:i.clearLastError?null:void 0})})}_emitError(i,s){var h;const r={...i,timestamp:Date.now()};return this.dispatchEvent(new CustomEvent(ie.Error,{detail:r})),this._emitDiagnostic({code:r.code,message:r.message,recoverable:r.recoverable,severity:r.recoverable?"warn":"error",cause:r.cause,timestamp:r.timestamp},{state:s.state,featureCount:s.featureCount,lastEvent:(h=s.lastEvent)!=null?h:ie.Error}),r}_emitDiagnostic(i,s){var h,f;const r={...i,state:s.state};return this.dispatchEvent(new CustomEvent(_i.Diagnostic,{detail:r})),this._setStatus({state:s.state,ready:s.state==="ready",busy:s.state==="initializing"||s.state==="loading",featureCount:(h=s.featureCount)!=null?h:this._status.featureCount,lastEvent:(f=s.lastEvent)!=null?f:_i.Diagnostic,lastError:{code:r.code,message:r.message,recoverable:r.recoverable,timestamp:r.timestamp}}),r}_setStatus(i){const s={...this._status,...i,lastError:i.lastError===null?void 0:i.lastError!==void 0?{...i.lastError}:this._status.lastError?{...this._status.lastError}:void 0,timestamp:Date.now()};this._status=s,this.dispatchEvent(new CustomEvent(_i.Status,{detail:this._cloneStatus(s)}))}_cloneStatus(i){return{...i,lastError:i.lastError?{...i.lastError}:void 0}}_syncApiKeyFromAttributes(){const i=this._normalizeText(this.getAttribute("api-key")),s=this._normalizeText(this.getAttribute("here-api-key"));this._apiKey=i!=null?i:s}_normalizeText(i,s){if(typeof i!="string")return;const r=i.trim();if(r)return s!=null&&s.lowercase?r.toLowerCase():r}_resolveTileProviderErrorCode(i){return i instanceof Error&&i.message.toLowerCase().includes("unknown tile provider")?"unknown_provider":"tile_load_failed"}_resolveHereTileLayerErrorCode(i){const s=i.toLowerCase();return s.includes("permission")||s.includes("forbidden")||s.includes("403")||s.includes("unauthorized")||s.includes("not authorized")||s.includes("not authorised")||s.includes("access denied")?"permission_denied":"invalid_api_key"}_describeTileLayerError(i,s){if(i&&typeof i=="object"&&"error"in i&&i.error instanceof Error)return i.error.message;if(i instanceof Error&&i.message)return i.message;if(i&&typeof i=="object"&&"message"in i&&typeof i.message=="string"){const r=i.message.trim();if(r.length>0)return r}return s==="here"?`Failed to load HERE tiles; verify API key, project permissions, and allowed localhost origin/referrer.${this._tileStyle==="satellite.day"?" If satellite.day fails, try lite.day.":""}`:"Failed to load tile layer"}_reflect(i,s){s===null?this.removeAttribute(i):this.getAttribute(i)!==s&&this.setAttribute(i,s)}_booleanReflect(i,s){s?this.hasAttribute(i)||this.setAttribute(i,""):this.hasAttribute(i)&&this.removeAttribute(i)}_coerceNumber(i,s){if(i==null)return s!=null?s:NaN;const r=Number(i);return Number.isFinite(r)?r:s!=null?s:NaN}}const Xh="leaflet-geokit";customElements.get(Xh)||customElements.define(Xh,sl);const Jh="leaflet-draw-map";if(!customElements.get(Jh)){class a extends sl{}customElements.define(Jh,a)}Nt.DrawEvent=ie,Nt.GROWER_PRESETS=Gp,Nt.GeoJSONValidationError=Br,Nt.GeoKitEvent=_i,Nt.LAYER_STYLE_PRESETS=zn,Nt.LeafletDrawMapElement=sl,Nt.applyGeoJSONPatch=Bf,Nt.boundingBoxGeoJSON=em,Nt.bufferGeoJSON=jp,Nt.centroidGeoJSON=tm,Nt.createBedWidthGuides=im,Nt.createCustomRasterProvider=iu,Nt.createIrrigationZones=rm,Nt.createMapLibreBasemapAdapter=Hf,Nt.createRasterProvider=eu,Nt.createRowSpacingGuides=nm,Nt.diffGeoJSON=Df,Nt.exportGeoJSONData=Of,Nt.findSnap=lu,Nt.formatMeasurements=qh,Nt.getProviderDiagnostics=ga,Nt.importGeoJSONData=Kl,Nt.importGeoJSONText=Ql,Nt.importGeoJSONURL=Rf,Nt.measureGeoJSON=Uh,Nt.mergeGeoJSON=Qp,Nt.normalizeGeoJSON=qo,Nt.simplifyGeoJSON=$p,Nt.splitGeoJSON=Kp,Nt.validateGeoJSON=Ji,Object.defineProperty(Nt,Symbol.toStringTag,{value:"Module"})}));
503
503
  //# sourceMappingURL=leaflet-geokit.umd.js.map